text stringlengths 8 1.32M |
|---|
//
// Copyright © 2021 Tasuku Tozawa. All rights reserved.
//
import Domain
protocol TagCollectionMenuBuildable {
func build(for tag: Tag) -> [TagCollection.MenuItem]
}
struct TagCollectionMenuBuilder {
// MARK: - Properties
private let storage: UserSettingsStorageProtocol
// MAKR: - Lifecycle
init(storage: UserSettingsStorageProtocol) {
self.storage = storage
}
}
extension TagCollectionMenuBuilder: TagCollectionMenuBuildable {
// MARK: - TagCollectionMenuBuildable
func build(for tag: Tag) -> [TagCollection.MenuItem] {
return [
.copy,
.rename,
tag.isHidden
? .reveal
: .hide(immediately: storage.readShowHiddenItems()),
.delete
]
}
}
|
//
// VersionTests.swift
// Server
//
// Created by Christopher Prince on 2/3/18.
//
//
import XCTest
@testable import Server
@testable import TestsCommon
import LoggerAPI
import Foundation
import ServerShared
class VersionTests: ServerTestCase {
override func setUp() {
super.setUp()
}
func testThatVersionGetsReturnedInHeaders() {
performServerTest { expectation in
// Use healthCheck just because it's a simple endpoint.
self.performRequest(route: ServerEndpoints.healthCheck) { response, dict in
XCTAssert(response!.statusCode == .OK, "Failed on healthcheck request")
// It's a bit odd, but Kitura gives a [String] for each http header key.
guard let versionHeaderArray = response?.headers[ServerConstants.httpResponseCurrentServerVersion], versionHeaderArray.count == 1 else {
XCTFail()
expectation.fulfill()
return
}
let versionString = versionHeaderArray[0]
let components = versionString.components(separatedBy: ".")
guard components.count == 3 else {
XCTFail("Didn't get three components in version: \(versionString)")
expectation.fulfill()
return
}
guard let _ = Int(components[0]),
let _ = Int(components[1]),
let _ = Int(components[2]) else {
XCTFail("All components were not integers: \(versionString)")
expectation.fulfill()
return
}
expectation.fulfill()
}
}
}
}
|
//
// Copyright (c) 2023 Related Code - https://relatedcode.com
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import MobileCoreServices
//-----------------------------------------------------------------------------------------------------------------------------------------------
class ImagePicker {
//-------------------------------------------------------------------------------------------------------------------------------------------
class func cameraPhoto(_ viewController: UIViewController, edit: Bool) {
let type = kUTTypeImage as String
if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
if let availableMediaTypes = UIImagePickerController.availableMediaTypes(for: .camera) {
if (availableMediaTypes.contains(type)) {
let imagePicker = UIImagePickerController()
imagePicker.mediaTypes = [type]
imagePicker.sourceType = .camera
if (UIImagePickerController.isCameraDeviceAvailable(.rear)) {
imagePicker.cameraDevice = .rear
} else if (UIImagePickerController.isCameraDeviceAvailable(.front)) {
imagePicker.cameraDevice = .front
}
imagePicker.allowsEditing = edit
imagePicker.showsCameraControls = true
imagePicker.delegate = viewController as? (UIImagePickerControllerDelegate & UINavigationControllerDelegate)
viewController.present(imagePicker, animated: true)
}
}
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------
class func cameraVideo(_ viewController: UIViewController, edit: Bool) {
let type = kUTTypeMovie as String
if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
if let availableMediaTypes = UIImagePickerController.availableMediaTypes(for: .camera) {
if (availableMediaTypes.contains(type)) {
let imagePicker = UIImagePickerController()
imagePicker.mediaTypes = [type]
imagePicker.sourceType = .camera
imagePicker.videoMaximumDuration = Appx.MaxVideo
if (UIImagePickerController.isCameraDeviceAvailable(.rear)) {
imagePicker.cameraDevice = .rear
} else if (UIImagePickerController.isCameraDeviceAvailable(.front)) {
imagePicker.cameraDevice = .front
}
imagePicker.allowsEditing = edit
imagePicker.showsCameraControls = true
imagePicker.delegate = viewController as? (UIImagePickerControllerDelegate & UINavigationControllerDelegate)
viewController.present(imagePicker, animated: true)
}
}
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------
class func cameraMulti(_ viewController: UIViewController, edit: Bool) {
let type1 = kUTTypeImage as String
let type2 = kUTTypeMovie as String
if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
if let availableMediaTypes = UIImagePickerController.availableMediaTypes(for: .camera) {
if (availableMediaTypes.contains(type1) && availableMediaTypes.contains(type2)) {
let imagePicker = UIImagePickerController()
imagePicker.mediaTypes = [type1, type2]
imagePicker.sourceType = .camera
imagePicker.videoMaximumDuration = Appx.MaxVideo
if (UIImagePickerController.isCameraDeviceAvailable(.rear)) {
imagePicker.cameraDevice = .rear
} else if (UIImagePickerController.isCameraDeviceAvailable(.front)) {
imagePicker.cameraDevice = .front
}
imagePicker.allowsEditing = edit
imagePicker.showsCameraControls = true
imagePicker.delegate = viewController as? (UIImagePickerControllerDelegate & UINavigationControllerDelegate)
viewController.present(imagePicker, animated: true)
}
}
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------
class func photoLibrary(_ viewController: UIViewController, edit: Bool) {
let type = kUTTypeImage as String
if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)) {
if let availableMediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary) {
if (availableMediaTypes.contains(type)) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.mediaTypes = [type]
imagePicker.allowsEditing = edit
imagePicker.delegate = viewController as? (UIImagePickerControllerDelegate & UINavigationControllerDelegate)
viewController.present(imagePicker, animated: true)
}
}
}
else if (UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum)) {
if let availableMediaTypes = UIImagePickerController.availableMediaTypes(for: .savedPhotosAlbum) {
if (availableMediaTypes.contains(type)) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .savedPhotosAlbum
imagePicker.mediaTypes = [type]
imagePicker.allowsEditing = edit
imagePicker.delegate = viewController as? (UIImagePickerControllerDelegate & UINavigationControllerDelegate)
viewController.present(imagePicker, animated: true)
}
}
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------
class func videoLibrary(_ viewController: UIViewController, edit: Bool) {
let type = kUTTypeMovie as String
if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)) {
if let availableMediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary) {
if (availableMediaTypes.contains(type)) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.mediaTypes = [type]
imagePicker.videoMaximumDuration = Appx.MaxVideo
imagePicker.allowsEditing = edit
imagePicker.delegate = viewController as? (UIImagePickerControllerDelegate & UINavigationControllerDelegate)
viewController.present(imagePicker, animated: true)
}
}
}
else if (UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum)) {
if let availableMediaTypes = UIImagePickerController.availableMediaTypes(for: .savedPhotosAlbum) {
if (availableMediaTypes.contains(type)) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .savedPhotosAlbum
imagePicker.mediaTypes = [type]
imagePicker.videoMaximumDuration = Appx.MaxVideo
imagePicker.allowsEditing = edit
imagePicker.delegate = viewController as? (UIImagePickerControllerDelegate & UINavigationControllerDelegate)
viewController.present(imagePicker, animated: true)
}
}
}
}
}
|
//
// ErrorMapper.swift
// InspireME
//
// Created by Brad Siegel on 4/20/16.
// Copyright © 2016 Brad Siegel. All rights reserved.
//
import Foundation
extension NSError {
func firebaseDescription() -> String {
var description: String
switch code {
case -5:
description = ErrorDescription.InvalidEmail.rawValue
case -6:
description = ErrorDescription.IncorrectPassword.rawValue
case -8:
description = ErrorDescription.UserNotFound.rawValue
case -9:
description = ErrorDescription.EmailTaken.rawValue
default:
description = "Oops, something went wrong."
}
return description
}
}
private enum ErrorDescription: String {
case EmailTaken = "This email address is already registered to an account."
case IncorrectPassword = "Invalid email/password."
case InvalidEmail = "Please enter a valid email/password."
case UserNotFound = "User not found."
}
|
//
// ViewController.swift
// SwiftDataStructures
//
// Created by Robin Kunde on 4/21/16.
// Copyright © 2016 Recoursive. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var swiftArrayPushLabel: UILabel!
@IBOutlet weak var swiftArrayPopLabel: UILabel!
@IBOutlet weak var nsArrayPushLabel: UILabel!
@IBOutlet weak var nsArrayPopLabel: UILabel!
@IBOutlet weak var genericStructPushLabel: UILabel!
@IBOutlet weak var genericStructPopLabel: UILabel!
@IBOutlet weak var genericStructNoOptionalPushLabel: UILabel!
@IBOutlet weak var genericStructNoOptionalPopLabel: UILabel!
@IBOutlet weak var structUInt32PushLabel: UILabel!
@IBOutlet weak var structUInt32PopLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func doTheThingButtonTapped(sender: AnyObject) {
let iterations = 10000000
//
var array = Array<UInt32>(count: 10000, repeatedValue: 0)
var startTime = CACurrentMediaTime()
for _ in 0..<iterations {
array.append(arc4random())
}
var pushTime = CACurrentMediaTime()
while array.popLast() != nil {
}
var popTime = CACurrentMediaTime()
swiftArrayPushLabel.text = String(format: "Push: %06fs", pushTime - startTime)
swiftArrayPopLabel.text = String(format: "Pop: %06fs", popTime - pushTime)
//
let nsarray = NSMutableArray(capacity: 10000)
startTime = CACurrentMediaTime()
for _ in 0..<iterations {
nsarray.addObject(NSNumber(unsignedInt: arc4random()))
}
pushTime = CACurrentMediaTime()
while nsarray.count > 0 {
nsarray.removeLastObject()
}
popTime = CACurrentMediaTime()
nsArrayPushLabel.text = String(format: "Push: %06fs", pushTime - startTime)
nsArrayPopLabel.text = String(format: "Pop: %06fs", popTime - pushTime)
//
var genericStack = Stack<UInt32>(initialCapacity: 10000, growingIncrement: 10000)
startTime = CACurrentMediaTime()
for _ in 0..<iterations {
let value = arc4random()
genericStack.push(value)
}
pushTime = CACurrentMediaTime()
while genericStack.count > 0 {
genericStack.pop()
}
popTime = CACurrentMediaTime()
genericStructPushLabel.text = String(format: "Push: %06fs", pushTime - startTime)
genericStructPopLabel.text = String(format: "Pop: %06fs", popTime - pushTime)
//
var genericStackNoOptional = StackNoOptional<UInt32>(initialCapacity: 10000, growingIncrement: 10000)
startTime = CACurrentMediaTime()
for _ in 0..<iterations {
let value = arc4random()
genericStackNoOptional.push(value)
}
pushTime = CACurrentMediaTime()
while genericStackNoOptional.count > 0 {
genericStackNoOptional.pop()
}
popTime = CACurrentMediaTime()
genericStructNoOptionalPushLabel.text = String(format: "Push: %06fs", pushTime - startTime)
genericStructNoOptionalPopLabel.text = String(format: "Pop: %06fs", popTime - pushTime)
//
var stack = StackUInt32(initialCapacity: 10000, growingIncrement: 10000)
startTime = CACurrentMediaTime()
for _ in 0..<iterations {
stack.push(arc4random())
}
pushTime = CACurrentMediaTime()
while stack.count > 0 {
stack.pop()
}
popTime = CACurrentMediaTime()
structUInt32PushLabel.text = String(format: "Push: %06fs", pushTime - startTime)
structUInt32PopLabel.text = String(format: "Pop: %06fs", popTime - pushTime)
}
}
|
//
// CommandLineRouter.swift
// CommandLineRouter
//
// Created by Pilipenko Dima on 11/06/16.
// Copyright © 2016 dimpiax. All rights reserved.
//
import Foundation
public struct CommandLineRouter {
private var _commands: [CommandsFlow] = []
public init() {
// empty initializer
}
public mutating func setCommands(name: String, commands: Command...) {
_commands.append(CommandsFlow(name: name, value: commands))
}
public func route(_ args: [String], callback: (CommandsFlow) -> Void) throws {
// TODO: make arguments enum
var arguments = Array(args.suffix(from: 1))
// format path
var path = [String]()
for (index, value) in arguments.enumerated() where index % 2 == 0 {
path.append(value)
}
let commandsFlow: CommandsFlow
do {
commandsFlow = try getCommandsFlow(path: path)
// create commands flow with arguments
var commands = [Command]()
for index in 0..<commandsFlow.count {
let command = commandsFlow[index]
let argument = arguments[index*2+1]
commands.append(Command(shortName: command.shortName, name: command.name, argument: argument))
}
// pass in route callback
callback(CommandsFlow(name: commandsFlow.name, value: commands))
} catch {
throw error
}
}
private func getCommandsFlow(path: [String]) throws -> CommandsFlow {
var commands = _commands
for (index, value) in path.enumerated() {
commands = filterCommands(step: value, level: index, commandsSet: commands)
}
let pathLength = path.count
commands = commands.filter { $0.count == pathLength }
guard let result = commands.first else {
throw NSError(domain: "Not found any matches commands chain", code: 0, userInfo: nil)
}
guard commands.count == 1 else {
throw NSError(domain: "Found concurrent commands chain. Solution: review created commands sets", code: 0, userInfo: nil)
}
return result
}
private func filterCommands(step: String, level: Int, commandsSet: [CommandsFlow]) -> [CommandsFlow] {
var result = [CommandsFlow]()
for commands in commandsSet {
guard level < commands.count else { continue }
let command = commands[level]
guard command.name == step || command.shortName == step else { continue }
result.append(commands)
}
return result
}
}
|
//
// ProductRegisterViewController.swift
// RafaelAlessandro
//
// Created by Usuário Convidado on 21/10/17.
// Copyright © 2017 FIAP. All rights reserved.
//
import UIKit
import CoreData
class ProductRegisterViewController: UIViewController {
var product: Product!
var smallImage: UIImage!
var pickerView: UIPickerView!
var stateDataSource: [State] = []
@IBOutlet weak var tfName: UITextField!
@IBOutlet weak var ivPicture: UIImageView!
@IBOutlet weak var tfStateName: UITextField!
@IBOutlet weak var tfValue: UITextField!
@IBOutlet weak var swIsCreditCardPayment: UISwitch!
@IBOutlet weak var btnAddUpdate: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tfName.placeholder = "Nome do produto"
tfStateName.placeholder = "Estado da compra"
tfValue.placeholder = "Valor (U$)"
btnAddUpdate.titleLabel?.text = "CADASTRAR"
if product != nil{
btnAddUpdate.titleLabel?.text = "ATUALIZAR"
tfName.text = product.name
// if let states = produto.states {
// tfEstadoProduto.text = states.map({($0 as! State).nome!})
// } else {
// print("o estado está vazio")
// }
// tfValor.text = String( produto.valor )
// swCartao.setOn(produto.cartao, animated: false)
// btCadastrar.setTitle("Atualizar", for: .normal)
if let picture = product.picture as? UIImage {
ivPicture.image = picture
}
}
loadState()
setupPickerView()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ProductRegisterViewController.handleTap))
ivPicture.addGestureRecognizer(tapGesture)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadState() {
let fetchRequest: NSFetchRequest<State> = State.fetchRequest()
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
do {
stateDataSource = try context.fetch(fetchRequest)
} catch {
print(error.localizedDescription)
}
}
// State picker
func setupPickerView() {
pickerView = UIPickerView() //Instanciando o UIPickerView
pickerView.backgroundColor = .white
pickerView.delegate = self //Definindo seu delegate
pickerView.dataSource = self //Definindo seu dataSource
//Criando uma toobar que servirá de apoio ao pickerView. Através dela, o usuário poderá
//confirmar sua seleção ou cancelar
let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 44))
//O botão abaixo servirá para o usuário cancelar a escolha de gênero, chamando o método cancel
let btCancel = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancel))
let btSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
//O botão done confirmará a escolha do usuário, chamando o método done.
let btDone = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(done))
toolbar.items = [btCancel, btSpace, btDone]
//Aqui definimos que o pickerView será usado como entrada do extField
tfStateName.inputView = pickerView
//Definindo a toolbar como view de apoio do textField (view que fica acima do teclado)
tfStateName.inputAccessoryView = toolbar
}
func cancel() {
tfStateName.resignFirstResponder()
}
func done() {
if stateDataSource.count > 0 {
tfStateName.text = stateDataSource[pickerView.selectedRow(inComponent: 0)].name
}
cancel()
}
func handleTap() {
//Criando o alerta que será apresentado ao usuário
let alert = UIAlertController(title: "Selecionar imagem", message: "De onde você quer escolher o imagem?", preferredStyle: .actionSheet)
//Verificamos se o device possui câmera. Se sim, adicionamos a devida UIAlertAction
if UIImagePickerController.isSourceTypeAvailable(.camera) {
let cameraAction = UIAlertAction(title: "Câmera", style: .default, handler: { (action: UIAlertAction) in
self.selectPicture(sourceType: .camera)
})
alert.addAction(cameraAction)
}
//As UIAlertActions de Biblioteca de fotos e Álbum de fotos também são criadas e adicionadas
let libraryAction = UIAlertAction(title: "Biblioteca de fotos", style: .default) { (action: UIAlertAction) in
self.selectPicture(sourceType: .photoLibrary)
}
alert.addAction(libraryAction)
let photosAction = UIAlertAction(title: "Álbum de fotos", style: .default) { (action: UIAlertAction) in
self.selectPicture(sourceType: .savedPhotosAlbum)
}
alert.addAction(photosAction)
let cancelAction = UIAlertAction(title: "Cancelar", style: .cancel, handler: nil)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
func selectPicture(sourceType: UIImagePickerControllerSourceType) {
//Criando o objeto UIImagePickerController
let imagePicker = UIImagePickerController()
//Definimos seu sourceType através do parâmetro passado
imagePicker.sourceType = sourceType
//Definimos a MovieRegisterViewController como sendo a delegate do imagePicker
imagePicker.delegate = self
//Apresentamos a imagePicker ao usuário
present(imagePicker, animated: true, completion: nil)
}
@IBAction func addUpdateProduct(_ sender: UIButton) {
if product == nil { product = Product(context: context) }
product.name = tfName.text
if smallImage != nil {
product.picture = smallImage
}
product.state = nil
product.value = Double( tfValue.text! )!
product.isCreditCardPayment = swIsCreditCardPayment.isOn
do {
try context.save()
} catch {
print(error.localizedDescription)
}
dismiss(animated: true, completion: nil)
}
}
// Picture picker
extension ProductRegisterViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//O método abaixo nos trará a imagem selecionada pelo usuário em seu tamanho original
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String: AnyObject]?) {
//Iremos usar o código abaixo para criar uma versão reduzida da imagem escolhida pelo usuário
let smallSize = CGSize(width: 300, height: 280)
UIGraphicsBeginImageContext(smallSize)
image.draw(in: CGRect(x: 0, y: 0, width: smallSize.width, height: smallSize.height))
//Atribuímos a versão reduzida da imagem à variável smallImage
smallImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
ivPicture.image = smallImage //Atribuindo a imagem à ivPoster
//Aqui efetuamos o dismiss na UIImagePickerController, para retornar à tela anterior
dismiss(animated: true, completion: nil)
}
}
// State picker
extension ProductRegisterViewController: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return stateDataSource[row].name
}
}
extension ProductRegisterViewController: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1 //Usaremos apenas 1 coluna (component) em nosso pickerView
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return stateDataSource.count //O total de linhas será o total de itens em nosso dataSource
}
}
|
//
// LazyGridsViewController.swift
// Layouts
//
// Created by Nestor Hernandez on 11/07/22.
//
import Foundation
class LazyGridsViewController:SwiftUIViewController<LazyGridsView> {
let viewModel: LazyGridsViewModel
var coordinator: AppNavigation?
init(viewModel: LazyGridsViewModel = LazyGridsViewModel(),
coordinator: AppNavigation?){
self.viewModel = viewModel
self.coordinator = coordinator
super.init(content: LazyGridsView(viewModel: viewModel,
coordinator: coordinator))
}
}
|
//
// ImageCoreData.swift
// Container
//
// Created by Ruslan Alikhamov on 26.02.19.
// Copyright © 2019 Imagemaker. All rights reserved.
//
import Foundation
import CoreData
import CoreLocation
@objc(ImageCoreData)
class ImageCoreData : NSManagedObject, ImagePure {
var name : String? {
get {
return self.coredata_name as String?
}
set {
self.coredata_name = newValue as NSString?
}
}
var url: String? {
get {
return self.coredata_url as String?
}
set {
self.coredata_url = newValue as NSString?
}
}
var data: Data? {
get {
return self.coredata_image as Data?
}
set {
self.coredata_image = newValue as NSData?
}
}
var created: Date? {
get {
return self.coredata_created as Date?
}
set {
self.coredata_created = newValue as NSDate?
}
}
@NSManaged var coredata_name: NSString?
@NSManaged var coredata_url: NSString?
@NSManaged var coredata_image: NSData?
@NSManaged var coredata_created: NSDate?
override func awakeFromInsert() {
super.awakeFromInsert()
self.created = Date()
}
}
extension Image : ContainerSupportInternal {
static var coredata_entityName: String {
return "ImageCoreData"
}
}
|
//
// MapaViewController.swift
// DesafioRealm
//
// Created by Swift on 19/01/2018.
// Copyright © 2018 Swift. All rights reserved.
//
import UIKit
import MapKit
class MapaViewController: UIViewController {
@IBOutlet weak var mapa: MKMapView!
var paisSelecionado : Pais?
override func viewDidLoad() {
super.viewDidLoad()
self.title = paisSelecionado?.nome
let zoom = MKCoordinateSpanMake(20.0, 20.0)
let regiao = MKCoordinateRegionMake(CLLocationCoordinate2DMake(CLLocationDegrees(paisSelecionado!.latitude.value!), CLLocationDegrees( paisSelecionado!.longitude.value!)), zoom)
self.mapa.setRegion(regiao, animated: true)
}
}
|
//
// CreateEventViewController.swift
// Volunteer Opportunity Tracker
//
// Created by Cindy Zhang on 3/4/18.
// Copyright © 2018 Cindy Zhang. All rights reserved.
//
import UIKit
class CreateEventViewController: UIViewController, UITextFieldDelegate{
var manager:EventsDataManager!
@IBOutlet weak var eventNameInput: UITextField!
@IBOutlet weak var locationInput: UITextField!
@IBOutlet weak var addressInput: UITextField!
@IBOutlet weak var descriptionInput: UITextView!
@IBOutlet weak var spotsInput: UITextField!
@IBOutlet weak var photoInput: UIImageView!
@IBOutlet weak var dateField: UITextField!
@IBOutlet weak var startTimeField: UITextField!
@IBOutlet weak var endTimeField: UITextField!
let datePickerView:UIDatePicker = UIDatePicker()
var dateTimeFieldEdited:String = ""
override func viewDidLoad() {
super.viewDidLoad()
manager = EventsDataManager.sharedInstance
descriptionInput.layer.borderColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0).cgColor
descriptionInput.layer.borderWidth = 1.0
descriptionInput.layer.cornerRadius = 5
createDatePicker()
}
func createDatePicker(){
let toolbar = UIToolbar()
toolbar.sizeToFit()
let done = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePickingDate))
toolbar.setItems([done], animated: false)
dateField.inputAccessoryView = toolbar
startTimeField.inputAccessoryView = toolbar
endTimeField.inputAccessoryView = toolbar
}
@IBAction func dateFieldEditing(_ sender: UITextField) {
if sender.accessibilityIdentifier! == "date" { datePickerView.datePickerMode = UIDatePickerMode.date }
else { datePickerView.datePickerMode = UIDatePickerMode.time }
sender.inputView = datePickerView
dateTimeFieldEdited = sender.accessibilityIdentifier!
}
@objc func donePickingDate() {
let dateFormatter = DateFormatter()
if dateTimeFieldEdited == "date" {
dateFormatter.dateStyle = DateFormatter.Style.medium
dateFormatter.timeStyle = DateFormatter.Style.none
dateField.text = dateFormatter.string(from: datePickerView.date)
dateField.endEditing(true)
}
else {
dateFormatter.dateStyle = DateFormatter.Style.none
dateFormatter.timeStyle = DateFormatter.Style.short
if dateTimeFieldEdited == "startTime" {
startTimeField.text = dateFormatter.string(from: datePickerView.date)
startTimeField.endEditing(true)
} else if dateTimeFieldEdited == "endTime" {
endTimeField.text = dateFormatter.string(from: datePickerView.date)
endTimeField.endEditing(true)
}
}
}
@IBAction func submitButton(_ sender: UIButton) {
let name = eventNameInput.text
let location = locationInput.text
let address = addressInput.text
let description = descriptionInput.text
let spots: Int? = Int(spotsInput.text!)
let date = dateField.text
let startTime = startTimeField.text
let endTime = endTimeField.text
let photo = photoInput.image
if name == "" || location == "" || address == "" || description == "" || date == "" || startTime == "" || endTime == "" || photo == UIImage(named: "Select") {
print ("you didn't enter all information required")
} else {
let event = EventObject(name: name!, location: location!, address: address!, description: description!, totalSpots: spots!, date: date!, startTime: startTime!, endTime: endTime!)
manager.addEventToDatabase(event, photo!)
}
eventNameInput.text = ""
locationInput.text = ""
addressInput.text = ""
descriptionInput.text = ""
spotsInput.text = ""
dateField.text = ""
startTimeField.text = ""
endTimeField.text = ""
photoInput.image = UIImage(named: "Select")
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
extension CreateEventViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBAction func selectImageFromPhotoLibrary(_ sender: UITapGestureRecognizer) {
//TODO: hide keyboard for whatever text field is currently being edited
let imagePickerController = UIImagePickerController()
imagePickerController.sourceType = .photoLibrary
imagePickerController.delegate = self // for this line, ui navigation controller delegate is necessary
present(imagePickerController, animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// Dismiss the picker if the user canceled.
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// The info dictionary may contain multiple representations of the image. You want to use the original.
guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
// Set photoImageView to display the selected image.
photoInput.image = selectedImage
// Dismiss the picker.
dismiss(animated: true, completion: nil)
}
}
|
//
// IndustryGrid.swift
// IVO
//
// Created by user on 12/28/16.
// Copyright © 2016 3dlink. All rights reserved.
//
import UIKit
class IndustryGrid: UICollectionViewCell {
@IBOutlet weak var industryName: UILabel!
}
|
//
// Rate.swift
// ExchangeRates
//
// Created by Andrey Novikov on 9/5/20.
// Copyright © 2020 Andrey Novikov. All rights reserved.
//
import Foundation
struct Rate {
// MARK: - Properties
var name: String
var rateValus: [Double]
var fromDate: Date?
var lastRateValue: String {
return String(format: "%.2f", rateValus.last ?? 0)
}
var minRateValue: Double {
return rateValus.min() ?? 0
}
var maxRateValue: Double {
return rateValus.max() ?? 0
}
var med: Double {
var value: Double = 0
rateValus.forEach { (rate) in
value += rate
}
value /= Double(rateValus.count)
return value
}
enum RateValue {
case maxRateValue
case medinaMaxRateValue
case medinaRateValue
case medinaMinRateValue
case minRateValue
}
// MARK: - Init
init() {
name = ""
rateValus = []
}
init(name: String, rateValus: [Double]) {
self.name = name
self.rateValus = rateValus
}
// MARK: - Methods
func getRate(withRateValue rateValue: RateValue) -> String {
let maxRateValue = rateValus.max() ?? 0
let minRateValue = rateValus.min() ?? 0
let medinaRateValue = (maxRateValue + minRateValue) / 2
let medinaMinRateValue = (minRateValue + medinaRateValue) / 2
let medinaMaxRateValue = (medinaRateValue + maxRateValue) / 2
let stringFormat = "%.2f"
switch rateValue {
case .maxRateValue:
return String(format: stringFormat, maxRateValue)
case .medinaMaxRateValue:
return String(format: stringFormat, medinaMaxRateValue)
case .medinaRateValue:
return String(format: stringFormat, medinaRateValue)
case .medinaMinRateValue:
return String(format: stringFormat, medinaMinRateValue)
case .minRateValue:
return String(format: stringFormat, minRateValue)
}
}
}
extension Rate: Hashable {
}
|
import Foundation
import HandySwift
struct Resource {
static let baseUrl = URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent(".testResources")
let path: String
let contents: String
var data: Data? {
return contents.data(using: .utf8)
}
init(path: String, contents: String) {
self.path = Resource.baseUrl.appendingPathComponent(path).path
self.contents = contents
}
}
|
//
// Constants.swift
// Finder
//
// Created by Simion Schiopu on 9/7/15.
// Copyright © 2015 YOPESO. All rights reserved.
//
import Foundation
enum FinderError: ErrorType {
case NotSpecifiedRootPath
case NotSpecifiedType
case WrongFilePath(path: String)
}
struct DirectorySuffix {
static let AllFiles = "/*"
static let AnyCombination = ".*"
static let Slash = "/"
}
struct ParametersKeys {
static let Path = "path"
static let Excludes = "excludes"
static let Files = "files"
static let FileType = "type"
} |
// Copyright (c) 2015-2019 Christian Tietze
//
// See the file LICENSE for copying permission.
import Foundation
import CocoaFob
/// Verifies license information based on the registration
/// scheme `APPNAME,LICENSEE_NAME` which ties licenses to
/// both application and user.
class LicenseVerifier {
let configuration: LicenseConfiguration
fileprivate var appName: String { return configuration.appName }
fileprivate var publicKey: String { return configuration.publicKey }
init(configuration: LicenseConfiguration) {
self.configuration = configuration
}
func isValid(licenseCode: String, forName name: String) -> Bool {
// Same format as on FastSpring
let registrationName = "\(appName),\(name)"
let publicKey = self.publicKey
guard let verifier = verifier(publicKey: publicKey) else {
assertionFailure("CocoaFob.LicenseVerifier cannot be constructed")
return false
}
return verifier.verify(licenseCode, forName: registrationName)
}
fileprivate func verifier(publicKey: String) -> CocoaFob.LicenseVerifier? {
return CocoaFob.LicenseVerifier(publicKeyPEM: publicKey)
}
}
|
//
// Balance.swift
// WavesWallet-iOS
//
// Created by Prokofev Ruslan on 07/09/2018.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import Foundation
public struct Balance: Equatable {
public struct Currency: Equatable {
public let title: String
public let ticker: String?
public init(title: String, ticker: String?) {
self.title = title
self.ticker = ticker
}
}
public let currency: Currency
public let money: Money
public init(currency: Currency, money: Money) {
self.currency = currency
self.money = money
}
}
public extension Balance {
enum Sign: String, Equatable {
case none = ""
case plus = "+"
case minus = "-"
}
func displayShortText(sign: Sign, withoutCurrency: Bool) -> String {
var text = ""
if withoutCurrency {
text = money.displayShortText
} else {
text = money.displayShortText + " " + currency.title
}
return sign.rawValue + text
}
func displayText(sign: Sign, withoutCurrency: Bool) -> String {
var text = ""
if withoutCurrency {
text = money.displayText
} else {
text = money.displayText + " " + currency.title
}
return sign.rawValue + text
}
var displayText: String {
return money.displayText + " " + currency.title
}
var displayTextWithoutCurrencyName: String {
return money.displayText
}
}
|
//
// FirebaseSignOut.swift
// Showcase-iOS
//
// Created by Lehlohonolo Mbele on 2018/05/31.
// Copyright © 2018 DVT. All rights reserved.
//
import Foundation
protocol FirebaseSignOut {
func signOut() throws
}
|
//
// WalletDelegate.swift
// Tipper
//
// Created by Ryan Romanchuk on 11/11/15.
// Copyright © 2015 Ryan Romanchuk. All rights reserved.
//
import Foundation
import PassKit
import Stripe
import ApplePayStubs
import SwiftyJSON
class PaymentController: NSObject, PKPaymentAuthorizationViewControllerDelegate, STPCheckoutViewControllerDelegate {
weak var walletDelegate: UIViewController?
var market: Market
let stripeCheckout = STPCheckoutViewController()
let ApplePayMerchantID = Config.get("APPLE_PAY_MERCHANT")
let SupportedPaymentNetworks = [PKPaymentNetworkVisa, PKPaymentNetworkMasterCard, PKPaymentNetworkAmex]
var applePaySupported: Bool {
get {
let paymentRequest = Stripe.paymentRequestWithMerchantIdentifier(ApplePayMerchantID)
return PKPaymentAuthorizationViewController.canMakePaymentsUsingNetworks(SupportedPaymentNetworks) && Stripe.canSubmitPaymentRequest(paymentRequest) ? true : false
}
}
init(withMarket: Market) {
market = withMarket
}
func pay() {
log.verbose("")
let request = PKPaymentRequest()
request.merchantIdentifier = ApplePayMerchantID
request.supportedNetworks = SupportedPaymentNetworks
request.merchantCapabilities = PKMerchantCapability.Capability3DS
request.countryCode = "US"
request.currencyCode = "USD"
let amount = (market.amount! as NSString).doubleValue
request.paymentSummaryItems = [PKPaymentSummaryItem(label: "\(Config.get("APP_NAME")) \(Settings.sharedInstance.fundAmount!)BTC deposit", amount: NSDecimalNumber(double: amount))]
if Stripe.canSubmitPaymentRequest(request) {
#if DEBUG
log.info("in debug mode")
let applePayController = STPTestPaymentAuthorizationViewController(paymentRequest: request)
applePayController.delegate = paymentController
self.presentViewController(applePayController, animated: true, completion: nil)
#else
let applePayController = PKPaymentAuthorizationViewController(paymentRequest: request)
applePayController.delegate = self
walletDelegate?.presentViewController(applePayController, animated: true, completion: nil)
#endif
} else {
launchStripeFlow()
}
}
private func launchStripeFlow() {
//default to Stripe's PaymentKit Form
let options = STPCheckoutOptions()
let amount = (market.amount! as NSString).doubleValue
options.purchaseDescription = "\(Config.get("APP_NAME")) \(Settings.sharedInstance.fundAmount!) deposit";
options.purchaseAmount = UInt(amount * 100)
options.companyName = "Tipper"
let checkoutViewController = STPCheckoutViewController(options: options)
checkoutViewController.checkoutDelegate = self
walletDelegate?.presentViewController(checkoutViewController, animated: true, completion: nil)
}
private func createBackendChargeWithToken(token: STPToken, completion: STPTokenSubmissionHandler) {
log.verbose("")
API.sharedInstance.charge(token.tokenId, amount:self.market.amount!, completion: { [weak self] (json, error) -> Void in
if (error != nil) {
completion(STPBackendChargeResult.Failure, error)
} else {
//self?.currentUser.updateEntityWithJSON(json)
completion(STPBackendChargeResult.Success, nil)
//TSMessage.showNotificationInViewController(self?.parentViewController!, title: "Payment complete", subtitle: "Your bitcoin will arrive shortly.", type: .Success, duration: 5.0)
}
})
}
// MARK: STPCheckoutViewControllerDelegate
func checkoutController(controller: STPCheckoutViewController, didCreateToken token: STPToken, completion: STPTokenSubmissionHandler) {
log.verbose("")
createBackendChargeWithToken(token, completion: completion)
}
func paymentAuthorizationViewControllerDidFinish(controller: PKPaymentAuthorizationViewController) {
log.verbose("")
walletDelegate?.parentViewController!.dismissViewControllerAnimated(true, completion: nil)
}
func checkoutController(controller: STPCheckoutViewController, didFinishWithStatus status: STPPaymentStatus, error: NSError?) {
log.error("error:\(error)")
walletDelegate?.parentViewController!.dismissViewControllerAnimated(true, completion: {
switch(status) {
case .UserCancelled:
return // just do nothing in this case
case .Success:
log.info("Backend stripe payment complete")
case .Error:
log.error("oh no, an error: \(error?.localizedDescription)")
}
})
}
// MARK: STPCheckoutViewControllerDelegate
func paymentAuthorizationViewController(controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, completion: ((PKPaymentAuthorizationStatus) -> Void)) {
log.verbose("")
STPAPIClient.sharedClient().createTokenWithPayment(payment, completion: { [weak self] (token, error) -> Void in
log.verbose("error:\(error), token: \(token)")
if error == nil {
if let token = token {
self?.createBackendChargeWithToken(token, completion: { (result, error) -> Void in
log.verbose("error:\(error), result: \(result)")
if result == STPBackendChargeResult.Success {
completion(PKPaymentAuthorizationStatus.Success)
return
}
})
}
} else {
completion(PKPaymentAuthorizationStatus.Failure)
}
})
}
}
protocol WalletDelegate {
func done()
} |
import UIKit
extension String {
private func capitalize() -> String {
let firstLetter = String(self.prefix(1)).capitalized
let restOfString = String(self.dropFirst())
return firstLetter + restOfString
}
mutating func capitalizeFirstLetter() {
self = self.capitalize()
}
}
//Use of Extension
var bedu = "bedu school"
bedu.capitalizeFirstLetter()
print(bedu)
// UIButton
extension UIButton {
func circled() {
self.frame = CGRect(x: self.center.x,
y: self.center.y,
width: self.frame.width/2,
height: self.frame.height/2)
self.setTitle("", for: .normal)
self.backgroundColor = .clear
}
}
|
//
// SecondViewController.swift
// R2D214
//
// Created by user178354 on 2/25/21.
// Copyright © 2021 user178354. All rights reserved.
//
import UIKit
import Firebase
class SecondViewController:UIViewController, UITableViewDataSource, UITableViewDelegate{
@IBOutlet weak var tableView2: UITableView!
let messageAlert = UIAlertController(title: "", message: "Is this the group you would like to send a message to?", preferredStyle: .alert)
let arrayOf = ArrayOf()
var numOfRows = 0
var counter = 000001
var check = 1
var idsel = ""
var IDNumber: [String] = []
var firstNameDictionary: [String] = []
var lastNameDictionary: [String] = []
var selectedRow:Int = 0
public func getData(){
arrayOf.IDNumber = []
arrayOf.counselor = []
arrayOf.Email = []
arrayOf.firstName = []
arrayOf.lastName = []
var check = 1
if check == 1 {
IDNumber = []
check = 2
}
let reference = Database.database().reference()
print(reference)
reference.observeSingleEvent(of: .value) { (snapshot) in
for data in snapshot.children.allObjects as! [DataSnapshot] {
let ID = data.key
if self.IDNumber.contains(ID) {
// let dictionary = data.value as! NSDictionary
}
else {
self.IDNumber.append(ID)
print("id: ",ID)
print(self.IDNumber.count)
print(self.arrayOf.IDNumber)
print(self.IDNumber)
let dictionary = data.value as! NSDictionary
let firstName = dictionary["First Name"] as! String
let lastName = dictionary["Last Name"] as! String
self.firstNameDictionary.append(firstName)
self.lastNameDictionary.append(lastName)
}
DispatchQueue.main.async {
self.tableView2.reloadData()
print(self.firstNameDictionary)
print(self.IDNumber.count)
}
}
}
}
override func viewDidLoad() {
tableView2.allowsSelection = true
tableView2.allowsSelectionDuringEditing = true
getData()
tableView2.dataSource = self
tableView2.delegate = self
super.viewDidLoad()
let yesAction = UIAlertAction(title: "Yes", style: .default) { _ in
let message = self.storyboard!.instantiateViewController(identifier: "messageVC") as! messageVC
message.idnum = self.IDNumber
}
// needs editing so that noAction stops third view controller from appearing
let noAction = UIAlertAction(title: "No", style: .default) { _ in
let thirdvc = self.storyboard!.instantiateViewController(identifier: "thirdvc") as! ThirdViewController
if self.selectedRow != 4 && self.IDNumber[self.selectedRow].isEmpty {
}
self.present(thirdvc, animated:true, completion: nil)
}
messageAlert.addAction(yesAction)
messageAlert.addAction(noAction)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexPath = tableView2.indexPathForSelectedRow!
selectedRow = indexPath.row
present(messageAlert, animated: true, completion: nil)
}
override func viewDidAppear(_ animated: Bool) {
tableView2.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return firstNameDictionary.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
DispatchQueue.main.async {
self.tableView2.reloadData()
}
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell")!
cell.textLabel?.text = "\(firstNameDictionary[indexPath.row])"
cell.detailTextLabel?.text = "\(lastNameDictionary[indexPath.row])"
return cell
}
// override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// let nvc = segue.destination as! FirstViewController
// let classYears = nvc.finalYears
// let counselors = nvc.arrayOf.counselor
// //yearNumbers.append(contentsOf: classYears)
// }
}
|
//
// EasyGuidePageView.swift
// Easy
//
// Created by OctMon on 2019/1/22.
//
import UIKit
public extension Easy {
typealias GuidePageView = EasyGuidePageView
}
public class EasyGuidePageView: UIView {
public let pageControl = EasyPageControl(frame: CGRect(x: 0, y: EasyApp.screenHeight - 30, width: EasyApp.screenWidth, height: 30))
let scrollView = UIScrollView(frame: EasyApp.screenBounds).then {
$0.isPagingEnabled = true
$0.showsHorizontalScrollIndicator = false
}
public var animateDuration: TimeInterval = 0.3
public var swipeToExit = true
public init(images: [UIImage?], skipButton: UIButton?) {
super.init(frame: EasyApp.screenBounds)
backgroundColor = UIColor.white
addSubview(scrollView)
scrollView.contentSize = CGSize(width: EasyApp.screenWidth * images.count.toCGFloat, height: EasyApp.screenHeight)
scrollView.delegate = self
images.enumerated().forEach { (offset, _) in
UIImageView(frame: CGRect(x: EasyApp.screenWidth * offset.toCGFloat, y: 0, width: EasyApp.screenWidth, height: EasyApp.screenHeight)).do {
$0.image = images[offset]
scrollView.addSubview($0)
if let button = skipButton, offset == images.count - 1 {
$0.addSubview(button)
$0.isUserInteractionEnabled = true
button.tap { [weak self] (_) in
self?.hide()
}
}
}
}
addSubview(pageControl)
pageControl.do {
$0.backgroundColor = .clear
$0.numberOfPages = images.count
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func hide() {
UIView.animate(withDuration: animateDuration, animations: {
self.alpha = 0
}) { (completion) in
self.removeFromSuperview()
}
}
}
extension EasyGuidePageView: UIScrollViewDelegate {
private func currentPage(scrollView: UIScrollView) -> Int {
return Int((scrollView.contentOffset.x + scrollView.bounds.width * 0.5) / scrollView.bounds.width)
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageControl.currentPage = currentPage(scrollView: scrollView)
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if swipeToExit && currentPage(scrollView: scrollView) == pageControl.numberOfPages - 1 && scrollView.panGestureRecognizer.translation(in: scrollView.superview).x < 0 {
hide()
}
}
}
public extension EasyGuidePageView {
func showFullscreen(animateDuration: TimeInterval? = nil) {
if let animateDuration = animateDuration {
self.animateDuration = animateDuration
}
EasyApp.keyWindow?.addSubview(self)
}
}
|
//
// MainCoordinator.swift
// Favloc
//
// Created by Kordian Ledzion on 13/01/2018.
// Copyright © 2018 KordianLedzion. All rights reserved.
//
import UIKit
class MainCoordinator: Coordinator {
var rootViewController: UIViewController {
return navigationController
}
private var navigationController: UINavigationController
private let viewModel: DataSource
init(viewModel: DataSource) {
self.viewModel = viewModel
let mainCollectionViewController = MainCollectionViewController(viewModel: viewModel)
self.navigationController = UINavigationController(rootViewController: mainCollectionViewController)
mainCollectionViewController.coordinator = self
}
func presentDetails(for place: Place, _ completion: @escaping () -> Void) {
let viewController = PlaceDetailsViewController(place: place, viewModel: viewModel, completion)
viewController.coordinator = self
navigationController.pushViewController(viewController, animated: true)
}
func presentLocationPicker(with dismissCompletion: @escaping (Double,Double) -> Void) {
let viewController = MapViewController(with: dismissCompletion)
viewController.coordinator = self
navigationController.pushViewController(viewController, animated: true)
}
func presentPhotoCapture(with dismissCompletion: @escaping (Data) -> Void) {
let viewController = CapturePhotoViewController(dismissCompletion: dismissCompletion)
viewController.coordinator = self
navigationController.pushViewController(viewController, animated: true)
}
}
|
//
// RecipesContainer.swift
// UserInterface
//
// Created by Fernando Moya de Rivas on 01/09/2019.
// Copyright © 2019 Fernando Moya de Rivas. All rights reserved.
//
import Foundation
import Repository
/// Dependency Injection container for the Recipes scene
final class RecipesContainer: ViewControllerProvider {
private let navigationController: UINavigationController
private let repositoryContainer: RepositoryContainer
init(navigationController: UINavigationController, repositoryContainer: RepositoryContainer) {
self.navigationController = navigationController
self.repositoryContainer = repositoryContainer
}
var viewModel: RecipesViewModel {
return RecipesViewModel(dataStorePager: repositoryContainer.dataStorePager)
}
var viewController: UIViewController {
return RecipesViewController(viewModel: viewModel)
}
var navigator: RecipesNavigator {
return RecipesNavigator(navigationController: navigationController, viewControllerProvider: self)
}
}
|
//
// UserImage.swift
// IntenseSwat
//
// Created by Basement on 12/18/15.
// Copyright © 2015 Apportable. All rights reserved.
//
import Foundation
import CoreData
class UserImage: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
// This function will save the pictures set to the user image to core data
func savePicture(image:UIImage){
self.imageData = UIImagePNGRepresentation(image)
CoreDataController.instance.save()
}
// This will load the picture set to the user image, if there
// is no picture data it will return nil
func loadPicture() -> UIImage?{
if imageData != nil{
let data = self.imageData!;
let image = UIImage(data: data)!
return image
}
return nil
}
}
/*
// This function will save the pictures set to the user image to the filesystem
func savePicture(image:UIImage){
let imageData = UIImagePNGRepresentation(image)
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let docURL = urls[urls.endIndex-1]
let url = docURL.URLByAppendingPathComponent("\(NSUUID().UUIDString).png")
self.imagePath = url.path!
imageData!.writeToFile(self.imagePath!, atomically: false)
CoreDataController.instance.save()
}
// This will load the picture set to the user image, if there
// is no picture data it will return nil
func loadPicture() -> UIImage?{
if imagePath != nil{
let image = UIImage(contentsOfFile: imagePath!)!
return image
}
return nil
}
*/ |
//: [Previous](@previous)
import Foundation
/*:
## Zadanie 3
Napisz extension do typu Int takie, aby możliwe było wykonanie funkcji niżej
*/
extension Int {
// TODO
}
//: Classic syntax
10.times({ () -> Void in
print("Hello DaftCode!")
})
//: () -> Void is the type that can be inferred by the compiler
10.times({
print("Hello DaftCode!")
})
//: Trailing closure syntax
10.times {
print("Hello DaftCode!")
}
//: [Next](@next)
|
//
// Storyboards.swift
// SupportI
//
// Created by Mohamed Abdu on 3/20/20.
// Copyright © 2020 MohamedAbdu. All rights reserved.
//
import Foundation
public enum Storyboards: String {
case main = "Main"
case auth = "Auth"
case category = "Category"
case store = "StoreDetail"
case createStore = "CreateStore"
case createAd = "CreateAd"
case pop = "Popup"
case Upgrade = "Upgrade"
case ads = "AdsDetail"
case forRent = "ForRent"
}
|
//
// Article.swift
// Article
//
// Created by Bruno Da luz on 18/05/16.
// Copyright © 2016 studies. All rights reserved.
//
import Foundation
class Article {
var title:String = ""
var body:String = ""
var date:NSDate = NSDate()
var bannerURL:NSURL = NSURL()
}
|
//
// PlayerController.swift
// GoogleMusicClientMacOS
//
// Created by Anton Efimenko on 19/12/2018.
// Copyright © 2018 Anton Efimenko. All rights reserved.
//
import Cocoa
import RxGoogleMusic
import RxSwift
import RxDataFlow
import AVFoundation
import GoogleMusicClientCore
import os.log
final class PlayerController: NSViewController {
@IBOutlet weak var albumImage: NSImageView!
@IBOutlet weak var songTitleLabel: NSTextField!
@IBOutlet weak var artistAndAlbumLabel: NSTextField!
@IBOutlet weak var shuffleButton: NSButton!
@IBOutlet weak var previousButton: NSButton!
@IBOutlet weak var playPauseButon: NSButton!
@IBOutlet weak var nextButton: NSButton!
@IBOutlet weak var repeatModeButton: NSButton!
@IBOutlet weak var queueButton: NSButton!
@IBOutlet weak var currentTimeLabel: NSTextField!
@IBOutlet weak var currentProgressSlider: ApplicationSlider!
@IBOutlet weak var trackDurationLabel: NSTextField!
@IBOutlet weak var volumeSlider: NSSlider!
@IBOutlet weak var showQueueButton: NSButton!
@objc dynamic var currentTrackTitle: String? = nil
@objc dynamic var currentArtistAndAlbum: String? = nil
@objc dynamic var currentTime: String? = nil
@objc dynamic var currentProgress: NSDecimalNumber? = nil
@objc dynamic var isCurrentProgressChangeEnabled = false
@objc dynamic var currentVolume: NSDecimalNumber = 100 {
didSet {
player?.volume = currentVolume.floatValue / 100
}
}
@objc dynamic var currentDuration: String? = nil
@objc dynamic var palyPauseImage = NSImage.pause
@objc dynamic var isRepeatQueueEnabled = Current.currentState.state.isRepeatQueueEnabled
@objc dynamic var isShuffleEnabled = Current.currentState.state.isShuffleEnabledForCurrentQueueSource
@objc dynamic var isShuffleAllowed = Current.currentState.state.queueSource?.isFavorites ?? false
let bag = DisposeBag()
var player: Player<GMusicTrack>? { return Current.currentState.state.player }
override func viewDidLoad() {
super.viewDidLoad()
player?.volume = currentVolume.floatValue / 100
bag.insert(bind())
subscribeToNotifications()
}
func bind() -> [Disposable] {
return [
Current.state.filter(isSetBy(PlayerAction.toggleQueueRepeat)).subscribe(onNext: { [weak self] in self?.isRepeatQueueEnabled = $0.state.isRepeatQueueEnabled }),
bindShuffle(),
bindShuffleAllowed(),
Current.currentTrack.observeOn(MainScheduler.instance).subscribe(onNext: { [weak self] in self?.update(with: $0?.track) }),
shuffleButton.rx.tap.subscribe(onNext: { Current.dispatch(PlayerAction.toggleShuffle) }),
previousButton.rx.tap.subscribe(onNext: { Current.dispatch(PlayerAction.playPrevious) }),
playPauseButon.rx.tap.subscribe(onNext: { Current.dispatch(PlayerAction.toggle) }),
nextButton.rx.tap.subscribe(onNext: { Current.dispatch(PlayerAction.playNext) }),
repeatModeButton.rx.tap.subscribe(onNext: { Current.dispatch(PlayerAction.toggleQueueRepeat) }),
// player?.currentItemStatus.subscribe(onNext: { print("ItemStatus: \($0)") }),
player?.currentItemTime.observeOn(MainScheduler.instance).subscribe(onNext: { [weak self] in self?.currentTime = $0?.timeString }),
player?.currentItemDuration.observeOn(MainScheduler.instance).subscribe(onNext: { [weak self] in self?.currentDuration = $0?.timeString }),
player?.isPlaying.observeOn(MainScheduler.instance).subscribe(onNext: { [weak self] in self?.palyPauseImage = $0 ? NSImage.pause : NSImage.play }),
currentProgressSlider.userSetValue.subscribe(onNext: { Current.currentState.state.player?.seek(to: $0) }),
Current.currentTrack.map { $0 != nil }.subscribe(onNext: { [weak self] in self?.isCurrentProgressChangeEnabled = $0 }),
player?.errors.subscribe(onNext: { Current.dispatch(PlayerAction.stop); Current.dispatch(UIAction.showErrorController($0)) }),
bindProgress(),
albumImage.rx.clicked.subscribe(onNext: { [weak albumImage] _ in Current.dispatch(UIAction.showAlbumPreviewPopover(albumImage!)) }),
albumImage.rx.mouseEntered.subscribe(onNext: { [weak albumImage] _ in albumImage?.scaleUp(by: 1.25) }),
albumImage.rx.mouseExited.subscribe(onNext: { [weak albumImage] _ in albumImage?.resetScale() }),
Current.currentTrackImage.observeOn(MainScheduler.instance).subscribe(onNext: { [weak self] in self?.albumImage.image = $0 })
].compactMap(id)
}
func bindShuffle() -> Disposable {
return Current.state.filter { state in
switch state.setBy {
case PlayerAction.setQueueSource, PlayerAction.toggleQueueRepeat: return true
default: return false
}
}.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] in self?.isShuffleEnabled = $0.state.isShuffleEnabledForCurrentQueueSource })
}
func bindShuffleAllowed() -> Disposable {
return Current.state.filter { state in
switch state.setBy {
case PlayerAction.setQueueSource: return true
default: return false
}
}.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] in self?.isShuffleAllowed = $0.state.queueSource?.isFavorites ?? false })
}
func bindProgress() -> Disposable? {
return player?.currentItemProgress
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] progress in
if self?.currentProgressSlider.isUserInteracting == false {
self?.currentProgress = progress?.asNsDecimalNumber
}
})
}
func update(with track: GMusicTrack?) {
currentTrackTitle = track?.title
currentArtistAndAlbum = track == nil ? nil : "\(track!.album) (\(track!.artist))"
if Current.currentState.state.queue.isCompleted, Current.currentState.state.isRepeatQueueEnabled {
Current.dispatch(CompositeActions.repeatFromQueueSource(shuffle: Current.currentState.state.isShuffleEnabledForCurrentQueueSource))
}
}
@IBAction func queueButtonClicked(_ sender: Any) {
Current.dispatch(UIAction.showQueuePopover(showQueueButton))
}
func subscribeToNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(didPlayToEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(playbackStalled), name: NSNotification.Name.AVPlayerItemPlaybackStalled, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(errorLogEntry), name: NSNotification.Name.AVPlayerItemNewErrorLogEntry, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(failedToPlayToEnd), name: NSNotification.Name.AVPlayerItemFailedToPlayToEndTime, object: nil)
}
@objc func didPlayToEnd() {
Current.dispatch(PlayerAction.playNext)
os_log(.default, log: .general, "Player didPlayToEnd")
}
@objc func playbackStalled() {
Current.dispatch(PlayerAction.pause)
os_log(.default, log: .general, "Player playbackStalled")
}
@objc func errorLogEntry() {
Current.dispatch(PlayerAction.stop)
os_log(.default, log: .general, "Player errorLogEntry")
}
@objc func failedToPlayToEnd() {
Current.dispatch(PlayerAction.stop)
Current.dispatch(UIAction.showErrorController("Unable to play current track"))
os_log(.default, log: .general, "Player failedToPlayToEnd")
}
deinit {
print("PlayerController deinit")
}
}
|
import RxSwift
import RxRelay
protocol IMarketMultiSortHeaderService: AnyObject {
var marketTop: MarketModule.MarketTop { get set }
var sortingField: MarketModule.SortingField { get set }
}
extension IMarketMultiSortHeaderService {
var marketTop: MarketModule.MarketTop {
get { .top100 }
set {}
}
}
class MarketMultiSortHeaderViewModel {
private let service: IMarketMultiSortHeaderService
private let decorator: MarketListMarketFieldDecorator
init(service: IMarketMultiSortHeaderService, decorator: MarketListMarketFieldDecorator) {
self.service = service
self.decorator = decorator
}
}
extension MarketMultiSortHeaderViewModel: IMarketMultiSortHeaderViewModel {
var sortItems: [String] {
MarketModule.SortingField.allCases.map { $0.title }
}
var sortIndex: Int {
MarketModule.SortingField.allCases.firstIndex(of: service.sortingField) ?? 0
}
var leftSelectorItems: [String] {
MarketModule.MarketTop.allCases.map { $0.title }
}
var leftSelectorIndex: Int {
MarketModule.MarketTop.allCases.firstIndex(of: service.marketTop) ?? 0
}
var rightSelectorItems: [String] {
MarketModule.MarketField.allCases.map { $0.title }
}
var rightSelectorIndex: Int {
MarketModule.MarketField.allCases.firstIndex(of: decorator.marketField) ?? 0
}
func onSelectSort(index: Int) {
service.sortingField = MarketModule.SortingField.allCases[index]
}
func onSelectLeft(index: Int) {
service.marketTop = MarketModule.MarketTop.allCases[index]
}
func onSelectRight(index: Int) {
decorator.marketField = MarketModule.MarketField.allCases[index]
}
}
|
//
// Utilities.swift
// Step Champ
//
// Created by Darien Sandifer on 7/11/16.
// Copyright © 2016 Darien Sandifer. All rights reserved.
//
import Foundation
import UIKit
func setColor(colorCode: String, alpha: Float = 1.0) -> UIColor {
let scanner = Scanner(string:colorCode)
var color:UInt32 = 0;
scanner.scanHexInt32(&color)
let mask = 0x000000FF
let r = CGFloat(Float(Int(color >> 16) & mask)/255.0)
let g = CGFloat(Float(Int(color >> 8) & mask)/255.0)
let b = CGFloat(Float(Int(color) & mask)/255.0)
return UIColor(red: r, green: g, blue: b, alpha: CGFloat(alpha))
}
extension String {
subscript (i: Int) -> Character {
return self[i + 1]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
// subscript (r: Range<Int>) -> String {
// let start = self.startIndex.advancedBy(r.lowerBound)
// let end = start.advancedBy(r.upperBound - r.lowerBound)
// return self[Range(start ..< end)]
// }
}
|
//Solution goes in Sources
struct SecretHandshake {
var commands: [String] = []
init(_ code: Int) {
if code & 1 != 0 { commands.append("wink") }
if code & 2 != 0 { commands.append("double blink") }
if code & 4 != 0 { commands.append("close your eyes") }
if code & 8 != 0 { commands.append("jump") }
if code & 16 != 0 { commands.reverse() }
}
}
|
//
// APIManager.swift
// Flicky
//
// Created by Kenny Orellana on 9/16/20.
// Copyright © 2020 Kenny Orellana. All rights reserved.
//
import Foundation
import Alamofire
class APIManager {
static func getFeed(page: Int = 1) -> DataRequest {
var params = getBaseParams(page: page)
params[Params.Method] = FlickrMethod.GetRecent
return AF.request(API.FlickrURL, parameters: params)
}
static func search(page: Int = 1, _ query: String) -> DataRequest {
var params = getBaseParams(page: page)
params[Params.Method] = FlickrMethod.Search
params[Params.Text] = query
return AF.request(API.FlickrURL, parameters: params)
}
private static func getBaseParams(page: Int = 1) -> [String:String] {
return [
Params.Format : ParamsValues.Json,
Params.NoJsonCallback : ParamsValues.One,
Params.ApiKey : API.FlickrKey,
Params.Extras : ParamsValues.Extras,
Params.Page : String(page)
]
}
}
|
//
// DatePicker_1_01.swift
// 100Views
//
// Created by Mark Moeykens on 6/16/19.
// Copyright © 2019 Mark Moeykens. All rights reserved.
//
import SwiftUI
struct DatePicker_MinMaxDateRange : View {
@State private var nextFullMoonDate = Date()
var withinNext30Days: ClosedRange<Date> {
let today = Calendar.current.date(byAdding: .minute, value: -1,
to: Date())!
let next30Days = Calendar.current.date(byAdding: .day, value: 30,
to: Date())!
return today...next30Days
}
var body: some View {
VStack(spacing: 30) {
Text("DatePicker").font(.largeTitle)
Text("Min and Max Date Range")
.foregroundColor(.gray)
HStack {
// Moon images
Spacer()
Image(systemName: "moon.circle")
Spacer()
Circle().frame(width: 60, height: 60)
Spacer()
Image(systemName: "moon.circle.fill")
Spacer()
}
.foregroundColor(Color.yellow)
Text("Select date of next full moon").font(.title)
DatePicker("", selection: $nextFullMoonDate,
in: withinNext30Days,
displayedComponents: .date)
.padding(.horizontal, 28)
.background(RoundedRectangle(cornerRadius: 10)
.foregroundColor(.yellow))
.shadow(radius: 20, y: 20)
.labelsHidden()
Text("(Valid range only in the next 30 days)")
.padding(.vertical)
Spacer()
}.font(.title)
}
}
struct DatePicker_MinMaxDateRange_Previews : PreviewProvider {
static var previews: some View {
Group {
DatePicker_MinMaxDateRange()
}
}
}
|
//
// SerializerDefinitions.swift
// XRPKit
//
// Created by Mitch Lang on 5/11/19.
//
import Foundation
let serializerDefinitions = """
{
"TYPES": {
"Validation": 10003,
"Done": -1,
"Hash128": 4,
"Blob": 7,
"AccountID": 8,
"Amount": 6,
"Hash256": 5,
"UInt8": 16,
"Vector256": 19,
"STObject": 14,
"Unknown": -2,
"Transaction": 10001,
"Hash160": 17,
"PathSet": 18,
"LedgerEntry": 10002,
"UInt16": 1,
"NotPresent": 0,
"UInt64": 3,
"UInt32": 2,
"STArray": 15
},
"LEDGER_ENTRY_TYPES": {
"Any": -3,
"Child": -2,
"Invalid": -1,
"AccountRoot": 97,
"DirectoryNode": 100,
"RippleState": 114,
"Ticket": 84,
"SignerList": 83,
"Offer": 111,
"LedgerHashes": 104,
"Amendments": 102,
"FeeSettings": 115,
"Escrow": 117,
"PayChannel": 120,
"DepositPreauth": 112,
"Check": 67,
"Nickname": 110,
"Contract": 99,
"GeneratorMap": 103
},
"FIELDS": [
[
"Generic",
{
"nth": 0,
"isVLEncoded": false,
"isSerialized": false,
"isSigningField": false,
"type": "Unknown"
}
],
[
"Invalid",
{
"nth": -1,
"isVLEncoded": false,
"isSerialized": false,
"isSigningField": false,
"type": "Unknown"
}
],
[
"LedgerEntryType",
{
"nth": 1,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt16"
}
],
[
"TransactionType",
{
"nth": 2,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt16"
}
],
[
"SignerWeight",
{
"nth": 3,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt16"
}
],
[
"Flags",
{
"nth": 2,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"SourceTag",
{
"nth": 3,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"Sequence",
{
"nth": 4,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"PreviousTxnLgrSeq",
{
"nth": 5,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"LedgerSequence",
{
"nth": 6,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"CloseTime",
{
"nth": 7,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"ParentCloseTime",
{
"nth": 8,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"SigningTime",
{
"nth": 9,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"Expiration",
{
"nth": 10,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"TransferRate",
{
"nth": 11,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"WalletSize",
{
"nth": 12,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"OwnerCount",
{
"nth": 13,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"DestinationTag",
{
"nth": 14,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"HighQualityIn",
{
"nth": 16,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"HighQualityOut",
{
"nth": 17,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"LowQualityIn",
{
"nth": 18,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"LowQualityOut",
{
"nth": 19,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"QualityIn",
{
"nth": 20,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"QualityOut",
{
"nth": 21,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"StampEscrow",
{
"nth": 22,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"BondAmount",
{
"nth": 23,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"LoadFee",
{
"nth": 24,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"OfferSequence",
{
"nth": 25,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"FirstLedgerSequence",
{
"nth": 26,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"LastLedgerSequence",
{
"nth": 27,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"TransactionIndex",
{
"nth": 28,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"OperationLimit",
{
"nth": 29,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"ReferenceFeeUnits",
{
"nth": 30,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"ReserveBase",
{
"nth": 31,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"ReserveIncrement",
{
"nth": 32,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"SetFlag",
{
"nth": 33,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"ClearFlag",
{
"nth": 34,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"SignerQuorum",
{
"nth": 35,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"CancelAfter",
{
"nth": 36,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"FinishAfter",
{
"nth": 37,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"IndexNext",
{
"nth": 1,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt64"
}
],
[
"IndexPrevious",
{
"nth": 2,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt64"
}
],
[
"BookNode",
{
"nth": 3,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt64"
}
],
[
"OwnerNode",
{
"nth": 4,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt64"
}
],
[
"BaseFee",
{
"nth": 5,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt64"
}
],
[
"ExchangeRate",
{
"nth": 6,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt64"
}
],
[
"LowNode",
{
"nth": 7,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt64"
}
],
[
"HighNode",
{
"nth": 8,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt64"
}
],
[
"EmailHash",
{
"nth": 1,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash128"
}
],
[
"LedgerHash",
{
"nth": 1,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"ParentHash",
{
"nth": 2,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"TransactionHash",
{
"nth": 3,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"AccountHash",
{
"nth": 4,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"PreviousTxnID",
{
"nth": 5,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"LedgerIndex",
{
"nth": 6,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"WalletLocator",
{
"nth": 7,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"RootIndex",
{
"nth": 8,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"AccountTxnID",
{
"nth": 9,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"BookDirectory",
{
"nth": 16,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"InvoiceID",
{
"nth": 17,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"Nickname",
{
"nth": 18,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"Amendment",
{
"nth": 19,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"TicketID",
{
"nth": 20,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"Digest",
{
"nth": 21,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"hash",
{
"nth": 257,
"isVLEncoded": false,
"isSerialized": false,
"isSigningField": false,
"type": "Hash256"
}
],
[
"index",
{
"nth": 258,
"isVLEncoded": false,
"isSerialized": false,
"isSigningField": false,
"type": "Hash256"
}
],
[
"Amount",
{
"nth": 1,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Amount"
}
],
[
"Balance",
{
"nth": 2,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Amount"
}
],
[
"LimitAmount",
{
"nth": 3,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Amount"
}
],
[
"TakerPays",
{
"nth": 4,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Amount"
}
],
[
"TakerGets",
{
"nth": 5,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Amount"
}
],
[
"LowLimit",
{
"nth": 6,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Amount"
}
],
[
"HighLimit",
{
"nth": 7,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Amount"
}
],
[
"Fee",
{
"nth": 8,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Amount"
}
],
[
"SendMax",
{
"nth": 9,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Amount"
}
],
[
"DeliverMin",
{
"nth": 10,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Amount"
}
],
[
"MinimumOffer",
{
"nth": 16,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Amount"
}
],
[
"RippleEscrow",
{
"nth": 17,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Amount"
}
],
[
"DeliveredAmount",
{
"nth": 18,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Amount"
}
],
[
"taker_gets_funded",
{
"nth": 258,
"isVLEncoded": false,
"isSerialized": false,
"isSigningField": false,
"type": "Amount"
}
],
[
"taker_pays_funded",
{
"nth": 259,
"isVLEncoded": false,
"isSerialized": false,
"isSigningField": false,
"type": "Amount"
}
],
[
"PublicKey",
{
"nth": 1,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Blob"
}
],
[
"MessageKey",
{
"nth": 2,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Blob"
}
],
[
"SigningPubKey",
{
"nth": 3,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Blob"
}
],
[
"TxnSignature",
{
"nth": 4,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": false,
"type": "Blob"
}
],
[
"Generator",
{
"nth": 5,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Blob"
}
],
[
"Signature",
{
"nth": 6,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": false,
"type": "Blob"
}
],
[
"Domain",
{
"nth": 7,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Blob"
}
],
[
"FundCode",
{
"nth": 8,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Blob"
}
],
[
"RemoveCode",
{
"nth": 9,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Blob"
}
],
[
"ExpireCode",
{
"nth": 10,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Blob"
}
],
[
"CreateCode",
{
"nth": 11,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Blob"
}
],
[
"MemoType",
{
"nth": 12,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Blob"
}
],
[
"MemoData",
{
"nth": 13,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Blob"
}
],
[
"MemoFormat",
{
"nth": 14,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Blob"
}
],
[
"Fulfillment",
{
"nth": 16,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Blob"
}
],
[
"Condition",
{
"nth": 17,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Blob"
}
],
[
"MasterSignature",
{
"nth": 18,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": false,
"type": "Blob"
}
],
[
"Account",
{
"nth": 1,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "AccountID"
}
],
[
"Owner",
{
"nth": 2,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "AccountID"
}
],
[
"Destination",
{
"nth": 3,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "AccountID"
}
],
[
"Issuer",
{
"nth": 4,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "AccountID"
}
],
[
"Authorize",
{
"nth": 5,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "AccountID"
}
],
[
"Unauthorize",
{
"nth": 6,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "AccountID"
}
],
[
"Target",
{
"nth": 7,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "AccountID"
}
],
[
"RegularKey",
{
"nth": 8,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "AccountID"
}
],
[
"ObjectEndMarker",
{
"nth": 1,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STObject"
}
],
[
"TransactionMetaData",
{
"nth": 2,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STObject"
}
],
[
"CreatedNode",
{
"nth": 3,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STObject"
}
],
[
"DeletedNode",
{
"nth": 4,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STObject"
}
],
[
"ModifiedNode",
{
"nth": 5,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STObject"
}
],
[
"PreviousFields",
{
"nth": 6,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STObject"
}
],
[
"FinalFields",
{
"nth": 7,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STObject"
}
],
[
"NewFields",
{
"nth": 8,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STObject"
}
],
[
"TemplateEntry",
{
"nth": 9,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STObject"
}
],
[
"Memo",
{
"nth": 10,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STObject"
}
],
[
"SignerEntry",
{
"nth": 11,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STObject"
}
],
[
"Signer",
{
"nth": 16,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STObject"
}
],
[
"Majority",
{
"nth": 18,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STObject"
}
],
[
"ArrayEndMarker",
{
"nth": 1,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STArray"
}
],
[
"Signers",
{
"nth": 3,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": false,
"type": "STArray"
}
],
[
"SignerEntries",
{
"nth": 4,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STArray"
}
],
[
"Template",
{
"nth": 5,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STArray"
}
],
[
"Necessary",
{
"nth": 6,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STArray"
}
],
[
"Sufficient",
{
"nth": 7,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STArray"
}
],
[
"AffectedNodes",
{
"nth": 8,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STArray"
}
],
[
"Memos",
{
"nth": 9,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STArray"
}
],
[
"Majorities",
{
"nth": 16,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "STArray"
}
],
[
"CloseResolution",
{
"nth": 1,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt8"
}
],
[
"Method",
{
"nth": 2,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt8"
}
],
[
"TransactionResult",
{
"nth": 3,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt8"
}
],
[
"TakerPaysCurrency",
{
"nth": 1,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash160"
}
],
[
"TakerPaysIssuer",
{
"nth": 2,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash160"
}
],
[
"TakerGetsCurrency",
{
"nth": 3,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash160"
}
],
[
"TakerGetsIssuer",
{
"nth": 4,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash160"
}
],
[
"Paths",
{
"nth": 1,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "PathSet"
}
],
[
"Indexes",
{
"nth": 1,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Vector256"
}
],
[
"Hashes",
{
"nth": 2,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Vector256"
}
],
[
"Amendments",
{
"nth": 3,
"isVLEncoded": true,
"isSerialized": true,
"isSigningField": true,
"type": "Vector256"
}
],
[
"Transaction",
{
"nth": 1,
"isVLEncoded": false,
"isSerialized": false,
"isSigningField": false,
"type": "Transaction"
}
],
[
"LedgerEntry",
{
"nth": 1,
"isVLEncoded": false,
"isSerialized": false,
"isSigningField": false,
"type": "LedgerEntry"
}
],
[
"Validation",
{
"nth": 1,
"isVLEncoded": false,
"isSerialized": false,
"isSigningField": false,
"type": "Validation"
}
],
[
"SignerListID",
{
"nth": 38,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"SettleDelay",
{
"nth": 39,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt32"
}
],
[
"Channel",
{
"nth": 22,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"ConsensusHash",
{
"nth": 23,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"CheckID",
{
"nth": 24,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "Hash256"
}
],
[
"TickSize",
{
"nth": 16,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt8"
}
],
[
"DestinationNode",
{
"nth": 9,
"isVLEncoded": false,
"isSerialized": true,
"isSigningField": true,
"type": "UInt64"
}
]
],
"TRANSACTION_RESULTS": {
"telNO_DST_PARTIAL": -393,
"temBAD_SRC_ACCOUNT": -281,
"tefPAST_SEQ": -189,
"terNO_ACCOUNT": -96,
"temREDUNDANT": -275,
"tefCREATED": -194,
"temDST_IS_SRC": -279,
"terRETRY": -99,
"temINVALID_FLAG": -276,
"temBAD_SEND_XRP_LIMIT": -288,
"terNO_LINE": -94,
"tefBAD_AUTH": -196,
"temBAD_EXPIRATION": -295,
"temBAD_SEND_XRP_NO_DIRECT": -286,
"temBAD_SEND_XRP_PATHS": -284,
"tefBAD_LEDGER": -195,
"tefNO_AUTH_REQUIRED": -190,
"terOWNERS": -93,
"terLAST": -91,
"terNO_RIPPLE": -90,
"temBAD_FEE": -294,
"terPRE_SEQ": -92,
"tefMASTER_DISABLED": -187,
"temBAD_CURRENCY": -296,
"tefDST_TAG_NEEDED": -193,
"temBAD_SIGNATURE": -282,
"tefFAILURE": -199,
"telBAD_PATH_COUNT": -397,
"temBAD_TRANSFER_RATE": -280,
"tefWRONG_PRIOR": -188,
"telBAD_DOMAIN": -398,
"temBAD_AMOUNT": -298,
"temBAD_AUTH_MASTER": -297,
"temBAD_LIMIT": -292,
"temBAD_ISSUER": -293,
"telBAD_PUBLIC_KEY": -396,
"tefBAD_ADD_AUTH": -197,
"temBAD_OFFER": -291,
"temBAD_SEND_XRP_PARTIAL": -285,
"temDST_NEEDED": -278,
"tefALREADY": -198,
"temUNCERTAIN": -272,
"telLOCAL_ERROR": -399,
"temREDUNDANT_SEND_MAX": -274,
"tefINTERNAL": -191,
"temBAD_PATH_LOOP": -289,
"tefEXCEPTION": -192,
"temRIPPLE_EMPTY": -273,
"telINSUF_FEE_P": -394,
"temBAD_SEQUENCE": -283,
"tefMAX_LEDGER": -186,
"terFUNDS_SPENT": -98,
"temBAD_SEND_XRP_MAX": -287,
"telFAILED_PROCESSING": -395,
"terINSUF_FEE_B": -97,
"tesSUCCESS": 0,
"temBAD_PATH": -290,
"temMALFORMED": -299,
"temUNKNOWN": -271,
"temINVALID": -277,
"terNO_AUTH": -95,
"temBAD_TICK_SIZE": -270,
"tecCLAIM": 100,
"tecPATH_PARTIAL": 101,
"tecUNFUNDED_ADD": 102,
"tecUNFUNDED_OFFER": 103,
"tecUNFUNDED_PAYMENT": 104,
"tecFAILED_PROCESSING": 105,
"tecDIR_FULL": 121,
"tecINSUF_RESERVE_LINE": 122,
"tecINSUF_RESERVE_OFFER": 123,
"tecNO_DST": 124,
"tecNO_DST_INSUF_XRP": 125,
"tecNO_LINE_INSUF_RESERVE": 126,
"tecNO_LINE_REDUNDANT": 127,
"tecPATH_DRY": 128,
"tecUNFUNDED": 129,
"tecNO_ALTERNATIVE_KEY": 130,
"tecNO_REGULAR_KEY": 131,
"tecOWNERS": 132,
"tecNO_ISSUER": 133,
"tecNO_AUTH": 134,
"tecNO_LINE": 135,
"tecINSUFF_FEE": 136,
"tecFROZEN": 137,
"tecNO_TARGET": 138,
"tecNO_PERMISSION": 139,
"tecNO_ENTRY": 140,
"tecINSUFFICIENT_RESERVE": 141,
"tecNEED_MASTER_KEY": 142,
"tecDST_TAG_NEEDED": 143,
"tecINTERNAL": 144,
"tecOVERSIZE": 145,
"tecCRYPTOCONDITION_ERROR": 146,
"tecINVARIANT_FAILED": 147,
"tecEXPIRED": 148,
"tecDUPLICATE": 149
},
"TRANSACTION_TYPES": {
"Invalid": -1,
"Payment": 0,
"EscrowCreate": 1,
"EscrowFinish": 2,
"AccountSet": 3,
"EscrowCancel": 4,
"SetRegularKey": 5,
"NickNameSet": 6,
"OfferCreate": 7,
"OfferCancel": 8,
"Contract": 9,
"TicketCreate": 10,
"TicketCancel": 11,
"SignerListSet": 12,
"PaymentChannelCreate": 13,
"PaymentChannelFund": 14,
"PaymentChannelClaim": 15,
"CheckCreate": 16,
"CheckCash": 17,
"CheckCancel": 18,
"DepositPreauth": 19,
"TrustSet": 20,
"EnableAmendment": 100,
"SetFee": 101
}
}
"""
|
//
// ViewController.swift
// SwipeableCards
//
// Created by admin on 16/7/22.
// Copyright © 2016年 Ding. All rights reserved.
//
import UIKit
class ViewController: UIViewController, SwipeableCardsDataSource, SwipeableCardsDelegate, UITableViewDelegate {
@IBOutlet weak var cards: SwipeableCards!
var cardsData = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
makeCardsData()
cards.dataSource = self
cards.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func makeCardsData() {
for i in 0..<100 {
cardsData.append(i)
}
}
@IBAction func changeOffset(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
cards.offset = (5, 5)
case 1:
cards.offset = (0, 5)
case 2:
cards.offset = (-5, 5)
case 3:
cards.offset = (-5, -5)
default:
break
}
}
@IBAction func changeNumber(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
cards.numberOfVisibleItems = 3
case 1:
cards.numberOfVisibleItems = 2
case 2:
cards.numberOfVisibleItems = 5
default:
break
}
}
@IBAction func changeSycllyState(sender: UISwitch) {
cards.showedCyclically = sender.on
}
// SwipeableCardsDataSource methods
func numberOfTotalCards(cards: SwipeableCards) -> Int {
return cardsData.count
}
func viewFor(cards: SwipeableCards, index: Int, reusingView: UIView?) -> UIView {
var label: UILabel? = view as? UILabel
if label == nil {
let size = cards.frame.size
let labelFrame = CGRect(x: 0, y: 0, width: size.width - 30, height: size.height - 20)
label = UILabel(frame: labelFrame)
label!.textAlignment = .Center
label!.layer.cornerRadius = 5
}
label!.text = String(cardsData[index])
label!.layer.backgroundColor = Color.randomColor().CGColor
return label!
}
// SwipeableCardsDelegate
func cards(cards: SwipeableCards, beforeSwipingItemAtIndex index: Int) {
print("Begin swiping card \(index)!")
}
func cards(cards: SwipeableCards, didLeftRemovedItemAtIndex index: Int) {
print("<--\(index)")
}
func cards(cards: SwipeableCards, didRightRemovedItemAtIndex index: Int) {
print("\(index)-->")
}
func cards(cards: SwipeableCards, didRemovedItemAtIndex index: Int) {
print("index of removed card:\(index)")
}
}
|
//
// CellTblDisplay.swift
// DemoKeyboard
//
// Created by admin on 08/03/21.
//
import UIKit
class CellTblDisplay: UITableViewCell {
@IBOutlet weak var imgDisplay: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.imgDisplay.layer.cornerRadius = 10
self.imgDisplay.layer.borderWidth = 1
self.imgDisplay.layer.borderColor = UIColor.clear.cgColor
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// Comment.swift
// Timeline
//
// Created by Taylor Mott on 11/3/15.
// Copyright © 2015 DevMountain. All rights reserved.
//
import Foundation
struct Comment: Equatable, FirebaseType {
private let kPost = "post"
private let kUsername = "username"
private let kText = "text"
let username: String
let text: String
let postIdentifier: String
var identifier: String?
var endpoint: String {
return "/posts/\(postIdentifier)/comments/"
}
var jsonValue: [String: AnyObject] {
return [kPost : postIdentifier, kUsername : username, kText : text]
}
init(username: String, text: String, postIdentifier: String, identifier: String? = nil) {
self.username = username
self.text = text
self.postIdentifier = postIdentifier
self.identifier = identifier
}
init?(json: [String : AnyObject], identifier: String) {
guard let postIdentifier = json[kPost] as? String,
let username = json[kUsername] as? String,
let text = json[kText] as? String else { return nil }
self.postIdentifier = postIdentifier
self.username = username
self.text = text
self.identifier = identifier
}
}
func ==(lhs: Comment, rhs: Comment) -> Bool {
return (lhs.username == rhs.username) && (lhs.identifier == rhs.identifier)
}
|
//
// SimpleCalcTests.swift
// SimpleCalcTests
//
// Created by Vincent Saluzzo on 29/03/2019.
// Copyright © 2019 Vincent Saluzzo. All rights reserved.
//
import XCTest
@testable import CountOnMe
class CountOnMeTests: XCTestCase {
var calculate = Calculator()
// MARK: ADDITION
// 0 + 0 = 0
func testGivenFirstNumberZero_WhenSecondNumberIsZero_ThenResultIsZero() {
calculate.addElement("0")
calculate.addElement("+")
calculate.addElement("0")
XCTAssertEqual(calculate.calcul(), "0")
}
// 0 + 1-9 = 1-9
func testGivenFirstNumberZero_WhenSecondNumberIsNoZero_ThenResultIsEgalToTheSecondNumber() {
calculate.addElement("4")
calculate.addElement("+")
calculate.addElement("3")
XCTAssertEqual(calculate.calcul(), "7")
}
// 890 + 60 = 950
func testGivenFirstNumberHaveTreeDecimal_WhenSecondNumberHaveTwoDecimal_ThenResultIsAdditionOfTwoNumber() {
calculate.addElement("890")
calculate.addElement("+")
calculate.addElement("60")
XCTAssertEqual(calculate.calcul(), "950")
}
// 1 + 2 + 0 = 3
func testGivenFirstAndSecondNumberIsNoZero_WhenNumberTreeIsZero_ThenResultIsAdditionOfTwoFirstNumber() {
calculate.addElement("1")
calculate.addElement("+")
calculate.addElement("2")
calculate.addElement("+")
calculate.addElement("0")
XCTAssertEqual(calculate.calcul(), "3")
}
// MARK: SUBSTRACTION
// 0 - 0 = 0
func testGivenFirstNumberZero_WhenSecondNumberIsZero_ThenResultSubstractionIsZero() {
calculate.addElement("0")
calculate.addElement("-")
calculate.addElement("0")
XCTAssertEqual(calculate.calcul(), "0")
}
// 0 - 1-9 = -1-9
func testGivenFirstNumberZero_WhenSecondNumberIsNoZero_ThenResultIsNegactiveSecondNumber() {
calculate.addElement("0")
calculate.addElement("-")
calculate.addElement("6")
XCTAssertEqual(calculate.calcul(), "-6")
}
// 890 - 60 = 830
func testGivenFirstNumberHaveTreeDecimal_WhenSecondNumberHaveTwoDecimal_ThenResultIsSubstractionOfTwoNumber() {
XCTAssertEqual(calculate.soustraction(x: 890, y: 60), "830")
}
// MARK: MULTIPLICATION
// 0 * 0 = 0
func testGivenFirstNumberZero_WhenSecondNumberIsZero_ThenResultMultiplicationIsZero() {
calculate.addElement("0")
calculate.addElement("*")
calculate.addElement("0")
XCTAssertEqual(calculate.calcul(), "0")
}
// 0 * 1-9 = 0
func testGivenFirstNumberZero_WhenSecondNumberIsNoZero_ThenResultMultiplicationIsZero() {
calculate.addElement("0")
calculate.addElement("*")
calculate.addElement("5")
XCTAssertEqual(calculate.calcul(), "0")
}
// 890 * 60 = 53400
func testGivenFirstNumberHaveTreeDecimal_WhenSecondNumberHaveTwoDecimal_ThenResultIsEgalToMultiplicationOfTwoNumber() {
calculate.addElement("890")
calculate.addElement("*")
calculate.addElement("60")
XCTAssertEqual(calculate.calcul(), "53400")
}
// MARK: DIVISION
// 0 / 0 = Error
func testGivenFirstNumberZero_WhenSecondNumberIsZero_ThenResultDivisionIsError() {
calculate.addElement("0")
calculate.addElement("/")
calculate.addElement("0")
XCTAssertEqual(calculate.calcul(), "ERROR")
}
// 0 / 1-9 = 0
func testGivenFirstNumberZero_WhenSecondNumberIsNoZero_ThenResultDivisionIsZero() {
calculate.addElement("0")
calculate.addElement("/")
calculate.addElement("3")
XCTAssertEqual(calculate.calcul(), "0")
}
// 1-9 / 0 = Error
func testGivenFirstNumberIsNoZero_WhenSecondNumberIsZero_ThenResultDivisionIsError() {
calculate.addElement("3")
calculate.addElement("/")
calculate.addElement("0")
XCTAssertEqual(calculate.calcul(), "inf")
}
// 890 / 60 = 830
func testGivenFirstNumberHaveTreeDecimal_WhenSecondNumberHaveTwoDecimal_henResultIsEgalToTheDivisionOfTwoNumber() {
calculate.addElement("890")
calculate.addElement("/")
calculate.addElement("60")
XCTAssertEqual(calculate.calcul(), "14.83")
}
// MARK: PRIORITIES
// 3 + 16 : 8 = 5
func testGivenWeHaveInFirstAddition_WhenWeHaveInSecondDivision_ThenDivisionHavePrioritieAndIsCalculateFirst() {
calculate.addElement("3")
calculate.addElement("+")
calculate.addElement("16")
calculate.addElement("/")
calculate.addElement("8")
XCTAssertEqual(calculate.calcul(), "5")
}
// 2 - 4 * 5 = -13
func testGivenWeHaveInFirstSubstraction_WhenWeHaveInSecondMultiplication_ThenMultiplicationHavePrioritieAndIsCalculateFirst() {
calculate.addElement("2")
calculate.addElement("-")
calculate.addElement("4")
calculate.addElement("*")
calculate.addElement("5")
XCTAssertEqual(calculate.calcul(), "-18")
}
// MARK: ADD ELEMENT
func testGivenAddNewElement_WhenAddElementHaveIsFive_ThenTheLastElementIsFive() {
calculate.addElement("5")
XCTAssertEqual(calculate.elements.last, "5")
}
func testGivenCalculHaveEnoughElement_WhenAddElementHaveTreeElement_ThenExpressionHaveEnoughElementIsTrue() {
calculate.addElement("5")
calculate.addElement("+")
calculate.addElement("26")
XCTAssertTrue(calculate.expressionHaveEnoughElement)
}
func testGivenCalculHaveEnoughElement_WhenAddElementHaveTwoElement_ThenExpressionHaveEnoughElementIsTrue() {
calculate.addElement("5")
calculate.addElement("+")
XCTAssertFalse(calculate.expressionHaveEnoughElement)
}
// MARK: EXPRESSION HAVE RESULT
func testGivenExpressionHaveResult_WhenElementContainEqual_ThenEpressionHaveResultTrue() {
calculate.addElement("=")
XCTAssertTrue(calculate.expressionHaveResult)
}
// MARK: CALCUL
func testGivenCalculHaveResult_WhenExpressionIsCorrect_ThenCaculHaveResult() {
calculate.addElement("5")
calculate.addElement("+")
calculate.addElement("26")
calculate.addElement("/")
calculate.addElement("2")
XCTAssertEqual(calculate.calcul(), "18")
}
func testGivenCalculNotHaveResult_WhenOperandIsIncorrect_ThenCaculHaveErrorResult() {
calculate.addElement("5")
calculate.addElement("@")
calculate.addElement("26")
calculate.addElement("/")
calculate.addElement("2")
XCTAssertEqual(calculate.calcul(), "ERROR")
}
// MARK: CAN ADD OPERATOR
func testGivenAddOperator_WhenLastElementIsNotNullAndIsNotAOperator_ThenICanAddOperator() {
calculate.addElement("5")
calculate.addElement("+")
calculate.addElement("2")
XCTAssertTrue(calculate.canAddOperator)
}
// MARK: EXPRESSION IS CORRECT
func testGivenexpressionIsCorrect_WhenLastElementIsNotNullAndIsNotAOperator_ThenExpressionIsCorrect() {
calculate.addElement("5")
calculate.addElement("+")
calculate.addElement("2")
XCTAssertTrue(calculate.expressionIsCorrect)
}
func testGivenLeftIsCorrect_WhenLeftIsString_ThenLeftEqualZero() {
calculate.addElement("test")
calculate.addElement("+")
calculate.addElement("0")
XCTAssertEqual(calculate.calcul(), "0")
}
func testGivenRightIsCorrect_WhenRightIsString_ThenRightEqualZero() {
calculate.addElement("0")
calculate.addElement("+")
calculate.addElement("test")
XCTAssertEqual(calculate.calcul(), "0")
}
}
|
//
// CourseViewController.swift
// Catalog
//
// Created by Elgendy on 1.05.2020.
// Copyright © 2020 Elgendy. All rights reserved.
//
import UIKit
import Common
public protocol CourseCoordinatorProtocol: Coordinator {}
public class CourseViewController: UIViewController {
public weak var coordinator: CourseCoordinatorProtocol?
public init() {
super.init(nibName: "CourseViewController", bundle: Bundle(identifier: "dev.elgendy.Course"))
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func viewDidLoad() {
super.viewDidLoad()
}
}
|
//
// UITextField.swift
// prkng-ios
//
// Created by Antonino Urbano on 2015-08-11.
// Copyright (c) 2015 PRKNG. All rights reserved.
//
extension UITextField {
func modifyClearButtonWithImageNamed(imageName: String, color: UIColor) {
let image = UIImage(named: imageName)?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
let button = UIButton(type: UIButtonType.Custom)
button.setImage(image, forState: UIControlState.Normal)
button.tintColor = color
button.frame = CGRect(x: 0, y: 0, width: 35, height: SearchFilterView.FIELD_HEIGHT)
button.contentMode = UIViewContentMode.Left
button.addTarget(self, action: "textFieldClear:", forControlEvents: UIControlEvents.TouchUpInside)
button.backgroundColor = Styles.Colors.cream1
self.rightView = button
self.rightViewMode = UITextFieldViewMode.Always
}
func textFieldClear(sender: AnyObject) {
self.delegate?.textFieldShouldClear!(self)
}
}
|
//
// ios_projectApp.swift
// ios-project
//
// Created by Eric Webb on 10/8/21.
//
import SwiftUI
@main
struct ios_projectApp: App {
@State private var message: String
init() {
hs_init(nil, nil)
print("ios_projectApp init")
message = String(cString: hello())
}
var body: some Scene {
WindowGroup {
ContentView(message: $message)
}
}
}
|
//
// vcResultInsertion.swift
// ETBAROON
//
// Created by imac on 10/3/17.
// Copyright © 2017 IAS. All rights reserved.
//
import UIKit
class vcResultInsertion: UIViewController {
@IBOutlet weak var lblFirstTeam: UILabel!
@IBOutlet weak var lblSeconondTeam: UILabel!
@IBOutlet weak var txtTeamScore1: UITextField!
@IBOutlet weak var txtTeamScore2: UITextField!
var teamPoints1 :String = ""
var teamPoints2 : String = ""
var SingelItemGame:OldGames?
var gameId : String = ""
override func viewDidLoad() {
super.viewDidLoad()
lblFirstTeam.text = SingelItemGame?.fldAppTeamName1
lblSeconondTeam.text = SingelItemGame?.fldAppTeamName2
gameId = (SingelItemGame?.fldAppGameID)!
// Do any additional setup after loading the view.
}
//String(Int(input1.text!)! + Int(input2.text!)!)
@IBAction func btnSaveResult(_ sender: Any) {
guard let teamScore1 = txtTeamScore1.text?.trimmed, !teamScore1.isEmpty, let teamScore2 = txtTeamScore2.text?.trimmed, !teamScore2.isEmpty else {
let attributedString = NSAttributedString(string: "خطا", attributes: [
NSFontAttributeName : UIFont.systemFont(ofSize: 15), //your font here
NSForegroundColorAttributeName : UIColor.red
])
let alert = UIAlertController(title: "", message: "لابد من ادخال جميع الحقول", preferredStyle: UIAlertControllerStyle.alert)
alert.setValue(attributedString, forKey: "attributedTitle")
alert.addAction(UIAlertAction(title: "موافق", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil);
//EnableBtn()
return }
if (teamScore1.characters.count > 2 || teamScore2.characters.count > 2){
let alertController = UIAlertController(title: "Error", message: "رقميت فقط", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
return
}
if((Int(txtTeamScore1.text!)!>Int(txtTeamScore2.text!)!))
{
teamPoints1 = "3"
teamPoints2 = "0"
}
else if((Int(txtTeamScore2.text!)!>Int(txtTeamScore1.text!)!))
{
teamPoints1 = "0"
teamPoints2 = "3"
}
else
{
teamPoints1 = "1"
teamPoints2 = "1"
}
print("\(teamPoints1)\(teamPoints2)")
handleRefersh()
}
@objc private func handleRefersh()
{
let teamScore1 = "\(String(describing: txtTeamScore1.text))"
let teamScore2 = "\(String(describing: txtTeamScore2.text))"
API_OldGames.inserGameScore(fldAppTeamID1Score: teamScore1, fldAppTeamID2Score: teamScore2, fldAppTeamID1Points: teamPoints1, fldAppTeamID2Points: teamPoints2,fldAppGameID: self.gameId) { (error: Error?, success: Bool) in
if success {
// print("Reigster succeed !! welcome to our small app :)")
self.setAlert(message: " تم ")
}
else {
self.setAlert(message: "تم التسجيل بالفعل ")
}
}
}
func setAlert(message : String)
{
let attributedString = NSAttributedString(string: " ", attributes: [
NSFontAttributeName : UIFont.systemFont(ofSize: 15), //your font here
NSForegroundColorAttributeName : UIColor.green
])
let alert = UIAlertController(title: "", message: "\(message)", preferredStyle: UIAlertControllerStyle.alert)
alert.setValue(attributedString, forKey: "attributedTitle")
alert.addAction(UIAlertAction(title: "موافق", style: UIAlertActionStyle.default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
|
#if canImport(SwiftUI)
import SwiftUI
#endif
@available(iOS 13, *)
public typealias Colour = Color
|
//
// Names.swift
// Svátky
//
// Created by Štěpán Vích on 03/05/2018.
// Copyright © 2018 Štěpán Vích. All rights reserved.
//
import Foundation
public struct Day {
let day: Int;
let month: Int;
let names : [String];
init(_ day: Int, _ month: Int, _ names : [String]) {
self.day = day;
self.month = month;
self.names = names;
}
public func calculateOffset(dayToAdd: Int) -> Day {
let dayDate = NSDateComponents()
dayDate.month = self.month
dayDate.day = self.day
let notificationDate = NSCalendar(identifier: NSCalendar.Identifier.gregorian)?.date(from: dayDate as DateComponents)
let offsetDate = Calendar.current.date(byAdding: .day, value: dayToAdd, to: notificationDate!);
// Extract day, month and year from offsetDate
let f = DateFormatter();
f.dateFormat = "MM";
let offsetMonth = Int(f.string(from: offsetDate!));
f.dateFormat = "dd";
let offsetDay = Int(f.string(from: offsetDate!));
return Day(offsetDay!, offsetMonth!, self.names);
}
}
// Help class for searching in static structure
public class Names {
public static func nameToDate(name:String) -> Day? {
for record in namesArray {
for recordName in record.names {
if recordName.lowercased() == name.lowercased() {
return Day(record.day, record.month, [name]);
}
}
}
return nil;
}
public static func dateToName(day: Int, month: Int) -> String {
for record in namesArray {
if record.day == day && record.month == month {
return record.names[0];
}
}
return "--";
}
private static let namesArray:[Day] = [
Day(1,1, ["Den obnovy"]),
Day(2,1, ["Karina", "Karína", "Karin"]),
Day(3,1, ["Radmila"]),
Day(4,1, ["Diana"]),
Day(5,1, ["Dalimil", "Dalemil"]),
Day(6,1, ["Tři Králové"]),
Day(7,1, ["Vilma", "Wilhelmina"]),
Day(8,1, ["Čestmír"]),
Day(9,1, ["Vladan"]),
Day(10,1, ["Břetislav"]),
Day(11,1, ["Bohdana"]),
Day(12,1, ["Pravoslav"]),
Day(13,1, ["Edita"]),
Day(14,1, ["Radovan"]),
Day(15,1, ["Alice"]),
Day(16,1, ["Ctirad", "Česlav"]),
Day(17,1, ["Drahoslav"]),
Day(18,1, ["Vladislav"]),
Day(19,1, ["Doubravka"]),
Day(20,1, ["Ilona"]),
Day(21,1, ["Běla"]),
Day(22,1, ["Slavomír"]),
Day(23,1, ["Zdeněk", "Zdenek", "Zdenko"]),
Day(24,1, ["Milena"]),
Day(25,1, ["Miloš"]),
Day(26,1, ["Zora"]),
Day(27,1, ["Ingrid"]),
Day(28,1, ["Otýlie", "Otilie"]),
Day(29,1, ["Zdislava", "Zdeslava"]),
Day(30,1, ["Robin"]),
Day(31,1, ["Marika"]),
Day(1,2, ["Hynek"]),
Day(2,2, ["Nela"]),
Day(3,2, ["Blažej"]),
Day(4,2, ["Jarmila"]),
Day(5,2, ["Dobromila"]),
Day(6,2, ["Vanda", "Wanda"]),
Day(7,2, ["Veronika"]),
Day(8,2, ["Milada"]),
Day(9,2, ["Apolena"]),
Day(10,2, ["Mojmír"]),
Day(11,2, ["Božena"]),
Day(12,2, ["Slavěna"]),
Day(13,2, ["Věnceslav"]),
Day(14,2, ["Valentýn", "Valentin", "Valentýna"]),
Day(15,2, ["Jiřina", "Jorga"]),
Day(16,2, ["Ljuba"]),
Day(17,2, ["Miloslav"]),
Day(18,2, ["Gizela", "Gisela"]),
Day(19,2, ["Patrik"]),
Day(20,2, ["Oldřich"]),
Day(21,2, ["Lenka", "Eleonora"]),
Day(22,2, ["Petr"]),
Day(23,2, ["Svatopluk"]),
Day(24,2, ["Matěj", "Matej", "Matyáš"]),
Day(25,2, ["Liliana", "Lilian", "Lily"]),
Day(26,2, ["Dorota", "Dorotea"]),
Day(27,2, ["Alexandr", "Alexander", "Alexis"]),
Day(28,2, ["Lumír"]),
Day(1,3, ["Bedřich"]),
Day(2,3, ["Anežka", "Agnes", "Ines"]),
Day(3,3, ["Kamil"]),
Day(4,3, ["Stela", "Stella"]),
Day(5,3, ["Kazimír"]),
Day(6,3, ["Miroslav", "Mirek"]),
Day(7,3, ["Tomáš", "Thomas", "Tom"]),
Day(8,3, ["Gabriela"]),
Day(9,3, ["Františka", "Francesca"]),
Day(10,3, ["Viktorie"]),
Day(11,3, ["Anděla", "Andělína", "Angelina"]),
Day(12,3, ["Řehoř", "Gregor"]),
Day(13,3, ["Růžena", "Rozálie", "Rosita"]),
Day(14,3, ["Rút", "Rut", "Matylda"]),
Day(15,3, ["Ida"]),
Day(16,3, ["Elena", "Herbert"]),
Day(17,3, ["Vlastimil"]),
Day(18,3, ["Eduard", "Edvard"]),
Day(19,3, ["Josef", "Jozef"]),
Day(20,3, ["Světlana"]),
Day(21,3, ["Radek", "Radomil"]),
Day(22,3, ["Leona"]),
Day(23,3, ["Ivona", "Yvona"]),
Day(24,3, ["Gabriel"]),
Day(25,3, ["Marián", "Marian", "Marius"]),
Day(26,3, ["Emanuel"]),
Day(27,3, ["Dita", "Ditta"]),
Day(28,3, ["Soňa", "Sonja", "Sonia"]),
Day(29,3, ["Taťana", "Tatiana"]),
Day(30,3, ["Arnošt"]),
Day(31,3, ["Kvido", "Quido"]),
Day(1,4, ["Hugo"]),
Day(2,4, ["Erika"]),
Day(3,4, ["Richard"]),
Day(4,4, ["Ivana", "Ivanka"]),
Day(5,4, ["Miroslava", "Mirka"]),
Day(6,4, ["Vendula", "Vendulka"]),
Day(7,4, ["Heřman", "Herman", "Hermína"]),
Day(8,4, ["Ema", "Emma"]),
Day(9,4, ["Dušan", "Dušana"]),
Day(10,4, ["Darja", "Daria", "Darya"]),
Day(11,4, ["Izabela", "Isabel"]),
Day(12,4, ["Julius", "Július", "Julian"]),
Day(13,4, ["Aleš"]),
Day(14,4, ["Vincenc", "Vincent"]),
Day(15,4, ["Anastázie", "Anastazia"]),
Day(16,4, ["Irena", "Irini"]),
Day(17,4, ["Rudolf", "Rolf"]),
Day(18,4, ["Valerie", "Valérie", "Valeria"]),
Day(19,4, ["Rostislava"]),
Day(20,4, ["Marcela"]),
Day(21,4, ["Alexandra"]),
Day(22,4, ["Evženie", "Evžénie"]),
Day(23,4, ["Vojtěch"]),
Day(24,4, ["Jiří", "Juraj", "George"]),
Day(25,4, ["Marek"]),
Day(26,4, ["Oto", "Ota", "Otto"]),
Day(27,4, ["Jaroslav"]),
Day(28,4, ["Vlastislav"]),
Day(29,4, ["Robert"]),
Day(30,4, ["Blahoslav"]),
Day(1,5, ["Svátek Práce"]),
Day(2,5, ["Zikmund"]),
Day(3,5, ["Alexej", "Alex"]),
Day(4,5, ["Květoslav"]),
Day(5,5, ["Klaudie", "Klaudia", "Claudia"]),
Day(6,5, ["Radoslav"]),
Day(7,5, ["Stanislav"]),
Day(8,5, ["Den Vítězství"]),
Day(9,5, ["Ctibor", "Stibor"]),
Day(10,5, ["Blažena"]),
Day(11,5, ["Svatava"]),
Day(12,5, ["Pankrác"]),
Day(13,5, ["Servác"]),
Day(14,5, ["Bonifác"]),
Day(15,5, ["Žofie"]),
Day(16,5, ["Přemysl"]),
Day(17,5, ["Aneta", "Anitta"]),
Day(18,5, ["Nataša"]),
Day(19,5, ["Ivo", "Ivoš"]),
Day(20,5, ["Zbyšek"]),
Day(21,5, ["Monika"]),
Day(22,5, ["Emil"]),
Day(23,5, ["Vladimír"]),
Day(24,5, ["Jana"]),
Day(25,5, ["Viola"]),
Day(26,5, ["Filip"]),
Day(27,5, ["Valdemar", "Waldemar"]),
Day(28,5, ["Vilém"]),
Day(29,5, ["Maxmilián", "Maxmilian", "Maximilian"]),
Day(30,5, ["Ferdinand"]),
Day(31,5, ["Kamila"]),
Day(1,6, ["Laura"]),
Day(2,6, ["Jarmil"]),
Day(3,6, ["Tamara"]),
Day(4,6, ["Dalibor"]),
Day(5,6, ["Dobroslav"]),
Day(6,6, ["Norbert"]),
Day(7,6, ["Iveta", "Yveta"]),
Day(8,6, ["Medard"]),
Day(9,6, ["Stanislava"]),
Day(10,6, ["Otta"]),
Day(11,6, ["Bruno"]),
Day(12,6, ["Antonie", "Antonina"]),
Day(13,6, ["Antonín", "Antonin"]),
Day(14,6, ["Roland"]),
Day(15,6, ["Vít", "Vítek"]),
Day(16,6, ["Zbyněk"]),
Day(17,6, ["Adolf"]),
Day(18,6, ["Milan"]),
Day(19,6, ["Leoš"]),
Day(20,6, ["Květa", "Kveta"]),
Day(21,6, ["Alois", "Aloys", "ALojz"]),
Day(22,6, ["Pavla"]),
Day(23,6, ["Zdeňka", "Zdena", "Zdenka"]),
Day(24,6, ["Jan"]),
Day(25,6, ["Ivan"]),
Day(26,6, ["Adriana"]),
Day(27,6, ["Ladislav"]),
Day(28,6, ["Lubomír", "Lubomil"]),
Day(29,6, ["Petr", "Pavel"]),
Day(30,6, ["Šárka"]),
Day(1,7, ["Jaroslava"]),
Day(2,7, ["Patricie"]),
Day(3,7, ["Radomír"]),
Day(4,7, ["Prokop"]),
Day(5,7, ["Den slovanských věrozvěstů Cyrila a Metoděje"]),
Day(6,7, ["Den upáleni mistra Jana Husa"]),
Day(7,7, ["Bohuslava"]),
Day(8,7, ["Nora"]),
Day(9,7, ["Drahoslava"]),
Day(10,7, ["Libuše", "Amálie"]),
Day(11,7, ["Olga"]),
Day(12,7, ["Bořek"]),
Day(13,7, ["Markéta", "Margareta", "Margit"]),
Day(14,7, ["Karolína", "Karolina", "Karla"]),
Day(15,7, ["Jindřich"]),
Day(16,7, ["Luboš", "Liboslava", "Luboslav"]),
Day(17,7, ["Martina"]),
Day(18,7, ["Drahomíra"]),
Day(19,7, ["Čeněk"]),
Day(20,7, ["Ilja"]),
Day(21,7, ["Vítězslav"]),
Day(22,7, ["Magdaléna", "Magdalena"]),
Day(23,7, ["Libor"]),
Day(24,7, ["Kristýna", "Kristina", "Kristen"]),
Day(25,7, ["Jakub"]),
Day(26,7, ["Anna"]),
Day(27,7, ["Věroslav"]),
Day(28,7, ["Viktor", "Victor"]),
Day(29,7, ["Marta", "Martha"]),
Day(30,7, ["Bořivoj"]),
Day(31,7, ["Ignác"]),
Day(1,8, ["Oskar"]),
Day(2,8, ["Gustav"]),
Day(3,8, ["Miluše"]),
Day(4,8, ["Dominik"]),
Day(5,8, ["Kristián", "Milivoj", "Křišťan"]),
Day(6,8, ["Oldřiška"]),
Day(7,8, ["Lada"]),
Day(8,8, ["Soběslav"]),
Day(9,8, ["Roman"]),
Day(10,8, ["Vavřinec"]),
Day(11,8, ["Zuzana", "Susana"]),
Day(12,8, ["Klára", "Clara"]),
Day(13,8, ["Alena"]),
Day(14,8, ["Alan"]),
Day(15,8, ["Hana", "Hanka", "Hannah"]),
Day(16,8, ["Jáchym", "Joachim"]),
Day(17,8, ["Petra", "Petronila"]),
Day(18,8, ["Helena"]),
Day(19,8, ["Ludvík"]),
Day(20,8, ["Bernard"]),
Day(21,8, ["Johana"]),
Day(22,8, ["Bohuslav", "Božislav"]),
Day(23,8, ["Sandra"]),
Day(24,8, ["Bartoloměj", "Bartolomej"]),
Day(25,8, ["Radim", "Radimír"]),
Day(26,8, ["Luděk"]),
Day(27,8, ["Otakar", "Otokar"]),
Day(28,8, ["Augustýn", "Augustin"]),
Day(29,8, ["Evelína", "Evelin", "Evelina"]),
Day(30,8, ["Vladěna"]),
Day(31,8, ["Pavlína", "Paulína"]),
Day(1,9, ["Linda", "Samuel"]),
Day(2,9, ["Adéla", "Adléta", "Adela"]),
Day(3,9, ["Bronislav"]),
Day(4,9, ["Jindřiška", "Henrieta"]),
Day(5,9, ["Boris"]),
Day(6,9, ["Boleslav"]),
Day(7,9, ["Regina", "Regína"]),
Day(8,9, ["Mariana"]),
Day(9,9, ["Daniela"]),
Day(10,9, ["Irma"]),
Day(11,9, ["Denisa", "Denis"]),
Day(12,9, ["Marie"]),
Day(13,9, ["Lubor"]),
Day(14,9, ["Radka"]),
Day(15,9, ["Jolana"]),
Day(16,9, ["Ludmila"]),
Day(17,9, ["Naděžda"]),
Day(18,9, ["Kryštof", "Krištof"]),
Day(19,9, ["Zita"]),
Day(20,9, ["Oleg"]),
Day(21,9, ["Matouš"]),
Day(22,9, ["Darina"]),
Day(23,9, ["Berta", "Bertina"]),
Day(24,9, ["Jaromír"]),
Day(25,9, ["Zlata"]),
Day(26,9, ["Andrea", "Ondřejka"]),
Day(27,9, ["Jonáš"]),
Day(28,9, ["Václav", "Václava"]),
Day(29,9, ["Michal", "Michael"]),
Day(30,9, ["Jeroným", "Jeronym", "Jarolím"]),
Day(1,10, ["Igor"]),
Day(2,10, ["Olívie", "Olivia", "Oliver"]),
Day(3,10, ["Bohumil"]),
Day(4,10, ["František"]),
Day(5,10, ["Eliška", "Elsa"]),
Day(6,10, ["Hanuš"]),
Day(7,10, ["Justýna", "Justina", "Justin"]),
Day(8,10, ["Věra", "Viera"]),
Day(9,10, ["Štefan", "Sára"]),
Day(10,10, ["Marina", "Marína"]),
Day(11,10, ["Andrej"]),
Day(12,10, ["Marcel"]),
Day(13,10, ["Renáta", "Renata"]),
Day(14,10, ["Agáta"]),
Day(15,10, ["Tereza"]),
Day(16,10, ["Havel"]),
Day(17,10, ["Hedvika"]),
Day(18,10, ["Lukáš"]),
Day(19,10, ["Michaela", "Michala"]),
Day(20,10, ["Vendelín"]),
Day(21,10, ["Brigita", "Bridget"]),
Day(22,10, ["Sabina"]),
Day(23,10, ["Teodor", "Theodor"]),
Day(24,10, ["Nina"]),
Day(25,10, ["Beáta", "Beata"]),
Day(26,10, ["Erik", "Ervín"]),
Day(27,10, ["Šarlota", "Zoe", "Zoja"]),
Day(28,10, ["Den vzniku samostatného ČS státu"]),
Day(29,10, ["Silvie", "Sylva", "Silva"]),
Day(30,10, ["Tadeáš"]),
Day(31,10, ["Štěpánka", "Stefanie"]),
Day(1,11, ["Felix"]),
Day(2,11, ["--"]),
Day(3,11, ["Hubert"]),
Day(4,11, ["Karel"]),
Day(5,11, ["Miriam"]),
Day(6,11, ["Liběna"]),
Day(7,11, ["Saskie"]),
Day(8,11, ["Bohumír"]),
Day(9,11, ["Bohdan"]),
Day(10,11, ["Evžen", "Eugen"]),
Day(11,11, ["Martin"]),
Day(12,11, ["Benedikt"]),
Day(13,11, ["Tibor"]),
Day(14,11, ["Sáva"]),
Day(15,11, ["Leopold"]),
Day(16,11, ["Otmar", "Otomar"]),
Day(17,11, ["Mahulena"]),
Day(18,11, ["Romana"]),
Day(19,11, ["Alžběta", "Elisabeth"]),
Day(20,11, ["Nikola"]),
Day(21,11, ["Albert"]),
Day(22,11, ["Cecílie"]),
Day(23,11, ["Klement", "Kliment"]),
Day(24,11, ["Emília", "Emilia"]),
Day(25,11, ["Kateřina", "Katka", "Katarína"]),
Day(26,11, ["Artur"]),
Day(27,11, ["Xenie"]),
Day(28,11, ["René", "Renée"]),
Day(29,11, ["Zina"]),
Day(30,11, ["Ondřej"]),
Day(1,12, ["Iva"]),
Day(2,12, ["Blanka"]),
Day(3,12, ["Svatoslav", "Světoslav"]),
Day(4,12, ["Barbora", "Barbara", "Bára"]),
Day(5,12, ["Jitka"]),
Day(6,12, ["Mikuláš", "Mikoláš", "Nikolas"]),
Day(7,12, ["Ambrož"]),
Day(8,12, ["Květoslava"]),
Day(9,12, ["Vratislav"]),
Day(10,12, ["Julie", "Julia", "Juliana"]),
Day(11,12, ["Dana"]),
Day(12,12, ["Simona", "Šimona", "Simeona"]),
Day(13,12, ["Lucie", "Lucia", "Luciana"]),
Day(14,12, ["Lýdie", "Lydia", "Lydie"]),
Day(15,12, ["Radana"]),
Day(16,12, ["Albína"]),
Day(17,12, ["Daniel", "Dana"]),
Day(18,12, ["Miloslav"]),
Day(19,12, ["Ester"]),
Day(20,12, ["Dagmar", "Dagmara", "Dáša"]),
Day(21,12, ["Natálie"]),
Day(22,12, ["Šimon"]),
Day(23,12, ["Vlasta"]),
Day(24,12, ["Adam", "Eva"]),
Day(25,12, ["1. svátek vánoční"]),
Day(26,12, ["Štěpán"]),
Day(27,12, ["Žaneta"]),
Day(28,12, ["Bohumila"]),
Day(29,12, ["Judita"]),
Day(30,12, ["David"]),
Day(31,12, ["Silvestr", "Silverter", "Sylvestr"])
]
}
|
//
// ItemStateViewC+Additions.swift
// MyLoqta
//
// Created by Ashish Chauhan on 13/08/18.
// Copyright © 2018 AppVenturez. All rights reserved.
//
import Foundation
extension ItemStateViewC {
func registerNib() {
//OrderIdDateCell DetailProductTypeCell , SellerCell for buyer cell
// Driver
self.tblViewProduct.register(ItemImageTableCell.self)
self.tblViewProduct.register(RejectedCell.self)
self.tblViewProduct.register(OrderTrackingCell.self)
self.tblViewProduct.register(ItemNamePriceCell.self)
self.tblViewProduct.register(ItemDescriptionCell.self)
self.tblViewProduct.register(ItemStateQuantity.self)
self.tblViewProduct.register(OrderIdDateCell.self)
self.tblViewProduct.register(ItemCell.self)
self.tblViewProduct.register(DriverCell.self)
self.tblViewProduct.register(ItemPriceCell.self)
self.tblViewProduct.register(DetailProductTypeCell.self)
self.tblViewProduct.register(SellerCell.self)
//self.tblViewOrderDetail.register(PaymentMethodCell.self)
}
}
extension ItemStateViewC: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
guard let _ = self.orderDetail else { return 0 }
return 5
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0: return self.arrayProductDetail.count
case 1: return self.arrayProductType.count
case 2: return 3
case 3: return self.arrayDriver.count
case 4: return 1
default: return 0
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch section {
case 0, 1: return 0
case 2: return 20
case 3: return (self.arrayDriver.count > 0 ? 20 : 0)
case 4: return 20
default: return 0
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.section {
case 0: return self.getCellHeight(indexPath: indexPath)
case 1: return UITableViewAutomaticDimension
case 2: return self.getThirdSectionHt(indexPath: indexPath)
case 3: return 88
case 4: return 62
default: return UITableViewAutomaticDimension
}
}
func getThirdSectionHt(indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0 {
return 88
} else {
return UITableViewAutomaticDimension
}
}
func getCellHeight(indexPath: IndexPath) -> CGFloat {
if let cellType = self.arrayProductDetail[indexPath.row][Constant.keys.kCellType] as? CellType {
switch cellType {
case .imageCell: return (191.0 * Constant.htRation)
case .orderIdDateCell: return 65
case .orderProgressCell: return 63
case .rejectedCell: return UITableViewAutomaticDimension
case .itemNameCell: return UITableViewAutomaticDimension
}
}
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: Constant.screenWidth, height: 20))
view.backgroundColor = UIColor.defaultBgColor
return view
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case 0: return self.getItemDetailCell(tableView: tableView, indexPath: indexPath)
case 1: return self.getItemTypeCell(tableView: tableView, indexPath: indexPath)
case 2: return self.getThirdSectionCell(tableView: tableView, indexPath: indexPath)
case 3: return self.getDriverCell(tableView: tableView, indexPath: indexPath)
case 4: return self.getItemPriceQuantityCell(tableView: tableView, indexPath: indexPath)
default: break
}
return UITableViewCell()
}
func getItemDetailCell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
let data = self.arrayProductDetail[indexPath.row]
if let cellType = data[Constant.keys.kCellType] as? CellType {
switch cellType {
case .imageCell:
let cell: ItemImageTableCell = tableView.dequeueReusableCell(forIndexPath: indexPath)
cell.configureCell(data: data)
cell.btnBack.addTarget(self, action: #selector(tapBack), for: .touchUpInside)
return cell
case .orderIdDateCell:
let cell: OrderIdDateCell = tableView.dequeueReusableCell(forIndexPath: indexPath)
cell.configureCell(data: data)
return cell
case .orderProgressCell:
let cell: OrderTrackingCell = tableView.dequeueReusableCell(forIndexPath: indexPath)
cell.configureCell(data: data)
return cell
case .rejectedCell:
let cell: RejectedCell = tableView.dequeueReusableCell(forIndexPath: indexPath)
cell.configureCell(data: data)
return cell
case .itemNameCell:
let cell: ItemNamePriceCell = tableView.dequeueReusableCell(forIndexPath: indexPath)
cell.configureCell(data: data)
return cell
}
}
return UITableViewCell()
}
func getItemTypeCell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
let cell: ItemDescriptionCell = tableView.dequeueReusableCell(forIndexPath: indexPath)
cell.configureCell(data: self.arrayProductType[indexPath.row])
return cell
}
func getThirdSectionCell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell: SellerCell = tableView.dequeueReusableCell(forIndexPath: indexPath)
if let order = self.orderDetail {
cell.configureCell(orderDetail: order)
}
return cell
} else {
let cell: ItemDescriptionCell = tableView.dequeueReusableCell(forIndexPath: indexPath)
if let order = self.orderDetail {
var newIndexPath = indexPath
newIndexPath.row = newIndexPath.row - 1
cell.configureAddressCell(order: order, indexPath: newIndexPath)
}
return cell
}
}
func getDriverCell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
let cell: SellerCell = tableView.dequeueReusableCell(forIndexPath: indexPath)
cell.configureDriverCell(driver: self.arrayDriver[indexPath.row])
return cell
}
func getItemPriceQuantityCell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
let cell: ItemStateQuantity = tableView.dequeueReusableCell(forIndexPath: indexPath)
if let order = self.orderDetail {
cell.configureCell(order: order)
}
return cell
}
}
|
//
// DetailTableViewCell.swift
// MyWeather
//
// Created by RaymonLewis on 8/15/16.
// Copyright © 2016 RaymonLewis. All rights reserved.
//
import UIKit
class DetailTableViewCell: UITableViewCell {
@IBOutlet weak var dayLabel: UILabel!
@IBOutlet weak var highTempLabel: UILabel!
@IBOutlet weak var lowTempLabel: UILabel!
@IBOutlet weak var detailCollectionView: UICollectionView!
var dailyWeatherData : DailyWeatherData? {
didSet {
setWeatherData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
setView()
}
func setWeatherData() {
if let day = self.dailyWeatherData?.dayOfTheWeek {
self.dayLabel.text = day
}
if let maxTemp = self.dailyWeatherData?.maxTemp {
let celciusMaxTemp = ViewController.fahrenheitToCelcius(maxTemp)
let formattedTemp = String(format: "%.f˚", celciusMaxTemp)
self.highTempLabel.text = formattedTemp
}
if let minTemp = self.dailyWeatherData?.minTemp {
let celciusMinTemp = ViewController.fahrenheitToCelcius(minTemp)
let formattedTemp = String(format: "%.f˚", celciusMinTemp)
self.lowTempLabel.text = formattedTemp
}
}
func setView() {
self.detailCollectionView.registerNib(UINib(nibName: "DetailCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: Constants.Identifiers.collectionViewCellID)
self.backgroundColor = UIColor.clearColor()
self.detailCollectionView.backgroundColor = UIColor.clearColor()
}
func setCollectionViewDataSourceDelegate
<D: protocol<UICollectionViewDataSource, UICollectionViewDelegate>>
(dataSourceDelegate: D, forRow row: Int) {
self.detailCollectionView.delegate = dataSourceDelegate
self.detailCollectionView.dataSource = dataSourceDelegate
self.detailCollectionView.tag = row
self.detailCollectionView.reloadData()
}
}
|
//
// GroupInvitationPermissionSettingJson.swift
// GworldSuperOffice
//
// Created by 陈琪 on 2020/8/1.
// Copyright © 2020 Gworld. All rights reserved.
//
import Foundation
// MARK: 会议室邀请权限设置
let GroupInvitationPermissionSettingJson: [String: Any] = [
"version": "0",
"template": [
"viewType": "StackView",
"property": ["axis":"vertical", "distribution": "fill", "alignment": "fill", "space": 0, "margin":[0, 0, 0, 0], "backgroudColor": "#0F1219"],
// 声明页面全局初始状态 reducer处理各状态直接关联业务逻辑
"state":[
"group_id": "",
// "list": "${memberList}",
"invitationType":1, // 邀请权限设置
"section0_list": [
["name": "仅管理员可邀请", "identifier": "templates_0", "image": "sign_selected.png", "isSelected":1, "invitationType":1, "actionType": "showPage", "actionParam": ["pageId": "groupManagerSetting", "group_id": "${group_id}"]],
["name": "全员可邀请", "identifier": "templates_0", "image": "sign_selected.png", "isSelected":0, "invitationType":2, "actionType": "showPage", "actionParam": ["pageId": "groupInvitationPermission"]],
["name": "部分成员可邀请", "identifier": "templates_0", "image": "sign_selected.png", "isSelected":0, "invitationType":3, "actionType": "showPage", "actionParam": ["pageId": "Blacklist"]]]
],
// 声明请求列表 initLoad方法只在界面初始加载调用
"requests":[
"initLoad":["meetingGroupService": ["group_id":"${group_id}", "pageIndex":0, "pageSize": 50, "search_key": "", "updated_at": 0]],
// "headerLoad":["group_id":"${group_id}", "page": 1],
// "footerLoad":["group_id":"${group_id}", "page": "${loadPage}"] // 底部上拉加载刷新
],
"subViews": [
// header
["templateType": "navHeader_1",
"property": ["title": "会议室邀请权限"]
],
// body
[
"viewType": "TableView",
"property": ["headerHeight": 54, "style": "plan", "color": "#0C0E13", "separatorStyle": "none"],
// "refreshControl": ["needRefresh": 1, "style": "default"],
// 模板数据映射关系
"templatesReflect": [
"templates_0": ["title": "${name}", "image": "${image}", "isSelected": "${isSelected}", "actionType": "signSelected","actionParam": ["selectedElement": "${invitationType}", "connectState": ["section0_list", "invitationType"]]],
"templates_4": ["headerIcon": "default_head.png","title": "${name}", "subTitle": "粉丝:3231"]
],
"dynamicSections": [
// ["header": "", "list": [
// ["name": "仅管理员可邀请", "identifier": "templates_0", "image": "sign_selected.png", "isSelected":1, "invitationType":1, "actionType": "showPage", "actionParam": ["pageId": "groupManagerSetting", "group_id": "${group_id}"]],
//
// ["name": "全员可邀请", "identifier": "templates_0", "image": "sign_selected.png", "isSelected":0, "invitationType":2, "actionType": "showPage", "actionParam": ["pageId": "groupInvitationPermission"]],
//
// ["name": "部分成员可邀请", "identifier": "templates_0", "image": "sign_selected.png", "isSelected":0, "invitationType":3, "actionType": "showPage", "actionParam": ["pageId": "Blacklist"]]]],
["header": "", "list": ["rowItems": "${section0_list}", "rowIdentifier": "1", "identifierMap": ["1":"templates_0"]]]
// ["header": "添加可邀请成员", "list": ["rowItems": "${list}", "rowIdentifier": "1", "identifierMap": ["1":"templates_4"]]]
],
// 侧滑Action配置
// "swipeActions": [
// ["title": "删除", "backgroudColor": "#FF5454","image": "login_exit_icon.png", "action": ["actionType": "objRemove", "params": ["connectState": ["list"], "rmvObj":"${memberName}", "filterKey":"memberName"]]],
// ["title": "标记已读", "backgroudColor": "#01CA58"],
// ["title": "标记未读", "backgroudColor": "#FFA100"]],
//
// "dynamicSections": [
// ["header": "", "list": ["rowItems": "${list}", "rowIdentifier": "1", "identifierMap": ["1":"templates_4"]]]
// ],
"subViews": [
]
]
]
],
"serviceData": [
"memberList": [
["memberHeader": "default_head.png", "name": "张三", "subTitle": "浙江省,丽水区"],
["memberHeader": "default_head.png", "name": "李四", "subTitle": "浙江省,丽水区"],
["memberHeader": "default_head.png", "name": "王五", "subTitle": "浙江省,丽水区"],
["memberHeader": "default_head.png", "name": "张三1", "subTitle": "浙江省,丽水区"]
]
]
]
|
//
// CapturedImage.swift
// Capture Images
//
// Created by Stefan Blos on 05.05.19.
// Copyright © 2019 Stefan Blos. All rights reserved.
//
struct CapturedImage: Codable {
let image: String
let name: String
}
|
import Foundation
internal enum ArgumentsError: String, Error {
case NoGoogleAPIKey = "No Google API Key was provided in GOOGLE_API_KEY environment variable"
}
internal enum ParseError: String, Error {
case NoEventsFolder = "No folder was provided as an argument to parse events from"
case NoEvents = "No events were found in the provided folder"
case NoEventDate = "Event's date or start time are not properly formatted"
}
|
//
// AppConstants.swift
// NewProject
//
// Created by Dharmesh Avaiya on 22/08/20.
// Copyright © 2020 dharmesh. All rights reserved.
//
import UIKit
let kAppName : String = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String ?? String()
let kAppBundleIdentifier : String = Bundle.main.bundleIdentifier ?? String()
enum DeviceType: String {
case iOS = "iOS"
case android = "android"
}
let emptyJsonString = "{}"
struct ICSettings {
static let cornerRadius: CGFloat = 5
static let borderWidth: CGFloat = 1
static let shadowOpacity: Float = 0.4
static let tableViewMargin: CGFloat = 50
static let nameLimit = 20
static let emailLimit = 70
static let passwordLimit = 20
static let footerMargin: CGFloat = 50
static let profileImageSize = CGSize.init(width: 400, height: 400)
static let profileBorderWidth: CGFloat = 4 }
struct ICColor {
static let appButton = UIColor(named: "appButton")
static let appWhite = UIColor(named: "appWhite")
static let appBorder = UIColor(named: "appBorder")
static let appLabel = UIColor(named: "appLabel")
static let appBlack = UIColor(named: "appBlack")
}
struct ICFont {
static let defaultRegularFontSize: CGFloat = 20.0
static let zero: CGFloat = 0.0
static let reduceSize: CGFloat = 3.0
static let increaseSize : CGFloat = 2.0
//"family: Poppins "
static func PoppinsLight(size: CGFloat?) -> UIFont {
return UIFont(name: "Poppins-Light", size: size ?? defaultRegularFontSize)!
}
static func PoppinsMedium(size: CGFloat?) -> UIFont {
return UIFont(name: "Poppins-Medium", size: size ?? defaultRegularFontSize)!
}
static func PoppinsRegular(size: CGFloat?) -> UIFont {
return UIFont(name: "Poppins-Regular", size: size ?? defaultRegularFontSize)!
}
static func PoppinsSemiBold(size: CGFloat?) -> UIFont {
return UIFont(name: "Poppins-SemiBold", size: size ?? defaultRegularFontSize)!
}
}
struct ICImageName {
static let iconLogo = "logo"
static let iconMail = "mail"
static let iconPassword = "password"
static let iconCheck = "check"
static let iconUncheck = "uncheck"
static let iconUser = "user"
}
struct ICScreenName {
static let subscribed = "subscribed"
static let home = "home"
static let settings = "settings"
}
|
//
// ViewController.swift
// Swift_Word_IB
//
// Created by 陈凡 on 15/8/22.
// Copyright (c) 2015年 湖南省 永州市 零陵区 湖南科技学院. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var lable:UILabel!
@IBOutlet weak var button:UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
button.addTarget(self, action: "clicked:", forControlEvents: UIControlEvents.TouchUpInside)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func clicked(sender:AnyObject){
NSLog("您点击了")
}
}
|
//
// NaturalLanguageViewController.swift
// Whatsnew11and12
//
// Created by Jan Kaltoun on 19/11/2019.
// Copyright © 2019 Jan Kaltoun. All rights reserved.
//
import UIKit
import NaturalLanguage
class NaturalLanguageViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
textView.text = """
💪 Here's to the crazy ones. The misfits. The rebels. The troublemakers.
🍏 meeting is at 14:00.
"""
/*textView.text = """
STRV s.r.o. is a company based at Rohanske nabrezi 678/23, 186 00 Prague.
Jan Kaltoun, Jan Schwarz and Jan Pacek are 🍏 platform leads.
The Android leads are Petr Nohejl and Juraj Kuliska.
"""*/
textView.text = """
Steve Jobs, Steve Wozniak, and Ronald Wayne founded Apple Inc in California.
"""
}
@IBAction func getDominantLanguage(_ sender: Any) {
let language = NLLanguageRecognizer.dominantLanguage(for: textView.text)
let languageName = language?.rawValue ?? "unknown"
let alert = UIAlertController(title: "Dominant language", message: languageName, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Awesome!", style: .default, handler: nil))
present(alert, animated: true)
}
@IBAction func getTokens(_ sender: Any) {
let text = textView.text!
let tokenizer = NLTokenizer(unit: .word)
tokenizer.string = text
var tokens = [String]()
tokenizer.enumerateTokens(in: text.startIndex ..< text.endIndex) { (range, attrs) -> Bool in
tokens.append("[\(attrs.rawValue)] \(text[range])")
return true
}
let message = tokens.joined(separator: "\n")
let alert = UIAlertController(title: "Found tokens", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Awesome!", style: .default, handler: nil))
present(alert, animated: true)
}
@IBAction func getNames(_ sender: Any) {
let text = textView.text!
let tagger = NLTagger(tagSchemes: [.nameType])
tagger.string = text
let options: NLTagger.Options = [.omitPunctuation, .omitWhitespace, .joinNames]
let tags: [NLTag] = [.personalName, .placeName, .organizationName]
var names = [String]()
tagger.enumerateTags(
in: text.startIndex..<text.endIndex,
unit: .word,
scheme: .nameType,
options: options
) { tag, tokenRange in
if let tag = tag, tags.contains(tag) {
names.append("[\(tag.rawValue)]: \(text[tokenRange])")
}
return true
}
let message = names.joined(separator: "\n")
let alert = UIAlertController(title: "Found names", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Awesome!", style: .default, handler: nil))
present(alert, animated: true)
}
}
|
//
// ProfileViewModel.swift
// HamHumApp
//
// Created by ALEMDAR on 22.08.2021.
//
import Foundation
protocol ProfileViewModelProtocol {
func load()
}
protocol ProfileViewModelDelegate: AnyObject {
func dataLoaded()
}
class ProfileViewModel: BaseViewModel {
var user: User?
weak var delegate: ProfileViewModelDelegate?
private func fetchUserInfo(){
let uid = UserDefaults.standard.integer(forKey: "userID")
print(uid)
API().fetchUserInfo(id: uid) { [weak self] (result) in
switch result {
case .success(let userInfoResponse):
self?.user = userInfoResponse.user
self?.delegate?.dataLoaded()
case .failure(let error):
print(error)
}
}
}
}
extension ProfileViewModel: ProfileViewModelProtocol {
func load() {
fetchUserInfo()
}
}
|
//
// ImageTransitionAnimator.swift
// Friends
//
// Created by Hayden Hastings on 5/23/19.
// Copyright © 2019 Hayden Hastings. All rights reserved.
//
import UIKit
class ImageTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromTVC = transitionContext.viewController(forKey: .from) as? FriendsTableViewCell,
let toVC = transitionContext.viewController(forKey: .to) as? FriendsDetailViewController,
let toView = transitionContext.view(forKey: .to) else { return }
let containerView = transitionContext.containerView
containerView.addSubview(toView)
let toViewEndFrame = transitionContext.finalFrame(for: toVC)
toView.frame = toViewEndFrame
let fromImage = fromTVC.photoImageView!
let toImage = toVC.photoImageView!
let fromLabel = fromTVC.nameLabel!
let toLabel = toVC.nameLabel!
toView.layoutIfNeeded()
let transitionalImageFrame = containerView.convert(fromImage.bounds, from: fromImage)
let transitionalImageEndFrame = containerView.convert(toImage.bounds, from: toImage)
let transitionalLabelFrame = containerView.convert(fromLabel.bounds, from: fromLabel)
let transitionalLabelEndFrame = containerView.convert(toLabel.bounds, from: toLabel)
let transitionalImage = UIImageView(frame: transitionalImageFrame)
let transitionalLabel = UILabel(frame: transitionalLabelFrame)
transitionalLabel.text = fromLabel.text
transitionalLabel.font = fromLabel.font
transitionalLabel.textColor = fromLabel.textColor
transitionalImage.image = fromImage.image
containerView.addSubview(transitionalImage)
containerView.addSubview(transitionalLabel)
let animationDuration = self.transitionDuration(using: transitionContext)
toLabel.alpha = 0
fromLabel.alpha = 0
UIView.animate(withDuration: animationDuration, animations: {
transitionalLabel.frame = transitionalLabelEndFrame
transitionalLabel.textColor = toLabel.textColor
transitionalImage.frame = transitionalImageEndFrame
}) { (_) in
transitionalLabel.removeFromSuperview()
toLabel.alpha = 1
fromLabel.alpha = 1
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
|
//
// ExpandableHeaderView.swift
// ExpandTableViewSample
//
// Created by Daisuke Todate on 2017/12/19.
// Copyright © 2017年 Daisuke Todate. All rights reserved.
//
import UIKit
protocol ExpandableHeaderViewDelegate {
func toggleSection(header: ExpandableHeaderView, section: Int)
}
class ExpandableHeaderView: UITableViewHeaderFooterView {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var iconImageView: UIImageView!
var delegate: ExpandableHeaderViewDelegate?
var section: Int!
override func awakeFromNib() {
self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(selectHeaderAction)))
}
@objc func selectHeaderAction(gestureRecognizer: UITapGestureRecognizer) {
let cell = gestureRecognizer.view as! ExpandableHeaderView
delegate?.toggleSection(header: self, section: cell.section)
}
override func layoutSubviews() {
super.layoutSubviews()
}
}
|
//
// CodeAnalyserCLI.swift
// pinfo
//
// Created by Mikael Konradsson on 2021-03-12.
//
import Foundation
import CodeAnalyser
import Funswift
struct CodeAnalyserCLI {
// TODO: Should this be in this library?
static func printTime(_ value: Double) -> IO<Void> {
IO { print("Total time: " + "\(value)".textColor(.accentColor) + " seconds") }
}
static func printLargestFiles(take: Int) -> ([FileLineInfo]) -> IO<Void> {
{ fileInfo in
IO {
let largestFiles = fileInfo
.sorted(by: { $0.linecount > $1.linecount })
.prefix(take)
.map { ($0.path, $0.linecount)}
largestFiles.forEach { (path, count) in
Console.output("\(path):", text: "\(count)", color: .lineColor)
}
Console.output("Total files:", text: "\(fileInfo.count)", color: .barColor)
}
}
}
static func printSummary(_ langs: [LanguageSummary], statistics: [Statistics]) -> IO<Void> {
IO {
var langSummaries = langs
if langSummaries.count == 2 {
langSummaries = langSummaries.dropLast()
}
langSummaries
.map(printSummaryFor)
.forEach { $0.unsafeRun() }
_ = zip(
printPercentSummary(statistics),
lineSeparator()
).unsafeRun()
}
}
static func printSummaryFor(_ language: LanguageSummary) -> IO<Void> {
guard language.filetype != .empty
else { return IO { } }
return IO {
let width = 35
Console.output(language.filetype.description, color: .white, lineWidth: width)
Console.output("classes:", data: language.classes, color: .classColor, width: width)
Console.output("\(language.filetype.structs.trimEnd):", data: language.structs, color: .structColor, width: width)
Console.output("\(language.filetype.enums.trimEnd):", data: language.enums, color: .enumColor, width: width)
Console.output("functions:", data: language.functions, color: .functionColor, width: width)
Console.output("\(language.filetype.interfaces.trimEnd):", data: language.interfaces, color: .interfaceColor, width: width)
Console.output("\(language.filetype.imports)", data: language.imports, color: .functionColor, width: width)
Console.output("\(language.filetype.extensions)", data: language.extensions, color: .functionColor, width: width)
Console.output("files:", data: language.filecount, color: .fileColor, width: width)
Console.output("lines:", data: language.linecount, color: .lineColor, width: width)
Console.output("Avg lines:", data: language.linecount / language.filecount, color: .lineColor, width: width)
}
}
static func printTodoSummary(_ todos: [Todo]) -> IO<Void> {
IO {
todos.map(printTodo).forEach { $0.unsafeRun() }
}
}
}
// MARK: - Private
extension CodeAnalyserCLI {
private static func printTodo(_ todo: Todo) -> IO<Void> {
IO {
printTodoComment(
for: todo.path,
comments: todo.comments
)
.unsafeRun()
}
}
private static func printTodoComment(for file: String, comments: [Comment]) -> IO<Void> {
IO {
Console.output(text: file, color: .classColor)
comments.forEach { comment in
Console.output(" #\(comment.line):", text: comment.comment, color: .enumColor)
}
}
}
private static func printPercentSummary(_ statistics: [Statistics]) -> IO<Void> {
guard statistics.isEmpty == false
else { return IO {} }
return IO {
let rounding = Rounding.decimals(1)
statistics
.filter { $0.lineCountPercentage > 0 }
.forEach { stat in
let percentage = rounding(stat.lineCountPercentage).unsafeRun()
lineSeparator().unsafeRun()
Console.output(
stat.filetype.description + " code",
text: "\(percentage) %",
color: .structColor,
width: 35
)
}
}
}
private static func lineSeparator(color: TerminalColor = .accentColor) -> IO<Void> {
printRepeatingCharacter("—", count: 35, color: color)
}
private static func printRepeatingCharacter(
_ char: Character,
count: Int,
color: TerminalColor = .accentColor
) -> IO<Void> {
IO { print(String(repeating: char, count: count).textColor(color)) }
}
}
|
//
// EmojiArtDocumentChooserTest.swift
// EmojiArtDocumentChooserTest
//
// Created by Hanna Lisa Franz on 14.01.21.
//
import XCTest
class EmojiArtDocumentChooserTest: XCTestCase {
func testEditName() throws {
let app = XCUIApplication()
app.launch()
app.buttons["plus"].tap()
app.buttons["Edit"].tap()
app.tables.cells.element(boundBy: 0).tap()
app.keys["Löschen"].tap()
app.keys["Löschen"].tap()
app.keys["Löschen"].tap()
app.keys["Löschen"].tap()
app.keys["Löschen"].tap()
app.keys["Löschen"].tap()
app.keys["Löschen"].tap()
app.keys["Löschen"].tap()
app.keys["C"].tap()
app.keys["o"].tap()
app.keys["w"].tap()
app.buttons["Done"].tap()
XCTAssertTrue(app.tables.cells.element(boundBy: 0).label=="Cow")
}
}
|
//
// Tweet.swift
// Twitter
//
// Created by Randy Ting on 9/30/15.
// Copyright © 2015 Randy Ting. All rights reserved.
//
import UIKit
import SwiftyJSON
class Tweet: NSObject {
// MARK: - Properties
let createdAt: String!
var favoriteCount: Int!
let idString: String!
let id: UInt64!
var retweetCount: Int!
let text: String!
let userName: String!
let userScreenname: String!
let profileImageURL: NSURL!
let retweetedStatus: [String:JSON]?
let originalTweetIdString: String?
var mediaURL: NSURL?
var favorited: Bool!
var retweeted: Bool!
// MARK: - Init
init(dictionary: [String: JSON]) {
createdAt = dictionary["created_at"]!.string
favoriteCount = dictionary["favorite_count"]?.int
idString = dictionary["id_str"]?.string
retweetCount = dictionary["retweet_count"]?.int
text = dictionary["text"]?.string
userName = dictionary["user"]!["name"].string
userScreenname = dictionary["user"]!["screen_name"].string
id = dictionary["id"]?.uInt64
retweetedStatus = dictionary["retweeted_status"]?.dictionary
originalTweetIdString = dictionary["retweeted_status"]?["id_str"].string
var profileImageURLString = dictionary["user"]!["profile_image_url_https"].string
let range = profileImageURLString!.rangeOfString("normal.jpg", options: .RegularExpressionSearch)
if let range = range {
profileImageURLString = profileImageURLString!.stringByReplacingCharactersInRange(range, withString: "bigger.jpg")
}
profileImageURL = NSURL(string: profileImageURLString!)
if let mediaURLString = dictionary["entities"]?["media"][0]["media_url_https"].string {
mediaURL = NSURL(string: mediaURLString)
}
favorited = dictionary["favorited"]?.bool
retweeted = dictionary["retweeted"]?.bool
super.init()
}
// MARK: - Class Methods
class func tweets(array array: [JSON]) -> [Tweet] {
var tweets = [Tweet]()
for tweet in array {
let tweetDictionary = tweet.dictionary!
tweets.append(Tweet.init(dictionary: tweetDictionary ))
}
return tweets
}
}
|
//
// CarService.swift
// CarTrackApp
//
// Created by Batu Orhanalp on 16/05/2017.
// Copyright © 2017 Batu Orhanalp. All rights reserved.
//
import Foundation
import Alamofire
struct CarService {
private static let rootPath = "cars.json"
static func get(completion: @escaping ([Car]) -> ()) {
if Router.checkConnection == .NotReachable {
return
}
// First clearing database in case of removed cars
DatabaseMethods.clearDatabase {
/*
* After database clearing completition fetchs the cars from Rest API
*/
let router = Router(method: .get, path: CarService.rootPath, parameters: nil)
do {
let request = try router.asURLRequest()
_ = Alamofire.request(request)
.responseObject(completionHandler: { (response: DataResponse<CarResponse>) in
debugPrint("Car response: \(response)")
if let value = response.result.value {
// Saving serialized data to Realm database
for car in value.cars {
_ = car.save(type: Car.self)
}
completion(value.cars)
} else {
completion([Car]())
}
})
} catch {
print("An error occured: \(error)")
completion([Car]())
}
}
}
}
/*
* Car service response serialization
*/
struct CarResponse: ResponseObjectSerializable, ResponseCollectionSerializable {
var cars = [Car]()
init?(response: HTTPURLResponse, representation: AnyObject) {
let object = representation as AnyObject
cars = Car.collection(response: response, representation: object)
}
}
|
//
// HourlyCollectionViewCell.swift
// viewtTesting
//
// Created by urjhams on 3/8/18.
// Copyright © 2018 urjhams. All rights reserved.
//
import UIKit
class HourlyCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var iconImage: UIImageView!
@IBOutlet weak var tempLabel: UILabel!
var hourlyUnit:HourlyModel? {
didSet {
if let unit = hourlyUnit {
timeLabel.text = convertToDate(fromTimeStamp: unit.time)
tempLabel.text = String(Int(currentTempMode == .F ? unit.temp : convertToC(fromF: unit.temp))) + "º" + (currentTempMode == .F ? " F" : " C")
iconImage.image = UIImage(named: unit.icon + "-icon")
}
}
}
}
|
//
// CustomAlertViewController.swift
// Teachify
//
// Created by Philipp on 14.06.18.
// Copyright © 2018 Christian Pfeiffer. All rights reserved.
//
import UIKit
class CustomAlertViewController : UIViewController{
@IBOutlet weak var alertView: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var alertTextField: UITextField!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var saveButton: UIButton!
@IBOutlet weak var cancelButtonView: UIView!
@IBOutlet weak var saveButtonView: UIView!
@IBOutlet var heightConstraint: NSLayoutConstraint!
@IBOutlet var subjectType: UISegmentedControl!
var delegate: CustomAlertViewDelegate?
var caller : CustomAlertViewCallers!
override func viewDidLoad() {
super.viewDidLoad()
alertTextField.becomeFirstResponder()
self.providesPresentationContextTransitionStyle = true
self.definesPresentationContext = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupView()
animateView()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
view.layoutIfNeeded()
}
func setupView(){
createCornerRadius()
setupText()
view.backgroundColor = UIColor.lightGray.withAlphaComponent(0.4)
alertTextField.tintColor = UIColor.black
}
func animateView(){
alertView.alpha = 0
alertView.backgroundColor = UIColor.clear
alertView.frame.origin.y = alertView.frame.origin.y + 50
UIView.animate(withDuration: 0.4, animations: { () -> Void in
self.alertView.alpha = 1;
self.alertView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.9)
self.alertView.frame.origin.y = self.alertView.frame.origin.y - 50
})
}
@IBAction func onClickCancelButton(_ sender: Any) {
alertTextField.resignFirstResponder()
delegate?.cancelButtonTapped()
self.dismiss(animated: true, completion: nil)
}
@IBAction func onSaveCancelButton(_ sender: Any) {
alertTextField.resignFirstResponder()
let color = getSelectedColor()
delegate?.okButtonTapped(textFieldValue: alertTextField.text!, subjectColor: color,with: caller)
self.dismiss(animated: true, completion: nil)
}
private func getSelectedColor() -> TKColor {
switch subjectType.selectedSegmentIndex {
case 0: return .mathBlue
case 1: return .teacherRed
default:
return TKColor.black
}
}
private func createCornerRadius(){
alertView.layer.masksToBounds = true
alertView.layer.cornerRadius = 15
let path = UIBezierPath(roundedRect:cancelButtonView.bounds,
byRoundingCorners:[.bottomLeft],
cornerRadii: CGSize(width: 15, height: 15))
let maskLayer = CAShapeLayer()
maskLayer.path = path.cgPath
cancelButtonView.layer.mask = maskLayer
let path2 = UIBezierPath(roundedRect:saveButtonView.bounds,
byRoundingCorners:[.bottomRight],
cornerRadii: CGSize(width: 15, height: 15))
let maskLayer2 = CAShapeLayer()
maskLayer2.path = path2.cgPath
saveButtonView.layer.mask = maskLayer2
}
private func setupText(){
guard let caller = caller else {return}
switch caller {
case .tkSubject:
titleLabel.text = "Create a new subject"
descriptionLabel.text = "Enter subject name"
case .tkClass:
titleLabel.text = "Create a new class"
descriptionLabel.text = "Enter class name"
heightConstraint.constant = 0
subjectType.isHidden = true
}
}
}
enum CustomAlertViewCallers{
case tkClass
case tkSubject
}
|
//
// CustomTVC.swift
// Api_Task
//
// Created by Farhana Khan on 11/04/21.
//
import UIKit
class CustomTVC: UITableViewCell {
@IBOutlet weak var timeLb: UILabel!
@IBOutlet weak var headerLb: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// DetailsView.swift
// NTGTags
//
// Created by Mena Gamal on 2/16/20.
// Copyright © 2020 Mena Gamal. All rights reserved.
//
import Foundation
import UIKit
protocol DetailsView :class{
var mainImageView: UIImageView! {
get set
}
var labelName: UILabel! {
get set
}
var labelDesc: UILabel! {
get set
}
var eventsCollection: UICollectionView! {
get set
}
var storiesCollection: UICollectionView! {
get set
}
var seriesCollection: UICollectionView! {
get set
}
var comicsCollection: UICollectionView! {
get set
}
}
|
//
// CollectionViewController.swift
// CalenderTesting
//
// Created by Thomas Martin on 1/1/17.
// Copyright © 2017 Thomas Martin. All rights reserved.
//
import UIKit
enum Style {
case classic
case fun
}
class CollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var monthLabel: UILabel!
//@IBOutlet weak var eventsLabel: UILabel!
@IBOutlet weak var eventsTable: UITableView!
var daysInMonth = 31
var startWeekday = 1
var currentStyle: Style = Style.fun
var primaryColor: UIColor = UIColor(red: 26/256, green: 35/256, blue: 126/256, alpha: 1.0)
var secondaryColor: UIColor = UIColor(red: 197/256, green: 202/256, blue: 233/256, alpha: 1.0)
var showMonthLabel: Bool = true
var selectedCellView: UIView?
var monthString: String?
var month: Int?
var yearString: String?
var year: Int?
var eventsArr: [Event] = []
var cellArr: [Int: DayCollectionViewCell] = [:]
var tableViewDelegate: EventsTableDelegate?
var today: Int = -1
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
//eventsLabel.isHidden = true
eventsTable.isHidden = true
tableViewDelegate = EventsTableDelegate(eventsArr: [], tableView: eventsTable, primaryColor: primaryColor)
eventsTable.delegate = tableViewDelegate
eventsTable.dataSource = tableViewDelegate
collectionView.translatesAutoresizingMaskIntoConstraints = false
if !showMonthLabel {
let topConstraint = NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.topLayoutGuide, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)
self.view.addConstraint(topConstraint)
monthLabel.removeFromSuperview()
} else {
let topConstraint = NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: monthLabel, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)
self.view.addConstraint(topConstraint)
}
if currentStyle == Style.fun {
collectionView.backgroundColor = secondaryColor
self.view.backgroundColor = secondaryColor
eventsTable.backgroundColor = secondaryColor
}
}
override func viewWillAppear(_ animated: Bool) {
let screenSize: CGRect = UIScreen.main.bounds
let dayWidth = (screenSize.width - 100)/7.0
if dayWidth > 42 {
monthLabel.font = monthLabel.font.withSize(19)
} else if dayWidth < 35 {
monthLabel.font = monthLabel.font.withSize(14)
}
}
func initMonth(month: Int, year: Int) {
daysInMonth = getDaysInMonth(month: month, year: year)
let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
monthLabel.text = "\(months[month - 1]) \(year)"
monthString = "\(months[month - 1])"
self.month = month
self.year = year
yearString = "\(year)"
if month < 10 {
startWeekday = getDayOfWeek(today: "\(year)-0\(month)-01")
} else {
startWeekday = getDayOfWeek(today: "\(year)-\(month)-01")
}
}
func getDayOfWeek(today:String)->Int {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let todayDate = formatter.date(from: today)!
let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
let myComponents = myCalendar.components(.weekday, from: todayDate)
let weekDay = myComponents.weekday
return weekDay!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (8 + daysInMonth + startWeekday - 1)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.row < 7 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
let screenSize: CGRect = UIScreen.main.bounds
let dayWidth = (screenSize.width - 100)/7.0
if dayWidth > 42 {
cell.dayLabel.font = cell.dayLabel.font.withSize(19)
} else if dayWidth < 35 {
print("In here")
cell.dayLabel.font = cell.dayLabel.font.withSize(14)
}
let week = ["S", "M", "T", "W", "T", "F", "S"]
cell.dayLabel.text = week[indexPath.row]
return cell
} else if indexPath.row == 7 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
cell.dayLabel.text = ""
cell.backgroundColor = UIColor.black.withAlphaComponent(0.5)
return cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "daycell", for: indexPath) as! DayCollectionViewCell
let screenSize: CGRect = UIScreen.main.bounds
let dayWidth = (screenSize.width - 100)/7.0
if dayWidth > 42 {
cell.dayNum.font = cell.dayNum.font.withSize(22)
} else if dayWidth < 35 {
print("In here")
cell.dayNum.font = cell.dayNum.font.withSize(14)
}
let day = indexPath.row - 6 - startWeekday
if day < 1 {
cell.dayNum.text = ""
} else {
cell.dayNum.text = "\(day)"
}
switch currentStyle {
case Style.fun:
cell.backgroundColor = primaryColor
cell.dayNum.textColor = UIColor.white
cell.layer.masksToBounds = true
cell.layer.cornerRadius = 6
if cell.dayNum.text == "" {
cell.backgroundColor = primaryColor.withAlphaComponent(0.5)
} else {
// Look here! So for these cells we need to add a date array
let calendar = Calendar.current
let cellDate = calendar.date(from: DateComponents(calendar: calendar, year: year, month: month, day: day))
let dayEvents = eventsArr.filter{ $0.dateNoTime == cellDate }
cell.eventsArr = dayEvents
cell.layer.shadowColor = UIColor.black.cgColor
cell.layer.shadowOffset = CGSize(width: 0, height: 2.0)
cell.layer.shadowRadius = 2.0
cell.layer.shadowOpacity = 1.0
cell.layer.masksToBounds = false
cell.layer.shadowPath = UIBezierPath(roundedRect: cell.bounds, cornerRadius: cell.contentView.layer.cornerRadius).cgPath
cell.tag = day
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector (self.selectDay (_:)))
cell.addGestureRecognizer(tapRecognizer)
cellArr[day] = cell
if dayEvents.count != 0 {
print(dayEvents)
let circlePath = UIBezierPath(arcCenter: CGPoint(x: cell.frame.width/2,y: cell.frame.height*2/3), radius: CGFloat(3), startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
//change the fill color
shapeLayer.fillColor = UIColor.white.cgColor
//you can change the stroke color
shapeLayer.strokeColor = UIColor.white.cgColor
//you can change the line width
shapeLayer.lineWidth = 3.0
cell.layer.addSublayer(shapeLayer)
}
}
break
default: break
}
let today = Date()
let calendar = Calendar.current
let currentYear = calendar.component(.year, from: today)
let currentMonth = calendar.component(.month, from: today)
let currentDay = calendar.component(.day, from: today)
let label: [String] = (monthLabel.text?.components(separatedBy: " "))!
let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
if day == currentDay && months[currentMonth-1] == label[0] && "\(currentYear)" == label[1] {
self.today = currentDay
switch currentStyle {
case Style.fun:
cell.backgroundColor = UIColor(red: 198/256, green: 40/256, blue: 40/256, alpha: 1.0)
break
case Style.classic:
cell.dayNum.layer.masksToBounds = true
cell.dayNum.layer.cornerRadius = cell.dayNum.frame.height/2.0
cell.dayNum.backgroundColor = UIColor.red
break
//default: break
}
/*cell.dayNum.textColor = UIColor.white
cell.dayNum.layer.masksToBounds = true
cell.dayNum.layer.cornerRadius = cell.dayNum.frame.height/2.0
cell.dayNum.backgroundColor = UIColor.red
// Comment
cell.circle.layer.masksToBounds = true
print(cell.circle.frame.width)
cell.circle.layer.cornerRadius = 8//cell.circle.frame.height/2.0
cell.circle.backgroundColor = UIColor.lightGray*/
}
return cell
}
}
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAtIndexPath: IndexPath) -> CGSize {
let screenSize: CGRect = UIScreen.main.bounds
let dayWidth = (screenSize.width - 100)/7.0
//print("The day width is \(dayWidth)")
if sizeForItemAtIndexPath.row < 7 {
return CGSize(width: dayWidth, height: 30.0)
} else if sizeForItemAtIndexPath.row > 7 {
return CGSize(width: dayWidth, height: dayWidth + dayWidth/2.0)
} else {
return CGSize(width: screenSize.width, height: 1)
}
}
func getDaysInMonth(month: Int, year: Int) -> Int {
let dateComponents = DateComponents(year: year, month: month)
let calendar = Calendar.current
let date = calendar.date(from: dateComponents)!
let range = calendar.range(of: .day, in: .month, for: date)!
let numDays = range.count
return numDays
}
func selectDay(_ sender:UITapGestureRecognizer){
if selectedCellView != nil {
if selectedCellView?.tag == today {
selectedCellView?.backgroundColor = UIColor(red: 198/256, green: 40/256, blue: 40/256, alpha: 1.0)
} else {
selectedCellView?.backgroundColor = primaryColor.withAlphaComponent(1.0)
}
sender.view?.layer.shadowOpacity = 1.0
}
let day: Int = (sender.view?.tag)!
if today == day {
sender.view?.backgroundColor = UIColor(red: 198/256, green: 40/256, blue: 40/256, alpha: 0.75)
} else {
sender.view?.backgroundColor = primaryColor.withAlphaComponent(0.5)
}
sender.view?.layer.shadowOpacity = 0.5
selectedCellView = sender.view
let heightConstraint = NSLayoutConstraint(item: collectionView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: collectionView.contentSize.height + 4)
collectionView.addConstraint(heightConstraint)
self.view.layoutIfNeeded()
tableViewDelegate?.eventsArr = (cellArr[day]?.eventsArr)!
eventsTable.reloadData()
//eventsLabel.text = "\(monthString!) \(day), \(yearString!)"
//eventsLabel.isHidden = false
eventsTable.isHidden = false
}
/*
// 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.
}
*/
}
|
//
// FavAddressManagementViewController.swift
// YuQinClient
//
// Created by ksn_cn on 16/3/26.
// Copyright © 2016年 YuQin. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class FavAddressManagementViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var favAddressList: [JSON] = { [JSON]() }()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "常用地址"
self.automaticallyAdjustsScrollViewInsets = false
self.hidesBottomBarWhenPushed = true
//去除多余分割线
self.tableView.tableFooterView = UIView(frame: CGRectZero)
//添加右上角编辑按钮
self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.navigationItem.rightBarButtonItem?.title = "编辑"
getAllFavAddress()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
tableView.setEditing(editing, animated: animated)
self.navigationItem.setHidesBackButton(editing, animated: true)
if editing {
self.navigationItem.rightBarButtonItem?.title = "完成"
} else {
self.navigationItem.rightBarButtonItem?.title = "编辑"
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return favAddressList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CellForFavAddressManagement", forIndexPath: indexPath)
cell.textLabel?.text = favAddressList[indexPath.row].string
// cell.textLabel?.text = favAddressList[indexPath.row]["description"].string
// cell.detailTextLabel?.text = favAddressList[indexPath.row]["detail"].string
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.layoutMargins = UIEdgeInsetsZero
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
deleteFavAddressByIndex(indexPath)
}
func onClickRightBarBtn(sender: UIBarButtonItem) {
}
func getAllFavAddress() {
URLConnector.request(Router.getAllFavoriateAddress, successCallBack: { value in
if let list = value.array {
self.favAddressList = list
self.tableView.reloadData()
self.favAddressList.count == 0 ? UITools.sharedInstance.showNoDataTipToView(self.tableView, tipStr: "暂无常用地址") : UITools.sharedInstance.hideNoDataTipFromView(self.tableView)
}
})
}
func deleteFavAddressByIndex(indexPath: NSIndexPath) {
URLConnector.request(Router.deleteHistoryAddress(address: favAddressList[indexPath.row].string!), successCallBack: { value in
if let status = value["status"].bool {
if status {
self.favAddressList.removeAtIndex(indexPath.row)
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else {
UITools.sharedInstance.toast("删除失败,请重试")
}
}
})
}
}
|
//
// UIView+Addtions.swift
// SwiftTest
//
// Created by Mekor on 20/11/2016.
// Copyright © 2016 Mekor. All rights reserved.
//
import UIKit
extension UIView {
// size
var width: CGFloat { return self.frame.size.width }
var height: CGFloat { return self.frame.size.height }
var size: CGSize { return self.frame.size}
// origin
var origin: CGPoint { return self.frame.origin }
var x: CGFloat { return self.frame.origin.x }
var y: CGFloat { return self.frame.origin.y }
var centerX: CGFloat { return self.center.x }
var centerY: CGFloat { return self.center.y }
var left: CGFloat { return self.frame.origin.x }
var right: CGFloat { return self.frame.origin.x + self.frame.size.width }
var top: CGFloat { return self.frame.origin.y }
var bottom: CGFloat { return self.frame.origin.y + self.frame.size.height }
public func setWidth(width: CGFloat) {
self.frame.size.width = width
}
public func setHeight(height: CGFloat) {
self.frame.size.height = height
}
public func setSize(size: CGSize) {
self.frame.size = size
}
public func setOrigin(point: CGPoint) {
self.frame.origin = point
}
public func setX(x: CGFloat) {
self.frame.origin.x = x
}
public func setY(y: CGFloat) {
self.frame.origin.y = y
}
public func roundedCorrner(radius: CGFloat) {
self.layer.cornerRadius = radius
self.clipsToBounds = true
}
public func roundedRectangleFilter() {
self.roundedCorrner(radius: self.height / 2)
}
public func circleFilter() {
self.roundedCorrner(radius: self.width / 2)
}
public func border(width: CGFloat, color: UIColor) {
self.layer.borderWidth = width
self.layer.borderColor = color.cgColor
}
public func removeSublayers() {
if let sublayers = self.layer.sublayers {
for layer in sublayers {
layer.removeFromSuperlayer()
}
}
}
public func hasViewClass(targetClass: AnyClass) -> Bool {
for childView in self.subviews {
if childView.isMember(of: targetClass) {
return true
}
}
return false
}
}
|
//
// Ship.swift
// Asteroids
//
// Created by Gabriel Robinson on 4/22/19.
// Copyright © 2019 CS4530. All rights reserved.
//
import UIKit
class Ship: Codable {
var angle: CGFloat
var velocity: CGFloat
var position: CGPoint
init() {
angle = 0
velocity = 0
position = CGPoint(x: 0, y: 0)
}
}
|
////
//// JWTSM.swift
////
////
//// Created by Vũ Quý Đạt on 25/04/2021.
////
//
//import JWTKit
//import Vapor
//import MongoKitten
//
//struct AccessTokenSM: JWTPayload {
// let expiration: ExpirationClaim
// let subject: ObjectId
//
// init(subject: UserSM) {
// // Expires in 24 hours
//// self.expiration = ExpirationClaim(value: Date().addingTimeInterval(24 * 3600))
//// self.expiration = ExpirationClaim(value: Date().addingTimeInterval(10 * 60))
// self.expiration = ExpirationClaim(value: Date().addingTimeInterval(60 * 60 * 24 * 365))
// self.subject = subject._id
// }
//
// func verify(using signer: JWTSigner) throws {
// try expiration.verifyNotExpired()
// }
//}
//
//extension Application {
// var jwtSM: JWTSigner {
// // Generate a random key and use that on production/
// // If this key is known by attackers, they can impersonate all users
// return JWTSigner.hs512(
// key: Array("yoursupersecretsecuritykey".utf8)
// )
// }
//}
|
//
// NextTableCell.swift
// UITableViewInsideUITableViewCell
//
// Created by Shantaram K on 02/10/20.
// Copyright © 2020 Shantaram Kokate. All rights reserved.
//
import UIKit
class NextTableCell: UITableViewCell {
@IBOutlet var tableView: OwnTableView!
@IBOutlet var cellContainerView: UIView!
@IBOutlet var button: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.selectionStyle = .none
setupView()
configureView()
configureButton()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
extension NextTableCell {
func setupView() {
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.register(UINib(nibName: "InfoCell", bundle: Bundle.main), forCellReuseIdentifier: "InfoCell")
tableView.backgroundColor = UIColor.white
tableView.separatorStyle = .singleLine
}
func configureView() {
cellContainerView.layer.cornerRadius = 8
cellContainerView.layer.borderColor = UIColor.gray.cgColor
cellContainerView.layer.borderWidth = 2.0
}
func configureButton() {
button.layer.maskedCorners = [.layerMinXMaxYCorner , .layerMaxXMaxYCorner]
button.clipsToBounds = true
button.layer.cornerRadius = 8
}
}
extension NextTableCell: UITableViewDelegate {
}
extension NextTableCell: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "InfoCell", for: indexPath) as! InfoCell
cell.layoutIfNeeded()
return cell
}
}
|
//
// Field7Cell.swift
// government_park
//
// Created by YiGan on 30/09/2017.
// Copyright © 2017 YiGan. All rights reserved.
//
import Foundation
class Field7Cell: FieldCell {
}
|
//
// HomeRouter.swift
// Submission1GameApp
//
// Created by izzudin on 21/11/20.
// Copyright © 2020 izzudin. All rights reserved.
//
import Foundation
class HomeRouter {
}
|
//
// LispInterpreter.swift
// LispInterpreter
//
// Created by Zach Butler on 6/26/20.
// Copyright © 2020 Zach Butler. All rights reserved.
//
import Foundation
func READ(_ s: String) -> String {
return s
}
func EVAL(_ s: String) -> String {
return s
}
func PRINT(_ s: String) -> String {
return s
}
func rep(_ s: String) -> String {
}
|
//
// DeviceService.swift
// eve-home-alarm-manager
//
// Created by Kevin Wei on 2019-12-13.
// Copyright © 2019 Kevin Wei. All rights reserved.
//
import UIKit
import HomeKit
extension HMService {
// App supported service types
enum AlarmServiceType {
case contact, motion, unknown
}
// Convert system service type into enum
var deviceServiceType: AlarmServiceType {
switch serviceType {
case HMServiceTypeMotionSensor: return .motion
// case HMServiceTypeWindow, HMServiceTypeDoor: return .door
case HMServiceTypeContactSensor: return .contact
default: return .unknown
}
}
/// The primary characteristic type to be controlled, given the service type.
var primaryControlCharacteristicType: String? {
switch deviceServiceType {
case .contact: return HMCharacteristicTypeContactState
case .motion: return HMCharacteristicTypeMotionDetected
case .unknown: return nil
}
}
// Main display characteristic of the service
var primaryDisplayCharacteristic: HMCharacteristic? {
return characteristics.first { $0.characteristicType == primaryControlCharacteristicType }
}
//Returns string of the current state of service
private var state: String {
switch deviceServiceType {
case .contact:
if let value = primaryDisplayCharacteristic?.value as? Int,
let doorState = HMCharacteristicValueContactState(rawValue: value) {
switch doorState {
// case .open: return ("Open")
// case .closed: return ("Closed")
// case .opening: return ("Opening")
// case .closing: return ("Closing")
// case .stopped: return ("Stopped")
case .detected: return ("Closed")
case .none: return ("Open")
@unknown default: return ("Unknown")
}
} else {
return ("Unknown")
}
case .motion:
if let value = primaryDisplayCharacteristic?.value as? Int,
let motionState = HMCharacteristicValueOccupancyStatus(rawValue: value) {
switch motionState {
case .occupied: return ("Motion Detected")
case .notOccupied: return ("No Motion Detected")
@unknown default: return ("Unknown")
}
} else {
return ("Unknown")
}
case .unknown:
return ("Unknown")
}
}
}
|
//
// KRBaseView_CollectionView.swift
// KoalaReadingTeacher
//
// Created by 李鹏跃 on 2017/8/31.
// Copyright © 2017年 Koalareading. All rights reserved.
//
import UIKit
///里面有一个collectionView,一个Button,可以展开,
class PYElasticityCollectionView:UIView,
UICollectionViewDelegate,
UICollectionViewDataSource
{
let CELLID = "CELLID"
init(frame: CGRect, cellClass: AnyClass, layout: UICollectionViewFlowLayout) {
self.isSelected = false
super.init(frame: frame)
self.layout = layout
self.cellClass = cellClass
show()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - 属性设置
///底部的展开按钮
var button = UIButton()
///数据源
var modelArray: [Any] = [] {
didSet {
setDataFunc()
}
}
///未展开的时候最多展示多少条
var maxShowItem: NSInteger = 0
///每一行有多少
var maxRowItemNum: NSInteger = 1
///collectionView 的layout
var layout = UICollectionViewFlowLayout()
///是否隐藏底部按钮
var isHiddenButton: Bool = false {
didSet {
setUPHiddenButton()
}
}
///button 的上下左右的 间距
var buttonInsets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) {
didSet {
setUPButtinInsets()
}
}
///button 的高度
var buttonH: CGFloat {
get {
return buttonH_
}
set {
buttonH_ = newValue
}
}
///点击底部的按钮
var clickBottomButtonCallBack: ((_ currentH: CGFloat)->())?
///点击底部的按钮的方法
func clickBottomButtonFunc (_ clickBottomButtonCallBack: @escaping ((_ currentH: CGFloat)->())) {
self.clickBottomButtonCallBack = clickBottomButtonCallBack
}
///展示的数据条数
var trueShowItemNum: NSInteger {
get {
return getTrueShowItemNum()
}
}
/// 是否为点击状态
var isSelected: Bool {
didSet {
button.isSelected = isSelected
}
}
//MARK: - 私有属性
private var cellClass: Swift.AnyClass?
private var buttonH_: CGFloat = kViewCurrentH_XP(H: 70)
private var collectionView: UICollectionView!
///父视图的记录
private weak var scrollView: UIScrollView? {
get {
return self.getScrollView(self)
}
}
private weak var cell: UIView? {
get {
return self.getCell(self)
}
}
private weak var cell_: UIView?
private weak var scrollView_: UIScrollView?
private func show() {
setUP()
}
private func setUP() {
self.setUPValue()
self.setUPFrame()
collectionView.reloadData()
collectionView.backgroundColor = self.backgroundColor
}
private func setUPValue() {
collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.isScrollEnabled = false
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(cellClass, forCellWithReuseIdentifier:CELLID)
button.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
}
private func setUPFrame() {
self.addSubview(collectionView)
self.addSubview(button)
let currentViewHRound = (currentCollectionViewH)
collectionView.snp.makeConstraints { (make) in
make.top.equalTo(self)
make.left.right.equalTo(self)
make.height.equalTo(currentViewHRound)
make.bottom.equalTo(self).offset(-buttonInsets.bottom - buttonInsets.top - buttonH)
}
button.snp.makeConstraints { (make) in
make.left.equalTo(self).offset(buttonInsets.left)
make.right.equalTo(self).offset(-buttonInsets.right)
make.height.equalTo(buttonH)
make.bottom.equalTo(self).offset(buttonInsets.bottom)
}
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
}
func getScrollView(_ view: UIView) -> (UIScrollView) {
if self.scrollView_ != nil {
return self.scrollView_!
}
if view is UITableView {
self.scrollView_ = view as! UIScrollView
return view as! UIScrollView
}
if view.superview == nil {
print("🌶 \\getScrollView(_ view: UIView) -> (UIScrollView)\\ superView为nil")
return UIScrollView()
}
let scrollView = self.getScrollView(view.superview!)
return scrollView
}
func getCell(_ view: UIView) -> (UIView) {
if self.cell_ != nil {
return self.cell_!
}
if view is UITableViewCell {
cell_ = view
return view
}
if view.superview == nil {
print("🌶 \\getCell(_ view: UIView) -> (UIView)\\ superView为nil")
return UIView()
}
let cell = self.getCell(view.superview!)
return cell
}
///当前这个view的高度
var currentViewH: CGFloat {
get {
return getCurrentViewH()
}
}
///当前的 collectionView的高度
var currentCollectionViewH: CGFloat {
get {
return getCurrentCollectionViewH()
}
}
//点击事件的相应
@objc private func clickButton(_ button: UIButton) {
collectionView.snp.updateConstraints{ (make) in
make.height.equalTo(currentCollectionViewH)
}
// self.indexPath =
clickBottomButtonCallBack?((currentViewH))
// collectionView.reloadData()
}
// private var indexPath: IndexPath?
// var isFirstCallBack = true
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let buttonPoint = self.convert(point, to: button)
if button.point(inside: buttonPoint, with: event) {
return button
}
return super.hitTest(point, with: event)
}
//MARK: - 一些属性的方法缩略
private func setDataFunc() {
self.isHiddenButton = modelArray.count <= self.maxShowItem
if let collectionView_ = collectionView {
collectionView_.snp.updateConstraints{ (make) in
make.height.equalTo(currentCollectionViewH)
}
collectionView.reloadData()
}
}
private func setUPHiddenButton() {
if isHiddenButton {
button.snp.updateConstraints { (make) in
make.left.equalTo(self).offset(buttonInsets.left)
make.right.equalTo(self).offset(-buttonInsets.right)
make.height.equalTo(0)
}
collectionView.snp.updateConstraints { (make) in
make.bottom.equalTo(self).offset(0)
}
}else{
button.snp.updateConstraints { (make) in
make.left.equalTo(self).offset(buttonInsets.left)
make.right.equalTo(self).offset(-buttonInsets.right)
make.height.equalTo(buttonH)
}
collectionView.snp.updateConstraints { (make) in
make.bottom.equalTo(self).offset(-buttonInsets.bottom - buttonInsets.top - buttonH)
}
}
}
private func setUPButtinInsets() {
button.snp.updateConstraints { (make) in
make.left.equalTo(self).offset(buttonInsets.left)
make.right.equalTo(self).offset(-buttonInsets.right)
make.bottom.equalTo(self).offset(buttonInsets.bottom)
}
collectionView.snp.updateConstraints { (make) in
make.bottom.equalTo(self).offset(-buttonInsets.bottom - buttonInsets.top - buttonH)
}
}
private func getTrueShowItemNum()->(NSInteger) {
if isHiddenButton {
return modelArray.count
}
if isSelected {
return modelArray.count
}
if maxShowItem < 0 {
return modelArray.count
}
if modelArray.count > maxShowItem {
return maxShowItem / maxRowItemNum * maxRowItemNum
}
return modelArray.count
}
private func getCurrentCollectionViewH() -> (CGFloat){
let itmeH = layout.itemSize.height
var margin: CGFloat = 0.0
var secionHeiderH: CGFloat = 0.0
var secionFootH: CGFloat = 0.0
var rightLeftW: CGFloat = 0.0
///
//minimumLineSpacing
if layout.scrollDirection == .horizontal {
margin = layout.minimumInteritemSpacing
rightLeftW = layout.minimumLineSpacing
secionHeiderH = layout.sectionInset.top
secionFootH = layout.sectionInset.bottom
}else {
margin = layout.minimumLineSpacing
rightLeftW = layout.minimumInteritemSpacing
secionHeiderH = layout.sectionInset.left
secionFootH = layout.sectionInset.right
}
//一共多少排
//计算一排有多少个
if trueShowItemNum == 0 {
return 0
}
var row = CGFloat(trueShowItemNum) / CGFloat(maxRowItemNum)
let rowIsSeleted = isSelected ? ceil(row) : floor(row)
row = isHiddenButton ? ceil(row) : rowIsSeleted
return (CGFloat(row - 1) * margin) + (CGFloat(row) * itmeH) + secionFootH + secionHeiderH
}
private func getCurrentViewH() -> (CGFloat) {
let notHiddenButtonViewH = (currentCollectionViewH + buttonH + buttonInsets.top + buttonInsets.bottom)
let hiddenButtonViewH = (currentCollectionViewH)
return isHiddenButton ? hiddenButtonViewH : notHiddenButtonViewH
}
}
//MARK: - DATADOURCE
extension PYElasticityCollectionView {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return trueShowItemNum
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CELLID, for: indexPath)
cell.model_BaseData_ = self.modelArray[indexPath.row]
self.stitchChannelFunc(sender: cell)
return cell
}
}
|
//
// BookStoreViewController.swift
// BookSeeker
//
// Created by Edwy Lugo on 28/06/20.
// Copyright © 2020 CIT. All rights reserved.
//
import UIKit
import Lottie
class BookStoreViewController: UIViewController {
private var viewModel: BookStoreViewModelProtocol
init(viewModel: BookStoreViewModelProtocol) {
self.viewModel = viewModel
super.init(nibName: "BookStoreViewController", bundle: nil)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@IBOutlet var containerView: AnimationView!
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.prefersLargeTitles = true
self.title = "Book Store"
// Create Animation object
let jsonName = "18123-developer"
let animation = Animation.named(jsonName)
// Load animation to AnimationView
let animationView = AnimationView(animation: animation)
// animationView.frame = CGRect(x: 0, y: 0, width: 327, height: 179)
// animationView.frame = self.containerView.frame
animationView.loopMode = .loop
animationView.contentMode = .scaleAspectFit
// Add animationView as subview
self.containerView.addSubview(animationView)
animationView.translatesAutoresizingMaskIntoConstraints = false
// Apply these constrains if you want animation size should be same as super view.
self.containerView.addConstraint(NSLayoutConstraint(item: animationView, attribute: .leading, relatedBy: .equal, toItem: self.containerView, attribute: .leading, multiplier: 1.0, constant: 1))
self.containerView.addConstraint(NSLayoutConstraint(item: animationView, attribute: .trailing, relatedBy: .equal, toItem: self.containerView, attribute: .trailing, multiplier: 1.0, constant: 1))
self.containerView.addConstraint(NSLayoutConstraint(item: animationView, attribute: .top, relatedBy: .equal, toItem: self.containerView, attribute: .top, multiplier: 1.0, constant: 1))
self.containerView.addConstraint(NSLayoutConstraint(item: animationView, attribute: .bottom, relatedBy: .equal, toItem: self.containerView, attribute: .bottom, multiplier: 1.0, constant: 1))
// Play the animation
animationView.play()
}
}
|
//
// StaffListViewController.swift
// PyConJP2016
//
// Created by Yutaro Muta on 9/10/16.
// Copyright © 2016 PyCon JP. All rights reserved.
//
import UIKit
import SafariServices
class StaffListViewController: UIViewController, TwitterURLSchemeProtocol, ErrorAlertProtocol {
@IBOutlet weak var tableView: UITableView! {
didSet {
let nib = UINib(nibName: staffListDataSource.reuseIdentifier, bundle:nil)
tableView.register(nib, forCellReuseIdentifier: staffListDataSource.reuseIdentifier)
refreshControl.addTarget(self, action: #selector(StaffListViewController.onRefresh(_:)), for: .valueChanged)
tableView.addSubview(refreshControl)
tableView.dataSource = staffListDataSource
tableView.rowHeight = StaffTableViewCell.estimatedRowHeight
}
}
private lazy var staffListDataSource: StaffListDataSource = StaffListDataSource(facebookAction: { (url) -> (() -> Void) in { self.facebookAction(urlString: url) } }, twitterAction: { (url) -> (() -> Void) in { self.twitterAction(urlString: url) } })
private let refreshControl = UIRefreshControl()
static func build() -> StaffListViewController {
return UIStoryboard(name: "More", bundle: Bundle.main).instantiateViewController(withIdentifier: "StaffListViewController") as! StaffListViewController
}
override func viewDidLoad() {
super.viewDidLoad()
refreshControl.beginRefreshing()
refresh()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let indexPath = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: indexPath, animated: true)
}
}
func onRefresh(_ sender: UIRefreshControl) {
refresh()
}
func refresh() {
staffListDataSource.refreshData { result in
switch result {
case .success:
DispatchQueue.main.async {
self.tableView.reloadData()
self.refreshControl.endRefreshing()
}
case .failure(let error):
DispatchQueue.main.async(execute: {
self.showErrorAlart(with: error, parent: self)
self.refreshControl.endRefreshing()
})
}
}
}
// MARK: - StaffTableViewCell Button Action
private func facebookAction(urlString: String) {
guard let url = URL(string: urlString) else { return }
let safariViewController = SFSafariViewController(url: url)
self.present(safariViewController, animated: true, completion: nil)
}
private func twitterAction(urlString: String) {
let userName = urlString.replacingOccurrences(of: "https://twitter.com/", with: "")
openTwitter(userName: userName, from: self)
}
}
|
//
// TopRatedCellViewModel.swift
// MovieDB
//
// Created by emirhan battalbaş on 23.04.2019.
// Copyright © 2019 emirhan battalbaş. All rights reserved.
//
import Foundation
import SDWebImage
class TopRatedCellViewModel: NSObject {
public var topRatedMovieModel: MovieTopRatedWelcome
init(topRatedMovieModel: MovieTopRatedWelcome) {
self.topRatedMovieModel = topRatedMovieModel
}
}
extension TopRatedCellViewModel {
func configureCell(cell: MDBTopRatedMovieCollectionViewCell, row: Int) {
cell.topRatedImageView.sd_setImage(with: URL(string: AppConstant.imageBaseUrl + (topRatedMovieModel.results?[row].backdropPath ?? "")), completed: nil)
}
}
|
//
// FriendsCell.swift
// VKlient
//
// Created by Никита Дмитриев on 18.10.2020.
// Copyright © 2020 Никита Дмитриев. All rights reserved.
//
import UIKit
class FriendsCollectionCell: UICollectionViewCell {
@IBOutlet weak var iconImageLabel: UIImageView!
@IBOutlet weak var likeControl: LikeControl!
override func awakeFromNib() {
super.awakeFromNib()
}
}
|
@testable import JSON
import XCTest
class JSONTests: XCTestCase {
func testStringInterpolation() {
let string: String = "string"
let json: JSON = [
"key": "\(string)"
]
XCTAssertNotNil(json["key"]?.stringValue)
XCTAssert(json["key"]!.stringValue! == "string")
let serialized = JSONSerializer().serializeToString(json: json)
XCTAssert(serialized == "{\"key\":\"string\"}")
}
func testJSONBasicUsage() {
let value = "value"
var json: JSON = [
"key": .string(value)
]
json["int"] = 3
XCTAssertEqual(json["key"]?.stringValue, "value")
XCTAssertNotEqual(json["int"]?.doubleValue, Double(3))
}
}
extension JSONTests {
static var allTests: [(String, (JSONTests) -> () throws -> Void)] {
return [
("testStringInterpolation", testStringInterpolation),
]
}
}
|
/*
* Copyright (c) 2019, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
*/
import XCTest
@testable import OktaAuthNative
class OktaAPITests : XCTestCase {
let url = URL(string: "https://B6D242A0-4FC6-41A4-A68B-F722B84BB346.com")!
var api: OktaAPI!
override func setUp() {
api = OktaAPI(oktaDomain: url)
}
override func tearDown() {
api = nil
}
func testPrimaryAuthentication() {
let username = "username"
let password = "password"
let exp = XCTestExpectation()
api.commonCompletion = { req, _ in
XCTAssertEqual(req.baseURL, self.url)
XCTAssertEqual(req.path, "/api/v1/authn")
XCTAssertEqual(req.bodyParams?["username"] as? String, username)
XCTAssertEqual(req.bodyParams?["password"] as? String, password)
exp.fulfill()
}
api.primaryAuthentication(username: username, password: password)
wait(for: [exp], timeout: 60.0)
}
func testPrimaryAuthenticationWithDeviceFingerprint() {
let username = "username"
let password = "password"
let deviceFingerprint = "fingerprint"
let exp = XCTestExpectation()
api.commonCompletion = { req, _ in
XCTAssertEqual(req.baseURL, self.url)
XCTAssertEqual(req.path, "/api/v1/authn")
XCTAssertEqual(req.bodyParams?["username"] as? String, username)
XCTAssertEqual(req.bodyParams?["password"] as? String, password)
XCTAssertEqual(req.additionalHeaders?["X-Device-Fingerprint"] , deviceFingerprint)
exp.fulfill()
}
api.primaryAuthentication(username: username, password: password, deviceFingerprint: deviceFingerprint)
wait(for: [exp], timeout: 60.0)
}
func testChangePassword() {
let token = "token"
let oldpass = "oldpass"
let newpass = "newpass"
let exp = XCTestExpectation()
api.commonCompletion = { req, _ in
XCTAssertEqual(req.baseURL, self.url)
XCTAssertEqual(req.path, "/api/v1/authn/credentials/change_password")
XCTAssertEqual(req.bodyParams?["stateToken"] as? String, token)
XCTAssertEqual(req.bodyParams?["oldPassword"] as? String, oldpass)
XCTAssertEqual(req.bodyParams?["newPassword"] as? String, newpass)
exp.fulfill()
}
api.changePassword(stateToken: token, oldPassword: oldpass, newPassword: newpass)
wait(for: [exp], timeout: 60.0)
}
func testChangePasswordWithLink() {
let link = LinksResponse.Link(name: "test", href: URL(string: "http://test")!, hints: [:])
let token = "token"
let oldpass = "oldpass"
let newpass = "newpass"
let exp = XCTestExpectation()
api.commonCompletion = { req, _ in
XCTAssertEqual(req.baseURL, link.href)
XCTAssertNil(req.path)
XCTAssertEqual(req.bodyParams?["stateToken"] as? String, token)
XCTAssertEqual(req.bodyParams?["oldPassword"] as? String, oldpass)
XCTAssertEqual(req.bodyParams?["newPassword"] as? String, newpass)
exp.fulfill()
}
api.changePassword(link: link, stateToken: token, oldPassword: oldpass, newPassword: newpass)
wait(for: [exp], timeout: 60.0)
}
func testGetTransactionState() {
let token = "token"
let exp = XCTestExpectation()
api.commonCompletion = { req, _ in
XCTAssertEqual(req.baseURL, self.url)
XCTAssertEqual(req.path, "/api/v1/authn")
XCTAssertEqual(req.bodyParams?["stateToken"] as? String, token)
exp.fulfill()
}
api.getTransactionState(stateToken: token)
wait(for: [exp], timeout: 60.0)
}
func testUnlockAccount() {
let username = "username"
let factorType = FactorType.email
let exp = XCTestExpectation()
api.commonCompletion = { req, _ in
XCTAssertEqual(req.baseURL, self.url)
XCTAssertEqual(req.path, "/api/v1/authn/recovery/unlock")
XCTAssertEqual(req.bodyParams?["username"] as? String, username)
XCTAssertEqual(req.bodyParams?["factorType"] as? String, factorType.rawValue)
exp.fulfill()
}
api.unlockAccount(username: username, factor: factorType)
wait(for: [exp], timeout: 60.0)
}
func testRecoverPassword() {
let username = "username"
let factorType = FactorType.email
let exp = XCTestExpectation()
api.commonCompletion = { req, _ in
XCTAssertEqual(req.baseURL, self.url)
XCTAssertEqual(req.path, "/api/v1/authn/recovery/password")
XCTAssertEqual(req.bodyParams?["username"] as? String, username)
XCTAssertEqual(req.bodyParams?["factorType"] as? String, factorType.rawValue)
exp.fulfill()
}
api.recoverPassword(username: username, factor: factorType)
wait(for: [exp], timeout: 60.0)
}
func testRecoverWith() {
let answer = "answer"
let stateToken = "stateToken"
let recoveryToken = "recoveryToken"
let link = LinksResponse.Link(name: "test", href: URL(string: "http://test")!, hints: [:])
let exp = XCTestExpectation()
api.commonCompletion = { req, _ in
XCTAssertEqual(req.baseURL, link.href)
XCTAssertNil(req.path)
XCTAssertEqual(req.bodyParams?["answer"] as? String, answer)
XCTAssertEqual(req.bodyParams?["stateToken"] as? String, stateToken)
XCTAssertEqual(req.bodyParams?["recoveryToken"] as? String, recoveryToken)
exp.fulfill()
}
api.recoverWith(answer: answer, stateToken: stateToken, recoveryToken: recoveryToken, link: link)
wait(for: [exp], timeout: 60.0)
}
func testResetPassword() {
let newPassword = "newPassword"
let stateToken = "stateToken"
let link = LinksResponse.Link(name: "test", href: URL(string: "http://test")!, hints: [:])
let exp = XCTestExpectation()
api.commonCompletion = { req, _ in
XCTAssertEqual(req.baseURL, link.href)
XCTAssertNil(req.path)
XCTAssertEqual(req.bodyParams?["newPassword"] as? String, newPassword)
XCTAssertEqual(req.bodyParams?["stateToken"] as? String, stateToken)
exp.fulfill()
}
api.resetPassword(newPassword: newPassword, stateToken: stateToken, link: link)
wait(for: [exp], timeout: 60.0)
}
func testCancelTransaction() {
let token = "token"
let exp = XCTestExpectation()
api.commonCompletion = { req, _ in
XCTAssertEqual(req.baseURL, self.url)
XCTAssertEqual(req.path, "/api/v1/authn/cancel")
XCTAssertEqual(req.bodyParams?["stateToken"] as? String, token)
exp.fulfill()
}
api.cancelTransaction(stateToken: token)
wait(for: [exp], timeout: 60.0)
}
func testCancelTransactionWithLink() {
let stateToken = "stateToken"
let link = LinksResponse.Link(name: "test", href: URL(string: "http://test")!, hints: [:])
let exp = XCTestExpectation()
api.commonCompletion = { req, _ in
XCTAssertEqual(req.baseURL, link.href)
XCTAssertNil(req.path)
XCTAssertEqual(req.bodyParams?["stateToken"] as? String, stateToken)
exp.fulfill()
}
api.cancelTransaction(with: link, stateToken: stateToken)
wait(for: [exp], timeout: 60.0)
}
func testPerformLink() {
let link = LinksResponse.Link(name: nil, href: url, hints: [:])
let token = "token"
let exp = XCTestExpectation()
api.commonCompletion = { req, _ in
XCTAssertEqual(req.baseURL, self.url)
XCTAssertEqual(req.bodyParams?["stateToken"] as? String, token)
exp.fulfill()
}
api.perform(link: link, stateToken: token)
wait(for: [exp], timeout: 60.0)
}
func testVerifyFactor() {
let factorId = "id"
let token = "token"
let answer = "answer"
let passCode = "passCode"
let rememberDevice = true
let autoPush = false
let exp = XCTestExpectation()
api.commonCompletion = { req, _ in
XCTAssertEqual(req.urlParams?["rememberDevice"], "true")
XCTAssertEqual(req.urlParams?["autoPush"], "false")
XCTAssertEqual(req.bodyParams?["stateToken"] as? String, token)
XCTAssertEqual(req.bodyParams?["answer"] as? String, answer)
XCTAssertEqual(req.bodyParams?["passCode"] as? String, passCode)
exp.fulfill()
}
api.verifyFactor(factorId: factorId,
stateToken: token,
answer: answer,
passCode: passCode,
rememberDevice: rememberDevice,
autoPush: autoPush)
wait(for: [exp], timeout: 60.0)
}
func testVerifyFactorWithLink() {
let stateToken = "stateToken"
let link = LinksResponse.Link(name: "test", href: URL(string: "http://test")!, hints: [:])
let exp = XCTestExpectation()
api.commonCompletion = { req, _ in
XCTAssertEqual(req.baseURL, link.href)
XCTAssertNil(req.path)
XCTAssertEqual(req.bodyParams?["stateToken"] as? String, stateToken)
exp.fulfill()
}
api.verifyFactor(with: link, stateToken: stateToken)
wait(for: [exp], timeout: 60.0)
}
func testEnrollFactor() {
let factor = EmbeddedResponse.Factor(
id: "id",
factorType: .sms,
provider: .okta,
vendorName: "Okta",
profile: nil,
embedded: nil,
links: nil,
enrollment: nil,
status: nil
)
let link = LinksResponse.Link(name: "test", href: URL(string: "http://test")!, hints: [:])
let stateToken = "stateToken"
let phoneNumber = "phoneNumber"
let questionId = "questionId"
let answer = "answer"
let credentialId = "credentialId"
let passCode = "passCode"
let exp = XCTestExpectation()
api.commonCompletion = { req, _ in
XCTAssertEqual(req.baseURL, link.href)
XCTAssertNil(req.path)
XCTAssertEqual(req.bodyParams?["stateToken"] as? String, stateToken)
XCTAssertEqual(req.bodyParams?["factorType"] as? String, factor.factorType.rawValue)
XCTAssertEqual(req.bodyParams?["provider"] as? String, factor.provider?.rawValue)
XCTAssertEqual(req.bodyParams?["passCode"] as? String, passCode)
let profile = req.bodyParams?["profile"] as? [AnyHashable:Any]
XCTAssertEqual(profile?["question"] as? String, questionId)
XCTAssertEqual(profile?["answer"] as? String, answer)
XCTAssertEqual(profile?["phoneNumber"] as? String, phoneNumber)
XCTAssertEqual(profile?["credentialId"] as? String, credentialId)
exp.fulfill()
}
api.enrollFactor(factor, with: link, stateToken: stateToken, phoneNumber: phoneNumber, questionId: questionId, answer: answer, credentialId: credentialId, passCode: passCode)
wait(for: [exp], timeout: 60.0)
}
func testSendActivationLink() {
let link = LinksResponse.Link(name: "test", href: URL(string: "http://test")!, hints: [:])
let stateToken = "stateToken"
let exp = XCTestExpectation()
api.commonCompletion = { req, _ in
XCTAssertEqual(req.baseURL, link.href)
XCTAssertNil(req.path)
XCTAssertEqual(req.bodyParams?["stateToken"] as? String, stateToken)
exp.fulfill()
}
api.sendActivationLink(link: link, stateToken: stateToken)
wait(for: [exp], timeout: 60.0)
}
}
|
//
// AppDelegate.swift
// 2019_ios_final
//
// Created by 王心妤 on 2019/5/30.
// Copyright © 2019 river. All rights reserved.
//
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge, .carPlay], completionHandler: { (granted, error) in
if granted {
print("允許接收信息通知")
} else {
print("不允許接收信息通知")
}
})
UNUserNotificationCenter.current().delegate = self
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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
application.setMinimumBackgroundFetchInterval(5)
// 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 active 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 AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.badge, .sound, .alert])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let content = response.notification.request.content
let identifier = response.notification.request.identifier
if identifier == "message" {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destinationViewController1 = storyboard.instantiateViewController(withIdentifier: "ChatMenu") as! ChatMenuViewController
let destinationViewController2 = storyboard.instantiateViewController(withIdentifier: "ChatView") as! ChatViewController
if let friend = Friend.getProfile(id: content.userInfo["sender"] as! String) {
destinationViewController2.receiver = friend
}
destinationViewController2.hidesBottomBarWhenPushed = true
let tabBarController = storyboard.instantiateViewController(withIdentifier: "TabBarController") as! UITabBarController
tabBarController.selectedIndex = 1
self.window?.rootViewController = tabBarController
let navigationController = tabBarController.selectedViewController as! UINavigationController
navigationController.pushViewController(destinationViewController1, animated: false)
navigationController.pushViewController(destinationViewController2, animated: false)
} else {
NetworkController.shared.getProfile(id: content.userInfo["sender"] as! String, completion: { status, data in
if let data = data, let profile = try? JSONDecoder().decode(Friend.self, from: data) {
DispatchQueue.main.async {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destinationViewController = storyboard.instantiateViewController(withIdentifier: "ProfileView") as! AddFriendViewController
destinationViewController.target = profile
let tabBarController = storyboard.instantiateViewController(withIdentifier: "TabBarController") as! UITabBarController
tabBarController.selectedIndex = 0
let navigationController = tabBarController.selectedViewController as! UINavigationController
navigationController.pushViewController(destinationViewController, animated: false)
self.window?.rootViewController = tabBarController
}
}
})
}
completionHandler()
}
}
|
//
// UBAAgent.swift
// UBAAgent
//
// Created by hwh on 16/1/22.
// Copyright © 2016年 Huangwh. All rights reserved.
//
import Foundation
import CryptoSwift
private let shareAgentInstance = UBAAgent()
private let ReStartUBATimerInterval = 10 * 3600 //如果程序进入后台 10分钟,就相当于程序杀掉重新加进入
public class UBAAgent : NSObject {
/// set send log to service timer interval ,default is 30s
private var _logSendInterval: NSTimeInterval = 30
private var _appId: String = ""
private var _reportPolicy: UBAReportPolicy = .BATCH
private var _startStamp: NSTimeInterval = 0 //程序启动时间
private var _enterToBackGoundStamp: NSTimeInterval = 0 // 程序进入后台的时间
//标识符
private var _identify : String = ""
private var _maxUploadLimitCount = 1 //1 ,方便测试
private var _exception: UBAException?
private var _signal : UBASignal?
private var _appBackTask:UIBackgroundTaskIdentifier? = 0
public enum UBAReportPolicy: Int {
case RealTime //实时上传
case BATCH //程序启动时 批量处理
}
/// 访问单例 private
class var ShareInstance: UBAAgent {
// performSelector("hehe", withObject: nil, afterDelay: 5)
// performSelector("haha",withObject: nil, afterDelay: 3)
return shareAgentInstance
}
override init() {
}
//MARK: - Public Class Methed
/**
统计初始化
- parameter appId: 统计应用,分配的appId
- parameter reportPolicy: 日志上传 方式 [批量|实时] ,default .BATCH
*/
public class func StartWithAppId(appId: String, reportPolicy: UBAReportPolicy ) {
ShareInstance.initWithAppId(appId, reportPolicy: reportPolicy)
}
public class func PostEvent(eventID: String, label: String? = nil) {
let event = Event(id: eventID,label: label)
UBADB.InsertEvent(event)
}
public class func Identify() -> String {
return ShareInstance._identify
}
public class func EnableCrashReport() {
ShareInstance._exception = UBAException()
ShareInstance._exception?.EnableException()
ShareInstance._signal = UBASignal()
ShareInstance._signal?.EnableSignal()
}
/**
单次上传最多条数据 限制 ,默认 100
- parameter limit: 上传上限
*/
public class func maxUploadlimit(limit: NSInteger) {
assert(limit>=1, "限制必须大于0")
ShareInstance._maxUploadLimitCount = limit
}
/**
设置 用户统计是否打印Log
- parameter enable: 是否打开日志系统 (default is True)
*/
public class func setLogEnable(enable: Bool) {
NSLog("[UBA]打开控制台输出")
userdefault.setBool(enable, forKey: Constant.UserDefaultKey.enableLogKey)
userdefault.synchronize()
UBAUpload.ShareInstance.uploadAllEvents()
}
/**
set send log to service timer interval ,default is 30s
- parameter timerInterval: send log timer interval
*/
public class func setLogSendInterval(timerInterval: NSTimeInterval) {
UBAAgent.ShareInstance._logSendInterval = timerInterval
}
//MARK: - Instance Methed
func initWithAppId(appId: String, reportPolicy: UBAReportPolicy) {
PrintLog("统计程序启动")
_appId = appId
_reportPolicy = reportPolicy
_startStamp = NSDate.currentDateStamp()
_identify = Helper.IdentifyForStamp(_startStamp)
//注册通知
registestNotification()
self.performSelectorInBackground("postEventsToService", withObject: nil)
}
func registestNotification() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "becomeActive:", name: UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "resignActive:", name: UIApplicationWillResignActiveNotification, object: nil)
}
func becomeActive(notification: NSNotification) {
PrintLog("程序进入前台")
let app = UIApplication.sharedApplication()
app.endBackgroundTask(_appBackTask!)
}
func resignActive(notifcation: NSNotification) {
PrintLog("程序进入后台")
_enterToBackGoundStamp = NSDate.currentDateStamp()
//Debug 时不放到后台执行
UBADB.BackUpTempDB()
return;
let app = UIApplication.sharedApplication()
_appBackTask = app.beginBackgroundTaskWithExpirationHandler({ () -> Void in
UBADB.BackUpTempDB()
})
}
/**
给服务器发送 事件
*/
func postEventsToService() {
if _reportPolicy == .BATCH {
postAllEvents()
}else {
postEventsAtPeriod()
}
}
/**
发送所有事件
*/
func postAllEvents() {
PrintLog("发送所有事件")
dispatch_async { () -> Void in
}
}
/**
定时发送事件
*/
func postEventsAtPeriod() {
PrintLog("定时发送事件")
}
}
|
//
// cellOfGalleryCollectionView.swift
// Bloom
//
// Created by Жарас on 27.06.17.
// Copyright © 2017 asamasa. All rights reserved.
//
import UIKit
class cellOfGalleryCollectionView: UICollectionViewCell {
@IBOutlet weak var imageItem: UIImageView!
}
|
//
// Card.swift
// Pods
//
// Created by Joel Fischer on 4/8/16.
//
//
import Foundation
import SwiftyJSON
import Alamofire
public enum CardType: String {
case All = "all"
case Closed = "closed"
case None = "none"
case Open = "open"
case Visible = "visible"
}
class Card{
var id: String!
var name: String!
var description: String?
var closed: Bool?
var position: Float?
var dueDate: Date?
var dueComplete:Bool?
var listId: String?
var memberIds = [String]()
var boardId: String?
var shortURL: String?
var labels = [Label]()
var checkLists = [CheckList]()
var checklistIDs = [String]()
var comments = [Comment]()
var actions = [Action]()
var attachments = [Attachment]()
private var isoDateFormatter: DateFormatter!
init(_ json: JSON){
isoDateFormatter = isoDate()
self.id = json["id"].stringValue
self.name = json["name"].stringValue
if json["desc"].null == nil{
self.description = json["desc"].stringValue
}
if json["pos"].null == nil{
self.position = json["pos"].floatValue
}
if json["closed"].null == nil{
self.closed = json["closed"].boolValue
}
if json["idList"].null == nil{
self.listId = json["idList"].stringValue
}
if json["due"].null == nil{
self.dueDate = isoDateFormatter.date(from: json["due"].stringValue)
}
if json["dueComplete"].null == nil{
self.dueComplete = json["dueComplete"].boolValue
}
if json["idMembers"].null == nil{
for member in json["idmembers"].arrayValue{
memberIds.append(member.stringValue)
}
}
if json["idBoard"].null == nil{
self.boardId = json["idBoard"].stringValue
}
if json["shortUrl"].null == nil{
self.shortURL = json["shortUrl"].stringValue
}
if json["labels"].null == nil{
for label in json["labels"].arrayValue{
self.labels.append(Label(label))
}
}
trello.getActionsForCard(self.id, .Minimal, completion: {(result)->Void in
if result.value != nil{
self.actions = result.value!
}
trello.getCommentsForCardID(self.id, completion: {(result)->Void in
self.comments = result.value!
NotificationCenter.default.post(name: refreshBoardsNotification, object:nil)
trello.getLabelsForCardID(self.id, completion: {(result)->Void in
if result.value != nil{
self.labels += result.value!
NotificationCenter.default.post(name: refreshBoardsNotification, object:nil)
}
})
})
})
trello.getAttachmentsForCardID(id, completion: {(result)->Void in
if result.value != nil{
self.attachments += result.value!
NotificationCenter.default.post(name: refreshBoardsNotification, object:nil)
}
})
trello.getChecklistForCardID(id, completion: {(result)->Void in
if result.value != nil{
self.checkLists += result.value!
for checklist in self.checkLists{
self.checklistIDs.append(checklist.id)
}
NotificationCenter.default.post(name: refreshBoardsNotification, object:nil)
}
})
}
init(){
self.name = ""
self.id = ""
}
}
// MARK: Card API
extension Trello {
func getCardsForList(_ id: String, withMembers: Bool = false, completion: @escaping (Result<[Card]>) -> Void) {
Alamofire.request(Router.cardsForList(listId: id).URLString, parameters: authParameters).responseJSON { (response) in
guard let json = response.result.value else {
completion(.failure(TrelloError.networkError(error: response.result.error)))
return
}
var cards = [Card]()
let data = JSON(json)
for card in data.arrayValue{
cards.append(Card(card))
}
completion(.success(cards))
}
}
func getCardByID(_ ID: String, completion: @escaping (Result<Card>) -> Void) {
Alamofire.request(Router.Card(cardID: ID).URLString, parameters: authParameters).responseJSON { (response) in
guard let json = response.result.value else {
completion(.failure(TrelloError.networkError(error: response.result.error)))
return
}
let card = Card(JSON(json))
completion(.success(card))
}
}
//mark: Card actions
func updateCard(card: Card, completion: @escaping () -> Void) {
let parameters = self.authParameters + ["name": card.name as AnyObject] + ["desc": card.description as AnyObject] + ["closed": card.closed as AnyObject] + ["idMembers": card.memberIds as AnyObject] + ["idList": card.listId as AnyObject] + ["pos": card.position as AnyObject] + ["dueComplete": card.dueComplete as AnyObject]
do{
try Alamofire.request(Router.Card(cardID: card.id).asURL(), method: .put
, parameters: parameters, encoding: JSONEncoding.default, headers: nil).response(completionHandler: {(response)->Void in
})
}catch let error{
print(error.localizedDescription)
}
}
func addCard(card: Card, completion: @escaping () -> Void) {
let parameters = self.authParameters + ["name": card.name as AnyObject] + ["desc": card.description as AnyObject] + ["pos": "top" as AnyObject] + ["dueComplete": card.dueComplete as AnyObject] + ["idList": card.listId! as AnyObject]
do{
try Alamofire.request(Router.Cards.asURL(), method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).response(completionHandler: {(response)->Void in
})
}catch let error{
print(error.localizedDescription)
}
}
func deleteCard(_ ID: String, completion: @escaping () -> Void) {
let parameters = self.authParameters
do{
try Alamofire.request(Router.Card(cardID: ID).asURL(), method: .delete
, parameters: parameters, encoding: JSONEncoding.default, headers: nil).response(completionHandler: {(response)->Void in
})
}catch let error{
print(error.localizedDescription)
}
}
}
extension Card:Equatable, Comparable{
static func ==(lhs: Card, rhs: Card)->Bool{
return lhs.id == rhs.id
}
static func <(lhs: Card, rhs: Card)->Bool{
return Int(lhs.position!) < Int(rhs.position!)
}
}
|
//
// ShortTextMutablePicker.swift
// government_sdk
//
// Created by X Young. on 2017/9/28.
// Copyright © 2017年 YiGan. All rights reserved.
//
import Foundation
public class MultiModel: BaseExampleModel {
/// 选项
public var options:[Option]? = [Option]()
}
|
//
// InicioViewController.swift
// Banregio
//
// Created by Benjamin on 02/01/18.
// Copyright © 2018 rodolfo. All rights reserved.
//
import UIKit
class InicioViewController: UIViewController {
// Auxiliar variables
var hidePassword = true
// Outlets
@IBOutlet weak var correoTF: UITextField!
@IBOutlet weak var passwordTF: UITextField!
@IBOutlet weak var correoLabel: UILabel!
@IBOutlet weak var ingresarButton: UIButton!
@IBOutlet weak var sucursal: UIButton!
@IBAction func sucursalAction(_ sender: Any) {
print("Sucursal")
}
@IBAction func ingresar(_ sender: Any) {
print("Ingresar presionado")
if correoTF.text == "" || passwordTF.text == "" {
Alert.createAlert(titulo: "Campos vacios", mensaje: "Por favor rellena todos los campos marcados", vista: self)
}
LoginService.login(user: correoTF.text!, password: passwordTF.text!, callback: {
status in
if status {
//Present the tutorial
let storyboard = UIStoryboard( name: "Main", bundle: nil )
let vistaInicio = storyboard.instantiateViewController(withIdentifier: "PageViewController")
self.present( vistaInicio, animated: true, completion: nil )
} else {
Alert.createAlert(titulo: "Datos incorrectos", mensaje: "Por favor revisa tu información", vista: self)
}
})
}
override func viewDidLoad() {
super.viewDidLoad()
prepareElements()
}
override func viewDidAppear(_ animated: Bool) {
// To hide Keyboard
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard ))
view.addGestureRecognizer(tap)
if !CheckConnection.isConnectedToInternet() {
Alert.createAlert(titulo: "Datos celulares desactivados", mensaje: "Para realizar esta acción activa los datos celulares o usa Wi-fi", vista: self)
}
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func prepareElements(){
ingresarButton.layer.cornerRadius = 8
sucursal.layer.cornerRadius = 9
}
}
|
// MIT License
//
// InteractiveTimeline
// Copyright © 2017 Mikołaj Styś
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
class ViewController: UIViewController {
let timeline = TimelineView()
var constraint: NSLayoutConstraint?
override func loadView() {
super.loadView()
setupRootView()
let scrollView = setupScrollView(into: view)
scrollView.addSubview(timeline)
setupTimeline(in: scrollView)
}
private func setupRootView() {
view.backgroundColor = .white
}
private func setupScrollView(into view: UIView) -> UIScrollView {
let scrollView = UIScrollView()
view.addSubview(scrollView)
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
scrollView.heightAnchor.constraint(equalToConstant: 200).isActive = true
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
return scrollView
}
private func setupTimeline(in scrollView: UIScrollView) {
timeline.isUserInteractionEnabled = true
timeline.backgroundColor = .white
timeline.translatesAutoresizingMaskIntoConstraints = false
timeline.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor).isActive = true
timeline.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor).isActive = true
timeline.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor).isActive = true
timeline.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor).isActive = true
timeline.prepare(scrollView, updateTime: true)
}
}
|
//
// FirestoreService.swift
// GTor
//
// Created by Safwan Saigh on 14/05/2020.
// Copyright © 2020 Safwan Saigh. All rights reserved.
//
import Foundation
import FirebaseFirestore
import CodableFirebase
enum FirestoreKeys {
enum Collection: String {
case users = "users"
case goals = "goals"
case categories = "categories"
case tasks = "tasks"
}
}
class FirestoreService {
static var shared = FirestoreService()
func getDocumentOnce<T: Codable>(collection: FirestoreKeys.Collection, documentId: String, completion: @escaping (Result<T, Error>) -> ()){
let reference = Firestore.firestore().collection(collection.rawValue).document(documentId)
reference.getDocument { (documentSnapshot, err) in
DispatchQueue.main.async {
if let err = err {
completion(.failure(err))
return
}
//Check the documentSnapshot
guard let documentSnapshot = documentSnapshot else {
completion(.failure(FirestoreErrorHandler.noDocumentSnapshot))
return
}
//Check the data
guard let document = documentSnapshot.data() else {
completion(.failure(FirestoreErrorHandler.noSnapshotData))
return
}
var model: T
//Decoding
do {
model = try FirebaseDecoder().decode(T.self, from: document)
} catch (let error) {
fatalError("Error in decoding the model: \(error.localizedDescription)")
}
completion(.success(model))
}
}
}
func getDocument<T: Codable>(collection: FirestoreKeys.Collection, documentId: String, completion: @escaping (Result<T, Error>) -> ()){
let reference = Firestore.firestore().collection(collection.rawValue).document(documentId)
reference.addSnapshotListener { (documentSnapshot, err) in
DispatchQueue.main.async {
if let error = err {
completion(.failure(error))
}
guard let documentSnapshot = documentSnapshot else {
completion(.failure(FirestoreErrorHandler.noDocumentSnapshot))
return
}
guard let document = documentSnapshot.data() else {
completion(.failure(FirestoreErrorHandler.noSnapshotData))
return
}
var model: T
do {
model = try FirebaseDecoder().decode(T.self, from: document)
} catch(let error) {
fatalError("Error in decoding the model: \(error.localizedDescription)")
}
completion(.success(model))
}
}
}
//Check for the snapShotData
func getDocumentsOnce<T: Codable>(collection: FirestoreKeys.Collection, documentId: String, completion: @escaping (Result<[T], Error>) -> ()){
let reference = Firestore.firestore().collection(collection.rawValue).whereField("uid", isEqualTo: documentId)//Revice this
reference.getDocuments { (querySnapshot, err) in
DispatchQueue.main.async {
if let error = err {
completion(.failure(error))
}
guard let querySnapshot = querySnapshot else {
completion(.failure(FirestoreErrorHandler.noDocumentSnapshot))
return
}
var models: [T] = []
let documents = querySnapshot.documents
for document in documents {
//Decoding
do {
try models.append(FirebaseDecoder().decode(T.self, from: document.data()))
} catch (let error) {
fatalError("Error in decoding the model: \(error.localizedDescription)")
}
}
completion(.success(models))
}
}
}
//Check for the snapShotData
func getDocuments<T: Codable>(collection: FirestoreKeys.Collection, documentId: String, completion: @escaping (Result<[T], Error>) -> ()){
let reference = Firestore.firestore().collection(collection.rawValue).whereField("uid", isEqualTo: documentId)//Revice this
reference.addSnapshotListener { (querySnapshot, err) in
DispatchQueue.main.async {
if let error = err {
completion(.failure(error))
}
guard let querySnapshot = querySnapshot else {
completion(.failure(FirestoreErrorHandler.noDocumentSnapshot))
return
}
var models: [T] = []
let documents = querySnapshot.documents
for document in documents {
//Decoding
do {
try models.append(FirebaseDecoder().decode(T.self, from: document.data()))
} catch (let error) {
fatalError("Error in decoding the model: \(error.localizedDescription)")
}
}
completion(.success(models))
}
}
}
func saveDocument<T: Codable>(collection: FirestoreKeys.Collection, documentId: String, model: T, completion: @escaping (Result<Void, Error>) -> ()){
let reference = Firestore.firestore().collection(collection.rawValue).document(documentId)
var doc: [String:Any] = [:]
do {
doc = try FirebaseEncoder().encode(model) as! [String : Any]
}catch(let error) {
fatalError("Error in encoding the model: \(error.localizedDescription)")
}
doc["appVersion"] = appVersion // This is a customized code
doc["updated_at"] = Timestamp(date: Date()) // This is a customized code
reference.setData(doc, merge: true) { error in
DispatchQueue.main.async {
if let error = error {
completion(.failure(error))
}
completion(.success(()))
}
}
}
func deleteDocument(collection: FirestoreKeys.Collection, documentId: String, completion: @escaping (Result<Void, Error>) -> ()){
let reference = Firestore.firestore().collection(collection.rawValue).document(documentId)
reference.delete { (error) in
if let error = error {
completion(.failure(error))
}
completion(.success(()))
}
}
func updateDocument<T: Codable>(collection: FirestoreKeys.Collection, documentId: String, field: String, newData: T, completion: @escaping (Result<Void, Error>) -> ()){
DispatchQueue.main.async {
do {
let doc = try FirebaseEncoder().encode(newData)
let reference = Firestore.firestore().collection(collection.rawValue).document(documentId)
reference.updateData([field: doc]) { (error) in
if let error = error {
completion(.failure(error))
}
completion(.success(()))
}
}catch(let error) {
fatalError("Error in encoding the model: \(error.localizedDescription)")
}
}
}
}
|
//
// SponserTimeLineCell.swift
// Elshams
//
// Created by mac on 2/27/19.
// Copyright © 2019 mac. All rights reserved.
//
import UIKit
class SponserTimeLineCell: UICollectionViewCell {
@IBOutlet weak var sponserLogo: UIImageView!
@IBOutlet weak var sponserName: UILabel!
func setSponserTimeLineCell(sponsersList:Sponsers) {
sponserLogo.layer.cornerRadius = sponserLogo.frame.width / 2
sponserLogo.clipsToBounds = true
sponserName.text = sponsersList.sponserName
if sponsersList.sponserImageUrl != nil || !((sponsersList.sponserImageUrl?.isEmpty)!) {
// imgUrl(imgUrl: )
Helper.loadImagesKingFisher(imgUrl: (sponsersList.sponserImageUrl)!, ImgView: sponserLogo)
}
}
}
|
//
// JobLocation.swift
// layout
//
// Created by Rama Agastya on 24/08/20.
// Copyright © 2020 Rama Agastya. All rights reserved.
//
import Foundation
struct JobLocation:Decodable {
let id: Int
let location_name: String
let sub_location: Int
let level: Int
let date_add: String
let long_location: String
let text: String
}
|
//
// UIImageView+Extension.swift
// AMImageEditor
//
// Created by Ali M Irshad on 08/10/20.
//
import UIKit
extension UIImageView {
/// Returns the image Rect(optional) from the image view
/// the Image content mode should be Aspect Fit
func getImageRect() -> CGRect? {
if let imageSize = self.image?.size {
let imageScale = fminf(Float(self.bounds.width / (imageSize.width)), Float(self.bounds.height / (imageSize.height)))
let scaledImageSize = CGSize(width: (imageSize.width) * CGFloat(imageScale), height: (imageSize.height ) * CGFloat(imageScale))
let imageFrame = CGRect(x: CGFloat(roundf(Float(0.5 * (self.bounds.width - scaledImageSize.width)))), y: CGFloat(roundf(Float(0.5 * (self.bounds.height - scaledImageSize.height)))), width: CGFloat(roundf(Float(scaledImageSize.width))), height: CGFloat(roundf(Float(scaledImageSize.height))))
return imageFrame
}
return nil
}
}
|
//
// CGURLSessionManagerConfiguration.swift
// TestCG_CGKit
//
// Created by DY on 2017/3/31.
// Copyright © 2017年 apple. All rights reserved.
//
import UIKit
class CGURLSessionManagerConfiguration: NSObject {
let sessionConfiguration : URLSessionConfiguration
let baseURL : URL?
var baseURLString : String? {
return self.baseURL?.absoluteString
}
init(sessionConfiguration: URLSessionConfiguration, baseURL: URL?) {
self.sessionConfiguration = sessionConfiguration
self.baseURL = baseURL
super.init()
}
override convenience init() {
self.init(sessionConfiguration: URLSessionConfiguration.default, baseURL: nil)
}
}
|
//
// DownloaderTask.swift
// AssetLoader
//
// Created by Shadrach Mensah on 02/01/2020.
// Copyright © 2020 Shadrach Mensah. All rights reserved.
//
import Foundation
open class AssetDownloadTask:NSObject, AssetDownloaderTaskProtocol{
let task:URLSessionDownloadTask
init(task:URLSessionDownloadTask) {
self.task = task
}
public func resume(){
task.resume()
}
public func cancel(){
task.cancel()
}
}
|
#if canImport(OpenGL)
import OpenGL.GL3
#endif
#if canImport(OpenGLES)
import OpenGLES
#endif
#if canImport(COpenGLES)
import COpenGLES.gles2
let GL_BGRA = GL_RGBA // A hack: Raspberry Pi needs this or framebuffer creation fails
#endif
#if canImport(COpenGL)
import COpenGL
#endif
public enum PixelFormat {
case bgra
case rgba
case rgb
case luminance
func toGL() -> Int32 {
switch self {
case .bgra: return GL_BGRA
case .rgba: return GL_RGBA
case .rgb: return GL_RGB
case .luminance: return GL_LUMINANCE
}
}
}
// TODO: Replace with texture caches where appropriate
public class RawDataInput: ImageSource {
public let targets = TargetContainer()
public init() {}
public func uploadBytes(_ bytes: [UInt8], size: Size, pixelFormat: PixelFormat, orientation: ImageOrientation = .portrait) {
let dataFramebuffer = sharedImageProcessingContext.framebufferCache.requestFramebufferWithProperties(orientation: orientation, size: GLSize(size), textureOnly: true, internalFormat: pixelFormat.toGL(), format: pixelFormat.toGL())
glActiveTexture(GLenum(GL_TEXTURE1))
glBindTexture(GLenum(GL_TEXTURE_2D), dataFramebuffer.texture)
glTexImage2D(GLenum(GL_TEXTURE_2D), 0, GL_RGBA, size.glWidth(), size.glHeight(), 0, GLenum(pixelFormat.toGL()), GLenum(GL_UNSIGNED_BYTE), bytes)
updateTargetsWithFramebuffer(dataFramebuffer)
}
public func transmitPreviousImage(to _: ImageConsumer, atIndex _: UInt) {
// TODO: Determine if this is necessary for the raw data uploads
}
} |
//
// MyColor.swift
// HelpENG
//
// Created by Wanni on 2020/06/18.
// Copyright © 2020 Wanni. All rights reserved.
//
import UIKit
protocol MyColor {
}
extension MyColor {
var mainColor: UIColor {
return #colorLiteral(red: 1, green: 0.3186968267, blue: 0.3049468994, alpha: 1)
}
var subColor: UIColor {
return .white
}
var backgroundColor: UIColor {
return #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
}
var clearColor: UIColor {
return #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0)
}
var textColor: UIColor {
return #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
}
var cellBackground: UIColor {
return #colorLiteral(red: 0.9656682611, green: 0.96549505, blue: 0.9593854547, alpha: 1)
}
}
|
import Foundation
struct Film: Codable, Hashable {
let title: String
let episodeId: Int
let openingCrawl, director, producer, releaseDate: String
let characters: [String]
let url: URL
}
|
//
// JSPreviewPopAnimator.swift
// JSPhotoPicker
//
// Created by jesse on 2/7/17.
// Copyright © 2017 jesse. All rights reserved.
//
import UIKit
class JSDismissAnimator: MainAnimator {
override func animateTransitionEvent() {
if !transitionContext.isInteractive {
guard let navControl = toControl as? UINavigationController else { return }
guard let toControl = navControl.top as? JSPhotoViewController,
let fromControl = fromControl as? JSPreviewController else { return }
let initialView: UIImageView = UIImageView(frame: fromControl.animationRect(index: fromControl.currentPage))
initialView.contentMode = .scaleAspectFill
initialView.clipsToBounds = true
if let image = fromControl.animationImage(index: fromControl.currentPage) {
initialView.image = image
}else {
initialView.image = UIImage(color: defaultColor, size: CGSize(width: 1, height: 1))
}
containerView.addSubview(initialView)
/// 将原来的view隐藏
fromControl.animationView(index: fromControl.currentPage)?.isHidden = true
UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
initialView.frame = toControl.animationRect(index: fromControl.currentPage)
self.fromControl.view.backgroundColor = UIColor.clear
}) { _ in
initialView.removeFromSuperview()
toControl.animationView(index: fromControl.currentPage)?.isHidden = false
self.completeTransition()
}
}
}
}
|
//
// SearchResult.swift
// iTunes Music Video Player
//
// Created by Gabriel on 26/05/2021.
//
import Foundation
struct SearchResult {
let query: String
let results: [MusicVideoListViewModel]
}
|
//
// Tree.swift
// AlgorithmSwift
//
// Created by Liangzan Chen on 1/30/18.
// Copyright © 2018 clz. All rights reserved.
//
import UIKit
class Tree<T: Equatable> : CustomStringConvertible {
var value: T
var parent: Tree?
var children: [Tree] = []
init(value: T) {
self.value = value
}
public var description: String {
var text = "\(value)"
if !children.isEmpty {
text += "{ \(children.map{$0.description}.joined(separator: ", ")) }"
}
return text
}
func add(child: Tree) {
self.children.append(child)
}
func add(children: [Tree]) {
self.children += children
}
func search(_ value: T) -> Tree? {
if value == self.value {
return self
}
for child in children {
if let found = child.search(value) {
return found
}
}
return nil
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.