text stringlengths 8 1.32M |
|---|
//
// FDDisplayModeAdditions.swift
// FruitzOfDojo
//
// Created by C.W. Betts on 5/18/16.
// Copyright © 2016 C.W. Betts. All rights reserved.
//
import Foundation
import FruitzOfDojo.FDDisplayMode
extension FDDisplayMode: Comparable {
static public func ==(lhs: FDDisplayMode, rhs: FDDisplayMode) -> Bool {
return lhs.isEqual(to: rhs)
}
static public func <(lhs:FDDisplayMode, rhs: FDDisplayMode) -> Bool {
return lhs.compare(rhs) == .orderedAscending
}
static public func >(lhs:FDDisplayMode, rhs: FDDisplayMode) -> Bool {
return lhs.compare(rhs) == .orderedDescending
}
}
|
import XCTest
import Foundation
import Dispatch
@testable import gRPC
func Log(_ message : String) {
FileHandle.standardError.write((message + "\n").data(using:.utf8)!)
}
class gRPCTests: XCTestCase {
func testBasicSanity() {
gRPC.initialize()
let latch = CountDownLatch(2)
DispatchQueue.global().async() {
do {
try server()
} catch (let error) {
XCTFail("server error \(error)")
}
latch.signal()
}
DispatchQueue.global().async() {
do {
try client()
} catch (let error) {
XCTFail("client error \(error)")
}
latch.signal()
}
latch.wait()
}
}
extension gRPCTests {
static var allTests : [(String, (gRPCTests) -> () throws -> Void)] {
return [
("testBasicSanity", testBasicSanity),
]
}
}
let address = "localhost:8999"
let host = "foo.test.google.fr"
let clientText = "hello, server!"
let serverText = "hello, client!"
let initialClientMetadata =
["x": "xylophone",
"y": "yu",
"z": "zither"]
let initialServerMetadata =
["a": "Apple",
"b": "Banana",
"c": "Cherry"]
let trailingServerMetadata =
["0": "zero",
"1": "one",
"2": "two"]
let steps = 30
let hello = "/hello"
let goodbye = "/goodbye"
let statusCode = 0
let statusMessage = "OK"
func verify_metadata(_ metadata: Metadata, expected: [String:String]) {
XCTAssertGreaterThanOrEqual(metadata.count(), expected.count)
for i in 0..<metadata.count() {
if expected[metadata.key(i)] != nil {
XCTAssertEqual(metadata.value(i), expected[metadata.key(i)])
}
}
}
func client() throws {
let message = clientText.data(using: .utf8)
let channel = gRPC.Channel(address:address)
channel.host = host
for i in 0..<steps {
let latch = CountDownLatch(1)
let method = (i < steps-1) ? hello : goodbye
let call = channel.makeCall(method)
let metadata = Metadata(initialClientMetadata)
try call.start(.unary, metadata:metadata, message:message) {
(response) in
// verify the basic response from the server
XCTAssertEqual(response.statusCode, statusCode)
XCTAssertEqual(response.statusMessage, statusMessage)
// verify the message from the server
let resultData = response.resultData
let messageString = String(data: resultData!, encoding: .utf8)
XCTAssertEqual(messageString, serverText)
// verify the initial metadata from the server
let initialMetadata = response.initialMetadata!
verify_metadata(initialMetadata, expected: initialServerMetadata)
// verify the trailing metadata from the server
let trailingMetadata = response.trailingMetadata!
verify_metadata(trailingMetadata, expected: trailingServerMetadata)
// report completion
latch.signal()
}
// wait for the call to complete
latch.wait()
}
usleep(500) // temporarily delay calls to the channel destructor
}
func server() throws {
let server = gRPC.Server(address:address)
var requestCount = 0
let latch = CountDownLatch(1)
server.run() {(requestHandler) in
do {
requestCount += 1
XCTAssertEqual(requestHandler.host, host)
if (requestCount < steps) {
XCTAssertEqual(requestHandler.method, hello)
} else {
XCTAssertEqual(requestHandler.method, goodbye)
}
let initialMetadata = requestHandler.requestMetadata
verify_metadata(initialMetadata, expected: initialClientMetadata)
let initialMetadataToSend = Metadata(initialServerMetadata)
try requestHandler.receiveMessage(initialMetadata:initialMetadataToSend)
{(messageData) in
let messageString = String(data: messageData!, encoding: .utf8)
XCTAssertEqual(messageString, clientText)
}
if requestHandler.method == goodbye {
server.stop()
}
let replyMessage = serverText
let trailingMetadataToSend = Metadata(trailingServerMetadata)
try requestHandler.sendResponse(message:replyMessage.data(using: .utf8)!,
statusCode:statusCode,
statusMessage:statusMessage,
trailingMetadata:trailingMetadataToSend)
} catch (let error) {
XCTFail("error \(error)")
}
}
server.onCompletion() {
// exit the server thread
latch.signal()
}
// wait for the server to exit
latch.wait()
}
|
//
// logo.swift
// buroptima1
//
// Created by Nail Safin on 28.05.2020.
// Copyright © 2020 Nail Safin. All rights reserved.
//
import SwiftUI
struct Logo: View {
var body: some View {
Image("logo")
.resizable()
.padding(.bottom, 38.0)
.frame(width: 300.0, height: 300.0)
.scaledToFill()
.clipShape(Circle())
.overlay(Circle().stroke(Color.white, lineWidth: 4))
.shadow(radius: 10)
}
}
struct Logo_Previews: PreviewProvider {
static var previews: some View {
Logo()
}
}
|
//
// SimulationViewController.swift
// Assignment3
//
// Created by stephen chang on 7/10/16.
// Copyright © 2016 Stephen Chang. All rights reserved.
import UIKit
class SimulationViewController: UIViewController, EngineDelegate {
//creat outlet for gridview
//allows you to use stuff in GridView
@IBOutlet weak var gridView: GridView!
override func viewDidLoad() {
super.viewDidLoad()
//set itself as the delegate of the StandardEngine singleton
StandardEngine.sharedInstance.delegate = self
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let rows = PersistenceService.sharedInstance.numberOfRows
let cols = PersistenceService.sharedInstance.numberOfCollumns
let grid = StandardEngine.sharedInstance.grid
if grid.cols != cols && grid.rows != rows {
StandardEngine.sharedInstance.grid = Grid(rows: rows, cols: cols)
}
}
// MARK: - EngineDelegate
func engineDidUpdate(withGrid: GridProtocol) {
if let grid = withGrid as? Grid {
self.gridView.grid = grid
}
}
//couldn't get this working in time.
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// StandardEngine.sharedInstance.step()
//let grid = StandardEngine.sharedInstance.grid
if let touch = touches.first {
//let position :CGPoint = touch.locationInView(view)
let position :CGPoint = touch.locationInView(view)
var xCGFloat = position.x
var yCGFloat = position.y
print("CGFloat coordinates before \(xCGFloat) \(yCGFloat)")
xCGFloat = (floor((xCGFloat - gridView.xStart)/10))
yCGFloat = (floor((yCGFloat - gridView.yStart)/10))
//xFloat = (floor((xFloat - 50 )/10))
let xInt = Int(xCGFloat)
let yInt = Int(yCGFloat)
print("CGFloat coordinates after \(xCGFloat) \(yCGFloat)")
//if gridView.before[yInt][xInt] == false{
//gridView.grid[yInt, xInt] = .Living
//gridView.grid[yInt][xInt] = toggle(gridView.grid[yInt][xInt])
//gridView.setNeedsDisplay()
//}
//gridView.fillCell(xCGFloat, yCoord: yCGFloat)
//grid[yInt, xInt] = .Living
//StandardEngine.sharedInstance.grid = grid
}
}//ends touchesBegan
//iterate button = runButton
@IBAction func runButton(sender: UIButton) {
StandardEngine.sharedInstance.step()
}
//start button = populateButton
@IBAction func populateButton(sender: UIButton) {
let grid = StandardEngine.sharedInstance.grid
/*
//clear existing if any grid
for y in 0..<grid.cols{//iterate 0-9
for x in 0..<grid.rows{//iterate 0-9
grid[y, x] = .Empty
}
}
*/
//initialize before array with random bools and update enum grid
for y in 0..<grid.cols{//iterate 0-9
for x in 0..<grid.rows{//iterate 0-9
// if arc4random_uniform generates 1, then it will set cell to true
if arc4random_uniform(3) == 1 {
gridView.numOfLivingCellsInBefore+=1
//update enum grid
grid[y, x] = .Living
} else {
//update enum grid
grid[y, x] = .Empty
}
}
}//ends initialize before array
StandardEngine.sharedInstance.grid = grid
}//ends populateButton
}//ends view controller
|
//
// ArrayDataSource.swift
// DataSources
//
// Created by Sergey on 14.09.2018.
// Copyright © 2018 Sergey. All rights reserved.
//
import UIKit
open class ArrayDataSource: DefaultDataSource, ArrayDataSourceRepresentable {
// MARK: - Private -
private func sectionChangeHandler(for sectionIndex: Int, with handler: SectionsChangeHandler?) -> SectionChangeHandler {
return { (indices) in
let indexPathes = indices.compactMap({ IndexPath(row: $0, section: sectionIndex) })
handler?(indexPathes)
}
}
// MARK: - Public -
// MARK: Append
public func append(with items: [PresenterType], toSectionAt sectionIndex: Int, handler: SectionsChangeHandler?) {
guard sections.indices.contains(sectionIndex) else { return }
let section = sections[sectionIndex]
section.append(with: items, handler: sectionChangeHandler(for: sectionIndex, with: handler))
}
public func append(with newSections: [SectionRepresentable], handler: DataSourceChangeHandler?) {
guard !newSections.isEmpty else { return }
let diff = newSections.indices.newRange(offsetBy: sections.count).asIndexSet()
sections.append(contentsOf: newSections)
handler?(diff)
}
// MARK: Remove
public func remove(itemAt indexPath: IndexPath) {
guard sections.indices.contains(indexPath.section) else { return }
let section = sections[indexPath.section]
section.remove(itemAt: indexPath.row)
}
public func removeAllItems(handler: SectionsChangeHandler?) {
let deletedIndexPathes = indexPathes
sections.forEach({ $0.removeAll(with: nil) })
handler?(deletedIndexPathes)
}
public func remove(sectionAt index: Int) {
guard sections.indices.contains(index) else { return }
sections.remove(at: index)
}
public func removeAllSections(handler: DataSourceChangeHandler?) {
let deletedIndices = sectionsIndices
sections.removeAll()
handler?(deletedIndices)
}
// MARK: Insert
public func insert(with items: [PresenterType], at indexPath: IndexPath, handler: SectionsChangeHandler?) {
guard sections.indices.contains(indexPath.section) else { return }
let section = sections[indexPath.section]
section.insert(with: items, at: indexPath.row, handler: sectionChangeHandler(for: indexPath.section, with: handler))
}
public func insert(with newSections: [SectionRepresentable], at index: Int, handler: DataSourceChangeHandler?) {
guard !newSections.isEmpty, sections.indices.contains(index) || index == 0 else { return }
let diff = newSections.indices.newRange(offsetBy: index).asIndexSet()
sections.insert(contentsOf: newSections, at: index)
handler?(diff)
}
// MARK: Replace/Reorder
public func replace(itemAt indexPath: IndexPath, with item: PresenterType) {
guard sections.indices.contains(indexPath.section) else { return }
let section = sections[indexPath.section]
section.replace(itemAt: indexPath.row, with: item)
}
public func reorderItems(at sourceIndexPath: IndexPath, and destinationIndexPath: IndexPath) {
guard sections.indices.contains(sourceIndexPath.section), sections.indices.contains(destinationIndexPath.section) else { return }
if sourceIndexPath.section == destinationIndexPath.section {
reorderItems(in: sourceIndexPath.section, at: sourceIndexPath.row, and: destinationIndexPath.row)
} else {
guard let sourceItem: PresenterType = item(at: sourceIndexPath) else { return }
if numberOfItems(in: destinationIndexPath.section) > destinationIndexPath.row {
insert(with: sourceItem, at: destinationIndexPath)
} else {
append(with: sourceItem, toSectionAt: destinationIndexPath.section, handler: nil)
}
remove(itemAt: sourceIndexPath)
}
}
public func replace(sectionAt index: Int, with section: SectionRepresentable) {
guard sections.indices.contains(index) else { return }
sections[index] = section
}
public func reorderSections(at sourceIndex: Int, and destinationIndex: Int) {
guard sections.indices.contains(sourceIndex), sections.indices.contains(destinationIndex) else { return }
sections.rearrange(from: sourceIndex, to: destinationIndex)
}
// MARK: - Private -
private func reorderItems(in sectionIndex: Int, at sourceIndex: Int, and destinationIndex: Int) {
guard sections.indices.contains(sectionIndex) else { return }
let section = sections[sectionIndex]
section.reorderItems(at: sourceIndex, and: destinationIndex)
}
}
|
//
// AppointmentsTableViewCell.swift
// SwiftAppointments
//
// Created by Venkata Vadigepalli on 02/01/2019.
// Copyright © 2019 vvrmobilesolutions. All rights reserved.
//
import UIKit
protocol AppointmentButtonsDelegate {
func viewTapped (at indexPath: IndexPath)
func printTapped (at indexPath: IndexPath)
}
class AppointmentsTableViewCell: UITableViewCell {
var delegate: AppointmentButtonsDelegate!
var indexPath: IndexPath!
@IBOutlet weak var hospitalDetailsLabel: UILabel!
@IBOutlet weak var appointmentDetailsLabel: UILabel!
@IBAction func printClick(_ sender: Any) {
self.delegate.viewTapped(at: indexPath)
}
@IBAction func saveClick(_ sender: Any) {
self.delegate.printTapped(at: indexPath)
}
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
}
func updateCell(hospitalAppointmentModel: HospitalAppointmentModel){
hospitalDetailsLabel.text = "\(hospitalAppointmentModel.hospitalName) ( \(hospitalAppointmentModel.hospitalId) )"
appointmentDetailsLabel.text = "\(hospitalAppointmentModel.dateOfAppointment) \(hospitalAppointmentModel.dayOfAppointment) \(hospitalAppointmentModel.timeOfAppointment)"
}
}
|
//
// SurveyController.swift
// Croesus
//
// Created by Ian Wanyoike on 02/02/2020.
// Copyright © 2020 Pocket Pot. All rights reserved.
//
import UIKit
import RxSwift
class SurveyController: UITableViewController {
let viewModel: SurveyViewModel
let disposeBag: DisposeBag
// MARK: - Initialisation
init(viewModel: SurveyViewModel) {
self.viewModel = viewModel
self.disposeBag = DisposeBag()
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardOnTap()
self.title = "Survey"
self.addNavButton(
to: self.navigationItem,
position: .left,
selector: #selector(self.goBack),
tintColor: .darkText,
image: R.image.leftArrow18()
)
self.addNavButton(
to: self.navigationItem,
position: .right,
selector: #selector(self.save),
tintColor: .darkText,
image: R.image.tick18()
)
self.tableView.separatorStyle = .none
self.tableView.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.register(
UINib(resource: R.nib.questionCell),
forCellReuseIdentifier: R.nib.questionCell.identifier
)
self.tableView.register(
UINib(resource: R.nib.answerCell),
forCellReuseIdentifier: R.nib.answerCell.identifier
)
self.viewModel.questions.bind { [weak self] _ in
self?.tableView.reloadData()
}.disposed(by: self.disposeBag)
self.viewModel.loadQuestions().subscribe { [weak self] _ in
guard let `self` = self else { return }
self.viewModel.setupBinding()
}.disposed(by: self.disposeBag)
}
@objc func goBack() {
self.viewModel.onCancel()
}
@objc func save() {
self.viewModel.onSave()
}
}
// MARK: - Table view data source
extension SurveyController {
override func numberOfSections(in tableView: UITableView) -> Int {
return self.viewModel.questions.value.count
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 48))
let label = UILabel(frame: CGRect(x: 24, y: 0, width: tableView.frame.width - 48, height: 48))
label.font = R.font.quicksandSemiBold(size: 16)
label.text = self.viewModel.questions.value[section].title.value
view.addSubview(label)
view.backgroundColor = UIColor.cellHeaderGray
return view
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 48
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let viewModel = self.viewModel.questions.value[section]
guard let type = viewModel.type.value else { return 1 }
switch type {
case .radio:
return 1 + viewModel.options.value.count
case .text:
return 2
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let viewModel = self.viewModel.questions.value[indexPath.section]
var cell = UITableViewCell()
switch indexPath.row {
case 0:
guard let questionCell = R.nib.questionCell(owner: tableView) else { break }
questionCell.viewModel = viewModel
cell = questionCell
case 1..<self.tableView(tableView, numberOfRowsInSection: indexPath.section):
guard let answerCell = R.nib.answerCell(owner: tableView) else { break }
answerCell.optionIndex = indexPath.row - 1
answerCell.viewModel = viewModel
cell = answerCell
default:
cell = UITableViewCell()
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let viewModel = self.viewModel.questions.value[indexPath.section]
guard viewModel.type.value != .some(.text) else { return }
viewModel.selectedOptionIndex.accept(indexPath.row - 1)
}
}
|
//
// MimicTests.swift
// MimicTests
//
// Created by Felipe Ruz on 5/23/19.
// Copyright © 2019 Felipe Ruz. All rights reserved.
//
@testable import Mimic
import XCTest
import PDFKit
class MimicTests: XCTestCase {
override func tearDown() {
Mimic.stopAllMimics()
super.tearDown()
}
func testGetRequest() {
let url = "http://localhost/get"
Mimic.mimic(
request: request(with: .get, url: url),
response: response(with: ["message": "testGetRequest"])
)
let exp = expectation(description: "testGetRequest")
makeRequest(url: url, method: .get, headers: nil) { data, response, error in
exp.fulfill()
XCTAssertNil(error)
XCTAssertEqual(response?.url?.absoluteString, url)
let headers = (response as? HTTPURLResponse)?.allHeaderFields
XCTAssertEqual(headers?.count, 1)
XCTAssertEqual(
headers?["Content-Type"] as? String,
"application/json; charset=utf-8"
)
guard
let data = data,
let json = try? JSONSerialization.jsonObject(with: data, options: [.allowFragments]),
let jsonDict = json as? [String: String]
else {
XCTFail("Failed to create JSON from data")
return
}
XCTAssertEqual(jsonDict["message"], "testGetRequest")
}
wait(for: [exp], timeout: 5)
}
func testPostRequest() {
let url = "http://localhost/post"
Mimic.mimic(
request: request(with: .post, url: url),
response: response(with: ["message": "testPostRequest"])
)
let exp = expectation(description: "testPostRequest")
makeRequest(
url: url,
method: .post,
headers: nil
) { data, response, error in
exp.fulfill()
XCTAssertNil(error)
XCTAssertEqual(response?.url?.absoluteString, url)
let headers = (response as? HTTPURLResponse)?.allHeaderFields
XCTAssertEqual(headers?.count, 1)
XCTAssertEqual(
headers?["Content-Type"] as? String,
"application/json; charset=utf-8"
)
guard
let data = data,
let json = try? JSONSerialization.jsonObject(with: data, options: [.allowFragments]),
let jsonDict = json as? [String: String]
else {
XCTFail("Failed to create JSON from data")
return
}
XCTAssertEqual(jsonDict["message"], "testPostRequest")
}
wait(for: [exp], timeout: 5)
}
func testDeleteRequest() {
let url = "http://localhost/delete"
Mimic.mimic(
request: request(with: .delete, url: url),
response: response(with: ["message": "testDeleteRequest"])
)
let exp = expectation(description: "testDeleteRequest")
makeRequest(
url: url,
method: .delete,
headers: nil
) { data, response, error in
exp.fulfill()
XCTAssertNil(error)
XCTAssertEqual(response?.url?.absoluteString, url)
let headers = (response as? HTTPURLResponse)?.allHeaderFields
XCTAssertEqual(headers?.count, 1)
XCTAssertEqual(
headers?["Content-Type"] as? String,
"application/json; charset=utf-8"
)
guard
let data = data,
let json = try? JSONSerialization.jsonObject(with: data, options: [.allowFragments]),
let jsonDict = json as? [String: String]
else {
XCTFail("Failed to create JSON from data")
return
}
XCTAssertEqual(jsonDict["message"], "testDeleteRequest")
}
wait(for: [exp], timeout: 5)
}
func testPutRequest() {
let url = "http://localhost/put"
Mimic.mimic(
request: request(with: .put, url: url),
response: response(with: ["message": "testPutRequest"])
)
let exp = expectation(description: "testPutRequest")
makeRequest(
url: url,
method: .put,
headers: nil
) { data, response, error in
exp.fulfill()
XCTAssertNil(error)
XCTAssertEqual(response?.url?.absoluteString, url)
let headers = (response as? HTTPURLResponse)?.allHeaderFields
XCTAssertEqual(headers?.count, 1)
XCTAssertEqual(
headers?["Content-Type"] as? String,
"application/json; charset=utf-8"
)
guard
let data = data,
let json = try? JSONSerialization.jsonObject(with: data, options: [.allowFragments]),
let jsonDict = json as? [String: String]
else {
XCTFail("Failed to create JSON from data")
return
}
XCTAssertEqual(jsonDict["message"], "testPutRequest")
}
wait(for: [exp], timeout: 5)
}
func testRequestWithHeaders() {
let url = "http://localhost/headers"
let data = [
"Cache-Control": "no-store",
"Pragma": "no-cache",
"Agent": "Mimic",
]
Mimic.mimic(
request: request(with: .get, url: url),
response: response(with: [:], status: 302, headers: data)
)
let exp = expectation(description: "testRequestWithHeaders")
makeRequest(url: url, method: .get, headers: data) { _, response, _ in
exp.fulfill()
guard let headers = (response as? HTTPURLResponse)?.allHeaderFields else {
fatalError("Failed to retrieve headers from response")
}
XCTAssertEqual(headers.count, 4)
XCTAssertEqual(headers["Cache-Control"] as? String, "no-store")
XCTAssertEqual(headers["Pragma"] as? String, "no-cache")
XCTAssertEqual(headers["Agent"] as? String, "Mimic")
}
wait(for: [exp], timeout: 500_000)
}
func testRawResponse() {
let url = "http://localhost/pdf"
guard
let path = Bundle(for: MimicTests.self).url(forResource: "SamplePDF", withExtension: "pdf"),
let data = try? Data(contentsOf: path)
else {
XCTFail("Failed to create Data from PDF")
return
}
Mimic.mimic(
request: request(with: .post, url: url),
response: rawResponse(with: data, headers: ["Content-Type": "application/pdf"])
)
let exp = expectation(description: "testRawResponse")
makeRequest(
url: url,
method: .post,
headers: nil
) { data, response, error in
exp.fulfill()
XCTAssertNil(error)
XCTAssertEqual(response?.url?.absoluteString, url)
let headers = (response as? HTTPURLResponse)?.allHeaderFields
XCTAssertEqual(headers?.count, 1)
XCTAssertEqual(headers?["Content-Type"] as? String, "application/pdf")
guard
let data = data,
let pdf = PDFDocument(data: data)
else {
XCTFail("Failed to create PDF from data")
return
}
XCTAssertEqual(pdf.pageCount, 1)
let text = pdf.page(at: 0)?.attributedString?.string
XCTAssertEqual("Sample PDF\n", text)
}
wait(for: [exp], timeout: 15)
}
func testStopMimic() {
let url = "http://localhost/delete"
let object = Mimic.mimic(
request: request(with: .delete, url: url),
response: response(with: ["message": "testDeleteRequest"])
)
XCTAssertEqual(MimicProtocol.mimics.count, 1)
Mimic.stopMimic(object)
XCTAssertTrue(MimicProtocol.mimics.isEmpty)
}
private func makeRequest(
url: String,
method: MimicHTTPMethod,
headers: [String: String]?,
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void
) {
guard let url = URL(string: url) else { return }
var request = URLRequest(url: url)
request.httpMethod = method.description
request.allHTTPHeaderFields = headers
let task = URLSession.shared.dataTask(with: request) { data, response, error in
completionHandler(data, response, error)
}
task.resume()
}
}
|
// UISearchBarExtensions.swift - Copyright 2020 SwifterSwift
#if canImport(UIKit) && os(iOS)
import UIKit
// MARK: - Properties
public extension UISearchBar {
/// SwifterSwift: Text field inside search bar (if applicable).
var textField: UITextField? {
if #available(iOS 13.0, *) {
return searchTextField
}
let subViews = subviews.flatMap(\.subviews)
guard let textField = (subViews.filter { $0 is UITextField }).first as? UITextField else {
return nil
}
return textField
}
/// SwifterSwift: Text with no spaces or new lines in beginning and end (if applicable).
var trimmedText: String? {
return text?.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
// MARK: - Methods
public extension UISearchBar {
/// SwifterSwift: Clear text.
func clear() {
text = ""
}
}
#endif
|
//
// Created by Pavel Sharanda on 20.09.16.
// Copyright © 2016. All rights reserved.
//
import Foundation
extension ObserveValueProtocol {
public func map<U>(_ transform: @escaping (ValueType) -> U) -> Observable<U> {
return Observable { observer in
return self.subscribe { result in
observer(transform(result))
}
}
}
public func map<U>(keyPath: KeyPath<ValueType, U>) -> Observable<U> {
return map { $0[keyPath: keyPath] }
}
public func compactMap<U>(_ transform: @escaping (ValueType) -> U?) -> Observable<U> {
return Observable { observer in
return self.subscribe { result in
if let newResult = transform(result) {
observer(newResult)
}
}
}
}
public func filter(_ isIncluded: @escaping (ValueType) -> Bool) -> Observable<ValueType> {
return compactMap { result in
return isIncluded(result) ? result : nil
}
}
public func forEach(_ f: @escaping (ValueType) -> Void) -> Observable<ValueType> {
return Observable { observer in
return self.subscribe { result in
f(result)
observer(result)
}
}
}
public func distinctUntilChanged(_ isEqual: @escaping (ValueType, ValueType) -> Bool) -> Observable<ValueType> {
return Observable { observer in
var lastValue: ValueType?
return self.subscribe { result in
if (lastValue.map { !isEqual($0, result) }) ?? true {
lastValue = result
observer(result)
}
}
}
}
}
extension ObserveValueProtocol {
public var withOldValue: Observable<(new: ValueType, old: ValueType?)> {
return Observable { observer in
var prevValue: ValueType?
return self.subscribe { result in
let oldPrevValue = prevValue
prevValue = result
observer((result, oldPrevValue))
}
}
}
}
extension ObserveValueProtocol {
public func just<U>(_ value: U) -> Observable<U> {
return map { _ -> U in
return value
}
}
public var just: Observable<Void> {
return just(())
}
}
extension ObserveValueProtocol where ValueType: Equatable {
public var distinctUntilChanged: Observable<ValueType> {
return distinctUntilChanged { $0 == $1 }
}
}
extension ObserveValueProtocol {
public var first: Observable<ValueType> {
return take(first: 1)
}
public func take(first: Int) -> Observable<ValueType> {
return Observable { observer in
var counter = 0
var disposable: Disposable?
disposable = self.subscribe { result in
if counter < first {
counter += 1
observer(result)
} else {
disposable?.dispose()
disposable = nil
}
}
return disposable!
}
}
public func take(while f: @escaping (ValueType) -> Bool) -> Observable<ValueType> {
return Observable { observer in
var canEmit = true
var disposable: Disposable?
disposable = self.subscribe { result in
if canEmit {
canEmit = f(result)
}
if canEmit {
observer(result)
} else {
disposable?.dispose()
disposable = nil
}
}
return disposable!
}
}
}
|
//
// DBManager.swift
// VisitMe
//
// Created by Oscar Allan Ruiz Toledo on 25/10/17.
// Copyright © 2017 Oscar Allan Ruiz Toledo . All rights reserved.
//
import Foundation
import OHMySQL
class DBManager{
var context: OHMySQLQueryContext?
func conectar(){
let client = OHMySQLUser(userName: "visitmeadmin", password: "Itesm2017", serverName: "visitme.cnqtyhpnqyxr.us-east-2.rds.amazonaws.com", dbName: "VisitMe", port: 3306, socket: nil)
let coordinator = OHMySQLStoreCoordinator(user: client!)
coordinator.encoding = .UTF8MB4
coordinator.connect()
context = OHMySQLQueryContext()
context?.storeCoordinator = coordinator
}
func registrarInvitacion(codigo: String, nombre: String, apellidoPaterno: String, apellidoMaterno: String, placas: String?, fecha: String, email: String, usuario: String) {
let query = OHMySQLQueryRequestFactory.insert("INVITACION", set: ["CODIGO": codigo, "USUARIO": usuario, "NOMBRE": nombre, "APELLIDO_PATERNO": apellidoPaterno, "APELLIDO_MATERNO": apellidoMaterno, "EMAIL": email, "FECHA_VISITA": fecha, "PLACAS": placas ?? nil])
try? context?.execute(query)
}
func registrarVigilante(nombre: String, apellidoPaterno: String, apellidoMaterno: String, password: String, email: String){
self.registrarUsuario(tabla: "VIGILANTE", nombre: nombre, apellidoPaterno: apellidoPaterno, apellidoMaterno: apellidoMaterno, password: password, email: email)
}
func registrarResidente(nombre: String, apellidoPaterno: String, apellidoMaterno: String, password: String, email: String){
self.registrarUsuario(tabla: "RESIDENTE", nombre: nombre, apellidoPaterno: apellidoPaterno, apellidoMaterno: apellidoMaterno, password: password, email: email)
}
func registrarResidenteCondominio(condoId: String, email: String){
var query = OHMySQLQueryRequestFactory.select("RESIDENTE", condition: "EMAIL= '\(email)'")
let responseQuery = (try? context?.executeQueryRequestAndFetchResult(query))!!
let response = responseQuery[0]
let residenteId = "\(response["ID"] as! NSNumber)"
query = OHMySQLQueryRequestFactory.insert("CONDOMINIO_USUARIO", set: ["CONDOMINIO": condoId, "USUARIO": residenteId])
try? context?.execute(query)
}
func registrarVigilanteCondominio(condoId: String, email: String){
var query = OHMySQLQueryRequestFactory.select("VIGILANTE", condition: "EMAIL= '\(email)'")
let responseQuery = (try? context?.executeQueryRequestAndFetchResult(query))!!
let response = responseQuery[0]
let vigilanteId = "\(response["ID"] as! NSNumber)"
query = OHMySQLQueryRequestFactory.insert("CONDOMINIO_VIGILANTE", set: ["CONDOMINIO": condoId, "VIGILANTE": vigilanteId])
try? context?.execute(query)
}
func registrarCondo(admin: String, calle: String, numero: String, colonia: String, cp: String, ciudad: String, estado: String){
let query = OHMySQLQueryRequestFactory.insert("CONDOMINIO", set: ["ADMIN": admin, "CALLE": calle, "NUMERO": numero, "COLONIA": colonia, "CP": cp, "CIUDAD": ciudad, "ESTADO": estado])
try? context?.execute(query)
}
func updateVigilante(atributoSeleccionado: String, datoActualizado: String, idActualizada: String){
self.updateUsuario(tabla: "VIGILANTE", atributo: atributoSeleccionado.uppercased(), dato: datoActualizado, ID: idActualizada)
}
func updateAdministrador(atributoSeleccionado: String, datoActualizado: String, idActualizada: String){
self.updateUsuario(tabla: "ADMINISTRADOR", atributo: atributoSeleccionado.uppercased(), dato: datoActualizado, ID: idActualizada)
}
func updateResidente(atributoSeleccionado: String, datoActualizado: String, idActualizada: String){
self.updateUsuario(tabla: "RESIDENTE", atributo: atributoSeleccionado.uppercased(), dato: datoActualizado, ID: idActualizada)
}
func updateUsuario(tabla: String, atributo: String, dato: String, ID: String) {
let condicionBusqueda: String = "ID=" + ID
let query = OHMySQLQueryRequestFactory.update(tabla, set: [atributo: dato], condition: condicionBusqueda)
try? context?.execute(query)
}
func updateInvitacion(codigo: String, atributo: String, dato: String){
let condicionBusqueda: String = "CODIGO= '\(codigo)'"
let query = OHMySQLQueryRequestFactory.update("INVITACION", set: [atributo.uppercased(): dato], condition: condicionBusqueda)
try? context?.execute(query)
}
func borrarAdmin(idSeleccionada: String){
self.borrarRegistro(tabla: "ADMINISTRADOR", ID: idSeleccionada)
}
func borrarResidente(idSeleccionada: String){
let query = OHMySQLQueryRequestFactory.delete("CONDOMINIO_USUARIO", condition: "USUARIO= \(idSeleccionada)")
try? context?.execute(query)
self.borrarRegistro(tabla: "RESIDENTE", ID: idSeleccionada)
}
func borrarVigilante(idSeleccionada: String){
let query = OHMySQLQueryRequestFactory.delete("CONDOMINIO_VIGILANTE", condition: "VIGILANTE= \(idSeleccionada)")
try? context?.execute(query)
self.borrarRegistro(tabla: "VIGILANTE", ID: idSeleccionada)
}
func borrarInvitacion(codigoSeleccionado: String){
let condicionBusqueda: String = "CODIGO= '\(codigoSeleccionado)'"
let query = OHMySQLQueryRequestFactory.delete("INVITACION", condition: condicionBusqueda)
try? context?.execute(query)
}
func borrarRegistro(tabla: String, ID: String){
let condicionBusqueda: String = "ID= '\(ID)'"
let query = OHMySQLQueryRequestFactory.delete(tabla, condition: condicionBusqueda)
try? context?.execute(query)
}
func registrarAdmin(nombre: String, apellidoPaterno: String, apellidoMaterno: String, password: String, email: String) -> Admin? {
self.registrarUsuario(tabla: "ADMINISTRADOR", nombre: nombre, apellidoPaterno: apellidoPaterno, apellidoMaterno: apellidoMaterno, password: password, email: email)
return cargarAdmin(email: email)
}
func registrarUsuario(tabla: String, nombre: String, apellidoPaterno: String, apellidoMaterno: String, password: String, email: String){
let query = OHMySQLQueryRequestFactory.insert(tabla, set: ["NOMBRE": nombre, "APELLIDO_PATERNO": apellidoPaterno, "APELLIDO_MATERNO": apellidoMaterno, "EMAIL": email, "PASSWORD": password])
try? context?.execute(query)
}
func cargarVigilante(email: String) -> Vigilante? {
let query = OHMySQLQueryRequestFactory.select("VIGILANTE", condition: "EMAIL= '\(email)'")
let responseQuery = (try? context?.executeQueryRequestAndFetchResult(query))!!
if responseQuery.count <= 0{
return nil
}
let response = responseQuery[0]
return Vigilante(id: "\(response["ID"] as! NSNumber)", nombre: response["NOMBRE"] as! String, apellidoPaterno: response["APELLIDO_PATERNO"] as! String, apellidoMaterno: response["APELLIDO_MATERNO"] as! String, email: response["EMAIL"] as! String)
}
func cargarCondominio(id: String) -> Condominio? {
let query = OHMySQLQueryRequestFactory.select("CONDOMINIO", condition: "id= \(id)")
let responseQuery = (try? context?.executeQueryRequestAndFetchResult(query))!!
if responseQuery.count <= 0{
return nil
}
let response = responseQuery[0]
return Condominio(id: id, adminEncargado: self.cargarAdmin(id: "\(response["ADMIN"] as! NSNumber)")!, calle: response["CALLE"] as! String, numero: response["NUMERO"] as! String, colonia: response["COLONIA"] as! String, cp: response["CP"] as! String, ciudad: response["CIUDAD"] as! String, estado: response["ESTADO"] as! String)
}
func cargarResidente(email: String) -> Usuario? {
let query = OHMySQLQueryRequestFactory.select("RESIDENTE", condition: "EMAIL= '\(email)'")
let responseQuery = (try? context?.executeQueryRequestAndFetchResult(query))!!
if responseQuery.count <= 0{
return nil
}
let response = responseQuery[0]
return Usuario(id: "\(response["ID"] as! NSNumber)", nombre: response["NOMBRE"] as! String, apellidoPaterno: response["APELLIDO_PATERNO"] as! String, apellidoMaterno: response["APELLIDO_MATERNO"] as! String, email: response["EMAIL"] as! String)
}
func cargarResidente(id: String) -> Usuario? {
let query = OHMySQLQueryRequestFactory.select("RESIDENTE", condition: "ID= \(id)")
let responseQuery = (try? context?.executeQueryRequestAndFetchResult(query))!!
if responseQuery.count <= 0{
return nil
}
let response = responseQuery[0]
return Usuario(id: "\(response["ID"] as! NSNumber)", nombre: response["NOMBRE"] as! String, apellidoPaterno: response["APELLIDO_PATERNO"] as! String, apellidoMaterno: response["APELLIDO_MATERNO"] as! String, email: response["EMAIL"] as! String)
}
func cargarAdmin(email: String) -> Admin? {
let query = OHMySQLQueryRequestFactory.select("ADMINISTRADOR", condition: "EMAIL= '\(email)'")
let responseQuery = (try? context?.executeQueryRequestAndFetchResult(query))!!
if responseQuery.count <= 0{
return nil
}
let response = responseQuery[0]
return Admin(id: "\(response["ID"] as! NSNumber)", nombre: response["NOMBRE"] as! String, apellidoPaterno: response["APELLIDO_PATERNO"] as! String, apellidoMaterno: response["APELLIDO_MATERNO"] as! String, email: response["EMAIL"] as! String)
}
func cargarAdmin(id: String) -> Admin? {
let query = OHMySQLQueryRequestFactory.select("ADMINISTRADOR", condition: "ID= \(id)")
let responseQuery = (try? context?.executeQueryRequestAndFetchResult(query))!!
if responseQuery.count <= 0{
return nil
}
let response = responseQuery[0]
return Admin(id: "\(response["ID"] as! NSNumber)", nombre: response["NOMBRE"] as! String, apellidoPaterno: response["APELLIDO_PATERNO"] as! String, apellidoMaterno: response["APELLIDO_MATERNO"] as! String, email: response["EMAIL"] as! String)
}
func compararPassword(email: String, password: String, tabla: String) ->Bool {
let query = OHMySQLQueryRequestFactory.select(tabla, condition: "EMAIL= '\(email)'")
let response = (try? context?.executeQueryRequestAndFetchResult(query))!!
if response.count <= 0{
return false;
}
let data = response[0]
let pass = data["PASSWORD"] as! String
if pass == password{
return true;
}
return false;
}
func buscarCodigo(codigo: String) -> Invitacion? {
let query = OHMySQLQueryRequestFactory.select("INVITACION", condition: "CODIGO= '\(codigo)'")
let response = (try? context?.executeQueryRequestAndFetchResult(query))!!
if response.count <= 0{
return nil
}
let data = response[0]
let usuario = "\(data["USUARIO"] as! NSNumber)"
let nombre = data["NOMBRE"] as! String
let apellidoPaterno = data["APELLIDO_PATERNO"] as! String
let apellidoMaterno = data["APELLIDO_MATERNO"] as! String
let placas = data["PLACAS"] as? String
let horaEntrada = data["HORA_ENTRADA"] as! String
let horaSalida = data["HORA_ENTRADA"] as! String
let expirada = data["EXPIRADA"] as! String
let email = data["EMAIL"] as! String
let fecha = data["FECHA_VISITA"] as! String
return Invitacion(folio: codigo, idUsuario: usuario, nombres: nombre, apellidoPaterno: apellidoPaterno, apellidoMaterno: apellidoMaterno, placas: placas, horaEntrada: horaEntrada, horaSalida: horaSalida, fechaValida: fecha, esExpirada: expirada == "1", email: email)
}
func cargarResidenteCondominio(id: String) -> Condominio {
let query = OHMySQLQueryRequestFactory.select("CONDOMINIO_USUARIO", condition: "USUARIO= \(id)")
let response = (try? context?.executeQueryRequestAndFetchResult(query))!![0]
return cargarCondominio(id: "\(response["CONDOMINIO"] as! NSNumber)")!
}
func cargarVigilanteCondominio(id: String) -> Condominio {
let query = OHMySQLQueryRequestFactory.select("CONDOMINIO_VIGILANTE", condition: "VIGILANTE= \(id)")
let response = (try? context?.executeQueryRequestAndFetchResult(query))!![0]
return cargarCondominio(id: "\(response["CONDOMINIO"] as! NSNumber)")!
}
func cargarAdminCondominio(adminId: String) -> Condominio{
let query = OHMySQLQueryRequestFactory.select("CONDOMINIO", condition: "ADMIN= \(adminId)")
let response = (try? context?.executeQueryRequestAndFetchResult(query))!![0]
return cargarCondominio(id: "\(response["ID"] as! NSNumber)")!
}
func cargarVisitantes(residenteId: String) -> [Invitacion]?{
let query = OHMySQLQueryRequestFactory.select("INVITACION", condition: "USUARIO= \(residenteId)")
let response = (try? context?.executeQueryRequestAndFetchResult(query))!!
if response.count <= 0{
return []
}
return self.toArrayVisitantes(dict: response)
}
func cargarResidentes(condoId: String) -> [Usuario]? {
let query = OHMySQLQueryRequestFactory.select("CONDOMINIO_USUARIO", condition: "CONDOMINIO= \(condoId)")
let response = (try? context?.executeQueryRequestAndFetchResult(query))!!
if response.count <= 0{
return []
}
return self.toArrayResidentes(dict: response)
}
func existeCorreo(tabla: String, correo: String) -> Bool{
let query = OHMySQLQueryRequestFactory.select(tabla, condition: "EMAIL= '\(correo)'")
let response = (try? context?.executeQueryRequestAndFetchResult(query))!!
if response.count <= 0{
return false
}
return true
}
func toArrayResidentes(dict: [[String: Any?]]) ->[Usuario]?{
var residentes: [Usuario] = []
for data in dict {
let residente = cargarResidente(id: "\(data["USUARIO"] as! NSNumber)")
residentes.append(residente!)
}
return residentes
}
func cargarVigilante(id: String) -> Vigilante? {
let query = OHMySQLQueryRequestFactory.select("VIGILANTE", condition: "ID= \(id)")
let responseQuery = (try? context?.executeQueryRequestAndFetchResult(query))!!
if responseQuery.count <= 0{
return nil
}
let response = responseQuery[0]
return Vigilante(id: "\(response["ID"] as! NSNumber)", nombre: response["NOMBRE"] as! String, apellidoPaterno: response["APELLIDO_PATERNO"] as! String, apellidoMaterno: response["APELLIDO_MATERNO"] as! String, email: response["EMAIL"] as! String)
}
func cargarVigilantes(condoId: String) -> [Vigilante]? {
let query = OHMySQLQueryRequestFactory.select("CONDOMINIO_VIGILANTE", condition: "CONDOMINIO= \(condoId)")
let response = (try? context?.executeQueryRequestAndFetchResult(query))!!
if response.count <= 0{
return []
}
return self.toArrayVigilantes(dict: response)
}
func toArrayVigilantes(dict: [[String: Any?]]) ->[Vigilante]?{
var vigilantes: [Vigilante] = []
for data in dict {
let vigilante = cargarVigilante(id: "\(data["VIGILANTE"] as! NSNumber)")
vigilantes.append(vigilante!)
}
return vigilantes
}
func toArrayVisitantes(dict: [[String:Any?]]) ->[Invitacion]?{
var visitantes: [Invitacion] = []
for data in dict {
let codigo = data["CODIGO"] as! String
let usuario = "\(data["USUARIO"] as! NSNumber)"
let nombre = data["NOMBRE"] as! String
let apellidoPaterno = data["APELLIDO_PATERNO"] as! String
let apellidoMaterno = data["APELLIDO_MATERNO"] as! String
let placas = data["PLACAS"] as? String
let horaEntrada = data["HORA_ENTRADA"] as! String
let horaSalida = data["HORA_ENTRADA"] as! String
let expirada = data["EXPIRADA"] as! String
let email = data["EMAIL"] as! String
let fecha = data["FECHA_VISITA"] as! String
let invitacion = Invitacion(folio: codigo, idUsuario: usuario, nombres: nombre, apellidoPaterno: apellidoPaterno, apellidoMaterno: apellidoMaterno, placas: placas, horaEntrada: horaEntrada, horaSalida: horaSalida, fechaValida: fecha, esExpirada: expirada == "1", email: email)
visitantes.append(invitacion)
}
return visitantes
}
}
|
import XCTest
@testable import XMLRPCSerialization
class XMLRPCDecoderTests: XCTestCase {
func testSimpleDecode() throws {
let rawXML = xmlHeader + """
<methodResponse><params>
<param><value><string>a</string></value></param>
<param><value><i4>5</i4></value></param>
<param><value><struct>
<member><name>c</name><value><string>d</string></value></member>
</struct></value></param>
</params></methodResponse>
"""
let decoder = XMLRPCDecoder()
let obj = try decoder.decode(SimpleTest.self, from: rawXML.xmlData, autoUnwrappingStructures: false)
XCTAssertEqual(obj.a, "a")
XCTAssertEqual(obj.b, 5)
XCTAssertEqual(obj.c["c"], "d")
}
func testWrappingDecode() throws {
let rawXML = xmlHeader + """
<methodResponse><params>
<param><value><struct>
<member><name>a</name><value><string>a</string></value></member>
<member><name>b</name><value><string>b</string></value></member>
<member><name>c</name><value><struct>
<member><name>c</name><value><string>d</string></value></member>
</struct></value></member>
</struct></value></param>
</params></methodResponse>
"""
let decoder = XMLRPCDecoder()
let obj = try decoder.decode(WrappingTest.self, from: rawXML.xmlData, autoUnwrappingStructures: true)
XCTAssertEqual(obj.a, "a")
XCTAssertEqual(obj.b, "b")
XCTAssertEqual(obj.c["c"], "d")
}
func testMethodCallDecode() throws {
let rawXML = xmlHeader + """
<methodCall><methodName>test.method</methodName><params>
<param><value><struct>
<member><name>a</name><value><string>a</string></value></member>
<member><name>b</name><value><string>b</string></value></member>
<member><name>c</name><value><struct>
<member><name>c</name><value><string>d</string></value></member>
</struct></value></member>
</struct></value></param>
</params></methodCall>
"""
let decoder = XMLRPCDecoder()
let obj = try decoder.decode(WrappingTestRequest.self, from: rawXML.xmlData, autoUnwrappingStructures: true)
XCTAssertEqual(obj.a, "a")
XCTAssertEqual(obj.b, "b")
XCTAssertEqual(obj.c["c"], "d")
}
func testTypesDecode() throws {
let rawIntXML = """
<?xml version=\"1.0\" encoding=\"utf-8\"?>
<methodResponse><params><param><value><struct>
<member><name>tiny_s</name><value><i4>-128</i4></value></member>
<member><name>tiny_u</name><value><i4>255</i4></value></member>
<member><name>small_s</name><value><i4>-32768</i4></value></member>
<member><name>small_u</name><value><i4>65535</i4></value></member>
<member><name>large_s</name><value><i4>-2147483648</i4></value></member>
<member><name>large_u</name><value><i4>4294967295</i4></value></member>
<member><name>huge_s</name><value><i4>-9223372036854775808</i4></value></member>
<member><name>huge_u</name><value><i4>18446744073709551615</i4></value></member>
</struct></value></param></params></methodResponse>
"""
let rawFPXML = """
<?xml version=\"1.0\" encoding=\"utf-8\"?>
<methodResponse><params><param><value><struct>
<member><name>small</name><value><double>2.0</double></value>
</member><member><name>large</name><value><double>2.0</double></value></member>
</struct></value></param></params></methodResponse>
"""
let decoder = XMLRPCDecoder()
let intObj = try decoder.decode(IntTypesTest.self, from: rawIntXML.xmlData), intDesired = IntTypesTest.filled()
let fpObj = try decoder.decode(FPTypesTest.self, from: rawFPXML.xmlData), fpDesired = FPTypesTest.filled()
XCTAssertEqual(intObj.tiny_s, intDesired.tiny_s)
XCTAssertEqual(intObj.tiny_u, intDesired.tiny_u)
XCTAssertEqual(intObj.small_s, intDesired.small_s)
XCTAssertEqual(intObj.small_u, intDesired.small_u)
XCTAssertEqual(intObj.large_s, intDesired.large_s)
XCTAssertEqual(intObj.large_u, intDesired.large_u)
XCTAssertEqual(intObj.huge_s, intDesired.huge_s)
XCTAssertEqual(intObj.huge_u, intDesired.huge_u)
XCTAssertEqual(fpObj.small, fpDesired.small, accuracy: 0.000000119209286)
XCTAssertEqual(fpObj.large, fpDesired.large, accuracy: 0.000000000000000222044605)
let rawFailXML = """
<?xml version=\"1.0\" encoding=\"utf-8\"?>
<methodResponse><params><param><value><struct>
<member><name>tiny_s</name><value><i4>-255</i4></value></member>
<member><name>tiny_u</name><value><i4>255</i4></value></member>
<member><name>small_s</name><value><i4>-32768</i4></value></member>
<member><name>small_u</name><value><i4>65535</i4></value></member>
<member><name>large_s</name><value><i4>-2147483648</i4></value></member>
<member><name>large_u</name><value><i4>4294967295</i4></value></member>
<member><name>huge_s</name><value><i4>-9223372036854775808</i4></value></member>
<member><name>huge_u</name><value><i4>18446744073709551615</i4></value></member>
</struct></value></param></params></methodResponse>
"""
XCTAssertThrowsError(_ = try decoder.decode(IntTypesTest.self, from: rawFailXML.xmlData)) {
guard let error = $0 as? Swift.DecodingError else {
XCTFail("expected decoding error, got \($0)")
return
}
guard case .dataCorrupted(let context) = error else {
XCTFail("expected data corrupted error, got \($0)")
return
}
XCTAssertEqual(context.codingPath.count, 2)
XCTAssertEqual(context.codingPath[0].stringValue, _XMLRPCCodingKey(intValue: 0)?.stringValue)
XCTAssertEqual(context.codingPath[1].stringValue, "tiny_s")
XCTAssertEqual(context.debugDescription, "Int8 can't hold -255")
}
}
func testDecodeIntAsUInt() throws {
let rawXML = xmlHeader + """
<methodResponse><params><param><value><i4>1</i4></value></param></params></methodResponse>
"""
let decoder = XMLRPCDecoder()
let value1 = try decoder.decode(Int.self, from: rawXML.xmlData)
XCTAssertEqual(value1, 1)
let value2 = try decoder.decode(UInt.self, from: rawXML.xmlData)
XCTAssertEqual(value2, 1)
let rawFailXML = xmlHeader + """
<methodResponse><params><param><value><i4>-1</i4></value></param></params></methodResponse>
"""
XCTAssertThrowsError(_ = try decoder.decode(UInt.self, from: rawFailXML.xmlData)) {
guard let error = $0 as? Swift.DecodingError else {
XCTFail("expected decoding error, got \($0)")
return
}
guard case .dataCorrupted(let context) = error else {
XCTFail("expected data corrupted error, got \($0)")
return
}
XCTAssertEqual(context.codingPath.count, 1)
}
}
func testDecodeIfPresent() throws {
let rawXML1 = xmlHeader + """
<methodResponse><params>
<param><value><struct>
<member><name>opt1</name><value><i4>5</i4></value></member>
</struct></value></param>
</params></methodResponse>
"""
let rawXML2 = xmlHeader + """
<methodResponse><params>
<param><value><struct>
<member><name>opt1</name><value><i4>5</i4></value></member>
<member><name>opt2</name><value><i4>1</i4></value></member>
</struct></value></param>
</params></methodResponse>
"""
let decoder = XMLRPCDecoder()
let obj1 = try decoder.decode(NilTest.self, from: rawXML1.xmlData)
let obj2 = try decoder.decode(NilTest.self, from: rawXML2.xmlData)
XCTAssertNotNil(obj1.opt1)
XCTAssertEqual(obj1.opt1, 5)
XCTAssertNil(obj1.opt2)
XCTAssertNotNil(obj2.opt1)
XCTAssertEqual(obj2.opt1, 5)
XCTAssertNotNil(obj2.opt2)
XCTAssertEqual(obj2.opt2, 1)
}
func testAllTestsIsComplete() {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
let linuxCount = type(of: self).allTests.count
let darwinCount = type(of: self).defaultTestSuite.testCaseCount
XCTAssertEqual(linuxCount, darwinCount, "\(darwinCount - linuxCount) tests are missing from allTests")
#endif
}
static var allTests = [
("testSimpleDecode", testSimpleDecode),
("testWrappingDecode", testWrappingDecode),
("testMethodCallDecode", testMethodCallDecode),
("testTypesDecode", testTypesDecode),
("testDecodeIntAsUInt", testDecodeIntAsUInt),
("testDecodeIfPresent", testDecodeIfPresent),
("testAllTestsIsComplete", testAllTestsIsComplete),
]
}
|
//
// MypageTableViewCell.swift
// SmartOrder
//
// Created by Jeong on 15/05/2019.
// Copyright © 2019 하영. All rights reserved.
//
import UIKit
class MypageTableViewCell: UITableViewCell {
@IBOutlet weak var cafeImage: UIImageView!
@IBOutlet weak var cafeName: UILabel!
@IBOutlet weak var dayInfo: UILabel!
@IBOutlet weak var totalPrice: 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
}
}
|
//
// ErrorPresentable.swift
// LeoCalc
//
// Created by Anton Pomozov on 25.07.2021.
//
import UIKit
protocol ErrorPresentable: AnyObject {
func presentAlert(title: String, message: String)
}
|
//
// Copyright 2014 ESRI
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// You may freely redistribute and use this sample code, with or
// without modification, provided you include the original copyright
// notice and use restrictions.
//
// See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm
//
import UIKit
import ArcGIS
class SketchLayerViewController: UIViewController {
@IBOutlet weak var mapView:AGSMapView!
@IBOutlet weak var toolbar:UIToolbar!
var sketchToolbar:SketchToolbar!
override func prefersStatusBarHidden() -> Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
//Show magnifier to help with sketching
self.mapView.showMagnifierOnTapAndHold = true
//Tiled basemap layer
let mapUrl = NSURL(string: "http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer")
let tiledLyr = AGSTiledMapServiceLayer(URL: mapUrl)
self.mapView.addMapLayer(tiledLyr, withName:"Tiled Layer")
//Graphics layer to hold all sketches (points, polylines, and polygons)
let graphicsLayer = AGSGraphicsLayer()
self.mapView.addMapLayer(graphicsLayer, withName:"Graphics Layer")
//A composite symbol for the graphics layer's renderer to symbolize the sketches
let composite = AGSCompositeSymbol()
let markerSymbol = AGSSimpleMarkerSymbol()
markerSymbol.style = .Square
markerSymbol.color = UIColor.greenColor()
composite.addSymbol(markerSymbol)
let lineSymbol = AGSSimpleLineSymbol()
lineSymbol.color = UIColor.grayColor()
lineSymbol.width = 4
composite.addSymbol(lineSymbol)
let fillSymbol = AGSSimpleFillSymbol()
fillSymbol.color = UIColor(red: 1, green: 1, blue: 0, alpha: 0.5)
composite.addSymbol(fillSymbol)
let renderer = AGSSimpleRenderer(symbol: composite)
graphicsLayer.renderer = renderer
//Sketch layer
let sketchLayer = AGSSketchGraphicsLayer(geometry: nil)
self.mapView.addMapLayer(sketchLayer, withName:"Sketch layer")
//Helper class to manage the UI toolbar, Sketch Layer, and Graphics Layer
//Basically, where the magic happens
self.sketchToolbar = SketchToolbar(toolbar: self.toolbar, sketchLayer: sketchLayer, mapView: self.mapView, graphicsLayer: graphicsLayer)
//Manhanttan, New York
let sr = AGSSpatialReference(WKID: 102100)
let env = AGSEnvelope(xmin: -8235886.761869, ymin:4977698.714786, xmax:-8235122.391586, ymax:4978797.497068, spatialReference:sr)
self.mapView.zoomToEnvelope(env, animated:true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// ListCellModel.swift
// Minerva
//
// Copyright © 2019 Optimize Fitness, Inc. All rights reserved.
//
import Foundation
import UIKit
public enum ListCellSize {
case autolayout
case explicit(size: CGSize)
case relative
}
// MARK: - ListCellModel
public protocol ListCellModel: CustomStringConvertible {
var reorderable: Bool { get }
var identifier: String { get }
var cellType: ListCollectionViewCell.Type { get }
func isEqual(to model: ListCellModel) -> Bool
func size(constrainedTo containerSize: CGSize) -> ListCellSize
}
extension ListCellModel {
public var description: String {
return "[\(String(describing: type(of: self))) \(identifier)]"
}
}
// MARK: - ListSelectableCellModel
public protocol ListSelectableCellModelWrapper {
func selected(at indexPath: IndexPath)
}
public protocol ListSelectableCellModel: ListSelectableCellModelWrapper {
associatedtype SelectableModelType: ListCellModel
typealias SelectionAction = (_ cellModel: SelectableModelType, _ indexPath: IndexPath) -> Void
var selectionAction: SelectionAction? { get }
}
extension ListSelectableCellModel {
public func selected(at indexPath: IndexPath) {
guard let model = self as? SelectableModelType else {
assertionFailure("Invalid cellModel type \(self)")
return
}
selectionAction?(model, indexPath)
}
}
// MARK: - ListBindableCellModel
public protocol ListBindableCellModelWrapper {
func willBind()
}
public protocol ListBindableCellModel: ListBindableCellModelWrapper {
associatedtype BindableModelType: ListCellModel
typealias BindAction = (_ cellModel: BindableModelType) -> Void
var willBindAction: BindAction? { get }
}
extension ListBindableCellModel {
public func willBind() {
guard let model = self as? BindableModelType else {
assertionFailure("Invalid cellModel type \(self)")
return
}
willBindAction?(model)
}
}
|
//
// StartPointViewController.swift
// Hivecast
//
// Created by Mingming Wang on 6/28/17.
// Copyright © 2017 Mingming Wang. All rights reserved.
//
import UIKit
class StartPointController: UIViewController {
@IBOutlet weak var signupButton: UIButton!
@IBOutlet weak var loginButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.initialize()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func initialize() {
signupButton.layer.cornerRadius = button_cornor_radius
loginButton.layer.cornerRadius = button_cornor_radius
loginButton.layer.borderWidth = button_border_width
loginButton.layer.borderColor = UIColor.colorFromRGB(0xFEC62E).cgColor
}
}
|
//
// MIDIPacketList+SequenceType.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
extension MIDIPacketList: Sequence {
/// Type alis for MIDI Packet List Generator
// public typealias Element = MIDIPacket
public typealias Iterator = MIDIPacketListGenerator
/// Create a generator from the packet list
public func makeIterator() -> Iterator {
return Iterator(packetList: self)
}
// var i = 0
// var ptr = UnsafeMutablePointer<Element>.allocate(capacity: 1)
// ptr.initialize(to: packet)
//
// return AnyIterator {
// guard i < Int(self.numPackets) else {
// ptr.deallocate(capacity: 1)
// return nil
// }
//
// defer {
// ptr = MIDIPacketNext(ptr)
// i += 1
// }
// return ptr.pointee
// }
// }
}
|
//
// CoverageData.swift
// Coverage Dirs
//
// Created by Dušan Tadić on 17.11.19.
// Copyright © 2019 Dušan Tadić. All rights reserved.
//
import Foundation
struct CoverageData: Equatable, Hashable {
var executableLines: Int
var coveredLines: Int
var coverage: Double {
if executableLines == 0 {
return 0
}
return Double(coveredLines) / Double(executableLines)
}
}
|
//
// SharedFile.swift
// RealmTodo
//
// Created by Sang Hyuk Cho on 1/17/17.
// Copyright © 2017 sang. All rights reserved.
//
import Foundation
public let groupID = "group.com.sang.RealmTodo"
public let dbName = "db.realm"
|
//
// NavigationButton.swift
// Wallet
//
// Created by Oleg Leizer on 13.06.2018.
// Copyright © 2018 Oleg Leizer. All rights reserved.
//
import Foundation
import UIKit
class NavigationButton: UIBarButtonItem {
enum NavigationButtonType {
case done
case next
// case edit
// case cancel
case backIcon
case myAssets
}
var selector: Selector?
var sender: AnyObject?
var type: NavigationButtonType = .done {
didSet {
self.update()
}
}
override init() {
super.init()
update()
}
convenience init(type: NavigationButtonType) {
self.init()
self.type = type
update()
}
convenience init(type: NavigationButtonType, target: AnyObject?, action: Selector?) {
self.init(type: type)
self.selector = action
self.sender = target
update()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func update() {
switch type {
case .backIcon:
image = R.image.backIcon()
tintColor = UIColor(componentType: .navigationBarTint)
case .done:
title = "common.actions.done".localized()
tintColor = UIColor(componentType: .navigationBarTint)
case .next:
title = "common.actions.next".localized()
tintColor = UIColor(componentType: .navigationBarTint)
case .myAssets:
title = "newassets.myassets".localized()
tintColor = UIColor(componentType: .navigationItemTint)
}
target = sender
action = selector
}
}
|
//
// Created by milkavian on 5/10/20.
// Copyright (c) 2020 milonmusk. All rights reserved.
//
import Foundation
class GameModel {
var gamesBase: [String : Game] = [:]
init() {
}
func randomString(length: Int) -> String {
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return String((0..<length).map { _ in letters.randomElement()! })
}
func createGame(ownerId: String, gameNumber: String) {
gamesBase["\(gameNumber)"] = Game(id: gameNumber, owner: ownerId, isFinished: false, teams: [], question: 1)
print("LOGIC: GAME \(gameNumber) STARTED")
}
func finishGame(forOwnerId: String ) -> [String] {
guard let game = getActiveGame(ownerId: forOwnerId) else {
return []
}
let gameId = game.id
gamesBase[gameId]!.isFinished = true
var idsToNotify = gamesBase[gameId]!.teams.map { $0.id }
idsToNotify += [gamesBase[gameId]!.owner]
// dump(gamesBase)
print("LOGIC: GAME \(gameId) FINISHED")
return idsToNotify
}
func teamsToNotify(ownerId: String) -> [String] {
guard let game = getActiveGame(ownerId: ownerId) else {
return []
}
let gameId = game.id
let idsToNotify = gamesBase[gameId]!.teams.map { $0.id }
return idsToNotify
}
func getCurrentQuestion(userId: String) -> Int {
guard let game = getActiveGame(ownerId: userId) else {
return 0
}
let gameId = game.id
let currentQuestionNumber = gamesBase[gameId]!.question
return currentQuestionNumber
}
func incrementQuestionNumber(userId: String) {
guard let game = getActiveGame(ownerId: userId) else {
return
}
let gameId = game.id
gamesBase[gameId]!.question += 1
}
func hasActiveGame(userId: String) -> Bool {
gamesBase.map { $0.value.owner }.contains( userId ) && gamesBase.map { $0.value.isFinished }.contains( false )
}
private func getActiveGame(ownerId: String) -> Game? {
gamesBase.values.first { $0.owner == ownerId && $0.isFinished == false }
}
func getTeamGame(teamId: String) -> Game? {
gamesBase.values.first { $0.teams.map { $0.id }.contains(teamId) && $0.isFinished == false }
}
private func isGameActive(gameId: String) -> Bool {
gamesBase[gameId]?.isFinished == false
}
func addTeamToTheGame(gameId: String, teamId: String, teamName: String) -> Team? {
guard let currentGame = gamesBase[gameId], isGameActive(gameId: gameId) else {
return nil
}
let team = Team(id: teamId, name: teamName)
gamesBase[gameId]!.teams += [team]
print("ZZZZ gameBase: \(gamesBase), currentGame: \(currentGame)")
return team
}
func getOwnerById(gameId: String) -> String? {
guard let game = gamesBase[gameId] else {
return nil
}
return game.owner
}
}
|
//
// DataCache.swift
// FBAnnotationClusteringSwift
//
// Created by 毛毛 on 2017/4/24.
// Copyright © 2017年 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
class DataCache {
private static var mInstance: DataCache?
static func sharedInstance() -> DataCache {
if mInstance == nil {
mInstance = DataCache()
}
return mInstance!
}
private init(){
}
private var mSpace:[Space] = [Space]()
func saveImage(aSpace: Space,aFilename: String){
mSpace.append(aSpace)
}
}
|
//
// Tile.swift
// RWCookieCrunch
//
// Created by Skyler Svendsen on 11/21/17.
// Copyright © 2017 Skyler Svendsen. All rights reserved.
//
class Tile {
}
|
//
// tweetDetailCell_middle.swift
// twitter_alamofire_demo
//
// Created by Sandra Flores on 3/10/18.
// Copyright © 2018 Charles Hieger. All rights reserved.
//
import UIKit
class tweetDetailCell_middle: UITableViewCell {
@IBOutlet weak var retweetsCount: UILabel!
@IBOutlet weak var retweetsLabel: UILabel!
@IBOutlet weak var favoritesCount: UILabel!
@IBOutlet weak var favoritesLabel: UILabel!
var tweet: Tweet! {
didSet{
retweetsCount.text = formatCounter(count: tweet.retweetCount)
favoritesCount.text = formatCounter(count: tweet.favoriteCount)
}
}
func formatCounter(count: Int) -> String{
var formattedCount = ""
// Billion, just in case
if(count >= 1000000000){
formattedCount = String(format: "%.1fb", Double(count) / 1000000000.0)
}
else if(count >= 1000000){
formattedCount = String(format: "%.1fm", Double(count) / 1000000.0)
}
else if(count >= 10000){
formattedCount = String(format: "%.1fk", Double(count) / 1000.0)
}
else{
formattedCount = "\(count)"
}
return formattedCount
}
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
}
}
|
//
// ViewController.swift
// ShimmerViews
//
// Created by Steve Rustom on 4/17/19.
// Copyright © 2019 Steve Rustom. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
let square1 = CGRect(x: 15, y: 0, width: 44, height: 43)
let square2 = CGRect(x: 170, y: 0, width: 44, height: 43)
let square3 = CGRect(x: 330, y: 0, width: 44, height: 43)
var count = 2
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
configureTableView()
}
//MARK: - TableView DataSource Methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "customTableViewCell", for: indexPath) as! CustomTableViewCell
cell.one = RayShimmerView(frame: square1)
cell.one.awakeFromNib()
cell.addSubview(cell.one)
cell.two = RayShimmerView(frame: square2)
cell.two.awakeFromNib()
cell.addSubview(cell.two)
cell.three = RayShimmerView(frame: square3)
cell.three.awakeFromNib()
cell.addSubview(cell.three)
return cell
} else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "customTableViewCellTwo", for: indexPath) as! CustomTableViewCellTwo
cell.label.adjustsFontSizeToFitWidth = true
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "customTableViewCellThree", for: indexPath) as! CustomTableViewCellThree
let cell2 = tableView.cellForRow(at: IndexPath(row: 1, section: 0)) as! CustomTableViewCellTwo
var lowestBottomView: UIView? = nil
for subview in cell2.contentView.subviews {
if let label = subview as? UILabel {
let textSize = CGSize(width: CGFloat(label.frame.size.width), height: CGFloat(MAXFLOAT))
let rHeight: Int = lroundf(Float(label.sizeThatFits(textSize).height))
let charSize: Int = lroundf(Float(label.font.pointSize))
let numberOfLines = rHeight / charSize
var y = subview.frame.origin.y
for _ in 1...numberOfLines {
let tempView: UIView = UIView(frame: CGRect(x: subview.frame.origin.x, y: y, width: CGFloat(subview.frame.size.width), height: CGFloat(charSize) * 0.7))
tempView.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addSubview(tempView)
tempView.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor, constant: subview.frame.origin.x).isActive = true
tempView.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: y).isActive = true
if lowestBottomView == nil || ((tempView.frame.origin.y + tempView.frame.size.height) > ((lowestBottomView?.frame.origin.y)! + (lowestBottomView?.frame.size.height)!)) {
lowestBottomView = tempView
}
tempView.widthAnchor.constraint(equalToConstant: subview.frame.size.width).isActive = true
tempView.heightAnchor.constraint(equalToConstant: CGFloat(charSize) * 0.7).isActive = true
y += CGFloat(charSize)
}
} else {
let tempView = UIView(frame: CGRect(x: subview.frame.origin.x, y: subview.frame.origin.y, width: subview.frame.size.width, height: subview.frame.size.height))
tempView.translatesAutoresizingMaskIntoConstraints = false
cell.contentView.addSubview(tempView)
tempView.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor, constant: subview.frame.origin.x).isActive = true
tempView.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: subview.frame.origin.y).isActive = true
if lowestBottomView == nil || ((tempView.frame.origin.y + tempView.frame.size.height) > ((lowestBottomView?.frame.origin.y)! + (lowestBottomView?.frame.size.height)!)) {
lowestBottomView = tempView
}
tempView.widthAnchor.constraint(equalToConstant: subview.frame.size.width).isActive = true
tempView.heightAnchor.constraint(equalToConstant: subview.frame.size.height).isActive = true
}
}
if let lowestBottomView = lowestBottomView {
lowestBottomView.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: -10).isActive = true
}
if cell.contentView.subviews.count > 1 {
cell.startShimmering(color: UIColor.white)
for subview in cell.contentView.subviews {
subview.startShimmering()
subview.stopShimmering()
}
} else {
for subview in cell.contentView.subviews {
subview.startShimmering()
}
}
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row == 1 {
count += 1
let indexPathOfLastRow = NSIndexPath.init(row: count - 1, section: 0)
tableView.insertRows(at: [indexPathOfLastRow as IndexPath], with: .bottom)
}
}
func configureTableView() {
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 250.0
}
}
|
//
// AlbumListViewModel.swift
// AlbumRSS
//
// Created by Gavin Li on 8/11/20.
// Copyright © 2020 Gavin Li. All rights reserved.
//
import Foundation
class AlbumListViewModel: AlbumListViewModelProtocol {
private let netWorker: NetworkerProtocol
private let imageDownloader: ImageDownloader
private let urlConstructor: UrlConstructorProtocol
private var listUpdateHandler: (() -> Void)?
private var listUpdateFailureHandler: ((Error) -> Void)?
private var albums: [AlbumViewModel] = [] {
didSet { listUpdateHandler?() }
}
init(netWorker: NetworkerProtocol = Networker(),
imageDownloader: ImageDownloader = ImageDownloader(),
urlConstructor: UrlConstructorProtocol = RSSUrlConstructor()) {
self.netWorker = netWorker
self.imageDownloader = imageDownloader
self.urlConstructor = urlConstructor
}
@discardableResult
func bind(onSuccess listUpdateHandler: @escaping () -> Void) -> Self {
self.listUpdateHandler = listUpdateHandler
return self
}
@discardableResult
func bind(onFailure listUpdateFailureHandler: @escaping (Error) -> Void) -> Self {
self.listUpdateFailureHandler = listUpdateFailureHandler
return self
}
func unbind() {
listUpdateHandler = nil
listUpdateFailureHandler = nil
}
func fetchData() {
netWorker.loadJSONData(type: Results.self, url: urlConstructor.rssFeedUrlString(), params: nil) {
result in
switch result {
case let .success(resultsContainer):
self.albums = self.albumViewModels(from: resultsContainer.results)
case let .failure(error):
self.listUpdateFailureHandler?(error)
}
}
}
private func albumViewModels(from albums: [Album]) -> [AlbumViewModel] {
albums.map {
AlbumViewModel.init(album: $0, imageDownloader: imageDownloader, urlConstructor: urlConstructor)
}
}
}
extension AlbumListViewModel {
var sectionCount: Int {
1
}
func numOfAlbums(in section: Int) -> Int {
albums.count
}
func albumViewModel(for indexPath: IndexPath) -> AlbumViewModel {
albums[indexPath.row]
}
func albumName(for indexPath: IndexPath) -> String {
albums[indexPath.row].name
}
func albumArtist(for indexPath: IndexPath) -> String {
albums[indexPath.row].artist
}
func image(for indexPath: IndexPath, completion: @escaping (Data?) -> Void) {
albums[indexPath.row].image(completion: completion)
}
}
extension AlbumListViewModel: AlbumListDelegateProtocol {
func didSelectAlbum(_ viewController: AlbumListViewController, at indexPath: IndexPath) {
let albumDetailViewController = AlbumDetailViewController.init(viewModel: albumViewModel(for: indexPath))
viewController.navigationController?.pushViewController(albumDetailViewController, animated: true)
}
}
|
// Copyright 2017, Postnummeruppror.nu
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import CoreData
class ViewController: UIViewController {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
struct defaultsKeys {
static let deviceUUID = "0"
}
var loadedUser = false
struct SaveUserResult: Decodable {
let success: Bool
}
struct User: Codable {
var identity: String
var acceptingCcZero: Bool
var firstName: String
var lastName: String
}
override func viewDidLoad() {
super.viewDidLoad()
// Check if user data already exists - if so load it into the fields
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
if result.count > 0 {
let user = result.first as! NSManagedObject
emailAddress.text = user.value(forKey: "email") as? String
firstName.text = user.value(forKey: "firstName") as? String
lastName.text = user.value(forKey: "lastName") as? String
// Disable accept toggle
acceptTerms.setOn(true, animated: true)
acceptTerms.isUserInteractionEnabled = false
saveBtn.isEnabled = true
self.loadedUser = true
}
} catch {
print("Failed getting stored user data")
}
// Enable tap outside to dismiss keyboard
let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:)))
tap.cancelsTouchesInView = false
self.view.addGestureRecognizer(tap)
}
@IBAction func accept(_ sender: Any) {
saveBtn.isEnabled = !saveBtn.isEnabled
}
@IBOutlet weak var saveBtn: UIButton!
@IBOutlet weak var acceptTerms: UISwitch!
@IBOutlet weak var emailAddress: UITextField!
@IBOutlet weak var firstName: UITextField!
func moveOn() {
print("Moving on")
navigationController?.popViewController(animated: true)
}
func saveUserData() {
print("Saving user data")
let context = appDelegate.persistentContainer.viewContext
// Delete all existing user data
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
let request = NSBatchDeleteRequest(fetchRequest: fetch)
do {
try context.execute(request)
} catch {
print("Error in deleting previous User data")
}
// Create new user object
let entity = NSEntityDescription.entity(forEntityName: "User", in: context)
let newUser = NSManagedObject(entity: entity!, insertInto: context)
newUser.setValue(self.firstName.text, forKey: "firstName")
newUser.setValue(self.lastName.text, forKey: "lastName")
newUser.setValue(self.emailAddress.text, forKey: "email")
newUser.setValue(Utils.getUUID(), forKey: "identity")
newUser.setValue(Date(), forKey: "updatedAt")
do {
try context.save()
DispatchQueue.main.async(){
self.moveOn()
}
} catch {
print("Failed saving user")
}
}
@IBAction func saveUser(_ sender: Any) {
let identifier = Utils.getUUID()
// Prepare data for account creation
let json: [String: Any] = ["identity": identifier,
"acceptingCcZero": true,
"firstName": firstName.text!,
"lastName": lastName.text!]
//let jsonData = try? JSONSerialization.data(withJSONObject: json)
let postURL = URL(string: "https://insamling.postnummeruppror.nu/api/0.0.5/account/set")!
var postRequest = URLRequest(url: postURL, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 60.0)
postRequest.httpMethod = "POST"
postRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
postRequest.setValue("application/json", forHTTPHeaderField: "Accept")
do {
let jsonParams = try JSONSerialization.data(withJSONObject: json, options: [])
postRequest.httpBody = jsonParams
} catch { print("Error: unable to add parameters to POST request.")}
URLSession.shared.dataTask(with: postRequest, completionHandler: { (data, response, error) -> Void in
if error != nil {
print("POST Request: Communication error: \(error!)")
DispatchQueue.main.async(execute: {
Utils.showAlert(view: self, title: "Något gick fel", message: "Kunde inte spara dina användaruppgifter. Försök senare.", buttontext: "OK")
})
}
if data != nil {
do {
if let safeData = data{
print("Response: \(String(describing: String(data:safeData, encoding:.utf8)))")
}
let resultObject = try JSONSerialization.jsonObject(with: data!, options: [])
DispatchQueue.main.async(execute: {
print("Results from POST:\n\(resultObject)")
// Validate that account was created
let saveResult = try? JSONDecoder().decode(SaveUserResult.self, from: data!)
if (saveResult?.success)! {
self.saveUserData()
} else {
Utils.showAlert(view: self, title: "Något gick fel", message: "Kunde inte spara dina användaruppgifter. Försök senare.", buttontext: "OK")
}
})
} catch {
DispatchQueue.main.async(execute: {
Utils.showAlert(view: self, title: "Fel vid skapa konto", message: "Kunde inte spara dina användaruppgifter. Försök senare.", buttontext: "OK")
print("Unable to parse JSON response")
})
}
} else {
DispatchQueue.main.async(execute: {
print("Received empty response for account creation.")
})
}
}).resume()
}
@IBOutlet weak var lastName: UITextField!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
//
// StopwatchViewController.swift
// Stopwatch
//
// Created by Mac on 22/06/2019.
// Copyright © 2019 Ilya Razumov. All rights reserved.
//
import UIKit
import TimerKit
class StopwatchViewController: UIViewController {
enum State {
case stop
case start
}
// MARK: Outlets
@IBOutlet weak var countingLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var mainFeaturesButton: StopwatchButton!
@IBOutlet weak var secondareFeaturesButton: StopwatchButton!
// MARK: Private properties
private let shedule = ScheduleTimer()
private var state: State = .stop {
didSet {
update(state)
}
}
private var times: [String] = [] {
didSet {
StorageHelper.save(times, forKey: .times)
tableView.reloadData()
}
}
// MARK: Life circle
override func viewDidLoad() {
super.viewDidLoad()
registerCell()
configure()
}
// MARK: Action funcs
@IBAction func secondaryFeatureTapped(_ sender: StopwatchButton) {
switch state {
case .start:
saveTime(countingLabel.text ?? "")
case .stop:
shedule.reset()
times.removeAll()
countingLabel.text = shedule.viewTime
}
}
@IBAction func mainFeaturesTapped(_ sender: StopwatchButton) {
switch state {
case .start:
state = .stop
case .stop:
state = .start
}
}
// MARK: Private funcs
private func configure() {
state = .stop
countingLabel.text = shedule.viewTime
fetchTimes()
}
private func update(_ state: State) {
switch state {
case .start:
mainFeaturesButton.type = .stop
secondareFeaturesButton.type = .round
secondareFeaturesButton.isEnabled = true
shedule.start()
case .stop:
mainFeaturesButton.type = .start
secondareFeaturesButton.type = .reset
secondareFeaturesButton.isEnabled = true
shedule.stop()
}
addCallBack()
}
private func registerCell() {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.dataSource = self
}
private func addCallBack() {
shedule.sendString = { [weak self] string in
self?.countingLabel.text = self?.shedule.viewTime
}
}
private func fetchTimes() {
let times: [String] = StorageHelper.loadObjectForKey(.times) ?? []
self.times = times
}
private func saveTime(_ time: String) {
times.append(time)
}
}
extension StopwatchViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return times.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = times[indexPath.row]
cell.backgroundColor = .black
cell.textLabel?.textColor = #colorLiteral(red: 1, green: 0.5764705882, blue: 0, alpha: 1)
return cell
}
}
|
//
// main.swift
// helloWorld
//
// Created by 山口智生 on 2016/05/19.
// Copyright © 2016年 ha1f. All rights reserved.
//
import Foundation
<<<<<<< HEAD
<<<<<<< HEAD
class Benchmark {
private var startTime: NSDate
private var key: String
init(key: String) {
self.startTime = NSDate()
self.key = key
}
// 処理終了
private func finish() {
let elapsed = NSDate().timeIntervalSinceDate(self.startTime)
let formatedElapsed = String(format: "%.3f", elapsed)
print("Benchmark: \(key), Elasped time: \(formatedElapsed)(s)")
}
// 処理をブロックで受け取る
class func measure(key: String, block: () -> ()) {
let benchmark = Benchmark(key: key)
block()
benchmark.finish()
}
}
func isPrime(n: Int) -> Bool {
guard n >= 2 else {
return false
}
if n == 2 {
return true
}
let m = max(Int(sqrt(Double(n))), 2)
for i in 2...m {
if n%i == 0 {
return false
}
}
return true
}
func e1() {
var nums = (2...10000).map{$0}
var primes = [Int]()
while let p = nums.first {
primes.append(p)
nums = nums.filter {$0 % p != 0}
}
print(primes)
}
func e2() {
let N = 500000
var isPrime = [Bool](count: N-1, repeatedValue: true)
for i in (2...Int(sqrt(Double(N)))) {
guard isPrime[i-2] else {
continue
}
for j in 2...Int(N/i) {
isPrime[i*j-2] = false
}
}
print(isPrime.enumerate().filter{(n, b) in b}.map{(n, b) in n+2})
}
print("Hello, Swift World!")
//Benchmark.measure("prime", block: e2)
Benchmark.measure("prime", block: {showPrime()})
print("finish")
=======
print("Hello, World!")
>>>>>>> 7b9a3dc... Initial Commit
=======
class Benchmark {
private var startTime: NSDate
private var key: String
init(key: String) {
self.startTime = NSDate()
self.key = key
}
// 処理終了
private func finish() {
let elapsed = NSDate().timeIntervalSinceDate(self.startTime)
let formatedElapsed = String(format: "%.3f", elapsed)
print("Benchmark: \(key), Elasped time: \(formatedElapsed)(s)")
}
// 処理をブロックで受け取る
class func measure(key: String, block: () -> ()) {
let benchmark = Benchmark(key: key)
block()
benchmark.finish()
}
}
func isPrime(n: Int) -> Bool {
guard n >= 2 else {
return false
}
if n == 2 {
return true
}
let m = max(Int(sqrt(Double(n))), 2)
for i in 2...m {
if n%i == 0 {
return false
}
}
return true
}
func e1() {
var nums = (2...10000).map{$0}
var primes = [Int]()
while let p = nums.first {
primes.append(p)
nums = nums.filter {$0 % p != 0}
}
print(primes)
}
func e2() {
let N = 500000
var isPrime = [Bool](count: N-1, repeatedValue: true)
for i in (2...Int(sqrt(Double(N)))) {
guard isPrime[i-2] else {
continue
}
for j in 2...Int(N/i) {
isPrime[i*j-2] = false
}
}
print(isPrime.enumerate().filter{(n, b) in b}.map{(n, b) in n+2})
}
print("Hello, Swift World!")
//Benchmark.measure("prime", block: e2)
Benchmark.measure("prime", block: {showPrime()})
print("finish")
>>>>>>> 6b2c3e7... いろいろ
|
//
// ITunesSearchResult.swift
// iOSArchitecturesDemo
//
// Created by Olga Martyanova on 19.02.2018.
// Copyright © 2018 olgamart. All rights reserved.
//
import Foundation
struct ITunesSearchResult<Element: Codable>: Codable {
let resultCount: Int
let results: [Element]
}
|
//
// MainNavigationController.swift
// toss_MVC
//
// Created by 장창순 on 06/07/2020.
// Copyright © 2020 AnAppPerTwoWeeks. All rights reserved.
//
import UIKit
class MainNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.tintColor = UIColor(red: 38/255, green: 48/255, blue: 63/255, alpha: 1.0)
navigationBar.backgroundColor = .clear
let attributes = [NSAttributedString.Key.font: UIFont(name: "HelveticaNeue-Medium", size: 17)!]
UINavigationBar.appearance().titleTextAttributes = attributes
}
}
|
//
// FirstViewController.swift
// AnimatableStatusBarViewController
//
// Created by Wirawit Rueopas on 21/4/18.
// Copyright © 2018 Wirawit Rueopas. All rights reserved.
//
import UIKit
class FirstViewController: AnimatableStatusBarViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// *** IMPORTANT
// ----------------
// You must inform the next view controller (SecondViewController)
// via `animatedStatusBarPreviouslyHideStatusBar`
// whether the previous view controller (FirstViewController)
// shows or hide the status bar.
let vc = segue.destination as! SecondViewController
vc.animatedStatusBarPreviouslyHideStatusBar = true
}
// Hide status bar
override var animatedStatusBarPrefersStatusBarHidden: Bool {
return true
}
// IMPORTANT: This might be a little unintuitive, but `.slide` here is used when this view controller appears (viewWillAppear). So if you want to use slide animation for the status bar when showing the next view controller (`SecondViewController`), you need to set `.slide` in the `SecondViewController`, not `FirstViewController`.
// In our case, .slide will take effect when we dismiss `SecondViewController`.
//
// In a nutshell, just remember that `preferredStatusBarUpdateAnimation` is tied to each view controller and it will be performed **only** in `viewWillAppear`.
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .slide
}
}
|
//
// Errors.swift
// Rick And Morty's Multiverse
//
// Created by Roman Rakhlin on 15.09.2021.
//
import Foundation
enum Errors: String, Error {
case invalidUsername = "This username created an invalid request. Please try again"
case unableToComplete = "Unable to complete your request"
case invalidResponse = "Invalid Response from the server"
case invalidData = "Data invalid from server"
case unableToFavorito = "There was an error in favorites"
case existsInFavorite = "The data already exist in favorites"
}
|
import Foundation
enum AssetsValidatorError: LocalizedError {
case badName(name: String)
case countMismatch(light: Int, dark: Int)
case foundDuplicate(assetName: String)
case lightAssetsNotFoundInDarkPalette(assets: [String])
case darkAssetsNotFoundInLightPalette(assets: [String])
case descriptionMismatch(assetName: String, light: String, dark: String)
var errorDescription: String? {
switch self {
case .badName(let name):
return "Bad asset name «\(name)»"
case .countMismatch(let light, let dark):
return "The number of assets doesn’t match. Light theme contains \(light), and dark \(dark)."
case .lightAssetsNotFoundInDarkPalette(let lights):
return "Dark theme doesn’t contains following assets: \(lights.joined(separator: ", ")), which exists in light theme. Add these assets to dark theme and publish to the Team Library."
case .darkAssetsNotFoundInLightPalette(let darks):
return "Light theme doesn’t contains following assets: \(darks.joined(separator: ", ")), which exists in dark theme. Add these assets to light theme and publish to the Team Library."
case .foundDuplicate(let assetName):
return "Found duplicates of asset with name \(assetName). Remove duplicates."
case .descriptionMismatch(let assetName, let light, let dark):
return "Asset with name \(assetName) have different description. In dark theme «\(dark)», in light theme «\(light)»"
}
}
}
|
//
// TodayView+Extensions.swift
// MyLeaderboard
//
// Created by Joseph Roque on 2020-03-15.
// Copyright © 2020 Joseph Roque. All rights reserved.
//
import myLeaderboardApi
typealias TodayViewRecord = MyLeaderboardApi.TodayViewRecordFragment
typealias TodayViewGame = MyLeaderboardApi.TodayViewGameFragment
|
//
// StringHelper.swift
// UnsplashedGallery
//
// Created by Jasjeev on 8/11/21.
//
import Foundation
extension StringProtocol {
var firstUppercased: String { return prefix(1).uppercased() + dropFirst() }
var firstCapitalized: String { return prefix(1).capitalized + dropFirst() }
}
|
//
// RxRepositoryProtocol.swift
// RealmPlatform
//
// Created by 이광용 on 19/05/2019.
// Copyright © 2019 GwangYongLee. All rights reserved.
//
import Foundation
import RxSwift
protocol RxRepositoryProtocol {
associatedtype Item
func save(_ item: Item,
update: Bool) -> Observable<Void>
func items() -> Observable<[Item]>
func item<PrimaryKey>(with primaryKey: PrimaryKey) -> Observable<Item?>
func delete(_ item: Item) -> Observable<Void>
func delete(contentsOf items: [Item]) -> Observable<Void>
}
|
//
// CustomUIButton.swift
// Hero Guide
//
// Created by Thiago Ferrão on 09/07/18.
// Copyright © 2018 Thiago Ferrão. All rights reserved.
//
import UIKit
class CustomUIButton: UIButton {
override var isHighlighted: Bool {
didSet {
guard isHighlighted else {
layer.borderColor = borderColor?.withAlphaComponent(Constants.ALPHA.ENABLE).cgColor
return
}
layer.borderColor = borderColor?.withAlphaComponent(Constants.ALPHA.DISABLE).cgColor
}
}
}
|
//
// ContinentsData.swift
// countries
//
// Created by Aileen Pierce
//
import Foundation
struct ContinentsData : Codable {
var continent : String
var countries : [String]
}
|
/*-
* Copyright (c) 2020 Sygic
*
* 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
* 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.
*
*/
// swiftlint:disable file_length trailing_closure
//
// ViewController.swift
// Covid
//
// Created by Boris Kolozsi on 09/03/2020.
//
import UIKit
import CoreLocation
import CoreBluetooth
import SwiftyUserDefaults
import FirebaseRemoteConfig
import AVFoundation
extension MainViewController: HasStoryBoardIdentifier {
static let storyboardIdentifier = "MainViewController"
}
final class MainViewController: ViewController, NotificationCenterObserver {
@IBOutlet private var protectView: UIView!
@IBOutlet private var symptomesView: UIView!
@IBOutlet private var emergencyButton: UIButton!
@IBOutlet private var actionButton: UIButton!
@IBOutlet private var quarantineView: UIView!
@IBOutlet private var statsView: UIView!
private let networkService = CovidService()
private var observer: DefaultsDisposable?
private var quarantineObserver: DefaultsDisposable?
private var faceCaptureCoordinator: FaceCaptureCoordinator?
var notificationTokens: [NotificationToken] = []
deinit {
unobserveNotifications()
}
override func viewDidLoad() {
super.viewDidLoad()
observeFaceIDRegistrationNotification()
if Defaults.didRunApp {
registerForPushNotifications()
}
if Defaults.profileId == nil {
registerUser()
}
tabBarController?.view.backgroundColor = view.backgroundColor
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.isNavigationBarHidden = true
updateView()
showWelcomeScreenIfNeeded()
quarantineObserver = Defaults.observe(\.quarantineEnd) { [weak self] _ in
DispatchQueue.main.async {
self?.updateView()
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
quarantineObserver?.dispose()
navigationController?.isNavigationBarHidden = false
}
override func loadView() {
super.loadView()
emergencyButton.isHidden = false
protectView.layer.cornerRadius = 20
protectView.layer.masksToBounds = true
symptomesView.layer.cornerRadius = 20
symptomesView.layer.masksToBounds = true
protectView.layer.cornerRadius = 20
protectView.layer.masksToBounds = true
emergencyButton.layer.cornerRadius = 20
emergencyButton.layer.masksToBounds = true
actionButton.layer.cornerRadius = 20
actionButton.layer.masksToBounds = true
actionButton.titleLabel?.textAlignment = .center
}
func showQuarantineRegistration() {
guard let importantViewController = UIStoryboard.controller(ofType: SelectAddressInfoViewController.self) else { return }
importantViewController.onContinue = {
importantViewController.performSegue(withIdentifier: "showCountryCode", sender: nil)
}
navigationController?.pushViewController(importantViewController, animated: true)
}
// MARK: Welcome screen
private func showWelcomeScreenIfNeeded() {
guard !Defaults.didRunApp else { return }
let welcomeViewController = UIStoryboard.controller(ofType: WelcomeViewController.self)
welcomeViewController?.modalPresentationStyle = .fullScreen
welcomeViewController?.onAgree = {
Defaults.didRunApp = true
welcomeViewController?.dismiss(animated: true) { [weak self] in
self?.registerForPushNotifications()
}
}
present(welcomeViewController!, animated: false, completion: nil)
}
// MARK: Permissions
private func registerForPushNotifications() {
let current = UNUserNotificationCenter.current()
current.getNotificationSettings { (settings) in
if settings.authorizationStatus == .notDetermined {
current.requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] _, _ in
DispatchQueue.main.async {
if !Defaults.didShowForeignAlert {
self?.performSegue(.foreignAlert)
}
}
}
}
}
UIApplication.shared.registerForRemoteNotifications()
}
@IBAction private func didTapQuarantine(_ sender: Any) {
if Defaults.quarantineActive {
startRandomCheck(showInfo: true)
} else {
showQuarantineRegistration()
}
}
@IBAction private func emergencyDidTap(_ sender: Any) {
let emergencyNumber = Firebase.remoteDictionaryValue(for: .hotlines)["SK"] as? String ?? ""
guard let number = URL(string: "tel://\(emergencyNumber)") else { return }
UIApplication.shared.open(number)
}
}
// MARK: - Private
extension MainViewController {
private func updateView() {
let showQuarantine = Defaults.quarantineActive || (Defaults.covidPass != nil && (Defaults.quarantineStart ?? Date(timeIntervalSinceNow: 10)) > Date() )
quarantineView?.isHidden = !showQuarantine
statsView?.isHidden = showQuarantine
actionButton?.isHidden = Defaults.covidPass != nil && (Defaults.quarantineStart == nil || (Defaults.quarantineStart ?? Date()) >= Date())
if Defaults.quarantineActive == false {
actionButton.setTitle(LocalizedString(forKey: "quarantine.register.title"), for: .normal)
actionButton.backgroundColor = UIColor(red: 80.0 / 255.0, green: 88.0 / 255.0, blue: 249.0 / 255.0, alpha: 1.0)
} else if Defaults.quarantineStart != nil {
actionButton.setTitle(LocalizedString(forKey: "quarantine.check.title"), for: .normal)
actionButton.backgroundColor = UIColor(red: 241.0 / 255.0, green: 106.0 / 255.0, blue: 195.0 / 255.0, alpha: 1.0)
}
}
private func showRegistrationFailureAlert(_ completion: @escaping () -> Void) {
Alert.show(title: LocalizedString(forKey: "error.title"),
message: LocalizedString(forKey: "error.registration.failed"),
defaultTitle: LocalizedString(forKey: "button.retry"),
defaultAction: { _ in
completion()
})
}
private func registerUser() {
let action = { [weak self] in
let data = RegisterProfileRequestData()
self?.networkService.registerUserProfile(profileRequestData: data) { [weak self] (result) in
switch result {
case .success(let profile):
Defaults.profileId = profile.profileId
case .failure:
self?.showRegistrationFailureAlert {
self?.registerUser()
}
}
}
}
if Defaults.FCMToken == nil {
observer = Defaults.observe(\.FCMToken) { _ in
DispatchQueue.main.async {
action()
}
}
} else {
action()
}
}
}
extension MainViewController {
// MARK: FaceID Flow
private func observeFaceIDRegistrationNotification() {
observeNotification(withName: .startFaceIDRegistration) { [weak self] (notification) in
let navigationController = StartFaceIDRegistrationNotification.navigationController(from: notification)
let completion = StartFaceIDRegistrationNotification.completion(from: notification)
if let navigationController = navigationController, let completion = completion {
self?.showFaceRegistration(in: navigationController, completion: completion)
}
}
observeNotification(withName: .startRandomCheck) { [weak self] _ in
self?.startRandomCheck()
}
}
private func showFaceRegistration(in navigationController: UINavigationController, completion: @escaping () -> Void) {
faceCaptureCoordinator = FaceCaptureCoordinator(useCase: .registerFace)
faceCaptureCoordinator?.onAlert = { alertControler in
navigationController.present(alertControler, animated: true, completion: nil)
}
faceCaptureCoordinator?.onCoordinatorResolution = { [weak self] result in
guard let self = self else { return }
self.finishProfileRegistration { [weak self] in
switch result {
case .success:
self?.faceCaptureCoordinator = nil
self?.navigationController?.popToRootViewController(animated: true)
completion()
case .failure:
break
}
}
}
let cameraAccess = AVCaptureDevice.authorizationStatus(for: .video) == .authorized
let authorizationStatus = CLLocationManager.authorizationStatus()
let isAuthorized = authorizationStatus == .authorizedAlways || authorizationStatus == .authorizedWhenInUse
let locationAccess = CLLocationManager.locationServicesEnabled() && isAuthorized
if cameraAccess && locationAccess {
faceCaptureCoordinator?.showOnboarding(in: navigationController)
} else {
guard let importantViewController = UIStoryboard.controller(ofType: SelectAddressInfoViewController.self) else { return }
importantViewController.onContinue = {
self.faceCaptureCoordinator?.showOnboarding(in: navigationController)
}
navigationController.pushViewController(importantViewController, animated: true)
}
}
func showAlertWhenNonceFails(completion: @escaping () -> Void) {
Alert.show(title: LocalizedString(forKey: "error.title"),
message: LocalizedString(forKey: "error.registration.failed.retry"),
cancelAction: { (_) in
DispatchQueue.main.async {
completion()
}
})
}
private func finishProfileRegistration(_ completion: @escaping () -> Void) {
observer?.dispose()
observer = Defaults.observe(\.noncePush) { [weak self] update in
DispatchQueue.main.async {
guard let nonceValue = update.newValue, let nonce = nonceValue else {
completion()
return
}
self?.networkService.updateUserProfileNonce(profileRequestData: BasicWithNonceRequestData(nonce: nonce)) { (result) in
switch result {
case .success:
DispatchQueue.main.async {
completion()
}
return
case .failure:
self?.showAlertWhenNonceFails {
completion()
}
}
}
}
}
networkService.requestNoncePush(nonceRequestData: BasicRequestData()) { [weak self] (result) in
switch result {
case .success: break // wait for silent push
case .failure:
self?.showAlertWhenNonceFails {
completion()
}
}
}
}
private func showFaceVerification(in navigationController: UINavigationController) {
faceCaptureCoordinator = FaceCaptureCoordinator(useCase: .verifyFace)
let viewController = faceCaptureCoordinator!.startFaceCapture()
faceCaptureCoordinator?.navigationController = navigationController
faceCaptureCoordinator?.onAlert = { alertControler in
navigationController.present(alertControler, animated: true, completion: nil)
}
faceCaptureCoordinator?.onCoordinatorResolution = { [weak self] faceResult in
switch faceResult {
case .success(let success):
if success {
self?.resolveCheck()
}
case .failure:
self?.onError()
}
}
navigationController.pushViewController(viewController, animated: true)
}
func onError() {
Alert.show(title: LocalizedString(forKey: "error.title"),
message: LocalizedString(forKey: "error.quarantine.check"),
cancelAction: { (_) in
DispatchQueue.main.async {
self.dismiss(animated: true) {
self.faceCaptureCoordinator = nil
}
}
})
}
func startRandomCheck(showInfo: Bool = false) {
guard FaceIDStorage().referenceFaceData != nil, Defaults.quarantineActive else { return }
actionButton.isEnabled = false
networkService.requestPresenceCheckNeeded(presenceNeededRequestData: BasicRequestData()) { [weak self] (result) in
switch result {
case .success(let data):
DispatchQueue.main.async {
if data.isPresenceCheckPending {
guard let viewController = UIStoryboard.controller(ofType: SelectAddressInfoViewController.self) else {
assertionFailure("this controller should exist")
return
}
let navigationController = UINavigationController(rootViewController: viewController)
navigationController.modalPresentationStyle = .fullScreen
viewController.onContinue = { [weak self] in
self?.showFaceVerification(in: navigationController)
}
self?.present(navigationController, animated: true, completion: nil)
} else if showInfo {
guard let viewController = UIStoryboard.controller(ofType: NoRandomCheckViewController.self) else {
assertionFailure("this controller should exist")
return
}
let navigationController = UINavigationController(rootViewController: viewController)
navigationController.modalPresentationStyle = .fullScreen
self?.present(navigationController, animated: true, completion: nil)
}
self?.actionButton.isEnabled = true
}
return
case .failure: break
}
DispatchQueue.main.async {
self?.actionButton.isEnabled = true
}
}
}
}
extension MainViewController {
func resolveCheck() {
let locationCheck = LocationMonitoring.shared.verifyQuarantinePresence()
networkService.requestNonce(nonceRequestData: BasicRequestData()) { [weak self] (result) in
switch result {
case .success(let data):
let status = locationCheck ? "OK" : "LEFT"
let data = PresenceCheckRequestData(status: status, nonce: data.nonce)
self?.networkService.requestPresenceCheck(presenceCheckRequestData: data) { [weak self] _ in
switch result {
case .success:
DispatchQueue.main.async {
self?.dismiss(animated: true, completion: {
self?.faceCaptureCoordinator = nil
})
}
return
case .failure:
self?.onError()
}
}
case .failure:
self?.onError()
}
}
}
}
|
//
// TableViewController.swift
// Elephant
//
// Created by Caelan Dailey on 2/20/18.
// Copyright © 2018 Caelan Dailey. All rights reserved.
//
// TABLE FOR EVENT TABLE
// A scrolling list that shows each event
// an event has a name, time, and day
// Can delete events
//
import Foundation
import UIKit
class EventTableViewController: UITableViewController, EventDatasetDelegate {
private static var cellReuseIdentifier = "EventTableViewController.DatasetItemsCellIdentifier"
let delegateID: String = UIDevice.current.identifierForVendor!.uuidString
// Need to update on mainthread
func datasetUpdated() {
DispatchQueue.main.async(){
self.tableView.reloadData()
self.tableView.setNeedsDisplay()
}
}
override func viewDidLoad() {
super.viewDidLoad()
EventDataset.registerDelegate(self)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: EventTableViewController.cellReuseIdentifier)
self.title = "EVENTS"
// Refresh button to reload data
self.navigationItem.leftBarButtonItem = refreshListButton
}
@objc func updateTable(sender: UIButton) {
datasetUpdated()
}
// Gets number of rows in table
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard tableView == self.tableView, section == 0 else {
return 0
}
return EventDataset.count
}
// Allows editing
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
// KNOWN ISSUE: Crashing on deleting event
// Attempt to fix because the error seems to happen if entry is deleted after the tableview updates
// Attempt to fix didnt' work. Must be naother issue
// Error message and internet not helpful :/
// Same code in alarm table view but doesnt work correctly
// ISSUE: UNKNOWN
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
// If deleting
if (editingStyle == .delete) {
// Create group
let group = DispatchGroup()
group.enter()
DispatchQueue.main.async {
EventDataset.deleteEntry(atIndex: indexPath.row)
group.leave()
}
// Tell main thread group is done
group.notify(queue: .main) {
tableView.beginUpdates()
tableView.deleteRows(at: [indexPath], with: .middle)
tableView.endUpdates()
}
}
}
// Refresh button for table data
lazy var refreshListButton : UIBarButtonItem = {
let refreshListButton = UIBarButtonItem()
refreshListButton.image = UIImage(named: "refresh_icon")
refreshListButton.action = #selector(updateTable)
refreshListButton.target = self
refreshListButton.style = .plain
return refreshListButton
}()
// THIS POPULATES CELLS
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard tableView === self.tableView, indexPath.section == 0, indexPath.row < EventDataset.count else {
return UITableViewCell()
}
var cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: EventTableViewController.cellReuseIdentifier, for: indexPath)
if cell.detailTextLabel == nil {
cell = UITableViewCell(style: .value1, reuseIdentifier: EventTableViewController.cellReuseIdentifier)
}
// Get object for row
let entry = EventDataset.entry(atIndex: indexPath.row)
cell.textLabel?.text = entry.name
// Calculates time
let hour: Int = Int(entry.time/3600)
let minute: Int = (Int(entry.time) - (hour)*3600) / 60
var minuteString = String(minute)
if (minute < 10) {
minuteString = "0\(minute)"
}
let dayString = entry.day
// Set labels
cell.detailTextLabel?.text = dayString + " \(hour):" + minuteString
cell.detailTextLabel?.adjustsFontSizeToFitWidth = true
return cell
}
}
|
import UIKit
extension Date {
static var today: Date {
return Calendar.current.startOfDay(for: Date())
}
func append(years: Int) -> Date? {
var dateComponents = DateComponents()
dateComponents.year = years
let date = Calendar.current.date(byAdding: dateComponents, to: self)
return date
}
}
|
//
// Appetiser.swift
// Appetisers
//
// Created by Dan Smith on 05/04/2021.
//
import Foundation
struct Appetiser: Decodable, Identifiable {
let id: Int
let name: String
let description: String
let imageURL: String
let price: Double
let calories: Int
let carbs: Int
let protein: Int
}
struct AppetiserResponse: Decodable {
let request: [Appetiser]
}
struct MockData {
static func sampleAppetiser(id: Int = 1,
name: String = "Takoyaki",
description: String = "Delicious description",
imageURL: String = "",
price: Double = 9.99,
calories: Int = 420,
carbs: Int = 42,
protein: Int = 24) -> Appetiser {
return Appetiser(id: id,
name: name,
description: description,
imageURL: imageURL,
price: price,
calories: calories,
carbs: carbs,
protein: protein)
}
static let appetisers = [sampleAppetiser(id: 1), sampleAppetiser(id: 2), sampleAppetiser(id: 3), sampleAppetiser(id: 4)]
}
|
//
// PostCell.swift
// MyProductHunter
//
// Created by Fernando on 9/22/17.
// Copyright © 2017 Specialist. All rights reserved.
//
import UIKit
class PostCell: UITableViewCell {
@IBOutlet weak var thumbnailImange: CustomImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var taglineLabel: UILabel!
@IBOutlet weak var votesCountLabel: 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
}
func configureCell(post: Post) {
nameLabel.text = post.name
taglineLabel.text = post.tagline
guard let voteCount = post.votesCount else {
return
}
votesCountLabel.text = "\(voteCount)"
setupThumbnailImage(post: post)
}
func setupThumbnailImage(post: Post) {
guard let thumbnailImageUrl = post.thumbnailUrl else {return}
thumbnailImange.loadImageFromUrlString(urlString: thumbnailImageUrl)
}
}
|
//
// Instruments.swift
// MusicGenerator
//
// Created by Henrique Figueiredo Conte on 23/04/20.
// Copyright © 2020 Henrique Figueiredo Conte. All rights reserved.
//
import Foundation
enum Instruments: String, CaseIterable {
case piano = "piano"
case guitar = "guitar"
case glockenspiel = "glockenspiel"
case harp = "harp"
case saxophone = "saxophone"
case trumpet = "trumpet"
static func getRandomInstrument() -> Instruments {
return Instruments.allCases.randomElement() ?? .piano
}
}
|
//
// JSONifiable.swift
// JSONCache
//
// Created by Anders Blehr on 12/03/2017.
// Copyright © 2017 Anders Blehr. All rights reserved.
//
import Foundation
public protocol JSONifiable {
func toJSONDictionary() -> [String: Any]
}
public extension JSONifiable {
public func toJSONDictionary() -> [String: Any] {
var dictionary = [String: Any]()
let isStruct = !(type(of:self) is AnyClass)
if isStruct {
for case let (label?, value) in Mirror(reflecting: self).children {
let stringValue = "\(value)"
if stringValue != "nil" && stringValue != "" {
dictionary[label] = value
}
}
}
return JSONConverter.convert(.toJSON, dictionary: dictionary)
}
}
|
//
// File.swift
// CardApp
//
// Created by RyoKitatani on 2021/05/13.
//
import Foundation
|
//
// TabBarMenu.swift
// Bloom
//
// Created by Жарас on 11.06.17.
// Copyright © 2017 asamasa. All rights reserved.
//
import UIKit
class TabBarMenu: UITabBarController{
}
|
//
// ReviewCell.swift
// TableExample
//
// Created by Malte Schonvogel on 24.05.17.
// Copyright © 2017 Malte Schonvogel. All rights reserved.
//
import UIKit
private let avatarWidth: CGFloat = 50
class ReviewCell: DefaultCollectionViewCell, CollectionViewCell {
typealias CellContent = (author: NSAttributedString, date: NSAttributedString, text: NSAttributedString, avatar: UIImage?)
var content: CellContent? {
didSet {
authorLabel.attributedText = content?.author
dateLabel.attributedText = content?.date
textView.attributedText = content?.text
avatarView.image = content?.avatar
}
}
private let authorLabel = UILabel()
private let dateLabel = UILabel()
private let textView = UITextView()
private let avatarView = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.backgroundColor = .white
contentView.layoutMargins = UIEdgeInsets(allSides: spacing)
var views = [String: UIView]()
authorLabel.setContentHuggingPriority(UILayoutPriorityRequired, for: .vertical)
authorLabel.translatesAutoresizingMaskIntoConstraints = false
views["authorLabel"] = authorLabel
contentView.addSubview(authorLabel)
authorLabel.setContentHuggingPriority(UILayoutPriorityRequired, for: .vertical)
dateLabel.translatesAutoresizingMaskIntoConstraints = false
views["dateLabel"] = dateLabel
contentView.addSubview(dateLabel)
textView.contentInset = .zero
textView.textContainerInset = .zero
textView.textContainer.lineFragmentPadding = 0
textView.isOpaque = false
textView.isScrollEnabled = false
textView.isEditable = false
textView.autocorrectionType = .no
textView.autocapitalizationType = .none
textView.backgroundColor = .clear
textView.translatesAutoresizingMaskIntoConstraints = false
views["textView"] = textView
contentView.addSubview(textView)
avatarView.backgroundColor = .gray
avatarView.layer.cornerRadius = 3
avatarView.layer.masksToBounds = true
avatarView.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .horizontal)
avatarView.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .vertical)
avatarView.translatesAutoresizingMaskIntoConstraints = false
views["avatarView"] = avatarView
contentView.addSubview(avatarView)
let metrics = ["spacing": spacing, "halfSpacing": spacing/2]
let constraints = [
"H:|-[avatarView]-(halfSpacing)-[authorLabel]-[dateLabel]-|",
"H:[avatarView]-(halfSpacing)-[textView]-|",
"V:|-[avatarView]",
"V:|-[authorLabel]-(halfSpacing)-[textView]-|",
"V:|-[dateLabel]",
].flatMap {
NSLayoutConstraint.constraints(withVisualFormat: $0, options: [], metrics: metrics, views: views)
} + [
avatarView.widthAnchor.constraint(equalToConstant: avatarWidth),
avatarView.heightAnchor.constraint(equalToConstant: avatarWidth),
]
NSLayoutConstraint.activate(constraints)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
static func calculateHeight(content: CellContent, forWidth width: CGFloat) -> CGFloat {
let availableSpace = width - avatarWidth - spacing*2 - spacing/2
let authorSize = content.author.boundingRect(
with: CGSize(width: availableSpace, height: CGFloat.greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesFontLeading],
context: nil
)
let textSize = content.text.boundingRect(
with: CGSize(width: availableSpace, height: CGFloat.greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesFontLeading],
context: nil
)
return textSize.height + authorSize.height + spacing*2 + spacing/2 + 2
}
}
|
//
// Device.swift
// SimPholders
//
// Created by Luo Sheng on 11/9/15.
// Copyright © 2015 Luo Sheng. All rights reserved.
//
import Foundation
struct Device {
enum State: String {
case Shutdown = "Shutdown"
case Unknown = "Unknown"
case Booted = "Booted"
}
let UDID: String
let type: String
let name: String
let runtime: Runtime
let state: State
let applications: [Application]
init(UDID: String, type: String, name: String, runtime: String, state: State) {
self.UDID = UDID
self.type = type
self.name = name
self.runtime = Runtime(name: runtime)
self.state = state
do {
let applicationPath = URLHelper.deviceURLForUDID(self.UDID).appendingPathComponent("data/Containers/Bundle/Application")
let contents = try FileManager.default.contentsOfDirectory(at: applicationPath, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsSubdirectoryDescendants, .skipsHiddenFiles])
self.applications = contents
.filter({ (url) -> Bool in
var isDirectoryObj: AnyObject?
do {
try (url as NSURL).getResourceValue(&isDirectoryObj, forKey: URLResourceKey.isDirectoryKey)
if let isDirectory = isDirectoryObj as? Bool , isDirectory {
return true
}
} catch {
}
return false
})
.map { Application(url: $0) }
.filter { $0 != nil }
.map { $0! }
} catch {
self.applications = []
}
}
var fullName:String {
get {
return "\(self.name) (\(self.runtime))"
}
}
func containerURLForApplication(_ application: Application) -> URL? {
let URL = URLHelper.containersURLForUDID(UDID)
do {
let directories = try FileManager.default.contentsOfDirectory(at: URL, includingPropertiesForKeys: nil, options: .skipsSubdirectoryDescendants)
if let matchingURL = directories.filter({ dir -> Bool in
if let contents = NSDictionary(contentsOf: dir.appendingPathComponent(".com.apple.mobile_container_manager.metadata.plist")),
let identifier = contents["MCMMetadataIdentifier"] as? String, identifier == application.bundleID {
return true
}
return false
}).first {
return matchingURL
} else {
return nil
}
} catch {
return nil
}
}
}
|
//
// Nav+Display.swift
// FlaskNav
//
// Created by hassan uriostegui on 9/21/18.
// Copyright © 2018 eonflux. All rights reserved.
//
import UIKit
import Delayed
extension FlaskNav{
func displayTabOperation(_ index:Int, completion:@escaping (Bool)->Void){
DispatchQueue.main.async {
print("Display tabIndex: \(index)")
self.tabController?.selectedIndex = index
}
DispatchQueue.main.async {
self.presentTab(index: index, completion: completion)
}
}
func dismissTabOperation(completion:@escaping (Bool)->Void){
DispatchQueue.main.async {
self.dismissTab(completion: completion)
}
}
func displayModalOperation(completion:@escaping ()->Void){
DispatchQueue.main.async {
self.presentModal(completion: completion)
}
}
func dismissModalOperation(completion:@escaping ()->Void){
DispatchQueue.main.async {
self.dismissModal(completion: completion)
}
}
}
extension FlaskNav{
func popToRoot(context:NavContext){
let nav = navInstance(forLayer: context.layer)
print("may POP-TO-ROOT \(context.desc())")
ensureNavCompletion(with: context){
DispatchQueue.main.async {
print("is POPING-TO-ROOT \(context.desc())")
nav.popToRootViewController(animated:true)
}
}
}
func pushController(_ controller:UIViewController, context:NavContext){
let nav = navInstance(forLayer: context.layer)
print("may PUSH \(context.desc())")
ensureNavCompletion(with: context){
DispatchQueue.main.async {
print("is PUSHING now \(context.desc())")
nav.pushViewController(controller, animated: true)
}
}
}
func popToController(_ controller:UIViewController, context:NavContext){
let nav = navInstance(forLayer: context.layer)
print("may POP \(context.desc())")
ensureNavCompletion(with: context){
DispatchQueue.main.async {
print("is POPING \(context.desc())")
nav.popToViewController(controller, animated: true)
}
}
}
}
extension FlaskNav{
func isValidComposition(nav:FlaskNavigationController, context:NavContext)->Bool{
print("validating composition... \(context.desc()) modal:\(isModalPresented()) tab:\(isTabPresented())")
if context.navigator == .Root && nav.viewControllers.count == 1{
print("error: already root \(context.desc())")
return false
}else if context.navigator == .Pop && context.viewController() == nil{
print("error: no controller to pop \(context.desc())")
return false
}else if context.navigator == .Pop && context.viewController() != nil && !(nav.viewControllers.contains(context.viewController()!)){
print("error: controller not in nav \(context.desc())")
return false
}else if NavLayer.IsModal(context.layer) && !isModalPresented() {
print("error: modal not visible \(context.desc())")
return false
}else if NavLayer.IsTab(context.layer) && !isTabPresented() {
print("error: tab not visible \(context.desc())")
return false
}else if NavLayer.IsNav(context.layer) && (isModalPresented() || isTabPresented()) {
print("error: nav not top controller \(context.desc())")
return false
}
return true
}
func dismissModalIntent(with context:NavContext, action:@escaping ()->Void){
if NavLayer.IsModal(context.layer){
print("skip HIDE modal -> context IS modal")
action()
return
}
print("may HIDE modal...")
dismissModal() {
print("after HIDE modal intent")
action()
}
}
func ensureNavCompletion(with context:NavContext, _ action:@escaping ()->Void){
let nav = navInstance(forLayer: context.layer)
let cancel = { [weak self] in
print("Aborting NAV Operation!! \(context.desc())")
self?.intentToCompleteOperationFor(context: context, completed: false)
}
let execute = {
print("Performing NAV Operation! \(context.desc())")
action()
}
let prepareAndExecute = { [weak self] in
print("Preparing NAV Operation \(context.desc())")
nav._isPerformingNavOperation = true
self?.dismissModalIntent(with: context){
execute()
}
}
if isValidComposition(nav: nav, context: context){
prepareAndExecute()
}else{
print("Invalid NAV composition! \(context.desc())")
cancel()
return
}
}
}
extension FlaskNav{
func navOperationKey()->String{
return "navOperationWatchdog"
}
func cancelWatchForNavOperationToComplete(){
print("cancelling WATCHDOG")
Kron.watchDogCancel(key:navOperationKey())
}
func watchForNavOperationToComplete(context: NavContext, finalizer:@escaping ()->Void){
let animatorDuration = context.animator?._duration ?? 1.0
let delay = max( animatorDuration, 4.0) * 1.2
print("setting WATCHDOG delay:\(delay) \(context.desc())")
Kron.watchDog(timeOut: delay, resetKey: navOperationKey()){ key,ctx in
finalizer()
}
}
}
|
//
// PhotoCell.swift
// CollectionViewWithCleanCode
//
// Created by sunil.kumar1 on 12/7/19.
// Copyright © 2019 sunil.kumar1. All rights reserved.
//
import UIKit
class PhotoCollectionCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
}
override func prepareForReuse() {
super.prepareForReuse()
self.imageView.image = nil
}
func fetchImage(imageModel: FlickrURLs) {
if let url = self.getDownloadUrl(imageModel: imageModel) {
ImageDownloader.shared.downloadImage(url:url) {[weak self] (image, error) in
if error == nil {
DispatchQueue.main.async {
self?.imageView.image = image
}
}
}
}
}
private func getDownloadUrl(imageModel: FlickrURLs)-> URL? {
var imageUrl = URLManager.getImageUrl()
imageUrl = imageUrl.replacingOccurrences(of: Constant.farm, with: "\(imageModel.farm)")
imageUrl = imageUrl.replacingOccurrences(of: Constant.server, with: imageModel.server)
imageUrl = imageUrl.replacingOccurrences(of: Constant.id, with: imageModel.id)
imageUrl = imageUrl.replacingOccurrences(of: Constant.secret, with: imageModel.secret)
return URL(string: imageUrl)
}
}
|
//
// Nesting
//
// Copyright (c) 2019-Present Warpdrives Team - https://github.com/warpdrives
//
// The software is available under the Apache 2.0 license. See the LICENSE file
// for more info.
//
// 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
public class NEMonitor {
private weak var delegate: NELinkage?
private var headerView: UIView?
private var navigationHeight: CGFloat = 0.0
/// Set NELinkage protocol.
public func setDelegate<T: Any>(targrt: T) {
delegate = targrt as? NELinkage
}
/// Synchronous headerView.
///
/// - Parameter header: The header of nested view controller.
/// - Parameter navigationBarHeight: The height of the navigation bar of the current view controller.
public func syncProperty(header: UIView, navigationBarHeight: CGFloat) {
headerView = header
navigationHeight = navigationBarHeight
}
deinit {
ne_print("NEMonitor is released")
}
}
extension NEMonitor {
static var scrollMonitorKey: UInt8 = 0
var scrollMonitor: NEScrollMonitor {
get {
let value = ne_associatedObject(base: self, key: &NEMonitor.scrollMonitorKey) {
return NEScrollMonitor()
}
value.delegate = delegate
value.headerView = headerView
value.navigationHeight = navigationHeight
return value
}
set(newValue) {
ne_associateObject(base: self, key: &NEMonitor.scrollMonitorKey, value: newValue)
}
}
}
class NEScrollMonitor: NSObject {
private let KVOKeyPath = "contentOffset"
private var ne_monitorTableViews = [UITableView]()
private var ne_monitorScrollView = UIScrollView()
fileprivate weak var delegate: NELinkage?
fileprivate var callback: ((CGPoint) -> ())?
fileprivate var headerView: UIView?
fileprivate var navigationHeight: CGFloat = 0.0
/// Monitor the tableView.
///
/// - Parameter tableView: Monitored object.
public func monitor(tableView: UITableView) {
/// Determine if the KVO observer has been added.
let ne_addKvo = ne_monitorTableViews.filter( {$0 == tableView} ).first
if ne_addKvo == nil {
ne_monitorTableViews.append(tableView)
tableView.addObserver(self, forKeyPath: KVOKeyPath, options: [.new,.old], context: nil)
}
}
/// Monitor the scrollView.
///
/// - Parameter scrollView: Monitored object.
/// - Parameter closure: A closure containing a CGPoint type return parameter.
public func monitor(scrollView: UIScrollView, closure: ((CGPoint) -> ())?) {
ne_monitorScrollView = scrollView
ne_monitorScrollView.addObserver(self, forKeyPath: KVOKeyPath, options: .new, context: nil)
callback = closure
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let obj = object as? UIScrollView else { return }
if obj.isKind(of: UITableView.classForCoder()) {
let oldOffset = change?[NSKeyValueChangeKey.newKey] as? CGPoint
let newOffset = change?[NSKeyValueChangeKey.oldKey] as? CGPoint
/// Dragging, when push nextViewController, reset offset.
/// Selected statusBar run kvo , use !(oldOffset?.y == newOffset?.y) filter.
if keyPath == KVOKeyPath && (obj.isDragging || !(oldOffset?.y == newOffset?.y)) {
let contentOffset = obj.contentOffset
delegate?.ne_changeHeaderView(originY: contentOffset.y)
updateTableViews(syncTarget: obj)
/// Check contentSize.
adjustMinScrollAreaIfNeeded()
}
} else if obj.isKind(of: UIScrollView.classForCoder()) {
let contentOffset = obj.contentOffset
if let theCallback = callback {
theCallback(contentOffset)
/// - TODO: need set sub scrollView header refresh frame.
}
lazyAddSubViewController()
}
}
deinit {
removeAllObserver()
ne_print("\(self.classForCoder) is released")
}
}
private extension NEScrollMonitor {
/// Lazy add subView.
private func lazyAddSubViewController() {
let obj = self.ne_monitorScrollView
let contentOffset = obj.contentOffset
let scorllIndex = Int(contentOffset.x / obj.bounds.size.width)
if let rootVC = self.delegate as? UIViewController{
guard rootVC.children.count > scorllIndex else { return }
let scrollVC = rootVC.children[scorllIndex]
if !rootVC.ne_scrollView.subviews.contains(scrollVC.view) {
rootVC.ne_scrollView.addSubview(scrollVC.view)
let firstVC = rootVC.children.first ?? UIViewController()
scrollVC.view.frame = CGRect(x: CGFloat(scorllIndex) * firstVC.view.frame.width, y: 0, width: firstVC.view.frame.width, height: firstVC.view.frame.height)
let subviews = scrollVC.view.subviews
for view in subviews {
if view.isKind(of: UITableView.classForCoder()) {
let tableView = view as! UITableView
tableView.ne_setContent(headerView, rootVC.ne_refreshTemplate)
rootVC.ne_monitor.scrollMonitor.monitor(tableView: tableView)
// synchronization max offset
let offsetMaxTablew = self.ne_monitorTableViews.max{tableMin,tableMax in tableMin.contentOffset.y < tableMax.contentOffset.y}
if let offsetMaxTablew = offsetMaxTablew {
delegate?.ne_changeHeaderView(originY: offsetMaxTablew.contentOffset.y)
updateTableViews(syncTarget: offsetMaxTablew)
adjustMinScrollAreaIfNeeded()
}
}
}
}
}
}
/// Remove all Observer.
private func removeAllObserver() {
ne_monitorScrollView.removeObserver(self, forKeyPath: KVOKeyPath)
ne_monitorTableViews.forEach( {$0.removeObserver(self, forKeyPath: KVOKeyPath)} )
ne_monitorTableViews.removeAll()
}
/// Synchronously update the contentOffset of all tableViews.
///
/// - Parameter syncTarget: Synchronized target object.
private func updateTableViews(syncTarget: UIScrollView) {
guard ne_monitorTableViews.count > 0 else { return }
guard let theHeaderView = headerView else { return }
let headerCategoryHeight = -theHeaderView.ne_categoryHeight
let syncTargetOffsetY = syncTarget.contentOffset.y
ne_monitorTableViews.forEach {
if $0 != syncTarget {
let contentOffsetY = $0.contentOffset.y
/// - Note: Synchronize all tableViews when the tableView's content scrolls to its top.
if headerCategoryHeight > contentOffsetY || headerCategoryHeight > syncTargetOffsetY {
let minY = min(headerCategoryHeight, syncTarget.contentOffset.y)
$0.contentOffset = CGPoint(x: syncTarget.contentOffset.x, y: minY)
}
}
}
}
/// Adjust the minimum scrolling area of the tableView when needed.
private func adjustMinScrollAreaIfNeeded() {
guard ne_monitorTableViews.count > 0 else { return }
ne_monitorTableViews.forEach {
guard $0.contentSize.height < $0.frame.size.height else { return }
guard let theHeaderView = headerView else { return }
let allElementsHeight: CGFloat = $0.contentSize.height + navigationHeight + theHeaderView.ne_categoryHeight
let footerHeight: CGFloat = UIScreen.main.bounds.size.height - allElementsHeight
if $0.tableFooterView == nil {
let footerView = UIView()
footerView.frame = CGRect(x: 0, y: 0, width: $0.frame.size.width, height: footerHeight)
$0.tableFooterView = footerView
} else {
$0.contentSize = CGSize(width: $0.contentSize.width, height: $0.contentSize.height + footerHeight)
}
}
}
}
|
//
// CardView.swift
// Pruebas
//
// Created by Julio Banda on 2/8/19.
// Copyright © 2019 Julio Banda. All rights reserved.
//
import UIKit
@IBDesignable class DFCardView: UIControl {
enum Side {
case front, back
}
var card: Card!
var side: Side { fatalError() }
override func layoutSubviews(){
super.layoutSubviews()
roundCorners()
}
func flip(to side: Side? = nil) {
UIView.transition(from: self, to: self, duration: 0.35, options: [.transitionFlipFromRight, .showHideTransitionViews])
}
}
|
//
// SceneTransitionSongManager.swift
// Bird-A-Poo
//
// Created by Báthory Krisztián on 2019. 04. 28..
// Copyright © 2019. Golden Games. All rights reserved.
//
import AVFoundation.AVFAudio
class SceneTransitionSongManager {
static let shared = SceneTransitionSongManager()
var audioPlayer = AVAudioPlayer()
private init() { }
func setup() {
try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.ambient)
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path(forResource: "OpeningSound", ofType: "mp3")!))
audioPlayer.prepareToPlay()
} catch {
print(error)
}
}
func play() {
try? AVAudioSession.sharedInstance().setActive(true)
if let volumePower = UserDefaults.standard.value(forKey: "UserVolumePower") as? String {
audioPlayer.volume = Float(volumePower)! / 100
}
else {
audioPlayer.volume = 1.0
}
if let soundState = UserDefaults.standard.value(forKey: "start") as? String {
if soundState.last! == "1" {
audioPlayer.play()
}
}
else if !GameViewController.fullVersionEnabled || GameViewController.fullVersionEnabled {
audioPlayer.play()
}
}
}
|
//
// CryptoKitServerEncryptor.swift
// NGTools
//
// Created by Lambert, Romain (Ordinateur) on 2022-11-01.
// Copyright © 2022 Nuglif. All rights reserved.
//
import Foundation
import CryptoKit
@available(iOS 13.0, *)
struct CryptoKitServerEncryptor: ServerEncryptor {
func encryptForAuthenticationServer(_ text: String, rsaPublicKey: String) throws -> String {
// 1. Generate AES key
let aesKeyData = try Data.randomBytes()
let symmetricKey = CryptoKitAES.getAESKey(aesKeyData)
// 2. Encrypt data
let encryptedData = try CryptoKitAES.encrypt(text, key: symmetricKey)
// 3. Encrypt AES key with RSA public key
let rsaPublicKey = try CryptoRSA.generatePublicKeyFrom(pemString: rsaPublicKey)
let aesKeyEncryptedData = try CryptoRSA.encrypt(aesKeyData, key: rsaPublicKey)
// 4. Build base64 string to share
let ivData64 = Data(encryptedData.nonce).base64EncodedString()
let cypherText64 = encryptedData.ciphertext.base64EncodedString()
let tag64 = encryptedData.tag.base64EncodedString()
let aesKeyEncryptedData64 = aesKeyEncryptedData.base64EncodedString()
let base64ToShare = "\(aesKeyEncryptedData64).\(ivData64).\(cypherText64).\(tag64)"
return base64ToShare
}
}
|
//
// AuthViewController.swift
// VkNewsFeed
//
// Created by Иван Абрамов on 31.08.2020.
// Copyright © 2020 Иван Абрамов. All rights reserved.
//
import UIKit
class AuthViewController: UIViewController {
private var authSetvice: AuthService!
override func viewDidLoad() {
super.viewDidLoad()
authSetvice = AppDelegate.shared().authService
}
@IBAction func sighInTouch() {
authSetvice.wakeUpSession()
}
}
|
//
// SocialCentreViewController.swift
// PFCM
//
// Created by Thomas Anderson on 10/04/2017.
// Copyright © 2017 Thomas Anderson. All rights reserved.
//
import UIKit
import Firebase
import SCLAlertView
class SocialCentreViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var addImage: UIButton!
@IBOutlet weak var post: UIButton!
@IBOutlet weak var txt: UITextField!
var ref: FIRDatabaseReference = FIRDatabase.database().reference()
var results: [Post] = []
var searchResults: [Post] = []
var searchController: UISearchController!
let storage = FIRStorage.storage()
let imagePicker = UIImagePickerController()
var profilePic: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
retrievePosts()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func retrievePosts() {
let postsRef = ref.child("posts")
postsRef.observe(.value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshot {
let post = Post(snapshot: snap)
self.results.append(post)
}
}
self.tableView.reloadData()
})
}
func setupSearch() {
searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.searchBar.sizeToFit()
searchController.searchBar.tintColor = UIColor.black
searchController.searchBar.delegate = self
searchController.searchBar.barTintColor = UIColor.white
searchController.dimsBackgroundDuringPresentation = false
searchController.hidesNavigationBarDuringPresentation = false
definesPresentationContext = true
tableView.tableHeaderView?.addSubview(searchController.searchBar)
}
@IBAction func addPhoto(_ sender: UIButton) {
imagePicker.allowsEditing = false
imagePicker.sourceType = .photoLibrary
imagePicker.modalPresentationStyle = .popover
present(imagePicker, animated: true, completion: nil)
}
@IBAction func post (_ sender: Any) {
createPost()
}
func createPost () {
let user = FIRAuth.auth()?.currentUser
let key = ref.child("posts").childByAutoId().key
let storage = FIRStorage.storage()
let storageRef = storage.reference()
let imageURL = "\(user!.uid)/posts/\(key).jpg"
let picRef = storageRef.child(imageURL)
let data = UIImageJPEGRepresentation(self.profilePic!, 0.7)! as Data
picRef.put(data,metadata: nil)
let postID = ["postID": key]
let post = Post(postID: key, caption: txt.text!, imageURL: imageURL, likes: 0, timestamp: FIRServerValue.timestamp())
let postsRef = ref.child("posts")
let userRef = ref.child("users").child(user!.uid)
postsRef.setValue(post.toAny())
userRef.child("posts").setValue(postID)
let addSuccessAlertView = SCLAlertView()
addSuccessAlertView.showSuccess("Congrats!", subTitle: "Post has successfully been added.")
self.tableView.setContentOffset(CGPoint.zero, animated: true)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.profilePic = pickedImage
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchController.isActive ? searchResults.count : results.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexPath) as! PostCell
let posts: Post = searchController.isActive ? searchResults[indexPath.item] : results[indexPath.row]
let storageRef = storage.reference(withPath: posts.imageURL)
//let usersRef = ref.child("users")
cell.caption.text = posts.caption
cell.likes.text = String(posts.likes)
storageRef.data(withMaxSize: 1 * 1024 * 1024) { (data, error) in
if let error = error {
print("error has occured: \(error)")
} else {
let image = UIImage(data: data!)
cell.profilePic.image = image
}
}
return cell
}
}
// MARK: - UISearchResultsUpdating
extension SocialCentreViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
guard let searchText = searchController.searchBar.text else {
return
}
print (searchText)
searchResults = results.filter { post in
return post.caption.lowercased().contains(searchText.lowercased())
}
tableView.reloadData()
}
}
// MARK: - UISearchBarDelegate
extension SocialCentreViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
}
}
|
//
// LandmarkList.swift
// Landmarks_2021
//
// Created by USER on 2021/05/15.
//
import SwiftUI
struct LandmarkList: View {
var body: some View {
NavigationView {
List {
NavigationLink(
destination: LandmarkDetail(landmark: Landmark(
name: "Turtle Rock",
category: "Rivers",
city: "Twentynine Palms",
state: "California",
id: 1001,
isFeatured: true,
isFavorite: true,
park: "Joshua Tree National Park",
description: "description",
imageName: "turtlerock",
coordinates: Landmark.Coordinate(
latitude: 34.011286,
longitude: -116.166868)
)
),
label: {
LandmarkRow(landmark: Landmark(
name: "Turtle Rock",
category: "Rivers",
city: "Twentynine Palms",
state: "California",
id: 1001,
isFeatured: true,
isFavorite: true,
park: "Joshua Tree National Park",
description: "description",
imageName: "turtlerock",
coordinates: Landmark.Coordinate(
latitude: 34.011286,
longitude: -116.166868)
)
)
}
)
NavigationLink(
destination: LandmarkDetail(landmark: Landmark(
name: "Silver Salmon Creek",
category: "Lakes",
city: "Port Alsworth",
state: "Alaska",
id: 1002,
isFeatured: false,
isFavorite: false,
park: "Lake Clark National Park and Preserve",
description: "description ...",
imageName: "silversalmoncreek",
coordinates: Landmark.Coordinate(
latitude: 59.980167,
longitude: -152.665167)
)
),
label: {
LandmarkRow(landmark: Landmark(
name: "Silver Salmon Creek",
category: "Lakes",
city: "Port Alsworth",
state: "Alaska",
id: 1002,
isFeatured: false,
isFavorite: false,
park: "Lake Clark National Park and Preserve",
description: "description ...",
imageName: "silversalmoncreek",
coordinates: Landmark.Coordinate(
latitude: 59.980167,
longitude: -152.665167)
)
)
}
)
}
.navigationTitle("Landmarks")
.navigationBarTitleDisplayMode(.automatic)
}
}
}
struct LandmarkList_Previews: PreviewProvider {
static var previews: some View {
LandmarkList()
}
}
|
//
// CanYouFigureItOut?.swift
// game
//
// Created by Fredrik Carlsson on 2018-01-11.
// Copyright © 2018 Fredrik Carlsson. All rights reserved.
//
import Foundation
public class CanYouFigureItOut {
public var subject = ""
public var answer = ""
public var clue1 = ""
public var clue2 = ""
public var clue3 = ""
public var clue4 = ""
public var clue5 = ""
init(title: String, answer: String, firstWord: String, secondWord: String, thirdWord: String, fourthWord: String, fifthWord: String) {
self.subject = title
self.answer = answer
self.clue1 = firstWord
self.clue2 = secondWord
self.clue3 = thirdWord
self.clue4 = fourthWord
self.clue5 = fifthWord
}
}
|
//
// ImageViewExtension.swift
// MovieOpedia
//
// Created by Sayantan Chakraborty on 08/02/19.
// Copyright © 2019 Sayantan Chakraborty. All rights reserved.
//
import Foundation
import UIKit
let imageCache = NSCache<AnyObject, AnyObject>()
extension UIImageView{
func loadImageFromImageUrlFromCache(url:String){
self.image = nil
if let cachedImage = imageCache.object(forKey: url as AnyObject) as? UIImage{
self.image = cachedImage
print("in cache")
return
}
print("in download")
let urlRequest = URLRequest(url: URL(string: url)!)
let session = URLSession(configuration: .default)
let task = session.dataTask(with: urlRequest) { (data:Data?, response:URLResponse?, error:Error?) in
guard error == nil else{
print(error?.localizedDescription ?? "error from loadImageFromImageUrlFromCache")
return
}
DispatchQueue.main.async {
if let downloadImage = UIImage(data: data!){
imageCache.setObject(downloadImage, forKey: url as AnyObject)
self.image = downloadImage
}
}
}
task.resume()
}
}
|
//
// ViewController.swift
// SampleApp
//
// Created by N94547 on 11/9/18.
// Copyright © 2018 Cigna Inc. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var sampleLabel: UILabel!
@IBOutlet weak var sampleTextView: UITextView!
@IBOutlet weak var buildTypeLabel: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
initializeView()
}
func initializeView() {
let titleText = String(format: "%@ Configuration", Helper.queryBuildType().rawValue)
buildTypeLabel.setTitle(titleText, for: .normal)
}
@IBAction func didTapRandomColorButton(_ sender: Any) {
let red = CGFloat(arc4random_uniform(256))
let green = CGFloat(arc4random_uniform(256))
let blue = CGFloat(arc4random_uniform(256))
let backgroundColor = UIColor(red: (red / 255), green: (green / 255), blue: (blue / 255), alpha: 1.0)
view.backgroundColor = backgroundColor
sampleTextView.backgroundColor = backgroundColor
}
}
|
//
// TabbarController.swift
// iOS-MVVMC-Architecture
//
// Created by Nishinobu.Takahiro on 2017/05/12.
// Copyright © 2017年 hachinobu. All rights reserved.
//
import UIKit
import RxSwift
final class TabbarController: UITabBarController, UITabBarControllerDelegate, TabbarViewProtocol {
enum SelectTabNumber: Int {
case homeTimeLine = 0
case trendLike
case trendReTweet
case accountDetail
}
private var selectHomeTimeLineTabObserver = PublishSubject<UINavigationController>()
lazy var selectHomeTimeLineTabObservable: Observable<UINavigationController> =
self.selectHomeTimeLineTabObserver.asObservable()
private var selectTrendLikeTweetListTabObserver = PublishSubject<UINavigationController>()
lazy var selectTrendLikeTweetListTabObservable: Observable<UINavigationController> =
self.selectTrendLikeTweetListTabObserver.asObservable()
private var selectTrendReTweetTimeLineTabObserver = PublishSubject<UINavigationController>()
lazy var selectTrendReTweetTimeLineTabObservable: Observable<UINavigationController> =
self.selectTrendReTweetTimeLineTabObserver.asObservable()
private var selectAccountDetailTabObserver = PublishSubject<UINavigationController>()
var selectAccountDetailTabObservable: Observable<UINavigationController> {
return selectHomeTimeLineTabObserver.asObservable()
}
private var loadTabbarObserver = PublishSubject<UINavigationController>()
var loadTabbarObservable: Observable<UINavigationController> {
return loadTabbarObserver.asObservable()
}
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
if let navigationController = customizableViewControllers?.first as? UINavigationController {
loadTabbarObserver.onNext(navigationController)
}
}
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
guard let navigationController = viewControllers?[selectedIndex] as? UINavigationController,
let tabRoot = SelectTabNumber(rawValue: selectedIndex) else {
return
}
switch tabRoot {
case .homeTimeLine:
selectHomeTimeLineTabObserver.onNext(navigationController)
case .trendLike:
selectTrendLikeTweetListTabObserver.onNext(navigationController)
case .trendReTweet:
selectTrendReTweetTimeLineTabObserver.onNext(navigationController)
case .accountDetail:
selectAccountDetailTabObserver.onNext(navigationController)
}
}
}
|
//
// EmptyTableViewCell.swift
// BookingVP
//
// Created by HoangVanDuc on 11/26/19.
// Copyright © 2019 HoangVanDuc. All rights reserved.
//
import UIKit
class EmptyTableViewCell: UITableViewCell {
@IBOutlet weak var cstHeightViewEmpty: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
cstHeightViewEmpty.constant = 2
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
|
//
// HomeViewController.swift
// iOSOnboardingProject
//
// Created by Arinjay Sharma on 15/06/21.
//
import UIKit
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
|
import Foundation
import RealmSwift
class RWorkItem: Object {
dynamic var Id = 0
dynamic var Title = ""
dynamic var Complete = false
dynamic var Date = NSDate()
dynamic var Weather = 0
dynamic var WeatherDescription = ""
dynamic var Image = ""
dynamic var City = ""
override static func primaryKey() -> String {
return "Id"
}
// override static func ignoredProperties() -> [String] {
// return []
// }
}
|
//
// API.swift
// BankApp
//
// Created by Hundily Cerqueira on 17/07/19.
// Copyright © 2019 Hundily Cerqueira. All rights reserved.
//
import Foundation
struct API {
enum Path {
case contacts
case payment
var value: String {
let baseURL = Environment.current.baseURLString
switch self {
case .contacts:
return "\(baseURL)/tests/mobdev/users"
case .payment:
return "\(baseURL)/tests/mobdev/transaction"
}
}
}
}
|
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
/// A rule context is a record of a single rule invocation.
///
/// We form a stack of these context objects using the parent
/// pointer. A parent pointer of null indicates that the current
/// context is the bottom of the stack. The ParserRuleContext subclass
/// as a children list so that we can turn this data structure into a
/// tree.
///
/// The root node always has a null pointer and invokingState of ATNState.INVALID_STATE_NUMBER.
///
/// Upon entry to parsing, the first invoked rule function creates a
/// context object (asubclass specialized for that rule such as
/// SContext) and makes it the root of a parse tree, recorded by field
/// Parser._ctx.
///
/// public final SContext s() throws RecognitionException {
/// SContext _localctx = new SContext(_ctx, getState()); <-- create new node
/// enterRule(_localctx, 0, RULE_s); <-- push it
/// ...
/// exitRule(); <-- pop back to _localctx
/// return _localctx;
/// }
///
/// A subsequent rule invocation of r from the start rule s pushes a
/// new context object for r whose parent points at s and use invoking
/// state is the state with r emanating as edge label.
///
/// The invokingState fields from a context object to the root
/// together form a stack of rule indication states where the root
/// (bottom of the stack) has a -1 sentinel value. If we invoke start
/// symbol s then call r1, which calls r2, the would look like
/// this:
///
/// SContext[-1] <- root node (bottom of the stack)
/// R1Context[p] <- p in rule s called r1
/// R2Context[q] <- q in rule r1 called r2
///
/// So the top of the stack, _ctx, represents a call to the current
/// rule and it holds the return address from another rule that invoke
/// to this rule. To invoke a rule, we must always have a current context.
///
/// The parent contexts are useful for computing lookahead sets and
/// getting error information.
///
/// These objects are used during parsing and prediction.
/// For the special case of parsers, we use the subclass
/// ParserRuleContext.
///
/// - SeeAlso: org.antlr.v4.runtime.ParserRuleContext
///
open class RuleContext: RuleNode {
/// What context invoked this rule?
public weak var parent: RuleContext?
/// What state invoked the rule associated with this context?
/// The "return address" is the followState of invokingState
/// If parent is null, this should be ATNState.INVALID_STATE_NUMBER
/// this context object represents the start rule.
///
public var invokingState = ATNState.INVALID_STATE_NUMBER
public init() {
}
public init(_ parent: RuleContext?, _ invokingState: Int) {
self.parent = parent
//if ( parent!=null ) { print("invoke "+stateNumber+" from "+parent)}
self.invokingState = invokingState
}
open func depth() -> Int {
var n = 0
var p: RuleContext? = self
while let pWrap = p {
p = pWrap.parent
n += 1
}
return n
}
/// A context is empty if there is no invoking state; meaning nobody called
/// current context.
///
open func isEmpty() -> Bool {
return invokingState == ATNState.INVALID_STATE_NUMBER
}
// satisfy the ParseTree / SyntaxTree interface
open func getSourceInterval() -> Interval {
return Interval.INVALID
}
open func getRuleContext() -> RuleContext {
return self
}
open func getParent() -> Tree? {
return parent
}
open func setParent(_ parent: RuleContext) {
self.parent = parent
}
open func getPayload() -> AnyObject {
return self
}
/// Return the combined text of all child nodes. This method only considers
/// tokens which have been added to the parse tree.
///
/// Since tokens on hidden channels (e.g. whitespace or comments) are not
/// added to the parse trees, they will not appear in the output of this
/// method.
///
open func getText() -> String {
let length = getChildCount()
if length == 0 {
return ""
}
var builder = ""
for i in 0..<length {
builder += self[i].getText()
}
return builder
}
open func getRuleIndex() -> Int {
return -1
}
open func getAltNumber() -> Int { return ATN.INVALID_ALT_NUMBER }
open func setAltNumber(_ altNumber: Int) { }
open func getChild(_ i: Int) -> Tree? {
return nil
}
open func getChildCount() -> Int {
return 0
}
open subscript(index: Int) -> ParseTree {
preconditionFailure("Index out of range (RuleContext never has children, though its subclasses may).")
}
open func accept<T>(_ visitor: ParseTreeVisitor<T>) -> T? {
return visitor.visitChildren(self)
}
/// Print out a whole tree, not just a node, in LISP format
/// (root child1 .. childN). Print just a node if this is a leaf.
/// We have to know the recognizer so we can get rule names.
///
open func toStringTree(_ recog: Parser) -> String {
return Trees.toStringTree(self, recog)
}
/// Print out a whole tree, not just a node, in LISP format
/// (root child1 .. childN). Print just a node if this is a leaf.
///
public func toStringTree(_ ruleNames: [String]?) -> String {
return Trees.toStringTree(self, ruleNames)
}
open func toStringTree() -> String {
return toStringTree(nil)
}
open var description: String {
return toString(nil, nil)
}
open var debugDescription: String {
return description
}
public final func toString<T>(_ recog: Recognizer<T>) -> String {
return toString(recog, ParserRuleContext.EMPTY)
}
public final func toString(_ ruleNames: [String]) -> String {
return toString(ruleNames, nil)
}
// recog null unless ParserRuleContext, in which case we use subclass toString(...)
open func toString<T>(_ recog: Recognizer<T>?, _ stop: RuleContext) -> String {
let ruleNames = recog?.getRuleNames()
return toString(ruleNames, stop)
}
open func toString(_ ruleNames: [String]?, _ stop: RuleContext?) -> String {
var buf = ""
var p: RuleContext? = self
buf += "["
while let pWrap = p, pWrap !== stop {
if let ruleNames = ruleNames {
let ruleIndex = pWrap.getRuleIndex()
let ruleIndexInRange = (ruleIndex >= 0 && ruleIndex < ruleNames.count)
let ruleName = (ruleIndexInRange ? ruleNames[ruleIndex] : String(ruleIndex))
buf += ruleName
}
else {
if !pWrap.isEmpty() {
buf += String(pWrap.invokingState)
}
}
if let pWp = pWrap.parent, (ruleNames != nil || !pWp.isEmpty()) {
buf += " "
}
p = pWrap.parent
}
buf += "]"
return buf
}
open func castdown<T>(_ subType: T.Type) -> T {
return self as! T
}
}
|
//
// ConversationCellModel.swift
// Test
//
// Created by a.belyaev3 on 26.09.2020.
// Copyright © 2020 a.belyaev3. All rights reserved.
//
import Foundation
import Firebase
struct ConversationCellModel {
let identifier: String
let name: String
let lastMessage: String?
let lastActivity: Timestamp?
}
|
//
// Schematic_CaptureTests.swift
// Schematic CaptureTests
//
// Created by Gi Pyo Kim on 1/23/20.
// Copyright © 2020 GIPGIP Studio. All rights reserved.
//
import XCTest
import Firebase
import FirebaseStorage
@testable import Schematic_Capture
struct AsyncOperation<Value> {
let queue: DispatchQueue = .main
let closure: () -> Value
func perform(then handler: @escaping (Value) -> Void) {
queue.async {
let value = self.closure()
handler(value)
}
}
}
class Schematic_CaptureTests: XCTestCase {
var loginController = LogInController()
var projectController = ProjectController()
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
let user = User(password: "Testing123!", username: "bob_johnson@lambdaschool.com")
let bearer = Bearer(token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InRpRFRmZU5GMUtjRWtXOTdnUExJcEc4NWl1YjIiLCJwYXNzd29yZCI6MSwiZW1haWwiOiJib2Jfam9obnNvbkBsYW1iZGFzY2hvb2wuY29tIiwicm9sZUlkIjoiVGVzdGluZzEyMyEiLCJpYXQiOjE1ODc1NzY2ODIsImV4cCI6MTU4NzY2MzA4Mn0.Ab_OLV463UTVY4gDvwTZt3orBOmBYGgEKPtDEWRVdUA")
let expectation = self.expectation(description: "loginController")
//MARK: Test LoginController
loginController.logIn(username: (user.username)!, password: user.password!, completion: { (error) in
if let error = error {
XCTFail("\(error)")
return
}
else {
expectation.fulfill()
}
} )
wait(for:[expectation], timeout:10)
}
func testLogIn(){
let bearer = Bearer?.self
let user = User(password: "Testing123!", username: "bob_johnson@lambdaschool.com")
XCTAssert(user.username == "bob_johnson@lambdaschool.com")
XCTAssertNotNil(bearer)
}
func testSignOut(){
let expectation = self.expectation(description: "Logged out succesfully")
loginController.signOut(completion: { (error)
in
if let error = error {
XCTFail("\(error)")
return
}
else {
expectation.fulfill()
}
} )
wait(for:[expectation], timeout:10)
}
//MARK:Test ProjectController
func testDownloadAssignedJobs() {
self.projectController.bearer = Bearer(token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6InRpRFRmZU5GMUtjRWtXOTdnUExJcEc4NWl1YjIiLCJwYXNzd29yZCI6MSwiZW1haWwiOiJib2Jfam9obnNvbkBsYW1iZGFzY2hvb2wuY29tIiwicm9sZUlkIjoiVGVzdGluZzEyMyEiLCJpYXQiOjE1ODc1NzY2ODIsImV4cCI6MTU4NzY2MzA4Mn0.Ab_OLV463UTVY4gDvwTZt3orBOmBYGgEKPtDEWRVdUA")
let expectation = self.expectation(description: "Downloading assigned jobs succesfully")
projectController.downloadAssignedJobs(completion: { error in
if let error = error {
if error != NetworkingError.badDecode {
XCTFail()
print(error)
return
}
else {
expectation.fulfill()
}
}
}
)
wait(for:[expectation], timeout:10)
}
}
|
//
// BookCollectionViewCell.swift
// Books
//
// Created by Nikhil Dhavale on 23/02/20.
// Copyright © 2020 Nikhil Dhavale. All rights reserved.
//
import UIKit
struct BookItemConstant {
static let bookItemImage = "image/jpeg"
static let html = "text/plain; charset=utf-8"
static let pdf = "application/pdf"
static let txt = "text/plain; charset=utf-8"
}
class BookCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: SecureImageView!
@IBOutlet weak var bookNameLabel: UILabel!
@IBOutlet weak var bookAuthorLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func updateCell(book:Book)
{
if let bookImage = book.formats?[BookItemConstant.bookItemImage]
{
imageView.getImageWithImageId(bookImage, shouldSaveToDisk: false)
}
bookNameLabel.font = UIFont.BookName
bookNameLabel.text = book.title?.uppercased()
bookNameLabel.textColor = ColorConstant.darkergrey
bookAuthorLabel.font = UIFont.BookAuthor
bookAuthorLabel.text = book.authorNames
bookAuthorLabel.textColor = ColorConstant.darkgrey
}
}
|
//
// WeaponTests.swift
// Ruins
//
// Created by Theodore Abshire on 7/6/16.
// Copyright © 2016 Theodore Abshire. All rights reserved.
//
import XCTest
@testable import Ruins
class WeaponTests: XCTestCase {
var weapon:Weapon!
override func setUp() {
super.setUp()
weapon = Weapon(type: "test weapon", material: "neutral", level: 0)
}
func testLoadWeaponFromPlist()
{
//test to make sure all of the loaded statistics, and calculated statistics, are as expected
normalLoadAsserts()
}
func testLoadWeaponFromSaveDict()
{
let saveDict = weapon.saveDict
weapon = Weapon(saveDict: saveDict)
normalLoadAsserts()
}
func testNoSubtypeDamageByLevel()
{
XCTAssertEqual(Weapon(type: "test weapon", material: "neutral", level: 13).damage, 150)
XCTAssertEqual(Weapon(type: "test weapon", material: "neutral", level: 26).damage, 200)
}
func testMaterialDamage()
{
XCTAssertEqual(Weapon(type: "test weapon", material: "double material", level: 0).damage, 200)
}
func testMaterialWeight()
{
XCTAssertEqual(Weapon(type: "test weapon", material: "double material", level: 0).weight, 200)
}
func testMaterialHealth()
{
let oWep = Weapon(type: "test weapon", material: "double material", level: 0)
XCTAssertEqual(oWep.maxHealth, 200)
XCTAssertEqual(oWep.health, 200)
}
func testSubtypePicking()
{
XCTAssertEqual(Weapon(type: "test subtype weapon", material: "neutral", level: 0).subtype, 0)
XCTAssertEqual(Weapon(type: "test subtype weapon", material: "neutral", level: 25).subtype, 0)
XCTAssertEqual(Weapon(type: "test subtype weapon", material: "neutral", level: 75).subtype, 1)
XCTAssertEqual(Weapon(type: "test subtype weapon", material: "neutral", level: 100).subtype, 1)
}
func testSubtypeDamage()
{
XCTAssertEqual(Weapon(type: "test subtype weapon", material: "neutral", level: 0).damage, 100)
XCTAssertEqual(Weapon(type: "test subtype weapon", material: "neutral", level: 100).damage, 200)
}
func testSubtypeName()
{
XCTAssertEqual(Weapon(type: "test subtype weapon", material: "neutral", level: 0).name, "neutral first subtype")
XCTAssertEqual(Weapon(type: "test subtype weapon", material: "neutral", level: 100).name, "neutral second subtype")
}
func testSubtypeWeight()
{
XCTAssertEqual(Weapon(type: "test subtype weapon", material: "neutral", level: 0).weight, 100)
XCTAssertEqual(Weapon(type: "test subtype weapon", material: "neutral", level: 100).weight, 200)
}
func testBroken()
{
XCTAssertFalse(weapon.broken)
weapon.health = 0
XCTAssertTrue(weapon.broken)
//no-durability weapons should be immune to breaking
let oWeapon = Weapon(type: "unarmed", material: "neutral", level: 0)
XCTAssertEqual(oWeapon.health, 0)
XCTAssertFalse(oWeapon.broken)
}
//MARK: helper functions
func normalLoadAsserts()
{
XCTAssertEqual(weapon.damage, 100)
XCTAssertEqual(weapon.accuracy, 100)
XCTAssertEqual(weapon.hitDamageMultiplier, 200)
XCTAssertEqual(weapon.weight, 100)
XCTAssertEqual(weapon.range, 100)
XCTAssertEqual(weapon.name, "neutral test weapon")
XCTAssertNil(weapon.strongVS)
XCTAssertNil(weapon.statusInflicted)
XCTAssertEqual(weapon.maxHealth, 100)
XCTAssertEqual(weapon.health, 100)
XCTAssertNil(weapon.spriteName)
XCTAssertEqual(weapon.description, "SAMPLE FLAVOR.\n200 damage (100 graze), 100% accuracy, 100 range, 100 weight")
}
} |
//
// Constants.swift
// Food Aggregator
//
// Created by Chashmeet on 13/11/18.
// Copyright © 2018 Chashmeet Singh. All rights reserved.
//
import UIKit
extension Client {
struct ResponseMessages {
static let InvalidParams = "Email ID / Password incorrect"
static let ServerError = "Problem connecting to server!"
static let SignedOut = "Successfully logged out"
static let PasswordInvalid = "Password chosen is invalid."
}
struct APIURL {
static let IPAddress = "http://167.99.179.118:8081"
}
struct Methods {
static let Login = "/signIn"
static let FoodCourts = "/getFoodCourtByCity"
static let FoodMenu = "/FoodMenu"
static let PlaceOrder = "/user/placeOrder"
static let Logout = "/user/logout"
static let GetOrders = "/user/getOrdersForUser"
static let UpdateProfile = "/user/updateProfile"
static let Register = "/register"
static let UpdateOrder = "/user/updateOrderStatus"
}
struct Keys {
static let Email = "email"
static let Password = "password"
static let Status = "status"
static let Token = "token"
static let Message = "message"
static let Name = "name"
static let FCList = "fcList"
static let Id = "id"
static let FoodCourtName = "foodCourtName"
static let Address = "address"
static let City = "city"
static let OpenTime = "open_time"
static let CloseTime = "close_time"
static let Restaurants = "restaurants"
static let IconName = "iconName"
static let FCID = "fc_id"
static let RestaurantName = "restaurantName"
static let ItemList = "ItemList"
static let Category = "category"
static let Cost = "cost"
static let FoodCourtId = "foodCourtId"
static let RestaurantId = "restaurant_id"
static let TimeToPrepareInMinutes = "timeToPrepareInMinutes"
static let OrderDetails = "orderDetails"
static let FirstName = "first_name"
static let LastName = "last_name"
static let PhoneNumber = "phone_number"
static let EmailID = "email_id"
static let FoodItemIds = "foodItemIds"
static let Quantity = "quantity"
static let CustomerOrder = "customerOrder"
static let OrderTime = "orderTime"
static let UserId = "userId"
static let Username = "userName"
static let TotalCost = "totalCost"
static let OrderStatus = "orderStatus"
static let PreparationTime = "prepTime"
static let OrderId = "orderId"
static let ItemCost = "itemCost"
static let OrderItemList = "orderItemList"
static let OrderList = "OrderList"
static let UserRole = "user_role"
static let Active = "ACTIVE"
static let Completed = "COMPLETED"
static let PhoneNum = "PhoneNum"
static let Phone_Number = "phoneNumber"
static let Customerorder = "customer order"
static let First_Name = "firstName"
static let Last_Name = "lastName"
static let RestaurantID = "restaurantId"
}
struct Colors {
static let overcastBlueColor = UIColor(red: 0, green: 187/255, blue: 204/255, alpha: 1.0)
}
}
|
//
// User.swift
// iAm-inquadrami
//
// Created by Antonio Virgone on 04/03/16.
// Copyright © 2016 Antonio Virgone. All rights reserved.
//
import Foundation
class User
{
var id : Int
var email : String
var username : String
var password : String
var avatar : String
var sessionId : String
init(id: Int, email: String, username: String, password: String, avatar: String, sessionId: String)
{
self.id = id
self.email = email
self.username = username
self.password = password
self.avatar = avatar
self.sessionId = sessionId
}
func getId() -> Int
{
return id
}
func getEmail() -> String
{
return email
}
func getUsername() -> String
{
return username
}
func getPassword() -> String
{
return password
}
func getAvatar() -> String
{
return avatar
}
func getSessionId() -> String
{
return sessionId
}
} |
//
// ViewController.swift
// CollapsibleTable
//
// Created by sdnmacmini24 on 10/12/18.
// Copyright © 2018 Personal. All rights reserved.
//
import UIKit
import CollapsibleTableSectionViewController
class ViewController: CollapsibleTableSectionViewController {
var firstSection:[String] = ["","","","","","","","",""]
var secondSection:[String] = ["","","","","","","","","","","","","",""]
var thirdSection:[String] = ["","","","","","","","","","","","","","","","","","",]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.delegate = self
self.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: CollapsibleTableSectionDelegate {
func numberOfSections(_ tableView: UITableView) -> Int {
return 3
}
func collapsibleTableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return (firstSection.count)
}else if section == 1 {
return (secondSection.count)
}else {
return (thirdSection.count)
}
}
func collapsibleTableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: ReservationCustomCell = tableView.dequeueReusableCell(withIdentifier: "ReservationCustomCell", for: indexPath) as! ReservationCustomCell
switch indexPath.section {
case 0:
if firstSection.count - 1 == indexPath.row {
cell.separatorView.isHidden = true
}else {
cell.separatorView.isHidden = true
}
cell.usernameLbl.text = "\(indexPath.section + 1) Section - \(indexPath.row) Row"
case 1:
if secondSection.count - 1 == indexPath.row {
cell.separatorView.isHidden = true
}else {
cell.separatorView.isHidden = true
}
cell.usernameLbl.text = "\(indexPath.section + 1) Section - \(indexPath.row) Row"
case 2:
if thirdSection.count - 1 == indexPath.row {
cell.separatorView.isHidden = true
}else {
cell.separatorView.isHidden = true
}
cell.usernameLbl.text = "\(indexPath.section + 1) Section - \(indexPath.row) Row"
default:
break;
}
return cell
}
func collapsibleTableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 1.0
}
func collapsibleTableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "First Section (\(self.firstSection.count))"
}else if section == 1 {
return "Second Section (\(self.secondSection.count))"
}else {
return "Third Section (\(self.thirdSection.count))"
}
}
func collapsibleTableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0 {
//self.showPendingController(indexPath)
}else if indexPath.section == 1 {
}else if indexPath.section == 2 {
}else {
}
}
func shouldCollapseByDefault(_ tableView: UITableView) -> Bool {
return true
}
func shouldCollapseOthers(_ tableView: UITableView) -> Bool {
return true
}
}
|
//
// ShoppingListViewController.swift
// Bring It!
//
// Created by Administrador on 10/19/17.
// Copyright © 2017 tec. All rights reserved.
//
import UIKit
import Alamofire
class ShoppingListViewController: UIViewController,UITableViewDataSource, UITableViewDelegate {
var arrayAllShoppingList = [ShoppingList]()
var arrayUserCurrentShoppingList = [ShoppingList]()
var alertController: UIAlertController!
var emailShareShoppinList:UITextField? = nil
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var shoppingListTableV: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.activityIndicator.hidesWhenStopped = true
self.shoppingListTableV.dataSource = self
self.shoppingListTableV.delegate = self
loadActionSheet()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func emailShareShoppingList(textField:UITextField){
emailShareShoppinList = textField
}
override func viewWillAppear(_ animated: Bool) {
tabBarController?.tabBar.isHidden = false
Singlenton.instance.arrayAllShoppingList = []
if currentReachabilityStatus == .reachableViaWWAN{
self.getShoppingList()
}else if currentReachabilityStatus == .reachableViaWiFi{
self.getShoppingList()
}else{
printMessageInternet(error: "Could not connect to the server Check your Internet connection and try again")
}
self.shoppingListTableV.reloadData()
}
func getShoppingList() {
self.activityIndicator.startAnimating()
let urlRequest = Constants.URL + Constants.GETUSERSHOPPINGLIST + (Singlenton.instance.currentUser?.id)!
Alamofire.request(urlRequest).responseJSON { response in
if response.response?.statusCode == Constants.STATUS_OK{
ParserJSON.parserJSONShoppingListUser(data:response.data!)
self.shoppingListTableV.reloadData()
self.activityIndicator.stopAnimating()
}else{
self.printMessage(error: "Connection fail")
}
}
}
func printMessageInternet(error:String){
let alert = UIAlertController(title: "Error de conexión", message: error, preferredStyle: .alert)
let accion = UIAlertAction(title: "Retry", style: .default){
(action) -> Void in
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyBoard.instantiateViewController(withIdentifier: "HomeView") as! UITabBarController
self.present(viewController, animated: true, completion: nil)
}
alert.addAction(accion)
self.present(alert,animated:true,completion: nil)
}
func printMessage(error:String){
let alert = UIAlertController(title: "Alert", message: error, preferredStyle: .alert)
let accion = UIAlertAction(title: "Ok", style: .default){
(action) -> Void in
}
alert.addAction(accion)
self.present(alert,animated:true,completion: nil)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var numberRows: Int = 0
numberRows = Singlenton.instance.arrayAllShoppingList.count
return numberRows
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCell(withIdentifier: "shoppingList", for: indexPath) as! ShoppingListTableViewCell
let shopList = Singlenton.instance.arrayAllShoppingList[(indexPath as NSIndexPath).row]
myCell.nameShoppingListLabel.text! = shopList.name
myCell.dateShoppingListLabel.text! = shopList.shopDate
return myCell
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let more = UITableViewRowAction(style:.normal,title: "More", handler: {action, indexPath in
Singlenton.instance.currentShoppingListEdit = Singlenton.instance.arrayAllShoppingList[(indexPath as NSIndexPath).row]
self.present(self.alertController, animated:true, completion:nil)
})
let delete = UITableViewRowAction(style:.destructive,title: "Delete", handler: {action, indexPath in
self.deleteShoppingList(tabRow: indexPath)
})
return [more, delete]
}
func loadActionSheet(){
alertController = UIAlertController(title:"", message:"",preferredStyle:UIAlertControllerStyle.actionSheet)
let sharedShoppinList = UIAlertAction(title:"Share",style:UIAlertActionStyle.default){ (ACTION) -> Void in
self.shareShoppingList()
}
let editShoppingList = UIAlertAction(title:"Edit",style:UIAlertActionStyle.default){ (ACTION) -> Void in
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyBoard.instantiateViewController(withIdentifier: "RegisterShoppingList") as! UINavigationController
self.present(viewController, animated: true, completion: nil)
}
let cancelAction = UIAlertAction(title:"Cancel",style:UIAlertActionStyle.cancel){ (ACTION) -> Void in
}
alertController.addAction(sharedShoppinList)
alertController.addAction(editShoppingList)
alertController.addAction(cancelAction)
}
func shareShoppingList(){
let alert = UIAlertController(title: "Share shopping list",
message: "",
preferredStyle: .alert)
// Submit button
let submitAction = UIAlertAction(title: "Share", style: .default, handler: { (action) -> Void in
// Get 1st TextField's text
let textField = alert.textFields![0]
let email = textField.text!
if email == ""{
self.printMessage(error: "Email address empty")
}else{
self.getShareUser(emailAddress: email)
}
})
// Cancel button
let cancel = UIAlertAction(title: "Cancel", style: .destructive, handler: { (action) -> Void in })
// Add 1 textField and customize it
alert.addTextField { (textField: UITextField) in
textField.keyboardAppearance = .dark
textField.keyboardType = .default
textField.autocorrectionType = .default
textField.placeholder = "Email address"
textField.clearButtonMode = .whileEditing
}
// Add action buttons and present the Alert
alert.addAction(submitAction)
alert.addAction(cancel)
present(alert, animated: true, completion: nil)
}
func shareShoppingList(userShare:User){
let idShoppingList = Singlenton.instance.currentShoppingListEdit?.id
let url = URL(string: Constants.URL + Constants.SHARESHOPPINGLIST + idShoppingList!)!
let parameters: Parameters = ["idUser": userShare.id]
var urlRequest = URLRequest(url: url)
print(parameters)
urlRequest.httpMethod = "PUT"
do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
}
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
Alamofire.request(urlRequest).responseJSON { response in
if response.response?.statusCode == Constants.STATUS_OK
{
self.printMessage(error: "It was successfully shared")
}else{
self.printMessage(error: "Connection fail")
}
}
}
func getShareUser(emailAddress: String){
let urlRequest = Constants.URL + Constants.GETUSER + emailAddress
Alamofire.request(urlRequest).responseJSON { response in
if response.response?.statusCode == Constants.STATUS_OK{
let userShare = ParserJSON.parserJSONShareUser(data:response.data!)
self.shareShoppingList(userShare: userShare)
}else{
self.printMessage(error: "Connection fail")
}
}
}
func deleteShoppingList(tabRow: IndexPath){
let shoppingList = Singlenton.instance.arrayAllShoppingList[tabRow.row]
let url = URL(string: Constants.URL+Constants.DELETESHOPPINGLIST+String(shoppingList.id))!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "DELETE"
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
Alamofire.request(urlRequest).responseJSON { response in
if response.response?.statusCode == Constants.STATUS_OK
{
Singlenton.instance.arrayAllShoppingList.remove(at: tabRow.row)
self.shoppingListTableV.reloadData()
}else{
self.printMessage(error: "Connection fail")
}
}
}
/*
private func tableView(_ tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "toSegueProductsShopList"{
let indexPath = shoppingListTableV.indexPathForSelectedRow! as IndexPath
Singlenton.instance.currentShoppingList = Singlenton.instance.arrayAllShoppingList[(indexPath as NSIndexPath).row]
}
}
}
|
//
// LocationsMapDelegate.swift
// EFI
//
// Created by LUIS ENRIQUE MEDINA GALVAN on 8/10/18.
// Copyright © 2018 LUIS ENRIQUE MEDINA GALVAN. All rights reserved.
//
import Foundation
import AsyncDisplayKit
class LocationsMapDelegate:NSObject,MKMapViewDelegate {
override init() {
super.init()
}
}
|
//
// DetailsController.swift
// TaskNew
//
// Created by Joe on 04/05/20.
// Copyright © 2020 jess. All rights reserved.
//
import UIKit
class DetailsController: UIViewController {
@IBOutlet weak var detailsDlabel: UILabel!
@IBOutlet weak var detailsAlabel: UILabel!
@IBOutlet weak var detailsDatelabel: UILabel!
@IBOutlet weak var detailsTlabel: UILabel!
var descr = ""
var amt = ""
var time = ""
var date = ""
override func viewDidLoad() {
super.viewDidLoad()
detailsDlabel.text = descr
detailsAlabel.text = amt
detailsTlabel.text = time
detailsDatelabel.text = date
let maximumLabelSize: CGSize = CGSize(width: 280, height: 9999)
let expectedLabelSize: CGSize = detailsDlabel.sizeThatFits(maximumLabelSize)
// create a frame that is filled with the UILabel frame data
var newFrame: CGRect = detailsDlabel.frame
// resizing the frame to calculated size
newFrame.size.height = expectedLabelSize.height
// put calculated frame into UILabel frame
detailsDlabel.frame = newFrame
}
}
|
import AppKit
import BuildStatusChecker
protocol StatusItemViewDelegate {
func updateMenu()
}
class StatusItemView: NSObject {
private let viewModel: StatusItemViewModel
private let statusItem = NSStatusBar.system.statusItem(withLength:NSStatusItem.variableLength)
init(viewModel: StatusItemViewModel) {
self.viewModel = viewModel
super.init()
viewModel.viewDelegate = self
statusItem.button?.title = viewModel.title
statusItem.button?.image = NSImage(imageLiteralResourceName: "StatusBarButtonImage")
statusItem.menu = NSMenu()
addDefaultMenuItems()
}
func update() {
statusItem.menu = NSMenu()
let branches = [viewModel.master, viewModel.development, viewModel.release, viewModel.hotfix]
for branchBuilds in branches {
for build in branchBuilds {
statusItem.menu?.addItem(statusItem(for: build))
}
}
statusItem.menu?.addItem(NSMenuItem.separator())
for featureBuild in viewModel.feature {
statusItem.menu?.addItem(statusItem(for: featureBuild))
}
addDefaultMenuItems()
}
private func addDefaultMenuItems() {
statusItem.menu?.addItem(NSMenuItem.separator())
statusItem.menu?.addItem(withTitle: "Open Main Window...", action: #selector(AppDelegate.openMainWindow(_:)), keyEquivalent: "")
statusItem.menu?.addItem(withTitle: "Preferences...", action: #selector(AppDelegate.openPreferences(_:)), keyEquivalent: ",")
statusItem.menu?.addItem(NSMenuItem.separator())
statusItem.menu?.addItem(withTitle: "Quit", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
}
@objc func openInBrowser(sender: Any) {
if let item = sender as? NSMenuItem, let build = item.representedObject as? Build {
viewModel.openInBrowser(build: build)
}
}
}
// MARK: - Mapping builds to status items
extension StatusItemView {
func statusItem(for build: BuildRepresentation) -> NSMenuItem {
let statusAttributedString = NSMutableAttributedString()
statusAttributedString.append(NSAttributedString(string: "●", attributes: viewModel.attributes(for: build.wrapped.status)))
statusAttributedString.append(NSAttributedString(string: " \(build.wrapped.branch)"))
if build.subBuilds.isEmpty {
if let info = build.wrapped.info {
statusAttributedString.append(NSMutableAttributedString(string: " - \(info)"))
}
}
else {
for build in build.subBuilds {
if let workflow = build.groupItemDescription {
let workflowAttributedString = NSMutableAttributedString()
workflowAttributedString.append(NSAttributedString(string: " ["))
workflowAttributedString.append(NSAttributedString(string: "●", attributes: viewModel.attributes(for: build.wrapped.status)))
workflowAttributedString.append(NSAttributedString(string: " \(workflow)]"))
statusAttributedString.append(workflowAttributedString)
}
}
}
let menuItem = NSMenuItem(title: build.wrapped.branch, action: #selector(openInBrowser(sender:)), keyEquivalent: "")
menuItem.attributedTitle = statusAttributedString
menuItem.target = self
menuItem.representedObject = build.wrapped
return menuItem
}
}
// MARK: StatusItemViewDelegate
extension StatusItemView: StatusItemViewDelegate {
func updateMenu() {
update()
}
}
|
//
// File.swift
//
//
// Created by Enrique Perez Velasco on 15/07/2020.
//
import Foundation
extension URLComponents {
mutating func setQueryItems(
with parameters: [String: String]
) {
self.queryItems = parameters.map {
URLQueryItem(
name: $0.key,
value: $0.value
)
}
}
}
extension Int {
func boundTo(_ min: Int, _ max: Int) -> Int {
self < min ? min : self > max ? max : self
}
}
|
public struct IdentifiableReferencePathComponent: Hashable {
public let noNormalizedComponent: NotNormalizedReferencePathComponent
public let typeName: TypeName
private let id: ReferenceID
public var hashValue: Int {
return self.id.hashValue
}
public init(id: ReferenceID, typeName: TypeName, noNormalizedComponent: NotNormalizedReferencePathComponent) {
self.id = id
self.typeName = typeName
self.noNormalizedComponent = noNormalizedComponent
}
public func isIdentified(by id: ReferenceID) -> Bool {
return self.id == id
}
public static func ==(lhs: IdentifiableReferencePathComponent, rhs: IdentifiableReferencePathComponent) -> Bool {
return lhs.id == rhs.id
}
}
|
//
// LoadinView.swift
// Udemy1-08 _anime
//
// Created by Mauro Ciargo on 4/25/20.
// Copyright © 2020 Mauro Ciargo. All rights reserved.
//
import SwiftUI
struct LoadinView: View {
@State private var isLoading = false
var body: some View {
ZStack{
Circle()
.stroke(Color.gray, lineWidth: 20)
.frame(width: 200, height: 200)
Circle()
.trim(from: 0.0, to: 0.35)
.stroke(Color.green, lineWidth: 8)
.frame(width: 200, height: 200)
.rotationEffect(Angle(degrees: isLoading ? 360 : 0))
.animation(Animation.linear(duration: 2).repeatForever(autoreverses: false))
.onAppear(){
self.isLoading = true
}
}
}
}
struct LoadinView_Previews: PreviewProvider {
static var previews: some View {
LoadinView()
}
}
|
//
// CampusResourceViewController.swift
// berkeley-mobile
//
// Created by Oscar Bjorkman on 10/31/20.
// Copyright © 2020 ASUC OCTO. All rights reserved.
//
import UIKit
import Firebase
fileprivate let kCardPadding: UIEdgeInsets = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
fileprivate let kViewMargin: CGFloat = 16
class CampusResourceViewController: UIViewController {
private var resourcesCard: CardView!
private var resourcesTable: FilterTableView = FilterTableView<Resource>(frame: .zero, tableFunctions: [], defaultSort: SortingFunctions.sortAlph(item1:item2:))
private var resourceEntries: [Resource] = [] {
didSet {
resourcesTable.setData(data: self.resourceEntries)
resourcesTable.update()
}
}
/// If not empty, this view will present the filtered set of campus resources.
private var resourceFilters: [Filter<Resource>] = []
convenience init(type: ResourceType, notIn: Set<ResourceType>? = nil) {
self.init(inSet: Set<ResourceType>([type]), notIn: notIn)
}
/// If `inSet` is non-nil, will filter resources for those matching those `ResourceType`s.
/// If `notIn` is non-nil, will filter resources for those not in the given set of types.
init(inSet: Set<ResourceType>? = nil, notIn: Set<ResourceType>? = nil) {
super.init(nibName: nil, bundle: nil)
if let types = inSet {
resourceFilters.append(Filter(label: "Type Filter: \(types)", filter: { resource in
guard let resourceType = ResourceType(rawValue: resource.type ?? "") else { return false }
return types.contains(resourceType)
}))
}
if let types = notIn {
resourceFilters.append(Filter(label: "Set Exclusion: \(types)", filter: { resource in
guard let resourceType = ResourceType(rawValue: resource.type ?? "") else { return true }
return !types.contains(resourceType)
}))
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupResourcesList()
DataManager.shared.fetch(source: ResourceDataSource.self) { resourceEntries in
let entries = resourceEntries as? [Resource] ?? []
_ = Filter.apply(filters: self.resourceFilters, on: entries) { entries in
DispatchQueue.main.async { self.resourceEntries = entries }
}
}
}
}
extension CampusResourceViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return resourcesTable.filteredData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: ResourceTableViewCell.kCellIdentifier, for: indexPath) as? ResourceTableViewCell {
if let entry = resourcesTable.filteredData[safe: indexPath.row] {
cell.cellConfigure(entry: entry)
return cell
}
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = CampusResourceDetailViewController(presentedModally: true)
vc.resource = resourcesTable.filteredData[indexPath.row]
present(vc, animated: true)
tableView.deselectRow(at: indexPath, animated: true)
}
}
extension CampusResourceViewController {
func setupResourcesList() {
let card = CardView()
card.layoutMargins = kCardPadding
view.addSubview(card)
card.translatesAutoresizingMaskIntoConstraints = false
card.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor, constant: kViewMargin).isActive = true
card.leftAnchor.constraint(equalTo: view.layoutMarginsGuide.leftAnchor).isActive = true
card.rightAnchor.constraint(equalTo: view.layoutMarginsGuide.rightAnchor).isActive = true
card.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: -kViewMargin).isActive = true
let functions: [TableFunction] = [
Sort<Resource>(label: "Nearby", sort: Resource.locationComparator()),
Filter<Resource>(label: "Open", filter: {resource in resource.isOpen ?? false})
]
resourcesTable = FilterTableView(frame: .zero, tableFunctions: functions, defaultSort: SortingFunctions.sortAlph(item1:item2:), initialSelectedIndices: [0])
resourcesTable.tableView.register(ResourceTableViewCell.self, forCellReuseIdentifier: ResourceTableViewCell.kCellIdentifier)
resourcesTable.tableView.delegate = self
resourcesTable.tableView.dataSource = self
resourcesTable.translatesAutoresizingMaskIntoConstraints = false
card.addSubview(resourcesTable)
resourcesTable.tableView.separatorStyle = .none
resourcesTable.topAnchor.constraint(equalTo: card.layoutMarginsGuide.topAnchor).isActive = true
resourcesTable.leftAnchor.constraint(equalTo: card.layoutMarginsGuide.leftAnchor).isActive = true
resourcesTable.rightAnchor.constraint(equalTo: card.layoutMarginsGuide.rightAnchor).isActive = true
resourcesTable.bottomAnchor.constraint(equalTo: card.layoutMarginsGuide.bottomAnchor).isActive = true
resourcesCard = card
}
}
|
import Foundation
import Yams
import Quick
import Nimble
@testable import SwaggerKit
final class SpecCallbacksTests: QuickSpec {
// MARK: - Instance Methods
override func spec() {
var callbacks: SpecCallbacks!
var callbacksYAML: String!
describe("Subcription callbacks") {
beforeEach {
callbacks = SpecCallbacksSeeds.subscription
callbacksYAML = SpecCallbacksSeeds.subscriptionYAML
}
it("should be correctly decoded from YAML string") {
do {
let decodedCallbacks = try YAMLDecoder.test.decode(
SpecCallbacks.self,
from: callbacksYAML
)
expect(decodedCallbacks).to(equal(callbacks))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
it("should be correctly encoded to YAML string") {
do {
let encodedCallbacksYAML = try YAMLEncoder.test.encode(callbacks)
expect(encodedCallbacksYAML).to(equal(try callbacksYAML.yamlSorted()))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
}
describe(".extensions") {
beforeEach {
callbacks = SpecCallbacksSeeds.subscription
}
it("should return extensions") {
expect(callbacks.extensions as? [String: Bool]).to(equal(["private": true]))
}
it("should modify extensions") {
callbacks.extensions["private"] = false
expect(callbacks.extensions as? [String: Bool]).to(equal(["private": false]))
}
}
}
}
|
//
// JankenModel.swift
// MVCJankenApp
//
// Created by 大塚周 on 2020/12/18.
//
import UIKit
class JankenModel {
private(set) var jankenHand = "✊" {
didSet {
print("値が変えられたので、Keyが「janken」ValueがjankenHandという通知を送った。 from Model")
notificationCenter.post(name: .init(rawValue: "janken"),
object: nil,
userInfo: ["janken":jankenHand])
}
}
let jankenArray = ["✊","✌️","🖐"]
let notificationCenter = NotificationCenter()
func janken(){
let jankenNumber = Int.random(in: 0 ... 2)
jankenHand = jankenArray[jankenNumber]
print("\(jankenHand)が出力された from Model")
}
}
|
//
// AppDelegate.swift
// Teleport
//
// Created by KaMi on 9/5/18.
// Copyright © 2018 Nenad VULIC. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
|
//
// Meme.swift
// MeMe
//
// Created by Leela Krishna Chaitanya Koravi on 12/22/20.
// Copyright © 2020 Leela Krishna Chaitanya Koravi. All rights reserved.
//
import Foundation
import UIKit
struct Meme {
var topText1:String
var bottomText1:String
var originalImage = UIImage()
var memedImage = UIImage()
}
extension Meme {
static var allMemes: [Meme] {
var memeArray = [Meme]()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
memeArray = appDelegate.memes
print("Meme array size: ", memeArray.count)
return memeArray
}
}
|
//
// MovieDetailPresentation.swift
// TMDbMoviesList
//
// Created by Salih Topcu on 30.01.2021.
// Copyright © 2021 Salih Topcu. All rights reserved.
//
import UIKit
struct MovieDetailPresentation: Equatable {
let title: String
let posterImageURL: String
let imageURL: String
let overview: String
let artistName: String
}
|
//
// LoggedInUser+CoreDataClass.swift
// splitwork
//
// Created by Vivek Madhusudan Badrinarayan on 4/25/18.
// Copyright © 2018 Vivek Badrinarayan. All rights reserved.
//
//
import Foundation
import CoreData
import UIKit
public class LoggedInUser: NSManagedObject {
static let shared = LoggedInUser()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
func getAllUsers() -> [LoggedInUser] {
var users = [LoggedInUser]()
do {
users = try context.fetch(LoggedInUser.fetchRequest())
} catch {
print("Error fetching logged in users from CoreData")
}
return users
}
func getUser() -> String? {
if getAllUsers().count == 0 {
return nil
}
return getAllUsers()[0].username
}
func addUser(username: String) {
clear()
let user = LoggedInUser(context: context)
user.username = username
appDelegate.saveContext()
}
func clear() {
for user in getAllUsers() {
context.delete(user)
}
appDelegate.saveContext()
}
}
|
//
// AWAngle.swift
// CalenderPlan
//
// Created by Zihao Arthur Wang [STUDENT] on 1/3/19.
// Copyright © 2019 Zihao Arthur Wang [STUDENT]. All rights reserved.
//
import Foundation
import Cocoa
struct AWAngle {
private var angle: CGFloat
var int: Int {
return Int(angle)
}
var double: Double {
return Double(angle)
}
var float: Float {
return Float(angle)
}
var cgFloat: CGFloat {
return angle
}
init(_ angle: Int) {
self.angle = CGFloat(angle)
self.toUnit()
}
init(_ angle: Float) {
self.angle = CGFloat(angle)
self.toUnit()
}
init(_ angle: Double) {
self.angle = CGFloat(angle)
self.toUnit()
}
init(_ angle: CGFloat) {
self.angle = angle
self.toUnit()
}
}
//MARK: some basic operations
extension AWAngle {
mutating func toUnit() {
angle = angle.remainder(dividingBy: 360)
angle += angle < 0 ? 360 : 0
}
func minus(angle: AWAngle, clockwise: Bool) -> AWAngle {
if clockwise {
return AWAngle(angle.angle-self.angle)
} else {
return AWAngle(self.angle-angle.angle)
}
}
func plus(angle: AWAngle, clockwise: Bool) -> AWAngle {
if clockwise {
return AWAngle(angle.angle-self.angle)
} else {
return AWAngle(self.angle+angle.angle)
}
}
}
|
//
// IOTPEvent.swift
// IOTrace
//
// Created by Jagni Bezerra on 07/12/2018.
// Copyright © 2018 IBM. All rights reserved.
//
import Foundation
import SwiftyJSON
import SwiftDate
class IOTPEvent : Comparable {
static func < (lhs: IOTPEvent, rhs: IOTPEvent) -> Bool {
return lhs.date < rhs.date
}
static func == (lhs: IOTPEvent, rhs: IOTPEvent) -> Bool {
return lhs.id == rhs.id
}
var timestamp = ""
var id = ""
init(json: JSON) {
self.timestamp = json["timestamp"].stringValue
self.id = json["id"].stringValue
}
init(smallJSON: JSON) {
self.timestamp = Date().toISO()
self.id = self.timestamp
}
var date : Date {
return self.timestamp.toISODate(nil, region: Region.current)!.date
}
var dateString : String {
return self.date.toFormat("dd/MM/yyyy")
}
var timeString : String {
return self.date.toString(.time(.short))
}
}
|
//
// ViewController.swift
// LocationPicker
//
// Created by Devarshi on 4/12/18.
// Copyright © 2018 Devarshi. All rights reserved.
//
import CoreLocation
import UIKit
import LocationPickerController
class ViewController: UIViewController, LocationPickerControllerProvider, LocationPickerControllerPresenter, SelectedLocationDelegate {
func selected(location: CLPlacemark) {
}
@IBAction func showLocationPicker(_ sender: Any) {
pushLocationPicker(with: self, provider: self, animated: true, on: self.navigationController)
}
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.
}
}
|
//
// HomeViewController.swift
// HealthSource
//
// Created by Tamilarasu on 10/02/18.
// Copyright © 2018 Tamilarasu. All rights reserved.
//
import UIKit
import HealthKit
fileprivate enum Row{
case followLink
case downloadWrite
case autoDownload
case autoDownloadOverWifiOnly
case unfollowLink
func title() -> String {
switch self {
case .followLink:
return "Paste Link"
case .downloadWrite:
return "Download & Write"
case .autoDownload:
return "Auto Download"
case .autoDownloadOverWifiOnly:
return "Auto Download over WiFi only"
case .unfollowLink:
return "Unfollow Link"
}
}
}
fileprivate enum Section {
case follow
case downloadWrite
case unfollow
func headerTitle() -> String {
switch self {
case .follow:
return "Download"
case .downloadWrite:
return "Download & Add to HealthKitData"
case .unfollow:
return ""
}
}
func footerTitle() -> String {
switch self {
case .follow:
return "Paste the dropbox link which shared from another device."
case .downloadWrite:
return "If the link is valid then it will keep on downloading the data from dropbox and it will write to HealthKit."
case .unfollow:
return "By clicking this will stop downloading the data from above link."
}
}
func rows() -> [Row] {
switch self {
case .follow:
return [.followLink]
case .downloadWrite:
return [.downloadWrite, .autoDownload, .autoDownloadOverWifiOnly]
case .unfollow:
return [.unfollowLink]
}
}
}
//let homeRangeSegueIdentifier = "HomeToRangeSegue"
//let zipFilePasteBoardString = "public.zip-archive"
//let jpgFilePasteBoardString = "public.image"
class DropboxDownloadVIewController: UIViewController, DateRangeViewControllerDelegate {
@IBOutlet weak var tableView: UITableView!
private let sections:[Section] = [.follow,
.downloadWrite,
.unfollow]
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Download"
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = UITableViewAutomaticDimension
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.destination is DateRangeViewController {
if let dateRangeVC: DateRangeViewController = segue.destination as? DateRangeViewController {
dateRangeVC.dateRange = dateRange
weak var weakSelf = self
dateRangeVC.dateRangeDelegate = weakSelf
}
}
}
//MARK: DateRangeViewController Delegate
func didChangeRange(newDateRange: DateRange) {
dateRange = newDateRange
tableView.reloadData()
}
}
extension DropboxDownloadVIewController: UITableViewDelegate,UITableViewDataSource {
//MARK: TableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].rows().count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = UITableViewCell()
var row = sections[indexPath.section].rows()[indexPath.row]
cell.textLabel?.text = row.title()
// switch row {
// case .range:
// cell = UITableViewCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: nil)
// cell.textLabel?.text = row.title()
// cell.detailTextLabel?.text = dateRange.displayText()
// cell.detailTextLabel?.numberOfLines = 0
// cell.accessoryType = .disclosureIndicator
// case .shareWithDropbox:
// cell.accessoryType = .disclosureIndicator
// default:
//// cell.textLabel?.textColor = cell.textLabel?.tintColor
// }
return cell
}
//MARK: TableViewDelegate
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section].headerTitle()
}
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return sections[section].footerTitle()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let row = sections[indexPath.section].rows()[indexPath.row]
switch row {
case .followLink:
followLink()
case .autoDownload:
autoDownload()
case .autoDownloadOverWifiOnly:
autoDownloadOverWiFiOnly()
case .unfollowLink:
unFollowLink()
case .downloadWrite:
downloadAndWrite()
}
}
}
extension DropboxDownloadVIewController {
//Selections
func followLink() {
}
func downloadAndWrite(){
}
func autoDownload() {
}
func autoDownloadOverWiFiOnly() {
}
func unFollowLink() {
}
}
|
//
// GLLoginModalVC.swift
// GameleySDK
//
// Created by Fitz Leo on 2018/6/12.
// Copyright © 2018年 Fitz Leo. All rights reserved.
//
import UIKit
class GLLoginModalVC: FitzPopUp, UITextFieldDelegate {
@IBOutlet weak var segmentControl: UISegmentedControl!
@IBOutlet weak var contentView: UIView!
@IBOutlet weak var loginView: UIView!
@IBOutlet weak var loginContentView: UIView!
// 快速注册成功view
@IBOutlet weak var quickRegisterView: UIView!
@IBOutlet weak var quickAccountLabel: UILabel!
@IBOutlet weak var quickPasswdLabel: UILabel!
var isRegister = true
// 注册view
@IBOutlet weak var registerPhoneView: UIView!
@IBOutlet weak var registerPhoneField: UITextField!
@IBOutlet weak var registerCodeField: UITextField!
@IBOutlet weak var registerSendCodeBtn: UIButton!
@IBOutlet weak var registerPasswdField: UITextField!
@IBOutlet weak var registerRepasswdField: UITextField!
@IBOutlet weak var registerBtn: UIButton!
// 重置密码 复用注册view
@IBOutlet weak var registerResetViewTitle: UILabel!
var currentTextField: UITextField?
var registerPhoneFieldCheck: Bool {
get {
guard let phoneNum = registerPhoneField.text, phoneNum.count == 13 else {
return false
}
return true
}
}
var registerCodeFieldCheck: Bool {
get {
guard let code = registerCodeField.text, code.count == 4 else {
return false
}
return true
}
}
var registerPasswdFieldCheck: (Bool, String) {
get {
let passwdPattern = "^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*).{6,16}$"
guard let passwd = registerPasswdField.text, let repasswd = registerRepasswdField.text else {
return (false, "密码不能为空")
}
guard GLUtil.GLRegex(passwdPattern).match(input: passwd) else {
return (false, "密码必须为6-16位,同时包含大小写字母和数字")
}
guard passwd == repasswd else {
return (false, "两次密码不一致")
}
return (true, "")
}
}
var countdownTimer: Timer?
var isCounting = false {
willSet {
if newValue {
countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime(timer:)), userInfo: nil, repeats: true)
remainingSeconds = 60
} else {
countdownTimer?.invalidate()
countdownTimer = nil
}
registerSendCodeBtn.isEnabled = !newValue
}
}
var remainingSeconds = 0 {
willSet{
registerSendCodeBtn.setTitle("\(newValue) 秒", for: .normal)
registerSendCodeBtn.setTitleColor(UIColor(red:0.13, green:0.51, blue:0.97, alpha:1.00), for: .normal)
if newValue <= 0 {
registerSendCodeBtn.setTitle("重新获取", for: .normal)
isCounting = false
}
}
}
// end 注册view
@IBOutlet weak var qqLoginBtn: UIButton! {
didSet{
if !GameleySDK.shared.registedType[.qq]! {
qqLoginBtn.isEnabled = false
}
}
}
@IBOutlet weak var wxLoginBtn: UIButton! {
didSet{
if !GameleySDK.shared.registedType[.weChat]! {
wxLoginBtn.isEnabled = false
}
}
}
@IBOutlet weak var wbLoginBtn: UIButton! {
didSet{
if !GameleySDK.shared.registedType[.weibo]! {
wbLoginBtn.isEnabled = false
}
}
}
let loginAccountView = GLLoginAccountVC(nibName: "GLLoginAccountVC", bundle: GameleySDK.shared.GLBundle)
let loginPhoneView = GLLoginPhoneVC(nibName: "GLLoginPhoneVC", bundle: GameleySDK.shared.GLBundle)
// 根据第三方初始化信息 判断是否启用第三方登录按钮
func initOAuthButton(_ btn: UIButton) {
btn.isEnabled = false
}
override func viewDidLoad() {
super.viewDidLoad()
segmentControl.addUnderlineForSelectedSegment()
// Do any additional setup after loading the view.
addChildViewController(loginPhoneView)
addChildViewController(loginAccountView)
loginContentView.addSubview(loginPhoneView.view)
loginContentView.addSubview(loginAccountView.view)
registerPhoneField.setBottomBorder()
registerCodeField.setBottomBorder()
registerPasswdField.setBottomBorder()
registerRepasswdField.setBottomBorder()
NotificationCenter.default.addObserver(self, selector: #selector(kbFrameChanged(_:)), name: .UIKeyboardWillChangeFrame, object: nil)
registerPhoneField.delegate = self
registerCodeField.delegate = self
registerRepasswdField.delegate = self
registerRepasswdField.delegate = self
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
@IBAction func removeView(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
// segmented changed
@IBAction func segmentChange(_ sender: UISegmentedControl) {
segmentControl.segmentedControlValueChanged()
switch sender.selectedSegmentIndex {
case 0:
loginContentView.bringSubview(toFront: loginAccountView.view)
case 1:
loginContentView.bringSubview(toFront: loginPhoneView.view)
default:
return
}
}
// login action
@IBAction func qqLogin(_ sender: UIButton) {
MonkeyKing.oauth(for: .qq, scope: "get_user_info") { [weak self] (info, resp, err) in
guard let unwrappedInfo = info, let token = unwrappedInfo["access_token"] as? String, let openID = unwrappedInfo["openid"] as? String else {
KRProgressHUD.showError(withMessage: "登录失败")
return
}
self?.xLogin(type: .oauthQQ, params: ["accessToken": token, "openId": openID])
}
}
@IBAction func wxLogin(_ sender: UIButton) {
MonkeyKing.oauth(for: .weChat) { [weak self] (dic, resp, err) in
guard let code = dic?["code"] as? String else {
KRProgressHUD.showError(withMessage: "登录失败")
return
}
self?.xLogin(type: .oauthWx, params: ["code": code])
}
}
@IBAction func wbLogin(_ sender: UIButton) {
MonkeyKing.oauth(for: .weibo) { [weak self] (info, response, error) in
guard let unwrappedInfo = info, let token = (unwrappedInfo["access_token"] as? String) ?? (unwrappedInfo["accessToken"] as? String), let userID = (unwrappedInfo["uid"] as? String) ?? (unwrappedInfo["userID"] as? String) else {
KRProgressHUD.showError(withMessage: "登录失败")
return
}
self?.xLogin(type: .oauthWb, params: ["accessToken": token, "uid": userID])
}
}
@IBAction func quickLogin(_ sender: UIButton) {
KRProgressHUD.show()
//todo 判断是否快速注册过
GameleyNetwork.shared.glRequest(.quickRegister, parameters: [:], addMask: false) { [weak self] (resp: GLQuickRegisterResp) in
guard resp.state == 0, let info = resp.info else {
KRProgressHUD.showError(withMessage: resp.msg)
return
}
guard let `self` = self else { return }
self.contentView.bringSubview(toFront:self.quickRegisterView)
self.quickAccountLabel.text = info.account
self.quickPasswdLabel.text = info.passwd
LocalStore.save(key: .userToken, info: info.token)
if let quickInfoImg = self.getQuickInfoImg() {
UIImageWriteToSavedPhotosAlbum(quickInfoImg, nil, nil, nil)
KRProgressHUD.showInfo(withMessage: "账号信息已保存到相册")
return
}
KRProgressHUD.dismiss()
}
}
func xLogin(type: GLConfig.GLRequestURL, params: [String: Any]) {
GameleyNetwork.shared.glRequest(type, parameters: params) { [weak self] (resp: GLOauthResp) in
guard let info = resp.info, let token = info.token else {
KRProgressHUD.showError(withMessage: "获取数据失败")
return
}
KRProgressHUD.dismiss()
LocalStore.save(key: .userToken, info: token)
GameleyApiHandler.shared.getUserInfo{ userInfo in
self?.dismiss(animated: false, completion: nil)
GameleySDK.shared.didLogin(userInfo: userInfo)
}
}
}
@IBAction func startGame(_ sender: UIButton) {
KRProgressHUD.showOn(self).show()
GameleyApiHandler.shared.getUserInfo(addMask: false) { [weak self] userInfo in
self?.dismiss(animated: false, completion: nil)
GameleySDK.shared.didLogin(userInfo: userInfo)
}
}
@IBAction func registerPhoneAction(_ sender: UIButton) {
isRegister = true
setRegisterView()
contentView.bringSubview(toFront: registerPhoneView)
}
@IBAction func resetPasswdAction(_ sender: UIButton) {
isRegister = false
setRegisterView()
contentView.bringSubview(toFront: registerPhoneView)
}
func setRegisterView() {
if isRegister {
registerResetViewTitle.text = "手机注册"
registerBtn.setTitle("注册", for: .normal)
} else {
registerResetViewTitle.text = "忘记密码"
registerBtn.setTitle("提交", for: .normal)
}
registerPhoneField.text = ""
registerCodeField.text = ""
registerPasswdField.text = ""
registerRepasswdField.text = ""
}
// 保存为UIImage
open func getQuickInfoImg() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(quickRegisterView.bounds.size, true, 0.0)
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
quickRegisterView.layer.render(in: context)
let quickInfo = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return quickInfo
}
// 弹出键盘
@objc func kbFrameChanged(_ notification : Notification) {
let info = notification.userInfo
let kbRect = (info?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
var offsetY = kbRect.origin.y - UIScreen.main.bounds.height
guard let curText = currentTextField else {
if offsetY != 0 {
offsetY = -60
}
UIView.animate(withDuration: 0.3) {
self.contentView.transform = CGAffineTransform(translationX: 0, y: offsetY)
}
return
}
if offsetY != 0 {
offsetY = 0 - curText.frame.origin.y
}
UIView.animate(withDuration: 0.3) {
self.contentView.transform = CGAffineTransform(translationX: 0, y: offsetY)
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
currentTextField = textField
}
//------------------------------手机注册--------------------------------
@objc func updateTime(timer: Timer) {
// 计时开始时,逐秒减少remainingSeconds的值
remainingSeconds -= 1
}
@IBAction func removePhoneRegisterView(_ sender: UIButton) {
contentView.bringSubview(toFront: loginView)
}
@IBAction func getVerifyCode(_ sender: UIButton) {
view.endEditing(true)
guard registerPhoneFieldCheck else {
KRProgressHUD.showError(withMessage: "手机号格式错误")
return
}
var url = GLConfig.GLRequestURL.sendRegisterPhoneCode
var params = ["phone": registerPhoneField.text!.replacingOccurrences(of: "-", with: "")]
if !isRegister {
url = GLConfig.GLRequestURL.passwdResetSendCode
params = ["account": registerPhoneField.text!.replacingOccurrences(of: "-", with: "")]
}
GameleyNetwork.shared.glRequest(url, parameters: params, encoding: URLEncoding(destination: .queryString)) { [weak self] (resp: GLBaseResp) in
guard resp.state == 0 else {
KRProgressHUD.showError(withMessage: resp.msg)
return
}
KRProgressHUD.showSuccess()
self?.isCounting = true
}
}
@IBAction func registerPhone(_ sender: UIButton) {
guard registerPhoneFieldCheck, registerCodeFieldCheck else{
KRProgressHUD.showError(withMessage: "后几号或验证码格式错误")
return
}
guard registerPasswdFieldCheck.0 else {
KRProgressHUD.showError(withMessage: registerPasswdFieldCheck.1)
return
}
let passwd = registerPasswdField.text!.sha1()!.replacingOccurrences(of: " ", with: "").lowercased()
let phoneNum = registerPhoneField.text!.replacingOccurrences(of: "-", with: "")
let code = registerCodeField.text!
if isRegister {
GameleyNetwork.shared.glRequest(.phoneRegister, parameters: ["phone": phoneNum, "passwd": passwd, "repasswd": passwd]) { [weak self] (resp: GLOauthResp) in
guard resp.state == 0, let info = resp.info, let token = info.token else {
KRProgressHUD.showError(withMessage: resp.msg)
return
}
KRProgressHUD.dismiss()
LocalStore.save(key: .userToken, info: token)
GameleyApiHandler.shared.getUserInfo { [weak self] userInfo in
self?.dismiss(animated: false, completion: nil)
GameleySDK.shared.didLogin(userInfo: userInfo)
}
}
} else {
GameleyNetwork.shared.glRequest(.passwdResetCheck,parameters: ["phone": phoneNum, "code": code]) { (resp: GLBaseResp) in
guard resp.state == 0 else {
KRProgressHUD.showError(withMessage: resp.msg)
return
}
KRProgressHUD.dismiss()
GameleyNetwork.shared.glRequest(.passwdReset, parameters: ["phone": phoneNum, "code": code, "passwd": passwd, "repasswd": passwd]) { [weak self] (resp: GLBaseResp) in
guard resp.state == 0, let `self` = self else {
KRProgressHUD.showError(withMessage: resp.msg)
return
}
KRProgressHUD.showSuccess(withMessage: "修改成功")
self.contentView.bringSubview(toFront: self.loginView)
self.currentTextField = nil
}
}
}
}
//---------------------------------------------------------------------
}
|
import UIKit
public class ConstraintKeyboardHandler: KeyboardHandler {
public var constraint: NSLayoutConstraint?
public weak var view: UIView?
public init() {}
public func willShow(info: KeyboardInfo) {
constraint?.constant = -info.height
UIView.animateWithDuration(info.duration, delay: 0, options: info.animation, animations: { [weak self] in
self?.view?.layoutIfNeeded()
}, completion: nil)
}
public func willHide(info: KeyboardInfo) {
constraint?.constant = 0
UIView.animateWithDuration(info.duration, delay: 0, options: info.animation, animations: { [weak self] in
self?.view?.layoutIfNeeded()
}, completion: nil)
}
}
|
//
// NamazModel.swift
// Gamification
//
// Created by Nurbek on 5/3/20.
// Copyright © 2020 Nurbek. All rights reserved.
//
struct namaz {
var id: Int!
var name: String!
var isDone: Bool!
}
|
//
// TrendingListCell.swift
// MovieOpedia
//
// Created by Sayantan Chakraborty on 08/02/19.
// Copyright © 2019 Sayantan Chakraborty. All rights reserved.
//
import UIKit
class TrendingListCell: UITableViewCell {
@IBOutlet weak var moviePoster: UIImageView!
@IBOutlet weak var movieTitle: UILabel!
@IBOutlet weak var movieAvgVotes: UILabel!
@IBOutlet weak var movieTotVotes: UILabel!
//@IBOutlet weak var movieSummary: UILabel!
@IBOutlet weak var containView: UIView!
var dropShadowLayer: CAShapeLayer?
@IBOutlet weak var releaseDate: UILabel!
@IBOutlet weak var accView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
//self.layer.insertSublayer(, at: 0)
}
override func layoutSubviews() {
super.layoutSubviews()
moviePoster.layer.cornerRadius = 6
moviePoster.clipsToBounds = true
accView.layer.cornerRadius = 2
accView.clipsToBounds = true
if let dSL = dropShadowLayer{
dSL.removeFromSuperlayer()
}
dropShadowLayer = containView.dropShadow()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setup(trendingItem:Items?){
if let item = trendingItem,let backdropUrl = item.backdrop_path{
moviePoster.loadImageFromImageUrlFromCache(url: backdropUrl)
movieTitle.text = item.title
movieAvgVotes.text = "\(item.vote_average)"
movieTotVotes.text = "\(item.vote_count) votes"
//movieSummary.text = trendingItem.overview
releaseDate.text = "Release Date: \(item.releaseDate)"
}
}
}
|
//
// AccountViewController.swift
// WatchList
//
// Created by Alex Grimes on 7/24/19.
// Copyright © 2019 Alex Grimes. All rights reserved.
//
import UIKit
class AccountViewController: UIViewController {
@IBOutlet weak var logoutButton: UIButton!
@IBAction func logoutButtonTapped(_ sender: Any) {
guard let appDel = UIApplication.shared.delegate as? AppDelegate else { return }
let rootController = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "WelcomeNavigation")
appDel.window?.rootViewController = rootController
Defaults.clearUserData()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
|
//
// ViewController.swift
// MyMusicApp
//
// Created by mac on 2020/10/24.
// Copyright © 2020 Seokjin. All rights reserved.
//
import UIKit
/*
- 트랙 모델 만들기
- 트랙 리스트 만들기
- tableviewdatasource, delegate
- 커스텀 테이블뷰 셀
- 뷰 구성하기
*/
class TrackListViewController: UIViewController {
let tableView = UITableView()
var musicTrackList: [Track] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(TrackCell.self, forCellReuseIdentifier: "Cell")
tableView.rowHeight = 80
loadTrackList()
setupUI()
}
func loadTrackList() {
musicTrackList = [
Track(title: "Swish", thumb:#imageLiteral(resourceName: "Swish"), artist: "Tyga"),
Track(title: "Dip", thumb: #imageLiteral(resourceName: "Dip"), artist: "Tyga"),
Track(title: "The Harlem Barber Swing", thumb: #imageLiteral(resourceName: "The Harlem Barber Swing"), artist: "Jazzinuf"),
Track(title: "Believer", thumb: #imageLiteral(resourceName: "Believer"), artist: "Imagine Dragon"),
Track(title: "Blue Birds", thumb: #imageLiteral(resourceName: "Blue Birds"), artist: "Eevee"),
Track(title: "Best Mistake", thumb: #imageLiteral(resourceName: "Best Mistake"), artist: "Ariana Grande"),
Track(title: "thank u, next", thumb: #imageLiteral(resourceName: "thank u, next"), artist: "Ariana Grande"),
Track(title: "7 rings", thumb: #imageLiteral(resourceName: "7 rings"), artist: "Ariana Grande"),
]}
private func setupUI() {
tableView.frame = view.frame
tableView.backgroundColor = .white
view.addSubview(tableView)
}
}
//MARK: - TableViewDataSource
extension TrackListViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return musicTrackList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? TrackCell else {
return UITableViewCell()
}
let track = musicTrackList[indexPath.row]
cell.thumbnail.image = track.thumb
cell.artistLabel.text = track.artist
cell.titleLabel.text = track.title
return cell
}
}
//MARK: - TableViewDataSource
extension TrackListViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Title: \(musicTrackList[indexPath.row].title), Artist:\(musicTrackList[indexPath.row].artist)")
let playerVC = PlayerViewController()
playerVC.modalPresentationStyle = .fullScreen
playerVC.track = musicTrackList[indexPath.row]
present(playerVC, animated: true)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.