text stringlengths 8 1.32M |
|---|
//
// BLNuevaTareaTableViewController.swift
// App_BatLogin
//
// Created by cice on 10/2/17.
// Copyright © 2017 cice. All rights reserved.
//
import UIKit
class BLNuevaTareaTableViewController: UITableViewController {
//MARK: - OUTlet
@IBOutlet weak var myImagenPerfil: UIImageView!
@IBOutlet weak var myUserNamePerfil: UILabel!
@IBOutlet weak var myFechaPerfil: UILabel!
@IBOutlet weak var myDescripcionNuevaTarea: UITextView!
@IBOutlet weak var myImagenNuevaTarea: UIImageView!
@IBOutlet weak var ocultarImagenBTN: UIButton!
//MARK: - ACTION
@IBAction func ocultarImagenACTION(_ sender: AnyObject) {
ocultarImagenBTN.isHidden = true
myImagenNuevaTarea.image = nil
}
@IBAction func ocultarVC(_ sender: AnyObject) {
dismiss(animated: true, completion: nil)
}
//MARK: - LIFE VC
override func viewDidLoad() {
super.viewDidLoad()
ocultarImagenBTN.isHidden = true
tableView.estimatedRowHeight = 60
tableView.rowHeight = UITableViewAutomaticDimension
myDescripcionNuevaTarea.delegate = self
//Bloque Toolbar
let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 0, height: 44))
toolbar.barTintColor = CONSTANTES.COLORES.colorNegro
toolbar.tintColor = CONSTANTES.COLORES.colorAmarillo
let camera = UIBarButtonItem(image: UIImage(named:"camera"),
style: .done,
target: self,
action: #selector(self.pickerFoto))
let salvarDatos = UIBarButtonItem(title: "Salvar",
style: .plain,
target: self,
action: #selector(self.salvarDatos))
let barraFlexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolbar.items = [camera, barraFlexible, salvarDatos]
myDescripcionNuevaTarea.inputAccessoryView = toolbar
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.bajarTeclado))
tableView.addGestureRecognizer(gestureRecognizer)
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(_ animated: Bool) {
// hacemos foco en el texto nada mas empezar
super.viewWillAppear(animated)
myDescripcionNuevaTarea.becomeFirstResponder()
}
func bajarTeclado(){
myDescripcionNuevaTarea.resignFirstResponder()
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 1{
return UITableViewAutomaticDimension
}
return super.tableView(tableView, heightForRowAt: indexPath)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: utils
func pickerFoto(){
pickerPicture()
}
func salvarDatos(){
if myDescripcionNuevaTarea.text != "" && myImagenNuevaTarea.image != nil{
let imageData = UIImageJPEGRepresentation(myImagenNuevaTarea.image!, 0.3)
tareasManager.tareas.append([CONSTANTES.USER_DEFAULTS.KEY_DESCRIPCION_TAREA : myDescripcionNuevaTarea.text as String])
tareasManager.fotoTarea.append([CONSTANTES.USER_DEFAULTS.KEY_IMAGEN_TAREA : imageData! as Data])
dismiss(animated: true, completion: nil)
}
present(alertVC("EY", "Rellena toda la información", "OK"), animated: true, completion: nil)
}
}
extension BLNuevaTareaTableViewController : UITextViewDelegate{
func textViewDidChange(_ textView: UITextView) {
let currentOffset = tableView.contentOffset
UIView.setAnimationsEnabled(false)
tableView.beginUpdates()
tableView.endUpdates()
UIView.setAnimationsEnabled(true)
tableView.setContentOffset(currentOffset, animated: false)
}
}
extension BLNuevaTareaTableViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate{
func pickerPicture(){
if UIImagePickerController.isSourceTypeAvailable(.camera){
showMenu()
}else{
showLibraryPictures()
}
}
func showMenu(){
let actionVC = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
actionVC.addAction(UIAlertAction(title: "Cancelar", style: .cancel, handler: nil))
actionVC.addAction(UIAlertAction(title: "Tomar foto", style: .default, handler: {
Void in
self.pickerPicture()
}))
actionVC.addAction(UIAlertAction(title: "Escoge de la librería", style: .default, handler: { Void in
self.showLibraryPictures()
}))
present(actionVC, animated: true, completion: nil)
}
func showLibraryPictures(){
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = self
imagePicker.allowsEditing = true
present(imagePicker, animated: true, completion: nil)
}
func cameraPictures(){
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .camera
imagePicker.delegate = self
imagePicker.allowsEditing = true
present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let imageData = info[UIImagePickerControllerOriginalImage] as? UIImage{
myImagenNuevaTarea.image = imageData
ocultarImagenBTN.isHidden = false
}
dismiss(animated: true, completion: nil)
}
}
|
//
// Place.swift
// Places of Interest
//
// Created by Leon Baird on 08/07/2015.
// Copyright (c) 2015 Leon Baird. All rights reserved.
//
import Foundation
import CoreData
import MapKit
let PlaceEntityName = "Place"
let PlaceAttributeName = "placeName"
let PlaceAttributeDate = "dateVisited"
class Place: NSManagedObject, MKAnnotation {
@NSManaged var placeName: String
@NSManaged var dateVisited: NSTimeInterval
@NSManaged var placeDescription: String
@NSManaged var imagePath: String
@NSManaged var geoLong: Double
@NSManaged var geoLat: Double
// MARK: - Mapkit Annotation values
var coordinate:CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: geoLat, longitude: geoLong)
}
var title:String {
return placeName
}
var subtitle:String {
return "Visited on \(self.shortDateFormat)"
}
// MARK: - Helper Methods
var shortDateFormat:String {
return NSDateFormatter.localizedStringFromDate(
NSDate(timeIntervalSince1970: dateVisited),
dateStyle: .ShortStyle,
timeStyle: .NoStyle
)
}
var longDateFormat:String {
return NSDateFormatter.localizedStringFromDate(
NSDate(timeIntervalSince1970: dateVisited),
dateStyle: .FullStyle,
timeStyle: .NoStyle
)
}
func deleteImageFileIfExists() {
NSFileManager.defaultManager().removeItemAtPath(
NSHomeDirectory()+imagePath, error: nil)
}
}
|
func diagonalDifference(of matrix: [[Int]]) -> Int {
var diff = 0
var sumLeftToRight = 0
var sumRightToLeft = 0
for index in 0..<matrix.count {
sumLeftToRight += matrix[index][index]
sumRightToLeft += matrix[index][(matrix.count - 1) - index]
}
diff = sumRightToLeft - sumLeftToRight
if diff >= 0 {
return diff
} else {
return diff * -1
}
}
var arr = [[1,2,3,4], [5,6,7,9], [10,11,12,13], [14,15,16,17]]
print(calcDiag(arr))
|
import UIKit
//assert
// - 특정 조건을 체크하고, 조건이 성립되지 않으면 메세지를 출력하게 할 수 있는 함수
// - assert함수는 디버깅 모드에서만 동작하고 주로 디버깅 중 조건의 검증을 위하여 사용합니다.
var value = 0
assert(value == 0)
value = 2
assert(value == 0, "값이 0이 아닙니다.") // error
//guard 문
// - 뭔가를 검사하여 그 다음에 오는 코드를 실행할지 말지 결정 하는 것
// - guard 문에 주어진 조건문이 거짓일 떄 구문이 실행됨
/*
guard 조건 else {
// 조건이 false 이면 else 구문이 실행되고
return or throw or break 를 통해 이 후 코드를 실행하지 않도록 한다.
}
*/
func guardTest(value: Int){
guard value == 0 else { return }
print("안녕하세요")
}
guardTest(value: 0)
//guard 문으로 옵셔널 바인딩하기
func guardTest1(value1: Int?){
guard value1 == value1 else { return }
print(value1)
}
guardTest1(value1: 2)
guardTest1(value1: nil) // nil값이 들어가서 guard 문에 막힘
|
///
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
///
///
/// - 4.3
///
import Foundation
public class ProfilingATNSimulator: ParserATNSimulator {
private(set) var decisions: [DecisionInfo]
internal var numDecisions: Int = 0
internal var _sllStopIndex: Int = 0
internal var _llStopIndex: Int = 0
internal var currentDecision: Int = 0
internal var currentState: DFAState?
///
/// At the point of LL failover, we record how SLL would resolve the conflict so that
/// we can determine whether or not a decision / input pair is context-sensitive.
/// If LL gives a different result than SLL's predicted alternative, we have a
/// context sensitivity for sure. The converse is not necessarily true, however.
/// It's possible that after conflict resolution chooses minimum alternatives,
/// SLL could get the same answer as LL. Regardless of whether or not the result indicates
/// an ambiguity, it is not treated as a context sensitivity because LL prediction
/// was not required in order to produce a correct prediction for this decision and input sequence.
/// It may in fact still be a context sensitivity but we don't know by looking at the
/// minimum alternatives for the current input.
///
internal var conflictingAltResolvedBySLL: Int = 0
public init(_ parser: Parser) {
decisions = [DecisionInfo]()
super.init(parser,
parser.getInterpreter().atn,
parser.getInterpreter().decisionToDFA,
parser.getInterpreter().sharedContextCache)
numDecisions = atn.decisionToState.count
for i in 0..<numDecisions {
decisions.append(DecisionInfo(i))
}
}
override
public func adaptivePredict(_ input: TokenStream, _ decision: Int,_ outerContext: ParserRuleContext?) throws -> Int {
let outerContext = outerContext
self._sllStopIndex = -1
self._llStopIndex = -1
self.currentDecision = decision
let start = ProcessInfo.processInfo.systemUptime //System.nanoTime(); // expensive but useful info
let alt: Int = try super.adaptivePredict(input, decision, outerContext)
let stop = ProcessInfo.processInfo.systemUptime //System.nanoTime();
decisions[decision].timeInPrediction += Int64((stop - start) * TimeInterval(NSEC_PER_SEC))
decisions[decision].invocations += 1
let SLL_k: Int64 = Int64(_sllStopIndex - _startIndex + 1)
decisions[decision].SLL_TotalLook += SLL_k
decisions[decision].SLL_MinLook = decisions[decision].SLL_MinLook == 0 ? SLL_k : min(decisions[decision].SLL_MinLook, SLL_k)
if SLL_k > decisions[decision].SLL_MaxLook {
decisions[decision].SLL_MaxLook = SLL_k
decisions[decision].SLL_MaxLookEvent =
LookaheadEventInfo(decision, nil, input, _startIndex, _sllStopIndex, false)
}
if _llStopIndex >= 0 {
let LL_k: Int64 = Int64(_llStopIndex - _startIndex + 1)
decisions[decision].LL_TotalLook += LL_k
decisions[decision].LL_MinLook = decisions[decision].LL_MinLook == 0 ? LL_k : min(decisions[decision].LL_MinLook, LL_k)
if LL_k > decisions[decision].LL_MaxLook {
decisions[decision].LL_MaxLook = LL_k
decisions[decision].LL_MaxLookEvent =
LookaheadEventInfo(decision, nil, input, _startIndex, _llStopIndex, true)
}
}
defer {
self.currentDecision = -1
}
return alt
}
override
internal func getExistingTargetState(_ previousD: DFAState, _ t: Int) -> DFAState? {
// this method is called after each time the input position advances
// during SLL prediction
_sllStopIndex = _input.index()
let existingTargetState: DFAState? = super.getExistingTargetState(previousD, t)
if existingTargetState != nil {
decisions[currentDecision].SLL_DFATransitions += 1 // count only if we transition over a DFA state
if existingTargetState == ATNSimulator.ERROR {
decisions[currentDecision].errors.append(
ErrorInfo(currentDecision, previousD.configs, _input, _startIndex, _sllStopIndex, false)
)
}
}
currentState = existingTargetState
return existingTargetState
}
override
internal func computeTargetState(_ dfa: DFA, _ previousD: DFAState, _ t: Int) throws -> DFAState {
let state = try super.computeTargetState(dfa, previousD, t)
currentState = state
return state
}
override
internal func computeReachSet(_ closure: ATNConfigSet, _ t: Int, _ fullCtx: Bool) throws -> ATNConfigSet? {
if fullCtx {
// this method is called after each time the input position advances
// during full context prediction
_llStopIndex = _input.index()
}
let reachConfigs = try super.computeReachSet(closure, t, fullCtx)
if fullCtx {
decisions[currentDecision].LL_ATNTransitions += 1 // count computation even if error
if reachConfigs != nil {
} else {
// no reach on current lookahead symbol. ERROR.
// TODO: does not handle delayed errors per getSynValidOrSemInvalidAltThatFinishedDecisionEntryRule()
decisions[currentDecision].errors.append(
ErrorInfo(currentDecision, closure, _input, _startIndex, _llStopIndex, true)
)
}
} else {
decisions[currentDecision].SLL_ATNTransitions += 1
if reachConfigs != nil {
} else {
// no reach on current lookahead symbol. ERROR.
decisions[currentDecision].errors.append(
ErrorInfo(currentDecision, closure, _input, _startIndex, _sllStopIndex, false)
)
}
}
return reachConfigs
}
override
internal func evalSemanticContext(_ pred: SemanticContext, _ parserCallStack: ParserRuleContext, _ alt: Int, _ fullCtx: Bool) throws -> Bool {
let result = try super.evalSemanticContext(pred, parserCallStack, alt, fullCtx)
if !(pred is SemanticContext.PrecedencePredicate) {
let fullContext = _llStopIndex >= 0
let stopIndex = fullContext ? _llStopIndex : _sllStopIndex
decisions[currentDecision].predicateEvals.append(
PredicateEvalInfo(currentDecision, _input, _startIndex, stopIndex, pred, result, alt, fullCtx)
)
}
return result
}
override
internal func reportAttemptingFullContext(_ dfa: DFA, _ conflictingAlts: BitSet?, _ configs: ATNConfigSet, _ startIndex: Int, _ stopIndex: Int) {
if let conflictingAlts = conflictingAlts {
conflictingAltResolvedBySLL = conflictingAlts.firstSetBit()
} else {
let configAlts = configs.getAlts()
conflictingAltResolvedBySLL = configAlts.firstSetBit()
}
decisions[currentDecision].LL_Fallback += 1
super.reportAttemptingFullContext(dfa, conflictingAlts, configs, startIndex, stopIndex)
}
override
internal func reportContextSensitivity(_ dfa: DFA, _ prediction: Int, _ configs: ATNConfigSet, _ startIndex: Int, _ stopIndex: Int) {
if prediction != conflictingAltResolvedBySLL {
decisions[currentDecision].contextSensitivities.append(
ContextSensitivityInfo(currentDecision, configs, _input, startIndex, stopIndex)
)
}
super.reportContextSensitivity(dfa, prediction, configs, startIndex, stopIndex)
}
override
internal func reportAmbiguity(_ dfa: DFA, _ D: DFAState, _ startIndex: Int, _ stopIndex: Int, _ exact: Bool,
_ ambigAlts: BitSet?, _ configs: ATNConfigSet) {
var prediction: Int
if let ambigAlts = ambigAlts {
prediction = ambigAlts.firstSetBit()
} else {
let configAlts = configs.getAlts()
prediction = configAlts.firstSetBit()
}
if configs.fullCtx && prediction != conflictingAltResolvedBySLL {
// Even though this is an ambiguity we are reporting, we can
// still detect some context sensitivities. Both SLL and LL
// are showing a conflict, hence an ambiguity, but if they resolve
// to different minimum alternatives we have also identified a
// context sensitivity.
decisions[currentDecision].contextSensitivities.append(
ContextSensitivityInfo(currentDecision, configs, _input, startIndex, stopIndex)
)
}
decisions[currentDecision].ambiguities.append(
AmbiguityInfo(currentDecision, configs, ambigAlts!,
_input, startIndex, stopIndex, configs.fullCtx)
)
super.reportAmbiguity(dfa, D, startIndex, stopIndex, exact, ambigAlts!, configs)
}
public func getDecisionInfo() -> [DecisionInfo] {
return decisions
}
}
|
import Foundation
import RealmSwift
public class DataBaseAPI {
private var _realm = Realm()
private var _dateApi = DateAPI()
init () {
setSchemaVersion(0, Realm.defaultPath, {
migration, oldSchemaVersion in
if oldSchemaVersion < 0 {
}
})
println("\(Realm.defaultPath)")
}
func initDB() {
_realm.beginWrite()
_realm.deleteAll()
_realm.commitWrite()
var workItems = getWorkItemList()
_realm.beginWrite()
for item in workItems {
_realm.add(item)
}
_realm.commitWrite()
}
func maxWorkItemId() -> Int {
var results = _realm.objects(RWorkItem)
var max = 0
for item in results {
if max < item.Id {
max = item.Id
}
}
return max
}
func updateWorkItem(workItem: RWorkItem) {
_realm.beginWrite()
println(workItem)
_realm.add(workItem, update: true)
_realm.commitWrite()
}
func updateWorkItemTitle(workItem: RWorkItem, title: String) {
_realm.beginWrite()
workItem.Title = title
_realm.commitWrite()
}
func deleteWorkItem(workItem: RWorkItem) {
_realm.beginWrite()
_realm.delete(workItem)
_realm.commitWrite()
}
func addWorkItem(workItem: RWorkItem) {
_realm.beginWrite()
_realm.add(workItem)
_realm.commitWrite()
}
func clearWorkItems() {
_realm.beginWrite()
_realm.delete(_realm.objects(RWorkItem))
_realm.commitWrite()
}
func getForToday() -> [RWorkItem] {
var todayCutOff = _dateApi.addToDate(0.0, minutes: 0.0, hours: 0.0, days: 1.0, date: _dateApi.getTodayStart())
var items = _realm.objects(RWorkItem)
.filter("Date < %@ AND Date >= %@", todayCutOff, _dateApi.getTodayStart())
.sorted("Date", ascending: true)
var results = [RWorkItem]()
for item in items {
results.append(item)
}
return results
}
func getForTomorrow() -> [RWorkItem] {
var tomorrowCutOff = _dateApi.addToDate(0.0, minutes: 0.0, hours: 0.0, days: 2.0, date: _dateApi.getTodayStart())
var todayStart = _dateApi.addToDate(0.0, minutes: 0.0, hours: 0.0, days: 1.0, date: _dateApi.getTodayStart())
var items = _realm.objects(RWorkItem)
.filter("Date < %@ AND Date >= %@", tomorrowCutOff, todayStart)
.sorted("Date", ascending: true)
var results = [RWorkItem]()
for item in items {
results.append(item)
}
return results
}
func getForThreePlus() -> [RWorkItem] {
var thirdDayCutOff = _dateApi.addToDate(0.0, minutes: 0.0, hours: 0.0, days: 3.0, date: _dateApi.getTodayStart())
var thirdDatStart = _dateApi.addToDate(0.0, minutes: 0.0, hours: 0.0, days: 2.0, date: _dateApi.getTodayStart())
var items = _realm.objects(RWorkItem)
.filter("Date < %@ AND Date >= %@", thirdDayCutOff, thirdDatStart)
.sorted("Date", ascending: true)
var results = [RWorkItem]()
for item in items {
results.append(item)
}
return results
}
func getWorkItemList() -> [RWorkItem] {
var maxId = _realm.objects(RWorkItem).count
var results = [RWorkItem]()
results.append(RWorkItem( value: [
"Id": maxId,
"Title": "Wash Clothes",
"Date": _dateApi.addToDay(0.0, minutes: 0.0, hours: 1.0, days: 0.0),
"Weather": Weather.Bad.rawValue,
"WeatherDescription":"Fair",
"Image": "fair",
"City": "San Francisco"]))
results.append(RWorkItem( value: [
"Title": "Cut the grass",
"Id": ++maxId,
"Date": _dateApi.addToDay(0.0, minutes: 0.0, hours: 2.0, days: 0.0),
"Weather": Weather.Good.rawValue,
"WeatherDescription":"Fair",
"Image": "fair",
"City": "San Francisco"]))
results.append(RWorkItem( value: [
"Title": "Work on project",
"Id": ++maxId,
"Date": _dateApi.addToDay(0.0, minutes: 0.0, hours: 3.0, days: 0.0),
"Weather": Weather.Bad.rawValue,
"WeatherDescription":"Fair",
"Image": "fair",
"City": "San Francisco"]))
// Tomorrow
results.append(RWorkItem( value: [
"Title": "Work on project",
"Id": ++maxId,
"Date": _dateApi.addToDay(0.0, minutes: 0.0, hours: 0.0, days: 1.0),
"Weather": Weather.Bad.rawValue,
"WeatherDescription":"Fair",
"Image": "fair",
"City": "San Francisco"]))
results.append(RWorkItem( value: [
"Title": "Wash dishes",
"Id": ++maxId,
"Date": _dateApi.addToDay(0.0, minutes: 0.0, hours: 2.0, days: 1.0),
"Weather": Weather.Bad.rawValue,
"WeatherDescription":"Fair",
"Image": "fair",
"City": "San Francisco"]))
results.append(RWorkItem( value: [
"Title": "Fix the roof",
"Id": ++maxId,
"Date": _dateApi.addToDay(0.0, minutes: 0.0, hours: 4.0, days: 1.0),
"Weather": Weather.Good.rawValue,
"WeatherDescription":"Fair",
"Image": "fair",
"City": "San Francisco"]))
// 3 +
results.append(RWorkItem( value: [
"Title": "Take dog to the Pet Smart",
"Id": ++maxId,
"Date": _dateApi.addToDay(0.0, minutes: 0.0, hours: 2.0, days: 2.0),
"Weather": Weather.Good.rawValue,
"WeatherDescription":"Fair",
"Image": "fair",
"City": "San Francisco"]))
results.append(RWorkItem( value: [
"Title": "Go grocery shopping",
"Id": ++maxId,
"Date": _dateApi.addToDay(0.0, minutes: 30.0, hours: 2.0, days: 2.0),
"Weather": Weather.Good.rawValue,
"WeatherDescription":"Fair",
"Image": "fair",
"City": "San Francisco"]))
results.append(RWorkItem( value: [
"Title": "Work on project",
"Id": ++maxId,
"Date": _dateApi.addToDay(0.0, minutes: 0.0, hours: 4.0, days: 2.0),
"Weather": Weather.Bad.rawValue,
"WeatherDescription":"Fair",
"Image": "fair",
"City": "San Francisco"]))
return results
}
} |
//
// SMDataProcessing.swift
// sensmove
//
// Created by alexandre on 30/08/2015.
// Copyright (c) 2015 ___alexprod___. All rights reserved.
//
import UIKit
class SMDataProcessing: NSObject {
override init() {
super.init()
}
func removeNoise(datas: JSON) -> JSON {
var activeValuesIndexes: Array = [Int]()
var possibleNoiseIndexes: Array = [Int]()
var trueArr: Array = datas["fsr"].arrayValue.map { (value:JSON) -> Float in
return value.floatValue
}
for(var i = 0; i < trueArr.count; i++) {
if trueArr[i] > 10 {
activeValuesIndexes.append(i)
}
if trueArr[i] < 10 && trueArr[i] > 0 {
possibleNoiseIndexes.append(i)
}
}
if possibleNoiseIndexes.count > 0 && activeValuesIndexes.count > 0 {
for noiseIndex: Int in possibleNoiseIndexes {
trueArr[noiseIndex] = Float(0)
}
return JSON(["fsr": trueArr])
}
return datas
}
}
|
//
// SelectFuncController.swift
// CosRemote
//
// Created by 郭 又鋼 on 2016/3/2.
// Copyright © 2016年 郭 又鋼. All rights reserved.
//
import Foundation
import UIKit
class SelectFunctionController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
var list = [TitleControler]() ;
class TitleControler {
var title:String
var viewController:UIViewController
var type:Int = 0 ;
init( t:String, v:UIViewController ) {
self.title = t ;
self.viewController = v ;
}
init( t:String, v:UIViewController, type:Int) {
self.title = t ;
self.viewController = v ;
self.type = type ;
}
}
func initList() {
self.list.removeAll() ;
let ledArrayView = self.storyboard?.instantiateViewControllerWithIdentifier("LedArrayController") as! LedArrayController ;
list.append(TitleControler(t: "Led跑馬燈-1", v: ledArrayView, type: 0 ))
list.append(TitleControler(t: "Led跑馬燈-2", v: ledArrayView, type: 1 ))
list.append(TitleControler(t: "單一顏色", v: ledArrayView, type: 2 ))
list.append(TitleControler(t: "火焰顏色控制", v: ledArrayView, type: 3 )) // HSL format
let accview = self.storyboard?.instantiateViewControllerWithIdentifier("AccController") ;
list.append(TitleControler(t: "三軸加速度感測器", v: accview!))
let inmoovbasic = self.storyboard?.instantiateViewControllerWithIdentifier("InmoovBasicController") ;
list.append(TitleControler(t: "機器手臂基本控制", v: inmoovbasic!))
let inmoovAdvance = self.storyboard?.instantiateViewControllerWithIdentifier("InmoovAdvanceController") ;
list.append(TitleControler(t: "機器手臂快速手勢", v: inmoovAdvance!))
}
override func viewDidLoad() {
initList() ;
self.tableView.delegate = self ;
self.tableView.dataSource = self ;
}
override func viewDidAppear(animated: Bool) {
self.navigationItem.title = "功能"
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.list.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let item = self.list[ indexPath.item ]
if let ledarray = item.viewController as? LedArrayController {
ledarray.naviTitle = item.title ;
ledarray.type = item.type ;
}
self.navigationController?.pushViewController(item.viewController, animated: true) ;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let item = self.list[ indexPath.item ]
let cell = tableView.dequeueReusableCellWithIdentifier("SelectFuncCell") as! SelectFuncCell
cell.lbTitle.text = item.title
return cell ;
}
} |
//
// BlockPadding.swift
// SwiftUIKit
//
// Created by Andrey Zonov on 13.12.2020.
//
import UIKit
public protocol BlockPadding: BlockModifying {}
extension BlockPadding {
public func padding(insets: UIEdgeInsets) -> Self {
var Block = self
Block.modifiers.padding = insets
return Block
}
public func padding(_ padding: CGFloat) -> Self {
return self.padding(insets: UIEdgeInsets(top: padding, left: padding, bottom: padding, right: padding))
}
public func padding(h: CGFloat, v: CGFloat) -> Self {
return self.padding(insets: UIEdgeInsets(top: v, left: h, bottom: v, right: h))
}
public func padding(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat) -> Self {
return self.padding(insets: UIEdgeInsets(top: top, left: left, bottom: bottom, right: right))
}
}
|
//
// FieldViewModel.swift
// Assignment
//
// Created by ankita khare on 23/09/21.
//
import Foundation
// FieldViewModel
protocol VSFieldViewModel {
var title: String { get}
var errorMessage: String { get }
// Observables
var value: Variable<String> { get set }
var errorValue: Variable<String?> { get}
// Validation
func validate() -> Bool
}
extension VSFieldViewModel {
func validateSize(_ value: String, size: (min:Int, max:Int)) -> Bool {
return (size.min...size.max).contains(value.count)
}
func validateString(_ value: String?, pattern: String) -> Bool {
let test = NSPredicate(format:"SELF MATCHES %@", pattern)
return test.evaluate(with: value)
}
}
|
//
// MemeCollectionViewCell.swift
// MemeMe
//
// Created by Dustin Howell on 2/20/17.
// Copyright © 2017 Dustin Howell. All rights reserved.
//
import UIKit
class MemeCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var memeImage: UIImageView!
}
|
//
// LogIn.swift
// Museify
//
// Created by Aron Korsunsky on 2/18/20.
// Copyright © 2020 Ethan Kopf. All rights reserved.
//
import Foundation
import Firebase
import FirebaseAuth
import Combine
import SwiftUI
struct LogIn: View {
@State var email: String = ""
@State var password: String = ""
@State var error: String = ""
@State var didItWork: Bool = false
@EnvironmentObject var auth: Authentication
func signIn() {
self.error = ""
auth.signIn(email: email, password: password) { (result, error) in
if let error = error {
self.error = error.localizedDescription
} else {
// self.email = ""
// self.password = ""
self.didItWork = true
}
}
}
var body: some View {
VStack {
Text("Sign in as an existing user:")
.font(.custom("Averia-Bold", size: 24))
VStack {
HStack {
Text("Email:")
TextField("Enter email", text: $email)
}
HStack{
Text("Password:")
TextField("Enter password", text: $password)
}
}.frame(width: 350)
NavigationLink(destination: ContentView(username: email).navigationBarBackButtonHidden(true), isActive: $didItWork) {
Button(action: self.signIn) {
Text("Sign in")
}
}
if error != "" {
Text("There was an error logging in.").foregroundColor(.red)
}
Spacer()
}.font(.custom("Averia-Regular", size: 18))
}
}
struct LogIn_Previews: PreviewProvider {
static var previews: some View {
LogIn()
}
}
|
//
// DatabaseService.swift
// CU Events v1.0
//
// Created by Mahmoud Aljarrash on 2/24/18.
// Copyright © 2018 Mahmoud Aljarrash. All rights reserved.
//
import Foundation
import Firebase
import CodableFirebase
class DatabaseService
{
static let shared = DatabaseService()
private init() {}
let eventsReference = Database.database().reference().child("production").child("events")
let storageReference = Storage.storage().reference()
// this function return empty array. required further troubleshooting
func getEvents() -> [Event]
{
var events = [Event]()
self.eventsReference.observeSingleEvent(of: .value, with: { (snapshot) in
for e in snapshot.children.allObjects as! [DataSnapshot]
{
guard let value = e.value else {return}
do
{
let event = try FirebaseDecoder().decode(Event.self, from: value)
print(event)
events.append(event)
}
catch let error
{
print(error)
}
}
})
print("getEvents() -> ",events)
return events
}
}
|
import AVFoundation
class PreloadedAVPlayer: AVPlayer {
init(url: URL, readyToPlay: @escaping () -> Void) {
super.init()
let asset = AVAsset(url: url)
let keys: [String] = ["playable"]
asset.loadValuesAsynchronously(forKeys: keys) { [weak self] in
DispatchQueue.main.async {
var error: NSError? = nil
let status = asset.statusOfValue(forKey: "playable", error: &error)
if status == .loaded {
let playerItem = AVPlayerItem(asset: asset)
self?.replaceCurrentItem(with: playerItem)
readyToPlay()
}
}
}
}
override init() {
let defaultURL = Bundle.main.url(forResource: "talkingtoamachine", withExtension: "mov")!
super.init()
self.replaceCurrentItem(with: AVPlayerItem(url: defaultURL))
}
}
|
//
// Caching.swift
// MoviesDB
//
// Created by Mohamed Oshiba on 2/21/19.
//
import Foundation
final class Caching {
private let memory = NSCache<NSString, NSData>()
private let diskPath: URL
var pathComponent:String = "Movies"
private let fileManager: FileManager
private let queue = DispatchQueue(label: "Movies")
init(fileManager: FileManager = FileManager.default) {
self.fileManager = fileManager
do {
let documentDirectory = try fileManager.url (
for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)
diskPath = documentDirectory.appendingPathComponent(pathComponent)
try createDirectoryIfNeeded()
} catch {
fatalError()
}
}
func save(data: Data, key: String, completion: (() -> Void)? = nil) {
let key = key.MD5
queue.async {
self.memory.setObject(data as NSData, forKey: key! as NSString)
do {
try data.write(to: self.filePath(key: key!))
completion?()
} catch {
print(error)
}
}
}
func load(key: String, completion: @escaping (Data?) -> Void) {
let key = key.MD5
queue.async {
if let data = self.memory.object(forKey: key! as NSString) {
completion(data as Data)
return
}
if let data = try? Data(contentsOf: self.filePath(key: key!)) {
self.memory.setObject(data as NSData, forKey: key! as NSString)
completion(data)
return
}
completion(nil)
}
}
private func filePath(key: String) -> URL {
return diskPath.appendingPathComponent(key)
}
private func createDirectoryIfNeeded() throws {
if !fileManager.fileExists(atPath: diskPath.path) {
try fileManager.createDirectory(at: diskPath, withIntermediateDirectories: false, attributes: nil)
}
}
/// Clear all items in memory and disk cache
func clear() throws {
memory.removeAllObjects()
try fileManager.removeItem(at: diskPath)
try createDirectoryIfNeeded()
}
}
|
//
// DetailViewController.swift
// MyMovie2
//
// Created by Mac on 2015. 11. 14..
// Copyright © 2015년 Mac. All rights reserved.
//
import UIKit
// 웹뷰를 내비게이션바 영역까지 전체를 덮어야 함.
// 호핀에서 반응형 웹페이지 제공
class DetailViewController : UIViewController {
@IBOutlet var naviBar: UINavigationItem!
@IBOutlet var wv: UIWebView!
// 목록에서 넘겨주는 영화 데이터를 받을 변수
var mvo : MovieVO? = nil
override func viewDidLoad() {
// 내비게이션 바의 타이틀에 영화명 출력
self.naviBar.title = self.mvo?.title
// 웹 뷰에 페이지를 출력
let req = NSURLRequest(URL: NSURL(string: (self.mvo?.detail)!)!)
self.wv.loadRequest(req)
}
}
|
import Foundation
enum carCommand: String { //команды запуска/остановки оборудования
case start, stop
}
protocol Car {
var model: String { get }
var fuelQty: UInt { get set } //количество топлива в баке
var engRun: Bool { get set } //состояние запуска двигателя
func carLoad(load: UInt) -> UInt
//определить метод загрузки автомобиля чем-либо в соответвии с его классом
}
extension Car {
mutating func fuelLoad(fuel: UInt) -> UInt { //заправка топливом
fuelQty += fuel
print ("\(model): заправлено \(fuel) л, всего в баке \(fuelQty) л")
return fuelQty
}
mutating func engine(command: carCommand) { //запуск/остановка двигателя
switch command {
case .start:
if engRun == true {
print("\(model): двигатель уже запущен")
} else {
engRun = true
print("\(model): двигатель запущен")
}
case .stop:
if engRun == false {
print("\(model): двигатель уже остановлен")
} else {
engRun = false
print("\(model): двигатель остановлен")
}
}
}
}
class Bus: Car { //пассажирский автобус
var model: String
var fuelQty: UInt
var engRun: Bool
let seatNum: UInt //количество мест для пассажиров
var passNum: UInt //количество пассажиров
func carLoad(load: UInt) -> UInt { //определение метода, объявленного в протоколе
if (seatNum - passNum) >= load {
passNum += load
print("\(model): занято \(passNum) мест для пассажиров из \(seatNum)")
} else {
print("\(model): недостаточно мест для пассажиров")
}
return passNum
}
func loadLevel() -> Int { //уровень загрузки салона в %%
return Int(round(Float(passNum) / Float(seatNum) * 100))
}
init(model: String, fuelQty: UInt, engRun: Bool, seatNum: UInt, passNum: UInt) {
self.model = model
self.fuelQty = fuelQty
self.engRun = engRun
self.seatNum = seatNum
self.passNum = passNum
}
}
extension Bus: CustomStringConvertible {
var description: String {
return "\(model): топливо \(fuelQty) л., пассажиров \(passNum) (\(loadLevel())%)"
}
}
class Truck: Car { //грузовой автомобиль
var model: String
var fuelQty: UInt
var engRun: Bool
var maxLoad: UInt //грузоподъемность, кг
var currentLoad: UInt //текущая загрузка кузова, кг
func carLoad(load: UInt) -> UInt { //определение метода, объявленного в протоколе
if (maxLoad - currentLoad) >= load {
currentLoad += load
print("\(model): загружено \(currentLoad) кг из \(maxLoad) возможных")
} else {
print("\(model): превышение максимальной загрузки")
}
return currentLoad
}
func loadLevel() -> Int { //уровень загрузки кузова в %%
return Int(round(Float(currentLoad) / Float(maxLoad) * 100))
}
init(model: String, fuelQty: UInt, engRun: Bool, maxLoad: UInt, currentLoad: UInt) {
self.model = model
self.fuelQty = fuelQty
self.engRun = engRun
self.maxLoad = maxLoad
self.currentLoad = currentLoad
}
}
extension Truck: CustomStringConvertible {
var description: String {
return "\(model): топливо \(fuelQty) л., загрузка \(currentLoad) кг (\(loadLevel())%)"
}
}
var kia = Bus(model: "Kia Grandbird", fuelQty: 10, engRun: false, seatNum: 45, passNum: 0)
var volvo = Truck(model: "Volvo FHX 6x4", fuelQty: 50, engRun: false, maxLoad: 30000, currentLoad: 0)
print (kia)
kia.fuelLoad(fuel: 100)
kia.fuelLoad(fuel: 50)
kia.engine(command: .start)
kia.engine(command: .stop)
kia.carLoad(load: 20)
kia.carLoad(load: 15)
kia.carLoad(load: 20)
print (kia)
print ("")
print (volvo)
volvo.fuelLoad(fuel: 100)
volvo.fuelLoad(fuel: 200)
volvo.engine(command: .start)
volvo.engine(command: .stop)
volvo.carLoad(load: 15000)
volvo.carLoad(load: 20000)
print (volvo)
|
//
// MainVC.swift
// TemplateSwiftAPP
//
// Created by wenhua yu on 2018/3/28.
// Copyright © 2018年 wenhua yu. All rights reserved.
//
import Foundation
import UIKit
class MainVC: BaseLoadTC {
override func viewDidLoad() {
super.viewDidLoad();
self.rightTitle(title: "登录")
self.leftTitle(title: "新主题")
LoginNotify.sharedInstance.addLoginObserver(target: self, selector: #selector(loginSuccess))
LoginNotify.sharedInstance.addLogoutObserver(target: self, selector: #selector(logoutSuccess))
self.emptyView.emptyViewType = EmptyViewType.EmptyViewType_NoNavAndTab
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
/// 通知相关
@objc func loginSuccess(notify: Notification) -> Void {
self.rightTitle(title: "个人信息")
}
@objc func logoutSuccess(notify: Notification) -> Void {
self.rightTitle(title: "登录")
}
// MAKR: - 加载数据
override func queryData() -> Array<Any>? {
let api = Topic_Get.init(offset: offset, limit: limit)
api.call(async: true)
return api.dataSource
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: TopicCell = TopicCell.tcell(tableView: tableView, reuse: true) as! TopicCell
let topic = self.dataSource![indexPath.row] as! Topic
cell.showIndicator(flag: true)
cell.updateTopic(topic: topic)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
super.tableView(tableView, didSelectRowAt: indexPath)
self.clickCell(index: indexPath.row)
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return TopicCell.classCellHeight()
}
// 点击 cell 事件
func clickCell(index: Int) {
let topic = self.dataSource![index] as! Topic
let vc = TopicDetailVC()
vc.topicID = topic.topicID!.uuidString
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
}
/// 空页面点击交互
@objc override func emptyTapGesture() -> Void {
self.loadData(more: false)
}
override func goBack() {
if !WorkSpace.sharedInstance.appPreference.isLoginSuccess {
UIHelper.show(title: "请先登录")
return
}
let vc = TopicNewVC()
let nav = UINavigationController.init(rootViewController: vc)
self.navigationController?.present(nav, animated: true, completion: nil)
}
// 进入登录
override func goNext() {
if WorkSpace.sharedInstance.appPreference.isLoginSuccess {
let vc = UserInfoVC()
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
} else {
let vc = LoginVC()
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
|
//
// Film.swift
// mobileTMDB
//
// Created by rushan adelshin on 24.11.2018.
// Copyright © 2018 Eldar Adelshin. All rights reserved.
//
import Foundation
struct Film {
let id: Int
let title: String
let vote_average: String
let poster_path: String
let release_date: String
let overview: String
let original_language: String
init (json: [String: Any]) {
id = json["id"] as? Int ?? -1
title = json["title"] as? String ?? ""
vote_average = json["vote_average"] as? String ?? ""
poster_path = json["poster_path"] as? String ?? ""
release_date = json["release_date"] as? String ?? ""
overview = json["overview"] as? String ?? ""
original_language = json["original_language"] as? String ?? ""
}
}
|
//
// ViewController.swift
// KeyboardAvoiding
//
// Created by Taof on 11/1/19.
// Copyright © 2019 Taof. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let backgroundImageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "img_bg_doimatkhau"))
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
return imageView
}()
private let oldPassWordTextField: UITextField = {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.background = UIImage(named: "txt_pass_gv")
textField.borderStyle = .none
textField.isSecureTextEntry = true
textField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 56))
textField.rightView = UIView(frame: CGRect(x: 0, y: 0, width: 16, height: 56))
textField.leftViewMode = UITextField.ViewMode.always
textField.rightViewMode = UITextField.ViewMode.always
textField.layer.borderColor = UIColor.lightGray.cgColor
textField.layer.borderWidth = 0.5
textField.placeholder = "Mật khẩu cũ"
textField.backgroundColor = UIColor.white
return textField
}()
private let newPasswordTextField: UITextField = {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.background = UIImage(named: "txt_pass_gv")
textField.borderStyle = .none
textField.isSecureTextEntry = true
textField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 56))
textField.rightView = UIView(frame: CGRect(x: 0, y: 0, width: 16, height: 56))
textField.leftViewMode = UITextField.ViewMode.always
textField.rightViewMode = UITextField.ViewMode.always
textField.layer.borderColor = UIColor.lightGray.cgColor
textField.layer.borderWidth = 0.5
textField.placeholder = "Mật khẩu mới"
textField.backgroundColor = UIColor.white
return textField
}()
private let confirmPasswordTextField: UITextField = {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.background = UIImage(named: "txt_pass_gv")
textField.borderStyle = .none
textField.isSecureTextEntry = true
textField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 56))
textField.rightView = UIView(frame: CGRect(x: 0, y: 0, width: 16, height: 56))
textField.leftViewMode = UITextField.ViewMode.always
textField.rightViewMode = UITextField.ViewMode.always
textField.layer.borderColor = UIColor.lightGray.cgColor
textField.layer.borderWidth = 0.5
textField.placeholder = "Nhập lại mật khẩu"
textField.backgroundColor = UIColor.white
return textField
}()
func setupLayout(){
// Background
view.backgroundColor = UIColor.white
view.addSubview(backgroundImageView)
backgroundImageView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
backgroundImageView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
backgroundImageView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
backgroundImageView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
// Scrollview
let scrollView = TPKeyboardAvoidingScrollView()
view.addSubview(scrollView)
scrollView.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11, *){
scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
}else{
scrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 20.0).isActive = true
}
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
// ContainerView
let containerView = UIView()
scrollView.addSubview(containerView)
containerView.translatesAutoresizingMaskIntoConstraints = false
containerView.rightAnchor.constraint(equalTo: scrollView.rightAnchor).isActive = true
containerView.leftAnchor.constraint(equalTo: scrollView.leftAnchor).isActive = true
containerView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
containerView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 20.0).isActive = true
containerView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
// old, new, confirm password
containerView.addSubview(oldPassWordTextField)
containerView.addSubview(newPasswordTextField)
containerView.addSubview(confirmPasswordTextField)
oldPassWordTextField.widthAnchor.constraint(equalToConstant: 280).isActive = true
oldPassWordTextField.heightAnchor.constraint(equalToConstant: 56).isActive = true
oldPassWordTextField.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 32).isActive = true
oldPassWordTextField.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
newPasswordTextField.widthAnchor.constraint(equalToConstant: 280).isActive = true
newPasswordTextField.heightAnchor.constraint(equalToConstant: 56).isActive = true
newPasswordTextField.topAnchor.constraint(equalTo: oldPassWordTextField.bottomAnchor, constant: 256).isActive = true
newPasswordTextField.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
confirmPasswordTextField.widthAnchor.constraint(equalToConstant: 280).isActive = true
confirmPasswordTextField.heightAnchor.constraint(equalToConstant: 56).isActive = true
confirmPasswordTextField.topAnchor.constraint(equalTo: newPasswordTextField.bottomAnchor, constant: 256).isActive = true
confirmPasswordTextField.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
confirmPasswordTextField.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -16).isActive = true
}
override func viewDidLoad() {
super.viewDidLoad()
setupLayout()
oldPassWordTextField.delegate = self
newPasswordTextField.delegate = self
confirmPasswordTextField.delegate = self
oldPassWordTextField.becomeFirstResponder()
setToolBar()
}
func setToolBar(){
//khởi tạo toolBar
let toolbar:UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 30))
// tạo một khoảng trắng (flexible) - tự động dãn theo các thành phần cố định
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneBtn: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(doneButtonAction))
toolbar.setItems([flexSpace, doneBtn], animated: false)
toolbar.sizeToFit()
//setting toolbar as inputAccessoryView
self.confirmPasswordTextField.inputAccessoryView = toolbar
}
@objc func doneButtonAction() {
self.view.endEditing(true)
}
}
extension ViewController: UITextFieldDelegate{
// func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
//
// return true
// }
//
// func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// if textField == oldPassWordTextField {
// newPasswordTextField.becomeFirstResponder()
// }else if textField == newPasswordTextField {
// confirmPasswordTextField.becomeFirstResponder()
// }else{
// self.view.endEditing(true)
// }
// return true
// }
// return fasle để không cho phép chỉnh sửa
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return true
}
// trạng thái phản hồi đầu tiên
func textFieldDidBeginEditing(_ textField: UITextField) {
print("textFieldDidBeginEditing")
}
// return true để cho phép chỉnh sửa dừng lại và từ bỏ trạng thái phản hồi đầu tiên
// return false để không cho phép phiên chỉnh sửa kết thúc
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return true
}
// có thể được gọi nếu bị ép buộc ngay cả khi shouldEndEditing return false hoặc kết thúc chỉnh sửa
func textFieldDidEndEditing(_ textField: UITextField) {
print("textFieldDidEndEditing")
}
// nếu được gọi, hàm này sẽ xử lý thay hàm textFieldDidEndEditing
func textFieldDidEndEditing(_ textField: UITextField, reason: UITextField.DidEndEditingReason) {
print("textFieldDidEndEditing and reason")
}
// return false để không thay đổi text
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let text = textField.text,
let textRange = Range(range, in: text) {
let updatedText = text.replacingCharacters(in: textRange, with: string)
print(updatedText)
// chỉ nhập 10 kí tự
if updatedText.count > 10 {
return false
}
}
return true
}
// được gọi khi nhấn nút xoá
// return false để bỏ qua
func textFieldShouldClear(_ textField: UITextField) -> Bool {
return false
}
// được gọi khi nhấn phím RETURN
// return false để bỏ qua
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return false
}
}
|
//
// Base.swift
// Scanner
//
// Created by Jaden Geller on 10/23/15.
// Copyright © 2015 Jaden Geller. All rights reserved.
//
import Parsley
import Foundation
import Spork
/**
Scan the string and initialize the variables in the pattern.
- Parameter pattern: The pattern to match.
*/
extension String {
func scan(pattern: CompoundScanPattern) -> Bool {
return pattern.match(ParseState(forkableGenerator: characters.generate()))
}
}
/**
Scan a string from the standard input and initialize the variables in the pattern.
- Parameter pattern: The pattern to match.
*/
func scan(pattern: CompoundScanPattern) -> Bool {
let stdin = NSFileHandle.fileHandleWithStandardInput()
guard var inputString = NSString(data: stdin.availableData, encoding: NSUTF8StringEncoding) as String? else { return false }
inputString.removeAtIndex(inputString.endIndex.predecessor()) // Remove new line character
return inputString.scan(pattern)
}
public protocol ScanInitializable {
static var scanner: Parser<Character, Self> { get }
}
/// A value that can be initialized by scanning.
public class Scannable<Value: ScanInitializable> {
public required init() { }
/**
The scanned value.
It is illegal to access this value unless it is used in a successful
call to scan.
*/
var value: Value!
private func match(stream: ParseState<Character>) -> Bool {
do {
try self.value = Value.scanner.parse(stream)
return true
} catch {
return false
}
}
}
public struct CompoundScanPattern: StringInterpolationConvertible, StringLiteralConvertible {
private let matchers: [ParseState<Character> -> Bool]
public init(stringLiteral value: String) {
matchers = [{ stream in
do {
try string(value).parse(stream)
return true
} catch {
return false
}
}]
}
public init(unicodeScalarLiteral value: String) {
self.init(stringLiteral: value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(stringLiteral: value)
}
private func match(stream: ParseState<Character>) -> Bool {
for matcher in matchers {
guard matcher(stream) else { return false }
}
do {
try terminating(none()).parse(stream)
return true
} catch {
return false
}
}
public init(stringInterpolation strings: CompoundScanPattern...) {
matchers = strings.map{ $0.matchers }.reduce([], combine: +)
}
public init<M: ScanInitializable>(stringInterpolationSegment expr: Scannable<M>) {
matchers = [expr.match]
}
public init(stringInterpolationSegment expr: String) {
self.init(stringLiteral: expr)
}
public init<T>(stringInterpolationSegment expr: T) {
fatalError("CompoundScanPattern can only be constructed with `Match` type and `MatchVerifyable` types.")
}
}
|
//
// LocationStorage.swift
// Breeze
//
// Created by Alex Littlejohn on 27/04/2020.
// Copyright © 2020 zero. All rights reserved.
//
import Foundation
struct SavedLocation: Hashable, Codable {
let id: String
let name: String
let coord: Coordinates
static let empty = SavedLocation(id: "", name: "", coord: Coordinates(lat: 0, lon: 0))
}
class LocationStorage {
static let shared = LocationStorage()
private(set) var savedLocations: [SavedLocation]
private let defaults = UserDefaults.standard
private let storageKey = "SavedLocations"
init() {
guard let data = defaults.data(forKey: storageKey),
let decoded = try? PropertyListDecoder().decode([SavedLocation].self, from: data) else {
savedLocations = []
return
}
savedLocations = decoded
}
func add(location: SavedLocation) {
guard !savedLocations.contains(location) else { return }
savedLocations.append(location)
sync()
}
func remove(location: SavedLocation) {
guard let index = savedLocations.firstIndex(of: location) else { return }
savedLocations.remove(at: index)
sync()
}
func sync() {
guard let data = try? PropertyListEncoder().encode(savedLocations) else { return }
defaults.set(data, forKey: storageKey)
}
func getAllLocationsFromCache() {
guard let data = defaults.data(forKey: storageKey),
let decoded = try? PropertyListDecoder().decode([SavedLocation].self, from: data) else {
self.savedLocations = []
return
}
self.savedLocations = decoded
}
deinit {
sync()
}
}
|
//
// Sweather.swift
//
// Created by Heiko Dreyer on 08/12/14.
// Copyright (c) 2014 boxedfolder.com. All rights reserved.
//
import Foundation
import CoreLocation
extension String {
func replace(_ string:String, replacement:String) -> String {
return self.replacingOccurrences(of: string,
with: replacement,
options: NSString.CompareOptions.literal,
range: nil)
}
func replaceWhitespace() -> String {
return self.replace(" ", replacement: "+")
}
}
open class Sweather {
public enum TemperatureFormat: String {
case Celsius = "metric"
case Fahrenheit = "imperial"
}
public enum Result {
case success(URLResponse?, NSDictionary?)
case Error(URLResponse?, NSError?)
public func data() -> NSDictionary? {
switch self {
case .success(_, let dictionary):
return dictionary
case .Error(_, _):
return nil
}
}
public func response() -> URLResponse? {
switch self {
case .success(let response, _):
return response
case .Error(let response, _):
return response
}
}
public func error() -> NSError? {
switch self {
case .success(_, _):
return nil
case .Error(_, let error):
return error
}
}
}
open var apiKey: String
open var apiVersion: String
open var language: String
open var temperatureFormat: TemperatureFormat
fileprivate struct Const {
static let basePath = "http://api.openweathermap.org/data/"
}
// MARK: -
// MARK: Initialization
public convenience init(apiKey: String) {
self.init(apiKey: apiKey, language: "en", temperatureFormat: .Fahrenheit, apiVersion: "2.5")
}
public convenience init(apiKey: String, temperatureFormat: TemperatureFormat) {
self.init(apiKey: apiKey, language: "en", temperatureFormat: temperatureFormat, apiVersion: "2.5")
}
public convenience init(apiKey: String, language: String, temperatureFormat: TemperatureFormat) {
self.init(apiKey: apiKey, language: language, temperatureFormat: temperatureFormat, apiVersion: "2.5")
}
public init(apiKey: String, language: String, temperatureFormat: TemperatureFormat, apiVersion: String) {
self.apiKey = apiKey
self.temperatureFormat = temperatureFormat
self.apiVersion = apiVersion
self.language = language
}
// MARK: -
// MARK: Retrieving current weather data
open func currentWeather(_ cityName: String, callback: @escaping (Result) -> ()) {
call("/weather?q=\(cityName.replaceWhitespace())", callback: callback)
}
open func currentWeather(_ coordinate: CLLocationCoordinate2D, callback: @escaping (Result) -> ()) {
let coordinateString = "lat=\(coordinate.latitude)&lon=\(coordinate.longitude)"
call("/weather?\(coordinateString)", callback: callback)
}
open func currentWeather(_ cityId: Int, callback: @escaping (Result) -> ()) {
call("/weather?id=\(cityId)", callback: callback)
}
// MARK: -
// MARK: Retrieving daily forecast
open func dailyForecast(_ cityName: String, callback: @escaping (Result) -> ()) {
call("/forecast/daily?q=\(cityName.replaceWhitespace())", callback: callback)
}
open func dailyForecast(_ coordinate: CLLocationCoordinate2D, callback: @escaping (Result) -> ()) {
call("/forecast/daily?lat=\(coordinate.latitude)&lon=\(coordinate.longitude)", callback: callback)
}
open func dailyForecast(_ cityId: Int, callback: @escaping (Result) -> ()) {
call("/forecast/daily?id=\(cityId)", callback: callback)
}
// MARK: -
// MARK: Retrieving forecast
open func forecast(_ cityName: String, callback: @escaping (Result) -> ()) {
call("/forecast?q=\(cityName.replaceWhitespace())", callback: callback)
}
open func forecast(_ coordinate: CLLocationCoordinate2D, callback:@escaping (Result) -> ()) {
call("/forecast?lat=\(coordinate.latitude)&lon=\(coordinate.longitude)", callback: callback)
}
open func forecast(_ cityId: Int, callback: @escaping (Result) ->()) {
call("/forecast?id=\(cityId)", callback: callback)
}
// MARK: -
// MARK: Retrieving city
open func findCity(_ cityName: String, callback: @escaping (Result) -> ()) {
call("/find?q=\(cityName.replaceWhitespace())", callback: callback)
}
open func findCity(_ coordinate: CLLocationCoordinate2D, callback: @escaping (Result) -> ()) {
call("/find?lat=\(coordinate.latitude)&lon=\(coordinate.longitude)", callback: callback)
}
// MARK: -
// MARK: Call the api
fileprivate func call(_ method: String, callback: @escaping (Result) -> ()) {
let url = Const.basePath + apiVersion + method + "&APPID=\(apiKey)&lang=\(language)&units=\(temperatureFormat.rawValue)"
let request = URLRequest(url: URL(string: url)!)
let currentQueue = OperationQueue.current
let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in
var error: NSError? = error as NSError?
var dictionary: NSDictionary?
if let data = data {
do {
dictionary = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? NSDictionary
} catch let e as NSError {
error = e
}
}
currentQueue?.addOperation {
var result = Result.success(response, dictionary)
if error != nil {
result = Result.Error(response, error)
}
callback(result)
}
})
task.resume()
}
}
|
//
// HomeView.swift
// UnsplashedGallery
//
// Created by Jasjeev on 8/11/21.
//
import SwiftUI
import URLImage
import PopupView
struct HomeView: View {
@EnvironmentObject var viewModel: UnsplashedViewModel
@State private var showingSheet = false
var body: some View {
GeometryReader { geo in
ZStack {
VStack {
Group {
Text("ACV Photo Challenge")
.font(.system(size: 17))
.fontWeight(.medium)
.padding([.top, .bottom], 10)
HStack{
Group{
Image(systemName: "magnifyingglass")
.padding([.leading, .trailing], 8)
.foregroundColor(imageGray)
TextField("Seach", text: $viewModel.searchText, onEditingChanged: { (changed) in
print("onEditingChanged - \(changed)")
viewModel.executeSearch()
}) {
print("onCommit")
viewModel.executeSearch()
}
.font(.system(size: 17))
.foregroundColor(searchGray)
Image(systemName: "mic.fill")
.padding([.leading, .trailing], 8)
.foregroundColor(imageGray)
.onTapGesture {
viewModel.speechRecognizer.record(to: $viewModel.transcript)
viewModel.beginVoice()
}
}.padding([.top, .bottom], 10)
.frame(minHeight: 36, maxHeight: 36)
}.background(lightGrayOpaque)
.cornerRadius(10)
// show no result icon
if(viewModel.images.count < 1) {
HStack(alignment: .center) {
Spacer()
VStack(alignment: .center) {
Spacer()
Image(systemName: "magnifyingglass.circle.fill")
.resizable()
.clipped()
.frame(width: CGFloat(200.0), height: CGFloat(200.0))
.foregroundColor(imageGray)
.padding(10)
Text("No Images found for this search.")
Text("Try a different search.")
Spacer()
}
Spacer()
}
}
else {
ScrollView {
LazyVStack(spacing: 20) {
ForEach(viewModel.images) { cardImage in
CardView(cardImage: cardImage, width: geo.size.width)
}
}
}.padding(.top, 10)
}
}
}
}.popup(isPresented: $viewModel.speechPopup) {
VStack() {
if(viewModel.transcript.count < 1) {
Text("Say something...")
.frame(width: geo.size.width - CGFloat(100.0), height: 60)
.foregroundColor(Color.yellow)
}
else {
Text(viewModel.transcript)
.frame(width: geo.size.width - CGFloat(100.0), height: 60)
.foregroundColor(Color.white)
}
Button("Done", action: viewModel.voiceComplete)
.padding([.bottom], 20)
}
.background(Color.black)
.cornerRadius(30.0)
}
}
.padding([.leading, .trailing], 15)
.sheet(isPresented: $viewModel.showingSheet) {
SheetView().environmentObject(viewModel)
}
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
HomeView()
}
}
|
//
// EventTitleCell.swift
// CalenderPOC
//
// Created by Shubhakeerti on 29/03/18.
// Copyright © 2018 Shubhakeerti. All rights reserved.
//
import UIKit
class EventTitleCell: UITableViewCell {
@IBOutlet weak var titleTextField: UITextField!
var returnCallBack: ((String) -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func configureCell(title: String, completion: ((String) -> Void)? = nil) {
self.titleTextField.text = title
self.returnCallBack = completion
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
extension EventTitleCell: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
self.returnCallBack?(self.titleTextField.text ?? "")
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.titleTextField.resignFirstResponder()
return true
}
}
|
//
// ModelCreationVC.swift
// StorageAbstraction
//
// Created by Samvel on 11/24/19.
// Copyright © 2019 Samo. All rights reserved.
//
import UIKit
class ModelCreationVC: UIViewController {
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var lastNameTextField: UITextField!
@IBOutlet weak var tableView: UITableView!
lazy var currentStorageType = StorageManager.currentStorageType
var storageContext: StorageContext!
var data:[Storable] = []
override func viewDidLoad() {
super.viewDidLoad()
switch currentStorageType {
case .realm:
storageContext = RealmStorageContext.shared
case .coreData:
storageContext = CoreDataStorageContext.shared
}
tableView.keyboardDismissMode = .onDrag
refreshList()
}
@IBAction func createBtn(_ sender: Any) {
guard let firstName = firstNameTextField.text, !firstName.isEmpty,
let lastName = lastNameTextField.text, !lastName.isEmpty else {return}
createNewUser(firstName: firstName, lastName: lastName)
refreshList()
clearFields()
}
func clearFields() {
firstNameTextField.text = ""
lastNameTextField.text = ""
}
func refreshList() {
let sort = [Sorted(key: "createdDate", asc: false)]
data = currentStorageType == .realm ? storageContext.fetch(RealmUser.self, sorted: sort)
: storageContext.fetch(CoreDataUser.self, sorted: sort)
tableView.reloadData()
}
func createNewUser(firstName:String, lastName: String) {
switch StorageManager.currentStorageType {
case .realm:
try? storageContext.create(RealmUser.self, completion: { (user) in
guard let user = user as? RealmUser else {return}
user.firstName = firstName
user.lastName = lastName
try? self.storageContext.save(object: user)
})
case .coreData:
try? storageContext.create(CoreDataUser.self, completion: { (user) in
guard let user = user as? CoreDataUser else {return}
user.firstName = firstName
user.lastName = lastName
user.createdDate = Date()
try? self.storageContext.save(object: user)
})
}
}
}
extension ModelCreationVC: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath)
let user = data[indexPath.row] as! UserData
cell.textLabel?.text = user.fullName
return cell
}
func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
return [.init(style: .destructive, title: "Delete", handler: { (action, indexPath) in
try? self.storageContext.delete(object: self.data[indexPath.row])
self.data.remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: .left)
})]
}
}
|
//
// KearningLabel.swift
// CoreML_test
//
// Created by Осина П.М. on 27.02.18.
// Copyright © 2018 Осина П.М. All rights reserved.
//
import Foundation
import UIKit
class KerningLabel: UILabel {
@IBInspectable
var kern: CGFloat = 1 {
didSet {
updateText()
}
}
override var text: String? {
didSet {
updateText()
}
}
private func updateText() {
var resultString: NSAttributedString?
if let text = self.text {
let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(NSAttributedStringKey.kern,
value: kern,
range: NSRange(location: 0, length: attributedString.length))
resultString = attributedString
}
self.attributedText = resultString
}
}
extension KerningLabel {
class func createForNavigationTitle(withFontSize fontSize: CGFloat = 22, kern: CGFloat = 3.8) -> KerningLabel{
let titleLabel = KerningLabel()
titleLabel.numberOfLines = 0
titleLabel.textAlignment = .center
titleLabel.kern = kern
titleLabel.textColor = .black
titleLabel.font = UIFont(name: "SFUIDisplay-Regular", size: fontSize)
return titleLabel
}
}
|
//
// Check.swift
// Splttng
//
// Created by Milo on 8/29/16.
// Copyright © 2016 ar.com.milohualpa. All rights reserved.
//
import Foundation
class Check: Expense {
var amount : NSDecimalNumber
var numberOfPeople : Int
var tip : Tip
init(amount:NSDecimalNumber, numberOfPeople:Int, tip:Tip) {
self.amount = amount
self.numberOfPeople = numberOfPeople
self.tip = tip
}
func calculateTotalPerPerson() -> NSDecimalNumber {
let peopleAmount = NSDecimalNumber.init(value: self.numberOfPeople)
let total = amount.adding(tip.calculate(amount: amount)).dividing(by: peopleAmount)
return total
}
}
|
//
// ScheduleTimer.swift
// TimerKit
//
// Created by Mac on 22/06/2019.
// Copyright © 2019 Ilya Razumov. All rights reserved.
//
import Foundation
open class ScheduleTimer {
private var timer: Timer?
public var sendString: ((String) -> Void)?
public private(set) var time: Int {
get {
let time: Int = StorageHelper.loadObjectForKey(.time) ?? 0
return time
}
set {
StorageHelper.save(newValue, forKey: .time)
}
}
public var viewTime: String {
return timeString(With: time)
}
public var isCounting: Bool {
return time > 0
}
public init() { }
public func start() {
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { [weak self] timer in
guard let `self` = self else { return }
self.time += 1
self.sendString?(self.timeString(With: self.time))
})
}
public func stop() {
timer?.invalidate()
timer = nil
}
public func reset() {
time = 0
timer = nil
}
private func timeString(With interval: Int) -> String {
let hour = interval/3600
let minutes = interval/60 % 60
let second = interval % 60
let string = String(format: "%02i:%02i:%02i", hour, minutes, second)
return string
}
}
|
//
// UIApplication+TopViewController.swift
// WeatherApp
//
// Created by Bartek Poskart on 29/05/2020.
// Copyright © 2020 Bartek Poskart. All rights reserved.
//
import UIKit
extension UIApplication {
var topPadding: CGFloat {
return self.keyWindow?.safeAreaInsets.top ?? 0
}
var bottomPadding: CGFloat {
return self.keyWindow?.safeAreaInsets.bottom ?? 0
}
var topNavBarViewControllers: [UIViewController]? {
return UIApplication.topViewController()?.navigationController?.viewControllers
}
class func topViewController(controller: UIViewController? = AppDelegate.shared.appCoordinator?.window.rootViewController) -> UIViewController? {
if let navigationController = controller as? UINavigationController {
return topViewController(controller: navigationController.visibleViewController)
}
if let tabBarController = controller as? UITabBarController {
return topViewController(controller: tabBarController.selectedViewController)
}
if let presented = controller?.presentedViewController {
return topViewController(controller: presented)
}
return controller
}
class func dismissOpenAlerts(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) {
if let alertController = UIApplication.topViewController() as? UIAlertController {
alertController.dismiss(animated: false, completion: nil)
}
}
}
|
//
// ChatFeaturesView.swift
// ContactTest
//
// Created by CHUN MARTHA on 28/04/2017.
// Copyright © 2017 CHUN MARTHA. All rights reserved.
//
import UIKit
class ChatFeaturesView: UIView {
override func awakeFromNib() {
super.awakeFromNib()
}
}
|
//
// ViewController.swift
// RequestApiEarthQuake
//
// Created by Vu on 4/29/19.
// Copyright © 2019 Vu. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
var dataQuake: [Features] = []
override func viewDidLoad() {
super.viewDidLoad()
DataService.shared.requestApiEarthQuake(compledHander: { (quake) in
self.dataQuake = quake.features
self.tableView.reloadData()
self.tableView.rowHeight = 120
})
// Do any additional setup after loading the view, typically from a nib.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataQuake.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell
cell.magLabel.text = "\(dataQuake[indexPath.row].mag ?? 0)"
cell.placeLabel.text = dataQuake[indexPath.row].place
cell.timeStringLabel.text = dataQuake[indexPath.row].timeString
cell.dateStringLabel.text = dataQuake[indexPath.row].dateString
return cell
}
}
|
//
// AgregarFavoritaViewController.swift
// INSSAFI
//
// Created by Pro Retina on 7/17/18.
// Copyright © 2018 Novacomp. All rights reserved.
//
import UIKit
import LocalAuthentication
class AgregarFavoritaViewController: UIViewController,UIPickerViewDataSource, UIPickerViewDelegate {
typealias JSONStandard = Dictionary<String, Any>
var user: User!
var favorita:JSONStandard!
@IBOutlet weak var cuentaField: UITextField!
var subcuentas = [JSONStandard]()
let tipoCuentas = ["Cuenta Cliente", "IBAN"]
let tipoCuentasTexto = ["Incluya los 17 caracteres", "Incluya los 22 caracteres"]
@IBOutlet weak var subcuentasButton: UIButton!
@IBOutlet weak var tipoCuentaButton: UIButton!
@IBOutlet weak var cuentaView: UIView!
@IBOutlet weak var pickerViewBack: UIView!
@IBOutlet weak var pickerView: UIPickerView!
var tipoPicker = 1
var selectedSubcuenta = 0
var selectedTipoCuenta = 0
@IBOutlet weak var numCuentaLabel: UILabel!
@IBOutlet weak var nombreCuentaLabel: UILabel!
@IBOutlet weak var entidadCuentaLabel: UILabel!
@IBOutlet weak var monedaCuentaLabel: UILabel!
@IBOutlet weak var descripcionCuentaLabel: UILabel!
@IBOutlet weak var agregarHuellaButton: UIButton!
@IBOutlet weak var agregarButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
user = User.getInstance()
cuentaView.isHidden = true
let context = LAContext()
var error: NSError?
if (!context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) || !UserDefaults.standard.bool(forKey: "TransaccionTouchID")) {
agregarHuellaButton.isHidden = true
agregarButton.center = CGPoint(x:cuentaView.center.x, y:agregarButton.center.y)
}
tipoCuentaButton.setTitle(tipoCuentas[selectedTipoCuenta], for: .normal)
obtenerCuentas()
hideKeyboardWhenTappedAround()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if(segue.identifier == "seleccionarCorreoSegue") {
let vc = segue.destination as! SeleccionarCorreoViewController
vc.favorita = favorita
}
}
@IBAction func seleccionarSubcuenta(_ sender: Any) {
tipoPicker = 1
pickerView.reloadAllComponents()
pickerViewBack.isHidden = false
}
@IBAction func seleccionarTipoCuenta(_ sender: Any) {
tipoPicker = 2
pickerView.reloadAllComponents()
pickerViewBack.isHidden = false
}
@IBAction func verificarCuentaAction () {
self.cuentaField.resignFirstResponder()
verificarCuenta()
}
@IBAction func agregarCuentaAction () {
self.cuentaField.resignFirstResponder()
performSegue(withIdentifier: "seleccionarCorreoSegue", sender: nil)
}
@IBAction func agregarCuentaHuellaAction () {
self.cuentaField.resignFirstResponder()
let context = LAContext()
var error: NSError?
if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
let reason = "Valide la acción con su huella"
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason, reply:
{(success, error) in
if success {
self.agregarFavorita(tipo:"B")
}
else {
}
})
}
else {
// Not available
}
}
@IBAction func cancelPickerView(_ sender: Any) {
pickerViewBack.isHidden = true
}
@IBAction func acceptPickerView(_ sender: Any) {
pickerViewBack.isHidden = true
if tipoPicker == 1 {
selectedSubcuenta = pickerView.selectedRow(inComponent: 0)
subcuentasButton.setTitle(subcuentas[selectedSubcuenta]["NC"] as? String, for: .normal)
}
else {
selectedTipoCuenta = pickerView.selectedRow(inComponent: 0)
tipoCuentaButton.setTitle(tipoCuentas[selectedTipoCuenta], for: .normal)
descripcionCuentaLabel.text = tipoCuentasTexto[selectedTipoCuenta]
}
}
func obtenerCuentas() {
let networkReachability = Reachability.forInternetConnection
let networkStatus = networkReachability().currentReachabilityStatus
if (networkStatus() == ReachableViaWiFi || networkStatus() == ReachableViaWWAN) {
let alert = Functions.getLoading("Obteniendo información")
present(alert!, animated: true, completion: obtenerSubcuentas)
}
else {
// Mostramos el error
//[self showAlert:@"Iniciar sesión" withMessage:@"No hay conexión a Internet"];
}
}
func obtenerSubcuentas() {
let url = RequestUtilities.getURL(WS_SERVICE_USUARIO, method: WS_METHOD_TRAER_SUBCUENTAS)
let params = ["CU":user.getSelectedCuenta()!,"NI":user.getUser()!,"TK":user.getToken()!]
let data = ["pConsulta":params]
var dataString = "\(data)"
dataString = dataString.replacingOccurrences(of: "[", with: "{")
dataString = dataString.replacingOccurrences(of: "]", with: "}")
let paramsExtern = ["pJsonString":dataString]
NetworkHandler.getRequest(urlString: url!, data: paramsExtern) { (data) in
self.dismiss(animated: true, completion: nil)
let response = data["TraerSubCuentasResult"] as! String
let dataJson = response.data(using: String.Encoding.utf8)
do {
let dataDictionary = try JSONSerialization.jsonObject(with: dataJson!, options: JSONSerialization.ReadingOptions(rawValue: JSONSerialization.ReadingOptions.RawValue(0))) as! JSONStandard
print(dataDictionary)
let resultado = dataDictionary["Resultado"] as! JSONStandard
let cuentasAux = resultado["Cuentas"] as! [JSONStandard]
for cuenta in cuentasAux {
if(self.user.getSelectedCuenta()! == (cuenta["CU"] as! NSNumber).stringValue) {
self.subcuentas.append(cuenta)
}
}
}
catch {
}
}
}
func verificarCuenta() {
let networkReachability = Reachability.forInternetConnection
let networkStatus = networkReachability().currentReachabilityStatus
if (networkStatus() == ReachableViaWiFi || networkStatus() == ReachableViaWWAN) {
let alert = Functions.getLoading("Obteniendo información")
present(alert!, animated: true, completion: verifyCuenta)
}
else {
// Mostramos el error
//[self showAlert:@"Iniciar sesión" withMessage:@"No hay conexión a Internet"];
}
}
func verifyCuenta() {
let url = RequestUtilities.getURL(WS_SERVICE_USUARIO, method: WS_METHOD_VERIFICAR_FAVORITA)
let params = ["NI":user.getUser()!, "CU":user.getSelectedCuenta()!, "SC":(subcuentas[selectedSubcuenta]["CS"] as! NSNumber).stringValue, "TC":"P","NC":cuentaField.text!, "TK":user.getToken()!]
// EJ: CR40015202946000161798
// CR70015202001142490739
let data = ["pConsulta":params]
var dataString = "\(data)"
dataString = dataString.replacingOccurrences(of: "[", with: "{")
dataString = dataString.replacingOccurrences(of: "]", with: "}")
let paramsExtern = ["pJsonString":dataString]
NetworkHandler.getRequest(urlString: url!, data: paramsExtern) { (data) in
self.dismiss(animated: true, completion: nil)
let response = data["VerificaInformacionCuentaFavResult"] as! String
let dataJson = response.data(using: String.Encoding.utf8)
do {
let dataDictionary = try JSONSerialization.jsonObject(with: dataJson!, options: JSONSerialization.ReadingOptions(rawValue: JSONSerialization.ReadingOptions.RawValue(0))) as! JSONStandard
print(dataDictionary)
let resultado = dataDictionary["Resultado"] as! JSONStandard
if let respuesta = resultado["Respuesta"] as? JSONStandard {
if(String(describing: respuesta["CodMensaje"]!) != "0") {
self.showAlert(title: "", message: respuesta["Mensajes"] as! String)
}
else if let contenido = resultado["Contenido"] as? JSONStandard {
self.favorita = contenido
self.numCuentaLabel.text = contenido["CC"] as? String
self.nombreCuentaLabel.text = (contenido["NO"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines)
self.entidadCuentaLabel.text = contenido["NE"] as? String
self.monedaCuentaLabel.text = contenido["MO"] as? String
self.cuentaView.isHidden = false
}
}
}
catch {
}
}
}
func agregarFavorita(tipo:String) {
let networkReachability = Reachability.forInternetConnection
let networkStatus = networkReachability().currentReachabilityStatus
if (networkStatus() == ReachableViaWiFi || networkStatus() == ReachableViaWWAN) {
let alert = Functions.getLoading("Obteniendo información")
present(alert!, animated: true, completion: {
self.addFavorita(tipo: tipo)
})
}
else {
// Mostramos el error
//[self showAlert:@"Iniciar sesión" withMessage:@"No hay conexión a Internet"];
}
}
func addFavorita(tipo:String) {
let url = RequestUtilities.getURL(WS_SERVICE_USUARIO, method: WS_METHOD_GRABAR_FAVORITA)
var params:JSONStandard!
let moned = monedaCuentaLabel.text! == "Colones" ? "COL" : "DOL"
params = ["NI":user.getUser()!, "CU":user.getSelectedCuenta()!, "TV":tipo, "CC":numCuentaLabel.text!,"NO":nombreCuentaLabel.text!,"MO":moned,"CE":(favorita["CE"] as! NSNumber).stringValue,"CO":"Correo", "TK":user.getToken()!]
if(tipo == "B") {
let format = DateFormatter()
format.dateFormat = "dd/MM/yyyy hh:mm:ss a"
let fecha = format.string(from: Date())
let detallesDispositivo = "Apple " + UIDevice.current.model + " " + UIDevice.current.systemVersion
let DV = ["DI":detallesDispositivo,"FE":fecha]
params = ["NI":user.getUser()!, "CU":user.getSelectedCuenta()!, "TV":tipo, "CC":numCuentaLabel.text!, "IT":favorita["IC"] as! String, "NO":nombreCuentaLabel.text!, "MO":moned,"CE":(favorita["CE"] as! NSNumber).stringValue, "DV":DV, "TK":user.getToken()!]
}
let data = ["pTransaccion":params!]
var dataString = "\(data)"
dataString = dataString.replacingOccurrences(of: "[", with: "{")
dataString = dataString.replacingOccurrences(of: "]", with: "}")
let paramsExtern = ["pJsonString":dataString]
NetworkHandler.getRequest(urlString: url!, data: paramsExtern) { (data) in
self.dismiss(animated: true, completion: nil)
let response = data["GrabarCuentaFavoritaResult"] as! String
let dataJson = response.data(using: String.Encoding.utf8)
do {
let dataDictionary = try JSONSerialization.jsonObject(with: dataJson!, options: JSONSerialization.ReadingOptions(rawValue: JSONSerialization.ReadingOptions.RawValue(0))) as! JSONStandard
print(dataDictionary)
let resultado = dataDictionary["Resultado"] as! JSONStandard
if let respuesta = resultado["Respuesta"] as? JSONStandard {
if(String(describing: respuesta["CodMensaje"]!) != "0") {
self.showAlert(title: "", message: respuesta["Mensajes"] as! String)
}
else {
self.showAlert(title: "Éxito", message: "Cuenta agregada con éxito.")
let alertSuccess = UIAlertController(title: "Éxito", message: respuesta["Mensajes"] as? String, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction (title: "OK", style: .default, handler: { (alert: UIAlertAction!) in
self.navigationController?.popViewController(animated: true)
})
alertSuccess.addAction(okAction)
self.present(alertSuccess, animated: true, completion: nil)
}
}
}
catch {
}
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
var result = 0
if tipoPicker == 1 {
result = subcuentas.count
}
else {
result = tipoCuentas.count
}
return result
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
var result = ""
if tipoPicker == 1 {
let cuenta = subcuentas[row]
result = cuenta["NC"] as! String
}
else {
result = tipoCuentas[row]
}
return result
}
}
|
//
// ProfileCell.swift
// YouthGroup
//
// Created by Adam Zarn on 2/13/18.
// Copyright © 2018 Adam Zarn. All rights reserved.
//
import Foundation
import UIKit
import Firebase
protocol ProfileCellDelegate: class {
func didTapProfileImageView(imageData: Data?)
func didSetProfilePhoto(image: UIImage?)
}
class ProfileCell: UITableViewCell {
@IBOutlet weak var profileImageView: CircleImageView!
@IBOutlet weak var nameLabel: UILabel!
weak var delegate: ProfileCellDelegate?
var imageData: Data?
var cachedImage: UIImage?
override func awakeFromNib() {
super.awakeFromNib()
profileImageView.isUserInteractionEnabled = false
let recognizer = UITapGestureRecognizer(target: self, action: #selector(ProfileCell.profileImageViewTapped(_:)))
profileImageView.addGestureRecognizer(recognizer)
}
@objc func profileImageViewTapped(_ sender: UITapGestureRecognizer) {
delegate?.didTapProfileImageView(imageData: imageData)
}
func setUp(image: UIImage?, user: User?) {
if let user = user {
nameLabel.text = user.displayName
cachedImage = imageCache[user.email!]
}
if let cachedImage = self.cachedImage {
profileImageView.isUserInteractionEnabled = true
profileImageView.image = cachedImage
self.delegate?.didSetProfilePhoto(image: cachedImage)
} else if let image = image {
profileImageView.isUserInteractionEnabled = true
profileImageView.image = image
self.delegate?.didSetProfilePhoto(image: image)
} else {
profileImageView.image = UIImage(named: "Boy")
if let user = user, let email = user.email {
FirebaseClient.shared.getProfilePhoto(email: email, completion: { (data, error) in
if let data = data {
DispatchQueue.global(qos: .background).async {
self.imageData = data
let image = UIImage(data: data)
self.delegate?.didSetProfilePhoto(image: image)
DispatchQueue.main.async {
self.profileImageView.isUserInteractionEnabled = true
self.profileImageView.image = image
imageCache[email] = image
}
}
} else {
self.profileImageView.isUserInteractionEnabled = true
}
})
}
}
}
}
|
//
// SceneTouristSpot.swift
// projetoWWDC20
//
// Created by Gustavo Feliciano Figueiredo on 02/04/20.
// Copyright © 2020 Gustavo Feliciano Figueiredo. All rights reserved.
//
import SpriteKit
import GameplayKit
class SceneTourist: SceneState{
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
return stateClass is SceneNormal.Type
}
override func didEnter(from previousState: GKState?) {
self.sceneGame.character?.isPaused = true
}
override func willExit(to nextState: GKState) {
self.sceneGame.character?.removeAllActions()
}
}
|
import SwiftUI
import SwiftUI
import URLImage
import shared
struct PlaylistView: View {
@ObservedObject var viewModel = PlaylistViewModel()
var body: some View {
switchView()
.navigationTitle(Text("Video Playlist"))
}
}
extension PlaylistView {
func switchView() -> AnyView {
switch viewModel.playlistState.state {
case .initial:
return initialView()
case .doneLoading:
return doneLoadingView()
case .loading:
return loadView()
case .success(let playlist):
return successView(playlist)
case .errorLoading:
return errorView("Error Loading")
case .errorShowing:
return errorView("Error Showing")
}
}
func initialView() -> AnyView {
AnyView(
Text("Initial View")
.onAppear(perform: {
viewModel.accept(intent: .loadList)
})
)
}
func loadView() -> AnyView {
AnyView(Text("Loading"))
}
func doneLoadingView() -> AnyView {
AnyView(
Text("Done Loading")
.onAppear(perform: {
viewModel.accept(intent: .showList)
})
)
}
func successView(_ playlist: Playlist) -> AnyView {
AnyView(
List {
ForEach (playlist.videos) {vid in
NavigationLink(destination: VideoViewer(video: vid)) {
ItemListView(video: vid)
}
}
}.navigationTitle(Text(Greeting().greeting()))
)
}
func errorView(_ message: String) -> AnyView {
AnyView(Text(message))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
PlaylistView()
}
}
extension Video : Identifiable {}
|
//
// PersonalAreaCell.swift
// Carousel
//
// Created by Andrey on 03.05.17.
// Copyright © 2017 Quest. All rights reserved.
//
import UIKit
class PersonalAreaCell: UITableViewCell, UITextFieldDelegate {
@IBOutlet weak var contentTextField: UITextField!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
contentTextField.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.contentTextField.endEditing(true)
return false
}
}
|
//
// SelectionButton.swift
// Metsterios
//
// Created by Chelsea Green on 3/30/16.
// Copyright © 2016 Chelsea Green. All rights reserved.
//
import UIKit
class SelectionButton: UIButton {
override init(frame: CGRect) {
let bg = UIColor(red: 250, green: 250, blue: 250, alpha: 1)
super.init(frame: frame)
super.layer.borderWidth = 1
super.layer.cornerRadius = 2
super.layer.borderColor = lightBlue.CGColor
super.setTitleColor(UIColor.blackColor(), forState: .Selected)
super.setTitleColor(UIColor.lightGrayColor(), forState: .Normal)
super.backgroundColor = bg
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// MemberDetailViewController.swift
// Westeros
//
// Created by Luis Herrera Lillo on 27-10-18.
// Copyright © 2018 Luis Herrera Lillo. All rights reserved.
//
import UIKit
class MemberDetailViewController: UIViewController {
// MARK: - Properties
let model: Person
// Mark - Outlets
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var aliasLabel: UILabel!
@IBOutlet weak var houseLabel: UILabel!
// MARK: - Initialization
init(model: Person) {
// Nos encargamos de nuestras propias propiedades
self.model = model
// llamamos a super
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Mark - Life Cycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Nos damos de alta en las notificaciones
NotificationCenter.default.addObserver(self, selector: #selector(houseDidChange(notification:)), name: .houseDidChangeNotification, object: nil)
// SyncModelWithView
syncModelWithView()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Nos damos de baja en las notificaciones
NotificationCenter.default.removeObserver(self)
}
// MARK: - SyncModelWithView
func syncModelWithView() {
self.nameLabel.text = self.model.name
self.aliasLabel.text = self.model.alias
self.houseLabel.text = self.model.house.name
self.title = self.model.fullName
}
}
// Mark - Notifications
extension MemberDetailViewController {
@objc func houseDidChange(notification: Notification) {
// Nos devolvemos al controlador de la pila anterior en el navigationController
self.navigationController?.popViewController(animated: true)
}
}
|
//
// AddAcquaintanceViewController.swift
// Face-To-Name
//
// Created by John Bales on 4/26/17.
// Copyright © 2017 John T Bales. All rights reserved.
//
import UIKit
import GoogleMobileAds
import AWSMobileHubHelper
import AWSRekognition
import AWSDynamoDB
import AWSS3
class AddAcquaintanceViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var detailsTextField: UITextField!
// @IBOutlet weak var bannerView: GADBannerView!
@IBOutlet weak var faceImageView: UIImageView!
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var doneBarButton: UIBarButtonItem!
var saving = false
override func viewDidLoad() {
super.viewDidLoad()
//Google AdMob
// bannerView.adUnitID = FaceToNameAds.sharedInstance.adUnitID
// bannerView.rootViewController = self
// let gadReqest = FaceToNameAds.sharedInstance.gadRequest
// bannerView.load(gadReqest)
}
override func viewDidAppear(_ animated: Bool) {
//Allow user to sign if in needed
presentSignInViewController()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// Dismiss the picker if the user canceled.
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// The info dictionary may contain multiple representations of the image. You want to use the original.
guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
// Set ImageView to display the selected image.
faceImageView.image = selectedImage
// Dismiss the picker.
dismiss(animated: true, completion: nil)
}
//MARK: Functions
func addAcquaintance(_ faceImage: UIImage) {
//Animation
progressView.setProgress(0, animated: true)
progressView.isHidden = false
Face.addFace(self, nameTextField.text?.trimmingCharacters(in: [" "]) ?? "", detailsTextField.text, faceImage, { (face) -> Void? in
//Success
self.presentationSync {
self.performSegue(withIdentifier: "unwindToAcquaintList", sender: self)
}
return nil
}) { (alertParams) -> Void? in
//Failure
self.alertMessageOkay(alertParams)
//Reset UI
self.progressView.isHidden = true
self.saveStopping()
return nil
}
}
//MARK: Actions
@IBAction func imageTypeSelect(_ sender: UITapGestureRecognizer) {
imageTypeSelect()
}
@IBAction func done(_ sender: UIBarButtonItem) {
if !AWSIdentityManager.default().isLoggedIn {
presentSignInViewController()
}
else if !saving {
//Name Required
//print("Name = \(nameTextField.text ?? "Nil Name Text Field")")
if (nameTextField.text == nil || (nameTextField.text!.trimmingCharacters(in: [" "])) == "") {
self.alertMessageOkay("Name Required", "Please enter a name to remember the person by.")
}
//Photo Required
else if faceImageView.image == nil || faceImageView.image == #imageLiteral(resourceName: "NoPhotoSelected") {
self.alertMessageOkay("Photo Required", "Make sure the image has a clear view of the person's face and no one else's.")
}
else {
//Ensure sequence
saveStarting()
//Start animations
progressView.setProgress(0, animated: true)
//Check if name is already taken
AWSDynamoDBObjectMapper.default().faceNameExists(nameTextField.text!.trimmingCharacters(in: [" "]), { (faceDataExists) -> Void? in
if faceDataExists {
self.alertMessageOkay("Name Taken", "You already have an acquaintance with that name.")
} else {
//Success
//Try to upload Image and add acquaintance
self.addAcquaintance(self.faceImageView.image!)
}
return nil
}, { (alertParams) -> Void? in
//Failure
self.alertMessageOkay(alertParams)
self.saveStopping()
return nil
})
}
} else {
print("Currently saving. Done trigger skipped.")
}
}
func saveStarting() {
saving = true
doneBarButton.isEnabled = false
alertMessageNoCancel("Loading...", "")
}
func saveStopping() {
saving = false
doneBarButton.isEnabled = true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// ProductViewController.swift
// fauxshop-mobile
//
// Created by Derek Zuk on 3/7/18.
// Copyright © 2018 Derek Zuk. All rights reserved.
//
import UIKit
class ProductViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
var products = [Products]()
var product: Products?
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
// Retrieve Products
retrieveProducts()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return products.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as! CustomCollectionViewCell
let priceValue = products[indexPath.row].productsPrice
cell.price.text = String(format: "$%.02f", priceValue)
cell.productDescription.text = products[indexPath.row].productsName
cell.imageView.image = UIImage(named: products[indexPath.row].productsImageMobile)
return cell;
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// handle tap events
print("You selected cell #\(indexPath.item)!")
self.product = products[indexPath.item]
self.performSegue(withIdentifier: "showProductDetail", sender: self)
}
func retrieveProducts() {
let url = URL(string: "http://localhost:8080/api/products")
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print(error ?? "Error encountered printing the error")
return
}
do {
self.products = try JSONDecoder().decode([Products].self, from: data!)
} catch {
print(error)
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}.resume()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "showProductDetail") {
let productDetailViewController = segue.destination as! ProductDetailViewController
productDetailViewController.product = self.product!
}
}
}
|
//
// LoginForm.swift
// Tracker
//
// Created by Nicholas Coffey on 11/6/20.
//
import SwiftUI
struct LoginForm: View {
@State private var email = ""
@State private var password = ""
@State private var showAlert = false
@State private var alertMessage = "ERROR"
@EnvironmentObject var session: SessionStore
func handleSubmit() {
session.signIn(email: email, password: password) { (result, error) in
if let error = error {
alertMessage = error.localizedDescription
showAlert = true
}
}
}
var body: some View {
Form {
Section(header: Text("Email")) {
TextField("Please enter your email", text: $email)
.autocapitalization(/*@START_MENU_TOKEN@*/.none/*@END_MENU_TOKEN@*/)
}
Section(header: Text("Password")) {
SecureField("Please enter your password", text: $password)
}
Button(action: {handleSubmit()}) {
HStack() {
Spacer()
Text("Login")
Spacer()
}
}.alert(isPresented: $showAlert) {
Alert(title: Text("Error"), message: Text(alertMessage), dismissButton: .default(Text("Okay")))
}
}
}
}
struct LoginForm_Previews: PreviewProvider {
static var previews: some View {
LoginForm()
}
}
|
//: [Previous](@previous)
import PlaygroundSupport
import Foundation
import Combine
let urls: [URL] = "... この文字順通りに出力されます"
.map(String.init).compactMap { (parameter) in
var components = URLComponents()
components.scheme = "https"
components.path = "postman-echo.com/get"
components.queryItems = [URLQueryItem(name: parameter, value: nil)]
return components.url
}
struct Postman: Decodable {
var args: [String: String]
}
var stream = ""
let s = urls.compactMap { value in
URLSession.shared.dataTaskPublisher(for: value)
.tryMap { data, response -> Data in
return data
}
.decode(type: Postman.self, decoder: JSONDecoder())
.catch {_ in
Just(Postman(args: [:]))
}
}
.publisher
.flatMap(maxPublishers: .max(1)){$0}
.sink(receiveCompletion: { (c) in
print(stream)
}, receiveValue: { (postman) in
print(postman.args.keys.joined(), terminator: "", to: &stream)
})
extension Collection where Element: Publisher {
func serialize() -> AnyPublisher<Element.Output, Element.Failure>? {
guard let start = self.first else { return nil }
return self.dropFirst().reduce(start.eraseToAnyPublisher()) {
return $0.append($1).eraseToAnyPublisher()
}
}
}
PlaygroundPage.current.needsIndefiniteExecution = true
//: [Next](@next)
|
class Food_menu : Codable{
var store_code : String?
var fm_code : String?
var fm_name : String?
var fm_image : String?
var fm_info : String?
var fm_price : String?
var fm_kcal : String?
var fm_allergy : String?
}
|
//
// FeedTracks.swift
// iOS_Coding_Challenge
//
// Created by Nika Kirkitadze on 2/23/19.
// Copyright © 2019 organization. All rights reserved.
//
import Foundation
struct FeedModel: Codable {
let feed: Feed?
struct Feed: Codable {
let title: String?
let id: String?
let author: Author?
let links: [Link]?
let copyright: String?
let country: String?
let icon: String?
let updated: String?
let results: [Result]?
struct Author: Codable {
let name: String?
let uri: String?
}
struct Link: Codable {
let linkSelf: String?
let alternate: String?
enum CodingKeys: String, CodingKey {
case linkSelf = "self"
case alternate
}
}
struct Result: Codable {
let artistName: String?
let id: String?
let releaseDate: String?
let name: String?
let kind: String?
let copyright: String?
let artistID: String?
let artistURL: String?
let artworkUrl100: String?
let genres: [Genre]?
let url: String?
let contentAdvisoryRating: String?
struct Genre: Codable {
let genreID: String?
let name: String?
let url: String?
enum CodingKeys: String, CodingKey {
case genreID = "genreId"
case name, url
}
}
enum CodingKeys: String, CodingKey {
case artistName, id, releaseDate, name, kind, copyright
case artistID = "artistId"
case artistURL = "artistUrl"
case artworkUrl100, genres, url, contentAdvisoryRating
}
}
}
}
|
//
// Networks.swift
// PayoneerTestApp
//
// Created by Bozidar Kokot on 05.05.21.
//
import Foundation
/// List response with possible payment networks
struct Networks: Decodable {
/// Collection of applicable payment networks that could be used by a customer to complete the payment in scope of this `LIST` session
let applicable: [ApplicableNetwork]
}
|
//
// LiteTableController.swift
// LiteTable
//
// Created by Yaxin Cheng on 2018-10-10.
// Copyright © 2018 Yaxin Cheng. All rights reserved.
//
import Cocoa
class LiteTableController: NSViewController {
let dataSource = (0...50).map { $0 }
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
(view as! LiteTableView).register(nib: NSNib(nibNamed: "TestCell", bundle: .main)!, withIdentifier: .test)
(view as! LiteTableView).liteDataSource = self
(view as! LiteTableView).liteDelegate = self
}
override func viewDidAppear() {
super.viewDidAppear()
(view as! LiteTableView).reload()
}
}
extension LiteTableController: LiteTableDelegate, LiteTableDataSource {
func cellReuseThreshold(_ tableView: LiteTableView) -> Int {
return 3
}
func numberOfCells(_ tableView: LiteTableView) -> Int {
return dataSource.count
}
func cellHeight(_ tableView: LiteTableView) -> CGFloat {
return 30
}
func prepareCell(_ tableView: LiteTableView, at index: Int) -> LiteTableCell {
let cell = tableView.dequeueCell(withIdentifier: .test) as! TestCell
let data = dataSource[index]
cell.numberLabel.stringValue = "\(data)"
return cell
}
}
|
//
// Copyright © 2021 Tasuku Tozawa. All rights reserved.
//
import UIKit
public protocol ThumbnailLoadObserver: AnyObject {
func didStartLoading(_ request: ThumbnailRequest)
func didFailedToLoad(_ request: ThumbnailRequest)
func didSuccessToLoad(_ request: ThumbnailRequest, image: UIImage)
}
|
//
// PantallaInicio.swift
// Kuali
//
// Created by Servio Tulio Reyes Castillo on 16/11/18.
// Copyright © 2018 Andrea . All rights reserved.
//
import UIKit
import Firebase
class PantallaInicio: UIViewController {
var database: DatabaseReference!
@IBOutlet weak var indicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
database = Database.database().reference()
loadPreferences()
let transform = CGAffineTransform(scaleX: 3, y: 3)
indicator.transform = transform
indicator.startAnimating()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
cargarElementos()
}
func cargarElementos() {
//self.productos.removeAll()
self.database.child("Productos").observeSingleEvent(of: .value) { (snapshot) in
/*self.productos = (snapshot.value as! [DataSnapshot])
print("Productos \(self.productos.count)")
print("Ejemplo \(self.productos[1].key)")
self.collectionView.reloadData()*/
for child in snapshot.children{
GeneralInformation.productos.append(child as! DataSnapshot)
}
}
self.database.child("Categorias").observeSingleEvent(of: .value) { (snapshot) in
for child in snapshot.children{
GeneralInformation.categorias.append(child as! DataSnapshot)
}
//self.ordenarProductos()
//self.collectionView.reloadData()
//print("\(self.productos[1].childSnapshot(forPath: "nombre"))")
self.realizarCambio()
}
}
func cargarCategorias() {
//self.productos.removeAll()
self.database.child("Categorias").observeSingleEvent(of: .value) { (snapshot) in
/*self.productos = (snapshot.value as! [DataSnapshot])
print("Productos \(self.productos.count)")
print("Ejemplo \(self.productos[1].key)")
self.collectionView.reloadData()*/
for child in snapshot.children{
GeneralInformation.categorias.append(child as! DataSnapshot)
}
//self.ordenarProductos()
//self.collectionView.reloadData()
//print("\(self.productos[1].childSnapshot(forPath: "nombre"))")
}
}
func realizarCambio(){
self.performSegue(withIdentifier: "CambioAProductos", sender: self)
}
func loadPreferences(){
let preferences = UserDefaults.standard
let value = preferences.array(forKey: "Kuali")
if value != nil{
GeneralInformation.favoritos = (value as! [Int])
} else {
GeneralInformation.favoritos = []
}
//label.text = "\(String(describing: ViewController.prefSet))"
//ViewController.prefSet.append(2)
}
/*
// 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.
}
*/
}
|
//: Playground - noun: a place where people can play
import UIKit
func isIsomorphic(s: String, t: String) -> Bool {
if s == t {
return true
}else if s.count != t.count {
return false
}else{
let arr1 = s.map{String($0)}
let arr2 = t.map{String($0)}
var dict = [String : String]()
for i in 0..<arr1.count {
if let val = dict[arr1[i]]{
if val != arr2[i]{
return false
}
}else{
dict[arr1[i]] = arr2[i]
}
}
}
return true
}
let result = isIsomorphic(s: "aab", t: "xxz")
print(result)
let result1 = isIsomorphic(s: "aab", t: "xyz")
print(result1)
|
// Copyright (c) 2020-2022 InSeven Limited
//
// 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 SwiftUI
import BookmarksCore
struct LogInView: View {
@Environment(\.openURL) var openURL
@Environment(\.manager) var manager
@State var username: String = ""
@State var password: String = ""
func submit() {
dispatchPrecondition(condition: .onQueue(.main))
manager.authenticate(username: username, password: password) { result in
switch result {
case .success:
break
case .failure(let error):
DispatchQueue.main.async {
// TODO: Show this error.
print("failed with error \(error)")
}
}
}
}
func createAccount() {
dispatchPrecondition(condition: .onQueue(.main))
guard let url = URL(string: "https://pinboard.in/signup/") else {
return
}
openURL(url)
}
var body: some View {
VStack {
Image("PinboardLogo")
.resizable()
.frame(width: 64, height: 64)
.background(Color.white)
.clipShape(RoundedRectangle(cornerRadius: 6))
Text("Sign in to Pinboard")
.bold()
.frame(maxWidth: .infinity)
Spacer()
Form {
TextField("Username:", text: $username)
SecureField("Password:", text: $password)
.onSubmit(submit)
}
Text("Your username and password are used to access your Pinboard API token and are not stored. You can reset your Pinboard API token anytime from the Pinboard website.")
.multilineTextAlignment(.center)
.font(.footnote)
.foregroundColor(.secondary)
Spacer()
VStack {
Button(action: submit) {
Text("Log In").frame(maxWidth: 300)
}
.keyboardShortcut(.defaultAction)
.buttonStyle(.borderedProminent)
Button(action: createAccount) {
Text("Create Account").frame(maxWidth: 300)
}
.buttonStyle(.bordered)
}
.controlSize(.large)
}
.padding()
.frame(minWidth: 300, idealWidth: 400, minHeight: 300, idealHeight: 340)
}
}
|
//
// RealmTalksProtocol.swift
// PyConJP2016
//
// Created by Yutaro Muta on 2016/08/18.
// Copyright © 2016 PyCon JP. All rights reserved.
//
import UIKit
import RealmSwift
protocol RealmTalksProtocol {
var filterPredicate: NSPredicate { get }
var sortProperties: Array<SortDescriptor> { get }
func loadTalkObjects(_ completionHandler: ((Result<Array<TalkObject>>) -> Void)) -> Void
func getTalksFromLocalDummyJson(completionHandler: ((Result<Void>) -> Void)) -> Void
}
extension RealmTalksProtocol {
func loadTalkObjects(_ completionHandler: ((Result<Array<TalkObject>>) -> Void)) -> Void {
do {
let realm = try Realm()
let talks = Array(realm.objects(TalkObject.self).filter(filterPredicate).sorted(by: sortProperties))
completionHandler(.success(talks))
} catch let error as NSError {
completionHandler(.failure(error))
}
}
}
extension RealmTalksProtocol {
func getTalksFromLocalDummyJson(completionHandler: ((Result<Void>) -> Void)) -> Void {
let path = Bundle.main.path(forResource: "DummyTalks", ofType: "json")
let fileHandle = FileHandle(forReadingAtPath: path!)
let data = fileHandle?.readDataToEndOfFile()
let dictionary = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! Dictionary<String, AnyObject>
let presentations = dictionary["presentations"] as? Array<Dictionary<String, AnyObject>> ?? [Dictionary<String, AnyObject>]()
do {
let realm = try Realm()
try realm.write({
presentations.forEach({
let talkObject = TalkObject(dictionary: $0)
realm.add(talkObject, update: true)
})
})
completionHandler(.success())
} catch let error as NSError {
completionHandler(.failure(error))
}
}
}
|
//
// ItemCollectionViewCell.swift
// iOSTopBooksLists
//
// Created by Zin Min Phyoe on 12/31/19.
// Copyright © 2019 Zin Min Phyoe. All rights reserved.
//
import UIKit
class ItemCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var bookLabel : UILabel!
@IBOutlet weak var bookImage : UIImageView!
func displayEachItem(image:UIImage,title:String){
self.bookImage.image = image
self.bookLabel.text = title
}
}
|
//
// RouteViewController.swift
// PruebaMap
//
// Created by Paul Silva on 8/4/16.
// Copyright © 2016 Paul Silva. All rights reserved.
//
import UIKit
import GoogleMaps
import GooglePlaces
class RouteViewController: UIViewController {
override func loadView() {
super.loadView()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// Group3Cell.swift
// government_park
//
// Created by YiGan on 20/09/2017.
// Copyright © 2017 YiGan. All rights reserved.
//
import UIKit
class Group3Cell: GroupCell {
@IBOutlet weak var imagesView: UIView!
}
|
//
// HippoActionMessage.swift
// Fugu
//
// Created by Vishal on 04/02/19.
// Copyright © 2019 Socomo Technologies Private Limited. All rights reserved.
//
import Foundation
class HippoActionMessage: HippoMessage {
var selectedBtnId: String = ""
var isUserInteractionEnbled: Bool = false
var buttons: [HippoActionButton]?
var responseMessage: HippoMessage?
var repliedBy: String?
var repliedById: Int?
override init?(dict: [String : Any]) {
super.init(dict: dict)
isActive = Bool.parse(key: "is_active", json: dict)
selectedBtnId = dict["selected_btn_id"] as? String ?? ""
repliedBy = dict["replied_by"] as? String
repliedById = Int.parse(values: dict, key: "replied_by_id")
if let content_value = dict["content_value"] as? [[String: Any]] {
self.contentValues = content_value
let selectedId = selectedBtnId.isEmpty ? nil : selectedBtnId
let (buttons, selectedButton) = HippoActionButton.getArray(array: contentValues, selectedId: selectedId)
if type == .dateTime || type == .address {
tryToSetResponseMessage()
}else if type == .botAttachment {
tryToSetResponseMessageForAttachment()
}else {
tryToSetResponseMessage(selectedButton: selectedButton)
}
self.buttons = buttons
}
setHeight()
isUserInteractionEnbled = isActive
}
func tryToSetResponseMessageForAttachment() {
if let dic = self.contentValues.first {
responseMessage = HippoMessage(message: "", type: .normal, senderName: repliedBy, senderId: repliedById, chatType: chatType)
if let rawFileType = dic["file_type"] as? String {
responseMessage?.documentType = FileType(mimeType: rawFileType)
}
responseMessage?.thumbnailUrl = dic["thumbnail_url"] as? String
responseMessage?.fileUrl = dic["url"] as? String ?? dic["attachment_url"] as? String
responseMessage?.fileName = dic["file_name"] as? String
responseMessage?.imageUrl = dic["attachment_url"] as? String
if responseMessage?.documentType == .document || responseMessage?.documentType == .video {
responseMessage?.type = .attachment
}else {
responseMessage?.type = .imageFile
}
responseMessage?.userType = .customer
responseMessage?.creationDateTime = self.creationDateTime
responseMessage?.status = status
cellDetail?.actionHeight = nil
}
}
func tryToSetResponseMessage(selectedButton: HippoActionButton?) {
guard let parsedSelectedButton = selectedButton else {
return
}
responseMessage = HippoMessage(message: parsedSelectedButton.title, type: .normal, senderName: repliedBy, senderId: repliedById, chatType: chatType)
responseMessage?.userType = .customer
responseMessage?.creationDateTime = self.creationDateTime
responseMessage?.status = status
cellDetail?.actionHeight = nil
}
func tryToSetResponseMessage() {
if let dic = self.contentValues.first {
if type == .dateTime {
responseMessage = HippoMessage(message: dic["date_time_message"] as? String ?? "", type: .normal, senderName: repliedBy, senderId: repliedById, chatType: chatType)
}else {
responseMessage = HippoMessage(message: dic["address"] as? String ?? "", type: .normal, senderName: repliedBy, senderId: repliedById, chatType: chatType)
}
responseMessage?.userType = .customer
responseMessage?.creationDateTime = self.creationDateTime
responseMessage?.status = status
cellDetail?.actionHeight = nil
}
}
func setHeight() {
cellDetail = HippoCellDetail()
cellDetail?.headerHeight = attributtedMessage.messageHeight + attributtedMessage.nameHeight + attributtedMessage.timeHeight
cellDetail?.showSenderName = false
if let attributtedMessage = responseMessage?.attributtedMessage {
if responseMessage?.type == .imageFile {
cellDetail?.responseHeight = 250
}else if responseMessage?.type == .attachment {
switch responseMessage?.concreteFileType {
case .video:
cellDetail?.responseHeight = 234
default:
cellDetail?.responseHeight = 80
}
}else {
let nameHeight: CGFloat = HippoConfig.shared.appUserType == .agent ? attributtedMessage.nameHeight : 0
cellDetail?.responseHeight = attributtedMessage.messageHeight + attributtedMessage.timeHeight + nameHeight + 10
}
cellDetail?.actionHeight = nil
} else {
let buttonHeight = buttonsHeight() //(buttons?.count ?? 0) * 50
cellDetail?.actionHeight = CGFloat(buttonHeight) + 15 + 10 + 10 //Button Height + (timeLabelHeight + time gap from top) + padding
}
cellDetail?.padding = 1
}
func buttonsHeight() -> CGFloat {
guard let buttons = buttons, !buttons.isEmpty else {
return 0
}
let maxWidth = windowScreenWidth - 27
var buttonCount: Int = 0
var remaningWidth: CGFloat = maxWidth
for each in buttons {
let w: CGFloat = findButtonWidth(each.title) + 40
let widthRemaningAfterInsertion = remaningWidth - w - 5
if remaningWidth == maxWidth {
buttonCount += 1
remaningWidth = widthRemaningAfterInsertion
} else if widthRemaningAfterInsertion <= -5 {
buttonCount += 1
remaningWidth = maxWidth - w - 5
} else {
remaningWidth = widthRemaningAfterInsertion
}
// let message = "===\(each.title)--w=\(w)--widthRemaningAfterInsertion=\(widthRemaningAfterInsertion)--b=\(buttonCount)--remaning=\(remaningWidth) \n"
// HippoConfig.shared.log.debug(message, level: .custom)
}
return CGFloat(buttonCount * 35) + CGFloat(5 * (buttonCount - 1))
}
private func findButtonWidth(_ text: String) -> CGFloat {
let attributedText = NSMutableAttributedString(string: text)
let range = (text as NSString).range(of: text)
attributedText.addAttribute(.font, value: HippoConfig.shared.theme.incomingMsgFont, range: range)
let boxSize: CGSize = CGSize(width: windowScreenWidth - 30, height: CGFloat.greatestFiniteMagnitude)
return sizeOf(attributedString: attributedText, availableBoxSize: boxSize).width
}
private func sizeOf(attributedString: NSMutableAttributedString, availableBoxSize: CGSize) -> CGSize {
return attributedString.boundingRect(with: availableBoxSize, options: .usesLineFragmentOrigin, context: nil).size
}
override func getJsonToSendToFaye() -> [String : Any] {
var json = super.getJsonToSendToFaye()
if type != .dateTime && type != .address && type != .botAttachment{
json["selected_btn_id"] = selectedBtnId
json["is_active"] = isActive.intValue()
}
json["content_value"] = contentValues
json["user_id"] = currentUserId()
json["replied_by"] = currentUserName()
json["replied_by_id"] = currentUserId()
return json
}
func selectBtnWith(btnId: String) {
selectedBtnId = btnId
isActive = false
isUserInteractionEnbled = false
repliedById = currentUserId()
repliedBy = currentUserName()
let selectedId = selectedBtnId.isEmpty ? nil : selectedBtnId
if type == .dateTime || type == .address {
tryToSetResponseMessage()
} else if type == .botAttachment {
tryToSetResponseMessageForAttachment()
}else{
if !contentValues.isEmpty {
contentValues.append(contentsOf: customButtons)
let list = contentValues
let (buttons, selectedButton) = HippoActionButton.getArray(array: list, selectedId: selectedId)
self.tryToSetResponseMessage(selectedButton: selectedButton)
self.buttons = buttons
}
}
setHeight()
}
func updateObject(with newObject: HippoActionMessage) {
super.updateObject(with: newObject)
self.selectedBtnId = newObject.selectedBtnId
self.isActive = newObject.isActive
self.isUserInteractionEnbled = newObject.isUserInteractionEnbled
self.repliedById = newObject.repliedById
self.repliedBy = newObject.repliedBy
let selectedId = selectedBtnId.isEmpty ? nil : selectedBtnId
if type == .dateTime || type == .address {
tryToSetResponseMessage()
}else if type == .botAttachment {
tryToSetResponseMessageForAttachment()
}else {
if !contentValues.isEmpty {
let (buttons, selectedButton) = HippoActionButton.getArray(array: contentValues, selectedId: selectedId)
self.tryToSetResponseMessage(selectedButton: selectedButton)
self.buttons = buttons
}
}
setHeight()
self.status = .sent
messageRefresed?()
}
func getButtonWithId(id: String) -> HippoActionButton? {
guard let buttons = self.buttons else {
return nil
}
let button = buttons.first { (b) -> Bool in
return b.id == id
}
return button
}
}
let customButtons: [[String: Any]] = [
[
"btn_id": "451",
"btn_color": "#FFFFFF",
"btn_title": "Agent List",
"btn_title_color": "#000000",
"btn_selected_color": "#1E7EFF",
"action": "AGENTS",
"btn_title_selected_color": "#FFFFFF"
],
[
"btn_id": "454",
"btn_color": "#FFFFFF",
"btn_title": "audio call",
"btn_title_color": "#000000",
"btn_selected_color": "#1E7EFF",
"action": "AUDIO_CALL",
"btn_title_selected_color": "#FFFFFF"
],
[
"btn_id": "455",
"btn_color": "#FFFFFF",
"btn_title": "video call",
"btn_title_color": "#000000",
"btn_selected_color": "#1E7EFF",
"action": "VIDEO_CALL",
"btn_title_selected_color": "#FFFFFF"
],
[
"btn_id": "455",
"btn_color": "#FFFFFF",
"btn_title": "Continue chat",
"btn_title_color": "#000000",
"btn_selected_color": "#1E7EFF",
"action": "CONTINUE_CHAT",
"btn_title_selected_color": "#FFFFFF"
]
]
|
//
// FlickerItem.swift
// Test Project SwiftUI
//
// Created by Admin on 09/06/2021.
//
import SwiftUI
struct FlickerItem: View {
let urlString: String
var body: some View {
VStack{
RemoteImage(urlString: urlString)
.frame(minWidth: 120, maxWidth: 160, minHeight: 120, maxHeight: 160, alignment: .center)
}
}
}
struct FlickerItem_Previews: PreviewProvider {
static var previews: some View {
FlickerItem(urlString: "https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico?v=ec617d715196")
}
}
|
//
// ContentIPadVScreen.swift
// Tutorial
//
// Created by Александр Сенин on 29.03.2021.
//
import RelizKit
class ContentIPadVScreen: ContentIPhoneVScreen{
override var contentWidth: RZProtoValue {router.isHorizontal ? 68 % self*.h : 68 % self*.w}
}
|
//
// BankAPI.swift
// Bank App
//
// Created by Chrystian (Pessoal) on 29/12/2018.
// Copyright © 2018 Salgado's Productions. All rights reserved.
//
import Foundation
class BankAPI: BankAPIProtocol {
/**
* Documentation for this class:
* https://hackernoon.com/everything-about-codable-in-swift-4-97d0e18a2999
* https://www.raywenderlich.com/567-urlsession-tutorial-getting-started
* https://medium.com/@sdrzn/networking-and-persistence-with-json-in-swift-4-c400ecab402d
*/
var urlHost = "bank-app-test.herokuapp.com"
var urlScheme = "https"
var urlPath = ""
func loginUser(login: UserLogin, completionHandler: @escaping (UserResponse?) -> Void) {
let encoder = JSONEncoder()
let jsonData = try? encoder.encode(login)
// try request
urlPath = "/api/login"
urlRequest(type: .post, params: jsonData) { (responseData) in
if let jsonData = responseData {
do {
let response = try JSONDecoder().decode(UserResponse.self, from: jsonData)
if let bankError = response.error, bankError.code != nil {
completionHandler(response)
print(bankError)
}
else if let _ = response.userAccount {
completionHandler(response)
}
} catch {
self.catchNetworkError(responseData)
completionHandler(nil)
}
}
else {
self.catchNetworkError(responseData)
completionHandler(nil)
}
}
}
func statementList(by userId: Int, completionHandler: @escaping (StatementResponse?) -> Void) {
// try request
urlPath = "/api/statements/\(userId)"
urlRequest(type: .get, params: nil) { (responseData) in
if let jsonData = responseData {
do {
let response = try JSONDecoder().decode(StatementResponse.self, from: jsonData)
if let bankError = response.error, bankError.code != nil {
completionHandler(response)
print(bankError)
}
else if let _ = response.statementList {
completionHandler(response)
}
} catch {
self.catchNetworkError(responseData)
completionHandler(nil)
}
}
else {
self.catchNetworkError(responseData)
completionHandler(nil)
}
}
}
}
|
//
// TodosTableViewCoordinator.swift
// TodoList
//
// Created by Christian Oberdörfer on 19.03.19.
// Copyright © 2019 Christian Oberdörfer. All rights reserved.
//
import UIKit
/**
Coordinates handling of todos table
*/
class TodosTableViewCoordinator: Coordinator {
private let navigationController: UINavigationController
private let todosTableViewController: TodosTableViewController
private var settingsTableViewCoordinator: SettingsTableViewCoordinator?
private var todoTableViewCoordinator: TodoTableViewCoordinator?
/**
Creates a new todos table coordinator
- parameter navigationController: The navigation controller to use
*/
init(navigationController: UINavigationController) {
self.navigationController = navigationController
self.todosTableViewController = TodosTableViewController()
super.init()
self.todosTableViewController.delegate = self
}
/**
Pushes the view controller onto the stack
*/
func start() {
self.navigationController.pushViewController(self.todosTableViewController, animated: true)
}
}
// MARK: - TodosTableViewControllerDelegate
extension TodosTableViewCoordinator: TodosTableViewControllerDelegate {
func add() {
// Create a new todo table view coordinator and start it
self.todoTableViewCoordinator = TodoTableViewCoordinator(navigationController: self.navigationController, todo: nil)
self.todoTableViewCoordinator?.start()
}
func delete(_ todo: Todo) {
// Update to server
NetworkService.shared.delete(id: todo.id) { _ in
// Update database
TodoRepository.shared.delete(todo)
}
}
func select(_ todo: Todo) {
// Update from server
NetworkService.shared.get(id: todo.id) { _, todoFull in
// Update database
TodoRepository.shared.update(todo, with: todoFull) { todo in
// Create a new todo table view coordinator and start it
guard todo != nil else {
return
}
self.todoTableViewCoordinator = TodoTableViewCoordinator(navigationController: self.navigationController, todo: todo)
self.todoTableViewCoordinator?.start()
}
}
}
func showSettings() {
// Create a new settings table view coordinator and start it
self.settingsTableViewCoordinator = SettingsTableViewCoordinator(navigationController: self.navigationController)
self.settingsTableViewCoordinator?.start()
}
func toggle(_ todo: Todo) {
let done = !todo.done
let id = todo.id
// Update from server
NetworkService.shared.get(id: id) { _, todoFull in
// Update to server
let todoBase = TodoBase(desc: todoFull.desc, done: done, dueDate: todoFull.dueDate, title: todoFull.title)
NetworkService.shared.update(id: id, todoBase: todoBase) { _ in
// Update database
let todoFullNew = TodoFull(id: todoFull.id, desc: todoFull.desc, done: done, dueDate: todoFull.dueDate, title: todoFull.title)
TodoRepository.shared.update(todo, with: todoFullNew)
}
}
}
}
|
//
// TrackOverviewCell.swift
// SpotifyClone
//
// Created by JAYANTA GOGOI on 1/18/20.
// Copyright © 2020 JAYANTA GOGOI. All rights reserved.
//
import UIKit
class TrackOverviewCell: CollectionBaseCell{
override func setupView() {
self.backgroundColor = UIColor.rgba(r: 0, g: 0, b: 0, a: 0.8)
title.text = "Kyon"
title.lineBreakMode = .byTruncatingTail
title.font = UIFont.systemFont(ofSize: 16)
title.numberOfLines = 1
subTitle.text = "papon angarag Mahanta"
subTitle.lineBreakMode = .byTruncatingTail
subTitle.numberOfLines = 1
subTitle.font = UIFont.systemFont(ofSize: 14)
subTitle.textColor = UIColor.lightGray
btnOnTapAction.setImage(#imageLiteral(resourceName: "vertical_dots"), for: .normal )
addSubview(title)
addSubview(subTitle)
addSubview(btnOnTapAction)
addConstraintWithFormat(formate: "H:|-10-[v0]-48-|", views: title)
addConstraintWithFormat(formate: "H:|-10-[v0]-48-|", views: subTitle)
addConstraintWithFormat(formate: "H:[v0(38)]-10-|", views: btnOnTapAction)
addConstraintWithFormat(formate: "V:|-5-[v0][v1(15)]", views: title, subTitle)
addConstraintWithFormat(formate: "V:|-5-[v0]-5-|", views: btnOnTapAction)
btnOnTapAction.addTarget(self, action: #selector(onTapShare(_:)), for: .touchUpInside)
}
@objc func onTapShare(_ sender: UIButton){
sender.onTapAnimation()
}
}
|
//
// SignUpTextField.swift
// Waver
//
// Created by Marco Burstein on 6/5/16.
// Copyright © 2016 Skunk. All rights reserved.
//
import UIKit
class SignUpTextField: UITextField, UITextFieldDelegate {
let incorrectColor = UIColor(red: 225.0/225.0, green: 0.0/225.0, blue: 25.0/225.0, alpha: 1.0)
let defaultColor = UIColor.blackColor()
let emailIncorrectMessage = "Must be valid and unused"
let usernameIncorrectMessage = "Must use allowed characters"
let passwordIncorrectMessage = "Must be more than 5 characters"
var showingRequirements = false
func showRequirements(typeToShow: String){
showingRequirements = true
textColor = incorrectColor
resignFirstResponder()
switch typeToShow {
case "email":
text = emailIncorrectMessage
case "username":
text = usernameIncorrectMessage
case "password":
text = passwordIncorrectMessage
default:
break
}
}
func hideRequirements(){
showingRequirements = false
textColor = defaultColor
text = ""
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
|
//
// MemberReplyViewController.swift
// v2ex
//
// Created by zhenwen on 7/13/15.
// Copyright (c) 2015 zhenwen. All rights reserved.
//
import UIKit
import v2exKit
class MemberReplyViewController: UITableViewController {
var username: String!
var dataSouce: [MemberReplyModel] = [] {
didSet {
tableView.reloadData()
}
}
//args: NSDictionary
func allocWithRouterParams(args: NSDictionary?) -> MemberReplyViewController {
let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("memberReplyViewController") as! MemberReplyViewController
viewController.hidesBottomBarWhenPushed = true
return viewController
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.layoutMargins = UIEdgeInsetsZero
tableView.estimatedRowHeight = 60
tableView.rowHeight = UITableViewAutomaticDimension
tableView.tableFooterView = defaultTableFooterView
reloadTableViewData(isPull: false)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func reloadTableViewData(isPull pull: Bool) {
MemberReplyModel.getMemberReplies(username, completionHandler: { (obj, error) -> Void in
if error == nil {
self.dataSouce = obj
} else {
}
})
}
}
// MARK: UITableViewDataSource & UITableViewDelegate
extension MemberReplyViewController {
// UITableViewDataSource
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: MemberReplyCell = tableView.dequeueReusableCellWithIdentifier("memberReplyCellId") as! MemberReplyCell
let replyModel = dataSouce[indexPath.row]
cell.updateCell(replyModel)
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSouce.count;
}
// UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let replyModel = dataSouce[indexPath.row]
let viewController = PostDetailViewController().allocWithRouterParams(nil)
viewController.postId = replyModel.post_id
navigationController?.pushViewController(viewController, animated: true)
}
}
|
//
// ReaderView_PDF.swift
// ReaderTranslator
//
// Created by Viktor Kushnerov on 9/28/19.
// Copyright © 2019 Viktor Kushnerov. All rights reserved.
//
import SwiftUI
struct ReaderView_Pdf: View {
@ObservedObject var store = Store.shared
@ObservedObject private var viewsStore = ViewsStore.shared
var body: some View {
VStack {
PDFKitView()
ReaderView_Pdf_Toolbar()
}.frame(width: viewsStore.viewWidth[.pdf] ?? ViewsStore.defaultWidth)
}
}
struct ReaderView_Pdf_Previews: PreviewProvider {
static var previews: some View {
ReaderView_Pdf()
}
}
|
//
// ToggleViewProtocol.swift
// SideMenu
//
// Created by Cuong on 10/9/19.
// Copyright © 2019 Cuong. All rights reserved.
//
import UIKit
@objc
protocol ToggleViewProtocol: class {
var controlConstraint: NSLayoutConstraint! {get set}
var corverButton: UIButton! {get set}
var menu: UIView! {get set}
var effectView: UIVisualEffectView? {get set}
var closeDistance: CGFloat {get set}
var showDistance: CGFloat {get set}
var isOpen: Bool {get set}
var view: UIView! {get set}
var coverAlpha: CGFloat {get set}
}
extension ToggleViewProtocol {
func performToggle(isOpen: Bool) {
self.controlConstraint.constant = self.isOpen ? self.showDistance : -self.closeDistance - 20
self.corverButton.alpha = self.isOpen ? self.coverAlpha : 0
self.effectView?.alpha = self.isOpen ? self.coverAlpha : 0
UIView.animate(withDuration: 0.35) {
self.view.layoutIfNeeded()
}
}
func setupToggleView(distance: CGFloat) {
closeDistance = distance
isOpen = false
setupShowingView()
controlConstraint.constant = -closeDistance - 20
corverButton.alpha = 0
effectView?.alpha = 0
view.layoutIfNeeded()
}
private func setupShowingView() {
menu.shadowColor = UIColor.black
menu.shadowRadius = 20
menu.shadowOpacity = 0.7
menu.shadowOffset = CGSize(width: 0, height: 0)
}
}
|
// Omnia iOS Playground
import UIKit
import Omnia
var str = "Hello, playground"
|
//
// ViewController.swift
// CoreDataDemo
//
// Created by Sandeep Tomar on 03/06/21.
//
import UIKit
import CoreData
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var names: [String] = ["Sandeep","tomar","new name", "testdataa"]
var people: [NSManagedObject] = []
override func viewDidLoad() {
super.viewDidLoad()
title = "The List"
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self,
forCellReuseIdentifier: "Cell")
people.removeAll()
for values in names {
storeDataToDB(str: values)
}
}
override func viewWillAppear(_ animated: Bool) {
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
let context = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Person")
do {
people = try context.fetch(fetchRequest)
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
if people.count > 0 {
tableView.reloadData()
}
}
func storeDataToDB(str:String) {
guard let appdelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appdelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedContext)
let person = NSManagedObject(entity: entity!, insertInto: managedContext)
person.setValue(str, forKey: "name")
// 4
do {
try managedContext.save()
people.append(person)
// tableView.reloadData()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return people.count
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath)
-> UITableViewCell {
let person = people[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell",
for: indexPath)
cell.textLabel?.text = person.value(forKey: "name") as? String
return cell
}
}
|
//
// ViewController.swift
// day06
//
// Created by Charles Lanier on 1/16/18.
// Copyright © 2018 vintra. All rights reserved.
//
import UIKit
import CoreMotion
let elasticity: CGFloat = 0.5;
class ViewController: UIViewController {
var motionManager = CMMotionManager();
var animator: UIDynamicAnimator?;
var gravity: UIGravityBehavior?;
var collisions: UICollisionBehavior?;
var itemBehavior: UIDynamicItemBehavior?;
@IBAction func detectTapGesture(_ sender: UITapGestureRecognizer) {
let shapeView = ShapeView(origin: sender.location(in: self.view));
self.view.addSubview(shapeView);
self.gravity?.addItem(shapeView);
self.collisions?.addItem(shapeView);
self.itemBehavior?.addItem(shapeView);
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(panning));
shapeView.addGestureRecognizer(panGesture);
let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(pinching));
shapeView.addGestureRecognizer(pinchGesture);
let rotationGesture = UIRotationGestureRecognizer(target: self, action: #selector(rotating));
shapeView.addGestureRecognizer(rotationGesture);
}
@objc func rotating(rotationGesture: UIRotationGestureRecognizer) {
switch rotationGesture.state {
case .began:
self.gravity?.removeItem(rotationGesture.view!);
case .changed:
self.collisions?.removeItem(rotationGesture.view!);
self.itemBehavior?.removeItem(rotationGesture.view!);
rotationGesture.view!.transform = rotationGesture.view!.transform.rotated(by: rotationGesture.rotation);
rotationGesture.rotation = 0;
self.collisions?.addItem(rotationGesture.view!);
self.itemBehavior?.addItem(rotationGesture.view!);
self.animator?.updateItem(usingCurrentState: rotationGesture.view!);
case .ended:
self.gravity?.addItem(rotationGesture.view!);
default:
break ;
}
}
@objc func pinching(pinchGesture: UIPinchGestureRecognizer) {
let view = pinchGesture.view as! ShapeView;
switch pinchGesture.state {
case .began:
self.gravity?.removeItem(view);
case .changed:
self.collisions?.removeItem(view);
self.itemBehavior?.removeItem(view);
view.bounds.size.width = view.originalBounds.width * pinchGesture.scale;
view.bounds.size.height = view.originalBounds.height * pinchGesture.scale;
self.collisions?.addItem(view);
self.itemBehavior?.addItem(view);
self.animator?.updateItem(usingCurrentState: view);
case .ended:
view.originalBounds = view.bounds;
self.gravity?.addItem(view);
default:
break ;
}
}
@objc func panning(panGesture: UIPanGestureRecognizer) {
switch panGesture.state {
case .began:
self.gravity?.removeItem(panGesture.view!);
case .changed:
panGesture.view?.center = panGesture.location(in: self.view);
self.animator?.updateItem(usingCurrentState: panGesture.view!);
case .ended:
self.gravity?.addItem(panGesture.view!);
default:
break ;
}
}
func handleAccelerometerUpdate(data: CMAccelerometerData?, error: Error?) -> Void {
if let d = data {
self.gravity!.gravityDirection = CGVector(dx: d.acceleration.x, dy: -d.acceleration.y);
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
animatorInit();
motionManagerInit();
}
func motionManagerInit() {
if (motionManager.isAccelerometerAvailable) {
motionManager.accelerometerUpdateInterval = 1;
motionManager.startAccelerometerUpdates(to: OperationQueue.main, withHandler: handleAccelerometerUpdate);
}
}
func animatorInit() {
animator = UIDynamicAnimator(referenceView: self.view);
addGravity();
addCollisions();
addItemBehavior();
}
func addGravity() {
self.gravity = UIGravityBehavior(items: []);
self.gravity!.gravityDirection = CGVector(dx: 0.0, dy: 1.0);
self.animator?.addBehavior(self.gravity!);
}
func addCollisions() {
self.collisions = UICollisionBehavior(items: []);
self.collisions!.translatesReferenceBoundsIntoBoundary = true;
self.animator?.addBehavior(self.collisions!);
}
func addItemBehavior() {
self.itemBehavior = UIDynamicItemBehavior(items: []);
self.itemBehavior?.elasticity = elasticity;
animator?.addBehavior(self.itemBehavior!);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// AddNewActivityViewController.swift
// Your Projects
//
// Created by Carlos Modinez on 06/06/19.
// Copyright © 2019 Carlos Modinez. All rights reserved.
//
import UIKit
class AddNewActivityViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
@IBOutlet weak var pcvProjects: UIPickerView!
@IBOutlet weak var inputTxtIntoProject: UITextField!
@IBOutlet weak var inputTxtActivityTitle: UITextField!
@IBOutlet weak var btnAddActivity: UIButton!
var newActivity = Activity()
var projects = Model.shared.projects
var projectPositionInModel = -1
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Add Atividade"
inputTxtIntoProject.delegate = self
inputTxtActivityTitle.delegate = self
btnAddActivity.isEnabled = false
btnAddActivity.isHidden = true
pcvProjects.dataSource = self
pcvProjects.delegate = self
pcvProjects.isHidden = true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
inputTxtIntoProject.resignFirstResponder()
inputTxtActivityTitle.resignFirstResponder()
return true
}
// Codigo do PickerView
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return projects.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
projectPositionInModel = row
return projects[row].Name
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
inputTxtIntoProject.text = projects[row].Name
}
//_________________ termino do código do pickerView
@IBAction func addActivityTitle(_ sender: UITextField) {
newActivity.name = sender.text!
view.endEditing(true)
pcvProjects.isHidden = true
//Nao habilita o botao se não houver título
if newActivity.name != ""{
btnAddActivity.isEnabled = true
btnAddActivity.isHidden = false
}
}
@IBAction func addProject(_ sender: Any) {
view.endEditing(true)
pcvProjects.isHidden = false
}
@IBAction func addProjectEnd(_ sender: Any) {
pcvProjects.isHidden = true
}
@IBAction func addActivityDeadline(_ sender: UITextField) {
newActivity.date = sender.text!
pcvProjects.isHidden = true
view.endEditing(true)
}
@IBAction func addActivityDescription(_ sender: UITextField) {
newActivity.description = sender.text!
pcvProjects.isHidden = true
}
@IBAction func addNewActivityPressed(_ sender: Any) {
Model.shared.projects[projectPositionInModel].activities.append(newActivity)
print(Model.shared.projects[projectPositionInModel].Name)
self.navigationController?.popViewController(animated: true)
}
}
|
//
// MedieView.swift
// SpecialTraining
//
// Created by 尹涛 on 2018/11/24.
// Copyright © 2018 youpeixun. All rights reserved.
//
import UIKit
class MedieView: UIView {
weak var delegate: MediaProtocol?
struct Frame {
static let itemWidth: CGFloat = 70
static let itemHeight: CGFloat = 70
static let h_margin = (UIScreen.main.bounds.size.width - 4*itemWidth) / 5.0
static let edgeInset: UIEdgeInsets = UIEdgeInsets.init(top: 15,
left: h_margin,
bottom: 15,
right: h_margin)
}
private var datasource: [String]!
private var collectionView: UICollectionView!
init(datasource: [String]) {
let h = datasource.count > 4 ? (Frame.itemHeight + Frame.edgeInset.top * 2) : (Frame.itemHeight * 2 + Frame.edgeInset.top * 3)
super.init(frame: .init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: h))
self.datasource = datasource
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func setupView() {
let layout = UICollectionViewFlowLayout.init()
layout.itemSize = .init(width: Frame.itemWidth, height: Frame.itemHeight)
layout.sectionInset = Frame.edgeInset
layout.minimumLineSpacing = Frame.edgeInset.top
layout.minimumInteritemSpacing = Frame.h_margin
collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: layout)
collectionView.backgroundColor = .white
collectionView.delegate = self
collectionView.dataSource = self
addSubview(collectionView)
collectionView.snp.makeConstraints{ $0.edges.equalTo(UIEdgeInsets.zero) }
collectionView.register(MediaCell.self, forCellWithReuseIdentifier: "MediaCellID")
}
}
extension MedieView: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return datasource.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = (collectionView.dequeueReusableCell(withReuseIdentifier: "MediaCellID", for: indexPath) as! MediaCell)
cell.imgStr = datasource[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.mediaItem(selected: indexPath.row)
}
}
class MediaCell: UICollectionViewCell {
private var imgV: UIImageView!
override init(frame: CGRect) {
super.init(frame: frame)
imgV = UIImageView()
addSubview(imgV)
imgV.snp.makeConstraints{ $0.edges.equalTo(UIEdgeInsets.zero) }
}
var imgStr: String! {
didSet {
imgV.image = UIImage.init(named: imgStr)
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
protocol MediaProtocol: class {
/// 多功能键盘选中item
///
/// - Parameter reload: 隐藏时是否需要刷新键盘
func mediaItem(selected idx: Int)
}
|
//
// ReminderDetailController.swift
// To-Do-List
//
// Created by YanDongZhang on 8/04/2016.
// Copyright © 2016 YanDongZhang. All rights reserved.
//
import UIKit
class ReminderDetailController: UIViewController {
var currentReminder : Reminder?
@IBOutlet weak var titleContentLabel: UILabel!
@IBOutlet weak var descriptionContentLabel: UILabel!
@IBOutlet weak var dueDateContentLabel: UILabel!
@IBOutlet weak var completeLabel: UILabel!
@IBOutlet weak var statueSwitch: UISwitch!
@IBAction func statusValueChanged(sender: AnyObject) {
//Identify the status of the complete label
if self.statueSwitch.on {
self.currentReminder?.complete = true
self.completeLabel.text = "Completed"
}else
{
self.currentReminder?.complete = false
self.completeLabel.text = "Incompleted"
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.titleContentLabel.text = currentReminder?.title
self.descriptionContentLabel.text = currentReminder?.descriptions
//Fomate the Data inot the String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let strDate = dateFormatter.stringFromDate((self.currentReminder?.dueDate)!)
self.dueDateContentLabel.text = strDate
//Event listening the Complete Status
if self.currentReminder?.complete == true
{
self.statueSwitch.setOn(true, animated: true)
self.completeLabel.text = "Completed"
}
if self.currentReminder?.complete == false
{
self.statueSwitch.setOn(false, animated: true)
self.completeLabel.text = "Incompleted"
}
}
}
|
//
// PieceTests.swift
// ChessKitTests
//
// Created by Alexander Perechnev on 12.07.2020.
// Copyright © 2020 Päike Mikrosüsteemid OÜ. All rights reserved.
//
import XCTest
@testable import ChessKit
class PieceTests: XCTestCase {
func testInitWithCharacter() throws {
XCTAssertEqual(Piece(character: "K"), Piece(kind: .king, color: .white))
XCTAssertEqual(Piece(character: "Q"), Piece(kind: .queen, color: .white))
XCTAssertEqual(Piece(character: "R"), Piece(kind: .rook, color: .white))
XCTAssertEqual(Piece(character: "B"), Piece(kind: .bishop, color: .white))
XCTAssertEqual(Piece(character: "N"), Piece(kind: .knight, color: .white))
XCTAssertEqual(Piece(character: "P"), Piece(kind: .pawn, color: .white))
XCTAssertEqual(Piece(character: "k"), Piece(kind: .king, color: .black))
XCTAssertEqual(Piece(character: "q"), Piece(kind: .queen, color: .black))
XCTAssertEqual(Piece(character: "r"), Piece(kind: .rook, color: .black))
XCTAssertEqual(Piece(character: "b"), Piece(kind: .bishop, color: .black))
XCTAssertEqual(Piece(character: "n"), Piece(kind: .knight, color: .black))
XCTAssertEqual(Piece(character: "p"), Piece(kind: .pawn, color: .black))
XCTAssertEqual(Piece(character: "-"), nil)
XCTAssertEqual(Piece(character: "x"), nil)
XCTAssertEqual(Piece(character: " "), nil)
}
func testMapToCharacter() throws {
XCTAssertEqual("\(Piece(kind: .king, color: .white))", "K")
XCTAssertEqual("\(Piece(kind: .queen, color: .white))", "Q")
XCTAssertEqual("\(Piece(kind: .rook, color: .white))", "R")
XCTAssertEqual("\(Piece(kind: .bishop, color: .white))", "B")
XCTAssertEqual("\(Piece(kind: .knight, color: .white))", "N")
XCTAssertEqual("\(Piece(kind: .pawn, color: .white))", "P")
XCTAssertEqual("\(Piece(kind: .king, color: .black))", "k")
XCTAssertEqual("\(Piece(kind: .queen, color: .black))", "q")
XCTAssertEqual("\(Piece(kind: .rook, color: .black))", "r")
XCTAssertEqual("\(Piece(kind: .bishop, color: .black))", "b")
XCTAssertEqual("\(Piece(kind: .knight, color: .black))", "n")
XCTAssertEqual("\(Piece(kind: .pawn, color: .black))", "p")
}
}
|
//
// OutsideVM+CoreData.swift
// Calm Cloud
//
// Created by Kate Duncan-Welke on 7/28/21.
// Copyright © 2021 Kate Duncan-Welke. All rights reserved.
//
import Foundation
import CoreData
extension OutsideViewModel {
func loadInventory() {
// load seedling inventory
var managedContext = CoreDataManager.shared.managedObjectContext
var fetchRequest = NSFetchRequest<InventoryItem>(entityName: "InventoryItem")
do {
Plantings.loaded.removeAll()
Plantings.loaded = try managedContext.fetch(fetchRequest)
for item in Plantings.loaded {
Plantings.availableSeedlings[Plant(rawValue: Int(item.id))!] = Int(item.quantity)
}
print("inventory loaded")
} catch let error as NSError {
//showAlert(title: "Could not retrieve data", message: "\(error.userInfo)")
}
}
func loadPlots() {
// load planted plots
var managedContext = CoreDataManager.shared.managedObjectContext
var fetchRequest = NSFetchRequest<Plot>(entityName: "Plot")
do {
Plantings.plantings = try managedContext.fetch(fetchRequest)
print("plots loaded")
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "loadPlants"), object: nil)
} catch let error as NSError {
//showAlert(title: "Could not retrieve data", message: "\(error.userInfo)")
}
}
func savePlanting() {
var id = Plantings.currentPlot
var plant = PlantManager.selected.rawValue
// save new planting
var managedContext = CoreDataManager.shared.managedObjectContext
let newPlot = Plot(context: managedContext)
newPlot.id = Int16(id)
newPlot.plant = Int16(plant)
newPlot.date = Date()
newPlot.mature = nil
Plantings.plantings.append(newPlot)
do {
try managedContext.save()
print("saved planting")
} catch {
// this should never be displayed but is here to cover the possibility
//showAlert(title: "Save failed", message: "Notice: Data has not successfully been saved.")
}
}
func deletePlanting() {
var id = Plantings.currentPlot
var managedContext = CoreDataManager.shared.managedObjectContext
let planting = Plantings.plantings.filter { $0.id == Int16(id) }.first
guard let toDelete = planting else {
print("didn't get item to delete")
return
}
managedContext.delete(toDelete)
do {
try managedContext.save()
print("delete successful")
} catch {
print("Failed to save")
}
loadPlots()
}
func saveWatering(id: Int) {
// save watering status for planting
var managedContext = CoreDataManager.shared.managedObjectContext
let planting = Plantings.plantings.filter { $0.id == Int16(id) }.first
guard let plot = planting else { return }
if plot.lastWatered == nil {
// plot has never been watered ie it's new
plot.lastWatered = Date()
plot.consecutiveWaterings = 1
print("new watering")
} else if PlantManager.needsWatering(date: plot.lastWatered) {
// plant getting new watering date
print("new watering date")
if let lastWatered = plot.lastWatered {
if Calendar.current.isDateInToday(lastWatered) == false {
// if it's a new day, plants can be watered
plot.consecutiveWaterings += 1
} else {
let differenceFromNowToLastWatering = PlantManager.checkDiff(date: lastWatered)
// if plot was last watered 12 hours or more ago and that last watering was within the current day, add to waterings
if differenceFromNowToLastWatering >= 12 && Calendar.current.isDateInToday(lastWatered) {
plot.consecutiveWaterings += 1
} else if let prevWatered = plot.prevWatered {
let differenceFromNowToPrevWatering = PlantManager.checkDiff(date: prevWatered)
// if plot was last watered less than 12 hours ago and that last watering was within the current day, add to waterings
if differenceFromNowToPrevWatering <= 12 && Calendar.current.isDateInToday(prevWatered) {
plot.consecutiveWaterings += 1
}
}
}
}
plot.prevWatered = plot.lastWatered
plot.lastWatered = Date()
if let currentStage = getStage(plot: plot) {
// determine maturity state, set if plant is mature and has no date
// remove mature date if erroneously set too soon
plot.mature = PlantManager.checkForValidMatureDate(currentStage: currentStage, plot: plot)
}
} else {
print("no need for water")
return
}
// exp gain from watering
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "waterPlant"), object: nil)
do {
try managedContext.save()
print("saved watering")
} catch {
// this should never be displayed but is here to cover the possibility
//showAlert(title: "Save failed", message: "Notice: Data has not successfully been saved.")
}
}
}
|
//
// Resources.swift
// saisaki
//
// Created by Chinh Vu on 3/7/20.
// Copyright © 2020 urameshiyaa. All rights reserved.
//
import UIKit
class Resources {
static let bundle: Bundle? = {
let bundle = Bundle(path: "/Library/Application Support/saisaki-resources.bundle")
if (bundle == nil) {
log("Cannot load resources")
}
return bundle
}()
static func image(named name: String) -> UIImage? {
return UIImage(named: name, in: bundle, compatibleWith: nil)
}
}
|
//
// Player.swift
// BingoApp
//
// Created by Zakk Hoyt on 11/14/15.
// Copyright © 2015 Zakk Hoyt. All rights reserved.
//
import UIKit
import MapKit
import CloudKit
class Player : NSObject, MKAnnotation {
var record : CKRecord!
var name : String!
var location : CLLocation!
weak var database : CKDatabase!
var assetCount = 0
// var healthyChoice : Bool {
// get {
// return record.objectForKey("HealthyOption").boolValue
// }
// }
//
// var kidsMenu: Bool {
// get {
// return record.objectForKey("KidsMenu").boolValue
// }
// }
init(record : CKRecord, database: CKDatabase) {
self.record = record
self.database = database
self.name = record.objectForKey("Name") as! String
self.location = record.objectForKey("Location") as! CLLocation
}
// func fetchRating(completion: (rating: Double, isUser: Bool) -> ()) {
// Model.sharedInstance().userInfo.userID() { userRecord, error in
// self.fetchRating(userRecord, completion: completion)
// }
// }
//
// func fetchRating(userRecord: CKRecordID!, completion: (rating: Double, isUser: Bool) -> ()) {
// //REPLACE THIS STUB
// completion(rating: 0, isUser: false)
// }
//
// func fetchNote(completion: (note: String!) -> ()) {
// Model.sharedInstance().fetchNote(self) { note, error in
// completion(note: note)
// }
// }
//
// func fetchPhotos(completion:(assets: [CKRecord]!)->()) {
// let predicate = NSPredicate(format: "Establishment == %@", record)
// let query = CKQuery(recordType: "EstablishmentPhoto", predicate: predicate);
// //Intermediate Extension Point - with cursors
// database.performQuery(query, inZoneWithID: nil) { results, error in
// if error == nil {
// self.assetCount = results.count
// }
// completion(assets: results as! [CKRecord])
// }
// }
//
// func changingTable() -> ChangingTableLocation {
// let changingTable = record?.objectForKey("ChangingTable") as? NSNumber
// var val:UInt = 0;
// if let changingTableNum = changingTable {
// val = changingTableNum.unsignedLongValue
// }
// return ChangingTableLocation(rawValue: val)
// }
//
// func seatingType() -> SeatingType {
// let seatingType = record?.objectForKey("SeatingType") as? NSNumber
// var val:UInt = 0;
// if let seatingTypeNum = seatingType {
// val = seatingTypeNum.unsignedLongValue
// }
// return SeatingType(rawValue: val)
// }
//
func loadCoverPhoto(completion:(photo: UIImage!) -> ()) {
// 1
dispatch_async(
dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)){
var image: UIImage!
// 2
if let asset = self.record.objectForKey("Avatar") as? CKAsset {
// 3
if let url: NSURL! = asset.fileURL {
let imageData = NSData(contentsOfFile: url.path!)!
// 4
image = UIImage(data: imageData)
}
}
// 5
completion(photo: image)
}
}
//MARK: - map annotation
var coordinate : CLLocationCoordinate2D {
get {
return location.coordinate
}
}
var title : String? {
get {
return name
}
}
} |
//
// SceneHelper.swift
// cube
//
// Created by 4 on 8/11/20.
// Copyright © 2020 XNO LLC. All rights reserved.
//
import SceneKit
struct SceneHelper {
func makeCamera(pos: SCNVector3, rot: SCNVector3) -> SCNNode {
// create and add a camera to the scene
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
cameraNode.camera?.usesOrthographicProjection = true
cameraNode.position = pos
cameraNode.eulerAngles.x = dToR(rot.x)
cameraNode.eulerAngles.y = dToR(rot.y)
cameraNode.eulerAngles.z = dToR(rot.z)
return cameraNode
}
func makeOmniLight() -> SCNNode {
let omniLightNode = SCNNode()
omniLightNode.light = SCNLight()
omniLightNode.light?.type = SCNLight.LightType.omni
omniLightNode.light?.color = UIColor(white: 1.0, alpha: 1.0)
omniLightNode.position = SCNVector3(x: 100, y: 250, z: -25)
omniLightNode.light?.attenuationStartDistance = 1000
return omniLightNode
}
func makeAmbiLight() -> SCNNode {
let ambiLightNode = SCNNode()
ambiLightNode.light = SCNLight()
ambiLightNode.light?.type = SCNLight.LightType.ambient
ambiLightNode.light?.color = UIColor(white: 1.0, alpha: 1.0)
return ambiLightNode
}
func makeBox(name: String, pos: SCNVector3, size: CGFloat, cmfr: CGFloat, color: UIColor) -> SCNNode {
let box = SCNBox(width: size, height: size, length: size, chamferRadius: cmfr)
let boxNode = SCNNode(geometry: box)
boxNode.name = name
boxNode.geometry?.firstMaterial?.diffuse.contents = color
boxNode.position = pos
return boxNode
}
func prepSCNView(scene: SCNScene) -> SCNView {
let scnView = SCNView()
scnView.scene = scene
scnView.allowsCameraControl = false
scnView.showsStatistics = false
scnView.backgroundColor = UIColor.systemBackground
return scnView
}
func dToR(_ degrees: Float) -> CGFloat {
return CGFloat(GLKMathDegreesToRadians(degrees))
}
func dToR(_ degrees: Float) -> Float {
return GLKMathDegreesToRadians(degrees)
}
}
|
//
// PopUpViewController.swift
// Evolution
//
// Created by Matthew Woodward on 4/15/20.
// Copyright © 2020 Matthew Woodward. All rights reserved.
//
import UIKit
class PopUpViewController: UIViewController {
@IBOutlet weak var popUpView: UIView!
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var speciesDescription: UILabel!
@IBOutlet weak var descriptionBox: UILabel!
var imageName:String = ""
var label1Text:String = ""
var descriptionText:String = ""
override func viewDidLoad() {
super.viewDidLoad()
showAnimation()
profileImage.image = UIImage(named: imageName)
label1.text = label1Text
speciesDescription.text = descriptionText
self.view.backgroundColor = UIColor.black.withAlphaComponent(0.8)
popUpView.layer.cornerRadius = 8.0
descriptionBox.layer.borderWidth = 4.0
descriptionBox.layer.cornerRadius = 8.0
}
@IBAction func closePopUp(_ sender: Any) {
removeAnimation()
}
func showAnimation() {
self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
self.view.alpha = 0.0
UIView.animate(withDuration: 0.25, animations: {
self.view.alpha = 1.0
self.view.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
})
}
func removeAnimation() {
UIView.animate(withDuration: 0.25, animations: {
self.view.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
self.view.alpha = 0.0
}, completion: {(finished: Bool) in
if(finished) {
self.view.removeFromSuperview()
}
})
}
}
|
//
// ViewController.swift
// CollectionViewDemo
//
// Created by Xueliang Zhu on 6/9/16.
// Copyright © 2016 kotlinchina. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let dataSource = DataSource()
let anotherDataSource = AnotherDataSource()
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = dataSource
collectionView.delegate = self
collectionView.allowsMultipleSelection = false
collectionView.registerNib(UINib(nibName: "Header2", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HEADER2")
}
@IBAction func change(sender: AnyObject) {
// collectionView.dataSource = anotherDataSource
// dataSource.images.removeAtIndex(0)
// collectionView.deleteItemsAtIndexPaths([NSIndexPath(forItem: 0, inSection: 0)])
// collectionView.performBatchUpdates({ [weak self] in
// self?.dataSource.images.removeAtIndex(0)
// self?.dataSource.images.removeAtIndex(1)
// self?.collectionView.deleteItemsAtIndexPaths([NSIndexPath(forItem: 0, inSection: 0), NSIndexPath(forItem: 1, inSection: 0)])
// }, completion: nil)
let vc = storyboard?.instantiateViewControllerWithIdentifier("Custom")
showViewController(vc!, sender: nil)
}
}
extension ViewController: UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, didHighlightItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath)
cell?.contentView.backgroundColor = UIColor.cyanColor()
}
func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath)
cell?.contentView.backgroundColor = nil
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionCell
cell?.selectImageView.image = UIImage(named: "Selected")
}
func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionCell
cell?.selectImageView.image = UIImage(named: "Empty")
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 40
}
}
|
//
// Cached.swift
// MEOKit
//
// Created by Mitsuhau Emoto on 2018/12/09.
// Copyright © 2018 Mitsuharu Emoto. All rights reserved.
//
import UIKit
/// データをキャッシュする
public class Cached: NSObject {
private static var shared: Cached = Cached()
private var cache: NSCache<AnyObject, AnyObject>!
private var pathCacheDir : String!
private let dirName:String = "CachesByCached"
private override init() {
super.init()
self.cache = NSCache()
self.cache.countLimit = 20
let paths = NSSearchPathForDirectoriesInDomains(.libraryDirectory,
.userDomainMask,
true)
let url = URL(string: paths[0])!
self.pathCacheDir = url.appendingPathComponent(dirName).absoluteString
self.makeTempDirs()
NotificationCenter.default.addObserver(self,
selector: #selector(didReceiveMemoryWarning(notification:)),
name: UIApplication.didReceiveMemoryWarningNotification,
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self,
name: UIApplication.didReceiveMemoryWarningNotification,
object: nil)
}
@objc func didReceiveMemoryWarning(notification: Notification){
self.clearCachesOnMemory()
}
private func clearCachesOnMemory(){
self.cache.removeAllObjects()
}
private func pathForUrl(urlString: String) -> URL{
let md5 = urlString.meo.md5
let path = URL(string: self.pathCacheDir)!.appendingPathComponent(md5)
return path
}
private func makeTempDirs(){
var isDir: ObjCBool = ObjCBool(false)
let exists: Bool = FileManager.default.fileExists(atPath: self.pathCacheDir,
isDirectory: &isDir)
if exists == false || isDir.boolValue == false{
do{
try FileManager.default.createDirectory(atPath: self.pathCacheDir,
withIntermediateDirectories: true,
attributes: nil)
}catch{
}
}
}
private func cachedEntity(key: String) -> CachedEntity?{
var data = self.cache.object(forKey: key.meo.md5 as AnyObject)
if data == nil{
data = CachedEntity.load(path: self.pathForUrl(urlString: key))
}
return (data as? CachedEntity)
}
private func setCachedEntity(cachedEntity: CachedEntity, key:String){
cachedEntity.write(path: self.pathForUrl(urlString: key))
self.cache.setObject(cachedEntity, forKey: key.meo.md5 as AnyObject)
}
}
// 公開メソッド
public extension Cached{
static func data(key: String) -> Data?{
let cached = Cached.shared
guard let cachedEntity = cached.cachedEntity(key: key) else {
return nil
}
return cachedEntity.data
}
static func string(key: String) -> String?{
let cached = Cached.shared
guard let cachedEntity = cached.cachedEntity(key: key) else {
return nil
}
return cachedEntity.string
}
static func image(url: URL) -> UIImage?{
return Cached.image(key: url.absoluteString)
}
static func image(key: String) -> UIImage?{
let cached = Cached.shared
guard let cachedEntity = cached.cachedEntity(key: key) else {
return nil
}
return cachedEntity.image
}
static func add(data: Data, key:String, validity:CachedValidity = .oneweek){
let cached = Cached.shared
let cachedEntity:CachedEntity = CachedEntity(data: data, validity: validity)
cached.setCachedEntity(cachedEntity: cachedEntity, key: key)
}
static func add(string: String, key:String, validity:CachedValidity = .oneweek) {
let cached = Cached.shared
let cachedEntity:CachedEntity = CachedEntity(string: string, validity: validity)
cached.setCachedEntity(cachedEntity: cachedEntity, key: key)
}
static func add(image: UIImage, url:URL, validity:CachedValidity = .oneweek) {
Cached.add(image: image, key: url.absoluteString, validity:validity)
}
static func add(image: UIImage, key:String, validity:CachedValidity = .oneweek) {
var imageFormat:CachedImageFormat = .jpg
if key.hasSuffix(".jpg") || key.hasSuffix(".jpeg"){
imageFormat = .jpg
}else if key.hasSuffix(".png"){
imageFormat = .png
}
let cached = Cached.shared
let cachedEntity:CachedEntity = CachedEntity(image: image,
imageFormat: imageFormat,
validity: validity)
cached.setCachedEntity(cachedEntity: cachedEntity, key: key)
}
static func delete(key: String){
let cached = Cached.shared
cached.cache.removeObject(forKey: key.meo.md5 as AnyObject)
CachedEntity.delete(path: cached.pathForUrl(urlString: key))
}
static func deleteAll(){
let cached = Cached.shared
cached.clearCachesOnMemory()
if FileManager.default.fileExists(atPath: cached.pathCacheDir){
do{
try FileManager.default.removeItem(atPath: cached.pathCacheDir)
cached.makeTempDirs()
}catch{
}
}
}
}
|
//
// CakeImageLoader.swift
// CakeClub
//
// Created by Vinicius Leal on 27/09/2020.
// Copyright © 2020 Vinicius Leal. All rights reserved.
//
import UIKit
public protocol CakeImageLoader {
func loadImage(from url: URL, into view: UIImageView)
}
|
//
// ListManager.swift
// FoodForFueled-Reactive
//
// Created by Pulkit Vaid on 19/04/17.
// Copyright © 2017 Pulkit Vaid. All rights reserved.
//
import Foundation
import UIKit
import ReactiveCocoa
import ReactiveSwift
class TableManager: NSObject, UITableViewDataSource, UITableViewDelegate {
var dataSource: Array<CellModel>?
//MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellModel = dataSource?[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: cellModel!.reuseIdententifier, for: indexPath)
if let cell = cell as? CellConfigurable {
cell.configureWithModel(cellModel: cellModel)
}
return cell
}
}
|
import UIKit
struct WordData {
var answer = ""
var wordIndex = -1
init(answer: String = "",
wordIndex: Int = -1) {
self.answer = answer
self.wordIndex = wordIndex
}
}
//func palindromePairs(_ words: [String]) -> [[Int]] {
//
// var dic = [String: WordData]()
//
// for (index, word) in words.enumerated() {
// var string = ""
// for char in word.reversed() {
// string += "\(char)"
// }
// let data = WordData.init(answer: string, wordIndex: index)
//
// dic[word] = data
// }
//
// var answer = [[Int]]()
// for word in words {
// if let data = dic[word], words.contains(data.answer), let answerIndex = words.firstIndex(of: data.answer), answerIndex != data.wordIndex {
// answer.append([data.wordIndex, answerIndex])
// }
// }
//
// return answer
//}
func palindromePairs(_ words: [String]) -> [[Int]] {
var answer = [[Int]]()
// 翻转
var dic = [String: String]()
for word in words {
var string = ""
for char in word.reversed() {
string += "\(char)"
}
dic[word] = string
}
for (indexWord, word) in words.enumerated() {
for (indexOther, otherWord) in words.enumerated() {
if indexWord == indexOther {
continue
}
// 相等
if word.count == otherWord.count {
let reverOther = dic[otherWord]
if word == reverOther {
answer.append([indexWord, indexOther])
}
} else if word.count > otherWord.count {
let reverOther = dic[otherWord]
let rangeIndex = word.index(word.startIndex, offsetBy: word.count)
let word_1 = word[word.startIndex...rangeIndex]
let word_2 = word[rangeIndex...(word.endIndex)]
if "\(word_1)" == reverOther, isPalind(word: "\(word_2)") {
answer.append([indexWord, indexOther])
}
} else if word.count < otherWord.count {
let reverWord = dic[word]
let rangeIndex = otherWord.index(otherWord.startIndex, offsetBy: otherWord.count)
let other_1 = otherWord[otherWord.startIndex...rangeIndex]
let other_2 = otherWord[rangeIndex...(word.endIndex)]
if "\(other_1)" == reverWord, isPalind(word: "\(other_2)") {
answer.append([indexWord, indexOther])
}
}
}
}
return answer
}
func isPalind(word: String?) -> Bool {
guard let string = word, !string.isEmpty else {
return false
}
let stringArray = Array(string)
var left = 0
var right = stringArray.count - 1
// print(word!, stringArray)
while left < right {
if stringArray[left] != stringArray[right] {
// print(string, "不符合")
return false
}
left += 1
right -= 1
}
return true
}
let words = ["abcd","dcba","lls","s","sssll"]
print(NSDate())
print(palindromePairs(words))
print(NSDate())
|
//
// NewYorkTimesViewModel.swift
// CovidAlert
//
// Created by Matthew Garlington on 12/27/20.
//
import Foundation
import Alamofire
import SwiftyJSON
class NewYorkTimesViewModel: ObservableObject {
@Published var nytimesnews: NYTimes?
init() {
//network code
guard let url = URL(string: "https://api.nytimes.com/svc/search/v2/articlesearch.json?q=Covid&api-key=u8ZvUFJdNbwzYayjscegwovL26WtlPfB") else { return }
URLSession.shared.dataTask(with: url) { (data, resp, err) in
DispatchQueue.main.async {
guard let data = data else { return }
do {
self.nytimesnews = try JSONDecoder().decode(NYTimes?.self, from: data)
print(self.nytimesnews?.response.docs.count)
print(self.nytimesnews?.status)
// print(self.nytimesnews?.response.docs[0].byline.original)
} catch let jsonError {
print("Decoding failed for New york Times News", jsonError)
}
}
}.resume()
}
}
|
//
// BaseModelProtocol.swift
// mobiita
//
// Created by 三木俊作 on 2016/12/10.
// Copyright © 2016年 Shunsaku Miki. All rights reserved.
//
import Foundation
/**
各モデルが準拠しなくてはいけないプロトコル
これを準拠しないとBaseContainerクラスを継承したContainerを実装できない
*/
protocol BaseModelProtocol {
}
|
//
// UIButton+Category.swift
// SwiftCaiYIQuan
//
// Created by 朴子hp on 2018/7/7.
// Copyright © 2018年 朴子hp. All rights reserved.
//
import UIKit
extension UIButton {
/* 便利构造函数:
1> convenience开头
2> 在构造函数中必须明确调用一个设计的构造函数(self)
*/
//MARK: 单独文字形式
convenience init(title : String , titleColor : UIColor , font : CGFloat) {
//1.实例化当前对象—因为在便利构造函数中是不负责创建对象的,所以必须调用本身的构造函数来创建对象后
//2.访问对象访问属性
self.init()
self.setTitle(title, for: .normal)
self.setTitleColor(titleColor, for: .normal)
self.titleLabel?.font = UIFont.systemFont(ofSize: font)
}
convenience init(title : String , titleColor : UIColor , font : CGFloat, backgroundColor : UIColor) {
self.init()
self.setTitle(title, for: .normal)
self.backgroundColor = backgroundColor
self.setTitleColor(titleColor, for: .normal)
self.titleLabel?.font = UIFont.systemFont(ofSize: font)
}
convenience init(title : String , titleColor : UIColor , font : CGFloat, backgroundColor : UIColor, cornerRadius: CGFloat) {
self.init()
self.setTitle(title, for: .normal)
self.backgroundColor = backgroundColor
self.setTitleColor(titleColor, for: .normal)
self.titleLabel?.font = UIFont.systemFont(ofSize: font)
//切圆角
self.layer.cornerRadius = cornerRadius
self.layer.masksToBounds = true
}
//MARK: 单独图片形式
convenience init(backgroundImageName: String) {
self.init()
self.setBackgroundImage(UIImage.init(named: backgroundImageName), for: .normal)
}
//MARK: 图文形式分两种 1> 图文并列
convenience init(title: String, titleColor: UIColor, imageName: String) {
self.init()
self.setTitle(title, for: .normal)
self.setTitleColor(titleColor, for: .normal)
self.titleLabel?.sizeToFit()
}
//MARK: 图文形式分两种 2> 以图为背景
convenience init(title: String, titleColor: UIColor, font: CGFloat, backgroundImageName: String) {
self.init()
self.setTitle(title, for: .normal)
self.setTitleColor(titleColor, for: .normal)
self.titleLabel?.font = UIFont.systemFont(ofSize: font)
}
}
|
//
// File.swift
// Pro App
//
// Created by Grosu Alexandru on 1/31/20.
// Copyright © 2020 Scripchin Mihail. All rights reserved.
//
import Foundation
struct Client:{
var id: Int
var nume:String
func vjhv
}
|
import Foundation
import Bow
// MARK: Optics extensions
public extension ArrayK {
/// Provides a polymorphic Iso between ArrayK and Option of NonEmptyArray.
///
/// - Returns: A polymorphic Iso between ArrayK and Option of NonEmptyArray.
static func toPOptionNEA<B>() -> PIso<ArrayK<A>, ArrayK<B>, Option<NonEmptyArray<A>>, Option<NonEmptyArray<B>>> {
return PIso<ArrayK<A>, ArrayK<B>, Option<NonEmptyArray<A>>, Option<NonEmptyArray<B>>>(
get: { nea in nea.isEmpty ?
Option<NonEmptyArray<A>>.none() :
Option<NonEmptyArray<A>>.some(NonEmptyArray<A>(head: nea.asArray[0], tail: Array(nea.asArray.dropFirst()))) },
reverseGet: { option in
option.fold(ArrayK<B>.empty, { nea in ArrayK<B>(nea.all()) })
})
}
/// Provides an Iso between ArrayK and Option of NonEmptyArray
static var toOptionNEA: Iso<ArrayK<A>, Option<NonEmptyArray<A>>> {
return toPOptionNEA()
}
/// Provides an AffineTraversal to retrieve the first element of an ArrayK
static var head: AffineTraversal<ArrayK<A>, A> {
return firstOption
}
/// Provides an AffineTraversal to retrieve the tail of an ArrayK
static var tail: AffineTraversal<ArrayK<A>, ArrayK<A>> {
return tailOption
}
}
// MARK: Optics extensions
public extension Array {
/// Provides a polymorphic Iso between Array and ArrayK
///
/// - Returns: A polymorphic Iso between Array and ArrayK
static func toPArrayK<B>() -> PIso<Array<Element>, Array<B>, ArrayK<Element>, ArrayK<B>> {
return PIso<Array<Element>, Array<B>, ArrayK<Element>, ArrayK<B>>(
get: ArrayK<Element>.init,
reverseGet: { arrayK in arrayK.asArray })
}
/// Provides an Iso between Array and ArrayK
static var toArrayK: Iso<Array<Element>, ArrayK<Element>> {
return toPArrayK()
}
/// Provides an AffineTraversal to retrieve the first element of an Array
static var head: AffineTraversal<Array<Element>, Element> {
return firstOption
}
/// Provides an AffineTraversal to retrieve the tail of an Array.
static var tail: AffineTraversal<Array<Element>, Array<Element>> {
return tailOption
}
}
|
//
// AnswersModels.swift
// StackOverflow-Interview
//
// Created by Neill Barnard on 2020/06/21.
// Copyright © 2020 Neill Barnard. All rights reserved.
//
import Foundation
struct AnswersInputParametersModel {
var questionId:Int
var order:String
var sort: String
}
struct allAnswersItems: Decodable{
var items: [answersModel]
}
struct answersModel: Decodable {
var owner : OwnerObjectModel?
var is_accepted: Bool
var score: Int
var last_activity_date: Int
var last_edit_date:Int?
var creation_date:Int
var answer_id:Int
var question_id:Int
var title:String
var body:String
}
|
//
// FunctionalCollectionData+UICollectionViewDataSource.swift
// FunctionalTableData
//
// Created by Geoffrey Foster on 2019-03-08.
// Copyright © 2019 Shopify. All rights reserved.
//
import UIKit
extension FunctionalCollectionData {
class DataSource: NSObject, UICollectionViewDataSource {
private let data: TableData
init(data: TableData) {
self.data = data
}
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return data.sections.count
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.sections[section].rows.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let sectionData = data.sections[indexPath.section]
let row = indexPath.item
let cellConfig = sectionData[row]
let cell = cellConfig.dequeueCell(from: collectionView, at: indexPath)
let accessibilityIdentifier = ItemPath(sectionKey: sectionData.key, itemKey: cellConfig.key).description
cellConfig.accessibility.with(defaultIdentifier: accessibilityIdentifier).apply(to: cell)
cellConfig.update(cell: cell, in: collectionView)
let style = cellConfig.style ?? CellStyle()
style.configure(cell: cell, at: indexPath, in: collectionView)
return cell
}
public func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
// Should only ever be moving within section
assert(sourceIndexPath.section == destinationIndexPath.section)
// Update internal state to match move
let cell = data.sections[sourceIndexPath.section].rows.remove(at: sourceIndexPath.item)
data.sections[destinationIndexPath.section].rows.insert(cell, at: destinationIndexPath.item)
data.sections[sourceIndexPath.section].didMoveRow?(sourceIndexPath.item, destinationIndexPath.item)
}
public func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
return data.sections[indexPath]?.actions.canBeMoved ?? false
}
}
}
|
//
// AboutTitleTableViewCell.swift
// Brizeo
//
// Created by Roman Bayik on 3/14/17.
// Copyright © 2017 Kogi Mobile. All rights reserved.
//
import UIKit
class AboutTitleTableViewCell: UITableViewCell {
// MARK: - Properties
@IBOutlet weak var firstLabel: UILabel! /* label for first passion */ {
didSet {
firstLabel.text = LocalizableString.First.localizedString
}
}
@IBOutlet weak var secondLabel: UILabel! /* label for second passion */ {
didSet {
secondLabel.text = LocalizableString.Second.localizedString
}
}
@IBOutlet weak var thirdLabel: UILabel! /* label for third passion */ {
didSet {
thirdLabel.text = LocalizableString.Third.localizedString
}
}
}
|
//
// ViewController.swift
// coder-swag
//
// Created by Zeynal Zeynalov on 6/12/18.
// Copyright © 2018 Zeynal Zeynalov. All rights reserved.
//
import UIKit
class CategoriesVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var categoryTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
categoryTable.dataSource = self
categoryTable.delegate = self
}
//Method for identifying number (quantity) of Rows needed for tableView in order to display as much data as per quantity of rows and as much as rows as quantity of data
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return DataService.instance.getCategories().count
}
// Method to perform followings:
// - indentify cell For Row at given indexPath
// - dequeueing of data from database into the reusable constant cell
// - create constant category with categories for each row
// - update View of category cells with provision of data at constant categpry
// - return all above mentioned data into the constant cell
//Row display. Implementers should always try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier;
//Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "CategoryCell") as? CategoryCell {
let category = DataService.instance.getCategories()[indexPath.row]
cell.updateViews(category: category)
return cell
}
else {
return CategoryCell()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let category = DataService.instance.getCategories()[indexPath.row]
performSegue(withIdentifier: "ProductsVC", sender: category)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let productVC = segue.destination as? ProductsVC {
let barBtn = UIBarButtonItem()
barBtn.title = ""
navigationItem.backBarButtonItem = barBtn
assert(sender as? Category != nil)
productVC.initProducts(category: sender as! Category)
}
}
}
|
//
// CarTrackRepoApp.swift
// CarTrackRepo
//
// Created by Piraba Nagkeeran on 5/6/21.
//
import SwiftUI
@main
struct CarTrackRepoApp: App {
var body: some Scene {
WindowGroup {
EntryView()
.environmentObject(AppState())
}
}
}
|
//
// ExampleContentView.swift
// Template
//
// Created by Domagoj Kulundzic on 27/05/2019.
//
import UIKit
class ExampleContentView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - Private Methods
private extension ExampleContentView {
func setupViews() {
backgroundColor = .red
}
}
|
//
// ListItem.swift
// SwiftDemo003
//
// Created by chenhui on 2018/1/2.
// Copyright © 2018年 vhuichen. All rights reserved.
//
import Foundation
class ListItem: NSObject {
var id:String?
var image:String?
var title:String?
var date:Date!
init(id:String?, image:String?, title:String?, date:Date!) {
self.id = id
self.image = image
self.title = title
self.date = date
}
}
|
//
// Updating.swift
// BeastlySearch
//
// Created by Trevor Beasty on 11/14/17.
// Copyright © 2017 Trevor Beasty. All rights reserved.
//
import Foundation
protocol Updating {
func update()
}
|
//
// AngryProfessor.swift
// Datasnok
//
// Created by Vladimir Urbano on 6/28/16.
// Copyright © 2016 Vladimir Urbano. All rights reserved.
//
/*
A Discrete Mathematics professor has a class of students. Frustrated with their lack of discipline, he decides to cancel class if fewer than students are present when class starts.
Given the arrival time of each student, determine if the class is canceled.
Input Format
The first line of input contains , the number of test cases.
Each test case consists of two lines. The first line has two space-separated integers, (students in the class) and (the cancelation threshold).
The second line contains space-separated integers () describing the arrival times for each student.
Note: Non-positive arrival times () indicate the student arrived early or on time; positive arrival times () indicate the student arrived minutes late.
Output Format
For each test case, print the word YES if the class is canceled or NO if it is not.
Constraints
Note
If a student arrives exactly on time , the student is considered to have entered before the class started.
Sample Input
2
4 3
-1 -3 4 2
4 2
0 -1 2 1
Sample Output
YES
NO
Explanation
For the first test case, . The professor wants at least students in attendance, but only have arrived on time ( and ). Thus, the class is canceled.
For the second test case, . The professor wants at least students in attendance, and there are who have arrived on time ( and ). Thus, the class is not canceled.
*/
class AngryProfessor {
init() {
// number of test cases
let t = Int(readLine()!)!
for _ in 1 ... t {
// total of students and cancelation threshold
var arr = readLine()!.componentsSeparatedByString(" ").map{ Int(String($0))! }
let k = arr[1]
// arrival times
arr = readLine()!.componentsSeparatedByString(" ").map{ Int(String($0))! }
let o = arr.filter{ $0 <= 0 }.count
if o < k {
print("YES")
} else {
print("NO")
}
}
}
}
|
//
// IntExtension.swift
// Vriends
//
// Created by Geart Otten on 15/06/2018.
// Copyright © 2018 Tjerk Dijkstra. All rights reserved.
//
import Foundation
extension Int {
static func random(range: CountableClosedRange<Int>) -> Int {
let MAX_RANDOM_VALUE: UInt32 = UInt32(range.upperBound)
let MIN_RANDOM_VALUE: UInt32 = UInt32(range.lowerBound)
return Int(arc4random_uniform(MAX_RANDOM_VALUE - MIN_RANDOM_VALUE) + MIN_RANDOM_VALUE)
}
}
|
//
// SampleDatabaseController.swift
// SlouchDB_Example
//
// Created by Allen Ussher on 11/12/17.
// Copyright © 2017 Ussher Press. All rights reserved.
//
import Foundation
import SlouchDB
extension Notification.Name {
static let didInsertPeople = Notification.Name(rawValue: "didInsertPeople")
static let didModifyPeople = Notification.Name(rawValue: "didModifyPeople")
}
class SampleDatabaseController {
var database: Database
var people: [Person] = []
init(database: Database) {
self.database = database
self.database.delegate = self
loadPeople()
}
private func person(from object: DatabaseObject) -> Person {
assert(object.identifier != DatabaseObject.kDeltaIdentifier)
// Some DatabaseObjects may be incomplete because they are merely deltas but we
// might accidentally treat them as 'inserts' if the original object does not yet
// exist. Therefore, we must check the properties to make sure we have them all
// or else create default values like below.
let name = object.properties[Person.namePropertyKey] ?? "<name>"
let weight = Int(object.properties[Person.weightPropertyKey] ?? "0")!
let age = Int(object.properties[Person.agePropertyKey] ?? "20")!
return Person(identifier: object.identifier,
name: name,
weight: weight,
age: age)
}
private func loadPeople() {
let objects = database.fetchObjects()
people = objects.map { person(from: $0) }
}
func add(person: Person) {
let properties: DatabaseObjectPropertiesDictionary = [
Person.weightPropertyKey : "\(person.weight)",
Person.agePropertyKey : "\(person.age)",
Person.namePropertyKey : person.name,
]
let now = Date()
let object = DatabaseObject(identifier: person.identifier,
creationDate: now,
lastModifiedDate: now,
properties: properties)
_ = database.insert(object: object)
}
func modifyPerson(identifier: String, properties: DatabaseObjectPropertiesDictionary) {
_ = database.update(identifier: identifier, properties: properties)
}
}
extension SampleDatabaseController: DatabaseDelegate {
func database(_ database: Database, didUpdateWithDeltas deltas: [String : DatabaseObject]) {
var modifiedPeople: [Person] = []
var modifiedProperties: [ [String] ] = []
var modifiedIndexes: [Int] = []
var newPeople: [Person] = []
let beforeCount = self.people.count
for delta in deltas {
let identifier = delta.key
let object = delta.value
if let index = people.index(where: { $0.identifier == identifier }) {
// modified entry
var person = people[index]
var modifiedPropertiesForPerson: [String] = []
for property in object.properties {
switch property.key {
case Person.weightPropertyKey:
person.weight = Int(property.value)!
case Person.agePropertyKey:
person.age = Int(property.value)!
case Person.namePropertyKey:
person.name = property.value
default:
assert(false)
}
modifiedPropertiesForPerson.append(property.key)
}
people[index] = person
modifiedProperties.append(modifiedPropertiesForPerson)
modifiedIndexes.append(index)
modifiedPeople.append(person)
} else {
// new entry
let person = self.person(from: object)
newPeople.append(person)
people.append(person)
}
}
let afterCount = self.people.count
if modifiedPeople.count > 0 {
let modifyUserInfo: [String : Any] = ["people": modifiedPeople,
"properties" : modifiedProperties,
"indexes" : modifiedIndexes]
NotificationCenter.default.post(name: .didModifyPeople, object: self, userInfo: modifyUserInfo)
}
if newPeople.count > 0 {
let insertedUserInfo: [String : Any] = ["people": newPeople,
"range" : Range(beforeCount...afterCount-1)]
NotificationCenter.default.post(name: .didInsertPeople, object: self, userInfo: insertedUserInfo)
}
}
func database(_ database: Database, saveLocalJournal localJournal: Journal) {
}
func database(_ database: Database, saveJournalCache journalCache: MultiplexJournalCache) {
}
func database(_ database: Database, saveDatabaseState databaseState: DatabaseObjectState) {
}
}
|
//
// Route.swift
// Routing
//
// Created by Dave Hardiman on 01/03/2016.
// Copyright © 2016 Ordnance Survey. All rights reserved.
//
import Foundation
import CoreLocation
/// Represents a parsed route returned from the routing API
@objc(OSRoute)
public final class Route: NSObject {
/// The CRS for the route
public let crs: CoordinateReferenceSystem
public var crsString: String {
return crs.rawValue
}
/// The distance of the route
public let distance: Double
/// Time taken to cover the route
public let time: Double
/// The instructions for the route
public let instructions: [Instruction]
/// The bounding box that covers the route
public let bbox: BoundingBox
/// The points making up the route
public let points: [Point]
/// The coordinates making up the route.
/// Note, this value is nonsense if the crs for the route isn't WGS:84.
public var coordinates: [CLLocationCoordinate2D] {
return points.map { CLLocationCoordinate2D(os_point: $0) }
}
/// The coordinates making up the route, wrapped in NSValue so as to be accessible from Objective-C
/// Note, this value is nonsense if the crs for the route isn't WGS:84.
public var coordinateValues: [NSValue] {
return points.map { NSValue.os_valueWithCoordinate(CLLocationCoordinate2D(os_point: $0)) }
}
init(crs: CoordinateReferenceSystem, distance: Double, time: Double, instructions: [Instruction], bbox: BoundingBox, points: [Point]) {
self.crs = crs
self.distance = distance
self.time = time
self.instructions = instructions
self.bbox = bbox
self.points = points
super.init()
}
}
|
import BuildStatusChecker
struct ConfigurationMock {
static let configuration = BitriseConfiguration(
authToken: "authToken",
baseUrl: "baseUrl",
appSlug: "appSlug",
orgSlug: "orgSlug"
)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.