text stringlengths 8 1.32M |
|---|
import Foundation
public struct SuggestResponse: Decodable {
public let popular: [String]
public let recommended: [String]
}
|
//
// ViewController.swift
// GameOn
//
// Created by Bogdan on 21/06/15.
// Copyright (c) 2015 Braincode. All rights reserved.
//
import UIKit
import Parse
class Homepage: UIViewController {
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.
}
@IBOutlet weak var textBoxName: UITextField!
@IBOutlet weak var labelScore: UILabel!
@IBAction func hit(sender: AnyObject) {
var gameScore = PFObject(className: "Score")
let query = PFQuery(className: "Score")
query.whereKey("Username", equalTo: "\(textBoxName.text)")
query.getFirstObjectInBackgroundWithBlock{
(object: PFObject?, error: NSError?) -> Void in
if error != nil || object == nil{
println("No username found, we'll create it.")
gameScore["Username"] = self.textBoxName.text
gameScore["Score"] = 1
gameScore.saveInBackgroundWithBlock{
(success: Bool, error: NSError?) -> Void in
if (success){
// The object has been saved.
}else
{
// There was a problem, check error.description
}
}
}else
{
// The find succeeded.
println("Username found, we'll update the score")
if let object = object! as? PFObject {
object.incrementKey("Score")
object.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
let score = object["Score"] as! Int
self.labelScore.text = String(score)
} else {
// There was a problem, check error.description
}
}
}
}
}
}
}
|
import UIKit
import RxSwift
import MarketKit
struct RestoreSelectModule {
static func viewController(accountName: String, accountType: AccountType, isManualBackedUp: Bool = true, returnViewController: UIViewController?) -> UIViewController {
let (enableCoinService, enableCoinView) = EnableCoinModule.module()
let service = RestoreSelectService(
accountName: accountName,
accountType: accountType,
isManualBackedUp: isManualBackedUp,
accountFactory: App.shared.accountFactory,
accountManager: App.shared.accountManager,
walletManager: App.shared.walletManager,
evmAccountRestoreStateManager: App.shared.evmAccountRestoreStateManager,
marketKit: App.shared.marketKit,
enableCoinService: enableCoinService
)
let viewModel = RestoreSelectViewModel(service: service)
return RestoreSelectViewController(
viewModel: viewModel,
enableCoinView: enableCoinView,
returnViewController: returnViewController
)
}
}
|
//
// GameViewController.swift
// PeachPicking
//
// Created by 辜鹏 on 2019/12/16.
// Copyright © 2019 PengGu. All rights reserved.
//
import UIKit
import AVFoundation
class GameViewController: UIViewController {
var passedType:String?
var problemText = ""
var answer = 0
var dict:[Int:String] = [Int:String]()
var hiddenArr:[Int] = [Int]()
@IBOutlet weak var problemLb: UILabel!
@IBOutlet weak var collectionView: UICollectionView!
var indexArr = [0,1,2,3,4,5]
var index = 0
var player1: AVAudioPlayer?
var player2: AVAudioPlayer?
var timer = 60
var clock:Timer?
var score = 0
@IBOutlet weak var scoreLb: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
initdata()
hiddenItem()
showRandomProblem()
NotificationCenter.default.addObserver(self, selector: #selector(backAction), name: NSNotification.Name(rawValue: "back"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(homeAction), name: NSNotification.Name(rawValue: "home"), object: nil)
gameStart()
startTimer()
}
func startTimer(){
clock = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(countdown), userInfo: nil, repeats: true)
}
@objc func countdown() {
timer = timer - 1
self.title = String(timer) + "s"
if timer <= 0 {
clock?.invalidate()
var score_arr:[Int] = UserDefaults.standard.array(forKey:passedType!) as? [Int] ?? []
score_arr.append(score)
UserDefaults.standard.set(score_arr, forKey: passedType!)
let coverVc:GameOverViewController = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "GameOverViewController") as! GameOverViewController
coverVc.modalPresentationStyle = .overCurrentContext
coverVc.modalTransitionStyle = .coverVertical
coverVc.score = score
self.present(coverVc, animated: true, completion: nil)
}
}
func gameStart() {
let gameVc:GameStarterViewController = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "GameStarterViewController") as! GameStarterViewController
gameVc.modalPresentationStyle = .overCurrentContext
gameVc.modalTransitionStyle = .coverVertical
self.present(gameVc, animated: true, completion: nil)
}
@objc func backAction() {
startTimer()
score = 0
scoreLb.text = String(score)
timer = 61
hiddenArr.removeAll()
dict.removeAll()
problemText = ""
answer = 0
index = 0
indexArr = [0,1,2,3,4,5]
restartProblem()
collectionView.reloadData()
}
@objc func homeAction() {
navigationController?.popToRootViewController(animated: true)
}
func restartProblem() {
timer = timer + 30
indexArr = [0,1,2,3,4,5]
initdata()
hiddenItem()
showRandomProblem()
self.view.layoutIfNeeded()
self.view.layoutSubviews()
}
func showRandomProblem() {
let a = Int.random(in: 0...5)
problemLb.text = String(Array(dict.values)[a])
indexArr.remove(at: a)
}
func refreshRandomProblem() {
let b = indexArr.randomElement()
problemLb.text = String(Array(dict.values)[b!])
if let index = indexArr.firstIndex(of: b!) {
indexArr.remove(at: index)
}
self.view.layoutIfNeeded()
self.view.layoutSubviews()
}
// hidden item
func hiddenItem() {
// 5 * 4
var a = [0,1,2,3,4]
a.shuffle()
var b = [5,6,7,8,9]
b.shuffle()
var c = [10,11,12,13,14]
c.shuffle()
var d = [15,16,17,18,19]
d.shuffle()
hiddenArr = [a[0],b[0],b[1],c[0],d[0],d[1]]
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
for (i,item) in self.hiddenArr.enumerated() {
let cell:GameCell = self.collectionView.cellForItem(at: IndexPath(item: item, section: 0)) as! GameCell
cell.peachLb.text = String(Array(self.dict.keys)[i])
cell.picImgView.image = UIImage(named: "peach")
}
}
}
func initdata() {
for _ in 0...100 {
switch passedType {
case "1":
simple()
case "2":
general()
case "3":
difficult()
default:
print("error ...")
}
}
}
// 20 plus or mlus
func simple() {
let randomPlusOrSub = Int.random(in: 0...1)
let a = Int.random(in: 1...9)
let b = Int.random(in: 1...5)
let c = Int.random(in: 11...15)
switch randomPlusOrSub {
case 0:
// plus
problemText = "\(a) + \(b)"
answer = a + b
dict[answer] = problemText
case 1:
// sub
problemText = "\(c) - \(b)"
answer = c - b
dict[answer] = problemText
default:
print(" error ... ")
}
}
func general() {
let randomPlusOrSub = Int.random(in: 0...1)
let c = Int.random(in: 50...75)
let a = Int.random(in: 1...25)
let b = Int.random(in: 1...25)
switch randomPlusOrSub {
case 0:
// plus
problemText = "\(a) + \(b)"
answer = a + b
dict[answer] = problemText
case 1:
// sub
problemText = "\(c) - \(b)"
answer = c - b
dict[answer] = problemText
default:
print(" error ... ")
}
}
func difficult() {
let randomPlusOrSub = Int.random(in: 0...1)
let c = Int.random(in: 75...100)
let a = Int.random(in: 1...50)
let b = Int.random(in: 1...50)
switch randomPlusOrSub {
case 0:
// plus
problemText = "\(a) + \(b)"
answer = a + b
dict[answer] = problemText
case 1:
// sub
problemText = "\(c) - \(b)"
answer = c - b
dict[answer] = problemText
default:
print(" error ... ")
}
}
func setupUI() {
collectionView.dataSource = self
collectionView.delegate = self
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: contentWidth / 5 - 5 , height: contentHeight / 4 - 5 )
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.scrollDirection = .vertical
collectionView.collectionViewLayout = layout
}
func playSuccessSound() {
let url = Bundle.main.url(forResource: "success", withExtension: "mp3")!
do {
player1 = try AVAudioPlayer(contentsOf: url)
guard let player = player1 else { return }
player.prepareToPlay()
player.play()
} catch let error as NSError {
print(error.description)
}
}
func playErrorSound() {
let url = Bundle.main.url(forResource: "error", withExtension: "mp3")!
do {
player2 = try AVAudioPlayer(contentsOf: url)
guard let player = player2 else { return }
player.prepareToPlay()
player.play()
} catch let error as NSError {
print(error.description)
}
}
}
extension GameViewController:UICollectionViewDataSource,UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let game:GameCell = collectionView.dequeueReusableCell(withReuseIdentifier: "GameCell", for: indexPath) as! GameCell
if hiddenArr.contains(indexPath.row) {
game.picImgView.image = UIImage(named: "peach")
// answer add to hiddenArr
game.contentView.isUserInteractionEnabled = true
}else {
game.picImgView.image = nil
game.peachLb.text = ""
game.contentView.isUserInteractionEnabled = false
}
return game
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell:GameCell = collectionView.cellForItem(at: indexPath) as! GameCell
// click show peach item
if hiddenArr.contains(indexPath.row) {
// get the click dict key
let rowIndex = hiddenArr.firstIndex(of: indexPath.row)
let dictKey = Array(dict.keys)[rowIndex!]
if dict[dictKey] == problemLb.text {
print("succes refresh ...")
playSuccessSound()
score = score + 1
scoreLb.text = String(score)
// hide current pic and label
cell.picImgView.image = nil
cell.peachLb.text = ""
index = index + 1
if index == 6 {
index = 0
// restart the game
restartProblem()
}else {
refreshRandomProblem()
}
}else{
playErrorSound()
print("jump the error page ...")
timer = timer - 5
// clock?.invalidate()
//
// var score_arr:[Int] = UserDefaults.standard.array(forKey:passedType!) as? [Int] ?? []
// score_arr.append(score)
// UserDefaults.standard.set(score_arr, forKey: passedType!)
//
//
// let overVc:GameOverViewController = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "GameOverViewController") as! GameOverViewController
//
// overVc.modalPresentationStyle = .overCurrentContext
// overVc.modalTransitionStyle = .coverVertical
//
// self.present(overVc, animated: true, completion: nil)
}
}else{
cell.contentView.isUserInteractionEnabled = false
}
}
}
|
import Foundation
enum CardType {
case Minion
case Spell
case Weapon
case Other
static func selectType(name: String) -> CardType {
switch name {
case "Minion": return .Minion
case "Spell": return .Spell
case "Weapon": return .Weapon
default: return .Other
}
}
}
|
//
// CustomCalloutView.swift
// CustomCalloutView
//
// Created by Malek T. on 3/10/16.
// Copyright © 2016 Medigarage Studios LTD. All rights reserved.
//
import UIKit
class CustomCalloutView: UIView {
@IBOutlet var price: UILabel!
@IBOutlet var parked: UILabel!
@IBAction func add(_ sender: Any) {
}
}
|
//
// Repo.swift
// Sileo
//
// Created by CoolStar on 7/21/19.
// Copyright © 2019 Sileo Team. All rights reserved.
//
import Foundation
final class Repo: Equatable {
var rawURL: String = ""
var suite: String = ""
var components: [String] = []
var compression = ""
var packageDict: [String: Package] = [:]
var packageArray: [Package] {
Array(packageDict.values)
}
var url: URL? {
guard let rawURL = URL(string: rawURL) else {
return nil
}
if isFlat {
return suite == "./" ? rawURL : rawURL.appendingPathComponent(suite)
} else {
return rawURL.appendingPathComponent("dists").appendingPathComponent(suite)
}
}
var repoURL: String {
url?.absoluteString ?? ""
}
var displayURL: String {
rawURL
}
var primaryComponentURL: URL? {
if isFlat {
return self.url
} else {
if components.isEmpty {
return nil
}
return self.url?.appendingPathComponent(components[0])
}
}
var isFlat: Bool {
suite.hasSuffix("/") || components.isEmpty
}
func packagesURL(arch: String?) -> URL? {
guard var packagesDir = primaryComponentURL else {
return nil
}
if !isFlat,
let arch = arch {
packagesDir = packagesDir.appendingPathComponent("binary-".appending(arch))
}
return packagesDir.appendingPathComponent("Packages")
}
}
func == (lhs: Repo, rhs: Repo) -> Bool {
lhs.rawURL == rhs.rawURL && lhs.suite == rhs.suite
}
|
import UIKit
class RecipeItemTableViewCell: UITableViewCell {
// MARK: - Setup
func populate(with item: String) {
textLabel?.text = item
}
}
|
//
// AppDelegate.swift
// Film
//
// Created by Tomas Vosicky on 22.11.16.
// Copyright © 2016 Tomas Vosicky. All rights reserved.
//
import UIKit
import MagicalRecord
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
let tabBarController = TabsController()
window?.rootViewController = tabBarController
UINavigationBar.appearance().barTintColor = .background
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
application.statusBarStyle = .lightContent
MagicalRecord.setupCoreDataStack(withStoreNamed: "MovieModel")
return true
}
}
|
//
// FilterCarouselCollectionViewCell.swift
// GitHubTest
//
// Created by Bruno on 12/02/20.
// Copyright © 2020 bruno. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
protocol FilterCarouselCollectionViewDelegate: AnyObject {
func performBatchUpdates(height: CGFloat)
}
class FilterCarouselCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var carouselFilterCollectionView: UICollectionView!
weak var delegate: FilterCarouselCollectionViewDelegate?
var appdelegate: AppDelegate {
return (UIApplication.shared.delegate as? AppDelegate)!
}
var tasks: BehaviorRelay<[Filter]> = BehaviorRelay(value: [])
private let disposeBag = DisposeBag()
var filters: [Filter] = []
override func awakeFromNib() {
super.awakeFromNib()
carouselFilterCollectionView.delegate = self
carouselFilterCollectionView.register(FilterCollectionViewCell.self)
bindAddFilter()
bindCollectionView()
}
override func layoutSubviews() {
super.layoutSubviews()
}
private func bindAddFilter() {
appdelegate.appCoordinator.homeCoordinator?
.filtersViewController.task.subscribe(onNext: { [weak self] task in
if (self?.tasks.value.map {$0.title})?.contains(task.title) ?? false {
self?.filters.remove(object: task)
} else {
self?.filters.append(task)
}
self?.tasks.accept(self?.filters ?? [])
if self?.tasks.value.isEmpty ?? false {
self?.delegate?.performBatchUpdates(height: 1)
}
}).disposed(by: disposeBag)
}
private func bindCollectionView() {
tasks.asObservable()
.bind(to: carouselFilterCollectionView
.rx
.items(cellIdentifier: "FilterCollectionViewCell",
cellType: FilterCollectionViewCell.self)) { [weak self] _, element, cell in
cell.setup(filterName: element.title)
cell.delegate = self
self?.delegate?.performBatchUpdates(height: 56)
}.disposed(by: disposeBag)
}
}
extension FilterCarouselCollectionViewCell: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let cell = carouselFilterCollectionView.dequeueReusableCell(of: FilterCollectionViewCell.self,
for: indexPath) as? FilterCollectionViewCell
cell?.setup(filterName: tasks.value[indexPath.row].title)
cell?.setNeedsLayout()
cell?.layoutIfNeeded()
let size: CGSize = (cell?.contentView
.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize))!
return CGSize(width: size.width, height: 36)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 8
}
}
extension FilterCarouselCollectionViewCell: FilterCollectionViewDelegate {
func removeFilterWith(name: String) {
filters.remove(object: Filter(title: name))
tasks.accept(self.filters)
UserDefaults.standard.set(false, forKey: "\(name)-selected")
if tasks.value.isEmpty {
delegate?.performBatchUpdates(height: 1)
}
}
}
|
//
// UIColor+Extras.swift
// WhatDidILike
//
// Created by Christopher G Prince on 9/3/17.
// Copyright © 2017 Spastic Muffin, LLC. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
private static func colorMode(light: UIColor, dark: UIColor) -> UIColor {
if #available(iOS 13, *) {
return UIColor { (traitCollection: UITraitCollection) -> UIColor in
if traitCollection.userInterfaceStyle == .dark {
return dark
} else {
return light
}
}
} else {
return light
}
}
static var textBoxBorder: UIColor {
return colorMode(
light: UIColor(white: 0.95, alpha: 1.0),
dark: UIColor(white: 0.20, alpha: 1.0))
}
static var segmentedControlBorder: UIColor {
let light = UIColor.gray
let dark = UIColor(white: 0.80, alpha: 1.0)
return colorMode(light: light, dark: dark)
}
static var textBoxBackground: UIColor {
let light = UIColor(white: 0.85, alpha: 1.0)
let dark = UIColor(white: 0.40, alpha: 1.0)
return colorMode(light: light, dark: dark)
}
static var locationBackground: UIColor {
let light = UIColor(white: 0.95, alpha: 1.0)
let dark = UIColor.black
return colorMode(light: light, dark: dark)
}
static var locationHeaderBackground: UIColor {
let light = UIColor.white
let dark = UIColor.black
return colorMode(light: light, dark: dark)
}
static var commentBackground: UIColor {
return locationBackground
}
static var modalBackground: UIColor {
let light = UIColor(white: 0.95, alpha: 1.0)
let dark = UIColor.black
return colorMode(light: light, dark: dark)
}
static var sortyFilterBackground: UIColor {
let light = UIColor(white: 0.95, alpha: 1.0)
let dark = UIColor(white: 0.30, alpha: 1.0)
return colorMode(light: light, dark: dark)
}
static var dropDownBackground: UIColor {
let light = UIColor(white: 0.85, alpha: 1.0)
let dark = UIColor(white: 0.20, alpha: 1.0)
return colorMode(light: light, dark: dark)
}
static var tableViewBackground: UIColor {
let light = UIColor(white: 0.95, alpha: 1.0)
let dark = UIColor.black
return colorMode(light: light, dark: dark)
}
static var openClosed: UIColor {
let light = UIColor.black
let dark = UIColor.white
return colorMode(light: light, dark: dark)
}
static var upDown: UIColor {
let light = UIColor.black
let dark = UIColor.white
return colorMode(light: light, dark: dark)
}
static var trash: UIColor {
return locked
}
static var locked: UIColor {
let light = UIColor.black
let dark = UIColor(white: 0.8, alpha: 1.0)
return colorMode(light: light, dark: dark)
}
}
|
//
// LocationManager.swift
// Taxi
//
// Created by Bhavin
// skype : bhavin.bhadani
//
import UIKit
import CoreLocation
import MapKit
import Firebase
typealias ReverseGeocodeCompletionHandler = ((_ reverseGecodeInfo:[String:String]?,_ placemark:CLPlacemark?, _ error:String?)->Void)?
typealias GeocodeCompletionHandler = ((_ gecodeInfo:[String:String]?,_ placemark:CLPlacemark?, _ error:String?)->Void)?
typealias LocationCompletionHandler = ((_ latitude:Double, _ longitude:Double, _ status:String, _ verboseMessage:String, _ error:String?)->())?
// Todo: Keep completion handler differerent for all services, otherwise only one will work
enum GeoCodingType{
case geocoding
case reverseGeocoding
}
class LocationManager: NSObject,CLLocationManagerDelegate {
fileprivate var locationManager: CLLocationManager!
fileprivate var reverseGeocodingCompletionHandler:ReverseGeocodeCompletionHandler = nil
fileprivate var geocodingCompletionHandler:GeocodeCompletionHandler = nil
fileprivate var timer : Timer? = nil {
willSet {
timer?.invalidate()
}
}
var latitude:Double = 0.0
var longitude:Double = 0.0
var autoUpdate:Bool = false
class var sharedInstance : LocationManager {
struct Static {
static let instance : LocationManager = LocationManager()
}
return Static.instance
}
// fileprivate override init(){
// super.init()
// }
func startUpdatingLocation(){
initLocationManager()
}
func stopUpdatingLocation(){
locationManager.stopUpdatingLocation()
}
fileprivate func initLocationManager() {
// App might be unreliable if someone changes autoupdate status in between and stops it
locationManager = CLLocationManager()
locationManager.delegate = self
// locationManager.locationServicesEnabled
locationManager.desiredAccuracy = kCLLocationAccuracyBest
if #available(iOS 8.0, *) {
locationManager.requestWhenInUseAuthorization()
}
startLocationManger()
}
fileprivate func startLocationManger(){
locationManager.startUpdatingLocation()
}
fileprivate func stopLocationManger(){
locationManager.stopUpdatingLocation()
}
internal func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
stopLocationManger()
}
internal func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let arrayOfLocation = locations
if let location = arrayOfLocation.last {
let coordLatLon = location.coordinate
latitude = coordLatLon.latitude
longitude = coordLatLon.longitude
if (Auth.auth().currentUser != nil && Common.instance.getUserId().count > 0) {
self.updateLocationFirebase(with: latitude, longitude:longitude);
}
if Common.instance.isOnline() {
if timer == nil {
timer = Timer.scheduledTimer(timeInterval: 60, target: self,
selector: #selector(updateLocation), userInfo: nil, repeats: true)
}
} else {
timer?.invalidate()
timer = nil
}
}
}
func updateLocationFirebase(with latitude:Double, longitude:Double) {
print("ibrahim")
print(latitude)
print(longitude)
print(Common.instance.getUserId())
let postRef = Database.database().reference().child("Location").child(Common.instance.getUserId())
let postObject = [
"latitude": latitude,
"longitude": longitude,
"uid": Auth.auth().currentUser?.uid] as [String:Any]
postRef.setValue(postObject, withCompletionBlock: { error, ref in
if error == nil {
} else {
}
})
}
// Reverse geocode
func reverseGeocodeLocationWithLatLong(latitude:Double, longitude: Double,onReverseGeocodingCompletionHandler:ReverseGeocodeCompletionHandler){
let location = CLLocation(latitude:latitude, longitude: longitude)
reverseGeocodeLocationWithCoordinates(location,onReverseGeocodingCompletionHandler: onReverseGeocodingCompletionHandler)
}
func reverseGeocodeLocationWithCoordinates(_ coord:CLLocation, onReverseGeocodingCompletionHandler:ReverseGeocodeCompletionHandler){
self.reverseGeocodingCompletionHandler = onReverseGeocodingCompletionHandler
reverseGocode(coord)
}
fileprivate func reverseGocode(_ location:CLLocation){
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location, completionHandler: {(placemarks, error)->Void in
if (error != nil) {
self.reverseGeocodingCompletionHandler!(nil,nil, error!.localizedDescription)
}
else{
if let placemark = placemarks?.first {
let address = AddressParser()
address.parseAppleLocationData(placemark)
let addressDict = address.getAddressDictionary()
self.reverseGeocodingCompletionHandler!(addressDict,placemark,nil)
}
else {
self.reverseGeocodingCompletionHandler!(nil,nil,"No Placemarks Found!")
return
}
}
})
}
// geocode
func geocodeAddressString(address:String, onGeocodingCompletionHandler:GeocodeCompletionHandler){
self.geocodingCompletionHandler = onGeocodingCompletionHandler
geoCodeAddress(address)
}
fileprivate func geoCodeAddress(_ address:String){
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(address) { (placemarks, error) in
if error != nil {
self.geocodingCompletionHandler!(nil,nil,error!.localizedDescription)
}
else{
if let placemark = placemarks?.first {
let address = AddressParser()
address.parseAppleLocationData(placemark)
let addressDict = address.getAddressDictionary()
self.geocodingCompletionHandler!(addressDict,placemark,nil)
}
else {
self.geocodingCompletionHandler!(nil,nil,"invalid address: \(address)")
}
}
}
}
func geocodeUsingGoogleAddressString(address:String, onGeocodingCompletionHandler:GeocodeCompletionHandler){
self.geocodingCompletionHandler = onGeocodingCompletionHandler
geoCodeUsignGoogleAddress(address)
}
fileprivate func geoCodeUsignGoogleAddress(_ address:String){
var urlString = "http://maps.googleapis.com/maps/api/geocode/json?address=\(address)&sensor=true"
urlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
performOperationForURL(urlString, type: GeoCodingType.geocoding)
}
fileprivate func performOperationForURL(_ urlString:String,type:GeoCodingType){
let url = URL(string:urlString)
let request = URLRequest(url:url!)
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
if(error != nil){
self.setCompletionHandler(responseInfo:nil, placemark:nil, error:error!.localizedDescription, type:type)
}
else{
let kStatus = "status"
let kOK = "ok"
let kZeroResults = "ZERO_RESULTS"
let kAPILimit = "OVER_QUERY_LIMIT"
let kRequestDenied = "REQUEST_DENIED"
let kInvalidRequest = "INVALID_REQUEST"
let kInvalidInput = "Invalid Input"
do {
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
var status = jsonResult[kStatus] as! String
status = status.lowercased()
if(status == kOK){
let address = AddressParser()
address.parseGoogleLocationData(jsonResult)
let addressDict = address.getAddressDictionary()
let placemark = address.getPlacemark()
self.setCompletionHandler(responseInfo:addressDict, placemark:placemark, error: nil, type:type)
}else if((status != kZeroResults) && (status != kAPILimit) && (status != kRequestDenied) && (status != kInvalidRequest)){
self.setCompletionHandler(responseInfo:nil, placemark:nil, error:kInvalidInput, type:type)
}
else{
self.setCompletionHandler(responseInfo:nil, placemark:nil, error:status as String, type:type)
}
} catch let e {
self.setCompletionHandler(responseInfo:nil, placemark:nil, error:e.localizedDescription, type:type)
}
}
})
task.resume()
}
fileprivate func setCompletionHandler(responseInfo:[String:String]?,placemark:CLPlacemark?, error:String?,type:GeoCodingType){
if(type == GeoCodingType.geocoding){
self.geocodingCompletionHandler!(responseInfo,placemark,error)
}else{
self.reverseGeocodingCompletionHandler!(responseInfo,placemark,error)
}
}
//------------------------------------------------------------------------------------------------------------------------------------------
// MARK:- API Requests
//------------------------------------------------------------------------------------------------------------------------------------------
@objc fileprivate func updateLocation(){
var params = [String:String]()
params["user_id"] = Common.instance.getUserId()
params["latitude"] = String(latitude)
params["longitude"] = String(longitude)
let headers = ["X-API-KEY":Common.instance.getAPIKey()]
APIRequestManager.request(apiRequest: APIRouters.UpdateUser(params,headers), success: { (responseData) in
if let data = responseData as? [String:String] {
if let user = UserDefaults.standard.data(forKey: "user"){
let userData = NSKeyedUnarchiver.unarchiveObject(with: user) as? User
userData?.lat = data["latitude"]
userData?.long = data["longitude"]
let encodedData = NSKeyedArchiver.archivedData(withRootObject: userData!)
UserDefaults.standard.set(encodedData, forKey: "user")
}
}
}, failure: { (message) in
// print(message)
}, error: { (err) in
// print(err.localizedDescription)
})
}
}
private class AddressParser: NSObject{
fileprivate var latitude = String()
fileprivate var longitude = String()
fileprivate var streetNumber = String()
fileprivate var route = String()
fileprivate var locality = String()
fileprivate var subLocality = String()
fileprivate var formattedAddress = String()
fileprivate var administrativeArea = String()
fileprivate var administrativeAreaCode = String()
fileprivate var subAdministrativeArea = String()
fileprivate var postalCode = String()
fileprivate var country = String()
fileprivate var subThoroughfare = String()
fileprivate var thoroughfare = String()
fileprivate var ISOcountryCode = String()
fileprivate var state = String()
override init(){
super.init()
}
fileprivate func getAddressDictionary()-> [String:String]{
var addressDict = [String:String]()
addressDict["latitude"] = latitude
addressDict["longitude"] = longitude
addressDict["streetNumber"] = streetNumber
addressDict["locality"] = locality
addressDict["subLocality"] = subLocality
addressDict["administrativeArea"] = administrativeArea
addressDict["postalCode"] = postalCode
addressDict["country"] = country
addressDict["formattedAddress"] = formattedAddress
return addressDict
}
fileprivate func parseAppleLocationData(_ placemark:CLPlacemark){
let addressLines = placemark.addressDictionary!["FormattedAddressLines"] as! [String]
if let stf = placemark.subThoroughfare { self.streetNumber = stf }
if let lcl = placemark.locality { self.locality = lcl }
if let postal = placemark.postalCode { self.postalCode = postal }
if let slcl = placemark.subLocality { self.subLocality = slcl }
if let aa = placemark.administrativeArea { self.administrativeArea = aa }
if let cntry = placemark.country { self.country = cntry }
self.longitude = placemark.location!.coordinate.longitude.description
self.latitude = placemark.location!.coordinate.latitude.description
if addressLines.count > 0 {
self.formattedAddress = addressLines.joined(separator: ", ")
} else {
self.formattedAddress = ""
}
}
fileprivate func parseGoogleLocationData(_ resultDict:[String:Any]){
if let locations = resultDict["results"] as? [[String:Any]] {
let locationDict = locations.first
let formattedAddrs = locationDict?["formatted_address"] as! String
let geometry = locationDict?["geometry"] as! [String:Any]
let location = geometry["location"] as! [String:Double]
self.latitude = String(location["lat"]!)
self.longitude = String(location["lng"]!)
let addressComponents = locationDict?["address_components"] as! [[String:Any]]
self.subThoroughfare = component("street_number", inArray: addressComponents, ofType: "long_name")
self.thoroughfare = component("route", inArray: addressComponents, ofType: "long_name")
self.streetNumber = self.subThoroughfare
self.locality = component("locality", inArray: addressComponents, ofType: "long_name")
self.postalCode = component("postal_code", inArray: addressComponents, ofType: "long_name")
self.route = component("route", inArray: addressComponents, ofType: "long_name")
self.subLocality = component("subLocality", inArray: addressComponents, ofType: "long_name")
self.administrativeArea = component("administrative_area_level_1", inArray: addressComponents, ofType: "long_name")
self.administrativeAreaCode = component("administrative_area_level_1", inArray: addressComponents, ofType: "short_name")
self.subAdministrativeArea = component("administrative_area_level_2", inArray: addressComponents, ofType: "long_name")
self.country = component("country", inArray: addressComponents, ofType: "long_name")
self.ISOcountryCode = component("country", inArray: addressComponents, ofType: "short_name")
self.formattedAddress = formattedAddrs
}
}
fileprivate func component(_ component:String,inArray:[[String:Any]],ofType:String) -> String{
let index = (inArray as NSArray).indexOfObject(passingTest:) {obj, idx, stop in
let objDict = obj as! NSDictionary
let types = objDict.object(forKey: "types") as! NSArray
let type = types.firstObject as! String
return type.isEqual(component)
}
if (index == NSNotFound){
return ""
}
if (index >= inArray.count){
return ""
}
let type = inArray[index][ofType] as! String
if (type.count > 0){
return type
}
return ""
}
fileprivate func getPlacemark() -> CLPlacemark{
var addressDict = [String : Any]()
let formattedAddressArray = self.formattedAddress.components(separatedBy: ", ") as [Any]
let kSubAdministrativeArea = "SubAdministrativeArea"
let kSubLocality = "SubLocality"
let kState = "State"
let kStreet = "Street"
let kThoroughfare = "Thoroughfare"
let kFormattedAddressLines = "FormattedAddressLines"
let kSubThoroughfare = "SubThoroughfare"
let kPostCodeExtension = "PostCodeExtension"
let kCity = "City"
let kZIP = "ZIP"
let kCountry = "Country"
let kCountryCode = "CountryCode"
addressDict[kSubAdministrativeArea] = self.subAdministrativeArea
addressDict[kSubLocality] = self.subLocality
addressDict[kState] = self.administrativeAreaCode
addressDict[kStreet] = formattedAddressArray.first!
addressDict[kThoroughfare] = self.thoroughfare
addressDict[kFormattedAddressLines] = formattedAddressArray
addressDict[kSubThoroughfare] = self.subThoroughfare
addressDict[kPostCodeExtension] = ""
addressDict[kCity] = self.locality
addressDict[kZIP] = self.postalCode
addressDict[kCountry] = self.country
addressDict[kCountryCode] = self.ISOcountryCode
let lat = Double(self.latitude)
let lng = Double(self.longitude)
let coordinate = CLLocationCoordinate2D(latitude: lat!, longitude: lng!)
let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDict)
return (placemark as CLPlacemark)
}
}
|
//
// LoginMock.swift
// FormulaEUnitTests
//
// Created by Antonio Ivcec on 25/10/18.
// Copyright © 2018 Antonio Ivcec. All rights reserved.
//
import UIKit
@testable import FormulaE
class MockLoginVMCoordinator: LoginVMCoordinatorDelegate {
var didSucceed: Bool?
func showErrorAlert(with message: String?) {
didSucceed = false
}
func loginSuccess() {
didSucceed = true
}
}
class MockLoginService: LoginServiceProtocol {
var didSucceed: Bool?
private let shouldSucceed: Bool
init(shouldSucceed: Bool) {
self.shouldSucceed = shouldSucceed
}
func peformLogin(from vc: UIViewController, onSuccess: @escaping () -> (), onError: @escaping (String) -> ()) {
if shouldSucceed {
onSuccess()
didSucceed = true
} else {
onError("Error")
didSucceed = false
}
}
}
|
//
// VoiceActorList.swift
// SwiftUISample
//
// Created by 坂上翔悟 on 2019/06/09.
// Copyright © 2019 Shogo Sakaue. All rights reserved.
//
import SwiftUI
struct VoiceActorList : View {
@EnvironmentObject var userData: UserData
var body: some View {
NavigationView {
List {
Toggle(isOn: $userData.showFavoritedOnly) {
Text("お気に入りのみ")
}
ForEach(userData.voiceActors) { actor in
if !self.userData.showFavoritedOnly || actor.isFavorited {
NavigationButton(destination: VoiceActorDetail(voiceActor: actor)) {
VoiceActorRow(actor: actor)
}
}
}
}.navigationBarTitle(Text("声優リスト"), displayMode: .large)
}
}
}
#if DEBUG
struct VoiceActorList_Previews : PreviewProvider {
static var previews: some View {
ForEach(["iPhone SE", "iPhone XS MAX"].identified(by: \.self)) {
VoiceActorList()
.environmentObject(UserData())
.previewDevice(PreviewDevice(rawValue: $0))
.previewDisplayName($0)
}
}
}
#endif
|
//
// support.swift
// Bookmark
//
// Created by 김희진 on 2021/07/29.
//
import Foundation
import CoreData
import UIKit
let context = (UIApplication.shared.delegate as! AppDelegate ).persistentContainer.viewContext
func saveContext(){
if context.hasChanges
{
do{
try context.save()
}catch{
print(error)
}
}
}
class PersistenceManager {
static var shared: PersistenceManager = PersistenceManager()
@discardableResult func deleteAll<T: NSManagedObject>(request: NSFetchRequest<T>) -> Bool {
let request: NSFetchRequest<NSFetchRequestResult> = T.fetchRequest()
let delete = NSBatchDeleteRequest(fetchRequest: request)
do {
try context.execute(delete)
return true
} catch {
return false
}
}
}
|
//
// SignUpViewController.swift
// MyApp2
//
// Created by Anıl Demirci on 22.06.2021.
//
import UIKit
import Firebase
class SignUpViewController: UIViewController {
@IBOutlet weak var stadiumSignUpButton: UIButton!
@IBOutlet weak var userSignUpButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
stadiumSignUpButton.setTitleColor(UIColor.white, for: .normal)
//stadiumSignUpButton.backgroundColor = .systemGreen
stadiumSignUpButton.layer.cornerRadius=25
userSignUpButton.setTitleColor(UIColor.white, for: .normal)
//userSignUpButton.backgroundColor = .systemGreen
userSignUpButton.layer.cornerRadius=25
navigationItem.title="Üye Ol"
navigationController?.navigationBar.titleTextAttributes=[NSAttributedString.Key.foregroundColor:UIColor.white]
// Do any additional setup after loading the view.
}
@IBAction func backButtonClicked(_ sender: Any) {
}
@IBAction func stadiumButtonClicked(_ sender: Any) {
}
@IBAction func userButtonClicked(_ sender: Any) {
}
}
|
//
// SettingsViewController.swift
// RxPlaygrounds
//
// Created by 杨弘宇 on 2016/9/18.
// Copyright © 2016年 杨弘宇. All rights reserved.
//
import UIKit
class SettingsViewController: UITableViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let sizeThatFits = self.tableView.sizeThatFits(CGSize(width: self.view.bounds.width, height: CGFloat(MAXFLOAT)))
UIView.animate(withDuration: 0.5) {
self.preferredContentSize = sizeThatFits
}
}
}
|
//
// EditViewController.swift
// examNavigation
//
// Created by 402-24 on 01/12/2018.
// Copyright © 2018 402-24. All rights reserved.
//
import UIKit
protocol EditDelegate {
func didMessageEditDone(_ controller: EditViewController, message: String)
}
class EditViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/*
// 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.
}
*/
}
|
//#Patterns: max-struct-length: {"max-struct-length": 2}
//#Issue: {"severity": "Info", "line": 5, "patternId": "max-struct-length"}
struct ThreeLineStruct {
// Yada Yada.
// Yada Yada.
// Yada Yada.
// Yada Yada.
// Yada Yada.
// Yada Yada.
// Yada Yada.
// Yada Yada.
// Yada Yada.
// Yada Yada.
// Yada Yada.
// Yada Yada.
}
|
//
// MockAppTests-MockAppMocks.generated.swift
// MockApp
//
// Generated by Mockingbird v0.18.1.
// DO NOT EDIT
//
@testable import MockApp
@testable import Mockingbird
import Alamofire
import Foundation
import Swift
import UIKit
private let genericStaticMockContext = Mockingbird.GenericStaticMockContext()
// MARK: - Mocked Birdble
public final class BirdbleMock: MockApp.Birdble, Mockingbird.Mock {
typealias MockingbirdSupertype = MockApp.Birdble
static let staticMock = Mockingbird.StaticMock()
public let mockingbirdContext = Mockingbird.Context(["generator_version": "0.18.1", "module_name": "MockApp"])
// MARK: Mocked canFly
public var `canFly`: Bool {
get {
return self.mockingbirdContext.mocking.didInvoke(Mockingbird.SwiftInvocation(selectorName: "canFly.getter", setterSelectorName: "canFly.setter", selectorType: Mockingbird.SelectorType.getter, arguments: [], returnType: Swift.ObjectIdentifier((Bool).self))) {
self.mockingbirdContext.recordInvocation($0)
let mkbImpl = self.mockingbirdContext.stubbing.implementation(for: $0)
if let mkbImpl = mkbImpl as? () -> Bool { return mkbImpl() }
if let mkbImpl = mkbImpl as? () -> Any? { return Mockingbird.dynamicCast(mkbImpl()) as Bool }
if let mkbImpl = mkbImpl as? () -> Any? { return Mockingbird.dynamicCast(mkbImpl()) as Bool }
for mkbTargetBox in self.mockingbirdContext.proxy.targets(for: $0) {
switch mkbTargetBox.target {
case .super:
break
case .object(let mkbObject):
guard var mkbObject = mkbObject as? MockingbirdSupertype else { break }
let mkbValue: Bool = mkbObject.`canFly`
self.mockingbirdContext.proxy.updateTarget(&mkbObject, in: mkbTargetBox)
return mkbValue
}
}
if let mkbValue = self.mockingbirdContext.stubbing.defaultValueProvider.value.provideValue(for: (Bool).self) { return mkbValue }
self.mockingbirdContext.stubbing.failTest(for: $0, at: self.mockingbirdContext.sourceLocation)
}
}
}
public func getCanFly() -> Mockingbird.Mockable<Mockingbird.PropertyGetterDeclaration, () -> Bool, Bool> {
return Mockingbird.Mockable<Mockingbird.PropertyGetterDeclaration, () -> Bool, Bool>(mock: self, invocation: Mockingbird.SwiftInvocation(selectorName: "canFly.getter", setterSelectorName: "canFly.setter", selectorType: Mockingbird.SelectorType.getter, arguments: [], returnType: Swift.ObjectIdentifier((Bool).self)))
}
fileprivate init(sourceLocation: Mockingbird.SourceLocation) {
self.mockingbirdContext.sourceLocation = sourceLocation
BirdbleMock.staticMock.mockingbirdContext.sourceLocation = sourceLocation
}
// MARK: Mocked `fly`()
public func `fly`() -> Void {
return self.mockingbirdContext.mocking.didInvoke(Mockingbird.SwiftInvocation(selectorName: "`fly`() -> Void", selectorType: Mockingbird.SelectorType.method, arguments: [], returnType: Swift.ObjectIdentifier((Void).self))) {
self.mockingbirdContext.recordInvocation($0)
let mkbImpl = self.mockingbirdContext.stubbing.implementation(for: $0)
if let mkbImpl = mkbImpl as? () -> Void { return mkbImpl() }
for mkbTargetBox in self.mockingbirdContext.proxy.targets(for: $0) {
switch mkbTargetBox.target {
case .super:
break
case .object(let mkbObject):
guard var mkbObject = mkbObject as? MockingbirdSupertype else { break }
let mkbValue: Void = mkbObject.`fly`()
self.mockingbirdContext.proxy.updateTarget(&mkbObject, in: mkbTargetBox)
return mkbValue
}
}
if let mkbValue = self.mockingbirdContext.stubbing.defaultValueProvider.value.provideValue(for: (Void).self) { return mkbValue }
self.mockingbirdContext.stubbing.failTest(for: $0, at: self.mockingbirdContext.sourceLocation)
}
}
public func `fly`() -> Mockingbird.Mockable<Mockingbird.FunctionDeclaration, () -> Void, Void> {
return Mockingbird.Mockable<Mockingbird.FunctionDeclaration, () -> Void, Void>(mock: self, invocation: Mockingbird.SwiftInvocation(selectorName: "`fly`() -> Void", selectorType: Mockingbird.SelectorType.method, arguments: [], returnType: Swift.ObjectIdentifier((Void).self)))
}
}
/// Returns a concrete mock of `Birdble`.
public func mock(_ type: MockApp.Birdble.Protocol, file: StaticString = #file, line: UInt = #line) -> BirdbleMock {
return BirdbleMock(sourceLocation: Mockingbird.SourceLocation(file, line))
}
// MARK: - Mocked Networkable
public final class NetworkableMock: MockApp.Networkable, Mockingbird.Mock {
typealias MockingbirdSupertype = MockApp.Networkable
static let staticMock = Mockingbird.StaticMock()
public let mockingbirdContext = Mockingbird.Context(["generator_version": "0.18.1", "module_name": "MockApp"])
fileprivate init(sourceLocation: Mockingbird.SourceLocation) {
self.mockingbirdContext.sourceLocation = sourceLocation
NetworkableMock.staticMock.mockingbirdContext.sourceLocation = sourceLocation
}
// MARK: Mocked `getMethod`(`completionHandler`: @escaping (MockApp.BitcoinResponse?) -> ())
public func `getMethod`(`completionHandler`: @escaping (MockApp.BitcoinResponse?) -> ()) -> Void {
return self.mockingbirdContext.mocking.didInvoke(Mockingbird.SwiftInvocation(selectorName: "`getMethod`(`completionHandler`: @escaping (MockApp.BitcoinResponse?) -> ()) -> Void", selectorType: Mockingbird.SelectorType.method, arguments: [Mockingbird.ArgumentMatcher(`completionHandler`)], returnType: Swift.ObjectIdentifier((Void).self))) {
self.mockingbirdContext.recordInvocation($0)
let mkbImpl = self.mockingbirdContext.stubbing.implementation(for: $0)
if let mkbImpl = mkbImpl as? (@escaping (MockApp.BitcoinResponse?) -> ()) -> Void { return mkbImpl(`completionHandler`) }
if let mkbImpl = mkbImpl as? () -> Void { return mkbImpl() }
for mkbTargetBox in self.mockingbirdContext.proxy.targets(for: $0) {
switch mkbTargetBox.target {
case .super:
break
case .object(let mkbObject):
guard var mkbObject = mkbObject as? MockingbirdSupertype else { break }
let mkbValue: Void = mkbObject.`getMethod`(completionHandler: `completionHandler`)
self.mockingbirdContext.proxy.updateTarget(&mkbObject, in: mkbTargetBox)
return mkbValue
}
}
if let mkbValue = self.mockingbirdContext.stubbing.defaultValueProvider.value.provideValue(for: (Void).self) { return mkbValue }
self.mockingbirdContext.stubbing.failTest(for: $0, at: self.mockingbirdContext.sourceLocation)
}
}
public func `getMethod`(`completionHandler`: @autoclosure () -> (MockApp.BitcoinResponse?) -> ()) -> Mockingbird.Mockable<Mockingbird.FunctionDeclaration, (@escaping (MockApp.BitcoinResponse?) -> ()) -> Void, Void> {
return Mockingbird.Mockable<Mockingbird.FunctionDeclaration, (@escaping (MockApp.BitcoinResponse?) -> ()) -> Void, Void>(mock: self, invocation: Mockingbird.SwiftInvocation(selectorName: "`getMethod`(`completionHandler`: @escaping (MockApp.BitcoinResponse?) -> ()) -> Void", selectorType: Mockingbird.SelectorType.method, arguments: [Mockingbird.resolve(`completionHandler`)], returnType: Swift.ObjectIdentifier((Void).self)))
}
}
/// Returns a concrete mock of `Networkable`.
public func mock(_ type: MockApp.Networkable.Protocol, file: StaticString = #file, line: UInt = #line) -> NetworkableMock {
return NetworkableMock(sourceLocation: Mockingbird.SourceLocation(file, line))
}
|
//
// MedicalRepository.swift
// FinalProject
//
// Created by yespinoza on 8/15/20.
//
import Foundation
class MedicalRepository{
static func getHistory(_ userName:String?, _protocol:MedicalProtocol){
let parameters:[String:AnyObject] = ["user":userName as AnyObject]
let action:String = NetworkEndpoint.Medical_GetHistory
NetworkHelper.getInstance().request(action: action, type: .post, param:parameters,
onSuccess: { (response) in
do{
let responseDecoded:BaseDataResponse<[MedicalHistory]>? = JSonUtil.decodeResponse(response.rawString() ?? "", action: action)
guard let responseObject = responseDecoded, responseObject.isSuccessful else {
_protocol.onError()
return
}
if let data = responseObject.data {
_protocol.onSuccess(data)
}else{
_protocol.onError()
}
}catch{
_protocol.onError()
}
}, onFailure: { (NSError) in
_protocol.onError()
})
}
}
|
//
// YoutubeMainViewModel.swift
// SwiftTraningProject
//
// Created by 吉祥具 on 2017/6/19.
// Copyright © 2017年 吉祥具. All rights reserved.
//
import Foundation
import ReactiveSwift
class YoutubeMainViewModel {
// MARK:- videoCatrgoriesModel的處理
var videoCatrgoriesModel:YoutubeVideoCategoriesModel!{
didSet{
//利用filter 把不合格的對象剔除掉
videoCatrgoriesModel.items = videoCatrgoriesModel?.items?.filter({ (model) -> Bool in
return (model.snippet?.assignable)!
})
}
}
func createViewCategoryViewCellModel(forIndex index:Int) -> ViewCategoryViewCellModel{
return ViewCategoryViewCellModel.init(withViewCatrgorySnippet: (videoCatrgoriesModel?.items![index].snippet)!)
}
// MARK:- mostPopularVideosModel的處理
var mostPopularVideosItemArray = [YoutubeItemModel]() //儲存videos的item的Array
var mostPopularVideosNextPageToken:String? //儲存下一頁的token
var mostPopularVideosModel:YoutubeVideosModel!{ //儲存整個videos的model
didSet{
mostPopularVideosModel.items = mostPopularVideosItemArray
mostPopularVideosNextPageToken = mostPopularVideosModel.nextPageToken
}
}
var mostPopularProgressViewArray = [Int:AnyObject]() //如果要放客製化Class 要使用AnyObject代替class對象本身
var mostPopularVideoImageCacheArray = [Int:AnyObject]() //儲存圖片的array
func createMostPopularProgressView(forIndex index:Int, boundsGet: CGRect ) {
if mostPopularProgressViewArray[index] == nil {
let progressView = CircularLoaderView.init(frame: CGRect.zero)
mostPopularProgressViewArray[index] = progressView
progressView.frame = boundsGet
progressView.autoresizingMask = [.flexibleWidth , .flexibleHeight]
}
}
// MARK: - create MostPupularVideosViewCellModel
func createMostPupularVideosViewCellModel(forIndex index:Int) -> VideoViewCellModel{
if let imageGet = mostPopularVideoImageCacheArray[index]{
return VideoViewCellModel.init(withVideoSnippet: (mostPopularVideosModel?.items![index].snippet)!, withVideoStatistics: (mostPopularVideosModel?.items![index].statistics)!, withImage: imageGet as? UIImage, withProgressView: (mostPopularProgressViewArray[index])! as! CircularLoaderView)
}else{
return VideoViewCellModel.init(withVideoSnippet: (mostPopularVideosModel?.items![index].snippet)!, withVideoStatistics: (mostPopularVideosModel?.items![index].statistics)!, withImage: nil, withProgressView: (mostPopularProgressViewArray[index])! as! CircularLoaderView)
}
}
// MARK:- mylikedVideosModel的處理
var myLikedVideosItemArray = [YoutubeItemModel]()
var myLikedVideosNextPageToken:String?
var myLikedVideosModel:YoutubeVideosModel!{
didSet{
myLikedVideosModel.items = myLikedVideosItemArray
myLikedVideosNextPageToken = myLikedVideosModel.nextPageToken
}
}
var myLikedProgressViewArray = [Int:AnyObject]() //如果要放客製化Class 要使用AnyObject代替class對象本身
var myLikedVideoImageCacheArray = [Int:AnyObject]()
func createMyLikedProgressView(forIndex index:Int, boundsGet: CGRect ) {
if myLikedProgressViewArray[index] == nil {
let progressView = CircularLoaderView.init(frame: CGRect.zero)
myLikedProgressViewArray[index] = progressView
progressView.frame = boundsGet
progressView.autoresizingMask = [.flexibleWidth , .flexibleHeight]
}
}
// MARK: - create ViewCategoryViewCellModel
func createMyLikeVideosViewCellModel(forIndex index:Int) -> VideoViewCellModel {
if let imageGet = myLikedVideoImageCacheArray[index]{
return VideoViewCellModel.init(withVideoSnippet: (myLikedVideosModel.items![index].snippet)!, withVideoStatistics: (myLikedVideosModel?.items![index].statistics)!, withImage: imageGet as? UIImage, withProgressView: (myLikedProgressViewArray[index])! as! CircularLoaderView)
}else{
return VideoViewCellModel.init(withVideoSnippet: (myLikedVideosModel?.items![index].snippet)!, withVideoStatistics: (myLikedVideosModel?.items![index].statistics)!, withImage: nil, withProgressView: (myLikedProgressViewArray[index])! as! CircularLoaderView)
}
}
// MARK: - clean cache
func cleanCache(){
mostPopularVideosItemArray.removeAll()
mostPopularProgressViewArray.removeAll()
mostPopularVideoImageCacheArray.removeAll()
myLikedVideosItemArray.removeAll()
myLikedProgressViewArray.removeAll()
myLikedVideoImageCacheArray.removeAll()
}
}
// MARK:- ViewCategoryViewCellModel for ViewCategoryViewCell
struct ViewCategoryViewCellModel{
let mainTitle:String
let subTitle:String
init(withViewCatrgorySnippet model:YoutubeSnippetModel){
mainTitle = LocalizationManagerTool.getString(key: model.title, tableSet: nil)
subTitle = model.title
}
}
// MARK:- VideoViewCellModel for VideoViewCell
struct VideoViewCellModel {
let mainTitle:String //取localized內的參數
let publishedAt:String
let thumbnailsURL:URL
let progressIndicatorView:CircularLoaderView
let thumbnailsImage:UIImage? //default尺寸為 120*90
let channelTitle:String
let viewCount:String
init(withVideoSnippet snippetModel:YoutubeSnippetModel, withVideoStatistics statisticsModel:YoutubeStatisticsModel, withImage image:UIImage? = nil, withProgressView progressView:CircularLoaderView){
mainTitle = (snippetModel.localized?.title)!
publishedAt = String.init(format: LocalizationManagerTool.getString(key: "publishedDate_Title", tableSet: nil), arguments: [DateStringFormatterTool.stringToString(dateString: snippetModel.publishedAt, format: youtubeDateformat, toFormat: localDateformat)])
thumbnailsURL = URL.init(string:(snippetModel.thumbnails?.defaultQuality?.url)!)!
if(image != nil){
thumbnailsImage = image!
}else{
thumbnailsImage = nil
}
progressIndicatorView = progressView
channelTitle = snippetModel.channelTitle
viewCount = String.init(format: LocalizationManagerTool.getString(key: "viewCount_Title", tableSet: nil), arguments: [statisticsModel.viewCount])
}
}
|
//
// ViewController.swift
// login
//
// Created by Student09 on 2017/11/17.
// Copyright © 2017年 s. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
var codeEdit: UITextField!
var mobileEdit:UITextField!
var pwdEdit:UITextField!
var result: Int!
@objc func forCode() {
result = Int(arc4random()) % (9999 - 1000 + 1) + 1000
print(result)
}
@objc func forRegister() {
//实现页面的跳转
let myInt = Int(codeEdit.text!)
//print(myInt!)
if myInt == result{
//将用户信息存储plist文件中
let dic:NSMutableDictionary = NSMutableDictionary()
let mobile = mobileEdit.text
let pwd = pwdEdit.text
dic.setObject(mobile!, forKey: "userID" as NSCopying)
dic.setObject(pwd!, forKey: "password" as NSCopying)
let plistPath = Bundle.main.path(forResource: "userInformation", ofType: "plist")
dic.write(toFile: plistPath!, atomically: true)
let data:NSMutableDictionary = NSMutableDictionary.init(contentsOfFile:plistPath!)!
let message = data.description
print(plistPath!)
print(message)
let registerViewController = RegisterViewController()
registerViewController.viewController = self
self.present(registerViewController, animated: true, completion: nil)
}
else {
print("验证码错误,请重新输入")
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
// Do any additional setup after loading the view, typically from a nib.
let title = UILabel(frame: CGRect(x: 130, y: 60, width: 70, height: 50))
title.text = "注册"
title.font = UIFont.systemFont(ofSize: 25)
self.view.addSubview(title)
let mobile = UILabel(frame: CGRect(x: 20, y: 150, width: 70, height: 50))
mobile.text = "手机号码"
mobileEdit = UITextField(frame: CGRect(x: 100, y: 150, width: 210, height: 50))
mobileEdit.placeholder = "请输入您的手机号码"
self.view.addSubview(mobile)
self.view.addSubview(mobileEdit)
let code = UILabel(frame: CGRect(x: 20, y: 200, width: 70, height: 50))
code.text = "验证码"
codeEdit = UITextField(frame: CGRect(x: 100, y: 200, width: 120, height: 50))
codeEdit.placeholder = "请输入验证码"
codeEdit.keyboardType = UIKeyboardType.default
let pwd = UILabel(frame: CGRect(x: 20, y: 250, width: 70, height: 50))
pwd.text = "密码"
pwdEdit = UITextField(frame: CGRect(x: 100, y: 250, width: 210, height: 50))
pwdEdit.placeholder = "请输入您要设置的密码"
pwdEdit.isSecureTextEntry = true
self.view.addSubview(pwd)
self.view.addSubview(pwdEdit)
let getCode = UIButton(frame: CGRect(x: 220, y: 210, width: 70, height: 30))
getCode.backgroundColor = UIColor.lightGray
getCode.layer.borderWidth = 2;
getCode.layer.cornerRadius = 10;
getCode.setTitle("获取验证码", for:.normal)
getCode.titleLabel?.font = UIFont.systemFont(ofSize: 11)
//添加获取验证码的点击事件
getCode.addTarget(self,action:#selector(ViewController.forCode),for:UIControlEvents.touchUpInside)
let register = UIButton(frame: CGRect(x: 110, y: 350, width: 100, height: 40))
register.setTitle("注册", for: UIControlState())
register.backgroundColor = UIColor.black
//添加注册按钮的点击事件
register.addTarget(self,action:#selector(ViewController.forRegister),for:UIControlEvents.touchUpInside)
self.view.addSubview(code)
self.view.addSubview(codeEdit)
self.view.addSubview(getCode)
self.view.addSubview(register)
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
}
|
//
// AppDelegate.swift
// Taxi
//
// Created by Bhavin on 03/03/17.
// Copyright © 2017 icanStudioz. All rights reserved.
//
import UIKit
import GoogleMaps
import IQKeyboardManagerSwift
import UserNotifications
import Firebase
import FirebaseInstanceID
import FirebaseMessaging
import Fabric
import Crashlytics
import GooglePlaces
let primaryColor = UIColor(red: 210/255, green: 109/255, blue: 180/255, alpha: 1)
let secondaryColor = UIColor(red: 52/255, green: 148/255, blue: 230/255, alpha: 1)
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate, MessagingDelegate {
var window: UIWindow?
var locationManager = LocationManager.sharedInstance
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// -- Use Firebase library to configure APIs --
FirebaseApp.configure()
// [START set_messaging_delegate]
Messaging.messaging().delegate = self
// [END set_messaging_delegate]
//-----------------------------------------------------------
// auth for platform application by ibrahim
let authListener = Auth.auth().addStateDidChangeListener { auth, user in
if user != nil {
UserService.observeUserProfile(user!.uid) { userProfile in
UserService.currentUserProfile = userProfile
}
}
}
//-----------------------------------------------------------
// Add observer for InstanceID token refresh callback.
NotificationCenter.default.addObserver(self,selector: #selector(self.tokenRefreshNotification),
name: .InstanceIDTokenRefresh,
object: nil)
// -- register for remote notifications
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
// For iOS 10 data message (sent via FCM)
Messaging.messaging().delegate = self
Messaging.messaging().shouldEstablishDirectChannel = true
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
// -- google maps provide api key --
//GMSServices.provideAPIKey(configs.googleAPIKey)
GMSServices.provideAPIKey("AIzaSyCa3yhDGMZM2xHCc5ieYeyz87SuHYDzozU")
//GMSPlacesClient.provideAPIKey("AIzaSyDQFAsFkYGDcH9SIayjQKtmCnmnDQDGP_U")
GMSPlacesClient.provideAPIKey("AIzaSyCa3yhDGMZM2xHCc5ieYeyz87SuHYDzozU")
// -- google search api key for search nearby by ibrahim
GoogleApi.shared.initialiseWithKey("AIzaSyCa3yhDGMZM2xHCc5ieYeyz87SuHYDzozU")
// -- enable IQKeyboardManager --
IQKeyboardManager.shared.enable = true
//IQKeyboardManager.sharedManager().enable = true
// -- start location manager --
locationManager.startUpdatingLocation()
// -- set navigationbar appearance --
UINavigationBar.appearance().tintColor = UIColor.black
UINavigationBar.appearance().barTintColor = UIColor.white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.font: UIFont(name: customFont.medium, size: 19.0)!,
NSAttributedString.Key.foregroundColor: UIColor.black ]
// set rootview controller
if Common.instance.isUserLoggedIn() {
if LocalizationSystem.sharedInstance.getLanguage() == "ar" {
self.updateLanguage(lang_nu:"1", lang_text:"ar")
}
else{
self.updateLanguage(lang_nu:"2", lang_text:"en")
}
if (Auth.auth().currentUser != nil && Common.instance.getUserId().count > 0) {
loginByMobile(mobileNumber: String((Auth.auth().currentUser?.phoneNumber)!),
password: String((Auth.auth().currentUser?.uid)!),
token: String((Auth.auth().currentUser?.refreshToken)!))
}
let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil)
let menu = mainStoryBoard.instantiateViewController(withIdentifier: "MenuViewController") as! MenuViewController
let dashboard = mainStoryBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
let dashboardNav = UINavigationController(rootViewController: dashboard)
let revealController = SWRevealViewController(rearViewController: menu, frontViewController: dashboardNav)
self.window?.rootViewController = revealController
}
Fabric.with([Crashlytics.self])
return true
}
func loginByMobile(mobileNumber:String ,password:String , token:String){
var params = [String:Any]()
//params["email"] = self.emailText.text
params["mobile"] = mobileNumber
params["password"] = password
params["utype"] = "1" // utype = "0" means user and "1" = driver
APIRequestManager.request(apiRequest: APIRouters.LoginUser(params), success: { (responseData) in
if let data = responseData as? [String:Any] {
let userData = User(userData: data)
let encodedData = NSKeyedArchiver.archivedData(withRootObject: userData)
UserDefaults.standard.set(encodedData, forKey: "user")
UserDefaults.standard.set(data["key"], forKey: "key")
if userData.brand?.count == 0 {
self.setVehicleInfo()
} else {
self.moveToDashboard()
}
}
}, failure: { (message) in
//Common.showAlert(with: NSLocalizedString("Alert!!", comment: ""), message: message, for: self)
self.moveToSignUpPage(mobileParam: mobileNumber , passwordParam: password, token:token)
}, error: { (err) in
})
}
func moveToDashboard(){
let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil)
let menu = mainStoryBoard.instantiateViewController(withIdentifier: "MenuViewController") as! MenuViewController
let dashboard = mainStoryBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
let dashboardNav = UINavigationController(rootViewController: dashboard)
let revealController = SWRevealViewController(rearViewController: menu, frontViewController: dashboardNav)
self.window?.rootViewController = revealController
}
func moveToSignUpPage(mobileParam:String , passwordParam:String , token:String){
let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil)
let menu = mainStoryBoard.instantiateViewController(withIdentifier: "MenuViewController") as! MenuViewController
let dashboard = mainStoryBoard.instantiateViewController(withIdentifier: "SplashViewController") as! SplashViewController
// dashboard.UserData = ["mobile":mobileParam, "password":passwordParam,"gcm_token":token]
let dashboardNav = UINavigationController(rootViewController: dashboard)
let revealController = SWRevealViewController(rearViewController: menu, frontViewController: dashboardNav)
self.window?.rootViewController = revealController
}
func setVehicleInfo() {
let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil)
let menu = mainStoryBoard.instantiateViewController(withIdentifier: "MenuViewController") as! MenuViewController
let dashboard = mainStoryBoard.instantiateViewController(withIdentifier: "VehicleTableViewController") as! VehicleTableViewController
dashboard.isFromLogin = true
let dashboardNav = UINavigationController(rootViewController: dashboard)
let revealController = SWRevealViewController(rearViewController: menu, frontViewController: dashboardNav)
self.window?.rootViewController = revealController
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// 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.
locationManager.stopUpdatingLocation()
// FIRMessaging.messaging().disconnect()
// print("Disconnected from FCM.")
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
locationManager.startUpdatingLocation()
connectToFcm()
}
func applicationWillTerminate(_ applcation: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// [START receive_message]
func application(_ application: UIApplication,
didReceiveRemoteNotification notification: [AnyHashable : Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if Auth.auth().canHandleNotification(notification) {
completionHandler(.newData)
return
}
// This notification is not auth related, developer should handle it.
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
let messageID = userInfo["gcm.message_id"]
print("Message ID: \(messageID)")
if let messageID = userInfo["gcm.message_id"] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
}
// [END receive_message]
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// InstanceID.instanceID().setAPNSToken(deviceToken, type: InstanceIDAPNSTokenType.unknown)
// Auth.auth().setAPNSToken(deviceToken, type: AuthAPNSTokenType.unknown)
// Messaging.messaging().apnsToken = deviceToken
let token1 = Messaging.messaging().fcmToken
print("FCM token: \(token1 ?? "")")
var params = [String:String]()
params["user_id"] = Common.instance.getUserId()
params["Token"] = token1
let headers = ["X-API-KEY":Common.instance.getAPIKey()]
APIRequestManager.request(apiRequest: APIRouters.UpdateToken(params,headers), success: { (responseData) in
print("success")
}, failure: { (message) in
}, error: { (err) in
})
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
// print(error.localizedDescription)
}
// [START: Handle Notification]
func handleNotification(userInfo:[AnyHashable:Any]){
NotificationCenter.default.post(name: Firebase.Notification.Name("NotificationRecieved"), object: nil)
}
// [END: Handle Notification]
// [START refresh_token]
@objc func tokenRefreshNotification(notification: NSNotification) {
//ibrahim was here
// if let refreshedToken = InstanceID.instanceID().token() {
// print("InstanceID token: \(refreshedToken)")
//
// let defaults = UserDefaults.standard
// defaults.set(refreshedToken, forKey: "DEVICE_TOKEN")
// defaults.synchronize()
//
// if Common.instance.getUserId().count > 0{
// self.updateToken(token: refreshedToken)
// }
// }
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
// [END refresh_token]
// [START connect_to_fcm]
func connectToFcm() {
//ibrahim was here
// Won't connect since there is no token
// guard InstanceID.instanceID().token() != nil else {
// return
// }
// Disconnect previous FCM connection if it exists.
// Messaging.messaging().disconnect()
// connect to FCM
// Messaging.messaging().connect { (error) in
// if (error != nil) {
// print("Unable to connect with FCM. \(error.debugDescription)")
// } else {
// print("Connected to FCM.")
// }
// }
}
// [END connect_to_fcm]
// MARK: - Update Token
func updateToken(token:String){
var params = [String:String]()
params["user_id"] = Common.instance.getUserId()
params["gcm_token"] = token
let headers = ["X-API-KEY":Common.instance.getAPIKey()]
APIRequestManager.request(apiRequest: APIRouters.UpdateUser(params,headers), success: { (responseData) in
//..
}, failure: { (message) in
}, error: { (err) in
// print(err.localizedDescription)
})
}
func updateLanguage(lang_nu:String, lang_text:String)
{
print("ibrahim change language")
//lang_nu 1 => arabic, 2 => english
var params = [String:String]()
params["user_id"] = Common.instance.getUserId()
params["lang_nu"] = lang_nu
params["lang_text"] = lang_text
let headers = ["X-API-KEY":Common.instance.getAPIKey()]
APIRequestManager.request(apiRequest: APIRouters.UpdateLanguage(params,headers), success: { (responseData) in
print("success changing language")
}, failure: { (message) in
}, error: { (err) in
})
}
}
// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// Print message ID.
// print("Message ID: \(userInfo["gcm.message_id"]!)")
// Print full message.
// debugPrint("%@", userInfo)
completionHandler(UNNotificationPresentationOptions.alert)
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
// print("Message ID: \(userInfo["gcm.message_id"]!)")
// Print full message.
// debugPrint("%@", userInfo)
completionHandler()
}
}
extension AppDelegate {
// Receive data message on iOS 10 devices.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
// print("Received data message: \(remoteMessage.appData)")
}
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
// print("Firebase registration token: \(fcmToken)")
}
func redirectToView(_ userInfo:[AnyHashable:Any]) {
if let viewInfo: [String:Any] = userInfo as? [String : Any], let view: String = viewInfo["action"] as? String {
let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil)
if view == "PENDING" {
let vc = mainStoryBoard.instantiateViewController(withIdentifier: "RequestsViewController") as! RequestsViewController
vc.requestPage = RequestView.pending
let nav = UINavigationController(rootViewController: vc)
nav.setViewControllers([vc], animated:true)
self.window?.rootViewController?.revealViewController().setFront(nav, animated: true)
self.window?.rootViewController?.revealViewController().pushFrontViewController(nav, animated: true)
} else if view == "ACCEPTED" {
let vc = mainStoryBoard.instantiateViewController(withIdentifier: "RequestsViewController") as! RequestsViewController
vc.requestPage = RequestView.accepted
let nav = UINavigationController(rootViewController: vc)
nav.setViewControllers([vc], animated:true)
self.window?.rootViewController?.revealViewController().setFront(nav, animated: true)
self.window?.rootViewController?.revealViewController().pushFrontViewController(nav, animated: true)
} else if view == "COMPLETED" {
let vc = mainStoryBoard.instantiateViewController(withIdentifier: "RequestsViewController") as! RequestsViewController
vc.requestPage = RequestView.completed
let nav = UINavigationController(rootViewController: vc)
nav.setViewControllers([vc], animated:true)
self.window?.rootViewController?.revealViewController().setFront(nav, animated: true)
self.window?.rootViewController?.revealViewController().pushFrontViewController(nav, animated: true)
} else if view == "CANCELLED" {
let vc = mainStoryBoard.instantiateViewController(withIdentifier: "RequestsViewController") as! RequestsViewController
vc.requestPage = RequestView.cancelled
let nav = UINavigationController(rootViewController: vc)
nav.setViewControllers([vc], animated:true)
self.window?.rootViewController?.revealViewController().setFront(nav, animated: true)
self.window?.rootViewController?.revealViewController().pushFrontViewController(nav, animated: true)
}
}
}
}
|
//
// Card.swift
// Flipcard
//
// Created by Natalia Zarawska 2 on 08/02/17.
// Copyright © 2017 Natalia Zarawska 2. All rights reserved.
//
import UIKit
struct CardDeck {
let name: String
let id: String
let cards: [Card]?
}
struct Card {
let question: CardSide
let answer: CardSide
}
struct CardSide {
let text: String
let image: String?
}
|
//
// DetailsInteractor.swift
// MovieApp
//
// Created by Ahmad Aulia Noorhakim on 27/02/21.
//
import Combine
import Foundation
protocol DetailsInteractorInput {
func fetchCredits(movieId id: Int)
}
protocol DetailsInteractorOutput {
func showSuccess(_ casts: [Details.ViewModel.Cast])
}
final class DetailsInteractor: DetailsInteractorInput {
let output: DetailsInteractorOutput
let worker: DetailsWorkerProtocol
var cancellables = Set<AnyCancellable>()
init(_ output: DetailsInteractorOutput, _ worker: DetailsWorkerProtocol) {
self.output = output
self.worker = worker
}
func fetchCredits(movieId id: Int) {
worker.fetchCredits(movieId: id)
.sink(
receiveCompletion: { completion in
switch completion {
case .finished: break
case .failure(let error): debugPrint(error)
}
},
receiveValue: { [weak self] response in
let casts = response.casts
.lazy
.filter { entry in entry.character != nil }
.map { entry in
Details.ViewModel.Cast(
name: entry.name,
character: entry.character!,
profile: entry.profile.map { ApiRouter.getImageUrl(path: $0, forType: .profile) }
)
}
self?.output.showSuccess(Array(casts))
}
)
.store(in: &cancellables)
}
}
|
//
// RxFormTests.swift
// RxFormTests
//
// Created by Matin Abdollahi on 9/1/20.
// Copyright © 2020 IEM. All rights reserved.
//
import XCTest
import RxSwift
@testable import RxForm
class RxFormTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testValidEmailFormat() {
let formControl = FormControl("Matin@gmail.com", validators: [Validators.email])
XCTAssertTrue(formControl.valid, "E-Mail validator failed")
}
func testInvalidEmailFormat() {
let formControl = FormControl("matin@gmail", validators: [Validators.email])
XCTAssertFalse(formControl.valid, "E-Mail validator failed")
}
func testValidMinLength() {
let formControl = FormControl("Hello", validators: [Validators.maxLength(6)])
XCTAssertTrue(formControl.valid, "Min length validator failed")
}
func testEmptyEmailFormat() {
let formControl = FormControl("", validators: [Validators.email])
XCTAssertTrue(formControl.valid, "E-Mail validator failed")
}
func testNullEmailFormat() {
let formControl = FormControl(nil, validators: [Validators.email])
XCTAssertTrue(formControl.valid, "E-Mail validator fail")
}
func testRequiredFormControl() {
let formControl = FormControl("", validators: [Validators.required])
XCTAssertTrue(formControl.errors["required"] != nil, "Required validator fail")
}
func testValue() {
let formControl = FormControl("Matin", validators: [Validators.required])
XCTAssertEqual(formControl.value as! String, "Matin")
}
func testFormGroupValidity() {
let formGroup = FormGroup(controls: [
"username": FormControl("matin3238@gmail.com", validators: [Validators.email]),
"password": FormControl("1234", validators: [Validators.required, Validators.minLength(4)])
])
XCTAssertTrue(formGroup.controls["username"]!.valid, "ridi")
}
func testSetFormControlValue() {
let formControl = FormControl()
formControl.setValue("Matin")
XCTAssertEqual(formControl.value as! String, "Matin")
}
func testSetFormGroupValue() {
let formGroup = FormGroup(controls: [
"username": FormControl("matin3238@gmail.com", validators: [Validators.email]),
"password": FormControl("1234", validators: [Validators.required, Validators.minLength(4)])
])
formGroup.setValue(["username" : "matin"], options: (false, true))
XCTAssertFalse(formGroup.valid)
}
func testValidNestedFormGroups() {
let innerFormGroup = FormGroup(controls: [
"username": FormControl("matin3238@gmail.com", validators: [Validators.email]),
"password": FormControl("1234", validators: [Validators.required, Validators.minLength(4)])
])
let outerFormGroup = FormGroup(controls: [
"inner": innerFormGroup,
"toggle": FormControl(true)
])
XCTAssertTrue(outerFormGroup.valid)
}
func testInValidNestedFormGroups() {
let innerFormGroup = FormGroup(controls: [
"username": FormControl("matin.com", validators: [Validators.email]),
"password": FormControl("1234", validators: [Validators.required, Validators.minLength(4)])
])
let outerFormGroup = FormGroup(controls: [
"inner": innerFormGroup,
"toggle": FormControl(true)
])
XCTAssertFalse(outerFormGroup.valid)
}
func testPendingState() {
let innerFormGroup = FormGroup(controls: [
"username": FormControl("matin3238@gmail.com", validators: [Validators.email]),
"password": FormControl("1234", validators: [Validators.required, Validators.minLength(4)]),
"toggle": FormControl(true, asyncValidators: [createAsyncValidator(seconds: 3)])
])
let outerFormGroup = FormGroup(controls: [
"inner": innerFormGroup,
"toggle": FormControl(true)
])
XCTAssertTrue(outerFormGroup.pending)
}
func testDeallocation() {
var innerFormGroup: FormGroup? = FormGroup(controls: [
"username": FormControl("matin3238@gmail.com", validators: [Validators.email]),
"password": FormControl("1234", validators: [Validators.required, Validators.minLength(4)]),
"toggle": FormControl(true, asyncValidators: [createAsyncValidator(seconds: 3)])
])
var outerFormGroup: FormGroup? = FormGroup(controls: [
"inner": innerFormGroup!,
"toggle": FormControl(true)
])
weak var weakControl: AbstractControl? = innerFormGroup?.get("username")
outerFormGroup?.setValue([
"inner": [
"username": "Matin",
"password": "1234",
]
])
outerFormGroup = nil
innerFormGroup = nil
XCTAssertNil(weakControl)
}
private func createAsyncValidator(seconds: Int) -> AsyncValidator {
return { (control: AbstractControl) in
return Single<[String : Any]?>.just(nil)
.delay(RxTimeInterval.seconds(seconds), scheduler: MainScheduler.instance)
}
}
}
|
//: Playground - noun: a place where people can play
import UIKit
/*
// Strings
var str = "Hello, playground"
var name:String = "Paige"
print("Hello " + name + ".")
print("Hello \(name)")
// Integers (whole numbers)
var int:Int = 9
int = int * 2
int = int / 4
var anotherInt = 7
print(int + anotherInt)
print("The value of int is \(int)")
// Doubles (numbers with decimals)
var number:Double = 8.4
print(number * Double(int))
// Booleans (true or false)
var isMale:Bool = true
var myDouble:Double = 2.2
var myInt:Int = 2
print("The product of \(myDouble) and \(myInt) is \(myDouble * Double(myInt))")
// Arrays
var array = [17, 25, 13, 47]
print(array[0])
print(array[2])
print(array.count)
array.append(56)
array.removeAtIndex(3)
print(array)
array.sort()
var myArray = [6.1, 8.4, 7.2]
myArray.removeAtIndex(1)
myArray.append(myArray[0] * myArray[1])
print(myArray)
// Dictionaries
var dictionary = [
"computer": "something to play Call of Duty on",
"coffee": "best drink ever"
]
print(dictionary["coffee"]!)
print(dictionary.count)
dictionary["pen"] = "Old fashioned writing implement"
dictionary.removeValueForKey("computer")
print(dictionary)
var menu = [
"coffee": 3.24,
"pizza": 5.99,
"ice cream": 4.99
]
var totalCost:Double = menu["coffee"]! + menu["pizza"]! + menu["ice cream"]!
print("The total cost of the three items is \(totalCost)")
// If Statements
var age = 13
// Greater than or equal to
if age >= 18 {
print("You can play!")
} else {
print("Sorry, you're too young")
}
var myName = "Johnny"
// Equal to
if myName == "Paige" {
print("Hi " + myName + " you can play!")
} else {
print("Sorry, " + " you can't play")
}
// 2 If statements with AND
if myName == "Johnny" && age >= 18 {
print("You can play!")
}
// 2 If statements with OR
if myName == "Johnny" || myName == "Paige" {
print("Welcome " + myName)
}
var isFemale = true
if isFemale {
print("You are a women!")
}
var userName = "pslim"
var password = "password"
if userName == "pslim" && password == "password" {
print("You're in!")
} else if userName != "pslim" && password != "password" {
print("Both fields are wrong")
} else if userName != "pslim" {
print("UserName incorrect")
} else if password != "password" {
print("Password is wrong")
}
// For Loops
for var i = 1; i < 10; i++ {
print(i)
}
for var i = 20; i > 10; i-- {
print(i)
}
for var i = 2; i <= 20; i = i + 2 {
print(i)
}
var arr = [8, 3, 9, 91]
for x in arr {
print(x)
}
for (index, value) in arr.enumerate() {
arr[index] = value + 1
}
print(arr)
var myArr:[Double] = [8, 3, 9, 91]
for (index,value) in myArr.enumerate() {
myArr[index] = value / 2
}
print(myArr)
// Basic While Loop
//var i = 1
//
//while i < 10 {
//
// print(i)
//
// i = i * 2
//}
//
//var n = 1
//
//while n <= 10 {
// print(n * 5)
// n++
//}
var arr2 = [8, 3, 1, 9, 4, 5, 7]
var i = 0
//while i < arr2.count {
// print(arr2[i])
// i++
//}
while i < arr2.count {
arr2[i] = arr2[i] - 1
i++
}
print(arr2)
var number = 47
var isPrime = true
if number != 2 && number != 1 {
for var i = 2; i < number; i++ {
if number % i == 0 {
isPrime = false
}
}
} else if number == 1 {
isPrime = false
}
print(isPrime)
*/
// String Manipulation
var str = "Hello"
var newString = str + " Paige"
for character in newString.characters {
print(character)
}
var newTypeString = NSString(string: newString)
newTypeString.substringToIndex(5)
newTypeString.substringFromIndex(6)
newTypeString.substringWithRange(NSRange(location: 3, length: 5))
if newTypeString.containsString("Paige") {
print("Paige is here!")
}
newTypeString.componentsSeparatedByString(" ")
newTypeString.uppercaseString
newTypeString.lowercaseString
|
//
// ResultHandler.swift
// Biirr
//
// Created by Ana Márquez on 05/03/2021.
//
import Foundation
enum Result<Value, Error> {
case success(Value)
case failure(Error)
}
|
//
// MovieDetailsViewModel.swift
// FaMulan
//
// Created by Bia Plutarco on 18/07/20.
// Copyright © 2020 Bia Plutarco. All rights reserved.
//
import UIKit
class MovieDetailsViewModel {
private let movieRepository: MovieDataRepository
private let genreRepository: GenreDataRepository
private var similarMovies = [SimilarMovie]()
private var mulan: Movie?
private var genres = [Genre]()
var image: UIImage? {
didSet {
reloadImage?()
}
}
var reloadImage: (() -> Void)?
var numberOfRows: Int {
return similarMovies.count
}
init(movieRepository: MovieDataRepository = MovieDataRepository(),
genreRepository: GenreDataRepository = GenreDataRepository()) {
self.movieRepository = movieRepository
self.genreRepository = genreRepository
loadMulanDetails()
}
private func loadMulanDetails() {
movieRepository.loadDetails(of: Constants.TMDB.mulanID) { result in
switch result {
case .failure(let error):
print(error.localizedDescription)
case .success(let movie):
self.mulan = movie
self.loadGenres()
self.loadMoviePoster()
self.loadSimilarMovies()
}
}
}
private func loadSimilarMovies() {
movieRepository.loadMoviesSimilar(to: Constants.TMDB.mulanID) { result in
switch result {
case .failure(let error):
print(error.localizedDescription)
case .success(let movie):
self.similarMovies = movie.similarMovies
}
}
}
private func loadGenres() {
genreRepository.loadGernes { result in
switch result {
case .failure(let error):
print(error.localizedDescription)
case .success(let genres):
self.genres = genres.genres
}
}
}
private func loadMoviePoster() {
guard let posterPath = self.mulan?.posterPath else { return }
movieRepository.loadMoviePoster(path: posterPath) { image in
self.image = image
}
}
func similarMovieViewModel(for index: Int) -> SimilarMovieViewModel {
var similarMovie = similarMovies[index]
similarMovie.genres = genres.filter({ similarMovie.genresID.contains($0.id) })
return SimilarMovieViewModel(similarMovie)
}
func headerViewMovel() -> MovieDetailsHeaderViewModel? {
guard let mulan = self.mulan else { return nil }
return MovieDetailsHeaderViewModel(mulan)
}
}
|
//
// CompanyListCoordinator.swift
// Favorites Food
//
// Created by Pavel Kurilov on 30.10.2018.
// Copyright © 2018 Pavel Kurilov. All rights reserved.
//
import Foundation
import UIKit
protocol UpdateableWitchContactList: class {
var company: Company? { get set }
var food: Food? { get set }
}
final class CompanyListCoordinator {
// MARK: - Properties
private weak var navigationController: UINavigationController?
private var navigFoodController: UINavigationController?
// MARK: - Init
init(navigationController: UINavigationController) {
let textAttributes = [NSAttributedStringKey.foregroundColor: UIColor.black]
self.navigationController = navigationController
self.navigationController?.navigationBar.barTintColor = .moderatePink
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.tintColor = .black
self.navigationController?.navigationBar.titleTextAttributes = textAttributes
self.navigationController?.setNavigationBarHidden(true, animated: false)
}
func start() {
showContactList()
}
// MARK: - Private implementation
private func showContactList() {
let companiesListViewModel = CompanyListViewModel()
let foodsListViewModel = FoodListViewModel()
foodsListViewModel.delegate = self
let mapViewModel = MapCompaniesViewModel()
let companiesController = CompanyListController(viewModel: companiesListViewModel)
let foodController = FoodListViewController(viewModel: foodsListViewModel)
let mapController = MapCompaniesController(viewModel: mapViewModel)
let navCompaniesController = UINavigationController(rootViewController: companiesController)
let navFoodController = UINavigationController(rootViewController: foodController)
let navMapController = UINavigationController(rootViewController: mapController)
navCompaniesController.configureNavigationBar(navigationController: navCompaniesController)
navMapController.configureNavigationBar(navigationController: navMapController)
navFoodController.configureNavigationBar(navigationController: navFoodController)
navigFoodController = navFoodController
companiesController.title = "Companies"
companiesController.tabBarItem.image = #imageLiteral(resourceName: "company-icon")
foodController.title = "Foods"
foodController.tabBarItem.image = #imageLiteral(resourceName: "food-icon")
mapController.title = "Map"
mapController.tabBarItem.image = #imageLiteral(resourceName: "map-icon")
let tabBarList = [navCompaniesController, navFoodController, navMapController]
let tabBarController = UITabBarController()
tabBarController.viewControllers = tabBarList
tabBarController.tabBar.tintColor = .red
tabBarController.navigationItem.title = "Hello"
tabBarController.navigationController?.setNavigationBarHidden(true, animated: false)
navigationController?.pushViewController(tabBarController, animated: false)
}
private func showFoodDetail(_ food: Food) {
let viewModel = FoodDetailViewModel(food: food)
let detailController = FoodDetailController(viewModel: viewModel)
detailController.navigationItem.title = viewModel.title
navigFoodController?.pushViewController(detailController, animated: true)
}
}
extension CompanyListCoordinator: FoodListViewModelDelegate {
func foodListViewModel(_ viewModel: FoodListViewModel, didSelectFood food: Food) {
showFoodDetail(food)
}
}
|
//
// Movie+CoreDataClass.swift
// CoreDataProject
//
// Created by Tino on 2/4/21.
//
//
import Foundation
import CoreData
@objc(Movie)
public class Movie: NSManagedObject {
}
|
// Generated using SwiftGen, by O.Halligon — https://github.com/SwiftGen/SwiftGen
#if os(OSX)
import AppKit.NSImage
internal typealias AssetColorTypeAlias = NSColor
internal typealias Image = NSImage
#elseif os(iOS) || os(tvOS) || os(watchOS)
import UIKit.UIImage
internal typealias AssetColorTypeAlias = UIColor
internal typealias Image = UIImage
#endif
// swiftlint:disable superfluous_disable_command
// swiftlint:disable file_length
@available(*, deprecated, renamed: "ImageAsset")
internal typealias ImagesType = ImageAsset
internal struct ImageAsset {
internal fileprivate(set) var name: String
internal var image: Image {
let bundle = Bundle(for: BundleToken.self)
#if os(iOS) || os(tvOS)
let image = Image(named: name, in: bundle, compatibleWith: nil)
#elseif os(OSX)
let image = bundle.image(forResource: NSImage.Name(name))
#elseif os(watchOS)
let image = Image(named: name)
#endif
guard let result = image else { fatalError("Unable to load image named \(name).") }
return result
}
}
internal struct ColorAsset {
internal fileprivate(set) var name: String
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, OSX 10.13, *)
internal var color: AssetColorTypeAlias {
return AssetColorTypeAlias(asset: self)
}
}
// swiftlint:disable identifier_name line_length nesting type_body_length type_name
internal enum Images {
internal static let logoBitcoin48 = ImageAsset(name: "logoBitcoin48")
internal static let logoBitcoincash48 = ImageAsset(name: "logoBitcoincash48")
internal static let logoDash48 = ImageAsset(name: "logoDash48")
internal static let logoEthereum48 = ImageAsset(name: "logoEthereum48")
internal static let logoEuro48 = ImageAsset(name: "logoEuro48")
internal static let logoLira48 = ImageAsset(name: "logoLira48")
internal static let logoLtc48 = ImageAsset(name: "logoLtc48")
internal static let logoMonero48 = ImageAsset(name: "logoMonero48")
internal static let logoUsd48 = ImageAsset(name: "logoUsd48")
internal static let logoWaves48 = ImageAsset(name: "logoWaves48")
internal static let logoWct48 = ImageAsset(name: "logoWct48")
internal static let logoZec48 = ImageAsset(name: "logoZec48")
internal static let scriptasset18White = ImageAsset(name: "scriptasset18White")
internal static let setting14Classic = ImageAsset(name: "setting14Classic")
internal static let sponsoritem18White = ImageAsset(name: "sponsoritem18White")
internal static let update14Classic = ImageAsset(name: "update14Classic")
// swiftlint:disable trailing_comma
internal static let allColors: [ColorAsset] = [
]
internal static let allImages: [ImageAsset] = [
logoBitcoin48,
logoBitcoincash48,
logoDash48,
logoEthereum48,
logoEuro48,
logoLira48,
logoLtc48,
logoMonero48,
logoUsd48,
logoWaves48,
logoWct48,
logoZec48,
scriptasset18White,
setting14Classic,
sponsoritem18White,
update14Classic,
]
// swiftlint:enable trailing_comma
@available(*, deprecated, renamed: "allImages")
internal static let allValues: [ImagesType] = allImages
}
// swiftlint:enable identifier_name line_length nesting type_body_length type_name
internal extension Image {
@available(iOS 1.0, tvOS 1.0, watchOS 1.0, *)
@available(OSX, deprecated,
message: "This initializer is unsafe on macOS, please use the ImageAsset.image property")
convenience init!(asset: ImageAsset) {
#if os(iOS) || os(tvOS)
let bundle = Bundle(for: BundleToken.self)
self.init(named: asset.name, in: bundle, compatibleWith: nil)
#elseif os(OSX)
self.init(named: NSImage.Name(asset.name))
#elseif os(watchOS)
self.init(named: asset.name)
#endif
}
}
internal extension AssetColorTypeAlias {
@available(iOS 11.0, tvOS 11.0, watchOS 4.0, OSX 10.13, *)
convenience init!(asset: ColorAsset) {
let bundle = Bundle(for: BundleToken.self)
#if os(iOS) || os(tvOS)
self.init(named: asset.name, in: bundle, compatibleWith: nil)
#elseif os(OSX)
self.init(named: NSColor.Name(asset.name), bundle: bundle)
#elseif os(watchOS)
self.init(named: asset.name)
#endif
}
}
private final class BundleToken {}
|
//
// ArtistLayoutType.swift
// ArtistCustomLayout
//
// Created by Alex Tapia on 15/06/20.
// Copyright © 2020 AlexTapia. All rights reserved.
//
import Foundation
enum ArtistLayoutType {
case list
case grid
}
|
//
// Entity+CoreDataClass.swift
// dasCriancas
//
// Created by Cassia Aparecida Barbosa on 22/07/19.
// Copyright © 2019 Cassia Aparecida Barbosa. All rights reserved.
//
//
import Foundation
import CoreData
public class Entity: NSManagedObject {
}
|
//
// FormArtController.swift
// ArtMap
//
// Created by Andrea Mantani on 10/10/15.
// Copyright © 2015 Andrea Mantani. All rights reserved.
//
import UIKit
import Social
class FormArtController : UIViewController{
@IBOutlet weak var imageForm: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var authorLabel: UILabel!
@IBOutlet weak var yearLabel: UILabel!
@IBOutlet weak var stateLabel: UILabel!
@IBOutlet weak var infoDecorationLabel: UILabel!
@IBAction func sendReport(sender: UIButton) {
if let resultController = storyboard?.instantiateViewControllerWithIdentifier("reportInterface") as? ReportViewController{
resultController.setReportInfo(setForm)
presentViewController(resultController, animated: true, completion: nil)
}
}
var setForm : Marker = Marker()
@IBAction func showArtist(sender: AnyObject) {
if setForm.getArt().getAuthor() == "" || setForm.getArt().getAuthor().uppercaseString == "UNKNOWN" {
return
}
if let resultController = storyboard?.instantiateViewControllerWithIdentifier("artistProfile") as? ArtistProfileController{
resultController.setArtist(setForm)
presentViewController(resultController, animated: true, completion: nil)
}
}
@IBAction func backAction(sender: UIBarButtonItem) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func shareButton(sender: UIBarButtonItem) {
var content : String
if setForm.getArt().getAuthor() == ""{
content = "Author: Unknown \n\nCondiviso con ArtMap! - versione iOS"
}
content = "Author: " + setForm.getArt().getAuthor() + " \n\nCondiviso con ArtMap! - versione iOS"
let act = UIActivityViewController(activityItems: [setForm, content, setForm.getMarker()], applicationActivities: nil)
self.presentViewController(act, animated: true, completion: nil)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
imageForm.image = setForm.getImage()
let tmp = setForm.getArt()
titleLabel.text = tmp.getTitle().capitalizedString
if tmp.getTitle() == "" || tmp.getTitle().uppercaseString == "UNKNOWN"{
titleLabel.text = "NESSUN TITOLO"
titleLabel.textColor = UIColor.grayColor().colorWithAlphaComponent(0.6)
}
authorLabel.text = tmp.getAuthor().uppercaseString
if tmp.getAuthor() == "" || tmp.getAuthor().uppercaseString == "UNKNOWN"{
authorLabel.text = "NESSUN AUTORE"
authorLabel.textColor = UIColor.grayColor().colorWithAlphaComponent(0.6)
infoDecorationLabel.hidden = true
}
yearLabel.text = String(tmp.getYear())
if tmp.getYear() == 0 {
yearLabel.text = "NESSUNA DATA"
yearLabel.textColor = UIColor.grayColor().colorWithAlphaComponent(0.6)
}
if tmp.getState() == 0{
stateLabel.text = "NON AGGIORNATO"
} else if tmp.getState() == 1{
stateLabel.text = "VISIBILE"
} else if tmp.getState() == 2{
stateLabel.text = "ROVINATO/INACCESSIBILE"
} else {
stateLabel.text = "RIMOSSO"
stateLabel.textColor = UIColor.grayColor().colorWithAlphaComponent(0.6)
}
super.viewDidLoad()
}
func setFormInfo(value: Marker){
self.setForm = value
print(value.getArt().getTitle())
print(self.setForm.getArt().getTitle())
}
} |
//
// ViewController.swift
// AutoLayoutPractice
//
// Created by Kristopher Kane on 7/15/15.
// Copyright (c) 2015 Kris Kane. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var calculationLabel = UILabel()
// First Row
var clearButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
var lineClearButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
var moduloButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
var divideButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
// Second Row
var sevenButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
var eightButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
var nineButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
var multiplyButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
// Third Row
var fourButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
var fiveButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
var sixButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
var minusButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
// Fourth Row
var oneButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
var twoButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
var threeButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
var plusButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
// Fifth Row
var zeroButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
var placeholder = UIButton.buttonWithType(UIButtonType.System) as! UIButton
var decimalButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
var equalButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
// Use this to set the spacing between button if so desired
let spacingConstant : CGFloat = 0.0
// Calculator functionality variables
var calculationValues : [Double] = [] // Stores calculated value
var operationArray : [(Double,Double)->Double] = [] // Stores user input of operators
var numbersEnteredArray : [String] = [] // Stores user input of numbers
// Store operators in dictionary
let operators: [String:(Double,Double)->Double] = [
"+": (+),
"-": (-),
"/": (/),
"x": (*)
]
// DRY function for operations in case statement nested inside doPressButton()
func doSomeOperation(buttonTitle: String) {
if calculationValues.count != 0 {
calculationLabel.text = "\(calculationValues[0]) \(buttonTitle)"
numbersEnteredArray = []
operationArray.append(operators[buttonTitle]!)
} else {
calculationValues.append((displayNumber as NSString).doubleValue)
if (calculationValues[0] % 1) == 0 {
let displayInteger = Int(calculationValues[0])
calculationLabel.text = "\(displayInteger) \(buttonTitle)"
numbersEnteredArray = []
operationArray.append(operators[buttonTitle]!)
} else {
calculationLabel.text = "\(calculationValues[0]) \(buttonTitle)"
numbersEnteredArray = []
operationArray.append(operators[buttonTitle]!)
}
}
}
// Create a string from the array of Numbers the user entered before an operator
func createNumberToDisplay() -> String {
var numberString = String()
numberString = "".join(numbersEnteredArray)
return numberString
}
// Empty temporary variables between calculations or on "C" press
func reset() {
numbersEnteredArray = []
if calculationValues.count == 0 {
calculationLabel.text = "0"
} else {
calculationLabel.text = "\(calculationValues[0])"
}
}
// Empty all variables, prepare for all new calculation
func clearAll() {
operationArray = []
displayNumber = ""
calculationValues = []
numbersEnteredArray = []
calculationLabel.text = "0"
}
// Actually perform the calculation by using the stored operator
func performCalculations() -> Double {
println(calculationValues)
println(calculationValues.count)
if calculationValues.count == 2 {
let solution = operationArray[0](calculationValues[0], calculationValues[1])
println("After: \(calculationValues)")
return solution
} else {
calculationLabel.text = "ERROR"
}
return 0.0
}
var displayNumber : String = ""
func doPressButton(sender: UIButton!) {
let buttonTitle = sender.titleLabel?.text
if let buttonTitle = buttonTitle {
switch buttonTitle {
case "1","2","3","4","5","6","7","8","9","0":
numbersEnteredArray.append(buttonTitle)
displayNumber = createNumberToDisplay()
calculationLabel.text = "\(displayNumber)"
case "AC":
clearAll()
case "C":
reset()
calculationLabel.text = "0"
case "%":
if calculationValues.count != 0 {
operationArray.append(%)
reset()
} else {
calculationValues.append((displayNumber as NSString).doubleValue)
operationArray.append(%)
reset()
}
case "/":
doSomeOperation(buttonTitle)
case "x":
doSomeOperation(buttonTitle)
case "-":
doSomeOperation(buttonTitle)
case "+":
doSomeOperation(buttonTitle)
case "=":
calculationValues.append((displayNumber as NSString).doubleValue)
let solution = performCalculations()
clearAll()
calculationValues.append(solution)
if (calculationValues[0] % 1) == 0 {
let displayInteger = Int(calculationValues[0])
calculationLabel.text = "\(displayInteger)"
println("end of equal case statement \(calculationValues)")
} else {
calculationLabel.text = "\(calculationValues[0])"
println("end of equal case statement \(calculationValues)")
}
case ".":
let numberString = "".join(numbersEnteredArray)
if numberString.rangeOfString(".") != nil{
println("exists")
}else {
numbersEnteredArray.append(".")
displayNumber = createNumberToDisplay()
calculationLabel.text = "\(displayNumber)"
}
default:
println("not a number")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupCalculator()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
}
func setupCalculator() {
// UIView Background Color = black, in lieu of using borders
view.backgroundColor = .blackColor()
// Calculation Label
calculationLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
calculationLabel.backgroundColor = .blackColor()
calculationLabel.font = UIFont(name: "HelveticaNeue-Thin", size: 70)
calculationLabel.numberOfLines = 0
calculationLabel.adjustsFontSizeToFitWidth = true
calculationLabel.textColor = .whiteColor()
calculationLabel.adjustsFontSizeToFitWidth = true
calculationLabel.textAlignment = .Right
view.addSubview(calculationLabel)
// First Row
clearButton.setTranslatesAutoresizingMaskIntoConstraints(false)
clearButton.setTitle("AC", forState: UIControlState.Normal)
view.addSubview(clearButton)
lineClearButton.setTranslatesAutoresizingMaskIntoConstraints(false)
lineClearButton.setTitle("C", forState: UIControlState.Normal)
view.addSubview(lineClearButton)
moduloButton.setTranslatesAutoresizingMaskIntoConstraints(false)
moduloButton.setTitle("%", forState: UIControlState.Normal)
view.addSubview(moduloButton)
divideButton.setTranslatesAutoresizingMaskIntoConstraints(false)
divideButton.setTitle("/", forState: UIControlState.Normal)
view.addSubview(divideButton)
// Second Row
sevenButton.setTranslatesAutoresizingMaskIntoConstraints(false)
sevenButton.setTitle("7", forState: UIControlState.Normal)
view.addSubview(sevenButton)
eightButton.setTranslatesAutoresizingMaskIntoConstraints(false)
eightButton.setTitle("8", forState: UIControlState.Normal)
view.addSubview(eightButton)
nineButton.setTranslatesAutoresizingMaskIntoConstraints(false)
nineButton.setTitle("9", forState: UIControlState.Normal)
view.addSubview(nineButton)
multiplyButton.setTranslatesAutoresizingMaskIntoConstraints(false)
multiplyButton.setTitle("x", forState: UIControlState.Normal)
view.addSubview(multiplyButton)
// Third Row
fourButton.setTranslatesAutoresizingMaskIntoConstraints(false)
fourButton.setTitle("4", forState: UIControlState.Normal)
view.addSubview(fourButton)
fiveButton.setTranslatesAutoresizingMaskIntoConstraints(false)
fiveButton.setTitle("5", forState: UIControlState.Normal)
view.addSubview(fiveButton)
sixButton.setTranslatesAutoresizingMaskIntoConstraints(false)
sixButton.setTitle("6", forState: UIControlState.Normal)
view.addSubview(sixButton)
minusButton.setTranslatesAutoresizingMaskIntoConstraints(false)
minusButton.setTitle("-", forState: UIControlState.Normal)
view.addSubview(minusButton)
// Fourth Row
oneButton.setTranslatesAutoresizingMaskIntoConstraints(false)
oneButton.setTitle("1", forState: UIControlState.Normal)
view.addSubview(oneButton)
twoButton.setTranslatesAutoresizingMaskIntoConstraints(false)
twoButton.setTitle("2", forState: UIControlState.Normal)
view.addSubview(twoButton)
threeButton.setTranslatesAutoresizingMaskIntoConstraints(false)
threeButton.setTitle("3", forState: UIControlState.Normal)
view.addSubview(threeButton)
plusButton.setTranslatesAutoresizingMaskIntoConstraints(false)
plusButton.setTitle("+", forState: UIControlState.Normal)
view.addSubview(plusButton)
// Fifth Row
zeroButton.setTranslatesAutoresizingMaskIntoConstraints(false)
zeroButton.setTitle("0", forState: UIControlState.Normal)
view.addSubview(zeroButton)
placeholder.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(placeholder)
decimalButton.setTranslatesAutoresizingMaskIntoConstraints(false)
decimalButton.setTitle(".", forState: UIControlState.Normal)
view.addSubview(decimalButton)
equalButton.setTranslatesAutoresizingMaskIntoConstraints(false)
equalButton.setTitle("=", forState: UIControlState.Normal)
view.addSubview(equalButton)
// List of grey buttons to be set as grey in subsequent function
let greyButtonArray : [UIButton] = [
clearButton,
lineClearButton,
moduloButton,
oneButton,
twoButton,
threeButton,
fourButton,
fiveButton,
sixButton,
sevenButton,
eightButton,
nineButton,
zeroButton,
decimalButton
]
// List of orange buttons to be set as grey in subsequent function
let orangeButtonArray : [UIButton] = [
divideButton,
multiplyButton,
minusButton,
plusButton,
equalButton
]
// calculationLabel Constraints
let calculationLabelTopConstraint = NSLayoutConstraint(
item: calculationLabel,
attribute: .Top,
relatedBy: .Equal,
toItem: view,
attribute: .Top,
multiplier: 1.0,
constant: 0
)
let calculationLabelLeftConstraint = NSLayoutConstraint(
item: calculationLabel,
attribute: .Left,
relatedBy: .Equal,
toItem: view,
attribute: .Left,
multiplier: 1.0,
constant: 0
)
let calculationLabelRightConstraint = NSLayoutConstraint(
item: calculationLabel,
attribute: .Right,
relatedBy: .Equal,
toItem: view,
attribute: .Right,
multiplier: 1.0,
constant: 0
)
let calculationLabelWidthConstraint = NSLayoutConstraint(
item: calculationLabel,
attribute: .Width,
relatedBy: .Equal,
toItem: view,
attribute: .Width,
multiplier: 1.0,
constant: 0
)
let calculationLabelHeightConstraint = NSLayoutConstraint(
item: calculationLabel,
attribute: .Height,
relatedBy: .Equal,
toItem: clearButton,
attribute: .Height,
multiplier: 2.0,
constant: 0
)
view.addConstraints([calculationLabelTopConstraint, calculationLabelLeftConstraint, calculationLabelRightConstraint, calculationLabelHeightConstraint])
// clearButton Constraints
let clearHeightConstraint = NSLayoutConstraint(
item: clearButton,
attribute: .Height,
relatedBy: .Equal,
toItem: sevenButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let clearWidthConstraint = NSLayoutConstraint(
item: clearButton,
attribute: .Width,
relatedBy: .Equal,
toItem: lineClearButton,
attribute: .Width,
multiplier: 1.0,
constant: 0
)
let clearTopConstraint = NSLayoutConstraint(
item: clearButton,
attribute: .Top,
relatedBy: .Equal,
toItem: calculationLabel,
attribute: .Bottom,
multiplier: 1.0,
constant: spacingConstant
)
let clearLeftConstraint = NSLayoutConstraint(
item: clearButton,
attribute: .Left,
relatedBy: .Equal,
toItem: view,
attribute: .Left,
multiplier: 1.0,
constant: 0
)
view.addConstraints([clearHeightConstraint, clearLeftConstraint, clearTopConstraint, clearWidthConstraint])
// lineClearButton Constraints
let lineClearHeightConstraint = NSLayoutConstraint(
item: lineClearButton,
attribute: .Height,
relatedBy: .Equal,
toItem: eightButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let lineClearWidthConstraint = NSLayoutConstraint(
item: lineClearButton,
attribute: .Width,
relatedBy: .Equal,
toItem: moduloButton,
attribute: .Width,
multiplier: 1.0,
constant: 0
)
let lineClearTopConstraint = NSLayoutConstraint(
item: lineClearButton,
attribute: .Top,
relatedBy: .Equal,
toItem: clearButton,
attribute: .Top,
multiplier: 1.0,
constant: spacingConstant
)
let lineClearLeftConstraint = NSLayoutConstraint(
item: lineClearButton,
attribute: .Left,
relatedBy: .Equal,
toItem: clearButton,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
view.addConstraints([lineClearHeightConstraint, lineClearLeftConstraint, lineClearTopConstraint, lineClearWidthConstraint])
// moduloButton Constraints
let moduloHeightConstraint = NSLayoutConstraint(
item: moduloButton,
attribute: .Height,
relatedBy: .Equal,
toItem: nineButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let moduloWidthConstraint = NSLayoutConstraint(
item: moduloButton,
attribute: .Width,
relatedBy: .Equal,
toItem: divideButton,
attribute: .Width,
multiplier: 1.0,
constant: 0
)
let moduloTopConstraint = NSLayoutConstraint(
item: moduloButton,
attribute: .Top,
relatedBy: .Equal,
toItem: clearButton,
attribute: .Top,
multiplier: 1.0,
constant: spacingConstant
)
let moduloLeftConstraint = NSLayoutConstraint(
item: moduloButton,
attribute: .Left,
relatedBy: .Equal,
toItem: lineClearButton,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
view.addConstraints([moduloHeightConstraint, moduloLeftConstraint, moduloTopConstraint, moduloWidthConstraint])
// divideButton Constraints
let divideHeightConstraint = NSLayoutConstraint(
item: divideButton,
attribute: .Height,
relatedBy: .Equal,
toItem: clearButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let divideWidthConstraint = NSLayoutConstraint(
item: divideButton,
attribute: .Width,
relatedBy: .Equal,
toItem: moduloButton,
attribute: .Width,
multiplier: 1.0,
constant: 0
)
let divideTopConstraint = NSLayoutConstraint(
item: divideButton,
attribute: .Top,
relatedBy: .Equal,
toItem: clearButton,
attribute: .Top,
multiplier: 1.0,
constant: spacingConstant
)
let divideLeftConstraint = NSLayoutConstraint(
item: divideButton,
attribute: .Left,
relatedBy: .Equal,
toItem: moduloButton,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
let divideRightConstraint = NSLayoutConstraint(
item: divideButton,
attribute: .Right,
relatedBy: .Equal,
toItem: view,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
view.addConstraints([divideHeightConstraint, divideWidthConstraint, divideTopConstraint, divideLeftConstraint, divideRightConstraint])
// sevenButton Constraints
let sevenTopConstraint = NSLayoutConstraint(
item: sevenButton,
attribute: .Top,
relatedBy: .Equal,
toItem: clearButton,
attribute: .Bottom,
multiplier: 1.0,
constant: spacingConstant
)
let sevenLeftConstraint = NSLayoutConstraint(
item: sevenButton,
attribute: .Left,
relatedBy: .Equal,
toItem: view,
attribute: .Left,
multiplier: 1.0,
constant: spacingConstant
)
let sevenHeightConstraint = NSLayoutConstraint(
item: sevenButton,
attribute: .Height,
relatedBy: .Equal,
toItem: clearButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let sevenWidthConstraint = NSLayoutConstraint(
item: sevenButton,
attribute: .Width,
relatedBy: .Equal,
toItem: eightButton,
attribute: .Width,
multiplier: 1.0,
constant: 0
)
view.addConstraints([sevenHeightConstraint, sevenLeftConstraint, sevenTopConstraint, sevenWidthConstraint])
// eightButton Constraints
let eightTopConstraint = NSLayoutConstraint(
item: eightButton,
attribute: .Top,
relatedBy: .Equal,
toItem: sevenButton,
attribute: .Top,
multiplier: 1.0,
constant: spacingConstant
)
let eightLeftConstraint = NSLayoutConstraint(
item: eightButton,
attribute: .Left,
relatedBy: .Equal,
toItem: sevenButton,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
let eightHeightConstraint = NSLayoutConstraint(
item: eightButton,
attribute: .Height,
relatedBy: .Equal,
toItem: clearButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let eightWidthConstraint = NSLayoutConstraint(
item: eightButton,
attribute: .Width,
relatedBy: .Equal,
toItem: sevenButton,
attribute: .Width,
multiplier: 1.0,
constant: 0
)
view.addConstraints([eightHeightConstraint, eightLeftConstraint, eightTopConstraint, eightWidthConstraint])
// nineButton Constraints
let nineTopConstraint = NSLayoutConstraint(
item: nineButton,
attribute: .Top,
relatedBy: .Equal,
toItem: eightButton,
attribute: .Top,
multiplier: 1.0,
constant: spacingConstant
)
let nineLeftConstraint = NSLayoutConstraint(
item: nineButton,
attribute: .Left,
relatedBy: .Equal,
toItem: eightButton,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
let nineHeightConstraint = NSLayoutConstraint(
item: nineButton,
attribute: .Height,
relatedBy: .Equal,
toItem: sixButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let nineWidthConstraint = NSLayoutConstraint(
item: nineButton,
attribute: .Width,
relatedBy: .Equal,
toItem: eightButton,
attribute: .Width,
multiplier: 1.0,
constant: 0
)
view.addConstraints([nineHeightConstraint, nineLeftConstraint, nineTopConstraint, nineWidthConstraint])
// multiplyButton Constraints
let multiplyHeightConstraint = NSLayoutConstraint(
item: multiplyButton,
attribute: .Height,
relatedBy: .Equal,
toItem: divideButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let multiplyWidthConstraint = NSLayoutConstraint(
item: multiplyButton,
attribute: .Width,
relatedBy: .Equal,
toItem: nineButton,
attribute: .Width,
multiplier: 1.0,
constant: 0
)
let multiplyTopConstraint = NSLayoutConstraint(
item: multiplyButton,
attribute: .Top,
relatedBy: .Equal,
toItem: sevenButton,
attribute: .Top,
multiplier: 1.0,
constant: spacingConstant
)
let multiplyLeftConstraint = NSLayoutConstraint(
item: multiplyButton,
attribute: .Left,
relatedBy: .Equal,
toItem: nineButton,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
let multiplyRightConstraint = NSLayoutConstraint(
item: multiplyButton,
attribute: .Right,
relatedBy: .Equal,
toItem: view,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
view.addConstraints([multiplyHeightConstraint, multiplyLeftConstraint, multiplyTopConstraint, multiplyWidthConstraint, multiplyRightConstraint])
// fourButton Constraints
let fourTopConstraint = NSLayoutConstraint(
item: fourButton,
attribute: .Top,
relatedBy: .Equal,
toItem: sevenButton,
attribute: .Bottom,
multiplier: 1.0,
constant: spacingConstant
)
let fourLeftConstraint = NSLayoutConstraint(
item: fourButton,
attribute: .Left,
relatedBy: .Equal,
toItem: view,
attribute: .Left,
multiplier: 1.0,
constant: spacingConstant
)
let fourHeightConstraint = NSLayoutConstraint(
item: fourButton,
attribute: .Height,
relatedBy: .Equal,
toItem: sevenButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let fourWidthConstraint = NSLayoutConstraint(
item: fourButton,
attribute: .Width,
relatedBy: .Equal,
toItem: fiveButton,
attribute: .Width,
multiplier: 1.0,
constant: 0
)
view.addConstraints([fourHeightConstraint, fourLeftConstraint, fourTopConstraint, fourWidthConstraint])
// fiveButton Constraints
let fiveTopConstraint = NSLayoutConstraint(
item: fiveButton,
attribute: .Top,
relatedBy: .Equal,
toItem: fourButton,
attribute: .Top,
multiplier: 1.0,
constant: spacingConstant
)
let fiveLeftConstraint = NSLayoutConstraint(
item: fiveButton,
attribute: .Left,
relatedBy: .Equal,
toItem: fourButton,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
let fiveHeightConstraint = NSLayoutConstraint(
item: fiveButton,
attribute: .Height,
relatedBy: .Equal,
toItem: eightButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let fiveWidthConstraint = NSLayoutConstraint(
item: fiveButton,
attribute: .Width,
relatedBy: .Equal,
toItem: sixButton,
attribute: .Width,
multiplier: 1.0,
constant: 0
)
view.addConstraints([fiveHeightConstraint, fiveLeftConstraint, fiveTopConstraint, fiveWidthConstraint])
// sixButton Constraints
let sixTopConstraint = NSLayoutConstraint(
item: sixButton,
attribute: .Top,
relatedBy: .Equal,
toItem: fourButton,
attribute: .Top,
multiplier: 1.0,
constant: spacingConstant
)
let sixLeftConstraint = NSLayoutConstraint(
item: sixButton,
attribute: .Left,
relatedBy: .Equal,
toItem: fiveButton,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
let sixHeightConstraint = NSLayoutConstraint(
item: sixButton,
attribute: .Height,
relatedBy: .Equal,
toItem: nineButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let sixWidthConstraint = NSLayoutConstraint(
item: nineButton,
attribute: .Width,
relatedBy: .Equal,
toItem: minusButton,
attribute: .Width,
multiplier: 1.0,
constant: 0
)
view.addConstraints([sixHeightConstraint, sixLeftConstraint, sixTopConstraint, sixWidthConstraint])
// minusButton Constraints
let minusTopConstraint = NSLayoutConstraint(
item: minusButton,
attribute: .Top,
relatedBy: .Equal,
toItem: fourButton,
attribute: .Top,
multiplier: 1.0,
constant: spacingConstant
)
let minusLeftConstraint = NSLayoutConstraint(
item: minusButton,
attribute: .Left,
relatedBy: .Equal,
toItem: sixButton,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
let minusHeightConstraint = NSLayoutConstraint(
item: minusButton,
attribute: .Height,
relatedBy: .Equal,
toItem: multiplyButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let minusWidthConstraint = NSLayoutConstraint(
item: minusButton,
attribute: .Width,
relatedBy: .Equal,
toItem: sixButton,
attribute: .Width,
multiplier: 1.0,
constant: 0
)
let minusRightConstraint = NSLayoutConstraint(
item: minusButton,
attribute: .Right,
relatedBy: .Equal,
toItem: view,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
view.addConstraints([minusHeightConstraint, minusLeftConstraint, minusRightConstraint, minusTopConstraint, minusWidthConstraint])
// oneButton Constraints
let oneTopConstraint = NSLayoutConstraint(
item: oneButton,
attribute: .Top,
relatedBy: .Equal,
toItem: fourButton,
attribute: .Bottom,
multiplier: 1.0,
constant: spacingConstant
)
let oneLeftConstraint = NSLayoutConstraint(
item: oneButton,
attribute: .Left,
relatedBy: .Equal,
toItem: view,
attribute: .Left,
multiplier: 1.0,
constant: spacingConstant
)
let oneHeightConstraint = NSLayoutConstraint(
item: oneButton,
attribute: .Height,
relatedBy: .Equal,
toItem: fourButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let oneWidthConstraint = NSLayoutConstraint(
item: oneButton,
attribute: .Width,
relatedBy: .Equal,
toItem: twoButton,
attribute: .Width,
multiplier: 1.0,
constant: 0
)
view.addConstraints([oneHeightConstraint, oneLeftConstraint, oneTopConstraint, oneWidthConstraint])
// twoButton Constraints
let twoTopConstraint = NSLayoutConstraint(
item: twoButton,
attribute: .Top,
relatedBy: .Equal,
toItem: oneButton,
attribute: .Top,
multiplier: 1.0,
constant: spacingConstant
)
let twoLeftConstraint = NSLayoutConstraint(
item: twoButton,
attribute: .Left,
relatedBy: .Equal,
toItem: oneButton,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
let twoHeightConstraint = NSLayoutConstraint(
item: twoButton,
attribute: .Height,
relatedBy: .Equal,
toItem: fiveButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let twoWidthConstraint = NSLayoutConstraint(
item: twoButton,
attribute: .Width,
relatedBy: .Equal,
toItem: threeButton,
attribute: .Width,
multiplier: 1.0,
constant: 0
)
view.addConstraints([twoHeightConstraint, twoLeftConstraint, twoTopConstraint, twoWidthConstraint])
// threeButton Constraints
let threeTopConstraint = NSLayoutConstraint(
item: threeButton,
attribute: .Top,
relatedBy: .Equal,
toItem: oneButton,
attribute: .Top,
multiplier: 1.0,
constant: spacingConstant
)
let threeLeftConstraint = NSLayoutConstraint(
item: threeButton,
attribute: .Left,
relatedBy: .Equal,
toItem: twoButton,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
let threeHeightConstraint = NSLayoutConstraint(
item: threeButton,
attribute: .Height,
relatedBy: .Equal,
toItem: sixButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let threeWidthConstraint = NSLayoutConstraint(
item: threeButton,
attribute: .Width,
relatedBy: .Equal,
toItem: plusButton,
attribute: .Width,
multiplier: 1.0,
constant: 0
)
view.addConstraints([threeHeightConstraint, threeLeftConstraint, threeTopConstraint, threeWidthConstraint])
// plusButton Constraints
let plusTopConstraint = NSLayoutConstraint(
item: plusButton,
attribute: .Top,
relatedBy: .Equal,
toItem: oneButton,
attribute: .Top,
multiplier: 1.0,
constant: spacingConstant
)
let plusLeftConstraint = NSLayoutConstraint(
item: plusButton,
attribute: .Left,
relatedBy: .Equal,
toItem: threeButton,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
let plusHeightConstraint = NSLayoutConstraint(
item: plusButton,
attribute: .Height,
relatedBy: .Equal,
toItem: minusButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let plusWidthConstraint = NSLayoutConstraint(
item: plusButton,
attribute: .Width,
relatedBy: .Equal,
toItem: threeButton,
attribute: .Width,
multiplier: 1.0,
constant: 0
)
let plusRightConstraint = NSLayoutConstraint(
item: plusButton,
attribute: .Right,
relatedBy: .Equal,
toItem: view,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
view.addConstraints([plusHeightConstraint, plusLeftConstraint, plusRightConstraint, plusTopConstraint, plusWidthConstraint])
// zeroButton Constraints
let zeroTopConstraint = NSLayoutConstraint(
item: zeroButton,
attribute: .Top,
relatedBy: .Equal,
toItem: oneButton,
attribute: .Bottom,
multiplier: 1.0,
constant: spacingConstant
)
let zeroLeftConstraint = NSLayoutConstraint(
item: zeroButton,
attribute: .Left,
relatedBy: .Equal,
toItem: view,
attribute: .Left,
multiplier: 1.0,
constant: spacingConstant
)
let zeroHeightConstraint = NSLayoutConstraint(
item: zeroButton,
attribute: .Height,
relatedBy: .Equal,
toItem: oneButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let zeroWidthConstraint = NSLayoutConstraint(
item: zeroButton,
attribute: .Width,
relatedBy: .Equal,
toItem: decimalButton,
attribute: .Width,
multiplier: 2.0,
constant: 0
)
let zeroBottomConstraint = NSLayoutConstraint(
item: zeroButton,
attribute: .Bottom,
relatedBy: .Equal,
toItem: view,
attribute: .Bottom,
multiplier: 1.0,
constant: 0
)
view.addConstraints([zeroHeightConstraint, zeroLeftConstraint, zeroTopConstraint, zeroWidthConstraint, zeroBottomConstraint])
// placeholder Constraints --> fixes Constraint error caused by zero having a double width
let placeholderTopConstraint = NSLayoutConstraint(
item: placeholder,
attribute: .Top,
relatedBy: .Equal,
toItem: zeroButton,
attribute: .Top,
multiplier: 1.0,
constant: spacingConstant
)
let placeholderLeftConstraint = NSLayoutConstraint(
item: placeholder,
attribute: .Left,
relatedBy: .Equal,
toItem: zeroButton,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
let placeholderHeightConstraint = NSLayoutConstraint(
item: placeholder,
attribute: .Height,
relatedBy: .Equal,
toItem: twoButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let placeholderBottomConstraint = NSLayoutConstraint(
item: placeholder,
attribute: .Bottom,
relatedBy: .Equal,
toItem: view,
attribute: .Bottom,
multiplier: 1.0,
constant: 0
)
view.addConstraints([placeholderHeightConstraint, placeholderLeftConstraint, placeholderTopConstraint, placeholderBottomConstraint])
// decimalButton Constraints
let decimalTopConstraint = NSLayoutConstraint(
item: decimalButton,
attribute: .Top,
relatedBy: .Equal,
toItem: zeroButton,
attribute: .Top,
multiplier: 1.0,
constant: spacingConstant
)
let decimalLeftConstraint = NSLayoutConstraint(
item: decimalButton,
attribute: .Left,
relatedBy: .Equal,
toItem: zeroButton,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
let decimalHeightConstraint = NSLayoutConstraint(
item: decimalButton,
attribute: .Height,
relatedBy: .Equal,
toItem: threeButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let decimalWidthConstraint = NSLayoutConstraint(
item: decimalButton,
attribute: .Width,
relatedBy: .Equal,
toItem: equalButton,
attribute: .Width,
multiplier: 1.0,
constant: 0
)
let decimalBottomConstraint = NSLayoutConstraint(
item: decimalButton,
attribute: .Bottom,
relatedBy: .Equal,
toItem: view,
attribute: .Bottom,
multiplier: 1.0,
constant: 0
)
view.addConstraints([decimalBottomConstraint, decimalHeightConstraint, decimalLeftConstraint, decimalTopConstraint, decimalWidthConstraint])
// equalButton Constraints
let equalTopConstraint = NSLayoutConstraint(
item: equalButton,
attribute: .Top,
relatedBy: .Equal,
toItem: zeroButton,
attribute: .Top,
multiplier: 1.0,
constant: spacingConstant
)
let equalLeftConstraint = NSLayoutConstraint(
item: equalButton,
attribute: .Left,
relatedBy: .Equal,
toItem: decimalButton,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
let equalHeightConstraint = NSLayoutConstraint(
item: equalButton,
attribute: .Height,
relatedBy: .Equal,
toItem: plusButton,
attribute: .Height,
multiplier: 1.0,
constant: 0
)
let equalWidthConstraint = NSLayoutConstraint(
item: equalButton,
attribute: .Width,
relatedBy: .Equal,
toItem: decimalButton,
attribute: .Width,
multiplier: 1.0,
constant: 0
)
let equalRightConstraint = NSLayoutConstraint(
item: equalButton,
attribute: .Right,
relatedBy: .Equal,
toItem: view,
attribute: .Right,
multiplier: 1.0,
constant: spacingConstant
)
let equalBottomConstraint = NSLayoutConstraint(
item: equalButton,
attribute: .Bottom,
relatedBy: .Equal,
toItem: view,
attribute: .Bottom,
multiplier: 1.0,
constant: spacingConstant
)
view.addConstraints([equalBottomConstraint, equalHeightConstraint, equalLeftConstraint, equalRightConstraint, equalWidthConstraint, equalTopConstraint])
func doMakeGreyButtons() {
for button in greyButtonArray {
button.backgroundColor = UIColor(hexString: "#D9DADC")
button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
}
}
func doMakeOrangeButtons() {
for button in orangeButtonArray {
button.backgroundColor = UIColor(hexString: "#F68F12")
button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
}
}
// Call methods to create borders and color buttons correctly
setupBordersFontsAndButtonActions()
doMakeGreyButtons()
doMakeOrangeButtons()
}
// ---> Rename this function
func setupBordersFontsAndButtonActions() {
for v in view.subviews {
if (v is UIButton) {
let button = v as! UIButton
button.titleLabel!.font = UIFont(name: "HelveticaNeue-Thin", size: 40)
button.layer.borderColor = UIColor.blackColor().CGColor
button.layer.borderWidth = 0.5
button.addTarget(self, action: "doPressButton:", forControlEvents: UIControlEvents.TouchUpInside)
}
}
}
} |
//
// TasksTableViewController.swift
// Tasks
//
// Created by Ilgar Ilyasov on 11/25/18.
// Copyright © 2018 Lambda School. All rights reserved.
//
import UIKit
import CoreData
class TasksTableViewController: UITableViewController {
let cellIdentifier = "taskCell"
let addSegue = "addSegue"
let cellSegue = "cellSegue"
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.reloadData()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
let task = tasks[indexPath.row]
cell.textLabel?.text = task.name
return cell
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let task = tasks[indexPath.row]
let moc = CoreDataStack.shared.mainContext
moc.delete(task)
do {
try moc.save()
} catch {
moc.reset() //If save fails it doesn't delete
}
tableView.reloadData()
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == cellSegue {
let detailVC = segue.destination as! TaskDetailViewController
if let indexPath = tableView.indexPathForSelectedRow {
detailVC.task = tasks[indexPath.row]
}
}
}
// MARK: - Properties
var tasks: [Task] {
let fetchRequest: NSFetchRequest<Task> = Task.fetchRequest()
let moc = CoreDataStack.shared.mainContext
do {
return try moc.fetch(fetchRequest)
} catch {
NSLog("Error fetching tasks: \(error)")
return []
}
}
}
|
//
// movieCollectionViewCell.swift
// MovieSwiftCoroutine
//
// Created by Mac on 22.08.2020.
// Copyright © 2020 Mac. All rights reserved.
//
import Foundation
import SDWebImage
import UIKit
class movieCollectionViewCell: UICollectionViewCell {
private var mainView : UIView!
private var imageView : UIImageView!
private var movieNameLabel : UILabel!
override init(frame: CGRect) {
super.init(frame:frame)
self.backgroundColor = .clear
self.layer.shadowColor = UIColor.purple.cgColor
self.layer.shadowOpacity = 1
self.layer.shadowOffset = CGSize(width: 10, height: 10)
self.layer.shadowRadius = 30
self.setMainView()
self.setMovieImageView()
self.setTitleLabel()
}
private func setMainView(){
self.mainView = UIView()
self.mainView.backgroundColor = UIColor.red.withAlphaComponent(0.5)
self.mainView.layer.borderWidth = 1.0
self.mainView.layer.borderColor = UIColor.blue.cgColor
self.addSubview(self.mainView)
self.mainView.translatesAutoresizingMaskIntoConstraints = false
self.mainView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
self.mainView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
self.mainView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
self.mainView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
self.mainView.layer.masksToBounds = true
self.mainView.layer.cornerRadius = 16
}
private func setMovieImageView(){
self.imageView = UIImageView()
self.imageView.translatesAutoresizingMaskIntoConstraints = false
self.mainView.addSubview(self.imageView)
self.imageView.leftAnchor.constraint(equalTo: self.mainView.leftAnchor , constant: 24).isActive = true
self.imageView.centerYAnchor.constraint(equalTo: self.mainView.centerYAnchor).isActive = true
self.imageView.heightAnchor.constraint(equalTo: self.mainView.heightAnchor , multiplier: 0.5).isActive = true
self.imageView.widthAnchor.constraint(equalTo: self.mainView.heightAnchor , multiplier: 0.5).isActive = true
}
private func setTitleLabel(){
self.movieNameLabel = UILabel()
self.movieNameLabel.text = ""
self.movieNameLabel.textColor = .white
self.movieNameLabel.textAlignment = .left
self.movieNameLabel.numberOfLines = 0
self.movieNameLabel.font = UIFont(name: "Avenir", size: 15)
self.mainView.addSubview(self.movieNameLabel)
self.movieNameLabel.translatesAutoresizingMaskIntoConstraints = false
self.movieNameLabel.leftAnchor.constraint(equalTo: self.imageView.rightAnchor , constant: 10).isActive = true
self.movieNameLabel.centerYAnchor.constraint(equalTo: self.mainView.centerYAnchor).isActive = true
self.movieNameLabel.rightAnchor.constraint(equalTo: self.mainView.rightAnchor).isActive = true
self.movieNameLabel.heightAnchor.constraint(equalTo: self.mainView.heightAnchor).isActive = true
}
func setData(_ movieName :String? , imageURL :String?){
self.movieNameLabel.text = movieName
let image_url = "https://image.tmdb.org/t/p/w500/"
self.imageView.sd_setImage(with: URL(string: image_url + imageURL!), completed: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// TFLLine-Cell.swift
// Brunel
//
// Created by Aaron McTavish on 20/01/2016.
// Copyright © 2016 ustwo Fampany Ltd. All rights reserved.
//
import UIKit
extension TFLLine: SearchableTableItem {
func configureTableViewCell(_ cell: UITableViewCell) {
if let lineCell = cell as? LineDetailTableViewCell {
lineCell.statusSection.lineLabel.textLabel.text = name
lineCell.statusSection.lineLabel.backgroundColor = color
if color.isLight() {
lineCell.statusSection.lineLabel.textLabel.textColor = UIColor.black
} else {
lineCell.statusSection.lineLabel.textLabel.textColor = UIColor.white
}
var statusText = ""
var statusTextColor = UIColor.black
var statusBackgroundColor = UIColor.white
if !lineStatuses.isEmpty {
var statusTextResult = ""
var usedStatuses = [String]()
for lineStatus in lineStatuses where !usedStatuses.contains(lineStatus.severityDescription) {
if !statusTextResult.isEmpty {
statusTextResult += ", "
} else {
if lineStatus.severity != 10 {
statusTextColor = UIColor.white
statusBackgroundColor = UIColor.purple
}
}
statusTextResult += lineStatus.severityDescription
usedStatuses.append(lineStatus.severityDescription)
}
statusText = statusTextResult
}
lineCell.statusSection.statusLabel.textLabel.text = statusText
lineCell.statusSection.statusLabel.textLabel.textColor = statusTextColor
lineCell.statusSection.statusLabel.backgroundColor = statusBackgroundColor
lineCell.selectionStyle = .none
lineCell.accessibilityIdentifier = AccessibilityIdentifiers.Lines.LineDetailCellPrefix + "_\(name)"
} else {
cell.textLabel?.text = name
cell.contentView.backgroundColor = color
if color.isLight() {
cell.textLabel?.textColor = UIColor.black
} else {
cell.textLabel?.textColor = UIColor.white
}
cell.accessibilityIdentifier = AccessibilityIdentifiers.Lines.LineCellPrefix + "_\(name)"
}
}
func searchableStrings() -> [String] {
return [name, mode.description]
}
}
|
//
// File.swift
// RO-SHAM-BILL
//
// Created by Patrick Molvik on 5/1/18.
// Copyright © 2018 Patrick Molvik. All rights reserved.
//
import Foundation
|
//
// Level4.swift
// In Search of the Lost Puzzle
//
// Created by Dimitrie-Toma Furdui on 16/04/2020.
// Copyright © 2020 The Green Meerkats. All rights reserved.
//
import SpriteKit
class Level4: Level2 {
override var helpText: String? {
"Something tells me you have a button on the screen that didn't work (until now)"
}
override func didBegin(_ contact: SKPhysicsContact) {
super.didBegin(contact)
let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
switch contactMask {
case Mask.player.rawValue | Mask.wall.rawValue:
self.physicsWorld.gravity = CGVector(dx: 0, dy: -9.8 * (self.isGravityInversed ? -1 : 1))
default:
break
}
}
override func moveVertically(in direction: Direction) {
var newPosition = CGPoint.zero
newPosition.y += Constants.moveAmount * (direction == .bottom ? -1 : 1)
let moveAction = SKAction.move(by: newPosition.cgVector, duration: 0.1)
let repeatAction = SKAction.repeatForever(moveAction)
self.physicsWorld.gravity = .zero
self.player.run(repeatAction, withKey: direction.rawValue)
}
}
|
//
// GameSceneNode.swift
// Fix Colors
//
// Created by Nurassyl Nuridin on 4/11/17.
// Copyright © 2017 Nurassyl Nuridin. All rights reserved.
//
import SpriteKit
protocol GameSceneNodeDelegate {
func levelCompleted()
func replay()
func prepareLevel()
func pauseButtonPressed()
func endOfGame()
}
protocol AdsDelegate {
func showAds()
}
class GameSceneNode: SKNode, GridDelegate, HUDNodeDelegate, CompletionNodeDelegate {
var delegate: GameSceneNodeDelegate?
var adsDelegate: AdsDelegate?
let settings: Settings
var level: Level?
var grid: Grid?
var gameScenePaused: Bool = false
let hudNode: HUDNode
let completionNode: CompletionNode
var completionOn: Bool = false {
didSet {
if !completionOn {
completionNode.alpha = 0.0
}
}
}
var adIsPresenting: Bool = false
init(settings: Settings) {
self.settings = settings
self.completionNode = CompletionNode(settings: settings)
self.hudNode = HUDNode(settings: settings)
super.init()
hudNode.position = CGPoint(x: 0.0, y: MainSize.height * 0.44)
hudNode.zPosition = 40.0
hudNode.delegate = self
addChild(hudNode)
completionNode.delegate = self
completionNode.alpha = 0.0
completionNode.position = CGPoint(x: 0.0, y: 0.0)
completionNode.zPosition = 60.0
addChild(completionNode)
}
func setup() {
makeGrid()
}
internal func updateMovesLabel() {
hudNode.updateLabelTexts()
}
internal func completionLevel() {
addCompletionScene()
}
internal func disableHUD() {
hudNode.isUserInteractionEnabled = false
}
internal func enableHUD() {
hudNode.isUserInteractionEnabled = true
}
internal func pauseNodeTouched() {
self.gameScenePaused = true
self.delegate?.pauseButtonPressed()
}
internal func replayButtonTouched() {
if settings.sound && !completionOn {
GameAudio.shared.playGridSwishSound()
}
if completionOn {
completionNode.animate(scaleFactor: 0.0, alpha: 0.0, completion: {
})
}
self.grid!.run(Actions.removeGridAction(), completion: {
self.completionOn = false
self.delegate?.replay()
self.hudNode.updateLabelTexts()
self.hudNode.isUserInteractionEnabled = true
self.isUserInteractionEnabled = true
})
}
internal func touchesEnabled() {
isUserInteractionEnabled = false
}
internal func continueButtonTouched() {
completionOn = false
continueGame()
}
private func makeGrid() {
if grid != nil { return }
hudNode.updateLabelTexts()
let width = level!.getWidth()
let (columns, rows) = level!.getColumnsAndRows()
grid = Grid(settings: settings, level: level!, columns: columns, rows: rows, width: width)
grid!.delegate = self
let y = (MainSize.height / 2.0 - MainSize.height * 0.38) / 2.0
grid!.position = CGPoint(x: 0.0, y: -y)
grid!.addSpritesToScene()
addChild(grid!)
}
private func addCompletionScene() {
if settings.sound {
GameAudio.shared.playCompletionSound()
}
completionNode.alpha = 1.0
showAd(level: settings.level)
completionNode.animate(scaleFactor: 1.0, alpha: 1.0) {
self.completionOn = true
self.hudNode.isUserInteractionEnabled = true
}
}
private func showAd(level: Int) {
if level == 1 || level % 4 == 0 {
adsDelegate?.showAds()
}
}
private func continueGame() {
settings.nextLevel()
let action = Actions.fadeOutAction(duration: 0.2)
completionNode.run(action, completion: {
if self.settings.level == MaxLevel {
self.delegate?.endOfGame()
} else {
self.delegate?.prepareLevel()
self.delegate?.levelCompleted()
self.hudNode.updateLabelTexts()
self.hudNode.isUserInteractionEnabled = true
}
})
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if hasActions() { return }
guard let g = grid else { return }
if g.hasActions() { return }
g.touchesEnded(touches, with: event)
if !hudNode.isUserInteractionEnabled { return }
hudNode.touchesEnded(touches, with: event)
if completionOn {
completionNode.touchesEnded(touches, with: event)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// NotificationTableViewCell.swift
// PushNotificationApplication
//
// Created by Александр Арсенюк on 23/03/2019.
// Copyright © 2019 Александр Арсенюк. All rights reserved.
//
import UIKit
class NotificationTableViewCell: UITableViewCell {
@IBOutlet weak var avatarImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
func configureCell(notification: NotificationObject) {
avatarImage.image = UIImage(data: notification.image)
nameLabel.text = notification.name
descriptionLabel.text = notification.descriprion
}
}
|
//
// WorlkHeadView.swift
// huicheng
//
// Created by lvxin on 2018/8/11.
// Copyright © 2018年 lvxin. All rights reserved.
//
import UIKit
class WorlkHeadView: UICollectionReusableView {
var nameLable : UILabel!
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
override init(frame: CGRect) {
super.init(frame: frame)
self.setUpUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setUpUI() {
let lineView = UIView(frame: CGRect(x: ip6(15), y: ip6(23), width: ip6(3), height: ip6(10)))
lineView.backgroundColor = UIColor.hc_colorFromRGB(rgbValue: 0xFF6900)
self.addSubview(lineView)
nameLable = UILabel(frame: CGRect(x: ip6(25), y: ip6(18), width: ip6(100), height: ip6(20)))
nameLable.font = hc_fzFontMedium(16)
nameLable.textColor = darkblueColor
nameLable.textAlignment = .left
self.addSubview(nameLable)
}
func creatUI(name : String,sectionNum : Int) {
HCLog(message: name)
nameLable.text = name
}
}
|
//
// TaskListViewController.swift
// DoIt
//
// Created by Michael Hartenburg on 3/28/17.
// Copyright © 2017 Michael Hartenburg. All rights reserved.
//
import UIKit
class TaskListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var tasks:[Task] = []
@IBOutlet weak var taskListTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tasks = makeTask()
self.taskListTable.dataSource = self
self.taskListTable.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Tables
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
let task = tasks[indexPath.row]
if task.important {
cell.textLabel?.text = " ❗️\(task.name)"
} else {
cell.textLabel?.text = task.name
}
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.
}
*/
func makeTask() -> [Task] {
let task1 = Task()
task1.name = "Walk the dog"
task1.important = false
let task2 = Task()
task2.name = "Buy cheese"
task2.important = true
let task3 = Task()
task3.name = "Mow the lawn"
task3.important = false
return [task1, task2, task3]
}
@IBAction func addTaskTapped(_ sender: Any) {
performSegue(withIdentifier: "addTaskSegue", sender: nil)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let nextVC = segue.destination as! AddTaskViewController
nextVC.previousVC = self
}
}
|
//
// ProfileController.swift
// testloginfb
//
// Created by Juan Lopez on 4/03/18.
// Copyright © 2018 Juan Lopez. All rights reserved.
//
import UIKit
class ProfileController: UITableViewController {
let colorPrimary = UIColor(r: 204, g: 153, b: 102, a: 1)
let colorBlack = UIColor(r: 32, g: 32, b: 32, a: 1)
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Perfil"
self.navigationController?.navigationBar.tintColor = colorPrimary
self.navigationController?.navigationBar.barTintColor = UIColor.black
self.navigationController?.navigationBar.titleTextAttributes =
[NSAttributedStringKey.foregroundColor: colorPrimary]
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
}
|
//
// MapDisplayViewController.swift
// PlaceMap
//
// Created by shunsukeshimada on 2015/11/14.
// Copyright © 2015年 shunsukeshimada. All rights reserved.
//
import UIKit
import MapKit
class MapDisplayViewController: UIViewController {
var selectedIndex : Int = 0
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var placeName: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
if(UIDevice.currentDevice().userInterfaceIdiom == .Pad){
let svc = self.splitViewController
let navItem = self.navigationItem
navItem.leftBarButtonItem = svc?.displayModeButtonItem()
}
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
print("Selected = \(selectedIndex)")
// \は、円記号ではなく、バックスラッシュです。option+¥ で入力できます。
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let places = appDelegate.placeDB.places
let prefName = places[selectedIndex]["pref"] as! String
let capName = places[selectedIndex]["name"] as! String
print("info = \(prefName)\(capName)")
self.placeName.text = "\(prefName)[\(capName)]"
let coordinate = CLLocationCoordinate2D(
latitude: places[selectedIndex]["latitude"] as! CLLocationDegrees,
longitude: places[selectedIndex]["longitude"] as! CLLocationDegrees
)
// self.mapView.centerCoordinate = coordinate
let span = MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005)
let region = MKCoordinateRegion(center: coordinate, span: span)
self.mapView.region = region
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// 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.
}
*/
}
|
//
// CategoryListInteractor.swift
// CategoryListInteractor
//
// Created by Harry Yan on 18/08/21.
//
import Foundation
final class CategoryListInteractor {
let dataProvider: DataProvider
init (dataProvider: DataProvider) {
self.dataProvider = dataProvider
}
@discardableResult
func fetchCurrencyRate() async throws -> Double {
let rate = try await dataProvider.fetchCurrency(url: CurrencyResponse.url)
return rate
}
}
|
//
// RestaurantDetailsModels.swift
// AGLViperProject
//
// Created by Раис Аглиуллов on 09.10.2020.
// Copyright (c) 2020 ___ORGANIZATIONNAME___. 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 RestaurantDetailsModel {
struct DisplayedSection: Equatable {
enum SectionType: Equatable {
case details
}
let type: SectionType
struct DisplayedCell: Equatable {
enum CellType: Equatable {
case details(title: String, imageName: String, descriptionText: String, price: Int32, priceText: String, header: String?, footer: String?, count: Int32?)
}
let type: CellType
}
let cells: [DisplayedCell]
}
enum FetchRestaurantDetailsData {
struct Request {
}
struct Response {
let detailsData: HomeScreenData?
}
struct ViewModel {
let displayedSection: [DisplayedSection]
}
}
enum ChangeControllerMode {
struct Request {
}
struct Response {
let mode: ControllerMode
}
struct ViewModel {
let mode: ControllerMode
}
}
enum SetBasketData {
struct Request {
let title: String
let imageName: String
let details: String
let price: Int32
let priceText: String
let count: Int32
}
struct Response {
let detailsData: BasketData
}
struct ViewModel {
let detailsData: BasketData
}
}
}
|
//
// Copyright © 2021 Tasuku Tozawa. All rights reserved.
//
typealias ClipPreviewPageViewCacheDependency = HasClipInformationViewCaching
enum ClipPreviewPageViewCacheReducer: Reducer {
typealias Dependency = ClipPreviewPageViewCacheDependency
typealias Action = ClipPreviewPageViewCacheAction
typealias State = ClipPreviewPageViewCacheState
static func execute(action: Action, state: State, dependency: Dependency) -> (State, [Effect<Action>]?) {
switch action {
// MARK: View Life-Cycle
case .viewWillDisappear:
dependency.informationViewCache?.stopUpdating()
return (state, .none)
case .viewDidAppear:
dependency.informationViewCache?.insertCachingViewHierarchyIfNeeded()
guard let itemId = state.itemId else { return (state, .none) }
dependency.informationViewCache?.startUpdating(clipId: state.clipId,
itemId: itemId)
return (state, .none)
// MARK: Transition
case let .pageChanged(clipId, itemId):
dependency.informationViewCache?.startUpdating(clipId: clipId, itemId: itemId)
var nextState = state
nextState.clipId = clipId
nextState.itemId = itemId
return (nextState, .none)
}
}
}
|
//
// UserLoginViewController.swift
// WrapItUpPayments
//
// Created by Derik Gagnon on 3/29/19.
// Copyright © 2019 Derik Gagnon. All rights reserved.
//
import UIKit
import FirebaseAuthUI
import SDWebImage
import FirebaseEmailAuthUI
import FirebaseGoogleAuthUI
import Firebase
class UserLoginViewController: UIViewController, FUIAuthDelegate {
fileprivate(set) var auth:Auth?
fileprivate(set) var authUI: FUIAuth? //only set internally but get externally
fileprivate(set) var authStateListenerHandle: AuthStateDidChangeListenerHandle?
func authUI(_ authUI: FUIAuth, didSignInWith user: User?, error: Error?) {
// jump out once we have a valid user
guard let authError = error else {
print("Login Successful")
return
}
let errorCode = UInt((authError as NSError).code)
// if user cancels login, error here
switch errorCode {
case FUIAuthErrorCode.userCancelledSignIn.rawValue:
print("User cancelled sign-in");
break
// error if not logged in
default:
let detailedError = (authError as NSError).userInfo[NSUnderlyingErrorKey] ?? authError
print("Login error: \((detailedError as! NSError).localizedDescription)");
}
}
override func viewDidLoad() {
super.viewDidLoad()
SDImageCache.shared.clearMemory()
SDImageCache.shared.clearDisk()
// Force a signout so that a different user could potentially sign back in
// Useful if the users have different accounts for different time menus.
try! Auth.auth().signOut()
// Setting up authentication listener
self.auth = Auth.auth()
self.authUI = FUIAuth.defaultAuthUI()
self.authUI?.delegate = self
var authProviders: [FUIAuthProvider] = []
if let authUI = self.authUI {
let googleAuthProvider = FUIGoogleAuth(authUI: authUI)
authProviders = [googleAuthProvider, FUIEmailAuth()]
}
self.authUI?.providers = authProviders
self.authStateListenerHandle = self.auth?.addStateDidChangeListener { (auth, user) in
// Jumps out when the state changes to valid user
guard user != nil else {
return
}
}
}
override func viewDidAppear(_ animated: Bool) {
// Once we have valid user, go to next view
if Auth.auth().currentUser != nil {
self.performSegue(withIdentifier: "LoginSegue", sender: self)
}
}
@IBAction func loginAction(sender: AnyObject) {
// Present the default login view controller provided by authUI
if let authViewController = authUI?.authViewController() {
authViewController.modalPresentationStyle = .fullScreen
self.present(authViewController, animated: true, completion: nil)
}
}
}
|
import Foundation
import Commander
import PathKit
import xcproj
import xclintrules
import Rainbow
let lintCommand = command(Argument<String>("project", description: "Path to the .xcodeproj to be linted")) { (project: String) in
let path = Path(project)
if path.extension != "xcodeproj" {
let message = "Invalid file. It must be a .xcodeproj file".red
print(message)
throw CommandError(description: message)
}
let project = try XcodeProj(path: path)
let lintErrors = project.lint()
if lintErrors.isEmpty {
print("Linting succeeded".green)
return
}
log(errors: lintErrors)
throw CommandError(description: "Linting failed")
}
lintCommand.run()
|
//
// PromotionListController.swift
// PlateiOS
//
// Created by Renner Leite Lucena on 10/20/17.
// Copyright © 2017 Renner Leite Lucena. All rights reserved.
//
import Foundation
import UIKit
final class PromotionListController {
let promotionListService = PromotionListService()
var promotionList = PromotionListModel()
let username: String
unowned let promotionListProtocol: PromotionListProtocol
init(username: String, promotionListProtocol: PromotionListProtocol) {
self.username = username
self.promotionListProtocol = promotionListProtocol
}
}
extension PromotionListController {
func initializePromotionList(username: String) {
promotionListProtocol.showLoading()
promotionListService.readPromotionsToGo(username: username, completionReadPromotionsToGo: { [weak self] success, toGoPromotions in
self?.handleReadPromotionsToGo(success: success, toGoPromotions: toGoPromotions, username: username)
})
promotionListProtocol.hideLoading()
}
func respondToCellButtonClickOnController(promotionModel: PromotionModel, firstClick: Bool) {
if(firstClick) {
promotionListService.createRequest(username: username, promotion_id: promotionModel.promotion_id, request_code: "0", completionCreateRequest: { [weak self] success in
self?.handleCreateRequestGoing(success: success, promotionModel: promotionModel)
})
}else {
let noFoodDialogViewController = UIStoryboard.init(name: "NoFoodDialog", bundle: nil).instantiateViewController(withIdentifier: "NoFoodDialog") as! NoFoodDialogViewController
noFoodDialogViewController.promotionModel = promotionModel
noFoodDialogViewController.positiveFunction = { [weak self] in
self?.promotionListService.createRequest(username: (self?.username)!, promotion_id: promotionModel.promotion_id, request_code: "1", completionCreateRequest: { [weak self] success in
self?.handleCreateRequestNoFoodLeft(success: success, promotionModel: promotionModel)
})}
promotionListProtocol.presentViewController(controller: noFoodDialogViewController)
}
}
func respondToPlusButtonClick() {
let addPromotionDialogViewController = UIStoryboard.init(name: "AddPromotionDialog", bundle: nil).instantiateViewController(withIdentifier: "AddPromotionDialog") as! AddPromotionDialogViewController
addPromotionDialogViewController.positiveFunction = { [weak self] promotionModel in
self?.promotionListService.createPromotion(title: promotionModel.title, start_time: promotionModel.start_time, end_time: promotionModel.end_time, location: promotionModel.location, completionCreatePromotion: { [weak self] success, promotionModel in
self?.handleCreatePromotion(success: success, promotionModel: promotionModel)
})}
addPromotionDialogViewController.errorFunction = { [weak self] in
self?.delayWithSeconds(0.25) {
self?.promotionListProtocol.showErrorMessage(title: "Error", message: "Something went wrong. Please, check your internet connection, inputs and try again.")
}
}
promotionListProtocol.presentViewController(controller: addPromotionDialogViewController)
}
fileprivate func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
completion()
}
}
}
extension PromotionListController {
func handleReadPromotionsToGo(success: Bool, toGoPromotions: [PromotionModel]?, username: String) {
if(success) {
for model in toGoPromotions ?? [] {
promotionList.promotions.append(model)
promotionList.promotionsStatus[model] = true
}
promotionListService.readPromotionsGoing(username: username, completionReadPromotionsGoing: { [weak self] success, goingPromotions in
self?.handleReadPromotionsGoing(success: success, goingPromotions: goingPromotions)
})
}else {
promotionListProtocol.showErrorMessage(title: "Error", message: "Something went wrong. Please, try again.")
}
}
func handleReadPromotionsGoing(success: Bool, goingPromotions: [PromotionModel]?) {
if(success) {
for model in goingPromotions ?? [] { // change this later maybe
promotionList.promotions.append(model)
promotionList.promotionsStatus[model] = false
}
promotionListProtocol.loadTable()
}else {
promotionListProtocol.showErrorMessage(title: "Error", message: "Something went wrong. Please, try again.")
}
}
func handleCreateRequestGoing(success: Bool, promotionModel: PromotionModel) {
if(success) {
promotionList.promotionsStatus[promotionModel] = false
promotionListProtocol.reloadTable()
}else {
promotionListProtocol.showErrorMessage(title: "Error", message: "Sorry. This action in unavailable (event has no more food or is over).")
}
}
func handleCreateRequestNoFoodLeft(success: Bool, promotionModel: PromotionModel) {
if(success) {
promotionList.removePromotion(promotionModel: promotionModel)
promotionListProtocol.reloadTable()
}else {
promotionListProtocol.showErrorMessage(title: "Error", message: "Sorry. This action in unavailable (event has no more food or is over).")
}
}
func handleCreatePromotion(success: Bool, promotionModel: PromotionModel?) {
if(success && promotionModel != nil) {
promotionList.addPromotion(promotionModel: promotionModel!)
promotionListProtocol.reloadTable()
}else {
promotionListProtocol.showErrorMessage(title: "Error", message: "Something went wrong. Please, check your internet connection, inputs and try again.")
}
}
}
|
//
// JSONEncodable.swift
// Ready4sApplication
//
// Created by Maciej Hełmecki on 15.06.2017.
// Copyright © 2017 Maciej Hełmecki. All rights reserved.
//
import Foundation
protocol JSONDecodable {
init?(json: [[String: Any]])
}
|
//
// DNSPacket.swift
// ShadowVPN
//
// Created by code8 on 16/11/28.
// Copyright © 2016年 code8. All rights reserved.
//
import Foundation
class DNSPacket : NSObject{
var identifier : UInt16 = 0
var queryDomains : NSArray? = nil
var rawData : NSData? = nil
var hexString : String = ""
init?(data : NSData){
super.init()
if data.length < 12 {
NSLog("packet too short")
}
rawData = data
let scanner : BinaryDataScanner = BinaryDataScanner(data: data, littleEndian: false)
//前两个自己为标识符
self.hexString = data.toHex()!
identifier = scanner.read16()!
scanner.skipTo(n: 4)
let count = scanner.read16()
let domains = NSMutableArray()
scanner.skipTo(n: 12)
//取出所有的DNS里的地址
for _ in 0..<Int(count!) {
let domain : NSMutableString = NSMutableString()
var domainLength = 0
var b = scanner.readByte()
while b != UInt8(0) {
//单个域名的长度
let len = Int(b!)
if scanner.remain == 0 {
return nil
}
//读取
let sdomain = scanner.readString(len: len)
domain.append(sdomain!)
//中间以.作为分割
domain.append(".")
//domainLength++
domainLength += len
//循环读取
b = scanner.readByte()
//domainLength++
domainLength += 1
}
//跳3个字节
scanner.advanceBy(n: 3)
if scanner.remain <= 0 {
return nil
}
//删除最后一个点
domain.deleteCharacters(in: NSMakeRange(domain.length-1, 1))
domains.add(domain)
}
queryDomains = domains
rawData = data
print("hello")
}
}
|
//
// ReservationListViewController.swift
// MagotakuApp
//
// Created by 宮本一成 on 2020/03/05.
// Copyright © 2020 ISSEY MIYAMOTO. All rights reserved.
//
//Reservationタブ左側「予約一覧」用のUIViewController
import UIKit
import FirebaseFirestore
import FirebaseUI
class ReservationListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// この ViewController で delegate のメソッドを使うために記述している。
tableView.delegate = self
// この ViewController で datasouce のメソッドを使うために記述している。
tableView.dataSource = self
// nib と xib はほぼ一緒
let nib = UINib(nibName: "ReservationCell", bundle: nil)
// tableView に使う xib ファイルを登録している。
tableView.register( nib, forCellReuseIdentifier: "ReservationCell")
ReservationCollection.shared.delegate = self as? ReservationCollectionDelegate
print(ReservationCollection.shared.reservationCount())
tableView.backgroundColor = UIColor(red: 225/255, green: 225/255, blue: 225/255, alpha: 1)
// if ReservationCollection.shared.reservationCount() == 0{
// //予約0件の場合のみ表示する
// setZeroReservation()
// }
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
//予約0件の時のみ表示するメソッド
func setZeroReservation(){
let view = UIView(frame: self.view.bounds)
view.backgroundColor = UIColor(red: 225/255, green: 225/255, blue: 225/255, alpha: 1)
self.view.addSubview(view)
//「確定している予約 0件」表示用のラベル
let zeroLable = UILabel()
zeroLable.text = "確定している予約 0件"
zeroLable.font = UIFont.boldSystemFont(ofSize: 16)
zeroLable.frame = CGRect(x: 24, y: 24, width: UIScreen.main.bounds.width - 16, height: 22)
view.addSubview(zeroLable)
//予約を促す ラベル
let stimulatorLabel = UILabel()
stimulatorLabel.text = "次の予約を行いましょう"
stimulatorLabel.font = UIFont.systemFont(ofSize: 14)
stimulatorLabel.frame = CGRect(x: 24, y: 54, width: UIScreen.main.bounds.width - 16, height: 22)
view.addSubview(stimulatorLabel)
//予約を行うためのボタン
let reservationBtn = UIButton(type: .system)
reservationBtn.setTitle("新規予約を行う", for: .normal)
reservationBtn.setTitleColor(.white, for: .normal)
reservationBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
reservationBtn.titleLabel?.textAlignment = .center
reservationBtn.backgroundColor = UIColor(red: 94/255, green: 123/255, blue: 211/255, alpha: 1)
reservationBtn.frame = CGRect(x: 24, y: 88, width: 240, height: 48)
reservationBtn.layer.cornerRadius = 6.0
view.addSubview(reservationBtn)
}
//1セクション内のrowの数を決める
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ReservationCollection.shared.reservationCount()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 登録したセルを使う。 as! CustomCell としないと、UITableViewCell のままでしか使えない。
let cell = tableView.dequeueReusableCell(withIdentifier: "ReservationCell", for: indexPath) as! ReservationCell
//日付用のUILabelに代入
cell.dateLabel.text = "\(ReservationCollection.shared.getReservation(at: indexPath.row).visitDate) \(ReservationCollection.shared.getReservation(at: indexPath.row).visitTime)"
//もし承認判定用の番号が1になっていたらテキストカラーと文言を変更
if ReservationCollection.shared.getReservation(at: indexPath.row).reservationNum == 1{
cell.decideLabel.text = " 承認済み "
cell.decideLabel.textColor = .red
cell.decideLabel.layer.borderColor = UIColor.red.cgColor
if let imageName: String = ReservationCollection.shared.getReservation(at: indexPath.row).studentImage,
let ref = ReservationCollection.shared.getImageRef(uid: ReservationCollection.shared.getReservation(at: indexPath.row).stUid, imageName: imageName){
cell.partnerImage.sd_setImage(with: ref)
}else{
cell.partnerImage.image = UIImage(systemName: "person.fill")
}
}else{
//承認されていない場合、imageViewにひとまずログインユーザーの顔写真を挿入する
if let imageName: String = seniorProfile.imageName, let ref = SeniorUserCollection.shared.getImageRef(imageName: imageName){
cell.partnerImage.sd_setImage(with: ref)
}
cell.partnerLabel.text = "パートナー:未定"
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 96
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 1
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if ReservationCollection.shared.getReservation(at: indexPath.row).reservationNum == 1{
let vc = ReservationDetailViewController()
let backButtonItem = UIBarButtonItem(title: "戻る", style: .plain, target: nil, action: nil)
navigationItem.backBarButtonItem = backButtonItem
navigationController?.pushViewController(vc, animated: true)
}else{
notDoneAlert(text: "まだパートナーが未定です。お決まりまでお待ちください")
}
}
}
// extension で分けた方が見やすくなる
extension ReservationListViewController: ReservationCollectionDelegate {
// デリゲートのメソッド
func saved() {
// tableView をリロードして、画面を更新する。
tableView.reloadData()
}
func loaded() {
tableView.reloadData()
}
}
|
import Fluent
import Vapor
import Leaf
// MongoDB
import MongoKitten
import JWTKit
func routes(_ app: Application) throws {
// MARK: - TIL.
let acronymsController = AcronymsController()
try app.register(collection: acronymsController)
let usersController = UsersController()
try app.register(collection: usersController)
let categoriesController = CategoriesController()
try app.register(collection: categoriesController)
let websiteController = WebsiteController()
try app.register(collection: websiteController)
try app.register(collection: TodoController())
// MARK: - Configure.
// Increases the streaming body collection limit to 500kb
app.routes.defaultMaxBodySize = "500kb"
// app.routes.caseInsensitive = true // Distinguish between lower case and upper case - default is `false`
// Collects streaming bodies (up to 1mb in size) before calling this route.
// app.on(.POST, "listings", body: .collect(maxSize: "1mb")) { req in
// // Handle request.
// }
// MARK: - Custom Encoder, Decoder.
// Calls to encoding and decoding methods like req.content.decode support passing in custom coders for one-off usages.
// create a new JSON decoder that uses unix-timestamp dates
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
// decodes Hello struct using custom decoder
// let hello = try req.content.decode(Hello.self, using: decoder) // using
// MARK: - Basic sample.
// Route with description (Metadata)
// app.get { req in
// return req.view.render("index", ["title": "Hello Vapor!"])
// }.description("says hello")
app.get("hello") { req -> String in
return "Hello, world!"
}
// Method 1.
// app.get("hello", "vapor") { req in
// return "Hello, vapor!"
// }
// Method 2.
app.on(.GET, "hello", "vapor") { req in
return "Hello, vapor!"
}
// responds to GET /hello/foo
// responds to GET /hello/bar
// ...
app.get("hello", ":name") { req -> String in
let name = req.parameters.get("name")!
return "Hello, \(name)!"
}
// responds to GET /foo/bar/baz
// responds to GET /foo/qux/baz
// ...
app.get("foo", "*", "baz") { req in
return ""
}
// responds to GET /foo/bar
// responds to GET /foo/bar/baz
// ...
app.get("foo", "**") { req in
return ""
}
app.get("foo") { req -> String in
return "bar"
}
// responds to GET /number/42
// responds to GET /number/1337
// ...
app.get("number", ":x") { req -> String in
guard let int = req.parameters.get("x", as: Int.self) else {
throw Abort(.badRequest)
}
return "\(int) is a great number"
}
// responds to GET /hello/foo
// responds to GET /hello/foo/bar
// ...
app.get("hello", "**") { req -> String in
let name = req.parameters.getCatchall().joined(separator: " ")
return "Hello, \(name)!"
}
// MARK: - Route Groups.
// Method 1
// let users = app.grouped("users")
// // GET /users
// users.get { req in
// ...
// }
// // POST /users
// users.post { req in
// ...
// }
// // GET /users/:id
// users.get(":id") { req in
// let id = req.parameters.get("id")!
// ...
// }
// Method 2
// app.group("users") { users in
// // GET /users
// users.get { req in
// ...
// }
// // POST /users
// users.post { req in
// ...
// }
// // GET /users/:id
// users.get(":id") { req in
// let id = req.parameters.get("id")!
// ...
// }
// }
// Method 3: Nesting path prefixing route groups.
// app.group("users") { users in
// // GET /users
// users.get { ... }
// // POST /users
// users.post { ... }
//
// users.group(":id") { user in
// // GET /users/:id
// user.get { ... }
// // PATCH /users/:id
// user.patch { ... }
// // PUT /users/:id
// user.put { ... }
// }
// }
// Method 4: Middleware.
// app.get("fast-thing") { req in
// ...
// }
// app.group(RateLimitMiddleware(requestsPerMinute: 5)) { rateLimited in
// rateLimited.get("slow-thing") { req in
// ...
// }
// }
// MARK: - Redirections.
// req.redirect(to: "/some/new/path")
// Specify the type of redirect, for example to redirect a page permanently (so that your SEO is updated correctly).
// req.redirect(to: "/some/new/path", type: .permanent)
// MARK: - Decoding URL query string
// /hello?name=Vapor
app.get("hello") { req -> String in
let hello = try req.query.decode(Hello.self)
// let name: String? = req.query["name"]
return "Hello, \(hello.name ?? "Anonymous")"
}
struct Hello: Content {
var name: String?
// MARK: - Hook.
// Vapor will automatically call beforeDecode and afterDecode on a Content type. Default implementations are provided which do nothing, but you can use these methods to run custom logic.
// Runs after this Content is decoded. `mutating` is only required for structs, not classes.
mutating func afterDecode() throws {
// Name may not be passed in, but if it is, then it can't be an empty string.
self.name = self.name?.trimmingCharacters(in: .whitespacesAndNewlines)
if let name = self.name, name.isEmpty {
throw Abort(.badRequest, reason: "Name must not be empty.")
}
}
// Runs before this Content is encoded. `mutating` is only required for structs, not classes.
mutating func beforeEncode() throws {
// Have to *always* pass a name back, and it can't be an empty string.
guard
let name = self.name?.trimmingCharacters(in: .whitespacesAndNewlines),
!name.isEmpty
else {
throw Abort(.badRequest, reason: "Name must not be empty.")
}
self.name = name
}
}
app.get("testhtml") { _ in
HTML(value: """
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
""")
}
}
// MARK: - Custom ResponseEncodable.
struct HTML {
let value: String
}
extension HTML: ResponseEncodable {
public func encodeResponse(for request: Request) -> EventLoopFuture<Response> {
var headers = HTTPHeaders()
headers.add(name: .contentType, value: "text/html")
return request.eventLoop.makeSucceededFuture(.init(
status: .ok, headers: headers, body: .init(string: value)
))
}
}
/* You can then use HTML as a response type in your routes:
app.get { _ in
HTML(value: """
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
""")
}
*/
|
//
// MyDayViewController.swift
// Lose It!
//
// Created by Abeer Nasir on 07/09/2021.
//
import Foundation
import UIKit
let notificationKey = "com.Abeer.notificationKey"
class MyDayViewController: UIViewController{
var caloriesVal: String?
var remainingVal : Int = 0
var totalCal : Int = 0
var myDayCals : Int = 0
@IBOutlet weak var inputTextField: UITextField!
@IBOutlet weak var remainingLabel: UILabel!
var datePicker: UIDatePicker?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
remainingLabel.text = caloriesVal
let datePicker = UIDatePicker()
datePicker .datePickerMode = .date
datePicker.addTarget(self, action: #selector(dateChanged(datePicker:)), for:UIControl.Event.valueChanged)
datePicker.frame.size = CGSize(width: 0, height: 300)
datePicker.preferredDatePickerStyle = .wheels
inputTextField.inputView = datePicker
inputTextField.text = formatDate(date: Date())
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(MyDayViewController.viewTapped(gestureRecognizer:)))
view.addGestureRecognizer(tapGesture)
NotificationCenter.default.addObserver(self, selector: #selector(doWhenNotify(_:)), name: Notification.Name(rawValue: notificationKey), object: nil)
}
@objc func viewTapped(gestureRecognizer: UITapGestureRecognizer){
view.endEditing(true)
}
@objc func dateChanged(datePicker: UIDatePicker){
inputTextField.text = formatDate(date: datePicker.date)
}
func formatDate(date: Date)-> String{
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yyyy"
return formatter.string(from: date)
}
@objc func doWhenNotify(_ notification: NSNotification){
if let dict = notification.userInfo as NSDictionary? {
if let total = dict["total"] as? String{
remainingVal = Int(caloriesVal!)!
myDayCals = remainingVal - Int(total)!
remainingLabel.text = String(myDayCals)
}
}
}
}
|
//
// HeadUpDisplayable.swift
// HeadUpDisplayer
//
// Created by dumbass.cn on 9/26/19.
// Copyright © 2019 dumbass.cn. All rights reserved.
//
import UIKit
public protocol HeadUpDisplayerContainer {
var hudContainer: UIView { get }
}
public enum Style {
public enum State { case success, failure, info, error }
case text(State, String)
case progress
case progressWithTitle(String)
}
public protocol HeadUpDisplayable {
typealias Container = HeadUpDisplayerContainer
var container: Container { get }
func show(style: Style)
}
public extension HeadUpDisplayable {
func show(style: Style) {
Displayer.instance.show(style: style, in: container.hudContainer)
}
func show(success text: String) {
show(style: .text(.success, text))
}
func show(failure text: String) {
show(style: .text(.failure, text))
}
}
extension UIView: HeadUpDisplayerContainer {
public var hudContainer: UIView { self }
}
extension UIViewController: HeadUpDisplayerContainer {
public var hudContainer: UIView { view }
}
extension HeadUpDisplayerWrapper: HeadUpDisplayable where Base: HeadUpDisplayerContainer {
public var container: Container { base }
}
|
//
// ReadJson.swift
// Roboty
//
// Created by Julia Debecka on 11/05/2020.
// Copyright © 2020 Julia Debecka. All rights reserved.
//
import Foundation
struct RobotsMovieRepository {
static func getMovieResources(_ completion: @escaping ((Characters) -> Void)) {
DispatchQueue.global(qos: .userInitiated).async {
if let path = Bundle.main.path(forResource: "Robots", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let decoder = JSONDecoder()
let robots: Characters = try decoder.decode(Characters.self, from: data)
DispatchQueue.main.async {
completion(robots)
}
}catch {
DispatchQueue.main.async {
completion([])
}
}
}
}
}
}
|
//
// ContactCell.swift
// Contacts
//
// Created by Svetlio on 9.04.21.
//
import UIKit
class ContactCell: UITableViewCell {
@IBOutlet var name: UILabel!
}
|
//
// SurveyDetailTVCTestCases.swift
// Nimble Survey AppTests
//
// Created by PRAKASH on 7/28/19.
// Copyright © 2019 Prakash. All rights reserved.
//
import XCTest
@testable import Nimble_Survey_App
class SurveyDetailTVCTestCases: XCTestCase {
var surveyListVC = SurveyListVC()
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
self.surveyListVC = (UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NavigationClass") as! UINavigationController).viewControllers[0] as! SurveyListVC
self.surveyListVC.navigationController?.loadViewIfNeeded()
self.surveyListVC.loadViewIfNeeded()
}
func test_numberOfSectionInSurveyDetailVC(){
let expectation = XCTestExpectation(description: "Fetching one survey data from server")
getSurveyDatas { (surveyModel) in
let detailVC = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SurveyDetailTVC") as! SurveyDetailTVC
detailVC.modelSurvey = surveyModel
self.surveyListVC.navigationController?.pushViewController(detailVC, animated: true)
XCTAssertEqual(detailVC.numberOfSections(in: detailVC.tableView), surveyModel.questions.count)
expectation.fulfill()
}
wait(for: [expectation], timeout: 21.0)
}
func test_numberOfRowsInSurveyDetailVC(){
let expectation = XCTestExpectation(description: "Fetching one survey data from server")
getSurveyDatas { (surveyModel) in
let detailVC = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SurveyDetailTVC") as! SurveyDetailTVC
detailVC.modelSurvey = surveyModel
self.surveyListVC.navigationController?.pushViewController(detailVC, animated: true)
let section = 0
XCTAssertEqual(detailVC.tableView(detailVC.tableView, numberOfRowsInSection: section), surveyModel.questions[section].answers.count)
expectation.fulfill()
}
wait(for: [expectation], timeout: 21.0)
}
func test_CellForRow_InSurveyDetailVC(){
let expectation = XCTestExpectation(description: "Fetching one survey data from server")
getSurveyDatas { (surveyModel) in
let detailVC = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SurveyDetailTVC") as! SurveyDetailTVC
detailVC.modelSurvey = surveyModel
self.surveyListVC.navigationController?.pushViewController(detailVC, animated: true)
let section = 0
let row = 0
let cell = detailVC.tableView(detailVC.tableView, cellForRowAt: IndexPath(row: row, section: section))
let question = surveyModel.questions[section]
var answerTitle = ""
if question.answers.count > 0{
answerTitle = question.answers[row].text ?? ""
}
XCTAssertEqual(cell.textLabel?.text, answerTitle)
expectation.fulfill()
}
wait(for: [expectation], timeout: 21.0)
}
func test_CellForRow_nonEmptyAnswer_InSurveyDetailVC(){
let expectation = XCTestExpectation(description: "Fetching one survey data from server")
getSurveyDatas { (surveyModel) in
let detailVC = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SurveyDetailTVC") as! SurveyDetailTVC
detailVC.modelSurvey = surveyModel
self.surveyListVC.navigationController?.pushViewController(detailVC, animated: true)
var section = 0
var question = surveyModel.questions[section]
var answerTitle = ""
while question.answers.count > 0{
section += 1
//to prevent crash in case no question contains the answe array
if surveyModel.questions.count == section{
section -= 1
// break
}
question = surveyModel.questions[section]
}
if question.answers.count > 0{
answerTitle = question.answers[section].text ?? ""
}
let cell = detailVC.tableView(detailVC.tableView, cellForRowAt: IndexPath(row: section, section: section))
XCTAssertEqual(cell.textLabel?.text, answerTitle)
expectation.fulfill()
}
wait(for: [expectation], timeout: 21.0)
}
func test_actionBack(){
let detailVC = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SurveyDetailTVC") as! SurveyDetailTVC
self.surveyListVC.navigationController?.pushViewController(detailVC, animated: true)
detailVC.loadViewIfNeeded()
detailVC.actionBack(detailVC.buttonBack)
XCTAssertFalse(self.surveyListVC.navigationController?.topViewController is SurveyDetailTVC)
}
func getSurveyDatas(completion:@escaping (_ modelData : SurveyListModel)->Void){
refreshAccessTokenIfNeeded {
APIClient.fetchSurveys{ (result) in
switch result {
case .success(let modelSurveyList):
completion(modelSurveyList[0])
break
case .failure(let error):
print(error.localizedDescription)
}
}
}
}
func refreshAccessTokenIfNeeded(completion:@escaping ()->Void){
if savedTokenDatas.accessToken != ""{
let date = Date(timeIntervalSince1970: savedTokenDatas.createdAt)
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
dateFormatter.timeZone = TimeZone(identifier: "en-US")
let localDate = dateFormatter.string(from: date)
let newDate = dateFormatter.date(from: localDate)?.addingTimeInterval(savedTokenDatas.expiresIn)
if Date() > dateFormatter.date(from: dateFormatter.string(from: newDate!))!{
refreshAccessToken(){
completion()
}
}else{
completion()
}
}else{
refreshAccessToken(){
completion()
}
}
}
func refreshAccessToken(completion:@escaping ()->Void){
APIClient.refreshAccessToken { (result) in
switch result {
case .success(let modelAccessToken):
savedTokenDatas = modelAccessToken
completion()
case .failure(let error):
print(error.localizedDescription)
}
}
}
func test_refreshTokenFunction(){
self.surveyListVC.refreshAccessToken()
//Assuming after 12 seconds it must fetch data from backend
wait(interval: 12) {
XCTAssertNotNil(savedTokenDatas.accessToken)
}
}
func test_didSelectRowAtIndexPath(){
let expectation = XCTestExpectation(description: "Fetching one survey data from server")
getSurveyDatas { (surveyModel) in
let detailVC = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SurveyDetailTVC") as! SurveyDetailTVC
detailVC.modelSurvey = surveyModel
self.surveyListVC.navigationController?.pushViewController(detailVC, animated: true)
let indexPath = IndexPath(row: 0, section: 0)
detailVC.tableView(detailVC.tableView, didSelectRowAt: indexPath)
XCTAssertNotEqual(detailVC.tableView.indexPathForSelectedRow, indexPath, "Added not equal to method because as soon as table view cell selected, code is deselcting the cell")
expectation.fulfill()
}
wait(for: [expectation], timeout: 21.0)
}
func test_titleForHeader(){
let expectation = XCTestExpectation(description: "Fetching one survey data from server")
getSurveyDatas { (surveyModel) in
let detailVC = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SurveyDetailTVC") as! SurveyDetailTVC
detailVC.modelSurvey = surveyModel
self.surveyListVC.navigationController?.pushViewController(detailVC, animated: true)
let section = 0
XCTAssertEqual(detailVC.tableView(detailVC.tableView, titleForHeaderInSection: section), surveyModel.questions[0].text)
expectation.fulfill()
}
wait(for: [expectation], timeout: 21.0)
}
func test_heightForHeader(){
let expectation = XCTestExpectation(description: "Fetching one survey data from server")
getSurveyDatas { (surveyModel) in
let detailVC = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SurveyDetailTVC") as! SurveyDetailTVC
detailVC.modelSurvey = surveyModel
self.surveyListVC.navigationController?.pushViewController(detailVC, animated: true)
let section = 0
XCTAssertEqual(detailVC.tableView(detailVC.tableView, heightForHeaderInSection: section), UITableView.automaticDimension)
expectation.fulfill()
}
wait(for: [expectation], timeout: 21.0)
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
|
//
// CountryListView.swift
// CovidUI
//
// Created by Daniel Plata on 15/04/2020.
// Copyright © 2020 silverapps. All rights reserved.
//
import SwiftUI
struct CountryListView: View {
@Environment(\.presentationMode) var presentationMode
@ObservedObject var viewModel: CountryListViewModel
@State var textInput: String = ""
@State private var showCancelButton: Bool = false
init(viewModel: CountryListViewModel){
self.viewModel = viewModel
UITableView.appearance().tableFooterView = UIView()
UITableView.appearance().separatorStyle = .none
}
var body: some View {
VStack {
SearchBar(text: $textInput)
List(viewModel.countries.filter {
self.textInput.isEmpty ? true: $0.name.lowercased().contains(self.textInput.lowercased())
}, id: \.id) { country in
CountryListRow(country: country)
}
}.navigationBarBackButtonHidden(true)
.navigationBarItems(leading:
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
BackButton(color: .black)
})
.navigationBarTitle("Select a country", displayMode: .inline)
.navigationBarColor(.white)
}
}
struct CountryListRow: View {
@State var country: Country
var body: some View {
ZStack {
CountryCardView(countryName: country.name, flagImage: country.flagImage)
.padding(.bottom, 10)
NavigationLink(destination: LazyView { CountryChartView(country: self.country) }) {
EmptyView()
}.frame(width: 0)
.opacity(0)
}
}
}
struct CountryListView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
CountryListView(viewModel: CountryListViewModel(countries: [Country(flagImage: "", name: "Spain", slug: "spain")]))
}
}
}
|
//
// UserDefault.swift
// neversitup
//
// Created by Kasidid Wachirachai on 23/1/21.
//
import Foundation
class UserDefault {
var username: String = ""
var token: String = ""
let userDefaultTokenKey = "userToken"
static let shared = UserDefault()
init() {
guard let dict = UserDefaults.standard.object(forKey: userDefaultTokenKey) as? [String: String] else { return }
username = dict["username"] ?? ""
token = dict["token"] ?? ""
}
func saveUser(username: String?, token: String?) {
if let username = username, let token = token {
let userData = [
"username": username,
"token": token
]
UserDefaults.standard.setValue(userData, forKey: userDefaultTokenKey)
self.username = username
self.token = token
}
}
func isAnyUserLoggedIn() -> Bool {
return UserDefaults.standard.object(forKey: userDefaultTokenKey) != nil
}
func clearUser() {
UserDefaults.standard.setValue(nil, forKey: userDefaultTokenKey)
}
}
|
//
// AjustesViewController.swift
// Citious_IOs
//
// Created by Manuel Citious on 1/4/15.
// Copyright (c) 2015 Citious Team. All rights reserved.
//
import UIKit
class AjustesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//MARK: - Variables
let cellId = "CeldaUserSettings"
//MARK: - Outlets
@IBOutlet weak var miTablaPersonalizada: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
modificarUI()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
vieneDeListadoMensajes = false
if(irPantallaLogin){
irPantallaLogin = false
self.dismissViewControllerAnimated(true, completion: { () -> Void in
})
}else{
Utils.customAppear(self)
//Nos damos de alta para responder a la notificacion enviada por push
NSNotificationCenter.defaultCenter().addObserver(self, selector: "cambiarBadge", name:notificationChat, object: nil)
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
func modificarUI(){
miTablaPersonalizada.backgroundColor = UIColor.clearColor()
//Creamos un footer con un UIView para eliminar los separator extras
miTablaPersonalizada.tableFooterView = UIView()
}
func cambiarBadge(){
let tabArray = self.tabBarController?.tabBar.items as NSArray!
let tabItem = tabArray.objectAtIndex(2) as! UITabBarItem
let numeroMensajesSinLeer = Conversation.numeroMensajesSinLeer()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if(numeroMensajesSinLeer > 0){
tabItem.badgeValue = "\(numeroMensajesSinLeer)"
UIApplication.sharedApplication().applicationIconBadgeNumber = numeroMensajesSinLeer
}else{
tabItem.badgeValue = nil
UIApplication.sharedApplication().applicationIconBadgeNumber = 0
}
})
}
//UITableView Methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
internal func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var textoCelda = ""
let cell = tableView.dequeueReusableCellWithIdentifier(cellId, forIndexPath: indexPath)
//Como solo tendremos dos filas ponemos a cada uno el titulo que le corresponda
if(indexPath.row == 0){
textoCelda = "Perfil"
}else{
textoCelda = "Cerrar sesión"
}
cell.textLabel?.text = textoCelda
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if(indexPath.row == 0){
self.performSegueWithIdentifier("showPerfil", sender: self)
}else{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
LogOut.desLoguearBorrarDatos()
ocultarLogIn = false
self.dismissViewControllerAnimated(true, completion: nil)
})
LogOut.desLoguear()
}
}
}
|
//
// Timer.swift
// AiNi
//
// Created by Julia Silveira de Souza on 18/05/21.
//
import SwiftUI
var defaultTImeRemaining: CGFloat = 10
var lineWidth: CGFloat = 5
var radius: CGFloat = 70
struct TreatmentTimer: View {
@State private var isActive = false
@State private var timeRemaining: CGFloat = defaultTImeRemaining
//@State var minutes: CGFloat = 1
//@State var seconds: CGFloat = 30
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
ZStack {
VStack(spacing: 25) {
VStack(content: {
ZStack {
Circle()
.stroke(Color.white.opacity(0.3), style: StrokeStyle(lineWidth: lineWidth, lineCap: .round))
Circle()
.trim(from: 0, to: 1 - ((defaultTImeRemaining - timeRemaining) / defaultTImeRemaining))
.stroke(timeRemaining > defaultTImeRemaining / 2 ? Color.blue : timeRemaining > defaultTImeRemaining / 4 ? Color.blue : Color.gray, style: StrokeStyle(lineWidth: lineWidth, lineCap: .round))
.rotationEffect(.degrees(90))
.animation(.easeOut)
VStack {
Text("\(timeRemaining == 0 ? "Pronto!" : "\(Int(timeRemaining))")")
.font(.title)
.fontWeight(.bold)
.foregroundColor(.black)
HStack{
Button(action: {isActive = false
timeRemaining = defaultTImeRemaining}, label: {
Text("\(Image(systemName:"goforward")) Repetir")
.font(.subheadline)
.fontWeight(.light)
.foregroundColor(.black)
})
.padding(6)
}.padding(.top)
}
}
}).frame(width: radius * 2.7, height: radius * 2.7, alignment: .center)
VStack {
HStack {
Button("\(isActive ? "Pausar" : !isActive && timeRemaining == defaultTImeRemaining ? "Começar" : "Pausado")", action: {
isActive.toggle()
}).buttonStyle(BlueButton())
if isActive == false {
DoneStageButton()
}
}
}
}
}.onReceive(timer, perform: { _ in
guard isActive else { return }
if timeRemaining > 0 {
timeRemaining -= 1
// }else if seconds > 60 {
// minutes -= 1
}else{
isActive = false
timeRemaining = defaultTImeRemaining
}
})
}
}
struct TreatmentTimer_Previews: PreviewProvider {
static var previews: some View {
TreatmentTimer()
}
}
|
//
// DetailInteractor.swift
// viper_test
//
// Created by Brian Baragar on 20/05/21.
//
//
import Foundation
class DetailInteractor: DetailInteractorInputProtocol {
// MARK: Properties
weak var presenter: DetailInteractorOutputProtocol?
var localDatamanager: DetailLocalDataManagerInputProtocol?
var remoteDatamanager: DetailRemoteDataManagerInputProtocol?
func detailPokemon(pokemonName: String) {
remoteDatamanager?.apiGetPokemon(name: pokemonName)
}
func getImageOfPokemon(url: String) {
remoteDatamanager?.remoteImageUrl(url: url)
}
}
extension DetailInteractor: DetailRemoteDataManagerOutputProtocol {
func remoteImageUrlCallBack(with image: Data) {
presenter?.pushImageToPresenter(imageData: image)
}
// TODO: Implement use case methods
func remoteDataManagerCallbackData(with pokemon: DetailPokemon) {
//El interactor debe enviarle los datos al presenter
//Los datos tienen que estar digeridos para el presenter
presenter?.interactorPushDataPresenter(receivedData: pokemon)
}
}
|
//
// AlbumDetailsViewController.swift
// SwiftFirestorePhotoAlbum
//
// Created by Alex Akrimpai on 15/09/2018.
// Copyright © 2018 Alex Akrimpai. All rights reserved.
//
import UIKit
import FirebaseFirestore
class AlbumDetailsViewController: UIViewController, ImageTaskDownloadedDelegate {
var album: AlbumEntity!
var imageEntities: [ImageEntity]?
var imageTasks = [String: ImageTask]()
var queryListener: ListenerRegistration!
var selectedPhoto: (index: Int, photoDetailsController: PhotoDetailsViewController)?
let urlSession = URLSession(configuration: URLSessionConfiguration.default)
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = album.name
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
selectedPhoto = nil
queryListener = ImageService.shared.getAllImagesFor(albumId: album.albumId) { [weak self] images in
guard let strongSelf = self else { return }
strongSelf.imageEntities = images
strongSelf.updateImageTasks()
if images.isEmpty {
strongSelf.collectionView.addNoDataLabel(text: "No Photos added yet.\n\nPlease press the + button to begin")
} else {
strongSelf.collectionView.removeNoDataLabel()
}
strongSelf.collectionView.reloadData()
strongSelf.activityIndicator.stopAnimating()
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if self.isMovingFromParentViewController {
queryListener.remove()
}
}
func updateImageTasks() {
imageEntities?.forEach { imageEntity in
if imageEntity.status == .ready, imageTasks[imageEntity.imageId] == nil, let urlStr = imageEntity.url, let url = URL(string: urlStr) {
imageTasks[imageEntity.imageId] = ImageTask(id: imageEntity.imageId, url: url, session: urlSession, delegate: self)
}
}
}
func imageDownloaded(id: String) {
if let index = imageEntities?.firstIndex(where: { $0.imageId == id }) {
collectionView.reloadItems(at: [IndexPath(row: index, section: 0)])
if let selectedPhoto = self.selectedPhoto, selectedPhoto.index == index, imageEntities?.count ?? 0 > index, let imageEntity = imageEntities?[index], let imageTask = imageTasks[imageEntity.imageId], let image = imageTask.image {
selectedPhoto.photoDetailsController.image = image
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SelectPhotosSegue", let selectPhotosController = segue.destination.childViewControllers.first as? SelectPhotosViewController {
selectPhotosController.album = album
} else if segue.identifier == "PhotoDetailsSegue", let photoDetailsController = segue.destination as? PhotoDetailsViewController, let index = sender as? Int, imageEntities?.count ?? 0 > index, let imageEntity = imageEntities?[index] {
selectedPhoto = (index, photoDetailsController)
photoDetailsController.imageId = imageEntity.imageId
photoDetailsController.image = imageTasks[imageEntity.imageId]?.image
}
}
}
|
//
// User.swift
// RealmTest
//
// Created by Enkhjargal Gansukh on 17/06/2017.
// Copyright © 2017 Enkhjargal Gansukh. All rights reserved.
//
import Foundation
import RealmSwift
class User: Object {
dynamic var id: String!
dynamic var name: String!
}
|
//
// BaseVC.swift
// TemplateSwiftAPP
//
// Created by wenhua yu on 2018/3/21.
// Copyright © 2018年 wenhua yu. All rights reserved.
//
import Foundation
import SVProgressHUD
class BaseVC: UIViewController {
var isHideNav: Bool = false
var isShowEmptyView: Bool = false {
didSet {
if isShowEmptyView == true {
view.addSubview(emptyView)
view.bringSubview(toFront: emptyView)
}
else {
emptyView.removeFromSuperview()
}
}
}
lazy var emptyView: EmptyView = {
var view = EmptyView.init(frame: CGRect.init(x: 0, y: 0, width: Device_width, height: Device_height))
view.emptyViewType = EmptyViewType.EmptyViewType_NoNavAndTab
let tap = UITapGestureRecognizer.init(target: self, action: #selector(emptyTapGesture))
view.addGestureRecognizer(tap)
return view
}()
private lazy var leftBtn: UIButton = {
var view = UIButton.init(type: .custom)
view.addTarget(self, action: #selector(BaseVC.goBack), for: .touchUpInside)
view.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
view.titleLabel?.font = FontMacro.font15
view.setTitleColor(.white, for: .normal)
return view
}()
private lazy var rightBtn: UIButton = {
var view = UIButton.init(type: .custom)
view.addTarget(self, action: #selector(BaseVC.goNext), for: .touchUpInside)
view.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
view.titleLabel?.font = FontMacro.font15
view.setTitleColor(.white, for: .normal)
return view
}()
// init() {
// super.init(nibName: nil, bundle: nil)
// }
//
// required init?(coder aDecoder: NSCoder) {
// fatalError("init(coder:) has not been implemented")
// }
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = ColorMacro.ColorBg
self.edgesForExtendedLayout = UIRectEdge.top
}
/// todo - 无效
func preferredStatusBarStyle() -> UIStatusBarStyle {
return .default
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if isHideNav {
self.navigationController?.setNavigationBarHidden(true, animated: true)
} else {
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
}
/// MARK: - Event
@objc func goNext() -> Void {}
@objc func goBack() -> Void {
self.navigationController?.popViewController(animated: true)
}
/// MARK: - UI
func leftTitle(title: String) -> Void {
leftBtn.setTitle(title, for: .normal)
let rightBarItem = UIBarButtonItem.init(customView: leftBtn)
self.navigationItem.leftBarButtonItem = rightBarItem
}
func rightTitle(title: String) -> Void {
rightBtn.setTitle(title, for: .normal)
let rightBarItem = UIBarButtonItem.init(customView: rightBtn)
self.navigationItem.rightBarButtonItem = rightBarItem
}
func leftIcon(icon: UIImage) -> Void {
leftBtn.setImage(icon, for: .normal)
let leftBarItem = UIBarButtonItem.init(customView: leftBtn)
self.navigationItem.leftBarButtonItem = leftBarItem
}
func rightIcon(icon: UIImage) -> Void {
rightBtn.setImage(icon, for: .normal)
let rightBarItem = UIBarButtonItem.init(customView: rightBtn)
self.navigationItem.rightBarButtonItem = rightBarItem
}
/// MARK: - SVProgressHUD
func showLoadingHUD() -> Void {
self.showLoadingHUD(hud: "正在加载")
}
func showLoadingHUD(hud: String) -> Void {
self.settingSVProgressHUD()
SVProgressHUD.show(withStatus: hud)
}
func hideLoadingHUD() -> Void {
SVProgressHUD.dismiss()
}
func showInfoMessage(hud: String) -> Void {
self.settingSVProgressHUD()
SVProgressHUD.showInfo(withStatus: hud)
}
func showSuccessMessage(hud: String) -> Void {
self.settingSVProgressHUD()
SVProgressHUD.showSuccess(withStatus: hud)
}
func showErrorMessage(hud: String) -> Void {
self.settingSVProgressHUD()
SVProgressHUD.showError(withStatus: hud)
}
func settingSVProgressHUD() -> Void {
SVProgressHUD.setDefaultStyle(.dark)
SVProgressHUD.setDefaultMaskType(.clear)
SVProgressHUD.setMinimumDismissTimeInterval(1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/// 空页面点击交互
@objc func emptyTapGesture() -> Void {}
/*
// 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.
}
*/
}
|
//
// FundsMoneyoutToggleController.swift
//
// Created on 15/7/16.
// NavigationTopView主页面控制器
import UIKit
class FundsMoneyoutToggleController: SlideMenuToggleController{
override func viewDidLoad() {
super.viewDidLoad()
}
override func setupMainView(){
MainViewController = FundsMoneyoutController()
}
override func setupTitleView() {
let titleView = UILabel()
titleView.textColor = UIColor.whiteColor()
titleView.text = "提现转出"
titleView.font = UIFont.boldSystemFontOfSize(18.0)
titleView.sizeToFit()
topBarView.naviItem.titleView = titleView
}
}
|
//
// StrokeInfoTableViewCell.swift
// StrokeInfo
//
// Created by Will Meyer on 1/17/16.
// Copyright © 2016 Will Meyer. All rights reserved.
//
import UIKit
class StrokeInfoTableViewCell: UITableViewCell {
@IBOutlet var infoLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.accessoryType = .DisclosureIndicator
self.preservesSuperviewLayoutMargins = false
self.layoutMargins = UIEdgeInsetsZero
self.separatorInset = UIEdgeInsets(top: 0, left: 4, bottom: 0, right: 4)
let bgColorView = UIView()
bgColorView.backgroundColor = selectedColor
bgColorView.layer.cornerRadius = 5
self.selectedBackgroundView = bgColorView
}
}
|
protocol IAddErc20TokenView: class {
func set(address: String?)
func set(error: Error?)
func set(spinnerVisible: Bool)
func set(viewItem: AddErc20TokenModule.ViewItem?)
func set(warningVisible: Bool)
func set(buttonVisible: Bool)
func refresh()
func showSuccess()
}
protocol IAddErc20TokenViewDelegate {
func onTapPasteAddress()
func onTapDeleteAddress()
func onTapAddButton()
func onTapCancel()
}
protocol IAddErc20TokenInteractor {
var valueFromPasteboard: String? { get }
func validate(address: String) throws
func existingCoin(address: String) -> Coin?
func fetchCoin(address: String)
func abortFetchingCoin()
func save(coin: Coin)
}
protocol IAddErc20TokenInteractorDelegate: AnyObject {
func didFetch(coin: Coin)
func didFailToFetchCoin(error: Error)
}
protocol IAddErc20TokenRouter {
func close()
}
class AddErc20TokenModule {
struct ViewItem {
let coinName: String
let symbol: String
let decimals: Int
}
}
|
// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import -enable-swift-newtype %s | FileCheck %s -check-prefix=CHECK-RAW
// RUN: %target-swift-frontend -emit-sil -sdk %S/Inputs -I %S/Inputs -enable-source-import -enable-swift-newtype %s | FileCheck %s -check-prefix=CHECK-CANONICAL
// REQUIRES: objc_interop
import Newtype
// CHECK-CANONICAL-LABEL: sil hidden @_TF7newtype17createErrorDomain
// CHECK-CANONICAL: bb0([[STR:%[0-9]+]] : $String)
func createErrorDomain(str: String) -> ErrorDomain {
// CHECK-CANONICAL: [[BRIDGE_FN:%[0-9]+]] = function_ref @{{.*}}_bridgeToObjectiveC
// CHECK-CANONICAL-NEXT: [[BRIDGED:%[0-9]+]] = apply [[BRIDGE_FN]]([[STR]])
// CHECK-CANONICAL: struct $ErrorDomain ([[BRIDGED]] : $NSString)
return ErrorDomain(rawValue: str)
}
// CHECK-RAW-LABEL: sil shared [transparent] [fragile] @_TFVSC11ErrorDomainCfT8rawValueSS_S_
// CHECK-RAW: bb0([[STR:%[0-9]+]] : $String,
// CHECK-RAW: [[SELF_BOX:%[0-9]+]] = alloc_box $ErrorDomain, var, name "self"
// CHECK-RAW: [[SELF:%[0-9]+]] = project_box [[SELF_BOX]]
// CHECK-RAW: [[UNINIT_SELF:%[0-9]+]] = mark_uninitialized [rootself] [[SELF]]
// CHECK-RAW: [[BRIDGE_FN:%[0-9]+]] = function_ref @{{.*}}_bridgeToObjectiveC
// CHECK-RAW: [[BRIDGED:%[0-9]+]] = apply [[BRIDGE_FN]]([[STR]])
// CHECK-RAW: [[RAWVALUE_ADDR:%[0-9]+]] = struct_element_addr [[UNINIT_SELF]]
// CHECK-RAW: assign [[BRIDGED]] to [[RAWVALUE_ADDR]]
func getRawValue(ed: ErrorDomain) -> String {
return ed.rawValue
}
// CHECK-RAW-LABEL: sil shared @_TFVSC11ErrorDomaing8rawValueSS
// CHECK-RAW: bb0([[SELF:%[0-9]+]] : $ErrorDomain):
// CHECK-RAW: [[FORCE_BRIDGE:%[0-9]+]] = function_ref @_forceBridgeFromObjectiveC_bridgeable
// CHECK-RAW: [[STORED_VALUE:%[0-9]+]] = struct_extract [[SELF]] : $ErrorDomain, #ErrorDomain._rawValue
// CHECK-RAW: [[STRING_META:%[0-9]+]] = metatype $@thick String.Type
// CHECK-RAW: [[STRING_RESULT_ADDR:%[0-9]+]] = alloc_stack $String
// CHECK-RAW: apply [[FORCE_BRIDGE]]<String, NSString>([[STRING_RESULT_ADDR]], [[STORED_VALUE]], [[STRING_META]])
// CHECK-RAW: [[STRING_RESULT:%[0-9]+]] = load [[STRING_RESULT_ADDR]]
// CHECK-RAW: return [[STRING_RESULT]]
|
//
// Transaction.swift
// Viajabessa
//
// Created by Lucas Ferraço on 14/05/18.
// Copyright © 2018 Lucas Ferraço. All rights reserved.
//
import Foundation
import Caishen
class Transaction {
public var publicationDate: Date!
public var package: TravelPackage!
public var cardHolderName: String!
public var card: Card!
private var phone: Phone! = Phone.shared
init(package: TravelPackage, cardHolderName: String, card: Card) {
self.publicationDate = Date()
self.package = package
self.cardHolderName = cardHolderName
self.card = card
}
}
extension Transaction: Encodable {
private enum CodingKeys: String, CodingKey {
case publicationDate = "publicada_em"
case value = "valor"
case packageId = "id_pacote"
case cardHolder = "nome_cartao"
case cardNumber = "numero_cartao"
case cardCode = "cvv_cartao"
case cardExpiration = "expiracao_cartao"
case phoneBrand = "marca_tel"
case phoneModel = "modelo_tel"
case phoneSystemVersion = "versao_so_tel"
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
let formatter = DateFormatter.timeStamp
try container.encode(formatter.string(from: self.publicationDate), forKey: .publicationDate)
// Package Info
try container.encode(package.value, forKey: .value)
try container.encode(package.id, forKey: .packageId)
// Card Info
try container.encode(cardHolderName, forKey: .cardHolder)
try container.encode(card.bankCardNumber.rawValue, forKey: .cardNumber)
try container.encode(card.cardVerificationCode.toInt(), forKey: .cardCode)
let cardFormatter = DateFormatter.expiration
try container.encode(cardFormatter.string(from: card.expiryDate.rawValue), forKey: .cardExpiration)
// Phone Info
try container.encode(phone.brand, forKey: .phoneBrand)
try container.encode(phone.model, forKey: .phoneModel)
try container.encode(phone.iOSVersion, forKey: .phoneSystemVersion)
}
}
|
//
// LevelData.swift
// Calm Cloud
//
// Created by Kate Duncan-Welke on 8/30/21.
// Copyright © 2021 Kate Duncan-Welke. All rights reserved.
//
import Foundation
class LevelData: Codable {
let tiles: [[Int]]
let targetScore: Int
let moves: Int
static func loadFrom(file filename: String) -> LevelData? {
var data: Data
var levelData: LevelData?
if let path = Bundle.main.url(forResource: filename, withExtension: "json") {
do {
data = try Data(contentsOf: path)
} catch {
print("file failed to load")
return nil
}
do {
levelData = try JSONDecoder().decode(LevelData.self, from: data)
} catch {
print("could not decode file")
return nil
}
}
return levelData
}
}
|
//
// ThreeImagesViewCell.swift
// KoombeaChallengeTest
//
// Created by Renato Mateus on 27/09/21.
//
import UIKit
protocol ThreeImagesViewCellDelegate: AnyObject {
func didThreeImagesTapped(image: UIImage)
}
class ThreeImagesViewCell: UITableViewCell {
// MARK: - Identifier
static let identifier: String = "ThreeImagesViewCell"
// MARK: - Outlets
@IBOutlet weak var postDateLabel: UILabel!
@IBOutlet weak var postImageView: UIImageView!
@IBOutlet weak var firstImageView: UIImageView!
@IBOutlet weak var secondImageView: UIImageView!
// MARK: - Private Properties
weak var delegate: ThreeImagesViewCellDelegate?
private var post: Post? {
didSet {
setupData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
// MARK: - Setup Data
extension ThreeImagesViewCell {
func setupData() {
let date = Date()
if let postedDate = self.post?.date {
self.postDateLabel.text = date.getDate(dateString: postedDate)
}
if let imagePic = self.post?.pics[0],
let url = URL(string: imagePic) {
self.postImageView.kf.setImage(with: url)
self.configureImageTapped(self.postImageView)
}
if let imagePic2 = self.post?.pics[2],
let url = URL(string: imagePic2) {
self.firstImageView.kf.setImage(with: url)
self.configureImageTapped(self.firstImageView)
}
if let imagePic3 = self.post?.pics[2],
let url = URL(string: imagePic3) {
self.secondImageView.kf.setImage(with: url)
self.configureImageTapped(self.secondImageView)
}
}
}
// MARK: - Cell Configuration
extension ThreeImagesViewCell {
func configure(with post: Post) {
self.post = post
}
func configureImageTapped(_ imageView: UIImageView) {
let tap = UITapGestureRecognizer(target: self,
action: #selector(didTappedImage(tapGesture:)))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tap)
}
}
// MARK: - Actions
extension ThreeImagesViewCell {
@objc func didTappedImage(tapGesture: UITapGestureRecognizer) {
let imageView = tapGesture.view as! UIImageView
if let image = imageView.image {
self.delegate?.didThreeImagesTapped(image: image)
}
}
}
|
//
// Persistence.swift
// Shared
//
// Created by Linus Skucas on 8/18/21.
//
import CoreData
import Combine
import SwiftUI
let appTransactionAuthorName = "Telescope"
class PersistenceController {
static let shared = PersistenceController()
private var subscriptions: Set<AnyCancellable> = []
let container: NSPersistentCloudKitContainer
init() {
container = NSPersistentCloudKitContainer(name: "Telescope")
guard let privateStoreDescription = container.persistentStoreDescriptions.first else {
fatalError("### \(#file) \(#function) L\(#line) No Description")
}
privateStoreDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
privateStoreDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
container.loadPersistentStores(completionHandler: { _, error in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("### \(#file) \(#function) L\(#line): Failed to load persistent stores: \(error.localizedDescription)")
}
})
container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
container.viewContext.transactionAuthor = appTransactionAuthorName
container.viewContext.automaticallyMergesChangesFromParent = true
do {
try container.viewContext.setQueryGenerationFrom(.current)
} catch {
fatalError("### \(#file) \(#function) L\(#line): Failed to pin viewContext to the current generation: \(error.localizedDescription)")
}
NotificationCenter.default
.publisher(for: .NSPersistentStoreRemoteChange)
.sink { _ in
self.processRemoteStoreChange()
}
.store(in: &subscriptions)
if let tokenData = try? Data(contentsOf: tokenFile) {
do {
lastHistoryToken = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSPersistentHistoryToken.self, from: tokenData)
} catch {
print("### \(#function): Failed to unarchive NSPersistentHistoryToken. Error = \(error)")
}
}
}
/**
Track the last history token processed for a store, and write its value to file.
The historyQueue reads the token when executing operations, and updates it after processing is complete.
*/
private var lastHistoryToken: NSPersistentHistoryToken? {
didSet {
guard let token = lastHistoryToken,
let data = try? NSKeyedArchiver.archivedData(withRootObject: token, requiringSecureCoding: true) else { return }
do {
try data.write(to: tokenFile)
} catch {
print("### \(#function): Failed to write token data. Error = \(error)")
}
}
}
/**
The file URL for persisting the persistent history token.
*/
private lazy var tokenFile: URL = {
let url = NSPersistentContainer.defaultDirectoryURL().appendingPathComponent("Telescope", isDirectory: true)
if !FileManager.default.fileExists(atPath: url.path) {
do {
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
} catch {
print("### \(#function): Failed to create persistent container URL. Error = \(error)")
}
}
return url.appendingPathComponent("token.data", isDirectory: false)
}()
/**
An operation queue for handling history processing tasks: watching changes, deduplicating tags, and triggering UI updates if needed.
*/
private lazy var historyQueue: OperationQueue = {
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
return queue
}()
private func mergeChanges(from transactions: [NSPersistentHistoryTransaction]) {
container.viewContext.perform {
transactions.forEach { [weak self] transaction in
guard let self = self, let userInfo = transaction.objectIDNotification().userInfo else { return }
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: userInfo, into: [self.container.viewContext])
}
}
}
}
extension PersistenceController {
func processRemoteStoreChange() {
historyQueue.addOperation {
self.processPersistentHistory()
}
}
}
extension PersistenceController {
func processPersistentHistory() {
let backgroundContext = container.newBackgroundContext()
backgroundContext.performAndWait {
// Fetch history received from outside the app since the last token
let historyFetchRequest = NSPersistentHistoryTransaction.fetchRequest!
historyFetchRequest.predicate = NSPredicate(format: "author != %@", appTransactionAuthorName)
let request = NSPersistentHistoryChangeRequest.fetchHistory(after: lastHistoryToken)
request.fetchRequest = historyFetchRequest
let result = (try? backgroundContext.execute(request)) as? NSPersistentHistoryResult
guard let transactions = result?.result as? [NSPersistentHistoryTransaction],
!transactions.isEmpty
else { return }
print("transactions = \(transactions)")
self.mergeChanges(from: transactions)
// Update the history token using the last transaction.
lastHistoryToken = transactions.last!.token
}
}
}
|
//
// LocationFetchController.swift
// Weather Diary
//
// Created by Spencer Halverson on 1/22/20.
// Copyright © 2020 Spencer. All rights reserved.
//
import Foundation
class LocationFetchController {
private let apikey: String = "c2d2dcee438f902d23984c439b29bd34"
func getWeather(at zipcode: String, completion: @escaping ((WeatherResponse?, String?) -> Void)) {
guard var urlComps = URLComponents(string: "https://api.openweathermap.org/data/2.5/weather") else {
completion(nil, "Invalid URL")
return
}
urlComps.queryItems = [
URLQueryItem(name: "zip", value: "\(zipcode),us"),
URLQueryItem(name: "units", value: "imperial"),
URLQueryItem(name: "appid", value: apikey)
]
var request = URLRequest(url: urlComps.url!)
request.httpMethod = "GET"
request.allHTTPHeaderFields = ["Accept":"application/json"]
URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) in
DispatchQueue.main.async {
guard let data = data else {
completion(nil, error?.localizedDescription);
return
}
do {
let weatherResponse = try JSONDecoder().decode(WeatherResponse.self, from: data)
print("PARSED RESPONSE: ", weatherResponse)
completion(weatherResponse, nil)
} catch let error {
print("PARSING ERROR: ", error)
completion(nil, error.localizedDescription)
}
}
}).resume()
}
}
|
//
// LanguageModel.swift
// ET
//
// Created by HungNguyen on 11/7/19.
// Copyright © 2019 HungNguyen. All rights reserved.
//
import Foundation
import ObjectMapper
class ListLanguageModel: Mappable {
var languages: [LanguageModel] = []
required init?(map: Map) {}
func mapping(map: Map) {
languages <- map["languages"]
}
}
class LanguageModel: Mappable {
var language: String?
var name: String?
var selected: Bool = false
init() {}
init(_ name: String?, _ language: String?) {
self.name = name
self.language = language
}
required init?(map: Map) { }
func mapping(map: Map) {
language <- map["language"]
name <- map["name"]
}
}
|
//
// ViewController+CollectionViewDataSource.swift
// Layout
//
// Created by Josh Grant on 6/26/16.
// Copyright © 2016 Josh Grant. All rights reserved.
//
import UIKit
var numberOfItemsInSectionZero: Int = 5
var numberOfItemsInSectionTwo: Int = 4
extension ViewController: UICollectionViewDataSource
{
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
{
return 4
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
switch section
{
case 0: return numberOfItemsInSectionZero
case 1: return 1
case 2: return numberOfItemsInSectionTwo
case 3: return 0
default: return 0
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath)
return cell
}
// func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
//
// }
func collectionView(collectionView: UICollectionView, canMoveItemAtIndexPath indexPath: NSIndexPath) -> Bool
{
return true
}
func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath)
{
}
} |
//
// DisplayLink.swift
// MetalImage
//
// Created by Andrei-Sergiu Pițiș on 29/03/2018.
// Copyright © 2018 Andrei-Sergiu Pițiș. All rights reserved.
//
import Foundation
import CoreVideo
#if os(iOS)
typealias MIDisplayLink = CADisplayLink
typealias MITimestamp = CFTimeInterval
#elseif os(OSX)
typealias MIDisplayLink = CVDisplayLink
typealias MITimestamp = CVTimeStamp
#endif
class DisplayLink {
private var displayLink: MIDisplayLink?
private var timestamp: MITimestamp!
private var callback: ((MIDisplayLink, MITimestamp) -> Void)
init(callback: @escaping (MIDisplayLink, MITimestamp) -> Void) {
self.callback = callback
#if os(iOS)
displayLink = CADisplayLink(target: self, selector: #selector(render))
displayLink?.add(to: RunLoop.main, forMode: .defaultRunLoopMode)
displayLink?.isPaused = true
#elseif os(OSX)
CVDisplayLinkCreateWithActiveCGDisplays(&displayLink)
CVDisplayLinkSetOutputHandler(displayLink!) { [weak self] (displayLink, inNow, inOutputTime, flagsIn, flagsOut) -> CVReturn in
self?.timestamp = inNow.pointee
self?.run(displayLink: displayLink)
return kCVReturnSuccess
}
#endif
}
deinit {
Logger.debug("Deinit Display Link")
}
func start() {
guard let displayLink = displayLink else {
Logger.debug("Display Link in nil.")
return
}
#if os(iOS)
displayLink.isPaused = false
#elseif os(OSX)
CVDisplayLinkStart(displayLink)
#endif
}
func stop() {
guard let displayLink = displayLink else {
Logger.debug("Display Link in nil.")
return
}
#if os(iOS)
displayLink.isPaused = true
#elseif os(OSX)
CVDisplayLinkStop(displayLink)
#endif
}
func invalidate() {
#if os(iOS)
displayLink?.invalidate()
#endif
}
func run(displayLink: MIDisplayLink) {
#if os(iOS)
let timestamp = displayLink.timestamp
#elseif os(OSX)
let timestamp = self.timestamp!
#endif
callback(displayLink, timestamp)
}
}
|
//
// ScreenBarView.swift
// gjs_user
//
// Created by 大杉网络 on 2019/9/15.
// Copyright © 2019 大杉网络. All rights reserved.
//
protocol sortDelegate {
func sortDelegatefuc(backMsg:Int)
}
class ScreenBar: UIView {
var sort = 0
var screenLabelList = [UILabel]()
var screenIconList = [UIImageView]()
// 定义一个符合改协议的代理对象
var delegate:sortDelegate?
func processMethod(sort:Int?){
if((delegate) != nil){
delegate?.sortDelegatefuc(backMsg: sort!)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
// 筛选栏
let screenBar = self
screenBar.backgroundColor = .white
screenBar.configureLayout { (layout) in
layout.isEnabled = true
layout.flexDirection = .row
layout.justifyContent = .spaceAround
layout.alignItems = .center
layout.width = YGValue(kScreenW)
layout.height = 40
}
let screenList = [
[
"name": "综合"
],
[
"name": "券后价",
"icon": 1
],
[
"name": "销量",
"icon": 1
],
[
"name": "佣金比例",
"icon": 1
]
]
for (index, item) in screenList.enumerated() {
let screenItem = UIButton()
screenItem.tag = index
screenItem.addTarget(self, action: #selector(sortChange), for: .touchUpInside)
screenItem.configureLayout { (layout) in
layout.isEnabled = true
layout.flexDirection = .row
layout.justifyContent = .center
layout.alignItems = .center
layout.height = 40
}
screenBar.addSubview(screenItem)
let itemLabel = UILabel()
itemLabel.text = item["name"] as! String
itemLabel.font = FontSize(12)
if index == 0 {
itemLabel.textColor = kLowOrangeColor
} else {
itemLabel.textColor = colorwithRGBA(150,150,150,1)
}
itemLabel.configureLayout { (layout) in
layout.isEnabled = true
}
screenItem.addSubview(itemLabel)
screenLabelList.append(itemLabel)
if item["icon"] != nil {
let itemIcon = UIImageView(image: UIImage(named: "screen-1"))
itemIcon.configureLayout { (layout) in
layout.isEnabled = true
layout.width = 8
layout.height = 14
layout.marginLeft = 3
}
screenItem.addSubview(itemIcon)
screenIconList.append(itemIcon)
}
}
// 列表格式
// let listType = UIImageView(image: UIImage(named: "listType-1"))
// listType.isUserInteractionEnabled = true
// let tap = UITapGestureRecognizer(target: self, action: #selector(self.listTypeChange(sender:)))
// listType.addGestureRecognizer(tap)
// listType.configureLayout { (layout) in
// layout.isEnabled = true
// layout.width = 18
// layout.height = 18
// }
// screenBar.addSubview(listType)
screenBar.yoga.applyLayout(preservingOrigin: true)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func sortChange (_ btn : UIButton) {
var index = btn.tag
for (labelIndex, item) in screenLabelList.enumerated() {
if labelIndex == index {
item.textColor = kLowOrangeColor
} else {
item.textColor = colorwithRGBA(150,150,150,1)
}
}
for item in screenIconList {
item.image = UIImage(named: "screen-1")
}
if index == 0 {
sort = 0
} else if index == 1 {
if sort == 1 {
sort = 2
screenIconList[0].image = UIImage(named: "screen-3")
} else {
sort = 1
screenIconList[0].image = UIImage(named: "screen-2")
}
} else if index == 2 {
if sort == 7 {
sort = 4
screenIconList[1].image = UIImage(named: "screen-3")
} else {
sort = 7
screenIconList[1].image = UIImage(named: "screen-2")
}
} else if index == 3 {
if sort == 8 {
sort = 5
screenIconList[2].image = UIImage(named: "screen-3")
} else {
sort = 8
screenIconList[2].image = UIImage(named: "screen-2")
}
}
// 触发回调函数
processMethod(sort:sort)
}
@objc func listTypeChange (sender:UITapGestureRecognizer) {
if listTypeNum == 1 {
listTypeNum = 2
listType = UIImageView(image: UIImage(named: "listType-2"))
} else {
listTypeNum = 1
listType = UIImageView(image: UIImage(named: "listType-1"))
}
}
}
|
// Example of quicksort
func quicksort<T: Comparable>(array: inout [T]) {
sliceQuicksort(array: &array[array.startIndex..<array.endIndex])
}
func sliceQuicksort<T: Comparable>(array: inout ArraySlice<T>) {
if array.count <= 1 {
return
}
let pivot = partition(array: &array)
sliceQuicksort(array: &(array[array.startIndex..<pivot]))
let secondStart = pivot + 1
if secondStart < array.endIndex {
sliceQuicksort(array: &(array[secondStart..<array.endIndex]))
}
}
func partition<T: Comparable>(array: inout ArraySlice<T>) -> Int{
let pivot = array.endIndex - 1
let pivotValue = array[pivot]
var changeIndex = array.startIndex
for i in array.startIndex..<array.endIndex {
if array[i] < pivotValue {
let aux = array[changeIndex]
array[changeIndex] = array[i]
array[i] = aux
changeIndex += 1
}
}
array[pivot] = array[changeIndex]
array[changeIndex] = pivotValue
return changeIndex
} |
//
// Player+CoreDataClass.swift
//
//
// Created by Pabel Nunez Landestoy on 1/25/19.
//
//
import Foundation
import CoreData
import PocketSwift
public enum PlayerPersistenceError: Error {
case retrievalError
case creationError
case walletCreationError
}
@objc(Player)
public class Player: NSManagedObject {
private var godfatherWallet: Wallet?
public var godfatherAddress: String? {
get {
if let godfatherWallet = self.getGodfatherWallet() {
return godfatherWallet.address
} else {
return nil
}
}
}
convenience init(obj: [AnyHashable: Any]?, context: NSManagedObjectContext) throws {
self.init(context: context)
if let playerObj = obj {
self.address = playerObj["address"] as? String ?? ""
self.balanceAmp = playerObj["balanceWei"] as? String ?? "0"
self.transactionCount = playerObj["transactionCount"] as? String ?? "0"
self.tavernMonsterAmount = playerObj["tavernMonsterAmount"] as? String ?? "0"
self.aionUsdPrice = playerObj["aionUsdPrice"] as? Double ?? 0.0
}
}
func save() throws {
try self.managedObjectContext?.save()
}
public static func dropTable(context: NSManagedObjectContext) throws {
let fetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Player")
let request = NSBatchDeleteRequest(fetchRequest: fetch)
let _ = try context.execute(request)
}
// Either returns a new player to save data to, or returns the existing player
public static func getPlayer(context: NSManagedObjectContext) throws -> Player {
var result: Player
let fetchRequest: NSFetchRequest<Player> = Player.fetchRequest()
let playerStore = try context.fetch(fetchRequest)
if playerStore.count > 0 {
guard let player = playerStore.first else {
throw PlayerPersistenceError.retrievalError
}
result = player
} else {
throw PlayerPersistenceError.retrievalError
}
return result
}
public func getWallet(passphrase: String) throws -> Wallet? {
var result: Wallet?
if let playerAddress = self.address {
result = try Wallet.retrieveWallet(network: AppConfiguration.network, netID: AppConfiguration.netID, address: playerAddress, passphrase: passphrase)
}
return result
}
public static func createPlayer(walletPassphrase: String) throws -> Player {
// First create the wallet
guard let wallet = try PocketAion.shared?.createWallet(netID: AppConfiguration.netID) else {
throw PlayerPersistenceError.walletCreationError
}
if try wallet.save(passphrase: walletPassphrase) == false {
throw PlayerPersistenceError.walletCreationError
}
// Create the player
return try Player.createAndSavePlayer(address: wallet.address)
}
public static func createPlayer(walletPassphrase: String, privateKey: String) throws -> Player {
// First create the wallet
guard let wallet = try PocketAion.shared?.importWallet(privateKey: privateKey, netID: AppConfiguration.netID) else {
throw PlayerPersistenceError.walletCreationError
}
if try wallet.save(passphrase: walletPassphrase) == false {
throw PlayerPersistenceError.walletCreationError
}
// Create the player
return try Player.createAndSavePlayer(address: wallet.address)
}
private static func createAndSavePlayer(address: String) throws -> Player {
let context = CoreDataUtils.mainPersistentContext
let player = try Player.init(obj: ["address": address], context: context)
try player.save()
return player
}
public func getGodfatherWallet() -> Wallet? {
if let result = self.godfatherWallet {
return result;
} else {
guard let godfatherWallet = try? PocketAion.shared?.importWallet(privateKey: AppConfiguration.godfatherPK, netID: AppConfiguration.netID) else {
return nil
}
self.godfatherWallet = godfatherWallet
return self.godfatherWallet
}
}
public static func wipePlayerData(context: NSManagedObjectContext, player: Player, wallet: Wallet) throws -> Bool {
var result = false
guard let playerAddress = player.address else {
return result
}
// First delete biometric record
if BiometricsUtils.biometricRecordExists(playerAddress: playerAddress) {
let _ = BiometricsUtils.removeBiometricRecord(playerAddress: playerAddress)
}
// Second delete core data
try Chase.dropTable(context: context)
try Monster.dropTable(context: context)
try Player.dropTable(context: context)
try Transaction.dropTable(context: context)
// Third delete wallet
let _ = try wallet.delete()
// Set result to true
result = true
return result
}
}
|
//
// ed25519_sc.swift
//
// Copyright 2017 pebble8888. All rights reserved.
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
import Foundation
struct shortsc {
var v: [UInt32] // 16
init() {
v = [UInt32](repeating: 0, count: 16)
}
}
struct sc {
var v: [UInt32] // 32
init() {
v = [UInt32](repeating: 0, count: 32)
}
private static let k = 32
/* Arithmetic modulo the group order
order
= 2^252 + 27742317777372353535851937790883648493
= 7237005577332262213973186563042994240857116359379907606001950938285454250989
= 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed
p = 2^255 - 19
= 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed
*/
// little endian group order m
private static let m: [UInt32] =
[0xED, 0xD3, 0xF5, 0x5C, 0x1A, 0x63, 0x12, 0x58, 0xD6, 0x9C, 0xF7, 0xA2, 0xDE, 0xF9, 0xDE, 0x14,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10]
/*
for barrett_reduce algorithm
b = 256 = 2^8
k = 32 = 2^5
b^(2k) = (2^8)^64 = 2^512
mu = 2^512 // m
= 1852673427797059126777135760139006525645217721299241702126143248052143860224795
= 0x0fffffffffffffffffffffffffffffffeb2106215d086329a7ed9ce5a30a2c131b
*/
private static let mu: [UInt32] =
[0x1B, 0x13, 0x2C, 0x0A, 0xA3, 0xE5, 0x9C, 0xED, 0xA7, 0x29, 0x63, 0x08, 0x5D, 0x21, 0x06, 0x21,
0xEB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F]
private static func lt(_ a: UInt32, _ b: UInt32) -> UInt32 /* 16-bit inputs */ {
if a < b {
return 1
} else {
return 0
}
}
/// if r > m: r = r - m
/// else : r = r
private static func reduce_add_sub(_ r: inout sc) {
var val: UInt32 = 0
var borrow: UInt32 = 0
// r - m
var t = [UInt8](repeating: 0, count: 32)
for i in 0..<k {
val += m[i]
borrow = lt(r.v[i], val)
let vv = Int64(r.v[i]) - Int64(val) + Int64(borrow << 8)
assert(vv >= 0 && vv <= 0xff)
t[i] = UInt8(vv)
val = borrow
}
// no borrow: mask = 0xffffffff -> r = r - m
// borrow : mask = 0x0 -> r = r
let mask = UInt32(bitPattern: Int32(borrow)-1)
for i in 0..<k {
r.v[i] ^= mask & (r.v[i] ^ UInt32(t[i]))
}
}
/// Reduce coefficients of x before calling barrett_reduce
/// r = x mod m
///
/// b = 256 = 2^8
/// k = 32 = 2^5
/// x < b^(2k)
/// x: LSB
private static func barrett_reduce(_ r: inout sc, _ x: [UInt32] /* 64 */) {
assert(x.count == 64)
/* See HAC(HANDBOOK OF APPLIED CRYPTOGRAPHY), Alg. 14.42 */
// STEP1
// q1 = floor(x / b^(k-1))
// q2 <- q1 * mu
var q2 = [UInt32](repeating: 0, count: 2*k+2) // LSB
for i in 0...k {
for j in 0...k {
if i+j >= k-1 {
q2[i+j] += x[j+k-1] * mu[i]
}
}
}
// q3 = floor(q2 / b^(k+1))
// q3 = (... + b^(k+1) * q2[k+1] + b^(k+2) * q2[k+2] + ... + b^(2k) * q2[2k] + b^(2k+1) * q2[2k+1])
// = q2[k+1] + b^1 * q2[k+1] + ... + b^(k-1) * q2[2k] + b^k * q2[2k+1]
// Since q2[2k] has carry q2[2k+1] is zero.
let carry1 = q2[k-1] >> 8
q2[k] += carry1
let carry2 = q2[k] >> 8
q2[k+1] += carry2
// STEP2,3
// r1 = x (mod b^(k+1))
var r1 = [UInt32](repeating: 0, count: k+1)
for i in 0...k {
r1[i] = x[i]
}
// r2 = q3 * m (mod b^(k+1))
var r2 = [UInt32](repeating: 0, count: k+1)
for i in 0...k-1 {
for j in 0...k {
if i+j < k+1 {
r2[i+j] += q2[j+k+1] * m[i]
}
}
}
for i in 0...k-1 {
let carry = r2[i] >> 8
r2[i+1] += carry
r2[i] &= 0xff
}
r2[k] &= 0xff
// r = r1 - r2 (or + b^(k+1))
// last borrow means STEP3 for r < 0
// r = (Q-q3) * m + R <= 2m
// 2m = 2 * (0x10 * b^(k-1) + ...) = 0x20 * b^(k-1) + ... < b^k
// so r can represented for b^0 y\_0 + b^1 y\_1 + ... + b^(k-1) y\_(k-1)
// it means r[v] is zero
var val: UInt32 = 0
for i in 0...k-1 {
val += r2[i]
let borrow = lt(r1[i], val)
let vv = Int64(r1[i]) - Int64(val) + Int64(borrow << 8)
assert(vv >= 0 && vv <= 0xff)
r.v[i] = UInt32(vv)
val = borrow
}
// STEP4: twice or once or none
reduce_add_sub(&r)
reduce_add_sub(&r)
}
// check x is [0, m)
static func sc25519_less_order(_ x: [UInt8] /* 32 */) -> Bool {
if x.count != k {
return false
}
for i in (0..<k).reversed() {
if x[i] < m[i] {
// less
return true
} else if x[i] > m[i] {
// large
return false
}
}
// equal to m
return false
}
static func sc25519_from32bytes(_ r: inout sc, _ x: [UInt8] /* 32 */) {
assert(x.count >= k)
var t = [UInt32](repeating: 0, count: k*2)
for i in 0..<k {
t[i] = UInt32(x[i])
}
for i in k..<k*2 {
t[i] = 0
}
// r = t mod m
sc.barrett_reduce(&r, t)
}
static func sc25519_from16bytes(_ r: inout shortsc, _ x: [UInt8] /* 16 */) throws {
assert(x.count >= 16)
for i in 0..<16 {
r.v[i] = UInt32(x[i])
}
}
static func sc25519_from64bytes(_ r: inout sc, _ x: [UInt8] /* 64 */) {
assert(x.count == k*2)
var t = [UInt32](repeating: 0, count: k*2)
for i in 0..<k*2 {
t[i] = UInt32(x[i])
}
// r = t mod b
sc.barrett_reduce(&r, t)
}
static func sc25519_from_shortsc(_ r: inout sc, _ x: shortsc) {
for i in 0..<16 {
r.v[i] = x.v[i]
}
for i in 0..<16 {
r.v[16+i] = 0
}
}
static func sc25519_to32bytes(_ r: inout [UInt8] /* 32 */, _ x: sc) {
assert(r.count == k)
for i in 0..<k {
r[i] = UInt8(x.v[i])
}
}
static func sc25519_iszero_vartime(_ x: sc) -> Int {
for i in 0..<k {
if x.v[i] != 0 {
return 0
}
}
return 1
}
static func sc25519_isshort_vartime(_ x: sc) -> Int {
for i in stride(from: 31, to: 15, by: -1) {
if x.v[i] != 0 {
return 0
}
}
return 1
}
static func sc25519_lt_vartime(_ x: sc, _ y: sc) -> UInt {
for i in stride(from: 31, through: 0, by: -1) {
if x.v[i] < y.v[i] {
return 1
}
if x.v[i] > y.v[i] {
return 0
}
}
return 0
}
static func sc25519_add(_ r: inout sc, _ x: sc, _ y: sc) {
var carry: UInt32
for i in 0..<k {
r.v[i] = x.v[i] + y.v[i]
}
for i in 0..<k-1 {
carry = r.v[i] >> 8
r.v[i+1] += carry
r.v[i] &= 0xff
}
sc.reduce_add_sub(&r)
}
static func sc25519_sub_nored(_ r: inout sc, _ x: sc, _ y: sc) {
var borrow: UInt32 = 0
var t: UInt32
for i in 0..<k {
t = x.v[i] - y.v[i] - borrow
r.v[i] = t & 0xff
borrow = (t >> 8) & 1
}
}
static func sc25519_mul(_ r: inout sc, _ x: sc, _ y: sc) {
var t = [UInt32](repeating: 0, count: k*2)
for i in 0..<k {
for j in 0..<k {
t[i+j] += x.v[i] * y.v[j]
}
}
/* Reduce coefficients */
for i in 0..<2*k-1 {
let carry = t[i] >> 8
t[i+1] += carry
t[i] &= 0xff
}
sc.barrett_reduce(&r, t)
}
static func sc25519_mul_shortsc(_ r: inout sc, _ x: sc, _ y: shortsc) {
var t = sc()
sc25519_from_shortsc(&t, y)
sc25519_mul(&r, x, t)
}
// divide to 3bits
// 3 * 85 = 255
static func sc25519_window3(_ r: inout [Int8] /* 85 */, _ s: sc) {
assert(r.count == 85)
for i in 0..<10 {
r[8*i+0] = Int8(bitPattern: UInt8(s.v[3*i+0] & 7))
r[8*i+1] = Int8(bitPattern: UInt8((s.v[3*i+0] >> 3) & 7))
r[8*i+2] = Int8(bitPattern: UInt8((s.v[3*i+0] >> 6) & 7))
r[8*i+2] ^= Int8(bitPattern: UInt8((s.v[3*i+1] << 2) & 7))
r[8*i+3] = Int8(bitPattern: UInt8((s.v[3*i+1] >> 1) & 7))
r[8*i+4] = Int8(bitPattern: UInt8((s.v[3*i+1] >> 4) & 7))
r[8*i+5] = Int8(bitPattern: UInt8((s.v[3*i+1] >> 7) & 7))
r[8*i+5] ^= Int8(bitPattern: UInt8((s.v[3*i+2] << 1) & 7))
r[8*i+6] = Int8(bitPattern: UInt8((s.v[3*i+2] >> 2) & 7))
r[8*i+7] = Int8(bitPattern: UInt8((s.v[3*i+2] >> 5) & 7))
}
let i = 10
r[8*i+0] = Int8(bitPattern: UInt8(s.v[3*i+0] & 7))
r[8*i+1] = Int8(bitPattern: UInt8((s.v[3*i+0] >> 3) & 7))
r[8*i+2] = Int8(bitPattern: UInt8((s.v[3*i+0] >> 6) & 7))
r[8*i+2] ^= Int8(bitPattern: UInt8((s.v[3*i+1] << 2) & 7))
r[8*i+3] = Int8(bitPattern: UInt8((s.v[3*i+1] >> 1) & 7))
r[8*i+4] = Int8(bitPattern: UInt8((s.v[3*i+1] >> 4) & 7))
/* Making it signed */
var carry: Int8 = 0
for i in 0..<84 {
r[i] += carry
r[i+1] += (r[i] >> 3)
r[i] &= 7
carry = r[i] >> 2
let vv: Int16 = Int16(r[i]) - Int16(carry<<3)
assert(vv >= -128 && vv <= 127)
r[i] = Int8(vv)
}
r[84] += Int8(carry)
}
// scalar is less than 2^255 - 19, so 256bit value always zero.
static func sc25519_2interleave2(_ r: inout [UInt8] /* 127 */, _ s1: sc, _ s2: sc) {
assert(r.count == 127)
for i in 0..<31 {
let a1 = UInt8(s1.v[i] & 0xff)
let a2 = UInt8(s2.v[i] & 0xff)
// 8bits = 2bits * 4
// s2 s1
r[4*i] = ((a1 >> 0) & 3) ^ (((a2 >> 0) & 3) << 2)
r[4*i+1] = ((a1 >> 2) & 3) ^ (((a2 >> 2) & 3) << 2)
r[4*i+2] = ((a1 >> 4) & 3) ^ (((a2 >> 4) & 3) << 2)
r[4*i+3] = ((a1 >> 6) & 3) ^ (((a2 >> 6) & 3) << 2)
}
let b1 = UInt8(s1.v[31] & 0xff)
let b2 = UInt8(s2.v[31] & 0xff)
r[124] = ((b1 >> 0) & 3) ^ (((b2 >> 0) & 3) << 2)
r[125] = ((b1 >> 2) & 3) ^ (((b2 >> 2) & 3) << 2)
r[126] = ((b1 >> 4) & 3) ^ (((b2 >> 4) & 3) << 2)
}
}
|
//
// DatabaseOperations.swift
// Week3_DataBase
//
// Created by Unmesh on 23/06/17.
// Copyright © 2017 Unmesh. All rights reserved.
//
func getBooksByAuthorId(_ id: Int) -> [BooksList] {
var books:[BooksList]!
do {
dbQueue.inDatabase { db in
do {
books = try BooksList.fetchAll(db, "select * from BooksList where authorID=?", arguments:[id])
//books = try BooksList.filter(b.authorID == id) // Problem with comparision
} catch let error {
print(error)
}
}
}
return books
}
func getIdByName(_ name: String) -> Int {
var some:Int = 0
do {
dbQueue.inDatabase { db in
do {
some = try Int.fetchOne(db,"select * from AuthorList where authorName=?",arguments:[name] )!
} catch let error {
print(error)
}
}
}
return some
}
|
import Foundation
import RxSwift
import RxRelay
class NonSpamPoolProvider {
private let poolProvider: PoolProvider
init(poolProvider: PoolProvider) {
self.poolProvider = poolProvider
}
private func single(from: TransactionRecord?, limit: Int, transactions: [TransactionRecord] = []) -> Single<[TransactionRecord]> {
// let extendedLimit = limit * 2
let extendedLimit = limit
return poolProvider.recordsSingle(from: from, limit: extendedLimit)
.flatMap { [weak self] newTransactions in
let allTransactions = transactions + newTransactions
let nonSpamTransactions = allTransactions.filter { !$0.spam }
if nonSpamTransactions.count >= limit || newTransactions.count < extendedLimit {
return Single.just(Array(nonSpamTransactions.prefix(limit)))
} else {
return self?.single(from: allTransactions.last, limit: limit, transactions: allTransactions) ?? Single.just([])
}
}
}
}
extension NonSpamPoolProvider {
var syncing: Bool {
poolProvider.syncing
}
var syncingObservable: Observable<Bool> {
poolProvider.syncingObservable
}
var lastBlockInfo: LastBlockInfo? {
poolProvider.lastBlockInfo
}
func recordsSingle(from: TransactionRecord?, limit: Int) -> Single<[TransactionRecord]> {
single(from: from, limit: limit)
}
func recordsObservable() -> Observable<[TransactionRecord]> {
poolProvider.recordsObservable()
.map { transactions in
transactions.filter { !$0.spam }
}
}
func lastBlockUpdatedObservable() -> Observable<Void> {
poolProvider.lastBlockUpdatedObservable()
}
}
|
//
// UserInfo.swift
// ios_mvvm
//
// Created by prongbang on 28/7/2561 BE.
// Copyright © 2561 prongbang. All rights reserved.
//
import Foundation
public class UserInfo: NSObject {
public static let instance = UserInfo()
var UID: String?
var token: String?
var name: String?
var phone: String?
}
|
// Omnia Mac Playground
import Cocoa
import Omnia
var str = "Hello, playground"
|
//
// Supercar.swift
// carAPI
//
// Created by Red Nguyen on 10/2/21.
//
import Foundation
struct superCarModel: Decodable {
public var supercarmodel:[carModel]
}
struct carModel: Decodable {
public var name: String
public var year: String
public var price: String
}
|
//
// ListPhotosViewControllerTests.swift
// unsplashTests
//
// Created by Dong-Wook Han on 2020/06/27.
// Copyright © 2020 kakaopay. All rights reserved.
//
import XCTest
@testable import unsplash
class ListPhotosViewControllerTests: XCTestCase {
private var unsplashService: UnsplashServiceStub!
private var viewController: ListPhotosViewController!
override func setUp() {
super.setUp()
self.unsplashService = UnsplashServiceStub()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let identifier = "ListPhotosViewController"
self.viewController = storyboard.instantiateViewController(withIdentifier: identifier) as? ListPhotosViewController
self.viewController.dependency = .init(unsplashService: self.unsplashService)
self.viewController.loadViewIfNeeded()
}
func testSearchBar_whenSearchBarSearchButtonClicked_searchWithText() {
// when
let searchBar = self.viewController.searchController.searchBar
searchBar.text = "UnsplashKit"
searchBar.delegate?.searchBarSearchButtonClicked?(searchBar)
// then
XCTAssertEqual(self.unsplashService.searchParameters?.keyword, "UnsplashKit")
}
func testActivityIndicatorView_sceenType_whileSearching() {
// when
let searchBar = self.viewController.searchController.searchBar
searchBar.text = "UnsplashKit"
searchBar.delegate?.searchBarSearchButtonClicked?(searchBar)
// then
XCTAssertEqual(self.viewController.currentSceenType,.search)
}
func testCloseButton_isHidden_whileSearching() {
// when
let searchBar = self.viewController.searchController.searchBar
searchBar.text = "UnsplashKit"
searchBar.delegate?.searchBarSearchButtonClicked?(searchBar)
// then
XCTAssertTrue(self.viewController.closeButton.isHidden)
}
// func testCollectionView_isVisible_afterSearching() {
// // given
// let searchBar = self.viewController.searchController.searchBar
// searchBar.text = "UnsplashKit"
// searchBar.delegate?.searchBarSearchButtonClicked?(searchBar)
//
// // when
// self.unsplashService.searchParameters?.completionHandler(.failure(TestError()))
//
// // then
// XCTAssertFalse(self.viewController.collectionView.isHidden)
// }
}
|
//
// ADRightMenuViewController.swift
// ADSideMenuSample
//
// Created by duanhongjin on 16/6/17.
// Copyright © 2016年 CrazyKids. All rights reserved.
//
import UIKit
class ADRightMenuViewController: UIViewController, UITableViewDataSource {
var tableView: UITableView?
let tableData = ["小明", "小红", "小兰", "小邓"]
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: view.bounds)
tableView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tableView?.dataSource = self
// tableView?.backgroundColor = UIColor.clearColor()
tableView?.tableFooterView = UIView(frame: CGRect.zero)
tableView?.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
view.addSubview(tableView!)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")!
cell.selectionStyle = .none
cell.textLabel?.text = tableData[indexPath.row]
cell.textLabel?.textAlignment = .right
return cell
}
}
|
//
// main.swift
// Platon2
//
// Created by Alexey Ivankov on 18.03.17.
// Copyright © 2017 Alexey Ivankov. All rights reserved.
//
import Foundation
import UIKit
UIApplicationMain(
CommandLine.argc,
UnsafeMutableRawPointer(CommandLine.unsafeArgv)
.bindMemory(
to: UnsafeMutablePointer<Int8>.self,
capacity: Int(CommandLine.argc)),
NSStringFromClass(Application.self),
NSStringFromClass(AppDelegate.self)
)
|
//
// NumberExtensions.swift
// WeatherApp
//
// Created by Alvyn SILOU on 07/10/2018.
// Copyright © 2018 Alvyn SILOU. All rights reserved.
//
import UIKit
extension Int {
}
|
//
// Q39ViewController.swift
// LeetCode-Swift-master
//
// Created by shunlian on 3/6/20.
// Copyright © 2020 Lengain. All rights reserved.
//
import UIKit
class Q39ViewController: LNBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
print(self.combinationSum([2,3,5], 8))
}
func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
var result = [[Int]].init()
let sortedNums = candidates.sorted()
self.search(candidates: sortedNums, target: target, limit: target) { (value) in
result.append(value)
}
return result
}
func search(candidates: [Int], target: Int, limit:(Int), callBack:(([Int]) -> ())) {
for i in 0 ..< candidates.count {
if candidates[i] <= target {
//去重 剪枝
//首先,程序执行减操作的时候,是排序后的,从小往大减的。
//limit为上一次循环中减去的这个值。如果当前循环的值candidates[i]这个值比大,说明上面一层已经减过了,会重复。直接return
if (limit < candidates[i]) {
return
}
let diff = target - candidates[i]
if diff > 0 {
self.search(candidates: candidates, target: diff, limit: candidates[i]) { (value) in
var values = [Int].init()
values.append(contentsOf: value)
values.append(candidates[i])
callBack(values)
}
}else if diff == 0 {
callBack([candidates[i]])
}
}
}
}
/*
// 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.
}
*/
}
|
//
// IAPProductType.swift
// ADGAP
//
// Created by Jitendra Kumar on 24/06/20.
// Copyright © 2020 Jitendra Kumar. All rights reserved.
//
import Foundation
import UIKit
import SwiftyStoreKit
enum IAPProductType:String,Hashable,Mappable {
case monthly = "ADGAP001"
var identifier:String{
return self.rawValue
}
var subscriptionType:SubscriptionType{
switch self {
case .monthly: return .autoRenewable
}
}
}
|
//
// CategoryTableViewController.swift
// Todoey
//
// Created by FGT MAC on 1/1/20.
// Copyright © 2020 App Brewery. All rights reserved.
//
import UIKit
import RealmSwift
import ChameleonFramework
class CategoryViewController: SwipeTableViewController {
//Initialize Realm
let realm = try! Realm()
//Creating array of [Category]()
var categoryArray: Results<Category>!
override func viewDidLoad() {
super.viewDidLoad()
//change the high of the cells for the icon to show correctly
tableView.rowHeight = 70.0
//Load current items in DB
loadCat()
//Remove the separator lines between cells
tableView.separatorStyle = .none
}
//SET INITIAL NAV BACKGROUND COLOR TO BLUE
override func viewWillAppear(_ animated: Bool) {
guard let navBar = navigationController?.navigationBar else {
fatalError("Navigation Controller does not exist")
}
//Extend the color to the safe area
let navBarAppearance = UINavigationBarAppearance()
navBarAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
navBarAppearance.backgroundColor = UIColor(hexString: "1D9BF6")
navBar.scrollEdgeAppearance = navBarAppearance
//Set the background to blue
// navBar.backgroundColor = UIColor(hexString: "1D9BF6")
//Set title letters to white
// navBar.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white]
}
//MARK: - TableView Data source Methods
//Set the number of rows
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//Count how many itmes are in the array to create a row for each
//But since is an optiona it could be nill so if is nil we would return 1
return categoryArray?.count ?? 1
}
//Create reusable cells with data
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//Creating Reusable cell
//let cell = tableView.dequeueReusableCell(withIdentifier: "CategoryCell", for: indexPath)
let cell = super.tableView(tableView, cellForRowAt: indexPath)
if let category = categoryArray?[indexPath.row] {
//iterate through array to Provide text for the cells
// since categoryArray is optional we will provide a default string if categoryArray is nil
cell.textLabel?.text = category.name
guard let categoryColor = UIColor(hexString: category.color) else {fatalError("Invalid cat color!")}
//cell background
cell.backgroundColor = categoryColor
//contras text color in each string cell
cell.textLabel?.textColor = ContrastColorOf(categoryColor, returnFlat: true)
}
return cell
}
//MARK: - Add New Category
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
//initializing a new text field object
var textField = UITextField()
//Create pop up alert with a title
let alert = UIAlertController(title: "Add New Category", message: "", preferredStyle: .alert)
//creating input field inside the popup
let action = UIAlertAction(title: "Add", style: .default) { (action) in
//initiating a new item
let newCat = Category()
//get the input text to equal the new cat
newCat.name = textField.text!
//Creating a random color
newCat.color = UIColor.randomFlat().hexValue()
// newCat.color = UIColor(randomFlatColorOf:.light).hexValue()
//call saveCat to save current context to DB
self.save(category: newCat)
}
//call method to add the textfield
alert.addTextField { (alertTextField) in
//create placeholder
alertTextField.placeholder = "Create new Category"
textField = alertTextField
//Capitalized first letter
textField.autocapitalizationType = .words
}
//add the action to the alert
alert.addAction(action)
//present the alert
present(alert, animated: true, completion: nil)
}
//MARK: - Data Manipulation Methods
//Saving data from Context to DB
func save(category: Category) {
do {
try realm.write {
realm.add(category)
}
} catch {
print("Error saving contect. \(error)")
}
//reload table to update content
tableView.reloadData()
}
func loadCat() {
categoryArray = realm.objects(Category.self)
//reload table to update content
tableView.reloadData()
}
//DELETE
override func updateModel(at indexPath: IndexPath) {
if let item = self.categoryArray?[indexPath.row] {
do {
try self.realm.write {
self.realm.delete(item)
}
}catch {
print("Error deleting \(error)")
}
}
}
//MARK: - TableView Delegate Methods
//When user click on a cell this will be trigger
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//Creating redirect to take user to another view
performSegue(withIdentifier: "goToItems", sender: self)
}
//Here we prepare before display the next view
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//getting hold of the destination / next view and downcasted as TodoListViewController
//because we already known which is the view controller
//If we would have a few different view then we could do an if statment on what to do on each
let destinationVC = segue.destination as! TodoListViewController
//identify the current selected row
if let indexPath = tableView.indexPathForSelectedRow {
//set a property inside the destinationVC to the selected row
//the selectedCategory must be created in the corresponding view to get the value
destinationVC.selectedCategory = categoryArray?[indexPath.row]
}
}
}
|
//
// UIView+Nib.swift
// Zendo
//
// Created by Anton Pavlov on 07/08/2018.
// Copyright © 2018 zenbf. All rights reserved.
//
import UIKit
extension UIView {
static var xibName: String {
return String(describing: classForCoder())
}
static var nib: UINib{
return UINib(nibName: self.xibName, bundle: nil)
}
/// Load self view from xib. Owner of the xib should be empty, xib's type
/// should be self.
static func loadFromNib() -> UIView? {
return UINib(nibName: xibName, bundle: Bundle(for: classForCoder())).instantiate(withOwner: nil, options: nil).first as? UIView
}
/// Add view from xib as subview. Owner of the xib shuold be self.
func loadNib() {
let view = UINib(nibName: String(describing: classForCoder), bundle: Bundle(for: self.classForCoder)).instantiate(withOwner: self, options: nil).first as! UIView
addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
view.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
view.topAnchor.constraint(equalTo: topAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.