text stringlengths 8 1.32M |
|---|
//
// ApiCommand.swift
// WeatherTest
//
// Created by Alexey Horokhov on 02.07.2020.
// Copyright © 2020 Alexey Horokhov. All rights reserved.
//
let apiKey = "975bfa93bb3d4da366de8628d7d30186"
enum ApiCommand: String {
case GetDetails = "https://api.openweathermap.org/data/2.5/weather?lat={LAT}&lon={LON}&appid=975bfa93bb3d4da366de8628d7d30186"
case GetWeatherIcon = "http://openweathermap.org/img/wn/@%@4x.png"
}
|
//
// CustomButton.swift
// PlaceB
//
// Created by Pavlo Dumyak on 27.01.16.
//
import UIKit
class CustomButton: UIButton {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setTitle("Downloading", forState: .Normal)
setTitle("Stop Downloading", forState: .Selected)
}
} |
//
// SocketIOManager.swift
// UXaccelerometer-2
//
// Created by cstore on 03/04/2020.
// Copyright © 2020 dasharedd. All rights reserved.
//
import Foundation
import SocketIO
class SocketIOManager {
// MARK: - Porperties
static let shared = SocketIOManager()
// Modify this url to connect to local host
private let manager = SocketManager(socketURL: URL(string: "http://cstore-af518b0d.localhost.run")!, config: [.log(true), .compress])
var socket: SocketIOClient
// MARK: - Init
private init() {
socket = manager.defaultSocket
}
// MARK: - Connection
func establichConnection() {
socket.connect()
}
func closeConnection() {
socket.disconnect()
}
}
|
//
// ClipboardManager.swift
// Combine
//
// Created by masatow on 2015/09/03.
// Copyright (c) 2015年 masatow. All rights reserved.
//
import UIKit
@objc protocol ClipboardManagerDelegate{
optional func changeClipboard(string:String?)
}
class ClipboardManager: NSObject {
var currentPasteboardChangeCount:Int!
override init() {
currentPasteboardChangeCount = UIPasteboard.generalPasteboard().changeCount
super.init()
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "receivedPasteboardChangedNotification:",
name: UIPasteboardChangedNotification,
object: nil
)
}
func getClipboardContents() -> Dictionary<String, AnyObject?>{
println(__FUNCTION__)
var board:UIPasteboard = UIPasteboard.generalPasteboard()
let string:String? = board.string
let url:NSURL? = board.URL
let image:UIImage? = board.image
return ["String":string,"URL":url,"Image":image]
}
func checkUpdateClipboard() -> Bool{
let changeCount = UIPasteboard.generalPasteboard().changeCount
if( changeCount > currentPasteboardChangeCount){
currentPasteboardChangeCount = changeCount
return true
}
return false
}
func receivedPasteboardChangedNotification(contents:NSNotification){
var board:UIPasteboard = UIPasteboard.generalPasteboard()
var string = board.string;
var image = board.image;
var url = board.URL;
println(__FUNCTION__)
}
}
|
//
// JSMovieDetialViewController.swift
// DoubanMini
//
// Created by jsonmess on 14/11/2.
// Copyright (c) 2014年 jsonmess. All rights reserved.
//
import UIKit
class JSMovieDetialViewController: UIViewController {
var getinfoTool:JSGetDoubanMovieInfo?;
var theMovie:JSMovieModel?;
var movieid:NSString?;
override func viewDidLoad() {
self.title="title";
super.viewDidLoad()
self.GetMovieDataFromDouban();
// Do any additional setup after loading the view.
}
func setMovieId(theid:NSString)
{
self.movieid=theid;
}
func GetMovieDataFromDouban()
{
if getinfoTool==nil
{
getinfoTool=JSGetDoubanMovieInfo();
}
getinfoTool?.getMovieDetailInfoFromDoubanServiceWithMovieID(movieid, successBlock: { (dic:[NSObject : AnyObject]!) -> Void in
//初始化电影模型
var thedic:NSDictionary = dic;
self.theMovie=JSMovieModel(movieInfo: dic);
NSLog("%@", self.theMovie!);
}, failedBlock: { (error:NSError!) -> Void in
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// ViewController.swift
// Ad
//
// Created by 小俣圭佑 on 2020/06/20.
// Copyright © 2020 KeisukeOmata. All rights reserved.
//
//GoogleAdMob
//アプリを追加
//広告ユニットを追加
//info.plistのソースコードにGADApplicationIdentifierキーとAdMobアプリIDの文字列を追加
import UIKit
import GoogleMobileAds
class ViewController: UIViewController {
//クラスはGADBannerView
@IBOutlet weak var BannerView: GADBannerView!
override func viewDidLoad() {
super.viewDidLoad()
//バナー広告の読み込み
//テストID
BannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
BannerView.rootViewController = self
BannerView.load(GADRequest())
}
}
|
//
// InviteNewUserController.swift
// mojo_test
//
// Created by Yunyun Chen on 1/26/19.
// Copyright © 2019 Yunyun Chen. All rights reserved.
//
import UIKit
import Firebase
import MessageUI
class InviteNewUserController: UIViewController, MFMessageComposeViewControllerDelegate {
var user: User? {
didSet {
guard let invitationCode = self.user?.invitationCode else { return }
self.codeLabel.text = "Your code: \(invitationCode)"
}
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
navigationItem.title = "Invite Friends"
// fetchCurrentUser()
setupLayout()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tabBarController?.tabBar.isHidden = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
tabBarController?.tabBar.isHidden = false
}
fileprivate func setupLayout() {
view.addSubview(inviteFriendsLabel)
inviteFriendsLabel.anchor(top: nil, leading: view.leadingAnchor, bottom: nil, trailing: view.trailingAnchor, padding: .init(top: 0, left: 36, bottom: 0, right: 36))
inviteFriendsLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
view.addSubview(invitationButton)
invitationButton.anchor(top: nil, leading: view.leadingAnchor, bottom: view.bottomAnchor, trailing: view.trailingAnchor, padding: .init(top: 0, left: 36, bottom: 48, right: 36), size: .init(width: view.frame.width - 72, height: 56))
invitationButton.backgroundColor = .black
invitationButton.setTitleColor(.white, for: .normal)
invitationButton.addTarget(self, action: #selector(handleSendMessage), for: .touchUpInside)
view.addSubview(codeLabel)
codeLabel.anchor(top: nil, leading: nil, bottom: invitationButton.topAnchor, trailing: nil, padding: .init(top: 0, left: 0, bottom: 24, right: 0))
codeLabel.centerXAnchor.constraint(equalToSystemSpacingAfter: view.centerXAnchor, multiplier: 1).isActive = true
}
@objc fileprivate func handleSendMessage() {
if MFMessageComposeViewController.canSendText() {
let composeVC = MFMessageComposeViewController()
composeVC.messageComposeDelegate = self
// Configure the fields of the interface.
composeVC.recipients = [""]
composeVC.body = "I've been using Mojo and think you'd really like it too! A new social app built on ethereum blockchain. If you sign up with my code, \(user?.invitationCode ?? ""), we'll both get 10 free Jo tokens. You can download the app here: ..."
// Present the view controller modally.
self.present(composeVC, animated: true, completion: nil)
} else {
print("SMS services are not available")
}
}
let codeLabel = UILabel(text: "Your code: ", font: .systemFont(ofSize: 18, weight: .bold))
let inviteFriendsLabel: UILabel = {
let label = UILabel()
let attributedString = NSMutableAttributedString(string: "Get Free 10 Jo", attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 22, weight: .medium)])
attributedString.append(NSMutableAttributedString(string: "\nWant more mojo? Every friend you get to join is worth 10 tokens, for both of you. Hit your peeps up!.", attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16)]))
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 4
attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
label.attributedText = attributedString
label.numberOfLines = 0
label.textAlignment = .center
return label
}()
let invitationButton = UIButton(title: "Send Text", cornerRadius: 4, font: .systemFont(ofSize: 18))
func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
controller.dismiss(animated: true, completion: nil)
}
}
|
//
// AppSegueIdentifiers.swift
// Asoft-Intern-Final-Demo
//
// Created by Danh Nguyen on 12/29/16.
// Copyright © 2016 Danh Nguyen. All rights reserved.
//
import Foundation
class AppSegueIdentifiers {
//#MARK: - Segue in Home
static let kIdentifierSegueHomeToCombineResultVC = "HomeToCombineResultVC"
static let kIdentifierSegueHomeToChefsVC = "HomeToChefsViewController"
static let kIdentifierSegueHomeToSettingVC = "HomeToSettingViewController"
static let kIdentifierSegueHomeToChallengeVC = "HomeToChallengeViewController"
static let kIdentifierSegueHomeToSearchVC = "HomeToSearchViewController"
static let kIdentifierSegueHomeToCategoryVC = "HomeToCategoryViewController"
static let kIdentifierSegueHomeToFavoriteVC = "HomeToFavoriteViewController"
//#MARK: - Segue in ChefsViewController
static let kIdentifierSegueGordonToChefVideo = "GordonToChefVideo"
static let kIdentifierSegueMarcoToChefVideo = "MarcoToChefVideo"
static let kIdentifierSegueWolfgangToChefVideo = "WolfgangToChefVideo"
//#MARK: - Segue in CategoryViewController
static let kIdentifierSegueCategoryToRecipeChoosen = "CategoryToRecipeChoosen"
}
|
//
// PhotoCell.swift
// Virtual Tourist
//
// Created by Johan Smet on 12/08/15.
// Copyright (c) 2015 Justcode.be. All rights reserved.
//
import Foundation
import UIKit
class PhotoCell : UICollectionViewCell {
@IBOutlet weak var image: UIImageView!
@IBOutlet weak var overlay: UIView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
////////////////////////////////////////////////////////////////////////////////
//
// change the appearance of the cell
//
func stateWaiting() {
image.hidden = true
overlay.backgroundColor = UIColor(red: 81.0/255, green: 137.0/255, blue: 180.0/255, alpha: 1.0)
overlay.alpha = 1.0
overlay.hidden = false
activityIndicator.hidden = false
}
func stateImage(path : String) {
activityIndicator.hidden = true
overlay.hidden = true
if let imgData = UIImage(contentsOfFile: path) {
image.image = imgData
image.hidden = false
}
}
func stateSelected() {
overlay.backgroundColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.8)
overlay.alpha = 0.8
overlay.hidden = false
activityIndicator.hidden = true
}
func stateDeselected() {
overlay.hidden = true
}
} |
//
// ViewController.swift
// CashierTips
//
// Created by Kevin Jackson on 4/4/19.
// Copyright © 2019 Kevin Jackson. All rights reserved.
//
import UIKit
class MainViewController: UITableViewController {
var stateController: StateController!
var sections = ["Total Tips", "Cashiers"]
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
navigationController?.navigationBar.prefersLargeTitles = true
navigationItem.leftBarButtonItem = editButtonItem
navigationItem.leftBarButtonItem?.tintColor = UIColor.init(named: "CTGreen")
title = "Cashier Tips"
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case "gotoTipView":
let totalTipsVC = segue.destination as! TipViewController
totalTipsVC.delegate = self
totalTipsVC.selectedAmount = stateController.worldState.totalTips
case "newCashier":
let cashierVC = segue.destination as! CashierViewController
cashierVC.delegate = self
case "editCashier":
let cashierVC = segue.destination as! CashierViewController
cashierVC.delegate = self
cashierVC.cashier = stateController.worldState.cashiers[tableView.indexPathForSelectedRow!.row]
cashierVC.cashierIndex = tableView.indexPathForSelectedRow!.row
default:
preconditionFailure("Unknown segue identifier.")
}
}
// MARK: - Target-Actions
@IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "newCashier", sender: self)
}
// MARK: - Helper Functions
@objc fileprivate func animateTableViewReloadData() {
UIView.transition(with: tableView,
duration: 0.4,
options: .transitionCrossDissolve,
animations: { self.tableView.reloadData() })
}
// MARK: - TableView Datasource
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == 0 ? 1 : stateController.worldState.cashiers.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell
if indexPath.section == 0 {
cell = tableView.dequeueReusableCell(withIdentifier: "totalTipsCell", for: indexPath)
cell.textLabel?.text = String(format: "$%.2f", stateController.worldState.totalTips)
cell.detailTextLabel?.text = stateController.worldState.totalTipsDescription
}
else {
cell = tableView.dequeueReusableCell(withIdentifier: "cashierCell", for: indexPath)
let cashier = stateController.worldState.cashiers[indexPath.row]
cell.textLabel?.text = cashier.name + String(format: " (%.2f h)", cashier.hoursWorked)
cell.detailTextLabel?.text = CurrencyFormatter().stringFrom(
double: cashier.calculateTips(usingRate: stateController.worldState.tipRate)
)
}
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
if indexPath.section == 0 {
stateController.setTotalTips(0)
animateTableViewReloadData()
}
else {
stateController.removeCashier(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
// Add delay to allow for the row deletion
perform(#selector(animateTableViewReloadData),
with: nil,
afterDelay: 0.4
)
}
}
}
// MARK: Moving Rows
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return indexPath.section == 0 ? false : true
}
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
stateController.moveCashier(
from: sourceIndexPath.row,
to: destinationIndexPath.row
)
}
// Prevent moving across sections.
override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
if proposedDestinationIndexPath.section != sourceIndexPath.section {
return sourceIndexPath
}
else {
return proposedDestinationIndexPath
}
}
// MARK: Headers
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// Header text
let header = view as! UITableViewHeaderFooterView
header.textLabel?.font = UIFont.systemFont(ofSize: Constants.HeaderFontSize)
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return Constants.HeaderFontSize + Constants.Padding
}
// MARK: Footers
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if section == 0 {
return nil
}
else {
if stateController.worldState.cashiers.isEmpty {
let footerView = UITableViewHeaderFooterView()
footerView.backgroundView = UIView(frame: footerView.bounds)
footerView.backgroundView?.backgroundColor = UIColor.white
footerView.textLabel?.text = "Press '+' to add cashiers."
return footerView
}
else {
return nil
}
}
}
override func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
let footerView = view as! UITableViewHeaderFooterView
footerView.textLabel?.textColor = UIColor.lightGray
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == 0 {
return 0
}
else {
if stateController.worldState.cashiers.isEmpty {
return 60
}
else {
return 0
}
}
}
// MARK: - TableView Delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0 {
performSegue(withIdentifier: "gotoTipView", sender: self)
}
else {
performSegue(withIdentifier: "editCashier", sender: self)
}
}
}
// MARK: - DollarAmountViewDelegate
extension MainViewController: TipViewDelegate {
func tipAmountUpdated(amount: Double) {
// Update model
stateController.setTotalTips(amount)
// Update view
animateTableViewReloadData()
}
}
// MARK: - CashierDelegate
extension MainViewController: CashierDelegate {
func cashierUpdated(cashier: Cashier, isNew: Bool, cashierIndex: Int) {
// Add new cashier
if isNew {
stateController.addCashier(cashier: cashier)
let indexPath = IndexPath(row: (stateController.worldState.cashiers.count - 1), section: 1)
tableView.insertRows(at: [indexPath], with: .automatic)
}
// Replace existing cashier
else {
stateController.updateCashier(cashier: cashier, at: cashierIndex)
}
animateTableViewReloadData()
}
}
|
import Foundation
/// A struct that holds user informations.
public struct User: Codable {
/// Holds the user id.
let id: Int
/// Holds the user username.
let username: String
/// Holds the user email.
let email: String
/// Holds the user first name.
let firstName: String
/// Holds the user last name.
let lastName: String
/// Holds the user student id.
let studentID: String?
/// :nodoc:
enum CodingKeys: String, CodingKey {
case id, username, email
case firstName = "first_name"
case lastName = "last_name"
case studentID = "student_id"
}
}
|
//
// AccountDetailCell.swift
// YouthGroup
//
// Created by Adam Zarn on 2/22/18.
// Copyright © 2018 Adam Zarn. All rights reserved.
//
import Foundation
import UIKit
class AccountDetailCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
func setUp() {
titleLabel?.textColor = Colors.darkBlue
}
}
|
//
// HeroViewController.swift
// Idle Poring Guide
//
// Created by Tommy Loh on 27/10/2017.
// Copyright © 2017 Tommy Loh. All rights reserved.
//
import UIKit
import Firebase
class HeroViewController: UIViewController {
@IBOutlet weak var HeroCharecter: UISegmentedControl!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var attributeLabel: UILabel!
var FirebaseRef = FIRDatabase.database().reference()
// var listOfHero = [Hero]()
override func viewDidLoad() {
super.viewDidLoad()
let heroCharecterTitle: String = HeroCharecter.titleForSegment(at: HeroCharecter.selectedSegmentIndex)!
self.imageView.image = UIImage(named:"Novice")
self.attributeLabel.text = heroCharecterTitle
}
@IBAction func HeroSegment(_ sender: Any) {
let heroCharecterTitle: String = HeroCharecter.titleForSegment(at: HeroCharecter.selectedSegmentIndex)!
if HeroCharecter.selectedSegmentIndex == 0 {
self.attributeLabel.text = heroCharecterTitle
self.imageView.image = UIImage(named:"archer")
}
if HeroCharecter.selectedSegmentIndex == 1 {
self.attributeLabel.text = heroCharecterTitle
}
if HeroCharecter.selectedSegmentIndex == 2 {
self.attributeLabel.text = heroCharecterTitle
}
}
}
|
//
// NetworkClientProtocol.swift
// MVVM
//
// Created by Kannan Prasad on 24/01/2021.
//
import Foundation
protocol NetworkClientProtocol {
func fetch<T:Decodable>(with request:URLRequest, decodingType:T.Type, completion:@escaping (Result<T,NetworkError>) -> Void)
}
|
//
// TransactScreen.swift
// WealthTrust
//
// Created by Hemen Gohil on 9/24/16.
// Copyright © 2016 Hemen Gohil. All rights reserved.
//
import UIKit
class TransactScreen: UIViewController {
@IBOutlet weak var view1Switch: UIView!
@IBOutlet weak var view2BuySip: UIView!
@IBOutlet weak var view3Redeem: UIView!
@IBOutlet weak var view4SmartSearch: UIView!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController!.navigationBar.tintColor = UIColor.whiteColor()
self.title = "Transact"
let titleDict: NSDictionary = [NSFontAttributeName: UIFont.boldSystemFontOfSize(18),NSForegroundColorAttributeName: UIColor.whiteColor()]
self.navigationController!.navigationBar.titleTextAttributes = titleDict as? [String : AnyObject]
// Change the navigation bar background color to blue.
self.navigationController!.navigationBar.barTintColor = UIColor.defaultAppColorBlue
SharedManager.addShadowToView(view1Switch)
SharedManager.addShadowToView(view2BuySip)
SharedManager.addShadowToView(view3Redeem)
SharedManager.addShadowToView(view4SmartSearch)
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(false, animated: true)
self.setNavigationBarItemLeftForTransactScreen()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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.
}
*/
@IBAction func btnSwitchClicked(sender: UIButton) {
print("Switch Clicked")
sender.backgroundColor = UIColor.clearColor()
RootManager.sharedInstance.isFrom = IS_FROM.SwitchToDirect
RootManager.sharedInstance.navigateToScreen(self, data: [:])
}
@IBAction func btnBuySIPClicked(sender: UIButton) {
print("Buy/SIP Clicked")
sender.backgroundColor = UIColor.clearColor()
RootManager.sharedInstance.isFrom = IS_FROM.BuySIP
RootManager.sharedInstance.navigateToScreen(self, data: [:])
}
@IBAction func btnRedeemClicked(sender: UIButton) {
print("Redeem Clicked")
sender.backgroundColor = UIColor.clearColor()
let allUser = DBManager.getInstance().getAllUser()
if allUser.count==0
{
SharedManager.invokeAlertMethod(APP_NAME, strBody: "Please do login first", delegate: nil)
}else{
let arrMFAccounts = DBManager.getInstance().getMFAccountsForRedeemCondition()
if arrMFAccounts.count==0 {
SharedManager.invokeAlertMethod("No schemes found", strBody: "Currently there are no schemes in your WealthTrust portfolio for redemption.", delegate: nil)
}else{
let objRedeem = self.storyboard?.instantiateViewControllerWithIdentifier(ksbIdRedeemScreen) as! RedeemScreen
objRedeem.arrSchemes = arrMFAccounts
self.navigationController?.pushViewController(objRedeem, animated: true)
}
}
}
@IBAction func btnSmartSearchClicked(sender: UIButton) {
print("Smart Clicked")
sender.backgroundColor = UIColor.clearColor()
let objSearch = self.storyboard?.instantiateViewControllerWithIdentifier(ksbidSearchScreen) as! SearchScreen
self.navigationController?.pushViewController(objSearch, animated: true)
}
@IBAction func btnTouchDown(sender: UIButton) {
sender.backgroundColor = UIColor(white: 1, alpha: opacityButtonTouchEffect)
}
@IBAction func btnTouchDragEnter(sender: UIButton) {
sender.backgroundColor = UIColor(white: 1, alpha: opacityButtonTouchEffect)
}
@IBAction func btnTouchDragExit(sender: UIButton) {
sender.backgroundColor = UIColor.clearColor()
}
}
|
//
// NumberExtension.swift
// TG
//
// Created by Andrii Narinian on 8/5/17.
// Copyright © 2017 ROLIQUE. All rights reserved.
//
import Foundation
extension Int {
var secondsFormatted: String {
let (h, m, s) = (self / 3600, (self % 3600) / 60, (self % 3600) % 60)
var output = ""
if h > 0 { output += "\(h) Hours, "}
output += "\(m) Minutes, \(s) Seconds"
return output
}
var secondsFormattedShort: String {
let (h, m, s) = (self / 3600, (self % 3600) / 60, (self % 3600) % 60)
var output = ""
if h > 0 { output += "\(h) Hours, "}
output += "\(m)m, \(s)s"
return output
}
}
|
//
// LazyGridsView.swift
// Layouts
//
// Created by Nestor Hernandez on 11/07/22.
//
import SwiftUI
enum LayoutType {
case v
case h
}
struct LazyGridsView: View {
@ObservedObject var viewModel: LazyGridsViewModel
var coordinator: AppNavigation?
let tw = UIScreen.main.bounds.width
@State var type: LayoutType? = .v
var body: some View {
NavigationView {
ScrollView(self.type == .v ? .vertical : .horizontal) {
if self.type == .v {
verticalGrid
} else {
horizontalGrid
}
}
.toolbar {
ToolbarItem(placement:.navigationBarLeading) {
Button("Back"){
self.coordinator?.navigateTo(.home)
}
}
ToolbarItem(placement:.navigationBarTrailing){
Menu("Options"){
Button("LazyVGrid"){
self.type = .v
}
Button("LazyHGrid"){
self.type = .h
}
}
}
}
}
}
@ViewBuilder
var verticalGrid: some View {
LazyVGrid(columns: [
GridItem(.adaptive(minimum: 70))
]){
ForEach(viewModel.randomSubgenres.shuffled(), content: \.view)
}.padding(.horizontal)
.navigationTitle("Lazy Grids")
.navigationBarTitleDisplayMode(.large)
}
@ViewBuilder
var horizontalGrid: some View {
LazyHGrid(rows: [
GridItem(.flexible(minimum: 100)),
GridItem(.flexible(minimum: 100))
]){
ForEach(viewModel.randomSubgenres.shuffled(), content: \.view).background(Color.red)
}.padding(.horizontal)
.navigationTitle("Lazy Grids")
.navigationBarTitleDisplayMode(.large)
}
}
struct LazyGridsView_Previews: PreviewProvider {
static var previews: some View {
LazyGridsView(viewModel: LazyGridsViewModel(), coordinator: nil)
}
}
|
//
// Game.swift
// bionic-app
//
// Created by Vitaliy on 11/23/16.
// Copyright © 2016 Vitaliy. All rights reserved.
//
import Foundation
import UIKit
import Messages
class FMKGameResponse : Serializable {
var userIdentifier : UUID!
var data : String!
init(userIdentifier: UUID, data: String)
{
self.data = data
self.userIdentifier = userIdentifier
}
static func fromJson(json: Dictionary<String, Any>) -> FMKGameResponse? {
if let userIdentifier = json["userIdentifier"] as? String, let id = UUID(uuidString: userIdentifier) {
let data = json["data"] as! String
return FMKGameResponse(userIdentifier: id, data: data)
}
return nil
}
}
class FMKGameInfo : Category {
var title: String!
init(_ code: String, title: String)
{
self.title = title
super.init(type: Category.GameInfo, code: code)
}
static func fromJson(json: Dictionary<String, Any>) -> FMKGameInfo? {
if let code = json["code"] as? String, let title = json["title"] as? String {
return FMKGameInfo(code, title: title)
}
return nil
}
}
class FMKGameItem : Category {
static let Fuck = "Fuck"
static let Marry = "Marry"
static let Kill = "Kill"
var data : String?
var imageUrl : String?
var responses : [FMKGameResponse] = []
init(_ code: String, imageUrl: String?, data: String?)
{
self.data = data
self.imageUrl = imageUrl
super.init(type: Category.FMKResult, code: code)
}
static func fromJson(json: Dictionary<String, Any>) -> FMKGameItem? {
if let code = json["code"] as? String {
let imageUrl = json["imageUrl"] as? String
let data = json["data"] as? String
let result = FMKGameItem(code, imageUrl: imageUrl, data: data!)
if let responses = json["responses"] as? [Dictionary<String, Any>] {
for response in responses {
result.responses.append(FMKGameResponse.fromJson(json: response)!)
}
}
return result
}
return nil
}
func marryCount() -> Int {
return self.responses
.filter { (c: FMKGameResponse) -> Bool in
return c.data == FMKGameItem.Marry
}.count
}
func fuckCount() -> Int {
return self.responses
.filter { (c: FMKGameResponse) -> Bool in
return c.data == FMKGameItem.Fuck
}.count
}
func killCount() -> Int {
return self.responses
.filter { (c: FMKGameResponse) -> Bool in
return c.data == FMKGameItem.Kill
}.count
}
}
class FMKGame : Categories, ExecutionContext {
var gameIdentifier : UUID?
var respondents : [String] = []
var games : [FMKGameItem] {
get {
let items = categories.filter { (c: Category) -> Bool in return c.type == Category.FMKResult }
return items as! [FMKGameItem]
}
}
var gameInfo : FMKGameInfo? {
get {
let items = categories.filter { (c: Category) -> Bool in return c.type == Category.GameInfo }
if items.count > 0 { return items[0] as? FMKGameInfo }
return nil
}
}
var fmks : [Element] {
get {
let items = categories.filter { (c: Category) -> Bool in return c.type == Category.FMK }
return items as! [Element]
}
}
var questions : [Element] {
get {
let items = categories.filter { (c: Category) -> Bool in return c.type == Category.Question }
return items as! [Element]
}
}
var buttons : [Element] {
get {
let items = categories.filter { (c: Category) -> Bool in return c.type == Category.Button }
return items as! [Element]
}
}
var titles : [Element] {
get {
let items = categories.filter { (c: Category) -> Bool in return c.type == Category.Title }
return items as! [Element]
}
}
init(type: String, code: String, userIdentifier: UUID, gameIdentifier: UUID?)
{
self.gameIdentifier = gameIdentifier
//self.title = title
super.init(code: code, type: type, userIdentifier: userIdentifier)
super.categories = [ ]
}
func getMarryKill() -> [FMKGameItem] {
return self.categories
.filter { (c: Category) -> Bool in
if let g = c as? FMKGameItem, let r = g.data {
return r == FMKGameItem.Fuck || r == FMKGameItem.Marry
}
return false
} as! [FMKGameItem]
}
static func fromJson(json: Dictionary<String, Any>) -> FMKGame {
let userIdentifier = UUID(uuidString: (json["userIdentifier"] as? String)!)
var gameIdentifier : UUID? = nil
if let uuid = json["gameIdentifier"] as? String { gameIdentifier = UUID(uuidString: uuid) }
let type = json["type"] as! String
let code = json["code"] as! String
let result = FMKGame(type: type, code: code, userIdentifier: userIdentifier!, gameIdentifier: gameIdentifier)
if let respondents = json["respondents"] as? [String] {
result.respondents = respondents
}
if let categories = json["categories"] as? [Dictionary<String, Any>] {
for category in categories {
if let type = category["type"] as? String, type == Category.FMKResult {
result.categories.append(FMKGameItem.fromJson(json: category)!)
} else if let type = category["type"] as? String, type == Category.GameInfo {
result.categories.append(FMKGameInfo.fromJson(json: category)!)
} else{
result.categories.append(Element.fromJson(json: category)!)
}
}
}
return result
}
}
extension FMKGame {
var queryItems: [URLQueryItem] {
return [URLQueryItem(name: "game", value: self.toJsonString()?.toBase64())]
}
convenience init?(queryItems: [URLQueryItem], isOriginal: Bool) {
if !isOriginal, let response = queryItems.first(where:{$0.name == "response"}), let r = Serializable.fromJson(jsonString: (response.value?.fromBase64()!)!, createFunction: FMKGame.fromJson) {
self.init(type: r.type, code: r.code, userIdentifier: r.userIdentifier, gameIdentifier: r.gameIdentifier)
self.categories = r.categories
} else {
if let game = queryItems.first(where:{$0.name == "game"}), let r = Serializable.fromJson(jsonString: (game.value?.fromBase64()!)!, createFunction: FMKGame.fromJson) {
self.init(type: r.type, code: r.code, userIdentifier: r.userIdentifier, gameIdentifier: r.gameIdentifier)
self.categories = r.categories
} else {
return nil
}
}
}
convenience init?(message: MSMessage?, isOriginal: Bool) {
guard let messageURL = message?.url else { return nil }
guard let urlComponents = NSURLComponents(url: messageURL, resolvingAgainstBaseURL: false), let queryItems = urlComponents.queryItems else { return nil }
self.init(queryItems: queryItems, isOriginal: isOriginal)
}
}
extension FMKGame {
func render() -> UIImage {
let view = UIView()
view.layer.frame = CGRect(x: 0, y: 0, width: 500, height: 500)
var images = self.getMarryKill()
var frame : CGRect
var imageView : UIImageView
if images.count > 0 {
if let url = images[0].imageUrl {
frame = CGRect(x: 0, y: 0, width: 250, height: 250)
imageView = UIImageView(frame: frame)
imageView.showImage(imageUrl: url, sync: true)
view.addSubview(imageView)
}
}
if images.count > 1 {
if let url = images[1].imageUrl {
frame = CGRect(x: 250, y: 0, width: 250, height: 250)
imageView = UIImageView(frame: frame)
imageView.showImage(imageUrl: url, sync: true)
view.addSubview(imageView)
}
}
if images.count > 2 {
if let url = images[2].imageUrl {
frame = CGRect(x: 0, y: 250, width: 250, height: 250)
imageView = UIImageView(frame: frame)
imageView.showImage(imageUrl: url, sync: true)
view.addSubview(imageView)
}
}
if images.count > 3 {
if let url = images[3].imageUrl {
frame = CGRect(x: 250, y: 250, width: 250, height: 250)
imageView = UIImageView(frame: frame)
imageView.showImage(imageUrl: url, sync: true)
view.addSubview(imageView)
}
}
return UIImage(view: view)
}
}
|
//
// TestModel.swift
// HCModel
//
// Created by hucong on 2018/1/22.
// Copyright © 2018年 hucong. All rights reserved.
//
import Foundation
class FirstModel: Codable {
var success = false
var errorMsg = ""
var content: SecondModel?
}
class SecondModel: Codable {
var title = ""
var count = 0
var time = 0.0
var childs: [ThirdModel]?
}
class ThirdModel: Codable {
var name = ""
var age = 0
}
|
// FeedView.swift
// Pursuitstgram-Firebase-Project
// Created by Eric Widjaja on 11/25/19.
// Copyright © 2019 Eric.W. All rights reserved.
import UIKit
class FeedView: UIView {
var feedCell = FeedCellCV()
//MARK: - Objects
var feedLabel: UILabel = {
let label = UILabel()
label.font = UIFont.init(name: "Noteworthy-Bold", size: 40)
label.text = "F E E D"
label.textAlignment = .center
label.textColor = .white
return label
}()
var feedCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 200, height: 200)
let collection = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collection.backgroundColor = .white
collection.register(FeedCellCV.self, forCellWithReuseIdentifier: "feedCell")
return collection
}()
lazy var feedViewArray = [self.feedLabel, self.feedCollectionView]
//MARK:Add ViewsToSubviews
func addViewsToSubView() {
for aView in feedViewArray {
self.addSubview(aView)
aView.translatesAutoresizingMaskIntoConstraints = false
}
}
//MARK: - Constraints
func feedConstraints() {
addViewsToSubView()
feedLabelConstraints()
collectionViewConstraints()
}
private func feedLabelConstraints() {
NSLayoutConstraint.activate([
feedLabel.centerXAnchor.constraint(equalTo: safeAreaLayoutGuide.centerXAnchor),
feedLabel.centerYAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor,constant: 40),
feedLabel.heightAnchor.constraint(equalToConstant: 60),
feedLabel.widthAnchor.constraint(equalToConstant: 150)])
}
private func collectionViewConstraints() {
NSLayoutConstraint.activate([
feedCollectionView.topAnchor.constraint(equalTo: feedLabel.bottomAnchor, constant: 40),
feedCollectionView.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor),
feedCollectionView.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor),
feedCollectionView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor)])
}
override init(frame: CGRect) {
super.init(frame: UIScreen.main.bounds)
feedConstraints()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
|
enum CarColor: String {
case black = "Black"
case white = "White"
}
enum CarBrand {
case Audi, Honda, Mazda
}
protocol Car {
var color: CarColor { get set }
func drive()
}
class Audi: Car {
var color: CarColor
func drive() {
print("driving \(color) audi")
}
init(_ color: CarColor) {
self.color = color
}
}
class Honda: Car {
var color: CarColor
func drive() {
print("driving \(color) honda")
}
init(_ color: CarColor) {
self.color = color
}
}
class Mazda: Car {
var color: CarColor
func drive() {
print("driving \(color) mazda")
}
init(_ color: CarColor) {
self.color = color
}
}
protocol CarFactory {
static func createMazda() -> Mazda
static func createHonda() -> Honda
static func createAudi() -> Audi
}
class WhiteCarsFactory: CarFactory {
static func createAudi() -> Audi {
return Audi(.white)
}
static func createHonda() -> Honda {
return Honda(.white)
}
static func createMazda() -> Mazda {
return Mazda(.white)
}
}
class BlackCarsFactory: CarFactory {
static func createAudi() -> Audi {
return Audi(.black)
}
static func createHonda() -> Honda {
return Honda(.black)
}
static func createMazda() -> Mazda {
return Mazda(.black)
}
}
// USAGE
let whiteAudi = WhiteCarsFactory.createAudi()
let whiteHonda = WhiteCarsFactory.createHonda()
let blackMazda = BlackCarsFactory.createMazda()
whiteAudi.drive()
whiteHonda.drive()
blackMazda.drive()
|
//
// NSLogDestination.swift
// Logging
//
// Copyright (c) 2020 Anodized Software, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
import Foundation
public class NSLogDestination<CategoryType>: Destination
where CategoryType: Hashable & CaseIterable & RawRepresentable,
CategoryType.RawValue == String {
let formatter: MessageFormatter<CategoryType>
public init(formatter: MessageFormatter<CategoryType> = DefaultMessageFormatter(includeTimestamp: false, includeCategory: true)) {
self.formatter = formatter
}
public func log(_ message: Message<CategoryType>) {
NSLog("%@", formatter.format(message))
}
}
|
//
// PhotosCell.swift
// AnimalClassifier
//
// Created by yauheni prakapenka on 16.11.2019.
// Copyright © 2019 yauheni prakapenka. All rights reserved.
//
import UIKit
import SDWebImage
class PhotosCell: UICollectionViewCell {
// MARK: - Input
static let reuseId = "PhotosCell"
// MARK: - Subview
private let checkmark: UIImageView = {
let image = #imageLiteral(resourceName: "check")
let imageView = UIImageView(image: image)
imageView.alpha = 0
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
let photoImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.backgroundColor = .white
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
return imageView
}()
// MARK: - View lifecycle
override func prepareForReuse() {
super.prepareForReuse()
photoImageView.image = nil
}
override var isSelected: Bool {
didSet {
updateSelectedState()
}
}
var unsplashPhoto: Unsplashphoto! {
didSet {
let photoUrl = unsplashPhoto.urls["regular"]
guard let imageURL = photoUrl, let url = URL(string: imageURL) else { return }
photoImageView.sd_setImage(with: url, completed: nil)
}
}
// MARK: - Initializer
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(photoImageView)
addSubview(checkmark)
makeConstraints()
updateSelectedState()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private methods
private func updateSelectedState() {
photoImageView.alpha = isSelected ? 0.7 : 1
checkmark.alpha = isSelected ? 1 : 0
}
}
// MARK: - Layout
private extension PhotosCell {
private func makeConstraints() {
NSLayoutConstraint.activate([
photoImageView.topAnchor.constraint(equalTo: self.topAnchor),
photoImageView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
photoImageView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
photoImageView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
checkmark.centerXAnchor.constraint(equalTo: photoImageView.centerXAnchor),
checkmark.centerYAnchor.constraint(equalTo: photoImageView.centerYAnchor),
checkmark.widthAnchor.constraint(equalToConstant: 60),
checkmark.heightAnchor.constraint(equalTo: checkmark.widthAnchor)
])
}
}
|
//
// StatisticalAnalysisController.swift
// HISmartPhone
//
// Created by DINH TRIEU on 12/25/17.
// Copyright © 2017 MACOS. All rights reserved.
//
import UIKit
class StatisticalAnalysisController: BaseViewController {
//MARK: Variable
fileprivate var isSelectFromDate = true
fileprivate let cellAverageBloodPressueId = "cellAverageBloodPressueId"
fileprivate let cellSurpassTheThresholdId = "cellSurpassTheThresholdId"
fileprivate var fromDate: Date?
fileprivate var toDate: Date?
//MARK: UIControl
fileprivate let datePicker: UIDatePicker = {
let datePickerConfig = UIDatePicker()
datePickerConfig.datePickerMode = .date
datePickerConfig.locale = Locale(identifier: "vi-VN")
datePickerConfig.maximumDate = Date()
return datePickerConfig
}()
private let titleLabel: UILabel = {
let label = UILabel()
label.text = "Kết quả huyết áp"
label.textColor = Theme.shared.primaryColor
label.font = UIFont.systemFont(ofSize: Dimension.shared.titleFontSize)
return label
}()
private let fromLabel: UILabel = {
let label = UILabel()
label.text = "Từ"
label.textColor = Theme.shared.darkBlueTextColor
label.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize)
return label
}()
private let toLabel: UILabel = {
let label = UILabel()
label.text = "Đến"
label.textColor = Theme.shared.darkBlueTextColor
label.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize)
return label
}()
private lazy var fromTextField: UITextField = {
let textfieldConfig = UITextField()
textfieldConfig.placeholder = "dd/MM/yyyy"
textfieldConfig.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize)
textfieldConfig.textColor = Theme.shared.primaryColor
textfieldConfig.inputView = self.datePicker
return textfieldConfig
}()
private var fromDropImage: UIImageView = {
let imageConfig = UIImageView()
imageConfig.image = UIImage(named: "Drop_item")
imageConfig.contentMode = .scaleAspectFill
return imageConfig
}()
private let fromLineDivider: UIView = {
let viewConfig = UIView()
viewConfig.backgroundColor = Theme.shared.lineDeviderColor
return viewConfig
}()
private lazy var toTextField: UITextField = {
let textfieldConfig = UITextField()
textfieldConfig.placeholder = "dd/MM/yyyy"
textfieldConfig.font = UIFont.systemFont(ofSize: Dimension.shared.bodyFontSize)
textfieldConfig.textColor = Theme.shared.primaryColor
textfieldConfig.inputView = self.datePicker
return textfieldConfig
}()
private var toDropImage: UIImageView = {
let imageConfig = UIImageView()
imageConfig.image = UIImage(named: "Drop_item")
imageConfig.contentMode = .scaleAspectFill
return imageConfig
}()
private let toLineDivider: UIView = {
let viewConfig = UIView()
viewConfig.backgroundColor = Theme.shared.lineDeviderColor
return viewConfig
}()
fileprivate lazy var resultTableView: UITableView = {
let tabelView = UITableView()
tabelView.isHidden = true
tabelView.delegate = self
tabelView.dataSource = self
tabelView.separatorColor = UIColor.clear
tabelView.backgroundColor = UIColor.clear
tabelView.estimatedRowHeight = 100
tabelView.isScrollEnabled = false
tabelView.rowHeight = UITableViewAutomaticDimension
tabelView.register(AverageBloodPressureCel.self, forCellReuseIdentifier: self.cellAverageBloodPressueId)
tabelView.register(SurpassTheThresholdCell.self, forCellReuseIdentifier: self.cellSurpassTheThresholdId)
return tabelView
}()
//MARK: Initialize function
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if UIDevice.current.orientation.isLandscape {
self.resultTableView.isScrollEnabled = true
} else {
self.resultTableView.isScrollEnabled = false
}
}
override func setupView() {
self.setupViewNavigationBar()
self.setupViewTitleLabel()
self.setupViewFromTextfiled()
self.setupViewFromDropItemImage()
self.setupViewFromLineDivider()
self.setupViewFromLabel()
self.setupViewToTextfiled()
self.setupViewToDropItemImage()
self.setupViewToLineDivider()
self.setupViewToLabel()
self.setupViewResultTableView()
self.fromTextField.becomeFirstResponder()
self.datePicker.addTarget(self, action: #selector(datePickerValueChanged(_:)), for: .valueChanged)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(superViewTapped))
self.view.addGestureRecognizer(tapGesture)
}
//MARK: Feature
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
if UIDevice.current.orientation.isLandscape {
self.resultTableView.isScrollEnabled = true
} else {
self.resultTableView.isScrollEnabled = false
}
}
private func fetchData() {
guard let fromDate = self.fromDate else { return }
guard let toDate = self.toDate else { return }
StatisticalAnalysisFacade.getStaticsticalFromToDate(fromDate: fromDate, toDate: toDate) { (BPOResults) in
self.resultTableView.isHidden = false
self.resultTableView.reloadData()
}
}
//MARK: Action UIControl
@objc func superViewTapped() {
self.view.endEditing(true)
}
@objc func backButtonPressed() {
BPOHelper.shared.BPOResults.removeAll()
self.navigationController?.popViewController(animated: true)
}
@objc func fromTextFieldBeginEdit() {
let toDate: Date? = self.toDate != nil ? self.toDate : Date()
self.datePicker.maximumDate = toDate
self.datePicker.minimumDate = nil
self.isSelectFromDate = true
self.fromLineDivider.backgroundColor = Theme.shared.primaryColor
}
@objc func fromTextFieldEndEdit() {
if self.fromDate == nil {
self.fromDate = self.datePicker.date
self.fromTextField.text = self.fromDate?.getDescription_DDMMYYYY_WithSlash()
}
self.isSelectFromDate = true
self.fromLineDivider.backgroundColor = Theme.shared.lineDeviderColor
self.fetchData()
}
@objc func toTextFieldBeginEdit() {
let fromDate: Date? = self.fromDate != nil ? self.fromDate : Date()
self.datePicker.minimumDate = fromDate
self.datePicker.maximumDate = Date()
self.isSelectFromDate = false
self.toLineDivider.backgroundColor = Theme.shared.primaryColor
self.fetchData()
}
@objc func toTextFieldEndEdit() {
if self.toDate == nil {
self.toDate = self.datePicker.date
self.toTextField.text = self.toDate?.getDescription_DDMMYYYY_WithSlash()
}
self.isSelectFromDate = false
self.toLineDivider.backgroundColor = Theme.shared.lineDeviderColor
self.fetchData()
}
@objc func datePickerValueChanged(_ sender: UIDatePicker) {
if self.isSelectFromDate {
self.fromDate = sender.date
self.fromTextField.text = sender.date.getDescription_DDMMYYYY_WithSlash()
} else {
self.toDate = sender.date
self.toTextField.text = sender.date.getDescription_DDMMYYYY_WithSlash()
}
}
//MARK: SetupView
private func setupViewNavigationBar() {
self.navigationItem.setHidesBackButton(true, animated: false)
//TITLE
let titleLabel = UILabel()
titleLabel.text = "Phân tích thống kê"
titleLabel.textColor = Theme.shared.defaultTextColor
titleLabel.frame = CGRect(x: 0, y: 0, width: 120, height: 30)
titleLabel.font = UIFont.systemFont(ofSize: Dimension.shared.titleFontSize, weight: UIFont.Weight.medium)
self.navigationItem.titleView = titleLabel
//BACK ITEM
self.navigationItem.addLeftBarItem(with: UIImage(named: "back_white"), target: self, selector: #selector(backButtonPressed), title: nil)
}
private func setupViewTitleLabel() {
self.view.addSubview(self.titleLabel)
if #available(iOS 11, *) {
self.titleLabel.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(Dimension.shared.normalHorizontalMargin)
make.top.equalTo(self.view.safeAreaInsets)
.offset(Dimension.shared.normalVerticalMargin)
}
} else {
self.titleLabel.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(Dimension.shared.normalHorizontalMargin)
make.top.equalTo(self.topLayoutGuide.snp.bottom)
.offset(Dimension.shared.normalVerticalMargin)
}
}
}
//FROM
private func setupViewFromTextfiled() {
self.view.addSubview(self.fromTextField)
if #available(iOS 11, *) {
self.fromTextField.snp.makeConstraints { (make) in
make.left.equalTo(self.view.safeAreaLayoutGuide)
.offset(Dimension.shared.largeHorizontalMargin)
make.width.equalTo(Dimension.shared.widthFROMANDTOTextField)
make.height.equalTo(Dimension.shared.defaultHeightTextField)
make.top.equalTo(self.titleLabel.snp.bottom).offset(3 * Dimension.shared.normalVerticalMargin)
}
} else {
self.fromTextField.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(Dimension.shared.largeHorizontalMargin)
make.width.equalTo(Dimension.shared.widthFROMANDTOTextField)
make.height.equalTo(Dimension.shared.defaultHeightTextField)
make.top.equalTo(self.titleLabel.snp.bottom).offset(3 * Dimension.shared.normalVerticalMargin)
}
}
self.fromTextField.addTarget(self, action: #selector(fromTextFieldBeginEdit), for: .editingDidBegin)
self.fromTextField.addTarget(self, action: #selector(fromTextFieldEndEdit), for: .editingDidEnd)
}
private func setupViewFromDropItemImage() {
self.view.addSubview(self.fromDropImage)
self.fromDropImage.snp.makeConstraints { (make) in
make.width.equalTo(10 * Dimension.shared.widthScale)
make.height.equalTo(5 * Dimension.shared.heightScale)
make.bottom.equalTo(self.fromTextField).offset(-Dimension.shared.smallVerticalMargin)
make.left.equalTo(self.fromTextField.snp.right)
}
}
private func setupViewFromLineDivider() {
self.view.addSubview(self.fromLineDivider)
self.fromLineDivider.snp.makeConstraints { (make) in
make.height.equalTo(Dimension.shared.heightLineDivider)
make.left.equalTo(self.fromTextField).offset(-Dimension.shared.smallHorizontalMargin)
make.right.equalTo(self.fromDropImage).offset(Dimension.shared.smallHorizontalMargin)
make.top.equalTo(self.fromTextField.snp.bottom).offset(Dimension.shared.smallHorizontalMargin)
}
}
private func setupViewFromLabel() {
self.view.addSubview(self.fromLabel)
self.fromLabel.snp.makeConstraints { (make) in
make.left.equalTo(self.fromTextField)
make.bottom.equalTo(self.fromTextField.snp.top).offset(-Dimension.shared.mediumVerticalMargin)
}
}
//TO
private func setupViewToTextfiled() {
self.view.addSubview(self.toTextField)
if #available(iOS 11, *) {
self.toTextField.snp.makeConstraints { (make) in
make.right.equalTo(self.view.safeAreaLayoutGuide)
.offset(-Dimension.shared.largeHorizontalMargin)
make.width.equalTo(self.fromTextField)
make.height.equalTo(Dimension.shared.defaultHeightTextField)
make.top.equalTo(self.fromTextField)
}
} else {
self.toTextField.snp.makeConstraints { (make) in
make.right.equalToSuperview().offset(-Dimension.shared.largeHorizontalMargin)
make.width.equalTo(self.fromTextField)
make.height.equalTo(Dimension.shared.defaultHeightTextField)
make.top.equalTo(self.fromTextField)
}
}
self.toTextField.addTarget(self, action: #selector(toTextFieldBeginEdit), for: .editingDidBegin)
self.toTextField.addTarget(self, action: #selector(toTextFieldEndEdit), for: .editingDidEnd)
}
private func setupViewToDropItemImage() {
self.view.addSubview(self.toDropImage)
self.toDropImage.snp.makeConstraints { (make) in
make.width.equalTo(10 * Dimension.shared.widthScale)
make.height.equalTo(5 * Dimension.shared.heightScale)
make.bottom.equalTo(self.toTextField).offset(-Dimension.shared.smallVerticalMargin)
make.left.equalTo(self.toTextField.snp.right)
}
}
private func setupViewToLineDivider() {
self.view.addSubview(self.toLineDivider)
self.toLineDivider.snp.makeConstraints { (make) in
make.height.equalTo(Dimension.shared.heightLineDivider)
make.left.equalTo(self.toTextField).offset(-Dimension.shared.smallHorizontalMargin)
make.right.equalTo(self.toDropImage).offset(Dimension.shared.smallHorizontalMargin)
make.top.equalTo(self.toTextField.snp.bottom).offset(Dimension.shared.smallHorizontalMargin)
}
}
private func setupViewToLabel() {
self.view.addSubview(self.toLabel)
self.toLabel.snp.makeConstraints { (make) in
make.left.equalTo(self.toTextField)
make.bottom.equalTo(self.toTextField.snp.top).offset(-Dimension.shared.mediumVerticalMargin)
}
}
private func setupViewResultTableView() {
self.view.addSubview(self.resultTableView)
self.resultTableView.snp.makeConstraints { (make) in
make.width.centerX.equalToSuperview()
make.bottom.equalToSuperview()
make.top.equalTo(self.fromLineDivider.snp.bottom).offset(Dimension.shared.largeHorizontalMargin)
}
}
}
//MARK: - UITableViewDelegate, UITableViewDataSource
extension StatisticalAnalysisController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.item == 0 {
guard let cell = tableView.dequeueReusableCell(withIdentifier: self.cellAverageBloodPressueId, for: indexPath) as? AverageBloodPressureCel else { return UITableViewCell() }
cell.selectionStyle = .none
cell.backgroundColor = Theme.shared.darkBGColor
cell.setData()
return cell
} else {
guard let cell = tableView.dequeueReusableCell(withIdentifier: self.cellSurpassTheThresholdId, for: indexPath) as? SurpassTheThresholdCell else { return UITableViewCell() }
cell.selectionStyle = .none
cell.backgroundColor = Theme.shared.darkBGColor
cell.setData()
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.view.endEditing(true)
}
}
|
//
// User.swift
// producehero
//
// Created by Ted Kim on 2020-02-15.
// Copyright © 2020 Ted Kim. All rights reserved.
//
import Foundation
struct User {
let id: String
let userId: String
let password: String?
}
|
//
// UITextField+Extension.swift
// IBKit
//
// Created by NateKim on 2019/12/10.
// Copyright © 2019 NateKim. All rights reserved.
//
import UIKit
extension UITextField {
@discardableResult public func text(_ text: String?) -> Self {
self.text = text
return self
}
@discardableResult public func attributedText(_ attributedText: NSAttributedString?) -> Self {
self.attributedText = attributedText
return self
}
@discardableResult public func textColor(_ textColor: UIColor) -> Self {
self.textColor = textColor
return self
}
@discardableResult public func font(_ font: UIFont) -> Self {
self.font = font
return self
}
@discardableResult public func textAlignment(_ textAlignment: NSTextAlignment) -> Self {
self.textAlignment = textAlignment
return self
}
@discardableResult public func borderStyle(_ borderStyle: UITextField.BorderStyle) -> Self {
self.borderStyle = borderStyle
return self
}
@discardableResult public func defaultTextAttributes(_ defaultTextAttributes: [NSAttributedString.Key: Any]) -> Self {
self.defaultTextAttributes = defaultTextAttributes
return self
}
@discardableResult public func placeholder(_ placeholder: String?) -> Self {
self.placeholder = placeholder
return self
}
@discardableResult public func attributedPlaceholder(_ attributedPlaceholder: NSAttributedString?) -> Self {
self.attributedPlaceholder = attributedPlaceholder
return self
}
@discardableResult public func clearsOnBeginEditing(_ clearsOnBeginEditing: Bool) -> Self {
self.clearsOnBeginEditing = clearsOnBeginEditing
return self
}
@discardableResult public func adjustsFontSizeToFitWidth(_ adjustsFontSizeToFitWidth: Bool) -> Self {
self.adjustsFontSizeToFitWidth = adjustsFontSizeToFitWidth
return self
}
@discardableResult public func minimumFontSize(_ minimumFontSize: CGFloat) -> Self {
self.minimumFontSize = minimumFontSize
return self
}
@discardableResult public func delegate(_ delegate: UITextFieldDelegate?) -> Self {
self.delegate = delegate
return self
}
@discardableResult public func background(_ background: UIImage?) -> Self {
self.background = background
return self
}
@discardableResult public func disabledBackground(_ disabledBackground: UIImage?) -> Self {
self.disabledBackground = disabledBackground
return self
}
@discardableResult public func allowsEditingTextAttributes(_ allowsEditingTextAttributes: Bool) -> Self {
self.allowsEditingTextAttributes = allowsEditingTextAttributes
return self
}
@discardableResult public func typingAttributes(_ typingAttributes: [NSAttributedString.Key: Any]?) -> Self {
self.typingAttributes = typingAttributes
return self
}
@discardableResult public func clearButtonMode(_ clearButtonMode: UITextField.ViewMode) -> Self {
self.clearButtonMode = clearButtonMode
return self
}
@discardableResult public func leftView(_ leftView: UIView?) -> Self {
self.leftView = leftView
return self
}
@discardableResult public func leftViewMode(_ leftViewMode: UITextField.ViewMode) -> Self {
self.leftViewMode = leftViewMode
return self
}
@discardableResult public func rightView(_ rightView: UIView?) -> Self {
self.rightView = rightView
return self
}
@discardableResult public func rightViewMode(_ rightViewMode: UITextField.ViewMode) -> Self {
self.rightViewMode = rightViewMode
return self
}
@discardableResult public func inputView(_ inputView: UIView?) -> Self {
self.inputView = inputView
return self
}
@discardableResult public func inputAccessoryView(_ inputAccessoryView: UIView?) -> Self {
self.inputAccessoryView = inputAccessoryView
return self
}
@discardableResult public func clearsOnInsertion(_ clearsOnInsertion: Bool) -> Self {
self.clearsOnInsertion = clearsOnInsertion
return self
}
}
|
//
// MashableViewController.swift
// Feedr
//
// Created by Adam Ostrich on 3/4/15.
// Copyright (c) 2015 Tedi Konda. All rights reserved.
//
import UIKit
class MashableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {
var json: NSDictionary?
override func viewDidLoad() {
super.viewDidLoad()
if let url = NSURL(string: "http://mashable.com/stories.json") {
let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
// Check for error
if error != nil {
println(error.localizedDescription)
}
else {
if let jsonDict: AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) {
self.json = jsonDict as? NSDictionary
}
else {
println("Error parsing JSON data")
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
})
task.resume()
}
else {
println("Oh noes! Couldn't unwrap url.")
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let jsonData = self.json {
if let newArticles = jsonData["new"] as? NSArray {
return newArticles.count
}
}
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell!
if cell == nil {
cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "cell")
}
if let jsonData = self.json {
if let newArticles = jsonData["new"] as? NSArray {
if let article = newArticles[indexPath.row] as? NSDictionary {
if let title = article["title"] as? NSString {
cell.textLabel?.text = title
}
if let author = article["author"] as? NSString {
cell.detailTextLabel?.text = author
}
}
}
}
return cell
}
//on click
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
/*
var url: NSURL?
if let jsonData = self.json {
if let newArticles = jsonData["new"] as? NSArray {
if let article = newArticles[indexPath.row] as? NSDictionary {
if let link = article["link"] as? NSString {
url = NSURL(string: link)
}
}
}
}
performSegueWithIdentifier("web", sender: NSURLRequest(URL: url!))
*/
performSegueWithIdentifier("web", sender: indexPath.row)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let index = sender as? Int {
if let jsonData = self.json {
if let newArticles = jsonData["new"] as? NSArray {
if let article = newArticles[index] as? NSDictionary {
var destinationViewController = segue.destinationViewController as WebViewController
var request: NSURLRequest?
if let link = article["link"] as? NSString {
if let url = NSURL(string: link) {
destinationViewController.request = NSURLRequest(URL: url)
}
}
if let myTitle = article["title"] as? NSString {
destinationViewController.passedTitle = myTitle
}
}
}
}
}
/*
if let request = sender as? NSURLRequest {
var destinationViewController = segue.destinationViewController as WebViewController
destinationViewController.request = request
destinationViewController.passedTitle =
}
*/
}
}
|
//
// SignInViewController.swift
// RootsCapstoneProj
//
// Created by Abby Allen on 7/24/20.
// Copyright © 2020 Abby Allen. All rights reserved.
//
import UIKit
import CoreData
import FirebaseFirestore
import FirebaseAuth
class SignInViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var emailText: UITextField!
@IBOutlet weak var passwordText: UITextField!
@IBOutlet weak var errorLabel: UILabel!
@IBOutlet weak var start: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
(UIApplication.shared.delegate as! AppDelegate).restrictRotation = .portrait
start.layer.cornerRadius = 3.0
start.layer.shadowOffset = CGSize(width: 0.0, height: 5.0)
start.layer.shadowOpacity = 0.3
start.layer.shadowRadius = 1.0
passwordText.delegate = self
emailText.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
passwordText.resignFirstResponder()
emailText.resignFirstResponder()
return true
}
@IBAction func resetPassword(_ sender: Any) {
let email = getEmailAddress()
if email != "" {
Auth.auth().sendPasswordReset(withEmail: email) { (error) in
if let error = error as NSError? {
self.errorLabel.textColor = UIColor.red
switch AuthErrorCode(rawValue: error.code) {
case .userNotFound:
self.errorLabel.text = "User not found"
case .invalidEmail:
self.errorLabel.text = "Invalid email"
case .invalidRecipientEmail:
self.errorLabel.text = "Invalid recipient"
case .invalidSender:
self.errorLabel.text = "Invalid sender"
case .invalidMessagePayload:
self.errorLabel.text = "Invalid message template"
default:
self.errorLabel.text = "Error message: \(error.localizedDescription)"
}
} else {
self.errorLabel.textColor = UIColor.black
self.errorLabel.text = "An email has been sent to reset your password"
}
}
}
else{
errorLabel.textColor = UIColor.black
errorLabel.text = "Please provide your email"
}
}
func getEmailAddress() -> String {
let email = emailText.text!
if emailText.text == nil {
return ""
}
else {
return email
}
}
@IBAction func signIn(_ sender: Any) {
let email = emailText.text!
let password = passwordText.text!
Auth.auth().signIn(withEmail: email, password: password) { [weak self] authResult, error in guard self != nil else { return }
if let error = error as NSError? {
self?.errorLabel.textColor = UIColor.red
switch AuthErrorCode(rawValue: error.code) {
case .operationNotAllowed:
self?.errorLabel.text = "This action is not allowed"
case .userDisabled:
self?.errorLabel.text = "This user has been disabled"
case .wrongPassword:
self?.errorLabel.text = "Wrong password"
case .invalidEmail:
self?.errorLabel.text = "Invalid email"
default:
self?.errorLabel.text = "\(error.localizedDescription)"
}
}
else {
self?.errorLabel.textColor = UIColor.green
self?.errorLabel.text = "Success!"
let db = Firestore.firestore()
let uid: String = Auth.auth().currentUser!.uid
let doc = db.collection("users").document(uid)
doc.getDocument { (document, error) in
if let document = document, document.exists {
let doc = document.get("admin")
if doc as! Int == 1 {
let storyboard = UIStoryboard(name: "Admin", bundle: nil)
let mainTabBarController = storyboard.instantiateViewController(identifier: "AdminViewController")
(UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.changeRootViewController(mainTabBarController)
}
else {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let mainTabBarController = storyboard.instantiateViewController(identifier: "MainViewController")
(UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.changeRootViewController(mainTabBarController)
}
} else {
print("Document does not exist")
}
}
}
}
}
@IBAction func unwind(_ sender: UIStoryboardSegue){}
}
|
import XCTest
@testable import Voysis
class UtilTests: XCTestCase {
private var sessionMock = AudioSessionMock()
func testGenerateAudioRecordParamsDefaultSampleRate() {
let config = DataConfig(url: URL(string: "https://test.com")!, refreshToken: "123")
let audioRecordParams = Utils.generateAudioRecordParams(config, sessionMock)
XCTAssertEqual(AudioSessionMock.TEST_DEFAULT_SAMPLE_RATE, audioRecordParams.sampleRate)
}
func testGenerateAudioRecordParamsOverrideValues() {
let audioRecordParams = AudioRecordParams(sampleRate: 123.0, readBufferSize: 321)
let config = DataConfig(url: URL(string: "https://test.com")!, refreshToken: "123", audioRecordParams: audioRecordParams)
let generatedParams = Utils.generateAudioRecordParams(config, sessionMock)
XCTAssertEqual(audioRecordParams.sampleRate, generatedParams.sampleRate)
XCTAssertEqual(audioRecordParams.readBufferSize, generatedParams.readBufferSize)
}
func testMaxRecordingLength() {
XCTAssertEqual(320000, Utils.calculateMaxRecordingLength(16000))
XCTAssertEqual(820000, Utils.calculateMaxRecordingLength(41000))
XCTAssertEqual(960000, Utils.calculateMaxRecordingLength(48000))
}
}
|
import Utils
import XCTest
typealias TestConfigurable = TestCaseConfigurable & TestCaseAPIConfigurable
protocol TestCaseConfiguration: CaseIterable, RawRepresentable where RawValue == String {}
protocol TestCaseConfigurable: BaseTest {
associatedtype Configuration: TestCaseConfiguration
}
extension TestCaseConfigurable {
var testCaseConfiguration: [Configuration] { Configuration.allCases.filter(contains) }
}
protocol TestCaseAPIConfiguration: TestCaseConfiguration {
var api: [MockAPI] { get }
}
protocol TestCaseAPIConfigurable: BaseTest {
associatedtype API: TestCaseAPIConfiguration
}
extension TestCaseAPIConfigurable {
var testCaseAPI: [MockAPI] {
API.allCases.filter(contains) |> map(\API.api) >>> flatMap(identity)
}
}
/// Arguments are set inside Scheme -> Tests -> Arguments
enum TestEnvironmentArgument: String {
case analytics
var argument: String? { ProcessInfo.processInfo.environment[rawValue] }
var boolValue: Bool { argument.boolValue }
var stringValue: String { argument ?? "" }
}
|
//
// MainTabBarController.swift
// DouBiShow
//
// Created by zhoubiwen on 2017/1/22.
// Copyright © 2017年 zhou. All reserved.
//
import UIKit
class MainTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
setupChildrenVC()
}
}
// 子控制器设置
extension MainTabBarController {
func setupChildrenVC() {
addChildVC(stroyboardName: "Home")
addChildVC(stroyboardName: "Live")
addChildVC(stroyboardName: "Follow")
addChildVC(stroyboardName: "Profile")
}
private func addChildVC(stroyboardName :String) {
let vc = UIStoryboard.init(name: stroyboardName, bundle: nil).instantiateInitialViewController()!
addChildViewController(vc)
}
}
|
//
// showTbilValue.swift
// animalHealthLog
//
// Created by 細川聖矢 on 2020/04/15.
// Copyright © 2020 Seiya. All rights reserved.
//
import SwiftUI
struct showTbilValue: View {
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(
entity: BtList.entity(),
sortDescriptors: [NSSortDescriptor(keyPath:\BtList.saveDate,ascending:false)],
predicate: NSPredicate(format:"tbil != %@","")
)
var notCompletedTbilLists:FetchedResults<BtList>
var dateFormatter:DateFormatter{
let formatter = DateFormatter()
formatter.setLocalizedDateFormatFromTemplate("yMMMMd")
return formatter
}
var body: some View {
List{
Section(header:Text("日付|結果|基準値|単位")){
ForEach(notCompletedTbilLists){list in
// if list.tbil as? String != nil{
HStack{
Text("\(list.saveDate ?? Date(),formatter: self.dateFormatter)").frame(width:UIScreen.screenWidth/5)
Divider()
TbilValueList(btList:list).frame(width: UIScreen.screenWidth/5)
ListSecondContainer(btUnitValue: BtListView().liverUnits["T-Bil"] ?? "error", btCriteriaValue: BtListView().liverBtCriteria["T-Bil"] ?? "error")
}
// }
}
.onDelete{
indexSet in
for index in indexSet{
self.managedObjectContext.delete(self.notCompletedTbilLists[index])
}//onDelete
}
}
}
}
}
struct showTbilValue_Previews: PreviewProvider {
static var previews: some View {
showTbilValue()
}
}
|
//
// PostsModel.swift
// DemoVIPER
//
// Created by Mahesh Mavurapu on 21/11/19.
// Copyright © 2019 Mahesh Mavurapu. All rights reserved.
//
import Foundation
import ObjectMapper
import UIKit
protocol PostListRemoteDataManagerInputProtocol: class {
var remoteRequestHandler: PostListRemoteDataManagerOutputProtocol? { get set }
// INTERACTOR -> REMOTEDATAMANAGER
func retrievePostList()
}
protocol PostListRemoteDataManagerOutputProtocol: class {
// REMOTEDATAMANAGER -> INTERACTOR
func onPostsRetrieved(_ posts: [PostsModel])
func onError()
}
protocol PostListLocalDataManagerInputProtocol: class {
// INTERACTOR -> LOCALDATAMANAGER
func retrievePostList() throws -> [Post]
func savePost(id: Int, title: String, imageUrl: String, thumbImageUrl: String) throws
}
struct PostsModel {
var id = 0
var title = ""
var imageUrl = ""
var thumbImageUrl = ""
}
extension PostsModel: Mappable {
init?(map: Map) {
}
mutating func mapping(map: Map) {
id <- map["id"]
title <- map["title"]
imageUrl <- map["url"]
thumbImageUrl <- map["thumbUrl"]
}
}
|
import Foundation
class UseCaseCopyParser {
class func action(parserID: String, transactionID: String) -> Composed.Action<Any, PCParserCopyResult> {
return Composed
.access(transactionID)
.action(PCParserRepository.fetchListUsingTransactionID(asCopy: false))
.action(PCParserRepository.createCopyInList(parserID))
.action(Composed.Action<PCParserCopyResult, PCParserCopyResult> { $1(.success($0!)) })
.copyAX()
.joinAY { copyResult,_ in return copyResult!.list }
.copyYA()
.action(PCParserRepository.storeList(transactionID: transactionID))
.copyXA()
.wrap()
}
}
|
#if os(OSX) || os(iOS) || os(tvOS) || os(watchOS)
import CoreLocation
extension Region {
init(coordinate: CLLocationCoordinate2D, precision: Int = defaultPrecision) {
self = Region(latitude: coordinate.latitude, longitude: coordinate.longitude, precision: precision)
}
init(location: CLLocation, precision: Int = defaultPrecision) {
self = Region(coordinate: location.coordinate, precision: precision)
}
}
extension CLLocationCoordinate2D {
public init(geohash: String) {
guard let region = Region(hash: geohash) else {
self = kCLLocationCoordinate2DInvalid
return
}
let (lat, lng) = region.center
self = CLLocationCoordinate2DMake(lat, lng)
}
public func geohash(precision: Int = defaultPrecision) -> String {
return Region(coordinate: self, precision: precision).hash
}
public func geohash(precision: Precision) -> String {
return Region(coordinate: self, precision: precision.rawValue).hash
}
/// Geohash neighbors
public func neighbors(precision: Int = defaultPrecision) -> [String] {
return Region.init(coordinate: self, precision: precision).neighbors().map { $0.hash }
}
public func neighbors(precision: Precision) -> [String] {
return neighbors(precision: precision.rawValue)
}
}
extension CLLocation {
public convenience init?(geohash: String) {
guard let region = Region.init(hash: geohash) else { return nil }
self.init(latitude: region.center.latitude, longitude: region.center.longitude)
}
public func geohash(precision: Int = defaultPrecision) -> String {
return Region(coordinate: self.coordinate, precision: precision).hash
}
public func geohash(precision: Precision) -> String {
return geohash(precision: precision.rawValue)
}
/// Geohash neighbors
public func neighbors(precision: Int = defaultPrecision) -> [String] {
return Region.init(location: self, precision: precision).neighbors().map { $0.hash }
}
public func neighbors(precision: Precision) -> [String] {
return neighbors(precision: precision.rawValue)
}
}
#endif
|
//
// TimetableTableViewController.swift
// CourseFantastic
//
// Created by Lee Kelly on 19/04/2016.
// Copyright © 2016 LMK Technologies. All rights reserved.
//
import UIKit
import CoreData
import SwiftyJSON
import CoreLocation
import CoreBluetooth
enum CheckType {
case In
case Out
}
class TimetableTableViewController: UITableViewController, NSFetchedResultsControllerDelegate, APIServiceDelegate, CLLocationManagerDelegate, CBPeripheralManagerDelegate {
var subjectDeliveries: [SubjectDelivery] = []
var fetchedResultsController: NSFetchedResultsController!
var subjectDelivery: SubjectDelivery!
var student: Student!
var locationManager: CLLocationManager!
var beaconRegion: CLBeaconRegion!
var lastFoundBeacon: CLBeacon! = CLBeacon()
var lastProximity: CLProximity! = CLProximity.Unknown
var bluetoothManager = CBPeripheralManager()
var btOn = false
var canRange = false
var isRanging = false
var attemptingAttendanceCheckType = CheckType.In
var hasAttemptedAttendanceCheck = false
var attemptedRanges = 0
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
// Allow auto resizing of tableview row
tableView.estimatedRowHeight = 60.0
tableView.rowHeight = UITableViewAutomaticDimension
// Core Data
if let managedObjectContext = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext {
fetchedResultsController = NSFetchedResultsController(fetchRequest: SubjectDelivery.fetchRequest(), managedObjectContext: managedObjectContext, sectionNameKeyPath: "dateOnly", cacheName: nil)
fetchedResultsController.delegate = self
do {
try fetchedResultsController.performFetch()
subjectDeliveries = fetchedResultsController.fetchedObjects as! [SubjectDelivery]
} catch {
print(error)
}
}
// Location Manager
locationManager = CLLocationManager()
locationManager.delegate = self
let uuid = NSUUID(UUIDString: "B0702880-A295-A8AB-F734-031A98A512DE")!
beaconRegion = CLBeaconRegion(proximityUUID: uuid, identifier: "GG.21")
// beaconRegion.notifyOnEntry = true
// beaconRegion.notifyOnExit = true
// locationManager.requestWhenInUseAuthorization()
// locationManager.startMonitoringForRegion(beaconRegion)
// locationManager.startUpdatingLocation()
// Bluetooth Manager
bluetoothManager.delegate = self
// Refresh Control
refreshControl = UIRefreshControl()
// refreshControl?.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl?.addTarget(self, action: #selector(refresh), forControlEvents: .ValueChanged)
// tableView.addSubview(refreshControl!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// override func viewDidAppear(animated: Bool) {
// ActivityIndicator().show()
// }
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return fetchedResultsController.sections!.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sections = fetchedResultsController.sections! as [NSFetchedResultsSectionInfo]
let sectionInfo = sections[section]
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let sections = fetchedResultsController.sections!
let sectionInfo = sections[section]
return sectionInfo.name.toDateString()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TimetableTableViewCell
let subjectDelivery = fetchedResultsController.objectAtIndexPath(indexPath) as! SubjectDelivery
// Configure the cell...
cell.startTimeLabel.text = subjectDelivery.startDate.timeFormat()
cell.endTimeLabel.text = subjectDelivery.endDate.timeFormat()
cell.subjectLabel.text = subjectDelivery.subject.name
cell.locationLabel.text = subjectDelivery.location
// Colour the time labels
cell.startTimeLabel.textColor = UIColor.grayColor()
cell.endTimeLabel.textColor = UIColor.grayColor()
let now = NSDate()
if subjectDelivery.startDate.isGreaterThanDate(now) {
cell.startTimeLabel.textColor = UIColor.blackColor()
} else {
if subjectDelivery.endDate.isGreaterThanDate(now) {
cell.endTimeLabel.textColor = UIColor.blackColor()
}
}
return cell
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
subjectDelivery = fetchedResultsController.objectAtIndexPath(indexPath) as! SubjectDelivery
// Check In/Out Button
var checkedOut = false
var checkedIn = false
var title = "\u{2691}\n Check In"
if let attendance = subjectDelivery.attendance {
checkedOut = attendance.complete.boolValue
if !checkedOut {
checkedIn = true
title = "\u{2690}\n Check Out"
}
}
let attendanceAction = UITableViewRowAction(style: .Default, title: title, handler: { (action, indexPath) -> Void in
self.tableView.setEditing(false, animated: true) // Close the editActions
checkedIn ? (self.attemptingAttendanceCheckType = .Out) : (self.attemptingAttendanceCheckType = .In)
self.attemptAttendanceCheck()
})
// Edit Button
let editAction = UITableViewRowAction(style: .Default, title: "\u{270E}\n Edit", handler: { (action, indexPath) -> Void in
self.tableView.setEditing(false, animated: true) // Close the editActions
self.performSegueWithIdentifier("showEditEvent", sender: indexPath)
})
// Doctor Button
let doctorAction = UITableViewRowAction(style: .Default, title: "\u{2624}\n Doc Cert", handler: { (action, indexPath) -> Void in
self.tableView.setEditing(false, animated: true) // Close the editActions
})
attendanceAction.backgroundColor = checkedIn ? UIColor(red: 230.0/255.0, green: 0, blue: 0, alpha: 1.0) : UIColor(red: 0, green: 230.0/255.0, blue: 0, alpha: 1.0)
editAction.backgroundColor = UIColor(red: 255.0/255.0, green: 166.0/255.0, blue: 2.0/255.0, alpha: 1.0)
doctorAction.backgroundColor = UIColor(red: 28.0/255.0, green: 165.0/255.0, blue: 253.0/255.0, alpha: 1.0)
if checkedOut {
return [doctorAction, editAction]
}
return [doctorAction, editAction, attendanceAction]
}
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Fetched Results Controller
func controllerWillChangeContent(controller: NSFetchedResultsController) {
tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
tableView.reloadData()
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
if let _newIndexPath = newIndexPath {
tableView.insertRowsAtIndexPaths([_newIndexPath], withRowAnimation: .Fade)
}
case .Delete:
if let _indexPath = indexPath {
tableView.deleteRowsAtIndexPaths([_indexPath], withRowAnimation: .Fade)
}
case .Update:
if let _indexPath = indexPath {
tableView.reloadRowsAtIndexPaths([_indexPath], withRowAnimation: .Fade)
}
default:
tableView.reloadData()
}
// Sync our array with the fetchedResultsController
subjectDeliveries = controller.fetchedObjects as! [SubjectDelivery]
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
tableView.endUpdates()
}
// MARK: - Refresh Control
func refresh(sender: AnyObject) {
// TODO: Move below to a seperate method, to be called upon an API response
self.tableView?.reloadData()
refreshControl?.attributedTitle = NSAttributedString(string: "Last updated \(NSDate().format("h:mm:ss a"))")
// tell refresh control it can stop showing up now
if refreshControl!.refreshing
{
refreshControl!.endRefreshing()
}
}
// MARK: - APIService Calls
func attemptAttendanceCheck() {
guard btOn else {
displayAlert("Oops!", message: "Please turn Bluetooth on.")
return
}
guard canRange else {
displayAlert("Oops!", message: "Please authorise location services.")
return
}
attemptedRanges = 0
hasAttemptedAttendanceCheck = false
ActivityIndicator().show()
startRanging()
}
func attendanceCheck(subjectDelivery: SubjectDelivery) {
do {
if !hasAttemptedAttendanceCheck {
if let student = try StudentService.getStudent() {
self.student = student
let apiService = APIService()
apiService.delegate = self
if attemptingAttendanceCheckType == .In {
apiService.postCheckIn(student, subjectDelivery: subjectDelivery)
} else {
apiService.postCheckOut(student, subjectDelivery: subjectDelivery)
}
hasAttemptedAttendanceCheck = true
}
}
} catch let error as NSError {
displayAlert("Oops!", message: error.localizedDescription)
}
}
func getTimetableVersion() {
do {
if let student = try StudentService.getStudent() {
self.student = student
ActivityIndicator().show()
let apiService = APIService()
apiService.delegate = self
apiService.getTimetableVersion(forStudentId: student.studentId)
}
} catch let error as NSError {
displayAlert("Oops!", message: error.localizedDescription)
}
}
// MARK: - APIService Delegate
func apiServiceResponse(responseType: APIServiceResponseType, error: String?, json: JSON?) {
ActivityIndicator().hide()
if let error = error {
displayAlert("Oops!", message: error)
return
}
if let json = json {
switch responseType {
case .POSTCheckIn:
handlePostCheckIn()
case .POSTCheckOut:
handlePostCheckOut()
case .GETTimetableVersion:
handleGetTimetableVersion(json)
default:
print(json.description)
}
}
}
// MARK: - Handle Attendance
func handlePostCheckIn() {
do {
try AttendanceService.checkIn(subjectDelivery)
displayAlert("Thank you", message: "You have checked in.")
} catch let error as NSError {
displayAlert("Oops!", message: error.localizedDescription)
}
}
func handlePostCheckOut() {
do {
try AttendanceService.checkOut(subjectDelivery)
displayAlert("Thank you", message: "You have checked out.")
} catch let error as NSError {
displayAlert("Oops!", message: error.localizedDescription)
}
}
func handleGetTimetableVersion(json: JSON) {
// guard let id = json["CourseDeliveryId"].int else {
// return
// }
//
// guard let version = json["Version"].string else {
// return
// }
//
// TODO: Write a service to handle checking of CourseDeliveryId and Versions
}
// MARK: - Error Alert
func displayAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
}
// MARK: - Bluetooth Manager
func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) {
if peripheral.state == .PoweredOff {
btOn = false
} else if peripheral.state == .PoweredOn {
btOn = true
}
}
// MARK: - Location Manager Delegate
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .NotDetermined:
locationManager.requestWhenInUseAuthorization()
case .AuthorizedWhenInUse, .AuthorizedAlways:
canRange = true
case .Denied, .Restricted:
canRange = false
NSNotificationCenter.defaultCenter().postNotificationName("LOCATION_DENIED", object: nil)
}
}
func startRanging() {
if !isRanging {
locationManager.startRangingBeaconsInRegion(beaconRegion)
isRanging = true
}
}
func stopRanging() {
if isRanging {
locationManager.stopRangingBeaconsInRegion(beaconRegion)
isRanging = false
}
}
func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) {
if isRanging {
attemptedRanges += 1
if beacons.count > 0 {
let closestBeacon = beacons[0]
if closestBeacon != lastFoundBeacon || lastProximity != closestBeacon.proximity {
lastFoundBeacon = closestBeacon
lastProximity = closestBeacon.proximity
switch lastFoundBeacon.proximity {
case .Immediate, .Near, .Far:
print("In Range")
stopRanging()
attendanceCheck(subjectDelivery)
default:
print("Not in Range")
}
}
}
if attemptedRanges > 10 {
print("Giving up")
stopRanging()
ActivityIndicator().hide()
displayAlert("Oops!", message: "Not in range.")
}
}
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print(error)
}
func locationManager(manager: CLLocationManager, monitoringDidFailForRegion region: CLRegion?, withError error: NSError) {
print(error)
}
func locationManager(manager: CLLocationManager, rangingBeaconsDidFailForRegion region: CLBeaconRegion, withError error: NSError) {
print(error)
}
/*
// 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
protocol LoggerSubscriber {
func log(namespace: String, message: String, onQueue: String)
func warn(namespace: String, message: String, onQueue: String)
}
public class Logger {
public static let shared = Logger()
public var didError: ((_: String, _: String) -> ())?
fileprivate let editingQueue = DispatchQueue(label: "LoggerSubscriberEditQueue")
fileprivate let notificationQueue = DispatchQueue(label: "LoggerNotificationQueue")
private var subscribers: [LoggerSubscriber] = []
func addSubscriber(_ subscriber: LoggerSubscriber) {
self.editingQueue.async {
self.subscribers.append(subscriber)
}
}
func log(namespace: String, message: String) {
let queueName = currentQueueName()
if logignores.contains(namespace) == false {
let logMessage = String(format:"%@: %@ (%@)", namespace, message, queueName)
print(logMessage)
// DebugLogView.shared?.log(logMessage)
}
self.notificationQueue.async {
self.subscribers.forEach({ (eachSubscriber) in
eachSubscriber.log(namespace: namespace, message: message, onQueue: queueName)
})
}
}
func warn(_ namespace: String, _ message: String) {
let queueName = currentQueueName()
let logMessage = String(format:"%@: %@ (%@)", namespace, message, queueName)
print(logMessage)
// DebugLogView.shared?.log(logMessage)
self.notificationQueue.async {
self.subscribers.forEach({ (eachSubscriber) in
eachSubscriber.warn(namespace: namespace, message: message, onQueue: queueName)
})
}
}
}
let logignores: [String] = [
"Harold",
"BrainManager",
"Capture",
// "Lighthouse",
//
// "BrainManagerVerbose",
// "BrainManager Accessory",
//
// "SlideshowSlide",
// "SlideshowTransitionCoordinator",
// "SlideshowViewController",
// "ScreenWatcher",
// "SlideshowController",
// "SessionServer",
// "SessionBroadcast",
"ShareWrangler",
// "ImageUtil",
"FileUtil",
"PhotoWatcher",
"Harold",
// "GalleryVC",
// "ImageView",
// "Main menu",
// "MainMenuVerbose",
// "CameraCell",
// "CameraManager",
// "CameraManagerVerbose",
// "CameraManagerHacks",
// "OverlayManager",
// "ItemViewerVC",
// "VideoProcessor",
// "ConfigVC",
// "ItemViewController",
// "ShareButtonsVC",
//
// "ShareLog",
// "ShareMessageManager",
// "ShareSettingsManager",
// "SimpleShareVC",
//
// "CaptureVC",
// "AssetSourceManager",
// "PrinterManager",
// "CountdownView",
// "App Delegate",
// "AtLeastSquareView",
// "LoadingBarView",
//
// "EmailMessageServiceManager",
// "TextMessageServiceManager",
//
// "LiveCamera",
//
// "CloudinaryData",
// "AnimatedImageView",
// "CastManager",
// "AssetMap",
// "DropboxExporter",
// "JSONPersistable",
"JSONPersistence",
"Purchases",
"FileUtil",
"ImageUtil",
// "ShareJob",
// "ShareJobUpload",
//
// "AssetManager",
// "AssetFetcher",
// "AssetFetcher Images",
// "AppAssetLoader",
//
// "AppAssetLoader",
//
// "WebVideoView",
//
// "AppScanner"
]
public func derror(_ namespace: String, _ message: String) {
Logger.shared.warn(namespace, message)
Logger.shared.didError?(namespace, message)
}
public func dwarn(_ namespace: String, _ message: String) {
#if DEBUG
Logger.shared.warn(namespace, message)
#endif
}
public func dl(_ namespace: String, _ message: String) {
#if DEBUG
Logger.shared.log(namespace: namespace, message: message)
#endif
}
var DebugRefTime = Date()
public func debugTime(_ message: String, resetting: Bool = false) {
#if DEBUG
if resetting {
DebugRefTime = Date()
}
let timestamp = DebugRefTime.timeIntervalSinceNow * -1.0
Logger.shared.log(namespace: "Timing", message: "\(timestamp): \(message)")
#endif
}
public func dropboxError(_ error: Any?) {
dwarn("Dropbox", error.debugDescription)
}
func currentQueueName() -> String {
let name = __dispatch_queue_get_label(nil)
return String(cString: name, encoding: .utf8) ?? "nil"
}
|
//
// EmuView.swift
// RockEmu
//
// Created by Rocky Pulley on 8/29/19.
// Copyright © 2019 Rocky Pulley. All rights reserved.
//
import Cocoa
import IOKit
import IOKit.usb
import IOKit.hid
class EmuView: NSView {
@IBOutlet weak var imgView: NSImageView!
public struct PixelData {
var a:UInt8 = 255
var r:UInt8
var g:UInt8
var b:UInt8
}
private let rgbColorSpace = CGColorSpaceCreateDeviceRGB()
private let bitmapInfo:CGBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue)
public static var drawing = false
var times = 0;
var ppuData : UnsafeMutablePointer<PpuData>
var pixelData = [PixelData](repeating: PixelData(a:0,r:0,g:0,b:0), count: 240 * 256);
var imageData = [[Int?]](
repeating: [Int?](repeating: nil, count: 256),
count: 240
)
required init?(coder decoder: NSCoder) {
ppuData = ppu_data_pointer();
super.init(coder: decoder)
for y in 0..<240 {
for x in 0..<256 {
imageData[y][x] = 0xffffffff
}
}
}
override var acceptsFirstResponder: Bool {
return true
}
func drawPatterns() {
var line = 0
var offset = 0
for two in 0..<16 {
for one in 0..<16 {
for y in 0..<8 {
for x in 0..<8 {
var n = ppu_get_pattern(UInt16(one + (two * 16)), UInt8(x), UInt8(y))
if (n == 0) {
imageData[line + (8 * two)][x + offset] = 0
//bytes[x + (offset) + ((240 * 255) - ((240 * line) + (240 * 8 * two)))] = 0xff000fff
} else if (n == 1) {
imageData[line + (8 * two)][x + offset] = 0x00ff00ff
//bytes[x + (offset) + ((240 * 255) - ((240 * line) + (240 * 8 * two)))] = 0xffffffff
} else if (n == 2) {
imageData[line + (8 * two)][x + offset] = 0x0000ffff
//bytes[x + (offset) + ((240 * 255) - ((240 * line) + (240 * 8 * two)))] = 0xcccccccc
} else {
imageData[line + (8 * two)][x + offset] = 0xff0000ff
//bytes[x + (offset) + ((240 * 255) - ((240 * line) + (240 * 8 * two)))] = 0xffff0000
//return;
}
}
line = line + 1
}
offset += 8
line = 0
}
offset = 0
//line = two
}
}
public func imageFromARGB32Bitmap(pixels:[PixelData], width:Int, height:Int)->NSImage {
let bitsPerComponent:Int = 8
let bitsPerPixel:Int = 32
assert(pixels.count == Int(width * height))
var data = pixels // Copy to mutable []
let providerRef = CGDataProvider(
data: NSData(bytes: &data, length: data.count * MemoryLayout.size(ofValue: pixels[0]))
)
let cgim = CGImage(
width: width,
height: height,
bitsPerComponent: bitsPerComponent,
bitsPerPixel: bitsPerPixel,
bytesPerRow: width * Int(MemoryLayout.size(ofValue: pixels[0])),
space: rgbColorSpace,
bitmapInfo: bitmapInfo,
provider: providerRef!,
decode: nil,
shouldInterpolate: true,
intent: .defaultIntent
)
return NSImage(cgImage: cgim!, size: NSZeroSize)
}
var lastFrame : UInt32 = 0;
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if (!EmuView.drawing) {
return;
}
if (ppuData.pointee.curFrame == lastFrame) {
return;
}
var pb = ppu_data().pictureBuffer;
lastFrame = ppuData.pointee.curFrame
//print("Drawing Frame: ", lastFrame)
var i = 0;
for yyy in 0..<240 {
var ypos = (yyy * 256);
for xxx in 0..<256 {
//print("y,x = ", yyy, ",", xxx)
var bt = pb![xxx]
var n = Int(bt![yyy]);
//imageData[yyy][xxx] = n
var p = PixelData(a:255, r: UInt8((n & 0xFF000000) >> 24), g: UInt8((n & 0x00FF0000) >> 16), b: UInt8((n & 0x0000FF00) >> 8))
pixelData[ypos + xxx] = p;
}
}
/*
let image = NSImage(size: NSSize(width: 240, height: 256))
image.lockFocus()
for y in 0..<240 {
for x in 0..<256 {
let n = imageData[y][x]
let scaledY = 255 - y
let c = NSColor(red: CGFloat(((n! & 0xFF000000) >> 24)) / 255.0, green: CGFloat((n! & 0x00FF0000) >> 16) / 255.0, blue: CGFloat((n! & 0x0000FF00) >> 8) / 255.0, alpha: 1.0)
c.drawSwatch(in: NSRect(x: x, y: scaledY, width: 1, height: 1))
}
}
image.unlockFocus()
*/
let image = imageFromARGB32Bitmap(pixels: pixelData, width: 256, height: 240)
imgView.image = image
}
/*
KEY CODE: 13
KEY CODE: 1
KEY CODE: 0
KEY CODE: 2
KEY CODE: 47
KEY CODE: 44
KEY CODE: 39
KEY CODE: 36
*/
var keyUp = false;
var keyDown = false;
var keyLeft = false;
var keyRight = false;
var keyA = false;
var keyB = false;
var keySel = false;
var keyStart = false;
override func keyUp(with event: NSEvent) {
var kc = event.keyCode
if (kc == 36) {
controller_set(0, UInt8(BUTTON_ST), 0);
keyStart = false;
} else if (kc == 13) {
controller_set(0, UInt8(BUTTON_U), 0);
keyUp = false;
} else if (kc == 1) {
controller_set(0, UInt8(BUTTON_D), 0);
keyDown = false;
} else if (kc == 0) {
controller_set(0, UInt8(BUTTON_L), 0);
keyLeft = false;
} else if (kc == 2) {
controller_set(0, UInt8(BUTTON_R), 0);
keyRight = false;
} else if (kc == 47) {
controller_set(0, UInt8(BUTTON_B), 0);
keyB = false;
} else if (kc == 44) {
controller_set(0, UInt8(BUTTON_A), 0);
keyA = false;
} else if (kc == 39) {
controller_set(0, UInt8(BUTTON_SE), 0);
keySel = false;
}
}
override func keyDown(with event: NSEvent) {
var kc = event.keyCode
//print("KEY CODE: ", kc);
if (!keyStart && kc == 36) {
controller_set(0, UInt8(BUTTON_ST), 1);
keyStart = true
} else if (!keyUp && kc == 13) {
controller_set(0, UInt8(BUTTON_U), 1);
keyUp = true
} else if (!keyDown && kc == 1) {
controller_set(0, UInt8(BUTTON_D), 1);
keyDown = true
} else if (!keyLeft && kc == 0) {
controller_set(0, UInt8(BUTTON_L), 1);
keyLeft = true
} else if (!keyRight && kc == 2) {
controller_set(0, UInt8(BUTTON_R), 1);
keyRight = true
} else if (!keyB && kc == 47) {
controller_set(0, UInt8(BUTTON_B), 1);
keyB = true
} else if (!keyA && kc == 44) {
controller_set(0, UInt8(BUTTON_A), 1);
keyA = true
} else if (!keySel && kc == 39) {
controller_set(0, UInt8(BUTTON_SE), 1);
keySel = true
//ppu_dump_ram();
}
}
}
|
//
// FirebaseValues.swift
// Loodos_Project
//
// Created by Ünal Öztürk on 4.02.2019.
// Copyright © 2019 Ünal Öztürk. All rights reserved.
//
import Firebase
enum ValueKey : String {
case appLabelText
}
class FirebaseValues {
static let sharedInstance = FirebaseValues()
var loadingDoneCallback: (() -> Void)?
var fetchComplete = false
private init() {
loadDefaultValues()
fetchCloudValues()
}
func loadDefaultValues() {
let appDefaults: [String: Any?] = [
ValueKey.appLabelText.rawValue : "Loodos"
]
RemoteConfig.remoteConfig().setDefaults(appDefaults as? [String: NSObject])
}
func fetchCloudValues() {
let fetchDuration: TimeInterval = 0
activateDebugMode()
RemoteConfig.remoteConfig().fetch(withExpirationDuration: fetchDuration) {
[weak self] (status, error) in
if let error = error {
print ("Got an error fetching remote values \(error)")
return
}
RemoteConfig.remoteConfig().activateFetched()
print ("Retrieved values from the cloud!")
self?.fetchComplete = true
self?.loadingDoneCallback?()
}
}
func activateDebugMode() {
let debugSettings = RemoteConfigSettings(developerModeEnabled: true)
RemoteConfig.remoteConfig().configSettings = debugSettings
}
func string(forKey key: ValueKey) -> String {
return RemoteConfig.remoteConfig()[key.rawValue].stringValue ?? ""
}
}
|
//
// StockDetailPairedLabelView.swift
// StockQuote
//
// Created by Ernest Fan on 2019-11-15.
// Copyright © 2019 ErnestFan. All rights reserved.
//
import UIKit
class StockDetailPairedLabelView: UIView {
let titleString : String!
let valueString : String!
// MARK: - Init
init(with titleString: String, and valueString: String) {
self.titleString = titleString
self.valueString = valueString
super.init(frame: CGRect.zero)
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - UI Setup
private func setupView() {
backgroundColor = .white
addSubview(titleLabel)
titleLabel.anchor(top: safeAreaLayoutGuide.topAnchor, leading: safeAreaLayoutGuide.leadingAnchor, bottom: safeAreaLayoutGuide.bottomAnchor, trailing: centerXAnchor, padding: .init(top: 0, left: 0, bottom: 0, right: 4))
addSubview(valueLabel)
valueLabel.anchor(top: safeAreaLayoutGuide.topAnchor, leading: centerXAnchor, bottom: safeAreaLayoutGuide.bottomAnchor, trailing: safeAreaLayoutGuide.trailingAnchor, padding: .init(top: 0, left: 4, bottom: 0, right: 0))
}
// MARK: - UI Properties
lazy var titleLabel : UILabel = {
let label = UILabel()
label.font = UIFont(name: "HelveticaNeue-Medium", size: 20)
label.textColor = .darkGray
label.textAlignment = .right
label.text = titleString
return label
}()
lazy var valueLabel: UILabel = {
let label = UILabel()
label.font = UIFont(name: "HelveticaNeue-Light", size: 20)
label.textColor = .darkGray
label.textAlignment = .left
label.text = valueString
return label
}()
}
|
//
// PaddingTextField.swift
// Cardify
//
// Created by Vu Tiep on 2/18/15.
// Copyright (c) 2015 Tiep Vu Van. All rights reserved.
//
import UIKit
class PaddingTextField: UITextField {
var paddingInsets = UIEdgeInsetsMake(0, 0, 0, 0)
override func textRectForBounds(bounds: CGRect) -> CGRect {
return rectForBounds(bounds)
}
override func placeholderRectForBounds(bounds: CGRect) -> CGRect {
return rectForBounds(bounds)
}
override func editingRectForBounds(bounds: CGRect) -> CGRect {
return rectForBounds(bounds)
}
private func rectForBounds(bounds: CGRect) -> CGRect {
return CGRectMake(paddingInsets.left, paddingInsets.top, bounds.width - (paddingInsets.right + paddingInsets.left), bounds.height - (paddingInsets.top + paddingInsets.bottom))
}
}
|
//
// LastSearchCollectionViewCell.swift
// iTunes Music Video Player
//
// Created by Gabriel on 26/05/2021.
//
import Foundation
import UIKit
class LastSearchCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var titleLabel: UILabel!
func setTitle(_ title: String) {
titleLabel.text = title
}
}
|
//
// AppDelegate.swift
// Mac Simple Bike Computer
//
// Created by Falko Richter on 16/10/14.
// Copyright (c) 2014 Falko Richter. All rights reserved.
//
import Cocoa
import CoreBluetooth
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, CadenceDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var totalDistanceTextField: NSTextField!
@IBOutlet weak var speedTextField: NSTextField!
@IBOutlet weak var crankRevolutionsTextField: NSTextField!
var heartBeatPeripheral: HeartRatePeripheral?
var peripheralManager:CBPeripheralManager!
override init() {
println("init")
super.init()
}
var cadenceConnector = CadenceConnector()
func applicationDidFinishLaunching(aNotification: NSNotification?) {
cadenceConnector.delegate = self
}
func distanceDidChange(cadence: CadenceConnector!, totalDistance : Double! ){
dispatch_async(dispatch_get_main_queue(), {
self.totalDistanceTextField.doubleValue = totalDistance
});
}
func speedDidChange(cadence: CadenceConnector!, speed: Double!) {
dispatch_async(dispatch_get_main_queue(), {
self.speedTextField.doubleValue = speed
});
}
func crankFrequencyDidChange(cadence: CadenceConnector!, crankRevolutionsPerMinute : Double! ){
dispatch_async(dispatch_get_main_queue(), {
self.crankRevolutionsTextField.doubleValue = crankRevolutionsPerMinute
});
}
func applicationWillTerminate(aNotification: NSNotification?) {
heartBeatPeripheral!.stopBroadcasting()
}
func applicationShouldTerminateAfterLastWindowClosed(theApplication: NSApplication!) -> Bool{
return true;
}
@IBAction func becomeHeartRateSensor(AnyObject){
heartBeatPeripheral = HeartRatePeripheral()
heartBeatPeripheral!.startBroadcasting();
}
}
|
//
// RepoScrollVC.swift
// GitGraphQL
//
// Created by Elex Lee on 4/9/19.
// Copyright © 2019 Elex Lee. All rights reserved.
//
import Apollo
import UIKit
class RepoScrollVC: UIViewController {
var indicatorView: UIActivityIndicatorView!
var tableView: UITableView!
var viewModel: RepoScrollViewModel!
var cellId = "RepoCell"
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
func setup() {
viewModel = RepoScrollViewModel(delegate: self)
self.view.backgroundColor = .black
self.title = "Repositories"
setupTableView()
setupIndicatorView()
viewModel.fetchRepos()
}
func setupTableView() {
tableView = UITableView(frame: CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: self.view.frame.height))
tableView.backgroundColor = .clear
tableView.isHidden = true
tableView.dataSource = self
tableView.delegate = self
tableView.register(UINib(nibName: "RepoScrollCell", bundle: nil), forCellReuseIdentifier: cellId)
self.view.addSubview(tableView)
}
func setupIndicatorView() {
indicatorView = UIActivityIndicatorView(style: .whiteLarge)
indicatorView.startAnimating()
indicatorView.center = self.view.center
self.view.addSubview(indicatorView)
}
}
extension RepoScrollVC: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.currentCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! RepoScrollCell
let repo = viewModel.repo(at: indexPath.row)
cell.setup(repo: repo)
cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 125.0
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == viewModel.currentCount - 10 {
viewModel.fetchRepos()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! RepoScrollCell
print("IndexPath: \(indexPath) \n\(viewModel.repo(at: indexPath.row))")
cell.bounce()
}
}
extension RepoScrollVC: RepoScrollViewModelDelegate {
func repoFetchCompleted() {
if !viewModel.didFinishInitialFetch {
viewModel.finishInitialFetch()
indicatorView.stopAnimating()
tableView.isHidden = false
tableView.reloadData()
return
}
tableView.reloadData()
}
func repoFetchFailed(with reason: String) {
indicatorView.stopAnimating()
let alert = UIAlertController(title: "Warning", message: reason, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}
|
//
// GroupedExercise.swift
// BalancedGym
//
// Created by Pablou on 12/1/17.
// Copyright © 2017 Pablou. All rights reserved.
//
import Foundation
import ObjectMapper
class GroupedExercise : Mappable {
var muscleGroup: String
var targets: [Targets] = []
var lastUpdated: Date?
var doneToday: Int = 0
required init?(map: Map){
self.muscleGroup = ""
}
func mapping(map: Map) {
muscleGroup <- map["muscleGroup"]
targets <- map["targets"]
doneToday <- map["doneToday"]
lastUpdated <- (map["lastUpdated"], BDateTransform())
}
}
|
//
// Coordinator.swift
// TinderCat
//
// Created by Yesid Hernandez on 5/12/19.
// Copyright © 2019 Yesid Hernandez. All rights reserved.
//
import Foundation
import UIKit
public protocol Coordinator: class{
var childCoordinators: [Coordinator]{get set}
init(navigationController: UINavigationController)
func start()
}
|
//
// AlbumViewController.swift
// ComponentTest
//
// Created by zou jingbo on 2021/10/22.
//
import UIKit
import SnapKit
import Photos
class AlbumViewController: UIViewController {
var navBar:NavBar!
var navigationBar:UIView!
var dropDownListView:UIView!
var dropDownSafeView:UIView!
var tableView:UITableView!
var tableCellId:String = "TableViewCellId"
var collectionView:UICollectionView!
var collectionLayout:UICollectionViewFlowLayout!
var collectionCellId:String = "CollectionCellId"
var oldOrientation:UIDeviceOrientation = .unknown
var isChoosing: Bool = false{
didSet{
if isChoosing != oldValue{
collectionView.reloadData()
}
}
}
var chosenItems:Set<Int> = []
var collections:[PHAssetCollection]!
var assets:[PHAsset]?{
didSet{
collectionView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
installUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
updateUI()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension AlbumViewController: NavBarDelegate{
func openDropDownList() {
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: {[self] in
dropDownListView.transform = CGAffineTransform(translationX: 0, y: -(height - 44 - self.view.safeAreaInsets.top))
}, completion: nil)
}
func closeDropDownList() {
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: {[self] in
dropDownListView.transform = CGAffineTransform.identity
}, completion: nil)
}
}
extension AlbumViewController: UITableViewDelegate, UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return collections.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: tableCellId)
if cell == nil{
cell = UITableViewCell(style: .value1, reuseIdentifier: tableCellId)
}
cell?.backgroundColor = UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1)
cell!.contentView.backgroundColor = UIColor.clear
//设置选中时的背景颜色
let backView = UIView(frame: CGRect(x: 0, y: 0, width: cell!.frame.width, height: cell!.frame.height))
backView.backgroundColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)
cell?.selectedBackgroundView = backView
cell!.textLabel?.textAlignment = .left
cell!.textLabel?.textColor = UIColor.white
cell!.textLabel?.font = UIFont.systemFont(ofSize: 16, weight: .regular)
cell!.detailTextLabel?.textAlignment = .right
cell!.detailTextLabel?.textColor = UIColor.white
cell!.detailTextLabel?.font = UIFont.systemFont(ofSize: 14, weight: .regular)
let collection = collections[indexPath.row]
cell!.textLabel?.text = collection.localizedTitle
cell!.detailTextLabel?.text = "\(PhotoUtils.shared.getAssetNumberOfCollection(albumName: collection.localizedTitle!))"
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
//根据相册名字获取相册中的所有图片的缩略图
let collection = collections[indexPath.row]
assets = PhotoUtils.shared.getAssetOfCollection(collection: collection, asceding: true)
self.navBar.isOpen = false
}
}
extension AlbumViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return assets?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let num: CGFloat = floor((self.view.frame.width + 3) / (cellLength + 3))
let right: CGFloat = self.view.frame.width - num * (cellLength + 3) + 3
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: right)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionCellId, for: indexPath) as! GSCollectionViewCell
cell.contentMode = .scaleAspectFill
cell.clipsToBounds = true
cell.tag = indexPath.row
cell.delegate = self
cell.isChoosing = self.isChoosing
if let assets = assets{
let asset = assets[indexPath.row]
cell.image = PhotoUtils.shared.getThumbnail(asset: asset, targetSize: CGSize(width: cellLength, height: cellLength))
if chosenItems.contains(indexPath.row){
cell.isChosen = true
}else{
cell.isChosen = false
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if chosenItems.contains(indexPath.row){
chosenItems.remove(indexPath.row)
}else{
chosenItems.insert(indexPath.row)
}
collectionView.reloadItems(at: [indexPath])
}
}
extension AlbumViewController: GSCollectionViewCellDelegate{
func beginLongPress(_ sender: UILongPressGestureRecognizer) {
}
func endLongPress(_ sender: UILongPressGestureRecognizer) {
let cell = sender.view
self.isChoosing = true
if let cell = cell{
chosenItems.insert(cell.tag)
}
}
}
extension AlbumViewController{
private func updateUI(){
navBar.snp.updateConstraints { make in
make.top.equalTo(self.view.safeAreaInsets.top)
make.left.equalTo(0)
make.width.equalToSuperview()
make.height.equalTo(44)
make.bottom.equalTo(0)
}
dropDownListView.snp.updateConstraints { make in
make.top.equalTo(height)
make.left.equalTo(0)
make.width.equalToSuperview()
make.height.equalTo(height - 44 - self.view.safeAreaInsets.top)
}
collectionView.snp.updateConstraints { make in
make.top.equalTo(navigationBar.snp.bottom)
make.left.equalTo(0)
make.width.equalToSuperview()
make.bottom.equalTo(-self.view.safeAreaInsets.bottom)
}
tableView.snp.updateConstraints { make in
make.top.equalTo(0)
make.left.equalTo(0)
make.width.equalToSuperview()
make.bottom.equalTo(-self.view.safeAreaInsets.bottom)
}
}
private func installUI(){
self.view.backgroundColor = UIColor.white
navigationBar = UIView()
navigationBar.backgroundColor = UIColor.white
self.view.addSubview(navigationBar)
navigationBar.snp.makeConstraints { make in
make.top.left.equalTo(0)
make.width.equalToSuperview()
}
navBar = NavBar()
navBar.heading = "Photo Library"
navBar.delegate = self
navigationBar.addSubview(navBar)
navBar.snp.makeConstraints { make in
make.top.equalTo(self.view.safeAreaInsets.top)
make.left.equalTo(0)
make.width.equalToSuperview()
make.height.equalTo(44)
make.bottom.equalTo(0)
}
collectionLayout = UICollectionViewFlowLayout()
collectionLayout.scrollDirection = .vertical
collectionLayout.itemSize = CGSize(width: cellLength, height: cellLength)
collectionLayout.minimumLineSpacing = 3
collectionLayout.minimumInteritemSpacing = 3
collectionView = UICollectionView(frame: CGRect(x: 0, y: 44 + self.view.safeAreaInsets.top, width: width, height: height - (44 + self.view.safeAreaInsets.top)), collectionViewLayout: collectionLayout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = UIColor(red: 0.97, green: 0.97, blue: 0.97, alpha: 1)
collectionView.register(GSCollectionViewCell.self, forCellWithReuseIdentifier: collectionCellId)
self.view.addSubview(collectionView)
collectionView.snp.makeConstraints { make in
make.top.equalTo(navigationBar.snp.bottom)
make.left.equalTo(0)
make.width.equalToSuperview()
make.bottom.equalTo(-self.view.safeAreaInsets.bottom)
}
dropDownListView = UIView()
dropDownListView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4)
self.view.addSubview(dropDownListView)
dropDownListView.snp.makeConstraints { make in
make.top.equalTo(height)
make.left.equalTo(0)
make.width.equalToSuperview()
make.height.equalTo(height - 44 - self.view.safeAreaInsets.top)
}
dropDownSafeView = UIView()
dropDownSafeView.backgroundColor = UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1)
dropDownListView.addSubview(dropDownSafeView)
dropDownSafeView.snp.makeConstraints { make in
make.top.equalTo(0)
make.left.equalTo(0)
make.width.equalToSuperview()
make.bottom.equalTo(0)
}
tableView = UITableView()
tableView.backgroundColor = UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1)
tableView.dataSource = self
tableView.delegate = self
dropDownListView.addSubview(tableView)
tableView.snp.makeConstraints { make in
make.top.equalTo(0)
make.left.equalTo(0)
make.width.equalToSuperview()
make.bottom.equalTo(-self.view.safeAreaInsets.bottom)
}
//获取系统相册
collections = PhotoUtils.shared.getAllAlbums()
//监听横竖屏切换
NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged), name: UIDevice.orientationDidChangeNotification, object: nil)
}
@objc private func orientationChanged(_ sender: Notification){
let orientation = UIDevice.current.orientation
if oldOrientation != orientation{
switch orientation {
case .portrait, .landscapeLeft, .landscapeRight:
collectionView.reloadData()
oldOrientation = orientation
default:
break
}
}
}
}
|
//
// SignupView.swift
// Todolist
//
// Created by Dinh Quoc Thuy on 5/24/20.
// Copyright © 2020 Dinh Quoc Thuy. All rights reserved.
//
import SwiftUI
struct SignupView: View {
@State var height:CGFloat = 0
var body: some View {
NavigationView {
ScrollView(UIScreen.main.bounds.height < 750 ? .vertical : (self.height == 0 ? .init() : .vertical) , showsIndicators: false) {
Text("Sign up")
}
}
}
}
struct SignupView_Previews: PreviewProvider {
static var previews: some View {
SignupView()
}
}
|
//
//
// SecureKeys.swift
//
// Created by Mark Evans on 2/22/17.
// Copyright © 2017 3Advance, LLC. All rights reserved.
//
import Foundation
@objc public class SecureKeys: NSObject {
public var FirebaseSenderID = ""
public var FirebaseApiEndpoint = ""
public var FirebaseAcessToken = ""
public static let shared: SecureKeys = {
let instance = SecureKeys()
return instance
}()
}
|
//
// LocalizationManager.swift
// SwiftTraningProject
//
// Created by 吉祥具 on 2017/5/20.
// Copyright © 2017年 吉祥具. All rights reserved.
//
import Foundation
class LocalizationManager : NSObject {
private static var mInstance : LocalizationManager?
var bundle : Bundle?
//TODO: Singleton create
static func shareInstance() -> LocalizationManager{
if (mInstance == nil) {
mInstance=LocalizationManager()
//設定語系
if Locale.preferredLanguages[0].contains("en") {
mInstance?.setLanguage(language: "en") //設定default語系
}else{
mInstance?.setLanguage(language: nil) //設定default語系
}
}
return mInstance!
}
//TODO:設定語系
func setLanguage(language:String?){
var pathGet : String?
if(language == nil){
pathGet = Bundle.main.path(forResource: "Base", ofType: "lproj")
}else{
pathGet = Bundle.main.path(forResource: language, ofType: "lproj")
if(pathGet == nil){
pathGet = Bundle.main.path(forResource: "Base", ofType: "lproj")
}
}
bundle = Bundle.init(path: pathGet!)
}
//TODO: 取得多語系字串
//如果是可能填入nil的參數 則要在參數種類後面加上問號 使其成為optional
func getString(key:String , tableSet:String?) -> String{
if(tableSet == nil){//如果沒有指定哪一個語系檔
//table的參數 可指定要去抓哪一個多語系檔案
return bundle!.localizedString(forKey: key, value: "default value", table: "LocalizedString")
}else{
return bundle!.localizedString(forKey: key, value: "default value", table: tableSet)
}
}
}
|
//
// LocalizedItemCollator.swift
// ListableUI
//
// Created by Kyle Van Essen on 12/7/20.
//
import UIKit
///
/// If you would like to make your `ItemContent` work with the `LocalizedItemCollator`,
/// you should make it conform to this protocol, and then return a `collationString` that
/// represents the primary content of your `ItemContent`; usually a name or title.
///
/// Upon collation, the `ItemContent` will then be grouped into sections according to its
/// first "character" in a localized manner.
/// ```
/// struct MyContent : ItemContent, LocalizedCollatableItemContent {
///
/// var title : String
///
/// var collationString : String {
/// self.title
/// }
/// }
/// ```
public protocol LocalizedCollatableItemContent : ItemContent {
/// A string that represents the primary content of your `ItemContent`; usually a name or title.
var collationString : String { get }
}
///
/// Represents an `AnyItem` which can be collated, via its vended `collationString`.
///
/// `Item` (and by extension `AnyItem`) is conditionally conformed to this protocol
/// when its `Content` conforms to `LocalizedCollatableItemContent`,
/// to allow vending homogenous lists of content to be collated.
///
public protocol AnyLocalizedCollatableItem : AnyItem {
var collationString : String { get }
}
///
/// If you're looking for the equivalent of `UILocalizedIndexedCollation` for lists,
/// you have come to the right place.
///
/// `LocalizedItemCollator` takes in a list of unsorted content, and sorts and then
/// partitions the content into sections, returning you a list of collated sections for display.
///
/// Just like `UILocalizedIndexedCollation`, `LocalizedItemCollator` takes
/// into account the localization settings of the device, using different collation for the various
/// supported iOS languages.
///
/// Example
/// -------
/// ```
/// List { list in
/// list += LocalizedItemCollator.sections(with: items) { collated, section in
///
/// /// You are passed a pre-populated section on which you may
/// /// customize the header and footer, or mutate the content.
///
/// section.header = HeaderFooter(DemoHeader(title: collated.title))
/// section.footer = HeaderFooter(DemoFooter(title: collated.title))
/// }
/// }
///
/// ```
/// Warning
/// -------
/// Sorting and partitioning thousands and thousands of `Items` each
/// time a list updates can be expensive, especially on slower devices.
///
/// If you have a list that you wish to collate that may contain thousands of items,
/// it is recommended that you store the list pre-collated outside of Listable,
/// so each recreation of the list's view model does not re-partake in an expensive sort operation.
/// Instead only re-collate when the underlying list receives an update (from Core Data, an API callback, etc).
///
public struct LocalizedItemCollator {
//
// MARK: Public
//
/// Collates and returns the set of items into `CollatedSection`s.
/// You may then convert these into list `Section`s, or for another use.
public static func collate(
collation : UILocalizedIndexedCollation = .current(),
items : [AnyLocalizedCollatableItem]
) -> [CollatedSection]
{
Self.init(
collation: collation,
items: items
).collated
}
/// Collates and returns the set of items into list `Sections`,
/// allowing you to customize each `Section` via the provided `modify`
/// closure.
///
/// ```
/// List { list in
/// list += LocalizedItemCollator.sections(with: items) { collated, section in
/// section.header = HeaderFooter(DemoHeader(title: collated.title))
/// section.footer = HeaderFooter(DemoFooter(title: collated.title))
/// }
/// }
///
/// ```
public static func sections(
collation : UILocalizedIndexedCollation = .current(),
with items : [AnyLocalizedCollatableItem],
_ modify : (CollatedSection, inout Section) -> () = { _, _ in }
) -> [Section]
{
let collated = Self.collate(collation: collation, items: items)
return collated.map { collated in
var section = Section(collated.title, items: collated.items)
modify(collated, §ion)
return section
}
}
//
// MARK: Internal
//
let collated : [CollatedSection]
init(
collation : UILocalizedIndexedCollation = .current(),
items : [AnyLocalizedCollatableItem]
) {
/// 1) Convert to providers so we can leverage `collationStringSelector`, which is Objective-C only.
let providers = items.map {
Provider(item: $0)
}
/// 2) Convert the titles from the collation into sections.
var collated = collation.sectionTitles.map { title in
CollatedSection(title: title)
}
/// 3) Sort all of the provided content based on the `collationString`.
let sorted = collation.sortedArray(from: providers, collationStringSelector: #selector(getter: Provider.collationString))
/// 4) Insert the sorted content into the correct section's items.
for provider in sorted {
let provider = provider as! Provider
let sectionIndex = collation.section(for: provider, collationStringSelector: #selector(getter: Provider.collationString))
collated[sectionIndex].items.append(provider.item)
}
/// 5) Only provide collated items that have content.
self.collated = collated.filter { $0.items.isEmpty == false }
}
/// A private wrapper that is used to ensure we have an Objective-C selector to vend to `collationStringSelector`.
private final class Provider {
/// The item backing the provider, to vend the `collationString`.
let item : AnyLocalizedCollatableItem
/// The string used to collate all items.
@objc let collationString : String
init(item: AnyLocalizedCollatableItem) {
self.item = item
self.collationString = self.item.collationString
}
}
}
extension LocalizedItemCollator {
/// The output of the collator, with the collated title and items
/// that should be added to a given section.
public struct CollatedSection {
/// The title of section – a single letter like A, B, C, D, E, etc.
/// Localized depending on locale.
/// See https://nshipster.com/uilocalizedindexedcollation/ for more examples.
public var title : String
/// The sorted items in the collated sections.
public var items : [AnyItem] = []
}
}
/// Ensures that `Item` (and by extension, `AnyItem`) will conform to `LocalizedCollatableItem`
/// when its `content` conforms to `LocalizedCollatableItemContent`.
extension Item : AnyLocalizedCollatableItem where Content : LocalizedCollatableItemContent {
public var collationString: String {
self.content.collationString
}
}
|
//
// ShareViewController.swift
// LaarcIOSShareExtension
//
// Created by Emily Kolar on 1/17/19.
// Copyright © 2019 Emily Kolar. All rights reserved.
//
import UIKit
import Social
import MobileCoreServices
let LAARC_GREEN = UIColor(red: 154/255, green: 186/255, blue: 170/255, alpha: 1.0)
class ShareViewController: SLComposeServiceViewController {
private var _url = ""
private var _postTags = "private"
private var _postComment = ""
private var _postTitle = ""
private let _appContainer = "group.com.emilykolar.Laarc"
private let _configName = "com.emilykolar.Laarc.BackgroundSessionConfig"
private let _baseUrl = "https://laarc.io"
override func viewDidLoad() {
super.viewDidLoad()
getUrl()
styleUi()
}
func getUrl() {
if let extensionItem = extensionContext?.inputItems.first as? NSExtensionItem,
let itemProvider = extensionItem.attachments?.first {
let propertyList = String(kUTTypePropertyList)
if itemProvider.hasItemConformingToTypeIdentifier(propertyList) {
itemProvider.loadItem(forTypeIdentifier: propertyList, options: nil) { item, error in
guard let dictionary = item as? NSDictionary else { return }
OperationQueue.main.addOperation {
if let results = dictionary[NSExtensionJavaScriptPreprocessingResultsKey] as? NSDictionary,
let titleString = results["String"] as? String,
let urlString = results["URL"] as? String {
self._url = urlString
self._postTitle = titleString
print(results.debugDescription)
}
}
}
}
} else {
print("some error happened")
}
}
func styleUi() {
navigationController?.navigationBar.tintColor = .white
navigationController?.navigationBar.backgroundColor = LAARC_GREEN
}
override func isContentValid() -> Bool {
// Do validation of contentText and/or NSExtensionContext attachments here
return true
}
func makeRequest(url: URL) -> URLRequest? {
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpMethod = "POST"
let json = NSMutableDictionary()
json["title"] = contentText
json["url"] = _url
json["tags"] = _postTags
do {
let jsonData = try JSONSerialization.data(withJSONObject: json, options: [])
request.httpBody = jsonData
return request
} catch let err {
print(err.localizedDescription)
}
return nil
}
override func didSelectPost() {
// This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.
if let url = URL(string: "\(self._baseUrl)?url=\(self._url)") {
if let request = makeRequest(url: url) {
let task = URLSession.shared.dataTask(with: request)
task.resume()
}
}
// Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context.
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
override func configurationItems() -> [Any]! {
// To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
// if let tagsItem = SLComposeSheetConfigurationItem(),
// let titleItem = SLComposeSheetConfigurationItem(),
// let urlItem = SLComposeSheetConfigurationItem() {
// tagsItem.title = "Tags"
// tagsItem.value = "news"
// tagsItem.tapHandler = {
//
// }
//
// titleItem.title = "Title"
// titleItem.value = self._postTitle
// titleItem.tapHandler = {
//
// }
//
// urlItem.title = "Url"
// urlItem.value = self._url
// urlItem.tapHandler = {
//
// }
// return []
// }
return nil
}
}
//extension ShareViewController: ShareSelectViewControllerDelegate {
// func enteredTags(deck: Deck) {
// selectedDeck = deck
// reloadConfigurationItems()
// popConfigurationViewController()
// }
//}
|
//
// FunnyViewModel.swift
// DouYuZhiBo
//
// Created by Young on 2017/2/28.
// Copyright © 2017年 YuYang. All rights reserved.
//
import UIKit
class FunnyViewModel: BaseRoomViewModel {
func requestFunnyData(completion: @escaping () -> ()) {
let dict = ["limit" : "30", "offset" : "0"]
super.requestData(isGroup: false, urlSting: "http://capi.douyucdn.cn/api/v1/getColumnRoom/3", parameters: dict, completion: completion)
}
}
|
//
// ViewController.swift
// CompanyProject
//
// Created by Master on 27/06/2019.
// Copyright © 2019 Kirirushi. All rights reserved.
//
import UIKit
struct CompaniesJSON: Codable {
var id: String
var name: String
}
class CompaniesViewController: UIViewController {
weak var companiesTableView: UITableView?
var companiesArray: [CompaniesJSON] = []
override func viewDidLoad() {
super.viewDidLoad()
let tempTableView = UITableView()
tempTableView.backgroundColor = .white
tempTableView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(tempTableView)
view.bringSubviewToFront(tempTableView)
companiesTableView = tempTableView
let constraints = [
NSLayoutConstraint(item: tempTableView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: tempTableView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: tempTableView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: tempTableView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0),
]
NSLayoutConstraint.activate(constraints)
companiesTableView?.delegate = self
companiesTableView?.dataSource = self
requestCompanies()
}
func requestCompanies() {
companiesArray.removeAll()
UIApplication.shared.isNetworkActivityIndicatorVisible = true
guard let companiesURL = URL(string: "http://megakohz.bget.ru/test.php") else { return }
let request = URLRequest(url: companiesURL)
URLSession(configuration: URLSessionConfiguration.default).dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
if let error = error {
let alertController = UIAlertController(title: "Ошибка", message: "Код ошибки \(error.localizedDescription)", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Ок", style: .default))
self.present(alertController, animated: true)
}
if let data = data {
do {
let companiesArray = try JSONDecoder().decode([CompaniesJSON].self, from: data)
self.companiesArray = companiesArray
DispatchQueue.main.async {
self.companiesTableView?.reloadData()
}
} catch {
let alertController = UIAlertController(title: "Ошибка", message: "Невозможно разобрать ответ от сервера", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "ОК", style: .default))
self.present(alertController, animated: true)
}
}
}.resume()
}
}
extension CompaniesViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return companiesArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let company = companiesArray[indexPath.row]
if let companyCell = tableView.dequeueReusableCell(withIdentifier: "companyCell") as? CompanyCell {
companyCell.textLabel?.text = company.name
companyCell.id = company.id
return companyCell
} else {
let companyCell = CompanyCell(style: .default, reuseIdentifier: "companyCell")
companyCell.textLabel?.text = companiesArray[indexPath.row].name
companyCell.id = company.id
return companyCell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let companyViewController = CompanyCardViewController()
companyViewController.title = companiesArray[indexPath.row].name
companyViewController.id = companiesArray[indexPath.row].id
navigationController?.pushViewController(companyViewController, animated: true)
}
}
class CompanyCell: UITableViewCell {
var id: String?
}
|
import SpriteKit
public class GameView: SKView {
#if os(macOS)
public var controlKeyDelegate: ControlKeyDelegate?
public override func keyDown(with event: NSEvent) {
if let controlKey = ControlKey(rawValue: event.keyCode) {
controlKeyDelegate?.didRecieveKeyInput(withControlKey: controlKey)
}
}
public override func keyUp(with event: NSEvent) {
if let controlKey = ControlKey(rawValue: event.keyCode) {
controlKeyDelegate?.didEndKeyInput(withControlKey: controlKey)
}
}
#endif
}
#if os(OSX)
public protocol ControlKeyDelegate {
func didRecieveKeyInput(withControlKey controlKey: ControlKey)
func didEndKeyInput(withControlKey controlKey: ControlKey)
}
//Enum for control keys
public enum ControlKey: UInt16 {
//Move player keys
case upKey = 13 // W
case leftKey = 0 // A
case downKey = 1 // S
case rightKey = 2 // D
//Move stick keys
case leftArrow = 123 // Left arrow
case rightArrow = 124 // Right arrow
case upArrow = 126 // Up arrow
case downArrow = 125 //Down arrow
//Space key
case space = 49
public static func from(event: NSEvent) -> ControlKey? {
return ControlKey(rawValue: event.keyCode)
}
public var oppositeKey: ControlKey {
switch self {
case .upKey :
return .downKey
case .downKey :
return .upKey
case .leftKey :
return .rightKey
case .rightKey :
return .leftKey
case .leftArrow :
return .rightArrow
case .rightArrow :
return .leftArrow
case .upArrow :
return .downArrow
case .downArrow :
return .upArrow
case .space :
return .space
}
}
public var isMovementKey: Bool {
switch self {
case .upKey, .leftKey, .rightKey, .downKey :
return true
default :
return false
}
}
public var isDekeKey: Bool {
switch self {
case .leftArrow, .rightArrow :
return true
default :
return false
}
}
}
#endif
|
//
// DefaultError.swift
// GenAPI_Example
//
// Created by Lucas Best on 12/13/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
struct DefaultError: Decodable, LocalizedError {
var code: Int?
var errorDescription: String? {
return "An Unknown Error Occured"
}
var recoverySuggestion: String? {
return "Please try again later."
}
}
|
//
// PaymentViewController.swift
// Urway
//
// Copyright (c) 2020 URWAY. All rights reserved.
import UIKit
import SafariServices
import WebKit
import CommonCrypto
protocol IPaymentViewController: class {
var router: IPaymentRouter? { get set }
func apiResult(result: paymentResult, response: [String: Any]? , error: Error?)
}
class PaymentViewController: UIViewController {
var interactor: IPaymentInteractor?
var router: IPaymentRouter?
internal var initModel: UWInitializer?
internal var initProto: Initializer? = nil
var activityIndicator = UIActivityIndicatorView()
var lblActivityIndicator = UILabel()
var webView: WKWebView = WKWebView()
var newURL: String = ""
var splitstring1 : String = ""
var payid:String = ""
var tranid:String = ""
var results:String = ""
var amount:String = ""
var cardToken: String = ""
var respMsg: String = ""
var responsehash:String = ""
var responsecode:String = ""
var cardBrand:String=""
var maskedPan:String=""
var data:String = ""
var requestHash:String = ""
var merchantKey : String = ""
override func viewDidLoad() {
super.viewDidLoad()
// do someting...
self.title = "URWAY"
self.navigationController?.setNavigationBarHidden(false, animated: true)
self.view.backgroundColor = .white
guard let model = initModel else {return}
self.interactor?.postAPI(for: model)
webView = WKWebView()
webView.configuration.preferences.javaScriptEnabled = true
webView.navigationDelegate = self
activityIndicator.frame = CGRect(x: view.frame.width / 2 - 40,
y: view.frame.height / 2,
width: 40,
height: 40)
activityIndicator.center = view.center
activityIndicator.color = .red
webView.frame = view.frame
self.view.addSubview(webView)
// self.view.addSubview(activityIndicator)
activityIndicator.layer.zPosition = 1
activityIndicator.startAnimating()
lblActivityIndicator = UILabel(frame: CGRect(x: view.frame.width / 2 - 40,
y: view.frame.height / 2,
width: 200,
height: 150))
lblActivityIndicator.center = view.center
lblActivityIndicator.textAlignment = .center
lblActivityIndicator.textColor = .black
// lblActivityIndicator.layer.zPosition = 1
lblActivityIndicator.numberOfLines = 2
lblActivityIndicator.text = "Please wait \n Transaction is in process ..."
self.view.addSubview(lblActivityIndicator)
webView.configuration.userContentController.addUserScript(self.getZoomDisableScript())
}
private func getZoomDisableScript() -> WKUserScript {
let source: String = "var meta = document.createElement('meta');" +
"meta.name = 'viewport';" +
"meta.content = 'width=device-width, initial-scale=1.0, maximum- scale=1.0, user-scalable=no';" +
"var head = document.getElementsByTagName('head')[0];" + "head.appendChild(meta);"
return WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
}
}
extension PaymentViewController: IPaymentViewController {
func apiResult(result: paymentResult , response: [String: Any]? , error: Error?) {
responsecode = (response?["responsecode"] as? String) ?? "nil"
if responsecode.isEmpty || responsecode == "nil"{
responsecode = (response?["responseCode"] as? String) ?? "nil"
}
if responsecode == "000" {
print("success")
payid = (response?["payid"] as? String) ?? "nil"
tranid = (response?["tranid"] as? String) ?? ""
responsecode = (response?["responsecode"] as? String) ?? "nil"
amount = (response?["amount"] as? String) ?? ""
cardToken = (response?["cardToken"] as? String) ?? ""
cardBrand=(response?["cardBrand"] as? String) ?? ""
maskedPan=(response?["maskedPAN"] as? String) ?? ""
if responsecode.isEmpty || responsecode == "nil"{
responsecode = (response?["responseCode"] as? String) ?? "nil"
}
let message = UMResponceMessage.responseDict[responsecode] ?? ""
let model = PaymentResultData(paymentID: payid, transID: tranid, responseCode: responsecode, amount: amount, result: message ,tokenID: cardToken,cardBrand: cardBrand,maskedPan: maskedPan,responseMsg: message)
initProto?.didPaymentResult(result: .sucess , error: nil , model: model)
return
}else {
print("not sucess")
// targeturl == "some value" || targeturl == ""/null
let targetURL : String = response?["targetUrl"] as? String ?? ""
if targetURL.count == 0 {
payid = (response?["payid"] as? String) ?? "nil"
tranid = (response?["tranid"] as? String) ?? ""
responsecode = (response?["responsecode"] as? String) ?? "nil"
amount = (response?["amount"] as? String) ?? ""
cardBrand=(response?["cardBrand"] as? String) ?? ""
maskedPan=(response?["maskedPAN"] as? String) ?? ""
if responsecode.isEmpty || responsecode == "nil"{
responsecode = (response?["responseCode"] as? String) ?? "nil"
}
let message = UMResponceMessage.responseDict[responsecode] ?? ""
print(message)
let model = PaymentResultData(paymentID: payid, transID: tranid, responseCode: responsecode, amount: amount, result: "Failure",tokenID: cardToken,cardBrand: cardBrand,maskedPan: maskedPan,responseMsg: message)
initProto?.didPaymentResult(result: .failure(message), error: nil , model: model)
return
}else{
DispatchQueue.main.async {
self.lblActivityIndicator.removeFromSuperview()
guard let url = URL(string: fullURL) else {return}
self.webView.load(URLRequest(url: url))
}
}
}
}
// do someting...
}
extension PaymentViewController: WKNavigationDelegate {
// do someting...
}
extension PaymentViewController {
// do someting...
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if webView.isLoading {
return
}
estimatedProgress(keyPath: "estimatedProgress")
}
func estimatedProgress(keyPath :String) {
activityIndicator.startAnimating()
if keyPath == "estimatedProgress" {
print("check-->" ,self.webView.url ?? "")
let thisnewURL = self.webView.url
self.newURL = thisnewURL?.absoluteString ?? ""
let fullNameArr = self.newURL.components(separatedBy: "&")
print(fullNameArr)
payid = fullNameArr.first?.split(separator: "?").last?.components(separatedBy: "=").last ?? "nill"
tranid = fullNameArr.filter({$0.contains("TranId")}).first?.components(separatedBy: "=").last ?? ""
results = fullNameArr.filter({$0.contains("Result")}).first?.components(separatedBy: "=").last ?? ""
responsecode = fullNameArr.filter({$0.contains("ResponseCode")}).first?.components(separatedBy: "=").last ?? ""
amount = fullNameArr.filter({$0.contains("amount")}).first?.components(separatedBy: "=").last ?? ""
cardToken = fullNameArr.filter({$0.contains("cardToken")}).first?.components(separatedBy: "=").last ?? ""
cardBrand =
fullNameArr.filter({$0.contains("cardBrand")}).first?.components(separatedBy: "=").last ?? ""
maskedPan =
fullNameArr.filter({$0.contains("maskedPAN")}).first?.components(separatedBy: "=").last ?? ""
if payid == "nill" || payid.isEmpty{
self.payid = tranid
}
if responsecode.isEmpty {
responsecode = fullNameArr.filter({$0.contains("Responsecode")}).first?.components(separatedBy: "=").last ?? ""
}
if responsecode.isEmpty {
responsecode = fullNameArr.filter({$0.contains("responseCode")}).first?.components(separatedBy: "=").last ?? ""
}
if !responsecode.isEmpty || self.newURL.contains("HTMLPage.html") || self.newURL.contains("gateway"){
self.activityIndicator.stopAnimating()
self.lblActivityIndicator.removeFromSuperview()
}
if newURL.contains("Successful") {
self.activityIndicator.stopAnimating()
self.lblActivityIndicator.removeFromSuperview()
let message = UMResponceMessage.responseDict[responsecode] ?? ""
let model = PaymentResultData(paymentID: payid, transID: tranid, responseCode: responsecode, amount: amount, result: message ,tokenID: cardToken,cardBrand: cardBrand,maskedPan: maskedPan,responseMsg: message)
initProto?.didPaymentResult(result: .sucess , error: nil , model: model)
}
else if newURL.contains("Unsuccessful")
{
self.activityIndicator.stopAnimating()
self.lblActivityIndicator.removeFromSuperview()
let message = UMResponceMessage.responseDict[responsecode] ?? ""
let model = PaymentResultData(paymentID: payid, transID: tranid, responseCode: responsecode, amount: amount, result: "Failure",tokenID: cardToken,cardBrand: cardBrand,maskedPan: maskedPan,responseMsg: message)
initProto?.didPaymentResult(result: .failure(message), error: nil , model: model)
}
else if newURL.contains("Failure")
{
self.activityIndicator.stopAnimating()
self.lblActivityIndicator.removeFromSuperview()
let message = UMResponceMessage.responseDict[responsecode] ?? ""
let model = PaymentResultData(paymentID: payid, transID: tranid, responseCode: responsecode, amount: amount, result: "Failure",tokenID: cardToken,
cardBrand: cardBrand,maskedPan: maskedPan,responseMsg: message)
initProto?.didPaymentResult(result: .failure(message), error: nil , model: model)
}
} else {
print("Testing")
}
}
}
public class PaymentResultData {
public var paymentID: String
public var transID: String
public var responseCode: String
public var amount: String
public var result: String
public var tokenID: String
public var cardBrand:String
public var maskedPan:String
public var respMsg:String
public init(paymentID: String , transID: String , responseCode: String , amount: String , result: String , tokenID: String,cardBrand:String,maskedPan:String, responseMsg:String) {
self.paymentID = paymentID
self.transID = transID
self.responseCode = responseCode
self.amount = amount
self.result = result
self.tokenID = tokenID
self.cardBrand=cardBrand
self.maskedPan=maskedPan
self.respMsg=responseMsg
}
}
|
//
// ApiRest.swift
// songFinderApp
//
// Created by Nebraska Melendez on 7/23/19.
// Copyright © 2019 Nebraska Melendez. All rights reserved.
//
import Foundation
class ApiRest{
let settings: ApiSettings
let serviceUrl: URL
init(settings: ApiSettings, route:String) {
self.settings = settings
guard let url = URL(string: settings.baseUrl)else {
fatalError("URL invalida")
}
self.serviceUrl = url.appendingPathComponent(route)
}
}
|
//
// ToDoItem.swift
// Todo
//
// Created by edison on 2019/4/25.
// Copyright © 2019年 EDC. All rights reserved.
//
import Foundation
public class ToDoItem: NSObject {
// var id:Int
var title: String
var note: String
var date: Date
var priority: Int
var repeatday: String
var alarmOn: Bool
public init(title: String, note: String, date: Date, priority: Int, repeatday: String, alarmOn: Bool) {
// self.id=id
self.title = title
self.note = note
self.date = date
self.priority = priority
self.repeatday = repeatday
self.alarmOn = alarmOn
}
public override init() {
// get now
let now = Date()
// self.id=9999
title = ""
note = ""
date = now
priority = 3
repeatday = "0"
alarmOn = false
}
}
|
//
// CityListViewModelTests.swift
// weatherTests
//
// Created by Lauriane Haydari on 05/03/2020.
// Copyright © 2020 Lauriane Haydari. All rights reserved.
//
import XCTest
@ testable import weather
// MARK: - Mock
class MockCityListViewModelDelegate: CityListViewModelDelegate {
var alert: AlertType?
var weatherItem: WeatherItem?
func didSelectCity(item: WeatherItem) {
self.weatherItem = item
}
func displayAlert(for type: AlertType) {
self.alert = type
}
}
// MARK: - Tests
class CityListViewModelTests: XCTestCase {
let weatherItem = WeatherItem(nameCity: "paris",
time: "2020-02-13 12:00:00",
temperature: "19 °C",
iconID: "01d",
temperatureMax: "20 °C",
temperatureMin: "15 °C",
pressure: "1002 hPa",
humidity: "50 %",
feelsLike: "18 °C",
description: "Sunny")
let cityItem = CityItem(nameCity: "fr", country: "paris")
let delegate = MockCityListViewModelDelegate()
let repository = MockWeatherRepository()
func test_Given_ViewModel_When_ViewDidLoad_Then_visibleItemsAreDiplayed() {
repository.weatherItems = [self.weatherItem]
repository.cityItems = [self.cityItem]
let viewModel = CityListViewModel(repository: repository, delegate: delegate)
let expectation = self.expectation(description: "Diplayed visibleItems")
viewModel.visibleWeatherItems = { items in
XCTAssertEqual(items, [self.weatherItem])
expectation.fulfill()
}
viewModel.viewDidLoad()
waitForExpectations(timeout: 1.0, handler: nil)
}
func test_Given_ViewModel_When_ViewDidLoad_isLoadingIsDiplayed() {
repository.weatherItems = [self.weatherItem]
repository.cityItems = [self.cityItem]
let viewModel = CityListViewModel(repository: repository, delegate: delegate)
let expectation = self.expectation(description: "Diplayed activityIndicator network")
var counter = 0
viewModel.isLoading = { state in
if counter == 1 {
XCTAssertFalse(state)
expectation.fulfill()
}
counter += 1
}
viewModel.viewDidLoad()
waitForExpectations(timeout: 1.0, handler: nil)
}
func test_Given_ViewModel_When_didSelectCity_Then_expectedResult() {
repository.weatherItems = [self.weatherItem]
repository.cityItems = [self.cityItem]
let viewModel = CityListViewModel(repository: repository, delegate: delegate)
viewModel.viewDidLoad()
viewModel.didSelectCity(at: 0)
XCTAssertEqual(delegate.weatherItem, self.weatherItem)
}
func test_Given_ViewModel_When_didPressDelete_Then_expectedResult() {
repository.weatherItems = [self.weatherItem]
repository.cityItems = [self.cityItem]
let viewModel = CityListViewModel(repository: repository, delegate: delegate)
viewModel.viewDidLoad()
viewModel.didPressDeleteCity(at: 0)
XCTAssertEqual(delegate.weatherItem, nil)
}
}
|
//
// Contract.swift
// My1COrders
//
// Created by Владимир on 02.07.2020.
// Copyright © 2020 VladCorp. All rights reserved.
//
struct Contract: Codable{
let name: String
let number: String
let date: String
let status: String
let dateEnd: String
init?(name: String?, number: String?, date: String?, status: String?, dateEnd: String?){
guard
let name = name,
let number = number,
let date = date,
let status = status,
let dateEnd = dateEnd else {return nil}
self.name = name
self.number = number
self.date = date
self.status = status
self.dateEnd = dateEnd
}
}
struct ContractResponse: Decodable{
let agreements:[Contract]
}
|
//
// Soldier.swift
// Save The Princess
//
// Created by Danyl SEMMACHE on 6/27/17.
// Copyright © 2017 Danyl SEMMACHE. All rights reserved.
//
import Foundation
|
//
// DataCache.swift
// swiftTest
//
// Created by X on 15/3/3.
// Copyright (c) 2015年 swiftTest. All rights reserved.
//
import Foundation
import UIKit
class DataCache: NSObject {
static let Share = DataCache()
lazy var appConfig = APPConfigModel()
lazy var User = UserModel()
private override init() {
super.init()
if let model = APPConfigModel.read(name: "APPConfigModel")
{
appConfig = model as! APPConfigModel
}
else
{
appConfig.save()
}
if let model = UserModel.read(name: "UserModel")
{
User = model as! UserModel
}
else
{
User.save()
}
}
} |
import Foundation
import Paranormal
import Quick
import Nimble
class StatusBarViewControllerTests : QuickSpec {
override func spec() {
describe("Status Bar Controller Tests") {
var document : Document?
var windowController : WindowController!
var statusBarController : StatusBarViewController!
beforeEach() {
let documentController = DocumentController()
document = documentController
.makeUntitledDocumentOfType("Paranormal", error: nil) as? Document
documentController.addDocument(document!)
document?.makeWindowControllers()
windowController = document?.singleWindowController
statusBarController = windowController.statusBarViewController
}
describe("gui elements") {
describe("zoom") {
it("Zooms in the editor") {
statusBarController.zoomTextField.floatValue = 200.0
statusBarController.zoomSentFromGUI(statusBarController.zoomTextField)
expect(windowController.editorViewController?.zoom).to(equal(2.0))
}
it("Triggers a PNNotificationZoomChanged notification") {
var ranNotification = false
NSNotificationCenter.defaultCenter()
.addObserverForName(PNNotificationZoomChanged, object: nil, queue: nil,
usingBlock: { (n) -> Void in
ranNotification = true
})
statusBarController.zoomSentFromGUI(statusBarController.zoomTextField)
let date = NSDate(timeIntervalSinceNow: 0.1)
NSRunLoop.currentRunLoop().runUntilDate(date)
expect(ranNotification).toEventually(beTrue(()))
}
}
}
}
}
}
|
//: [Previous](@previous)
import Combine
import Foundation
var cancellables = Set<AnyCancellable>()
// Threadの切り替えを行なっていないため
// 全ての処理はMainThreadで行われている(Playgroundでは)
run("subscribe(on:) Thread切り替えなし") {
print("start: \(Thread.current.number)")
[1,2,3,4].publisher
.handleEvents(receiveSubscription: { _ in print("handleEvents receiveSubscription: \(Thread.current.number)") },
receiveOutput: { _ in print("handleEvents receiveOutput: \(Thread.current.number)") },
receiveCompletion: { _ in print("handleEvents receiveCompletion: \(Thread.current.number)") },
receiveCancel: { print("handleEvents receiveCancel: \(Thread.current.number)") },
receiveRequest: { _ in print("handleEvents receiveRequest: \(Thread.current.number)") })
.sink { _ in print("sink receivedValue: \(Thread.current.number)") }
.store(in: &cancellables)
}
//: [Next](@next)
|
//
// ErrorPresenterViewController.swift
// PopUpCorn
//
// Created by Elias Paulino on 16/02/19.
// Copyright © 2019 Elias Paulino. All rights reserved.
//
import UIKit
/// a view controller responsible by showing errors alerts. It make custom alerts using the alert decorators.
class ErrorPresenterViewController: UIViewController {
weak var reloadDelegate: ReloaderAlertBuilderDelegate?
private var isPresentingAlert = false
override func viewDidLoad() {
super.viewDidLoad()
view.isUserInteractionEnabled = false
}
private func alertMiddleware(
withTitle title: String,
andMessage message: String,
completion: (AlertBuilderProtocol, (AlertBuilderProtocol) -> Void) -> Void) {
let alertBuilder: AlertBuilderProtocol = AlertBuilder.init(withTitle: title, andMessage: message)
completion(alertBuilder, { alertBuilder in
guard self.isPresentingAlert == false else {
return
}
self.isPresentingAlert = true
present(alertBuilder.alertController(), animated: true, completion: {
self.isPresentingAlert = false
})
})
}
func showSimpleError(withTitle title: String, andMessage message: String) {
alertMiddleware(withTitle: title, andMessage: message) { (simpleAlertBuilder, present) in
present(simpleAlertBuilder)
}
}
func showReloaderError(withTitle title: String, andMessage message: String) {
alertMiddleware(withTitle: title, andMessage: message) { (alertBuilder, present) in
let reloadAlertBuilder = ReloaderAlertBuilder.init(
withAlertBuilder: alertBuilder,
andDelegate: reloadDelegate
)
present(reloadAlertBuilder)
}
}
func showQuitError(
withTitle title: String,
andMessage message: String,
andControllerToQuit controllerToQuit: ClosableViewControllerProtocol) {
alertMiddleware(withTitle: title, andMessage: message) { (alertBuilder, present) in
let quitAlertBuilder = QuitAlertBuilder.init(
withAlertBuilder: alertBuilder,
controllerToQuit: controllerToQuit
)
present(quitAlertBuilder)
}
}
}
|
//
// UIImageView+loader.swift
// gallery
//
// Created by Algis on 18/10/2020.
//
import UIKit
extension UIImageView {
func loadImage(at url: String) {
UIImageLoader.loader.load(url, for: self)
}
func cancelImageLoad() {
UIImageLoader.loader.cancel(for: self)
}
}
|
//
// TopicController.swift
// rush00
//
// Created by Audran DITSCH on 1/13/18.
// Copyright © 2018 Charles LANIER. All rights reserved.
//
import UIKit
class TopicController: UITableViewController, API42Delegate {
var apiController: API42Controller? {
didSet {
apiController?.delegate = self;
}
};
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "segueShowTopic") {
if let vc = segue.destination as? TopicContentController {
if let sender = sender as? TopicCell {
vc.apiController = apiController;
vc.topicId = sender.topic?.id;
vc.messages_url = sender.topic?.messages_url;
}
}
}
else if segue.identifier == "segueNewTopic" {
print("New Topic")
}
}
override func viewDidAppear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(false, animated: animated);
super.viewDidAppear(animated);
}
override func viewDidLoad() {
super.viewDidLoad()
tableView?.rowHeight = UITableViewAutomaticDimension;
tableView.estimatedRowHeight = 80;
tableView.cellLayoutMarginsFollowReadableWidth = false;
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
return (1);
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (Topics.count);
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "topicCell", for: indexPath) as! TopicCell
cell.topic = Topics[indexPath.row];
return (cell);
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath);
tableView.deselectRow(at: indexPath, animated: true)
performSegue(withIdentifier: "segueShowTopic", sender: cell)
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return (UITableViewAutomaticDimension);
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.contentView.backgroundColor = indexPath.row % 2 == 0 ? UIColor.GrayCell : UIColor.WhiteCell;
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
}
extension UIColor {
static var GrayCell: UIColor { return (UIColor(red: 0.96, green: 0.96, blue: 0.96, alpha: 1)) }
static var WhiteCell: UIColor { return (UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1)) }
static var GrayBorder: UIColor { return (UIColor(red:0.92, green:0.92, blue:0.92, alpha:1.0)) }
}
|
//
// p04_samjdavis13.swift
//
//
// Created by Sam Davis on 24/05/2016.
//
//
extension List {
var length: Int {
var count = 1
var current = self
while let next = current.nextItem {
current = next
count += 1
}
return count
}
} |
//
// main.swift
// JASON
//
// Created by MacStudent on 2020-02-19.
// Copyright © 2020 MacStudent. All rights reserved.
//
import Foundation
func readTextFile(filename: String)
{
print(Bundle.main.bundlePath)
if let path = Bundle.main.path(forResource: filename, ofType: "txt")
{
//print(path)
let str = try! String(contentsOfFile: path)
print(str)
}
}
//readTextFile(filename: "data")
func readUserInfo(filename: String) {
let filePath = Bundle.main.url(forResource: filename, withExtension: "json")
guard let path = filePath else {
print("Invalid file path found")
return
}
guard let data = try? Data(contentsOf: path) else {
print("Error while read Data from URL")
return
}
guard let json = try? JSONSerialization.jsonObject(with: data, options: []) else
{
print("Error while reading Json Data from file")
return
}
print(json)
}
readUserInfo(filename: "singleUser")
|
import Foundation
extension CoreStateSlice {
func reduce(_ action: Actionable) -> CoreStateSlice {
if let reducer = self.reducers[action.type] {
return reducer.call(self, action)
}
return self // TODO: return nil if no change
}
}
|
//
// MemoCoreData+CoreDataClass.swift
//
//
// Created by 행복한 개발자 on 27/06/2019.
//
//
import Foundation
import CoreData
@objc(MemoCoreData)
public class MemoCoreData: NSManagedObject {
}
|
//
// LifecycleTests.swift
// FirstTests
//
// Created by Andrei Chenchik on 16/6/21.
//
import XCTest
class LifecycleTests: XCTestCase {
override class func setUp() {
print("In class setUp.")
}
override class func tearDown() {
print("In class tearDown.")
}
override func setUpWithError() throws {
print("In setUp.")
}
override func tearDownWithError() throws {
print("In tearDown.")
}
func testExample() throws {
print("Starting test.")
addTeardownBlock {
print("In first tearDown block.")
}
print("In middle of test.")
addTeardownBlock {
print("In second tearDown block.")
}
print("Finishing test.")
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
|
// Helper functions
func pad(string : String, toSize: Int = 8) -> String {
var padded = string
for _ in 0..<(toSize - string.count) {
padded = "0" + padded
}
return padded
}
func printBinary(of num: UInt8) {
let str = String(num, radix: 2)
print("num:\t\(num)\t\tbinary:\t\(pad(string: str))") // 00010110
}
/*
Q342 Power of Four
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
*/
printBinary(of: 4)
printBinary(of: 16)
printBinary(of: 64)
/*
num: 4 binary: 00000100
num: 16 binary: 00010000
num: 64 binary: 01000000
*/
/*
Solving Power of Four we care about 3 bits, if the last 3 bits is '100',
so instead of & 1 to check the last 3 bits, we use '& 7' (& 111) and we count the number of '100' we have found
if it is '100' we increase the count, return false if the count > 1
if it is '000' we can shift right by 2
if it is other value besides of '100' or '000', then it can not be a power of 4, return false directly
*/
func isPowerOfFour1(num: Int) -> Bool {
if num == 0 { return false }
var count100s = 0
var n = num
while n >= 4 {
if n & 7 == 4 {
if count100s > 0 { return false }
count100s += 1
} else if n & 7 != 0 {
return false
}
n = n >> 2
}
if n < 4 && n != 1 {
return false
} else {
return count100s == 1
}
}
print("is power of 4: \(isPowerOfFour1(num: 4))")
print("is power of 4: \(isPowerOfFour1(num: 12))")
print("is power of 4: \(isPowerOfFour1(num: 64))")
printBinary(of: 15)
printBinary(of: 16)
printBinary(of: 17)
/*
We will be able to find another solution by introducing 0x55555555,
0x55555555 = 0101 0101 ... 0101
0xaaaaaaaa = 1010 1010 ... 1010
For a power of 4: n, n & 0x55555555 should be n
*/
func isPowerOfFour2(num: Int) -> Bool {
return (num > 0) && (num & (num - 1)) == 0 && (num & 0x55555555) == num
}
/*
Other solutions, I am not going to cover so much in this page
*/
func isPowerOfFour3(num: Int) -> Bool {
return (num > 0) && (num & (num - 1)) == 0 && (num - 1) % 3 == 0
}
// works in C++, NOT work in Swift or Java,
func isPowerOfFour4(num: Int) -> Bool {
let res = log(Double(num)) / log(3.0)
let ceilRes = ceil(res)
return (num > 0) && (res == ceilRes)
}
print(isPowerOfFour4(num: 15))
print(isPowerOfFour4(num: 16))
print(isPowerOfFour4(num: 4))
|
//
// TaskService.swift
// splitwork
//
// Created by Vivek Madhusudan Badrinarayan on 4/27/18.
// Copyright © 2018 Vivek Badrinarayan. All rights reserved.
//
import Foundation
import UIKit
class TaskService {
let httpService: HTTPService
private static var sharedService: TaskService = {
let service = TaskService()
return service
}()
private init() {
self.httpService = HTTPService.shared()
print("CardService initialized..")
}
class func shared() -> TaskService {
return sharedService
}
func syncTasks(onSync: (() -> ())?) {
Business.shared().tasks?.clear()
let completionHandler: (String, [String: Any]) -> () = { error, data in
if(error != "") {
print("Error in TaskService.syncUsers()")
} else {
if let tasks = data["data"] as? [String:Any] {
print("received tasks from server, task count \(tasks.count)")
for _task in tasks {
let task = _task.value as! [String: Any]
let id = _task.key
let name = task["name"] as! String
let desc = task["desc"] as! String
let assignedTo = task["assignedTo"] as! String
let assignedDate = task["assignedDate"] as! String
let deadlineDate = task["deadlineDate"] as! String
let completionDate = task["completionDate"] as! String
let groupId = task["groupId"] as! String
let status = task["status"] as! String
let completionPercentage = task["completionPercentage"] as! String
let _assignedDate = Util.strToDate(dateInStr: assignedDate)
let _deadlineDate = Util.strToDate(dateInStr: deadlineDate)
let _completionDate = Util.strToDate(dateInStr: completionDate)
let _completionPercentage = Double(completionPercentage)
// add task to model
Business.shared().tasks?.addTask(id: id, name: name, desc: desc, assignedTo: assignedTo, assignedDate: _assignedDate!, deadlineDate: _deadlineDate!, completionDate: _completionDate!, groupId: groupId, status: status, completionPercentage: _completionPercentage!)
}
}
}
print("synced tasks from server, task count = \((Business.shared().tasks?.tasks.count)!)")
onSync?()
}
httpService.get(url: "tasks", completionHandler: completionHandler)
}
func addTask(groupId: String, name: String, desc: String, assignedTo: String, deadlineDate: Date) {
var task = [String: Any]()
task["groupId"] = groupId
task["name"] = name
task["desc"] = desc
task["assignedTo"] = assignedTo
task["assignedDate"] = Util.dateToStr(date: Date())
task["deadlineDate"] = Util.dateToStr(date: deadlineDate)
task["completionDate"] = Util.dateToStr(date: deadlineDate)
task["status"] = "Assigned"
task["completionPercentage"] = "0.0"
let completionHandler: (String, [String: Any]) -> () = { error, data in
if(error != "") {
print("Error in adding task to firebase, error = \(error)")
} else {
print("Success in adding task to firebase")
print("data = \(data)")
if let res = data["data"] as? [String: Any] {
if let taskId = res["name"] as? String {
print("taskId = \(taskId)")
// add the taskId to group
GroupService.shared().addTaskToGroup(groupId: groupId, taskId: taskId)
}
}
self.syncTasks(onSync: nil)
}
}
httpService.post(url: "tasks", data: task, completionHandler: completionHandler)
}
func updateTaskStatus(taskId: String, status: String) {
var task = [String: Any]()
task["status"] = status
let completionHandler: (String, [String: Any]) -> () = { error, data in
if(error != "") {
print("Error in adding task to firebase, error = \(error)")
} else {
print("Success in adding task to firebase")
self.syncTasks(onSync: nil)
}
}
httpService.patch(url: "tasks/\(taskId)", data: task, completionHandler: completionHandler)
}
}
|
import Cocoa
// Initialize player's data storage
var players = [
["name": "Joe Smith", "height": "42", "playedb4" : "YES", "guardian" : "Jim and Jan Smith"],
["name": "Jill Tanner", "height" : "36", "playedb4" : "YES", "guardian" : "Clara Tanner"],
["name": "Bill Bon", "height" : "43", "playedb4" : "YES", "guardian" : "Sara and Jenny Bon"],
["name": "Eva Gordon", "height" : "45", "playedb4" : "NO", "guardian" : "Wendy and Mike Gordon"],
["name": "Matt Gill", "height": "40", "playedb4": "NO", "guardian": "Charles and Sylvia Gill"],
["name": "Kimmy Stein", "height": "41", "playedb4": "NO", "guardian": "Bill and Hillary Stein"],
["name": "Sammy Adams", "height": "45", "playedb4": "NO", "guardian": "Jeff Adams"],
["name": "Karl Saygan", "height": "42", "playedb4": "YES", "guardian": "Heather Bledsoe"],
["name": "Suzane Greenberg", "height": "44", "playedb4": "YES", "guardian": "Henrietta Dumas"],
["name": "Sal Dali", "height": "41", "playedb4": "NO", "guardian": "Gala Dali"],
["name": "Joe Kavalier", "height": "39", "playedb4": "NO", "guardian": "Sam and Elaine Kavalier"],
["name": "Ben Finkelstein", "height": "44", "playedb4": "NO", "guardian": "Aaron and Jill Finkelstein"],
["name": "Diego Soto", "height": "41", "playedb4": "YES", "guardian": "Robin and Sarika Soto"],
["name": "Chloe Alaska", "height": "47", "playedb4": "NO", "guardian": "David and Jamie Alaska"],
["name": "Arnold Willis", "height": "43", "playedb4": "NO", "guardian": "Claire Willis"],
["name":"Phillip Helm", "height": "44", "playedb4": "YES", "guardian": "Thomas Helm and Eva Jones"],
["name": "Les Clay", "height": "42", "playedb4": "YES", "guardian": "Wynonna Brown"],
["name": "Herschel Krustofski","height": "45", "playedb4": "YES", "guardian": "Hyman and Rachel Krustofski"]
]
// Intialize three evenly matched teams
typealias Team = [String : Any]
typealias Player = [String : String]
var teamSharks : Team = ["name": "teamSharks", "players": NSMutableArray()],
teamDragons : Team = ["name": "teamDragons", "players": NSMutableArray()],
teamRaptors : Team = ["name": "teamRaptors", "players": NSMutableArray()]
// Divide players into two group, experienced group and inexperienced group
var experiencedPlayers = [Player]()
var inexperiencedPlayers = [Player]()
for player in players {
if player["playedb4"] == "YES" {
experiencedPlayers += [player]
} else {
inexperiencedPlayers += [player]
}
}
// Sort players by height, with two groups inverted to each other
experiencedPlayers.sort{ Int($0["height"]!)! < Int($1["height"]!)! }
inexperiencedPlayers.sort{ Int($0["height"]!)! > Int($1["height"]!)! }
// Pairing every two players as a partner
var partners = [[Player]]()
for i in 0..<players.count / 2 {
partners += [[experiencedPlayers[i], inexperiencedPlayers[i]]]
}
// Divide partners into three evenly distributed teams
for j in 1...3 {
var currentTeam = NSMutableArray()
switch j {
case 1:
currentTeam = teamSharks["players"] as! NSMutableArray
case 2:
currentTeam = teamDragons["players"] as! NSMutableArray
case 3:
currentTeam = teamRaptors["players"] as! NSMutableArray
default: break
}
for i in stride(from: j, through: (players.count / 2), by: 3) {
currentTeam.add( partners[i - 1] )
}
}
// Create a teams variable that contains all three teams
var teams = [teamRaptors, teamDragons, teamSharks]
/**
Calculate the average height of a specified team
*/
func averageHeight(forTeam team: Team) -> Int {
var accumulatedHeight = 0
var memberCount = 0
for partner in team["players"] as! [[Player]] {
for player in partner {
memberCount += 1
accumulatedHeight += Int(player["height"]!)!
}
}
return accumulatedHeight / memberCount
}
/**!
Prints letter to parents of a specified team
*/
func letter(for team: Team) -> [String] {
var output = [String]()
var practiceTime = ""
switch team["name"] as! String {
case "teamSharks":
practiceTime = "March 17, 3pm"
case "teamDragons":
practiceTime = "March 17, 1pm"
case "teamRaptors":
practiceTime = "March 18, 1pm"
default:
practiceTime = "Not on schedule"
}
for partner in team["players"] as! [[Player]] {
if partner.count > 1 {
for player in partner {
if let guardian = player["guardian"],
let playerName = player["name"],
let teamName = team["name"] {
output += ["Greetings \(guardian), \n" +
"\(playerName) is placed into \(teamName) in the up coming Soccer League Game, \n" +
"average player height for team: \(averageHeight(forTeam: team)) inch\n" +
"Be sure to come for team practice at \(practiceTime)\n" +
"-Soccer League Coordinator\n"]
}
}
}
}
return output
}
// Letters for guardians of players in each team
let lettersForTeamDragons = letter(for: teamDragons)
let lettersForTeamSharks = letter(for: teamSharks)
let lettersForTeamRaptors = letter(for: teamRaptors)
let letters = lettersForTeamRaptors + lettersForTeamSharks + lettersForTeamDragons
// Print all letters
for letter in letters {
print(letter)
}
|
//
// DeviceViewModel.swift
// iOS_Aura
//
// Created by Yipei Wang on 2/21/16.
// Copyright © 2016 Ayla Networks. All rights reserved.
//
import Foundation
import iOS_AylaSDK
class DeviceViewModel:NSObject, AylaDeviceListener {
private let logTag = "DeviceViewModel"
/// Device panel, refer to DevicePanelView for details
weak var devicePanel: DevicePanelView?
var sharesModel: DeviceSharesModel?
/// Property list model view
let propertyListViewModel :PropertyListViewModel?
/// Device representd by this view model
let device: AylaDevice
required init(device:AylaDevice, panel:DevicePanelView?, propertyListTableView: UITableView?, sharesModel:DeviceSharesModel?) {
self.devicePanel = panel
self.device = device
self.sharesModel = sharesModel
if let tv = propertyListTableView {
// If a table view has been passed in, create a property list view model and assign the input tableview to it.
self.propertyListViewModel = PropertyListViewModel(device: device, tableView: tv)
} else {
self.propertyListViewModel = nil
}
super.init()
// Add self as device listener
device.add(self)
self.update()
}
func shareDevice(_ presentingViewController:UIViewController, withShare share:AylaShare, successHandler: ((_ share: AylaShare) -> Void)?, failureHandler: ((_ error: Error) -> Void)?){
if let sessionManager = AylaNetworks.shared().getSessionManager(withName: AuraSessionOneName){
sessionManager.createShare(share, emailTemplate: nil, success: { (share: AylaShare) in
NotificationCenter.default.post(name: Notification.Name(rawValue: AuraNotifications.SharesChanged), object:self)
let successAlert = UIAlertController(title: "Success", message: "Device successfully shared.", preferredStyle: .alert)
let okayAction = UIAlertAction(title: "Okay", style: .cancel, handler: {(action) -> Void in
if let successHandler = successHandler{
successHandler(share)
}
})
successAlert.addAction(okayAction)
presentingViewController.present(successAlert, animated: true, completion: nil)
}, failure: { (error: Error) in
let alert = UIAlertController(title: "Error", message: error.description, preferredStyle: .alert)
let gotIt = UIAlertAction(title: "Got it", style: .cancel, handler: { (action) -> Void in
if let failureHandler = failureHandler{
failureHandler(error)
}
})
alert.addAction(gotIt)
presentingViewController.present(alert, animated: true, completion: nil)
})
}
}
func shareDevice(_ presentingViewController:UIViewController, successHandler: ((_ share: AylaShare) -> Void)?, failureHandler: ((_ error: Error) -> Void)?){
let shareStoryboard: UIStoryboard = UIStoryboard(name: "CreateShare", bundle: nil)
let shareNavVC = shareStoryboard.instantiateInitialViewController() as! UINavigationController
let createShareController = shareNavVC.viewControllers.first! as! CreateDeviceShareViewController
createShareController.deviceViewModel = self
presentingViewController.navigationController?.present(shareNavVC, animated: true, completion:nil)
}
func unregisterDeviceWithConfirmation(_ presentingViewController:UIViewController, successHandler: (() -> Void)?, failureHandler: ((_ error: Error) -> Void)?) {
let name = device.productName ?? "unnamed device"
let dsn = device.dsn ?? "unknown"
func unregisterDeviceWithError(){
self.device.unregister(success: {
let alert = UIAlertController(title: "Device Unregistered.", message: nil, preferredStyle: .alert)
let okayAction = UIAlertAction(title: "Okay", style: .cancel, handler: {(action) -> Void in
if let successHandler = successHandler{successHandler()}
})
alert.addAction(okayAction)
presentingViewController.present(alert, animated: true, completion: nil)
}, failure: { (error) in
let alert = UIAlertController(title: "Error", message: error.description, preferredStyle: .alert)
let okayAction = UIAlertAction(title: "Okay", style: .cancel, handler: {(action) -> Void in
if let failureHandler = failureHandler{failureHandler(error as NSError)}
})
alert.addAction(okayAction)
presentingViewController.present(alert, animated: true, completion: nil)
})
}
if device.grant != nil { // Device is shared to the user
let alert = UIAlertController(title:"Cannot Unregister this device", message: "This device is shared to you, so you are not able to unregister it, but you may unshare it.", preferredStyle: .alert)
let unshareAction = UIAlertAction(title:"Delete Share", style: .destructive) { (action) in
if let share = self.sharesModel?.receivedShareForDevice(self.device) {
let shareViewModel = ShareViewModel(share: share)
shareViewModel.deleteShareWithoutConfirmation(presentingViewController, successHandler: {
unregisterDeviceWithError()
}, failureHandler: { (error) in
let alert = UIAlertController(title: "Error", message: error.description, preferredStyle: .alert)
let gotIt = UIAlertAction(title: "Got it", style: .cancel, handler: {(action) -> Void in
if let failureHandler = failureHandler{
failureHandler(error)
}
})
alert.addAction(gotIt)
presentingViewController.present(alert, animated: true, completion: nil)
})
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .default) { (action) in }
alert.addAction(cancelAction)
alert.addAction(unshareAction)
presentingViewController.present(alert, animated: true, completion:nil)
} else { // Device owned by user
let alert = UIAlertController(title: "Continue?", message: "Are you sure you want to unregister device \(name), (DSN: \(dsn))?", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let okAction = UIAlertAction(title: "Unregister", style: .destructive) { (action) in
// Check if device is shared to anyone before unregistering
if let shares = self.sharesModel?.ownedSharesForDevice(self.device) {
// Device is shared
if shares.count > 0 {
let alert = UIAlertController(title:"Device is shared to \(shares.count) other user" + (shares.count > 1 ? "s." : "." ), message: "You must unshare it from all users to whom you have shared it first.", preferredStyle: .alert)
let unshareAction = UIAlertAction(title:(shares.count < 2 ? "Delete Share" : "Delete Shares"), style: .destructive) { (action) in
// Delete all extant owned shares
var sharesCount = shares.count
for share in (shares as [AylaShare]!) {
let shareViewModel = ShareViewModel(share: share)
shareViewModel.deleteShareWithoutConfirmation(presentingViewController, successHandler: {
sharesCount = sharesCount - 1
if sharesCount == 0 {
// Unregister device when done deleting shares.
let alert = UIAlertController(title: "Shares Successfully Deleted.", message: "Continue with Unregistration?", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {(action) -> Void in })
let continueAction = UIAlertAction(title: "Continue", style: .destructive, handler: {(action) -> Void in
unregisterDeviceWithError()
})
alert.addAction(cancelAction)
alert.addAction(continueAction)
presentingViewController.present(alert, animated: true, completion: nil)
}
}, failureHandler: { (error) in
let alert = UIAlertController(title: "Error", message: error.description, preferredStyle: .alert)
let gotIt = UIAlertAction(title: "Got it", style: .cancel, handler: {(action) -> Void in
if let failureHandler = failureHandler{failureHandler(error)}
})
alert.addAction(gotIt)
presentingViewController.present(alert, animated: true, completion: nil)
})
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .default) { (action) in }
alert.addAction(cancelAction)
alert.addAction(unshareAction)
presentingViewController.present(alert, animated: true, completion:nil)
}
// Device not shared.
else {
unregisterDeviceWithError()
}
// Shares comes back nil, not empty. This shouldn't happen, but try to unregister anyway.
} else {
unregisterDeviceWithError()
}
}
alert.addAction(cancelAction)
alert.addAction(okAction)
presentingViewController.present(alert, animated: true, completion: nil)
}
}
func renameDevice(_ presentingViewController:UIViewController, successHandler: (() -> Void)?, failureHandler: ((_ error: NSError) -> Void)?){
var nameTextField = UITextField()
let alert = UIAlertController(title: "Rename " + (device.productName)!, message: "Enter the new name", preferredStyle: UIAlertControllerStyle.alert)
alert.addTextField { (textField) -> Void in
textField.placeholder = "New name"
textField.tintColor = UIColor(red: 93.0/255.0, green: 203/255.0, blue: 152/255.0, alpha: 1.0)
nameTextField = textField
}
let okAction = UIAlertAction (title: "Confirm", style: UIAlertActionStyle.default) { (action) -> Void in
let newName = nameTextField.text
if newName == nil || newName!.characters.count < 1 {
UIAlertController.alert("Error", message: "No name was provided", buttonTitle: "OK",fromController: presentingViewController)
return;
}
self.device.updateProductName(to: newName!, success: { () -> Void in
let alert = UIAlertController(title: "Device renamed", message: nil, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction (title: "OK", style: UIAlertActionStyle.default, handler:{(action) -> Void in
if let successHandler = successHandler{
successHandler()
}
})
alert.addAction(okAction)
presentingViewController.present(alert, animated: true, completion: nil)
}, failure: { (error) -> Void in
let errorAlert = UIAlertController(title: "Device renamed", message: nil, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction (title: "OK", style: UIAlertActionStyle.default, handler:{(action) -> Void in
if let failureHandler = failureHandler{
failureHandler(error as NSError)
}
})
alert.addAction(okAction)
presentingViewController.present(errorAlert, animated: true, completion: nil)
})
}
let cancelAction = UIAlertAction (title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(cancelAction)
alert.addAction(okAction)
presentingViewController.present(alert, animated: true, completion: nil)
}
/**
Use this method to update UI which are managed by this view model.
*/
func update() {
if self.devicePanel != nil {
devicePanel?.configure(device, sharesModel:sharesModel)
}
// We don't update property list here since PropertyListViewModel will take care of it.
}
// MARK - device manager listener
func device(_ device: AylaDevice, didFail error: Error) {
AylaLogW(tag: logTag, flag: 0, message:"an error happened on device \(error)")
}
func device(_ device: AylaDevice, didObserve change: AylaChange) {
// We don't update property list here since PropertyListViewModel will take care of it.
if let _ = change as? AylaPropertyChange {
return
}
self.update()
}
func device(_ device: AylaDevice, didUpdateLanState isActive: Bool) {
self.update()
}
}
|
//
// CBServer.swift
// ADGAP
//
// Created by Jitendra Kumar on 22/05/20.
// Copyright © 2020 Jitendra Kumar. All rights reserved.
//
import UIKit
import Alamofire
typealias CBServerResponse<Success> = (Swift.Result<Success, Error>)->Void
typealias CBServerProgress = (Progress) -> Void
typealias CBHTTPHeaders = HTTPHeaders
typealias CBHTTPHeader = HTTPHeader
typealias CBParameters = Parameters
final class CBServer: NSObject {
static let shared = CBServer()
struct CBEncoder {
enum DataEncoding {
case URL
case JSON
var `default`:ParameterEncoding{
switch self {
case .JSON:return JSONEncoding.default
default: return URLEncoding.default
}
}
}
enum JSONEncoder {
case URL
case JSON
var `default`:ParameterEncoder{
switch self {
case .JSON:return JSONParameterEncoder.default
default: return URLEncodedFormParameterEncoder.default
}
}
}
}
//MARK:- dataTask
func dataTask(_ state:CBSessionConfig.State = .default, endpoint: CBEndpoint,
method: HTTPMethod = .post,
parameters: CBParameters? = nil,
encoding: CBEncoder.DataEncoding = .URL,
headers: CBHTTPHeaders? = nil,completion:@escaping CBServerResponse<Data>){
print(String(describing: parameters))
CBSession.shared.request(state,url: endpoint.url, method: method, parameters: parameters, encoding: encoding.default, headers: headers).responseData { dataResponse in
let result = dataResponse.result
switch result{
case .success(let data):
completion(.success(data))
case .failure(let error):
completion(.failure(error))
}
}.resume()
}
//MARK:- JSON DataTask
func dataTask<T:Mappable>(_ state:CBSessionConfig.State = .default, endpoint: CBEndpoint,
method: HTTPMethod = .post,
parameters: CBParameters? = nil,
encoding: CBEncoder.DataEncoding = .URL,
headers: CBHTTPHeaders? = nil,completion:@escaping CBServerResponse<T>){
CBSession.shared.request(state,url: endpoint.url, method: method, parameters: parameters, encoding: encoding.default, headers: headers).responseData { response in
self.decodableResponse(dataResponse: response, completion: completion)
}.resume()
}
func dataTask<T: Mappable>(_ state:CBSessionConfig.State = .default, endpoint: CBEndpoint,
method: HTTPMethod = .post,
parameters: T? = nil,
encoder: CBEncoder.JSONEncoder = .JSON,
headers: CBHTTPHeaders? = nil,completion:@escaping CBServerResponse<T>){
CBSession.shared.request(state, url: endpoint.url, method: method, parameters: parameters, encoder: encoder.default, headers: headers).responseData { response in
self.decodableResponse(dataResponse: response, completion: completion)
}.resume()
}
//MARK:- DownloadTask
func downloadTask(_ state:CBSessionConfig.State = .default, endpoint: CBEndpoint,
method: HTTPMethod = .get,
headers: CBHTTPHeaders? = nil,completion:@escaping CBServerResponse<URL?>, downloadProgress:@escaping CBServerProgress){
let destination: DownloadRequest.Destination = { filePath,response in
let directory = CBSessionConfig.shared.documentsDirectoryURL
let fileURL = directory.appendingPathComponent(response.suggestedFilename!)
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
CBSession.shared.download(state, url: endpoint.url, method: method, headers: headers, to: destination).response { (downloadResponse) in
switch downloadResponse.result{
case .success(let url):
completion(.success(url))
case .failure(let error):
completion(.failure(error))
}
}.downloadProgress(closure: downloadProgress).resume()
}
}
fileprivate extension CBServer{
//MARK:- decodableResponse
func decodableResponse<T:Mappable>(dataResponse:AFDataResponse<Data>,completion:@escaping CBServerResponse<T>){
//let statusCode = dataResponse.response!.statusCode
let result = dataResponse.result
switch result{
case .success(let data):
let jsR = data.JKDecoder(T.self)
switch jsR {
case .success(let v):
completion(.success(v))
case .failure(let error):
print(String(describing: data.utf8String))
completion(.failure(error))
}
case .failure(let error):
completion(.failure(error))
}
}
}
|
//
// ContentView.swift
// NGenTodo
//
// Created by yamada.ryo on 2020/07/04.
// Copyright © 2020 yamada.ryo. All rights reserved.
//
import SwiftUI
struct ContentView: View {
var body: some View {
MainTabBarView()
.environmentObject(TodoListViewModel())
.environmentObject(TemplateListViewModel())
.onAppear {
DarkModeModel().reflectDarkMode()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
//
// lapData.swift
// Timer
//
// Created by 김예진 on 2017. 11. 12..
// Copyright © 2017년 Kim,Yejin. All rights reserved.
//
import Foundation
class lapData {
var lapCount : Int = 0
var lapTime : String = ""
init(lapTime: String, lapCount: Int) {
self.lapTime = lapTime
self.lapCount = lapCount
}
}
|
//
// AssetGirdVC.swift
// VideoMarks
//
// Created by nevercry on 7/14/16.
// Copyright © 2016 nevercry. All rights reserved.
//
import UIKit
import Photos
import AVKit
import QuartzCore
//private let reuseIdentifier = VideoMarks.GirdViewCellID
private var AssetGirdThumbnailSize: CGSize?
class AssetGirdVC: UICollectionViewController {
var assetsFetchResults: PHFetchResult<AnyObject>?
var assetCollection: PHAssetCollection?
var imageManager: PHCachingImageManager?
var previousPreheatRect: CGRect?
var taskManager = TaskManager.sharedInstance
var longTapGuesture: UILongPressGestureRecognizer?
deinit {
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupAssetGirdThumbnailSize()
self.setupController()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// 注册通知
NotificationCenter.default.addObserver(self, selector: #selector(downloadFinished), name: VideoMarksConstants.DownloadTaskFinish, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(downloading), name: VideoMarksConstants.DownloadTaskProgress, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(startDownloading), name: VideoMarksConstants.DownloadTaskStart, object: nil)
PHPhotoLibrary.shared().register(self)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// 注销通知
PHPhotoLibrary.shared().unregisterChangeObserver(self)
NotificationCenter.default.removeObserver(self)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
updateCollectionViewLayout(with: size)
}
private func updateCollectionViewLayout(with size: CGSize) {
if let layout = self.collectionView?.collectionViewLayout as? UICollectionViewFlowLayout {
let itemLength = size.width / 4
layout.itemSize = CGSize(width: itemLength, height: itemLength)
layout.invalidateLayout()
}
}
func setupAssetGirdThumbnailSize() {
let scale = UIScreen.main.scale
// 设备最小尺寸来显示Cell 考虑横屏时的情况
let minWidth = min(UIScreen.main.bounds.width, UIScreen.main.bounds.height)
let itemWidth = minWidth / 4
AssetGirdThumbnailSize = CGSize(width: itemWidth * scale, height: itemWidth * scale)
}
func setupController() {
imageManager = PHCachingImageManager()
resetCachedAssets()
self.updateCachedAssets()
if let _ = assetCollection {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addVideo))
}
self.longTapGuesture = UILongPressGestureRecognizer(target: self, action: #selector(userLongPressed(sender:)))
self.collectionView?.addGestureRecognizer(self.longTapGuesture!)
let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
let itemLength = UIScreen.main.bounds.width / 4
flowLayout.itemSize = CGSize(width: itemLength, height: itemLength)
}
// MARK: - Actions
func userLongPressed(sender: UILongPressGestureRecognizer) {
let pressedLocation = sender.location(in: self.collectionView)
if let pressedItemIndexPath = self.collectionView?.indexPathForItem(at: pressedLocation) {
if let asset = self.assetsFetchResults?[pressedItemIndexPath.item] as? PHAsset {
if let pressedView = self.collectionView?.cellForItem(at: pressedItemIndexPath) as? GirdViewCell {
showDeleteVideoActionSheet(atView: pressedView, deleteVideo: asset)
}
}
}
}
func deleteVideo(video: PHAsset) {
// Delete asset from library
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.deleteAssets([video] as NSArray)
}, completionHandler: nil)
}
func showDeleteVideoActionSheet(atView view: UIView, deleteVideo video: PHAsset) {
let alertController = UIAlertController(title: nil, message: NSLocalizedString("Delete Video?", comment: "删除视频?"), preferredStyle: .actionSheet)
alertController.modalPresentationStyle = .popover
if let presenter = alertController.popoverPresentationController {
presenter.sourceView = view
presenter.sourceRect = view.bounds
presenter.permittedArrowDirections = .any
presenter.canOverlapSourceViewRect = true
}
alertController.addAction(UIAlertAction(title: NSLocalizedString("Delete", comment: "删除"), style: .destructive, handler: { (_) in
self.deleteVideo(video: video)
}))
alertController.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "取消"), style: .cancel, handler: nil))
if self.presentedViewController == nil {
present(alertController, animated: true, completion: nil)
}
}
func addVideo(_ sender: UIBarButtonItem) {
let alertController = UIAlertController(title: NSLocalizedString("Enter the URL for the video you want to save.", comment: "输入你想要保存的视频地址"), message: nil, preferredStyle: .alert)
alertController.addTextField { (textField) in
textField.keyboardType = .URL
textField.placeholder = "Video URL"
}
alertController.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "取消"), style: .cancel, handler: nil))
alertController.addAction(UIAlertAction(title: NSLocalizedString("Save", comment: "保存"), style: .default, handler: { [weak self] (action) in
// 添加下载任务
guard let videoUrl = alertController.textFields?.first?.text, let vURL = URL(string: videoUrl) , videoUrl.isEmpty != true else { return }
self?.taskManager.addNewTask(vURL, collectionId: self!.assetCollection!.localIdentifier)
}))
present(alertController, animated: true, completion: nil)
}
func startDownloading(_ note: Notification) {
DispatchQueue.main.async {
self.collectionView?.reloadData()
}
}
func downloadFinished(_ note: Notification) {
DispatchQueue.main.async {
self.collectionView?.reloadData()
}
}
func downloading(_ note: Notification) {
// 下载中
if let progressInfo: [String: AnyObject] = note.object as? [String: AnyObject] {
guard let task = progressInfo["task"] as? DownloadTask else { return }
// 获得对应的Cell
if let taskIdx = self.taskManager.taskList.index(of: task) {
if let cell = collectionView?.cellForItem(at: IndexPath(item: taskIdx, section: 1)) as? DownloadViewCell {
cell.progressLabel.text = "\(Int(task.progress.fractionCompleted * 100)) %"
}
}
}
}
}
// MARK: - UICollectionViewDataSource and Delegate
extension AssetGirdVC {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
var numberOfItems: Int
if section == 0 {
numberOfItems = self.assetsFetchResults?.count ?? 0
} else {
numberOfItems = self.taskManager.taskList.count
}
return numberOfItems
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var collectionViewCell: UICollectionViewCell
if indexPath.section == 0 {
let asset = self.assetsFetchResults![indexPath.item] as! PHAsset
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GirdViewCell", for: indexPath) as! GirdViewCell
cell.representedAssetIdentifier = asset.localIdentifier
self.imageManager?.requestImage(for: asset, targetSize: AssetGirdThumbnailSize!, contentMode: .aspectFill, options: nil, resultHandler: { (image, info) in
if cell.representedAssetIdentifier == asset.localIdentifier {
cell.thumbnail = image
}
})
collectionViewCell = cell
} else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DownloadViewCell", for: indexPath) as! DownloadViewCell
// 设置DownloadCell...
collectionViewCell = cell
}
return collectionViewCell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if (indexPath as NSIndexPath).section == 0 {
let asset = self.assetsFetchResults![(indexPath as NSIndexPath).item] as! PHAsset
let videoRequestOptions = PHVideoRequestOptions()
videoRequestOptions.deliveryMode = .highQualityFormat
self.imageManager?.requestPlayerItem(forVideo: asset, options: videoRequestOptions, resultHandler: { (avplayerItem, info) in
let player = AVPlayer(playerItem: avplayerItem!)
PlayerController.sharedInstance.playVideo(player, inViewController: self)
})
}
}
// MARK: - Asset Caching
func resetCachedAssets() {
imageManager?.stopCachingImagesForAllAssets()
previousPreheatRect = CGRect.zero
}
func updateCachedAssets() {
let isVisible = self.isViewLoaded && self.view.window != nil
guard isVisible else {
return
}
var preheatRect = self.collectionView?.bounds
let preHeight = preheatRect!.height
preheatRect = preheatRect!.insetBy(dx: 0.0, dy: -0.5 * preHeight)
let delta = abs(preheatRect!.midY - self.previousPreheatRect!.midY)
if delta > self.collectionView!.bounds.height / 3.0 {
var addedIndexPaths: [IndexPath] = []
var removedIndexPaths: [IndexPath] = []
self.computeDifferenceBetween(self.previousPreheatRect!, andNewRect: preheatRect!, removedHandler: { (removedRect) in
let indexPaths = self.collectionView!.indexPathsForElementsIn(removedRect)
removedIndexPaths.append(contentsOf: indexPaths)
}, addedHandler: { (addedRect) in
let indexPaths = self.collectionView!.indexPathsForElementsIn(addedRect)
addedIndexPaths.append(contentsOf: indexPaths)
})
let assetsToStartCaching = self.assetsAt(addedIndexPaths)
let assetsToStopCaching = self.assetsAt(removedIndexPaths)
self.imageManager?.stopCachingImages(for: assetsToStopCaching, targetSize: AssetGirdThumbnailSize!, contentMode: .aspectFill, options: nil)
self.imageManager?.startCachingImages(for: assetsToStartCaching, targetSize: AssetGirdThumbnailSize!, contentMode: .aspectFill, options: nil)
self.previousPreheatRect = preheatRect
}
}
func computeDifferenceBetween(_ oldRect: CGRect, andNewRect newRect: CGRect, removedHandler: (_ removedRect: CGRect)-> Void, addedHandler: (_ addedRect: CGRect) -> Void ) {
if oldRect.intersects(newRect) {
let oldMaxY = oldRect.maxY
let oldMinY = oldRect.minY
let newMaxY = newRect.maxY
let newMinY = newRect.minY
if (newMaxY > oldMaxY) {
let rectToAdd = CGRect(x: newRect.origin.x, y: oldMaxY, width: newRect.size.width, height: (newMaxY - oldMaxY))
addedHandler(rectToAdd)
}
if (oldMinY > newMinY) {
let rectToAdd = CGRect(x: newRect.origin.x, y: newMinY, width: newRect.size.width, height: (oldMinY - newMinY))
addedHandler(rectToAdd)
}
if (newMaxY < oldMaxY) {
let rectToRemoved = CGRect(x: newRect.origin.x, y: newMaxY, width: newRect.size.width, height: (oldMaxY - newMaxY))
removedHandler(rectToRemoved)
}
if (oldMinY < newMinY) {
let rectToRemoved = CGRect(x: newRect.origin.x, y: oldMinY, width: newRect.size.width, height: (newMinY - oldMinY))
removedHandler(rectToRemoved)
}
} else {
addedHandler(newRect)
removedHandler(oldRect)
}
}
func assetsAt(_ indexPaths: [IndexPath]) -> [PHAsset] {
guard indexPaths.count > 0 else { return [] }
var assets: [PHAsset] = []
indexPaths.forEach { (idx) in
if (idx as NSIndexPath).section == 0 {
let asset = self.assetsFetchResults![(idx as NSIndexPath).item] as! PHAsset
assets.append(asset)
}
}
return assets
}
}
extension AssetGirdVC: PHPhotoLibraryChangeObserver {
func photoLibraryDidChange(_ changeInstance: PHChange) {
guard self.assetsFetchResults != nil else { return }
if let collectionChanges = changeInstance.changeDetails(for: self.assetsFetchResults! as! PHFetchResult<PHObject>) {
DispatchQueue.main.async(execute: { [weak self] in
self?.assetsFetchResults = collectionChanges.fetchResultAfterChanges as? PHFetchResult<AnyObject>
if !collectionChanges.hasIncrementalChanges || collectionChanges.hasMoves {
self?.collectionView?.reloadData()
} else {
self?.collectionView?.performBatchUpdates({
if let removedIndexes = collectionChanges.removedIndexes , removedIndexes.count > 0 {
self?.collectionView?.deleteItems(at: removedIndexes.indexPathsFromIndexesWith(0))
}
if let insertedIndexes = collectionChanges.insertedIndexes , insertedIndexes.count > 0 {
self?.collectionView?.insertItems(at: insertedIndexes.indexPathsFromIndexesWith(0))
}
if let changedIndexes = collectionChanges.changedIndexes , changedIndexes.count > 0 {
self?.collectionView?.reloadItems(at: changedIndexes.indexPathsFromIndexesWith(0))
}
}, completion:{ success in
if success {
self?.collectionView?.reloadData()
}
})
}
self?.resetCachedAssets()
})
}
}
}
extension AssetGirdVC: URLSessionDelegate {
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
if let completionHandler = appDelegate.backgroundSessionCompletionHandler {
appDelegate.backgroundSessionCompletionHandler = nil
DispatchQueue.main.async(execute: {
completionHandler()
})
}
}
}
}
|
//
// UIDeviceExt.swift
// Dayang
//
// Created by 田向阳 on 2017/12/27.
// Copyright © 2017年 田向阳. All rights reserved.
//
import UIKit
extension UIDevice {
class func dy_deviceAlias() -> String {
let device = UIDevice()
return device.name
}
}
|
import SwiftCheck
import Bow
public class SemigroupLaws<A: Semigroup & Arbitrary & Equatable> {
public static func check() {
associativity()
reduction()
}
private static func associativity() {
property("Associativity") <~ forAll { (a: A, b: A, c: A) in
a.combine(b).combine(c)
==
a.combine(b.combine(c))
}
}
private static func reduction() {
property("Reduction") <~ forAll { (a: A, b: A, c: A) in
A.combineAll(a, b, c)
==
a.combine(b).combine(c)
}
}
}
|
//
// GameViewController.swift
// test
//
// Created by Alex Iakab on 16/01/2019.
// Copyright © 2019 Alex Iakab. All rights reserved.
//
import UIKit
import Alamofire
class GameViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var gameArray = [Game]()
var searchArray = [Game]()
@IBOutlet weak var tableview: UITableView!
@IBOutlet weak var searchbutton: UIButton!
@IBOutlet weak var searchbar: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
tableview.delegate = self
tableview.dataSource = self
Alamofire.request(URL.GameList).responseObject { (response: DataResponse<Games>) in
if let gamearray = response.value{
self.gameArray = gamearray
//self.searchArray = gamearray
self.tableview.reloadData()
}
}
}
@IBAction func searchPressed(_ sender: UIButton) {
searchArray.removeAll()
for item in gameArray{
if item.gTitle.lowercased().contains(searchbar.text!.lowercased()){
searchArray.append(item);
}
}
if searchbar.text == "" {
searchArray.removeAll()
}
tableview.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchArray.count > 0 {
return searchArray.count
}
else{
return gameArray.count
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCell(withIdentifier: "testCell", for: indexPath)
if searchArray.count > 0{
cell.textLabel?.text = searchArray[indexPath.row].gTitle
}
else{
cell.textLabel?.text = gameArray[indexPath.row].gTitle
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if searchArray.count > 0 {
getRequirements(searchArray[indexPath.row].gID)
}
else{
getRequirements(gameArray[indexPath.row].gID)
}
}
func getRequirements(_ gameID : String){
Alamofire.request(URL.GameStats + gameID).responseObject { (response: DataResponse<minreq>) in
if let resp = response.value{
self.alert(title: "", message:"Your build: " + sharedInstance.shared.toBuildString() + ", required = " + resp.cpuIntel + ", " + resp.gpuNvidia + ", " + resp.memory, option:"Aight" )
}
}
}
func alert(title: String, message: String, option: String) {
let alert = UIAlertController(title: title, message: message , preferredStyle: .alert)
let action = UIAlertAction(title: option, style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
}
|
//
// ServiceBase.swift
// florafinder
//
// Created by Andrew Tokeley on 9/01/16.
// Copyright © 2016 Andrew Tokeley . All rights reserved.
//
import Foundation
import CoreData
enum ServiceError: ErrorType {
case DeletionError
case RetrievalError
}
class Service<M: NSManagedObject> {
var coreDataController: CoreDataController
var entityName: NSString
init(controller:CoreDataController, entityName: NSString)
{
self.coreDataController = controller
self.entityName = entityName
}
func add() -> M
{
let newEntity = NSEntityDescription.insertNewObjectForEntityForName(self.entityName as String,inManagedObjectContext: self.coreDataController.managedObjectContext) as! M
return newEntity
}
func getObject(objectId: NSManagedObjectID) -> M?
{
return try? self.coreDataController.managedObjectContext.existingObjectWithID(objectId) as!M
}
func getObjects(predicate: NSPredicate?) -> [M]
{
return getObjects(predicate, sortDescriptors: nil)
}
func getObjects(predicate: NSPredicate?, sortDescriptors: [NSSortDescriptor]?) -> [M]
{
do
{
let request = NSFetchRequest()
let entity = NSEntityDescription.entityForName(self.entityName as String, inManagedObjectContext: self.coreDataController.managedObjectContext)
request.entity = entity
request.predicate = predicate
request.sortDescriptors = sortDescriptors
return try self.coreDataController.managedObjectContext.executeFetchRequest(request) as! [M]
}
catch
{
//log
return [M]()
}
}
/**
Returns all objects of the given type. If none exist and empty array is returned.
*/
func getAll() -> [M]
{
return getObjects(nil, sortDescriptors: nil)
}
func deleteObject(object: M)
{
self.coreDataController.managedObjectContext.deleteObject(object)
}
func deleteAll() -> Int
{
var deleteCount = 0
for object in getObjects(nil)
{
deleteObject(object)
deleteCount += 1
}
return deleteCount
}
func save() throws
{
// somewhat misleading as managed objects aren't saved directly, but as part of a context save
try self.coreDataController.save()
}
} |
//
// Copyright © 2021 Tasuku Tozawa. All rights reserved.
//
import Combine
/// @mockable
public protocol ClipItemListQuery {
var items: CurrentValueSubject<[ClipItem], Error> { get }
}
|
//
// Listing.swift
// ListingsApp
//
// Created by Ijaz on 23/11/2020.
//
import Foundation
struct ListingResponse: Decodable {
let results: [Listing]
//let pagination: Pagination
enum CodingKeys: String, CodingKey {
case results
//case pagination
}
}
/*
struct Pagination: Decodable {
let key: String
enum CodingKeys: String, CodingKey {
case key
}
}*/
struct Listing: Decodable {
let uid: String
let name: String
let price: String
let createdDate: String
let thumbnailsURLs: [String]
let imageURLs: [String]
enum CodingKeys: String, CodingKey {
case uid, name, price
case createdDate = "created_at"
case thumbnailsURLs = "image_urls_thumbnails"
case imageURLs = "image_urls"
}
}
|
//
// Section.swift
// iCare
//
// Created by kalonizator on 23.06.17.
// Copyright © 2017 kalonizator. All rights reserved.
//
import Foundation
import UIKit
struct Section {
var month: String!
var dayOfTheWeek: String!
var numberOfRequests: String!
var requestsText : [String]!
var expanded: Bool!
init(month:String, dayOfTheWeek:String, numberOfRequests:String, requestsText: [String], expanded: Bool) {
self.month = month
self.dayOfTheWeek = dayOfTheWeek
self.numberOfRequests = numberOfRequests
self.requestsText = requestsText
self.expanded = expanded
}
}
|
//
// Notifications.swift
// Vlack
//
// Created by Yuma Antoine Decaux on 11/10/17.
// Copyright © 2017 Yuma Antoine Decaux. All rights reserved.
//
import Foundation
let refreshBoardsNotification = Notification.Name(rawValue: "refreshBoard")
let startTimerNotification = Notification.Name(rawValue: "StartTimer")
let itemCreatedNotification = Notification.Name(rawValue: "createdItem")
let itemDeletedNotification = Notification.Name(rawValue: "deletedItem")
let itemMovedNotification = Notification.Name(rawValue: "movedItem")
let itemUpdatedNotification = Notification.Name(rawValue: "updatedItem")
let actionsUpdatedNotification = Notification.Name(rawValue: "updatedActions")
let audioNotification = Notification.Name(rawValue: "audio")
|
//
// UIWindow.swift
// Animal House
//
// Created by Roy Geagea on 8/29/19.
// Copyright © 2019 Roy Geagea. All rights reserved.
//
import SwiftUI
extension UIWindow {
func setRootView<rootView: View>(rootView: rootView) {
guard let rootViewController = self.rootViewController else { return }
let rootVC = UIHostingController(rootView: rootView)
rootVC.view.frame = rootViewController.view.frame
rootVC.view.layoutIfNeeded()
self.makeKeyAndVisible()
UIView.transition(with: self, duration: 0.5, options: .transitionFlipFromLeft, animations: {
self.rootViewController = rootVC
}, completion: nil)
}
}
|
//
// QuestionarreLineOfWorkView.swift
// CovidAlert
//
// Created by Matthew Garlington on 12/21/20.
//
import SwiftUI
struct QuestionarreLineOfWorkView: View {
@State var isMarked10:Bool = false
@State var isMarked11:Bool = false
@State var isMarked12:Bool = false
var body: some View {
ScrollView{
VStack(spacing: 30) {
Text("What Symptoms do you Currently have? (Check all that Apply) :")
.bold()
.font(.title2)
ZStack(alignment: .leading) {
Spacer()
.frame(width: 400, height: 150)
.background(Color(.init(white: 0.95, alpha: 1)))
.cornerRadius(30)
.shadow(radius: 10)
HStack {
Text("Have you experienced any new gastrointestinal symptoms such as nausea, vomiting, diarrhea, or loss of appetite in the last few days?")
.foregroundColor(.black)
.font(.headline)
.fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
.padding(.horizontal)
Spacer()
Button(action:{
self.isMarked10.toggle()
}) {
Image(systemName: self.isMarked10 ? "checkmark.circle.fill" : "checkmark.circle")
.renderingMode(.original)
.font(.title)
}.padding()
}
}
ZStack(alignment: .leading) {
Spacer()
.frame(width: 400, height: 150)
.background(Color(.init(white: 0.95, alpha: 1)))
.cornerRadius(30)
.shadow(radius: 10)
HStack {
Text("Are you isolating or quarantining because you may have been exposed to a person with COVID-19 or are worried that you may be sick with COVID-19?")
.foregroundColor(.black)
.font(.headline)
.fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
.padding(.horizontal)
Spacer()
Button(action:{
self.isMarked11.toggle()
}) {
Image(systemName: self.isMarked11 ? "checkmark.circle.fill" : "checkmark.circle")
.renderingMode(.original)
.font(.title)
}.padding()
}
}
ZStack(alignment: .leading) {
Spacer()
.frame(width: 400, height: 300)
.background(Color(.init(white: 0.95, alpha: 1)))
.cornerRadius(30)
.shadow(radius: 10)
HStack {
Text("""
Within the past 14 days, have you been in close physical contact (6 feet or closer for a cumulative total of 15 minutes) with:
• Anyone who is known to have laboratory-confirmed COVID-19? OR
• Anyone who has any symptoms consistent with COVID-19?
""")
.foregroundColor(.black)
.font(.headline)
.fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
.padding(.horizontal)
Spacer()
Button(action:{
self.isMarked12.toggle()
}) {
Image(systemName: self.isMarked12 ? "checkmark.circle.fill" : "checkmark.circle")
.renderingMode(.original)
.font(.title)
}.padding()
}
}
}.padding(.horizontal)
VStack {
NavigationLink(
destination: SymptomAnaylsisView(),
label: {
ZStack{
Spacer()
.frame(width: 400, height: 75)
.background(Color.blue)
.cornerRadius(30)
.shadow(radius: 10)
Text("Next")
.foregroundColor(.white)
.bold()
.font(.title2)
}
})
}.padding(.top)
}
}
}
struct QuestionarreLineOfWorkView_Previews: PreviewProvider {
static var previews: some View {
QuestionarreLineOfWorkView()
}
}
|
//
// WelcomeAboardViewController.swift
// gameDealsApp
//
// Created by Deyvidy F.S on 24/06/21.
//
import Foundation
import UIKit
import WelcomeAboard
class WelcomeAboardViewController : UIViewController {
override func loadView() {
super.loadView()
let content = createWAContent()
view = WABaseView(content: content)
}
private func createWAContent() -> WAContent.Base {
let color = UIColor(red:0.90, green:0.22, blue:0.31, alpha:1.00)
let title = WAContent.Title(format: .multiline(welcomeText: "Welcome to"),
text: "WelcomeAboard")
let items = [
WAContent.Card(title: "Receive New Users",
resume: "Tell us about your application, explain the main features and what else you want to tell!",
icon: UIImage(systemName: "person.2.square.stack.fill"),
iconTintColor: color),
WAContent.Card(title: "Highlight Features",
resume: "I'm sure your application contains incredible features. Use this space to give more visibility.",
icon: UIImage(systemName: "text.bubble.fill"),
iconTintColor: color),
WAContent.Card(title: "Notify Bugfixes",
resume: "Nobody likes to receive a bug report. Informing that annoying problem has been fixed is much more nicer.",
icon: UIImage(systemName: "hammer.fill"),
iconTintColor: color)
]
let button = WAContent.Button(text: "Continue", backgroundColor: color) { [weak self] in
self?.dismiss(animated: true)
}
return WAContent.Base(backgroundColor: .white,
title: title,
cards: items,
button: button)
}
}
|
//
// IndexSetTests.swift
// FeinstrukturUtils
//
// Created by Sven A. Schmidt on 03/07/2015.
//
//
import XCTest
import Nimble
class IndexSetTests: XCTestCase {
func test_init_array() {
let i = IndexSet([0,2,4])
let g = i.generate()
expect(g.next()) == 0
expect(g.next()) == 2
expect(g.next()) == 4
expect(g.next()).to(beNil())
}
func test_init_array_duplicates() {
let i = IndexSet([0,1,1,2])
let g = i.generate()
expect(g.next()) == 0
expect(g.next()) == 1
expect(g.next()) == 1
expect(g.next()) == 2
expect(g.next()).to(beNil())
}
func test_init_range() {
let i = IndexSet(2..<5)
let g = i.generate()
expect(g.next()) == 2
expect(g.next()) == 3
expect(g.next()) == 4
expect(g.next()).to(beNil())
}
func test_addIndex() {
var i = IndexSet(2..<5)
i.addIndex(1)
let g = i.generate()
expect(g.next()) == 2
expect(g.next()) == 3
expect(g.next()) == 4
expect(g.next()) == 1
expect(g.next()).to(beNil())
}
}
|
import XCTest
@testable import Voysis
class VoysisTests: XCTestCase {
let textResponse = "{\"type\":\"response\",\"entity\":{\"id\":\"1\",\"locale\":\"en-US\",\"conversationId\":\"1\",\"queryType\":\"text\",\"textQuery\":{\"text\":\"go to my cart\"},\"intent\":\"goToCart\",\"reply\":{\"text\":\"Here's what's in your cart\"},\"entities\":{\"products\":[]},\"_links\":{\"self\":{\"href\":\"/queries/1\"},\"audio\":{\"href\":\"/queries/1/audio\"}},\"_embedded\":{}},\"requestId\":\"0\",\"responseCode\":201,\"responseMessage\":\"Created\"}"
let audioResponse = "{\"type\":\"notification\",\"entity\":{\"id\":\"1\",\"locale\":\"en-US\",\"conversationId\":\"1\",\"queryType\":\"audio\",\"textQuery\":{\"text\":\"test\"},\"audioQuery\":{\"mimeType\":\"audio/pcm;encoding=signed-int;rate=48000;bits=16;channels=1;big-endian=false\"},\"intent\":\"goToCart\",\"reply\":{\"text\":\"test\"},\"hint\":{\"text\":\"test\"},\"_links\":{\"self\":{\"href\":\"\"},\"audio\":{\"href\":\"\"}},\"_embedded\":{}},\"notificationType\":\"query_complete\"}"
let token = "{\"type\":\"response\",\"entity\":{\"token\":\"1\",\"expiresAt\":\"2018-04-17T14:14:06.701Z\"},\"requestId\":\"0\",\"responseCode\":200,\"responseMessage\":\"OK\"}"
let feedback = "{\"type\":\"response\",\"entity\":{},\"requestId\":\"0\",\"responseCode\":200,\"responseMessage\":\"OK\"}"
private let config = DataConfig(url: URL(string: "wss://test.io")!, refreshToken: "12345", isVadEnabled: false)
private var voysis: ServiceImpl!
private var audioRecordManager: AudioRecordManagerMock!
private var client: ClientMock!
private var context: TestContext?
private var tokenManager: TokenManager!
private var refreshToken = "token"
private var callbackMock = CallbackMock()
private var sessionMock = AudioSessionMock()
override func setUp() {
super.setUp()
client = ClientMock()
audioRecordManager = AudioRecordManagerMock()
tokenManager = TokenManager(refreshToken: refreshToken, dispatchQueue: DispatchQueue.main)
let feedbackManager = FeedbackManager(DispatchQueue.main)
voysis = ServiceImpl(client: client,
recorder: audioRecordManager,
dispatchQueue: DispatchQueue.main,
feedbackManager: feedbackManager,
tokenManager: tokenManager,
config: config,
session: sessionMock)
//closure cannot be null but is not required for most tests.
client.dataCallback = { ( data: Data) in
}
}
override func tearDown() {
super.tearDown()
voysis = nil
audioRecordManager = nil
client = nil
}
func testCreateAndFinishRequestWithVad() {
let vadReceived = expectation(description: "vad received")
client.stringEvent.append(token)
client.setupStreamEvent = "{\"type\":\"notification\",\"notificationType\":\"vad_stop\"}"
audioRecordManager.onDataResponse = { (data: Data) in
}
audioRecordManager.stopWithData = true
let callback = { (call: String) in
if (call == "vadReceived") {
vadReceived.fulfill()
}
}
callbackMock.callback = callback
voysis!.startAudioQuery(context: context, callback: callbackMock)
waitForExpectations(timeout: 5, handler: nil)
}
func testSuccessWithSessionShutdown() {
let decodedExpectation = expectation(description: "string decoded correctly")
client.stringEvent.append(token)
client.setupStreamEvent = audioResponse
audioRecordManager.stopWithData = true
let success = { (response: StreamResponse<TestContext, TestEntities>) in
if (response.id == "1") {
decodedExpectation.fulfill()
}
}
callbackMock.success = success
voysis.startAudioQuery(context: context, callback: callbackMock)
XCTAssertEqual(sessionMock.hasShutDown, false)
waitForExpectations(timeout: 5, handler: nil)
XCTAssertEqual(sessionMock.hasShutDown, true)
}
func testSendTextRequest() {
let decodedExpectation = expectation(description: "string decoded correctly")
client.stringEvent.append(token)
client.stringEvent.append(textResponse)
let success = { (response: StreamResponse<TestContext, TestEntities>) in
if (response.id == "1") {
decodedExpectation.fulfill()
}
}
callbackMock.success = success
voysis!.sendTextQuery(text: "show me shoes", context: context, callback: callbackMock)
waitForExpectations(timeout: 5, handler: nil)
}
func testSendTextRequestDecodingFail() {
let failExpectation = expectation(description: "string decoded incorrectly")
client.stringEvent.append(token)
client.stringEvent.append("fail")
let error = { (response: VoysisError) in
switch response {
case .serializationError:
failExpectation.fulfill()
default:
XCTFail("Wrong Error")
}
}
callbackMock.fail = error
voysis!.sendTextQuery(text: "show me shoes", context: context, callback: callbackMock)
waitForExpectations(timeout: 5, handler: nil)
}
func testSuccessFeedbackResponse() {
let successResponse = expectation(description: "success")
tokenManager.token = Token(expiresAt: "2018-04-17T14:14:06.701Z", token: "")
client.stringEvent.append(token)
client.stringEvent.append(feedback)
let feedbackHandler = { (response: Int) in
if response == 200 {
successResponse.fulfill()
}
}
voysis.sendFeedback(queryId: "1", feedback: FeedbackData(), feedbackHandler: feedbackHandler, errorHandler: { (_: VoysisError) in })
waitForExpectations(timeout: 5, handler: nil)
}
func testCreateAndManualFinishRequest() {
let endData = expectation(description: "one bytes sent at end")
let startData = expectation(description: "two bytes sent at end")
audioRecordManager.stopWithData = false
client.stringEvent.append(token)
client.dataCallback = { ( data: Data) in
if data.count == 2 {
startData.fulfill()
} else if data.count == 1 {
endData.fulfill()
}
}
voysis.startAudioQuery(context: context, callback: callbackMock)
voysis.finish()
waitForExpectations(timeout: 5, handler: nil)
}
func testErrorResponse() {
let errorReceived = expectation(description: "error received")
client.error = VoysisError.unknownError("error")
client.stringEvent.append(token)
let error = { (response: VoysisError) in
switch response {
case .unknownError:
errorReceived.fulfill()
default:
XCTFail("Wrong Error")
}
}
callbackMock.fail = error
voysis.startAudioQuery(context: context, callback: callbackMock)
waitForExpectations(timeout: 5, handler: nil)
}
func testStateChanges() {
XCTAssertEqual(voysis.state, State.idle)
client.stringEvent.append(token)
client.setupStreamEvent = "{\"type\":\"notification\",\"notificationType\":\"vad_stop\"}"
audioRecordManager.onDataResponse = { (data: Data) in
}
audioRecordManager.stopWithData = true
let completed = expectation(description: "completed")
let callback = { (call: String) in
if (call == "vadReceived") {
completed.fulfill()
XCTAssertEqual(self.voysis.state, State.processing)
}
}
callbackMock.callback = callback
voysis.startAudioQuery(context: context, callback: callbackMock)
XCTAssertEqual(voysis.state, State.recording)
waitForExpectations(timeout: 5, handler: nil)
}
func testMaxByteLimitOnRequest() {
let completed = expectation(description: "max bytes exceeded. byte(4) sent at end ")
audioRecordManager.data = Data(bytes: [0xFF, 0xD9] as [UInt8], count: 320001)
client.dataCallback = { ( data: Data) in
if (data.count == 1) {
completed.fulfill()
}
}
client.stringEvent.append(token)
voysis.startAudioQuery(context: context, callback: callbackMock)
waitForExpectations(timeout: 5, handler: nil)
}
}
|
//: [Previous](@previous)
import Foundation
func readCSV(in filename: String) -> [String]? {
guard let textsURL = Bundle.main.url(forResource: filename, withExtension: "csv") else {
return nil
}
do {
let fileContent = try String(contentsOf: textsURL, encoding: String.Encoding.utf8)
return fileContent.components(separatedBy: NSCharacterSet.newlines)
} catch {
print("Error parsing csv file named: \(filename)")
}
return nil
}
protocol CommunicationRecord {
var sender: String { get set }
var recipient: String { get set }
var date: Date { get set }
}
extension CommunicationRecord {
static var dateFormatter: DateFormatter {
let df = DateFormatter()
df.dateFormat = "MM-dd-yyyy hh:mm:ss"
return df
}
static func parse(csvRow text: String) -> (String, String, Date, Int?) {
let data = text.split(separator: ",")
let sender = String(data[0])
let recipient = String(data[1])
let date = Self.dateFormatter.date(from: String(data[2])) ?? Date()
var duration: Int? = nil
if let last = data.last, let num = Int(String(last)) {
let num = NSNumber(value: num)
duration = num.intValue
}
return(sender, recipient, date, duration)
}
}
struct PhoneCall: CommunicationRecord {
var sender: String
var recipient: String
var date: Date
var duration: Int
init(_ csvString: String) {
let (sender, recipient, date, duration) = Self.parse(csvRow: csvString)
self.sender = sender
self.recipient = recipient
self.date = date
self.duration = duration ?? 0
}
}
struct TextMessage: CommunicationRecord {
var sender: String
var recipient: String
var date: Date
init(_ csvString: String) {
let (sender, recipient, date, _) = Self.parse(csvRow: csvString)
self.sender = sender
self.recipient = recipient
self.date = date
}
}
/*
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
*/
//: [Next](@next)
var ignoreThese: Set<String> = []
var possibleTelemarketers = [String]()
// for text in text
// cache sender phone # in ignoreThese
// cache receiver phone # in ignoreThese
let texts = readCSV(in: "texts")
if let textData = readCSV(in: "texts") {
for textString in textData {
if textString.isEmpty { continue }
let text = TextMessage(textString)
ignoreThese.insert(text.sender)
ignoreThese.insert(text.recipient)
}
}
if let callData = readCSV(in: "calls") {
// For call in
for callString in callData {
if callString.isEmpty { continue }
let call = PhoneCall(callString)
// cache receiver phone # in ignoreThese
ignoreThese.insert(call.recipient)
}
// for call in calls
for callString in callData {
if callString.isEmpty { continue }
let call = PhoneCall(callString)
// skip if sender phone # in ignoreThese
if ignoreThese.contains(call.sender) { continue }
// append sender phone # to possibleTelemarketers
possibleTelemarketers.append(call.sender)
// ensure number is only added once
ignoreThese.insert(call.sender)
}
}
print("These numbers could be telemarketers:\n\(possibleTelemarketers.joined(separator: "\n"))")
|
//
// ViewController+Occlusions.swift
// PathVisualiser
//
// Created by Max Cobb on 12/12/18.
// Copyright © 2018 Max Cobb. All rights reserved.
//
import ARKit
extension ViewController {
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
if let planeAnchor = anchor as? ARPlaneAnchor, planeAnchor.alignment == .vertical, let geom = ARSCNPlaneGeometry(device: MTLCreateSystemDefaultDevice()!) {
geom.update(from: planeAnchor.geometry)
geom.firstMaterial?.colorBufferWriteMask = .alpha
node.geometry = geom
}
}
func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
if let planeAnchor = anchor as? ARPlaneAnchor, planeAnchor.alignment == .vertical, let geom = node.geometry as? ARSCNPlaneGeometry {
geom.update(from: planeAnchor.geometry)
}
}
}
|
//
// InteractorOutputSpy.swift
// WeatherAppTests
//
// Created by Yaroslav Tutushkin on 09.03.2020.
//
@testable import WeatherApp
final class InteractorOutputSpy<T: Decodable> {
enum Call: Equatable {
case none
case error
case model
}
private(set) var latestCall: Call = .none
}
extension InteractorOutputSpy: InteractorOutput {
func received<T>(model: T) where T : Decodable {
latestCall = .model
}
func received(error: RequestServiceError) {
latestCall = .error
}
}
|
//
// Copyright © 2017 Vlas Voloshin. All rights reserved.
//
import UIKit
/// Enumeration values that determine the current state of an alert in the presenter.
@objc(RALAlertState)
public enum AlertState: Int {
/// The alert is about to be presented.
case willPresent = 0
/// The alert has just been presented.
case didPresent
/// The alert is about to be dismissed. The action that triggered the dismissal will be invoked shortly after.
case willDismiss
/// The alert has been dismissed. The action that triggered the dismissal has already been invoked at this point.
case didDismiss
}
public typealias AlertStateHandler = (UIAlertController, AlertState) -> Void
|
//
// TableViewController.swift
// RXSwiftDemo
//
// Created by mkrq-yh on 2019/8/27.
// Copyright © 2019 mkrq-yh. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
class TableViewController: UIViewController {
@IBOutlet weak var refreshBtn: UIBarButtonItem!
@IBOutlet weak var cancleBtn: UIBarButtonItem!
let disposeBag = DisposeBag()
var tableView:UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//UITableView 和 RXSwift 的基本使用
// self.baseTable()
/*
注意:RxDataSources 是以 section 来做为数据结构的。所以不管我们的 tableView 是单分区还是多分区,在使用 RxDataSources 的过程中,都需要返回一个 section 的数组。
*/
//使用RxDataSources
// self.useRxDataSources()
//使用自定义的Section
// self.customRxDataSources()
//多个分区,使用自带的section
// self.moreSection()
//多个分区,自定义section
self.customMoreSection()
//刷新table
// self.updateTable()
}
//UITableView 和 RXSwift 的基本使用
func baseTable() {
self.tableView = UITableView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height), style: .plain)
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CellId")
self.view.addSubview(self.tableView)
//初始化数据
let items = Observable.just([
"AAAAAAAAA",
"BBBBBBBBB",
"CCCCCCCCC",
"DDDDDDDDD",
"EEEEEEEEE",
"FFFFFFFFF",
])
//设置单元格数据(其实就是对 cellForRowAt 的封装)
items.bind(to: tableView.rx.items) {(tableView,row,element) in
let cell = tableView.dequeueReusableCell(withIdentifier: "CellId")!
cell.textLabel?.text = "\(row):\(element)"
return cell
}
.disposed(by: disposeBag)
//获取选中项的索引
tableView.rx.itemSelected.subscribe(onNext: { indexPath in
print("选中项:\(indexPath.row)")
}).disposed(by: disposeBag)
//获取选中项的内容
tableView.rx.modelSelected(String.self).subscribe(onNext: { item in
print("选中项的标题为:\(item)")
}).disposed(by: disposeBag)
// 打开 cell 的编辑功能
tableView.setEditing(true, animated: true)
//获取被取消选中项的索引
tableView.rx.itemDeselected.subscribe(onNext: { indexPath in
print("取消选中项:\(indexPath.row)")
}).disposed(by: disposeBag)
//获取被取消选中项的内容
tableView.rx.modelDeselected(String.self).subscribe(onNext: { item in
print("获取被取消的标题为:\(item)")
}).disposed(by: disposeBag)
//获取删除项的索引
tableView.rx.itemDeleted.subscribe(onNext: { indexPath in
print("获取删除项的索引:\(indexPath)")
}).disposed(by: disposeBag)
//获取删除项的内容
tableView.rx.modelDeleted(String.self).subscribe(onNext:{ item in
print("获取删除项的内容:\(item)")
}).disposed(by: disposeBag)
//获取移动项的索引
tableView.rx.itemMoved.subscribe(onNext: { sourceIndexPath, destinationIndexPath in
print("移动项原来的indexPath为:\(sourceIndexPath)")
print("移动项现在的indexPath为:\(destinationIndexPath)")
}).disposed(by: disposeBag)
//获取插入项的索引
tableView.rx.itemInserted.subscribe(onNext: { indexPath in
print("插入项的indexPath为:\(indexPath)")
}).disposed(by: disposeBag)
//获取点击的尾部图标的索引
tableView.rx.itemAccessoryButtonTapped.subscribe(onNext: { indexPath in
print("尾部项的indexPath为:\(indexPath)")
}).disposed(by: disposeBag)
//获取选中项的索引
tableView.rx.willDisplayCell.subscribe(onNext: { cell, indexPath in
print("将要显示单元格indexPath为:\(indexPath)")
print("将要显示单元格cell为:\(cell)\n")
}).disposed(by: disposeBag)
}
// 方式一:使用自带的Section
func useRxDataSources() {
self.tableView = UITableView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height), style: .plain)
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CellId")
self.view.addSubview(self.tableView)
//初始化数据
let items = Observable.just([SectionModel(model: "", items: ["苹果","香蕉","橘子","葡萄"])])
//创建数据源
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String,String>>(
configureCell: { dataSource, tableView, indexPath, item in
let cell = tableView.dequeueReusableCell(withIdentifier: "CellId")!
cell.textLabel?.text = "\(indexPath.row):\(item)"
return cell
})
//绑定数据源
items.bind(to: tableView.rx.items(dataSource: dataSource) ).disposed(by: disposeBag)
}
//方式二:使用自定义的Section
func customRxDataSources() {
self.tableView = UITableView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height), style: .plain)
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CellId")
self.view.addSubview(self.tableView!)
let items = Observable.just([MySection(header: "", items: ["UILable的用法","UIText的用法","UIButton的用法"])])
let data = RxTableViewSectionedReloadDataSource<MySection>(
configureCell: { dataSource, tableView, indexPath, item in
let cell = tableView.dequeueReusableCell(withIdentifier: "CellId")!
cell.textLabel?.text = "\(indexPath.row):\(item)"
return cell
})
items.bind(to: tableView.rx.items(dataSource: data)).disposed(by: disposeBag)
}
//多个sections使用自带的Section
func moreSection() {
self.tableView = UITableView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height), style: .plain)
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CellId")
self.view.addSubview(self.tableView)
let items = Observable.just([
SectionModel(model: "手机", items: ["Apple","华为","小米","OPPO","一佳","Vivo","魅族"]),
SectionModel(model: "电脑", items: ["Apple","戴尔","华为","联想","弘基","神州","其他",])
])
let data = RxTableViewSectionedReloadDataSource<SectionModel<String, String>>(
configureCell: { dataSource, tableView, indexPath, item in
let cell = tableView.dequeueReusableCell(withIdentifier: "CellId")!
cell.textLabel?.text = "\(indexPath.row):\(item)"
return cell
})
//设置分区头标题
data.titleForHeaderInSection = { dataSource,index in
return dataSource.sectionModels[index].model
}
items.bind(to: tableView.rx.items(dataSource: data)).disposed(by: disposeBag)
}
//多个sections使用自定义Section
func customMoreSection() {
//创建表格视图
self.tableView = UITableView(frame: self.view.frame, style:.plain)
//创建一个重用的单元格
self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
self.view.addSubview(self.tableView!)
let items = Observable.just([
MySection(header: "手机", items: ["Apple","华为","小米","OPPO","一佳","Vivo","魅族"]),
MySection(header: "电脑", items: ["Apple","戴尔","华为","联想","弘基","神州","其他",])
])
let data = RxTableViewSectionedReloadDataSource<MySection>(
configureCell: {dataSource, tableView, indexPath, item in
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = "\(indexPath.row):\(item)"
return cell
})
data.titleForHeaderInSection = { dataSource,index in
return dataSource.sectionModels[index].header
}
items.bind(to: tableView.rx.items(dataSource: data)).disposed(by: disposeBag)
tableView.rx.itemSelected.subscribe(onNext: { indexpath in
print(indexpath)
}).disposed(by: disposeBag)
}
//刷新table
func updateTable() {
self.tableView = UITableView(frame: self.view.frame, style: .plain)
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CellID")
self.view.addSubview(self.tableView)
//随机的表格数据
let data = refreshBtn.rx.tap.asObservable()
.throttle(1, scheduler: MainScheduler.instance) //在主线程中操作,1秒内值若多次改变,取最后一次
.startWith(())
.flatMapLatest{ self.getRandomResult().takeUntil(self.cancleBtn.rx.tap) }
.share(replay: 1)
//数据源
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String,Int>>(
configureCell: { dataSource, tableView, indexPath, item in
let cell = tableView.dequeueReusableCell(withIdentifier: "CellID")!
cell.textLabel?.text = "\(indexPath.row),\(item)"
return cell
})
data.bind(to: self.tableView.rx.items(dataSource: dataSource)).disposed(by: disposeBag)
}
//获取随机数据
func getRandomResult() -> Observable<[SectionModel<String, Int>]> {
print("正在请求数据......")
let items = (0 ..< 5).map {_ in
Int(arc4random())
}
let observable = Observable.just([SectionModel(model: "S", items: items)])
return observable.delay(2, scheduler: MainScheduler.instance)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
//struct CustomData {
// var anInt: Int
// var aString: String
// var aCGPoint: CGPoint
//}
//自定义Section
struct MySection {
var header: String
var items: [Item]
}
extension MySection : AnimatableSectionModelType {
typealias Item = String
var identity: String {
return header
}
init(original: MySection, items: [Item]) {
self = original
self.items = items
}
}
|
// Builder maket for entities
import UIKit
import Firebase
import SwiftyJSON
class User {
var userLogin: String?
var userPassword: String?
init (dictionary: [String: AnyObject]) {
self.userLogin = dictionary["login"] as? String
self.userPassword = dictionary["pass"] as? String
}
}
class Dish {
var dishName: String
var dishDesc: String
init (dishName: String, dishDesc: String) {
self.dishName = dishName
self.dishDesc = dishDesc
}
init (snapshot: DataSnapshot) {
let json = JSON(snapshot.value ?? "")
self.dishName = json["Description"].stringValue
self.dishDesc = json["Name"].stringValue
}
func saveIntoDatabase() {
let dishRef = Database.database().reference().child("Dish").childByAutoId()
let newDishDict = ["Name" : self.dishName, "Description": self.dishDesc]
dishRef.setValue(newDishDict)
}
}
class Drink {
var drinkName: String
var drinkDesc: String
var drinkCapacity: Double
var drinkCost: Double
var drinkImage: UIImage
init (drinkName: String, drinkDesc: String, drinkCapacity: Double, drinkCost: Double, drinkImage: UIImage) {
self.drinkName = drinkName
self.drinkDesc = drinkDesc
self.drinkCapacity = drinkCapacity
self.drinkCost = drinkCost
self.drinkImage = drinkImage
}
}
class Test: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.