text stringlengths 8 1.32M |
|---|
import Foundation
import Combine
public enum Loadable<T> {
case notRequested
case loading
case success(T)
case failure(Error)
var value: T? {
switch self {
case let .success(last): return last
default: return nil
}
}
var error: Error? {
switch self {
case let .failure(error): return error
default: return nil
}
}
}
public extension Publisher {
func sinkToLoadable(_ completion: @escaping (Loadable<Output>) -> Void) -> AnyCancellable {
sink(receiveCompletion: {
if case let .failure(error) = $0 {
completion(.failure(error))
}
}, receiveValue: {
completion(.success($0))
})
}
func assignToLoadable<Root>(to keyPath: ReferenceWritableKeyPath<Root, Loadable<Self.Output>>, on object: Root) -> AnyCancellable {
sinkToLoadable { value in
object[keyPath: keyPath] = value
}
}
}
|
//
// PhotoCollectionViewCell.swift
// Photo Studio
//
// Created by Дмитро Мостовий on 31.01.2021.
//
import UIKit
protocol PhotoCollectionViewCellProtocol {
func display(imageUrl: String?)
}
class PhotoCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
resetContent()
setupView()
}
override func prepareForReuse() {
super.prepareForReuse()
resetContent()
}
private func resetContent() {
// imageView.image = nil
}
private func setupView() {
}
}
extension PhotoCollectionViewCell: PhotoCollectionViewCellProtocol {
func display(imageUrl: String?) {
}
}
|
//
// TaskViewController.swift
// Fabric
//
// Created by Samantha Lauer on 2016-02-11.
// Copyright © 2016 Samantha Lauer. All rights reserved.
//
import UIKit
class TaskViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate {
//MARK: Properties
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var saveButton: UIBarButtonItem!
@IBOutlet weak var descTextField: UITextField!
@IBOutlet weak var dueDatePicker: UIDatePicker!
@IBOutlet weak var publicSwitch: UISwitch!
@IBOutlet weak var sendToButton: UIButton!
@IBOutlet weak var listContactsForSending: UILabel!
@IBAction func SelectingDate(sender: AnyObject) {
let currDate = NSDate()
self.dueDatePicker.minimumDate = currDate
}
/*
@IBOutlet weak var dueDatePicker: UIDatePicker!
This value is either passed by `TaskTableViewController` in `prepareForSegue(_:sender:)`
or constructed as part of adding a new task.
*/
var task: Task?
var origin: String?
var origin_idx: Int?
var receivingContacts: String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Handle the text field's user input through delegate callbacks
nameTextField.delegate = self
// Set up views if editing an existing Task.
if let task = task {
navigationItem.title = task.name
nameTextField.text = task.name
descTextField.text = task.desc
dueDatePicker.date = task.dueDate!
publicSwitch.on = task.visible
listContactsForSending.text = ""
dueDatePicker.minimumDate = NSDate()
}
listContactsForSending.text = ""
//Enable the Save button only if the text field has a valid Task name.
checkValidTaskName()
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(textField: UITextField) {
checkValidTaskName()
navigationItem.title = textField.text
}
func textFieldDidBeginEditing(textField: UITextField) {
// Disable the Save button while editing.
saveButton.enabled = false
}
func checkValidTaskName() {
// Disable the Save button if the text field is empty.
let text = nameTextField.text ?? ""
saveButton.enabled = !text.isEmpty
}
//MARK:Navigation
@IBAction func cancel(sender: UIBarButtonItem) {
// Depending on style of presentation (modal or push presentation), this view controller needs to be dismissed in two different ways.
//let isPresentingInAddTaskMode = presentingViewController is UINavigationController
let isPresentingInAddTaskMode = presentingViewController is UITabBarController
if isPresentingInAddTaskMode {
dismissViewControllerAnimated(true, completion: nil)
} else {
navigationController!.popViewControllerAnimated(true)
}
}
@IBAction func unwindToTask(sender: UIStoryboardSegue) {
if let sourceViewController = sender.sourceViewController as? recipientTableViewController {
for cell in sourceViewController.tableView.visibleCells as! [recipientTableCell] {
if cell.sending.on {
if (cell.nameLabel.text != nil) {
let user = cell.nameLabel.text
receivingContacts += String(user!) + ", "
}
}
}
}
listContactsForSending.text = receivingContacts
}
//This method lets you configure a view controller before it's presented.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if saveButton === sender {
let name = nameTextField.text ?? ""
let desc = descTextField.text ?? ""
let dueDate = dueDatePicker.date ?? NSDate()
let status = "Current"
let visible = publicSwitch.on ?? true
// set the task to be passed to TaskTableViewController after the unwind segue.
print("taskview prepareforsegue")
print(receivingContacts)
if receivingContacts == "" {
task = Task(name: name, desc: desc, dueDate: dueDate, status: status, visible: visible)
} else {
task = Task(name: name, desc: desc, dueDate: dueDate, status: "ToBeSent " + receivingContacts, visible: true)
}
if origin != nil {
navigationController!.popViewControllerAnimated(false)
} else {
navigationController!.popViewControllerAnimated(true)
}
}
}
}
|
//
// BandDataSource.swift
// Fusion
//
// Created by Charles Imperato on 12/23/18.
// Copyright © 2018 Wind Valley Software. All rights reserved.
//
import Foundation
import wvslib
class BandDataSource {
// - Fetches band member info
func fetchBand(_ onSuccess: @escaping (_ members: [Member]) -> (), _ onFailure: @escaping (_ error: String) -> ()) {
let request = MembersRequest()
request.sendRequest { (result) in
DispatchQueue.main.async {
switch result {
case .error(let error):
log.error("Unable to fetch the band members. \(error)")
onFailure(error.localizedDescription)
case .success(let data):
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any], let membersJson = json["members"] {
let members = try JSONDecoder.init().decode([Member].self, from: try JSONSerialization.data(withJSONObject: membersJson))
onSuccess(members)
}
else {
onFailure(JSONError.notFound.localizedDescription)
}
}
catch {
onFailure(error.localizedDescription)
}
}
}
}
}
}
|
//
// MessageList.swift
// Lenna
//
// Created by MacBook Air on 7/8/19.
// Copyright © 2019 sdtech. All rights reserved.
//
import UIKit
protocol ListMessageDelegate {
func listMessage(newMessage : String)
}
class MessageList: UITableViewCell, UITableViewDataSource, UITableViewDelegate {
var arrList = [ColumnList]()
var listmessage : ListMessageDelegate?
@IBOutlet weak var imagePaket: UIImageView!
@IBOutlet weak var heightList: NSLayoutConstraint!
@IBOutlet weak var collectionList: UITableView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
collectionList.register(UINib.init(nibName: "ListCell", bundle: nil), forCellReuseIdentifier: "ListCell")
collectionList.delegate = self
collectionList.dataSource = self
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : ListCell = tableView.dequeueReusableCell(withIdentifier: "ListCell", for: indexPath) as! ListCell
cell.descriptionLabel.text = arrList[indexPath.row].text
cell.priceList.text = arrList[indexPath.row].subText
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
listmessage?.listMessage(newMessage: arrList[indexPath.row].defaultAction!.data)
}
}
|
//
// ToyView.swift
// ToyView
//
// Created by Sven Svensson on 28/08/2021.
//
import SwiftUI
struct ToyView: View {
@EnvironmentObject var manager: SOTManager
var toy: Toy
@State private var toyData: Toy.Data = Toy.Data()
@State private var presentToyData = false
func editToyData(){
toyData = toy.data
presentToyData = true
}
func updateToy(){
manager.update(toy, from: toyData)
presentToyData = false
}
func deletToy(){
manager.remove(toy)
presentToyData = false
}
var body: some View {
Form {
ListItemView(toy)
}
.navigationTitle("Toy")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("Edit") { editToyData() }
}
}
.sheet(isPresented: $presentToyData) {
NavigationView {
ToyDataEditView(toyData: $toyData)
.background(LinearGradient.editItemColors)
.navigationTitle("Edit Toy")
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button("Cancel") { presentToyData = false }
}
ToolbarItem(placement: .navigationBarTrailing) {
Button("Done") { updateToy() }
}
ToolbarItem(placement: .bottomBar) {
Button("Delete") { deletToy() }
.foregroundColor(.red)
}
} // Toolbar
} // NavigationView
} // screen
} // body
}
struct ToyView_Previews: PreviewProvider {
static var previews: some View {
NavigationView{
ToyView(toy: Toy.data[0])
}
}
}
|
import Combine
import HsExtensions
class PersonalSupportViewModel {
private let service: PersonalSupportService
private var cancellables = Set<AnyCancellable>()
private let hiddenRequestButtonSubject = CurrentValueSubject<Bool, Never>(false)
private let enabledRequestButtonSubject = CurrentValueSubject<Bool, Never>(false)
private let hiddenRequestingButtonSubject = CurrentValueSubject<Bool, Never>(false)
private let showRequestedScreenSubject = CurrentValueSubject<Bool, Never>(true)
init(service: PersonalSupportService) {
self.service = service
service.$requestButtonState
.sink { [weak self] state in
self?.sync(state: state)
}
.store(in: &cancellables)
subscribe(&cancellables, service.$requested) { [weak self] in self?.showRequestedScreenSubject.send($0) }
sync(state: service.requestButtonState)
showRequestedScreenSubject.send(service.requested)
}
private func sync(state: AsyncActionButtonState) {
var requestButtonEnabled = false
var requestButtonHidden = false
var requestingButtonHidden = false
switch state {
case .enabled:
requestButtonEnabled = true
requestingButtonHidden = true
case .spinner:
requestButtonHidden = true
case .disabled:
requestingButtonHidden = true
}
hiddenRequestButtonSubject.send(requestButtonHidden)
enabledRequestButtonSubject.send(requestButtonEnabled)
hiddenRequestingButtonSubject.send(requestingButtonHidden)
}
}
extension PersonalSupportViewModel {
var showRequestedScreenPublisher: AnyPublisher<Bool, Never> {
showRequestedScreenSubject.eraseToAnyPublisher()
}
var hiddenRequestButtonPublisher: AnyPublisher<Bool, Never> {
hiddenRequestButtonSubject.eraseToAnyPublisher()
}
var enabledRequestButtonPublisher: AnyPublisher<Bool, Never> {
enabledRequestButtonSubject.eraseToAnyPublisher()
}
var hiddenRequestingButtonPublisher: AnyPublisher<Bool, Never> {
hiddenRequestingButtonSubject.eraseToAnyPublisher()
}
var successPublisher: AnyPublisher<Void, Never> {
service.successPublisher.eraseToAnyPublisher()
}
var errorPublisher: AnyPublisher<String, Never> {
service.errorPublisher
.map { _ in "settings.personal_support.failed".localized }
.eraseToAnyPublisher()
}
func onChanged(username: String?) {
service.set(username: username?.trimmingCharacters(in: .whitespaces))
}
func onTapRequest() {
service.request()
}
func onTapNewRequest() {
service.newRequest()
}
}
|
//
// MenuViewController.swift
// GitHub
//
// Created by mac on 7/24/19.
// Copyright © 2019 OwnProjects. All rights reserved.
//
import UIKit
import RealmSwift
import RxSwift
class GithubViewController: BaseGithubViewController {
let disposeBag = DisposeBag()
let githubViewModel = GithubViewModel()
private var reposList = [RepoItemModel]()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.setAttributedTitle()
setSearchBarDelegate()
setGithubTitle()
setupPagination()
setupSwipeRefresh()
listenToReposListResponse()
}
override func setupCellNibNames()
{
self.githubTableView.registerCellNib(cellClass: GithubTableViewCell.self)
}
func listenToReposListResponse()
{
githubViewModel.observableGithubRepoList.subscribe(onNext: { (reposList) in
self.reposList = reposList
self.setTableViewDataSource()
}, onError: { (error) in
print(error)
}, onCompleted: {
print("Completed")
}).disposed(by: disposeBag)
}
func setSearchBarDelegate()
{
self.githubSearchBar.delegate = self
}
func setGithubTitle()
{
self.title = Constants.githubScreenTitle.localized
}
func setTableViewDataSource()
{
self.checkRefreshControlState()
self.removeLoadingMoreView()
self.githubTableView.reloadData()
}
override func swipeRefreshTableView() {
if !self.githubViewModel.userName.isEmpty
{
self.githubViewModel.refreshReposList()
}
else
{
self.checkRefreshControlState()
}
}
override func getCellsCount(with section: Int) -> Int {
return self.reposList.count
}
override func getSectionsCount() -> Int {
return 1
}
override func getCellHeight(indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
override func getCustomCell(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeue() as GithubTableViewCell
let repoItem = self.reposList[indexPath.row]
cell.configureCell(repoItemModel: repoItem)
return cell
}
override func didSelectCellAt(indexPath: IndexPath) {
let repoItem = self.reposList[indexPath.row]
guard let url = URL(string: repoItem.repoUrl) else {
return //be safe
}
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
override func handlePaginationRequest() {
if !self.githubViewModel.isLoadingMore && self.reposList.count > 0
{
self.showLoadingMoreView()
self.githubViewModel.loadMoreRepos()
}
}
}
extension GithubViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
self.githubSearchBar.becomeFirstResponder()
self.githubSearchBar.endEditing(true)
if let searchText = searchBar.text
{
self.githubViewModel.getReposWith(text: searchText)
}
}
}
|
import Foundation
import HandyJSON
extension Data {
public func deserialize<T>() -> T? where T: HandyJSON {
let tObject = T.deserialize(from: String(data: self, encoding: .utf8))
return tObject
}
}
|
//
// GalleryTransition.swift
// Gallery
//
// Created by Migu on 2019/1/18.
// Copyright © 2019 VictorChee. All rights reserved.
//
import UIKit
class GalleryTransition: NSObject {
var isDismissal = false
}
extension GalleryTransition: UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.25
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
guard let toViewController = transitionContext.viewController(forKey: .to) else { return }
if !isDismissal {
container.addSubview(toViewController.view)
}
}
}
|
import Foundation
class AppConfigProvider: IAppConfigProvider {
let fiatDecimal: Int = 2
let maxDecimal: Int = 8
let reachabilityHost = "ipfs.horizontalsystems.xyz"
let apiUrl = "https://ipfs.horizontalsystems.xyz/ipns/Qmd4Gv2YVPqs6dmSy1XEq7pQRSgLihqYKL2JjK7DMUFPVz/io-hs/data"
var testMode: Bool {
return Bundle.main.object(forInfoDictionaryKey: "TestMode") as? String == "true"
}
var defaultWords: [String] {
guard let wordsString = Bundle.main.object(forInfoDictionaryKey: "DefaultWords") as? String else {
return []
}
return wordsString.split(separator: " ", omittingEmptySubsequences: true).map(String.init)
}
var infuraKey: String {
return (Bundle.main.object(forInfoDictionaryKey: "InfuraApiKey") as? String) ?? ""
}
var etherscanKey: String {
return (Bundle.main.object(forInfoDictionaryKey: "EtherscanApiKey") as? String) ?? ""
}
var disablePinLock: Bool {
return Bundle.main.object(forInfoDictionaryKey: "DisablePinLock") as? String == "true"
}
let currencies: [Currency] = [
Currency(code: "USD", symbol: "\u{0024}"),
Currency(code: "EUR", symbol: "\u{20AC}"),
Currency(code: "GBP", symbol: "\u{00A3}"),
Currency(code: "JPY", symbol: "\u{00A5}"),
Currency(code: "AUD", symbol: "\u{20B3}"),
Currency(code: "CAD", symbol: "\u{0024}"),
Currency(code: "CHF", symbol: "\u{20A3}"),
Currency(code: "CNY", symbol: "\u{00A5}"),
Currency(code: "KRW", symbol: "\u{20A9}"),
Currency(code: "RUB", symbol: "\u{20BD}"),
Currency(code: "TRY", symbol: "\u{20BA}")
]
var defaultCoins: [Coin] {
return [
Coin(title: "Bitcoin", code: "BTC", type: .bitcoin),
Coin(title: "Bitcoin Cash", code: "BCH", type: .bitcoinCash),
Coin(title: "Ethereum", code: "ETH", type: .ethereum),
]
}
}
|
//
// AfterRecordViewController.swift
// hecApp-iOS
//
// Created by Asianark on 16/2/16.
// Copyright © 2016年 Asianark. All rights reserved.
//
import UIKit
class AfterRecordViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var bigTableView: UITableView!
@IBOutlet weak var indicatorView: UIActivityIndicatorView!
@IBOutlet weak var promptLabel: UILabel!
@IBOutlet weak var footer: UIView!
var refreshControl:UIRefreshControl?
var menuTag : String = ""
var count : Int = 0
var sortedAfterRecords = [AfterRecord]()
var firstInOrderbyDate = [0]
override func viewDidLoad() {
super.viewDidLoad()
//添加下拉刷新
setupRefreshControl()
bigTableView.delegate = self
bigTableView.dataSource = self
bigTableView.scrollsToTop = true
}
func setupRefreshControl(){
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: #selector(self.onPullToFresh), forControlEvents: UIControlEvents.ValueChanged)
bigTableView.addSubview(refreshControl!)
}
func loadData(){
var hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hud.mode = MBProgressHUDMode.Indeterminate
hud.labelText = "正在获取追号记录"
hud.show(true)
let parameter = ["state": String(self.menuTag) , "offset" : "0" , "limit" : "9"]
AfterRecord.getAfterHistory(parameter){ (afterRecords:[AfterRecord]) -> Void in
self.sortedAfterRecords = afterRecords.sort({self.getNSDate($0.orderTime).compare(self.getNSDate($1.orderTime)) == .OrderedDescending })
self.firstInOrderbyDate = self.getFirstSameDateInArray()
self.bigTableView.reloadData()
hud.removeFromSuperview()
hud = nil
if self.sortedAfterRecords.count < 9 {
self.indicatorView.hidden = true
self.promptLabel.text = "已经加载全部"
self.footer.hidden = false
} else {
self.footer.hidden = true
}
}
}
//下拉刷新
func onPullToFresh() {
let parameter = ["state": String(self.menuTag) , "offset" : "0" , "limit" : "9"]
AfterRecord.getAfterHistory(parameter){ (afterRecords:[AfterRecord]) -> Void in
self.sortedAfterRecords = afterRecords.sort({self.getNSDate($0.orderTime).compare(self.getNSDate($1.orderTime)) == .OrderedDescending })
self.firstInOrderbyDate = self.getFirstSameDateInArray()
self.bigTableView.reloadData()
self.refreshControl?.endRefreshing()
if self.sortedAfterRecords.count < 9 {
self.indicatorView.hidden = true
self.promptLabel.text = "已经加载全部"
self.footer.hidden = false
} else {
self.footer.hidden = true
}
}
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
let offset = scrollView.contentOffset.y
let maxOffset = scrollView.contentSize.height - scrollView.frame.size.height
if (maxOffset - offset) <= 40{
self.indicatorView.startAnimating()
self.promptLabel.text = "正在加载..."
loadSegment(self.sortedAfterRecords.count,limit: 9)
}
}
func loadSegment(offset:Int,limit:Int) {
self.footer.hidden = (offset==0) ? true : false
let parameter = ["state": String(self.menuTag) , "offset" : String(offset) , "limit" : String(limit)]
AfterRecord.getAfterHistory(parameter, done: { (afterRecords:[AfterRecord]) -> Void in
var row = self.sortedAfterRecords.count
for afterRecord in afterRecords {
let indexPath = NSIndexPath(forRow:row,inSection:0)
self.sortedAfterRecords.append(afterRecord)
self.bigTableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
row = row + 1
}
self.sortedAfterRecords = self.sortedAfterRecords.sort({self.getNSDate($0.orderTime).compare(self.getNSDate($1.orderTime)) == .OrderedDescending })
self.firstInOrderbyDate = self.getFirstSameDateInArray()
self.indicatorView.startAnimating()
self.bigTableView.reloadData()
if self.sortedAfterRecords.count < limit {
self.indicatorView.hidden = true
self.promptLabel.text = "已经加载全部"
self.footer.hidden = false
} else {
self.footer.hidden = true
}
})
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.sortedAfterRecords.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let svc = findViewControllerByIdFromStoryboard("AfterRecord",viewControllerId: "RecordDetailViewControllerID") as! RecordDetailViewController
svc.afterNoID = self.sortedAfterRecords[indexPath.row].afterNoID
svc.lotteryType = self.sortedAfterRecords[indexPath.row].lotteryType
naviController!.pushViewController(svc, animated: true)
tableView.deselectRowAtIndexPath(indexPath, animated: false)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("AfterRecordBigCell") as! AfterRecordBigCell
cell.periousLabel.text = String(self.sortedAfterRecords[indexPath.row].totalPeriods - self.sortedAfterRecords[indexPath.row].restPeriods) + "/" + String(self.sortedAfterRecords[indexPath.row].totalPeriods)
cell.lotteryTypeLabel.text = self.sortedAfterRecords[indexPath.row].lotteryType
cell.orderMonLabel.text = "¥" + String(self.sortedAfterRecords[indexPath.row].orderMoney)
cell.winLossLabel.text = String(self.sortedAfterRecords[indexPath.row].winLoss)
cell.selectionStyle = UITableViewCellSelectionStyle.Gray
if(self.sortedAfterRecords[indexPath.row].afterState == 1){
cell.stateLabel.text = "已结束"
cell.periousLabel.textColor = UIColor.AfterRecordtextColor()
cell.statusImg.image = UIImage(named: "icon_time_rect")
} else if (self.sortedAfterRecords[indexPath.row].afterState == 2){
cell.stateLabel.text = "已终止"
cell.periousLabel.textColor = UIColor.AfterRecordtextColor()
cell.statusImg.image = UIImage(named: "icon_tick_rect")
} else if (self.sortedAfterRecords[indexPath.row].afterState == 0) {
cell.stateLabel.text = "进行中"
cell.periousLabel.textColor = UIColor.backGroundColor()
cell.statusImg.image = UIImage(named: "icon_underway_rect")
}
if firstInOrderbyDate.contains(indexPath.row) {
cell.longSeperateLine.hidden = false
cell.shortSeperateLine.hidden = true
cell.DateLabel.text = fromMillToDate(getNSDate(self.sortedAfterRecords[indexPath.row].orderTime)).day.description + "日"
cell.monthLabel.text = fromMillToDate(getNSDate(self.sortedAfterRecords[indexPath.row].orderTime)).month.description + "月"
} else {
cell.longSeperateLine.hidden = true
cell.shortSeperateLine.hidden = false
cell.DateLabel.text = ""
cell.monthLabel.text = ""
}
return cell
}
override func getFirstSameDateInArray() -> [Int]{
var firstInOrderbyDate:[Int] = [0]
for (index,_) in sortedAfterRecords.enumerate(){
if index < sortedAfterRecords.count - 1 {
if (fromMillToDate(getNSDate(sortedAfterRecords[index].orderTime)).month != fromMillToDate(getNSDate(sortedAfterRecords[index+1].orderTime)).month) || (
fromMillToDate(getNSDate(sortedAfterRecords[index].orderTime)).day != fromMillToDate(getNSDate(sortedAfterRecords[index+1].orderTime)).day) {
firstInOrderbyDate.append(index+1)
}
}
}
return firstInOrderbyDate
}
} |
//
// NetworkClient.swift
// ruvSpilari
//
// Created by Hannes Sverrisson on 13/09/2018.
// Copyright © 2018 Rikisutvarpid. All rights reserved.
//
import UIKit
import os
enum APIRequestError: Error {
case url(url: String?)
case parsing(error: Error?)
case network(error: Error?)
}
// NetworkClient singleton handles all network traffic in and out
class NetworkClient {
static var shared = NetworkClient()
private var serverDomain = "http://10.0.1.4:3000"
private let pathname = "/session"
init() {
// Check if Server Domain is set in settings
let defaults = UserDefaults.standard
if let serverDomain = defaults.string(forKey: Constants.serverDomainKey) {
os_log("Server domain from settings: %@", type: .info, serverDomain)
self.serverDomain = serverDomain
}
}
func fetchData(clientID: String, callback: @escaping (Client?, URLResponse?, Error?) -> Void) throws -> Void {
let href: String = serverDomain + pathname + clientID
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 8
let session = URLSession(configuration: config)
if let url = URL(string: href) {
os_log("Fetching href: %@", type: .debug, url.absoluteString)
session.dataTask(with: url) { (data, response, error) in
guard let data = data else {
os_log("Network fetch error", type: .error)
callback(nil, response, error)
return
}
var client: Client? = nil
do {
client = try JSONDecoder().decode(Client.self, from: data)
} catch {
DispatchQueue.main.async {
callback(nil, response, nil)
}
os_log("Error in JSON Model: %@", type: .error, error.localizedDescription)
return
}
if let client = client {
DispatchQueue.main.async {
callback(client, response, nil)
}
} else {
os_log("Client did not decode: %@", type: .error)
}
}.resume()
} else { throw APIRequestError.url(url: href) }
}
// Send data and return the success
func sendDataSynchronously(_ uploadData: Data) -> Bool {
// Check if Server Domain has changed in settings
let defaults = UserDefaults.standard
if let serverDomain = defaults.string(forKey: Constants.serverDomainKey) {
os_log("Server domain from settings: %@", type: .info, serverDomain)
self.serverDomain = serverDomain
}
let href: String = serverDomain + pathname
let semaphore = DispatchSemaphore(value: 0)
var success = false
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 8
let session = URLSession(configuration: config)
if let url = URL(string: href) {
os_log("POST href: %@", type: .debug, url.absoluteString)
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// Upload data
let task = session.uploadTask(with: request, from: uploadData) { data, response, error in
if let error = error {
os_log("POST error: %@", type: .error, error.localizedDescription)
semaphore.signal()
}
guard let response = response as? HTTPURLResponse else {
os_log("POST Server error", type: .error)
semaphore.signal()
return
}
os_log("Server statusCode: %li", type: .debug, response.statusCode)
guard (200...299).contains(response.statusCode) else {
os_log("POST Server error", type: .error)
semaphore.signal()
return
}
if let mimeType = response.mimeType,
mimeType == "application/json",
let data = data,
let dataString = String(data: data, encoding: .utf8) {
os_log("Server response: %@", type: .error, dataString)
success = true
semaphore.signal()
}
}
task.resume()
}
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
return success
}
}
|
//
// AppDelegate.swift
// JSONMapping
//
// Created by BraveShine on 2020/10/5.
//
import Cocoa
import SwiftUI
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var window: NSWindow!
func applicationDidFinishLaunching(_ aNotification: Notification) {
let contentView = ContentView().frame(minWidth: 800, maxWidth: .infinity, minHeight: 400, maxHeight: .infinity)
window = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 960, height: 600),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
backing: .buffered, defer: false)
window.isReleasedWhenClosed = false
window.setFrameAutosaveName("JSONMapping")
window.title = "JSONMapping"
window.contentView = NSHostingView(rootView: contentView)
window.center()
window.makeKeyAndOrderFront(nil)
window.delegate = self
}
@IBAction func preferenceItemClick(_ sender: NSMenuItem) {
openPreferenceWindow()
}
@objc func reOpenWindow(){
for window: NSWindow in NSApplication.shared.windows {
if window == self.window {
window.makeKeyAndOrderFront(self)
}
}
}
@IBAction func reopenMainWindow(_ sender: NSMenuItem) {
reOpenWindow()
}
func openPreferenceWindow(){
let size : NSSize = NSSize(width: 350, height: 200)
let contentView = PreferenceView()
.frame(width: size.width, height: size.height, alignment: .center)
let preferenceWindow = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: size.width, height: size.height),
styleMask: [.titled, .closable,],
backing: .buffered, defer: false)
preferenceWindow.isReleasedWhenClosed = false
preferenceWindow.center()
preferenceWindow.title = NSLocalizedString("Preferences", comment: "")
preferenceWindow.contentView = NSHostingView(rootView: contentView)
preferenceWindow.center()
preferenceWindow.makeKeyAndOrderFront(nil)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
func applicationDockMenu(_ sender: NSApplication) -> NSMenu? {
let menu = NSMenu()
let reopenItem = NSMenuItem(title: NSLocalizedString("JSONMapping", comment: ""), action: #selector(reOpenWindow), keyEquivalent: "O")
let prefreenceItem = NSMenuItem(title: NSLocalizedString("Preferences", comment: ""), action: #selector(preferenceItemClick(_:)), keyEquivalent: "0")
menu.addItem(reopenItem)
menu.addItem(prefreenceItem)
return menu
}
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
if !flag {
reOpenWindow()
return true
}
return true
}
}
extension AppDelegate : NSWindowDelegate{
func windowShouldClose(_ sender: NSWindow) -> Bool {
sender.orderOut(self)
if sender.isZoomed {
return true
}else{
sender.orderOut(self)
}
return false
}
}
|
//
// ViewController.swift
// Convertisseur
//
// Created by Kevin Trebossen on 22/09/18.
// Copyright © 2018 KTD. All rights reserved.
//
import UIKit
// Constantes hors des classes -> EN MAJUSCULE
let DEVISE = "Devises"
let TEMPERATURE = "Température"
let DISTANCE = "Distance"
class ViewController: UIViewController {
// Bouttons du UIcontroller principal
@IBOutlet weak var deviseView: UIView!
@IBOutlet weak var distanceView: UIView!
@IBOutlet weak var temperatureView: UIView!
// Constante
let segueID = "Convert" // Nom de l'identifiant de la SEGUE
var views: [UIView] = [] //
override func viewDidLoad() {
super.viewDidLoad()
views = [deviseView, distanceView, temperatureView]
arrondirLesAngles()
}
// arrondir les angles sur toutes les views
func arrondirLesAngles() {
for v in views {
v.layer.cornerRadius = 10
}
}
// Préparation de la SEGUE
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == segueID { // vérification de l'identifiant de la SEGUE
if let convertController = segue.destination as? ConvertController { // On vérifie si la segue a bien comme destination le ConvertController
convertController.type = sender as? String // On affecte une valeur à la variable type du ConvertController
}
}
}
@IBAction func buttonAction(_ sender: UIButton) {
switch sender.tag {
case 0: performSegue(withIdentifier: segueID, sender: DEVISE)
case 1: performSegue(withIdentifier: segueID, sender: DISTANCE)
case 2: performSegue(withIdentifier: segueID, sender: TEMPERATURE)
default: break
}
}
}
|
//
// GameBoardViewModel.swift
// GameOfLife
//
// Created by Robert Faist on 10/17/20.
// Copyright © 2020 Robert Faist. All rights reserved.
//
import Foundation
import Combine
class GameBoardViewModel: ObservableObject {
let gridSize: Int
var gameBoard: GameBoard
@Published var cells = [Cell]()
var rows: Int {
gridSize
}
var cols: Int {
gridSize
}
init(gridSize: Int = 20){
self.gridSize = gridSize
self.gameBoard = GameBoard(rows: gridSize, cols: gridSize, boardSetup: GameRandom())
self.cells = self.gameBoard.cells
}
func hasCell(row: Int, col: Int) -> Bool {
cells.first(where: { $0.x == row && $0.y == col }) != nil
}
func cell(row: Int, col: Int) -> Cell {
guard let cell = cells.first(where: { $0.x == row && $0.y == col }) else {
return Cell(state: .dead, x: row, y: col)
}
return cell
}
func nextGeneration() {
gameBoard.nextGeneration()
self.cells = gameBoard.cells
}
}
|
//
// GameModel.swift
// Asteroids
//
// Created by Gabriel Robinson on 4/19/19.
// Copyright © 2019 CS4530. All rights reserved.
//
import UIKit
enum Boundary: Int {
case top = 0
case bottom = 1
case left = 2
case right = 3
}
class Game: Codable {
private enum CodingKeys: String, CodingKey {
case leftBoundary
case rightBoundary
case topBoundary
case bottomBoundary
case asteroidsGenerated
case projectileCount
case waveNumber
case numberOfLives
case ship
case projectiles
case asteroids
case playersScore
case asteroidSpeedIncrease
}
var viewProtocols: UpdateViewProtocols?
var leftBoundary: CGFloat?
var rightBoundary: CGFloat?
var topBoundary: CGFloat?
var bottomBoundary: CGFloat?
let twoPi: CGFloat
let piHalves: CGFloat
var asteroidsGenerated: Bool
var asteroidsCount = 0
var projectileCount = 0
var playersScore = 0
var waveNumber = 1
var numberOfLives = 3
var asteroidSpeedIncrease: CGFloat
var ship: Ship
var shipsPreviousAngle: CGFloat?
var projectiles: [Int: Projectile]
var asteroids: [Int: Asteroid]
var updateLock = NSLock()
init(left: CGFloat, right: CGFloat, top: CGFloat, bottom: CGFloat, protocols: UpdateViewProtocols) {
leftBoundary = left
rightBoundary = right
topBoundary = top
bottomBoundary = bottom
ship = Ship()
projectiles = [Int: Projectile]()
asteroids = [Int: Asteroid]()
viewProtocols = protocols
twoPi = 2 * CGFloat.pi
piHalves = CGFloat.pi / 2
asteroidsGenerated = false
projectileCount = 0
waveNumber = 1
numberOfLives = 3
asteroidSpeedIncrease = 0.0
generateAsteroids()
}
// Decodes game model from json
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
leftBoundary = try values.decode(CGFloat.self, forKey: .leftBoundary)
rightBoundary = try values.decode(CGFloat.self, forKey: .rightBoundary)
topBoundary = try values.decode(CGFloat.self, forKey: .topBoundary)
bottomBoundary = try values.decode(CGFloat.self, forKey: .bottomBoundary)
ship = try values.decode(Ship.self, forKey: .ship)
projectiles = try values.decode([Int: Projectile].self, forKey: .projectiles)
asteroids = try values.decode([Int: Asteroid].self, forKey: .asteroids)
asteroidsGenerated = try values.decode(Bool.self, forKey: .asteroidsGenerated)
playersScore = try values.decode(Int.self, forKey: .playersScore)
twoPi = 2 * CGFloat.pi
piHalves = CGFloat.pi / 2
projectileCount = try values.decode(Int.self, forKey: .projectileCount)
waveNumber = try values.decode(Int.self, forKey: .waveNumber)
numberOfLives = try values.decode(Int.self, forKey: .numberOfLives)
asteroidSpeedIncrease = try values.decode(CGFloat.self, forKey: .asteroidSpeedIncrease)
}
// Encodes object into json
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(leftBoundary, forKey: .leftBoundary)
try container.encode(rightBoundary, forKey: .rightBoundary)
try container.encode(topBoundary, forKey: .topBoundary)
try container.encode(bottomBoundary, forKey: .bottomBoundary)
try container.encode(ship, forKey: .ship)
try container.encode(projectiles, forKey: .projectiles)
try container.encode(asteroids, forKey: .asteroids)
try container.encode(waveNumber, forKey: .waveNumber)
try container.encode(numberOfLives, forKey: .numberOfLives)
try container.encode(projectileCount, forKey: .projectileCount)
try container.encode(asteroidsGenerated, forKey: .asteroidsGenerated)
try container.encode(playersScore, forKey: .playersScore)
try container.encode(asteroidSpeedIncrease, forKey: .asteroidSpeedIncrease)
}
// sets the view protocol in the case that the game state is decoded from json
func set(viewProtocols: UpdateViewProtocols) {
self.viewProtocols = viewProtocols
guard let viewProtocols = self.viewProtocols else {
exit(0)
}
for el in asteroids {
viewProtocols.addAsteroid(id: el.key, position: el.value.position, angle: el.value.angle
, size: el.value.size)
}
for el in projectiles {
viewProtocols.addProjectile(id: el.key, angle: el.value.angle, position: el.value.position)
}
viewProtocols.updateLivesNumber(num: numberOfLives)
viewProtocols.updateScore(count: playersScore)
viewProtocols.updateShip(angle: ship.angle)
viewProtocols.updateShipPosition(position: ship.position, isThrusting: false, false)
}
// turns the ship by the specified angle. The angle passed should be in degrees
// and is then transformed into radians.
func turnShip(angle: CGFloat) {
ship.angle += degreesToRadians(angle)
if ship.angle > twoPi {
ship.angle -= twoPi
} else if ship.angle < 0 {
ship.angle += twoPi
}
if let viewProtocols = viewProtocols {
viewProtocols.updateShip(angle: ship.angle)
}
}
// increases the ve
func accelerateShip(_ accelerationRate: CGFloat) {
var shipsTransformationAngle: CGFloat
if accelerationRate < 0 {
if let shipsPreviousAngle = shipsPreviousAngle{
shipsTransformationAngle = shipsPreviousAngle
} else {
shipsPreviousAngle = ship.angle
shipsTransformationAngle = ship.angle
}
} else {
shipsTransformationAngle = ship.angle
shipsPreviousAngle = ship.angle
}
// if the acceleration is less than zero or the velocity
// is less than zero we can return early
if accelerationRate < 0 && ship.velocity <= 0 { return }
// increment the ships velocity by the acceleration rate
if (ship.velocity <= 10.3 && accelerationRate > 0) || accelerationRate < 0 {
ship.velocity += accelerationRate
}
// calculate ships delta vector based on its velocity and angle
let delta = calculateDelta(velocity: ship.velocity, angle: shipsTransformationAngle - piHalves)
// enforce a wrap around effect if the ship goes out of the boundaries
let changeVector = checkWrapAround(delta: delta, position: ship.position)
// change the position of the ship based upon the delta vector
ship.position.x += changeVector.dx
ship.position.y += changeVector.dy
// let the view protocol know to update the view
if let viewProtocols = viewProtocols {
viewProtocols.updateShipPosition(position: ship.position, isThrusting: accelerationRate > 0, false)
}
}
// adds a projectile to the model with the current velocity of the ship plus seven, traveling in the direction
// that the ship is travelling.
func fireProjectile() {
projectiles[projectileCount] = Projectile(angle: ship.angle, velocity: ship.velocity + 7, position: ship.position)
if let viewProtocols = viewProtocols, let projectile = projectiles[projectileCount] {
print("ships angle: \(ship.angle), projectiles angle: \(projectile.angle)")
viewProtocols.addProjectile(id: projectileCount, angle: projectile.angle, position: projectile.position)
}
// only allow 500 projectiles at a time
if projectileCount == 500 {
projectileCount = 0
} else {
projectileCount += 1
}
}
func updateProjectileStates() {
let copy = projectiles
for el in copy {
if let projectile = projectiles[el.key] {
let change = calculateDelta(velocity: el.value.velocity, angle: el.value.angle - piHalves)
projectile.position.x += change.dx
projectile.position.y += change.dy
print("projectile <x, y> : < \(projectile.position.x), \(projectile.position.y)>")
print("left boundary : \(leftBoundary!)")
let outOfBounds = projectileOutOfBounds(projectile: projectile)
if outOfBounds {
if let idx = projectiles.index(forKey: el.key), let viewProtocols = viewProtocols {
viewProtocols.removeProjectile(id: el.key)
projectiles.remove(at: idx)
}
} else if let viewProtocols = viewProtocols {
viewProtocols.updateProjectile(id: el.key, position: projectile.position)
}
}
}
}
// iterates over each asteroid and updates their position based upon their velocity, and
// their direction of travel. This function also changes the position if the asteroid is outside
// the game boundaries so that a wrap around can occur if need be.
//
// Finally, this function checks for collisions with other objects in the game, including projectiles
// and the ship.
func updateAsteroidStates() {
if !asteroidsGenerated { return }
updateLock.lock()
let copyAsteroids = asteroids
for asteroidEl in copyAsteroids {
if let asteroid = asteroids[asteroidEl.key] {
// check for collisions with projectiles
var collidedWithProjectile = false
let copyProjectiles = projectiles
for projectileEl in copyProjectiles {
if asteroid.checkCollision(otherPosition: projectileEl.value.position, radius: Constants.boltWidth / 2) {
playersScore += 1
// remove asteroid
if let viewProtocols = viewProtocols {
viewProtocols.removeAsteroid(id: asteroidEl.key)
viewProtocols.removeProjectile(id: projectileEl.key)
if let idx = asteroids.index(forKey: asteroidEl.key) {
asteroids.remove(at: idx)
}
if let idx = projectiles.index(forKey: projectileEl.key) {
projectiles.remove(at: idx)
}
viewProtocols.updateScore(count: playersScore)
// todo if there is time:
// spawning more asteroids causes issues where asteroids wil freeze in the view
if !asteroid.isShard() {
let velocity = (CGFloat.pi * asteroid.size / 2 * asteroid.size / 2 * asteroid.velocity + Constants.boltWidth * Constants.boltHeight * projectileEl.value.velocity) / 2500
createAsteroid(id: asteroidsCount, asteroid.position, velocity, projectileEl.value.angle + CGFloat.pi / 4, asteroid.size / 4 + 15, isShard: true)
asteroidsCount += 1
createAsteroid(id: asteroidsCount, asteroid.position, velocity, projectileEl.value.angle + 3 * CGFloat.pi / 4, asteroid.size / 4 + 15, isShard: true)
asteroidsCount += 1
createAsteroid(id: asteroidsCount, asteroid.position, velocity, projectileEl.value.angle + 5 * CGFloat.pi / 4, asteroid.size / 4 + 15, isShard: true)
asteroidsCount += 1
createAsteroid(id: asteroidsCount, asteroid.position, velocity, projectileEl.value.angle + 7 * CGFloat.pi / 4, asteroid.size / 4 + 15, isShard: true)
asteroidsCount += 1
}
}
// add 4 smaller ones going in different directions
collidedWithProjectile = true
break
}
}
if collidedWithProjectile { continue }
// check for collisions with the ship
if asteroid.checkCollision(otherPosition: ship.position, radius: Constants.shipSize / 2) {
// stop game wait a few seconds respaw the ship
// set ships position, and velocity to 0
numberOfLives -= 1
ship.position = CGPoint(x: 0.0, y: 0.0)
ship.angle = 0.0
ship.velocity = 0.0
if let viewProtocols = viewProtocols {
viewProtocols.updateLivesNumber(num: numberOfLives)
viewProtocols.updateShipPosition(position: ship.position, isThrusting: false, true)
viewProtocols.updateShip(angle: ship.angle)
}
reloadAsteroidPositions()
if numberOfLives == 0 {
if let viewProtocols = viewProtocols {
viewProtocols.gameOver()
}
}
}
let change = checkWrapAround(delta: calculateDelta(velocity: asteroidEl.value.velocity, angle: asteroidEl.value.angle - piHalves), position: asteroid.position)
asteroid.position.x += change.dx
asteroid.position.y += change.dy
print("asteroid <x, y> : < \(asteroid.position.x), \(asteroid.position.y)>")
print("left boundary : \(leftBoundary!)")
if let viewProtocols = viewProtocols {
viewProtocols.updateAsteroid(id: asteroidEl.key, position: asteroid.position)
}
}
}
updateLock.unlock()
if asteroids.count == 0 {
newWave()
}
}
// Iterates over all asteroids and returns them to their original positions. Used when
// when the players ship dies, and a respawn is to occur
func reloadAsteroidPositions() {
for asteroid in asteroids {
asteroid.value.reloadPosition()
if let viewProtocols = viewProtocols {
viewProtocols.updateAsteroid(id: asteroid.key, position: asteroid.value.position)
}
}
}
// creates asteroids when a wave begins. the number of asteroids is the save as the wave number
// asteroids are placed in random positions on the game boundary, with a random velocity, and a random
// direction of travel
func generateAsteroids() {
updateLock.lock()
if let left = leftBoundary, let right = rightBoundary, let top = topBoundary, let bottom = bottomBoundary {
let numAsteroids = waveNumber
for i in 0...numAsteroids-1 {
let boundary = Boundary(rawValue: Int.random(in: 0...3))!
var xCoordinate: CGFloat = 0.0
var yCoordinate: CGFloat = 0.0
switch boundary {
case .top:
// generate the x coordinate and use the top boundary as the y coordinate
xCoordinate = CGFloat.random(in: left...right)
yCoordinate = top
// generate random velocity in the positive y direction
break
case .bottom:
// generate the x coordinate and use the bottom boundary as the y coordinate
xCoordinate = CGFloat.random(in: left...right)
yCoordinate = bottom
// generate random velocity in the negative y direction
break
case .left:
// generate the y coordinate and use the left boundary as the x coordinate
yCoordinate = CGFloat.random(in: top...bottom)
xCoordinate = left
break
case .right:
// generate the y coordinate and use the right boundary as the x coordinate
yCoordinate = CGFloat.random(in: top...bottom)
xCoordinate = right
// generate random velocity in the negative x direction
break
}
let velocity = CGFloat.random(in: (0.1+asteroidSpeedIncrease)...(1+asteroidSpeedIncrease))
let angle = CGFloat.random(in: 0.0...twoPi)
let size = CGFloat.random(in: 50.0...100.0)
createAsteroid(id: asteroidsCount, CGPoint(x: xCoordinate, y: yCoordinate), velocity, angle, size, isShard: false)
asteroidsCount += 1
}
asteroidsGenerated = true
}
updateLock.unlock()
}
// creates an asteroid with the specified id, position, velcoicty, angle, and size. Invokes the view protocol to add a asteroid
func createAsteroid(id: Int, _ position: CGPoint, _ velocity: CGFloat, _ angle: CGFloat, _ size: CGFloat, isShard: Bool) {
asteroids[id] = Asteroid(angle: angle, velocity: velocity, position: position, size: size, isShard: isShard)
guard let asteroid = asteroids[id] else {
print("asteroid should never be nil")
exit(0)
}
if let viewProtocols = viewProtocols {
viewProtocols.addAsteroid(id: id, position: asteroid.position, angle: asteroid.angle, size: asteroid.size)
}
}
// calculates a change of position vector based upon the angle and velocity of the object.
func calculateDelta(velocity: CGFloat, angle: CGFloat) -> CGVector {
let deltaX = velocity * cos(angle)
let deltaY = velocity * sin(angle)
return CGVector(dx: deltaX, dy: deltaY)
}
func hasAsteroids() -> Bool {
return asteroidsGenerated
}
// changes the position of the object based upon the position and the direction of travel
private func checkWrapAround(delta: CGVector, position: CGPoint)->CGVector {
// Don't let a ship go any further than the screen boundaries.
if let leftBoundary = leftBoundary,
let rightBoundary = rightBoundary,
let topBoundary = topBoundary,
let bottomBoundary = bottomBoundary {
var dx: CGFloat
if position.x < leftBoundary - 15 && delta.dx < 0 {
dx = abs(position.x) + rightBoundary - 10
} else if position.x > rightBoundary + 15 && delta.dx > 0 {
dx = -position.x + leftBoundary + 10
} else {
dx = delta.dx
}
var dy: CGFloat
if position.y < topBoundary - 15 && delta.dy < 0 {
dy = abs(position.y) + bottomBoundary - 10
} else if position.y > bottomBoundary + 15 && delta.dy > 0 {
dy = -position.y + topBoundary + 10
} else {
dy = delta.dy
}
return CGVector(dx: dx, dy: dy)
}
return delta
}
// checks to see if a projectile is out of bounds so that it can be removed
// if it is
private func projectileOutOfBounds(projectile: Projectile) -> Bool {
if let left = leftBoundary,
let right = rightBoundary,
let top = topBoundary,
let bottom = bottomBoundary {
if projectile.position.x < left - 10 {
return true
} else if projectile.position.x > right + 10 {
return true
}
if projectile.position.y < top - 10 {
return true
} else if projectile.position.y > bottom + 10 {
return true
}
}
return false
}
// creates a new wave by incrementing the wave number, the number of lives,
// temporarily setting the asteroidsGenerate flag to halt updates, updates the view,
// adn finally invokes generateAsteroids()
private func newWave() {
asteroidsCount = 0
waveNumber += 1
numberOfLives += 1
if waveNumber % 5 == 0 {
asteroidSpeedIncrease += 0.025
}
self.asteroidsGenerated = false
if let viewProtocols = viewProtocols {
viewProtocols.updateLivesNumber(num: numberOfLives)
}
generateAsteroids()
}
// takes an angle in degrees and returns the angle in radians
private func degreesToRadians(_ angle: CGFloat)->CGFloat {
return angle * CGFloat.pi / 180
}
}
|
//
// topGamesViewController.swift
// desafioZapVivaReal
//
// Created by Mac on 06/02/18.
// Copyright © 2018 Mac. All rights reserved.
//
import UIKit
import CoreData
class TopGamesViewController: UIViewController, FavoriteGame {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var bottomActivityIndicator: UIActivityIndicatorView!
var refreshControl: UIRefreshControl?
var apiRequest: APIRequest?
var games: [Game]?
var filteredGames: [Game]?
var useFilteredArray = false
var indexPathRow: Int?
var page: Int?
var limit: Int?
var favoriteGamesViewController: FavoriteGameViewController?
let network = NetworkManager.sharedInstance
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
//MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.network.reachability.whenUnreachable = { reachability in
self.showOfflinePage()
}
self.refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: #selector(refreshGames), for: .valueChanged)
self.searchBar.showsCancelButton = false
self.searchBar.delegate = self
self.collectionView.addSubview(refreshControl!)
self.activityIndicator.startAnimating()
self.collectionView.isHidden = true
self.games = [Game]()
self.page = 0
self.limit = 20
self.getGames(limit: 20, pages: self.page!)
self.collectionView.reloadData()
self.collectionView.layoutIfNeeded()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.bottomActivityIndicator.isHidden = true
self.getGames(limit: 20, pages: self.page!)
}
//MARK: Methods
func favoriteGame(cell: TopGamesCollectionViewCell) {
let indexPath = self.collectionView.indexPath(for: cell)
self.indexPathRow = indexPath?.row
self.collectionView.reloadData()
}
@objc func refreshGames() {
self.getGames(limit: self.limit!, pages: self.page!)
}
func getGames(limit: Int, pages: Int) {
DispatchQueue.main.async {
APIRequest.shared.getGames(limit: limit, pages: pages, completion: { (gamesResult) in
if !gamesResult.isEmpty {
for game in gamesResult {
self.games?.append(game)
self.collectionView.reloadData()
}
}
self.activityIndicator.stopAnimating()
self.collectionView.isHidden = false
self.bottomActivityIndicator.stopAnimating()
self.bottomActivityIndicator.isHidden = true
self.refreshControl?.endRefreshing()
})
}
}
private func showOfflinePage() -> Void {
DispatchQueue.main.async {
self.performSegue(withIdentifier: "NetworkUnavailable", sender: self)
}
}
}
//MARK: SearchBar
extension TopGamesViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
self.filteredGames = [Game]()
self.filteredGames = self.games?.filter({ (games) -> Bool in
return games.gameName?.name?.lowercased().range(of: searchText.lowercased()) != nil
})
if searchText == "" || searchText.count < 1 {
self.useFilteredArray = false
self.searchBar.showsCancelButton = false
self.searchBar.resignFirstResponder()
self.collectionView.reloadData()
} else {
self.useFilteredArray = true
self.searchBar.showsCancelButton = true
self.collectionView.reloadData()
}
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = nil
searchBar.showsCancelButton = false
searchBar.endEditing(true)
self.useFilteredArray = false
self.collectionView.reloadData()
}
}
//MARK: DataSource
extension TopGamesViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let games = self.useFilteredArray ? self.filteredGames : self.games
return games!.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cellGames = self.useFilteredArray ? self.filteredGames : self.games
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TopGamesCell", for: indexPath) as! TopGamesCollectionViewCell
cell.delegate = self
cell.setup(game: cellGames![indexPath.row])
if self.indexPathRow != nil && indexPath.row == self.indexPathRow! {
cell.favoriteButton.setImage(UIImage(named: "favoriteGame"), for: .normal)
cellGames![indexPath.row].isFavorite = true
let gameHash:[String: Game] = ["game": cellGames![indexPath.row]]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "addGameNotification"), object: nil, userInfo: gameHash)
}
if self.useFilteredArray == false {
if indexPath.row == (self.games?.count)! - 1 {
self.page! = self.page! + 20
self.bottomActivityIndicator.isHidden = false
self.bottomActivityIndicator.startAnimating()
self.getGames(limit: self.limit! , pages: self.page!)
self.collectionView.reloadData()
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let gameDetail = storyboard.instantiateViewController(withIdentifier: "GameDetailViewController") as!
GameDetailViewController
let cellGames = self.useFilteredArray ? self.filteredGames : self.games
gameDetail.setupVC(game: cellGames![indexPath.row])
self.navigationController?.show(gameDetail, sender: self)
}
}
//MARK: Delegate
extension TopGamesViewController: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width:(collectionView.frame.width/2), height: 250)
}
}
|
//
// ViewController.swift
// youtube
//
// Created by Nakib on 12/10/16.
// Copyright © 2016 Nakib. All rights reserved.
//
import UIKit
class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let navTitles = ["Home", "Trending", "Subscriptions", "Account"]
let cellId = "cellId"
let subscriptionCellId = "subscriptionCellId"
let trendingCellId = "trendingCellId"
override func viewDidLoad() {
super.viewDidLoad()
let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: view.frame.size.width-32, height: view.frame.size.height))
titleLabel.text = " Home"
titleLabel.textColor = UIColor.white
titleLabel.font = UIFont.systemFont(ofSize: 20)
navigationItem.titleView = titleLabel
setupCollectionView()
setupNavBar()
setupMenuBar()
}
func setupCollectionView() {
if let layout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 0
}
collectionView?.isPagingEnabled = true
collectionView?.backgroundColor = UIColor.white;
//register cells
collectionView?.register(FeedCell.self, forCellWithReuseIdentifier: cellId)
collectionView?.register(SubscriptionCell.self, forCellWithReuseIdentifier: subscriptionCellId)
collectionView?.register(TrendingCell.self, forCellWithReuseIdentifier: trendingCellId)
collectionView?.contentInset = UIEdgeInsetsMake(50, 0, 0, 0)
collectionView?.scrollIndicatorInsets = UIEdgeInsetsMake(50, 0, 0, 0)
}
private func setupNavBar() {
navigationController?.navigationBar.isTranslucent = false
let searchIcon = UIImage(named: "search_icon")?.withRenderingMode(.alwaysOriginal)
let searchButton = UIBarButtonItem(image: searchIcon, style: .plain, target: self, action: #selector(handleSearch))
let menuIcon = UIImage(named: "nav_more_icon")?.withRenderingMode(.alwaysOriginal)
let menuButton = UIBarButtonItem(image: menuIcon, style: .plain, target: self, action: #selector(handleMenu))
navigationItem.rightBarButtonItems = [menuButton, searchButton]
}
func handleSearch() {
}
func scrollToMenuAtIndex(index: Int) {
let indexPath = IndexPath(item: index, section: 0)
collectionView?.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition(), animated: true)
setTitleForIndex(index: index)
}
private func setTitleForIndex(index: Int) {
if let titleLabel = navigationItem.titleView as? UILabel {
titleLabel.text = " \(navTitles[index])"
}
}
lazy var settingsMenu: SettingsMenu = {
let menu = SettingsMenu()
menu.homeController = self
return menu
}()
func handleMenu() {
settingsMenu.openMenu()
}
func showSettingsController(setting: Setting) {
let dummyViewController = UIViewController()
dummyViewController.view.backgroundColor = UIColor.white
dummyViewController.navigationItem.title = setting.name.rawValue
navigationController?.navigationBar.tintColor = UIColor.white
navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]
navigationController?.pushViewController(dummyViewController, animated: true)
}
lazy var menuBar: MenuBar = {
let mb = MenuBar()
mb.homeController = self
mb.translatesAutoresizingMaskIntoConstraints = false
return mb
}()
private func setupMenuBar() {
navigationController?.hidesBarsOnSwipe = true
let redView = UIView()
redView.backgroundColor = UIColor.rgb(red: 230, green: 30, blue: 32)
view.addSubview(redView)
view.addConstraintsWithVisualFormat(format: "H:|[v0]|", views: redView)
view.addConstraintsWithVisualFormat(format: "V:[v0(50)]", views: redView)
view.addSubview(menuBar)
view.addConstraintsWithVisualFormat(format: "H:|[v0]|", views: menuBar)
view.addConstraintsWithVisualFormat(format: "V:[v0(50)]", views: menuBar)
menuBar.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var identifier = cellId
if indexPath.item == 1 {
identifier = trendingCellId
} else if indexPath.item == 2 {
identifier = subscriptionCellId
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.size.width, height: view.frame.size.height - 50)
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
menuBar.barLeftAnchorConstraint?.constant = scrollView.contentOffset.x / 4
}
override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let index = targetContentOffset.pointee.x / view.frame.size.width
let indexPath = IndexPath(item: Int(index), section: 0)
menuBar.collectionView.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition())
setTitleForIndex(index: Int(index))
}
}
|
//
// LandingViewHelper.swift
// koshelek_ru_testAPI_VIPER
//
// Created by maksim on 06.11.2020.
//
import Foundation
import UIKit
extension LandingViewController{
func setUpModule(){
//MARK: - view
view.backgroundColor = .white
tableView.dataSource = self
tableView.delegate = self
//MARK: - tableView
view.addSubview(tableView)
tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
tableView.tableHeaderView = headerView
//MARK: - headerView
headerView.widthAnchor.constraint(equalTo: tableView.widthAnchor, multiplier: 1).isActive = true
headerView.heightAnchor.constraint(equalTo: tableView.heightAnchor, multiplier: 0.2).isActive = true
tableView.tableHeaderView?.layoutIfNeeded()
// MARK: - dropdownOut
headerView.addSubview(dropdownOut)
dropdownOut.widthAnchor.constraint(equalTo: headerView.widthAnchor, multiplier: 0.5).isActive = true
dropdownOut.heightAnchor.constraint(equalTo: headerView.heightAnchor, multiplier: 0.3).isActive = true
dropdownOut.centerXAnchor.constraint(equalTo: headerView.centerXAnchor).isActive = true
dropdownOut.topAnchor.constraint(equalTo: headerView.topAnchor, constant: 10).isActive = true
//MARK: - stackView
headerView.addSubview(stackView)
stackView.widthAnchor.constraint(equalTo: headerView.widthAnchor, multiplier: 1).isActive = true
stackView.heightAnchor.constraint(equalTo: headerView.heightAnchor, multiplier: 0.3).isActive = true
stackView.bottomAnchor.constraint(equalTo: headerView.bottomAnchor, constant: 0).isActive = true
//MARK: - amountLabel & priceLabel & totalLabel
stackView.addArrangedSubview(amountLabel)
stackView.addArrangedSubview(priceLabel)
stackView.addArrangedSubview(totalLabel)
}
}
|
//
// MenuViewController.swift
// Trispective
//
// Created by USER on 2017/4/27.
// Copyright © 2017年 Trispective. All rights reserved.
//
import UIKit
class MenuViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,Step1{
func step1() {
performSegue(withIdentifier: "showStep1", sender: nil)
}
func showDish(d: Dish) {
self.d=d
performSegue(withIdentifier: "showDish", sender: nil)
}
var d=Dish()
var restaurant=Restaurant()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
switch(identifier){
case "showDish" :
if let vc=segue.destination as? DishDetailViewController{
vc.dish=self.d
}
default:
break
}
}
}
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var selectButton: UIBarButtonItem!
@IBAction func selectDish(_ sender: UIBarButtonItem) {
if (selectButton.title?.contains("Select"))!{
selectButton.title="Cancel"
self.tabBarController?.tabBar.isHidden=true
bottomViewHeight.constant=0.075*view.frame.height
ModelManager.getInstance().restaurant.changeStateToSelect()
}else{
selectButton.title="Select"
self.tabBarController?.tabBar.isHidden=false
bottomViewHeight.constant=0
ModelManager.getInstance().restaurant.changeStateToHide()
}
tableView.reloadData()
}
@IBAction func deleteDish(_ sender: UIButton) {
let restaurant=ModelManager.getInstance().restaurant
for (url,state) in restaurant.getDishState(){
if state.contains("isSelected"){
let cate=restaurant.getDishCategoryByUrl(u: url)
ModelManager.getInstance().deleteDish(dishId: restaurant.getDishIdByUrl(u: url), category: cate)
restaurant.deleteDishByUrl(u: url, c: cate)
ModelManager.getInstance().deleteDishFromLocal(url: url)
}
}
tableView.reloadData()
}
@IBOutlet weak var bottomViewHeight: NSLayoutConstraint!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.alpha=1
if !ModelManager.getInstance().restaurant.getId().isEmpty{
self.tabBarController?.tabBar.isHidden=false
}
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.titleTextAttributes=[NSFontAttributeName: UIFont(name: DemoImage.font,size: DemoImage.fontSize)!,NSForegroundColorAttributeName: UIColor(red: 30/225, green: 155/225, blue: 156/225, alpha: 1)]
let item = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)
self.navigationItem.backBarButtonItem = item
tableView.dataSource=self
tableView.delegate=self
if ModelManager.getInstance().restaurant.getId().isEmpty{
selectButton.isEnabled=false
selectButton.title=""
self.tabBarController?.tabBar.isHidden=true
}else{
selectButton.isEnabled=true
selectButton.title="Select"
self.tabBarController?.tabBar.isHidden=false
}
// Do any additional setup after loading the view.
}
@IBOutlet weak var holdTitleView: UIView!
@IBOutlet weak var titleConstraint: NSLayoutConstraint!
@IBOutlet weak var titleButton: UIButton!
func scrollViewDidScroll(_ scrollView: UIScrollView) {
var category=[String]()
if ModelManager.getInstance().restaurant.getId().isEmpty{
category=restaurant.getMenuCategory()
}else{
category=ModelManager.getInstance().restaurant.getMenuCategory()
}
var sumHeight:CGFloat=0
for i in 0 ..< cellHeight.count{
sumHeight+=cellHeight[i]
//print(sumHeight)
//print(scrollView.contentOffset.y)
if scrollView.contentOffset.y < -64+sumHeight{
if scrollView.contentOffset.y > -64+sumHeight-30{
titleConstraint.constant = -(scrollView.contentOffset.y-(-64+sumHeight-30))
}else{
if scrollView.contentOffset.y <= -64{
holdTitleView.isHidden=true
}else{
holdTitleView.isHidden=false
titleConstraint.constant = 0
}
}
if i<category.count{
titleButton.titleLabel?.text=category[i]
titleButton.setTitle(category[i], for: .normal)
}
break
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section==0{
if ModelManager.getInstance().restaurant.getId().isEmpty{
return restaurant.getMenuCategory().count
}else{
return ModelManager.getInstance().restaurant.getMenuCategory().count
}
}
else{
return 0
}
}
var cellHeight=[CGFloat]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section==0{
let cell = tableView.dequeueReusableCell(withIdentifier: "menuCell", for: indexPath) as! MenuTableViewCell
var category=[String]()
var r=Restaurant()
if ModelManager.getInstance().restaurant.getId().isEmpty{
category=self.restaurant.getMenuCategory()
r=self.restaurant
}else{
category=ModelManager.getInstance().restaurant.getMenuCategory()
r=ModelManager.getInstance().restaurant
}
cell.restaurant=r
cell.categoryButton.setTitle(category[indexPath.row], for: .normal)
cell.count=r.getMenuDish(category: category[indexPath.row]).count
cell.dishes=r.getMenuDish(category: category[indexPath.row])
cell.delegate=self
cell.updateCollectionView()
return cell
}else{
let cell = tableView.dequeueReusableCell(withIdentifier: "addCell", for: indexPath) as! AddTableViewCell
return cell
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section==0{
var category=[String]()
var r=Restaurant()
if ModelManager.getInstance().restaurant.getId().isEmpty{
category=self.restaurant.getMenuCategory()
r=self.restaurant
}else{
category=ModelManager.getInstance().restaurant.getMenuCategory()
r=ModelManager.getInstance().restaurant
}
let percent=CGFloat((r.getMenuDish(category: category[indexPath.row]).count+1)/2)
let height=view.frame.height*0.562/2*0.92*percent
cellHeight.append(height+view.frame.width*0.0265+70)
return height+view.frame.width*0.0265+70
}else{
return 60
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section==1{
}
}
}
|
//
// EditProfileViewController.swift
// Koku
//
// Created by HoangVu on 3/10/19.
// Copyright © 2019 HoangVu. All rights reserved.
//
import UIKit
import MaterialComponents
import iOSDropDown
class EditProfileViewController: UIViewController {
@IBOutlet weak var countryTF: DropDown!
@IBOutlet weak var phoneNumberTF: MDCTextField!
@IBOutlet weak var firstNameTF: MDCTextField!
@IBOutlet weak var lastNameTF: MDCTextField!
var activeTF: UITextField?
var firstNameTFController: MDCTextInputControllerUnderline?
var lastNameTFController: MDCTextInputControllerUnderline?
var countryTFController: MDCTextInputControllerUnderline?
var phoneNumberTFController: MDCTextInputControllerUnderline?
override func viewDidLoad() {
super.viewDidLoad()
setUpUI()
setUpData()
// Do any additional setup after loading the view.
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
func setUpUI()
{
firstNameTF.delegate = self
firstNameTFController = MDCTextInputControllerUnderline(textInput: firstNameTF)
firstNameTFController?.activeColor = UIColor.colorWithHexString(hexString: "558FA6")
firstNameTFController?.floatingPlaceholderActiveColor = UIColor.colorWithHexString(hexString: "558FA6")
lastNameTF.delegate = self
lastNameTFController = MDCTextInputControllerUnderline(textInput: lastNameTF)
lastNameTFController?.activeColor = UIColor.colorWithHexString(hexString: "558FA6")
lastNameTFController?.floatingPlaceholderActiveColor = UIColor.colorWithHexString(hexString: "558FA6")
countryTF.optionArray = UserSetting.sharedInstance.listCountriesName
countryTF.selectedRowColor = UIColor.colorWithHexString(hexString: "558FA6")
countryTF.listWillAppear {
let lineView = self.view.viewWithTag(100)
lineView?.backgroundColor = UIColor.colorWithHexString(hexString: "558FA6")
self.activeTF = self.countryTF
}
countryTF.listDidDisappear(completion: {
let lineView = self.view.viewWithTag(100)
lineView?.backgroundColor = UIColor.lightGray
})
//Its Id Values and its optionalVuh
phoneNumberTF.delegate = self
phoneNumberTF.keyboardType = .phonePad
phoneNumberTFController = MDCTextInputControllerUnderline(textInput: phoneNumberTF)
phoneNumberTFController?.activeColor = UIColor.colorWithHexString(hexString: "558FA6")
phoneNumberTFController?.floatingPlaceholderActiveColor = UIColor.colorWithHexString(hexString: "558FA6")
}
func setUpData()
{
firstNameTF.text = UserSetting.sharedInstance.currentUser?.firstName
lastNameTF.text = UserSetting.sharedInstance.currentUser?.lastName
phoneNumberTF.text = UserSetting.sharedInstance.currentUser?.phoneNumber
countryTF.text = UserSetting.sharedInstance.currentUser?.country
}
func isValidInputValue() -> Bool
{
if let firtName = firstNameTF.text , firtName == ""
{
firstNameTFController?.setErrorText("Please input first name", errorAccessibilityValue: nil)
return false
}
if let lastName = lastNameTF.text , lastName == ""
{
lastNameTFController?.setErrorText("Please input last name", errorAccessibilityValue: nil)
return false
}
if let phoneNumber = phoneNumberTF.text
{
if(phoneNumber == "")
{
phoneNumberTFController?.setErrorText("Please input your phone number", errorAccessibilityValue: nil)
return false
}
else if( !phoneNumber.isValidatePhoneNumber())
{
phoneNumberTFController?.setErrorText("Phone number format is not correct", errorAccessibilityValue: nil)
return false
}
}
if let country = countryTF.text , !UserSetting.sharedInstance.listCountriesName.contains(country)
{
let alert = UIAlertController(title: "Error", message: "Country is not correct. Please try again", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
self.present(alert, animated: true)
return false
}
return true
}
@IBAction func continueBtnTapped(_ sender: Any) {
if(isValidInputValue())
{
guard let currentUser = UserSetting.sharedInstance.currentUser else
{
return
}
currentUser.country = countryTF.text
currentUser.firstName = firstNameTF.text
currentUser.lastName = lastNameTF.text
currentUser.phoneNumber = phoneNumberTF.text
let loadingView = UIViewController.showLoading(onView: view)
NetworkManager.updateAccountDetail(userModel: currentUser, success: {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
UIViewController.hideLoading(view: loadingView)
self.dismiss(animated: true, completion: nil)
}
}) { (error) in
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
UIViewController.hideLoading(view: loadingView)
let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
self.present(alert, animated: true)
}
}
}
}
@objc func keyboardWillShow(notification: NSNotification) {
guard let userInfo = notification.userInfo else {return}
guard let keyboardSize = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {return}
let keyboardFrame = keyboardSize.cgRectValue
var aRect : CGRect = self.view.frame
aRect.size.height -= keyboardSize.cgRectValue.height
if let activeField = self.activeTF {
if (!aRect.contains(activeField.frame.origin)){
if self.view.frame.origin.y == 0
{
self.view.frame.origin.y -= keyboardFrame.height
}
}
if (self.activeTF as? DropDown) != nil
{
if self.view.frame.origin.y == 0
{
self.view.frame.origin.y -= keyboardFrame.height
}
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
guard let userInfo = notification.userInfo else {return}
guard let keyboardSize = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {return}
let keyboardFrame = keyboardSize.cgRectValue
if self.view.frame.origin.y != 0
{
self.view.frame.origin.y += keyboardFrame.height
}
}
@IBAction func TapOutView(_ sender: Any) {
view.endEditing(true)
}
@IBAction func dismissView(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
extension EditProfileViewController: UITextFieldDelegate
{
func textFieldDidBeginEditing(_ textField: UITextField){
activeTF = textField
if (textField as? MDCTextField == firstNameTF)
{
firstNameTFController?.setErrorText(nil, errorAccessibilityValue: nil)
}
else if (textField as? MDCTextField == lastNameTF)
{
lastNameTFController?.setErrorText(nil, errorAccessibilityValue: nil)
}
else if (textField as? MDCTextField == phoneNumberTF)
{
phoneNumberTFController?.setErrorText(nil, errorAccessibilityValue: nil)
}
}
func textFieldDidEndEditing(_ textField: UITextField){
activeTF = nil
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
}
|
//
// CalendarWeekView.swift
// iOS_Calendar
//
// Created by zhangnan on 2017/5/29.
// Copyright © 2017年 2345.com. All rights reserved.
//
import UIKit
class CalendarWeekView: UIView {
var dayViews: [CalendarDayView]!
init() {
super.init(frame: .zero)
createDayViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
layoutDayViews()
super.layoutSubviews()
}
func mapDayViews(_ body: (CalendarDayView) -> ()) {
if let dayViews = dayViews {
for dayView in dayViews {
body(dayView)
}
}
}
}
// MARK: - Content fill & reload
extension CalendarWeekView {
func createDayViews() {
dayViews = [CalendarDayView]()
for _ in 1...7 {
let dayView = CalendarDayView()
dayViews.append(dayView)
addSubview(dayView)
}
}
func layoutDayViews() {
let height = bounds.height
let width = bounds.width / 7.0
for (index, dayView) in dayViews.enumerated() {
let x = CGFloat(index) * CGFloat(width)
dayView.frame = CGRect(x: x, y: 0, width: width, height: height)
}
}
}
|
//
// PhotoCollectionViewCell.swift
// Flickr Digger
//
// Created by Ikjot Singh on 8/31/19.
// .
//
import UIKit
class PhotoCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
}
}
|
import Foundation
struct Model_Base : Codable {
let title: String?
var rows: [Rows]
enum CodingKeys: String, CodingKey {
case title = "title"
case rows = "rows"
}
}
|
//
// EditUserNavigator.swift
// PodTest
//
// Created by Mariusz Jakowienko on 02.06.2018.
// Copyright © 2018 personal. All rights reserved.
//
import Foundation
import UIKit
protocol EditUserNavigator {
func toUsers()
}
class DefaultEditUserNavigator: EditUserNavigator {
private let navigationController: UINavigationController
init(navigationController: UINavigationController) {
self.navigationController = navigationController
}
func toUsers() {
navigationController.popViewController(animated: true)
}
}
|
//
// postsDetails.swift
// Elshams
//
// Created by mac on 2/17/19.
// Copyright © 2019 mac. All rights reserved.
//
import UIKit
//import AlamofireImage
import Alamofire
import WebKit
class postsDetails: UIViewController {
var singlePostsItem : NewsFeedData?
@IBOutlet weak var postsTimeLineContainer: UIView!
@IBOutlet weak var imagePost: UIImageView!
@IBOutlet weak var videoContainerWV: WKWebView!
@IBOutlet weak var authorPic: UIImageView!
@IBOutlet weak var authorPost: UILabel!
@IBOutlet weak var likeUnlikeImg: UIImageView!
@IBOutlet weak var likeCounter: UILabel!
@IBOutlet weak var postDescribtion: UITextView!
var postLikeCounter = ""
override func viewDidLoad() {
super.viewDidLoad()
loadPostData()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
UIApplication.shared.isStatusBarHidden = false
}
/* func imgUrl(imgUrl:String,imageView:UIImageView) {
if imgUrl == "" || imgUrl == nil {
return
} else {
if let imagUrlAl = imgUrl as? String {
Alamofire.request(imagUrlAl).responseImage(completionHandler: { (response) in
print(response)
switch response.result {
case .success(let value):
if let image = response.result.value {
DispatchQueue.main.async{
imageView.image = image
}
}
case .failure(let error):
print(error)
}
})
}
}
}
*/
func loadPostData() {
self.navigationItem.title = "Post"
postsTimeLineContainer.isHidden = false
if singlePostsItem?.post_Type == "text" || singlePostsItem?.post_Type == "video_text" {
videoContainerWV.isHidden = true
// imgUrl(imgUrl: (singlePostsItem?.post_Image)!, imageView: imagePost)
Helper.loadImagesKingFisher(imgUrl: (singlePostsItem?.post_Image)!, ImgView: imagePost)
}
else if singlePostsItem?.post_Type == "video" {
videoContainerWV.isHidden = false
if singlePostsItem?.post_VideoURl != nil {
let videoUrl = NSURL(string: "\((singlePostsItem?.post_VideoURl)!)")
let requestObj = URLRequest(url: videoUrl as! URL)
videoContainerWV.load(requestObj)
}
}
authorPic.layer.cornerRadius = authorPic.frame.width / 2
authorPic.clipsToBounds = true
if singlePostsItem?.post_AutherPicture == "" || singlePostsItem?.post_AutherPicture == nil {
authorPic.image = UIImage(named: "home-logo")
}else {
// imgUrl(imgUrl: (singlePostsItem?.post_AutherPicture)!, imageView: authorPic)
Helper.loadImagesKingFisher(imgUrl: (singlePostsItem?.post_AutherPicture)!, ImgView: authorPic)
}
if singlePostsItem?.post_Author == "" || singlePostsItem?.post_Author == nil {
authorPost.text = "CIT"
} else {
authorPost.text = singlePostsItem?.post_Author
}
let postDesc = singlePostsItem?.post_Discription
postDescribtion.text = postDesc?.htmlToString
likeUnlikeImg.layer.cornerRadius = likeUnlikeImg.frame.width / 2
likeUnlikeImg.clipsToBounds = true
let likeCounterInt = singlePostsItem?.post_LikeCount
if likeCounterInt == 0 || likeCounterInt == nil {
if singlePostsItem?.post_Islike == true {
likeCounter.isHidden = false
// likeImage.backgroundColor = UIColor.blue
// likeImage.backgroundColor = UIColor.blue
likeUnlikeImg.image = UIImage(named: "liked")
likeCounter.text = "" //You like this
} else {
// likeImage.backgroundColor = UIColor.clear
likeCounter.textColor = UIColor.black
likeUnlikeImg.image = UIImage(named: "like")
// likeCounterLabel.text = "You,and \((NewsfeedList.post_LikeCount)!) likes"
likeCounter.isHidden = true
}
} else {
postLikeCounter = "\(likeCounter!)"
if singlePostsItem?.post_Islike == true {
likeCounter.isHidden = false
// likeImage.backgroundColor = UIColor.blue
likeUnlikeImg.image = UIImage(named: "liked")
likeCounter.textColor = UIColor.blue
likeCounter.text = "\(likeCounterInt!)"
} else {
// likeImage.backgroundColor = UIColor.clear
likeCounter.textColor = UIColor.black
likeUnlikeImg.image = UIImage(named: "like")
likeCounter.isHidden = false
likeCounter.text = "\(likeCounterInt!)"
// likeCounterLabel.isHidden = true
}
}
}
}
|
//
// PopComponentJson.swift
// GworldSuperOffice
//
// Created by 陈琪 on 2020/6/30.
// Copyright © 2020 Gworld. All rights reserved.
//
import Foundation
// MARK: 系统弹框
let PopComponentJson: [String: Any] = [
"version": 0,
"template": [
"viewType": "View",
"property": ["ratioW":0.8,"ratio": 2, "margin":[0, 0, 0, 0], "backgroudColor": "#ffffff", "cornerRadius": 8, "popupCustomAlignment": 0, "popupAnimationType": 2],
// ratoW 为宽度相对屏幕宽度的比率。ratio 为宽/高 值 由父视图获取
"subViews": [
[
"viewType": "StackView",
"property": ["axis":"vertical", "distribution": "fill", "alignment": "fill", "space": 0, "margin":[22, 0, 0, 0]],
"subViews": [
["viewType": "Text",
"property":["size": 18,"id":"1", "alignment": "center", "isBold": 1, "color": "#141922", "height": 20, "content":"${title}", "expressionSetters": ["content": "title"]]],
["viewType": "Text",
"property":["size": 15,"numberOfLines": 0, "id":"2", "alignment": "center", "color": "#737D92", "content":"${description}", "expressionSetters": ["content": "description"]]],
// 线条
["viewType": "View",
"property": ["height": 1, "backgroudColor": "#EEEEEE"]],
// 按钮
["viewType": "View",
"property": ["backgroudColor": "#EEEEEE", "height":44],
"subViews": [
["viewType": "StackView",
"property": ["axis":"horizontal", "distribution": "fillEqually", "alignment": "fill", "space": 1, "margin":[0, 0, 0, 0]],
"subViews":[
["viewType": "Button",
"property":["size": 15, "id":"3", "backgroudColor": "#ffffff", "alignment": "center", "color": "#737D92", "content":"${cancelTitle}", "expressionSetters": ["content": "cancelTitle"], "action": ["actionType": "cancel", "params": ["key": "value"]]]],
// // 线条
// ["viewType": "View",
// "property": ["width": 1, "backgroundColor": "#EEEEEE"]],
["viewType": "Button",
"property":["size": 15, "id":"4","backgroudColor": "#ffffff", "alignment": "center", "color": "#141922", "content":"${confirmTitle}", "expressionSetters": ["content": "confirmTitle"], "action": ["actionType": "confirm", "params": ["key": "value"]]]]
]
]
]
]
]
]
]
]
]
// MARK: 口令输入弹框
let inputPopComponentJson: [String: Any] = [
"viewType": "View",
"property": ["ratioW":0.8,"ratio": 1.26, "margin":[0, 0, 0, 0], "backgroudColor": "#ffffff", "cornerRadius": 8, "popupCustomAlignment": 0, "popupAnimationType": 2],
// ratoW 为宽度相对屏幕宽度的比率。ratio 为宽/高 值 由父视图获取
"subViews": [
[
"viewType": "StackView",
"property": ["axis":"vertical", "distribution": "fill", "alignment": "center", "space": 32, "margin":[32, 0, 0, 24]],
"subViews": [
["viewType": "ImageView",
"property":["id":"1", "height": 72, "width": 72, "content":"icon_tc_srmm.png"]],
["viewType": "Text",
"property":["size": 24, "isBold": 1, "id":"2", "alignment": "center", "color": "#2B2B2B", "content":"请输入参会密码", "expressionSetters": ["content": "description"]]],
// 输入框
["viewType": "StackView",
"property": ["height": 84, "backgroudColor": "#EEEEEE"],
"subViews": [
["viewType": "Text",
"property":["size": 13, "fontName": "PingFangSC", "id":"2", "alignment": "center", "color": "#4E586E", "content":"请输入验证口令", "expressionSetters": ["content": "description"]]]
]
],
]
]
]
]
|
//
// ViewController.swift
// Flat Files
//
// Created by Adam Ostrich on 2/25/15.
// Copyright (c) 2015 Adam Ostrich. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Accessing App/tmp
var tempPath = NSTemporaryDirectory() + "hello.txt"
println(tempPath)
var stringToSave = self.textView.text
var fileManager = NSFileManager()
stringToSave.writeToFile(tempPath, atomically: true, encoding: NSUTF32StringEncoding, error: nil)
}
@IBAction func loadData(sender: UIButton) {
var txtPath = NSTemporaryDirectory() + "hello.txt"
var stringToLoad: NSString? = NSString(contentsOfFile: txtPath, encoding: NSUTF16StringEncoding, error: nil)
if let loadedContent = stringToLoad {
self.textView.text = loadedContent
}
else {
println("Could not load!")
}
}
}
|
//
// Calculator.swift
// pgbot-new
//
// Created by Tiancong Wang on 8/22/18.
// Copyright © 2018 twang14. All rights reserved.
//
import Foundation
import UIKit
class ViewControllerCalculator: UIViewController {
static let limit = 3
var botIdentifier : Int = -1
var botColor : UIColor = .white
var increment : Bool = true
func setIdentifier(id: Int, color: UIColor){
botIdentifier = id
botColor = color
}
func setDecrement() {
increment = false
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBOutlet weak var resultDisplay: UILabel!
@IBOutlet weak var warningDisplay: UILabel!
func addDisplay(digit : Int) {
if (resultDisplay.text!.count >= ViewControllerCalculator.limit) {
warningDisplay.text = "Too many Elektros"
return
}
let result:Int? = Int(resultDisplay.text!)
if result! == 0 {
resultDisplay.text = String(digit)
}
else {
resultDisplay.text = String(result!*10+digit)
}
}
func removeDisplay() {
warningDisplay.text = ""
if resultDisplay.text?.count == 1 {
resultDisplay.text = "0"
}
else {
resultDisplay.text?.remove(at: resultDisplay.text!.index(before: resultDisplay.text!.endIndex))
}
}
@IBAction func pressButton(_ sender: UIButton, forEvent event: UIEvent) {
var digit = -1
for i in 0...9 {
if sender.title(for: .normal) == String(i) {
print("Press Button "+String(i))
digit = i
}
}
if (digit > -1) {
addDisplay(digit: digit)
}
else {
if sender.title(for: .normal) == "⌫" {
removeDisplay()
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dest = segue.destination as? ViewControllerDisplay {
let result = Int(resultDisplay.text!)
dest.setIdentifier(id: botIdentifier, color: botColor)
dest.changeMoneyWithCalculator(money: result!, increment: increment)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// SMAInverter
// MacSunnySender
//
// Created by Jan Verrept on 24/06/17.
// Copyright © 2017 OneClick. All rights reserved.
//
import Cocoa
import GRDB
protocol InverterViewModel {
var serial: Int?{get}
var number: Handle?{get}
var name: String?{get}
var type: String?{get}
var measurementValues:[Measurement]?{get}
var parameterValues:[Measurement]?{get}
var testValues:[Measurement]?{get}
}
/// C-callback functions
// Should always be declared global???
var callBackFunctionForYasdiEvents:(TYASDIDetectionSub, UInt32, UInt32)->() = {
(event: TYASDIDetectionSub, deviceHandle: UInt32, param1: UInt32)->() in
switch event{
case YASDI_EVENT_DEVICE_ADDED:
debugger.log(debugLevel:.Message ,"Device \(deviceHandle) added")
case YASDI_EVENT_DEVICE_REMOVED:
debugger.log(debugLevel:.Message,"Device \(deviceHandle) removed")
case YASDI_EVENT_DEVICE_SEARCH_END:
debugger.log(debugLevel:.Message,"No more devices found")
case YASDI_EVENT_DOWNLOAD_CHANLIST:
debugger.log(debugLevel:.Message,"Channels downloaded")
default:
debugger.log(debugLevel:.Error,"Unkwown event occured during async device detection")
}
}
class SMAInverter: InverterViewModel{
enum ChannelsType:UInt32{
case spotChannels
case parameterChannels
case testChannels
case allChannels
}
public static var inverters:[SMAInverter] = []
public var model:Inverter!
var serial: Int?{return model.serial}
var number: Handle?{return model.number}
var name: String?{return model.name}
var type: String?{return model.type}
public var measurementValues:[Measurement]? = nil // These values will eventually be displayed by the MainViewcontroller
public var parameterValues:[Measurement]? = nil // These values will eventually be displayed by the parameterViewcontroller
public var testValues:[Measurement]? = nil // These values will not be displayed for now
private var pollingTimer: Timer! = nil
typealias ID = Int
private var spotChannels:[Channel] = []
private var parameterChannels:[Channel] = []
private var testChannels:[Channel] = []
class func handleAllYasdiEvents(){
yasdiMasterAddEventListener(&callBackFunctionForYasdiEvents, YASDI_EVENT_DEVICE_DETECTION)
}
class func createInverters(maxNumberToSearch maxNumber:Int){
if let devices:[Handle] = searchDevices(maxNumberToSearch:maxNumber){
for device in devices{
var inverterModel = composeInverterModel(fromDevice:device)
// Archive in SQL and
// complete the model-class with the PK from the SQlrecord
var sqlRecord = JVSQliteRecord(data:inverterModel, in:dataBaseQueue)
let changedSQLRecords = sqlRecord.changeOrCreateRecord(matchFields: ["serial"])
inverterModel.inverterID = changedSQLRecords?.first?[0]
let inverterViewModel = SMAInverter(model:inverterModel)
inverters.append(inverterViewModel)
// Automaticly create a document for each inverter that was found
NSDocumentController.shared.addDocument(Document(inverter:inverterViewModel))
}
}
}
class private func searchDevices(maxNumberToSearch maxNumber:Int)->[Handle]?{
var devices:[Handle]? = nil
let errorCode:Int32 = -1
var resultCode:Int32 = errorCode
resultCode = DoStartDeviceDetection(CInt(maxNumber), 1);
if resultCode != errorCode {
let errorCode:DWORD = 0
var resultCode:DWORD = errorCode
let deviceHandles:UnsafeMutablePointer<Handle> = UnsafeMutablePointer<Handle>.allocate(capacity:maxNumber)
resultCode = GetDeviceHandles(deviceHandles, DWORD(maxNumber))
if resultCode != errorCode {
// convert to a swift array of devicehandles
devices = []
let numberOfDevices = resultCode
for _ in 0..<numberOfDevices{
devices!.append(deviceHandles.pointee)
_ = deviceHandles.advanced(by: 1)
}
}
}
return devices
}
class private func composeInverterModel(fromDevice deviceHandle:Handle)->Inverter{
var deviceSN:DWORD = 2000814023
var deviceName:String = "WR46A-01 SN:2000814023"
var deviceType:String = "WR46A-01"
let errorCode:Int32 = -1
var resultCode:Int32 = errorCode
let deviceSNvar: UnsafeMutablePointer<DWORD> = UnsafeMutablePointer<DWORD>.allocate(capacity: 1)
resultCode = errorCode
resultCode = GetDeviceSN(deviceHandle,
deviceSNvar)
if resultCode != errorCode {
deviceSN = deviceSNvar.pointee
}
let deviceNameVar: UnsafeMutablePointer<CChar> = UnsafeMutablePointer<CChar>.allocate(capacity: MAXCSTRINGLENGTH)
resultCode = errorCode
resultCode = GetDeviceName(deviceHandle,
deviceNameVar,
Int32(MAXCSTRINGLENGTH))
if resultCode != errorCode {
deviceName = String(cString:deviceNameVar)
}
let deviceTypeVar: UnsafeMutablePointer<CChar> = UnsafeMutablePointer<CChar>.allocate(capacity: MAXCSTRINGLENGTH)
resultCode = errorCode
resultCode = GetDeviceType(deviceHandle,
deviceTypeVar,
Int32(MAXCSTRINGLENGTH))
if resultCode != errorCode {
deviceType = String(cString: deviceTypeVar)
}
let inverterRecord = Inverter(
inverterID: nil,
serial: Int(deviceSN),
number: deviceHandle,
name: deviceName,
type: deviceType
)
return inverterRecord
}
init(model: Inverter){
self.model = model
// Read all channels just once
readChannels(maxNumberToSearch: 30, channelType: .allChannels)
// Sample spotvalues at a fixed time interval (30seconds here)
pollingTimer = Timer.scheduledTimer(timeInterval: 30,
target: self,
selector: #selector(self.readValues),
userInfo: ChannelsType.spotChannels,
repeats: true
)
print("✅ Inverter \(name!) found online")
}
private func readChannels(maxNumberToSearch:Int, channelType:ChannelsType = .allChannels){
var channelTypesToRead = [channelType]
if channelType == .allChannels{
channelTypesToRead = [ChannelsType.spotChannels, ChannelsType.parameterChannels, ChannelsType.testChannels]
}
for typeToRead in channelTypesToRead{
let errorCode:DWORD = 0
var resultCode:DWORD = errorCode
var channelHandles:UnsafeMutablePointer<Handle> = UnsafeMutablePointer<Handle>.allocate(capacity: maxNumberToSearch)
resultCode = GetChannelHandlesEx(number!,
channelHandles,
DWORD(maxNumberToSearch),
TChanType(typeToRead.rawValue)
)
if resultCode != errorCode {
let numberOfChannels = resultCode
for _ in 0..<numberOfChannels{
let channelNumber = Int(channelHandles.pointee)
let errorCode:Int32 = -1
var resultCode:Int32 = errorCode
let channelName: UnsafeMutablePointer<CChar> = UnsafeMutablePointer<CChar>.allocate(capacity: MAXCSTRINGLENGTH)
resultCode = GetChannelName(
DWORD(channelNumber),
channelName,
DWORD(MAXCSTRINGLENGTH)
)
if resultCode != errorCode {
let unit: UnsafeMutablePointer<CChar> = UnsafeMutablePointer<CChar>.allocate(capacity: MAXCSTRINGLENGTH)
GetChannelUnit(Handle(channelNumber), unit, DWORD(MAXCSTRINGLENGTH))
// Create the model
var channelRecord = Channel(
channelID: nil,
type: Int(typeToRead.rawValue),
number: channelNumber,
name: String(cString: channelName),
unit: String(cString: unit),
inverterID: model.inverterID
)
// Archive in SQL and
// complete the model-class with the PK from the SQlrecord
var sqlRecord = JVSQliteRecord(data:channelRecord, in:dataBaseQueue)
let changedSQLRecords = sqlRecord.changeOrCreateRecord(matchFields:["type","name"])
channelRecord.channelID = changedSQLRecords?.first?[0]
// Divide all channels found by their channeltype
switch typeToRead{
case .spotChannels:
spotChannels.append(channelRecord)
case .parameterChannels:
parameterChannels.append(channelRecord)
case .testChannels:
testChannels.append(channelRecord)
default:
break
}
}
channelHandles = channelHandles.advanced(by: 1)
}
}
}
}
// Callbackfunction for the timer
@objc private func readValues(timer:Timer){
let channelType = timer.userInfo as! ChannelsType
let sqlTimeStampFormatter = DateFormatter()
sqlTimeStampFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" // GMT date string in SQL-format
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "dd-MM-yyyy" // Local date string
let timeFormatter = DateFormatter()
timeFormatter.timeZone = TimeZone.current
timeFormatter.dateFormat = "HH:mm:ss" // Local time string
let systemTimeStamp = Date()
let currentLocalHour = Calendar.current.component(Calendar.Component.hour, from: systemTimeStamp)
// Only record dat between 06:00 and 22:59
if (6...22) ~= currentLocalHour{
var channelTypesToRead = [channelType]
if channelType == .allChannels{
channelTypesToRead = [ChannelsType.allChannels, ChannelsType.parameterChannels, ChannelsType.testChannels]
}
for typeToRead in channelTypesToRead{
let channelsToRead:[Channel]
switch typeToRead{
case .spotChannels:
channelsToRead = spotChannels
case .parameterChannels:
channelsToRead = parameterChannels
case .testChannels:
channelsToRead = testChannels
default:
channelsToRead = spotChannels + parameterChannels + testChannels
}
var currentValues:[Measurement] = []
for channel in channelsToRead{
let channelNumber = channel.number!
var recordedTimeStamp = systemTimeStamp
let onlineTimeStamp = GetChannelValueTimeStamp(Handle(channelNumber), number!)
if onlineTimeStamp > 0{
recordedTimeStamp = Date(timeIntervalSince1970:TimeInterval(onlineTimeStamp))
}
let currentValue:UnsafeMutablePointer<Double> = UnsafeMutablePointer<Double>.allocate(capacity: 1)
let currentValueAsText: UnsafeMutablePointer<CChar> = UnsafeMutablePointer<CChar>.allocate(capacity: MAXCSTRINGLENGTH)
let maxChannelAgeInSeconds:DWORD = 5
let errorCode:Int32 = -1
var resultCode:Int32 = errorCode
resultCode = GetChannelValue(Handle(channelNumber),
number!,
currentValue,
currentValueAsText,
DWORD(MAXCSTRINGLENGTH),
maxChannelAgeInSeconds
)
if resultCode != errorCode {
// Create the model
var measurementRecord = Measurement(
measurementID: nil,
samplingTime: timeFormatter.string(from: systemTimeStamp),
timeStamp: sqlTimeStampFormatter.string(from: recordedTimeStamp),
date: dateFormatter.string(from: recordedTimeStamp),
time: timeFormatter.string(from: recordedTimeStamp),
value: currentValue.pointee,
channelID: channel.channelID
)
// Archive in SQL and
// complete the model-class with the PK from the SQlrecord
var sqlRecord = JVSQliteRecord(data:measurementRecord, in:dataBaseQueue)
let changedSQLRecords = sqlRecord.createRecord()
measurementRecord.channelID = changedSQLRecords?.first?[0]
currentValues.append(measurementRecord)
}
}
// Divide all channels found, by channeltype
switch typeToRead{
case .spotChannels:
measurementValues = currentValues
case .parameterChannels:
parameterValues = currentValues
case .testChannels:
testValues = currentValues
default:
break
}
}
}
}
public func saveCsvFile(forDate dateQueried: String){
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "dd-MM-yyyy" // Local date string
var CSVSource = """
SUNNY-MAIL
Version 1.2
Source SDC
Date 01/12/2017
Language EN
Type Serialnumber Channel Date DailyValue 10:47:06 11:02:06
"""
let dataSeperator = ";"
if let dailyRecords = searchData(forDate: Date()){
let columNamesToReport = ["Type","SerialNumber","Channel","Date","DailyValue","valueColumns"]
if let firstRecordedTime = dateFormatter.date(from: (dailyRecords.first!["samplingTime"])!){
var timeToReport = firstRecordedTime
for record in dailyRecords{
let recordedTime = dateFormatter.date(from: (record["samplingTime"])!)
if recordedTime?.compare(timeToReport) == ComparisonResult.orderedAscending{
// Not there yet
}else if recordedTime?.compare(timeToReport) == ComparisonResult.orderedDescending{
// Shooting past the interval, point to the next higher interval
while recordedTime?.compare(timeToReport) == ComparisonResult.orderedDescending{
timeToReport = timeToReport.addingTimeInterval(15*60)
}
// and give it a second shot
if recordedTime?.compare(timeToReport) == ComparisonResult.orderedSame{
// recordsToReport.append(record)
}
}else{
// When it was recorded at the exact time-interval
// Put the record in the report
// recordsToReport.append(record)
}
}
}
}
print(CSVSource) // replace with saved CSVFile
}
private func searchData(forDate reportDate:Date)->[Row]?{
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "dd-MM-yyyy" // Local date string
let searchRequest = Measurement(
measurementID: nil,
samplingTime: nil,
timeStamp: nil,
date: dateFormatter.string(from: reportDate),
time: nil,
value: nil,
channelID: nil
)
var dailyRequest = JVSQliteRecord(data:searchRequest, in:dataBaseQueue)
return dailyRequest.findRecords()
}
}
|
import SectionsTableView
import SnapKit
import ThemeKit
import RxSwift
import RxCocoa
import MessageUI
import SafariServices
import ComponentKit
class AboutViewController: ThemeViewController {
private let viewModel: AboutViewModel
private var urlManager: UrlManager
private let disposeBag = DisposeBag()
private let tableView = SectionsTableView(style: .grouped)
private let headerCell = LogoHeaderCell()
private var showTermsAlert = false
init(viewModel: AboutViewModel, urlManager: UrlManager) {
self.viewModel = viewModel
self.urlManager = urlManager
super.init()
hidesBottomBarWhenPushed = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "settings.about_app.title".localized
navigationItem.backBarButtonItem = UIBarButtonItem(title: title, style: .plain, target: nil, action: nil)
view.addSubview(tableView)
tableView.snp.makeConstraints { maker in
maker.edges.equalToSuperview()
}
tableView.separatorStyle = .none
tableView.backgroundColor = .clear
tableView.sectionDataSource = self
tableView.registerCell(forClass: DescriptionCell.self)
headerCell.image = UIImage(named: AppIcon.main.imageName)
headerCell.title = "settings.about_app.app_name".localized(AppConfig.appName)
headerCell.subtitle = "version".localized(viewModel.appVersion)
subscribe(disposeBag, viewModel.termsAlertDriver) { [weak self] alert in
self?.showTermsAlert = alert
self?.tableView.reload()
}
subscribe(disposeBag, viewModel.openLinkSignal) { [weak self] url in
self?.urlManager.open(url: url, from: self)
}
tableView.buildSections()
}
override func viewWillAppear(_ animated: Bool) {
tableView.deselectCell(withCoordinator: transitionCoordinator, animated: animated)
}
private func openTellFriends() {
let text = "settings_tell_friends.text".localized + "\n" + AppConfig.appWebPageLink
let activityViewController = UIActivityViewController(activityItems: [text], applicationActivities: [])
present(activityViewController, animated: true, completion: nil)
}
private func handleEmailContact() {
let email = AppConfig.reportEmail
if MFMailComposeViewController.canSendMail() {
let controller = MFMailComposeViewController()
controller.setToRecipients([email])
controller.mailComposeDelegate = self
present(controller, animated: true)
} else {
CopyHelper.copyAndNotify(value: email)
}
}
private func handleTelegramContact() {
navigationController?.pushViewController(PersonalSupportModule.viewController(), animated: true)
}
private func handleContact() {
let viewController = BottomSheetModule.viewController(
image: .local(image: UIImage(named: "at_24")?.withTintColor(.themeJacob)),
title: "settings.contact.title".localized,
items: [],
buttons: [
.init(style: .yellow, title: "settings.contact.via_email".localized, actionType: .afterClose) { [weak self] in
self?.handleEmailContact()
},
.init(style: .gray, title: "settings.contact.via_telegram".localized, actionType: .afterClose) { [weak self] in
self?.handleTelegramContact()
}
]
)
present(viewController, animated: true)
}
private func openTwitter() {
let account = AppConfig.appTwitterAccount
if let appUrl = URL(string: "twitter://user?screen_name=\(account)"), UIApplication.shared.canOpenURL(appUrl) {
UIApplication.shared.open(appUrl)
} else {
urlManager.open(url: "https://twitter.com/\(account)", from: self)
}
}
}
extension AboutViewController: SectionsDataSource {
private func row(id: String, image: String, title: String, alert: Bool = false, isFirst: Bool = false, isLast: Bool = false, action: @escaping () -> ()) -> RowProtocol {
var elements = tableView.universalImage24Elements(image: .local(UIImage(named: image)), title: .body(title), value: nil, accessoryType: .disclosure)
if alert {
elements.insert(.imageElement(image: .local(UIImage(named: "warning_2_24")?.withTintColor(.themeLucian)), size: .image24), at: 2)
}
return CellBuilderNew.row(
rootElement: .hStack(elements),
tableView: tableView,
id: id,
height: .heightCell48,
autoDeselect: true,
bind: { cell in
cell.set(backgroundStyle: .lawrence, isFirst: isFirst, isLast: isLast)
},
action: action
)
}
func buildSections() -> [SectionProtocol] {
let descriptionText = "settings.about_app.description".localized(AppConfig.appName, AppConfig.appName)
return [
Section(
id: "header",
rows: [
StaticRow(
cell: headerCell,
id: "header",
height: LogoHeaderCell.height
),
Row<DescriptionCell>(
id: "description",
dynamicHeight: { containerWidth in
DescriptionCell.height(containerWidth: containerWidth, text: descriptionText)
},
bind: { cell, _ in
cell.label.text = descriptionText
}
)
]
),
Section(
id: "release-notes",
headerState: .margin(height: .margin24),
footerState: .margin(height: .margin32),
rows: [
row(
id: "release-notes",
image: "circle_information_24",
title: "settings.about_app.whats_new".localized,
isFirst: true,
isLast: true,
action: { [weak self] in
guard let url = self?.viewModel.releaseNotesUrl else {
return
}
self?.navigationController?.pushViewController(MarkdownModule.gitReleaseNotesMarkdownViewController(url: url, presented: false), animated: true)
}
)
]
),
Section(
id: "main",
footerState: .margin(height: .margin32),
rows: [
row(
id: "app-status",
image: "app_status_24",
title: "app_status.title".localized,
isFirst: true,
action: { [weak self] in
self?.navigationController?.pushViewController(AppStatusRouter.module(), animated: true)
}
),
row(
id: "terms",
image: "unordered_24",
title: "terms.title".localized,
alert: showTermsAlert,
action: { [weak self] in
self?.present(TermsModule.viewController(), animated: true)
}
),
row(
id: "privacy",
image: "user_24",
title: "settings.privacy".localized,
isLast: true,
action: { [weak self] in
self?.navigationController?.pushViewController(PrivacyPolicyViewController(config: .privacy), animated: true)
}
),
]
),
Section(
id: "web",
footerState: .margin(height: .margin32),
rows: [
row(
id: "github",
image: "github_24",
title: "GitHub",
isFirst: true,
action: { [weak self] in
self?.viewModel.onTapGithubLink()
}
),
row(
id: "twitter",
image: "twitter_24",
title: "Twitter",
action: { [weak self] in
self?.openTwitter()
}
),
row(
id: "website",
image: "globe_24",
title: "settings.about_app.website".localized,
isLast: true,
action: { [weak self] in
self?.viewModel.onTapWebPageLink()
}
)
]
),
Section(
id: "share",
footerState: .margin(height: .margin32),
rows: [
row(
id: "rate-us",
image: "rate_24",
title: "settings.about_app.rate_us".localized,
isFirst: true,
action: { [weak self] in
self?.viewModel.onTapRateApp()
}
),
row(
id: "tell-friends",
image: "share_1_24",
title: "settings.about_app.tell_friends".localized,
isLast: true,
action: { [weak self] in
self?.openTellFriends()
}
),
]
),
Section(
id: "contact",
footerState: .margin(height: .margin32),
rows: [
row(
id: "email",
image: "at_24",
title: "settings.about_app.contact".localized,
isFirst: true,
isLast: true,
action: { [weak self] in
self?.handleContact()
}
)
]
)
]
}
}
extension AboutViewController: MFMailComposeViewControllerDelegate {
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true)
}
}
|
/* Copyright Airship and Contributors */
import SwiftUI
#if canImport(AirshipCore)
import AirshipCore
#elseif canImport(AirshipKit)
import AirshipKit
#endif
@available(iOS 13.0, *)
struct OpenView: View {
@State var address: String = ""
@State var platformName: String = ""
@ObservedObject var identifiers = Identifiers()
var body: some View {
VStack(alignment: .leading) {
TextField("Address", text: $address)
TextField("Platform name", text: $platformName)
Button("CREATE") {
let options = OpenRegistrationOptions.optIn(platformName: platformName, identifiers: identifiers.getIdentifiers())
Airship.contact.registerOpen(address, options: options)
}
.frame(width: 85, height: 30)
.clipShape(RoundedRectangle(cornerRadius: 7))
HStack {
Text("Identifiers")
.font(.system(size: 18, weight: .semibold))
NavigationLink(destination: IdentifiersView(identifiers: identifiers)) {
Text("Add Identifiers")
}
}
ForEach(identifiers.getIdentifiers().sorted(by: >), id: \.key) { item in
HStack {
Text(item.key)
}
}
Spacer()
}
}
}
@available(iOS 13.0.0, *)
struct OpenView_Previews: PreviewProvider {
static var previews: some View {
OpenView()
}
}
|
//
// EditFriendViewController.swift
// Vriends
//
// Created by Tjerk Dijkstra on 03/08/2018.
// Copyright © 2018 Tjerk Dijkstra. All rights reserved.
//
import UIKit
class EditFriendViewController: UIViewController {
@IBOutlet weak var NameTextField: UITextField!
@IBOutlet weak var ColorPicker: UICollectionView!
@IBOutlet weak var BirthDatePicker: UIDatePicker!
@IBOutlet weak var TimeSelector: UISegmentedControl!
var friend: Friend!
var selectedColor: String = ""
var sliderchanged = false
// RRGGBB hex colors in the same order as the image
let colorArray =
[
0xFF5E5E,
0xFFB84C,
0x38D96F,
0x7CD0EA,
0x44A9F2,
0xAC7ADE,
0xD95050,
0xD99341,
0x30B85E,
0x69B1C7,
0x3A90CE,
0x9268BD
]
let wishDateArray = [7, 14, 31, 32]
let notificationHelper = NotificationHelper.instance
override func viewDidLoad() {
super.viewDidLoad()
ColorPicker.allowsMultipleSelection = false
ColorPicker.delegate = self
ColorPicker.dataSource = self
// setup fields for edit
NameTextField.text = friend.name!
selectedColor = friend.favoriteColor!
BirthDatePicker.date = friend.birthdate!
// change segemented control accordingly
switch Int(friend.wishToSee!) {
case 7:
TimeSelector.selectedSegmentIndex = 0
case 14:
TimeSelector.selectedSegmentIndex = 1
case 31:
TimeSelector.selectedSegmentIndex = 2
default:
TimeSelector.selectedSegmentIndex = 3
}
}
func uiColorFromHex(rgbValue: Int) -> UIColor {
let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 0xFF
let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 0xFF
let blue = CGFloat(rgbValue & 0x0000FF) / 0xFF
let alpha = CGFloat(1.0)
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "BackToProfile", let destination = segue.destination as? VriendViewController {
destination.friend = friend
}
}
@IBAction func SaveFriend(_ sender: Any) {
if(NameTextField.text != nil) {
friend.name = NameTextField.text
if(selectedColor == "") {
friend.favoriteColor = String(colorArray[Int.random(range: 0...12)])
} else {
friend.favoriteColor = selectedColor
}
}
friend.wishToSee = String(wishDateArray[TimeSelector.selectedSegmentIndex])
// birthday changed so we need to do notifications
if(friend.birthdate != BirthDatePicker.date) {
friend.birthdate = BirthDatePicker.date
friend.triggerdate = Calendar.current.date(byAdding: .day, value: -7, to: friend.birthdate!)
// setup notifications, these repeat yearly
notificationHelper.setBirthDaySoonNotification(friend: friend)
notificationHelper.setupBirthDayNotification(friend: friend)
}
CoreDataStack.instance.saveContext()
performSegue(withIdentifier: "BackToProfile", sender: self)
}
@IBAction func DeleteFriend(_ sender: Any) {
let alertController = UIAlertController(title: "Are you sure you want to delete " + friend.name! + " ?", message: "This will permanently delete this friend from Vriends.", preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { action in }
alertController.addAction(cancelAction)
let destroyAction = UIAlertAction(title: "Delete", style: .destructive) { action in
let context = CoreDataStack.instance.managedObjectContext
context.delete(self.friend)
CoreDataStack.instance.saveContext()
self.navigationController?.popToRootViewController(animated: true)
}
alertController.addAction(destroyAction)
self.present(alertController, animated: true) {}
}
}
extension EditFriendViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UITextFieldDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return colorArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "colorCollectionCell", for: indexPath) as! colorCollectionCell
cell.layer.cornerRadius = cell.frame.width / 2
cell.backgroundColor = uiColorFromHex(rgbValue: Int(colorArray[indexPath.row]))
if colorArray[indexPath.row] == Int(selectedColor) {
cell.selectedImage.image = UIImage(named: "selected-color")
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let parent = collectionView
return CGSize(width: (parent.frame.height / 2) - 20, height: (parent.frame.height / 2) - 20)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! colorCollectionCell
selectedColor = String(colorArray[indexPath.row])
// away with you, stupid selected image, bit overkill but its friday 23:21 SO SUE ME
for cell in collectionView.visibleCells as! [colorCollectionCell] {
cell.selectedImage.image = nil
}
cell.selectedImage.image = UIImage(named: "selected-color")
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! colorCollectionCell
self.view.endEditing(true)
cell.selectedImage.image = nil
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
|
//
// dashboardpage.swift
// idashboard
//
// Created by Hasanul Isyraf on 25/04/2018.
// Copyright © 2018 Hasanul Isyraf. All rights reserved.
//
import UIKit
import Firebase
class dashboardpage: UIViewController {
@IBOutlet weak var currentdate: UIButton!
@IBOutlet weak var totalsite: UIButton!
@IBOutlet weak var completesite: UIButton!
@IBOutlet weak var dismantling: UIButton!
@IBOutlet weak var scrollview1: UIScrollView!
@IBOutlet weak var balance: UIButton!
@IBOutlet weak var lockin: UIButton!
@IBOutlet weak var remaining: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//set bar button item
let btn1 = UIButton(type: .custom)
btn1.setImage(#imageLiteral(resourceName: "logout"), for: .normal)
btn1.frame = CGRect(x: 0, y: 0, width: 10, height: 10)
btn1.addTarget(self, action: #selector(dashboardpage.logoutfirebase), for: .touchUpInside)
let item1 = UIBarButtonItem(customView: btn1)
self.navigationItem.setRightBarButtonItems([item1], animated: true)
fetch1()
// fetch2()
// fetch3()
// fetch4()
// fetch5()
// fetch6()
// fetch7()
let date = Date()
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .none
formatter.locale = Locale(identifier: "en_US")
let result = formatter.string(from: date)
currentdate.setTitle(result, for: .normal)
self.title = "REALTIME IPMSAN DASHBOARD"
self.navigationController?.navigationBar.titleTextAttributes = [ NSAttributedStringKey.font: UIFont(name: "Arial", size: 12)!]
scrollview1.isDirectionalLockEnabled = true
}
@objc func logoutfirebase(){
try! FIRAuth.auth()!.signOut()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let initialViewController2 = storyboard.instantiateViewController(withIdentifier: "startpage") as! ViewController
self.navigationController?.pushViewController(initialViewController2, animated: true)
}
func fetch1(){
let urlrequest = URLRequest(url: URL(string:"http://58.27.84.166/mcconline/MCC%20Online%20V3/decom_pstn.php")!)
let task = URLSession.shared.dataTask(with: urlrequest){(data,response,error) in
if let data = data {
do{
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String : AnyObject]
var value:String = ""
if let summaryfromjson = json["totalsite"] as? String{
print(summaryfromjson)
value = summaryfromjson
}
var value2:String = ""
if let summaryfromjson2 = json["completesite"] as? String{
print(summaryfromjson2)
value2 = summaryfromjson2
}
var value3:String = ""
if let summaryfromjson3 = json["inprogresssite"] as? String{
print(summaryfromjson3)
value3 = summaryfromjson3
}
var value4:String = ""
if let summaryfromjson4 = json["pendingsite"] as? String{
print(summaryfromjson4)
value4 = summaryfromjson4
}
var value5:String = ""
if let summaryfromjson5 = json["payment"] as? String{
print(summaryfromjson5)
value5 = summaryfromjson5
}
var value6:String = ""
if let summaryfromjson6 = json["payreceive"] as? String{
print(summaryfromjson6)
value6 = summaryfromjson6
}
DispatchQueue.main.async {
self.totalsite.setTitle(value, for: .normal)
self.completesite.setTitle(value2, for: .normal)
self.dismantling.setTitle(value3, for: .normal)
self.remaining.setTitle(value4, for: .normal)
self.lockin.setTitle(value5, for: .normal)
self.balance.setTitle(value6, for: .normal)
}
}
catch let error as NSError {
print(error.localizedDescription)
}
}
else if let error = error {
print(error.localizedDescription)
}
}
task.resume()
}
func fetch2(){
let urlrequest = URLRequest(url: URL(string:"http://58.27.84.166/mcconline/MCC%20Online%20V3/query_listmonitoring.php")!)
let task = URLSession.shared.dataTask(with: urlrequest){(data,response,error) in
if let data = data {
do{
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String : AnyObject]
var value:String = ""
if let summaryfromjson = json["total"] as? String{
print(summaryfromjson)
value = summaryfromjson
}
DispatchQueue.main.async {
// self.migratedtext.setTitle(value, for: .normal)
}
}
catch let error as NSError {
print(error.localizedDescription)
}
}
else if let error = error {
print(error.localizedDescription)
}
}
task.resume()
}
func fetch3(){
let urlrequest = URLRequest(url: URL(string:"http://58.27.84.166/mcconline/MCC%20Online%20Dashboard_Yana/query_dashboard_header.php")!)
let task = URLSession.shared.dataTask(with: urlrequest){(data,response,error) in
if let data = data {
do{
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String : AnyObject]
var value:String = ""
if let summaryfromjson = json["totaltt"] as? String{
print(summaryfromjson)
value = summaryfromjson
}
var value2:String = ""
if let summaryfromjson2 = json["cabinetmonitor"] as? String{
print(summaryfromjson2)
value2 = summaryfromjson2
}
var value3:String = ""
if let summaryfromjson3 = json["totalaging"] as? String{
print(summaryfromjson3)
value3 = summaryfromjson3
}
DispatchQueue.main.async {
//self.totaltttext.setTitle(value, for: .normal)
//self.monitoringsites.setTitle(value2, for: .normal)
//self.activetttoday.setTitle(value3, for: .normal)
}
}
catch let error as NSError {
print(error.localizedDescription)
}
}
else if let error = error {
print(error.localizedDescription)
}
}
task.resume()
}
func fetch4(){
let urlrequest = URLRequest(url: URL(string:"http://58.27.84.166/mcconline/MCC%20Online%20V3/query_actual.php")!)
let task = URLSession.shared.dataTask(with: urlrequest){(data,response,error) in
if let data = data {
do{
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String : AnyObject]
var actualsubb:String = ""
if let summaryfromjson = json["subb"] as? String{
print(summaryfromjson)
actualsubb = summaryfromjson
}
var plansubbvalue:String = ""
if let summaryfromjson = json["plansubb"] as? String{
print(summaryfromjson)
plansubbvalue = summaryfromjson
}
var planfibervalue:String = ""
if let summaryfromjson = json["planfiber"] as? String{
print(summaryfromjson)
planfibervalue = summaryfromjson
}
var actualfibervalue:String = ""
if let summaryfromjson = json["fiber"] as? String{
print(summaryfromjson)
actualfibervalue = summaryfromjson
}
var actualcolovalue:String = ""
if let summaryfromjson = json["colo"] as? String{
print(summaryfromjson)
actualcolovalue = summaryfromjson
}
var plancolovalue:String = ""
if let summaryfromjson = json["plancolo"] as? String{
print(summaryfromjson)
plancolovalue = summaryfromjson
}
DispatchQueue.main.async {
//self.plancolo.setTitle(plancolovalue, for: .normal)
}
}
catch let error as NSError {
print(error.localizedDescription)
}
}
else if let error = error {
print(error.localizedDescription)
}
}
task.resume()
}
func fetch5(){
let urlrequest = URLRequest(url: URL(string:"http://58.27.84.166/mcconline/MCC%20Online%20V3/query_balancesubb.php")!)
let task = URLSession.shared.dataTask(with: urlrequest){(data,response,error) in
if let data = data {
do{
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String : AnyObject]
var value:String = ""
if let summaryfromjson = json["countsubb"] as? String{
print(summaryfromjson)
value = summaryfromjson
}
DispatchQueue.main.async {
// self.subbbalance.setTitle(value, for: .normal)
}
}
catch let error as NSError {
print(error.localizedDescription)
}
}
else if let error = error {
print(error.localizedDescription)
}
}
task.resume()
}
func fetch6(){
let urlrequest = URLRequest(url: URL(string:"http://58.27.84.166/mcconline/MCC%20Online%20V3/query_balancecolo.php")!)
let task = URLSession.shared.dataTask(with: urlrequest){(data,response,error) in
if let data = data {
do{
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String : AnyObject]
var value:String = ""
if let summaryfromjson = json["countcolo"] as? String{
print(summaryfromjson)
value = summaryfromjson
}
DispatchQueue.main.async {
// self.colobalance.setTitle(value, for: .normal)
}
}
catch let error as NSError {
print(error.localizedDescription)
}
}
else if let error = error {
print(error.localizedDescription)
}
}
task.resume()
}
func fetch7(){
let urlrequest = URLRequest(url: URL(string:"http://58.27.84.166/mcconline/MCC%20Online%20V3/query_balancefiber.php")!)
let task = URLSession.shared.dataTask(with: urlrequest){(data,response,error) in
if let data = data {
do{
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String : AnyObject]
var value:String = ""
if let summaryfromjson = json["countfiber"] as? String{
print(summaryfromjson)
value = summaryfromjson
}
DispatchQueue.main.async {
//self.fiberbalance.setTitle(value, for: .normal)
}
}
catch let error as NSError {
print(error.localizedDescription)
}
}
else if let error = error {
print(error.localizedDescription)
}
}
task.resume()
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView.contentOffset.x>0 {
scrollView.contentOffset.x = 0
}
}
func fetch8(){
let urlrequest = URLRequest(url: URL(string:"http://58.27.84.166/mcconline/MCC%20Online%20V3/Dashboard_json.php")!)
let task = URLSession.shared.dataTask(with: urlrequest){(data,response,error) in
if let data = data {
do{
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String : AnyObject]
var value:String = ""
if let summaryfromjson = json["totalplan"] as? String{
print(summaryfromjson)
value = summaryfromjson
}
DispatchQueue.main.async {
//self.todayplan.setTitle(value, for: .normal)
}
}
catch let error as NSError {
print(error.localizedDescription)
}
}
else if let error = error {
print(error.localizedDescription)
}
}
task.resume()
}
@IBAction func reloadbutton(_ sender: Any) {
// fetch1()
// fetch2()
// fetch3()
// fetch4()
// fetch5()
// fetch6()
// fetch7()
//
let date = Date()
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .none
formatter.locale = Locale(identifier: "en_US")
let result = formatter.string(from: date)
currentdate.setTitle(result, for: .normal)
self.title = "PSTN DECOMM 2018"
self.navigationController?.navigationBar.titleTextAttributes = [ NSAttributedStringKey.font: UIFont(name: "Arial", size: 12)!]
}
@IBAction func totalsiteaction(_ sender: Any) {
let myVC = storyboard?.instantiateViewController(withIdentifier: "totalsites") as! totalsites
myVC.section = "listtotalstatesite"
myVC.statestr = "totalstate"
navigationController?.pushViewController(myVC, animated: true)
}
@IBAction func completesite(_ sender: Any) {
let myVC = storyboard?.instantiateViewController(withIdentifier: "totalsites") as! totalsites
myVC.section = "listcompletestatesite"
myVC.statestr = "count(STATE)"
navigationController?.pushViewController(myVC, animated: true)
}
@IBAction func dismantlingaction(_ sender: Any) {
let myVC = storyboard?.instantiateViewController(withIdentifier: "totalsites") as! totalsites
myVC.section = "listinprogressstatesite"
myVC.statestr = "count(STATE)"
navigationController?.pushViewController(myVC, animated: true)
}
@IBAction func remainingaction(_ sender: Any) {
let myVC = storyboard?.instantiateViewController(withIdentifier: "totalsites") as! totalsites
myVC.section = "listpendingstatesite"
myVC.statestr = "count(STATE)"
navigationController?.pushViewController(myVC, animated: true)
}
}
|
//
// day8.swift
// AdventOfCode
//
// Created by Robbie Plankenhorn on 4/29/16.
// Copyright © 2016 Plankenhorn.net. All rights reserved.
//
import Foundation
private extension String {
func numberOfCharactersInEncodedString() -> UInt {
var count:UInt = 2
for c in self.characters {
print(c)
if c == "\"" {
count += 2
} else if c == "\\" {
count += 2
} else {
count += 1
}
}
return count
}
func numberOfCharactersInCode() -> UInt {
return UInt(self.stringByReplacingOccurrencesOfString("\"", withString: "aa").characters.count)
}
func numberOfCharactersInMemory() -> UInt {
var modifiedString = self
let regex = try! NSRegularExpression(pattern: "[\\u005C]x[A-Fa-f0-9]{2}", options: NSRegularExpressionOptions(rawValue: 0))
modifiedString = regex.stringByReplacingMatchesInString(modifiedString, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length: self.characters.count), withTemplate: "X")
modifiedString = modifiedString.stringByReplacingOccurrencesOfString("\\\\", withString: "\\")
return UInt(modifiedString.characters.count)
}
}
func day8Part1() -> UInt {
let strings = readInputFile("day8_input")!.componentsSeparatedByString("\n")
let numberOfCharactersInCode = strings.reduce(0, combine: {$0 + $1.numberOfCharactersInCode() })
let numberOfCharactersInMemory = strings.reduce(0, combine: {$0 + $1.numberOfCharactersInMemory() })
return numberOfCharactersInCode - numberOfCharactersInMemory
}
func day8Part2() -> UInt {
let strings = readInputFile("day8_input")!.componentsSeparatedByString("\n")
let numberOfCharactersInEncodedString = strings.reduce(0, combine: {$0 + $1.numberOfCharactersInEncodedString() })
let numberOfCharactersInCode = strings.reduce(0, combine: {$0 + UInt($1.characters.count) })
return numberOfCharactersInEncodedString - numberOfCharactersInCode
} |
//
// UserDetailController.swift
// Tinder-App
//
// Created by Миронов Влад on 18.10.2019.
// Copyright © 2019 Миронов Влад. All rights reserved.
//
import UIKit
import SDWebImage
class UserDetailController: UIViewController, UIScrollViewDelegate {
// MARK: - Private Properties
fileprivate var isFirstOpened = true
fileprivate let swipingPhotosController = SwipingPhotosController(isCardViewModel: false)
fileprivate let extraSwipingHeight: CGFloat = 80
fileprivate let extraPostionY: CGFloat = 0
// MARK: - Public Properties
var cardViewModel: CardViewModel! {
didSet{
infoLabel.attributedText = cardViewModel.attributedString
swipingPhotosController.cardViewModel = cardViewModel
}
}
let infoLabel: UILabel = {
let label = UILabel()
label.text = "User name 30\n Doctor\nSome Bio text"
label.numberOfLines = 0
return label
}()
let dismissButton: UIButton = {
let button = UIButton(type: .system)
button.setImage(#imageLiteral(resourceName: "icons8-circled_up").withRenderingMode(.alwaysOriginal), for: .normal)
button.addTarget(self, action: #selector(handleTapDismiss), for: .touchUpInside)
return button
}()
lazy var dislikeButton = self.createButtons(image: #imageLiteral(resourceName: "Nope"), selector: #selector(handleDislike))
lazy var superLikeButton = self.createButtons(image: #imageLiteral(resourceName: "Super Like"), selector: #selector(handleDislike))
lazy var likeButton = self.createButtons(image: #imageLiteral(resourceName: "Like"), selector: #selector(handleDislike))
lazy var scrollView: UIScrollView = {
let sv = UIScrollView()
sv.alwaysBounceVertical = true
sv.contentInsetAdjustmentBehavior = .never
sv.delegate = self
return sv
}()
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupLayout()
setupVisualBlurEffect()
setupBottomControls()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if isFirstOpened{
let swipingPhoto = swipingPhotosController.view!
swipingPhoto.frame = CGRect(x: 0, y: extraPostionY, width: view.frame.width, height: view.frame.width + extraSwipingHeight)
isFirstOpened = false
}
}
//MARK: - Delegate Method
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let imageView = swipingPhotosController.view!
let changeY = scrollView.contentOffset.y
if changeY < 70 && changeY > -1{
imageView.frame = CGRect(x: -changeY/2, y: -changeY/2 + extraPostionY, width: view.frame.width + changeY, height: view.frame.width + changeY + extraSwipingHeight)
}
}
// MARK: - Private Methods
fileprivate func setupBottomControls(){
let stackView = UIStackView(arrangedSubviews: [dislikeButton, superLikeButton, likeButton])
stackView.distribution = .fillEqually
stackView.spacing = 16
view.addSubview(stackView)
stackView.anchor(top: nil, leading: nil, bottom: view.safeAreaLayoutGuide.bottomAnchor, trailing: nil, padding: .init(top: 0, left: 0, bottom: 0, right: 0), size: .init(width: 270, height: 80))
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
}
fileprivate func createButtons(image: UIImage, selector: Selector) -> UIButton{
let button = UIButton(type: .system)
button.setImage(image.withRenderingMode(.alwaysOriginal), for: .normal)
button.addTarget(self, action: selector, for: .touchUpInside)
button.imageView?.contentMode = .scaleAspectFit
return button
}
fileprivate func setupVisualBlurEffect(){
let blurEffect = UIBlurEffect(style: .regular)
let visualEffect = UIVisualEffectView(effect: blurEffect)
view.addSubview(visualEffect)
visualEffect.anchor(top: view.topAnchor, leading: view.leadingAnchor, bottom: view.safeAreaLayoutGuide.topAnchor, trailing: view.trailingAnchor, padding: .init(top: 0, left: 0, bottom: 0, right: 0))
}
fileprivate func setupLayout() {
view.addSubview(scrollView)
scrollView.fillSuperview()
let swipingView = swipingPhotosController.view!
scrollView.addSubview(swipingView)
scrollView.addSubview(infoLabel)
infoLabel.anchor(top: swipingView.bottomAnchor, leading: scrollView.leadingAnchor, bottom: nil, trailing: scrollView.trailingAnchor, padding: .init(top: 16, left: 16, bottom: 0, right: 16))
view.backgroundColor = .white
view.addSubview(dismissButton)
dismissButton.anchor(top: swipingView.bottomAnchor, leading: nil, bottom: nil, trailing: view.trailingAnchor, padding: .init(top: -25, left: 0, bottom: 0, right: 23), size: .init(width: 50, height: 50))
}
//MARK: - Handlers
@objc fileprivate func handleDislike() {
print("Dislikeee")
}
@objc func handleTapDismiss(){
self.dismiss(animated: true)
}
}
|
import Foundation
import XCTest
import xcproj
@testable import xclintrules
final class PBXVariantGroup_ProjectLintableTests: XCTestCase {
func test_lintFails_whenChildrenAreMissing() {
let subject = PBXVariantGroup(reference: "ref", children: ["child"])
let project = PBXProj(objectVersion: 0, rootObject: "1")
let got = subject.lint(project: project)
let expected = LintError.missingReference(objectType: "PBXVariantGroup", objectReference: "ref", missingReference: "PBXFileReference/PBXGroup/PBXVariantGroup<child>")
XCTAssertEqual(got.first, expected)
}
}
|
import Nimble
import Quick
import Testable
class TitleValueTransformerSpec: QuickSpec {
override func spec() {
describe(TitleValueTransformer.self) {
describe(TitleValueTransformer.allowsReverseTransformation) {
it("should be false") {
expect(TitleValueTransformer.allowsReverseTransformation()) == false
}
}
describe(TitleValueTransformer.transformedValueClass) {
it("should be a string") {
expect(TitleValueTransformer.transformedValueClass()) === NSString.self
}
}
describe(TitleValueTransformer.transformedValue(_:)) {
var subject: TitleValueTransformer!
beforeEach {
subject = .init()
}
context(true) {
it("should show offline title") {
expect(subject.transformedValue(true) as? String) == "Connect Offline to Local Sparta"
}
}
context(false) {
it("should show online title") {
expect(subject.transformedValue(false) as? String) == "Connect to Sparta Science"
}
}
}
}
}
}
|
//: Playground - noun: a place where people can play
import UIKit
var lotteryWinnings: Int? // ? = this variable may or may not have a value
// Unrapping optional
if(lotteryWinnings != nil) { // this if statment is required
print(lotteryWinnings!) // ! = unrapping an optional
}
// Best way to unrap optional
if let winnings = lotteryWinnings {
print(winnings)
}
class Car {
var model: String?
}
var vehicle: Car? // Object declaration of a class that might have a value later
// Unrap object variable
if let v = vehicle {
if let m = v.model {
print(m)
}
} else {
print("no values for vehicle object")
}
print(vehicle?.model) // prints if there is a value and doesn't if not
vehicle = Car() // creates a car object
vehicle?.model = "Bronco" // ? tells the compiler that the object might not have a value
// Best way to unrap object variable
if let v = vehicle, let m = v.model {
print(m)
}
var cars: [Car]?
cars = [Car]() // Creates an array of car objects
if let carArr = cars, carArr.count > 0 { // Same as if let carArr = cars where carArr.count > 0
// only execute if not nil and if more than 0 elements
} else {
cars?.append(Car())
print(cars?.count)
}
// Class variables without using constructors
class Person {
var tempAge: Int! // Implicitly unwrapped optional: can be accessed with out failing if empty
var age: Int { // Computed property
if tempAge == nil {
tempAge = 2
}
return tempAge
}
func setAge(newAge: Int) {
self.tempAge = newAge
}
}
var jack = Person()
print(jack.tempAge) // nil
print(jack.age) // 2
print(jack.tempAge) // 2
// Class variables using variables
class Dog {
var species: String
init(someSpecies: String) { // Constructer
self.species = someSpecies
}
}
var lab = Dog(someSpecies: "Black Lab")
print(lab.species)
|
import UIKit
import SalesforceSDKCore
/// Protocol adopted by classes that wish to be informed when an `ObjectLayoutDataSource`
/// instance is updated.
protocol ObjectLayoutDataSourceDelegate: AnyObject {
/// Called when a data source has updated the value of its `fields` property.
///
/// - Parameter dataSource: The data source that was updated.
func objectLayoutDataSourceDidUpdateFields(_ dataSource: ObjectLayoutDataSource)
}
/// Supplies data to a `UITableView` for a list of fields belonging to a single object.
/// An instance of this class can be used as a table view's `dataSource`.
class ObjectLayoutDataSource: NSObject {
/// An individual field for an object retrieved from the Salesforce server.
typealias ObjectField = (label: String, value: String)
/// A closure that configures a given table view cell using the given
/// label and value for a field of the requested object.
typealias CellConfigurator = (ObjectField, UITableViewCell) -> Void
/// The type of object to request from the server.
let objectType: String
/// The unique identifier of the object to request from the server.
let objectId: String
/// The reuse identifier to use for dequeueing cells from the table view.
let cellReuseIdentifier: String
/// The closure to call for each cell being provided by the data source.
/// This will be called for each field in the object as it is displayed.
let cellConfigurator: CellConfigurator
/// The list of field names to omit from the results.
let fieldBlacklist = ["attributes", "Id"]
/// The fields for the object returned from the Salesforce server.
/// Each field is a tuple providing the `label` and `value` for the field.
private(set) var fields: [ObjectField] = []
/// The delegate to notify when the list of fields is updated.
weak var delegate: ObjectLayoutDataSourceDelegate?
/// Initializes a data source for a given object type and identifier.
///
/// - Parameters:
/// - objectType: The type of object to request from the server.
/// - objectId: The unique identifier of the object to request from the server.
/// - cellReuseIdentifier: The reuse identifier to use for dequeueing cells
/// from the table view.
/// - cellConfigurator: The closure to call for each cell being provided
/// by the data source.
init(objectType: String, objectId: String, cellReuseIdentifier: String, cellConfigurator: @escaping CellConfigurator) {
self.objectType = objectType
self.objectId = objectId
self.cellReuseIdentifier = cellReuseIdentifier
self.cellConfigurator = cellConfigurator
super.init()
}
/// Logs the given error.
///
/// This Project doesn't do any sophisticated error checking, and simply
/// uses this as the failure handler for `RestClient` requests. In a real-world
/// application, be sure to replace this with information presented to the user
/// that can be acted on.
///
/// - Parameters:
/// - error: The error to be logged.
/// - urlResponse: Ignored; this argument provides compatibility with
/// the `SFRestFailBlock` API.
private func handleError(_ error: Error?, urlResponse: URLResponse? = nil) {
let errorDescription: String
if let error = error {
errorDescription = "\(error)"
} else {
errorDescription = "An unknown error occurred."
}
SalesforceLogger.e(type(of: self), message: "Failed to successfully complete the REST request. \(errorDescription)")
}
/// Retrieves the compact layout metadata for the given object type, and
/// based on the field list, constructs a request to retrieve the fields
/// for the object with the given ID.
///
/// - Parameters:
/// - objectType: The type of object to request from the server.
/// - objectId: The unique identifier of the object to request from the server.
/// - completionHandler: The closure to call when the request completes.
/// - request: The request that was built, which can be used to retrieve
/// the fields for the object.
private func buildRequestFromCompactLayout(forObjectType objectType: String, objectId: String, completionHandler: @escaping (_ request: RestRequest) -> Void) {
let layoutRequest = RestRequest(method: .GET, path: "v44.0/compactLayouts", queryParams: ["q": objectType])
layoutRequest.parseResponse = false
RestClient.shared.send(request: layoutRequest, onFailure: handleError) { response, _ in
guard let responseData = response as? Data else { return }
do {
// The root object of the compact layouts response is a dictionary
// that maps object type names to their layouts. The first step
// is to find the requested object type in the dictionary.
let decodedJSON = try JSONDecoder().decode([String: CompactLayout].self, from: responseData)
guard let layout = decodedJSON[objectType] else {
SalesforceLogger.e(type(of: self), message: "Missing \(objectType) object type in response.")
return
}
// The layout contains a list of fields (`fieldItems`), each of which
// has an array of layout components, where the `value` of the layout
// component is the field name.
let fields = layout.fieldItems.compactMap { $0.layoutComponents.first?.value }
let fieldList = fields.joined(separator: ", ")
// Now a request can be built for the list of fields.
let dataRequest = RestClient.shared.requestForRetrieve(withObjectType: objectType, objectId: objectId, fieldList: fieldList)
completionHandler(dataRequest)
} catch {
self.handleError(error)
}
}
}
/// Sends the given request and parses the result into the `fields` list.
///
/// - Parameter request: The request to send.
private func retrieveData(for request: RestRequest) {
RestClient.shared.send(request: request, onFailure: handleError) { [weak self] response, _ in
guard let self = self else { return }
var resultsToReturn = [ObjectField]()
if let dictionaryResponse = response as? [String: Any] {
resultsToReturn = self.fields(from: dictionaryResponse)
}
DispatchQueue.main.async {
self.fields = resultsToReturn
self.delegate?.objectLayoutDataSourceDidUpdateFields(self)
}
}
}
/// Transforms the fields in the record into `ObjectField` values, omitting
/// any fields that are in the blacklist or that are not strings.
///
/// - Parameter record: The record to be transformed.
/// - Returns: The list of object fields extracted from the record.
private func fields(from record: [String: Any]) -> [ObjectField] {
let filteredRecord = record.lazy.filter { key, value in !self.fieldBlacklist.contains(key) && value is String }
return filteredRecord.map { key, value in (label: key, value: value as! String) }
}
/// Retrieves the compact layout for the `objectType` and then fetches the
/// fields specified in the layout for the object identified by `objectId`.
///
/// When it successfully completes, the `fields` property is set, and the
/// delegate is notified of the update.
@objc func fetchData() {
self.buildRequestFromCompactLayout(forObjectType: self.objectType, objectId: self.objectId) { request in
self.retrieveData(for: request)
}
}
}
extension ObjectLayoutDataSource: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fields.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath)
cellConfigurator(fields[indexPath.row], cell)
return cell
}
}
|
//
// Recipe.swift
// Recipe
//
// Created by Shrikanta Mazumder on 18/8/21.
//
import Foundation
class Recipe: Identifiable, Decodable {
var id: UUID?
var name: String = ""
var category: String
var featured: Bool
var image: String
var description: String
var prepTime: String
var cookTime: String
var servings: Int
var highlights: [String]
var ingredients: [Ingradient]
var directions: [String]
}
class Ingradient: Identifiable, Decodable {
var id: UUID?
var name: String
var num: Int?
var denom: Int?
var unit: String?
}
|
//
// TwoSumViewController.swift
// LeetCode-Swift-master
//
// Created by lengain on 2019/1/14.
// Copyright © 2019 Lengain. All rights reserved.
//
import UIKit
class TwoSumViewController: LNBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print(Solution1.twoSum([2,7,11,5], 9))
print(Solution1.twoSum([2,7,11,5], 13))
print(Solution1.twoSum([2,7,11,5], 18))
print()
print(Solution2.twoSum([2,7,11,5], 9))
print(Solution2.twoSum([2,7,11,5], 13))
print(Solution2.twoSum([2,7,11,5], 18))
print()
print(Solution3.twoSum([2,7,11,5], 9))
print(Solution3.twoSum([2,7,11,5], 13))
print(Solution3.twoSum([2,7,11,5], 18))
}
/// 方法一:暴力破解法
/// 复杂度分析:
/// 时间复杂度:O(n^2), 对于每个元素,我们试图通过遍历数组的其余部分来寻找它所对应的目标元素,这将耗费 O(n)的时间。因此时间复杂度为 O(n^2)
/// 空间复杂度:O(1)
class Solution1 {
class func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
for i in 0..<nums.count {
for j in i + 1..<nums.count {
if nums[i] + nums[j] == target {
return [i,j]
}
}
}
return [];
}
}
/// 方法二:两遍哈希表
/// 为了对运行时间复杂度进行优化,我们需要一种更有效的方法来检查数组中是否存在目标元素。如果存在,我们需要找出它的索引。保持数组中的每个元素与其索引相互对应的最好方法是什么?哈希表。
/// 通过以空间换取速度的方式,我们可以将查找时间从 O(n) 降低到 O(1)。哈希表正是为此目的而构建的,它支持以 近似 恒定的时间进行快速查找。我用“近似”来描述,是因为一旦出现冲突,查找用时可能会退化到 O(n)。但只要你仔细地挑选哈希函数,在哈希表中进行查找的用时应当被摊销为 O(1)。
/// 一个简单的实现使用了两次迭代。在第一次迭代中,我们将每个元素的值和它的索引添加到表中。然后,在第二次迭代中,我们将检查每个元素所对应的目标元素(target - nums[i])是否存在于表中。注意,该目标元素不能是 nums[i]nums[i] 本身!
class Solution2 {
class func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
let values = NSMutableDictionary.init()
for i in 0..<nums.count {
values.setValue(NSNumber.init(value: i), forKey: "\(nums[i])")
}
let setKeys = NSSet.init(array: nums);
for i in 0..<nums.count {
let diff = target - nums[i];
if setKeys.contains(diff) {
let index : NSNumber = values.object(forKey: "\(diff)") as! NSNumber
if index.intValue != i {
return [i,index.intValue]
}
}
}
return []
}
}
class Solution3 {
class func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
let values = NSMutableDictionary.init()
for i in 0..<nums.count {
values.setValue(NSNumber.init(value: i), forKey: "\(nums[i])")
let setKeys = NSSet.init(array: values.allKeys);
let diff = target - nums[i];
if setKeys.contains("\(diff)") {
let index : NSNumber = values.object(forKey: "\(diff)") as! NSNumber
if index.intValue != i {
return [index.intValue, i]
}
}
}
return []
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// DexSignInVC.swift
// VampÏr
//
// Created by 60436 on 4/13/18.
// Copyright © 2018 Spencer Crow. All rights reserved.
//
import UIKit
import ObjectMapper
class DexSignInVC: UIViewController {
@IBOutlet weak var lblUser: UITextField!
@IBOutlet weak var lblPass: UITextField!
@IBAction func btnLogin(_ sender: Any) {
login()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vcc = segue.destination as? LinkVC {
vcc.realLink = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//Looks for single or multiple taps.
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(SignUpVC.dismissKeyboard))
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func login() {
let parameters = ["username":lblUser.text,"password":lblPass.text]
NetworkCallManager.baseURLRequest(urlString: Endpoints.base + Endpoints.encrypt, parameters: parameters, method: .post, completion: {json in
let map = Map(mappingType: MappingType.fromJSON, JSON: json)
let message = Message(map: map)
UserDefaults.standard.set(message!.message, forKey: "message")
}, errorHandler: {_ in
//error modal
//remove
fatalError()
})
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// File.swift
// Metronome
//
// Created by Jocelyn Griselle on 27/04/2020.
// Copyright © 2020 Jocelyn Griselle. All rights reserved.
//
import AVFoundation
import SwiftUI
import MediaPlayer
class MusicalGenreAudioPlayer : ObservableObject {
@Published var genre : MusicalGenre
@Published var isPlaying : Bool
@Published var isRunning : Bool
@Published var bpm : Float
private var engine : AVAudioEngine
private var speedControl : AVAudioUnitVarispeed
private var pitchControl : AVAudioUnitTimePitch
private var playerNode : AVAudioPlayerNode
private var userData: UserData
init(genre: MusicalGenre) {
self.userData = UserData()
self.genre = genre
self.bpm = genre.bpm
self.isPlaying = false
self.isRunning = false
self.engine = AVAudioEngine()
self.speedControl = AVAudioUnitVarispeed()
self.pitchControl = AVAudioUnitTimePitch()
self.playerNode = AVAudioPlayerNode()
connect()
setupRemoteTransportControls()
start() // should not be in init
}
func connect() {
// connect the components to our playback engine
engine.attach(playerNode)
engine.attach(pitchControl)
engine.attach(speedControl)
// arrange the parts so that output from one is input to another
engine.connect(playerNode, to: speedControl, format: nil)
engine.connect(speedControl, to: pitchControl, format: nil)
engine.connect(pitchControl, to: engine.mainMixerNode, format: nil)
}
func loadAudioFile() {
let audioFormat = genre.loop.processingFormat
let audioFrameCount = UInt32(self.genre.loop.length)
let audioFileBuffer = AVAudioPCMBuffer(pcmFormat: audioFormat, frameCapacity: audioFrameCount)
try? genre.loop.read(into: audioFileBuffer!)
playerNode.scheduleBuffer(audioFileBuffer!, at: nil, options:.loops, completionHandler: nil)
playerNode.scheduleFile(genre.loop, at:nil)
}
func changeMusicalGenre(genre: MusicalGenre) {
stop()
self.genre = genre
start()
play()
}
func start() {
try? engine.start()
isRunning = true
self.loadAudioFile()
}
func play() {
if !engine.isRunning { try? engine.start() }
playerNode.play()
isPlaying = true
setupNowPlaying(playing: true)
}
func pause() {
setupNowPlaying(playing: false)
isPlaying = false
playerNode.pause()
engine.pause()
}
func next() {
if let index = self.userData.musicalGenres.firstIndex(of: self.genre) {
changeMusicalGenre(genre: self.userData.musicalGenres[(index+1) % self.userData.musicalGenres.count])
}
changeMusicalGenre(genre:self.userData.musicalGenres[0])
}
func previous() {
if let index = self.userData.musicalGenres.firstIndex(of: self.genre) {
changeMusicalGenre(genre: self.userData.musicalGenres[(index-1) % self.userData.musicalGenres.count])
}
changeMusicalGenre(genre:self.userData.musicalGenres[0])
}
func stop() {
playerNode.stop()
engine.stop()
withAnimation {
isPlaying = playerNode.isPlaying
isRunning = engine.isRunning
}
}
func setRate(rate : Float) {
speedControl.rate = rate
}
func setBpm(rate : Float) {
bpm = genre.bpm * rate
setRate(rate :rate)
setPitch(rate: rate)
}
func setBpm() {
let rate = self.bpm / self.genre.bpm
setRate(rate :rate)
setPitch(rate: rate)
//setupNowPlaying()
}
func setPitch(rate : Float) {
pitchControl.pitch = -1200 * (log2(rate) / log2(2))
}
func setupRemoteTransportControls() {
let commandCenter = MPRemoteCommandCenter.shared()
// Disable all buttons you will not use (including pause and togglePlayPause commands)
[commandCenter.changeRepeatModeCommand, commandCenter.stopCommand, commandCenter.changeShuffleModeCommand, commandCenter.changePlaybackRateCommand, commandCenter.seekBackwardCommand, commandCenter.seekForwardCommand, commandCenter.skipBackwardCommand, commandCenter.skipForwardCommand, commandCenter.changePlaybackPositionCommand, commandCenter.ratingCommand, commandCenter.likeCommand, commandCenter.dislikeCommand, commandCenter.bookmarkCommand].forEach {
$0.isEnabled = false
}
commandCenter.playCommand.addTarget { [unowned self] event in
self.play()
return .success
//return .commandFailed
}
commandCenter.pauseCommand.addTarget { [unowned self] event in
self.pause()
return .success
//return .commandFailed
}
commandCenter.nextTrackCommand.addTarget { [unowned self] event in
self.next()
return .success
//return .commandFailed
}
commandCenter.previousTrackCommand.addTarget { [unowned self] event in
self.previous()
return .success
//return .commandFailed
}
}
func elapsedPlaybackTime() -> Double {
guard let nodeTime = playerNode.lastRenderTime, let playerTime = playerNode.playerTime(forNodeTime: nodeTime) else {
return 0.0
}
return Double(TimeInterval(playerTime.sampleTime) / playerTime.sampleRate)
}
func getArtWork() -> MPMediaItemArtwork {
let image = UIImage(cgImage: self.genre.cgImage)
return MPMediaItemArtwork(boundsSize: image.size, requestHandler: { size in
return image
})
}
func setupNowPlaying(playing:Bool=false) {
let nowPlayingInfoCenter = MPNowPlayingInfoCenter.default()
var nowPlayingInfo = [String: Any]()
nowPlayingInfo[MPMediaItemPropertyTitle] = self.genre.name
nowPlayingInfo[MPNowPlayingInfoPropertyMediaType] = MPNowPlayingInfoMediaType.audio.rawValue
nowPlayingInfo[MPMediaItemPropertyArtist] = "\(Int(self.bpm)) BPM"
nowPlayingInfo[MPMediaItemPropertyArtwork] = self.getArtWork()
// let elapsed = elapsedPlaybackTime()
// nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = elapsed
// let audioNodeFileLength = AVAudioFrameCount(self.genre.loop.length)
// nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = Double(Double(audioNodeFileLength) / 44100)
// nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackProgress] = elapsed
// / Double(Double(audioNodeFileLength) / 44100)
// nowPlayingInfo[MPNowPlayingInfoPropertyDefaultPlaybackRate] = NSNumber(value:1.0)
nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = NSNumber(value: playing ? speedControl.rate : 0.0)
nowPlayingInfoCenter.nowPlayingInfo = nowPlayingInfo
print("PLAYING: \(playing)")
print(nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] as Any)
print(nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackProgress] as Any)
print(nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] as Any
)
print(nowPlayingInfoCenter.playbackState.rawValue)
print("END")
}
}
|
// Created by Dominik on 10/07/2016.
// The MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// v2.1
import StoreKit
/*
Swifty Receipt Obtainer
Singleton class to manage in app purchase receipt fetching.
*/
final class SwiftyReceiptObtainer: NSObject {
// MARK: - Static Properties
/// Shared instance
static let shared = SwiftyReceiptObtainer()
// MARK: - Properties
/// Receipt url
fileprivate let receiptURL = Bundle.main.appStoreReceiptURL
/// Completion handler
fileprivate var handler: ((URL?) -> ())?
/// Check if receipt exists at patch
fileprivate var isReceiptExistsAtPath: Bool {
guard let path = receiptURL?.path, FileManager.default.fileExists(atPath: path) else { return false }
return true
}
// MARK: - Init
/// Private singleton init
private override init () { }
// MARK: - Methods
/// Fetch app store in app purchase receipt
func fetch(handler: @escaping (URL?) -> ()) {
self.handler = handler
guard isReceiptExistsAtPath else {
print("Requesting a new receipt")
let request = SKReceiptRefreshRequest(receiptProperties: nil)
request.delegate = self
request.start()
return
}
print("Receipt found")
self.handler?(receiptURL)
}
}
// MARK: - Delegates
// SKRequestDelegate
extension SwiftyReceiptObtainer: SKRequestDelegate {
/// Request did finish
func requestDidFinish(_ request: SKRequest) {
print("Receipt request did finish")
guard isReceiptExistsAtPath else {
print("Could not obtainin the receipt from the receipt request, maybe the user did not successfully enter it's credentials")
handler?(nil)
return
}
print("Newly created receipt found")
handler?(receiptURL)
}
/// Request did fail with error
func request(_ request: SKRequest, didFailWithError error: Error) {
print(error.localizedDescription)
handler?(nil)
}
}
|
//
// FoodPersistence.swift
// foodprint-hackathon-app
//
// Created by EricM on 12/18/19.
// Copyright © 2019 Sunni Tang. All rights reserved.
//
import Foundation
struct FoodPersistenceHelper {
static let manager = FoodPersistenceHelper()
func saveUser(newUser: Food) throws {
try persistenceHelper.save(newElement: newUser)
}
func getUser() throws -> [Food] {
return try persistenceHelper.getObjects()
}
private let persistenceHelper = PersistenceHelper<Food>(fileName: "mySavedFood.plist")
private init() {}
}
|
//
// Story.swift
// HackerNews
//
// Created by Julio Ismael Robles on 22/11/2021.
//
import Foundation
struct Story: Codable {
let id: Int
let title: String
let url: String
}
extension Story {
static func placeholder() -> Story {
return Story(id: 0, title: "", url: "")
}
}
|
//
// TMNewAddressTableViewCell.swift
// consumer
//
// Created by Gregory Sapienza on 1/12/17.
// Copyright © 2017 Human Ventures Co. All rights reserved.
//
import UIKit
protocol TMNewAddressTableViewCellProtocol {
/// Text field in cell has become the first responder.
///
/// - Parameter cell: Cell where text field was selected.
func textFieldSelected(cell: TMNewAddressTableViewCell)
/// Text field is no longer the first responder.
///
/// - Parameters:
/// - cell: Cell where text field will no longer be the first responder.
/// - text: Text from text field.
func textFieldEndedEditing(cell: TMNewAddressTableViewCell, text: String)
}
class TMNewAddressTableViewCell: UITableViewCell {
//MARK: - Public iVars
var isDarkStyle = false
/// Title label displaying on top of cell.
@IBOutlet weak var titleLabel: UILabel!
/// Cell text field content with a placeholder value.
@IBOutlet weak var textField: UITextField!
/// Validation view line on bottom of cell.
@IBOutlet weak var validationView: UIView!
/// Row index of this cell. Should be set by table datasource.
var addressField: AddressField? {
didSet {
switch addressField!.fieldType() {
case let .picker(items, textEntryAllowed):
let picker = TMNewAddressPickerInput()
pickerInput = TMNewAddressInput(picker)
pickerInput?.backingData = items
pickerInput?.textEntryAllowed = textEntryAllowed
pickerInput?.textField = textField
textField.inputView = picker.generate()
break
default:
textField.inputView = nil
break
}
}
}
/// Delegate for table view cell.
var delegate: TMNewAddressTableViewCellProtocol?
//MARK: - Private iVars
/* These are input views. Currently there must be a reference for every input aside from the standard keyboard that we support for text fields.
This is because Swift does not currently support covariance with generics yet. In the future when this is supported a more ideal solution would be.
private var input: TMNewAddressInput<Any, Any, Any>?
With the above, you would be able to cast one input object to fit any type.
*/
/// Picker input complying with TMNewAddressInputProtocol.
var pickerInput: TMNewAddressInput<UIPickerView, Int, [String]>?
//MARK: - Public
override func awakeFromNib() {
super.awakeFromNib()
textField.delegate = self
titleLabel.textColor = UIColor.TMGrayColor
if DeviceType.IS_IPHONE_6P {
textField.font = UIFont.ActaBook(20.0)
titleLabel.font = UIFont.MalloryMedium(14.0)
}
else {
textField.font = UIFont.ActaBook(18.0)
titleLabel.font = UIFont.MalloryMedium(12.0)
}
guard let text = titleLabel.text else {
return
}
let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(NSKernAttributeName, value: 1.2, range: NSMakeRange(0, text.characters.count))
titleLabel.attributedText = attributedString
}
override func layoutSubviews() {
super.layoutSubviews()
contentView.layoutIfNeeded()
guard let addressField = addressField else {
return
}
textField.removeSubviews()
switch addressField.fieldType() {
case .picker(_):
guard let pickerInput = pickerInput else {
print("Picker input is nil.")
return
}
pickerInput.loadTextfieldSubviews()
default:
break
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
if selected {
if !isDarkStyle {
titleLabel.textColor = UIColor.TMTitleBlackColor
validationView.backgroundColor = UIColor.TMTitleBlackColor
}
else {
titleLabel.textColor = UIColor.TMPinkColor
validationView.backgroundColor = UIColor.TMPinkColor
}
}
else {
if isDarkStyle {
titleLabel.textColor = UIColor.TMGrayCell
validationView.backgroundColor = UIColor.TMGrayCell
}
else {
titleLabel.textColor = UIColor.TMLightGrayPlaceholder
validationView.backgroundColor = UIColor.TMColorWithRGBFloat(74.0, green: 74.0, blue: 74.0, alpha: 0.1)
}
}
}
}
// MARK: - UITextFieldDelegate
extension TMNewAddressTableViewCell: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
guard let addressField = addressField else {
return
}
switch addressField.fieldType() {
case .picker(_):
guard let pickerInput = pickerInput else {
print("Picker input is nil.")
return
}
pickerInput.textFieldDidBeginEditing()
default:
break
}
delegate?.textFieldSelected(cell: self)
}
/// Determines if text editing should complete editing. This function should go in textFieldDidEndEditing but an issue with IQKeyboardManager makes it so that the keyboard is stuck do to a not functioning done button. This is do to the order in which text field notifications are called and how IQKeyboardManager handles them.
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
guard let addressField = addressField else {
return true
}
switch addressField.fieldType() {
case .picker(_):
guard let pickerInput = pickerInput else {
print("Picker input is nil.")
return true
}
if pickerInput.textFieldShouldEndEditing() {
guard let text = textField.text else { //Text is set in textFieldShouldEndEditing function. So text must be referenced here.
print("Text field is empty.")
return true
}
delegate?.textFieldEndedEditing(cell: self, text: text)
return true
} else {
return false
}
default:
guard let text = textField.text else {
print("Text field is empty.")
return true
}
delegate?.textFieldEndedEditing(cell: self, text: text)
return true
}
}
}
|
//
// OptionTableViewCell.swift
// huicheng
//
// Created by lvxin on 2018/4/13.
// Copyright © 2018年 lvxin. All rights reserved.
//
import UIKit
let OptionTableViewCellID = "OptionTableViewCell_ID"
let OptionTableViewCellH = CGFloat(50)
class OptionTableViewCell: UITableViewCell {
@IBOutlet weak var titleNameLabel: UILabel!
@IBOutlet weak var contentLabel: UILabel!
func setData_caseDetail(titleStr : String,contentStr : String) {
self.titleNameLabel.text = titleStr
self.contentLabel.text = contentStr
}
func setOptionData(contentStr : String) {
self.contentLabel.text = contentStr
}
func setDataOption(titleStr : String) {
self.titleNameLabel.text = "报销类型"
self.contentLabel.text = titleStr
}
func setDataObject(titleStr : String,contentStr : String) {
self.titleNameLabel.text = titleStr
self.contentLabel.text = contentStr
}
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
}
}
|
//
// Package.swift
// Brewlet
//
// Created by zzada on 2/21/20.
//
import Foundation
struct Package {
var name: String
var desc: String?
var outdated: Bool
var versions: Version
var installed_on_request: Bool
var installed: [InstalledPackage]
func getInstalledVersion() -> String? {
var version: String? = nil
if !installed.isEmpty {
version = installed[0].version
}
return version
}
}
struct Version {
var stable: String
}
struct InstalledPackage {
var version: String
var installed_on_request: Bool
var installed_as_dependency: Bool
}
func packagesFromJson(jsonData: Data) throws -> [Package] {
var packages = [Package]()
if let elements = try JSONSerialization.jsonObject(with: jsonData) as? [NSDictionary] {
for element in elements {
let name = element["name"] as? String ?? "Unknown"
let desc = element["desc"] as? String
let outdated = element["outdated"] as? Bool ?? false
// Versions
var versions = Version(stable: "?")
if let versionsElement = element["versions"] as? NSDictionary {
let stable = versionsElement["stable"] as? String ?? "?"
versions = Version(stable: stable)
}
var installedPackages = [InstalledPackage]()
if let installedElements = element["installed"] as? [NSDictionary] {
for installedElement in installedElements {
let version = installedElement["version"] as? String ?? "Unknown"
let isRequested = installedElement["installed_on_request"] as? Bool ?? false
let isDependency = installedElement["installed_as_dependency"] as? Bool ?? false
installedPackages.append(InstalledPackage(version: version,
installed_on_request: isRequested,
installed_as_dependency: isDependency))
}
}
let isRequested : Bool = installedPackages.filter{$0.installed_on_request}.count > 0
packages.append(Package(name: name,
desc: desc,
outdated: outdated,
versions: versions,
installed_on_request: isRequested,
installed: installedPackages))
}
}
return packages
}
|
//
// UISearchBar.swift
// Essentials
//
// Created by Micha Volin on 2017-05-03.
// Copyright © 2017 Vmee. All rights reserved.
//
|
//
// ViewModel.swift
// ViewModel
//
// Created by MIZUKI ISHII on 2019/02/09.
// Copyright © 2019 MIZUKI ISHII. All rights reserved.
//
import Foundation
|
//
// ZTextEditor.swift
// Seriously
//
// Created by Jonathan Sand on 2/19/18.
// Copyright © 2018 Jonathan Sand. All rights reserved.
//
import Foundation
#if os(OSX)
import AppKit
#elseif os(iOS)
import UIKit
#endif
let gTextEditor = ZTextEditor()
var gCurrentlySelectedText : String? { return gCurrentlyEditingWidget?.text?.substring(with: gTextEditor.selectedRange) }
var gCurrentlyEditingWidget : ZoneTextWidget? { return gTextEditor.currentTextWidget }
class ZTextPack: NSObject {
let createdAt = Date()
var packedZone : Zone?
var packedTrait : ZTrait?
var originalText : String?
var textWidget : ZoneTextWidget? { return widget?.textWidget }
var widget : ZoneWidget? { return packedZone?.widget }
var adequatelyPaused : Bool { return Date().timeIntervalSince(createdAt) > 0.1 }
var emptyName: String {
if let trait = packedTrait {
return trait .emptyName
} else if let zone = packedZone {
return zone .emptyName
}
return kNoValue
}
var unwrappedName: String {
if let trait = packedTrait {
return trait .unwrappedName
} else if let zone = packedZone {
return zone .unwrappedName
}
return kNoValue
}
var textWithSuffix: String {
var result = emptyName
if let zone = packedZone {
result = zone.unwrappedNameWithEllipses(zone.isInFavorites)
let dups = zone.duplicateZones.count
let bad = zone.hasBadRecordName
var need = dups
if bad { // bad trumps dups
need = -1
} else if need == 0 { // dups trump count mode
switch gCountsMode {
case .fetchable: need = zone.indirectCount
case .progeny: need = zone.progenyCount
default: return result
}
}
var suffix: String?
// //////////////////////////////////
// add suffix for "show counts as" //
// //////////////////////////////////
if gPrintModes.contains(.dNames), let name = zone.recordName {
suffix = name
} else {
var showNeed = (need > 1) && (!zone.isExpanded || (gCountsMode == .progeny))
if (dups > 0 && need > 0 && gIsShowingDuplicates) || bad {
showNeed = true
}
if showNeed {
suffix = String(describing: need)
}
}
if let s = suffix {
result.append(" ( \(s) )")
}
}
return result
}
// MARK: - internals: editing zones and traits
// MARK: -
convenience init(_ iZRecord: ZRecord) {
self.init()
self.setup(for: iZRecord)
}
func updateText(isEditing: Bool = false) {
var text = isEditing ? unwrappedName : textWithSuffix
if !isEditing,
let w = widget {
let isLinear = w.isLinearMode
let threshold = isLinear ? 18 : 20
let type = w.widgetType
if threshold < text.length,
!type.contains(.tExemplar),
!type.contains(.tBigMap) || !isLinear { // is in favorites or is circular
let isLine = text[0] == kHyphen
text = text.substring(toExclusive: isLinear ? isLine ? 20 : 15 : 10) // shorten to fit (in small map area or in circles)
if !isLine {
text.append(kEllipsis)
}
}
}
textWidget?.setText(text)
}
func setup(for iZRecord: ZRecord) {
packedTrait = iZRecord as? ZTrait // do this first
packedZone = iZRecord as? Zone ?? packedTrait?.ownerZone
originalText = unwrappedName
textWidget?.setText(originalText)
}
func isEditing(_ iZRecord: ZRecord) -> Bool {
return packedZone == iZRecord || packedTrait == iZRecord
}
func updateWidgetsForEndEdit() {
if let z = packedZone,
let w = gWidgets.widgetForZone(z),
let t = w.textWidget {
t.abortEditing() // NOTE: this does NOT remove selection highlight
t.deselectAllText()
t.updateTextColor()
t.updateText()
}
}
func capture(_ iText: String?) {
if let text = iText == emptyName ? nil : iText {
if let trait = packedTrait { // traits take logical priority
trait.ownerZone?.setTraitText(text, for: trait.traitType)
} else if let zone = packedZone { // ignore zone if editing a trait, above
zone.zoneName = text.unescaped
zone.zRecords?.removeFromLocalSearchIndex(nameOf: zone)
zone.addToLocalSearchIndex()
}
}
}
func removeSuffix(from iText: String?) -> String? {
var newText: String?
if let components = iText?.components(separatedBy: " (") {
newText = components[0]
if newText == emptyName || newText == kEmpty {
newText = nil
}
}
return newText
}
func captureTextAndUpdateWidgets(_ iText: String?) {
capture(iText)
updateWidgetsForEndEdit()
}
func captureText(_ iText: String?, redrawSync: Bool = false) {
if (iText == emptyName || iText == kEmpty) {
if let type = packedTrait?.traitType {
packedZone?.removeTrait(for: type) // trait text was deleted (email, hyperlink)
}
} else if iText != originalText {
let newText = removeSuffix(from: iText)
gTextCapturing = true
if let w = textWidget {
let original = originalText
prepareUndoForTextChange(gUndoManager) { [self] in
originalText = w.text
captureText(original, redrawSync: true)
w.updateGUI()
}
}
captureTextAndUpdateWidgets(newText)
if packedTrait == nil { // only if zone name is being edited
updateBookmarkAssociates()
}
}
gTextCapturing = false
if redrawSync {
gRelayoutMaps()
}
}
func updateBookmarkAssociates() {
if var zone = packedZone,
let newText = zone.zoneName {
if let target = zone.bookmarkTarget {
zone = target
ZTextPack(target).captureTextAndUpdateWidgets(newText)
}
for bookmark in zone.bookmarksTargetingSelf {
ZTextPack(bookmark).captureTextAndUpdateWidgets(newText)
}
}
}
func prepareUndoForTextChange(_ manager: UndoManager?,_ onUndo: @escaping Closure) {
if let text = textWidget?.text,
text != originalText {
manager?.registerUndo(withTarget:self) { iUndoSelf in
let newText = iUndoSelf.textWidget?.text ?? kEmpty
iUndoSelf.originalText = newText
iUndoSelf.textWidget?.setText(iUndoSelf.originalText)
onUndo()
}
}
}
}
class ZTextEditor: ZTextView {
var cursorOffset : CGFloat?
var currentOffset : CGFloat?
var currentEdit : ZTextPack?
var currentlyEditedZone : Zone? { return currentEdit?.packedZone }
var currentTextWidget : ZoneTextWidget? { return currentlyEditedZone?.widget?.textWidget }
var currentZoneName : String { return currentlyEditedZone?.zoneName ?? kEmpty }
var currentFont : ZFont { return currentTextWidget?.font ?? gBigFont }
var atEnd : Bool { return selectedRange.lowerBound == currentTextWidget?.text?.length ?? -1 }
var atStart : Bool { return selectedRange.upperBound == 0 }
// MARK: - editing
// MARK: -
func clearOffset() { currentOffset = nil }
func clearEdit() {
currentEdit = nil
clearOffset()
fullResign()
gSetMapWorkMode()
}
func cancel() {
if let e = currentEdit,
let zone = currentlyEditedZone {
clearEdit()
zone.grab()
e.updateWidgetsForEndEdit()
}
}
@discardableResult func updateText(inZone: Zone?, isEditing: Bool = false) -> ZTextPack? {
var pack: ZTextPack?
if let zone = inZone {
pack = ZTextPack(zone)
pack?.updateText(isEditing: isEditing)
}
return pack
}
@discardableResult func edit(_ zRecord: ZRecord, setOffset: CGFloat? = nil, immediately: Bool = false) -> ZTextEditor {
if (currentEdit == nil || !currentEdit!.isEditing(zRecord)) { // prevent infinite recursion inside becomeFirstResponder, called below
let pack = ZTextPack(zRecord)
if let zone = pack.packedZone,
zone.userCanWrite {
currentEdit = pack
printDebug(.dEdit, " MAYBE " + zone.unwrappedName)
deferEditingStateChange()
pack.updateText(isEditing: true) // updates drawnSize of textWidget
gSelecting.ungrabAll(retaining: [zone]) // so crumbs will appear correctly
gSetEditIdeaMode()
if let t = zone.widget?.textWidget {
t.enableUndo()
assignAsFirstResponder(t)
}
if let at = setOffset ?? gCurrentMouseDownLocation {
setCursor(at: at)
}
gSignal([.spCrumbs, .spPreferences])
}
}
return self
}
func placeCursorAtEnd() {
selectedRange = NSMakeRange(-1, 0)
}
func applyPreservingOffset(_ closure: Closure) {
let o = currentOffset
closure()
currentOffset = o
}
func applyPreservingEdit(_ closure: Closure) {
let e = currentEdit
applyPreservingOffset {
closure()
}
currentEdit = e
}
func quickStopCurrentEdit() {
if let e = currentEdit {
applyPreservingEdit {
capture()
e.packedZone?.grab()
}
}
}
func stopCurrentEdit(forceCapture: Bool = false, andRedraw: Bool = true) {
if let e = currentEdit, !gIsEditingStateChanging {
let zone = e.packedZone
capture(force: forceCapture)
clearEdit()
fullResign()
e.updateWidgetsForEndEdit()
zone?.grab()
if andRedraw {
gRelayoutMaps(for: zone)
}
}
}
func deferEditingStateChange() {
gIsEditingStateChanging = true
FOREGROUND(after: 0.1) {
gIsEditingStateChanging = false
}
}
func capture(force: Bool = false) {
if let current = currentEdit, let text = current.textWidget?.text, (!gTextCapturing || force) {
printDebug(.dEdit, " CAPTURE \(text)")
current.captureText(text)
}
}
func assign(_ iText: String?, to iZone: Zone?) {
if let zone = iZone {
ZTextPack(zone).captureText(iText)
}
}
func prepareUndoForTextChange(_ manager: UndoManager?,_ onUndo: @escaping Closure) {
currentEdit?.prepareUndoForTextChange(manager, onUndo)
}
// MARK: - selecting
// MARK: -
func selectAllText() {
let range = NSRange(location: 0, length: currentTextWidget?.text?.length ?? 0)
deferEditingStateChange()
selectedRange = range
}
func selectText(_ iText: String?) {
if let text = currentTextWidget?.text?.searchable,
let ranges = text.rangesMatching(iText),
ranges.count > 0 {
let range = ranges[0]
selectedRange = range
}
}
// MARK: - events
// MARK: -
@IBAction func genericMenuHandler(_ iItem: ZMenuItem?) { gAppDelegate?.genericMenuHandler(iItem) }
func moveOut(_ iMoveOut: Bool) {
let revealed = currentlyEditedZone?.isExpanded ?? false
gTemporarilySetTextEditorHandlesArrows() // done first, this timer is often not be needed, KLUDGE to fix a bug where arrow keys are ignored
let editAtOffset: FloatClosure = { [self] iOffset in
if let grabbed = gSelecting.firstSortedGrab {
gSelecting.ungrabAll()
edit(grabbed, setOffset: iOffset, immediately: revealed)
}
gTextEditorHandlesArrows = false // done last
}
if iMoveOut {
quickStopCurrentEdit()
gMapEditor.moveOut { reveal in
editAtOffset(100000000.0)
}
} else if currentlyEditedZone?.children.count ?? 0 > 0 {
quickStopCurrentEdit()
gMapEditor.moveInto { [self] reveal in
if !reveal {
editAtOffset(.zero)
} else {
gRelayoutMaps(for: currentlyEditedZone) {
editAtOffset(.zero)
}
}
}
}
}
func editingOffset(_ atStart: Bool) -> CGFloat {
return currentTextWidget?.offset(for: selectedRange, atStart) ?? .zero
}
func moveUp(_ up: Bool, stopEdit: Bool) {
currentOffset = currentOffset ?? editingOffset(up)
let e = currentEdit // for the case where stopEdit is true
if stopEdit {
applyPreservingOffset {
capture()
currentlyEditedZone?.grab()
}
}
if var original = e?.packedZone {
gMapEditor.moveUp(up, [original], targeting: currentOffset) { kinds in
gControllers.signalFor(nil, multiple: kinds) { [self] in
if let widget = original.widget, widget.isHere { // offset has changed
currentOffset = widget.textWidget?.offset(for: selectedRange, up)
}
if let first = gSelecting.firstSortedGrab, stopEdit {
original = first
if original != currentlyEditedZone { // if move up (above) does nothing, ignore
edit(original)
} else {
currentEdit = e // restore after capture sets it to nil
gSelecting.ungrabAll()
assignAsFirstResponder(e?.textWidget)
}
} // else widgets are wrong
FOREGROUND(after: 0.01) { [self] in
setCursor(at: currentOffset)
gMapView?.setNeedsDisplay()
}
}
}
}
}
func setCursor(at iOffset: CGFloat?) {
gTextEditorHandlesArrows = false
if var offset = iOffset,
let zone = currentlyEditedZone,
let to = currentTextWidget {
var point = CGPoint.zero
point = to.convert(point, from: nil)
offset += point.x - 3.0 // subtract half the average character width -> closer to user expectation
let name = zone.unwrappedName
let location = name.location(of: offset, using: currentFont)
printDebug(.dEdit, " AT \(location) \(name)")
selectedRange = NSMakeRange(location, 0)
}
}
}
|
//
// Currency.swift
// VendingMachine
//
// Created by Frank McAuley on 5/28/15.
// Copyright (c) 2015 fmcauley. All rights reserved.
//
import Foundation
enum Currency {
case Coin(String,String)
}
|
//
// ContentView.swift
// API Calling
//
// Created by Henry Majewski on 7/29/21.
//
import SwiftUI
struct ContentView: View {
@State private var showingAlert = false
@State private var songs = [Song]()
var body: some View {
NavigationView {
List(songs) { song in
NavigationLink(
destination: VStack{
Text(song.rank)
.font(.title)
Text(song.name)
Text(song.artist)
Text("\(song.weeksOnChart) weeks on chart")
},
label: {
Text("\(song.rank) \(song.name)")
}
)
}
.navigationTitle("Top 10 BillBoard Songs")
}
.onAppear(perform: {
getSongs()
})
.alert(isPresented: $showingAlert, content: {
Alert(title: Text("Loading Error"),
message: Text("There was a problem loading the data"),
dismissButton: .default(Text("OK")))
})
}
func getSongs() {
let apiKey = "b617eab960msh0dfbbe9ea27b312p1268e7jsn3c209154ec9d"
let query = "https://billboard-api2.p.rapidapi.com/hot-100?date=2021-07-31&range=1-10&rapidapi-key=\(apiKey)"
if let url = URL(string: query) {
if let data = try? Data(contentsOf: url) {
let json = try! JSON(data: data)
let content = json["content"].dictionaryValue
for i in 1...10 {
if let item = content[String(i)]?.dictionaryValue {
let rank = item["rank"]!.stringValue
let name = item["title"]!.stringValue
let artist = item["artist"]!.stringValue
let weeksOnChart = item["weeks on chart"]!.stringValue
let song = Song(rank: rank, name: name, artist: artist, weeksOnChart: weeksOnChart)
songs.append(song)
}
}
return
}
}
showingAlert = true
}
}
struct Song: Identifiable {
let id = UUID()
var rank: String
var name: String
var artist: String
var weeksOnChart: String
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
import UIKit
final class ContactListPresenter: ContactListPresenterProtocol {
var interactor: ContactListInteractorProtocol
var router: ContactListRouterProtocol
weak var view: ContactListViewProtocol?
init(router: ContactListRouterProtocol, interactor: ContactListInteractorProtocol) {
self.router = router
self.interactor = interactor
}
func onViewDidLoad() {
self.interactor.getAllContacts()
self.showLoader()
}
func showDetail(_ navigationController: UINavigationController, with contact: Contact) {
self.router.showDetailView(on: navigationController, with: contact)
}
func showAddContact(on controller: UINavigationController) {
self.router.showAddContact(on: controller)
}
}
extension ContactListPresenter: ContactListInteractorOutputProtocol {
func didRecievedContacts(_ contacts: [Contact]) {
self.view?.didRecieved(contacts: contacts)
}
func didFailed(_ error: String) {
self.view?.didFailedWith(eror: error)
}
func showLoader() {
self.view?.showLoader()
}
}
|
//
// NewspeedTVC.swift
// Ink_iOS_Deviloper
//
// Created by 신동규 on 2018. 2. 26..
// Copyright © 2018년 신동규. All rights reserved.
//
import UIKit
class ExampleCell : UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var detailsLabel: UILabel!
}
class NewspeedTVC: UITableViewController {
var list = ["dmdkdkdkdkdkdsfasdfsadfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfㅁㄴㅇㄹㅁㄴㅇㄹㅁㄴㅇㄹㅁㄴㅇㄹㅁㄴㅇㄹㅁㄴㅇㄹㅁㄴㅇㄹㄴㅁㅇㄹㄴㅁㄹㅁㄴㅇㄹㅁㄴㅇㄹㅁㄴㅇㄹㄴㅁㄹㅇㅁㄴㅇㄹㅁㄴㅇㄹㅁㄴㅇㅁㄴㄹㅁㄴㅇㄹㅁㄴㅇㄹㅁㄴㅇㄹㅁㄴㅇㄹ","asdfasdf","asdfasdfasdfasdfsfs"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 44
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return list.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ExampleCell", for: indexPath) as! ExampleCell
cell.layer.cornerRadius = 8
cell.detailsLabel.text = list[indexPath.row]
return cell
}
}
|
//
// TabThreeViewController.swift
// Day 21 - Tab Bar and Modal
//
// Created by 杜赛 on 2020/3/20.
// Copyright © 2020 Du Sai. All rights reserved.
//
import UIKit
class TabThreeViewController: UIViewController, StateControllerProtocol
{
func setState(state: StateController) {
self.stateController = state
}
var stateController: StateController?
@IBAction func showPopover(_ sender: UIButton) {
performSegue(withIdentifier: "Popover", sender: sender)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
|
//
// CarListViewModelMapper.swift
// CarFun
//
// Created by Andrei Konstantinov on 18/06/2019.
// Copyright © 2019 Test. All rights reserved.
//
import UIKit
final class CarListViewModelMapper {
func map(cars: [Car]) -> [CarListItemViewModel] {
return cars.map({ map(car: $0) })
}
func map(car: Car) -> CarListItemViewModel {
let cleanliness = NSLocalizedString("innerCleanliness.\(car.innerCleanliness)", comment: "")
return CarListItemViewModel(
model: car.modelName,
name: car.name,
licensePlate: car.licensePlate,
fuelLevel: "Fuel level: \(car.fuelLevel)",
innerCleanliness: cleanliness,
imageURL: car.imageUrl
)
}
}
|
//
// CATiledImageLayerViewController.swift
// CALayerDemo
//
// Created by wizard on 12/26/15.
// Copyright © 2015 Alchemist. All rights reserved.
//
import UIKit
class CATiledImageLayerViewControlle : UIViewController {
}
|
//
// UIImageView.swift
// MovieMaster
//
// Created by Andre & Bianca on 11/12/19.
// Copyright © 2019 Andre. All rights reserved.
//
import UIKit
extension UIImageView {
func allCornersRounded(width: Int = 5, height: Int = 5) {
let maskPath = UIBezierPath(
roundedRect: bounds,
byRoundingCorners: UIRectCorner.allCorners,
cornerRadii: CGSize(width: width, height: height)
)
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = maskPath.cgPath
layer.mask = maskLayer
layer.masksToBounds = true
self.clipsToBounds = true
}
func topCornersRounded(width: Int = 5, height: Int = 5){
let maskPath = UIBezierPath(
roundedRect: bounds,
byRoundingCorners: [.topLeft , .topRight],
cornerRadii: CGSize(width: width, height: height)
)
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = maskPath.cgPath
layer.mask = maskLayer
}
}
|
//: [Previous](@previous)
import Foundation
// ARC
class AClassWithLazyClosure {
lazy var aClosure: (Int, String) -> String = {
[unowned self] (index: Int, stringToProcess: String) -> String in
// closure body goes here
return ""
}
}
//: [Next](@next)
|
//
// Variable.swift
// CYaml
//
// Created by Rob Saunders on 7/16/19.
//
import Foundation
struct Variable: ProjectObject, Codable {
let name: String
var optional: Bool
var type: Type
var value: String?
var description: String?
init(name: String) {
self.name = name
optional = false
type = .primitive(.String)
}
func find(in variables: [Variable]) -> Variable? {
return variables.first(where: {
self.name == $0.name
})
}
}
indirect enum Type: Equatable, Codable {
case primitive(PrimitiveType)
case array(Type)
case complex(String)
enum CodingKeys: String, CodingKey {
case Array
case Complex
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .primitive(let type):
try type.encode(to: encoder)
// try container.encode(type, forKey: .primitive)
case .array(let type):
// let str = try type.json()
// try ("[" + str + "]").encode(to: encoder)
try container.encode(type, forKey: .Array)
case .complex(let type):
// try type.encode(to: encoder)
try container.encode(type, forKey: .Complex)
}
}
init(from decoder: Decoder) throws {
let container = try? decoder.singleValueContainer()
if let str = try? container?.decode(String.self) {
self = Type.decode(str:str)
}
else {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let type = try? container.decode(String.self, forKey: .Complex) {
self = .array(Type.decode(str: type))
}
else
if let type = try? container.decode(String.self, forKey: .Array) {
self = .array(Type.decode(str: type))
}
else
if let type = try? container.decode(Type.self, forKey: .Array) {
self = .array(type)
}
else {
self = .complex("unknown")
}
}
}
private static func decode(str: String) -> Type {
// var str = str
switch str {
case "Int": return .primitive(.Int)
case "String": return .primitive(.String)
case "Float": return .primitive(.Float)
case "Bool": return .primitive(.Bool)
default:
return .complex(str)
// if String(str.suffix(1)) == "[" {
// str = String(str.suffix(str.count - 1))
// str = String(str.prefix(str.count - 1))
// return .Array(decode(str: str))
// }
// else {
// return .Complex(str)
// }
}
}
}
enum PrimitiveType: String, Codable {
case String
case Int
case Float
case Bool
}
|
//
// PrayerRequestsViewController.swift
// YouthGroup
//
// Created by Adam Zarn on 2/8/18.
// Copyright © 2018 Adam Zarn. All rights reserved.
//
import Foundation
import UIKit
import FirebaseAuth
class PrayerRequestsViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var aivView: UIView!
@IBOutlet weak var churchLabel: UIBarButtonItem!
var prayerRequests: [PrayerRequest] = []
var groupUID: String?
var email: String?
var allLoaded = false
var firstTime = true
var lastPrayerRequestTimestamp: Int64?
var isLoadingMore = false
var scrollingLocked = true
override func viewDidLayoutSubviews() {
scrollingLocked = false
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.tabBar.isHidden = false
let currentGroupUID = UserDefaults.standard.string(forKey: "currentGroup")
if currentGroupUID != groupUID || Auth.auth().currentUser?.email != email {
isLoadingMore = true
firstTime = true
refresh()
}
}
@objc func refresh() {
if let groupUID = UserDefaults.standard.string(forKey: "currentGroup") {
checkIfUserBelongsToGroup(groupUID: groupUID)
} else {
self.reloadTableView(prayerRequests: [])
}
}
func checkIfUserBelongsToGroup(groupUID: String) {
if let email = Auth.auth().currentUser?.email {
self.email = email
FirebaseClient.shared.getGroupUIDs(email: email, completion: { (groupUIDs, error) in
if let error = error {
self.aivView.isHidden = true
self.reloadTableView(prayerRequests: [])
Alert.showBasic(title: Helper.getString(key: "error"), message: error, vc: self)
} else {
if let groupUIDs = groupUIDs, groupUIDs.contains(groupUID) {
self.startObservingNewPrayerRequests(groupUID: groupUID)
Helper.setChurchName(groupUID: groupUID, button: self.churchLabel)
self.groupUID = groupUID
self.getPrayerRequests(groupUID: groupUID, start: nil)
} else {
UserDefaults.standard.set(nil, forKey: "currentGroup")
self.reloadTableView(prayerRequests: [])
}
}
})
}
}
func startObservingNewPrayerRequests(groupUID: String) {
FirebaseClient.shared.removeObservers(node: "PrayerRequests", uid: groupUID)
FirebaseClient.shared.observeNewPrayerRequests(groupUID: groupUID, completion: { (prayerRequest, error) in
if let error = error {
self.reloadTableView(prayerRequests: [])
Alert.showBasic(title: Helper.getString(key: "error"), message: error, vc: self)
} else {
if let prayerRequest = prayerRequest, !self.firstTime {
self.prayerRequests.insert(prayerRequest, at: 0)
self.tableView.reloadData()
} else {
self.firstTime = false
}
}
})
}
func getPrayerRequests(groupUID: String, start: Int64?) {
self.prayerRequests = []
FirebaseClient.shared.queryPrayerRequests(groupUID: groupUID, start: start, completion: { (prayerRequests, error) in
self.aivView.isHidden = true
self.allLoaded = false
self.lastPrayerRequestTimestamp = nil
if let error = error {
self.aivView.isHidden = true
self.reloadTableView(prayerRequests: [])
Alert.showBasic(title: Helper.getString(key: "error"), message: error, vc: self)
} else {
if let prayerRequests = prayerRequests {
let firstPrayerRequests = prayerRequests.sorted(by: { $0.timestamp < $1.timestamp })
self.lastPrayerRequestTimestamp = firstPrayerRequests.last?.timestamp
self.prayerRequests = firstPrayerRequests
if prayerRequests.count == QueryLimits.prayerRequests {
self.prayerRequests.remove(at: self.prayerRequests.count - 1)
} else {
self.allLoaded = true
}
self.reloadTableView(prayerRequests: self.prayerRequests)
}
}
})
}
func getMorePrayerRequests(groupUID: String, start: Int64?) {
if !allLoaded {
FirebaseClient.shared.queryPrayerRequests(groupUID: groupUID, start: start, completion: { (prayerRequests, error) in
self.aivView.isHidden = true
if let error = error {
self.aivView.isHidden = true
self.reloadTableView(prayerRequests: [])
Alert.showBasic(title: Helper.getString(key: "error"), message: error, vc: self)
} else {
if let prayerRequests = prayerRequests {
if prayerRequests.count == 1 {
self.allLoaded = true
self.prayerRequests = self.prayerRequests + prayerRequests
self.reloadTableView(prayerRequests: self.prayerRequests)
} else {
let newPrayerRequests = prayerRequests.sorted(by: { $0.timestamp < $1.timestamp })
self.lastPrayerRequestTimestamp = newPrayerRequests.last?.timestamp
self.prayerRequests = self.prayerRequests + newPrayerRequests
self.prayerRequests.remove(at: self.prayerRequests.count - 1)
self.reloadTableView(prayerRequests: self.prayerRequests)
}
}
}
})
} else {
self.aivView.isHidden = true
}
}
func reloadTableView(prayerRequests: [PrayerRequest]) {
self.prayerRequests = prayerRequests.sorted(by: { $0.timestamp < $1.timestamp })
self.tableView.reloadData()
}
@IBAction func addButtonPressed(_ sender: Any) {
let addPrayerRequestVC = self.storyboard?.instantiateViewController(withIdentifier: "AddPrayerRequestViewController") as! AddPrayerRequestViewController
addPrayerRequestVC.delegate = self
self.navigationController?.pushViewController(addPrayerRequestVC, animated: true)
}
}
extension PrayerRequestsViewController: UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if let email = Auth.auth().currentUser?.email {
if email == prayerRequests[indexPath.row].submittedByEmail {
return true
} else {
return false
}
}
return false
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
if let groupUID = self.groupUID {
let prayerRequestUID = prayerRequests[indexPath.row].uid!
FirebaseClient.shared.deletePrayerRequest(groupUID: groupUID, prayerRequestUID: prayerRequestUID, completion: { error in
if let error = error {
Alert.showBasic(title: Helper.getString(key: "error"), message: error, vc: self)
} else {
self.prayerRequests.remove(at: indexPath.row)
self.tableView.reloadData()
}
})
}
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60.0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return prayerRequests.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "prayerRequestCell") as! PrayerRequestCell
let request = prayerRequests[indexPath.row]
cell.setUp(request: request)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
let prayerRequestVC = self.storyboard?.instantiateViewController(withIdentifier: "PrayerRequestViewController") as! PrayerRequestViewController
prayerRequestVC.prayerRequest = prayerRequests[indexPath.row]
prayerRequestVC.indexPath = indexPath
prayerRequestVC.groupUID = groupUID
prayerRequestVC.delegate = self
print(prayerRequests[indexPath.row].uid!)
self.navigationController?.pushViewController(prayerRequestVC, animated: true)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollingLocked {
return
}
let contentOffset = scrollView.contentOffset.y
let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height
if !isLoadingMore && (maximumOffset - contentOffset < Constants.threshold) {
self.isLoadingMore = true
self.aivView.isHidden = false
if let groupUID = groupUID {
self.getMorePrayerRequests(groupUID: groupUID, start: self.lastPrayerRequestTimestamp)
}
}
}
}
extension PrayerRequestsViewController: PrayerRequestViewControllerDelegate {
func toggleAnswered(indexPath: IndexPath) {
prayerRequests[indexPath.row].answered = !prayerRequests[indexPath.row].answered
tableView.reloadRows(at: [indexPath], with: .automatic)
}
func update(prayingMembers: [Member], indexPath: IndexPath) {
prayerRequests[indexPath.row].prayingMembers = prayingMembers
tableView.reloadRows(at: [indexPath], with: .automatic)
}
}
extension PrayerRequestsViewController: AddPrayerRequestViewControllerDelegate {
func push(prayerRequest: PrayerRequest, groupUID: String) {
if prayerRequests.count == 0 {
firstTime = true
prayerRequests.insert(prayerRequest, at: 0)
tableView.reloadData()
startObservingNewPrayerRequests(groupUID: groupUID)
}
}
func displayError(error: String) {
Alert.showBasic(title: Helper.getString(key: "error"), message: error, vc: self)
}
}
|
#!/usr/bin/env swift
import Foundation
let arguments = Array(CommandLine.arguments[1 ..< CommandLine.arguments.count])
let fileManager = FileManager.default
let stderr = FileHandle.standardError
for arg in arguments
{
let url = NSURL(fileURLWithPath: arg)
var err: NSError?
if !url.checkResourceIsReachableAndReturnError(&err)
{
stderr.write("🚫 file `\(arg)` doesn't exist".data(using: String.Encoding.utf8)!)
continue;
}
var val = "\(url.absoluteURL)"
if url.pathExtension == "webloc"
{
let dict : NSDictionary = NSDictionary(contentsOf: url as URL)!
val = dict["URL"] as! String
}
print(val)
}
|
//
// Setter.swift
// Patter
//
// Created by Maksim Ivanov on 09/07/2019.
// Copyright © 2019 Maksim Ivanov. All rights reserved.
//
import Foundation
protocol SetCollection {
func setup()
}
|
//
// NearbyUsers.swift
// Surface
//
// Created by Appinventiv Mac on 10/04/18.
// Copyright © 2018 Appinventiv. All rights reserved.
//
import UIKit
class NearbyUsers: UIViewController , GetMyLocation {
// MARK: IBOUTLETS
// ===============
@IBOutlet weak var loaderView: UIView!
@IBOutlet weak var navigationView: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var nearbyTabelView: UITableView!
// MARK: CLASS PROPERTIES
// ======================
var data = [String:Any]()
var nearby:NearBy!
var cLocation = CurrentLocation()
var lat,lng:Float?
// MARK: LIFECYCLE METHOD
// =======================
override func viewDidLoad() {
super.viewDidLoad()
self.cLocation.delegate = self
self.registerCells()
self.setUpViews()
self.getNearbyUsers()
self.nearbyTabelView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: METHOD TO REGISTER CELL
// =============================
func registerCells(){
nearbyTabelView.register(UINib(nibName: "TagPeopleTVC", bundle: nil), forCellReuseIdentifier: "TagPeopleTVC")
}
// MARK: PROTOCOL METHOD TO GET LAT. AND LNG. OF DEVICE
// ====================================================
func coordinates(_ lat:Float, _ lng:Float){
self.lat = lat
self.lng = lng
}
func setUpViews(){
self.loaderView.alpha = 0.0
self.navigationView.layer.shadowColor = UIColor.gray.cgColor
self.navigationView.layer.shadowOffset = CGSize(width: 2.5, height: 2.5)
self.navigationView.clipsToBounds = false
self.navigationView.layer.masksToBounds = false
self.navigationView.layer.shadowOpacity = 0.7
nearbyTabelView.delegate = self
nearbyTabelView.dataSource = self
let refreshControl = UIRefreshControl()
refreshControl.attributedTitle = NSAttributedString(string: "Pull to search again", attributes: [NSAttributedStringKey.foregroundColor: #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1) , NSAttributedStringKey.font: AppFonts.regular.withSize(11.0)])
refreshControl.addTarget(self, action: #selector(self.refresh(refreshControl:)), for: UIControlEvents.valueChanged)
self.nearbyTabelView.addSubview(refreshControl)
self.viewWillLayoutSubviews()
}
// MARK: METHOD TO GET THE NEAR BY USER'S LIST
// ===========================================
func getNearbyUsers(){
self.data["longitude"] = self.lat ?? 77.367783
self.data["lattitude"] = self.lng ?? 28.628151
self.data["page"] = 1
WebServices.user_byLocation(params: data, success: { (nearby) in
self.nearby = nearby
}, failure: {(mess,code) in
})
}
// MARK: ONJECT C METHOD
// =====================
@objc private func refresh(refreshControl: UIRefreshControl){
self.view.endEditing(true)
self.loaderView.alpha = 1.0
UIView.animate(withDuration: 2.0, animations: {
self.loaderView.alpha = 0.0
})
self.nearbyTabelView.reloadData()
refreshControl.endRefreshing()
}
@IBAction func popVCButton(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
// MARK: TABLEVIEW DELEGATE AND DATASOURCES METHODS
// ================================================
extension NearbyUsers:UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if nearby == nil {
return 0
}else{
return (nearby.data?.count)!
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = nearbyTabelView.dequeueReusableCell(withIdentifier: "TagPeopleTVC", for: indexPath) as? TagPeopleTVC else { return UITableViewCell()}
cell.userNameLabel.text = nearby.data?[indexPath.row].user_name
cell.nameLabel.text = nearby.data?[indexPath.row].user_name
cell.profileImageView.image = UIImage(named: "1")
cell.selectImageView.image = UIImage(named: "icFriendListAddFriend")
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? TagPeopleTVC
else { return }
cell.backgroundColor = .white
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 90
}
}
|
//
// DictionaryExtension.swift
// SwiftLearning
//
// Created by 邓光洋 on 2019/3/6.
// Copyright © 2019 邓光洋. All rights reserved.
//
import Foundation
extension Dictionary {
//Returns the value of a random Key-Value pair from the Dictionary
public func random() -> Value? {
return Array(values).random()
}
//Union of self and the input dictionaries.
public func union(_ dictionaries: Dictionary...) -> Dictionary {
var result = self
dictionaries.forEach { (dictionary) -> Void in
dictionary.forEach { (arg) -> Void in
let (key, value) = arg
result[key] = value
}
}
return result
}
//Checks if a key exists in the dictionary.
public func has(_ key: Key) -> Bool {
return index(forKey: key) != nil
}
//Creates an Array with values generated by running
// each [key: value] of self through the mapFunction.
//map函数 public func map<T>(_ transform: ((key: Key, value: Value)) throws -> T) rethrows -> [T]
public func toArray<T>(_ map: (Key, Value) -> T) -> [T] {
return self.map(map)
}
//Creates a Dictionary with the same keys as self and values generated by running
// each [key: value] of self through the mapFunction.
public func mapValues<T>(_ map: (Key, Value) -> T) -> [Key: T] {
var mapped: [Key: T] = [:]
forEach {
mapped[$0] = map($0, $1)
}
return mapped
}
// Creates a Dictionary with the same keys as self and values generated by running
// each [key: value] of self through the mapFunction discarding nil return values.
public func mapFilterValues<T>(_ map: (Key, Value) -> T?) -> [Key: T] {
var mapped: [Key: T] = [:]
forEach {
if let value = map($0, $1) {
mapped[$0] = value
}
}
return mapped
}
// Creates a Dictionary with keys and values generated by running
// each [key: value] of self through the mapFunction discarding nil return values.
public func mapFilter<K, V>(_ map: (Key, Value) -> (K, V)?) -> [K: V] {
var mapped: [K: V] = [:]
forEach {
if let value = map($0, $1) {
mapped[value.0] = value.1
}
}
return mapped
}
// Creates a Dictionary with keys and values generated by running
// each [key: value] of self through the mapFunction.
public func map<K, V>(_ map: (Key, Value) -> (K, V)) -> [K: V] {
var mapped: [K: V] = [:]
forEach {
let (_key, _value) = map($0, $1)
mapped[_key] = _value
}
return mapped
}
//Constructs a dictionary containing every [key: value] pair from self
// for which testFunction evaluates to true.
public func filter(_ test: (Key, Value) -> Bool) -> Dictionary {
var result = Dictionary()
for (key, value) in self {
if test(key, value) {
result[key] = value
}
}
return result
}
//Checks if test evaluates true for all the elements in self.
public func testAll(_ test: (Key, Value) -> (Bool)) -> Bool {
return contains { !test($0, $1) }
}
//Unserialize JSON string into Dictionary
//jsonObject函数 open class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
public static func constructFromJSON(json: String) -> Dictionary? {
if let data = (try? JSONSerialization.jsonObject(
with: json.data(using: String.Encoding.utf8, allowLossyConversion: true)!,
options: JSONSerialization.ReadingOptions.mutableContainers)) as? Dictionary {
return data
} else {
return nil
}
}
// Serialize Dictionary into JSON string
public func formatJson() -> String? {
if let jsonData = try? JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions()) {
let jsonStr = String(data: jsonData, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
return String(jsonStr ?? "")
}
return nil
}
}
extension Dictionary where Value: Equatable {
// Difference of self and the input dictionaries.
// Two dictionaries are considered equal if they contain the same [key: value] pairs.
public func difference(_ dictionaries: [Key: Value]...) -> [Key: Value] {
var result = self
for dictionary in dictionaries {
for (key, value) in dictionary {
if result.has(key) && result[key] == value {
result.removeValue(forKey: key)
}
}
}
return result
}
}
//Combines the first dictionary with the second and returns single dictionary
//运算符重载
public func += <KeyType, ValueType>(left: inout [KeyType: ValueType], right: [KeyType: ValueType]) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
}
|
//
// TrickShot.swift
// AdventOfCode
//
// Created by Shawn Veader on 12/17/21.
//
import Foundation
class TrickShot {
let targetAreaX: ClosedRange<Int>
let targetAreaY: ClosedRange<Int>
var workingShots = [[Int]]()
var highestHeight: Int = 0
enum ShotMetrics {
case fellShort
case overShot
case hit(maxHeight: Int)
}
init(areaX: ClosedRange<Int>, areaY: ClosedRange<Int>) {
targetAreaX = areaX
targetAreaY = areaY
}
func findShots() {
for x in (0...targetAreaX.upperBound) {
// print("Considering x: \(x)")
for y in (targetAreaY.lowerBound..<1000) {
let result = modelShot(horizontal: x, vertical: y)
if case .hit(let maxHeight) = result {
// print("\tVertical \(y) hits with max height of \(maxHeight)")
highestHeight = max(highestHeight, maxHeight)
workingShots.append([x,y])
} else if case .overShot = result {
// print("\tOvershot starting with \(y). Stopping...")
break
}
}
}
print("-------------")
print(workingShots)
print("\n Count: \(workingShots.count)")
print("\n Highest: \(highestHeight)")
}
func modelShot(horizontal: Int, vertical: Int, debugPrint: Bool = false) -> ShotMetrics {
var result: ShotMetrics?
var point = Coordinate(x: 0, y: 0) // start at origin
var horizontalComp = horizontal
var verticalComp = vertical
var maxHeight = 0
if debugPrint { print("Modeling \(horizontal), \(vertical)...") }
while inBounds(point) && result == nil {
// move point
point = point.moving(xOffset: horizontalComp, yOffset: verticalComp)
maxHeight = max(maxHeight, point.y)
if debugPrint { print("\t\(point) with maxHeight \(maxHeight)") }
// adjust coeffiecient/components
horizontalComp = max(0, horizontalComp - 1)
verticalComp -= 1
if inTargetArea(point) {
if debugPrint { print("HIT!") }
result = .hit(maxHeight: maxHeight)
} else if point.x > targetAreaX.upperBound {
result = .overShot
} else if point.y < targetAreaY.lowerBound {
result = .fellShort
}
}
guard let result = result else { return .fellShort } // not sure what would cause this...
return result
}
/// Determine if the given coordinate is "in bounds".
///
/// Meaning is the X less than the `targetAreaX.upperBound` and Y greater then `targetAreaY.lowerBound`.
func inBounds(_ coordinate: Coordinate) -> Bool {
coordinate.x <= targetAreaX.upperBound &&
coordinate.y >= targetAreaY.lowerBound
}
func inTargetArea(_ coordinate: Coordinate) -> Bool {
targetAreaX.contains(coordinate.x) && targetAreaY.contains(coordinate.y)
}
}
|
import UIKit
var pirates = [("José", 1), ("Antonio", 8), ("Pedro", 0), ("Juan", 1), ("Enrique", 2), ("Alfonso", 3)]
var premio: [(String, Int)] = []
|
//
// UploadTweetViewModel.swift
// Twitter
//
// Created by Ngo Dang tan on 9/4/20.
// Copyright © 2020 Ngo Dang tan. All rights reserved.
//
import UIKit
enum UploadTweetConfiguration{
case tweet
case reply(Tweet)
}
struct UploadTweetViewModel {
let actionButtonTitle: String
let placeholderText: String
var shoudShowReplyLabel: Bool
var replyText:String?
init(config: UploadTweetConfiguration){
switch config{
case .tweet:
actionButtonTitle = "Tweet"
placeholderText = "What's happening?"
shoudShowReplyLabel = false
case .reply(let tweet):
actionButtonTitle = "Reply"
placeholderText = "Tweet your reply"
shoudShowReplyLabel = true
replyText = "Replying to @\(tweet.user.username)"
}
}
}
|
//
// ParseLoginHelper.swift
// Makestagram
//
// Created by Benjamin Encz on 4/15/15.
// Copyright (c) 2015 Make School. All rights reserved.
//
import Foundation
import FBSDKCoreKit
import Parse
import ParseUI
import Alamofire
typealias ParseLoginHelperCallback = (PFUser?, NSError?) -> Void
/**
This class implements the 'PFLogInViewControllerDelegate' protocol. After a successfull login
it will call the callback function and provide a 'PFUser' object.
*/
class ParseLoginHelper : NSObject, NSObjectProtocol {
static let errorDomain = "com.makeschool.parseloginhelpererrordomain"
static let usernameNotFoundErrorCode = 1
static let usernameNotFoundLocalizedDescription = "Could not retrieve Facebook username"
let callback: ParseLoginHelperCallback
init(callback: ParseLoginHelperCallback) {
self.callback = callback
}
}
extension ParseLoginHelper : PFLogInViewControllerDelegate {
func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) {
// Determine if this is a Facebook login
let isFacebookLogin = FBSDKAccessToken.currentAccessToken() != nil
if !isFacebookLogin {
// Plain parse login, we can return user immediately
self.callback(user, nil)
} else {
// if this is a Facebook login, fetch the username from Facebook
FBSDKGraphRequest(graphPath: "me", parameters: nil).startWithCompletionHandler {
(connection: FBSDKGraphRequestConnection!, result: AnyObject?, error: NSError?) -> Void in
if let error = error {
// Facebook Error? -> hand error to callback
self.callback(nil, error)
}
if let fbUsername = result?["name"] as? String {
// assign Facebook name to PFUser
user.username = fbUsername
//TODO: assign Facebook image to it
if let userData=result as? [String: AnyObject]{
let facebookUserId = userData["id"] as! String
var link = "http://graph.facebook.com/\(facebookUserId)/picture"
let url = NSURL(string: link)
var request = NSURLRequest(URL: url!)
let params = ["height": "200", "width": "200", "type": "square"]
Alamofire.request(.GET, link, parameters: params).response() {
(request, response, data, error) in
if ( error != nil ) {
self.callback(nil,error)
}else{
var image=UIImage(data:data as! NSData)
if var image=image{
if image.size.width>280{
image=Images.resizeImage(image, width: 280, height: 280)!
}
var imageData=UIImageJPEGRepresentation(image, 0.8)
var filePicture = PFFile(data: imageData)
filePicture.saveInBackgroundWithBlock{
(success: Bool, error: NSError?) -> Void in
if success {
// println("saveImage")
}
if error != nil {
println(" ParseLogin filePicture error \(error)")
}
}
user[PF_USER_PICTURE]=filePicture
// store PFUser after image is saved
user.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) -> Void in
if (success) {
// updated username could be stored -> call success
self.callback(user, error)
} else {
// updating username failed -> hand error to callback
self.callback(nil, error)
}
})
}
}
}
}
} else {
// cannot retrieve username? -> create error and hand it to callback
let userInfo = [NSLocalizedDescriptionKey : ParseLoginHelper.usernameNotFoundLocalizedDescription]
let noUsernameError = NSError(
domain: ParseLoginHelper.errorDomain,
code: ParseLoginHelper.usernameNotFoundErrorCode,
userInfo: userInfo
)
self.callback(nil, error)
}
}
}
}
}
extension ParseLoginHelper : PFSignUpViewControllerDelegate {
func signUpViewController(signUpController: PFSignUpViewController, didSignUpUser user: PFUser) {
self.callback(user, nil)
}
} |
//
// EditViewController.swift
// BMI Calculator
//
// Created by 陳耀奇 on 2021/6/15.
//
import UIKit
class EditViewController: UIViewController {
@IBOutlet weak var name: UILabel!
@IBOutlet weak var widthTextField: UITextField!
@IBOutlet weak var heightTextField: UITextField!
var nameForLabel = ""
var bmi = 0.0
override func viewDidLoad() {
super.viewDidLoad()
name.text = nameForLabel
}
@IBAction func confirm(_ sender: Any) {
let h :Double = Double(heightTextField.text!)!
let w :Double = Double(widthTextField.text!)!
bmi = w/(h*h)
}
}
|
//
// Assertions.swift
// BreakingBadTests
//
// Created by Joshua Simmons on 15/02/2021.
//
import Foundation
import XCTest
import Difference
public func XCTAssertEqualWithDiff<T: Equatable>(
_ expected: @autoclosure () throws -> T,
_ received: @autoclosure () throws -> T,
file: StaticString = #filePath,
line: UInt = #line
) {
do {
let expected = try expected()
let received = try received()
XCTAssertTrue(
expected == received,
"Found difference for \n" + diff(expected, received).joined(separator: ", "),
file: file,
line: line
)
}
catch {
XCTFail("Caught error while testing: \(error)", file: file, line: line)
}
}
|
import UIKit
class ChoreListTableViewController: UITableViewController {
let listToUsers = "ListToUsers"
var items: [ChoreItem] = []
var user: User!
var userCountBarButtonItem: UIBarButtonItem!
let ref = FIRDatabase.database().reference(withPath: "chore-items")
let usersRef = FIRDatabase.database().reference(withPath: "online")
let dataBaseRef = FIRDatabase.database().reference()
override func viewDidLoad() {
super.viewDidLoad()
tableView.allowsMultipleSelectionDuringEditing = false
userCountBarButtonItem = UIBarButtonItem(title: "1", style: .plain, target: self, action: #selector(userCountButtonDidTouch))
userCountBarButtonItem.tintColor = UIColor.white
navigationItem.leftBarButtonItem = userCountBarButtonItem
FIRAuth.auth()!.addStateDidChangeListener { auth, user in
guard let user = user else { return }
self.user = User(authData: user)
let currentUserRef = self.usersRef.child(self.user.uid)
currentUserRef.setValue(self.user.email)
currentUserRef.onDisconnectRemoveValue()
}
// ATTACH LISTENER TO OBSERVE FOR VALUE CHANGES OF NEW CHOREITEMS THAT ARE BEING CREATED
// PLUS ORDER BY COMPLETED SO THAT COMPLETED TASKS FALL BELOW
ref.queryOrdered(byChild: "completed").observe(.value, with: { snapshot in
var newItems: [ChoreItem] = []
for item in snapshot.children {
let choreItem = ChoreItem(snapshot: item as! FIRDataSnapshot)
newItems.append(choreItem)
}
self.items = newItems
self.tableView.reloadData()
})
// OBSERVE FOR VALUE CHANGES TO SET ONLINE UER COUNT
usersRef.observe(.value, with: { snapshot in
if snapshot.exists() {
self.userCountBarButtonItem?.title = snapshot.childrenCount.description
} else {
self.userCountBarButtonItem?.title = "0"
}
})
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)
let choreItem = items[indexPath.row]
cell.textLabel?.text = choreItem.name
cell.detailTextLabel?.text = "Added By: " + choreItem.addedByUser
toggleCellCheckbox(cell, isCompleted: choreItem.completed, chore: choreItem)
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
// CREATING THE UPDATE BUTTON ON SWIPE
let updateAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "Update" , handler: { (action:UITableViewRowAction!, indexPath:IndexPath!) -> Void in
let choreItem = self.items[indexPath.row]
let alert = UIAlertController(title: "Chore Item", message: "Edit a Chore", preferredStyle: .alert)
// ALERT SAVE BUTTON CLICKED AND DB OBJECT UPDATED
let saveAction = UIAlertAction(title: "Save", style: .default) { _ in
guard let textField = alert.textFields?.first, let text = textField.text else { return }
choreItem.ref?.updateChildValues([
"name": text
])
}
// ALERT CANCEL BUTTON CLICKED
let cancelAction = UIAlertAction(title: "Cancel", style: .default)
let textField = alert.addTextField(){ (textField) in
textField.text = choreItem.name
}
alert.addAction(saveAction)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
})
// DELETE CELL ROW SLIDER BUTTON
let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "Delete" , handler: { (action:UITableViewRowAction!, indexPath:IndexPath!) -> Void in
let choreItem = self.items[indexPath.row]
choreItem.ref?.removeValue()
})
updateAction.backgroundColor = UIColor.lightGray
return [deleteAction,updateAction]
}
// UPDATING CHECKBOX
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) else { return }
let choreItem = items[indexPath.row]
let toggledCompletion = !choreItem.completed
toggleCellCheckbox(cell, isCompleted: toggledCompletion, chore: choreItem)
choreItem.ref?.updateChildValues([
"completed": toggledCompletion,
"completedByUser": self.user.email
])
}
func toggleCellCheckbox(_ cell: UITableViewCell, isCompleted: Bool, chore: ChoreItem) {
// STYLING FOR INCOMPLETE ITEMS
if !isCompleted {
cell.accessoryType = .none
cell.textLabel?.textColor = UIColor.black
cell.detailTextLabel?.textColor = UIColor.black
cell.detailTextLabel?.text = "Added By: " + chore.addedByUser
} else {
// STYLING FOR COMPLETE ITEMS
cell.accessoryType = .checkmark
cell.textLabel?.textColor = UIColor.gray
cell.detailTextLabel?.textColor = UIColor.gray
cell.detailTextLabel?.text = "Added By: " + chore.addedByUser + " / Completed By: " + chore.completedByUser
}
}
@IBAction func addButtonDidTouch(_ sender: AnyObject) {
let alert = UIAlertController(title: "Chore Item", message: "Add a Chore", preferredStyle: .alert)
// ALERT SAVE BUTTON PRESSED AND SAVED TO DB
let saveAction = UIAlertAction(title: "Save", style: .default) { _ in
guard let textField = alert.textFields?.first, let text = textField.text else { return }
let choreItem = ChoreItem(name: text, addedByUser: self.user.email, completedByUser: "", completed: false)
let choreItemRef = self.dataBaseRef.child("chore-items").childByAutoId()
choreItemRef.setValue(choreItem.toAnyObject())
}
// ALERT CANCEL BUTTON PRESSED
let cancelAction = UIAlertAction(title: "Cancel", style: .default)
alert.addTextField()
alert.addAction(saveAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
func userCountButtonDidTouch() {
performSegue(withIdentifier: listToUsers, sender: nil)
}
}
|
//
// ViewController.swift
// Threadz
//
// Created by Jake on 12/7/16.
// Copyright © 2016 Jake Mor. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var statusLabel: UILabel!
var titlesLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// status label
statusLabel = UILabel(frame: CGRect(x: 10, y: 0, width: view.frame.size.width/2 - 15, height: view.frame.size.height))
statusLabel.text = "Waiting..."
statusLabel.textAlignment = .left
statusLabel.lineBreakMode = .byWordWrapping
statusLabel.numberOfLines = 0
view.addSubview(statusLabel)
// titles label
titlesLabel = UILabel(frame: CGRect(x: view.frame.size.width/2 + 5, y: 0, width: view.frame.size.width/2 - 15, height: view.frame.size.height))
titlesLabel.text = "ORIGINAL ORDER"
titlesLabel.textAlignment = .left
titlesLabel.lineBreakMode = .byWordWrapping
titlesLabel.numberOfLines = 0
view.addSubview(titlesLabel)
// some hacker news story ids
let topStoryIDs = [ 13122669, 13122339, 13122790, 13120872, 13121402, 13121399, 13122253, 13122330, 13120794, 13121878]
getStoryTitlesAsync(topStoryIDs: topStoryIDs) {
titles in
print("// Callback printing titles")
for t in titles.sorted() {
print(t)
self.titlesLabel.text = "\(self.titlesLabel.text!)\n\(t)"
}
}
}
// gets all titles of storys with given IDS. Callback is called on main thread
func getStoryTitlesAsync(topStoryIDs: [Int], completion: @escaping ([String])->()) {
// create group
let group = DispatchGroup()
// mutable, not threadsafe
var titles = [String]()
print("// starting in order, because its a serial queue")
for (i,id) in topStoryIDs.enumerated() {
// enter
group.enter()
getStoryTitle(id: id, completion: { title in
let t = "\(i + 1) - \(title)"
print("[ finished job \(i) ]")
// go to main queue bc titles is mutable
// also update ui
DispatchQueue.main.async {
self.statusLabel.text = "\(self.statusLabel.text!)\nfinished job \(i)"
titles.append(t)
}
// leave
group.leave()
})
print("[ started job \(i) ]")
}
print("// finishing out of order, because its async")
statusLabel.text = "ORDER OF COMPLETION"
group.notify(queue: DispatchQueue.main, execute: {
print("// all done, executing callback on main queue")
completion(titles)
})
}
// gets title of one story, given id
func getStoryTitle(id: Int, completion: @escaping (String)->()) {
guard let url = URL(string: "https://hacker-news.firebaseio.com/v0/item/\(id).json") else {
return
}
let urlRequest = URLRequest(url: url)
// set up session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// make request
let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
if let e = error {
print(e)
return
}
do {
guard let d = data else {
return
}
if let parsed = try JSONSerialization.jsonObject(with: d, options: .allowFragments) as? [String:Any] {
if let t = parsed["title"] as? String {
completion(t)
}
}
} catch let error as NSError {
print(error)
}
})
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// UserController.swift
// App
//
// Created by Timothy Dillman on 1/24/19.
//
import Vapor
struct UsersController: RouteCollection {
func boot(router: Router) throws {
let routeGroup = router.grouped("api", "users")
// api/users
routeGroup.post(User.self, use: createHandler)
// api/users
routeGroup.get(use: getHandler)
// api/users/<id>
routeGroup.get(User.parameter, use: findOneHandler)
// api/users/<id>/acronyms
routeGroup.get(User.parameter, "acronyms", use: getAcronyms)
}
func createHandler(_ r: Request, user: User) throws -> Future<User> {
return user.save(on: r)
}
func getHandler(_ r: Request) throws -> Future<[User]> {
return User.query(on: r).all()
}
func findOneHandler(_ r: Request) throws -> Future<User> {
return try r.parameters.next(User.self)
}
func getAcronyms(_ r: Request) throws -> Future<[Acronym]> {
return try r.parameters.next(User.self)
.flatMap(to: [Acronym].self) { user in
try user.acronyms.query(on: r).all()
}
}
}
|
//
// ViewController.swift
// Pay-hub
//
// Created by RSTI E-Services on 11/04/17.
// Copyright © 2017 RSTI E-Services. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UIPickerViewDataSource, UIPickerViewDelegate{
@IBOutlet weak var selectCity: UITextField!
@IBOutlet weak var selectArea: UITextField!
@IBOutlet weak var pickerView1: UIPickerView!
@IBAction func orderNowButton(_ sender: UIButton) {
self.performSegue(withIdentifier: "cuisinegroups", sender: self)
}
var City = ["Delhi", "Noida", "Gurgaon", "Bangalore", "Mumbai"]
var Area = ["Sector 12" , "Sector 18", "Sector 21", "Sector 32", "Sector 50"]
override func viewDidLoad() {
super.viewDidLoad()
pickerView1.dataSource = self
pickerView1.delegate = self
self.selectCity.inputView = pickerView1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return City.count
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
return City[row]
}
if component == 1 {
return Area[row]
}
else {
return nil
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectCity.text = City[row]
selectArea.text = Area[row]
}
}
|
//
// DMInputView.swift
// DirectMessage
//
// Created by Seraph on 2020/3/15.
// Copyright © 2020 Paradise. All rights reserved.
//
import UIKit
protocol DMInputViewDelegate: class {
func inputBoxView(_: DMInputBoxView, didTapSendButtonWith text: String)
}
class DMInputBoxView: UIView {
enum Constants {
static let height: CGFloat = 64
}
@IBOutlet weak var inputBoxView: UITextField!
@IBOutlet weak var sendButton: UIButton!
weak var delegate: DMInputViewDelegate?
override var canBecomeFirstResponder: Bool {
true
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setupView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
self.setupView()
}
func setupView() {
guard let view = Bundle(for: type(of: self)).loadNibNamed(String(describing: self.classForCoder), owner: self, options: nil)?.first as? UIView else { return }
view.frame = self.bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.addSubview(view)
}
@IBAction func sendButtonTapped(_ sender: Any) {
guard let text = self.inputBoxView.text,
!text.isEmpty else { return }
self.delegate?.inputBoxView(self, didTapSendButtonWith: text)
self.inputBoxView.text = nil
}
}
|
//
// BaseContainer.swift
// mobiita
//
// Created by 三木俊作 on 2016/12/10.
// Copyright © 2016年 Shunsaku Miki. All rights reserved.
//
import Foundation
import Alamofire
typealias ConnectionResultHandler = (_ result: ConnectResult) -> ()
class BaseContainer<T: BaseModelProtocol> {
// MARK: - property
/** モデルリスト */
var modelList: [T] = []
}
|
//
// ViewController.swift
// Dicee-iOS13
import UIKit
class ViewController: UIViewController {
//With the help of IBOutlet we created two UIImageView variable refers to our design elements
@IBOutlet weak var diceImageView1: UIImageView!
@IBOutlet weak var diceImageView2: UIImageView!
//We created Image Array which include all of our 6 dice images
let diceArray = [ #imageLiteral(resourceName: "DiceOne"), #imageLiteral(resourceName: "DiceTwo"), #imageLiteral(resourceName: "DiceThree"), #imageLiteral(resourceName: "DiceFour"), #imageLiteral(resourceName: "DiceFive"), #imageLiteral(resourceName: "DiceSix") ]
@IBAction func rollButtonPressed(_ sender: UIButton) {
//randomElement function is a built-in function that helps us to get a random index element from desired array
diceImageView1.image = diceArray.randomElement()
diceImageView2.image = diceArray.randomElement()
}
}
|
//
// Pawn.swift
// Swifty Chess
//
// Created by Mikael Mukhsikaroyan on 10/28/16.
// Copyright © 2016 MSquaredmm. All rights reserved.
//
import UIKit
class Pawn: ChessPiece {
var tryingToAdvanceBy2 = false
init(row: Int, column: Int, color: UIColor) {
super.init(row: row, column: column)
self.color = color
symbol = "♟"
}
/** Checks to see if the direction the piece is moving is the way this piece type is allowed to move. Doesn't take into account the sate of the board */
func isMovementAppropriate(toIndex dest: BoardIndex) -> Bool {
// is it advancing by 2
// check if the move is in the same column
if self.col == dest.column {
// can only move 2 forward if first time moving pawn
if (self.row == 1 && dest.row == 3 && color == .white) || (self.row == 6 && dest.row == 4 && color == .black) {
tryingToAdvanceBy2 = true
return true
}
}
tryingToAdvanceBy2 = false
// the move direction depends on the color of the piece
let moveDirection = color == .black ? -1 : 1
// if the movement is only 1 row up/down
if dest.row == self.row + moveDirection {
// check for diagonal movement and forward movement
if (dest.column == self.col - 1) || (dest.column == self.col) || (dest.column == self.col + 1) {
return true
}
}
return false
}
}
|
//
// Bundle+XMExtension.swift
// TestWeibo_Swift
//
// Created by TwtMac on 16/12/13.
// Copyright © 2016年 Mazy. All rights reserved.
//
import Foundation
extension Bundle {
// 计算性属性,没有参数,没有返回值
var nameSpace: String {
return infoDictionary?["CFBundleExecutable"] as? String ?? ""
}
}
|
//
// RequestMetaData.swift
// HeWeatherIO
//
// Created by iMac on 2018/5/25.
// Copyright © 2018年 iMac. All rights reserved.
//
import Foundation
struct RequestMetaData {
let cacheControl: String?
let apiRequestsCount: Int?
let responseTime: Float?
}
|
//
// SignInController.swift
// SSASideMenuStoryboardExample
//
// Created by RAYW2 on 1/2/2017.
// Copyright © 2017年 SebastianAndersen. All rights reserved.
//
import UIKit
import Parse
class SignInController: UIViewController {
@IBOutlet weak var createEmail: UITextField!
@IBOutlet weak var createLoginName: UITextField!
@IBOutlet weak var createLoginPassward: UITextField!
@IBOutlet weak var confirmPassward: UITextField!
@IBOutlet weak var createAccountButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//Config
//textfield
let textfieldArray: [UITextField] = [self.createEmail, self.createLoginName, self.createLoginPassward, self.confirmPassward]
for item in textfieldArray{
let border = CALayer()
let width = CGFloat(2.0)
border.borderColor = UIColor.cyan.cgColor
border.frame = CGRect(x: 0, y: item.frame.size.height - width, width: item.frame.size.width, height: item.frame.size.height)
border.borderWidth = width
item.layer.addSublayer(border)
item.layer.masksToBounds = true
}
//Button
//round corner
createAccountButton.layer.cornerRadius = 10
//shadow
createAccountButton.layer.shadowColor = UIColor.black.cgColor
createAccountButton.layer.shadowOpacity = 1
createAccountButton.layer.shadowOffset = CGSize(width: 0, height: 0)
createAccountButton.layer.shadowRadius = 10
//Tap
self.hideKeyboardWhenTappedAround()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func signupButtonClicked(_ sender: Any) {
print("Sign up btn is clicked")
// Basic Validation on the input field
guard let username = createLoginName.text, !username.isEmpty else {
present(getErrorAlertCtrl(title: "Missing Username", message: "Please fill in the username"),
animated: true, completion: nil)
return
}
guard let password = createLoginPassward.text, !password.isEmpty else {
present(getErrorAlertCtrl(title: "Missing Password", message: "Please fill in the password"),
animated: true, completion: nil)
return
}
guard let passwordConfirm = confirmPassward.text, !passwordConfirm.isEmpty, password == passwordConfirm else {
present(getErrorAlertCtrl(title: "Password Mismatch", message: "Please enter the same password again"),
animated: true, completion: nil)
return
}
let user = PFUser()
user.username = username
user.password = passwordConfirm
user.signUpInBackground { (success:Bool, error:Error?) in
if let error = error {
print(error.localizedDescription)
// Show warning alert to user
let alertCtrl = getErrorAlertCtrl(title: "Sign up failed", message: error.localizedDescription)
self.present(alertCtrl, animated: true, completion: nil)
} else {
// login success
print("success login \(success)")
// TODO: redirect to somewhere else
signIned = true
let controller = self.storyboard?.instantiateViewController(withIdentifier: "Profile")
self.sideMenuViewController?.contentViewController = UINavigationController(rootViewController: controller!)
}
}
}
}
|
//
// NewsManager.swift
// NewsApp
//
// Created by Игорь Корабельников on 22.06.2021.
//
import UIKit
import FeedKit
import Alamofire
import AlamofireRSSParser
class NewsManager {
static let shared = NewsManager()
private let defaultNewsURL = "https://news.google.com/rss?pz=1&cf=all&hl=en-US&topic=n&gl=US&ceid=US:en"
func getTheNewsViaAlamofire(completion: @escaping ([Article]?) -> Void) {
var translatedNewsURL = URL(string: defaultNewsURL)! // Default Link
do {
translatedNewsURL = try NSLocalizedString("localizedNewsURL", comment: "articlesLanguage").asURL()
} catch {
print(error.localizedDescription)
}
var articles = [Article]()
guard Connectivity.isConnectedToInternet else {
print("Is not connected")
articles.loadFromCoreData()
completion(articles)
return
}
AF.request(translatedNewsURL).responseRSS { response in
guard let news = response.value?.items else { return }
let newsItems = news.convertToArticleArray()
newsItems.saveToCoreData()
completion(newsItems)
}
}
}
|
//
// MapController.swift
// CarFinder
//
// Created by Mauri on 21/4/17.
// Copyright © 2017 Mauri. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class MapView: UIViewController, CLLocationManagerDelegate, UIWebViewDelegate, ContainerToMaster {
@IBOutlet weak var WebBrowserView: UIWebView!
@IBOutlet weak var activity: UIActivityIndicatorView!
var locationManager: CLLocationManager = CLLocationManager()
var startLocation: CLLocation!
private var matriculaSeleccionada : String = ""
var containerViewController: MapTableController?
private var latitudActual : Double = 0
private var longitudActual : Double = 0
private var localizacionDesactivada : Bool = true
override func viewDidLoad() {
super.viewDidLoad()
WebBrowserView.delegate = self
if (self.inicializarLocalizacion()) {
localizacionDesactivada = false
self.cargarMapa(lat: 0, lng: 0, descripcion: "vacio")
}
}
//Si la RAM se agota, elimina la caché cargada en RAM del navegador
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
URLCache.shared.removeAllCachedResponses()
URLCache.shared.diskCapacity = 0
URLCache.shared.memoryCapacity = 0
}
//Prepara para cargar el ContainerView con la tabla inferior de la sección
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "containerViewSegue" {
containerViewController = segue.destination as? MapTableController
containerViewController!.containerToMaster = self
}
}
//Cuando se muestre la interfaz se inicializará la localización
override func viewWillAppear(_ animated: Bool) {
locationManager.startUpdatingLocation()
}
//Cuando se descarga la vista se desactiva la localización para ahorrar batería
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
URLCache.shared.removeAllCachedResponses()
URLCache.shared.diskCapacity = 0
URLCache.shared.memoryCapacity = 0
locationManager.stopUpdatingLocation()
}
//Activa la localización, pidiendo los permisos necesarios en caso de no disponer de ellos
private func inicializarLocalizacion() ->Bool {
locationManager.delegate = self
let authorizationStatus = CLLocationManager.authorizationStatus()
//Si no tiene han seleccionado permisos, lo pide al usuario
if (authorizationStatus == CLAuthorizationStatus.notDetermined) {
locationManager.requestWhenInUseAuthorization()
return false
}
//Si no tiene han seleccionado permisos, muestra error
else if (authorizationStatus == CLAuthorizationStatus.denied){
mostrarError()
return false
}
//Inicia el seguimiento
else {
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
self.startLocation = nil
}
return true
}
//Muestra un error por no disponer de permisos de localización
private func mostrarError() {
let URL = Bundle.main.url(forResource: "error", withExtension: "html")
let request = URLRequest(url: URL!)
WebBrowserView.loadRequest(request)
WebBrowserView.scrollView.isScrollEnabled = false
WebBrowserView.scrollView.bounces = false
}
//Guarda la localización actual para el vehículo seleccionado
@IBAction func savePosition(_ sender: Any) {
if (!localizacionDesactivada) {
//Si no se ha seleccionado ninguno
if (matriculaSeleccionada == "") {
self.mostrarError(mess: "No ha seleccionado ningún vehículo")
}
else {
let con = Mapa()
con.insertarPosicion(matricula: matriculaSeleccionada, latitud: String(format:"%f", latitudActual), longitud: String(format:"%f", longitudActual)) {
respuesta in
//Si ocurrió un problema con el servidor
if (respuesta.value(forKey: "errorno") as! NSNumber == 404) {
self.mostrarError(mess: respuesta.value(forKey: "errorMessage") as! String)
}
//Posición guardada con éxito
else {
let alertController = UIAlertController(title: nil, message: "Posición guardada", preferredStyle: .alert)
DispatchQueue.main.async(execute: {
if self.presentedViewController == nil {
self.present(alertController, animated: true, completion: nil)
} else{
self.dismiss(animated: false) { () -> Void in
self.present(alertController, animated: true, completion: nil)
}
}
})
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
alertController.dismiss(animated: true, completion: nil)
self.containerViewController?.actualizarPosicionCoche(matricula: self.matriculaSeleccionada, lat: String(self.latitudActual), long: String (self.longitudActual))
self.cargarMapa(lat : self.latitudActual, lng: self.longitudActual, descripcion : self.matriculaSeleccionada)
}
}
}
}
} else {
self.mostrarError(mess: "No puede guardar la localización porque la aplicación no tiene permisos para conocer esta")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let latestLocation: CLLocation = locations[locations.count - 1]
let long = latestLocation.coordinate.longitude;
let lat = latestLocation.coordinate.latitude;
if startLocation == nil {
startLocation = latestLocation
localizacionDesactivada = false
}
if (lat > latitudActual + 0.0005 || lat < latitudActual - 0.0005 || long > longitudActual + 0.0005 || long < longitudActual - 0.0005) {
latitudActual = lat
longitudActual = long
cargarMapa(lat : lat, lng: long, descripcion: "actual")
}
}
//Carga el mapa en el web view con los datos indicados
internal func cargarMapa(lat : Double, lng: Double, descripcion : String) {
var URL = Bundle.main.url(forResource: "mapa", withExtension: "html")
let URLwithparameters : String = (URL?.path)! + "?lat="+String(format:"%.4f", lat)+"&lng="+String(format:"%.4f", lng)+"&description="+descripcion
URL = Foundation.URL(string: URLwithparameters)
let request = URLRequest(url: URL!)
WebBrowserView.loadRequest(request)
}
//Muestra un activity indicator cuando el Web View se está cargando
func webViewDidStartLoad(_: UIWebView){
activity.isHidden = false
activity.startAnimating()
}
//Captura la matricula del coche con su posición y redirige a la aplicación de Apple Maps
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if request.url?.scheme == "carfinder" {
let lat = request.url?.getQueryItemValueForKey(key: "lat")
let long = request.url?.getQueryItemValueForKey(key: "lon")
let matr = request.url?.getQueryItemValueForKey(key: "description")
let latitud: CLLocationDegrees = Double(lat!)!
let longitud: CLLocationDegrees = Double(long!)!
let distancia:CLLocationDistance = 44
let coordenadas = CLLocationCoordinate2DMake(latitud, longitud)
let region = MKCoordinateRegionMakeWithDistance(coordenadas, distancia, distancia)
let opciones = [
MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: region.center),
MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: region.span)
]
let puntoMapa = MKPlacemark(coordinate: coordenadas, addressDictionary: nil)
let itemMapa = MKMapItem(placemark: puntoMapa)
itemMapa.name = matr
itemMapa.openInMaps(launchOptions: opciones)
}
return true
}
//Detiene el Acitivty Indicator
func webViewDidFinishLoad(_: UIWebView){
activity.isHidden = true
activity.stopAnimating()
}
//Redirección desde la clase MapTableController, se usa al deseleccionar un coche para cargar la localización actual
func matriculafromcontainer(containerData : String) {
self.matriculaSeleccionada = containerData
if (!localizacionDesactivada) {
cargarMapa(lat : latitudActual, lng: longitudActual, descripcion: "actual")
}
else {
mostrarError()
}
}
//Redirección desde la clase MapTableController, se usa al seleccionar un coche para cargar la localización del coche
func matriculafromcontainer(containerData : String, latitud : String, long : String, description : String) {
self.matriculaSeleccionada = containerData
cargarMapa(lat : Double(latitud)!, lng: Double(long)!, descripcion: description)
}
}
|
//
// CountryCovidInfoCellViewModel.swift
// CovidApp
//
// Creado por Joan Martin Martrus el 21/01/2021.
// Copyright (c) 2021 ___ORGANIZATIONNAME___. Todos los derechos reservados.
import Foundation
internal final class CountryCovidInfoCellViewModel {
var countryName: String
var totalDeaths: Int
var countryCovidInfo: CountryCovidInfoResponse
init(countryCovidInfo: CountryCovidInfoResponse) {
self.countryName = countryCovidInfo.country ?? ""
self.totalDeaths = countryCovidInfo.deaths ?? 0
self.countryCovidInfo = countryCovidInfo
}
}
// MARK: - DrawerItemProtocol -
extension CountryCovidInfoCellViewModel: DrawerItemProtocol {
var cellDrawer: CellDrawerProtocol {
return CountryCovidInfoCellDrawer()
}
}
|
import Foundation
public protocol Log: Codable {
init(text: String, logLevel: LogLevel)
// TODO: short, medium, long, or unix timestamp version
var date: Date { get }
var text: String { get }
var logLevel: LogLevel { get }
}
|
//
// DrawOViewController.swift
// Ball
//
// Created by Quynh on 2/13/20.
// Copyright © 2020 Taof. All rights reserved.
//
import UIKit
class DrawOViewController: UIViewController {
var ball: UIImageView!
let radius: CGFloat = 50.0
var bienX: CGFloat = 0
var bienY: CGFloat = 0
var timer = Timer()
var diNgang = false
var diDoc = false
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
ball = UIImageView(frame: CGRect(x: 0, y: 0, width: radius, height: radius))
ball.image = UIImage(named: "bong")
ball.contentMode = .scaleAspectFit
view.addSubview(ball)
bienX = self.ball.frame.origin.x
bienY = self.ball.frame.origin.y
runTimer()
}
func runTimer() {
timer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: (#selector(runningFunction)), userInfo: nil, repeats: true)
}
@objc func runningFunction(){
ball.transform = ball.transform.concatenating(CGAffineTransform(rotationAngle: -CGFloat.pi/2))
// Nếu vị trí hiện tại nhỏ hơn max
if bienX < (self.view.bounds.width - radius) && diNgang == false {
setX(x: bienX)
bienX = bienX + 5
} else { // x = max rồi thì di chuyển y neu y < max
if bienY<(self.view.bounds.height - radius) && diDoc == false {
setY(y:bienY)
bienY = bienY + 5
} else {// y = max rồi giảm x -> 0
diDoc = true
if bienX > 0 {
diNgang = true
setX(x: bienX)
bienX = bienX - 5
} else {
if bienY > 0 {
setY(y: bienY)
bienY = bienY - 5
} else {
diNgang = false
diDoc = false
}
}
}
}
}
func setX(x: CGFloat) {
self.ball.frame.origin.x = x
}
func setY(y: CGFloat) {
self.ball.frame.origin.y = y
}
}
|
//
// StringExtension.swift
// MockApp
//
// Created by M. Ensar Baba on 27.03.2019.
// Copyright © 2019 MobileNOC. All rights reserved.
//
import UIKit
extension String {
func validateEmail() -> Bool {
let emailRegEx = "^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$"
let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: self)
}
func localized() -> String {
return NSLocalizedString(self, comment: "")
}
func widthOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSAttributedString.Key.font: font]
let size = self.size(withAttributes: fontAttributes)
return size.width
}
func heightOfString(usingFont font: UIFont) -> CGFloat {
let fontAttributes = [NSAttributedString.Key.font: font]
let size = self.size(withAttributes: fontAttributes)
return size.height
}
subscript (i: Int) -> Character {
return self[index(startIndex, offsetBy: i)]
}
subscript (bounds: CountableRange<Int>) -> Substring {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[start ..< end]
}
subscript (bounds: CountableClosedRange<Int>) -> Substring {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[start ... end]
}
subscript (bounds: CountablePartialRangeFrom<Int>) -> Substring {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(endIndex, offsetBy: -1)
return self[start ... end]
}
subscript (bounds: PartialRangeThrough<Int>) -> Substring {
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[startIndex ... end]
}
subscript (bounds: PartialRangeUpTo<Int>) -> Substring {
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[startIndex ..< end]
}
}
|
//
// CreateAliasPresenter.swift
// WavesWallet-iOS
//
// Created by mefilt on 29/10/2018.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import Foundation
import RxFeedback
import RxSwift
import RxCocoa
import WavesSDKExtensions
import WavesSDK
import Extensions
import DomainLayer
protocol CreateAliasModuleOutput: AnyObject {
func createAliasCompletedCreateAlias(_ alias: String)
}
protocol CreateAliasModuleInput {}
protocol CreateAliasPresenterProtocol {
typealias Feedback = (Driver<CreateAliasTypes.State>) -> Signal<CreateAliasTypes.Event>
var moduleOutput: CreateAliasModuleOutput? { get set }
func system(feedbacks: [Feedback])
}
final class CreateAliasPresenter: CreateAliasPresenterProtocol {
fileprivate typealias Types = CreateAliasTypes
private let disposeBag: DisposeBag = DisposeBag()
private let aliasesRepository: AliasesRepositoryProtocol = UseCasesFactory.instance.repositories.aliasesRepositoryRemote
private let authorizationInteractor: AuthorizationUseCaseProtocol = UseCasesFactory.instance.authorization
private let transactionsInteractor: TransactionsUseCaseProtocol = UseCasesFactory.instance.transactions
private let accountBalanceInteractor: AccountBalanceUseCaseProtocol = UseCasesFactory.instance.accountBalance
weak var moduleOutput: CreateAliasModuleOutput?
func system(feedbacks: [Feedback]) {
var newFeedbacks = feedbacks
newFeedbacks.append(checkExistAliasQuery())
newFeedbacks.append(getAliasesQuery())
newFeedbacks.append(externalQueries())
newFeedbacks.append(enoughtWavesFeeBalanceQuery())
let initialState = self.initialState()
let system = Driver.system(initialState: initialState,
reduce: CreateAliasPresenter.reduce,
feedback: newFeedbacks)
system
.drive()
.disposed(by: disposeBag)
}
}
// MARK: - Feedbacks
fileprivate extension CreateAliasPresenter {
func enoughtWavesFeeBalanceQuery() -> Feedback {
return react(request: { state -> Bool? in
return state.displayState.isAppeared ? true : nil
}, effects: { [weak self] _ -> Signal<Types.Event> in
guard let self = self else { return Signal.empty() }
return self
.authorizationInteractor.authorizedWallet()
.flatMap{ [weak self] wallet -> Observable<Bool> in
guard let self = self else { return Observable.empty() }
return self.transactionsInteractor.calculateFee(by: .createAlias, accountAddress: wallet.address)
.flatMap { [weak self] fee -> Observable<Bool> in
guard let self = self else { return Observable.empty() }
return self.accountBalanceInteractor
.balances()
.flatMap { (balances) -> Observable<Bool> in
if let assetBalance = balances.first(where: {$0.assetId == WavesSDKConstants.wavesAssetId}) {
return Observable.just(assetBalance.availableBalance >= fee.amount)
}
return Observable.just(false)
}
}
}
.map {.didFinishValidateFeeBalance($0)}
.asSignal(onErrorRecover: { e in
SweetLogger.error(e)
return Signal.just(Types.Event.didFinishValidateFeeBalance(false))
})
})
}
func externalQueries() -> Feedback {
return react(request: { state -> Types.Query? in
switch state.query {
case .completedCreateAlias?:
return state.query
default:
return nil
}
}, effects: { [weak self] query -> Signal<Types.Event> in
guard let self = self else { return Signal.empty() }
if case .completedCreateAlias(let name) = query {
self.moduleOutput?.createAliasCompletedCreateAlias(name)
}
return Signal.just(.completedQuery)
})
}
func getAliasesQuery() -> Feedback {
return react(request: { state -> String? in
if case .createAlias(let name)? = state.query {
return name
} else {
return nil
}
}, effects: { [weak self] name -> Signal<Types.Event> in
guard let self = self else { return Signal.empty() }
return self
.authorizationInteractor
.authorizedWallet()
.flatMap({ [weak self] wallet -> Observable<(Money, DomainLayer.DTO.SignedWallet)> in
guard let self = self else { return Observable.empty() }
return self
.transactionsInteractor
.calculateFee(by: .createAlias, accountAddress: wallet.address)
.map { ($0, wallet) }
})
.flatMap({ [weak self] data -> Observable<Bool> in
guard let self = self else { return Observable.empty() }
return self
.transactionsInteractor
.send(by: .createAlias(.init(alias: name, fee: data.0.amount)), wallet: data.1)
.map { _ in true }
})
.map { _ in .aliasCreated }
.asSignal(onErrorRecover: { e in
SweetLogger.error(e)
return Signal.just(Types.Event.handlerError(e))
})
})
}
func checkExistAliasQuery() -> Feedback {
return react(request: { state -> String? in
if case .checkExist(let name)? = state.query {
return name
} else {
return nil
}
}, effects: { [weak self] name -> Signal<Types.Event> in
guard let self = self else { return Signal.empty() }
return self
.authorizationInteractor
.authorizedWallet()
.flatMap({ wallet -> Observable<String> in
return self.aliasesRepository.alias(by: name, accountAddress: wallet.address)
})
.map { _ in .errorAliasExist }
.asSignal(onErrorRecover: { e in
if let error = e as? AliasesRepositoryError, error == .dontExist {
return Signal.just(Types.Event.aliasNameFree)
}
return Signal.just(Types.Event.errorAliasExist)
})
})
}
}
// MARK: Core State
private extension CreateAliasPresenter {
static func reduce(state: Types.State, event: Types.Event) -> Types.State {
var newState = state
reduce(state: &newState, event: event)
return newState
}
static func reduce(state: inout Types.State, event: Types.Event) {
switch event {
case .viewWillAppear:
state.displayState.isAppeared = true
let section = Types.ViewModel.Section(rows: [.input(state.displayState.input, error: nil)])
state.displayState.sections = [section]
state.displayState.action = .reload
case .viewDidDisappear:
state.displayState.isAppeared = false
case .input(let text):
state.displayState.input = text
state.displayState.action = .none
state.query = nil
state.displayState.errorState = .none
var inputError: String? = nil
if let text = text {
if RegEx.alias(text) {
if text.count < WavesSDKConstants.aliasNameMinLimitSymbols {
state.displayState.isEnabledSaveButton = false
inputError = Localizable.Waves.Createalias.Error.minimumcharacters
} else if text.count > WavesSDKConstants.aliasNameMaxLimitSymbols {
state.displayState.isEnabledSaveButton = false
inputError = Localizable.Waves.Createalias.Error.charactersmaximum
} else {
state.displayState.isLoading = true
state.displayState.isEnabledSaveButton = false
inputError = nil
state.query = .checkExist(text)
}
} else {
inputError = Localizable.Waves.Createalias.Error.invalidcharacter
state.displayState.isEnabledSaveButton = false
}
} else {
inputError = nil
state.displayState.isEnabledSaveButton = false
}
state.displayState.action = .update
let section = Types.ViewModel.Section(rows: [.input(state.displayState.input, error: inputError)])
state.displayState.sections = [section]
case .aliasNameFree:
state.query = nil
state.displayState.action = .update
state.displayState.isLoading = false
state.displayState.isEnabledSaveButton = state.displayState.isValidEnoughtFee
let section = Types.ViewModel.Section(rows: [.input(state.displayState.input, error: nil)])
state.displayState.sections = [section]
case .errorAliasExist:
state.query = nil
state.displayState.action = .update
state.displayState.isLoading = false
state.displayState.isEnabledSaveButton = false
let section = Types.ViewModel.Section(rows: [.input(state.displayState.input, error: Localizable.Waves.Createalias.Error.alreadyinuse)])
state.displayState.sections = [section]
case .handlerError(let error):
state.query = nil
state.displayState.isLoading = false
state.displayState.isEnabledSaveButton = state.displayState.isValidEnoughtFee
state.displayState.errorState = DisplayErrorState.error(DisplayError(error: error))
case .aliasCreated:
guard let text = state.displayState.input else { return }
state.displayState.isLoading = false
state.displayState.isEnabledSaveButton = true
state.query = .completedCreateAlias(text)
state.displayState.errorState = .none
case .createAlias:
guard let text = state.displayState.input else { return }
state.query = .createAlias(text)
state.displayState.isLoading = true
state.displayState.isEnabledSaveButton = false
state.displayState.errorState = .none
case .completedQuery:
state.query = nil
case .didFinishValidateFeeBalance(let isValidEnoughtFee):
state.displayState.isEnabledSaveButton = isValidEnoughtFee
state.displayState.isValidEnoughtFee = isValidEnoughtFee
state.displayState.action = .updateValidationFeeBalance(isValidEnoughtFee)
}
}
}
// MARK: UI State
private extension CreateAliasPresenter {
func initialState() -> Types.State {
return Types.State(query: nil,
displayState: initialDisplayState())
}
func initialDisplayState() -> Types.DisplayState {
return Types.DisplayState(sections: [],
input: nil,
errorState: .none,
isEnabledSaveButton: false,
isLoading: false,
isAppeared: false,
action: .none,
isValidEnoughtFee: true)
}
}
|
//
// ViewController.swift
// swiftTableView
//
// Created by Chi Zhang on 14/6/4.
// Copyright (c) 2014年 Chi. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet
var tableView: UITableView
var items: String[] = ["China", "USA", "Russia"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return self.items.count;
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel.text = self.items[indexPath.row]
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
println("You selected cell #\(indexPath.row)!")
var detail:DetailViewController = self.storyboard.instantiateViewControllerWithIdentifier("detail") as DetailViewController
detail.capitalString = self.items[indexPath.row]
// self.presentViewController(detail,animated:true,completion:nil);
// detail.capitalLabel.text = self.items[indexPath.row]
self.navigationController.pushViewController(detail,animated:true)
}
}
|
//
// Reusable.swift
// PlayerList
//
// Created by André Lucas Ota on 27/10/21.
//
import Foundation
import UIKit
protocol Reusable { }
extension Reusable {
static var identifier: String {
return String(describing: Self.self)
}
}
extension UITableViewCell: Reusable { }
|
//
// CustomRankingCriterionTests.swift
//
//
// Created by Vladislav Fitc on 12.03.2020.
//
import Foundation
import XCTest
@testable import AlgoliaSearchClient
class CustomRankingCriterionTests: XCTestCase {
func testCoding() throws {
try AssertEncodeDecode(CustomRankingCriterion.asc("attr"), "asc(attr)")
try AssertEncodeDecode(CustomRankingCriterion.desc("attr"), "desc(attr)")
}
}
|
//
// HistoryTypes+State.swift
// WavesWallet-iOS
//
// Created by Mac on 02/08/2018.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import Foundation
import DomainLayer
// MARK: Set Methods
extension HistoryTypes.State {
func setIsAppeared(_ isAppeared: Bool) -> HistoryTypes.State {
var newState = self
newState.isAppeared = isAppeared
return newState
}
func setIsRefreshing(_ isRefreshing: Bool) -> HistoryTypes.State {
var newState = self
newState.isRefreshing = isRefreshing
return newState
}
func setSections(sections: [HistoryTypes.ViewModel.Section]) -> HistoryTypes.State {
var newState = self
newState.sections = sections
return newState
}
func setTransactions(transactions: [DomainLayer.DTO.SmartTransaction]) -> HistoryTypes.State {
var newState = self
newState.transactions = transactions
return newState
}
func setFilter(filter: HistoryTypes.Filter) -> HistoryTypes.State {
var newState = self
newState.currentFilter = filter
return newState
}
}
extension HistoryTypes.State {
static func initialState(historyType: HistoryType) -> HistoryTypes.State {
return HistoryTypes.State(currentFilter: .all,
filters: historyType.filters,
transactions: [],
sections: self.skeletonSections(),
isRefreshing: false,
isAppeared: false,
refreshData: .refresh,
errorState: .none)
}
static func skeletonSections() -> [HistoryTypes.ViewModel.Section] {
return [HistoryTypes.ViewModel.Section(items: [.transactionSkeleton,
.transactionSkeleton,
.transactionSkeleton,
.transactionSkeleton,
.transactionSkeleton,
.transactionSkeleton,
.transactionSkeleton])]
}
}
|
//
// MediaView.swift
// iTunes_Media
//
// Created by Collins on 4/12/19.
// Copyright © 2019 Collins. All rights reserved.
//
import UIKit
class MediaView: MediaProcession {
// pull, commit, push, pull
// 123
// Playstation 5
// Apple
//New label made
var yagmurIsAwesome = UILabel()
//helloworld
override func viewDidLoad() {
super.viewDidLoad()
let barHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height
let displayWidth: CGFloat = self.view.frame.width
let displayHeight: CGFloat = self.view.frame.height
myTableView = UITableView(frame: CGRect(x: 0, y: 0, width: displayWidth, height: displayHeight - barHeight))
myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
myTableView.dataSource = self
myTableView.delegate = self
myTableView.backgroundColor = UIColor.white
self.view.addSubview(myTableView)
myTableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
// Attaching the content's edges to the scroll view's edges
myTableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
myTableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
myTableView.topAnchor.constraint(equalTo: self.view.topAnchor),
myTableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
// Satisfying size constraints
myTableView.widthAnchor.constraint(equalTo: self.view.widthAnchor)
])
myTableView.translatesAutoresizingMaskIntoConstraints = false
network_request()
}
}
|
//
// LocalTaskRepository.swift
// Agenda
//
// Created by VICTOR ALVAREZ LANTARON on 10/12/18.
// Copyright © 2018 victorSL. All rights reserved.
//
import Foundation
import RealmSwift
class LocalTaskRepository: Repository{
func getAll() -> [Task]{
var tasks: [Task] = []
do {
let entities = try Realm().objects(TaskEntity.self).sorted(byKeyPath: "toDo", ascending: true)
for entity in entities {
let model = entity.taskModel()
tasks.append(model)
}
}
catch let error as NSError {
print("ERROR getAll Tasks: ", error.description)
}
return tasks
}
func get(identifier:String) -> Task?{
do {
let realm = try! Realm()
if let entity = realm.objects(TaskEntity.self).filter("id == %@",identifier).first {
let model = entity.taskModel()
return model
}
}
return nil
}
func create(a: Task) -> Bool {
do {
let realm = try! Realm()
let entity = TaskEntity(id: a.id, toDo: a.toDo, isDone: a.isDone)
try realm.write {
// El metodo update: true indica que si encuentra uno igual lo replaza
realm.add(entity, update: true)
}
} catch {
return false
}
return true
}
func delete(a:Task) ->Bool {
do{
let realm = try Realm()
try realm.write {
let entryToDelete = realm.objects(TaskEntity.self).filter("id == %@", a.id)
realm.delete(entryToDelete)
}
}
catch {
return false
}
return true
}
func update(a: Task) -> Bool {
return create(a: a)
}
}
|
//
// Utile.swift
// practice
//
// Created by SangDo on 2017. 7. 2..
// Copyright © 2017년 SangDo. All rights reserved.
//
import UIKit
extension Date {
func getCurrentDate() -> String {
let time = Date.init()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.timeZone = TimeZone.autoupdatingCurrent
return formatter.string(from: time)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.