text
stringlengths
8
1.32M
// // CustomButton.swift // Test // // Created by a.belyaev3 on 24.09.2020. // Copyright © 2020 a.belyaev3. All rights reserved. // import UIKit class CustomButton: UIButton { required init?(coder: NSCoder) { super.init(coder: coder) //До вызова инита родительского класса доступа к frame нет Logger.log("Edit button frame: \(self.frame)") } }
@testable import ABA_Music import XCTest class SearchResultCollectionViewModelTests: XCTestCase { func testViewModelPublicAPI() { let track = Artist.generateArtist(index: 0).tracks.first! let viewModel = SearchResultCollectionViewModel(track: track) as SearchResultCollectionViewModelType let expectedArtworkUrl = URL(string: "https://mock-url.com") let expectedName = "Mock track number 1" let expectedReleaseDate = "Oct 15, 2019" XCTAssertNotNil(viewModel.artworkUrl) XCTAssertEqual(viewModel.artworkUrl, expectedArtworkUrl) XCTAssertEqual(viewModel.name, expectedName) XCTAssertEqual(viewModel.releaseDate, expectedReleaseDate) } func testCellDataControllerConformanceWithValidModel() { let track = Artist.generateArtist(index: 0).tracks.first! let viewModel = SearchResultCollectionViewModel.populate(with: track) as? SearchResultCollectionViewModelType let expectedArtworkUrl = URL(string: "https://mock-url.com") let expectedName = "Mock track number 1" let expectedReleaseDate = "Oct 15, 2019" XCTAssertNotNil(viewModel) XCTAssertNotNil(viewModel?.artworkUrl) XCTAssertEqual(viewModel?.artworkUrl, expectedArtworkUrl) XCTAssertEqual(viewModel?.name, expectedName) XCTAssertEqual(viewModel?.releaseDate, expectedReleaseDate) } func testCellDataControllerConformanceWithNonValidModel() { let model: Int = 0 let viewModel = SearchResultCollectionViewModel.populate(with: model) as? SearchResultCollectionViewModelType let expectedName = "" let expectedReleaseDate = "Jan 01, 1970" XCTAssertNotNil(viewModel) XCTAssertNil(viewModel?.artworkUrl) XCTAssertEqual(viewModel?.name, expectedName) XCTAssertEqual(viewModel?.releaseDate, expectedReleaseDate) } }
// // EventServiceError.swift // Mevents // // Created by Isnard Silva on 05/01/21. // import Foundation enum EventServiceError: Error { case objectNotDecoded } extension EventServiceError: LocalizedError { var errorDescription: String? { switch self { case .objectNotDecoded: return "Não foi possível decodificar os dados." } } }
// // LoginField.swift // Chat-SwiftUI // // Created by 3bdo on 6/13/20. // Copyright © 2020 3bdo. All rights reserved. // import SwiftUI struct SignUp: View { @State var mail = "" @State var pass = "" @State var rePass = "" @State var hide = true @State var hide2 = true var body: some View { VStack { VStack{ HStack(spacing: 15){ Image(systemName: "envelope") .foregroundColor(.black) .frame(width: 25, height: 25) TextField("Enter your mail", text: self.$mail) }.padding(.vertical, 20) .padding(.top, 10) .padding(.leading, 15) .padding(.trailing, 10) Divider() HStack(spacing: 15){ if !self.hide { Image(systemName: "lock") .resizable() .frame(width: 15, height: 18) .foregroundColor(.black) TextField("Enter your Password", text: self.$pass) }else { Image(systemName: "lock") .resizable() .frame(width: 15, height: 18) .foregroundColor(.black) SecureField("Enter your Password", text: self.$pass) } Button(action: { self.hide.toggle() }) { Image(systemName: "eye") .foregroundColor(self.hide ? .black : .green) } }.padding(.vertical, 20) .padding(.bottom, 10) .padding(.leading, 20) .padding(.trailing, 10) Divider() HStack(spacing: 15){ if !self.hide2 { Image(systemName: "lock") .resizable() .frame(width: 15, height: 18) .foregroundColor(.black) TextField("Enter your Password", text: self.$rePass) }else { Image(systemName: "lock") .resizable() .frame(width: 15, height: 18) .foregroundColor(.black) SecureField("Enter your Password", text: self.$rePass) } Button(action: { self.hide2.toggle() }) { Image(systemName: "eye") .foregroundColor(self.hide2 ? .black : .green) } }.padding(.vertical, 20) .padding(.bottom, 10) .padding(.leading, 20) .padding(.trailing, 10) } .padding(.bottom, 40) .background(Color.white) .cornerRadius(10) .padding(.horizontal, 20) Button(action: { }) { Text("Login") .padding(.vertical) .foregroundColor(Color.white) .frame(width: (UIScreen.main.bounds.width - 100)) .font(Font.custom("", size: 24)) } .background( LinearGradient(gradient: Gradient(colors: [Color("Color1"),Color("Color2"),Color("Color1")]), startPoint: .leading, endPoint: .trailing) ).cornerRadius(10) .offset(y: -40) .shadow(radius: 20) } } } struct SignUp_Previews: PreviewProvider { static var previews: some View { SignUp().previewLayout(.sizeThatFits) } }
// // HomeDetailVC.swift // Saucesy // // Created by Meeky Dekowski on 11/25/16. // Copyright © 2016 Meek Apps. All rights reserved. // import UIKit class HomeDetailVC: UITableViewController { override func viewDidLoad() { super.viewDidLoad() //make the reuseable cell with identifier and connet it to the class tableView.register(MyCell.self, forCellReuseIdentifier: "HomeDetailVC") tableView.register(Header.self, forHeaderFooterViewReuseIdentifier: "HeaderId") } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "HomeDetailVC", for: indexPath) return cell } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44.0 } //Section Header override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "HeaderId") return header } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 336.0 } } // Custom header class Header: UITableViewHeaderFooterView{ override init(reuseIdentifier: String?){ super.init(reuseIdentifier: reuseIdentifier) setupHeader() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //Food Image let foodImage: UIImageView = { let imageView = UIImageView() imageView.image = UIImage(named: "foodImage") imageView.contentMode = .scaleToFill imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() // Name Label let nameLabel: UILabel = { let label = UILabel() label.text = "Salsa Verde Chicken Bake" label.translatesAutoresizingMaskIntoConstraints = false return label }() // Calories Label let caloriesLabel: UILabel = { let label = UILabel() let calorie = "360" let caloriesText = "CALORIES" let caloriesLabel = "\(calorie) \(caloriesText)" label.textColor = UIColor(red:234/255, green:84/255, blue:85/255, alpha:1.0) label.font = UIFont(name: "Avenir", size: 13.0) label.font = UIFont.systemFont(ofSize: 13.0, weight: UIFontWeightMedium) //Api request number (changing color) let range = (caloriesLabel as NSString).range(of: caloriesText) let attributedString = NSMutableAttributedString(string: caloriesLabel) attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red:45/255, green:64/255, blue:89/255, alpha:1.0) , range: range) label.attributedText = attributedString label.translatesAutoresizingMaskIntoConstraints = false return label }() func setupHeader(){ addSubview(foodImage) addSubview(caloriesLabel) //Horizontal Constraints for Image addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": foodImage])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0(260)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": foodImage])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-20-[v1]-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v1": caloriesLabel])) //Calories Stackview // let caloriesStackview = UIStackView(arrangedSubviews: [caloriesLabel,caloriesLabelStatic]) // caloriesStackview.axis = .horizontal // caloriesStackview.spacing = 3 // caloriesStackview.alignment = .fill // caloriesStackview.distribution = .fill // caloriesStackview.translatesAutoresizingMaskIntoConstraints = false // // //Servings Stackview // let servingsStackview = UIStackView(arrangedSubviews: [servingsLabel,servingsLabelStatic]) // servingsStackview.axis = .horizontal // servingsStackview.spacing = 3 // servingsStackview.alignment = .fill // servingsStackview.distribution = .fill // servingsStackview.translatesAutoresizingMaskIntoConstraints = false // // //Nest Servings and Calories Stackview // let foodDetailsStackview = UIStackView(arrangedSubviews: [caloriesStackview, servingsStackview]) // foodDetailsStackview.spacing = 10 // foodDetailsStackview.alignment = .fill // foodDetailsStackview.distribution = .fill // foodDetailsStackview.translatesAutoresizingMaskIntoConstraints = false // addSubview(foodDetailsStackview) // // // //Nest Name Label with Nested Servings and Calories Stackview // let foodInformationStackview = UIStackView(arrangedSubviews: [nameLabel, foodDetailsStackview]) // foodInformationStackview.axis = .vertical // foodInformationStackview.spacing = 9 // foodInformationStackview.alignment = .fill // foodInformationStackview.distribution = .fill // foodInformationStackview.translatesAutoresizingMaskIntoConstraints = false // addSubview(foodInformationStackview) //Horizontal Constraints for Nest Name Label with Nested Servings and Calories Stackview // addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-20-[v1]-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v1": caloriesLabel])) //Vertical Constraints for Image and Nest Name Label with Nested Servings and Calories Stackview // addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0(260)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": foodImage])) } } // Custom cell class MyCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?){ super.init(style: style, reuseIdentifier: reuseIdentifier) setupviews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } let nameLabel: UILabel = { let label = UILabel() label.text = "test" label.translatesAutoresizingMaskIntoConstraints = false return label }() func setupviews(){ addSubview(nameLabel) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-16-[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel])) } } //var detail_recipe: model_Recipe! // //@IBOutlet weak var tableview: UITableView! //// @IBOutlet weak var label: UILabel! // // //override func viewDidLoad() { // super.viewDidLoad() // // tableview.delegate = self // tableview.dataSource = self // self.navigationController?.navigationBar.isHidden = true // print(detail_recipe.model_recipe_array[0].name) // label!.text = detail_recipe.model_recipe_array[0].name // Do any additional setup after loading the view. //} // func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // let cell = UITableViewCell() // // cell.textLabel?.text = "test" // // return cell // } // // func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return 20 // }
// // ZLBaseJsonModel.swift // TestProject // // Created by DanaLu on 2018/4/18. // Copyright © 2018年 gh. All rights reserved. // import UIKit import HandyJSON class ZLBaseJsonModel: HandyJSON { public required init(){} }
// // CodeManager.swift // BlocklyCodeLabStarter // // Created by MANINDER SINGH on 26/05/20. // Copyright © 2020 Google. All rights reserved. // import Foundation import Blockly /** Manages JS code in the app. It generates JS code from workspace XML and saves it in-memory for future use. */ class CodeManager { private var savedCode = [String: String]() /// Service used for converting workspace XML into JS code. private var codeGeneratorService: CodeGeneratorService = { let service = CodeGeneratorService( jsCoreDependencies: [ // The JS file containing the Blockly engine "blockly_web/blockly_compressed.js", // The JS file containing a list of internationalized messages "blockly_web/msg/js/en.js" ]) let builder = CodeGeneratorServiceRequestBuilder( // This is the name of the JS object that will generate JavaScript code jsGeneratorObject: "Blockly.JavaScript") // Load the block definitions for all default blocks builder.addJSONBlockDefinitionFiles(fromDefaultFiles: .allDefault) // Load the block definitions for our custom sound block builder.addJSONBlockDefinitionFiles(["sound_blocks.json"]) builder.addJSBlockGeneratorFiles([ // Use JavaScript code generators for the default blocks "blockly_web/javascript_compressed.js", // Use JavaScript code generators for our custom sound block "sound_block_generators.js"]) // Assign the request builder to the service and cache it so subsequent // code generation runs are immediate. service.setRequestBuilder(builder, shouldCache: true) return service }() deinit { codeGeneratorService.cancelAllRequests() } /** Generates code for a given `key`. */ func generateCode(forKey key: String, workspaceXML: String) { do { // Clear the code for this key as we generate the new code. self.savedCode[key] = nil let _ = try codeGeneratorService.generateCode( forWorkspaceXML: workspaceXML, onCompletion: { requestUUID, code in // Code generated successfully. Save it for future use. self.savedCode[key] = code }, onError: { requestUUID, error in print("An error occurred generating code - \(error)\n" + "key: \(key)\n" + "workspaceXML: \(workspaceXML)\n") }) } catch let error { print("An error occurred generating code - \(error)\n" + "key: \(key)\n" + "workspaceXML: \(workspaceXML)\n") } } func code(forKey key: String) -> String? { return savedCode[key] } }
// // chessLoop.swift // ChessBeta // // Created by Evelyn Zhang on 9/21/20. // import Foundation //var plyaerKing:King=King() //var aiKing:King=king() func setup(){ } func checkWin(){ }
// // person.swift // 私人通讯录 // // Created by 周冰烽 on 2016/11/14. // Copyright © 2016年 周冰烽. All rights reserved. // import UIKit class person: NSObject { var name: String? var phone: String? var title: String? }
// // UIColor.swift // RingMeter // // Created by Michał Kreft on 01/04/15. // Copyright (c) 2015 Michał Kreft. All rights reserved. // //import Foundation import UIKit public let AppleBlue1 = UIColor(red: 0.965, green: 0.094, blue: 0.122, alpha: 1.0) public let AppleBlue2 = UIColor(red: 0.973, green: 0.0, blue: 0.671, alpha: 1.0) public let AppleGreen1 = UIColor(red: 0.647, green: 1.0, blue: 0.0, alpha: 1.0) public let AppleGreen2 = UIColor(red: 0.845, green: 1.0, blue: 0.004, alpha: 1.0) public let AppleRed1 = UIColor(red: 0.271, green: 0.878, blue: 0.984, alpha: 1.0) public let AppleRed2 = UIColor(red: 0.306, green: 0.988, blue: 0.918, alpha: 1.0) internal extension UIColor { class func gradientValuesFromColors(colors: [UIColor]) -> [CGFloat] { var outputValues = [CGFloat]() var r, g, b, a :CGFloat (r, g, b, a) = (0.0, 0.0, 0.0, 0.0) for color in colors { //TODO try to simply add CGColors to array (like in c) color.getRed(&r, green: &g, blue: &b, alpha: &a) outputValues += [r, g, b, a] } return outputValues } func darker() -> UIColor { var h, s, b, a :CGFloat (h, s, b, a) = (0.0, 0.0, 0.0, 0.0) self.getHue(&h, saturation: &s, brightness: &b, alpha: &a) return UIColor(hue: h, saturation: s * 1.2, brightness: 0.25, alpha: a) } func blend(color: UIColor) -> UIColor { let alpha: CGFloat = 0.5 let beta = 1.0 - alpha var r1, g1, b1, a1, r2, g2, b2, a2 :CGFloat (r1, g1, b1, a1, r2, g2, b2, a2) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) self.getRed(&r1, green: &g1, blue: &b1, alpha: &a1) color.getRed(&r2, green: &g2, blue: &b2, alpha: &a2) let r = r1 * beta + r2 * alpha; let g = g1 * beta + g2 * alpha; let b = b1 * beta + b2 * alpha; return UIColor(red: r, green: g, blue: b, alpha: 1.0) } }
// // MediaItem.swift // MediaBatchRenamer // // Created by Emil Hörnlund on 2019-01-09. // Copyright © 2019 Emil Hörnlund. All rights reserved. // import Foundation enum MediaType { case show(String, Int, Int, String) case movie(String) func filename(extension ext: String) -> String { switch self { case .show(let show, let season, let episode, let title): return "\(show) - S\(String(format: "%02d", season))E\(String(format: "%02d", episode)) - \(title).\(ext)" case .movie(let title): return "\(title).\(ext)" } } } struct MediaItem { var type: MediaType var inputURL: URL var inputName: String { return inputURL.lastPathComponent } var outputName: String { let ext = inputURL.pathExtension return type.filename(extension: ext) } var outputURL: URL { return self.inputURL.deletingLastPathComponent().appendingPathComponent(outputName) } }
// // LoveViewController.swift // NewMiniProject // // Created by Angela Huynh on 6/4/20. // Copyright © 2020 Angela Huynh. All rights reserved. // import UIKit class LoveViewController: UIViewController { @IBAction func loveButton(_ sender: UIButton) { let loveController = UIAlertController(title: "This is your writng prompt!", message:"A lonely woman strolls through the city and stumbles upon an oddities and antiques store. A fantasy story ensues when she picks up a tiny glass bottle the proprietor mistakenly tells her is a love spell but is actually a time-traveling potion. Home alone later that evening, she pours some of the liquid into her glass. She wakes up in another era and finds her soulmate.", preferredStyle: .alert); loveController.addAction (UIAlertAction(title: "Heck yeah! Love this prompt!!", style: .default)) self.present(loveController, animated: true, completion:nil) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
// // HotelsViewController.swift // Challenge Republic // // Created by Artur Gurgul on 02/02/2017. // Copyright © 2017 Chatting Solutions LTD. All rights reserved. // import UIKit import RxSwift import SDWebImage import MBProgressHUD class HotelsViewController: UITableViewController { private let viewModel = HotelsViewModel() private let disposeBag = DisposeBag() private var loadingVisible:Bool = false { willSet { if let _ = hud, newValue == false { MBProgressHUD.hide(for: view, animated: true) } else if hud == nil && newValue == true { self.hud = MBProgressHUD(view: view) hud?.mode = .determinate MBProgressHUD.showAdded(to: view, animated: true) } } } private var hud: MBProgressHUD? = nil override func viewDidLoad() { super.viewDidLoad() viewModel.loadData() setupDataBindings() setupBindings() } func setupDataBindings() { viewModel.hotels.asObservable() .subscribe(onNext: hotelsReady) .addDisposableTo(disposeBag) } func setupBindings() { viewModel.viewState.asObservable() .subscribe(onNext: adjustViewToState) .addDisposableTo(disposeBag) } func adjustViewToState(state: HotelsViewModel.ViewState) { switch state { case .error(let error): print("error") loadingVisible = false let alertController = UIAlertController(title: NSLocalizedString("error", comment: ""), message: error.localizedDescription, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel)) alertController.addAction(UIAlertAction(title: NSLocalizedString("Retry", comment: ""), style: .default, handler: retryOnFailed)) present(alertController, animated: true) case .normal: loadingVisible = false case .loading: loadingVisible = true } } func retryOnFailed(_: Any?) { viewModel.loadData() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.hotels.value.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "HotelViewCell", for: indexPath) as! HotelViewCell let hotel = viewModel.hotels.value[indexPath.row] adjust(cell: cell, with: hotel) return cell } func adjust(cell: HotelViewCell, with hotel: Hotel) { cell.titleLabel.text = hotel.title let imageSize = cell.photoImageView.bounds.size let imageUrl = hotel.imageUrl(size: imageSize) cell.photoImageView.sd_setImage(with: imageUrl) cell.priceLabel.text = String(format: "£ %.2lf", hotel.minPrice) } private func hotelsReady(hotels:[Hotel]) { tableView.reloadData() } }
// // FollowViewModel.swift // DouYu_Swift // // Created by iwindy on 2020/9/13. // Copyright © 2020 Lucien. All rights reserved. // import UIKit class FollowViewModel: BaseViewModel { } extension FollowViewModel{ func loadFollowData(finishedCallback: @escaping () -> ()){ NetWorkTools.requestData(.get, urlString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time":NSDate.getCurrentTime()]) {(result) in // 1.获取字典 guard let resultDict = result as? [String : Any] else { return } // 2.取出 dataArray guard let dataArray = resultDict["data"] as? [[String : Any]] else { return } // 3.1创建数组 let gruop = AnchorGroupModel() gruop.tag_name = "推荐直播" gruop.icon_name = "Img_orange" // 3.2遍历 dataArray所有的字典 for dict in dataArray { gruop.anchors.append(AnchorModel(dict: dict)) } // 3.3 将 group 添加到 anchorGroups 里面 self.anchorGroups.append(gruop) // 4.回调 finishedCallback() } } }
// // ViewController.swift // PoliticalParty // // Created by Brian Hans on 10/13/16. // Copyright © 2016 Brian Hans. All rights reserved. // import UIKit class GameViewController: UIViewController, AnswerButtonDelegate { @IBOutlet weak var questionLabel: UILabel! @IBOutlet weak var question1btn: AnswerButton! @IBOutlet weak var question2btn: AnswerButton! @IBOutlet weak var question3btn: AnswerButton! @IBOutlet weak var question4btn: AnswerButton! @IBOutlet weak var timerLabel: UILabel! @IBOutlet weak var categoryLabel: UILabel! var game: Game! var buttons: [AnswerButton] = [] var startTime: TimeInterval! let questionTime: Double = 10 var timer: Timer! var countDown: Bool = false{ didSet{ if(countDown){ startTime = Date.timeIntervalSinceReferenceDate let runLoop = RunLoop.current timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) runLoop.add(timer, forMode: RunLoopMode.commonModes) runLoop.add(timer, forMode: RunLoopMode.UITrackingRunLoopMode) }else{ timer.invalidate() } } } override func viewDidLoad() { super.viewDidLoad() buttons = [question1btn, question2btn, question3btn, question4btn] game = Game() setupQuestion(game.getNextQuestion()!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillDisappear(_ animated: Bool) { countDown = false } override func viewDidAppear(_ animated: Bool) { self.buttons[0].animate() } func setupQuestion(_ question: Question) { countDown = true self.questionLabel.text = question.text self.categoryLabel.text = question.category.rawValue for i in 0..<question.options.count{ self.buttons[i].answer = question.options[i] self.buttons[i].isSelected = false } enableButtons() self.startTime = Date.timeIntervalSinceReferenceDate } func pressed(_ sender: AnswerButton) { sender.isSelected = true selectRightAnswer() //Prevent issues with timer countDown = false //Delay 4 seconds so they can see correct answer if(!self.game.sendAnswer(sender.answer)){ sender.animation = "shake" sender.animate() } disableButtons() selectRightAnswer() perform(#selector(nextQuestion), with: sender, afterDelay: 2) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if(segue.identifier == "GameOver"){ let controller = segue.destination as! GameOverViewController controller.game = self.game } } func selectRightAnswer(){ for button in buttons{ if(button.answer.correct){ button.isSelected = true return } } } func disableButtons(){ for button in buttons{ button.isUserInteractionEnabled = false } } func enableButtons(){ for button in buttons{ button.isUserInteractionEnabled = true } } func nextQuestion(){ countDown = false if let question = self.game.getNextQuestion(){ for button in buttons{ button.animation = "zoomOut" button.animateTo() button.animateNext(completion: { button.animation = "pop" button.animate() }) } setupQuestion(question) }else{ performSegue(withIdentifier: "GameOver", sender: nil) } } func updateTimer(){ let currentTimeDifference = Date.timeIntervalSinceReferenceDate - startTime if(questionTime - currentTimeDifference <= 0){ game.timeUp() countDown = false nextQuestion() }else{ timerLabel.text = String(Int(questionTime - currentTimeDifference)) } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if(!countDown){ NSObject.cancelPreviousPerformRequests(withTarget: self) nextQuestion() } } }
// // Enums.swift // Cellar // // Created by James Garrett on 7/13/16. // Copyright © 2016 James Garrett. All rights reserved. // import Foundation enum NewOrEditType{ case New case Edit }
// // DashboardPlanView.swift // KayakFirst Ergometer E2 // // Created by Balazs Vidumanszki on 2017. 05. 17.. // Copyright © 2017. Balazs Vidumanszki. All rights reserved. // import Foundation class DashboardPlanView: RefreshView<ViewDashboardPlanLayout> { private let telemetry = Telemetry.sharedInstance //MARK: properties var plan: Plan? var isDone: Bool { return planTelemetryObject != nil && planTelemetryObject!.isDone } let planSoundHelper = PlanSoundHelper.sharedInstance private var planTelemetryObject: PlanTelemetryObject? = nil override func getContentLayout(contentView: UIView) -> ViewDashboardPlanLayout { return ViewDashboardPlanLayout(contentView: contentView) } //MARK: functions func viewDidLayoutSubViews() { var gradientOrientation: GradientOrientation = .verticalPortrait if contentLayout!.isLandscape { gradientOrientation = .verticalLandscape } contentLayout!.viewGrad.superview?.layer.mask = getGradient(withColours: [Colors.colorPrimary, Colors.colorTransparent], gradientOrientation: gradientOrientation) } override func refreshUi() { contentLayout!.deActual1000.refreshUi() contentLayout!.deSpm.refreshUi() planTelemetryObject = telemetry.planTelemetryObject if let planTelemetryObject = planTelemetryObject { setTexts(value: planTelemetryObject.value, accentValue: planTelemetryObject.valueAccent) contentLayout!.progressViewComplete.progress = Float(planTelemetryObject.totalProgress / 100) contentLayout!.progressViewPlanElement.progress = (Float(planTelemetryObject.actualProgress / 100)) setProgressBarPlanElementColor(color: planTelemetryObject.planElementColor) contentLayout!.peTableView.dataList = planTelemetryObject.planElementList planSoundHelper.playSoundIfNeeded(value: planTelemetryObject.value, planType: plan!.type) } } private func setTexts(value: Double, accentValue: Double) { var valueText = getFormattedTimeText(value: value) var valueAccentText = getFormattedDistanceText(value: accentValue) if plan!.type == PlanType.distance { valueText = getFormattedDistanceText(value: value) valueAccentText = getFormattedTimeText(value: accentValue) } setTexts(valueText: valueText, valueAccentText: valueAccentText) } private func setTexts(valueText: String, valueAccentText: String) { contentLayout!.labelValue.text = valueText contentLayout!.labelValueAccent.text = valueAccentText } private func getFormattedTimeText(value: Double) -> String { return DateFormatHelper.getDate(dateFormat: DateFormatHelper.minSecFormat, timeIntervallSince1970: value) } private func getFormattedDistanceText(value: Double) -> String { return "" + "\(Int(value))" + " " + UnitHelper.getDistanceUnit() } private func setProgressBarPlanElementColor(color: UIColor) { contentLayout!.progressViewPlanElement.trackTintColor = color } }
// // Parametrics.swift // ArsNovis // // Created by Matt Brandt on 3/23/16. // Copyright © 2016 WalkingDog Design. All rights reserved. // import Cocoa enum MeasurementType: Int { case distance, angle } /// Parametric Value - represents a property of type CGFloat or CGPoint class ParametricNode: NSObject, NSCoding, NSPasteboardReading, NSPasteboardWriting { var context: ParametricContext? var value: NSValue var image = NSImage() var count: Int { return 1 } init(context: ParametricContext?) { self.context = context value = NSNumber(value: 0) super.init() createImage() } required init?(coder decoder: NSCoder) { if let context = decoder.decodeObject(forKey: "context") as? ParametricContext { self.context = context self.value = NSNumber(value: 0) } else { return nil } super.init() createImage() } required init?(pasteboardPropertyList propertyList: Any, ofType type: NSPasteboard.PasteboardType) { fatalError("init(pasteboardPropertyList:ofType:) has not been implemented") } static func readableTypes(for pasteboard: NSPasteboard) -> [NSPasteboard.PasteboardType] { return [ParametricItemUTI] } func writableTypes(for pasteboard: NSPasteboard) -> [NSPasteboard.PasteboardType] { return [ParametricItemUTI] } func pasteboardPropertyList(forType type: NSPasteboard.PasteboardType) -> Any? { let data = NSKeyedArchiver.archivedData(withRootObject: self) return data } func encode(with encoder: NSCoder) { encoder.encode(context, forKey: "context") } var isVariable: Bool { return false } override var description: String { return "node" } func dependsOn(_ node: ParametricNode) -> Bool { return node == self } var variableNode: ParametricNode? { return nil } var targetString: String { return "-node-" } var baseHue: CGFloat { return 0.6 } var origin = CGPoint(x: 0, y: 0) var frame: CGRect { return CGRect(origin: origin, size: image.size) } func createImage(_ width: CGFloat = 0) { if self.targetString == "" { return } let targetString = AttributedString(string: self.targetString) var imageSize = targetString.size() let stringWidth = imageSize.width if width > 0 { imageSize.width = width } else { imageSize.width += 8 } let offset = (imageSize.width - stringWidth) / 2 image = NSImage(size: imageSize) image.lockFocus() let path = NSBezierPath(roundedRect: CGRect(origin: CGPoint(x: 0, y: 0), size: imageSize), xRadius: imageSize.height / 2, yRadius: imageSize.height / 2) var color = NSColor(calibratedHue: baseHue, saturation: 1.0, brightness: 1.0, alpha: 1.0) color.setStroke() color = NSColor(calibratedHue: baseHue, saturation: 0.2, brightness: 1.0, alpha: 1.0) color.setFill() path.lineWidth = 0.5 path.fill() path.stroke() targetString.draw(at: CGPoint(x: offset, y: 0)) image.unlockFocus() } func itemAtIndex(_ index: Int) -> ParametricNode { return self } func insertItem(_ item: ParametricNode, atIndex index: Int) -> ParametricNode { return self } func removeItemAtIndex(_ index: Int) -> ParametricNode? { return nil } func removeItem(_ item: ParametricNode) -> ParametricNode? { if item != self { return self } return nil } func indexOfItem(_ item: ParametricNode) -> Int? { if item == self { return 0 } return nil } func itemAtPoint(_ point: CGPoint) -> ParametricNode? { return frame.contains(point) ? self : nil } } class ParametricConstant: ParametricNode { override var targetString: String { return "\(value)" } init(value: NSValue, context: ParametricContext?) { super.init(context: context) self.value = value } required init?(coder decoder: NSCoder) { super.init(coder: decoder) if let value = decoder.decodeObject(forKey: "value") as? NSValue { self.value = value } else { return nil } } required init?(pasteboardPropertyList propertyList: Any, ofType type: NSPasteboard.PasteboardType) { fatalError("init(pasteboardPropertyList:ofType:) has not been implemented") } override func encode(with encoder: NSCoder) { super.encode(with: encoder) encoder.encode(value, forKey: "value") } override var description: String { return "\(value)" } override func insertItem(_ item: ParametricNode, atIndex index: Int) -> ParametricNode { if index == 0 { if let op = item as? ParametricOperation { return ParametricOperation(op: op.op, left: op.left, right: self, context: context) } return ParametricOperation(op: "?", left: item, right: self, context: context) } else { if let op = item as? ParametricOperation { return ParametricOperation(op: op.op, left: self, right: op.right, context: context) } return ParametricOperation(op: "?", left: self, right: item, context: context) } } } class ParametricValue: ParametricNode { var target: Graphic var name: String var type: InspectionType override var isVariable: Bool { return true } override var value: NSValue { get { if let v = target.value(forKey: name) as? CGFloat { return v } return CGFloat(0) } set { if let val = target.value(forKey: name) as? NSValue, val != newValue { //print("\(context.prefix)set \(self) = \(newValue)") target.setValue(newValue, forKey: name) } } } init(target: Graphic, name: String, type: InspectionType, context: ParametricContext?) { self.target = target self.name = name self.type = type super.init(context: context) } required init?(coder decoder: NSCoder) { if let target = decoder.decodeObject(forKey: "target") as? Graphic, let name = decoder.decodeObject(forKey: "name") as? String { self.target = target self.name = name self.type = InspectionType(rawValue: decoder.decodeInteger(forKey: "type")) ?? .float } else { return nil } super.init(coder: decoder) } required init?(pasteboardPropertyList propertyList: Any, ofType type: NSPasteboard.PasteboardType) { fatalError("init(pasteboardPropertyList:ofType:) has not been implemented") } override func encode(with encoder: NSCoder) { super.encode(with: encoder) encoder.encode(target, forKey: "target") encoder.encode(name, forKey: "name") encoder.encode(type.rawValue, forKey: "type") } override var description: String { return "G\(target.identifier).\(name)" } override var variableNode: ParametricNode? { return self } override var targetString: String { return "\(target.parametricName).\(name)" } override func insertItem(_ item: ParametricNode, atIndex index: Int) -> ParametricNode { if index == 0 { if let op = item as? ParametricOperation { return ParametricOperation(op: op.op, left: op.left, right: self, context: context) } return ParametricOperation(op: "?", left: item, right: self, context: context) } else { if let op = item as? ParametricOperation { return ParametricOperation(op: op.op, left: self, right: op.right, context: context) } return ParametricOperation(op: "?", left: self, right: item, context: context) } } } /// Parametric Variable - a named variable of type CGFloat or CGPoint class ParametricVariable: ParametricNode { override var targetString: String { return "\(name)" } var name: String override var value: NSValue { didSet { //print("\(context.prefix)\(self) set to \(value)") context?.resolve(self) } } var measurementType: MeasurementType override var isVariable: Bool { return true } var transformer: ValueTransformer { return measurementType == .angle ? AngleTransformer() : DistanceTransformer() } var stringValue: String { get { if let sv = transformer.transformedValue(value) as? String { return sv } return "\(value)" } set { if let v = transformer.reverseTransformedValue(newValue) as? NSValue { value = v } } } init(name: String, value: NSValue, type: MeasurementType, context: ParametricContext) { self.name = name measurementType = type super.init(context: context) self.value = value } required init?(coder decoder: NSCoder) { if let name = decoder.decodeObject(forKey: "name") as? String, let value = decoder.decodeObject(forKey: "value") as? NSValue { self.name = name measurementType = decoder.decodeBool(forKey: "isAngle") ? .angle : .distance super.init(coder: decoder) self.value = value } else { return nil } } required init?(pasteboardPropertyList propertyList: AnyObject, ofType type: String) { fatalError("init(pasteboardPropertyList:ofType:) has not been implemented") } override func encode(with encoder: NSCoder) { super.encode(with: encoder) encoder.encode(name, forKey: "name") encoder.encode(value, forKey: "value") encoder.encode(measurementType == .angle, forKey: "isAngle") } override var description: String { return "\(name)" } override var variableNode: ParametricNode? { return self } override func insertItem(_ item: ParametricNode, atIndex index: Int) -> ParametricNode { if index == 0 { if let op = item as? ParametricOperation { return ParametricOperation(op: op.op, left: op.left, right: self, context: context) } return ParametricOperation(op: "?", left: item, right: self, context: context) } else { if let op = item as? ParametricOperation { return ParametricOperation(op: op.op, left: self, right: op.right, context: context) } return ParametricOperation(op: "?", left: self, right: item, context: context) } } } class ParametricBinding: ParametricOperation { override var value: NSValue { get { return right?.value ?? 0.0 } set { right?.value = newValue left?.value = newValue } } init(left: ParametricNode, right: ParametricNode, context: ParametricContext?) { super.init(op: "=", left: left, right: right, context: context) } required init?(coder decoder: NSCoder) { super.init(coder: decoder) op = "=" } required init?(pasteboardPropertyList propertyList: AnyObject, ofType type: String) { fatalError("init(pasteboardPropertyList:ofType:) has not been implemented") } override func encode(with encoder: NSCoder) { super.encode(with: encoder) encoder.encode(left, forKey: "left") encoder.encode(right, forKey: "right") } func resolve() { if let left = left, let context = context, !context.isException(left) { //print("\(context.prefix)binding value \(left) = \(right) = \(right.value)") context.addException(left) if let v = right?.value { left.value = v } } } override var variableNode: ParametricNode? { return right?.variableNode } } class ParametricOperation: ParametricNode { var op: String var left: ParametricNode? var right: ParametricNode? var leftValue: NSValue { return left?.value ?? 0 } var rightValue: NSValue { return right?.value ?? 1 } override var value: NSValue { get { switch op { case "+": return leftValue + rightValue case "-": return leftValue - rightValue case "*": return leftValue * rightValue case "/": return leftValue / rightValue default: return rightValue } } set { //print("\(context.prefix)set \(self) = \(newValue)") switch op { case "+": if let left = left, left.isVariable { left.value = newValue - rightValue } else if let right = right, right.isVariable { right.value = newValue - leftValue } case "-": if let left = left, left.isVariable { left.value = rightValue + newValue } else if let right = right, right.isVariable { right.value = leftValue - newValue } case "*": if let left = left, left.isVariable { left.value = newValue / rightValue } else if let right = right, right.isVariable { right.value = newValue / leftValue } default: break } } } override var isVariable: Bool { if op == "=" { return right?.isVariable ?? false } return (left?.isVariable ?? false) || (right?.isVariable ?? false) } override var targetString: String { return op } init(op: String, left: ParametricNode?, right: ParametricNode?, context: ParametricContext?) { self.op = op self.left = left self.right = right super.init(context: context) } required init?(coder decoder: NSCoder) { if let op = decoder.decodeObject(forKey: "op") as? String, let left = decoder.decodeObject(forKey: "left") as? ParametricNode, let right = decoder.decodeObject(forKey: "right") as? ParametricNode { self.op = op self.left = left self.right = right } else { return nil } super.init(coder: decoder) } required init?(pasteboardPropertyList propertyList: AnyObject, ofType type: String) { fatalError("init(pasteboardPropertyList:ofType:) has not been implemented") } override func encode(with encoder: NSCoder) { super.encode(with: encoder) encoder.encode(op, forKey: "op") encoder.encode(left, forKey: "left") encoder.encode(right, forKey: "right") } override var description: String { return "\(left) \(op) \(right)" } override func dependsOn(_ node: ParametricNode) -> Bool { if let left = left, left.dependsOn(node) { return true } else if let right = right, right.dependsOn(node) { return true } else { return super.dependsOn(node) } } override var variableNode: ParametricNode? { return left?.variableNode ?? right?.variableNode } override var count: Int { return (left?.count ?? 0) + 1 + (right?.count ?? 0) } override func itemAtIndex(_ index: Int) -> ParametricNode { if let left = left, index < left.count { return left.itemAtIndex(index) } let index = index - (left?.count ?? 0) if index == 0 { return self } return right?.itemAtIndex(index - 1) ?? self } override func insertItem(_ item: ParametricNode, atIndex index: Int) -> ParametricNode { if let left = left, index < left.count { return ParametricOperation(op: op, left: left.insertItem(item, atIndex: index), right: right, context: context) } else { let index = index - (left?.count ?? 0) if index == 0 { if let op = item as? ParametricOperation { return ParametricOperation(op: op.op, left: left, right: right, context: context) } else if left == nil { return ParametricOperation(op: op, left: item, right: right, context: context) } else { let newOp = ParametricOperation(op: "?", left: left, right: item, context: context) return ParametricOperation(op: op, left: newOp, right: right, context: context) } } else if let right = right { let newRight = right.insertItem(item, atIndex: index - 1) return ParametricOperation(op: op, left: left, right: newRight, context: context) } else { return ParametricOperation(op: op, left: left, right: item, context: context) } } } override func removeItemAtIndex(_ index: Int) -> ParametricNode? { if let left = left, index < left.count { return left.removeItemAtIndex(index) } else { let index = index - (left?.count ?? 0) if index == 0 { return ParametricOperation(op: "?", left: left, right: right, context: context) } else { return right?.removeItemAtIndex(index - 1) } } } override func removeItem(_ item: ParametricNode) -> ParametricNode? { if item == self { return ParametricOperation(op: "?", left: left, right: right, context: context) } else { return ParametricOperation(op: op, left: left?.removeItem(item), right: right?.removeItem(item), context: context) } } override func itemAtPoint(_ point: CGPoint) -> ParametricNode? { return super.itemAtPoint(point) ?? left?.itemAtPoint(point) ?? right?.itemAtPoint(point) } override func indexOfItem(_ item: ParametricNode) -> Int? { if item == self { return left?.count ?? 0 } else if let index = left?.indexOfItem(item) { return index } else if let index = right?.indexOfItem(item) { return (left?.count ?? 0) + 1 + index } else { return nil } } } private func +(a: NSValue, b: NSValue) -> NSValue { if let a = a as? CGFloat, let b = b as? CGFloat { return a + b } else { return NSValue(point: a.pointValue + b.pointValue) } } private func -(a: NSValue, b: NSValue) -> NSValue { if let a = a as? CGFloat, let b = b as? CGFloat { return a - b } else { return NSValue(point: a.pointValue - b.pointValue) } } private func *(a: NSValue, b: NSValue) -> NSValue { if let a = a as? CGFloat, let b = b as? CGFloat { return a + b } else if let a = a as? CGFloat { return NSValue(point: a * b.pointValue) } else if let b = b as? CGFloat { return NSValue(point: a.pointValue * b) } else { return 1 } } private func /(a: NSValue, b: NSValue) -> NSValue { if let a = a as? CGFloat, let b = b as? CGFloat { return a + b } else if let b = b as? CGFloat { return NSValue(point: a.pointValue / b) } return 1 } @objc protocol ParametricContextDelegate { @objc optional func parametricContextDidUpdate(_ parametricContext: ParametricContext) } struct ObservationInfo { var target: Graphic var property: String } class ParametricContext: NSObject, NSCoding { var variablesByName: [String: ParametricVariable] = [:] var variables: [ParametricVariable] = [] var parametrics: [ParametricBinding] = [] var delegate: ParametricContextDelegate? var exceptions: [ParametricNode] = [] var prefix: String = "" var observing: [ObservationInfo] = [] var suspendCount = 0 override init() { super.init() } required init?(coder decoder: NSCoder) { super.init() if let variables = decoder.decodeObject(forKey: "variables") as? [ParametricVariable] { self.variables = variables for v in variables { variablesByName[v.name] = v } } if let parametrics = decoder.decodeObject(forKey: "parametrics") as? [ParametricBinding] { self.parametrics = parametrics for p in parametrics { if let left = p.left as? ParametricValue { let target = left.target startObserving(target, property: left.name) } } } print("New parametric context \(self)") showVariables() showParametrics() } func encode(with encoder: NSCoder) { encoder.encode(variables, forKey: "variables") encoder.encode(parametrics, forKey: "parametrics") } override func setValue(_ value: AnyObject?, forKey key: String) { if let value = value as? NSValue { if let v = variablesByName[key] { v.value = value } } } override func value(forUndefinedKey key: String) -> AnyObject? { if let pv = variablesByName[key] { return pv.value } return nil } func variableForKey(_ key: String) -> ParametricVariable? { return variablesByName[key] } func defineVariable(_ key: String, value: NSValue, type: MeasurementType) -> ParametricVariable { let pv = ParametricVariable(name: key, value: value, type: type, context: self) variables.append(pv) variablesByName[key] = pv return pv } func startObserving(_ target: Graphic, property: String) { print("\(self) registers for \(property) of G\(target.identifier)") observing.append(ObservationInfo(target: target, property: property)) target.addObserver(self, forKeyPath: property, options: NSKeyValueObservingOptions.new, context: nil) } func suspendObservation() { suspendCount += 1 if suspendCount > 1 { return } //print("\(self) suspends observation") for info in observing { //print(" remove observer G\(info.target.identifier).\(info.property)") info.target.removeObserver(self, forKeyPath: info.property) } } func resumeObservation() { suspendCount -= 1 if suspendCount > 0 { return } //print("\(self) resumes observation") for info in observing { //print(" add observer G\(info.target.identifier).\(info.property)") info.target.addObserver(self, forKeyPath: info.property, options: NSKeyValueObservingOptions.new, context: nil) } for p in parametrics { if let right = p.right, let left = p.left, right.isVariable { // reverse resolve to get new variables right.value = left.value } } } /// resolve -- propagate any changes to variable values to the rest of the context func resolve(_ depends: ParametricNode?) { let oldExceptions = exceptions let oldPrefix = prefix //print("\(prefix)resolving \(depends)") prefix += " " for p in parametrics { if depends == nil || p.dependsOn(depends!) { p.resolve() } } exceptions = oldExceptions prefix = oldPrefix //print("\(prefix)done resolving \(depends)") delegate?.parametricContextDidUpdate?(self) } func showVariables() { var vars: [String] = [] for v in variables { vars.append(v.description) } print("\(prefix)variables: \(vars)") } func showParametrics() { for p in parametrics { print("\(prefix)parametric: \(p)") } } func assign(_ target: Graphic, property: String, expression: ParametricNode) { let param = ParametricValue(target: target, name: property, type: target.inspectionTypeForKey(property), context: self) let assignment = ParametricBinding(left: param, right: expression, context: self) startObserving(target, property: property) parametrics = parametrics.filter { if let p = $0.left as? ParametricValue, p.target == target && p.name == property { return false } return true } parametrics.append(assignment) showParametrics() } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : AnyObject]?, context: UnsafeMutableRawPointer) { if let target = object as? Graphic, let keyPath = keyPath { if isException(target, key: keyPath) { return } //print("\(prefix)start observing \(keyPath) for G\(target.identifier), context = \(self), change = \(change![NSKeyValueChangeNewKey])") let oldPrefix = prefix prefix += " " let oldExceptions = exceptions for p in parametrics { if let pv = p.left as? ParametricValue, pv.target == target && pv.name == keyPath { if let left = p.left, let right = p.right, left.value != right.value { addException(left) right.value = left.value } } } exceptions = oldExceptions prefix = oldPrefix //print("\(prefix)end observing \(keyPath) for G\(target.identifier), context = \(self)") } } func showExceptions() { var exs: [String] = [] for ex in exceptions { exs.append(ex.description) } //print("\(prefix)exceptions: \(exs)") } func addException(_ node: ParametricNode) { exceptions.append(node) showExceptions() } func removeException(_ node: ParametricNode) { exceptions = exceptions.filter { $0 != node } showExceptions() } func isException(_ node: ParametricNode) -> Bool { return exceptions.contains(node) } func isException(_ graphic: Graphic, key: String) -> Bool { for ex in exceptions { if let pv = ex as? ParametricValue { if pv.target == graphic && pv.name == key { return true } } } return false } } // MARK: PARSING enum ParseToken { case number(CGFloat) case id(String) case `operator`(String) case error(String) case eof } enum ParseError: Error { case badExpression case badCharacter(Character) case badNumber case badFraction } class ParametricParser { var context: ParametricContext var type: MeasurementType var expression: ParametricNode var value: NSValue { return expression.value } private let EOF: Character = "\0" private var content = "" private var location: String.Index private var lastToken: ParseToken private var newDefinitions: [String] = [] private var defaultValue: NSValue = NSNumber(value: 0) private var lastch: Character { if location == content.endIndex { return EOF } return content[location] } init(context: ParametricContext, string: String, defaultValue: NSValue, type: MeasurementType) { self.defaultValue = defaultValue content = string location = content.startIndex self.context = context self.type = type lastToken = .eof expression = ParametricConstant(value: 0.0, context: context) if let t = try? getToken() { lastToken = t } if let v = try? addOperation() { expression = v } if newDefinitions.count > 0 { expression.value = defaultValue } } private func nextch() { if lastch != EOF && location != content.endIndex { location = content.index(after: location) } } private func skipSpace() { while lastch == " " || lastch == "\n" || lastch == "\t" { nextch() } } private func isUpperCase(_ c: Character) -> Bool { switch c { case "A"..."Z": return true default: return false } } private func isLowerCase(_ c: Character) -> Bool { switch c { case "a"..."z": return true default: return false } } private func isDigit(_ c: Character) -> Bool { switch c { case "0"..."9": return true default: return false } } private func isAlpha(_ c: Character) -> Bool { return isUpperCase(c) || isLowerCase(c) } private func isAlphaNumeric(_ c: Character) -> Bool { return isAlpha(c) || isDigit(c) } private func getToken() throws -> ParseToken { skipSpace() switch lastch { case "A"..."Z", "a"..."z": var s = "" while isAlphaNumeric(lastch) { s.append(lastch) nextch() } return .id(s) case "0"..."9": var s = "" while isDigit(lastch) { s.append(lastch) nextch() } if lastch == "." { s.append(lastch) nextch() while isDigit(lastch) { s.append(lastch) nextch() } } if lastch == "e" || lastch == "E" { s.append(lastch) nextch() if lastch == "-" { s.append(lastch) nextch() } while isDigit(lastch) { s.append(lastch) nextch() } } if let v = Double(s) { return .number(CGFloat(v)) } throw ParseError.badNumber case "+", "-", "*", "/", "(", ")", "\"", "'", "{", "}", ",": let op = String(lastch) nextch() return .operator(op) case EOF: return .eof default: let char = lastch nextch() throw ParseError.badCharacter(char) } } private func nextToken() throws { lastToken = try getToken() } private var defaultUnitMultiplier: CGFloat { switch measurementUnits { case .feet_dec, .inches_dec, .feet_frac, .inches_frac: // these default to inches return 100.0 case .millimeters: return 100 / 25.4 // default to millimeters case .meters: return 1000 * 100 / 25.4 // default to meters } } private var defaultUnitMultiplierNode: ParametricConstant { return ParametricConstant(value: defaultUnitMultiplier, context: context) } private func unary() throws -> ParametricNode { switch lastToken { case .operator("-"): try nextToken() switch try unary() { case let p as ParametricConstant: return ParametricConstant(value: 0 - p.value, context: context) case let p: let zero = ParametricConstant(value: 0, context: context) return ParametricOperation(op: "-", left: zero, right: p, context: context) } case let .id(s): try nextToken() if let p = context.variableForKey(s) { return p } else { newDefinitions.append(s) return context.defineVariable(s, value: 0, type: type) } case let .number(n): var n = n let p = ParametricConstant(value: n, context: context) try nextToken() if case .number(let numerator) = lastToken { try nextToken() if case .operator("/") = lastToken { try nextToken() if case .number(let denominator) = lastToken { try nextToken() n += numerator / denominator } else { throw ParseError.badFraction } } else { throw ParseError.badFraction } } switch lastToken { case .id("mm"): p.value = n * (100 / 25.4) try nextToken() case .id("m"): p.value = n * 1000 * (100 / 25.4) try nextToken() case .id("in"), .operator("\""): p.value = n * 100 try nextToken() case .id("ft"), .operator("'"): p.value = n * 1200 try nextToken() if case .number(_) = lastToken { let u = try unary() p.value = p.value + u.value } default: if type == .angle { p.value = n * PI / 180 // convert from degrees } else { p.value = n * defaultUnitMultiplier } } return p case .operator("{"): try nextToken() let x = try anyOperation() if case .operator(",") = lastToken { try nextToken() } else { throw ParseError.badExpression } let y = try anyOperation() if case .operator("}") = lastToken { try nextToken() if let xv = x.value as? CGFloat, let yv = y.value as? CGFloat { let pvalue = CGPoint(x: xv, y: yv) return ParametricConstant(value: NSValue(point: pvalue), context: context) } } throw ParseError.badExpression default: throw ParseError.badExpression } } private func timesOperation() throws -> ParametricNode { let p = try unary() switch lastToken { case .operator("*"): try nextToken() let q = try timesOperation() let qq = ParametricOperation(op: "/", left: q, right: defaultUnitMultiplierNode, context: context) return ParametricOperation(op: "*", left: p, right: qq, context: context) case .operator("/"): try nextToken() let q = try timesOperation() let qq = ParametricOperation(op: "/", left: q, right: defaultUnitMultiplierNode, context: context) return ParametricOperation(op: "/", left: p, right: qq, context: context) default: return p } } private func addOperation() throws -> ParametricNode { let p = try timesOperation() switch lastToken { case .operator("+"): try nextToken() let q = try addOperation() return ParametricOperation(op: "+", left: p, right: q, context: context) case .operator("-"): try nextToken() let q = try addOperation() return ParametricOperation(op: "-", left: p, right: q, context: context) default: return p } } private func anyOperation() throws -> ParametricNode { return try addOperation() } }
// // DemoCollectionCell.swift // DataSourcePratice // // Created by Vincent Lin on 2018/7/1. // Copyright © 2018 Vincent Lin. All rights reserved. // import Foundation import UIKit open class SampleCollectionCell: UICollectionViewCell, ReusableCell { var title: String? { didSet { guard let title = title else { return } self.titleLabel.text = "" self.titleLabel.text = title } } let titleLabel: UILabel = { let _titleLabel = UILabel() _titleLabel.textColor = .darkText _titleLabel.isHidden = true return _titleLabel }() public override init(frame: CGRect) { super.init(frame: frame) configure() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configure() } fileprivate func configure() { addSubview(titleLabel) } open override func layoutSubviews() { super.layoutSubviews() titleLabel.frame = self.bounds titleLabel.isHidden = false } }
// // Date+ToString.swift // DicodingMovieFirst // // Created by Kevin Yulias on 05/08/20. // Copyright © 2020 Kevin Yulias. All rights reserved. // import Foundation struct DateHelper { static func convertDateToStringByLocale(date: Date) -> String { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .none dateFormatter.locale = Locale.current return dateFormatter.string(from: date) } static func convertStringToDateString(from string: String) -> String? { let dateFormatter = ISO8601DateFormatter() let releaseDate = dateFormatter.date(from: string) let localeString = Self.convertDateToStringByLocale(date: releaseDate ?? Date()) return localeString } }
// // DeviceModal.swift // PaymentsApp // // Created by Chinmay Bapna on 11/08/20. // Copyright © 2020 Chinmay Bapna. All rights reserved. // import Foundation struct DeviceModal : Codable { var name : String var phone : String }
// // InterfaceController.swift // PollsFramework-watch Extension // // Created by Stefanita Oaca on 10/09/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import WatchKit import Foundation import PollsFramework class PollsInterfaceController: WKInterfaceController { @IBOutlet var lblNoData: WKInterfaceLabel! @IBOutlet var pollsTable: WKInterfaceTable! var array: [Poll]! override func awake(withContext context: Any?) { super.awake(withContext: context) array = PollsFrameworkController.sharedInstance.dataController().getAllObjectsFor(entityName: "Poll") as! [Poll] pollsTable.setNumberOfRows(array.count, withRowType: "pollsRow") for index in 0..<array.count { if let controller = pollsTable.rowController(at: index) as? PollsRowController { controller.poll = array[index] } } lblNoData.setHidden(array.count != 0) // Configure interface objects here. } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } override func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) { let poll = array[rowIndex] if poll.pollTypeId == PollTypes.singleText.rawValue{ pushController(withName: "SingleTextPoll", context: poll) }else if poll.pollTypeId == PollTypes.bestText.rawValue{ pushController(withName: "BestTextPoll", context: poll) }else if poll.pollTypeId == PollTypes.singleImage.rawValue{ pushController(withName: "SingleImagePoll", context: poll) }else if poll.pollTypeId == PollTypes.bestImage.rawValue{ pushController(withName: "BestImagePoll", context: poll) } } }
// // Constants.swift // FCCWW // // Created by user162489 on 2/6/20. // Copyright © 2020 FCCWW. All rights reserved. // import Foundation import UIKit struct Colors{ // UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0) // Instagram Colors static let instagramPurpleViolet = UIColor(red: 138.0/255.0, green: 58.0/255.0, blue: 185.0/255.0, alpha: 1.0) static let instagramRedOrange = UIColor(red: 233.0/255.0, green: 89.0/255.0, blue: 80.0/255.0, alpha: 1.0) static let instagramRedViolet = UIColor(red: 188.0/255.0, green: 42.0/255.0, blue: 141.0/255.0, alpha: 1.0) static let instagramYellow = UIColor(red: 252.0/255.0, green: 204.0/255.0, blue: 99.0/255.0, alpha: 1.0) static let instagramOrange = UIColor(red: 251.0/255.0, green: 173.0/255.0, blue: 80.0/255.0, alpha: 1.0) static let instagramMaroon = UIColor(red: 250.0/255.0, green: 72.0/255.0, blue: 107.0/255.0, alpha: 1.0) static let instagramBlue = UIColor(red: 76.0/255.0, green: 104.0/255.0, blue: 215.0/255.0, alpha: 1.0) // Facebook Blue static let facebookBlue = UIColor(red: 59.0/255.0, green: 89.0/255.0, blue: 152.0/255.0, alpha: 1.0) // Twitter Blue static let twitterBlue = UIColor(red: 85.0/255.0, green: 172.0/255.0, blue: 238.0/255.0, alpha: 1.0) // Tumblr Turquoise static let tumblrTurquoise = UIColor(red: 50.0/255.0, green: 80.0/255.0, blue: 109.0/255.0, alpha: 1.0) }
// // RXSwiftDemoForCurrencyApp.swift // RXSwiftDemoForCurrency // // Created by Knoxpo MacBook Pro on 19/04/21. // import SwiftUI @main struct RXSwiftDemoForCurrencyApp: App { var body: some Scene { WindowGroup { // ContentView() InfiniteScrollView() } } }
import Foundation import FileSystem import Url import POSIX /** . └── your app/ ├── _highway/ │   ├── .gitignore │   ├── .build/ │ ├── .project_description.json │   ├── Package.resolved │   ├── Package.swift │   ├── config.xcconfig │   └── main.swift ├── _highway.xcodeproj/ └── your app.xcodeproj/ */ public final class HighwayBundle { // MARK: - Init public init(url: Absolute, fileSystem: FileSystem, configuration: Configuration = .standard) throws { try fileSystem.assertItem(at: url, is: .directory) self.url = url self.fileSystem = fileSystem self.configuration = configuration } public convenience init(fileSystem: FileSystem, parentUrl: Absolute = abscwd(), configuration: Configuration = .standard) throws { let url = parentUrl.appending(configuration.directoryName) try self.init(url: url, fileSystem: fileSystem, configuration: configuration) } // MARK: - Properties public let url: Absolute public let fileSystem: FileSystem public let configuration: Configuration public var xcodeprojectParent: Absolute { return url.parent } public var xcodeprojectUrl: Absolute { return url.parent.appending(configuration.xcodeprojectName) } // MARK: - Writing public func write(xcconfigData data: Data) throws { try fileSystem.writeData(data, to: xcconfigFileUrl) } public func write(gitignore data: Data) throws { try fileSystem.writeData(data, to: url.appending(configuration.gitignoreName)) } public func write(mainSwiftData data: Data) throws { try fileSystem.writeData(data, to: mainSwiftFileUrl) } public func write(packageDescription data: Data) throws { try fileSystem.writeData(data, to: packageFileUrl) } public func write(projectDescription: ProjectDescription) throws { let data = try JSONEncoder().encode(projectDescription) try fileSystem.writeData(data, to: projectDescriptionUrl) } // MARK: - Deleting public func deletePinsFileIfPresent() throws -> Absolute? { return try fileSystem.delete(file: pinsFileUrl) } public func deleteBuildDirectoryIfPresent() throws -> Absolute? { return try fileSystem.delete(directory: buildDirectory) } public func deleteProjectDescriptionIfPresent() throws -> Absolute? { return try fileSystem.delete(file: projectDescriptionUrl) } // MARK: - Working with the Bundle public var gitignoreFileUrl: Absolute { return url.appending(configuration.gitignoreName) } public var xcconfigFileUrl: Absolute { return url.appending(configuration.xcconfigName) } public var projectDescriptionUrl: Absolute { return url.appending(configuration.projectDescriptionName) } public var mainSwiftFileUrl: Absolute { return url.appending(configuration.mainSwiftFileName) } public var packageFileUrl: Absolute { return url.appending(configuration.packageSwiftFileName) } private var pinsFileUrl: Absolute { return url.appending(configuration.pinsFileName) } public var buildDirectory: Absolute { return url.appending(configuration.buildDirectoryName) } // MARK: - Cleaning public struct CleanResult { public let deletedFiles: [Absolute] } /// Removes build artifacts and calculateable information from the /// highway bundle = the folder that contains your custom "highfile". public func clean() throws -> CleanResult { return CleanResult(deletedFiles: [ try deletePinsFileIfPresent(), try deleteBuildDirectoryIfPresent(), try deleteProjectDescriptionIfPresent() ].flatMap { $0 } ) } public func executableUrl(swiftBinUrl: Absolute) -> Absolute { return swiftBinUrl.appending(configuration.targetName) } } extension HighwayBundle { public struct Configuration { // MARK: - Getting the default Configuration public static let standard: Configuration = { var config = Configuration() config.branch = env("HIGHWAY_BUNDLE_BRANCH", defaultValue: "master") return config }() // MARK: - Properties public var mainSwiftFileName = "main.swift" public var packageSwiftFileName = "Package.swift" public var xcodeprojectName = "_highway.xcodeproj" public var packageName = "_highway" public var targetName = "_highway" public var directoryName = "_highway" public var buildDirectoryName = ".build" // there is a bug in PM: generating the xcode project causes .build to be used every time... public var pinsFileName = "Package.resolved" // MARK: - Properties / Convenience public var xcconfigName = "config.xcconfig" public var gitignoreName = ".gitignore" public var projectDescriptionName = ".project_description.json" // MARK: - Private Stuff public var branch = "master" } }
// // RecordingDataModel.swift // recoder // // Created by 陳昱豪 on 2019/11/21. // Copyright © 2019 Chen_Yu_Hao. All rights reserved. // import Foundation struct Recording { let fileURL: URL let createdAt: Date } struct Songinfo:Identifiable,Codable{ var id = UUID() var filename:String var singer:String }
// // DataAcess.swift // WikiSearch // // Created by user142467 on 9/30/18. // Copyright © 2018 user142467. All rights reserved. // import Foundation import CoreData class DataAccess{ var context = CoreDataStack.shared.persistentContainer.viewContext func loadSearchData(text:String, complete: @escaping ((WikiSearchData?)-> Void)){ let baseUrl = "https://en.wikipedia.org//w/api.php?action=query&format=json&prop=pageimages%7Cpageterms&generator=prefixsearch&redirects=1&formatversion=2&piprop=thumbnail&pithumbsize=50&pilimit=10&wbptterms=description&gpssearch=\(text.formattedString())&gpslimit=10" let url = URL.init(string: baseUrl) let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in guard let data = data else {return } do{ let searchResult = try JSONDecoder().decode(WikiSearchData.self, from: data) //JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as! [String:Any] print(searchResult) complete(searchResult) }catch{ print(error.localizedDescription) complete(nil) } } task.resume() } func saveData(page:Page , complete: @escaping ((Bool) -> Void)){ let pageData = PageData(context: context) pageData.title = page.title ?? "" pageData.pageDescription = page.terms?.description?.first ?? "" pageData.imageUrl = page.thumbnail!.source ?? "" CoreDataStack.shared.saveContext() } func deleteData(complete: @escaping ((Bool) -> Void)){ let request:NSFetchRequest<PageData> = PageData.fetchRequest() let deleteRequest = NSBatchDeleteRequest(fetchRequest: request as! NSFetchRequest<NSFetchRequestResult>) do{ try context.execute(deleteRequest) complete(true) }catch{ print(error.localizedDescription) complete(false) } } func loadPersistedData(complete: @escaping (([PageData]?) -> Void)){ let request:NSFetchRequest<PageData> = PageData.fetchRequest() do{ let pageData = try context.fetch(request) complete(pageData) }catch{ print(error.localizedDescription) complete(nil) } } }
// // HomeWebViewController.swift // Weibo10 // // Created by male on 15/10/31. // Copyright © 2015年 itheima. All rights reserved. // import UIKit class HomeWebViewController: UIViewController { private lazy var webView = UIWebView() private var url: NSURL // MARK: - 构造函数 init(url: NSURL) { self.url = url super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { view = webView title = "网页" } override func viewDidLoad() { super.viewDidLoad() webView.loadRequest(NSURLRequest(URL: url)) } }
//: [Previous](@previous) import Foundation import RxSwift // Imagine an Observable Sequence that consists of objects that are themselves Observables and you want to create a new Sequence from those. This is where FlatMap comes into play. FlatMap merges the emission of these resulting Observables and emitting these merged results as its own sequence. let sequence1 = Observable<Int>.of(1,2) let sequence2 = Observable<Int>.of(1,2) let sequenceOfSequences = Observable.of(sequence1,sequence2) sequenceOfSequences.flatMap{ return $0 }.subscribe(onNext:{ print($0) }) //: [Next](@next)
// // Day112DArrays.swift // Datasnok // // Created by Vladimir Urbano on 7/8/16. // Copyright © 2016 Vladimir Urbano. All rights reserved. // /* Objective Today, we're building on our knowledge of Arrays by adding another dimension. Check out the Tutorial tab for learning materials and an instructional video! Context Given a 2D Array, : 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 We define an hourglass in to be a subset of values with indices falling in this pattern in 's graphical representation: a b c d e f g There are hourglasses in , and an hourglass sum is the sum of an hourglass' values. Task Calculate the hourglass sum for every hourglass in , then print the maximum hourglass sum. Input Format There are lines of input, where each line contains space-separated integers describing 2D Array ; every value in will be in the inclusive range of to . Constraints Output Format Print the largest (maximum) hourglass sum found in . Sample Input 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 2 4 4 0 0 0 0 2 0 0 0 0 1 2 4 0 Sample Output 19 Explanation contains the following hourglasses: 1 1 1 1 1 0 1 0 0 0 0 0 1 0 0 0 1 1 1 1 1 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 1 0 0 0 0 2 0 2 4 2 4 4 4 4 0 1 1 1 1 1 0 1 0 0 0 0 0 0 2 4 4 0 0 0 0 0 2 0 2 0 2 0 0 0 0 2 0 2 4 2 4 4 4 4 0 0 0 2 0 0 0 1 0 1 2 1 2 4 2 4 0 The hourglass with the maximum sum () is: 2 4 4 2 1 2 4 */ class Day112DArrays { init() { var input = Array<Array<Int>>() for _ in 1 ... 6 { let arr = readLine()!.componentsSeparatedByString(" ").map({ Int(String($0))! }) input.append(arr) } var max = -200 for i in 0 ..< input.count - 2 { for j in 0 ..< input[i].count - 2 { let a = (input[i][j], input[i][j + 1], input[i][j + 2]) let b = (input[i + 1][j + 1]) let c = (input[i + 2][j], input[i + 2][j + 1], input[i + 2][j + 2]) let hourglass = (a, b, c) let sum = hourglass.0.0 + hourglass.0.1 + hourglass.0.2 + hourglass.1 + hourglass.2.0 + hourglass.2.1 + hourglass.2.2 if sum > max { max = sum } } } print(max) } }
// // DayPickerView.swift // Weatherer // // Created by HexaHack on 4/2/20. // Copyright © 2020 HexaHack. All rights reserved. // import UIKit protocol DayPickerViewDataSource { func dayPickerCount(_ dayPicker: DayPickerView) -> Int func dayPickerTitle(_ dayPicker: DayPickerView, indexPath: IndexPath) -> String } class DayPickerView: UIControl { public var dataSourse: DayPickerViewDataSource? { didSet { setupView() self.backgroundColor = .systemPink } } private var buttons: [UIButton] = [] private var stackView: UIStackView! public var onButtonPressed: Int = 0 public var myVC: ViewController? = nil override func layoutSubviews() { super.layoutSubviews() stackView.frame = bounds } func setupView() { let count = dataSourse?.dayPickerCount(self) for item in 0..<count! { let indexPath = IndexPath(row: item, section: 0) let title = dataSourse?.dayPickerTitle(self, indexPath: indexPath) let button = UIButton(type: .system) button.setTitle(title, for: .normal) button.tag = item button.setTitleColor(UIColor.lightGray, for: .normal) button.setTitleColor(UIColor.white, for: .selected) button.addTarget(self, action: #selector(selectedButton), for: .touchUpInside) buttons.append(button) self.addSubview(button) } buttons[0].isSelected = true stackView = UIStackView(arrangedSubviews: self.buttons) self.addSubview(stackView) stackView.backgroundColor = .systemPink stackView.spacing = 8 stackView.axis = .horizontal stackView.distribution = .fillEqually stackView.alignment = .center } @objc func selectedButton(sender: UIButton) { for b in buttons { b.isSelected = false } let index = sender.tag let button = self.buttons[index] button.isSelected = true onButtonPressed = index * 6 myVC?.getImage(forecastIndex: onButtonPressed) } }
// // BrowseViewModel.swift // CrushAndLovelyCodingTest // // Created by Kervins Valcourt on 1/3/17. // Copyright © 2017 Crush and Lovely. All rights reserved. // import Foundation import YelpAPI import CoreLocation class BrowseViewModel: NSObject { private var yelpClient: YLPClient? weak var delegate: BrowseViewModelDelegate? var businesses: [Business?] override init() { businesses = [] super.init() } func createYelpClient() { YLPClient.authorize(withAppId: yelpAppID, secret: yelpAppSecret) { client, err in self.yelpClient = client if client == nil { print("Authentication failed: \(err)") } else { self.delegate?.browseViewModelYelpClientCreate(self) } } } func fetchYelpLocationsNearUser(latitude: Double = currentUserLocation.coordinate.latitude, longitude: Double = currentUserLocation.coordinate.longitude) { yelpClient?.search(with: YLPCoordinate(latitude: latitude, longitude: longitude), completionHandler: { result, err in if result != nil { if let yelpBusinessItems = result?.businesses { for item in yelpBusinessItems { let bizModel = Business(model: item) self.businesses.append(bizModel) } self.delegate?.browseViewModelDidUpdateBusinessesNearUser(self, businesses: self.businesses) } } else { print("Search failed: \(err)") } }) } } protocol BrowseViewModelDelegate: class { func browseViewModelYelpClientCreate(_ browseViewModel: BrowseViewModel) func browseViewModelDidUpdateBusinessesNearUser(_ browseViewModel: BrowseViewModel, businesses: [Business?]) }
// // CadastrarCoachViewController.swift // WorkFit // // Created by Marllon Sóstenes on 10/03/17. // Copyright © 2017 Work Fit Team. All rights reserved. // import UIKit import FirebaseAuth import Firebase import FirebaseStorage class CadastrarCoachViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet weak var editEmail: TxtFieldImg! @IBOutlet weak var editNome: TxtFieldImg! @IBOutlet weak var editSenha: TxtFieldImg! @IBOutlet weak var imgView: UIImageView! var currentUserRef = FIRDatabaseReference() let databaseRef = FIRDatabase.database().reference() let storageRef = FIRStorage.storage().reference() override func viewDidLoad() { super.viewDidLoad() self.navigationController?.isNavigationBarHidden = false editSenha.delegate = self editEmail.delegate = self editNome.delegate = self roundAndShowImage(img: imgView, str: "https://firebasestorage.googleapis.com/v0/b/workfit-27ade.appspot.com/o/pic%2F0.jpg?alt=media&token=8a2e5751-407c-4a43-86a2-f8339c973a61") } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == editEmail.self{ editNome.becomeFirstResponder() } if textField == editNome.self{ editSenha.becomeFirstResponder() } if textField == editSenha.self{ editEmail.becomeFirstResponder() } return true } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } func roundAndShowImage(img: UIImageView, str: String) { img.loadImageUsingCacheWithUrlString(str) img.layer.cornerRadius = img.frame.size.height/2 img.clipsToBounds = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func carregaImg(_ sender: Any) { let picker = UIImagePickerController() picker.delegate = self picker.allowsEditing = true picker.sourceType = UIImagePickerControllerSourceType.photoLibrary self.present(picker, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let image = info[UIImagePickerControllerOriginalImage] as! UIImage let imageUrl = info[UIImagePickerControllerReferenceURL] as? NSURL let imageName = imageUrl?.lastPathComponent let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let photoURL = URL(fileURLWithPath: documentDirectory) let localPath = photoURL.appendingPathComponent(imageName!) var selectedImageFromPicker: UIImage? if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage{ selectedImageFromPicker = editedImage } else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage{ selectedImageFromPicker = originalImage } if let selectedImage = selectedImageFromPicker{ imgView.image = selectedImage } dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } @IBAction func bSaveCoach(_ sender: UIButtonBorder) { if (editEmail.text == "") || (editSenha.text == "") || (editNome.text == "") { let alert = UIAlertController(title: "Atenção", message: "Insira todos os campos para concluir o cadastro", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } else { handleEmailPasswordSignUp() self.saveChanges() } } func handleEmailPasswordSignUp(){ FIRAuth.auth()!.createUser(withEmail: editEmail.text!, password: editSenha.text!, completion: {(user, error) in if error == nil{ self.saveChanges() } else { let alert = UIAlertController(title: "Atenção", message: (error?.localizedDescription)! as String, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) print((error?.localizedDescription)! as String) } }) } func saveChanges(){ if let users = FIRAuth.auth()?.currentUser { let uid = users.uid; self.databaseRef.child("Clients").child(uid).setValue(["email": users.email]) self.databaseRef.child("Clients").child(uid).updateChildValues(["id": uid]) self.databaseRef.child("Clients").child(uid).updateChildValues(["Senha": self.editSenha.text!]) self.databaseRef.child("Clients").child(uid).updateChildValues(["name": editNome.text!]) self.databaseRef.child("Clients").child(uid).updateChildValues(["levelAcess": "2"]) let data = UIImagePNGRepresentation(self.imgView.image!) let storedImage = storageRef.child("pic").child(uid) storedImage.put(data!, metadata: nil) { (metadata, error) in guard let metadata = metadata else { DispatchQueue.main.async { let alert = UIAlertController(title: "Atenção", message: "Um erro ocorreu ao fazer o upload da imagem. Selecione a imagem novamente.", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } return } self.databaseRef.child("Clients").child(uid).updateChildValues(["pic": "\(metadata.downloadURL()!)"]) userPic = "\(metadata.downloadURL()!)" self.dismiss(animated: true, completion: nil) } } } }
// // MapViewController.swift // MemorablePlaces // // Created by Charles Martin Reed on 9/15/18. // Copyright © 2018 Charles Martin Reed. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate{ @IBOutlet weak var mapView: MKMapView! //MARK:- User location information var userLocationCoordinates = CLLocationCoordinate2D() var userLocationTitle = "" var userLocationSubtitle = "" let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self //MARK:- Location manager setup locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() //MARK:- Dummy data map setup //set up the map for the first bit of data, Tower Bridge in London // let lat: CLLocationDegrees = 51.505153 // let long: CLLocationDegrees = -0.075664 // // let latDelta: CLLocationDegrees = 0.05 // let longDelta: CLLocationDegrees = 0.05 // // let location: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: lat, longitude: long) // // let span: MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: longDelta) // // let region: MKCoordinateRegion = MKCoordinateRegion(center: location, span: span) // // mapView.setRegion(region, animated: true) //MARK:- Dummy data annotation setup // let annotation = MKPointAnnotation() // annotation.title = "Tower Bridge" // annotation.subtitle = "Contrary to popular belief, the bridge is not falling down." // annotation.coordinate = location // // mapView.addAnnotation(annotation) } //MARK:- Grabbing the location the user touched and placing a pin there func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //if there's a location to grab, grab the first one let userLocation = locations[0] //build and show the map in the view makeMap(lat: userLocation.coordinate.latitude, long: userLocation.coordinate.longitude) CLGeocoder().reverseGeocodeLocation(userLocation) { (placemarks, error) in if error != nil { print(error?.localizedDescription) } else { //update the user variables guard let placemark = placemarks?[0] else { return } if let thoroughfare = placemark.thoroughfare { if let subthoroughfare = placemark.subThoroughfare { self.userLocationTitle = subthoroughfare + " " + thoroughfare } } if let sublocality = placemark.subLocality { self.userLocationSubtitle = sublocality } //MARK:- User created annotation setup let longPressRecognizer: UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(self.placeAnnotation(_:))) longPressRecognizer.minimumPressDuration = 1 self.mapView.addGestureRecognizer(longPressRecognizer) } } } @objc func placeAnnotation(_ gestureRecognizer: UIGestureRecognizer) { //grab the location from where the user long-pressed let touchPoint = gestureRecognizer.location(in: self.mapView) //conver the touch point into a location let coordinate = mapView.convert(touchPoint, toCoordinateFrom: self.mapView) //create the annotation, per usual let userAnnotation = MKPointAnnotation() userAnnotation.coordinate = coordinate userAnnotation.title = userLocationTitle userAnnotation.subtitle = userLocationSubtitle mapView.addAnnotation(userAnnotation) } @objc func makeMap(lat: CLLocationDegrees, long: CLLocationDegrees) { //MARK:- User location map setup //set up the map for the first bit of data, Tower Bridge in London let latDelta: CLLocationDegrees = 0.05 let longDelta: CLLocationDegrees = 0.05 let location: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: lat, longitude: long) let span: MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: latDelta, longitudeDelta: longDelta) let region: MKCoordinateRegion = MKCoordinateRegion(center: location, span: span) mapView.setRegion(region, animated: true) //put an annotation denoting where the user is let annotation = MKPointAnnotation() annotation.coordinate = location annotation.title = "You are here." annotation.subtitle = "Creepy, no?" mapView.addAnnotation(annotation) } @objc func saveLocation(latitude lat: CLLocationDegrees, longitude long: CLLocationDegrees) { //take the user location and lat and store them UserDefaults.standard.set(lat, forKey: "userLat") UserDefaults.standard.set(long, forKey: "userLong") } }
// // PokemonDetailViewController.swift // PokemonSearch // // Created by Jocelyn Stuart on 1/25/19. // Copyright © 2019 JS. All rights reserved. // import UIKit class PokemonDetailViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() updateViews() // Do any additional setup after loading the view. } var pokemon: Pokemon? { didSet { updateViews() } } var pokemonController: PokemonController? /* // 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. } */ @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var idLabel: UILabel! @IBOutlet weak var typeLabel: UILabel! @IBOutlet weak var abilitiesLabel: UILabel! func updateViews() { if let pokemon = pokemon, isViewLoaded { nameLabel.text = pokemon.name idLabel.text = "ID: \(pokemon.id)" typeLabel.text = "Abilities: " + pokemon.abilities.map({ $0.ability.name}).joined(separator: ", ") abilitiesLabel.text = "Types: " + pokemon.types.map({ $0.type.name }).joined(separator: ", ") navigationItem.title = pokemon.name } } }
// // AddItemTableViewController.swift // ToDoApp // // Created by Akhil Singh on 29/05/19. // Copyright © 2019 Akhil Singh. All rights reserved. // import UIKit class ItemDetailViewController: UITableViewController { @IBOutlet weak var addNotesLabel: UILabel! @IBOutlet weak var itemNotesTextView: UITextView! @IBOutlet weak var priorityLabel: UILabel! @IBOutlet weak var addPriorityButton: UIButton! var toBeEditedItem:ToDoItem? var itemList:ToDoList? var toBeEditedIndex:IndexPath? var priorityObject:Priority = .no @IBOutlet weak var doneBarButtonItem: UIBarButtonItem! @IBOutlet weak var addItemTextField: UITextField! var itemUpdateHandler:((ToDoItem,IndexPath?)->Void)! override func viewDidLoad() { super.viewDidLoad() addItemTextField.attributedPlaceholder = NSAttributedString(string: "Add Item", attributes: [NSAttributedString.Key.foregroundColor: appThemeColorFaded]) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let item = toBeEditedItem{ addItemTextField.text = item.itemName itemNotesTextView.text = item.itemDescription ?? "" if let notes = item.itemDescription{ itemNotesTextView.text = notes showTextViewPlaceholderIfNotesAreEmpty(notes) } self.title = "Edit Item" addPriorityButton.isHidden = true } else{ self.title = "Add Item" addPriorityButton.isHidden = false } addItemTextField.becomeFirstResponder() } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { return nil } private func showTextViewPlaceholderIfNotesAreEmpty(_ notes:String){ if notes.count > 0{ addNotesLabel.isHidden = true } else{ addNotesLabel.isHidden = false } } private func enableDoneButtonBasedOnChanges(_ changedString:String){ if changedString.isEmpty{ doneBarButtonItem.isEnabled = false } else{ doneBarButtonItem.isEnabled = true } } @IBAction func addPriority(_ sender: Any) { let priorityActionSheet = UIAlertController(title: "", message: "Select Priority", preferredStyle: .actionSheet) let highAction = UIAlertAction(title: "High", style: .default) { (action) in self.updatePriority(.high) } priorityActionSheet.addAction(highAction) let mediumAction = UIAlertAction(title: "Medium", style: .default) { (action) in self.updatePriority(.medium) } priorityActionSheet.addAction(mediumAction) let lowAction = UIAlertAction(title: "Low", style: .default) { (action) in self.updatePriority(.low) } priorityActionSheet.addAction(lowAction) self.present(priorityActionSheet, animated: true, completion: nil) priorityActionSheet.view.tintColor = appThemeColor } private func updatePriority(_ priority:Priority){ priorityObject = priority doneBarButtonItem.isEnabled = true switch priority { case .high: priorityLabel.text = "!!!" break case .medium: priorityLabel.text = "!!" break case .low: priorityLabel.text = "!" break default: priorityLabel.text = "" } } @IBAction func cancel(_ sender: Any) { self.navigationController?.popViewController(animated: true) } @IBAction func done(_ sender: Any) { let trimmedItemName = addItemTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) if itemList?.checkIfItemAlreadyExists(trimmedItemName ?? "") ?? false{ let itemExistAlert = UIAlertController(title: "", message: "Item already exists", preferredStyle: .alert) let okAlertAction = UIAlertAction(title: "OK", style: .default, handler: nil) itemExistAlert.addAction(okAlertAction) self.present(itemExistAlert, animated: true, completion: nil) return } if let handler = itemUpdateHandler{ if let editedItem = toBeEditedItem{ let itemData:NSDictionary = NSDictionary(dictionary: [itemName:trimmedItemName ?? "",itemPriority:editedItem.itemPriority,itemDescription:itemNotesTextView.text ?? ""]) itemList?.updateToDoItem(editedItem, itemDict: itemData as NSDictionary) handler(editedItem, toBeEditedIndex) } else{ let itemData:NSDictionary = NSDictionary(dictionary: [itemName:trimmedItemName ?? "",isCompleted:false,itemPriority:priorityObject.rawValue,itemDescription:"",itemReminderDate:NSDate(),itemDescription:itemNotesTextView.text ?? ""]) let toDoItem = itemList?.createAToDoItem(itemData as NSDictionary) ?? ToDoItem() handler(toDoItem,toBeEditedIndex) } } self.navigationController?.popViewController(animated: true) } } extension ItemDetailViewController:UITextFieldDelegate{ func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return false } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let oldText = textField.text, let stringRange = Range(range, in: oldText) else { return false } let newText = oldText.replacingCharacters(in: stringRange, with: string) enableDoneButtonBasedOnChanges(newText) return true } } extension ItemDetailViewController:UITextViewDelegate{ func textViewDidChange(_ textView: UITextView) { showTextViewPlaceholderIfNotesAreEmpty(textView.text) enableDoneButtonBasedOnChanges(textView.text) } }
import Foundation public class TitleValueTransformer: ValueTransformer { override public class func transformedValueClass() -> AnyClass { NSString.self } override public class func allowsReverseTransformation() -> Bool { false } override public func transformedValue(_ value: Any?) -> Any? { if let defined = value, let isOffline = defined as? Bool, isOffline { return "Connect Offline to Local Sparta" } return "Connect to Sparta Science" } }
import XCTest @testable import AroundTheTableTests XCTMain([ testCase(ExtensionsTests.allTests), testCase(StencilFiltersTests.allTests), // Models testCase(ActivityTests.allTests), testCase(ActivityRegistrationTests.allTests), testCase(BSONExtensionsTests.allTests), testCase(ConversationTests.allTests), testCase(ConversationMessageTests.allTests), testCase(CoordinatesTests.allTests), testCase(GameTests.allTests), testCase(LocationTests.allTests), testCase(NotificationTests.allTests), testCase(UserTests.allTests), testCase(SponsorTests.allTests), // Persistence testCase(ActivityRepositoryTests.allTests), testCase(ConversationRepositoryTests.allTests), testCase(CredentialsRepositoryTests.allTests), testCase(GameRepositoryTests.allTests), testCase(NotificationRepositoryTests.allTests), testCase(SponsorRepositoryTests.allTests), testCase(UserRepositoryTests.allTests), // Middleware testCase(ForwardingMiddlewareTests.allTests), // Routes testCase(RoutesTests.allTests), // Services testCase(CloudObjectStorageTests.allTests) ])
// // WalletController.swift // mojo_test // // Created by Yunyun Chen on 12/21/18. // Copyright © 2018 Yunyun Chen. All rights reserved. // import UIKit import Firebase import SDWebImage class WalletController: BaseListController, UICollectionViewDelegateFlowLayout { let cellId = "cellId" let headerCellId = "headerCellId" let emptyLabel = UILabel(text: "You will receive gifts in your wallet when accept chat request from other users. You can send your gifts to your friends on mojo.", font: .systemFont(ofSize: 14)) override func viewDidLoad() { super.viewDidLoad() collectionView.backgroundColor = .white setupNavigationBar() fetchCurrentUser() collectionView.register(WalletHeaderCell.self, forCellWithReuseIdentifier: headerCellId) collectionView.register(UserGiftCell.self, forCellWithReuseIdentifier: cellId) setupLayout() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) gifts.removeAll() fetchGifts() } fileprivate func setupLayout() { view.addSubview(emptyLabel) emptyLabel.fillSuperview(padding: .init(top: 0, left: 36, bottom: 0, right: 36)) emptyLabel.textAlignment = .center emptyLabel.numberOfLines = 0 emptyLabel.textColor = .lightGray emptyLabel.isHidden = true } var user: User? fileprivate func fetchCurrentUser() { guard let uid = Auth.auth().currentUser?.uid else { return } Firestore.firestore().collection("users").document(uid).getDocument { (snapshot, err) in if let err = err { print(err) return } guard let dictionary = snapshot?.data() else { return } self.user = User(dictionary: dictionary) } } var gifts = [Gift]() fileprivate func fetchGifts() { guard let uid = Auth.auth().currentUser?.uid else { return } let ref = Firestore.firestore().collection("drinks").whereField("owner", isEqualTo: uid) ref.getDocuments() { (querySnapshot, err) in if let err = err { print("Error getting documents: \(err)") } else { for document in querySnapshot!.documents { let giftType = document.data() let gift = Gift(giftType: giftType) if gift.blocked != true { self.gifts.append(gift) } self.collectionView.reloadData() } } if (self.gifts.count == 0) { self.emptyLabel.isHidden = false } } } override func numberOfSections(in collectionView: UICollectionView) -> Int { return 2 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if section == 1 { return gifts.count } return 1 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.section == 1 { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! UserGiftCell cell.gift = gifts[indexPath.item] // let gift = gifts[indexPath.item] return cell } let cell = collectionView.dequeueReusableCell(withReuseIdentifier: headerCellId, for: indexPath) as! WalletHeaderCell cell.accountButton.addTarget(self, action: #selector(handleAccount), for: .touchUpInside) cell.topUpButton.addTarget(self, action: #selector(handleTopup), for: .touchUpInside) cell.freeTokenButton.addTarget(self, action: #selector(handleFreeToken), for: .touchUpInside) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { let width = (view.frame.width - 2) / 3 return CGSize(width: width, height: width) } return CGSize(width: view.frame.width, height: 216) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { if section == 1 { return 1 } return 1 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { if section == 1 { return 1 } return 1 } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if indexPath.section != 0 { collectionView.cellForItem(at: indexPath)?.backgroundColor = #colorLiteral(red: 0.9632236362, green: 0.8585800529, blue: 0.8492385745, alpha: 0.5) let gift = gifts[indexPath.row] let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) alertController.addAction(UIAlertAction(title: "Send to ..", style: .default, handler: { (_) in let sendGiftController = SendGiftController() sendGiftController.gift = gift self.navigationController?.pushViewController(sendGiftController, animated: true) collectionView.cellForItem(at: indexPath)?.backgroundColor = .clear })) alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (_) in collectionView.cellForItem(at: indexPath)?.backgroundColor = .clear })) present(alertController, animated: true, completion: nil) } } override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { if indexPath.section != 0 { collectionView.cellForItem(at: indexPath)?.backgroundColor = .clear } } fileprivate func setupNavigationBar() { self.navigationItem.title = "Wallet" self.navigationController?.navigationBar.prefersLargeTitles = true } @objc fileprivate func handleAccount() { let walletAccountController = WalletAccountController() walletAccountController.user = self.user navigationController?.pushViewController(walletAccountController, animated: true) } @objc fileprivate func handleTopup() { let topupController = TopUpController() navigationController?.pushViewController(topupController, animated: true) } @objc fileprivate func handleFreeToken() { let inviteNewUserController = InviteNewUserController() inviteNewUserController.user = self.user navigationController?.pushViewController(inviteNewUserController, animated: true) } }
import Foundation public struct GoogleCaptchaConfig { public var secretKey: String public init(secretKey: String = "") { self.secretKey = secretKey } }
// // PersonDetailsViewController.swift // HW_2.7_TableView_Persons // // Created by 1 on 09.06.2020. // Copyright © 2020 Anzhelika. All rights reserved. // import UIKit class PersonDetailsViewController: UIViewController { @IBOutlet var telephoneLabel: UILabel! @IBOutlet var eMaiLabel: UILabel! @IBOutlet var contactDetails: UINavigationItem! var contact: Person! override func viewDidLoad() { super.viewDidLoad() contactDetails.title = contact.fullName telephoneLabel.text = contact.telephone eMaiLabel.text = contact.eMail } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let backItem = UIBarButtonItem() backItem.title = "Person contacts" navigationItem.backBarButtonItem = backItem } }
// // String+Utilities.swift // TheExternalSwiftStaticFramework // // Created by Laurie Keith on 05/12/2018. // Copyright © 2018 Laurie Laptop. All rights reserved. // import Foundation extension String { public func stringByAppendingPathComponent(path: String) -> String { let temp = self as NSString return temp.appendingPathComponent(path) } }
// // Created by Jasmin Suljic on 01/09/2020. // import Foundation import UIKit import WebKit @objc class PaymentAuthWebView: WKWebView { }
// // StartLeasingConfirmationViewController.swift // WavesWallet-iOS // // Created by Pavel Gubin on 11/20/18. // Copyright © 2018 Waves Platform. All rights reserved. // import UIKit import WavesSDK import DomainLayer private enum Constants { static let cornerRadius: CGFloat = 2 } final class StartLeasingConfirmationViewController: UIViewController { @IBOutlet private weak var viewContainer: UIView! @IBOutlet private weak var labelAmount: UILabel! @IBOutlet private weak var tickerView: TickerView! @IBOutlet private weak var labelNodeAddressTitle: UILabel! @IBOutlet private weak var labelNodeAddress: UILabel! @IBOutlet private weak var labelFeeTitle: UILabel! @IBOutlet private weak var labelFee: UILabel! @IBOutlet private weak var buttonConfirm: HighlightedButton! var order: StartLeasingTypes.DTO.Order! weak var output: StartLeasingModuleOutput? weak var errorDelegate: StartLeasingErrorDelegate? override func viewDidLoad() { super.viewDidLoad() createBackWhiteButton() setupLocalization() setupData() } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) removeTopBarLine() setupBigNavigationBar() navigationItem.backgroundImage = UIImage() navigationItem.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white] navigationItem.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white] } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() viewContainer.createTopCorners(radius: Constants.cornerRadius) } @IBAction private func confirmTapped(_ sender: Any) { let vc = StoryboardScene.StartLeasing.startLeasingLoadingViewController.instantiate() vc.input = .init(kind: .send(order), errorDelegate: errorDelegate, output: output) navigationController?.pushViewController(vc, animated: true) UseCasesFactory.instance.analyticManager.trackEvent(.walletLeasing(.leasingConfirmTap)) } private func setupData() { tickerView.update(with: .init(text: WavesSDKConstants.wavesAssetId, style: .soft)) labelAmount.text = order.amount.displayText labelNodeAddress.text = order.recipient labelFee.text = order.fee.displayText + " " + WavesSDKConstants.wavesAssetId } private func setupLocalization() { title = Localizable.Waves.Startleasingconfirmation.Label.confirmation labelNodeAddressTitle.text = Localizable.Waves.Startleasingconfirmation.Label.nodeAddress labelFeeTitle.text = Localizable.Waves.Startleasingconfirmation.Label.fee buttonConfirm.setTitle(Localizable.Waves.Startleasingconfirmation.Button.confirm, for: .normal) } }
//Copyright (c) 2017 Laszlo Pinter // //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 UIKit @IBDesignable internal class RainbowCircleView: UIView { var rainbowRadius: CGFloat = 100.0 { didSet{ setNeedsDisplay() } } var rainbowWidth: CGFloat = 8.0 { didSet{ setNeedsDisplay() } } func drawRainbow(onContext context: CGContext){ var huePath: UIBezierPath let sectors = 720 let sectorAngle = CGFloat(360 / CGFloat(sectors)).degreesToRadians() for sectorNumber in 0 ... sectors{ let currentAngle = (CGFloat(sectorNumber) * sectorAngle) huePath = UIBezierPath.init(arcCenter: origo, radius: rainbowRadius+20, startAngle: currentAngle, endAngle: currentAngle + sectorAngle*1.05, clockwise: true) huePath.addLine(to: origo) huePath.close() let color = UIColor.init(hue: getHue(at: currentAngle), saturation: 1, brightness: 1, alpha: 1).cgColor context.setFillColor(color) context.addPath(huePath.cgPath) context.fillPath() } } override func draw(_ rect: CGRect) { super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } let circle = UIBezierPath(ovalIn: CGRect(x: origo.x - rainbowRadius, y: origo.y - rainbowRadius , width: rainbowRadius*2, height: rainbowRadius*2)) let shapeCopyPath = circle.cgPath.copy(strokingWithWidth: rainbowWidth, lineCap: .butt, lineJoin: .bevel, miterLimit: 0) context.addPath(shapeCopyPath) context.clip(using: .winding) drawRainbow(onContext: context) context.resetClip() } var origo: CGPoint { get{ return CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2) } } func getHue(at radians: CGFloat) -> CGFloat { return ((radians.radiansToDegrees()+360).truncatingRemainder(dividingBy: 360))/360 } }
// // ActivityHistoryController.swift // countit // // Created by David Grew on 01/02/2019. // Copyright © 2019 David Grew. All rights reserved. // import UIKit import CoreData protocol ActivityHistoryController: class { func withItem(id: NSManagedObjectID) -> ActivityHistoryController func editButtonPressed() func doneButtonPressed() }
// // SpellListTableViewManager.swift // GlyphMaker // // Created by Patrik Hora on 18/03/2018. // Copyright © 2018 Manicek. All rights reserved. // import UIKit protocol SpellListTableViewManagerDelegate: class { func pushRequest(_ vc: SchoolViewController) } class SpellListTableViewManager: NSObject { struct Const { static let cellHeight: CGFloat = 45 static let headerHeight: CGFloat = 20 static let fireSectionIndex = 0 static let coldSectionIndex = 1 static let physicalSectionIndex = 2 } weak var delegate: SpellListTableViewManagerDelegate? weak var tableView: UITableView? { didSet { tableView?.delegate = self tableView?.dataSource = self tableView?.register(SpellListTableViewCell.self, forCellReuseIdentifier: SpellListTableViewCell.cellIdentifier) tableView?.separatorStyle = .none } } private var fireSpells = [Spell]() private var coldSpells = [Spell]() private var physicalSpells = [Spell]() func reload() { fireSpells = SpellStore.getSpells(ofType: .fire) coldSpells = SpellStore.getSpells(ofType: .cold) physicalSpells = SpellStore.getSpells(ofType: .physical) tableView?.reloadData() } } extension SpellListTableViewManager: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.section { case Const.fireSectionIndex: delegate?.pushRequest(SchoolViewController(glyph: fireSpells[indexPath.row].glyph)) case Const.coldSectionIndex: delegate?.pushRequest(SchoolViewController(glyph: coldSpells[indexPath.row].glyph)) case Const.physicalSectionIndex: delegate?.pushRequest(SchoolViewController(glyph: physicalSpells[indexPath.row].glyph)) default: return } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return Const.cellHeight } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return Const.headerHeight } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { switch section { case Const.fireSectionIndex: return SpellListHeaderView(forType: .fire) case Const.coldSectionIndex: return SpellListHeaderView(forType: .cold) case Const.physicalSectionIndex: return SpellListHeaderView(forType: .physical) default: return nil } } } extension SpellListTableViewManager: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: SpellListTableViewCell.cellIdentifier, for: indexPath) as! SpellListTableViewCell switch indexPath.section { case Const.fireSectionIndex: cell.configure(with: fireSpells[indexPath.row]) case Const.coldSectionIndex: cell.configure(with: coldSpells[indexPath.row]) case Const.physicalSectionIndex: cell.configure(with: physicalSpells[indexPath.row]) default: break } return cell } func numberOfSections(in tableView: UITableView) -> Int { return 3 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case Const.fireSectionIndex: return fireSpells.count case Const.coldSectionIndex: return coldSpells.count case Const.physicalSectionIndex: return physicalSpells.count default: return 0 } } }
import Foundation private let formatter = DateFormatter() extension Date { /** The date's day. Uses `Settings.timeZone` to determine the correct value. */ var day: Int { return Settings.calendar.dateComponents(in: Settings.timeZone, from: self).day! } /** The date's month. Uses `Settings.timeZone` to determine the correct value. */ var month: Int { return Settings.calendar.dateComponents(in: Settings.timeZone, from: self).month! } /** The date's year. Uses `Settings.timeZone` to determine the correct value. */ var year: Int { return Settings.calendar.dateComponents(in: Settings.timeZone, from: self).year! } /** Returns the previous day. */ var previous: Date { return Settings.calendar.date(byAdding: .day, value: -1, to: self)! } /** Returns the date 30 days after this one. */ var adding30Days: Date { return Settings.calendar.date(byAdding: .day, value: 30, to: self)! } /** Returns the date 30 days before this one. */ var subtracting30Days: Date { return Settings.calendar.date(byAdding: .day, value: -30, to: self)! } /** Returns a localized formatted date. Uses `Settings.locale` and `Settings.timeZone` by default. */ func formatted(dateStyle: DateFormatter.Style = .none, timeStyle: DateFormatter.Style = .none, locale: Locale = Locale(identifier: Settings.locale), timeZone: TimeZone = Settings.timeZone) -> String { formatter.locale = locale formatter.timeZone = timeZone formatter.dateStyle = dateStyle formatter.timeStyle = timeStyle return formatter.string(from: self) } /** Returns a localized formatted date. Uses `Settings.locale` and `Settings.timeZone` by default. */ func formatted(format: String, locale: Locale = Locale(identifier: Settings.locale), timeZone: TimeZone = Settings.timeZone) -> String { formatter.locale = locale formatter.timeZone = timeZone formatter.setLocalizedDateFormatFromTemplate(format) return formatter.string(from: self) } }
// // NewLocationRequestParameters.swift // EFI // // Created by LUIS ENRIQUE MEDINA GALVAN on 8/9/18. // Copyright © 2018 LUIS ENRIQUE MEDINA GALVAN. All rights reserved. // import Foundation struct NewLocationRequestParameters:Codable { var UserId:String? = "fe040b94-82bf-4e09-b171-ec6e050810a4" //"b3f5b6d3-d53b-4c27-8ad8-4841f7b39aaf" var Nombre:String? var ConsumoInicial:Float? var FinPeriodo:String? var InicioPeriodo:String? var ClaveEstado:String? var ClaveMunicipio:String? var ClaveDivisionElectrica:String? var ClaveTarifaCRE:String? var ClaveEmpresa:String? }
// // FileManager+Ext.swift // countdown // // Created by shadow on 30/1/21. // import Foundation extension FileManager { static let appGroupContainerURL = FileManager.default .containerURL(forSecurityApplicationGroupIdentifier: "group.com.coundown")! }
// // FavoriteRepositoryPresenter.swift // iOSEngineerCodeCheck // // Created by craptone on 2021/07/10. // Copyright © 2021 YUMEMI Inc. All rights reserved. // import Foundation protocol FavoriteRepositoryPresenterInput { func viewDidLoad() func viewWillAppear() func deleteFavoriteRepository(indexPath: IndexPath) func getRepository(index: Int) -> Repository? var favoritedCoreDataRepositories: [CoreDataRepository] { get } } protocol FavoriteRepositoryPresenterOutput: AnyObject { func reload() func deleteCell(indexPath: IndexPath) } final class FavoriteRepositoryPresenter: FavoriteRepositoryPresenterInput { private var view: FavoriteRepositoryPresenterOutput? private var dataManager: FavoriteRepositoryDataManager? private(set) var favoritedCoreDataRepositories: [CoreDataRepository] = [] init(view: FavoriteRepositoryPresenterOutput, dataManager: FavoriteRepositoryDataManager = FavoriteRepositoryDataManager.shared ) { self.view = view self.dataManager = dataManager } func viewDidLoad() { } func viewWillAppear() { dataManager?.fetchItems(completion: { (repo) in self.favoritedCoreDataRepositories = repo?.reversed() ?? [] self.view?.reload() }) } func deleteFavoriteRepository(indexPath: IndexPath) { dataManager?.delete(favoritedCoreDataRepositories[indexPath.row]) dataManager?.saveContext() dataManager?.fetchItems(completion: { (repo) in self.favoritedCoreDataRepositories = repo ?? [] self.view?.deleteCell(indexPath: indexPath) }) } func getRepository(index: Int) -> Repository? { return dataManager?.coreDataRepository2Repository(coreDataRepository: favoritedCoreDataRepositories[index]) } }
// // MainController.swift // itweet // // Created by tramp on 2018/4/4. // Copyright © 2018年 tramp. All rights reserved. // import UIKit class MainController: TRTabBarController { // MARK: - 生命周期 - override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // 1. 配置 configure() } // MARK: - 懒加载属性 - /// 撰写按钮 lazy var composeBtn = UIButton.init(normalImage: UIImage.init(named: "tabbar_compose_icon_add"), highlightedImage: UIImage.init(named: "tabbar_compose_icon_add_highlighted"), normalBackground: UIImage.init(named: "tabbar_compose_button"), highlightedBackground: UIImage.init(named: "tabbar_compose_button_highlighted"), target: self, action: nil) } // MARK: - UITabBarControllerDelegate extension MainController: UITabBarControllerDelegate { func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool { // 1. 屏蔽 中间的item 点击 if viewController.isMember(of: UIViewController.self) { return false } return true } } // MARK: - 初始化 extension MainController { /// 配置 private func configure(){ // 0. 设置代理 delegate = self // 1. 添加子控制器 guard let filePath = Bundle.filePath(name: "configure.json") , let data = NSData.init(contentsOfFile: filePath) as Data?, let items = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! Array<[String:String]> else { return } // 1.2 遍历 数组 for item in items { let controller = initChildController(dict: item) addChildViewController(controller) } // 2. 添加撰写按钮 let width = tabBar.bounds.width / CGFloat(childViewControllers.count) tabBar.addSubview(composeBtn) composeBtn.frame = tabBar.bounds.insetBy(dx: width * 2, dy: 0) } /// 初始化子控制器 /// /// - Parameter dict: 字典参数 private func initChildController(dict: [String: String])-> UIViewController { // 1. 获取参数 guard let title = dict["title"], let image = dict["image"], let cls = dict["class"], let _class = NSClassFromString("\(Bundle.main.nameSpace).\(cls)") as? TRViewController.Type else {return UIViewController.init()} // 2. 创建控制器 let rootVC = _class.init() // 3. 预设 rootVC.title = title rootVC.tabBarItem.title = title rootVC.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.init(hex: "#696969")], for: UIControlState.selected) rootVC.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.init(hex: "#696969")], for: UIControlState.normal) rootVC.tabBarItem.image = UIImage.init(named: image)?.withRenderingMode(.alwaysOriginal) rootVC.tabBarItem.selectedImage = UIImage.init(named: "\(image)_selected")?.withRenderingMode(.alwaysOriginal) // 4. 包装导航控制器 let controller = TRNavigationController.init(rootViewController:rootVC) // 5. 返回 return controller } }
// // ViewController.swift // Branch Terms // // Created by Daniel Berger on 5/26/20. // Copyright © 2020 Mike Horn. All rights reserved. // import UIKit class DanielViewController: UIViewController { //MARK:- initializing and presenting the View Controller to the screen override func loadView() { // initialize view from code } override func viewDidLoad() { super.viewDidLoad() // inital view setup or network calls or other one time tasks } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() // change sizing of views } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // after view is in foreground } //MARK:- removing View Controller from screen override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // called right before view is removed. De-Init animations, persistent network calls, etc. } override func viewDidDisappear(_ animated: Bool) { // cease notifications } }
// // GameOverTableViewCell.swift // Charades // // Created by Jeff on 8/27/15. // Copyright © 2015 Jeff Berman. All rights reserved. // // Used at the end of the game to display the questions that were both guessed correctly and passed over. import UIKit class GameOverTableViewCell: UITableViewCell { @IBOutlet weak var leftQuestion: UILabel! { didSet { leftQuestion.text = nil } } @IBOutlet weak var rightQuestion: UILabel! { didSet { rightQuestion.text = nil } } enum Corner { case top, bottom, both } // Loads and formats cell based on passed-in Question. // Position 0 = left part of cell // Position 1 = right part of cell func loadCellWithQuestion(question: Question, position: Int) { if position >= 0 && position <= 1 { let label = position == 0 ? leftQuestion : rightQuestion label.text = question.text label.textColor = question.guessedCorrectly ? Constants.resultCorrectColor : Constants.resultPassColor } } // Rounds cell corners func roundCorners(corner: Corner, radius: CGFloat) { var rectCorner: UIRectCorner switch corner { case .top: rectCorner = [UIRectCorner.TopLeft, UIRectCorner.TopRight] case .bottom: rectCorner = [UIRectCorner.BottomLeft, UIRectCorner.BottomRight] case .both: rectCorner = [UIRectCorner.TopLeft, UIRectCorner.TopRight, UIRectCorner.BottomLeft, UIRectCorner.BottomRight] } let shape = CAShapeLayer() shape.path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: rectCorner, cornerRadii: CGSize(width: radius, height: radius)).CGPath self.layer.mask = shape self.layer.masksToBounds = true } }
// // ZXDrugCategoryViewController.swift // YDY_GJ_3_5 // // Created by screson on 2017/5/16. // Copyright © 2017年 screson. All rights reserved. // import UIKit /// 药品分类 class ZXDrugCategoryViewController: ZXSTUIViewController { @IBOutlet weak var tblCategory1: UITableView! @IBOutlet weak var ccvSubCategory: UICollectionView! var categories:Array<ZXCategoryTreeModel>? var topIndex = 0 override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.title = "全部类目" self.hidesBottomBarWhenPushed = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !onceLoad { onceLoad = true self.fetchAllCategory() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.tblCategory1.backgroundColor = UIColor.zx_subTintColor self.tblCategory1.separatorStyle = .none self.tblCategory1.register(UINib(nibName: ZXSingleTextCell.NibName, bundle: nil), forCellReuseIdentifier: ZXSingleTextCell.reuseIdentifier) self.ccvSubCategory.register(UINib(nibName: ZXCategoryCCVCell.NibName, bundle: nil), forCellWithReuseIdentifier: ZXCategoryCCVCell.reuseIdentifier) self.ccvSubCategory.contentInset = UIEdgeInsetsMake(0, 20, 0, 20) } fileprivate func fetchAllCategory() { ZXHUD.showLoading(in: self.view, text: "获取分类列表...", delay: 0) ZXStoreHomeViewModel.categoryTree(storeId: ZXStoreParams.storeId) { (s, c, errorMsg, list) in ZXEmptyView.hide(from: self.view) ZXHUD.hide(for: self.view, animated: true) if s { self.topIndex = 0 self.categories = list self.tblCategory1.reloadData() self.ccvSubCategory.reloadData() if list.count == 0 { ZXEmptyView.show(in: self.view, type: .networkError, text: nil, retry: { [unowned self] in self.fetchAllCategory() }) }else{ self.tblCategory1.selectRow(at: IndexPath(row: 0, section: 0), animated: false, scrollPosition: .none) } } else { if c != ZXAPI_LOGIN_INVALID { ZXHUD.showFailure(in: self.view, text: errorMsg, delay: ZX.HUDDelay) } } } } }
// // MockUILabel.swift // MarsWeather // // Created by Martin Klöppner on 06/08/16. // Copyright © 2016 Martin Klöppner. All rights reserved. // import UIKit public class MockUILabel : UILabel { var textCalledCounter : Int = 0; public override var text: String? { didSet { self.textCalledCounter = self.textCalledCounter + 1; } } }
// // ViewController.swift // TIPR // // Created by Michael Litman on 4/8/17. // Copyright © 2017 thinkful. All rights reserved. // import UIKit import FirebaseDatabase import FirebaseAuth class ViewController: UIViewController { //let ref = FirebaseDatabase(url: "https://tipr-9e7b9.firebaseio.com/") @IBOutlet weak var username: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var segmentControl: UISegmentedControl! @IBOutlet weak var submitButton: UIButton! @IBAction func action(_ sender: UIButton) { if username.text != "" && password.text != "" { if segmentControl.selectedSegmentIndex == 0 //Login User { FIRAuth.auth()?.signIn(withEmail: username.text!, password: password.text!, completion: { (user, error) in if user != nil { //Sign in successful print("SUCCESS") } else { if let myError = error?.localizedDescription { print(myError) } else { print("ERROR") } } }) } else // Sign up user { FIRAuth.auth()?.createUser(withEmail: username.text!, password: password.text!, completion: { (user, error) in if user != nil { //Sign up successful print("SUCCESS") } else { if let myError = error?.localizedDescription { print(myError) } else { print("ERROR") } } }) } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func backButtonPressed() { self.dismiss(animated: true, completion: nil) } }
class Node<E> { let x: E let next: Node? init(x: E, next: Node?) { self.x = x self.next = next } } class List<E> { var head: Node<E>? func add(x: E) { let node = Node(x:x, next:head) head = node } func printAll() { var n = head while n != nil { print(n!.x) n = n!.next } } } func main() { let list = List <Int>() list.add(3) list.add(9) list.printAll() } main() // forgot to call main
// // DetailPresenter.swift // MVPtest // // Created by Муслим Курбанов on 22.06.2020. // Copyright © 2020 Муслим Курбанов. All rights reserved. // import Foundation protocol DetailViewProtocol: class { func setComment(comment: [Model]?) } protocol DetailViewPresenterProtocol: class { init(view: DetailViewProtocol, networkService: NetworkServiceProtocol, comment: [Model]?) func setComment() } class DetailPresenter: DetailViewPresenterProtocol { weak var view: DetailViewProtocol? let networkService: NetworkServiceProtocol! var comment: [Model]? required init(view: DetailViewProtocol, networkService: NetworkServiceProtocol, comment: [Model]?) { self.view = view self.networkService = networkService self.comment = comment } public func setComment() { self.view?.setComment(comment: comment) } }
// // ViewUrlViewController.swift // PollsFramework // // Created by Stefanita Oaca on 05/09/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import Cocoa import PollsFramework import WebKit class ViewUrlViewController: NSViewController { @IBOutlet weak var webView: WKWebView! var url : String! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. webView.load(NSURLRequest(url: NSURL(string: url)! as URL) as URLRequest) } }
// // MatchCellViewModel.swift // tennislike // // Created by Maik Nestler on 21.12.20. // import UIKit struct MatchCellViewModel { let nameText: String let profileImageUrl: URL? let uid: String init(match: Match) { nameText = match.name profileImageUrl = URL(string: match.profileImageUrl) uid = match.uid } }
// // LoginViewModel.swift // ChatDS // // Created by Денис Семерич on 03.11.2020. // import Foundation import Combine class LoginViewModel { let authService: AuthServiceInterface let storageService: StorageServiceInterface init(authService: AuthServiceInterface = FirebaseAuthService(), storageService: StorageServiceInterface = StorageService()) { self.authService = authService self.storageService = storageService } public let title: String = "Login" public let loginPlaceholder: String = "Enter your login" public let passwordPlaceholder: String = "Enter your password" public let buttonTitle: String = "Sign in" public var login: String = "" public var password: String = "" public var authorizedUser: User? public var authorizedSuccessMark: Int = 1 public var isUserAuthorized: Int? public var errorParsedText: String = "" public func onSignIn() { guard !login.isEmpty, !password.isEmpty else { return } authService.signInWith(login: login, password: password, completion: {[weak self] result in guard let self = self else { return } switch result { case .failure(let error): self.errorParsedText = self.parse(error: error) case .success(let user): self.authorizedUser = self.storageService.store(user: user) self.isUserAuthorized = 1 } }) } } extension LoginViewModel { private func parse(error: Error) -> String { return error.localizedDescription } }
// // Int-Extension.swift // ZLHJHelpAPP // // Created by 周希财 on 2019/10/24. // Copyright © 2019 VIC. All rights reserved. // import Foundation extension Int { func getAmountString() -> String { let formatter = NumberFormatter() formatter.groupingSeparator = " " formatter.numberStyle = .decimal let amount = formatter.string(from: NSNumber(value: self)) ?? "" return amount } }
// // AEDictionaryExtension.swift // AESwiftWorking_Example // // Created by Adam on 2021/4/21. // Copyright © 2021 CocoaPods. All rights reserved. // import Foundation // MARK: 字典转字符串 extension Dictionary { func toJsonString() -> String? { guard let data = try? JSONSerialization.data(withJSONObject: self, options: []) else { return nil } guard let str = String(data: data, encoding: .utf8) else { return nil } return str } } // MARK: 字符串转字典 extension String { func toDictionary() -> [String : Any] { var result = [String : Any]() guard !self.isEmpty else { return result } guard let dataSelf = self.data(using: .utf8) else { return result } if let dic = try? JSONSerialization.jsonObject(with: dataSelf, options: .mutableContainers) as? [String : Any] { result = dic } return result } }
// // StoryViewModel.swift // CleansePlayground // // Created by Tzatzo, Marsel, Vodafone Greece on 12/02/2020. // Copyright © 2020 Tzatzo, Marsel, Vodafone Greece. All rights reserved. // import Cleanse import RxSwift import RxCocoa struct StoryViewModel { struct Output { let title: Driver<String> let url: Driver<URL?> } let output: Output init(story: HNStory) { let titleDriver = Driver.just(story.title) let urlDriver = Driver.just(URL(string: story.url ?? "")) self.output = Output(title: titleDriver, url: urlDriver) } }
// // SlackPost.swift // Presense // // Created by Chay Choong on 21/3/16. // Copyright © 2016 SUTDiot. All rights reserved. // import UIKit import Foundation import CoreData enum FieldError: Error { case emptyName case invalidURL case beaconsNotFound } func sendMessage(_ message: String) throws { var err: String = "" let semaphore = DispatchSemaphore(value: 0) // let payload = "payload={\"channel\": \"#presensetest\", \"username\": \"webhookbot\", \"icon_emoji\":\":calling:\", \"text\": \"\(message)\"}" let payload = "payload={\"user\": \"\(identity!.value(forKey: "name") as! String)\", \"status\": \"\(message)\"}" let data = (payload as NSString).data(using: String.Encoding.utf8.rawValue) if let url = URL(string: (identity!.value(forKey: "url") as? String)!) { let request = NSMutableURLRequest(url: url) request.httpMethod = "POST" request.httpBody = data let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if error != nil { let nserr = error as! NSError err = ("error: \(error!.localizedDescription): \(nserr.userInfo)") print(err) } else if data != nil { if let str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) { print("\(str)") } else { err = ("error") } } semaphore.signal() }) task.resume() } else { err = ("error") } _ = semaphore.wait(timeout: DispatchTime.distantFuture) if (err != "") { throw FieldError.invalidURL } } func saveStatus(_ status: String) { let appDelegate = UIApplication.shared.delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "SlackData") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)] fetchRequest.fetchLimit = 1 do { let result = try managedContext.fetch(fetchRequest) let count = result.count let entity = NSEntityDescription.entity(forEntityName: "SlackData", in:managedContext) var webhookURL = NSManagedObject(entity: entity!, insertInto: managedContext) if (count > 0) { webhookURL = result[0] as! NSManagedObject } webhookURL.setValue(status, forKey: "status") try webhookURL.managedObjectContext?.save() print("Status changed to \(status)") identity = webhookURL } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } }
// // TabBar.swift // News163 // // Created by panqiang on 15/8/27. // Copyright (c) 2015年 panqiang. All rights reserved. // import UIKit class TabBar: UIView { var delegate:TabBarDelegate? var selButton:BarButton? var imgView:UIImageView? override func layoutSubviews() { let imgView:UIImageView = self.subviews[0] as! UIImageView imgView.frame = self.bounds for index in 1...self.subviews.count - 1 { let btn:UIButton = self.subviews[index] as! UIButton btn.frame = CGRect(x: CGFloat(index - 1) * mainWidth/5, y: 0, width: mainWidth/5, height: 49) btn.tag = index - 1 } } func addImageView() { let imgView = UIImageView() self.imgView = imgView self.addSubview(imgView) } func addBarButton(nor:String, dis:String, title:String) { let btn = BarButton() btn.setImage(UIImage(named: nor), forState: UIControlState.Normal) btn.setImage(UIImage(named: dis), forState: UIControlState.Disabled) btn.setTitle(title, forState: UIControlState.Normal) btn.setTitleColor(UIColor(red: 133/255.0, green: 133/255.0, blue: 133/255.0, alpha: 1), forState: UIControlState.Normal) btn.setTitleColor(UIColor(red: 223/255.0, green: 48/255.0, blue: 49/255.0, alpha: 1), forState: UIControlState.Disabled) btn.addTarget(self, action: #selector(TabBar.btnClick(_:)), forControlEvents: UIControlEvents.TouchDown) self.addSubview(btn) if (self.subviews.count == 2) { btn.tag = 1 self.btnClick(btn) } } func btnClick(btn:BarButton) { if (self.selButton == nil) { self.delegate?.ChangSelIndex(0, to: btn.tag) }else{ self.delegate?.ChangSelIndex(self.selButton!.tag, to: btn.tag) self.selButton!.enabled = true } self.selButton = btn btn.enabled = false } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ } protocol TabBarDelegate:NSObjectProtocol { func ChangSelIndex(from:Int, to:Int) }
// // Net.swift // Movies // // Created by GIRGEZ on 10/11/16. // Copyright © 2016 GIRGEZ. All rights reserved. // import Foundation import SystemConfiguration import ISMessages class Net { // d99e352cd5504b9d1aa0d540e0c594f1 static let apiKey = "a07e22bc18f5cb106bfe4cc1f83ad8ed" static let urlMoviesNowPlaying = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=\(apiKey)") static let urlMoviesTopRate = URL(string: "https://api.themoviedb.org/3/movie/top_rated?api_key=\(apiKey)") static func loadMovies(type: MoviesViewControllerType, isProgressHUDLoading: Bool, success: @escaping (_ movies: [NSDictionary])->Void, fail: (()->Void)? = nil) { if !Net.isConnectedNetwork { ISMessages.showCardAlert(withTitle: "No Internet access!", message: "Please check your connection.", iconImage: nil, duration: 2, hideOnSwipe: true, hideOnTap: true, alertType: .error, alertPosition: .top) fail?() return } if isProgressHUDLoading { ProgressHUD.show() } let url: URL? if type == MoviesViewControllerType.nowPlaying { url = urlMoviesNowPlaying } else { url = urlMoviesTopRate } let request = URLRequest( url: url!, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData, timeoutInterval: 10) let session = URLSession( configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: OperationQueue.main ) let task: URLSessionDataTask = session.dataTask(with: request, completionHandler: { (dataOrNil, response, error) in if let data = dataOrNil { if let responseDictionary = try! JSONSerialization.jsonObject( with: data, options:[]) as? NSDictionary { if let movies = responseDictionary["results"] as? [NSDictionary] { success(movies) if isProgressHUDLoading { ProgressHUD.dismiss() } } } } }) task.resume() } static func urlSmallPoster(posterPath: String?) -> URL? { if posterPath != nil { return URL(string: "https://image.tmdb.org/t/p/w75\(posterPath!)") } return nil } static func urlMediumPoster(posterPath: String?) -> URL? { if posterPath != nil { return URL(string: "https://image.tmdb.org/t/p/w160\(posterPath!)") } return nil } static func urlLargePoster(posterPath: String?) -> URL? { if posterPath != nil { return URL(string: "https://image.tmdb.org/t/p/w342\(posterPath!)") } return nil } static var isConnectedNetwork: Bool { get { var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) } } var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0) if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false { return false } let isReachable = flags == .reachable let needsConnection = flags == .connectionRequired return isReachable && !needsConnection } } }
// // Episode.swift // MindValley // // Created by Sudhanshu Sharma (HLB) on 19/05/2020. // Copyright © 2020 Sudhanshu Sharma (HLB). All rights reserved. // import Foundation struct Episode: Codable { let type, title: String let channel : ChannelEpisode let coverAsset : CoverAsset enum CodingKeys: String, CodingKey { case type, title case channel = "channel" case coverAsset } init?(data: Data) { guard let me = try? JSONDecoder().decode(Episode.self, from: data) else { return nil } self = me } } // MARK: Convenience initializers struct ChannelEpisode : Codable { let title : String enum CodingKeys: String, CodingKey { case title } } struct CoverAsset : Codable { let url : String enum CodingKeys: String, CodingKey { case url } }
// // SwiftubeUtil.swift // swiftube // // Created by 玉越敬典 on 2015/12/27. // Copyright © 2015年 玉越敬典. All rights reserved. // import Foundation class SwitubeUtils { static func safeFilename(text: String, max_length: Int = 200) -> String { var replaceText = text replaceText = replaceText.stringByReplacingOccurrencesOfString("_", withString: "") replaceText = replaceText.stringByReplacingOccurrencesOfString(":", withString: "-") let ntfs:[String] = ([Int])(0...31).map{String($0)} let paranoid: Array<String> = ["\"", "#", "$", "%", "\'", "*", ",", ".", "/", ":", ";", "<", ">", "?", "\\", "^", "|", "~", "\\\\"] let filename = replaceText.stringByReplacingOccurrencesOfString((ntfs + paranoid).joinWithSeparator("|"), withString: "") return truncate(filename) } static func truncate(filename: String, max_length: Int = 200) -> String{ return filename.componentsSeparatedByString(" ")[0] } }
// // TodoList.swift // DemoToDoList // // Created by Hoang Tung on 1/6/20. // Copyright © 2020 Hoang Tung. All rights reserved. // import Foundation import UIKit struct User { let name: String let phone: String let image: UIImage }
// // RadioStationCollectionViewItem.swift // GoogleMusicClientMacOS // // Created by Anton Efimenko on 09/03/2019. // Copyright © 2019 Anton Efimenko. All rights reserved. // import Cocoa import RxSwift import RxRelay private final class PlayPauseView: NSView { enum State { case hidden case play case pause } private let circle = NSVisualEffectView() |> mutate(^\NSVisualEffectView.blendingMode, .withinWindow) |> mutate(^\NSVisualEffectView.material, .appearanceBased) private let image = NSImageView() |> mutate(^\NSImageView.imageScaling, NSImageScaling.scaleProportionallyUpOrDown) override func layout() { super.layout() circle.layer?.cornerRadius = circle.bounds.height / 2 } init() { super.init(frame: .zero) addSubviews(circle, image) circle.lt.edges(to: self) image.lt.edges(to: circle, constant: 5) setState(.hidden) } required init?(coder decoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setState(_ value: State) { switch value { case .hidden: isHidden = true case .pause: isHidden = false image.image = NSImage.pauseFilled.tinted(tintColor: NSColor.onImagePlayPauseMainColor) case .play: isHidden = false image.image = NSImage.playFilled.tinted(tintColor: NSColor.onImagePlayPauseMainColor) } } } final class RadioStationCollectionViewItem: NSCollectionViewItem { let bag = DisposeBag() private let playPauseView = PlayPauseView() private let progressIndicator = NSProgressIndicator() |> mutate(^\NSProgressIndicator.style, .spinning) private let image = NSImageView() |> mutate(^\NSImageView.imageScaling, NSImageScaling.scaleProportionallyUpOrDown) private let titleLabel = baseLabel() |> mutate(^\NSTextField.font, ApplicationFont.semibold.value) |> mutate(^\NSTextField.alignment, NSTextAlignment.center) |> mutate { $0.setContentPriority(.hugging(1000, .vertical)) } |> mutate { $0.setContentPriority(.compression(1000, .vertical)) } override var title: String? { get { return titleLabel.stringValue } set { titleLabel.stringValue = newValue ?? "" } } private var selectableView: SelectableNSView { return view as! SelectableNSView } private var imageLoaderDisposable: Disposable? = nil private let isPlayingRelay = BehaviorRelay(value: false) private var isPlayingDisposable: Disposable? = nil override func prepareForReuse() { imageLoaderDisposable?.dispose() imageLoaderDisposable = nil isPlayingDisposable?.dispose() isPlayingDisposable = nil } func setImage(from loader: Observable<NSImage?>) { imageLoaderDisposable = loader .observeOn(MainScheduler.instance) .do(onSubscribe: { [weak self] in self?.toggleSpiner(animating: true); self?.updateImage(with: nil) }) .do(onNext: { [weak self] in self?.updateImage(with: $0) }) .do(onError: { [weak self] _ in self?.image.image = NSImage.album; }) .do(onDispose: { [weak self] in self?.toggleSpiner(animating: false) }) .subscribe() } func subscribeToIsPlaying(_ isPlaying: Observable<Bool>) { isPlayingDisposable = isPlaying.bind(to: isPlayingRelay) } func toggleSpiner(animating: Bool) { if animating { progressIndicator.startAnimation(nil) progressIndicator.isHidden = false } else { progressIndicator.stopAnimation(nil) progressIndicator.isHidden = true } } func updateImage(with image: NSImage?) { self.image.image = image } override func loadView() { view = SelectableNSView() view.addSubviews(image, titleLabel, progressIndicator, playPauseView) selectableView.drawHoverBackground = false selectableView.setupTrackingArea() selectableView.isSelectedChanged = { [weak self] _ in self?.togglePlayPauseIndicator() } selectableView.isHoveredChanged = { [weak self] _ in self?.togglePlayPauseIndicator() } isPlayingRelay .observeOn(MainScheduler.instance) .do(onNext: { [weak self] _ in self?.togglePlayPauseIndicator() }) .subscribe() .disposed(by: bag) createConstraints() } override var isSelected: Bool { didSet { selectableView.isSelected = isSelected } } func togglePlayPauseIndicator() { switch (selectableView.isSelected, selectableView.isHovered, isPlayingRelay.value) { case (true, true, true): playPauseView.setState(.pause) case (true, true, false): playPauseView.setState(.play) case (true, false, true): playPauseView.setState(.play) case (true, _, false): playPauseView.setState(.pause) case (false, true, _): playPauseView.setState(.play) default: playPauseView.setState(.hidden) } } func createConstraints() { image.lt.top.equal(to: view.lt.top, constant: 5) image.lt.leading.equal(to: view.lt.leading, constant: 5) image.lt.trailing.equal(to: view.lt.trailing, constant: -5) progressIndicator.lt.edges(to: image, constant: 20) playPauseView.lt.top.equal(to: image.lt.top, constant: 10) playPauseView.lt.leading.equal(to: image.lt.leading, constant: 10) playPauseView.lt.width.equal(to: 30) playPauseView.lt.height.equal(to: 30) titleLabel.lt.top.equal(to: image.lt.bottom, constant: 10) titleLabel.lt.leading.equal(to: image.lt.leading) titleLabel.lt.trailing.equal(to: image.lt.trailing) titleLabel.lt.bottom.equal(to: view.lt.bottom, constant: -5) } }
// // PopularTableController.swift // CleanemaRx // // Created by Ganesha Danu on 10/01/19. // Copyright © 2019 Ganesha Danu. All rights reserved. // import UIKit class PopularTableController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var movies: [Movie] = [Movie]() override func viewDidLoad() { super.viewDidLoad() movies.append(Movie(title: "Hello")) movies.append(Movie()) print() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { print(movies.count) return movies.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MovieItem", for: indexPath) if let aCell = cell as? MovieItemController { aCell.title.text = movies[indexPath.row].title return aCell } return cell } }
// // SLPAllWebservices.swift // SLP // // Created by Hardik Davda on 6/1/17. // Copyright © 2017 SLP-World. All rights reserved. // import UIKit let WebPath = SLPAllWebservicesList(fromString: "") var UserDetail = [AdvanceSearchDataList]() var PropertyList = [PropertyType]() var CunsultantDetailList = [CounsultantProfile]() var SearchScreenList = [SearchDataList]() var SearchDetailList = [SearchDetailsDataList]() var userLoginList = [userLoginDetailList]() var filterList = [filterSavedList]() var suburbList = [SuburbListData]() var moreDataList = [MoreList]() var recordCount = String() var message = String() var status = Bool() let keyboardToolbar = UIToolbar() var defaults = UserDefaults.standard class SLPAllWebservices: NSObject { func userLogin(with parameters: String, API: String, completion:((([userLoginDetailList]),String,Bool)->())?) { userLoginList = [userLoginDetailList]() let url = NSURL(string: SLPAllWebservicesList(fromString: "").Web_UserLogin as String) var request = URLRequest(url: url! as URL) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" var Parameter : NSString = NSString() Parameter = parameters as NSString request.httpBody = Parameter.data(using: String.Encoding.utf8.rawValue) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print(error!) // some fundamental network error return } do { if let parsedData = try? JSONSerialization.jsonObject(with: data) as! [String:Any] { status = parsedData["status"] as! Bool message = parsedData["message"] as! String if(!status){ }else{ let field = parsedData["data"] as! [[String:Any]] print(field.count) var cmd = userLoginDetailList() for blog in field { cmd.strId = (blog["id"] as! NSString) as String! cmd.strName = (blog["name"] as! NSString) as String! cmd.strEmail = (blog["email"] as! NSString) as String! cmd.strPhone = (blog["phone"] as! NSString) as String! cmd.strProfilePicture = (blog["profile_picture"] as! NSString) as String! cmd.strServiceToken = (blog["service_token"] as! NSString) as String! appDelegate.USERID = (blog["id"] as! NSString) appDelegate.USERNAME = (blog["name"] as! NSString) appDelegate.USEREMAIL = (blog["email"] as! NSString) appDelegate.USERPHONE = (blog["phone"] as! NSString) appDelegate.USERPROFILE = (blog["profile_picture"] as! NSString) appDelegate.USERTOKEN = (blog["service_token"] as! NSString) defaults.set(status, forKey: "STATUS") defaults.set(appDelegate.USERID, forKey: "USERID") defaults.set(appDelegate.USERNAME, forKey: "USERNAME") defaults.set(appDelegate.USEREMAIL, forKey: "USEREMAIL") defaults.set(appDelegate.USERPHONE, forKey: "USERPHONE") defaults.set(appDelegate.USERPROFILE, forKey: "USERPROFILE") defaults.set(appDelegate.USERTOKEN, forKey: "TOKEN") // if defaults.bool(forKey: "STATUS") as Bool{ // USERID = defaults.string(forKey: "USERID")! as NSString // USERNAME = defaults.string(forKey: "USERNAME")! as NSString // USEREMAIL = defaults.string(forKey: "USEREMAIL")! as NSString // USERPHONE = defaults.string(forKey: "USERPHONE")! as NSString // USERPROFILE = defaults.string(forKey: "USERPROFILE")! as NSString // USERTOKEN = defaults.string(forKey: "TOKEN")! as NSString // } userLoginList.append(cmd) } } } } DispatchQueue.main.async { completion?(userLoginList,message,status) } } task.resume() } func signUpUser(with parameters: String, API: String, completion:((String,Bool)->())?) { let url = NSURL(string: SLPAllWebservicesList(fromString: "").Web_UserSignup as String) var request = URLRequest(url: url! as URL) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" var Parameter : NSString = NSString() Parameter = parameters as NSString request.httpBody = Parameter.data(using: String.Encoding.utf8.rawValue) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print(error!) // some fundamental network error return } do { if let parsedData = try? JSONSerialization.jsonObject(with: data) as! [String:Any] { // let status = parsedData["status"] as! Bool status = parsedData["status"] as! Bool message = parsedData["message"] as! String } } DispatchQueue.main.async { completion?(message,status) } } task.resume() } func SearchDashboardList(with parameters: String, API: String, completion:((([SearchDataList]),String,String)->())?) { SearchScreenList = [SearchDataList]() let url = NSURL(string: SLPAllWebservicesList(fromString: "").Web_PropertyList as String) var request = URLRequest(url: url! as URL) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" var Parameter : NSString = NSString() Parameter = parameters as NSString request.httpBody = Parameter.data(using: String.Encoding.utf8.rawValue) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print(error!) // some fundamental network error return } do { if let parsedData = try? JSONSerialization.jsonObject(with: data) as! [String:Any] { // print(parsedData) let status = parsedData["status"] as! Bool // recordCount = "Showing 15 of 26 resultes" recordCount = parsedData["total_records"] as! String message = parsedData["message"] as! String if(!status){ } else{ let field = parsedData["data"] as! [[String:Any]] // print(field.count) var cmd = SearchDataList() for blog in field{ print(blog) cmd.strId = (blog["id"] as! NSString) as String! cmd.strHeading = (blog["heading"] as! NSString) as String! cmd.strLot = (blog["lot"] as! NSString) as String! cmd.strUnit = (blog["unit"] as! NSString) as String! cmd.strSuburb = (blog["suburb"] as! NSString) as String! cmd.strStreetNo = (blog["street_number"] as! NSString) as String! cmd.strPoBox = (blog["po_box"] as! NSString) as String! cmd.strStreet = (blog["street"] as! NSString) as String! cmd.strPropertyPriceFrom = (blog["property_price_from"] as! NSString) as String! cmd.strPropertyPriceTo = (blog["property_price_to"] as! NSString) as String! cmd.strBedrooms = (blog["bedrooms"] as! NSString) as String! cmd.strBathrooms = (blog["baathrooms"] as! NSString) as String! cmd.strGarage = (blog["garage"] as! NSString) as String! cmd.arrayPropertyImages = (blog["property_images"] as! Array) cmd.strStatus = (blog["status"] as! NSString) as String! cmd.strWebsiteBroachurDisplayPrice = (blog["website_brochure_display_price"] as! NSString) as String! cmd.strConsultantOneId = (blog["consultant_one_id"] as! NSString) as String! cmd.strConsultantOneName = (blog["consultant_one_name"] as! NSString) as String! cmd.strConsultantOnePosition = (blog["consultant_one_position"] as! NSString) as String! cmd.strConsultantOneImage = (blog["consultant_one_image"] as! NSString) as String! cmd.strConsultantTwoId = (blog["consultant_two_id"] as! NSString) as String! cmd.strConsultantTwoName = (blog["consultant_two_name"] as! NSString) as String! cmd.strConsultantTwoPosition = (blog["consultant_two_position"] as! NSString) as String! cmd.strConsultantTwoImage = (blog["consultant_two_image"] as! NSString) as String! cmd.isSave = true cmd.strIsFavourite = (blog["is_favourite"] as! NSString) as String! cmd.IsNew = (blog["is_new"] as! NSString) as String! // print("Fevortys := \(cmd.isSave )") SearchScreenList.append(cmd) } } } } DispatchQueue.main.async { completion?(SearchScreenList, recordCount,message) } } task.resume() } func FavoritProperty(with parameters: String, API: String, completion:((String,Bool)->())?) { let url = NSURL(string: SLPAllWebservicesList(fromString: "").Web_FavoritUnfavorit as String) var request = URLRequest(url: url! as URL) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" var Parameter : NSString = NSString() Parameter = parameters as NSString request.httpBody = Parameter.data(using: String.Encoding.utf8.rawValue) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print(error!) // some fundamental network error return } do { if let parsedData = try? JSONSerialization.jsonObject(with: data) as! [String:Any] { // let status = parsedData["status"] as! Bool status = parsedData["status"] as! Bool message = parsedData["message"] as! String } } DispatchQueue.main.async { completion?(message,status) } } task.resume() } func SaveSearch(with parameters: String, API: String, completion:((String,Bool)->())?) { let url = NSURL(string: SLPAllWebservicesList(fromString: "").Web_FavoritUnfavorit as String) var request = URLRequest(url: url! as URL) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" var Parameter : NSString = NSString() Parameter = parameters as NSString request.httpBody = Parameter.data(using: String.Encoding.utf8.rawValue) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print(error!) // some fundamental network error return } do { if let parsedData = try? JSONSerialization.jsonObject(with: data) as! [String:Any] { // let status = parsedData["status"] as! Bool status = parsedData["status"] as! Bool message = parsedData["message"] as! String } } DispatchQueue.main.async { completion?(message,status) } } task.resume() } func sendEnquiryDetail(with parameters: String, API: String, completion:((String,Bool)->())?) { let url = NSURL(string: SLPAllWebservicesList(fromString: "").Web_SendEnquiry as String) var request = URLRequest(url: url! as URL) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" var Parameter : NSString = NSString() Parameter = parameters as NSString request.httpBody = Parameter.data(using: String.Encoding.utf8.rawValue) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print(error!) // some fundamental network error return } do { if let parsedData = try? JSONSerialization.jsonObject(with: data) as! [String:Any] { // let status = parsedData["status"] as! Bool status = parsedData["status"] as! Bool message = parsedData["message"] as! String } } DispatchQueue.main.async { completion?(message,status) } } task.resume() } func removeFilterSaved(with parameters: String, API: String, completion:((String,Bool)->())?) { let url = NSURL(string: SLPAllWebservicesList(fromString: "").Web_RemoveFilter as String) var request = URLRequest(url: url! as URL) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" var Parameter : NSString = NSString() Parameter = parameters as NSString request.httpBody = Parameter.data(using: String.Encoding.utf8.rawValue) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print(error!) // some fundamental network error return } do { if let parsedData = try? JSONSerialization.jsonObject(with: data) as! [String:Any] { // let status = parsedData["status"] as! Bool status = parsedData["status"] as! Bool message = parsedData["message"] as! String } } DispatchQueue.main.async { completion?(message,status) } } task.resume() } func SearchDashboardDetailList(with parameters: String, API: String, completion:((([SearchDetailsDataList]),String,String,Bool)->())?) { SearchDetailList = [SearchDetailsDataList]() let url = NSURL(string: SLPAllWebservicesList(fromString: "").Web_PropertyDetail as String) var request = URLRequest(url: url! as URL) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" var Parameter : NSString = NSString() Parameter = parameters as NSString request.httpBody = Parameter.data(using: String.Encoding.utf8.rawValue) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print(error!) // some fundamental network error return } do { if let parsedData = try? JSONSerialization.jsonObject(with: data) as! [String:Any] { status = parsedData["status"] as! Bool recordCount = "" message = parsedData["message"] as! String if(!status){ } else{ let field = parsedData["data"] as! [[String:Any]] for blog in field { var SearchHome = [SearchDetailHomeOpens]() let homeData = blog["home_open_data"] as! [[String:Any]] if homeData.count == 0{ }else{ for data in homeData { var home = SearchDetailHomeOpens() home.strdate = data["date"] as! String home.strend_time = data["start_time"] as! String home.strstart_time = data["end_time"] as! String SearchHome.append(home) } } let cmd = SearchDetailsDataList(strId: blog["id"] as! String, strStreetNumber: blog["street_number"] as! String, strStreet: blog["street"] as! String, strState: blog["state"] as! String, strSuburb: blog["suburb"] as! String, strWebsiteBrochureDisplayPrice: blog["website_brochure_display_price"] as! String, strBedrooms: blog["bedrooms"] as! String, strBathrooms: blog["baathrooms"] as! String, strGarage: blog["garage"] as! String, arrayPropertyImages: (blog["property_images"] as! Array), strFloorImage: blog["floor_image"] as! String, strHeading: blog["heading"] as! String, strDescription: blog["description"] as! String, strPropertyType: blog["property_type"] as! String, strLandAreaSqm: blog["land_area_sqm"] as! String, strBuildingAreaSqm: blog["building_area_sqm"] as! String, strParkingOther: blog["parking_other"] as! String, strPool: blog["pool"] as! String, strStudy: blog["study"] as! String, strExternalLink: blog["external_link"] as! String, strVideoLink: blog["video_link"] as! String, strLatitude: blog["latitude"] as! String, strLongitude: blog["longitude"] as! String, strConsultantOneId: blog["consultant_one_id"] as! String, strConsultantOneName: blog["consultant_one_name"] as! String, strConsultantOnePosition: blog["consultant_one_position"] as! String, strConsultantOneImage: blog["consultant_one_image"] as! String, strConsultantOneMobile: blog["consultant_one_mobile"] as! String, strConsultantOneEmail: blog["consultant_one_email"] as! String, strConsultantOneFbUrl: blog["consultant_one_fb_url"] as! String, strConsultantOneLinkedinUrl: blog["consultant_one_linkedin_url"] as! String, strConsultantOnePinterestUrl: blog["consultant_one_pinterest_url"] as! String, strConsultantOneGplusUrl: blog["consultant_one_gplus_url"] as! String, strConsultantOneTwitterUrl: blog["consultant_one_twitter_url"] as! String, strConsultantTwoId: blog["consultant_two_id"] as! String, strConsultantTwoName: blog["consultant_two_name"] as! String, strConsultantTwoPosition: blog["consultant_two_position"] as! String, strConsultantTwoImage: blog["consultant_two_image"] as! String, strConsultantTwoMobile: blog["consultant_two_mobile"] as! String, strConsultantTwoEmail: blog["consultant_two_email"] as! String, strConsultantTwoFbUrl: blog["consultant_two_fb_url"] as! String, strConsultantTwoLinkedinUrl: blog["consultant_two_linkedin_url"] as! String, strConsultantTwoPinterestUrl: blog["consultant_two_pinterest_url"] as! String, strConsultantTwoGplusUrl: blog["consultant_two_gplus_url"] as! String, strConsultantTwoTwitterUrl : blog["consultant_two_twitter_url"] as! String, structHomeOpenData: SearchHome) SearchDetailList.append(cmd) } } } } DispatchQueue.main.async { completion?(SearchDetailList, recordCount,message,status) } } task.resume() } func filterDetailList(with parameters: String, API: String, completion:((([filterSavedList]),String,Bool)->())?) { filterList = [filterSavedList]() let url = NSURL(string: SLPAllWebservicesList(fromString: "").Web_FilterListSaved as String) var request = URLRequest(url: url! as URL) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" var Parameter : NSString = NSString() Parameter = parameters as NSString request.httpBody = Parameter.data(using: String.Encoding.utf8.rawValue) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print(error!) // some fundamental network error return } do { if let parsedData = try? JSONSerialization.jsonObject(with: data) as! [String:Any] { status = parsedData["status"] as! Bool recordCount = "" message = parsedData["message"] as! String if(!status){ } else{ let field = parsedData["data"] as! [[String:Any]] for blog in field { var cmd = filterSavedList() let fillData = blog["filter_search"] as! [[String:Any]] for search in fillData { let SelectedValue = AdvanceSearch(location: search["strLocation"] as? String, priceMin: search["strPriceMin"] as? String, priceMax: search["strPriceMax"] as? String, PropertyType: search["strPropertyType"] as? String, InspectionSchedule: search["strInspectionSchedule"] as? String, BedroomsMin: search["strBedroomsMin"] as? String, BedroomsMax: search["strBedroomsMax"] as? String, BathroomMin: search["strBathroomsMin"] as? String, BathroomMax: search["strBathroomsMax"] as? String, LandMin: search["strLandSizeMin"] as? String, LandMax: search["strLandSizeMax"] as? String, Sort: search["strSort"] as? String, Suburbs: search["strSuburbs"] as? String, SuburbsId: search["strSuburbsId"] as? String, PropertyTypeId: search["strPropertyTypeId"] as? String, Garage: search["strGarage"] as? String, Keyword: search["strKeyword"] as? String, Surrounding: search["boolSurroundingSuburb"] as? Bool, Exclude: search["boolExcludeUnderOffer"] as? Bool) cmd.strObject = SelectedValue } cmd.strId = blog["id"] as! String cmd.strName = blog["name"] as! String print(blog["id"]! ) filterList.append(cmd) } } } } DispatchQueue.main.async { completion?(filterList,message,status) } } task.resume() } func suburbDataFilterList(with parameters: String, API: String, completion:((([SuburbListData]),String,Bool)->())?) { suburbList = [SuburbListData]() let url = NSURL(string: SLPAllWebservicesList(fromString: "").Web_SuburbList as String) var request = URLRequest(url: url! as URL) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" var Parameter : NSString = NSString() Parameter = parameters as NSString request.httpBody = Parameter.data(using: String.Encoding.utf8.rawValue) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print(error!) // some fundamental network error return } do { if let parsedData = try? JSONSerialization.jsonObject(with: data) as! [String:Any] { status = parsedData["status"] as! Bool message = parsedData["message"] as! String if(!status){ }else{ let field = parsedData["data"] as! [[String:Any]] print(field.count) var cmd = SuburbListData() for blog in field { cmd.strId = (blog["id"] as! NSString) as String! cmd.strSuburb = (blog["suburb"] as! NSString) as String! cmd.strStatus = (blog["status"] as! NSString) as String! cmd.strStateId = (blog["state"] as! NSString) as String! cmd.strCreatedAt = (blog["created_at"] as! NSString) as String! cmd.strUpdatedAt = (blog["updated_at"] as! NSString) as String! cmd.strStateName = (blog["state_name"] as! NSString) as String! suburbList.append(cmd) } } } } DispatchQueue.main.async { completion?(suburbList,message,status) } } task.resume() } func editProfileDetail(with parameters: String, API: String, completion:((([userLoginDetailList]),String,Bool)->())?) { userLoginList = [userLoginDetailList]() let url = NSURL(string: SLPAllWebservicesList(fromString: "").Web_EditProfile as String) var request = URLRequest(url: url! as URL) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" var Parameter : NSString = NSString() Parameter = parameters as NSString request.httpBody = Parameter.data(using: String.Encoding.utf8.rawValue) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print(error!) // some fundamental network error return } do { if let parsedData = try? JSONSerialization.jsonObject(with: data) as! [String:Any] { status = parsedData["status"] as! Bool message = parsedData["message"] as! String if(!status){ }else{ let field = parsedData["data"] as! [[String:Any]] print(field.count) var cmd = userLoginDetailList() for blog in field { cmd.strId = (blog["id"] as! NSString) as String! cmd.strName = (blog["name"] as! NSString) as String! cmd.strEmail = (blog["email"] as! NSString) as String! cmd.strPhone = (blog["phone"] as! NSString) as String! cmd.strProfilePicture = (blog["profile_picture"] as! NSString) as String! cmd.strServiceToken = (blog["service_token"] as! NSString) as String! appDelegate.USERID = (blog["id"] as! NSString) appDelegate.USERNAME = (blog["name"] as! NSString) appDelegate.USEREMAIL = (blog["email"] as! NSString) appDelegate.USERPHONE = (blog["phone"] as! NSString) appDelegate.USERPROFILE = (blog["profile_picture"] as! NSString) appDelegate.USERTOKEN = (blog["service_token"] as! NSString) defaults.set(status, forKey: "STATUS") defaults.set(appDelegate.USERID, forKey: "USERID") defaults.set(appDelegate.USERNAME, forKey: "USERNAME") defaults.set(appDelegate.USEREMAIL, forKey: "USEREMAIL") defaults.set(appDelegate.USERPHONE, forKey: "USERPHONE") defaults.set(appDelegate.USERPROFILE, forKey: "USERPROFILE") defaults.set(appDelegate.USERTOKEN, forKey: "TOKEN") // if defaults.bool(forKey: "STATUS") as Bool{ // USERID = defaults.string(forKey: "USERID")! as NSString // USERNAME = defaults.string(forKey: "USERNAME")! as NSString // USEREMAIL = defaults.string(forKey: "USEREMAIL")! as NSString // USERPHONE = defaults.string(forKey: "USERPHONE")! as NSString // USERPROFILE = defaults.string(forKey: "USERPROFILE")! as NSString // USERTOKEN = defaults.string(forKey: "TOKEN")! as NSString // } userLoginList.append(cmd) } } } } DispatchQueue.main.async { completion?(userLoginList,message,status) } } task.resume() } func sortListingByDataList(with parameters: String, API: String, completion:(([AdvanceSearchDataList])->())?) { UserDetail = [AdvanceSearchDataList]() var cmd = AdvanceSearchDataList(strTitle: "Newest", strData: "", isSelect: false) UserDetail.append(cmd) cmd = AdvanceSearchDataList(strTitle: "Lowest Price", strData: "", isSelect: false) UserDetail.append(cmd) cmd = AdvanceSearchDataList(strTitle: "Highest Price", strData: "", isSelect: false) UserDetail.append(cmd) cmd = AdvanceSearchDataList(strTitle: "Earliest Inspection", strData: "", isSelect: false) UserDetail.append(cmd) cmd = AdvanceSearchDataList(strTitle: "Suburb", strData: "", isSelect: false) UserDetail.append(cmd) DispatchQueue.main.async { completion?(UserDetail) } } func SearchListDate(with parameters: String, API: String, completion:(([AdvanceSearchDataList])->())?) { UserDetail = [AdvanceSearchDataList]() var cmd = AdvanceSearchDataList(strTitle: "Location", strData: "Map Area", isSelect: false) UserDetail.append(cmd) cmd = AdvanceSearchDataList(strTitle: "Surrounding Suburbs", strData: "Switch", isSelect: false) UserDetail.append(cmd) cmd = AdvanceSearchDataList(strTitle: "Price", strData: "Any", isSelect: false) UserDetail.append(cmd) cmd = AdvanceSearchDataList(strTitle: "Property Type", strData: "Any", isSelect: false) UserDetail.append(cmd) cmd = AdvanceSearchDataList(strTitle: "Inspections Scheduled", strData: "At any time", isSelect: false) UserDetail.append(cmd) cmd = AdvanceSearchDataList(strTitle: "Bedrooms", strData: "Any", isSelect: false) UserDetail.append(cmd) cmd = AdvanceSearchDataList(strTitle: "Bathrooms", strData: "Any", isSelect: false) UserDetail.append(cmd) cmd = AdvanceSearchDataList(strTitle: "Garage", strData: "Any", isSelect: false) UserDetail.append(cmd) cmd = AdvanceSearchDataList(strTitle: "Land size", strData: "Any", isSelect: false) UserDetail.append(cmd) cmd = AdvanceSearchDataList(strTitle: "Keywords", strData: "TextField", isSelect: false) UserDetail.append(cmd) cmd = AdvanceSearchDataList(strTitle: "Exclude Under Offer", strData: "Switch", isSelect: false) UserDetail.append(cmd) DispatchQueue.main.async { completion?(UserDetail) } } func SearchPropertyType(with parameters: String, API: String, completion:((([PropertyType]),String,Bool) ->())?) { PropertyList = [PropertyType]() let url = NSURL(string: SLPAllWebservicesList(fromString: "").Web_PropertyTypeList as String) var request = URLRequest(url: url! as URL) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" var Parameter : NSString = NSString() Parameter = parameters as NSString request.httpBody = Parameter.data(using: String.Encoding.utf8.rawValue) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print(error!) // some fundamental network error return } do { if let parsedData = try? JSONSerialization.jsonObject(with: data) as! [String:Any] { status = parsedData["status"] as! Bool message = parsedData["message"] as! String if(!status){ }else{ let field = parsedData["data"] as! [[String:Any]] print(field.count) var cmd = PropertyType() for blog in field { cmd.strId = (blog["id"] as! NSString) as String! cmd.strPropertyType = (blog["property_type"] as! NSString) as String! cmd.strStatus = (blog["status"] as! NSString) as String! cmd.strCreatedAt = (blog["created_at"] as! NSString) as String! cmd.strUpdatedAt = (blog["updated_at"] as! NSString) as String! cmd.isSelect = false PropertyList.append(cmd) } } } } DispatchQueue.main.async { completion?(PropertyList,message,status) } } task.resume() // var cmd = AdvanceSearchDataList(strTitle: "Any", strData: "", isSelect: false) // UserDetail.append(cmd) // // cmd = AdvanceSearchDataList(strTitle: "House", strData: "", isSelect: false) // UserDetail.append(cmd) // // cmd = AdvanceSearchDataList(strTitle: "Apartment / Unit / Flat", strData: "", isSelect: false) // UserDetail.append(cmd) // cmd = AdvanceSearchDataList(strTitle: "Townhouse", strData: "", isSelect: false) // UserDetail.append(cmd) // cmd = AdvanceSearchDataList(strTitle: "Land", strData: "", isSelect: false) // UserDetail.append(cmd) // cmd = AdvanceSearchDataList(strTitle: "Rural", strData: "", isSelect: false) // UserDetail.append(cmd) // cmd = AdvanceSearchDataList(strTitle: "New Apartments / Off the plan", strData: "", isSelect: false) // UserDetail.append(cmd) // cmd = AdvanceSearchDataList(strTitle: "New Home Designs", strData: "", isSelect: false) // UserDetail.append(cmd) // cmd = AdvanceSearchDataList(strTitle: "New House and Land", strData: "", isSelect: false) // UserDetail.append(cmd) // // DispatchQueue.main.async { // completion?(UserDetail) // } } func InspectionScheduled(with parameters: String, API: String, completion:(([AdvanceSearchDataList])->())?) { UserDetail = [AdvanceSearchDataList]() var cmd = AdvanceSearchDataList(strTitle: "Any", strData: "", isSelect: false) UserDetail.append(cmd) cmd = AdvanceSearchDataList(strTitle: "Today", strData: "", isSelect: false) UserDetail.append(cmd) cmd = AdvanceSearchDataList(strTitle: "This Weekend", strData: "", isSelect: false) UserDetail.append(cmd) cmd = AdvanceSearchDataList(strTitle: "Next Weekend", strData: "", isSelect: false) UserDetail.append(cmd) cmd = AdvanceSearchDataList(strTitle: "Next 7 days", strData: "", isSelect: false) UserDetail.append(cmd) cmd = AdvanceSearchDataList(strTitle: "This Month", strData: "", isSelect: false) UserDetail.append(cmd) DispatchQueue.main.async { completion?(UserDetail) } } func moreListData(with parameters: String, API: String, completion:(([MoreList])->())?) { moreDataList = [MoreList]() var cmd = MoreList(strTitle: "Profile", imgIcones: #imageLiteral(resourceName: "iconeProfileAvtar"), isSelect: false) moreDataList.append(cmd) // // cmd = MoreList(strTitle: "Alerts", imgIcones: #imageLiteral(resourceName: "iconNotification"), isSelect: false) // moreDataList.append(cmd) // cmd = MoreList(strTitle: "Rat us", imgIcones: #imageLiteral(resourceName: "iconRating"), isSelect: false) moreDataList.append(cmd) cmd = MoreList(strTitle: "Feedback", imgIcones: #imageLiteral(resourceName: "iconComments"), isSelect: false) moreDataList.append(cmd) cmd = MoreList(strTitle: "Change Password", imgIcones: #imageLiteral(resourceName: "iconLockBlack"), isSelect: false) moreDataList.append(cmd) cmd = MoreList(strTitle: "Logout", imgIcones: #imageLiteral(resourceName: "iconLogout"), isSelect: false) moreDataList.append(cmd) DispatchQueue.main.async { completion?(moreDataList) } } func CunsultantView(with parameters: String, API: String, completion:((([CounsultantProfile]),String,Bool) ->())?) { CunsultantDetailList = [CounsultantProfile]() let url = NSURL(string: SLPAllWebservicesList(fromString: "").Web_ProfileView as String) var request = URLRequest(url: url! as URL) request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" var Parameter : NSString = NSString() Parameter = parameters as NSString request.httpBody = Parameter.data(using: String.Encoding.utf8.rawValue) let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { print(error!) // some fundamental network error return } do { if let parsedData = try? JSONSerialization.jsonObject(with: data) as! [String:Any] { status = parsedData["status"] as! Bool message = parsedData["message"] as! String if(!status){ }else{ let field = parsedData["data"] as! [[String:Any]] print(field.count) var cmd = CounsultantProfile() for blog in field { cmd.strId = (blog["id"] as! NSString) as String! cmd.strName = (blog["name"] as! NSString) as String! cmd.strPhoto = (blog["photo"] as! NSString) as String! cmd.strDescription = (blog["description"] as! NSString) as String! cmd.strPosition = (blog["position"] as! NSString) as String! cmd.strPhone = (blog["phone"] as! NSString) as String! cmd.strMobile = (blog["mobile"] as! NSString) as String! cmd.strEmail = (blog["email"] as! NSString) as String! cmd.strWebsite = (blog["website"] as! NSString) as String! cmd.strProfileVideoUrl = (blog["profile_video_url"] as! NSString) as String! cmd.strFacebookProfileUrl = (blog["facebook_profile_url"] as! NSString) as String! cmd.strTwitterProfileUrl = (blog["twitter_profile_url"] as! NSString) as String! cmd.strLinkedinProfileUrl = (blog["linkedin_profile_url"] as! NSString) as String! cmd.strPinterestProfileUrl = (blog["pinterest_profile_url"] as! NSString) as String! cmd.strGooglePlusProfileUrl = (blog["google_plus_profile_url"] as! NSString) as String! cmd.strStateName = (blog["state_name"] as! NSString) as String! CunsultantDetailList.append(cmd) } } } } DispatchQueue.main.async { completion?(CunsultantDetailList,message,status) } } task.resume() } } extension String { func toBool() -> Bool? { switch self { case "True", "true", "yes", "1": return true case "False", "false", "no", "0": return false default: return nil } } }
// // PLAPIManager.swift // ProSwiftLibrary // // Created by Amit Chandel on 7/28/15. // Copyright (c) 2015 Amit Chandel. All rights reserved. // import UIKit import Alamofire enum Router: URLRequestConvertible { case PostBook([String: AnyObject]) case GetBooks case GetABook(String) case UpdateBook(String, [String: AnyObject]) case DeleteBook(String) var method: Alamofire.Method { switch self { case .PostBook: return .POST case .GetBooks: return .GET case .GetABook: return .GET case .UpdateBook: return .PUT case .DeleteBook: return .DELETE } } var path: String { switch self { case .PostBook: return "/books/" case .GetBooks: return "/books" case .GetABook(let bookEndPoint): return "\(bookEndPoint)" case .UpdateBook(let bookEndPoint, _): return "\(bookEndPoint)" case .DeleteBook(let bookEndPoint): return "\(bookEndPoint)" } } var URLRequest: NSURLRequest { let URL:NSURL! = NSURL(string: kBaseURL) let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path)) mutableURLRequest.HTTPMethod = method.rawValue switch self { case .PostBook(let parameters): return Alamofire.ParameterEncoding.JSON.encode(mutableURLRequest, parameters: parameters).0 case .UpdateBook(_, let parameters): return Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: parameters).0 default: return mutableURLRequest } } }
// // cameraViewController.swift // lemon // // Created by 笹倉 一也 on 2018/05/23. // Copyright © 2018年 笹倉 一也. All rights reserved. // import UIKit import AVFoundation class cameraViewController: UIViewController { var device: AVCaptureDevice! var session: AVCaptureSession! override func viewDidLoad() { super.viewDidLoad() } }
// // PropertyFactsTableViewCell.swift // PropertyFinder // // Created by Raul Brito on 22/02/19. // Copyright © 2019 Raul Brito. All rights reserved. // import UIKit class PropertyFactsTableViewCell: UITableViewCell { // MARK: - Properties var propertyViewModel: PropertyViewModel! { didSet { bedroomCountLabel.text = "\(propertyViewModel.bedroomCount)" bathroomCountLabel.text = "\(propertyViewModel.bathroomCount)" areaLabel.text = "\(propertyViewModel.area) sqft" referenceLabel.text = propertyViewModel.reference reraLabel.text = propertyViewModel.rera } } @IBOutlet var bedroomCountLabel: UILabel! @IBOutlet var bathroomCountLabel: UILabel! @IBOutlet var areaLabel: UILabel! @IBOutlet var referenceLabel: UILabel! @IBOutlet var reraLabel: UILabel! }
struct Coordinate { var x = 0 var y = 0 }
//: Playground - noun: a place where people can play import UIKit import XCPlayground XCPSetExecutionShouldContinueIndefinitely() // old way do { func divide(number: CGFloat, by: CGFloat, error: NSErrorPointer) -> CGFloat { guard by != 0 else { // return what? error.memory = NSError(domain: "domain", code: 123, userInfo: nil) return -1 } return number/by } var error: NSError? = nil let result = divide(100, by: 0, error: &error) error } // 1.2 do { enum Result<T, U> { case Success(T) case Failure(U) } func divide(number: CGFloat, by: CGFloat) -> Result<CGFloat, String> { guard by != 0 else { return .Failure("Cannot divide by zero") } return .Success(number/by) } let result = divide(20, by: 0) switch result { case .Success(let quotient): quotient case .Failure(let errString): errString } } // 2.0 do { enum Result<T: Any, U: ErrorType> { case Success(T) case Failure(U) } enum DivisionError: ErrorType { case DivideByZero case Unknown(String) } func divide(number: Float, by: Float) -> Result<Float, DivisionError> { guard by != 0 else { return .Failure(.DivideByZero) } return .Success(number/by) } let result = divide(20, by: 10) switch result { case .Success(let quotient): quotient case .Failure(let divisionError): switch divisionError { case .DivideByZero: "dividing by zero" case .Unknown(let errString): errString } } } // 2.0 with chaining do { enum Result<T, U: ErrorType> { case Success(T) case Failure(U) func errThen<V>(nextOperation:T -> Result<V, U>) -> Result<V, U> { switch self { case let .Failure(error): return .Failure(error) case let .Success(value): return nextOperation(value) } } func then<V>(nextOperation: T -> V) -> Result<V, U> { switch self { case let .Failure(error): return .Failure(error) case let .Success(value): return .Success(nextOperation(value)) } } } enum MathError: ErrorType { case DivideByZero case Other(String) } func divide(number: CGFloat, by: CGFloat) -> Result<CGFloat, MathError> { guard by != 0 else { return .Failure(.DivideByZero) } return .Success(number/by) } func magicNumber(quotient: Float) -> Result<Float, MathError> { // then requires a failure type guard quotient != 0 else { return .Failure(.Other("log 0")) } return .Success(log(quotient)) } func magicNumber2(quotient: Float) -> Float { // then requires a failure type return log(quotient) } let result = divide(0, by: 10).errThen{ quotient in magicNumber(Float(quotient)) }.then(magicNumber2) } // 2.0 with try do { enum MathError: ErrorType { case DivideByZero case Other(String) } func divide(number: CGFloat, by: CGFloat) throws -> CGFloat { guard by != 0 else { throw MathError.DivideByZero } return number/by } func magicNumber(quotient: Float) throws -> Float { // then requires a failure type guard quotient != 0 else { throw MathError.Other("log 0") } return log(quotient) } do { let result = try Float(divide(0, by: 20)) let mResult = try magicNumber(result) } catch MathError.Other(let errString) { errString } catch { "foo" } // in b6 we can also say if let result = try? Float(divide(20, by: 0)), let mResult = try? magicNumber(result) { result mResult } else { "foo" } // divide(20, by: 10) // cannot be run without try } // issue async calls /* The general concern about Result types is that they are too easy to ignore, and in the space of error handling we wanted the error of omission (i.e., forgetting to think about error handling) to result in a build error. There is nothing in our model that prevents a Result type from being used, and in fact, it would be very natural to use the Swift 2 error handling model along with a Result type for async and other functions that want to propagate "result|error" values across threads or other boundaries. What we need is a function to transform an function that throws (which would typically be a closure expr in practice) into a Result, and turn a Result into an value or a thrown error. - Lattner */ do { enum Result<T, U> { case Success(T) case Failure(U) } enum MathError: ErrorType { case DivideByZero case Other(String) } // easy to do but also easy to ignore, much like func myAsyncJob(completion: Result<Any, MathError> -> Void) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { completion(Result.Failure(MathError.Other("foo error"))) } } typealias DivideTaskResult = () throws -> CGFloat func divide(number: CGFloat, by: CGFloat, completion: DivideTaskResult -> Void) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { guard by != 0 else { completion { throw MathError.DivideByZero } return } completion{ number/by } } } typealias MagicNumberTaskResult = () throws -> Float func magicNumber(quotient: Float, completion: MagicNumberTaskResult -> Void) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { guard quotient != 0 else { completion { throw MathError.Other("log 0") } return } completion{ log(quotient) } } } divide(20, by: 0) { (result: DivideTaskResult) -> Void in do{ let r = try result() } catch (let err) { err } } // alt divide(20, by: 10) { do { let r = try $0() magicNumber(Float(r)) { do { let mr = try $0() } catch(let err) { err } } } catch (let err) { err } } }
// // Created by Иван Лизогуб on 15.11.2020. // import Foundation import UIKit class UserRegistrationPlayerView: AutoLayoutView { let scrollableStackView: ScrollableStackView = { let config: ScrollableStackView.Config = ScrollableStackView.Config( stack: ScrollableStackView.Config.Stack(axis: .vertical, distribution: .fill, alignment: .fill, spacing: 20.0), scroll: .defaultVertical, pinsStackConstraints: UIEdgeInsets(top: 20.0, left: 16.0, bottom: 0.0, right: -16.0) ) return ScrollableStackView(config: config) }() private let textFieldHeight: CGFloat = 40.0 private let registrationButtonSpacingToContentView: CGFloat = 20.0 private let registrationButtonHeight: CGFloat = 66.0 private let switchToOrganizerStackViewHeight: CGFloat = 30.0 let maxValueOfId = 999999999 var registrationOffset: CGFloat { registrationButtonSpacingToContentView + registrationButtonHeight + switchToOrganizerStackViewHeight } private lazy var lastNameStackView = buildStackView(withTextField: lastName, andLabel: lastNameWarning) let lastName = MaterialTextField() let lastNameWarning = WarningLabel() private lazy var firstNameStackView = buildStackView(withTextField: firstName, andLabel: firstNameWarning) let firstName = MaterialTextField() let firstNameWarning = WarningLabel() lazy var sex = UISegmentedControl(items: sexList) var sexStackView = UIStackView() var sexLabel = UILabel() var sexList: [String] = Sex.allCases.map{ $0.rawValue } let patronymicName = MaterialTextField() let latinFullname = MaterialTextField() private let fullnameButton = UIButton(type: .infoLight) var onTapLatinFullnameButton: (()->Void)? let fideID = MaterialTextField() private let fideIDButton = UIButton(type: .infoLight) var onTapFideButton: (() -> Void)? let frcID = MaterialTextField() private let frcIDButton = UIButton(type: .infoLight) var onTapFrcButton: (() -> Void)? private lazy var emailAddressStackView = buildStackView(withTextField: emailAddress, andLabel: emailAddressWarning) let emailAddress = MaterialTextField() let emailAddressWarning = WarningLabel() let emailWasRegisteredWarning = WarningLabel() private lazy var passwordStackView = buildStackView(withTextField: password, andLabel: passwordWarning) let password = MaterialTextField() let passwordWarning = WarningLabel() private lazy var validatePasswordStackView = buildStackView(withTextField: validatePassword, andLabel: validatePasswordWarning) let validatePassword = MaterialTextField() let validatePasswordWarning = WarningLabel() private let birthdateStackView = UIStackView() private let birthdateLabel = UILabel() private let birthdateDatePicker = UIDatePicker() private let switchToOrganizerStackView = UIStackView() private let switchToOrganizer = UISwitch() private let switchToOrganizerLabel = UILabel() let organizationCity = MaterialTextField() private let organizationNameStackView = UIStackView() let organizationName = MaterialTextField() let organizationNameWarning = WarningLabel() private let registrationButton = UIButton(type: .system) var onTapRegistrationButton: ((String?, String?, String?, String?, String?, String?, String?, String?, Bool, String?, String?, Date, String?, String?) -> Void)? init() { super.init(frame: .zero) setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setup() { addSubview(scrollableStackView) setupRoundedTextField(textField: lastName, textFieldPlaceholder: "Фамилия*") self.lastNameWarning.text = "Пустое поле. Введите свою фамилию" self.scrollableStackView.addArrangedSubview(lastNameStackView) setupRoundedTextField(textField: firstName, textFieldPlaceholder: "Имя*") firstNameWarning.text = "Пустое поле. Введите свое имя" scrollableStackView.addArrangedSubview(firstNameStackView) setupRoundedTextField(textField: patronymicName, textFieldPlaceholder: "Отчество") scrollableStackView.addArrangedSubview(patronymicName) self.sex.setTitleTextAttributes([NSAttributedString.Key.font: UIFont(name: "AppleSDGothicNeo-Regular", size: 20) as Any ,NSAttributedString.Key.foregroundColor: UIColor.gray as Any], for: .normal) self.sex.selectedSegmentIndex = 0 self.sexLabel.textColor = UIColor.rgba(142, 142, 147) self.sexLabel.attributedText = buildStringWithColoredAsterisk(string: "Пол*") self.sexLabel.textAlignment = .center self.sexLabel.font = UIFont(name: "AppleSDGothicNeo-Regular", size: 20) self.sexStackView.addArrangedSubview(sexLabel) self.sexStackView.addArrangedSubview(sex) self.sexStackView.spacing = 16 self.scrollableStackView.addArrangedSubview(sexStackView) self.birthdateLabel.textColor = UIColor.rgba(142, 142, 147) self.birthdateLabel.attributedText = buildStringWithColoredAsterisk(string: "Дата рождения*") self.birthdateLabel.font = UIFont(name: "AppleSDGothicNeo-Regular", size: 20) let calendar = Calendar(identifier: .gregorian) var components = DateComponents() components.calendar = calendar components.year = -150 let minDate = calendar.date(byAdding: components, to: Date()) let maxDate = Date() self.birthdateDatePicker.datePickerMode = .date self.birthdateDatePicker.maximumDate = maxDate self.birthdateDatePicker.minimumDate = minDate self.birthdateDatePicker.locale = Locale(identifier: "ru_RU") self.birthdateStackView.addArrangedSubview(birthdateLabel) self.birthdateStackView.addArrangedSubview(birthdateDatePicker) self.scrollableStackView.addArrangedSubview(birthdateStackView) setupRoundedTextField( textField: emailAddress, textFieldPlaceholder: "Введите Ваш email*", textFieldKeyboard: .emailAddress ) emailAddressWarning.text = "Адрес почты недействителен. Введите его в формате email@example.com" emailAddressStackView.addArrangedSubview(emailWasRegisteredWarning) scrollableStackView.addArrangedSubview(emailAddressStackView) setupRoundedTextField(textField: fideID, textFieldPlaceholder: "FideID", textFieldKeyboard: .numberPad) fideID.rightView = fideIDButton fideID.rightViewMode = .always fideIDButton.addTarget(self, action: #selector(onTapFide), for: .touchUpInside) scrollableStackView.addArrangedSubview(fideID) setupRoundedTextField(textField: frcID, textFieldPlaceholder: "ФШР ID", textFieldKeyboard: .numberPad) frcID.rightView = frcIDButton frcID.rightViewMode = .always frcIDButton.addTarget(self, action: #selector(onTapFrc), for: .touchUpInside) scrollableStackView.addArrangedSubview(frcID) setupRoundedTextField(textField: latinFullname, textFieldPlaceholder: "Фамилия и имя (Латиница)", textFieldKeyboard: .default) latinFullname.rightView = fullnameButton latinFullname.rightViewMode = .always fullnameButton.addTarget(self, action: #selector(onTapLatinFullname), for: .touchUpInside) latinFullname.addTarget(self, action: #selector(textFieldFullnameChanged), for: .editingChanged) scrollableStackView.addArrangedSubview(latinFullname) setupRoundedTextField(textField: password, textFieldPlaceholder: "Пароль*") password.isSecureTextEntry = true passwordWarning.text = "Пароль недействителен. Он должен содержать 1 Большую букву, 1 маленькую и 1 цифру" scrollableStackView.addArrangedSubview(passwordStackView) setupRoundedTextField(textField: validatePassword, textFieldPlaceholder: "Подтверждение пароля*") validatePassword.isSecureTextEntry = true validatePasswordWarning.text = "Пароли не совпадают." scrollableStackView.addArrangedSubview(validatePasswordStackView) self.registrationButton.setTitle("Зарегистрироваться", for: .normal) self.registrationButton.titleLabel?.font = UIFont(name: "AppleSDGothicNeo-Bold", size: 22) self.registrationButton.backgroundColor = UIColor.rgba(0, 122, 255) self.registrationButton.setTitleColor(.white, for: .normal) self.registrationButton.layer.cornerRadius = 15.0 self.registrationButton.clipsToBounds = false self.registrationButton.addTarget(self, action: #selector(onTapRegistration), for: .touchUpInside) scrollableStackView.addSubview(registrationButton) switchToOrganizerStackView.axis = .horizontal switchToOrganizerStackView.distribution = .equalSpacing switchToOrganizerStackView.alignment = .fill switchToOrganizerLabel.text = "Вы организатор?" switchToOrganizerStackView.addArrangedSubview(switchToOrganizerLabel) switchToOrganizerStackView.addArrangedSubview(switchToOrganizer) scrollableStackView.addSubview(switchToOrganizerStackView) setupRoundedTextField(textField: organizationCity, textFieldPlaceholder: "Город") organizationCity.isHidden = true scrollableStackView.addArrangedSubview(organizationCity) organizationNameStackView.axis = .vertical organizationNameStackView.distribution = .fill organizationNameStackView.alignment = .fill setupRoundedTextField(textField: organizationName, textFieldPlaceholder: "Название организации*") organizationNameWarning.text = "Поле названия организации пустое. Пожалуйста, заполните его" organizationNameStackView.addArrangedSubview(organizationName) organizationNameStackView.addArrangedSubview(organizationNameWarning) organizationName.isHidden = true scrollableStackView.addArrangedSubview(organizationNameStackView) switchToOrganizer.addTarget(self, action: #selector(onTapSwitchToOrganizer), for: .touchUpInside) } override func setupConstraints() { super.setupConstraints() scrollableStackView.pins() let margins = layoutMarginsGuide NSLayoutConstraint.activate([ switchToOrganizerStackView.heightAnchor.constraint(equalToConstant: switchToOrganizerStackViewHeight), switchToOrganizerStackView.bottomAnchor.constraint(equalTo: margins.bottomAnchor), switchToOrganizerStackView.trailingAnchor.constraint(equalTo: margins.trailingAnchor), switchToOrganizerStackView.leadingAnchor.constraint(equalTo: margins.leadingAnchor), registrationButton.topAnchor.constraint( equalTo: scrollableStackView.contentView.bottomAnchor, constant: registrationButtonSpacingToContentView ), sex.widthAnchor.constraint(equalToConstant: 267), sexStackView.heightAnchor.constraint(equalToConstant: 44), //birthdateLabel.leadingAnchor.constraint(equalTo: sexLabel.leftAnchor, constant: 20), birthdateDatePicker.widthAnchor.constraint(equalToConstant: 166), birthdateDatePicker.heightAnchor.constraint(equalToConstant: 44), birthdateStackView.heightAnchor.constraint(equalToConstant: 44), registrationButton.heightAnchor.constraint(equalToConstant: registrationButtonHeight), //283 registrationButton.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor, constant: 46), registrationButton.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor, constant: -46), registrationButton.centerXAnchor.constraint(equalTo: scrollableStackView.contentView.centerXAnchor), ]) scrollableStackView.set(contentInset: UIEdgeInsets(top: 0, left: 0, bottom: registrationOffset, right: 0)) } @objc private func onTapSwitchToOrganizer() { scrollableStackView.set(contentInset: UIEdgeInsets(top: 0.0, left: 0, bottom: registrationOffset, right: 0) ) UIView.animate(withDuration: 0.5, delay:0.0, options: [], animations: { self.organizationName.isHidden = !self.switchToOrganizer.isOn self.organizationCity.isHidden = !self.switchToOrganizer.isOn self.organizationNameWarning.isHidden = true self.layoutIfNeeded() }, completion: nil ) } @objc private func onTapRegistration() { onTapRegistrationButton?( lastName.text, firstName.text, patronymicName.text, fideID.text, frcID.text, emailAddress.text, password.text, validatePassword.text, switchToOrganizer.isOn, organizationCity.text, organizationName.text, birthdateDatePicker.date, sex.titleForSegment(at: sex.selectedSegmentIndex), latinFullname.text) } @objc private func onTapFide() { onTapFideButton?() } @objc private func onTapFrc() { onTapFrcButton?() } @objc private func onTapLatinFullname() { onTapLatinFullnameButton?() } @objc private func textFieldFullnameChanged(){ if latinFullname.text != "" { fideID.isEnabled = false fideID.alpha = 0.5 frcID.isEnabled = false frcID.alpha = 0.5 } else { fideID.alpha = 1 fideID.isEnabled = true frcID.alpha = 1 frcID.isEnabled = true } } } private extension UserRegistrationPlayerView { func buildStackView(withTextField textField: UITextField, andLabel label: UILabel) -> UIStackView { let stackView = UIStackView() stackView.axis = .vertical stackView.distribution = .fill stackView.alignment = .fill stackView.addArrangedSubview(textField) stackView.addArrangedSubview(label) return stackView } func setupRoundedTextField(textField: MaterialTextField, textFieldPlaceholder: String, textFieldKeyboard: UIKeyboardType = .default) { let attribudetString = buildStringWithColoredAsterisk(string: textFieldPlaceholder) textField.attributedPlaceholder = attribudetString textField.backgroundColor = UIColor.rgba(240, 241, 245) textField.layer.cornerRadius = 8 textField.keyboardType = textFieldKeyboard textField.autocapitalizationType = .none textField.sizeToFit() } func buildStringWithColoredAsterisk(string: String) -> NSMutableAttributedString { let attributedString = NSMutableAttributedString.init(string: string) let range = (string as NSString).range(of: "*") attributedString.addAttribute(NSAttributedString.Key.font, value: UIColor.rgba(0, 122, 255), range: NSRange(location: 0, length: attributedString.length)) attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "AppleSDGothicNeo-Regular", size: 20 ) as Any, range: NSRange(location: 0, length: attributedString.length)) attributedString.addAttribute( NSAttributedString.Key.foregroundColor, value: Styles.Color.asteriskRed, range: range ) return attributedString } }
// // EscapingRefererViewController.swift // SwiftSamples // // Created by Tsukasa Hasegawa on 2019/02/02. // Copyright © 2019 Tsukasa Hasegawa. All rights reserved. // import UIKit class EscapingRefererViewController: UIViewController { private var refered: EscapingRefered? var count = 0 @IBOutlet weak var label: UILabel! override func viewDidLoad() { super.viewDidLoad() refered = EscapingRefered(closure: { [weak self] in self?.count += 1 }) label.text = "\(count)" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func didTapIncreseButton(_ sender: UIButton) { refered?.storedClosure() label.text = "\(count)" } }
// // tableVC.swift // My Travel Book // // Created by Mac9 on 2.05.2019. // Copyright © 2019 Mac9. All rights reserved. // import UIKit import CoreData class tableVC: UIViewController ,UITableViewDelegate,UITableViewDataSource{ var titleArray=[String]() var subtitleArray=[String]() var latitudeArray=[Double]() var longitudeArray=[Double]() var selectedTitle="" var selectedSubtitle="" var selectedLatitude:Double=0 var selectedLongitude:Double=0 @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.delegate=self tableView.dataSource=self fetchData() } override func viewWillAppear(_ animated: Bool) { NotificationCenter.default.addObserver(self,selector:#selector(tableVC.fetchData),name:NSNotification.Name(rawValue: "newPlace"),object:nil) } @objc func fetchData(){ let appDelegate=UIApplication.shared.delegate as! AppDelegate let context=appDelegate.persistentContainer.viewContext let request=NSFetchRequest<NSFetchRequestResult>(entityName: "Places") request.returnsObjectsAsFaults=false do{ let results=try context.fetch(request) if results.count>0{ self.titleArray.removeAll(keepingCapacity: false) self.subtitleArray.removeAll(keepingCapacity: false) self.latitudeArray.removeAll(keepingCapacity: false) self.longitudeArray.removeAll(keepingCapacity: false) for result in results as![NSManagedObject]{ if let title=result.value(forKey:"title") as? String{ self.titleArray.append(title) } if let subtitle=result.value(forKey:"subtitle") as? String{ self.subtitleArray.append(subtitle) } if let latitude=result.value(forKey:"latitude") as? Double{ self.latitudeArray.append(latitude) } if let longitude=result.value(forKey:"longitude") as? Double{ self.longitudeArray.append(longitude) } self.tableView.reloadData() } } }catch{ print("error") } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedTitle=titleArray[indexPath.row] selectedSubtitle=subtitleArray[indexPath.row] selectedLatitude=latitudeArray[indexPath.row] selectedLongitude=longitudeArray[indexPath.row] performSegue(withIdentifier: "toMapVc", sender: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier=="toMapVc"{ let destinationVC=segue.destination as! mapVC destinationVC.selectedTitle=self.selectedTitle destinationVC.selectedSubtitle=self.selectedSubtitle destinationVC.selectedLatitude=self.selectedLatitude destinationVC.selectedLongitude=self.selectedLongitude } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return titleArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell=UITableViewCell() cell.textLabel?.text=titleArray[indexPath.row] return cell } @IBAction func add(_ sender: Any) { selectedTitle="" performSegue(withIdentifier: "toMapVc", sender: nil) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete{ let appDelegate=UIApplication.shared.delegate as! AppDelegate let context=appDelegate.persistentContainer.viewContext let request=NSFetchRequest<NSFetchRequestResult>(entityName: "Places") do{ let results=try context.fetch(request) for result in results as![NSManagedObject]{ if let title=result.value(forKey: "title") as? String{ if title==titleArray[indexPath.row]{ context.delete(result) titleArray.remove(at: indexPath.row) subtitleArray.remove(at: indexPath.row) latitudeArray.remove(at: indexPath.row) longitudeArray.remove(at: indexPath.row) self.tableView.reloadData() do{ try context.save() }catch{ } break } } } }catch{ } } } }
import Foundation struct ErrorMock: LocalizedError { var errorDescription = Seeds.string }
// // RestManager.swift // attendanceCheck // // Created by Fanky on 04.05.16. // Copyright © 2016 Fanky. All rights reserved. // import Foundation class RestManager: NSURLSessionDataTask { static let apiBaseUrl: String = "http://46.101.106.41/api/v1/" static func performRequest(urlPart: String, method: String, body: AnyObject?, completionHandler: (AnyObject?, NSURLResponse?, NSError?) -> Void) { print(RestManager.apiBaseUrl + urlPart) let url = NSURL(string: RestManager.apiBaseUrl + urlPart)! let config = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: config) let request = NSMutableURLRequest(URL: url) request.HTTPMethod = method request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") if let HTTPBody = body { request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(HTTPBody, options: .PrettyPrinted) } let task = session.dataTaskWithRequest(request) { (data, response, error) in let responseObject: AnyObject? if let tmpData = data { if (data?.length > 0) { responseObject = try! NSJSONSerialization.JSONObjectWithData(tmpData, options: []) } else { responseObject = nil } } else { responseObject = nil } completionHandler(responseObject, response, error) } task.resume() } }
// // APIType.swift // DHBC // // Created by Kiều anh Đào on 7/3/20. // Copyright © 2020 Anhdk. All rights reserved. // import Foundation import UIKit protocol APIType { } extension APIType { func userAgent() -> String { let bundleName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName")! let bundleVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion")! let systemName = UIDevice.current.systemName let systemVersion = UIDevice.current.systemVersion return "\(bundleName)/\(bundleVersion) \(systemName)/\(systemVersion)" } func getCommonHeader() -> [String: String] { return ["User-Agent": userAgent()] } func getCommonParam() -> [String: Any] { let uuid = "uuid" return [ "uuid": uuid, "os": Define.Api.os ] } }
// // LoginFormViewController.swift // VkApp // // Created by Macbook on 14.04.2021. // import UIKit class LoginFormViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } }
import Foundation // Strategy protocol PurchaseStrategy { func buy() } // concrete strategy struct CashMethod : PurchaseStrategy { func buy() { print("by: Cash") } } struct QRMethod : PurchaseStrategy { func buy() { print("by: QR code") } } struct BankingMethod : PurchaseStrategy { func buy() { print("by: internet banking") } } struct Customer { //context var strategy: PurchaseStrategy init(strategy: PurchaseStrategy) { self.strategy = strategy } func buyAnItem() { strategy.buy() } } let johny = Customer(strategy: QRMethod()) johny.buyAnItem()
// // ViewController.swift // Demo // // Created by Aaron on 2023/6/1. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let worker = Worker() worker.cpf .id(111) .name("zhang") .company("Apple") let teacher = Teacher() teacher.cpf .id(222) .name("Chen") .school("Tsinghua") debugPrint(worker) debugPrint(teacher) worker.cpf .update(\.id, 999) .update(\.name, "Loadar") .update(\.company, "Zhiyi") debugPrint(worker) dateTest() } private func dateTest() { debugPrint(Date.cpf.secondsOfOneDay, Date.cpf.yesterday) } }
// // Setting.swift // coalay // // Created by 落合裕也 on 2020/11/07. // Copyright © 2020 落合裕也. All rights reserved. // import Foundation let Debug = true
// // Genre.swift // filmania // // Created by Matheus Fróes on 16/10/19. // Copyright © 2019 Matheus Fróes. All rights reserved. // import Foundation struct Genre: Decodable { let id: Int let name: String }
// // ProfileModel.swift // final // // Created by James on 2018/12/1. // Copyright © 2018年 James. All rights reserved. // import UIKit import Foundation class ProfileModel: NSObject { var username : String? var sex : String? var desc : String? var useremail : String? var birthday : String? var city : String? var image : String? override init() { } init(username: String, sex : String, desc : String, useremail:String, birthday:String, city:String, image:String) { self.username = username self.sex = sex self.desc = desc self.useremail = useremail self.birthday = birthday self.city = city self.image = image } override var description: String{ return "Username:\(username),Sex:\(sex), Desc:\(desc), Useremail:\(useremail), Birthday:\(birthday), City:\(city), Image:\(image)" } }
// // MathQuestion.swift // Math-a-Mole-1.0 // // Created by Carson Cooley on 7/29/21. // import Foundation class MathQuestion { var no1: Int = -1 var no2: Int = -1 var operation: String? = nil var answer: Int = -1 var answeredCorrectly: Bool = false var dummyAnswers: [Int] = [] func generalSetUpAndSolve(questionParamMin: Int, questionParamMax: Int) { if let question = self as? AddQuestion { question.setUp(questionParamMin: questionParamMin, questionParamMax: questionParamMax) question.solve() } else if let question = self as? SubQuestion { question.setUp(questionParamMin: questionParamMin, questionParamMax: questionParamMax) question.solve() } else if let question = self as? MultQuestion { question.setUp(questionParamMin: questionParamMin, questionParamMax: questionParamMax) question.solve() } else if let question = self as? DivQuestion { question.setUp(questionParamMin: questionParamMin, questionParamMax: questionParamMax) question.solve() } } func setDummyAnswers() { if self is AddQuestion { dummyAddQuestions() } else if self is SubQuestion { dummySubQuestions() } else if self is MultQuestion { dummyMultQuestions() } else if self is DivQuestion { dummyDivQuestions() } } func dummyAddQuestions() { if self.answer == 0 { dummyAnswers.append(2) } else { dummyAnswers.append(self.answer - 1) } dummyAnswers.append(self.answer + 1) } func dummySubQuestions() { if self.answer == 0 { dummyAnswers.append(2) } else { dummyAnswers.append(self.answer - 1) } dummyAnswers.append(self.answer + 1) } func dummyMultQuestions() { if self.no1 == 0 && self.no2 == 0 { // 0 * 0 dummyAnswers.append(1) dummyAnswers.append(2) } else if self.answer == 0 { // 0 * 5 if self.no1 == 0 { dummyAnswers.append(self.no2) dummyAnswers.append(self.no2 + 1) } else { dummyAnswers.append(self.no1) dummyAnswers.append(self.no1 + 1) } } else { // 2 * 3 dummyAnswers.append(self.answer + self.no1) dummyAnswers.append(self.answer - self.no2) } } func dummyDivQuestions() { if self.answer == 0 { // 0 / 5 dummyAnswers.append(self.no2) dummyAnswers.append(1) } else if self.answer == 1 { if self.no1 == 1 && self.no2 == 1 { // 1 / 1 dummyAnswers.append(0) dummyAnswers.append(2) } else { // 5 / 5 dummyAnswers.append(0) dummyAnswers.append(self.no1) } } else { // 10 / 5 dummyAnswers.append(self.answer - 1) dummyAnswers.append(self.answer + 1) } } func toString() -> String { return "\(no1) \(operation!) \(no2)" } } class AddQuestion: MathQuestion, Solvable { var questionParamMin: Int = 0 var questionParamMax: Int = 10 func setUp(questionParamMin: Int, questionParamMax: Int) { self.operation = "+" self.no1 = Int.random(in: questionParamMin...questionParamMax) self.no2 = Int.random(in: questionParamMin...questionParamMax) } func solve() { self.answer = no1 + no2 } } class SubQuestion: MathQuestion, Solvable { var questionParamMin: Int = 0 var questionParamMax: Int = 10 func setUp(questionParamMin: Int, questionParamMax: Int) { self.operation = "-" while true { // Create a subtraction problem and then translate into an addition problem let reverseProblem = AddQuestion() reverseProblem.setUp(questionParamMin: questionParamMin, questionParamMax: questionParamMax) reverseProblem.solve() self.no1 = reverseProblem.answer self.no2 = reverseProblem.no2 self.answer = reverseProblem.no1 if (self.no2 != 0) { break } } } func solve() { self.answer = no1 - no2 } } class MultQuestion: MathQuestion, Solvable { var questionParamMin: Int = 0 var questionParamMax: Int = 10 func setUp(questionParamMin: Int, questionParamMax: Int) { self.operation = "x" self.no1 = Int.random(in: questionParamMin...questionParamMax) self.no2 = Int.random(in: questionParamMin...questionParamMax) } func solve() { self.answer = no1 * no2 } } class DivQuestion: MathQuestion, Solvable { var questionParamMin: Int = 0 var questionParamMax: Int = 10 func setUp(questionParamMin: Int, questionParamMax: Int) { self.operation = "/" while true { // Create a multiplication problem and then translate into a division problem let reverseProblem = MultQuestion() reverseProblem.setUp(questionParamMin: questionParamMin, questionParamMax: questionParamMax) reverseProblem.solve() self.no1 = reverseProblem.answer self.no2 = reverseProblem.no2 self.answer = reverseProblem.no1 if (self.no2 != 0) { break } } } func solve() { self.answer = no1 / no2 } }
// // HeaderCollection.swift // Driveo // // Created by Admin on 6/9/18. // Copyright © 2018 ITI. All rights reserved. // import UIKit class HeaderCollection: UICollectionReusableView { @IBOutlet weak var headerLabel: UILabel! }
import UIKit func findOutlier(_ array: [Int]) -> Int { var evenNum = [Int]() var oddNum = [Int]() for num in array{ if num % 2 == 0 { evenNum.append(num) } if num % 2 != 0 { oddNum.append(num) } } if evenNum.count == 1{ print(evenNum[0]) }else if oddNum.count == 1{ print(oddNum[0]) } return 0 } findOutlier([2,4,0,4,11,2602,36])
// // MarvelAPIService.swift // MarvelCharacters // // Created by Alexander Gurzhiev on 04.04.2021. // import Foundation import Alamofire final class MarvelAPIService { private let configuration: NetworkConfiguration private var pagination: (hasMore: Bool, offset: Int) = (true, 0) private var loadInProgress: Bool = false init(configuration: NetworkConfiguration = .Default) { self.configuration = configuration } private func buildRequest(_ entity: MarvelRequest, path: String, method: HTTPMethod) -> DataRequest { let fullPath = "\(configuration.basePath)\(path)" let parameters = encodeParameters(entity) return AF .request(fullPath, method: method, parameters: parameters) .cURLDescription { debugPrint($0) } } private func encodeParameters<Value>(_ value: Value) -> [String: Any] where Value: Encodable { guard let data = try? JSONEncoder().encode(value), let result = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { return [:] } return result } } extension MarvelAPIService: NetworkService { func load(search: String?, completion: @escaping RequestCompletion) { guard !loadInProgress else { return } guard pagination.hasMore else { completion(.failure(MarvelError.noMorePages)) return } loadInProgress = true let entity = MarvelRequest(configuration: configuration, offset: pagination.offset, search: search) let request = buildRequest(entity, path: "v1/public/characters", method: .get) request.responseData { [weak self] dataResponse in switch dataResponse.result { case .success(let data): if let response: MarvelResponse = try? JSONDecoder().decode(MarvelResponse.self, from: data), let responseData = response.data { self?.pagination = (responseData.hasMorePages, responseData.nextOffset) completion(.success(responseData)) } else { completion(.failure(MarvelError.decodeError)) } case .failure(let error): completion(.failure(error)) } self?.loadInProgress = false } } func reset() { pagination = (true, 0) loadInProgress = false } }
// // ExtensionManifest.swift // Ad Collector Extension // // Created by Ryan Govostes on 2/14/18. // Copyright © 2018 ProPublica. All rights reserved. // import Foundation internal class ExtensionManifest: Codable { var background: Background? // File references will be relative to this baseURL var baseURL: URL? open static let `default`: ExtensionManifest = { let url = Bundle.main.url(forResource: "manifest", withExtension: "json", subdirectory: "dist")! return ExtensionManifest.load(fromURL: url) }() class func load(fromURL: URL) -> ExtensionManifest { let data = try! Data(contentsOf: fromURL, options: .mappedIfSafe) let instance = try! JSONDecoder().decode(ExtensionManifest.self, from: data) instance.baseURL = fromURL.deletingLastPathComponent() return instance } func urlForResource(named name: String) -> URL? { return baseURL?.appendingPathComponent(name) } func validate() { // TODO: It might be nice to cross-check the Info.plist with the // information in manifest.json fatalError("Manifest validation is not yet implemented") } } internal struct Background: Codable { var scripts: [String]? var pages: [String]? }
// // ScreenCapture.swift // MyTestApp // // Created by Joe Kletz on 09/11/2020. // import UIKit import AVFoundation import ReplayKit class ScreenCapture: NSObject, RPPreviewViewControllerDelegate { var recording = false let rp = RPScreenRecorder.shared() var ovc : UIViewController? override init() { super.init() rp.startRecording { (err) in } } func stop() { let vc = RPPreviewViewController() vc.previewControllerDelegate = self rp.stopRecording { (vc, err) in self.ovc!.present(vc!, animated: true, completion: nil) } } }
// // MentionsTableViewController.swift // Smashtag // // Created by Caroline Liu on 2015-09-07. // Copyright (c) 2015 Caroline Liu. All rights reserved. // import UIKit class MentionsTableViewController: UITableViewController { var tweet: Tweet! enum mentionsSections: Printable { case Hashtags case Users case Media case URLS var description: String { switch self { case .Hashtags: return "Hashtags" case .URLS: return "URLs" case .Users: return "Users" case .Media: return "Images" } } } var groups = [mentionsSections]() var selectedText: String? func loadSections() { if (groups.count == 0) { if (tweet.media.count > 0) { groups.append(mentionsSections.Media) } if (tweet.hashtags.count > 0) { groups.append(mentionsSections.Hashtags) } if (tweet.userMentions.count > 0) { groups.append(mentionsSections.Users) } if (tweet.urls.count > 0) { groups.append(mentionsSections.URLS) } } } private func fetchImage(imageURL: NSURL, cell: ImageTableViewCell) { let qos = Int(QOS_CLASS_USER_INITIATED.value) dispatch_async(dispatch_get_global_queue(qos, 0)) { () -> Void in let imageData = NSData(contentsOfURL: imageURL) dispatch_async(dispatch_get_main_queue()) { if imageData != nil { cell.imageView?.image = UIImage(data: imageData!, scale: 1) self.tableView.reloadData() } } } } override func viewDidLoad() { super.viewDidLoad() loadSections() // 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() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. return groups.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. switch groups[section] { case .Hashtags: return tweet.hashtags.count ?? 0 case .Media: return tweet.media.count ?? 0 case .URLS: return tweet.urls.count ?? 0 case .Users: return tweet.userMentions.count ?? 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Configure the cell... switch groups[indexPath.section] { case .Media: let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.ImageCellReuseIdentifier, forIndexPath: indexPath) as! ImageTableViewCell if cell.imageView?.image == nil { fetchImage(tweet.media[indexPath.row].url, cell: cell) } return cell case .Users: let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.TextCellReuseIdentifier, forIndexPath: indexPath) as! UITableViewCell cell.textLabel?.text = tweet.userMentions[indexPath.row].keyword return cell case .Hashtags: let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.TextCellReuseIdentifier, forIndexPath: indexPath) as! UITableViewCell cell.textLabel?.text = tweet.hashtags[indexPath.row].keyword return cell case .URLS: let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.TextCellReuseIdentifier, forIndexPath: indexPath) as! UITableViewCell cell.textLabel?.text = tweet.urls[indexPath.row].keyword return cell } } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String { return groups[section].description } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch groups[indexPath.section] { case .URLS: if let URL = NSURL(string: tweet.urls[indexPath.row].keyword) { UIApplication.sharedApplication().openURL(URL) } case .Hashtags: self.selectedText = tweet.hashtags[indexPath.row].keyword self.performSegueWithIdentifier(Storyboard.UnwindReuseIdentifier, sender: self) case .Users: self.selectedText = tweet.userMentions[indexPath.row].keyword self.performSegueWithIdentifier(Storyboard.UnwindReuseIdentifier, sender: self) case .Media: // TODO: segue to new view which will allow gestures on the image break } } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { // Configure the cell... switch groups[indexPath.section] { case .Media: var aspectRatio = tweet.media[indexPath.row].aspectRatio return view.frame.width / CGFloat(aspectRatio) case .Hashtags, .URLS, .Users: return UITableViewAutomaticDimension } } /* // 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. } */ }
// // ViewController.swift // Guaymas 6.0 // // Created by saul ulises urias guzmàn on 17/01/17. // Copyright © 2017 saul ulises urias guzmàn. All rights reserved. // import UIKit class ViewController: UIViewController { //MARK: - Ciclo de vida de la Vista override func viewDidLoad() { super.viewDidLoad(); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning(); } //MARK: - Acciones @IBAction func btnPagina(_ sender: Any) { UIApplication.shared.open(NSURL(string:"http://www.guaymas.gob.mx") as! URL, options: [:], completionHandler: nil); } @IBAction func btnFacebook(_ sender: Any) { UIApplication.shared.open(NSURL(string:"https://www.facebook.com/AquiEsGuaymas/?pnref=story.unseen-section") as! URL, options: [:], completionHandler: nil); } @IBAction func btnTwitter(_ sender: Any) { UIApplication.shared.open(NSURL(string:"https://twitter.com/Guaymas_2017") as! URL, options: [:], completionHandler: nil); } @IBAction func btnYoutuber(_ sender: Any) { UIApplication.shared.open(NSURL(string:"https://www.youtube.com/channel/UC6LQww1epc_VzH7RYMo8HzQ") as! URL, options: [:], completionHandler: nil); } }
import Foundation class PDFViewModel { private let bill: Bill init(bill: Bill) { self.bill = bill } //MARK: - Properties var costA: String { return bill.costA.formattedString } var costB: String { return bill.costB.formattedString } var costC: String { return bill.costC.formattedString } var consumptionA: String { return bill.consumptionA.formattedString } var consumptionB: String { return bill.consumptionB.formattedString } var consumptionC: String { return bill.consumptionC.formattedString } var fixedCharge: String { return bill.fixedCharge.formattedString } var surcharge: String { return bill.surcharge.formattedString } var otherCharges: String { return bill.otherCharges.formattedString } var total: String { return bill.total.formattedString } var labelA: String { return "Band-A Consumption @ MRF 22.0/Cbm" } var labelB: String { return "Band-B Consumption @ MRF 70.0/Cbm" } var labelC: String { return "Band-C Consumption @ MRF 95.0/Cbm" } var previousDate: String { return bill.previousDate.stringWithFormat(Strings.dateFormat) } var currentDate: String { return bill.currentDate.stringWithFormat(Strings.dateFormat) } var previousReading: String { return bill.previousReading.formattedString } var currentReading: String { return bill.currentReading.formattedString } var days: String { return "\(bill.currentDate.numberOfDaysFrom(date: bill.previousDate))" } var consumption: String { return bill.consumption.formattedString } var rate: String { return bill.consumptionRate.formattedString } var billee: String { return "\(bill.tenantName)\nH. Jenin – \(bill.unitNumber)\nAbadhah Fehi Magu\nK. Malé 20081" } var billDetails: String { let format = "dd.MM.yyyy" let printedOn = Date().stringWithFormat(format) let dueDate = Date().dateByAdding(days: 30).stringWithFormat(format) return "\(bill.id)\n\(bill.meterNumber)\n\(printedOn)\n\(dueDate)" } }