text stringlengths 8 1.32M |
|---|
//
// MembersCoordinator.swift
// Quota
//
// Created by Marcin Włoczko on 24/11/2018.
// Copyright © 2018 Marcin Włoczko. All rights reserved.
//
import UIKit
final class MembersCoordinator: Coordinator {
var rootCoordinator: RootCoordinator?
var navigationController: UINavigationController?
var root: UIViewController?
weak var delegate: TabBarCoordinatorDelegate?
private let builder: MembersBuilder
private let group: Group
init(group: Group, builder: MembersBuilder) {
self.builder = builder
self.group = group
}
func start() {
let membersVC = builder.buildMembersViewController(with: group)
membersVC.viewModel?.delegate = self
navigationController = UINavigationController(rootViewController: membersVC)
root = navigationController
}
}
extension MembersCoordinator: MembersViewModelDelegate {
func closeMembersFlow() {
delegate?.closeTabBar()
}
func membersViewModel(didSelect member: Member) {
let memberDetailVC = builder.buildMemberDetailViewController(with: member,
in: group)
memberDetailVC.viewModel?.delegate = self
navigationController?.pushViewController(memberDetailVC, animated: true)
}
}
extension MembersCoordinator: MemberDetailViewModelDelegate {
func memberDetailViewModelDidRequestCurrencyTable(for member: Member) {
let currencyTableVC = builder.buildCurrencyTableViewController(with: member)
currencyTableVC.viewModel?.delegate = self
navigationController?.pushViewController(currencyTableVC, animated: true)
}
}
extension MembersCoordinator: CurrencyTableViewModelDelegate {
func currencyTableViewModelDidRequestExchange(_ viewModel: CurrencyTabelViewModel, with exchangeRate: ExchangeRate?) {
let exchangeRateVC = builder.buildExchangeRateViewController(with: exchangeRate)
exchangeRateVC.viewModel?.onDissmis = { [weak self] in
self?.navigationController?.popViewController(animated: true)
}
exchangeRateVC.viewModel?.errorDelegate = self
exchangeRateVC.viewModel?.delegate = viewModel
navigationController?.pushViewController(exchangeRateVC, animated: true)
}
}
extension MembersCoordinator: ExchangeRateViewModelErrorDelegate {
func exchangeRateViewModel(didFailWith errorMessage: String) {
UIAlertController.showAlert(withTitle: "", message: errorMessage)
}
}
|
//
// CurrencyRateModel.swift
// MMWallet
//
// Created by Dmitry Muravev on 21.07.2018.
// Copyright © 2018 micromoney. All rights reserved.
//
import Foundation
import RealmSwift
import ObjectMapper
class CurrencyRateModel: Object, Mappable {
@objc dynamic var id = 0
@objc dynamic var currency = ""
@objc dynamic var USD = 0.0
@objc dynamic var createdAt: Date? = nil
override class func primaryKey() -> String? {
return "id"
}
required convenience init?(map: Map) {
self.init()
}
func mapping(map: Map) {
id <- map["id"]
USD <- map["USD"]
currency <- map["currency"]
createdAt <- (map["createdAt"], DateIntTransform())
}
}
|
//
// DataModelProtocol.swift
// SQLiteSample
//
// Created by Seonghun Kim on 27/02/2019.
// Copyright © 2019 Seonghun Kim. All rights reserved.
//
import Foundation
protocol DataModelProtocol {
// MARK:- Properties
var tableName: String { get }
var columns: [Column] { get }
// MARK:- Initialize
init()
init(data: [String: SQLiteRowDataProtocol])
}
enum ColumnType: String {
case text = "TEXT"
case integer = "INTEGER"
case double = "DOUBLE"
case char = "CHAR"
}
struct Column {
var name: String
var type: ColumnType
var row: SQLiteRowDataProtocol
}
|
import Nimble
import Quick
import RxSwift
import SVProgressHUD
@testable import Workshops_Module2
class UIApplication_RxSpec: QuickSpec {
override func spec() {
describe("UIApplication+Rx") {
var showCallCount: Int = 0
var hideCallCount: Int = 0
beforeEach {
showCallCount = 0
hideCallCount = 0
SVProgressHUD_show = { showCallCount += 1 }
SVProgressHUD_dismiss = { hideCallCount += 1 }
}
afterEach {
SVProgressHUD_show = SVProgressHUD.show
SVProgressHUD_dismiss = SVProgressHUD.dismiss
}
describe("progress") {
var progress: PublishSubject<Bool>!
beforeEach {
progress = PublishSubject()
_ = progress
.asDriver(onErrorJustReturn: false)
.drive(UIApplication.shared.rx.progress)
}
afterEach {
progress = nil
}
context("when true is emitted") {
beforeEach {
progress.onNext(true)
progress.onNext(true)
}
it("should call show method") {
expect(showCallCount) == 2
}
}
context("when false is emitted") {
beforeEach {
progress.onNext(false)
progress.onNext(false)
progress.onNext(false)
}
it("should call hide method") {
expect(hideCallCount) == 3
}
}
}
}
}
}
|
//
// Bank.swift
// ExamenAlanSantiago
//
// Created by Alan Santiago on 03/03/20.
// Copyright © 2020 Alan Santiago. All rights reserved.
//
import Foundation
struct BankAPI: Codable {
var bankName: String
var description: String
var age: Int
var url: String
}
|
//
// secondViewController.swift
// videoSimaltaniousPlay
//
// Created by 伊藤走 on 10/31/20.
//
import UIKit
import WebKit
class secondViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
@IBOutlet var videoB: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
displayVideoB()
}
private func displayVideoB(){
videoB .uiDelegate = self
videoB.navigationDelegate = self
if let videoURL:URL = URL(string: "https://www.youtube.com/embed/qOiDlprXF2w?playsinline=1") {
print("videoUrl:\(videoURL)")
let request:URLRequest = URLRequest(url: videoURL)
videoB.load(request)
}
}
}
|
//
// SplashViewController.swift
// Trivia
//
// Created by admin on 18/04/19.
// Copyright © 2019 AcknoTech. All rights reserved.
//
import UIKit
class SplashVC: UIViewController {
// MARK: - Constants -
private let pulselayer = CAShapeLayer()
// MARK: - View Methods -
override func loadView() {
super.loadView()
addSubViews()
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(red: 255/255, green: 0/255, blue: 169/255, alpha: 1)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
startPulse()
}
override var preferredStatusBarStyle: UIStatusBarStyle{
return .lightContent
}
// MARK: - Defined Views -
fileprivate lazy var brandLogo:UIImageView = {
let brandImage = UIImageView()
brandImage.image = UIImage(named: "Splash")
brandImage.layer.cornerRadius = 5
brandImage.clipsToBounds = true
brandImage.translatesAutoresizingMaskIntoConstraints = false
brandImage.contentMode = .scaleAspectFit
return brandImage
}()
fileprivate lazy var brandTitle:UILabel = {
let brandLabel = UILabel()
brandLabel.textColor = .white
brandLabel.text = "Trivia"
brandLabel.font = UIFont(name: "Avenirnext-Heavy", size: 20)
brandLabel.textAlignment = .center
brandLabel.translatesAutoresizingMaskIntoConstraints = false
return brandLabel
}()
// MARK: - custom functions -
private func addSubViews(){
activateLogoConstraints()
activateLabelConstraints()
}
private func activateLogoConstraints(){
view.addSubview(brandLogo)
NSLayoutConstraint.activate([
brandLogo.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0),
brandLogo.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 0),
brandLogo.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.3),
brandLogo.heightAnchor.constraint(equalTo: brandLogo.widthAnchor)
])
}
private func activateLabelConstraints(){
view.addSubview(brandTitle)
NSLayoutConstraint.activate([
brandTitle.topAnchor.constraint(equalTo: brandLogo.bottomAnchor, constant: 20),
brandTitle.leadingAnchor.constraint(equalTo: brandLogo.leadingAnchor, constant: 0),
brandTitle.trailingAnchor.constraint(equalTo: brandLogo.trailingAnchor, constant: 0),
brandTitle.heightAnchor.constraint(equalToConstant: 40)
])
}
private func deactiveConstraints(){
brandLogo.removeFromSuperview()
brandTitle.removeFromSuperview()
}
private func startPulse(){
Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(animation), userInfo: nil, repeats: false)
}
private func createPulse(){
let circlePath = UIBezierPath(arcCenter: .zero, radius: UIScreen.main.bounds.size.height/2 + (view.frame.width/3)/2, startAngle: 0, endAngle: view.frame.size.height/2, clockwise: true)
pulselayer.path = circlePath.cgPath
pulselayer.lineWidth = 10.0
pulselayer.fillColor = UIColor(red: 37/255, green: 42/255, blue: 64/255, alpha: 1).cgColor
pulselayer.strokeColor = UIColor(red: 255/255, green: 0/255, blue: 169/255, alpha: 1).cgColor
pulselayer.lineCap = CAShapeLayerLineCap.square
pulselayer.position = view.center
view.layer.addSublayer(pulselayer)
animate()
}
private func animate(){
let anim = CABasicAnimation(keyPath: "transform.scale")
anim.duration = 0.40
anim.fromValue = 0.0
anim.toValue = 0.9
anim.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
pulselayer.add(anim, forKey: "scale")
}
// MARK: - Selectors -
@objc func animation(){
UIView.animate(withDuration: 0.2, animations: {
self.createPulse()
self.deactiveConstraints()
self.activateLogoConstraints()
self.activateLabelConstraints()
}) { (_) in
Timer.scheduledTimer(timeInterval: 0.8, target: self, selector: #selector(self.rootViewController), userInfo: nil, repeats: false)
}
}
@objc func rootViewController(){
UIApplication.shared.keyWindow?.rootViewController = MainVC()
}
}
|
extension Parser {
public var typeErased: Parser<Input, Void> {
Parser<Input, Void> { input, index in
let result = try self.parse(input, index)
switch result {
case let .success(_, _, nextIndex):
return .success(output: (), input: input, next: nextIndex)
case let .failure(err):
return .failure(err)
}
}
}
public var optional: Parser<Input, Output?> {
(map { $0 }) | Parser.just(nil)
}
public func or(_ other: Parser<Input, Output>) -> Parser<Input, Output> {
Parser { input, index in
let output = try self.parse(input, index)
switch output {
case .failure:
return try other.parse(input, index)
default:
return output
}
}
}
public func rep(_ min: Int, _ max: Int? = nil) -> Parser<Input, [Output]> {
let failure = ParseResult<Input, [Output]>.failure(Errors.expectedAtLeast(count: min))
return Parser<Input, [Output]> { input, index in
var outputs = ContiguousArray<Output>()
var i = index
loop: while max == nil || outputs.count < max! {
switch try self.parse(input, i) {
case let .success(output, _, nextIndex):
outputs.append(output)
i = nextIndex
case .failure:
break loop
}
}
if outputs.count >= min {
return .success(output: Array(outputs), input: input, next: i)
} else {
return failure
}
}
}
public func rep1sep<R2>(sep: Parser<Input, R2>) -> Parser<Input, [Output]> {
(self ~ (sep ~> self).rep(0)).map { head, tail in
var outputs = ContiguousArray<Output>()
outputs += [head]
outputs += tail
return Array(outputs)
}
}
public var positiveLookahead: Parser<Input, Void> {
let failure = ParseResult<Input, Void>.failure(Errors.positiveLookaheadFailed)
return Parser<Input, Void> { input, index in
let r = try self.parse(input, index)
switch r {
case .success: return .success(output: (), input: input, next: index)
case .failure: return failure
}
}
}
public var negativeLookahead: Parser<Input, Void> {
let failure = ParseResult<Input, Void>.failure(Errors.negativeLookaheadFailed)
return Parser<Input, Void> { input, index in
switch try self.parse(input, index) {
case .success:
return failure
case .failure:
return .success(output: (), input: input, next: index)
}
}
}
}
|
//
// PartyNavigationController.swift
// SFParties
//
// Created by Genady Okrain on 4/30/16.
// Copyright © 2016 Okrain. All rights reserved.
//
import UIKit
class PartyNavigationController: UINavigationController {
override func previewActionItems() -> [UIPreviewActionItem] {
let open = UIPreviewAction(title: "Open in Safari", style: .Default) { [weak self] action, previewViewController in
if let vc = self?.viewControllers[0] as? PartyTableViewController {
UIApplication.sharedApplication().openURL(vc.party.url)
}
}
let walk = UIPreviewAction(title: "Walking Directions", style: .Default) { [weak self] action, previewViewController in
if let vc = self?.viewControllers[0] as? PartyTableViewController {
vc.openMaps(action)
}
}
let lyft = UIPreviewAction(title: "Request Lyft Line", style: .Default) { [weak self] action, previewViewController in
if let vc = self?.viewControllers[0] as? PartyTableViewController {
vc.openLyft(action)
}
}
return [open, walk, lyft]
}
}
|
//
// LoginViewController.swift
// Sopt_iOS_1Week_Assignment
//
// Created by 김민희 on 2020/10/13.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var partTextField: UITextField!
@IBOutlet weak var nameTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
setView()
}
@IBAction func LoginDidTab(_ sender: UIButton) {
// "로그인" 버튼 클릭 시 event
// 첫 화면으로 입력받은 값 넘겨주기
if let mainView = self.presentingViewController as? MainViewController {
mainView.part = self.partTextField.text
mainView.name = self.nameTextField.text
}
self.dismiss(animated: true, completion: nil)
}
@IBAction func goSignDidTab(_ sender: UIButton) {
// "회원가입" 버튼 클릭 시 event
guard let dvc = self.storyboard?.instantiateViewController(identifier: "SignViewController") else {
return
}
self.navigationController?.pushViewController(dvc, animated: true)
}
}
extension LoginViewController {
func setView() {
self.navigationItem.title = "Login"
}
}
|
//
// ChannelFullPreviewVC.swift
// Fantasticoh!
//
// Created by MAC on 6/8/17.
// Copyright © 2017 AppInventiv. All rights reserved.
//
import UIKit
class ChannelFullPreviewVC: UIViewController {
//MARK:- @IBOutlet & Propertie's
//MARK:-
@IBOutlet weak var channelImageView: UIImageView!
@IBOutlet weak var nameLbl: UILabel!
@IBOutlet weak var fanCounterLbl: UILabel!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var noDataAvalible: UILabel!
weak var delegate: TabBarDelegate!
weak var allTagVCDelegate: AllTagVCDelegate!
var channelId = ""
var msg = ""
var isFriend = false
var imgArrayObj = [AnyObject]()
var previousNav: UINavigationController!
//MARK:- View Life Cycle
//MARK:-
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.delegate = self
self.collectionView.dataSource = self
self.setChannelDetail()
self.noDataAvalible.isHidden = true
self.hideShowContaint(bool: true)
self.channelImageView.layer.cornerRadius = self.channelImageView.frame.height/2
self.channelImageView.clipsToBounds = true
self.activityIndicator.tintColor = CommonColors.globalRedColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func readMoreAction() {
let vc = self.storyboard?.instantiateViewController(withIdentifier:"ChannelViewFanVC") as! ChannelViewFanVC
vc.channelViewFanVCState = ChannelViewFanVCState.AllTagVCChannelState
if let dele = self.allTagVCDelegate {
vc.allTagVCDelegate = dele
}
if let dele = self.delegate {
vc.delegate = dele
}
vc.channelId = self.channelId
self.navigationController?.pushViewController(vc, animated: true)
}
func hideShowContaint(bool: Bool) {
self.channelImageView.isHidden = bool
self.nameLbl.isHidden = bool
self.fanCounterLbl.isHidden = bool
self.collectionView.isHidden = bool
self.activityIndicator.isHidden = !bool
}
func getChannelDetail() {
let vc = self.storyboard?.instantiateViewController(withIdentifier:"ChannelViewFanVC") as! ChannelViewFanVC
vc.delegate = TABBARDELEGATE
vc.channelViewFanVCState = ChannelViewFanVCState.AllTagVCState
vc.channelId = self.channelId
if let nav = self.previousNav {
nav.pushViewController(vc, animated: true)
}
//self.navigationController?
}
@available(iOS 9.0, *)
override var previewActionItems: [UIPreviewActionItem] {
let action0 = UIPreviewAction(title: "Read More", style: .default, handler: { previewAction, viewController in
self.getChannelDetail()
})
let action1 = UIPreviewAction(title: self.msg, style: .default, handler: { previewAction, viewController in
self.followChannel(channelId: self.channelId, follow: !self.isFriend)
})
let action2 = UIPreviewAction(title: "Cancel", style: .default, handler: { previewAction, viewController in
})
return [action0, action1, action2]
}
}
//MARK:- UICollectionViewDelegate
//MARK:-
extension ChannelFullPreviewVC: UICollectionViewDelegate {
//400
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
return CGSize(width: SCREEN_WIDTH, height: 500-100)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
//set HorizontalDistance
return 0
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
//return self.tagVerticalDistance
return 0
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
}
//MARK:- UICollectionViewDataSource
//MARK:-
extension ChannelFullPreviewVC: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if self.imgArrayObj.count == 0 {
return 1
}
return imgArrayObj.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PreviewVCCollectionViewCell", for: indexPath) as! PreviewVCCollectionViewCell
if self.imgArrayObj.isEmpty {
cell.imgView.image = CONTAINERPLACEHOLDER
} else {
guard let imgUrls = self.imgArrayObj[indexPath.row]["imgURLs"] as? [String : AnyObject] else {
cell.imgView.image = CONTAINERPLACEHOLDER
return cell
}
guard let url = imgUrls["img2x"] as? String else {
cell.imgView.image = CONTAINERPLACEHOLDER
return cell
}
cell.imgView.sd_setImage(with: URL(string: url), placeholderImage: CONTAINERPLACEHOLDER)
}
return cell
}
}
//MARK:- WebService
//MARK:-
extension ChannelFullPreviewVC {
func followChannel(channelId: String, follow: Bool) {
let params: [String: AnyObject] = ["channelID" : channelId as AnyObject, "virtualChannel" : false as AnyObject, "follow": follow as AnyObject]
WebServiceController.follwUnfollowChannel(parameters: params) { (sucess, errorMessage, data) in
if sucess {
if let dele = TABBARDELEGATE {
dele.sideMenuUpdate()
}
print_debug(object: "You click on follow btn.")
if follow {
//Save NSUserDefault
if let list = UserDefaults.getStringArrayVal(key: NSUserDefaultKeys.FRIENDSLIST) as? [String] {
var tempList = list
tempList.append(channelId)
UserDefaults.setStringVal(value: tempList as AnyObject, forKey: NSUserDefaultKeys.FRIENDSLIST)
} else {
let id: [String] = [channelId]
UserDefaults.setStringVal(value: id as AnyObject, forKey: NSUserDefaultKeys.FRIENDSLIST)
}
} else {
//Remove NSUserDefault
if let list = UserDefaults.getStringArrayVal(key: NSUserDefaultKeys.FRIENDSLIST) as? [String], list.count > 0 {
var tempList = list
var index = 0
for tempChannelId in tempList {
if tempChannelId == channelId {
break
}
index = index + 1
}
tempList.remove(at: index)
UserDefaults.setStringVal(value: tempList as AnyObject, forKey: NSUserDefaultKeys.FRIENDSLIST)
}
}
} else {
print_debug(object: errorMessage)
}
}
}
func setChannelDetail() {
if channelId.isEmpty {
self.hideShowContaint(bool: true)
self.noDataAvalible.isHidden = false
return }
WebServiceController.getMiniChannelDetail(channelId: self.channelId) { (success, errorMessage, data) in
if success {
guard let channelData = data else { return }
if let imgUrl = channelData["avatarURLLarge"] as? String {
self.channelImageView.sd_setImage(with: URL(string: imgUrl), placeholderImage: CHANNELLOGOPLACEHOLDER)
}
if let name = channelData["name"] as? String {
self.nameLbl.text = name
} else { self.nameLbl.text = "" }
if let count = channelData["countFollowers"]?.int64Value {
self.fanCounterLbl.text = count > 1 ? "\(count) Fans" : "\(count) Fan"
} else {
self.fanCounterLbl.text = "0 Fan"
}
if let text = self.nameLbl.text, text.isEmpty {
self.noDataAvalible.isHidden = false
self.hideShowContaint(bool: true)
} else {
self.noDataAvalible.isHidden = true
self.hideShowContaint(bool: false)
}
} else {
self.collectionView.reloadData()
self.noDataAvalible.isHidden = false
self.hideShowContaint(bool: true)
print_debug(object: errorMessage)
}
}
}
}
//MARK:- UICollectionViewCell class
//MARK:-
class PreviewVCCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imgView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
self.imgView.contentMode = .center
}
override func prepareForReuse() {
super.prepareForReuse()
self.imgView.contentMode = .center
}
}
|
//
// CollectionVC.swift
// DemoSwift
//
// Created by Megha on 11/01/18.
// Copyright © 2018 com.parmar. All rights reserved.
//
import UIKit
protocol CollectionVCDelegate {
func dictPassing(dictParam:NSDictionary)
}
class CollectionVC: UIViewController {
var delegates: CollectionVCDelegate?
@IBOutlet var collectionMain: UICollectionView!
var arrMutable : [NSString] = [];
override func viewDidLoad() {
super.viewDidLoad()
self.arrMutable = ["A","B","C","D","E"]
let dict = ["name": "Jay","City": "AMD"]
self.delegates?.dictPassing(dictParam: dict as NSDictionary)
let s1 = simple1()
let display = s1.simpleDescription
var d2 = s1.Display()
print("===>",display)
print("===>",d2)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension CollectionVC: UICollectionViewDataSource {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return self.arrMutable.count;
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
let Cell1:collectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as! collectionCell
Cell1.lblName.text = self.arrMutable[indexPath.row] as String
return Cell1
}
}
extension CollectionVC: UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("===\(indexPath.row)")
print("Value ===>\(self.arrMutable[indexPath.row])")
}
}
protocol SampleProtocol {
var simpleDescription : String { get}
mutating func Display()
}
class simple1: SampleProtocol{
var simpleDescription: String = "Welcome Test"
func Display() {
simpleDescription += " hello Testing"
}
}
|
//
// ThemeTVCell.swift
// Kabetsu
//
// Created by Hai Long Danny Thi on 2020/02/16.
// Copyright © 2020 Hai Long Danny Thi. All rights reserved.
//
import UIKit
protocol ThemeTVCellDelegate: class {
func themeSegmentControlValueChanged(_ segmentIndex: Int)
}
class ThemeTVCell: KBTSettingsBaseTVCell {
static let reuseId = "themeTVCell"
struct ImageKey {
static let cellSymbol = "chevron.right.2"
}
override var symbolImageInset: UIEdgeInsets { return UIEdgeInsets(top: 16, left: 40, bottom: 16, right: 0) }
private var themeSegmentControl: UISegmentedControl!
weak var delegate: ThemeTVCellDelegate?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configureCell()
configureThemeSegementControl()
configureThemeSegmentControlConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func set(selectedSegmentIndex index: Int) {
themeSegmentControl.selectedSegmentIndex = index
}
}
// MARK: - ACTIONS
extension ThemeTVCell {
@objc private func themeSegmentControlValueChanged(_ sender: UISegmentedControl) {
let selectedIndex = sender.selectedSegmentIndex
guard let delegate = delegate else {
print(KBTError.delegateNotSet("ThemeTVCell").formatted)
return
}
delegate.themeSegmentControlValueChanged(selectedIndex)
}
}
// MARK: - CONFIGURATION
extension ThemeTVCell {
private func configureCell() {
let image = UIImage(systemName: ImageKey.cellSymbol, withConfiguration: GlobalImageKeys.symbolConfig())
symbolImageView.image = image
}
private func configureThemeSegementControl() {
themeSegmentControl = UISegmentedControl(items: InterfaceStyle.allCases.map { $0.title } )
themeSegmentControl.translatesAutoresizingMaskIntoConstraints = false
themeSegmentControl.addTarget(self, action: #selector(themeSegmentControlValueChanged), for: .valueChanged)
addSubview(themeSegmentControl)
}
}
// MARK: - CONSTRAINTS
extension ThemeTVCell {
private func configureThemeSegmentControlConstraints() {
NSLayoutConstraint.activate([
themeSegmentControl.topAnchor.constraint(equalTo: contentView.safeAreaLayoutGuide.topAnchor, constant: verticalEdgeInset),
themeSegmentControl.bottomAnchor.constraint(equalTo: contentView.safeAreaLayoutGuide.bottomAnchor, constant: -verticalEdgeInset),
themeSegmentControl.leadingAnchor.constraint(equalTo: symbolImageView.trailingAnchor, constant: 8),
themeSegmentControl.trailingAnchor.constraint(equalTo: contentView.safeAreaLayoutGuide.trailingAnchor, constant: -horizontalEdgeInset),
])
}
}
|
//
// Renderer.Types.swift
// SwiftDraw
//
// Created by Simon Whitty on 14/6/17.
// Copyright 2020 Simon Whitty
//
// Distributed under the permissive zlib license
// Get the latest version from here:
//
// https://github.com/swhitty/SwiftDraw
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
import Foundation
struct CGTextTypes: RendererTypes {
typealias Float = LayerTree.Float
typealias Point = String
typealias Size = String
typealias Rect = String
typealias Color = String
typealias Gradient = LayerTree.Gradient
typealias Mask = [Any]
typealias Path = String
typealias Pattern = String
typealias Transform = String
typealias BlendMode = String
typealias FillRule = String
typealias LineCap = String
typealias LineJoin = String
typealias Image = LayerTree.Image
}
struct CGTextProvider: RendererTypeProvider {
typealias Types = CGTextTypes
var supportsTransparencyLayers: Bool = true
func createFloat(from float: LayerTree.Float) -> LayerTree.Float {
return float
}
func createPoint(from point: LayerTree.Point) -> String {
return "CGPoint(x: \(point.x), y: \(point.y))"
}
func createSize(from size: LayerTree.Size) -> String {
return "CGSize(width: \(size.width), height: \(size.height))"
}
func createRect(from rect: LayerTree.Rect) -> String {
return "CGRect(x: \(rect.x), y: \(rect.y), width: \(rect.width), height: \(rect.height))"
}
func createColor(from color: LayerTree.Color) -> String {
switch color {
case .none:
return "CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [0, 0, 0, 0])!"
case let .rgba(r, g, b, a):
return "CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [\(r), \(g), \(b), \(a)])!"
case .gray(white: let w, a: let a):
return "CGColor(colorSpace: CGColorSpaceCreateExtendedGray(), components: [\(w), \(a)])!"
}
}
func createGradient(from gradient: LayerTree.Gradient) -> LayerTree.Gradient {
return gradient
}
func createMask(from contents: [RendererCommand<CGTextTypes>], size: LayerTree.Size) -> [Any] {
return []
}
func createBlendMode(from mode: LayerTree.BlendMode) -> String {
switch mode {
case .normal:
return ".normal"
case .copy:
return ".copy"
case .sourceIn:
return ".sourceIn"
case .destinationIn:
return ".destinationIn"
}
}
func createTransform(from transform: LayerTree.Transform.Matrix) -> String {
"""
let transform1 = CGAffineTransform(
a: \(createFloat(from: transform.a)),
b: \(createFloat(from: transform.b)),
c: \(createFloat(from: transform.c)),
d: \(createFloat(from: transform.d)),
tx: \(createFloat(from: transform.tx)),
ty: \(createFloat(from: transform.ty))
)
"""
}
func createPath(from shape: LayerTree.Shape) -> String {
switch shape {
case .line(let points):
return createLinePath(between: points)
case .rect(let frame, let radii):
return createRectPath(frame: frame, radii: radii)
case .ellipse(let frame):
return createEllipsePath(frame: frame)
case .path(let path):
return createPath(from: path)
case .polygon(let points):
return createPolygonPath(between: points)
}
}
func createLinePath(between points: [LayerTree.Point]) -> String {
"""
let path1 = CGMutablePath()
path1.addLines(between: [
\(points, indent: 2)
])
"""
}
func createRectPath(frame: LayerTree.Rect, radii: LayerTree.Size) -> String {
"""
let path1 = CGPath(
roundedRect: \(createRect(from: frame)),
cornerWidth: \(createFloat(from: radii.width)),
cornerHeight: \(createFloat(from: radii.height)),
transform: nil
)
"""
}
func createPolygonPath(between points: [LayerTree.Point]) -> String {
var lines: [String] = ["let path1 = CGMutablePath()"]
lines.append("path1.addLines(between: [")
for p in points {
lines.append(" \(createPoint(from: p)),")
}
lines.append("])")
lines.append("path1.closeSubpath()")
return lines.joined(separator: "\n")
}
func createEllipsePath(frame: LayerTree.Rect) -> String {
"""
let path1 = CGPath(
ellipseIn: \(createRect(from: frame)),
transform: nil
)
"""
}
func createPath(from path: LayerTree.Path) -> String {
var lines: [String] = ["let path1 = CGMutablePath()"]
for s in path.segments {
switch s {
case .move(let p):
lines.append("path1.move(to: \(createPoint(from: p)))")
case .line(let p):
lines.append("path1.addLine(to: \(createPoint(from: p)))")
case .cubic(let p, let cp1, let cp2):
lines.append("""
path1.addCurve(to: \(createPoint(from: p)),
control1: \(createPoint(from: cp1)),
control2: \(createPoint(from: cp2)))
""")
case .close:
lines.append("path1.closeSubpath()")
}
}
return lines.joined(separator: "\n")
}
func createPattern(from pattern: LayerTree.Pattern, contents: [RendererCommand<Types>]) -> String {
let optimizer = LayerTree.CommandOptimizer<CGTextTypes>(options: [.skipRedundantState, .skipInitialSaveState])
let contents = optimizer.optimizeCommands(contents)
let renderer = CGTextRenderer(name: "pattern", size: pattern.frame.size)
renderer.perform(contents)
let lines = renderer.lines
.map { " \($0)" }
.joined(separator: "\n")
return """
let patternDraw1: CGPatternDrawPatternCallback = { _, ctx in
\(lines)
}
var patternCallback1 = CGPatternCallbacks(version: 0, drawPattern: patternDraw1, releaseInfo: nil)
let pattern1 = CGPattern(
info: nil,
bounds: \(createRect(from: pattern.frame)),
matrix: .identity,
xStep: \(pattern.frame.width),
yStep: \(pattern.frame.height),
tiling: .constantSpacing,
isColored: true,
callbacks: &patternCallback1
)!
"""
}
func createPath(from subPaths: [String]) -> String {
return "subpaths"
}
func createPath(from text: String, at origin: LayerTree.Point, with attributes: LayerTree.TextAttributes) -> String? {
return nil
}
func createFillRule(from rule: LayerTree.FillRule) -> String {
switch rule {
case .nonzero:
return ".winding"
case .evenodd:
return ".evenOdd"
}
}
func createLineCap(from cap: LayerTree.LineCap) -> String {
switch cap {
case .butt:
return ".butt"
case .round:
return ".round"
case .square:
return ".square"
}
}
func createLineJoin(from join: LayerTree.LineJoin) -> String {
switch join {
case .bevel:
return ".bevel"
case .round:
return ".round"
case .miter:
return ".miter"
}
}
func createImage(from image: LayerTree.Image) -> LayerTree.Image? {
return image
}
func getBounds(from shape: LayerTree.Shape) -> LayerTree.Rect {
return CGProvider().getBounds(from: shape)
}
}
public final class CGTextRenderer: Renderer {
typealias Types = CGTextTypes
private let name: String
private let size: LayerTree.Size
init(name: String, size: LayerTree.Size) {
self.name = name
self.size = size
}
private(set) var lines = [String]()
private var patternLines = [String]()
private var colorSpaces: Set<ColorSpace> = []
private var colors: [String: String] = [:]
private var paths: [String: String] = [:]
private var transforms: [String: String] = [:]
private var gradients: [LayerTree.Gradient: String] = [:]
private var patterns: [String: String] = [:]
enum ColorSpace: String, Hashable {
case rgb
case gray
init?(for color: String) {
if color.contains("CGColorSpaceCreateExtendedGray()") {
self = .gray
} else if color.contains("CGColorSpaceCreateDeviceRGB()") {
self = .rgb
} else {
return nil
}
}
}
func createOrGetColorSpace(for color: String) -> ColorSpace {
guard let space = ColorSpace(for: color) else {
fatalError("not a support color")
}
if !colorSpaces.contains(space) {
switch space {
case .gray:
lines.append("let gray = CGColorSpace(name: CGColorSpace.extendedGray)!")
colorSpaces.insert(.gray)
case .rgb:
lines.append("let rgb = CGColorSpaceCreateDeviceRGB()")
colorSpaces.insert(.rgb)
}
}
return space
}
func updateColor(_ color: String) -> String {
let space = createOrGetColorSpace(for: color)
switch space {
case .gray:
return color.replacingOccurrences(of: "CGColorSpaceCreateExtendedGray()", with: "gray")
case .rgb:
return color.replacingOccurrences(of: "CGColorSpaceCreateDeviceRGB()", with: "rgb")
}
}
func createOrGetColor(_ color: String) -> String {
let color = updateColor(color)
if let identifier = colors[color] {
return identifier
}
let identifier = "color\(colors.count + 1)"
colors[color] = identifier
lines.append("let \(identifier) = \(color)")
return identifier
}
func createOrGetColor(_ color: LayerTree.Color) -> String {
switch color {
case .none:
return createOrGetColor("CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [0, 0, 0, 0])!")
case let .rgba(r, g, b, a):
return createOrGetColor("CGColor(colorSpace: CGColorSpaceCreateDeviceRGB(), components: [\(r), \(g), \(b), \(a)])!")
case .gray(white: let w, a: let a):
return createOrGetColor("CGColor(colorSpace: CGColorSpaceCreateExtendedGray(), components: [\(w), \(a)])!")
}
}
func createOrGetPath(_ path: String) -> String {
if let identifier = paths[path] {
return identifier
}
let idx = paths.count
let identifier = "path".makeIdentifier(idx)
paths[path] = identifier
let newPath = path
.replacingOccurrences(of: "path1", with: identifier)
.split(separator: "\n")
.map(String.init)
lines.append(contentsOf: newPath)
return identifier
}
func createOrGetTransform(_ transform: String) -> String {
if let identifier = transforms[transform] {
return identifier
}
let idx = transforms.count
let identifier = "transform".makeIdentifier(idx)
transforms[transform] = identifier
let newTransform = transform
.replacingOccurrences(of: "transform1", with: identifier)
.split(separator: "\n")
.map(String.init)
lines.append(contentsOf: newTransform)
return identifier
}
func createOrGetGradient(_ gradient: LayerTree.Gradient) -> String {
if let identifier = gradients[gradient] {
return identifier
}
let idx = gradients.count
let identifier = "gradient".makeIdentifier(idx)
gradients[gradient] = identifier
let colorTxt = gradient.stops
.map { createOrGetColor($0.color) }
.joined(separator: ", ")
let pointsTxt = gradient.stops
.map { String($0.offset) }
.joined(separator: ", ")
let space = createOrGetColorSpace(for: "CGColorSpaceCreateDeviceRGB()")
let locationsIdentifier = "locations".makeIdentifier(idx)
let code = """
var \(locationsIdentifier): [CGFloat] = [\(pointsTxt)]
let \(identifier) = CGGradient(
colorsSpace: \(space.rawValue),
colors: [\(colorTxt)] as CFArray,
locations: &\(locationsIdentifier)
)!
""".split(separator: "\n").map(String.init)
lines.append(contentsOf: code)
return identifier
}
func createOrGetPattern(_ pattern: String) -> String {
if let identifier = patterns[pattern] {
return identifier
}
let idx = patterns.count
let identifier = "pattern".makeIdentifier(idx)
let draw = "patternDraw".makeIdentifier(idx)
let callback = "patternCallback".makeIdentifier(idx)
patterns[pattern] = identifier
let newPattern = pattern
.replacingOccurrences(of: "pattern1", with: identifier)
.replacingOccurrences(of: "patternDraw1", with: draw)
.replacingOccurrences(of: "patternCallback1", with: callback)
.split(separator: "\n")
.map(String.init)
patternLines.append(contentsOf: newPattern)
return identifier
}
func pushState() {
lines.append("ctx.saveGState()")
}
func popState() {
lines.append("ctx.restoreGState()")
}
func pushTransparencyLayer() {
lines.append("ctx.beginTransparencyLayer(auxiliaryInfo: nil)")
}
func popTransparencyLayer() {
lines.append("ctx.endTransparencyLayer()")
}
func concatenate(transform: String) {
let identifier = createOrGetTransform(transform)
lines.append("ctx.concatenate(\(identifier))")
}
func translate(tx: LayerTree.Float, ty: LayerTree.Float) {
lines.append("ctx.translateBy(x: \(tx), y: \(ty))")
}
func rotate(angle: LayerTree.Float) {
lines.append("ctx.rotate(by: \(angle))")
}
func scale(sx: LayerTree.Float, sy: LayerTree.Float) {
lines.append("ctx.scaleBy(x: \(sx), y: \(sy))")
}
func setFill(color: String) {
let identifier = createOrGetColor(color)
lines.append("ctx.setFillColor(\(identifier))")
}
func setFill(pattern: String) {
let identifier = createOrGetPattern(pattern)
let alpha = identifier.replacingOccurrences(of: "pattern", with: "patternAlpha")
lines.append("ctx.setFillColorSpace(CGColorSpace(patternBaseSpace: nil)!)")
lines.append("var \(alpha) : CGFloat = 1.0")
lines.append("ctx.setFillPattern(\(identifier), colorComponents: &\(alpha))")
}
func setStroke(color: String) {
let identifier = createOrGetColor(color)
lines.append("ctx.setStrokeColor(\(identifier))")
}
func setLine(width: LayerTree.Float) {
lines.append("ctx.setLineWidth(\(width))")
}
func setLine(cap: String) {
lines.append("ctx.setLineCap(\(cap))")
}
func setLine(join: String) {
lines.append("ctx.setLineJoin(\(join))")
}
func setLine(miterLimit: LayerTree.Float) {
lines.append("ctx.setMiterLimit(\(miterLimit))")
}
func setClip(path: String) {
let identifier = createOrGetPath(path)
lines.append("ctx.addPath(\(identifier))")
lines.append("ctx.clip()")
}
func setClip(mask: [Any], frame: String) {
lines.append("ctx.clip(to: \(frame), mask: \(mask))")
}
func setAlpha(_ alpha: LayerTree.Float) {
lines.append("ctx.setAlpha(\(alpha))")
}
func setBlend(mode: String) {
lines.append("ctx.setBlendMode(\(mode))")
}
func stroke(path: String) {
let identifier = createOrGetPath(path)
lines.append("ctx.addPath(\(identifier))")
lines.append("ctx.strokePath()")
}
func fill(path: String, rule: String) {
let identifier = createOrGetPath(path)
lines.append("ctx.addPath(\(identifier))")
lines.append("ctx.fillPath(using: \(rule))")
}
func draw(image: LayerTree.Image) {
lines.append("ctx.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height)")
}
func draw(gradient: LayerTree.Gradient, from start: String, to end: String) {
let identifier = createOrGetGradient(gradient)
lines.append("""
ctx.drawLinearGradient(\(identifier),
start: \(start),
end: \(end),
options: [.drawsAfterEndLocation, .drawsBeforeStartLocation])
""")
}
func makeText() -> String {
var template = """
extension UIImage {
static func \(name)() -> UIImage {
let f = UIGraphicsImageRendererFormat.default()
f.opaque = false
f.preferredRange = .standard
return UIGraphicsImageRenderer(size: CGSize(width: \(size.width), height: \(size.height)), format: f).image {
drawSVG(in: $0.cgContext)
}
}
private static func drawSVG(in ctx: CGContext) {
"""
let indent = String(repeating: " ", count: 4)
let patternLines = self.patternLines.map { "\(indent)\($0)" }
let lines = self.lines.map { "\(indent)\($0)" }
let allLines = patternLines + lines
template.append(allLines.joined(separator: "\n"))
template.append("\n }\n}")
return template
}
}
extension String.StringInterpolation {
mutating func appendInterpolation(_ points: [LayerTree.Point], indent: Int) {
let indentation = String(repeating: " ", count: indent)
let provider = CGTextProvider()
let elements = points
.map { "\(indentation)\(provider.createPoint(from: $0))" }
.joined(separator: ",\n")
appendLiteral(elements)
}
}
private extension String {
func makeIdentifier(_ index: Int) -> String {
guard index > 0 else {
return self
}
return "\(self)\(index)"
}
}
|
//
// Created by Anton Heestand on 2021-02-04.
//
#if swift(>=5.5)
import SwiftUI
import RenderKit
import PixelColor
@available(iOS 14.0, *)
public struct CirclePX: PXView {
@Environment(\.pxObjectExtractor) var pxObjectExtractor: PXObjectExtractor
let radius: CGFloat
public init(radius: CGFloat) {
print("PX Circle Init", radius)
self.radius = radius
}
public func makeView(context: Context) -> PIXView {
print("PX Circle Make")
let object: PXObject = context.coordinator
let pixView: PIXView = object.pix.pixView
pxObjectExtractor.object = object
return pixView
}
public func animate(object: PXObject, transaction: Transaction) {
let pix: CirclePIX = object.pix as! CirclePIX
if !transaction.disablesAnimations,
let animation: Animation = transaction.animation {
print("PX Circle Animate", radius)
PXHelper.animate(animation: animation, timer: &object.timer) { fraction in
PXHelper.motion(pxKeyPath: \.radius, pixKeyPath: \.radius, px: self, pix: pix, at: fraction)
}
} else {
print("PX Circle Animate Direct", radius)
pix.radius = radius
}
}
public func updateView(_ pixView: PIXView, context: Context) {
print("PX Circle Update")
let object: PXObject = context.coordinator
animate(object: object, transaction: context.transaction)
}
public func makeCoordinator() -> PXObject {
PXObject(pix: CirclePIX(at: .square(1000)))
}
}
#endif
|
//
// Account+CoreDataProperties.swift
// Free Bank
//
// Created by Sasha Zontova on 4/6/21.
//
//
import Foundation
import CoreData
extension Account {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Account> {
return NSFetchRequest<Account>(entityName: "Account")
}
@NSManaged public var balance: Int64
@NSManaged public var id: String?
@NSManaged public var bank: Bank?
@NSManaged public var cards: NSSet?
@NSManaged public var company: Organization?
@NSManaged public var credit: Credit?
@NSManaged public var deposit: Deposit?
@NSManaged public var owner: Individual?
@NSManaged public var transactions: NSSet?
}
// MARK: Generated accessors for cards
extension Account {
@objc(addCardsObject:)
@NSManaged public func addToCards(_ value: Card)
@objc(removeCardsObject:)
@NSManaged public func removeFromCards(_ value: Card)
@objc(addCards:)
@NSManaged public func addToCards(_ values: NSSet)
@objc(removeCards:)
@NSManaged public func removeFromCards(_ values: NSSet)
}
// MARK: Generated accessors for transactions
extension Account {
@objc(addTransactionsObject:)
@NSManaged public func addToTransactions(_ value: Transaction)
@objc(removeTransactionsObject:)
@NSManaged public func removeFromTransactions(_ value: Transaction)
@objc(addTransactions:)
@NSManaged public func addToTransactions(_ values: NSSet)
@objc(removeTransactions:)
@NSManaged public func removeFromTransactions(_ values: NSSet)
}
extension Account: Identifiable {}
|
//
// Datasource.swift
// Wendys
//
// Created by Ty Schultz on 3/2/17.
// Copyright © 2017 Ty Schultz. All rights reserved.
//
import UIKit
import Alamofire
import RealmSwift
import Kanna
import AlamofireImage
import RxSwift
class Datasource: NSObject {
func pullData(downloaded : BehaviorSubject<Bool>) {
Alamofire.request("https://github.com/TySchultz/Zelda/blob/master/README.md").responseString { response in
print("\(response.result.isSuccess)")
if let html = response.result.value {
self.parseHTML(html: html, downloaded: downloaded)
}
}
}
func parseHTML(html: String, downloaded : BehaviorSubject<Bool>) -> Void {
if let doc = HTML(html: html, encoding: .utf8) {
let realm = try! Realm()
var count = 0
var collections = 0
let collectionNames = ["An Amazing","Golden Retriever", "Named Zelda"]
let list = List<Photo>()
for link in doc.xpath("//a[contains(@href, '/TySchultz/Zelda/blob/master/images/')]") {
guard let href = link["href"] else { return }
let title = link["href"]?.replacingOccurrences(of: "/TySchultz/Zelda/blob/master/images/", with: "").replacingOccurrences(of: ".jpg?raw=true", with: "")
let pictureURL = "https://github.com/" + href
let newPhoto = Photo(value: [title, pictureURL])
list.append(newPhoto)
if count >= 2 {
let newCollection = Collection(value: [collectionNames[collections],
list])
try! realm.write {
realm.add(newCollection, update: true)
}
collections += 1
list.removeAll()
count = 0
}else{
count += 1
}
try! realm.write {
realm.add(newPhoto, update: true)
}
}
downloaded.onNext(true)
}
}
func downloadImage(pictureURL : String, pictureSubject : BehaviorSubject<UIImage>) {
Alamofire.request(pictureURL).responseImage { response in
if let downloadedImage = response.result.value {
print("image downloaded: \(downloadedImage)")
pictureSubject.onNext(downloadedImage)
}
}
}
}
|
/*
XCTestManifests.swift
Copyright (c) 2016, 2017 Stephen Whittle All rights reserved.
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
import XCTest
import ISFLibrary
import NanoMessage
let payload = Message(value: "This above all...to thine own self be true.")
public var pauseTime = TimeInterval(milliseconds: 200)
public var pauseCount: UInt32 = 0
func pauseForBind() {
usleep(pauseTime)
pauseCount += 1
}
#if os(Linux)
public let allTests = [
testCase(NanoMsgTests.allTests),
testCase(VersionTests.allTests),
testCase(SenderReceiverTests.allTests),
testCase(SocketOptionTests.allTests),
testCase(EndPointTests.allTests),
testCase(PipelineProtocolFamilyTests.allTests),
testCase(PairProtocolFamilyTests.allTests),
testCase(RequestReplyProtocolFamilyTests.allTests),
testCase(PublishSubscribeProtocolFamilyTests.allTests),
testCase(SurveyProtocolFamilyTests.allTests),
testCase(BusProtocolFamilyTests.allTests),
testCase(PollSocketTests.allTests),
testCase(SocketStatisticTests.allTests),
testCase(MessageSizeTests.allTests),
testCase(MessageSpeedTests.allTests),
testCase(BindToSocketTests.allTests),
testCase(LoopBackTests.allTests),
testCase(TerminateTests.allTests)
]
#endif
|
//
// DetailViewController.swift
// Flicks
//
// Created by Portia Sharma on 9/17/17.
// Copyright © 2017 Portia Sharma. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
var movieSelected : NSDictionary!
@IBOutlet weak var detailScrollView: UIScrollView!
@IBOutlet weak var posterImageView: UIImageView!
@IBOutlet weak var infoView: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var overviewLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
detailScrollView.contentSize = CGSize(width: detailScrollView.frame.size.width, height: infoView.frame.origin.y + infoView.frame.size.height)
// Do any additional setup after loading the view.
if let title = movieSelected?["title"] {
titleLabel.text = title as? String
}
else{
print("no title")
}
if let overview = movieSelected?["overview"] {
overviewLabel.text = (overview as! String)
overviewLabel.sizeToFit()
}
else{
print("no overview")
}
if let posterPath = movieSelected?["poster_path"] as? String {
let posterUrl = URL(string: "https://image.tmdb.org/t/p/w500" + posterPath)
//cell.posterImageView.image = UIImage(named: "photo")
posterImageView.setImageWith(posterUrl!)
}
else{
print("no poster")
}
}
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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// PopUpViewController.swift
// PopupDemo
//
// Created by Jon Eikholm on 01/05/2020.
// Copyright © 2020 Jon Eikholm. All rights reserved.
//
import UIKit
class PopUpViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
var parentVC:ViewController? // parent viewController, so we can pass the text entered.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func saveBtnPressed(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
if let txt = textField.text {
parentVC?.handleReturnFromPopup(txt: txt) //
print("in popup \(txt)")
}
}
}
|
//
// GolbexError.swift
// GolbexSwift iOS
//
// Created by Nikolay Dolgopolov on 12/11/2018.
//
import Foundation
public class GolbexError:Codable{
public var code = 0
public var msg = ""
}
|
//
// Employee.swift
// PMI
//
// Created by João Victor Batista on 13/03/20.
// Copyright © 2020 João Victor Batista. All rights reserved.
//
import Foundation
class Employee {
var name: String
init(name: String) {
self.name = name
}
}
|
/*
* Copyright (c) 2020 Elastos Foundation
*
* 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
class IDTransactionInfo: DIDTransaction {
private var _transactionId: String
private var _timestamp: Date
private var _request: IDChainRequest
init(_ transactionId: String, _ timestamp: Date, _ request: IDChainRequest) {
self._transactionId = transactionId;
self._timestamp = timestamp;
self._request = request;
}
/// Get did.
/// - Returns: The handle of did.
public func getDid() -> DID {
return request.did!
}
/// Get transaction id.
/// - Returns: The handle of transaction id.
public func getTransactionId() -> String {
return self.transactionId
}
/// Get time stamp.
/// - Returns: The handle time stamp.
public func getTimestamp() -> Date {
return self.timestamp
}
/// Get IDChain request operation.
/// - Returns: The handle of operation.
public func getOperation() -> IDChainRequestOperation {
return request.operation
}
/// Get DID Document.
/// - Returns: The handle of DID Document.
public func getDocument() -> DIDDocument {
return request.document!
}
var transactionId: String {
return self._transactionId
}
var timestamp: Date {
return self._timestamp
}
var did: DID? {
return self._request.did
}
var operation: IDChainRequestOperation {
return self._request.operation
}
var payload: String {
return self._request.toJson(false)
}
var request: IDChainRequest {
return self._request
}
class func fromJson(_ node: JsonNode) throws -> IDTransactionInfo {
let error = { (des: String) -> DIDError in
return DIDError.didResolveError(des)
}
let serializer = JsonSerializer(node)
var options: JsonSerializer.Options
options = JsonSerializer.Options()
.withHint("transaction id")
.withError(error)
let transactionId = try serializer.getString(Constants.TXID, options)
options = JsonSerializer.Options()
.withHint("transaction timestamp")
.withError(error)
let timestamp = try serializer.getDate(Constants.TIMESTAMP, options)
let subNode = node.get(forKey: Constants.OPERATION)
guard let _ = subNode else {
throw DIDError.didResolveError("missing ID operation")
}
let request = try IDChainRequest.fromJson(subNode!)
return IDTransactionInfo(transactionId, timestamp, request)
}
func toJson(_ generator: JsonGenerator) {
generator.writeStartObject()
generator.writeStringField(Constants.TXID, self.transactionId)
generator.writeStringField(Constants.TIMESTAMP, self.timestamp.description)
generator.writeFieldName(Constants.OPERATION)
self._request.toJson(generator, false)
generator.writeEndObject()
}
}
|
//
// Image.swift
// VideoMarks
//
// Created by nevercry on 6/10/16.
// Copyright © 2016 nevercry. All rights reserved.
//
import Foundation
import CoreData
class Image: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
}
|
import Foundation
enum CharacterFilterOption {
case name(String)
case status(CharacterStatus)
case species(String)
}
|
//
// Phantom.swift
// GISHelperKit
//
// Created by 游宗諭 on 2019/12/11.
// Copyright © 2019 ytyubox. All rights reserved.
//
import Foundation
/// limiting string to type safe
/// ```swift
/// enum TFDate {}
/// typealias DateString = PhamtomString<TFDate>
/// ```
///
public struct PhantomString<T>: Hashable, CustomStringConvertible {
public var value: String
public init(_ value: String) {
self.value = value
}
public init(stringLiteral value: String) {
self.value = value
}
public var description: String { value}
}
extension PhantomString: Decodable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
value = try container.decode(String.self)
}
}
@propertyWrapper
public
struct Phantom<Phantomed, Value> {
public var projectedValue: PhantomType<Phantomed, Value>
public var wrappedValue: Value {projectedValue.value}
public init(wrappedValue: Value) {
self.projectedValue = .init(wrappedValue)
}
}
extension Phantom: Equatable where Value: Equatable {
}
extension Phantom: Hashable where Value: Hashable & CustomStringConvertible {
}
@dynamicMemberLookup
public struct PhantomType<Phantom, Value> {
public var value: Value
public init(_ value: Value) {
self.value = value
}
public
subscript<T>(
dynamicMember keyPath: WritableKeyPath<Value, T>
) -> T {
get { value[keyPath: keyPath] }
set { value[keyPath: keyPath] = newValue}
}
}
extension PhantomType: Equatable where Value: Equatable {
}
extension PhantomType: Hashable, CustomStringConvertible where Value: Hashable & CustomStringConvertible {
public var description: String {value.description}
}
extension PhantomType: Codable where Value: Codable {
}
|
//
// ResetNickNameViewController.swift
// OBD
//
// Created by 苏沫离 on 2017/5/12.
// Copyright © 2017年 苏沫离. All rights reserved.
//
import UIKit
class ResetNickNameViewController: UIViewController {
@IBOutlet weak var textFiled: UITextField!
private let httpManager:LoginHttpManager = LoginHttpManager.init()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.edgesForExtendedLayout = UIRectEdge.init(rawValue: 0)
self.navigationItem.title = "修改昵称"
let leftItem = LeftBackItem.init(target: self, selector: #selector(leftItemClick))
self.navigationItem.leftBarButtonItem = leftItem
let rightItem = UIBarButtonItem.init(title: "保存", style: .done, target: self, action: #selector(rightItemClick))
self.navigationItem.rightBarButtonItem = rightItem
let account:AccountInfo = AccountInfo.standard()
textFiled.text = account.nickname
}
@objc func leftItemClick()
{
self.navigationController?.popViewController(animated: true)
}
@objc func rightItemClick()
{
let account:AccountInfo = AccountInfo.standard()
let nickName = textFiled.text!
let dict:NSDictionary = ["user_id":account.userId,"birthday":account.birthday,"nickname":nickName,"sex":account.sex,"minename":account.realName,"headimg":account.headimg]
self.httpManager.updatePersonalInfoParameterDict(dict as! [AnyHashable : Any], successBlock: {[weak self] (string:String?) in
account.nickname = nickName
account.store()
self?.navigationController?.popViewController(animated: true)
}) { (error:Error?) in
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
textFiled.resignFirstResponder()
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
textFiled.resignFirstResponder()
}
}
|
//
// File.swift
// Bookcase
//
// Created by jungwooram on 2020-05-02.
// Copyright © 2020 jungwooram. All rights reserved.
//
import UIKit
class SpinnerCell: UITableViewCell {
static let reuseIdentifier = "SpinnerCell"
static let height = CGFloat(60.0)
private let spinner = UIActivityIndicatorView()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configureContents()
autoLayout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configureContents() {
spinner.translatesAutoresizingMaskIntoConstraints = false
self.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: UIScreen.main.bounds.width)
contentView.backgroundColor = .clear
contentView.addSubview(spinner)
}
private func autoLayout() {
NSLayoutConstraint.activate([
spinner.centerXAnchor.constraint(equalTo: centerXAnchor),
spinner.centerYAnchor.constraint(equalTo: centerYAnchor),
])
}
func startSpin(_ isLoading: Bool) {
isLoading ? spinner.startAnimating() : spinner.stopAnimating()
}
}
|
//
// Created by Jasmin Suljic on 01/09/2020.
//
import Foundation
public protocol SavedPaymentMethod {
var type: String { get }
var data: Dictionary<String, String>{ get }
}
extension SavedPaymentMethod {
public func toJSON() -> Dictionary<String, Any> {
return [
"type": type,
"data": data
]
}
}
|
//
// FiltersViewController.swift
// GetGoingClass
//
// Created by shaunyan on 2019-02-04.
// Copyright © 2019 SMU. All rights reserved.
//
import UIKit
import Foundation
class FiltersViewController: UIViewController {
var delegate: FiltersViewControllerDelegate?
// MARK: - IBOutlets
@IBOutlet weak var radiusSlider: UISlider!
@IBOutlet weak var isOpenNow: UISwitch!
@IBOutlet weak var rankByLabel: UILabel!
@IBOutlet weak var pickerView: UIPickerView!
@IBOutlet weak var rankBySelectedLabel: UILabel!
@IBOutlet weak var toolBar: UIToolbar!
// MARK: - Properties
var rankByDictionary: [String] = ["prominence", "distance"]
var selected: String {
return UserDefaults.standard.string(forKey: "selected") ?? ""
}
// MARK: - View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
pickerView.isHidden = true
toolBar.isHidden = true
pickerView.delegate = self
pickerView.dataSource = self
rankByLabel.isUserInteractionEnabled = true
if let row = rankByDictionary.index(of:selected) {
pickerView.selectRow(row, inComponent: 0, animated: false)
}
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(rankByLabelTapped))
tapGestureRecognizer.numberOfTapsRequired = 1
rankByLabel.addGestureRecognizer(tapGestureRecognizer)
rankBySelectedLabel.text = rankByDictionary.first
let radiusValue = UserDefaults.standard.object(forKey: "radiusValue")
radiusSlider.value = radiusValue as? Float ?? Float(Constants.defaultRadius)
let rankbyText = UserDefaults.standard.object(forKey: "rankbyText")
rankBySelectedLabel.text = rankbyText as? String ?? Constants.defaultRankby
let opennow = UserDefaults.standard.object(forKey: "opennow")
isOpenNow.isOn = opennow as? Bool ?? Constants.defaultOpennow
pickerView.isUserInteractionEnabled = true
}
@IBAction func resetClick(_ sender: UIButton) {
radiusSlider.value = Float(Constants.defaultRadius)
rankBySelectedLabel.text = Constants.defaultRankby
isOpenNow.isOn = Constants.defaultOpennow
UserDefaults.standard.removeObject(forKey: "radiusValue")
UserDefaults.standard.removeObject(forKey: "rankbyText")
UserDefaults.standard.removeObject(forKey: "opennow")
}
@IBAction func saveClick(_ sender: UIBarButtonItem) {
UserDefaults.standard.set(radiusSlider.value,forKey: "radiusValue")
UserDefaults.standard.set(rankBySelectedLabel.text, forKey:
"rankbyText")
UserDefaults.standard.set(rankBySelectedLabel.text, forKey: "selected")
UserDefaults.standard.set(isOpenNow.isOn, forKey:"opennow")
}
// MARK: - IBActions
@objc func rankByLabelTapped() {
print("label was tapped")
pickerView.isHidden = !pickerView.isHidden
toolBar.isHidden = !toolBar.isHidden
}
@IBAction func doneClick(_ sender: UIBarButtonItem) {
print("done was tapped")
pickerView.isHidden = true
toolBar.isHidden = true
}
@IBAction func closeButtonAction(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
@IBAction func radiusSliderChangedValue(_ sender: UISlider) {
print("slider value changed to \(sender.value) int \(Int(sender.value))")
}
@IBAction func switchValueChanged(_ sender: UISwitch) {
print("switch value was changed to \(sender.isOn)")
}
/*
// 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.
}
*/
override func viewWillDisappear(_ animated: Bool) {
delegate?.filterResponse(raduis: radiusSlider.value, rankby: rankBySelectedLabel.text ?? Constants.defaultRankby, opennow: isOpenNow.isOn)
}
}
extension FiltersViewController: UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return rankByDictionary.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return rankByDictionary[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
rankBySelectedLabel.text = rankByDictionary[row]
}
}
|
//
// moneyListTableViewController.swift
// recipe
//
// Created by Kyoseung on 8/9/14.
// Copyright (c) 2014 devfun. All rights reserved.
//
import UIKit
class moneyListTableViewController: UITableViewController, addMoneyViewControllerDelegate {
// var dbManager: CMoneySqliteManager = CMoneySqliteManager()
var ANum = [Int32]()
var AStrLabel = [String]()
var AStrDate = [String]()
var AMoney = [Int32]()
var pocketNum = -1
func endPopAction(controller: addMoneyViewController, pocketNum: Int) {
self.tableInit(pocketNum)
}
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()
var swipeLeft = UISwipeGestureRecognizer(target: self, action: "respondToSwipeGesture:")
swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
self.view.addGestureRecognizer(swipeLeft)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return self.ANum.count
}
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell = tableView.dequeueReusableCellWithIdentifier("moneyTable") as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: .Default, reuseIdentifier: "moneyTable")
}
cell!.textLabel.text = "\(self.pocketNum), \(self.ANum[indexPath.row]), \(self.AStrLabel[indexPath.row]), \(self.AStrDate[indexPath.row]), \(self.AMoney[indexPath.row])"
return cell
}
func tableInit(inputPocketNum: Int) {
self.pocketNum = inputPocketNum
var aTotal = dbManager.selectAtMoney(self.pocketNum)
ANum = aTotal.num
AStrLabel = aTotal.strLabel
AStrDate = aTotal.strDate
AMoney = aTotal.money
self.tableView.reloadData()
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView!, moveRowAtIndexPath fromIndexPath: NSIndexPath!, toIndexPath: NSIndexPath!) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView!, canMoveRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
if segue!.identifier == "addMoneySegue" {
var nextView = segue.destinationViewController as addMoneyViewController
nextView.pocketNum = self.pocketNum
nextView.delegate = self
}
}
func respondToSwipeGesture(gesture: UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.Right:
println("Right")
case UISwipeGestureRecognizerDirection.Left:
println("Left")
performSegueWithIdentifier("addMoneySegue", sender: self)
case UISwipeGestureRecognizerDirection.Up:
println("Up")
case UISwipeGestureRecognizerDirection.Down:
println("Down")
default:
break
}
}
}
}
|
//
// FloatingButton.swift
// iExpense
//
// Created by Tino on 22/4/21.
//
import SwiftUI
struct FloatingButton: View {
let action: () -> Void
var body: some View {
VStack {
Spacer()
HStack {
Spacer()
Button(action: action) {
buttonImage
}
}
}
}
var buttonImage: some View {
Image(systemName: "plus")
.font(.largeTitle)
.foregroundColor(.white)
.frame(width: 80, height: 80)
.background(Color("red"))
.clipShape(Circle())
.shadow(radius: 10)
}
}
struct FloatingButton_Previews: PreviewProvider {
static var previews: some View {
FloatingButton() {}
}
}
|
//
// DIctionary+Extension.swift
// ZLHJHelpAPP
//
// Created by 周希财 on 2019/12/31.
// Copyright © 2019 VIC. All rights reserved.
//
import Foundation
import UIKit
extension Dictionary {
static func delLabelNameForKey(changeDic: [String:Any]) -> [String:Any]{
if changeDic.isEmpty {return changeDic}
var resultDic:[String:Any] = [:]
for str in changeDic.keys {
let value = changeDic[str] as Any
let key:String = str.contains(".") ? str.components(separatedBy: ".").first! : str
resultDic.updateValue(value, forKey: key )
}
return resultDic
}
}
extension NSDictionary {
//检查key是否存在
func objectForCheckedKey(key:AnyObject)-> (AnyObject){
let object = self.object(forKey: key)
if object == nil {
return "" as (AnyObject)
}
return object as (AnyObject)
}
func stringForCheckedKey(key:String)-> (AnyObject){
let object = self.object(forKey: key)
if object is String {
return object as (AnyObject)
}
if object is NSNumber{
return object as (AnyObject)
}
return "" as (AnyObject)
}
}
|
//
// MyViewController.swift
// HelloWorld
//
// Created by d on 2015/07/13.
// Copyright (c) 2015年 d. All rights reserved.
//
import UIKit
class MyViewController : UIViewController {
@IBOutlet weak var textField : UITextField?
@IBOutlet weak var label : UILabel?
var string : String?
override func viewDidLoad() {
self.textField?.clearButtonMode = UITextFieldViewMode.WhileEditing
self.label?.text = self.textField?.placeholder
}
func updateString() {
self.string = self.textField?.text
self.label?.text = self.string
}
func textFieldShouldReturn(theTextField : UITextField) -> Bool {
if theTextField == self.textField {
self.textField?.resignFirstResponder()
self.updateString()
}
return true
}
override func touchesBegan(touches : Set<NSObject>, withEvent event : UIEvent) {
self.textField?.resignFirstResponder()
self.textField?.text = self.string
super.touchesBegan(touches as Set<NSObject>, withEvent:event)
}
} |
// ==========================================================
// meef: A Modern ZMachine Interpreter
// https://github.com/nkirby/meef
// ==========================================================
import Foundation
public class ZObjectTable {
private let propertyDefaultsStorage: ZDataSlice
weak var game: ZGame?
let defaultsStartAddress: Int
let objectStartAddress: Int
private(set) var endAddress: Int = .max
private(set) var objects = [ZObject]()
private let zcodeVersion: ZVersion
init(data: ZData, header: ZHeader, parserInfo: ZParserInfo) {
self.zcodeVersion = header.zcodeVersion
let defaultsOffset: Int
if header.zcodeVersion.isAtleast(version: .v4) {
fatalError()
} else {
defaultsOffset = parserInfo.objectPropertyDefaultsSize * 2
self.propertyDefaultsStorage = data[0..<defaultsOffset]
}
self.defaultsStartAddress = Int(header.objectTableAddress)
self.objectStartAddress = Int(header.objectTableAddress) + defaultsOffset
}
func setupObjects() {
guard let game = self.game else {
fatalError()
}
if self.zcodeVersion.isAtleast(version: .v4) {
fatalError()
} else {
self.parseV1(startAddress: self.objectStartAddress, game: game)
}
}
private func parseV1(startAddress: Int, game: ZGame) {
var address = startAddress
while address < self.endAddress {
let obj = game.makeObject(at: address)
let addr = Int(obj.propertyAddress)
if addr < self.endAddress {
self.endAddress = addr
}
self.objects.append(obj)
address += game.parserInfo.objectTableEntrySize
}
}
}
|
//
// File.swift
// PopUpCorn
//
// Created by Elias Paulino on 08/06/19.
// Copyright © 2019 Elias Paulino. All rights reserved.
//
import Foundation
protocol MovieDetailCoordinatorDelegate: AnyObject {
func movieReminderWasRemoved(movie: DetailableMovie)
}
|
//
// ClientModel.swift
// SimpleProjects
//
// Created by Kenneth Cluff on 3/14/19.
// Copyright © 2019 Kenneth Cluff. All rights reserved.
//
import Foundation
import CoreData
import CloudKit
struct ClientModel {
// MARK: - Standard items
static var owningZone: CKRecordZone? = Core.shared.cloud.customZone
let recordType = "Client"
let id: String
var isLocalDeleted: Bool = false
var isDirty: Bool = false
var lastUpdated: Date = Date()
var recordName: String
var changeTag: String = ""
var updatedBy: CKRecord.ID? = Core.shared.cloud.currentUserRecordID
// MARK: - Object critical values
var clientName: String
var isActive: Bool = false
init(_ name: String, _ newID: String = Core.getIDString() ) {
clientName = name
id = newID
recordName = id
}
mutating func editName(_ newName: String) {
clientName = newName
lastUpdated = Date()
isDirty = true
}
mutating func setActive(_ isActive: Bool) {
self.isActive = isActive
lastUpdated = Date()
isDirty = true
}
}
extension ClientModel: CloudKitObject {
static func initFrom(_ record: CKRecord) -> CloudKitObject? {
guard let recordName = record[.recordName] as? String,
let clientName = record[.clientName] as? String else { return nil }
var retValue = ClientModel(clientName, recordName)
retValue.setCloudMetaTags(record)
return retValue
}
mutating func updateFromCloud(_ record: CKRecord) {
setCloudMetaTags(record)
guard let clientName = record[.clientName] as? String else { return }
editName(clientName)
}
func managedObjectRepresentation() -> NSManagedObject {
let retValue = Client(context: Core.shared.data.viewContext)
retValue.name = clientName
retValue.id = id
retValue.isLocalDeleted = isLocalDeleted
return retValue
}
}
extension ClientModel: CoreDataObject {
func ckRecordRepresentation() -> CKRecord {
let retValue = CKRecord(recordType: recordType, recordID: cloudKitRecordID)
retValue[.clientName] = clientName
return retValue
}
static func initFromStore(_ record: NSManagedObject) -> ModelObject? {
guard let clientObject = record as? Client,
let clientName = clientObject.name,
let clientID = clientObject.id else { return nil }
let retValue = ClientModel(clientName, clientID)
return retValue
}
mutating func updateFromStore(_ record: NSManagedObject) {
guard let client = record as? Client,
let clientName = client.name else { return }
editName(clientName)
}
}
fileprivate enum ClientKeys: String {
case recordName
case lastUpdated
case changeTag
case clientName
}
fileprivate extension CKRecord {
subscript(key: ClientKeys) -> Any? {
get {
return self[key.rawValue]
}
set {
self[key.rawValue] = newValue as? CKRecordValue
}
}
}
|
//
// BaseAPI.swift
// VechicleTracker
//
// Created by vineeth on 6/13/18.
// Copyright © 2018 vineeth. All rights reserved.
//
import UIKit
@objcMembers
class BaseMappableObject: NSObject {
func toDictionary() -> [String:AnyObject] {
var dictionary = [String:AnyObject]()
let mirrored_object = Mirror(reflecting: self)
dictionary = getParamsAsDictionaryFrom(mirrored_object: mirrored_object)!
return dictionary
}
func toMultiPartDictionary() -> [String:AnyObject] {
var dictionary = [String:AnyObject]()
let mirrored_object = Mirror(reflecting: self)
dictionary = getParamsAsMultipartDictionaryFrom(mirrored_object: mirrored_object)!
return dictionary
}
func getParamsAsDictionaryFrom(mirrored_object: Mirror) -> [String: AnyObject]? {
var dictionary = [String:AnyObject]()
for child in mirrored_object.children {
if let key = child.label {
if (self.value(forKey: key) != nil) {
if (self.value(forKey: key)! as AnyObject) is BaseMappableObject {
dictionary[key] = (self.value(forKey: key)! as! BaseMappableObject).toDictionary() as AnyObject?
}else if (self.value(forKey: key)! as AnyObject) is NSArray {
if ((self.value(forKey: key)! as AnyObject) as! NSArray).count > 0 {
if (self.value(forKey: key) as! NSArray)[0] is BaseMappableObject {
let objArray = (self.value(forKey: key)! as! [BaseMappableObject])
var dictArray : [[String:AnyObject]] = []
for obj in objArray {
do {
let jsonData = try JSONSerialization.data(withJSONObject: obj.toDictionary() as NSDictionary, options: .prettyPrinted)
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
if let dictFromJSON = decoded as? [String:AnyObject] {
dictArray.append(dictFromJSON)
}
} catch {
print(error.localizedDescription)
}
}
do {
let jsonData = try JSONSerialization.data(withJSONObject: dictArray, options: .prettyPrinted)
let stringData = String.init(data: jsonData, encoding: .utf8)
dictionary[key] = stringData as AnyObject?
} catch {
print(error.localizedDescription)
}
}else {
dictionary[key] = self.value(forKey: key)! as AnyObject?
}
}
else {
dictionary[key] = self.value(forKey: key)! as AnyObject?
}
}else if self.value(forKey: key)! is [String: AnyObject] {
do {
let jsonData = try JSONSerialization.data(withJSONObject: self.value(forKey: key)!, options: .prettyPrinted)
let stringData = String.init(data: jsonData, encoding: .utf8)
dictionary[key] = stringData as AnyObject?
} catch {
print(error.localizedDescription)
}
}else{
dictionary[key] = self.value(forKey: key)! as AnyObject?
}
}
}
}
if let parent = mirrored_object.superclassMirror{
let temporaryDictionary = getParamsAsDictionaryFrom(mirrored_object: parent)!
for (key, value) in temporaryDictionary {
if dictionary[key] == nil {
dictionary[key] = value
}
}
}
return dictionary
}
func getParamsAsMultipartDictionaryFrom(mirrored_object: Mirror) -> [String: AnyObject]? {
var dictionary = [String:AnyObject]()
for child in mirrored_object.children {
if let key = child.label {
if (self.value(forKey: key) != nil) {
if (self.value(forKey: key)! as AnyObject) is BaseMappableObject {
dictionary = dictionary.union(dictionary: (self.value(forKey: key)! as! BaseMappableObject).toMultiPartDictionary())
}else{
dictionary[key] = self.value(forKey: key)! as AnyObject?
}
}
}
}
if let parent = mirrored_object.superclassMirror{
let temporaryDictionary = getParamsAsMultipartDictionaryFrom(mirrored_object: parent)!
for (key, value) in temporaryDictionary {
if dictionary[key] == nil {
dictionary[key] = value
}
}
}
return dictionary
}
}
|
//
// File.swift
// Tooli
//
// Created by Impero IT on 11/08/17.
// Copyright © 2017 impero. All rights reserved.
//
import Foundation
import UIKit
import ObjectMapper
class GetSignUp1: NSObject, Mappable {
var Status = 0
var Message = ""
var Result : Results1 = Results1()
override init()
{
}
required init?(map: Map){
Status <- map["Status"]
Message <- map["Message"]
Result <- map["Result"]
}
func mapping(map: Map) {
Status <- map["Status"]
Message <- map["Message"]
Result <- map["Result"]
}
}
class Results1: NSObject, Mappable {
var CertificateID = 0
var ProfileImageLink = ""
var IsPhonePublic = false
var DateOfBirth = ""
var PhoneNumber = ""
var Website = ""
var IsEmailPublic = false
var MobileNumber = ""
var IsMobilePublic = false
var CompanyEmailAddress = ""
var CompanyName = ""
var Description = ""
override init()
{
}
required init?(map: Map){
ProfileImageLink <- map["ProfileImageLink"]
IsPhonePublic <- map["IsPhonePublic"]
DateOfBirth <- map["DateOfBirth"]
PhoneNumber <- map["PhoneNumber"]
Website <- map["Website"]
IsEmailPublic <- map["IsEmailPublic"]
MobileNumber <- map["MobileNumber"]
IsMobilePublic <- map["IsMobilePublic"]
CompanyEmailAddress <- map["CompanyEmailAddress"]
CompanyName <- map["CompanyName"]
Description <- map["Description"]
}
func mapping(map: Map) {
ProfileImageLink <- map["ProfileImageLink"]
IsPhonePublic <- map["IsPhonePublic"]
DateOfBirth <- map["DateOfBirth"]
PhoneNumber <- map["PhoneNumber"]
Website <- map["Website"]
IsEmailPublic <- map["IsEmailPublic"]
MobileNumber <- map["MobileNumber"]
IsMobilePublic <- map["IsMobilePublic"]
CompanyEmailAddress <- map["CompanyEmailAddress"]
CompanyName <- map["CompanyName"]
Description <- map["Description"]
}
}
|
//
// NotificationBanner.swift
// DeliveryApp
//
// Created by abhisheksingh03 on 15/07/19.
// Copyright © 2019 abhisheksingh03. All rights reserved.
//
import Foundation
import NotificationBannerSwift
// MARK: NotificationBanner
func showBannerWith(title: String? = nil, subtitle: String?, style: BannerStyle = BannerStyle.danger) {
let banner = GrowingNotificationBanner(title: title, subtitle: subtitle, style: style)
banner.show()
}
|
//
// PageViewController.swift
// berkeley-mobile
//
// Created by Eashan Mathur on 10/17/20.
// Copyright © 2020 ASUC OCTO. All rights reserved.
//
import UIKit
class PageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
var pages = [UIViewController]()
var pageColors = [UIColor]()
private let pageControl : UIPageControl = {
let pageControl = UIPageControl()
return pageControl
}()
var currentIndex: Int {
guard let vc = viewControllers?.first else { return 0 }
return pages.firstIndex(of: vc) ?? 0
}
let closeButton: UIButton = {
let button = UIButton()
button.titleLabel?.font = Font.medium(18)
button.setTitle("X", for: .normal)
button.setTitleColor(.gray, for: .normal)
button.addTarget(self, action: #selector(close(_:)), for: .touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
self.dataSource = self
self.delegate = self
configurePageControl()
configureButtons()
}
override func viewDidLayoutSubviews() {
pageControl.subviews.forEach {
$0.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
}
}
func configureButtons() {
view.addSubview(closeButton)
closeButton.widthAnchor.constraint(equalToConstant: 50).isActive = true
closeButton.heightAnchor.constraint(equalToConstant: 30).isActive = true
closeButton.translatesAutoresizingMaskIntoConstraints = false
closeButton.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 8).isActive = true
closeButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16).isActive = true
}
@objc func close(_: UIButton) {
self.dismiss(animated: true, completion: nil)
}
func moveToNextPage() {
if currentIndex != pages.count - 1 {
setViewControllers([pages[currentIndex + 1]], direction: .forward, animated: true, completion: nil)
}
pageControl.currentPage += 1
pageControl.pageIndicatorTintColor = pageColors[pageControl.currentPage]
}
func configurePageControl() {
let initialPage = 0
pageColors = [Color.StudyPact.Onboarding.pink, Color.StudyPact.Onboarding.yellow, Color.StudyPact.Onboarding.blue]
let page1 = StudyPactOnboardingViewController(stepText: "Sign Up", themeColor: pageColors[0], stepNumber: 1, screenshotImage: UIImage(named: "OnboardingScreenshot1")!, blobImage: UIImage(named: "OnboardingBlob1")!, descriptionText: "Sign up by tapping the Sign In button on the new study tab of the Berkeley Mobile home screen to authenticate your berkeley.edu Gmail account.", pageViewController: self, boldedStrings: ["Sign In", "study tab"])
let page2 = StudyPactOnboardingViewController(stepText: "Create a Preference", themeColor: pageColors[1], stepNumber: 2, screenshotImage: UIImage(named: "OnboardingScreenshot2")!, blobImage: UIImage(named: "OnboardingBlob2")!, descriptionText: "Create a study preference by filling out your class details, preferred method of study, and number of members.", pageViewController: self)
let page3 = StudyPactOnboardingViewController(stepText: "Get Matched!", themeColor: pageColors[2], stepNumber: 3, screenshotImage: UIImage(named: "OnboardingScreenshot3")!, blobImage: UIImage(named: "OnboardingBlob3")!, descriptionText: "Once you create a preference, your group will be marked as pending. Check back frequently to see if you’ve been matched with a group!", pageViewController: self, boldedStrings: ["pending"], getStarted: true)
// add the individual viewControllers to the pageViewController
self.pages.append(page1)
self.pages.append(page2)
self.pages.append(page3)
setViewControllers([pages[initialPage]], direction: .forward, animated: true, completion: nil)
// pageControl
self.pageControl.currentPageIndicatorTintColor = UIColor.black
self.pageControl.pageIndicatorTintColor = UIColor.lightGray
self.pageControl.numberOfPages = self.pages.count
self.pageControl.currentPage = initialPage
self.pageControl.pageIndicatorTintColor = pageColors[pageControl.currentPage]
self.view.addSubview(self.pageControl)
self.pageControl.translatesAutoresizingMaskIntoConstraints = false
self.pageControl.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -30).isActive = true
self.pageControl.widthAnchor.constraint(equalToConstant: 140).isActive = true
self.pageControl.heightAnchor.constraint(equalToConstant: 20).isActive = true
self.pageControl.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
self.pageControl.isUserInteractionEnabled = false
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = self.pages.firstIndex(of: viewController), viewControllerIndex != 0 else { return nil }
return self.pages[viewControllerIndex - 1]
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = self.pages.firstIndex(of: viewController), viewControllerIndex < self.pages.count - 1 else { return nil }
// go to next page in array
return self.pages[viewControllerIndex + 1]
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if let viewControllers = pageViewController.viewControllers {
if let viewControllerIndex = self.pages.firstIndex(of: viewControllers[0]) {
pageControl.currentPage = viewControllerIndex
pageControl.pageIndicatorTintColor = pageColors[pageControl.currentPage]
}
}
}
}
|
//
// ListViewController.swift
// ShuffleSongs
//
// Created by Gilson Gil on 22/03/19.
// Copyright (c) 2019 Gilson Gil. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
protocol ListDisplayLogic: class {
func displayLoading()
func displayList(viewModel: List.TracksList.ViewModel)
}
final class ListViewController: UIViewController {
var interactor: ListBusinessLogic?
var listView: ListViewLogic?
var displayedTracks: [List.DisplayedTrack]?
// MARK: - Object lifecycle
init() {
super.init(nibName: nil, bundle: nil)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
// MARK: - Setup
private func setup() {
let viewController = self
let interactor = ListInteractor()
let presenter = ListPresenter()
viewController.interactor = interactor
interactor.presenter = presenter
presenter.viewController = viewController
title = String.List.title
}
// MARK: - View lifecycle
override func loadView() {
let listView = ListView()
listView.viewInteractions = self
self.listView = listView
self.view = listView
}
override func viewDidLoad() {
super.viewDidLoad()
setupTableView()
setupNavigationItem()
fetchList()
}
// MARK: - Table View
private func setupTableView() {
listView?.tableView.register(ListTrackCell.self, forCellReuseIdentifier: ListTrackCell.reuseIdentifier)
listView?.tableView.dataSource = self
}
// MARK: - Navigation Item
private func setupNavigationItem() {
if let rightBarButtonItems = listView?.rightBarButtonItems {
navigationItem.rightBarButtonItems = rightBarButtonItems
}
}
// MARK: - Fetch List
func fetchList() {
let request = List.TracksList.Request()
interactor?.fetchList(request: request)
displayLoading()
}
}
// MARK: - Display Logic
extension ListViewController: ListDisplayLogic {
func displayLoading() {
DispatchQueue.main.async {
self.listView?.tableView.isHidden = true
self.listView?.activityIndicator.startAnimating()
}
}
func displayList(viewModel: List.TracksList.ViewModel) {
DispatchQueue.main.async {
self.displayedTracks = viewModel.list
self.listView?.tableView.isHidden = false
self.listView?.tableView.reloadData()
self.listView?.activityIndicator.stopAnimating()
}
}
}
// MARK: - UITableView DataSource
extension ListViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return displayedTracks?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ListTrackCell.reuseIdentifier, for: indexPath)
if let trackCell = cell as? ListTrackCell, let displayedTrack = displayedTracks?[indexPath.row] {
trackCell.update(track: displayedTrack)
}
return cell
}
}
// MARK: - ListViewInteractions
extension ListViewController: ListViewInteractions {
func didTapShuffle(at view: ListView) {
interactor?.shuffle()
}
}
|
//
// ContentViewController.swift
// Hospital
//
// Created by Nick Baidikoff on 01.05.16.
// Copyright © 2016 KPI. All rights reserved.
//
import UIKit
class ContentViewController: UIViewController {
var menuDelegate: BurgerMenuEnter!
}
|
// URLExtensionsTests.swift - Copyright 2022 SwifterSwift
@testable import SwifterSwift
import XCTest
#if canImport(Foundation)
import Foundation
final class URLExtensionsTests: XCTestCase {
let params = ["foo": "bar"]
let queryUrl = URL(string: "https://www.google.com?q=swifter%20swift&steve=jobs&empty")!
let queryUrlWithParams = URL(string: "https://www.google.com?q=swifter%20swift&steve=jobs&empty&foo=bar")!
func testQueryParameters() {
guard let parameters = queryUrl.queryParameters else {
XCTFail("Failed to extract query parameters from \(queryUrl)")
return
}
XCTAssertEqual(parameters.count, 2)
XCTAssertEqual(parameters["q"], "swifter swift")
XCTAssertEqual(parameters["steve"], "jobs")
XCTAssertNil(parameters["empty"])
}
func testAllQueryParameters() {
guard let parameters = queryUrl.allQueryParameters else {
XCTFail("Failed to extract query parameters from \(queryUrl)")
return
}
XCTAssertEqual(parameters.count, 3)
XCTAssertEqual(parameters[0], URLQueryItem(name: "q", value: "swifter swift"))
XCTAssertEqual(parameters[1], URLQueryItem(name: "steve", value: "jobs"))
XCTAssertEqual(parameters[2], URLQueryItem(name: "empty", value: nil))
}
func testOptionalStringInitializer() {
XCTAssertNil(URL(string: nil, relativeTo: nil))
XCTAssertNil(URL(string: nil))
let baseURL = URL(string: "https://www.example.com")
XCTAssertNotNil(baseURL)
XCTAssertNil(URL(string: nil, relativeTo: baseURL))
let string = "/index.html"
let optionalString: String? = string
XCTAssertEqual(URL(string: optionalString, relativeTo: baseURL), URL(string: string, relativeTo: baseURL))
XCTAssertEqual(
URL(string: optionalString, relativeTo: baseURL)?.absoluteString,
"https://www.example.com/index.html")
}
func testAppendingQueryParameters() {
XCTAssertEqual(queryUrl.appendingQueryParameters(params), queryUrlWithParams)
}
func testAppendQueryParameters() {
var url = queryUrl
url.appendQueryParameters(params)
XCTAssertEqual(url, queryUrlWithParams)
}
func testValueForQueryKey() {
let url = URL(string: "https://google.com?code=12345&empty")!
let codeResult = url.queryValue(for: "code")
let emptyResult = url.queryValue(for: "empty")
let otherResult = url.queryValue(for: "other")
XCTAssertEqual(codeResult, "12345")
XCTAssertNil(emptyResult)
XCTAssertNil(otherResult)
}
func testDeletingAllPathComponents() {
let url = URL(string: "https://domain.com/path/other/")!
let result = url.deletingAllPathComponents()
XCTAssertEqual(result.absoluteString, "https://domain.com/")
let pathlessURL = URL(string: "https://domain.com")!
let pathlessResult = pathlessURL.deletingAllPathComponents()
XCTAssertEqual(pathlessResult.absoluteString, "https://domain.com")
}
func testDeleteAllPathComponents() {
var url = URL(string: "https://domain.com/path/other/")!
url.deleteAllPathComponents()
XCTAssertEqual(url.absoluteString, "https://domain.com/")
var pathlessURL = URL(string: "https://domain.com")!
pathlessURL.deleteAllPathComponents()
XCTAssertEqual(pathlessURL.absoluteString, "https://domain.com")
}
#if os(iOS) || os(tvOS)
func testThumbnail() {
XCTAssertNil(queryUrl.thumbnail())
let videoUrl = Bundle(for: URLExtensionsTests.self)
.url(forResource: "big_buck_bunny_720p_1mb", withExtension: "mp4")!
XCTAssertNotNil(videoUrl.thumbnail())
XCTAssertNotNil(videoUrl.thumbnail(fromTime: 1))
}
#endif
func testDropScheme() {
let urls: [String: String?] = [
"https://domain.com/path/other/": "domain.com/path/other/",
"https://domain.com": "domain.com",
"http://domain.com": "domain.com",
"file://domain.com/image.jpeg": "domain.com/image.jpeg",
"://apple.com": "apple.com",
"//apple.com": "apple.com",
"apple.com": "apple.com",
"http://": nil,
"//": "//"
]
urls.forEach { input, expected in
guard let url = URL(string: input) else { return XCTFail("Failed to initialize URL.") }
XCTAssertEqual(url.droppedScheme()?.absoluteString, expected, "input url: \(input)")
}
}
func testStringInitializer() throws {
let testURL = try XCTUnwrap(URL(string: "https://google.com"))
let extensionURL = URL(unsafeString: "https://google.com")
XCTAssertEqual(testURL, extensionURL)
}
}
#endif
|
//
// SettingsViewController.swift
// GonzagaCampusWalkingTour
//
// Created by Max Heinzelman on 3/6/20.
// Copyright © 2020 Senior Design Group 8. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
var tourProgress: TourProgress?
var tourProgressRetriever: TourProgressRetrievable?
var distanceTracker: DistanceTracker?
@IBOutlet weak var progressResetButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
if let nav = self.navigationController {
nav.topViewController?.title = "Settings"
}
}
@IBAction func progressResetButtonPressed(_ sender: Any) {
let alertMsg = "Are you sure you want to reset tour progress? Once you rest your progress it cannot be recovered"
let alert = UIAlertController(title: "Reset Tour Progress", message: alertMsg, preferredStyle: .alert)
//create an action for if the reset button is pressed
let resetAction = UIAlertAction(title: "Reset", style: .default, handler: {(alertAction) in
if let progress = self.tourProgress, let progressRetriever = self.tourProgressRetriever {
//reset the progress
if let dt = self.distanceTracker {
dt.currentDistance = 0.0
}
progressRetriever.resetTourProgress(progress: progress)
}
})
//create an action for a cancel button
let cancelAction = UIAlertAction(title: "Cancel", style: .default)
alert.addAction(resetAction)
alert.addAction(cancelAction)
//present alert dialog
self.present(alert, animated: true, completion: nil)
}
override func viewWillDisappear(_ animated: Bool) {
if let parentVC = self.navigationController?.topViewController as? GoogleMapsViewController {
//update the progress label
parentVC.setProgressLabel()
//reset the directions path
parentVC.addDirectionsPath()
//update monitored region
parentVC.updateMonitoredRegion()
}
}
}
|
////
//// ForgotPassword.swift
//// Neostore
////
//// Created by Neosoft on 27/03/20.
//// Copyright © 2020 Neosoft. All rights reserved.
////
//
//import SwiftUI
//
//struct ResetPassword: View {
// var body: some View {
// ZStack{
// Color(UIColor.red)
// .edgesIgnoringSafeArea(.all)
// VStack(spacing:30){
// Text("NeoSTORE")
//
// .foregroundColor(Color.white)
// .font(.largeTitle)
// // VStack{
// // // TextFields(icon: "password_icon", placeholder: "Current password")
// // //TextFields(icon: "password_icon", placeholder: "New password")
// // //TextFields(icon: "password_icon", placeholder: "Confirm password")
// // }
// VStack(spacing:15){
// Button(action: {
// print("Login")
// }){
// Text("RESET PASSWORD")
// .font(.headline)
// .foregroundColor(.red)
// }
// .frame(width: size.width-40, height: 45, alignment: .center)
// .background(Color.white)
// .cornerRadius(8)
//
//
// }
//
//
//
// }
//
// }
//
// }
//}
//
//struct ForgotPassword_Previews: PreviewProvider {
// static var previews: some View {
// ResetPassword()
// }
//}
|
//
// LabelViewController+TableViewDelegate.swift
// FundooApp
//
// Created by admin on 22/06/20.
// Copyright © 2020 admin. All rights reserved.
//
import UIKit
let addLabelCellReusableId = "AddLabelCell"
let numberOfSectionsForAddLabel = 2
extension LabelViewController: UITableViewDataSource,UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return numberOfSectionsForAddLabel
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return section == firstSection ? 1 : labels.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == firstSection {
let cell = tableView.dequeueReusableCell(withIdentifier: addLabelCellReusableId, for: indexPath) as! AddLabelCell
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: labelCellReusableId, for: indexPath) as! LabelCell
cell.labelTitle.text = labels[indexPath.row].label
cell.labelDelete.tag = indexPath.row
cell.labelDelete.addTarget(self, action: #selector(onDeletePressed(sender: )), for: .touchUpInside)
cell.layer.borderWidth = cellBorderWidth
cell.layer.borderColor = UIColor.gray.cgColor
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let board = UIStoryboard(name: Constants.FEATURES_STORYBOARD, bundle: nil)
guard let childVC = board.instantiateViewController(withIdentifier: Constants.UPDATE_LABEL_VC ) as? UpdateLabelViewController else {
return
}
if indexPath.section != firstSection {
let label = labels[indexPath.row]
childVC.label = label
}
navigationController?.pushViewController(childVC, animated: true)
}
@objc func onDeletePressed(sender:UIButton){
let index = sender.tag
let label = labels[index]
labelPresenter.deleteLabel(label: label)
reloadDataSource()
tableview.reloadData()
}
}
|
//
// User.swift
// Mini
//
// Created by Rishi Palivela on 20/06/20.
// Copyright © 2020 StarDust. All rights reserved.
//
import Foundation
struct EnsafeUser: Codable {
enum Gender: Int {
case male = 0
case female = 1
case other = 2
case notDetermined = -1
}
enum Kind: Int {
case citizen = 0
case police = 1
case ambulance
case firestation
case other
case notDetermined = -1
}
enum CodingKeys: String, CodingKey {
case id
case name
case email
case age
case gender
case kind
}
var id: String?
var name: String
var email: String
var age: Int
var gender: Gender
var kind: Kind
init(name: String, email: String, age: Int, gender: Gender,kind: Kind) {
self.name = name
self.email = email
self.age = age
self.gender = gender
self.kind = kind
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
email = try container.decode(String.self, forKey: .email)
age = try container.decode(Int.self, forKey: .age)
gender = Gender(rawValue: (try? container.decode(Int.self, forKey: .gender)) ?? -1)!
kind = Kind(rawValue: (try? container.decode(Int.self, forKey: .kind)) ?? -1)!
}
func encode(to encoder: Encoder) throws {
var container = try encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(email, forKey: .email)
try container.encode(age, forKey: .age)
try container.encode(gender.rawValue, forKey: .gender)
try container.encode(kind.rawValue, forKey: .kind)
}
}
|
//
// ZeroBuyController.swift
// gjs_user
//
// Created by 大杉网络 on 2019/9/18.
// Copyright © 2019 大杉网络. All rights reserved.
//
import UIKit
class ZeroBuyController: ViewController {
var allHeight = 0
let number = UILabel()
override func viewDidLoad() {
setNav(titleStr: "粉丝0元购", titleColor: kMainTextColor, navItem: navigationItem, navController: navigationController)
view.backgroundColor = .white
let body = UIScrollView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: kScreenH - 40))
body.configureLayout { (layout) in
layout.isEnabled = true
layout.flexDirection = .column
layout.width = YGValue(kScreenW)
layout.height = YGValue(kScreenH - 40)
}
// banner
let bannerView = UIView()
bannerView.configureLayout { (layout) in
layout.isEnabled = true
layout.width = YGValue(kScreenW)
layout.height = YGValue(kScreenW * 0.84)
layout.position = .relative
}
body.addSubview(bannerView)
let bannerImg = UIImageView(image: UIImage(named: "zeroBuy-banner"))
bannerImg.configureLayout { (layout) in
layout.isEnabled = true
layout.width = YGValue(kScreenW)
layout.height = YGValue(kScreenW * 0.84)
}
bannerView.addSubview(bannerImg)
let ruleBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 80, height: 24))
ruleBtn.layer.mask = ruleBtn.configRectCorner(view: ruleBtn, corner: [.bottomLeft, .topLeft], radii: CGSize(width: 10, height: 10))
ruleBtn.setTitle("活动规则", for: .normal)
ruleBtn.setTitleColor(kLowOrangeColor, for: .normal)
ruleBtn.backgroundColor = .white
ruleBtn.titleLabel?.font = FontSize(14)
ruleBtn.configureLayout { (layout) in
layout.isEnabled = true
layout.width = 80
layout.height = 24
layout.position = .absolute
layout.right = 0
layout.top = 15
}
bannerView.addSubview(ruleBtn)
// 步骤
let stepView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: 80))
stepView.backgroundColor = .white
stepView.layer.mask = stepView.configRectCorner(view: stepView, corner: [.topRight, .topLeft], radii: CGSize(width: 10, height: 10))
stepView.configureLayout { (layout) in
layout.isEnabled = true
layout.flexDirection = .row
layout.justifyContent = .spaceAround
layout.marginTop = -20
layout.width = YGValue(kScreenW)
layout.padding = 15
layout.paddingLeft = 20
layout.paddingRight = 20
}
body.addSubview(stepView)
for index in 1...3 {
let stepItem = UIView()
stepItem.configureLayout { (layout) in
layout.isEnabled = true
layout.alignItems = .center
// layout.width = YGValue(kScreenW)
}
stepView.addSubview(stepItem)
let itemImg = UIImageView(image: UIImage(named: "zeroBuy-\(index)"))
itemImg.configureLayout { (layout) in
layout.isEnabled = true
layout.width = 35
layout.height = 35
layout.marginBottom = 10
}
stepItem.addSubview(itemImg)
var itemText = "1.点击商品"
if index == 2 {
itemText = "2.补贴购买"
} else if index == 3 {
itemText = "3.收货返现"
}
let itemLabel = UILabel()
itemLabel.text = itemText
itemLabel.font = FontSize(14)
itemLabel.textColor = kMainTextColor
itemLabel.configureLayout { (layout) in
layout.isEnabled = true
}
stepItem.addSubview(itemLabel)
}
// 当前次数
let currentNumber = UIView()
currentNumber.configureLayout { (layout) in
layout.isEnabled = true
layout.flexDirection = .row
layout.justifyContent = .center
}
body.addSubview(currentNumber)
let numberLeft = UILabel()
numberLeft.text = "当前拥有"
numberLeft.textColor = kMainTextColor
numberLeft.font = FontSize(14)
numberLeft.configureLayout { (layout) in
layout.isEnabled = true
}
currentNumber.addSubview(numberLeft)
number.text = "0"
number.textColor = kLowOrangeColor
number.font = FontSize(18)
number.textAlignment = .center
number.configureLayout { (layout) in
layout.isEnabled = true
layout.width = 30
}
currentNumber.addSubview(number)
let numberRight = UILabel()
numberRight.text = "次参与0元购资格"
numberRight.textColor = kMainTextColor
numberRight.font = FontSize(14)
numberRight.configureLayout { (layout) in
layout.isEnabled = true
}
currentNumber.addSubview(numberRight)
// 新老用户
let newOld = UIView()
newOld.layer.borderWidth = 1
newOld.layer.borderColor = kLowOrangeColor.cgColor
newOld.configureLayout { (layout) in
layout.isEnabled = true
layout.width = YGValue(kScreenW - 20)
layout.marginLeft = 10
layout.marginTop = 15
layout.padding = 10
}
body.addSubview(newOld)
let newLabel = UILabel()
newLabel.text = "新用户:注册即可享受一次0元购"
newLabel.font = FontSize(14)
newLabel.textColor = kLowOrangeColor
newLabel.numberOfLines = 0
newLabel.configureLayout { (layout) in
layout.isEnabled = true
layout.width = YGValue(kScreenW - 40)
layout.marginBottom = 10
}
newOld.addSubview(newLabel)
let oldLabel = UILabel()
oldLabel.text = "老用户:邀请三个有效会员(完成淘宝授权),可再次获取一次0元购"
oldLabel.font = FontSize(14)
oldLabel.textColor = kLowOrangeColor
oldLabel.numberOfLines = 0
oldLabel.configureLayout { (layout) in
layout.isEnabled = true
layout.width = YGValue(kScreenW - 40)
layout.marginBottom = 10
}
newOld.addSubview(oldLabel)
let totalLabel = UILabel()
totalLabel.text = "已结算订单于次月25号前到账提现。"
totalLabel.font = FontSize(14)
totalLabel.textColor = kLowOrangeColor
totalLabel.numberOfLines = 0
totalLabel.configureLayout { (layout) in
layout.isEnabled = true
layout.width = YGValue(kScreenW - 40)
}
newOld.addSubview(totalLabel)
body.yoga.applyLayout(preservingOrigin: true)
body.contentInset = UIEdgeInsets(top: CGFloat(0), left: CGFloat(0), bottom: CGFloat(allHeight + 40), right: CGFloat(0))
// body.delegate = self
view.addSubview(body)
}
}
|
//
// Character.swift
// FamilyHouse
//
// Created by Marie Park on 10/10/16.
// Copyright © 2016 Flatiron School. All rights reserved.
//
import UIKit
struct Character {
let name: String
let realLifeName: String
let tvSeries: TVSeries
var currentLocation: FilmLocation
let image: UIImage
func canReportToSet(on location:FilmLocation) -> Bool {
if self.currentLocation.address == location.address {
return true
} else {
return false
}
}
mutating func reportToSet(on location: FilmLocation) {
guard canReportToSet(on: location) else {return}
currentLocation = location
}
}
|
//
// EmojiSelectionViewController.swift
// ShoppingCart
//
// Created by Jim Campagno on 8/10/16.
// Copyright © 2016 Gamesmith, LLC. All rights reserved.
//
import UIKit
class EmojiSelectionViewController: UIViewController {
//Stored properties
var emojiDelegate: EmojiCreation?
@IBOutlet weak var textfield1: UITextField!
@IBOutlet weak var textfield2: UITextField!
@IBAction func savebutton(_ sender: Any) {
if let first = textfield1.text {
if let second = textfield2.text {
let emoji: (String, String) = (first, second)
emojiDelegate?.create(emojiGroup: emoji)
}
}
dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(red:0.22, green:0.33, blue:0.58, alpha:1.00)
}
}
|
//
// ContentView.swift
// WebView
//
// Created by Victor Smirnov on 14.11.2019.
// Copyright © 2019 Victor Smirnov. All rights reserved.
//
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
List {
ImageRow()
}.navigationBarTitle(Text("Landscape"))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().preferredColorScheme(.dark)
}
}
|
//
// SpotTableViewController.swift
// Harvey
//
// Created by Sean Hart on 8/31/17.
// Copyright © 2017 TangoJ Labs, LLC. All rights reserved.
//
import FBSDKShareKit
import UIKit
protocol SpotTableViewControllerDelegate
{
func reloadData()
}
class SpotTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, UIGestureRecognizerDelegate, UserViewControllerDelegate, AWSRequestDelegate, RequestDelegate
{
var spots = [Spot]()
var spotContent = [SpotContent]()
var allowDelete: Bool = false
var visibleCells: Int = 0
var backgroundText: String = ""
convenience init(spots: [Spot], allowDelete: Bool)
{
self.init(nibName:nil, bundle:nil)
self.spots = spots
self.allowDelete = allowDelete
// Create an array of only the content
for spot in self.spots
{
if spot.spotContent.count > 0
{
self.spotContent = self.spotContent + spot.spotContent
}
}
print("STVC - CONTENT INIT COUNT: \(self.spotContent.count)")
if self.spotContent.count > 5
{
visibleCells = 5
}
else
{
visibleCells = self.spotContent.count
if self.spotContent.count == 0
{
print("STVC - SHOW BG TEXT")
backgroundText = "No content exists here. Go to the main map to add some!"
}
}
}
var spotTableDelegate: SpotTableViewControllerDelegate?
// MARK: PROPERTIES
// Save device settings to adjust view if needed
var screenSize: CGRect!
var statusBarHeight: CGFloat!
var navBarHeight: CGFloat!
var viewFrameY: CGFloat!
var vcHeight: CGFloat!
var vcOffsetY: CGFloat!
// The views to hold major components of the view controller
var statusBarView: UIView!
var viewContainer: UIView!
var backgroundLabel: UILabel!
var spotContentTableView: UITableView!
var tableGestureRecognizer: UITapGestureRecognizer!
// Properties to hold local information
var viewContainerHeight: CGFloat!
var spotCellWidth: CGFloat!
// var spotCellContentHeight: CGFloat!
var spotMediaSize: CGFloat!
// Settings to increment the number of cells displayed as the user scrolls content into view
// Prevents all content being displayed at once and overloading the app with content and downloading
let visibleIncrementSize: Int = 5
override func viewDidLoad()
{
super.viewDidLoad()
print("STVC - CONTENT COUNT: \(spotContent.count)")
prepVcLayout()
self.automaticallyAdjustsScrollViewInsets = false
// Add the Status Bar, Top Bar and Search Bar last so that they are placed above (z-index) all other views
statusBarView = UIView(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: statusBarHeight))
statusBarView.backgroundColor = Constants.Colors.colorStatusBar
self.view.addSubview(statusBarView)
// Add the view container to hold all other views (allows for shadows on all subviews)
viewContainer = UIView(frame: CGRect(x: 0, y: vcOffsetY, width: self.view.bounds.width, height: vcHeight))
viewContainer.backgroundColor = Constants.Colors.standardBackgroundGrayUltraLight
self.view.addSubview(viewContainer)
backgroundLabel = UILabel(frame: CGRect(x: 50, y: 5, width: viewContainer.frame.width - 100, height: viewContainer.frame.height / 2))
backgroundLabel.textColor = Constants.Colors.colorTextDark
backgroundLabel.text = backgroundText
backgroundLabel.numberOfLines = 3
backgroundLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
backgroundLabel.textAlignment = .center
backgroundLabel.font = UIFont(name: "HelveticaNeue-UltraLight", size: 20)
viewContainer.addSubview(backgroundLabel)
// Set the main cell standard dimensions
spotCellWidth = viewContainer.frame.width
spotMediaSize = viewContainer.frame.width
// A tableview will hold all comments
spotContentTableView = UITableView(frame: CGRect(x: 0, y: 0, width: viewContainer.frame.width, height: viewContainer.frame.height))
spotContentTableView.dataSource = self
spotContentTableView.delegate = self
spotContentTableView.register(SpotTableViewCell.self, forCellReuseIdentifier: Constants.Strings.spotTableViewCellReuseIdentifier)
spotContentTableView.separatorStyle = .none
spotContentTableView.backgroundColor = UIColor.clear //Constants.Colors.standardBackground
spotContentTableView.isScrollEnabled = true
spotContentTableView.bounces = true
spotContentTableView.alwaysBounceVertical = true
spotContentTableView.allowsSelection = false
spotContentTableView.showsVerticalScrollIndicator = false
// spotContentTableView.isUserInteractionEnabled = true
// spotContentTableView.allowsSelection = true
spotContentTableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
viewContainer.addSubview(spotContentTableView)
tableGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(SpotTableViewController.tableGesture(_:)))
tableGestureRecognizer.delegate = self
spotContentTableView.addGestureRecognizer(tableGestureRecognizer)
NotificationCenter.default.addObserver(self, selector: #selector(MapViewController.statusBarHeightChange(_:)), name: Notification.Name("UIApplicationWillChangeStatusBarFrameNotification"), object: nil)
// Order the SpotContent Array
spotContent.sort {
$0.datetime > $1.datetime
}
}
override func viewWillAppear(_ animated: Bool)
{
print("STVC - viewWillAppear")
refreshSpotViewTable()
}
// MARK: LAYOUT METHODS
func statusBarHeightChange(_ notification: Notification)
{
prepVcLayout()
statusBarView.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: statusBarHeight)
viewContainer.frame = CGRect(x: 0, y: vcOffsetY, width: screenSize.width, height: vcHeight)
spotContentTableView.frame = CGRect(x: 0, y: 0, width: viewContainer.frame.width, height: viewContainer.frame.height)
}
func prepVcLayout()
{
// Record the status bar settings to adjust the view if needed
UIApplication.shared.isStatusBarHidden = false
UIApplication.shared.statusBarStyle = Constants.Settings.statusBarStyle
statusBarHeight = UIApplication.shared.statusBarFrame.size.height
// Navigation Bar settings
navBarHeight = 44.0
if let navController = self.navigationController
{
navController.isNavigationBarHidden = false
navBarHeight = navController.navigationBar.frame.height
navController.navigationBar.barTintColor = Constants.Colors.colorOrangeOpaque
}
viewFrameY = self.view.frame.minY
screenSize = UIScreen.main.bounds
vcHeight = screenSize.height - statusBarHeight - navBarHeight
vcOffsetY = statusBarHeight + navBarHeight
if statusBarHeight == 40
{
vcHeight = screenSize.height - 76
vcOffsetY = 56
}
}
// MARK: TABLE VIEW DATA SOURCE
func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return visibleCells
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
let cellHeight: CGFloat = tableView.frame.width
return cellHeight
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
// print("STVC - CREATING CELL: \(indexPath.row)")
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Strings.spotTableViewCellReuseIdentifier, for: indexPath) as! SpotTableViewCell
// Remove all subviews
for subview in cell.subviews
{
subview.removeFromSuperview()
}
if spotContent.count > indexPath.row
{
// Store the spotContent for this cell for reference
let cellSpotContent = spotContent[indexPath.row]
cell.cellContainer = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: tableView.frame.width + 50))
cell.addSubview(cell.cellContainer)
// cell.footerContainer = UIView(frame: CGRect(x: 0, y: cell.cellContainer.frame.height - 50, width: cell.cellContainer.frame.width, height: 50))
// cell.footerContainer.backgroundColor = Constants.Colors.standardBackground
// cell.cellContainer.addSubview(cell.footerContainer)
cell.cellImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: cell.cellContainer.frame.width, height: cell.cellContainer.frame.width))
cell.cellImageView.contentMode = UIViewContentMode.scaleAspectFit
cell.cellImageView.clipsToBounds = true
cell.cellContainer.addSubview(cell.cellImageView)
// Add a loading indicator until the Media has downloaded
// Give it the same size and location as the imageView
cell.mediaActivityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: cell.cellImageView.frame.width, height: cell.cellImageView.frame.height))
cell.mediaActivityIndicator.color = UIColor.black
cell.cellImageView.addSubview(cell.mediaActivityIndicator)
cell.mediaActivityIndicator.startAnimating()
cell.userImageView = UIImageView(frame: CGRect(x: 10, y: 10, width: 50, height: 50))
// cell.userImageView = UIImageView(frame: CGRect(x: 0, y: cell.cellContainer.frame.height - 50, width: 50, height: 50))
cell.userImageView.backgroundColor = Constants.Colors.standardBackgroundGrayTransparent
cell.userImageView.contentMode = UIViewContentMode.scaleAspectFit
cell.userImageView.clipsToBounds = true
cell.cellContainer.addSubview(cell.userImageView)
// Add a loading indicator until the user image has downloaded
// Give it the same size and location as the user image
cell.userImageActivityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: cell.userImageView.frame.width, height: cell.userImageView.frame.height))
cell.userImageActivityIndicator.color = UIColor.black
cell.userImageView.addSubview(cell.userImageActivityIndicator)
cell.userImageActivityIndicator.startAnimating()
cell.datetimeLabel = UILabel(frame: CGRect(x: cell.cellImageView.frame.width - 60, y: cell.cellImageView.frame.height - 60, width: 50, height: 50))
// cell.datetimeLabel = UILabel(frame: CGRect(x: 50, y: cell.cellContainer.frame.height - 50, width: 50, height: 50))
cell.datetimeLabel.backgroundColor = Constants.Colors.standardBackgroundGrayTransparent
cell.datetimeLabel.font = UIFont(name: Constants.Strings.fontAlt, size: 16)
cell.datetimeLabel.textColor = Constants.Colors.colorTextLight
cell.datetimeLabel.textAlignment = .center
cell.datetimeLabel.numberOfLines = 2
cell.datetimeLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
cell.cellContainer.addSubview(cell.datetimeLabel)
cell.shareButtonView = UIView(frame: CGRect(x: cell.cellImageView.frame.width - 60, y: 10, width: 50, height: 50))
// cell.shareButtonView = UIView(frame: CGRect(x: cell.cellContainer.frame.width - 50, y: cell.cellContainer.frame.height - 50, width: 50, height: 50))
cell.shareButtonView.backgroundColor = Constants.Colors.standardBackgroundGrayTransparent
cell.cellContainer.addSubview(cell.shareButtonView)
cell.shareButtonImage = UIImageView(frame: CGRect(x: 10, y: 10, width: 30, height: 30))
cell.shareButtonImage.image = UIImage(named: Constants.Strings.iconShareArrow)
cell.shareButtonImage.contentMode = UIViewContentMode.scaleAspectFit
cell.shareButtonImage.clipsToBounds = true
cell.shareButtonView.addSubview(cell.shareButtonImage)
cell.flagButtonView = UIView(frame: CGRect(x: 10, y: cell.cellImageView.frame.height - 60, width: 50, height: 50))
// cell.flagButtonView = UIView(frame: CGRect(x: cell.cellContainer.frame.width - 100, y: cell.cellContainer.frame.height - 50, width: 50, height: 50))
cell.flagButtonView.backgroundColor = Constants.Colors.standardBackgroundGrayTransparent
cell.cellContainer.addSubview(cell.flagButtonView)
cell.flagButtonImage = UILabel(frame: CGRect(x: 10, y: 10, width: 30, height: 30))
// cell.flagButtonImage.image = UIImage(named: Constants.Strings.iconShareArrow)
// cell.flagButtonImage.contentMode = UIViewContentMode.scaleAspectFit
// cell.flagButtonImage.clipsToBounds = true
cell.flagButtonImage.font = UIFont(name: Constants.Strings.fontAlt, size: 30)
cell.flagButtonImage.textColor = Constants.Colors.colorTextLight
cell.flagButtonImage.textAlignment = .center
cell.flagButtonImage.text = "\u{2691}" // "\u{26A0}"
cell.flagButtonView.addSubview(cell.flagButtonImage)
if indexPath.row > 0
{
let border1 = CALayer()
border1.frame = CGRect(x: 0, y: 0, width: cell.cellContainer.frame.width, height: 1)
border1.backgroundColor = Constants.Colors.standardBackgroundGrayUltraLight.cgColor
cell.cellContainer.layer.addSublayer(border1)
}
cell.datetimeLabel.text = String(indexPath.row)
if let datetime = cellSpotContent.datetime
{
// Capture the number of hours it has been since the Spot was created (as a positive integer)
// print("STVC - CURRENT TIME: \(Date().timeIntervalSince1970), CONTENT TIME: \(datetime), CONTENT AGE: \(datetime.timeIntervalSinceNow), AGE ROUNDED: \(Date(timeIntervalSince1970: Double(Int(datetime.timeIntervalSinceNow / 3600))))")
let dateAgeHrs: Int = -1 * Int(datetime.timeIntervalSinceNow / 3600)
// Set the datetime label. If the Spot's recency is less than 5 days (120 hours), just show the day and time.
// If the Spot's recency is more than 5 days, include the date
let formatter = DateFormatter()
formatter.amSymbol = "am"
formatter.pmSymbol = "pm"
// Set the date age label. If the age is less than 24 hours, just show it in hours. Otherwise, show the number of days and hours.
var stringDate = String(dateAgeHrs / Int(24)) + "\ndays" //+ String(dateAgeHrs % 24) + " hrs"
if dateAgeHrs < 24
{
stringDate = String(dateAgeHrs) + "\nhrs"
}
else if dateAgeHrs < 48
{
stringDate = "1\nday"
}
else if dateAgeHrs < 120
{
formatter.dateFormat = "E\nh:mm\na" //"E, H:mma"
stringDate = formatter.string(from: datetime as Date)
cell.datetimeLabel.font = UIFont(name: Constants.Strings.fontAlt, size: 12)
cell.datetimeLabel.numberOfLines = 3
}
else
{
formatter.dateFormat = "E\nMMM d" // "E, MMM d" "E, MMM d, H:mma"
stringDate = formatter.string(from: datetime as Date)
cell.datetimeLabel.font = UIFont(name: Constants.Strings.fontAlt, size: 14)
}
cell.datetimeLabel.text = stringDate
}
// If the delete button is allowed, place it over the user image
if allowDelete
{
cell.deleteButtonView = UIView(frame: CGRect(x: 10, y: cell.cellImageView.frame.height - 60, width: 50, height: 50))
cell.deleteButtonView.backgroundColor = Constants.Colors.colorGrayDark
cell.cellContainer.addSubview(cell.deleteButtonView)
cell.deleteButtonImage = UILabel(frame: CGRect(x: 0, y: 0, width: cell.deleteButtonView.frame.width, height: cell.deleteButtonView.frame.height))
cell.deleteButtonImage.text = "DELETE"
cell.deleteButtonImage.textColor = Constants.Colors.colorTextLight
cell.deleteButtonImage.font = UIFont(name: Constants.Strings.fontAlt, size: 12)
cell.deleteButtonImage.textAlignment = .center
// Add a loading indicator in case the content is waiting to be deleted
// Give it the same size and location as the delete button
cell.deleteButtonActivityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: cell.deleteButtonView.frame.width, height: cell.deleteButtonView.frame.height))
cell.deleteButtonActivityIndicator.color = UIColor.white
if cellSpotContent.deletePending
{
cell.deleteButtonView.addSubview(cell.deleteButtonActivityIndicator)
cell.deleteButtonActivityIndicator.startAnimating()
}
else
{
cell.deleteButtonView.addSubview(cell.deleteButtonImage)
}
// Show the current user's image in all the cells
if let image = Constants.Data.currentUser.image
{
cell.userImageView.image = image
cell.cellContainer.addSubview(cell.userImageView)
cell.userImageActivityIndicator.stopAnimating()
}
else if let image = Constants.Data.currentUser.thumbnail
{
cell.userImageView.image = image
cell.cellContainer.addSubview(cell.userImageView)
cell.userImageActivityIndicator.stopAnimating()
}
else
{
// For some reason the thumbnail has not yet downloaded for this user - request the image again
RequestPrep(requestToCall: FBDownloadUserImage(facebookID: Constants.Data.currentUser.facebookID, largeImage: false), delegate: self as RequestDelegate).prepRequest()
}
}
else
{
// Various users' content is shown - show the user image
// Find the associated user and assign the image, if available (if not, don't show the user imageview)
spotLoop: for spot in Constants.Data.allSpot
{
if spot.spotID == cellSpotContent.spotID
{
userLoop: for user in Constants.Data.allUsers
{
if user.userID == spot.userID
{
if let image = user.thumbnail
{
cell.userImageView.image = image
cell.cellContainer.addSubview(cell.userImageView)
cell.userImageActivityIndicator.stopAnimating()
}
else
{
// For some reason the thumbnail has not yet downloaded for this user - request the image again
RequestPrep(requestToCall: FBDownloadUserImage(facebookID: user.facebookID, largeImage: false), delegate: self as RequestDelegate).prepRequest()
}
break userLoop
}
}
break spotLoop
}
}
}
// Add the content image, if available - otherwise download and indicate as being downloaded so it does not fire again
if let contentImage = cellSpotContent.image
{
cell.cellImageView.image = contentImage
// Stop animating the activity indicator
cell.mediaActivityIndicator.stopAnimating()
}
else
{
if !spotContent[indexPath.row].imageDownloading
{
// Get the missing image
let awsObject = AWSDownloadMediaImage(imageID: cellSpotContent.contentID)
awsObject.imageParentID = cellSpotContent.spotID
AWSPrepRequest(requestToCall: awsObject, delegate: self as AWSRequestDelegate).prepRequest()
// Save the downloading indicator on the object in the array, otherwise it will download again
spotContent[indexPath.row].imageDownloading = true
}
}
}
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
{
print("STVC - VISIBLE CELLS: \(visibleCells) - WILL DISPLAY CELL: \(indexPath.row)")
// Determine if the last visible cell is being shown - if so, show more cells
// (subtract one from the cell count since the table indices start at 0)
if indexPath.row == visibleCells - 1
{
// Increase the cells viewable and refresh the table (ensure not more than the original list count)
let oldVisibleCellCount = visibleCells
if spotContent.count >= oldVisibleCellCount + visibleIncrementSize
{
visibleCells = oldVisibleCellCount + visibleIncrementSize
}
else
{
visibleCells = spotContent.count
}
print("STVC - INCREASING CELL RANGE TO: \(visibleCells)")
// Only refresh if the count changed
if visibleCells > oldVisibleCellCount
{
refreshSpotViewTable()
}
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
// print("STVC - SELECTED CELL: \(indexPath.row)")
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath)
{
}
func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath)
{
}
func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath)
{
}
// MARK: SCROLL VIEW DELEGATE METHODS
func scrollViewDidScroll(_ scrollView: UIScrollView)
{
}
// MARK: GESTURE RECOGNIZERS
func tableGesture(_ gesture: UITapGestureRecognizer)
{
if gesture.state == UIGestureRecognizerState.ended
{
let tapLocation = gesture.location(in: self.spotContentTableView)
print("STVC - TAP LOCATION: \(tapLocation)")
if let tappedIndexPath = spotContentTableView.indexPathForRow(at: tapLocation)
{
print("STVC - TAPPED INDEX PATH: \(tappedIndexPath)")
if spotContent.count > 0
{
if let tappedCell = self.spotContentTableView.cellForRow(at: tappedIndexPath) as? SpotTableViewCell
{
let cellTapLocation = gesture.location(in: tappedCell)
if tappedCell.userImageView.frame.contains(cellTapLocation)
{
// Load the UserVC
print("STVC - SPOT CONTENT COUNT: \(spotContent.count)")
if spotContent.count > tappedIndexPath.row
{
let spotID = spotContent[tappedIndexPath.row].spotID
spotLoop: for spot in Constants.Data.allSpot
{
if spot.spotID == spotID
{
userLoop: for user in Constants.Data.allUsers
{
if user.userID == spot.userID
{
print("STVC - USER TAP: \(user.userID)")
let userVC = UserViewController(user: user)
userVC.userDelegate = self
self.navigationController!.pushViewController(userVC, animated: true)
break userLoop
}
}
break spotLoop
}
}
}
}
if tappedCell.shareButtonView.frame.contains(cellTapLocation)
{
// Share the image on Facebook
// print("STVC - SHARE CONTAINS")
if let image = spotContent[tappedIndexPath.row].image
{
let photo : FBSDKSharePhoto = FBSDKSharePhoto()
photo.image = image
photo.isUserGenerated = true
let fbShareContent : FBSDKSharePhotoContent = FBSDKSharePhotoContent()
fbShareContent.photos = [photo]
let shareDialog = FBSDKShareDialog()
shareDialog.shareContent = fbShareContent
shareDialog.mode = .native
if let fbShareResponse = try? shareDialog.show()
{
print("STVC - FB SHARE RESPONSE: \(fbShareResponse)")
if !fbShareResponse
{
// Sharing is not allowed without the app - show a popup to explain
let alertController = UIAlertController(title: "Facebook App Not Installed", message: "We're sorry, you need the Facebook app installed to share photos.", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default)
{ (result : UIAlertAction) -> Void in
print("STVC - POPUP CLOSE")
}
alertController.addAction(okAction)
alertController.show()
}
}
}
}
else if tappedCell.flagButtonView.frame.contains(cellTapLocation)
{
// If delete isn't allowed, the user is tapping on the user image, if it is, the user is tapping on the delete button
if !allowDelete
{
// Ensure the user wants to flag the content "Are you sure you want to report this image as objectionable or inaccurate?"
let alertController = UIAlertController(title: "REPORT IMAGE", message: "", preferredStyle: UIAlertControllerStyle.alert)
let objectionableAction = UIAlertAction(title: "Inappropriate", style: UIAlertActionStyle.default)
{ (result : UIAlertAction) -> Void in
// Flag the image as objectionable
let contentID = self.spotContent[tappedIndexPath.row].contentID
let spotID = self.spotContent[tappedIndexPath.row].spotID
print("STVC - FLAG 00 FOR CONTENT: \(String(describing: contentID))")
// Send the SpotContent update
AWSPrepRequest(requestToCall: AWSSpotContentStatusUpdate(contentID: contentID, spotID: spotID, statusUpdate: "flag-00"), delegate: self as AWSRequestDelegate).prepRequest()
}
let inaccurateAction = UIAlertAction(title: "Inaccurate", style: UIAlertActionStyle.default)
{ (result : UIAlertAction) -> Void in
// Flag the image as objectionable
let contentID = self.spotContent[tappedIndexPath.row].contentID
let spotID = self.spotContent[tappedIndexPath.row].spotID
print("STVC - FLAG 01 FOR CONTENT: \(String(describing: contentID))")
// Send the SpotContent update
AWSPrepRequest(requestToCall: AWSSpotContentStatusUpdate(contentID: contentID, spotID: spotID, statusUpdate: "flag-01"), delegate: self as AWSRequestDelegate).prepRequest()
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default)
{ (result : UIAlertAction) -> Void in
print("STVC - FLAG CANCELLED")
}
alertController.addAction(objectionableAction)
alertController.addAction(inaccurateAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
else
{
print("STVC - DELETE IMAGE: \(spotContent[tappedIndexPath.row].contentID)")
// Ensure the user wants to delete the content
let alertController = UIAlertController(title: "DELETE PHOTO", message: "Are you sure you want to delete this photo?", preferredStyle: UIAlertControllerStyle.alert)
let deleteAction = UIAlertAction(title: "Delete", style: UIAlertActionStyle.default)
{ (result : UIAlertAction) -> Void in
// Flag the image as objectionable
let contentID = self.spotContent[tappedIndexPath.row].contentID
let spotID = self.spotContent[tappedIndexPath.row].spotID
print("STVC - DELETE FOR CONTENT: \(String(describing: contentID))")
// Send the SpotContent update
AWSPrepRequest(requestToCall: AWSSpotContentStatusUpdate(contentID: contentID, spotID: spotID, statusUpdate: "delete"), delegate: self as AWSRequestDelegate).prepRequest()
// Update the content so that it displays as waiting for the delete command to complete
self.spotContent[tappedIndexPath.row].deletePending = true
// Update the tableview
self.refreshSpotViewTable()
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default)
{ (result : UIAlertAction) -> Void in
print("STVC - DELETE CANCELLED")
}
alertController.addAction(cancelAction)
alertController.addAction(deleteAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
}
}
}
}
// MARK: CUSTOM METHODS
// Dismiss the latest View Controller presented from this VC
// This version is used when the top VC is popped from a Nav Bar button
func popViewController(_ sender: UIBarButtonItem)
{
self.navigationController!.popViewController(animated: true)
}
func popViewController()
{
self.navigationController!.popViewController(animated: true)
}
func refreshSpotViewTable()
{
DispatchQueue.main.async(execute:
{
if self.spotContentTableView != nil
{
print("STVC - REFRESH SPOT VIEW TABLE")
// Reload the TableView
self.spotContentTableView.reloadData()
// self.spotContentTableView.performSelector(onMainThread: #selector(UITableView.reloadData), with: nil, waitUntilDone: true)
}
})
}
func reloadSpotViewTable()
{
if self.spotContentTableView != nil
{
print("STVC - RELOAD SPOT VIEW TABLE")
if self.spotContent.count > 5
{
visibleCells = 5
}
else
{
visibleCells = self.spotContent.count
}
// self.spotContentTableView.reloadData()
self.spotContentTableView.performSelector(onMainThread: #selector(UITableView.reloadData), with: nil, waitUntilDone: true)
}
}
func updateData()
{
// Remove all banned user's data from the local list
// Create a new list with all non-blocked users' data (removing the data directly will fault out)
var nonBlockedSpots = [Spot]()
var nonBlockedSpotContent = [SpotContent]()
for spot in spots
{
print("STVC - CHECK USER: \(index): \(spot.userID)")
var userBlocked = false
for user in Constants.Data.allUserBlockList
{
print("STVC - BLOCKED USER: \(user)")
if user == spot.userID
{
print("STVC - ALL SPOT COUNT: \(Constants.Data.allSpot.count)")
print("STVC - REMOVE BLOCKED USER: \(index)")
userBlocked = true
}
}
if !userBlocked
{
nonBlockedSpots.append(spot)
for spotContent in spot.spotContent
{
nonBlockedSpotContent.append(spotContent)
}
}
}
spots = nonBlockedSpots
spotContent = nonBlockedSpotContent
print("STVC - SPOT COUNT: \(spots.count)")
if spotContent.count > 0
{
reloadSpotViewTable()
}
else
{
reloadSpotViewTable()
popViewController()
}
// Remove all banned user's data from the global list
UtilityFunctions().updateUserConnections()
UtilityFunctions().removeBlockedUsersFromGlobalSpotArray()
}
// MARK: AWS DELEGATE METHODS
func showLoginScreen()
{
print("BAVC - SHOW LOGIN SCREEN")
// Load the LoginVC
let loginVC = LoginViewController()
self.navigationController!.pushViewController(loginVC, animated: true)
}
func processAwsReturn(_ objectType: AWSRequestObject, success: Bool)
{
DispatchQueue.main.async(execute:
{
// Process the return data based on the method used
switch objectType
{
case let awsDownloadMediaImage as AWSDownloadMediaImage:
if success
{
if let contentImage = awsDownloadMediaImage.contentImage
{
// Find the spotContent Object in the local array and add the downloaded image to the object variable
findSpotContentLoop: for contentObject in self.spotContent
{
if contentObject.contentID == awsDownloadMediaImage.imageID
{
// Set the local image property to the downloaded image
contentObject.image = contentImage
if let filePath = awsDownloadMediaImage.imageFilePath
{
contentObject.imageFilePath = filePath
}
break findSpotContentLoop
}
}
// Find the spotContent Object in the global array and add the downloaded image to the object variable
findSpotLoop: for spotObject in Constants.Data.allSpot
{
// The parentID should be the spotID, use it to narrow down which Spot contains the needed content
if let spotID = awsDownloadMediaImage.imageParentID
{
if spotID == spotObject.spotID
{
findSpotContentLoop: for contentObject in spotObject.spotContent
{
if contentObject.contentID == awsDownloadMediaImage.imageID
{
// Set the local image property to the downloaded image
contentObject.image = contentImage
if let filePath = awsDownloadMediaImage.imageFilePath
{
contentObject.imageFilePath = filePath
}
break findSpotContentLoop
}
}
break findSpotLoop
}
}
}
// Reload the TableView
self.refreshSpotViewTable()
}
}
else
{
// Show the error message
let alertController = UtilityFunctions().createAlertOkView("Network Error", message: "I'm sorry, you appear to be having network issues. Please try again.")
self.present(alertController, animated: true, completion: nil)
}
case let awsSpotContentStatusUpdate as AWSSpotContentStatusUpdate:
if success
{
// The flagging / delete update was successful, so remove the image from the current view
// THE GLOBAL ARRAY WAS UPDATED IN THE AWS CLASS RESPONSE
localSpotContentLoop: for (index, spotContentObject) in self.spotContent.enumerated()
{
if spotContentObject.contentID == awsSpotContentStatusUpdate.contentID
{
// Remove the SpotContent object
self.spotContent.remove(at: index)
// Update the tableview
self.refreshSpotViewTable()
break localSpotContentLoop
}
}
}
else
{
// Show the error message
let alertController = UtilityFunctions().createAlertOkView("Network Error", message: "I'm sorry, you appear to be having network issues. Please try again.")
self.present(alertController, animated: true, completion: nil)
}
default:
print("STVC-DEFAULT: THERE WAS AN ISSUE WITH THE DATA RETURNED FROM AWS")
// Show the error message
let alertController = UtilityFunctions().createAlertOkView("Network Error", message: "I'm sorry, you appear to be having network issues. Please try again.")
self.present(alertController, animated: true, completion: nil)
}
})
}
func processRequestReturn(_ requestCalled: RequestObject, success: Bool)
{
// Process the return data based on the method used
switch requestCalled
{
case _ as FBDownloadUserImage:
if success
{
print("STVC-FBDownloadUserImage")
self.refreshSpotViewTable()
}
else
{
// Show the error message
let alert = UtilityFunctions().createAlertOkView("Network Error", message: "I'm sorry, you appear to be having network issues. Please try again.")
alert.show()
}
default:
// Show the error message
let alert = UtilityFunctions().createAlertOkView("Network Error", message: "I'm sorry, you appear to be having network issues. Please try again.")
alert.show()
}
}
}
|
//
// RootView.swift
// PlumTestTask
//
// Created by Adrian Śliwa on 22/06/2020.
// Copyright © 2020 sliwa.adrian. All rights reserved.
//
import ComposableArchitecture
import SwiftUI
struct RootView: View {
@ObservedObject private var viewStore: ViewStore<RootState, RootAction>
private let flowDecorator: (AnyView) -> AnyView
init(
viewStore: ViewStore<RootState, RootAction>,
flowDecorator: @escaping (AnyView) -> AnyView
) {
self.viewStore = viewStore
self.flowDecorator = flowDecorator
viewStore.send(.initialize)
UITableView.appearance().separatorStyle = .none
UITableView.appearance().backgroundColor = .clear
UITableViewCell.appearance().selectionStyle = .none
}
var body: some View {
let resultView: AnyView
switch viewStore.status {
case .loading:
resultView = VStack {
if viewStore.squadHeros.isNotEmpty {
MySquadView(viewStore: viewStore)
}
ActivityIndicator(
isAnimating: .constant(true),
style: .large
)
.frame(maxHeight: .infinity, alignment: .center)
}
.padding(.top, 1)
.eraseToAnyView()
case .didFailToLoadHeros:
resultView = Text(Strings.didFailToLoadHeros)
.font(.title)
.foregroundColor(.white)
.eraseToAnyView()
case .idle:
resultView = List {
if viewStore.squadHeros.isNotEmpty {
MySquadView(viewStore: viewStore)
.listRowInsets(EdgeInsets())
.listRowBackground(Color.background)
.padding(.bottom, Insets.small)
}
ForEach(viewStore.allHeros, id: \.self) { hero in
HeroRow(
hero: hero,
viewStore: self.viewStore
)
}
.listRowBackground(Color.background)
}
.padding(.top, 1)
.eraseToAnyView()
}
return resultView
.inject(flowDecorator: flowDecorator)
}
}
struct RootView_Previews: PreviewProvider {
static var previews: some View {
RootViewBuilder.makeRootView(
store: Store(
initialState: AppState(),
reducer: appReducer,
environment: AppEnvironment(
mainQueue: DispatchQueue.main.eraseToAnyScheduler(),
herosProvider: HerosNetworkProvider(),
persistency: FilePersistency()
)
)
)
}
}
|
//
// RecordsViewController.swift
// deepstream iOS
//
// Created by Akram Hussein on 18/02/2017.
// Copyright © 2017 deepstreamHub GmbH. All rights reserved.
//
import UIKit
class RecordsViewController: UIViewController {
@IBOutlet weak var firstnameTextField: UITextField!
@IBOutlet weak var lastnameTextField: UITextField!
private var client : DeepstreamClient?
private var record : Record?
override func viewDidLoad() {
super.viewDidLoad()
// Get the pre-configured client
guard let client = DeepstreamFactory.getInstance().getClient(DeepstreamHubURL) else {
print("Error: Unable to initialize client")
return
}
self.client = client
/////////////////////////////////////////
// Create or retrieve a record with the name test/johndoe
// Get record handler
guard let record = self.client?.record.getRecord("test/johndoe") else {
return
}
self.record = record
// Create a RecordPathChangedCallback that will handle changes to a record path
final class NameRecordPathChangedCallback : NSObject, RecordPathChangedCallback {
var textField : UITextField!
init(textField: UITextField) {
self.textField = textField
super.init()
}
func onRecordPathChanged(_ recordName: String!, path: String!, data: JsonElement!) {
print("Record '\(recordName!)' changed, data is now: \(data)")
// Update text field in main thread
DispatchQueue.main.async {
self.textField.text = "\(data.getAsString()!)"
}
}
}
// Subscribe to changes for path 'firstname' and provide a callback to handle changes
record.subscribe("firstname", recordPathChangedCallback: NameRecordPathChangedCallback(textField: self.firstnameTextField))
// Subscribe to changes for path 'firstname' and provide a callback to handle changes
record.subscribe("lastname", recordPathChangedCallback: NameRecordPathChangedCallback(textField: self.lastnameTextField))
}
// We want to synchronize a path within the record, e.g. `firstname`
// with an input so that every change to the input will be saved to the
// record and every change from the record will be written to the input
@IBAction func editingChanged(_ sender: UITextField) {
// Identify which text field changed and set the relevant path
let path = (sender == self.firstnameTextField) ? "firstname" : "lastname"
// Set the record for the path
if let record = self.record {
record.set(path, value: sender.text)
}
}
}
|
//
// ChartVC.swift
// EidoSearch
//
// Created by Junius Gunaratne on 1/29/17.
// Copyright © 2017 Junius Gunaratne. All rights reserved.
//
import UIKit
import Charts
import RealmSwift
import MaterialComponents
public class EDSChartVC: UIViewController, ChartViewDelegate {
public let appBar = MDCAppBar()
var dates = NSMutableArray()
let infoLabel = UILabel()
var lineView: LineChartView!
let nameLabel = UILabel()
let priceLabel = UILabel()
let priceDescLabel = UILabel()
var timeButton = UIBarButtonItem()
private var _prediction = NSDictionary()
@objc public var prediction: NSDictionary {
get {
return _prediction
}
set(newValue) {
_prediction = newValue
}
}
private var _result = NSDictionary()
@objc public var result: NSDictionary {
get {
return _result
}
set(newValue) {
_result = newValue
}
}
private var _projectionType = EDSProjection.projection5D
@objc public var projectionType: EDSProjection {
get {
return _projectionType
}
set(newValue) {
_projectionType = newValue
var timeIcon = UIImage(named: "ic_looks_5_white")
switch (projectionType) {
case .projection1D:
timeIcon = UIImage(named: "ic_looks_1_white")
break
case .projection5D:
timeIcon = UIImage(named: "ic_looks_5_white")
break
case .projection1M:
timeIcon = UIImage(named: "ic_filter_1_white")
break
case .projection3M:
timeIcon = UIImage(named: "ic_filter_3_white")
break
case .projection6M:
timeIcon = UIImage(named: "ic_filter_6_white")
break
case .projection1Y:
timeIcon = UIImage(named: "ic_filter_1_white")
break
default:
break
}
timeButton.image = timeIcon
}
}
let bgColor = UIColor(
red: CGFloat(21) / CGFloat(255),
green: CGFloat(26) / CGFloat(255),
blue: CGFloat(31) / CGFloat(255),
alpha: 1)
override public var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
init() {
super.init(nibName: nil, bundle: nil)
self.addChildViewController(appBar.headerViewController)
appBar.headerViewController.headerView.backgroundColor = UIColor.clear
appBar.navigationBar.tintColor = UIColor.white
appBar.navigationBar.titleTextAttributes =
[ NSAttributedStringKey.foregroundColor: UIColor.white ]
appBar.navigationBar.titleAlignment = .leading
let timeIcon = UIImage(named: "ic_looks_5_white")
timeButton = UIBarButtonItem(image: timeIcon,
style: .done,
target: self,
action: #selector(didSelectTime))
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
@objc func didSelectTime() {
}
override public func viewDidLoad() {
super.viewDidLoad()
let contentView = UIView(frame: view.frame)
contentView.backgroundColor = bgColor
contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(contentView)
title = result["name"] as? String
let lineChartFrame = CGRect(x: -10,
y: -10,
width: view.frame.size.width + 20,
height: view.frame.size.height + 20)
lineView = LineChartView(frame: lineChartFrame)
lineView.delegate = self
lineView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
contentView.addSubview(lineView)
infoLabel.text = "Projected price shown in yellow. Upper line is projected high. Lower line is projected low. Middle line is projected average."
infoLabel.textColor = UIColor.white
infoLabel.font = UIFont.systemFont(ofSize: 10)
infoLabel.numberOfLines = 2
infoLabel.frame = CGRect(x: 30,
y: contentView.frame.size.height - 150,
width: contentView.frame.size.width - 60,
height: 100)
contentView.addSubview(infoLabel)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let patterns = prediction["patterns"] as! NSArray
let firstPattern = patterns[0] as! NSDictionary
let queryResults = firstPattern["queryResults"] as! NSArray
let firstResults = queryResults[0] as! NSDictionary
let dataSeries = firstResults["dataSeries"] as! NSArray
var chartDataEntryArray = Array<ChartDataEntry>()
for i in 0..<dataSeries.count {
let dataXY = dataSeries[i] as! [String:Any]
let dataX = dataXY["x"] as! String
let dataY = dataXY["y"] as! String
let date = dateFormatter.date(from: dataX)
let timeInterval = date?.timeIntervalSince1970
let dataEntry = ChartDataEntry.init(x: Double(timeInterval!),
y: Double(dataY)!, data: date as AnyObject?)
chartDataEntryArray.append(dataEntry)
}
let statistics = prediction["statistics"] as! NSArray
let firstStats = statistics[0] as! NSDictionary
let projectionData = firstStats["projectionData"] as! NSDictionary
let projectionTimeSeries = projectionData["projectionTimeSeries"] as! NSArray
var chartDataEntryArray2 = Array<ChartDataEntry>()
var lowerEntryArray = Array<ChartDataEntry>()
var upperEntryArray = Array<ChartDataEntry>()
for i in 0..<projectionTimeSeries.count {
let dataXY = projectionTimeSeries[i] as! [String:Any]
let dataY = dataXY["data"] as! NSNumber
let lowerY = dataXY["lower"] as! NSNumber
let upperY = dataXY["upper"] as! NSNumber
let dateString = dataXY["date"] as! NSString
let date = dateFormatter.date(from: dateString as String)
let timeInterval = date?.timeIntervalSince1970
let dataEntry = ChartDataEntry.init(x: Double(timeInterval!),
y: Double(truncating: dataY), data: date as AnyObject?)
chartDataEntryArray2.append(dataEntry)
let upperEntry = ChartDataEntry.init(x: Double(timeInterval!),
y: Double(truncating: upperY), data: date as AnyObject?)
upperEntryArray.append(upperEntry)
let lowerEntry = ChartDataEntry.init(x: Double(timeInterval!),
y: Double(truncating: lowerY), data: date as AnyObject?)
lowerEntryArray.append(lowerEntry)
}
updateChartWithData(chartDataEntryArray: chartDataEntryArray,
projectionEntryArray: chartDataEntryArray2,
upperEntryArray: upperEntryArray,
lowerEntryArray: lowerEntryArray)
appBar.addSubviewsToParent()
nameLabel.text = result["symbol"] as? String
nameLabel.font = UIFont.systemFont(ofSize: 24, weight: UIFont.Weight(rawValue: 0))
nameLabel.textColor = UIColor.white
nameLabel.sizeToFit()
let headerViewHeight = appBar.headerViewController.headerView.frame.size.height
nameLabel.frame = CGRect(x: 72,
y: headerViewHeight - 12,
width: nameLabel.frame.size.width,
height: 40)
contentView.addSubview(nameLabel)
priceLabel.text = result["price"] as? String
priceLabel.font = UIFont.systemFont(ofSize: 24, weight: UIFont.Weight(rawValue: 0))
priceLabel.textColor = UIColor.white
priceLabel.textAlignment = .right
contentView.addSubview(priceLabel)
priceDescLabel.text = ""
priceDescLabel.font = UIFont.systemFont(ofSize: 10, weight: UIFont.Weight(rawValue: 0))
priceDescLabel.textColor = UIColor.white
priceDescLabel.sizeToFit()
priceDescLabel.textAlignment = .right
contentView.addSubview(priceDescLabel)
}
func updateChartWithData(chartDataEntryArray: Array<ChartDataEntry>,
projectionEntryArray: Array<ChartDataEntry>,
upperEntryArray: Array<ChartDataEntry>,
lowerEntryArray: Array<ChartDataEntry>) {
let chartDataSet = LineChartDataSet(values: chartDataEntryArray, label: "History")
chartDataSet.setColor(UIColor.white)
chartDataSet.drawCirclesEnabled = false
chartDataSet.drawValuesEnabled = false
let chartDataSet2 = LineChartDataSet(values: projectionEntryArray, label: "Projection")
chartDataSet2.setColor(UIColor.white)
chartDataSet2.drawCirclesEnabled = false
chartDataSet2.drawValuesEnabled = false
let whiteAlpha = UIColor(white: 1, alpha: 0.25)
let upperDataSet = LineChartDataSet(values: upperEntryArray, label: "Upper")
upperDataSet.setColor(whiteAlpha)
upperDataSet.drawCirclesEnabled = false
upperDataSet.drawValuesEnabled = false
let lowerDataSet = LineChartDataSet(values: lowerEntryArray, label: "Lower")
lowerDataSet.setColor(whiteAlpha)
lowerDataSet.drawCirclesEnabled = false
lowerDataSet.drawValuesEnabled = false
let blue1 = UIColor(
red: CGFloat(16) / CGFloat(255),
green: CGFloat(159) / CGFloat(255),
blue: CGFloat(227) / CGFloat(255),
alpha: 1)
let blue2 = UIColor(
red: CGFloat(16) / CGFloat(255),
green: CGFloat(159) / CGFloat(255),
blue: CGFloat(227) / CGFloat(255),
alpha: 0)
let yellow1 = UIColor(
red: CGFloat(232) / CGFloat(255),
green: CGFloat(132) / CGFloat(255),
blue: CGFloat(33) / CGFloat(255),
alpha: 1)
let yellow2 = UIColor(
red: CGFloat(232) / CGFloat(255),
green: CGFloat(132) / CGFloat(255),
blue: CGFloat(33) / CGFloat(255),
alpha: 0)
let blueColors = [blue2.cgColor, blue1.cgColor] as CFArray
let blueColorSpace = CGColorSpaceCreateDeviceRGB()
let blueGradient = CGGradient(colorsSpace: blueColorSpace, colors: blueColors , locations: nil)
let yellowColors = [yellow2.cgColor, yellow1.cgColor] as CFArray
let yellowColorSpace = CGColorSpaceCreateDeviceRGB()
let yellowGradient = CGGradient(colorsSpace: yellowColorSpace, colors: yellowColors , locations: nil)
chartDataSet.fillAlpha = 1
chartDataSet.fill = Fill(linearGradient: blueGradient!, angle: 90)
chartDataSet.drawFilledEnabled = true
chartDataSet2.fillAlpha = 1
chartDataSet2.fill = Fill(linearGradient: yellowGradient!, angle: 90)
chartDataSet2.drawFilledEnabled = true
let chartData =
LineChartData(dataSets: [chartDataSet, chartDataSet2, upperDataSet, lowerDataSet])
lineView.data = chartData
lineView.borderColor = UIColor.white
lineView.backgroundColor = UIColor.clear
lineView.noDataTextColor = UIColor.white
lineView.pinchZoomEnabled = true
let xAxis = lineView.xAxis
xAxis.labelPosition = .bottomInside
xAxis.drawAxisLineEnabled = false
xAxis.drawGridLinesEnabled = false
xAxis.centerAxisLabelsEnabled = true
xAxis.labelTextColor = UIColor.white
xAxis.labelRotationAngle = 45
xAxis.gridColor = UIColor(white: 1, alpha: 0.1)
xAxis.valueFormatter = EDSDateValueFormatter()
let leftAxis = lineView.leftAxis
leftAxis.labelPosition = .insideChart
leftAxis.drawAxisLineEnabled = false
leftAxis.drawGridLinesEnabled = true
leftAxis.centerAxisLabelsEnabled = true
leftAxis.labelTextColor = UIColor.white
leftAxis.gridColor = UIColor(white: 1, alpha: 0.1)
let rightAxis = lineView.rightAxis
rightAxis.enabled = false
lineView.chartDescription?.enabled = false
let legend = lineView.legend
legend.enabled = false
lineView.setNeedsLayout()
}
override public var childViewControllerForStatusBarHidden: UIViewController? {
return appBar.headerViewController
}
override public var childViewControllerForStatusBarStyle: UIViewController? {
return appBar.headerViewController
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let lineChartFrame = CGRect(x: -10,
y: -10,
width: self.view.frame.size.width + 20,
height: self.view.frame.size.height + 20);
self.lineView.frame = lineChartFrame
priceDescLabel.frame = CGRect(x: 0,
y: 85,
width: self.view.frame.size.width - 50,
height: 40)
priceLabel.frame = CGRect(x: 0,
y: 62,
width: self.view.frame.size.width - 50,
height: 40)
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
let message = MDCSnackbarMessage()
message.text = "Tap on line for price. Pinch to zoom chart.";
message.duration = 2;
MDCSnackbarManager.show(message)
}
public func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
priceLabel.text = String(format: "%.2f", entry.y)
let date = entry.data as! Date
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
priceDescLabel.text = dateFormatter.string(from: date)
}
}
|
//
// ItemManager.swift
// Timer
//
// Created by Saga on 9/27/14.
// Copyright (c) 2014 Charles. All rights reserved.
//
import Foundation
import UIKit
class ItemManager: NSObject {
var items = [TimedItem]()
override init() {
items.append(TimedItem(tag: "Hello"))
items.append(TimedItem(tag: "World World World"))
}
} |
//
// main.swift
// test1
//
// Created by yunna on 2020/4/3.
// Copyright © 2020 yunna. All rights reserved.
//
import UIKit
UIApplicationMain(
CommandLine.argc,
UnsafeMutableRawPointer(CommandLine.unsafeArgv)
.bindMemory(
to: UnsafeMutablePointer<Int8>.self,
capacity: Int(CommandLine.argc)),
NSStringFromClass(MyApplication.self),
NSStringFromClass(AppDelegate.self)
)
|
//
// UIColor+Utils.swift
// Reddit
//
// Created by Suneeth on 9/19/20.
// Copyright © 2020 Suneeth. All rights reserved.
//
import UIKit
extension UIColor {
static var navigationBarbuttonTextColor: UIColor {
return #colorLiteral(red: 1, green: 0.3137254902, blue: 0.3137254902, alpha: 1)
}
static var navigationBarColor: UIColor {
return #colorLiteral(red: 0.9803921569, green: 0.9803921569, blue: 0.9803921569, alpha: 1)
}
}
|
//
// DateWrapped.swift
// ExchangeRates
//
// Created by Andrey Novikov on 9/5/20.
// Copyright © 2020 Andrey Novikov. All rights reserved.
//
import Foundation
struct DateWrapped {
let startDate: String
let endDate: String
let baseRate: String
let dates: [String]
}
|
import UIKit
import SnapKit
import ActionSheet
import ThemeKit
import HUD
import ComponentKit
import CurrencyKit
import RxSwift
class TransactionsViewController: ThemeViewController {
private let viewModel: TransactionsViewModel
private let disposeBag = DisposeBag()
private let headerView: TransactionsHeaderView
private let tableView = UITableView(frame: .zero, style: .plain)
private let emptyView = PlaceholderView()
private let typeFiltersView = FilterView(buttonStyle: .tab)
private let syncSpinner = HUDActivityView.create(with: .medium24)
private var sectionViewItems = [TransactionsViewModel.SectionViewItem]()
private var allLoaded = true
private var loaded = false
init(viewModel: TransactionsViewModel) {
self.viewModel = viewModel
headerView = TransactionsHeaderView(viewModel: viewModel)
super.init()
headerView.viewController = self
tabBarItem = UITabBarItem(title: "transactions.tab_bar_item".localized, image: UIImage(named: "filled_transaction_2n_24"), tag: 0)
navigationItem.largeTitleDisplayMode = .never
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "transactions.title".localized
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "button.reset".localized, style: .plain, target: self, action: #selector(onTapReset))
view.addSubview(tableView)
tableView.backgroundColor = .clear
if #available(iOS 15.0, *) {
tableView.sectionHeaderTopPadding = 0
}
tableView.separatorStyle = .none
tableView.backgroundColor = .clear
tableView.tableFooterView = UIView(frame: .zero)
tableView.estimatedRowHeight = 0
tableView.estimatedSectionHeaderHeight = 0
tableView.estimatedSectionFooterHeight = 0
tableView.delaysContentTouches = false
tableView.dataSource = self
tableView.delegate = self
tableView.registerCell(forClass: SpinnerCell.self)
tableView.registerCell(forClass: EmptyCell.self)
tableView.registerHeaderFooter(forClass: TransactionDateHeaderView.self)
view.addSubview(typeFiltersView)
typeFiltersView.snp.makeConstraints { maker in
maker.leading.trailing.equalToSuperview()
maker.top.equalTo(view.safeAreaLayoutGuide)
maker.height.equalTo(FilterView.height)
}
typeFiltersView.reload(filters: viewModel.typeFilterViewItems)
typeFiltersView.onSelect = { [weak self] index in
self?.viewModel.onSelectTypeFilter(index: index)
}
view.addSubview(headerView)
headerView.snp.makeConstraints { maker in
maker.leading.trailing.equalToSuperview()
maker.top.equalTo(typeFiltersView.snp.bottom)
maker.height.equalTo(CGFloat.heightSingleLineCell)
}
view.addSubview(emptyView)
emptyView.snp.makeConstraints { maker in
maker.top.equalTo(headerView.snp.bottom)
maker.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide)
}
emptyView.isHidden = true
let holder = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
holder.addSubview(syncSpinner)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: holder)
tableView.snp.makeConstraints { maker in
maker.top.equalTo(headerView.snp.bottom)
maker.leading.trailing.bottom.equalToSuperview()
}
subscribe(disposeBag, viewModel.typeFilterIndexDriver) { [weak self] index in
self?.typeFiltersView.select(index: index)
}
subscribe(disposeBag, viewModel.viewDataDriver) { [weak self] in self?.handle(viewData: $0) }
subscribe(disposeBag, viewModel.viewStatusDriver) { [weak self] in self?.sync(viewStatus: $0) }
subscribe(disposeBag, viewModel.resetEnabledDriver) { [weak self] in
self?.navigationItem.leftBarButtonItem?.isEnabled = $0
}
loaded = true
}
@objc private func onTapReset() {
viewModel.onTapReset()
}
private func itemClicked(item: TransactionsViewModel.ViewItem) {
if let record = viewModel.record(uid: item.uid) {
guard let module = TransactionInfoModule.instance(transactionRecord: record) else {
return
}
present(ThemeNavigationController(rootViewController: module), animated: true)
}
}
private func color(valueType: TransactionsViewModel.ValueType) -> UIColor {
switch valueType {
case .incoming: return .themeRemus
case .outgoing: return .themeLucian
case .neutral: return .themeLeah
case .secondary: return .themeGray
}
}
private func handle(viewData: TransactionsViewModel.ViewData) {
sectionViewItems = viewData.sectionViewItems
if let allLoaded = viewData.allLoaded {
self.allLoaded = allLoaded
}
guard loaded else {
return
}
if let updateInfo = viewData.updateInfo {
// print("Update Item: \(updateInfo.sectionIndex)-\(updateInfo.index)")
let indexPath = IndexPath(row: updateInfo.index, section: updateInfo.sectionIndex)
if let cell = tableView.cellForRow(at: indexPath) as? BaseThemeCell {
cell.bind(rootElement: rootElement(viewItem: sectionViewItems[updateInfo.sectionIndex].viewItems[updateInfo.index]))
}
} else {
// print("RELOAD TABLE VIEW")
tableView.reloadData()
}
}
private func sync(viewStatus: TransactionsViewModel.ViewStatus) {
syncSpinner.isHidden = !viewStatus.showProgress
if viewStatus.showProgress {
syncSpinner.startAnimating()
} else {
syncSpinner.stopAnimating()
}
if let messageType = viewStatus.messageType {
switch messageType {
case .syncing:
emptyView.image = UIImage(named: "clock_48")
emptyView.text = "transactions.syncing_text".localized
case .empty:
emptyView.image = UIImage(named: "outgoing_raw_48")
emptyView.text = "transactions.empty_text".localized
}
emptyView.isHidden = false
} else {
emptyView.isHidden = true
}
}
private func rootElement(viewItem: TransactionsViewModel.ViewItem) -> CellBuilderNew.CellElement {
.hStack([
.transactionImage { component in
component.set(progress: viewItem.progress)
switch viewItem.iconType {
case .icon(let imageUrl, let placeholderImageName):
component.setImage(
urlString: imageUrl,
placeholder: UIImage(named: placeholderImageName)
)
case .localIcon(let imageName):
component.set(image: imageName.flatMap { UIImage(named: $0)?.withTintColor(.themeLeah) })
case let .doubleIcon(frontType, frontUrl, frontPlaceholder, backType, backUrl, backPlaceholder):
component.setDoubleImage(
frontType: frontType,
frontUrl: frontUrl,
frontPlaceholder: UIImage(named: frontPlaceholder),
backType: backType,
backUrl: backUrl,
backPlaceholder: UIImage(named: backPlaceholder)
)
case .failedIcon:
component.set(image: UIImage(named: "warning_2_20")?.withTintColor(.themeLucian), contentMode: .center)
}
},
.margin(10),
.vStackCentered([
.hStack([
.text { component in
component.font = .body
component.textColor = .themeLeah
component.setContentCompressionResistancePriority(.required, for: .horizontal)
component.text = viewItem.title
},
.text { [weak self] component in
if let primaryValue = viewItem.primaryValue, !primaryValue.text.isEmpty {
component.isHidden = false
component.font = .body
component.textColor = self?.color(valueType: primaryValue.type) ?? .themeLeah
component.textAlignment = .right
component.lineBreakMode = .byTruncatingMiddle
component.text = primaryValue.text
} else {
component.isHidden = true
}
},
.margin8,
.image20 { component in
component.isHidden = !viewItem.sentToSelf
component.imageView.image = UIImage(named: "arrow_return_20")?.withTintColor(.themeGray)
},
.margin(6),
.image20 { component in
if let locked = viewItem.locked {
component.imageView.image = locked ? UIImage(named: "lock_20")?.withTintColor(.themeGray) : UIImage(named: "unlock_20")?.withTintColor(.themeGray)
component.isHidden = false
} else {
component.isHidden = true
}
}
]),
.margin(1),
.hStack([
.text { component in
component.font = .subhead2
component.textColor = .themeGray
component.setContentCompressionResistancePriority(.required, for: .horizontal)
component.text = viewItem.subTitle
},
.text { [weak self] component in
if let secondaryValue = viewItem.secondaryValue, !secondaryValue.text.isEmpty {
component.isHidden = false
component.font = .subhead2
component.textColor = self?.color(valueType: secondaryValue.type) ?? .themeLeah
component.textAlignment = .right
component.lineBreakMode = .byTruncatingMiddle
component.text = secondaryValue.text
} else {
component.isHidden = true
}
}
])
])
])
}
}
extension TransactionsViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
sectionViewItems.count + (allLoaded ? 0 : 1) + 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section < sectionViewItems.count {
return sectionViewItems[section].viewItems.count
} else {
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section < sectionViewItems.count {
return CellBuilderNew.preparedCell(
tableView: tableView,
indexPath: indexPath,
selectable: true,
rootElement: rootElement(viewItem: sectionViewItems[indexPath.section].viewItems[indexPath.row]),
layoutMargins: UIEdgeInsets(top: 0, left: .margin6, bottom: 0, right: .margin16)
)
} else if indexPath.section == numberOfSections(in: tableView) - 1 {
return tableView.dequeueReusableCell(withIdentifier: String(describing: EmptyCell.self), for: indexPath)
} else {
return tableView.dequeueReusableCell(withIdentifier: String(describing: SpinnerCell.self), for: indexPath)
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.section < sectionViewItems.count {
let viewItems = sectionViewItems[indexPath.section].viewItems
let viewItem = viewItems[indexPath.row]
if let cell = cell as? BaseThemeCell {
cell.set(backgroundStyle: .bordered, isFirst: indexPath.row == 0, isLast: indexPath.row == viewItems.count - 1)
cell.bind(rootElement: rootElement(viewItem: viewItem))
}
viewModel.onDisplay(sectionIndex: indexPath.section, index: indexPath.row)
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section < sectionViewItems.count {
tableView.deselectRow(at: indexPath, animated: true)
itemClicked(item: sectionViewItems[indexPath.section].viewItems[indexPath.row])
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
indexPath.section < sectionViewItems.count ? .heightDoubleLineCell : .margin32
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
section < sectionViewItems.count ? .heightSingleLineCell : 0
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section < sectionViewItems.count {
return tableView.dequeueReusableHeaderFooterView(withIdentifier: String(describing: TransactionDateHeaderView.self))
} else {
return nil
}
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let view = view as? TransactionDateHeaderView else {
return
}
view.text = sectionViewItems[section].title
}
}
|
//
// RunLoopWaiter.swift
// RunLoopWaiter
//
// Created by muukii on 2020/10/08.
//
import Foundation
import Foundation
public final class Expectation {
var fulfilled: Bool = false
public func fulfill() {
fulfilled = true
}
}
public final class Waiter {
private var runloop: RunLoop?
func wait(for expectations: [Expectation]) {
let runloop = RunLoop.current
self.runloop = runloop
var isFinished: Bool {
!expectations.contains(where: { !$0.fulfilled })
}
while !isFinished {
runloop.run(mode: .default, before: Date(timeIntervalSinceNow: 0.1))
}
}
}
extension RunLoop {
public func wait<Result>(
resultType: Result.Type? = nil,
perform: @escaping (_ fullfill: @escaping (Result) -> Void) -> Void
) -> Result {
var result: Result!
let runLoopModeRaw = RunLoop.Mode.default.rawValue._bridgeToObjectiveC()
let cfRunLoop = getCFRunLoop()
CFRunLoopPerformBlock(getCFRunLoop(), runLoopModeRaw) {
perform { r in
result = r
CFRunLoopPerformBlock(cfRunLoop, runLoopModeRaw) {
CFRunLoopStop(cfRunLoop)
}
CFRunLoopWakeUp(cfRunLoop)
}
}
CFRunLoopWakeUp(cfRunLoop)
CFRunLoopRun()
return result
}
}
|
//
// AuthError.swift
// Chimp (iOS)
//
// Created by Sean on 21.10.20.
//
import Foundation
enum AuthErrors: String, Error {
case userNotFound = "We are unable to find any account with this email & password combination."
case userAlreadyExists = "This account already exists!"
case incorrectInputSignIn = "Sign in error - data isn't valid! Make sure to fill in all necessary field(s) correctly!"
case incorrectInputSignUp = "Sign up error - data isn't valid! Make sure to fill in all necessary field(s) correctly!"
}
enum DeauthErrors: String, Error{
case userUidNotFound = "user_uid does not exist in db!"
case incorrectInputSignUp = "Sign up error - data isn't valid! Make sure to fill in all necessary field(s) correctly!"
}
extension AuthErrors: LocalizedError {
var errorDescription: String? {return NSLocalizedString(rawValue, comment: "")}
}
extension DeauthErrors: LocalizedError {
var errorDescription: String? {return NSLocalizedString(rawValue, comment: "")}
}
|
class Solution {
private let bits = [1, 2, 4, 8, 16, 32]
func readBinaryWatch(_ num: Int) -> [String] {
guard num > 0 else { return ["0:00"] }
var result = [String]()
func minutes(_ i: Int, _ n: Int, _ h: Int, _ m: Int) {
guard m < 60 else { return }
if i <= 6, n == num {
let m = m < 10 ? "0\(m)" : "\(m)"
result.append("\(h):\(m)")
return
} else if i >= 6 || n > num { return }
minutes(i + 1, n, h, m)
minutes(i + 1, n + 1, h, m + bits[i])
}
func hours(_ i: Int, _ n: Int, _ h: Int) {
guard h < 12 else { return }
if i == 4, n <= num {
minutes(0, n, h, 0)
return
} else if i >= 4 || n > num { return }
hours(i + 1, n, h)
hours(i + 1, n + 1, h + bits[i])
}
hours(0, 0, 0)
return result
}
}
print(Solution().readBinaryWatch(1)) |
//
// AssetsDetailViewModel.swift
// DevBoostItau-Project1
//
// Created by Helio Junior on 05/09/20.
// Copyright © 2020 DevBoost-Itau. All rights reserved.
//
import Foundation
class AssetsDetailViewModel {
let repository: AssetDetailRepository!
private var asset: AssetModel?
private var stockPrice: StockPrice?
init(assetModel: AssetModel?, _ repository: AssetDetailRepository = AssetDetailRepository()) {
self.asset = assetModel
self.repository = repository
}
var onSuccess: (() -> Void)?
var onFail: ((String) -> Void)?
func getStockPrice() {
guard let code = asset?.brokerName else {return}
repository.getStockPrice(code: code, onSuccess: { [weak self] stockPrice in
self?.stockPrice = stockPrice
self?.onSuccess?()
}) { [weak self] error in
self?.onFail?(error)
}
}
func getAssetName() -> String?{
return asset?.brokerName
}
func getAssetDetail() -> AssetDetail? {
guard let asset = asset, let stockPrice = stockPrice else {return nil}
return AssetDetail(name: stockPrice.getName,
quantity: "\(asset.quantityOfStocks)",
pricePurchase: asset.getPricePurchase(),
datePurchase: asset.getDatePurchase(),
totalValuePurchase: asset.getTotalValuePurchase(),
dateToday: asset.dateFormatter.string(from: Date()),
valueToday: getTotalValueToday(),
rentability: getRentability(),
hasPositiveResults: getRentabilityValue() >= 0 ? true : false,
investment: asset.investment)
}
func getTotalValueToday() -> String {
let quantity = Double(asset?.quantityOfStocks ?? 0)
let priceToday = stockPrice?.getPriceNumber ?? 0.0
let totalValue = quantity * priceToday
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale(identifier: "pt_BR")
return formatter.string(from: NSNumber(value: totalValue)) ?? "R$ 0,00"
}
func getRentabilityValue() -> Double {
let quantity = Double(asset?.quantityOfStocks ?? 0)
let pricePurchase = asset?.purchasePrice ?? 0
let priceToday = stockPrice?.getPriceNumber ?? 0.0
let totalPurchase = quantity * pricePurchase
let totalToday = quantity * priceToday
let rentability = ((totalToday * 100) / totalPurchase) - 100
return rentability
}
func getRentability() -> String {
let rentability = getRentabilityValue()
return "\(Int(rentability))%"
}
}
|
//
// TableViewCellClass.swift
// VideosApp
//
// Created by Usama on 11/02/2021.
//
import UIKit
import AVKit
class HomeCollectionViewCell: UICollectionViewCell {
//MARK:- @IBOutlets
@IBOutlet weak var homePlayerView: HomePlayerView!
@IBOutlet weak var likesLabel: UILabel!
@IBOutlet weak var likeButton: UIButton!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var userImageView: UIImageView!
//MARK:-Class Properties
var homeLikedVideosArray : [VideosModel]?
var videoID: String?
var likesCount: Int?
//MARK:- Class Methods
func configureCell(video: VideosModel) {
let url = NSURL(string: (video.url ?? "")!)
let avPlayer = AVPlayer(url: url! as URL)
self.homePlayerView.playerLayer.frame = self.bounds
self.homePlayerView.playerLayer.player = avPlayer
self.layer.cornerRadius = 10
if let vidID = video.id{
videoID = vidID
}
likesCount = video.likesCount
}
func likedVideosUpdate(likedVideo: [VideosModel]){
likedVideo.forEach { (likedVideo) in
if likedVideo.likedVideoCheck == true{
likeButton.setTitleColor(.systemBlue, for: .normal)
likeButton.setTitle("Liked", for: .normal)
}
}
}
func homeImageUser(userData: UserInfo){
self.usernameLabel.text = userData.firstName
if let imageURL = URL(string: userData.imageURL ?? "")
{
let data = try? Data(contentsOf: imageURL)
self.userImageView?.image = UIImage(data: data ?? Data())
}
self.userImageView.clipsToBounds = true
self.userImageView.layer.masksToBounds = true
self.userImageView.layer.cornerRadius = self.userImageView.frame.width/2
self.usernameLabel.font = UIFont.boldSystemFont(ofSize: 20.0)
}
//MARK:- @IBActions
@IBAction func likeButtonPressed(_ sender: Any) {
let videoViewModel = VideoViewModel()
if likeButton.currentTitle == "Liked"{
likesCount! -= 1
videoViewModel.updataLikesCount(videoID: videoID ?? "", likesCount: likesCount ?? 0, isLiked: true) { (response) in
if response == true {
if let likes = self.likesCount {
self.likesLabel.text = "\(likes) Likes"
self.likeButton.setTitleColor(.black, for: .normal)
self.likeButton.setTitle("Like", for: .normal)
}
}
}
}
else {
likesCount! += 1
videoViewModel.updataLikesCount(videoID: videoID ?? "", likesCount: likesCount ?? 0, isLiked: false) { [self] (bool) in
if bool == true {
if let likes = likesCount{
self.likesLabel.text = "\(likes) Likes"
self.likeButton.setTitleColor(.systemBlue, for: .normal)
self.likeButton.setTitle("Liked", for: .normal)
}
}
}
}
videoViewModel.myLikedVideos(videoID: videoID ?? "")
}
}
|
//
// ChapterNavigatorViewController.swift
// ScriptureMap
//
// Created by Cole Fox on 11/16/17.
// Copyright © 2017 Cole Fox. All rights reserved.
//
import Foundation
import UIKit
class ChapterNavigatorViewController : UITableViewController {
//MARK: Properties
var chapters: [Int]?
var bookId: Int?
//TODO: show title if applicable (ie introduction)
//MARK: Storyboard
struct storyboard {
static let navCellId = "ChapterNavCell"
}
//MARK: VC lifecycle
override func viewDidLoad() {
super.viewDidLoad()
if let ID = bookId {
chapters = GeoDatabase.sharedGeoDatabase.getChaptersForBook(bookId: ID)
if chapters?.count == 1 {
performSegue(withIdentifier: "SingleChapter", sender: self)
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationViewController = segue.destination as? ScriptureNavigationViewController {
destinationViewController.book = bookId
if segue.identifier == "SingleChapter" {
destinationViewController.chapter = 0
} else {
destinationViewController.chapter = (tableView.indexPathForSelectedRow?.row)! + 1
}
}
}
//MARK: Config
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return chapters!.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: storyboard.navCellId)!
cell.textLabel?.text = "Chapter \(chapters![indexPath.row])"
//TODO:append chapter with book name
//TODO:use section for D&C
return cell
}
}
|
//
// FriendViewController.swift
// Live-zzu
//
// Created by 如是我闻 on 2017/5/5.
// Copyright © 2017年 如是我闻. All rights reserved.
//
import UIKit
class FriendViewController: UIViewController,UIPopoverPresentationControllerDelegate {
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var firstView: UIView!
@IBOutlet weak var secondView: UIView!
@IBOutlet weak var btn: UIButton!
@IBAction func indexChanged(_ sender: UISegmentedControl) {
switch segmentedControl.selectedSegmentIndex
{
case 0:
firstView.isHidden = false
secondView.isHidden = true
case 1:
firstView.isHidden = true
secondView.isHidden = false
default:
break;
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func btnTap(_ sender: Any) {
let pop = PopViewController()
pop.modalPresentationStyle = .popover
pop.popoverPresentationController?.delegate = self
pop.popoverPresentationController?.sourceView = btn
pop.popoverPresentationController?.sourceRect = btn.bounds
pop.preferredContentSize = CGSize(width: 150, height: 150)
self.present(pop, animated: true, completion: nil)
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// LocalizedStringResource.swift
// Resource
//
// Created by Justin Jia on 11/6/16.
// Copyright © 2016 TintPoint. MIT license.
//
/// A protocol that describes an item that can represent a localized string.
public protocol LocalizedStringDescribing {
/// The `String` that represents the key of the localized string.
var key: String { get }
/// The `String` that represents the table name of the localized string.
var tableName: String? { get }
/// The `Bundle` that represents the bundle of the localized string.
var bundle: Bundle { get }
/// The `String` that represents the value of the localized string.
var value: String { get }
/// The `String` that represents the comment of the localized string.
var comment: String { get }
/// The array of `Any` that represents the arguments of the localized string.
var arguments: [Any]? { get }
}
public extension LocalizedStringDescribing {
var tableName: String? {
return nil
}
var bundle: Bundle {
return .main
}
var value: String {
return ""
}
var comment: String {
return ""
}
var arguments: [Any]? {
return nil
}
}
/// A struct that describes an item that can represent a localized string.
public struct LocalizedStringDescription: LocalizedStringDescribing {
/// The `String` that represents the key of the localized string.
public let key: String
/// The `String` that represents the table name of the localized string.
public let tableName: String?
/// The `Bundle` that represents the bundle of the localized string.
public let bundle: Bundle
/// The `String` that represents the value of the localized string.
public let value: String
/// The `String` that represents the comment of the localized string.
public let comment: String
/// The array of `Any` that represents the arguments of the localized string.
public let arguments: [Any]?
public init(key: String, tableName: String? = nil, bundle: Bundle = .main, value: String = "", comment: String = "", arguments: [Any]? = nil) {
self.key = key
self.tableName = tableName
self.bundle = bundle
self.value = value
self.comment = comment
self.arguments = arguments
}
}
public extension Resource {
/// Returns a `String` that is represented by the item that conforms to `LocalizedStringDescribing`.
/// - Parameter describing: An item that conforms to `LocalizedStringDescribing`.
/// - Returns: A represented localized string.
static func of(_ describing: LocalizedStringDescribing) -> String {
let localizedString = NSLocalizedString(describing.key, tableName: describing.tableName, bundle: describing.bundle, value: describing.value, comment: describing.comment)
guard let arguments = describing.arguments as? [CVarArg] else {
return localizedString
}
return String(format: localizedString, arguments: arguments)
}
}
|
enum CheckInServiceError: Error {
case unknown
case notCheckedIn
}
|
//
// RoundedEdge.swift
// ReaderTranslator
//
// Created by Viktor Kushnerov on 18/1/20.
// Copyright © 2020 Viktor Kushnerov. All rights reserved.
//
import SwiftUI
struct RoundedEdge: ViewModifier {
let width: CGFloat
let color: Color
let cornerRadius: CGFloat
func body(content: Content) -> some View {
content
.cornerRadius(cornerRadius - width)
.padding(width)
.background(color)
.cornerRadius(cornerRadius)
}
}
|
import UIKit
protocol GroupedDomainDataSourceDelegate: UITableViewController {
/// Currently only called when a row is moved and the `tableView` is frontmost.
func groupedDomainDataSource(needsUpdate row: Int)
}
// ##########################
// #
// # MARK: DataSource
// #
// ##########################
class GroupedDomainDataSource: FilterPipelineDelegate, SyncUpdateDelegate {
let parent: String?
private let pipeline = FilterPipeline<GroupedDomain>()
private var currentOrder: DateFilterOrderBy = .Date
private var orderAsc = false
private(set) lazy var search = SearchBarManager { [unowned self] _ in
self.pipeline.reloadFilter(withId: "search")
}
/// Will init `sync.allowPullToRefresh()` on `tableView.refreshControl` as well.
weak var delegate: GroupedDomainDataSourceDelegate? {
willSet { if #available(iOS 10.0, *), newValue !== delegate {
sync.allowPullToRefresh(onTVC: newValue, forObserver: self)
}}}
/// - Note: Will call `tableview.reloadData()`
init(withParent: String?) {
parent = withParent
let len: Int
if let p = withParent, p.first != "#" { len = p.count } else { len = 0 }
pipeline.addFilter("search") { [unowned self] in
!self.search.isActive ||
$0.domain.prefix($0.domain.count - len).lowercased().contains(self.search.term)
}
pipeline.delegate = self
resetSortingOrder(force: true)
NotifyDNSFilterChanged.observe(call: #selector(didChangeDomainFilter), on: self)
NotifySortOrderChanged.observe(call: #selector(didChangeSortOrder), on: self)
sync.addObserver(self) // calls syncUpdate(reset:)
}
/// Callback fired when user changes date filter settings. (`NotifySortOrderChanged` notification)
@objc private func didChangeSortOrder(_ notification: Notification) {
resetSortingOrder()
}
/// Read user defaults and apply new sorting order. Either by setting a new or reversing the current.
/// - Parameter force: If `true` set new sorting even if the type does not differ.
private func resetSortingOrder(force: Bool = false) {
let orderAscChanged = (orderAsc <-? Prefs.DateFilter.OrderAsc)
let orderTypChanged = (currentOrder <-? Prefs.DateFilter.OrderBy)
if orderTypChanged || force {
switch currentOrder {
case .Date:
pipeline.setSorting { [unowned self] in
self.orderAsc ? $0.lastModified < $1.lastModified : $0.lastModified > $1.lastModified
}
case .Name:
pipeline.setSorting { [unowned self] in
self.orderAsc ? $0.domain < $1.domain : $0.domain > $1.domain
}
case .Count:
pipeline.setSorting { [unowned self] in
self.orderAsc ? $0.total < $1.total : $0.total > $1.total
}
}
} else if orderAscChanged {
pipeline.reverseSorting()
}
}
/// Callback fired when user edits list of `blocked` or `ignored` domains in settings. (`NotifyDNSFilterChanged` notification)
@objc private func didChangeDomainFilter(_ notification: Notification) {
guard let domain = notification.object as? String else {
preconditionFailure("Domain independent filter reset not implemented") // `syncUpdate(reset:)` async!
}
if let x = pipeline.dataSourceGet(where: { $0.domain == domain }) {
var obj = x.object
obj.options = DomainFilter[domain]
pipeline.update(obj, at: x.index)
}
}
// MARK: Table View Data Source
@inline(__always) var numberOfRows: Int { get { pipeline.displayObjectCount() } }
@inline(__always) subscript(_ row: Int) -> GroupedDomain { pipeline.displayObject(at: row) }
}
// ################################
// #
// # MARK: - Partial Update
// #
// ################################
extension GroupedDomainDataSource {
func syncUpdate(_: SyncUpdate, reset rows: SQLiteRowRange) {
var logs = AppDB?.dnsLogsGrouped(range: rows, parentDomain: parent) ?? []
for (i, val) in logs.enumerated() {
logs[i].options = DomainFilter[val.domain]
}
DispatchQueue.main.sync {
pipeline.reset(dataSource: logs)
}
}
func syncUpdate(_: SyncUpdate, insert rows: SQLiteRowRange, affects: SyncUpdateEnd) {
guard let latest = AppDB?.dnsLogsGrouped(range: rows, parentDomain: parent) else {
assertionFailure("NotifySyncInsert fired with empty range")
return
}
DispatchQueue.main.sync {
cellAnimationsGroup(if: latest.count > 14)
for x in latest {
if let (i, obj) = pipeline.dataSourceGet(where: { $0.domain == x.domain }) {
pipeline.update(obj + x, at: i)
} else {
var y = x
y.options = DomainFilter[x.domain]
pipeline.addNew(y)
}
}
cellAnimationsCommit()
}
}
func syncUpdate(_ sender: SyncUpdate, remove rows: SQLiteRowRange, affects: SyncUpdateEnd) {
if affects == .Latest {
// TODO: alternatively query last modified from db (last entry _before_ range)
syncUpdate(sender, reset: sender.rows)
return
}
guard let outdated = AppDB?.dnsLogsGrouped(range: rows, parentDomain: parent),
outdated.count > 0 else {
return
}
DispatchQueue.main.sync {
cellAnimationsGroup(if: outdated.count > 14)
var listOfDeletes: [Int] = []
for x in outdated {
guard let (i, obj) = pipeline.dataSourceGet(where: { $0.domain == x.domain }) else {
assertionFailure("Try to remove non-existent element")
continue // should never happen
}
if obj.total > x.total {
pipeline.update(obj - x, at: i)
} else {
listOfDeletes.append(i)
}
}
pipeline.remove(indices: listOfDeletes.sorted())
cellAnimationsCommit()
}
}
func syncUpdate(_ sender: SyncUpdate, partialRemove affectedFQDN: String) {
let affectedParent = affectedFQDN.extractDomain()
guard parent == nil || parent == affectedParent else {
return // does not affect current table
}
let affected = (parent == nil ? affectedParent : affectedFQDN)
let updated = AppDB?.dnsLogsGrouped(range: sender.rows, matchingDomain: affected, parentDomain: parent)?.first
DispatchQueue.main.sync {
guard let old = pipeline.dataSourceGet(where: { $0.domain == affected }) else {
// can only happen if delete sheet is open while background sync removed the element
return
}
if var updated = updated {
assert(old.object.domain == updated.domain)
updated.options = DomainFilter[updated.domain]
pipeline.update(updated, at: old.index)
} else {
pipeline.remove(indices: [old.index])
}
}
}
}
// #################################
// #
// # MARK: - Cell Animations
// #
// #################################
extension GroupedDomainDataSource {
/// Sets `pipeline.delegate = nil` to disable individual cell animations (update, insert, delete & move).
private func cellAnimationsGroup(if condition: Bool = true) {
if condition || delegate?.tableView.isFrontmost == false {
pipeline.delegate = nil
}
}
/// No-Op if cell animations are enabled already.
/// Else, set `pipeline.delegate = self` and perform `reloadData()`.
private func cellAnimationsCommit() {
if pipeline.delegate == nil {
pipeline.delegate = self
delegate?.tableView.reloadData()
}
}
// TODO: Collect animations and post them in a single animations block.
// This will require enormous work to translate them into a final set.
func filterPipelineDidReset() { delegate?.tableView.reloadData() }
func filterPipeline(delete rows: [Int]) { delegate?.tableView.safeDeleteRows(rows) }
func filterPipeline(insert row: Int) { delegate?.tableView.safeInsertRow(row, with: .left) }
func filterPipeline(update row: Int) {
guard let tv = delegate?.tableView else { return }
if !tv.isEditing { tv.safeReloadRow(row) }
else if tv.isFrontmost == true {
delegate?.groupedDomainDataSource(needsUpdate: row)
}
}
func filterPipeline(move oldRow: Int, to newRow: Int) {
delegate?.tableView.safeMoveRow(oldRow, to: newRow)
if delegate?.tableView.isFrontmost == true {
delegate?.groupedDomainDataSource(needsUpdate: newRow)
}
}
}
// ##########################
// #
// # MARK: - Edit Row
// #
// ##########################
protocol GroupedDomainEditRow : UIViewController, EditableRows {
var source: GroupedDomainDataSource { get }
}
extension GroupedDomainEditRow {
func editableRowActions(_ index: IndexPath) -> [(RowAction, String)] {
let x = source[index.row]
if x.domain.starts(with: "#") {
return [(.delete, "Delete")]
}
let b = x.options?.contains(.blocked) ?? false
let i = x.options?.contains(.ignored) ?? false
return [(.delete, "Delete"), (.block, b ? "Unblock" : "Block"), (.ignore, i ? "Unignore" : "Ignore")]
}
func editableRowActionColor(_: IndexPath, _ action: RowAction) -> UIColor? {
action == .block ? .systemOrange : nil
}
func editableRowUserInfo(_ index: IndexPath) -> Any? { source[index.row] }
func editableRowCallback(_ index: IndexPath, _ action: RowAction, _ userInfo: Any?) -> Bool {
let entry = userInfo as! GroupedDomain
switch action {
case .ignore: showFilterSheet(entry, .ignored)
case .block: showFilterSheet(entry, .blocked)
case .delete:
let name = entry.domain
let flag = (source.parent != nil)
AlertDeleteLogs(name, latest: entry.lastModified) {
TheGreatDestroyer.deleteLogs(domain: name, since: $0, strict: flag)
}.presentIn(self)
}
return true
}
private func showFilterSheet(_ entry: GroupedDomain, _ filter: FilterOptions) {
if entry.options?.contains(filter) ?? false {
DomainFilter.update(entry.domain, remove: filter)
} else {
// TODO: alert sheet
DomainFilter.update(entry.domain, add: filter)
}
}
}
// MARK: Extensions
extension TVCDomains : GroupedDomainEditRow {
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
getRowActionsIOS9(indexPath, tableView)
}
@available(iOS 11.0, *)
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
getRowActionsIOS11(indexPath)
}
}
extension TVCHosts : GroupedDomainEditRow {
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
getRowActionsIOS9(indexPath, tableView)
}
@available(iOS 11.0, *)
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
getRowActionsIOS11(indexPath)
}
}
|
//
// HUD.swift
// Rocket Simulation
//
// Created by Sam Bunger on 10/19/18.
// Copyright © 2018 Samster. All rights reserved.
//
import Foundation
import SpriteKit
class HUD{
//Content
private var map:Map
private let sol:System
private let cam:SKCameraNode
private let gameArea:CGRect
//Time Skipping
private let leftSkip = SKSpriteNode(imageNamed: "timeSkipLeft")
private let rightSkip = SKSpriteNode(imageNamed: "timeSkipRight")
private let timeSkipBG = SKSpriteNode(imageNamed: "timeSkip")
private var skipValue:CGFloat = 1
private var skipIndex:CGFloat = 0
private let skipLabel = SKLabelNode(fontNamed: "KoHo-Light")
//Formatting
private let hudZ = CGFloat(10)
init(system:System, rocket:Rocket, cam:SKCameraNode, gameArea:CGRect){
self.sol = system
self.cam = cam
self.map = Map(system: system, cam: cam, rocket: rocket)
self.map.setCamPos(to: sol.pos(of: "Earth"))
self.gameArea = gameArea
format()
}
func format(){
self.cam.addChild(timeSkipBG)
timeSkipBG.setScale(1.4)
let tsp = CGPoint(x:gameArea.size.width/2 - timeSkipBG.size.width/2, y:gameArea.size.height/2 - timeSkipBG.size.height/2 + 3)
timeSkipBG.position = tsp
timeSkipBG.zPosition = hudZ
timeSkipBG.addChild(rightSkip)
timeSkipBG.addChild(leftSkip)
timeSkipBG.addChild(skipLabel)
rightSkip.position = CGPoint(x: 85, y: 3)
rightSkip.zPosition = hudZ
leftSkip.position = CGPoint(x: -75, y: 3)
leftSkip.zPosition = hudZ
skipLabel.zPosition = hudZ
skipLabel.position = CGPoint(x: 0, y: -10)
updateSkipValue()
map.activate()
}
func touchesBegan(touch: AnyObject, mainPoint: CGPoint){
map.touchesBegan(touch: mainPoint)
}
func touchesEnded(touch: AnyObject, mainPoint: CGPoint){
let skip = touch.location(in: timeSkipBG)
//Left Time Skip
if rightSkip.contains(skip){
print("Skip Right")
skipRight()
}
//Right Time Skip
if leftSkip.contains(skip){
print("Skip Left")
skipLeft()
}
map.touchesEnded(touch: touch)
}
func mapSet(on:Bool){
if(on){
map.activate()
}else{
map.deactivate()
}
}
func touchesMoved(x: CGFloat, y: CGFloat) {
if(map.isActive()){
map.touchesMoved(x: x, y: y)
}
}
func update(ct:CGFloat){
if(map.isActive()){
map.update(ct: ct)
}
}
func scaleMap(scale:CGFloat){
if(map.isActive()){
map.zoom(scale: scale)
}
}
func skipRight(){
if skipValue < 10000000{
skipIndex += 1
skipValue = pow(8, skipIndex)
}
updateSkipValue()
}
func skipLeft(){
if skipValue > 1{
skipIndex -= 1
skipValue = pow(8, skipIndex)
}
updateSkipValue()
}
func updateSkipValue(){
skipLabel.text = "x\(skipIndex)"
}
func getMultiplyer()->CGFloat{
return skipValue
}
}
|
//
// RegularButton.swift
// 100Views
//
// Created by Mark Moeykens on 6/5/19.
// Copyright © 2019 Mark Moeykens. All rights reserved.
//
import SwiftUI
struct RegularButton : View {
var body: some View {
VStack(spacing: 20) {
Text("Button")
.font(.largeTitle)
Text("Introduction")
.foregroundColor(.gray)
Text("If you just want to show the default text style in a button then you can pass in a string as the first parameter.")
.padding().frame(maxWidth: .infinity)
.background(Color.purple)
.foregroundColor(.white)
.layoutPriority(2)
Button("Default Button Style") {
// Your code here
}
Text("You can customize the text shown for a button.")
.padding().frame(maxWidth: .infinity)
.background(Color.purple).layoutPriority(1)
.foregroundColor(.white)
Button(action: {
// Your code here
}) {
Text("Headline Font")
.font(.headline)
}
Divider()
Button(action: {}) {
Text("Foreground Color")
.foregroundColor(Color.red)
}
Divider()
Button(action: {}) {
Text("Thin Font Weight")
.fontWeight(.thin)
}
}.font(.title) // Make all fonts use the title style
}
}
#if DEBUG
struct RegularButton_Previews : PreviewProvider {
static var previews: some View {
RegularButton()
}
}
#endif
|
//
// Direction.swift
// ToyRobotSimulator
//
// Created by Rameez Hassan on 21/9/20.
// Copyright © 2020 Rameez Hassan. All rights reserved.
//
import Foundation
/// Facing Direction Of the Robot
enum Direction: String {
case north = "NORTH", /// facing upwards
east = "EAST", /// facing right
south = "SOUTH", /// facing downward
west = "WEST" /// facing left
}
extension Direction {
/// Function to change direction to left
mutating func turnLeft() {
switch self {
case .north:
self = .west
case .south:
self = .east
case .east:
self = .north
case .west:
self = .south
}
}
/// Function to change direction to right
mutating func turnRight() {
switch self {
case .north:
self = .east
case .south:
self = .west
case .east:
self = .south
case .west:
self = .north
}
}
}
|
//
// TransactionsListPresenter.swift
// Transactions
//
// Created by Thiago Santiago on 1/17/19.
// Copyright © 2019 Thiago Santiago. All rights reserved.
//
import UIKit
protocol TransactionListPresentationLogic {
func closeLoadingView()
func presentLoadingView()
func presentUser(_ image: UIImage)
func presentList(_ transactions: TransactionList)
func presentError(_ error: TransactionsAPIError)
}
class TransactionListPresenter: TransactionListPresentationLogic {
weak var viewController: TransactionsListDisplayLogic?
var totalBalance = 0.0
func closeLoadingView() {
viewController?.hideLoadingView()
}
func presentLoadingView() {
viewController?.displayLoadingView()
}
func presentUser(_ image: UIImage) {
viewController?.displayUser(image: image)
}
func presentList(_ transactions: TransactionList) {
viewController?.displayTransactions(list: treatTransactionData(transactions))
}
func treatTransactionData(_ data: TransactionList) -> TransactionsListViewModel {
var balance = 0.0
var transactions: [TransactionViewModel] = []
for transaction in data.transactions {
var latitude = 0.0
var longitude = 0.0
let dateFormatted = transaction.date.formatDateString()
let amoutFormatted = transaction.amount.formatCurrency()
let effectiveDateFormatted = transaction.effectiveDate.formatDateString()
let transactionType: TransactionType = transaction.amount.contains("-") ? .debit : .credit
if transaction.coordinates.extractCoordinates().count == 2 {
latitude = Double(transaction.coordinates.extractCoordinates()[1]) ?? 0.0
longitude = Double(transaction.coordinates.extractCoordinates()[0]) ?? 0.0
}
let viewModel = TransactionViewModel(date: dateFormatted,
amount: amoutFormatted,
description: transaction.description,
latitude: latitude,
longitude: longitude,
effectiveDate: effectiveDateFormatted, transactionType: transactionType)
transactions.append(viewModel)
let amount = Double(transaction.amount.replacingOccurrences(of: ",", with: ".")) ?? 0.0
balance += amount
}
self.totalBalance += balance
return TransactionsListViewModel(transactions: transactions,
nextPage: data.nextPage,
totalBalance: self.totalBalance.formattedToCurrency)
}
func presentError(_ error: TransactionsAPIError) {
viewController?.displayError(message: error.errorMessage)
}
}
|
//
// PickedCardDialogViewController.swift
// PlanningPoker
//
// Created by david.gonzalez on 28/10/16.
// Copyright © 2016 BEEVA. All rights reserved.
//
import UIKit
class PickedCardDialogViewController: BaseUIViewController {
@IBOutlet weak var btnAccept: UIButton!
@IBOutlet weak var btnCancel: UIButton!
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var imgCard: UIImageView!
var card: Card?
var presenter: PickedCardDialogPresenter!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clear
view.isOpaque = false
presenter = PickedCardDialogPresenter(view: self)
presenter.initialize()
presenter.viewDidLoad(card: card!)
btnAccept.setTitle("label.ok".localized, for: .normal)
btnCancel.setTitle("label.cancel".localized, for: .normal)
}
}
extension PickedCardDialogViewController: PickedCardDialogPresenterOutput {
func setImageCard(image: UIImage) {
imgCard.image = image
}
func setTitleDialog(title: String) {
lblTitle.text = title
}
func setBackgroundButtons() {
btnAccept.backgroundColor = UIColor.beevaBlack
btnCancel.backgroundColor = UIColor.beevaYellow
}
func dismissOverlay() {
self.willMove(toParentViewController: nil)
self.view.removeFromSuperview()
self.removeFromParentViewController()
}
func navigateToDetail() {
let controller = storyboard?.instantiateViewController(withIdentifier: NavigationIdentifier.DeckDetailViewController.rawValue) as! DeckDetailViewController
controller.card = card
self.show(controller, sender: nil)
}
}
extension PickedCardDialogViewController: PickedCardDialogPresenterView {
@IBAction func onClickButtonAccept() {
presenter.onClickButtonAccept()
}
@IBAction func onClickButtonCancel() {
presenter.onClickButtonCancel()
}
}
|
//
// QRScannerViewController.swift
// MMWallet
//
// Created by Dmitry Muravev on 08.08.2018.
// Copyright © 2018 micromoney. All rights reserved.
//
import UIKit
import AVFoundation
class QRScannerViewController: BaseViewController, Messageable, Loadable {
@IBOutlet weak var fadeView: UIView!
@IBOutlet weak var maskView: UIView!
@IBOutlet weak var infoLabel: UILabel!
var captureSession: AVCaptureSession?
var videoPreviewLayer: AVCaptureVideoPreviewLayer?
private let supportedCodeTypes = [AVMetadataObject.ObjectType.qr]
var isShowAllert = false
var delayTimer: Timer?
var sendViewController: SendViewController?
override func viewDidLoad() {
super.viewDidLoad()
createMask()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
isShowAllert = false
stopDelay()
setupScanner()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
stopScanner()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func configureView(isRefresh: Bool) {
}
func createMask() {
let maskLayer = CAShapeLayer()
maskLayer.frame = fadeView.bounds
maskLayer.fillColor = UIColor.black.cgColor
let path = UIBezierPath(rect: UIScreen.main.bounds)
maskLayer.fillRule = CAShapeLayerFillRule.evenOdd
let rect = fadeView.convert(maskView.bounds, from: maskView)
path.append(UIBezierPath(roundedRect: rect, cornerRadius: 15))
maskLayer.path = path.cgPath
fadeView.layer.mask = maskLayer
}
func setupScanner() {
captureSession = AVCaptureSession()
let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back)
guard let captureDevice = deviceDiscoverySession.devices.first else {
print("Failed to get the camera device")
return
}
do {
let input = try AVCaptureDeviceInput(device: captureDevice)
captureSession!.addInput(input)
let captureMetadataOutput = AVCaptureMetadataOutput()
captureSession!.addOutput(captureMetadataOutput)
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
captureMetadataOutput.metadataObjectTypes = supportedCodeTypes
// captureMetadataOutput.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
} catch {
print(error)
return
}
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
videoPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
videoPreviewLayer?.frame = view.layer.bounds
view.layer.addSublayer(videoPreviewLayer!)
captureSession?.startRunning()
view.bringSubviewToFront(fadeView)
view.bringSubviewToFront(maskView)
view.bringSubviewToFront(infoLabel)
}
func startDelay() {
delayTimer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(stopDelay), userInfo: nil, repeats: false)
}
@objc func stopDelay() {
if delayTimer != nil {
delayTimer?.invalidate()
delayTimer = nil
}
}
func stopScanner() {
captureSession?.stopRunning()
if let inputs = captureSession?.inputs as? [AVCaptureDeviceInput] {
for input in inputs {
captureSession?.removeInput(input)
}
}
videoPreviewLayer?.removeFromSuperlayer()
videoPreviewLayer = nil
captureSession = nil
}
func analyzeCode(codeString: String) {
if isShowAllert {
return
}
if delayTimer != nil {
return
}
isShowAllert = true
self.showLoader()
DataManager.shared.checkAddress(address: codeString) { [weak self] (currencyString, error) in
if error == nil {
self?.hideLoaderSuccess() { [weak self] in
if currencyString != nil {
if let asset = DataManager.shared.getFirstAsset(currency: currencyString!) {
//self?.stopScanner()
self?.isShowAllert = true
self?.stopDelay()
self?.sendViewController = self?.navigateToSendModal(assetsId: asset.id, address: codeString)
self?.sendViewController?.delegate = self
return
}
}
self?.showSorryAlert()
}
} else {
self?.hideLoaderFailure(errorLabelTitle: "Check address failed", errorLabelMessage: "Unknown Error")
self?.startDelay()
}
}
}
func showSorryAlert() {
let errorAlert = UIAlertController(title: nil, message: "Sorry, we can't recognize this QR-code", preferredStyle: UIAlertController.Style.alert)
errorAlert.addAction(UIAlertAction(title: "OK", style: .default) { [weak self] (action:UIAlertAction!) in
self?.isShowAllert = false
})
self.present(errorAlert, animated: true)
isShowAllert = true
}
}
extension QRScannerViewController: AVCaptureMetadataOutputObjectsDelegate {
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
if metadataObjects.count == 0 {
//qrCodeFrameView?.frame = CGRect.zero
//messageLabel.text = "No QR code is detected"
return
}
let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
if supportedCodeTypes.contains(metadataObj.type) {
//let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj)
//qrCodeFrameView?.frame = barCodeObject!.bounds
if metadataObj.stringValue != nil {
analyzeCode(codeString: metadataObj.stringValue!)
}
}
}
}
extension QRScannerViewController: SendViewControllerDelegate {
func sendViewControllerClosed(_ sendViewController: SendViewController) {
isShowAllert = false
stopDelay()
}
}
|
//
// Price.swift
// LemonadeStand
//
// Created by jim Veneskey on 5/18/15.
// Copyright (c) 2015 Jim Veneskey. All rights reserved.
//
import Foundation
struct Price {
// our fixed prices
let lemon = 2
let iceCube = 1
} |
//
// Helpers.swift
// Animator
//
// Created by Daniel Hooper on 2021-05-24.
//
import SwiftUI
extension CGPoint {
func toAngle() -> Angle {
return Angle(radians: Double(atan2(x, y)))
}
func mirrored(relativeTo p: CGPoint) -> CGPoint {
let relative = self - p
return p - relative
}
func distance(to: CGPoint) -> CGFloat {
sqrt(pow(to.x - x, 2) + pow(to.y - y, 2))
}
static prefix func -(rhs: CGPoint) -> CGPoint {
CGPoint(x: -rhs.x, y: -rhs.y)
}
static func +(lhs: CGPoint, rhs: CGPoint) -> CGPoint {
CGPoint(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
static func +(lhs: CGPoint, rhs: CGSize) -> CGPoint {
CGPoint(x: lhs.x + rhs.width, y: lhs.y + rhs.width)
}
static func -(lhs: CGPoint, rhs: CGPoint) -> CGPoint {
lhs + (-rhs)
}
func rounded() -> CGPoint {
return CGPoint(x: x.rounded(), y: y.rounded())
}
}
extension CGSize {
init(_ square: CGFloat) {
self.init(width: square, height: square)
}
}
extension Array where Element: Identifiable {
func elementForId(_ id: UUID) -> Element? {
return first(where: { $0.id as! UUID == id })
}
}
extension View {
@discardableResult
func openInWindow(title: String, sender: Any?) -> NSWindow {
let controller = NSHostingController(rootView: self)
let win = NSWindow(contentViewController: controller)
win.contentViewController = controller
win.title = title
win.makeKeyAndOrderFront(sender)
return win
}
}
//
//extension View {
// func asImage() -> NSImage {
// let host = NSHostingController(rootView: self)
// return host.view.image()
// }
//}
//
//extension NSView {
//
// func image() -> NSImage {
// let imageSize = NSSize(width: bounds.size.width, height: bounds.size.height)
// let bitmap = bitmapImageRepForCachingDisplay(in: bounds)
//// cacheDisplay(in: bounds, to: bitmap ?? NSBitmapImageRep(data: Data())!)
// let image = NSImage(size: imageSize)
//// image.addRepresentation(bitmap ?? NSBitmapImageRep(data: Data())!)
// return image
// }
//}
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
extension Color {
var components: (red: CGFloat, green: CGFloat, blue: CGFloat, opacity: CGFloat) {
#if canImport(UIKit)
typealias NativeColor = UIColor
#elseif canImport(AppKit)
typealias NativeColor = NSColor
#endif
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var o: CGFloat = 0
NativeColor(self).getRed(&r, green: &g, blue: &b, alpha: &o)
return (r, g, b, o)
}
}
|
//
// GradeSelectedViewController.swift
// JiaoAn
//
// Created by Marlon Ou on 2016-01-03.
// Copyright (c) 2016 TPTJ. All rights reserved.
//
import UIKit
class GradeSelectedViewController: UIViewController {
//from grade selection view, taping on certain image sets name var
//from question view, the name var is determined by current problem sets' title information
//For progress bar or difficulty infomation: when the UIImage is determined, when which grade we are in. Pull from database for the information
@IBOutlet weak var displayImage: UIImageView!
var name : String?
var nameForLevelTest : String?//Used when selects level test. Since name has to be used in selec..provider func as leveltest, this extra string is needed for identifying what grade. Regular exercise doesnot require this. because name is directly used for grade identification between views.
@IBOutlet weak var fallLabel: UILabel!
@IBOutlet weak var winterLabel: UILabel!
@IBOutlet weak var summerLabel: UILabel!
var myGrade:String!
override func viewDidLoad() {
super.viewDidLoad()
myGrade = name
if name != nil{
displayImage.image = UIImage(named: name!)
}
print("\(name)")
fallLabel.textColor = UIColor.blackColor()
winterLabel.textColor = UIColor.blackColor()
summerLabel.textColor = UIColor.blackColor()
let dif = getDifficulty()
if(dif == 0){
fallLabel.textColor = UIColor.blueColor()
}else if (dif == 1){
winterLabel.textColor = UIColor.blueColor()
}else if (dif == 2){
summerLabel.textColor = UIColor.blueColor()
}else{
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func toLevelTest(sender: AnyObject) {
nameForLevelTest = name!
name = "levelTest"
performSegueWithIdentifier("selectedToQView", sender: sender)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
selectedToQViewQuestionProvider(segue, grade: name!)
}
private func selectedToQViewQuestionProvider(segue : UIStoryboardSegue, var grade : String){
if segue.identifier == "selectedToQView"{
let desView = segue.destinationViewController as! QuestionViewController
var index = self.getQuestionArrayIndex()
print("index is \(index)");
var dif = self.getDifficulty();
if(dif == 3){
grade = "levelTest";
}
switch grade {
case "grade 7":
if(dif == 0){
desView.problemSet = Grade7().fall[index]
}else if (dif == 1){
desView.problemSet = Grade7().winter[index]
}else if (dif == 2){
desView.problemSet = Grade7().summer[index]
}
desView.myGrade = name!
desView.islevelTest = false;
case "grade 8":
if(dif == 0){
desView.problemSet = Grade8().fall[index]
}else if (dif == 1){
desView.problemSet = Grade8().winter[index]
}else if (dif == 2) {
desView.problemSet = Grade8().summer[index]
}
desView.myGrade = name!
desView.islevelTest = false;
case "grade 9":
if(dif == 0){
desView.problemSet = Grade9().fall[index]
}else if (dif == 1){
desView.problemSet = Grade9().winter[index]
}else if (dif == 2){
desView.problemSet = Grade9().summer[index]
}
desView.myGrade = name!
desView.islevelTest = false;
case "levelTest":
switch myGrade!{
case "grade 7":
desView.problemSet = LevelTest.array1[index]
case "grade 8":
desView.problemSet = LevelTest.array2[index]
case "grade 9":
desView.problemSet = LevelTest.array3[index]
default:
break
}
desView.myGrade = nameForLevelTest!
desView.islevelTest = true;
default:
print("***Error")
}
}
}
func getQuestionArrayIndex() -> Int{
let userDefaults = NSUserDefaults.standardUserDefaults();
if(userDefaults.objectForKey("index") != nil){
var index = userDefaults.integerForKey("index");
if(index == 2){
userDefaults.setInteger(0, forKey: "index");
userDefaults.synchronize();
return 0;
}else{
var nextIndex = index + 1;
userDefaults.setInteger(nextIndex, forKey: "index");
userDefaults.synchronize();
return index;
}
}else{
userDefaults.setInteger(0, forKey: "index");
userDefaults.synchronize();
return 0;
}
}
func setQuestionArrayIndex(index:Int){
let userDefaults = NSUserDefaults.standardUserDefaults();
userDefaults.setInteger(index, forKey: "index");
userDefaults.synchronize();
}
func getDifficulty() -> Int{
// fall : 0
// winter : 1
// summer : 2
// need to do level test: 3
var key = "grade7difficulty"
switch myGrade!{
case "grade 7":
break
case "grade 8":
key = "grade8difficulty"
case "grade 9":
key = "grade9difficulty"
default:
break
}
let userDefaults = NSUserDefaults.standardUserDefaults();
if(userDefaults.objectForKey(key) != nil){
return userDefaults.integerForKey(key);
}else{
return 3;
}
}
@IBAction func practiceTapGesture(sender: AnyObject) {
// let dif = getDifficulty();
// print("dif is \(dif)")
// if(dif == 3){
// let alert = UIAlertView.init(title: "请先做水平测试", message: nil, delegate: self, cancelButtonTitle: "OK")
// alert.show()
// }else{
// performSegueWithIdentifier("selectedToQView", sender: sender)
// }
//
}
@IBAction func doPractice(sender: AnyObject) {
let dif = getDifficulty();
print("dif is \(dif)")
if(dif == 3){
let alert = UIAlertView.init(title: "请先做水平测试", message: nil, delegate: self, cancelButtonTitle: "OK")
alert.show()
}else{
performSegueWithIdentifier("selectedToQView", sender: sender)
}
}
/*
// 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.
}
*/
}
|
//
// CollectionViewControllerTests.swift
// Filme App CollectionTests
//
// Created by Miguel Fernandes Lopes on 29/11/19.
// Copyright © 2019 Miguel Fernandes Lopes. All rights reserved.
//
import XCTest
import CoreData
@testable import Filme_App_Collection
class IdCoreDataTests: XCTestCase {
// MARK: - Properties
private var idCoreData: [Int] = []
private var existe = false
private var Verifica: DescricaoViewController?
override func setUp() {
super.setUp()
idCoreData = [105486,162489,251234]
print(idCoreData)
}
override func tearDown() {
idCoreData = []
}
func testExample() {
for idCoreData in (Verifica?.self.dadosID)! {
if idCoreData == Verifica?.self.dados_json[0].id {
existe = true
}
}
if Verifica?.verifID() == existe {
print("Erro, nao existe")
}
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
|
//
// ViewController.swift
// ClassSample
//
// Created by 齋藤律哉 on 2020/07/10.
// Copyright © 2020 ritsuya. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITableViewDataSource {
@IBOutlet var timelineTableView: UITableView!
var posts = [Post]()
override func viewDidLoad() {
super.viewDidLoad()
timelineTableView.dataSource = self
// Do any additional setup after loading the view.
let nib = UINib(nibName: "TimelineTableViewCell", bundle: nil)
timelineTableView.register(nib, forCellReuseIdentifier: "TimelineTableViewCell")
timelineTableView.rowHeight = 500
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TimelineTableViewCell") as! TimelineTableViewCell
cell.userNameLabel.text = posts[indexPath.row].name
cell.userImageView.image = posts[indexPath.row].userImage
cell.postImageView.image = posts[indexPath.row].postImage
cell.textView.text = posts[indexPath.row].text
return cell
}
@IBAction func didTapButton() {
makeInstance()
timelineTableView.reloadData()
}
func makeInstance(){
let post1 = Post(userName: "ドラえもん", userImage: UIImage(named: "Human1.jpg")!, image: UIImage(named: "Picture1.jpg")!)
let post2 = Post(userName: "ルフィー", userImage: UIImage(named: "Human2.png")!, image: UIImage(named: "Picture2.jpg")!)
post2.text = "オプショナルだから任意"
let post3 = Post(userName: "サザエ", userImage: UIImage(named: "Human3.png")!, image: UIImage(named: "Picture3.jpeg")!)
post3.text = "デデーン"
posts.append(post1)
posts.append(post2)
posts.append(post3)
}
}
|
//
// Entry.swift
// RedditMe
//
// Created by Andrey Krit on 13.11.2020.
//
import Foundation
struct EntryModel: Codable {
let data: EntryDataModel
}
struct EntryDataModel: Codable {
let name: String
let title: String
let author: String?
let thumbnailUrl: String?
let createdAt: Date?
let commentsCount: Int?
enum CodingKeys: String, CodingKey {
case name, title, author
case thumbnailUrl = "thumbnail"
case createdAt = "created_utc"
case commentsCount = "num_comments"
}
}
struct Entry {
let name: String
let title: String
let author: String?
var thumbnailUrl: URL? = nil
let createdAt: String?
let commentsCount: String?
init(_ model: EntryModel) {
name = model.data.name
title = model.data.title
author = model.data.author
createdAt = model.data.createdAt?.toString
commentsCount = String(model.data.commentsCount ?? 0) + "comments"
if let urlString = model.data.thumbnailUrl, urlString.isURL {
thumbnailUrl = URL(string: urlString)
}
}
}
|
//
// Card.swift
// Concentration
//
// Created by Juyong Lee on 11/06/2019.
// Copyright © 2019 Juyong Lee. All rights reserved.
//
import Foundation
struct Card {
var inFaceUp = false
var isMatched = false
var identifier: Int
// No!!!!! It doesn't have to value!!!!
// This card is UI independent!!
// var emoji
static var identifierFactory = 0
static func getUniqueIdentifier() -> Int {
Card.identifierFactory += 1
return Card.identifierFactory
}
init() {
identifier = Card.getUniqueIdentifier()
}
}
|
//
// BaseViewController.swift
// intermine-ios
//
// Created by Nadia on 5/8/17.
// Copyright © 2017 Nadia. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
let interactor = Interactor()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.configureNavBar()
}
func configureNavBar() {
self.navigationController?.navigationBar.barTintColor = UIColor.white//Colors.palma
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.tintColor = UIColor.black//Colors.white
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.black]//Colors.white]
}
func showMenuButton() {
let button = UIButton()
button.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
button.setImage(Icons.blackMenu, for: .normal)
button.addTarget(self, action: #selector(BaseViewController.menuButtonPressed), for: .touchUpInside)
button.tintColor = UIColor.black//Colors.white
let barButton = UIBarButtonItem()
barButton.customView = button
self.navigationItem.leftBarButtonItem = barButton
}
func setNavBarTitle(title: String) {
self.navigationController?.navigationBar.topItem?.title = title
}
func menuButtonPressed() {
// present VC modaly
if let menuVC = MenuViewController.menuViewController() {
menuVC.transitioningDelegate = self
menuVC.interactor = interactor
present(menuVC, animated: true, completion: nil)
}
}
func indicatorFrame() -> CGRect {
if let navbarHeight = self.navigationController?.navigationBar.frame.size.height, let tabbarHeight = self.tabBarController?.tabBar.frame.size.height {
let viewHeight = BaseView.viewHeight(view: self.view)
let indicatorHeight = viewHeight - (tabbarHeight + navbarHeight)
let indicatorWidth = BaseView.viewWidth(view: self.view)
return CGRect(x: 0, y: 0, width: indicatorWidth, height: indicatorHeight)
} else {
return self.view.frame
}
}
func indicatorPadding() -> CGFloat {
return BaseView.viewWidth(view: self.view) / 2.5
}
func defaultNavbarConfiguration(withTitle: String) {
self.navigationController?.navigationBar.barTintColor = UIColor.white//Colors.palma
self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.tintColor = UIColor.black//Colors.white
self.navigationController?.navigationBar.topItem?.title = withTitle
//self.navigationController?.navigationBar.topItem?.titleView = UIImageView(image: Icons.titleBarPlaceholder)
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.black]//Colors.white]
let button = UIButton()
button.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
button.setImage(Icons.titleBarPlaceholder, for: .normal)
button.addTarget(self, action: #selector(LoadingTableViewController.menuButtonPressed), for: .touchUpInside)
button.tintColor = UIColor.black//Colors.white
let barButton = UIBarButtonItem()
barButton.customView = button
self.navigationItem.leftBarButtonItem = barButton
}
}
extension BaseViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return PresentMenuAnimator()
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return DismissMenuAnimator()
}
func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactor.hasStarted ? interactor : nil
}
func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactor.hasStarted ? interactor : nil
}
}
|
//
// Cardify.swift
// stanford SwiftUI Course
//
// Created by Halis Kara on 2.05.2021.
//
import SwiftUI
struct Cardify: AnimatableModifier{
var rotation : Double
init(isFaceUp: Bool){
rotation = isFaceUp ? 0 :180
}
var isFaceUp: Bool{
rotation < 90
}
var animatableData : Double {
get {return rotation }
set{rotation = newValue}
}
func body(content: Content)-> some View{
ZStack{
Group{
RoundedRectangle(cornerRadius: cornerRadius).fill(Color.white)
RoundedRectangle(cornerRadius: cornerRadius).stroke(lineWidth: edgeineWidth)
content
}.opacity(isFaceUp ? 1 :0)
RoundedRectangle(cornerRadius: cornerRadius).fill(Color(#colorLiteral(red: 0.9372549057, green: 0.3490196168, blue: 0.1921568662, alpha: 1)))
.opacity(isFaceUp ? 0 :1
)
}
.rotation3DEffect(
Angle.degrees(rotation),
axis: (x: 0.0, y: 1.0, z: 0.0)
)
}
private let cornerRadius : CGFloat = 10
private let edgeineWidth : CGFloat = 3
}
extension View {
func cardify(isFaceUp: Bool) ->some View{
self.modifier(Cardify(isFaceUp: isFaceUp))
}
}
|
//
// ViewController.swift
// Lab3
//
// Created by Rishabh Sanghvi on 11/3/15.
// Copyright © 2015 Rishabh Sanghvi. All rights reserved.
//
import UIKit
import GoogleMaps
class ViewController: UIViewController,UIScrollViewDelegate {
var transform : CGAffineTransform!
@IBOutlet weak var myLocationButton: UIButton!
@IBOutlet weak var SearchBtn: UIButton!
@IBOutlet var scView: UIScrollView!
@IBOutlet var mapsView: Widget!
var widget: Widget! = Widget()
var searchButton : UIButton?
var currentLocation : UIButton?
let playImage = UIImage(named: "play")
let currentLocationImage = UIImage(named: "myLocation")
let defaults = NSUserDefaults.standardUserDefaults()
var i = 0
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBarHidden = true
i = 0
self.scView.minimumZoomScale = 1
self.scView.maximumZoomScale = 6
NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOFReceivedNotication:", name: "NotificationIdentifier", object: nil)
self.searchButton = UIButton(frame: CGRect(origin: CGPoint(x: self.view.frame.width - 90, y: self.view.frame.height / 1.30 + 40), size: CGSize(width: 50, height: 50)))
self.searchButton!.setBackgroundImage(playImage, forState: UIControlState.Normal)
self.view.addSubview(searchButton!)
self.view.bringSubviewToFront(searchButton!)
self.searchButton!.addTarget(self, action: "searchButtonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
self.currentLocation = UIButton(frame: CGRect(origin: CGPoint(x: 20, y: self.view.frame.height / 1.30 + 40), size: CGSize(width: 50, height: 50)))
self.currentLocation!.setBackgroundImage(currentLocationImage, forState: UIControlState.Normal)
self.view.addSubview(currentLocation!)
self.view.bringSubviewToFront(currentLocation!)
self.currentLocation!.addTarget(self, action: "myLocationClicked:", forControlEvents: UIControlEvents.TouchUpInside)
self.navigationController?.navigationBarHidden = true
let twoFingerPinch = UIPinchGestureRecognizer(target: self, action: "respondToSwipeGesture:")
self.view.addGestureRecognizer(twoFingerPinch)
if let zoomScale = defaults.stringForKey("zoom level") {
print("Application logged in zoom scale \(String(zoomScale))")
if let zoolScaleFloat = NSNumberFormatter().numberFromString(zoomScale) {
let zoomScaleCGFloat : CGFloat = CGFloat(zoolScaleFloat)
scView.setZoomScale(zoomScaleCGFloat, animated: true)
}
}
}
override func viewWillAppear(animated: Bool) {
self.navigationController?.navigationBarHidden = true
}
func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
print("Current Zoom Level is \(scale.description)")
defaults.setFloat(Float(scale), forKey: "zoom level")
defaults.synchronize()
}
func methodOFReceivedNotication(notification: NSNotification) {
guard let dataObj: DataObj? = notification.object as? DataObj else {
return
}
print("In Notification")
print(dataObj!.getBuildingName())
self.view.bringSubviewToFront(SearchBtn)
let buildingCordinates = getBuildingLatLong((dataObj?.getBuildingName())!)
let point : CGPoint = CGPointMake(CGFloat(buildingCordinates["x"]!), CGFloat(buildingCordinates["y"]!));
let xStart : Int = Int(point.x);
let yStart : Int = Int(point.y);
let innerCircleRect : CGRect = CGRectMake(CGFloat(xStart), CGFloat(yStart), 10, 10)
let innerCircleView : UIView = UIView(frame: innerCircleRect)
innerCircleView.tag = 999
innerCircleView.backgroundColor = UIColor.redColor();
innerCircleView.layer.cornerRadius = 10.0;
self.mapsView.addSubview(innerCircleView);
let scrollViewSize: CGSize = self.view.bounds.size
let w: CGFloat = scrollViewSize.width / 2;
let h: CGFloat = scrollViewSize.height / 2
let x = CGFloat(buildingCordinates["x"]!) - (w/2.0)
let y = CGFloat(buildingCordinates["y"]!) //- (h/2.0)
let rectTozoom=CGRectMake(x, y, w, h)
self.scView.zoomToRect(rectTozoom, animated: true)
self.scView.scrollRectToVisible(rectTozoom, animated: true)
}
func respondToSwipeGesture(gesture: UIPinchGestureRecognizer){
if(gesture.scale < 2 && gesture.scale > 0.5){
transform = CGAffineTransformMakeScale(gesture.scale, gesture.scale);
self.view.transform = transform;
transform = CGAffineTransformMakeScale(2, 2);
}
}
override func viewDidAppear(animated: Bool) {
let twoFingerPinch = UIPinchGestureRecognizer(target: self, action: "respondToSwipeGesture:")
self.view.addGestureRecognizer(twoFingerPinch)
}
func searchButtonClicked(sender: UIButton){
if let viewWithTag = self.view.viewWithTag(999) {
viewWithTag.removeFromSuperview()
}
self.performSegueWithIdentifier("segueExercise", sender: self)
}
func myLocationClicked(sender: UIButton) {
self.performSegueWithIdentifier("myLocation", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "segueExercise") {
}
if(segue.identifier == "myLocation"){
self.navigationController?.navigationBarHidden = false
let detailVC = segue.destinationViewController as! MyLocation
if let loc = segueMyLocation {
detailVC.longitude = loc.longitude
detailVC.lattitude = loc.latitude
}
}
}
func getBuildingLatLong(buildingName: String) -> [String : Float]{
var x: Float!
var y: Float!
switch(buildingName) {
case "King Library":
x = 110
y = 140
break
case "Engineering Building":
x = 385
y = 150
break
case "Yoshihiro Uchida Hall":
x = 100
y = 240
break
case "BBC":
x = 585
y = 230
break
case "Student Union":
x = 393
y = 195
break
case "SouthParkingGarage":
x = 248
y = 310
break
default:
break
}
let buildingCordinates: [String : Float] = ["x" : x, "y" : y]
return buildingCordinates
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return self.mapsView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
} |
// swift-tools-version:5.2
import PackageDescription
let package = Package(
name: "MultiPackageName",
products: [
.library(
name: "MultiPackageLibOne",
targets: ["MultiPackageTargetOne"]),
.library(
name: "MultiPackageLibTwo",
targets: ["MultiPackageTargetTwo"])
],
targets: [
.target(name: "MultiPackageTargetOne"),
.target(name: "MultiPackageTargetTwo")
]
)
|
//
// YNCycleRingViewController.swift
// 2015-08-06
//
// Created by 农盟 on 15/8/6.
// Copyright (c) 2015年 农盟. All rights reserved.
//
import UIKit
class YNCycleRingViewController: UIViewController {
}
|
import Foundation
enum SearchReducer: String, Codable {
case updatePostcodeReducer
case updateRestaurantsReducer
// Adaptors add area reducers below
}
extension SearchReducer {
var call: ReducerFunc<SearchStateSlice> {
switch self {
case .updatePostcodeReducer: return ios.updatePostcodeReducer
case .updateRestaurantsReducer: return ios.updateRestaurantsReducer
}
}
}
|
//
// AssertEqualToAny.swift
// SOTopTwentyKitTests
//
// Created by Trevor Doodes on 15/02/2020.
// Copyright © 2020 IronworksMediaLimited. All rights reserved.
//
import XCTest
public func XCTAssertEqualToAny<T: Equatable>(_ actual: @autoclosure () throws -> T,
_ expected: @autoclosure () throws -> Any?,
file: StaticString = #file,
line: UInt = #line) throws {
let actual = try actual()
let expected = try XCTUnwrap(expected() as? T)
XCTAssertEqual(actual, expected, file: file, line: line)
}
|
//
// GridFlowList.swift
// SwiftUIHub
//
// Created by Yu Fan on 2019/6/28.
// Copyright © 2019 Yu Fan. All rights reserved.
//
import SwiftUI
struct GridItem<T> where T: View {
var title: String
var destination: T
}
struct FlowList : View {
private var itemsTitle = ["Icon Text", "Grid Image", "Grid Image Text", "Grid Block", "HScroll Block"]
var body: some View {
FlowStack(direction: .vertical,
numPerRow: 1,
numOfItems: itemsTitle.count,
alignment: .leading,
showIndicator: true)
{ index, width in
PresentationButton(destination: FlowIconText()) {
HStack {
Text(self.itemsTitle[index])
.font(.title)
.foregroundColor(.primary)
.padding(.leading, 20)
Spacer()
}
.frame(height: 50)
.border(Color.secondary, width: 1, cornerRadius: 10)
.padding(EdgeInsets(top: 10, leading: 20, bottom: 10, trailing: 20)
)
}
}
.navigationBarTitle(Text("GridFlows"))
}
}
#if DEBUG
struct FlowList_Previews : PreviewProvider {
static var previews: some View {
FlowList()
}
}
#endif
|
//
// CategoryPage.swift
// IGotIt
//
// Created by Gregory Johnson on 10/9/18.
// Copyright © 2018 Johnson Production. All rights reserved.
//
import Foundation
import UIKit
struct CategoryPage
{
var category : String
init(category: String)
{
self.category = category
}
}
var categoryPage = CategoryPage(category: "Category")
|
//
// Bodies.swift
// Rocket Simulation
//
// Created by Sam Bunger on 9/26/18.
// Copyright © 2018 Samster. All rights reserved.
//
import Foundation
|
//
// MyDeliveries2
//
// Created by SAP Cloud Platform SDK for iOS Assistant application on 01/03/20
//
import Foundation
enum CollectionType: String {
case deliveryStatus = "DeliveryStatus"
case packages = "Packages"
case none = ""
static let all = [deliveryStatus, packages]
}
|
//
// NetworkStatus.swift
// ADGAP
//
// Created by Jitendra Kumar on 29/05/20.
// Copyright © 2020 Jitendra Kumar. All rights reserved.
//
import UIKit
import Alamofire
class NetworkStatus:NSObject{
static let shared = NetworkStatus()
fileprivate var jkHud:JKProgressHUD!
var isConnected:Bool{
guard let isReachable = NetworkReachabilityManager.default?.isReachable else {
AppPermission.network.show()
return false }
return isReachable
}
var progress:Double = 0.0{
didSet{
self.jkHud.progress = Float(progress)
}
}
func startNotifier(completion:@escaping(NetworkReachabilityManager.NetworkReachabilityStatus)->Void){
NetworkReachabilityManager.default!.startListening(onUpdatePerforming: completion)
}
//MARK:- showProgressHud-
func showHud(inView view:UIView = AppDelegate.shared.window!, progressMode:JKProgressHUD.HudStyle = .Indeterminate,hudPosition position:JKProgressHUD.Position = .center,message title:String = ""){
self.hideHud()
self.jkHud = JKProgressHUD.showProgressHud(inView: view, progressMode: progressMode,hudPosition: position, titleLabel: title)
self.jkHud.islineColors = true
self.jkHud.setNeedsLayout()
}
//MARK:- hideHud-
func hideHud(){
if let jkHud = jkHud {
self.progress = 0.0
jkHud.hideHud()
}
}
}
enum AppPermission {
case network
func show(){
var title:String = kAppTitle
var message:String?
switch self {
case .network:
title = "\"\(kAppTitle)\" \(kConnectionError)"
message = "The Internet connection appears to be offline."
}
AppSettingAlert(title: title, message: message)
}
}
|
//
// QuotationDao.swift
// Everything
//
// Created by Sergey Okhotnikov on 25.07.2020.
// Copyright © 2020 Sergey Okhotnikov. All rights reserved.
//
import Foundation
import Combine
import Reachability
class AppState : ObservableObject {
let session = URLSession(configuration : .default)
static let decoder = JSONDecoder()
static let encoder = JSONEncoder()
@Published var user : User
@Published var settings : Settings
@Published var quotations : [Chapter] = []
@Published var chapters : [Chapter] = []
@Published var error : ErrorType = .NoException
@Published var chapterOfTheDay : Chapter?
@Published var hasInternetConnection = true
@Published var storeObserver: StoreObserver
@Published var suggestedNumbers : [Int] = []
private var reachability : Reachability?
private var started = false
var hasContent : Bool{
!quotations.isEmpty || !chapters.isEmpty
}
var allertAction : (()-> Void)?
var hasAllertAction : Bool {
allertAction != nil
}
init() {
user = User.user
settings = Settings.setting
storeObserver = StoreObserver()
monitorConnection()
AppState.state = self
storeObserver.owner = self
}
func monitorConnection(){
reachability = try! Reachability()
reachability!.whenReachable = { reachability in
self.hasInternetConnection = true
if !self.started {
self.start()
}
if reachability.connection == .wifi {
print("Reachable via WiFi \(self.error)")
} else {
print("Reachable via Cellular")
}
}
reachability!.whenUnreachable = { _ in
print("Not reachable \(self.error)")
self.hasInternetConnection = false
}
do {
try reachability!.startNotifier()
} catch {
print("Unable to start notifier")
}
}
fileprivate func getNumberOfTheDay() {
if self.settings.numberOfTheDay != Chapter.numberOfTheDay{
self.fetchNumberOfTheDay()
}
}
fileprivate func readWithCode(_ code: String) {
self.setAccessCode(code, numbers: self.settings.layers){
if !self.user.canRead{
self.fetchQuotations()
self.user.accessDenied()
}
}
}
func startReading() {
self.started = true
self.error = .NoException
if let code = self.user.accessCode{
self.readWithCode(code)
} else{
self.fetchQuotations()
}
}
func start() {
if user.isReader {
error = .Processing
refresh(onSucces : {
self.startReading()
self.getNumberOfTheDay()
}, onError: { error in
self.started = true
self.error = error
if error == .Unauthorized{
self.user.logout()
}
self.error = .NoException
self.fetchQuotations()
self.getNumberOfTheDay()
})
} else {
if user.canRead {
readWithCode(user.accessCode!)
} else {
fetchQuotations()
getNumberOfTheDay()
}
}
}
func read(){
print("start reading")
}
func getChapters(numbers : [Int]){
if let code = user.accessCode{
setAccessCode(code, numbers: numbers){
self.user.hasAccess = true
}
}
}
func go(to number: Int) -> Bool{
return settings.setTop(to: number) || hasChapter(number)
}
func hasChapter(_ number: Int) ->Bool{
return chapters.contains(Chapter.empty(number: number))
}
func add(number: Int) -> Bool{
return settings.addTop(number: number)
}
func set(to number: Int) -> Bool{
return settings.set(to: number)
}
func simulateProcess(){
let prev = error
error = .Processing
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01)
{
self.error = prev
}
}
var cancelableQuotations : AnyCancellable?
func fetchQuotations() {
if !hasInternetConnection{
error = .NoNetwork
return
}
error = .Processing
cancelableQuotations = session.dataTaskPublisher(for: AppState.quotationsurl)
.map({$0.data})
.map{ data -> [Chapter] in
do{
return try AppState.decoder.decode([Chapter].self, from:data)
}catch{
print(error)
return[]
}
}
.eraseToAnyPublisher()
.receive(on: RunLoop.main)
.sink(receiveCompletion: {print($0)},
receiveValue:{
print("got quotations \($0)")
self.error = .NoException
self.quotations = $0
})
}
var cancelableNumberofTheDay : AnyCancellable?
func fetchNumberOfTheDay() {
if !hasInternetConnection{
error = .NoNetwork
return
}
cancelableNumberofTheDay = session.dataTaskPublisher(for: AppState.numberOfTheDayUrl)
.map({$0.data})
.map{ data -> Chapter? in
do{
return try AppState.decoder.decode([Chapter].self, from:data)[0]
}catch{
print(error)
return nil
}
}
.eraseToAnyPublisher()
.receive(on: RunLoop.main)
.sink(receiveCompletion: {print($0)},
receiveValue:{
self.chapterOfTheDay = $0
if let chapter = self.chapterOfTheDay{
self.settings.setNumberOfTheDay(chapter.number)
}
})
}
var cancelableLogin : AnyCancellable?
fileprivate func requestChapters(with request: URLRequest,mergeType : MergeType, _ onSucces: @escaping () -> Void) {
if !hasInternetConnection{
error = .NoNetwork
return
}
error = .Processing
cancelableLogin = session
.dataTaskPublisher(for: request)
.map{ response -> (error: ErrorType,chapters:[Chapter]) in
if let httpResponse = response.response as? HTTPURLResponse{
if httpResponse.statusCode != 200 {
return (error : ErrorType(rawValue: httpResponse.statusCode)!, chapters: [])
}
}
do{
return (error: .NoException,
chapters: try AppState.decoder.decode([Chapter].self, from: response.data))
}catch{
return(error: .UnparsableResponse, chapters:[])
}
}
.eraseToAnyPublisher()
.receive(on: RunLoop.main)
.sink(receiveCompletion: {
print("read")
print($0)},
receiveValue:{
switch mergeType{
case .new:
if $0.chapters.count > 0 {
self.chapters = $0.chapters
}
default:
self.chapters.append(contentsOf: $0.chapters)
self.chapters = Array(Set(self.chapters))
}
self.error = $0.error
if self.error == .Unauthorized{
self.user.accessDenied()
}
onSucces()
print($0.error)
print($0.chapters)
})
}
func getNumbersOfTheDay(onSucces: @escaping ()->Void){
if let token = user.accessCode{
var request = URLRequest(url: AppState.numbersOfTheDayUrl)
request.httpMethod = "GET"
request.addValue(token, forHTTPHeaderField: AppState.authorization)
request.addValue(AppState.contentTypeJson, forHTTPHeaderField: AppState.contentType)
requestChapters(with: request, mergeType: .new, onSucces)
} else{
fatalError("this function for authorized users only")
}
}
fileprivate func prepareNumberRequest(_ numbers: [Int]) -> BookRequest {
chapters.append(contentsOf: numbers
.filter{$0 > Chapter.max}
.map{Chapter.build(from: $0)})
chapters = Array(Set(self.chapters))
return BookRequest(numbers : numbers.filter{ number in
return number <= Chapter.max
})
}
func setAccessCode(_ accessCode: String,numbers : [Int] = [1], onSucces: @escaping ()->Void){
var request = URLRequest(url: AppState.readsurl)
request.httpMethod = "POST"
request.addValue(accessCode, forHTTPHeaderField: AppState.authorization)
request.addValue(AppState.contentTypeJson, forHTTPHeaderField: AppState.contentType)
let obj : BookRequest = prepareNumberRequest(numbers)
request.httpBody = AppState.encoder.optionalEncode(obj)
requestChapters(with: request, mergeType: .both, onSucces)
}
fileprivate func mapChaptersToSettings() {
self.settings.set(with: self.chapters.map({chapter in chapter.number}))
}
func textSearch(_ text: String){
if let token = user.accessCode{
var request = URLRequest(url: URL(string: (AppState.searchLink + text).encodedUrl)!)
request.httpMethod = "GET"
request.addValue(token, forHTTPHeaderField: AppState.authorization)
requestChapters(with: request, mergeType: .new){
self.mapChaptersToSettings()
}
} else{
error = .Unauthorized
}
}
fileprivate func processUser(_ receivedUser: User) {
receivedUser.readersAccess()
receivedUser.storeCode(self.user.accessCode)
self.user = receivedUser
self.user.save()
}
func requestAuthentication(_ request: URLRequest, _ onSucces: @escaping () -> Void) {
error = .Processing
cancelableLogin = session
.dataTaskPublisher(for: request)
.map{ response -> (error: ErrorType,user: User?) in
if let httpResponse = response.response as? HTTPURLResponse{
if httpResponse.statusCode != 200 {
return (error : ErrorType(rawValue: httpResponse.statusCode)!, user: nil)
}
}
do{
return (error: .NoException,
user: try AppState.decoder.decode(User.self, from: response.data))
}catch{
return(error: .UnparsableResponse, nil)
}
}
.eraseToAnyPublisher()
.receive(on: RunLoop.main)
.sink(receiveCompletion: {
print("register")
print($0)},
receiveValue:{
self.error = $0.error
if let receivedUser = $0.user{
self.processUser(receivedUser)
onSucces()
print(receivedUser)
}
print($0.error)
})
}
fileprivate func requestAuthentication(_ request: URLRequest, _ onSucces: @escaping () -> Void, _ onError: @escaping (ErrorType) -> Void) {
cancelableLogin = session
.dataTaskPublisher(for: request)
.map{ response -> (error: ErrorType,user: User?) in
if let httpResponse = response.response as? HTTPURLResponse{
if httpResponse.statusCode != 200 {
return (error : ErrorType(rawValue: httpResponse.statusCode)!, user: nil)
}
}
do{
return (error: .NoException,
user: try AppState.decoder.decode(User.self, from: response.data))
}catch{
return(error: .UnparsableResponse, nil)
}
}
.eraseToAnyPublisher()
.receive(on: RunLoop.main)
.sink(receiveCompletion: {
print("register")
print($0)},
receiveValue:{
if $0.error == .NoException{
if let receivedUser = $0.user{
self.processUser(receivedUser)
onSucces()
// print(receivedUser.username!)
// print(receivedUser.roles!)
// print(receivedUser.token!)
}else{
onError(.UnparsableResponse)
}
}
print($0.error)
onError($0.error)
})
}
func loginWithCode(code: String, onError: @escaping (_ : ErrorType)->Void, onSucces: @escaping ()->Void){
var request = URLRequest(url: AppState.codeUrl)
request.httpMethod = "PUT"
request.addValue(AppState.contentTypeJson, forHTTPHeaderField: AppState.contentType)
request.httpBody = AppState.encoder.optionalEncode(TokenRequest(token: code))
requestAuthentication(request, onSucces, onError)
}
func register(username: String, password: String, onSucces: @escaping ()->Void){
var request = URLRequest(url: AppState.registerUrl)
request.httpMethod = "POST"
request.addValue(AppState.contentTypeJson, forHTTPHeaderField: AppState.contentType)
request.httpBody = AppState.encoder.optionalEncode(
Credentials(username: username, password: password))
requestAuthentication(request, onSucces)
}
func login(username: String, password: String, onSucces: @escaping ()->Void){
var request = URLRequest(url: AppState.loginUrl)
request.httpMethod = "PUT"
request.addValue(AppState.contentTypeJson, forHTTPHeaderField: AppState.contentType)
request.httpBody = AppState.encoder.optionalEncode(
Credentials(username: username, password: password))
requestAuthentication(request, onSucces)
}
func refresh( onSucces: @escaping ()->Void, onError: @escaping (_ : ErrorType)->Void ) {
if let token = user.refreshToken{
var request = URLRequest(url: AppState.refreshUrl)
request.httpMethod = "PUT"
request.addValue(AppState.contentTypeJson, forHTTPHeaderField: AppState.contentType)
request.httpBody = AppState.encoder.optionalEncode(
TokenRequest(token: token))
requestAuthentication(request, onSucces, onError)
} else{
onError(.Unauthorized)
}
}
func verifyReceipt(receipt: String, onSucces: @escaping ()->Void, onError: @escaping (_ : ErrorType)->Void ){
if let token = user.token{
var request = URLRequest(url: AppState.verifyReceiptUrl)
request.httpMethod = "POST"
request.addValue(AppState.contentTypeJson, forHTTPHeaderField: AppState.contentType)
request.addValue(token, forHTTPHeaderField: AppState.authorization)
request.httpBody = AppState.encoder.optionalEncode(
TokenRequest(token: receipt))
error = .Processing
requestAuthentication(request, onSucces, onError)
} else{
error = .Unauthorized
}
}
fileprivate func voidRequest(_ request: URLRequest, _ onSucces: @escaping () -> Void, _ onError: @escaping (ErrorType) -> Void) {
cancelableLogin = session
.dataTaskPublisher(for: request)
.map{ response -> ErrorType in
if let httpResponse = response.response as? HTTPURLResponse{
if httpResponse.statusCode != 200 {
print("status code: \(httpResponse.statusCode)")
return ErrorType(rawValue: httpResponse.statusCode)!
}
}
return .NoException
}
.eraseToAnyPublisher()
.receive(on: RunLoop.main)
.sink(receiveCompletion: {
print($0)},
receiveValue:{
if $0 == .NoException{
onSucces()
} else {
onError($0)
}
print($0)
})
}
func forget(for email: String, onError: @escaping (_ : ErrorType)->Void, onSucces: @escaping ()->Void){
var request = URLRequest(url: URL(string: (AppState.forgetLink + email).encodedUrl)!)
request.httpMethod = "GET"
voidRequest(request, onSucces, onError)
}
func changePassword(to newPassword: String, onError: @escaping (_ : ErrorType)->Void, onSucces: @escaping ()->Void){
if let token = user.token {
var request = URLRequest(url: AppState.changePasswordUrl)
request.httpMethod = "POST"
request.addValue(AppState.contentTypeJson, forHTTPHeaderField: AppState.contentType)
request.addValue(token, forHTTPHeaderField: AppState.authorization)
request.httpBody = AppState.encoder.optionalEncode(
TokenRequest(token: newPassword))
voidRequest(request, onSucces, onError)
} else {
onError(.UnparsableResponse)
}
}
}
//MARK: Singleton
extension AppState{
static var state : AppState?
static func refreshQuotations(){
if let appState = state{
appState.fetchQuotations()
}
}
static func setAccessCode(_ accessCode: String, allertAction :(()->Void)?){
if let appState = state{
appState.allertAction = allertAction
appState.setAccessCode(accessCode){
if appState.error == .NoException{
appState.user.accessGranted(with: accessCode)
}
}
}
}
static func textSearch(_ text: String){
if let appState = state{
appState.textSearch(text)
}
}
static func aсquireChapter(_ number: Int, _ appState: AppState) {
if number <= Chapter.max{
appState.getChapters(numbers: [number])
} else{
appState.chapters.append(Chapter.build(from: number))
appState.chapters = Array(Set(appState.chapters))
}
}
static func getNumbersOfTheDay() {
if let appState = state {
appState.getNumbersOfTheDay {
appState.mapChaptersToSettings()
appState.settings.sort()
}
}
}
static func go(to number: Int){
if let appState = state{
if !appState.go(to: number){
aсquireChapter(number, appState)
} else {
appState.simulateProcess()
}
}
}
static func add(number: Int){
if let appState = state{
if !appState.add(number: number){
aсquireChapter(number, appState)
}
}
}
static func set(to number: Int){
if let appState = state{
if !appState.set(to: number){
aсquireChapter(number, appState)
}
}
}
static func noException(){
if let appState = state{
appState.error = .NoException
}
}
static func register(username: String, password: String, allertAction :(()->Void)?, onSucces: @escaping ()->Void){
if let appState = state{
appState.allertAction = allertAction
appState.register(username: username, password: password){
onSucces()
appState.startReading()
}
}
}
static func login(username: String, password: String, allertAction :(()->Void)?, onSucces: @escaping ()->Void){
if let appState = state{
appState.allertAction = allertAction
appState.login(username: username, password: password){
onSucces()
appState.startReading()
}
}
}
static func runAllertAction(){
if let appState = state{
if let action = appState.allertAction{
action()
} else {
print("no stored action")
}
}
}
static func cutTop(){
if let appState = state{
appState.settings.cutTop()
}
}
static func collapse(){
if let appState = state{
appState.settings.collapse()
}
}
static func canCollapse() -> Bool{
if let appState = state{
return appState.settings.canCollapse
}
return false
}
static func increaseFont(){
if let appState = state{
appState.settings.increaseFont()
}
}
static func decreaseFont(){
if let appState = state{
appState.settings.decreaseFont()
}
}
static func dismissNumberOfTheDay(){
if let appState = state{
appState.chapterOfTheDay = nil
}
}
static func forget(for email: String, onError : @escaping (_ : ErrorType)->Void, onSucces: @escaping ()->Void){
if let appState = state{
appState.forget(for: email, onError: onError, onSucces: onSucces)
}
}
static func loginWithCode(code: String, onError : @escaping (_ : ErrorType)->Void, onSucces: @escaping ()->Void){
if let appState = state{
appState.loginWithCode(code: code, onError: onError, onSucces: onSucces)
}
}
static func verifyReceipt(receipt: String, onDone: @escaping ()->Void){
if let appState = state{
appState.verifyReceipt(receipt: receipt,
onSucces: {
print("verification success, token: \(appState.user.accessCode!)")
appState.startReading()
onDone()
})
{ error in
appState.error = error
if error != .NoException{
print("error \(error)")
onDone()
}
}
}
}
static func changePassword(to newPassword: String, onError : @escaping (_ : ErrorType)->Void, onSucces: @escaping ()->Void){
if let appState = state{
appState.changePassword(to: newPassword, onError: onError, onSucces: onSucces)
}
}
static func textWithNumbers(taped numbers: [Int]){
if let appState = state{
let n = numbers.filter(){ number in
return number != appState.settings.top
}
print(n)
if n.count == 0{
return
}
if n.count == 1{
add(number: n[0])
return
}
appState.suggestedNumbers = n
}
}
}
//MARK: Literals
extension AppState{
static let authorization = "Authorization"
static let contentType = "Content-type"
static let contentTypeJson = "application/json; charset=utf8"
}
//MARK: urls
extension AppState{
static let serverLink = "https://everything-from.one/"
static let quotationsLink = "free/quotations"
static let readLink = "book/read"
static let registerLink = "pub/register"
static let loginLink = "pub/login"
static let searchLink = serverLink + "book/search/"
static let numberOfTheDayLink = "free/day"
static let numbersOfTheDayLink = "book/day"
static let forgetLink = serverLink + "pub/forget/"
static let codeLink = "pub/code"
static let changePasswordLink = "usr/password"
static let refreshLink = "pub/refresh"
static let verifyReceiptLink = "usr/apple"
static let quotationsurl = URL(string: serverLink + quotationsLink)!
static let readsurl = URL(string: serverLink + readLink)!
static let registerUrl = URL(string: serverLink + registerLink)!
static let loginUrl = URL(string: serverLink + loginLink)!
static let numberOfTheDayUrl = URL(string: serverLink + numberOfTheDayLink)!
static let numbersOfTheDayUrl = URL(string: serverLink + numbersOfTheDayLink)!
static let codeUrl = URL(string: serverLink + codeLink)!
static let changePasswordUrl = URL(string: serverLink + changePasswordLink)!
static let refreshUrl = URL(string: serverLink + refreshLink)!
static let verifyReceiptUrl = URL(string: serverLink + verifyReceiptLink)!
}
|
import Foundation
import Combine
import HsExtensions
class ICloudBackupNameService {
private let iCloudManager: CloudAccountBackupManager
let account: Account
@PostPublished private(set) var state: State = .failure(error: NameError.empty)
init(iCloudManager: CloudAccountBackupManager, account: Account) {
self.iCloudManager = iCloudManager
self.account = account
set(name: account.name)
}
}
extension ICloudBackupNameService {
var initialName: String {
account.name
}
func set(name: String) {
let name = name.trimmingCharacters(in: NSCharacterSet.whitespaces)
guard !name.isEmpty else {
state = .failure(error: NameError.empty)
return
}
if iCloudManager.existFilenames.contains(where: { s in s.lowercased() == name.lowercased() }) {
state = .failure(error: NameError.alreadyExist)
return
}
state = .success(name: name)
}
}
extension ICloudBackupNameService {
enum State {
case success(name: String)
case failure(error: Error)
}
enum NameError: Error {
case empty
case alreadyExist
}
}
|
//
// Movie.swift
// MovieLand
//
// Created by Galih Asmarandaru on 24/12/20.
//
import UIKit
struct Movie: Decodable {
var page: Int
var results: [MovieResult]
var total_pages: Int
var total_results: Int
}
struct MovieResult: Decodable {
var poster_path: String
var title: String
var release_date: String
var overview: String
}
enum MovieError: Error {
case noDataAvailable
case cannotProcessData
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.