text stringlengths 8 1.32M |
|---|
//
// GameController.swift
// Asteroids
//
// Created by Gabriel Robinson on 4/12/19.
// Copyright © 2019 CS4530. All rights reserved.
//
import UIKit
protocol GameProtocols {
func turnLeft()
func turnRight()
func fire()
func accelerate()
}
protocol UpdateViewProtocols {
func updateShip(angle: CGFloat)
func updateShipPosition(position: CGPoint, isThrusting: Bool, _ respawn: Bool)
// functions to add to view
func addProjectile(id: Int, angle: CGFloat, position: CGPoint)
func addAsteroid(id: Int, position: CGPoint, angle: CGFloat, size: CGFloat)
// functions to update view
func updateProjectile(id: Int, position: CGPoint)
func updateAsteroid(id: Int, position: CGPoint)
// functions to remove from the view
func removeProjectile(id: Int)
func removeAsteroid(id: Int)
func updateScore(count: Int)
func updateLivesNumber(num: Int)
func gameOver()
}
class GameController: UIViewController {
var gameModel: Game?
var gameView: GameView!
var isTurningLeft = false
var isTurningRight = false
var isFiring = false
var isAccelerating = false
var isGameOver = false
var gameTimer: Timer?
var velocity: CGFloat = 0
var fireCount = 0
var updatingEnabled = true
var regenTimer: Timer?
convenience init(_ game: Game) {
self.init()
self.gameModel = game
}
override func loadView() {
super.loadView()
let gameView: GameView = GameView(frame: CGRect(x: 0, y: (navigationController?.navigationBar.frame.height)!, width: self.view.frame.width, height: self.view.frame.height - (navigationController?.navigationBar.frame.height)!))
self.view.addSubview(gameView)
self.gameView = gameView
if let gameModel = gameModel {
gameModel.set(viewProtocols: self)
} else {
gameModel = Game(left: -(gameView.asteroidFieldView?.frame.width)! / 2, right: (gameView.asteroidFieldView?.frame.width)! / 2,
top: -(gameView.asteroidFieldView?.frame.height)! / 2 + (navigationController?.navigationBar.frame.height)!,
bottom: (gameView.asteroidFieldView?.frame.height)! / 2, protocols: self)
}
}
override func viewDidLoad() {
super.viewDidLoad()
gameTimer = Timer.scheduledTimer(timeInterval: 0.0167, target: self, selector: #selector(updateGameState), userInfo: nil, repeats: true)
if let gameButtonPanel = gameView!.gameButtonPanelView {
gameButtonPanel.accelerateButton.addTarget(self, action: #selector(activateAccelerate), for: [.touchDown, .touchDragEnter])
gameButtonPanel.fireButton.addTarget(self, action: #selector(activateFire), for: [.touchDown, .touchDragEnter])
gameButtonPanel.turnLeftButton.addTarget(self, action: #selector(activateTurnLeft), for: [.touchDown, .touchDragEnter])
gameButtonPanel.turnRightButton.addTarget(self, action: #selector(activateTurnRight), for: [.touchDown, .touchDragEnter])
gameButtonPanel.accelerateButton.addTarget(self, action: #selector(endAccelerate), for: [.touchUpInside, .touchUpOutside, .touchDragExit])
gameButtonPanel.fireButton.addTarget(self, action: #selector(endFire), for: [.touchUpInside, .touchUpOutside, .touchDragExit])
gameButtonPanel.turnLeftButton.addTarget(self, action: #selector(endLeftTurn), for: [.touchUpInside, .touchUpOutside, .touchDragExit])
gameButtonPanel.turnRightButton.addTarget(self, action: #selector(endRightTurn), for: [.touchUpInside, .touchUpOutside, .touchDragExit])
}
let backButton: UIBarButtonItem = UIBarButtonItem(title: "<", style: UIBarButtonItem.Style.plain, target: self, action: #selector(popToRoot))
self.navigationItem.leftBarButtonItem = backButton
self.navigationController?.navigationBar.barStyle = UIBarStyle.black
}
func writeGame() {
let encoder = JSONEncoder()
let jsonData = try? encoder.encode(gameModel)
let docDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
try! jsonData?.write(to: docDirectory.appendingPathComponent("currentGame"))
}
@objc func popToRoot() {
writeGame()
gameModel = nil
_ = navigationController?.popToRootViewController(animated: true)
}
@objc func updateGameState() {
if isGameOver {
guard let gameTimer = gameTimer else {
print("If this executes, there are issues")
exit(-1)
}
gameTimer.invalidate()
if let gameModel = gameModel {
let highScores = HighScores()
if highScores.shouldAdd(score: gameModel.playersScore) {
let alert = UIAlertController(title: "New High Score!", message: "Enter your name", preferredStyle: .alert)
alert.addTextField(configurationHandler: { (textField) in
textField.placeholder = "Player's Name"
})
alert.addAction(UIAlertAction(title: NSLocalizedString("Create", comment: "Default action"), style: .default, handler: { _ in
if let playersName = alert.textFields?[0].text {
highScores.addHighScore(name: playersName, score: gameModel.playersScore)
}
if let navigationController = self.navigationController {
self.gameModel = nil
self.removeCurrentGameFile()
let viewControllers = [self.navigationController!.viewControllers[0], HighScoresListController()]
navigationController.setViewControllers(viewControllers, animated: true)
}
}))
self.present(alert, animated: true, completion: nil)
} else {
let alert = UIAlertController(title: "GAME OVER", message: "You destroyed \(gameModel.playersScore) asteroids. Have to try harder than that.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("Okay", comment: "Default action"), style: .default, handler: { _ in
if let navigationController = self.navigationController {
self.gameModel = nil
self.removeCurrentGameFile()
_ = navigationController.popViewController(animated: true)
}
}))
self.present(alert, animated: true, completion: nil)
}
}
}
fire()
accelerate()
turnLeft()
turnRight()
if let gameModel = gameModel {
gameModel.updateProjectileStates()
if let gameView = gameView {
if let asteroidsView = gameView.asteroidFieldView {
if asteroidsView.asteroidViews.count > 0 && gameModel.hasAsteroids() {
gameModel.updateAsteroidStates()
}
}
}
}
}
func removeCurrentGameFile() {
let docDirectory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
if let docDirectory = docDirectory {
try? FileManager.default.removeItem(at: docDirectory.appendingPathComponent("currentGame"))
}
}
@objc func activateAccelerate() {
print("Accelerating...")
isAccelerating = true
}
@objc func activateFire() {
print("Firing...")
isFiring = true
}
@objc func activateTurnLeft() {
print("Turning left...")
isTurningLeft = true
}
@objc func activateTurnRight() {
print("Turning right...")
isTurningRight = true
}
@objc func endLeftTurn() {
print("End turn...")
isTurningLeft = false
}
@objc func endRightTurn() {
print("End turn...")
isTurningRight = false
}
@objc func endFire() {
print("End fire...")
isFiring = false
}
@objc func endAccelerate() {
print("End accelerate...")
isAccelerating = false
}
}
extension GameController: GameProtocols {
func turnRight() {
if isTurningRight, let gameModel = gameModel {
gameModel.turnShip(angle: 2.5)
}
}
func fire() {
if isFiring && fireCount % 7 == 0, let gameModel = gameModel {
gameModel.fireProjectile()
fireCount = 1
} else {
fireCount += 1
}
}
func turnLeft() {
if isTurningLeft, let gameModel = gameModel {
gameModel.turnShip(angle: -2.5)
}
}
func accelerate() {
if let gameModel = gameModel {
if isAccelerating {
gameModel.accelerateShip(0.2)
} else {
gameModel.accelerateShip(-0.1)
}
}
}
}
extension GameController: UpdateViewProtocols {
func addAsteroid(id: Int, position: CGPoint, angle: CGFloat, size: CGFloat) {
if let gameView = gameView {
if let asteroidView = gameView.asteroidFieldView {
asteroidView.addAsteroid(id, angle, position, size)
}
}
}
func updateAsteroid(id: Int, position: CGPoint) {
if let gameView = gameView {
if let asteroidView = gameView.asteroidFieldView {
asteroidView.updateAsteroid(id, position)
}
}
}
func addProjectile(id: Int, angle: CGFloat, position: CGPoint) {
if let gameView = gameView {
if let asteroidView = gameView.asteroidFieldView {
asteroidView.addProjectile(id, angle, position)
}
}
}
func updateProjectile(id: Int, position: CGPoint) {
if let gameView = gameView {
if let asteroidView = gameView.asteroidFieldView {
asteroidView.updateProjectile(id, position)
}
}
}
func updateShip(angle: CGFloat) {
if let gameView = gameView {
if let asteroidView = gameView.asteroidFieldView {
asteroidView.setShipsAngleTransformation(angle)
}
}
}
func updateShipPosition(position: CGPoint, isThrusting: Bool, _ respawn: Bool) {
if let gameView = gameView {
if let asteroidView = gameView.asteroidFieldView {
asteroidView.setShipsTranslationTransformation(position: position, isThrusting: isThrusting, respawn)
}
}
}
func removeProjectile(id: Int) {
if let gameView = gameView {
if let asteroidView = gameView.asteroidFieldView {
asteroidView.removeProjectile(id: id)
}
}
}
func removeAsteroid(id: Int) {
if let gameView = gameView {
if let asteroidView = gameView.asteroidFieldView {
asteroidView.removeAsteroid(id: id)
}
}
}
func updateScore(count: Int) {
if let gameView = gameView {
if let asteroidView = gameView.asteroidFieldView {
asteroidView.updateScore(count)
}
}
}
func updateLivesNumber(num: Int) {
if let gameView = gameView {
if let asteroidView = gameView.asteroidFieldView {
asteroidView.updateNumberOfLives(num)
}
}
}
func gameOver() {
isGameOver = true
}
}
|
//
// UIColor.swift
// umbrella
// Created by Pranav Shashikant Deshpande on 9/17/17.
// Copyright © 2017 Pranav Shashikant Deshpande. All rights reserved.
//
import UIKit
extension UIColor {
public convenience init (_ rgbHex: UInt, alpha: CGFloat = 1.0) {
let rawRed = Double((rgbHex >> 16) & 0xFF) / 255.0
let rawGreen = Double((rgbHex >> 8) & 0xFF) / 255.0
let rawBlue = Double(rgbHex & 0xFF) / 255.0
self.init(red: CGFloat(rawRed), green: CGFloat(rawGreen), blue: CGFloat(rawBlue), alpha: alpha)
}
}
|
//
// DataProvider.swift
// Movies
//
// Created by Rodrigo Morbach on 04/11/18.
// Copyright © 2018 Movile. All rights reserved.
//
import Foundation
protocol DataProvider {
associatedtype ModelT: Any
typealias ResultClosure = (_ error: Error?, _ result: [ModelT]?) -> Void
func fetch(completion: ResultClosure)
func save(object: ModelT) -> Bool
func delete(object: ModelT) -> Bool
}
|
//
// LoginViewController.swift
// Chat
//
// Created by Vahagn Manasyan on 4/14/20.
// Copyright © 2020 Vahagn Manasyan. All rights reserved.
//
import UIKit
import Firebase
class LoginViewController: UIViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loginButton: UIButton!
let auth = Auth.auth()
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
// MARK: Actions
@IBAction func loginTapped(_ sender: UIButton) {
login()
}
// MARK: Methods
func login() {
guard let email = emailTextField.text,
let password = passwordTextField.text else {
let errorMessage = "Not all fields are filled"
showErrorAlert(errorMessage)
return
}
auth.signIn(withEmail: email, password: password) { (result, error) in
if let error = error {
self.showErrorAlert(error.localizedDescription)
} else {
self.turnToGroupsPage()
}
}
}
func turnToGroupsPage() {
let storyBoard = UIStoryboard(name: "Main", bundle:nil)
let groupsViewController = storyBoard.instantiateViewController(withIdentifier: "GroupsViewController") as! GroupsViewController
self.navigationController?.pushViewController(groupsViewController, animated: true)
// groupsViewController.modalPresentationStyle = .fullScreen
// self.present(groupsViewController, animated:true, completion:nil)
}
func showErrorAlert(_ errorMessage: String?) {
guard let errorMessage = errorMessage else {return}
let alert = UIAlertController(title: "Error", message: errorMessage, preferredStyle: .alert)
let action = UIAlertAction(title: "Cancel", style: .cancel)
alert.addAction(action)
present(alert, animated: true)
}
func setup() {
loginButton.layer.cornerRadius = 0.05 * loginButton.bounds.size.width
emailTextField.returnKeyType = .next
passwordTextField.returnKeyType = .done
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
}
|
//
// MainmenuView.swift
// Dibilingo-iOS
//
// Created by Vlad Vrublevsky on 05.12.2020.
//
import SwiftUI
/*
struct MainmenuView: View {
var categories = [Category(id: 0, name: "cat"), Category(id: 1, name: "train"), Category(id: 2, name: "weather"), Category(id: 3, name: "random")]
@State var geo: GeometryProxy?
@ObservedObject var userprofile = UserProfile_ViewModel()
@State private var totalCoins: Int = 0
var body: some View {
NavigationView {
GeometryReader { geo in
ZStack {
Color(hex: "6495ed")
.edgesIgnoringSafeArea(.all)
VStack {
ZStack {
Rectangle()
.foregroundColor(.black)
.frame(width: geo.frame(in: .global).width, height: 80, alignment: .center)
.opacity(0.5)
HStack {
Text("\(userprofile.profile?.name ?? "Unknown")")
.font(Font.custom("boomboom", size: 32))
.foregroundColor(.white)
.offset(y: 14)
.onTapGesture(count: 1, perform: {
userprofile._SaveAndUpload()
})
Spacer()
Text("\(totalCoins)")
.font(Font.custom("Coiny", size: 38))
.foregroundColor(.white)
.offset(y: 12)
.onTapGesture {
self.totalCoins = userprofile.getTotalCoins()
}
}
.padding(.horizontal)
}
.edgesIgnoringSafeArea(.top)
Spacer()
}.zIndex(3)
ScrollView {
VStack {
Rectangle()
.frame(width: 100, height: 150, alignment: .center)
.opacity(0)
ForEach(categories) { category in
LevelPreview(userprofile: userprofile, category_name: category.name)
.position(x: category.id % 2 == 0 ? geo.frame(in: .global).maxX - 145 : geo.frame(in: .global).minX + 145 )
}
}
}
}
.navigationBarHidden(true)
.onAppear(perform: {
self.geo = geo
//print("MainmenuView appered")
self.userprofile.mainmenuLoad()
if userprofile.onUpdateFinish == nil {
userprofile.onUpdateFinish = { newCoins in
self.totalCoins = newCoins
print("Updated!")
}
}
self.totalCoins = userprofile.getTotalCoins()
/*
DispatchQueue.main.asyncAfter(deadline: .now() + 0.50) {
self.totalCoins = userprofile.getTotalCoins()
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.totalCoins = userprofile.getTotalCoins()
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
self.totalCoins = userprofile.getTotalCoins()
} */
})
}
}
}
}
struct MainmenuView_Previews: PreviewProvider {
static var previews: some View {
Group {
MainmenuView()
.previewDevice("iPhone 11")
MainmenuView()
.previewDevice("iPhone 8")
}
}
}
*/
|
//
// FeedsTabController.swift
// Eventer
//
// Created by Мирошниченко Марина on 19.06.2020.
// Copyright © 2020 Мирошниченко Марина. All rights reserved.
//
import UIKit
class FeedsViewController: UIViewController {
}
|
//
// SystemIcon.swift
// MyMacOSApp
//
// Created by steve.ham on 2021/01/05.
//
import AppKit
struct SystemIcon: Hashable {
let name: String
let userAdded: Bool
let identifier = UUID()
init(name: String, userAdded: Bool) {
self.name = name
self.userAdded = userAdded
}
func hash(into hasher: inout Hasher) {
hasher.combine(identifier)
}
static func == (lhs: SystemIcon, rhs: SystemIcon) -> Bool {
return lhs.identifier == rhs.identifier
}
}
|
//
// ListPatientController.swift
// HISmartPhone
//
// Created by MACOS on 12/21/17.
// Copyright © 2017 MACOS. All rights reserved.
//
import UIKit
class ListPatientController: BaseViewController {
//MARK: Variable
fileprivate let cellId = "cellId"
fileprivate var listPatient = [Patient]()
fileprivate var filterListPatient = [Patient]()
fileprivate var isSorting = false
//MARK: UIControl
fileprivate lazy var alertSigout: AlertAnnoucementSignoutController = {
let alert = AlertAnnoucementSignoutController()
alert.setMessage("Bạn chắc chắn \n muốn đăng xuất khỏi hệ thống")
alert.alertDelegate = self
return alert
}()
fileprivate lazy var sideMenuVC: SideMenuController = {
let menu = SideMenuController()
menu.delegate = self
return menu
}()
fileprivate lazy var searchBar: UISearchBar = {
let searchBar = UISearchBar()
searchBar.delegate = self
searchBar.placeholder = "Tìm kiếm bệnh nhân"
searchBar.backgroundImage = UIImage()
return searchBar
}()
private let searchBarView: UIView = {
let viewConfig = UIView()
viewConfig.backgroundColor = UIColor.clear
return viewConfig
}()
private let contentSearchView: UIView = {
let viewConfig = UIView()
viewConfig.backgroundColor = Theme.shared.lightNavigationBarColor
viewConfig.makeShadow(color: #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1), opacity: 1.0, radius: 7.0)
return viewConfig
}()
private let orderNumberLabel: UILabel = {
let label = UILabel()
label.text = "STT"
label.textAlignment = .center
label.textColor = Theme.shared.primaryColor
label.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize)
return label
}()
private let codeLabel: UILabel = {
let label = UILabel()
label.text = "Mã BN liên kết"
label.textAlignment = .left
label.textColor = Theme.shared.primaryColor
label.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize)
return label
}()
private let phoneLabel: UILabel = {
let label = UILabel()
label.text = "Số điện thoại"
label.textAlignment = .right
label.textColor = Theme.shared.primaryColor
label.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize)
return label
}()
fileprivate lazy var tableViewListPatient: UITableView = {
let tableViewConfig = UITableView()
tableViewConfig.delegate = self
tableViewConfig.dataSource = self
tableViewConfig.separatorColor = UIColor.clear
tableViewConfig.register(ListPatientCell.self, forCellReuseIdentifier: self.cellId)
tableViewConfig.backgroundColor = Theme.shared.defaultBGColor
tableViewConfig.estimatedRowHeight = 100
tableViewConfig.rowHeight = UITableViewAutomaticDimension
return tableViewConfig
}()
//MARK: Initialize
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
HISMartManager.share.updateIsListPatientVC(true)
UIApplication.shared.statusBarStyle = .default
self.navigationController?.navigationBar.tintColor = Theme.shared.darkBlueTextColor
self.setupViewNavigationBar()
}
override func setupView() {
self.addLeftBarItem()
self.setupViewContainSearchView()
self.setupViewSearchBar()
self.setupViewNavigationBar()
self.setupViewOrderNumberLabel()
self.setupViewCodeLabel()
self.setupViewPhoneNumberLabel()
self.setupViewListPatientTableView()
self.fetchData()
NotificationCenter.default.addObserver(self, selector: #selector(addLeftBarItem), name: NSNotification.Name.init(Notification.Name.obseverMessage), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(addRightBarItem), name: NSNotification.Name.init(Notification.Name.updateNotification), object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
UIApplication.shared.statusBarStyle = .lightContent
HISMartManager.share.updateIsListPatientVC(false)
}
//MARK: Action UIControl
@objc func handleWarningButton() {
self.navigationController?.pushViewController(WarningController(), animated: true)
}
@objc func handleOptionMenu() {
self.present(self.sideMenuVC, animated: true) {
//TO DO
}
}
@objc func addRightBarItem() {
//NOTICE
let warningButton = SSBadgeButton()
warningButton.frame = CGRect(x: 0, y: 0, width: 30, height: 40)
warningButton.setImage(UIImage(named: "warning_blue"), for: .normal)
warningButton.badgeEdgeInsets = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 4)
warningButton.badge = "\(BloodPressureNotifiHelper.shared.newBPNotifications.count)"
warningButton.addTarget(self, action: #selector(handleWarningButton), for: .touchUpInside)
let warningItem = UIBarButtonItem(customView: warningButton)
self.navigationItem.rightBarButtonItem = warningItem
}
//MARK: Feature
private func fetchData() {
ListPatientFacade.loadAllPatient { (listPatient) in
self.listPatient = listPatient
self.filterListPatient = self.listPatient
self.tableViewListPatient.reloadData()
}
}
fileprivate func searchIsEmpty() -> Bool {
return self.searchBar.text?.isEmpty ?? true
}
fileprivate func filterContentForSearchText(_ searchText: String, scrop: String = "All") {
if self.searchIsEmpty() {
self.filterListPatient = self.listPatient
return
}
self.filterListPatient = self.listPatient.filter {
$0.patient_Name.lowercased().contains(searchText.lowercased()) || $0.patient_ID.lowercased().contains(searchText.lowercased())
}
}
fileprivate func isFiltering() -> Bool {
return !self.searchIsEmpty()
}
//MARK: SetupView
@objc private func addLeftBarItem() {
let number = HISMartManager.share.numberNewMessages
//OPTION
let optionButton = SSBadgeButton()
optionButton.frame = CGRect(x: 0, y: 0, width: 25, height: 25)
optionButton.setImage(UIImage(named: "main_menu_blue"), for: .normal)
optionButton.badgeEdgeInsets = UIEdgeInsets(top: 15, left: 0, bottom: 0, right: 1)
optionButton.badge = number == 0 ? nil : number.description
optionButton.addTarget(self, action: #selector(handleOptionMenu), for: .touchUpInside)
let optionItem = UIBarButtonItem(customView: optionButton)
self.navigationItem.leftBarButtonItems = [optionItem]
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
private func setupViewNavigationBar() {
//TITLE LABEL
let titleLabel = UILabel()
titleLabel.text = "Danh sách bệnh nhân"
titleLabel.textAlignment = .center
titleLabel.textColor = Theme.shared.darkBlueTextColor
titleLabel.frame = CGRect(x: 0, y: 0, width: 50, height: 30)
titleLabel.font = UIFont.systemFont(ofSize: Dimension.shared.titleFontSize)
self.navigationItem.titleView = titleLabel
//NOTICE
let warningButton = SSBadgeButton()
warningButton.frame = CGRect(x: 0, y: 0, width: 30, height: 40)
warningButton.setImage(UIImage(named: "warning_blue"), for: .normal)
warningButton.badgeEdgeInsets = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 4)
warningButton.badge = "\(BloodPressureNotifiHelper.shared.newBPNotifications.count)"
warningButton.addTarget(self, action: #selector(handleWarningButton), for: .touchUpInside)
let warningItem = UIBarButtonItem(customView: warningButton)
self.navigationItem.rightBarButtonItem = warningItem
//CUSTOM NAVIBAR
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.barTintColor = Theme.shared.lightNavigationBarColor
}
private func setupViewContainSearchView() {
self.view.addSubview(self.contentSearchView)
if #available(iOS 11, *) {
self.contentSearchView.snp.makeConstraints { (make) in
make.width.centerX.equalToSuperview()
make.height.equalTo(Dimension.shared.heightContainsViewSearchBar)
make.top.equalTo(self.view.safeAreaInsets)
}
} else {
self.contentSearchView.snp.makeConstraints { (make) in
make.width.centerX.equalToSuperview()
make.height.equalTo(Dimension.shared.heightContainsViewSearchBar)
make.top.equalTo(self.topLayoutGuide.snp.bottom)
}
}
}
private func setupViewSearchBar() {
self.contentSearchView.addSubview(self.searchBar)
self.searchBar.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(Dimension.shared.mediumHorizontalMargin)
make.centerY.equalToSuperview()
make.height.equalTo(Dimension.shared.heightSearchBar)
make.right.equalToSuperview().offset(-Dimension.shared.normalHorizontalMargin)
}
}
private func setupViewOrderNumberLabel() {
self.view.addSubview(self.orderNumberLabel)
if #available(iOS 11, *) {
self.orderNumberLabel.snp.makeConstraints { (make) in
make.top.equalTo(self.contentSearchView.snp.bottom).offset(11 * Dimension.shared.heightScale)
make.left.equalTo(self.view.safeAreaLayoutGuide)
.offset(Dimension.shared.mediumHorizontalMargin)
}
} else {
self.orderNumberLabel.snp.makeConstraints { (make) in
make.top.equalTo(self.contentSearchView.snp.bottom).offset(11 * Dimension.shared.heightScale)
make.left.equalToSuperview().offset(Dimension.shared.mediumHorizontalMargin)
}
}
}
private func setupViewCodeLabel() {
self.view.addSubview(self.codeLabel)
self.codeLabel.snp.makeConstraints { (make) in
make.top.equalTo(self.orderNumberLabel)
make.left.equalTo(self.orderNumberLabel.snp.right).offset(37 * Dimension.shared.heightScale)
}
}
private func setupViewPhoneNumberLabel() {
self.view.addSubview(self.phoneLabel)
if #available(iOS 11, *) {
self.phoneLabel.snp.makeConstraints { (make) in
make.top.equalTo(self.orderNumberLabel)
make.right.equalTo(self.view.safeAreaLayoutGuide)
.offset(-Dimension.shared.mediumVerticalMargin)
}
} else {
self.phoneLabel.snp.makeConstraints { (make) in
make.top.equalTo(self.orderNumberLabel)
make.right.equalToSuperview().offset(-Dimension.shared.mediumVerticalMargin)
}
}
}
private func setupViewListPatientTableView() {
self.view.addSubview(self.tableViewListPatient)
if #available(iOS 11, *) {
self.tableViewListPatient.snp.makeConstraints { (make) in
make.width.centerX.equalToSuperview()
make.top.equalTo(self.orderNumberLabel.snp.bottom)
.offset(Dimension.shared.mediumVerticalMargin)
make.bottom.equalTo(self.view.safeAreaLayoutGuide)
}
} else {
self.tableViewListPatient.snp.makeConstraints { (make) in
make.width.bottom.centerX.equalToSuperview()
make.top.equalTo(self.orderNumberLabel.snp.bottom)
.offset(Dimension.shared.mediumVerticalMargin)
}
}
}
}
//MARK: - UISearchResultsUpdating
extension ListPatientController: UISearchResultsUpdating {
@available(iOS 8.0, *)
func updateSearchResults(for searchController: UISearchController) {
}
}
//MARK: - UITableViewDelegate, UITableViewDataSource
extension ListPatientController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.filterListPatient.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: self.cellId, for: indexPath) as? ListPatientCell else { return UITableViewCell() }
cell.selectionStyle = .none
cell.index = (indexPath.item + 1)
cell.patient = self.filterListPatient[indexPath.item]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
HISMartManager.share.setCurrentPatient(self.filterListPatient[indexPath.item])
BPOChartManager.shared.BPOResults.removeAll()
BPOHelper.shared.BPOResults.removeAll()
self.present(TabBarController(), animated: true, completion: nil)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.searchBar.endEditing(true)
}
}
//MARK: - SideMenuControllerDelegate
extension ListPatientController: SideMenuControllerDelegate {
func presentVC(_ vc: UIViewController) {
self.navigationController?.pushViewController(vc, animated: true)
}
func popToListPatient() {
//
}
func didSelectLogout() {
self.present(self.alertSigout, animated: true, completion: nil)
}
}
//MARK: - AlertAnnoucementSignoutControllerDelegate
extension ListPatientController: AlertAnnoucementSignoutControllerDelegate {
func didSelectSignOut() {
Authentication.share.signOut()
guard let window = UIApplication.shared.keyWindow else { return }
window.rootViewController = UINavigationController(rootViewController: LoginController())
}
}
//MARK: - UISearchBarDelegate
extension ListPatientController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
self.searchBar.endEditing(true)
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
self.filterContentForSearchText(searchText)
self.tableViewListPatient.reloadData()
}
}
|
/*
See LICENSE folder for this sample’s licensing information.
Abstract:
An NSManagedObject subclass for the Quake entity.
*/
import CoreData
// MARK: - Core Data
/**
Managed object subclass for the Quake entity.
*/
class Quake: NSManagedObject {
// The characteristics of a quake.
@NSManaged var magnitude: Float
@NSManaged var place: String
@NSManaged var time: Date
// A unique identifier for removing duplicates. Constrain
// the Quake entity on this attribute in the data model editor.
@NSManaged var code: String
/**
Updates a Quake instance with the values from a QuakeProperties.
*/
func update(with quakeProperties: QuakeProperties) throws {
// Update the quake only if all provided properties have values.
guard let newCode = quakeProperties.code,
let newMagnitude = quakeProperties.mag,
let newPlace = quakeProperties.place,
let newTime = quakeProperties.time else {
throw QuakeError.missingData
}
code = newCode
magnitude = newMagnitude
place = newPlace
time = Date(timeIntervalSince1970: newTime / 1000.0)
}
}
// MARK: - Codable
/**
A struct for decoding JSON with the following structure:
"{
"features":[{
"properties":{
"mag":1.9,
"place":"21km ENE of Honaunau-Napoopoo, Hawaii",
"time":1539187727610,"updated":1539187924350,
"code":"70643082"
}
}]
}"
Stores an array of decoded QuakeProperties for later use in
creating or updating Quake instances.
*/
struct GeoJSON: Decodable {
private enum RootCodingKeys: String, CodingKey {
case features
}
private enum FeatureCodingKeys: String, CodingKey {
case properties
}
// A QuakeProperties array of decoded Quake data.
var quakePropertiesArray = [QuakeProperties]()
init(from decoder: Decoder) throws {
let rootContainer = try decoder.container(keyedBy: RootCodingKeys.self)
var featuresContainer = try rootContainer.nestedUnkeyedContainer(forKey: .features)
while featuresContainer.isAtEnd == false {
let propertiesContainer = try featuresContainer.nestedContainer(keyedBy: FeatureCodingKeys.self)
// Decodes a single quake from the data, and appends it to the array.
let properties = try propertiesContainer.decode(QuakeProperties.self, forKey: .properties)
quakePropertiesArray.append(properties)
}
}
}
/**
A struct encapsulating the properties of a Quake. All members are
optional in case they are missing from the data.
*/
struct QuakeProperties: Decodable {
let mag: Float? // 1.9
let place: String? // "21km ENE of Honaunau-Napoopoo, Hawaii"
let time: Double? // 1539187727610
let code: String? // "70643082"
}
|
//
// MainAPI.swift
// DealApp
//
// Created by Egor Sakhabaev on 13.07.2018.
// Copyright © 2018 Egor Sakhabaev. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
protocol MainAPI {
static func sendRequest(type: HTTPMethod, url: String!, baseURL: String, parameters: [String: AnyObject]?, headers: HTTPHeaders?, completion: ServerResult?)
}
extension MainAPI {
static func sendRequest(type: HTTPMethod, url: String!, baseURL: String = API.baseURL, parameters: [String: AnyObject]?, headers: HTTPHeaders?, completion: ServerResult?) {
let urlString = baseURL + url
var encoding: ParameterEncoding = URLEncoding()
if type == .post {
encoding = JSONEncoding()
}
let tagString = "[Request] "
print(tagString + urlString + "\r\n \(String(describing: parameters))")
Alamofire.request(urlString, method: type, parameters: parameters, encoding: encoding ,headers: headers).responseJSON { (response) in
print(response)
guard let response = response.result.value as? Dictionary<String, AnyObject> else {
completion?( .Error (code: nil, message: "Нет соединения!\r\nИнтернет подключение отсутствует или слишком медленное."))
return
}
if let type = response["type"] as? String, type == "error" {
print("[Error] \(response["message"] as! String)")
completion?( .Error (code: response["code"] as? String, message: response["message"] as? String))
return
}
if let status = response["success"] as? Bool, status == false {
print("[Response] \(response["message"] as? String ?? "no message")")
completion?( .Error (code: response["code"] as? String, message: response["message"] as? String))
return
}
let json = JSON(response)
completion?( .Success (response: json))
}
}
static func sendRequest(type: HTTPMethod, url: String!, baseURL: String = API.baseURL, parameters: [String: AnyObject]?, headers: HTTPHeaders?, completion: ServerArrayResult?) {
let urlString = baseURL + url
let tagString = "[Request] "
var header: HTTPHeaders = headers == nil ? HTTPHeaders() : headers!
header["Authorization:Basic"] = "cGV2c2VldkBleGFtcGxlLmNvbTpzZWNyZXQ="
print(tagString + urlString + "\r\n \(String(describing: parameters))")
Alamofire.request(urlString, method: type, parameters: parameters, headers: header).responseJSON { (response) in
print(response)
guard let response = response.result.value as? [Dictionary<String, AnyObject>] else {
completion?( .Error (message: "Нет соединения!\r\nИнтернет подключение отсутствует или слишком медленное."))
return
}
completion?( .Success (response: response))
}
}
}
|
//
// 119_杨辉三角.swift
// algorithm.swift
//
// Created by yaoning on 1/21/20.
// Copyright © 2020 yaoning. All rights reserved.
//
import Foundation
//给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
//
//
//
//在杨辉三角中,每个数是它左上方和右上方的数的和。
//
//示例:
//
//输入: 3
//输出: [1,3,3,1]
//进阶:
//
//你可以优化你的算法到 O(k) 空间复杂度吗?
//
//来源:力扣(LeetCode)
//链接:https://leetcode-cn.com/problems/pascals-triangle-ii
//著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
// 解题思路
// 第n行的数据 = 第n-1行 最前边补0 除最后一个外两两相加
// 第4行 1 3 3 1
// 第5行 = (0, 1, 3, 3, 1) 两两相加(0+1, 1+3, 3+3, 3+1, 1)
//
class Solution119 {
func getRow(_ rowIndex: Int) -> [Int] {
if rowIndex == 0 {
return [1]
}
var res = [1]
for i in 1...rowIndex {
res.insert(0, at: 0)
for j in 0..<i {
res[j] = res[j] + res[j + 1]
}
}
return res
}
static func test() {
print("119_杨辉三角2")
let res = Solution119().getRow(3)
print(res)
}
}
|
//
// WordsRepository.swift
// Waker
//
// Created by Joe Ciou on 2021/6/12.
//
import Foundation
import Combine
enum WordsRepositorySource {
case store(WordsStore)
case service(WordsService)
case serviceWithSyncableStore(WordsService, WordsStore & WordsSyncable)
}
class WordsRepository: Repository {
typealias Model = [Word]
static let shared = WordsRepository()
private let source: WordsRepositorySource
private var dataSubject: PassthroughSubject<[Word], Never>?
private var refreshResultSubject: PassthroughSubject<RepositoryRefreshResult, Never>?
private var storeCanceller: AnyCancellable?
private var serviceCanceller: AnyCancellable?
var isConnected: Bool {
dataSubject != nil
}
init(source: WordsRepositorySource = .serviceWithSyncableStore(WordsService.shared, WordsRealmStore.shared)) {
self.source = source
}
deinit {
disconnect()
}
func connect() -> (AnyPublisher<[Word], Never>, AnyPublisher<RepositoryRefreshResult, Never>) {
dataSubject = PassthroughSubject<[Word], Never>()
refreshResultSubject = PassthroughSubject<RepositoryRefreshResult, Never>()
switch source {
case .store(let store):
storeCanceller = store.connect().sink { [unowned self] words in
self.dataSubject?.send(words)
}
case .service(let service):
refreshWith(service: service)
case .serviceWithSyncableStore(let service, let store):
storeCanceller = store.connect().sink { [unowned self] words in
self.dataSubject?.send(words)
}
refreshWith(service: service, store: store)
}
return (dataSubject!.eraseToAnyPublisher(), refreshResultSubject!.eraseToAnyPublisher())
}
func disconnect() {
storeCanceller?.cancel()
serviceCanceller?.cancel()
dataSubject = nil
refreshResultSubject = nil
switch source {
case .store(let store):
if store.isConnected {
store.disconnect()
}
case .service(_):
break
case .serviceWithSyncableStore(_, let store):
if store.isConnected {
store.disconnect()
}
}
}
func refresh() {
switch source {
case .store(_):
return // Realm store will update immediately if there are any changes
case .service(let service):
refreshWith(service: service)
case .serviceWithSyncableStore(let service, let store):
refreshWith(service: service, store: store)
}
}
private func refreshWith(service: WordsService, store: (WordsStore & WordsSyncable)? = nil) {
serviceCanceller = service.fetch()
.receive(on: DispatchQueue.main)
.sink { [unowned self] completion in
switch completion {
case .finished:
self.refreshResultSubject?.send(.completed)
case .failure(let error):
self.refreshResultSubject?.send(.failed(error))
}
self.serviceCanceller?.cancel()
} receiveValue: { words in
self.dataSubject?.send(words)
store?.sync(data: words)
}
}
}
|
//
// MovieCollectionListViewController.swift
// boostcamp_3_iOS
//
// Created by 이호찬 on 09/12/2018.
// Copyright © 2018 leehochan. All rights reserved.
//
import UIKit
class MovieCollectionListViewController: UIViewController {
// MARK: - IBOutlets
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
// MARK: - Properties
let cellIdentifier = "MovieListCollectionViewCell"
let itemLength = (UIScreen.main.bounds.width / 2) - 10
var navigationTitle: String? {
didSet {
self.navigationItem.title = navigationTitle
}
}
// MARK: - LifeCycles
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
collectionViewLayout()
// refreshControl
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refreshOptions(sender:)), for: .valueChanged)
collectionView.refreshControl = refreshControl
// 데이터가 없을경우 받아옴
if MovieListData.shared.movieLists.isEmpty {
self.activityIndicator.startAnimating()
getMovieListData()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationTitle = MovieListData.shared.sortRule.name()
collectionView.reloadData()
}
// MARK: - Methods
@objc func refreshOptions(sender: UIRefreshControl) {
getMovieListData()
sender.endRefreshing()
}
func collectionViewLayout() {
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
let space = (view.bounds.width - itemLength * 2) / 3
layout.sectionInset = .init(top: 10, left: space, bottom: 0, right: space)
layout.itemSize = CGSize(width: itemLength, height: itemLength * 1.9)
layout.minimumInteritemSpacing = space
layout.minimumLineSpacing = 5
}
}
func getMovieListData() {
MovieStaticMethods.getMovieData { isSucced in
if !isSucced {
self.networkErrorAlert()
DispatchQueue.main.async {
self.activityIndicator.stopAnimating()
}
return
}
DispatchQueue.main.async {
self.navigationTitle = MovieListData.shared.sortRule.name()
self.activityIndicator.stopAnimating()
self.collectionView.reloadData()
}
}
}
// MARK: - IBActions
@IBAction func actionChangeSortingRule(_ sender: UIBarButtonItem) {
sortActionSheet { title in
self.navigationTitle = title
self.activityIndicator.startAnimating()
self.getMovieListData()
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let movieDetailViewController: MovieDetailViewController = segue.destination as? MovieDetailViewController else { return }
guard let cell: MovieListCollectionViewCell = sender as? MovieListCollectionViewCell else { return }
guard let indexPath: IndexPath = collectionView.indexPath(for: cell) else { return }
movieDetailViewController.id = MovieListData.shared.movieLists[indexPath.row].id
movieDetailViewController.movieName = MovieListData.shared.movieLists[indexPath.row].title
let backItem = UIBarButtonItem()
backItem.title = "영화목록"
navigationItem.backBarButtonItem = backItem
}
}
// MARK: - CollectionView
extension MovieCollectionListViewController: UICollectionViewDataSource {
// MARK: CollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return MovieListData.shared.movieLists.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell: MovieListCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as? MovieListCollectionViewCell else { return UICollectionViewCell() }
let movieList = MovieListData.shared.movieLists[indexPath.row]
cell.configure(data: movieList)
if (MovieListData.shared.cache?.object(forKey: (indexPath as NSIndexPath).row as AnyObject) != nil) {
cell.movieImageView.image = MovieListData.shared.cache?.object(forKey: (indexPath as NSIndexPath).row as AnyObject) as? UIImage
} else {
DispatchQueue.global().async {
guard let imageURL: URL = URL(string: movieList.thumb) else { return }
guard let imageData: Data = try? Data(contentsOf: imageURL) else { return }
DispatchQueue.main.async {
if let index: IndexPath = collectionView.indexPath(for: cell) {
if index.row == indexPath.row {
if let movieImage = UIImage(data: imageData) {
cell.movieImageView.image = movieImage
MovieListData.shared.cache?.setObject(movieImage, forKey: (indexPath as NSIndexPath).row as AnyObject)
}
}
}
}
}
}
return cell
}
}
|
//
// Statistics.swift
// DeliriumOver
//
// Created by Mate Redecsi on 2019. 11. 02..
// Copyright © 2019. rmatesz. All rights reserved.
//
import Foundation
struct Statistics {
var alcoholEliminationDate: Date = Date()
var bloodAlcoholConcentration: Double = 0.0
}
|
//
// StartCommand.swift
// KayakFirst Ergometer E2
//
// Created by Balazs Vidumanszki on 2017. 02. 26..
// Copyright © 2017. Balazs Vidumanszki. All rights reserved.
//
import Foundation
class CommandProcessor<E: MeasureCommand> {
//MARK: properties
let telemetry = Telemetry.sharedInstance
private var f_avElement: CalculateF_AV<E>?
private var t200Av: CalculateT_200_AV<E>?
private var t200Element: CalculateElementT_200<E>?
var force: Double = 0
var speed: Double = 0
var distance: Double = 0
var strokes: Double = 0
var forceAv: Double = 0
var speedAv: Double = 0
var strokesAv: Double = 0
private var maF = MovingAverage()
private var maV = MovingAverage()
private var maStrokes = MovingAverage()
func calculate(measureCommands: [E]) -> Training {
return calculateValues(measureCommands: measureCommands)
}
func calculateAvg() -> TrainingAvg {
return createTrainingAvg()
}
func updateSumTraining(sumTraining: SumTraining) -> SumTraining {
sumTraining.distance = distance
sumTraining.duration = telemetry.duration
sumTraining.trainingCount = Int(telemetry.averageIndex)
return sumTraining
}
func reset() {
f_avElement = CalculateF_AV(startCommand: self)
t200Av = CalculateT_200_AV(startCommand: self)
t200Element = CalculateElementT_200(startCommand: self)
force = 0
speed = 0
distance = 0
strokes = 0
forceAv = 0
speedAv = 0
strokesAv = 0
maF = MovingAverage()
maV = MovingAverage()
maStrokes = MovingAverage(numAverage: 5)
}
//MARK: abstract functions
func calculateValues(measureCommands: [E]) -> Training {
fatalError("Must be implemented")
}
func createTraining() -> Training {
return KayakFirst_Ergometer_E2.createTraining(
timestamp: getCalculatedTimeStamp(),
force: maF.calAverage(newValue: force),
speed: maV.calAverage(newValue: speed),
distance: distance,
strokes: maStrokes.calAverage(newValue: strokes),
t200: t200Element!.run())
}
func createTrainingAvg() -> TrainingAvg {
return KayakFirst_Ergometer_E2.createTrainingAvg(
force: f_avElement!.run(),
speed: speedAv,
strokes: strokesAv,
t200: t200Av!.run())
}
//MARK: timestamp
func getCalculatedTimeStamp() -> Double {
return telemetry.getAbsoluteTimestamp()
}
func getDoubleFromCommand(measureCommand: MeasureCommand) -> Double {
return CommandParser.getDouble(stringValue: measureCommand.getValue()!)
}
}
|
//
// Recipe.swift
// Domain
//
// Created by Fernando Moya de Rivas on 01/09/2019.
// Copyright © 2019 Fernando Moya de Rivas. All rights reserved.
//
import Foundation
/// Holds the basic model of a recipe
public struct Recipe {
public var title: String
public var imageUrl: String
// This initializer is not automatically generated public by XCode and it needs to be implemented
public init(title: String, imageUrl: String) {
self.title = title
self.imageUrl = imageUrl
}
}
|
//
// GlanceController.swift
// Weather WatchKit Extension
//
// Created by Luke de Castro on 2/19/15.
// Copyright (c) 2015 Luke de Castro. All rights reserved.
//
import WatchKit
import Foundation
import CoreLocation
class GlanceController: WKInterfaceController, CLLocationManagerDelegate {
var userLocationCity = String()
var vc = ViewController()
var manager = CLLocationManager()
var watchWeather = String()
var arrayWeather = [String()]
@IBOutlet var watchCityLabel: WKInterfaceLabel!
@IBOutlet var watchWeatherLabel: WKInterfaceLabel!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var userLocation: CLLocation = locations[0] as! CLLocation
CLGeocoder().reverseGeocodeLocation(userLocation, completionHandler: {
(placemark, error) in
if (error != nil) {
println(error)
}
else {
let p: CLPlacemark = CLPlacemark(placemark: placemark[0] as! CLPlacemark)
self.userLocationCity = p.locality
println(p.locality)
self.watchWeather = self.vc.getWeather(self.userLocationCity)
self.watchCityLabel.setText(self.userLocationCity)
self.arrayWeather = self.watchWeather.componentsSeparatedByString("\n\n")
var newWatchWeather = self.arrayWeather[0]
self.watchWeatherLabel.setText(newWatchWeather)
}
})
}
}
|
//
// SecureTipsViewController.swift
// SuperSenha
//
// Created by Pedro Barbosa on 16/03/21.
// Copyright © 2021 Pedro Barbosa. All rights reserved.
//
import UIKit
class SecureTipsViewController: UIViewController {
// MARK: - Properties
@IBOutlet weak var textView: UITextView!
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
isModalInPresentation = true
if let filepath = Bundle.main.path(forResource: "DicasSenha", ofType: "txt") {
let contents = try? String(contentsOfFile: filepath)
textView.text = contents ?? "Não foi possível carregar o arquivo."
}
}
// MARK: - Actions
@IBAction func close(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
|
//
// LoginViewController.swift
// Flash Chat iOS13
//
// Created by Angela Yu on 21/10/2019.
// Copyright © 2019 Angela Yu. All rights reserved.
//
import UIKit
import Firebase
class LoginViewController: UIViewController {
@IBOutlet weak var emailTextfield: UITextField!
@IBOutlet weak var passwordTextfield: UITextField!
@IBAction func loginPressed(_ sender: UIButton) {
//Login user with email and passport with optional chaining
if let email = emailTextfield.text, let password = passwordTextfield.text{
Auth.auth().signIn(withEmail: email, password: password) { (authresult, error) in
//If any error occurs, let me know by optional binding
if let e = error{
//Function
self.alerta(title: "Something went wrong", message: e.localizedDescription)
}else{
//Navigate to the ChatViewController
self.performSegue(withIdentifier: K.loginSegue, sender: self)
}
}
}
}
//Function with two inputs in oder to use them inside the registerPressed button
func alerta(title: String, message: String){
let alert = UIAlertController.init(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true)
}
}
|
//
// AlertConvertible.swift
// DataSourcePratice
//
// Created by Vincent Lin on 2018/7/1.
// Copyright © 2018 Vincent Lin. All rights reserved.
//
import Foundation
import UIKit
public enum AlertType {
case alert, sheets
}
public enum AlertActionType {
case action, cancel, retry
}
public typealias AlertActionCompletion = (_ action: AlertActionType) -> ()
public protocol BasicAlertConvertible {
func show(title: String, msg: String, type: AlertType, action: AlertActionType, completion: AlertActionCompletion?)
}
public protocol ViewAssistantConvertible {
var dataManager: DataConvertible { get set }
var logger: Logger? { get }
}
public extension UIAlertController {
convenience init(_ alerTitle: String = "",
subTitle msg: String? = "",
actionButtonTitle actionTitle: String? = "",
cancelButtonTitle cancelTitle: String? = "",
completion: AlertActionCompletion?) {
self.init(title: alerTitle, message: msg, preferredStyle: .alert)
let action = UIAlertAction(title: actionTitle ?? "Sure", style: .destructive) { (_) in
completion?(.action)
}
let cancel = UIAlertAction(title: cancelTitle ?? "Cancel", style: .cancel) { (_) in
completion?(.cancel)
}
addAction(action)
addAction(cancel)
}
}
public struct EasyAlert: BasicAlertConvertible {
public func show(title: String, msg: String, type: AlertType, action: AlertActionType, completion: AlertActionCompletion?) {
let alert = UIAlertController.init(
"DemoTitle",
subTitle: "DemoSubtitle",
actionButtonTitle: "DemoAction",
cancelButtonTitle: "DemoCancel",
completion: completion)
}
}
|
//
// ResultViewController.swift
// Tipsy
//
// Created by Tarokh on 8/4/20.
// Copyright © 2020 Tarokh. All rights reserved.
//
import UIKit
class ResultViewController: UIViewController {
// define some variables
var amountPerPersonValue: Double?
var tipSelection: Int?
var numberOfPeople: Double?
// define some @IBOutlets
@IBOutlet var tipLabel: UILabel!
@IBOutlet var amountPerPersonLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let formattedPeople = String(format: "%.0f", numberOfPeople!)
// Do any additional setup after loading the view.
self.amountPerPersonLabel.text = String(format: "%.1f", amountPerPersonValue!)
self.tipLabel.text = "Split between \(formattedPeople) people, with \(tipSelection!)% tip."
}
// define some functions
@IBAction func reCalculateButtonPressed(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
|
//
// CXGalleryViewController.swift
// Silly Monks
//
// Created by Sarath on 10/04/16.
// Copyright © 2016 Sarath. All rights reserved.
//
import UIKit
import SDWebImage
import mopub_ios_sdk
import CoreLocation
class CXGalleryViewController: UIViewController,UICollectionViewDataSource, UICollectionViewDelegate,CHTCollectionViewDelegateWaterfallLayout {
var galleryCollectionView: UICollectionView!
var spinner:DTIActivityIndicatorView!// = DTIActivityIndicatorView()
var imageViewCntl: CXImageViewController!
var activityIndicatorView: DTIActivityIndicatorView!
var bottomAd: MPAdView!
let reuseIdentifier = "cell" // also enter this string as the cell identifier in the storyboard
var stores : NSMutableArray!
var headerStr : String!
var viewControllers : NSMutableArray!
var imageItemsDict:NSMutableDictionary = NSMutableDictionary()
var galleryImages: [UIImage] = []
var imagesCache: NSCache = NSCache()
var leftAndRightCount : NSInteger = 0
var interstitialAdController:MPInterstitialAdController!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.smBackgroundColor()
self.stores.removeObjectAtIndex(0)
print("Gallery Stores \(self.stores)")
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
self.activityIndicatorView = DTIActivityIndicatorView(frame: CGRect(x:(self.view.frame.size.width-60)/2, y:200.0, width:60.0, height:60.0))
self.activityIndicatorView.hidden = false
self.view.addSubview(self.activityIndicatorView)
self.activityIndicatorView.startActivity()
}
self.customizeHeaderView()
self.performSelector(#selector(CXGalleryViewController.threadAction), withObject: self, afterDelay: 1.0, inModes: [NSDefaultRunLoopMode])
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
func threadAction() {
self.customizeMainView()
}
func customizeHeaderView() {
self.navigationController?.navigationBar.translucent = false;
self.navigationController?.navigationBar.barTintColor = UIColor.navBarColor()
let lImage = UIImage(named: "left_aarow.png") as UIImage?
let button = UIButton (type: UIButtonType.Custom) as UIButton
button.frame = CGRectMake(0, 0, 40, 40)
button.setImage(lImage, forState: .Normal)
button.addTarget(self, action: #selector(CXGalleryViewController.backAction), forControlEvents: .TouchUpInside)
self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: button)
let tLabel : UILabel = UILabel()
tLabel.frame = CGRectMake(0, 0, 120, 40);
tLabel.backgroundColor = UIColor.clearColor()
tLabel.font = UIFont.init(name: "Roboto-Bold", size: 18)
tLabel.text = "Gallery - \(headerStr)"
tLabel.textAlignment = NSTextAlignment.Center
tLabel.textColor = UIColor.whiteColor()
self.navigationItem.titleView = tLabel
}
func customizeMainView() {
let layout = CHTCollectionViewWaterfallLayout()
layout.minimumColumnSpacing = 10.0
layout.minimumInteritemSpacing = 10.0
self.galleryCollectionView = UICollectionView.init(frame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-50), collectionViewLayout: layout)
self.galleryCollectionView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth]
self.galleryCollectionView.delegate = self
self.galleryCollectionView.dataSource = self
self.galleryCollectionView.alwaysBounceVertical = true
self.galleryCollectionView.backgroundColor = UIColor.clearColor()
self.galleryCollectionView.registerClass(CXGalleryCollectionViewCell.self, forCellWithReuseIdentifier: "GalleryCellIdentifier")
self.view.addSubview(self.galleryCollectionView)
self.activityIndicatorView.stopActivity()
self.addTheBottomAdd()
}
//MARK:Add The bottom add
func addTheBottomAdd(){
let bottomAddView : UIView = UIView(frame:CGRectMake(0, self.galleryCollectionView.frame.size.height+5, self.galleryCollectionView.frame.size.width, 49))
//bottomAddView.backgroundColor = UIColor.greenColor()
self.bottomAd = SampleAppInstanceProvider.sharedInstance.buildMPAdViewWithAdUnitID(CXConstant.mopub_banner_ad_id, size: CGSizeMake(self.view.frame.size.width, 49))
self.bottomAd.frame = CGRectMake(50, 0, self.view.frame.size.width, 50)
if CXConstant.currentDeviceScreen() == IPHONE_5S{
self.bottomAd = SampleAppInstanceProvider.sharedInstance.buildMPAdViewWithAdUnitID(CXConstant.mopub_banner_ad_id, size: CGSizeMake(self.view.frame.size.width, 40))
self.bottomAd.frame = CGRectMake(0, 0, self.view.frame.size.width, 39)
}
//self.bottomAd.backgroundColor = UIColor.redColor()
self.bottomAd.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin, .FlexibleTopMargin, .FlexibleBottomMargin]
bottomAddView.addSubview(self.bottomAd)
self.bottomAd.loadAd()
self.view.addSubview(bottomAddView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func backAction() {
self.navigationController?.popViewControllerAnimated(true)
}
func rightBtnAction() {
}
func collectionView(collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return self.stores.count;
// return galleryImages.count
}
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let identifier = "GalleryCellIdentifier"
let cell: CXGalleryCollectionViewCell! = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as?CXGalleryCollectionViewCell
if cell == nil {
collectionView.registerNib(UINib(nibName: "CXGalleryCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: identifier)
}
cell.picView.image = nil
cell.activity.hidden = true
let store :NSDictionary = self.stores[indexPath.row] as! NSDictionary
let gallImage :String = store.valueForKey("URL") as! String
cell.picView.sd_setImageWithURL(NSURL(string: gallImage)!,
placeholderImage: UIImage(named: "smlogo.png"),
options: SDWebImageOptions.RefreshCached,
completed: { (image, error, cacheType, imageURL) -> () in
// print("Downloaded and set! and Image size \(image?.size)")
self.imageItemsDict.setValue(image, forKey: String(indexPath.row))
//collectionView.reloadItemsAtIndexPaths([indexPath])
}
)
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
print("Collection view at row \(collectionView.tag) selected index path \(indexPath) indexPath Row\(indexPath.row)")
// NSNumber(int: UIPageViewControllerSpineLocation.Mid)
let o = UIPageViewControllerSpineLocation.Mid.rawValue //toRaw makes it conform to AnyObject
let k = UIPageViewControllerOptionSpineLocationKey
let options = NSDictionary(object: o, forKey: k)
let pageCntl : CXPageViewController = CXPageViewController(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: options as! [String : AnyObject])
self.viewControllers = NSMutableArray()
for var i = 0; i <= self.stores.count-1; i++ {
let store :NSDictionary = self.stores[i] as! NSDictionary
let gallImage :String = store.valueForKey("URL") as! String
let imageControl = CXImageViewController.init()
imageControl.imagePath = gallImage
imageControl.pageIndex = i
self.viewControllers.addObject(imageControl)
}
pageCntl.setViewControllers([viewControllers[indexPath.item] as! UIViewController], direction: .Forward, animated: true) { (animated) in
}
pageCntl.doubleSided = false
pageCntl.dataSource = self
self.presentViewController(pageCntl, animated: true) {
}
/*self.navigationController?.setNavigationBarHidden(true, animated: true)
let store :NSDictionary = self.stores[indexPath.row] as! NSDictionary
let gallImage :String = store.valueForKey("URL") as! String
let imageControl = CXImageViewController.init()
imageControl.imagePath = gallImage
self.navigationController?.pushViewController(imageControl, animated: false)*/
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let cWidth = collectionView.frame.size.width;
let reqImgWidth = (cWidth-30)/2
let ratioValue = 480/reqImgWidth
let reqImgHeight = 800/ratioValue
return CGSizeMake(reqImgWidth, reqImgHeight)
}
}
extension CXGalleryViewController : UIPageViewControllerDataSource {
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
self.leftAndRightCount += 1
if self.leftAndRightCount == 10 {
self.leftAndRightCount = 0
self.addTheInterstitialCustomAds()
}
let imageControl : CXImageViewController = (viewController as? CXImageViewController)!
self.imageViewCntl = imageControl
//imageControl.swipeCount = self.leftAndRightCount
if(imageControl.pageIndex == 0){
return nil
}
return self.viewControllers![imageControl.pageIndex - 1] as! UIViewController
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
self.leftAndRightCount += 1
if self.leftAndRightCount == 10 {
self.leftAndRightCount = 0
self.addTheInterstitialCustomAds()
}
let imageControl : CXImageViewController = (viewController as? CXImageViewController)!
self.imageViewCntl = imageControl
//imageControl.swipeCount = self.leftAndRightCount
if(imageControl.pageIndex < (self.viewControllers?.count)!-1){
return self.viewControllers![imageControl.pageIndex + 1] as! UIViewController
}
return nil
}
func addTheInterstitialCustomAds(){
self.interstitialAdController = SampleAppInstanceProvider.sharedInstance.buildMPInterstitialAdControllerWithAdUnitID(CXConstant.mopub_interstitial_ad_id)
self.interstitialAdController.delegate = self
self.interstitialAdController.loadAd()
self.interstitialAdController.showFromViewController(self.imageViewCntl)
// if let dataaDelegate = UIApplication.sharedApplication().delegate
//delegate.window!!.rootViewController
}
}
extension CXGalleryViewController: MPInterstitialAdControllerDelegate {
func interstitialDidAppear(interstitial: MPInterstitialAdController!) {
self.interstitialAdController.showFromViewController(self.imageViewCntl)
}
//[[[[UIApplication sharedApplication] delegate] window] rootViewController]
}
//http://stackoverflow.com/questions/25305945/use-of-undeclared-type-viewcontroller-when-unit-testing-my-own-viewcontroller
|
//
// LocalImagesFooterReusableView.swift
// piwigo
//
// Created by Eddy Lelièvre-Berna on 19/04/2020.
// Copyright © 2020 Piwigo.org. All rights reserved.
//
import UIKit
class LocalImagesFooterReusableView: UICollectionReusableView {
@IBOutlet weak var nberOfImagesLabel: UILabel!
func configure(with nberOfImages: Int) -> Void {
// Appearance
nberOfImagesLabel.textColor = UIColor.piwigoColorHeader()
nberOfImagesLabel.font = UIFont.piwigoFontLight()
// Number of images
if nberOfImages == 0 {
// Display "No images"
nberOfImagesLabel.text = NSLocalizedString("noImages", comment: "No Images")
} else {
// Display number of images…
nberOfImagesLabel.text = String(format: "%ld %@", nberOfImages,
(nberOfImages > 1 ? NSLocalizedString("categoryTableView_photosCount", comment: "photos") : NSLocalizedString("categoryTableView_photoCount", comment: "photo")))
}
}
}
|
//
// ASChoicesRow.swift
// SimpleAgricolaScorer
//
// Created by Benjamin Wishart on 2015-04-27.
// Copyright (c) 2015 Benjamin Wishart. All rights reserved.
//
import UIKit
protocol ChoicesDelegate {
func choicesView(changedChoiceToIndex choiceIndex: Int)
}
class ASChoicesRow: ASRow {
var choice: String = ""
var multiChoices: [String] = []
var delegate: ChoicesDelegate?
init(title: String, withChoices choices: [String], modifierRule: ASModifierRule) {
super.init(title: title)
multiChoices = choices
rule = modifierRule
}
func choiceChanged(index: Int) {
delegate?.choicesView(changedChoiceToIndex: index)
}
}
|
//
// SearchViewController.swift
// OrgTech
//
// Created by Maksym Balukhtin on 22.04.2020.
// Copyright © 2020 Maksym Balukhtin. All rights reserved.
//
import Foundation
import UIKit
enum SearchViewEvent {
case onTableViewEvent(SearchTableViewManagerEvent)
case onSeacrhEvent(SearchManagerEvent)
}
protocol SearchPresenterToView: AnyObject {
func setupInitialState()
func populateSearchData(_ data: [ShortProductModel])
func clear(_ totally: Bool)
func showError()
}
final class SearchViewController: BuildableViewController<SearchView>, TabRepresentile {
var presenter: SearchViewToPresenter?
var relatedTabBarItem: UITabBarItem? = AppDefaults.TabIndicator.search
var tableViewManager: SearchTableViewManager?
var searchManager: SearchManager?
override func viewDidLoad() {
super.viewDidLoad()
presenter?.onViewLoaded()
}
}
extension SearchViewController: SearchPresenterToView {
func setupInitialState() {
setupUI()
setupActions()
}
func populateSearchData(_ data: [ShortProductModel]) {
guard !data.isEmpty else {
mainView.tableView.isHidden = true
mainView.tipLabel.isHidden = false
return
}
mainView.tableView.isHidden = false
mainView.tipLabel.isHidden = true
tableViewManager = SearchTableViewManager(mainView.tableView, data: data)
tableViewManager?.eventHandler = { [unowned self] event in
self.presenter?.onViewEvent(.onTableViewEvent(event))
}
}
func clear(_ totally: Bool = false) {
tableViewManager = nil
mainView.tableView.isHidden = true
mainView.tipLabel.isHidden = false
mainView.tipLabel.text = totally ? AppDefaults.Strings.Label.searchTip : mainView.tipLabel.text
}
func showError() {
clear()
mainView.tipLabel.text = AppDefaults.Strings.Label.searchEmpty
}
}
private extension SearchViewController {
func setupUI() {
let searchBar = UISearchBar()
searchBar.placeholder = AppDefaults.Strings.Placeholder.search
searchManager = SearchManager(searchBar)
navigationItem.titleView = searchBar
isKeyboardHandlable = true
}
func setupActions() {
searchManager?.eventHandler = { [unowned self] event in
self.presenter?.onViewEvent(.onSeacrhEvent(event))
}
}
}
|
//
// homedishesVC.swift
// final-project
//
// Created by Vinsofts on 11/19/20.
// Copyright © 2020 Vinsofts. All rights reserved.
//
import UIKit
class homedishesVC: BaseVC {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var lblTitle: UILabel!
var arrDisplay = dataFood
var HomePopularCollectionViewCell = "HomePopularCollectionViewCell"
var name = String()
var hvc : homevc = .none
override func viewDidLoad() {
super.viewDidLoad()
initUI()
}
func initUI() {
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UINib(nibName: HomePopularCollectionViewCell, bundle: nil), forCellWithReuseIdentifier: HomePopularCollectionViewCell)
self.lblTitle.text = name
switch hvc {
case .popular:
arrDisplay = arrDisplay.sorted{$0.rating! > $1.rating!}
case .all:
arrDisplay = arrDisplay.sorted{$0.name! < $1.name!}
case .none:
return
}
}
@IBAction func backAct(_ sender: Any) {
self.navigationController?.popViewController(animated: true)
}
}
extension homedishesVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrDisplay.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomePopularCollectionViewCell, for: indexPath) as! HomePopularCollectionViewCell
if let image = arrDisplay[indexPath.item].image {
cell.foodImage.kf.setImage(with: URL(string: image))
}
if let name = arrDisplay[indexPath.item].name {
cell.foodName.text = name
}
if let star = arrDisplay[indexPath.item].rating {
switch star {
case 0:
cell.foodStar1.image = #imageLiteral(resourceName: "gray-star")
cell.foodStar2.image = #imageLiteral(resourceName: "gray-star")
cell.foodStar3.image = #imageLiteral(resourceName: "gray-star")
cell.foodStar4.image = #imageLiteral(resourceName: "gray-star")
cell.foodStar5.image = #imageLiteral(resourceName: "gray-star")
case 1:
cell.foodStar1.image = #imageLiteral(resourceName: "red-star")
cell.foodStar2.image = #imageLiteral(resourceName: "gray-star")
cell.foodStar3.image = #imageLiteral(resourceName: "gray-star")
cell.foodStar4.image = #imageLiteral(resourceName: "gray-star")
cell.foodStar5.image = #imageLiteral(resourceName: "gray-star")
case 2:
cell.foodStar1.image = #imageLiteral(resourceName: "red-star")
cell.foodStar2.image = #imageLiteral(resourceName: "red-star")
cell.foodStar3.image = #imageLiteral(resourceName: "gray-star")
cell.foodStar4.image = #imageLiteral(resourceName: "gray-star")
cell.foodStar5.image = #imageLiteral(resourceName: "gray-star")
case 3:
cell.foodStar1.image = #imageLiteral(resourceName: "red-star")
cell.foodStar2.image = #imageLiteral(resourceName: "red-star")
cell.foodStar3.image = #imageLiteral(resourceName: "red-star")
cell.foodStar4.image = #imageLiteral(resourceName: "gray-star")
cell.foodStar5.image = #imageLiteral(resourceName: "gray-star")
case 4:
cell.foodStar1.image = #imageLiteral(resourceName: "red-star")
cell.foodStar2.image = #imageLiteral(resourceName: "red-star")
cell.foodStar3.image = #imageLiteral(resourceName: "red-star")
cell.foodStar4.image = #imageLiteral(resourceName: "red-star")
cell.foodStar5.image = #imageLiteral(resourceName: "gray-star")
case 5:
cell.foodStar1.image = #imageLiteral(resourceName: "red-star")
cell.foodStar2.image = #imageLiteral(resourceName: "red-star")
cell.foodStar3.image = #imageLiteral(resourceName: "red-star")
cell.foodStar4.image = #imageLiteral(resourceName: "red-star")
cell.foodStar5.image = #imageLiteral(resourceName: "red-star")
default:
cell.foodStar1.image = #imageLiteral(resourceName: "gray-star")
cell.foodStar2.image = #imageLiteral(resourceName: "gray-star")
cell.foodStar3.image = #imageLiteral(resourceName: "gray-star")
cell.foodStar4.image = #imageLiteral(resourceName: "gray-star")
cell.foodStar5.image = #imageLiteral(resourceName: "gray-star")
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: UIScreen.main.bounds.width / 2.1, height: UIScreen.main.bounds.width / 2.1)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
cart.append(arrDisplay[indexPath.item])
}
}
|
//
// ViewController.swift
// InstaCloneApp
//
// Created by Semih Kalaycı on 23.08.2021.
//
import UIKit
import Firebase
class ViewController: UIViewController {
@IBOutlet weak var emailText: UITextField!
@IBOutlet weak var passwordText: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func singInClicked(_ sender: Any) {
if emailText.text != "" && passwordText.text != "" {
Auth.auth().signIn(withEmail: emailText.text! , password: passwordText.text!) { authData, error in
if error != nil {
self.makeAlert(titleInput: "ERROR!", messageInput: error!.localizedDescription ?? "Error")
}else{
self.performSegue(withIdentifier: "toFeedVC", sender: nil)
}
}
}else{
makeAlert(titleInput: "ERROR!", messageInput: "USERNAME or PASSWORD can not be nil!")
}
}
@IBAction func singUpClicked(_ sender: Any) {
if emailText.text != "" && passwordText.text != "" {
Auth.auth().createUser(withEmail: emailText.text!, password: passwordText.text!) { authData, error in
if error != nil {
self.makeAlert(titleInput: "ERROR!", messageInput: error!.localizedDescription ?? "Error")
}else{
self.performSegue(withIdentifier: "toFeedVC", sender: nil)
}
}
}
else{
makeAlert(titleInput: "ERROR!", messageInput: "USERNAME or PASSWORD can not be nil!")
}
}
func makeAlert(titleInput:String, messageInput:String) {
let alert = UIAlertController(title: titleInput , message: messageInput, preferredStyle: UIAlertController.Style.alert)
let okBtn = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)
alert.addAction(okBtn)
self.present(alert, animated: true, completion: nil)
}
}
|
//
// AppInitializer.swift
// SilofitExam
//
// Created by Piyush Sharma on 2020-04-26.
// Copyright © 2020 Piyush Sharma. All rights reserved.
//
import Foundation
import AHContainer
import Firebase
import EitherResult
final class AppInitializer {
private let window: UIWindow
var rootRouter: RootRouter?
private var serviceProvider: ServiceProviderType = ServiceProvider()
init(window: UIWindow) {
self.window = window
}
func start() {
initializeFirebase()
launchUI()
}
private func launchUI() {
let container = ALViewControllerContainer(initialVC: UIViewController())
let factory = RootRouterFactory(serviceProvider: serviceProvider,
_container: container,
containerProvider: ContainerProviderImp())
rootRouter = RootRouter(userInfoServiceProvider: serviceProvider,
routableFactory: factory)
window.rootViewController = rootRouter?.container.viewController
window.makeKeyAndVisible()
}
private func initializeFirebase() {
FirebaseApp.configure()
}
}
|
//
// CategoryImage.swift
// ToDo
//
// Created by Takumi Fuzawa on 2021/01/15.
//
import SwiftUI
struct CategoryImage: View {
var category: TodoEntity.Category
init(_ category: TodoEntity.Category?) {
self.category = category ?? .ImpUrg_1st
}
var body: some View {
Image(systemName: category.image())
.resizable()
.scaledToFit()
.foregroundColor(.white)
.padding(2.0)
.frame(width: 30, height: 30)
.background(category.color())
.cornerRadius(6.0)
}
}
struct CategoryImage_Previews: PreviewProvider {
static var previews: some View {
CategoryImage(TodoEntity.Category.ImpUrg_1st).scaledToFit()
}
}
|
//
// SoundRow.swift
// PlayIt WatchKit Extension
//
// Created by Gokul Nair on 25/08/20.
// Copyright © 2020 Gokul Nair. All rights reserved.
//
import WatchKit
class SoundRow: NSObject {
@IBOutlet weak var musicLabel: WKInterfaceLabel!
}
|
//
// ColoredPolyline.swift
// CycloApp
//
// Created by Michal Klein on 12/03/2017.
// Copyright © 2017 Michal Klein. All rights reserved.
//
import Foundation
import MapKit
struct SpeedInterval {
let speeds: [Double]
let isPause: Bool
}
final class ColoredPolyline: MKPolyline {
var color: UIColor?
class func polylines(for path: [Point]) -> [ColoredPolyline] {
var segments: [ColoredPolyline] = []
let red = (r: 1.0, g: 20.0 / 255.0, b: 44.0 / 255.0)
let yellow = (r: 1.0, g: 215.0 / 255.0, b: 0.0)
let green = (r: 0.0, g: 146.0 / 255.0, b: 78.0 / 255.0)
let intervals = speedIntervals(for: path)
let sortedSpeeds: [Double] = intervals.filter { !$0.isPause }.flatMap { $0.speeds }.sorted()
let maxSpeedIndex = Int(0.9 * Double(sortedSpeeds.count))
let midSpeadIndex = Int(0.3 * Double(sortedSpeeds.count))
let minSpeedIndex = Int(0.05 * Double(sortedSpeeds.count))
let minSpeed = sortedSpeeds[minSpeedIndex]
let midSpeed = sortedSpeeds[midSpeadIndex]
let maxSpeed = sortedSpeeds[maxSpeedIndex]
var pathIndex = 1
for interval in intervals {
for i in 1..<interval.speeds.count {
var coords = [path[pathIndex-1].coordinate, path[pathIndex].coordinate]
pathIndex += 1
let speed = interval.speeds[i-1]
let color: UIColor
if interval.isPause { // Paused interval is always gray
color = .cycloGray
} else if speed < minSpeed { // Slowest x% speeds are always red
color = UIColor(red: CGFloat(red.r), green: CGFloat(red.g), blue: CGFloat(red.b), alpha: 1)
} else if speed < midSpeed { // red -> yellow
let ratio = (speed - minSpeed) / (midSpeed - minSpeed)
let r = CGFloat(red.r + ratio * (yellow.r - red.r))
let g = CGFloat(red.g + ratio * (yellow.g - red.g))
let b = CGFloat(red.b + ratio * (yellow.b - red.b))
color = UIColor(red: r, green: g, blue: b, alpha: 1)
} else if speed < maxSpeed { // yellow -> green
let ratio = (speed - midSpeed) / (maxSpeed - midSpeed)
let r = CGFloat(yellow.r + ratio * (green.r - yellow.r))
let g = CGFloat(yellow.g + ratio * (green.g - yellow.g))
let b = CGFloat(yellow.b + ratio * (green.b - yellow.b))
color = UIColor(red: r, green: g, blue: b, alpha: 1)
} else { // Top x% speeds are always green
color = UIColor(red: CGFloat(green.r), green: CGFloat(green.g), blue: CGFloat(green.b), alpha: 1)
}
let segment = ColoredPolyline(coordinates: &coords, count: coords.count)
segment.color = color
segments.append(segment)
}
}
return segments
}
private class func speedIntervals(for path: [Point]) -> [SpeedInterval] {
guard path.count >= 2 else { return [] }
var intervals: [SpeedInterval] = []
var currentIntervalPoints: [Point] = []
for i in 1..<path.count {
let prev = path[i-1]
let cur = path[i]
currentIntervalPoints.append(prev)
if cur.isPause != prev.isPause {
if currentIntervalPoints.count >= 2 {
intervals.append(speedInterval(for: currentIntervalPoints))
}
currentIntervalPoints = []
}
}
currentIntervalPoints.append(path.last!)
if currentIntervalPoints.count >= 2 {
intervals.append(speedInterval(for: currentIntervalPoints))
}
return intervals
}
private class func speedInterval(for path: [Point]) -> SpeedInterval {
var speeds: [Double] = []
for i in 1 ..< path.count {
let p1 = path[i-1]
let p2 = path[i]
let cl1 = CLLocation(latitude: p1.coordinate.latitude, longitude: p1.coordinate.longitude)
let cl2 = CLLocation(latitude: p2.coordinate.latitude, longitude: p2.coordinate.longitude)
let d = cl2.distance(from: cl1)
let t = p2.date.timeIntervalSince(p1.date)
let s = d/t
speeds.append(s)
}
return SpeedInterval(speeds: speeds, isPause: path[0].isPause)
}
}
|
//
// String+APPDemo.swift
// APPDemo
//
// Created by Francesco Colleoni on 28/04/16.
// Copyright © 2016 Near srl. All rights reserved.
//
import Foundation
extension String {
var localized: String {
return NSLocalizedString(self, comment: "")
}
func pluralized(args: CVarArgType...) -> String {
return withVaList(args) { NSString(format: self.localized, locale: NSLocale.currentLocale(), arguments: $0) } as String
}
}
func -(source: String, unwanted: [String]) -> String {
var output = source
for string in unwanted {
output = output.stringByReplacingOccurrencesOfString(string, withString: "")
}
return output
}
|
//
// LabelWithAdaptiveTextHeight.swift
// KayakFirst Ergometer E2
//
// Created by Balazs Vidumanszki on 2017. 03. 11..
// Copyright © 2017. Balazs Vidumanszki. All rights reserved.
//
import UIKit
class LabelWithAdaptiveTextHeight: UILabel {
private var defMaxFontSize: CGFloat = 300
init(maxFontSize: CGFloat) {
self.defMaxFontSize = maxFontSize
super.init(frame: CGRect.zero)
}
init() {
super.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
font = fontToFitHeight()
}
// Returns an UIFont that fits the new label's height.
private func fontToFitHeight() -> UIFont {
var minFontSize: CGFloat = 18
var maxFontSize = defMaxFontSize
var fontSizeAverage: CGFloat = 0
var textAndLabelHeightDiff: CGFloat = 0
while (minFontSize <= maxFontSize) {
fontSizeAverage = minFontSize + (maxFontSize - minFontSize) / 2
guard text != nil && text!.characters.count > 0 else {
break
}
if let labelText: String = text {
let labelHeight = frame.size.height
let testStringHeight = labelText.size(
attributes: [NSFontAttributeName: font.withSize(fontSizeAverage)]
).height
textAndLabelHeightDiff = labelHeight - testStringHeight
if (fontSizeAverage == minFontSize || fontSizeAverage == maxFontSize) {
if (textAndLabelHeightDiff < 0) {
return font.withSize(fontSizeAverage - 1)
}
return font.withSize(fontSizeAverage)
}
if (textAndLabelHeightDiff < 0) {
maxFontSize = fontSizeAverage - 1
} else if (textAndLabelHeightDiff > 0) {
minFontSize = fontSizeAverage + 1
} else {
return font.withSize(fontSizeAverage)
}
}
}
return font.withSize(fontSizeAverage)
}
}
|
//
// DetailProtocol.swift
// Examen_Miguel_Delgado
//
// Created by Miguel Angel Delgado Alcantara on 25/02/21.
//
import Foundation
import UIKit
protocol DetailPresenterProtocol: class {
func getTextForLabel(codeLabel: UILabel, nameLabel: UILabel, unidadLabel: UILabel, dateLabel: UILabel, valueLabel: UILabel)
}
protocol DetailViewProtocol: class {
}
|
//
// MusicClassFormViewController.swift
// NodaTrainer
//
// Created by sangeles on 8/29/18.
// Copyright © 2018 SAM Creators. All rights reserved.
//
import UIKit
import Firebase
class MusicClassFormViewController: UIViewController {
@IBOutlet weak var txtTitle: UITextField!
@IBOutlet weak var txtPrice: UITextField!
@IBOutlet weak var txtProfessor: UITextField!
@IBOutlet weak var txtPhone: UITextField!
@IBOutlet weak var txtDescription: UITextView!
@IBOutlet weak var txtComments: UITextView!
@IBOutlet weak var imgClass: UIImageView!
@IBOutlet weak var btnPublish: UIButton!
@IBOutlet weak var scType: UISegmentedControl!
var imagePicker: UIImagePickerController!
var indexType: Int!
let databaseRef = Database.database().reference()
var musicClassId: String!
var musicClassPassed: MusicClass!
override func viewDidLoad() {
print("MusicClassController")
print("viewDidLoad")
super.viewDidLoad()
let imageTap = UITapGestureRecognizer(target: self, action: #selector(openImagePicker))
imgClass.isUserInteractionEnabled = true
imgClass.addGestureRecognizer(imageTap)
imgClass.clipsToBounds = true
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = true
imagePicker.sourceType = .photoLibrary
imagePicker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
btnPublish.isHidden = false
scType.selectedSegmentIndex = 0
indexType = 0
if musicClassPassed != nil {
print("musicClassPassed != nil, " + musicClassPassed.title)
loadSelected()
}
}
@objc func openImagePicker(_ sender: Any) {
self.present(imagePicker, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func loadSelected() {
print("loadSelected")
btnPublish.isHidden = true
txtTitle.text = musicClassPassed.title
txtPrice.text = musicClassPassed.price
txtProfessor.text = musicClassPassed.professor
txtPhone.text = musicClassPassed.phone
txtDescription.text = musicClassPassed.description
txtComments.text = musicClassPassed.comments
scType.selectedSegmentIndex = musicClassPassed.type
indexType = scType.selectedSegmentIndex
let url = URL(string: musicClassPassed.image)
let data = try? Data(contentsOf: url!)
if data != nil {
imgClass.image = UIImage(data: data!)
}
}
@IBAction func addMusicClass(_ sender: Any) {
//guardar firebase
let title = txtTitle.text
let price = txtPrice.text
let professor = txtProfessor.text
let phone = txtPhone.text
let description = txtDescription.text
let comments = txtComments.text
guard let image = imgClass.image else { return }
if((title?.isEmpty)! || (price?.isEmpty)! || (professor?.isEmpty)! || (phone?.isEmpty)!) {
displayAlertMessage(message: "Ingrese todos los campos obligatorios");
return;
}
self.uploadClassImage(image) { url in
if(url != nil) {
self.saveClassData(titleValue: title!, priceValue: price!, professorValue: professor!, phoneValue: phone!, descriptionValue: description!, commentsValue: comments!, imageURL: url!) { success in
if success {
self.dismiss(animated: true, completion: nil)
} else {
print("Error: No se pudo publicar la clase de música")
self.displayAlertMessage(message: "No se pudo publicar la clase de música")
}
}
} else {
self.displayAlertMessage(message: "No se pudo guardar la imagen seleccionada")
}
}
}
//uploadImage to Firebase Storage
func uploadClassImage(_ image: UIImage, completion: @escaping ((_ url:URL?) -> ())) {
musicClassId = databaseRef.child("classes").childByAutoId().key
let storageRef = Storage.storage().reference().child("classes/\(String(describing: musicClassId))")
//guard let imageData = UIImageJPEGRepresentation(image, 0.15) else { return }
guard let imageData = image.jpegData(compressionQuality: 0.15) else { return }
let metaData = StorageMetadata()
metaData.contentType = "image/jpg"
storageRef.putData(imageData, metadata: metaData) { metaData, error in
if error == nil, metaData != nil {
storageRef.downloadURL { url, error in
if error == nil, url != nil {
if let newUrl = url {
completion(newUrl)
} else {
print("newUrl error \(error!.localizedDescription)")
completion(nil)
}
} else {
print("error is not nil or url is nil, error \(error!.localizedDescription)")
completion(nil)
}
}
} else {
print("metadata is nil or error is not nil, error \(error!.localizedDescription)")
completion(nil)
}
}
}
func saveClassData(titleValue: String, priceValue: String, professorValue: String, phoneValue: String, descriptionValue: String, commentsValue: String, imageURL: URL, completion: @escaping ((_ success: Bool) -> ()) ) -> Void{
let classesObject = [
"title": titleValue,
"price": priceValue,
"professor": professorValue,
"phone": phoneValue,
"description": descriptionValue,
"comments": commentsValue,
"type": indexType,
"image": imageURL.absoluteString
] as [String:Any]
let childUpdates = ["/classes/\(String(describing: musicClassId))/": classesObject]
databaseRef.updateChildValues(childUpdates, withCompletionBlock: { (error, ref) in
completion(error == nil)
})
}
@IBAction func goBack(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func switchType(_ sender: UISegmentedControl) {
indexType = sender.selectedSegmentIndex
}
//Alert message. Receives the message as a parameter
func displayAlertMessage(message:String) {
let alert = UIAlertController(title: "Vuelva a Intentar", message: message, preferredStyle: UIAlertController.Style.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil);
alert.addAction(okAction);
self.present(alert, animated: true, completion: nil);
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
txtTitle.resignFirstResponder()
txtPrice.resignFirstResponder()
txtProfessor.resignFirstResponder()
txtPhone.resignFirstResponder()
txtDescription.resignFirstResponder()
txtComments.resignFirstResponder()
}
}
extension MusicClassFormViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let pickedImage = info[.originalImage] as? UIImage {
imgClass.image = pickedImage
}
picker.dismiss(animated: true, completion: nil)
}
}
|
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
///
/// A _org.antlr.v4.runtime.Token_ object representing a token of a particular type; e.g.,
/// `<ID>`. These tokens are created for _org.antlr.v4.runtime.tree.pattern.TagChunk_ chunks where the
/// tag corresponds to a lexer rule or token type.
///
public class TokenTagToken: CommonToken {
///
/// This is the backing field for _#getTokenName_.
///
private let tokenName: String
///
/// This is the backing field for _#getLabel_.
///
private let label: String?
///
/// Constructs a new instance of _org.antlr.v4.runtime.tree.pattern.TokenTagToken_ for an unlabeled tag
/// with the specified token name and type.
///
/// - Parameter tokenName: The token name.
/// - Parameter type: The token type.
///
public convenience init(_ tokenName: String, _ type: Int) {
self.init(tokenName, type, nil)
}
///
/// Constructs a new instance of _org.antlr.v4.runtime.tree.pattern.TokenTagToken_ with the specified
/// token name, type, and label.
///
/// - Parameter tokenName: The token name.
/// - Parameter type: The token type.
/// - Parameter label: The label associated with the token tag, or `null` if
/// the token tag is unlabeled.
///
public init(_ tokenName: String, _ type: Int, _ label: String?) {
self.tokenName = tokenName
self.label = label
super.init(type)
}
///
/// Gets the token name.
/// - Returns: The token name.
///
public final func getTokenName() -> String {
return tokenName
}
///
/// Gets the label associated with the rule tag.
///
/// - Returns: The name of the label associated with the rule tag, or
/// `null` if this is an unlabeled rule tag.
///
public final func getLabel() -> String? {
return label
}
///
///
///
/// The implementation for _org.antlr.v4.runtime.tree.pattern.TokenTagToken_ returns the token tag
/// formatted with `<` and `>` delimiters.
///
override
public func getText() -> String {
if let label = label {
return "<" + label + ":" + tokenName + ">"
}
return "<" + tokenName + ">"
}
///
///
///
/// The implementation for _org.antlr.v4.runtime.tree.pattern.TokenTagToken_ returns a string of the form
/// `tokenName:type`.
///
override
public var description: String {
return tokenName + ":" + String(type)
}
}
|
import Foundation
import UIKit
class RoundedButton: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLayout()
}
override init(frame: CGRect) {
super.init(frame: frame)
setupLayout()
}
private func setupLayout() {
layer.cornerRadius = frame.height / 2
}
}
|
//
// Search.swift
// IT Book
//
// Created by Eryk Chrustek on 25/09/2020.
// Copyright © 2020 Eryk Chrustek. All rights reserved.
//
import UIKit
import Foundation
// MARK: ViewController
struct Welcome: Codable {
let error, total, page: String
let books: [Book]
}
struct Book: Codable {
let title, subtitle, isbn13, price: String
let image: String
let url: String
}
|
//
// NSAttributedString+HTML.swift
// StarterKit
//
// Created by Emilio Pavia on 25/11/2019.
// Copyright © 2019 Emilio Pavia. All rights reserved.
//
import UIKit
extension NSAttributedString {
public convenience init?(htmlBody: String?,
font: UIFont,
color: UIColor,
tintColor: UIColor? = nil,
lineHeight: Float? = nil,
alignment: NSTextAlignment = .left,
layoutDirection: UITraitEnvironmentLayoutDirection = .leftToRight) {
guard let body = htmlBody else { return nil }
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
color.getRed(&r, green: &g, blue: &b, alpha: &a)
var tr: CGFloat = 0, tg: CGFloat = 0, tb: CGFloat = 0, ta: CGFloat = 0
(tintColor ?? color).getRed(&tr, green: &tg, blue: &tb, alpha: &ta)
// FIXME: https://openradar.appspot.com/6153065
let fontFamily: String
if font.familyName == UIFont.systemFont(ofSize: font.pointSize).familyName {
fontFamily = "-apple-system"
} else {
fontFamily = font.familyName
}
let lh = lineHeight != nil ? "\(lineHeight!)px" : "normal"
let document = """
<html>
<head>
<style>
html * {
color: rgba(\(r * 255.0), \(g * 255.0), \(b * 255.0), \(a));
font-family: \(fontFamily) !important;
font-size: \(font.pointSize) !important;
line-height: \(lh);
text-align: \(alignment.htmlTextAlignment);
direction: \(layoutDirection.htmlDirection);
}
a {
color: rgba(\(tr * 255.0), \(tg * 255.0), \(tb * 255.0), \(ta));
font-weight: bold;
}
</style>
</head>
<body>
\(body)
</body>
</html>
"""
try? self.init(data: document.data(using: String.Encoding.utf8)!,
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
}
}
extension NSTextAlignment {
var htmlTextAlignment: String {
switch self {
case .center:
return "center"
case .right:
return "right"
case .justified:
return "justify"
default:
return "left"
}
}
}
extension UITraitEnvironmentLayoutDirection {
var htmlDirection: String {
switch self {
case .rightToLeft:
return "rtl"
default:
return "ltr"
}
}
}
|
//
// ViewController.swift
// Contact_style_test
//
// Created by Gregory Keeley on 5/21/20.
// Copyright © 2020 Gregory Keeley. All rights reserved.
//
import UIKit
import Contacts
import ContactsUI
class allContactsViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var testContacts = CustomContact.defaultContacts()
var contacts = [CNContact]()
//MARK:- ViewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
configureTableView()
}
private func configureTableView() {
tableView.delegate = self
tableView.dataSource = self
}
//MARK:- Presents the native iOS contacts View Controller to ge the user
@IBAction func addContactButtonPressed(_ sender: UIBarButtonItem) {
let contactPicker = CNContactPickerViewController()
contactPicker.delegate = self
//Note: This is where we can create a predicate to only allow certain contacts on the CNContactPickerViewController to be highlighted
//Question: How to create a predicate? The formatting below is not something I am familiar with. It's contained within a string and has an "@" before the condition
contactPicker.predicateForEnablingContact = NSPredicate(format: "emailAddresses.@count > 0")
present(contactPicker, animated: true)
}
}
//MARK:- CNContactPickerDelegate
extension allContactsViewController: CNContactPickerDelegate {
//Note: There is a delegate for a single contact and multiple!
func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
//Note: This compactMap uses the contact from the convenience init in CustomContact class
let contacts = contacts.compactMap { CustomContact(contact: $0) }
for contact in contacts {
if !testContacts.contains(contact) {
testContacts.append(contact)
}
}
tableView.reloadData()
}
}
//MARK:- TableViewDelegate & DataSource
extension allContactsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let contact = testContacts[indexPath.row]
// let editViewController = TableViewController(contact: contact)
let contactViewController = CNContactViewController(forUnknownContact: contact.contactValue)
// editViewController.contact = contact
// editViewController.cnContact = contact.contactValue
// navigationController?.pushViewController(editViewController, animated: true)
navigationController?.pushViewController(contactViewController, animated: true)
}
}
extension allContactsViewController: UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return testContacts.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "contact", for: indexPath)
let contact = testContacts[indexPath.row]
cell.textLabel?.text = contact.firstName
cell.detailTextLabel?.text = contact.workEmail
return cell
}
}
|
import Tailor
final class Person: Persistable, Equatable {
let id: UInt
var name: String
var gender: String
var birthDate: Date
var deathDate: Date?
var reignStartDate: Date?
var reignEndDate: Date?
var fatherId: UInt?
var motherId: UInt?
init(name: String, gender: String, birthDate: Date, deathDate: Date? = nil, reignStartDate: Date? = nil, reignEndDate: Date? = nil, father: Person? = nil, mother: Person? = nil) {
self.id = 0
self.gender = gender
self.name = name
self.birthDate = birthDate
self.deathDate = deathDate
self.reignStartDate = reignStartDate
self.reignEndDate = reignEndDate
self.fatherId = father?.id
self.motherId = mother?.id
}
init(deserialize values: SerializableValue) throws {
id = try values.read("id")
gender = try values.read("gender")
name = try values.read("name")
birthDate = try values.read("birth_date")
deathDate = try values.read("death_date")
reignStartDate = try values.read("reign_start_date")
reignEndDate = try values.read("reign_end_date")
fatherId = try values.read("father_id")
motherId = try values.read("mother_id")
}
func valuesToPersist() -> [String: SerializationEncodable?] {
return [
"name": name,
"gender": gender,
"birth_date": birthDate,
"death_date": deathDate,
"reign_start_date": reignStartDate,
"reign_end_date": reignEndDate,
"father_id": fatherId,
"mother_id": motherId
]
}
var father: Person? {
get { return Person.query.find(fatherId ?? 0) }
set { fatherId = newValue?.id }
}
var mother: Person? {
get { return Person.query.find(motherId ?? 0) }
set { motherId = newValue?.id }
}
static let tableName = "people"
static let query = Query<Person>()
} |
//
// BillListViewController.swift
// Open Secrets
//
// Created by Adam Barr-Neuwirth on 12/25/17.
// Copyright © 2017 Adam Barr-Neuwirth. All rights reserved.
//
import Foundation
import UIKit
import SwiftyJSON
import CRRefresh
import Firebase
import SwiftyStoreKit
let stateDictionaryWords: [String : String] = [
"AK" : "Alaska",
"AL" : "Alabama",
"AR" : "Arkansas",
"AS" : "American Samoa",
"AZ" : "Arizona",
"CA" : "California",
"CO" : "Colorado",
"CT" : "Connecticut",
"DC" : "District of Columbia",
"DE" : "Delaware",
"FL" : "Florida",
"GA" : "Georgia",
"GU" : "Guam",
"HI" : "Hawaii",
"IA" : "Iowa",
"ID" : "Idaho",
"IL" : "Illinois",
"IN" : "Indiana",
"KS" : "Kansas",
"KY" : "Kentucky",
"LA" : "Louisiana",
"MA" : "Massachusetts",
"MD" : "Maryland",
"ME" : "Maine",
"MI" : "Michigan",
"MN" : "Minnesota",
"MO" : "Missouri",
"MS" : "Mississippi",
"MT" : "Montana",
"NC" : "North Carolina",
"ND" : "North Dakota",
"NE" : "Nebraska",
"NH" : "New Hampshire",
"NJ" : "New Jersey",
"NM" : "New Mexico",
"NV" : "Nevada",
"NY" : "New York",
"OH" : "Ohio",
"OK" : "Oklahoma",
"OR" : "Oregon",
"PA" : "Pennsylvania",
"PR" : "Puerto Rico",
"RI" : "Rhode Island",
"SC" : "South Carolina",
"SD" : "South Dakota",
"TN" : "Tennessee",
"TX" : "Texas",
"UT" : "Utah",
"VA" : "Virginia",
"VI" : "Virgin Islands",
"VT" : "Vermont",
"WA" : "Washington",
"WI" : "Wisconsin",
"WV" : "West Virginia",
"WY" : "Wyoming",
"MP" : "Northern Mariana Islands"]
let stateDictionary: [String : String] = [
"AK" : "alaska",
"AL" : "alabama",
"AR" : "arkansas",
"AZ" : "arizona",
"CA" : "california",
"CO" : "colorado",
"CT" : "connecticut",
"DE" : "delaware",
"FL" : "florida",
"GA" : "georgia",
"HI" : "hawaii",
"IA" : "iowa",
"ID" : "idaho",
"IL" : "illinois",
"IN" : "indiana",
"KS" : "kansas",
"KY" : "kentucky",
"LA" : "louisiana",
"MA" : "massachusetts",
"MD" : "maryland",
"ME" : "maine",
"MI" : "michigan",
"MN" : "minnesota",
"MO" : "missouri",
"MS" : "mississippi",
"MT" : "montana",
"NC" : "north_carolina",
"ND" : "north_dakota",
"NE" : "nebraska",
"NH" : "new_hampshire",
"NJ" : "new_jersey",
"NM" : "new_mexico",
"NV" : "nevada",
"NY" : "new_york",
"OH" : "ohio",
"OK" : "oklahoma",
"OR" : "oregon",
"PA" : "pennsylvania",
"PR" : "puerto_rico",
"RI" : "rhode_island",
"SC" : "south_carolina",
"SD" : "south_dakota",
"TN" : "tennessee",
"TX" : "texas",
"UT" : "utah",
"VA" : "virginia",
"VT" : "vermont",
"WA" : "washington",
"WI" : "wisconsin",
"WV" : "west_virginia",
"WY" : "wyoming"]
extension UITableView {
func reloadDataWithAutoSizingCellWorkAround() {
self.isScrollEnabled = false
self.reloadData()
self.setNeedsLayout()
self.layoutIfNeeded()
self.reloadData()
self.isScrollEnabled = true
}
}
class BillTableCell: UITableViewCell {
@IBOutlet weak var stateLabel: UILabel!
@IBOutlet weak var stateFlag: UIImageView!
@IBOutlet weak var titleHeight: NSLayoutConstraint!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var numberLabel: UILabel!
@IBOutlet weak var voteLabel: UILabel!
@IBOutlet weak var questionResultLabel: UILabel!
@IBOutlet weak var bodyView: UITextView!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var sponsorParty: UILabel!
@IBOutlet weak var csD: UILabel!
@IBOutlet weak var csR: UILabel!
@IBOutlet weak var csI: UILabel!
@IBOutlet weak var separatorView: UIView!
}
class BillListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
@IBOutlet weak var loadingLabel: UILabel!
@IBOutlet weak var loadingSpinner: UIActivityIndicatorView!
@IBOutlet weak var tableView: UITableView!
var type = ""
var url = ""
var name = ""
var oneparty = ""
var descriptionArray: [String] = []
var numberArray: [String] = []
var chamberArray: [String] = []
var dateArray: [String] = []
var titleArray: [String] = []
var questionArray: [String] = []
var voteArray: [Int] = []
var repArray: [Int] = []
var demArray: [Int] = []
var indArray: [Int] = []
var uriArray: [String] = []
var slugArray: [String] = []
var task: URLSessionDataTask? = nil
var sponsorPartyArray: [String] = []
var sponsorStateArray: [String] = []
var sponsorStateWordArray: [String] = []
var offset = 1
var showalert = true
var loading = false
var cellHeights: [IndexPath : CGFloat] = [:]
override func viewDidLoad() {
super.viewDidLoad()
self.title = name
tableView.contentInset = UIEdgeInsetsMake(10, 0, 0, 0);
self.view.backgroundColor = UIColor(red:0.93, green:0.94, blue:0.95, alpha:1.0)
tableView.backgroundColor = UIColor(red:0.93, green:0.94, blue:0.95, alpha:1.0)
tableView.delegate = self
tableView.dataSource = self
tableView.isHidden = true
loadingSpinner.startAnimating()
if(url.contains("subjects") && premium == false){
askForPurchase()
}
else{
getInfo()
}
}
func askForPurchase(){
let alert = UIAlertController(title: "Congress Reveal Premium", message: "You need premium to access this feature. Get premium for $1.99?", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Get Premium", style: UIAlertActionStyle.default, handler: getPremium))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: dismissView))
self.present(alert, animated: true, completion: nil)
}
func getPremium(alert: UIAlertAction){
SwiftyStoreKit.retrieveProductsInfo(["premiumPurchase"]) { result in
if let product = result.retrievedProducts.first {
SwiftyStoreKit.purchaseProduct(product, quantity: 1, atomically: true) { result in
switch result {
case .success(let purchase):
print("Purchase Success: \(purchase.productId)")
premium = true
UserDefaults.standard.set(true, forKey: "premium")
self.thankYou()
case .error(let error):
switch error.code {
case .unknown: print("Unknown error. Please contact support")
case .clientInvalid: print("Not allowed to make the payment")
case .paymentCancelled: break
case .paymentInvalid: print("The purchase identifier was invalid")
case .paymentNotAllowed: print("The device is not allowed to make the payment")
case .storeProductNotAvailable: print("The product is not available in the current storefront")
case .cloudServicePermissionDenied: print("Access to cloud service information is not allowed")
case .cloudServiceNetworkConnectionFailed: print("Could not connect to the network")
case .cloudServiceRevoked: print("User has revoked permission to use this cloud service")
}
}
}
}
}
}
func thankYou(){
let alert = UIAlertController(title: "Thank you!", message: "You now have access to all premium features", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: getInfo)
}
func errorPay(){
let alert = UIAlertController(title: "Error", message: "There was an error purchasing premium", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: dismissViewCompletion)
}
func dismissView(alert: UIAlertAction){
_ = navigationController?.popViewController(animated: true)
}
func dismissViewCompletion(){
_ = navigationController?.popViewController(animated: true)
}
func getInfo(){
print("getting info: " + url)
let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
let session = URLSession.shared
request.httpMethod = "GET"
request.addValue("oudp6lkdQjlsgqHFlXSzk6Jg64A3a6WoYeOIlG0t", forHTTPHeaderField: "X-API-Key")
task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
if(data != nil){
let json = JSON(data: data!)
dump("getting bills")
var members = json
if(self.type == "subject"){
members = json["results"]
}
else if(self.type == "sponsored"){
members = json["results"][0]["bills"]
}
for (_,subJson):(String, JSON) in members {
var skip = false
if let shortt = subJson["short_title"].string{
self.numberArray.append(shortt)
}
else{
skip = true
}
if(!skip){
if(subJson["bill_uri"].string != nil){
self.uriArray.append(subJson["bill_uri"].string as String!)
}
else{
self.uriArray.append("0")
}
if var billid = subJson["bill_id"].string{
if let dashRange = billid.range(of: "-") {
billid.removeSubrange(dashRange.lowerBound..<billid.endIndex)
}
self.slugArray.append(billid as String!)
}
else{
self.slugArray.append("0")
}
self.chamberArray.append(subJson["number"].string as String!)
self.dateArray.append(self.changeDate(dateIn: subJson["introduced_date"].string as String!))
if let title = (subJson["title"].string as String!){ //if title isnt null
self.descriptionArray.append(title)
print("appending title")
if let ss = subJson["summary_short"].string{
if(title != ss && ss != ""){
self.titleArray.append(title + "\n\n" + ss)
}
else{
self.titleArray.append(title)
}
}
else{
self.titleArray.append(title)
}
}
else{
self.descriptionArray.append("")
if let ss = subJson["summary_short"].string{
self.titleArray.append(ss)
print("appending ss")
}
else{
self.titleArray.append("No summary available")
}
}
self.sponsorPartyArray.append(subJson["sponsor_party"].string!)
self.sponsorStateArray.append(subJson["sponsor_state"].string!)
self.sponsorStateWordArray.append(stateDictionaryWords[subJson["sponsor_state"].string!]!)
let name = (subJson["sponsor_name"].string! as String!).replacingOccurrences(of: "'", with: "'")
self.questionArray.append(name) //add html entity parser
self.voteArray.append(subJson["cosponsors"].int!)
if let reps = subJson["cosponsors_by_party"]["R"].int{
self.repArray.append(reps)
}
else{
self.repArray.append(0)
}
if let dems = subJson["cosponsors_by_party"]["D"].int{
self.demArray.append(dems)
}
else{
self.demArray.append(0)
}
if let inds = subJson["cosponsors_by_party"]["I"].int{
self.indArray.append(inds)
}
else{
self.indArray.append(0)
}
}
}
}
DispatchQueue.main.async(execute: {
self.loadingSpinner.stopAnimating()
self.loadingSpinner.isHidden = true
self.loadingLabel.isHidden = true
if(self.dateArray.count > 0){
print("reloading data")
self.tableView.reloadData()
self.tableView.isHidden = false
}
else{
if(self.showalert){
let alert = UIAlertController(title: "No Data", message: "No bill data was found.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: {action in
_ = self.navigationController?.popViewController(animated: true)
}))
self.present(alert, animated: true, completion: nil)
}
}
})
})
task?.resume()
tableView.cr.addFootRefresh(animator: NormalFooterAnimator()) { [weak self] in
/// start refresh
self?.loadNext(lastRow: (self?.dateArray.count)!)
DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
/// If common end
self?.tableView.cr.endLoadingMore()
/// If no more data
self?.tableView.cr.noticeNoMoreData()
/// Reset no more data
self?.tableView.cr.resetNoMore()
})
}
}
func loadNext(lastRow: Int){
loading = true
let request = NSMutableURLRequest(url: NSURL(string: url + "?offset=" + String(describing: 20*offset))! as URL)
let session = URLSession.shared
request.httpMethod = "GET"
request.addValue("oudp6lkdQjlsgqHFlXSzk6Jg64A3a6WoYeOIlG0t", forHTTPHeaderField: "X-API-Key")
task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
if(data != nil){
let json = JSON(data: data!)
dump("getting bills")
var members = json
if(self.type == "subject"){
members = json["results"]
}
else if(self.type == "sponsored"){
members = json["results"][0]["bills"]
}
if(members.isEmpty){
print("no more results")
}
else{
for (_,subJson):(String, JSON) in members {
var skip = false
if let shortt = subJson["short_title"].string{
self.numberArray.append(shortt)
}
else{
skip = true
}
if(!skip){
if(subJson["bill_uri"].string != nil){
self.uriArray.append(subJson["bill_uri"].string as! String)
}
else{
self.uriArray.append("0")
}
if var billid = subJson["bill_id"].string{
if let dashRange = billid.range(of: "-") {
billid.removeSubrange(dashRange.lowerBound..<billid.endIndex)
}
self.slugArray.append(billid as! String)
}
else{
self.slugArray.append("0")
}
self.chamberArray.append(subJson["number"].string!)
self.dateArray.append(self.changeDate(dateIn: subJson["introduced_date"].string as String!))
if let title = (subJson["title"].string as String!){ //if title isnt null
self.descriptionArray.append(title)
print("appending title")
if let ss = subJson["summary_short"].string{
if(title != ss && ss != ""){
self.titleArray.append(title + "\n\n" + ss)
}
else{
self.titleArray.append(title)
}
}
else{
self.titleArray.append(title)
}
}
else{
self.descriptionArray.append("")
if let ss = subJson["summary_short"].string{
self.titleArray.append(ss)
print("appending ss")
}
else{
self.titleArray.append("No summary available")
}
}
self.sponsorPartyArray.append(subJson["sponsor_party"].string!)
self.sponsorStateArray.append(subJson["sponsor_state"].string!)
self.sponsorStateWordArray.append(stateDictionaryWords[subJson["sponsor_state"].string! as String!]!)
self.questionArray.append((subJson["sponsor_name"].string! as String!).replacingOccurrences(of: "'", with: "'"))
self.voteArray.append(subJson["cosponsors"].int!)
if let reps = subJson["cosponsors_by_party"]["R"].int{
self.repArray.append(reps)
}
else{
self.repArray.append(0)
}
if let dems = subJson["cosponsors_by_party"]["D"].int{
self.demArray.append(dems)
}
else{
self.demArray.append(0)
}
if let inds = subJson["cosponsors_by_party"]["I"].int{
self.indArray.append(inds)
}
else{
self.indArray.append(0)
}
}
}
}
}
DispatchQueue.main.async(execute: {
self.offset+=1
self.tableView.reloadData()
self.loading = false
})
})
task?.resume()
}
override func viewWillAppear(_ animated: Bool) {
print("bill view will appear")
Analytics.setScreenName("Bill List", screenClass: self.description)
self.navigationController?.setNavigationBarHidden(false, animated: animated)
if(oneparty == "R"){
print("setting bar to red")
self.navigationController!.navigationBar.barStyle = .blackTranslucent
self.navigationController?.navigationBar.barTintColor = UIColor.red
self.navigationController?.navigationBar.tintColor = .white
}
else if(oneparty == "D"){
print("setting bar to blue")
self.navigationController!.navigationBar.barStyle = .blackTranslucent
self.navigationController?.navigationBar.barTintColor = UIColor.blue
self.navigationController?.navigationBar.tintColor = .white
}
else{
self.navigationController!.navigationBar.barStyle = .default
self.navigationController?.navigationBar.tintColor = nil
self.navigationController?.navigationBar.barTintColor = nil
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
showalert = false
task?.cancel()
}
func handleHtml(string : String) -> NSAttributedString{
var returnStr = NSMutableAttributedString()
do {
returnStr = try NSMutableAttributedString(data: string.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
let fullRange : NSRange = NSMakeRange(0, returnStr.length)
returnStr.addAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 13.0)], range: fullRange)
} catch {
print(error)
}
return returnStr
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//count of array
return dateArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! BillTableCell
cell.bodyView.backgroundColor = UIColor.white
cell.backgroundColor = UIColor(red:0.93, green:0.94, blue:0.95, alpha:1.0)
cell.bodyView.sizeToFit()
cell.bodyView.isScrollEnabled = false
cell.bodyView.isUserInteractionEnabled = false
cell.descriptionLabel.numberOfLines = 3
cell.descriptionLabel.adjustsFontSizeToFitWidth = false
cell.descriptionLabel.attributedText = handleHtml(string: numberArray[indexPath.row])
cell.descriptionLabel.font = UIFont.boldSystemFont(ofSize: 17.0)
cell.descriptionLabel.lineBreakMode = .byTruncatingTail
cell.titleHeight.constant = CGFloat(63 - 21*(3-cell.descriptionLabel.numberOfVisibleLines))
if let imagename = stateDictionary[sponsorStateArray[indexPath.row]]{
cell.stateFlag.image = UIImage(named: imagename)
}
else{
cell.stateFlag.image = UIImage(named: "about")
}
cell.stateFlag.layer.borderWidth = 0
cell.stateFlag.layer.cornerRadius = 3.0
cell.stateFlag.layer.masksToBounds = true
cell.numberLabel.text = chamberArray[indexPath.row]
cell.dateLabel.text = dateArray[indexPath.row]
cell.bodyView.attributedText = handleHtml(string: titleArray[indexPath.row])
cell.voteLabel.text = questionArray[indexPath.row]
if(sponsorPartyArray[indexPath.row] == "D"){
cell.sponsorParty.textColor = UIColor.blue
cell.sponsorParty.text = "Ⓓ"
}
else if(sponsorPartyArray[indexPath.row] == "R"){
cell.sponsorParty.textColor = UIColor.red
cell.sponsorParty.text = "Ⓡ"
}
else{
cell.sponsorParty.textColor = UIColor.black
cell.sponsorParty.text = "Ⓘ"
}
cell.questionResultLabel.text = "Cosponsors: "
cell.stateLabel.text = sponsorStateWordArray[indexPath.row]
cell.csR.text = String(describing: repArray[indexPath.row]) + " Ⓡ"
cell.csD.text = String(describing: demArray[indexPath.row]) + " Ⓓ"
cell.csI.text = String(describing: indArray[indexPath.row]) + " Ⓘ"
cell.containerView.backgroundColor = UIColor.white
cell.containerView.layer.borderWidth = 0
cell.containerView.layer.cornerRadius = 3.0
cell.containerView.layer.shadowRadius = 2
cell.containerView.layer.shadowOffset = CGSize(width: 0, height: 1)
cell.containerView.layer.shadowOpacity = 0.5
cell.containerView.clipsToBounds = false
cell.containerView.layer.masksToBounds = false
cell.selectionStyle = UITableViewCellSelectionStyle.none
cell.containerView.setNeedsLayout()
cell.containerView.layoutIfNeeded()
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("DETAILS TAPPED:")
dump(self.chamberArray[indexPath.row])
dump(self.slugArray[indexPath.row])
if(self.uriArray[indexPath.row] != "0"){
let controller = self.storyboard?.instantiateViewController(withIdentifier: "billview") as! BillViewController
controller.id = self.chamberArray[indexPath.row]
controller.url = self.uriArray[indexPath.row]
controller.slug = self.slugArray[indexPath.row]
self.navigationController?.pushViewController(controller, animated: true)
}
else{
let alert = UIAlertController(title: "No Details", message: "There are no more details available for this bill", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath){
cellHeights[indexPath] = cell.frame.size.height
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
guard let height = cellHeights[indexPath] else { return 70.0 }
return height
}
func changeDate(dateIn: String) -> String{
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM d, y"
let date: NSDate? = dateFormatterGet.date(from: dateIn) as NSDate?
return dateFormatter.string(from: date! as Date)
}
}
|
//
// UIView+Extension.swift
// Foody2
//
// Created by Sebastian Strus on 2018-06-15.
// Copyright © 2018 Sebastian Strus. All rights reserved.
//
import UIKit
extension UIView {
func createStackView(views: [UIView]) -> UIStackView {
let stackView = UIStackView(arrangedSubviews: views)
stackView.axis = .vertical
stackView.distribution = .fillProportionally
stackView.spacing = Device.IS_IPHONE ? 10 : 20
return stackView
}
func setAnchor(width: CGFloat, height: CGFloat) {
self.setAnchor(top: nil,
leading: nil,
bottom: nil,
trailing: nil,
paddingTop: 0,
paddingLeft: 0,
paddingBottom: 0,
paddingRight: 0,
width: width,
height: height)
}
func setAnchor(top: NSLayoutYAxisAnchor?, leading: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, trailing: NSLayoutXAxisAnchor?, paddingTop: CGFloat, paddingLeft: CGFloat, paddingBottom: CGFloat, paddingRight: CGFloat, width: CGFloat = 0, height: CGFloat = 0) {
self.translatesAutoresizingMaskIntoConstraints = false
if let top = top {
self.topAnchor.constraint(equalTo: top, constant: paddingTop).isActive = true
}
if let leading = leading {
self.leadingAnchor.constraint(equalTo: leading, constant: paddingLeft).isActive = true
}
if let bottom = bottom {
self.bottomAnchor.constraint(equalTo: bottom, constant: -paddingBottom).isActive = true
}
if let trailing = trailing {
self.trailingAnchor.constraint(equalTo: trailing, constant: -paddingRight).isActive = true
}
if width != 0 {
self.widthAnchor.constraint(equalToConstant: width).isActive = true
}
if height != 0 {
self.heightAnchor.constraint(equalToConstant: height).isActive = true
}
}
var safeTopAnchor: NSLayoutYAxisAnchor {
if #available(iOS 11.0, *) {
return safeAreaLayoutGuide.topAnchor
}
return topAnchor
}
var safeLeadingAnchor: NSLayoutXAxisAnchor {
if #available(iOS 11.0, *) {
return safeAreaLayoutGuide.leadingAnchor
}
return leadingAnchor
}
var safeBottomAnchor: NSLayoutYAxisAnchor {
if #available(iOS 11.0, *) {
return safeAreaLayoutGuide.bottomAnchor
}
return bottomAnchor
}
var safeTrailingAnchor: NSLayoutXAxisAnchor {
if #available(iOS 11.0, *) {
return safeAreaLayoutGuide.trailingAnchor
}
return trailingAnchor
}
func setCellShadow() {
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width: 2, height: 2)
self.layer.shadowOpacity = 0.4
self.layer.shadowRadius = 4.0
self.layer.masksToBounds = false
self.clipsToBounds = false
self.layer.cornerRadius = 4
}
func pinToEdges(view: UIView) {
setAnchor(top: view.safeTopAnchor,
leading: view.leadingAnchor,
bottom: view.safeBottomAnchor,
trailing: view.trailingAnchor,
paddingTop: 0,
paddingLeft: 0,
paddingBottom: 0,
paddingRight: 0)
}
}
|
import XCTest
import CoreMLTrainingTests
var tests = [XCTestCaseEntry]()
tests += CoreMLTrainingTests.allTests()
XCTMain(tests)
|
import Delta
struct ToggleCompletedAction: ActionType {
let todo: Todo
func reduce(state: State) -> State {
state.todos.value = state.todos.value.map {
todo in
guard todo == self.todo else { return todo }
return Todo(todoId: todo.todoId,
name: todo.name,
description: todo.description,
notes: todo.notes,
completed: !todo.completed,
synced: !todo.synced,
selected: todo.selected)
}
return state
}
}
|
import XCTest
import GISHelperKit
final class GISHelperKitTests: XCTestCase {
func testArraySum() {
let list = (1...5).map{$0}
let expect = list
.reduce(0, +)
let result = list.sum(by: \.self)
XCTAssertEqual(expect, result)
}
static var allTests = [
("testArraySum", testArraySum),
]
}
|
import UIKit
class AllMusicController: UITableViewController {
var searchController : UISearchController!
var audiosArray = Array<HRAudioItemModel>()
var loading = false
var hrRefeshControl = UIRefreshControl()
override func loadView() {
super.loadView()
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "All Music"
self.tableView.rowHeight = 70
self.tableView.tableFooterView = UIView(frame: CGRectZero)
self.refreshAudios()
self.tableView.registerClass(HRAllMusicCell.self, forCellReuseIdentifier: "HRAllMusicCell")
self.tableView.allowsMultipleSelectionDuringEditing = false
self.addLeftBarButton()
self.hrRefeshControl.addTarget(self, action: "refreshAudios", forControlEvents: UIControlEvents.ValueChanged)
self.refreshControl = self.hrRefeshControl
// add search
let searchAudioController = HRSearchAudioController()
self.searchController = UISearchController(searchResultsController: searchAudioController)
self.searchController.searchResultsUpdater = searchAudioController
self.searchController.searchBar.sizeToFit()
self.searchController.searchBar.tintColor = UIColor.blackColor()
self.searchController.searchBar.placeholder = ""
self.tableView.tableHeaderView = self.searchController.searchBar
self.definesPresentationContext = true
self.extendedLayoutIncludesOpaqueBars = true
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
// MARK: - load all audio
func loadMoreAudios() {
if loading == false {
loading = true
dispatch.async.global({ () -> Void in
HRAPIManager.sharedInstance.vk_audioget(0, count: 100, offset: self.audiosArray.count, completion: { (vkAudiosArray) -> () in
var countAudios = self.audiosArray.count
self.audiosArray.appendContentsOf(vkAudiosArray)
var indexPaths = [NSIndexPath]()
for countAudios; countAudios < self.audiosArray.count;countAudios++ {
let indexPath = NSIndexPath(forRow: countAudios-1, inSection: 0)
indexPaths.append(indexPath)
}
dispatch.async.main({ () -> Void in
//TODO: !hack! disable animations it's not good soulution for fast add cells, mb. need play with layer.speed in cell :/
//UIView.setAnimationsEnabled(false)
self.tableView.beginUpdates()
self.tableView.insertRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.None)
self.tableView.endUpdates()
//UIView.setAnimationsEnabled(true)
self.loading = false
})
})
})
}
}
func refreshAudios() {
if loading == false {
loading = true
HRAPIManager.sharedInstance.vk_audioget(0, count: 100, offset: 0, completion: { (vkAudiosArray) -> () in
self.audiosArray = vkAudiosArray
dispatch.async.main({ () -> Void in
self.refreshControl?.endRefreshing()
self.tableView.reloadData()
self.loading = false
})
})
}
}
// mark: - tableView delegate
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.audiosArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let audio = self.audiosArray[indexPath.row]
let cell:HRAllMusicCell = self.tableView.dequeueReusableCellWithIdentifier("HRAllMusicCell", forIndexPath: indexPath) as! HRAllMusicCell
cell.audioAristLabel.text = audio.artist
cell.audioTitleLabel.text = audio.title
cell.allMusicController = self
cell.audioModel = audio
if audio.downloadState == 3 {
cell.downloadButton.hidden = true
} else {
cell.downloadButton.hidden = false
}
//cell.audioDurationTime.text = self.durationFormater(Double(audio.duration))
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
dispatch.async.main { () -> Void in
let audioLocalModel = self.audiosArray[indexPath.row]
HRPlayerManager.sharedInstance.items = self.audiosArray
HRPlayerManager.sharedInstance.currentPlayIndex = indexPath.row
HRPlayerManager.sharedInstance.playItem(audioLocalModel)
self.presentViewController(PlayerController(), animated: true, completion: nil)
}
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {
//add code here for when you hit delete
}
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == self.audiosArray.count - 7 {
self.loadMoreAudios()
}
}
//MARK :- stuff
func downloadAudio(model:HRAudioItemModel,progressView:UIProgressView) {
HRDownloadManager.sharedInstance.downloadAudio(model) { (progress) -> () in
dispatch.async.main({ () -> Void in
log.debug("download progress = \(progress)")
progressView.hidden = false
progressView.setProgress(Float(progress), animated: true)
})
}
}
func durationFormater(duration:Double) -> String {
let min = Int(floor(duration / 60))
let sec = Int(floor(duration % 60))
return "\(min):\(sec)"
}
func addLeftBarButton() {
let button = UIBarButtonItem(image: UIImage(named: "menuHumb"), style: UIBarButtonItemStyle.Plain, target: self, action: "openMenu")
self.navigationItem.leftBarButtonItem = button
}
func openMenu() {
HRInterfaceManager.sharedInstance.openMenu()
}
}
|
//
// UIAnimation+PlayAnimation.swift
// Appy
//
// Created by Bizet Rodriguez on 11/14/18.
// Copyright © 2018 Bizet Rodriguez. All rights reserved.
//
import UIKit
import Lottie
extension LOTAnimationView {
func playAnimation(image: String, loop: Bool = true) {
self.setAnimation(named: image)
self.loopAnimation = loop
self.contentMode = .scaleAspectFit
self.play()
}
}
|
//
// BlogIdeaEditorViewController.swift
// BlogIdeaList
//
// Created by Andrew Bancroft on 6/7/19.
// Copyright © 2019 Andrew Bancroft. All rights reserved.
//
import UIKit
import CoreData
class BlogIdeaEditorViewController: UIViewController {
var managedObjectContext: NSManagedObjectContext!
var blogIdea: BlogIdea!
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var descriptionTextField: UITextField!
// MARK: - View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.setUIValues()
}
// MARK: - Set UI
func setUIValues() {
guard let blogIdea = self.blogIdea else { return }
self.titleTextField.text = blogIdea.ideaTitle
self.descriptionTextField.text = blogIdea.ideaDescription
}
// MARK: - Save
// In a storyboard-based application, you will often want to do a little preparation before navigation
@IBAction func saveButtonTapped(_ sender: Any) {
if self.blogIdea == nil {
self.blogIdea = (NSEntityDescription.insertNewObject(forEntityName: BlogIdea.entityName,
into: self.managedObjectContext) as! BlogIdea)
}
self.blogIdea.ideaTitle = self.titleTextField.text
self.blogIdea.ideaDescription = self.descriptionTextField.text
do {
try self.managedObjectContext.save()
_ = self.navigationController?.popViewController(animated: true)
} catch {
let alert = UIAlertController(title: "Trouble Saving",
message: "Something went wrong when trying to save the Blog Idea. Please try again...",
preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK",
style: .default,
handler: {(action: UIAlertAction) -> Void in
self.managedObjectContext.rollback()
self.blogIdea = NSEntityDescription.insertNewObject(forEntityName: BlogIdea.entityName, into: self.managedObjectContext) as? BlogIdea
})
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
self.managedObjectContext.rollback()
}
}
|
//
// ExploreTableViewCell.swift
// SuCasa
//
// Created by Arthur Rodrigues on 08/11/19.
// Copyright © 2019 João Victor Batista. All rights reserved.
//
import UIKit
class ExploreTableViewCell: UITableViewCell {
/// Outlet variables
@IBOutlet weak var adImage: UIImageView!
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var adTitleLabel: UILabel!
@IBOutlet weak var adPriceLabel: UILabel!
@IBOutlet weak var availabilityLabel: UILabel!
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
}
}
|
//
// APIClient.swift
// CovidLookup
//
// Created by Liubov Kaper on 12/3/20.
//
import Foundation
struct APIClient {
// communicate retrieved data back to to the viewController
//ways to do it:
// closure, completion handler
// notification center
// delegation
//combine
// URLSession is an asynchronous API
// sychronous code blocks UI
// asynchronous does not block the main thread, performs request on a background thread
// @escaping means function returns before closure returns
func fetchCovidDAta(completion: @escaping (Result<[Summary], Error>) -> ()) {
//1. endpointURL
// 2. convert the string to an URL
// 3. make request using URLSession
let endpointURLString = "https://api.covid19api.com/summary"
guard let url = URL(string: endpointURLString) else {
print("bad url")
return
}
// .shared is a singleton instance on URLSession, comes with basic configs needed for most requests
let dataTask = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
return completion(.failure(error))
}
// TODO
if let jsonData = data {
// convert data to our swift model
do {
let countries = try JSONDecoder().decode(SummaryWrapper.self, from: jsonData).countries
completion(.success(countries))
} catch {
// decoding error
completion(.failure(error))
}
}
}
dataTask.resume()
}
}
|
//
// MockAPIServiceDelegate.swift
// ClearScoreTests
//
// Created by Sagar Patel on 06/12/2019.
// Copyright © 2019 Sagar Patel. All rights reserved.
//
@testable import ClearScore
// MARK:- MockAPIServiceDelegate
// A stub class implementing the APIServiceDelegate to mock and capture the functionality of
// classes implementing it.
class MockAPIServiceDelegate: APIServiceDelegate {
var dataModel: DataModel?
var error: Error?
var willRefreshDataCalled = false
var dataUpdatedCalled = false
var dataFailedCalled = false
func willRefreshData() {
willRefreshDataCalled = true
}
func data(updatedWith dataModel: DataModel) {
dataUpdatedCalled = true
self.dataModel = dataModel
}
func data(failedWith error: Error) {
dataFailedCalled = true
self.error = error
}
}
|
//
// NewMessageControllerExtension.swift
// GameOfChats
//
// Created by Apple on 3/15/18.
// Copyright © 2018 syntaxerror. All rights reserved.
//
import UIKit
import Firebase
extension NewMessageViewController{
func setUpNavigationBarItems(){
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelNewMessage))
}
func getAllMembers(){
Firebase.Database.database().reference().child(FirebaseConstants.userTableName).observe(.childAdded) { (snapShot) in
if let dictionary = snapShot.value as? [String:AnyObject] {
let user = User(json: dictionary)
self.usersList.append(user)
DispatchQueue.main.async {
self.tableView.reloadData()
}
print("Did Get All Chat Members")
}
}
}
@objc private func cancelNewMessage(){
dismiss(animated: true, completion: nil)
print("Cancelled New Message")
}
}
|
//
// Enums.swift
// Velocity Bom
//
// Created by piyush sinroja on 26/12/18.
// Copyright © 2018 Credencys. All rights reserved.
//
import UIKit
/// Enum For DevelopmentEnvironment
enum DevelopmentEnvironment: String {
///
case development = "Development"
///
case production = "Production"
///
case local = "Local"
///
case staging = "Staging"
}
enum SideMenuSectionScreen: String {
case news = "NEWS"
case event = "EVENTS"
case survey = "SURVEY" //ENQUÊTE
}
|
//
// MyLeaderboardApi+WidgetExtensions.swift
// MyLeaderboardWidgetExtension
//
// Created by Joseph Roque on 2020-06-22.
// Copyright © 2020 Joseph Roque. All rights reserved.
//
import myLeaderboardApi
import UIKit
extension MyLeaderboardApi.WidgetGameFragment {
var previewImage: UIImage? {
guard let image = image, image.hasPrefix("#") else { return nil }
return UIImage(named: String(image.dropFirst()))
}
}
extension MyLeaderboardApi.SmallWidgetRecordFragment: Identifiable {
// swiftlint:disable:next identifier_name
public var id: GraphID {
return game.id
}
}
// MARK: - Mocks
extension MyLeaderboardApi.SmallWidgetResponse {
// swiftlint:disable line_length
static var preview: MyLeaderboardApi.SmallWidgetResponse {
.init(player: .init(records: [
MyLeaderboardApi.SmallWidgetResponse.Player.Records(smallWidgetRecordFragmentFragment: .init(game: .init(widgetGameFragmentFragment: .init(id: GraphID(rawValue: "0"), image: "#HivePreview", name: "Hive")), overallRecord: .init(recordFragmentFragment: .init(wins: 12, losses: 2, ties: 1, isBest: true, isWorst: false)))),
MyLeaderboardApi.SmallWidgetResponse.Player.Records(smallWidgetRecordFragmentFragment: .init(game: .init(widgetGameFragmentFragment: .init(id: GraphID(rawValue: "1"), image: "#PatchworkPreview", name: "Hive")), overallRecord: .init(recordFragmentFragment: .init(wins: 29, losses: 3, ties: 0, isBest: false, isWorst: false)))),
]))
}
// swiftlint:enable line_length
}
extension MyLeaderboardApi.MediumWidgetResponse {
static var preview: MyLeaderboardApi.MediumWidgetResponse {
fatalError()
}
}
|
//
// JoinViewController.swift
// strolling-of-time-ios
//
// Created by 강수진 on 2019/08/17.
// Copyright © 2019 wiw. All rights reserved.
//
import UIKit
class JoinViewController: UIViewController, NibLoadable {
// MARK: - Private
@IBOutlet private weak var profileImageView: UIImageView!
@IBOutlet private weak var idTextField: UITextField!
@IBOutlet private weak var pwdTextField: UITextField!
@IBOutlet private weak var nicknameTextField: UITextField!
@IBOutlet weak var joinButton: UIButton!
private lazy var picker: UIImagePickerController = {
let picker = UIImagePickerController()
picker.allowsEditing = true
picker.delegate = self
picker.sourceType = .photoLibrary
return picker
}()
private func setUI() {
self.profileImageView?.contentMode = .scaleAspectFill
self.profileImageView?.makeRounded()
}
// MARK: - Action
@IBAction private func selectImage(_ sender: Any) {
guard UIImagePickerController.isSourceTypeAvailable(.photoLibrary) else {
return
}
present(picker, animated: true)
}
@IBAction func dismiss(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction private func join(_ sender: Any) {
let id = idTextField?.text
let pwd = pwdTextField?.text
let nickname = nicknameTextField?.text
print("통신 \(id) \(pwd) \(nickname)")
self.dismiss(animated: true, completion: nil)
}
override func viewDidLayoutSubviews() {
self.setUI()
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
hideKeyboarOnTap()
setTextField()
}
func setTextField() {
self.idTextField.delegate = self
self.pwdTextField.delegate = self
self.nicknameTextField.delegate = self
}
func isJoinButtonValid() -> Bool {
guard idTextField.text != "" && pwdTextField.text != "" && nicknameTextField?.text != "" else {
return false
}
return true
}
func setJoinButton() {
self.joinButton.setValidButton(isActive: isJoinButtonValid())
}
}
// MARK: - ImagePickerController & NavigationController
extension JoinViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let image = info[.editedImage] as? UIImage {
self.profileImageView?.image = image
}
self.dismiss(animated: true, completion: nil)
}
}
extension JoinViewController: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
self.setJoinButton()
}
}
|
//
// ContactDetailViewController.swift
// BoostAppTest
//
// Created by 2.9mac256 on 18/03/2020.
//
import UIKit
protocol ContactDetailViewControllerDelegate: class {
func contactDetailViewControllerDidCancel(_ controller: ContactDetailViewController)
func contactDetailViewController(_ controller: ContactDetailViewController, didFinishAdding contact: Contact)
func contactDetailViewController(_ controller: ContactDetailViewController, didFinishEditing contact: Contact)
}
class ContactDetailViewController: UITableViewController {
// MARK:- Properties
enum ContactDetailSection: Int, CaseIterable {
case Main
case Sub
var title: String? {
switch self {
case .Main: return "Main Information"
case .Sub: return "Sub Information"
}
}
}
private let viewModel: ContactDetailViewModel
weak var delegate: ContactDetailViewControllerDelegate?
private var cellArr = [[UITableViewCell]]()
private let headerView: UIView = {
let cell = UIView(frame: .zero)
return cell
}()
private let firstNameCell: UITableViewCell = {
let cell = UITableViewCell(frame: .zero)
return cell
}()
private let lastNameCell: UITableViewCell = {
let cell = UITableViewCell(frame: .zero)
return cell
}()
private let emailCell: UITableViewCell = {
let cell = UITableViewCell(frame: .zero)
return cell
}()
private let phoneCell: UITableViewCell = {
let cell = UITableViewCell(frame: .zero)
return cell
}()
private let avatarView: AvatarView = {
let view = AvatarView(frame: .zero)
return view
}()
private let firstNameTF: CustomTextField = {
let textfield = CustomTextField(frame: .zero)
textfield.returnKeyType = .next
textfield.enablesReturnKeyAutomatically = true
textfield.autocapitalizationType = .words
textfield.autocorrectionType = .no
textfield.keyboardType = .alphabet
return textfield
}()
private let lastNameTF: CustomTextField = {
let textfield = CustomTextField(frame: .zero)
textfield.enablesReturnKeyAutomatically = true
textfield.returnKeyType = .next
textfield.autocapitalizationType = .words
textfield.autocorrectionType = .no
textfield.keyboardType = .alphabet
return textfield
}()
private let emailTF: CustomTextField = {
let textfield = CustomTextField(frame: .zero)
textfield.returnKeyType = .next
textfield.autocapitalizationType = .none
textfield.keyboardType = .emailAddress
textfield.autocorrectionType = .no
return textfield
}()
private let phoneTF: CustomTextField = {
let textfield = CustomTextField(frame: .zero)
textfield.returnKeyType = .done
textfield.keyboardType = .numberPad
return textfield
}()
// MARK:- Lifecycle
init(config: ContactDetailConfiguration) {
viewModel = ContactDetailViewModel(config: config)
super.init(style: .plain)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
super.loadView()
setupLayout()
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
// MARK:- Helper methods
@objc private func cancel() {
delegate?.contactDetailViewControllerDidCancel(self)
}
@objc private func save() {
viewModel.save(
firstName: firstNameTF.text,
lastName: lastNameTF.text,
email: emailTF.text,
phone: phoneTF.text)
}
private func showValidationAlert(for textField: UITextField, alertMessage: String) {
let alertController = UIAlertController(title: "Whoops!", message: alertMessage, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .cancel) { (action) in
textField.becomeFirstResponder()
}
alertController.addAction(action)
present(alertController, animated: true)
}
// MARK:- Interface methods
private func setupLayout() {
setupAvatarView()
setupFields()
}
private func setupAvatarView() {
headerView.addSubview(avatarView)
let avatarViewDimension = view.frame.width * 0.27
avatarView.anchor(size: .init(width: avatarViewDimension, height: avatarViewDimension), centerX: headerView.centerXAnchor)
avatarView.centerYAnchor.constraint(equalTo: headerView.centerYAnchor, constant: -view.frame.width * 0.02).isActive = true
}
private func setupFields() {
let cells = [firstNameCell, lastNameCell, emailCell, phoneCell]
let textFields = [firstNameTF, lastNameTF, emailTF, phoneTF]
let labelTitles = ["First Name", "Last Name", "Email", "Phone"]
for i in 0 ..< cells.count {
let label = UILabel(frame: .zero)
label.text = labelTitles[i]
label.font = UIFont.systemFont(ofSize: 16)
let cell = cells[i]
cell.selectionStyle = .none
let textField = textFields[i]
textField.delegate = self
let stackView = UIStackView(arrangedSubviews: [label, textField])
cell.addSubview(stackView)
stackView.anchor(leading: cell.leadingAnchor, trailing: cell.trailingAnchor, padding: .init(top: 0, left: 15, bottom: 0, right: 15), centerY: cell.centerYAnchor)
label.anchor(size: .init(width: 90, height: 0))
textField.anchor(size: .init(width: 0, height: 32))
}
}
private func setupUI() {
view.backgroundColor = .white
hideKeyboardWhenTappedAround()
setupLeftBarButtonItem()
setupRightBarButtonItem()
setupTableView()
initViewModel()
}
func setupTableView() {
tableView.tableHeaderView = headerView
headerView.frame = .init(x: 0, y: 0, width: view.frame.width, height: view.frame.width * 0.4)
tableView.separatorInset = .init(top: 0, left: 15, bottom: 0, right: 0)
tableView.tableFooterView = .init(frame: .zero)
}
private func initViewModel() {
firstNameTF.text = viewModel.firstName
lastNameTF.text = viewModel.lastName
emailTF.text = viewModel.email
phoneTF.text = viewModel.phone
viewModel.showAlertClosure = { [weak self] (message, inputType) in
guard let weakSelf = self else { return }
let textFieldToFocus: UITextField
switch inputType {
case .firstName:
textFieldToFocus = weakSelf.firstNameTF
case .lastName:
textFieldToFocus = weakSelf.lastNameTF
case .email:
textFieldToFocus = weakSelf.emailTF
case .phone:
textFieldToFocus = weakSelf.phoneTF
}
weakSelf.showValidationAlert(for: textFieldToFocus, alertMessage: message)
}
viewModel.createNewContactClosure = { [weak self] (contact) in
guard let weakSelf = self else { return }
weakSelf.delegate?.contactDetailViewController(weakSelf, didFinishAdding: contact)
}
viewModel.editContactClosure = { [weak self] (contact) in
guard let weakSelf = self else { return }
weakSelf.delegate?.contactDetailViewController(weakSelf, didFinishEditing: contact)
}
}
private func setupLeftBarButtonItem() {
let cancelBarButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancel))
navigationItem.leftBarButtonItem = cancelBarButton
}
private func setupRightBarButtonItem() {
let saveBarButton = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(save))
navigationItem.rightBarButtonItem = saveBarButton
}
deinit {
print("deinit \(self)")
}
}
// MARK: - TableViewDataSource / TableViewDelegate
extension ContactDetailViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return ContactDetailSection.allCases.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch ContactDetailSection(rawValue: indexPath.section) {
case .Main:
if indexPath.row == 0 {
return firstNameCell
} else {
return lastNameCell
}
case .Sub:
if indexPath.row == 0 {
return emailCell
} else {
return phoneCell
}
default:
return UITableViewCell()
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return ContactDetailSection(rawValue: section)?.title
}
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
return nil
}
}
extension ContactDetailViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
switch textField {
case firstNameTF:
lastNameTF.becomeFirstResponder()
case lastNameTF:
emailTF.becomeFirstResponder()
case emailTF:
phoneTF.becomeFirstResponder()
default:
phoneTF.resignFirstResponder()
}
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard textField == phoneTF, let currentText = textField.text else { return true }
if string.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) != nil { return false }
let newCount = currentText.count + string.count - range.length
let addingCharacter = range.length <= 0
if newCount == 1 {
textField.text = addingCharacter ? currentText + "(\(string)" : String(currentText.dropLast(2))
return false
} else if newCount == 5 {
textField.text = addingCharacter ? currentText + ") \(string)" : String(currentText.dropLast(2))
return false
} else if newCount == 10 {
textField.text = addingCharacter ? currentText + "-\(string)" : String(currentText.dropLast(2))
return false
}
if newCount > 14 {
return false
}
return true
}
}
|
//
// RefeicaoDao.swift
// Projeto_Alura
//
// Created by Gabriel Zambelli on 01/02/20.
// Copyright © 2020 Gabriel Zambelli. All rights reserved.
//
import Foundation
class RefeicaoDao{
func save(_ refeicoes: [Refeicao]){
guard let caminho = recuperaCaminho() else{return}
//do: tentar executar, tentar fazer
do{
//metodo para armazenar arquivos no IOS, todo metodo que for throws deve se utilizar "do/try" pois se caso ele não conseguir
//executar devemos tratar o erro no catch
let dados = try NSKeyedArchiver.archivedData(withRootObject: refeicoes, requiringSecureCoding: false)
//escrevao arquivo no caminho
try dados.write(to: caminho)
} catch{
print(error.localizedDescription)
}
}
func recuperaCaminho() -> URL? {
//FileManager gerenciador de diretorios do IOS, resgatando diretorio
guard let diretorio = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {return nil}
//adicionando pasta, caminho ao diretorio, ao Path
let caminho = diretorio.appendingPathComponent("refeicao")
return caminho
}
func recupera() -> [Refeicao]{
guard let caminho = recuperaCaminho() else { return [] }
do{
//regatar os dados do path
let dados = try Data(contentsOf: caminho)
//recuperar os dados salvos
guard let refeicoesSalvas = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(dados) as? [Refeicao] else {return [] }
return refeicoesSalvas
}
catch{
print(error.localizedDescription)
return []
}
}
}
|
//
// MyCrewTitle.swift
// Reached
//
// Created by John Wu on 2016-08-06.
// Copyright © 2016 ReachedTechnologies. All rights reserved.
//
class MyCrewTitle: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var background: UIImageView = {
let imageView = UIImageView()
imageView.backgroundColor = UIColor.darkGrayColor()
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
var title: UILabel = {
let label = UILabel()
label.textColor = UIColor(red: 232/255, green: 159/255, blue: 56/255, alpha: 1)
label.text = "My Crew"
label.textAlignment = NSTextAlignment.Center
label.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI_2))
label.font = UIFont(name: "Montserrat-SemiBold", size: 10.0)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
func setupViews() {
addSubview(background)
addSubview(title)
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":background]))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":background]))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":title]))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":title]))
}
}
|
//
// BarcodeVC.swift
// Hahago
//
// Created by 黃德桑 on 2019/7/13.
// Copyright © 2019 sun. All rights reserved.
//
import UIKit
class BarcodeVC: UIViewController {
@IBOutlet weak var time: UILabel!
@IBOutlet weak var lbshopname: UILabel!
@IBOutlet weak var lbproductname: UILabel!
@IBOutlet weak var lbprice: UILabel!
var product: Product?
var timer: Timer?
var count = 180
override func viewDidLoad() {
super.viewDidLoad()
lbprice.text = product?.price
lbshopname.text = product?.shopname
lbproductname.text = product?.productname
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timeChanged), userInfo: nil, repeats: true)
}
@objc func timeChanged() {
count -= 1
/* 如果下載進度還沒到最大值就顯示下載進度;下載完成就顯示"Download Finished" */
if count > 0 {
/* 用%跳脫後面%,所以%%等於%文字。下載進度為0%~100%所以progressView的值乘以100 */
time.text = "\(count)s"
} else {
time.text = "time's up"
timer?.invalidate()
timer = nil
}
}
@IBAction func clickback(_ sender: UIButton) {
dismiss(animated: false, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// ViewController.swift
// Facilities
//
// Created by hager on 2/1/19.
// Copyright © 2019 Vodafone. All rights reserved.
//
import UIKit
import SDWebImage
class ServicesViewController: UIViewController , UITableViewDelegate , UITableViewDataSource {
@IBOutlet weak var errorView: UIView!
var selectedCell : Int?
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var serviceTableView: UITableView!
@IBOutlet weak var errorLabel: UILabel!
var services : [Data]?
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
// MARK:- Prepare For Segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToDetails"
{
if let serviceDetailsViewcontroller = segue.destination as? ServiceDetailsViewController{
serviceDetailsViewcontroller.service = self.services?[selectedCell ?? 0]
}
}
}
func setupUI(){
self.navigationItem.title = NSLocalizedString("pageTitle", comment: "")
let backItem = UIBarButtonItem()
backItem.title = ""
navigationItem.backBarButtonItem = backItem
serviceTableView.register(UINib(nibName: "ServiceTableViewCell", bundle: nil), forCellReuseIdentifier: "myDataCell")
self.serviceTableView.dataSource = self
self.serviceTableView.delegate = self
}
func loadData() {
self.errorView.isHidden = true
self.serviceTableView.isHidden = true
self.activityIndicator.startAnimating()
NetworkService.shared.getServices(pageSize: 10, pageIndex: 1, departmentNumber: 2) { data , error in
self.activityIndicator.stopAnimating()
if data != nil && error == nil {
self.services = (data?.data)!
self.errorView.isHidden = true
self.serviceTableView.isHidden = false
self.serviceTableView.reloadData {
self.animateTable()
}
}else{
self.errorLabel.text = NSLocalizedString("error", comment: "")
self.errorView.isHidden = false
self.serviceTableView.isHidden = true
}
}
}
func animateTable() {
serviceTableView.reloadData()
let cells = serviceTableView.visibleCells
let tableHeight: CGFloat = serviceTableView.bounds.size.height
for i in cells {
let cell: UITableViewCell = i as UITableViewCell
cell.transform = CGAffineTransform(translationX: 0, y: tableHeight)
}
var index = 0
for a in cells {
let cell: UITableViewCell = a as UITableViewCell
UIView.animate(withDuration: 1.5, delay: 0.05 * Double(index), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: [], animations: {
cell.transform = CGAffineTransform(translationX: 0, y: 0);
}, completion: nil)
index += 1
}
}
// MARK :- actions
@IBAction func retryButtonDidTapped(_ sender: Any) {
loadData()
}
// MARK:- Table Data Source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return services?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myDataCell", for: indexPath) as! ServiceTableViewCell
if let services = self.services {
if let imageSource = services[indexPath.row].imageSrc {
cell.myImage.sd_setImage(with: URL(string: imageSource))
}
cell.titleLabel.text = services[indexPath.row].titleEN
cell.subtitleLabel.text = services[indexPath.row].briefTrimmedEN
}
return cell
}
// MARK:- Table Delegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedCell = indexPath.row
performSegue(withIdentifier: "goToDetails", sender: self)
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.alpha = 0
UIView.animate(withDuration: 1.0) {
cell.alpha = 1.0
}
}
}
|
//
// UITableView.swift
// DesafioHurb
//
// Created by Guilherme Siepmann on 27/08/19.
// Copyright © 2019 Guilherme Siepmann. All rights reserved.
//
import UIKit
extension UITableView {
func registerTableViewCell<T: ReusableCellIdentifiable>(_ cell: T.Type) {
register(
UINib(
nibName: String(describing: cell),
bundle: nil
),
forCellReuseIdentifier: T.reusableIdentifier
)
}
}
|
//
// BalanceRechargeBankslip.swift
// TrocoSimples
//
// Created by gustavo r meyer on 7/13/17.
// Copyright © 2017 gustavo r meyer. All rights reserved.
//
import Foundation
class BalanceRechargeBankslip {
// MARK: - Constants
internal struct Keys {
static let amount = "amount"
static let promotionalCode = "promotionalCode"
}
// MARK: - Intance Properties
let amount:NSNumber
let promotionalCode:String
// MARK: - Object Lifecycle
init(amount:NSNumber, promotionalCode:String ) {
self.amount = amount
self.promotionalCode = promotionalCode
}
func validate() -> Bool {
return amount.doubleValue > 0
}
public func toDictionary() -> [String : Any] {
return [
Keys.amount: amount,
Keys.promotionalCode: promotionalCode,
]
}
}
|
struct RestaurantMenuItem {
let name: String
let price: Float
}
|
//
// ViewModelProvider.swift
// SpaceX
//
// Created by Marcin Maciukiewicz on 08/05/2021.
//
import Foundation
import Combine
enum ContentState<T> {
case fetching
case loaded(T)
case empty
case error(DataSourceError)
}
protocol ViewModelProvider {
func fetchCompanyInfo(forceReload: Bool) -> AnyPublisher<ContentState<String>, Never>
func fetchAllLaunches(criteria: FilterCriteria, order: ComparisonResult, forceReload: Bool) -> AnyPublisher<ContentState<[LaunchModel]>, Never>
}
|
//
// ShapeIllustration.swift
// Metronome CocoaTests
//
// Created by luca strazzullo on 13/5/20.
// Copyright © 2020 luca strazzullo. All rights reserved.
//
import SwiftUI
enum ShapeIllustration: String {
case button1 = "button-shape-1"
case button2 = "button-shape-2"
case button3 = "button-shape-3"
case button4 = "button-shape-4"
case button5 = "button-shape-5"
case button6 = "button-shape-6"
var name: String {
return self.rawValue
}
}
extension Image {
init(_ shape: ShapeIllustration) {
self = Image(shape.name)
}
}
|
//
// TranslateRouterProtocol.swift
// Tanslator
//
// Created by Дмитрий Мельников on 11/02/2019.
// Copyright © 2019 Дмитрий Мельников. All rights reserved.
//
import Foundation
protocol TranslateRouterProtocol: class {
/// Show history screen
func showHistory()
}
|
//
// Constants.swift
// basiviti
//
// Created by BeeSightSoft on 10/17/18.
// Copyright © 2018 hnc. All rights reserved.
//
import UIKit
import Colorkit
class Constants {
static let appName = "basiviti"
struct Colors {
static let main = UIColor(hexString: "F16D6A")
static let unverifiedQuestionColor = UIColor(hexString: "ebd534")
static let verifiedQuestionColor = UIColor(hexString: "55c94d")
static let answeredQuestionColor = UIColor(hexString: "1d68e0")
}
}
enum BSDeviceType: Int {
case pc
case mobile
}
enum BSOperationSystemType: Int {
case windows
case macos
case ios
case android
case linux
case other
}
|
//
// Matt_Dolan_s_CardApp.swift
// Matt Dolan's Card
//
// Created by Matt Dolan External macOS on 2021-03-12.
//
import SwiftUI
@main
struct Matt_Dolan_s_CardApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
|
//
// ViewController.swift
// GTMRouterExample
//
// Created by luoyang on 2016/12/19.
// Copyright © 2016年 luoyang. All rights reserved.
//
import UIKit
import GTMRouter
class ViewController: UIViewController {
let label: UILabel = {
let lab = UILabel()
lab.text = "A"
lab.textAlignment = .center
lab.textColor = UIColor.red
lab.font = UIFont.systemFont(ofSize: 38)
return lab
}()
let nextBButton: UIButton = {
let btn = UIButton(type: .custom)
btn.setTitle("ViewControllerB", for: .normal)
btn.setTitleColor(UIColor.blue, for: .normal)
btn.addTarget(self, action: #selector(onNextBTouch), for: .touchUpInside)
return btn
}()
let nextCButton: UIButton = {
let btn = UIButton(type: .custom)
btn.setTitle("ViewControllerC", for: .normal)
btn.setTitleColor(UIColor.blue, for: .normal)
btn.addTarget(self, action: #selector(onNextCTouch), for: .touchUpInside)
return btn
}()
let nextDButton: UIButton = {
let btn = UIButton(type: .custom)
btn.setTitle("ViewControllerD", for: .normal)
btn.setTitleColor(UIColor.blue, for: .normal)
btn.addTarget(self, action: #selector(onNextDTouch), for: .touchUpInside)
return btn
}()
let nextWebButton: UIButton = {
let btn = UIButton(type: .custom)
btn.setTitle("WebViewController", for: .normal)
btn.setTitleColor(UIColor.blue, for: .normal)
btn.addTarget(self, action: #selector(onNextWebTouch), for: .touchUpInside)
return btn
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = "GTMRouter Demo"
self.view.addSubview(self.label)
self.label.frame = self.view.bounds
let h = self.view.bounds.size.height, w = self.view.bounds.size.width
self.view.addSubview(self.nextBButton)
self.view.addSubview(self.nextCButton)
self.view.addSubview(self.nextDButton)
self.view.addSubview(self.nextWebButton)
self.nextDButton.frame = CGRect(x: 0, y: h-100, width: w, height: 50)
self.nextCButton.frame = CGRect(x: 0, y: h-150, width: w, height: 50)
self.nextBButton.frame = CGRect(x: 0, y: h-200, width: w, height: 50)
self.nextWebButton.frame = CGRect(x: 0, y: h-250, width: w, height: 50)
// 支持网页
GTMRouter.setWebVCFactory(factory: WebViewControllerFactory())
}
// MARK: - Events
@objc func onNextBTouch() {
GTMRouter.push(url: "router://GTMRouterExample/ViewControllerB")
}
@objc func onNextCTouch() {
let params:[String:Any] = ["image": UIImage(named: "logo.png") as Any]
GTMRouter.push(url: "router://GTMRouterExample/ViewControllerC?ip=1&fp=1.2345&dp=12222.2345&bp=true&name=GTMYang,你好", parameter: params)
}
@objc func onNextDTouch() {
GTMRouter.push(url: "router://GTMRouterExample/ViewControllerD")
}
@objc func onNextWebTouch() {
GTMRouter.push(url: "https://www.baidu.com", parameter: ["title": "测试网页传参数"])
}
}
|
//
// Unit.swift
// ELRDRG
//
// Created by Martin Mangold on 24.08.18.
// Copyright © 2018 Martin Mangold. All rights reserved.
//
import UIKit
import CoreData
public class Unit: NSManagedObject , dbInterface{
}
extension Unit{
public func getImage() -> UIImage?
{
return BaseUnit.getImage(type: self.type)
}
public var unitType : UnitType{
get{
return UnitType(rawValue: self.type) ?? .Sonstiges
}
set{
self.type = newValue.rawValue
}
}
public func getID() -> Int32? {
return self.dbID
}
public func setID(id: Int32) {
self.dbID = id
}
convenience init() {
self.init()
if self.dbID == -1
{
self.dbID = NSManagedObject.getNextID(objects: NSManagedObject.getAll(entity: Unit.self))
}
UnitHandler().saveData()
}
public func setNextID()
{
if self.dbID == -1
{
self.dbID = NSManagedObject.getNextID(objects: NSManagedObject.getAll(entity: Unit.self))
}
UnitHandler().saveData()
}
public func getVictimCount() -> Int{
if let victimList = self.patient?.allObjects as? [Victim]
{
return victimList.count
}
return 0
}
public func hasDestination() -> Bool
{
if let victimList = self.patient?.allObjects as? [Victim]
{
for vic in victimList
{
if let _ = vic.hospital
{
return true
}
}
}
return false
}
public func getDestination() -> Hospital?
{
if let victimList = self.patient?.allObjects as? [Victim]
{
for vic in victimList
{
if let hospital = vic.hospital
{
return hospital
}
}
}
return nil
}
public func getVictims()->[Victim]?
{
if let victims = self.patient?.allObjects as? [Victim]
{
return victims
}
return nil
}
//Gibt die schwerwiegenste Kategorie zurück
public func getGlobalCategory()->Int16?
{
var category : Int16 = 10
if let victimList = self.patient?.allObjects as? [Victim]
{
for vic in victimList
{
if vic.category < category
{
category = vic.category
}
}
}
return nil
}
}
|
//
// RegistrationViewController.swift
// practise03
//
// Created by Admin on 02.08.16.
// Copyright © 2016 Admin. All rights reserved.
//
import UIKit
class RegistrationViewController: UIViewController {
@IBOutlet weak var name: UITextField!
@IBOutlet weak var location: UITextField!
@IBOutlet weak var login: UITextField!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var email: UITextField!
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.
}
@IBAction func submitInfo(sender: AnyObject) {
print("Name: \(name.text!)")
print("Location: \(location.text!)")
print("Login: \(login.text!)")
print("Password: \(password.text!)")
print("Email: \(email.text!)")
}
}
|
import UIKit
class RequestHelper {
let LOGIN_URL = "http://localhost:3000/api/users/authenticate.json?email=%@&password=%@"
let CATS_URL = "http://localhost:3000/api/cats.json?email=%@&token=%@"
let CAT_LIKE_URL = "http://localhost:3000/api/cat_likes?email=%@&token=%@&cat_id=%d&like=%d"
func request<T>(url:String, callback: (T) -> (), errCallback: (NSError) -> () = {(error) in}) {
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
performRequest(request, callback: callback)
}
func postRequest<T>(url:String, callback: (T) -> ()) {
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
performRequest(request, callback: callback)
}
private func performRequest<T>(request: NSURLRequest, callback: (T) -> ()) {
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
if error == nil {
var jsonError:NSError?
var response = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as! T
callback(response)
}
}
}
func doLogin(email: String, password: String, callback: (NSDictionary) -> ()) {
let url = NSString(format: String(format: LOGIN_URL, email, password))
NSLog("hey %@", url)
request(url as String, callback: callback)
}
func getCats(callback: (NSArray) -> ()) {
let (email, token) = getEmailAndToken()
request(String(format: CATS_URL, email!, token!), callback: callback)
}
func doLike(cat: Int, like: Bool, callback: (NSDictionary) -> ()) {
let (email, token) = getEmailAndToken()
NSLog("going to like with %@", String(format: CAT_LIKE_URL, email!, token!, cat, like ? 1 : 0))
request(String(format: CAT_LIKE_URL, email!, token!, cat, like ? 1 : 0), callback: callback)
}
private func getEmailAndToken() -> (NSString?, NSString?) {
let userDefaults = NSUserDefaults.standardUserDefaults()
return (userDefaults.stringForKey("email"), userDefaults.stringForKey("token"))
}
} |
//
// String+.swift
//
// Created by Ken Yu
//
import Foundation
public extension String {
/**
This function allows you to get i th char in the string by string[i]
*/
subscript (i: Int) -> Character {
return self[self.startIndex.advancedBy(i)]
}
/**
This function allow you to get i th char in the string as a String by string[i]
*/
subscript (i: Int) -> String {
return String(self[i] as Character)
}
/**
This function allow you to get subString by string[i...j]
*/
subscript (r: Range<Int>) -> String {
return substringWithRange(Range(start: startIndex.advancedBy(r.startIndex), end: startIndex.advancedBy(r.endIndex)))
}
/**
This function allow you to get substring using NSRange
*/
func substringWithRange(range: NSRange) -> String {
var start = self.startIndex
start = start.advancedBy(range.location)
let end = start.advancedBy(range.length)
return self.substringWithRange(Range<String.Index>(start: start,end: end))
}
/*
:returns the floatValue of a string using NSString's method.
*/
public var floatValue: Float {
return (self as NSString).floatValue
}
/*
Returns a copy of the string, with leading and trailing whitespace omitted.
*/
public func trim() -> String {
return stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
/**
Returns true if the text has any printable characters else returns false
*/
public func hasPrintableCharacters() -> Bool {
let trimmedText = stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return !trimmedText.isEmpty
}
// return the length of string
public var length: Int {
return self.utf16.count
}
public func contains(find: String) -> Bool {
return self.rangeOfString(find) != nil
}
// Validation for string entered into email field
public func isEmail() -> Bool {
let regex = try? NSRegularExpression(pattern: "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$", options: .CaseInsensitive)
return regex?.firstMatchInString(self, options: [], range: NSMakeRange(0, self.characters.count)) != nil
}
public func filter(pred: Character -> Bool) -> String {
return String(self.characters.filter(pred))
}
public func URLencode() -> String {
let characters = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet
characters.removeCharactersInString("&")
guard let encodedString = self.stringByAddingPercentEncodingWithAllowedCharacters(characters) else {
return self
}
return encodedString
}
} |
//
// TitleViewController.swift
// FetchRewardsCookbook
//
// Created by Wesley Luntsford on 11/11/21.
//
import UIKit
class TitleViewController: UIViewController {
var recipeFetcher: RecipeFetcher?
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
self.activityIndicator.transform = CGAffineTransform(scaleX: 3, y: 3)
activityIndicator.startAnimating()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func viewDidAppear(_ animated: Bool) {
recipeFetcher = RecipeFetcher()
self.performSegue(withIdentifier: K.SegueID.showRecipes, sender: self)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == K.SegueID.showRecipes {
let recipesVC = segue.destination as! RecipeBrowserViewController
recipesVC.recipeFetcher = self.recipeFetcher
}
}
}
|
//
// MessageCollectionViewCell.swift
// DeclarativeTableView
//
// Created by Robin Charlton on 20/07/2021.
//
import UIKit
class MessageCollectionViewCell: UICollectionViewCell, ViewHeightProviding, Reusable, TypeDepending {
static var viewHeight: CGFloat = 50 // TODO: review how heights are generated
private let textLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
initialize()
}
private func initialize() {
contentView.backgroundColor = .systemPurple
textLabel.frame = contentView.bounds
contentView.addSubview(textLabel)
}
func setDependency(_ dependency: String) {
textLabel.text = dependency
}
}
|
//
// UserListViewController.swift
// UserDisplayer
//
// Created by Jeremi Kaczmarczyk on 02/02/2017.
// Copyright © 2017 Jeremi Kaczmarczyk. All rights reserved.
//
import UIKit
class UserListViewController: UITableViewController, UserListView {
private let connector: UserListConnector
private let presenter: UserListPresenter
// MARK: - Initialization
init(presenter: UserListPresenter, connector: UserListConnector) {
self.presenter = presenter
self.connector = connector
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - UITableViewController
override func viewDidLoad() {
super.viewDidLoad()
showNetworkActivityIndicator()
setupTableView()
title = presenter.title
presenter.viewReady()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return presenter.numberOfRows
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: UserTableViewCell.identifier, for: indexPath) as! UserTableViewCell
presenter.setup(cell: cell, at: indexPath.row)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
presenter.selectCell(at: indexPath.row)
}
// MARK: - Private
func setupTableView() {
tableView.registerCellsWithClass(UserTableViewCell.self)
tableView.rowHeight = 80.0
tableView.tableFooterView = UIView()
tableView.backgroundView = LoadingView()
}
// MARK: - UserListView
func refresh() {
tableView.reloadData()
tableView.backgroundView = nil
hideNetworkActivityIndicator()
}
func showUserDetails(for user: UserDisplayData) {
connector.navigateToUserDetails(for: user, fromView: self)
}
}
|
//
// ViewController.swift
// Test
//
// Created by Andy Adams on 6/27/18.
// Copyright © 2018 Andy Adams. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
//MARK: Properties
@IBOutlet weak var mealLabel: UILabel!
//MARK: Actions
@IBAction func defaultTextButton(_ sender: UIButton) {
mealLabel.text = "Shit"
}
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.
}
}
|
//
// TerminalView.swift
// Me
//
// Created by James Pickering on 4/30/16.
// Copyright © 2016 James Pickering. All rights reserved.
//
import UIKit
let FlickerAnimationKey = "FlickerAnimationKey"
let ShakeAnimationKey = "ShakeAnimationKey"
class TerminalView: UIView {
@IBOutlet weak var glyphLabel: UILabel!
@IBOutlet weak var consoleLabel: UILabel!
weak var linesView: UIImageView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let linesView = UIImageView()
linesView.image = UIImage(named: "Terminal Background")
linesView.contentMode = .ScaleAspectFill
self.insertSubview(linesView, atIndex: 0)
self.linesView = linesView
}
func viewWillAppear() {
linesView.frame = bounds
linesView.layer.addAnimation(flickerAnimation(YDirection), forKey: FlickerAnimationKey)
glyphLabel.layer.addAnimation(flickerAnimation(XDirection), forKey: FlickerAnimationKey)
consoleLabel.layer.addAnimation(flickerAnimation(XDirection), forKey: FlickerAnimationKey)
}
func flickerAnimation(direction: String) -> CAAnimation {
let animation = CAKeyframeAnimation(keyPath: "transform.translation.\(direction)")
let from = NSNumber(double: -1.0)
let to = NSNumber(double: 1.0)
animation.values = [from, to]
animation.autoreverses = true
animation.duration = 0.003
animation.repeatCount = Float.infinity
return animation
}
func shakeAnimation(angle: CGFloat) -> CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath: "transform")
let left = NSValue(CATransform3D: CATransform3DMakeRotation(angle, 0.0, 0.0, 1.0))
let right = NSValue(CATransform3D: CATransform3DMakeRotation(-angle, 0.0, 0.0, 1.0))
animation.values = [left, right]
animation.autoreverses = true
animation.duration = 0.03
animation.delegate = self
return animation
}
// func applyShakeAnimation(force: CGFloat) {
// consoleLabel.layer.addAnimation(shakeAnimation(force / 100.0), forKey: ShakeAnimationKey)
// glyphLabel.layer.addAnimation(shakeAnimation(force / 100.0), forKey: ShakeAnimationKey)
// linesView.layer.addAnimation(shakeAnimation(force / 100.0), forKey: ShakeAnimationKey)
// }
func updateShakeAnimation(force: CGFloat) -> Bool {
if consoleLabel.layer.animationForKey(ShakeAnimationKey) != nil {
consoleLabel.layer.removeAnimationForKey(ShakeAnimationKey)
// glyphLabel.layer.removeAnimationForKey(ShakeAnimationKey)
// linesView.layer.removeAnimationForKey(ShakeAnimationKey)
}
if force > 0 {
consoleLabel.layer.addAnimation(shakeAnimation(force / 100.0), forKey: ShakeAnimationKey)
// glyphLabel.layer.addAnimation(shakeAnimation(force / 100.0), forKey: ShakeAnimationKey)
// linesView.layer.addAnimation(shakeAnimation(force / 100.0), forKey: ShakeAnimationKey)
return true
} else {
return false
}
}
}
|
//
// Model.swift
// SwiftGroupDemo
//
// Created by 高鑫 on 2017/12/4.
// Copyright © 2017年 高鑫. All rights reserved.
//
import Foundation
import UIKit
struct Item {
var title : String!
var item : [String]!
var isShow : Bool!
}
class ItemData {
static let itemData = [
Item(title: "😂", item: ["00001","00002","00003"], isShow: false),
Item(title: "😎", item: ["00001","00002","00003"], isShow: false),
Item(title: "😜", item: ["00001","00002","00003"], isShow: false),
Item(title: "🙄", item: ["00001","00002","00003"], isShow: false),
Item(title: "🤔", item: ["00001","00002","00003"], isShow: false)
]
}
|
//
// File.swift
// CoreDataStack
//
// Created by Ryan Yan on 1/19/18.
// Copyright © 2018 Jiaqi Yan. All rights reserved.
//
import Foundation
enum Gender: String {
case Male
case Female
}
|
//
// HSCYLoginViewController.swift
// hscy
//
// Created by 周子聪 on 2017/8/22.
// Copyright © 2017年 melodydubai. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
import SVProgressHUD
class HSCYLoginViewController: UIViewController,UITextFieldDelegate{
@IBOutlet weak var countNameTF: UITextField!
@IBOutlet weak var passwordTF: UITextField!
@IBOutlet weak var loginView: UIButton!
@IBAction func login(_ sender: UIButton) {
let phoneNum=countNameTF.text!
let pwd=passwordTF.text!
let param=["phoneNum":phoneNum,
"pwd":pwd]
if phoneNum==""{
SVProgressHUD.showInfo(withStatus: "手机号不能为空")
}else if pwd==""{
SVProgressHUD.showInfo(withStatus: "请输入密码")
}
else if !validatePhonoNum(phono: phoneNum){
SVProgressHUD.showInfo(withStatus: "请输入正确的手机号")
}else{
Alamofire.request("http://218.94.74.231:9999/SeaProject/login", method: .post, parameters: param).responseJSON{
(returnResult) in
if let response=returnResult.result.value{
if let responseJSON=JSON(response).dictionaryObject as Dictionary<String, AnyObject>?{
if responseJSON["status"] == nil{
let shipID=responseJSON["ship_id"] as! String
let showName=responseJSON["show_name"] as! String
if shipID=="false"{
SVProgressHUD.showInfo(withStatus: responseJSON["show_name"] as? String)
}else{
SVProgressHUD.showInfo(withStatus: "登陆成功")
let cbsbh=responseJSON["cbsbh"] as! String
let cnName=responseJSON["cn_name"] as! String
let time=responseJSON["time"] as! String
UserDefaults.standard.set(phoneNum, forKey: "phoneNum")
UserDefaults.standard.set(pwd, forKey: "pwd")
UserDefaults.standard.set(shipID, forKey: "shipID")
UserDefaults.standard.set(showName, forKey: "showName")
UserDefaults.standard.set(cbsbh, forKey: "cbsbh")
UserDefaults.standard.set(cnName, forKey: "cnName")
UserDefaults.standard.set(time, forKey: "time")
UserDefaults.standard.synchronize()
let sb = UIStoryboard(name: "Main", bundle: nil)
let vc = sb.instantiateViewController(withIdentifier: "HSCYTabBarController") as! HSCYTabBarController
UIApplication.shared.delegate?.window??.rootViewController=vc
}
}else{
SVProgressHUD.showInfo(withStatus: "服务器正在维护")
}
}
}
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
countNameTF.resignFirstResponder()
passwordTF.resignFirstResponder()
}
override func viewDidLoad(){
super.viewDidLoad()
loginView.layer.cornerRadius=CGFloat(3.14)
let phoneNum=UserDefaults.standard.string(forKey: "phoneNum")
if phoneNum != nil {
countNameTF.text=phoneNum
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return true
}
}
|
//
// User.swift
// DigitsFYF
//
// Created by Valentin Polouchkine on 8/24/15.
// Copyright (c) 2015 Fabric. All rights reserved.
//
import Foundation
class User : AWSDynamoDBObjectModel, AWSDynamoDBModeling {
var cognitoId : String?
var digitsId : String?
var phoneNumber : String?
static func dynamoDBTableName() -> String {
return "users"
}
static func hashKeyAttribute() -> String {
return "cognitoId"
}
override func isEqual(anObject: AnyObject?) -> Bool {
return super.isEqual(anObject)
}
} |
//
// NewsDTO.swift
// WebScraper
//
// Created by RSQ Technologies on 11/04/2019.
// Copyright © 2019 RSQ Technologies. All rights reserved.
//
import UIKit
import ObjectMapper
class News: NSObject, Mappable {
var author: String?
var date: String?
var text: String?
var link: String?
var photo: String?
var tags: [String]?
required init?(map: Map) {
super.init()
self.mapping(map: map)
}
func mapping(map: Map) {
author <- map["author"]
date <- map["date"]
text <- map["text"]
link <- map["link"]
photo <- map["photo"]
tags <- map["tags"]
}
}
|
//
// authorPublish.swift
// Grocr
//
// Created by vic_liu on 2019/3/24.
// Copyright © 2019 Razeware LLC. All rights reserved.
//
import Foundation
import Firebase
class authorPublish: NSObject {
var uid: String
var author: String
var text: String
init(uid: String, author: String, text: String) {
self.uid = uid
self.author = author
self.text = text
}
convenience override init() {
self.init(uid: "", author: "", text: "")
}
}
|
//
// QuestionTableViewCell.swift
// Honest Badger
//
// Created by Steve Cox on 7/18/16.
// Copyright © 2016 stevecoxio. All rights reserved.
//
import UIKit
protocol QuestionResponseDelegate: class {
func viewResponseButtonTapped(_ sender: QuestionTableViewCell)
func submitResponseToQuestionButtonTapped(_ sender: QuestionTableViewCell)
}
class QuestionTableViewCell: UITableViewCell, UITableViewDelegate {
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var submitResponseButton: UIButton!
@IBOutlet weak var viewResponsesButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
questionLabel.font = UIFont.init(name: "Rockwell", size:21.0)
submitResponseButton.titleLabel?.font = UIFont.init(name: "Rockwell", size: 18.0)
viewResponsesButton.titleLabel?.font = UIFont.init(name: "Rockwell", size: 18.0)
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerFired(_:)), userInfo: nil, repeats: true)
}
var question: Question?
var timer: Timer?
var formatter = DateComponentsFormatter()
weak var delegate: QuestionResponseDelegate?
func timerFired(_ timer: Timer?){
guard let question = self.question else
{ return }
let dateComparisonResult: ComparisonResult = Date().compare(question.timeLimit as Date)
if dateComparisonResult == ComparisonResult.orderedAscending {
if question.responseKeys.contains(UserController.shared.currentUserID) {
submitResponseButton.setTitle("Edit Response", for: UIControlState())
submitResponseButton.backgroundColor = UIColor(red: 169/255, green: 169/255, blue: 169/255, alpha: 1)
submitResponseButton.isEnabled = true
formatter.unitsStyle = .positional
let interval = question.timeLimit.timeIntervalSince1970 - Date().timeIntervalSince1970
viewResponsesButton.setTitle(" \(formatter.string(from: interval)!) left\n to respond", for: UIControlState())
viewResponsesButton.isEnabled = false
viewResponsesButton.backgroundColor = UIColor.white
} else {
submitResponseButton.setTitle("Submit Response", for: UIControlState())
submitResponseButton.backgroundColor = UIColor(red: 133/255, green: 178/255, blue: 131/255, alpha: 1)
submitResponseButton.isEnabled = true
formatter.unitsStyle = .positional
let interval = question.timeLimit.timeIntervalSince1970 - Date().timeIntervalSince1970
viewResponsesButton.setTitle(" \(formatter.string(from: interval)!) left\n to respond", for: UIControlState())
viewResponsesButton.isEnabled = false
viewResponsesButton.backgroundColor = UIColor.white
}
} else {
if question.responses.count == 1 {
submitResponseButton.setTitle(" \(question.responses.count) response\n received", for: UIControlState())
}
if question.responses.count != 1 {
submitResponseButton.setTitle(" \(question.responses.count) responses\n received", for: UIControlState())
}
submitResponseButton.backgroundColor = UIColor.white
submitResponseButton.isEnabled = false
viewResponsesButton.isEnabled = true
viewResponsesButton.setTitle("View Responses", for: UIControlState())
viewResponsesButton.backgroundColor = UIColor(red: 249/255, green: 81/255, blue: 197/255, alpha: 1)
}
}
@IBAction func viewResponseButtonTapped(_ sender: UIButton) {
self.delegate?.viewResponseButtonTapped(self)
}
@IBAction func submitResponseToQuestionButtonTapped(_ sender: UIButton) {
self.delegate?.submitResponseToQuestionButtonTapped(self)
}
func loadQuestionInfo(_ question: Question) {
self.question = question
self.timerFired(nil)
questionLabel.text = "\(question.questionText)"
}
}
|
//
// UpdateModel.swift
//
// Copyright © 2020 Steamclock Software.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import Netable
import SwiftyUserDefaults
struct Batsignal: Decodable {
let title: String
let message: String
let url: String
}
struct CheckForBatsignal: Request {
typealias Parameters = Empty
typealias RawResource = Batsignal
public var method: HTTPMethod { .get }
public var path: String {
"notify.json"
}
}
struct VersionInfo: Decodable {
let version: String
let url: String
let notes: String
}
struct CheckForNewVersion: Request {
typealias Parameters = Empty
typealias RawResource = VersionInfo
public var method: HTTPMethod { .get }
public var path: String { "version.json" }
}
enum AppSource: String {
case debug
case testFlight
case appStore
}
class UpdateModel {
static let shared = UpdateModel()
private let updateAPI: Netable
private let currentVersion: String
private var batsignal: Batsignal?
private var batsignalRetrievedAt: Date?
private init() {
updateAPI = Netable(baseURL: URL(string: "https://quests-beta.netlify.com/")!)
updateAPI.headers["Accept"] = "application/json"
currentVersion = Bundle.versionString
}
func checkForBatsignal(onSuccess: @escaping (Batsignal?) -> Void, onFailure: @escaping (NetableError) -> Void) {
if let batsignal = batsignal, let batsignalDate = batsignalRetrievedAt,
batsignalDate.timeIntervalSinceNow > -3600 { // Only update every hour
onSuccess(batsignal)
return
}
updateAPI.request(CheckForBatsignal()) { result in
switch result {
case .success(let batsignal):
self.batsignal = batsignal
self.batsignalRetrievedAt = Date()
onSuccess(batsignal)
case .failure(let error):
onFailure(error)
}
}
}
func checkForUpdates(onSuccess: @escaping (VersionInfo?) -> Void, onFailure: @escaping (NetableError) -> Void) {
Defaults[.updateLastChecked] = Date()
updateAPI.request(CheckForNewVersion()) { result in
switch result {
case .success(let versionInfo):
guard versionInfo.version.compare(self.currentVersion, options: .numeric) == .orderedDescending else {
LogManager.shared.log("Current version is the same as or newer than available")
onSuccess(nil)
return
}
LogManager.shared.log("Found a new version to download")
onSuccess(versionInfo)
case .failure(let error):
onFailure(error)
}
}
}
func appSource() -> AppSource {
// if isSimulator() {
// return .debug
// }
#if INTERNAL
return .testFlight
#endif
// When in doubt just show app store version
return .appStore
}
private func isSimulator() -> Bool {
#if arch(i386) || arch(x86_64)
return true
#else
return false
#endif
}
}
|
//
// CityTableview.swift
// inke
//
// Created by bb on 2017/8/13.
// Copyright © 2017年 bb. All rights reserved.
//
import UIKit
private var kInset: CGFloat = 40
private var kAreaCityTableviewCellID: String = "kAreaCityTableviewCellID"
class AreaCityTableview: UIView {
var areaModelArray: [AreaModel] = [AreaModel](){
didSet {
updateUI()
}
}
fileprivate lazy var tableview: UITableView = { [unowned self] in
let tableview = UITableView()
tableview.delegate = self
tableview.dataSource = self
tableview.separatorInset = UIEdgeInsets(top: 0, left: kInset, bottom: 0, right: kInset)
tableview.separatorColor = UIColor.init(r: 228, g: 228, b: 228)
tableview.register(AreaCityTableViewCell.self, forCellReuseIdentifier: kAreaCityTableviewCellID)
return tableview
}()
var gradientLayer: CAGradientLayer = {
//渐变颜色
let gradientLayer = CAGradientLayer()
//设置渐变的主颜色(可多个颜色添加)
let white = UIColor.white.cgColor
let clear = UIColor.clear.cgColor
gradientLayer.colors = [clear, white, white, white, white, white, white, white, clear]
return gradientLayer
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// 获取自动布局后控件的frame
override func layoutSubviews() {
super.layoutSubviews()
// 设置遮罩的frame位当前view的frame
gradientLayer.frame = self.bounds
}
}
extension AreaCityTableview {
fileprivate func setupUI() {
self.addSubview(tableview)
// 设置遮罩
self.layer.mask = gradientLayer
tableview.snp.makeConstraints { (make) in
make.left.equalTo(self)
make.top.equalTo(self)
make.right.equalTo(self)
make.bottom.equalTo(self)
}
}
fileprivate func updateUI() {
tableview.reloadData()
}
}
extension AreaCityTableview: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableview.deselectRow(at: indexPath, animated: true)
for (i,value) in areaModelArray.enumerated() {
if i != indexPath.item {
value.isSelected = false
} else {
value.isSelected = true
}
}
tableView.reloadData()
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
}
}
extension AreaCityTableview: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return areaModelArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCell(withIdentifier: kAreaCityTableviewCellID, for: indexPath) as! AreaCityTableViewCell
cell.area = areaModelArray[indexPath.item]
return cell
}
}
|
//
// UIViewControllerExtension.swift
// PasswordStorage
//
// Created by João Paulo dos Anjos on 02/02/18.
// Copyright © 2018 Joao Paulo Cavalcante dos Anjos. All rights reserved.
//
import UIKit
extension UIViewController {
func showAlert(title: String, message: String, buttonTitle: String, dissmisBlock: @escaping () -> Void) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let button = UIAlertAction(title: buttonTitle, style: .default) { (alertAction) in
dissmisBlock()
}
alertController.addAction(button)
self.present(alertController, animated: true, completion: nil)
}
func showAlertWithOptions(title: String, message: String, rightButtonTitle: String, leftButtonTitle: String, rightDissmisBlock: @escaping () -> Void, leftDissmisBlock: @escaping () -> Void) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let leftButton = UIAlertAction(title: leftButtonTitle, style: .default) { (alertAction) in
leftDissmisBlock()
}
let rightButton = UIAlertAction(title: rightButtonTitle, style: .default) { (alertAction) in
rightDissmisBlock()
}
alertController.addAction(leftButton)
alertController.addAction(rightButton)
self.present(alertController, animated: true, completion: nil)
}
func showToaster(message: String) {
let alertController = UIAlertController(title: "", message: message, preferredStyle: .alert)
self.present(alertController, animated: true, completion: nil)
let when = DispatchTime.now() + 2
DispatchQueue.main.asyncAfter(deadline: when) {
alertController.dismiss(animated: true, completion: nil)
}
}
}
|
//
// TableViewController.swift
// ARMGEO
//
// Created by Falcon on 1/12/17.
// Copyright © 2017 ex. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
var items = [(title: "Interactive Map", image:UIImage(named:"Interactive Map Icon")),
(title: "Cross-Board Thematic Tours", image:UIImage(named:"Cross-Board Thematic Tours Icon")),
(title: "Customize Your Own Tour", image:UIImage(named:"Customize Your Own Tour Icon")),
(title: "Database", image:UIImage(named:"Database Icon"))]
override func viewDidLoad() {
super.viewDidLoad()
let img = UIImage(named: "Menu Icon")!.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
let leftBarButtonItem = UIBarButtonItem(image: img, style: UIBarButtonItemStyle.done, target: self, action: nil)
self.navigationItem.leftBarButtonItem = leftBarButtonItem
self.title = "ARM-GEO"
navigationController?.navigationBar.barTintColor = UIColor.blue
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
let image = UIImage(named: "Bg")
self.tableView.backgroundView = UIImageView(image: image)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 4
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
cell.backgroundColor = UIColor(white: 0 , alpha: 0.3)
cell.imageView?.image = items[indexPath.row].image
cell.textLabel?.text = items[indexPath.row].title
cell.textLabel?.textColor = UIColor.white
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// Data+Extension.swift
// MJExtension
//
// Created by chenminjie on 2020/11/7.
//
import Foundation
import CommonCrypto
import CryptoSwift
extension TypeWrapperProtocol where WrappedType == Data {
public var md5String: String {
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
#if swift(>=5.0)
_ = wrappedValue.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
return CC_MD5(bytes.baseAddress, CC_LONG(wrappedValue.count), &digest)
}
#else
_ = data.withUnsafeBytes { bytes in
return CC_MD5(bytes, CC_LONG(wrappedValue.count), &digest)
}
#endif
return digest.reduce(into: "") { $0 += String(format: "%02x", $1) }
}
}
|
//
// PostRepository.swift
// RepoDB-Demo-MVC
//
// Created by Groot on 25.09.2020.
// Copyright © 2020 K. All rights reserved.
//
import RepoDB
protocol PostRepository: DatabaseRepository where Entity == DatabasePost { }
|
//
// DataModel.swift
// WeatherService
//
// Created by 天野修一 on 2020/11/29.
//
import Foundation
struct CityModel {
//APIで取ってくるエリア情報の型を設定する
//地域の名前とURLを追加するプロパティを持つ
let code: String
let name: String
init(cityCode:String, cityName:String) {
code = cityCode
name = cityName
}
}
struct CityList {
var list = [CityModel]()
//Webサイトを見て適当に地域を追加
init() {
list.append(CityModel(cityCode: "sapporo", cityName: "札幌"))
list.append(CityModel(cityCode: "muroran", cityName: "室蘭"))
list.append(CityModel(cityCode: "sendai", cityName: "仙台"))
list.append(CityModel(cityCode: "saitama", cityName: "さいたま"))
list.append(CityModel(cityCode: "tokyo", cityName: "東京"))
list.append(CityModel(cityCode: "yokohama", cityName: "横浜"))
list.append(CityModel(cityCode: "shizuoka", cityName: "静岡"))
list.append(CityModel(cityCode: "nagoya", cityName: "名古屋"))
list.append(CityModel(cityCode: "kyoto", cityName: "京都"))
list.append(CityModel(cityCode: "osaka", cityName: "大阪"))
list.append(CityModel(cityCode: "kobe", cityName: "神戸"))
list.append(CityModel(cityCode: "hiroshima", cityName: "広島"))
list.append(CityModel(cityCode: "fukuoka", cityName: "福岡"))
list.append(CityModel(cityCode: "naha", cityName: "那覇"))
}
}
|
//
// NetworkManagerDelegate.swift
// TODO
//
// Created by Marcin Jucha on 11.06.2017.
// Copyright © 2017 Marcin Jucha. All rights reserved.
//
import Foundation
protocol NetworkManagerDelegate {
func displayAlert(_ status: HttpStatusMessage)
func displayAlert(_ message: String)
}
extension NetworkManagerDelegate where Self: UIViewController {
func displayAlert(_ message: String) {
let alert = UIAlertController.createAlertWithText(title: "Network Error", message: message)
present(alert, animated: true, completion: nil)
}
func displayAlert(_ status: HttpStatusMessage) {
var alert: UIAlertController!
if status == .unauthorized {
alert = UIAlertController.createOneButtonAlertWithText(title: "Network Error", message: status.message()) {
self.performSegue(withIdentifier: UNWIND_TO_LOGIN_LIST, sender: nil)
}
} else {
alert = UIAlertController.createAlertWithText(title: "Network Error", message: status.message())
}
self.present(alert, animated: true, completion: nil)
}
}
extension UIViewController: NetworkManagerDelegate {}
|
//
// Quote.swift
// RiseAlarm
//
// Created by Tiffany Cai on 5/17/20.
// Copyright © 2020 Tiffany Cai. All rights reserved.
//
import Foundation
struct Quote: Codable {
let _id: String
let content: String
let author: String
let length: Int
let tags: [String]
}
/*
{
"_id":"2OVqy9KVYy3m",
"tags":["famous-quotes"],
"content":"No one saves us but ourselves. No one can and no one may. We ourselves must walk the path.",
"author":"Buddha",
"length":90
}
*/
|
import Foundation
protocol testYoozooDelegate: class {
func sucessMessage(message: String?)
func failMessage(message: String?)
func UserInfo(userInfo: UserInfo?)
func UserInfo(userInfo: [Items]?)
func UserDetails(userDetails: UserDetails?)
}
extension testYoozooDelegate {
func sucessMessage(message: String?){}
func failMessage(message: String?){}
func UserInfo(userInfo: UserInfo?){}
func UserInfo(userInfo: [Items]?){}
func UserDetails(userDetails: UserDetails?){}
}
|
//
// BasePresenter.swift
// VIPER
//
// Created by Felipe Remigio on 22/05/20.
// Copyright © 2020 Remigio All rights reserved.
//
protocol BasePresenterProtocol: AnyObject {
func viewDidLoad()
func viewWillAppear()
func setUp(interactor: BaseInteractorProtocol)
func setUp()
}
class BasePresenter<T, V, Z>: BasePresenterProtocol {
private weak var baseDelegate: BasePresenterDelegate?
private var baseRouter: BaseRouterProtocol?
private var baseInteractor: BaseInteractorProtocol?
var delegate: T? { return self.baseDelegate as? T }
var router: V? { return self.baseRouter as? V }
var interactor: Z? { return self.baseInteractor as? Z }
init(delegate: BasePresenterDelegate?, router: BaseRouterProtocol?) {
self.baseDelegate = delegate
self.baseRouter = router
}
func setUp(interactor: BaseInteractorProtocol) {
self.baseInteractor = interactor
}
func viewDidLoad() {
self.setUp()
}
func viewWillAppear() {}
func setUp() {}
}
protocol BasePresenterDelegate: AnyObject {
}
|
//
// ViewController.swift
// pomodoro-amigo
//
// Created by Alex L. Deweert on 2020-12-23.
//
import UIKit
class LoginViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view = LoginView()
}
}
extension LoginViewController: LoginViewControllerDelegate {
@objc
func handleSignInWithAppleButtonClicked() {
print("handleSignInWithAppleButtonClicked")
}
@objc
func handleForgottenPasswordButtonClicked() {
print("handleForgottenPasswordButtonClicked")
}
@objc
func handleSignInWithFacebookButtonClicked() {
print("handleSignInWithFacebookButtonClicked")
}
@objc
func handleSignInWithGoogleButtonClicked() {
print("handleSignInWithGoogleButtonClicked")
}
@objc
func handleLoginSigninButtonClicked() {
print("handleLoginSigninButtonClicked")
}
@objc
func handleSkipButtonClicked() {
print("handleSkipButtonClicked")
}
}
|
//
// PopupCoordinator.swift
// ExampleCoordinator
//
// Created by Karlo Pagtakhan on 3/29/18.
// Copyright © 2018 kidap. All rights reserved.
//
import UIKit
//kp:in the future can be an actual PopupCoordinator the can be reused
class PopupCoordinator {
//Coordinator Protocol Requirements
var didFinish: CoordinatorDidFinish?
var childCoordinators: ChildCoordinatorsDictionary = [:]
var rootController: UIViewController { return navigationController }
//NavigationControllerCoordinator Protocol Requirements
var navigationController: UINavigationController = UINavigationController(nibName: nil, bundle: nil)
var navigationControllerCoordinatorDelegate: NavigationControllerCoordinatorDelegate { return NavigationControllerCoordinatorDelegate(coordinator: self)
}
// Private variables
var onClose: ()->()
init(onClose: @escaping ()->()) {
self.onClose = onClose
self.navigationController.delegate = navigationControllerCoordinatorDelegate
self.navigationController.modalPresentationStyle = .formSheet
self.navigationController.preferredContentSize = CGSize(width: 200, height: 200)
}
deinit {
print("☠️deallocing \(self)")
}
}
//MARK:- Coordinator
extension PopupCoordinator: NavigationControllerCoordinator {
func start() {
print("✅ Starting PopupCoordinator")
showPopup()
}
}
private extension PopupCoordinator {
func showPopup() {
let popupViewModel = PopupViewModel { [unowned self] in
self.onClose()
}
let popupViewController = PopupViewController(viewModel: popupViewModel)
present(popupViewController, animated: true, completion: nil)
}
}
|
//
// CATransform3DExtensions.swift
//
//
// Created by Adam Bell on 5/16/20.
//
import simd
import QuartzCore
public extension CATransform3D {
/// Returns the identity matrix of `CATransform3D`
static var identity: CATransform3D {
return CATransform3DIdentity
}
/// Returns the a `CATransform3D` initialized with all zeros.
static var zero: CATransform3D {
return CATransform3D(matrix_double4x4.zero)
}
/// Intializes a `CATransform3D` with a `matrix_double4x4`.
init(_ matrix: matrix_double4x4) {
self = CATransform3DIdentity
self.m11 = CGFloat(matrix[0][0])
self.m12 = CGFloat(matrix[0][1])
self.m13 = CGFloat(matrix[0][2])
self.m14 = CGFloat(matrix[0][3])
self.m21 = CGFloat(matrix[1][0])
self.m22 = CGFloat(matrix[1][1])
self.m23 = CGFloat(matrix[1][2])
self.m24 = CGFloat(matrix[1][3])
self.m31 = CGFloat(matrix[2][0])
self.m32 = CGFloat(matrix[2][1])
self.m33 = CGFloat(matrix[2][2])
self.m34 = CGFloat(matrix[2][3])
self.m41 = CGFloat(matrix[3][0])
self.m42 = CGFloat(matrix[3][1])
self.m43 = CGFloat(matrix[3][2])
self.m44 = CGFloat(matrix[3][3])
}
init(_ matrix: matrix_float4x4) {
self = CATransform3DIdentity
self.m11 = CGFloat(matrix[0][0])
self.m12 = CGFloat(matrix[0][1])
self.m13 = CGFloat(matrix[0][2])
self.m14 = CGFloat(matrix[0][3])
self.m21 = CGFloat(matrix[1][0])
self.m22 = CGFloat(matrix[1][1])
self.m23 = CGFloat(matrix[1][2])
self.m24 = CGFloat(matrix[1][3])
self.m31 = CGFloat(matrix[2][0])
self.m32 = CGFloat(matrix[2][1])
self.m33 = CGFloat(matrix[2][2])
self.m34 = CGFloat(matrix[2][3])
self.m41 = CGFloat(matrix[3][0])
self.m42 = CGFloat(matrix[3][1])
self.m43 = CGFloat(matrix[3][2])
self.m44 = CGFloat(matrix[3][3])
}
/// Returns a `matrix_double4x4` from the contents of this transform.
internal var matrix: matrix_double4x4 {
return matrix_double4x4(self)
}
/// Returns a `matrix_double4x4.DecomposedTransform` from the contents of this transform.
internal func _decomposed() -> matrix_double4x4.DecomposedTransform {
return matrix.decomposed()
}
func decomposed() -> DecomposedTransform {
return DecomposedTransform(_decomposed())
}
/// The translation of the transform.
var translation: Translation {
get {
return Translation(_decomposed().translation)
}
set {
var decomposed = _decomposed()
decomposed.translation = newValue.storage
self = CATransform3D(decomposed.recomposed())
}
}
/// Returns a copy by translating the current transform by the given translation amount.
func translated(by translation: Translation) -> Self {
var transform = self
transform.translate(by: translation)
return transform
}
/**
Returns a copy by translating the current transform by the given translation components.
- Note: Omitted components have no effect on the translation.
*/
func translatedBy(x: CGFloat = 0.0, y: CGFloat = 0.0, z: CGFloat = 0.0) -> Self {
let translation = Translation(x, y, z)
return self.translated(by: translation)
}
/**
Returns a copy by translating the current transform by the given translation components.
- Note: Omitted components have no effect on the translation.
*/
func translated(by translation: CGPoint) -> Self {
let translation = Translation(translation.x, translation.y, 0.0)
return self.translated(by: translation)
}
/// Translates the current transform by the given translation amount.
mutating func translate(by translation: Translation) {
self = CATransform3D(matrix.translated(by: translation.storage))
}
/// Translates the current transform by the given translation amount.
mutating func translate(by translation: CGPoint) {
let translation = Translation(translation.x, translation.y, 0.0)
translate(by: translation)
}
/// The scale of the transform.
var scale: Scale {
get {
return Scale(_decomposed().scale)
}
set {
var decomposed = _decomposed()
decomposed.scale = newValue.storage
self = CATransform3D(decomposed.recomposed())
}
}
/// Returns a copy by scaling the current transform by the given scale.
func scaled(by scale: Scale) -> Self {
var transform = self
transform.scale(by: scale)
return transform
}
/// Returns a copy by scaling the current transform by the given scale.
func scaled(by scale: CGPoint) -> Self {
return self.scaled(by: Scale(scale.x, scale.y, 0.0))
}
/**
Returns a copy by scaling the current transform by the given scale.
- Note: Omitted components have no effect on the scale.
*/
func scaledBy(x: CGFloat = 1.0, y: CGFloat = 1.0, z: CGFloat = 1.0) -> Self {
let scale = Scale(x, y, z)
return self.scaled(by: scale)
}
/// Scales the current transform by the given scale.
mutating func scale(by scale: Scale) {
self = CATransform3D(matrix.scaled(by: scale.storage))
}
/// Scales the current transform by the given scale.
mutating func scale(by scale: CGPoint) {
let scale = Scale(scale.x, scale.y, 0.0)
self.scale(by: scale)
}
/// The rotation of the transform (expressed as a quaternion).
var rotation: CGQuaternion {
get {
return CGQuaternion(_decomposed().rotation)
}
set {
var decomposed = _decomposed()
decomposed.rotation = newValue.storage
self = CATransform3D(decomposed.recomposed())
}
}
/// Returns a copy by applying a rotation transform (expressed as a quaternion) to the current transform.
func rotated(by rotation: CGQuaternion) -> Self {
var transform = self
transform.rotate(by: rotation)
return transform
}
/** Returns a copy by applying a rotation transform (expressed as a quaternion) to the current transform.
- Note: Omitted components have no effect on the rotation.
*/
func rotatedBy(angle: CGFloat = 0.0, x: CGFloat = 0.0, y: CGFloat = 0.0, z: CGFloat = 0.0) -> Self {
let rotation = CGQuaternion(angle: angle, axis: CGVector3(x, y, z))
return self.rotated(by: rotation)
}
/// Rotates the current rotation by applying a rotation transform (expressed as a quaternion) to the current transform.
mutating func rotate(by rotation: CGQuaternion) {
self = CATransform3D(matrix.rotated(by: rotation.storage))
}
/// The rotation of the transform, expressed in radians.
var eulerAngles: CGVector3 {
get {
return CGVector3(_decomposed().eulerAngles)
}
set {
var decomposed = _decomposed()
decomposed.eulerAngles = newValue.storage
self = CATransform3D(decomposed.recomposed())
}
}
/// Returns a copy by applying a rotation transform (expressed as euler angles, expressed in radians) to the current transform.
func rotated(by eulerAngles: CGVector3) -> Self {
var transform = self
transform.rotate(by: eulerAngles)
return transform
}
/** Returns a copy by applying a rotation transform (expressed as euler angles, expressed in radians) to the current transform.
- Note: Omitted components have no effect on the rotation.
*/
func rotatedBy(x: CGFloat = 0.0, y: CGFloat = 0.0, z: CGFloat = 0.0) -> Self {
let rotation = CGVector3(x, y, z)
return self.rotated(by: rotation)
}
/// Rotates the current rotation by applying a rotation transform (expressed as euler angles, expressed in radians) to the current transform.
mutating func rotate(by eulerAngles: CGVector3) {
self = CATransform3D(matrix.rotated(by: eulerAngles.storage))
}
/// The skew of the transform.
var skew: Skew {
get {
return Skew(_decomposed().skew)
}
set {
var decomposed = _decomposed()
decomposed.skew = newValue.storage
self = CATransform3D(decomposed.recomposed())
}
}
/// Returns a copy by skewing the current transform by a given skew.
func skewed(by skew: Skew) -> Self {
var transform = self
transform.skew(by: skew)
return transform
}
/**
Returns a copy by skewing the current transform by the given skew components.
- Note: Omitted components have no effect on the skew.
*/
func skewedBy(xy: CGFloat? = nil, xz: CGFloat? = nil, yz: CGFloat? = nil) -> Self {
let skew = Skew(xy ?? self.skew.xy, xz ?? self.skew.xz, yz ?? self.skew.yz)
return self.skewed(by: skew)
}
mutating func skew(by skew: Skew) {
self = CATransform3D(matrix.skewed(by: skew.storage))
}
/// The perspective of the transform.
var perspective: Perspective {
get {
return Perspective(_decomposed().perspective)
}
set {
var decomposed = _decomposed()
decomposed.perspective = newValue.storage
self = CATransform3D(decomposed.recomposed())
}
}
/// Returns a copy by changing the perspective of the current transform.
func applyingPerspective(_ perspective: Perspective) -> Self {
var transform = self
transform.applyPerspective(perspective)
return transform
}
/**
Returns a copy by changing the perspective of the current transform.
- Note: Omitted components have no effect on the perspective.
*/
func applyingPerspective(m14: CGFloat? = nil, m24: CGFloat? = nil, m34: CGFloat? = nil, m44: CGFloat? = nil) -> Self {
let perspective = Perspective(m14: m14 ?? self.m14, m24: m24 ?? self.m24, m34: m34 ?? self.m34, m44: m44 ?? self.m44)
return self.applyingPerspective(perspective)
}
/// Sets the perspective of the current transform.
mutating func applyPerspective(_ perspective: Perspective) {
self = CATransform3D(matrix.applyingPerspective(perspective.storage))
}
}
// MARK: - DecomposedTransform
public extension CATransform3D {
/// Represents a decomposed CATransform3D in which the transform is broken down into its transform attributes (scale, translation, etc.).
struct DecomposedTransform {
// This is just a simple wrapper overtop `matrix_double4x4.DecomposedTransform`.
internal var storage: matrix_double4x4.DecomposedTransform
/// The translation of the transform.
public var translation: Translation {
get {
return CGVector3(storage.translation)
}
set {
storage.translation = newValue.storage
}
}
/// The scale of the transform.
public var scale: Translation {
get {
return CGVector3(storage.scale)
}
set {
storage.scale = newValue.storage
}
}
/// The rotation of the transform (exposed as a quaternion).
public var rotation: CGQuaternion {
get {
return CGQuaternion(storage.rotation)
}
set {
storage.rotation = newValue.storage
}
}
/// The skew of the transform.
public var skew: Skew {
get {
return Skew(storage.skew)
}
set {
storage.skew = newValue.storage
}
}
/// The perspective of the transform.
public var perspective: Perspective {
get {
return Perspective(storage.perspective)
}
set {
storage.perspective = newValue.storage
}
}
/**
Designated initializer.
- Note: You'll probably want to use `CATransform3D.decomposed()` instead.
*/
public init(_ decomposed: matrix_double4x4.DecomposedTransform) {
self.storage = decomposed
}
/// Merges all the properties of the the decomposed transform into a `CATransform3D`.
public func recomposed() -> CATransform3D {
return CATransform3D(storage.recomposed())
}
}
}
// MARK: - CATransform3D Extensions
extension CATransform3D.DecomposedTransform: Interpolatable {
public func lerp(to: Self, fraction: Double) -> Self {
return CATransform3D.DecomposedTransform(self.storage.lerp(to: to.storage, fraction: Double(fraction)))
}
}
extension CATransform3D: Interpolatable {
public func lerp(to: Self, fraction: CGFloat) -> Self {
return CATransform3D(self._decomposed().lerp(to: to._decomposed(), fraction: Double(fraction)).recomposed())
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.