text stringlengths 8 1.32M |
|---|
import Domain
import RxSwift
import Moya
public final class RepositoryUseCase: Domain.RepositoryUseCase {
private let network: Networking
public init(network: Networking) {
self.network = network
}
public func repository(apiUrl: String) -> Observable<Domain.Repository> {
return network.request(.custom(url: apiUrl, method: .get))
.filterAPIError()
.map(to: Repository.self)
}
public func readme(owner: String, repo: String) -> Observable<Domain.ReadMe> {
return network.requestNoFilter(.readme(owner: owner, repo: repo))
.filterAPIError()
.map(to: ReadMe.self)
}
} |
//
// courseCell.swift
// QuizMe
//
// Created by Samuel Kudadji on 4/13/17.
// Copyright © 2017 Samuel Kudadji. All rights reserved.
//
import UIKit
class courseCell: UICollectionViewCell {
var nameBel = OldLabel()
var scorebel = UILabel()
var rounder = UIView()
required init(coder decoder: NSCoder) {
super.init(coder: decoder)!
}
override func layoutSubviews() {
rounder.frame = CGRect.init(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height * 0.98)
// rounder.backgroundColor = newColors()
rounder.layer.cornerRadius = 10
rounder.clipsToBounds = true
nameBel.frame = CGRect.init(x: 0, y: 0, width: self.bounds.width , height: self.bounds.height * 0.7 )
nameBel.backgroundColor = UIColor(red: 14.0/255.0, green: 179.0/255.0, blue: 201.0/255.0, alpha: 1.0)
//UIColor.init(red: 255/255, green: 255/255, blue: 255/255, alpha: 1.0)
// nameBel.textColor = UIColor.darkGray
// nameBel.font = UIFont(name: "AvenirNext-Bold", size: 15)
nameBel.numberOfLines = 4
nameBel.textAlignment = .center
// nameBel.layer.cornerRadius = 10
nameBel.clipsToBounds = true
scorebel.frame = CGRect.init(x: 0, y: self.bounds.height * 0.7, width: self.bounds.width, height: self.bounds.height * 0.3 )
scorebel.backgroundColor = UIColor.init(red: 197/255, green: 59/255, blue: 62/255, alpha: 1.0)
scorebel.textColor = UIColor.init(red: 255/255, green: 255/255, blue: 255/255, alpha: 0.6)
scorebel.font = UIFont(name: "AvenirNext-Bold", size: 13)
scorebel.numberOfLines = 1
scorebel.textAlignment = .center
// scorebel.layer.cornerRadius = 10
scorebel.clipsToBounds = true
self.contentView.addSubview(rounder)
self.rounder.addSubview(nameBel)
self.rounder.addSubview(scorebel)
}
}
|
//
// settings.swift
// iQuiz
//
// Created by Just on 16/11/3.
// Copyright © 2016年 Just. All rights reserved.
//
import UIKit
class settings: UIBarButtonItem {
}
|
//
// DocumentView.swift
// Syntax_SwiftUI
//
// Created by Joey
//
import SwiftUI
struct DocumentView: View {
@State var document: Document
@State var lexer: Lexer = SwiftLexer(DarkTheme())
var dismiss: () -> Void
var body: some View {
ZStack {
HStack {
SyntaxTextView(document: $document, lexer: $lexer)
}
VStack {
Spacer()
Button("Done", action: dismiss)
}
}
}
}
|
//
// NoteDetailController.swift
// one-note
//
// Created by 杜哲 on 2018/9/10.
// Copyright © 2018年 duzhe. All rights reserved.
//
import UIKit
import RealmSwift
class NoteDetailController: UIViewController {
@IBOutlet private var closeButton: UIButton!
@IBOutlet private var tableView: UITableView!
@IBOutlet private var bottomView: UIView!
@IBOutlet private var downloadButton: UIButton!
@IBOutlet private var editButton: UIButton!
@IBOutlet private var bottomConstraint: NSLayoutConstraint!
fileprivate var _token: NotificationToken?
enum RowType{
case head,content
}
var items: [RowType] = [.head,.content]
var lastOffset: CGPoint = .zero
var isBottomAnimating = false
var isBottomShowing = false
let note: Note
init(note: Note) {
self.note = note
super.init(nibName: "NoteDetailController", bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupGesture()
}
deinit {
_token?.invalidate()
}
}
// MARK: - setup
extension NoteDetailController: Gestureable {
func setup(){
view.backgroundColor = UIColor.white
closeButton.style(.add)
closeButton.transform = CGAffineTransform.identity.rotated(by: CGFloat(Double.pi/4))
closeButton.hero.id = HeroID.close
bottomView.backgroundColor = UIColor.clear
bottomView.hero.modifiers = [ .translate(x: 0, y: 40, z: 0) ]
hero.isEnabled = true
tableView.basicsConfig()
tableView.separatorStyle = .none
tableView.easyRegisterNib(DetailHeadCell.self)
tableView.easyRegisterNib(DetailContentCell.self)
tableView.dataSource = self
tableView.delegate = self
// tableView.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "pattern"))
// view.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "pattern"))
tableView.contentInset = UIEdgeInsets(top: 90, left: 0, bottom: 40, right: 0)
downloadButton.addTarget(self, action: #selector(download), for: .touchUpInside)
editButton.addTarget(self, action: #selector(edit), for: .touchUpInside)
setupObserver()
}
func setupObserver(){
_token = note.observe({ [weak self] (change) in
switch change{
case .change:
self?.tableView.reloadData()
default:break
}
})
}
}
// MARK: - operaters
extension NoteDetailController {
@objc func download(){
// 截图tableview
let image = tableView.createImage()
// 保存到相册
UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
// 将图片保存到相册
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
print(error.localizedDescription)
} else {
let ac = UIAlertController(title: "保存成功!", message: "", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "确定", style: .default))
present(ac, animated: true)
}
}
@objc func edit(){
let controller = AddNoteController(pageType: .edit(note))
present(controller, animated: true, completion: nil)
}
}
// MARK: - UITableViewDataSource
extension NoteDetailController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch items[indexPath.row] {
case .head:
let cell = tableView.easyDequeueReusableCell(forIndexPath: indexPath) as DetailHeadCell
cell.configWith(self.note)
return cell
case .content:
let cell = tableView.easyDequeueReusableCell(forIndexPath: indexPath) as DetailContentCell
cell.configWith(self.note)
return cell
}
}
}
// MARK: - UITableViewDelegate
extension NoteDetailController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch items[indexPath.row] {
case .head:
return 100
case .content:
return UITableViewAutomaticDimension
}
}
}
// MARK: - bottomview handler
extension NoteDetailController {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y > self.lastOffset.y{
// 向下滑动 隐藏
hideBottom()
} else if scrollView.contentOffset.y < self.lastOffset.y{
// 向上滑动 显示
showBottom()
}
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.lastOffset = scrollView.contentOffset
}
func showBottom(){
guard !isBottomShowing && !isBottomAnimating else { return }
isBottomAnimating = true
bottomConstraint.constant = 0
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
}) { _ in
self.isBottomShowing = true
self.isBottomAnimating = false
}
}
func hideBottom(){
guard isBottomShowing && !isBottomAnimating else { return }
isBottomAnimating = true
bottomConstraint.constant = -40
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
}) { _ in
self.isBottomShowing = false
self.isBottomAnimating = false
}
}
}
|
//
// MainScene+PhysicsContact.swift
// gloop-drop
//
// Created by Fernando Fernandes on 17.11.20.
//
import SpriteKit
extension MainScene: SKPhysicsContactDelegate {
func didBegin(_ contact: SKPhysicsContact) {
let collision = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
switch collision {
case PhysicsCategory.player.rawValue | PhysicsCategory.collectible.rawValue:
GloopDropApp.log("Player hit collectible", category: .collision)
handle(contact: contact, isCollectibleCollected: true)
case PhysicsCategory.floor.rawValue | PhysicsCategory.collectible.rawValue:
GloopDropApp.log("Collectible hit the floor", category: .collision)
handle(contact: contact, isCollectibleCollected: false)
default:
break
}
}
}
// MARK: - Private
private extension MainScene {
func handle(contact: SKPhysicsContact, isCollectibleCollected: Bool) {
// Find out which body is attached to the collectible node.
let body = (contact.bodyA.categoryBitMask == PhysicsCategory.collectible.rawValue) ?
contact.bodyA.node :
contact.bodyB.node
// Verify the object is a collectible.
if let collectible = body as? Collectible {
if isCollectibleCollected {
collectible.collected()
dropsCollected += 1
score += level
checkForRemainingDrops()
addChompLabel()
} else {
collectible.missed()
gameOver()
}
}
}
}
|
//
// ViewController.swift
// PlayingCard
//
// Created by Ivan De Martino on 8/29/20.
// Copyright © 2020 Ivan De Martino. All rights reserved.
//
import UIKit
class CardDetailViewController: UIViewController {
var deck = PlayingCardDeck()
@IBAction func flipCard(_ sender: UITapGestureRecognizer) {
switch sender.state {
case .ended:
playingCardView.isFaceUp.toggle()
default:
break
}
}
@IBOutlet weak var playingCardView: PlayingCardView! {
didSet {
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(nextCard))
swipe.direction = [.left, .right]
playingCardView.addGestureRecognizer(swipe)
let pinch = UIPinchGestureRecognizer(target: playingCardView, action: #selector(PlayingCardView.adjustFaceCardScale(byHandlingGestureRecognizerBy:)))
playingCardView.addGestureRecognizer(pinch)
}
}
@objc func nextCard() {
if let card = deck.draw() {
playingCardView.rank = card.rank.order
playingCardView.suit = card.suit.rawValue
}
}
}
|
//
// NoteThat : GenricTableVC.swift by Tymek on 05/10/2020 15:39.
// Copyright ©Tymek 2020. All rights reserved.
import UIKit
import SwipeCellKit
import ChameleonFramework
class GenricTableVC: UITableViewController, SwipeTableViewCellDelegate {
override func viewDidLoad() {
super.viewDidLoad()
tableView.separatorStyle = .none
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! SwipeTableViewCell
cell.delegate = self
return cell
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
guard orientation == .right else { return nil }
let deleteAction = SwipeAction(style: .destructive, title: "Delete") { action, indexPath in
self.removeElement(at: indexPath)
}
// customize the action appearance
deleteAction.image = UIImage(named: "delete")
return [deleteAction]
}
func removeElement(at indexPath: IndexPath) {
print("Element: \(indexPath.row) has been removed.")
}
}
|
//
// FirstVC.swift
// procon-proj
//
// Created by 伊東佑真 on 2020/06/15.
// Copyright © 2020 伊東佑真. All rights reserved.
//
import UIKit
import Firebase
import FirebaseFirestore
class DocumentOnlineListVC: UIViewController,UITableViewDataSource,UITableViewDelegate{
var userInfos:[String:SimpleUserInfo] = [:]
var dataArray:[DataForOnlineList] = []
@IBOutlet weak var tableView: UITableView!
private let refreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
tableView.refreshControl = refreshControl
refreshControl.addTarget(self, action: #selector(self.updateListCall(_:)), for: .valueChanged)
}
var count:Int = 0
func updateList(){
count += 1
print("update"+String(count))
userInfos = [:]
dataArray = []
let dispatchGroup = DispatchGroup()
let dispatchQueue = DispatchQueue(label: "queue")
let db = Firestore.firestore()
let docRef = db.collection("documents")
let userRef = db.collection("userInfos")
dispatchGroup.enter()
dispatchQueue.async(group: dispatchGroup){
print("read user ref start")
var isTaskFinished = false
userRef.getDocuments(){(querySnapShot,error) in
if let error = error {
print("error when getting document from online database : \(error)")
} else{
for document in querySnapShot!.documents{
let user_uid = document.documentID
let data = document.data()
if let name = data["name"] as? String,let email = data["email"] as? String{
// print(name)
// print(email)
let userInfo = SimpleUserInfo(name: name, email: email)
self.userInfos[user_uid] = userInfo
}
}
isTaskFinished = true
}
}
while !isTaskFinished{
// print("not finished1")
}
dispatchGroup.leave()
print("read user ref finished")
}
dispatchGroup.enter()
dispatchQueue.async(group: dispatchGroup){
print("read doc ref start")
var isTaskFinished = false
docRef.getDocuments(){(querySnapShot,error) in
if let error = error {
print("error when getting document from online database : \(error)")
} else{
for document in querySnapShot!.documents{
let user_uid = document.documentID
let data = document.data()
// print(user_uid)
for val in data.values{
if let docData = val as? Data{
if let docInfo = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(docData) as? DocumentInfo {
let onlineListData:DataForOnlineList = DataForOnlineList(document: docInfo, user: self.userInfos[user_uid]!)
self.dataArray.append(onlineListData)
}
}
}
}
isTaskFinished = true
}
}
while !isTaskFinished{
// print("not finished2")
}
dispatchGroup.leave()
print("read doc ref finished")
}
dispatchGroup.notify(queue: .main){
print("all complete")
for data in self.dataArray{
let doc = data.document
let user = data.user
/*
print(doc.explain ?? "nil")
print(user.name)
print(user.email)
*/
}
self.tableView.reloadData()
self.refreshControl.endRefreshing()
}
print("update finish"+String(count))
}
@objc func updateListCall(_ sender:UIRefreshControl){
updateList()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "docListCell", for: indexPath)
assert(indexPath.row < dataArray.count, "index is out of range uid array")
let data = dataArray[indexPath.row]
let docInfo:DocumentInfo = data.document
let userInfo:SimpleUserInfo = data.user
let name = cell.viewWithTag(1) as! UILabel
name.text = userInfo.name
let email = cell.viewWithTag(2) as! UILabel
email.text = userInfo.email
let title = cell.viewWithTag(3) as! UILabel
title.text = docInfo.explain
let savedDate = cell.viewWithTag(4) as! UILabel
savedDate.text = docInfo.savedDate
let context = cell.viewWithTag(5) as! UITextView
context.text = docInfo.context
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 300
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("select")
assert(indexPath.row < dataArray.count, "index is out of range uid array")
let docInfo:DocumentInfo = dataArray[indexPath.row].document
let userInfo:SimpleUserInfo = dataArray[indexPath.row].user
let message = userInfo.name + "\n" + userInfo.email + "\n" + String(describing: docInfo.explain) + "\n" + String(describing: docInfo.savedDate)
let alertController = UIAlertController(title:"確認メッセージ",message: message,preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "戻る", style: .default, handler: {action in print("back")})
let okAction = UIAlertAction(title: "問題を解く", style: .default, handler: {action in
print("go")
let questionScene = self.storyboard?.instantiateViewController(identifier: "QuestionSceneVC") as! QuestionSceneVC
questionScene.modalPresentationStyle = .fullScreen
self.present(questionScene,animated: true,completion: nil)
})
alertController.addAction(cancelAction)
alertController.addAction(okAction)
self.present(alertController,animated: true,completion: nil)
}
}
struct DataForOnlineList{
var document:DocumentInfo
var user:SimpleUserInfo
}
struct SimpleUserInfo{
var name:String
var email:String
}
|
//
// GreetingViewModel.swift
// Architectures
//
// Created by jiangbin on 16/3/28.
// Copyright © 2016年 lechange. All rights reserved.
//
class GreetingViewModel : GreetingViewModelProtocol {
let person: MMPerson
var greeting: String? {
didSet {
self.greetingDidChange?(self)
}
}
var greetingDidChange: ((GreetingViewModelProtocol) -> ())?
required init(person: MMPerson) {
self.person = person
}
func showGreeting() {
self.greeting = "Hello" + " " + self.person.firstName + " " + self.person.lastName
}
} |
//
// ViewController.swift
// CelebMedia
//
// Created by Gabriella Smith on 11/16/19.
// Copyright © 2019 Gabriella Smith. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var tableView: UITableView!
var artistCountLabel: UILabel!
let rightBarButtonItem = UIBarButtonItem()
let reuseIdentifier = "celebrityCellReuse"
let cellWidth: CGFloat = 379
let cellHeight: CGFloat = 74
var celebrities: [Celebrity]!
override func viewDidLoad() {
super.viewDidLoad()
title = "AppName"
view.backgroundColor = .white
let bts = Celebrity(name: "BTS", profile: "bts")
let ariana = Celebrity(name: "Ariana Grande", profile: "ari")
let halsey = Celebrity(name: "Halsey", profile: "halsey")
celebrities = [bts, ariana, halsey]
tableView = UITableView()
//tableView.delegate = self
tableView.separatorStyle = .none
tableView.backgroundColor = .white
tableView.rowHeight = 104
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.dataSource = self
tableView.register(CelebrityTableViewCell.self, forCellReuseIdentifier: reuseIdentifier)
let headerView = ArtistHeader(frame: .init(x: 0, y: 0, width: cellWidth, height: 98))
tableView.tableHeaderView = headerView
headerView.artistCountLabel.text = "You have added " + String(celebrities.count) + " artist(s)."
view.addSubview(tableView)
rightBarButtonItem.title = "+"
rightBarButtonItem.style = .plain
rightBarButtonItem.tintColor = .black
rightBarButtonItem.target = self
rightBarButtonItem.action = #selector(pushAddViewController)
navigationItem.rightBarButtonItems = [rightBarButtonItem]
setupConstraints()
}
@objc func pushAddViewController() {
let viewController = AddViewController()
// viewController.delegate = self
navigationController?.pushViewController(viewController, animated: true)
}
func setupConstraints() {
NSLayoutConstraint.activate([
tableView.widthAnchor.constraint(equalToConstant: cellWidth + 10),
tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 17),
tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 8),
])
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return celebrities.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! CelebrityTableViewCell
let celeb = celebrities[indexPath.row]
cell.configure(for: celeb)
cell.selectionStyle = .none
return cell
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return cellHeight
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! CelebrityTableViewCell
let viewController = ArtistViewController(cells: cell)
// viewController.delegate = self
present(viewController, animated: true, completion: nil)
}
// func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// let cell = tableView.cellForRow(at: indexPath) as! PlaylistTableViewCell
// let index = indexPath.row
// let viewController = DetailViewController(songTextFieldtext: cell.songLabel.text!
// , artistTextFieldtext: cell.artistLabel.text!, albumTextFieldtext: cell.albumLabel.text!, index: index)
// viewController.delegate = self
//
// present(viewController, animated: true, completion: nil)
}
// func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// let celeb = celebrities[indexPath.row]
// let viewController = SongViewController(song: song)
// navigationController?.pushViewController(viewController, animated: true)
// viewController.delegate = self
// }
|
//
// AuthenticationDelegate.swift
// SimpleLoginLogoutAPI
//
// Created by Lainel John Dela Cruz on 11/10/2018.
// Copyright © 2018 Lainel John Dela Cruz. All rights reserved.
//
import Foundation
protocol AuthenticationDelegate{
func errorMessage(message:String?)
}
|
//
// newInfoData.swift
// alinaNutrisport
//
// Created by Brandon Gonzalez on 28/07/20.
// Copyright © 2020 Easycode. All rights reserved.
//
import UIKit
class newInfoData: UIViewController {
let UserID = UserDefaults.standard.string(forKey: "IDUser")
//Main Section
@IBOutlet weak var pesoTF: UITextField!
@IBOutlet weak var alturaTF: UITextField!
@IBOutlet weak var pGrasaTF: UITextField!
@IBOutlet weak var musculoKGTF: UITextField!
@IBOutlet weak var pAguaTF: UITextField!
//Second Section
@IBOutlet weak var masaOseaGKTF: UITextField!
@IBOutlet weak var pesoTresAñosTF: UITextField!
@IBOutlet weak var grasaVisceralTF: UITextField!
@IBOutlet weak var metabolismoBasal: UITextField!
@IBOutlet weak var evaluacionFisica: UITextField!
@IBOutlet weak var edadMetabolica: UITextField!
@IBOutlet weak var pesoEsperado: UITextField!
//Third Section
@IBOutlet weak var tricepsTF: UITextField!
@IBOutlet weak var bicepsTF: UITextField!
@IBOutlet weak var abdominalTF: UITextField!
@IBOutlet weak var pantorrilaTF: UITextField!
@IBOutlet weak var subaescapularTF: UITextField!
@IBOutlet weak var suprailiacoTF: UITextField!
@IBOutlet weak var musloTF: UITextField!
@IBOutlet weak var sexImage: UIImageView!
//Fourth Section
@IBOutlet weak var cinturaTF: UITextField!
@IBOutlet weak var abdomenTF: UITextField!
@IBOutlet weak var caderaTF: UITextField!
@IBOutlet weak var brazoRelajadoTF: UITextField!
@IBOutlet weak var muñecaTF: UITextField!
@IBOutlet weak var tobilloTF: UITextField!
@IBOutlet weak var pantorrilla2TF: UITextField!
@IBOutlet weak var muslo2: UITextField!
@IBOutlet weak var antebrazo2TF: UITextField!
@IBOutlet weak var pecho: UITextField!
@IBOutlet weak var comentariosTF: UITextField!
//Button
@IBOutlet weak var sendInfoButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
getInfo()
}
func setupView() {
sendInfoButton.layer.cornerRadius = 14
}
func getInfo() {
let url = URL(string: http.baseURL())!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") // Headers
request.httpMethod = "POST" // Metodo
let postString = "funcion=getLastTracking&id_user="+UserID!
print(postString)
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
let msrmnts = try? JSONDecoder().decode(updatedSepUserMeasurements.self, from: data)
DispatchQueue.main.async {
if msrmnts?.data?.info?.sexo == "1" {
self.sexImage.image = UIImage(named: "medias_alina_hombre")
}
if msrmnts?.data?.info?.sexo == "2" {
self.sexImage.image = UIImage(named: "medias_alina_mujer")
}
self.pesoTF.text = msrmnts?.data?.info?.peso
self.alturaTF.text = msrmnts?.data?.info?.altura
self.pGrasaTF.text = msrmnts?.data?.info?.pGrasa
self.musculoKGTF.text = msrmnts?.data?.info?.pMusculo
self.pAguaTF.text = msrmnts?.data?.info?.pAgua
self.masaOseaGKTF.text = msrmnts?.data?.info?.pAgua
self.pesoTresAñosTF.text = msrmnts?.data?.info?.mejorPeso
self.grasaVisceralTF.text = msrmnts?.data?.info?.grasaVisceral
self.metabolismoBasal.text = msrmnts?.data?.info?.metabolismoBasal
self.evaluacionFisica.text = msrmnts?.data?.info?.evFisica
self.edadMetabolica.text = msrmnts?.data?.info?.edadMetabolica
self.pesoEsperado.text = msrmnts?.data?.info?.pesoEsperado
self.cinturaTF.text = msrmnts?.data?.info?.cinturaPerimetro
self.abdomenTF.text = msrmnts?.data?.info?.abdomenPerimetro
self.caderaTF.text = msrmnts?.data?.info?.cinturaPerimetro
self.brazoRelajadoTF.text = msrmnts?.data?.info?.brazoRelajadoPerimetro
self.muñecaTF.text = msrmnts?.data?.info?.muniecaPerimetro
self.tobilloTF.text = msrmnts?.data?.info?.tobilloPerimetro
self.muslo2.text = msrmnts?.data?.info?.musloPerimetro
self.pantorrilla2TF.text = msrmnts?.data?.info?.pantorrillaPerimetro
self.antebrazo2TF.text = msrmnts?.data?.info?.antebrazoPerimetro
self.pecho.text = msrmnts?.data?.info?.pechoPerimetro
self.comentariosTF.text = msrmnts?.data?.info?.comment
}
}
}
task.resume()
}
}
|
//
// DetailsWorker.swift
// MovieApp
//
// Created by Ahmad Aulia Noorhakim on 27/02/21.
//
import Alamofire
import Combine
import Foundation
protocol DetailsWorkerProtocol {
func fetchCredits(movieId id: Int) -> AnyPublisher<Details.Response, AFError>
}
final class DetailsWorker: DetailsWorkerProtocol {
func fetchCredits(movieId id: Int) -> AnyPublisher<Details.Response, AFError> {
return ApiRouter.request(ApiRoute.TMDB.credits(id), ofType: Details.Response.self)
}
}
|
//
// LoginViewModel.swift
// GetReactive
//
// Created by Andreas Kompanez on 21.01.21.
//
import Foundation
// MARK: -
// MARK: LoginViewModelType
protocol LoginViewModelType: ViewModelType {
var username: String { get set }
var password: String { get set }
var isLoginAllowed: Bool { get }
typealias LoginCallbackType = (Bool) -> Void
var canLoginCallback: (LoginCallbackType)? { get set }
func attemptLogin() -> Result<Bool, LoginError>
}
// MARK: -
// MARK: LoginViewModel implementation
final class LoginViewModel: LoginViewModelType {
let tabBarTitle = "MVVM"
let tabBarImageName = "fruit-grapes"
let navigationTitle = "🍊 Fruit Inc. Login"
var canLoginCallback: ((Bool) -> Void)?
var isLoginAllowed: Bool {
return checkIfLoginIsAllowed()
}
var username = "" {
didSet {
evaluateLoginState()
}
}
var password = "" {
didSet {
evaluateLoginState()
}
}
func attemptLogin() -> Result<Bool, LoginError> {
return .success(true)
}
// MARK: -
// MARK: Private methods
private func evaluateLoginState() {
let valid = checkIfLoginIsAllowed()
canLoginCallback?(valid)
}
private func checkIfLoginIsAllowed() -> Bool {
return !username.isEmpty && !password.isEmpty
}
}
|
//
// Account.swift
// Instagram_withStoryBoard
//
// Created by My iMac on 11/22/18.
// Copyright © 2018 My iMac. All rights reserved.
//
import UIKit
class Account: UIViewController {
var mPost: [Posts] = []
@IBOutlet var collectionView: UICollectionView!
@IBAction func displayAllUserButton(_ sender: Any) {
}
@IBAction func logoutButton(_ sender: Any) {
Api.auth.signOut(onFail: { (error) in
CustomAlert.showError(withMessage: error)
}) {
self.dismiss(animated: true, completion: nil)
}
}
fileprivate func fetchPost() {
Api.myPost.getPostFromServer(completion: { (post) in
self.mPost.append(post)
self.collectionView.reloadData()
})
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
collectionView.delegate = self
fetchPost()
}
}
extension Account: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return mPost.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! ImageCell
let post = mPost[indexPath.row]
cell.post = post
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerViewCell = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HeaderProfile", for: indexPath) as! HeaderProfileCollectionReusableView
headerViewCell.updateView()
return headerViewCell
}
}
extension Account: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.width / 3 - 1 , height: collectionView.frame.width / 3 - 1)
}
}
|
//
// FISTriviaSpec.swift
// swift-LocationTrivia-Objects
//
// Created by Zachary Drossman on 10/14/14.
// Copyright (c) 2014 Zachary Drossman. All rights reserved.
//
import Quick
import Nimble
import swift_LocationTrivia_Objects
class FISTriviaSpec: QuickSpec {
override func spec() {
describe("FISTrivia") {
let trivia : FISTrivia = FISTrivia(content: "This is the content", likes: 0)
describe("properties") {
it("should have a content NSString property") {
trivia.content = "ASDF"
expect(trivia.content).to(equal("ASDF"))
}
it("should have a likes NSInteger property") {
trivia.likes=5;
expect(trivia.likes).to(equal(5))
}
}
describe("init(content:likes:) function") {
let initTrivia: FISTrivia = FISTrivia(content: "Joe is amazing", likes: 5)
it("Should initialize content correctly") {
expect(initTrivia.content).to(equal("Joe is amazing"))
}
it("Should initialize likes correctly") {
expect(initTrivia.likes).to(equal(5))
}
}
}
}
}
|
//
// LocationNagView.swift
// Schuylkill-App
//
// Created by Sam Hicks on 3/6/21.
//
import Combine
import Foundation
import SwiftUI
import UIKit
public struct LocationNagView: UIViewControllerRepresentable {
public typealias UIViewControllerType = LocationNagViewController
public func makeUIViewController(context: Context) -> UIViewControllerType {
LocationNagViewController()
}
public func updateUIViewController(_ uiViewController: LocationNagViewController, context: Context) {
}
}
struct LocationNagView_Previews: PreviewProvider {
static var previews: some View {
LocationNagView()
}
}
|
//
// HomeCell.swift
// Muve
//
// Created by Luan Nguyen on 2019-09-20.
// Copyright © 2019 Luan Nguyen. All rights reserved.
//
import Foundation
import UIKit
class HomeCell: UITableViewCell {
var amountOfRepsToDoForTodayLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.systemFont(ofSize: 30, weight: .heavy)
label.text = "10"
// label.textAlignment = .center
label.numberOfLines = 0
return label
}()
var excersieLabel = UILabel()
var timeLeftToFinishChallengeLabel: UILabel = {
let label = UILabel()
//DATE TEst
var currentDateTime = Date()
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .medium
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.systemFont(ofSize: 13, weight: .semibold)
label.text = "\(dateFormatter.string(from: currentDateTime)) left "
label.textAlignment = .center
label.numberOfLines = 0
return label
}()
var daysLeftLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.systemFont(ofSize: 13, weight: .semibold)
label.text = "DAY 1/60"
label.textAlignment = .center
label.numberOfLines = 0
return label
}()
var challengeCompletedButton: UIButton = {
let label = UIButton()
label.translatesAutoresizingMaskIntoConstraints = false
label.setTitle("I DID IT", for: .normal)
label.setTitleColor(.white, for: .normal)
label.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: .bold)
label.clipsToBounds = true
label.layer.cornerRadius = 10
label.backgroundColor = .purple
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addTheViews()
configureExLabel()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addTheViews() {
addSubview(excersieLabel)
addSubview(amountOfRepsToDoForTodayLabel)
addSubview(timeLeftToFinishChallengeLabel)
addSubview(challengeCompletedButton)
addSubview(daysLeftLabel)
setConstraints()
}
func configureExLabel () {
excersieLabel.translatesAutoresizingMaskIntoConstraints = false
excersieLabel.numberOfLines = 0
excersieLabel.adjustsFontSizeToFitWidth = true
excersieLabel.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
excersieLabel.text = "SQUATS"
}
func setConstraints() {
NSLayoutConstraint.activate([
amountOfRepsToDoForTodayLabel.topAnchor.constraint(equalTo: topAnchor, constant: 5),
amountOfRepsToDoForTodayLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 25),
amountOfRepsToDoForTodayLabel.heightAnchor.constraint(equalToConstant: 40),
])
NSLayoutConstraint.activate([
excersieLabel.topAnchor.constraint(equalTo: amountOfRepsToDoForTodayLabel.bottomAnchor, constant: 7.5),
excersieLabel.heightAnchor.constraint(equalToConstant: 20),
excersieLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 25)
])
NSLayoutConstraint.activate([
timeLeftToFinishChallengeLabel.topAnchor.constraint(equalTo: excersieLabel.bottomAnchor, constant: 7.5),
timeLeftToFinishChallengeLabel.heightAnchor.constraint(equalToConstant: 20),
timeLeftToFinishChallengeLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 25)
])
NSLayoutConstraint.activate([
daysLeftLabel.topAnchor.constraint(equalTo: timeLeftToFinishChallengeLabel.bottomAnchor, constant: 7.5),
daysLeftLabel.heightAnchor.constraint(equalToConstant: 20),
daysLeftLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 25),
daysLeftLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -5)])
NSLayoutConstraint.activate([
challengeCompletedButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20),
challengeCompletedButton.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -20),
challengeCompletedButton.heightAnchor.constraint(equalToConstant: 30),
challengeCompletedButton.widthAnchor.constraint(equalToConstant: 70)
])
}
}
|
//
// ApiRepository.swift
// UserDisplayer
//
// Created by Jeremi Kaczmarczyk on 05/02/2017.
// Copyright © 2017 Jeremi Kaczmarczyk. All rights reserved.
//
import Foundation
enum ApiError: Error {
case unknown
case network
case parse
}
class ApiRepository: EntityGateway {
// MARK: - EntityGateway
func getUsers(completion: @escaping (Result<[User], Error>) -> Void) {
get(.users) { result in
completion(result)
}
}
func getPosts(forUserId id: Int, completion: @escaping (Result<[Post], Error>) -> Void) {
get(.posts(userId: id)) { result in
completion(result)
}
}
// MARK: - Utility
private func get<T: JSONParsable>(_ endpoint: ApiEndpoint, completion: @escaping (Result<[T], Error>) -> Void) {
URLSession.shared.dataTask(with: endpoint.url) { data, response, error in
if let _ = error {
completion(.error(ApiError.network))
}
DispatchQueue.main.async {
do {
guard
let data = data,
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [JSONDictionary]
else {
completion(.error(ApiError.parse))
return
}
completion(.success(json.flatMap(T.fromJSON)))
} catch {
completion(.error(ApiError.parse))
}
}
}.resume()
}
}
|
//
// EV3CommandDefinitions.swift
// LEGOEV3OpenSourceControllerForSwift
//
// Created by 邓杰豪 on 2016/9/5.
// Copyright © 2016年 邓杰豪. All rights reserved.
//
//import UIKit
//
//class EV3CommandDefinitions: NSObject {
//
//}
enum EV3ParameterSize : Int {
case Byte = 0x81
case Int16 = 0x82
case Int32 = 0x83
case String = 0x84
}
enum EV3ReplyType : Int {
case Direct = 0x82
case System = 0x83
case DirectError = 0x04
case SystemError = 0x05
}
enum EV3OperationCode : Int {
case EV3OperationUIReadGetFirmware = 0x810a
case EV3OperationUIWriteLED = 0x821b
case EV3OperationUIButtonPressed = 0x8309
case EV3OperationUIDrawUpdate = 0x8400
case EV3OperationUIDrawClean = 0x8401
case EV3OperationUIDrawPixel = 0x8402
case EV3OperationUIDrawLine = 0x8403
case EV3OperationUIDrawCircle = 0x8404
case EV3OperationUIDrawText = 0x8405
case EV3OperationUIDrawFillRect = 0x8409
// case EV3OperationUIDrawRect = 0x8401
case EV3OperationUIDrawInverseRect = 0x8410
case EV3OperationUIDrawSelectFont = 0x8411
case EV3OperationUIDrawTopline = 0x8412
case EV3OperationUIDrawFillWindow = 0x8413
case EV3OperationUIDrawDotLIne = 0x8415
case EV3OperationUIDrawFillCircle = 0x8418
case EV3OperationUIDrawBmpFile = 0x841c
case EV3OperationSoundBreak = 0x9400
case EV3OperationSoundTone = 0x9401
case EV3OperationSoundPlay = 0x9402
case EV3OperationSoundRepeat = 0x9403
case EV3OperationSoundService = 0x9404
case EV3OperationInputDeviceGetTypeMode = 0x9905
case EV3OperationInputDeviceGetDeviceName = 0x9915
case EV3OperationInputDeviceGetModeName = 0x9916
case EV3OperationInputDeviceReadyPct = 0x991b
case EV3OperationInputDeviceReadyRaw = 0x991c
case EV3OperationInputDeviceReadySI = 0x991d
case EV3OperationInputDeviceClearAll = 0x990a
case EV3OperationInputDeviceClearChanges = 0x991a
case EV3OperationInputRead = 0x9a
case EV3OperationInputReadExt = 0x9e
case EV3OperationInputReadSI = 0x9d
case EV3OperationOutputStop = 0xa3
case EV3OperationOutputPower = 0xa4
case EV3OperationOutputSpeed = 0xa5
case EV3OperationOutputStart = 0xa6
case EV3OperationOutputPolarity = 0xa7
case EV3OperationOutputStepPower = 0xac
case EV3OperationOutputTimePower = 0xad
case EV3OperationOutputStepSpeed = 0xae
case EV3OperationOutputTimeSpeed = 0xaf
case EV3OperationOutputStepSync = 0xb0
case EV3OperationOutputTimeSync = 0xb1
case EV3OperationTest = 0xff
}
enum EV3CommandType : Int {
case DirectReply = 0x00
case DirectNoReply = 0x80
}
enum EV3SensorDataFormat : Int {
case Percent = 0x10
case Raw = 0x11
case SI = 0x12
}
enum EV3MotorPolarity : Int {
case Backward = -1
case Opposite = 0
case Forward = 1
}
enum EV3InputPort : Int {
case _1 = 0x00
case _2 = 0x01
case _3 = 0x02
case _4 = 0x03
case A = 0x10
case B = 0x11
case C = 0x12
case D = 0x13
}
enum EV3OutputPort : Int {
case A = 0x01
case B = 0x02
case C = 0x04
case D = 0x08
case EV3OutputAll = 0x0f
}
enum EV3SensorType : Int {
case LargeMotor = 0x07
case MediumMotor = 0x08
case TouchSensor = 0x10
case ColorSensor = 0x1d
case UltrasonicSensor = 0x1e
case GyroscopeSensor = 0x20
case InfraredSensor = 0x21
case Initializing = 0x7d
case Empty = 0x7e
case WrongPort = 0x7f
case Unknown = 0xff
}
enum EV3BrickButton : Int {
case None
case Up
case Enter
case Down
case Right
case Left
case Back
case Any
}
enum EV3LEDPattern : Int {
case Black
case Green
case Red
case Orange
case GreenFlash
case RedFlash
case OrangeFlash
case GreenPulse
case RedPulse
case OrangePulse
}
enum EV3ScreenColor : Int {
case Background
case Foreground
}
enum EV3FontType : Int {
case Small
case Medium
case Large
}
enum EV3TouchSensorMode : Int {
case Touch
case Bumps
}
enum EV3MotorMode : Int {
case Degrees
case Rotations
}
enum EV3ColorSensorMode : Int {
case Reflective
case Ambient
case Color
case ReflectiveRaw
case ReflectiveRGB
case Calibration
}
enum EV3UltrasonicSensorMode : Int {
case Centimeters
case Inches
case Listen
}
enum EV3GyroscopeSensorMode : Int {
case Angle
case Rate
case GyroCalibration = 0x04
}
enum EV3InfraredSensorMode : Int {
case Proximity
case Seek
case Remote
case RemoteA
case SAlt
case InfrCalibration
}
enum EV3ColorSensorColor : Int {
case Transparent
case BlackColor
case BlueColor
case GreenColor
case YellowColor
case RedColor
case WhiteColor
case BrownColor
} |
// swift-tools-version:5.1
import PackageDescription
let package = Package(
name: "SkeletonUI",
platforms: [
.iOS(.v13),
.tvOS(.v13),
.watchOS(.v6),
.macOS(.v10_15)
],
products: [
.library(
name: "SkeletonUI",
targets: ["SkeletonUI"]
)
],
dependencies: [
.package(url: "https://github.com/pointfreeco/swift-snapshot-testing", from: "1.11.1")
],
targets: [
.target(
name: "SkeletonUI"
),
.testTarget(
name: "SkeletonUISnapshotTests",
dependencies: ["SkeletonUI", "SnapshotTesting"]
),
.testTarget(
name: "SkeletonUIUnitTests",
dependencies: ["SkeletonUI"]
)
],
swiftLanguageVersions: [.v5]
)
|
import MapKit
extension ViewController: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
@objc func didDragMap(gestureRecognizer: UIGestureRecognizer) {
if (gestureRecognizer.state == UIGestureRecognizer.State.began) {
localizeMeButton.localizeMeState = .unlocalized
}
}
func setUpLocalizeMeButton() {
let mapDragRecognizer = UIPanGestureRecognizer(target: self, action: #selector(self.didDragMap(gestureRecognizer:)))
mapDragRecognizer.delegate = self
self.view.addGestureRecognizer(mapDragRecognizer)
localizeMeButton.listener = { [weak self] localizeMeState in
switch localizeMeState {
case .localized:
self?.localizeMeManager.stop()
self?.localizeMeManager.manager(for: .whenInUse, completion: { result in
if case let .Success(manager) = result {
manager.startUpdatingLocation(isHeadingEnabled: false) { [weak self] result in
if case let .Success(locationHeading) = result, let location = locationHeading.location {
self?.mapView.centerCamera(to: location)
}
}
}
})
case .unlocalized:
self?.localizeMeManager.stop()
case .navigated:
self?.localizeMeManager.stop()
self?.localizeMeManager.manager(for: .whenInUse, completion: { result in
if case let .Success(manager) = result {
manager.startUpdatingLocation(isHeadingEnabled: true) { [weak self] result in
if case let .Success(locationHeading) = result {
self?.mapView.centerCamera(to: locationHeading.location, heading: locationHeading.heading?.trueHeading)
}
}
}
})
}
}
}
}
|
//
// NewWalkTableViewController.swift
// att-hack
//
// Created by Cameron Moreau on 8/20/16.
// Copyright © 2016 Kolten. All rights reserved.
//
import UIKit
import MapKit
class NewWalkTableViewController: UITableViewController {
@IBAction func cancelPressed(sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func donePressed(sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var familySelectedLabel: UILabel!
var selectedCoord: CLLocationCoordinate2D?
var selectedZoom: Double?
var selectedUserIndexs = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.deselectRowAtIndexPath(indexPath, animated: 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?) {
if segue.identifier == "SelectLocationSegue" {
let vc = segue.destinationViewController as! SelectLocationViewController
vc.delegate = self
vc.startLocation = self.selectedCoord
vc.startZoom = self.selectedZoom
}
else if segue.identifier == "SelectUsersSegue" {
let vc = segue.destinationViewController as! SelectUserTableViewController
vc.delegate = self
vc.selectedIndexs = selectedUserIndexs
}
}
}
extension NewWalkTableViewController: SelectLocationDelegate {
func locationSelected(coord: CLLocationCoordinate2D, zoom: Double) {
self.selectedCoord = coord
self.selectedZoom = zoom
locationLabel.text = "(\(String(format: "%.4f", coord.latitude)), \(String(format: "%.4f", coord.longitude)))"
}
}
extension NewWalkTableViewController: SelectUsersDelegate {
func usersChanged(indexes: [Int]) {
self.selectedUserIndexs = indexes
familySelectedLabel.text = "\(indexes.count) Selected"
}
}
|
//
// TablePresenter.swift
// Auction
//
// Created by Raymond Law on 1/20/18.
// Copyright (c) 2018 Clean Swift LLC. 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
import RealmSwift
protocol TablePresentationLogic
{
func presentFetchedItems(response: Table.FetchObjects.Response)
func presentFetchedBuyers(response: Table.FetchObjects.Response)
func presentFetchedSellers(response: Table.FetchObjects.Response)
}
class TablePresenter: TablePresentationLogic
{
weak var viewController: TableDisplayLogic?
lazy var currencyFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
return formatter
}()
// MARK: Format items
func presentFetchedItems(response: Table.FetchObjects.Response)
{
if let objects = response.objects {
let displayedObjects = Array(objects).map { (object) -> DisplayedObject in
let item = object as! Item
return formatItem(item: item)
}
let viewModel = Table.FetchObjects.ViewModel(displayedObjects: displayedObjects)
viewController?.displayFetchedObjects(viewModel: viewModel)
}
}
private func formatItem(item: Item) -> Table.FetchObjects.ViewModel.DisplayedItem
{
let quantity = String(item.quantity)
let price = currencyFormatter.string(from: NSNumber(value: item.price))!
return Table.FetchObjects.ViewModel.DisplayedItem(name: item.name, quantity: quantity, price: price)
}
// MARK: Format buyers
func presentFetchedBuyers(response: Table.FetchObjects.Response)
{
if let objects = response.objects {
let displayedObjects = Array(objects).map { (object) -> DisplayedObject in
let buyer = object as! User
return formatBuyer(buyer: buyer)
}
let viewModel = Table.FetchObjects.ViewModel(displayedObjects: displayedObjects)
viewController?.displayFetchedObjects(viewModel: viewModel)
}
}
private func formatBuyer(buyer: User) -> Table.FetchObjects.ViewModel.DisplayedBuyer
{
return Table.FetchObjects.ViewModel.DisplayedBuyer(name: "\(buyer.name) - Buyer", email: buyer.email)
}
// MARK: Format sellers
func presentFetchedSellers(response: Table.FetchObjects.Response)
{
if let objects = response.objects {
let displayedObjects = Array(objects).map { (object) -> DisplayedObject in
let seller = object as! User
return formatSeller(seller: seller)
}
let viewModel = Table.FetchObjects.ViewModel(displayedObjects: displayedObjects)
viewController?.displayFetchedObjects(viewModel: viewModel)
}
}
private func formatSeller(seller: User) -> Table.FetchObjects.ViewModel.DisplayedSeller
{
return Table.FetchObjects.ViewModel.DisplayedSeller(name: "\(seller.name) - Seller", email: seller.email)
}
}
|
//
// MoodCommentCell.swift
// GardenCoceral
//
// Created by TongNa on 2018/3/30.
// Copyright © 2018年 tongna. All rights reserved.
//
import UIKit
import Reusable
class MoodCommentCell: UITableViewCell, Reusable {
var commentView = UIView()
var commentLabel = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
_ = commentView.then{
addSubview($0)
$0.snp.makeConstraints({ (m) in
m.left.equalTo(60)
m.right.equalTo(-15)
m.top.equalTo(0)
m.bottom.equalTo(0)
})
$0.backgroundColor = UIColor(hexString: "#ededed")
}
_ = commentLabel.then{
commentView.addSubview($0)
$0.snp.makeConstraints({ (m) in
m.left.equalTo(3)
m.right.equalTo(-3)
m.top.equalTo(3)
m.bottom.equalTo(-3)
})
$0.numberOfLines = 0
$0.font = UIFont.systemFont(ofSize: 13)
$0.textColor = UIColor(hexString: "#666")
}
}
func setData(_ model: String) {
commentLabel.text = model
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
import Foundation
import SwiftSyntax
let scriptPath = URL(fileURLWithPath: String(#file))
let codePath = scriptPath
.deletingLastPathComponent()
.deletingLastPathComponent()
.deletingLastPathComponent()
.appendingPathComponent("Resources/code.swift")
let sourceFile = try SyntaxTreeParser.parse(codePath)
let blocks = sourceFile.children.compactMap { $0 as? CodeBlockItemListSyntax }.first!
let block: CodeBlockItemSyntax = blocks.first!
let classDecl = block.children.compactMap { $0 as? ClassDeclSyntax }.first!
let funcDecl = classDecl.members.members.children.compactMap { $0 as? FunctionDeclSyntax }.first!
let funcSig = funcDecl.children.compactMap { $0 as? FunctionSignatureSyntax }.first!
let paramClause = funcSig.children.compactMap { $0 as? ParameterClauseSyntax }.first!
let params = paramClause.children.compactMap { $0 as? FunctionParameterListSyntax }.first!
let param0: FunctionParameterSyntax = params[0]
print(param0)
if let ellipsis = param0.ellipsis {
print("---ellipsis---")
print(type(of: ellipsis))
print(ellipsis)
print("---")
} else {
print("no ellipsis")
}
if let trailingComma = param0.trailingComma {
print("---trailing comma---")
print(type(of: trailingComma))
print(trailingComma)
print("---")
} else {
print("no trailing comma")
}
|
//
// iOS7StyleCalendar.swift
// Swift Examples
//
// Copyright (c) 2014 Telerik. All rights reserved.
//
import Foundation
class iOS7StyleCalendar:TKExamplesExampleViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type:UIButtonType.System)
button.setTitle("Tap to load iOS 7 style calendar", forState: UIControlState.Normal)
button.addTarget(self, action: #selector(iOS7StyleCalendar.buttonTouched(_:)), forControlEvents: UIControlEvents.TouchUpInside)
button.frame = CGRectMake(0, self.view.bounds.size.height/2.0 - 20, self.view.bounds.size.width, 40)
self.view.addSubview(button)
}
func buttonTouched(sender: AnyObject) {
self.title = "Back"
// >> localization-firstweekday-swift
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
calendar.firstWeekday = 2
// << localization-firstweekday-swift
let date = NSDate()
// >> view-modes-viewcontroller-swift
let controller = TKCalendarYearViewController()
controller.contentView.minDate = TKCalendar.dateWithYear(2012, month: 1, day: 1, withCalendar: calendar)
controller.contentView.maxDate = TKCalendar.dateWithYear(2018, month: 12, day: 31, withCalendar: calendar)
controller.contentView.navigateToDate(date, animated: false)
self.navigationController?.pushViewController(controller, animated: true)
// << view-modes-viewcontroller-swift
}
override func viewDidAppear(animated: Bool) {
self.title = "iOS 7 style calendar"
self.navigationController?.delegate = nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// ViewController.swift
// RxSwift_Practice
//
// Created by ShawnHuang on 2019/12/17.
// Copyright © 2019 ShawnHuang. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class ViewController: UIViewController {
/*
可觀察序列 - Observable
觀察者 - Observer
調度者 - Scheduler
銷毀者 - Dispose
*/
@IBOutlet weak var testBtn: UIButton!
@IBOutlet weak var testField: UITextField!
@IBOutlet weak var testLabel: UILabel!
let disposeBag = DisposeBag()
let err = NSError(domain: "errorDomain", code: 123, userInfo: ["test":"error"])
override func viewDidLoad() {
super.viewDidLoad()
Observable_Type()
Subject_Type()
// Observable序列的創建方式()
高階函數_組合操作符()
高階函數_映射操作符()
// 高階函數_過濾條件操作符()
// 高階函數_集合控制操作符ㄧ()
// 高階函數_集合控制操作符二()
let ob = Observable.of("xxx","aaa")
let a = testLabel.rx.text.asObserver()
ob.subscribe({ str in
print(str)
})
ob.bind { str in
print(str)
}
}
//MARK: - Observable 類型
func Observable_Type()
{
//MARK: Observable 隨意產生
print("********Observable********")
let ob = Observable<String>.create { (obs) -> Disposable in
obs.onNext("可以")
obs.onNext("多個")
obs.onError(self.err)
obs.onCompleted()
return Disposables.create()
}
ob.subscribe(onNext : { str in
print(str)
},onError: { err in
print(err)
}).disposed(by: disposeBag)
//MARK: single 只產生一個元素 或一個error
print("********single********")
let singleOB = Single<Any>.create { (single) -> Disposable in
print("singleOB 是否共享")
single(.success("Cooci"))
single(.error(self.err))
return Disposables.create()
}
singleOB.subscribe { (reslut) in
print("訂閱:\(reslut)")
}.disposed(by: disposeBag)
//MARK: Completable 只產生一個completed or 一個error Completable 適用於那種你只關心任務是否完成,而不需要在意任務返回值的情況。它和 Observable<Void> 有點相似。
print("********Completable********")
let completableOB = Completable.create { (completable) -> Disposable in
print("completableOB 是否共享")
completable(.completed)
completable(.error(self.err))
return Disposables.create()
}
completableOB.subscribe { (reslut) in
print("訂閱:\(reslut)")
}.disposed(by: disposeBag)
//MARK: Maybe 只產生一個元素 or completed or 一個error
print("********Maybe********")
_ = Maybe<Any>.create { maybe -> Disposable in
maybe(.error(self.err))
maybe(.success("xxx"))
maybe(.completed)
return Disposables.create()
}.subscribe(onSuccess: { str in
print(str)
}, onError: { eee in
print(eee.localizedDescription)
}, onCompleted: {
print("completed")
}).disposed(by: disposeBag)
}
//MARK: - Subject 類型
func Subject_Type()
{
//MARK: PublishSubject 只有訂閱後的訊號
print("********PublishSubject********")
// 1:初始化序列
let publishSub = PublishSubject<Int>() //初始化一個PublishSubject 裝著Int類型的序列
// 2:發送響應序列
publishSub.onNext(1)
// 3:訂閱序列
publishSub.subscribe { print("訂閱到了:",$0)}
.disposed(by: self.disposeBag)
// 再次發送響應
publishSub.onNext(2)
publishSub.onNext(3)
//MARK: BehaviorSubject 收到上一個訊號若無則發送初始值 有complete error事件 跟BehaviorSubject
print("********BehaviorSubject********")
let behaviorSub = BehaviorSubject<String>(value:"init")
behaviorSub.onNext("1")
behaviorSub.onNext("2")
behaviorSub.subscribe(onNext:{
print($0)
}).disposed(by: self.disposeBag)
behaviorSub.onCompleted()
behaviorSub.onNext("3")
//MARK: ReplaySubject 可以收到往前n個事件 看buffer size
print("********ReplaySubject********")
let replaySub = ReplaySubject<Int>.create(bufferSize: 5)
replaySub.onNext(1)
replaySub.onNext(2)
replaySub.onNext(3)
replaySub.onNext(4)
replaySub.subscribe{ print("訂閱到了:",$0)}
.disposed(by: self.disposeBag)
replaySub.onNext(7)
//MARK: AsyncSubject 只會收到完成前的最後一個事件
print("********AsyncSubject********")
let asynSub = AsyncSubject<Int>()
asynSub.onNext(1)
asynSub.onNext(2)
asynSub.onCompleted()
asynSub.onNext(3)
asynSub.subscribe{ print("訂閱到了:",$0)}
.disposed(by: self.disposeBag)
//MARK: BehaviorRelay 就是 BehaviorSubject 去掉終止事件 onError 或 onCompleted
print("********BehaviorRelay********")
let behaviorRelay = BehaviorRelay<Int>(value: 200)
behaviorRelay.accept(500)
behaviorRelay.subscribe(onNext: { (num) in
print(num)
}, onError: { (err) in
print(err)
}, onCompleted: {
print("complete")
}) {
print("disposeable")
}.disposed(by: self.disposeBag)
behaviorRelay.accept(2000)
behaviorRelay.accept(1000)
}
//MARK: - Observable序列的創建方式
func Observable序列的創建方式()
{
//MARK: empty -- 空的
print("********empty********")
let empty = Observable<Int>.empty()
_ = empty.subscribe(onNext : { num in print(num)
}, onError:{ error in print(error)
}, onCompleted: { print("完成")
},onDisposed: {print("釋放")})
//MARK: just -- 單個信號序列創建
print("********just********")
let arr = ["aa" , "bb"]
Observable<[String]>.just(arr)
.subscribe({ event in
print(event)
}).disposed(by: disposeBag)
_ = Observable<[String]>.just(arr).subscribe(onNext : { number in
print("訂閱:",number)
},onError: { print("error:",$0)
},onCompleted: {print("finish")
},onDisposed: {print("dispose")})
print("********of********")
//MARK: of - 多個元素 - 針對序列處理 可以兩個以上
Observable<String>.of("cc","dd").subscribe { (event) in
print(event)
}.disposed(by: disposeBag)
Observable<[String:Any]>.of(["ee":"ff"] , ["11":"22"])
.subscribe { (event) in print(event)
}.disposed(by: disposeBag)
print("********from********")
// MARK: from - 將一個可選值轉換為 Observable:
let optional: String? = "optional value"
_ = Observable<String>.from(optional: optional)
.subscribe { (event) in print(event)}
.disposed(by: disposeBag)
_ = Observable<[String]>.from(optional: ["opt1" , "opt2" ])
.subscribe(onNext:{
print($0)
})
print("********defer********")
//MARK: defer
var isOdd = true
_ = Observable<Int>.deferred({ () -> Observable<Int> in
isOdd.toggle()
if isOdd{
return Observable.just(1)
}
else {
return Observable.of(1,2,3)
}
}).subscribe({print($0)})
print("********rang********")
//MARK: rang
Observable.range(start: 2, count: 5)
.subscribe { (event) in
print(event)
}.disposed(by: disposeBag)
print("********generate********")
//MARK: generate
// 數組遍歷
let textArr = ["1","2","3","4","5","6","7","8","9","10"]
Observable.generate(initialState: 0,// 初始值
condition: { $0 < textArr.count}, // 條件1
iterate: { $0 + 1 }) // 條件2 +2
.subscribe(onNext: {
print("遍歷arr:",textArr[$0])
})
.disposed(by: disposeBag)
print("********timer********")
//MARK: timer 起始 間隔
// Observable<Int>.timer(0, period: 1, scheduler: MainScheduler.instance).subscribe(onNext:{print($0)})
// Observable<Int>.timer(0, scheduler: MainScheduler.instance).subscribe(onNext:{print($0)})
print("********interval********")
//MARK: interval
// 定時器 兩秒固定發送一次
// Observable<Int>.interval(2, scheduler: MainScheduler.instance).subscribe { (event) in
// print(event)
// }
print("********repeatElement********")
//MARK: repeatElement ... // 无数次
// Observable<Int>.repeatElement(5).subscribe({print($0)})
print("********error********")
//MARK: error
Observable<Int>.error(err).subscribe { (event) in
print(event)
}.disposed(by: disposeBag)
print("********never********")
//MARK: never
Observable<String>.never().subscribe({event in
print(event)
}).disposed(by: disposeBag)
print("********create********")
let ob = Observable<String>.create({ observ in
observ.onNext("observable")
observ.onCompleted()
return Disposables.create()
})
ob.subscribe({print($0)}).disposed(by: disposeBag)
ob.subscribe(onNext: {print($0)}).disposed(by: disposeBag)
}
//MARK: - Observable序列的創建方式
func 高階函數_組合操作符()
{
//MARK: startWith
print("*****startWith*****")
Observable.of("1","2","3","4")
.startWith("A")
.startWith("B")
.startWith("C","a","b")
.subscribe(onNext: {print($0)})
.disposed(by: disposeBag)
//效果: CabBA1234
//MARK: merage
print("*****merage*****")
let subject1 = PublishSubject<String>()
let subject2 = PublishSubject<String>()
Observable.of(subject1,subject2).merge().subscribe(onNext:{
print($0)
}).disposed(by: disposeBag)
subject1.onNext("sub1")
subject2.onNext("sub2")
subject1.onNext("sub11")
//MARK: zip
print("*****zip*****")
let stringSubject = PublishSubject<String>()
let intSubject = PublishSubject<Int>()
Observable.zip(stringSubject, intSubject){ stringElement, intElement in
"\(stringElement) - \(intElement)"
}.subscribe(onNext:{
print($0 + " zip")
}).disposed(by: disposeBag)
stringSubject.onNext("C")
stringSubject.onNext("o") // 到這裡存儲了 C o 但是不會響應除非;另一個響應
intSubject.onNext(1) // 勾出一個
intSubject.onNext(2) // 勾出另一個
stringSubject.onNext("i") // 存一個
intSubject.onNext(3) // 勾出一個
// 說白了: 只有兩個序列同時有值的時候才會響應,否則存值
//MARK: combineLatest
print("*****combineLatest*****")
let stringSub = PublishSubject<String>()
let intSub = PublishSubject<Int>()
Observable.combineLatest(stringSub, intSub) { strElement, intElement in
"\(strElement) + \(intElement)"
}
.subscribe(onNext: { print($0 + " combineLatest") })
.disposed(by: disposeBag)
stringSub.onNext("L") // 存一個 L
stringSub.onNext("G") // 存了一個覆蓋 - 和zip不一樣
intSub.onNext(1) // 發現strOB也有G 響應 G 1
intSub.onNext(2) // 覆蓋1 -> 2 發現strOB 有值G 響應 G 2
stringSub.onNext("Cooci") // 覆蓋G -> Cooci 發現intOB 有值2 響應 Cooci 2
// combineLatest 比較zip 會覆蓋
// 應用非常頻繁: 比如賬戶和密碼同時滿足->才能登陸. 不關係賬戶密碼怎麼變化的只要查看最後有值就可以 loginEnable
//MARK: switchLatest
print("*****switchLatest*****")
let switchLatestSub1 = BehaviorSubject(value: "L")
let switchLatestSub2 = BehaviorSubject(value: "1")
let switchLatestSub = BehaviorSubject(value: switchLatestSub1)// 選擇了 switchLatestSub1 就不會監聽 switchLatestSub2
switchLatestSub.asObservable()
.switchLatest()
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
switchLatestSub1.onNext("G")
switchLatestSub1.onNext("_")
switchLatestSub2.onNext("2")
switchLatestSub2.onNext("3") // 2-3都會不會監聽,但是默認保存由 2覆蓋1 3覆蓋2
switchLatestSub.onNext(switchLatestSub2) // 切換到 switchLatestSub2
switchLatestSub1.onNext("*")
switchLatestSub1.onNext("Cooci") // 原理同上面 下面如果再次切換到 switchLatestSub1會打印出 Cooci
switchLatestSub2.onNext("4")
}
//MARK: - 高階函數_映射操作符
func 高階函數_映射操作符()
{
//MARK: map
print("*****map*****")
let ob = Observable.of(1,2,3,4)
ob.map { (num) -> Int in
return num + 2
}.subscribe(onNext:{
print($0)
}).disposed(by: disposeBag)
//MARK: flatMap
print("*****flatMap*****")
let disposeBag = DisposeBag()
let first = BehaviorSubject(value: "👦🏻")
let second = BehaviorSubject(value: "🅰️")
let variable = Variable(first)
variable.asObservable()
.flatMap { $0 }
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
first.onNext("🐱")
variable.value = second
second.onNext("🅱️")
first.onNext("🐶")
//MARK: scan
print("*****scan*****")
Observable.of(10, 100, 1000)
.scan(2) { aggregateValue, newValue in
aggregateValue + newValue // 10 + 2 , 100 + 10 + 2 , 1000 + 100 + 2
}
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
}
//MARK: - 高階函數_過濾條件操作符
func 高階函數_過濾條件操作符()
{
//MARK: filter -
print("*****filter*****")
let obs = Observable.of(1,2,3,4,5,6).filter { (num) -> Bool in
return num % 2 == 0
}
obs.subscribe(onNext:{
print($0)
}).disposed(by: disposeBag)
//MARK: distinctUntilChanged 去除重複的
print("*****distinctUntilChanged*****")
Observable.of("1", "2", "2", "2", "3", "3", "4")
.distinctUntilChanged()
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
//MARK: elementAt 特定元素
print("*****elementAt*****")
Observable.of("1", "2", "3", "4", "5")
.elementAt(3)
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
//MARK: single 指回傳符合的一個 若大於兩個則回傳錯誤
print("*****single*****")
Observable.of("Cooci", "Kody")
.single()
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
Observable.of("Cooci", "Kody" )
.single { $0 == "Kody" }
.subscribe (onNext: { print($0) })
.disposed(by: disposeBag)
//MARK: take 取幾個
print("*****take*****")
Observable.of("1", "2","3", "4")
.take(3)
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
//MARK: takeLast 取後面數來幾個
print("*****takeLast*****")
Observable.of("1", "2","3", "4")
.takeLast(2)
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
//MARK: takeUntil
// 從源可觀察序列發出元素,直到參考可觀察序列發出元素
// 這個要重點,應用非常頻繁 比如我頁面銷毀了,就不能獲取值了(cell重用運用)
print("*****takeUntil*****")
let sourceSequence = PublishSubject<String>()
let referenceSequence = PublishSubject<String>()
sourceSequence
.takeUntil(referenceSequence)
.subscribe { print($0) }
.disposed(by: disposeBag)
sourceSequence.onNext("1")
sourceSequence.onNext("2")
sourceSequence.onNext("3")
referenceSequence.onNext("a") // 條件一出來,下面就走不了
sourceSequence.onNext("4")
//MARK: skip
// 這個要重點,應用非常頻繁 不用解釋 textfiled 都會有默認序列產生
print("*****skip*****")
Observable.of(1, 2, 3, 4, 5, 6)
.skip(2)
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
print("*****skipWhile*****") // 成立就跳過
Observable.of(1, 2, 3, 4, 5, 6)
.skipWhile { $0 < 4 }
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
print("*****skipUntil*****") //
let sourceSeq = PublishSubject<String>()
let referenceSeq = PublishSubject<String>()
sourceSeq
.skipUntil(referenceSeq)
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
// 沒有條件命令 下面走不了
sourceSeq.onNext("1")
sourceSeq.onNext("2")
sourceSeq.onNext("3")
referenceSeq.onNext("on") // 條件一出來,下面就可以走了
sourceSeq.onNext("4")
}
//MARK: - 高階函數_集合控制操作符一
func 高階函數_集合控制操作符一()
{
//MARK: toArray -
print("*****toArray*****")
PublishSubject.range(start: 1, count: 10)
.toArray()
.subscribe { print($0) }
.disposed(by: disposeBag)
//MARK: reduce -
print("*****reduce*****")
Observable.of(10, 100, 1000)
.reduce(1, accumulator: +) // 1 + 10 + 100 + 1000 = 1111
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
//MARK: concat -
print("*****concat*****")
let subject1 = BehaviorSubject(value: "Hank")
let subject2 = BehaviorSubject(value: "1")
let subjectsSubject = BehaviorSubject(value: subject1)
subjectsSubject.asObservable()
.concat()
.subscribe { print($0) }
.disposed(by: disposeBag)
subject1.onNext("Cooci")
subject1.onNext("Kody")
subjectsSubject.onNext(subject2)
subject2.onNext("打印不出來")
subject2.onNext("2")
subject1.onCompleted() // 必須要等subject1 完成了才能訂閱到! 用來控制順序 網絡數據的異步
subject2.onNext("3")
}
//MARK: - 高階函數_集合控制操作符二
func 高階函數_集合控制操作符二()
{
//MARK: catchErrorJustReturn - 失敗後即停止
print("*****catchErrorJustReturn*****")
let sequenceThatFails = PublishSubject<String>()
sequenceThatFails
.catchErrorJustReturn("Cooci")
.subscribe { print($0) }
.disposed(by: disposeBag)
sequenceThatFails.onNext("Hank")
sequenceThatFails.onNext("Kody") // 正常序列發送成功的
//發送失敗的序列,一旦訂閱到位 返回我們之前設定的錯誤的預案
sequenceThatFails.onError(err)
sequenceThatFails.onNext("qqq") // 不發送
//MARK: catchError - 攔截失敗後替換另一組
print("*****catchError*****")
let recoverySequence = PublishSubject<String>()
let sequenceThatFails22 = PublishSubject<String>()
sequenceThatFails22
.catchError {
print("Error:", $0)
return recoverySequence // 獲取到了錯誤序列-我們在中間的閉包操作處理完畢,返回給用戶需要的序列(showAlert)
}
.subscribe { print($0) }
.disposed(by: disposeBag)
sequenceThatFails22.onNext("Hank")
sequenceThatFails22.onNext("Kody") // 正常序列發送成功的
sequenceThatFails22.onError(err) // 發送失敗的序列
recoverySequence.onNext("CC") // 繼續發送
//MARK: retry - 通過無限地重新訂閱可觀察序列來恢復重複的錯誤事件
print("*****retry*****")
var count = 1 // 外界變量控制流程
let sequenceRetryErrors = Observable<String>.create { observer in
observer.onNext("Hank")
observer.onNext("Kody")
observer.onNext("CC")
if count == 1 {
// 流程進來之後就會過度-這裡的條件可以作為出口,失敗的次數
observer.onError(self.err) // 接收到了錯誤序列,重試序列發生
print("錯誤序列來了")
count += 1
}
observer.onNext("Lina")
observer.onNext("小雁子")
observer.onNext("婷婷")
observer.onCompleted()
return Disposables.create()
}
sequenceRetryErrors
.retry()
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
//MARK: retry(_:) - 直到重試次數達到max為止 遇到onError則進行下一回合
print("*****retry(_:)*****")
var conunt2 = 1
let sequenceThatErrors2 = Observable<String>.create { observer in
observer.onNext("1")
observer.onNext("2")
observer.onNext("3")
if conunt2 < 3 {
observer.onError(self.err)
print("錯誤序列")
conunt2 += 1
}
observer.onNext("4")
observer.onNext("5")
observer.onCompleted()
return Disposables.create()
}
sequenceThatErrors2.retry(5).subscribe({
print($0)
}).disposed(by: disposeBag)
//MARK: RxSwift.Resources.total : 提供所有Rx資源分配的計數,這對於在開發期間檢測洩漏非常有用
print("*****RxSwift.Resources.total*****")
print(RxSwift.Resources.total)
let subject = BehaviorSubject(value: "Cooci")
let subscription1 = subject.subscribe(onNext: { print($0) })
print(RxSwift.Resources.total)
let subscription2 = subject.subscribe(onNext: { print($0) })
print(RxSwift.Resources.total)
subscription1.dispose()
print(RxSwift.Resources.total)
subscription2.dispose()
print(RxSwift.Resources.total)
//MARK: multicast 注意 publish() 被訂閱後不會發出元素,直到 connect 操作符被應用為止
print("*****multicast*****")
let netOB = Observable<Any>.create { (observer) -> Disposable in
// sleep(2)// 模擬網絡延遲
print("我開始請求網絡了")
observer.onNext("請求到的網絡數據")
observer.onNext("請求到的本地")
observer.onCompleted()
return Disposables.create {
print("銷毀回調了")
}
}.publish()
netOB.subscribe(onNext: { (anything) in
print("訂閱1:",anything)
})
.disposed(by: disposeBag)
netOB.subscribe(onNext: { (anything) in
print("訂閱2:",anything)
})
.disposed(by: disposeBag)
_ = netOB.connect()
//MARK: replay
print("*****replay*****")
// let intSequence = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance)
// .replay(5)
// _ = intSequence
// .subscribe(onNext: { print("Subscription 1:, Event: \($0)") })
// DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
// _ = intSequence.connect()
// }
// DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
// _ = intSequence
// .subscribe(onNext: { print("Subscription 2:, Event: \($0)") })
// }
// DispatchQueue.main.asyncAfter(deadline: .now() + 8) {
// _ = intSequence
// .subscribe(onNext: { print("Subscription 3:, Event: \($0)") })
// }
}
}
|
//
// SeedsTableViewCell.swift
// Guardianes Monarca
//
// Created by Juan David Torres on 10/25/19.
// Copyright © 2019 Juan David Torres. All rights reserved.
//
import UIKit
class SeedsTableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var viewSeeds: UIView!
}
|
//
// FilmsApp.swift
// Films
//
// Created by Javier Fernández on 30/10/2020.
//
import SwiftUI
@main
struct FilmsApp: App {
@StateObject var scoresData = ScoresData()
var body: some Scene {
WindowGroup {
FilmsView()
.environmentObject(scoresData)
}
}
}
struct FilmsApp_Previews: PreviewProvider {
static var previews: some View {
FilmsView()
.environmentObject(ScoresData())
}
}
|
//
// SwiftIconFont+NSTextField.swift
// SwiftIconFont
//
// Created by Sedat G. ÇİFTÇİ on 6.06.2020.
// Copyright © 2020 Sedat Gökbek ÇİFTÇİ. All rights reserved.
//
#if os(OSX)
import Cocoa
public extension NSTextField {
func parseIcon() {
let text = SwiftIconFont.replace(withText: (self.stringValue as NSString))
self.attributedStringValue = getAttributedString(text, ofSize: self.font!.pointSize)
}
}
#endif
|
//
// Constants.swift
// SeaBattle
//
// Created by Vadym Shchepin on 12/6/16.
// Copyright © 2016 Vadym Shchepin. All rights reserved.
//
import Foundation
let kGlobalAmountOfShips = 10
let kGlobalCountOfShipTypes = 4
let kGlobalFieldDimension: Int = 10
let kDefaultFirstPlayerName = "Player 1"
let kDefaultSecondPlayerName = "Player 2"
|
//
// Globals.swift
// CatanProbabilityCalc
//
// Created by Frederik Lohner on 29/Nov/15.
// Copyright © 2015 FredLoh. All rights reserved.
//
import Foundation
import UIKit
public enum TileType {
case Desert
case Sheep
case Clay
case Wood
case Stone
case Wheat
}
struct Trifecta {
var square0: TileView?
var square1: TileView?
var square2: TileView?
}
struct TileSquare {
var tileType: TileType?
var tileColor: UIColor?
var tileProbability: Int?
}
struct Tile {
var tileType: TileType?
var tileProbability: Int?
}
public class Vertex {
var tile: Tile?
var neighbors: Array<Edge>
init() {
self.neighbors = Array<Edge>()
}
}
public class Edge {
var neighbor: Vertex
var weight: Int
init() {
weight = 0
self.neighbor = Vertex()
}
}
public class SwiftGraph {
//declare a default directed graph canvas
private var canvas: Array<Vertex>
public var isDirected: Bool
init() {
canvas = Array<Vertex>()
isDirected = true
}
//create a new vertex
func addVertex(tile tile: Tile) -> Vertex {
//set the key
let childVertex: Vertex = Vertex()
childVertex.tile = tile
//add the vertex to the graph canvas
canvas.append(childVertex)
return childVertex
}
func addEdge(source source: Vertex, neighbor: Vertex, weight: Int) {
let newEdge = Edge()
//establish the default properties
newEdge.neighbor = neighbor
newEdge.weight = weight
source.neighbors.append(newEdge)
//check condition for an undirected graph
if isDirected == false {
//create a new reversed edge
let reverseEdge = Edge()
//establish the reversed properties
reverseEdge.neighbor = source
reverseEdge.weight = weight
neighbor.neighbors.append(reverseEdge)
}
}
}
//add edge to source vertex
var tileViewArray = [TileView]()
let defaultTile = Tile(tileType: nil, tileProbability: nil)
var tilesArray = [TileSquare]()
var pickingColors = true
var showNextProbability = true
var typeAndProbTileArray = [Tile]()
var arrayOfTrifectas = [Trifecta]()
|
//
// NetworkService.swift
// MapFinder
//
// Created by haru on 2020/06/17.
// Copyright © 2020 Harunobu Agematsu. All rights reserved.
//
import Foundation
import MapKit
class NetworkFourSquareService {
var venueList:[(name:String, lat:Double, lng:Double, category:String?)] = []
func searchAroundVenue(loc:CLLocationCoordinate2D,completion: @escaping ([(name:String, lat:Double, lng:Double, category:String?)]?) -> ()){
let clientId = "JN0UJMZ0JDVEPJ3B1N2BTHYDUBZ1LLOXC0ZVEEWZZL5UXLPD"
let clientSecret = "5MXF4GNXS3QZTNW0YSLQRHG5LWY2RWKA1SKHAAJDBS2OSJ3F"
let loc = Utility().coordinateToString(loc: loc)
let radius = 500
let version = "20200601"
let query = ["sushi","noodle","soba","udon"]
var url = "https://api.foursquare.com/v2/venues/explore?&client_id=" + clientId
url += "&client_secret=" + clientSecret
url += "&v=" + version
url += "&ll=" + loc
url += "&query=" + query[3]
url += "&radius=" + String(radius)
let req_url = URL(string: url)
let req = URLRequest(url: req_url!)
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
let task = session.dataTask(with: req, completionHandler: {
(data, response, error) in
session.finishTasksAndInvalidate()
print(String(data:data!, encoding:String.Encoding(rawValue: String.Encoding.utf8.rawValue))!)
self.ParseJSON(data: data!)
dispatchGroup.leave()
})
task.resume()
dispatchGroup.notify(queue: .main){
completion(self.venueList)
}
}
func ParseJSON(data:Data){
do {
let decoder = JSONDecoder()
let json = try decoder.decode(ResultJson.self, from: data)
let items = json.response.groups[0].items
for item in items{
let venue = item.venue
let place = (venue.name,venue.location.lat,venue.location.lng,venue.categories[0].name)
venueList.append(place)
}
} catch {
print("エラー")
}
}
}
|
//
// ScanningAnimationViewController.swift
// Bluefruit Connect
//
// Created by Antonio García on 06/02/16.
// Copyright © 2016 Adafruit. All rights reserved.
//
import UIKit
class ScanningAnimationViewController: PeripheralModeViewController {
@IBOutlet weak var scanningWave0ImageView: UIImageView!
@IBOutlet weak var scanningWave1ImageView: UIImageView!
private var isAnimating = false
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if isAnimating {
startAnimating()
}
// Observe notifications for coming back from background
registerNotifications(enabled: true)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
registerNotifications(enabled: false)
}
// MARK: - BLE Notifications
private weak var applicationWillEnterForegroundObserver: NSObjectProtocol?
private func registerNotifications(enabled: Bool) {
let notificationCenter = NotificationCenter.default
if enabled {
applicationWillEnterForegroundObserver = notificationCenter.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] _ in
guard let context = self else { return }
// Restarts animation when coming back from background
if context.isAnimating {
context.startAnimating()
}
}
} else {
if let applicationWillEnterForegroundObserver = applicationWillEnterForegroundObserver {notificationCenter.removeObserver(applicationWillEnterForegroundObserver)}
}
}
func startAnimating() {
isAnimating = true
guard isViewLoaded else { return }
// Scanning animation
let duration: Double = 15
let initialScaleFactor: CGFloat = 0.17
let finalScaleFactor: CGFloat = 2.0
// First wave
self.scanningWave0ImageView.transform = CGAffineTransform(scaleX: initialScaleFactor, y: initialScaleFactor)
self.scanningWave0ImageView.alpha = 1
UIView.animate(withDuration: duration, delay: 0, options: [.repeat, .curveEaseInOut], animations: {
self.scanningWave0ImageView.transform = CGAffineTransform(scaleX: finalScaleFactor, y: finalScaleFactor)
self.scanningWave0ImageView.alpha = 0
}, completion: nil)
// Second wave
self.scanningWave1ImageView.transform = CGAffineTransform(scaleX: initialScaleFactor, y: initialScaleFactor)
self.scanningWave1ImageView.alpha = 1
UIView.animate(withDuration: duration, delay: duration/2, options: [.repeat, .curveEaseInOut], animations: {
self.scanningWave1ImageView.transform = CGAffineTransform(scaleX: finalScaleFactor, y: finalScaleFactor)
self.scanningWave1ImageView.alpha = 0
}, completion: nil)
}
func stopAnimating() {
isAnimating = false
if isViewLoaded {
scanningWave0ImageView.layer.removeAllAnimations()
scanningWave1ImageView.layer.removeAllAnimations()
}
}
}
|
//
// FieldViewModel.swift
// DatePatternTextField
//
// Created by Jad on 05/01/2018.
// Copyright © 2018 Jad . All rights reserved.
//
import Foundation
import RxSwift
struct DigitViewModel: FieldViewModel {
var value: Variable<String> = Variable("")
var placeHolder: String = ""
}
protocol FieldViewModel {
var value: Variable<String> { get set }
var placeHolder: String { get }
}
|
//
// NewProject
// Copyright (c) Yuichi Nakayasu. All rights reserved.
//
import Foundation
protocol EventEditInteractorInput: class {
var output: EventEditInteractorOutput! { get set }
}
protocol EventEditInteractorOutput: class {
}
class EventEditRepository: EventEditInteractorInput {
weak var output: EventEditInteractorOutput!
}
|
//
// Indicator.swift
//
//
// Created by nori on 2021/09/20.
//
import SwiftUI
struct Indicator: View {
class Model: ObservableObject {
var frameCount: Int = 0
var date: Date = Date()
@Published var isCompleted: Bool = false
}
@StateObject var model: Model = Model()
@Binding var selection: Int?
var count: Int
var stop: Bool
var interaval: TimeInterval
var frameRate: TimeInterval = 60
var action: () -> Void
init(_ count: Int, selection: Binding<Int?>, stop: Bool, interval: TimeInterval = 6, action: @escaping () -> Void) {
self.count = count
self._selection = selection
self.stop = stop
self.interaval = interval
self.action = action
}
var body: some View {
HStack(spacing: 4) {
if let selection = self.selection {
ForEach(0..<count) { index in
if index == selection {
TimelineView(.periodic(from: Date(), by: 1 / frameRate)) { timeline in
ZStack {
RoundedRectangle(cornerRadius: 2)
.fill(Color.gray.opacity(0.25))
IndicatorComponent(date: timeline.date, frameRate: frameRate, maximumTimeInterval: interaval, stop: stop, action: action)
.onAppear {
model.frameCount = 0
model.date = timeline.date
}
}
}
} else if index < selection {
RoundedRectangle(cornerRadius: 2)
.fill(Color.white)
} else {
RoundedRectangle(cornerRadius: 2)
.fill(Color.gray.opacity(0.25))
}
}
} else {
EmptyView()
}
}
.frame(height: 3)
.environmentObject(model)
.onChange(of: selection) { _ in
DispatchQueue.main.async {
model.isCompleted = false
}
}
}
}
struct IndicatorComponent: View {
@EnvironmentObject var model: Indicator.Model
var date: Date
var frameRate: TimeInterval
var maximumTimeInterval: TimeInterval
var stop: Bool
var action: () -> Void
init(date: Date, frameRate: TimeInterval, maximumTimeInterval: TimeInterval, stop: Bool, action: @escaping () -> Void) {
self.date = date
self.frameRate = frameRate
self.maximumTimeInterval = maximumTimeInterval
self.stop = stop
self.action = action
}
var progress: CGFloat {
CGFloat(CGFloat(model.frameCount) / (frameRate * maximumTimeInterval))
}
var body: some View {
GeometryReader { proxy in
RoundedRectangle(cornerRadius: 2)
.fill(Color.white)
.frame(width: proxy.size.width * progress)
.onChange(of: date) { newValue in
if !stop {
model.frameCount += 1
}
if 1 <= progress, !model.isCompleted {
model.isCompleted = true
}
}
.onChange(of: model.isCompleted) { isCompleted in
if isCompleted {
DispatchQueue.main.async {
action()
}
}
}
}
}
}
struct Indicator_Previews: PreviewProvider {
struct ContentView: View {
@State var selection: Int? = 0
@State var stop: Bool = false
var body: some View {
Indicator(5, selection: $selection, stop: stop) {
selection? += 1
}
.padding()
.background(Color.black)
}
}
static var previews: some View {
ContentView()
}
}
|
//
// HomeScene.swift
// Prototipo1TFG
//
// Created by Arancha Ferrero Ortiz de Zárate on 28/10/18.
// Copyright © 2018 Arancha Ferrero Ortiz de Zárate. All rights reserved.
//
import Foundation
import SpriteKit
class HomeScene: SKScene {
let tapStartLabel: SKSpriteNode
override init(size: CGSize) {
self.tapStartLabel = SKSpriteNode(imageNamed: "tapToStart")
super.init(size: size)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed: "homeBackground")
background.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
background.scale(to: CGSize(width: size.width, height: size.height))
background.zPosition = 0
addChild(background)
let title = SKSpriteNode(imageNamed: "gameTitle")
title.position = CGPoint(x: size.width/2, y: size.height - (size.width/4))
title.scale(to: CGSize(width: (size.width/5)*2, height: (size.width/5)*2))
title.zPosition = 4
addChild(title)
tapStartLabel.position = CGPoint(x: size.width/2, y: size.height/5)
tapStartLabel.zPosition = 4
addChild(tapStartLabel)
var blinkAlpha = 1.0
var alphaAsc = false
let blinkAction = SKAction.customAction(withDuration: 10.0) { (node, elapsedTime) in
if alphaAsc && blinkAlpha < 1 {
blinkAlpha += 0.02
} else {
alphaAsc = false
if blinkAlpha > 0.1 {
blinkAlpha -= 0.02
} else {
alphaAsc = true
blinkAlpha += 0.02
}
}
print("\(blinkAlpha)")
node.alpha = CGFloat(blinkAlpha)
}
tapStartLabel.run(SKAction.repeatForever(blinkAction))
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let gameScene = GameScene(size: size)
gameScene.scaleMode = scaleMode
let transition = SKTransition.doorsOpenVertical(withDuration: 1.0)
view?.presentScene(gameScene, transition: transition)
}
}
|
//
// OneModel.swift
// MVVMFramework
//
// Created by lisilong on 2018/12/5.
// Copyright © 2018 lisilong. All rights reserved.
//
import Foundation
class OneModel: BaseModel {
var name: String = ""
var orderPrice: String = ""
var orderStatus: Int = 0
}
extension OneModel: OneTableViewCellViewModelProtocol {
var title: String {
return name
}
var price: String {
return orderPrice
}
var status: Int {
return orderStatus
}
}
|
//
// HomePresenter.swift
// Marvel
//
// Created by Aya on 9/21/20.
// Copyright © 2020 Aya. All rights reserved.
//
import Foundation
class HomePresenter : IHomePresenter, ICheckConnection{
var myOffset : Int?
var homeViewObj : IHomeView?
var homeModelObj : IHomeModel?
var localHomeObj : ILocalHomeModel?
var charDataList = [CharacterData]()
var charObj : CharacterData?
init(view : IHomeView) {
homeViewObj = view
}
func getDataFromHomeModel(offset: Int) {
var check = InternetConnection.checkInternetConnection(iCheckConnection: self)
myOffset = offset
}
func onSuccess(characterObjList: [Character], characterOffset: Int) {
homeViewObj?.showDataInHomeView(characterObjList: characterObjList , characterOffset: characterOffset)
/*
if localHomeObj!.fetchCharFromRealm().count == 0 {
localHomeObj!.saveCharacteInRealm(chararcterObjList : charDataList)
}else{
}*/
}
func onFail() {
}
func onSucessfullyConnected() {
homeModelObj = HomeModel(presenter: self)
homeModelObj?.getCharacters(offset: myOffset!)
}
func onFailConnected() {
localHomeObj = LocalHomeModel(presenter: self)
}
}
/*
*/
|
//
// HomeViewModel.swift
// SampleProject
//
// Created by 近藤浩市郎 on 2017/09/12.
// Copyright © 2017 Koichiro Kondo. All rights reserved.
//
import Foundation
import RxSwift
class HomeViewModel: BaseViewModel {
let rooms: BehaviorSubject<[RoomDto]> = BehaviorSubject(value: [])
let roomsModel = RoomsModel()
func fetchRoom() {
let params = RoomFetchRequest.Params()
roomsModel.fetchRooms(params)
.subscribeOn(SerialDispatchQueueScheduler(qos: .userInitiated))
.observeOn(MainScheduler.instance)
.subscribe(
onNext: {[weak self](data) in
self?.rooms.onNext(data.rooms ?? [])
},
onError: {[weak self](error) in
},
onCompleted: {
},
onDisposed: {
}
).disposed(by: disposeBag)
}
}
|
//
// PollsObjectValidator.swift
// Pods
//
// Created by Stefanita Oaca on 20/07/2017.
//
//
open class PollsObjectValidator: NSObject {
/// Validate a LocationDetails object
///
/// - Parameter location: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validateLocationDetails(_ location:LocationDetails!) -> String?{
//Properties that are required
let requiredFields = ["latitude", "longitude", "radius"]
for name in requiredFields{
if let value = (location as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
}
} else {
return name
}
}
return nil
}
/// Validate a Location object
///
/// - Parameter location: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validateLocation(_ location:Location!) -> String?{
//Properties that are required
let requiredFields = ["latitude", "longitude"]
for name in requiredFields{
if let value = (location as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
}
} else {
return name
}
}
return nil
}
/// Validate a SNSDevice object
///
/// - Parameter device: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validateSNSDevice(_ device:SNSDevice!) -> String?{
//Properties that are required
let requiredFields = ["userId", "deviceId"]
for name in requiredFields{
if let value = (device as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
}
} else {
return name
}
}
return nil
}
/// Validate a ChargePayment object
///
/// - Parameter chargePayment: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validateChargePayment(_ chargePayment:ChargePayment!) -> String?{
//Properties that are required
let requiredFields = ["userId", "planId"]
for name in requiredFields{
if let value = (chargePayment as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
}
} else {
return name
}
}
return nil
}
/// Validate a ResponseInvitation object
///
/// - Parameter pollAnswer: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validateResponseInvitation(_ responseInvitation:ResponseInvitation!) -> String?{
//Properties that are required
let requiredFields = ["userId", "isAccepted"]
for name in requiredFields{
if let value = (responseInvitation as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
}
} else {
return name
}
}
return nil
}
/// Validate a PollAnswer object
///
/// - Parameter pollAnswer: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validatePollAnswer(_ pollAnswer:PollAnswer!) -> String?{
//Properties that are required
let requiredFields = ["pollId"]
for name in requiredFields{
if let value = (pollAnswer as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
}
} else {
return name
}
}
return nil
}
/// Validate a RemoteImage object
///
/// - Parameter state: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validateRemoteImage(_ remoteImage:RemoteImage!) -> String?{
//Properties that are required
let requiredFields = ["remoteImageUrl"]
for name in requiredFields{
if let value = (remoteImage as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
}
} else {
return name
}
}
return nil
}
/// Validate a Country object
///
/// - Parameter state: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validateState(_ state:State!) -> String?{
//Properties that are required
let requiredFields = ["id"]
for name in requiredFields{
if let value = (state as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
}
} else {
return name
}
}
return nil
}
/// Validate a Country object
///
/// - Parameter country: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validateCountry(_ country:Country!) -> String?{
//Properties that are required
let requiredFields = ["id"]
for name in requiredFields{
if let value = (country as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
}
} else {
return name
}
}
return nil
}
/// Validate a PollsNotificationPreference object
///
/// - Parameter pollsNotificationPreference: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validatePollsNotificationPreference(_ pollsNotificationPreference:PollsNotificationPreference!) -> String?{
//Properties that are required
let requiredFields = ["browser","deviceId","email","phoneCall","pushNotification","sms"]
for name in requiredFields{
if let value = (pollsNotificationPreference as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
}
} else {
return name
}
}
return nil
}
/// Validate a BillingAgreement object
///
/// - Parameter billingAgreement: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validateBillingAgreement(_ billingAgreement:BillingAgreement!) -> String?{
//Properties that are required
let requiredFields = ["payerEmail","planId"]
for name in requiredFields{
if let value = (billingAgreement as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
}
} else {
return name
}
}
return nil
}
/// Validate a VerifyPayment object
///
/// - Parameter verifyPayment: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validateVerifyPayment(_ verifyPayment:VerifyPayment!) -> String?{
//Properties that are required
let requiredFields = ["transactionId","receiptData","productId","planId"]
for name in requiredFields{
if let value = (verifyPayment as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
}
} else {
return name
}
}
return nil
}
/// Validate a GetFilters object
///
/// - Parameter getFilters: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validateGetFilters(_ getFilters:GetFilters!) -> String?{
//Properties that are required
let requiredFields = ["filterType"]
for name in requiredFields{
if let value = (getFilters as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
}
} else {
return name
}
}
return nil
}
/// Validate a Thumbs object
///
/// - Parameter thumbs: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validateThumbs(_ thumbs:Thumbs!) -> String?{
//Properties that are required
let requiredFields = ["workerId"]
for name in requiredFields{
if let value = (thumbs as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
}
} else {
return name
}
}
return nil
}
/// Validate a VerifyPhone object
///
/// - Parameter verifyPhone: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validateVerifyPhone(_ verifyPhone:VerifyPhone!) -> String?{
//Properties that are required
let requiredFields = ["verificationCode","userName"]
for name in requiredFields{
if let value = (verifyPhone as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
}
} else {
return name
}
}
return nil
}
/// Validate a GetPolls object
///
/// - Parameter getPolls: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validateGetPolls(_ getPolls:GetPolls!) -> String?{
//Properties that are required
let requiredFields = ["viewAll"]
for name in requiredFields{
if let value = (getPolls as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
}
} else {
return name
}
}
return nil
}
/// Validate a Contact object
///
/// - Parameter contact: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validateContact(_ contact:Contact!) -> String?{
//Properties that are required
let requiredFields = ["countryCode","phoneNumber","firstName","lastName","payPalEmail"]
for name in requiredFields{
if let value = (contact as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
}
} else {
return name
}
}
return nil
}
/// Validate a Device object
///
/// - Parameter contact: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validateDevice(_ device:Device!) -> String?{
//Properties that are required
let requiredFields = ["snsDeviceId","snsType"]
for name in requiredFields{
if let value = (device as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
}
} else {
return name
}
}
return nil
}
/// Validate a Poll object
///
/// - Parameter contact: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validatePoll(_ poll:Poll!) -> String?{
//Properties that are required
var requiredFields = ["pollTitle","question","assignmentDurationInSeconds","isPublished","lifeTimeInSeconds"]
// Different properties are required accorinding to the poll type
if poll.pollTypeId == 2{
requiredFields.append("firstOption")
requiredFields.append("secondOption")
} else if poll.pollTypeId == 3{
requiredFields.append("firstImagePath")
} else if poll.pollTypeId == 4{
requiredFields.append("firstImagePath")
requiredFields.append("secondImagePath")
}
// if poll.isPublished && poll.filterNameValue?.count == 0{
// return "filters"
// }
if (poll.pollTitle?.characters.count)! < 20{
return "pollTitle with more than 20 characters"
}
if (poll.question?.characters.count)! < 20{
return "question with more than 20 characters"
}
if poll.assignmentDurationInSeconds < 30{
return "assignmentDurationInSeconds with a number bigger 30"
}
if poll.lifeTimeInSeconds < 30{
return "lifeTimeInSeconds with a number bigger 30"
}
for name in requiredFields{
if let value = (poll as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
}
} else {
return name
}
}
return nil
}
/// Validate a Login object
///
/// - Parameter contact: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validateLogin(_ loginVM:Login!) -> String?{
//Properties that are required
let requiredFields = ["username","password","kIdDevice_newDevice"]
for name in requiredFields{
if let value = (loginVM as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
} else if value is Device{
let returnValue = validateDevice(value as! Device)
if returnValue != nil{
return returnValue
}
}
} else {
return name
}
}
return nil
}
/// Validate a Register object
///
/// - Parameter contact: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validateRegister(_ registerVM:Register!) -> String?{
//Properties that are required
let requiredFields = ["userName","emailAddress","password","userType","kIdDevice_newDevice","kIdContact_newProfileContact","verificationMethod"]
for name in requiredFields{
if let value = (registerVM as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
} else if value is Device{
let returnValue = validateDevice(value as! Device)
if returnValue != nil{
return returnValue
}
} else if value is Contact{
let returnValue = validateContact(value as! Contact)
if returnValue != nil{
return returnValue
}
}
} else {
return name
}
}
return nil
}
/// Validate a Employee object
///
/// - Parameter contact: Object to be validated
/// - Returns: Property that does not have a valid format
open class func validateEmployee(_ employee:Employee!) -> String?{
//Properties that are required
let requiredFields = ["emailAddress","password","userType","newDevice","newProfileContact","verificationMethod"]
for name in requiredFields{
if let value = (employee as! NSObject).value(forKey: name){
if value is String && (value as! String).characters.count == 0{
return name
} else if value is Device{
let returnValue = validateDevice(value as! Device)
if returnValue != nil{
return returnValue
}
} else if value is Contact{
let returnValue = validateContact(value as! Contact)
if returnValue != nil{
return returnValue
}
}
} else {
return name
}
}
return nil
}
open class func validateString(_ string:String?) -> String?{
if string == nil || string!.characters.count <= 3{
return "should be at least 3 characters"
}
return nil
}
open class func validateInteger(_ int:Int?) -> String?{
if int == nil || int == 0{
return "should be different than 0"
}
return nil
}
}
|
//
// UserTextFieldView.swift
// SwiftUI-Journey
//
// Created by Kumar, Amit on 05/09/20.
// Copyright © 2020 Kumar, Amit. All rights reserved.
//
import SwiftUI
struct UserTextFieldView: View {
@Binding var email: String
var body: some View {
TextField("Enter email", text: $email)
.padding()
.frame(minWidth: 0, maxWidth: .infinity)
.frame(height: 60)
.background(Color(UIColor(red: 235.0/255.0, green: 235.0/255.0, blue: 235.0/255.0, alpha: 1.0)))
.cornerRadius(5)
}
}
struct UserTextFieldView_Previews: PreviewProvider {
static var previews: some View {
UserTextFieldView(email: .constant("email@gmail.com"))
}
}
|
//
// File.swift
//
//
// Created by Michal Ziobro on 09/07/2020.
//
import Foundation
extension String {
func asURL() throws -> URL {
if let url = URL(string: self) {
return url
}
throw URLError(.unknown)
}
}
|
//
// ViewController.swift
// 2DA_EVA_4_RESTAURANT
//
// Created by JUAN on 07/03/17.
// Copyright 2017 Juan. All rights Reserved
//EVA_2 TABLAS2_Restaurant <Manejo de tablas y datos>
//Written by:<Juan Humberto Chacon Holguin>
//<13550355>
//<Plataforma I>
//<07/03/2017>
import UIKit
//agregar protocolos requeridos para utilizar la tabla view
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
//declarar un arreglo con los nombres de los restaurants, en este caso se le puso el nombre de las imagenes, son datos de tipo cadena.
let misDatos=["Barrafina","bourkestreetbakery","cafedeadend","cafeloisl","cafelore","confessional","donostia","fiveleaves","forkeerestaurant","grahamavenuemeats","haighschocolate","homei","palominoespresso","petiteoyster","posatelier","royaloak","teakha","thaicafe","traif","upstate","wafflewolf"]
//arreglo de nombre misResImg para guardar las imagenes.
let misRestImg = ["barrafina","bourkestreetbakery","cafedeadend","cafeloisl","cafelore","confessional","donostia","fiveleaves","forkeerestaurant","grahamavenuemeats","haighschocolate","homei","palominoespresso","petiteoyster","posatelier","royaloak","teakha","thaicafe","traif","upstate","wafflewolf"]
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.
}
//Func tableView =regresa el valor contenido en el arreglo, esto es la cantidad de datos que estan en el.
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return misDatos.count
}
//func tableView
//se declara una alerta para desplegar el dato del arreglo seleccionado, es decir el dato que esta en el arreglo, esto en la variable controlador
//El boton manda un mensaje de ok en una alerta,mostrando el valor seleccionado.
//controlador.addAction(boton), es para mandar llamar la alerta, el mensaje.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let controlador = UIAlertController(title:"Tus datos",message: misDatos[indexPath.row],preferredStyle: .Alert)
let boton = UIAlertAction(title: "ok",style: .Default,handler: nil)
controlador.addAction(boton)
presentViewController(controlador, animated: true, completion: nil)
}
//devuelve la celda prototipo.
//Se le daran valores a la variable celda, los cuales son los valores del arreglo.
//indexPath es el numero de columna en cual se encuentra el dato del arreglo previamente declarado.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var celda = tableView.dequeueReusableCellWithIdentifier("miCelda")
if celda == nil {
celda = UITableViewCell(style: .Default, reuseIdentifier: "miCelda")
}
celda?.textLabel?.text=misDatos[indexPath.row]
let imFija = UIImage(named:misRestImg[indexPath.row])//Imagen fija de cada elemento de la tabla
celda?.imageView?.image = imFija//Asignacion de imagen fija a cada celda.
return celda!
}
}
|
//
// Card.swift
// War
//
// Created by Daniel Baird on 3/23/19.
// Copyright © 2019 Daniel Baird. All rights reserved.
//
import Foundation
enum Card {
case Ace(Suit)
case King(Suit)
case Queen(Suit)
case Jack(Suit)
case Ten(Suit)
case Nine(Suit)
case Eight(Suit)
case Seven(Suit)
case Six(Suit)
case Five(Suit)
case Four(Suit)
case Three(Suit)
case Two(Suit)
}
|
//
// TableView.swift
// twitterPractice
//
// Created by 平野 隆昭 on 2016/08/26.
// Copyright © 2016年 mycompany. All rights reserved.
//
import Foundation
|
//
// ProfileTableViewCell.swift
// PodTest
//
// Created by Mariusz Jakowienko on 17.06.2018.
// Copyright © 2018 personal. All rights reserved.
//
import Foundation
import UIKit
class ProfileTableViewCell: UITableViewCell {
@IBOutlet weak var nameUILabel: UILabel!
@IBOutlet weak var surnameUILabel: UILabel!
@IBOutlet weak var emailUILabel: UILabel!
@IBOutlet weak var facebookIDUILabel: UILabel!
func bind(_ viewModel: UserItemViewModel) {
nameUILabel.text = viewModel.first_name
surnameUILabel.text = viewModel.last_name
emailUILabel.text = "\(viewModel.id)"
facebookIDUILabel.text = viewModel.user.token
}
}
|
//
// ViewController.swift
// ListKitDemo
//
// Created by KingCQ on 2016/12/16.
// Copyright © 2016年 KingCQ. All rights reserved.
//
import UIKit
class ViewController: GroupDatil {
override func viewDidLoad() {
super.viewDidLoad()
items = [
[
Item(title: "我的关注", subtitle: "wobuhao")
],
[
Item(title: "我的收藏", subtitle: "hello world"),
Item(title: "最近浏览", subtitle: "")
],
[
Item(title: "我的书夹", dest: TableGroupDetail(), selectable: true)
]
]
}
}
|
//
// ViewController.swift
// MyMapKit
//
// Created by Vũ Quý Đạt on 10/12/2020.
//
import UIKit
import MapKit
import CoreLocation
//// MARK: - Statics
//struct UserLocationManager {
// static var userLocation = CLLocation()
//}
// MARK: - MapView container.
class ViewController: UIViewController, CLLocationManagerDelegate {
// MARK: - Bool
var isJustGetintoApp = true
// MARK: - Statics
static var userLocationVal = CLLocation()
var userLocation: CLLocation? {
willSet {
if isJustGetintoApp {
guard let location = newValue else {
return
}
let initialLocation = CLLocation(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
mapView.centerToLocation(initialLocation)
isJustGetintoApp = false
}
ViewController.userLocationVal = newValue!
// print("user location: \(String(describing: newValue))")
}
}
// MARK: - Variables
var locationManager:CLLocationManager!
// outlets
// @IBOutlet private weak var mapView: MKMapView!
@IBOutlet private var mapView: MKMapView!
// variables
private var artworks: [Annotation] = []
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setUpUserLocationGetter()
// // Set initial location in Honolulu
// let initialLocation = CLLocation(latitude: userLocation.coordinate.latitude, longitude: userLocation.coordinate.longitude)
// mapView.centerToLocation(initialLocation)
// let oahuCenter = CLLocation(latitude: 21.4765, longitude: -157.9647)
// let region = MKCoordinateRegion(
// center: oahuCenter.coordinate,
// latitudinalMeters: 50000,
// longitudinalMeters: 60000)
// mapView.setCameraBoundary(
// MKMapView.CameraBoundary(coordinateRegion: region),
// animated: true)
// let zoomRange = MKMapView.CameraZoomRange(maxCenterCoordinateDistance: 200000)
// mapView.setCameraZoomRange(zoomRange, animated: true)
setUpViewUserInfoButton()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
mapView?.delegate = self
mapView?.register(
AnnotationView.self,
forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)
loadInitialData()
mapView?.addAnnotations(artworks)
isJustGetintoApp = true
}
func setUpUserLocationGetter() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled(){
locationManager.startUpdatingLocation()
}
}
private func loadInitialData() {
// 1
guard
let fileName = Bundle.main.url(forResource: "Annotation", withExtension: "geojson"),
let artworkData = try? Data(contentsOf: fileName)
else {
return
}
do {
// 2
let features = try MKGeoJSONDecoder()
.decode(artworkData)
.compactMap { $0 as? MKGeoJSONFeature }
// 3
let validWorks = features.compactMap(Annotation.init)
// 4
artworks.append(contentsOf: validWorks)
} catch {
// 5
print("Unexpected error: \(error).")
}
}
func setUpViewUserInfoButton() {
}
}
private extension MKMapView {
func centerToLocation(_ location: CLLocation, regionRadius: CLLocationDistance = 1000) {
let coordinateRegion = MKCoordinateRegion(
center: location.coordinate,
latitudinalMeters: regionRadius,
longitudinalMeters: regionRadius)
setRegion(coordinateRegion, animated: true)
}
}
extension ViewController: MKMapViewDelegate {
func mapView(
_ mapView: MKMapView,
annotationView view: MKAnnotationView,
calloutAccessoryControlTapped control: UIControl
) {
// custom
// if (control as? UIButton)?.buttonType == UIButton.ButtonType.detailDisclosure {
// mapView.deselectAnnotation(view.annotation, animated: false)
// return
// }
guard let artwork = view.annotation as? Annotation else {
return
}
let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
artwork.mapItem?.openInMaps(launchOptions: launchOptions)
}
// func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
// var view: AnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: "annotation") as? AnnotationView
// if view == nil {
// view = AnnotationView(annotation: annotation, reuseIdentifier: "annotation")
// }
// let annotation = annotation as! Annotation
// view?.image = annotation.image
// view?.annotation = annotation
//
// return view
// }
// func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
// mapView.showsUserLocation = true
// }
}
//MARK: - Location delegate methods
extension ViewController {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// let userLocation :CLLocation = locations[0] as CLLocation
userLocation = locations[0] as CLLocation
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(userLocation!) { (placemarks, error) in
if (error != nil){
print("error in reverseGeocode - can not get location of device!")
}
var placemark: [CLPlacemark]!
if placemarks != nil {
placemark = placemarks! as [CLPlacemark]
} else {
print("loading location..")
return
}
if placemark.count > 0 {
// let placemark = placemarks![0]
// print(placemark.locality!)
// print(placemark.administrativeArea!)
// print(placemark.country!)
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Location Service Error \(error)")
}
}
|
//
// Dispatcher.swift
// Beekeeper
//
// Created by Andreas Ganske on 15.04.18.
// Copyright © 2018 Andreas Ganske. All rights reserved.
//
import Foundation
import ConvAPI
import PromiseKit
public protocol Dispatcher {
var timeout: TimeInterval { get }
var maxBatchSize: Int { get }
func dispatch(event: Event) -> Promise<Void>
func dispatch(events: [Event]) -> Promise<Void>
}
public struct URLDispatcherError: Codable, Error {
public let error: String
}
public class URLDispatcher: Dispatcher {
let baseURL: URL
let path: String
let backend: API
let signer: Signer
public let timeout: TimeInterval
public var maxBatchSize: Int
public init(baseURL: URL, path: String, signer: Signer, timeout: TimeInterval = 30, maxBatchSize: Int = 10, backend: API = ConvAPI()) {
self.baseURL = baseURL
self.path = path
self.signer = signer
self.timeout = timeout
self.maxBatchSize = maxBatchSize
self.backend = backend
}
public func dispatch(events: [Event]) -> Promise<Void> {
return send(events: events)
}
public func dispatch(event: Event) -> Promise<Void> {
return send(events: [event])
}
private func send(events: [Event]) -> Promise<Void> {
return backend.request(method: .POST,
baseURL: baseURL,
resource: path,
headers: nil,
params: nil,
body: events,
error: URLDispatcherError.self,
decorator: signer.sign(request:))
}
}
|
//
// CameraFeed.swift
// TikTokTrainer
//
// Created by David Sadowsky on 1/29/21.
//
import Foundation
import AVFoundation
import SwiftUI
import Photos
import Vision
import VideoToolbox
import MetalKit
import Promises
class CameraModel: NSObject,
ObservableObject {
@Published var flashlightOn = false
@Published var isRecording = false
@Published var isOverlayEnabled = true
@Published var inErrorState = false
@Published var isVideoRecorded = false
@Published var hasPermission = false
@Published var currentUIImage: UIImage?
@Published var currentResult: PoseNetResult?
@Published var currentOrientation: AVCaptureDevice.Position = .front
// camera feed
let cameraSession = AVCaptureSession()
var outputURL: URL!
var previousSavedURL: URL = URL(string: "placeholder")!
var imageBounds: CGSize!
var frontCameraDevice: AVCaptureDevice?
var backCameraDevice: AVCaptureDevice?
let videoDataOutput = AVCaptureVideoDataOutput()
var videoFileOutputWriter: AVAssetWriter?
var videoFileOutputWriterInput: AVAssetWriterInput?
var videoFileOutputWriterPool: AVAssetWriterInputPixelBufferAdaptor?
var startTime: Double = 0
// queue for processing video data to posenet
private let posenetDataQueue = DispatchQueue(label: "dev.hunterjarrell.t3.posenetDataQueue")
private let sessionQueue = DispatchQueue(label: "dev.hunterjarrell.t3.avSessionQueue")
let approvedJointKeys: Set<VNHumanBodyPoseObservation.JointName> = [
.neck,
.rightShoulder,
.rightElbow,
.rightWrist,
.rightHip,
.rightKnee,
.rightAnkle,
.root,
.leftAnkle,
.leftKnee,
.leftElbow,
.leftHip,
.leftWrist,
.leftElbow,
.leftShoulder,
.nose,
.leftEye,
.rightEye,
.leftEar,
.rightEar
]
func checkPermissionsAndSetup(_ permissions: PermissionHandler) {
permissions.checkCameraPermissions().then(on: sessionQueue) {
self.setup()
}.then(on: .main) {
self.hasPermission = true
}.catch(on: .main) { err in
print("Error checking camera permissions. Error: \(err)")
self.hasPermission = false
}
}
private func setupInput() -> Bool {
self.frontCameraDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front)
self.backCameraDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back)
guard frontCameraDevice != nil && backCameraDevice != nil else {
print("Could not find a front camera nor back camera.")
return false
}
guard let device = self.currentOrientation == .front ? self.frontCameraDevice : self.backCameraDevice else {
print("Could not create device for current orientation \(currentOrientation)")
return false
}
guard let input = try? AVCaptureDeviceInput(device: device) else {
print("Could not create input for device \(device)")
return false
}
self.cameraSession.inputs.forEach { existingInput in
self.cameraSession.removeInput(existingInput)
}
guard self.cameraSession.canAddInput(input) else {
print("Cannot add input to session.")
return false
}
self.cameraSession.addInput(input)
return true
}
private func setupOutput() -> Bool {
self.cameraSession.outputs.forEach { existingOutput in
self.cameraSession.removeOutput(existingOutput)
}
self.videoDataOutput.alwaysDiscardsLateVideoFrames = true
self.videoDataOutput.setSampleBufferDelegate(self, queue: self.posenetDataQueue)
guard self.cameraSession.canAddOutput(self.videoDataOutput) else {
print("Cannot add video data output")
return false
}
self.cameraSession.addOutput(self.videoDataOutput)
self.videoDataOutput.connections.first?.videoOrientation = .portrait
return true
}
func setup() {
self.sessionQueue.async {
if self.cameraSession.isRunning {
self.cameraSession.stopRunning()
}
self.cameraSession.beginConfiguration()
if self.cameraSession.canSetSessionPreset(.high) {
self.cameraSession.sessionPreset = .high
}
self.cameraSession.automaticallyConfiguresCaptureDeviceForWideColor = true
let inputSuccess = self.setupInput()
if !inputSuccess {
self.currentOrientation = self.currentOrientation == .front ? .back : .front
let secondAttempt = self.setupInput()
guard secondAttempt else {
self.inErrorState = true
print("Could not setup camera input")
return
}
}
let outputSuccess = self.setupOutput()
guard outputSuccess else {
self.inErrorState = true
print("Could not setup camera output")
return
}
self.cameraSession.commitConfiguration()
self.cameraSession.startRunning()
self.setupWriter()
}
}
func reset() {
DispatchQueue.main.async {
self.isRecording = false
self.isOverlayEnabled = true
self.inErrorState = false
self.isVideoRecorded = false
self.setup()
}
}
func setupWriter() {
guard !self.isRecording else { return }
let device = self.currentOrientation == .front ? self.frontCameraDevice : self.backCameraDevice
if (device?.isSmoothAutoFocusSupported)! {
do {
try device?.lockForConfiguration()
device?.isSmoothAutoFocusEnabled = false
device?.unlockForConfiguration()
} catch {
print("Error setting configuration: \(error)")
}
}
// generate a url for where this video will be saved
self.outputURL = self.tempURL()
do {
try self.videoFileOutputWriter = AVAssetWriter(outputURL: self.outputURL, fileType: .mov)
let videoSettings = self.videoDataOutput.recommendedVideoSettingsForAssetWriter(writingTo: .mov)
self.videoFileOutputWriterInput = AVAssetWriterInput(mediaType: .video, outputSettings: videoSettings)
self.videoFileOutputWriterInput?.expectsMediaDataInRealTime = true
self.videoFileOutputWriterPool = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: self.videoFileOutputWriterInput!,
sourcePixelBufferAttributes: nil)
if self.videoFileOutputWriter?.canAdd(self.videoFileOutputWriterInput!) ?? false {
self.videoFileOutputWriter?.add(self.videoFileOutputWriterInput!)
self.videoFileOutputWriter!.startWriting()
} else {
self.isRecording = false
}
} catch {
print("Error setting up video file output. Error: \(error)")
self.isRecording = false
}
}
// MARK: - Recording
func startRecording() {
self.isVideoRecorded = false
self.isRecording = true
self.videoFileOutputWriter?.startSession(atSourceTime: .zero)
}
func stopRecording(isEarly: Bool) {
self.isRecording = false
if self.flashlightOn {
self.toggleFlash()
}
guard !isEarly else {
DispatchQueue.main.async {
self.isVideoRecorded = false
}
self.setup()
return
}
guard let output = self.videoFileOutputWriter else {
return
}
output.finishWriting {
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: self.outputURL)
}) { saved, error in
if saved {
DispatchQueue.main.async {
self.isVideoRecorded = true
}
self.previousSavedURL = self.outputURL
self.setup()
} else {
DispatchQueue.main.async {
self.isVideoRecorded = false
}
print("Could not save video at url \(String(describing: self.outputURL))", error as Any)
}
}
}
// turn off flashlight if it's on
if self.flashlightOn {
self.toggleFlash()
}
}
/// Gets the document directory.
/// From: https://www.hackingwithswift.com/books/ios-swiftui/writing-data-to-the-documents-directory
func getDocumentsDirectory() -> URL {
// find all possible documents directories for this user
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
// just send back the first one, which ought to be the only one
return paths[0]
}
func tempURL() -> URL? {
let directory = getDocumentsDirectory()
let path = directory.appendingPathComponent(NSUUID().uuidString + ".mov")
return path
}
func switchCameraInput() {
self.currentOrientation = self.currentOrientation == .front ? .back : .front
self.setup()
}
func toggleFlash() {
self.flashlightOn.toggle()
guard self.currentOrientation == .back else { return }
guard let device = self.backCameraDevice else { return }
guard device.hasTorch else { return }
do {
try device.lockForConfiguration()
if device.torchMode == .on {
device.torchMode = .off
} else {
try device.setTorchModeOn(level: 1.0)
}
device.unlockForConfiguration()
} catch {
print("Could not toggle device flashlight. Error: \(error)")
}
}
}
// MARK: - Vision
extension CameraModel: AVCaptureVideoDataOutputSampleBufferDelegate {
func emptyPose() {
DispatchQueue.main.async {
self.currentResult = PoseNetResult(points: [:], imageSize: nil)
}
}
func bodyPoseHandler(request: VNRequest, error: Error?) {
guard error == nil else { return emptyPose() }
guard let observations = request.results as? [VNRecognizedPointsObservation] else { return emptyPose() }
guard !observations.isEmpty else {return emptyPose()}
// Process each observation to find the recognized body pose points.
observations.forEach { processObservation($0) }
}
func processObservation(_ observation: VNRecognizedPointsObservation) {
// Retrieve all joints.
guard let recognizedPoints = try? observation.recognizedPoints(forGroupKey: .all) else { return emptyPose() }
guard observation.confidence > 0.6 else { return emptyPose() }
var parsedPoints: [VNHumanBodyPoseObservation.JointName: CGPoint] = [:]
// collect all non-nil points
for pnt in recognizedPoints {
let jointName = VNHumanBodyPoseObservation.JointName(rawValue: pnt.key)
if pnt.value.confidence <= 0 || !approvedJointKeys.contains(jointName) {
continue
}
parsedPoints[jointName] = pnt.value.location
}
DispatchQueue.main.async {
self.currentResult = PoseNetResult(points: parsedPoints, imageSize: nil)
}
}
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
if let pixelBuffer = sampleBuffer.imageBuffer {
connection.isVideoMirrored = self.currentOrientation == .front
let timestamp = CMSampleBufferGetPresentationTimeStamp(sampleBuffer).seconds
// Attempt to lock the image buffer to gain access to its memory.
guard CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly) == kCVReturnSuccess
else {
return
}
// Create Core Graphics image placeholder.
var cgImage: CGImage?
// Create a Core Graphics bitmap image from the pixel buffer.
VTCreateCGImageFromCVPixelBuffer(pixelBuffer, options: nil, imageOut: &cgImage)
if self.isRecording && self.videoFileOutputWriterInput?.isReadyForMoreMediaData ?? false {
let time = CMTime(seconds: timestamp - self.startTime - 0.01, preferredTimescale: CMTimeScale(600))
self.videoFileOutputWriterPool?.append(pixelBuffer, withPresentationTime: time)
}
if !self.isRecording {
self.startTime = timestamp
}
let uiImage = UIImage(cgImage: cgImage!)
// Release the image buffer.
CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly)
if self.isOverlayEnabled {
let requestHandler = VNImageRequestHandler(cgImage: cgImage!)
// Create a new request to recognize a human body pose.
let request = VNDetectHumanBodyPoseRequest(completionHandler: bodyPoseHandler)
do {
// Perform the body pose-detection request.
try requestHandler.perform([request])
} catch {
print("Unable to perform the request: \(error).")
emptyPose()
}
} else {
emptyPose()
}
DispatchQueue.main.async {
self.currentUIImage = uiImage
}
}
}
}
|
//: Please build the scheme 'RxSwiftPlayground' first
import UIKit
import RxSwift
import RxCocoa
// Support code -- DO NOT REMOVE
class TimelineView<E>: TimelineViewBase, ObserverType where E: CustomStringConvertible {
static func make() -> TimelineView<E> {
let view = TimelineView(frame: CGRect(x: 0, y: 0, width: 400, height: 100))
view.setup()
return view
}
public func on(_ event: Event<E>) {
switch event {
case .next(let value):
add(.Next(String(describing: value)))
case .completed:
add(.Completed())
case .error(_):
add(.Error())
}
}
}
// Buffering operators
// 3. window() - kontrolisani buffering, radi veoma slicno kao buffer(), samo sto za razliku od njega emituje Observable bufferovanih elemenata umesto emitovanja niza
let elementsperSecond = 3
let windowTimeSpan: RxTimeInterval = 4
let windowMaxCount = 10
let sourceObservable = PublishSubject<String>()
let sourceTimeline = TimelineView<String>.make()
let stack = UIStackView.makeVertical([
UILabel.makeTitle("Window"),
UILabel.make("Emitted elements \(elementsperSecond) per sec:"),
sourceTimeline,
UILabel.make("Windowed observables at most \(windowMaxCount) every \(windowTimeSpan) sec:")
])
let timer = DispatchSource.timer(interval: 1.0 / Double(elementsperSecond), queue: .main) {
sourceObservable.onNext("$$")
}
_ = sourceObservable.subscribe(sourceTimeline)
_ = sourceObservable.window(timeSpan: windowTimeSpan, count: windowMaxCount, scheduler: MainScheduler.instance).flatMap({ (windowedObservable) -> Observable<(TimelineView<Int>,String?)> in
let timeline = TimelineView<Int>.make()
stack.insert(timeline, at: 4)
stack.keep(atMost: 8)
return windowedObservable
.map({ value in (timeline, value) })
.concat(Observable.just(timeline, nil))
}).subscribe(onNext: { (tuple) in
let (timeline, value) = tuple
if let value = value {
timeline.add(.Next(value))
} else {
timeline.add(.Completed(true))
}
})
// svaki put kada flatMap dobije novi Observable, ubacuje se novi timeline view
// onda se mapira observable elemenata kao observable tapla, ovo treba zbog prenosenja obe vrednosti i vremena kada ih prikazati
// kad se ovi unutrasnji observables elemenata zavrsi, obavim konkatenaciju u jedan tuple
let hostView = setupHostView()
hostView.addSubview(stack)
hostView
// X---|---|---|---|---|---|---|---$$ ovo su emitovani elementi na tri sekunde
// windowed observables - najvise 10 na svakih 4 sekunde
// |---$$
// |---|---|---|---$$
// C
// X|---|---|---|---$$
// C
// X|---|---$$
|
//
// User.swift
// Mixtape
//
// Created by Eva Marie Bresciano on 7/11/16.
// Copyright © 2016 Eva Bresciano. All rights reserved.
//
import Foundation
import CloudKit
import CoreData
class User: SyncableObject, SearchableRecord, CloudKitManagedObject {
static let kType = "User"
static let kUsername = "username"
private let kUsername = "username"
convenience init(username: String, playlist: Playlist? = nil, song: Song? = nil, context: NSManagedObjectContext = Stack.sharedStack.managedObjectContext){
guard let entity = NSEntityDescription.entityForName(User.kType, inManagedObjectContext: context) else { fatalError() }
self.init(entity: entity, insertIntoManagedObjectContext: context)
self.username = username
self.recordName = NSUUID().UUIDString
}
convenience init?(dictionary:[String:AnyObject]) {
self.init()
guard let username = dictionary[kUsername] as? String else {
return nil }
self.username = username
}
@objc func matchesSearchTerm(searchTerm: String) -> Bool {
return username.containsString(searchTerm) ?? false
}
var recordType: String = User.kType
var cloudKitRecord: CKRecord? {
let recordID = CKRecordID(recordName: recordName)
let record = CKRecord(recordType: recordType, recordID: recordID)
record[User.kUsername] = username
return record
}
convenience required init?(record: CKRecord, context: NSManagedObjectContext = Stack.sharedStack.managedObjectContext) {
guard let username = record[User.kUsername] as? String
else {
return nil
}
guard let entity = NSEntityDescription.entityForName(User.kType, inManagedObjectContext: context)
else { fatalError("Error: CoreData failed to create entity from entity description. \(#function)") }
self.init(entity: entity, insertIntoManagedObjectContext: context)
self.username = username
self.recordIDData = NSKeyedArchiver.archivedDataWithRootObject(record.recordID)
self.recordName = record.recordID.recordName
}
func updateWithRecord(record: CKRecord) {
self.recordIDData = NSKeyedArchiver.archivedDataWithRootObject(record)
}
}
|
//
// PrimerCollectionViewCell.swift
// StickyCollectionView
//
// Created by Bogdan Matveev on 02/02/16.
// Copyright © 2016 Bogdan Matveev. All rights reserved.
//
import UIKit
class PrimerCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var lessonLabel: UILabel!
var lesson: String? {
didSet {
lessonLabel.text = lesson
}
}
}
|
//
// BaseComponents.swift
// SwiftUI_Test
//
// Created by Andres Felipe Ocampo Eljaiesk on 01/11/2019.
// Copyright © 2019 icologic. All rights reserved.
//
import Foundation
import SwiftUI
/// CustomCellOne
struct CustomCellOne : View {
var number : Int
var body : some View{
VStack(alignment: .center) {
HStack{
Rectangle()
.foregroundColor(.red)
.background(Color.white)
.cornerRadius(3)
.frame(width:100)
Text("Persona- \(number)")
}
Image(systemName: "p.circle.fill")
.font(.largeTitle)
.background(Color.yellow)
}
}
}
/// CustomCellTwo
struct CustomCellTwo : View {
var user: PeopleModelElement
init(user: PeopleModelElement) {
self.user = user
}
var body: some View {
return GeometryReader { geometry in
VStack() {
Spacer()
Text("\(self.user.name ?? "") \(self.user.email ?? "")")
Text("\(self.user.city ?? "")")
Text("\(self.user.creditcard ?? "")")
Divider().padding(.vertical, 12)
}.frame(width: geometry.size.width,
height: geometry.size.height)
}
}
}
struct ActivityIndicator: UIViewRepresentable {
@Binding var isAnimating: Bool
let style: UIActivityIndicatorView.Style
func makeUIView(context: UIViewRepresentableContext<ActivityIndicator>) -> UIActivityIndicatorView {
return UIActivityIndicatorView(style: style)
}
func updateUIView(_ uiView: UIActivityIndicatorView, context: UIViewRepresentableContext<ActivityIndicator>) {
isAnimating ? uiView.startAnimating() : uiView.stopAnimating()
}
}
struct LoadingView<Content>: View where Content: View {
@Binding var isShowing: Bool
var content: () -> Content
var body: some View {
GeometryReader { geometry in
ZStack(alignment: .center) {
self.content()
.disabled(self.isShowing)
.blur(radius: self.isShowing ? 3 : 0)
VStack {
Text("Loading...")
ActivityIndicator(isAnimating: .constant(true), style: .large)
}
.frame(width: geometry.size.width / 2,
height: geometry.size.height / 5)
.background(Color.secondary.colorInvert())
.foregroundColor(Color.primary)
.cornerRadius(20)
.opacity(self.isShowing ? 1 : 0)
}
}
}
}
|
//
// SettingOnBoardingViewController.swift
// DealTyme
//
// Created by Ali Apple on 14/02/2019.
// Copyright © 2019 Ali Apple. All rights reserved.
//
import UIKit
class SettingsOnBoardingViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UITextFieldDelegate, UICollectionViewDelegateFlowLayout {
let collectionView: UICollectionView = {
let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
let collection = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
layout.scrollDirection = .horizontal
collection.backgroundColor = .clear
collection.alwaysBounceHorizontal = true
collection.layer.cornerRadius = 20
collection.layer.borderWidth = 2
collection.clipsToBounds = true
collection.layer.borderColor = UIColor(r: 246, g: 249, b: 248).cgColor
collection.translatesAutoresizingMaskIntoConstraints = false
collection.isScrollEnabled = false
return collection
}()
let cellId = "cellId"
let pageControl: UIPageControl = {
let pg = UIPageControl()
pg.translatesAutoresizingMaskIntoConstraints = false
pg.currentPage = 0
pg.numberOfPages = 4
pg.currentPageIndicatorTintColor = .black
pg.pageIndicatorTintColor = .lightGray
pg.sizeToFit()
pg.isEnabled = false
return pg
}()
var skipButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = .clear
button.setTitle("Skip", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitleColor(UIColor.black, for: .normal)
button.layer.borderColor = UIColor.gray.cgColor
button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
button.addTarget(self, action: #selector(handleSkip), for:.touchUpInside)
return button
}()
@objc func handleSkip(){
// pageControl.next += 1
}
var nextButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = UIColor(r: 80, g:169, b:53)
button.setTitle("Next", for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitleColor(UIColor.white, for: .normal)
button.layer.cornerRadius = 50/2
button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
button.addTarget(self, action: #selector(handleNext), for:.touchUpInside)
return button
}()
@objc func handleNext(){
let nextPath = min(self.pageControl.currentPage + 1, 3)
self.pageControl.currentPage = nextPath
let indexPath = IndexPath(item: nextPath, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
// pageControl.next += 1
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
collectionView.delegate = self
collectionView.dataSource = self
view.addSubview(self.collectionView)
self.collectionView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30).isActive = true
self.collectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: 30).isActive = true
self.collectionView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.65).isActive = true
self.collectionView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -30).isActive = true
self.collectionView.register(OnBoardingViewCell.self, forCellWithReuseIdentifier: cellId)
self.collectionView.isPagingEnabled = true
setupViews()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
self.tabBarController?.tabBar.isHidden = true
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! OnBoardingViewCell
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.collectionView.frame.width, height: self.collectionView.frame.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
// let topInset = self.view.frame.height - self.collectionView.contentSize.height
// if topInset < self.collectionView.frame.height{
// return UIEdgeInsets(top: topInset, left: 0, bottom: 0, right: 0)
// }
// else {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
// }
}
func setupViews(){
view.addSubview(pageControl)
pageControl.topAnchor.constraint(equalTo: collectionView.bottomAnchor, constant: 10).isActive = true
pageControl.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
view.addSubview(nextButton)
nextButton.topAnchor.constraint(equalTo: pageControl.bottomAnchor, constant: 20).isActive = true
nextButton.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -100).isActive = true
nextButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
nextButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
view.addSubview(skipButton)
skipButton.topAnchor.constraint(equalTo: nextButton.bottomAnchor, constant: 20).isActive = true
skipButton.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -100).isActive = true
skipButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
skipButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
}
//class OnBoardingCell: BaseCell {
//
// let mainView: UIView = {
// var view = UIView()
// view.translatesAutoresizingMaskIntoConstraints = false
// view.backgroundColor = .white
// view.layer.borderColor = UIColor(r: 246, g: 249, b: 248).cgColor
// view.layer.borderWidth = 2
// view.clipsToBounds = true
// view.layer.cornerRadius = 20
// return view
// }()
//
// let backCoverImageView: UIImageView = {
// var imageView = UIImageView()
// imageView.image = UIImage(named: "greenbackcover")
// // imageView.contentMode = .scaleAspectFit
// imageView.translatesAutoresizingMaskIntoConstraints = false
// return imageView
// }()
//
// let dealTymeWhiteImageView: UIImageView = {
// var imageView = UIImageView()
// imageView.image = UIImage(named: "logowhite")
// imageView.contentMode = .scaleAspectFit
// imageView.translatesAutoresizingMaskIntoConstraints = false
// return imageView
// }()
//
//
// override func setupViews() {
// super.setupViews()
//
// self.addSubview(mainView)
// mainView.widthAnchor.constraint(equalTo: self.widthAnchor, constant: -60).isActive = true
// mainView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.7).isActive = true
// mainView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
// mainView.topAnchor.constraint(equalTo: self.topAnchor, constant: 30).isActive = true
//
// mainView.addSubview(backCoverImageView)
// backCoverImageView.widthAnchor.constraint(equalTo: mainView.widthAnchor).isActive = true
// backCoverImageView.heightAnchor.constraint(equalTo: mainView.heightAnchor, multiplier: 0.6).isActive = true
// backCoverImageView.centerXAnchor.constraint(equalTo: mainView.centerXAnchor).isActive = true
// backCoverImageView.topAnchor.constraint(equalTo: mainView.topAnchor).isActive = true
//
// backCoverImageView.addSubview(dealTymeWhiteImageView)
// dealTymeWhiteImageView.widthAnchor.constraint(equalToConstant: 180).isActive = true
// dealTymeWhiteImageView.heightAnchor.constraint(equalToConstant: 100).isActive = true
// dealTymeWhiteImageView.centerXAnchor.constraint(equalTo: backCoverImageView.centerXAnchor).isActive = true
// dealTymeWhiteImageView.topAnchor.constraint(equalTo: backCoverImageView.topAnchor, constant: 50).isActive = true
// }
//
//}
//
//
//
|
import Combine
import ComposableArchitecture
import SwiftUI
import SwiftUIRefresh
struct EventListView: View {
let store: Store<EventListState, EventListAction>
init(store: Store<EventListState, EventListAction>) {
self.store = store
UINavigationBar.appearance().tintColor = .systemPink
}
var body: some View {
WithViewStore(store) { viewStore in
NavigationView {
List {
ForEach(viewStore.events, id: \.id) { event in
NavigationLink(destination: EventDetailsView(
store: Store(
initialState: EventDetailsState(id: event.id),
reducer: eventDetailsReducer,
environment: EventDetailsEnvironment(facade: EventFacade()))))
{
EventRow(event: event)
}
}
}
.navigationBarTitle("Events")
.alert(isPresented: viewStore.binding(get: \.alert, send: .dismissAlert)) {
return Alert(title: Text("Network failure"), message: Text(viewStore.alertText))
}
.pullToRefresh(isShowing: viewStore.binding(get: \.isRefreshing,
send: EventListAction.refreshingChanged)) {
viewStore.send(.fetchEvents)
}
.onAppear(perform: {
viewStore.send(.fetchEvents)
})
}
}
}
}
|
class Solution {
func numsSameConsecDiff(_ N: Int, _ K: Int) -> [Int] {
var result: [Int] = [Int]()
if N <= 1 {
for i in 0...9 {
result.append(i)
}
return result
}
var resultSet: Set<Int> = Set<Int>()
func addNums(_ cand: Int, _ d: Int, _ count: Int) {
if count == N {
resultSet.insert(cand)
return
}
if d - K >= 0 {
addNums(cand * 10 + (d - K), d - K, count + 1)
}
if d + K <= 9 {
addNums(cand * 10 + (d + K), d + K, count + 1)
}
}
for i in 1...9 {
addNums(i, i, 1)
}
for n in resultSet {
result.append(n)
}
return result
}
}
|
//
// ActionDelegate.swift
// BitBucketList
//
// Created by Sreekanth on 3/9/21.
//
import Foundation
public protocol DelegateAction {}
public protocol ActionDelegate: class {
func actionSender(didReceiveAction action: DelegateAction)
}
|
//
// ScreenShotCell.swift
// appstoreSearch
//
// Created by Elon on 21/03/2019.
// Copyright © 2019 Elon. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
final class ScreenShotCell: UITableViewCell {
@IBOutlet weak var imageCollectionView: UICollectionView!
private let disposeBag = DisposeBag()
static let identifier: String = "ScreenShotCell"
lazy var dataSource = BehaviorRelay(value: [String]())
override func awakeFromNib() {
super.awakeFromNib()
imageCollectionView.dataSource = nil
imageCollectionView.delegate = nil
dataBinding()
}
}
extension ScreenShotCell {
private func dataBinding() {
dataSource
.observeOn(MainScheduler.instance)
.bind(to: imageCollectionView.rx.items) { collectionView, item, urlString in
let index = IndexPath(item: item, section: 0)
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: ScreenShotImageCell.identifier,
for: index
) as! ScreenShotImageCell
cell.setImage(by: urlString)
return cell
}
.disposed(by: disposeBag)
}
func setScreenShot(with model: ScreenShots) {
dataSource.accept(model.urlStrings)
}
}
|
//
// SourcesVC.swift
// ThePaper
//
// Created by Gautier Billard on 24/03/2020.
// Copyright © 2020 Gautier Billard. All rights reserved.
//
import UIKit
class SourcesVC: UIViewController {
private var collectionView: UICollectionView!
private var images = ["le-monde","les-echos","liberation","lequipe"]
private var mediaNames = ["le-monde": "Le Monde", "les-echos":"Les Echos","liberation":"Libération","lequipe":"L'Equipe"]
override func viewDidLoad() {
super.viewDidLoad()
getmediaForCountry()
addCollectionView()
addObservers()
}
private func addObservers() {
let notificationName = Notification.Name(rawValue: K.shared.locationChangeNotificationName)
NotificationCenter.default.addObserver(self, selector: #selector(updateMedia), name: notificationName, object: nil)
}
@objc private func updateMedia() {
getmediaForCountry()
self.collectionView.reloadData()
}
fileprivate func getmediaForCountry() {
let countryCode = localISOCode
print(countryCode)
switch countryCode {
case "gb":
images = K.shared.gb().images
mediaNames = K.shared.gb().mediaNames
case "cn":
images = K.shared.zh().images
mediaNames = K.shared.zh().mediaNames
case "de":
images = K.shared.de().images
mediaNames = K.shared.de().mediaNames
case "it":
images = K.shared.it().images
mediaNames = K.shared.it().mediaNames
case "us":
images = K.shared.us().images
mediaNames = K.shared.us().mediaNames
default:
break
}
}
fileprivate func addCollectionView() {
let spacing:CGFloat = 10.0
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.minimumLineSpacing = spacing
layout.minimumInteritemSpacing = spacing
layout.sectionInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing)
collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: 100, height: 100), collectionViewLayout: layout)
collectionView.backgroundColor = .clear
collectionView.showsHorizontalScrollIndicator = false
collectionView.delegate = self
collectionView.dataSource = self
collectionView.isScrollEnabled = true
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellID")
self.view.addSubview(collectionView)
//view
let fromView = collectionView!
//relative to
let toView = self.view!
fromView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([fromView.leadingAnchor.constraint(equalTo: toView.leadingAnchor, constant: 0),
fromView.trailingAnchor.constraint(equalTo: toView.trailingAnchor, constant: 0),
fromView.topAnchor.constraint(equalTo: toView.topAnchor, constant: 10),
fromView.bottomAnchor.constraint(equalTo: toView.bottomAnchor, constant: -10)])
}
}
extension SourcesVC: UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath)
let imageView = UIImageView()
imageView.backgroundColor = .gray
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.layer.cornerRadius = 8
imageView.image = UIImage(named: images[indexPath.row])
cell.addSubview(imageView)
//view
let fromView = imageView
//relative to
let toView = cell
fromView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([fromView.leadingAnchor.constraint(equalTo: toView.leadingAnchor, constant: 0),
fromView.trailingAnchor.constraint(equalTo: toView.trailingAnchor,constant: 0),
fromView.topAnchor.constraint(equalTo: toView.topAnchor, constant: 0),
fromView.bottomAnchor.constraint(equalTo: toView.bottomAnchor,constant: 0)])
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (self.view.frame.width) / 2 - 15
let height = width * 1.25
let size = CGSize(width: width, height: height)
return size
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let media = images[indexPath.row]
let mediaName = mediaNames[media]
let cvc = TableVC()
cvc.hasATitleBar = true
cvc.urlString = "https://newsapi.org/v2/top-headlines?pageSize=100&sources=\(media)"
cvc.mediaName = mediaName
addChild(cvc)
cvc.didMove(toParent: self)
self.view.addSubview(cvc.view)
//view
let fromView = cvc.view!
//relative to
let toView = self.view!
fromView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([fromView.leadingAnchor.constraint(equalTo: toView.leadingAnchor, constant: 0),
fromView.trailingAnchor.constraint(equalTo: toView.trailingAnchor, constant: 0),
fromView.topAnchor.constraint(equalTo: toView.topAnchor, constant: 0),
fromView.bottomAnchor.constraint(equalTo: toView.bottomAnchor,constant: 0)])
}
}
|
import XCTest
import ComposableArchitecture
@testable import ExerciseTimer
final class ExerciseTimerUnitTests: XCTestCase {
// NB:- Syntax is a bit unusual if unfamilar with ComposableArchitecture.
// TestStore handles actions and compares its mutated state against
// the expected mutation passed in via the trailing closure.
// Absence of a closure is an assertion that there should be no state changes.
func testStartSession() {
let scheduler = DispatchQueue.test
let store = TestStore(
initialState: ExerciseTimerState(),
reducer: exerciseTimerReducer,
environment: .init(mainQueue: scheduler.eraseToAnyScheduler())
)
store.send(.sessionStarted) { $0.currentTimerState = .performingRep }
// ComposableArchitecture requires all effects to finish/be handled in tests, so we have to stop the timer.
// TODO: dluo - see if there is a way to cancel the timer without needing to send this action so this can be a true unit test
store.send(.stopButtonTapped) { $0.currentTimerState = .stopped }
}
func testStopTimerDuringRep() {
var initialState = ExerciseTimerState()
initialState.currentTimerState = .performingRep
let scheduler = DispatchQueue.test
let store = TestStore(
initialState: initialState,
reducer: exerciseTimerReducer,
environment: .init(mainQueue: scheduler.eraseToAnyScheduler())
)
store.send(.stopButtonTapped) { $0.currentTimerState = .stopped }
}
func testStopTimerBetweenReps() {
var initialState = ExerciseTimerState()
initialState.currentTimerState = .betweenReps
initialState.secondsRemainingForRep = 0
let scheduler = DispatchQueue.test
let store = TestStore(
initialState: initialState,
reducer: exerciseTimerReducer,
environment: .init(mainQueue: scheduler.eraseToAnyScheduler())
)
store.send(.stopButtonTapped) { $0.currentTimerState = .stopped }
}
func testStopTimerBetweenSets() {
var initialState = ExerciseTimerState()
initialState.currentTimerState = .betweenSets
initialState.secondsRemainingForRep = 0
initialState.currentRep = ExerciseTimerState.repsPerSet
let scheduler = DispatchQueue.test
let store = TestStore(
initialState: initialState,
reducer: exerciseTimerReducer,
environment: .init(mainQueue: scheduler.eraseToAnyScheduler())
)
store.send(.stopButtonTapped) { $0.currentTimerState = .stopped }
}
func testStopTimerWhenStopped() {
var initialState = ExerciseTimerState()
initialState.currentTimerState = .stopped
let scheduler = DispatchQueue.test
let store = TestStore(
initialState: initialState,
reducer: exerciseTimerReducer,
environment: .init(mainQueue: scheduler.eraseToAnyScheduler())
)
// Pressing Stop when timer is already stopped should NOT mutate timer state.
store.send(.stopButtonTapped)
}
func testStopTimerWhenFinished() {
var initialState = ExerciseTimerState()
initialState.currentTimerState = .finished
initialState.secondsRemainingForRep = 0
initialState.currentRep = ExerciseTimerState.repsPerSet
initialState.currentSet = initialState.totalNumberOfSets
let scheduler = DispatchQueue.test
let store = TestStore(
initialState: initialState,
reducer: exerciseTimerReducer,
environment: .init(mainQueue: scheduler.eraseToAnyScheduler())
)
// Pressing Stop when timer is already finished should NOT mutate timer state.
store.send(.stopButtonTapped)
}
func testTimerTickWithTimerStopped() {
let scheduler = DispatchQueue.test
let store = TestStore(
initialState: .init(),
reducer: exerciseTimerReducer,
environment: .init(mainQueue: scheduler.eraseToAnyScheduler())
)
// No state changes expected
store.send(.timerTicked)
}
func testTimerTickWithTimerFinished() {
var initialState = ExerciseTimerState()
initialState.currentTimerState = .finished
let scheduler = DispatchQueue.test
let store = TestStore(
initialState: initialState,
reducer: exerciseTimerReducer,
environment: .init(mainQueue: scheduler.eraseToAnyScheduler())
)
// No state changes expected
store.send(.timerTicked)
}
func testTimerTickInRep() {
var initialState = ExerciseTimerState()
initialState.currentTimerState = .performingRep
let scheduler = DispatchQueue.test
let store = TestStore(
initialState: initialState,
reducer: exerciseTimerReducer,
environment: .init(mainQueue: scheduler.eraseToAnyScheduler())
)
let expected = ExerciseTimerState().secondsRemainingForRep - 1
store.send(.timerTicked) { $0.secondsRemainingForRep = expected }
}
func testTimerTickToRepResetPeriod() {
var initialState = ExerciseTimerState()
initialState.currentTimerState = .performingRep
initialState.secondsRemainingForRep = 0
let scheduler = DispatchQueue.test
let store = TestStore(
initialState: initialState,
reducer: exerciseTimerReducer,
environment: .init(mainQueue: scheduler.eraseToAnyScheduler())
)
store.send(.timerTicked) {
$0.secondsRemainingForRep = ExerciseTimerState.secondsPerRep
$0.currentTimerState = .betweenReps
}
}
func testTimerTickToNewRep() {
var initialState = ExerciseTimerState()
initialState.currentTimerState = .betweenReps
let scheduler = DispatchQueue.test
let store = TestStore(
initialState: initialState,
reducer: exerciseTimerReducer,
environment: .init(mainQueue: scheduler.eraseToAnyScheduler())
)
let expected = initialState.currentRep + 1
store.send(.timerTicked) {
$0.currentRep = expected
$0.currentTimerState = .performingRep
}
}
func testTimerTickToRestPeriod() {
var initialState = ExerciseTimerState()
initialState.currentTimerState = .performingRep
initialState.currentRep = ExerciseTimerState.repsPerSet
initialState.secondsRemainingForRep = 0
let scheduler = DispatchQueue.test
let store = TestStore(
initialState: initialState,
reducer: exerciseTimerReducer,
environment: .init(mainQueue: scheduler.eraseToAnyScheduler())
)
store.send(.timerTicked) { $0.currentTimerState = .betweenSets }
}
func testTimerTickInRestPeriod() {
var initialState = ExerciseTimerState()
initialState.currentTimerState = .betweenSets
let scheduler = DispatchQueue.test
let store = TestStore(
initialState: initialState,
reducer: exerciseTimerReducer,
environment: .init(mainQueue: scheduler.eraseToAnyScheduler())
)
let expected = initialState.restPeriodInSeconds - 1
store.send(.timerTicked) { $0.secondsRemainingInRestPeriod = expected }
}
func testTimerTickToNewSet() {
var initialState = ExerciseTimerState()
initialState.currentTimerState = .betweenSets
initialState.secondsRemainingInRestPeriod = 0
let scheduler = DispatchQueue.test
let store = TestStore(
initialState: initialState,
reducer: exerciseTimerReducer,
environment: .init(mainQueue: scheduler.eraseToAnyScheduler())
)
let expected = initialState.currentSet + 1
store.send(.timerTicked) {
$0.currentSet = expected
$0.currentTimerState = .performingRep
$0.secondsRemainingInRestPeriod = initialState.restPeriodInSeconds
}
}
func testTimerTickToSessionEnd() {
var initialState = ExerciseTimerState()
initialState.currentRep = ExerciseTimerState.repsPerSet
initialState.currentSet = initialState.totalNumberOfSets
initialState.currentTimerState = .performingRep
initialState.secondsRemainingForRep = 0
let scheduler = DispatchQueue.test
let store = TestStore(
initialState: initialState,
reducer: exerciseTimerReducer,
environment: .init(mainQueue: scheduler.eraseToAnyScheduler())
)
store.send(.timerTicked) { $0.currentTimerState = .finished }
}
}
|
//
// BaseViewController.swift
// TodoeyRealmAndVIPER
//
// Created by Julio Collado on 9/20/19.
// Copyright © 2019 Julio Collado. All rights reserved.
//
import UIKit
import SVProgressHUD
import SwipeCellKit
class BaseViewController: UIViewController {
var viewWillAppear = false
override func viewDidLoad() {
let color = UIColor(red: 236, green: 240, blue: 241, alpha: 0)
SVProgressHUD.setBackgroundColor(color)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewWillAppear = true
}
func toggleLoading(isOn: Bool) {
if isOn {
SVProgressHUD.show()
} else {
SVProgressHUD.dismiss()
}
}
//Override at view controllers children in order to update model
func updateModel(indexPath: IndexPath) {
}
func animateReloadData(for tableView: UITableView) {
defer { viewWillAppear = false }
if !viewWillAppear {
tableView.reloadData()
return
}
tableView.reloadData()
let cells = tableView.visibleCells
let tableViewHeight = tableView.frame.size.height
cells.forEach{ $0.transform = CGAffineTransform(translationX: 0, y: tableViewHeight)}
var delayCounter: Double = 0
for cell in cells {
UIView.animate(withDuration: 1.75, delay: delayCounter * 0.05, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseOut, animations: {
cell.transform = CGAffineTransform.identity
}, completion: nil)
delayCounter += 1
}
}
}
extension BaseViewController: SwipeTableViewCellDelegate {
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
guard orientation == .right else { return nil }
let deleteAction = SwipeAction(style: .destructive, title: "Delete") { [weak self] action, indexPath in
if let saveSelf = self {
saveSelf.updateModel(indexPath: indexPath)
}
}
deleteAction.image = UIImage(named: CONSTANTS.ICONS_NAME.DELETE_ICON)
return [deleteAction]
}
func tableView(_ tableView: UITableView, editActionsOptionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeOptions {
var options = SwipeOptions()
options.expansionStyle = .destructive
options.transitionStyle = .border
return options
}
}
|
//
// OrderedCoordinate.swift
// GonzagaCampusWalkingTour
//
// Created by Max Heinzelman on 1/26/20.
// Copyright © 2020 Senior Design Group 8. All rights reserved.
//
import Foundation
import MapKit
class OrderedCoordinate {
var coordinate: CLLocationCoordinate2D
var order: Int
init(coordinate: CLLocationCoordinate2D, order: Int) {
self.coordinate = coordinate
self.order = order
}
}
|
//
// TransparentTableView.swift
// Coordinate
//
// Created by James Wilkinson on 23/01/2016.
// Copyright © 2016 James Wilkinson. All rights reserved.
//
import UIKit
class TransparentTableView: UITableView {
var backgroundBlurView: UIVisualEffectView!
override var contentSize: CGSize {
didSet {
self.backgroundBlurView?.frame = CGRect(origin: CGPointZero, size: self.contentSize)
}
}
override var frame: CGRect {
didSet {
let inset = frame.height - CGFloat(1) * self.rowHeight
// FIXME: Should auto-scroll to inset initially (i.e. on init?)
self.contentInset = UIEdgeInsets(top: inset, left: 0.0, bottom: 0.0, right: 0.0)
self.contentOffset = CGPoint(x: 0.0, y: -inset)
}
}
override func layoutSubviews() {
super.layoutSubviews()
if self.backgroundBlurView == nil {
self.backgroundBlurView = UIVisualEffectView(effect: UIBlurEffect(style: .ExtraLight))
self.backgroundBlurView.frame = CGRect(origin: CGPointZero, size: self.contentSize)
self.insertSubview(self.backgroundBlurView, atIndex: 0)
}
}
// Ignore touch if not inside cell or blur background
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
if let _ = self.indexPathForRowAtPoint(point) {
return super.hitTest(point, withEvent: event)
}
if self.backgroundBlurView.pointInside(point, withEvent: event) != false {
return super.hitTest(point, withEvent: event)
}
return nil
}
}
|
//
// StatusBarViewModel.swift
// FlexPomo
//
// Created by Sebastian Hojas on 16/04/2017.
// Copyright © 2017 Sebastian Hojas. All rights reserved.
//
import Foundation
import ReactiveSwift
import Result
class StatusBarViewModel {
weak private var pomoViewModel: PomoViewModel?
init(pomoViewModel: PomoViewModel) {
self.pomoViewModel = pomoViewModel
}
var title: String? {
return pomoViewModel?.currentPomo.map {
$0.status.description + $0.description
}
}
public func action() {
pomoViewModel?.action()
}
}
extension PomoStatus: CustomStringConvertible {
var description: String {
switch self {
case .normal: return ""
case .error: return "!! "
case .warning: return "! "
case .paused: return "> "
}
}
}
|
//
// LoginViewModel.swift
// BangJon
//
// Created by ZISACHMAD on 16/05/21.
//
import SwiftUI
import Firebase
class LoginViewModel: ObservableObject {
@Published var countryCode = ""
@Published var phNumber = ""
@Published var showAlert = false
@Published var errorMsg = ""
@Published var ID = ""
@Published var isLoading = false
// KIRIM OTP VERFIVIKASI NOMOR HP USER
func verifyUser() {
withAnimation{isLoading = true}
// UNDO INI JIKA TEST PAKAI HP DAN NOMOR BENERAN
Auth.auth().settings?.isAppVerificationDisabledForTesting = true
//
PhoneAuthProvider.provider().verifyPhoneNumber("+\(countryCode + phNumber)", uiDelegate: nil) { ID, err in
if let error = err {
self.errorMsg = error.localizedDescription
self.showAlert.toggle()
return
}
self.ID = ID!
self.alertWithTF()
}
}
// ALERT UNTUK KODE OTP
func alertWithTF() {
let alert = UIAlertController(title: "Verification", message: "Enter OTP Code", preferredStyle: .alert)
alert.addTextField { txt in
txt.placeholder = "123456"
}
alert.addAction(UIAlertAction(title: "Cancel", style: .destructive, handler: nil))
alert.addAction(UIAlertAction(title: "Ok", style: .destructive, handler: { _ in
if let code = alert.textFields?[0].text {
self.LoginUser(code: code)
}
else {
self.reportError()
}
}))
UIApplication.shared.windows.first?.rootViewController?.present(alert, animated: true, completion: nil)
}
// BERHASIL LOGIN
func LoginUser(code: String) {
let credential = PhoneAuthProvider.provider().credential(withVerificationID: self.ID, verificationCode: code)
Auth.auth().signIn(with: credential) { result, err in
if let error = err {
self.errorMsg = error.localizedDescription
self.showAlert.toggle()
return
}
print("success")
}
}
// JIKA ADA KESALAHAN
func reportError() {
self.errorMsg = "Please coba lagi jon"
self.showAlert.toggle()
}
}
|
//
// MapController.swift
// Project1
//
// Created by Raffaele P on 23/07/16.
// Copyright © 2016 Gruppo2. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class MapController: UIViewController, CLLocationManagerDelegate {
var ad: AppDelegate? = UIApplication.sharedApplication().delegate as? AppDelegate
@IBOutlet weak var mapView: MKMapView!
var locationManager = CLLocationManager ()
var initMap = true
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
//Rimuovo all Annotations
let annotationsToRemove = mapView.annotations.filter { $0 !== mapView.userLocation }
mapView.removeAnnotations( annotationsToRemove )
if let shops = ad?.dataShop {
for shop in shops{
let annotation = MKPointAnnotation()
let numberFormatter = NSNumberFormatter()
let numberLat = numberFormatter.numberFromString("\(shop["lat"]!)") as! Double
let numberLng = numberFormatter.numberFromString("\(shop["lng"]!)") as! Double
var coordinates = CLLocationCoordinate2D()
coordinates.latitude = numberLat
coordinates.longitude = numberLng
annotation.coordinate = coordinates
annotation.title = shop["name"] as?String
annotation.subtitle = "Totale Speso: " + "\(shop["totalExpense"]!)" + "€"
self.mapView.addAnnotation(annotation)
}
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.delegate = self
self.locationManager.startUpdatingLocation()
}
}
//override func viewWillAppear(animated: Bool) {
//self.mapView.showsUserLocation = true
// }
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
if let location = locations.last {
if self.initMap {
var region : MKCoordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 50, 50)
var span = MKCoordinateSpan()
//print("\(location.coordinate)")
region.center = location.coordinate
self.initMap = false
UIView.animateWithDuration(8, animations: {
span.latitudeDelta = self.mapView.region.span.latitudeDelta * 0.09
span.longitudeDelta = self.mapView.region.span.longitudeDelta * 0.09
region.span = span;
self.mapView.setRegion(region, animated: 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.
}
*/
}
|
//
// GameViewController.swift
// Teachify
//
// Created by Normen Krug on 08.04.18.
// Copyright © 2018 Christian Pfeiffer. All rights reserved.
//
import UIKit
import SpriteKit
class MathPianoGameViewController: UIViewController {
var converterReturn: (MathPianoGame, Bool)!
var mathPianoGameModel: MathPianoGame!
let skView: SKView = {
let view = SKView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var scene: BasicScene!
override func viewDidLoad() {
super.viewDidLoad()
print("Game")
scene = BasicScene(size: view.frame.size)
let converter = ExerciseConverter()
converterReturn = converter.convert()
if converterReturn.1{
mathPianoGameModel = RandomQuestionGenerator().generateGame(numberOfQuestions: 10, lifes: 3)
scene.gameMode = .endless
}else{
mathPianoGameModel = converterReturn.0
scene.gameMode = .task
}
//
NotificationCenter.default.addObserver(self, selector: #selector(exitGame), name: Notification.Name("exitGame"), object: nil)
// Do any additional setup after loading the view.
view.addSubview(skView)
skView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
skView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
skView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
skView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
scene.pianoModel = mathPianoGameModel
skView.presentScene(scene)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func exitGame(){
//TODO: let viewcontroller disappear
self.dismiss(animated: true) {
self.scene.removeFromParent()
}
//switch to view
}
}
|
import XCTest
import Nimble
class GameViewControllerUITests: XCTestCase {
var app: XCUIApplication!
override func setUp() {
super.setUp()
continueAfterFailure = false
app = XCUIApplication()
app.launch()
}
func testUserAction() {
let gameView = app.otherElements["GameView"]
let playButton = app.buttons["PlayButton"]
let randomButton = app.buttons["RandomButton"]
let stopButton = app.buttons["StopButton"]
expect(gameView.isHittable).to(beTrue())
expect(gameView.exists).to(beTrue())
expect(playButton.isHittable).to(beTrue())
expect(playButton.exists).to(beTrue())
expect(randomButton.isHittable).to(beTrue())
expect(randomButton.exists).to(beTrue())
expect(stopButton.exists).to(beFalsy())
playButton.tap()
expect(stopButton.isHittable).to(beTrue())
expect(stopButton.exists).to(beTrue())
expect(playButton.exists).to(beFalsy())
}
}
|
public final class Google {
public static let place = GooglePlaceAPI.shared
}
|
//
// TapMarkerViewController.swift
// FlightMap-Demo-iOS
//
// Created by Intern on 23/06/20.
// Copyright © 2020 Intern. All rights reserved.
//
import UIKit
import Mapbox
class TapMarkerViewController: UIViewController {
// MARK: Properties
private var mapView: MGLMapView!
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
setupMapView()
}
private func setupViews() {
/// setup navigation views
navigationItem.rightBarButtonItem = UIBarButtonItem(title: TEXT.reset, style: .plain, target: self, action: #selector(resetAction))
}
@objc private func resetAction() {
mapView.clear()
}
private func setupMapView() {
/// Initialize mapview with along with frame and style URL
mapView = MGLMapView(frame: self.view.bounds, styleURL: FLIGHTMAP.lightTheme)
/// Set camera at a specific lat long along with zoom and animation
let center = CLLocationCoordinate2D(latitude: 28.644800, longitude: 77.216721)
/// Optionally set a starting point.
mapView?.setCenter(center, zoomLevel: 13.0, direction: 0, animated: false)
self.view.addSubview(mapView!)
/// Adding single tap gesture to the mapView
let singleTap = UITapGestureRecognizer(target: self, action: #selector(handleMapTap(sender:)))
for recognizer in mapView.gestureRecognizers! where recognizer is UITapGestureRecognizer {
singleTap.require(toFail: recognizer)
}
mapView.addGestureRecognizer(singleTap)
}
@objc func handleMapTap(sender: UITapGestureRecognizer) {
/// Converting CGPoint to CLLocationCoordinate2D
let tapPoint: CGPoint = sender.location(in: mapView)
let tapCoordinate: CLLocationCoordinate2D = mapView.convert(tapPoint, toCoordinateFrom: nil)
print("You tapped at: \(tapCoordinate.latitude), \(tapCoordinate.longitude)")
let annotation = MGLPointAnnotation()
annotation.coordinate = tapCoordinate
mapView.addAnnotation(annotation)
}
}
|
//
// flickrPhotos.swift
// VirtualTourist
//
// Created by Hajar F on 12/4/19.
// Copyright © 2019 Hajar F. All rights reserved.
//
struct Constants {
static let key = "2ac76dbc3aa3f406f2ff5eeabaf37b29"
static let flickrPhotos = "https://api.flickr.com/services/rest?method=flickr.photos.search&format=json&api_key=\(Constants.key)&bbox={bbox}&per_page=21&page={page}&extras=url_m&nojsoncallback=1"
}
|
import UIKit
class HowToPlayViewController: UIViewController{
let soundManger = SoundManager.shared
@IBOutlet weak var bgImg: UIImageView!
@IBOutlet weak var talkBlockImg: UIImageView!
@IBOutlet weak var departLineImg: UIImageView!
@IBOutlet weak var howToPlayLB: UILabel!
@IBOutlet weak var contentLB: UILabel!
@IBOutlet weak var dismissBtn: UIButton!
@IBOutlet weak var playLB: UILabel!
override func viewDidLoad(){
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backAtn(){
soundManger.playSEwith(sound: .SE3_back)
UIView.animate(withDuration: 0.8) {
self.bgImg.frame.size.height = 0
self.talkBlockImg.frame.origin.y = self.view.frame.height
self.departLineImg.frame.size.width = 0
self.howToPlayLB.frame = CGRect(x: self.view.frame.width / 2, y: self.view.frame.height / 2, width: 0, height: 0)
self.contentLB.frame = self.howToPlayLB.frame
self.playLB.frame = self.howToPlayLB.frame
// self.dismissBtn.frame.origin.x = 0
self.dismissBtn.frame = CGRect(x: 0, y: self.dismissBtn.frame.origin.y, width: 0, height: 0)
}
DispatchQueue.main.asyncAfter(deadline: .now()+0.8) {
self.dismiss(animated: false, completion: nil)
}
}
}
|
import UIKit
class MainViewController: UIViewController {
@IBOutlet weak var dispalyLable: UILabel!
private var score = 0
@IBAction func tap(_ sender: UIButton) {
score += 1
dispalyLable.text = "\(score)"
}
override func viewDidLoad() {
super.viewDidLoad()
dispalyLable.text = "\(score)"
}
}
|
//
// Inventory.swift
// CagesFarm
//
// Created by Gilberto Magno on 3/22/21.
//
import Foundation
import SpriteKit
// swiftlint:disable for_where
class Inventory: SKSpriteNode {
var items: [Items]
var textureBackground: SKSpriteNode = SKSpriteNode(imageNamed: "inventario")
var squares: [SKShapeNode] = []
var auxPositionItem = 0
func organizeInventory() {
for increment in 0...4 {
squares.append(SKShapeNode(rect: CGRect(x: -30, y: 128 - increment*65, width: 40, height: 40), cornerRadius: 5))
self.addChild(squares[increment])
squares[increment].fillColor = .gray
squares[increment].zPosition = +1
}
organizeItems()
self.size = CGSize(width: 70, height: UIScreen.main.bounds.height)
//self.addChild(textureBackground)
self.position = CGPoint(x: 335, y: 0)
}
func organizeItems() {
for item in items {
if item.parent == nil {
addChild(item)
item.size = squares[auxPositionItem].frame.size
item.setScale(0.95)
item.position.x = squares[auxPositionItem].frame.origin.x + item.size.width/2 + 1
item.position.y = squares[auxPositionItem].frame.origin.y + item.size.height/2 + 1
auxPositionItem += 1
item.zPosition = +1
}
}
}
func addItem(itemName: Items) {
items.append(itemName)
organizeItems()
}
func removeItem() {}
func touchItem() {}
init(items: [Items]) {
self.items = items
self.textureBackground.color = .clear
super.init(texture: self.textureBackground.texture, color: .clear, size: (self.textureBackground.texture?.size())!)
organizeInventory()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// SearchWordList.swift
// Fid
//
// Created by CROCODILE on 14.01.2021.
//
import Foundation
import UIKit
class MainData {
var key: String!
var value: String!
init(key: String, value: String) {
self.key = key
self.value = value
}
}
|
//
// Listenable.swift
// OmiseGO
//
// Created by Mederic Petit on 9/3/18.
//
/// Represents an object that can be listened with websockets
public protocol Listenable {
var socketTopic: String { get }
}
public extension Listenable {
/// Stop listening for events
///
/// - Parameter client: The client used when starting to listen
public func stopListening(withClient client: SocketClient) {
client.leaveChannel(withTopic: self.socketTopic)
}
}
public extension Listenable where Self == User {
/// Opens a websocket connection with the server and starts to listen for any event regarding the current user
///
/// - Parameters:
/// - client: The correctly initialized client to use for the websocket connection
/// - eventDelegate: The delegate that will receive events
public func startListeningEvents(withClient client: SocketClient, eventDelegate: UserEventDelegate?) {
client.joinChannel(withTopic: self.socketTopic, dispatcher: SocketDispatcher.user(handler: eventDelegate))
}
}
public extension Listenable where Self == TransactionRequest {
/// Opens a websocket connection with the server and starts to listen for events happening on this transaction request
/// Typically, this should be used to listen for consumption request made on the request
///
/// - Parameters:
/// - client: The correctly initialized client to use for the websocket connection
/// - eventDelegate: The delegate that will receive events
public func startListeningEvents(withClient client: SocketClient, eventDelegate: TransactionRequestEventDelegate?) {
client.joinChannel(withTopic: self.socketTopic, dispatcher: SocketDispatcher.transactionRequest(handler: eventDelegate))
}
}
public extension Listenable where Self == TransactionConsumption {
/// Opens a websocket connection with the server and starts to listen for events happening on this transaction consumption
/// Typically, this should be used to listen for consumption confirmation
///
/// - Parameters:
/// - client: The correctly initialized client to use for the websocket connection
/// - eventDelegate: The delegate that will receive events
public func startListeningEvents(withClient client: SocketClient, eventDelegate: TransactionConsumptionEventDelegate?) {
client.joinChannel(withTopic: self.socketTopic, dispatcher: SocketDispatcher.transactionConsumption(handler: eventDelegate))
}
}
|
import Foundation
import EvmKit
class WalletConnectSendEthereumTransactionRequestService {
private let request: WalletConnectSendEthereumTransactionRequest
private let signService: IWalletConnectSignService
init(request: WalletConnectSendEthereumTransactionRequest, baseService: IWalletConnectSignService) {
self.request = request
signService = baseService
}
}
extension WalletConnectSendEthereumTransactionRequestService {
var transactionData: TransactionData {
TransactionData(
to: request.transaction.to,
value: request.transaction.value,
input: request.transaction.data
)
}
var gasPrice: GasPrice? {
if let maxFeePerGas = request.transaction.maxFeePerGas,
let maxPriorityFeePerGas = request.transaction.maxPriorityFeePerGas {
return GasPrice.eip1559(maxFeePerGas: maxFeePerGas, maxPriorityFeePerGas: maxPriorityFeePerGas)
}
return request.transaction.gasPrice.flatMap { GasPrice.legacy(gasPrice: $0) }
}
func approve(transactionHash: Data) {
signService.approveRequest(id: request.id, result: transactionHash)
}
func reject() {
signService.rejectRequest(id: request.id)
}
}
|
//
// LoginAccessor.swift
// FoxelBox
//
// Created by Mark Dietzer on 25/03/16.
// Copyright © 2016 Mark Dietzer. All rights reserved.
//
import Foundation
import KeychainAccess
import Crashlytics
protocol LoginReceiver: class {
func loginStateChanged()
}
class LoginAccessor: APIAccessor {
internal var sessionToken: String?
var expiresAt: Int = 0
fileprivate var username :String?
fileprivate var password :String?
fileprivate var passwordChanged :Bool = false
let loginDispatchGroup = DispatchGroup()
var refreshId = 0
var lastActionWasRefresh = false
let loginReceiversLock = NSLock()
var loginReceivers: NSHashTable<AnyObject> = NSHashTable.weakObjects()
let keychain = Keychain(server: "https://foxelbox.com", protocolType: .https)
.synchronizable(true)
override init() {
super.init()
self.loadCredentials()
}
func getUsername() -> String? {
return self.username
}
func isLoggedIn() -> Bool {
self.loginDispatchGroup.wait(timeout: DispatchTime.distantFuture)
return self.sessionToken != nil && self.expiresAt > Int(Date().timeIntervalSince1970)
}
func hasCredentials() -> Bool {
return self.username != nil && self.password != nil
}
override func onSuccess(_ response: BaseResponse) throws {
let myResponse = try LoginResponse(response.result!)
self.refreshId += 1
let myRefreshId = self.refreshId
self.sessionToken = myResponse.sessionId
self.expiresAt = myResponse.expiresAt
loginDispatchGroup.leave()
let expiresIn = self.expiresAt - Int(Date().timeIntervalSince1970)
DispatchQueue.global(qos: DispatchQoS.QoSClass.utility).asyncAfter(
deadline: DispatchTime.now() + Double(Int64(expiresIn - 60) * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC)) {
if (self.refreshId == myRefreshId) {
self.refreshLogin()
}
}
}
override func makeToastForErrors() -> Bool {
return false
}
override func onError(_ message: BaseResponse) {
if message.statusCode == APIAccessor.STATUS_CANCELLED {
self.loginDispatchGroup.leave()
return
}
if self.lastActionWasRefresh && message.statusCode == 401 {
self.sessionToken = nil
self.doLogin(true)
self.loginDispatchGroup.leave()
return
}
self.loginDispatchGroup.leave()
self.sessionToken = nil
if message.statusCode == 401 {
self.logout(clearChat: false)
self.askLogin("Error: \(message.message!)")
return
}
super.onError(message)
}
func loadCredentials() {
self.loginDispatchGroup.enter()
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async {
self.username = UserDefaults.standard.string(forKey: "username")
if self.username != nil {
self.password = self.keychain[self.username!]
}
self.loginDispatchGroup.leave()
}
}
func saveCredentials() {
self.loginDispatchGroup.enter()
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async {
let oldUsername = UserDefaults.standard.string(forKey: "username")
UserDefaults.standard.set(self.username, forKey: "username")
if oldUsername != nil && oldUsername != self.username {
self.keychain[oldUsername!] = nil
}
if self.username != nil {
self.keychain[self.username!] = self.password
}
self.loginDispatchGroup.leave()
}
}
fileprivate func loginStateChanged() {
loginReceiversLock.lock()
for receiver in self.loginReceivers.objectEnumerator() {
(receiver as! LoginReceiver).loginStateChanged()
}
loginReceiversLock.unlock()
}
var loginDialogShowing :Bool = false
func askLogout() {
DispatchQueue.main.async {
guard !self.loginDialogShowing else {
return
}
self.loginDialogShowing = true
let alert = UIAlertController(title: "Log out?", message: "You will need to log in again to send chat", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Confirm", style: .default) { action in
self.loginDialogShowing = false
self.logout()
})
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { action in
self.loginDialogShowing = false
})
UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
}
}
fileprivate func tryLoginAskOnError(_ username: String?, password: String?) {
self.login(username, password: password) { response in
if !response.success {
self.askLogin("Error: \(response.message!) (\(response.statusCode))")
}
}
}
func askLogin(_ message: String?=nil) {
self.sessionToken = nil
self.loginDialogShowing = true
self.keychain.getSharedPassword() { (username, password, error) in
self.loginDialogShowing = false
if error != nil {
print("Keychain error: \(error!)")
}
if username == nil || password == nil || error != nil {
self.askLoginOwn(message)
} else {
self.tryLoginAskOnError(username, password: password)
}
}
}
func askLoginOwn(_ message: String?=nil) {
var showMessage = message
if showMessage == nil {
showMessage = "Please use the same credentials as you do on foxelbox.com"
}
DispatchQueue.main.async(execute: {
guard !self.loginDialogShowing else {
return
}
self.loginDialogShowing = true
let alert = UIAlertController(title: "Please log in", message: showMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default) { action in
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async {
self.tryLoginAskOnError(alert.textFields![0].text, password: alert.textFields![1].text)
self.loginDialogShowing = false
}
})
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { action in
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async {
self.loginDialogShowing = false
self.logout(true, clearChat: self.username != nil)
}
})
alert.addTextField(configurationHandler: { textField in
textField.placeholder = "Username"
textField.isSecureTextEntry = true
textField.text = self.username
})
alert.addTextField(configurationHandler: { textField in
textField.placeholder = "Password"
textField.isSecureTextEntry = true
textField.text = self.password
})
UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
})
}
func login(_ username :String?, password :String?, callback: ((BaseResponse) -> (Void))?=nil) {
if self.username != nil && self.username != username {
AppDelegate.chatPoller.clear()
}
if username == "" {
self.username = nil
} else {
self.username = username
}
if password == "" {
self.password = nil
} else {
self.password = password
}
self.passwordChanged = true
if self.username == nil || self.password == nil {
logout(clearChat: false)
callback?(BaseResponse(message: "Empty username/password"))
return
}
Crashlytics.sharedInstance().setUserName(self.username)
Crashlytics.sharedInstance().setUserIdentifier(nil)
self.sessionToken = nil
self.doLogin(callback: callback)
return
}
func logout(_ unsetUsername :Bool=false, clearChat :Bool=true) {
if unsetUsername {
self.username = nil
Crashlytics.sharedInstance().setUserName(nil)
}
Crashlytics.sharedInstance().setUserIdentifier(nil)
self.password = nil
self.sessionToken = nil
self.cancel(true)
self.saveCredentials()
self.loginStateChanged()
if clearChat {
AppDelegate.chatPoller.clear()
}
}
func doLogin(_ ignoreLoggedIn: Bool=false, succeedOnNoCredentials: Bool=false, callback: ((BaseResponse) -> (Void))?=nil) {
guard ignoreLoggedIn || !self.isLoggedIn() else {
callback?(BaseResponse(message: "OK", statusCode: 200, success: true))
return
}
guard self.hasCredentials() else {
if succeedOnNoCredentials {
callback?(BaseResponse(message: "OK", statusCode: 200, success: true))
} else {
callback?(BaseResponse(message: "No credentials present"))
}
return
}
self.loginDispatchGroup.enter()
self.cancel(true)
self.lastActionWasRefresh = false
request("/login", method: "POST", parameters: [
"username": self.username!,
"password": self.password!
], noSession: true, waitOnLogin: false) { response in
if response.success {
Crashlytics.sharedInstance().setUserIdentifier(self.username)
self.loginStateChanged()
self.saveCredentials()
} else {
Crashlytics.sharedInstance().setUserIdentifier(nil)
}
callback?(response)
}
}
fileprivate func refreshLogin() {
if self.sessionToken == nil {
self.doLogin()
return
}
self.loginDispatchGroup.enter()
self.cancel(true)
self.lastActionWasRefresh = true
request("/login/refresh", method: "POST", waitOnLogin: false)
return
}
internal func addReceiver(_ receiver: LoginReceiver) {
self.loginReceiversLock.lock()
self.loginReceivers.add(receiver)
self.loginReceiversLock.unlock()
}
internal func removeReceiver(_ receiver: LoginReceiver) {
self.loginReceiversLock.lock()
self.loginReceivers.remove(receiver)
self.loginReceiversLock.unlock()
}
}
|
infix operator <- : AssignmentPrecedence
prefix operator |<-
/// Creates a binding expression.
///
/// - Parameters:
/// - bound: Variable to be bound in the expression.
/// - fa: Monadic effect.
/// - Returns: A binding expression.
public func <-<F: Monad, A>(
_ bound: BoundVar<F, A>,
_ fa: @autoclosure @escaping () -> Kind<F, A>) -> BindingExpression<F> {
BindingExpression(bound, fa)
}
/// Creates a binding expression.
///
/// - Parameters:
/// - bounds: A 2-ary tuple of variables to be bound to the values produced by the effect.
/// - fa: Monadic effect.
/// - Returns: A binding expresssion.
public func <-<F: Monad, A, B>(
_ bounds: (BoundVar<F, A>, BoundVar<F, B>),
_ fa: @autoclosure @escaping () -> Kind<F, (A, B)>) -> BindingExpression<F> {
BindingExpression(
BoundVar2(bounds.0, bounds.1),
fa)
}
/// Creates a binding expression.
///
/// - Parameters:
/// - bounds: A 3-ary tuple of variables to be bound to the values produced by the effect.
/// - fa: Monadic effect.
/// - Returns: A binding expresssion.
public func <-<F: Monad, A, B, C>(
_ bounds: (BoundVar<F, A>, BoundVar<F, B>, BoundVar<F, C>),
_ fa: @autoclosure @escaping () -> Kind<F, (A, B, C)>) -> BindingExpression<F> {
BindingExpression(
BoundVar3(bounds.0, bounds.1, bounds.2),
fa)
}
/// Creates a binding expression.
///
/// - Parameters:
/// - bounds: A 4-ary tuple of variables to be bound to the values produced by the effect.
/// - fa: Monadic effect.
/// - Returns: A binding expresssion.
public func <-<F: Monad, A, B, C, D>(
_ bounds: (BoundVar<F, A>, BoundVar<F, B>, BoundVar<F, C>, BoundVar<F, D>),
_ fa: @autoclosure @escaping () -> Kind<F, (A, B, C, D)>) -> BindingExpression<F> {
BindingExpression(
BoundVar4(bounds.0, bounds.1, bounds.2, bounds.3),
fa)
}
/// Creates a binding expression.
///
/// - Parameters:
/// - bounds: A 5-ary tuple of variables to be bound to the values produced by the effect.
/// - fa: Monadic effect.
/// - Returns: A binding expresssion.
public func <-<F: Monad, A, B, C, D, E>(
_ bounds: (BoundVar<F, A>, BoundVar<F, B>, BoundVar<F, C>, BoundVar<F, D>, BoundVar<F, E>),
_ fa: @autoclosure @escaping () -> Kind<F, (A, B, C, D, E)>) -> BindingExpression<F> {
BindingExpression(
BoundVar5(bounds.0, bounds.1, bounds.2, bounds.3, bounds.4),
fa)
}
/// Creates a binding expression.
///
/// - Parameters:
/// - bounds: A 6-ary tuple of variables to be bound to the values produced by the effect.
/// - fa: Monadic effect.
/// - Returns: A binding expresssion.
public func <-<F: Monad, A, B, C, D, E, G>(
_ bounds: (BoundVar<F, A>, BoundVar<F, B>, BoundVar<F, C>, BoundVar<F, D>, BoundVar<F, E>, BoundVar<F, G>),
_ fa: @autoclosure @escaping () -> Kind<F, (A, B, C, D, E, G)>) -> BindingExpression<F> {
BindingExpression(
BoundVar6(bounds.0, bounds.1, bounds.2, bounds.3, bounds.4, bounds.5),
fa)
}
/// Creates a binding expression.
///
/// - Parameters:
/// - bounds: A 7-ary tuple of variables to be bound to the values produced by the effect.
/// - fa: Monadic effect.
/// - Returns: A binding expresssion.
public func <-<F: Monad, A, B, C, D, E, G, H>(
_ bounds: (BoundVar<F, A>, BoundVar<F, B>, BoundVar<F, C>, BoundVar<F, D>, BoundVar<F, E>, BoundVar<F, G>, BoundVar<F, H>),
_ fa: @autoclosure @escaping () -> Kind<F, (A, B, C, D, E, G, H)>) -> BindingExpression<F> {
BindingExpression(
BoundVar7(bounds.0, bounds.1, bounds.2, bounds.3, bounds.4, bounds.5, bounds.6),
fa)
}
/// Creates a binding expression.
///
/// - Parameters:
/// - bounds: A 8-ary tuple of variables to be bound to the values produced by the effect.
/// - fa: Monadic effect.
/// - Returns: A binding expresssion.
public func <-<F: Monad, A, B, C, D, E, G, H, I>(
_ bounds: (BoundVar<F, A>, BoundVar<F, B>, BoundVar<F, C>, BoundVar<F, D>, BoundVar<F, E>, BoundVar<F, G>, BoundVar<F, H>, BoundVar<F, I>),
_ fa: @autoclosure @escaping () -> Kind<F, (A, B, C, D, E, G, H, I)>) -> BindingExpression<F> {
BindingExpression(
BoundVar8(bounds.0, bounds.1, bounds.2, bounds.3, bounds.4, bounds.5, bounds.6, bounds.7),
fa)
}
/// Creates a binding expression.
///
/// - Parameters:
/// - bounds: A 9-ary tuple of variables to be bound to the values produced by the effect.
/// - fa: Monadic effect.
/// - Returns: A binding expresssion.
public func <-<F: Monad, A, B, C, D, E, G, H, I, J>(
_ bounds: (BoundVar<F, A>, BoundVar<F, B>, BoundVar<F, C>, BoundVar<F, D>, BoundVar<F, E>, BoundVar<F, G>, BoundVar<F, H>, BoundVar<F, I>, BoundVar<F, J>),
_ fa: @autoclosure @escaping () -> Kind<F, (A, B, C, D, E, G, H, I, J)>) -> BindingExpression<F> {
BindingExpression(
BoundVar9(bounds.0, bounds.1, bounds.2, bounds.3, bounds.4, bounds.5, bounds.6, bounds.7, bounds.8),
fa)
}
/// Creates a binding expression.
///
/// - Parameters:
/// - bounds: A 10-ary tuple of variables to be bound to the values produced by the effect.
/// - fa: Monadic effect.
/// - Returns: A binding expresssion.
public func <-<F: Monad, A, B, C, D, E, G, H, I, J, K>(
_ bounds: (BoundVar<F, A>, BoundVar<F, B>, BoundVar<F, C>, BoundVar<F, D>, BoundVar<F, E>, BoundVar<F, G>, BoundVar<F, H>, BoundVar<F, I>, BoundVar<F, J>, BoundVar<F, K>),
_ fa: @autoclosure @escaping () -> Kind<F, (A, B, C, D, E, G, H, I, J, K)>) -> BindingExpression<F> {
BindingExpression(
BoundVar10(bounds.0, bounds.1, bounds.2, bounds.3, bounds.4, bounds.5, bounds.6, bounds.7, bounds.8, bounds.9),
fa)
}
/// Creates a binding expression that discards the produced value.
///
/// - Parameter fa: Monadic effect.
/// - Returns: A binding expression.
public prefix func |<-<F: Monad, A>(_ fa: @autoclosure @escaping () -> Kind<F, A>) -> BindingExpression<F> {
BindingExpression(BoundVar(), fa)
}
|
//
// JISHOTests.swift
// JISHOTests
//
// Created by Alex on 08/02/2020.
// Copyright © 2020 Alex McMillan. All rights reserved.
//
import XCTest
@testable import JISHO_Go_
class SearchPresenterTests: XCTestCase {
let sut = SearchPresenter()
// Main entry uses slug as the word
func test_makeDisplayItem_usesSlugWord_asMainWord() {
let slug = Datum(slug: "日本", japanese: [Japanese(word: nil, reading: "にほん")], senses: [])
XCTAssertEqual("日本", displayItems(from: [slug]).first!.mainForm.word)
}
// Main entry uses first Japanese kana (reading) as its reading
func test_mainEntry_usesFirstReading_asReading() {
let slug = Datum(slug: "日本", japanese: [Japanese(word: "日本", reading: "にほん")], senses: [])
XCTAssertEqual("にほん", displayItems(from: [slug]).first!.mainForm.reading)
}
// Make sure any -(num) is stripped from the slug
func test_ifHyphenNumberOnSlug_removesIt() {
let slug1 = Datum(slug: "日本", japanese: [Japanese(word: nil, reading: "にほん")], senses: [])
let slug2 = Datum(slug: "日本-1", japanese: [Japanese(word: nil, reading: "にほんにほん")], senses: [])
XCTAssertEqual("日本", displayItems(from: [slug1, slug2])[1].mainForm.word)
}
func test_ifSlugIsAlphanumeric_removesIt() {
let slug1 = Datum(slug: "1234567890", japanese: [Japanese(word: nil, reading: "Reading")], senses: [])
let slug2 = Datum(slug: "dcb5", japanese: [Japanese(word: nil, reading: "Reading")], senses: [])
let slug3 = Datum(slug: "日本", japanese: [Japanese(word: nil, reading: "にっぽん")], senses: [])
let displayItems = self.displayItems(from: [slug1, slug2, slug3])
XCTAssertEqual(1, displayItems.count)
XCTAssertEqual("日本", displayItems.first!.mainForm.word)
}
func test_ifWikipediaDefinitionInPartsOfSpeech_omitsFromDisplayItem() {
let slug = Datum(slug: "日本", japanese: [Japanese(word: nil, reading: "にっぽん")], senses: [Sense(english_definitions: ["Japan"], parts_of_speech: ["Wikipedia definition"], links: [])])
XCTAssertTrue(displayItems(from: [slug]).first!.definitions.isEmpty)
}
func test_ifLinksPresentInPartsOfSpeech_addedToDisplayItem() {
let slug = Datum(slug: "日本", japanese: [Japanese(word: nil, reading: "にっぽん")], senses: [Sense(english_definitions: ["Japan"], parts_of_speech: ["Wikipedia definition"], links: [Link(text: "English Wikipedia", url: "https://something")])])
XCTAssertEqual(1, displayItems(from: [slug]).first!.links.count)
}
func test_ifOtherFormsPresent_addedToDisplayItem() {
let slug = Datum(slug: "日本", japanese: [Japanese(word: "日本", reading: "にほん"), Japanese(word: "日本", reading: "にっぽん")], senses: [])
let displayItems = self.displayItems(from: [slug])
XCTAssertEqual(1, displayItems.first!.otherForms.count)
XCTAssertEqual("にっぽん", displayItems.first!.otherForms.first!.reading)
}
func test_ifMoreThan2Definitions_numberIncludedAsNotSurfaced() {
let slug = Datum(slug: "日本",
japanese: [Japanese(word: "日本", reading: "にほん"), Japanese(word: "日本", reading: "にっぽん")],
senses: [Sense(english_definitions: ["A"], parts_of_speech: ["Noun"], links: []),
Sense(english_definitions: ["B"], parts_of_speech: ["Noun"], links: []),
Sense(english_definitions: ["C"], parts_of_speech: ["Noun"], links: [])])
XCTAssertEqual(1, displayItems(from: [slug]).first!.definitionsNotSurfaced)
}
func test_if2Definitions_notSurfacedIs0() {
let slug = Datum(slug: "日本",
japanese: [Japanese(word: "日本", reading: "にほん"),
Japanese(word: "日本", reading: "にっぽん")],
senses: [Sense(english_definitions: ["A"], parts_of_speech: ["Noun"], links: []),
Sense(english_definitions: ["B"], parts_of_speech: ["Noun"], links: [])])
XCTAssertEqual(0, displayItems(from: [slug]).first!.definitionsNotSurfaced)
}
func test_ifFewerThan2Definitions_notSurfacedIs0() {
let slug = Datum(slug: "日本",
japanese: [Japanese(word: "日本", reading: "にほん"), Japanese(word: "日本", reading: "にっぽん")],
senses: [Sense(english_definitions: ["A"], parts_of_speech: ["Noun"], links: [])])
XCTAssertEqual(0, displayItems(from: [slug]).first!.definitionsNotSurfaced)
}
func test_deduplicate_removesDuplicateDisplayItems() {
let inputItems: [EntryDisplayItem] = [EntryDisplayItem(favouriteButtonState: .unfavourited, mainForm: Form(word: "日本", reading: "にほん"), otherForms: [], definitions: [], definitionsNotSurfaced: 0, links: [], kanji: []), EntryDisplayItem(favouriteButtonState: .unfavourited, mainForm: Form(word: "日本", reading: "にほん"), otherForms: [], definitions: [], definitionsNotSurfaced: 0, links: [], kanji: [])]
let deduplicated = sut.deduplicate(displayItems: inputItems)
XCTAssertEqual(1, deduplicated.count)
}
func test_makeDisplayItems_whenStoredObjectsIdsArePassedWithResponseItems_ifFavouritePresentInSearchResults_marksAFoundFavouriteAsAFavourite() {
let realmIds = ["日本にっぽん"]
let slug = Datum(slug: "日本",
japanese: [Japanese(word: "日本", reading: "にっぽん"), Japanese(word: "日本", reading: "にほん")],
senses: [Sense(english_definitions: ["A"], parts_of_speech: ["Noun"], links: []),
Sense(english_definitions: ["B"], parts_of_speech: ["Noun"], links: []),
Sense(english_definitions: ["C"], parts_of_speech: ["Noun"], links: [])])
let displayItems = sut.makeDisplayItems(from: [slug], favouritesIds: realmIds)
XCTAssertEqual(FavouriteButtonState.favourited, displayItems.first!.favouriteButtonState)
}
func test_makeDisplayItems_whenStoredObjectsIdsArePassedWithResponseItems_ifNoFavouritesPresentInSearchResults_doesNotMarkAsAFavourite() {
let realmIds = ["日に"]
let slug = Datum(slug: "日本",
japanese: [Japanese(word: "日本", reading: "にっぽん"), Japanese(word: "日本", reading: "にほん")],
senses: [Sense(english_definitions: ["A"], parts_of_speech: ["Noun"], links: []),
Sense(english_definitions: ["B"], parts_of_speech: ["Noun"], links: []),
Sense(english_definitions: ["C"], parts_of_speech: ["Noun"], links: [])])
let displayItems = sut.makeDisplayItems(from: [slug], favouritesIds: realmIds)
XCTAssertEqual(FavouriteButtonState.unfavourited, displayItems.first!.favouriteButtonState)
}
}
extension SearchPresenterTests {
private func displayItems(from slugs: [Datum]) -> [EntryDisplayItem] {
return sut.makeDisplayItems(from: slugs, favouritesIds: [])
}
}
|
//
// MapaViewController.swift
// Agenda
//
// Created by Gabriel Zambelli on 07/03/20.
// Copyright © 2020 Alura. All rights reserved.
//
import UIKit
import MapKit
class MapaViewController: UIViewController, CLLocationManagerDelegate {
// MARK: - Variavel
var aluno: Aluno?
lazy var localizacao = Localizacao()
lazy var gerenciadorDeLocalizacao = CLLocationManager()
// MARK: view Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = getTitulo()
verificaAutorizacaoDoUsario()
self.localizacaoInicial()
//self.localizarAluno()
mapa.delegate = localizacao
gerenciadorDeLocalizacao.delegate = self
// Do any additional setup after loading the view.
}
// MARK: Metodos
func getTitulo() -> String{
return "Localizar Alunos"
}
// criar o ponto no mapa
/*func configuraPino(titulo: String, localizacao: CLPlacemark) -> MKPointAnnotation{
let pino = MKPointAnnotation()
pino.title = titulo
pino.coordinate = localizacao.location!.coordinate
return pino
}*/
func verificaAutorizacaoDoUsario(){
//verifica se o recurso de gps esta disponivel no dispositivo
if CLLocationManager.locationServicesEnabled(){
//verifica qual o status da autorização de utilização do GPS
switch CLLocationManager.authorizationStatus() {
case .authorizedWhenInUse:
let botao = Localizacao().configuraBotaoLocalizacaoAtual(mapa: mapa)
//adiciona o botao no mapa
mapa.addSubview(botao)
//inicia a geração de atualizações que relatam a localização atual do usuário
gerenciadorDeLocalizacao.startUpdatingLocation()
break
case .notDetermined:
//solicita ao usuário a autorização para uso do GPS
gerenciadorDeLocalizacao.requestWhenInUseAuthorization()
break
case .denied:
break
default:
break
}
}
}
func localizacaoInicial(){
Localizacao().converteEnderecoEmCoordenada(endereco: "Caelum - São Paulo") { (localizacaoEncontrada) in
//let pino = self.configuraPino(titulo: "Caelum", localizacao: localizacaoEncontrada)
let pino = Localizacao().configuraPino(titulo: "Caelum", localizacao: localizacaoEncontrada, cor: .black, icone: UIImage(named: "icon_caelum"))
let regiao = MKCoordinateRegionMakeWithDistance(pino.coordinate, 6000, 6000)
self.mapa.setRegion(regiao, animated: true)
self.mapa.addAnnotation(pino)
}
}
func localizarAluno(){
if let aluno = aluno{
Localizacao().converteEnderecoEmCoordenada(endereco: aluno.endereco!) { (localizacaoEncontrada) in
//let pino = self.configuraPino(titulo: aluno.nome!, localizacao: localizacaoEncontrada)
let pino = Localizacao().configuraPino(titulo: aluno.nome!, localizacao: localizacaoEncontrada, cor: nil, icone: nil)
self.mapa.addAnnotation(pino)
//tenta exibir todos os pinos no mapa
self.mapa.showAnnotations(self.mapa.annotations, animated: true)
self.localizarAluno()
}
}
}
//MARK: - CLLocationManagerDelegate
//metodo na qual é chamado sempre que a autorização do GPS é alterada
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .authorizedWhenInUse:
let botao = Localizacao().configuraBotaoLocalizacaoAtual(mapa: mapa)
//adiciona o botao no mapa
mapa.addSubview(botao)
//inicia a geração de atualizações que relatam a localização atual do usuário
gerenciadorDeLocalizacao.startUpdatingLocation()
break
default:
break
}
}
//metodo é chamado sempre que a localição do usuários é alterada
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
}
//MARK: IBOutlet
@IBOutlet weak var mapa: MKMapView!
}
|
//
// ViewControllerAddLink.swift
// Projecte
//
// Created by 1181432 on 5/2/16.
// Copyright © 2016 FIB. All rights reserved.
//
import UIKit
protocol linkAddDelegate {
func saveNewDownloadLinkSelected(link:String, language:String)
}
class ViewControllerAddLink: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var languagesPicker: UIPickerView!
var delegate: linkAddDelegate!
@IBOutlet weak var linkText: UITextField!
let languages = ["EN","ES","CAT"]
override func viewDidLoad() {
super.viewDidLoad()
linkText.becomeFirstResponder()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return languages.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return languages[row]
}
@IBAction func saveClicked() {
// print(linkText.selectedTextRange?.description)
print(languages[languagesPicker.selectedRowInComponent(0)])
if linkText.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet() ) != "" {
delegate.saveNewDownloadLinkSelected(linkText.text!, language: languages[languagesPicker.selectedRowInComponent(0)])
}
}
@IBAction func cancelClicked() {
self.dismissViewControllerAnimated(true, completion: nil)
}
/*
// 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.
}
*/
}
|
import Foundation
import FigUtils
public struct FigSpec: Encodable {
public enum Template: String, Encodable {
case filepaths
case folders
case history
}
public enum SuggestionKind: String, Encodable {
case folder
case file
case arg
case subcommand
case option
case special
case shortcut
}
public enum Icon: Encodable {
// pre-defined icon or file extension
public struct Preset: ExpressibleByStringLiteral {
public var rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public init(stringLiteral value: String) {
self.rawValue = value
}
public static let alert: Preset = "alert"
public static let android: Preset = "android"
public static let apple: Preset = "apple"
public static let asterisk: Preset = "asterisk"
public static let aws: Preset = "aws"
public static let azure: Preset = "azure"
public static let box: Preset = "box"
public static let carrot: Preset = "carrot"
public static let characters: Preset = "characters"
public static let command: Preset = "command"
public static let commandkey: Preset = "commandkey"
public static let commit: Preset = "commit"
public static let database: Preset = "database"
public static let docker: Preset = "docker"
public static let firebase: Preset = "firebase"
public static let gcloud: Preset = "gcloud"
public static let git: Preset = "git"
public static let github: Preset = "github"
public static let gitlab: Preset = "gitlab"
public static let gradle: Preset = "gradle"
public static let heroku: Preset = "heroku"
public static let invite: Preset = "invite"
public static let kubernetes: Preset = "kubernetes"
public static let netlify: Preset = "netlify"
public static let node: Preset = "node"
public static let npm: Preset = "npm"
public static let option: Preset = "option"
public static let package: Preset = "package"
public static let slack: Preset = "slack"
public static let string: Preset = "string"
public static let twitter: Preset = "twitter"
public static let vercel: Preset = "vercel"
public static let yarn: Preset = "yarn"
}
public struct Overlay {
public var colorHex: String?
public var badge: String?
public init(colorHex: String? = nil, badge: String? = nil) {
self.colorHex = colorHex
self.badge = badge
}
public func apply(to components: inout URLComponents) {
var queryItems: [URLQueryItem] = []
if let colorHex = colorHex {
queryItems.append(URLQueryItem(name: "color", value: colorHex))
}
if let badge = badge {
queryItems.append(URLQueryItem(name: "badge", value: badge))
}
guard !queryItems.isEmpty else { return }
components.queryItems = (components.queryItems ?? []) + queryItems
}
}
case character(Character)
case path(URL, Overlay?)
case preset(Preset, Overlay?)
case template(Overlay)
public static func path(_ url: URL) -> Icon {
.path(url, nil)
}
public static func preset(_ preset: Preset) -> Icon {
.preset(preset, nil)
}
private func buildFigURL(_ builder: (inout URLComponents) throws -> Void) rethrows -> String? {
var components = URLComponents()
components.scheme = "fig"
try builder(&components)
return components.string
}
public var rawValue: String? {
switch self {
case .character(let c):
return "\(c)"
case let .path(url, overlay):
return buildFigURL { components in
components.path = url.path
overlay?.apply(to: &components)
}
case let .preset(preset, overlay):
return buildFigURL { components in
components.host = "icon"
components.queryItems = [URLQueryItem(name: "type", value: preset.rawValue)]
overlay?.apply(to: &components)
}
case let .template(overlay):
return buildFigURL { components in
components.host = "template"
overlay.apply(to: &components)
}
}
}
public func encode(to encoder: Encoder) throws {
guard let rawValue = rawValue else {
throw ErrorMessage("Could not encode icon \(self)")
}
var container = encoder.singleValueContainer()
try container.encode(rawValue)
}
}
// .option/.flag arguments
public struct Option: Encodable {
public struct RepeatCount: Encodable, ExpressibleByIntegerLiteral, Hashable {
public let value: UInt?
init(value: UInt?) {
self.value = value
}
public static let infinity = RepeatCount(value: nil)
public init(integerLiteral value: UInt) {
self.value = value
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
if let value = value {
try container.encode(value)
} else {
try container.encode(true)
}
}
}
public var names: [String]
public var arguments: [Argument]?
public var isPersistent: Bool?
public var isRequired: Bool?
public var requiresEquals: Bool?
public var repeatCount: RepeatCount?
public var exclusiveOn: [String]?
public var dependsOn: [String]?
public var displayName: String?
public var insertValue: String?
public var description: String?
public var icon: Icon?
public var priority: Double?
public var isDangerous: Bool?
public var isHidden: Bool?
public var isDeprecated: Bool?
public init(
names: [String],
arguments: [FigSpec.Argument]? = nil,
isPersistent: Bool? = nil,
isRequired: Bool? = nil,
requiresEquals: Bool? = nil,
repeatCount: FigSpec.Option.RepeatCount? = nil,
exclusiveOn: [String]? = nil,
dependsOn: [String]? = nil,
displayName: String? = nil,
insertValue: String? = nil,
description: String? = nil,
icon: FigSpec.Icon? = nil,
priority: Double? = nil,
isDangerous: Bool? = nil,
isHidden: Bool? = nil,
isDeprecated: Bool? = nil
) {
self.names = names
self.arguments = arguments
self.isPersistent = isPersistent
self.isRequired = isRequired
self.requiresEquals = requiresEquals
self.repeatCount = repeatCount
self.exclusiveOn = exclusiveOn
self.dependsOn = dependsOn
self.displayName = displayName
self.insertValue = insertValue
self.description = description
self.icon = icon
self.priority = priority
self.isDangerous = isDangerous
self.isHidden = isHidden
self.isDeprecated = isDeprecated
}
private enum CodingKeys: String, CodingKey {
case names = "name"
case arguments = "args"
case isPersistent
case isRequired
case requiresEquals
case repeatCount = "isRepeatable"
case exclusiveOn
case dependsOn
case displayName
case insertValue
case description
case icon
case priority
case isDangerous
case isHidden = "hidden"
case isDeprecated = "deprecated"
}
}
// .positional arguments in ArgumentParser parlance
public struct Argument: Encodable {
public struct ParserDirectives: Encodable {
public var alias: String?
}
public var name: String?
public var description: String?
public var templates: [Template]?
public var `default`: String?
public var parserDirectives: ParserDirectives?
public var isDangerous: Bool?
public var isVariadic: Bool?
public var optionsCanBreakVariadicArg: Bool?
public var isOptional: Bool?
public var isCommand: Bool?
public var isScript: Bool?
public var debounce: Bool?
public init(
name: String? = nil,
description: String? = nil,
templates: [FigSpec.Template]? = nil,
default: String? = nil,
parserDirectives: FigSpec.Argument.ParserDirectives? = nil,
isDangerous: Bool? = nil,
isVariadic: Bool? = nil,
optionsCanBreakVariadicArg: Bool? = nil,
isOptional: Bool? = nil,
isCommand: Bool? = nil,
isScript: Bool? = nil,
debounce: Bool? = nil
) {
self.name = name
self.description = description
self.templates = templates
self.default = `default`
self.parserDirectives = parserDirectives
self.isDangerous = isDangerous
self.isVariadic = isVariadic
self.optionsCanBreakVariadicArg = optionsCanBreakVariadicArg
self.isOptional = isOptional
self.isCommand = isCommand
self.isScript = isScript
self.debounce = debounce
}
private enum CodingKeys: String, CodingKey {
case name
case description
case templates = "template"
case `default`
case parserDirectives
case isDangerous
case isVariadic
case optionsCanBreakVariadicArg
case isOptional
case isCommand
case isScript
case debounce
}
}
public struct Subcommand: Encodable {
public struct ParserDirectives: Encodable {
public var flagsArePosixNoncompliant: Bool?
}
public var names: [String]
public var subcommands: [Subcommand]?
public var options: [Option]?
public var arguments: [Argument]?
public var parserDirectives: ParserDirectives?
public var displayName: String?
public var insertValue: String?
public var description: String?
public var icon: Icon?
public var priority: Double?
public var isDangerous: Bool?
public var isHidden: Bool?
public var isDeprecated: Bool?
public init(
names: [String],
subcommands: [FigSpec.Subcommand]? = nil,
options: [FigSpec.Option]? = nil,
arguments: [FigSpec.Argument]? = nil,
parserDirectives: FigSpec.Subcommand.ParserDirectives? = nil,
displayName: String? = nil,
insertValue: String? = nil,
description: String? = nil,
icon: FigSpec.Icon? = nil,
priority: Double? = nil,
isDangerous: Bool? = nil,
isHidden: Bool? = nil,
isDeprecated: Bool? = nil
) {
self.names = names
self.subcommands = subcommands
self.options = options
self.arguments = arguments
self.parserDirectives = parserDirectives
self.displayName = displayName
self.insertValue = insertValue
self.description = description
self.icon = icon
self.priority = priority
self.isDangerous = isDangerous
self.isHidden = isHidden
self.isDeprecated = isDeprecated
}
private enum CodingKeys: String, CodingKey {
case names = "name"
case subcommands
case options
case arguments = "args"
case parserDirectives
case displayName
case insertValue
case description
case icon
case priority
case isDangerous
case isHidden = "hidden"
case isDeprecated = "deprecated"
}
}
public var root: Subcommand
public init(root: Subcommand) {
self.root = root
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(root)
}
}
|
import UIKit
protocol TransactionViewControllerInput : ParentViewDataItemSettable, BasicAlertPresentable, ProjectIDSettable {
func displayViewData(_ viewData: TransactionViewData)
func updatedCopiedItem(_ item: TransactionViewDataItem)
func refreshView(_ sender: AnyObject?)
func addTransaction(_ sender: AnyObject?)
func navigate(segueID: String)
}
protocol TransactionViewControllerDelegate {
func getViewData(parentRefID: String, viewController: TransactionViewControllerInput)
func viewController(_ viewController: TransactionViewControllerInput, didSelect item: TransactionViewDataItem)
func addTransaction(parentRefID: String, viewController: TransactionViewControllerInput)
func update(item: TransactionViewDataItem, parentRefID: String, viewController: TransactionViewControllerInput)
func delete(item: TransactionViewDataItem, parentRefID: String, viewController: TransactionViewControllerInput)
func copy(item: TransactionViewDataItem, parentRefID: String, viewController: TransactionViewControllerInput)
func updateOrdinality(viewData: TransactionViewData, parentRefID: String, viewController: TransactionViewControllerInput)
}
class TransactionViewController : UITableViewController {
var viewData : TransactionViewData = TransactionViewData(section: [])
var viewDataParent : ViewDataItem = TransactionViewDataItem()
var selectedViewDataItem : TransactionViewDataItem?
var projectID: String?
@IBOutlet weak var delegateObject : AnyObject?
var delegate : TransactionViewControllerDelegate? {
return delegateObject as? TransactionViewControllerDelegate
}
lazy var addButton : UIBarButtonItem =
UIBarButtonItem(barButtonSystemItem: .add,
target: self,
action: #selector(addTransaction(_:)))
lazy var cloneButton : UIBarButtonItem =
UIBarButtonItem(image: UIImage(named: self.cloneButtonImageName),
style: .plain,
target: self,
action: #selector(cloneButtonAction(_:)))
var buttonItemsNorm : [UIBarButtonItem] { return [self.editButtonItem] }
var buttonItemsEdit : [UIBarButtonItem] { return [self.editButtonItem, self.addButton, self.cloneButton] }
var cloningIsDesired : Bool = false
var isCloning : Bool { return self.isEditing && self.cloningIsDesired }
var cloneButtonImageName : String {
return (cloningIsDesired) ? "iconCopyFill" : "iconCopy"
}
}
// MARK: - Lifecycle
extension TransactionViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.setupNavigationBar()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.beginObservingKeyboardNotifications()
self.refreshView(nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.endObservingKeyboardNotifications()
}
private func setupNavigationBar() {
self.navigationItem.setRightBarButtonItems(buttonItemsNorm, animated: false)
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
let buttonItems = (editing) ? buttonItemsEdit : buttonItemsNorm
self.navigationItem.setRightBarButtonItems(buttonItems, animated: animated)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dest = segue.destination as? ViewDataItemSettable,
let item = self.selectedViewDataItem {
dest.set(viewDataItem: item)
}
if let dest = segue.destination as? ParentViewDataItemSettable {
dest.set(parentViewDataItem: self.viewDataParent)
}
if let dest = segue.destination as? ProjectIDSettable {
dest.projectID = self.projectID
}
}
}
// MARK: - TransactionViewControllerInput
extension TransactionViewController : TransactionViewControllerInput {
func set(parentViewDataItem: ViewDataItem) {
self.viewDataParent = parentViewDataItem
self.navigationItem.title = parentViewDataItem.title
}
func displayViewData(_ viewData: TransactionViewData) {
self.viewData = viewData
self.tableView?.reloadData()
self.refreshControl?.endRefreshing()
}
func updatedCopiedItem(_ item: TransactionViewDataItem) {
guard let indexPath = self.findIndexPath(forRefID: "COPY") else { return }
self.replaceViewDataItem(atIndexPath: indexPath, withItem: item)
DispatchQueue.main.asyncAfter(deadline: (.now()+0.88)) {
self.tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.none)
}
}
@IBAction func refreshView(_ sender: AnyObject?) {
self.delegate?.getViewData(parentRefID: viewDataParent.refID, viewController: self)
}
@IBAction func addTransaction(_ sender: AnyObject?) {
self.delegate?.addTransaction(parentRefID: viewDataParent.refID, viewController: self)
}
@IBAction func cloneButtonAction(_ sender: AnyObject?) {
let wasEnabled = self.cloningIsDesired
self.cloningIsDesired = !wasEnabled
self.cloneButton.image = UIImage(named: self.cloneButtonImageName)
self.tableView?.reloadData()
}
func navigate(segueID: String) {
self.performSegue(withIdentifier: segueID, sender: self)
}
}
|
//
// ViewController.swift
// Steps
//
// Created by jason on 2019/4/23.
// Copyright © 2019年 jason. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var authBtn: UIButton = {
var btn = UIButton()
btn.setTitleColor(UIColor(red: 0.2667, green: 0.1804, blue: 0.149, alpha: 1.0), for: .normal)
btn.layer.cornerRadius = 15
btn.layer.borderColor = UIColor.clear.cgColor
btn.layer.borderWidth = 1
btn.backgroundColor = UIColor(red: 1, green: 0.4667, blue: 0, alpha: 1.0)
return btn
}()
var startBtn: UIButton = {
let btn = UIButton()
btn.layer.cornerRadius = 15
btn.setTitleColor(UIColor(red: 0.2667, green: 0.1804, blue: 0.149, alpha: 1.0), for: .normal)
btn.layer.borderColor = UIColor.clear.cgColor
btn.layer.borderWidth = 1
btn.backgroundColor = UIColor(red: 1, green: 0.4667, blue: 0, alpha: 1.0)
btn.isHidden = true
return btn
}()
var authInfo: UILabel = {
let label = UILabel()
label.text = "*HealthKit authorized."
label.font = label.font.withSize(13)
label.isHidden = true
return label
}()
var backgroundPic: UIImageView = {
let img = UIImageView()
img.backgroundColor = UIColor(red: 0.5098, green: 0.5686, blue: 0.6078, alpha: 1.0)
return img
}()
override func viewWillAppear(_ animated: Bool) {
checkStatus()
}
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
func checkStatus() {
if HealthKitSetUp.checkAuthorized() {
update()
}
}
fileprivate func setupView(){
view.addSubview(backgroundPic)
backgroundPic.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: nil, topPadding: 0, leftPadding: 0, bottomPadding: 0, rightPadding: 0, width: view.frame.width, height: 0)
authBtn.setTitle("Authorization", for: .normal)
startBtn.setTitle("Start", for: .normal)
view.addSubview(authBtn)
view.addSubview(startBtn)
authBtn.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topPadding: (view.frame.height - 120)/2, leftPadding: (view.frame.width - 200)/2, bottomPadding: 0, rightPadding: (view.frame.width - 200)/2, width: 0, height: 60)
startBtn.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, topPadding: (view.frame.height - 120)/2, leftPadding: (view.frame.width - 200)/2, bottomPadding: 0, rightPadding: (view.frame.width - 200)/2, width: 0, height: 60)
view.addSubview(authInfo)
authInfo.anchor(top: startBtn.bottomAnchor, left: view.leftAnchor, bottom: nil, right: nil, topPadding: 4, leftPadding: (view.frame.width - 200)/2, bottomPadding: 0, rightPadding: 0, width: 200, height: 20)
authBtn.addTarget(self, action: #selector(authorizeHealthKit), for: .touchUpInside)
startBtn.addTarget(self, action: #selector(handleStart), for: .touchUpInside)
}
@objc fileprivate func handleStart(){
let nextPage = StepsViewController()
present(nextPage, animated: true)
}
@objc private func authorizeHealthKit() {
HealthKitSetUp.authorizeHealthKit { (authorized, error) in
guard authorized else {
let baseMessage = "HealthKit Authorization Failed"
if let error = error {
print("\(baseMessage). Reason: \(error.localizedDescription)")
} else {
print(baseMessage)
}
return
}
DispatchQueue.main.async {
self.update()
}
}
}
func update(){
print()
authBtn.removeFromSuperview()
authInfo.isHidden = false
startBtn.isHidden = false
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
|
//
// RecipeCollectionViewCell.swift
// RecipeApp
//
// Created by Cesar Cavazos on 10/25/17.
// Copyright © 2017 The Recipe App. All rights reserved.
//
import UIKit
class RecipeCollectionViewCell: UICollectionViewCell {
@IBOutlet var recipeImage: UIImageView!
@IBOutlet var categoryLabel: UILabelCategory!
@IBOutlet var createdByLabel: UILabel!
@IBOutlet var recipeTitle: UILabel!
var recipeId: String?
var recipe: Recipe?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.contentView.layer.cornerRadius = 5
self.layer.cornerRadius = 5
}
}
|
//
// LSHTTPREquest.swift
// LetSing
//
// Created by MACBOOK on 2018/5/4.
// Copyright © 2018年 MACBOOK. All rights reserved.
//
import Foundation
enum LSHTTPMethod: String {
case post = "POST"
case get = "GET"
case patch = "PATCH"
case delete = "DELETE"
}
protocol LSHTTPRequest {
//If there are no custom header, adaptor doesn't need to implemete this method.
// func customHeader() -> [String: String]
func urlParameter() -> String
func httpMethod() -> LSHTTPMethod
func requestParameters() -> [String: String]
func urlString() -> String
func request() throws -> URLRequest
}
extension LSHTTPRequest {
func request() throws -> URLRequest {
var url = URLComponents(string: urlString() + urlParameter())
let parameters = requestParameters()
url?.queryItems = [URLQueryItem]()
for (key, value) in parameters {
url?.queryItems?.append(URLQueryItem(name: key, value: value))
}
guard let requestUrl = url else {
throw LSError.youtubeError
}
var request = URLRequest(url: requestUrl.url!)
// request.allHTTPHeaderFields = requestHeader()
request.httpMethod = httpMethod().rawValue
// request.httpBody = try JSONSerialization.data(
// withJSONObject: requestBody(),
// options: .prettyPrinted
//
// )
return request
}
}
|
//
// RoundedView.swift
// ICON
//
// Created by Yossi Sud on 31/01/2017.
// Copyright © 2017 elie buff. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable class RoundedView: UIView {
fileprivate var regularBackgroundColor : UIColor?
@IBInspectable var CornerRadius: Int = 0 {
didSet {
self.layer.cornerRadius = CGFloat(CornerRadius)
}
}
@IBInspectable var RegularBackgroundColor: UIColor? = nil {
didSet {
if let color = RegularBackgroundColor{
self.backgroundColor = color
self.regularBackgroundColor = color
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
}
}
|
//
// ReusableCell.swift
// Spearmint
//
// Created by Brian Ishii on 5/19/19.
// Copyright © 2019 Brian Ishii. All rights reserved.
//
import Foundation
protocol ReusableIdentifier: class {
static var reuseIdentifier: String { get }
static var xib: String { get }
}
extension ReusableIdentifier {
static var reuseIdentifier: String {
return "\(self)"
}
static var xib: String {
return "\(self)"
}
}
|
//
// ConsumptionListSwinject.swift
// DeliriumOver
//
// Created by Mate on 2019. 02. 10..
// Copyright © 2019. rmatesz. All rights reserved.
//
import Foundation
import Swinject
class ConsumptionListSwinject {
class func setup(_ container: Container) {
container.storyboardInitCompleted(ConsumptionListViewController.self) { (resolver, controller) in
container.register(UIViewController.self, factory: { (resolver) -> UIViewController in
controller
})
container.register(UIStoryboard.self, factory: { (resolver) -> UIStoryboard in
controller.storyboard!
})
controller.viewModel = resolver.resolve(ConsumptionListViewModel.self)
}
container.register(ConsumptionListViewModel.self) { (resolver) -> ConsumptionListViewModel in
ConsumptionListViewModelImpl(sessionRepository: resolver.resolve(SessionRepository.self)!, consumptionRepository: resolver.resolve(ConsumptionRepository.self)!, drinkRepository: resolver.resolve(DrinkRepository.self)!)
}
}
}
|
//
// SearchResponce.swift
// MusicPlayer
//
// Created by Vlad Tkachuk on 25.05.2020.
// Copyright © 2020 Vlad Tkachuk. All rights reserved.
//
import Foundation
struct SearchResponce: Codable {
var resultCount: Int
var results: [Track]
}
struct Track: Codable {
var trackName: String
var artistName: String
var collectionName: String?
var artworkUrl100: String?
var previewUrl: String?
}
|
//
// YNOrderFormViewController.swift
// 2015-08-06
//
// Created by 农盟 on 15/9/16.
// Copyright (c) 2015年 农盟. All rights reserved.
//
import UIKit
class YNOrderFormViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, YNOrderFormPayCellDelegate, YNOrderFormBottomViewDelegate {
//MARK: - public proporty
var restaurant: Restaurant?
var selectedArray: Array<YNPorterhouseDish>?
var totalPrice: Float?
var realTotalPrice: Float? {
var temp: Float = 0
if discount > 0 {
temp = totalPrice! - Float(discount)
} else {
temp = totalPrice!
}
return temp
}
var isDiscount: Bool {
return discount > 0 ? true : false
}
var discount: Int {
var temp: Int = 0
for item in orderForm!.payWay {
if item.selected {
temp += item.discount
break
}
}
temp += orderForm!.discount
return temp
}
var orderForm: OrderForm? {
didSet {
setupInterface()
setupLayout()
setupData()
}
}
func setupData() {
self.bottomView.discount = discount
bottomView.price = realTotalPrice
}
//MARK: - life cycle
override func viewDidLoad() {
super.viewDidLoad()
self.title = "订单确认"
self.view.backgroundColor = UIColor(red: 234/255.0, green: 234/255.0, blue: 234/255.0, alpha: 1)
getData()
}
func getData() {
let path = Bundle.main.path(forResource: "preOrder", ofType: "plist")
if let tempPath = path {
let dataDict: NSDictionary = NSDictionary(contentsOfFile: tempPath)!
if let status: Int = dataDict["status"] as? Int{
if status == 1 {
let typeArray: NSDictionary = dataDict["data"] as! NSDictionary
orderForm = OrderForm(dict: typeArray)
} else {
YNProgressHUD().showText("该商店暂未上传菜品", toView: self.view)
}
}
} else {
print("\n --plist文件不存在 -- \n", terminator: "")
}
}
func setupInterface() {
self.view.addSubview(tableView)
self.view.addSubview(bottomView)
}
func setupLayout() {
//tableView
Layout().addTopConstraint(tableView, toView: self.view, multiplier: 1, constant: 0)
Layout().addBottomConstraint(tableView, toView: self.view, multiplier: 1, constant: -bottomViewHeight)
Layout().addLeftConstraint(tableView, toView: self.view, multiplier: 1, constant: 0)
Layout().addRightConstraint(tableView, toView: self.view, multiplier: 1, constant: 0)
//bottomView
Layout().addTopToBottomConstraint(bottomView, toView: tableView, multiplier: 1, constant: 0)
Layout().addLeftConstraint(bottomView, toView: self.view, multiplier: 1, constant: 0)
Layout().addRightConstraint(bottomView, toView: self.view, multiplier: 1, constant: 0)
Layout().addBottomConstraint(bottomView, toView: self.view, multiplier: 1, constant: 0)
}
//MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
if isDiscount {
return 4
}
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return orderForm!.payWay.count
}
if isDiscount {
if section == 3 {
return selectedArray!.count
}
} else {
if section == 2 {
return selectedArray!.count
}
}
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// if indexPath.section == 0 {
//
// let identify: String = "CELL_userAddress"
// var cell: YNOrderFormAddressCell? = tableView.dequeueReusableCellWithIdentifier(identify) as? YNOrderFormAddressCell
//
// if cell == nil {
//
// cell = YNOrderFormAddressCell(style: UITableViewCellStyle.Default, reuseIdentifier: identify)
//
// }
//
// return cell!
// }
if (indexPath as NSIndexPath).section == 0 {
let identify: String = "CELL_pay"
var cell: YNOrderFormPayCell? = tableView.dequeueReusableCell(withIdentifier: identify) as? YNOrderFormPayCell
if cell == nil {
cell = YNOrderFormPayCell(style: UITableViewCellStyle.default, reuseIdentifier: identify)
}
cell?.payWay = orderForm?.payWay[(indexPath as NSIndexPath).row]
cell?.delegate = self
return cell!
}
if (indexPath as NSIndexPath).section == 1 {
let identify: String = "CELL_remark"
var cell: YNMealTimeOrOtherCell? = tableView.dequeueReusableCell(withIdentifier: identify) as? YNMealTimeOrOtherCell
if cell == nil {
cell = YNMealTimeOrOtherCell(style: UITableViewCellStyle.default, reuseIdentifier: identify)
}
return cell!
}
if isDiscount {
if (indexPath as NSIndexPath).section == 2 {
let identify: String = "CELL_Compon"
var cell: YNOrderFormComponCell? = tableView.dequeueReusableCell(withIdentifier: identify) as? YNOrderFormComponCell
if cell == nil {
cell = YNOrderFormComponCell(style: UITableViewCellStyle.default, reuseIdentifier: identify)
}
cell?.discount = "-¥\(discount)"
return cell!
}
if (indexPath as NSIndexPath).section == 3 {
let identify: String = "CELL_SelectDish"
var cell: YNOrderFormSelectDishCell? = tableView.dequeueReusableCell(withIdentifier: identify) as? YNOrderFormSelectDishCell
if cell == nil {
cell = YNOrderFormSelectDishCell(style: UITableViewCellStyle.default, reuseIdentifier: identify)
}
cell?.data = self.selectedArray![(indexPath as NSIndexPath).row]
return cell!
}
} else {
if (indexPath as NSIndexPath).section == 2 {
let identify: String = "CELL_SelectDish"
var cell: YNOrderFormSelectDishCell? = tableView.dequeueReusableCell(withIdentifier: identify) as? YNOrderFormSelectDishCell
if cell == nil {
cell = YNOrderFormSelectDishCell(style: UITableViewCellStyle.default, reuseIdentifier: identify)
}
cell?.data = self.selectedArray![(indexPath as NSIndexPath).row]
return cell!
}
}
let identify: String = "CELL_Address"
var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: identify)
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: identify)
}
cell!.textLabel?.text = "rose"
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// if indexPath.section == 0 {
//
// return 80
// }
//
// if indexPath.section == 3 {
//
// if indexPath.row == 1 {
//
// return 64
// }
//
// }
return 44
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 16
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 1
}
//MARK: - YNOrderFormPayCellDelegate
func orderFormPayCellSelectedButtonDidClick(_ cell: YNOrderFormPayCell) {
if cell.payWay!.selected {
let payWayId = cell.payWay!.id
for item in orderForm!.payWay {
let itemId = item.id
if itemId == payWayId {
item.selected = cell.payWay!.selected
} else {
item.selected = false
}
}
} else {
for item in orderForm!.payWay {
if item.id == cell.payWay!.id {
item.selected = cell.payWay!.selected
break
}
}
}
self.tableView.reloadData()
bottomView.discount = discount
bottomView.price = realTotalPrice
}
//MAEK: - YNOrderFormBottomViewDelegate
func orderFormBottomViewDoneButtonDidClick(_ orderFormBottomView: YNOrderFormBottomView) {
for item in orderForm!.payWay {
if item.selected {
if item.id! == "1" {//在线支付
let vertifyVc = YNVertifyOrderViewController()
vertifyVc.restaurant = restaurant
vertifyVc.totalPrice = realTotalPrice
self.navigationController?.pushViewController(vertifyVc, animated: true)
} else if item.id! == "2" {//到付
let orderSuccessVc = YNOrderSuccessViewController()
self.navigationController?.pushViewController(orderSuccessVc, animated: true)
}
break
}
}
}
//MARK: - private property
fileprivate let bottomViewHeight: CGFloat = 50
fileprivate let bottomSepatatorHeight: CGFloat = 0.6
fileprivate lazy var tableView: UITableView = {
var tempTableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.grouped)
tempTableView.delegate = self
tempTableView.dataSource = self
tempTableView.translatesAutoresizingMaskIntoConstraints = false
tempTableView.backgroundColor = UIColor.clear
return tempTableView
}()
fileprivate lazy var bottomView: YNOrderFormBottomView = {
let tempView: YNOrderFormBottomView = YNOrderFormBottomView()
tempView.translatesAutoresizingMaskIntoConstraints = false
tempView.delegate = self
return tempView
}()
}
|
//
// SwippableViewDataSource.swift
// UtilsSwippableView
//
// Created by Serg on 10.02.2020.
// Copyright © 2020 Sergey Gladkiy. All rights reserved.
//
import Foundation
import UIKit
public protocol SwippableViewDataSource: class {
func view(view: UIView, atIndex index: Int )
func numberOfViews () -> Int
}
|
//
// Income.swift
// Baisti
//
// Created by Mahmood al-Zadjali on 01/08/2017.
// Copyright © 2017 Mahmood al-Zadjali. All rights reserved.
//
import Foundation
class Income: NSObject, NSCoding {
// MARK: Properties
var name: String
var value: String
// MARK: Archiving Paths
static let documentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let archiveURL = documentsDirectory.appendingPathComponent("BaistiIncome")
//MARK: Types
struct PropertyKey {
static let name = "name"
static let value = "value"
}
//MARK: Initialisation
init(name: String, value: String) {
self.name = name
self.value = value
}
//MARK: NSCoding
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: PropertyKey.name)
aCoder.encode(value, forKey: PropertyKey.value)
}
required convenience init?(coder aDecoder: NSCoder) {
guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else {return nil}
let value = aDecoder.decodeObject(forKey: PropertyKey.value) as? String
self.init(name: name, value: value!)
}
}
|
// Corona-Warn-App
//
// SAP SE and all other contributors
// copyright owners license this file to you under the Apache
// License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
import Foundation
import UIKit
class ExposureSubmissionTestResultHeaderView: DynamicTableViewHeaderFooterView {
// MARK: Attributes.
private var titleLabel: UILabel!
private var subTitleLabel: UILabel!
private var timeLabel: UILabel!
private var imageView: UIImageView!
private var barView: UIView!
private var column = UIView()
private var baseView = UIView()
// MARK: - UITableViewCell methods.
override func prepareForReuse() {
super.prepareForReuse()
baseView.subviews.forEach { $0.removeFromSuperview() }
baseView.removeFromSuperview()
}
// MARK: - DynamicTableViewHeaderFooterView methods.
func configure(testResult: TestResult, timeStamp: Int64?) {
setupView(testResult)
subTitleLabel.text = AppStrings.ExposureSubmissionResult.card_subtitle
titleLabel.text = localizedString(for: testResult)
barView.layer.backgroundColor = color(for: testResult).cgColor
if let timeStamp = timeStamp {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .none
let date = Date(timeIntervalSince1970: TimeInterval(timeStamp))
timeLabel.text = "\(AppStrings.ExposureSubmissionResult.registrationDate) \(formatter.string(from: date))"
} else {
timeLabel.text = AppStrings.ExposureSubmissionResult.registrationDateUnknown
}
}
// MARK: Configuration helpers.
// swiftlint:disable:next function_body_length
private func setupView(_ result: TestResult) {
self.backgroundView = {
let view = UIView()
view.tintColor = UIColor.preferredColor(for: .backgroundSecondary)
return view
}()
baseView.backgroundColor = UIColor.preferredColor(for: .backgroundSecondary)
baseView.layer.cornerRadius = 14
baseView.translatesAutoresizingMaskIntoConstraints = false
addSubview(baseView)
baseView.widthAnchor.constraint(equalTo: widthAnchor, constant: -32).isActive = true
baseView.topAnchor.constraint(equalTo: topAnchor, constant: 16).isActive = true
baseView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -16).isActive = true
baseView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
barView = UIView()
barView.layer.cornerRadius = 2
barView.translatesAutoresizingMaskIntoConstraints = false
baseView.addSubview(barView)
barView.widthAnchor.constraint(equalToConstant: 4).isActive = true
barView.heightAnchor.constraint(equalToConstant: 120).isActive = true
barView.centerYAnchor.constraint(equalTo: baseView.centerYAnchor).isActive = true
barView.leftAnchor.constraint(equalTo: baseView.leftAnchor, constant: 14).isActive = true
barView.topAnchor.constraint(equalTo: baseView.topAnchor, constant: 16).isActive = true
column = UIView()
column.translatesAutoresizingMaskIntoConstraints = false
baseView.addSubview(column)
column.heightAnchor.constraint(equalTo: baseView.heightAnchor).isActive = true
column.widthAnchor.constraint(equalToConstant: 160).isActive = true
column.centerYAnchor.constraint(equalTo: baseView.centerYAnchor).isActive = true
column.leftAnchor.constraint(equalTo: barView.rightAnchor, constant: 25).isActive = true
subTitleLabel = UILabel()
subTitleLabel.text = "subTitle"
subTitleLabel.font = UIFont.systemFont(ofSize: 13)
subTitleLabel.translatesAutoresizingMaskIntoConstraints = false
column.addSubview(subTitleLabel)
subTitleLabel.leftAnchor.constraint(equalTo: column.leftAnchor, constant: 5).isActive = true
subTitleLabel.topAnchor.constraint(equalTo: barView.topAnchor).isActive = true
titleLabel = UILabel()
titleLabel.text = "title"
titleLabel.numberOfLines = 0
titleLabel.font = UIFont.boldSystemFont(ofSize: 22)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
column.addSubview(titleLabel)
titleLabel.leftAnchor.constraint(equalTo: column.leftAnchor, constant: 5).isActive = true
titleLabel.topAnchor.constraint(equalTo: subTitleLabel.bottomAnchor, constant: 5).isActive = true
titleLabel.widthAnchor.constraint(equalTo: column.widthAnchor).isActive = true
timeLabel = UILabel()
timeLabel.text = "timelabel"
timeLabel.font = UIFont.systemFont(ofSize: 13)
timeLabel.translatesAutoresizingMaskIntoConstraints = false
column.addSubview(timeLabel)
timeLabel.leftAnchor.constraint(equalTo: column.leftAnchor, constant: 5).isActive = true
timeLabel.bottomAnchor.constraint(equalTo: baseView.bottomAnchor, constant: -16).isActive = true
imageView = UIImageView(image: image(for: result))
imageView.translatesAutoresizingMaskIntoConstraints = false
baseView.addSubview(imageView)
imageView.contentMode = .scaleAspectFit
imageView.widthAnchor.constraint(equalToConstant: 100).isActive = true
imageView.heightAnchor.constraint(equalToConstant: 100).isActive = true
imageView.centerYAnchor.constraint(equalTo: baseView.centerYAnchor).isActive = true
imageView.rightAnchor.constraint(equalTo: baseView.rightAnchor, constant: -20).isActive = true
}
private func localizedString(for testResult: TestResult) -> String {
switch testResult {
case .positive:
return "\(AppStrings.ExposureSubmissionResult.card_title)\n\(AppStrings.ExposureSubmissionResult.card_positive)"
case .negative:
return "\(AppStrings.ExposureSubmissionResult.card_title)\n\(AppStrings.ExposureSubmissionResult.card_negative)"
case .invalid:
return AppStrings.ExposureSubmissionResult.card_invalid
case .pending:
return AppStrings.ExposureSubmissionResult.card_pending
}
}
private func color(for testResult: TestResult) -> UIColor {
switch testResult {
case .positive:
return UIColor.preferredColor(for: .negativeRisk)
case .negative:
return UIColor.preferredColor(for: .positiveRisk)
case .invalid:
return UIColor.preferredColor(for: .chevron)
case .pending:
return UIColor.preferredColor(for: .chevron)
}
}
private func image(for result: TestResult) -> UIImage? {
switch result {
case .positive:
return UIImage(named: "Illu_Submission_PositivTestErgebnis")
case .negative:
return UIImage(named: "Illu_Submission_NegativesTestErgebnis")
case .invalid:
return UIImage(named: "Illu_Submission_FehlerhaftesTestErgebnis")
case .pending:
return UIImage(named: "Illu_Submission_PendingTestErgebnis")
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.