text stringlengths 8 1.32M |
|---|
//
// Countries.swift
// domaci16
//
// Created by Apple on 9/4/20.
// Copyright © 2020 milic. All rights reserved.
//
import Foundation
import UIKit
class Countries{
var country:String
var city:[String]
init (country:String,city:[String]){
self.country = country
self.city = city
}
}
|
//
// FamilyTableViewCell.swift
// huicheng
//
// Created by lvxin on 2018/10/21.
// Copyright © 2018年 lvxin. All rights reserved.
//
import UIKit
let FamilyTableViewCellID = "FamilyTableViewCell_id"
let FamilyTableViewCellH = CGFloat(100)
class FamilyTableViewCell: UITableViewCell {
@IBOutlet weak var left1Label: UILabel!
@IBOutlet weak var left2Label: UILabel!
@IBOutlet weak var left3Label: UILabel!
@IBOutlet weak var left4Label: UILabel!
@IBOutlet weak var rightLabel: UILabel!
func setData(model : usermanageInfoModel_info2_family) {
let strName = NSMutableAttributedString(string: "关系:")
let strName2 = model.relation.getAttributedStr_color(color: .black, fontSzie: 13)
strName.append(strName2)
self.left1Label.attributedText = strName
let strName1 = NSMutableAttributedString(string: "单位:")
let strName3 = model.work.getAttributedStr_color(color: .black, fontSzie: 13)
strName1.append(strName3)
self.left2Label.attributedText = strName1
let strName4 = NSMutableAttributedString(string: "职位:")
let strName5 = model.job.getAttributedStr_color(color: .black, fontSzie: 13)
strName4.append(strName5)
self.left3Label.attributedText = strName4
let strName6 = NSMutableAttributedString(string: "联系电话:")
let strName7 = model.phone.getAttributedStr_color(color: .black, fontSzie: 13)
strName6.append(strName7)
self.left4Label.attributedText = strName6
let strName8 = NSMutableAttributedString(string: "姓名:")
let strName9 = model.name.getAttributedStr_color(color: .black, fontSzie: 13)
strName8.append(strName9)
self.rightLabel.attributedText = strName8
}
func setData1(model : usermanageInfoModel_info3) {
self.left1Label.text = "外语:"
let strName1 = NSMutableAttributedString(string: "英语 级别:")
let strName3 = model.language_en.getAttributedStr_color(color: .black, fontSzie: 13)
strName1.append(strName3)
self.left2Label.attributedText = strName1
let strName4 = NSMutableAttributedString(string: "日语 级别:")
let strName5 = model.language_jp.getAttributedStr_color(color: .black, fontSzie: 13)
strName4.append(strName5)
self.left3Label.attributedText = strName4
let strName6 = NSMutableAttributedString(string: "\(model.language_other) 级别:")
let strName7 = model.languagelevel.getAttributedStr_color(color: .black, fontSzie: 13)
strName6.append(strName7)
self.left4Label.attributedText = strName6
self.rightLabel.text = ""
}
func setData2(model : usermanageInfoModel_info3_school) {
let strName = NSMutableAttributedString(string: "时间:")
let str = model.begintime + "~" + model.endtime
let strName2 = str.getAttributedStr_color(color: .black, fontSzie: 13)
strName.append(strName2)
self.left1Label.attributedText = strName
let strName1 = NSMutableAttributedString(string: "学校:")
let strName3 = model.school.getAttributedStr_color(color: .black, fontSzie: 13)
strName1.append(strName3)
self.left2Label.attributedText = strName1
let strName4 = NSMutableAttributedString(string: "专业:")
let strName5 = model.project.getAttributedStr_color(color: .black, fontSzie: 13)
strName4.append(strName5)
self.left3Label.attributedText = strName4
let strName6 = NSMutableAttributedString(string: "学历:")
let strName7 = model.diploma.getAttributedStr_color(color: .black, fontSzie: 13)
strName6.append(strName7)
self.left4Label.attributedText = strName6
self.rightLabel.text = ""
}
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
}
}
|
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
Thread.detachNewThreadSelector(#selector(ViewController.runNative), toTarget: self, with: nil)
Timer.scheduledTimer(withTimeInterval: 0.04, repeats: true, block: {_ in self.updateNativeView()})
let frame = CGRect(x: 0, y: 0, width: 1024, height: 768)
self.nativeView = NativeView(frame: frame)
self.nativeView?.setNativeUiSize(width: 1024, height: 768)
view.addSubview(self.nativeView!)
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func runNative()
{
run_host_monitor();
}
func updateNativeView(){
if(self.nativeView == nil){
return
}
self.nativeView?.needsDisplay = true
}
var nativeView: NativeView? = nil
}
|
//
// MenuScene.swift
// DragonFly
//
// Created by Utkin Aleksandr on 15/05/2020.
// Copyright © 2020 Utkin Aleksandr. All rights reserved.
//
import SpriteKit
class MenuScene: ParentScene {
override func didMove(to view: SKView) {
if !Assets.shared.isLoaded {
Assets.shared.preloadAssets()
Assets.shared.isLoaded = true
}
setHeader(withName: nil, andBackground: "header1")
let spacingMenu = CGFloat(20)
let buttonPlay = ButtonNode(titled: "play", backgroundName: "play")
buttonPlay.position = CGPoint(x: self.frame.midX, y: self.frame.midY - (buttonPlay.size.height) * 0 - spacingMenu)
buttonPlay.name = "play"
addChild(buttonPlay)
let buttonPlayEndless = ButtonNode(titled: "endlessGame", backgroundName: "endlessGame")
buttonPlayEndless.position = CGPoint(x: self.frame.midX, y: buttonPlay.position.y - (buttonPlay.size.height) - spacingMenu)//- CGFloat(spacing * 1))
buttonPlayEndless.name = "endlessGame"
addChild(buttonPlayEndless)
let buttonOptions = ButtonNode(titled: "options", backgroundName: "options")
buttonOptions.position = CGPoint(x: self.frame.midX, y: buttonPlayEndless.position.y - (buttonPlay.size.height) - spacingMenu)//- CGFloat(spacing * 2))
buttonOptions.name = "options"
addChild(buttonOptions)
let buttonBest = ButtonNode(titled: "best", backgroundName: "best")
buttonBest.position = CGPoint(x: self.frame.midX, y: buttonOptions.position.y - (buttonPlay.size.height) - spacingMenu)//- CGFloat(spacing * 3))
buttonBest.name = "best"
addChild(buttonBest)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let location = touches.first!.location(in: self)
let node = self.atPoint(location)
if node.name == "play" {
let transition = SKTransition.fade(withDuration: 1.0)
let gameScene = GameScene(size: self.size)
gameScene.scaleMode = .aspectFill
self.scene!.view?.presentScene(gameScene, transition: transition)
} else if node.name == "endlessGame" {
let transition = SKTransition.fade(withDuration: 1.0)
EndlessGame.shared.endlessGame = true
let optionsScene = GameScene(size: self.size)
optionsScene.backScene = self
optionsScene.scaleMode = .aspectFill
self.scene!.view?.presentScene(optionsScene, transition: transition)
} else if node.name == "options" {
let transition = SKTransition.fade(withDuration: 1.0)
let optionsScene = OptionsScene(size: self.size)
optionsScene.backScene = self
optionsScene.scaleMode = .aspectFill
self.scene!.view?.presentScene(optionsScene, transition: transition)
} else if node.name == "best" {
let transition = SKTransition.fade(withDuration: 1.0)
let bestScene = BestScene(size: self.size)
bestScene.backScene = self
bestScene.scaleMode = .aspectFill
self.scene!.view?.presentScene(bestScene, transition: transition)
}
}
}
|
//
// SavedViewController.swift
// textbook
//
// Created by Vicki Yang on 2/4/21.
// Copyright © 2021 Anya Ji. All rights reserved.
//
import UIKit
class SavedViewController: UIViewController {
let pink: UIColor = UIColor(red: 1, green: 0.479, blue: 0.479, alpha: 1)
var savedTableView: UITableView!
var savedTotalLabelLeft: LeftLabel!
var savedTotalLabelRight: RightLabel!
var blackLine: UILabel!
var confirmButton: UIButton!
let sidePadding:CGFloat = 25
//var totalValue:Double = 0
var booksInSaved: [Book] = []
var cartFromBackend : [Book] = []
var retrievedUserInfo: userInfoResponseDataStruct!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.backgroundColor = .white
//Initialize tableView
savedTableView = UITableView()
savedTableView.translatesAutoresizingMaskIntoConstraints = false
savedTableView.dataSource = self
savedTableView.delegate = self
savedTableView.register(SavedTableViewCell.self, forCellReuseIdentifier: SavedTableViewCell.savedTableViewCellIdentifier)
savedTableView.backgroundColor = .white
savedTableView.layer.cornerRadius = 20
savedTableView.layer.maskedCorners = [.layerMinXMinYCorner,.layerMaxXMinYCorner]
savedTableView.clipsToBounds = true
savedTableView.showsVerticalScrollIndicator = false
savedTableView.frame.inset(by: UIEdgeInsets(top: 0, left: 0, bottom: 10, right: 0))
savedTableView.bounces = false
savedTableView.separatorStyle = .none
view.addSubview(savedTableView)
// blackLine = UILabel()
// blackLine.translatesAutoresizingMaskIntoConstraints = false
// blackLine.backgroundColor = .black
// blackLine.isUserInteractionEnabled = false
// view.addSubview(blackLine)
// savedTotalLabelLeft = LeftLabel()
// savedTotalLabelLeft.translatesAutoresizingMaskIntoConstraints = false
// savedTotalLabelLeft.backgroundColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1)
// savedTotalLabelLeft.layer.cornerRadius = 20
// savedTotalLabelLeft.layer.maskedCorners = [.layerMinXMaxYCorner]
// savedTotalLabelLeft.clipsToBounds = true
// savedTotalLabelLeft.text = "Total"
// savedTotalLabelLeft.isUserInteractionEnabled = false
// savedTotalLabelLeft.font = .systemFont(ofSize: 20)
// view.addSubview(savedTotalLabelLeft)
// savedTotalLabelRight = RightLabel()
// savedTotalLabelRight.translatesAutoresizingMaskIntoConstraints = false
// savedTotalLabelRight.backgroundColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1)
// savedTotalLabelRight.layer.cornerRadius = 20
// savedTotalLabelRight.layer.maskedCorners = [.layerMaxXMaxYCorner]
// savedTotalLabelRight.clipsToBounds = true
// savedTotalLabelRight.text = "$ 0"
// savedTotalLabelRight.textAlignment = .right
// savedTotalLabelRight.isUserInteractionEnabled = false
// savedTotalLabelRight.font = .systemFont(ofSize: 20)
// view.addSubview(savedTotalLabelRight)
// confirmButton = UIButton()
// confirmButton.layer.cornerRadius = 20
// confirmButton.clipsToBounds = true
// confirmButton.setTitle("Confirm Purchase", for: .normal)
// //confirmButton.titleLabel?.font = UIFont.systemFont(ofSize: 20)
// confirmButton.setTitleColor(.white, for: .normal)
// confirmButton.translatesAutoresizingMaskIntoConstraints = false
// confirmButton.backgroundColor = pink
// confirmButton.addTarget(self, action: #selector(confirmButtonTapped), for: .touchUpInside)
// view.addSubview(confirmButton)
//retrieveUserCart()
setupConstraints()
}
override func viewDidAppear(_ animated: Bool){
retrieveUserCart()
}
func setupConstraints(){
NSLayoutConstraint.activate([
savedTableView.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant: sidePadding),
savedTableView.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant: -sidePadding),
savedTableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor,constant: 10),
savedTableView.heightAnchor.constraint(equalToConstant: view.frame.height*0.5)
])
// NSLayoutConstraint.activate([
// blackLine.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant: sidePadding),
// blackLine.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant: -sidePadding),
// blackLine.topAnchor.constraint(equalTo: savedTableView.bottomAnchor),
// blackLine.heightAnchor.constraint(equalToConstant: 1)
// ])
// NSLayoutConstraint.activate([
// savedTotalLabelLeft.leadingAnchor.constraint(equalTo: view.leadingAnchor,constant: sidePadding),
// savedTotalLabelLeft.topAnchor.constraint(equalTo: blackLine.bottomAnchor),
// savedTotalLabelLeft.heightAnchor.constraint(equalToConstant: 50),
// savedTotalLabelLeft.widthAnchor.constraint(equalToConstant: (view.frame.width-sidePadding*2)/2)
// ])
// NSLayoutConstraint.activate([
// savedTotalLabelRight.leadingAnchor.constraint(equalTo: cartTotalLabelLeft.trailingAnchor),
// savedTotalLabelRight.trailingAnchor.constraint(equalTo: view.trailingAnchor,constant: -sidePadding),
// savedTotalLabelRight.topAnchor.constraint(equalTo: blackLine.bottomAnchor),
// savedTotalLabelRight.heightAnchor.constraint(equalToConstant: 50)
// ])
// NSLayoutConstraint.activate([
// confirmButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -30),
// confirmButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: sidePadding),
// confirmButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -sidePadding),
// confirmButton.heightAnchor.constraint(equalToConstant: 40)
// ])
}
private func retrieveUserCart(){ // need to update backend stuff
let sellerID :Int = NetworkManager.currentUser.id //this is correct now
var cartFromBackend : [Book] = []
self.booksInSaved = []
//self.totalValue = 0
//self.cartTotalLabelRight.text = String(format: "%.2f", self.totalValue)
self.savedTableView.reloadData()
NetworkManager.getUserCart(currentUserId: sellerID){ books in
cartFromBackend = books
for item in cartFromBackend{
let newItem = item
self.booksInSaved.append(newItem)
//self.totalValue += Double(newItem.price)!
//self.cartTotalLabelRight.text = String(format: "%.2f", self.totalValue)
}
//reload
DispatchQueue.main.async {
self.savedTableView.reloadData()
}
}
}
private func updateCartAfterDelete(deletedBookID:Int){
let books = booksInSaved
booksInSaved = []
for b in books{
if b.id != deletedBookID{
booksInSaved.append(b)
}
else{
//self.totalValue -= Double(b.price)!
//self.cartTotalLabelRight.text = String(format: "%.2f", self.totalValue)
}
}
//reload
DispatchQueue.main.async {
self.savedTableView.reloadData()
}
}
// @objc func confirmButtonTapped(){
// let newViewController = SuccessViewController()
// navigationController?.pushViewController(newViewController, animated: true)
// }
}
extension SavedViewController:UITableViewDataSource{
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Items"
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//return currentCart.count
return booksInSaved.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 200
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: SavedTableViewCell.savedTableViewCellIdentifier, for: indexPath) as! SavedTableViewCell
//let oneBook = currentCart[indexPath.row]
let oneBook = booksInSaved[indexPath.row]
cell.configure(inputbookData: oneBook)
cell.delegate = self
return cell
}
}
extension SavedViewController:UITableViewDelegate{
}
extension UIView {
func roundCorners(corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
}
extension SavedViewController:deleteFromCart{
func deleteFromCartAction(bookId: Int) {
let sellerID :Int = NetworkManager.currentUser.id
let updateToken:String = NetworkManager.currentUser.update_token
//call network manager to delete the book
NetworkManager.deleteOneBookFromCart(currentUserId: sellerID, bookId: bookId,updateToken: updateToken){ books in //returned cart is not used
//call retrieve user cart to update cart information
self.updateCartAfterDelete(deletedBookID: bookId)
}
}
}
|
//
// MapPresenter.swift
// carWash
//
// Created by Juliett Kuroyan on 19.11.2019.
// Copyright © 2019 VooDooLab. All rights reserved.
//
import SwiftKeychainWrapper
import CoreLocation
class MapPresenter {
// MARK: - Properties
unowned let view: MapViewProtocol
var interactor: MapInteractorProtocol!
let router: MapRouterProtocol
var isAuthorized: Bool = false
var isWashingStart: Bool = false
var washes: [WashResponse] = []
var sales: [StockResponse]?
var selectedWash: WashResponse?
var washId: Int?
init(view: MapViewProtocol,
router: MapRouterProtocol) {
self.view = view
self.router = router
}
// MARK: - Private
private func getWashes() {
view.requestDidSend()
interactor.getWashes(city: nil, onSuccess: { [weak self] (response) in
guard let self = self else { return }
self.washes = response.washes
if self.isWashingStart {
self.view.detectLocation()
}
response.washes.forEach { [weak self] (wash) in
guard let self = self else { return }
let lat = wash.coordinates[0]
let lon = wash.coordinates[1]
self.view.responseDidRecieve()
self.view.set(latitude: lat,
longitude: lon,
id: wash.id,
cashbackText: "\(wash.cashback)%") {
if self.isWashingStart {
self.view.configureWashingStartView()
} else {
self.view.configureWashInfoView()
}
self.selectedWash = wash
self.didSelectWash(id: wash.id)
}
let latitude = KeychainWrapper.standard.double(forKey: "cityLatitude")
let longitude = KeychainWrapper.standard.double(forKey: "cityLongitude")
if latitude == nil,
longitude == nil,
self.washId == nil,
let wash = self.washes.first {
self.view.configureDefaultMode(latitude: wash.coordinates[0], longitude: wash.coordinates[1])
KeychainWrapper.standard.set(wash.city, forKey: "city")
}
}
if let washId = self.washId {
self.view.selectWash(id: washId)
}
}) { [weak self] in
self?.view.responseDidRecieve()
// alert
}
}
private func didSelectWash(id: Int) {
interactor.getWash(id: id, onSuccess: { [weak self] (response) in
guard let self = self else { return }
let address = response.address
var cashback = "Кешбек: \(response.cashback)%"
if response.cashback == 0 {
cashback = "Нет кешбека"
}
var happyTimesText = ""
var isHappyTimesHidden = true
if let happyHours = response.happyHours{
happyTimesText = "с \(happyHours.start) до \(happyHours.end)"
isHappyTimesHidden = !happyHours.isEnabled
}
let sales = response.stocks
self.sales = sales
if self.isWashingStart {
self.view.showWashingStartInfo(address: address,
terminalsCount: 10) // !
} else {
self.view.showWashInfo(address: address,
cashback: cashback,
sales: sales ?? [],
happyTimesText: happyTimesText,
isHappyTimesHidden: isHappyTimesHidden)
}
}) {
()
}
}
}
// MARK: - MapPresenterProtocol
extension MapPresenter: MapPresenterProtocol {
func didSelectTerminal(index: Int, address: String) {
view.showConfirmationView(address: "\(address), терминал №\(index + 1)") { [weak self] in
guard let self = self else { return }
let systemId = self.selectedWash?.systemId ?? ""
let code = systemId + "-" + String(index) // !!!!!!!!!!!!!!
let onSuccess: (WashStartResponse) -> () = { [weak self] (wash) in
switch wash.status {
case "ok":
self?.view.setSucceeded(message: QRConstants.defaultSucceededMessage)
default:
let message = wash.msg ?? QRConstants.defaultErrorMessage
self?.view.setError(message: message)
}
}
let onFailure: () -> ()? = { [weak self] in
self?.view.setError(message: QRConstants.defaultErrorMessage)
}
self.interactor.startWash(code: code,
onSuccess: onSuccess,
onFailure: onFailure)
}
}
func didReceiveUserLocation(lat: Double, lon: Double) {
var distance: Double?
var nearestWash: WashResponse?
let location = CLLocation(latitude: lat, longitude: lon)
washes.forEach { (wash) in
let washLat = wash.coordinates[0]
let washLon = wash.coordinates[1]
let washLocation = CLLocation(latitude: washLat, longitude: washLon)
let currentDistance = washLocation.distance(from: location)
if distance == nil || currentDistance < distance! {
distance = currentDistance
nearestWash = wash
}
}
if let wash = nearestWash {
view.showAlert(message: "Вы находитесь на мойке по адресу \(wash.address)?",
title: "Подтверждение",
okButtonTitle: "Да",
cancelButtonTitle: "Нет",
okAction: { [weak self] in
self?.view.startWash(id: wash.id)
}) { [weak self] in
self?.view.select(latitude: lat, longitude: lon, locationDelta: nil)
self?.view.showMessage(text: "Выберите нужную мойку")
}
}
}
func selectCity(cityChanged: (() -> ())?) {
router.presentCityView(cityChanged: cityChanged)
}
func logout() { // !
view.showAlert(message: "Вы действительно хотите выйти?",
title: "Выход",
okButtonTitle: "Да",
cancelButtonTitle: "Нет",
okAction: { [weak self] in
self?.interactor.logout(onSuccess: { [weak self] in
self?.router.popToAuthorization()
KeychainWrapper.standard.removeAllKeys()
}) {
// alert
}
}) {}
}
func presentSaleInfoView(row: Int) {
if let saleId = sales?[row].id {
router.presentSaleInfoView(id: saleId)
}
}
func popView() {
router.popView()
}
func viewDidLoad() {
getWashes()
if washId != nil {
view.configureSelectedWashMode()
}
}
func viewWillAppear() {
if washId == nil {
if let latitude = KeychainWrapper.standard.double(forKey: "cityLatitude"),
let longitude = KeychainWrapper.standard.double(forKey: "cityLongitude") {
view.configureDefaultMode(latitude: latitude, longitude: longitude)
}
}
}
}
|
//
// FirstViewController.swift
// FinalProject3
//
// Created by Tejas Shah on 4/25/16.
// Copyright © 2016 Tejas Shah. All rights reserved.
//
import AVFoundation
import UIKit
class FirstViewController: UIViewController
{
var player = AVAudioPlayer()
@IBAction func alertButton(sender: AnyObject)
{
let alertController = UIAlertController(title: "Fire Water Grass", message: "Fire beats Grass, Water beats Fire, and Grass beats Water!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
override func viewDidLoad()
{
let url:NSURL = NSBundle.mainBundle().URLForResource("bg", withExtension: "mp3")!
do
{
player = try AVAudioPlayer(contentsOfURL: url, fileTypeHint: nil)
}
catch
let error as NSError
{
print(error.description)
}
player.numberOfLoops = -1
player.prepareToPlay()
player.play()
}
} |
//
// PresentationState.HeaderFooterStateTests.swift
// ListableUI-Unit-Tests
//
// Created by Kyle Van Essen on 5/22/20.
//
import XCTest
@testable import ListableUI
class PresentationState_HeaderFooterStateTests : XCTestCase
{
}
|
//
// ViewController.swift
// Flash Chat
//
//
// Created by Lucas Dahl 11/11/2018.
// Copyright © 2018 Lucas Dahl. All rights reserved.
//
import UIKit
import Firebase
import ChameleonFramework
class ChatViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
// Properties
var messageArray = [Message]()
// BOutlets
@IBOutlet var heightConstraint: NSLayoutConstraint!
@IBOutlet var sendButton: UIButton!
@IBOutlet var messageTextfield: UITextField!
@IBOutlet var messageTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// delegate and datasource
messageTableView.delegate = self
messageTableView.dataSource = self
// delegate of the text field
messageTextfield.delegate = self
// tapGesture
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tableViewTapped))
messageTableView.addGestureRecognizer(tapGesture)
// Register MessageCell.xib file
messageTableView.register(UINib(nibName: "MessageCell", bundle: nil), forCellReuseIdentifier: "customMessageCell")
// Connfigure the tableview
configureTableView()
// Retrieve the messages
retrieveMessages()
// Take out the seperator lines
messageTableView.separatorStyle = .none
}
///////////////////////////////////////////
//MARK: - TableView DataSource Methods
// CellForRowAtIndexPath
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Creat the cell and declare it as the custom cell class to call properties
let cell = tableView.dequeueReusableCell(withIdentifier: "customMessageCell", for: indexPath) as! CustomMessageCell
cell.messageBody.text = messageArray[indexPath.row].messageBody
cell.senderUsername.text = messageArray[indexPath.row].sender
cell.avatarImageView.image = UIImage(named: "egg")
// check if the message is from the user or someone else
if cell.senderUsername.text == Auth.auth().currentUser?.email {
cell.avatarImageView.backgroundColor = UIColor.flatMint()
cell.messageBackground.backgroundColor = UIColor.flatSkyBlue()
} else {
cell.avatarImageView.backgroundColor = UIColor.flatWatermelon()
cell.messageBackground.backgroundColor = UIColor.flatGray()
}
// return the cell
return cell
}
// NumberOfRowsInSection
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messageArray.count
}
// TableViewTapped
@objc func tableViewTapped() {
// Trigger the endEditing method to trigger the animation for the tap gesture.
messageTextfield.endEditing(true)
}
// ConfigureTableView
func configureTableView() {
// Set the cell height
messageTableView.rowHeight = UITableViewAutomaticDimension
messageTableView.estimatedRowHeight = 120
}
///////////////////////////////////////////
//MARK:- TextField Delegate Methods
// textFieldDidBeginEditing
func textFieldDidBeginEditing(_ textField: UITextField) {
// ANimate the pop up for the kewyboard
UIView.animate(withDuration: 0.25) {
// Set the height constrant for the textfield when it's tapped
self.heightConstraint.constant = 308
self.view.layoutIfNeeded()
}
}
// textFieldDidEndEditing
func textFieldDidEndEditing(_ textField: UITextField) {
// ANimate the pop up for the kewyboard
UIView.animate(withDuration: 0.25) {
// Set the height constrant for the textfield when it's tapped
self.heightConstraint.constant = 50
self.view.layoutIfNeeded()
}
}
///////////////////////////////////////////
//MARK: - Send & Recieve from Firebase
@IBAction func sendPressed(_ sender: AnyObject) {
// Call the end editing method
messageTextfield.endEditing(true)
// Send the message to Firebase and save it in our database
// Temp disable UI elements to avoid problems sending to firebase
messageTextfield.isEnabled = false
sendButton.isEnabled = false
// This will be for messages in the database
let messagesDB = Database.database().reference().child("Messages")
// Save the users message as a dictionary based on the user
let messageDictionary = ["Sender":Auth.auth().currentUser?.email, "MessageBody":messageTextfield.text!]
// Creats a custom random ID for the database and saves it
messagesDB.childByAutoId().setValue(messageDictionary) {
(error, reference) in
if error != nil {
// Print the error
print(error!)
} else {
// It worked
print("The message was saved")
// Enable the textFiled and sendButton
self.messageTextfield.isEnabled = true
self.sendButton.isEnabled = true
// Clear the text field after the message is sent
self.messageTextfield.text = ""
}
}
}
// Create the retrieveMessages method here:
func retrieveMessages() {
// Get a reference to the Messages database
let messageDB = Database.database().reference().child("Messages")
// Grab the new messges saved into the database
messageDB.observe(.childAdded) { (snapshot) in
let snapshotValue = snapshot.value as! Dictionary<String,String>
let text = snapshotValue["MessageBody"]!
let sender = snapshotValue["Sender"]!
// Create the message object
let message = Message()
// Set the message values
message.messageBody = text
message.sender = sender
// Add the message to teh message array
self.messageArray.append(message)
// Configure the tableView and reload
self.configureTableView()
self.messageTableView.reloadData()
}
}
@IBAction func logOutPressed(_ sender: AnyObject) {
// Log out the user and send them back to WelcomeViewController
do {
try Auth.auth().signOut()
// Go to the Welcome(root) ViewController
navigationController?.popToRootViewController(animated: true)
} catch {
// Prints the error
print(error)
}
}// End logOutPressed
}
|
func sumNumbers(numbers: Int...) {
var sum = 0
for number in numbers {
sum += number
}
print(sum)
}
sumNumbers(numbers: 10, 12, 13, 14)
|
//
// FavoriteWeatherPicturesViewController.swift
// WeatherApp
//
// Created by Donkemezuo Raymond Tariladou on 1/21/19.
// Copyright © 2019 Pursuit. All rights reserved.
//
import UIKit
class FavoriteWeatherPicturesViewController: UIViewController {
@IBOutlet weak var savedPhotosTableView: UITableView!
var favoritedImages = [SavedImage](){
didSet {
savedPhotosTableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
loadFavorites()
savedPhotosTableView.delegate = self
savedPhotosTableView.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadFavorites()
}
func loadFavorites() {
favoritedImages = SavedImageModel.getSavedImages().sorted {$0.time > $1.time}
}
}
extension FavoriteWeatherPicturesViewController: UITableViewDataSource, UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return favoritedImages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = savedPhotosTableView.dequeueReusableCell(withIdentifier: "PhotoCell", for: indexPath) as? SavedPicturesTableViewCell else {return UITableViewCell()}
let image = favoritedImages[indexPath.row]
cell.imageView?.image = nil
cell.savedPictureView.image = UIImage.init(data: image.imageURL)
return cell
}
}
|
//
// MemeDetailController.swift
// MeMe
//
// Created by Leela Krishna Chaitanya Koravi on 12/23/20.
// Copyright © 2020 Leela Krishna Chaitanya Koravi. All rights reserved.
//
import Foundation
import UIKit
class MemeDetailController:UIViewController {
var meme:Meme!
@IBOutlet weak var memeDetailImage: UIImageView!
override func viewDidLoad() {
print("MemeDetailController viewDidLoad")
navigationItem.title = "Meme Details"
memeDetailImage?.image = meme.memedImage
}
}
|
//
// NameQuizViewDelegate.swift
// FlagQuiz
//
// Created by Soohan Lee on 2020/01/24.
// Copyright © 2020 Soohan Lee. All rights reserved.
//
import Foundation
protocol NameQuizViewDelegate {
func button(_ button: AnswerButton, didTouchUpInsideAt location: ButtonLocation)
}
|
//
// JogViewModel.swift
// JogTracker
//
// Created by MAC on 10/28/19.
// Copyright © 2019 micantia. All rights reserved.
//
import Foundation
enum modelValidation {
case distanceEmpty
case timeEmpty
case dateFormat
case valid
}
class JogViewModel {
var jog: Jog
var jogId: Int {
return jog.id
}
var time: String {
return "\(jog.time)"
}
var distance: String {
return "\(jog.distance)"
}
var date: String {
let dateFormatted = Date(timeIntervalSince1970: Double(jog.date))
let dateFormatter = DateFormatter()
dateFormatter.timeZone = .current
dateFormatter.dateFormat = "yyyy-MMM-dd hh:mm"
return dateFormatter.string(from: dateFormatted)
}
var dateObj: Date {
return Date(timeIntervalSince1970: Double(jog.date))
}
init(jog: Jog) {
self.jog = jog
}
static func validateJog(date: String?, time: String?, distance: String?) -> modelValidation {
if date == nil {
return .dateFormat
}
if distance!.isEmpty {
return .distanceEmpty
}
if time!.isEmpty {
return .timeEmpty
}
return .valid
}
static func addJog (date: String, time: String, distance: String, completion: @escaping (Bool, String?) -> Void) {
let valid = validateJog(date: date, time: time, distance: distance)
switch valid{
case .dateFormat:
completion(false, "Incorrect date format")
return
case .distanceEmpty:
completion(false, "Distance field is Empty")
return
case .timeEmpty:
completion(false, "Time field is Empty")
return
case .valid:
WebService.addJog(date: date, time: time, distance: distance) { jog in
JogsViewModel.list.appendJog(jog)
DispatchQueue.main.async {
completion(true, nil)
}
}
}
}
static func editJog (jog: JogViewModel, date: String, time: String, distance: String, completion: @escaping (Bool, String?) -> Void) {
let jogModel = jog.jog
let valid = validateJog(date: date, time: time, distance: distance)
switch valid{
case .dateFormat:
completion(false, "Incorrect date format")
return
case .distanceEmpty:
completion(false, "Distance field is Empty")
return
case .timeEmpty:
completion(false, "Time field is Empty")
return
case .valid:
WebService.editJog(jog: jogModel, date: date, time: time, distance: distance) { jog in
JogsViewModel.list.editJog(jog)
DispatchQueue.main.async {
completion(true, nil)
}
}
}
}
}
|
//
// KLineModel.swift
// KLineView
//
// Created by 程守斌 on 2019/3/1.
//
import Foundation
public class KLineModel : NSObject {
/// - 赋值属性 (k线)
var timestamp: Double = 0.0 //时间轴
var open: Double = 0.0 //开盘价
var high: Double = 0.0 //收盘价
var low: Double = 0.0 //最高价
var close: Double = 0.0 //最低价(分时price)
var volume: Double = 0.0 //成交量
/// - 计算属性
// var amountVol: Double = 0.0
var avePrice: Double = 0.0
// var total: Double = 0.0
// var maSum: Double = 0.0
//SMA(简单均线)
var smaLine1: Double = 0.0
var smaLine2: Double = 0.0
//EMA(指数均线)
var emaLine1: Double = 0.0
var emaLine2: Double = 0.0
//BOLL(布林轨道)
var boll: Double = 0.0 //布林中线
var ub: Double = 0.0 //布林上线
var lb: Double = 0.0 //布林下线
//MACD
var dif: Double = 0.0 //短期与长期移动平均线间的离差值
var dea: Double = 0.0 //平滑移动平均线
var bar: Double = 0.0 //指数平滑移动
//KDJ
var k: Double = 0.0 //快速线
var d: Double = 0.0 //慢速线
var j: Double = 0.0 //k&d的乘离
//RSI(KLineConst.kRSILine ...)
var rsiLine1: Double = 0.0 //相对强弱线1
var rsiLine2: Double = 0.0 //相对强弱线2
var rsiLine3: Double = 0.0 //相对强弱线3
public init(timestamp: Double, open: Double, high: Double, low: Double, close: Double, volume: Double) {
self.timestamp = timestamp
self.open = open
self.high = high
self.low = low
self.close = close
self.volume = volume
}
}
|
/*:
Finally, we are ready to explore how analog signals are converted to digital ones. In the Live View, you see the diagram of a *successive approximation analog-to-digital converter*.
This circuit works by comparing the input voltage to a voltage generated by a digital-to-analog (“D/A”) converter. A logic implements *binary search* to quickly find the closest matching voltage the D/A converter is able to generate. Since the closest matching voltage is also the best representable approximation of the input signal, the fixed-point number used to generate this voltage is the result of the analog-to-digital conversion.
This logic is implemented in the code down below. Isn’t it wonderful that algorithms of the world of computer science also have applications in the electrical domain?
- Experiment:
Vary the parameters below and see how the obtained digital signal changes. **Adjust the parameters in a way that the main voltage peak at approximately 0.25 seconds can be identified in the acquired digital signal.**
*/
//#-code-completion(everything, hide)
//#-code-completion(literal, show, integer)
//#-hidden-code
import Book
import Foundation
import PlaygroundSupport
import Darwin
var numberOfBits: Int = 0
var maximumVoltage: Double = 0.0
var timeBetweenConversions: TimeInterval = 0.5
func setNumberOfBits(_ value: Int) {
guard (2...UInt64.bitWidth).contains(value) else {
fatalError("This example requires 2 bits at least and 64 bits at most.")
}
numberOfBits = value
}
func setMaximumVoltage(_ value: Double) {
guard value > 0.0 else {
fatalError("This example only supports maximum voltages that are larger than zero.")
}
maximumVoltage = value
}
func setTimeBetweenConversions(_ value: TimeInterval) {
guard value > 0.0 else {
fatalError("The time between conversions must be larger than zero.")
}
timeBetweenConversions = value
}
//#-end-hidden-code
setNumberOfBits(/*#-editable-code*/8/*#-end-editable-code*/)
setMaximumVoltage(/*#-editable-code*/0.02/*#-end-editable-code*/)
setTimeBetweenConversions(/*#-editable-code*/0.07/*#-end-editable-code*/)
/*:
- Callout(Tip):
Try the different execution modes by tapping on the stopwatch button next to the “Run My Code” button. For example, choose “Step Through My Code” to see how the algorithm implemented in the logic works line-by-line, or choose “Run Fastest” to quickly obtain the conversion result.
*/
//#-hidden-code
let remoteView = PlaygroundPage.current.liveView as! PlaygroundRemoteLiveViewProxy
var resistorLadder = R2RResistorLadder(numberOfBits: numberOfBits, referenceVoltage: maximumVoltage)
var currentTime: TimeInterval = 0.0
var delay: TimeInterval {
switch PlaygroundPage.current.executionMode {
case .run:
return 0.2
case .runFaster:
return 0.1
default:
return 0.0
}
}
func setBit(at index: Int) {
resistorLadder.setBit(at: index)
remoteView.send(.dictionary([
"SetBit": .integer(index),
"ShowOutputVoltage": .dictionary([
"Time": .floatingPoint(currentTime),
"Voltage": .floatingPoint(resistorLadder.outputVoltage)
])
]))
Thread.sleep(forTimeInterval: delay)
}
func clearBit(at index: Int) {
resistorLadder.clearBit(at: index)
remoteView.send(.dictionary([
"ClearBit": .integer(index),
"ShowOutputVoltage": .dictionary([
"Time": .floatingPoint(currentTime),
"Voltage": .floatingPoint(resistorLadder.outputVoltage)
])
]))
Thread.sleep(forTimeInterval: delay)
}
func clearAllBits() {
resistorLadder.clearAllBits()
if currentTime >= timeBetweenConversions {
remoteView.send(.dictionary([
"ClearAllBits": .boolean(true),
"ShowOutputVoltage": .dictionary([
"Time": .floatingPoint(currentTime - timeBetweenConversions),
"Voltage": .floatingPoint(resistorLadder.outputVoltage)
])
]))
Thread.sleep(forTimeInterval: max(PlaygroundPage.current.executionMode == .runFastest ? 0.001 : 0.1, delay))
remoteView.send(.dictionary([
"ClearAllBits": .boolean(true),
"ShowOutputVoltage": .dictionary([
"Time": .floatingPoint(currentTime),
"Voltage": .floatingPoint(resistorLadder.outputVoltage)
])
]))
} else {
remoteView.send(.dictionary([
"ClearAllBits": .boolean(true),
"ShowOutputVoltage": .dictionary([
"Time": .floatingPoint(currentTime),
"Voltage": .floatingPoint(resistorLadder.outputVoltage)
])
]))
Thread.sleep(forTimeInterval: delay)
}
}
func getOutputValue() -> Double {
resistorLadder.outputVoltage
}
func getNextInputValue() -> OpaqueSignalValue? {
// Validate user-configurable parameters here since fatalError() seems to show a error message to the user only when called inside a function that is called in non-hidden code
guard maximumVoltage > 0.0 else {
fatalError("The maximum voltage must be larger than zero.")
}
guard timeBetweenConversions > 0.0 else {
fatalError("The sample rate must be larger than zero.")
}
if currentTime <= 0.7 {
return getInputSignalValue(at: currentTime)
} else {
return nil
}
}
func saveResult(_ value: Double) {
Thread.sleep(forTimeInterval: delay)
remoteView.send(.dictionary([
"SaveSample": .dictionary([
"Time": .floatingPoint(currentTime),
"Voltage": .floatingPoint(resistorLadder.outputVoltage)
])
]))
}
func incrementTime() {
currentTime += timeBetweenConversions
}
remoteView.send(.dictionary([
"SetDacResolution": .integer(numberOfBits),
"SetMaximumVoltage": .floatingPoint(maximumVoltage),
"ClearSamples": .boolean(true)
]))
//#-end-hidden-code
while let inputValue = getNextInputValue() {
clearAllBits()
for index in (0..<numberOfBits).reversed() {
setBit(at: index)
// Note: In a real-world converter, the comparison of the two voltages is performed in the comparator (which is shown as a triangle with a plus and a minus symbol in the circuit diagram). The logic would only receive a binary input from the comparator containing the comparison result.
if inputValue < getOutputValue() {
clearBit(at: index)
}
}
saveResult(getOutputValue())
//#-hidden-code
incrementTime()
//#-end-hidden-code
}
//#-hidden-code
clearAllBits()
remoteView.send(.dictionary([
"CheckForAssessmentFailure": .boolean(true)
]))
//#-end-hidden-code
|
//
// ReceiveFriendsListViewController.swift
// Skunk
//
// Created by Anant Goel on 9/23/15.
// Copyright © 2015 CS408. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
class ReceiveFriendsListViewController: UITableViewController {
let sessionIdentifier = "Session"
var accountManager: UserAccountManager!
var sessionManager: ShareSessionManager!
var selectedSharerSession: ShareSession!
var sharerList = [RegisteredUserAccount]()
override func viewDidLoad() {
super.viewDidLoad()
let refreshControl = UIRefreshControl()
refreshControl.backgroundColor = UIColor.darkGrayColor()
refreshControl.tintColor = UIColor.whiteColor()
refreshControl.addTarget(self, action: "listRefresh", forControlEvents: .ValueChanged)
self.refreshControl = refreshControl
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.tableView.userInteractionEnabled = false
self.refreshControl!.beginRefreshing()
// Per http://stackoverflow.com/a/22471166
let offset = CGPointMake(0, self.tableView.contentOffset.y - 80.0)
self.tableView.setContentOffset(offset, animated: true)
listRefresh()
}
func reloadData() {
self.tableView.reloadData()
let formatter = NSDateFormatter()
formatter.dateFormat = "MMM d, h:mm a"
let refreshTitle = "Last updated at \(formatter.stringFromDate(NSDate()))"
let attributes = [
NSForegroundColorAttributeName: UIColor.whiteColor(),
]
let attributedText = NSAttributedString(string: refreshTitle, attributes: attributes)
self.refreshControl!.attributedTitle = attributedText
if self.sharerList.isEmpty {
let noSessionsLabel = UILabel()
noSessionsLabel.text = "No sessions shared with you\n\nPull to refresh"
noSessionsLabel.numberOfLines = 0
noSessionsLabel.textAlignment = .Center
noSessionsLabel.textColor = UIColor.grayColor()
self.tableView.backgroundView = noSessionsLabel
self.tableView.separatorStyle = .None
} else {
self.tableView.backgroundView = nil
self.tableView.separatorStyle = .SingleLine
}
}
override func numberOfSectionsInTableView(friendsTableView: UITableView) -> Int {
return 1;
}
override func tableView(friendsTableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sharerList.count;
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let sharerRegisteredUserAccount = sharerList[indexPath.row]
let sharerUid = sharerRegisteredUserAccount.identifier
selectedSharerSession = sessionManager.sharerInformation[sharerUid]
performSegueWithIdentifier(sessionIdentifier, sender: self)
}
override func tableView(friendsTableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = friendsTableView.dequeueReusableCellWithIdentifier("FriendsCell", forIndexPath: indexPath)
let sharerRegisteredUserAccount = sharerList[indexPath.row]
let sharerUserAccount = sharerRegisteredUserAccount.userAccount
let sharerUid = sharerRegisteredUserAccount.identifier
let sharerSession = sessionManager.sharerInformation[sharerUid]!
cell.textLabel!.text = sharerUserAccount.firstName + " " + sharerUserAccount.lastName
cell.detailTextLabel!.font = UIFont.systemFontOfSize(cell.detailTextLabel!.font.pointSize)
var detailText = ""
if sharerSession.needsDriver {
if let driverIdentifier = sharerSession.driverIdentifier {
if driverIdentifier == self.accountManager.registeredAccount!.identifier {
detailText += "You are the driver"
} else {
detailText += "Has a driver"
}
} else {
cell.detailTextLabel!.font = UIFont.boldSystemFontOfSize(cell.detailTextLabel!.font.pointSize)
detailText += "Needs Driver"
}
detailText += " | "
}
switch sharerSession.endCondition {
case .Location(_):
detailText += "Sharing until Destination"
case .Time(let endDate):
let currentDate = NSDate()
let secondDifference = endDate.timeIntervalSince1970 - currentDate.timeIntervalSince1970
let hourDifference = secondDifference / 60.0 / 60.0
// Round to nearest 0.5
let roundedHourDifference = round(2.0 * hourDifference) / 2.0
let hourText = String(format: "%.1f %@",
roundedHourDifference, (roundedHourDifference == 1.0 ? "hour" : "hours"))
detailText += "\(hourText) til done sharing"
}
cell.detailTextLabel!.text = detailText
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
switch segue.identifier {
case sessionIdentifier?:
let sessionController = segue.destinationViewController as! ReceiveMainViewController
sessionController.accountManager = accountManager
sessionController.sessionManager = sessionManager
sessionController.sharerSession = selectedSharerSession
default:
break
}
}
func listRefresh() {
sessionManager.fetchShareSessions(accountManager.registeredAccount!) { (registeredAccounts) -> () in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let registeredAccounts = registeredAccounts {
self.sharerList = registeredAccounts
} else {
self.sharerList.removeAll()
self.presentErrorAlert("Failed to Request All Sessions")
}
self.refreshControl!.endRefreshing()
self.reloadData()
self.tableView.userInteractionEnabled = true
})
}
}
}
|
//
// BottomThreeView.swift
// ZLHJHelpAPP
//
// Created by 周希财 on 2019/12/23.
// Copyright © 2019 VIC. All rights reserved.
//
import UIKit
class BottomThreeView: UIView,NibLoadable {
@IBOutlet weak var PerviousStepBtn: UIButton!
@IBOutlet weak var nextBtn: UIButton!
@IBOutlet weak var creditBtn: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
PerviousStepBtn.backgroundColor = systemColor
creditBtn.backgroundColor = systemColor
nextBtn.backgroundColor = systemColor
PerviousStepBtn.height = 50
creditBtn.height = 50
nextBtn.height = 50
}
}
|
//
// AppDelegate.swift
// LyonsDen
//
// Created by Inal Gotov on 2016-06-30.
// Copyright © 2016 William Lyon Mackenize CI. All rights reserved.
//
import UIKit
import Firebase
import Contacts
let navigationBarColor:UIColor = UIColor(red: 0.023, green: 0.2980, blue: 0.6980, alpha: 1)
let foregroundColor:UIColor = UIColor(red: 0.0118, green: 0.2431, blue: 0.5765, alpha: 1)
let backgroundColor:UIColor = UIColor(red: 0.0078, green: 0.1647, blue: 0.3922, alpha: 1)
let accentColor:UIColor = UIColor(red: 0.9961, green: 0.7765, blue: 0.2784, alpha: 1)
let skyBlueColor:UIColor = UIColor(red: 0.6392, green: 0.7451, blue: 0.8980, alpha: 1)
// New color Scheme: New color scheme will put "color" before name, to uncomplicate things, since color change will be gradual, or so i think... It wasn't
let colorBackground:UIColor = UIColor(red: 0.9255, green: 0.9412, blue: 0.9451, alpha: 1) // ECF0F1
let colorTextFieldBackground:UIColor = UIColor(red: 0.1608, green: 0.5020, blue: 0.7255, alpha: 1) // 2980B9
let colorNavigationBar:UIColor = UIColor(red: 0.9451, green: 0.7686, blue: 0.0588, alpha: 1) // F1C40F
let colorNavigationText:UIColor = UIColor(red: 0.5843, green: 0.6471, blue: 0.6510, alpha: 1) // 95A5A6
let colorAccent:UIColor = UIColor(red: 0.2118, green: 0.2745, blue: 0.6276, alpha: 1) // 3646A0 yes this one
let colorListBackground:UIColor = UIColor(red: 0.2471, green: 0.3176, blue: 0.7098, alpha: 1) // 3F51B5 <- and ^ are not much different to be honest
let colorListDivider:UIColor = UIColor(red: 0.3765, green: 0.4902, blue: 0.5451, alpha: 1) // 607D8B
let colorEventViewBackground:UIColor = UIColor(red: 0.0078, green: 0.1647, blue: 0.3922, alpha: 1)
let colorTimeTableDividers:UIColor = UIColor(red: 0.2627, green: 0.3333, blue: 0.3686, alpha: 1) // 43555E
let colorWhiteText:UIColor = UIColor(white: 1, alpha: 1)
let keyCalendarEventBank:String = "calendarEventBank"
let keyDayDictionary:String = "dayDictionary"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FIRApp.configure()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
extension UIViewController {
// To use: call, implement completion handler, the parameter in the completion handler will contain result
// Completion handler should further handle the result
// Inspired by: http://stackoverflow.com/a/32649027/6728099
func checkInternet(completionHandler: ((_ internet:Bool, _ response:HTTPURLResponse?) -> Void)?) {
let url = URL (string: "https://www.google.ca")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
let rsp = response as! HTTPURLResponse?
completionHandler?(rsp?.statusCode == 200, rsp)
}
task.resume()
}
}
|
//
// PhotoViewController.swift
// APP-SCONTRINI
//
// Created by Mhscio on 26/11/2019.
// Copyright © 2019 Mhscio. All rights reserved.
//
import UIKit
import TesseractOCR
import FirebaseStorage
import FirebaseFirestore
import FirebaseAuth
class PhotoViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, G8TesseractDelegate{
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var formCF: UITextField!
@IBOutlet weak var textParsato: UILabel!
@IBOutlet weak var formTotale: UITextField!
@IBOutlet weak var formDetraibile: UITextField!
@IBOutlet weak var datePicker: UIDatePicker!
var imagePicker : UIImagePickerController?
@IBAction func postImage(_ sender: Any) {
if (formCF.text!.isEmpty) || (formTotale.text!.isEmpty) && (formDetraibile.text!.isEmpty){
self.showToast(message: "Riempire tutti i campi")
}else {
guard let image = imageView.image, let data = image.jpegData(compressionQuality: 1.0) else {
print("errore errore errore!")
return
}
let stringa = self.datePicker.date.description
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss '+0000'"
let dateFormatterYear = DateFormatter()
dateFormatterYear.dateFormat = "yyyy"
let dateFormatterMonth = DateFormatter()
dateFormatterMonth.dateFormat = "MM"
let dateFormatterDay = DateFormatter()
dateFormatterDay.dateFormat = "dd"
var anno = " "
var mese = " "
var giorno = " "
if let date = dateFormatterGet.date(from: stringa) {
anno = dateFormatterYear.string(from: date)
mese = dateFormatterMonth.string(from: date)
giorno = dateFormatterDay.string(from: date)
} else {
print("There was an error decoding the string")
}
let imageName = UUID().uuidString
var urlScontrino = " "
let imageReference = Storage.storage().reference().child(imageName)
imageReference.putData(data, metadata: nil) { (metadata, err) in
if err != nil {
print("errore errore errore!")
return
}
imageReference.downloadURL { (url, err) in
if err != nil {
print("errore errore errore!")
return
}
guard let url = url else {
print("errore errore errore!")
return
}
urlScontrino = url.absoluteString
let hashScontrino = String(self.strHash(urlScontrino))
print(urlScontrino)
print(String(self.strHash(urlScontrino)))
print("questo è l'url: \(urlScontrino)")
let db = Firestore.firestore()
if let uid = Auth.auth().currentUser?.uid {
let campo = db.collection("users").document(uid)
campo.collection("scontrini").document(hashScontrino).setData([
"URL": urlScontrino ,
"data": self.datePicker.date.description,
"detraibile": self.formDetraibile.text ?? " ",
"totale" : self.formTotale.text ?? " ",
"CF" : self.formCF.text ?? " ",
"anno" : anno,
"mese" : mese,
"giorno" : giorno
]) { err in
if let err = err {
print("Error writing document: \(err)")
} else {
print("Document successfully written!")
self.showToast(message: "Documento Aggiunto!")
self.resetView()
}
}
}
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
imagePicker = UIImagePickerController()
imagePicker?.delegate = self
}
@IBAction func selectPhotoTapped(_ sender: Any) {
if imagePicker != nil {
imagePicker!.sourceType = .photoLibrary
present(imagePicker!, animated: true, completion: nil)
}
}
@IBAction func cameraTapped(_ sender: Any) {
if imagePicker != nil {
imagePicker!.sourceType = .camera
present(imagePicker!, animated: true, completion: nil)
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
imageView.image = image
print("Ho cambiato le immagini")
if let tesseract = G8Tesseract(language: "ita"){
tesseract.delegate = self
tesseract.image = image
tesseract.recognize()
let testoScontrino = tesseract.recognizedText
print(testoScontrino!)
trovaTotale(testo: testoScontrino ?? "TOTALE non trovato ")
trovaDetraibile(testo: testoScontrino ?? "DETRAIBILE non trovato")
//trovaData(testo: testoScontrino ?? "DATA NON TROVATA")
//trovaCf(testo: testoScontrino ?? "CF NON TROVATO" )
let data = matches(for: "\\b(?:20)?(\\d\\d)[-./](0?[1-9]|1[0-2])[-./](3[0-1]|[1-2][0-9]|0?[1-9])\\b", in: testoScontrino ?? "data")
setData(testo: data)
print(data)
let cf = matches(for: "\\b(?:[A-Z][AEIOU][AEIOUX]|[B-DF-HJ-NP-TV-Z]{2}[A-Z]){2}(?:[\\dLMNP-V]{2}(?:[A-EHLMPR-T](?:[04LQ][1-9MNP-V]|[15MR][\\dLMNP-V]|[26NS][0-8LMNP-U])|[DHPS][37PT][0L]|[ACELMRT][37PT][01LM]|[AC-EHLMPR-T][26NS][9V])|(?:[02468LNQSU][048LQU]|[13579MPRTV][26NS])B[26NS][9V])(?:[A-MZ][1-9MNP-V][\\dLMNP-V]{2}|[A-M][0L](?:[1-9MNP-V][\\dLMNP-V]|[0L][1-9MNP-V]))[A-Z]\\b", in: testoScontrino ?? "cf non trovato")
setCf(testo: cf)
print(cf)
}
dismiss(animated: true, completion: nil)
}
func trovaTotale(testo: String) {
let arrayTesto = testo.components(separatedBy: "\n")
for index in arrayTesto {
if (index.contains("TOTALE")) || (index.contains("IMPORTO")) || (index.contains("TOT.")){
let tot = matches(for: "[-+]?[0-9]*\\.?[0-9]+", in: index )
let totfinale = tot.joined()
print("questo è il totale rilevato : \(tot) ")
formTotale.text = totfinale
}
}
}
func trovaDetraibile(testo: String) {
let arrayTesto = testo.components(separatedBy: "\n")
print(arrayTesto)
for index in arrayTesto {
if (index.contains("detraibile")) || (index.contains("Medicinali")){
let detra = matches(for: "[-+]?[0-9]*\\.?[0-9]+", in: index )
let detrafinale = detra.joined()
print("questo è il totale rilevato : \(detra) ")
formTotale.text = detrafinale
}
}
}
func setCf (testo:[String]){
let cf = testo
print(cf)
let joined = cf.joined(separator: " ")
formCF.text = joined
}
func setData(testo:[String]) {
let data = testo
let array = data
let joined = array.joined(separator: " ")
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yy"
//formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(abbreviation: "GMT+0:00")
if let startDate = formatter.date(from: joined) {
//print(startDate)
datePicker.date = startDate
}
}
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: text,
range: NSRange(text.startIndex..., in: text))
return results.map {
String(text[Range($0.range, in: text)!])
}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
func showToast(message : String) {
let toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2-self.view.frame.size.width/4, y: self.view.frame.size.height-210, width: 200, height: 35))
toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
toastLabel.textColor = UIColor.white
// toastLabel.font = font
toastLabel.textAlignment = .center;
toastLabel.text = message
toastLabel.alpha = 1.0
toastLabel.layer.cornerRadius = 10;
toastLabel.clipsToBounds = true
self.view.addSubview(toastLabel)
UIView.animate(withDuration: 4.0, delay: 0.1, options: .curveEaseOut, animations: {
toastLabel.alpha = 0.0
}, completion: {(isCompleted) in
toastLabel.removeFromSuperview()
})
}
func resetView(){
self.formCF.text = nil
self.formTotale.text = nil
self.formDetraibile.text = nil
let yourImage: UIImage = UIImage(named: "bill")!
self.imageView.image = yourImage
self.datePicker.date = Date()
}
func strHash(_ str: String) -> UInt64 {
var result = UInt64 (5381)
let buf = [UInt8](str.utf8)
for b in buf {
result = 127 * (result & 0x00ffffffffffffff) + UInt64(b)
}
return result
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}
|
//
// CalendarWithSimpleEvent.swift
// TelerikUIExamplesInSwift
//
// Copyright © 2016 Telerik. All rights reserved.
//
// >> getting-started-example-swift
import Foundation
// >> getting-started-datasource-swift
class CalendarDocsWithSimpleEvent: TKExamplesExampleViewController, TKCalendarDataSource, TKCalendarDelegate {
// << getting-started-datasource-swift
let calendarView = TKCalendar();
var events = NSMutableArray();
override func viewDidLoad() {
super.viewDidLoad()
// >> getting-started-calendar-swift
let calendarView = TKCalendar(frame: self.view.bounds)
calendarView.autoresizingMask = UIViewAutoresizing(rawValue:UIViewAutoresizing.FlexibleWidth.rawValue | UIViewAutoresizing.FlexibleHeight.rawValue)
self.view.addSubview(calendarView)
// << getting-started-calendar-swift
calendarView.delegate = self
// >> getting-started-assigndatasource-swift
calendarView.dataSource = self
// << getting-started-assigndatasource-swift
// >> getting-started-minmaxdate-swift
calendarView.minDate = TKCalendar.dateWithYear(2010, month: 1, day: 1, withCalendar: nil)
calendarView.maxDate = TKCalendar.dateWithYear(2016, month: 12, day: 31, withCalendar: nil)
// << getting-started-minmaxdate-swift
// >> getting-started-event-swift
let array = NSMutableArray();
let calendar = NSCalendar.currentCalendar()
let date = NSDate()
for _ in 0..<3 {
let event = TKCalendarEvent()
event.title = "Sample event"
let components = self.calendarView.calendar.components(NSCalendarUnit(rawValue:NSCalendarUnit.Year.rawValue | NSCalendarUnit.Month.rawValue | NSCalendarUnit.Day.rawValue), fromDate: date)
components.day = Int(arc4random() % 50)
event.startDate = calendar.dateFromComponents(components)!
event.endDate = calendar.dateFromComponents(components)!
event.eventColor = UIColor.redColor()
self.events.addObject(event)
}
self.events = array;
// << getting-started-event-swift
// >> getting-started-navigatetodate-swift
let components = NSDateComponents()
components.year = 2016
components.month = 6
components.day = 1
let newDate = self.calendarView.calendar.dateFromComponents(components)
// >> navigation-navigate-swift
calendarView.navigateToDate(newDate!, animated: false)
// << navigation-navigate-swift
// << getting-started-navigatetodate-swift
self.calendarView.reloadData();
}
// >> getting-started-eventsfordate-swift
func calendar(calendar: TKCalendar, eventsForDate date: NSDate) -> [AnyObject]? {
let components = self.calendarView.calendar.components(NSCalendarUnit(rawValue:NSCalendarUnit.Year.rawValue | NSCalendarUnit.Month.rawValue | NSCalendarUnit.Day.rawValue), fromDate: date)
components.hour = 23
components.minute = 59
components.second = 59
let endDate = self.calendarView.calendar.dateFromComponents(components)
let predicate = NSPredicate(format: "(startDate <= %@) AND (endDate >= %@)", endDate!, date)
return self.events.filteredArrayUsingPredicate(predicate)
}
// << getting-started-eventsfordate-swift
// >> getting-started-didselectdate-swift
func calendar(calendar: TKCalendar, didSelectDate date: NSDate) {
NSLog("%@", date)
}
// << getting-started-didselectdate-swift
}
// << getting-started-example-swift
|
//
// AuthorizationService.swift
// Swift-Base
//
// Created by Анастасия Леонтьева on 20/05/2021.
// Copyright © 2021 Flatstack. All rights reserved.
//
import Foundation
import Combine
@available(iOS 13.0, *)
protocol AuthorizationService {
// MARK: - Instance Methods
func refreshToken() -> AnyPublisher<String, Error>?
func signOut()
}
|
//
// ZQCryptoSwiftController.swift
// ZQOpenTools
//
// Created by Darren on 2020/6/23.
// Copyright © 2020 Darren. All rights reserved.
//
import UIKit
/// CryptoSwift 控制器
class ZQCryptoSwiftController: ZQBaseController {
override func viewDidLoad() {
super.viewDidLoad()
// Data from bytes:
let data = Data([0x01, 0x02, 0x03])
print("--__--|| data__\(data)") // 3 bytes
// Data to Array<UInt8>
let bytes = data.bytes
print("--__--|| bytes__\(bytes)") // [1,2,3]
// Hexadecimal encoding
let bytes1 = Array<UInt8>(hex: "0x010203")
print("--__--|| bytes1__\(bytes1)") // [1,2,3]
let hex = bytes1.toHexString()
print("--__--|| hex__\(hex)") // "010203"
// Build bytes out of String
let bytes2:Array<UInt8> = "cipherkey".bytes
print("--__--|| bytes2__\(bytes2)") // [99, 105, 112, 104, 101, 114, 107, 101, 121]
// base64
let base64Str = "ZQCryptoSwiftController".bytes.toBase64()
print("--__--|| base64Str__\(base64Str)") // "WlFDcnlwdG9Td2lmdENvbnRyb2xsZXI="
// Hash struct usage
let bytes3:Array<UInt8> = [0x01, 0x02, 0x03]
print("--__--|| bytes3__\(bytes3)") // [1, 2, 3]
let digest = "ZQCryptoSwiftController".md5()
print("--__--|| digest__\(digest)") // 2718e864b903946141daf1a3b7457263
let digest1 = Digest.md5(bytes3)
print("--__--|| digest1__\(digest1)") // [82, 137, 223, 115, 125, 245, 115, 38, 252, 221, 34, 89, 122, 251, 31, 172]
let hash = data.md5()
print("--__--|| hash__\(hash)") // 16 bytes
let hash1 = data.sha1()
print("--__--|| hash1__\(hash1)") // 20 bytes
let hash2 = data.sha224()
print("--__--|| hash2__\(hash2)") // 28 bytes
let hash3 = data.sha256()
print("--__--|| hash3__\(hash3)") // 32 bytes
let hash4 = data.sha384()
print("--__--|| hash4__\(hash4)") // 48 bytes
let hash5 = data.sha512()
print("--__--|| hash5__\(hash5)") // 64 bytes
do {
var digest = MD5()
let partial1 = try digest.update(withBytes: [0x31, 0x32])
print("--__--|| partial1__\(partial1)") // [1, 35, 69, 103, 137, 171, 205, 239, 254, 220, 186, 152, 118, 84, 50, 16]
let partial2 = try digest.update(withBytes: [0x33])
print("--__--|| partial2__\(partial2)") // [1, 35, 69, 103, 137, 171, 205, 239, 254, 220, 186, 152, 118, 84, 50, 16]
let result = try digest.finish()
print("--__--|| result__\(result)") // [32, 44, 185, 98, 172, 89, 7, 91, 150, 75, 7, 21, 45, 35, 75, 112]
}
catch {}
/// 其他情况看 https://github.com/krzyzanowskim/CryptoSwift
}
}
|
//
// Constants.swift
// store inventory
//
// Created by Jad Rawda on 3/14/19.
// Copyright © 2019 Rawda. All rights reserved.
//
import Foundation
class Constants {
let address = "http://192.168.1.108:3000"
}
|
import Foundation
struct Tournament: Identifiable{
var id: String
var organizerId: String
var name: String
var mode: Mode
var openDate: String
var closeDate: String
var location: String
var ratingType: RatingType
var tours: Int
var participantsCount: Int = 0
//var timeControl: String
var minutes: Int
var seconds: Int
var increment: Int
var prizeFund: Int
var fee: Int
var url: URL
// TODO: class Date - DateFormatter!
// TODO: class Location
init(id: String = "0", organizerId: String = "", name: String = "Some event", mode: Mode = .classic, openDate: String = "01.01.1970",
closeDate: String = "01.01.1970", location: String = "Moscow", ratingType: RatingType = .without,
tours: Int = 9, minutes: Int = 1, seconds: Int = 0, increment: Int = 0,
prizeFund: Int = 0, fee: Int = 0, url: URL = URL(string: "https://vk.com/oobermensch")!) {
self.id = id
self.organizerId = organizerId
self.name = name
self.mode = mode
self.openDate = openDate
self.closeDate = closeDate
self.location = location
self.ratingType = ratingType
self.tours = tours
self.minutes = minutes
self.seconds = seconds
self.increment = increment
self.prizeFund = prizeFund
self.fee = fee
self.url = url
}
}
enum Mode: String, Codable, CaseIterable{
case classic = "Классика", rapid = "Рапид", blitz = "Блиц", bullet = "Пуля", fide = "Классика FIDE", chess960 = "Шахматы 960"
}
enum RatingType: String, Codable, CaseIterable{
case fide = "FIDE", russian = "ФШР", without = "Без обсчёта"
}
|
//
// SaveableKey.swift
// Spearmint
//
// Created by Brian Ishii on 6/27/19.
// Copyright © 2019 Brian Ishii. All rights reserved.
//
import Foundation
public protocol SaveableKey: Codable, Hashable {
}
extension SaveableKey {
}
|
import UIKit
/**
Alert presenter.
*/
class Alert {
/**
Present alert on ViewController.
- parameters:
- vc: ViewController for presenting.
- message: Alert message.
*/
static func presentErrorAlert(on viewController: UIViewController, message: String) {
let title = Localization.localize(key: "error")
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: Localization.localize(key: "button.ok"), style: .cancel, handler: nil))
viewController.present(alert, animated: true)
}
}
|
//
// FundTableViewCell.swift
// Investimentos
//
// Created by Lipe glautier on 10/04/21.
//
import UIKit
class FundTableViewCell: UITableViewCell {
@IBOutlet weak var view: UIView!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var fundRiskProfileName: UILabel!
@IBOutlet weak var mininalApplication: UILabel!
func setup (fund: Fund) {
self.title.text = fund.simpleName
self.fundRiskProfileName.text = fund.specification.fundSuitabilityProfile.name
self.mininalApplication.text = "R$ \(fund.operability.minimumInitialApplicationAmount)"
self.view.layer.cornerRadius = 8.0
}
}
|
//
// ViewController.swift
// PutItOnMyTabBar
//
// Created by jnwagstaff on 08/18/2017.
// Copyright (c) 2017 jnwagstaff. All rights reserved.
//
import UIKit
import PutItOnMyTabBar
class NormalTabBarController : PutItOnMyTabBarController {
override func viewDidLoad() {
super.viewDidLoad()
//Home Tab
let home = HomeViewController()
let homeNav = UINavigationController()
homeNav.viewControllers = [home]
//Excursion Tab
let excursion = ExcursionViewController()
let excursionNav = UINavigationController()
excursionNav.viewControllers = [excursion]
//Record Tab
let record = RecordViewController()
let recordNav = UINavigationController()
recordNav.viewControllers = [record]
//Map Tab
let map = MapViewController()
let mapNav = UINavigationController()
mapNav.viewControllers = [map]
//Tackle Tab
let tackle = TackleViewController()
let tackleNav = UINavigationController()
tackleNav.viewControllers = [tackle]
viewControllers = [homeNav, excursionNav, recordNav, mapNav, tackleNav]
}
// MARK: Overrides for PutItOnMyTabBar
override func numberOfTabs() -> Int {
return 5
}
override func highLightedImages() -> [UIImage] {
return [#imageLiteral(resourceName: "homeSelected"), #imageLiteral(resourceName: "excursionSelected"), #imageLiteral(resourceName: "recordSelected"), #imageLiteral(resourceName: "mapSelected"), #imageLiteral(resourceName: "tackleSelected")]
}
override func unHighlightedImages() -> [UIImage] {
return [#imageLiteral(resourceName: "home"), #imageLiteral(resourceName: "excursion"), #imageLiteral(resourceName: "record"), #imageLiteral(resourceName: "map"), #imageLiteral(resourceName: "tackle")]
}
}
|
//
// DetailRecipeViewCell.swift
// HayChef
//
// Created by sebastian on 13/01/17.
// Copyright © 2017 nhvm. All rights reserved.
//
import UIKit
class DetailRecipeViewCell: UITableViewCell {
@IBOutlet var valueLabel: UILabel!
//Variables
@IBOutlet var keyLabel: UILabel!
}
|
//
// Created by Florian Maffini on 12.04.20.
//
import Foundation
public enum APIError: Error {
case clientError(HTTPURLResponse?)
case serverError(HTTPURLResponse?)
case redirection(HTTPURLResponse?)
case invalidEndpoint
case invalidResponse(URLResponse?)
case unsupported(Error)
case noResponse
case noData(HTTPURLResponse?)
case decodeError(HTTPURLResponse?)
case encodeError
}
|
//
// RootContract.swift
// iOSPHAssetDemoApp
//
// Created by Yuki Okudera on 2020/02/05.
// Copyright © 2020 Yuki Okudera. All rights reserved.
//
import Foundation
import Photos
// MARK: - View
/// From presenter
protocol RootView: class {
var presenter: RootViewPresentation! { get }
func showAlert(title: String, message: String)
}
// MARK: - Presenter
/// From view
protocol RootViewPresentation {
init(view: RootView, wireframe: RootWireframe, usecase: RootUsecase)
func requestPhotosFetching()
func requestVideosFetching()
}
/// From interactor
protocol RootInteractorDelegate: class {
func repliedAuthorizationStatus(status: PHAuthorizationStatus)
func fetchedImageURLs(imageFileURLs: [URL])
func fetchedVideoURLs(videoFileURLs: [URL])
}
// MARK: - Interactor
/// From presenter
protocol RootUsecase {
var output: RootInteractorDelegate? { get }
func requestPhotoLibraryAuthorization()
func fetchPhotos()
func fetchVideos()
}
// MARK: - Router
/// From presenter
protocol RootWireframe {
func showRootScreen()
}
|
//
// AVPlayer+Rx.swift
// PokeData
//
// Created by jikichi on 2021/04/02.
//
import Foundation
import RxSwift
import AVKit
extension Reactive where Base: AVPlayer {
var status: Observable<AVPlayer.Status> {
return observe(AVPlayer.Status.self, #keyPath(AVPlayer.status))
.map { $0 ?? .unknown }
}
}
|
//
// HomeTabCoordinator.swift
// Cinephile
//
// Created by Muhammad Fahied on 5/4/19.
// Copyright © 2019 Spider. All rights reserved.
//
import XCoordinator
enum HomeRoute: Route {
case movies
case favorites
}
class HomeTabCoordinator: TabBarCoordinator<HomeRoute> {
// MARK: - Stored properties
private let SearchResultRouter: AnyRouter<SearchResultRoute>
private let favoritesRouter: AnyRouter<FavoritesRoute>
// MARK: - Init
convenience init() {
let searchResultCoordinator = SearchResultCoordinator()
searchResultCoordinator.rootViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .search, tag: 0)
let favoritesCoordinator = FavoritesCoordinator()
favoritesCoordinator.rootViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .favorites, tag: 1)
self.init(SearchResultRouter: searchResultCoordinator.anyRouter,
favoritesRouter: favoritesCoordinator.anyRouter)
}
init(SearchResultRouter: AnyRouter<SearchResultRoute>,
favoritesRouter: AnyRouter<FavoritesRoute>) {
self.SearchResultRouter = SearchResultRouter
self.favoritesRouter = favoritesRouter
super.init(tabs: [SearchResultRouter, favoritesRouter], select: SearchResultRouter)
}
// MARK: - Overrides
override func prepareTransition(for route: HomeRoute) -> TabBarTransition {
switch route {
case .movies:
return .select(SearchResultRouter)
case .favorites:
return .select(favoritesRouter)
}
}
}
|
//
// DataManager.swift
// TableViewHW
//
// Created by User on 04.11.2020.
// Copyright © 2020 Evgeny. All rights reserved.
//
import Foundation
struct DataManager {
static let names = ["John", "Aaron", "Tim", "Ted", "Steven", "Ivan",
"Bruce", "Allan", "Carl", "Nicola", "Sharon", "Lev"]
static let surnames = ["Smith", "Dow", "Isaacson", "Pennyworth",
"Jankins", "Po", "White", "Williams",
"Roberts", "Cook", "Gibson", "Tavares"]
static let phoneNumbers = ["7465543", "7452311", "7342349", "7009322",
"9832422", "6723423", "7123121", "7405390",
"1273444", "7213991", "7281593", "7334231"]
static let emails = ["John@mail.com", "First@avatar.com", "Dom@gmail.com",
"Home@tb.com", "Mymail@ya.com", "Mailll@mail.com",
"Secret@ya.com", "Hosdfs@mail.com", "Still@swift.com",
"Adam24@mail.com", "Pochta@ya.com", "Mewmew@mail.com"]
static func getRandomPersons() -> [Person] {
let names = self.names.shuffled()
let surnames = self.surnames.shuffled()
let phoneNumbers = self.phoneNumbers.shuffled()
let emails = self.emails.shuffled()
var result = [Person]()
for index in 0...names.count - 1 {
result.append(Person(name: names[index],
surname: surnames[index],
phoneNumber: phoneNumbers[index],
email: emails[index]))
}
return result
}
}
|
//
// Helpers.swift
// CoffeeNerd
//
// Created by Baptiste Leguey on 14/11/2017.
// Copyright © 2017 Baptiste Leguey. All rights reserved.
//
import Foundation
// MARK: - ClassNameable protocol
/**
* Protocol and extension implementing a ClassName static variable to retrieve easily a string from a class' name.
*/
public protocol ClassNameable {
static var ClassName: String { get }
}
extension ClassNameable {
public static var ClassName: String {
return String(describing: self)
}
}
|
import HopotPackage
open class HotpotPackageTest {
public init() {}
open func test() {
print("HotpotPackageTest test function");
HotpotPackage().test()
}
}
|
import UIKit
// MARK: Using closures as parameters when they return values
func travelThree(action: (String) -> String) {
print("I'm getting ready to go.")
let desc = action("Japan")
print(desc)
print("I'm arrived!")
}
travelThree { (place: String) -> String in
return "I'm going to \(place) in my car"
}
// MARK: Shorthand parameter names
func travelFour(action: (String) -> String) {
print("I'm getting ready to go.")
let desc = action("London")
print(desc)
print("I'm arrived!")
}
travelFour {
"I'm going to \($0) in my car.."
}
// MARK: Closures with multiple parameters
func travel(action: (String, Int) -> String) {
print("I'm getting ready to go.")
let desc = action("US", 70)
print(desc)
print("I'm arrived!")
}
travel {
"I'm going to \($0) at \($1) miles per hour"
}
// MARK: Returning closures from functions
func travelWithReturningClosure() -> (String) -> Void {
return {
print("I'm going to \($0)")
}
}
travelWithReturningClosure()("London")
// MARK: Capturing values
func travelCapturingValues() -> (String) -> Void {
var counter = 1
return {
print("\(counter). I'm going to \($0)")
counter += 1
}
}
let result = travelCapturingValues()
result("London")
result("London")
result("London")
// MARK: Test
func fix(item: String, payBill: (Int) -> Void) {
print("I've fixed your \(item)")
payBill(450)
}
fix(item: "roof") { (bill: Int) in
print("You want $\(bill) for that? Outrageous!")
}
|
//
// RouteDao.swift
// GiftManager
//
// Created by David Johnson on 12/8/17.
// Copyright © 2017 David Johnson. All rights reserved.
//
import Foundation
import CoreData
/// DAO pattern class for the route table.
class RouteDao : BaseDao {
/// Get an array of route objects from the table
///
/// - Returns: an array of route objects
func list() -> [Route]? {
var results: [Route]?
do {
let request: NSFetchRequest<Route> = Route.fetchRequest()
let sortDescriptor = NSSortDescriptor(key: "routenumber", ascending: true)
request.sortDescriptors = [sortDescriptor]
request.returnsObjectsAsFaults = false
try results = manageObjectContext?.fetch(request)
} catch let error as NSError {
NSLog("Unresolved error in fetch \(error), \(error.userInfo)")
}
return results
}
/// Get a route from it's number.
///
/// - Parameter routeNumber: the route number to query on
/// - Returns: the route found by the query
func getRoute(routeNumber:String) -> Route? {
var result:Route?
for route:Route in self.list()!
{
if route.routenumber == routeNumber
{
result = route
}
}
return result
}
/// Create a new route with the parameters.
///
/// - Parameters:
/// - routeNumber: the number of the route
/// - street: the street on the route
/// - Returns: the new route record object
func create(routeNumber: String, street:String) -> Route? {
do {
let route = NSEntityDescription.insertNewObject(forEntityName: "Route", into: self.manageObjectContext!) as! Route
route.routenumber = routeNumber
route.street = street
try route.managedObjectContext?.save()
return route
} catch let error as NSError {
NSLog("Unresolved error in adding \(error), \(error.userInfo)")
}
return nil
}
/// Update the selected route record.
///
/// - Parameter route: the route to update
func update(route:Route) {
do {
try route.managedObjectContext?.save()
} catch let error as NSError {
NSLog("Unresolved error in updating \(error), \(error.userInfo)")
}
}
/// Delete the selected route from the route table.
///
/// - Parameter route: the route to delete
func delete(route:Route) {
do {
self.manageObjectContext?.delete(route)
try self.manageObjectContext?.save()
} catch let error as NSError {
NSLog("Unresolved error in deleting \(error), \(error.userInfo)")
}
}
/// Deletes all records from the route table.
func deleteAll() {
if let objs = self.list() {
for obj:Route in objs {
delete(route: obj)
}
}
}
}
|
//
// Recipe.swift
// FoodFriend
//
// Created by Tim Davis on 10/7/15.
// Copyright © 2015 TimDavis. All rights reserved.
//
import Foundation
import Alamofire
class Recipe
{
fileprivate var _id: String!
fileprivate var _name: String!
fileprivate var _ingredients: [String]!
fileprivate var _fullIngredients: [String]!
fileprivate var _flavors: Dictionary<String, Float>!
fileprivate var _source: Dictionary<String, String>!
fileprivate var _numOfServings: Int!
fileprivate var _totalTime: String!
init(id: String, name: String, ingredients: [String])
{
_id = id
_name = name
_ingredients = ingredients
}
var id: String{
return _id
}
var name: String{
return _name
}
var ingredients: [String]{
return _ingredients
}
var fullIngredients: [String]{
return _fullIngredients
}
var flavors: Dictionary<String, Float>{
return _flavors
}
var source: Dictionary<String, String>{
return _source
}
var numOfServings: Int {
return _numOfServings
}
var totalTime: String {
return _totalTime
}
func toString() -> String{
return "\(_name)\n\(_id)\n\(_fullIngredients)\n\(_flavors)\n\(_source)\n\(_totalTime)\n\(_numOfServings)"
}
func downloadRecipeDetails(_ completed: @escaping DownloadComplete)
{
let urlString = "\(RECIPE_URL_BEGIN)\(_id)\(RECIPE_URL_END)"
let url = (NSURL(scheme: "https", host: "api.yummly.com", path: urlString) as? URL)!
print(url)
Alamofire.request(.GET, url).responseJSON { (request: URLRequest?, response: HTTPURLResponse?, result: Result<AnyObject>) -> Void in
if let dict = result.value as? Dictionary<String, AnyObject> {
if let totalTime = dict["totalTime"] as? String{
self._totalTime = totalTime
}
if let numOfServings = dict["numberOfServings"] as? Int {
self._numOfServings = numOfServings
}
if let fullIngredients = dict["ingredientLines"] as? [String] {
self._fullIngredients = fullIngredients
}
if let source = dict["source"] as? Dictionary<String, String> {
self._source = source
}
if let flavors = dict["flavors"] as? Dictionary<String, Float> {
self._flavors = flavors
}
completed()
}
}
}
}
|
//
// ContactsViewModelTests.swift
// ContactsTests
//
// Created by Anudeep Gone on 19/10/21.
//
import XCTest
@testable import Contacts
class ContactsViewModelTests: XCTestCase {
var sut: ContactsViewModel!
var mockAPIService: MockAPIService!
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
mockAPIService = MockAPIService()
sut = ContactsViewModel(apiService: mockAPIService)
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
sut = nil
mockAPIService = nil
}
func testinitFetchContacts() throws {
sut.initFetchContacts()
XCTAssertFalse(false)
}
func testNumberOfSections() throws {
sut.initFetchContacts()
XCTAssertTrue(sut.numberOfSections == 27)
}
func testNumberOfRows() throws {
sut.initFetchContacts()
//number of rows for A section
XCTAssert(sut.numberOfRows(in: 0) == 0)
//number of rows for C section
XCTAssert(sut.numberOfRows(in: 2) == 1)
}
func testGetTitleForHeader() throws {
sut.initFetchContacts()
XCTAssert(sut.getTitleForHeader(in: 2) == "C")
}
func testGetContact() throws {
sut.initFetchContacts()
XCTAssertNotNil(sut.getContact(at: IndexPath(row: 0, section: 2)))
}
func testUpdateLoadingStatus() {
let expect = XCTestExpectation(description: "Loading status updated")
sut.updateLoadingStatus = {
expect.fulfill()
}
sut.initFetchContacts()
wait(for: [expect], timeout: 1.0)
}
}
|
//
// HTTPCache.swift
// BookRead
//
// Created by fox on 2017/6/20.
// Copyright © 2017年 DZM. All rights reserved.
//
import UIKit
import ObjectMapper
class HTTPCache: CacheManager {
static func store<T: Mappable>(_ obj: T?, forKey key: String) {
if let jsonString = obj?.toJSONString() {
CacheManager.xwj_setObject(object: jsonString as NSCoding, forKey: key)
}
}
static func objectModel<T: Mappable>(jsonString: String) -> T? {
// string -> data -> json -> map -> response
let jsonData = jsonString.data(using: .utf8)
let jsonObj = try? JSONSerialization.jsonObject(with: jsonData!, options: [])
let json = jsonObj as? [String: Any]
let map = Map.init(mappingType: .fromJSON, JSON: json!)
let response = T.init(map: map)
return response
}
static func object<T: Mappable>(class: T.Type, forKey key: String) -> T? {
// string -> data -> json -> map -> response
if let jsonString = CacheManager.xwj_objectForKey(forkey: key) as? String,
let jsonData = jsonString.data(using: .utf8),
let jsonObj = try? JSONSerialization.jsonObject(with: jsonData, options: []),
let json = jsonObj as? [String: Any] {
let map = Map.init(mappingType: .fromJSON, JSON: json)
let response = T.init(map: map)
return response
} else {
return nil
}
}
}
|
//
// MovieDetailViewModel.swift
// BoxOffice_SwiftUI
//
// Created by Presto on 2019/10/16.
// Copyright © 2019 presto. All rights reserved.
//
import Combine
import Foundation
final class MovieDetailViewModel: ObservableObject, NetworkImageFetchable {
private enum RequestType {
case movie
case comments
}
private let apiService: MovieAPIServiceProtocol
private var cancellables = Set<AnyCancellable>()
init(movieID: String, apiService: MovieAPIServiceProtocol = MovieAPIService()) {
self.apiService = apiService
isPresentedSubject
.compactMap { $0 }
.sink(receiveValue: { [weak self] _ in
self?.requestData()
})
.store(in: &cancellables)
isLoadingSubject
.compactMap { $0 }
.map { $0 || $1 }
.assign(to: \.isLoading, on: self)
.store(in: &cancellables)
showsCommentPostingSubject
.compactMap { $0 }
.assign(to: \.showsCommentPosting, on: self)
.store(in: &cancellables)
let movieSharedPublisher = movieSubject
.compactMap { $0 }
.compactMap { try? $0.get() }
.share()
movieSharedPublisher
.sink(receiveCompletion: { [weak self] completion in
self?.movieErrors.append(.movieDetailRequestFailed)
}, receiveValue: { [weak self] movieResponse in
self?.movie = movieResponse
})
.store(in: &cancellables)
movieSharedPublisher
.map(\.imageURLString)
.flatMap(networkImageData(from:))
.assign(to: \.posterImageData, on: self)
.store(in: &cancellables)
movieSharedPublisher
.map(\.title)
.assign(to: \.title, on: self)
.store(in: &cancellables)
movieSharedPublisher
.map(\.grade)
.compactMap(Grade.init)
.map(\.imageName)
.assign(to: \.gradeImageName, on: self)
.store(in: &cancellables)
movieSharedPublisher
.map(\.date)
.map { "\($0) 개봉" }
.assign(to: \.date, on: self)
.store(in: &cancellables)
movieSharedPublisher
.map { ($0.genre, $0.duration) }
.map { "\($0) / \($1)분" }
.assign(to: \.genreAndDuration, on: self)
.store(in: &cancellables)
movieSharedPublisher
.map { ($0.reservationGrade, $0.reservationRate) }
.map { "\($0)위 \(String(format: "%.1f%%", $1))" }
.assign(to: \.reservationMetric, on: self)
.store(in: &cancellables)
movieSharedPublisher
.map(\.userRating)
.assign(to: \.userRating, on: self)
.store(in: &cancellables)
movieSharedPublisher
.map(\.userRating)
.map { String(format: "%.2f", $0) }
.assign(to: \.userRatingDescription, on: self)
.store(in: &cancellables)
movieSharedPublisher
.map(\.audience)
.compactMap { NumberFormatter.decimal.string(from: $0 as NSNumber) }
.assign(to: \.audience, on: self)
.store(in: &cancellables)
movieSharedPublisher
.map(\.synopsis)
.assign(to: \.synopsis, on: self)
.store(in: &cancellables)
movieSharedPublisher
.map(\.director)
.assign(to: \.director, on: self)
.store(in: &cancellables)
movieSharedPublisher
.map(\.actor)
.assign(to: \.actor, on: self)
.store(in: &cancellables)
commentsSubject
.compactMap { $0 }
.tryMap { try $0.get() }
.sink(receiveCompletion: { [weak self] completion in
if case .failure = completion {
self?.movieErrors.append(.commentsRequestFailed)
}
}, receiveValue: { [weak self] comments in
self?.comments = comments
})
.store(in: &cancellables)
movieIDSubject.send(movieID)
}
// MARK: - Inputs
func setPresented() {
isPresentedSubject.send(Void())
}
func setShowsCommentPosting() {
showsCommentPostingSubject.send(true)
}
func requestData() {
setLoading(true, to: .movie)
setLoading(true, to: .comments)
movieErrors = []
movieIDSubject
.compactMap { $0 }
.first()
.flatMap(apiService.requestMovieDetail(movieID:))
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: { [weak self] completion in
if case let .failure(error) = completion {
self?.movieSubject.send(.failure(error))
}
self?.setLoading(false, to: .movie)
}, receiveValue: { [weak self] movieResponse in
self?.movieSubject.send(.success(movieResponse))
})
.store(in: &cancellables)
movieIDSubject
.compactMap { $0 }
.first()
.flatMap(apiService.requestComments(movieID:))
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: { [weak self] completion in
if case let .failure(error) = completion {
self?.commentsSubject.send(.failure(error))
}
self?.setLoading(false, to: .comments)
}, receiveValue: { [weak self] commentsResponse in
self?.commentsSubject.send(.success(commentsResponse.comments))
})
.store(in: &cancellables)
}
// MARK: - Outputs
@Published var isLoading = false
@Published var showsCommentPosting = false
@Published var movie: MovieDetailResponseModel = .dummy
@Published var comments: [CommentsResponseModel.Comment] = []
@Published var posterImageData: Data?
@Published var movieErrors: [MovieError] = []
@Published var title: String = ""
@Published var gradeImageName: String = ""
@Published var date: String = ""
@Published var genreAndDuration: String = ""
@Published var reservationMetric: String = ""
@Published var userRating: Double = 0
@Published var userRatingDescription: String = ""
@Published var audience: String = ""
@Published var synopsis: String = ""
@Published var director: String = ""
@Published var actor: String = ""
// MARK: - Subjects
private let isPresentedSubject = CurrentValueSubject<Void?, Never>(nil)
private let isLoadingSubject = CurrentValueSubject<(Bool, Bool)?, Never>(nil)
private let showsCommentPostingSubject = CurrentValueSubject<Bool?, Never>(nil)
private let movieIDSubject = CurrentValueSubject<String?, Never>(nil)
private let movieSubject = CurrentValueSubject<Result<MovieDetailResponseModel, Error>?, Never>(nil)
private let commentsSubject = CurrentValueSubject<Result<[CommentsResponseModel.Comment], Error>?, Never>(nil)
}
// MARK: - Private Method
extension MovieDetailViewModel {
private func setLoading(_ loading: Bool, to type: MovieDetailViewModel.RequestType) {
var currentLoading = isLoadingSubject.value ?? (false, false)
switch type {
case .movie:
currentLoading.0 = loading
case .comments:
currentLoading.1 = loading
}
isLoadingSubject.send(currentLoading)
}
}
extension MovieDetailViewModel {
func commentDateString(timestamp: Double) -> String {
let formatter = DateFormatter.custom("yyyy-MM-dd HH:mm:ss")
return formatter.string(from: Date(timeIntervalSince1970: timestamp))
}
}
|
//
// Copyright © 2020 Tasuku Tozawa. All rights reserved.
//
import Combine
/// @mockable
public protocol TagQuery {
var tag: CurrentValueSubject<Tag, Error> { get }
}
|
//
// CTTTextNode.swift
// EFI
//
// Created by LUIS ENRIQUE MEDINA GALVAN on 7/24/18.
// Copyright © 2018 LUIS ENRIQUE MEDINA GALVAN. All rights reserved.
//
import AsyncDisplayKit
class CTTTextNode:ASTextNode {
fileprivate var _fontSize:Float!
fileprivate var _color:UIColor!
fileprivate var _text:String!
init(withFontSize:Float,color:UIColor,with text:String) {
super.init()
isLayerBacked = true
cornerRadius = 5
// style.flexGrow = 1
_fontSize = withFontSize
_color = color
_text = text
attributedText = NSAttributedString(string: _text, attributes: [NSAttributedStringKey.foregroundColor:_color,NSAttributedStringKey.font:UIFont.boldSystemFont(ofSize: CGFloat(_fontSize!))])
}
func changeText(text:String ){
attributedText = NSAttributedString(string: text, attributes: [NSAttributedStringKey.foregroundColor:_color,NSAttributedStringKey.font:UIFont.boldSystemFont(ofSize: CGFloat(_fontSize!))])
}
}
|
//
// LabelDatePicker.swift
// APSoft
//
// Created by Yesid Melo on 4/25/19.
// Copyright © 2019 Exsis. All rights reserved.
//
import UIKit
class LabelDatePicker: UIView {
@IBOutlet var ContainerView: UIView!
@IBOutlet weak var LabelDate: UILabel!
@IBOutlet weak var ImageViewArrow: UIImageView!
var delegate : ((Date)->Void)!
var dateDefault : Date!{
didSet{
loadDateDefault()
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
preload()
}
private func preload(){
registerXib()
addInParent()
addListener()
}
private func registerXib(){
Bundle.main.loadNibNamed("LabelDatePicker", owner: self, options: nil)
}
private func addInParent(){
ContainerView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
self.addSubview(ContainerView)
}
private func addListener(){
enableInteractionUser()
addGestures()
}
private func enableInteractionUser(){
LabelDate.isUserInteractionEnabled = true
ImageViewArrow.isUserInteractionEnabled = true
ContainerView.isUserInteractionEnabled = true
}
private func addGestures(){
let gestureLabelDate = UITapGestureRecognizer(target: self, action: #selector(listenLabelDate))
let gestureImageViewArrow = UITapGestureRecognizer(target: self, action: #selector(listenImageViewArrow))
LabelDate.addGestureRecognizer(gestureLabelDate)
ImageViewArrow.addGestureRecognizer(gestureImageViewArrow)
}
@objc func listenLabelDate(){
if !iCanSendDateToDelegate() { return }
updateLabelDate()
//showDatePickerGeneric()
}
private func updateLabelDate(){
let myDate = Date()
LabelDate.text = myDate.toString(withFormat: Constants.Formats.SLASH_DAY_MONTH_YEAR)
delegate(myDate)
}
private func iCanSendDateToDelegate() -> Bool{
return delegate != nil
}
private func showDatePickerGeneric(){
let datePicker = DatePickerGeneric(self)
datePicker.delegate = delegate
}
@objc func listenImageViewArrow(){
if !iCanSendDateToDelegate() { return }
updateLabelDate()
//showDatePickerGeneric()
}
private func loadDateDefault(){
if !iCanLabelWithDateDefault() { return }
LabelDate.text = dateDefault.toString(withFormat: Constants.Formats.SLASH_DAY_MONTH_YEAR)
}
private func iCanLabelWithDateDefault() -> Bool{
return dateDefault != nil
}
}
|
//
// DifferenceProtocols.swift
// koshelek_ru_testAPI_VIPER
//
// Created by maksim on 07.11.2020.
//
import Foundation
import UIKit
protocol ViewToDifferencePresenterProtocol : class{
var view : PresenterToDifferenceViewProtocol? { get set }
var router : PresenterToDifferenceRouterProtocol? { get set }
var interactor : PresenterToDifferenceInteractorProtocol? { get set }
func preparingData()
func startTimer()
func stop()
func selectQuotedCurrency(select : Int?)
}
protocol PresenterToDifferenceViewProtocol : class{
func viewDataForButton(selectArray : [String]?)
func viewData(response: DifferenceResponse?)
func viewTimer(timer : String?)
}
protocol PresenterToDifferenceRouterProtocol : class{
static func createDifferenceModule() -> DifferenceViewController
}
protocol PresenterToDifferenceInteractorProtocol : class{
var presenter : InteractorToDifferencePresenterProtocol? { get set }
func startProcessing()
func timerProcessing()
func stopProcessing()
func selectDataProcessing(select : Int?)
}
protocol InteractorToDifferencePresenterProtocol : class{
func dataForButtonTransfer(selectArray : [String]?)
func dataTransfer(response : DifferenceResponse?)
func timerTransfer(timer : String?)
}
|
//
// Copyright 2014 ESRI
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// You may freely redistribute and use this sample code, with or
// without modification, provided you include the original copyright
// notice and use restrictions.
//
// See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm
//
import UIKit
import ArcGIS
class CustomSegue: UIStoryboardSegue {
var rect:CGRect!
var view:UIView!
var popOverController:UIPopoverController!
override func perform() {
//in case of iPad present new view as pop over
if AGSDevice.currentDevice().isIPad() {
self.popOverController.presentPopoverFromRect(self.rect, inView:self.view, permittedArrowDirections:.Any, animated:true)
}
//in case of iPhone present view as a modal view
else {
self.sourceViewController.presentViewController(self.destinationViewController as UIViewController, animated:true, completion:nil)
}
}
}
|
import CoreLocation
@objc(geolocation) class geolocation : CDVPlugin {
override func pluginInitialize() {
}
// Function show status plugin
@objc(getstatus:)
func getstatus(command: CDVInvokedUrlCommand) {
var pluginResult = CDVPluginResult(
status: CDVCommandStatus_ERROR
)
let msg = command.arguments[0] as? String ?? ""
if msg.characters.count > 0 {
pluginResult = CDVPluginResult(
status: CDVCommandStatus_OK,
messageAs: msg
)
}
self.commandDelegate!.send(
pluginResult,
callbackId: command.callbackId
)
}
// Function get current location
@objc(getgeolocation:)
func getgeolocation(command: CDVInvokedUrlCommand) {
var pluginResult = CDVPluginResult(
status: CDVCommandStatus_ERROR
)
// Get current location
let locationManager = CLLocationManager()
locationManager.delegate = self as? CLLocationManagerDelegate;
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
var currentLocation: CLLocation!
currentLocation = locationManager.location
print(currentLocation.coordinate.latitude)
print(currentLocation.coordinate.longitude)
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
// Pass latitude & longitude to view
let lat = ["lat": currentLocation.coordinate.latitude] as [AnyHashable : Any]
let lng = ["lng": currentLocation.coordinate.longitude] as [AnyHashable : Any]
let array = [lat, lng]
pluginResult = CDVPluginResult(
status: CDVCommandStatus_OK,
messageAs: array
)
self.commandDelegate!.send(
pluginResult,
callbackId: command.callbackId
)
}
}
|
//
// ViewController.swift
// tvOSCopilot
//
// Created by William Rory Kronmiller on 7/6/18.
// Copyright © 2018 William Rory Kronmiller. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
import AVKit
import MultipeerConnectivity
import Charts
class TrafficCamAnnotation: NSObject, MKAnnotation {
var address: URL
var title: String?
var coordinate: CLLocationCoordinate2D
init(trafficCam: TrafficCam) {
self.address = trafficCam.address
self.title = trafficCam.name
self.coordinate = trafficCam.location.coordinate
}
}
class DarkMapController: UIViewController {
internal let baseMapOverlay: MKTileOverlay
internal let baseTileRenderer: MKTileOverlayRenderer
required init?(coder aDecoder: NSCoder) {
self.baseMapOverlay = MKTileOverlay(urlTemplate: Configuration.shared.baseMapTileUrl)
self.baseTileRenderer = MKTileOverlayRenderer(tileOverlay: self.baseMapOverlay)
baseMapOverlay.canReplaceMapContent = true
super.init(coder: aDecoder)
}
}
//TODO: annotation clustering
class ViewController: DarkMapController, MKMapViewDelegate, CLLocationManagerDelegate, MeshBaseStationDelegate {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var playerContainer: UIView!
private var meshConnection: MeshConnection? = nil
private var trackedDeviceTrace: MKPolyline? = nil
private let locationManager = CLLocationManager()
private let trafficCams = TrafficCams()
private var showingCameras: Bool = false
private var trafficCamAnnotations: [TrafficCamAnnotation] = []
private let radarMapOverlay: MKTileOverlay
private let radarTileRenderer: MKTileOverlayRenderer
private var radarLastRefreshed: Date? = nil
private var statisticsViewController: StatisticsViewController?
private let meshNetwork = MeshBaseStation()
private var statsConnection: MeshConnection?
required init?(coder aDecoder: NSCoder) {
self.radarMapOverlay = MKTileOverlay(urlTemplate: Configuration.shared.radarTileUrl)
self.radarTileRenderer = MKTileOverlayRenderer(tileOverlay: self.radarMapOverlay)
super.init(coder: aDecoder)
locationManager.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
self.statisticsViewController = storyboard?.instantiateViewController(withIdentifier: "StatisticsView") as! StatisticsViewController
locationManager.requestWhenInUseAuthorization()
mapView.delegate = self
mapView.add(baseMapOverlay, level: .aboveLabels)
mapView.add(radarMapOverlay, level: .aboveLabels)
mapView.showsUserLocation = true
mapView.showsScale = false
baseTileRenderer.reloadData()
radarTileRenderer.reloadData()
radarLastRefreshed = Date()
trafficCams.refresh(allCamerasLoaded: {error in
if error != nil {
NSLog("Error getting all traffic cameras \(error!)")
return
}
self.trafficCamAnnotations = self.trafficCams.getCameras().map({cam in
return TrafficCamAnnotation(trafficCam: cam)
})
})
meshNetwork.delegate = self
meshNetwork.startAdvertising()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKTileOverlay {
if overlay as! MKTileOverlay == self.baseMapOverlay {
return baseTileRenderer
}
return radarTileRenderer
}
if overlay is MKPolyline {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.strokeColor = UIColor.purple
renderer.lineWidth = 6
return renderer
}
return MKOverlayRenderer()
}
private func scaleImage(scale: Int, image: UIImage) -> UIImage {
let size = CGSize(width: scale, height: scale)
UIGraphicsBeginImageContext(size)
image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return resizedImage
}
private func ensureView(withIdentifier: String, annotation: MKAnnotation?) -> MKAnnotationView {
let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: withIdentifier)
if annotationView == nil {
return MKAnnotationView(annotation: annotation, reuseIdentifier: withIdentifier)
}
return annotationView!
}
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
self.maybeShowCameras()
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
NSLog("Handling annotation \(annotation)")
if annotation is MKUserLocation {
NSLog("User location annotation")
let annotationView = ensureView(withIdentifier: "userLocation", annotation: annotation)
NSLog("Ensured annotation view \(annotationView)")
annotationView.isEnabled = true
let pinImage = UIImage(named: "crosshairs")!
annotationView.image = scaleImage(scale: 50, image: pinImage)
return annotationView
}
if annotation is TrafficCamAnnotation {
let annotationView = ensureView(withIdentifier: "trafficCameras", annotation: annotation)
annotationView.image = scaleImage(scale: 30, image: UIImage(named: "camera")!)
annotationView.isEnabled = true
annotationView.canShowCallout = true
return annotationView
}
return nil
}
private var playing: URL? = nil
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
NSLog("Selected view \(view)")
if view.annotation is TrafficCamAnnotation {
let trafficAnnotation = view.annotation as! TrafficCamAnnotation
self.playing = trafficAnnotation.address
let player = AVPlayer(url: trafficAnnotation.address)
player.isMuted = true
let playerLayer = AVPlayerLayer(player: player)
DispatchQueue.main.async {
self.playerContainer.layer.sublayers?.forEach{ $0.removeFromSuperlayer() }
playerLayer.frame = self.playerContainer.bounds
self.playerContainer.layer.addSublayer(playerLayer)
player.play()
}
}
if view.annotation is MKUserLocation {
self.playing = nil
DispatchQueue.main.async {
self.playerContainer.layer.sublayers?.forEach{ $0.removeFromSuperlayer() }
}
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
NSLog("Got locations \(locations)")
if let lastLoc = locations.last {
let region = MKCoordinateRegionMakeWithDistance(lastLoc.coordinate, 1000, 1000)
mapView.setRegion(region, animated: false)
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
NSLog("Failed to get locations \(error)")
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch(status) {
case .denied:
NSLog("Denied location permissions")
break
case .notDetermined:
NSLog("Location status not determined")
break
case .authorizedWhenInUse:
NSLog("Authorized to use location")
self.locationManager.requestLocation()
break
default:
NSLog("Location status changed \(status.rawValue)")
}
}
@IBAction func longPressed(_ sender: Any) {
if let url = self.playing {
let playerController = AVPlayerViewController()
playerController.modalPresentationStyle = .fullScreen
let player = AVPlayer(url: url)
playerController.player = player
player.play()
DispatchQueue.main.async {
self.present(playerController, animated: true, completion: {
NSLog("Went fullscreen")
})
}
return
}
DispatchQueue.main.async {
var doRefresh = true
if let lastReloaded = self.radarLastRefreshed {
doRefresh = (abs(lastReloaded.timeIntervalSinceNow) > 5)
}
if doRefresh {
self.radarLastRefreshed = Date()
NSLog("Refreshing radar data")
self.radarTileRenderer.reloadData()
}
}
}
func maybeShowCameras() {
let maxZoom = 0.4
let zoomLevel = self.mapView!.region.span.latitudeDelta
NSLog("Zoom level \(zoomLevel)")
if zoomLevel > maxZoom && showingCameras {
self.showingCameras = false
self.mapView.removeAnnotations(self.trafficCamAnnotations)
NSLog("Hiding cameras")
}
if zoomLevel < maxZoom && !showingCameras && self.trafficCamAnnotations.count > 0 {
self.showingCameras = true
self.mapView.addAnnotations(self.trafficCamAnnotations)
NSLog("Showing cameras")
}
}
func connection(_ network: MeshNetwork, gotRideStatistics rideStatistics: RideStatistics, connection: MeshConnection) {
self.statsConnection = connection
NSLog("Loading stats")
DispatchQueue.main.async {
if self.statisticsViewController!.loaded == false {
NSLog("Presenting stats view")
self.present(self.statisticsViewController!, animated: true, completion: nil)
} else {
NSLog("Stats VC already loaded")
}
NSLog("Refreshing stats")
self.statisticsViewController!.refreshData(rideStatistics: rideStatistics)
}
}
func connection(_ network: MeshNetwork, didConnect connection: MeshConnection) {}
func connection(_ network: MeshNetwork, didDisconnect peerID: MCPeerID) {}
}
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
print ("Hello, World!")
print (str)
let http404error = (404, "Not Found")
let (statusCode, statusMessage) = http404error
let (justTheStatusCode, _) = http404error
print ("The status code is \(justTheStatusCode)")
print ("The status code is \(http404error.0)")
print ("The status code is \(http404error.1)")
|
//
// Constants.swift
// FundooApp
//
// Created by admin on 04/06/20.
// Copyright © 2020 admin. All rights reserved.
//
import UIKit
enum Constants {
static let TOGGLE_MENU = "TOGGLE_MENU"
static let SET_BACK_BUTTON = "SET_BACK_BUTTON"
static let UPDATE_NAV = "UPDATE_NAV"
static let SET_MENU = "SET_MENU"
static let EMAIL_KEY = "EMAIL"
static let NAVIGATE_TO_LABELS = "create labels"
static let NAVIGATE_TO_ARCHIVE = "Nav to Archive"
static let NAVIGATE_TO_TRASH = "Nav to Trash"
static let DELETE_NOTE_KEY = "delete note"
static let CLOSE_SLIDE_UP_MENU = "close slideUp"
static let ADD_LABEL_KEY = "labelKey"
static let IS_LOGGED_IN_KEY = "IS_LOGGED_IN"
static let NAVIGATE_TO_NOTE = "HOME"
static let NAVIGATE_TO_REMINDER = "REMINDER"
static let TOGGLE_GRID = "TOGGLE_GRID"
static let ADD_NOTE = "Add Note"
static let RELOAD_CELLS = "Reload cells"
static let RELOAD_LABEL_CELLS = "Reload Label cells"
static let UPDATE_COLOR = "update color"
static let OPTIONS_CELL_ID = "OptionsCell"
static let labelsHeaderTitle = " LABELS"
static let CollectionView_TabelCell_ID = "CollectionViewTabelCell"
static let COLOR_KEY = "color"
static let NOTES_TITLE = "Notes"
static let HOME_STORYBOARD = "Home"
static let FEATURES_STORYBOARD = "Features"
static let REMINDER_STORYBOARD = "Reminder"
static let MAIN_STORYBOARD = "Main"
static let EDIT_NOTE_VC = "EditNoteVC"
static let NOTE_VC = "NoteViewController"
static let UPDATE_LABEL_VC = "UpdateLabelViewController"
static let ADD_LABEL_VC = "AddLabelVC"
static let CONTAINER_VC = "ContainerViewController"
static let LABELS_VC = "labels"
static let LABELS = "labels_View"
static let REMINDER_VC = "ReminderViewController"
static let USER_NOT_FOUND = "user not found"
static let FETCH_ERROR = "fetching error"
static let DATA_ERROR = "data not found error"
static let signUpTitle = "Sign Up"
static let signInTitle = "Sign In"
static let gridImage = "rectangle.grid.2x2.fill"
static let singleColumnImage = "rectangle.grid.1x2.fill"
static let colors = ["#FFFFFF":#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1),"#83B1FC": #colorLiteral(red: 0.5137254902, green: 0.6941176471, blue: 0.9882352941, alpha: 1),
"#F3BACF":#colorLiteral(red: 0.9529411765, green: 0.7294117647, blue: 0.8117647059, alpha: 1),"#D8CDCA":#colorLiteral(red: 0.8470588235, green: 0.8039215686, blue: 0.7921568627, alpha: 1),
"#B389FD":#colorLiteral(red: 0.7019607843, green: 0.537254902, blue: 0.9921568627, alpha: 1),"#A5FAEB":#colorLiteral(red: 0.6470588235, green: 0.9803921569, blue: 0.9215686275, alpha: 1),
"#81D8FC":#colorLiteral(red: 0.5058823529, green: 0.8470588235, blue: 0.9882352941, alpha: 1),"#EE877F":#colorLiteral(red: 0.9333333333, green: 0.5294117647, blue: 0.4980392157, alpha: 1),
"#E6C9A8":#colorLiteral(red: 0.9019607843, green: 0.7882352941, blue: 0.6588235294, alpha: 1),"#FFF476":#colorLiteral(red: 1, green: 0.9568627451, blue: 0.462745098, alpha: 1),
"#C8F68A":#colorLiteral(red: 0.7843137255, green: 0.9647058824, blue: 0.5411764706, alpha: 1),"#F0B531":#colorLiteral(red: 0.9411764706, green: 0.7098039216, blue: 0.1921568627, alpha: 1),"#000000":#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
]
static let myColors = [
#colorLiteral(red: 0.5137254902, green: 0.6941176471, blue: 0.9882352941, alpha: 1),#colorLiteral(red: 0.9529411765, green: 0.7294117647, blue: 0.8117647059, alpha: 1),#colorLiteral(red: 0.8470588235, green: 0.8039215686, blue: 0.7921568627, alpha: 1),#colorLiteral(red: 0.7019607843, green: 0.537254902, blue: 0.9921568627, alpha: 1),#colorLiteral(red: 0.6470588235, green: 0.9803921569, blue: 0.9215686275, alpha: 1),#colorLiteral(red: 0.5058823529, green: 0.8470588235, blue: 0.9882352941, alpha: 1),#colorLiteral(red: 0.9333333333, green: 0.5294117647, blue: 0.4980392157, alpha: 1),#colorLiteral(red: 0.9019607843, green: 0.7882352941, blue: 0.6588235294, alpha: 1),#colorLiteral(red: 1, green: 0.9568627451, blue: 0.462745098, alpha: 1),#colorLiteral(red: 0.7843137255, green: 0.9647058824, blue: 0.5411764706, alpha: 1),#colorLiteral(red: 0.9411764706, green: 0.7098039216, blue: 0.1921568627, alpha: 1)
]
static func getContentHeight(for text: String, with font: UIFont, width: CGFloat) -> CGFloat {
let nsstring = NSString(string: text)
let textAttributes = [NSAttributedString.Key.font : font]
let boundingRect = nsstring.boundingRect(with: CGSize(width: width, height: maxContentHeight), options: .usesLineFragmentOrigin, attributes: textAttributes, context: nil)
return ceil(boundingRect.height)
}
static func getContentWidth(for text: String, with font: UIFont, width: CGFloat) -> CGFloat {
let nsstring = NSString(string: text)
let textAttributes = [NSAttributedString.Key.font : font]
let boundingRect = nsstring.boundingRect(with: CGSize(width: width, height: maxContentHeight), options: .usesLineFragmentOrigin, attributes: textAttributes, context: nil)
return ceil(boundingRect.width)
}
}
|
// Created by Axel Ancona Esselmann on 2/21/20.
//
import KeychainQueryBuilder
public enum OSError: Swift.Error {
case unhandledError(status: OSStatus)
case duplicateItem
case unimplemented
case diskFull
case ioError
case fileAlreadyOpen
case invalidParameter
case noWritePermission
case failedToAllocateMemory
init?(_ status: OSStatus) {
switch status {
case errSecSuccess:
return nil
case errSecUnimplemented:
self = .unimplemented
case errSecDiskFull:
self = .diskFull
case errSecIO:
self = .ioError
case errSecOpWr:
self = .fileAlreadyOpen
case errSecParam:
self = .invalidParameter
case errSecWrPerm:
self = .noWritePermission
case errSecAllocate:
self = .failedToAllocateMemory
// TODO: do others
case errSecDuplicateItem:
self = .duplicateItem
default:
self = .unhandledError(status: status)
}
}
}
public class KeychainWrapper {
public init() {
}
public func set(_ query: CFDictionary) throws {
let status = SecItemAdd(query, nil)
if let error = OSError(status) {
throw error
}
}
public func update(existingItemQuery: CFDictionary, updateQuery: CFDictionary) throws {
let status = SecItemUpdate(existingItemQuery, updateQuery)
if let error = OSError(status) {
throw error
}
}
public func delete(_ existingItemQuery: CFDictionary) throws {
let status = SecItemDelete(existingItemQuery)
if let error = OSError(status) {
throw error
}
}
public func getOne(_ query: CFDictionary) -> Data? {
var item: CFTypeRef?
let status = SecItemCopyMatching(query, &item)
let result = KeychainQueryResultBuilder(forQuery: query)
.result(for: item, status: status)
switch result {
case .none:
return nil
case .one(let result):
return result.data
case .many(let results):
if let first = results.first {
return first.data
} else {
return nil
}
case .error:
return nil
}
}
public func setGenericPassword(_ password: String, for key: String) throws {
let query = KeychainQueryBuilder(type: .genericPassword)
.account(key)
.data(fromString: password)
.build()
try set(query)
}
public func setGenericPassword(_ password: String, for uuid: UUID, context: String? = nil) throws {
let context = context ?? ""
try setGenericPassword(password, for: uuid.uuidString + context)
}
public func updateGenericPassword(_ password: String, for key: String) throws {
let existingItemQuery = KeychainQueryBuilder(type: .genericPassword)
.account(key)
.build()
let updateQuery = KeychainQueryBuilder()
.account(key)
.data(fromString: password)
.build()
try update(existingItemQuery: existingItemQuery, updateQuery: updateQuery)
}
public func updateGenericPassword(_ password: String, for uuid: UUID, context: String? = nil) throws {
let context = context ?? ""
try updateGenericPassword(password, for: uuid.uuidString + context)
}
public func deleteGenericPassword(for key: String) throws {
let existingItemQuery = KeychainQueryBuilder(type: .genericPassword)
.account(key)
.build()
try delete(existingItemQuery)
}
public func deleteGenericPassword(for uuid: UUID, context: String? = nil) throws {
let context = context ?? ""
try deleteGenericPassword(for: uuid.uuidString + context)
}
public func getGenericPassword(for key: String) -> String? {
let query = KeychainQueryBuilder(type: .genericPassword)
.account(key)
.matchLimit(.one)
.returnAttributes()
.returnData()
.build()
guard let data = getOne(query) else {
return nil
}
guard let password = String(data: data, encoding: .utf8) else {
return nil
}
return password
}
public func getGenericPassword(for uuid: UUID, context: String? = nil) -> String? {
let context = context ?? ""
return getGenericPassword(for: uuid.uuidString + context)
}
}
|
//
// EdgesMaster.swift
// GradesGuru
//
// Created by Superpower on 22/09/20.
// Copyright © 2020 iMac superpower. All rights reserved.
//
import Foundation
import Firebase
import FirebaseFirestoreSwift
import FirebaseFirestore
var EdgeDetails : EdgeMaster = EdgeMaster(device_ID: "", CardID: "", Pictures : ["1","2","3"], SurfaceValue : "", PSA : 1, BGS : 2, SGC: 1, ViewonPSA: "")
class EdgeMaster : NSObject {
var device_ID: String!
var CardID: String!
var Pictures : [String]!
var SurfaceValue : String!
var PSA : Int!
var BGS : Int!
var SGC : Int!
var ViewonPSA: String!
init(device_ID: String, CardID: String, Pictures : [String], SurfaceValue : String, PSA : Int, BGS : Int, SGC : Int, ViewonPSA: String) {
self.device_ID = device_ID
self.CardID = CardID
self.Pictures = Pictures
self.SurfaceValue = SurfaceValue
self.PSA = PSA
self.BGS = BGS
self.SGC = SGC
self.ViewonPSA = ViewonPSA
}
func LoadEdge() {
}
}
func UpdateEdge(EdgeMaster: EdgeMaster) {
// let docData = ["device_ID": Users.device_ID!,
// "Subscription_Status": Users.Subscription_Status!,
// "Subscription_Date": Users.Subscription_Date!,
// "Subscription_Type": Users.Subscription_Type!,
// "Cost": Users.Cost!,
// "CurrentScan_Count": Users.CurrentScan_Count! ] as [String : Any]
//
//
// db.collection("Users").document(Users.device_ID).setData(docData) { err in
// if let err = err {
// print("Error writing document: \(err)")
// } else {
// print("Document successfully written!")
// }
// }
//
}
|
import Foundation
import RxSwift
import ObjectMapper
import HsToolKit
import Alamofire
class HsLabelProvider {
private let networkManager: NetworkManager
private let apiUrl = AppConfig.marketApiUrl
private let headers: HTTPHeaders?
init(networkManager: NetworkManager) {
self.networkManager = networkManager
headers = AppConfig.hsProviderApiKey.flatMap { HTTPHeaders([HTTPHeader(name: "apikey", value: $0)]) }
}
}
extension HsLabelProvider {
func updateStatusSingle() -> Single<EvmUpdateStatus> {
let request = networkManager.session.request("\(apiUrl)/v1/status/updates", headers: headers)
return networkManager.single(request: request)
}
func evmMethodLabelsSingle() -> Single<[EvmMethodLabel]> {
let request = networkManager.session.request("\(apiUrl)/v1/evm-method-labels", headers: headers)
return networkManager.single(request: request)
}
func evmAddressLabelsSingle() -> Single<[EvmAddressLabel]> {
let request = networkManager.session.request("\(apiUrl)/v1/addresses/labels", headers: headers)
return networkManager.single(request: request)
}
}
|
//
// CategoryTableViewCell.swift
// TaskManager
//
// Created by Истина on 10/06/2019.
// Copyright © 2019 Истина. All rights reserved.
//
import UIKit
class CategoryTableViewCell: UITableViewCell {
@IBOutlet weak var textCategory: UILabel!
@IBOutlet weak var colorCategory: UILabel!
}
|
//
// SearchManager.swift
// Githuber
//
// Created by Meng Li on 2020/9/9.
// Copyright © 2020 Meng Li. All rights reserved.
//
import RxSwift
final class SearchManager {
static let shared = SearchManager()
private init() {}
func searchRepo(keyword: String) -> Single<[RepositoryItem]> {
return SearchRepository.shared.searchRepo(keyword: keyword)
}
}
|
//
// MapViewController.swift
// VirtualTourist
//
// Created by Bhavya D J on 01/12/18.
// Copyright © 2018 Bhavya D J. All rights reserved.
//
import UIKit
import MapKit
import CoreData
class MapViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapImage: MKMapView!
//MARK: Properties
var dataController: DataController!
var allPins: [Pin] = []
var currentPin: Pin!
var pinHasPhotos: Bool!
//MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
mapImage.delegate = self
let scale = MKScaleView(mapView: mapImage)
scale.isHidden = false
mapImage.addSubview(scale)
//load the mapView zoom level and center point from last time user was in the view
let defaults = UserDefaults.standard
if let lat = defaults.value(forKey: "lat"),
let lon = defaults.value(forKey: "lon"),
let latDelta = defaults.value(forKey: "latDelta"),
let lonDelta = defaults.value(forKey: "lonDelta") {
let center: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: lat as! Double, longitude: lon as! Double)
let span: MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: latDelta as! Double, longitudeDelta: lonDelta as! Double)
let region: MKCoordinateRegion = MKCoordinateRegion(center: center, span: span)
mapImage.setRegion(region, animated: true)
}
let fetchRequest: NSFetchRequest<Pin> = Pin.fetchRequest()
if let result = try? dataController.viewContext.fetch(fetchRequest) {
allPins = result
}
//Add allPins to the map for the user to see
for pin in allPins {
let annotation = PinAnnotation()
annotation.setCoordinate(newCoordinate: CLLocationCoordinate2D(latitude: pin.latitude, longitude: pin.longitude))
annotation.associatedPin = pin
self.mapImage.addAnnotation(annotation)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
//save mapView zoom level and center point as user exits view
let defaults = UserDefaults.standard
defaults.set(self.mapImage.centerCoordinate.latitude, forKey: "lat")
defaults.set(self.mapImage.centerCoordinate.longitude, forKey: "lon")
defaults.set(self.mapImage.region.span.latitudeDelta, forKey: "latDelta")
defaults.set(self.mapImage.region.span.longitudeDelta, forKey: "lonDelta")
}
@IBAction func droppingPin(sender: UILongPressGestureRecognizer) {
if sender.state == UIGestureRecognizer.State.began { return}
let location = sender.location(in: self.mapImage)
let coordinates = self.mapImage.convert(location, toCoordinateFrom: self.mapImage)
//place pin on the map where user long presses
let annotation = PinAnnotation()
annotation.setCoordinate(newCoordinate: coordinates)
self.mapImage.addAnnotation(annotation)
//create Pin to be saved to persistent store
let pin = Pin(context: dataController.viewContext)
pin.latitude = coordinates.latitude
pin.longitude = coordinates.longitude
try? dataController.viewContext.save()
//set the pin being dropped as the current pin
self.currentPin = pin
annotation.associatedPin = pin
self.pinHasPhotos = true
}
func mapView(_ mapView: MKMapView, didSelect: MKAnnotationView) {
let photoAlbumVC = self.storyboard?.instantiateViewController(withIdentifier: "photoAlbumVC") as! PhotoAlbumViewController
let annotation = didSelect.annotation as! PinAnnotation
photoAlbumVC.dataController = self.dataController
photoAlbumVC.photosExist = true
photoAlbumVC.currentPin = annotation.associatedPin
navigationController?.pushViewController(photoAlbumVC, animated: true)
}
}
|
//
// Math.swift
// Rocket Simulation
//
// Created by Sam Bunger on 10/18/18.
// Copyright © 2018 Samster. All rights reserved.
//
import Foundation
|
//
// ProductResult.swift
// GBShop
//
// Created by Константин Кузнецов on 01.07.2021.
//
import Foundation
struct ProductResult: Codable {
let result: Int
let name: String
let price: Int
let description: String
let errorMassage: String?
enum CodingKeys: String, CodingKey {
case result = "result"
case name = "product_name"
case price = "product_price"
case description = "product_description"
case errorMassage = "error_message"
}
}
|
//
// BaseViewController.swift
// Loustagram
//
// Created by Kiet on 12/23/17.
// Copyright © 2017 Kiet. All rights reserved.
//
import Foundation
import AsyncDisplayKit
class BaseViewController: ASViewController<ASDisplayNode> {
override func viewDidLoad() {
super.viewDidLoad()
}
func setupBarButton(with image: UIImage, leftOfBar: Bool) {
if leftOfBar {
let button = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(leftBarButtonTap))
navigationItem.leftBarButtonItem = button
} else {
let button = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(rightBarButtonTap))
navigationItem.rightBarButtonItem = button
}
}
@objc func rightBarButtonTap() {
}
@objc func leftBarButtonTap() {
}
}
|
//
// MapViewController.swift
// Places of Interest
//
// Created by Trainer on 25/03/2015.
// Copyright (c) 2015 leonbaird. All rights reserved.
//
import UIKit
import MapKit
// import CoreData
class MapViewController: UIViewController {
// Outlets
@IBOutlet weak var map: MKMapView!
// Model to display on map as pin
var model:Place?
override func viewDidLoad() {
super.viewDidLoad()
// Put model onto map
if model != nil {
updateMapAnnotation(model!)
}
/* Example of adding all places to map
let request = NSFetchRequest(entityName: PlaceEntityName)
let allPlaces = AppDelegate.getContext().executeFetchRequest(request, error: nil)
map.addAnnotations(allPlaces)
*/
}
func updateMapAnnotation(pin:Place) {
map.removeAnnotations(map.annotations)
map.addAnnotation(pin)
map.setRegion(
MKCoordinateRegion(
center: pin.coordinate,
span: MKCoordinateSpan(
latitudeDelta: 0.05,
longitudeDelta: 0.05
)
),
animated: true
)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Action methods
@IBAction func changeMapView(sender: UIBarButtonItem) {
switch sender.tag {
case 1:
map.mapType = .Satellite
case 2:
map.mapType = .Hybrid
default:
map.mapType = .Standard
}
}
}
|
//
// AddressPickView.swift
// Lex
//
// Created by nbcb on 2016/12/23.
// Copyright © 2016年 ZQC. All rights reserved.
//
import UIKit
import SnapKit
protocol AddressPickDelegate {
func selectedCancel()
func selectedConfirm(_ dic : Dictionary<String, Any>)
}
class AddressPickView: UIView {
var adDelegate : AddressPickDelegate?
var dic : Dictionary<String, Any>?
var pickerDic : NSDictionary!
var provinceArray : NSArray!
var cityArray : NSArray!
var townArray : NSArray!
var selectedArray : NSArray!
override init(frame: CGRect) {
super.init(frame: frame)
self.dic = Dictionary()
addPickView()
getPickerData()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: -添加地址选择器
fileprivate func addPickView() {
self.addSubview(likeToolView)
likeToolView.snp.makeConstraints { (make) in
make.top.left.equalTo(0)
make.size.equalTo(CGSize.init(width: app_width, height: 44))
}
self.addSubview(cityPickView)
cityPickView.snp.makeConstraints { (make) in
make.top.equalTo(44)
make.left.equalTo(0)
make.right.equalTo(0)
make.bottom.equalTo(0)
}
likeToolView.addSubview(cancelBtn)
cancelBtn.snp.makeConstraints { (make) in
make.left.equalTo(15)
make.top.equalTo(7)
make.size.equalTo(CGSize.init(width: 40, height: 30))
}
likeToolView.addSubview(confirmBtn)
confirmBtn.snp.makeConstraints { (make) in
make.right.equalTo(-15)
make.top.equalTo(7)
make.size.equalTo(CGSize.init(width: 40, height: 30))
}
}
lazy var likeToolView : UIView = {
let view : UIView = UIView()
view.backgroundColor = UIColor.gray
return view
}()
lazy var confirmBtn : UIButton = {
let btn : UIButton = UIButton()
btn.setTitle("确定", for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 15.0)
btn.setBackgroundImage(UIImage.init(named: "progresshud_background"), for: .normal)
btn.addTarget(self, action: #selector(AddressPickView.confirmClick), for:
.touchUpInside)
btn.sizeToFit()
return btn
}()
lazy var cancelBtn : UIButton = {
let btn : UIButton = UIButton()
btn.setTitle("取消", for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 15.0)
btn.setTitleColor(UIColor.green, for: .normal)
btn.addTarget(self, action: #selector(AddressPickView.cancelClick), for: .touchUpInside)
return btn
}()
lazy var cityPickView : UIPickerView = {
let view : UIPickerView = UIPickerView()
view.backgroundColor = globalBGColor()
view.delegate = self
view.dataSource = self
return view
}()
//MARK: -pickerView
func getSubViews(_ view : UIView) {
for subView in view.subviews {
if subView.subviews.count != 0 {
self.getSubViews(subView)
}
else {
if subView.frame.size.height <= 1 {
subView.backgroundColor = RGBA(41, g: 196, b: 117, a: 1.0)
subView.alpha = 0.5
}
}
}
}
func confirmClick() {
if self.adDelegate != nil {
if self.dic?.count == 0 {
//省
let state : String = (self.provinceArray[self.cityPickView.selectedRow(inComponent: 0)] as? String)!
self.dic = ["state" : state]
//市
let city : String = (self.cityArray[self.cityPickView.selectedRow(inComponent: 1)] as? String)!
self.dic = ["state" : state, "city" : city]
//区
let area : String = (self.townArray[self.cityPickView.selectedRow(inComponent: 2)]as? String)!
self.dic = ["state" : state, "city" : city, "area" : area]
}
self.adDelegate?.selectedConfirm(self.dic!)
}
}
func cancelClick() {
if self.adDelegate != nil {
self.adDelegate?.selectedCancel()
}
}
//解析plist文件
func getPickerData() {
let path = Bundle.main.path(forResource: "Address", ofType: "plist")
self.pickerDic = NSDictionary.init(contentsOfFile: path!)
self.provinceArray = self.pickerDic.allKeys as NSArray!
self.selectedArray = self.pickerDic.object(forKey: self.pickerDic.allKeys[0]) as! NSArray
if (self.selectedArray.count > 0) {
self.cityArray = (self.selectedArray[0] as AnyObject).allKeys as NSArray!
}
if (self.cityArray.count > 0) {
self.townArray = (self.selectedArray[0] as AnyObject).object(forKey: self.cityArray[0]) as! NSArray
}
}
}
//MARK: UIPickerViewDelegate UIPickerViewDataSource
extension AddressPickView : UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
self.getSubViews(pickerView)
var pickerLabel = UILabel()
pickerLabel = UILabel.init()
// pickerLabel.font = UIFont(name: "Helvetica", size: 8)
pickerLabel.font = UIFont.systemFont(ofSize: 15)
pickerLabel.adjustsFontSizeToFitWidth = true
pickerLabel.textAlignment = .left
pickerLabel.backgroundColor = UIColor.clear
pickerLabel.text = self.pickerView(pickerView, titleForRow: row, forComponent: component)
return pickerLabel
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if (component == 0) {
return self.provinceArray.count;
}
else if (component == 1) {
return self.cityArray.count
}
else {
return self.townArray.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if (component == 0) {
//return [self.provinceArray objectAtIndex:row];
return self.provinceArray[row] as? String
}
else if (component == 1) {
return self.cityArray[row] as? String
}
else {
return self.townArray[row] as? String
}
}
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
if component == 0 {
return 100
}
return 110
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if (component == 0) {
self.selectedArray = self.pickerDic.object(forKey: self.provinceArray[row]) as! NSArray
if (self.selectedArray.count > 0) {
self.cityArray = (self.selectedArray[0] as AnyObject).allKeys as NSArray!
}
else {
self.cityArray = nil;
}
if (self.cityArray.count > 0) {
self.townArray = (self.selectedArray[0] as AnyObject).object(forKey: self.cityArray[0]) as! NSArray
}
else {
self.townArray = nil;
}
// pickerView.selectRow(0, inComponent: 1, animated: true)
}
pickerView.selectedRow(inComponent: 1)
pickerView.reloadComponent(1)
pickerView.selectedRow(inComponent: 2)
if (component == 1) {
if (self.selectedArray.count > 0 && self.cityArray.count > 0) {
self.townArray = (self.selectedArray[0] as AnyObject).object(forKey: self.cityArray[row]) as! NSArray
} else {
self.townArray = nil;
}
pickerView.selectRow(1, inComponent: 2, animated: true)
}
pickerView.reloadComponent(2)
//省
let state : String = (self.provinceArray[self.cityPickView.selectedRow(inComponent: 0)] as? String)!
self.dic = ["state" : state]
//市
let city : String = (self.cityArray[self.cityPickView.selectedRow(inComponent: 1)] as? String)!
self.dic = ["state" : state, "city" : city]
//区
let area : String = (self.townArray[self.cityPickView.selectedRow(inComponent: 2)]as? String)!
self.dic = ["state" : state, "city" : city, "area" : area]
}
}
|
import Foundation
struct LFSamplePoint<T> {
var probability: Double {
didSet {
assert(probability <= 1 || probability >= 0)
}
}
var value: T
}
|
//
// EventTableViewController.swift
// CalendarApp
//
// Created by Ryusei Wada on 2018/11/13.
// Copyright © 2018年 Ryusei Wada. All rights reserved.
//
import UIKit
class EventTableViewController: UITableViewController {
var eventArray: [(String, String)] = []
var calendarModel: CalendarModel = CalendarModel()
var selectDay = ""
override func viewDidLoad() {
super.viewDidLoad()
eventArray = calendarModel.getEvents(date: selectDay)
print(eventArray)
}
// Sectionの個数
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
// Cellの個数
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return eventArray.count
}
// Cellの設定
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = eventArray[indexPath.row].1
return cell
}
// Cellタップ時の挙動
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(indexPath)
}
// 予定を削除
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
calendarModel.removeEvent(id: eventArray[indexPath.row].0)
eventArray.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
}
|
//
// ListStockMapViewController.swift
// SOSVietnam
//
// Created by Ecko Huynh on 24/04/2020.
// Copyright © 2020 admin. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class ListStockMapViewController: UIViewController {
@IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
@IBOutlet weak var infoView: UIView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var addressLabel: UILabel!
@IBOutlet weak var phoneLabel: UILabel!
@IBOutlet weak var phoneButton: UIButton!
@IBOutlet weak var bottomMapConstraint: NSLayoutConstraint!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var mapDetailBottomConstraint: NSLayoutConstraint!
var markers: [MKPointAnnotation] = []
var depots: [Depot]? = []
var currentPlaceMark: CLPlacemark?
var currentLine: MKPolyline?
var currentDepotAnnotation: DepotAnnotation?
override func viewDidLoad() {
super.viewDidLoad()
if (CLLocationManager.locationServicesEnabled()) {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
} else {
print("Location services are not enabled")
}
mapView.delegate = self
mapView.mapType = MKMapType.standard
mapView.showsUserLocation = true
APIClient.getFoodDepots { [weak self] (response) in
if let _ = response.error {
return
}
self?.depots = response.value
self?.loadMarkers()
}
searchBar.delegate = self
searchBar.placeholder = "Tìm địa điểm"
searchBar.resignFirstResponder()
infoView.isHidden = true
dismissKey()
}
func dismissKey()
{
let tap: UITapGestureRecognizer = UITapGestureRecognizer( target: self, action: #selector(ListStockMapViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
@IBAction func phoneClick(_ sender: Any) {
if let phone = currentDepotAnnotation?.phone, let url = URL(string: "tel://\(phone)"), UIApplication.shared.canOpenURL(url) {
if #available(iOS 10, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}
}
}
func loadMarkers() {
var lastLocationPoint: CLLocationCoordinate2D?
if let depots = depots {
for depot in depots {
let location = CLLocationCoordinate2D(latitude: CLLocationDegrees(depot.latitude), longitude: CLLocationDegrees(depot.longitude))
lastLocationPoint = location
// 3)
let span = MKCoordinateSpan(latitudeDelta: 0.4, longitudeDelta: 0.4)
let region = MKCoordinateRegion(center: location, span: span)
mapView.setRegion(region, animated: true)
// 4)
// let annotation = MKPointAnnotation()
let annotation = DepotAnnotation(depot: depot, coordinate: location)
// annotation.coordinate = location
// annotation.description
// annotation.title = depot.name
// annotation.subtitle = depot.provider
mapView.addAnnotation(annotation)
}
}
// Center map
if let currentLocation = locationManager.location?.coordinate{
centerMapOnLocation(location: currentLocation)
} else {
if let lastLocationPoint = lastLocationPoint {
centerMapOnLocation(location: lastLocationPoint)
}
}
}
func highlightCurrentRestaurant() {
// for currentMarker in markers {
// currentMarker.icon?.tintImage(UIColor.lightGray)
// if let currentMarkerData = currentMarker.userData as? Restaurant {
// guard let currentRestaurantID = currentRestaurant?.id else {
// self.currentRestaurant = currentMarkerData
// updateBottomData()
// currentMarker.icon?.tintImage(UIColor.orange)
// return
// }
//
// if currentMarkerData.id == currentRestaurantID {
// currentMarker.icon?.tintImage(UIColor.orange)
// updateBottomData()
// }
// }
// }
}
func createPolyline() {
guard let currentPlacemark = currentPlaceMark?.location?.coordinate, let currentLocaiton = locationManager.location?.coordinate else {
return
}
if let currentLine = currentLine {
self.mapView.removeOverlay(currentLine)
}
let request = MKDirections.Request()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: currentPlacemark, addressDictionary: nil))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: currentLocaiton, addressDictionary: nil))
request.requestsAlternateRoutes = false
request.transportType = .automobile
let directionRequest = MKDirections(request: request)
directionRequest.calculate { [unowned self] response, error in
guard let unwrappedResponse = response else { return }
for route in unwrappedResponse.routes {
self.currentLine = route.polyline
self.mapView.addOverlay(route.polyline)
return
}
}
}
func centerMapOnLocation(location: CLLocationCoordinate2D) {
let span = MKCoordinateSpan(latitudeDelta: 0.4, longitudeDelta: 0.4)
let region = MKCoordinateRegion(center: location, span: span)
print("locations = \(location.latitude) \(location.longitude)")
mapView.setRegion(region, animated: true)
}
@objc func actionWithParam(){
print("locations")
}
}
extension ListStockMapViewController: CLLocationManagerDelegate {
private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse || status == .authorizedAlways {
locationManager.requestLocation()
}
}
private func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
mapView.showsUserLocation = true
if let location = locations.first {
let span = MKCoordinateSpan(latitudeDelta: 0.4, longitudeDelta: 0.4)
let region = MKCoordinateRegion(center: location.coordinate, span: span)
mapView.setRegion(region, animated: true)
}
}
private func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("error:: \(error)")
}
}
extension ListStockMapViewController: MKMapViewDelegate {
// func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
// let identifier = "pin"
//
// if annotation.isKind(of: MKUserLocation.self) {
// return nil
// }
//
// let image = UIImage(named: "car")
//// let button = UIButton(type: .custom)
//// button.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
//// button.setImage(image, for: .normal)
//// button.addTarget(self, action: #selector(actionWithParam), for: .touchUpInside)
//
//// button.addTarget(self, action: #selector(Map.info(_:)), forControlEvents:UIControlEvents.TouchUpInside)
//
// var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
// if annotationView == nil {
// annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "pin")
// annotationView!.canShowCallout = true
// annotationView!.image = UIImage(named: "annotation")
//// annotationView!.rightCalloutAccessoryView = button
// }
// else {
// annotationView!.annotation = annotation
// }
//
// return annotationView
// }
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
let location = view.annotation
self.currentPlaceMark = MKPlacemark(coordinate: location!.coordinate)
currentDepotAnnotation = view.annotation as? DepotAnnotation
nameLabel.text = currentDepotAnnotation?.title
addressLabel.text = currentDepotAnnotation?.address
phoneButton.setTitle(currentDepotAnnotation?.phone, for: .normal)
infoView.isHidden = false
createPolyline()
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
}
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
print("cHere we are")
}
func mapViewDidFailLoadingMap(_ mapView: MKMapView, withError error: Error) {
print("error:: \(error)")
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(polyline: overlay as! MKPolyline)
renderer.strokeColor = .red
renderer.lineWidth = 2.0
return renderer
}
}
extension ListStockMapViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
view.endEditing(true)
updateSearchResultsForSearchController(searchText: searchBar.text)
}
func updateSearchResultsForSearchController(searchText: String?) {
guard let mapView = mapView,
let searchBarText = searchText else { return }
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = searchBarText
request.region = mapView.region
let search = MKLocalSearch(request: request)
search.start { [weak self] response, _ in
guard let response = response else {
return
}
// self.matchingItems = response.mapItems
// self.tableView.reloadData()
let searchViewController = SearchViewController()
searchViewController.tableData = response.mapItems
searchViewController.callback = { [weak self] placemark in
DispatchQueue.main.async {
let center = placemark.coordinate
let mRegion = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self?.mapView.setRegion(mRegion, animated: true)
}
}
self?.navigationController?.present(searchViewController, animated: true, completion: nil)
}
}
}
class DepotAnnotation: NSObject, MKAnnotation {
var id: String?
var title: String?
var address: String?
var coordinate: CLLocationCoordinate2D
var provider: String?
var phone: String?
init(id: String?, name: String?, address: String?, coordinate: CLLocationCoordinate2D, provider: String?, phone: String?) {
self.id = id
self.title = name
self.address = address
self.coordinate = coordinate
self.provider = provider
self.phone = phone
}
init(depot: Depot, coordinate: CLLocationCoordinate2D) {
self.id = depot.id
self.title = depot.name
self.address = depot.address
self.coordinate = coordinate
self.provider = depot.provider
self.phone = depot.phone
}
}
|
import Foundation
//List of API keys that have different services enabled with them
enum AcceptOnKeyProperty {
case PaypalRest
case Stripe
case PublicKey
case StripeApplePay
case ApplePay
}
struct AcceptOnAPIKeyInfo {
var key: String
var properties: [AcceptOnKeyProperty]
//Meta-data is just extra information
var metadata: [String:AnyObject]
}
let keys = [
AcceptOnAPIKeyInfo(key: "pkey_24b6fa78e2bf234d", properties: [.PaypalRest, .Stripe, .PublicKey, .StripeApplePay, .ApplePay], metadata: ["stripe_merchant_identifier": "merchant.com.accepton"]),
AcceptOnAPIKeyInfo(key: "pkey_89f2cc7f2c423553", properties: [.Stripe], metadata: [:])
]
//Get a key with a set of properties
func apiKeyWithProperties(properties: [AcceptOnKeyProperty], withoutProperties: [AcceptOnKeyProperty]) -> AcceptOnAPIKeyInfo {
//Must contain all mentioned properties
var filteredKeys = keys.filter { keyInfo in
for p in properties {
if keyInfo.properties.indexOf(p) == nil { return false }
}
return true
}
//Must *not* contain all negatively mentioned properties
filteredKeys = filteredKeys.filter { keyInfo in
for p in withoutProperties {
if keyInfo.properties.indexOf(p) != nil { return false }
}
return true
}
let resultKey = filteredKeys.first
if resultKey == nil {
NSException(name: "apiKeyWithProperties", reason: "Couldn't find an API key that had the properties of \(properties) without the properties of \(withoutProperties)", userInfo: nil).raise()
}
return resultKey!
}
|
//
// CommonAssembly
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright (c) ___YEAR___ Jex. All rights reserved.
import Swinject
class CommonAssembly: Assembly {
func assemble(container: Container) {
container.register(IAppRouter.self) { _ in
AppRouter.shared
}
}
}
|
// DO NOT EDIT.
//
// Generated by the Swift generator plugin for the protocol buffer compiler.
// Source: tracker.proto
//
// For information on using the generated types, please see the documenation:
// https://github.com/apple/swift-protobuf/
import Foundation
import SwiftProtobuf
// If the compiler emits an error on this type, it is because this file
// was generated by a version of the `protoc` Swift plug-in that is
// incompatible with the version of SwiftProtobuf to which you are linking.
// Please ensure that your are building against the same version of the API
// that was used to generate this file.
fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck {
struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {}
typealias Version = _2
}
struct Grpc_PingRequest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var payload: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Grpc_PongResponse {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var payload: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Grpc_AddLocationsRequest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var tid: String = String()
var locations: [Models_Location] = []
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Grpc_AddLocationResponse {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var ok: Bool = false
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Grpc_GetLocationsRequest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var tid: String = String()
var limit: Int32 = 0
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Grpc_GenerateTrackerIDRequest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var prevTid: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Grpc_GenerateTrackerIDResponse {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var tid: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Grpc_TestTrackerIDRequest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var tid: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Grpc_TestTrackerIDResponse {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var ok: Bool = false
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Grpc_FreeTrackerIDRequest {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var tid: String = String()
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
struct Grpc_FreeTrackerIDResponse {
// SwiftProtobuf.Message conformance is added in an extension below. See the
// `Message` and `Message+*Additions` files in the SwiftProtobuf library for
// methods supported on all messages.
var ok: Bool = false
var unknownFields = SwiftProtobuf.UnknownStorage()
init() {}
}
// MARK: - Code below here is support for the SwiftProtobuf runtime.
fileprivate let _protobuf_package = "grpc"
extension Grpc_PingRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".PingRequest"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "payload"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.payload)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.payload.isEmpty {
try visitor.visitSingularStringField(value: self.payload, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Grpc_PingRequest, rhs: Grpc_PingRequest) -> Bool {
if lhs.payload != rhs.payload {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Grpc_PongResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".PongResponse"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "payload"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.payload)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.payload.isEmpty {
try visitor.visitSingularStringField(value: self.payload, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Grpc_PongResponse, rhs: Grpc_PongResponse) -> Bool {
if lhs.payload != rhs.payload {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Grpc_AddLocationsRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".AddLocationsRequest"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "tid"),
2: .same(proto: "locations"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.tid)
case 2: try decoder.decodeRepeatedMessageField(value: &self.locations)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.tid.isEmpty {
try visitor.visitSingularStringField(value: self.tid, fieldNumber: 1)
}
if !self.locations.isEmpty {
try visitor.visitRepeatedMessageField(value: self.locations, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Grpc_AddLocationsRequest, rhs: Grpc_AddLocationsRequest) -> Bool {
if lhs.tid != rhs.tid {return false}
if lhs.locations != rhs.locations {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Grpc_AddLocationResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".AddLocationResponse"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "ok"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularBoolField(value: &self.ok)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if self.ok != false {
try visitor.visitSingularBoolField(value: self.ok, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Grpc_AddLocationResponse, rhs: Grpc_AddLocationResponse) -> Bool {
if lhs.ok != rhs.ok {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Grpc_GetLocationsRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".GetLocationsRequest"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "tid"),
2: .same(proto: "limit"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.tid)
case 2: try decoder.decodeSingularInt32Field(value: &self.limit)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.tid.isEmpty {
try visitor.visitSingularStringField(value: self.tid, fieldNumber: 1)
}
if self.limit != 0 {
try visitor.visitSingularInt32Field(value: self.limit, fieldNumber: 2)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Grpc_GetLocationsRequest, rhs: Grpc_GetLocationsRequest) -> Bool {
if lhs.tid != rhs.tid {return false}
if lhs.limit != rhs.limit {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Grpc_GenerateTrackerIDRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".GenerateTrackerIDRequest"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .standard(proto: "prev_tid"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.prevTid)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.prevTid.isEmpty {
try visitor.visitSingularStringField(value: self.prevTid, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Grpc_GenerateTrackerIDRequest, rhs: Grpc_GenerateTrackerIDRequest) -> Bool {
if lhs.prevTid != rhs.prevTid {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Grpc_GenerateTrackerIDResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".GenerateTrackerIDResponse"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "tid"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.tid)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.tid.isEmpty {
try visitor.visitSingularStringField(value: self.tid, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Grpc_GenerateTrackerIDResponse, rhs: Grpc_GenerateTrackerIDResponse) -> Bool {
if lhs.tid != rhs.tid {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Grpc_TestTrackerIDRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestTrackerIDRequest"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "tid"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.tid)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.tid.isEmpty {
try visitor.visitSingularStringField(value: self.tid, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Grpc_TestTrackerIDRequest, rhs: Grpc_TestTrackerIDRequest) -> Bool {
if lhs.tid != rhs.tid {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Grpc_TestTrackerIDResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".TestTrackerIDResponse"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "ok"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularBoolField(value: &self.ok)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if self.ok != false {
try visitor.visitSingularBoolField(value: self.ok, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Grpc_TestTrackerIDResponse, rhs: Grpc_TestTrackerIDResponse) -> Bool {
if lhs.ok != rhs.ok {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Grpc_FreeTrackerIDRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".FreeTrackerIDRequest"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "tid"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularStringField(value: &self.tid)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if !self.tid.isEmpty {
try visitor.visitSingularStringField(value: self.tid, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Grpc_FreeTrackerIDRequest, rhs: Grpc_FreeTrackerIDRequest) -> Bool {
if lhs.tid != rhs.tid {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
extension Grpc_FreeTrackerIDResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding {
static let protoMessageName: String = _protobuf_package + ".FreeTrackerIDResponse"
static let _protobuf_nameMap: SwiftProtobuf._NameMap = [
1: .same(proto: "ok"),
]
mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws {
while let fieldNumber = try decoder.nextFieldNumber() {
switch fieldNumber {
case 1: try decoder.decodeSingularBoolField(value: &self.ok)
default: break
}
}
}
func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws {
if self.ok != false {
try visitor.visitSingularBoolField(value: self.ok, fieldNumber: 1)
}
try unknownFields.traverse(visitor: &visitor)
}
static func ==(lhs: Grpc_FreeTrackerIDResponse, rhs: Grpc_FreeTrackerIDResponse) -> Bool {
if lhs.ok != rhs.ok {return false}
if lhs.unknownFields != rhs.unknownFields {return false}
return true
}
}
|
//
// PerformanceTests.swift
//
//
// Created by Noah Kamara on 09.11.20.
//
import XCTest
@testable import JellyKit
class PerformanceTests: XCTestCase {
private var api: API!
override func setUpWithError() throws {
let exp = expectation(description: "Authorize")
api = API("192.168.178.10", 8096, nil, nil)
var err: Error? = nil
api.authorize("jellyfin", "") { response in
switch response {
case .success(_ ): break
case .failure(let error): err = error
}
exp.fulfill()
}
if err != nil {
throw err!
}
waitForExpectations(timeout: 30.0)
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testItemFetch() {
measure() {
let expect = expectation(description: "run")
api.getItems { result in
switch result {
case .success(_): break
case .failure(let error): XCTFail(error.localizedDescription)
}
expect.fulfill()
}
waitForExpectations(timeout: 10.0)
}
}
}
|
//
// XcodeProjectXMLParser.swift
// Buildasaur
//
// Created by Honza Dvorsky on 02/10/2015.
// Copyright © 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import Ji
class XcodeProjectXMLParser {
enum WorkspaceParsingError: ErrorType {
case ParsingFailed
case FailedToFindWorkspaceNode
case NoProjectsFound
case NoLocationInProjectFound
}
static func parseProjectsInsideOfWorkspace(url: NSURL) throws -> [NSURL] {
let contentsUrl = url.URLByAppendingPathComponent("contents.xcworkspacedata")
guard let jiDoc = Ji(contentsOfURL: contentsUrl, isXML: true) else { throw WorkspaceParsingError.ParsingFailed }
guard
let workspaceNode = jiDoc.rootNode,
let workspaceTag = workspaceNode.tag where workspaceTag == "Workspace" else { throw WorkspaceParsingError.FailedToFindWorkspaceNode }
let projects = workspaceNode.childrenWithName("FileRef")
guard projects.count > 0 else { throw WorkspaceParsingError.NoProjectsFound }
let locations = try projects.map { projectNode throws -> String in
guard let location = projectNode["location"] else { throw WorkspaceParsingError.NoLocationInProjectFound }
return location
}
let parsedRelativePaths = locations.map { $0.componentsSeparatedByString(":").last! }
let absolutePaths = parsedRelativePaths.map { return url.URLByAppendingPathComponent("..").URLByAppendingPathComponent($0) }
return absolutePaths
}
}
|
//
// ScratchSettingsViewController.swift
// Nodus
//
// Created by Eden on 5/14/17.
// Copyright © 2017 Eden. All rights reserved.
//
import UIKit
class ScratchSettingsViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var collectionView: UICollectionView!
let cellGap: CGFloat = 5.0
var imageNames = ["scratch_it", "100m_boost", "500m_boost", "1km_boost", "2km_boost"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ScratchCell", for: indexPath)
let imageView = cell.viewWithTag(100) as! UIImageView
imageView.image = UIImage(named: imageNames[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellWidth = (collectionView.bounds.width - 4 * cellGap) / 5
let cellHeight = collectionView.bounds.height
let cellSize = min(cellWidth, cellHeight)
return CGSize(width: cellSize, height: cellSize)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return cellGap
}
@IBAction func onBackBtnClick(_ sender: Any) {
_ = navigationController?.popViewController(animated: true)
}
}
|
//
// DribbbleAPI.swift
// iShots
//
// Created by Seo Yoochan on 10/15/15.
// Copyright © 2015 yoochan. All rights reserved.
//
import Foundation
class DribbbleAPI {
let accessToken = "6d23de112fd5859e7d5658e6b41eee5f1e76291e3327882017457352c56e61a9"
func loadShots(completion: ((AnyObject) -> Void)!) {
let url = "https://api.dribbble.com/v1/shots?access_token=" + accessToken
let session = NSURLSession.sharedSession()
let shotsURL = NSURL(string: url)
let task = session.dataTaskWithURL(shotsURL!) {
(data, resposne, error) -> Void in
if error != nil {
print(error!.localizedDescription)
} else {
do {
let shotsData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)
var shots = [Shot]()
for shot in shotsData as! NSArray {
let shot = Shot(data: shot as! NSDictionary)
shots.append(shot)
}
if shots.count > 0 {
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0)){
dispatch_async(dispatch_get_main_queue()){
completion(shots)
}
}
}
} catch {
}
}
}
task.resume()
}
} |
//
// PhotoGridCell.swift
// FBMIF50
//
// Created by BeInMedia on 3/26/20.
// Copyright © 2020 MIF50. All rights reserved.
//
import UIKit
import LBTATools
class PhotoGridCell: LBTAListCell<String> {
override var item: String! {
didSet {
imageView.image = UIImage(named: item)
}
}
let imageView: UIImageView = {
let img = UIImageView(image: UIImage(named: "avatar1"), contentMode: .scaleAspectFill)
return img
}()
override func setupViews() {
backgroundColor = .yellow
stack(imageView)
}
}
#if canImport(SwiftUI) && DEBUG
import SwiftUI
@available(iOS 13.0, *)
struct PhotoGridCell_Preview: PreviewProvider {
static var previews: some View {
PhotoGridCellRepresentable().previewLayout(.fixed(width: 200, height: 200))
}
}
struct PhotoGridCellRepresentable: UIViewRepresentable {
func makeUIView(context: Context) -> UIView {
return PhotoGridCell()
}
func updateUIView(_ view: UIView, context: Context) {
}
}
#endif
|
//
// ViewController.swift
// CTA Train Tracker 2
//
// Created by Thomas Bart on 8/9/19.
// Copyright © 2019 Thomas Bart. All rights reserved.
//
import UIKit
class ArrivalsController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let cellId = "route"
var requestedStation = "Fullerton"
var routes = [Route]()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
fetchTrainData()
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Incoming Trains"
collectionView?.backgroundColor = Theme.current.viewBackgroundColor
collectionView?.register(ArrivalsCell.self, forCellWithReuseIdentifier: cellId)
self.navigationController?.navigationBar.barStyle = Theme.current.statusBarStyle
setupNavBarButtons()
}
func setupNavBarButtons() {
let refreshImage = UIImage(named: "refresh")?.withRenderingMode(.alwaysTemplate)
let refreshButton = UIBarButtonItem(image: refreshImage, style: .plain, target: self, action: #selector(fetchTrainData))
let searchImage = UIImage(named: "search")?.withRenderingMode(.alwaysTemplate)
let searchButton = UIBarButtonItem(image: searchImage, style: .plain, target: self, action: #selector(pushSearchController))
refreshButton.tintColor = Theme.current.navBarButtonColor
searchButton.tintColor = Theme.current.navBarButtonColor
navigationItem.rightBarButtonItems = [refreshButton, searchButton]
}
@objc func fetchTrainData() {
routes.removeAll()
routes = getTrainArrivalData(for: requestedStation)
self.collectionView?.reloadData()
}
@objc func pushSearchController() {
self.navigationController?.pushViewController(SearchController(), animated: true)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let count = routes.count
if count == 0 {
self.collectionView.displayNoTrainsFoundError()
} else {
self.collectionView.restore()
}
return count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! ArrivalsCell
cell.route = routes[indexPath.item]
cell.backgroundColor = Theme.current.cellBackgroundColor
cell.layer.cornerRadius = 5
cell.layer.masksToBounds = true
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let textViewHeight = CGFloat(routes[indexPath.item].etas.count) * 19.5
return CGSize(width: view.frame.width - 32, height: 68 + textViewHeight + 16)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 16, left: 0, bottom: 0, right: 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 16
}
}
|
//
// RejectReason.swift
// MyLoqta
//
// Created by Shivansh Jaitly on 8/21/18.
// Copyright © 2018 AppVenturez. All rights reserved.
//
import UIKit
import ObjectMapper
class RejectReason: Mappable {
var reasonId : Int?
var rejectReason : String?
func mapping(map: Map) {
reasonId <- map["id"]
rejectReason <- map["rejectReason"]
}
required init?(map: Map) {
}
}
|
//
// Flavor.swift
// LemonadeStand
//
// Created by Christian Romeyke on 22/11/14.
// Copyright (c) 2014 Christian Romeyke. All rights reserved.
//
import Foundation
enum Flavor: Printable {
case Acidic, Neutral, Diluted
var description: String {
switch self {
case Acidic:
return "Acidic"
case Neutral:
return "Neutral"
case Diluted:
return "Diluted"
}
}
} |
//
// AgeScreenerView.swift
// CovidAlert
//
// Created by Matthew Garlington on 12/28/20.
//
import SwiftUI
extension Color {
static let offWhite = Color(red: 225 / 255, green: 225 / 255, blue: 235 / 255)
}
struct SimpleButtonStyle: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.padding(10)
.background(
Group {
if configuration.isPressed {
Capsule()
.fill(Color.offWhite)
} else {
Capsule()
.fill(Color.offWhite)
.shadow(color: Color.black.opacity(0.2), radius: 10, x: 10, y: 10)
.shadow(color: Color.white.opacity(0.7), radius: 10, x: -5, y: -5)
}
}
)
}
}
struct AgeScreenerView: View {
@State var isUnder18Checked : Bool = false
@State var is64checked : Bool = false
@State var isOver65Checked : Bool = false
@State private var didTap: Bool = false
@State private var showNextPage: Bool = false
@State private var showTooYoungPage: Bool = false
@ObservedObject var screenerStatus: ScreenerStatus
var body: some View {
VStack {
Text("How old are you?")
.font(.title)
.bold()
VStack(spacing: 50){
// Action to turn off other selected Checkmarks when Under 18 is selected and turn on selected check mark
Button(action: {
if self.is64checked == true {
self.is64checked.toggle()
self.isUnder18Checked.toggle()
}
else {
self.isUnder18Checked.toggle()
}
if self.isOver65Checked == true {
self.isOver65Checked.toggle()
self.isUnder18Checked.toggle()
}
else {
self.isUnder18Checked.toggle()
}
// Action to Display Check Mark when Under 18 button is pressed
if self.is64checked || self.isOver65Checked == true {
}
else {
self.isUnder18Checked.toggle()
}
// Tap Action for responding Next button
if
self.isUnder18Checked == true
{
self.didTap = true}
else {
self.didTap = false
}
}, label: {
ZStack {
HStack(spacing: 250) {
Text("Under 18")
.bold()
.foregroundColor(.primary)
.frame(width: 75)
Image(systemName: self.isUnder18Checked ? "checkmark.circle.fill" : "circle")
.foregroundColor(Color.init(#colorLiteral(red: 0.3067349494, green: 0.3018456101, blue: 0.7518180013, alpha: 1)))
.font(.system(size: 25))
.frame(width: 10)
}
}.padding()
})
.buttonStyle(SimpleButtonStyle())
// View for Button 18 - 64
Button(action: {
if self.isUnder18Checked == true {
self.isUnder18Checked.toggle()
self.is64checked.toggle()
}
else {
self.is64checked.toggle()
}
if self.isOver65Checked == true {
self.isOver65Checked.toggle()
self.is64checked.toggle()
}
else {
self.is64checked.toggle()
}
if self.isUnder18Checked || self.isOver65Checked == true {
}
else {
self.is64checked.toggle()
}
if
self.is64checked == true
{
self.didTap = true}
else {
self.didTap = false
}
}, label: {
ZStack {
HStack(spacing: 250) {
Text("Between 18 and 64")
.bold()
.foregroundColor(.primary)
.frame(width: 85)
Image(systemName: self.is64checked ? "checkmark.circle.fill" : "circle")
.foregroundColor(Color.init(#colorLiteral(red: 0.3067349494, green: 0.3018456101, blue: 0.7518180013, alpha: 1)))
.font(.system(size: 25))
.frame(width: 10)
}
}.padding()
}) .buttonStyle(SimpleButtonStyle())
Button(action: {
if self.isUnder18Checked == true {
self.isUnder18Checked.toggle()
self.isOver65Checked.toggle()
}
else {
self.isOver65Checked.toggle()
}
if self.is64checked == true {
self.is64checked.toggle()
self.isOver65Checked.toggle()
}
else {
self.isOver65Checked.toggle()
}
if self.is64checked || self.isUnder18Checked == true {
}
else {
self.isOver65Checked.toggle()
}
if
self.isOver65Checked == true
{
self.didTap = true}
else {
self.didTap = false
}
}, label: {
ZStack {
HStack(spacing: 240) {
Text("65 or Older")
.bold()
.foregroundColor(.primary)
Image(systemName: self.isOver65Checked ? "checkmark.circle.fill" : "circle")
.foregroundColor(Color.init(#colorLiteral(red: 0.3067349494, green: 0.3018456101, blue: 0.7518180013, alpha: 1)))
.font(.system(size: 25))
}
}.padding()
}) .buttonStyle(SimpleButtonStyle())
Spacer()
}
VStack{
// These are the two views that will be the destination depending on which box is checked
NavigationLink(
destination: RecentTestingScreenerView(screenerStatus: screenerStatus), isActive: $showNextPage,
label: { Text("") }
)
NavigationLink(
destination: AgeRestrictionView(), isActive: $showTooYoungPage,
label: { Text("") }
)
//This is the nevigation button view at the button
Button(action: {
if
self.is64checked || self.isOver65Checked == true{
self.showNextPage = true }
else {
self.showNextPage = false
}
if
self.isUnder18Checked == true{
self.showTooYoungPage = true }
else {
self.showTooYoungPage = false
}
}, label: {
ZStack {
Spacer()
.frame(width: 375, height: 50, alignment: .center)
.background(didTap ? Color.init(#colorLiteral(red: 0.3036714792, green: 0.2938330173, blue: 0.7397083044, alpha: 1)) : Color.gray)
.cornerRadius(10)
HStack {
Text("Next")
.foregroundColor(.white)
}
}
})
}.padding()
}.background(Color(.init(white: 0.95, alpha: 1)))
}
}
struct AgeScreenerView_Previews: PreviewProvider {
static var previews: some View {
AgeScreenerView(screenerStatus: ScreenerStatus.init())
}
}
|
//
// QuProvinceCell.swift
// Project
//
// Created by 张凯强 on 2018/3/9.
// Copyright © 2018年 HHCSZGD. All rights reserved.
//
import UIKit
class QuProvinceCell: ProvinceCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
var quProvinceModel: AreaModel? {
didSet{
if quProvinceModel?.isSelected ?? false {
self.contentView.backgroundColor = secondSelectedBackColor
self.myTitleLabel.textColor = UIColor.colorWithHexStringSwift("333333")
}else {
self.myTitleLabel.textColor = UIColor.white
self.contentView.backgroundColor = unSelectBackColor
}
if let mo = quProvinceModel {
self.rightBtn.isHidden = mo.rightBtnIsHidden
self.rightBtn.isSelected = mo.rightBtnIsSelect
}
self.myTitleLabel.text = quProvinceModel?.name
}
}
let secondSelectedBackColor: UIColor = UIColor.lightGray
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// ViewController.swift
// RegHackTO
//
// Created by Yevhen Kim on 2016-11-25.
// Copyright © 2016 Yevhen Kim. All rights reserved.
//
import UIKit
import LocalAuthentication
import QuartzCore
class LoginViewController: UIViewController {
@IBOutlet weak var touchButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true, animated: false)
let pulseAnimation = CABasicAnimation(keyPath: "opacity")
pulseAnimation.duration = 2
pulseAnimation.fromValue = 0
pulseAnimation.toValue = 1
pulseAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
pulseAnimation.autoreverses = true
pulseAnimation.repeatCount = FLT_MAX
self.touchButton.layer.add(pulseAnimation, forKey: nil)
}
@IBAction func touchButtonPressed(_ sender: Any) {
authenticateUser()
}
func authenticateUser() {
//get the Local authentication context
let authenticationContext: LAContext = LAContext()
//declare a NSError var
var error: NSError?
// 2. Check if the device has a fingerprint sensor
// If not, show the user an alert view and bail out!
guard authenticationContext.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) else {
showAlertViewIfNoBiometricSensorHasBeenDetected()
return
}
// 3. Check the fingerprint
authenticationContext.evaluatePolicy(
LAPolicy.deviceOwnerAuthentication,
localizedReason: "Only awesome people are allowed",
reply: { [unowned self] (success, error) -> Void in
if( success ) {
// Fingerprint recognized
// Go to view controller
self.navigateToAuthenticatedViewController()
}else {
// Check if there is an error
if let error = error {
let message = self.errorMessageForLAErrorCode(errorCode: error._code)
self.showAlertWithTitle(title: "Error", message: message)
}
}
})
}
func showAlertViewIfNoBiometricSensorHasBeenDetected(){
showAlertWithTitle(title: "Error", message: "This device does not have a TouchID sensor.")
}
func showAlertWithTitle( title:String, message:String ) {
let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
alertVC.addAction(okAction)
DispatchQueue.main.async {
self.present(alertVC, animated: true, completion: nil)
}
}
func navigateToAuthenticatedViewController(){
if let validationInVC = storyboard?.instantiateViewController(withIdentifier: "ValidationViewController") {
DispatchQueue.main.async {
self.navigationController?.pushViewController(validationInVC, animated: true)
}
}
}
func errorMessageForLAErrorCode( errorCode:Int ) -> String{
var message = ""
switch errorCode {
case LAError.appCancel.rawValue:
message = "Authentication was cancelled by application"
case LAError.authenticationFailed.rawValue:
message = "The user failed to provide valid credentials"
case LAError.invalidContext.rawValue:
message = "The context is invalid"
case LAError.passcodeNotSet.rawValue:
message = "Passcode is not set on the device"
case LAError.systemCancel.rawValue:
message = "Authentication was cancelled by the system"
case LAError.touchIDLockout.rawValue:
message = "Too many failed attempts."
case LAError.touchIDNotAvailable.rawValue:
message = "TouchID is not available on the device"
case LAError.userCancel.rawValue:
message = "The user did cancel"
case LAError.userFallback.rawValue:
message = "The user chose to use the fallback"
default:
message = "Did not find error code on LAError object"
}
return message
}
}
|
//
// detailsSizes.swift
// Mona
//
// Created by Tariq on 8/26/19.
// Copyright © 2019 Tariq. All rights reserved.
//
import UIKit
class detailsSizes: UICollectionViewCell {
@IBOutlet weak var sizeLb: UILabel!
func configureCell(product: productsModel) {
sizeLb.text = product.size
}
override func awakeFromNib() {
// self.layer.cornerRadius = 15
// self.contentView.layer.borderColor = UIColor.gray.cgColor
// self.clipsToBounds = true
// self.layer.masksToBounds = true
}
override var isSelected: Bool {
didSet{
layer.cornerRadius = isSelected ? 5.0 : 0.0
layer.borderWidth = isSelected ? 1.0 : 0.0
layer.borderColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
}
}
}
|
//
// ExchangeCurrencyVCWithUIExtension.swift
// PaypayCurrencyConverter
//
// Created by Chung Han Hsin on 2021/3/7.
//
import UIKit
extension ExchangeCurrencyViewController {
func makeInputAmountTextfiled() -> UITextField {
let textField = UITextField()
textField.placeholder = "Please type amount here!"
textField.returnKeyType = .done
textField.keyboardType = .numbersAndPunctuation
textField.clearButtonMode = .whileEditing
textField.addTarget(self, action: #selector(inputAmountTextfieldDidChange(sender:)), for: .editingChanged)
textField.delegate = self
return textField
}
@objc func inputAmountTextfieldDidChange(sender: UITextField) {
viewModel.inputAmount.value = Float.init(sender.text ?? "")
}
func makeCurrencyLable() -> UILabel {
let label = UILabel()
label.textAlignment = .center
label.text = "Use picker view select currency!"
return label
}
func setIsUserInteractionEnable(button: UIButton, isUserInteractionEnabled: Bool) {
button.isUserInteractionEnabled = isUserInteractionEnabled
if isUserInteractionEnabled {
button.backgroundColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
}else {
button.backgroundColor = .lightGray
}
}
func makeExchangeCurrencyButton() -> UIButton {
let button = UIButton(type: .system)
button.setTitle("Exchange currency!", for: .normal)
button.addTarget(self, action: #selector(pressExchangeCurrencyButton(sender:)), for: .touchUpInside)
button.setTitleColor(.white, for: .normal)
setIsUserInteractionEnable(button: button, isUserInteractionEnabled: false)
return button
}
@objc func pressExchangeCurrencyButton(sender: UIButton) {
flowDelegate?.exchangeCurrencyViewControllerFlowDelegateGoToDisplayCurrenciesViewController(self, amountCurrency: viewModel.amountCurrency)
}
func makeCurrenciesPickeView() -> CurrenciesPickerView {
let pickeView = CurrenciesPickerView(currenciesPickerViewDataSource: self, currenciesPickerViewDelegate: self)
return pickeView
}
func setupLayout() {
view.backgroundColor = .white
[inputAmountTextfiled, currencyLable, exchangeCurrencyButton, currenciesPickeView].forEach {
view.addSubview($0)
}
inputAmountTextfiled.snp.makeConstraints {
$0.height.equalTo(30)
$0.width.equalTo(UIScreen.main.bounds.width - 40)
$0.centerX.equalTo(view.snp.centerX)
$0.top.equalTo(view.snp.top).offset(100)
}
currencyLable.snp.makeConstraints {
$0.height.equalTo(30)
$0.width.equalTo(UIScreen.main.bounds.width - 40)
$0.centerX.equalTo(view.snp.centerX)
$0.top.equalTo(inputAmountTextfiled.snp.bottom).offset(10)
}
exchangeCurrencyButton.snp.makeConstraints {
$0.height.equalTo(50)
$0.width.equalTo(UIScreen.main.bounds.width/2)
$0.centerX.equalTo(view.snp.centerX)
$0.top.equalTo(currencyLable.snp.bottom).offset(20)
}
currenciesPickeView.snp.makeConstraints {
$0.height.equalTo(UIScreen.main.bounds.height/4)
$0.left.equalTo(view.snp.left)
$0.right.equalTo(view.snp.right)
$0.bottom.equalTo(view.snp.bottom)
}
}
}
extension ExchangeCurrencyViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
view.endEditing(true)
return true
}
}
|
//
// Point.swift
// Contech
//
// Created by Lauren Shultz on 7/6/18.
// Copyright © 2018 Lauren Shultz. All rights reserved.
//
import Foundation
class Point {
var x: Float
var y: Float
var z: Float = 0
init (x: Float, y: Float, z: Float?) {
self.x = x
self.y = y
if (z != nil) {
self.z = z!
}
}
}
|
//
// Particle.swift
// Particles
//
// Created by Andrew Barba on 11/15/15.
// Copyright © 2015 abarba.me. All rights reserved.
//
import Foundation
import UIKit
class BasicParticle: NSObject {
// View containing the particle
let view: UIView
let color: UIColor
let layer: CALayer
// Physics
let size: CGFloat
var acceleration: CGVector
var position: CGPoint
var velocity: CGVector
init(view: UIView, position: CGPoint, velocity: CGVector, acceleration: CGVector, size: CGFloat = 6.0, color: UIColor = UIColor.blueColor()) {
self.view = view
self.position = position
self.velocity = velocity
self.acceleration = acceleration
self.size = size
self.color = color
self.layer = CALayer()
super.init()
setupLayer()
}
private func setupLayer() {
layer.frame = CGRectMake(position.x, position.y, size, size)
layer.backgroundColor = color.CGColor
layer.cornerRadius = size / 2.0
view.layer.addSublayer(layer)
}
}
// MARK: - Rendering
extension BasicParticle {
func render() {
layer.position = position
}
func die() {
layer.removeFromSuperlayer()
}
var dead: Bool {
let deadX = position.x < -10.0 || position.x > view.bounds.size.width + 10.0
let deadY = position.y > view.bounds.size.height + 10.0
return deadX || deadY
}
}
// MARK: - Movement
extension BasicParticle {
func move() {
position = CGPoint(x: position.x + velocity.dx, y: position.y + velocity.dy)
velocity = CGVector(dx: velocity.dx + acceleration.dx, dy: velocity.dy + acceleration.dy)
}
}
|
//
// IncomingAudioTableViewCell.swift
// OfficeChat
//
// Created by Vishal on 22/03/18.
// Copyright © 2018 Fugu-Click Labs Pvt. Ltd. All rights reserved.
//
import UIKit
import AVFoundation
class IncomingAudioTableViewCell: AudioTableViewCell {
@IBOutlet weak var downloadingIndicator: UIActivityIndicatorView!
@IBOutlet weak var senderNameLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// addTapGestureInNameLabel()
}
func setData(message: HippoMessage) {
setUIAccordingToTheme()
self.message = message
self.cellIdentifier = message.fileUrl ?? ""
setTime()
senderNameLabel.text = message.senderFullName
updateUI()
}
func setUIAccordingToTheme() {
timeLabel.text = ""
timeLabel.font = HippoConfig.shared.theme.dateTimeFontSize
timeLabel.textAlignment = .left
timeLabel.textColor = HippoConfig.shared.theme.timeTextColor
downloadingIndicator.stopAnimating()
bgView.layer.cornerRadius = HippoConfig.shared.theme.chatBoxCornerRadius
bgView.backgroundColor = HippoConfig.shared.theme.incomingChatBoxColor
bgView.layer.borderWidth = HippoConfig.shared.theme.chatBoxBorderWidth
bgView.layer.borderColor = HippoConfig.shared.theme.chatBoxBorderColor.cgColor
senderNameLabel.font = HippoConfig.shared.theme.senderNameFont
senderNameLabel.textColor = HippoConfig.shared.theme.senderNameColor
fileName.font = HippoConfig.shared.theme.incomingMsgFont
fileName.textColor = HippoConfig.shared.theme.incomingMsgColor
self.backgroundColor = UIColor.clear
}
func addTapGestureInNameLabel() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(nameTapped))
senderNameLabel.addGestureRecognizer(tapGesture)
}
@objc func nameTapped() {
// if let msg = message {
// interactionDelegate?.nameOnMessageTapped(msg)
// }
}
}
class AudioTableViewCell: MessageTableViewCell {
var cellIdentifier = ""
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var fullLengthLineview: UIView!
@IBOutlet weak var progressViewWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var bgView: UIView!
@IBOutlet weak var controlButton: UIButton!
@IBOutlet weak var totalTimeLabel: UILabel!
@IBOutlet weak var audioPlayedTimeLabel: UILabel!
@IBOutlet weak var audiocompletionProgressView: UIView!
@IBOutlet weak var fileName: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
addNotificationObservers()
}
func addNotificationObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(fileDownloadCompleted(_:)), name: Notification.Name.fileDownloadCompleted, object: nil)
}
@objc func fileDownloadCompleted(_ notification: Notification) {
guard let url = notification.userInfo?[DownloadManager.urlUserInfoKey] as? String else {
return
}
if message?.fileUrl == url {
updateDownloadProgressView()
updateButtonAccordingToStatus()
}
}
func updateUI() {
updateButtonAccordingToStatus()
self.updateProgressBarView()
updateLabels()
updateDownloadProgressView()
}
func updateButtonAccordingToStatus() {
controlButton.isHidden = isFileBeingDownloaded()
guard isFileDownloaded() else {
controlButton.setImage(HippoConfig.shared.theme.downloadIcon, for: .normal)
return
}
if AudioPlayerManager.shared.tag != cellIdentifier {
controlButton.setImage(HippoConfig.shared.theme.playIcon, for: .normal)
return
}
if AudioPlayerManager.shared.audioPlayer?.isPlaying == false {
controlButton.setImage(HippoConfig.shared.theme.playIcon, for: .normal)
} else {
controlButton.setImage(HippoConfig.shared.theme.pauseIcon, for: .normal)
}
}
func isFileDownloaded() -> Bool {
guard !self.cellIdentifier.isEmpty else {
return false
}
return DownloadManager.shared.isFileDownloadedWith(url: self.cellIdentifier)
}
func updateDownloadProgressView() {
if isFileBeingDownloaded() {
activityIndicator.isHidden = false
activityIndicator.startAnimating()
} else {
activityIndicator.stopAnimating()
}
}
func isFileBeingDownloaded() -> Bool {
return DownloadManager.shared.isFileBeingDownloadedWith(url: cellIdentifier)
}
func updateProgressBarView() {
DispatchQueue.main.async {
guard AudioPlayerManager.shared.tag == self.cellIdentifier else {
self.progressViewWidthConstraint.constant = 0
self.layoutIfNeeded()
return
}
let totalTime = round(AudioPlayerManager.shared.audioPlayer?.duration ?? 1)
let completedTime = round(AudioPlayerManager.shared.audioPlayer?.currentTime ?? 0)
let ratio = completedTime / totalTime
self.progressViewWidthConstraint.constant = CGFloat(ratio * Double(self.fullLengthLineview.frame.width))
self.layoutIfNeeded()
}
}
func updateLabels() {
DispatchQueue.main.async {
self.fileName.text = self.message!.fileName
guard AudioPlayerManager.shared.tag == self.cellIdentifier else {
self.totalTimeLabel.text = ""
self.audioPlayedTimeLabel.text = ""
return
}
let totalTime = round(AudioPlayerManager.shared.audioPlayer?.duration ?? 0)
let completedTime = round(AudioPlayerManager.shared.audioPlayer?.currentTime ?? 0)
self.totalTimeLabel.text = self.getMintues(from: totalTime) + ":" + self.getSeconds(from: totalTime)
self.audioPlayedTimeLabel.text = self.getMintues(from: completedTime) + ":" + self.getSeconds(from: completedTime)
}
}
func getSeconds(from timeInterval: Double) -> String {
guard isFileDownloaded() else {
return "--"
}
var seconds = "00"
guard timeInterval > 0 else {
return seconds
}
let sec = Int(timeInterval.truncatingRemainder(dividingBy: 60))
seconds = String.init(format: "%.2d", sec)
return seconds
}
func getMintues(from timeInterval: Double) -> String {
guard isFileDownloaded() else {
return "-"
}
var minutes = "0"
guard timeInterval > 0 else {
return minutes
}
let min = Int(timeInterval / 60)
minutes = "\(min)"
return minutes
}
func startDownloading() {
guard !cellIdentifier.isEmpty else {
return
}
let name = message?.fileName ?? ""
DownloadManager.shared.downloadFileWith(url: cellIdentifier, name: name)
updateDownloadProgressView()
updateButtonAccordingToStatus()
}
@IBAction func controlButtonAction(_ sender: Any) {
guard isFileDownloaded() else {
self.startDownloading()
return
}
if AudioPlayerManager.shared.tag == cellIdentifier {
AudioPlayerManager.shared.delegate = self
if AudioPlayerManager.shared.audioPlayer?.isPlaying == true {
AudioPlayerManager.shared.stop()
} else if AudioPlayerManager.shared.audioPlayer?.isPlaying == false {
AudioPlayerManager.shared.play()
}
updateButtonAccordingToStatus()
return
}
if let newInstance = AudioPlayerManager.getNewObject(with: cellIdentifier) {
AudioPlayerManager.shared = newInstance
AudioPlayerManager.shared.delegate = nil
}
AudioPlayerManager.shared.delegate = self
AudioPlayerManager.shared.play()
updateButtonAccordingToStatus()
}
}
extension AudioTableViewCell: AudioPlayerManagerDelegate {
func playerEnded(_ player: AVAudioPlayer) {
updateUI()
}
func timer(_ player: AVAudioPlayer) {
self.updateLabels()
self.updateProgressBarView()
}
}
|
//
// DetailViewController.swift
// Many To-Do Lists
//
// Created by Martijn de Jong on 03-10-16.
// Copyright © 2016 Martijn de Jong. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
private let db = DatabaseHelper()
var currentListId = Int64?()
var currentState = false
@IBOutlet weak var detailDescriptionLabel: UILabel!
@IBOutlet var inputTextField: UITextField!
@IBOutlet var tableView: UITableView!
@IBOutlet var stateButton: UIBarButtonItem!
@IBOutlet var navBarOutlet: UINavigationItem!
@IBAction func stateAction(sender: AnyObject) {
if currentState == false {
self.loadToDo(true)
if allArrays.currentArray! != [] {
currentState = true
stateButton.title = "To-Do's"
self.tableView.reloadData()
}
else {
self.loadToDo(false)
noToDoAlert()
}
}
else if currentState == true {
currentState = false
self.loadToDo(false)
stateButton.title = "Checked"
self.tableView.reloadData()
}
}
@IBAction func inputAction(sender: AnyObject) {
if inputTextField.text! != "" {
do {
try self.db?.createToDo(inputTextField.text!, state: false, listid: currentListId!)
inputTextField.text! = ""
currentState = true
stateAction(inputTextField)
}
catch {
print(error)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.configureView()
if detailItem != nil {
currentListId = db?.getListId(detailItem as! String)
}
else if detailItem == nil {
currentListId = 0
}
loadToDo(false)
}
func configureView() {
if let detail = self.detailItem {
if let label = self.detailDescriptionLabel {
label.text = detail.description
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
var detailItem: AnyObject? {
didSet {
self.configureView()
}
}
func noToDoAlert () {
let alertController = UIAlertController(title: "Oops!", message: "No to-do's checked yet.", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { (result : UIAlertAction) -> Void in }
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
func loadToDo(state: Bool) {
do {
allArrays.currentArray = try self.db?.checkState(currentListId!, stateCheck: state)
} catch {
print(error)
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allArrays.currentArray!.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("todoCell", forIndexPath: indexPath)
cell.textLabel!.text = (allArrays.currentArray![indexPath.row])[1]
if currentState == true {
view.backgroundColor = UIColor(red:0.00, green:1.00, blue:0.76, alpha:1.0)
stateButton.tintColor = UIColor(red:1.00, green:0.00, blue:0.36, alpha:1.0)
}
else if currentState == false {
view.backgroundColor = UIColor(red:1.00, green:0.00, blue:0.36, alpha:1.0)
stateButton.tintColor = UIColor(red:0.00, green:1.00, blue:0.76, alpha:1.0)
}
return cell
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .Normal, title: "Delete") { action, index in
do {
try self.db?.deleteToDo(Int64(allArrays.currentArray![indexPath.row][0])!)
self.loadToDo(self.currentState)
self.tableView.reloadData()
} catch {
print(error)
}
}
delete.backgroundColor = UIColor(red:1.00, green:0.00, blue:0.36, alpha:1.0)
if currentState == false {
let check = UITableViewRowAction(style: .Normal, title: "Check Off") { action, index in
do {
try self.db?.changeState(allArrays.currentArray![indexPath.row][1])
self.loadToDo(false)
self.tableView.reloadData()
} catch {
print(error)
}
}
check.backgroundColor = UIColor(red:0.00, green:1.00, blue:0.76, alpha:1.0)
return [check, delete]
}
return [delete]
}
}
|
//
// waitingScene.swift
// newblackjack
//
// Created by Kohei Nakai on 2017/03/17.
// Copyright © 2017年 NakaiKohei. All rights reserved.
//
import SpriteKit
import GameplayKit
class waitingScene: SKScene {
let Label = SKLabelNode(fontNamed: "HiraginoSans-W6")
let breakButton=UIButton() //対戦中じゃないのに対戦中から移動しないとき用
let cancelButton=UIButton()
let nets=net()
var last:CFTimeInterval! //前に更新した時間
var didfirst=false
static var sendstart=false //ダブルwaiting対策→net.swiftのreceive()
static var dobreak=false //受信と同時に働くのを防ぐため?
let queue = DispatchQueue.main//メインスレッド
override func didMove(to view: SKView) {
let uuid1=UIDevice.current.identifierForVendor!.uuidString //識別子
let start=uuid1.startIndex
let end=uuid1.index(start, offsetBy: 4)
net.uuid=String(uuid1[start...end])
backgroundColor=SKColor.init(red: 0.8, green: 0.3, blue: 0.3, alpha: 0.3)
Label.text = "Waiting..."
Label.fontSize = 45
Label.position = CGPoint(x:self.frame.midX, y:self.frame.midY - 20)
self.addChild(Label)
self.cancelButton.frame = CGRect(x: 0,y: 0,width: 160,height: 30)
self.cancelButton.backgroundColor = UIColor.gray
self.cancelButton.layer.masksToBounds = true
self.cancelButton.setTitle("キャンセル", for: UIControlState())
self.cancelButton.setTitleColor(UIColor.white, for: UIControlState())
self.cancelButton.setTitle("キャンセル", for: UIControlState.highlighted)
self.cancelButton.setTitleColor(UIColor.black, for: UIControlState.highlighted)
self.cancelButton.layer.position = CGPoint(x: 100, y:self.view!.frame.height-20)
self.cancelButton.addTarget(self, action: #selector(self.onClickBreakButton(_:)), for: .touchUpInside) //動作はbreakButtonと同じ
self.cancelButton.addTarget(self, action: #selector(self.touchDownCancelButton(_:)), for: .touchDown)
self.cancelButton.addTarget(self, action: #selector(self.enableButtons(_:)), for: .touchUpOutside)
self.view!.addSubview(self.cancelButton)
}
override func update(_ currentTime: CFTimeInterval) {
// Called before each frame is rendered
// lastが未定義ならば、今の時間を入れる。
if last == nil{
last = currentTime
}
// 3秒おきに行う処理をかく。(1秒だと到着順番が入れ替わりやすい)
if last + 1 <= currentTime {
queue.async { //3秒以上たっても処理が終わるまで次の処理を行わない
if waitingScene.dobreak==true{
Game.state = .br
//クラス変数を初期化
Game.pcards.removeAll()
Game.deckCards.removeAll()
Game.ccards.removeAll()
self.nets.sendData()
let gameScene = LaunchScene(size: self.view!.bounds.size) // create your new scene
let transition = SKTransition.fade(withDuration: 1.0) // create type of transition (you can check in documentation for more transtions)
gameScene.scaleMode = SKSceneScaleMode.fill
self.view!.presentScene(gameScene, transition: transition) //LaunchSceneに移動
self.breakButton.isHidden=true
self.cancelButton.isHidden=true
waitingScene.dobreak=false
self.didfirst=false
net.fLastId=0
}else{
let tmp=Game.state //更新前の状態
self.nets.receiveData() //更新(Gameに反映)
if net.isLatest==true{
if (Game.state == .start && tmp == .waiting) || (Game.state == .ready && tmp == .start) {//こっちがwaitingで向こうからstart(p1turn???)が帰ってきたとき(didfirstより前に行う)
self.breakButton.isHidden=true
self.cancelButton.isHidden=true
let gameScene:loadingScene = loadingScene(size: self.view!.bounds.size) // create your new scene
let transition = SKTransition.fade(withDuration: 0.3) // create type of transition (you can check in documentation for more transtions)
gameScene.scaleMode = SKSceneScaleMode.fill
self.view!.presentScene(gameScene, transition: transition) //loadingSceneに移動
}
// if Game.state=="p2turn" && tmp=="p1turn"{//2つ進んでいたらloadingSceneを飛ばす(片方が進め過ぎるとバグるので、起こらないように仕様変更)
// if net.dealer==2{ //ありえないはず
// let gameScene:Netp1Scene = Netp1Scene(size: self.view!.bounds.size) // create your new scene
// let transition = SKTransition.fade(withDuration: 1.0) // create type of transition (you can check in documentation for more transtions)
// gameScene.scaleMode = SKSceneScaleMode.fill
// self.view!.presentScene(gameScene, transition: transition) //Netp1Sceneに移動
// }else if net.dealer==1{
// let gameScene:Netp2Scene = Netp2Scene(size: self.view!.bounds.size) // create your new scene
// let transition = SKTransition.fade(withDuration: 1.0) // create type of transition (you can check in documentation for more transtions)
// gameScene.scaleMode = SKSceneScaleMode.fill
// self.view!.presentScene(gameScene, transition: transition) //Netp2Sceneに移動
// }else{
// print("dealerの値が\(net.dealer)です。")
// exit(1)
// }
// }
if self.didfirst==false{//最初だけ行うべき内容?
if Game.state == .end||Game.state == .br{
Game.state = .waiting
self.nets.sendData()
self.Label.text = "Waiting..."
self.breakButton.isHidden=true
}else if Game.state == .waiting{ //誰かが待っていたら→p2
self.cancelButton.isHidden=true
Game.state = .start
self.nets.sendData()
Thread.sleep(forTimeInterval: 3.0)
let gameScene:preparingScene = preparingScene(size: self.view!.bounds.size) // create your new scene
let transition = SKTransition.fade(withDuration: 0.3) // create type of transition (you can check in documentation for more transtions)
gameScene.scaleMode = SKSceneScaleMode.fill
self.view!.presentScene(gameScene, transition: transition) //preparingSceneに移動
}else{
self.Label.text="対戦中"
self.breakButton.frame = CGRect(x: 0,y: 0,width: 200,height: 40)
self.breakButton.backgroundColor = UIColor.red;
self.breakButton.layer.masksToBounds = true
self.breakButton.setTitle("強制終了", for: UIControlState())
self.breakButton.setTitleColor(UIColor.white, for: UIControlState())
self.breakButton.setTitle("強制終了", for: UIControlState.highlighted)
self.breakButton.setTitleColor(UIColor.black, for: UIControlState.highlighted)
self.breakButton.layer.cornerRadius = 20.0
self.breakButton.layer.position = CGPoint(x: self.view!.frame.width-100, y:self.view!.frame.height-20)
self.breakButton.addTarget(self, action: #selector(self.onClickBreakButton(_:)), for: .touchUpInside)
self.breakButton.addTarget(self, action: #selector(self.touchDownBreakButton(_:)), for: .touchDown)
self.breakButton.addTarget(self, action: #selector(self.enableButtons(_:)), for: .touchUpOutside)
self.view!.addSubview(self.breakButton)
}
self.didfirst=true
}
if (Game.state == .end)||(Game.state == .br){//??
Game.state = .waiting
self.nets.sendData()
self.Label.text = "Waiting..."
self.breakButton.isHidden=true
}
if waitingScene.sendstart==true{
self.cancelButton.isHidden=true
Game.state = .start
waitingScene.sendstart=false
self.nets.sendData()
let gameScene:preparingScene = preparingScene(size: self.view!.bounds.size) // create your new scene
let transition = SKTransition.fade(withDuration: 0.3) // create type of transition (you can check in documentation for more transtions)
gameScene.scaleMode = SKSceneScaleMode.fill
self.view!.presentScene(gameScene, transition: transition) //preparingSceneに移動
}
}//
}
self.last = currentTime
}
}
}
@objc func onClickBreakButton(_ sender : UIButton){
waitingScene.dobreak=true
}
//同時押し対策
@objc func touchDownBreakButton(_ sender: UIButton){ //他のボタンをdisableする
cancelButton.isEnabled=false
}
@objc func touchDownCancelButton(_ sender: UIButton){ //他のボタンをdisableする
breakButton.isEnabled=false
}
@objc func enableButtons(_ sender:UIButton){
breakButton.isEnabled=true
cancelButton.isEnabled=true
}
}
|
//
// AllPlayers.swift
// ETBAROON
//
// Created by imac on 9/28/17.
// Copyright © 2017 IAS. All rights reserved.
//
import UIKit
class AllPlayers: NSObject {
var FirstName: String = ""
var LastName: String = ""
var url: String = ""
var CaptainId: String = ""
var CurrentTeamId: String = ""
var fldAppPlayerID: String = ""
}
|
//
// ViewController.swift
// Count
//
// Created by Tommy on 2019/04/07.
// Copyright © 2019 Tommy. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var number : Int = 0
@IBOutlet var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
label.layer.cornerRadius = 60
label.clipsToBounds = true
}
@IBAction func plus() {
number = number + 1
change()
}
@IBAction func minus(_ sender: Any) {
number = number - 1
change()
}
@IBAction func reset(_ sender: Any) {
number = 0
change()
}
//端末を振った時にカウントを増やす。
override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
number = number + 1
change()
}
func change() {
if number > 10 {
label.textColor = UIColor.red
} else if number < 0 {
label.textColor = UIColor.blue
} else {
label.textColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
}
label.text = String(number)
}
}
|
//
// MainRouter.swift
// carWash
//
// Created by Juliett Kuroyan on 18.11.2019.
// Copyright © 2019 VooDooLab. All rights reserved.
//
import UIKit
class MainRouter {
weak var view: MainViewController?
weak var tabBarController: MainTabBarController?
init(view: MainViewController?) {
self.view = view
}
}
// MARK: - MainRouterProtocol
extension MainRouter: MainRouterProtocol {
func presentPaymentView() {
guard let view = view else { return }
let configurator = PaymentConfigurator()
let vc = configurator.viewController
if let navigationController = view.navigationController {
navigationController.pushViewController(vc, animated: true)
} else {
vc.modalPresentationStyle = .fullScreen
view.present(vc, animated: true, completion: nil)
}
}
func popToAuthorization() {
tabBarController?.navigationController?.popViewController(animated: true)
}
func presentCityView() {
guard let view = view else { return }
let configurator = CitiesConfigurator(cityChanged: nil)
let vc = configurator.viewController
view.navigationController?.pushViewController(vc, animated: true)
}
func presentOperationsView() {
guard let view = view else { return }
let configurator = OperationsConfigurator()
let vc = configurator.viewController
view.navigationController?.pushViewController(vc, animated: true)
}
}
|
//
// DashBoardElement_AvSpeed.swift
// KayakFirst Ergometer E2
//
// Created by Balazs Vidumanszki on 2017. 02. 18..
// Copyright © 2017. Balazs Vidumanszki. All rights reserved.
//
import Foundation
class DashBoardElement_AvSpeed: DashBoardElementBase {
static let tagInt = 8
override func getStringFormatter() -> String {
return "%.1f"
}
override func getValue() -> Double {
return UnitHelper.getSpeedValue(metricValue: telemetry.speed_av)
}
override func getTitleMetric() -> String {
return getString("dashboard_outdoor_title_av_speed_metric")
}
override func getTitleImperial() -> String {
return getString("dashboard_outdoor_title_av_speed_imperial")
}
override func getTitleOneLineMetric() -> String {
return getString("dashboard_title_av_speed_metric")
}
override func getTitleOneLineImperial() -> String {
return getString("dashboard_title_av_speed_imperial")
}
override func getTagInt() -> Int {
return DashBoardElement_AvSpeed.tagInt
}
override func isMetric() -> Bool {
return UnitHelper.isMetricDistance()
}
}
|
/**
Copyright IBM Corporation 2016
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
extension String: Convertible {}
extension Int: Convertible {}
extension Float: Convertible {}
extension Bool: Convertible {}
public protocol Result {
var success: Bool { get }
var asRows: [[String: Any]]? { get }
var asPrepared: [Byte]? { get }
var asError: Error? { get }
}
public enum DataType: Int {
case custom = 0x0000
case ASCII = 0x0001
case bigInt = 0x0002
case blob = 0x0003
case boolean = 0x0004
case counter = 0x0005
case decimal = 0x0006
case double = 0x0007
case float = 0x0008
case int = 0x0009
case text = 0x000A
case timestamp = 0x000B
case uuid = 0x000C
case varChar = 0x000D
case varInt = 0x000E
case timeUUID = 0x000F
case inet = 0x0010
case list = 0x0020
case map = 0x0021
case set = 0x0022
case UDT = 0x0030
case tuple = 0x0031
}
public enum Consistency: UInt16 {
case any = 0x0000
case one = 0x0001
case two = 0x0002
case three = 0x0003
case quorum = 0x0004
case all = 0x0005
case local_quorum = 0x0006
case each_quorum = 0x0007
case serial = 0x0008
case local_serial = 0x0009
case local_one = 0x000A
case unknown = 0x000F
}
public enum BatchType: Byte {
case logged = 0x00
case unlogged = 0x01
case counter = 0x02
}
public enum OrmErrors: Error {
case general
}
public func changeDictType<T>(dict: [T: Any]) -> [String: Any] {
var cond = [String: Any]()
for (key, value) in dict {
cond[String(describing: key)] = value
}
return cond
}
func packType(_ item: Any) -> String? {
switch item {
case let val as Int : return String(describing: val)
case let val as String : return "'\(val)'"
case let val as Float : return String(describing: val)
case let val as Double : return String(describing: val)
case let val as Decimal : return String(describing: val)
case let val as Bool : return String(describing: val)
default: return nil
}
}
func packColumnData(key: String, mirror: Mirror) -> String {
var str = ""
for child in mirror.children {
switch child.value {
case is Int : str += child.label! + " int "
case is String : str += child.label! + " text "
case is Float : str += child.label! + " float "
case is Double : str += child.label! + " double "
case is Decimal : str += child.label! + " decimal "
case is Bool : str += child.label! + " bool "
default: break
}
child.label! == key ? (str += "PRIMARY KEY,") : (str += ",")
}
return str
}
func packPairs(_ pairs: [String: Any], mirror: Mirror? = nil) -> String {
return pairs.map{key,val in key + "=" + packType(val)! }.joined(separator: ", ")
}
func packKeys(_ dict: [String: Any]) -> String {
return dict.map {key, value in key }.joined(separator: ", ")
}
func packKeys(_ mirror: Mirror) -> String {
return mirror.children.map { $0.label! }.joined(separator: ", ")
}
func packValues(_ dict: [String: Any]) -> String {
return dict.map {key, value in packType(value)! }.joined(separator: ", ")
}
func packValues(_ mirror: Mirror) -> String {
return mirror.children.map{ packType($0.value)! }.joined(separator: ", ")
}
|
//
// ViewCustomerViewController.swift
// BankingSystemiOS
//
// Created by Ashish on 2019-07-18.
// Copyright © 2019 Richu Jain. All rights reserved.
//
import UIKit
import FirebaseDatabase
class UserInfoViewController: UIViewController {
@IBOutlet weak var txtAccountNumber: UILabel!
@IBOutlet weak var txtAccountBalance: UILabel!
@IBOutlet weak var txtAccountType: UILabel!
@IBOutlet weak var txtCustomerName: UITextField!
@IBOutlet weak var txtAddress: UITextField!
@IBOutlet weak var txtContactNumber: UITextField!
@IBOutlet weak var txtEmailId: UITextField!
@IBOutlet weak var txtBirthDate: UITextField!
@IBOutlet weak var lblAccountType: UILabel!
@IBOutlet weak var txtPhotoAddressIdProof: UITextField!
@IBOutlet weak var txtBankBranch: UITextField!
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
var personId: String = ""
var ref: DatabaseReference!
var flag:Int = 0
typealias completion = (_ isFinished:Bool) -> Void
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController!.navigationBar.isHidden = true;
ref = Database.database().reference()
self.ref.child("customers").child(self.personId).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let customerName = value?["name"] as? String ?? ""
let address = value?["address"] as? String ?? ""
let emailId = value?["emailid"] as? String ?? ""
let birthDate = value?["birthdate"] as? String ?? ""
let photoAddressProofId = value?["photoaddressproofid"] as? String ?? ""
let contactNumber = value?["contactnumber"] as? String ?? ""
self.txtCustomerName.text = customerName
self.txtAddress.text = address
self.txtContactNumber.text = contactNumber
self.txtEmailId.text = emailId
self.txtBirthDate.text = birthDate
self.txtPhotoAddressIdProof.text = photoAddressProofId
//let user = User(username: username)
// ...
}) { (error) in
print(error.localizedDescription)
}
//print("Account Type is \(getAccountType(ref: ref))")
getAccountType(ref: ref, completionHandler: { (isFinished) in
if isFinished {
print("Account Type is \(self.flag)")
}
})
var accountType: String = ""
if flag == 1{
accountType = "savings"
}
else{
accountType = "current"
}
self.ref.child("bank").child(accountType).child(self.personId).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
self.txtAccountNumber.text = "Account Number : \(self.personId)"
self.txtAccountType.text = "Account Type : \(accountType)"
let accountBalance = value?["accountbalance"] as? String ?? ""
self.txtAccountBalance.text = "Account Balance : \(accountBalance)"
//let user = User(username: username)
// ...
}) { (error) in
print(error.localizedDescription)
}
// Do any additional setup after loading the view.
}
func getAccountType(ref: DatabaseReference, completionHandler: @escaping completion) {
print("Person ID is \(self.personId)")
flag = 0
ref.child("bank").child("savings").child(personId).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
var acc = "0"
acc = value?["accountnumber"] as? String ?? ""
if Int(acc) ?? 0 > 0{
self.flag = 1
//return "current"
completionHandler(true)
}
//let user = User(username: username)
// ...
}) { (error) in
print(error.localizedDescription)
}
ref.child("bank").child("current").child(personId).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
var acc = "0"
acc = value?["accountnumber"] as? String ?? ""
if Int(acc) ?? 0 > 0{
self.flag = 2
//return "savings"
completionHandler(true)
}
//let user = User(username: username)
// ...
}) { (error) in
print(error.localizedDescription)
}
}
/*
// 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.
}
*/
@IBAction func btnDone(_ sender: Any) {
self.performSegue(withIdentifier: "UserInfoToEmployeeHome", sender: self)
}
}
|
//
// Onboarding.swift
// MC7-Camp
//
// Created by Amaury A V A Souza on 16/07/20.
// Copyright © 2020 Paula Leite. All rights reserved.
//
import Foundation
import SpriteKit
import CoreData
import TVServices
class Onboarding: SKScene {
var familyMembers: [FamilyMember] = []
var familyMember: FamilyMember?
var families: [Family] = []
var family: Family?
var background = SKSpriteNode()
var increaseAmountOfMembersButton = MenuButtonNode()
var decreaseAmountOfMembersButton = MenuButtonNode()
var doneSettingUpButton = MenuButtonNode()
var buttons = [MenuButtonNode]()
var numberOfFamilyMembers: Int64 = 2
var context: NSManagedObjectContext?
var askAmountOfMembersLabel = SKLabelNode()
var amountOfMembersLabel = SKLabelNode()
var increaseAmountOfMembersLabel = SKLabelNode(fontNamed: "Pompiere-Regular")
var decreaseAmountOfMembersLabel = SKLabelNode(fontNamed: "Pompiere-Regular")
var doneSettingUpLabel = SKLabelNode(fontNamed: "Pompiere-Regular")
var didGoToOnboarding = Bool()
override func didMove(to view: SKView) {
context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
setupBackground()
setupUI()
addTapGestureRecognizer()
}
func setupBackground() {
background = SKSpriteNode(imageNamed: "mainMenuBackground")
background.size = self.size
background.position = CGPoint(x: 960, y: 540)
background.zPosition = -1
addChild(background)
let signForText = SKSpriteNode(imageNamed: "textSign")
signForText.size = CGSize(width: self.size.width/2, height: self.size.height/4)
signForText.position = CGPoint(x: 960, y: 950)
signForText.zPosition = 0
addChild(signForText)
}
func setupUIText() {
askAmountOfMembersLabel.fontName = "Pompiere-Regular"
askAmountOfMembersLabel.fontColor = .black
askAmountOfMembersLabel.fontSize = 50
askAmountOfMembersLabel.text = NSLocalizedString("Ask_Amount_Members", comment: "Asks abuout the amount of members in the family.")
askAmountOfMembersLabel.position = CGPoint(x: 960, y: 980)
askAmountOfMembersLabel.zPosition = 1
addChild(askAmountOfMembersLabel)
amountOfMembersLabel.fontName = "Pompiere-Regular"
amountOfMembersLabel.fontColor = .black
amountOfMembersLabel.fontSize = 120
amountOfMembersLabel.text = String(numberOfFamilyMembers)
amountOfMembersLabel.position = CGPoint(x: 960, y: 440)
amountOfMembersLabel.zPosition = 0
addChild(amountOfMembersLabel)
increaseAmountOfMembersLabel.fontColor = .black
increaseAmountOfMembersLabel.numberOfLines = 0
increaseAmountOfMembersLabel.fontSize = 70
increaseAmountOfMembersLabel.text = NSLocalizedString("Increase_Amount", comment: "Button to increase amount of players.")
increaseAmountOfMembersLabel.position = CGPoint(x: 1420, y: 400)
increaseAmountOfMembersLabel.zPosition = 1
addChild(increaseAmountOfMembersLabel)
decreaseAmountOfMembersLabel.fontColor = .black
decreaseAmountOfMembersLabel.numberOfLines = 0
decreaseAmountOfMembersLabel.fontSize = 70
decreaseAmountOfMembersLabel.text = NSLocalizedString("Decrease_Amount", comment: "Button to increase amount of players.")
decreaseAmountOfMembersLabel.position = CGPoint(x: 517.5, y: 400)
decreaseAmountOfMembersLabel.zPosition = 1
addChild(decreaseAmountOfMembersLabel)
doneSettingUpLabel.fontColor = .black
doneSettingUpLabel.numberOfLines = 0
doneSettingUpLabel.fontSize = 60
doneSettingUpLabel.text = NSLocalizedString("Play_Button", comment: "Play button text.")
doneSettingUpLabel.position = CGPoint(x: 1795, y: 105)
doneSettingUpLabel.zPosition = 1
addChild(doneSettingUpLabel)
}
func setupUI() {
setupUIText()
increaseAmountOfMembersButton = MenuButtonNode(name: "increaseButtonImage")
increaseAmountOfMembersButton.position = CGPoint(x: 1402.5, y: 440)
increaseAmountOfMembersButton.zPosition = 0
addChild(increaseAmountOfMembersButton)
buttons.append(increaseAmountOfMembersButton)
decreaseAmountOfMembersButton = MenuButtonNode(name: "decreaseButtonImage")
decreaseAmountOfMembersButton.position = CGPoint(x: 517.5, y: 440)
addChild(decreaseAmountOfMembersButton)
buttons.append(decreaseAmountOfMembersButton)
doneSettingUpButton = MenuButtonNode(name: "playButton")
doneSettingUpButton.position = CGPoint(x: 1775, y: 120)
addChild(doneSettingUpButton)
buttons.append(doneSettingUpButton)
for button in buttons {
button.isUserInteractionEnabled = true
}
}
func updateNumberOfMembersLabel() {
amountOfMembersLabel.text = String(numberOfFamilyMembers)
}
func addTapGestureRecognizer() {
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.tapped(sender:)))
self.view?.addGestureRecognizer(tapRecognizer)
}
override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
let prevItem = context.previouslyFocusedItem
let nextItem = context.nextFocusedItem
if let prevButton = prevItem as? MenuButtonNode {
prevButton.buttonDidLoseFocus()
}
if let nextButton = nextItem as? MenuButtonNode {
nextButton.buttonDidGetFocus()
}
}
@objc func tapped(sender: AnyObject) {
if let focussedItem = UIScreen.main.focusedItem as? MenuButtonNode {
if focussedItem == decreaseAmountOfMembersButton {
if numberOfFamilyMembers > 2 {
numberOfFamilyMembers -= 1
updateNumberOfMembersLabel()
}
} else if focussedItem == increaseAmountOfMembersButton {
if numberOfFamilyMembers < 6 {
numberOfFamilyMembers += 1
updateNumberOfMembersLabel()
}
} else {
saveData()
guard let size = view?.frame.size else { return }
let scene = MainMenu(size: size)
loadScreens(scene: scene)
}
}
}
func saveData() {
do {
guard let context = context else { return }
families = try context.fetch(Family.fetchRequest())
familyMembers = try context.fetch(FamilyMember.fetchRequest())
if self.numberOfFamilyMembers != 0 {
guard let family = NSEntityDescription.insertNewObject(forEntityName: "Family", into: context) as? Family else { return }
family.numberOfFamilyMembers = self.numberOfFamilyMembers
var i = 0
let nameShack = "shack"
let nameFlag = "flag"
while i < family.numberOfFamilyMembers {
guard let familyMember = NSEntityDescription.insertNewObject(forEntityName: "FamilyMember", into: context) as? FamilyMember else { return }
let nameShack = nameShack + "\(i + 1)"
familyMember.shackName = nameShack
let nameFlag = nameFlag + "\(i + 1)"
familyMember.flagName = nameFlag
familyMember.timesPlayedBasketballGame = 0.0
familyMember.timesPlayedMessGame = 0.0
familyMember.family = family
self.familyMembers.append(familyMember)
i = i + 1
}
self.families.append(family)
}
(UIApplication.shared.delegate as! AppDelegate).saveContext()
didGoToOnboarding = true
} catch let error {
print(error.localizedDescription)
}
}
func loadScreens(scene: SKScene) {
/* Grab reference to our SpriteKit view */
guard let skView = self.view as SKView? else {
print("Could not get Skview")
return
}
skView.showsFPS = false
skView.showsNodeCount = false
/* 3) Ensure correct aspect mode */
scene.scaleMode = .aspectFill
/* 4) Start game scene */
skView.presentScene(scene)
}
}
|
//
// MKMapView+Extension.swift
// Guard
//
// Created by Idan Moshe on 22/09/2020.
// Copyright © 2020 Idan Moshe. All rights reserved.
//
import MapKit
extension MKMapView {
/// SwifterSwift: Dequeue reusable MKAnnotationView using class type
///
/// - Parameters:
/// - name: MKAnnotationView type.
/// - Returns: optional MKAnnotationView object.
func dequeueReusableAnnotationView<T: MKAnnotationView>(withClass name: T.Type) -> T? {
return dequeueReusableAnnotationView(withIdentifier: String(describing: name)) as? T
}
/// SwifterSwift: Register MKAnnotationView using class type
///
/// - Parameter name: MKAnnotationView type.
@available(iOS 11.0, tvOS 11.0, macOS 10.13, *)
func register<T: MKAnnotationView>(annotationViewWithClass name: T.Type) {
register(T.self, forAnnotationViewWithReuseIdentifier: String(describing: name))
}
/// SwifterSwift: Dequeue reusable MKAnnotationView using class type
///
/// - Parameters:
/// - name: MKAnnotationView type.
/// - annotation: annotation of the mapView.
/// - Returns: optional MKAnnotationView object.
@available(iOS 11.0, tvOS 11.0, macOS 10.13, *)
func dequeueReusableAnnotationView<T: MKAnnotationView>(withClass name: T.Type,
for annotation: MKAnnotation) -> T? {
guard let annotationView = dequeueReusableAnnotationView(
withIdentifier: String(describing: name),
for: annotation) as? T else {
fatalError("Couldn't find MKAnnotationView for \(String(describing: name))")
}
return annotationView
}
}
|
//
// myMealsTests.swift
// myMealsTests
//
// Created by Marc Felden on 29.02.16.
// Copyright © 2016 madeTK.com. All rights reserved.
//
import XCTest
@testable import myMeals
class myMealsTests: XCTestCase
{
override func setUp()
{
super.setUp() }
override func tearDown()
{
super.tearDown()
}
}
|
//
// AuthService.swift
// VkFeedExample
//
// Created by Станислав Шияновский on 9/28/19.
// Copyright © 2019 Станислав Шияновский. All rights reserved.
//
import Foundation
import VKSdkFramework
public protocol AuthServiceDelegate: class {
func authServiceShouldShow(_ viewController: UIViewController)
func authServiceSignIn()
func authServiceDidSignInFail()
}
final public class AuthService: NSObject {
public static let shared = AuthService()
// Data
public var token: String? {
return VKSdk.accessToken()?.accessToken
}
public var userId: String? {
return VKSdk.accessToken()?.userId
}
private let appId = "7151795"
private let vkSdk: VKSdk
public weak var delegate: AuthServiceDelegate!
private override init() {
vkSdk = VKSdk.initialize(withAppId: appId)
super.init()
vkSdk.register(self)
vkSdk.uiDelegate = self
}
public func wakeupSession() {
let scope = ["wall", "friends"]
VKSdk.wakeUpSession(scope) { [delegate] (state, error) in
if state == VKAuthorizationState.authorized {
print("VKAuthorizationState.authorized")
delegate?.authServiceSignIn()
} else if state == VKAuthorizationState.initialized {
print("VKAuthorizationState.initialized")
VKSdk.authorize(scope)
} else {
let description = error?.localizedDescription ?? ""
print("auth problems, state \(state), error \(description)")
delegate?.authServiceDidSignInFail()
}
}
}
}
extension AuthService: VKSdkDelegate {
public func vkSdkAccessAuthorizationFinished(with result: VKAuthorizationResult!) {
if result.token != nil {
delegate.authServiceSignIn()
}
}
public func vkSdkUserAuthorizationFailed() {
print(#function)
delegate.authServiceDidSignInFail()
}
}
extension AuthService: VKSdkUIDelegate {
public func vkSdkShouldPresent(_ controller: UIViewController!) {
print(#function)
delegate.authServiceShouldShow(controller)
}
public func vkSdkNeedCaptchaEnter(_ captchaError: VKError!) {
print(#function)
}
}
|
//
// AudioFile.swift
// Sampler
//
// Created by Daniel Song on 9/9/16.
// Copyright © 2016 Daniel Song. All rights reserved.
//
import Foundation
/*
*
* THIS CLASS IS NOT BEING USED FOR NOW. WILL ADD LATER.
* TABLEVIEW CELLS CURRENTLY ONLY DISPLAY FILE NAMES.
*/
class AuidoFile: NSObject{
var name: String
var date: Date
var audioURL: URL
init(name: String, date: Date, audioURL: URL){
self.name = name
self.date = date
self.audioURL = audioURL
super.init()
}
}
|
//
// NewChatRoomVC.swift
// FirebaseChat
//
// Created by Chad Parker on 2020-06-09.
// Copyright © 2020 Chad Parker. All rights reserved.
//
import UIKit
class NewChatRoomVC: UIViewController {
var modelController: ModelController!
@IBOutlet weak var newChatRoomTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func cancel(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func done(_ sender: Any) {
guard let chatRoomName = newChatRoomTextField.text, !chatRoomName.isEmpty else { return }
modelController.createChatRoom(chatRoomName)
dismiss(animated: true, completion: nil)
}
}
|
//
// StatusItemManange.swift
// SwiftQR
//
// Created by 马权 on 2017/3/14.
// Copyright © 2017年 马权. All rights reserved.
//
import Foundation
enum RightMouseMenu: String {
case cleanHistory = "Clean History"
case hotkey = "Hot Key"
case quit = "Quit"
}
class StatusItemManange {
fileprivate var _statusItem: NSStatusItem = NSStatusBar.system().statusItem(withLength: NSSquareStatusItemLength)
fileprivate var _popver: NSPopover = NSPopover()
fileprivate var _mainViewController = QRMainViewController()
fileprivate var _settingWindowController: HotKeySettingWindowController?
init() {
_ = HotKeyCenter.shared.regist(observer: self, selector: #selector(self.hotKeyAction(event:)))
_statusItem.do {
$0.button?.target = self
$0.button?.action = #selector(self.statusItemAction(button:))
$0.button?.sendAction(on: [.rightMouseDown, .leftMouseDown])
$0.button?.image = NSImage(named: "StatusBarItemIcon")
}
_popver.do {
$0.contentViewController = _mainViewController
$0.behavior = .transient
}
}
fileprivate func showLeftClickPopver() {
if let button = _statusItem.button as NSButton? {
NSRunningApplication.current().activate(options: [.activateAllWindows, .activateIgnoringOtherApps])
_popver.show(relativeTo: NSRect.zero, of: button, preferredEdge: NSRectEdge.minY)
}
}
fileprivate func showRightClickMenu(on view: NSView) {
NSMenu(title: "Setting").with {
let cleanHistoryItem = NSMenuItem(title: RightMouseMenu.cleanHistory.rawValue,
action: #selector(cleanHistorAction(sender:)),
keyEquivalent: RightMouseMenu.cleanHistory.rawValue).with {
$0.target = self
}
let shortCutSettingItem = NSMenuItem(title: RightMouseMenu.hotkey.rawValue,
action: #selector(showSettingContoller(sender:)),
keyEquivalent: HotKeyCenter.shared.hotKey.keyCodeReadable.lowercased()).with {
$0.target = self
$0.keyEquivalentModifierMask = [.option]
}
let quitItem = NSMenuItem(title: RightMouseMenu.quit.rawValue,
action: #selector(quitAppAction(sender:)),
keyEquivalent: RightMouseMenu.quit.rawValue).with {
$0.target = self
}
$0.addItem(cleanHistoryItem)
$0.addItem(shortCutSettingItem)
$0.addItem(NSMenuItem.separator())
$0.addItem(quitItem)
}.do {
_statusItem.popUpMenu($0)
}
}
}
// MARK: - Public
extension StatusItemManange {
}
// MARK: - Action
private extension StatusItemManange {
/// statusItemClick
@objc func statusItemAction(button: NSButton) {
guard let event: NSEvent = NSApp.currentEvent else { return }
if event.type == NSEventType.leftMouseDown {
showLeftClickPopver()
}
else {
showRightClickMenu(on: button)
}
}
/// shortCut
@objc func hotKeyAction(event: NSEvent) {
if !_popver.isShown {
showLeftClickPopver()
}
else {
_popver.close()
}
}
/// clean History setting
@objc func cleanHistorAction(sender: Any) {
_statusItem.button?.highlight(false)
_mainViewController.cleanHistory()
}
/// shortCut setting
@objc func showSettingContoller(sender: NSMenuItem) {
_statusItem.button?.highlight(false)
if let window = _settingWindowController?.window as NSWindow?, window.isVisible {
return
}
NSRunningApplication.current().activate(options: [.activateAllWindows, .activateIgnoringOtherApps])
_settingWindowController = HotKeySettingWindowController.windowController()
_settingWindowController?.showWindow(self)
}
/// quit
@objc func quitAppAction(sender: Any) {
NSApp.terminate(self)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.