text stringlengths 8 1.32M |
|---|
//
// Country.swift
// Domain
//
// Created by Ganesha Danu on 11/01/19.
// Copyright © 2019 Ganesha Danu. All rights reserved.
//
import Foundation
public struct Country: Codable {
var iso_3166_1: String
var name: String
}
|
//
// RepositoriesInteractorIO.swift
// ViperSample
//
// Created by InKwon Devik Kim on 20/03/2019.
//Copyright © 2019 InKwon Devik Kim. All rights reserved.
//
/// It's interface for interactor
protocol RepositoriesInteractorInput: class {
func fetchRepositories(userName: String)
}
/// It's interface for presenter
protocol RepositoriesInteractorOutput: class {
func result(model: [Repository])
func result(error: Error)
func result(panicError: Error)
}
|
//
// PropertyFilterController.swift
// RumahHokie
//
// Created by Hadron Megantara on 16/10/18.
// Copyright © 2018 Hadron Megantara. All rights reserved.
//
import Foundation
import UIKit
import Alamofire
class PropertyFilterController: UIViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var txtKeyWord: UITextField!
@IBOutlet weak var radioPropertyStatusSold: UIImageView!
@IBOutlet weak var radioPropertyStatusRent: UIImageView!
@IBOutlet weak var btnPropertyType: UIButton!
@IBOutlet weak var txtPriceMin: UITextField!{
didSet {
txtPriceMin?.addDoneCancelToolbar(onDone: (target: self, action: #selector(doneButtonTappedForMyNumericTextField)))
}
}
@IBOutlet weak var txtPriceMax: UITextField!{
didSet {
txtPriceMax?.addDoneCancelToolbar(onDone: (target: self, action: #selector(doneButtonTappedForMyNumericTextField)))
}
}
@IBOutlet weak var btnPropertyProvince: UIButton!
@IBOutlet weak var txtPropertyBuildingMin: UITextField!{
didSet {
txtPropertyBuildingMin?.addDoneCancelToolbar(onDone: (target: self, action: #selector(doneButtonTappedForMyNumericTextField)))
}
}
@IBOutlet weak var txtPropertyBuildingMax: UITextField!{
didSet {
txtPropertyBuildingMax?.addDoneCancelToolbar(onDone: (target: self, action: #selector(doneButtonTappedForMyNumericTextField)))
}
}
@IBOutlet weak var txtPropertyAreaMin: UITextField!{
didSet {
txtPropertyAreaMin?.addDoneCancelToolbar(onDone: (target: self, action: #selector(doneButtonTappedForMyNumericTextField)))
}
}
@IBOutlet weak var txtPropertyAreaMax: UITextField!{
didSet {
txtPropertyAreaMax?.addDoneCancelToolbar(onDone: (target: self, action: #selector(doneButtonTappedForMyNumericTextField)))
}
}
@IBOutlet weak var txtPropertyBedRoom: UITextField!{
didSet {
txtPropertyBedRoom?.addDoneCancelToolbar(onDone: (target: self, action: #selector(doneButtonTappedForMyNumericTextField)))
}
}
@IBOutlet weak var txtPropertyBathRoom: UITextField!{
didSet {
txtPropertyBathRoom?.addDoneCancelToolbar(onDone: (target: self, action: #selector(doneButtonTappedForMyNumericTextField)))
}
}
@IBOutlet weak var txtPropertyGarage: UITextField!{
didSet {
txtPropertyGarage?.addDoneCancelToolbar(onDone: (target: self, action: #selector(doneButtonTappedForMyNumericTextField)))
}
}
@IBOutlet weak var baseView: UIView!
@IBOutlet weak var viewBtnPropertyType: UIView!
var senderVar: Int = 1
let defaults = UserDefaults.standard
var propertyStatus: Int = 0
var propertyType: Int = 0
var propertyTypeString: String = ""
var propertyProvince: Int = 0
var propertyProvinceString: String = ""
var propertyPriceMin: Int = 0
var propertyPriceMax: Int = 0
var propertyBuildingMin: Int = 0
var propertyBuildingMax: Int = 0
var propertyAreaMin: Int = 0
var propertyAreaMax: Int = 0
var propertyBedRoom: Int = 0
var propertyBathroom: Int = 0
var propertyGarage: Int = 0
var propertyKeyword: String = ""
@IBOutlet weak var propertyViewSold: UIView!
@IBOutlet weak var propertyViewRent: UIView!
var propertyTypeData = ["Apartemen", "Rumah", "Tanah", "Komersial", "Properti Baru"]
var propertyProvinceData: Array = [Any]()
var pickerPropertyType = UIPickerView()
var pickerPropertyProvince = UIPickerView()
let alert = UIAlertController(title: "", message: "\n\n\n\n\n\n\n\n\n\n", preferredStyle: .alert)
let alert2 = UIAlertController(title: "", message: "\n\n\n\n\n\n\n\n\n\n", preferredStyle: .alert)
override func viewDidLoad() {
super.viewDidLoad()
txtKeyWord.delegate = self
txtKeyWord.tag = 200
txtPriceMin.delegate = self
txtPriceMin.delegate = self
txtPriceMax.delegate = self
txtPropertyBuildingMin.delegate = self
txtPropertyBuildingMax.delegate = self
txtPropertyAreaMin.delegate = self
txtPropertyAreaMax.delegate = self
txtPropertyBedRoom.delegate = self
txtPropertyBathRoom.delegate = self
txtPropertyGarage.delegate = self
propertyProvinceData.append(["mstr_provinsi_id": 0, "mstr_provinsi_desc": "Semua"])
loadProvince()
let gesture = UITapGestureRecognizer(target: self, action: #selector(viewPropertySoldAction))
propertyViewSold.addGestureRecognizer(gesture)
let gesture2 = UITapGestureRecognizer(target: self, action: #selector(viewPropertyRentAction))
propertyViewRent.addGestureRecognizer(gesture2)
var pickerRect = pickerPropertyType.frame
pickerRect.origin.x = -30
pickerRect.origin.y = 0
pickerPropertyType.tag = 1
pickerPropertyType.frame = pickerRect
pickerPropertyType.delegate = self
pickerPropertyType.dataSource = self
pickerPropertyType.isHidden = true
alert.isModalInPopover = true
alert.view.addSubview(pickerPropertyType)
var pickerRect2 = pickerPropertyProvince.frame
pickerRect2.origin.x = -30
pickerRect.origin.y = 0
pickerPropertyProvince.tag = 2
pickerPropertyProvince.frame = pickerRect2
pickerPropertyProvince.delegate = self
pickerPropertyProvince.dataSource = self
pickerPropertyProvince.isHidden = true
alert2.isModalInPopover = true
alert2.view.addSubview(pickerPropertyProvince)
txtPriceMin.delegate = self
txtPriceMin.keyboardType = .decimalPad
txtPriceMax.delegate = self
txtPriceMax.keyboardType = .decimalPad
txtPropertyBuildingMin.delegate = self
txtPropertyBuildingMin.keyboardType = .decimalPad
txtPropertyBuildingMax.delegate = self
txtPropertyBuildingMax.keyboardType = .decimalPad
txtPropertyAreaMin.delegate = self
txtPropertyAreaMin.keyboardType = .decimalPad
txtPropertyAreaMax.delegate = self
txtPropertyAreaMax.keyboardType = .decimalPad
txtPropertyBedRoom.delegate = self
txtPropertyBedRoom.keyboardType = .decimalPad
txtPropertyBathRoom.delegate = self
txtPropertyBathRoom.keyboardType = .decimalPad
txtPropertyGarage.delegate = self
txtPropertyGarage.keyboardType = .decimalPad
}
func loadProvince(){
let group = DispatchGroup()
group.enter()
DispatchQueue.main.async {
Alamofire.request("http://api.rumahhokie.com/mstr_provinsi?order_by=mstr_provinsi_desc&order_type=asc", method: .get).responseJSON { response in
if let json = response.result.value {
if let res = (json as AnyObject).value(forKey: "mstr_provinsi"){
if let resArray = res as? Array<AnyObject>{
for r in resArray{
self.propertyProvinceData.append(r)
}
}
}
}
self.pickerPropertyProvince.delegate = self;
}
group.leave()
}
group.notify(queue: DispatchQueue.main) {
}
}
@objc func viewPropertySoldAction(){
propertyStatus = 1
radioPropertyStatusSold.image = UIImage(named:"radio-btn-checked.png")
radioPropertyStatusRent.image = UIImage(named:"radio-btn-unchecked.png")
}
@objc func viewPropertyRentAction(){
propertyStatus = 2
radioPropertyStatusRent.image = UIImage(named:"radio-btn-checked.png")
radioPropertyStatusSold.image = UIImage(named:"radio-btn-unchecked.png")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backAction(_ sender: Any) {
if senderVar == 1{
let vc = self.storyboard!.instantiateViewController(withIdentifier: "propertyListView") as? PropertyListController
self.navigationController!.pushViewController(vc!, animated: true)
} else{
let vc = self.storyboard!.instantiateViewController(withIdentifier: "homeView") as? HomeController
self.navigationController!.pushViewController(vc!, animated: true)
}
}
@IBAction func btnPropertyTypeAction(_ sender: Any) {
pickerPropertyType.isHidden = false
self.present(alert, animated: true, completion:{
self.alert.view.superview?.isUserInteractionEnabled = true
self.alert.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.alertControllerBackgroundTapped)))
})
}
@objc func alertControllerBackgroundTapped(){
pickerPropertyType.isHidden = true
self.dismiss(animated: true, completion: nil)
}
@IBAction func btnPropertyProvinceAction(_ sender: Any) {
pickerPropertyProvince.isHidden = false
self.present(alert2, animated: true, completion:{
self.alert2.view.superview?.isUserInteractionEnabled = true
self.alert2.view.superview?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.alertController2BackgroundTapped)))
})
}
@objc func alertController2BackgroundTapped(){
pickerPropertyProvince.isHidden = true
self.dismiss(animated: true, completion: nil)
}
@IBAction func btnSearchAction(_ sender: Any) {
if let switchViewController = self.storyboard!.instantiateViewController(withIdentifier: "propertyListView") as? PropertyListController{
switchViewController.propertyStatus = self.propertyStatus
switchViewController.propertyType = self.propertyType
switchViewController.propertyProvince = self.propertyProvince
if txtPriceMin.text != ""{
switchViewController.propertyPriceMin = Int(txtPriceMin.text!)!
}
if txtPriceMax.text != ""{
switchViewController.propertyPriceMax = Int(txtPriceMax.text!)!
}
if txtPropertyBuildingMin.text != ""{
switchViewController.propertyBuildingMin = Int(txtPropertyBuildingMin.text!)!
}
if txtPropertyBuildingMax.text != ""{
switchViewController.propertyBuildingMax = Int(txtPropertyBuildingMax.text!)!
}
if txtPropertyAreaMin.text != ""{
switchViewController.propertyAreaMin = Int(txtPropertyAreaMin.text!)!
}
if txtPropertyAreaMax.text != ""{
switchViewController.propertyAreaMax = Int(txtPropertyAreaMax.text!)!
}
if txtPropertyBedRoom.text != ""{
switchViewController.propertyBedRoom = Int(txtPropertyBedRoom.text!)!
}
if txtPropertyBathRoom.text != ""{
switchViewController.propertyBathroom = Int(txtPropertyBathRoom.text!)!
}
if txtPropertyGarage.text != ""{
switchViewController.propertyGarage = Int(txtPropertyGarage.text!)!
}
if txtKeyWord.text != ""{
switchViewController.propertyKeyword = txtKeyWord.text!
}
self.navigationController!.pushViewController(switchViewController, animated: true)
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView.tag == 1{
return propertyTypeData.count
} else{
return propertyProvinceData.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView.tag == 1{
return propertyTypeData[row]
} else{
let dataProvinceObj = propertyProvinceData[row] as AnyObject
let dataProvince = dataProvinceObj.value(forKey: "mstr_provinsi_desc")
return dataProvince as? String
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView.tag == 1{
propertyTypeString = propertyTypeData[row]
btnPropertyType.setTitle(propertyTypeString, for: UIControlState.normal)
pickerPropertyType.isHidden = true
alert.dismiss(animated: true, completion: nil)
if propertyTypeString == "Apartemen"{
propertyType = 1
} else if propertyTypeString == "Rumah"{
propertyType = 2
} else if propertyTypeString == "Tanah"{
propertyType = 6
} else if propertyTypeString == "Komersial"{
propertyType = 10
} else if propertyTypeString == "Properti Baru"{
propertyType = 11
}
} else{
let dataProvinceObj = propertyProvinceData[row] as AnyObject
let dataProvinceString = dataProvinceObj.value(forKey: "mstr_provinsi_desc")
let dataProvinceId = dataProvinceObj.value(forKey: "mstr_provinsi_id")
propertyProvinceString = dataProvinceString as! String
propertyProvince = dataProvinceId as! Int
btnPropertyProvince.setTitle(propertyProvinceString, for: UIControlState.normal)
pickerPropertyProvince.isHidden = true
alert2.dismiss(animated: true, completion: nil)
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField.tag != 200 {
let aSet = NSCharacterSet(charactersIn:"0123456789").inverted
let compSepByCharInSet = string.components(separatedBy: aSet)
let numberFiltered = compSepByCharInSet.joined(separator: "")
return string == numberFiltered
} else{
return true
}
}
@objc func doneButtonTappedForMyNumericTextField() {
txtPriceMin.resignFirstResponder()
txtPriceMax.resignFirstResponder()
txtPropertyBuildingMin.resignFirstResponder()
txtPropertyBuildingMax.resignFirstResponder()
txtPropertyAreaMin.resignFirstResponder()
txtPropertyAreaMax.resignFirstResponder()
txtPropertyBedRoom.resignFirstResponder()
txtPropertyBathRoom.resignFirstResponder()
txtPropertyGarage.resignFirstResponder()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
}
extension UITextField {
func addDoneCancelToolbar(onDone: (target: Any, action: Selector)? = nil, onCancel: (target: Any, action: Selector)? = nil) {
let onCancel = onCancel ?? (target: self, action: #selector(cancelButtonTapped))
let onDone = onDone ?? (target: self, action: #selector(doneButtonTapped))
let toolbar: UIToolbar = UIToolbar()
toolbar.barStyle = .default
toolbar.items = [
UIBarButtonItem(title: "Cancel", style: .plain, target: onCancel.target, action: onCancel.action),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil),
UIBarButtonItem(title: "Done", style: .done, target: onDone.target, action: onDone.action)
]
toolbar.sizeToFit()
self.inputAccessoryView = toolbar
}
// Default actions:
@objc func doneButtonTapped() { self.resignFirstResponder() }
@objc func cancelButtonTapped() { self.resignFirstResponder() }
}
|
//
// BusinessesViewController.swift
// Yelp
//
// Created by Timothy Lee on 4/23/15.
// Copyright (c) 2015 Timothy Lee. All rights reserved.
//
import UIKit
import MBProgressHUD
class BusinessesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UIScrollViewDelegate {
@IBOutlet weak var tableView: UITableView!
var businesses: [Business] = []
let searchBar = UISearchBar()
var isMoreDataLoading = false
var dataLimit = 20;
var defaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
configureSearchBar()
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
MBProgressHUD.showAdded(to: self.view, animated: true)
if defaults.object(forKey: "searchText") != nil {
searchWith(term: defaults.object(forKey: "searchText") as! String, offset: 0)
} else {
searchWith(term: "Asian", offset:0)
defaults.set("Asian", forKey: "searchText")
}
/* Example of Yelp search with more search options specified
Business.searchWithTerm("Restaurants", sort: .Distance, categories: ["asianfusion", "burgers"], deals: true) { (businesses: [Business]!, error: NSError!) -> Void in
self.businesses = businesses
for business in businesses {
print(business.name!)
print(business.address!)
}
}
*/
}
func searchWith(term: String, offset:Int) {
Business.searchWithTerm(term: term, offset:offset, completion: { (businesses: [Business]?, error: Error?) -> Void in
if offset == 0 {
print("offset is 0")
self.businesses = businesses!
} else {
self.businesses = self.businesses + businesses!
}
self.isMoreDataLoading = false
self.tableView.reloadData()
if let businesses = businesses {
for business in businesses {
print(business.name!)
print(business.address!)
}
}
}
)
Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(hideLoadingView), userInfo: nil, repeats: false)
}
func hideLoadingView() {
MBProgressHUD.hide(for: self.view, animated: true)
}
func configureSearchBar() {
searchBar.delegate = self
searchBar.placeholder = "Search for a restaurant or cuisine"
searchBar.showsCancelButton = false
self.navigationItem.titleView = searchBar
self.navigationController?.navigationBar.barTintColor = UIColor.red
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
self.searchBar.showsCancelButton = false
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
self.searchBar.showsCancelButton = false
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.showsCancelButton = false
searchBar.text = ""
searchBar.resignFirstResponder()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
print(searchBar.text)
if (searchBar.text != nil && searchBar.text! != "") {
if searchBar.text! != defaults.object(forKey: "searchText") as? String {
defaults.set(searchBar.text!, forKey: "searchText")
searchWith(term: defaults.object(forKey: "searchText") as! String, offset:0)
}
}
searchBar.resignFirstResponder()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (!isMoreDataLoading) {
let scrollViewContentHeight = tableView.contentSize.height
let scrollOffsetThreshold = scrollViewContentHeight - tableView.bounds.size.height
if(scrollView.contentOffset.y > scrollOffsetThreshold && tableView.isDragging) {
MBProgressHUD.showAdded(to: self.view, animated: true)
searchWith(term: defaults.object(forKey: "searchText") as! String, offset: self.businesses.count)
isMoreDataLoading = true
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return businesses.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BusinessCell", for: indexPath) as! BusinessCell
cell.business = businesses[indexPath.row]
return cell
}
// 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.
searchBar.resignFirstResponder()
if (segue.identifier == "map") {
let destinationViewController = segue.destination as! MapViewController
destinationViewController.businessArray = self.businesses
}
if (segue.identifier == "detail") {
let cell = sender as! BusinessCell
let destinationVC = segue.destination as! DetailViewController
destinationVC.name = cell.nameLabel.text
destinationVC.ratingImage = cell.ratingImageView.image
destinationVC.image = cell.thumbImageView.image
destinationVC.address = cell.addressLabel.text
}
}
}
|
//
// AppDelegate.swift
// iXploreNew
//
// Created by Ryan Davey on 6/8/16.
// Copyright © 2016 Ryan Davey. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, MKMapViewDelegate,CLLocationManagerDelegate {
var window: UIWindow?
var location: CLLocation!
var mainNavigationController: UINavigationController?
var locationManager: CLLocationManager?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
locationManager = CLLocationManager()
locationManager?.requestWhenInUseAuthorization()
locationManager!.delegate = self
self.locationManager!.desiredAccuracy = kCLLocationAccuracyBest
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let mainViewController = MainViewController(nibName: "MainViewController", bundle:nil)
mainNavigationController = UINavigationController(rootViewController: mainViewController)
self.window?.rootViewController = self.mainNavigationController
self.window?.makeKeyAndVisible()
self.mainNavigationController?.navigationBarHidden = true
return true
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
location = locations.last! as CLLocation
// let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
//
// let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))
//
// self.mapView.setRegion(region, animated: true)
print(location)
PlacesController.sharedInstance.addPlace(location.coordinate.latitude, longitude: location.coordinate.longitude, title: "Current Location", description: "")
locationManager!.stopUpdatingLocation()
}
func locationManager(manager:CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .NotDetermined:
locationManager!.requestAlwaysAuthorization()
break
case .AuthorizedWhenInUse:
locationManager!.startUpdatingLocation()
break
case .AuthorizedAlways:
locationManager!.startUpdatingLocation()
break
case .Restricted:
// restricted by e.g. parental controls. User can't enable Location Services
break
case .Denied:
// user denied your app access to Location Services, but can grant access from Settings.app
break
default:
break
}
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
//
// SecondViewController.swift
// ProyectoFinal
//
// Created by Alumno on 11/22/20.
// Copyright © 2020 Alumno. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var selectedPlayer: Player?
var players: [Player] = []
let reuseId = "playerCell"
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return players.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseId) as! MVPPlayerTableViewCell
let player = players[indexPath.row]
cell.lblRank.text = "\(player.mvpRank!)"
cell.imgTeam.image = UIImage(named: player.team!)
cell.lblName.text = player.name
cell.lblPoints.text = "\(player.mvpPoints!)"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedPlayer = players[indexPath.row]
performSegue(withIdentifier: "playerDetailsSegue", sender: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
players.append(Player(role: "bot", name: "Aiming", team: "kt", mvpPoints: 1600, mvpRank: 1, img: "aiming", fullName: "Kim \"Aiming\" Ha-ram"))
players.append(Player(role: "mid", name: "Bdd", team: "geng", mvpPoints: 1300, mvpRank: 2, img: "bdd", fullName: "Gwak \"Bdd\" Bo-seong"))
players.append(Player(role: "mid", name: "Showmaker", team: "dwg", mvpPoints: 1100, mvpRank: 3, img: "showmaker", fullName: "Heo \"Showmaker\" Su"))
players.append(Player(role: "top", name: "Canna", team: "t1", mvpPoints: 1000, mvpRank: 4, img: "canna", fullName: "Kim \"Canna\" Chang-dong"))
players.append(Player(role: "jg", name: "Canyon", team: "dwg", mvpPoints: 1000, mvpRank: 4, img: "canyon", fullName: "Kim \"Canyon\" Geon-bu"))
players.append(Player(role: "mid", name: "Chovy", team: "drx", mvpPoints: 1000, mvpRank: 4, img: "chovy", fullName: "Jeong \"Chovy\" Ji-hoon"))
players.append(Player(role: "top", name: "Rich", team: "dyn", mvpPoints: 900, mvpRank: 7, img: "rich", fullName: "Lee \"Rich\" Jae-won"))
players.append(Player(role: "supp", name: "Keria", team: "drx", mvpPoints: 800, mvpRank: 8, img: "keria", fullName: "Ryu \"Keria\" Min-seok"))
players.append(Player(role: "bot", name: "Ruler", team: "geng", mvpPoints: 700, mvpRank: 9, img: "ruler", fullName: "Park \"Ruler\" Jae-hyuk"))
players.append(Player(role: "supp", name: "BeryL", team: "dwg", mvpPoints: 600, mvpRank: 10, img: "beryl", fullName: "Cho \"BeryL\" Geon-hee"))
players.append(Player(role: "supp", name: "Doran", team: "drx", mvpPoints: 600, mvpRank: 10, img: "doran", fullName: "Choi \"Doran\" Hyeon-joon"))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "playerDetailsSegue" {
let destination = segue.destination as! PlayerDetailsViewController
destination.player = selectedPlayer!
}
}
}
|
//
// SlideUpVCPresenterImpl.swift
// FundooApp
//
// Created by admin on 12/06/20.
// Copyright © 2020 admin. All rights reserved.
//
import Foundation
class SlideUpVCPresenterImpl: SlideUpVCDelegate {
let dbManager = RemoteNoteManager.shared
func deleteNote(note: NoteResponse) {
dbManager.addToTrash(note: note)
}
}
|
//
// StorageService.swift
// MarvelCharacters
//
// Created by Alexander Gurzhiev on 07.04.2021.
//
protocol ViewModel {
var id: Int { get }
}
protocol StorageService {
func fetch(_ vmType: ViewModel.Type, by id: Int) -> ViewModel?
func subscribe(_ vmType: ViewModel.Type, handler: @escaping StorageSubscriptionHandler)
func save(models: [Decodable])
func save(model: Decodable)
func deleteAll()
}
typealias StorageSubscriptionHandler = ([ViewModel], [DataUpdate]) -> Void
struct DataUpdate {
let indexes: [Int]
let action: Action
enum Action {
case reload
case delete
case insert
}
}
|
let getProductsJSON =
"""
{
"products": [{
"identifier": 234,
"name": "Buggati Veyron",
"brand": "Buggati",
"original_price": 600000,
"current_price": 100000,
"currency": "EUR",
"image": {
"id": 101,
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/c/c9/Bugatti_Veyron_16.4_%E2%80%93_Frontansicht_%281%29%2C_5._April_2012%2C_D%C3%BCsseldorf.jpg/280px-Bugatti_Veyron_16.4_%E2%80%93_Frontansicht_%281%29%2C_5._April_2012%2C_D%C3%BCsseldorf.jpg"
}
}, {
"identifier": 235,
"name": "Rubber duck",
"brand": "Rubber Paradise",
"original_price": 60,
"current_price": 1,
"currency": "EUR",
"image": {
"id": 102,
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/8e/Rubber_duckies_So_many_ducks.jpg/220px-Rubber_duckies_So_many_ducks.jpg"
}
}, {
"identifier": 237,
"name": "Tasty cucumber",
"brand": "Veggie World",
"original_price": 1,
"current_price": 0.79,
"currency": "CHF",
"image": {
"id": 103,
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/96/ARS_cucumber.jpg/220px-ARS_cucumber.jpg"
}
}, {
"identifier": 239,
"name": "Toilet with flush water tank",
"brand": "Plastic Fantastic",
"original_price": 100,
"current_price": 20,
"currency": "USD",
"image": {
"id": 104,
"url": "https://upload.wikimedia.org/wikipedia/commons/0/06/Toilet_with_flush_water_tank.jpg"
}
}, {
"identifier": 242,
"name": "Ceramic vessel",
"brand": "Siemens",
"original_price": 200,
"current_price": 200,
"currency": "PLN",
"image": {
"id": 107,
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3d/20140707_Radkersburg_-_Large_ceramic_vessel_%28Gombosz_collection%29_-_H4225.jpg/240px-20140707_Radkersburg_-_Large_ceramic_vessel_%28Gombosz_collection%29_-_H4225.jpg"
}
}, {
"identifier": 243,
"name": "Ferrari 550",
"brand": "Ferrari",
"original_price": 1000000,
"current_price": 50000,
"currency": "USD",
"image": {
"id": 108,
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/77/Ferrari_550_maranello_vue_avant.jpg/240px-Ferrari_550_maranello_vue_avant.jpg"
}
}, {
"identifier": 244,
"name": "Kebab",
"brand": "Mustafa",
"original_price": 3,
"current_price": 3,
"currency": "EUR",
"image": {
"id": 109,
"url": "https://upload.wikimedia.org/wikipedia/commons/b/b3/Kebab_Bakhtyari.jpg"
}
}, {
"identifier": 245,
"name": "Grass seeds",
"brand": "Farmer Bob",
"original_price": 10,
"current_price": 5,
"currency": "USD",
"image": {
"id": 789,
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/AllenParkSeeds.JPG/240px-AllenParkSeeds.JPG"
}
},
{
"identifier": 246,
"name": "Hands on mobile",
"brand": "Hands on",
"original_price": 12398,
"current_price": 3829,
"currency": "EUR",
"image": {
"id": 110,
"url": "https://upload.wikimedia.org/wikipedia/commons/2/28/Samsung-Galaxy-S8-Test-Hands-On-7-1024x769.jpg"
}
}, {
"identifier": 247,
"name": "Talking Fish",
"brand": "Fisher-Price",
"original_price": 12,
"current_price": 12,
"currency": "EUR",
"image": {
"id": 111,
"url": "https://upload.wikimedia.org/wikipedia/commons/6/6e/Redear_sunfish_FWS_1.jpg"
}
}, {
"identifier": 248,
"name": "Ice Tea",
"brand": "Tea-Land",
"original_price": 1,
"current_price": 0.79,
"currency": "CHF",
"image": {
"id": 112,
"url": "https://upload.wikimedia.org/wikipedia/commons/a/a0/Ice_Tea_peach.jpg"
}
}, {
"identifier": 250,
"name": "Turbine blade on a steam turbine rotor",
"brand": "Siemens",
"original_price": 100000,
"current_price": 20000,
"currency": "USD",
"image": {
"id": 114,
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d7/Dampfturbine_Laeufer01.jpg/1024px-Dampfturbine_Laeufer01.jpg"
}
}, {
"identifier": 251,
"name": "Spoon",
"brand": "Generic",
"original_price": 2,
"current_price": 1,
"currency": "CHF",
"image": {
"id": 115,
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/92/Soup_Spoon.jpg/240px-Soup_Spoon.jpg"
}
}, {
"identifier": 253,
"name": "Ferrari 780 Booster",
"brand": "Ferrari",
"original_price": 2000000,
"current_price": 80000,
"currency": "USD",
"image": {
"id": 117,
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/f/f0/Ferrari_430_Scuderia_Spider.JPG/1200px-Ferrari_430_Scuderia_Spider.JPG"
}
}, {
"identifier": 254,
"name": "Vegetarian Kebab",
"brand": "Kathy",
"original_price": 3,
"current_price": 3,
"currency": "EUR",
"image": {
"id": 118,
"url": "https://upload.wikimedia.org/wikipedia/commons/6/69/Zwei_Doener_Kebab.JPG"
}
}, {
"identifier": 255,
"name": "Plastic seeds",
"brand": "Farmer Rolf",
"original_price": 10,
"current_price": 5,
"currency": "USD",
"image": {
"id": 119,
"url": "https://upload.wikimedia.org/wikipedia/commons/1/13/Plastic_beach_-_geograph.org.uk_-_798994.jpg"
}
}
]
}
"""
|
//
// ViewController.swift
// SimpleSDR3
//
// Created by Andy Hooper on 2019-12-15.
// Copyright © 2019 Andy Hooper. All rights reserved.
//
import Cocoa
import SimpleSDRLibrary
class ViewController: NSViewController {
@IBOutlet weak var frequencyEntry: NSTextField!
@IBOutlet weak var antennaSelect: NSPopUpButton!
@IBOutlet weak var demodulatorSelect: NSPopUpButton!
@IBOutlet weak var startStopButton: NSButton!
@IBOutlet weak var spectrumView: SpectrumView!
@IBOutlet weak var spectrumMenu: NSMenuItem!
let SPECTRUM_INTERVAL = TimeInterval(0.1/*seconds*/) //TODO configurable
var spectrumTimer:Timer? = nil
var receive:ReceiveSDR?
var windowTitle:String = "SimpleSDR3"
fileprivate func startSDR() {
receive = ReceiveSDR()
windowTitle = receive?.deviceDescription ?? "No tuner description"
receive!.start()
Timer.scheduledTimer(withTimeInterval:5/*seconds*/, repeats:true) { timer in
self.receive?.printTimes()
}
}
fileprivate func startSpectrum(_ spec:SpectrumData?) {
print(#function, spec?.name ?? "nil")
spectrumTimer?.invalidate()
guard let spec = spec else {return}
spectrumTimer = Timer.scheduledTimer(withTimeInterval:SPECTRUM_INTERVAL, repeats:true) { timer in
if spec.numberSummed > 0 {
self.spectrumView.newData(source: spec)
}
}
}
var isTestSignal = false
fileprivate func startTestSignal() {
isTestSignal = true
spectrumMenu.isEnabled = false
let signal = TestSignal()
signal.start()
windowTitle = "Test Signal"
startSpectrum(signal.spectrum)
//Timer.scheduledTimer(withTimeInterval:5/*seconds*/, repeats:true) { timer in
// signal.processTime.printAccumulated(reset:true)
//}
}
override func viewDidLoad() {
super.viewDidLoad()
// https://stackoverflow.com/a/29991529
if ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil {
// don't start receiver if unit testing
return
}
#if true
// TEMPORARY testing settings
antennaSelect.selectItem(at:0/*Antenna A*/)
//frequencyEntry.stringValue = "96300"
//demodulatorSelect.selectItem(at:1/*Wide FM*/)
frequencyEntry.stringValue = "1550"
demodulatorSelect.selectItem(at:2/*AM*/)
startSDR()
#elseif true
startTestSignal()
#endif
}
override func viewDidAppear() {
view.window?.title = windowTitle
super.viewDidAppear()
// transfer UI settings to receiver
antennaAction(antennaSelect)
frequencyAction(frequencyEntry)
demodulatorAction(demodulatorSelect)
spectrumChoiceAction(tunerSpectrumChoice!)
}
override func viewWillDisappear() {
receive?.stopReceive()
receive = nil
}
func setFrequency(_ val: String) {
print("ViewController setFrequency", val)
if let num = NumberFormatter().number(from: val),
let tuner = receive?.tuner {
let tuneHz = num.doubleValue * 1000.0
tuner.tuneHz = tuneHz
receive!.tunerSpectrum.centreHz = tuneHz
spectrumView.rebuildAxis = true
if tuneHz >= 88e6 && tuneHz <= 108e6 {
demodulatorSelect.selectItem(at:1) // Wide FM
demodulatorAction(demodulatorSelect)
}
}
}
@IBAction func frequencyAction(_ sender:NSTextField) {
setFrequency(sender.stringValue)
}
@IBAction func antennaAction(_ sender:NSPopUpButton) {
let val = sender.selectedItem!.title
print("ViewController antennaAction", val)
receive?.tuner.setOption(SDRplay.OptAntenna, val)
}
@IBAction func demodulatorAction(_ sender:NSPopUpButton) {
let val = sender.selectedItem!.title
print("ViewController demodulatorAction", val, sender.selectedItem!.tag)
switch sender.selectedItem!.tag {
case 0:
receive?.setDemodulator(ReceiveSDR.Demodulator.None)
case 1:
receive?.setDemodulator(ReceiveSDR.Demodulator.WFM)
case 2:
receive?.setDemodulator(ReceiveSDR.Demodulator.AM)
case 3:
receive?.setDemodulator(ReceiveSDR.Demodulator.DSBSC)
default:
print("ViewController demodulatorAction invalid tag", val, sender.selectedItem!.tag)
}
}
@IBAction func startStopAction(_ sender:NSButton) {
let val = sender.state
print("ViewController startStopAction", val.rawValue)
sender.title = val == .off ? "Start" : "Stop"
if val == .on {
setFrequency(frequencyEntry!.stringValue)
receive?.startReceive()
} else {
receive?.stopReceive()
}
}
@IBOutlet weak var tunerSpectrumChoice: NSMenuItem!
@IBOutlet weak var demodulatorSpectrumChoice: NSMenuItem!
@IBOutlet weak var offSpectrumChoice: NSMenuItem!
@IBAction func spectrumChoiceAction (_ sender: Any) {
print(#function, sender)
if isTestSignal { return }
// all chocies off
tunerSpectrumChoice.state = .off
demodulatorSpectrumChoice.state = .off
offSpectrumChoice.state = .off
// sender choice on
var spectrum:SpectrumData? = nil
if let menuItem = sender as? NSMenuItem {
menuItem.state = .on
if menuItem == tunerSpectrumChoice {
spectrum = receive?.tunerSpectrum
} else if menuItem == demodulatorSpectrumChoice {
spectrum = receive?.demodSwitch.currentDemod?.spectrum
} else if menuItem == offSpectrumChoice {
spectrum = nil
} else {
print(className, #function, "unexpected menu item", sender)
}
}
// apply selection
startSpectrum(spectrum)
}
}
|
import Foundation
protocol ContactUsInteractable {
func retrieveContacts()
}
|
//
// String+Utils.swift
// mon-bicloo-plus
//
// Created by Cédric Derache on 07/09/2020.
// Copyright © 2020 Cédric Derache. All rights reserved.
//
import Foundation
extension String {
func capitalizingFirstLetter() -> String {
return prefix(1).capitalized + dropFirst()
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}
|
import UIKit
import AVKit
import AVFoundation
import SafariServices
class ViewController: UIViewController {
@IBAction func playVideo(_ sender: UIButton) {
guard let url = URL(string: "https://www.youtube.com/?gl=JP&hl=ja") else {
return
}
let safariViewControllerObject = SFSafariViewController(url: url)
self.present(safariViewControllerObject, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// GitRepository.swift
// Git-macOS
//
// Copyright (c) 2018 Max A. Akhmatov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Cocoa
extension RepositoryError: LocalizedError {
public var errorDescription: String? {
return GitRepositoryErrorFormatter.message(from: self)
}
}
class GitRepositoryErrorFormatter {
class func message(from error: RepositoryError) -> String {
switch error {
case .activeOperationInProgress:
return "[GIT.framework] RE0001: An attempt to perform an operation on repository when active operation already in progress."
case .repositoryNotInitialized:
return "[GIT.framework] RE0002: An attempt to perform an operation on repository which is not initialized yet. Please initialize the repository with remote URL or local path."
case .repositoryHasBeenAlreadyCloned:
return "[GIT.framework] RE0003: An attempt to clone a repository that has been already cloned. Please create a new instance of repository and try to clone it again"
case .repositoryLocalPathNotExists:
return "[GIT.framework] RE0004: Local path for the repository is no longer valid."
case .cloneErrorDirectoryIsNotEmpty(let atPath):
return "[GIT.framework] RE0005: Unable to clone a repository at '\(atPath)'. Path is not empty."
case .cloneError(let message):
return "[GIT.framework] RE0006: An error occurred during cloning a repository. Error says: '\(message)'"
case .unableToCreateTemporaryPath:
return "[GIT.framework] RE0007: Unable to create a temporary directory on the local machine."
case .checkoutError(let message):
return "[GIT.framework] RE0008: An error occurred during checking out branch. Error says: '\(message)'"
case .fetchError(let message):
return "[GIT.framework] RE0009: An error occurred during fetch operation. Error says: '\(message)'"
case .unableToListRemotes(let message):
return "[GIT.framework] RE0010: An error occurred during listing remotes operation. Error says: '\(message)'"
case .unableToRenameRemote(let message):
return "[GIT.framework] RE0011: An error occurred during renaming a remote. Error says: '\(message)'"
case .commitError(let message):
return "[GIT.framework] RE0012: An error occurred during committing changes. Error says: '\(message)'"
case .pushError(let message):
return "[GIT.framework] RE0013: An error occurred during pushing changes. Error says: '\(message)'"
case .unableToChangeRemoteURL(let message):
return "[GIT.framework] RE0014: An error occurred during trying to change and url of a remots. Error says: '\(message)'"
}
}
}
|
//
// Person.swift
// Antino Labs Task
//
// Created by Ajay Choudhary on 23/05/20.
// Copyright © 2020 Ajay Choudhary. All rights reserved.
//
struct Person: Codable {
let profileUrl: String
let name: String
let age: String
let location: String
let details: [String]
let bodyType: String
let userDesire: String
enum CodingKeys: String, CodingKey {
case profileUrl = "url"
case name
case age
case location
case details = "Details"
case bodyType
case userDesire
}
}
|
//
// ViewController.swift
// todoListapp
//
// Created by havisha tiruvuri on 9/16/17.
// Copyright © 2017 havisha tiruvuri. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController {
weak var delegate: todolistdelegate? = nil
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var notesTextField: UITextField!
@IBOutlet weak var dateDatePicker: UIDatePicker!
@IBAction func additem(_ sender: UIButton) {
let myDate = dateDatePicker.date
print(myDate)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let dateString = dateFormatter.string(from: myDate)
print(dateString)
if delegate != nil {
delegate?.add(by: self, title: titleTextField.text!, notes: notesTextField.text!, date: dateString)
dismiss(animated: true, completion: nil )
}
}
}
|
//
// SignUpView.swift
// Twitter
//
// Created by Mark on 19/12/2019.
// Copyright © 2019 Twitter. All rights reserved.
//
import UIKit
protocol SignUpDelegate {
func createAccount(userName: String, firstName: String, lastName: String, emailAddress: String, password: String, passwordVerification: String) -> Void
}
class SignUpView: UIView {
var didTapCreateAccountDelegate: SignUpDelegate?
let userName: UITextField = {
let textField = UITextField()
textField.placeholder = "Username"
textField.translatesAutoresizingMaskIntoConstraints = false
textField.autocorrectionType = .no
textField.autocapitalizationType = .none
textField.backgroundColor = .systemBackground
return textField
}()
let firstName: UITextField = {
let textField = UITextField()
textField.placeholder = "First Name"
textField.translatesAutoresizingMaskIntoConstraints = false
textField.autocorrectionType = .no
textField.autocapitalizationType = .none
textField.backgroundColor = .systemBackground
return textField
}()
let lastName: UITextField = {
let textField = UITextField()
textField.placeholder = "Last Name"
textField.translatesAutoresizingMaskIntoConstraints = false
textField.autocorrectionType = .no
textField.autocapitalizationType = .none
textField.backgroundColor = .systemBackground
return textField
}()
let emailAddress: UITextField = {
let textField = UITextField()
textField.placeholder = "Email Address"
textField.translatesAutoresizingMaskIntoConstraints = false
textField.autocorrectionType = .no
textField.autocapitalizationType = .none
textField.backgroundColor = .systemBackground
return textField
}()
let passwordField: UITextField = {
var textField = UITextField()
textField.placeholder = "Password"
textField.isSecureTextEntry = true
textField.translatesAutoresizingMaskIntoConstraints = false
textField.autocorrectionType = .no
textField.autocapitalizationType = .none
textField.backgroundColor = .systemBackground
return textField
}()
let passwordVerificationField: UITextField = {
let textField = UITextField()
textField.placeholder = "Password Verification"
textField.isSecureTextEntry = true
textField.translatesAutoresizingMaskIntoConstraints = false
textField.autocorrectionType = .no
textField.autocapitalizationType = .none
textField.backgroundColor = .systemBackground
return textField
}()
let createAccountButton: UIButton = {
let button = UIButton()
button.setTitle("Create Account", for: .normal)
button.backgroundColor = UIColor(named: "TwitterBlue")
button.layer.cornerRadius = 8
button.addTarget(self, action: #selector(createNewAccount), for: .touchUpInside)
return button
}()
let signUpStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.spacing = 8
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.backgroundColor = .systemBackground
return stackView
}()
let twitterLogo: UIImageView = {
let image = UIImage(named: "twitter")
let imageView = UIImageView(image: image)
imageView.contentMode = .scaleAspectFill
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
var subViews: [UIView]!
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: Setup Views
fileprivate func setupView() {
backgroundColor = .systemBackground
addSubview(signUpStackView)
addSubview(twitterLogo)
self.subViews = [userName, firstName, lastName, emailAddress, passwordField, passwordVerificationField, createAccountButton]
subViews.forEach { view in
addSubview(view)
signUpStackView.addArrangedSubview(view)
}
setupConstraints()
}
//MARK: Constraint Setup
fileprivate func setupConstraints() {
NSLayoutConstraint.activate([
signUpStackView.centerYAnchor.constraint(equalTo: centerYAnchor),
signUpStackView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 30),
signUpStackView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -30),
twitterLogo.bottomAnchor.constraint(equalTo: signUpStackView.topAnchor, constant: -20),
twitterLogo.centerXAnchor.constraint(equalTo: centerXAnchor),
twitterLogo.heightAnchor.constraint(equalToConstant: 100),
twitterLogo.widthAnchor.constraint(equalToConstant: 122.78),
createAccountButton.heightAnchor.constraint(equalToConstant: 45)
])
}
@objc fileprivate func createNewAccount() {
createAccount(userName: userName.text!, firstName: firstName.text!, lastName: lastName.text!, emailAddress: emailAddress.text!, password: passwordField.text!, passwordVerification: passwordVerificationField.text!)
}
}
//MARK: Delegate Method
extension SignUpView: SignUpDelegate {
func createAccount(userName: String, firstName: String, lastName: String, emailAddress: String, password: String, passwordVerification: String) {
didTapCreateAccountDelegate?.createAccount(userName: userName, firstName: firstName, lastName: lastName, emailAddress: emailAddress, password: password, passwordVerification: passwordVerification)
}
}
|
//
// CPU.swift
// 6502
//
// Created by Michał Kałużny on 15/11/2016.
//
//
import Foundation
public class CPU {
static let nmiVector: UInt16 = 0xFFFA
static let resetVector: UInt16 = 0xFFFC
static let interruptVector: UInt16 = 0xFFFE
enum Error: Swift.Error {
case unimplementedInstruction(instruction: Instruction)
}
enum Register {
case X
case Y
}
//MARK: Registers
public var PC: UInt16 = 0
var A: UInt8 = 0
var X: UInt8 = 0
var Y: UInt8 = 0
var SP: UInt8 = 0
var Status: Flags = []
let bus: Bus
let breakpoints: [UInt16] = [0x378A]
public init(bus: Bus) {
self.bus = bus
}
public func reset() throws {
PC = try bus.read(from: CPU.resetVector)
A = 0
X = 0
Y = 0
SP = 0xFF
Status = [.break, .interrupt, .always]
}
public func step() throws {
if breakpoints.contains(PC) {
print("Breakpoint!")
}
print(self)
let instruction = try fetch()
print(instruction)
try execute(instruction: instruction)
print(self)
print("=============================")
}
public func run() throws {
while true {
try step()
}
}
private func fetch() throws -> Instruction {
return try Instruction(from: bus, PC: PC)
}
subscript(register: Register) -> UInt8 {
switch register {
case .X:
return X
case .Y:
return Y
}
}
}
extension CPU: CustomStringConvertible {
public var description: String {
return "PC: \(PC.hex) SP: \(SP.hex) A: \(A.hex) X: \(X.hex) Y: \(Y.hex) \nFlags: \(Status.rawValue.bin)"
}
}
extension FixedWidthInteger {
public var hex: String {
return String(self, radix: 16, uppercase: true)
}
var bin: String {
return String(self, radix: 2, uppercase: true)
}
}
|
//
// UnoViewController.swift
// RisingCamp_Week2_Lfiecycle
//
// Created by 김우성 on 2021/09/11.
//
import UIKit
class UnoViewController: UIViewController {
@IBOutlet weak var label: UILabel!
override func loadView() {
super.loadView()
print(#function)
}
override func viewDidLoad() {
super.viewDidLoad()
print(#function)
setupLayout()
}
@IBAction func buttonDidTap(_ sender: UIButton) {
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print(#function)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print(#function)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print(#function)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
print(#function)
}
func setupLayout() {
}
}
|
//
// FavoritesTableViewController.swift
// moviesChallenge
//
// Created by Jacqueline Minneman on 1/3/17.
// Copyright © 2017 Jacqueline Schweiger. All rights reserved.
//
import Foundation
import UIKit
import CoreData
class FavoritesTableViewController: UITableViewController {
//TODO: segue row to detail view
var store = MoviesDataStore.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
store.fetchData()
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return store.favoriteMovies.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "basicCell", for: indexPath)
let movie = store.favoriteMovies[indexPath.row]
cell.textLabel?.text = movie.title
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
store.deleteData(indexPath: indexPath.row)
}
tableView.reloadData()
}
}
|
//
// ViewController.swift
// hustle-mode
//
// Created by Lebo on 2020/03/10.
// Copyright © 2020 Lebo. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
// connecting ui labels with code
@IBOutlet weak var DarkBlueBG: UIImageView!
@IBOutlet weak var PowerBtn: UIButton!
@IBOutlet weak var Cloudholder: UIView!
@IBOutlet weak var Rocket: UIImageView!
@IBOutlet weak var hustlelb: UILabel!
@IBOutlet weak var Onlb: UILabel!
var player: AVAudioPlayer!
// app entry point
override func viewDidLoad() {
super.viewDidLoad()
}
// power button when pressed
@IBAction func PowerButtonPressed(_ sender: Any) {
Cloudholder.isHidden = false
DarkBlueBG.isHidden = true
PowerBtn.isHidden = true
UIView.animate(withDuration: 2.3, animations: {
self.Rocket.frame = CGRect(x: 0, y: 20, width: 586, height:1194)
})
{ (finished) in
self.hustlelb.isHidden = true
self.Onlb.isHidden = false
}
if let path = Bundle.main.path(forResource: "hustle-on", ofType: "wav") {
let url = URL(fileURLWithPath: path)
do {
player = try AVAudioPlayer(contentsOf: url)
player.play()
} catch let error as NSError {
print (error.description)
}
}
}
}
|
//
// AppError.swift
// Carousel
//
// Created by Andrey on 05.05.17.
// Copyright © 2017 Quest. All rights reserved.
//
import Foundation
enum AppErrorCode : Int {
// app-error-description-XXX will be used as localizable identificators
case AppErrorInternalError = 001
case AppErrorEmptyJSON = 100
case AppErrorInvalidJSON = 101
case AppErrorNeedToCreateNewSession = 102
case AppErrorDuplicatedItemsInFeedList = 103
case AppErrorFeedListQueryInProgress = 104
case AppErrorInvalidEventObject = 105
case AppErrorGetProgress = 106
case AppErrorCoreDataFetch = 200
case AppErrorAuthorizationInputData = 300
case AppErrorAuthorizationCanceled = 301
case AppErrorAuthorizationTwitterNilSession = 302
case AppErrorNoInputData = 400
case AppErrorLocationServiceDenied = 500
case AppErrorLocationServiceNoPermission = 501
case AppErrorLocationServiceAuthFailed = 502
case AppErrorLocationTrackingBadSignal = 503
case AppErrorLocationRegionTrackingUnaviable = 504
case AppErrorLocationUserLocationUnknown = 505
case AppErrorLocationCoordinatesInvalid = 506
case AppErrorLocationUnableToRoute = 507
case AppErrorRevealBalanceOverdraft = 508
case AppErrorLocationNoRoute = 509
case AppErrorInvalidNavigationStack = 900
}
class AppError: BaseError {
static let kErrorDomain = "appError"
static let kLocalizationPrefix = "app-error"
static let kPrettyString = "App Error"
static func errorWithCode(code: AppErrorCode) -> AppError {
return AppError(domain: kErrorDomain, code: code.rawValue,
localizationPrefix: kLocalizationPrefix, prettyString: kPrettyString)
}
static func errorWithCode(code: AppErrorCode, customDescription: String) -> AppError {
return AppError(domain: kErrorDomain, code: code.rawValue,
localizationPrefix: kLocalizationPrefix, prettyString: kPrettyString, customDescription: customDescription)
}
static func defaultErrorDescriptionKey(code: AppErrorCode) -> String {
return "\(kLocalizationPrefix)-description-\(code.rawValue)"
}
}
|
//
// MarvelAPITests.swift
// HeroLibraryTests
//
// Created by Foliveira on 13/09/20.
// Copyright © 2020 filipero.dev. All rights reserved.
//
import XCTest
@testable import HeroLibrary
class MarvelAPITests: XCTestCase {
var marvelAPI: MarvelAPI?
override func setUp() {
super.setUp()
marvelAPI = MarvelAPI()
}
override func tearDown() {
super.tearDown()
marvelAPI = nil
}
func test_valid_call_does_get_characters() {
marvelAPI?.getCharacters(offset: 0, limit: 1, completion: { characters in
XCTAssertNotNil(characters)
})
}
func test_invalid_offset_fails() {
marvelAPI?.getCharacters(offset: -1, limit: 1, completion: { characters in
XCTAssertNil(characters)
})
}
func test_invalid_limit_fails() {
marvelAPI?.getCharacters(offset: 0, limit: -1, completion: { characters in
XCTAssertNil(characters)
})
}
}
|
//
// DatabaseViewModel.swift
// SoTube
//
// Created by .jsber on 18/05/17.
// Copyright © 2017 NV Met Talent. All rights reserved.
//
import Foundation
enum DatabaseError: Error {
case notLoggedIn, notEnoughCoins
var localizedDescription: String {
switch self {
case .notLoggedIn:
return "You are not logged in."
case .notEnoughCoins:
return "You have not enough coins."
}
}
}
struct ErrorAlert {
let title: String
let message: String
let actions: [UIAlertAction]?
}
protocol DatabaseModel {
// Account stuff
func login(withEmail email: String, password: String, onCompletion: ((ErrorAlert?) -> ())?)
func signOut() throws
func createNewAccount(withUserName userName: String, emailAddress: String, password: String, delegate: DatabaseDelegate)
func resetPassword(forEmail email: String, delegate: DatabaseDelegate)
func checkForSongs(onCompletion: @escaping (Bool) -> ())
func getCurrentUserProfile(onCompletion: @escaping (Profile) -> ())
func changeUsername(to: String, onCompletion: @escaping (Error?) -> ())
func change(_ currentPassword: String, with newPassword: String, for email: String, on delegate: userInfoDelegate, onCompletion completionHandler: @escaping (Error?) -> ())
// Store stuff
func updateCoins(with: CoinPurchase, onCompletion: @escaping ()->())
func getCoinHistory(onCompletion completionHandler: @escaping ([CoinPurchase])->())
func getCoins(onCompletion: @escaping (Int)->())
func buy(_ track: Track, withCoins coins: Int, onCompletion: (Error?)->())
// Music stuff
func getTracks(onCompletion completionHandler: @escaping ([Track])->())
func getAlbums(onCompletion completionHandler: @escaping ([Album])->())
func getAlbum(byID id: String, onCompletion completionHandler: @escaping (Album) -> ())
func getArtists(onCompletion completionHandler: @escaping ([Artist])->())
}
protocol DatabaseDelegate {
func showAlert(withTitle title: String, message: String, actions: [UIAlertAction]?)
func dismiss(animated: Bool, completion: (() -> Void)?)
}
class DatabaseViewModel {
var databaseModel: DatabaseModel = Firebase()
var delegate: DatabaseDelegate?
var musicSource = SpotifyModel()
func checkUserHasSongs(onCompletion completionHandler: @escaping (Bool) -> () ) {
databaseModel.checkForSongs(onCompletion: completionHandler)
}
func login(withEmail email: String, password: String, onCompletion completionHandler: ((ErrorAlert?) -> ())? ) {
databaseModel.login(withEmail: email, password: password, onCompletion: completionHandler)
}
func createNewAccount(withUserName userName: String, emailAddress: String, password: String) {
guard let delegate = delegate else {
fatalError("DatabaseDelegate not yet set!")
}
databaseModel.createNewAccount(withUserName: userName, emailAddress: emailAddress, password: password, delegate: delegate)
}
func resetPassword(forEmail email: String) {
guard let delegate = delegate else {
fatalError("DatabaseDelegate not yet set!")
}
databaseModel.resetPassword(forEmail: email, delegate: delegate)
}
func getCurrentUserProfile(onCompletion completionHandler: @escaping (Profile) -> ()) {
databaseModel.getCurrentUserProfile(onCompletion: completionHandler)
}
func changeUsername(to newUsername: String, onCompletion completionHandler: @escaping (Error?) -> ()) {
databaseModel.changeUsername(to: newUsername, onCompletion: completionHandler)
}
func change(_ currentPassword: String, with newPassword: String, for email: String, on delegate: userInfoDelegate, onCompletion completionHandler: @escaping (Error?) -> ()) {
databaseModel.change(currentPassword, with: newPassword, for: email, on: delegate, onCompletion: completionHandler)
}
func signOut(onCompletion completionHandler: () -> ()) {
do {
try databaseModel.signOut()
} catch {
delegate?.showAlert(withTitle: "Problem signing off", message: error.localizedDescription, actions: nil)
return
}
completionHandler()
}
func updateCoins(with coinPurchase: CoinPurchase, onCompletion completionHandler: @escaping ()->()) {
databaseModel.updateCoins(with: coinPurchase, onCompletion: completionHandler)
}
func getCoinHistory(onCompletion completionHandler: @escaping ([CoinPurchase])->()) {
databaseModel.getCoinHistory(onCompletion: completionHandler)
}
func getTracks(onCompletion completionHandler: @escaping ([Track])->()) {
databaseModel.getTracks(onCompletion: completionHandler)
}
func getCoins(onCompletion completionHandler: @escaping (Int)->()) {
databaseModel.getCoins(onCompletion: completionHandler)
}
func buy(_ track: Track, withCoins coins: Int, onCompletion completionHandler: @escaping (Error?)->()) {
// we already checked for enough coins
self.musicSource.getCoverUrl(forArtistID: track.artistId) { [weak self] url in
// print("url: \(url)")
let track = track
track.artistCoverUrl = url
track.dateOfPurchase = Date()
track.priceInCoins = coins
self?.databaseModel.buy(track, withCoins: coins, onCompletion: completionHandler)
}
}
func getAlbums(forArtist artist: Artist, onCompletion completionHandler: @escaping ([Album])->()) {
let albumIds = artist.albumIds
let albumIdsCount = albumIds.count
var albums: [Album] = []
albumIds.forEach {
databaseModel.getAlbum(byID: $0) { album in
// print("getAlbum(byID: \(album)")
// DispatchQueue.main.async {
albums.append(album)
if albums.count >= albumIdsCount {
completionHandler(albums)
}
// }
}
// print($0)
}
}
func getAlbum(byId albumId: String, onCompletion completionHandler: @escaping (Album)->()) {
databaseModel.getAlbum(byID: albumId, onCompletion: completionHandler)
}
func getAlbums(onCompletion completionHandler: @escaping ([Album])->()) {
databaseModel.getAlbums(onCompletion: completionHandler)
}
func getArtists(onCompletion completionHandler: @escaping ([Artist])->()) {
databaseModel.getArtists(onCompletion: completionHandler)
}
}
|
//
// UIGameViewController.swift
// tachistoscope
//
// Created by Giovanni Gorgone on 19/11/2019.
// Copyright © 2019 undesigned. All rights reserved.
//
import UIKit
import Speech
class UIGameViewController: UIViewController,SFSpeechRecognizerDelegate {
let audioEngine = AVAudioEngine()
let speechRecognizer: SFSpeechRecognizer? = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))
let request = SFSpeechAudioBufferRecognitionRequest()
var recognitionTask: SFSpeechRecognitionTask?
var words: Array<String> = [""]
var delayForDisappearing: TimeInterval = TimeInterval(0.3)
@IBOutlet weak var textView: UILabel!
@IBOutlet weak var hiddenButton: UIButton!
@IBOutlet weak var correctView: UIImageView!
@IBOutlet weak var wrongView: UIImageView!
@IBOutlet weak var micView: UIImageView!
var recognisedWord: String = String("")
var expectedWord: String = String("")
var index: Int = 0
var correctAnswers: Int = 0
var wrongAnswers: Int = 0
@IBAction func buttonTapped(_ sender: UIButton) {
if(self.audioEngine.isRunning){
self.micView.layer.removeAllAnimations()
self.micView.alpha=0
self.cancelRecording()
self.hiddenButton.setTitle("Tap and I'll give you a word!", for: .normal)
if(recognisedWord == expectedWord){
self.correctAnswers+=1
self.correctView.alpha = 1.0
UIView.animate(withDuration: 0.5, delay: 0.0, options: [],animations: {
self.correctView.alpha = 0
})
}else{
self.wrongAnswers+=1
self.wrongView.alpha = 1.0
UIView.animate(withDuration: 0.5, delay: 0.0, options: [],animations: {
self.wrongView.alpha = 0
})
}
}else{
if(self.index < self.words.count){
self.textView.alpha = 1.0
self.textView.text = self.words[self.index]
self.expectedWord = self.self.words[self.index]
self.index = (self.index + 1)%words.count
self.hiddenButton.setTitle("Tap after you've read the word", for: .normal)
UIView.animate(withDuration: self.delayForDisappearing, animations: {self.textView.alpha = 0.0})
DispatchQueue.global(qos: .userInitiated).async {
self.startRecord()
}
UIView.animate(withDuration: 0.4, delay: 0.0, options: [.repeat,.autoreverse], animations: {self.micView.alpha=1})
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.correctView.alpha = 0
self.wrongView.alpha = 0
self.micView.alpha = 0
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.words = WordsByComplexity.normalWords
self.index = 0
self.delayForDisappearing = TimeInterval(0.3)
}
func startRecord(){
var resultFinal: String = ""
request.requiresOnDeviceRecognition = true
let node = audioEngine.inputNode
let recordingFormat = node.outputFormat(forBus: 0)
node.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat){buffer, _ in
self.request.append(buffer)
}
audioEngine.prepare()
do { try audioEngine.start() } catch { print(error)}
recognitionTask = speechRecognizer?.recognitionTask(with: request, resultHandler: { result, error in
if let result = result {
resultFinal = result.bestTranscription.formattedString
self.recognisedWord = resultFinal.lowercased()
}
})
}
func cancelRecording() {
audioEngine.stop()
audioEngine.inputNode.removeTap(onBus: 0)
recognitionTask?.cancel()
}
}
|
//
// AnomaliesListView.swift
// Ananas
//
// Created by Thierry Soulie on 19/11/2020.
//
import SwiftUI
struct AnomaliesListView: View {
var anomaliesList: [Anomalie]
var noAnomalieText: String
var body: some View {
ScrollView {
VStack {
if anomaliesList.count == 0 {
Text(noAnomalieText)
.bold()
.multilineTextAlignment(.center)
.padding(.top, 50)
.padding(.horizontal, 20)
} else {
ForEach(anomaliesList.sorted(), id: \.self.debut) { anomalie in
NavigationLink(
destination: AnomalieDetailsView(anomalie: anomalie),
label: {AnomalieTileView(anomalie: anomalie)}
)
.buttonStyle(PlainButtonStyle())
.font(.title2)
.padding(.vertical,5)
}
}
}
}
}
}
struct AnomaliesListView_Previews: PreviewProvider {
static var previews: some View {
Group {
AnomaliesListView(anomaliesList: [sampleAnomalie1, sampleAnomalie2, sampleAnomalie3], noAnomalieText: "Tout est normal")
AnomaliesListView(anomaliesList: [], noAnomalieText: "Tout est normal")
}
}
}
|
// Playground - noun: a place where people can play
import UIKit
// In0ut parameters let us modify external variables
// The parameter is prefixed with an inout before the parameter declaration on the function. The parameter passed into the function when the function is called is prefixed with a &. Warning: it is not good practice to do this usually.
// ex: func modifyVar(inout myString: String
// ex: modifyVar(&passedparameter)
// Write a function changeName that prints out "Name changed to 'parameter'" and that changes the value of the variable passed to it
func changeName(inout thing: String) {
thing = "Pants"
println("Name changed to \(thing)")
}
var x = "not pants"
println(x)
changeName(&x)
println(x)
// Write a function to find the sum of any two multiples below any max value (make the default 2000)
// call sould be something like this: addMultiples(mult1: 3, mult2: 5). answer should be 233,168
func addMultiples(mult: Int, max: Int = 2000) -> Int {
var total = 0
var x = mult
while x < max {
total += x
x += mult
}
return total
}
//println(addMultiples(3))
//println(addMultiples(5))
//println(addMultiples(15))
func addSetMultiples(mult1: Int, mult2: Int, max: Int=2000) -> Int {
return addMultiples(mult1, max: max) + addMultiples(mult2, max: max)
}
//println(addSetMultiples(3, 5))
// Change calculator: write a function that takes a dollar amount and returns the amount of pennies, nickles, dimes, and quarters needed to return as change (if under $1)
func changeCalculator(money: Float) -> (pennies: Int, nickles: Int, dimes: Int, quarters: Int, dollars: Int) {
var pennies = 0, nickles = 0, dimes = 0, quarters = 0, dollars = 0
var change: Int
// Dollars
dollars = Int(floor(money))
// Convert change to an int
// Need to take the ceiling because subtracting the float
// in dollars can result in a value just under what we want
// (i.e. instead of 35, we get 34.9999)
change = Int( ceil((money - Float(dollars)) * 100 ))
println(change)
// Quarters
quarters = change / 25
change -= 25 * quarters
// Dimes
dimes = change / 10
change -= 10 * dimes
// Nickles
nickles = change / 5
change -= 5 * nickles
// Pennies
pennies = change
return (pennies, nickles, dimes, quarters, dollars)
}
var change = changeCalculator(7.35)
println("Dollars: \(change.dollars), Quarters: \(change.quarters), Dimes: \(change.dimes), Nickles: \(change.nickles), Pennies: \(change.pennies)")
// Variadic parameters are an endless list of parameters that can be passed inside a function. The data inside the function itself is greated as an array. Write a function that takes a parameter describing whether to multiply or add, and a variadic parameter that represents all the numbers. Return either the sum or the multiplicaiton of the integerss.
// Variadic parameters example: addNumbers(numbers: Int...)
func doMath(mode: String, numbers: Int...) -> Int {
var total = 0
// Check mode
if !contains(["add", "multiply"], mode) {
println("Invalid mode. Should be \"add\" or \"multiple\"")
return total
}
// Add
if mode == "add" {
for val in numbers {
total += val
}
}
// Multiply
else {
total = numbers[0]
for val in numbers[1..<numbers.count] {
total *= val
}
}
return total
}
println(doMath("add", 1, 2, 3, 4, 5))
println(doMath("multiply", 1, 2, 3, 4, 5))
println(doMath("subtract", 1, 2, 3, 4, 5))
// Closures are self contained blocks that are anonymously defined (similar to blocks in c)
// Functions are a type of named closure
// Closures can be passed around as variables
// A great use for closures is the ability to increment variables/constants. We can return a contained function that returns another value.
// ex: makeIncrements(incrementAmount: Int) -> () -> int
// Now we can do let myVal = makeIncrements(20). Everytime we run myVal() the return value will increment by the incrementAmount.
// More info on closures: http://fuckingswiftblocksyntax.com/ and https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html
// Write a function similar to the one above that gives us the option to either multiply or add, asks us for a base value, and returns a new value everytime we execute the constant/variable
func makeIncrements(incrementAmount: Int) -> () -> Int {
var myVal = 0
func increment() -> Int {
myVal += incrementAmount
return myVal
}
return increment
}
let myVal = makeIncrements(20)
myVal()
myVal()
func addOrMultiply(mode: String, base: Int) -> Int -> Int {
// Check mode
if !contains(["add", "multiply"], mode) {
println("Invalid mode. Should be \"add\" or \"multiple\". You get a lame function.")
func doMath(Int) -> Int {
return 0
}
return doMath
}
var total = base
// Define Add function
if mode == "add" {
func doAddition(val: Int) -> Int {
total += val
return total
}
return doAddition
}
// Define Multiple Function
else {
func doMultiplication(val: Int) -> Int {
total *= val
return total
}
return doMultiplication
}
}
let myAdd = addOrMultiply("add", 1)
myAdd(4)
myAdd(7)
let myMultiply = addOrMultiply("multiply", 3)
myMultiply(5)
myMultiply(3)
let myLame = addOrMultiply("not add", 7)
myLame(7)
myLame(32)
// The map function is an example of a closure. Use the map function to take an array of names and change the value of each name to "name has been updated".
func updateChipmunks(inout chipmunks: Array<String>) {
chipmunks = chipmunks.map( {(chipmunk: String) -> String in "\(chipmunk) has been updated)"} )
}
var chipmunks = ["Alvin", "Simon", "Theodore"]
updateChipmunks(&chipmunks)
println(chipmunks)
// Recursion happens when a funciton calls itself from within itself
// Re-write the fibonacci sequence function to use recursion
func nextFib(val1: Int, val2: Int, place: Int) -> Int {
let newVal = val1 + val2
if place == 1 {
return newVal
}
return nextFib(val2, newVal, place-1)
}
func findFibonacci(place: Int) -> Int {
// Check to make sure the input makes sense
if place < 1 {
println("You fail")
return 37
}
// Already know the values for places 1 and 2
else if place == 1 {
return 0
}
else if place == 2 {
return 1
}
return nextFib(0,1,place-2)
}
findFibonacci(4)
findFibonacci(9) |
//
// File.swift
// Basics
//
// Created by Venkatnarayansetty, Badarinath on 11/11/19.
// Copyright © 2019 Badarinath Venkatnarayansetty. All rights reserved.
//
import Foundation
import SwiftUI
import Combine
struct CombineEssentialsView: View {
@State private var createAccountButtonDisabled : Bool = false
@State private var buttonBackGround:Color = Color.gray
//States need to be handled via model
@ObservedObject var toggleModel = ToggleModel()
@State var cancellable: AnyCancellable?
var body: some View {
NavigationView {
VStack(spacing: 20) {
Toggle(isOn: self.$toggleModel.readTask) {
Text("Read Manual").font(.system(size: 16, weight: Font.Weight.bold))
}.padding(.horizontal , 10).padding(.top, 10)
Toggle(isOn: self.$toggleModel.practiceTask) {
Text("Practiced in Simulator").font(.system(size: 16, weight: Font.Weight.bold))
}.padding(.horizontal , 10).padding(.top, 10)
Toggle(isOn: self.$toggleModel.teacherApproved) {
Text("Teacher Approved").font(.system(size: 16, weight: Font.Weight.bold))
}.padding(.horizontal , 10).padding(.top, 10)
Button(action: {}) {
Text("Create Account")
.foregroundColor(Color.white)
}.padding()
.background(RoundedRectangle(cornerRadius: 20).foregroundColor(buttonBackGround))
.disabled(!self.$createAccountButtonDisabled.wrappedValue)
.onReceive(self.toggleModel.validatedTasks) { (publisher) in
self.createAccountButtonDisabled = (publisher.0 && publisher.1 && publisher.2)
self.buttonBackGround = (publisher.0 && publisher.1 && publisher.2) ? Color.blue : Color.gray
}
Spacer()
}.navigationBarTitle("Terms & Conditions")
}
}
}
class ToggleModel: ObservableObject {
@Published var readTask: Bool = false
@Published var practiceTask: Bool = false
@Published var teacherApproved: Bool = false
var validateRead: AnyPublisher<Bool, Never> {
return $readTask
.debounce(for: 0.1, scheduler: RunLoop.main)
.eraseToAnyPublisher()
}
var validatePractice: AnyPublisher<Bool, Never> {
return $practiceTask
.debounce(for: 0.1, scheduler: RunLoop.main)
.eraseToAnyPublisher()
}
var validateTeacherApproved: AnyPublisher<Bool, Never> {
return $teacherApproved
.debounce(for: 0.1, scheduler: RunLoop.main)
.eraseToAnyPublisher()
}
var validatedTasks: AnyPublisher<(Bool,Bool,Bool), Never> {
return Publishers.CombineLatest3(validateRead,validatePractice,validateTeacherApproved)
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
}
}
|
//
// SerieDetailsHeaderView.swift
// jobsitychallenge
//
// Created by Rafael Freitas on 17/01/21.
//
import UIKit
class SerieDetailsHeaderView: UIView {
// MARK: - UI Elements
lazy var serieNameLabel: UILabel = {
let label = UILabel()
label.font = .boldSystemFont(ofSize: Constants.xlargeFont)
label.numberOfLines = 0
return label
}()
lazy var posterImage: UIImageView = {
let image = UIImageView()
image.contentMode = .scaleAspectFit
return image
}()
lazy var airDateAndTimeLabel: UILabel = {
let label = UILabel()
label.font = .systemFont(ofSize: Constants.mediumFont, weight: .light)
label.numberOfLines = 0
return label
}()
lazy var genresLabel: UILabel = {
let label = UILabel()
label.font = .systemFont(ofSize: Constants.mediumFont, weight: .light)
label.numberOfLines = 0
return label
}()
lazy var summaryLabel: UILabel = {
let label = UILabel()
label.font = .systemFont(ofSize: Constants.mediumFont)
label.textAlignment = .justified
label.numberOfLines = 0
return label
}()
// MARK: - Stacks
lazy var mainStack: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [
serieNameLabel,
genresLabel,
posterImage,
summaryLabel,
airDateAndTimeLabel
])
stackView.axis = .vertical
stackView.spacing = Constants.stackSpacing / 2
stackView.alignment = .center
return stackView
}()
// MARK: - Init
override init(frame: CGRect) {
super.init(frame: frame)
config()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Setup
private func config() {
viewSetup()
setContraints()
}
private func viewSetup() {
self.addSubview(mainStack)
}
private func setContraints() {
mainStack.snp.makeConstraints {
$0.edges.equalToSuperview().inset(Constants.baseInset)
}
}
// MARK: - Methods
func setViewWith(serie: SerieDetailsEntity) {
serieNameLabel.text = serie.name
genresLabel.text = formatGenresStringArray(serie.genres)
self.setImage(image: posterImage, with: serie.image?.medium ?? "")
summaryLabel.text = serie.summary?.html2String ?? ""
airDateAndTimeLabel.text = formatSerieSchedule(schedule: serie.schedule)
}
private func formatGenresStringArray(_ genres: [String]) -> String {
var string = ""
genres.forEach {
string = "\($0), \(string)"
}
return string
}
private func formatSerieSchedule(schedule: SerieDetailsEntity.ShowSchedule? = nil) -> String {
var string = ""
if let schedule = schedule {
string = "At \(string)\(schedule.time)\non "
schedule.days.forEach {
string = "\(string) \($0),"
}
} else {
string = "No dates and time available"
}
return string
}
}
|
//
// AppDelegate.swift
// WatchItLater
//
// Created by Weiran Zhang on 25/12/2016.
// Copyright © 2017 Weiran Zhang. All rights reserved.
//
import UIKit
import AVFoundation
import SwiftyUserDefaults
import SwinjectStoryboard
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
_ = Database.shared
SwinjectStoryboard.configure()
try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback)
return true
}
func applicationDidBecomeActive(_ application: UIApplication) {
NotificationCenter.default.post(name: NSNotification.Name.didBecomeActive, object: nil)
}
}
|
//
// configure.swift
// App
//
// Created by Shun Usami on 2019/10/02.
// Copyright © 2019 Yenom Inc. All rights reserved.
//
import Foundation
import AppCore
internal func confitgure(_ environment: EnvironmentProvider) {
logger = Logger(label: environment.appInfo.bundleIdentifier)
switch environment.appInfo.buildConfiguration {
case .debug:
logger.logLevel = .debug
case .release:
logger.logLevel = .critical
}
}
|
//
// GameModel.swift
// final
//
// Created by James on 2018/12/2.
// Copyright © 2018年 James. All rights reserved.
//
import UIKit
import Foundation
class GameModel: NSObject {
var useremail : String?
var gamename: String?
var userid : String?
var rank : String?
var id : String?
override init() {
}
init(useremail:String, gamename:String, userid:String, rank : String, id :String) {
self.useremail = useremail
self.gamename = gamename
self.userid = userid
self.rank = rank
self.id = id
}
override var description: String{
return "Useremail:\(useremail),Gamename:\(gamename),Userid:\(userid),Rank:\(rank),Id:\(id)"
}
}
|
//
// Constants.swift
// DodgeThePenguin
//
// Created by admin on 4/17/17.
// Copyright © 2017 JPDaines. All rights reserved.
//
import UIKit
extension ViewController{
internal struct Constants {
static let initialPenguinCount = 20
static let shipBoundaryName = "Ship"
static let shipSizeToMinBoundsEdgeRatio: CGFloat = 1/5
static let PenguinMagnitude: CGFloat = 6 // as a multiple of view.bounds.size
static let normalizedDistanceOfShipFromEdge: CGFloat = 0.2
static let burnAcceleration: CGFloat = 0.07 // points/s/s
struct Shield {
static let duration: TimeInterval = 1.0 // how long shield stays up
static let updateInterval: TimeInterval = 0.2 // how often we update shield level
static let regenerationRate: Double = 5 // per second
static let activationCost: Double = 15 // per activation
static var regenerationPerUpdate: Double
{ return Constants.Shield.regenerationRate * Constants.Shield.updateInterval }
static var activationCostPerUpdate: Double
{ return Constants.Shield.activationCost / (Constants.Shield.duration/Constants.Shield.updateInterval) }
}
static let defaultShipDirection: [UIInterfaceOrientation:CGFloat] = [
.portrait : CGFloat.up,
.portraitUpsideDown : CGFloat.down,
.landscapeLeft : CGFloat.right,
.landscapeRight : CGFloat.left
]
static let normalizedAsteroidFieldCenter: [UIInterfaceOrientation:CGPoint] = [
.portrait : CGPoint(x: 0.5, y: 1.0-Constants.normalizedDistanceOfShipFromEdge),
.portraitUpsideDown : CGPoint(x: 0.5, y: Constants.normalizedDistanceOfShipFromEdge),
.landscapeLeft : CGPoint(x: Constants.normalizedDistanceOfShipFromEdge, y: 0.5),
.landscapeRight : CGPoint(x: 1.0-Constants.normalizedDistanceOfShipFromEdge, y: 0.5),
.unknown : CGPoint(x: 0.5, y: 0.5)
]
}
}
|
//
// LogViewController.swift
// Lose It!
//
//
//
import UIKit
class LogViewController: UIViewController{
@IBOutlet weak var breakfastLabel: UILabel!
@IBOutlet weak var lunchLabel: UILabel!
@IBOutlet weak var totalCaloriesLabel: UILabel!
@IBOutlet weak var breakfastButton: UIButton!
@IBOutlet weak var lunchButton: UIButton!
@IBOutlet weak var dinnerLabel: UILabel!
@IBOutlet weak var dinnerButton: UIButton!
var bfCal : Int = 0
var dCal : Int = 0
var lCal : Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let navController = segue.destination as! UINavigationController
let destController = navController.topViewController as! SearchViewController
destController.delagate = self
if segue.identifier == "bfToSearch"{
destController.mealType = .breakfast
}
if segue.identifier == "lunchToSearch"{
destController.mealType = .lunch
}
if segue.identifier == "dinnerToSearch"{
destController.mealType = .dinner
}
}
}
extension LogViewController: DataDelegate{
func updateLogCalories(str: String?, mealType: MealType) {
if mealType == MealType.breakfast{
breakfastLabel.text = str
bfCal = Int(str!)!
}else if mealType == MealType.lunch{
lunchLabel.text = str
lCal = Int(str!)!
}else if mealType == MealType.dinner{
dinnerLabel.text = str
dCal = Int(str!)!
}
let tCal = bfCal + lCal + dCal
totalCaloriesLabel.text = String(tCal)
var info = [String: String]()
info["total"] = totalCaloriesLabel.text
NotificationCenter.default.post(name: Notification.Name(rawValue: notificationKey), object: self, userInfo: info)
}
}
|
import CoreLocation
import Foundation
let locationManager = CLLocationManager()
public class Location {
public init () {}
public func coordinate() -> (latitude: Float?, longitude: Float?) {
guard let lat = locationManager.location?.coordinate.latitude,
let long = locationManager.location?.coordinate.longitude else {
return (latitude: nil, longitude: nil)
}
let latitude = lat
let longitude = long
return (latitude: Float(latitude), longitude: Float(longitude))
}
public func getCity() -> String {
var returnCity: String = "N/A"
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: (locationManager.location?.coordinate.latitude)!, longitude: (locationManager.location?.coordinate.longitude)!)
geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
// Place details
var placeMark: CLPlacemark!
placeMark = placemarks?[0]
// City
if let city = placeMark.addressDictionary!["City"] as? String {
returnCity = city
}
})
return returnCity
}
public func getCountry() -> String {
var returnCountry: String = "N/A"
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: (locationManager.location?.coordinate.latitude)!, longitude: (locationManager.location?.coordinate.longitude)!)
geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
// Place details
var placeMark: CLPlacemark!
placeMark = placemarks?[0]
// City
if let country = placeMark.addressDictionary!["Country"] as? String {
returnCountry = country
}
})
return returnCountry
}
public func getZip() -> Int {
var returnZip: Int = 0
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: (locationManager.location?.coordinate.latitude)!, longitude: (locationManager.location?.coordinate.longitude)!)
geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
// Place details
var placeMark: CLPlacemark!
placeMark = placemarks?[0]
// City
if let zip = placeMark.addressDictionary!["ZIP"] as? Int {
returnZip = zip
}
})
return returnZip
}
public func getLocationName() -> String {
var returnName: String = "N/A"
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: (locationManager.location?.coordinate.latitude)!, longitude: (locationManager.location?.coordinate.longitude)!)
geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
// Place details
var placeMark: CLPlacemark!
placeMark = placemarks?[0]
// City
if let locationName = placeMark.addressDictionary!["Name"] as? String {
returnName = locationName
}
})
return returnName
}
public func getStreetAddress() -> String {
var returnAddress: String = "N/A"
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: (locationManager.location?.coordinate.latitude)!, longitude: (locationManager.location?.coordinate.longitude)!)
geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
// Place details
var placeMark: CLPlacemark!
placeMark = placemarks?[0]
// City
if let street = placeMark.addressDictionary!["Thoroughfare"] as? String {
returnAddress = street
}
})
return returnAddress
}
}
|
import Foundation
class PCEnvironmentDataStoreProvider : PCEnvironmentRepositoryDataStoreProvider {
class func getDataStore() -> PCEnvironmentDataStore.Type {
return PCEnvironmentDataStoreLocal.self
}
}
|
//
// HomeListView.swift
// SwiftUIPractice
//
// Created by Mac on 2020/4/22.
// Copyright © 2020 灵 Q. All rights reserved.
//
import SwiftUI
/**
@ObservedObject:告诉SwiftUI,这个对象是可以被观察的,里面含有被@Published包装了的属性。@ObservedObject包装的对象,必须遵循ObservableObject协议。也就是说必须是class对象,不能是struct。
@EnvironmentObject:包装的属性是全局的,整个app都可以访问。需要注意的是,不需要给定默认值,由于该属性是整个app都可以访问的,SwiftUI会自动的从环境中取出来
@Environment:是从环境中取出预定义的值,比如获得当前是暗黑模式还是正常模式,屏幕的大小等等。
@Binding:用的比较少,但是也是非常重要的一个包装,声明一个属性是从外部获取的,并且与外部是共享的。相当于外部传过来的时候,不是传递的值。
@GestureState:能够让我们传递手势的状态,虽然使用@State也能实现,但@GestureState能让手势结束后我们回到最初的状态。
*/
/// @Published属性需要遵循ObservableObject协议,Published会自动修改与该属性绑定的界面,@Published包装会自动添加willSet方法监视属性的改变
class HomeListSectionModel: ObservableObject, Identifiable {
let id = UUID()
var title: String = ""
/// 禁止删除
var deleteDisabled = true
/// 禁止移动
var mobileDisabled = true
/// 是否显示row
var rowShow: Bool = true
var rowModels: [HomeListRowModel] = []
init(title: String, rowModels: [HomeListRowModel] = []) {
self.title = title
self.rowModels = rowModels
}
}
/// @Published属性需要遵循ObservableObject协议
class HomeListRowModel: ObservableObject, Identifiable {
let id = UUID()
var title: String = ""
/// 禁止删除
var deleteDisabled = true
/// 禁止移动
var mobileDisabled = true
/// 默认不喜欢
var isLive: Bool = true
init(title: String, deleteDisabled: Bool = true, mobileDisabled: Bool = true, isLive: Bool = true) {
self.title = title
self.deleteDisabled = deleteDisabled
self.mobileDisabled = mobileDisabled
self.isLive = isLive
}
}
class HomeListDate: ObservableObject {
/// 标明为 publish 属性
@Published var sectionDataArr = [HomeListSectionModel](){
didSet {
print(#function, "值改变了")
// 发送改变, 通知视图更新
self.objectWillChange.send()
}
}
init(_ dataArr: [HomeListSectionModel] = []) {
self.sectionDataArr = dataArr
}
}
fileprivate var dataArr = [HomeListSectionModel(title: "这是表头不可删除", rowModels: [HomeListRowModel(title: "Cell 默认不可删除,不可移动")])]
struct HomeListView: View {
/// 一般静态数据, 用 @State, 动态用 @ObservedObject
@ObservedObject var dataObj = HomeListDate(dataArr)
var body: some View {
List {
ForEach(dataObj.sectionDataArr) { sectionModel in
// Text("Hello")
Section(
header: HomeListHeaderView(dataObj: self.dataObj, sectionModel: sectionModel)
// ,footer: HomeListFooterView()
) {
if sectionModel.rowShow {
ForEach(sectionModel.rowModels) { rowModel in
HomeListRowView(dataObj: self.dataObj, rowModel: rowModel)
}
.onDelete { (indexSet) in
print("...执行删除...",indexSet)
sectionModel.rowModels.remove(at: indexSet.first!)
self.dataObj.objectWillChange.send()
}
.onMove { (indexSet, index) in
print("....执行移动....",index)
sectionModel.rowModels.move(fromOffsets: indexSet, toOffset: index)
self.dataObj.objectWillChange.send()
}
}
}
}
}
// .listStyle(GroupedListStyle())
.listStyle(PlainListStyle())
.navigationBarItems(trailing:
HStack {
Button.init("Add Section") {
let model = HomeListSectionModel(title: "Header\(self.dataObj.sectionDataArr.count)")
model.deleteDisabled = false
self.dataObj.sectionDataArr.append(model)
}
EditButton()
.foregroundColor(Color.red)
})
.navigationBarTitle("List")
}
}
/// ListCell
struct HomeListRowView: View {
@ObservedObject var dataObj: HomeListDate
@ObservedObject var rowModel: HomeListRowModel
var body: some View {
VStack(alignment: .leading){
HStack {
Text(rowModel.title)
Spacer()
Image(rowModel.isLive ? "HomeLive" : "HomeUnLive")
.onTapGesture {
self.rowModel.isLive = !self.rowModel.isLive
self.dataObj.objectWillChange.send()
}
}
Text("10:30")
.padding(.top, 5)
}
.padding(.top, 5)
.padding(.bottom, 5)
.deleteDisabled(rowModel.deleteDisabled)
.moveDisabled(rowModel.mobileDisabled)
}
}
/// HeaderView
struct HomeListHeaderView: View {
@ObservedObject var dataObj: HomeListDate
@ObservedObject var sectionModel: HomeListSectionModel
var body: some View {
HStack {
Text(sectionModel.title)
Spacer()
if !sectionModel.deleteDisabled {
Button("Delete Section") {
let index = self.dataObj.sectionDataArr.lastIndex { (model) -> Bool in
if model.id == self.sectionModel.id {
return true
}
return false
}
if let index = index {
self.dataObj.sectionDataArr.remove(at: index)
}
}.foregroundColor(Color.red)
}
Button("Add Cell") {
let model = HomeListRowModel(title: "Cell\(self.sectionModel.rowModels.count)", deleteDisabled: false, mobileDisabled: false, isLive: false)
self.sectionModel.rowModels.append(model)
self.dataObj.objectWillChange.send()
}
Button(sectionModel.rowShow ? "Hide" : "Show") {
self.sectionModel.rowShow = !self.sectionModel.rowShow
self.dataObj.objectWillChange.send()
}
}
}
}
/// FooterView
struct HomeListFooterView: View {
var body: some View {
HStack {
Text("这是尾部")
}
}
}
struct HomeListView_Previews: PreviewProvider {
static var previews: some View {
HomeListView()
}
}
|
//
// ToggableRow.swift
// Oak
//
// Created by Alex Catchpole on 31/01/2021.
//
import SwiftUI
import Combine
import Resolver
struct ToggableRow: View {
var title: String
var key: SettingsKey
var onChangeCallback: ((_ status: Bool) -> Void)?
private var settings: Settings
@State private var isOn: Bool = false
init(title: String, key: SettingsKey, settings: Settings = Resolver.resolve(), onChange: ((_ status: Bool) -> Void)? = nil) {
self.title = title
self.key = key
self.settings = settings
_isOn = State(initialValue: settings.bool(key: key))
self.onChangeCallback = onChange
}
var body: some View {
HStack {
Text(title)
Spacer()
Toggle(isOn: $isOn) {
Text(title)
}
}
.labelsHidden()
.accessibility(identifier: "\(key.rawValue)Switch")
.padding(EdgeInsets(top: 5, leading: 0, bottom: 5, trailing: 0))
.onChange(of: isOn, perform: { value in
settings.set(key: key, value: value)
self.onChangeCallback?(value)
})
}
}
struct ToggableRow_Previews: PreviewProvider {
static var previews: some View {
ToggableRow(title: "Face ID or Touch ID", key: .biometricsEnabled)
}
}
|
//
// User.swift
// App
//
// Created by Daniel Santos on 10/2/17.
//
import Vapor
import FluentProvider
import HTTP
import BCrypt
extension BCrypt.Hash {
static func hash(password: String) throws -> String {
let hash = try BCrypt.Hash.make(message: password)
guard let hashedPassword = String(bytes: hash, encoding: .utf8) else {
throw Abort.badRequest
}
return hashedPassword
}
}
final class User: Model {
let storage = Storage()
var firstName: String
var lastName: String
var username: String
var password: String
var email: String
var dateOfBirth: Date
var summary: String
var location: String
static let firstNameKey = "first_name"
static let lastNameKey = "last_name"
static let usernameKey = "username"
static let passwordKey = "password"
static let emailKey = "email"
static let dateOfBirthKey = "date_of_birth"
static let summaryKey = "summary"
static let locationKey = "location"
required init(firstName: String,
lastName: String,
username: String,
password: String,
email: String,
dateOfBirth: Date,
summary: String,
location: String
) throws {
self.firstName = firstName
self.lastName = lastName
self.username = username
self.password = try BCrypt.Hash.hash(password: password)
self.email = email
self.dateOfBirth = dateOfBirth
self.summary = summary
self.location = location
}
required init(row: Row) throws {
self.firstName = try row.get(User.firstNameKey)
self.lastName = try row.get(User.lastNameKey)
self.username = try row.get(User.usernameKey)
self.password = try row.get(User.passwordKey)
self.email = try row.get(User.emailKey)
self.dateOfBirth = try row.get(User.dateOfBirthKey)
self.summary = try row.get(User.summaryKey)
self.location = try row.get(User.locationKey)
}
func makeRow() throws -> Row {
var row = Row()
try row.set(User.firstNameKey, self.firstName)
try row.set(User.lastNameKey, self.lastName)
try row.set(User.usernameKey, self.username)
try row.set(User.passwordKey, self.password)
try row.set(User.emailKey, self.email)
try row.set(User.dateOfBirthKey, self.dateOfBirth)
try row.set(User.summaryKey, self.summary)
try row.set(User.locationKey, self.location)
return row
}
func update(with json: JSON) throws {
self.firstName = try json.get(User.firstNameKey)
self.lastName = try json.get(User.lastNameKey)
self.username = try json.get(User.usernameKey)
self.password = try BCrypt.Hash.hash(password: try json.get(User.passwordKey))
self.email = try json.get(User.emailKey)
self.dateOfBirth = try json.get(User.dateOfBirthKey)
self.summary = try json.get(User.summaryKey)
self.location = try json.get(User.locationKey)
try self.save()
}
func fullUser() throws -> JSON {
var userData = try self.makeJSON()
try userData.set("skills", self.skills.all())
try userData.set("attachments", self.attachments.all())
try userData.set("educations", self.educations.all())
try userData.set("languages", self.languages.all())
return userData
}
}
// MARK: Relation
extension User {
var skills: Children<User, Skill> {
return children()
}
var languages: Children<User, Language> {
return children()
}
var educations: Children<User, Education> {
return children()
}
var attachments: Children<User, Attachment> {
return children()
}
var portfolio: Children<User, Portfolio> {
return children()
}
}
// MARK: JSON
extension User: JSONConvertible {
convenience init(json: JSON) throws {
try self.init(
firstName: json.get(User.firstNameKey),
lastName: json.get(User.lastNameKey),
username: json.get(User.usernameKey),
password: json.get(User.passwordKey),
email: json.get(User.emailKey),
dateOfBirth: json.get(User.dateOfBirthKey),
summary: json.get(User.summaryKey),
location: json.get(User.locationKey))
}
func makeJSON() throws -> JSON {
var json = JSON()
try json.set(User.idKey, self.id)
try json.set(User.firstNameKey, self.firstName)
try json.set(User.lastNameKey, self.lastName)
try json.set(User.usernameKey, self.username)
try json.set(User.emailKey, self.email)
try json.set(User.dateOfBirthKey, self.dateOfBirth)
try json.set(User.summaryKey, self.summary)
try json.set(User.locationKey, self.location)
return json
}
}
// MARK: HTTP
extension User: ResponseRepresentable { }
// MARK: Fluent Preparation
extension User: Preparation {
static func prepare(_ database: Database) throws {
try database.create(self) { builder in
builder.id()
builder.string(User.firstNameKey)
builder.string(User.lastNameKey)
builder.string(User.usernameKey, unique: true)
builder.string(User.passwordKey)
builder.string(User.emailKey, unique: true)
builder.date(User.dateOfBirthKey)
builder.string(User.summaryKey)
builder.string(User.locationKey)
}
}
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
|
//
// RequestService.swift
// KifuSF
//
// Created by Alexandru Turcanu on 28/07/2018.
// Copyright © 2018 Alexandru Turcanu. All rights reserved.
//
import Foundation
import FirebaseDatabase
struct RequestService {
/**
Creates a donation request for the given donation and creates a user request for the current user
*/
public static func createRequest(for donation: Donation, completion: @escaping (Bool) -> Void) {
let currentUserUid = User.current.uid
let refDonationRequests = Database.database().reference()
.child("donation-requests")
.child(donation.uid)
.child(currentUserUid)
refDonationRequests.updateChildValues(User.current.dictValue) { error, _ in
if let error = error {
print(error)
return completion(false)
}
let refUserRequests = Database.database().reference()
.child("user-requests")
.child(currentUserUid)
.child(donation.uid)
refUserRequests.setValue(donation.dictValue) { error, _ in
if let error = error {
print(error.localizedDescription)
return completion(false)
}
completion(true)
}
}
}
/**
removes the current user, or given userUid, from the given donation in the
donation-requests and user-requests subtrees
- Remark: used when the current user cancels their request from the given donation.
Also, when the given donation clears its requests.
*/
public static func cancelRequest(for donation: Donation, completion: @escaping (Bool) -> Void) {
self.cancelRequest(for: donation, forUserUid: User.current.uid, completion: completion)
}
/**
removes the current user, or given userUid, from the given donation in the
donation-requests and user-requests subtrees
- Remark: used when the current user cancels their request from the given donation.
Also, when the given donation clears its requests.
*/
private static func cancelRequest(
for donation: Donation,
forUserUid userUid: String,
completion: @escaping (Bool) -> Void) {
//remove donation from user-requests
let refUserRequest = Database.database().reference()
.child("user-requests")
.child(userUid)
.child(donation.uid)
refUserRequest.setValue(nil) { error, _ in
guard error == nil else {
print("for user uid \(userUid), there was an error \(error!.localizedDescription)")
completion(false)
return
}
//remove user from donation-requests
let refDonationRequests = Database.database().reference()
.child("donation-requests")
.child(donation.uid)
.child(userUid)
refDonationRequests.setValue(nil) { error, _ in
guard error == nil else {
print("there was an error deleting the user requests in the donation-requests \(donation.uid): \(error!.localizedDescription)") // swiftlint:disable:this line_length
completion(false)
return
}
completion(true)
}
}
}
/**
removes all requests for the given user from the user-requests. Then, removes
the given user from the donation-requests
- Remark: when the given userUid was accepted as a volunteer of a donation
*/
public static func clearRequests(for user: User, completion: @escaping (Bool) -> Void) {
//fetch donations from user-requests from the given uid
self.fetchPendingRequests(for: user) { (donationsToCancel) in
//for each donation, cancel the request
let dg = DispatchGroup() // swiftlint:disable:this identifier_name
var isSuccessful = true
for aDonation in donationsToCancel {
dg.enter()
RequestService.cancelRequest(for: aDonation, forUserUid: user.uid, completion: { (success) in
if success == false {
isSuccessful = false
}
dg.leave()
})
}
dg.notify(queue: DispatchQueue.main, execute: {
completion(isSuccessful)
})
}
}
/**
Removes all requets from the given donation from the donation-request sub tree. Then, removes
the given donation from the user-requests for each user who requested to deliver the donation
- Remark: when a volunteer is selected or when the donation is canceled
*/
public static func clearRequests(for donation: Donation, completion: @escaping (Bool) -> Void) {
/**
fetches all of the users for the given donation and invokes self.cancelRequest
for each user that requested to pick up the donation. This will remove
the given donation from the user's list of donations and the donation's
list of users.
*/
//get all users that have requested to deliever in the donation-requests
let refDonationRequests = Database.database().reference()
.child("donation-requests")
.child(donation.uid)
refDonationRequests.observeSingleEvent(of: .value) { (snapshot) in
guard let snapshotOfUsers = snapshot.children.allObjects as? [DataSnapshot] else {
print("failed to convert snapshot into children of snapshots")
return completion(false)
}
//for each user, remove the given donation from user-requests and donation-requests subtrees
let uidOfRequestedUsers = snapshotOfUsers.map { $0.key }
let dgRemoveRequests = DispatchGroup()
var isSuccessful = true
for aUserUid in uidOfRequestedUsers {
dgRemoveRequests.enter()
self.cancelRequest(for: donation, forUserUid: aUserUid, completion: { (successful) in
if successful == false {
isSuccessful = false
}
dgRemoveRequests.leave()
})
}
dgRemoveRequests.notify(queue: DispatchQueue.main, execute: {
completion(isSuccessful)
})
}
}
/**
Fetch all the users for the given donation
*/
public static func retrieveVolunteers(for donation: Donation, completion: @escaping ([User]) -> Void) {
let ref = Database.database().reference().child("donation-requests").child(donation.uid)
ref.observeSingleEvent(of: .value) { (snapshot) in
guard let volunteersSnapshot = snapshot.children.allObjects as? [DataSnapshot] else {
fatalError("could not decode")
}
let volunteers = volunteersSnapshot.compactMap(User.init)
completion(volunteers)
}
}
/**
Fetch all donations the user given has reqeusted to deliver
*/
public static func fetchPendingRequests(for user: User, completion: @escaping ([Donation]) -> Void) {
let ref = Database.database().reference().child("user-requests").child(user.uid)
ref.observeSingleEvent(of: .value) { (snapshot) in
guard let donationSnapshots = snapshot.children.allObjects as? [DataSnapshot] else {
fatalError("could not decode")
}
let requestingDonations = donationSnapshots.compactMap(Donation.init)
completion(requestingDonations)
}
}
/**
Observe all donations the user has reqeusted to deliver
*/
public static func observePendingRequests(completion: @escaping ([Donation]) -> Void) {
let currentUserUid = User.current.uid
let ref = Database.database().reference().child("user-requests").child(currentUserUid)
ref.observe(.value) { (snapshot) in
guard let donationSnapshots = snapshot.children.allObjects as? [DataSnapshot] else {
fatalError("could not decode")
}
let requestingDonations = donationSnapshots.compactMap(Donation.init)
completion(requestingDonations)
}
}
}
|
//
// GoogleBooksService.swift
// BooksManager
//
// Created by Sebastian Staszczyk on 12/03/2021.
//
import Foundation
import Combine
struct BooksService<O: BooksAPI> {
private let apiService = APIService.shared
private var apiCallQuery: URLComponents?
private var apiCallURL: URL?
private let apiComponents: O
init(_ service: O) {
self.apiComponents = service
}
mutating func fetchBooks(form: SearchBooksForm, startAt index: Int) -> AnyPublisher<[BookViewModel], APIServiceError> {
if index == 0 {
setAPICallQuery(for: form)
}
let url = getAPICallURL(startAt: index)
return performBooksCall(url)
.map { $0.results ?? [] }
.compactMap { $0.map { BookViewModel(bookType: $0) } as? [BookViewModel] }
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
}
private func performBooksCall(_ apiCall: URL) -> AnyPublisher<O.Response, APIServiceError> {
apiService.fetchFromLinkURL(apiCall)
.eraseToAnyPublisher()
}
private mutating func setAPICallQuery(for form: SearchBooksForm) {
var components = apiComponents.startComponents
let search = apiComponents.getBasicParameters(for: form)
let additional = apiComponents.getAdditionalParameters(for: form)
components.queryItems?.append(contentsOf: search)
components.queryItems?.append(contentsOf: additional)
apiCallQuery = components
}
private func getAPICallURL(startAt index: Int) -> URL {
let startIndex = apiComponents.getOffsetParameter(for: index)
var apiCallURL = apiCallQuery
apiCallURL?.queryItems?.append(startIndex)
return apiCallURL!.url!
}
}
|
//
// Simplemon.swift
// Pokedex Plus
//
// Created by Iskierka, Julia on 15/06/2020.
// Copyright © 2020 Iskierka Lipiec. All rights reserved.
//
import Foundation
class Simplemon: Decodable {
var name: String
var url: String
public var description: String {
return url.replacingOccurrences(of: "https://pokeapi.co/api/v2/pokemon-species/", with: "").replacingOccurrences(of: "/", with: "")
}
}
|
//
// CatCollectionView.swift
// Catty Project
//
// Created by Сергей Коршунов on 23.07.2020.
// Copyright © 2020 Sergey Korshunov. All rights reserved.
//
import UIKit
import RxSwift
final class CatCollectionView: UICollectionView {
init(indetifier: String = "CatCollection") {
let flowLayout = UICollectionViewFlowLayout()
super.init(frame: CGRect.zero, collectionViewLayout: flowLayout)
let width = UIScreen.main.bounds.width / 2 - 16
flowLayout.itemSize = CGSize(width: width, height: width)
flowLayout.sectionInset = UIEdgeInsets(top: 8, left: 8, bottom: 20, right: 8)
register(CatCell.self, forCellWithReuseIdentifier: CatCell.id)
backgroundColor = .systemBackground
accessibilityIdentifier = indetifier
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// ViewController.swift
// Flavor Town
//
// Created by Stephen Furlani on 9/2/20.
// Copyright © 2020 Upside Commerce Group. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var topBox: UIView!
@IBOutlet weak var bottomBox: UIView!
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
topBox.backgroundColor = Theme.primary.default
bottomBox.backgroundColor = Theme.secondary.default
label.text = NSLocalizedString("Fieri", comment: "String to show on main app page")
}
}
|
//
// TMMenuVC.swift
// TortyMozyrApp
//
// Created by Саша Капчук on 3.04.21.
//
import TTGTagCollectionView
import UIKit
struct CustomData {
var title: String
var image: UIImage
var url: String
}
class TMMenuVC: UIViewController {
let data = [
CustomData(title: "Торты в Мозыре", image: #imageLiteral(resourceName: "bigFruitCakeImage"), url: "google.com"),
CustomData(title: "На ДР", image: #imageLiteral(resourceName: "medovikCakeImage"), url: "google.com"),
CustomData(title: "Торты для детей", image: #imageLiteral(resourceName: "bigFruitCakeImage"), url: "google.com"),
CustomData(title: "Учителю", image: #imageLiteral(resourceName: "medovikCakeImage"), url: "google.com"),
CustomData(title: "Наборы", image: #imageLiteral(resourceName: "bigFruitCakeImage"), url: "google.com"),
CustomData(title: "Пироги", image: #imageLiteral(resourceName: "bigFruitCakeImage"), url: "google.com"),
CustomData(title: "Любимым", image: #imageLiteral(resourceName: "medovikCakeImage"), url: "google.com"),
CustomData(title: "Торты в Мозыре", image: #imageLiteral(resourceName: "bigFruitCakeImage"), url: "google.com")
]
// MARK: - gui variables
private lazy var tagsCollectionView: TTGTextTagCollectionView = {
let tags = TTGTextTagCollectionView()
let textTagConfig = TTGTextTagConfig()
textTagConfig.backgroundColor = .systemBlue
textTagConfig.textColor = .white
tags.addTags(["Торт", "Десерт", "Подарок", "Пирог", "Наборы", "Десерты детства", "На День Рождения", "Любимому человеку"], with: textTagConfig)
tags.scrollDirection = .horizontal
tags.showsHorizontalScrollIndicator = false
tags.alignment = .left
tags.delegate = self
return tags
}()
private var tagSelections = [String]()
private lazy var storiesCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 15
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.showsHorizontalScrollIndicator = false
cv.translatesAutoresizingMaskIntoConstraints = false
cv.register(CustomCell.self, forCellWithReuseIdentifier: "cell")
return cv
}()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Меню"
self.view.backgroundColor = .white
view.addSubview(tagsCollectionView)
self.view.addSubview(storiesCollectionView)
self.storiesCollectionView.backgroundColor = .white
self.storiesCollectionView.delegate = self
self.storiesCollectionView.dataSource = self
self.setUpConstraints()
}
// MARK: - set up constraints
func setUpConstraints() {
self.tagsCollectionView.snp.makeConstraints { (make) in
make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top).offset(15)
make.width.equalTo(500)
make.height.equalTo(40)
}
self.storiesCollectionView.snp.makeConstraints { (make) in
make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top).offset(70)
make.left.equalToSuperview().offset(10)
make.width.equalTo(400)
make.height.equalTo(130)
}
}
}
class CustomCell: UICollectionViewCell {
var data: CustomData? {
didSet {
guard let data = data else { return }
storiesImageView.image = data.image
storiesTitle.text = data.title
}
}
private lazy var colorCircleStoriesView: UIView = {
let view = UIView()
view.backgroundColor = .systemOrange
view.layer.cornerRadius = 46
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private lazy var whiteCircleStoriesView: UIView = {
let view = UIView()
view.backgroundColor = .white
view.layer.cornerRadius = 43
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private lazy var storiesImageView: UIImageView = {
let iv = UIImageView()
iv.clipsToBounds = true
iv.layer.cornerRadius = 40
iv.contentMode = .scaleAspectFill
iv.translatesAutoresizingMaskIntoConstraints = false
return iv
}()
private lazy var storiesTitle: UILabel = {
let title = UILabel()
title.font = UIFont.systemFont(ofSize: 12, weight: .bold)
title.textAlignment = .center
title.translatesAutoresizingMaskIntoConstraints = false
return title
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(colorCircleStoriesView)
contentView.addSubview(whiteCircleStoriesView)
contentView.addSubview(storiesImageView)
contentView.addSubview(storiesTitle)
storiesImageView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
storiesImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
storiesImageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
storiesImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
self.storiesTitle.snp.makeConstraints { (make) in
make.centerX.equalTo(self.storiesImageView)
make.top.equalTo(self.storiesImageView.snp.bottom).offset(10)
}
self.colorCircleStoriesView.snp.makeConstraints { (make) in
make.size.equalTo(92)
make.centerX.equalTo(self.storiesImageView.snp.centerX)
make.centerY.equalTo(self.storiesImageView.snp.centerY)
}
self.whiteCircleStoriesView.snp.makeConstraints { (make) in
make.size.equalTo(86)
make.centerX.equalTo(self.storiesImageView.snp.centerX)
make.centerY.equalTo(self.storiesImageView.snp.centerY)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - extensions
extension TMMenuVC: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// return CGSize(width: collectionView.frame.width / 2.5, height: collectionView.frame.width / 2)
return CGSize(width: 80, height: 80)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.data.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
if let cell = cell as? CustomCell {
cell.data = self.data[indexPath.row]
}
return cell
}
}
extension TMMenuVC: TTGTextTagCollectionViewDelegate {
func textTagCollectionView(_ textTagCollectionView: TTGTextTagCollectionView!, didTapTag tagText: String!, at index: UInt, selected: Bool, tagConfig config: TTGTextTagConfig!) {
tagSelections.append(tagText)
print(tagSelections)
}
}
|
//
// SearchCell.swift
// pixabay
//
// Created by Dmitriy Zadoroghnyy on 02/04/2019.
// Copyright © 2019 Dmitriy Zadoroghnyy. All rights reserved.
//
import UIKit
class SearchCell: UITableViewCell {
static let id = "searchCell"
}
|
//
// InstructionTableViewCell.swift
// Hookah
//
// Created by Bogdan Kostyuchenko on 25/03/2018.
// Copyright © 2018 Bogdan Kostyuchenko. All rights reserved.
//
import UIKit
class InstructionTableViewCell: UITableViewCell {
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var categoryDescriptionLabel: UILabel!
@IBOutlet weak var categoryImageView: UIImageView!
}
|
//
import MarvelUIKit
class CharacterTableCellView: UIView {
convenience init() {
self.init(frame: .zero)
configUI()
}
var tableView: UITableView = {
let tableView = UITableView()
tableView.register(
MUICharacterTableCell.self,
forCellReuseIdentifier: MUICharacterTableCell.reuseIdentifier
)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.rowHeight = 150
return tableView
}()
func configUI() {
addSubview(tableView)
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: self.topAnchor),
tableView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
tableView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: self.trailingAnchor)
])
}
}
|
import CurrencyKit
import MarketKit
class MarketListDefiDecorator {
typealias Item = MarketGlobalDefiMetricService.DefiItem
private let service: IMarketListDecoratorService
var marketField: MarketModule.MarketField {
didSet {
service.onUpdate(marketFieldIndex: marketField.rawValue)
}
}
init(service: IMarketListDecoratorService) {
self.service = service
marketField = MarketModule.MarketField.allCases[service.initialMarketFieldIndex]
}
}
extension MarketListDefiDecorator: IMarketSingleSortHeaderDecorator {
var allFields: [String] {
MarketModule.MarketField.allCases.map { $0.title }
}
var currentFieldIndex: Int {
MarketModule.MarketField.allCases.firstIndex(of: marketField) ?? 0
}
func setCurrentField(index: Int) {
marketField = MarketModule.MarketField.allCases[index]
}
}
extension MarketListDefiDecorator: IMarketListDecorator {
func listViewItem(item: MarketGlobalDefiMetricService.DefiItem) -> MarketModule.ListViewItem {
let marketInfo = item.marketInfo
let currency = service.currency
let price = marketInfo.price.flatMap { ValueFormatter.instance.formatShort(currency: currency, value: $0) } ?? "n/a".localized
let dataValue: MarketModule.MarketDataValue
switch marketField {
case .price: dataValue = .diff(marketInfo.priceChangeValue(type: service.priceChangeType))
case .volume: dataValue = .volume(marketInfo.totalVolume.flatMap { ValueFormatter.instance.formatShort(currency: currency, value: $0) } ?? "n/a".localized)
case .marketCap: dataValue = .marketCap(marketInfo.marketCap.flatMap { ValueFormatter.instance.formatShort(currency: currency, value: $0) } ?? "n/a".localized)
}
return MarketModule.ListViewItem(
uid: marketInfo.fullCoin.coin.uid,
iconUrl: marketInfo.fullCoin.coin.imageUrl,
iconShape: .square,
iconPlaceholderName: "placeholder_circle_32",
leftPrimaryValue: marketInfo.fullCoin.coin.code,
leftSecondaryValue: marketInfo.fullCoin.coin.name,
badge: "\(item.tvlRank)",
badgeSecondaryValue: nil,
rightPrimaryValue: price,
rightSecondaryValue: dataValue
)
}
}
|
//
// ViewController.swift
// sa15aci
//
// Created by sa15ach on 20/04/2018.
// Copyright © 2018 sa15ach. All rights reserved.
//
import UIKit
class ViewController: UIViewController{
var dynamicAnimator: UIDynamicAnimator!
var dynamiItemBehavior: UIDynamicItemBehavior!
var collisionBehavior: UICollisionBehavior!
@IBOutlet var roadView: UIImageView!
@IBOutlet weak var mainCar: dragCar!
// @IBOutlet weak var gameOver: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Animation of the road
var imageArray: [UIImage]!
imageArray = [UIImage(named: "road1.png")!,
UIImage(named: "road2.png")!,
UIImage(named: "road3.png")!,
UIImage(named: "road4.png")!,
UIImage(named: "road5.png")!,
UIImage(named: "road6.png")!,
UIImage(named: "road7.png")!,
UIImage(named: "road8.png")!,
UIImage(named: "road9.png")!,
UIImage(named: "road10.png")!,
UIImage(named: "road11.png")!,
UIImage(named: "road12.png")!,
UIImage(named: "road13.png")!,
UIImage(named: "road15.png")!,
UIImage(named: "road16.png")!,
UIImage(named: "road17.png")!,
UIImage(named: "road18.png")!,
UIImage(named: "road19.png")!,
UIImage(named: "road20.png")!]
roadView.image = UIImage.animatedImage(with: imageArray, duration: 0.5)
class dragCar: UIImageView {
var startLocation: CGPoint?
//define variable
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?){
startLocation = touches.first?.location(in: self)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?){
let dx = startLocation!.x - startLocation!.x
let dy = startLocation!.y - startLocation!.y
self.center = CGPoint(x: self.center.x+dx, y: self.center.y+dy)
}
//addition of car obstacle
//Create amn array of new UIImageView from scratch
var carView = UIImageView(image: nil)
//Assign an image to the image view
carView.image = UIImage(named: "car1.png")
//Assign the size of the image view
carView.frame = CGRect(x: 50, y: 0, width:30, height: 50)
//view.frame.origin.x += 10
//Add the image view to the main view
self.view.addSubview(carView)
//make car fall down the screen
dynamicAnimator = UIDynamicAnimator(referenceView: self.view)
dynamiItemBehavior = UIDynamicItemBehavior(items: [carView])
self.dynamiItemBehavior.addLinearVelocity (CGPoint(x: 0, y:300),for: carView)
dynamicAnimator.addBehavior(dynamiItemBehavior)
collisionBehavior = UICollisionBehavior(items: [carView,mainCar])
//do not allow cars to leave the view
collisionBehavior.translatesReferenceBoundsIntoBoundary = false
dynamicAnimator.addBehavior(collisionBehavior)
// var carView1 = UIImageView(image: nil)
// carView1.image = UIImage(named: "car2.png")
// carView.frame = CGRect(x: 120, y: 0, width:30, height: 50)
// self.view.addSubview(carView1)
//make car fall down the screen
// dynamicAnimator = UIDynamicAnimator(referenceView: self.view)
// dynamiItemBehavior = UIDynamicItemBehavior(items: [carView])
// self.dynamiItemBehavior.addLinearVelocity (CGPoint(x: 0, y:300),for: carView)
// dynamicAnimator.addBehavior(dynamiItemBehavior)
// collisionBehavior = UICollisionBehavior(items: [carView,mainCar,carView1])
//do not allow cars to leave the view
// collisionBehavior.translatesReferenceBoundsIntoBoundary = false
// dynamicAnimator.addBehavior(collisionBehavior)
// var carView2 = UIImageView(image: nil)
// carView2.image = UIImage(named: "car2.png")
// carView.frame = CGRect(x: 150, y: 0, width:30, height: 50)
// self.view.addSubview(carView2)
//make car fall down the screen
// dynamicAnimator = UIDynamicAnimator(referenceView: self.view)
// dynamiItemBehavior = UIDynamicItemBehavior(items: [carView])
// self.dynamiItemBehavior.addLinearVelocity (CGPoint(x: 0, y:300),for: carView2)
// dynamicAnimator.addBehavior(dynamiItemBehavior)
// collisionBehavior = UICollisionBehavior(items: /[carView2,mainCar, carView1])
//do not allow cars to leave the view
// collisionBehavior.translatesReferenceBoundsIntoBoundary = false
// dynamicAnimator.addBehavior(collisionBehavior)
//Create a new image view and assign an image: game over subview
var gameOverView = UIImageView(image: nil)
//assign image
gameOverView.image = UIImage(named: "game over page.jpg")
//Make this image view fulfil the screen
gameOverView.frame = UIScreen.main.bounds
//Add the image view to the main view
//self.view.addSubview(roadView)
//bring view forward
//self.view.bringSubview(toFront: roadView)
let when = DispatchTime.now() + 16
DispatchQueue.main.asyncAfter(deadline: when)
{
self.view.addSubview(gameOverView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
import Kitura
import HeliumLogger
HeliumLogger.use()
let router = Router()
Kitura.addHTTPServer(onPort: 8090, with: router)
Kitura.run()
|
//
// Created by Daniel Heredia on 2/27/18.
// Copyright © 2018 Daniel Heredia. All rights reserved.
//
// JukeBox
import Foundation
class CD {
// Stores data like id, artist and songs
}
class Song {
// Stores data like id, title, length, etc
}
class User {
// General information of the user: name, id, etc
}
class SongSelector {
// Allows to the user to select the songs and keeps a big queue of songs to play.
// Interacts directly with the cd player, due that the cdplayer can just store one CD at time.
// Additionaly display the info of the current song and the following songs
var currentSong: Song? {
return nil
}
}
// A list of songs to play, not necessarily songs from the same CD
class PlayList {
private var song: Song
private var songsQueue: [Song]
init(song: Song, songQueue: [Song]) {
self.song = song
self.songsQueue = songQueue
}
var nextSongToPlay: Song? {
return self.songsQueue.first
}
func queueSong(_ song: Song) {
self.songsQueue.append(song)
}
}
// CD player that can store one cd to play and follows
// a playlist composed of song inside of the provided cd.
class CDPlayer {
var playList: [Song]
var cd: CD
init(cd: CD, playlist: [Song]) {
self.playList = playlist
self.cd = cd
}
func playSong(_ song: Song) {
}
}
// Basic stucture of the Jukebox itself
class Jukebox {
private let cdPlayer: CDPlayer
private var user: User
private let cdCollection: [CD]
private let songSelector: SongSelector
init(cdPlayer: CDPlayer, user: User, cdCollection: [CD], songSelector: SongSelector) {
self.cdPlayer = cdPlayer
self.user = user
self.cdCollection = cdCollection
self.songSelector = songSelector
}
var currentSong: Song? {
return self.songSelector.currentSong
}
}
|
//
// RulesViewController.swift
// Tourney
//
// Created by Thaddeus Lorenz on 8/24/20.
// Copyright © 2020 Will Cohen. All rights reserved.
//
import UIKit
protocol RulesViewControllerDelegate: class {
func didTapStartCompeting()
}
class RulesViewController: UIViewController, UIScrollViewDelegate {
var feedVC: FeedVC!
@IBOutlet weak var rulesScrollView: UIScrollView!
@IBOutlet weak var rulePageControl: UIPageControl!
let rule1 = ["title":"Watch challenge video","image":"watchVideo"]
let rule2 = ["title":"Start competing by recording and uploading","image":"competitionStart"]
let rule3 = ["title":"Everyone can vote","image":"vote"]
let rule4 = ["title":"Whoever has the most votes wins","image":"competitionEnd"]
let rule5 = ["title":"Winner has to upload a new challenge","image":"trophy"]
let rule6 = ["title":"Invite your friends","image":"invite_friends"]
var ruleArray = [Dictionary<String, String>]()
weak var delegate: RulesViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
ruleArray = [rule1, rule2, rule3, rule4, rule5, rule6]
rulesScrollView.isPagingEnabled = true
rulesScrollView.contentSize = CGSize(width: self.view.bounds.width * CGFloat(ruleArray.count), height: 250)
rulesScrollView.showsHorizontalScrollIndicator = false
rulesScrollView.delegate = self
loadRules()
// Do any additional setup after loading the view.
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let page = scrollView.contentOffset.x / scrollView.frame.size.width
rulePageControl.currentPage = Int(page)
}
func loadRules(){
for (index, rule) in ruleArray.enumerated() {
if let ruleView = Bundle.main.loadNibNamed("Rule", owner: self, options: nil)?.first as? ruleView{
ruleView.ruleImageView.image = UIImage(named: rule["image"]!)
ruleView.titleLabel.text = rule["title"]
rulesScrollView.addSubview(ruleView)
ruleView.frame.size.width = self.view.bounds.size.width
ruleView.frame.origin.x = CGFloat(index) * self.view.bounds.size.width
}
}
}
@IBAction func uploadVideoButtonTapped() {
dismiss(animated: true) {
self.delegate?.didTapStartCompeting()
}
}
@IBAction func cancel(_ sender: AnyObject) {
dismiss(animated: true, completion: nil)
}
}
|
//
// AddContactViewController.swift
// Spoint
//
// Created by kalyan on 07/11/17.
// Copyright © 2017 Personal. All rights reserved.
//
import UIKit
import Firebase
import Messages
class AddContactViewController: UIViewController,UITextFieldDelegate, UserSelectionDelegate, UITableViewDataSource, UITableViewDelegate,UISearchBarDelegate {
func usersSelected(users: [User]) {
if users.count > 0 {
selectedUser = users[0]
//self.phoneField.text = users[0].phone
}
}
@IBOutlet var phoneField: UITextField!
@IBOutlet var timelineSwitch: UISwitch!
@IBOutlet var locationSwitch: UISwitch!
@IBOutlet var notificationSwitch: UISwitch!
var selectedUser:User!
@IBOutlet var tableView:UITableView!
var searchUsers = [FollowUser]()
var followingUserIds = [String]()
@IBOutlet var searchBar:UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(FollowerRequestTableViewCell.self)
tableView.delegate = self
tableView.dataSource = self
searchBar.delegate = self
let inviteBtn = UIButton(type: .custom)
inviteBtn.frame.size.height = 50.0
inviteBtn.setTitle("Invite Friends", for: .normal)
inviteBtn.setTitleColor(UIColor.red, for: .normal)
inviteBtn.addTarget(self, action: #selector(inviteButtonAction(sender:)), for: .touchUpInside)
tableView.tableFooterView = inviteBtn
// self.resultSearchController = ({
// let controller = UISearchController(searchResultsController: nil)
// controller.searchResultsUpdater = self
// controller.dimsBackgroundDuringPresentation = false
// controller.searchBar.sizeToFit()
// controller.searchBar.searchBarStyle = .minimal
//
// self.tableView.tableHeaderView = controller.searchBar
//
// return controller
// })()
self.navigationController?.extendedLayoutIncludesOpaqueBars = true
}
@objc func inviteButtonAction(sender:UIButton) {
let vc = storyboard?.instantiateViewController(withIdentifier: "PhoneContactsViewController") as! PhoneContactsViewController
self.navigationController?.pushViewController(vc, animated: true)
}
func updateSearchResults(for searchController: UISearchController) {
let searchtext = searchController.searchBar.text?.lowercased().description
let array = FireBaseContants.firebaseConstant.allUsers.filter { (message:User) -> Bool in
return message.name.lowercased().hasPrefix(searchtext!) || message.email.lowercased().hasPrefix(searchtext!) || message.phone.hasPrefix(searchtext!)
}
//searchUsers = array
//self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func addButtonAction(sender:UIButton) {
guard (selectedUser) != nil else {
return
}
if selectedUser != nil {
if !selectedUser.accountTypePrivate {
FireBaseContants.firebaseConstant.requestPostUrl(strUrl: "https://fcm.googleapis.com/fcm/send", postHeaders:["Content-Type":"application/json","Authorization":"key=AAAAvyiQ5LQ:APA91bFLwzsyhfe347dLfJgwBmeQVyulPLSIkQiSLOiRKvsCG_OqGTk3g6_j7c9XR0wslUd0Hi9LIT-1975_sLuDVwXmGvib-VVa6lUrHWQ21pNr62T7Mpnr_8_Gm7h5EF-dMgc22bin"] , payload: self.buildPushPayloadForFollowing() ) { (response, error, data) in
}
let values = [keys.requestStatusKey: 1,keys.seeTimelineKey:true,keys.seeLocationKey:true,"checkin":true,keys.notificationsKey:true,keys.timestampKey:Int64(TimeStamp),"message":true] as [String : Any]
FireBaseContants.firebaseConstant.Followers.child(FireBaseContants.firebaseConstant.CURRENT_USER_ID).child(selectedUser.id).updateChildValues([keys.requestStatusKey:1])
FireBaseContants.firebaseConstant.Following.child(selectedUser.id).child(FireBaseContants.firebaseConstant.CURRENT_USER_ID).updateChildValues(values)
}else{
UserDefaults.standard.set(true, forKey: "requestSent")
let values = [keys.requestStatusKey: 0, keys.recieverKey: selectedUser.phone,keys.seeTimelineKey:true,keys.seeLocationKey:true,keys.notificationsKey:true,keys.senderKey:UserDefaults.standard.value(forKey: UserDefaultsKey.phoneNoKey) as! String,keys.timestampKey:Int64(TimeStamp)] as [String : Any]
FireBaseContants.firebaseConstant.requestPostUrl(strUrl: "https://fcm.googleapis.com/fcm/send", postHeaders:[:] , payload: self.buildPushPayload() ) { (response, error, data) in }
let reqName = FireBaseContants.firebaseConstant.currentUserInfo?.name as? String ?? ""
let notificaitonvalues = [keys.recieverKey: selectedUser.phone,keys.messageKey:"\(reqName) has requested to follow you",keys.notificationTypeKey:"FollowerRequest",keys.createdByKey:FireBaseContants.firebaseConstant.CURRENT_USER_ID,keys.senderNameKey:FireBaseContants.firebaseConstant.currentUserInfo?.name as! String,keys.timestampKey:Int64(TimeStamp)] as [String : Any]
FireBaseContants.firebaseConstant.sendRequestToUser(selectedUser.id,param: values )
let reqValues = [keys.requestStatusKey: 0, keys.recieverKey: selectedUser.phone,keys.seeTimelineKey:true,keys.seeLocationKey:true,keys.notificationsKey:true,keys.senderKey:UserDefaults.standard.value(forKey: UserDefaultsKey.phoneNoKey) as! String,keys.timestampKey:Int64(TimeStamp),keys.unread:true] as [String : Any]
//FireBaseContants.firebaseConstant.Following.child(FireBaseContants.firebaseConstant.CURRENT_USER_ID).child(selectedUser.id).updateChildValues(param)
FireBaseContants.firebaseConstant.saveNotification(selectedUser.id, key: "", param: notificaitonvalues)
FireBaseContants.firebaseConstant.updateUnReadNotificationsForId(selectedUser.id, count: selectedUser.unreadNotifications+1)
}
self.searchUsers[sender.tag].requestStatus = 0
self.tableView.reloadData()
//self.backButtonAction()
}
}
@IBAction func closeButtonAction(){
self.dismiss(animated: true, completion: nil)
}
@IBAction func backButtonAction(){
self.navigationController?.popViewController(animated: true)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return searchUsers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "FollowerRequestTableViewCell") as! FollowerRequestTableViewCell
cell.titleLabel?.text = searchUsers[indexPath.item].userInfo.name.capitalized
cell.imageview?.kf.setImage(with: searchUsers[indexPath.item].userInfo.profilePic)
if searchUsers[indexPath.item].requestStatus == 0 {
cell.requestButton.setTitle("Requested", for: .normal)
}else if searchUsers[indexPath.item].requestStatus == 1 {
cell.requestButton.setTitle("Following", for: .normal)
}else{
cell.requestButton.setTitle("Follow", for: .normal)
}
cell.requestButton.tag = indexPath.row
cell.requestButton.addTarget(self, action: #selector(requestButtonAction(sender:)), for: .touchUpInside)
cell.contentView.backgroundColor = UIColor.clear
cell.backgroundColor = UIColor.clear
//cell.accessoryType = cell.isSelected ? .checkmark : .none
// cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(self.searchUsers[indexPath.item].userInfo.name)
selectedUser = self.searchUsers[indexPath.item].userInfo
//self.addButtonAction(sender: nil)
//resultSearchController.isActive = false
}
@objc func requestButtonAction(sender:UIButton){
if sender.titleLabel?.text?.lowercased() == "Follow".lowercased() {
selectedUser = self.searchUsers[sender.tag].userInfo
self.addButtonAction(sender: sender)
}else if sender.titleLabel?.text?.lowercased() == "Following".lowercased() {
}else{
self.showAlertWithTitle(title: "", message: "Cancel the request?", buttonCancelTitle: "NO", buttonOkTitle: "YES", completion: { (index) in
if index == 1 {
self.selectedUser = self.searchUsers[sender.tag].userInfo
FireBaseContants.firebaseConstant.Followers.child(self.selectedUser.id).child(FireBaseContants.firebaseConstant.CURRENT_USER_ID).removeValue()
self.searchUsers[sender.tag].requestStatus = 2
self.tableView.reloadData()
}
})
}
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
self.performSegue(withIdentifier: "searchFriend", sender: self)
return false
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
if textField == phoneField {
let count = phoneField.text?.characters.count as! Int
if count > 8 , !string.isEmpty {
self.phoneField.text = self.phoneField.text! + string
textField.resignFirstResponder()
}
}
return true
}
//MARK: Search Bar Delegates
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.text = ""
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar){
searchBar.resignFirstResponder()
self.searchUsers.removeAll()
if let searchtext = searchBar.text, searchtext.count > 0 {
if searchtext.isNumber {
self.phoneSearch(searchText: searchBar.text!)
}else{
self.userNameSearch(searchText: searchBar.text!.lowercased())
self.userNameFullSearch(searchText: searchBar.text!.lowercased())
}
}
self.tableView.reloadData()
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
self.searchUsers.removeAll()
if let searchtext = searchBar.text, searchtext.count > 0 {
if searchtext.isNumber {
self.phoneSearch(searchText: searchBar.text!)
}else{
self.userNameSearch(searchText: searchBar.text!.lowercased())
self.userNameFullSearch(searchText: searchBar.text!.lowercased())
}
}
self.tableView.reloadData()
}
func phoneSearch(searchText:String) {
//self.showLoaderWithMessage(message: "Loading")
let ref = FireBaseContants.firebaseConstant.USER_REF().queryOrdered(byChild:keys.phoneNumberKey ).queryEqual(toValue : searchBar.text!)
ref.observeSingleEvent(of: .value, with:{ (snapshot: DataSnapshot) in
for snapshot in snapshot.children.allObjects as! [DataSnapshot] {
if ((snapshot.value as? [String:Any]) != nil){
if ((snapshot.childSnapshot(forPath: keys.usernameKey).value as? String) != nil && snapshot.key != FireBaseContants.firebaseConstant.CURRENT_USER_ID) {
let name = snapshot.childSnapshot(forPath: keys.usernameKey).value as! String
let email = snapshot.childSnapshot(forPath: keys.emailKey).value as! String
let fullname = snapshot.childSnapshot(forPath: keys.fullnameKey).value as! String
let age = snapshot.childSnapshot(forPath: keys.ageKey).value as? String ?? "18"
let gender = snapshot.childSnapshot(forPath: keys.genderKey).value as! String
let dob = snapshot.childSnapshot(forPath: keys.dobKey).value as? String ?? ""
let id = snapshot.key
let latitude = snapshot.childSnapshot(forPath: keys.lattitudeKey).value as? Double ?? 17.44173698171217
let longitude = snapshot.childSnapshot(forPath: keys.longitudeKey).value as? Double ?? 78.38839530944824
let fileURL = Bundle.main.path(forResource: "profile_ph@3x", ofType: "png")
var link:URL?
if ((snapshot.childSnapshot(forPath: keys.imageUrlKey).value as? String) != nil){
link = URL.init(string: snapshot.childSnapshot(forPath: keys.imageUrlKey).value as! String )
}else{
link = URL.init(string: fileURL!)
}
let city = snapshot.childSnapshot(forPath: keys.cityKey).value as? String ?? ""
let token = snapshot.childSnapshot(forPath: keys.tokenKey).value as! String
let locationState = snapshot.childSnapshot(forPath: keys.locationStateKey).value as? Bool ?? false
let devicetype = snapshot.childSnapshot(forPath: keys.deviceTypeKey).value as? Int ?? 0
let phoneNo = snapshot.childSnapshot(forPath: keys.phoneNumberKey).value as? String ?? ""
let unreadNotification = snapshot.childSnapshot(forPath: keys.unreadNotification).value as? Int ?? 0
let unreadMessage = snapshot.childSnapshot(forPath: keys.unreadMessages).value as? Int ?? 0
let user = User.init(name: name, email: email, id: id, profilePic: link!, fullname:fullname , age:age , gender: gender, latitude: latitude, longitude: longitude, city: city, token: token, locationState: locationState,devicetype:devicetype, phoneNo: phoneNo, permission: nil, dob: dob, unreadmessage: unreadMessage, unreadnotification: unreadNotification)
FireBaseContants.firebaseConstant.Followers.child(id).child(FireBaseContants.firebaseConstant.CURRENT_USER_ID).observeSingleEvent(of: .value, with: { (child) in
if child.exists() {
let follower = FollowUser(userinfo: user, locationstatus: child.childSnapshot(forPath: keys.seeLocationKey).value as! Bool, timelinestatus: child.childSnapshot(forPath: keys.seeTimelineKey).value as! Bool, notificationstatus: child.childSnapshot(forPath: keys.notificationsKey).value as! Bool, requeststatus: child.childSnapshot(forPath: keys.requestStatusKey).value as! Int, messageStatus: true)
self.searchUsers.append(follower)
}else{
let follower = FollowUser(userinfo: user, locationstatus: true, timelinestatus: true, notificationstatus: true, requeststatus: 4, messageStatus: true)
self.searchUsers.append(follower)
}
self.tableView.reloadData()
})
}
}
}
self.dismissLoader()
})
}
func userNameSearch(searchText:String) {
//self.showLoaderWithMessage(message: "Loading")
let ref = FireBaseContants.firebaseConstant.USER_REF().queryOrdered(byChild:keys.usernameKey ).queryStarting(atValue: searchText , childKey: keys.usernameKey).queryEnding(atValue: searchText + "\u{f8ff}", childKey: keys.usernameKey)
ref.observeSingleEvent(of: .value, with:{ (snapshot: DataSnapshot) in
for snapshot in snapshot.children.allObjects as! [DataSnapshot] {
if ((snapshot.value as? [String:Any]) != nil){
if ((snapshot.childSnapshot(forPath: keys.usernameKey).value as? String) != nil && snapshot.key != FireBaseContants.firebaseConstant.CURRENT_USER_ID ) {
let name = snapshot.childSnapshot(forPath: keys.usernameKey).value as! String
let email = snapshot.childSnapshot(forPath: keys.emailKey).value as! String
let fullname = snapshot.childSnapshot(forPath: keys.fullnameKey).value as! String
let age = snapshot.childSnapshot(forPath: keys.ageKey).value as? String ?? "18"
let gender = snapshot.childSnapshot(forPath: keys.genderKey).value as! String
let dob = snapshot.childSnapshot(forPath: keys.dobKey).value as? String ?? ""
let id = snapshot.key
let latitude = snapshot.childSnapshot(forPath: keys.lattitudeKey).value as? Double ?? 17.44173698171217
let longitude = snapshot.childSnapshot(forPath: keys.longitudeKey).value as? Double ?? 78.38839530944824
let fileURL = Bundle.main.path(forResource: "profile_ph@3x", ofType: "png")
var link:URL?
if ((snapshot.childSnapshot(forPath: keys.imageUrlKey).value as? String) != nil){
link = URL.init(string: snapshot.childSnapshot(forPath: keys.imageUrlKey).value as! String )
}else{
link = URL.init(string: fileURL!)
}
let city = snapshot.childSnapshot(forPath: keys.cityKey).value as? String ?? ""
let token = snapshot.childSnapshot(forPath: keys.tokenKey).value as! String
let locationState = snapshot.childSnapshot(forPath: keys.locationStateKey).value as? Bool ?? false
let devicetype = snapshot.childSnapshot(forPath: keys.deviceTypeKey).value as? Int ?? 0
let phoneNo = snapshot.childSnapshot(forPath: keys.phoneNumberKey).value as? String ?? ""
let unreadNotification = snapshot.childSnapshot(forPath: keys.unreadNotification).value as? Int ?? 0
let unreadMessage = snapshot.childSnapshot(forPath: keys.unreadMessages).value as? Int ?? 0
let user = User.init(name: name, email: email, id: id, profilePic: link!, fullname:fullname , age:age , gender: gender, latitude: latitude, longitude: longitude, city: city, token: token, locationState: locationState,devicetype:devicetype, phoneNo: phoneNo, permission: nil, dob: dob, unreadmessage: unreadMessage, unreadnotification: unreadNotification)
FireBaseContants.firebaseConstant.Followers.child(id).child(FireBaseContants.firebaseConstant.CURRENT_USER_ID).observeSingleEvent(of: .value, with: { (child) in
if child.exists() {
let id = child.key
let follower = FollowUser(userinfo: user, locationstatus: child.childSnapshot(forPath: keys.seeLocationKey).value as! Bool, timelinestatus: child.childSnapshot(forPath: keys.seeTimelineKey).value as! Bool, notificationstatus: child.childSnapshot(forPath: keys.notificationsKey).value as! Bool, requeststatus: child.childSnapshot(forPath: keys.requestStatusKey).value as! Int, messageStatus: true)
let filter = self.searchUsers.filter{$0.userInfo.id == user.id}
if filter.count == 0 {
self.searchUsers.append(follower)
}
}else{
let follower = FollowUser(userinfo: user, locationstatus: true, timelinestatus: true, notificationstatus: true, requeststatus: 4, messageStatus: true)
let filter = self.searchUsers.filter{$0.userInfo.id == user.id}
if filter.count == 0 {
self.searchUsers.append(follower)
}
}
self.tableView.reloadData()
})
}
}
}
self.dismissLoader()
})
}
func userNameFullSearch(searchText:String) {
//self.showLoaderWithMessage(message: "Loading")
let ref = FireBaseContants.firebaseConstant.USER_REF().queryOrdered(byChild:keys.usernameKey ).queryEqual(toValue: searchText)
ref.observeSingleEvent(of: .value, with:{ (snapshot: DataSnapshot) in
for snapshot in snapshot.children.allObjects as! [DataSnapshot] {
let filter = self.searchUsers.filter{$0.userInfo.id == snapshot.key}
if ((snapshot.value as? [String:Any]) != nil){
if ((snapshot.childSnapshot(forPath: keys.usernameKey).value as? String) != nil && snapshot.key != FireBaseContants.firebaseConstant.CURRENT_USER_ID && filter.count == 0) {
let name = snapshot.childSnapshot(forPath: keys.usernameKey).value as! String
let email = snapshot.childSnapshot(forPath: keys.emailKey).value as! String
let fullname = snapshot.childSnapshot(forPath: keys.fullnameKey).value as! String
let age = snapshot.childSnapshot(forPath: keys.ageKey).value as? String ?? "18"
let gender = snapshot.childSnapshot(forPath: keys.genderKey).value as! String
let dob = snapshot.childSnapshot(forPath: keys.dobKey).value as? String ?? ""
let id = snapshot.key
let latitude = snapshot.childSnapshot(forPath: keys.lattitudeKey).value as? Double ?? 17.44173698171217
let longitude = snapshot.childSnapshot(forPath: keys.longitudeKey).value as? Double ?? 78.38839530944824
let fileURL = Bundle.main.path(forResource: "profile_ph@3x", ofType: "png")
var link:URL?
if ((snapshot.childSnapshot(forPath: keys.imageUrlKey).value as? String) != nil){
link = URL.init(string: snapshot.childSnapshot(forPath: keys.imageUrlKey).value as! String )
}else{
link = URL.init(string: fileURL!)
}
let city = snapshot.childSnapshot(forPath: keys.cityKey).value as? String ?? ""
let token = snapshot.childSnapshot(forPath: keys.tokenKey).value as! String
let locationState = snapshot.childSnapshot(forPath: keys.locationStateKey).value as? Bool ?? false
let devicetype = snapshot.childSnapshot(forPath: keys.deviceTypeKey).value as? Int ?? 0
let phoneNo = snapshot.childSnapshot(forPath: keys.phoneNumberKey).value as? String ?? ""
let unreadNotification = snapshot.childSnapshot(forPath: keys.unreadNotification).value as? Int ?? 0
let unreadMessage = snapshot.childSnapshot(forPath: keys.unreadMessages).value as? Int ?? 0
let user = User.init(name: name, email: email, id: id, profilePic: link!, fullname:fullname , age:age , gender: gender, latitude: latitude, longitude: longitude, city: city, token: token, locationState: locationState,devicetype:devicetype, phoneNo: phoneNo, permission: nil, dob: dob, unreadmessage: unreadMessage, unreadnotification: unreadNotification)
FireBaseContants.firebaseConstant.Followers.child(id).child(FireBaseContants.firebaseConstant.CURRENT_USER_ID).observeSingleEvent(of: .value, with: { (child) in
if child.exists() {
let id = child.key
let follower = FollowUser(userinfo: user, locationstatus: child.childSnapshot(forPath: keys.seeLocationKey).value as! Bool, timelinestatus: child.childSnapshot(forPath: keys.seeTimelineKey).value as! Bool, notificationstatus: child.childSnapshot(forPath: keys.notificationsKey).value as! Bool, requeststatus: child.childSnapshot(forPath: keys.requestStatusKey).value as! Int, messageStatus: true)
let filter = self.searchUsers.filter{$0.userInfo.id == user.id}
if filter.count == 0 {
self.searchUsers.append(follower)
}
}else{
let follower = FollowUser(userinfo: user, locationstatus: true, timelinestatus: true, notificationstatus: true, requeststatus: 4, messageStatus: true)
let filter = self.searchUsers.filter{$0.userInfo.id == user.id}
if filter.count == 0 {
self.searchUsers.append(follower)
}
}
self.tableView.reloadData()
})
}
}
}
self.dismissLoader()
})
}
func buildPushPayload() -> [String:Any]{
let devicetoken = selectedUser.token
let reqName = FireBaseContants.firebaseConstant.currentUserInfo?.name ?? ""
let payload = [keys.senderKey:FireBaseContants.firebaseConstant.CURRENT_USER_ID]
var pushPayload:[String:Any] = [:]
let devicetype = selectedUser.deviceType
if devicetype == 0 {
pushPayload = ["registration_ids":[devicetoken],"notification":["title":"Follower Request","body":"\(reqName) has requested to follow you",keys.notificationTypeKey:"FollowerRequest", "sound":"default"]]
}else{
pushPayload = ["registration_ids":[devicetoken],"data":["message":"\(reqName) has requested to follow you",keys.notificationTypeKey:"FollowerRequest","data":payload]]
}
return pushPayload
}
func buildPushPayloadForFollowing() -> [String:Any]{
let devicetoken = selectedUser.token
let senderName = FireBaseContants.firebaseConstant.currentUserInfo?.name as! String
var pushPayload:[String:Any] = [:]
if selectedUser.deviceType == 0 {
pushPayload = ["registration_ids":[devicetoken],"notification":["title":"Request accepted","body":"Request accepted by \(senderName)","sound":"default"]]
}else{
pushPayload = ["registration_ids":[devicetoken],"data":["message":"Request accepted by \(senderName)"]]
}
return pushPayload
}
// 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.
let nav = segue.destination as! UINavigationController
if let vc = nav.visibleViewController as? AllUsersViewController {
vc.selectionDelegate = self
print(vc)
}
}
}
|
//
// NumberShouldBeEven.swift
// RxValidator
//
// Created by 유금상 on 2018. 6. 20..
//
import Foundation
public final class NumberShouldBeEven: IntValidatorType {
public init() {}
public func validate(_ value: Int) throws {
if (value % 2) != 0 {
throw RxValidatorResult.notEvenNumber
}
}
}
|
//
// API.swift
// comprasUSA
//
// Created by Kleyson on 26/10/2020.
// Copyright © 2020 Kleyson. All rights reserved.
//
import Foundation
final class API {
//funçao assincrona, pois o servidor pode demorar para retornar os dados e essa espera é assincrona utilizando o @escaping.
static func fetchMoney(typeMoney: MoneyTypes, completion: @escaping((Money) -> Void) ) {
let url = URL(string: Endpoints.baseUrl + typeMoney.rawValue)!
let dataTask = URLSession.shared.dataTask(with: url) { (data, _ , error) in
if error == nil { // deu certo, sem erro
let model = try! JSONDecoder().decode(Money.self, from: data!)
DispatchQueue.main.async {//voltar pra thread principal
completion(model)
}
}
else { // imprime o erro
print(error!)
}
}
dataTask.resume() // da o play na dataTask
}
}
|
//
// ProvinceDetailDrawer.swift
// CovidApp
//
// Creado por Joan Martin Martrus el 23/01/2021.
// Copyright (c) 2021 ___ORGANIZATIONNAME___. Todos los derechos reservados.
import UIKit
internal final class ProvinceDetailDrawer: CollectionDrawerProtocol {
func dequeueCollectionCell(_ collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell {
collectionView.register(UINib(nibName: ProvinceDetailCell.getCollectionIdentifier(),
bundle: nil),
forCellWithReuseIdentifier: ProvinceDetailCell.getCollectionIdentifier())
return collectionView.dequeueReusableCell(withReuseIdentifier: ProvinceDetailCell.getCollectionIdentifier(),
for: indexPath)
}
func drawCollectionCell(_ collectionView: UICollectionViewCell, withItem item: Any) {
guard let cell = collectionView as? ProvinceDetailCell, let cellVM = item as? ProvinceDetailViewModel
else {
return
}
cell.setProvinceNameLabel(provinceName: cellVM.provinceName)
cell.drawBarChart(confirmed: cellVM.confirmed,
recovered: cellVM.recovered,
deaths: cellVM.deaths,
active: cellVM.active)
}
}
|
//
// JsonParsingViewController.swift
// SwiftP
//
// Created by Rushikesh Kulkarni on 08/06/17.
// Copyright © 2017 simplicity. All rights reserved.
//
import UIKit
class JsonParsingViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {
var fetchedCountryCapital = [CountryClass]()
@IBOutlet weak var countryTblView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
countryTblView.dataSource = self
countryTblView.delegate = self
parseData()
SearchBar()
}
func SearchBar () {
let searchBar = UISearchBar(frame: CGRect(x: 0, y: 20, width: self.view.frame.size.width, height: 50))
searchBar.delegate = self
searchBar.showsScopeBar = true
searchBar.tintColor = UIColor.lightGray
searchBar.scopeButtonTitles = ["Country", "Capital"]
self.countryTblView.tableHeaderView = searchBar
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText == "" {
parseData()
}
else {
if searchBar.selectedScopeButtonIndex == 0 {
fetchedCountryCapital = fetchedCountryCapital.filter({ (country) -> Bool in
return country.countryStr.lowercased().contains(searchText.lowercased())
})
}
else {
fetchedCountryCapital = fetchedCountryCapital.filter({ (country) -> Bool in
return country.capitalStr.lowercased().contains(searchText.lowercased())
})
}
}
self.countryTblView .reloadData()
}
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
self.countryTblView .reloadData()
return true
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedCountryCapital.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = countryTblView.dequeueReusableCell(withIdentifier: "Cell")
cell?.textLabel?.text = fetchedCountryCapital[indexPath.row].countryStr
cell?.detailTextLabel?.text = fetchedCountryCapital[indexPath.row].capitalStr
return cell!
}
func parseData() {
fetchedCountryCapital = []
let url = "https://restcountries.eu/rest/v1/all"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) {(data , response, error) in
if(error != nil){
print("Error")
}
else {
do {
let fetchedDataArray = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
print(fetchedDataArray)
for eachFetchedCountry in fetchedDataArray {
let eachCountry = eachFetchedCountry as! [String: Any]
let countryNameStr = eachCountry["name"] as! String
let capitalNameStr = eachCountry["capital"] as! String
self.fetchedCountryCapital.append(CountryClass(country: countryNameStr, capital:capitalNameStr))
}
print(self.fetchedCountryCapital)
self.countryTblView.reloadData()
}
catch {
print("Error 2")
}
}
}
task.resume()
}
}
class CountryClass {
var countryStr : String
var capitalStr : String
init(country :String , capital : String) {
self.countryStr = country
self.capitalStr = capital
}
}
|
//
// EVDetailDictionaryViewController.swift
// testArtjoker
//
// Created by Admin on 27.05.16.
// Copyright © 2016 Ievgen Tkachenko. All rights reserved.
//
import Foundation
class EVDetailDictionaryViewController : UITableViewController {
@IBOutlet weak var titleLabel : UILabel!
@IBOutlet weak var languageLabel : UILabel!
@IBOutlet weak var optionalDetailLabel : UILabel!
var optionalDetail = String()
var translateTitle = String()
var language = String()
private var aHeightDetailCell : CGFloat = 0.0
private var aHeightTitleCell : CGFloat = 44.0
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
p_addCustomBackButton()
titleLabel.text! = translateTitle
languageLabel.text! = language
p_addTextInOptionalLabel()
// устанавливается высота ячейки в зависимости от высоты optionalDetailLabel
aHeightDetailCell = optionalDetailLabel.frame.size.height
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
// MARK: - Public Methods
// переходит на предыдущий контроллер
func backButtonPressed(sender:UIButton) {
navigationController?.popViewControllerAnimated(true)
}
// MARK: - Private Methods
// создание кастомной унопки на navigationBar
private func p_addCustomBackButton() {
let button = UIButton(type: .Custom)
button.setImage(UIImage(named: "backButton"), forState: .Normal)
button.addTarget(self, action:"backButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
button.frame = CGRectMake(0, 0, 30.0, 30.0)
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
}
// добавляет слова в optionalDetailLabel
private func p_addTextInOptionalLabel() {
let input : Character = "*"
var result = String()
for value in optionalDetail.characters {
if value == input {
optionalDetailLabel.text! += result + "\n"
result = String()
continue
}
result.append(value)
}
}
// MARK: - UITableViewDelegate
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return indexPath.section == 0 ? aHeightTitleCell : aHeightDetailCell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
} |
//
// Operations.swift
// Functional
//
// Created by justin on 3/24/15.
// Copyright (c) 2015 Electroreef. All rights reserved.
//
//https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html#//apple_ref/doc/uid/TP40014097-CH27-XID_65
infix operator | { associativity left precedence 140 }
public func | <A,B> (left:@autoclosure()->A,right: A->B)->B
{
return right(left())
}
|
//
// Constant.swift
// Milestone Project 19-21
//
// Created by Andrei Chenchik on 3/6/21.
//
import Foundation
struct K {
static let noteController = "noteController"
static let tableCell = "tableCell"
}
|
//
// NotificationViewController.swift
// TabBarItem
//
// Created by apple on 2/24/20.
// Copyright © 2020 apple. All rights reserved.
//
import UIKit
import AVKit
class NotificationViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
@IBOutlet weak var videwtable: UITableView!
var videourl = [NSURL(string: "https://v.pinimg.com/videos/720p/77/4f/21/774f219598dde62c33389469f5c1b5d1.mp4"),
NSURL(string: "https://v.pinimg.com/videos/720p/75/40/9a/75409a62e9fb61a10b706d8f0c94de9a.mp4"),
NSURL(string: "https://v.pinimg.com/videos/720p/0d/29/18/0d2918323789eabdd7a12cdd658eda04.mp4"),
NSURL(string: "https://v.pinimg.com/videos/720p/dd/24/bb/dd24bb9cd68e9e25d1def88cad0a9ea7.mp4"),
NSURL(string: "https://v.pinimg.com/videos/720p/5f/aa/3d/5faa3d057eb31dd05876f622ea2e7502.mp4"),
NSURL(string: "https://v.pinimg.com/videos/720p/62/81/60/628160e025f9d61b826ecc921b9132cd.mp4"),
NSURL(string: "https://v.pinimg.com/videos/720p/65/b0/54/65b05496c385c89f79635738adc3b15d.mp4"),
NSURL(string: "https://v.pinimg.com/videos/720p/86/a1/c6/86a1c63fc58b2e1ef18878b7428912dc.mp4")]
override func viewDidLoad() {
super.viewDidLoad()
videwtable.rowHeight = 301
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return videourl.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! VideoTableViewCell
let avPlayer = AVPlayer(url: videourl[indexPath.row]! as URL)
cell.videocell.PlayerLayer.player = avPlayer
cell.videocell.player?.play()
return cell
}
/*
// 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.
}
*/
}
|
//
// Coordinator.swift
// epg
//
// Created by Yakimovich, Kirill on 9/26/17.
// Copyright © 2017 Yakimovich, Kirill. All rights reserved.
//
import UIKit
protocol Coordinator {
var navigationController: UINavigationController { get }
func start()
}
|
//
// InitialViewController.swift
// BodyMetrics
//
// Created by Ken Yu on 11/28/15.
// Copyright © 2015 Ken Yu. All rights reserved.
//
import UIKit
import Parse
public
class InitialViewController: UIViewController {
@IBOutlet weak var usernameButton: UIButton!
@IBOutlet weak var passwordButton: UIButton!
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var usernameWrapperView: UIView!
@IBOutlet weak var passwordWrapperView: UIView!
@IBOutlet weak var noAccountWrapperView: UIView!
@IBOutlet weak var usernameBorderView: UIView!
@IBOutlet weak var passwordBorderView: UIView!
@IBOutlet weak var leftSpacerView: UIView!
@IBOutlet weak var rightSpacerView: UIView!
@IBOutlet weak var signInButton: UIButton!
@IBOutlet weak var signUpButton: UIButton!
@IBOutlet weak var forgotPasswordButton: UIButton!
@IBOutlet weak var noAccountLabel: UILabel!
public static let kTitleLabelFont: UIFont = Styles.Fonts.MediumMedium!
public static let kSignInButtonFont: UIFont = Styles.Fonts.MediumMedium!
public static let kSignUpButtonFont: UIFont = Styles.Fonts.MediumMedium!
public static let kForgotPasswordButtonFont: UIFont = Styles.Fonts.MediumSmall!
public static let kTextFieldFont: UIFont = Styles.Fonts.ThinLarge!
public override func viewDidLoad() {
super.viewDidLoad()
setup()
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
registerKeyboardNotifications()
}
public override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
deregisterKeyboardNotifications()
}
public func setup() {
view.backgroundColor = Styles.Colors.AppDarkBlue
usernameWrapperView.backgroundColor = UIColor.clearColor()
passwordWrapperView.backgroundColor = UIColor.clearColor()
noAccountWrapperView.backgroundColor = UIColor.clearColor()
leftSpacerView.backgroundColor = UIColor.clearColor()
rightSpacerView.backgroundColor = UIColor.clearColor()
signInButton.titleLabel?.font = InitialViewController.kSignInButtonFont
signUpButton.titleLabel?.font = InitialViewController.kSignUpButtonFont
forgotPasswordButton.titleLabel?.font = InitialViewController.kForgotPasswordButtonFont
signInButton.tintColor = Styles.Colors.BarNumber
signUpButton.tintColor = Styles.Colors.BarNumber
forgotPasswordButton.tintColor = Styles.Colors.BarNumber
usernameTextField.font = InitialViewController.kTextFieldFont
passwordTextField.font = InitialViewController.kTextFieldFont
usernameTextField.textColor = Styles.Colors.BarNumber
passwordTextField.textColor = Styles.Colors.BarNumber
usernameTextField.setPlaceholder("Username or email", withColor: Styles.Colors.BarLabel)
passwordTextField.setPlaceholder("Password", withColor: Styles.Colors.BarLabel)
noAccountLabel.font = InitialViewController.kSignUpButtonFont
noAccountLabel.textColor = Styles.Colors.BarLabel
usernameBorderView.backgroundColor = UIColor.whiteColor()
passwordBorderView.backgroundColor = UIColor.whiteColor()
}
@IBAction func didTapSignUp(sender: UIButton) {
}
@IBAction func didTapLogIn(sender: UIButton) {
if let username = usernameTextField.text, password = passwordTextField.text {
PFUser.logInWithUsernameInBackground(username, password: password) { [weak self] (user, error) -> Void in
if let error = error {
// handle UI to show error message
print(error)
} else {
// success, we have user
if let strongSelf = self {
// success, handle
AppDelegate.launchAppControllers()
// strongSelf.dismissViewControllerAnimated(true, completion: { () -> Void in
// AppDelegate.launchAppControllers()
// })
}
}
}
}
}
}
/// Keyboard shit
extension InitialViewController {
public func registerKeyboardNotifications() {
// NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidShow:", name: UIKeyboardDidShowNotification, object: nil)
// NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidShow:", name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
public func deregisterKeyboardNotifications() {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
public func keyboardDidShow(notification: NSNotification) {
if let info = notification.userInfo {
if let keyboardFrameBeginUserInfoKey = info[UIKeyboardFrameBeginUserInfoKey] {
let keyboardSize = keyboardFrameBeginUserInfoKey.CGRectValue.size
let textFieldOrigin = passwordTextField.frame.origin
let textFieldHeight = passwordTextField.height
var visibleRect = self.view.frame
visibleRect.size.height -= keyboardSize.height
if self.view.frame.origin.y >= 0 {
self.view.frame.origin.y -= keyboardSize.height
}
// if !CGRectContainsPoint(visibleRect, textFieldOrigin) {
// let scrollPoint = CGPointMake(0, textFieldOrigin.y - visibleRect.size.height + textFieldHeight)
// self.view.frame.origin.y -= keyboardSize.height
// }
}
}
}
public func keyboardWillHide(notification: NSNotification) {
print("Keyboard will hide")
self.view.frame.origin.y = 0
// if let info = notification.userInfo {
// if let keyboardFrameBeginUserInfoKey = info[UIKeyboardFrameBeginUserInfoKey] {
// let keyboardSize = keyboardFrameBeginUserInfoKey.CGRectValue.size
// let textFieldOrigin = passwordTextField.frame.origin
// let textFieldHeight = passwordTextField.height
// var visibleRect = self.view.frame
// visibleRect.size.height -= keyboardSize.height
//
// self.view.frame.origin.y -= keyboardSize.height
// // if !CGRectContainsPoint(visibleRect, textFieldOrigin) {
// // let scrollPoint = CGPointMake(0, textFieldOrigin.y - visibleRect.size.height + textFieldHeight)
// // self.view.frame.origin.y -= keyboardSize.height
// // }
// }
// }
}
public func keyboardDidChangeFrame(notification: NSNotification) {
print("Keyboard did change frame")
// if let info = notification.userInfo as? NSDictionary {
// if let keyboardFrameBeginUserInfoKey = info.objectForKey(UIKeyboardFrameBeginUserInfoKey) {
// var keyboardSize = keyboardFrameBeginUserInfoKey.CGRectValue.size
// let textFieldOrigin = passwordTextField.frame.origin
// let textFieldHeight = passwordTextField.height
// var visibleRect = self.view.frame
// visibleRect.size.height -= keyboardSize.height
//
// if !CGRectContainsPoint(visibleRect, textFieldOrigin) {
// let scrollPoint = CGPointMake(0, textFieldOrigin.y - visibleRect.size.height + textFieldHeight)
// self.view.frame.origin.y -= keyboardSize.height
// }
// }
// }
// if (!CGRectContainsPoint(visibleRect, buttonOrigin)){
//
// CGPoint scrollPoint = CGPointMake(0.0, buttonOrigin.y - visibleRect.size.height + buttonHeight);
//
// [self.scrollView setContentOffset:scrollPoint animated:YES];
//
// }
}
@IBAction func signUp(sender: UIButton) {
let signUpViewController = SignUpViewController()
presentViewController(signUpViewController, animated: true, completion: nil)
}
}
|
//
// Location+CoreDataClass.swift
// GoToRun
//
// Created by lauda on 17/1/24.
// Copyright © 2017年 lauda. All rights reserved.
//
import Foundation
import CoreData
public class Location: NSManagedObject {
}
|
//
// File.swift
// googleMapz
//
// Created by Macbook on 6/13/21.
//
import Foundation
import MapKit
extension CLLocationCoordinate2D {
static let eventCenter = CLLocationCoordinate2D(latitude: 10.339_400, longitude: 107.082_200)
}
extension MKCoordinateRegion {
static let afterHours = MKCoordinateRegion(center: CLLocationCoordinate2D.eventCenter, latitudinalMeters: 1500, longitudinalMeters: 1500)
}
|
//
// RegisterFormUITextFieldDelegate.swift
// RegisterForm
//
// Created by Ahmed Elbasha on 8/23/18.
// Copyright © 2018 Ahmed Elbasha. All rights reserved.
//
import Foundation
import UIKit
extension RegisterFormViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
switch textField.tag {
case 0, 1, 3:
return true
case 2, 4, 5, 6:
return false
default:
return false
}
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
switch textField.tag {
case 0, 1:
textField.clearButtonMode = .whileEditing
return true
case 2, 3, 4, 5, 6:
return false
default:
return false
}
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
switch textField.tag {
case 0, 1:
return true
case 2, 3, 4, 5, 6:
return false
default:
return false
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
switch textField.tag {
case 0, 1:
textField.text = ""
break
default:
break
}
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
switch textField.tag {
case 0:
if textField.text == "" {
textField.text = "First Name"
textField.resignFirstResponder()
} else {
textField.resignFirstResponder()
}
break
case 1:
if textField.text == "" {
textField.text = "Password"
textField.resignFirstResponder()
} else {
textField.resignFirstResponder()
}
break
default:
break
}
}
}
|
//
// Double+convert.swift
// WaadsuGeoJSONApp
//
// Created by Igor Malyarov on 01.11.2021.
//
import Foundation
extension Double {
/// Convert units of the same unit of measure.
///
/// For example,
/// ```swift
/// let length: Double
/// // ...
/// length.convert(from: .meters, to: .kilometers)
/// ```
func convert(
from originalUnit: UnitLength,
to convertedUnit: UnitLength
) -> Double {
Measurement(
value: self,
unit: originalUnit
)
.converted(to: convertedUnit)
.value
}
}
|
//
// NetworkKit.swift
// SwiftNetWorkFlow
//
// Created by TifaTsubasa on 16/4/25.
// Copyright © 2016年 Upmer Inc. All rights reserved.
// https://api.douban.com/v2/movie/subject/1764796
import Foundation
import Alamofire
enum HttpRequestType: String {
case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
}
class NetworkKit<Model> {
typealias SuccessHandlerType = (AnyObject? -> Void)
typealias ErrorHandlerType = ((Int, AnyObject?) -> Void)
typealias FailureHandlerType = (NSError? -> Void)
typealias FinishHandlerType = (Void -> Void)
typealias ResultHandlerType = (Model -> Void)
typealias ReflectHandlerType = (AnyObject? -> Model)
var type: HttpRequestType!
var url: String?
var params: [String: AnyObject]?
var headers: [String: String]?
var successHandler: SuccessHandlerType?
var errorHandler: ErrorHandlerType?
var failureHandler: FailureHandlerType?
var finishHandler: FinishHandlerType?
var resultHandler: ResultHandlerType?
var reflectHandler: ReflectHandlerType?
var httpRequest: Request?
deinit {
debugPrint("deinit")
}
func reflect(f: ReflectHandlerType) -> Self {
reflectHandler = f
return self
}
func fetch(url: String, type: HttpRequestType = .GET) -> Self {
self.type = type
self.url = url
return self
}
func params(params: [String: AnyObject]) -> Self {
self.params = params
return self
}
func headers(headers: [String: String]) -> Self {
self.headers = headers
return self
}
func finish(handler: FinishHandlerType) -> Self {
self.finishHandler = handler
return self
}
func success(handler: SuccessHandlerType) -> Self {
self.successHandler = handler
return self
}
func result(handler: ResultHandlerType) -> Self {
self.resultHandler = handler
return self
}
func error(handler: ErrorHandlerType) -> Self {
self.errorHandler = handler
return self
}
func failure(handler: FailureHandlerType) -> Self {
self.failureHandler = handler
return self
}
func request() -> Self {
let alamofireType = Method(rawValue: type.rawValue)!
if let url = url {
httpRequest = Alamofire.request(alamofireType, url, parameters: params, encoding: .URL, headers: headers)
.response { request, response, data, error in
self.finishHandler?()
let statusCode = response?.statusCode
if let statusCode = statusCode { // request success
let json: AnyObject? = data.flatMap {
return try? NSJSONSerialization.JSONObjectWithData($0, options: .MutableContainers)
}
if statusCode == 200 {
self.successHandler?(json)
if let reflectHandler = self.reflectHandler {
self.resultHandler?(reflectHandler(json))
}
} else {
self.errorHandler?(statusCode, json)
}
} else { // request failure
self.failureHandler?(error)
}
}
}
return self
}
func cancel() {
httpRequest?.cancel()
}
} |
// RUN: %target-swift-frontend -parse %s
// REQUIRES: objc_interop
import Dispatch
func getAnyValue<T>(_ opt: T?) -> T { return opt! }
// dispatch/io.h
let io = DispatchIO(type: .stream, fileDescriptor: 0, queue: DispatchQueue.main, cleanupHandler: { (error: Int32) -> () in fatalError() })
io.close(flags: .stop)
io.setInterval(interval: 0, flags: .strictInterval)
// dispatch/queue.h
let q = DispatchQueue(label: "", attributes: .serial)
_ = DispatchQueue(label: "", attributes: .concurrent)
_ = q.label
if #available(OSX 10.10, iOS 8.0, *) {
_ = DispatchQueue.global(attributes: .qosUserInteractive)
_ = DispatchQueue.global(attributes: .qosBackground)
_ = DispatchQueue.global(attributes: .qosDefault)
}
// dispatch/source.h
_ = DispatchSource.userDataAdd()
_ = DispatchSource.userDataOr()
_ = DispatchSource.machSend(port: mach_port_t(0), eventMask: [])
_ = DispatchSource.machReceive(port: mach_port_t(0))
_ = DispatchSource.memoryPressure(eventMask: [])
_ = DispatchSource.process(identifier: 0, eventMask: [])
_ = DispatchSource.read(fileDescriptor: 0)
_ = DispatchSource.signal(signal: SIGINT)
_ = DispatchSource.timer()
_ = DispatchSource.fileSystemObject(fileDescriptor: 0, eventMask: [])
_ = DispatchSource.write(fileDescriptor: 0)
// dispatch/time.h
_ = DispatchTime.now()
_ = DispatchTime.distantFuture
|
//
// FeedCollectionCell.swift
// InstagramLab
//
// Created by Brendon Cecilio on 3/9/20.
// Copyright © 2020 Brendon Cecilio. All rights reserved.
//
import UIKit
import Kingfisher
import FirebaseAuth
class FeedCollectionCell: UICollectionViewCell {
@IBOutlet weak var userImageView: UIImageView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var captionLabel: UILabel!
public func updateUI(for item: Item) {
guard let user = Auth.auth().currentUser else {
return
}
userImageView.kf.setImage(with: user.photoURL)
usernameLabel.text = user.email
imageView.kf.setImage(with: URL(string: item.imageURL))
captionLabel.text = item.postCaption
}
}
|
// RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %swift -emit-module -o %t %S/Inputs/cycle-depend/A.swift -I %S/Inputs/cycle-depend -enable-source-import
// RUN: %swift -emit-module -o %t %S/Inputs/cycle-depend/B.swift -I %S/Inputs/cycle-depend -enable-source-import
// RUN: %sourcekitd-test -req=index %t/A.swiftmodule -- %t/A.swiftmodule -I %t | %sed_clean > %t.response
// RUN: diff -u %S/Inputs/cycle-depend/A.response %t.response
|
//
// Created by Jim Wilenius on 2020-06-11.
//
import Foundation
public protocol IEvent : Codable {
}
|
//
// ViewController.swift
// Swift_Delegate
//
// Created by 陈凡 on 15/8/22.
// Copyright (c) 2015年 湖南省 永州市 零陵区 湖南科技学院. All rights reserved.
//
import UIKit
protocol Delegate{
mutating func love()
}
class ChenFan {
var delegate :Delegate!
func love(){
NSLog("陈凡 喜欢 朱茁")
delegate.love()
}
}
class ZhuZhuo :Delegate{
func love() {
NSLog("朱茁 喜欢 陈凡")
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var chenfan = ChenFan()
chenfan.delegate = ZhuZhuo()
chenfan.love()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// Root.swift
// BotanicalGarden
//
// Created by 黃偉勛 Terry on 2021/4/18.
//
import Foundation
public struct Root<T: Decodable>: Decodable {
public let result: Result
public struct Result: Decodable {
public let results: T
}
}
|
//
// ViewController.swift
// Where is Teji's
//
// Created by Stoyanov, Jennifer N on 12/2/18.
// Copyright © 2018 Stoyanov, Jennifer N. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
//Map
@IBOutlet weak var map: MKMapView!
let manager = CLLocationManager()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[0]
let span:MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)
let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let region:MKCoordinateRegion = MKCoordinateRegion(center: myLocation, span: span)
map.setRegion(region, animated: true)
self.map.showsUserLocation = true
}
mapView.userLocation.coordinate
currentLocation!.distance(from: latitudeDelta: 30.266546 longitudeDelta: -97.736376)
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
}
|
//
// TWButton.swift
//
// The MIT License (MIT)
//
// Created by Txai Wieser on 25/02/15.
// Copyright (c) 2015 Txai Wieser.
//
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
//
//
import SpriteKit
class TWButton: TWControl {
// MARK: Initializers
init(normalText: String, highlightedText: String) {
super.init(normalText: normalText, highlightedText: highlightedText, selectedText: normalText, disabledText: normalText)
}
init(normalTexture: SKTexture, highlightedTexture: SKTexture) {
super.init(normalTexture: normalTexture, highlightedTexture: highlightedTexture, selectedTexture: normalTexture, disabledTexture: normalTexture)
}
init(normalColor: SKColor, highlightedColor: SKColor, size:CGSize) {
super.init(normalColor: normalColor, highlightedColor: highlightedColor, selectedColor: normalColor, disabledColor: normalColor, size:size)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Button Methods
var icon:SKSpriteNode? {
willSet {
if let oldValue = icon where oldValue.parent == self {
oldValue.removeFromParent()
}
}
didSet {
if let newValue = icon {
self.addChild(newValue)
newValue.colorBlendFactor = 1
if self.highlighted { newValue.color = self.stateHighlightedFontColor }
else { newValue.color = self.stateNormalFontColor }
}
}
}
override var highlighted:Bool {
set {
super.highlighted = newValue
if newValue { self.icon?.color = self.stateHighlightedFontColor }
else { self.icon?.color = self.stateNormalFontColor }
}
get {
return super.highlighted
}
}
}
|
import SpriteKit
public class Plant {
var x: CGFloat
var y: CGFloat
var name: String = "plant"
var size: Int = 10
var typeNumber: Int = 1
init() {
x = 0
y = 0
}
init(x: CGFloat, y: CGFloat, size: CGFloat) {
self.x = x
self.y = y
}
func getShape() -> SKSpriteNode {
var shape: SKSpriteNode = .init(imageNamed: "plant\(typeNumber)")
shape.position = CGPoint(x: x, y: y)
shape.name = name
shape.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: size, height: size))
shape.physicsBody!.collisionBitMask = 0b0001
shape.physicsBody!.contactTestBitMask = shape.physicsBody!.collisionBitMask
return shape
}
}
|
//
// HomeVC.swift
// ClassyDrives
//
// Created by Mindfull Junkies on 08/06/19.
// Copyright © 2019 Mindfull Junkies. All rights reserved.
//
import UIKit
import CoreLocation
protocol OfferRideDelegate {
func getLocation(_ lat: CLLocationDegrees, _ long:CLLocationDegrees, _ str:String, _ index:Int)
}
class HomeVC: BaseVC, UITextFieldDelegate, OfferRideDelegate{
fileprivate var newStatus:Bool = false
@IBOutlet weak var sosBtn: UIButton!
@IBOutlet var mainImg: UIImageView!
@IBOutlet var exploreBtn: UIButton!
@IBOutlet var offerRideView: UIView!
@IBOutlet var offerRideHeight: NSLayoutConstraint!
@IBOutlet var offerRideTable: UITableView!
@IBOutlet var findRideView: UIView!
@IBOutlet var FindRideHeight: NSLayoutConstraint!
@IBOutlet var findPicTF: UITextField!
@IBOutlet var findDropTF: UITextField!
@IBOutlet var dateTF: UITextField!
@IBOutlet var findNextBtn: UIButton!
@IBOutlet weak var currentRideBtn: UIButton!
@IBOutlet var findPicView: UIView!
@IBOutlet var dropPicView: UIView!
@IBOutlet var dateView: UIView!
@IBOutlet var heightOfferRideTFView: NSLayoutConstraint!
@IBOutlet var offerDropTF: UITextField!
@IBOutlet var offerDateTF: UITextField!
@IBOutlet var offerTimeTF: UITextField!
@IBOutlet var offerNextBtn: UIButton!
@IBOutlet var offerPickupView: UIView!
@IBOutlet var offerdateView: UIView!
@IBOutlet var offerTimeView: UIView!
var lat = String()
var lat1 = String()
var lat2 = String()
var lat3 = String()
var lat4 = String()
var lat5 = String()
var newRide:String = ""
var am_i_booked:String = ""
var long = String()
var long1 = String()
var long2 = String()
var long3 = String()
var long4 = String()
var long5 = String()
var address = String()
var address1 = String()
var address2 = String()
var address3 = String()
var address4 = String()
var address5 = String()
var addArr = [String]()
var addLat = [String]()
var offerDropLat = String()
var offerDropLong = String()
var findPicLat = String()
var findPicLong = String()
var findDropLat = String()
var findDropLong = String()
var text = ["Pickup Location"]
// var images = [#imageLiteral(resourceName: "pickup_location"),#imageLiteral(resourceName: "where_u_go")]
var text1 = ["Pickup Location","Drop Location","Date"]
var image1 = [#imageLiteral(resourceName: "pickup_location"),#imageLiteral(resourceName: "where_u_go"),#imageLiteral(resourceName: "date")]
var offerValue = false
var findValue = false
var offerHeight = 500
var indexValue = 1
var offerDate = String()
var offerTime = String()
var dropLocation = String()
var date = UIDatePicker()
var date1 = UIDatePicker()
var newOfferTime:String = ""
var currentLocation = CLLocation()
var locationManager = CLLocationManager()
var myLocationLat:String?
var myLocationLng:String?
func sosCall()
{
if CLLocationManager.locationServicesEnabled()
&& CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse
{
if let location = locationManager.location
{
currentLocation = location
}
let latii = String(format: "%.8f", currentLocation.coordinate.latitude)
let longi = String(format: "%.8f", currentLocation.coordinate.longitude)
print(latii,longi)
let rideId = UserDefaults.standard.value(forKey: "rideID") as? String ?? ""
let userId = UserDefaults.standard.value(forKey: "LoginID") as? String ?? ""
Indicator.sharedInstance.showIndicator()
UserVM.sheard.panicApi(user_id: userId , ride_id: newRide, lattitude: latii, longitude: longi) { (success, message, error) in
if error == nil{
Indicator.sharedInstance.hideIndicator()
if success{
// self.showAlert(message: message)
// let story = self.storyboard?.instantiateViewController(withIdentifier:"MainTabVC") as! MainTabVC
// DataManager.isLogin = true
// self.navigationController?.pushViewController(story, animated: true)
}else{
// self.showAlert(message: message)
}
}else{
// self.showAlert(message: error?.domain)
}
}
if let url = URL(string: "tel://911"), UIApplication.shared.canOpenURL(url) {
if #available(iOS 10, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}
}
}
}
@IBAction func notificationsBtn(_ sender: Any) {
let story = self.storyboard?.instantiateViewController(withIdentifier: "NotificationVC") as! NotificationVC
self.navigationController?.pushViewController(story, animated: true)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.rideOnlineStatus { (status,ride_id,m_booked) in
if status{
self.newRide = ride_id
self.am_i_booked = m_booked
self.currentRideBtn.isHidden = false
self.sosBtn.isHidden = false
}else{
self.currentRideBtn.isHidden = true
self.sosBtn.isHidden = true
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// self.tabBarController?.hidesBottomBarWhenPushed = false
offerRideTable.isScrollEnabled = false
self.offerRideHeight.constant = 190
self.FindRideHeight.constant = 130
self.heightOfferRideTFView.constant = 0
// exploreBtn.setButtonBorder()
exploreBtn.layer.cornerRadius = exploreBtn.frame.height/2
exploreBtn.layer.borderColor = UIColor.white.cgColor
exploreBtn.layer.borderWidth = 2
exploreBtn.alpha = 0.8
exploreBtn.clipsToBounds = true
offerRideView.setShadow()
offerRideView.layer.cornerRadius = 40
offerRideView.layer.borderColor = UIColor.white.cgColor
offerRideView.layer.borderWidth = 1
offerPickupView.setShadow()
offerdateView.setShadow()
offerTimeView.setShadow()
offerNextBtn.setButtonBorder()
offerDateTF.delegate = self
offerTimeTF.delegate = self
findRideView.setShadow()
findRideView.layer.cornerRadius = 40
findRideView.layer.borderColor = UIColor.white.cgColor
findRideView.layer.borderWidth = 1
findNextBtn.setButtonBorder()
findPicView.setShadow()
dropPicView.setShadow()
dateView.setShadow()
dateTF.placeholder = "Date"
dateTF.delegate = self
//curntDate()
}
func curntDate()->String {
let dateFormatter : DateFormatter = DateFormatter()
// dateFormatter.dateFormat = "yyyy-mmm-dd"
//dateFormatter.dateFormat = "mm-dd-yyy"
dateFormatter.dateFormat = "MM-dd-yyyy"
let date = Date()
let dateString = dateFormatter.string(from: date)
return dateString
// currentDate = dateString
}
func curentRide()
{
let story = self.storyboard?.instantiateViewController(withIdentifier: "OfferedRideDetailsCurrentVC") as! OfferedRideDetailsCurrentVC
// let rideId = UserDefaults.standard.value(forKey: "rideID") as? String
// let bookID = UserDefaults.standard.value(forKey: "bookID") as? String
story.isFromView = true
// story.islocal = UserVM.sheard.allRidesDetails[0].bookedRide[indexPath.row].is_local_ride ?? ""
if am_i_booked == "1"{
story.bookid = ""
//story.isFromCurrentRide = true
story.rideId = newRide
}else{
story.rideId = newRide
//story.isFromCurrentRide = true
story.bookid = ""
}
// story.rideId = newRide
// story.isReceived = true
// story.cancelReason = "usercancel"
self.navigationController?.pushViewController(story, animated: true)
}
@IBAction func currentRideBtnAction(_ sender: Any) {
self.curentRide()
}
@IBAction func sosBtnAction(_ sender: Any) {
self.sosCall()
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == dateTF{
self.date.datePickerMode = .date
if #available(iOS 14.0, *) {
self.date.preferredDatePickerStyle = .wheels
} else {
// Fallback on earlier versions
}
self.date.minimumDate = Date()
self.date.backgroundColor = .white
// self.date.setValue(UIColor.white, forKeyPath: "textColor")
let toolbar = UIToolbar()
toolbar.sizeToFit()
toolbar.backgroundColor = .black
dateTF.inputAccessoryView = toolbar
dateTF.inputView = self.date
let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
let cancelBtn = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(self.cancelBtn))
cancelBtn.tintColor = .white
let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.finddoneAction))
doneBtn.tintColor = .white
toolbar.setItems([cancelBtn,flexSpace,doneBtn], animated: true)
}
else if textField == offerDateTF{
self.date.datePickerMode = .date
if #available(iOS 14.0, *) {
self.date.preferredDatePickerStyle = .wheels
} else {
// Fallback on earlier versions
}
self.date.minimumDate = Date()
self.date.backgroundColor = .white
//x self.date.setValue(UIColor.white, forKeyPath: "textColor")
let toolbar = UIToolbar()
toolbar.sizeToFit()
toolbar.backgroundColor = .black
offerDateTF.inputAccessoryView = toolbar
offerDateTF.inputView = self.date
let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
let cancelBtn = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(self.cancelBtn))
cancelBtn.tintColor = .white
let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.doneAction))
doneBtn.tintColor = .white
toolbar.setItems([cancelBtn,flexSpace,doneBtn], animated: true)
}
else if textField == offerTimeTF{
// self.date1.datePickerMode = .time
// self.date1.minimumDate = Date()
print(Date().toString(format: "MM-dd-yyyy"))
if offerDateTF.text ?? "" == Date().toString(format: "MM-dd-yyyy"){
self.date1.minimumDate = Date()
self.date1.datePickerMode = .time
if #available(iOS 14.0, *) {
self.date1.preferredDatePickerStyle = .wheels
} else {
// Fallback on earlier versions
}
}else{
date1 = UIDatePicker()
self.date1.datePickerMode = .time
if #available(iOS 14.0, *) {
self.date1.preferredDatePickerStyle = .wheels
} else {
// Fallback on earlier versions
}
}
self.date1.backgroundColor = .white
// self.date1.setValue(UIColor.white, forKeyPath: "textColor")
let toolbar1 = UIToolbar()
toolbar1.sizeToFit()
toolbar1.backgroundColor = .black
offerTimeTF.inputAccessoryView = toolbar1
offerTimeTF.inputView = self.date1
let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
let cancelBtn1 = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(self.cancelBtn))
cancelBtn1.tintColor = .white
let doneBtn1 = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(self.doneActionTime))
doneBtn1.tintColor = .white
toolbar1.setItems([cancelBtn1,flexSpace,doneBtn1], animated: true)
}
}
@objc func finddoneAction() {
let formatter = DateFormatter()
formatter.dateFormat = "MM-dd-yyyy"
dateTF.text = "\(formatter.string(from: date.date))"
self.view.endEditing(true)
offerRideTable.reloadData()
}
func getLocation(_ lat: CLLocationDegrees, _ long:CLLocationDegrees, _ str:String, _ index:Int) {
print(str)
print(lat)
print(long)
print(index)
if index <= 2{
newStatus = true
text[index] = str
}
if index == 0{
self.lat = "\(lat)"
self.long = "\(long)"
self.address = str
}else if index == 1{
self.lat1 = "\(lat)"
self.long1 = "\(long)"
self.address1 = str
}else if index == 2{
self.lat2 = "\(lat)"
self.long2 = "\(long)"
self.address2 = str
}else if index == 3{
self.offerDropLat = "\(lat)"
self.offerDropLong = "\(long)"
self.offerDropTF.text = str
}
else if index == 4{
self.findPicLat = "\(lat)"
self.findPicLong = "\(long)"
findPicTF.text = str
}else if index == 5{
self.findDropLat = "\(lat)"
self.findDropLong = "\(long)"
findDropTF.text = str
}
offerRideTable.reloadData()
}
@IBAction func findRideBtnAtn(_ sender: Any) {
UIView.animate(withDuration: 0.5) {
if self.findValue == false && self.offerValue == false{
self.offerRideHeight.constant = 400
self.FindRideHeight.constant = 350
self.heightOfferRideTFView.constant = 0
self.view.layoutIfNeeded()
self.findValue = true
self.offerValue = false
}
else if self.offerValue == false && self.findValue == true{
self.offerRideHeight.constant = 190
self.FindRideHeight.constant = 130
self.heightOfferRideTFView.constant = 0
self.view.layoutIfNeeded()
self.findValue = false
self.offerValue = false
}
else if self.offerValue == true && self.findValue == false{
self.offerRideHeight.constant = 400
self.FindRideHeight.constant = 350
self.heightOfferRideTFView.constant = 50
self.view.layoutIfNeeded()
self.findValue = true
self.offerValue = false
}
}
}
@IBAction func findPicLocationBtnAtn(_ sender: Any) {
let story = self.storyboard?.instantiateViewController(withIdentifier: "MapVC") as! MapVC
story.index = 4
story.delegate = self
self.navigationController?.pushViewController(story, animated: true)
}
@IBAction func dropLocationBtnAtn(_ sender: Any) {
let story = self.storyboard?.instantiateViewController(withIdentifier: "MapVC") as! MapVC
story.index = 5
story.delegate = self
self.navigationController?.pushViewController(story, animated: true)
}
@IBAction func findNextBtnAtn(_ sender: Any) {
if findPicTF.text!.isEmpty && findDropTF.text!.isEmpty && dateTF.text!.isEmpty{
showAlert(message: "Please fill the required data.")
}else{
findRide(fromAdd: findPicTF.text!, toAdd: findDropTF.text!, fromLat: findPicLat, fromLong: findPicLong, to_lat: findDropLat, to_Long: findDropLong)
}
}
@IBAction func exploreBtnAtn(_ sender: Any) {
let story = storyboard?.instantiateViewController(withIdentifier: "LocalRideVC") as! LocalRideVC
navigationController?.pushViewController(story, animated: true)
}
@IBAction func offerRideBtnAtn(_ sender: Any) {
UIView.animate(withDuration: 0.5) {
if self.offerValue == false && self.findValue == false{
self.offerRideHeight.constant = CGFloat(self.offerHeight)
self.heightOfferRideTFView.constant = 335
self.FindRideHeight.constant = 130
self.offerValue = true
self.findValue = false
self.view.layoutIfNeeded()
}else if self.offerValue == true && self.findValue == false{
self.offerRideHeight.constant = 190
self.FindRideHeight.constant = 130
self.heightOfferRideTFView.constant = 0
self.offerValue = false
self.findValue = false
self.view.layoutIfNeeded()
}
else if self.offerValue == false && self.findValue == true{
self.offerRideHeight.constant = CGFloat(self.offerHeight)
self.FindRideHeight.constant = 130
self.heightOfferRideTFView.constant = 335
self.offerValue = true
self.findValue = false
self.view.layoutIfNeeded()
}
}
}
@IBAction func offerDropBtnAtn(_ sender: Any) {
let story = self.storyboard?.instantiateViewController(withIdentifier: "MapVC") as! MapVC
story.index = 3
story.delegate = self
self.navigationController?.pushViewController(story, animated: true)
}
func covertDate(date : String) -> String
{
let dateString = date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateObj = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: dateObj ?? Date()))")
return dateFormatter.string(from: dateObj ?? Date())
}
@IBAction func offerNextBtnAtn(_ sender: Any) {
if self.lat == "" && offerDropTF.text!.isEmpty && offerDateTF.text!.isEmpty && offerTimeTF.text!.isEmpty{
self.showAlert(message: "Please fill all data")
}else{
let story = self.storyboard?.instantiateViewController(withIdentifier: "RideDetailsVC") as! RideDetailsVC
story.rideFromAdd = address
story.rideFromLat = lat
story.rideFromLong = long
story.address2 = address1
story.rideLat2 = lat1
story.rideLong2 = long1
story.address3 = address2
story.rideLat3 = lat2
story.rideLong3 = long2
story.rideToAdd = offerDropTF.text!
story.rideToLat = offerDropLat
story.rideToLong = offerDropLong
story.ridedate = self.offerDateTF.text ?? ""
story.rideTime = self.offerTimeTF.text ?? ""
self.navigationController?.pushViewController(story, animated: true)
}
}
}
extension HomeVC : UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if text.count < 3 {
return text.count + 1
}
return text.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == text.count {
print(text)
tableView.register(UINib.init(nibName: "addStopCellFile", bundle: nil), forCellReuseIdentifier: "addStopCellFile")
let cell = tableView.dequeueReusableCell(withIdentifier: "addStopCellFile") as! addStopCellFile
cell.addStpBtn.isHidden = false
cell.addStopAtn = { (action) in
let story = self.storyboard?.instantiateViewController(withIdentifier: "MapVC") as! MapVC
cell.addStpBtn.isHidden = false
story.index = indexPath.row
story.delegate = self
story.boolPickup = true
self.navigationController?.pushViewController(story, animated: true)
self.text.append("")
self.indexValue = self.indexValue + 1
if self.text.count < 3 {
self.offerHeight = self.offerHeight + 50
cell.addStpBtn.isHidden = false
} else {
cell.addStpBtn.isHidden = true
}
self.offerRideHeight.constant = CGFloat(self.offerHeight)
tableView.reloadData()
}
return cell
}else{
if indexPath.row == 0 {
tableView.register(UINib.init(nibName: "offerRideCellFile", bundle: nil), forCellReuseIdentifier: "offerRideCellFile")
let cell = tableView.dequeueReusableCell(withIdentifier:
"offerRideCellFile") as! offerRideCellFile
if newStatus{
cell.cellName.text = text[indexPath.row]
}else{
cell.cellName.placeholder = text[indexPath.row]
}
cell.cellName.textColor = .black
cell.cellAtn = { (action) in
let story = self.storyboard?.instantiateViewController(withIdentifier: "MapVC") as! MapVC
story.index = indexPath.row
story.delegate = self
story.boolPickup = false
self.navigationController?.pushViewController(story, animated: true)
}
return cell
} else {
tableView.register(UINib.init(nibName: "offerRidetnCellFile", bundle: nil), forCellReuseIdentifier: "offerRidetnCellFile")
let cell = tableView.dequeueReusableCell(withIdentifier: "offerRidetnCellFile") as! offerRidetnCellFile
cell.locationNameTF.text = text[indexPath.row]
cell.locationNameTF.textColor = .black
cell.addLocationAtn = { (action) in
let story = self.storyboard?.instantiateViewController(withIdentifier: "MapVC") as! MapVC
story.index = indexPath.row
story.delegate = self
story.boolPickup = false
self.navigationController?.pushViewController(story, animated: true)
}
cell.cellAtn = { (action) in
self.text.remove(at: indexPath.row)
if self.text.count < 2 {
self.offerHeight = self.offerHeight - 50
}
tableView.reloadData()
self.offerRideHeight.constant = CGFloat(self.offerHeight)
}
return cell
}
}
}
@objc func doneAction() {
let formatter = DateFormatter()
formatter.dateFormat = "MM-dd-yyyy"
offerDateTF.text = "\(formatter.string(from: date.date))"
self.view.endEditing(true)
offerRideTable.reloadData()
}
@objc func doneActionTime(sender: UITextField){
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm a"
offerTimeTF.text = "\(formatter.string(from: date1.date))"
self.view.endEditing(true)
offerRideTable.reloadData()
}
@objc func cancelBtn(){
self.view.endEditing(true)
}
}
//MARK: - API Methods
extension HomeVC{
func findRide(fromAdd: String, toAdd: String, fromLat: String, fromLong: String, to_lat: String, to_Long: String) {
UserVM.sheard.allRideDetails.removeAll()
Indicator.sharedInstance.showIndicator()
UserVM.sheard.findRide(userid: userID, from_address: fromAdd, to_address: toAdd, from_lat: fromLat, from_long: fromLong, to_lat: to_lat, to_long: to_Long, date: dateTF.text ?? "", price: "ASC", is_local_ride: "0") { (success, message, error) in
if error == nil{
Indicator.sharedInstance.hideIndicator()
if success{
print(UserVM.sheard.allRideDetails)
let story = self.storyboard?.instantiateViewController(withIdentifier:"allRides") as! allRides
story.topvalue = "\(fromAdd)"
story.bottomValue = toAdd
story.rideFromAdd = fromAdd
story.rideFromLat = fromLat
story.rideFromLong = fromLong
story.rideToAdd = toAdd
story.rideToLat = to_lat
story.rideToLong = to_Long
story.date = self.dateTF.text!
self.navigationController?.pushViewController(story, animated: true)
}else{
self.showAlert(message: message)
}
}else{
self.showAlert(message: error?.domain)
}
}
}
}
extension Date {
func toString(format: String = "yyyy-MM-dd") -> String {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.dateFormat = format
return formatter.string(from: self)
}
}
|
//
// InfoCell.swift
// FastStyleTransferDemo
//
// Created by Arthur Tonelli on 4/18/20.
// Copyright © 2020 Arthur Tonelli. All rights reserved.
//
import UIKit
class InfoCell: UITableViewCell {
@IBOutlet weak var fieldNameLabel: UILabel!
@IBOutlet weak var infoLabel: UILabel!
}
|
//
// ServerHelper.swift
// Bottle
//
// Created by Will Schreiber on 12/30/16.
// Copyright © 2016 lxv. All rights reserved.
//
import Foundation
import UIKit
import Alamofire
class ServerHelper {
static func URLWithMethod(_ method: String, objectID: String? = nil, additionalSpecifier: String? = nil, additionalSpecifierID: String? = nil) -> String {
var withObjectId = ""
if let objectID = objectID {
withObjectId = "/\(objectID)"
}
var withAdditionalSpecifier = ""
if let additionalSpecifier = additionalSpecifier {
withAdditionalSpecifier = "/\(additionalSpecifier)"
}
var withAdditionalSpecifierID = ""
if let additionalSpecifierID = additionalSpecifierID {
withAdditionalSpecifierID = "/\(additionalSpecifierID)"
}
return "\(GlobalVariables.rootURL)\(method)\(withObjectId)\(withAdditionalSpecifier)\(withAdditionalSpecifierID).json"
}
static func authorizationHelper(user: User) -> HTTPHeaders {
var headers: HTTPHeaders = [:]
if let authorizationHeader = Request.authorizationHeader(user: user.handle!, password: user.password!) {
headers[authorizationHeader.key] = authorizationHeader.value
}
print(headers)
return headers
}
static func updatedSince(withMethod: String, updatedSince: Double?) -> Double {
var methodUpdatedSince: Double = 0.0
if let updatedSince = updatedSince {
methodUpdatedSince = updatedSince
} else {
methodUpdatedSince = SyncBrain.getUpdatedSince(forMethod: withMethod)
}
return methodUpdatedSince
}
}
|
/*
Mastering Swift
Copyright (c) 2022 KxCoding
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.
*/
//: [Previous](@previous)
import Foundation
/*:
# Comparable for Classes
*/
enum MembershipGrade {
case normal
case premium
case vip
case vvip
}
class Membership {
let name: String
let grade: MembershipGrade
let point: Int
init(name: String, grade: MembershipGrade, point: Int) {
self.name = name
self.grade = grade
self.point = point
}
}
let a = Membership(name: "James", grade: .premium, point: 123)
let b = Membership(name: "Yuna", grade: .vvip, point: 2020)
let c = Membership(name: "Paul", grade: .normal, point: 37)
a < b
b > c
|
//
// CropProfileViewController.swift
// CropBook
//
// Created by Bowen He on 2018-07-03.
// Copyright © 2018 CMPT276-Group15. All rights reserved.
//
import UIKit
import Firebase
class CropProfileViewController: UIViewController {
@IBOutlet weak var cropImage: UIImageView!
@IBOutlet weak var notifText: UITextField!
@IBOutlet weak var waterAmount: UILabel!
@IBOutlet weak var plantCare: UILabel!
@IBOutlet weak var feeding: UILabel!
@IBOutlet weak var spacing: UILabel!
@IBOutlet weak var note: UILabel!
@IBOutlet weak var harvesting: UILabel!
@IBOutlet weak var notificationBtn: UIButton!
@IBOutlet weak var calcBtn: UIButton!
@IBOutlet weak var resetBtn: UIButton!
@IBOutlet weak var image: UIImageView!
var gardenIndex = 0
var myIndex = 0
var crop: CropProfile!
var garden:MyGarden?
var waterAmll:Double = 0.00
let ref = Database.database().reference()
override func viewDidLoad() {
notificationBtn.layer.cornerRadius = 5
calcBtn.layer.cornerRadius = 5
resetBtn.layer.cornerRadius = 5
super.viewDidLoad()
let midGrowth = crop?.GetWateringVariable().getMid()
weather.UpdateWaterRequirements(coEfficient: midGrowth!)
//crop = (GardenList[gardenIndex]?.cropProfile[myIndex])!
//cropName.topItem?.title = crop.GetCropName()
plantCare.text = "Plant Care: " + (crop?.getCare())!
feeding.text = "Feeding: " + (crop?.getFeeding())!
spacing.text = "Spacing: " + (crop?.getSpacing())!
note.text = "Note: " + (crop?.getNotes())!
harvesting.text = "Harvesting: " + (crop?.getHarvesting())!
cropImage.image = UIImage(named: (crop?.getImage())!)
waterAmount.text = String(waterAmll) + " (ml)/ day"
self.title = crop?.GetCropName();
}
override func viewDidAppear(_ animated: Bool) {
}
// Dispose of any resources that can be recreated.
func isStringInt(theString : String) -> Bool{
return Int(theString) != nil
}
/*
Displaying notification for seconds for demonstration purposes
*/
@IBAction func setNotification(_ sender: Any) {
calculateWater(sender)
var notifMsg = "You need to water " + String(waterAmll) + " ml today."
// Used this to test notification -- should give notification after 1 minute
if isStringInt(theString : notifText.text!){
crop?.setNotification(Hours: Int(notifText.text!)!,msg : notifMsg)
}
}
@IBAction func calculateWater(_ sender: Any) {
let midGrowth = crop?.GetWateringVariable().getMid()
weather.UpdateWaterRequirements(coEfficient: midGrowth!)
waterAmll = Double(weather.GetWaterRequirements())/10*crop.surfaceArea!
waterAmll = Double( round(100*waterAmll)/100)
viewDidLoad()
}
@IBAction func ResetSize(_ sender: Any) {
//it pops up a screen asking user for a new XY input for calcualting the surfaceArea.
ResetPlotSize()
}
func ResetPlotSize(){
let alertController = UIAlertController(title: "New Plot Size", message: "Enter new length and width", preferredStyle: .alert)
alertController.addTextField { (textField) in
textField.placeholder = "Length"
}
alertController.addTextField { (textField) in
textField.placeholder = "Width"
}
let changeAction = UIAlertAction(title: "Change", style: .default) { (_) in
let lengthField = alertController.textFields![0]
let widthField = alertController.textFields![1]
let length = lengthField.text
let width = widthField.text
if length != "" && width != "" {
let gardenID = self.garden?.gardenID
let cropRef = self.ref.child("Gardens/\(gardenID!)/CropList/\(self.crop.cropID!)/SurfaceArea")
let plotX = (length! as NSString).doubleValue
let plotY = (width! as NSString).doubleValue
self.crop.coreData?.plotLength = Double(plotX)
self.crop.coreData?.plotWidth = Double(plotY)
let newArea=plotX*plotY
cropRef.setValue(newArea)
self.crop.surfaceArea = newArea
} else {
alertController.dismiss(animated: true, completion: nil)
let alert = UIAlertController(title: "Missing Entries", message: nil, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { (action) in
alert.dismiss(animated:true, completion:nil)
}))
self.present(alert, animated: true, completion: nil)
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
alertController.addAction(changeAction)
alertController.addAction(cancelAction)
DispatchQueue.main.async {
self.present(alertController, animated: true, completion: nil)
}
}
}
|
//
// ViewController.swift
// moviesTest
//
// Created by Nikita Thomas on 8/27/19.
// Copyright © 2019 Nikita Thomas. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
let cellIdentifier = "cell"
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
<#code#>
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
<#code#>
}
}
extension ViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
<#code#>
}
}
|
//
// WeatherForecastsModels.swift
// WeatherApp
//
// Created by Alvyn SILOU on 06/10/2018.
// Copyright (c) 2018 Alvyn SILOU. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
enum WeatherForecasts
{
// MARK: Use cases
enum FetchWeatherData
{
struct Request
{
}
struct Response
{
var interimStatements: [Date: [DailyInterimStatement]]
}
struct ViewModel
{
struct DaysWeatherData {
let date: Date
let minTemperature: Int
let maxTemperature: Int
}
let weatherData: [DaysWeatherData]
}
}
enum ShowDetails
{
struct Request
{
let date: Date
}
struct Response
{
}
struct ViewModel
{
}
}
}
|
//
// Equation.swift
// NodeDomain
//
// Created by Jure Mocnik Berljavac on 10/10/2021.
//
import Foundation
public struct ComputationObject<LHS: LHSField, RHS: RHSField>{
let lhs: LHS
let rhs: RHS
@usableFromInline
internal init (lhs: LHS, rhs: RHS) {
self.lhs = lhs
self.rhs = rhs
}
}
extension LHSField {
// func isEqualTo<RHS: RHSField>(rhs: ()->RHS) -> ComputationObject<Self, RHS> {
// return ComputationObject(lhs: self, rhs: rhs())
// }
@inlinable
public func isEqualTo<RHS: RHSField>(_ rhs: RHS) -> ComputationObject<Self, RHS> {
return ComputationObject(lhs: self, rhs: rhs)
}
}
@inlinable
public func ==<LHS: LHSField, RHS: RHSField>(lhs: LHS, rhs: RHS) -> ComputationObject<LHS, RHS> {
return lhs.isEqualTo(rhs)
}
@resultBuilder
public enum EquationBuilder {
@inlinable
public static func buildBlock<LHS,RHS>(_ v: ComputationObject<LHS,RHS>) -> ComputationObject<LHS,RHS>
{ v }
@inlinable
public static func buildBlock<LHS1,RHS1, LHS2, RHS2>(_ v: ComputationObject<LHS1,RHS1>, _ u: ComputationObject<LHS2,RHS2>)
-> (ComputationObject<LHS1,RHS1>,ComputationObject<LHS2,RHS2>)
{ (v,u) }
@inlinable
public static func buildBlock<LHS1,RHS1, LHS2, RHS2, LHS3, RHS3>
(_ v: ComputationObject<LHS1,RHS1>, _ u: ComputationObject<LHS2,RHS2>, _ w: ComputationObject<LHS3,RHS3>)
-> (ComputationObject<LHS1,RHS1>,ComputationObject<LHS2,RHS2>,ComputationObject<LHS3,RHS3>)
{ (v,u,w) }
@inlinable
public static func buildBlock<LHS1,RHS1, LHS2, RHS2, LHS3, RHS3, LHS4, RHS4>
(_ v: ComputationObject<LHS1,RHS1>, _ u: ComputationObject<LHS2,RHS2>, _ w: ComputationObject<LHS3,RHS3>, _ z: ComputationObject<LHS4, RHS4>)
-> (ComputationObject<LHS1,RHS1>,ComputationObject<LHS2,RHS2>,ComputationObject<LHS3,RHS3>, ComputationObject<LHS4, RHS4>)
{ (v,u,w,z) }
}
|
//
// FeedLoader.swift
// Feed
//
// Created by Stas Lee on 12/1/19.
// Copyright © 2019 Stas Lee. All rights reserved.
//
import Foundation
public protocol FeedLoader {
typealias Result = Swift.Result<[FeedImage], Error>
func load(completion: @escaping (Result) -> Void)
}
|
//
// Command+Answers.swift
//
//
// Created by Vladislav Fitc on 19/11/2020.
//
import Foundation
extension Command {
enum Answers {
struct Find: AlgoliaCommand {
let method: HTTPMethod = .post
let callType: CallType = .read
let path: URL
let body: Data?
let requestOptions: RequestOptions?
init(indexName: IndexName,
query: AnswersQuery,
requestOptions: RequestOptions?) {
self.requestOptions = requestOptions
self.path = URL
.answers
.appending(indexName)
.appending(.prediction)
self.body = query.httpBody
}
}
}
}
|
//
// ConfigMethod.swift
// ObjcTools
//
// Created by douhuo on 2021/2/18.
// Copyright © 2021 wangergang. All rights reserved.
//
// MARK: - 弹框的显示
/**
* 弹框的显示
*/
func showMsg(_ msg: String) {
if msg.count > 0 {
appWindow().makeToast(msg,duration:1.5, position: ToastPosition.center)
}
}
/**
* 这个屏幕
*/
func appwindowBounds() -> CGRect{
return appw?.bounds ?? CGRect.init(x: 0, y: 0, width: SRNW, height: SRNH)
}
/**
* 获取 window
*/
func appWindow() -> UIWindow {
return appw ?? UIApplication.shared.keyWindow!
}
/** 信息打印 */
func PrintLog<T>(_ message: T, file: String = #file, method: String = #function, line: Int = #line) {
// #if DEBUG
//
// debugPrint("=======================================================")
// debugPrint("file >>> \((file as NSString).lastPathComponent) <<<")
// debugPrint("METHOD: >>> \(method) <<<")
// debugPrint("LINE: >>> \(line) <<<")
// debugPrint("打印信息--> Message:")
// debugPrint(message)
// debugPrint("<--打印信息")
// debugPrint("Time: >>> 时间:时间戳(13位):\(Date().currentMilliStamp) <<<")
// debugPrint("Time: >>> 时间:\("\(Date().currentTimeStamp)".transformTimestamptoDate("yyyy-MM-dd HH:mm:ss EEE")) <<<")
// #endif
#if DEBUG
print("""
=======================================================
file :\((file as NSString).lastPathComponent)
METHOD:\(method)
LINE :\(line)
打印信息--> Message:
\(message)
<--打印信息
Time:时间戳(13位):\(Date().currentMilliStamp)
Time:\("\(Date().currentTimeStamp)".transformTimestamptoDate("yyyy-MM-dd HH:mm:ss EEE"))
=======================================================
""")
#endif
}
// MARK: - 获取当前显示的控制器
func getCurrentVC() -> UIViewController? {
var currVC: UIViewController? = nil
var rootVC: UIViewController? = appWindow().rootViewController
repeat {
if (rootVC is UINavigationController) {
let nav = rootVC as? UINavigationController
let v: UIViewController? = nav?.viewControllers.last
currVC = v
rootVC = v?.presentedViewController
continue
} else if (rootVC is UITabBarController) {
let tabVC = rootVC as? UITabBarController
currVC = tabVC
rootVC = tabVC?.viewControllers?[tabVC?.selectedIndex ?? 0]
continue
}else if (rootVC is UIViewController) {
currVC = rootVC
break
}
} while rootVC != nil
return currVC
}
|
//
// WebServiceManager.swift
// photobomb
//
// Created by BJ Griffin on 7/18/15.
// Copyright © 2015 mojo. All rights reserved.
//
import UIKit
import Parse
import CoreData
class WebServiceManager {
class var sharedInstance : WebServiceManager {
struct Static {
static let instance : WebServiceManager = WebServiceManager()
}
return Static.instance
}
//MARK: Private Methods
private func createHashtagPFObjectArray(hashtagStrings:[String], photo:PFObject) -> [PFObject] {
var hashtagObjects = [PFObject]()
for tag in hashtagStrings {
let hashtag = PFObject(className: "Hashtag")
hashtag["tag"] = tag
hashtag["photo"] = photo
hashtag.saveInBackgroundWithBlock({(success, error) -> Void in
if !success {
if let error = error {
print(error)
}
}
})
hashtagObjects.append(hashtag)
}
return hashtagObjects
}
//MARK: Create Methods
func savePhoto(image:UIImage, caption:String, hashtags:[String], completion:(error:NSError?) -> ()) {
let photo = PFObject(className: "Photo")
if let data = UIImageJPEGRepresentation(image, 0.5) {
let imageFile = PFFile(data:data)
photo["image"] = imageFile
photo["caption"] = caption
photo["hashtags"] = createHashtagPFObjectArray(hashtags, photo:photo)
photo["imageIdentifier"] = NSUUID().UUIDString
photo.saveInBackgroundWithBlock({(success, error) -> Void in
if !success {
if let error = error {
print(error)
}
}
completion(error: error)
})
}
}
func createComment() {
// var list = PFObject(className: "Comment")
// list["image"] = UIImage()
// list["name"] = name
// list.saveInBackgroundWithBlock({(success:Bool, error:NSError?) -> Void in
// if success {
//
// } else {
// if let error = error {
// print(error)
// }
// }
// })
}
func createLocation() {
// var list = PFObject(className: "Location")
// list["image"] = UIImage()
// list["name"] = name
// list.saveInBackgroundWithBlock({(success:Bool, error:NSError?) -> Void in
// if success {
//
// } else {
// if let error = error {
// print(error)
// }
// }
// })
}
//MARK: Fetch Methods
func fetchUser() {
let query = PFQuery(className:"User")
query.getObjectInBackgroundWithId("xWMyZEGZ") {
(gameScore: PFObject?, error: NSError?) -> Void in
if error == nil && gameScore != nil {
print(gameScore)
} else {
print(error)
}
}
}
func fetchComments() {
let query = PFQuery(className:"Comment")
query.getObjectInBackgroundWithId("xWMyZEGZ") {
(gameScore: PFObject?, error: NSError?) -> Void in
if error == nil && gameScore != nil {
print(gameScore)
} else {
print(error)
}
}
}
func fetchLocation() {
let query = PFQuery(className:"Location")
query.getObjectInBackgroundWithId("xWMyZEGZ") {
(gameScore: PFObject?, error: NSError?) -> Void in
if error == nil && gameScore != nil {
print(gameScore)
} else {
print(error)
}
}
}
}
|
import UIKit
// MARK: Variable
var str = "Hello, playground"
str = "Hello, SwiftUI"
// MARK: String and Integer
var language = "Swift"
var age = 38
var population = 8_000_000_000
// MARK: Note
// Swift let's you use underscores as thousands separators do make it easier to read.
// MARK: Multi-line strings
// Standard Swift string use double quotes, but you can't include line breaks in there.
var str1 = """
This goes
over multiple
lines
"""
// NOTES: The str1 have line breaks, if you don't want those line breaks to actually be in your string, end each line with a \, like this:
var str2 = """
This goes \
over multiple \
lines
"""
// MARK: Doubles and Booleans
var pi = 3.141
var awesome = true
// Integers hold whole numbers, doubles hold fractional numbers, and booleans hold true or false.
// MARK: String Interpolation
var score = 85
var strOne = "Your score was \(score)"
// MARK: Constants
// The let keywoard creates constants, which are values that can be set once and never again.
let taylor = "Swift"
// MARK: Type Annotations
let album: String = "Reputation"
let year: Int = 1989
let height: Double = 1.78
let taylorRocks: Bool = true
// MARK: SUMMARY
//You’ve made it to the end of the first part of this series, so let’s summarize.
//
//You make variables using var and constants using let. It’s preferable to use constants as often as possible.
//Strings start and end with double quotes, but if you want them to run across multiple lines you should use three sets of double quotes.
//Integers hold whole numbers, doubles hold fractional numbers, and booleans hold true or false.
//String interpolation allows you to create strings from other variables and constants, placing their values inside your string.
//Swift uses type inference to assign each variable or constant a type, but you can provide explicit types if you want.
|
//
// LinearRing+MapKit.swift
// MiniGeo
//
// Created by Christian Rühl on 16.02.18.
// Copyright © 2018 Objectix Software Solutions GmbH. All rights reserved.
//
import Foundation
import MapKit
public extension LinearRing {
// Initializes a ring from a list of MKMapPoints.
convenience init(mapkitPoints: [MKMapPoint]) {
assert(!mapkitPoints.isEmpty)
self.init(coordinates: mapkitPoints.map({ (mapPoint) -> Coordinate2D in
return Coordinate2D(mapkitPoint: mapPoint)
}))
}
// Initializes a ring from a MapKit Polygon (using its exterior boundary only).
convenience init(mapkitPolygon: MKPolygon) {
let points: [Coordinate2D] = Array(UnsafeBufferPointer(start: mapkitPolygon.points(), count: mapkitPolygon.pointCount)).map { (mapkitPoint) -> Coordinate2D in
return Coordinate2D(mapkitPoint: mapkitPoint)
}
self.init(coordinates: points)
}
// Returns the coordinates of this geometry as MapKit points.
func mapkitPoints() -> [MKMapPoint] {
return coordinates.map { (coordinate) -> MKMapPoint in
return coordinate.mapkitPoint()
}
}
// Creates a MKPolygon shape from this geometry
func mapkitPolygon() -> MKPolygon {
let points: [MKMapPoint] = mapkitPoints()
return MKPolygon(points: UnsafePointer<MKMapPoint>(points), count: points.count)
}
}
|
//
// SingleItemViewController.swift
// KikoBusiness
//
// Created by Leonardo Lanzinger on 16/05/15.
// Copyright (c) 2015 Massimo Frasson. All rights reserved.
//
import UIKit
class SingleItemViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var imageSingleView: UIImageView!
@IBOutlet weak var ingredientTable: UITableView!
var imageInspiration : Inspiration!
override func viewDidLoad() {
super.viewDidLoad()
ingredientTable.delegate = self
ingredientTable.dataSource = self
//imageSingleView.image = UIImage(named: imageInspiration.imageFileLocal)
imageSingleView.image = UIImage.animatedImageWithAnimatedGIFURL( NSURL(string: imageInspiration.imageFile))
self.reloadInputViews()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return imageInspiration.ingredientsList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as! IngredientCell
cell.setContents(UIImage(named: imageInspiration.ingredientsList[indexPath.item].ingredientImage)!, name: imageInspiration.ingredientsList[indexPath.item].ingredientTitle, desc: imageInspiration.ingredientsList[indexPath.item].ingredientDescription)
return cell
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// ViewController.swift
// nazarov-set
//
// Created by user147983 on 12/17/18.
// Copyright © 2018 user147983. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
//@IBOutlet var cardButtons: [SetUIButton]!
@IBOutlet weak var dealThreeMoreCardsButton: UIButton!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var setGameView: SetGameView!{
didSet {
let swipe = UISwipeGestureRecognizer(target: self,
action: #selector(onSwipe))
swipe.direction = .down
setGameView.addGestureRecognizer(swipe)
let rotate = UIRotationGestureRecognizer(target: self,
action: #selector(onRotation))
setGameView.addGestureRecognizer(rotate)
}
}
let setGame = SetGame()
override func viewDidLoad() {
super.viewDidLoad()
updateViewFromModel()
}
@objc private func onSwipe(){
dealMoreCards() }
@objc private func onRotation(){
setGame.reshuffle()
updateViewFromModel()
}
private func updateViewFromModel() {
scoreLabel.text = "Score: \(setGame.score)"
updateCardsViewFromModel()
}
private func updateCardsViewFromModel(){
removeUnusedCardViews()
for index in setGame.cardsInGame.indices {
let card = setGame.cardsInGame[index]
if index >= (setGameView.cardViews.count) {
let cardView = SetCardView()
updateCardView(forView: cardView, withModel: card)
addTapListener(forCardView: cardView)
setGameView.cardViews.append(cardView)
} else {
let cardView = setGameView.cardViews [index]
updateCardView(forView: cardView, withModel: card)
}
}
}
private func removeUnusedCardViews(){
if setGameView.cardViews.count - setGame.cardsInGame.count > 0 {
let cardViews = setGameView.cardViews [..<setGame.cardsInGame.count ]
setGameView.cardViews = Array(cardViews)
}
}
private func addTapListener(forCardView cardView: SetCardView){
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(onCardTap(recognizedBy:)))
tapRecognizer.numberOfTapsRequired=1
cardView.addGestureRecognizer(tapRecognizer)
}
@objc
private func onCardTap(recognizedBy recognizer: UITapGestureRecognizer){
switch recognizer.state {
case .ended:
if let cardView = recognizer.view! as? SetCardView {
let cardViewIndex = setGameView.cardViews.index(of: cardView)
setGame.select(card: setGame.cardsInGame[cardViewIndex!])
}
default: break
}
updateViewFromModel()
}
private func updateCardView(forView cardView: SetCardView, withModel modelCard: SetCard){
cardView.colorInt = 1 + (SetCardColor.allValues.firstIndex(of: modelCard.cardColor) ?? 1)
cardView.fillInt = 1 + (SetCardFill.allValues.firstIndex(of: modelCard.cardFill) ?? 1)
cardView.count = 1 + (SetCardCount.allValues.firstIndex(of: modelCard.cardCount) ?? 1)
cardView.symbolInt = 1 + (SetCardSymbol.allValues.firstIndex(of: modelCard.cardSymbol) ?? 1)
cardView.isSelected = setGame.isCardSelected(card: modelCard)
cardView.isSet = cardView.isSelected && setGame.isSet()
cardView.isHint = setGame.hintCards.contains(modelCard)
}
@IBAction private func dealThreeMoreCards(_ sender: UIButton){
dealMoreCards()
}
private func dealMoreCards(){
setGame.dealThreeModeCards()
updateViewFromModel()
}
@IBAction private func hint(_ sender: UIButton){
setGame.hint()
updateViewFromModel()
setGame.removeHint()
}
@IBAction private func shuffle(_ sender: UIButton){
onRotation()
}
}
|
//
// UICollectionViewLeftAlignedFlowLayout.swift
// TVShow
//
// Created by Seth Jin on 16/5/5.
// Copyright © 2016年 imeng. All rights reserved.
//
import UIKit
//import CGRectExtensions
class UICollectionViewLeftAlignedFlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let oldAttributes = super.layoutAttributesForElements(in: rect) else {
return super.layoutAttributesForElements(in: rect)
}
let spacing = minimumInteritemSpacing // REPLACE WITH WHAT SPACING YOU NEED
var newAttributes = [UICollectionViewLayoutAttributes]()
var leftMargin = sectionInset.left
var previousAttributes = UICollectionViewLayoutAttributes()
for i in 0 ..< oldAttributes.count {
let attributes = oldAttributes[i]
if i == 0 {
leftMargin = sectionInset.left
} else {
if (abs(attributes.center.y - previousAttributes.center.y) > 0.1) { //换行
leftMargin = sectionInset.left
}
else { //不换行
var newLeftAlignedFrame = attributes.frame
newLeftAlignedFrame.origin.x = leftMargin
attributes.frame = newLeftAlignedFrame
}
}
attributes.frame.origin.x = leftMargin
newAttributes.append(attributes)
leftMargin += attributes.frame.width + spacing
previousAttributes = attributes
}
return newAttributes
}
}
|
//
// SceneDelegate.swift
// Shop
//
// Created by Mahutin Aleksei on 01/10/2019.
// Copyright © 2019 Mahutin Aleksei. All rights reserved.
//
import UIKit
import RealmSwift
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
var navigationController: UINavigationController?
let tabBarController = MainViewController()
let tabViewController1 = CategoryViewController()
let tabViewController2 = CartViewController()
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// guard let _ = (scene as? UIWindowScene) else { return }
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
tabViewController1.tabBarItem = UITabBarItem(title: "Категории", image: nil, tag: 0)
tabViewController2.tabBarItem = UITabBarItem(title: "Корзина", image: nil, tag: 1)
let controllers = [tabViewController1,tabViewController2]
tabBarController.viewControllers = controllers
navigationController = UINavigationController(rootViewController: tabBarController)
window.rootViewController = navigationController
self.window = window
window.makeKeyAndVisible()
PersistanceData.shared.updateImage()
DataNow.shared.loadData(complite: {
new in
if new {
self.tabViewController1.loadData()
}
})
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
|
//
// Opponent.swift
// myWizardClone
//
// Created by Dennis Vocke on 30.12.18.
// Copyright © 2018 Dennis Vocke. All rights reserved.
//
import Foundation
class Opponent {
let id : Int
var hasYellow : Bool
var hasBlue : Bool
var hasRed : Bool
var hasGreen : Bool
init (thisId : Int){
id = thisId
hasYellow = true
hasBlue = true
hasRed = true
hasGreen = true
}
}
|
//
// SearchSettingsViewController.swift
// GithubDemo
//
// Created by Victoria Zhou on 3/1/17.
// Copyright © 2017 codepath. All rights reserved.
//
import UIKit
class SearchSettingsViewController: UIViewController {
@IBOutlet weak var starsSlider: UISlider!
@IBOutlet weak var numStarsLabel: UILabel!
weak var delegate: SettingsPresentingViewControllerDelegate?
var settings: GithubRepoSearchSettings?
override func viewDidLoad() {
super.viewDidLoad()
if (settings == nil) {
numStarsLabel.text = "100"
starsSlider.value = 100
settings = GithubRepoSearchSettings()
settings?.minStars = 100
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onSaveButton(_ sender: Any) {
self.settings?.minStars = Int(starsSlider.value)
self.delegate?.didSaveSettings(settings: settings!)
self.dismiss(animated: true, completion: nil)
}
@IBAction func onCancelButton(_ sender: Any) {
self.delegate?.didCancelSettings()
self.dismiss(animated: true, completion: nil)
}
@IBAction func onSliderChanged(_ sender: Any) {
self.numStarsLabel.text = "\(Int(starsSlider.value))"
}
/*
// 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.
}
*/
}
protocol SettingsPresentingViewControllerDelegate: class {
func didSaveSettings(settings: GithubRepoSearchSettings)
func didCancelSettings()
}
|
//
// Pagination.swift
// TodayNews
//
// Created by Ron Rith on 1/20/18.
// Copyright © 2018 Ron Rith. All rights reserved.
//
import Foundation
import SwiftyJSON
class Pagination{
var page: Int
var pageSize: Int
var totalElements: Int
var totalPages: Int
init(){
page = 0
pageSize = 0
totalElements = 0
totalPages = 0
}
init(_ data: JSON){
page = data["numberOfElements"].int ?? 0
pageSize = data["size"].int ?? 0
totalElements = data["totalElements"].int ?? 0
totalPages = data["totalPages"].int ?? 0
}
}
|
//
// StyleGuide.swift
// TipCalculator
//
// Created by Anthroman on 4/6/20.
// Copyright © 2020 Anthroman. All rights reserved.
//
import UIKit
extension UIView {
func addCornerRadius(_ radius: CGFloat = 4) {
self.layer.cornerRadius = radius
}
func addAccentBorder(width: CGFloat = 1, color: UIColor = UIColor.slateGray) {
self.layer.borderWidth = width
self.layer.borderColor = color.cgColor
}
}
extension UIColor {
static let clayBrown = UIColor(named: "clayBrown")!
static let lightGreen = UIColor(named: "lightGreen")!
static let mediumGreen = UIColor(named: "mediumGreen")!
static let darkGreen = UIColor(named: "darkGreen")!
static let slateGray = UIColor(named: "slateGray")!
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.