text
stringlengths
8
1.32M
// // SearchView.swift // FoodTrucksEx // // Created by Hai Nguyen on 8/31/19. // Copyright © 2019 Hai Nguyen. All rights reserved. // import SwiftUI struct SearchView: View { @State private var searchText: String = "" var body: some View { HStack { TextField("Search", text: $searchText) } } } struct SearchView_Previews: PreviewProvider { static var previews: some View { SearchView() } }
// // Loading.swift // UniversalComponent // // Created by Igor Shelopaev on 07.05.2021. // import SwiftUI /// Mask modifier fileprivate struct Mask: ViewModifier, Stylable { /// true - is loading, false - loaded let loading : Bool /// Text while loading let text : String /// Visibility var boder : Bool // MARK: - API Methods /// The type of view representing the body of this view func body(content: Content) -> some View { content.overlay( Rectangle() .foregroundColor(componentRGB) .overlay( Text(text).foregroundColor(.white).font(.system(.body)), alignment: .center) .opacity(loading ? 1.0 : 0.0 ), alignment: .center) .border(width: boder ? 1.0 : 0.0 , edges: [.leading, .bottom], color: selectedRGB) .border(width: boder ? 1.0 : 0.0 , edges: [.top, .trailing], color: borderRGB) .background(componentRGB) } } // MARK: -- Extension -- extension View { /// Mask or unmask View. Depends on Store loading process /// - Parameters: /// - loading: Boolean flag true - is loading, false - loaded /// - text: Text displayed while loading. Default value "Loading..." /// - Returns: Mask view public func mask(_ loading: Bool, text: String = "Loading...", border : Bool = true) -> some View { self.modifier(Mask(loading: loading, text: text, boder: border)) } }
// // NavigationRouter.swift // EXPNSR-iOS // // Created by Thathsara Senarathne on 11/27/20. // import Foundation import UIKit import RxSwift import Action public class NavigationRouter: NSObject { weak var navigationController: UINavigationController! private var popActionsToPerform = [UIViewController:CocoaAction]() var isHideBackButtonText: Bool = false private var isHidebackButtonTemp = false private var isChangedBackButtonTitleVisibilityTemp = false public init(_ navigationController: UINavigationController ){ self.navigationController = navigationController super.init() navigationController.rx .didShow .map{ result -> UIViewController in guard let dismissedVC = navigationController.transitionCoordinator?.viewController(forKey: .from) else{ return result.viewController } return dismissedVC }.filter{ return !navigationController.viewControllers.contains($0) } .subscribe(onNext:{[weak self] in self?.performDismissAction(for: $0) }).disposed(by: rx.disposeBag) } } //MARK:- Router extension NavigationRouter: Router { public func route(_ viewController: UIViewController, animated: Bool,_ dismissAction: CocoaAction?){ if let _action = dismissAction{ popActionsToPerform[viewController] = _action } setNavigationBarBackButtonTextAppearance(in: viewController) if isChangedBackButtonTitleVisibilityTemp { isHideBackButtonText = isHidebackButtonTemp isChangedBackButtonTitleVisibilityTemp = false } navigationController.pushViewController(viewController, animated: animated) } private func performDismissAction(for viewController:UIViewController){ guard let action = popActionsToPerform[viewController] else { return } action.execute() popActionsToPerform[viewController] = nil } public func dismiss(animated: Bool) { self.navigationController.popViewController(animated: animated) } public func dismissToRoot(isAnimated animated: Bool) { navigationController.popToRootViewController(animated: true) emptyDismissActions() } public func emptyDismissActions() { popActionsToPerform.enumerated().forEach { [weak self] in self?.performDismissAction(for: $0.element.key) } } } //Navigation bar local configuration for router extension NavigationRouter { fileprivate func setNavigationBarBackButtonTextAppearance(in viewController: UIViewController) { if isHideBackButtonText { viewController.navigationItem.backBarButtonItem = UIBarButtonItem.init(title: "", style: .plain, target: nil, action: nil) } else { viewController.navigationItem.backBarButtonItem = nil } } public func setTempVisibleBackTitle(set visible: Bool) { isHidebackButtonTemp = isHideBackButtonText isHideBackButtonText = !visible isChangedBackButtonTitleVisibilityTemp = true } } ////MARK: - Controll Navigation custom animation //extension NavigationRouter: UINavigationControllerDelegate { // public func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { // // switch toVC { // case is CreateAdTypesViewController: // if operation == .push { // return NavigationOverCurrentContextTransition(presenting: true) // } else { // return NavigationOverCurrentContextTransition(presenting: false) // } // // default: // return nil // } // // } //}
// // Maintenance.swift // GloveBox // // Created by Nick George on 11/9/19. // Copyright © 2019 SimpleDev Studios. All rights reserved. // import Foundation
// // MVVMViewController.swift // Zadatak // // Created by dejan kraguljac on 09/03/2020. // import UIKit import RxSwift import RxCocoa class MVVMViewController<T: ViewModelType>: UIViewController { var viewModel: T var disposeBag = DisposeBag() var coordinatorType: SceneCoordinatorType var transition: Binder<Scene> { return Binder(self) { controller, scene in controller.coordinatorType.transition(to: scene, transitionType: .push(true)) } } required init(coordinatorType: SceneCoordinatorType, viewModel: T) { self.viewModel = viewModel self.coordinatorType = coordinatorType super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() bindOuput(viewModel.transform(input: bindInput())) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let actualController = actualViewController() if actualController != coordinatorType.currentViewController { coordinatorType.currentViewController = actualController } } func bindInput() -> T.Input { fatalError("bindInput not implemented") } func bindOuput(_ output: T.Output) { fatalError("bindoutput not implemented") } }
// // ReadVC.swift // OneCopy // // Created by Mac on 16/10/13. // Copyright © 2016年 DJY. All rights reserved. // import UIKit class ReadVC: BaseViewController { var bannerView : NJBannerView! var datas : [ReadListModel]! var scrollView : UIScrollView! override func viewDidLoad() { super.viewDidLoad() self.title = "阅读" self.datas = Array.init() self.getListDatas() } func setupView() -> Void { //bannerview self.bannerView = NJBannerView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.bounds.size.width, height: 150)) self.getBannerDatas() self.view.addSubview(self.bannerView) //scrollview self.scrollView = UIScrollView.init(frame: CGRect.init(x: 0, y: 150, width: self.view.bounds.size.width, height: self.view.bounds.size.height - 64 - 49 - 49)) self.scrollView.isPagingEnabled = true self.scrollView.showsHorizontalScrollIndicator = false for i in 0..<self.datas.count { let item = ReadListCardItem.init(model: self.datas[i], frame: CGRect.init(x: self.scrollView.bounds.width * CGFloat.init(i), y: 0, w: self.scrollView.bounds.width, h: self.scrollView.bounds.height)) self.scrollView.addSubview(item) } self.scrollView.contentSize = CGSize.init(width: CGFloat.init(self.datas.count) * self.view.bounds.size.width, height: 0) self.view.addSubview(self.scrollView) } func getBannerDatas() -> Void { let datas : NSMutableArray = NSMutableArray.init() //网络请求 HttpManager.readImageGet { dataArray in //遍历数组 for dic:Dictionary<String,AnyObject> in dataArray{ print(dic) datas.add(dic) } DispatchQueue.main.async { self.bannerView.datas = datas } } } func getListDatas() -> Void { let list_1 : ReadListModel = ReadListModel.init() list_1.readList = Array.init() //网络请求 HttpManager.readConmentGet { dataArray in //遍历数组 for dic:Dictionary<String,AnyObject> in dataArray{ let model : ReadModel = ReadModel.init() model.title = dic["title"] as! NSString? model.writer = dic["writer"] as! NSString? model.content = dic["content"] as! NSString? model.type = dic["type"] as! NSString? list_1.readList?.append(model) } list_1.calLayout() self.datas.append(list_1) self.datas.append(list_1) DispatchQueue.main.async { self.setupView() } } } } // let tempDict1 : Dictionary = ["img":"b_1","link":""] // let tempDict2 : Dictionary = ["img":"b_2","link":""] // let tempDict3 : Dictionary = ["img":"b_3","link":""] // let tempDict4 : Dictionary = ["img":"b_4","link":""] // datas.add(tempDict1) // datas.add(tempDict2) // datas.add(tempDict3) // datas.add(tempDict4) // let model_1 : ReadModel = ReadModel.init() // model_1.title = "云想衣裳" // model_1.writer = "吴浩然" // model_1.content = "岂止衣裳不知道放哪了。你现在年轻,不知道的还多着呢。" // model_1.type = "短篇" // list_1.readList?.append(model_1) // // let model_2 : ReadModel = ReadModel.init() // model_2.title = "玩家 第七话" // model_2.writer = "夜X" // model_2.content = "愤怒是治疗恐惧的良方,而它自身的副作用大小因人而异。陆仁甲克服它只用了大概二十秒的时间" // model_2.type = "连载" // list_1.readList?.append(model_2) // // let model_3 : ReadModel = ReadModel.init() // model_3.title = "人与人之间的信任到底有多脆弱" // model_3.writer = "@周宏翔 答潘大曼" // model_3.content = "有时候并非我们真正感到孤独,而是我们太敏感,太恐惧,太害怕受伤,才会让自己孤独。" // model_3.type = "问答" // list_1.readList?.append(model_3)
// // DataTypeTest.swift // StanwoodCore_Tests // // Created by Tal Zion on 03/01/2018. // Copyright © 2018 CocoaPods. All rights reserved. // import XCTest import StanwoodCore import SourceModel class DataTypeTest: XCTestCase { var objects: Elements<Item>! var sections: Sections! override func setUp() { super.setUp() let floats: [Item] = [ Item(title: "CGFloat", subTitle: "Alpha", signature: "CGFloat.Alpha.clear", value: "0.0"), Item(title: "CGFloat", subTitle: "Alpha", signature: "CGFloat.Alpha.veryLight", value: "0.3"), Item(title: "CGFloat", subTitle: "Alpha", signature: "CGFloat.Alpha.light", value: "0.4"), Item(title: "CGFloat", subTitle: "Alpha", signature: "CGFloat.Alpha.half", value: "0.5"), Item(title: "CGFloat", subTitle: "Alpha", signature: "CGFloat.Alpha.faded", value: "0.7"), Item(title: "CGFloat", subTitle: "Alpha", signature: "CGFloat.Alpha.full", value: "1.0"), Item(title: "CGFloat", subTitle: "Damping", signature: "CGFloat.Damping.low", value: "0.3"), Item(title: "CGFloat", subTitle: "Damping", signature: "CGFloat.Damping.medium", value: "0.7"), Item(title: "CGFloat", subTitle: "Damping", signature: "CGFloat.Damping.high", value: "1.0"), Item(title: "CGFloat", subTitle: "Spring", signature: "CGFloat.Spring.low", value: "0.3"), Item(title: "CGFloat", subTitle: "Spring", signature: "CGFloat.Spring.medium", value: "0.7"), Item(title: "CGFloat", subTitle: "Spring", signature: "CGFloat.Spring.high", value: "1.0"), Item(title: "CGFloat", subTitle: "Radius", signature: "CGFloat.Radius.tiny", value: "5"), Item(title: "CGFloat", subTitle: "Radius", signature: "CGFloat.Radius.small", value: "8"), Item(title: "CGFloat", subTitle: "Radius", signature: "`CGFloat.Radius.medium`", value: "15"), Item(title: "CGFloat", subTitle: "Radius", signature: "`CGFloat.Radius.large`", value: "20") ] let strings: [Item] = [ Item(title: "String", subTitle: "String", signature: "\"MY_LOCAL_STRING\".localized", value: "Some Pretty string"), Item(title: "String", subTitle: "String", signature: "\"Some Pretty string\".first", value: "Some Pretty string".first), Item(title: "String", subTitle: "String", signature: "\"Some Pretty string\".last", value: "Some Pretty string".last), Item(title: "String", subTitle: "String", signature: "\"www.here.com\".httpURLString", value: "www.here.com".httpURLString), Item(title: "String", subTitle: "String", signature: "\"07976876560\".phoneFormat", value: "07976876560".phoneFormat), Item(title: "String", subTitle: "String", signature: "\"myNiceNameHere\".snakeCased()", value: "myNiceNameHere".snakeCased()), ] let allFloats = MainItem(items: floats) let allStrings = MainItem(items: strings) sections = Sections(items: [allFloats, allStrings]) let sectionOne = Elements(items: floats) objects = sectionOne let sectionTwo = Elements(items: strings) sections = Sections(items: [sectionOne, sectionTwo]) continueAfterFailure = true } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // MARK: - Test Sections func testSectionCount() { let count = 2 XCTAssertEqual(sections.numberOfSections, count) } func testCountNumberOfItemsInSectionTwo() { let count = 6 XCTAssertEqual(sections[1].numberOfItems, count) } func testCountNumberOfItemsInSectionOne() { let count = 16 XCTAssertEqual(sections[0].numberOfItems, count) } func testLastSectionItemID() { let title = "String" let indexPath = IndexPath(item: 5, section: 1) let item = sections[indexPath] as! Item XCTAssertEqual(item.title, title) } func testSectionOneItemID() { let subTitle = "Spring" let indexPath = IndexPath(item: 10, section: 0) let item = sections[indexPath] as! Item XCTAssertEqual(item.subTitle, subTitle) } // MARK: - Test Elements func testCount() { let count = 16 XCTAssertEqual(objects.numberOfItems, count) } func testInsert() { let object = Item(title: "Test", subTitle: "Item", signature: "Aaron", value: "Is Great") let objects = self.objects! objects.insert(item: object, at: 7) XCTAssert(objects.contains(object)) } func testContains() { let object = Item(title: "Test", subTitle: "Item", signature: "Aaron", value: "Is Likely Better Than Great") let objects: Elements<Item> = self.objects XCTAssertFalse(objects.contains(object)) objects.append(object) XCTAssert(objects.contains(object)) } func testMoveLow() { let objects: Elements<Item> = self.objects let indexPath = IndexPath(item: 2, section: 0) let objectThree = objects[indexPath] as! Item let movedToIndexPath = IndexPath(item: 7, section: 0) let from = objects[indexPath] as! Item objects.move(objectThree, to: 7) let to = objects[movedToIndexPath] as! Item XCTAssertEqual(from, to) } func testMoveHigh() { let elements: Elements<Item> = Elements<Item>(items: self.objects.items) let indexPath = IndexPath(item: 12, section: 0) let objectThree = objects[indexPath] as! Item let movedToIndexPath = IndexPath(item: 7, section: 0) let from = elements[indexPath] as! Item elements.move(objectThree, to: 7) let to = elements[movedToIndexPath] as! Item XCTAssertEqual(from, to) } func testMoveEnd() { let elements: Elements<Item> = Elements<Item>(items: self.objects.items) let indexPath = IndexPath(item: 7, section: 0) let objectThree = objects[indexPath] as! Item let movedToIndexPath = IndexPath(item: 13, section: 0) let from = elements[indexPath] as! Item elements.move(objectThree, to: 13) let to = elements[movedToIndexPath] as! Item XCTAssertEqual(from, to) } func testDelete() { let objects: Elements<Item> = self.objects let indexPath = IndexPath(item: 2, section: 0) let objectThree = objects[indexPath] as! Item XCTAssert(objects.contains(objectThree)) objects.delete(objectThree) XCTAssertFalse(objects.contains(objectThree)) } func testIndex() { let indexPath = IndexPath(item: 2, section: 0) let objectThree = objects[indexPath] as! Item let index = objects.index(of: objectThree) XCTAssertEqual(index, 2) } func testDataPersistence() { do { try objects.save() let loadedDeals = Elements<Item>.loadFromFile() XCTAssertNotNil(loadedDeals) if let loadedDeals = loadedDeals { XCTAssertEqual(objects.numberOfItems, loadedDeals.numberOfItems) let object = Item(title: "Test", subTitle: "Item", signature: "Aaron", value: "Most Handsome Man?") loadedDeals.append(object) XCTAssertNotEqual(objects.numberOfItems, loadedDeals.numberOfItems) try loadedDeals.save(withFileName: "objects_file") let objectsFile = Elements<Item>.loadFromFile(withFileName: "objects_file") XCTAssertNotNil(objectsFile) if let objectsFile = objectsFile { XCTAssertEqual(objectsFile.numberOfItems, loadedDeals.numberOfItems) } } } catch { XCTFail(error.localizedDescription) } } }
import UIKit /* Example : class func regularFont(withSize size: CGFloat) -> UIFont { if let font = UIFont(name: "Montserrat-Regular", size: size) { return font } return UIFont.systemFont(ofSize: size) } */ extension UIFont { } /* Example : class func blueColor() -> UIColor { return #colorLiteral(red: 0, green: 0.5725490196, blue: 0.8352941176, alpha: 1) } */ extension UIColor { }
// // NavigationControllerCoordinator.swift // ExampleCoordinator // // Created by Karlo Pagtakhan on 4/5/18. // Copyright © 2018 kidap. All rights reserved. // import UIKit //-------------------------------------------------------------------------------- // NavigationControllerCoordinator //-------------------------------------------------------------------------------- protocol NavigationControllerCoordinator: Coordinator { var navigationController: UINavigationController { get } var navigationControllerCoordinatorDelegate: NavigationControllerCoordinatorDelegate { get } } // Methods that can be called on the actual type extension NavigationControllerCoordinator { var rootController: UIViewController { return navigationController } func present(_ viewController: UIViewController, animated: Bool, completion: (() -> ())?) { guard let topViewController = navigationController.topViewController else { navigationController.viewControllers = [viewController] return } topViewController.present(viewController, animated: animated, completion: completion) } func push(_ viewController: UIViewController, animated: Bool) { navigationController.pushViewController(viewController, animated: animated) } func pop(_ viewController: UIViewController, animated: Bool) { // Adding the guard prevents popping the Coordinator.rootViewController when using the back button guard viewController == navigationController.viewControllers.last else { return } navigationController.popViewController(animated: animated) } func push(_ childCoordinator: Coordinator, animated: Bool) { addReference(to: childCoordinator) childCoordinator.didFinish = { [unowned childCoordinator, unowned self] in self.pop(childCoordinator.rootController, animated: animated) self.removeReference(from: childCoordinator) } childCoordinator.start() push(childCoordinator.rootController, animated: animated) } func pop(to viewController: UIViewController, animated: Bool) { // Adding the guard prevents popping the Coordinator.rootViewController when using the back button guard viewController == navigationController.viewControllers.last else { return } navigationController.popToViewController(viewController, animated: animated) } } // Override default implementation extension NavigationControllerCoordinator { func unsafePresentChildCoordinator(_ childCoordinator: Coordinator, animated: Bool, completion: (() -> ())?) { present(childCoordinator.rootController, animated: animated, completion: completion) } }
// // EnemyPlatform.swift // Trapescapes // // Created by Jüri Ilmjärv on 11/03/2019. // Copyright © 2019 Juri Ilmjarv. All rights reserved. // import Foundation import SpriteKit class EnemyPlatform: SKSpriteNode, GameSprite { var textureAtlas: SKTextureAtlas = SKTextureAtlas(named: "enemies.atlas") var platform = SKSpriteNode(imageNamed: "movingPlatform.png") var movingAction = SKAction() func spawn(parentNode: SKNode, position: CGPoint, size: CGSize = CGSize(width: 300, height: 150)) { parentNode.addChild(platform) platform.size = size platform.position = position createMoving() platform.run(movingAction) platform.physicsBody = SKPhysicsBody(texture: platform.texture!, size: platform.size) platform.physicsBody?.affectedByGravity = false platform.physicsBody?.isDynamic = false platform.physicsBody?.categoryBitMask = PhysicsCategory.enemy.rawValue platform.physicsBody?.collisionBitMask = ~PhysicsCategory.damagedOwl.rawValue } func createMoving() { let pathLeft = SKAction.moveBy(x: -200, y: 0, duration: 2) let pathRight = SKAction.moveBy(x: 200, y: 0, duration: 2) let movement = SKAction.sequence([pathLeft,pathRight]) movingAction = SKAction.repeatForever(movement) } func onTap() { } }
// // Index.swift // // // Created by Vladislav Fitc on 02/07/2020. // import Foundation public extension Index { /** Iterate over all objects in the index. - Parameter query: The Query used to search. - Parameter requestOptions: Configure request locally with RequestOptions - Returns: Launched asynchronous operation */ @discardableResult func browseObjects(query: Query = Query(), requestOptions: RequestOptions? = nil, completion: @escaping ResultCallback<[SearchResponse]>) -> Operation { let operation = BlockOperation { completion(.init { try self.browseObjects(query: query, requestOptions: requestOptions) }) } return operationLauncher.launch(operation) } /** Iterate over all objects in the index. - Parameter query: The Query used to search. - Parameter requestOptions: Configure request locally with RequestOptions - Returns: [SearchResponse] object */ @discardableResult func browseObjects(query: Query = Query(), requestOptions: RequestOptions? = nil) throws -> [SearchResponse] { var responses: [SearchResponse] = [] let initial = try browse(query: query, requestOptions: requestOptions) var cursor: Cursor? = initial.cursor responses.append(initial) while let nextCursor = cursor { let response = try browse(cursor: nextCursor) responses.append(response) cursor = response.cursor } return responses } /** Iterate over all Synonym in the index. - Parameter query: The SynonymQuery used to search. - Parameter requestOptions: Configure request locally with RequestOptions - Returns: Launched asynchronous operation */ @discardableResult func browseSynonyms(query: SynonymQuery = .init(), requestOptions: RequestOptions? = nil, completion: @escaping ResultCallback<[SynonymSearchResponse]>) -> Operation { let operation = BlockOperation { completion(.init { try self.browseSynonyms(query: query, requestOptions: requestOptions) }) } return operationLauncher.launch(operation) } /** Iterate over all Synonym in the index. - Parameter query: The SynonymQuery used to search. - Parameter requestOptions: Configure request locally with RequestOptions - Returns: [SynonymSearchResponse] object */ @discardableResult func browseSynonyms(query: SynonymQuery = .init(), requestOptions: RequestOptions? = nil) throws -> [SynonymSearchResponse] { var responses: [SynonymSearchResponse] = [] var page = 0 var response = try searchSynonyms(query, requestOptions: requestOptions) while !response.hits.isEmpty { response = try searchSynonyms(query.set(\.page, to: page), requestOptions: requestOptions) responses.append(response) page += 1 } return responses } /** Iterate over all Rule in the index. - Parameter query: The RuleQuery used to search. - Parameter requestOptions: Configure request locally with RequestOptions - Returns: Launched asynchronous operation */ @discardableResult func browseRules(query: RuleQuery = .init(), requestOptions: RequestOptions? = nil, completion: @escaping ResultCallback<[RuleSearchResponse]>) -> Operation { let operation = BlockOperation { completion(.init { try self.browseRules(query: query, requestOptions: requestOptions) }) } return operationLauncher.launch(operation) } /** Iterate over all Rule in the index. - Parameter query: The RuleQuery used to search. - Parameter requestOptions: Configure request locally with RequestOptions - Returns: [RuleSearchResponse] object */ @discardableResult func browseRules(query: RuleQuery = .init(), requestOptions: RequestOptions? = nil) throws -> [RuleSearchResponse] { var responses: [RuleSearchResponse] = [] var page = 0 var response = try searchRules(query, requestOptions: requestOptions) while !response.hits.isEmpty { response = try searchRules(query.set(\.page, to: page), requestOptions: requestOptions) responses.append(response) page += 1 } return responses } }
// // VriendsUITests.swift // VriendsUITests // // Created by Tjerk Dijkstra on 20/11/2018. // Copyright © 2018 Tjerk Dijkstra. All rights reserved. // import XCTest class VriendsUITests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() let app = XCUIApplication() setupSnapshot(app) app.launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. snapshot("01LoginScreen") let app = XCUIApplication() app.collectionViews.cells.otherElements.containing(.staticText, identifier:"Bruce").element.press(forDuration: 1.0); let friendProfileNavigationBar = app.navigationBars["Friend profile"] friendProfileNavigationBar.buttons["Edit"].tap() app.navigationBars["Edit Friend"].buttons["Friend profile"].tap() snapshot("02Vriendscreen") friendProfileNavigationBar.buttons["back button"].tap() app.navigationBars["Vriends"].buttons["?"].tap() app.otherElements["Page1"].swipeLeft() let textView = app.otherElements["Page2"].children(matching: .textView).element textView.swipeLeft() textView.swipeLeft() textView.swipeLeft() snapshot("03Offline") } }
// // ExepenseDetailTableViewCell.swift // Driver-Logger // // Created by Developer on 2/6/17. // Copyright © 2017 rtbdesigns. All rights reserved. // import UIKit class ExepenseDetailTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var imageLabel: UIImageView! 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 } }
// // TabBarVC.swift // LetsPo // // Created by Pin Liao on 25/07/2017. // Copyright © 2017 Walker. All rights reserved. // import UIKit import CoreData var noteDataManager:CoreDataManager<NoteData> = CoreDataManager.init(initWithModel: "LetsPoModel", dbFileName: "LetsPo.sqlite", dbPathURL: nil, sortKey: "note_ID", entityName: "NoteData") var boardDataManager:CoreDataManager<BoardData> = CoreDataManager.init(initWithModel: "LetsPoModel", dbFileName: "LetsPo.sqlite", dbPathURL: nil, sortKey: "board_CreateTime", entityName: "BoardData") var memberDataManager:CoreDataManager<MemberData> = CoreDataManager.init(initWithModel: "LetsPoModel", dbFileName: "LetsPo.sqlite", dbPathURL: nil, sortKey: "member_ID", entityName: "MemberData") class TabBarVC: UITabBarController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // 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. } */ }
// // Bill.swift // Jenin Residences // // Created by Ahmed Khalaf on 19/4/17. // Copyright © 2017 pxlshpr. All rights reserved. // import Foundation import RealmSwift class Bill: Object { dynamic var id: String = "" dynamic var unit: Unit? dynamic var creator: User? dynamic var previousDate: Date = Date() dynamic var currentDate: Date = Date() dynamic var previousReading: Double = 0.0 dynamic var currentReading: Double = 0.0 dynamic var fixedMonthlyCharge: Double = 0.0 dynamic var surcharge: Double = 0.0 dynamic var extraCharges: Double = 0.0 override static func primaryKey() -> String? { return "id" } }
// // DiaSelecionado.swift // HptMobileIOS // // Created by Rodrigo Lotrario on 30/06/17. // Copyright © 2017 Rodrigo Lotrario. All rights reserved. // import Foundation import UIKit class DiaSelecionado: UIViewController, UITableViewDelegate{ @IBOutlet var detalhesEventoView: DetalhesEvento! @IBOutlet var detalhesDiaView: DetalhesDia! @IBOutlet var comentariosView: ComentariosTarefa! public var largura: CGFloat = 0 public var altura: CGFloat = 0 public var data = Date() private var eventosArray: Array<Array<String>> = [] override func viewDidLoad() { self.view.frame = CGRect(x: 0, y: 0, width: largura, height: altura) carregarEventos() } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) construirDetalhesView(informacoes: eventosArray[indexPath.row]) } private func carregarEventos(){ let conn = ConexaoWebService() conn.realizarConexao(pacote: "eventos", funcao: "consultarEventos", metodo: "GET") { (objeto) in print(objeto) if(objeto is NSNull){ self.construirDetalhesDia() }else{ let tempDict = objeto as! Dictionary<String,String> DispatchQueue.main.async(execute: { for i in 0...tempDict.count-1{ self.eventosArray.append(objeto[String(i)] as! Array<String>) } self.construirDetalhesDia() }) } } } private func construirDetalhesView(informacoes: Array<String>){ detalhesEventoView.center = self.view.center detalhesEventoView.layer.cornerRadius = 10 detalhesEventoView.alpha = 0 detalhesEventoView.definirTamanho(largura: view.frame.width, altura: view.frame.height) detalhesEventoView.tarefasTableView.selectRow(at: [0,0], animated: true, scrollPosition: .top) detalhesEventoView.informacoes(data: informacoes) self.view.addSubview(detalhesEventoView) UIView.animate(withDuration: 0.3) { self.detalhesDiaView.alpha = 0 self.detalhesEventoView.alpha = 1 } } private func construirDetalhesDia(){ detalhesDiaView.center = self.view.center detalhesDiaView.layer.cornerRadius = 10 detalhesDiaView.alpha = 0 detalhesDiaView.eventos(eventos: eventosArray) detalhesDiaView.definirTamanho(largura: view.frame.width, altura: view.frame.height) self.view.addSubview(detalhesDiaView) UIView.animate(withDuration: 0.3) { self.detalhesDiaView.alpha = 1 } } @IBAction func voltarButton(_ sender: Any) { dismiss(animated: true, completion: nil) } @IBAction func comentarioButton(_ sender: Any) { comentariosView.load(largura: view.frame.width, altura: view.frame.height, centro: view.center) view.addSubview(comentariosView) UIView.animate(withDuration: 0.3) { self.detalhesEventoView.alpha = 0 } } @IBAction func eventoConcluidoButton(_ sender: Any) { self.detalhesDiaView.alpha = 1 UIView.animate(withDuration: 0.3, animations: { self.detalhesEventoView.alpha = 0 }) { (finished) in self.detalhesEventoView.removeFromSuperview() } } @IBAction func observacoesSalvarButton(_ sender: Any) { self.detalhesEventoView.alpha = 1 UIView.animate(withDuration: 0.3) { self.comentariosView.alpha = 0 } } }
// // MockDefaultJSONResourceType.swift // LoadIt // // Created by Luciano Marisi on 20/07/2016. // Copyright © 2016 Luciano Marisi. All rights reserved. // import Foundation @testable import LoadIt struct MockDefaultJSONResourceType: JSONResourceType { typealias Model = MockObject }
import UIKit /** View for editing details of project model. Used in editing and creating project controllers. */ class ProjectView: UIView, UITextFieldDelegate { @IBOutlet private var view: UIView! @IBOutlet private weak var nameTextField: UITextField! @IBOutlet private weak var detailTextField: UITextField! private var project: Project? override func awakeFromNib() { super.awakeFromNib() configureUI() } private func configureUI() { Bundle.main.loadNibNamed(String(describing: type(of: self)), owner: self, options: nil) view.frame = bounds addSubview(view) } /** UITextFieldDelegate method. Hide keyboard when tap on return button. */ func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } /** Bind view with project. - Parameters: - item: Project. */ func bind(_ item: Project? = nil) { project = item nameTextField.text = item?.name detailTextField.text = item?.detail } /** Unbind project view. Returns new or updated project. Throws validation error if project cannot be created or edited. - Throws: ValidationError. - Returns: Project. */ func unbind() throws -> Project { let converter = Unwrapper() let textValidator = TextValidator() let name = try converter.unwrap(nameTextField.text) let detail = try converter.unwrap(detailTextField.text) guard textValidator.notEmpty(name) else { throw ValidationError(message: Localization.localize(key: "error.validation.project.name")) } guard textValidator.notEmpty(detail) else { throw ValidationError(message: Localization.localize(key: "error.validation.project.detail")) } let newProject = Project(name: name, detail: detail) if let id = project?.id { newProject.id = id } return newProject } }
// // ApiCallExampleVC.swift // UsefulExamples // // Created by Nitin Khurana on 23/02/18. // Copyright © 2018 Nitin Khurana. All rights reserved. // import UIKit import SwiftyJSON class ApiCallExampleVC: ViewController, UITableViewDataSource, UITableViewDelegate{ @IBOutlet var tableView:UITableView! var data = [UserData]() // number of sections func numberOfSections(in tableView: UITableView) -> Int { return 1 } // number of items in each section func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if data == nil{ return 0 } return data.count } // table cell item func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserTableViewCell var user:UserData = data[indexPath.row] cell.name.text = user.name! let url = URL(string: user.picture!) let imageData = try? Data(contentsOf: url!) cell.userImage?.image = UIImage(data: imageData!) cell.email.text = user.email return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 150 } func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 150 } override func viewDidLoad() { super.viewDidLoad() RestApiManager.instance.callApi(url: AppConfig.URL_USERS, onCompletion: {json in let result = json["results"] for user in result{ for _ in 0 ... 10{ self.data.append(UserData(json: user.1)) } } DispatchQueue.main.async { self.tableView.reloadData() } }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // GetRyujumeModel.swift // RyujumeApp // // Created by baby1234 on 22/07/2019. // Copyright © 2019 baby1234. All rights reserved. // import Foundation struct RyujumeModel: Codable { let userName: String let identityImg: String? let phoneNumber: String let email: String let simpleIntroduce: String let career: [Career]? let academicBackground: [AcademicBackground]? let prize: [Prize]? let foreignLanguage: [ForeignLanguage]? let link: [String]? let isLiked: Bool enum CodingKeys: String, CodingKey { case userName case identityImg = "profileImg" case phoneNumber case email case simpleIntroduce = "simpleInfo" case career case academicBackground = "academicBack" case prize case foreignLanguage = "language" case link case isLiked = "likeStatus" } } struct Career: Codable { let isWorking: Bool let company: String let startDate: Int? let endDate: Int? enum CodingKeys: String, CodingKey { case isWorking = "isServed" case company = "companyName" case startDate case endDate } } struct AcademicBackground: Codable { let isAttending: Bool let school: String let startDate: Int? let endDate: Int? enum CodingKeys: String, CodingKey { case isAttending = "isInSchool" case school = "schoolName" case startDate case endDate } } struct Prize: Codable { let prize: String let prizedDate: Int? enum CodingKeys: String, CodingKey { case prize = "title" case prizedDate = "prizeDate" } } struct ForeignLanguage: Codable { let language: String let level: String enum CodingKeys: String, CodingKey { case language = "languageName" case level } }
// // SortableColumns.swift // Project4 // // Created by Josh Hollandsworth on 7/16/19. // Copyright © 2019 umsl. All rights reserved. // import Foundation enum SortOptions { case AscendingDate, DescendingDate, Duration, CaloriesPerMinute }
// // NoteTableViewController+NSFetchedResultsControllerDelegate.swift // Everpobre // // Created by Antonio Blazquez Bea on 09/04/2018. // Copyright © 2018 Antonio Blazquez Bea. All rights reserved. // import Foundation import CoreData extension NoteTableViewController : NSFetchedResultsControllerDelegate { func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { self.tableView.reloadData() } }
// // NetworkManager.swift // braincode-ios // // Created by Kacper Harasim on 18.03.2016. // Copyright © 2016 Kacper Harasim. All rights reserved. // import Foundation import Alamofire import RxSwift import SwiftyJSON import RxAlamofire enum NetworkManagerError: ErrorType, CustomStringConvertible { case BadResponse(code: Int) case MultipartDataSendFailed(ErrorType) case MultipartResponseFailure(ErrorType) case JSONParsingError var description: String { return "" } } class NetworkManager { private static let baseAddress = "http://10.3.8.27:5000/" // private static let baseAddress = "http://requestb.in/usw27yus" enum Endpoint: String { case Compute = "compute" var path: String { return baseAddress + self.rawValue } } func sendDataMultipart(data: NSData, endpoint: Endpoint = .Compute) -> (Observable<JSON>, Observable<Double>) { var cancelRequestToken: Request? let progressSubject = PublishSubject<Double>() let json = Observable.create { (observer: AnyObserver<JSON>) in Alamofire.upload( .POST, endpoint.path, multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: data, name: "img", fileName: "ios_\(NSDate().timeIntervalSince1970).jpg", mimeType: "image/jpg") }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.progress { _, written, expected in let val = Double(written) / Double(expected) print(val) progressSubject.onNext(val) } cancelRequestToken = upload.responseJSON { response in switch response.result { case let .Success(val): let json = JSON(val) observer.onNext(json) observer.onCompleted() case .Failure(let error): observer.onError(NetworkManagerError.MultipartDataSendFailed(error)) } } case .Failure(let encodingError): observer.onError(NetworkManagerError.MultipartDataSendFailed(encodingError)) } }) return AnonymousDisposable { cancelRequestToken?.cancel() } } return (json, progressSubject) } func basicRequest(endpoint: Endpoint) -> Observable<JSON> { return requestJSON(.POST, endpoint.path).flatMap { response, json -> Observable<JSON> in if response.statusCode != 200 { return Observable.error(NetworkManagerError.BadResponse(code: response.statusCode)) } return Observable.just(JSON(json)) } } }
// // DayNineTests.swift // Test // // Created by Shawn Veader on 12/9/18. // Copyright © 2018 Shawn Veader. All rights reserved. // import XCTest class DayNineTests: XCTestCase { func testCircleInsert() { let circle = MarbleCircle() circle.insert(marble: 1) circle.insert(marble: 2) circle.insert(marble: 3) XCTAssertEqual([0, 2, 1, 3], circle.array) XCTAssertEqual(4, circle.count) circle.insert(marble: 4) circle.insert(marble: 5) XCTAssertEqual([0, 4, 2, 5, 1, 3], circle.array) XCTAssertEqual(6, circle.count) } func testCircleRemove() { let circle = MarbleCircle() circle.insert(marble: 1) circle.insert(marble: 2) circle.insert(marble: 3) circle.insert(marble: 4) circle.insert(marble: 5) circle.insert(marble: 6) circle.insert(marble: 7) circle.insert(marble: 8) circle.insert(marble: 9) let answer = circle.removeMarble() XCTAssertEqual(1, answer) XCTAssertEqual([0, 8, 4, 9, 2, 5, 6, 3, 7], circle.array) XCTAssertEqual(9, circle.count) } func testPlayLogic() { let day = DayNine() var answer = day.play(players: 9, until: 25) XCTAssertEqual(32, answer) answer = day.play(players: 10, until: 1618) XCTAssertEqual(8317, answer) answer = day.play(players: 13, until: 7999) XCTAssertEqual(146373, answer) answer = day.play(players: 17, until: 1104) XCTAssertEqual(2764, answer) answer = day.play(players: 21, until: 6111) XCTAssertEqual(54718, answer) answer = day.play(players: 30, until: 5807) XCTAssertEqual(37305, answer) } }
import Foundation class CharactersClient: CharactersClientProtocol { private let httpClient: HTTPAPIClient init(httpClient: HTTPAPIClient) { self.httpClient = httpClient } func getCharacters(_ comicsRequest: CharactersRequest, completion: @escaping (Result<DataContainer<CharactersRequest.Response>>) -> Void) { httpClient.send(comicsRequest, completion: completion) } func getComics(_ comicRequest: CharacterComicsRequest, completion: @escaping (Result<DataContainer<CharacterComicsRequest.Response>>) -> Void) { httpClient.send(comicRequest, completion: completion) } func getEvents(_ eventRequest: CharacterEventsRequest, completion: @escaping (Result<DataContainer<CharacterEventsRequest.Response>>) -> Void) { httpClient.send(eventRequest, completion: completion) } func getSeries(_ seriesRequest: CharacterSeriesRequest, completion: @escaping (Result<DataContainer<CharacterSeriesRequest.Response>>) -> Void) { httpClient.send(seriesRequest, completion: completion) } func getStories(_ storiesRequest: CharacterStoriesRequest, completion: @escaping (Result<DataContainer<CharacterStoriesRequest.Response>>) -> Void) { httpClient.send(storiesRequest, completion: completion) } }
// // DetailView.swift // blog // // Created by maart on 2021/01/13. // import SwiftUI struct DetailView: View { var body: some View { VStack { Text("Hello, world!") .padding() } .navigationTitle("Detail") .onAppear(perform: { print("onAppear DetailView") }) .onDisappear(perform: { print("onDisappear DetailView") }) } } struct DetailView_Previews: PreviewProvider { static var previews: some View { DetailView() } }
// // VC+ARSCNViewDelegate.swift // ar // // Created by Kaan Ozdemir on 9.12.2020. // import Foundation import ARKit extension ViewController: ARSCNViewDelegate{ func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) { DispatchQueue.main.async { self.updateFocusSquare() } } }
// // CoachAthleteSearchVC.swift // SandRecruits // // Created by PC on 03/05/19. // Copyright © 2019 PC. All rights reserved. // import UIKit class CoachAthleteSearchVC: UIViewController, UITableViewDelegate, UITableViewDataSource , UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet var filterMainViewHeightConstraint: NSLayoutConstraint! @IBOutlet var applyFilterBtn: UIButton! @IBOutlet var applyFilterSearchBackViewHeightConstraint: NSLayoutConstraint! @IBOutlet var applyFilterSearchBackView: UIView! @IBOutlet var tblView: UITableView! @IBOutlet var tblViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var searchAthletTxt: TextField! @IBOutlet weak var pickerView: UIView! @IBOutlet weak var athletePicker: UIPickerView! @IBOutlet weak var graduationTxt: TextField! @IBOutlet weak var educationTxt: TextField! @IBOutlet weak var stateTxt: TextField! @IBOutlet weak var travelTxt: TextField! @IBOutlet weak var gpaTxt: TextField! @IBOutlet weak var positionTxt: TextField! @IBOutlet weak var totalAthletLbl: Label! @IBOutlet weak var viewTrackBtn: UIButton! @IBOutlet weak var hideCommitBtn: UIButton! var arrPlayerData : [PlayerMainModel] = [PlayerMainModel]() var arr : [ValueModel] = [ValueModel]() var filterDict : [String : Any] = [String : Any]() var arrGrandyear : [ValueModel] = [ValueModel]() var arrCurrentEducationLevel : [ValueModel] = [ValueModel]() var arrState : [ValueModel] = [ValueModel]() var arrTravel : [ValueModel] = [ValueModel]() var arrGPA : [ValueModel] = [ValueModel]() var arrPosition : [ValueModel] = [ValueModel]() var page = 1 var limit = 10 var isLoadNextData : Bool = true var type = 0 override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(updateTrackStatus(noti:)), name: NSNotification.Name.init(NOTIFICATION.UPDATE_TRACK_STATUS), object: nil) tblView.register(UINib(nibName: "CoachAthleteSearchTVC", bundle: nil), forCellReuseIdentifier: "CoachAthleteSearchTVC") AppDesign() resetAllData() getfilterDict() refreshData() } @objc func updateTrackStatus(noti : Notification) { if let dict : [String : Any] = noti.object as? [String : Any] { let tempPlayer : PlayerMainModel = PlayerMainModel.init(dict: dict) let index = arrPlayerData.firstIndex { (temp) -> Bool in temp.id == tempPlayer.id } if index != nil { arrPlayerData[index!].track_player = tempPlayer.track_player tblView.reloadData() } } } func AppDesign() { applyFilterBtn.isSelected = false applyFilterSearchBackView.isHidden = true applyFilterSearchBackViewHeightConstraint.constant = 0 filterMainViewHeightConstraint.constant = 108 } func refreshData() { page = 1 limit = 100 isLoadNextData = true getPlayerList() } func resetAllData() { filterDict = [String : Any]() filterDict["grandyear"] = "" filterDict["currenteducationlevel"] = "" filterDict["state"] = "" filterDict["willing_travel"] = "" filterDict["gpa"] = "" filterDict["position"] = "" filterDict["tracked"] = "0" filterDict["committed"] = "0" searchAthletTxt.text = "" graduationTxt.text = "" educationTxt.text = "" stateTxt.text = "" travelTxt.text = "" gpaTxt.text = "" positionTxt.text = "" } //MARK: - Button Click @IBAction func clickToBack(_ sender: Any) { self.navigationController?.popViewController(animated: true) } @IBAction func clickToSideMenu(_ sender: Any) { self.view.endEditing(true) self.menuContainerViewController.toggleRightSideMenuCompletion { } } @IBAction func clicKToApplyFilter(_ sender: Any) { if applyFilterBtn.isSelected == true { applyFilterBtn.isSelected = false applyFilterSearchBackView.isHidden = true applyFilterSearchBackViewHeightConstraint.constant = 0 filterMainViewHeightConstraint.constant = 108 } else { applyFilterBtn.isSelected = true applyFilterSearchBackView.isHidden = false applyFilterSearchBackViewHeightConstraint.constant = 606 filterMainViewHeightConstraint.constant = 714 } } @IBAction func clickToSelectPicker(_ sender: UIButton) { self.view.endEditing(true) arr = [ValueModel]() type = sender.tag switch type { case 1: arr = arrGrandyear break case 2: arr = arrCurrentEducationLevel break case 3: arr = arrState break case 4: arr = arrTravel break case 5: arr = arrGPA break case 6: arr = arrPosition break default: break } athletePicker.reloadAllComponents() pickerView.isHidden = false } @IBAction func clickToDone(_ sender: Any) { pickerView.isHidden = true } @IBAction func clickToApplyFilter(_ sender: Any) { clicKToApplyFilter(applyFilterBtn) refreshData() } @IBAction func clickToResetFilter(_ sender: Any) { clicKToApplyFilter(applyFilterBtn) resetAllData() refreshData() } @IBAction func clickToSearch(_ sender: Any) { self.view.endEditing(true) refreshData() } //MARK; - TableView Delegate func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrPlayerData.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tblView.dequeueReusableCell(withIdentifier: "CoachAthleteSearchTVC", for: indexPath) as! CoachAthleteSearchTVC let dict = arrPlayerData[indexPath.row] setButtonBackgroundImage(dict.profile_image, btn: [cell.profileImgBtn]) cell.nameLbl.text = dict.name cell.srLbl.text = "SR#: " + dict.sr cell.addressLbl.text = dict.location cell.yearLbl.text = dict.grandyear cell.trackBtn.isSelected = (dict.track_player.lowercased() == "yes") cell.trackBtn.tag = indexPath.row cell.trackBtn.addTarget(self, action: #selector(clickToTrackPlayer(sender:)), for: .touchUpInside) tblViewHeightConstraint.constant = tblView.contentSize.height cell.selectionStyle = .none return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc : OtherUserProfileVC = self.storyboard?.instantiateViewController(withIdentifier: "OtherUserProfileVC") as! OtherUserProfileVC vc.player_id = arrPlayerData[indexPath.row].id vc.track_player = arrPlayerData[indexPath.row].track_player.lowercased() self.navigationController?.pushViewController(vc, animated: true) } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if indexPath.row == (arrPlayerData.count - 1) && isLoadNextData { print(arrPlayerData.count) // getPlayerList() } } @objc func clickToTrackPlayer(sender : UIButton) { sender.isSelected = !sender.isSelected arrPlayerData[sender.tag].track_player = (sender.isSelected ? "yes" : "no") let dict = arrPlayerData[sender.tag] serviceCallToTrackPlayer(player_id: dict.id, value: (sender.isSelected ? "yes" : "no")) } @IBAction func clickToViewTrackCheckbox(sender : UIButton) { sender.isSelected = sender.isSelected == true ? false : true filterDict["tracked"] = (sender.isSelected) ? "1" : "0" getPlayerList() } @IBAction func clickToHideCommitedPlayerCheckbox(sender : UIButton) { sender.isSelected = sender.isSelected == true ? false : true filterDict["committed"] = (sender.isSelected) ? "1" : "0" getPlayerList() } //MARK: - PickerView Delegate func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return arr.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return arr[row].label } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch type { case 1: graduationTxt.text = arrGrandyear[row].label filterDict["grandyear"] = arrGrandyear[row].value break case 2: educationTxt.text = arrCurrentEducationLevel[row].label filterDict["currenteducationlevel"] = arrCurrentEducationLevel[row].value break case 3: stateTxt.text = arrState[row].label filterDict["state"] = arrState[row].value break case 4: travelTxt.text = arrTravel[row].label filterDict["willing_travel"] = arrTravel[row].value break case 5: gpaTxt.text = arrGPA[row].label filterDict["gpa"] = arrGPA[row].value break case 6: positionTxt.text = arrPosition[row].label filterDict["position"] = arrPosition[row].value break default: break } } func getfilterDict() { APIManager.shared.serviceCallToGetPlayerFilter { (data) in if let temp : [[String : Any]] = data["grandyear"] as? [[String : Any]] { for tempDict in temp { self.arrGrandyear.append(ValueModel.init(dict: tempDict)) } } if let temp : [[String : Any]] = data["currenteducationlevel"] as? [[String : Any]] { for tempDict in temp { self.arrCurrentEducationLevel.append(ValueModel.init(dict: tempDict)) } } if let temp : [[String : Any]] = data["state"] as? [[String : Any]] { for tempDict in temp { self.arrState.append(ValueModel.init(dict: tempDict)) } } if let temp : [[String : Any]] = data["willing_travel"] as? [[String : Any]] { for tempDict in temp { self.arrTravel.append(ValueModel.init(dict: tempDict)) } } if let temp : [[String : Any]] = data["gpa"] as? [[String : Any]] { for tempDict in temp { self.arrGPA.append(ValueModel.init(dict: tempDict)) } } if let temp : [[String : Any]] = data["position"] as? [[String : Any]] { for tempDict in temp { self.arrPosition.append(ValueModel.init(dict: tempDict)) } } } } func getPlayerList() { var param : [String : Any] = [String : Any]() param["user_id"] = AppModel.shared.currentUser.uId param["page_no"] = page param["limit"] = limit param["sp"] = searchAthletTxt.text param["grandyear"] = filterDict["grandyear"] param["currenteducationlevel"] = filterDict["currenteducationlevel"] param["state"] = filterDict["state"] param["willing_travel"] = filterDict["willing_travel"] param["gpa"] = filterDict["gpa"] param["position"] = filterDict["position"] param["tracked"] = filterDict["tracked"] param["committed"] = filterDict["committed"] print(param) APIManager.shared.serviceCallToGetPlayerList(param) { (data, total_count) in self.totalAthletLbl.text = total_count + " Athletes" self.arrPlayerData = [PlayerMainModel]() for temp in data { self.arrPlayerData.append(PlayerMainModel.init(dict: temp)) } DispatchQueue.main.async { self.tblView.reloadData() self.tblViewHeightConstraint.constant = self.tblView.contentSize.height } if data.count < self.limit { self.isLoadNextData = false } else { self.page = self.page + 1 } } } func serviceCallToTrackPlayer(player_id : String, value : String) { var param : [String : Any] = [String : Any]() param["user_id"] = AppModel.shared.currentUser.uId param["player_id"] = player_id param["value"] = value APIManager.shared.serviceCallToTrackPlayer(param) { (data) in } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // Photo.swift // PhotoGallery // // Created by Ajay Rawat on 2021-03-22. // import Foundation private enum PhotoListCodingKeys: String, CodingKey { case total case total_pages case results } extension PhotoList { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: PhotoListCodingKeys.self) total = try container.decode(Int.self, forKey: .total) total_pages = try container.decode(Int.self, forKey: .total_pages) photos = try container.decode([Photo].self, forKey: .results) } } struct PhotoList: Decodable { struct Photo: Decodable { struct User: Decodable { var id: String var userName: String var name: String } struct Url: Decodable { var raw: String? var full: String? var regular: String? var small: String? var thumb: String? } var isExpand: Bool var id: String var description: String? var alt_description: String? var url: Url? var width: Float var height: Float var user: User } var total: Int var total_pages: Int var photos: [Photo] } private enum CodingKeys: String, CodingKey { case id case description case alt_description case width case height case urls case user } extension PhotoList.Photo { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decode(String.self, forKey: .id) description = try container.decodeIfPresent(String.self, forKey: .description) alt_description = try container.decodeIfPresent(String.self, forKey: .alt_description) width = try container.decode(Float.self, forKey: .width) height = try container.decode(Float.self, forKey: .height) url = try container.decode(Url.self, forKey: .urls) user = try container.decode(User.self, forKey: .user) isExpand = false } } private enum UserCodingKeys: String, CodingKey { case id case username case name } extension PhotoList.Photo.User { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: UserCodingKeys.self) id = try container.decode(String.self, forKey: .id) userName = try container.decode(String.self, forKey: .username) name = try container.decode(String.self, forKey: .name) } var displayUserName: String { return "Clicked By: \(userName)" } } extension PhotoList.Photo { var calculatedHeight: Float { return max((height * 0.050), 220) } }
// // SignalingSDP.swift // SimpleWebRTC // // Created by tkmngch on 2019/01/08. // Copyright © 2019 tkmngch. All rights reserved. // import Foundation //struct SignalingSDP: Codable { // let type: String // let sdp: String //} // //struct SignalingCandidate: Codable { // let type: String // let candidate: Candidate //} //struct callResponser: Codable { // var action: String? = "" // var msg: String? = "" // var room:String? = "" // // init(action: String? = "", msg: String? = "", room: String? = "") { // self.action = action ?? "" // self.msg = msg ?? "" // self.room = room ?? "" // } //} //struct emirSocket: Codable { // let action: String // let content: String //} struct CallSocketResp : Codable { let action: String let room: String } struct ConnectSocketResp : Codable { let location: String let room: String let action: String } struct sendSmsStr: Codable { let action: String let room: String let tid: String let tan: String } struct ToogleCamera: Codable { let action: String let result: Bool } struct ToogleTorch: Codable { let action: String let result: Bool } struct SDPSender: Codable { let action: String let room: String let sdp: SDP2? } struct SDP2: Codable { let type: String let sdp: String } struct SendCandidate: Codable { let action: String let candidate: Candidate? let room: String? let sessionDescription: SDP? } struct SMSCandidate: Codable { let action: String let room: String? let is_admin: Bool? let tid: Int? } struct GetCandidate: Codable { let action: String? let candidate: Candidate? let room: String? } struct SignalingMessage: Codable { let type: String let sessionDescription: SDP? let candidate: Candidate? } struct NewCandidate: Codable { let action: String let candidate: Candidate? let room: String } struct SDP: Codable { let sdp: String } struct Candidate: Codable { let candidate: String let sdpMLineIndex: Int32 let sdpMid: String }
// // SecretCollection.swift // Scar // // Created by Mattia Cardone on 02/05/2020. // Copyright © 2020 Mattia Cardone. All rights reserved. // import UIKit import CloudKit class Password: UIViewController { @IBOutlet weak var pass: UITextField! override func viewDidLoad() { super.viewDidLoad() overrideUserInterfaceStyle = .light } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(false, animated: animated) } @IBAction func tryPass(_ sender: Any) { if(pass.text == "uragani"){ SecretCollection.allDescr = [] SecretCollection.allImages = [] let storyboard = UIStoryboard(name: "Main", bundle: nil) let secondVC = storyboard.instantiateViewController(withIdentifier: "collection") as! SecretCollection self.navigationController?.pushViewController(secondVC, animated: true) } else { pass.text = "" } } }
// // PageViewController.swift // Pruebas // // Created by Julio Banda on 4/18/19. // Copyright © 2019 Julio Banda. All rights reserved. // import UIKit class PageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate { let pets = PetsStore.pets override func viewDidLoad() { super.viewDidLoad() dataSource = self setViewControllers([viewControllerForPage(at: 0)], direction: .forward, animated: false, completion: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.isHidden = true } override func viewDidDisappear(_ animated: Bool) { super.viewDidAppear(animated) self.navigationController?.navigationBar.isHidden = false } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let viewController = viewController as? CustomCardViewController, let pageIndex = viewController.index, pageIndex > 0 else { return nil } return viewControllerForPage(at: pageIndex - 1) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let viewController = viewController as? CustomCardViewController, let pageIndex = viewController.index, pageIndex + 1 < pets.count else { return nil } return viewControllerForPage(at: pageIndex + 1) } func presentationCount(for pageViewController: UIPageViewController) -> Int { return pets.count } func presentationIndex(for pageViewController: UIPageViewController) -> Int { guard let viewControllers = pageViewController.viewControllers, let currentVC = viewControllers.first as? CustomCardViewController, let currentPageIndex = currentVC.index else { return 0 } return currentPageIndex } func viewControllerForPage(at index: Int) -> UIViewController { let viewController = UIStoryboard.init(name: "CustomTransition", bundle: nil).instantiateViewController(withIdentifier: "CustomCardViewController") as? CustomCardViewController viewController?.index = index viewController?.pet = pets[index] return viewController! } }
// // MonthViewController.swift // CalendarPOC // // Created by Ravi Bastola on 3/14/20. // Copyright © 2020 Ravi Bastola. All rights reserved. // import UIKit class MonthViewController: UIViewController { fileprivate lazy var monthCollectionView: UICollectionViewController = { let collection = HorizontalMonthCollectionViewController() collection.view.translatesAutoresizingMaskIntoConstraints = false return collection }() lazy var calendarEventsCollectionView: CalendarEventsCollectionViewController = { let collection = CalendarEventsCollectionViewController() collection.view.translatesAutoresizingMaskIntoConstraints = false collection.collectionView.contentInsetAdjustmentBehavior = .never return collection }() lazy var settingsView: UIButton = { let button = UIButton(type: .system) button.translatesAutoresizingMaskIntoConstraints = false button.setImage(#imageLiteral(resourceName: "menuw").withRenderingMode(.alwaysOriginal), for: .normal) button.addTarget(self, action: #selector(showSettingsView), for: .touchUpInside) return button }() lazy var gregorianMonthName: UILabel = { let label = UILabel() label.font = UIFont(name: Font.YantramanavBold.rawValue, size: 16) label.textColor = .label label.text = "November/December" label.textAlignment = .center return label }() fileprivate lazy var settingsController: UIViewController = { let controller = SettingsViewController() return controller }() //MARK:- LifeCycle override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground layoutMonthsCollectionView() layoutSettingsButton() layoutGregorainLabel() } //MARK:- UI func layoutMonthsCollectionView() { let container = UIView() container.addSubview(monthCollectionView.view) container.translatesAutoresizingMaskIntoConstraints = false container.widthAnchor.constraint(equalToConstant: view.frame.width).isActive = true container.heightAnchor.constraint(equalToConstant: 186).isActive = true addChild(monthCollectionView) monthCollectionView.didMove(toParent: self) //monthCollectionView.view.translatesAutoresizingMaskIntoConstraints = false //monthCollectionView.view.heightAnchor.constraint(equalToConstant: 186).isActive = true monthCollectionView.view.leadingAnchor.constraint(equalTo: container.leadingAnchor).isActive = true monthCollectionView.view.topAnchor.constraint(equalTo: container.topAnchor).isActive = true monthCollectionView.view.trailingAnchor.constraint(equalTo: container.trailingAnchor).isActive = true monthCollectionView.view.bottomAnchor.constraint(equalTo: container.bottomAnchor).isActive = true addChild(calendarEventsCollectionView) calendarEventsCollectionView.didMove(toParent: self) calendarEventsCollectionView.didMove(toParent: self) let stackView: UIStackView = UIStackView(arrangedSubviews: [ container, calendarEventsCollectionView.view ]) stackView.axis = .vertical //stackView.alignment = .center stackView.distribution = .fill view.addSubview(stackView) stackView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor), stackView.topAnchor.constraint(equalTo: view.topAnchor), stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor), stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor), ]) } func layoutSettingsButton() { monthCollectionView.view.addSubview(settingsView) NSLayoutConstraint.activate([ settingsView.heightAnchor.constraint(equalToConstant: 35), settingsView.widthAnchor.constraint(equalToConstant: 35), settingsView.topAnchor.constraint(equalTo: monthCollectionView.view.safeAreaLayoutGuide.topAnchor, constant: 10), settingsView.trailingAnchor.constraint(equalTo: monthCollectionView.view.trailingAnchor, constant: -20) ]) } func layoutGregorainLabel() { monthCollectionView.view.addSubview(gregorianMonthName) gregorianMonthName.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ gregorianMonthName.leadingAnchor.constraint(equalTo: monthCollectionView.view.safeAreaLayoutGuide.leadingAnchor, constant: 46), gregorianMonthName.bottomAnchor.constraint(equalTo: monthCollectionView.view.bottomAnchor, constant: -20) ]) } @objc func showSettingsView() { // viewController.didTapCloseButton = { // blurEffectView.removeFromSuperview() // } settingsController.modalTransitionStyle = .crossDissolve settingsController.modalPresentationStyle = .overCurrentContext present(settingsController, animated: true, completion: nil) } }
import Foundation public enum ApiServer: CaseIterable { case localhost case offline case staging case production static let displayNames: [Self: String] = [ .offline: "Sparta Offline System", .production: "home.spartascience.com" ] static let servers: [Self: String] = [ .localhost: "http://localhost:4000", .offline: "http://spartascan.local", .staging: "https://staging.spartascience.com", .production: "https://home.spartascience.com" ] public func serverUrlString() -> String { Self.servers[self].map { $0 + "/api/app-setup" }! } }
// // PostAPI.swift // Heyoe // // Created by Nam Phong on 7/24/15. // Copyright (c) 2015 Nam Phong. All rights reserved. // import UIKit class PostAPI: NSObject { class func sharePost(status: String!, imageURL: String!, videoURL: String!, completion:(newPost: PostObject)->Void, failure:(error: String)->Void) { let object = QBCOCustomObject() object.className = "Posts" object.fields.setObject(status, forKey: "status") object.fields.setObject(QMApi.instance().currentUser.fullName, forKey: "userName") if imageURL != nil { object.fields.setObject(imageURL, forKey: "photoURL") object.fields.setObject(false, forKey: "isVideo") } else if videoURL != nil { object.fields.setObject(videoURL, forKey: "photoURL") object.fields.setObject(true, forKey: "isVideo") } QBRequest.createObject(object, successBlock: { (response: QBResponse!, responseObj: QBCOCustomObject!) -> Void in let senderPost = PostObject(obj: responseObj) completion(newPost: senderPost) }) { (response: QBResponse!) -> Void in failure(error: "Fail to post. Try again later") } } class func updatePost(post: PostObject, completion: (newPost: PostObject!) -> Void, failure: (error: String) ->Void) { QBRequest.updateObject(post.convertToPost(), successBlock: { (response: QBResponse!,newPost: QBCOCustomObject!) -> Void in let senderPost = PostObject(obj: newPost) completion(newPost: senderPost) }) { (response: QBResponse!) -> Void in failure(error: response.error.description) } } class func postNewPostWithoutImage(status: String, completion: (newPost: PostObject!) -> Void, failure: (error: String) ->Void) { let object = QBCOCustomObject() object.className = "Posts" object.fields.setObject(status, forKey: "status") object.fields.setObject(QMApi.instance().currentUser.fullName, forKey: "userName") QBRequest.createObject(object, successBlock: { (response: QBResponse!, responseObj: QBCOCustomObject!) -> Void in let senderPost = PostObject(obj: responseObj) completion(newPost: senderPost) }) { (response: QBResponse!) -> Void in failure(error: "Fail to post. Try again later") } } class func postNewStatusWithVideo(status: String, url: NSURL!, completion:(newPost: PostObject!)->Void, failure:(error: String)->Void) { let data = NSData(contentsOfURL: url) SVProgressHUD.showProgress(0, status: nil, maskType: SVProgressHUDMaskType.Clear) QMApi.instance().contentService.uploadVideoData(data, progress: { (progress: Float) -> Void in SVProgressHUD.showProgress(progress, status: nil, maskType: SVProgressHUDMaskType.Clear) print("UPLOAD PROGRESS: \(progress)") }) { (result :QBCFileUploadTaskResult!) -> Void in SVProgressHUD.dismiss() print("RESULT: \(result)") if result.success { let photoURL = result.uploadedBlob.publicUrl() let object = QBCOCustomObject() object.className = "Posts" object.fields.setObject(status, forKey: "status") object.fields.setObject(QMApi.instance().currentUser.fullName, forKey: "userName") object.fields.setObject(photoURL, forKey: "photoURL") object.fields.setObject(true, forKey: "isVideo") QBRequest.createObject(object, successBlock: { (response: QBResponse!, responseObj: QBCOCustomObject!) -> Void in let senderPost = PostObject(obj: responseObj) completion(newPost: senderPost) }) { (response: QBResponse!) -> Void in failure(error: "Fail to post. Try again later") } } else { failure(error: result.errors.first as! String) } } } class func postNewPost(image: UIImage!, video: AnyObject!, status: String, completion: (newPost: PostObject!) -> Void, failure: (error: String) ->Void) { let data = UIImageJPEGRepresentation(image, 0.6) QBRequest.TUploadFile(data, fileName: "postPhoto", contentType: "image/jpeg", isPublic: true, successBlock: { (response: QBResponse!, lob: QBCBlob!) -> Void in let photoURL = lob.publicUrl() let object = QBCOCustomObject() object.className = "Posts" object.fields.setObject(status, forKey: "status") object.fields.setObject(QMApi.instance().currentUser.fullName, forKey: "userName") object.fields.setObject(photoURL, forKey: "photoURL") QBRequest.createObject(object, successBlock: { (response: QBResponse!, responseObj: QBCOCustomObject!) -> Void in let senderPost = PostObject(obj: responseObj) completion(newPost: senderPost) }) { (response: QBResponse!) -> Void in failure(error: "Fail to post. Try again later") } }, statusBlock: { (request: QBRequest!, requestStatus: QBRequestStatus!) -> Void in }) { (errRes: QBResponse!) -> Void in failure(error: "Fail to post. Try again later") } } class func getAllPostOfUser(user: QBUUser, completion: (postList: [PostObject]!) -> Void, failure: (error: String) ->Void) { let getRequest = NSMutableDictionary() getRequest.setObject(user.ID, forKey: "user_id") getRequest.setObject("_id", forKey: "sort_desc") QBRequest.objectsWithClassName("Posts", extendedRequest: getRequest, successBlock: { (response: QBResponse!, responseObject: [AnyObject]!, page: QBResponsePage!) -> Void in if let result = responseObject as? [QBCOCustomObject] { var senderObj: [PostObject] = [PostObject]() for obj in result { let _obj: PostObject = PostObject(obj: obj) senderObj.append(_obj) } completion(postList: senderObj) } }) { (response: QBResponse!) -> Void in failure(error: "Fail to get posts") } } class func getPostWithID(postID: String, completion: (post: PostObject)->Void, failure:(error: String)->Void) { QBRequest.objectWithClassName("Posts", ID: postID, successBlock: { (response: QBResponse!, responseObject:QBCOCustomObject!) -> Void in let post = PostObject(obj: responseObject) completion(post: post) }) { (error: QBResponse!) -> Void in failure(error: "Error") } } class func getAllPost(listUser: [QBUUser]!, completion: (postList: [PostObject]!) -> Void, failure: (error: String) ->Void) { let getRequest = NSMutableDictionary() var tmpArr = [QMApi.instance().currentUser.ID] for usr in listUser { tmpArr.append(usr.ID) } getRequest.setObject(tmpArr, forKey: "user_id[or]") getRequest.setObject("_id", forKey: "sort_desc") QBRequest.objectsWithClassName("Posts", extendedRequest: getRequest, successBlock: { (response: QBResponse!, responseObject: [AnyObject]!, page: QBResponsePage!) -> Void in if let result = responseObject as? [QBCOCustomObject] { var senderObj: [PostObject] = [PostObject]() var tmpUsers = listUser tmpUsers.append(QMApi.instance().currentUser) for obj in result { let _obj: PostObject = PostObject(obj: obj) senderObj.append(_obj) } completion(postList: senderObj) } }) { (response: QBResponse!) -> Void in failure(error: "Fail to get posts") } } }
// // DDItem3NaviVC.swift // ENWay // // Created by WY on 2019/82/13. // Copyright © 2018 WY. All rights reserved. // import UIKit class DDItem3NaviVC: DDBaseNavVC { convenience init(){ // let rootVC = DDItem2VC() let rootVC = DDItem3VC() // rootVC.title = DDLanguageManager.text("tabbar_item2_title") self.init(rootViewController: rootVC) self.title = "tabbar_item3_title"|?| // self.navigationBar.shadowImage = UIImage() // // self.tabBarItem.image = UIImage(named:"messageuncheckedIcon") // self.tabBarItem.selectedImage = UIImage(named:"messageselectionicon") self.tabBarItem.image = UIImage(named:"JL_personal") self.tabBarItem.selectedImage = UIImage(named:"JL_personal_sel") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func pushViewController(_ viewController: UIViewController, animated: Bool) { if self.children.count != 0 { viewController.hidesBottomBarWhenPushed = true } super.pushViewController(viewController, animated: animated) } }
// // DesafiosPageViewController.swift // Bloomy // // Created by Mayara Mendonça de Souza on 09/12/20. // import UIKit class DesafiosPageViewController: UIPageViewController { override func viewDidLoad() { super.viewDidLoad() } }
// // RegistrationViewController.swift // CatFacts // // Created by Serhii PERKHUN on 1/7/19. // Copyright © 2019 Serhii PERKHUN. All rights reserved. // import UIKit class RegistrationViewController: UIViewController { @IBOutlet weak var email: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var confirmPassword: UITextField! @IBOutlet weak var registerButton: UIButton! { willSet { newValue.layer.borderWidth = 2 newValue.layer.borderColor = UIColor(red:0.74, green:0.82, blue:0.81, alpha:1.0).cgColor newValue.layer.cornerRadius = newValue.frame.size.height * 0.45 newValue.clipsToBounds = true newValue.titleLabel?.adjustsFontSizeToFitWidth = true; newValue.titleLabel?.lineBreakMode = NSLineBreakMode.byClipping; } } @IBAction func hideKeyboard(_ sender: UITapGestureRecognizer) { view.endEditing(true) } @IBAction func registerButton(_ sender: UIButton) { if isValid(email: email.text!) == false || UserManager.instance.findUser(with: email.text!){ showAlert(message: "Email is invalid or already taken") } else if password.text!.count <= 5 { showAlert(message: "Too short password") } else if password.text! != confirmPassword.text! { showAlert(message: "Password does not match the confirm password") } else { let user = Users() user.email = email.text! user.password = password.text! UserManager.instance.saveContext() UserDefaults.standard.set(true, forKey: "auth") performSegue(withIdentifier: "segueFromRegistrationToCatFacts", sender: nil) } } func isValid(email: String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: email) } func showAlert(message: String) { let alert = UIAlertController(title: "", message: message, preferredStyle: .alert) self.present(alert, animated: true) let when = DispatchTime.now() + 3 DispatchQueue.main.asyncAfter(deadline: when){ alert.dismiss(animated: true, completion: nil) } } }
// // reminderDashboardViewController.swift // RHRN-Swft // // Created by Guy on 9/26/17. // Copyright © 2017 Durango Computers. All rights reserved. // import Foundation import UIKit class reminderDashboardViewController: UIViewController { 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. } @IBAction func riseShine(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "categoryViewController") as! categoryViewController controller.callingController = "rise" self.navigationController?.pushViewController(controller, animated: true) } @IBAction func relsButton2(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "categoryViewController") as! categoryViewController controller.callingController = "rels" self.navigationController?.pushViewController(controller, animated: true) } @IBAction func kidsButton(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "categoryViewController") as! categoryViewController controller.callingController = "kids" self.navigationController?.pushViewController(controller, animated: true) } @IBAction func tribeButton(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "categoryViewController") as! categoryViewController controller.callingController = "tribe" self.navigationController?.pushViewController(controller, animated: true) } @IBAction func comButton(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "categoryViewController") as! categoryViewController controller.callingController = "com" self.navigationController?.pushViewController(controller, animated: true) } @IBAction func clanButton(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "categoryViewController") as! categoryViewController controller.callingController = "clan" self.navigationController?.pushViewController(controller, animated: true) } @IBAction func jobButton(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "categoryViewController") as! categoryViewController controller.callingController = "job" self.navigationController?.pushViewController(controller, animated: true) } @IBAction func stressButton(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "categoryViewController") as! categoryViewController controller.callingController = "stress" self.navigationController?.pushViewController(controller, animated: true) } @IBAction func moolaButton(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "categoryViewController") as! categoryViewController controller.callingController = "moola" self.navigationController?.pushViewController(controller, animated: true) } @IBAction func healthButton(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "categoryViewController") as! categoryViewController controller.callingController = "health" self.navigationController?.pushViewController(controller, animated: true) } @IBAction func fitButton(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "categoryViewController") as! categoryViewController controller.callingController = "fit" self.navigationController?.pushViewController(controller, animated: true) } @IBAction func petsButton(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "categoryViewController") as! categoryViewController controller.callingController = "pets" self.navigationController?.pushViewController(controller, animated: true) } }
// // TextField.swift // SNKit_TJS // // Created by ZJaDe on 2018/5/10. // Copyright © 2018年 syk. All rights reserved. // import UIKit open class TextField: UITextField { public override init(frame: CGRect) { super.init(frame: frame) configInit() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder: ) has not been implemented") } open func configInit() { if self.textColor == nil { self.textColor = Color.black } if self.font == nil { self.font = Font.thinh3 } self.placeholderColor = Color.placeholder } open override var placeholder: String? { didSet { updatePlaceholder() } } public var placeholderFont: UIFont? { didSet { updatePlaceholder() } } public var placeholderColor: UIColor? { didSet { updatePlaceholder() } } func updatePlaceholder() { self.attributedPlaceholder = self.attributedPlaceholder? .mergeStyle(.color(placeholderColor), .font(placeholderFont)).finalize() } // MARK: - /// 输入框text位置 open var textInset: UIEdgeInsets = .zero open override func editingRect(forBounds bounds: CGRect) -> CGRect { super.editingRect(forBounds: bounds) - textInset } open override func textRect(forBounds bounds: CGRect) -> CGRect { super.textRect(forBounds: bounds) - textInset } }
// // XLActivityViewController.swift // 108Days-Swift // // Created by Shelin on 16/4/8. // Copyright © 2016年 GreatGate. All rights reserved. // import UIKit class ActivityViewController: XLRootViewController { //MARK: - life cyle override func viewDidLoad() { super.viewDidLoad() customNavBar() } //MARK: - UI private func customNavBar() { navigationItem.leftBarButtonItem = nil navigationItem.rightBarButtonItem = UIBarButtonItem.createBarButtonItem(self, action: Selector("sortAction"), imageName: "active_nav_right_btn") } //MARK: - btn action func sortAction() { print(__FUNCTION__) } }
/*: ### iOSDevUK 2016 — Intermediate Swift This is the completed playground from part 3a on Classes, covering Core Graphics. */ import UIKit // Slightly better way of drawing, taking advantage of CGContext as a class let bounds = CGRect(x: 0, y: 0, width: 300, height: 200) UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0) let path = UIBezierPath(ovalIn: bounds) let context = UIGraphicsGetCurrentContext()! context.setFillColor(UIColor.cyan.cgColor) context.addPath(path.cgPath) context.drawPath(using: .fill) if let contextImage = context.makeImage() { let uiImage = UIImage(cgImage: contextImage) } UIGraphicsEndImageContext() // The even better classy all-class way let renderer = UIGraphicsImageRenderer(size: bounds.size) let renderedImage = renderer.image { (renderContext) in let context = renderContext.cgContext context.setFillColor(UIColor.magenta.cgColor) context.addPath(path.cgPath) context.drawPath(using: .fill) } renderedImage
// // CustomerDataTVC.swift // OAuthentication // // Created by Sayantan Chakraborty on 09/06/17. // Copyright © 2017 SAP. All rights reserved. // import UIKit import SAPFiori class ViewController: UITableViewController { private var dA: ESPMContainerDataAccess? = nil var collections = [String]() private let appDelegate = UIApplication.shared.delegate as! AppDelegate var selectedIndexPath : IndexPath? weak var delegate: MasterDetailCustomerDelegate? override func viewDidLoad() { super.viewDidLoad() dA = appDelegate.espmContainer collections = CollectionType.allValues.map({ (collectionType) -> String in return collectionType.rawValue }).filter{$0 == CollectionType.customers.rawValue || $0 == CollectionType.products.rawValue} } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - UITableViewDelegate override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return collections.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: FUISimplePropertyFormCell.reuseIdentifier, for: indexPath) as! FUISimplePropertyFormCell cell.keyName = self.collections[indexPath.row] cell.valueTextField.isHidden = true cell.accessoryType = .detailDisclosureButton return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedIndexPath = indexPath let selectedCollectionType = CollectionType(rawValue: collections[indexPath.row]) self.delegate?.showDetail(type: selectedCollectionType!) //performSegue(withIdentifier: "showCustomerDetails", sender: self) // if let detailViewController = self.delegate as? CustomerDataTVC { // splitViewController?.showDetailViewController(detailViewController, sender: nil) // } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let selectedRow = self.tableView.indexPathForSelectedRow?.row { print("CollectionType:\(CollectionType(rawValue: collections[selectedRow])!)") let selectedCollectionType = CollectionType(rawValue: collections[selectedRow]) switch selectedCollectionType! { case .customers: if segue.destination is CustomerDataTVC { } default: print("unknown") } } } }
// // Shop.swift // DinoGame // // Created by Jordan Klein on 7/1/20. // Copyright © 2020 JordanKlein. All rights reserved. // import Foundation import SpriteKit import UIKit import GameKit import GoogleMobileAds //Localizing Strings for pop up notifications here let purpleTitle = NSLocalizedString("purpleAsteroid", comment: "My comment") let redTitle = NSLocalizedString("redAsteroid", comment: "My comment") let blueTitle = NSLocalizedString("blueAsteroid", comment: "My comment") let greenTitle = NSLocalizedString("greenAsteroid", comment: "My comment") let specialTitle = NSLocalizedString("specialAsteroid", comment: "My comment") // Unlockables let purpleUnlockable = NSLocalizedString("purpleUnlockable", comment: "My comment") let redUnlockable = NSLocalizedString("redUnlockable", comment: "My comment") let blueUnlockable = NSLocalizedString("blueUnlockable", comment: "My comment") let greenUnlockable = NSLocalizedString("greenUnlockable", comment: "My comment") let specialUnlockable = NSLocalizedString("specialUnlockable", comment: "My comment") // Remove Ads Button let removeAdButton = UIButton(type: .system) // Making an Asteroid User Default var asteroid = UserDefaults.standard.string(forKey: "texture") ?? "asteroid1" // Declaring Buttons Public let buttonNumber1 = UIButton(type: .custom) let buttonNumber2 = UIButton(type: .custom) let buttonNumber3 = UIButton(type: .custom) let buttonNumber4 = UIButton(type: .custom) let buttonNumber5 = UIButton(type: .custom) let buttonNumber6 = UIButton(type: .custom) // User Defaults for unlockables var blueSkin = UserDefaults.standard.bool(forKey: "blue") var redSkin = UserDefaults.standard.bool(forKey: "red") var greenSkin = UserDefaults.standard.bool(forKey: "green") var purpleSkin = UserDefaults.standard.bool(forKey: "purple") var mixSkin = UserDefaults.standard.bool(forKey: "mix") // Creating labels for below the buttons let blueLabel = SKLabelNode(fontNamed: "Press Start 2P") let redLabel = SKLabelNode(fontNamed: "Press Start 2P") let greenLabel = SKLabelNode(fontNamed: "Press Start 2P") let purpleLabel = SKLabelNode(fontNamed: "Press Start 2P") let mixLabel = SKLabelNode(fontNamed: "Press Start 2P") class ShopScene: SKScene, Alertable{ override func didMove(to view: SKView) { for view in view.subviews { if view is UIButton{ view.removeFromSuperview() } else { view.removeFromSuperview() } } // Adding in Custom UI Buttons to purchase new asteroid with Stars rewardedAdsButtonfunc() addingShopBackground() buttonsForBackground() labels() // Checks which asteroid is selected run(SKAction.repeatForever(SKAction.sequence([SKAction.run{self.buttonBackgrounds() }, SKAction.wait(forDuration: 0.01)]))) self.backgroundColor = .black } func addingShopBackground(){ //Star Textures behind if let particles = SKEmitterNode(fileNamed: "Stars"){ particles.position = CGPoint(x: -10, y: screenHeight) particles.zPosition = -1000 particles.advanceSimulationTime(60) addChild(particles) } starLabel.position = CGPoint(x: screenWidth * 0.5, y: screenHeight * 0.75) starLabel.fontSize = 15 starLabel.name = "starLabel" starLabel.zPosition = 3 starLabel.text = "\(starTitle):\(collectedStars)" starLabel.physicsBody?.isDynamic = false addChild(starLabel) } func buttonBackgrounds(){ // Checking the star count starLabel.text = "\(starTitle):\(collectedStars)" buttonNumber1.backgroundColor = .white buttonNumber2.backgroundColor = .white buttonNumber3.backgroundColor = .white buttonNumber4.backgroundColor = .white buttonNumber5.backgroundColor = .white buttonNumber6.backgroundColor = .white if asteroid == "asteroid1"{ buttonNumber1.backgroundColor = .link } else if asteroid == "asteroid2" { buttonNumber2.backgroundColor = .link } else if asteroid == "asteroid3" { buttonNumber3.backgroundColor = .link } else if asteroid == "asteroid4" { buttonNumber4.backgroundColor = .link } else if asteroid == "asteroid5" { buttonNumber5.backgroundColor = .link } else if asteroid == "asteroid6" { buttonNumber6.backgroundColor = .link } } func labels(){ if blueSkin == false { blueLabel.fontSize = 10 blueLabel.position = CGPoint(x: buttonNumber3.frame.origin.x + 50, y: buttonNumber3.frame.origin.y - 120) blueLabel.text = "100 \(starTitle)" blueLabel.zPosition = 100 addChild(blueLabel) } else { } if greenSkin == false { greenLabel.fontSize = 10 greenLabel.position = CGPoint(x: buttonNumber6.frame.origin.x + 50, y: buttonNumber6.frame.origin.y - 120) greenLabel.text = "50 \(starTitle)" addChild(greenLabel) } else { } if redSkin == false { redLabel.fontSize = 10 redLabel.position = CGPoint(x: buttonNumber4.frame.origin.x + 50, y: buttonNumber4.frame.origin.y - 120) redLabel.text = "150 \(starTitle)" addChild(redLabel) } else { } if purpleSkin == false { purpleLabel.fontSize = 10 purpleLabel.position = CGPoint(x: buttonNumber1.frame.origin.x + 50, y: buttonNumber1.frame.origin.y - 120) purpleLabel.text = "200 \(starTitle)" addChild(purpleLabel) } else { } if mixSkin == false { mixLabel.fontSize = 10 mixLabel.position = CGPoint(x: buttonNumber2.frame.origin.x + 50, y: buttonNumber2.frame.origin.y - 120) mixLabel.text = "250 \(starTitle)" addChild(mixLabel) } else { return } } func buttonsForBackground() { // MARK: Back Button backButton.frame = CGRect (x: Int(frame.width/2 - 100), y:Int(screenHeight * 0.05), width: 200, height: 40) let backTitle = NSLocalizedString("back", comment: "My comment") backButton.setTitle(backTitle, for: UIControl.State.normal) backButton.setTitleColor(UIColor.white, for: .normal) backButton.backgroundColor = customGreen backButton.layer.cornerRadius = 10 backButton.layer.borderWidth = 1 backButton.layer.borderColor=UIColor.white.cgColor backButton.addTarget(self, action: #selector(backbuttonRun), for: UIControl.Event.touchUpInside) backButton.titleLabel!.font = UIFont(name: "Press Start 2P", size: 20) backButton.titleLabel!.textAlignment = NSTextAlignment.center self.view!.addSubview(backButton) // MARK: Remove Ads Button // if !UserDefaults.standard.bool(forKey: "adsRemoved") { // self.view!.addSubview(removeAdButton) // } else { // // } // MARK: Asteroid Buttons //Default Asteroid buttonNumber1.setImage(UIImage(named: "as"), for: .normal) buttonNumber1.frame = CGRect(x: Int(frame.width)/2 - 150, y: Int(screenHeight * 0.25), width: 100, height: 100) buttonNumber1.layer.cornerRadius = 20 buttonNumber1.layer.borderWidth = 2 buttonNumber1.addTarget(self, action: #selector(asteroid1), for: UIControl.Event.touchUpInside) self.view!.addSubview(buttonNumber1) // Asteroid 2 buttonNumber2.setImage(UIImage(named: "asGreen"), for: .normal) buttonNumber2.frame = CGRect(x: Int(frame.width)/2 + 50, y: Int(screenHeight * 0.25), width: 100, height: 100) buttonNumber2.layer.cornerRadius = 20 buttonNumber2.layer.borderWidth = 2 buttonNumber2.addTarget(self, action: #selector(asteroid2), for: UIControl.Event.touchUpInside) self.view!.addSubview(buttonNumber2) // Asteroid 3 buttonNumber3.setImage(UIImage(named: "asBlue"), for: .normal) buttonNumber3.frame = CGRect(x: Int(frame.width)/2 - 150, y: Int(screenHeight * 0.5), width: 100, height: 100) buttonNumber3.layer.cornerRadius = 20 buttonNumber3.layer.borderWidth = 2 buttonNumber3.addTarget(self, action: #selector(asteroid3), for: UIControl.Event.touchUpInside) self.view!.addSubview(buttonNumber3) // Asteroid 4 buttonNumber4.setImage(UIImage(named: "asRed"), for: .normal) buttonNumber4.frame = CGRect(x: Int(frame.width)/2 + 50, y: Int(screenHeight * 0.5), width: 100, height: 100) buttonNumber4.layer.cornerRadius = 20 buttonNumber4.layer.borderWidth = 2 buttonNumber4.addTarget(self, action: #selector(asteroid4), for: UIControl.Event.touchUpInside) self.view!.addSubview(buttonNumber4) // Asteroid 5 buttonNumber5.setImage(UIImage(named: "asPurple"), for: .normal) buttonNumber5.frame = CGRect(x: Int(frame.width)/2 - 150, y: Int(screenHeight * 0.75), width: 100, height: 100) buttonNumber5.layer.cornerRadius = 20 buttonNumber5.layer.borderWidth = 2 buttonNumber5.addTarget(self, action: #selector(asteroid5), for: UIControl.Event.touchUpInside) self.view!.addSubview(buttonNumber5) // Asteroid 6 buttonNumber6.setImage(UIImage(named: "asMix"), for: .normal) buttonNumber6.frame = CGRect(x: Int(frame.width)/2 + 50, y: Int(screenHeight * 0.75), width: 100, height: 100) buttonNumber6.layer.cornerRadius = 20 buttonNumber6.layer.borderWidth = 2 buttonNumber6.addTarget(self, action: #selector(asteroid6), for: UIControl.Event.touchUpInside) self.view!.addSubview(buttonNumber6) } @objc func backbuttonRun(sender: UIButton!) { removeAllActions() removeAllChildren() let nextScene = MenuScene(size: scene!.size) let transition = SKTransition.fade(withDuration: 0.0) nextScene.scaleMode = .aspectFill scene?.view?.presentScene(nextScene,transition: transition) } //asteroid 1 @objc func asteroid1(sender: UIButton!) { asteroid = "asteroid1" UserDefaults.standard.set(asteroid,forKey: "texture") } //asteroid Green @objc func asteroid2(sender: UIButton!) { if greenSkin == false { if collectedStars >= 50 { asteroid = "asteroid2" UserDefaults.standard.set(asteroid,forKey: "texture") collectedStars = collectedStars - 50 UserDefaults.standard.setValue(collectedStars, forKey: "starcollection") greenSkin = true UserDefaults.standard.set(true, forKey: "green") greenLabel.removeFromParent() // Set the user's achievement to complete once purchased let achievement = GKAchievement(identifier: "GreenAsteroid") achievement.percentComplete = 100 achievement.showsCompletionBanner = true GKAchievement.report([achievement]) { error in guard error == nil else { print(error?.localizedDescription ?? "") return } print("Achievement Blue Asteroid") } } else { showAlert(withTitle: "\(greenTitle)!", message: "\(greenUnlockable)") } } else { asteroid = "asteroid2" UserDefaults.standard.set(asteroid,forKey: "texture") } } //asteroid Blue @objc func asteroid3(sender: UIButton!) { if blueSkin == false { if collectedStars >= 100 { asteroid = "asteroid3" UserDefaults.standard.set(asteroid,forKey: "texture") collectedStars = collectedStars - 100 UserDefaults.standard.setValue(collectedStars, forKey: "starcollection") blueSkin = true UserDefaults.standard.set(true, forKey: "blue") blueLabel.removeFromParent() // Set the user's achievement to complete once purchased let achievement = GKAchievement(identifier: "BlueAsteroid") achievement.percentComplete = 100 achievement.showsCompletionBanner = true GKAchievement.report([achievement]) { error in guard error == nil else { print(error?.localizedDescription ?? "") return } print("Achievement Blue Asteroid") } } else { showAlert(withTitle: "\(blueTitle)!", message: "\(blueUnlockable)") } } else { asteroid = "asteroid3" UserDefaults.standard.set(asteroid,forKey: "texture") } } //asteroid Red @objc func asteroid4(sender: UIButton!) { if redSkin == false { if collectedStars >= 150 { asteroid = "asteroid4" UserDefaults.standard.set(asteroid,forKey: "texture") collectedStars = collectedStars - 150 UserDefaults.standard.setValue(collectedStars, forKey: "starcollection") redSkin = true UserDefaults.standard.set(true, forKey: "red") redLabel.removeFromParent() // Set the user's achievement to complete once purchased let achievement = GKAchievement(identifier: "RedAsteroid") achievement.percentComplete = 100 achievement.showsCompletionBanner = true GKAchievement.report([achievement]) { error in guard error == nil else { print(error?.localizedDescription ?? "") return } print("Achievement Red Asteroid") } } else { showAlert(withTitle: "\(redTitle)!", message: "\(redUnlockable)") } } else { asteroid = "asteroid4" UserDefaults.standard.set(asteroid,forKey: "texture") } } //asteroid Purple @objc func asteroid5(sender: UIButton!) { if purpleSkin == false { if collectedStars >= 200 { asteroid = "asteroid5" UserDefaults.standard.set(asteroid,forKey: "texture") collectedStars = collectedStars - 200 UserDefaults.standard.setValue(collectedStars, forKey: "starcollection") purpleSkin = true UserDefaults.standard.set(true, forKey: "purple") purpleLabel.removeFromParent() // Set the user's achievement to complete once purchased let achievement = GKAchievement(identifier: "PurpleAsteroid") achievement.percentComplete = 100 achievement.showsCompletionBanner = true GKAchievement.report([achievement]) { error in guard error == nil else { print(error?.localizedDescription ?? "") return } print("Achievement Purple Asteroid") } } else { showAlert(withTitle: "\(purpleTitle)!", message: "\(purpleUnlockable)") } } else { asteroid = "asteroid5" UserDefaults.standard.set(asteroid,forKey: "texture") } } //asteroid Special @objc func asteroid6(sender: UIButton!) { if mixSkin == false { if collectedStars >= 250 { asteroid = "asteroid6" UserDefaults.standard.set(asteroid,forKey: "texture") collectedStars = collectedStars - 250 UserDefaults.standard.setValue(collectedStars, forKey: "starcollection") mixSkin = true UserDefaults.standard.set(true, forKey: "mix") mixLabel.removeFromParent() // Set the user's achievement to complete once purchased let achievement = GKAchievement(identifier: "SpecialAsteroid") achievement.percentComplete = 100 achievement.showsCompletionBanner = true GKAchievement.report([achievement]) { error in guard error == nil else { print(error?.localizedDescription ?? "") return } print("Achievement Special Asteroid") } } else { showAlert(withTitle: "\(specialTitle)!", message: "\(specialUnlockable)") } } else { asteroid = "asteroid6" UserDefaults.standard.set(asteroid,forKey: "texture") } } @objc func videoAdPushed() { NotificationCenter.default.post(name: .showVideoRewardAd, object: nil) } //Rewarded video func rewardedAdsButtonfunc(){ rewardedAdsButton.frame = CGRect (x: Int(screenWidth/2 - 150), y:Int(screenHeight * 0.15), width: 300, height: 45) let rewardedTitle = NSLocalizedString("rewardAd", comment: "My comment") rewardedAdsButton.setTitle(rewardedTitle, for: UIControl.State.normal) rewardedAdsButton.setTitleColor(UIColor.white, for: .normal) rewardedAdsButton.backgroundColor = customGreen rewardedAdsButton.layer.cornerRadius = 10 rewardedAdsButton.layer.borderWidth = 1 rewardedAdsButton.layer.borderColor=UIColor.white.cgColor rewardedAdsButton.addTarget(self, action: #selector(videoAdPushed), for: UIControl.Event.touchUpInside) rewardedAdsButton.titleLabel!.font = UIFont(name: "Press Start 2P", size: 15) rewardedAdsButton.titleLabel!.textAlignment = NSTextAlignment.center self.view!.addSubview(rewardedAdsButton) } }
import Css import CssReset import CssTestSupport import Prelude import XCTest import SnapshotTesting class ResetTests: XCTestCase { func testResetPretty() async { await assertSnapshot(matching: reset, as: .css) } func testResetCompact() async { await assertSnapshot(matching: reset, as: .css(.compact)) } }
//: [Previous](@previous) import Foundation // Enumerations enum MLSTeam { case montreal case toronto case newYork case columbus case losAngeles case seattle } let theTeam = MLSTeam.montreal // Pattern matching switch theTeam { case .montreal: print("Montreal Impact") case .toronto: print("Toronto FC") case .newYork: print("Newyork Redbulls") case .columbus: print("Columbus Crew") case .losAngeles: print("LA Galaxy") case .seattle: print("Seattle Sounders") } // Algebraic data types enum NHLTeam { case canadiens, senators, rangers, penguins, blackHawks, capitals } enum Team { case hockey(NHLTeam) case soccer(MLSTeam) } //struct HockeyAndSoccerTeams { // var hockey: NHLTeam // var soccer: MLSTeam //} // product type enum HockeyAndSoccerTeams { case value(hockey: NHLTeam, soccer: MLSTeam) } //: [Next](@next)
// // Episode.swift // HelloCast // // Created by Johnson Osei Yeboah on 28/01/2021. // struct Episode { let name:String? let description:String let pubDate:String }
// // HelpViewController.swift // Note Master 9000 // // Created by Maciej Eichler on 28/03/16. // Copyright © 2016 Mattijah. All rights reserved. // import UIKit class TutorialViewController: UIViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource { // MARK: Model var parentVC: LessonViewController? var lesson: TutorialLesson? { didSet { if lesson != nil { createPageViewController() setupPageControl() } } } private var pageViewController: UIPageViewController? // MARK: Constants private struct Constants { static let PageControllerIdentifier = "PageController" static let PageItemControllerIdentifier = "LessonPageView" static let LastPageControllerIdentifier = "LastPageView" } // MARK: - ViewController lifecycle override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = ColorPalette.Clouds setupPageControl() } // MARK: PageViewController private func createPageViewController() { let pageController = self.storyboard!.instantiateViewController(withIdentifier: Constants.PageControllerIdentifier) as! UIPageViewController pageController.dataSource = self if lesson!.pages.count > 0 { let firstController = getTutorialPageController(0)! let startingViewControllers: NSArray = [firstController] pageController.setViewControllers(startingViewControllers as? [UIViewController], direction: .forward, animated: true, completion: nil) } pageViewController = pageController addChildViewController(pageViewController!) self.view.addSubview(pageViewController!.view) pageViewController!.didMove(toParentViewController: self) } private func setupPageControl() { let appearance = UIPageControl.appearance() appearance.pageIndicatorTintColor = ColorPalette.Asbestos appearance.currentPageIndicatorTintColor = ColorPalette.MidnightBlue appearance.backgroundColor = ColorPalette.Clouds } // MARK: PageItemController private func getTutorialPageController(_ itemIndex: Int) -> TutorialPageController? { if itemIndex < lesson!.pages.count { let pageItemController = self.storyboard!.instantiateViewController(withIdentifier: Constants.PageItemControllerIdentifier) as! TutorialPageController pageItemController.itemIndex = itemIndex pageItemController.content = lesson!.pages[itemIndex] return pageItemController } else { return nil } } private func getLastPageController(_ itemIndex: Int) -> TutorialEndViewController? { if itemIndex == lesson!.pages.count { let pageItemController = self.storyboard!.instantiateViewController(withIdentifier: Constants.LastPageControllerIdentifier) as! TutorialEndViewController pageItemController.parentVC = parentVC return pageItemController } else { return nil } } // MARK: PageViewControllerDelegate func presentationCount(for pageViewController: UIPageViewController) -> Int { return lesson!.pages.count+1 } func presentationIndex(for pageViewController: UIPageViewController) -> Int { if let firstViewController = pageViewController.viewControllers?.first as? TutorialPageController { return firstViewController.itemIndex } else if let firstViewController = pageViewController.viewControllers?.first as? TutorialEndViewController { return firstViewController.itemIndex } else { return 0 } } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { if let itemController = viewController as? TutorialPageController { if itemController.itemIndex > 0 { return getTutorialPageController(itemController.itemIndex-1) } } else if let itemController = viewController as? TutorialEndViewController { return getTutorialPageController(itemController.itemIndex-1) } return nil } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { if let itemController = viewController as? TutorialPageController { if itemController.itemIndex < lesson!.pages.count-1 { return getTutorialPageController(itemController.itemIndex+1) } else { return getLastPageController(itemController.itemIndex+1) } } else if let _ = viewController as? TutorialEndViewController { return nil } return nil } /* // 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. } */ }
// // TrackCellTableView.swift // TrackListSongs // // Created by Larisa on 11.09.2021. // import UIKit class TrackTableViewCell: UITableViewCell { var viewModel: TrackCellViewModelProtocol! { didSet { var content = defaultContentConfiguration() content.text = viewModel.nameSong content.secondaryText = viewModel.artist content.image = UIImage(named: viewModel.image) content.imageProperties.cornerRadius = 100 / 2 contentConfiguration = content } } }
// // StringResource.swift // Resource // // Created by Justin Jia on 11/6/16. // Copyright © 2016 TintPoint. MIT license. // /// A protocol that describes an item that can represent a string. public protocol StringDescribing { /// The `String` that represents the content of the string. var content: String { get } } /// A struct that describes an item that can represent a string. public struct StringDescription: StringDescribing { /// The `String` that represents the content of the string. public let content: String public init(content: String) { self.content = content } } public extension Resource { /// Returns a `String` that is represented by the item that conforms to `StringDescribing`. /// - Parameter describing: An item that conforms to `StringDescribing`. /// - Returns: A represented string. static func of(_ describing: StringDescribing) -> String { return describing.content } }
// // Data.swift // App // import Vapor class Data { static let shared: Data = { return Data() }() private var results: [House] = [] func saveAndDiff(_ elements: [House]) -> [House] { print("\(#function)") guard results.isEmpty == false, elements.isEmpty == false else { results += elements return [] } let diff = elements.filter { results.contains($0) == false } print("diff \(diff.count)") guard diff.isEmpty == false else { return [] } results += diff return diff } }
// // UIViewController.swift // NYC_JOBS_DATA_FINAL // // Created by Jonathan Cravotta on 5/28/18. // Copyright © 2018 Jonathan Cravotta. All rights reserved. // import Foundation import UIKit extension UIViewController { func setUpDefaultNavgationStyle() { //navigationController?.navigationBar.prefersLargeTitles = true navigationController?.navigationBar.backgroundColor = .white navigationController?.navigationBar.barTintColor = UIColor.white navigationController?.navigationBar.isTranslucent = false } }
import Foundation extension Logger { enum Failure { case decoding (model: Decodable.Type, error: Swift.Error, path: String) } }
// // Statistic.swift // GV24 // // Created by HuyNguyen on 6/22/17. // Copyright © 2017 admin. All rights reserved. // import Foundation import SwiftyJSON class Statistic: AppModel { var totalPrice:Int = 0 var tasks = [TaskStatistic]() override init() { super.init() } override init(json: JSON) { super.init(json: json) self.totalPrice = json["totalPrice"].int ?? 0 if let task = json["task"].array { for info in task { self.tasks.append(TaskStatistic(json: info)) } } } } enum TaskType: String { case completed = "000000000000000000000005" case inProcess = "000000000000000000000004" case awaiting = "000000000000000000000003" case unknown } class TaskStatistic: AppModel { var id:TaskType = .unknown var count:Int = 0 override init() { super.init() } override init(json: JSON) { super.init(json: json) if let id = json["_id"].string, let type = TaskType(rawValue: id) { self.id = type } self.count = json["count"].int ?? 0 } }
// // UserProperty.swift // Semenova Gym // // Created by user on 02.03.2021. // import Foundation var weight: String? var height: String?
import Combine import Nimble import Quick import Testable extension TabViewController { func add(numberOfTabs: Int) { (1...numberOfTabs).forEach { _ in addChild(Init(.init()) { $0.view = .init() }) } } } class TabViewControllerSpec: QuickSpec { override func spec() { describe(TabViewController.self) { var subject: TabViewController! beforeEach { subject = Init(.init()) { $0?.add(numberOfTabs: 4) } } context("state changes") { var mockNotifier: MockStateNotifier! beforeEach { mockNotifier = .createAndInject() expect(subject.view).notTo(beNil()) subject.selectedTabViewItemIndex = 3 } it("should update to corresponding tab") { let tabForState: [Int: State] = [ 0: .login, 1: .busy(value: .init()), 2: .complete ] tabForState.forEach { (tab: Int, state: State) in mockNotifier.send(state: state) expect(subject.selectedTabViewItemIndex) == tab } } } } } }
// // DataService.swift // TacoPOP // // Created by Steven Sherry on 3/20/17. // Copyright © 2017 Affinity for Apps. All rights reserved. // import Foundation
// // TrackAutocompleteClickRequestBuilder.swift // Constructor.io // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import Foundation class TrackAutocompleteClickRequestBuilder: RequestBuilder { private var itemName = "" private var hasSectionName = false init(tracker: CIOAutocompleteClickTracker, autocompleteKey: String) { super.init(autocompleteKey: autocompleteKey) set(itemName: tracker.clickedItemName) set(originalQuery: tracker.searchTerm) set(autocompleteSection: tracker.sectionName) } func set(itemName: String) { self.itemName = itemName } func set(originalQuery: String) { queryItems.append(URLQueryItem(name: Constants.TrackAutocompleteResultClicked.originalQuery, value: originalQuery)) } func set(autocompleteSection: String?) { guard let sectionName = autocompleteSection else { return } self.hasSectionName = true queryItems.append(URLQueryItem(name: Constants.TrackAutocomplete.autocompleteSection, value: sectionName)) } override func getURLString() -> String { let type = hasSectionName ? Constants.TrackAutocompleteResultClicked.selectType : Constants.TrackAutocompleteResultClicked.searchType return String(format: Constants.Track.trackStringFormat, Constants.Track.baseURLString, Constants.TrackAutocomplete.pathString, itemName.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!, type) } override func addAdditionalQueryItems() { addTriggerQueryItem() addDateQueryItem() } private func addTriggerQueryItem() { queryItems.append(URLQueryItem(name: Constants.TrackAutocompleteResultClicked.trigger, value: Constants.TrackAutocompleteResultClicked.triggerType)) } private func addDateQueryItem() { queryItems.append(URLQueryItem(name: Constants.TrackAutocompleteResultClicked.dateTime, value: String(Date().millisecondsSince1970))) } }
// // ConditionalContent.swift // SwiftUI_DSL_explained // // Created by Geri Borbás on 2020. 06. 27.. // // swiftlint:disable syntactic_sugar import SwiftUI struct ConditionalContent_If_standard: View { var showHand = true var body: some View { VStack { Text("Hello") Text("world!").bold() if showHand { Text("👋") } } } } struct ConditionalContent_If_article: View { var showHand = true var body: VStack<TupleView<(Text, Text, Optional<Text>)>> { // Views. let helloText: Text = Text("Hello") let worldText: Text = Text("world!").bold() let optionalHandText: Optional<Text> = showHand ? .some(Text("👋")) : .none // Tuple and vertical stack. let tupleView = TupleView((helloText, worldText, optionalHandText)) return VStack(content: { return tupleView }) } } struct ConditionalContent_If_else_standard: View { var useImage = true var body: some View { VStack { Text("Hello") if useImage { Image(systemName: "globe") } else { Text("world!").bold() } } } } struct ConditionalContent_If_else_article: View { var useImage = true var body: VStack<TupleView<(Text, _ConditionalContent<Text, Image>)>> { // Views. let helloText: Text = Text("Hello") let worldText: Text = Text("world!").bold() let worldImage: Image = Image(systemName: "globe") // Create content for each branch. let trueContent: _ConditionalContent<Text, Image> = ViewBuilder.buildEither(first: worldText) // ConditionalContent<Text, Image>(storage: .trueContent(worldText)) let falseContent: _ConditionalContent<Text, Image> = ViewBuilder.buildEither(second: worldImage) // Equivalent to _ConditionalContent<Text, Image>(storage: .falseContent(worldImage)) // Pick either conditional content at runtime (with a static type designating both). let worldTextOrWorldImage: _ConditionalContent<Text, Image> = useImage ? trueContent : falseContent // Tuple and vertical stack. let tupleView = TupleView((helloText, worldTextOrWorldImage)) return VStack(content: { return tupleView }) } } enum `Type`: String, CaseIterable { case text, image, color, divider, spacer } struct ConditionalContent_Switch_standard: View { var type: `Type` = .image var body: some View { Group { switch type { case .text: Text("Text") case .image: Image(systemName: "photo") case .color: Color.red case .divider: Divider() case .spacer: Spacer() } } } } typealias SwitchGroupType = Group< _ConditionalContent< _ConditionalContent< _ConditionalContent<Text, Image>, _ConditionalContent<Color, Divider> >, Spacer > > struct ConditionalContent_Switch_Switch_standard: View { var type: `Type` = .image var body: some View { let group: Group<_ConditionalContent<_ConditionalContent<_ConditionalContent<Text, Image>, _ConditionalContent<Color, Divider>>, Spacer>> = Group { switch type { case .text: Text("Text") case .image: Image(systemName: "photo") case .color: Color.red case .divider: Divider() case .spacer: Spacer() } } return group } } struct ConditionalContent_Switch_If_else_standard: View { var type: `Type` = .image var body: some View { let group: SwitchGroupType = Group { if type == .text { Text("Text") } else if type == .image { Image(systemName: "photo") } else if type == .color { Color.red } else if type == .divider { Divider() } else { // if type == .spacer Spacer() } } return group } } struct ConditionalContent_Switch_dissected_1: View { var type: `Type` = .image var body: some View { let textOrImage: _ConditionalContent<Text, Image> = type == .text ? ViewBuilder.buildEither(first: Text("Text")) : ViewBuilder.buildEither(second: Image(systemName: "photo")) let colorOrDivider: _ConditionalContent<Color, Divider> = type == .color ? ViewBuilder.buildEither(first: Color.red) : ViewBuilder.buildEither(second: Divider()) let textOrImageOrColorOrDivider: _ConditionalContent<_ConditionalContent<Text, Image>, _ConditionalContent<Color, Divider>> = type == .text || type == .image ? ViewBuilder.buildEither(first: textOrImage) : ViewBuilder.buildEither(second: colorOrDivider) let textOrImageOrColorOrDividerOrSpacer: _ConditionalContent<_ConditionalContent<_ConditionalContent<Text, Image>, _ConditionalContent<Color, Divider>>, Spacer> = type == .text || type == .image || type == .color || type == .divider ? ViewBuilder.buildEither(first: textOrImageOrColorOrDivider) : ViewBuilder.buildEither(second: Spacer()) let group: SwitchGroupType = Group(content: { return textOrImageOrColorOrDividerOrSpacer }) return group } } struct ConditionalContent_Switch_dissected_2: View { var type: `Type` = .image var body: some View { let group: SwitchGroupType = Group(content: { return type == .text || type == .image || type == .color || type == .divider ? ViewBuilder.buildEither( first: ( type == .text || type == .image ? ViewBuilder.buildEither( first: ( type == .text ? ViewBuilder.buildEither(first: Text("Text")) : ViewBuilder.buildEither(second: Image(systemName: "photo")) ) ) : ViewBuilder.buildEither( second: ( type == .color ? ViewBuilder.buildEither(first: Color.red) : ViewBuilder.buildEither(second: Divider()) ) ) ) ) : ViewBuilder.buildEither( second: Spacer() ) }) return group } } struct ConditionalContent_Switch_dissected_3: View { var type: `Type` = .image var body: Group< _ConditionalContent< _ConditionalContent< _ConditionalContent<Text, Image>, _ConditionalContent<Color, Divider> >, Spacer > > { return Group(content: { switch type { case .text: return ViewBuilder.buildEither( first: ViewBuilder.buildEither( first: ViewBuilder.buildEither( first: Text("Text") ) ) ) case .image: return ViewBuilder.buildEither( first: ViewBuilder.buildEither( first: ViewBuilder.buildEither( second: Image(systemName: "photo") ) ) ) case .color: return ViewBuilder.buildEither( first: ViewBuilder.buildEither( second: ViewBuilder.buildEither( first: Color.red ) ) ) case .divider: return ViewBuilder.buildEither( first: ViewBuilder.buildEither( second: ViewBuilder.buildEither( second: Divider() ) ) ) case .spacer: return ViewBuilder.buildEither( second: Spacer() ) } }) } } #if _CONDITIONAL_CONTENT_WERE_PUBLIC struct ConditionalContent_Switch_dissected_4: View { var type: `Type` = .image var body: Group< _ConditionalContent< _ConditionalContent< _ConditionalContent<Text, Image>, _ConditionalContent<Color, Divider> >, Spacer > > { return Group(content: { switch type { case .text: return _ConditionalContent(storage: .trueContent( _ConditionalContent(storage: .trueContent( _ConditionalContent(storage: .trueContent( Text("Text") )) )) )) case .image: return _ConditionalContent(storage: .trueContent( _ConditionalContent(storage: .trueContent( _ConditionalContent(storage: .falseContent( Image(systemName: "photo") )) )) )) case .color: return _ConditionalContent(storage: .trueContent( _ConditionalContent(storage: .falseContent( _ConditionalContent(storage: .trueContent( Color.red )) )) )) case .divider: return _ConditionalContent(storage: .trueContent( _ConditionalContent(storage: .falseContent( _ConditionalContent(storage: .falseContent( Divider() )) )) )) case .spacer: return _ConditionalContent(storage: .falseContent( Spacer() )) } }) } } #endif struct ConditionalContent_Switch_interactive: View { @State var type: `Type` = .image var typePicker: some View { Picker("Type", selection: $type) { ForEach(`Type`.allCases, id: \.self) { eachType in Text(eachType.rawValue.capitalized) } } .pickerStyle(SegmentedPickerStyle()) } var body: some View { let textOrImage: _ConditionalContent<Text, Image> = type == .text ? ViewBuilder.buildEither(first: Text("Text")) : ViewBuilder.buildEither(second: Image(systemName: "photo")) let colorOrDivider: _ConditionalContent<Color, Divider> = type == .color ? ViewBuilder.buildEither(first: Color.red) : ViewBuilder.buildEither(second: Divider()) let textOrImageOrColorOrDivider: _ConditionalContent<_ConditionalContent<Text, Image>, _ConditionalContent<Color, Divider>> = type == .text || type == .image ? ViewBuilder.buildEither(first: textOrImage) : ViewBuilder.buildEither(second: colorOrDivider) let textOrImageOrColorOrDividerOrSpacer: _ConditionalContent<_ConditionalContent<_ConditionalContent<Text, Image>, _ConditionalContent<Color, Divider>>, Spacer> = type == .text || type == .image || type == .color || type == .divider ? ViewBuilder.buildEither(first: textOrImageOrColorOrDivider) : ViewBuilder.buildEither(second: Spacer()) return VStack { typePicker textOrImageOrColorOrDividerOrSpacer } } } // MARK: - Previews #if DEBUG struct ConditionalContent_Previews: PreviewProvider { static var previews: some View { Group { ConditionalContent_If_standard() .previewDisplayName("ConditionalContent_If_standard") ConditionalContent_If_article() .previewDisplayName("ConditionalContent_If_standard") ConditionalContent_If_else_standard() .previewDisplayName("ConditionalContent_If_else_standard") ConditionalContent_If_else_article() .previewDisplayName("ConditionalContent_If_else_article") ConditionalContent_Switch_standard() .previewDisplayName("ConditionalContent_Switch_standard") ConditionalContent_Switch_Switch_standard() .previewDisplayName("ConditionalContent_Switch_Switch_standard") ConditionalContent_Switch_If_else_standard() .previewDisplayName("ConditionalContent_Switch_If_else_standard") ConditionalContent_Switch_dissected_1() .previewDisplayName("ConditionalContent_Switch_dissected_1") ConditionalContent_Switch_dissected_2() .previewDisplayName("ConditionalContent_Switch_dissected_2") ConditionalContent_Switch_dissected_3() .previewDisplayName("ConditionalContent_Switch_dissected_3") // Wow, 11th child view! 😲 ConditionalContent_Switch_interactive() .previewDisplayName("ConditionalContent_Switch_interactive") } } } #endif
// // DownGestureTransition.swift // BJTransition // // Created by 유병재 on 2019/07/11. // import UIKit class DownGestureTransition: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let fromViewController = transitionContext.viewController(forKey: .from), let toViewController = transitionContext.viewController(forKey: .to) else { return } let containerView = transitionContext.containerView containerView.backgroundColor = UIColor.white if let tabBarController = toViewController.tabBarController { containerView.insertSubview(tabBarController.tabBar, belowSubview: fromViewController.view) } containerView.insertSubview(toViewController.view, belowSubview: fromViewController.view) let screenBounds = UIScreen.main.bounds let bottomLeftCorner = CGPoint(x: 0, y: screenBounds.height) let finalFrame = CGRect(origin: bottomLeftCorner, size: screenBounds.size) let dimView = UIView(frame: CGRect(x: 0,y: 0, width: toViewController.view.frame.width, height: toViewController.view.frame.height)) dimView.backgroundColor = UIColor.black dimView.alpha = 0.5 toViewController.view.addSubview(dimView) UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { dimView.alpha = 0 fromViewController.view.frame = finalFrame }) { (_) in dimView.removeFromSuperview() if let tabBarController = toViewController.tabBarController { tabBarController.view.addSubview(tabBarController.tabBar) } transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } } class DownTransitionInteractor: UIPercentDrivenInteractiveTransition { var hasStarted = false var shouldFinish = false }
// // ViewController.swift // MiviTest // // Created by RajkumarThyadi on 5/6/18. // Copyright © 2018 RajkumarThyadi. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var txtEmail : UITextField! @IBOutlet var txtPassword : UITextField! @IBOutlet var btnLogIn : UIButton! @IBOutlet var txtBGView : UIView! override func viewDidLoad() { super.viewDidLoad() self.viewSetup() // Do any additional setup after loading the view, typically from a nib. } func viewSetup(){ self.btnLogIn.layer.cornerRadius = self.btnLogIn.frame.height/2 self.btnLogIn.titleLabel?.textAlignment = NSTextAlignment.center self.txtBGView.layer.cornerRadius = 5.0 } @IBAction func logInButtonPressed(sender: UIButton) { self.view.endEditing(true) var valid : Bool = true if(txtEmail.text!.characters.count <= 0 ) { valid = false self.showAlert(title: "Error", message: "Please input your email address", tag: 0) } else if(!(txtEmail.text!.isValidEmail)){ valid = false self.showAlert(title: "Error", message: "Invalid email address format", tag: 0) } else if( txtPassword.text!.length < 5) { valid = false self.showAlert(title: "Error", message: "Invalid password", tag: 0) } if(valid == true) { if let customerDetails = self.getDatafromJson(){ if let val = customerDetails.data["attributes"] as? NSDictionary { if( ((val.object(forKey: "email-address") ?? "") as! String) == txtEmail.text!){ let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "CustomerViewControllerId") as! CustomerViewController nextVC.customerData = customerDetails self.present(nextVC, animated: true, completion: nil) } else{ self.showAlert(title: "Error", message: "Invalid email address entered", tag: 0) } } } } } func getDatafromJson() -> (data:NSDictionary,included:NSArray)? { guard let path = Bundle.main.path(forResource: "collection", ofType: "json") else { return nil } do { // do stuff let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe) let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let data = jsonResult["data"] as? NSDictionary, let included = jsonResult["included"] as? [NSDictionary]{ return (data,included as NSArray) } else{ return nil } } catch { // handle error return nil } } //MARK:================ Alertview =========================================================== func showAlert(title : String, message :String , tag: NSInteger) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } //MARK:================ TextField KeyBoard Handling =========================================================== func textFieldShouldReturn(textField: UITextField) -> Bool { //delegate method switch textField { case self.txtEmail : self.txtPassword.becomeFirstResponder() break default: textField.resignFirstResponder() } return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // UIViewController+Extension.swift // KarrotRouter // // Created by Geektree0101 on 2020/07/03. // Copyright © 2020 Geektree0101. All rights reserved. // import UIKit private var drainableKey: String = "darainable" extension UIViewController { var drainable: DataDrainable? { get { return objc_getAssociatedObject(self, &drainableKey) as? DataDrainable } set { objc_setAssociatedObject(self, &drainableKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } func emit(context: DataDrainContext?) { guard let context = context else { return } self.behindViewControllers.forEach({ vc in guard let drainable = vc.drainable else { return } drainable.drain(context: context) }) } } extension UIViewController { fileprivate var behindViewControllers: [UIViewController] { return findBehindViewControllers(from: self, child: []).filter({ $0 != self }) } private func findBehindViewControllers(from viewController: UIViewController?, child: [UIViewController]) -> [UIViewController] { if let nav = viewController?.navigationController { return self.findBehindViewControllers( from: nav.presentingViewController, child: Array(nav.children.reversed()) + Array(child.reversed()) ) } else if let nav = viewController as? UINavigationController { return self.findBehindViewControllers( from: nav.presentingViewController, child: Array(nav.children.reversed()) + Array(child.reversed()) ) } else { return child } } }
// // CoordinateReferenceSystem.swift // Routing // // Created by Dave Hardiman on 01/03/2016. // Copyright © 2016 Ordnance Survey. All rights reserved. // import Foundation /** Available coordinate reference systems */ public enum CoordinateReferenceSystem: String { case BNG = "bng" case EPSG_27700 = "EPSG:27700" case WGS_84 = "wgs84" case EPSG_4326 = "EPSG:4326" case EPSG_3857 = "EPSG:3857" case EPSG_4258 = "EPSG:4258" }
// // PatientTreatmentStage.swift // AiNi // // Created by Julia Silveira de Souza on 13/05/21. // import SwiftUI struct PatientTreatmentCard: View { @State var Treatment: String @State var StageofTreatment: String var body: some View { ZStack { CardsGradientStyle() VStack (alignment: .leading) { Text(Treatment) .font(.title) .foregroundColor(.white) Text(StageofTreatment) .foregroundColor(.white) HStack (spacing: 2) { HStack (alignment: .center, spacing: -5) { } Spacer() } } .padding() } .frame(height: 133, alignment: .center) .clipShape(RoundedRectangle(cornerRadius: 22)) } } struct PatientTreatmentCard_Previews: PreviewProvider { static var previews: some View { PatientTreatmentCard(Treatment: "", StageofTreatment: "") .preferredColorScheme(.dark) .previewLayout(.fixed(width: 349, height: 153)) } }
// // ViewController.swift // URLSession // // Created by Bhavneet Singh on 12/12/17. // Copyright © 2017 Bhavneet Singh. All rights reserved. // import UIKit class MainVC: UIViewController { let httpMethods = [HTTPMethod.get, HTTPMethod.put, HTTPMethod.delete, HTTPMethod.post] @IBOutlet weak var mainCollectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.initialSetup() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func initialSetup() { self.mainCollectionView.delegate = self self.mainCollectionView.dataSource = self } } extension MainVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return httpMethods.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ButtonCollectionCell", for: indexPath) as? ButtonCollectionCell else { fatalError("Cell Not Found") } cell.button.setTitle(self.httpMethods[indexPath.item].rawValue, for: .normal) switch self.httpMethods[indexPath.item] { case .get: cell.button.addTarget(self, action: #selector(MainVC.get(_:)), for: .touchUpInside) case .put: cell.button.addTarget(self, action: #selector(MainVC.put(_:)), for: .touchUpInside) case .delete: cell.button.addTarget(self, action: #selector(MainVC.deleteMethod(_:)), for: .touchUpInside) case .post: cell.button.addTarget(self, action: #selector(MainVC.post(_:)), for: .touchUpInside) } return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let screenSize = UIScreen.main.bounds return CGSize(width: (screenSize.width/2)-30, height: 50) } } // FUNCTIONS extension MainVC { @objc private func get(_ btn: UIButton) { print(#function) WebServices.getPosts(parameter: JSONDictionary(), success: { (json) in }) { (error) in } } @objc private func put(_ btn: UIButton) { print(#function) WebServices.putPost(parameter: JSONDictionary(), success: { (json) in }) { (error) in } } @objc private func deleteMethod(_ btn: UIButton) { print(#function) WebServices.deletePost(parameter: JSONDictionary(), success: { (json) in }) { (error) in } } @objc private func post(_ btn: UIButton) { print(#function) let params: JSONDictionary = ["name": "Bhavneet Singh", "number": "987654321"] WebServices.postPosts(parameter: params, success: { (json) in print(json) }) { (error) in } } } class ButtonCollectionCell: UICollectionViewCell { @IBOutlet weak var mainBackView: UIView! @IBOutlet weak var button: UIButton! override func awakeFromNib() { super.awakeFromNib() self.initialSetup() } private func initialSetup() { self.mainBackView.layer.cornerRadius = 5 } }
// // CustomAlertView.swift // OneNation // // Created by Shilpa on 07/11/17. // Copyright © 2017 Ashish Chauhan. All rights reserved. // import UIKit class CustomAlertView: UIView { //Create Topic @IBOutlet weak var viewPopup: UIView! @IBOutlet weak var viewGradient: AVView! @IBOutlet weak var lblProductName: UILabel! @IBOutlet weak var txtViewReply: UITextView! @IBOutlet weak var imgViewProduct: UIView! @IBOutlet weak var lbllQuestion: UILabel! @IBOutlet weak var btnCancel: UIButton! @IBOutlet weak var btnCreate: UIButton! @IBOutlet weak var centerYTopicCnst: NSLayoutConstraint! var handler : ((Any) -> Void)! override init(frame: CGRect) { super.init(frame: frame) } deinit { self.removeKeyboardNotifications() } // MARK: - Keyboard Notification Observers private func registerForKeyboardNotifications() { //Adding noti. on keyboard appearing NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } private func removeKeyboardNotifications() { //Removing notifies on keyboard appearing NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) } @objc func finishEditing() { self.endEditing(true) } @objc func keyboardWasShown(notification: NSNotification) { if let userInfo = notification.userInfo { if let keyboardSize: CGSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size { Threads.performTaskInMainQueue { self.centerYTopicCnst.constant = -100 self.updateConstraints() UIView.animate(withDuration: 0.2, delay: 0.0, options: .allowAnimatedContent, animations: { () -> Void in self.layoutIfNeeded() }, completion: nil) } } } } @objc func keyboardWillBeHidden(notification: NSNotification) { self.centerYTopicCnst.constant = 0 self.updateConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func loadView(productImage : String, productName : String = "", question: String = "", eventHandler: ((Any) -> Void)?) { registerForKeyboardNotifications() let arrView = Bundle.main.loadNibNamed("CustomAlert", owner: self, options: nil) let replyView = arrView![0] as! UIView replyView.frame = self.bounds addSubview(replyView) self.viewPopup.layer.borderWidth = 2.0 self.viewPopup.layer.borderColor = UIColor.gray.cgColor self.txtViewReply.layer.borderWidth = 1.0 self.txtViewReply.layer.borderColor = UIColor.gray.cgColor Threads.performTaskAfterDealy(0.05) { self.viewGradient.drawGradientWithRGB(startColor: UIColor.lightOrangeGradientColor, endColor: UIColor.darkOrangeGradientColor) } self.lblProductName.text = "Nokia Phone" // btnCancel.setTitle(firstBtnTitle.localizedString, for: .normal) // btnCreate.setTitle(secondBtnTitle.localizedString, for: .normal) // btnCreate.dropShadow(color: UIColor.lightGray, opacity: 3.0, offSet: CGSize(width: 10, height: 10) , radius: 5, scale: true) // btnCancel.dropShadow(color: UIColor.lightGray, opacity: 3.0, offSet: CGSize(width: 10, height: 10) , radius: 5, scale: true) // txtDiscussion.placeholder = ConstantTexts.enterDiscussionTopic.localizedString // txtDiscussion.addToolbarWithButtonTitled(title: ConstantTexts.done.localizedString, forTarget: self, selector: #selector(finishEditing)) // txtDiscussion.delegate = self // if Constant.isRightToLeftDirection { // txtDiscussion.textAlignment = .right // } else { // txtDiscussion.textAlignment = .left // } // imgUperDiscsn.image = UIImage(named: image.rawValue) // viewRound.roundCorners(borderWidth: 0, borderColor: UIColor.clear.cgColor, cornerRadius: viewRound.frame.size.width/2) handler = eventHandler } //MARK: - IBAction @IBAction func tapCreate(_ sender: UIButton) { self.endEditing(true) if (self.handler != nil) { // if txtDiscussion.text == "" { // TAAlert.showOkAlert(title: ConstantTexts.AppName.localizedString, message: ConstantTexts.enterTopicName.localizedString) // } else { // self.handler(["type" : AlertButtonType.create, "param" : ["topicName" : txtDiscussion.text ?? "", "shareAs" : shareAs]]) // } } } } extension CustomAlertView : UITextViewDelegate { func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { // if Constant.isRightToLeftDirection { // textView.textAlignment = .right // } else { // textView.textAlignment = .left // } return true } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if(text == "\n") { // textView.resignFirstResponder() // return false } let newLength = (textView.text?.count)! + text.count - range.length if textView == txtViewReply { if newLength > 60 { return false } } return true } } extension UIButton { func addShadow() { self.layer.shadowRadius = 4.0 self.layer.shadowOpacity = 3.0 self.layer.shadowColor = UIColor.lightGray.cgColor } }
// // IsPrimeModalView.swift // PrimeTimeAlt // // Created by Ilya Belenkiy on 10/29/19. // Copyright © 2019 Ilya Belenkiy. All rights reserved. // import SwiftUI class IsPrimeModelViewModel: ObservableObject { enum Action { case saveFavoritePrimeTapped case removeFavoritePrimeTapped case none } struct State { var count: Int var favoritePrimes: [Int] var countDescription: String var buttonInfo: (actionTitle: String, action: Action)? } @Published var state: State init(count: Int, favoritePrimes: [Int]) { state = State(count: count, favoritePrimes: favoritePrimes, countDescription: "", buttonInfo: nil) Self.reduce(state: &state, action: .none) } static func reduce(state: inout State, action: Action) -> Void { switch action { case .saveFavoritePrimeTapped: state.favoritePrimes.append(state.count) case .removeFavoritePrimeTapped: state.favoritePrimes.removeAll(where: { $0 == state.count }) case .none: break } let suffix = isPrime(state.count) ? " is prime 🎉" : " is not prime :(" state.countDescription = "\(state.count)\(suffix)" if isPrime(state.count) { if state.favoritePrimes.contains(state.count) { state.buttonInfo = ( actionTitle: "Remove from favorite primes", action: .removeFavoritePrimeTapped ) } else { state.buttonInfo = ( actionTitle: "Save to favorite primes", action: .saveFavoritePrimeTapped ) } } else { state.buttonInfo = nil } } } func isPrime(_ p: Int) -> Bool { if p <= 1 { return false } if p <= 3 { return true } for i in 2...Int(sqrtf(Float(p))) { if p % i == 0 { return false } } return true } struct IsPrimeModalView: View { @ObservedObject var model: IsPrimeModelViewModel var body: some View { VStack { Text(model.state.countDescription) model.state.buttonInfo.map { (text, action) in Button(text, action: { IsPrimeModelViewModel.reduce(state: &self.model.state, action: action) }) } } } } struct IsPrimeModalView_Previews: PreviewProvider { static let model = IsPrimeModelViewModel( count: 11, favoritePrimes: [] ) static var previews: some View { IsPrimeModalView(model: Self.model) } }
import Foundation func solution(_ cacheSize:Int, _ cities:[String]) -> Int { if cacheSize == 0{ return 5 * cities.count } var answer = 0 var cache:[String] = [] for i in cities{ let city = i.lowercased() if cache.contains(city){ answer += 1 cache.remove(at: cache.firstIndex(of: city)!) cache.append(city) }else{ answer += 5 if cache.count >= cacheSize{ cache.removeFirst() } cache.append(city) } } return answer }
// // AcronymsList.swift // Acronyms // // Created by Douglas Poveda on 28/04/21. // import SwiftUI struct AcronymsListView: View { private let titleSize: CGFloat = 25 private let mainSpacing: CGFloat = 8 @ObservedObject private var viewModel:AcronymSearchViewModel @State private var searchText = "" init(viewModel: AcronymSearchViewModel) { self.viewModel = viewModel } var body: some View { VStack(spacing: mainSpacing, content: { SearchBar(text: $searchText) Button("Search") { viewModel.getAcronyms(keyword: searchText) } if viewModel.acronyms.isEmpty { Text("Search something!") } else { List(viewModel.acronyms) { acronym in VStack(alignment: .leading) { Text(acronym.sf ?? "") .font(.system(size: titleSize)).fontWeight(.bold) ForEach(acronym.lfs ?? []) { meaning in MeaningView(meaning: meaning).padding(mainSpacing) } } }.gesture(DragGesture().onChanged { _ in UIApplication.shared.endEditing(true) }) } Spacer() }) } }
// // DemoTests.swift // DemoTests // // Created by Henrik Rostgaard on 07/02/16. // Copyright (c) 2016 35b.dk. All rights reserved. // import XCTest @testable import Demo class DemoTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testSearch() { let expectation = expectationWithDescription("Search for some result") FoursquareDataManager().loadFoursquareData("sushi", location: (55.765,12.497)) { (data, resultOk) in XCTAssertTrue(resultOk) XCTAssert(data.count > 0, "No data found") expectation.fulfill() } //wait until the expectation is fulfilled or timeout waitForExpectationsWithTimeout(5) { error in XCTAssertNil(error, "Oh, we got timeout") } } func testSearchNoResults() { let expectation = expectationWithDescription("Search with expectation to found 0 entries") FoursquareDataManager().loadFoursquareData("1234567890abcdefghijklmnopq", location: (55.765,12.497)) { (data, resultOk) in XCTAssertTrue(resultOk) XCTAssertEqual(data.count, 0, "Unexpected data found") expectation.fulfill() } // Loop until the expectation is fulfilled in onDone method waitForExpectationsWithTimeout(5) { error in XCTAssertNil(error, "Oh, we got timeout") } } func testSearchWithIlligalSearchString() { let expectation = expectationWithDescription("Search with illigal searchString, expect") FoursquareDataManager().loadFoursquareData("min sushi", location: (55.765,12.497)) { (data, resultOk) in XCTAssertFalse(resultOk) expectation.fulfill() } // Loop until the expectation is fulfilled in onDone method waitForExpectationsWithTimeout(5) { error in XCTAssertNil(error, "Oh, we got timeout") } } }
// // FavouritesView.swift // OrgTech // // Created by Maksym Balukhtin on 01.05.2020. // Copyright © 2020 Maksym Balukhtin. All rights reserved. // import UIKit class FavouritesView: BuildableView { //MARK: Subviews let tableView = UITableView() let emptyLabel = UILabel() override func addViews() { //add subviews into array [emptyLabel, tableView].forEach{addSubview($0)} } override func anchorViews() { tableView.fillSuperview() emptyLabel.fillSuperview() } override func configureViews() { [tableView, emptyLabel].forEach { $0.backgroundColor = .white } tableView.showsVerticalScrollIndicator = false tableView.showsHorizontalScrollIndicator = false tableView.bounces = true tableView.isHidden = true tableView.register(cell: FovouriteTableViewCell.self) emptyLabel.font = .systemFont(ofSize: 17.0) emptyLabel.numberOfLines = 0 emptyLabel.textAlignment = .center emptyLabel.textColor = .lightGray emptyLabel.text = AppDefaults.Strings.Label.cartFollowEmpty } }
// // Constants.swift // Chatter // import Foundation typealias CompletionHandler = (Bool) -> Void // URL Constants let baseUrl = "https://fierce-oasis-16295.herokuapp.com/v1/" let urlRegister = "\(baseUrl)account/register" let urlLogin = "\(baseUrl)account/login" let urlUserAdd = "\(baseUrl)user/add" let urlUserByEmail = "\(baseUrl)user/byEmail/" let urlGetChannels = "\(baseUrl)channel/" let urlGetMessages = "\(baseUrl)message/byChannel/" // Fonts let helveticaRegular = "HelveticaNeue-Regular" let helveticaBold = "HelveticaNeue-Bold" // Colors let purplePlaceholder = #colorLiteral(red: 0.2588235294, green: 0.3294117647, blue: 0.7254901961, alpha: 0.5) let redPlaceholder = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 0.5) // Text fields Placeholders enum Placeholders: String { case channelName = "name" case channelDescription = "description" case channelNameRequired = "name is required" case userName = "username" case userEmail = "email" case userPassword = "password" case userNameRequired = "username is required" case userEmailRequired = "email is required" case userPasswordRequired = "password is required" } // Segues names enum Segues: String { case toLogin case toCreateAccount case unwindToChannel case toAvatarPicker } // Cells identifiers enum Cell: String { case messageCell case channelCell case avatarCell } // User Defaults Keys enum UserDefaultsKeys: String { case tokenKey case loggedIn case userEmail } // Headers let header = [ "Content-Type": "application/json; charset=utf-8" ] let bearerHeader = [ "Authorization": "Bearer \(AuthenticationService.instance.authenticationToken)", "Content-Type": "application/json; charset=utf-8" ]
/*Copyright (c) 2016, Andrew Walz. Redistribution and use in source and binary forms, with or without modification,are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // MARK: IMPORT STATEMENTS import UIKit import AVFoundation import AVKit // MARK: VIDEO VIEW CONTROLLER - CLASS class VideoViewController: UIViewController { // MARK: PROPERTIES public var videoURL: URL! var player: AVPlayer? var playerController : AVPlayerViewController? @IBOutlet weak var closeButton: UIButton! // MARK: VIEW DID LOAD - FUNCTION override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.gray player = AVPlayer(url: videoURL) playerController = AVPlayerViewController() guard player != nil && playerController != nil else { return } playerController!.showsPlaybackControls = false playerController!.player = player! self.addChildViewController(playerController!) self.view.addSubview(playerController!.view) playerController!.view.frame = view.frame NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.player!.currentItem) closeButton.setImage(#imageLiteral(resourceName: "closeButton"), for: .normal) closeButton.setImage(#imageLiteral(resourceName: "closeButton"), for: .highlighted) closeButton.addAnimations() self.view.bringSubview(toFront: closeButton) } // MARK: DISMISS - FUNCTION @IBAction func dismiss(_ sender: Any) { self.dismiss(animated: true, completion: nil) } // MARK: VIEW DID APPEAR - FUNCTION override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) player?.play() } // MARK: PLAY ITEM DID REACH END - FUNCTION @objc fileprivate func playerItemDidReachEnd(_ notification: Notification) { if self.player != nil { self.player!.seek(to: kCMTimeZero) self.player!.play() } } // MARK: PREFERRED STATUS BAR STYLE - VARIABLE override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
// // PrincipalTabBarViewController.swift // Modi // // Created by Ramses Miramontes Meza on 28/11/15. // Copyright © 2015 RASOFT. All rights reserved. // import UIKit class PrincipalTabBarViewController: UITabBarController { var invitado = false override func viewDidLoad() { super.viewDidLoad() if invitado { if let items = tabBar.items! as [UITabBarItem]! { items[1].enabled = false items[3].enabled = false } } // 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // Baby.swift // vaporWebAuth // // Created by SH on 05/12/2017. // import FluentProvider // MARK: - Class: Baby - final class Baby: Model, NodeConvertible { let storage = Storage() var name: String var gender: Gender.RawValue var age: Int var daiperBrand: String var daiperSize: String // MARK: - Initializer - init(name: String, gender: Gender, age: Int, daiperBrand: String, daiperSize: String) { self.name = name self.gender = gender.rawValue self.age = age self.daiperBrand = daiperBrand self.daiperSize = daiperSize } // MARK: - NodeConvertible - init(node: Node) throws { name = try node.get("name") gender = try node.get("gender") age = try node.get("age") daiperBrand = try node.get("daiperBrand") daiperSize = try node.get("daiperSize") } func makeNode(in context: Context?) throws -> Node { var node = Node(context) try node.set("name", name) try node.set("gender", gender) try node.set("age", age) try node.set("daiperBrand", daiperBrand) try node.set("daiperSize", daiperSize) return node } // MARK: - DB: Parse & Serialize - init(row: Row) throws { name = try row.get("name") gender = try row.get("gender") age = try row.get("age") daiperBrand = try row.get("daiperBrand") daiperSize = try row.get("daiperSize") } func makeRow() throws -> Row { var row = Row() try row.set("name", name) try row.set("gender", gender) try row.set("age", age) try row.set("daiperBrand", daiperBrand) try row.set("daiperSize", daiperSize) return row } } // MARK: - JSONConvertible - extension Baby: JSONConvertible { convenience init(json: JSON) throws { try self.init( name: json.get("name"), gender: json.get("gender"), age: json.get("age"), daiperBrand: json.get("daiperBrand"), daiperSize: json.get("daiperSize") ) } func makeJSON() throws -> JSON { var json = JSON() try json.set("name", name) try json.set("gender", gender) try json.set("age", age) try json.set("daiperBrand", daiperBrand) try json.set("daiperSize", daiperSize) return json } } // MARK: - Database Preparation - extension Baby: Preparation { static func prepare(_ database: Database) throws { try database.create(self, closure: { babies in babies.id() babies.foreignId(for: Client.self) babies.string("name") babies.string("gender") babies.int("age") babies.string("daiperBrand") babies.string("daiperSize") }) } static func revert(_ database: Database) throws { try database.delete(self) } } // MARK: - Timestampable - extension Baby: Timestampable { } // MARK: - ResponseRepresentable - extension Baby: ResponseRepresentable { }
// // ViewController.swift // 带参数和返回值闭包 // // Created by qianjn on 16/7/24. // Copyright © 2016年 SF. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. weak var weakSelf = self weakSelf?.view.backgroundColor = UIColor.red() block1 { () -> Int in return 4 } } func block1(numCount:() -> Int) { for i in 0...numCount { print(i) } } }
// // Barcode.swift // LocationApp // // Created by Ford, Ryan M. on 11/23/18. // Copyright © 2018 Ford, Ryan M. All rights reserved. // import AVFoundation import UIKit import CloudKit import CoreLocation //MARK: Class class ScannerViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate { let reachability = Reachability()! let locations = container.locations let settingsService = container.settings var recordsupdate = RecordsUpdate() var zoomFactor:CGFloat = 3 var captureSession: AVCaptureSession! var previewLayer: AVCaptureVideoPreviewLayer! var counter:Int64 = 0 let dispatchGroup = DispatchGroup() var records = [CKRecord]() var itemRecord:CKRecord? var tempRecords = [CKRecord]() var locationManager = CLLocationManager() var alertTextField: UITextField! var isRescan: Bool = false var outOfRangeCounter: Int = 0 let numberOfGPSRetry: Int = 2 var settings: Settings? var audioPlayer: AudioPlayer? var photo: UIImage? @IBOutlet weak var innerView: UIView! @IBOutlet weak var outerView: UIView! struct variables { //key variables needed in other classes static var dosiNumber:String? static var QRCode:String? static var codeType:String? static var dosiLocation:String? static var collected:Int64? static var mismatch:Int64? static var active:Int64? static var cycle:String? static var latitude:String? static var longitude:String? static var moderator:Int64? } //end struct override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white captureSession = AVCaptureSession() guard let videoCaptureDevice = AVCaptureDevice.default(for: .video) else { return } let videoInput: AVCaptureDeviceInput //set zoom factor to 3x do { try videoCaptureDevice.lockForConfiguration() } catch { // handle error return } // When this point is reached, we can be sure that the locking succeeded //end set zoom factor to 3X do { videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice) } catch { return } if (captureSession.canAddInput(videoInput)) { captureSession.addInput(videoInput) } else { failed() return } let metadataOutput = AVCaptureMetadataOutput() if (captureSession.canAddOutput(metadataOutput)) { captureSession.addOutput(metadataOutput) metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) //Location barcode is a QR Code (.qr) //Dosimeter barcoce is a CODE 128 barcode (.code128) metadataOutput.metadataObjectTypes = [AVMetadataObject.ObjectType.qr, AVMetadataObject.ObjectType.code128] } else { failed() return }//end else previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer.frame.size = innerView.frame.size innerView.layer.addSublayer(previewLayer) previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill videoCaptureDevice.videoZoomFactor = zoomFactor videoCaptureDevice.unlockForConfiguration() DispatchQueue.global(qos: .background).async { self.captureSession.startRunning() } configReachability() settingsService.getSettings(completionHandler: { self.settings = $0 }) audioPlayer = AudioPlayer() }//end viewDidLoad() @IBAction func done(_ sender: Any) { self.dismiss(animated: true, completion: nil) } func failed() { let ac = UIAlertController(title: "Scanning not supported", message: "Your device does not support scanning a code from an item. Please use a device with a camera.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) captureSession = nil }//end failed override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.previewLayer?.frame.size = self.innerView.frame.size if (captureSession?.isRunning == false) { DispatchQueue.global(qos: .background).async { self.captureSession.startRunning() } } }//end viewWillAppear override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if (captureSession?.isRunning == true) { captureSession.stopRunning() } }//end viewWillDisappear func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { captureSession.stopRunning() if let metadataObject = metadataObjects.first { guard let readableObject = metadataObject as? AVMetadataMachineReadableCodeObject else { return } let stringValue = readableObject.stringValue switch readableObject.type { case .qr: variables.codeType = "QRCode" case .code128: if(stringValue?.count ?? 0 >= settings!.dosimeterMinimumLength && stringValue?.count ?? 0 <= settings!.dosimeterMaximumLength){ variables.codeType = "Code128" } else { alert14() return } default: print("Code not found") }//end switch scannerLogic(code: stringValue) }//end if let }//end function meetadataOutput override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } //end supportedInterfaceOrientations } //end class /* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ All methods, alerts, handlers and queries needed to implement the scanner logic (see figures under "other assets") by Ryan M. Ford 2019 */ // MARK: ScannerViewController //MARK: Extension extension ScannerViewController { func scannerLogic(code: String?) { //see Other Assets Scanner Logic diagrams switch self.counter { case 0: //first scan if(isRescan){ isRescan = false } else { variables.QRCode = nil variables.dosiNumber = nil clearForQR() } switch variables.codeType { case "QRCode": if(code != nil ){ variables.QRCode = code //store the QRCode queryForQRFound() //use the QRCode to look up record & store values dispatchGroup.notify(queue: .main) { print("1 - Dispatch QR Code Notify") //record found if self.itemRecord != nil { //deployed dosimeter if variables.collected == 0 { self.audioPlayer?.beep() if variables.active == 1 { if(RecordsUpdate.generateCycleDate() == variables.cycle){ self.alert13(nextFunction: self.alert3a) } else { self.alert3a() //Exchange Dosimeter (active location) } } else { if(RecordsUpdate.generateCycleDate() == variables.cycle){ self.alert13(nextFunction: self.alert3i) } else { self.alert3i() //Collect Dosimeter (inactive location) } } } //collected or no dosimeter else { if variables.active == 1 { self.audioPlayer?.beep() self.alert2() //Location Found [cancel/deploy] } else { self.audioPlayer?.beepFail() self.alert2a() //Inactive Location (activate to deploy) } } } //no record found else { self.audioPlayer?.beep() self.alert2() //New Location [cancel/deploy] } } //end dispatch group } else { self.alert12() //Invalid code (rescan) } case "Code128": if(code != nil ){ variables.dosiNumber = code //store the dosi number queryForDosiFound() //use the dosiNumber to look up record & store values dispatchGroup.notify(queue: .main) { print("1 - Dispatch Code 128 Notify") //record found if self.itemRecord != nil { //deployed dosimeter if variables.collected == 0 { self.audioPlayer?.beep() if variables.active == 1 { if(RecordsUpdate.generateCycleDate() == variables.cycle){ self.alert13(nextFunction: self.alert3a) } else { self.alert3a() //Exchange Dosimeter (active location) } } else { if(RecordsUpdate.generateCycleDate() == variables.cycle){ self.alert13(nextFunction: self.alert3i) } else { self.alert3i() //Collect Dosimeter (inactive location) } } } //collected dosimeter else { self.audioPlayer?.beepFail() self.alert9a() //Invalid Dosimeter (already collected) } } //no record found else { self.audioPlayer?.beep() self.alert1() //Dosimeter Not Found [cancel/deploy] } } } //end dispatch group else { self.alert12() //Invalid code (rescan) } default: print("Invalid Code") //exhaustive alert9() } //end switch case 1: //second scan logic //self.captureSession.startRunning() if(isRescan){ isRescan = false } switch variables.codeType { case "QRCode": if(code != nil ){ //looking for QRCode if variables.QRCode == nil { clearForQR() queryForQRUsed(tempQR: code!) dispatchGroup.notify(queue: .main) { print("2 - Dispatch QR Code Notify") //existing location if self.records != [] { //location in use/inactive location if variables.collected == 0 || variables.active == 0 { self.audioPlayer?.beepFail() self.alert7b(code: code!) } //valid location else { self.audioPlayer?.beep() variables.QRCode = code self.save() } } //new location else { self.audioPlayer?.beep() variables.QRCode = code self.save() } } //end dispatch group } //not looking for QRCode else { self.audioPlayer?.beepFail() alert6b() } } else { alert12() } case "Code128": if(code != nil ){ //looking for barcode if variables.dosiNumber == nil { queryForDosiUsed(tempDosi: code!) dispatchGroup.notify(queue: .main) { print("2 - Dispatch Code 128 Notify") //duplicate dosimeter if self.records != [] { self.audioPlayer?.beepFail() self.alert7a(code: code!) } //new dosimeter else { self.audioPlayer?.beep() variables.dosiNumber = code self.save() } } //end dispatch group } //looking for barcode //not looking for barcode else { self.audioPlayer?.beepFail() alert6a() } } else { alert12() } default: print("Invalid Code") if variables.QRCode == nil { alert6a() } else if variables.dosiNumber == nil { alert6b() } } default: if(isRescan){ isRescan = false } print("Invalid Scan") counter = 0 DispatchQueue.global(qos: .background).async { self.captureSession.startRunning() } } } //end func //MARK: Collect func collect(collected: Int64, mismatch: Int64, modifiedDate: Date) { itemRecord!.setValue(collected, forKey: "collectedFlag") itemRecord!.setValue(mismatch, forKey: "mismatch") itemRecord!.setValue(modifiedDate, forKey: "modifiedDate") let item = LocationRecordCacheItem(withRecord: itemRecord!)! locations.save(item: item, completionHandler: nil) } //end collect func deploy() { self.counter = 1 } //end deploy func clearData() { variables.codeType = nil variables.dosiNumber = nil variables.QRCode = nil variables.latitude = nil variables.longitude = nil variables.dosiLocation = nil variables.collected = nil variables.mismatch = nil variables.active = nil variables.moderator = nil variables.cycle = nil itemRecord = nil counter = 0 self.photo = nil } //end clear data func clearForQR() { variables.dosiLocation = nil variables.collected = nil variables.mismatch = nil variables.active = nil variables.moderator = nil } func save(){ variables.cycle = RecordsUpdate.generateCycleDate() locationManager.requestAlwaysAuthorization() var currentLocation = CLLocation() if (locationManager.authorizationStatus == .authorizedWhenInUse || locationManager.authorizationStatus == .authorizedAlways) { currentLocation = locationManager.location! } if(Slac.isLocationInRange(location: currentLocation) || outOfRangeCounter >= numberOfGPSRetry ) { setCoordinates(currentLocation: (outOfRangeCounter >= numberOfGPSRetry ? Slac.defaultCoordinates : currentLocation)) self.alert8() } else{ //Wrong Location, Show Try Again alert self.outOfRangeCounter+=1 self.alert15() } } func setCoordinates(currentLocation: CLLocation) { let latitude = String(format: "%.8f", currentLocation.coordinate.latitude) let longitude = String(format: "%.8f", currentLocation.coordinate.longitude) variables.latitude = latitude variables.longitude = longitude } fileprivate func configReachability() { reachability.whenReachable = { reachability in self.outerView.backgroundColor = UIColor(named: "MainOnline") } reachability.whenUnreachable = { reachability in self.outerView.backgroundColor = UIColor(named: "MainOffline") } do { try reachability.startNotifier() } catch { print("Unable to start notifier") } } } //end extension methods /* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */ //MARK: Extension ScannerViewController extension ScannerViewController { //queries func queryForDosiFound() { dispatchGroup.enter() locations.filter(by: { l in l.dosinumber == variables.dosiNumber!}, completionHandler: { items in var lrecords = [CKRecord]() for item in items { lrecords.append(item.to()) } if lrecords != [] { variables.active = lrecords[0]["active"] as? Int64 variables.collected = lrecords[0]["collectedFlag"] as? Int64 variables.QRCode = lrecords[0]["QRCode"] as? String variables.dosiLocation = lrecords[0]["locdescription"] as? String variables.cycle = lrecords[0]["cycleDate"] as? String if lrecords[0]["moderator"] != nil { variables.moderator = lrecords[0]["moderator"] as? Int64 } if lrecords[0]["mismatch"] != nil { variables.mismatch = lrecords[0]["mismatch"] as? Int64 } self.itemRecord = lrecords[0] } self.records = lrecords self.dispatchGroup.leave() }) } //end queryforDosiFound func queryForQRFound() { dispatchGroup.enter() locations.filter(by: { l in l.QRCode == variables.QRCode! && l.createdDate != nil}, completionHandler: { items in var litems = [LocationRecordCacheItem](items) litems.sort { $0.createdDate! > $1.createdDate! } var lrecords = [CKRecord]() for item in litems { lrecords.append(item.to()) } if lrecords != [] { variables.active = lrecords[0]["active"] as? Int64 variables.dosiLocation = lrecords[0]["locdescription"] as? String if lrecords[0]["collectedFlag"] != nil { variables.collected = lrecords[0]["collectedFlag"] as? Int64 } if lrecords[0]["dosinumber"] != nil { variables.dosiNumber = lrecords[0]["dosinumber"] as? String } if lrecords[0]["moderator"] != nil { variables.moderator = lrecords[0]["moderator"] as? Int64 } if lrecords[0]["mismatch"] != nil { variables.mismatch = lrecords[0]["mismatch"] as? Int64 } if lrecords[0]["cycleDate"] != nil { variables.cycle = lrecords[0]["cycleDate"] as? String } self.itemRecord = lrecords[0] } self.records = lrecords self.dispatchGroup.leave() }) } //end queryForQRFound func queryForDosiUsed(tempDosi: String) { dispatchGroup.enter() locations.filter(by: { l in l.dosinumber == tempDosi}, completionHandler: { items in var lrecords = [CKRecord]() for item in items { lrecords.append(item.to()) } self.records = lrecords self.dispatchGroup.leave() }) } //end queryForDosiUsed func queryForQRUsed(tempQR: String) { dispatchGroup.enter() locations.filter(by: { l in l.QRCode == tempQR && l.createdDate != nil}, completionHandler: {items in var litems = [LocationRecordCacheItem](items) litems.sort { $0.createdDate! > $1.createdDate! } var lrecords = [CKRecord]() for item in litems { lrecords.append(item.to()) } if lrecords != [] { variables.active = lrecords[0]["active"] as? Int64 variables.dosiLocation = lrecords[0]["locdescription"] as? String if lrecords[0]["collectedFlag"] != nil { variables.collected = lrecords[0]["collectedFlag"] as? Int64} if lrecords[0]["moderator"] != nil { variables.moderator = lrecords[0]["moderator"] as? Int64 } if lrecords[0]["mismatch"] != nil { variables.mismatch = lrecords[0]["mismatch"] as? Int64 } } self.records = lrecords self.dispatchGroup.leave() }) } //end queryForQRUsed } //end extension queries /* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */ extension ScannerViewController { //camera func openCamera(tempDesc: String?){ if tempDesc != nil { variables.dosiLocation = tempDesc } let vc = UIImagePickerController() vc.sourceType = .camera vc.allowsEditing = true vc.delegate = self present(vc, animated: true) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { picker.dismiss(animated: true) guard let image = info[.editedImage] as? UIImage else { print("No image found") return } self.photo = image self.alert8() } } extension ScannerViewController { //alerts func alert1() { let alert = UIAlertController(title: "Dosimeter Not Found:\n\(variables.dosiNumber ?? "Nil Dosi")", message: nil, preferredStyle: .alert) let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: handlerCancel) let deployDosimeter = UIAlertAction(title: "Deploy", style: .default) { (_) in variables.QRCode = nil self.deploy() self.alert4() } //end let alert.addAction(deployDosimeter) alert.addAction(cancel) DispatchQueue.main.async { //UIAlerts need to be shown on the main thread. self.present(alert, animated: true, completion: nil) } } //end alert1 func alert2() { let title = itemRecord != nil ? "Location Found:\n\(variables.QRCode ?? "Nil QRCode")" : "New Location:\n\(variables.QRCode ?? "Nil QRCode")" let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert) let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: handlerCancel) let deployDosimeter = UIAlertAction(title: "Deploy", style: .default) { (_) in variables.dosiNumber = nil self.deploy() self.alert5() } //end let alert.addAction(deployDosimeter) alert.addAction(cancel) DispatchQueue.main.async { //UIAlerts need to be shown on the main thread. self.present(alert, animated: true, completion: nil) } } //end alert2 func alert2a() { let message = "Please activate this location to deploy a dosimeter." //set up alert let alert = UIAlertController.init(title: "Inactive Location:\n\(variables.QRCode ?? "Nil QRCode")", message: message, preferredStyle: .alert) let OK = UIAlertAction(title: "OK", style: .default, handler: handlerCancel) alert.addAction(OK) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } //MARK: Alert 3a Exchange func alert3a() { let message = "\nCycle Date: \(variables.cycle ?? "Nil Cycle")" let alert = UIAlertController(title: "Exchange Dosimeter:\n\(variables.dosiNumber ?? "Nil Dosi")\n\nLocation:\n\(variables.QRCode ?? "Nil QRCode")", message: message, preferredStyle: .alert) let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: handlerCancel) let ExchangeDosimeter = UIAlertAction(title: "Exchange", style: .default) { (_) in self.collect(collected: 1, mismatch: variables.mismatch ?? 0, modifiedDate: Date(timeInterval: 0, since: Date())) self.alert11a() } let mismatch = UIAlertAction(title: "Mismatch", style: .default) { (_) in self.alert3a() } alert.addAction(mismatch) alert.view.addSubview(mismatchSwitch()) alert.addAction(ExchangeDosimeter) alert.addAction(cancel) DispatchQueue.main.async { //UIAlerts need to be shown on the main thread. self.present(alert, animated: true, completion: nil) } } //end alert3a //MARK: Alert 3i Collect func alert3i() { let message = "\nCycle Date: \(variables.cycle ?? "Nil Cycle")" let alert = UIAlertController(title: "Collect Dosimeter:\n\(variables.dosiNumber ?? "Nil Dosi")\n\nLocation:\n\(variables.QRCode ?? "Nil QRCode")", message: message, preferredStyle: .alert) let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: handlerCancel) let collectDosimeter = UIAlertAction(title: "Collect", style: .default) { (_) in self.collect(collected: 1, mismatch: variables.mismatch ?? 0, modifiedDate: Date(timeInterval: 0, since: Date())) self.alert11() } let mismatch = UIAlertAction(title: "Mismatch", style: .default) { (_) in self.alert3i() //reopen alert } alert.addAction(mismatch) alert.view.addSubview(mismatchSwitch()) alert.addAction(collectDosimeter) alert.addAction(cancel) DispatchQueue.main.async { //UIAlerts need to be shown on the main thread. self.present(alert, animated: true, completion: nil) } } //end alert3i func alert3() { let message = "Please scan the new dosimeter for location \(variables.QRCode ?? "Nil Dosi").\n\n\n\n\n\n\n" let picture = Bundle.main.path(forResource: "Inlight", ofType: "jpg")! let imageView = UIImageView(frame: CGRect(x: 75, y: 90, width: 120, height: 80)) let image = UIImage(named: picture) imageView.image = image //set up alert let alert = UIAlertController.init(title: "Replace Dosimeter", message: message, preferredStyle: .alert) let OK = UIAlertAction(title: "OK", style: .default, handler: handlerOK) alert.view.addSubview(imageView) alert.addAction(OK) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } //end alert3 func alert4() { let message = "Dosimeter barcode accepted \(variables.dosiNumber ?? "Nil Dosi"). Please scan the corresponding location code.\n\n\n\n\n\n\n" let picture = Bundle.main.path(forResource: "QRCodeImage", ofType: "png")! let imageView = UIImageView(frame: CGRect(x: 90, y: 90, width: 100, height: 100)) let image = UIImage(named: picture) imageView.image = image //set up alert let alert = UIAlertController.init(title: "Scan Accepted", message: message, preferredStyle: .alert) let OK = UIAlertAction(title: "OK", style: .default, handler: handlerOK) alert.view.addSubview(imageView) alert.addAction(OK) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } //end alert4 func alert5() { let message = "Location code accepted \(variables.QRCode ?? "Nil QR"). Please scan the corresponding dosimeter.\n\n\n\n\n\n" let picture = Bundle.main.path(forResource: "Inlight", ofType: "jpg")! let imageView = UIImageView(frame: CGRect(x: 75, y: 100, width: 120, height: 80)) let image = UIImage(named: picture) imageView.image = image //set up alert let alert = UIAlertController.init(title: "Scan Accepted", message: message, preferredStyle: .alert) let OK = UIAlertAction(title: "OK", style: .default, handler: handlerOK) alert.view.addSubview(imageView) alert.addAction(OK) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } //end alert5 func alert6a() { let message = "Try again...Please scan the corresponding location code.\n\n\n\n\n\n\n" let picture = Bundle.main.path(forResource: "QRCodeImage", ofType: "png")! let imageView = UIImageView(frame: CGRect(x: 90, y: 90, width: 100, height: 100)) let image = UIImage(named: picture) imageView.image = image //set up alert let alert = UIAlertController.init(title: "Error", message: message, preferredStyle: .alert) let OK = UIAlertAction(title: "OK", style: .cancel, handler: handlerOK) alert.view.addSubview(imageView) alert.addAction(OK) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } //end alert6a func alert6b() { let message = "Try again...Please scan the corresponding dosimeter.\n\n\n\n\n\n\n" let picture = Bundle.main.path(forResource: "Inlight", ofType: "jpg")! let imageView = UIImageView(frame: CGRect(x: 75, y: 90, width: 120, height: 80)) let image = UIImage(named: picture) imageView.image = image //set up alert let alert = UIAlertController.init(title: "Error", message: message, preferredStyle: .alert) let OK = UIAlertAction(title: "OK", style: .cancel, handler: handlerOK) alert.view.addSubview(imageView) alert.addAction(OK) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } //end alert6b func alert7a(code: String) { let message = "Try again...Please scan a new dosimeter.\n\n\n\n\n\n\n" let picture = Bundle.main.path(forResource: "Inlight", ofType: "jpg")! let imageView = UIImageView(frame: CGRect(x: 75, y: 110, width: 120, height: 80)) let image = UIImage(named: picture) imageView.image = image //set up alert let alert = UIAlertController.init(title: "Duplicate Dosimeter:\n\(code)", message: message, preferredStyle: .alert) let OK = UIAlertAction(title: "OK", style: .cancel, handler: handlerOK) alert.view.addSubview(imageView) alert.addAction(OK) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } //end alert7a func alert7b(code: String) { let title = variables.collected == 0 ? "Location In Use:\n\(code)" : "Inactive Location:\n\(variables.QRCode ?? "Nil QRCode")" let message = "Try again...Please scan a different location.\n\n\n\n\n\n\n" let picture = Bundle.main.path(forResource: "QRCodeImage", ofType: "png")! let imageView = UIImageView(frame: CGRect(x: 90, y: 110, width: 100, height: 100)) let image = UIImage(named: picture) imageView.image = image //set up alert let alert = UIAlertController.init(title: title, message: message, preferredStyle: .alert) let OK = UIAlertAction(title: "OK", style: .cancel, handler: handlerOK) alert.view.addSubview(imageView) alert.addAction(OK) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } //end alert7b //MARK: Alert8 func alert8() { let alert = UIAlertController(title: "Deploy Dosimeter:\n\(variables.dosiNumber ?? "Nil Dosi")", message: "\nLocation: \(variables.QRCode ?? "Nil QRCode")", preferredStyle: .alert) let moderator = UIAlertAction(title: "Moderator", style: .default) { (_) in if let tempDesc = alert.textFields?.first?.text { variables.dosiLocation = tempDesc } self.alert8() } let saveRecord = UIAlertAction(title: "Save", style: .default) { (_) in if let text = alert.textFields?.first?.text { let label = UILabel(frame: CGRect(x: 0, y: 97, width: 270, height:18)) label.textAlignment = .center label.textColor = .red //label.font = label.font.withSize(12) label.font = .boldSystemFont(ofSize: 14) alert.view.addSubview(label) label.isHidden = true if text == ""{ label.text = "Please enter a location" label.isHidden = false self.present(alert, animated: true, completion: nil) } else { let description = text.replacingOccurrences(of: ",", with: "-") let newRecord = CKRecord(recordType: "Location") newRecord.setValue(variables.latitude ?? "Nil Latitude", forKey: "latitude") newRecord.setValue(variables.longitude ?? "Nil Longitude", forKey: "longitude") newRecord.setValue(description, forKey: "locdescription") newRecord.setValue(variables.dosiNumber ?? "Nil Dosi", forKey: "dosinumber") newRecord.setValue(0, forKey: "collectedFlag") newRecord.setValue(variables.cycle, forKey: "cycleDate") newRecord.setValue(variables.QRCode ?? "Nil QRCode", forKey: "QRCode") newRecord.setValue(variables.moderator ?? 0, forKey: "moderator") newRecord.setValue(1, forKey: "active") newRecord.setValue(Date(timeInterval: 0, since: Date()), forKey: "createdDate") newRecord.setValue(Date(timeInterval: 0, since: Date()), forKey: "modifiedDate") newRecord.setValue(variables.mismatch ?? 0, forKey: "mismatch") if let qrCode = variables.QRCode { let reportGroup = Groups[qrCode] newRecord.setValue(reportGroup, forKey: "reportGroup") } var locationRecordCacheItem = LocationRecordCacheItem(withRecord: newRecord)! if let photo = self.photo { do { try locationRecordCacheItem.setPhoto(photo: photo) } catch { print("Unexpected error: \(error).") } } self.locations.save(item: locationRecordCacheItem, completionHandler: nil) self.photo = nil self.outOfRangeCounter = 0 self.alert10() //Succes } //text = text?.replacingOccurrences(of: ",", with: "-") //Ver 1.2 - supply default location to prevent empty string in DB. //rather than alert on top of alert for field valication //if text == "" { // text = "Default Location (field left empty)" } //end if let } //end let let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: handlerCancel) alert.addTextField { (textfield) in if variables.dosiLocation != nil { textfield.text = variables.dosiLocation // assign self.description with the textfield information } textfield.placeholder = "Type or dictate location details" //assign self.description with the textfield information } // end addTextField alert.addAction(moderator) alert.view.addSubview(modSwitch()) if(reachability.isReachable){ let photo = UIAlertAction(title: (self.photo == nil) ? "Add photo" : "Replace photo", style: .default, handler: {(action) in let tempDesc = alert.textFields?.first?.text self.openCamera(tempDesc: tempDesc) }) alert.addAction(photo) } alert.addAction(saveRecord) alert.addAction(cancel) DispatchQueue.main.async { //UIAlerts need to be shown on the main thread. self.present(alert, animated: true, completion: nil) } } //end alert8 func alert9() { //invalid barcode type let message = "Please scan either a location barcode or a dosimeter." //set up alert let alert = UIAlertController.init(title: "Invalid Barcode Type", message: message, preferredStyle: .alert) let OK = UIAlertAction(title: "OK", style: .cancel, handler: handlerCancel) alert.addAction(OK) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } //end alert9 func alert9a() { //already collected dosimeter let message = "This dosimeter has already been collected." //set up alert let alert = UIAlertController.init(title: "Invalid Dosimeter:\n\(variables.dosiNumber ?? "Nil Dosi")", message: message, preferredStyle: .alert) let OK = UIAlertAction(title: "OK", style: .cancel, handler: handlerCancel) alert.addAction(OK) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } //end alert9 func alert10(){ //Success! (Deploy) //let message = "Data saved: \nQR Code: \(variables.QRCode ?? "Nil QRCode")\nDosimeter: \(variables.dosiNumber ?? "Nil Dosi")\nLocation: \(variables.dosiLocation ?? "Nil location")\nFlag (Depl'y = 0, Collected = 1): 0\nLatitude: \(variables.latitude ?? "Nil Latitude")\nLongitude: \(variables.longitude ?? "Nil Longitude")\nWear Date: \(variables.cycle ?? "Nil cycle")\nMismatch (No = 0 Yes = 1): \(variables.mismatch ?? 0)\nModerator (No = 0 Yes = 1): \(variables.moderator ?? 0)" let message = "QR Code: \(variables.QRCode ?? "Nil QRCode")\nDosimeter: \(variables.dosiNumber ?? "Nil Dosi")" //set up alert let alert = UIAlertController.init(title: "Save Successful!", message: message, preferredStyle: .alert) let OK = UIAlertAction(title: "OK", style: .default, handler: handlerCancel) alert.addAction(OK) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } //end alert10 func alert11() { //Success! (Collect) //let message = "Data Saved:\nQR Code: \(variables.QRCode ?? "Nil QRCode")\nDosimeter: \(variables.dosiNumber ?? "Nil Dosi")\nLocation: \(variables.dosiLocation ?? "Nil location")\nFlag (Depl'y = 0, Collected = 1): 1 \nMismatch (No = 0 Yes = 1): \(variables.mismatch ?? 0)" let message = "QR Code: \(variables.QRCode ?? "Nil QRCode")\nDosimeter: \(variables.dosiNumber ?? "Nil Dosi")" //set up alert let alert = UIAlertController.init(title: "Collection Successful!", message: message, preferredStyle: .alert) let OK = UIAlertAction(title: "OK", style: .default, handler: handlerCancel) alert.addAction(OK) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } //end alert11 func alert11a() { //Success! (Exchange) //let message = "Data Saved:\nQR Code: \(variables.QRCode ?? "Nil QRCode")\nDosimeter: \(variables.dosiNumber ?? "Nil Dosi")\nLocation: \(variables.dosiLocation ?? "Nil location")\nFlag (Depl'y = 0, Collected = 1): 1 \nMismatch (No = 0 Yes = 1): \(variables.mismatch ?? 0)" let message = "QR Code: \(variables.QRCode ?? "Nil QRCode")\nDosimeter: \(variables.dosiNumber ?? "Nil Dosi")" //set up alert let alert = UIAlertController.init(title: "Collection Successful!", message: message, preferredStyle: .alert) let OK = UIAlertAction(title: "OK", style: .default) { (_) in self.deploy() variables.mismatch = 0 variables.dosiNumber = nil self.alert3() } alert.addAction(OK) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } //end alert11a //MARK: Alert12 func alert12() { //invalid code, rescan let message = "Invalid barcode, please rescan!" //set up alert let alert = UIAlertController.init(title: "Invalid code", message: message, preferredStyle: .alert) let rescan = UIAlertAction(title: "Rescan", style: .default) { (_) in self.isRescan = true DispatchQueue.global(qos: .background).async { self.captureSession.startRunning() } } alert.addAction(rescan) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } //end alert12 //MARK: Alert13 func alert13(nextFunction: @escaping () -> Void) { //invalid cycle date let message = "This dosimeter already exchanged in the current cycle. Are you sure you want to continue?" //set up alert let alert = UIAlertController.init(title: "Warning", message: message, preferredStyle: .alert) alert.view.subviews.first?.subviews.first?.subviews.first?.backgroundColor = UIColor(named: "WarningDialogBackground") let cont = UIAlertAction(title: "Continue", style: .destructive) { (_) in nextFunction() } let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: handlerCancel) alert.addAction(cont) alert.addAction(cancel) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } //end alert13 //MARK: Alert14 func alert14() { //invalid code length, rescan let min = settings!.dosimeterMinimumLength let max = settings!.dosimeterMaximumLength var message = "The length of the dosimeter barcodes must be " message += min == max ? "\(min) " : "between \(min) and \(max) " message += "characters. Please rescan!" self.audioPlayer?.beepFail() //set up alert let alert = UIAlertController.init(title: "Invalid length", message: message, preferredStyle: .alert) let rescan = UIAlertAction(title: "Rescan", style: .default) { (_) in self.isRescan = true DispatchQueue.global(qos: .background).async { self.captureSession.startRunning() } } alert.addAction(rescan) DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) } } //end alert14 //MARK: Alert15 func alert15() { //Outside of SLAC let message = (outOfRangeCounter == numberOfGPSRetry) ? "Your fix is still outside of SLAC property. Please tap Try Again for a final attempt, and if it’s still out of range then standard coordinates will be assigned. These can be adjusted later in the Tools menu. " : "Your fix is not on SLAC property. Please tap Try Again." self.audioPlayer?.beepFail() let alert = UIAlertController(title: "GPS Coordinate Error\n", message: message, preferredStyle: .alert) let tryAgain = UIAlertAction(title: "Try Again", style: .cancel){ (_) in self.save() } alert.addAction(tryAgain) DispatchQueue.main.async { //UIAlerts need to be shown on the main thread. self.present(alert, animated: true){ alert.view.superview?.subviews[0].isUserInteractionEnabled = false } } } //end alert15 //mismatch switch func mismatchSwitch() -> UISwitch { let switchControl = UISwitch(frame: CGRect(x: 200, y: 191, width: 0, height: 0)) switchControl.tintColor = UIColor.gray switchControl.setOn(variables.mismatch == 1, animated: false) switchControl.addTarget(self, action: #selector(mismatchSwitchValueDidChange), for: .valueChanged) return switchControl } @objc func mismatchSwitchValueDidChange(_ sender: UISwitch!) { variables.mismatch = sender.isOn ? 1 : 0 } //moderator switch func modSwitch() -> UISwitch { let switchControl = UISwitch(frame: CGRect(x: 200, y: 161, width: 0, height: 0)) switchControl.tintColor = UIColor.gray switchControl.setOn(variables.moderator == 1, animated: false) switchControl.addTarget(self, action: #selector(modSwitchValueDidChange), for: .valueChanged) return switchControl } @objc func modSwitchValueDidChange(_ sender: UISwitch!) { variables.moderator = sender.isOn ? 1 : 0 } }//end extension alerts /* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ */ extension ScannerViewController { //handlers func handlerOK(alert: UIAlertAction!) { //used for OK in the alert prompt. DispatchQueue.global(qos: .background).async { self.captureSession.startRunning() } } //end handler func handlerCancel(alert: UIAlertAction!) { self.clearData() DispatchQueue.global(qos: .background).async { self.captureSession.startRunning() } } } //end extension
// // EmptyTests.swift // MastodonKit // // Created by Ornithologist Coder on 6/8/17. // Copyright © 2017 MastodonKit. All rights reserved. // import XCTest @testable import MastodonKit class EmptyTests: XCTestCase { func testEmptyFromJSON() { let fixture = try! Fixture.load(fileName: "Fixtures/Empty.json") let empty = try? Empty.decode(data: fixture) XCTAssertNotNil(empty) } func testEmptyWithEmptyDictionary() { let fixture = "[:]".data(using: .utf8)! let parsed = try? Empty.decode(data: fixture) XCTAssertNil(parsed) } func testEmptyWithNonEmptyDictionary() { let fixture = "[\"foo\": \"bar\"]".data(using: .utf8)! let parsed = try? Empty.decode(data: fixture) XCTAssertNil(parsed) } func testEmptyWithEmptyString() { let fixture = "".data(using: .utf8)! let parsed = try? Empty.decode(data: fixture) XCTAssertNil(parsed) } func testEmptyWithString() { let fixture = "foo".data(using: .utf8)! let parsed = try? Empty.decode(data: fixture) XCTAssertNil(parsed) } }
// // HomeRouter.swift // MVVMFramework // // Created by lisilong on 2018/12/11. // Copyright © 2018 lisilong. All rights reserved. // import UIKit enum HomeRouterTable: String { /// 首页模块 case home } class HomeRouter: NSObject { /// 界面跳转路由 /// /// - Parameters: /// - route: 跳转类型 /// - parameters: 参数 /// - fromViewController: 当前页面 static func pushTo(_ route: HomeRouterTable, parameters: [String: Any]?, fromViewController: UIViewController) { switch route { case .home: let VC = HomeViewController() DispatchQueue.main.async { fromViewController.navigationController?.pushViewController(VC, animated: true) } } } }
// // GroupsViewModel.swift // Quota // // Created by Marcin Włoczko on 03/11/2018. // Copyright © 2018 Marcin Włoczko. All rights reserved. // import Foundation import RxSwift import RxCocoa protocol GroupsViewModelDelegate: class { func groupsViewModelDidTapInsert() func groupsViewModel(didSelect group: Group) } protocol GroupsViewModel { var delegate: GroupsViewModelDelegate? { get set } var reloadAction: PublishRelay<Void> { get } var title: String { get } var newTitle: String { get } func insertTapped() func numberOfRows() -> Int func cellViewModel(forRowAt indexPath: IndexPath) -> SystemTableCellViewModel func selectedRowAt(_ indexPath: IndexPath) func addGroup(_ group: Group) } final class GroupsViewModelImp: GroupsViewModel { // MARK: - Observers let reloadAction: PublishRelay<Void> = PublishRelay() let title: String = "groups_title".localized let newTitle: String = "new".localized private let disposeBag = DisposeBag() // MARK: - Delegate weak var delegate: GroupsViewModelDelegate? // MARK: - Variables private var groups: [Group] { didSet { reloadAction.accept(()) } } // MARK: - Initializer init() { self.groups = [] fetchGroups() } // MARK: - Main func addGroup(_ group: Group) { groups.append(group) } func insertTapped() { delegate?.groupsViewModelDidTapInsert() } private func fetchGroups() { let groupsMO: [GroupManagedObject]? = DatabaseManager.shared.fetch() let currencyService = CurrencyServiceImp() currencyService.fetchCurrencies() .subscribe(onNext: { [weak self] currencies in guard let accgGoupsMO = groupsMO else { return } let converter = DatabaseConverterImp(currencies: currencies) self?.groups = accgGoupsMO.map { converter.convertToGroup($0)! } }).disposed(by: disposeBag) } // MARK: - Table view methods func numberOfRows() -> Int { return groups.count } func cellViewModel(forRowAt indexPath: IndexPath) -> SystemTableCellViewModel { return groups[indexPath.row].toCellData() } func selectedRowAt(_ indexPath: IndexPath) { delegate?.groupsViewModel(didSelect: groups[indexPath.row]) } }
// // AlertController.swift // Ultra, Simple Browser // // Created by Peter Zhu on 15/2/13. // Copyright (c) 2015年 Peter Zhu. All rights reserved. // import UIKit class AlertController: UIAlertController { override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
// // ViewController.swift // PokeAPI // // Created by Etudiant on 16-11-24. // Copyright © 2016 Etudiant. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, typeChoisiDelegate, CapturerDelegate { var UrlPokemon = "https://pokeapi.co/api/v2/type/1" var RequeteUrl = URL(string: "") var pokemonUrlList = Array<Dictionary<String, String>>() var pokemonAfficherUrlList = Array<Dictionary<String, String>>() var pokemonList = Dictionary<String,Dictionary<String, Any>>() var pokemonImgList = Dictionary<String,UIImage>() var capturedList = Dictionary<String,Bool>() var nbCapture = 0; let limit = 1000 var etatBtCap = false @IBOutlet weak var btCapture: UIButton! @IBOutlet weak var monTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() monTableView.reloadData() returnTypeUrl(info: UrlPokemon) } func returnTypeUrl(info: String) { UrlPokemon = info print("le url de type \(info)") RequeteUrl = URL(string: UrlPokemon)! getPokemonListFromTypeUrl(leUrl: RequeteUrl!)//recherche de donné selon le url en paramêtre } func envoieDuType(info:String){ print("les infos de type\(info)") pokemonUrlList = Array<Dictionary<String, String>>() returnTypeUrl(info: info) monTableView.reloadData()//réception du type du VC type et changement des donné } func envoieDuLaCapture(info: String) { capturedList[info] = true monTableView.reloadData() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == "showType"{//segue vers les type let vcType:listeTypeViewController = segue.destination as! listeTypeViewController vcType.delegate = self }else if segue.identifier == "showPokemon"{//autres segue (vers pokemon et pokemonCapturer) //print("Autre segue\()") let laCell = sender as! PokemonTableViewCell if let leNom = laCell.champNom.text{ print("le nom sur click\(leNom)") let vcPokemon:PokemonViewController = segue.destination as! PokemonViewController vcPokemon.delegate = self if let lesInfos = pokemonList[leNom]{ vcPokemon.lePokemon = lesInfos } } }else if segue.identifier == "showPokemonCapturer"{//segue vers le pokemon let laCell = sender as! PokemonTableViewCell print("Show pokemon capturer go") if let leNom = laCell.champNom.text{ let vcPokemon:PokemonCapturerViewController = segue.destination as! PokemonCapturerViewController if let lesInfos = pokemonList[leNom]{ vcPokemon.lePokemon = lesInfos } } } } override func shouldPerformSegue(withIdentifier identifier: String?, sender: Any?) -> Bool {//vérification si possible de faire le segue print("should?") if let ident = identifier { if(ident == "showPokemon"){ let laCell = sender as! PokemonTableViewCell if let leNom = laCell.champNom.text{ print("ident3") if let pokemon = pokemonList[leNom]{ print("ident4") ////////Revoir la condition }else{ print("should not") return false } }// empêche de continuer sur la page d'un pokemon singulier si les infos ne sont pas chargé. //monTableView.reloadRows(at: [monTableView.indexPathForSelectedRow! as IndexPath], with: UITableViewRowAnimation(rawValue: 0)!)// reload la cellule cliqué si elle a fini de chargé. monTableView.reloadData() } } return true } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { pokemonAfficherUrlList = Array<Dictionary<String , String>>() if etatBtCap{//si le bouton capturer montre l'état true, seulement les pokémon capturé son affiché for pokemon in pokemonUrlList{ if let leId = pokemon["name"]{ if let leBool = capturedList[leId]{ if(leBool){ pokemonAfficherUrlList.append(pokemon) } } } } }else{//sinon tout les pokémon dans la list de url du type choisi sont montré pokemonAfficherUrlList = pokemonUrlList } return pokemonAfficherUrlList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //initie la cellulle let _id = pokemonAfficherUrlList[indexPath.row]["name"]! as String//cherche le id dans la liste var uneCell:PokemonTableViewCell if let _cap = capturedList[_id] as Bool!{ if (_cap){// si le pokemon est capturé associé choisi une cellule avec un identifiant différent uneCell = tableView.dequeueReusableCell(withIdentifier: "PokemonCapture") as! PokemonTableViewCell print("Captured 1 \(capturedList[_id])") }else{// sinon le po uneCell = tableView.dequeueReusableCell(withIdentifier: "Pokemon") as! PokemonTableViewCell } }else{//si la variable de capture n'existe pas? crée la variable et à false de base capturedList[_id] = false uneCell = tableView.dequeueReusableCell(withIdentifier: "Pokemon") as! PokemonTableViewCell } if let lePokemon = self.pokemonList[_id]{//si les info son stocker en variable? if (!lePokemon.isEmpty){//si les info ne sont pas vide afficherLesInfos(lesInfos: lePokemon, laCellulle: uneCell, leId: _id)//afficher le info et image dans la cellule self.afficherLesImages(lesInfos: (self.pokemonList[_id])!, laCellulle: uneCell, lesImg: self.pokemonImgList, leId: _id) }else{//sinon afficher la cellule de loading afficherLoading(laCellulle: uneCell) print("loading en cours\(_id)") } }else{// si les info n'existe pas? //RECHERCHE DES INFO if let _url = self.pokemonAfficherUrlList[indexPath.row]["url"] as String! {//rechercher selon le url afficherLoading(laCellulle: uneCell)//affiche la cellule de loading self.pokemonList[_id] = Dictionary<String,Any>()//prépare le tableau vide pour évité les requête double DispatchQueue.global().async { self.getPokemonFromUrl(leUrl: URL(string: _url)!, idPath:indexPath) } } } return uneCell } func afficherLoading(laCellulle:PokemonTableViewCell){ //AFFICHE LES INFO DE LOADING laCellulle.champNom.text = "Loading" laCellulle.champId.text = "???" laCellulle.img.image = UIImage(named: "pokemonSubstitute100x100.png") laCellulle.bgType.image = UIImage(named: "listeType-unknown.png") } func afficherLesInfos(lesInfos:Dictionary<String,Any>, laCellulle:PokemonTableViewCell, leId:String){ //AFFICHE LES INFOs if let _nom = lesInfos["name"] as? String { laCellulle.champNom.text = "\(_nom)" } if let _id = lesInfos["id"] as? Int { if(_id<10000){ laCellulle.champId.text = "\(_id)" } } //change le Background selon le type primaire du pokemon if let _lesTypes = lesInfos["types"] as? Array<Dictionary<String,Any>>{ for type in _lesTypes{ let _leType = type["type"] as? Dictionary<String,String> if let _nomType = _leType?["name"] as String!{ laCellulle.bgType.image = UIImage(named: "listeType-\(_nomType).png") } } } } func afficherLesImages(lesInfos:Dictionary<String,Any>,laCellulle:PokemonTableViewCell, lesImg:Dictionary<String,UIImage>, leId:String){ if let uneIMG = lesImg[leId]{//si l'image est déja chargé affiche la laCellulle.img.image = uneIMG }else{//sinon faire une requête if let _liens = lesInfos["sprites"] as? Dictionary<String,Any> { print("Liens trouvé") if let _lien = _liens["front_default"] as? String{ let _url = URL(string: _lien) if let _data = NSData(contentsOf: _url!) as? Data { let _img = UIImage(data: _data) self.pokemonImgList[leId] = _img! laCellulle.img.image = _img } } }else{//si la requête fail, retour à l'image par défault laCellulle.img.image = UIImage(named: "pokemonSubstitute100x100.png") } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func getPokemonListFromTypeUrl(leUrl : URL) { /// DispatchQueue.main.async ( execute: { //recherche de donné selon le type choisie if let _données = NSData(contentsOf: leUrl) as? Data { do { let json = try JSONSerialization.jsonObject(with: _données, options: JSONSerialization.ReadingOptions()) as? Dictionary<String, Any> print("Reception Json des liens") //print(json) var laList = Array<Dictionary<String, String>>() //memorise les liens dans un dictionaire dont la clé est leur nom for pokemon in json?["pokemon"] as! Array<Dictionary<String, Any>>{ laList.append(pokemon["pokemon"] as! [String : String]) } self.pokemonUrlList = laList //return json! } catch { print("\n\n#Erreur: Problème de conversion json:\(error)\n\n") } // do/try/catch } else { print("\n\n#Erreur: impossible de lire les données via:\(leUrl.absoluteString)\n\n") } // if let _données = NSData /// }) // DispatchQueue.main.async } func getPokemonFromUrl(leUrl : URL, idPath: IndexPath) { //requête de donné d'un pokemon spécifique //appellé pour les pokémon affiché seulement if let _données = NSData(contentsOf: leUrl) as? Data { do { let json = try JSONSerialization.jsonObject(with: _données, options: JSONSerialization.ReadingOptions()) as? Dictionary<String, Any> let id = json?["name"] as! String print("Conversion JSON du \(id)") self.pokemonList[id] = ( json as Dictionary<String, Any>!) //reload la cellule une fois les information chargé if(!etatBtCap){ //ne va pas essayer d'afficher des thread qui ne sont plus afficher lorque le tri est pour les pokemon capturé self.monTableView.reloadRows(at: [idPath], with: UITableViewRowAnimation(rawValue: 0)!) } } catch { print("\n\n#Erreur: Problème de conversion json:\(error)\n\n") } // do/try/catch } else { print("\n\n#Erreur: impossible de lire les données via:\(leUrl.absoluteString)\n\n") } // if let _données = NSData } @IBAction func rechercheCapture(_ sender: AnyObject) { etatBtCap = !etatBtCap if etatBtCap{//change l'état du bouton btCapture.setBackgroundImage(UIImage(named:"interface-13.png"), for: .normal ) }else{ btCapture.setBackgroundImage(UIImage(named:"interface-14.png"), for: .normal ) } //reload le tableau pour afficher ce qui doit l'être selon l'état du bt monTableView.reloadData() } }
import Foundation import XCTest @testable import Retry class RetryAsyncTests: XCTestCase { enum TestError: Error { case testError } //MARK: - async retries func testAsyncNoThrow() { var output = "" retryAsync { output += "try" } output += "-end" XCTAssertEqual(output, "try-end", "Didn't succed at first try") } func testAsyncDefaults() { let e1 = expectation(description: "retry end") var output = "" retryAsync { output += "try" throw TestError.testError } .finalDefer { e1.fulfill() } waitForExpectations(timeout: 1.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytrytry", "Didn't retry default(3) times asynchroniously") } } func testSyncMax() { let e1 = expectation(description: "retry end") var output = "" retryAsync (max: 5) { output += "try" throw TestError.testError } .finalDefer { e1.fulfill() } waitForExpectations(timeout: 1.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytrytrytrytry", "Didn't retry 5 times asynchroniously") } } //MARK: - async retries + final catch func testSyncMaxFinalCatch() { let e1 = expectation(description: "retry end") var output = "" retryAsync (max: 5) { output += "try" throw TestError.testError }.finalCatch {_ in output += "-catch" }.finalDefer { e1.fulfill() } waitForExpectations(timeout: 1.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytrytrytrytry-catch", "Didn't retry 5 times asynchroniously + catch") } } func testSyncMaxFinalCatchErrorMessage() { let e1 = expectation(description: "retry end") var output = "" retryAsync (max: 5) { output += "try" throw TestError.testError }.finalCatch {_ in output += "-\(TestError.testError)" } .finalDefer { e1.fulfill() } waitForExpectations(timeout: 1.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytrytrytrytry-testError", "Didn't retry 5 times asynchroniously + catch") } } //MARK: - sync retries + strategy //TODO: - how to check for the immediate strategy??? func testSyncMaxImmediate() { let e1 = expectation(description: "retry end") var output = "" var lastTime: UInt64? retryAsync (max: 5, retryStrategy: .immediate) { if let lastTime = lastTime { XCTAssertEqualWithAccuracy(StopWatch.deltaSince(t1: lastTime) , 0.001, accuracy: 0.01, "Didn't have the expected delay of 0") } output += "try" lastTime = mach_absolute_time() throw TestError.testError } .finalDefer { e1.fulfill() } waitForExpectations(timeout: 1.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytrytrytrytry", "Didn't retry 2 times asynchroniously") } } func testSyncMaxDelay() { let e1 = expectation(description: "retry end") var output = "" var lastTime: UInt64? retryAsync (max: 5, retryStrategy: .delay(seconds: 2.0)) { if let lastTime = lastTime { XCTAssertEqualWithAccuracy(StopWatch.deltaSince(t1: lastTime) , 2.0, accuracy: 0.2, "Didn't have the expected delay of 2.0") } output += "try" lastTime = mach_absolute_time() throw TestError.testError } .finalDefer { e1.fulfill() } waitForExpectations(timeout: 10.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytrytrytrytry", "Didn't retry 5 times asynchroniously") } } func testSyncMaxCustomRetryRepetitions() { let e1 = expectation(description: "retry end") var output = "" var lastTime: UInt64? retryAsync (max: 5, retryStrategy: .custom {count,_ in return count == 2 ? nil : 0} ) { if let lastTime = lastTime { XCTAssertEqualWithAccuracy(StopWatch.deltaSince(t1: lastTime) , 0.0, accuracy: 0.1, "Didn't have the expected delay of 2.0") } output += "try" lastTime = mach_absolute_time() throw TestError.testError } .finalDefer { e1.fulfill() } waitForExpectations(timeout: 10.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytrytry", "Didn't retry 3 times asynchroniously") } } func testSyncMaxCustomRetryDelay() { let e1 = expectation(description: "retry end") var output = "" var lastTime: UInt64? var lastTestDelay: TimeInterval = 0.0 retryAsync (max: 3, retryStrategy: .custom {count, lastDelay in return (lastDelay ?? 0.0) + 1.0} ) { if let lastTime = lastTime { lastTestDelay += 1.0 let stopTime = StopWatch.deltaSince(t1: lastTime) //if only XCTAssertEqualWithAccuracy worked ... XCTAssert(stopTime > (lastTestDelay - lastTestDelay/10.0) && stopTime < (lastTestDelay + lastTestDelay/10.0), "Didn't have the correct delay, expected \(lastTestDelay) timed \(stopTime)") } output += "try" lastTime = mach_absolute_time() throw TestError.testError } .finalDefer { e1.fulfill() } waitForExpectations(timeout: 5.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytrytry", "Didn't retry 3 times asynchroniously") } } //MARK: - sync successful func testSuccessFirstTry() { let e1 = expectation(description: "retry end") var output = "" retryAsync { output += "try" } .finalCatch {_ in output += "-catch" } .finalDefer { output += "-defer" e1.fulfill() } waitForExpectations(timeout: 1.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "try-defer", "Didn't succeed") } } func testSuccessSecondTry() { let e1 = expectation(description: "retry end") var output = "" var succeed = false retryAsync (max: 3) { output += "try" if !succeed { succeed = true throw TestError.testError } }.finalCatch {_ in output += "-catch" } .finalDefer { e1.fulfill() } waitForExpectations(timeout: 10.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytry", "Didn't succeed at second try") } } func testSuccessSecondTryDelayed() { let e1 = expectation(description: "retry end") var output = "" var succeed = false retryAsync (max: 3, retryStrategy: .custom(closure: {_, _ in return 1.0})) { output += "try" if !succeed { succeed = true throw TestError.testError } }.finalCatch {_ in output += "-catch" } .finalDefer { e1.fulfill() } waitForExpectations(timeout: 5.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytry", "Didn't succeed at second try") } } func testAsyncFromBackgroundQueue() { let e1 = expectation(description: "final Defer") var output = "" DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async { retryAsync (max: 3, retryStrategy: .immediate) { output.append("try") throw TestError.testError }.finalCatch {_ in output.append("-catch") }.finalDefer { e1.fulfill() } } waitForExpectations(timeout: 2.0) {error in XCTAssertTrue(error == nil) XCTAssertEqual(output, "trytrytry-catch", "Didn't succeed at the third try") } } }
// // UserResponse.swift // carWash // // Created by Juliett Kuroyan on 05.12.2019. // Copyright © 2019 VooDooLab. All rights reserved. // // MARK: - UserResponse struct UserResponse: Codable { var status: String? var message: String? var data: UserResponseData var monthCashBack: [Cashback] private enum CodingKeys : String, CodingKey { case status, message, data, monthCashBack = "month_cash_back" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.status = try? container.decode(String.self, forKey: .status) self.message = try? container.decode(String.self, forKey: .message) self.data = try container.decode(UserResponseData.self, forKey: .data) self.monthCashBack = try container.decode([Cashback].self, forKey: .monthCashBack) } } // MARK: - UserResponseData struct UserResponseData: Codable { var id: Int var name: String? var phone: String var city: String var balance: Int? var monthSpent: Int var email: String? var emailVerifiedAt: String? var lastSmsSendAt: String? var createdAt: String? var updatedAt: String? private enum CodingKeys : String, CodingKey { case id, name, phone, city, balance, email, emailVerifiedAt = "email_verified_at", lastSmsSendAt = "last_sms_send_at", createdAt = "created_at", updatedAt = "updated_at", monthSpent = "month_spent" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) id = try container.decode(Int.self, forKey: .id) name = try? container.decode(String.self, forKey: .name) phone = try container.decode(String.self, forKey: .phone) balance = try? container.decode(Int?.self, forKey: .balance) city = try container.decode(String.self, forKey: .city) if let _ = balance { balance! /= 100 } self.monthSpent = try container.decode(Int.self, forKey: .monthSpent) / 100 self.email = try? container.decode(String?.self, forKey: .email) self.emailVerifiedAt = try? container.decode(String?.self, forKey: .emailVerifiedAt) self.lastSmsSendAt = try? container.decode(String?.self, forKey: .lastSmsSendAt) self.createdAt = try? container.decode(String?.self, forKey: .createdAt) self.updatedAt = try? container.decode(String?.self, forKey: .updatedAt) } } struct Cashback: Codable { var percent: Int var value: Int init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.percent = try container.decode(Int.self, forKey: .percent) self.value = try container.decode(Int.self, forKey: .value) / 100 } }
// // CFPlaceholderTextView.swift // 花菜微博 // // Created by 花菜 on 2017/1/13. // Copyright © 2017年 花菜ChrisCai. All rights reserved. // import UIKit class CFPlaceholderTextView: UITextView { var emoticonString: String { // 创建可变字符串, var restulString = String() if let attr = attributedText { let range = NSRange(location: 0, length: attr.length) attr.enumerateAttributes(in: range, options: [], using: { (dict, range, _) in // 获取附件,并从附件中获取图片表情对应的文本 if let attachment = dict["NSAttachment"] as? CFEmoticonAttachment, let chs = attachment.chs { restulString += chs } else { restulString += (attr.string as NSString).substring(with: range) } }) } return restulString } var placeholder: String? { didSet { setNeedsDisplay() } } var placeholderColor = UIColor.white { didSet { setNeedsDisplay() } } override var font: UIFont? { didSet { setNeedsDisplay() } } override var text: String! { didSet { setNeedsDisplay() } } override var attributedText: NSAttributedString! { didSet { setNeedsDisplay() } } override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) setupUI() font = UIFont.systemFont(ofSize: 14) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } override func draw(_ rect: CGRect) { if self.hasText { return } var attrs = [String: AnyObject]() attrs[NSForegroundColorAttributeName] = placeholderColor if let font = font { attrs[NSFontAttributeName] = font } else { attrs[NSFontAttributeName] = UIFont.systemFont(ofSize: 14) } let x: CGFloat = 5 let y: CGFloat = 8 let w: CGFloat = self.frame.size.width - 2 * x let h: CGFloat = self.frame.size.height - 2 * y let placeholderRect = CGRect(x: x, y: y, width: w, height: h) if let placeholder = placeholder { (placeholder as NSString).draw(in: placeholderRect, withAttributes: attrs) } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { setNeedsDisplay() } deinit { NotificationCenter.default.removeObserver(self) self.removeObserver(self, forKeyPath: "contentOffset") } } fileprivate extension CFPlaceholderTextView { func setupUI() { NotificationCenter.default.addObserver(self, selector: #selector(textDidChange), name: NSNotification.Name.UITextViewTextDidChange, object: nil) self.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil) } @objc func textDidChange() { setNeedsDisplay() } } extension CFPlaceholderTextView { /// 向文本视图插入表情 /// /// - Parameter em: 表情模型 func inserEmoticon(_ em: CFEmoticon?) { guard let em = em else { deleteBackward() return } // 插入 emoji 表情 if let emoji = em.emoji, let range = selectedTextRange { replace(range, withText: emoji) return } // 插入图片表情 // 获取表情文本 let imageText = em.imageText(font: font!) // 获取 textView 属性文本,并转换为可变 let attrM = NSMutableAttributedString(attributedString: attributedText) // 将图片的表情文本插入到 textView 属性文本中 // 获取光标位置 let range = selectedRange attrM.replaceCharacters(in: selectedRange, with: imageText) // 重新赋值给 textView attributedText = attrM // 恢复光标位置,此处 length 不能使用 range.lengt -> 是选的字符总长 -> 可能会多选,此处应使用0 selectedRange = NSRange(location: range.location + 1, length: 0) // 通知代理文本改变 delegate?.textViewDidChange?(self) // 重绘占位文本 textDidChange() } }
// // Color.swift // Colors // // Created by Alex Davis on 4/5/19. // Copyright © 2019 Alex Davis. All rights reserved. // import UIKit struct Color { let name: String let uiColor: UIColor }
// // LoginViewController.swift // sevenloan // // Created by spectator Mr.Z on 2018/12/3. // Copyright © 2018 tangxers. All rights reserved. // import UIKit import Foundation import Alamofire import SwiftyJSON class LoginViewController: SNBaseViewController { var model:[TokenModel] = [] let banner = UIImageView().then { $0.image = Image("logo") } let baseView = UIView().then{ $0.backgroundColor = Color(0xffffff) $0.layer.cornerRadius = fit(20) } let titleLabel = UILabel().then { $0.textColor = Color(0x2a3457) $0.text = "用户登录" $0.font = Font(36) } let usernameView = LoginInputView().then{ $0.backgroundColor = Color(0xffffff) } let passwordView = LoginInputView().then{ $0.backgroundColor = Color(0xffffff) } let forgetPassordButton = UIButton().then { $0.setTitle("忘记密码", for: .normal) $0.setTitleColor(Color(0x2777ff), for: .normal) $0.titleLabel?.font = Font(30) } let loginButton = BGButton().then { $0.set(content: "登 录") } let registerButton = BorderButton().then { $0.set(content: "会员注册") } var popCallBack: (()->())? } extension LoginViewController { override func loadData() { } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.isTranslucent = true navigationController?.navigationBar.isHidden = true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) navigationController?.navigationBar.isHidden = false navigationController?.navigationBar.isTranslucent = false } /// setup view -- 加载视图 override func setupView() { navigationController?.navigationBar.isTranslucent = true navigationController?.navigationBar.isHidden = true view.backgroundColor = UIColor.init(patternImage: UIImage(named: "login_bg")!) view.addSubviews(views: [banner,baseView,registerButton]) baseView.addSubviews(views: [titleLabel,usernameView,passwordView,forgetPassordButton,loginButton]) passwordView.textField.isSecureTextEntry = true usernameView.textField.keyboardType = .numberPad banner.snp.makeConstraints { (make) in make.top.snEqualToSuperview().snOffset(185) make.centerX.equalToSuperview() make.height.snEqualTo(156) make.width.snEqualTo(190) } baseView.snp.makeConstraints { (make) in make.top.equalTo(banner.snp.bottom).snOffset(98) make.left.equalToSuperview().snOffset(30) make.right.equalToSuperview().snOffset(-30) make.height.snEqualTo(600) } titleLabel.snp.makeConstraints { (make) in make.left.equalToSuperview().snOffset(47) make.top.equalToSuperview().snOffset(60) } usernameView.snp.makeConstraints { (make) in make.top.equalTo(titleLabel.snp.bottom).snOffset(33) make.height.snEqualTo(100) make.left.equalToSuperview() make.right.equalToSuperview() } passwordView.snp.makeConstraints { (make) in make.top.snEqualTo(usernameView.snp.bottom) make.height.snEqualTo(100) make.left.equalToSuperview() make.right.equalToSuperview() } forgetPassordButton.snp.makeConstraints { (make) in make.left.snEqualToSuperview().snOffset(55) make.top.snEqualTo(passwordView.snp.bottom).snOffset(33) make.height.snEqualTo(30) } loginButton.snp.makeConstraints { (make) in make.left.snEqualToSuperview().snOffset(45) make.right.snEqualToSuperview().snOffset(-45) make.height.snEqualTo(90) make.top.equalTo(forgetPassordButton.snp.bottom).snOffset(30) } registerButton.snp.makeConstraints { (make) in make.bottom.snEqualToSuperview().snOffset(-70) make.centerX.snEqualToSuperview() make.width.snEqualTo(260) make.height.snEqualTo(78) } usernameView.set(title: "账号", placeholder: "请输入登录账号") passwordView.set(title: "密码", placeholder: "请输入密码") loginButton.layer.cornerRadius = fit(50) registerButton.layer.cornerRadius = fit(35) } func getRootViewController() -> UIViewController? { let window = (UIApplication.shared.delegate?.window)! assert(window != nil, "The window is empty") return window?.rootViewController } func getCurrentViewController() -> UIViewController? { var currentViewController: UIViewController? = getRootViewController() let runLoopFind = true while runLoopFind { if currentViewController?.presentedViewController != nil { currentViewController = currentViewController?.presentedViewController } else if (currentViewController is UINavigationController) { let navigationController = currentViewController as? UINavigationController currentViewController = navigationController?.children.last } else if (currentViewController is UITabBarController) { let tabBarController = currentViewController as? UITabBarController currentViewController = tabBarController?.selectedViewController } else { let childViewControllerCount = currentViewController?.children.count if childViewControllerCount! > 0 { currentViewController = currentViewController!.children.last return currentViewController } else { return currentViewController } } } } @objc func loginAction(){ if usernameView.textField.text! == ""{ SZHUD("请输入登录账号", type: .info, callBack: nil) return } if passwordView.textField.text! == ""{ SZHUD("请输入登录密码", type: .info, callBack: nil) return } let para = ["phone":usernameView.textField.text!,"pwd":passwordView.textField.text!] let url = httpUrl + "/user/validateCredentials" Alamofire.request(url, method: .post, parameters:para, headers: nil).responseJSON { [unowned self](res) in let jsonData = JSON(data: res.data!) CNLog(jsonData) if jsonData["code"].intValue == 1000{ //登录成功数据解析 let jsonObj = jsonData["data"] self.model = jsonObj.arrayValue.compactMap { TokenModel(jsonData: $0) } XKeyChain.set(self.model[0].token, key: TOKEN) XKeyChain.set(self.usernameView.textField.text!, key: PHONE) XKeyChain.set(self.model[0].uid, key: UITOKEN_UID) self.dismiss(animated: true, completion: nil) }else{ if !jsonData["msg"].stringValue.isEmpty{ SZHUD(jsonData["msg"].stringValue , type: .info, callBack: nil) }else{ SZHUD("请求错误" , type: .error, callBack: nil) } } } } @objc func registerAction(){ self.present(RegisterViewController(), animated: true, completion: nil) } @objc func forgetPasswordAction(){ self.present(ForgetPasswordViewController(), animated: true, completion: nil) // self.present(UpdatePasswordController(), animated: true, completion: nil) } override func bindEvent() { loginButton .addTarget(self, action: #selector(loginAction), for: .touchUpInside) registerButton .addTarget(self, action: #selector(registerAction), for: .touchUpInside) forgetPassordButton .addTarget(self, action: #selector(forgetPasswordAction), for: .touchUpInside) } }
// // CharacterExtension.swift // Nalssi // // Created by Corentin Redon on 6/29/18. // Copyright © 2018 mti. All rights reserved. // import Foundation extension Character { var asciiValue: Int { return Int(self.unicodeScalars.filter{$0.isASCII}.first?.value ?? 0) } static func -(left: Character, right: Character) -> Int { return left.asciiValue - right.asciiValue } }
// // NotesListVC.swift // NasiShadchanHelper // // Created by apple on 08/10/20. // Copyright © 2020 user. All rights reserved. // import UIKit import Firebase class NotesListVC: UIViewController { @IBOutlet weak var tblVwNotes: UITableView! @IBOutlet weak var vwBgPlaceholder: UIView! var girlId : String? var ref: DatabaseReference! var notesArr = [[String : String]]() override func viewDidLoad() { super.viewDidLoad() self.setUpUi() self.title = "Notes" getFavUserNotes() } func setUpUi() { tblVwNotes.register(NotesTableCell.self) //self.setBackBtn() } @IBAction func btnAddNotesTapped(_ sender: Any) { let vcAddNotesVC = self.storyboard?.instantiateViewController(withIdentifier: "AddNotesVC") as! AddNotesVC vcAddNotesVC.hidesBottomBarWhenPushed = true vcAddNotesVC.girlId = girlId vcAddNotesVC.editNote = false self.navigationController?.pushViewController(vcAddNotesVC, animated: true) } func getFavUserNotes() { self.view.showLoadingIndicator() guard let myId = UserInfo.curentUser?.id, let gID = girlId else { print("data nil") return } self.notesArr.removeAll() ref = Database.database().reference() ref.child("favUserNotes").child(myId).observe(.childAdded) { (snapShot) in self.view.hideLoadingIndicator() if var snap = snapShot.value as? [String : String] { snap["key"] = snapShot.key self.notesArr.append(snap) }else{ print("invalid data") } print("user notes :-") let dict:[[String:String]] = self.notesArr.filter{($0["userId"] as! String) == gID} self.notesArr = dict // self.tblVwNotes.reloadData() self.displayDataInNotes() } if notesArr.count > 0 { } else { self.view.hideLoadingIndicator() self.displayDataInNotes() } } func displayDataInNotes() { if notesArr.count > 0 { self.tblVwNotes.isHidden = false self.vwBgPlaceholder.isHidden = true self.tblVwNotes.reloadData() } else { self.tblVwNotes.isHidden = true self.vwBgPlaceholder.isHidden = false } } // MARK: -Status Bar Style override var preferredStatusBarStyle: UIStatusBarStyle { return .default } } // MARK:- TableViewDelegates&Datasource extension NotesListVC : UITableViewDelegate,UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.notesArr.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableview(tableView, notesTableCell: indexPath) } func tableview(_ tableview: UITableView, notesTableCell indexPath : IndexPath) -> UITableViewCell { let cell = tblVwNotes.deque(NotesTableCell.self, at: indexPath) cell.vwBg.addRoundedViewCorners(width: 10, colorBorder: UIColor.clear) cell.vwBg.addDropShadow() cell.noteLbl.text = notesArr[indexPath.row]["note"] ?? "" cell.deleteBtn.tag = indexPath.row cell.editBtn.tag = indexPath.row cell.deleteBtn.addTarget(self, action: #selector(deleteNote(_:)), for: .touchUpInside) cell.editBtn.addTarget(self, action: #selector(editNote(_:)), for: .touchUpInside) return cell } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.0001 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } @objc func deleteNote(_ sender : UIButton) { guard let myId = UserInfo.curentUser?.id, let noteKey = notesArr[sender.tag]["key"] else { print("data nil") return } ref = Database.database().reference() ref.child("favUserNotes").child(myId).child(noteKey).removeValue() getFavUserNotes() } @objc func editNote(_ sender : UIButton){ let vcAddNotesVC = self.storyboard?.instantiateViewController(withIdentifier: "AddNotesVC") as! AddNotesVC vcAddNotesVC.girlId = girlId vcAddNotesVC.editNote = true vcAddNotesVC.prevData = notesArr[sender.tag] vcAddNotesVC.delegate = self vcAddNotesVC.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(vcAddNotesVC, animated: true) } } extension NotesListVC : reloadNoteDelegate { func reloadNotes() { getFavUserNotes() } }
// // MenuCell.swift // Turkey // // Created by Evelio Tarazona on 11/6/16. // Copyright © 2016 Evelio Tarazona. All rights reserved. // import Foundation import UIKit class MenuCell: UITableViewCell { @IBOutlet weak var menuLabel: UILabel! }
// // TVAPI.swift // jan15 // // Created by 황현지 on 2021/01/15. // import Foundation
// // Colors.swift // Emergencias Pediatricas // // Created by Anderson Alencar on 20/09/20. // import Foundation import UIKit extension UIColor { static let backgroundSystemColor = UIColor(red: 0.96, green: 1.00, blue: 1.00, alpha: 1.00) static let acessoryColor = UIColor(red: 0.67, green: 0.85, blue: 0.90, alpha: 1.00) static let buttonColor = UIColor(red: 0.13, green: 0.80, blue: 0.80, alpha: 1.00) static let acessoryTextColor = UIColor(red: 0.29, green: 0.29, blue: 0.29, alpha: 1.00) }
// // TableViewController.swift // todoListapp // // Created by havisha tiruvuri on 9/15/17. // Copyright © 2017 havisha tiruvuri. All rights reserved. // import UIKit import CoreData class TableViewController: UITableViewController, todolistdelegate{ var list = [Todolist]() // var list = [["book","notes on the book","9/13/2017"],"book","notes on the book","9/13/2017"]] let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext //scrach pad where we can add and delete stuff @IBOutlet var tableview: UITableView! func fetchAllItems() { let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Todolist") do { let result = try managedObjectContext.fetch(request) list = result as! [Todolist] } catch { print("\(error)") } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return list.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "todolistview") as! TableViewCell cell.TitleLabel?.text = list[indexPath.row].title cell.NotesLabel?.text = list[indexPath.row].notes cell.DateLabel?.text = list[indexPath.row].date if list[indexPath.row].checklist == false { cell.accessoryType = UITableViewCellAccessoryType.none } else { cell.accessoryType = UITableViewCellAccessoryType.checkmark } return cell } // tableview add @IBAction func addButton(_ sender: UIBarButtonItem) { performSegue(withIdentifier: "additem", sender: sender) } // override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath:IndexPath) { // // performSegue(withIdentifier: "additem", sender: indexPath) // // } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "additem" { let controller = segue.destination as! ViewController controller.delegate = self } } func add(by: UIViewController, title: String, notes: String, date: String){ let item = NSEntityDescription.insertNewObject(forEntityName: "Todolist", into: managedObjectContext) as! Todolist item.title = title item.date = date item.notes = notes item.checklist = false list.append(item) do { try managedObjectContext.save() } catch { print("\(error)") } tableView.reloadData() // dismiss(animated: true, completion: nil) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //add check mark when the user type the cell if tableView.cellForRow(at: indexPath)?.accessoryType == UITableViewCellAccessoryType.checkmark { tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.none list[indexPath.row].checklist = false } else { tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCellAccessoryType.checkmark list[indexPath.row].checklist = true } do { try managedObjectContext.save() } catch { print("\(error)") } } override func viewDidLoad() { super.viewDidLoad() fetchAllItems() // print(x) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // MyProfileViewController.swift // PupCare // // Created by Uriel Battanoli on 7/11/16. // Copyright © 2016 PupCare. All rights reserved. // import UIKit import Parse class MyProfileViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, AddAddressDelegate { // MARK: Outlets @IBOutlet weak var tableView: UITableView! // MARK: Variables fileprivate let numberOfSections = 3 fileprivate let numberOfRowSection0 = 1 fileprivate var numberOfRowSection1 = 5 fileprivate let numberOfRowSection2 = 1 fileprivate let numberOfRowSectionShrunk = 2 var section1Expanded = false var section2Expanded = false var user: User! var imageProfile: UIImageView?{ didSet{ let gest = UITapGestureRecognizer(target: self, action: #selector(self.didPressPhoto)) self.imageProfile!.addGestureRecognizer(gest) } } // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() if UserManager.sharedInstance.user == nil{ UserManager.sharedInstance.createUserByCurrentUser() } self.user = UserManager.sharedInstance.user } override func viewDidAppear(_ animated: Bool) { AddressManager.sharedInstance.getAddressListFromUser(self.user.userId!) { (addresses) in if addresses.count > self.user.addressList.count { self.user.addressList = addresses UserManager.sharedInstance.user?.addressList = addresses } } self.tableView.reloadSections(IndexSet(integer: 1), with: .automatic) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Table View Data Source func numberOfSections(in tableView: UITableView) -> Int { return self.numberOfSections } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { self.numberOfRowSection1 = self.user.addressList.count + 5 switch section { case 0: return self.numberOfRowSection0 case 1 where self.section1Expanded: return self.numberOfRowSection1 case 2 where self.section2Expanded: return self.numberOfRowSection2 default: print("default section\(section)") } return self.numberOfRowSectionShrunk } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let separator = tableView.dequeueReusableCell(withIdentifier: "cellSeparator")! let cell = tableView.dequeueReusableCell(withIdentifier: "cellProfileDetail") as! MyProfileDetailTableViewCell let section = tableView.dequeueReusableCell(withIdentifier: "cellProfileSection") as! MyProfileDetailTableViewCell switch (indexPath as NSIndexPath).section { case 0: let profile = tableView.dequeueReusableCell(withIdentifier: "cellProfile") as! MyProfileTableViewCell profile.photoUrl = user.photoUrl self.imageProfile = profile.imageProfile return profile case 1 where (indexPath as NSIndexPath).row == 0: section.string = "Dados Pessoais" if !self.section1Expanded{ section.changeConstraintSize(0) } else{ section.changeConstraintSize(-15) } section.setCorner() return section case 1 where (indexPath as NSIndexPath).row == 1: if !self.section1Expanded{ return separator } cell.string = self.user.name case 1 where (indexPath as NSIndexPath).row == 2: cell.string = self.user.email case 1 where (indexPath as NSIndexPath).row > 2 && (indexPath as NSIndexPath).row < self.numberOfRowSection1-1: let addressCell = tableView.dequeueReusableCell(withIdentifier: "cellAddress") as! MyProfileAddressTableViewCell if (indexPath as NSIndexPath).row == self.numberOfRowSection1-2{ addressCell.setCorner() addressCell.lblAddress.text = "Adicionar novo endereço" addressCell.imageAddress.image = UIImage(named: "moreBt") return addressCell } addressCell.imageAddress.image = nil addressCell.address = self.user.addressList[(indexPath as NSIndexPath).row-3] return addressCell case 1 where (indexPath as NSIndexPath).row == self.numberOfRowSection1-1: return separator case 2 where (indexPath as NSIndexPath).row == 0: let logOut = tableView.dequeueReusableCell(withIdentifier: "cellLogOut") as! MyProfileDetailTableViewCell logOut.string = "Sair" logOut.setCorner() return logOut case 2 where (indexPath as NSIndexPath).row == 1: return separator default: print("default section in cell for row") } return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if (indexPath as NSIndexPath).section == 1{ if (indexPath as NSIndexPath).row > 2 && (indexPath as NSIndexPath).row < self.numberOfRowSection1-2{ return true } } return false } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { switch editingStyle { case .delete: if (indexPath as NSIndexPath).section == 1{ let address = self.user.addressList[(indexPath as NSIndexPath).row-3] AddressManager.sharedInstance.removeAddressFromParse(address) self.user.addressList.remove(at: (indexPath as NSIndexPath).row-3) self.numberOfRowSection1 -= 1 tableView.deleteRows(at: [indexPath], with: .fade) } default: print("default commitEditing") } } // MARK: Table View Delegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch (indexPath as NSIndexPath).section { case 1 where (indexPath as NSIndexPath).row == 0: self.section1Expanded = !self.section1Expanded self.tableView.reloadSections(IndexSet(integer: (indexPath as NSIndexPath).section), with: .fade) case 1 where (indexPath as NSIndexPath).row > 2 && (indexPath as NSIndexPath).row < self.numberOfRowSection1-1: if (indexPath as NSIndexPath).row == self.numberOfRowSection1-2{ performSegue(withIdentifier: "goToAddAddress", sender: nil) return } let address = self.user.addressList[(indexPath as NSIndexPath).row-3] performSegue(withIdentifier: "goToAddAddress", sender: address) case 2: self.didPressLogOut() default: print("default didSelect") } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if (indexPath as NSIndexPath).section == 0{ return 255 } else if (indexPath as NSIndexPath).row == 0{ return 45 } else if ((indexPath as NSIndexPath).section == 1 && (indexPath as NSIndexPath).row == numberOfRowSection1-1)||((indexPath as NSIndexPath).section == 2 && (indexPath as NSIndexPath).row == self.numberOfRowSection2-1) || (!self.section1Expanded && (indexPath as NSIndexPath).section == 1) || (!self.section2Expanded && (indexPath as NSIndexPath).section == 2){ return 20 } return 40 } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let deleteBt = UITableViewRowAction(style: .default, title: "Remover") { (acton, indexPath) in self.tableView.dataSource?.tableView!( self.tableView, commit: .delete, forRowAt: indexPath) return } deleteBt.backgroundColor = UIColor(red: 165, green: 22, blue: 25) return [deleteBt] } // MARK: Functions func didPressPhoto(_ obj: AnyObject) { print(obj) } func didPressLogOut() { UserManager.sharedInstance.logOutUser { if let vcLoginProfile = self.tabBarController?.viewControllers![3].childViewControllers[0].childViewControllers[0] as? Login_ProfileViewController { vcLoginProfile.updateView() } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier! { // case "logInSegue": // segue.destination.childViewControllers[0] as! LoginViewController case "goToAddAddress": let addressVC = segue.destination as! AddressViewController addressVC.delegate = self if let address = sender as? Address{ addressVC.address = address } default: print("default prepareForSegue") } } // MARK: Address delegate func addressAdded(_ address: Address){ if !self.user.addressList.contains(address){ self.user.addressList.append(address) } self.tableView.reloadSections(IndexSet(integer: 1), with: .fade) } }
// // GenresViewModel.swift // The Movie DB // // Created by v.a.jayachandran on 23/5/20. // Copyright © 2020 v.a.jayachandran. All rights reserved. // import Foundation struct DiscoverViewModel { let movies: [Movie] }
// // SMConstants.swift // sensmove // // Created by RIEUX Alexandre on 16/05/2015. // Copyright (c) 2015 ___alexprod___. All rights reserved. // import Foundation import UIKit import CoreBluetooth let blockDelimiter = "$" let rightInsoleMarkup = "@" let leftInsoleMarkup = "*" let insoleName = "coco" //MARK: UUID Retrieval func uartServiceUUID()->CBUUID{ return CBUUID(string: "6e400001-b5a3-f393-e0a9-e50e24dcca9e") } func txCharacteristicUUID()->CBUUID{ return CBUUID(string: "6e400002-b5a3-f393-e0a9-e50e24dcca9e") } func rxCharacteristicUUID()->CBUUID{ return CBUUID(string: "6e400003-b5a3-f393-e0a9-e50e24dcca9e") } func deviceInformationServiceUUID()->CBUUID{ return CBUUID(string: "180A") } func hardwareRevisionStringUUID()->CBUUID{ return CBUUID(string: "2A27") } func manufacturerNameStringUUID()->CBUUID{ return CBUUID(string: "2A29") } func modelNumberStringUUID()->CBUUID{ return CBUUID(string: "2A24") } func firmwareRevisionStringUUID()->CBUUID{ return CBUUID(string: "2A26") } func softwareRevisionStringUUID()->CBUUID{ return CBUUID(string: "2A28") } func serialNumberStringUUID()->CBUUID{ return CBUUID(string: "2A25") } func systemIDStringUUID()->CBUUID{ return CBUUID(string: "2A23") } func dfuServiceUUID()->CBUUID{ return CBUUID(string: "00001530-1212-efde-1523-785feabcd123") } func UUIDsAreEqual(firstID:CBUUID, secondID:CBUUID)->Bool { return firstID.representativeString() == secondID.representativeString() }
// // TopMoviesViewController.swift // TheMovies // // Created by Usman Ansari on 29/03/21. // /**View controller Used to show collection of top ten poster images*/ import UIKit class PopularTopMoviesViewController: UIViewController { var presenter : MoviesListPresenterInterface? @IBOutlet weak var collectionView: UICollectionView! let sectionInsets = UIEdgeInsets(top: 20.0, left: 20.0, bottom: 20.0, right: 20.0) @IBOutlet weak var activityIndicator: UIActivityIndicatorView! // MARK: - Life cycle methods override func viewDidLoad() { super.viewDidLoad() self.activityIndicator.hidesWhenStopped = true self.navigationItem.title = self.presenter?.navigationTitle presenter?.viewDidLoad() } } // MARK: - Extension MoviesListPresenterOutputDelegate extension PopularTopMoviesViewController: MoviesListPresenterOutputDelegate { func showMovies() { DispatchQueue.main.async { self.collectionView.reloadData() } } func showError(errorModel: ErrorMovieViewModel) { DispatchQueue.main.async { let errorAlert : UIAlertController = UIAlertController(title: errorModel.title, message: errorModel.message, preferredStyle: UIAlertController.Style.alert) let okAction: UIAlertAction = UIAlertAction(title: NSLocalizedString("Ok", comment: ""), style: UIAlertAction.Style.cancel) { ACTION -> Void in } errorAlert.addAction(okAction) self.present(errorAlert, animated: true, completion: nil) } } func showLoading() { DispatchQueue.main.async { self.activityIndicator.startAnimating() } } func hideLoading() { DispatchQueue.main.async { self.activityIndicator.stopAnimating() } } }
// // AddRecordVC.swift // DemoSwift // // Created by Megha on 19/11/17. // Copyright © 2017 com.parmar. All rights reserved. // import UIKit import CoreData class AddRecordVC: UIViewController,UITextFieldDelegate { @IBOutlet weak var txtAddress: UITextField! @IBOutlet weak var txtName: UITextField! @IBOutlet weak var txtNo: UITextField! @IBAction func btnSave(_ sender: Any) { btnAddRecord(); } //let context =[AppDelegate .performSelector(onMainThread: <#T##Selector#>, with: <#T##Any?#>, waitUntilDone: <#T##Bool#>)] //let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext // MARK: UIView Method override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: CoreDatabase func btnAddRecord(){ let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let studentObj = NSEntityDescription.insertNewObject(forEntityName:"Student", into: context) as! Student studentObj.name = txtName.text studentObj.number = txtNo.text studentObj.address = txtAddress.text // Stream let streameObj = NSEntityDescription.insertNewObject(forEntityName:"Stream", into: context) as! Stream streameObj.science = "12" streameObj.commerce = "11" streameObj.artce = "11" do { try context.save() print("Add record success") self.navigationController!.popViewController(animated: true) } catch { print("Failed saving") } } } //
import Foundation class Deck : NSObject { static let allSpades: [Card] = Value.allValues.map{Card(c: Color.Spade, v: $0)}; static let allClubs: [Card] = Value.allValues.map{Card(c: Color.Club, v: $0)}; static let allHearts: [Card] = Value.allValues.map{Card(c: Color.Heart, v: $0)}; static let allDiamonds: [Card] = Value.allValues.map{Card(c: Color.Diamond, v: $0)}; static let allCards: [Card] = allSpades + allHearts + allClubs + allDiamonds var cards: [Card]; var discards: [Card]; var outs: [Card]; override var description: String { return ("\(cards)"); } init(sorted: Bool) { self.cards = Deck.allCards; self.discards = []; self.outs = []; if (!sorted) { self.cards.shuffle(); } } func draw() -> Card? { var card: Card; if (self.cards.count == 0) { return (nil); } card = self.cards[0]; self.outs.append(card); self.cards.remove(at: 0); return (card); } func fold(c: Card) { if (self.outs.contains(c)) { self.outs.remove(at: self.outs.index(of: c)!); self.discards.append(c); } } } extension Array { mutating func shuffle() { var i: Int; let rounds = self.count * (self.count / 2); for _ in 0...rounds { i = Int(arc4random_uniform(UInt32(self.count))); self.append(self[i]); self.remove(at: i); } } }
/// Anything that represents a FieldName /// /// Either a String or a Type-Safe querylanguage object public protocol FieldNameRepresentable { var fieldName: String { get } } /// Allows a String to represent a field name extension String: FieldNameRepresentable { public var fieldName: String { return self } } /// Generic errors you can throw in the ORM when (de)serializing public enum ORMError: Error { case missingKey(String) } public protocol Application { associatedtype DB: Database static var database: DB! { get } } public protocol Routable {} public protocol WebServerApplication: Application { associatedtype R: Routable } public struct Sort: ExpressibleByDictionaryLiteral { public enum Order { case ascending case descending } public var order: [String: Order] = [:] public init(dictionaryLiteral elements: (FieldNameRepresentable, Order)...) { for (key, order) in elements { self.order[key.fieldName] = order } } } public protocol SerializableObject { associatedtype SupportedValue init(dictionary: [String: SupportedValue]) func getValue(forKey key: String) -> SupportedValue? mutating func setValue(to newValue: SupportedValue?, forKey key: String) func getKeys() -> [String] func getValues() -> [SupportedValue] func getKeyValuePairs() -> [String: SupportedValue] } public protocol IdentifierType : Hashable, Equatable { } public protocol DatabaseEntity: SerializableObject { associatedtype Identifier: IdentifierType static var defaultIdentifierField: String { get } func getIdentifier() -> Identifier? } public protocol Table { associatedtype Query associatedtype Entity: DatabaseEntity func store(_ entity: Entity) throws func find(matching query: Query?, sorted by: Sort?) throws -> AnyIterator<Entity> func findOne(matching query: Query?) throws -> Entity? func findOne(byId identifier: Entity.Identifier) throws -> Entity? func update(matching query: Query?, to entity: Entity) throws func update(matchingIdentifier identifier: Entity.Identifier, to entity: Entity) throws func delete(byId identifier: Entity.Identifier) throws func delete(_ entity: Entity) throws static func generateIdentifier() -> Entity.Identifier } extension Table { public func delete(_ entity: Entity) throws { guard let id = entity.getIdentifier() else { throw ORMError.missingKey(Entity.defaultIdentifierField) } return try self.delete(byId: id) } } public protocol Database { associatedtype T: Table func getTable(named table: String) -> T } /// When implemented, it allows conversion to and from a database Entity public protocol ConcreteSerializable { associatedtype T: Table init(from source: T.Entity) throws func serialize() -> T.Entity mutating func getIdentifier() -> T.Entity.Identifier static func find(matching query: T.Query?, sorted by: Sort?) throws -> AnyIterator<Self> static func findOne(matching query: T.Query?) throws -> Self? static func findOne(byId identifier: T.Entity.Identifier) throws -> Self? } extension ConcreteSerializable { public func convert<S: SerializableObject>(to type: S.Type) -> (converted: S, remainder: Self.T.Entity) { var s = S(dictionary: [:]) var remainder = T.Entity(dictionary: [:]) for (key, value) in self.serialize().getKeyValuePairs() { if let value = value as? S.SupportedValue { s.setValue(to: value, forKey: key) // } else if let value = T.Entity.self.convert(value, to: S.self) { // s.setValue(to: value, forKey: key) } else { remainder.setValue(to: value, forKey: key) } } return (s, remainder) } } /// A database model public protocol Model { /// The database identifier var id: Any? { get set } } /// A database mdoel without schema public protocol SchemalessModel : ConcreteModel { var extraFields: T.Entity? { get } } /// An embeddable object public protocol Embeddable {} /// A database model that has a specified table/collection with specified (de-)serialization public protocol ConcreteModel : Model, ConcreteSerializable { /// The table/collection this model resides in static var table: T { get } } /// An embdeddabe with specified (de-)serialization public protocol ConcreteEmbeddable : Embeddable, ConcreteSerializable {} extension ConcreteModel { /// The model's identifier public mutating func getIdentifier() -> T.Entity.Identifier { if let identifier = self.id as? T.Entity.Identifier { return identifier } else { let identifier = T.generateIdentifier() self.id = identifier return identifier } } /// Saves the entity to the database public mutating func save() throws { if let id = id as? Self.T.Entity.Identifier { try Self.table.update(matchingIdentifier: id, to: self.serialize()) } else { id = Self.T.generateIdentifier() try Self.table.store(self.serialize()) } } /// Destroys the entity public func destroy() throws { if let id = id as? Self.T.Entity.Identifier { try Self.table.delete(byId: id) } } }