text
stringlengths 8
1.32M
|
|---|
//
// R.reuseIdentifier.swift
// YumaApp
//
// Created by Yuma Usa on 2018-06-18.
// Copyright © 2018 Yuma Usa. All rights reserved.
//
import Foundation
extension R
{
struct reuseIdentifier
{
fileprivate init() {}
}
}
|
//
// MockRSSUrlConstructor.swift
// AlbumRSSTests
//
// Created by Gavin Li on 8/16/20.
// Copyright © 2020 Gavin Li. All rights reserved.
//
import Foundation
@testable import AlbumRSS
class MockRSSUrlConstructor: UrlConstructorProtocol {
private let mockFile = "mockRSS"
func rssFeedUrl() -> URL? {
let bundle = Bundle(for: MockRSSUrlConstructor.self)
guard let path = bundle.path(forResource: mockFile, ofType: "json") else {
fatalError("Invalid URL")
}
let url = URL(fileURLWithPath: path)
return url
}
func rssFeedUrlString() -> String {
mockFile
}
}
|
//
// LPaimUtilsOperators.swift
// LPaimUtils
//
// Created by LPaimUtils on 29/10/14.
// Copyright (c) 2014 LPaimUtils. All rights reserved.
//
import Foundation
prefix operator ~ {}
/**
:returns: A NSDictionary with the object atributtes
*/
prefix public func ~( _object: AnyObject) -> NSDictionary{
if(_object.classForCoder.description() == "NSDictionary"){
return _object as! NSDictionary
}
var dictionary: NSMutableDictionary = NSMutableDictionary()
for(var i = 0; i < reflect(_object).count; ++i){
if(reflect(_object)[i].0 == "super"){
continue
}
var valor: AnyObject? = _object.valueForKey("\(reflect(_object)[i].0)")
dictionary.setValue(valor, forKey: reflect(_object)[i].0)
}
return dictionary
}
infix operator <-- {associativity left precedence 140}
/**
Populate a left object with the attributes of a right object
*/
public func <-- (left: AnyObject, right: AnyObject){
var dicionarioDeDados = ~right
for field in dicionarioDeDados.allKeys {
if(dicionarioDeDados.valueForKey(field as! String)!.classForCoder.description() == "NSDictionary"){
if(left.respondsToSelector(Selector(field as! String))){
var obj: AnyObject? = left.valueForKey(field as! String)
if(obj != nil){
obj! <-- dicionarioDeDados.valueForKey(field as! String)!
}
}
continue
}
if( dicionarioDeDados.valueForKey(field as! String)!.classForCoder.description() == "NSNull"){
continue
}
if(left.respondsToSelector(Selector(field as! String))){
left.setValue(dicionarioDeDados.valueForKey(field as! String), forKey: field as! String)
}else if(left.respondsToSelector(Selector("_" + (field as! String)))){
left.setValue(dicionarioDeDados.valueForKey(field as! String), forKey: "_" + (field as! String))
}
}
}
|
import Cocoa
let PanelSize = 120
let NUMAXES = 2
let NUMPANELS = 4
var panelIndex = Int()
var selectIndex = Int()
var controlPickerSelection = Int()
var vcControl:ControlViewController! = nil
var panelList:[ControlPanelView]! = nil
var panelRect:[NSRect]! = nil
class ControlViewController: NSViewController {
@IBOutlet var panel1: ControlPanelView!
@IBOutlet var panel2: ControlPanelView!
@IBOutlet var panel3: ControlPanelView!
@IBOutlet var panel4: ControlPanelView!
func launchPopOver(_ pIndex:Int, _ sIndex:Int) {
panelIndex = pIndex
selectIndex = sIndex
vc.presentPopover(self.view,"ControlPickerVC")
}
@IBAction func x1(_ sender: NSButton) { launchPopOver(0,0) }
@IBAction func y1(_ sender: NSButton) { launchPopOver(0,1) }
@IBAction func x2(_ sender: NSButton) { launchPopOver(1,0) }
@IBAction func y2(_ sender: NSButton) { launchPopOver(1,1) }
@IBAction func x3(_ sender: NSButton) { launchPopOver(2,0) }
@IBAction func y3(_ sender: NSButton) { launchPopOver(2,1) }
@IBAction func x4(_ sender: NSButton) { launchPopOver(3,0) }
@IBAction func y4(_ sender: NSButton) { launchPopOver(3,1) }
@IBAction func helpPressed(_ sender: NSButton) { showHelpPage(view,.Control) }
override func viewDidLoad() {
super.viewDidLoad()
vcControl = self
panelList = [ panel1,panel2,panel3,panel4 ]
panelRect = [ // UL corner, flipped Y
NSRect(x:020, y:320, width:PanelSize, height:PanelSize),
NSRect(x:150, y:320, width:PanelSize, height:PanelSize),
NSRect(x:020, y:166, width:PanelSize, height:PanelSize),
NSRect(x:150, y:166, width:PanelSize, height:PanelSize)]
for i in 0 ..< 4 { panelList[i].panelID = i }
}
// so user can issue commands while viewing the help page
override func keyDown(with event: NSEvent) {
func alterValueViaArrowKeys(_ axis:Int, _ direction:Int) {
decodeSelectionIndex(getPanelWidgetIndex(panelIndex,axis))
if winHandler.widgetPointer(selectedWindow).data[selectedRow].alterValue(direction) {
winHandler.refreshWidgetsAndImage()
refreshControlPanels()
}
}
updateModifierKeyFlags(event)
vc.widget.updateAlterationSpeed(event)
switch Int32(event.keyCode) {
case LEFT_ARROW : alterValueViaArrowKeys(0,-1); return
case RIGHT_ARROW : alterValueViaArrowKeys(0,+1); return
case UP_ARROW : alterValueViaArrowKeys(1,-1); return
case DOWN_ARROW : alterValueViaArrowKeys(1,+1); return
case 48 : panelIndex = (panelIndex + 1) % 4; refreshControlPanels() // Tab
default : break
}
vc.keyDown(with: event)
}
override func keyUp(with event: NSEvent) {
vc.keyUp(with: event)
}
//MARK: -
func widgetSelectionMade() {
setPanelWidgetIndex(panelIndex,selectIndex,controlPickerSelection)
panelList[panelIndex].refresh()
}
func refreshControlPanels() { for p in panelList { p.refresh() }}
func checkAllWidgetIndices() {
for i in 0 ..< NUMPANELS {
for j in 0 ..< NUMAXES {
if !vc.widget.isLegalControlPanelIndex(getPanelWidgetIndex(i,j)) { setPanelWidgetIndex(i,j,0) }
}
}
}
}
//MARK: -
// save encoded picker selection for X or Y axis of specified panel
func setPanelWidgetIndex(_ panelIndex:Int, _ axisIndex:Int, _ value:Int) {
switch panelIndex * 2 + axisIndex {
case 0 : vc.control.panel00 = Int32(value)
case 1 : vc.control.panel01 = Int32(value)
case 2 : vc.control.panel10 = Int32(value)
case 3 : vc.control.panel11 = Int32(value)
case 4 : vc.control.panel20 = Int32(value)
case 5 : vc.control.panel21 = Int32(value)
case 6 : vc.control.panel30 = Int32(value)
case 7 : vc.control.panel31 = Int32(value)
default : break
}
}
// retrieve encoded picker selection from X or Y axis of specified panel
func getPanelWidgetIndex(_ panelIndex:Int, _ axisIndex:Int) -> Int {
var index = Int()
switch panelIndex * 2 + axisIndex {
case 0 : index = Int(vc.control.panel00)
case 1 : index = Int(vc.control.panel01)
case 2 : index = Int(vc.control.panel10)
case 3 : index = Int(vc.control.panel11)
case 4 : index = Int(vc.control.panel20)
case 5 : index = Int(vc.control.panel21)
case 6 : index = Int(vc.control.panel30)
case 7 : index = Int(vc.control.panel31)
default : index = 0
}
return index
}
//MARK: -
var selectedRow = Int()
var selectedWindow = Int()
func decodeSelectionIndex(_ selection:Int) {
selectedRow = decodePickerSelection(selection).0
selectedWindow = decodePickerSelection(selection).1
if (selectedWindow == 0) && vc.control.isStereo { selectedRow += 1 } // 'Parallax' widget offset
}
//MARK: -
//MARK: -
class ControlPanelView: NSView {
var panelID = Int()
var ratio:[Float] = [ 0,0 ]
func refresh() {
for i in 0 ..< NUMAXES {
decodeSelectionIndex(getPanelWidgetIndex(panelID,i))
ratio[i] = winHandler.widgetPointer(selectedWindow).data[selectedRow].getRatio()
}
setNeedsDisplay(self.bounds)
}
override func keyDown(with event: NSEvent) {
switch event.charactersIgnoringModifiers!.uppercased() {
case " " : spaceKeyDown = true
default : vc.keyDown(with: event)
}
}
override func keyUp(with event: NSEvent) {
spaceKeyDown = false
vc.keyUp(with: event)
}
var isMouseDown:Bool = false
var spaceKeyDown:Bool = false
var xCoord = Float()
var oldXCoord = Float()
var yCoord = Float()
var oldYCoord = Float()
func clamp(_ value:Float, _ min:Float, _ max:Float) -> Float {
if value < min { return min }
if value > max { return max }
return value
}
override func mouseDown(with event: NSEvent) {
let pt:NSPoint = event.locationInWindow
if !isMouseDown {
for i in 0 ..< NUMPANELS {
let p = panelRect[i]
if pt.x >= p.minX && pt.x < p.minX + CGFloat(PanelSize) &&
pt.y <= p.minY && pt.y > p.minY - CGFloat(PanelSize) {
panelIndex = i
isMouseDown = true
}
}
}
if isMouseDown {
let pSize = Float(PanelSize)
let p = panelRect[panelIndex]
decodeSelectionIndex(getPanelWidgetIndex(panelIndex,0))
oldXCoord = xCoord
xCoord = Float(pt.x - p.minX)
if spaceKeyDown { xCoord = oldXCoord + (xCoord - oldXCoord) * 0.01 }
xCoord = clamp(xCoord,0,pSize)
winHandler.widgetPointer(selectedWindow).data[selectedRow].setRatio(xCoord / pSize)
decodeSelectionIndex(getPanelWidgetIndex(panelIndex,1))
oldYCoord = yCoord
yCoord = Float(p.minY - pt.y)
if spaceKeyDown { yCoord = oldYCoord + (yCoord - oldYCoord) * 0.01 }
yCoord = clamp(yCoord,0,pSize)
winHandler.widgetPointer(selectedWindow).data[selectedRow].setRatio(yCoord / pSize)
winHandler.refreshWidgetsAndImage()
refresh()
}
}
override func mouseDragged(with event: NSEvent) { mouseDown(with:event) }
override func mouseUp(with event: NSEvent) {
isMouseDown = false
}
override func draw(_ rect: NSRect) {
let cr = (panelID == panelIndex) ? CGFloat(0.3) : CGFloat(0.1)
let c = CGFloat(0.1)
NSColor(red:cr, green:c, blue:c, alpha:1).set()
NSBezierPath(rect:bounds).fill()
func legend(_ index:Int) {
let axisString:[String] = [ "X","Y" ]
let tableString:[String] = [ "Main","Light","Color" ]
var str = String()
let encodedSelection = getPanelWidgetIndex(panelID,index)
var r = decodePickerSelection(encodedSelection).0
let w = decodePickerSelection(encodedSelection).1
if w == 0 && vc.control.isStereo { r += 1 } // 'parallax' widget offset
str = String(format:"%@: %@ %@",axisString[index],tableString[w],winHandler.stringForRow(w,r))
drawText(5,5 + CGFloat(index) * 16,str,12,.white,0)
}
for i in 0 ..< NUMAXES { legend(i) }
let r = NSRect(x:CGFloat(ratio[0] * Float(PanelSize) - 5), y:CGFloat(ratio[1] * Float(PanelSize) - 5), width:CGFloat(10), height:CGFloat(10))
drawFilledCircle(r,.red)
}
func drawText(_ x:CGFloat, _ y:CGFloat, _ txt:String, _ fontSize:Int, _ color:NSColor, _ justifyCode:Int) { // 0,1,2 = left,center,right
let a1 = NSMutableAttributedString(
string: txt,
attributes: [
kCTFontAttributeName as NSAttributedString.Key:NSFont(name: "Helvetica", size: CGFloat(fontSize))!,
NSAttributedString.Key.foregroundColor : color
])
var cx = CGFloat(x)
let size = a1.size()
switch justifyCode {
case 1 : cx -= size.width/2
case 2 : cx -= size.width
default : break
}
a1.draw(at: CGPoint(x:cx, y:CGFloat(y)))
}
func drawFilledCircle(_ rect:NSRect, _ color:NSColor) {
let context = NSGraphicsContext.current?.cgContext
let path = CGMutablePath()
path.addEllipse(in: rect)
context?.setFillColor(color.cgColor)
context?.addPath(path)
context?.drawPath(using:.fill)
}
override var isFlipped: Bool { return true }
override var acceptsFirstResponder: Bool { return true }
}
|
//
// SearchExperimentsOperation.swift
// Experiment Go
//
// Created by luojie on 9/27/15.
// Copyright © 2015 LuoJie. All rights reserved.
//
import Foundation
import CloudKit
class SearchExperimentsOperation: GetObjectsWithCreatorUserOperation {
convenience init(searchText: String?) {
self.init(type: .Refresh(CKExperiment.QueryForSearchText(searchText)))
}
}
|
//
// RepositoryResponse.swift
//
// Created by Augusto Cesar do Nascimento dos Reis on 13/12/20
// Copyright (c) ACNR. All rights reserved.
//
import Foundation
struct RepositoryResponse: Decodable {
let items: [ItemResponse]?
let incompleteResults: Bool?
let totalCount: Int?
enum CodingKeys: String, CodingKey {
case items
case incompleteResults = "incomplete_results"
case totalCount = "total_count"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
items = try container.decodeIfPresent([ItemResponse].self, forKey: .items)
incompleteResults = try container.decodeIfPresent(Bool.self, forKey: .incompleteResults)
totalCount = try container.decodeIfPresent(Int.self, forKey: .totalCount)
}
}
|
//
// FCNetworkConfiguration.swift
// icar
//
// Created by 陈琪 on 2019/12/3.
// Copyright © 2019 Carisok. All rights reserved.
//
import Foundation
struct Configs {
struct Network {
static let useStaging = true // 测试模式
static let loggingEnabled = false // 请求日志输出
static let environment: Environment = .test
static let apiversion = "1.0" // API版本
static let loadPageCount = 20 // 加载数据条数
}
struct Path {
static let Documents = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
static let Tmp = NSTemporaryDirectory()
}
}
/**
* 服务器环境配置信息
*/
enum Environment {
/** 正式环境*/
case formal
/** 灰度*/
case grey
/** 测试环境*/
case test
var baseUrl: String {
switch self {
case .formal:
return ""
case .grey:
return ""
case .test:
return "http://baidu.com"
}
}
}
|
//
// ProductCell.swift
// FoodicsAssesment
//
// Created by mohamed gamal on 12/17/20.
//
import UIKit
class ProductCell: UICollectionViewCell {
//MARK:- OutLets
@IBOutlet weak var productImage: UIImageView!
@IBOutlet weak var productTitle: UILabel!
@IBOutlet weak var continerView: UIView!
@IBOutlet weak var priceLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.continerView.layer.cornerRadius = 8
self.continerView.layer.borderWidth = 3
self.continerView.layer.borderColor = UIColor.black.cgColor
}
func configureProducts(products: ProductModel) {
productImage.setImage(with: products.image ?? "")
productTitle.text = products.name ?? ""
priceLabel.text = "Price: \(products.price ?? 0.0)"
}
}
|
//
// Model.swift
// E-card
//
// Created by EthanLin on 2018/2/6.
// Copyright © 2018年 EthanLin. All rights reserved.
//
import Foundation
|
//
// GameScene.swift
// ShootingGallery
//
// Created by Juan Francisco Dorado Torres on 22/09/19.
// Copyright © 2019 Juan Francisco Dorado Torres. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene {
// MARK: - Properties
var scoreLabel: SKLabelNode!
var shotsNode: SKSpriteNode!
var gameTimer: Timer?
var appearedEnemies = 0
var velocityEnemies: Double = 150
var numOfShots = 3
var score = 0 {
didSet {
scoreLabel.text = "Score: \(score)"
}
}
// MARK: - Game lifecycle
override func didMove(to view: SKView) {
// add background music
let backgroundSound = SKAudioNode(fileNamed: "bg.mp3")
self.addChild(backgroundSound)
// add background
let woodBackground = SKSpriteNode(imageNamed: "wood-background")
woodBackground.size = self.frame.size
woodBackground.position = CGPoint(x: 512, y: 384)
woodBackground.zPosition = -2
addChild(woodBackground)
// add grass background
let grassBackground = SKSpriteNode(imageNamed: "grass-trees")
grassBackground.size = resized(grassBackground.size, expectedWidth: self.frame.size.width)
grassBackground.position = CGPoint(x: 512, y: 384)
grassBackground.zPosition = -1
addChild(grassBackground)
// add water
let waterBackground = SKSpriteNode(imageNamed: "water-bg")
waterBackground.size = resized(waterBackground.size, expectedWidth: self.frame.size.width)
waterBackground.position = CGPoint(x: 512, y: 240)
waterBackground.zPosition = 1
addChild(waterBackground)
let waterForeground = SKSpriteNode(imageNamed: "water-fg")
waterForeground.size = resized(waterBackground.size, expectedWidth: self.frame.size.width)
waterForeground.position = CGPoint(x: 512, y: 170)
waterForeground.zPosition = 3
addChild(waterForeground)
// add curtains
let curtainsForeground = SKSpriteNode(imageNamed: "curtains")
curtainsForeground.size = self.frame.size
curtainsForeground.position = CGPoint(x: 512, y: 384)
curtainsForeground.zPosition = 5
addChild(curtainsForeground)
// add score
scoreLabel = SKLabelNode(fontNamed: "Chalkduster")
scoreLabel.text = "Score: 0"
scoreLabel.horizontalAlignmentMode = .right
scoreLabel.position = CGPoint(x: 850, y: 60)
scoreLabel.zPosition = 5
addChild(scoreLabel)
// add shots
numOfShots = 3
print("shots\(numOfShots)")
shotsNode = SKSpriteNode(imageNamed: "shots\(numOfShots)")
shotsNode.size = resized(shotsNode.size, expectedWidth: shotsNode.size.width + 50)
shotsNode.position = CGPoint(x: 250, y: 75)
shotsNode.zPosition = 5
addChild(shotsNode)
physicsWorld.gravity = CGVector(dx: 0, dy: 0) // the gravity of our physics world is empty (because it is the space)
gameTimer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(createDuck), userInfo: nil, repeats: true)
}
override func update(_ currentTime: TimeInterval) {
for node in children { // check each node
if node.position.x < -300 || node.position.x > 1324 { // if the node is out of screen
node.removeFromParent() // remove the node from the parent
}
}
}
// MARK: - Touches events
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
let location = touch.location(in: self)
let tappedNodes = nodes(at: location)
guard numOfShots > 0 else {
run(SKAction.playSoundFileNamed("empty.wav", waitForCompletion: false))
return
}
for node in tappedNodes {
// SpriteNode -> ShotTarget -> Screen
guard let shotTarget = node.parent as? ShotTarget else {
continue
}
shotTarget.hit()
numOfShots -= 1
shotsNode.texture = SKTexture(imageNamed: "shots\(numOfShots)")
run(SKAction.playSoundFileNamed("shot.wav", waitForCompletion: false))
if node.name == "good" {
print("good target")
score += 5
} else if node.name == "bad" {
print("bad target")
//whackSlot.charNode.xScale = 0.85
//whackSlot.charNode.yScale = 0.85
score += 1
}
}
}
// MARK: - Methods
func resized(_ size: CGSize, expectedWidth: CGFloat) -> CGSize {
let oldWidth = size.width
let scaleFactor = expectedWidth / oldWidth
let newHeight = size.height * scaleFactor
let newWidth = oldWidth * scaleFactor
return CGSize(width: newWidth, height: newHeight)
}
@objc func createDuck() {
print(velocityEnemies)
let shotTarget = ShotTarget()
let duckPositions: [ShotTarget.RowPosition] = [.bottom, .middle, .front]
let selectedPosition = duckPositions.shuffled()[0]
shotTarget.configure(at: selectedPosition)
addChild(shotTarget)
// shotTarget move
shotTarget.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 115, height: 240), center: CGPoint(x: 0, y: 50))
shotTarget.physicsBody?.collisionBitMask = 0
shotTarget.physicsBody?.categoryBitMask = 0
shotTarget.physicsBody?.velocity = CGVector(dx: selectedPosition == .middle ? (velocityEnemies * -1) : velocityEnemies, dy: 0) // make it move horizontal way
shotTarget.physicsBody?.angularVelocity = 5 // give an angular velocity to make the enemy rotate
shotTarget.physicsBody?.linearDamping = 0 // this avoids to reduce the linear velocity during the moving time
shotTarget.physicsBody?.angularVelocity = 0 // this avoids to reduce the rotation during the moving time
appearedEnemies += 1
if appearedEnemies == 5 {
appearedEnemies = 0
velocityEnemies *= 1.2
if velocityEnemies > 1000 {
gameTimer?.invalidate()
let gameOver = SKSpriteNode(imageNamed: "gameOver") // create a new node with the game over image
gameOver.position = CGPoint(x: 512, y: 384) // add on the center of the screen
gameOver.zPosition = 1 // put the node over eveything
addChild(gameOver) // add it to the screen
}
}
}
func reloadBullets() {
numOfShots = 3
shotsNode.texture = SKTexture(imageNamed: "shots\(numOfShots)")
run(SKAction.playSoundFileNamed("reload.wav", waitForCompletion: false))
}
}
|
//
// LeaveFeedbackActivityTableCell.swift
// MyLoqta
//
// Created by Kirti on 9/7/18.
// Copyright © 2018 AppVenturez. All rights reserved.
//
import UIKit
protocol LeaveFeedbackActivityTableCellDelegate: class {
func leaveFeedbackTapped(cell: LeaveFeedbackActivityTableCell)
func replyTapped(cell: LeaveFeedbackActivityTableCell)
}
class LeaveFeedbackActivityTableCell: BaseTableViewCell, NibLoadableView, ReusableView {
//MARK:- IBOutlets
@IBOutlet weak var viewShadow: UIView!
@IBOutlet weak var viewContainer: UIView!
@IBOutlet weak var imgViewProduct: UIImageView!
@IBOutlet weak var lblDescription: UILabel!
@IBOutlet weak var btnFeedback: AVButton!
//ConstraintOutlets
@IBOutlet weak var cnstrntBtnFeedbackWidth: NSLayoutConstraint!
//MARK: - Variables
weak var delegate: LeaveFeedbackActivityTableCellDelegate?
var isReply = false
override func awakeFromNib() {
super.awakeFromNib()
self.setupView()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
//MARK: - Private Methods
private func setupView() {
self.imgViewProduct.roundCorners(4.0)
self.configureViewForShadow()
if isReply {
self.btnFeedback.localizeKey = "Reply".localize()
self.cnstrntBtnFeedbackWidth.constant = 70.0
} else {
self.btnFeedback.localizeKey = "Leave feedback".localize()
self.cnstrntBtnFeedbackWidth.constant = 115.0
}
}
private func configureViewForShadow() {
self.viewShadow.layer.shadowColor = UIColor.gray.cgColor
self.viewShadow.layer.shadowOffset = CGSize(width: 0, height: 0)
self.viewShadow.layer.shadowOpacity = 0.2
self.viewShadow.layer.shadowRadius = 5.0
self.viewShadow.layer.cornerRadius = 8.0
self.viewContainer.layer.cornerRadius = 8.0
}
//MARK:- IBActions
@IBAction func tapBtnLeaveFeedback(_ sender: AVButton) {
if let delegate = delegate {
if isReply {
delegate.replyTapped(cell: self)
} else {
delegate.leaveFeedbackTapped(cell: self)
}
}
}
//MARK:- Public Methods
func configureCellForSellerBuyerLeavesFeedback(activity: Activity) {
if let itemName = activity.itemName, let buyerName = activity.buyerName {
let yourItem = "Your item".localize()
let hasSold = "has been sold to".localize()
let finalText = yourItem + " \(itemName) " + hasSold + " \(buyerName)."
self.lblDescription.text = finalText
}
}
func configureCellForSellerBuyerAsksQuestion(activity: Activity) {
if let buyerName = activity.buyerName, let question = activity.question {
let commentedOn = "commented on".localize()
let finalText = buyerName + " \(commentedOn): " + question
self.lblDescription.text = finalText
}
}
}
|
//
// ForecastView.swift
// SwiftWeatherTemplate
//
// Created by Florian on 18.07.20.
// Copyright © 2020 Florian. All rights reserved.
//
import UIKit
import SnapKit
final class ForecastView: UIView {
let tableView = UITableView()
convenience init() {
self.init(frame: .zero)
tableView.adoptBackgroundMode()
addSubview(tableView)
makeConstraints()
}
}
// MARK: - ViewProtocol
extension ForecastView: ViewProtocol {
func makeConstraints() {
tableView.snp.makeConstraints {
$0.left.top.right.bottom.equalToSuperview()
}
}
}
|
//
// main.swift
// h.w.f
//
// Created by Ghada Fahad on 15/03/1443 AH.
//
import Foundation
print("Hello, World!")
|
//
// ChatMessage.swift
// Finder
//
// Created by Tai on 6/18/20.
// Copyright © 2020 DJay. All rights reserved.
//
import Foundation
//import FirebaseDatabase
class ChatMessage {
var id = ""
var senderId = ""
var receiverId = ""
var message = ""
var imgURL = ""
var isRead = true
var createdAt = dateToString(date: Date())
private let ref = Database.database().reference()
init(id: String, senderId: String, receiverId: String, message: String, imgURL: String = "") {
self.id = id
self.senderId = senderId
self.receiverId = receiverId
self.message = message
self.imgURL = imgURL
self.isRead = false
}
init(data: [String : Any]) {
update(data: data)
}
private func update(data: [String : Any]) {
self.id = (data[ct_id] as? String) ?? ""
self.senderId = (data[ct_senderId] as? String) ?? ""
self.receiverId = (data[ct_receiverId] as? String) ?? ""
self.message = (data[ct_message] as? String) ?? ""
self.imgURL = (data[ct_imgURL] as? String) ?? ""
self.isRead = (data[ct_isRead] as? Bool) ?? true
self.createdAt = (data[ct_createdAt] as? String) ?? dateToString(date: Date())
}
func asDictionary() -> [String : Any] {
return [ct_id : self.id,
ct_senderId : self.senderId,
ct_receiverId : self.receiverId,
ct_message : self.message,
ct_imgURL : self.imgURL,
ct_isRead : self.isRead,
ct_createdAt : self.createdAt]
}
func updateOnServer(chatId: String) {
ref.child("chats/\(chatId)/\(id)").setValue(self.asDictionary())
}
}
|
//
// PreparePlayerViewController.swift
// Avgle
//
// Created by ChenZheng-Yang on 2018/1/7.
// Copyright © 2018年 ChenCheng-Yang. All rights reserved.
//
import UIKit
import BMPlayer
import SafariServices
import Firebase
import SVProgressHUD
class PreparePlayerViewController: BaseViewController {
// MARK: - Property
/// 是否從收藏進來的,此頁面可由主頁及我的收藏兩個地方進來,分不同模式,在likeBtn有不同呈現
public var isFromCollection: Bool = false
/// 若需要刪除會有key
public var dataKey: String = ""
var video: VideoModel? {
didSet {
let url = URL(string: (video!.preview_video_url?.urlEncoded())!)!
let asset = BMPlayerResource(url: url, name: video!.title!)
player.seek(30)
player.setVideo(resource: asset)
}
}
var ref: DatabaseReference!
fileprivate lazy var player: BMPlayer = {
let player = BMPlayer(customControlView: BMPlayerCustomControlView())
player.delegate = self
return player
}()
fileprivate lazy var blurEffectView: UIVisualEffectView = {
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = self.view.bounds
return blurEffectView
}()
fileprivate lazy var backgroundImageView: UIImageView = {
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight))
imageView.image = UIImage(named: "BG_3")
imageView.addSubview(blurEffectView)
return imageView
}()
fileprivate lazy var cancelBtn: UIButton = {
let btn = UIButton(type: .custom)
btn.backgroundColor = UIColor.clear
btn.layer.borderWidth = 1
btn.layer.borderColor = UIColor.white.cgColor
btn.setTitle(NSLocalizedString("Cancel", comment: "") , for: .normal)
btn.setTitleColor(.white, for: .normal)
btn.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
return btn
}()
fileprivate lazy var watchTheVideoBtn: UIButton = {
let btn = UIButton(type: .custom)
btn.layer.borderWidth = 1
btn.layer.borderColor = UIColor.white.cgColor
btn.setTitle(NSLocalizedString("Watch the video", comment: ""), for: .normal)
btn.setTitleColor(.white, for: .normal)
btn.addTarget(self, action: #selector(watchFullVideo), for: .touchUpInside)
return btn
}()
fileprivate lazy var likeBtn: UIButton = {
let btn = UIButton(type: .custom)
btn.layer.borderWidth = 1
btn.layer.borderColor = UIColor.white.cgColor
btn.setTitle(NSLocalizedString(isFromCollection ? "Delete The Video":"Add My Collection", comment: ""), for: .normal)
btn.setTitleColor(.white, for: .normal)
btn.addTarget(self, action: #selector(likeAction(btn:)), for: .touchUpInside)
return btn
}()
// MARK: - ViewController Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
//Animation
let scale = CGAffineTransform(scaleX: 0.0, y: 0.0)
let translate = CGAffineTransform(translationX: 0, y: 500)
self.likeBtn.transform = scale.concatenating(translate)
self.watchTheVideoBtn.transform = scale.concatenating(translate)
self.cancelBtn.transform = scale.concatenating(translate)
self.player.transform = scale.concatenating(translate)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources t hat can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//Animation
UIButton.animate(withDuration: 0.5, delay: 0.0, options: [], animations: {
self.likeBtn.transform = CGAffineTransform.identity
self.watchTheVideoBtn.transform = CGAffineTransform.identity
self.cancelBtn.transform = CGAffineTransform.identity
self.player.transform = CGAffineTransform.identity
}, completion: nil)
}
// MARK : - Setup UI
override func setUI() {
super.setUI()
view.addSubview(backgroundImageView)
view.addSubview(cancelBtn)
view.addSubview(watchTheVideoBtn)
view.addSubview(player)
view.addSubview(likeBtn)
resetPlayerManager()
setNeedsLayout()
setData()
}
func setData() {
ref = Database.database().reference()
}
// MARK: - Button Action
@objc func cancelAction() {
UIApplication.shared.setStatusBarHidden(false, with: .fade)
dismiss(animated: true, completion: nil)
}
@objc func watchFullVideo() {
let urlStr: String = self.video!.embedded_url!.urlEncoded()
let safariVC = SFSafariViewController(url: URL(string: urlStr)!)
safariVC.delegate = self
self.present(safariVC, animated: true, completion: nil)
}
@objc func likeAction(btn: UIButton) {
btn.isEnabled = false
SVProgressHUD.showProgress(2.0, status: NSLocalizedString("Loading...", comment: ""))
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
SVProgressHUD.dismiss()
btn.setTitle(NSLocalizedString(self.isFromCollection ? "Successfully deleted":"Added successfully", comment: ""), for: .normal)
}
// 節點值
let childKey: String = (Auth.auth().currentUser?.displayName)! + "_" + (Auth.auth().currentUser?.uid)!
if self.isFromCollection {
// 刪除
ref.child(childKey).child(dataKey).removeValue()
} else {
// 新增
// 獲得現在日期
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "yyyyMMdd_hh:mm:ss"
let nowDate: String = dateFormatterPrint.string(from: Date())
let dataDic: [String : Any] = ["title": video!.title!,
"duration": video!.duration!,
"likes": video!.likes!,
"dislikes": video!.dislikes!,
"embedded_url": video!.embedded_url!,
"preview_url": video!.preview_url!,
"preview_video_url": video!.preview_video_url!]
// 上傳Database
ref.child(childKey).child(nowDate).setValue(dataDic)
}
}
// MARK: - Player
func resetPlayerManager() {
BMPlayerConf.shouldAutoPlay = true
BMPlayerConf.tintColor = UIColor.white
BMPlayerConf.topBarShowInCase = .none
}
// MARK: - Auto Layout
func setNeedsLayout() {
cancelBtn.snp.makeConstraints { (make) in
make.bottom.equalTo(-30 * proportion).priority(1000)
make.leading.equalTo(50)
make.trailing.equalTo(-50)
make.height.equalTo(50)
}
watchTheVideoBtn.snp.makeConstraints { (make) in
make.width.height.centerX.equalTo(cancelBtn)
make.bottom.equalTo(cancelBtn.snp.top).offset(-30)
}
likeBtn.snp.makeConstraints { (make) in
make.width.height.centerX.equalTo(cancelBtn)
make.bottom.equalTo(watchTheVideoBtn.snp.top).offset(-30)
}
player.snp.makeConstraints { (make) in
make.top.equalTo(view.snp.top)
make.left.equalTo(view.snp.left)
make.right.equalTo(view.snp.right)
make.height.equalTo(view.snp.width).multipliedBy(9.0/16.0).priority(500)
}
}
// MARK: Device Orientation
override var shouldAutorotate: Bool {
return true
}
}
extension PreparePlayerViewController: BMPlayerDelegate {
func bmPlayer(player: BMPlayer, playerOrientChanged isFullscreen: Bool) {
player.snp.remakeConstraints { [weak self](make) in
make.top.equalTo(view.snp.top)
make.left.equalTo(view.snp.left)
make.right.equalTo(view.snp.right)
if isFullscreen {
self?.likeBtn.isHidden = true
make.bottom.equalTo(view.snp.bottom)
} else {
self?.likeBtn.isHidden = false
make.height.equalTo(view.snp.width).multipliedBy(9.0/16.0).priority(500)
}
}
}
// Call back when playing state changed, use to detect is playing or not
func bmPlayer(player: BMPlayer, playerIsPlaying playing: Bool) {
print("| BMPlayerDelegate | playerIsPlaying | playing - \(playing)")
}
// Call back when playing state changed, use to detect specefic state like buffering, bufferfinished
func bmPlayer(player: BMPlayer, playerStateDidChange state: BMPlayerState) {
print("| BMPlayerDelegate | playerStateDidChange | state - \(state)")
}
// Call back when play time change
func bmPlayer(player: BMPlayer, playTimeDidChange currentTime: TimeInterval, totalTime: TimeInterval) {
// print("| BMPlayerDelegate | playTimeDidChange | \(currentTime) of \(totalTime)")
}
// Call back when the video loaded duration changed
func bmPlayer(player: BMPlayer, loadedTimeDidChange loadedDuration: TimeInterval, totalDuration: TimeInterval) {
// print("| BMPlayerDelegate | loadedTimeDidChange | \(loadedDuration) of \(totalDuration)")
}
}
extension PreparePlayerViewController: SFSafariViewControllerDelegate {
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
controller.dismiss(animated: true, completion: nil)
}
}
|
//
// UserTeaser.swift
// TinderApp
//
// Created by Serg on 13.02.2020.
// Copyright © 2020 Sergey Gladkiy. All rights reserved.
//
import Foundation
struct TinderUserTeaser: Decodable {
let type: String?
let string: String
}
struct UserJob: Decodable {
let company: CompanyJob?
let title: TitleJob?
}
struct UserSchool: Decodable {
let name: String?
}
struct CompanyJob: Decodable {
let name: String
}
struct TitleJob: Decodable {
let name: String
}
|
//
// GoogleSignINView.swift
// caffinho-iOS
//
// Created by Rafael M. A. da Silva on 8/3/16.
// Copyright © 2016 venturus. All rights reserved.
//
import Foundation
import UIKit
public class GoogleSignINView: UIView {
var contentView: GoogleSignINContentView!
public override func awakeFromNib() {
super.awakeFromNib()
contentView = GoogleSignINContentView.loadFromNibNamed(NibNames.googleSignINContentView) as! GoogleSignINContentView
self.addSubview(contentView)
}
}
|
//
// UIColor+Extensions.swift
// InAppNotification
//
// Created by Arnold Plakolli on 5/20/18.
// Copyright © 2018 Arnold Plakolli. All rights reserved.
//
import Foundation
extension UIColor {
convenience init(r: CGFloat, g: CGFloat, b: CGFloat) {
self.init(r: r, g: g, b: b, a: 255)
}
convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) {
self.init(red: r/255, green: g/255, blue: b/255, alpha: a/255)
}
}
|
import GRDB
class AccountRecordStorage {
private let dbPool: DatabasePool
init(dbPool: DatabasePool) {
self.dbPool = dbPool
}
}
extension AccountRecordStorage {
var all: [AccountRecord] {
try! dbPool.read { db in
try AccountRecord.fetchAll(db)
}
}
func save(record: AccountRecord) {
_ = try! dbPool.write { db in
try record.insert(db)
}
}
func delete(by id: String) {
_ = try! dbPool.write { db in
try AccountRecord.filter(AccountRecord.Columns.id == id).deleteAll(db)
}
}
func clear() {
_ = try! dbPool.write { db in
try AccountRecord.deleteAll(db)
}
}
}
|
//
// bigImageViewController.swift
// SlideshowApp
//
// Created by まく on 2018/07/15.
// Copyright © 2018年 sshiono. All rights reserved.
//
import UIKit
class bigImageViewController: UIViewController {
@IBOutlet weak var bigImageParts: UIImageView!
var firstValue:Int = 0
let imageList = ["cat.jpg", "dog.jpg", "fox.jpg"]
override func viewDidLoad() {
super.viewDidLoad()
bigImageParts.image = UIImage(named:imageList[firstValue])
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// SecondScreen.swift
// bleedApp
//
// Created by Peter Ostiguy on 11/19/16.
// Copyright © 2016 Peter Ostiguy. All rights reserved.
//
import UIKit
class SecondScreen: UIViewController, GIDSignInUIDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func signOutButton(_ sender: Any) {
GIDSignIn.sharedInstance().signOut()
print("signed out")
}
}
|
//
// AllBreedsList.swift
// Doggy_App
//
// Created by User on 19/06/2019.
// Copyright © 2019 Maximkapitonov. All rights reserved.
//
import Foundation
struct AllBreedsList: Codable {
var status: String?
var message: [String: [String]]?
}
|
//
// ViewController.swift
// Foodie COPY - TRY DUMB SHIT OUT HERE
//
// Created by Justine Breuch on 8/30/15.
// Copyright (c) 2015 Justine Breuch. All rights reserved.
//
import UIKit
import Parse
import Bolts
class ViewController: UIViewController {
// override func viewDidLoad() {
// super.viewDidLoad()
// // Do any additional setup after loading the view, typically from a nib.
// get_place()
// }
//
// override func didReceiveMemoryWarning() {
// super.didReceiveMemoryWarning()
// // Dispose of any resources that can be recreated.
// }
//
// func get_place() -> Void {
// // version needs to be yyyymmdd format
// var version = "20150705"
//
// // latitude and longitude
// var ll = "40.0522776,-75.2913171"
//
// // standard base
// let url = NSURL(string: "https://api.foursquare.com/v2/venues/explore?ll=\(ll)§ion=food&openNow=1&client_id=\(foursquare_client_id)&client_secret=\(foursquare_client_secret)&v=\(version)")
//
// var data = NSData(contentsOfURL: url!)
//
// let jsonError: NSError?
//
// if let json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary {
//
// let response = json["response"] as! NSDictionary
// let groups = response["groups"] as! NSArray
// let recommended = groups[0] as! NSDictionary
// let items = recommended["items"] as! NSArray
//
// let item = items[0] as! NSDictionary
//
// // venue is one restaurant
// let venue: NSDictionary = (item["venue"] as? NSDictionary)!
// var checkpoint: String = venue["id"] as! String
//
// // check if it already exists
// var query = PFQuery(className:"Place")
//
// query.whereKey("foursquare_id", equalTo: "\(checkpoint)")
// query.findObjectsInBackgroundWithBlock {
// (objects: [AnyObject]?, error: NSError?) -> Void in
//
// if error == nil {
// // The find succeeded.
// println("Retrieved \(objects!.count) places.")
//
//
// if (objects!.count == 0) {
// // save new entries
// println("creating new object")
// var place = PFObject(className:"Place")
//
// place["foursquare_id"] = venue["id"]
//
// place["name"] = venue["name"]
// println(venue["name"])
//
// if (venue["url"] != nil) {
// place["url"] = venue["url"]
// }
//
// if (venue["rating"] != nil) {
// place["rating"] = venue["rating"]
// }
//
// if (venue["contact"] != nil) {
// let contact = venue["contact"] as! NSDictionary
// if (contact["phone"] != nil && contact["formattedPhone"] != nil) {
// place["phone"] = contact["phone"]
// place["formatted_phone"] = contact["formattedPhone"]
// }
//
// }
//
// if (venue["location"] != nil) {
// let location = venue["location"] as! NSDictionary
//
// if (location["formattedAddress"] != nil) {
// let address:Array<String> = (location["formattedAddress"] as? Array<String>)!
// place["formatted_address"] = join(" ", address) as String
//
// }
//
// }
// place["instagram_id"] = self.getInstagramId(checkpoint)
// self.nameLabel.text = place["name"] as? String
// self.getInstagramData(place["instagram_id"] as! String)
//
//
// place.saveInBackgroundWithBlock {
// (success: Bool, error: NSError?) -> Void in
// if (success) {
// println("Success!")
// } else {
// println("There was a problem!")
// }
// }
//
// } else {
// // Do something with the found objects
// println("Looking in Parse")
// if let objects = objects as? [PFObject] {
// for object in objects {
// println(object["name"])
// self.nameLabel.text = object["name"] as? String
// self.getInstagramData(object["instagram_id"] as! String)
// }
// }
// }
//
// } else {
// // Log details of the failure
// println("Error: \(error!) \(error!.userInfo!)")
//
// }
// }
//
// }
//
// }
//
// func getAPIdata() -> Void {
//
// // version needs to be yyyymmdd format
// var version = "20150705"
//
// // latitude and longitude
// var ll = "40.7,-74"
//
// // standard base
// let url = NSURL(string: "https://api.foursquare.com/v2/venues/explore?ll=\(ll)§ion=food&openNow=1&client_id=\(foursquare_client_id)&client_secret=\(foursquare_client_secret)&v=\(version)")
//
// var data = NSData(contentsOfURL: url!)
//
// let jsonError: NSError?
//
// if let json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary {
//
// let response = json["response"] as! NSDictionary
// let groups = response["groups"] as! NSArray
// let recommended = groups[0] as! NSDictionary
// let items = recommended["items"] as! NSArray
//
// for item in items {
// // venue is one restaurant
// let venue: NSDictionary = (item["venue"] as? NSDictionary)!
// var checkpoint: String = venue["id"] as! String
//
// // check if it already exists
// var query = PFQuery(className:"Place")
//
// query.whereKey("foursquare_id", equalTo: "\(checkpoint)")
// query.findObjectsInBackgroundWithBlock {
// (objects: [AnyObject]?, error: NSError?) -> Void in
//
// if error == nil {
// // The find succeeded.
// println("Retrieved \(objects!.count) places.")
//
//// // Do something with the found objects
//// if let objects = objects as? [PFObject] {
//// for object in objects {
//// println(object["name"])
//// }
//// }
//
// if (objects!.count == 0) {
// // save new entries
// println("creating new object")
// var place = PFObject(className:"Place")
//
// place["foursquare_id"] = venue["id"]
//
// place["name"] = venue["name"]
//
// if (venue["url"] != nil) {
// place["url"] = venue["url"]
// }
//
// if (venue["rating"] != nil) {
// place["rating"] = venue["rating"]
// }
//
// if (venue["contact"] != nil) {
// let contact = venue["contact"] as! NSDictionary
// if (contact["phone"] != nil && contact["formattedPhone"] != nil) {
// place["phone"] = contact["phone"]
// place["formatted_phone"] = contact["formattedPhone"]
// }
//
// }
//
// if (venue["location"] != nil) {
// let location = venue["location"] as! NSDictionary
//
// if (location["formattedAddress"] != nil) {
// let address:Array<String> = (location["formattedAddress"] as? Array<String>)!
// place["formatted_address"] = join(" ", address) as String
//
// }
//
// }
// place["instagram_id"] = self.getInstagramId(checkpoint)
//
// place.saveInBackgroundWithBlock {
// (success: Bool, error: NSError?) -> Void in
// if (success) {
// println("Success!")
// } else {
// println("There was a problem!")
// }
// }
//
// }
//
// } else {
// // Log details of the failure
// println("Error: \(error!) \(error!.userInfo!)")
//
//
// }
// }
// }
// }
// }
//
// func getInstagramId(checkpoint:String) -> String? {
//
// // standard base
// let url = NSURL(string: "https://api.instagram.com/v1/locations/search?foursquare_v2_id=\(checkpoint)&access_token=\(instagram_access_token)")
//
// var data = NSData(contentsOfURL: url!)
//
// // Create another error optional
// var jsonerror:NSError?
//
// if let json: AnyObject! = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &jsonerror) as? NSDictionary {
//
// let data = json["data"] as! NSArray
// let info = data[0] as! NSDictionary
// return info["id"] as! String?
// }
//
// return ""
// }
//
// func getInstagramData(instagram_id:String) -> Void {
//
// var glanceOfPlaceImageView: UIImageView!
// var scrollViewContentSize:CGFloat = 0
//
// picturesScrollView.backgroundColor = UIColor.orangeColor()
// picturesScrollView.frame = self.view.bounds
// picturesScrollView.directionalLockEnabled = true
//
// if let url = NSURL(string: "https://api.instagram.com/v1/locations/\(instagram_id)/media/recent?access_token=\(instagram_access_token)") {
//
// var contents = NSData(contentsOfURL: url)
//
// // Create another error optional
// var jsonerror:NSError?
//
// if let json: AnyObject! = NSJSONSerialization.JSONObjectWithData(contents!, options: NSJSONReadingOptions.MutableContainers, error: &jsonerror) as? NSDictionary {
//
// let instas = json["data"] as! NSArray
//
// for insta in instas {
//
// let pictures = insta["images"] as! NSDictionary!
// let standard_res = pictures["standard_resolution"] as! NSDictionary!
//
// let url = NSURL(string: standard_res["url"] as! String!)
// let data = NSData(contentsOfURL: url!)
//
// if data != nil {
//
// glanceOfPlaceImageView = UIImageView(image: UIImage(data:data!))
// glanceOfPlaceImageView.frame.size.height = 400
// glanceOfPlaceImageView.frame.size.width = picturesScrollView.bounds.width
// glanceOfPlaceImageView.frame.origin.y = scrollViewContentSize
//
// scrollViewContentSize += glanceOfPlaceImageView.bounds.height
//
// picturesScrollView.addSubview(glanceOfPlaceImageView)
// println(scrollViewContentSize)
//
// }
//
// picturesScrollView.contentSize.width = view.bounds.size.width
// picturesScrollView.contentSize.height = scrollViewContentSize
// picturesScrollView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
//
// view.addSubview(picturesScrollView)
//
// }
//
// }
// }
// }
}
|
//
// MyAccCSViewController.swift
// YumaApp
//
// Created by Yuma Usa on 2018-02-15.
// Copyright © 2018 Yuma Usa. All rights reserved.
//
import UIKit
class MyAccCSViewController: UIViewController
{
@IBOutlet weak var navBar: UINavigationBar!
@IBOutlet weak var navTitle: UINavigationItem!
@IBOutlet weak var navClose: UIBarButtonItem!
@IBOutlet weak var navHelp: UIBarButtonItem!
override func viewDidLoad()
{
super.viewDidLoad()
// if #available(iOS 11.0, *) {
// navBar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
// } else {
// navBar.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true
// }
navHelp.title = FontAwesome.questionCircle.rawValue
navHelp.setTitleTextAttributes([NSAttributedStringKey.font : R.font.FontAwesomeOfSize(pointSize: 21)], for: .normal)
navHelp.setTitleTextAttributes([
NSAttributedStringKey.font : R.font.FontAwesomeOfSize(pointSize: 21)
], for: UIControlState.highlighted)
navBar.applyNavigationGradient(colors: [R.color.YumaDRed, R.color.YumaRed], isVertical: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Actions
@IBAction func navCloseAct(_ sender: Any)
{
self.dismiss(animated: false, completion: nil)
}
@IBAction func navHelpAct(_ sender: Any)
{
let viewC = Assistance()
viewC.array = R.array.help_my_account_credit_slips_guide
viewC.title = "\(R.string.CreditSlips.capitalized) \(R.string.help.capitalized)"
viewC.modalTransitionStyle = .crossDissolve
viewC.modalPresentationStyle = .overCurrentContext
self.present(viewC, animated: true, completion: nil)
}
}
|
//
// EmojiArtDocument.swift
// EmojiArt
//
// Created by Ahmed Albaqawi on 6/27/20.
// Copyright © 2020 Ahmed Albaqawi. All rights reserved.
//
import SwiftUI
import Combine
//ViewModel
class EmojiArtDocument: ObservableObject {
private static let untitled = "EmojiArtDocument.Untitled"
//we have a bug with property wrapers do not behave will with property observes
@Published private var emojiArt: EmojiArt
//now we can DECODE JSON we can init with the DECODER we did with init? on model
// we need to create the following private var to ensure the sink live past the execution of the init with AnyCancellable?
// now we ensure that this lives as long as this ViewModel lives
private var autoSaveCancellable: AnyCancellable?
private var fetchImageCancellable: AnyCancellable?
init() {
//this is a failable init so it can return nil so we have to add ?? and set to the empty model (start case)
emojiArt = EmojiArt(json: UserDefaults.standard.data(forKey: EmojiArtDocument.untitled)) ?? EmojiArt()
//we need to go back and fetch the backgound image, the Document do not store image only url and must fetch again
//A new fix for the bug of property wrapers do not behave will with property observes
autoSaveCancellable = $emojiArt.sink { emojiArt in
UserDefaults.standard.set(emojiArt.json, forKey: EmojiArtDocument.untitled)
print("json = \(emojiArt.json?.utf8 ?? "nil")")
print("we are in the autoSaveCancellable block")
}
fetchBackgroundImageData()
}
//only model fitches images from internet, we must publish to be tracked in ViewModel
@Published private(set) var backgroundImage: UIImage?
//the model is private so we need to make this read version of emojiArt model
//this will return all the emojis in our array
// the { } acts like the Get
var emojis: [EmojiArt.Emoji] { emojiArt.emojis }
static let palette : String = "💻🤪😘😔😡😃🥶😱🥵😎🤩🥳🧀🥨"
// MARK: - Intents
func addEmoji(_ emoji: String, at location: CGPoint, size: CGFloat) {
emojiArt.addEmoji(emoji, x: Int(location.x), y: Int(location.y), size: Int(size))
}
//we extedned the Collection a protocol that Array impliments with 1st index matching to be able to control
//collection content
func moveEmoji(_ emoji: EmojiArt.Emoji, by offset: CGSize) {
if let index = emojiArt.emojis.firstIndex(matching: emoji) {
emojiArt.emojis[index].x += Int(offset.width)
emojiArt.emojis[index].y += Int(offset.height)
}
}
func scaleEmoji(_ emoji: EmojiArt.Emoji, by scale: CGFloat) {
if let index = emojiArt.emojis.firstIndex(matching: emoji) {
emojiArt.emojis[index].size = Int((CGFloat(emojiArt.emojis[index].size) * scale).rounded(.toNearestOrEven))
}
}
//change setbackgroundURL to computed var as backgroundURL to provide get and set to use in view, and assess if loading
var backgoundURL: URL? {
get {
emojiArt.backgroundURL
}
set{
emojiArt.backgroundURL = newValue?.imageURL
fetchBackgroundImageData()
}
}
private func fetchBackgroundImageData() {
backgroundImage = nil
if let url = self.emojiArt.backgroundURL {
// Every time there is a new request, cancel the old one
fetchImageCancellable?.cancel()
// Then make a new one... no need for condetional checking like before
//the new publisher way of handling HTTP requests
fetchImageCancellable = URLSession.shared.dataTaskPublisher(for: url)
//dataTaskPublisher returns a tuple data and failure response
.map {
//we want to have our own publisher response that maps the data from dataTaskPublisher into UIImage
// where we know we want a UIImage for the BackgoundImage
data, URLResponse in UIImage(data: data)
}
//REMEMBER we need to do it on Main Queue as this is updating the backgound of app
.receive(on: DispatchQueue.main)
//next line is to ensure on sink or subscriber to publisher we do not handle errors
.replaceError(with: nil)
//we assigned it to our publisher declared above, assign only works if you have never as your error, link here or above on the spinner example
.assign(to: \EmojiArtDocument.backgroundImage, on: self)
//the previous manual way of handling HTTP requests
// //manually go on network of UI thread to get image from netowrk
// DispatchQueue.global(qos: .userInitiated).async {
// if let imageData = try? Data(contentsOf: url) {
// //now this is a problem that will try to update UI on non-main thread
// DispatchQueue.main.async {
// //to avoid loading more than 1 background check the url used at start of the exec block is same,
// // if user drops more than 1 backgound we will not get impacted and cause conflicts
// // this prevention allows us to show the latest url selected
// if url == self.emojiArt.backgroundURL {
// self.backgroundImage = UIImage(data: imageData)
//
// }
// }
// }
// }
}
}
}
|
//
// CategoryViewController.swift
// bundapp
//
// Created by YinZhang on 14/12/8.
// Copyright (c) 2014年 THEBUND. All rights reserved.
//
import UIKit
class CategoryViewController: UIViewController {
var key: (String, String, String?, String?, String?, String?, String?, String?, Bool) = ("","",nil,nil,nil,nil,nil,nil, false)
@IBOutlet weak var tableView: AsyncTable!
var refreshControl: UIRefreshControl?
var page = 1
var pageEnd = false
override func viewDidLoad() {
super.viewDidLoad()
// refresh control
var refresh = UIRefreshControl()
var attr = [NSForegroundColorAttributeName:UIColor.blackColor()]
YinCache.sharedInstance.getString(key: "\(self.key.1)_type_last_refresh_time", onSuccess: { string in
refresh.attributedTitle = NSAttributedString(string: string, attributes:attr)
}, onFailure: { _ in
// refresh.attributedTitle = NSAttributedString(string: "上次刷新时间:无", attributes:attr)
refresh.attributedTitle = NSAttributedString(string: "下拉刷新", attributes:attr)
})
refresh.addTarget(self, action: "refresh", forControlEvents:.ValueChanged)
self.refreshControl = refresh
self.tableView.insertSubview(refresh, atIndex: 0)
var focus = CategoryFocusData()
focus.firstImgId = self.key.3
if self.key.8 {
focus.secondImgId = self.key.2
}
focus.title = self.key.4
focus.link = self.key.5
focus.showLink = self.key.6
focus.clickLink = self.key.7
PostList.sharedInstance.cateList = []
PostList.sharedInstance.appendCategoryList(focus)
self.tableView.fetchData = getData
self.tableView.selectData = selectData
self.tableView.onSwipeUp = swipeUp
self.tableView.onSwipeDown = swipeDown
self.tableView.loadSegment(nil)
}
func refresh() {
self.refreshControl?.attributedTitle = NSAttributedString(string: "刷啊刷~")
self.page = 1
pageEnd = false
var first = PostList.sharedInstance.cateList[0]
PostList.sharedInstance.cateList = []
PostList.sharedInstance.cateList.append(first)
self.tableView.loadSegment() {
() -> () in
let time = NSDate()
let outFormatter = NSDateFormatter()
outFormatter.locale = NSLocale(localeIdentifier: "zh_CN")
outFormatter.dateFormat = "'上次刷新时间:'MM'月'dd'日 'HH:mm:ss"
let last_time = outFormatter.stringFromDate(time)
YinCache.sharedInstance.setString(value: last_time, key: "\(self.key.1)_type_last_refresh_time")
dispatch_async(dispatch_get_main_queue(), {
self.refreshControl?.attributedTitle = NSAttributedString(string: "下拉刷新")
self.refreshControl?.endRefreshing()
return
})
}
}
var loggedDate: NSDate?
func getData(listener:(Bool,[CellData]?) -> ()) {
if pageEnd {
listener(false,nil)
return
}
// println("get data page:\(self.page)")
// PostList.sharedInstance.appendCategoryList(date)
let urlstr = "http://www.bundpic.com/app-post?n=10&p=\(self.page++)&c=\(self.key.1)"
// println("category:\(urlstr)")
YinCache.sharedInstance.getJson(url: urlstr, refresh: true, onSuccess: { data in
let postArr = data as Array<AnyObject>
let inFormatter = NSDateFormatter()
inFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'.'SSS'Z'"
inFormatter.timeZone = NSTimeZone(name: "UTC")
self.loggedDate == nil
if self.loggedDate == nil {
let now = NSDate()
let cal = NSCalendar.currentCalendar()
var com = cal.components(NSCalendarUnit.CalendarUnitYear|NSCalendarUnit.CalendarUnitMonth|NSCalendarUnit.CalendarUnitDay, fromDate: now)
com.day += 1
self.loggedDate = cal.dateFromComponents(com)
}
let outFormatter = NSDateFormatter()
outFormatter.locale = NSLocale(localeIdentifier: "zh_CN")
outFormatter.dateFormat = "MM'月'd'日 'EEEE"
for index in 0..<postArr.count {
let item : AnyObject? = postArr[index]
let post = item! as Dictionary<String, AnyObject>
let id = post["_id"]! as String
let title = post["标题"]! as String
let image = post["图片链接"] as String?
var link:String? = post["链接"] as String?
let dateStr = post["发布时间"]! as String
var date = inFormatter.dateFromString(dateStr)
let showLink:String? = post["出现统计"] as String?
let clickLink:String? = post["点击统计"] as String?
let pic = post["缩略图"] as? Dictionary<String, AnyObject>
var picName : String? = nil
if pic != nil {
picName = pic!["filename"] as String?
}
var sourceName: String?
if let source = post["来源"] as? Dictionary<String, AnyObject> {
if let sName = source["名称"] as String? {
var sTime = YTools.getRelativeTime(date!)
sourceName = "\(sName) 发表于 \(sTime)"
}
}
var noTime = true
if self.loggedDate?.compare(date!) == NSComparisonResult.OrderedDescending {
let cal = NSCalendar.currentCalendar()
var com = cal.components(NSCalendarUnit.CalendarUnitYear|NSCalendarUnit.CalendarUnitMonth|NSCalendarUnit.CalendarUnitDay, fromDate: date!)
self.loggedDate = cal.dateFromComponents(com)
var categoryDate = CategoryDateData()
categoryDate.date = self.loggedDate
categoryDate.text = outFormatter.stringFromDate(self.loggedDate!)
PostList.sharedInstance.appendCategoryList(categoryDate)
noTime = false
}
if noTime {
var blank = BlankData()
PostList.sharedInstance.appendHomeList(blank)
}
var categoryPost = PostData()
categoryPost.title = title
categoryPost.clickLink = clickLink
categoryPost.source = sourceName
categoryPost.link = "http://www.bundpic.com/mpost/\(id)"
if link != nil {
if let linkUrl : NSURL? = NSURL(string: link!) {
if linkUrl != nil && linkUrl?.scheme != nil {
categoryPost.link = link
}
}
}
if picName != nil {
categoryPost.imgLink = "http://www.bundpic.com/upload/\(picName!)"
} else {
categoryPost.imgLink = image
}
PostList.sharedInstance.appendCategoryList(categoryPost)
if let url:String = showLink {
if let nsurl: NSURL = NSURL(string: url)? {
Network.callUrl(url)
}
}
}
if postArr.count == 0 {
self.pageEnd = true
listener(false,nil)
return
}
listener(true, PostList.sharedInstance.cateList)
})
}
func selectData(index: Int) {
if let post = PostList.sharedInstance.cateList[index] as? PostData {
PostList.sharedInstance.cateListIndex = index
if let url:String = post.clickLink {
if let nsurl: NSURL = NSURL(string: url)? {
Network.callUrl(url)
}
}
if let postUrl:String = post.link {
openUrl(postUrl)
}
} else if let focus = PostList.sharedInstance.cateList[index] as? CategoryFocusData{
PostList.sharedInstance.cateListIndex = index
if let url:String = focus.clickLink {
if let nsurl: NSURL = NSURL(string: url)? {
Network.callUrl(url)
}
}
if let postUrl:String = focus.link {
openUrl(postUrl)
}
}
}
var segueUrl: String = ""
func openUrl(url:String) {
if url == "" || url == "undefined"{
return
}
segueUrl = url
if let _ = url.rangeOfString("http://www.bundpic.com/mpost/") {
performSegueWithIdentifier("openpost", sender: self)
} else {
performSegueWithIdentifier("openweb", sender: self)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
var view:UIViewController = segue.destinationViewController as UIViewController
if let webView:WebViewController = view as? WebViewController {
webView.url = segueUrl
} else if let webView:PostViewController = view as? PostViewController {
webView.url = segueUrl
webView.getNext = PostList.sharedInstance.cateListNext
}
}
func swipeUp() {
setTabBarVisible(false, animated: true)
}
func swipeDown() {
setTabBarVisible(true, animated: true)
}
func setTabBarVisible(visible:Bool, animated:Bool) {
//* This cannot be called before viewDidLayoutSubviews(), because the frame is not set before this time
// bail if the current state matches the desired state
if (tabBarIsVisible() == visible) { return }
// get a frame calculation ready
let frame = self.tabBarController?.tabBar.frame
let height = frame?.size.height
let offsetY = (visible ? -height! : height)
// zero duration means no animation
let duration:NSTimeInterval = (animated ? 0.3 : 0.0)
// animate the tabBar
if frame != nil {
UIView.animateWithDuration(duration) {
self.tabBarController?.tabBar.frame = CGRectOffset(frame!, 0, offsetY!)
return
}
}
}
func tabBarIsVisible() ->Bool {
return self.tabBarController?.tabBar.frame.origin.y < CGRectGetMaxY(self.view.frame)
}
}
|
// DomRoundTripTableViewCell.swift
import UIKit
class AirLinesCell: UITableViewCell {
@IBOutlet weak var airlineLogo: UIImageView!
@IBOutlet weak var centerLine: UIImageView!
@IBOutlet weak var airlineName: UILabel!
@IBOutlet weak var depTime: UILabel!
@IBOutlet weak var arrTime: UILabel!
@IBOutlet weak var fromCityCode: UILabel!
@IBOutlet weak var toCityCode: UILabel!
@IBOutlet weak var duration: UILabel!
@IBOutlet weak var stops: UILabel!
@IBOutlet weak var specialTag: UILabel!
@IBOutlet weak var grossFare: UILabel!
@IBOutlet weak var netFare: UILabel!
@IBOutlet weak var arrTime_splitView: UILabel!
@IBOutlet weak var netFare_splitView: UILabel!
@IBOutlet weak var logoHightConst: NSLayoutConstraint!
@IBOutlet weak var logoWidthConst: NSLayoutConstraint!
@IBOutlet weak var depTimeLeftConst: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
self.layoutIfNeeded()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func layoutSubviews() {
super.layoutSubviews()
DispatchQueue.main.async {
if self.frame.size.width < 200 {
self.arrTime_splitView.isHidden = false
self.netFare_splitView.isHidden = false
self.airlineLogo.isHidden = false
self.depTime.isHidden = false
self.logoHightConst.constant = 45
self.logoWidthConst.constant = 45
self.depTimeLeftConst.constant = 10
self.depTime.font = AppFont.bodyFont
self.arrTime_splitView.font = AppFont.bodyFont
self.netFare_splitView.font = UIFont.systemFont(ofSize: 16)
self.airlineName.isHidden = true
self.arrTime.isHidden = true
self.fromCityCode.isHidden = true
self.toCityCode.isHidden = true
self.duration.isHidden = true
self.stops.isHidden = true
self.specialTag.isHidden = true
self.grossFare.isHidden = true
self.netFare.isHidden = true
self.centerLine.isHidden = true
}else{
self.arrTime_splitView.isHidden = true
self.netFare_splitView.isHidden = true
self.logoHightConst.constant = 56
self.logoWidthConst.constant = 56
self.depTimeLeftConst.constant = 64
self.depTime.font = UIFont.systemFont(ofSize: 18)
self.airlineLogo.isHidden = false
self.airlineName.isHidden = false
self.depTime.isHidden = false
self.arrTime.isHidden = false
self.fromCityCode.isHidden = false
self.toCityCode.isHidden = false
self.duration.isHidden = false
self.stops.isHidden = false
self.specialTag.isHidden = false
self.grossFare.isHidden = false
self.netFare.isHidden = false
self.centerLine.isHidden = false
}
}
}
}
|
//
// CreatePaymentDataSource.swift
// Hippo
//
// Created by Vishal on 21/02/19.
//
import UIKit
class CreatePaymentDataSource: NSObject {
var store: PaymentStore
var shouldSavePaymentPlan : Bool?
init(store: PaymentStore) {
self.store = store
}
enum DataSourceSection: Int, CaseCountable {
case fields = 0
case items
case button
}
}
extension CreatePaymentDataSource: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return DataSourceSection.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let tableSection = DataSourceSection(rawValue: section) else {
return 0
}
switch tableSection {
case .fields:
return store.fields.count
case .items:
return store.items.count
case .button:
return store.buttons.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let tableSection = DataSourceSection(rawValue: indexPath.section) else {
return UITableView.defaultCell()
}
switch tableSection {
case .fields:
let customCell = tableView.dequeueReusableCell(withIdentifier: "BroadCastTextFieldCell", for: indexPath) as! BroadCastTextFieldCell
let form = store.fields[indexPath.row]
customCell.setupCell(form: form)
customCell.isUserInteractionEnabled = store.isEditing
return customCell
case .button:
let value = store.buttons[indexPath.row]
switch value.action {
case .addMore:
let customCell = tableView.dequeueReusableCell(withIdentifier: "ShowMoreTableViewCell", for: indexPath) as! ShowMoreTableViewCell
customCell.button_CheckBox.isHidden = ((store.canEditPlan ?? false) || (store.isCustomisedPayment ?? false)) ? true : false
customCell.button_CheckBox.imageView?.tintColor = .black
customCell.button_CheckBox.isSelected = shouldSavePaymentPlan ?? false
customCell.button_CheckBox.setImage((shouldSavePaymentPlan ?? false) ? HippoConfig.shared.theme.checkBoxActive : HippoConfig.shared.theme.checkBoxInActive, for: .normal)
customCell.totalPriceLabel.text = ((store.canEditPlan ?? false) || (store.isCustomisedPayment ?? false)) ? " " : HippoStrings.savePlan
customCell.setupCell(form: value, store: store)
return customCell
default:
let customCell = tableView.dequeueReusableCell(withIdentifier: "BroadcastButtonCell", for: indexPath) as! BroadcastButtonCell
customCell.setupCellFor(form: value)
return customCell
}
case .items:
let customCell = tableView.dequeueReusableCell(withIdentifier: "PaymentItemDescriptionCell", for: indexPath) as! PaymentItemDescriptionCell
customCell.isCustomPayment = store.isCustomisedPayment
customCell.hideTitleTextField(store.isCustomisedPayment ?? false)
let item = store.items[indexPath.row]
let count = store.items.count
customCell.setupCellFor(item: item)
customCell.isUserInteractionEnabled = store.isEditing
customCell.cancelIcon.isHidden = count == 1 || !store.isEditing
return customCell
}
}
}
|
public func width(_ size: Size) -> Feature {
return .init(key: "width", value: size.value())
}
public func maxWidth(_ size: Size) -> Feature {
return .init(key: "max-width", value: size.value())
}
public func minWidth(_ size: Size) -> Feature {
return .init(key: "min-width", value: size.value())
}
|
//
// MapMarker.swift
// bm-persona
//
// Created by Kevin Hu on 2/24/20.
// Copyright © 2020 RJ Pimentel. All rights reserved.
//
import Foundation
import UIKit
import MapKit
// MARK: - KnownType
enum KnownType<T: RawRepresentable>: RawRepresentable {
typealias RawValue = T.RawValue
case known(type: T)
case unknown(raw: RawValue)
var rawValue: RawValue {
switch self {
case .known(let type):
return type.rawValue
case .unknown(let raw):
return raw
}
}
init?(rawValue: RawValue) {
let type = T(rawValue: rawValue)
if let type = type {
self = .known(type: type)
} else {
self = .unknown(raw: rawValue)
}
}
}
// MARK: - MapMarkerType
/**
Lists all recognized Map Marker Types, where the `rawValue` is the Collection
name on Firebase. Add to this enum to add another type of map resource.
*/
enum MapMarkerType: String, CaseIterable, Comparable {
case restaurant = "Restaurant"
case cafe = "Cafe"
case store = "Store"
case mentalHealth = "Mental Health"
case garden = "Campus Garden"
case bikes = "Lyft Bike"
case lactation = "Lactation"
case rest = "Rest"
case microwave = "Microwave"
case printer = "Printer"
case water = "Water"
case waste = "Waste"
case none = "_none"
static func < (lhs: MapMarkerType, rhs: MapMarkerType) -> Bool {
// Compare marker types by their declaration order
guard let lhsIdx = allCases.firstIndex(of: lhs), let rhsIdx = allCases.firstIndex(of: rhs) else {
return true
}
return lhsIdx < rhsIdx
}
/** The icon to be shown on the map at the marker location */
func icon() -> UIImage {
let icon: UIImage?
switch self {
case .microwave:
icon = UIImage(named: "microwave-icon")?
.withShadow()
break
case .rest:
icon = UIImage(named: "nap-pods-icon")?
.withRoundedBorder(width: 3, color: .white)?
.withShadow()
break
case .printer:
icon = UIImage(named: "printer-icon")?
.withRoundedBorder(width: 3, color: .white)?
.withShadow()
break
case .water:
icon = UIImage(named: "water-bottle-icon")?
.withShadow()
break
case .bikes:
icon = UIImage(named: "bike-icon")?
.withRoundedBorder(width: 3, color: .white)?
.withShadow()
break
case .lactation:
icon = UIImage(named: "lactation-icon")?
.withShadow()
break
case .waste:
icon = UIImage(named: "waste-icon")
break
case .garden:
icon = UIImage(named: "garden-icon")?
.withShadow()
break
case .cafe:
icon = UIImage(named: "cafe-icon")?
.withShadow()
break
case .store:
icon = UIImage(named: "store-icon")?
.withRoundedBorder(width: 3, color: .white)?
.withShadow()
break
case .mentalHealth:
icon = UIImage(named: "mental-health-icon")?
.withShadow()
break
default:
icon = UIImage(named: "Placemark")?
.colored(Color.MapMarker.other)
break
}
return (icon ?? UIImage()).resized(size: CGSize(width: 30, height: 30))
}
/** The color describing this marker type */
func color() -> UIColor {
switch self {
case .microwave:
return Color.MapMarker.microwave
case .rest:
return Color.MapMarker.rest
case .printer:
return Color.MapMarker.printer
case .water:
return Color.MapMarker.water
case .bikes:
return Color.MapMarker.bikes
case .lactation:
return Color.MapMarker.lactation
case .waste:
return Color.MapMarker.waste
case .garden:
return Color.MapMarker.garden
case .store:
return Color.MapMarker.store
case .cafe:
return Color.MapMarker.cafe
case .mentalHealth:
return Color.MapMarker.mentalHealth
default:
return Color.MapMarker.other
}
}
}
// MARK: - MapMarker
/** Object describing resource locations (Microwaves, Bikes, Nap Pods, etc.) */
class MapMarker: NSObject, MKAnnotation, HasOpenTimes, SearchItem {
var type: KnownType<MapMarkerType>
var coordinate: CLLocationCoordinate2D
@Display var title: String?
@Display var subtitle: String?
@Display var phone: String?
@Display var email: String?
@Display var address: String?
var onCampus: Bool?
var weeklyHours: WeeklyHours?
var appointment: Bool?
var mealPrice: String?
var cal1Card: Bool?
var eatWell: Bool?
var searchName: String
var location: (Double, Double)
var locationName: String
var icon: UIImage?
var name: String
init?(type: String,
location: CLLocationCoordinate2D,
name: String? = nil,
description: String? = nil,
address: String? = nil,
onCampus: Bool? = nil,
phone: String? = nil,
email: String? = nil,
weeklyHours: WeeklyHours? = nil,
appointment: Bool? = nil,
mealPrice: String? = nil,
cal1Card: Bool? = nil,
eatWell: Bool? = nil) {
guard let type = KnownType<MapMarkerType>(rawValue: type) else { return nil }
self.type = type
self.coordinate = location
self.title = name
self.subtitle = description
self.address = address
self.onCampus = onCampus
self.phone = phone
self.email = email
self.weeklyHours = weeklyHours
self.mealPrice = mealPrice
self.cal1Card = cal1Card
self.eatWell = eatWell
self.searchName = name ?? ""
self.location = (location.latitude, location.longitude)
self.locationName = address ?? ""
self.icon = nil
self.name = name ?? ""
}
}
|
//
// LPJNavigationController.swift
// LightPomodoro
//
// Created by 王嘉宁 on 2020/12/9.
// Copyright © 2020 Johnny. All rights reserved.
//
import UIKit
class LPJNavigationController: UINavigationController {
}
|
//
// ViewController.swift
// Past Paper Crawler
//
// Created by 吴浩榛 on 2018/8/26.
// Copyright © 2018年 吴浩榛. All rights reserved.
//
import Cocoa
class MainViewController: NSViewController {
@IBOutlet var quickOpComboBox: NSComboBox!
@IBOutlet var quickOpPerformButton: NSButton!
@IBOutlet var quickOpProcess: NSProgressIndicator!
@IBOutlet var quickOpPromptLabel: PromptLabel!
@IBOutlet var quickOpRetryButton: NSButton!
var quickOpRetryAction: () -> () = {} {
didSet {
quickOpRetryButton.isHidden = false
}
}
var quickOpPossiblePapers: [WebFile] = [] {
didSet {
quickOpComboBox.reloadData()
}
}
var currentCode = ""
var currentSubjectPrompt = ""
var accessCount = 0
@IBOutlet var subjectPopButton: QuickListPopUpButton!
let subjectPopButtonOperationQueue = DispatchQueue(label: "Subject Pop Button Protect")
var defaultPopButtonPrompt = ""
@IBOutlet weak var subjectProgress: NSProgressIndicator!
@IBOutlet var subjectPromptLabel: PromptLabel!
enum Mode {
case Subject
case Paper
}
var quickOpMode: Mode = .Paper {
willSet {
if newValue != quickOpMode {
if newValue == .Subject {
quickOpPerformButton.title = "open sub"
}
else {
quickOpPerformButton.title = "download"
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
quickOpComboBox.usesDataSource = true
quickOpComboBox.dataSource = self
quickOpComboBox.delegate = self
quickOpMode = .Subject
}
@IBAction func operationConfirmed(_ sender: Any) {
let text = quickOpComboBox.stringValue
if quickOpMode == .Subject {
if !quickOpPerformButton.isHidden {
subjectPopButton.performConfirmSelection()
}
}
else if let selectedPaper = quickOpPossiblePapers.first(where: { $0.name == text }) {
quickOpDownload(paper: selectedPaper)
}
}
func quickOpDownload(paper: WebFile, to path: String? = nil) {
quickOpProcess.startAnimation(nil)
quickOpPromptLabel.showPrompt("Downloading...")
quickOpComboBox.isEnabled = false
quickOpPerformButton.isEnabled = false
ADDownload(papers: [paper], to: path) {
path, failed in
DispatchQueue.main.async {
if !failed.isEmpty {
self.quickOpPromptLabel.showError("Failed!")
self.quickOpRetryAction = {
self.quickOpDownload(paper: paper, to: path)
}
}
else {
self.quickOpPromptLabel.showPrompt("Succeed!")
}
self.quickOpProcess.stopAnimation(nil)
self.quickOpComboBox.isEnabled = true
self.quickOpPerformButton.isEnabled = true
}
}
}
@IBAction func retryClicked(_ sender: Any) {
quickOpRetryButton.isHidden = true
quickOpRetryAction() // fire action
}
func startLoadingSubject() {
// lock up button
quickOpComboBox.isEnabled = false
quickOpPerformButton.isEnabled = false
subjectPopButton.isEnabled = false
subjectProgress.startAnimation(nil)
}
func endLoadingSubject() {
}
var _subjactLoading: Bool = false
var subjectLoading: Bool {
get {
return _subjactLoading
}
set {
_subjactLoading = newValue
if newValue {
// lock up button
quickOpComboBox.isEnabled = false
quickOpPerformButton.isEnabled = false
subjectPopButton.isEnabled = false
subjectProgress.startAnimation(nil)
}
else {
quickOpComboBox.isEnabled = true
quickOpPerformButton.isEnabled = true
subjectPopButton.isEnabled = true
subjectProgress.stopAnimation(nil)
}
}
}
@IBAction func subjectSelected(_ sender: Any) {
if let subject = subjectPopButton.selectedSubject {
var undone = false
undoManager?.registerUndo(withTarget: subjectPopButton) { _ in
undone = true
self.subjectLoading = false
}
subjectPromptLabel.setToDefault()
subjectLoading = true
let paperWindow: NSWindowController = getController("Papers Window")!
let paperView = paperWindow.contentViewController as! PapersViewController
DispatchQueue.global(qos: .userInteractive).async {
defer {
DispatchQueue.main.async {
self.subjectLoading = false
self.undoManager?.removeAllActions()
}
}
// load current subject
if !paperView.rawLoad(subject: subject) {
DispatchQueue.main.async {
self.subjectPromptLabel.showError("Failed to load subject!")
}
return
}
if undone { return }
DispatchQueue.main.async {
// display paper window
paperView.subjectPopButton.selectedSubject = subject
paperView.defaultUpdateAfterLoadingSubject()
paperWindow.showWindow(nil)
// set back prompt
self.subjectPopButton.discardSelectedSubject()
self.quickOpPerformButton.isHidden = true
}
}
}
}
}
extension MainViewController: NSComboBoxDelegate {
func controlTextDidChange(_ obj: Notification) {
quickOpRetryButton.isHidden = true
let text = quickOpComboBox.stringValue
if text.isEmpty {
quickOpPromptLabel.setToDefault()
return
}
if text[0] < "0" || text[0] > "9" {
findSubject()
}
else {
loadPapers()
}
}
func findSubject() {
quickOpMode = .Subject
quickOpPromptLabel.setToDefault()
quickOpPossiblePapers = []
let text = quickOpComboBox.stringValue
subjectPopButtonOperationQueue.sync { // find subject from quick list
let lowercasedText = text.lowercased()
var found = false
for index in 2..<2+PFQuickListCount {
if let item = subjectPopButton.item(at: index), item.isEnabled && item.title.lowercased().hasPrefix(lowercasedText) {
DispatchQueue.main.async {
self.subjectPopButton.select(item)
self.quickOpMode = .Subject
self.quickOpPerformButton.isHidden = false
}
found = true
break
}
}
if !found {
quickOpPerformButton.isHidden = true
}
}
}
func loadPapers() {
quickOpMode = .Paper
let text = quickOpComboBox.stringValue
quickOpPerformButton.isHidden = !quickOpPossiblePapers.contains(where: { $0.name == text })
let count = text.count
if count < 4 {
quickOpPossiblePapers = []
if count > 0 {
quickOpPromptLabel.showError("Subject code incomplete!")
}
currentCode = ""
currentSubjectPrompt = ""
quickOpProcess.stopAnimation(nil)
return
}
let code = text[0...3]
if code != currentCode {
currentCode = code
loadSubject(code: code)
}
else if !currentSubjectPrompt.isEmpty {
quickOpPromptLabel.showPrompt(currentSubjectPrompt)
}
}
func loadSubject(code: String) {
quickOpPromptLabel.showPrompt("Loading subject...")
quickOpProcess.startAnimation(nil)
accessCount += 1
DispatchQueue.global(qos: .userInteractive).async {
defer {
DispatchQueue.main.async {
self.accessCount -= 1
if self.accessCount == 0 {
self.quickOpProcess.stopAnimation(nil)
}
}
}
guard let subject = SubjectUtil.current.findSubject(with: code) else {
DispatchQueue.main.async {
self.quickOpPossiblePapers = []
self.quickOpPromptLabel.showError("Failed to find subject code!")
self.quickOpRetryAction = {
self.loadSubject(code: code)
}
}
return
}
if self.currentCode != code {
return
}
guard let files = PFUsingWebsite.getPapers(level: subject.level, subject: subject.name) else {
DispatchQueue.main.async {
self.quickOpPossiblePapers = []
self.quickOpPromptLabel.showError("Failed to get paper list!")
self.quickOpRetryAction = {
self.loadSubject(code: code)
}
}
return
}
if self.currentCode != code {
return
}
DispatchQueue.main.async {
self.quickOpPossiblePapers = files
self.currentSubjectPrompt = "Subject: \(subject.name)"
self.quickOpPromptLabel.showPrompt(self.currentSubjectPrompt)
}
}
}
}
extension MainViewController: NSComboBoxDataSource {
func numberOfItems(in comboBox: NSComboBox) -> Int {
return quickOpPossiblePapers.count
}
func comboBox(_ comboBox: NSComboBox, objectValueForItemAt index: Int) -> Any? {
return quickOpPossiblePapers[index].name
}
}
|
//
// Copyright © 2020 Tasuku Tozawa. All rights reserved.
//
import Combine
import Domain
protocol SettingsViewProtocol: AnyObject {
func set(version: String)
func set(isICloudSyncEnabled: Bool)
func confirmToUnavailabilityICloudSync(shouldTurnOff: @escaping (Bool) -> Void)
func confirmToUnavailabilityICloudSync(shouldTurnOn: @escaping (Bool) -> Void)
func confirmToTurnOffICloudSync(confirmation: @escaping (Bool) -> Void)
}
class SettingsPresenter {
private let storage: UserSettingsStorageProtocol
private let availabilityStore: CloudAvailabilityStore
private var subscriptions: Set<AnyCancellable> = .init()
private(set) var shouldHideHiddenItems: CurrentValueSubject<Bool, Never>
private(set) var shouldSyncICloudEnabled: CurrentValueSubject<Bool, Never>
weak var view: SettingsViewProtocol?
// MARK: - Lifecycle
init(storage: UserSettingsStorageProtocol,
availabilityStore: CloudAvailabilityStore)
{
self.storage = storage
self.availabilityStore = availabilityStore
self.shouldHideHiddenItems = .init(false)
self.shouldSyncICloudEnabled = .init(false)
self.storage.showHiddenItems
.receive(on: DispatchQueue.main)
.map { !$0 }
.sink(receiveValue: { [weak self] value in
self?.shouldHideHiddenItems.send(value)
})
.store(in: &self.subscriptions)
self.storage.enabledICloudSync
.combineLatest(self.availabilityStore.state)
.receive(on: DispatchQueue.main)
.sink(receiveValue: { [weak self] settingEnabled, availability in
let isOn = settingEnabled && availability?.isAvailable == true
self?.shouldSyncICloudEnabled.send(isOn)
})
.store(in: &self.subscriptions)
}
func set(hideHiddenItems: Bool) {
self.storage.set(showHiddenItems: !hideHiddenItems)
}
func set(isICloudSyncEnabled: Bool) -> Bool {
guard let availability = self.availabilityStore.state.value else { return false }
if isICloudSyncEnabled, availability == .unavailable {
let isEnabledICloudSync = self.storage.readEnabledICloudSync()
if isEnabledICloudSync {
self.view?.confirmToUnavailabilityICloudSync(shouldTurnOff: { [weak self] shouldTurnOff in
guard shouldTurnOff else { return }
self?.view?.confirmToTurnOffICloudSync { isOk in
guard isOk else { return }
self?.storage.set(enabledICloudSync: false)
}
})
} else {
self.view?.confirmToUnavailabilityICloudSync(shouldTurnOn: { [weak self] shouldTurnOn in
guard shouldTurnOn else { return }
self?.storage.set(enabledICloudSync: true)
})
}
return false
}
if isICloudSyncEnabled {
self.storage.set(enabledICloudSync: true)
} else {
self.view?.confirmToTurnOffICloudSync { [weak self] isOk in
guard isOk else {
self?.view?.set(isICloudSyncEnabled: true)
return
}
self?.storage.set(enabledICloudSync: false)
}
}
return true
}
func displayVersion() {
// swiftlint:disable:next force_cast force_unwrapping
let versionString = Bundle(for: Self.self).infoDictionary!["CFBundleShortVersionString"] as! String
self.view?.set(version: "\(versionString)")
}
}
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
var platesArray = [1,2,3,4,5,5,5,5,9,10,11,12]
for i in platesArray{
i
}
for var i = 0; i < platesArray.count; i++ {
++platesArray[i]
}
var plates = [10,0,2,0,0,0]
var thePlates = [0,0,0,0,0,0]
//1 is 45
//2 is 35
//3 is 25
//4 is 10
//5 is 5
//if there are more than 12 45 plates make it so theres only 12 in the array
if plates[0] > 12 {
for var i = 0; i < thePlates.count; i++ {
thePlates[i] = 1
//return the array
}
}
var plateRefs = [Int]()
for var i = 0; i < thePlates.count; i++ {
if plates[i] == 2 && i == 0 {
thePlates[i] = 1
plateRefs.append(1)
} else if plates[i] == 2 && i == 1 {
thePlates[i] = 2
plateRefs.append(2)
} else if plates[i] == 2 && i == 2 {
thePlates[i] = 3
plateRefs.append(3)
} else if plates[i] == 2 && i == 3 {
thePlates[i] = 4
plateRefs.append(4)
} else if plates[i] == 2 && i == 4 {
thePlates[i] = 5
plateRefs.append(5)
} else if plates[0] == 4 && i == 0 {
plateRefs.append(1)
plateRefs.append(1)
} else if plates[0] == 6 && i == 0 {
plateRefs.append(1)
plateRefs.append(1)
plateRefs.append(1)
} else if plates[0] == 8 && i == 0 {
plateRefs.append(1)
plateRefs.append(1)
plateRefs.append(1)
plateRefs.append(1)
} else if plates[0] == 10 && i == 0 {
plateRefs.append(1)
plateRefs.append(1)
plateRefs.append(1)
plateRefs.append(1)
plateRefs.append(1)
}
print(plateRefs)
var temp = plateRefs
for var i = 0; i < plateRefs.count; i++ {
temp.append(plateRefs[i])
}
println(temp)
temp.sort({ (T: Int, P: Int) -> Bool in
return P > T
})
println(temp)
// temp.sort({ (a,b) -> Bool in
// println(temp)
// })
}
|
//
// AddTableViewController.swift
// FoodPin
//
// Created by 廖慶麟 on 2016/2/25.
// Copyright © 2016年 廖慶麟. All rights reserved.
//
import UIKit
import Foundation
import CoreData
import CloudKit
class AddTableViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
@IBOutlet weak var imageView:UIImageView!
@IBOutlet weak var nameTextField:UITextField!
@IBOutlet weak var typeTextField:UITextField!
@IBOutlet weak var locationTextField:UITextField!
@IBOutlet weak var yesButton:UIButton!
@IBOutlet weak var noButton:UIButton!
var restaurant:Restaurant!
override func viewDidLoad() {
super.viewDidLoad()
yesButton.addTarget(self, action: "yesButtonTapped", forControlEvents: .TouchUpInside)
noButton.addTarget(self, action: "noButtonTapped", forControlEvents: .TouchUpInside)
nameTextField.delegate = self;
typeTextField.delegate = self;
locationTextField.delegate = self;
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 0 {
if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = false
imagePicker.sourceType = .PhotoLibrary
self.presentViewController(imagePicker, animated: true, completion: nil)
}
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
// when press return on keyboard, then dismiss it!
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// After user finishes picking pictures.
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
imageView.image =
info[UIImagePickerControllerOriginalImage] as? UIImage
imageView.contentMode = UIViewContentMode.ScaleAspectFill
imageView.clipsToBounds = true
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func save(){
let alert = UIAlertView()
var emptyfield: String!
if nameTextField.text == "" {
emptyfield = "restaurant name"
}
else if typeTextField.text == "" {
emptyfield = "restaurant type"
}
else if locationTextField.text == "" {
emptyfield = "restaurant location"
}
if emptyfield == nil {
var isVisited: Bool = true
if noButton.backgroundColor == UIColor.redColor(){
isVisited = false
}
// Save object to CoreData
if let managedObjectContext = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext {
restaurant = NSEntityDescription.insertNewObjectForEntityForName("Restaurant", inManagedObjectContext: managedObjectContext) as! Restaurant
restaurant.name = nameTextField.text
restaurant.type = typeTextField.text
restaurant.location = locationTextField.text
restaurant.image = UIImagePNGRepresentation(imageView.image!)
restaurant.isVisited = isVisited
var e: NSError?
do {
try managedObjectContext.save()
} catch {
print("insert error: \(e!.localizedDescription)")
}
saveRecordToCloud(restaurant)
performSegueWithIdentifier("unwindToHomeScreen", sender: self)
}
}else {
alert.title = "Ooops"
alert.message = "We can't proceed as you forget to fill in the \(emptyfield). All fields are mandatory."
alert.addButtonWithTitle("OK")
alert.show()
}
}
func noButtonTapped(){
noButton.backgroundColor = UIColor.redColor()
yesButton.backgroundColor = UIColor.lightGrayColor()
}
func yesButtonTapped(){
yesButton.backgroundColor = UIColor.redColor()
noButton.backgroundColor = UIColor.lightGrayColor()
}
func saveRecordToCloud(restaurant:Restaurant!) -> Void {
// Prepare the record to save
var record = CKRecord(recordType: "Restaurant")
record.setValue(restaurant.name, forKey:"name")
record.setValue(restaurant.type, forKey:"type")
record.setValue(restaurant.location, forKey:"location")
// Resize the image
var originalImage = UIImage(data: restaurant.image)
var scalingFactor = (originalImage!.size.width > 1024) ? 1024 / originalImage!.size.width : 1.0
var scaledImage = UIImage(data: restaurant.image, scale: scalingFactor)
// Write the image to local file for temporary use
let imageFilePath = NSTemporaryDirectory() + restaurant.name
UIImageJPEGRepresentation(scaledImage!, 0.8)?.writeToFile(imageFilePath, atomically: true)
// Create image asset for upload
let imageFileURL = NSURL(fileURLWithPath: imageFilePath)
var imageAsset = CKAsset(fileURL: imageFileURL)
record.setValue(imageAsset, forKey: "image")
// Get the Public iCloud Database
let cloudContainer = CKContainer.defaultContainer()
let publicDatabase =
CKContainer.defaultContainer().publicCloudDatabase
// Save the record to iCloud
publicDatabase.saveRecord(record, completionHandler: {
(record:CKRecord?, error:NSError?) -> Void in
// Remove temp file
var err:NSError?
do{
try NSFileManager.defaultManager().removeItemAtPath(imageFilePath)
} catch {
print("Failed to save record to the cloud: \(err?.localizedDescription)")
}
})
}
// MARK: - Table view data source
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// SessionManager+Exposure.swift
// Exposure
//
// Created by Fredrik Sjöberg on 2017-10-13.
// Copyright © 2017 emp. All rights reserved.
//
import Foundation
import iOSClientDownload
import iOSClientExposure
extension iOSClientDownload.SessionManager where T == ExposureDownloadTask {
/* /// Create an `ExposureDownloadTask` by requesting a `PlaybackEntitlementV2` supplied through exposure.
///
/// If the requested content is *FairPlay* protected, the appropriate `DownloadExposureFairplayRequester` will be created. Configuration will be taken from the `PlaybackEntitlementV2` response.
///
/// A relevant `ExposureAnalytics` object will be created.
///
/// - parameter assetId: A unique identifier for the asset
/// - parameter sessionToken: Token identifying the active session
/// - parameter environment: Exposure environment used for the active session
/// - returns: `ExposureDownloadTask`
public func download(assetId: String, using sessionToken: SessionToken, in environment: Environment) -> T {
let provider = ExposureAnalytics(environment: environment, sessionToken: sessionToken)
return download(assetId: assetId, analyticProvider: provider)
}
*/
public func download(assetId: String, using sessionToken: SessionToken, in environment: Environment) -> T {
return download(assetId: assetId, sessionToken: sessionToken, environment: environment)
}
}
extension iOSClientDownload.SessionManager where T == ExposureDownloadTask {
/*
Remove passing analyticsProvider temporary
/// Create an `ExposureDownloadTask` by requesting a `PlaybackEntitlementV2` supplied through exposure.
///
/// Entitlement requests will be done by using the `Environment` and `SessionToken` associated with `analyticsProvider`
///
/// If the requested content is *FairPlay* protected, the appropriate `DownloadExposureFairplayRequester` will be created. Configuration will be taken from the `PlaybackEntitlementV2` response.
///
/// - parameter assetId: A unique identifier for the asset
/// - parameter analyticsProvider: The specified analytics provider.
/// - returns: `ExposureDownloadTask`
public func download(assetId: String, analyticProvider: ExposureDownloadAnalyticsProvider) -> T {
if let currentTask = delegate[assetId] {
print("♻️ Retrieved ExposureDownloadTask associated with request for: \(assetId)")
return currentTask
}
else {
print("✅ Created new ExposureDownloadTask for: \(assetId)")
return ExposureDownloadTask(assetId: assetId,
sessionManager: self,
analyticsProvider: analyticProvider)
}
}
*/
/// Create an `ExposureDownloadTask` by requesting a `PlaybackEntitlementV2` supplied through exposure.
///
/// Entitlement requests will be done by using the `Environment` and `SessionToken` associated with `analyticsProvider`
///
/// If the requested content is *FairPlay* protected, the appropriate `DownloadExposureFairplayRequester` will be created. Configuration will be taken from the `PlaybackEntitlementV2` response.
///
/// - Parameters:
/// - assetId: assetId: A unique identifier for the asset
/// - sessionToken: user session token
/// - environment: customer enviornment
/// - Returns: ExposureDownloadTask
public func download(assetId: String, sessionToken: SessionToken, environment: Environment ) -> T {
if let currentTask = delegate[assetId] {
print("♻️ Retrieved ExposureDownloadTask associated with request for: \(assetId)")
return currentTask
}
else {
print("✅ Created new ExposureDownloadTask for: \(assetId)")
return ExposureDownloadTask(assetId: assetId,
sessionManager: self,
sessionToken: sessionToken,
environment: environment)
}
}
}
// MARK: - OfflineMediaAsset
extension iOSClientDownload.SessionManager where T == ExposureDownloadTask {
public func getDownloadedAsset(assetId: String) -> OfflineMediaAsset? {
return getDownloadedAssets()
.filter{ $0.assetId == assetId }
.first
}
public func getDownloadedAssets() -> [OfflineMediaAsset] {
guard let localMedia = localMediaRecords else { return [] }
return localMedia.map{ resolve(mediaRecord: $0) }
}
/// Get downloaded Assets by `accountId`
/// - Parameter accountId: accountId
/// - Returns: array of OfflineMediaAsset
public func getDownloadedAssets(accountId:String?) -> [OfflineMediaAsset] {
guard let localMedia = localMediaRecords else { return [] }
guard let accountId = accountId else {
return []
}
let allLocalMdeia = localMedia.map{ resolve(mediaRecord: $0) }
return allLocalMdeia.filter(){ $0.accountId == accountId }
}
/// Shoud renew licenes for a given asset
/// - Parameters:
/// - assetId: asset Id
/// - sessionToken: session token
/// - environment: environment
/// - completion: completion
public func renewLicense(assetId: String, sessionToken: SessionToken, environment: Environment, completion: @escaping (OfflineMediaAsset?, Error?) -> Void) {
guard let media = getDownloadedAsset(assetId: assetId) else {
print("❌ Could not find local media for renewal: assetId \(assetId)")
let error = ExposureDownloadTask.Error.fairplay(reason: .missingApplicationCertificateUrl)
completion(nil, error)
return
}
self.validateEntitlementRequest(environment: environment, sessionToken: sessionToken, assetId: assetId) { [weak self] newEntitlement, error in
guard let `self` = self else {
completion(nil, nil )
return }
if let error = error {
print("❌ Entitlement granted failed for assetId: \(assetId) , Error \(error)")
completion(nil, error )
} else {
print("✅ New entitlement was granted for assetId : \(assetId)")
do {
if let localRecord = self.getLocalMediaRecordFor(assetId: assetId) {
var updatedLocalRecord = localRecord
updatedLocalRecord.entitlement = newEntitlement
self.save(localRecord: updatedLocalRecord)
let offlineAsset = OfflineMediaAsset(assetId: assetId, accountId: sessionToken.accountId, userId: sessionToken.userId, entitlement: newEntitlement, url: try media.fairplayRequester?.contentKeyUrl(for: assetId), downloadState: .completed, format: media.format, sessionManager: self)
self.sendDownloadRenewed(assetId: assetId, environment:environment, sessionToken: sessionToken )
completion(offlineAsset, nil )
}
} catch {
print("❌ Updating local record with new entitlement was failed for assetId : \(assetId) , Error \(error)")
completion(nil, error)
}
}
}
}
/// Send download renewal completion to the exposure
/// - Parameter assetId: assetId
internal func sendDownloadRenewed(assetId: String, environment: Environment, sessionToken: SessionToken) {
SendDownloadRenewed(assetId: assetId, environment: environment, sessionToken: sessionToken)
.request()
.validate()
.response { result in
if result.error != nil {
// Ignore any errors , keep the downloaded media
print("🚨 DownloadRenewed request to the Backend was failed. Error from Exposure : \(result.error )" )
} else {
print("✅ DownloadRenewed request to the Backend was success. Message from Exposure : \(result.value )" )
}
}
}
fileprivate func validateEntitlementRequest(environment:Environment,sessionToken:SessionToken, assetId: String, completionHandler: @escaping (PlayBackEntitlementV2?, ExposureError?) -> Void) {
let _ = Entitlement(environment:environment,
sessionToken: sessionToken)
.validate(downloadId: assetId)
.request()
.validate()
.response {
guard let entitlement = $0.value else {
// self.eventPublishTransmitter.onError(self, nil, $0.error!)
completionHandler(nil, $0.error)
return
}
completionHandler(entitlement, nil )
}
}
/// Get downloaded Assets by `userId`
/// - Parameter userId: userId
/// - Returns: array of OfflineMediaAsset
public func getDownloadedAssets(userId:String?) -> [OfflineMediaAsset] {
guard let localMedia = localMediaRecords else { return [] }
guard let userId = userId else {
return []
}
let allLocalMdeia = localMedia.map{ resolve(mediaRecord: $0) }
return allLocalMdeia.filter(){ $0.userId == userId }
}
public func delete(media: OfflineMediaAsset) {
remove(localRecordId: media.assetId)
do {
try media.fairplayRequester?.deletePersistedContentKey(for: media.assetId)
if let url = media.urlAsset?.url {
try FileManager.default.removeItem(at: url)
}
print("✅ SessionManager+Exposure. Cleaned up local media",media.assetId,"Destination:",media.urlAsset?.url)
}
catch {
print("🚨 SessionManager+Exposure. Failed to clean local media: ",error.localizedDescription)
}
}
/// Delete a downloaded asset
/// - Parameter assetId: assetId
public func removeDownloadedAsset(assetId: String, sessionToken: SessionToken, environment: Environment) {
guard let media = getDownloadedAsset(assetId: assetId) else { return }
delete(media: media)
}
internal func save(assetId: String, accountId:String?, userId:String?, entitlement: PlayBackEntitlementV2?, url: URL?, downloadState: DownloadState) {
do {
if let currentAsset = getDownloadedAsset(assetId: assetId) {
if currentAsset.urlAsset?.url != nil {
print("⚠️ There is another record for an offline asset with id: \(assetId). This data will be overwritten. The location of any downloaded media or content keys will be lost!")
print(" x ",currentAsset.urlAsset?.url)
print(" <- ",url)
}
else {
print("✅ SessionManager+Exposure. Updated \(assetId) with a destination url \(url)")
}
}
let record = try LocalMediaRecord(assetId: assetId, accountId: accountId, userId: userId, entitlement: entitlement, completedAt: url, downloadState: downloadState, format: entitlement?.formats?.first?.format ?? "HLS")
save(localRecord: record)
}
catch {
print("🚨 Unable to bookmark local media record \(assetId): ",error.localizedDescription)
}
}
}
// MARK: - LocalMediaRecord
extension iOSClientDownload.SessionManager where T == ExposureDownloadTask {
/// Get local media record for a given `assetId`
func getLocalMediaRecordFor(assetId: String) -> LocalMediaRecord? {
do {
let logFile = try logFileURL()
let logData = try Data(contentsOf: logFile)
print("Reading... 📖: \(logFile.description)")
let localMedia = try JSONDecoder().decode([LocalMediaRecord].self, from: logData)
let filteredLog = localMedia.filter{ $0.assetId == assetId }.first
return filteredLog
} catch {
print("🚨 Error fetching local media : \(error)")
return nil
}
}
var localMediaRecords: [LocalMediaRecord]? {
do {
let logFile = try logFileURL()
if !FileManager.default.fileExists(atPath: logFile.path) {
return []
}
let data = try Data(contentsOf: logFile)
let localMedia = try JSONDecoder().decode([LocalMediaRecord].self, from: data)
return localMedia
}
catch {
print("localMediaLog failed",error.localizedDescription)
return nil
}
}
fileprivate func resolve(mediaRecord: LocalMediaRecord) -> OfflineMediaAsset {
var bookmarkDataIsStale = false
guard let urlBookmark = mediaRecord.urlBookmark else {
return OfflineMediaAsset(assetId: mediaRecord.assetId, accountId: mediaRecord.accountId, userId: mediaRecord.userId, entitlement: mediaRecord.entitlement, url: nil, downloadState: mediaRecord.downloadState, format: mediaRecord.format, sessionManager: self)
}
do {
let url = try URL(resolvingBookmarkData: urlBookmark, bookmarkDataIsStale: &bookmarkDataIsStale)
/* guard let url = try URL(resolvingBookmarkData: urlBookmark, bookmarkDataIsStale: &bookmarkDataIsStale) else {
return OfflineMediaAsset(assetId: mediaRecord.assetId, entitlement: mediaRecord.entitlement, url: nil)
} */
guard !bookmarkDataIsStale else {
return OfflineMediaAsset(assetId: mediaRecord.assetId, accountId: mediaRecord.accountId, userId: mediaRecord.userId, entitlement: mediaRecord.entitlement, url: nil, downloadState: mediaRecord.downloadState, format: mediaRecord.format, sessionManager: self)
}
return OfflineMediaAsset(assetId: mediaRecord.assetId, accountId: mediaRecord.accountId, userId: mediaRecord.userId, entitlement: mediaRecord.entitlement, url: url, downloadState: mediaRecord.downloadState, format: mediaRecord.format, sessionManager: self)
}
catch {
return OfflineMediaAsset(assetId: mediaRecord.assetId, accountId: mediaRecord.accountId, userId: mediaRecord.userId, entitlement: mediaRecord.entitlement, url: nil, downloadState: mediaRecord.downloadState, format: mediaRecord.format, sessionManager: self)
}
}
}
// MARK: Directory
extension iOSClientDownload.SessionManager where T == ExposureDownloadTask {
fileprivate var localMediaRecordsFile: String {
return "localMediaRecords"
}
fileprivate func logFileURL() throws -> URL {
return try baseDirectory().appendingPathComponent(localMediaRecordsFile)
}
/// This directory should be reserved for analytics data.
///
/// - returns: `URL` to the base directory
/// - throws: `FileManager` error
internal func baseDirectory() throws -> URL {
return try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent("emp")
.appendingPathComponent("exposure")
.appendingPathComponent("offlineMedia")
}
}
// MARK: Save / Remove
extension iOSClientDownload.SessionManager where T == ExposureDownloadTask {
/// This method will update `LocalMediaLog` with given updated `localRecord`
fileprivate func update(localRecord: LocalMediaRecord) {
var localMedia = localMediaRecords ?? []
let filteredLog = localMedia.filter{ $0.assetId == localRecord.assetId }.first
localMedia.removeAll(where: {$0.assetId == filteredLog?.assetId })
localMedia.append(localRecord)
save(mediaLog: localMedia)
print("✅ Update bookmark for local media record \(localRecord.assetId): ")
}
/// This method will ensure `LocalMediaLog` has a unique list of downloads with respect to `assetId`
fileprivate func save(localRecord: LocalMediaRecord) {
let localMedia = localMediaRecords ?? []
var filteredLog = localMedia.filter{ $0.assetId != localRecord.assetId }
filteredLog.append(localRecord)
save(mediaLog: filteredLog)
print("✅ Saved bookmark for local media record \(localRecord.assetId): ")
}
fileprivate func save(mediaLog: [LocalMediaRecord]) {
do {
let logURL = try baseDirectory()
let data = try JSONEncoder().encode(mediaLog)
try data.persist(as: localMediaRecordsFile, at: logURL)
}
catch {
print("save(mediaLog:) failed",error.localizedDescription)
}
}
internal func remove(localRecordId: String) {
guard let localMedia = localMediaRecords else { return }
/// Update and save new log
let newLog = localMedia.filter{ $0.assetId != localRecordId }
save(mediaLog: newLog)
}
}
// MARK: - Download Info
extension iOSClientDownload.SessionManager where T == ExposureDownloadTask {
/// Returns if an asset is available to download or not
/// - Parameters:
/// - assetId: assetId
/// - environment: enviornment
/// - sessionToken: sessionToken
/// - completionHandler: completion
public func isAvailableToDownload( assetId: String, environment: Environment, sessionToken: SessionToken, _ completionHandler: @escaping (Bool) -> Void) {
self.getDownloadableInfo(assetId: assetId, environment: environment, sessionToken: sessionToken) { [weak self] info in
completionHandler( info != nil ? true : false )
}
}
/// Get downloadable info of an Asset
/// - Parameters:
/// - assetId: assetId
/// - environment: Exposure Enviornment
/// - sessionToken: user sessionToken
/// - completionHandler: completion
public func getDownloadableInfo(assetId: String, environment: Environment, sessionToken: SessionToken, _ completionHandler: @escaping (DownloadInfo?) -> Void) {
GetDownloadableInfo(assetId: assetId, environment: environment, sessionToken: sessionToken)
.request()
.validate()
.response { info in
if let downloadInfo = info.value {
completionHandler(downloadInfo)
} else {
completionHandler(nil)
}
}
}
/// Check if the license has expired or not
/// - Parameter assetId: asset id
/// - Returns: true if the license has expired
public func isExpired(assetId: String)-> Bool {
let downloadedAsset = getDownloadedAsset(assetId: assetId)
guard let playTokenExpiration = downloadedAsset?.entitlement?.playTokenExpiration else {
return true
}
let today = Date().millisecondsSince1970
return playTokenExpiration * 1000 >= today ? false : true
}
/// get the license expiration time
/// - Parameter assetId: asset id
/// - Returns: playTokenExpiration
public func getExpiryTime(assetId: String)->Int? {
let downloadedAsset = getDownloadedAsset(assetId: assetId)
return downloadedAsset?.entitlement?.playTokenExpiration
}
}
|
//
// LeafEdgeImageSelectionView.swift
// florafinder
//
// Created by Andrew Tokeley on 6/05/16.
// Copyright © 2016 Andrew Tokeley . All rights reserved.
//
import Foundation
class LeafEdgeImageSelectionView: ImageSelectionView
{
override internal var cellSize: CGSize
{
return CGSizeMake(70,80)
}
override internal var showLabel: Bool
{
return true
}
override internal var numberOfColumns: Int?
{
return 3
}
var selectedItem: LeafEdgeType?
{
return super._selectedItem?.tag as? LeafEdgeType
}
override internal var datasource: [ImageSelectionData]
{
if (_datasource.count == 0)
{
_datasource = [ImageSelectionData]()
let service = ServiceFactory.shareInstance.leafEdgeTypeService
for edge in service.getAll()
{
if let lookup = LeafEdgeTypeEnum(rawValue: edge.name!)
{
if let image = lookup.image().changeColor(UIColor.leafDarkGreen())
{
let data = ImageSelectionData(image: image, text: edge.name, selected: false)
data.tag = edge
_datasource.append(data)
}
}
}
}
return _datasource
}
}
|
//
// TimerViewController.swift
// StudyUp
//
// Created by Mitchel Eppich on 2017-03-04.
// Copyright © 2017 SFU Health++. All rights reserved.
//
// Contributions from: Owen Kwok, Leone Tory
//
import UIKit
import FirebaseAuth
class TimerViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
let courses = current_user.course
var timerCount = 60
var timerRunning = false
var start_time : Int? // Mitchel Added
var timer = Timer()
var breakTimer = Timer()
var breakRunning = false
var timerEnabled = false
var sessionTime = 3001 // 3000 seconds = 50 min sessions
var breakTime = 600 // = 10 min break
var breakRatio : Double = 1/6 // Break time for <50 min sessions
@IBOutlet weak var timePicker: UIDatePicker!
@IBOutlet weak var countDownLabel: UILabel!
@IBOutlet weak var breakTimeLabel: UILabel!
@IBOutlet weak var totalTimeLabel: UILabel!
@IBOutlet weak var totalTextLabel: UILabel!
@IBOutlet weak var coursePickerButton: UIButton!
@IBOutlet weak var coursePicker: UIPickerView!
@IBOutlet weak var smartStudyToggle: UISwitch!
@IBOutlet weak var smartStudyToggleView: UIView!
@IBOutlet weak var smartStudyView: UIView!
@IBOutlet weak var breakButton: UIButton!
@IBOutlet weak var resumeButton: UIButton!
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var endButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
coursePicker.dataSource = self
coursePicker.delegate = self
timePicker.countDownDuration = 60.0
if timerCount == 0 {
timerRunning = false
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Sends int value from UIDatePicker
@IBAction func timePickerAction(_ sender: UIDatePicker) {
timerCount = Int(timePicker.countDownDuration)
}
@IBAction func courseButtonPressed(_ sender: AnyObject) {
coursePicker.isHidden = false
smartStudyToggleView.isHidden = true
smartStudyView.isHidden = true
}
// Toggles smartStudy
@IBAction func smartStudyToggled(_ sender: AnyObject) {
if smartStudyToggle.isOn{
smartStudyView.isHidden = false
}
else {
smartStudyView.isHidden = true
totalTimeLabel.isHidden = true
totalTextLabel.isHidden = true
}
}
func numberOfComponents(in pickerView: UIPickerView)-> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return courses.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent: Int) -> String? {
return Array(courses.keys)[row]
}
// Displays courses to select in the scroll wheel
// User will not be able to start unless they pick a course or general setting
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){
coursePickerButton.setTitle(Array(courses.keys)[row], for: UIControlState.normal)
coursePicker.isHidden = true
smartStudyView.isHidden = false
smartStudyToggleView.isHidden = false
startButton.isEnabled = true
}
// Main functionality of timer
// Uses timerCount to display the timer value and initializes timer
@IBAction func startButtonPressed(_ sender: UIButton) {
// Prevents multiple timers running
if timerRunning == false {
timerCount = Int(timePicker.countDownDuration)
start_time = timerCount
timerCount += 1
sessionTime = 3001
timerRunning = true
// Timer function buttons
startButton.isHidden = true
endButton.isHidden = false
breakButton.isHidden = false
// Hide/show UI elements
timePicker.isHidden = true
countDownLabel.isHidden = false
smartStudyToggle.isUserInteractionEnabled = false
smartStudyToggleView.isHidden = true
coursePickerButton.isEnabled = false
if smartStudyToggle.isOn{
totalTimeLabel.isHidden = false
totalTextLabel.isHidden = false
}
runTimer()
}
}
func runTimer(){
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(TimerViewController.updateCounter)), userInfo: nil, repeats: true)
}
func updateCounter() {
// Decrement timers
timerCount -= 1
sessionTime -= 1
// Smart Study ON - counter with small total timer
if smartStudyToggle.isOn{
if (timerCount > sessionTime){
countDownLabel.text = timeString(time: TimeInterval(sessionTime))
totalTimeLabel.text = timeString(time: TimeInterval(timerCount))
}
else {
countDownLabel.text = timeString(time: TimeInterval(timerCount))
totalTimeLabel.text = timeString(time: TimeInterval(timerCount))
}
}
// Smart Study OFF
else{
countDownLabel.text = timeString(time: TimeInterval(timerCount))
}
// Stops the timer when it reaches 0
if timerCount == 0 {
timer.invalidate()
timerRunning = false
// Notification on session completion
let alertController = UIAlertController(title: "Session Complete!", message: "Keep studying or take a break?", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default)
{
(result : UIAlertAction) -> Void in
print("You pressed OK")
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
}
func runBreak(){
breakTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(TimerViewController.updateBreak)), userInfo: nil, repeats: true)
}
// Used by runBreak() to update counters
// and send a notification when the break ends
func updateBreak(){
breakTime -= 1
breakTimeLabel.text = timeString(time: TimeInterval(breakTime))
if breakTime <= 0 {
breakTimer.invalidate()
breakRunning = false
let alertController = UIAlertController(title: "Break Ended", message: "Time to study!", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default)
{
(result : UIAlertAction) -> Void in
print("You pressed OK")
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
}
@IBAction func breakBtnPressed(_ sender: UIButton) {
resumeButton.isHidden = false
breakButton.isHidden = true
timer.invalidate()
// Break timer for Smart Study
// if statement will prevent multiple timers leading to a sped up timer
if breakRunning == false{
breakTime = 600
breakRunning = true
// Show the break time timer
if smartStudyToggle.isOn{
countDownLabel.isHidden = true
breakTimeLabel.isHidden = false
if (timerCount > sessionTime){
breakTimeLabel.text = timeString(time: TimeInterval(breakTime))
}
else{
breakTime = Int(breakRatio * Double(timerCount))
breakTimeLabel.text = timeString(time: TimeInterval(breakTime))
}
}
runBreak()
}
}
// Function for resuming the timer
@IBAction func resumeBtnPressed(_ sender: UIButton) {
breakButton.isHidden = false
resumeButton.isHidden = true
breakTimeLabel.isHidden = true
countDownLabel.isHidden = false
breakTimer.invalidate()
breakRunning = false
runTimer()
}
// Ends timer and displays the standard timer UI
@IBAction func endButtonPressed(_ sender: UIButton) {
timer.invalidate()
timerRunning = false
breakTimer.invalidate()
breakRunning = false
startButton.isEnabled = false
coursePickerButton.isEnabled = true
// Timer buttons
startButton.isHidden = false
endButton.isHidden = true
breakButton.isHidden = true
resumeButton.isHidden = true
// Timer UI labels
timePicker.isHidden = false
countDownLabel.isHidden = true
totalTimeLabel.isHidden = true
totalTextLabel.isHidden = true
breakTimeLabel.isHidden = true
// Button UI
smartStudyToggleView.isHidden = false
coursePickerButton.isHidden = false
smartStudyToggle.isUserInteractionEnabled = true
// Save timer values as int and send to Firebase
let course = Array(courses.keys)[self.coursePicker.selectedRow(inComponent: 0)]
let time = (self.start_time! - self.timerCount) / (60 * 60)
if current_user.course[course] == nil {
current_user.course[course] = time
} else {
current_user.course[course] = current_user.course[course]! + time
}
current_user.localSave()
current_user.update()
}
// Method to format time into HH:MM:SS
func timeString(time:TimeInterval) -> String {
let hours = Int(time) / 3600
let minutes = Int(time) / 60 % 60
let seconds = Int(time) % 60
return String(format:"%02i:%02i:%02i", hours, minutes, seconds)
}
/*
// 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.
}
*/
}
|
//
// PeripheralsTVC.swift
// Bluetooth Scanner
//
// Created by Pavan Athreya on 01/03/2019.
// Copyright (c) 2019 Pavan Athreya. All rights reserved.
//
import UIKit
import CoreBluetooth
import CoreLocation
//Class for listing the peripherals
class PeripheralsTVC: UITableViewController, CBCentralManagerDelegate, CBPeripheralDelegate, CLLocationManagerDelegate {
// CoreBluetooth Central Manager
static var centralManager:CBCentralManager!
// CoreLocation Location Manager
var locationManager:CLLocationManager!
// All peripherals in Central Manager
var peripherals = [CBPeripheral]()
// Peripheral chosen by user
var connectedPeripheral:CBPeripheral!
// MARK: - View Life Cycle
//View Did Load
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
// This will trigger centralManagerDidUpdateState
PeripheralsTVC.centralManager = CBCentralManager(delegate: self, queue: nil)
//centralManager = CBCentralManager(delegate: self, queue: DispatchQueue.main)
}
//View Did Appear
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Re-start scan after coming back from background
peripherals.removeAll()
if PeripheralsTVC.centralManager.state == .poweredOn {
PeripheralsTVC.centralManager.scanForPeripherals(withServices:nil, options: ["CBCentralManagerScanOptionAllowDuplicatesKey" : false])
}
}
//View Will Disappear
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Stop scan to save battery when entering background
PeripheralsTVC.centralManager.stopScan()
// Remove all peripherals from the table and array (they will be re-discovered upon viewDidAppear)
peripherals.removeAll(keepingCapacity: false)
self.tableView.reloadData()
}
// MARK : - CLLocationManager Delegates
//Location manager did change authorization status
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
print("Did update Status: \(status)")
}
// MARK: - CBCentralManagerDelegate
//Central manager did update bluetooth state
func centralManagerDidUpdateState(_ central: CBCentralManager) {
print("Central Manager did update state")
if (central.state == .poweredOn) {
print("Bluetooth is powered on")
// Scan for any peripherals
peripherals.removeAll()
PeripheralsTVC.centralManager.scanForPeripherals(withServices: nil, options: ["CBCentralManagerScanOptionAllowDuplicatesKey" : false])
}
else {
var message = String()
switch central.state {
case .unsupported:
message = "Bluetooth is unsupported"
case .unknown:
message = "Bluetooth state is unkown"
case .unauthorized:
message = "Bluetooth is unauthorized"
case .poweredOff:
message = "Bluetooth is powered off"
default:
break
}
print(message)
}
}
//Central manager did discover peripheral
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
print("Peripheral discovered: \(peripheral)")
print("Advertisement Data: \(advertisementData)")
peripherals.append(peripheral)
self.tableView.reloadData()
}
//Central manager did connect to peripheral
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("Peripheral connected: \(String(describing: peripheral))")
PeripheralsTVC.centralManager.stopScan()
// Keep reference to be used in prepareForSegue
self.connectedPeripheral = peripheral
performSegue(withIdentifier: "Services", sender: self)
}
//Central Manager Failed to connect to peripheral
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
print("Peripheral failed to connect: \(peripheral)")
}
// MARK: - Table view data source
//Number of sections in Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
//Number of rows in given section of the table view
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return peripherals.count
}
//Table View Cell for row at index path
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Peripheral", for: indexPath) as UITableViewCell
let p = peripherals[indexPath.row]
cell.textLabel?.text = p.name ?? "[Unkown name]"
cell.detailTextLabel?.text = "UUID: \(p.identifier.uuidString)"
return cell
}
// MARK: - Table view delegates
//Table View did select row at index path
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.connectedPeripheral = peripherals[indexPath.row]
print("Tring to connnect to peripheral: \(String(describing: self.connectedPeripheral))")
PeripheralsTVC.centralManager.connect(self.connectedPeripheral, options: nil)
}
// MARK: - Segue
//View Controller Prepare for segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let servicesTVC = segue.destination as! ServicesTVC
servicesTVC.peripheral = self.connectedPeripheral
}
}
|
//
// MoreListViewController.swift
// PyConJP2016
//
// Created by Yutaro Muta on 3/7/16.
// Copyright © 2016 PyCon JP. All rights reserved.
//
import UIKit
import WebAPIFramework
import SafariServices
class MoreListViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let indexPath = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: indexPath, animated: true)
}
}
// MARK: - Table View Controller Delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let sectionType = SectionType(rawValue: (indexPath as NSIndexPath).section) else { return }
let rowType = sectionType.rows[(indexPath as NSIndexPath).row]
switch rowType {
case .whatsPyConJP, .codeOfConduct, .summary, .license, .staffList:
guard let identifier = rowType.identifier, let viewController = self.storyboard?.instantiateViewController(withIdentifier: identifier) else { return }
self.navigationController?.pushViewController(viewController, animated: true)
case .participantsInformation, .sponsor, .questionnaire, .repository:
guard let url = rowType.url else { return }
let safariViewController = SFSafariViewController(url: url)
self.present(safariViewController, animated: true, completion: nil)
case .conferenceMap:
let mapListViewController = MapListViewController.build()
self.navigationController?.pushViewController(mapListViewController, animated: true)
case .sprintMap:
let mapViewController = MapViewController.build(venue: MapViewController.Venue.microsoft)
self.navigationController?.pushViewController(mapViewController, animated: true)
case .library:
let acknowledgmentsListViewController = AcknowledgmentsListViewController.build()
self.navigationController?.pushViewController(acknowledgmentsListViewController, animated: true)
case .feedback:
guard let urlSheme = rowType.urlSheme else { return }
UIApplication.shared.openURL(urlSheme)
tableView.deselectRow(at: indexPath, animated: true)
}
}
private enum SectionType: Int {
case about
case map
case application
var rows: Array<RowType> {
switch self {
case .about:
return [.participantsInformation, .whatsPyConJP, .codeOfConduct, .summary, .sponsor, .staffList, .questionnaire]
case .map:
return [.conferenceMap, .sprintMap]
case .application:
return [.repository, .library, .license, .feedback]
}
}
}
private enum RowType: MailURLSchemeProtocol {
case participantsInformation
case whatsPyConJP
case codeOfConduct
case summary
case sponsor
case staffList
case questionnaire
case conferenceMap
case sprintMap
case repository
case library
case license
case feedback
var identifier: String? {
switch self {
case .whatsPyConJP: return "WhatsPyConJPViewController"
case .codeOfConduct: return "CodeOfConductViewController"
case .summary: return "SummaryViewController"
case .license: return "LicenseViewController"
case .staffList: return "StaffListViewController"
default: return nil
}
}
var url: URL? {
switch self {
case .participantsInformation: return URL(string: WebConfig.baseURL + "participants/")
case .sponsor: return URL(string: WebConfig.baseURL + "sponsors/")
case .questionnaire: return URL(string: "https://docs.google.com/forms/d/e/1FAIpQLSefOgaVN8_cwUAcW-NmTaBNoNG8K47vursedtxkE_cbv_E37A/viewform")
case .repository: return URL(string: "https://github.com/pyconjp/pyconjp-ios")
default: return nil
}
}
var urlSheme: URL? {
switch self {
case .feedback: return mailURLScheme(to: PCJConfig.mailAddress,
subject: "Feedback for PyCon JP 2016 App",
body: String(format: "iOS version: %@\nDevice Model: %@\nReply-to:\n\nFeedback:", arguments: [UIDevice.current.systemVersion, UIDevice.current.modelType]))
default: return nil
}
}
}
}
|
//
// TeamsTableViewCell.swift
// AutosportInfo
//
// Created by Egor Salnikov on 05.10.2020.
// Copyright © 2020 Egor Salnikov. All rights reserved.
//
import UIKit
class TeamsTableViewCell: UITableViewCell {
@IBOutlet weak var cellView: UIView!
@IBOutlet weak var teamName: UILabel!
@IBOutlet weak var teamNationalityLabel: UILabel!
@IBOutlet weak var countWins: UILabel!
@IBOutlet weak var countPoints: UILabel!
@IBOutlet weak var countPosition: UILabel!
}
|
//
// productsCollectionViewCell.swift
// D2020
//
// Created by MacBook Pro on 3/10/20.
// Copyright © 2020 Abdallah Eslah. All rights reserved.
//
import UIKit
class productsCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var productImageView: RoundedImageView!
@IBOutlet weak var productNameLabel: UILabel!
@IBOutlet weak var productPriceLabel: UILabel!
@IBOutlet weak var editButton: UIButton!
}
|
//
// Mine.swift
// FudanNews
//
// Created by Lotus on 2016/11/16.
// Copyright © 2016年 Fudan University. All rights reserved.
//
import UIKit
import AlamofireImage
import MJRefresh
class SubscriptionMine: UITableViewController {
var dataArray = [Subscription]()
var dataArrayAll = [Subscription]()
var now = 0
var flag = 0
var rootView: SubscriptionViewController!
override func viewWillAppear(_ animated: Bool) {
if LocalStorageManager.loadUserLoginInfo() != nil {
rootView.button1.alpha = 0
if (dataArray.count == 0) {
headerRefresh()
return
}
if (rootView.nowView == 1){
headerRefresh()
rootView.nowView = 0
return
}
var i = -1
for e in dataArray {
i += 1
if !e.isSubscribed {
dataArray.remove(at: i)
dataArrayAll.remove(at: i)
break
}
}
now = dataArrayAll.count
if now == 0 {
rootView.button2.alpha = 1
}
else {
rootView.button2.alpha = 0
}
tableView.reloadData()
}
else {
rootView.button2.alpha = 0
dataArray.removeAll()
dataArrayAll.removeAll()
now = 0
tableView.reloadData()
rootView.button1.alpha = 1
self.tableView.mj_header.endRefreshing()
self.tableView.mj_footer.endRefreshing()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView!.separatorStyle = UITableViewCellSeparatorStyle.none
self.tableView!.delegate = self
self.tableView!.dataSource = self
self.tableView!.register(UINib(nibName:"SubscriptionMyTableViewCell", bundle:nil),
forCellReuseIdentifier:"SubscriptionMyTableViewCell")
let header:MJRefreshGifHeader = MJRefreshGifHeader(refreshingTarget: self,refreshingAction:#selector(self.headerRefresh))
self.tableView!.mj_header = header
self.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self,refreshingAction:#selector(self.headerRefresh))
self.tableView.mj_footer = MJRefreshBackFooter(refreshingTarget: self, refreshingAction: #selector(self.footerRefresh))
self.tableView.backgroundColor = UIColor(red:248/255,green:248/255,blue:248/255,alpha:1)
}
func footerRefresh() {
refreshData()
}
func headerRefresh(){
dataArrayAll.removeAll()
now = 0
refreshData()
}
func refreshData() {
NetworkManager.getMySubscriptionList(startedFrom: self.now, withLimit: 15) { subscriptionList in
if let subscriptionList = subscriptionList {
for subscription in subscriptionList {
self.dataArrayAll.append(subscription)
}
self.dataArray = self.dataArrayAll
self.now = self.dataArrayAll.count
if (self.now == 0){
self.rootView.button2.alpha = 1
}
else {
self.rootView.button2.alpha = 0
}
self.tableView.mj_header.endRefreshing()
self.tableView.mj_footer.endRefreshing()
self.tableView.reloadData()
}
else {
if (self.now == 0){
self.rootView.button2.alpha = 1
}
else {
self.rootView.button2.alpha = 0
}
self.tableView.mj_header.endRefreshing()
self.tableView.mj_footer.endRefreshing()
}
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:SubscriptionMyTableViewCell = tableView.dequeueReusableCell(withIdentifier: "SubscriptionMyTableViewCell") as!
SubscriptionMyTableViewCell
cell.content = dataArray[indexPath.row]
cell.article = dataArray[indexPath.row].previewArticles
cell.prepare()
cell.rootView = self.rootView
cell.Entry.tag = indexPath.row
cell.Entry.addTarget(self, action: #selector(entry), for: .touchUpInside)
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return kScreenWidth/2+40+kScreenWidth/10
}
func entry(_sender : UIButton){
rootView.nowView = 0
rootView.performSegue(withIdentifier: "ShowTopic", sender: dataArray[_sender.tag])
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
rootView.nowView = 0
rootView.performSegue(withIdentifier: "ShowTopic", sender: dataArray[indexPath.row])
}
}
|
//
// LoginViewController.swift
// Frames-App
//
// Created by Tyler Zhao on 12/5/18.
// Copyright © 2018 Tyler Zhao. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class SignInViewController: UIViewController, StoryboardInitializable {
@IBOutlet weak var loginTextField: FramesTextField!
@IBOutlet weak var passwordTextField: FramesTextField!
@IBOutlet weak var forgotPasswordButton: UIButton!
@IBOutlet weak var signInButton: FramesButton!
var viewModel: SignInViewModel!
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
setup()
bindViewModel()
}
private func setup() {
title = "Sign In"
}
private func bindViewModel() {
assert(viewModel != nil)
let input = SignInViewModel.Input(signInTrigger: signInButton.rx.tap.asObservable())
let output = viewModel.transform(input: input)
}
}
|
//
// TimeEntryCellDelegate.swift
// MPM-Sft-Eng-Proj
//
// Created by Sebastian Peden on 9/18/18.
// Copyright © 2018 Harrison Ellerm. All rights reserved.
//
import Foundation
import UIKit
protocol TimeEntryCellDelegate {
func textFieldInCell(cell: TimeEntryCell, editingChangedInTextField newText:String)
}
|
//
// Constants.swift
// Papr
//
// Created by Mitchell Sturba on 2020-03-23.
// Copyright © 2020 Mitchell Sturba. All rights reserved.
//
import Foundation
struct Constants {
struct StoryBoard {
static let homeViewController = "HomeVC"
}
}
|
//
// UIKitExtension.swift
// delinshe_ios
//
// Created by Xu on 2020/9/28.
// Copyright © 2020 com.delinshe. All rights reserved.
//
import UIKit
public enum PostingType: String {
case all = "default"
case note = "note"
case value = "value"
case remove_mines = "remove_mines"
case dynamic = "no_idea"
case qa = "interlocution"
}
extension UIViewController {
}
// MARK: ShadowLayer
class ShadowLayer: CAShapeLayer {
@discardableResult
func setFrame(_ frame: CGRect)-> ShadowLayer {
self.frame = frame
return self
}
@discardableResult
func setPath(_ path: CGPath)-> ShadowLayer {
self.shadowPath = path
return self
}
@discardableResult
func setOpacity(_ opacity: Float)-> ShadowLayer {
self.shadowOpacity = opacity
return self
}
@discardableResult
func setOffset(_ offset: CGSize)-> ShadowLayer {
self.shadowOffset = offset
return self
}
@discardableResult
func setColor(_ color: UIColor?, alpha: CGFloat = 1.0)-> ShadowLayer {
if color == nil {
self.shadowColor = UIColor.black.withAlphaComponent(alpha).cgColor
return self
}
self.shadowColor = color!.withAlphaComponent(alpha).cgColor
return self
}
func done()-> UIView {
let view = UIView(frame: self.frame)
view.backgroundColor = .clear
view.layer.insertSublayer(self, at: 0)
return view
}
}
// MARK: UIView
extension UIView {
// #if DEBUG
// @objc open func injected() {
// print("injected UIView")
// //find now VC
// guard let nowVC = UIApplication.shared.keyWindow?.rootViewController else {
// return
// }
// for subV in nowVC.view.subviews {
// subV.removeFromSuperview()
// }
// nowVC.viewDidLoad()
// }
// #endif
/// 部分圆角
///
/// - Parameters:
/// - corners: 需要实现为圆角的角,可传入多个
/// - radii: 圆角半径
func corner(byRoundingCorners corners: UIRectCorner, radii: CGFloat) {
let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radii, height: radii))
let maskLayer = CAShapeLayer()
maskLayer.frame = self.bounds
maskLayer.path = maskPath.cgPath
self.layer.mask = maskLayer
}
func setBackgroundGradientColor(colors:[UIColor], startPoint: CGPoint? = nil , endPoint: CGPoint? = nil, locations: [NSNumber]? = nil, cornerRadius: CGFloat) {
let gradientLayer1 = CAGradientLayer()
gradientLayer1.frame = self.bounds
gradientLayer1.colors = colors.map({ (color) -> CGColor in
return color.cgColor
})
var start_point = CGPoint(x: 0, y: 0)
if startPoint != nil {
start_point = startPoint!
}
var end_point = CGPoint(x: 0, y: 1)
if endPoint != nil {
end_point = endPoint!
}
gradientLayer1.startPoint = start_point
gradientLayer1.endPoint = end_point
if locations != nil {
gradientLayer1.locations = locations!
}
gradientLayer1.cornerRadius = cornerRadius
self.layer.insertSublayer(gradientLayer1, at: 0)
}
}
// MARK: UIButton
extension UIButton {
func setGradientColor(colors:[UIColor], startPoint: CGPoint? = nil , endPoint: CGPoint? = nil, locations: [NSNumber]? = nil, cornerRadius: CGFloat) {
let gradientLayer1 = CAGradientLayer()
gradientLayer1.frame = self.bounds
gradientLayer1.colors = colors.map({ (color) -> CGColor in
return color.cgColor
})
var start_point = CGPoint(x: 0, y: 0)
if startPoint != nil {
start_point = startPoint!
}
var end_point = CGPoint(x: 0, y: 1)
if endPoint != nil {
end_point = endPoint!
}
var loca:[NSNumber] = [0, 1]
if locations != nil {
loca = locations!
}
gradientLayer1.startPoint = start_point
gradientLayer1.endPoint = end_point
gradientLayer1.locations = loca
gradientLayer1.cornerRadius = cornerRadius
self.layer.addSublayer(gradientLayer1)
}
}
// MARK: UITableView
extension UITableView {
// MARK: - Cell register and reuse
/**
Register cell nib
- parameter aClass: class
*/
func xz_registerCellNib<T: UITableViewCell>(_ aClass: T.Type) {
let name = String(describing: aClass)
let nib = UINib(nibName: name, bundle: nil)
self.register(nib, forCellReuseIdentifier: name)
}
/**
Register cell class
- parameter aClass: class
*/
func xz_registerCellClass<T: UITableViewCell>(_ aClass: T.Type) {
let name = String(describing: aClass)
self.register(aClass, forCellReuseIdentifier: name)
}
/**
Reusable Cell
- parameter aClass: class
- returns: cell
*/
func xz_dequeueReusableCell<T: UITableViewCell>(_ aClass: T.Type) -> T! {
let name = String(describing: aClass)
guard let cell = dequeueReusableCell(withIdentifier: name) as? T else {
fatalError("\(name) is not registed")
}
return cell
}
// MARK: - HeaderFooter register and reuse
/**
Register cell nib
- parameter aClass: class
*/
func xz_registerHeaderFooterNib<T: UIView>(_ aClass: T.Type) {
let name = String(describing: aClass)
let nib = UINib(nibName: name, bundle: nil)
self.register(nib, forHeaderFooterViewReuseIdentifier: name)
}
/**
Register cell class
- parameter aClass: class
*/
func xz_registerHeaderFooterClass<T: UIView>(_ aClass: T.Type) {
let name = String(describing: aClass)
self.register(aClass, forHeaderFooterViewReuseIdentifier: name)
}
/**
Reusable Cell
- parameter aClass: class
- returns: cell
*/
func xz_dequeueReusableHeaderFooter<T: UIView>(_ aClass: T.Type) -> T! {
let name = String(describing: aClass)
guard let cell = dequeueReusableHeaderFooterView(withIdentifier: name) as? T else {
fatalError("\(name) is not registed")
}
return cell
}
}
// MARK: UIImage
extension UIImage {
func byAlpha(_ alpha: CGFloat)-> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.size, false, 0.0)
if let ctx = UIGraphicsGetCurrentContext() {
let area = CGRect(x: 0,
y: 0,
width: size.width,
height: size.height)
ctx.scaleBy(x: 1, y: -1);
ctx.translateBy(x: 0, y: -area.height)
ctx.setBlendMode(.multiply)
ctx.setAlpha(alpha)
ctx.draw(self.cgImage!, in: area)
let new = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return new
}
return nil
}
}
extension Date {
/// 获取当前 秒级 时间戳 - 10位
var timeStamp : String {
let timeInterval: TimeInterval = self.timeIntervalSince1970
let timeStamp = Int(timeInterval)
return "\(timeStamp)"
}
/// 获取当前 毫秒级 时间戳 - 13位
var milliStamp : String {
let timeInterval: TimeInterval = self.timeIntervalSince1970
let millisecond = CLongLong(round(timeInterval*1000))
return "\(millisecond)"
}
}
extension Array {
subscript (safe index: Int)-> Element? {
return (0..<count).contains(index) ? self[index] : nil
}
func isNull()-> Bool {
if self == nil, self.count <= 0 {
return true
}
return false
}
}
// 数组切片
extension Sequence {
func clump(by clumpsize:Int) -> [[Element]] {
let slices : [[Element]] = self.reduce(into:[]) {
memo, cur in
if memo.count == 0 {
return memo.append([cur])
}
if memo.last!.count < clumpsize {
memo.append(memo.removeLast() + [cur])
} else {
memo.append([cur])
}
}
return slices
}
}
extension String {
/// 转换成阅读数 1w+ 10w+ 999w+
var convertToReadNumber: String {
if let number = self.toFloat() {
if number >= 10000 && number < 10000000 {
return String(format: "%.1fw", number)
}else {
if number >= 10000000 {
return "999w"
}
return String(format: "%.f", number)
}
}
return self
}
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else { return NSAttributedString() }
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
/// 生成随机字符串
///
/// - Parameters:
/// - count: 生成字符串长度
/// - isLetter: false=大小写字母和数字组成,true=大小写字母组成,默认为false
/// - Returns: String
static func random(_ count: Int, _ isLetter: Bool = false) -> String {
var ch: [CChar] = Array(repeating: 0, count: count)
for index in 0..<count {
var num = isLetter ? arc4random_uniform(58)+65:arc4random_uniform(75)+48
if num>57 && num<65 && isLetter==false { num = num%57+48 }
else if num>90 && num<97 { num = num%90+65 }
ch[index] = CChar(num)
}
return String(cString: ch)
}
static func currenTimeStampString()-> String {
let date = Date()
let stamp = date.timeIntervalSince1970
return String(stamp)
}
func toInt() -> Int? {
return Int(self)
}
func toFloat() -> Float? {
return Float(self)
}
func toDouble() -> Double? {
return Double(self)
}
//MARK:- 去除字符串两端的空白字符
func trim() -> String {
return self.trimmingCharacters(in: CharacterSet.whitespaces)
}
func subString(to: Int) -> String {
var to = to
if to > self.count {
to = self.count
}
return String(self.prefix(to))
}
func subString(from: Int) -> String {
if from >= self.count {
return ""
}
let startIndex = self.index(self.startIndex, offsetBy: from)
let endIndex = self.endIndex
return String(self[startIndex..<endIndex])
}
func subString(start: Int, end: Int) -> String {
if start < end {
let startIndex = self.index(self.startIndex, offsetBy: start)
let endIndex = self.index(self.startIndex, offsetBy: end)
return String(self[startIndex..<endIndex])
}
return ""
}
}
extension UIColor {
/// 文字-白色
static var app_main_white: UIColor {
UIColor(hexString: "#FFFFFF")
}
/// App主基调
/// 背景色
static var app_main_background: UIColor {
UIColor(hexString: "#F8F8F8")
}
/// 品牌红色
static var app_main_red: UIColor {
UIColor(hexString: "#FF323E")
}
/// 品牌绿色
static var app_main_green: UIColor {
UIColor(hexString: "#57D975")
}
/// 标题文字颜色
static var app_main_title: UIColor {
UIColor(hexString: "#333333")
}
/// 正文颜色
static var app_main_content: UIColor {
UIColor(hexString: "#666666")
}
/// 辅助信息颜色
static var app_main_subinfo: UIColor {
UIColor(hexString: "#999999")
}
/// 分割线颜色
static var app_main_line: UIColor {
UIColor(hexString: "#F3F3F3")
}
/// 按钮背景颜色
static var app_main_buttonBackground: UIColor {
UIColor(hexString: "#EEEEEE")
}
/// 搜素输入框背景颜色
static var app_main_inputboxBackground: UIColor {
UIColor(hexString: "#EEEFF3")
}
static var app_main_thinRed: UIColor {
UIColor(hexString: "#FF5656")
}
open class var live_yellow: UIColor {
get {
return UIColor(hexString: "#FFC63C")
}
}
open class var live_blue: UIColor {
get {
return UIColor(hexString: "#66E0E8")
}
}
open class var black_25: UIColor {
get {
return UIColor(hexString: "#000000").withAlphaComponent(0.25)
}
}
open class var cellAnimatedColor: UIColor {
get {
return UIColor(hexString: "#f5f5f5")
}
}
static func setColor(hex: String, alpha: @autoclosure() -> CGFloat)-> UIColor {
return UIColor(hexString: hex).withAlphaComponent(alpha())
}
func createImage(bounds: CGRect)-> UIImage? {
var image = UIImage()
UIGraphicsBeginImageContext(bounds.size)
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(self.cgColor)
context.fill(bounds)
image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
UIGraphicsEndImageContext()
}
return image
}
}
extension UIFont {
static var app_main_big: UIFont {
.systemFont(ofSize: 18.0)
}
static var app_main_section: UIFont {
.systemFont(ofSize: 16.0)
}
static var app_main_tab: UIFont {
.systemFont(ofSize: 15.0)
}
static var app_main_title: UIFont {
.systemFont(ofSize: 14.0)
}
static var app_main_content: UIFont {
.systemFont(ofSize: 13.0)
}
static var app_main_subinfo: UIFont {
.systemFont(ofSize: 12.0)
}
var bold: UIFont {
.systemFont(ofSize: pointSize, weight: .bold)
}
var medium: UIFont {
.systemFont(ofSize: pointSize, weight: .medium)
}
var regular: UIFont {
.systemFont(ofSize: pointSize, weight: .regular)
}
}
|
//
// Enums.swift
// Adapt
//
// Created by 599944 on 11/21/18.
// Copyright © 2018 TheATeam. All rights reserved.
//
import Foundation
enum SetType {
case rep
case Tsec
case Tmin
case distMi
case distKm
case distM
case NA }
enum WorkoutType {
case superset
case fortime
case NA
}
enum Tier1MuscleGroup{
case arms
case legs
case chest
case neck
case back
case core
}
enum Tier2MuscleGroup{
case biceps
case triceps
case forearms
case NA
}
enum WorkoutEquipment {
case barbell
case dumbell
case speedladder
case mat
case plyobox
case propbox
case chair
case footprop
case soupcans
}
enum WeightStatus {
case none
case optional
case preferred
case required
}
|
//
// ActionManagerModel.swift
// Rondo-iOS
//
// Created by Nikola Zagorchev on 19.07.22.
// Copyright © 2022 Leanplum. All rights reserved.
//
import Foundation
import Leanplum
enum MessageDisplay: String, CaseIterable {
case show = "Show"
case discard = "Discard"
case delayIndefinitely = "DelayIndefinitely"
case delay = "Delay"
func messageDisplayChoice() -> ActionManager.MessageDisplayChoice {
switch self {
case .show:
return .show()
case .discard:
return.discard()
case .delayIndefinitely:
return .delayIndefinitely()
default:
return .show()
}
}
}
enum MessagePrioritization: String, CaseIterable {
case all = "All"
case firstOnly = "First Only"
case allReversed = "All Reversed"
}
struct ActionModel: Encodable {
let name: String
let messageId: String
let parent: String
let handler: String
let actionName: String?
static func description(from context: ActionContext, handler: String?, action: String?) -> String {
let model = ActionModel(name: context.name,
messageId: context.messageId,
parent: context.parent?.messageId ?? "",
handler: handler ?? "",
actionName: action ?? "")
return Util.jsonPrettyString(model)
}
}
class ActionManagerModel {
init(trackMessageDisplayed: Bool, trackMessageDismissed: Bool, trackMessageActions: Bool) {
// invoke didSet
defer {
self.trackMessageDisplayed = trackMessageDisplayed
self.trackMessageDismissed = trackMessageDismissed
self.trackMessageActions = trackMessageActions
}
}
convenience init() {
self.init(trackMessageDisplayed: true, trackMessageDismissed: true, trackMessageActions: true)
}
var eventsLog = [String]()
var displayChoice: MessageDisplay? {
didSet {
if let displayChoice = displayChoice {
switch displayChoice {
// .delay with seconds is handled separately
case .show, .discard, .delayIndefinitely:
ActionManager.shared.shouldDisplayMessage { _ in
self.logAsyncHandlers(message: "ShouldDisplayMessage")
return displayChoice.messageDisplayChoice()
}
default:
break
}
} else {
ActionManager.shared.shouldDisplayMessage(nil)
}
}
}
var prioritizationChoice: MessagePrioritization? {
didSet {
if oldValue != prioritizationChoice {
prioritizationChoiceChanged(prioritizationChoice)
}
}
}
var delaySeconds: Int = -1 {
didSet {
ActionManager.shared.shouldDisplayMessage { [weak self]_ in
return .delay(seconds: self?.delaySeconds ?? 0)
}
}
}
var isAsyncEnabled = ActionManager.shared.useAsyncHandlers {
didSet {
ActionManager.shared.useAsyncHandlers = isAsyncEnabled
}
}
var isQueueEnabled = ActionManager.shared.isEnabled {
didSet {
ActionManager.shared.isEnabled = isQueueEnabled
}
}
var isQueuePaused = ActionManager.shared.isPaused {
didSet {
ActionManager.shared.isPaused = isQueuePaused
}
}
var dismissOnPushArrival = ActionManager.shared.configuration.dismissOnPushArrival {
didSet {
if oldValue != dismissOnPushArrival {
applyConfiguration()
}
}
}
var resumeOnEnterForeground = ActionManager.shared.configuration.resumeOnEnterForeground {
didSet {
if oldValue != resumeOnEnterForeground {
applyConfiguration()
}
}
}
var trackMessageDisplayed: Bool? {
didSet {
if trackMessageDisplayed == true {
ActionManager.shared.onMessageDisplayed(onMessageHandler(#function))
} else {
ActionManager.shared.onMessageDisplayed(nil)
}
}
}
var trackMessageDismissed: Bool? {
didSet {
if trackMessageDismissed == true {
ActionManager.shared.onMessageDismissed(onMessageHandler(#function))
} else {
ActionManager.shared.onMessageDismissed(nil)
}
}
}
var trackMessageActions: Bool? {
didSet {
if trackMessageActions == true {
ActionManager.shared.onMessageAction(onMessageActionHandler(#function))
} else {
ActionManager.shared.onMessageAction(nil)
}
}
}
lazy var onMessageHandler: ((String) -> (ActionContext) -> ()) = { handler in
{ context in
self.logAsyncHandlers(message: handler)
self.addAction(context: context, handler: handler)
}
}
lazy var onMessageActionHandler: ((String) -> (String, ActionContext) -> ()) = { handler in
{ action, context in
self.addAction(action: action, context: context, handler: handler)
}
}
lazy var onMessageDismissed: ((ActionContext) -> ()) = { context in
self.addAction(context: context, handler: #function)
}
func applyConfiguration() {
ActionManager.shared.configuration = ActionManager.Configuration(dismissOnPushArrival: dismissOnPushArrival,
resumeOnEnterForeground: resumeOnEnterForeground)
}
func prioritizationChoiceChanged(_ prioritization: MessagePrioritization?) {
switch prioritization {
case .all:
ActionManager.shared.prioritizeMessages { contexts, trigger in
self.logAsyncHandlers(message: "MessagePrioritization")
return contexts
}
case .firstOnly:
ActionManager.shared.prioritizeMessages { contexts, trigger in
guard let first = contexts.first else {
return []
}
self.logAsyncHandlers(message: "MessagePrioritization")
return [first]
}
case .allReversed:
ActionManager.shared.prioritizeMessages { contexts, trigger in
self.logAsyncHandlers(message: "MessagePrioritization")
return contexts.reversed()
}
default:
ActionManager.shared.prioritizeMessages(nil)
break
}
}
func triggerDelayedMessages() {
ActionManager.shared.triggerDelayedMessages()
}
func addAction(context: ActionContext, handler: String) {
addAction(action: nil, context: context, handler: handler)
}
func addAction(action: String?, context: ActionContext, handler: String) {
let desc = ActionModel.description(from: context, handler: handler, action: action)
eventsLog.append(desc)
}
func showEventLogs() -> UIViewController {
let ctrl = TextAreaController()
ctrl.title = "Action Logs"
ctrl.message = eventsLog.joined(separator: ", \n")
return ctrl
}
func resetEventLogs() {
eventsLog.removeAll()
}
func showMessageQueue() -> UIViewController {
var log = [String]()
for ctx in queueContexts {
log.append(ActionModel.description(from: ctx, handler: nil, action: nil))
}
let ctrl = TextAreaController()
ctrl.title = "Queue"
ctrl.message = log.joined(separator: ", \n")
return ctrl
}
func showDelayedMessageQueue() -> UIViewController {
var log = [String]()
for ctx in delayedQueueContexts {
log.append(ActionModel.description(from: ctx, handler: nil, action: nil))
}
let ctrl = TextAreaController()
ctrl.title = "Delayed Queue"
ctrl.message = log.joined(separator: ", \n")
return ctrl
}
var queueContexts: [ActionContext] {
getActionManagerQueueContexts("queue")
}
var delayedQueueContexts: [ActionContext] {
getActionManagerQueueContexts("delayedQueue")
}
/// Accessing the ActionManager Queues which are private lazy properties of private type Queue
/// The Queue holds a private array of the private type Action
/// The Action holds a context
func getActionManagerQueueContexts(_ queueName: String) -> [ActionContext] {
let queue = Util.getPrivateValue(subject: ActionManager.shared, label: queueName, true, true)
if let queue = queue {
if let arr = Util.getPrivateValue(subject: queue, label: "queue") as? [Any] {
return arr.map { action in
return Util.getPrivateValue(subject: action, label: "context") as? ActionContext
}.compactMap { $0 }
}
}
return []
}
func logAsyncHandlers(message: String) {
var logMessage = message.appending(" running on main thread: \(Thread.isMainThread)")
if Thread.isMainThread == ActionManager.shared.useAsyncHandlers {
logMessage = "[ERROR]: \(message)"
}
Log.print(logMessage)
}
}
|
//
// WeeklyWeeklyPresenter.swift
// Weather
//
// Created by KONSTANTIN KUSAINOV on 21/03/2018.
// Copyright © 2018 Konstantin. All rights reserved.
//
import UIKit
class WeeklyPresenter: BasePresenter, WeeklyModuleInput, WeeklyViewOutput, WeeklyInteractorOutput {
private weak var weekyView: WeeklyViewInput!
override weak var view: BaseViewInput! {
get {
return weekyView
}
set {
guard let v = newValue as? WeeklyViewInput else {
fatalError()
}
weekyView = v
}
}
private var weeklyInteractor: WeeklyInteractorInput!
override var interactor: BaseInteractorInput! {
get {
return weeklyInteractor
}
set {
guard let i = newValue as? WeeklyInteractorInput else {
fatalError()
}
weeklyInteractor = i
}
}
// MARK: BaseInteractorOutput
override func assignFetchData() {
super.assignFetchData()
self.weekyView.setCityTitleName(title: self.weeklyInteractor.viewModel!.cityName)
}
// MARK: WeeklyViewOutput
func titleForHeader(index: Int) -> String {
return self.weeklyInteractor.viewModel!.items[index].dataString
}
// MARK: TableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
guard let items = self.weeklyInteractor.viewModel?.items else {
return 0
}
return items.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let items = self.weeklyInteractor.viewModel?.items else {
return 0
}
return items[section].items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: WeatherDayTableViewCell.cellReuseIdentifier) as? WeatherDayTableViewCell, let models = self.weeklyInteractor.viewModel?.items[indexPath.section] else {
fatalError("Unexpected type")
}
cell.configureForCell(model: models.items[indexPath.row])
return cell
}
}
|
//
// InvitePopoverViewController.swift
// CoffeeAlum Gamma
//
// Created by Trevin Wisaksana on 1/15/17.
// Copyright © 2017 Trevin Wisaksana. All rights reserved.
//
import Foundation
import Firebase
import MapKit
protocol InviteDelegate: class {
func sendInvitation()
}
final class InvitePopoverVC: UIViewController {
private enum State {
case `default`
case loading
case attemptToSendInvite
case failedToSendInvitation(as: Error)
case inviteSentSuccessfully
}
private enum `Error` {
case dateIsEmpty
case locationIsEmpty
case timeIsEmpty
}
private var state: State = .default {
didSet {
didChange(state)
}
}
private func didChange(_ state: State) {
switch state {
case .loading:
break
case .failedToSendInvitation(let error):
throwWarning(for: error)
case .attemptToSendInvite:
delegate?.sendInvitation()
default:
break
}
}
// TODO: MAKE FILEPRIVATE
var viewedUser: User?
var thisUser: User?
fileprivate var date: String?
fileprivate var time: String?
fileprivate var coffee: Coffee?
fileprivate var coreLocationManager = CLLocationManager()
fileprivate var currentLocation: CLLocation!
fileprivate var locationManager: LocationManager!
fileprivate var location: String?
fileprivate var locationSet: Bool = false
fileprivate var resultSearchController: UISearchController?
fileprivate var selectedPin: MKPlacemark?
weak var delegate: InviteDelegate?
@IBOutlet weak var dateTextField: UITextField!
@IBOutlet weak var timeTextField: UITextField!
@IBOutlet weak var placeTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
state = .loading
// Assigning the delegate to self
// coreLocationManager.delegate = self
// Setup the map view
// userLocationHelper()
}
/*
- Sets the coffee data
– Sends the information to Firebase
*/
@IBAction func inviteButtonAction(_ sender: UIButton) {
state = .attemptToSendInvite
if inviteComplete() {
// Create coffee
// MAP VIEW LOCATION IS FOR TESTING
// replace with this: mapView.userLocation.title!
coffee = Coffee(date: dateTextField.text!,
time: timeTextField.text!,
location: "Jakarta, Indonesia",
fromId: thisUser!.uid,
toId: viewedUser!.uid,
fromName: thisUser!.name,
toName: viewedUser!.name)
// Saves the meetup data
self.coffee?.save(new: true)
// TODO: Create warning for incomplete invite
self.dismiss(animated: true, completion: {
})
} else {
print("Incomplete")
}
}
private func throwWarning(for error: Error) {
switch error {
case .dateIsEmpty:
break
case .timeIsEmpty:
break
case .locationIsEmpty:
break
default:
break
}
}
/// Method to check if the invitation information is nil or not
fileprivate func inviteComplete() -> Bool {
guard let date = dateTextField.text else {
state = .failedToSendInvitation(as: .dateIsEmpty)
return false
}
guard let time = timeTextField.text else {
state = .failedToSendInvitation(as: .timeIsEmpty)
return false
}
guard let location = placeTextField.text else {
state = .failedToSendInvitation(as: .locationIsEmpty)
return false
}
// TODO: Change the location because this is just a default value
print(date, time, location)
return true
}
}
|
//
// FlickrPictureConvenience.swift
// TaskOut
//
// Created by Reagan Wood on 9/28/16.
// Copyright © 2016 RW Software. All rights reserved.
//
import Foundation
class FlickrPictureConvenience: NSObject {
let urlForImage = "https://c4.staticflickr.com/9/8412/10245552163_1a7f690bc3_h.jpg"
func getFlickrImage(completionHandler handler: (data: NSData) -> Void){
// start activity indicator
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { () -> Void in
if let url = NSURL(string: self.urlForImage),let imgData = NSData(contentsOfURL: url){
handler(data: imgData)
}// end if
} // end closure
}
// MARK: Shared Instance
class func sharedInstance() -> FlickrPictureConvenience{
struct Singleton {
static var sharedInstance = FlickrPictureConvenience()
}
return Singleton.sharedInstance
}
}
|
//
// UploadFile.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** Your file to be uploaded. */
public struct UploadFile: Codable {
/** Your base64 encoded file string. */
public var content: String
public init(content: String) {
self.content = content
}
}
|
import Foundation
import CoreLocation
extension CLLocationCoordinate2D {
func location(for bearing:Double, and distanceMeters:Double) -> CLLocationCoordinate2D {
let distRadians = distanceMeters / (6372797.6) // earth radius in meters
let lat1 = latitude * Double.pi / 180
let lon1 = longitude * Double.pi / 180
let lat2 = asin(sin(lat1) * cos(distRadians) + cos(lat1) * sin(distRadians) * cos(bearing))
let lon2 = lon1 + atan2(sin(bearing) * sin(distRadians) * cos(lat1), cos(distRadians) - sin(lat1) * sin(lat2))
return CLLocationCoordinate2D(latitude: lat2 * 180 / Double.pi, longitude: lon2 * 180 / Double.pi)
}
}
|
//
// SecureField_Customization2.swift
// 100Views
//
// Created by Mark Moeykens on 9/4/19.
// Copyright © 2019 Mark Moeykens. All rights reserved.
//
import SwiftUI
struct SecureField_CustomizationLayers: View {
@State private var userName = ""
@State private var password = ""
var body: some View {
VStack(spacing: 20) {
Text("SecureField")
.font(.largeTitle)
Text("Customization Layers")
.font(.title)
.foregroundColor(.gray)
Text("You can also add a background to the SecureField. It's all the same idea adjust the layers.")
.frame(maxWidth: .infinity)
.padding().font(.title)
.background(Color.purple)
.foregroundColor(Color.white)
.layoutPriority(1)
SecureField("password", text: $password)
.foregroundColor(Color.white)
.frame(height: 40)
.padding(.horizontal)
.background(
Capsule()
.foregroundColor(.purple)
)
.padding(.horizontal)
Image("SecureFieldLayers")
Text("The highlighted layer in that image is the actual text field layer of the view.")
.font(.title)
.padding(.horizontal)
}
}
}
struct SecureField_CustomizationLayers_Previews: PreviewProvider {
static var previews: some View {
SecureField_CustomizationLayers()
}
}
|
import Foundation
import UIKit
import LocalAuthentication
public class SendViewController : UIViewController, UITextFieldDelegate, ValidationDelegate, ScanViewControllerDelegate {
/**
This method will be called on delegate object when validation fails.
- returns: No return value.
*/
@IBOutlet weak var addressTxtField: UITextField!
@IBOutlet weak var addressErrorLabel : UILabel!
@IBOutlet weak var ffLbl : UILabel!
@IBOutlet weak var hhLbl : UILabel!
@IBOutlet weak var hLbl : UILabel!
@IBOutlet weak var ffSwitch : UISwitch!
@IBOutlet weak var hhSwitch : UISwitch!
@IBOutlet weak var hSwitch : UISwitch!
@IBOutlet weak var amountSlider : UISlider!
@IBOutlet weak var sliderMaxValSatoshiLabl : UILabel!
@IBOutlet weak var sliderMaxValFiatLabl : UILabel!
@IBOutlet weak var amountErrorLabel: UILabel!
@IBOutlet weak var amountSatTxtField: UITextField!
@IBOutlet weak var amountFiatTxtField: UITextField!
@IBOutlet weak var amountFiatCodeLabel: UILabel!
@IBOutlet weak var feeValSatLbl : UILabel!
@IBOutlet weak var feeValFiatLbl : UILabel!
let validator = Validator()
var counterTx : Int = 0
var address : Address!
var key : BRKey!
var feeData : Fee!
let testNet = true
//TestAddress, using for initialization
let testAddress = "0000000000000000000000000000"
var scanViewController : ScanViewController!
var selectedFeeRate : Int!
var transactionProtocol : TransactionProtocol?
var minersFeeProtocol : MinersFeeProtocol?
//UISwitch logic variables
var switchArr : [UISwitch] = []
var switchDictionary: [UISwitch : UILabel] = [:]
//"transaction.send.response"
//Notifications
let selectorFeeChanged = Notification.Name("sendviewcontroller.feeData.changed")
let selectorAmountChanged = Notification.Name("sendviewcontroller.amount.changed")
//FlagForSendOperation
var addressValid : Bool = false
var amountValid : Bool = false
//Authentification
var laContext : LAContext!
var authenticated = false
//TextField And Slider synchronization
var uiItemsSynchrArr = [AnyObject]()
override public func viewDidLoad() {
super.viewDidLoad()
//UISwitchLogic
switchArr += [ffSwitch,hhSwitch,hSwitch]
switchDictionary = [ self.ffSwitch! : self.ffLbl! , self.hhSwitch! : self.hhLbl! , self.hSwitch! : self.hLbl! ]
////TextField And Slider synchronization
//self.uiItemsSynchrArr += [self.amountSlider , self.amountSatTxtField , self.amountFiatTxtField ]
self.uiItemsSynchrArr.append(self.amountSlider)
self.uiItemsSynchrArr.append(self.amountSatTxtField)
self.uiItemsSynchrArr.append(self.amountFiatTxtField)
self.prepareAndLoadViewData()
//Notifications
//Need to know when feeData is loaded
NotificationCenter.default.addObserver(self, selector: #selector(feeDataChanged), name: selectorFeeChanged, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(amountDataChanged), name: selectorAmountChanged, object: nil)
//Authentication
self.laContext = LAContext()
//Valiadtion in privateKeyTextField
validator.registerField(field: addressTxtField, errorLabel: addressErrorLabel, rules: [RequiredRule(), AddressRule() ])
validator.registerField(field: amountSatTxtField, errorLabel: amountErrorLabel, rules: [RequiredRule(), DigitRule() ])
validator.registerField(field: amountFiatTxtField, errorLabel: amountErrorLabel, rules: [RequiredRule(), DecimalRule() ])
}
func prepareAndLoadViewData(){
self.loadSliderData()
self.updateFeeData()
self.loadFeeData()
self.selectedFeeRate = 0
self.feeValSatLbl.text = "0"
self.updateFiatData()
addressTxtField.layer.cornerRadius = 5
addressTxtField.delegate = self
amountSatTxtField.delegate = self
amountFiatTxtField.delegate = self
}
override public func viewWillAppear(_ animated: Bool) {
self.scanViewController = self.storyboard?.instantiateViewController(withIdentifier: "ScanViewController") as! ScanViewController
}
func createTxDataWithDefaultParameters(){
//Needs only for initialization
let defaultFee = 0
let sendAddress = self.testAddress
let validKey = self.key!
let amountSatTxtField = self.amountSatTxtField.text!
let amount = Int(amountSatTxtField)!
let transaction : Transaction = Transaction(address: self.address!, brkey: validKey, sendAddress: sendAddress, fee: defaultFee , amount: amount)
self.transactionProtocol = transaction
self.minersFeeProtocol = transaction
self.minersFeeProtocol?.calculateMinersFee()
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK:FeeLogic
func loadFeeData(){
let userInitiatedQueue = GCDManager.sharedInstance.getQueue(byQoS: DispatchQoS.userInitiated)
userInitiatedQueue.async {
BlockCypherApi.getFeeData(doWithJson: { json in
guard let t_feeData : Fee = Fee(json: json) else {
return
}
self.feeData = t_feeData
self.updateFeeData()
self.createTxDataWithDefaultParameters()
self.updateSelectedFeeRate(switcherSelected: self.hhSwitch!)
})
}
}
func updateFeeData(){
if( nil != self.feeData?.fastestFee){
self.ffLbl?.text = String(self.feeData!.fastestFee!)
self.hhLbl?.text = String(self.feeData!.halfHourFee!)
self.hLbl?.text = String(self.feeData!.hourFee!)
}else{
self.ffLbl?.text = "NO"
self.hhLbl?.text = "NO"
self.hLbl?.text = "NO"
}
}
func updateFiatData(){
let cp : CurrencyPrice? = MPManager.sharedInstance.sendData(byString: MPManager.localCurrency) as! CurrencyPrice?
self.amountFiatCodeLabel.text! = cp != nil ? (cp?.code!)! : "No Data"
}
func setFeeForSelectedSwitchAndTurnOffSwitchesExcept(switched: UISwitch){
switched.isEnabled = false
self.updateSelectedFeeRate(switcherSelected: switched)
for uiSwitch in self.switchArr{
if (uiSwitch != switched && uiSwitch.isOn){
uiSwitch.isEnabled = true
uiSwitch.setOn(false, animated: true)
break
}
}
}
func updateSelectedFeeRate(switcherSelected: UISwitch){
let switchLbl : UILabel = switchDictionary[switcherSelected]!
guard let switchText : String = switchLbl.text! as String else {
return
}
let oldValue = self.selectedFeeRate
let newVal = Int( switchText )
if (newVal != oldValue && nil != newVal) {
self.selectedFeeRate = newVal
NotificationCenter.default.post(name: selectorFeeChanged, object: self)
}
}
//MARK:
//MARK:Slider methods
func loadSliderData(){
guard let balance : Int = Int((self.address?.balance)!) else {
NSException(name: NSExceptionName(rawValue: "SendViewControllerAddressNil"), reason: "Address or balance is nil", userInfo: nil).raise()
}
self.amountSlider.maximumValue = Float(balance)
self.sliderMaxValSatoshiLabl.text = String(balance)
self.sliderMaxValFiatLabl.text = getFiatString(bySatoshi: balance, withCode: true)
let defaultVal = Float(balance/10)
self.amountSlider.setValue( defaultVal , animated: true)
self.amountSatTxtField.text = "\(Int(defaultVal))"
self.amountFiatTxtField.text = getFiatString(bySatoshi: Int(defaultVal), withCode: false)
}
//MARK:
//MARK:ScanViewControllerDelegate
func DelegateScanViewController(controller: ScanViewController, dataFromQrCode : String?){
guard let t_dataQrCode = dataFromQrCode else {return}
self.addressTxtField.text = t_dataQrCode
validator.validate(delegate: self as! ValidationDelegate)
}
//MARK:
//MARK:TextDelegate
@nonobjc public func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
if(textField == self.amountSatTxtField || textField == self.amountFiatTxtField ) {
validator.validateField(field: textField){ error in
//Kostil 2000 b|
let isAmountNoMoreThanBalance = Int(self.amountSatTxtField.text!)! <= Int((self.address.balance)!)
let isAmountDigitAndNoMoreThanBalance : Bool = error == nil ? isAmountNoMoreThanBalance : false
if ( isAmountDigitAndNoMoreThanBalance ) {
//Field validation was successful
//let amount : Int = Int(textField.text!)!
self.changeValidatableFieldToDefault(validateField: self.amountSatTxtField, errorLbl: self.amountErrorLabel)
NotificationCenter.default.post(name: selectorAmountChanged, object: self)
self.amountValid = true
self.synchronizeTxtFields(textField: textField)
} else {
// Validation error occurred
let field = self.amountSatTxtField
field?.layer.borderColor = UIColor.red.cgColor
field?.layer.borderWidth = 1.0
//Kostil 2000 b|
let errorMessage : String = isAmountNoMoreThanBalance ? "Not number value" : "Amount more than Balance"
self.amountErrorLabel.text = errorMessage // works if you added labels
self.amountErrorLabel.isHidden = false
self.amountValid = false
}
}
}else {
validator.validate(delegate: self as! ValidationDelegate)
}
return true
}
//MARK:
func synchronizeTxtFields(textField : UITextField) {
for uiItem in self.uiItemsSynchrArr {
//Mark: - Zlo
if uiItem is UISlider {
(uiItem as! UISlider).setValue(Float(textField.text!)!, animated: true)
} else if uiItem is UITextField {
(uiItem as! UITextField).text = textField.text
}
//Mark: -
}
}
func getFiatString(bySatoshi : Int , withCode : Bool) -> String {
let localCurrency : CurrencyPrice? = MPManager.sharedInstance.sendData(byString: MPManager.localCurrency) as! CurrencyPrice?
let fiatBalanceString = Utilities.getFiatBalanceString(model: localCurrency, satoshi: bySatoshi, withCode: withCode)
let fiatString = fiatBalanceString != "" ? "\(fiatBalanceString)" : ""
return fiatString
}
func changeValidatableFieldToDefault(validateField: UITextField, errorLbl : UILabel){
validateField.layer.borderColor = UIColor.green.cgColor
validateField.layer.borderWidth = 1.0
errorLbl.isHidden = true
}
//MARK:Validation
public func validationSuccessful(){
self.addressValid = true
self.changeValidatableFieldToDefault(validateField: self.addressTxtField, errorLbl: self.addressErrorLabel!)
self.transactionProtocol?.changeSendAddress(newAddress: self.addressTxtField.text!)
}
public func validationFailed(errors: [(Validatable, ValidationError)]) {
for (field, error) in errors {
let field = field as? UITextField
if (field != self.amountSatTxtField){
field!.layer.borderColor = UIColor.red.cgColor
field!.layer.borderWidth = 1.0
error.errorLabel?.text = error.errorMessage // works if you added labels
error.errorLabel?.isHidden = false
self.addressValid = false
}
}
}
//MARK:
//MARK:Notifications
func feeDataChanged() {
let miners_fee : Int = (self.minersFeeProtocol!.updateMinersFeeWithFee(newFeeRate: self.selectedFeeRate))
self.feeValSatLbl?.text = "\(miners_fee)"
self.feeValFiatLbl!.text! = self.getFiatString(bySatoshi: miners_fee, withCode: true)
}
func amountDataChanged() {
let strAmount : String = self.amountSatTxtField.text!
let miners_fee : Int = (self.minersFeeProtocol!.updateMinersFeeWithAmount(newAmount: Int(strAmount)!))
self.feeValSatLbl?.text = "\(miners_fee)"
self.feeValFiatLbl!.text! = self.getFiatString(bySatoshi: miners_fee, withCode: true)
}
//MARK:
//MARK: Authentification
func authenticateUser( reasonString: String, complete: @escaping ( _ authSucces : Bool ) -> Void ) {
var laError : NSError?
let reasonString = reasonString
var auth = false
//Auth does't work on simulator
//LAPolicy.deviceOwnerAuthentication
if (laContext.canEvaluatePolicy( .deviceOwnerAuthentication , error: &laError)){
laContext.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reasonString, reply: { (success, error) -> Void in
if(success) {
auth = true
}
complete(auth)
})
} else {
complete(auth)
}
}
// DispatchQueue.main.async {
// <#code#>
// }
//MARK:
//MARK:Actions
@IBAction func cancel(sender: AnyObject) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func inserBtnTapped(sender: AnyObject) {
let pasteBoard = UIPasteboard.general.strings
if ((addressTxtField.text?.isEmpty) != nil){
addressTxtField?.text = ""
}
addressTxtField?.text = pasteBoard?.last
validator.validate(delegate: self as! ValidationDelegate)
}
@IBAction func qrCodeBtnTapped(sender: AnyObject) {
self.scanViewController.delegate = self
self.navigationController?.present(self.scanViewController , animated: true, completion: nil)
}
@IBAction func ffValueChanged(_ sender: UISwitch) {
setFeeForSelectedSwitchAndTurnOffSwitchesExcept(switched: sender)
}
@IBAction func hhValueChanged(_ sender: UISwitch) {
setFeeForSelectedSwitchAndTurnOffSwitchesExcept(switched: sender)
}
@IBAction func hValueChanged(_ sender: UISwitch) {
setFeeForSelectedSwitchAndTurnOffSwitchesExcept(switched: sender)
}
@IBAction func sliderChanged(sender: UISlider) {
let intValue = Int(sender.value)
self.amountSatTxtField.text = String(intValue)
self.amountFiatTxtField.text = self.getFiatString(bySatoshi: intValue, withCode: false)
self.changeValidatableFieldToDefault(validateField: self.amountSatTxtField, errorLbl: self.amountErrorLabel!)
self.changeValidatableFieldToDefault(validateField: self.amountFiatTxtField, errorLbl: self.amountErrorLabel!)
NotificationCenter.default.post(name: selectorAmountChanged, object: self)
}
@IBAction func acceptTxBtnTapped(sender: AnyObject) {
validator.validate(delegate: self as! ValidationDelegate)
textFieldShouldReturn(textField: self.amountSatTxtField)
let alertController = UIAlertController(title: "Send Transaction Error", message: "Error not all properties are valid", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler:{ UIAlertAction in
//b|
})
alertController.addAction(cancelAction)
if (addressValid && amountValid){
let reasonString = "Authenticate yourself \nYou want to send \(self.amountSatTxtField!.text!)(\(self.amountFiatTxtField!.text!)) \nTo address \(self.addressTxtField!.text!)\nWith miners fee \(self.feeValSatLbl!.text!)(\(self.feeValFiatLbl!.text!))"
self.authenticateUser(reasonString: reasonString, complete: { auth in
if auth {
self.counterTx = self.counterTx + 1
print("Counter equals \(self.counterTx)")
self.transactionProtocol?.createTransaction()
self.transactionProtocol?.signTransaction()
self.transactionProtocol?.sendTransaction(succes: { response in
alertController.title = "Transaction sended"
alertController.message = "Authentication is successfull Transaction Sended"
self.present(alertController, animated: true, completion: nil)
//self.dismissViewControllerAnimated(true, completion: nil)
})
}
})
} else {
self.present(alertController, animated: true, completion: nil)
}
}
//MARK:
}
|
func sayHay(name: String, age: Int, planet: String) {
println("I'm \(name) and I am \(age) and I hail from \(planet)")
}
func sayHay1(name: String, age: Int, andPlanet planet: String) {
println("I'm \(name) and I am \(age) and I hail from \(planet)")
}
func sayHey(name: String, #age: Int, planet: String) { //shorthand external parameter name
println("I'm \(name) and I am \(age) and I hail from \(planet)")
}
func sayHoy(name: String, age: Int, planet: String = "Venus") { //default parameter value
println("I'm \(name) and I am \(age) and I hail from \(planet)")
}
func sayHiy(name: String, age: Int, planet: String = "Venus", country: String = "USA") { //default parameter values
println("I'm \(name) and I am \(age) and I hail from \(country), \(planet)")
}
func sayHays(name: String, age: Int, planets: String...) {
println("I'm \(name) and I am \(age) and I hail from \(planets)")
}
func sayHays1(name: String, age: Int, country: String = "USA", planets: String...) {
println("I'm \(name) and I am \(age) and I hail from \(country), \(planets)")
}
func sayHoy1(inout name: String, age: Int) {
name = "Jack"
println("I'm \(name) and I am \(age).")
}
func sayHoy2(inout names: [String], age: Int) {
names.append("Kobe")
println("We are \(names), and we are \(age)")
}
sayHay("Jerry", 21, "Mars") //no external parameter names, so no need for parameter labels
sayHay1("Jerry", 21, andPlanet: "Saturn")
sayHey("Jerry", age: 21, "Pluto") //shorthand external paramter name used with #, so we include paramter name age
sayHoy("Jerry", 21, planet: "Neptune")
sayHiy("Jerry", 21, country: "France") //func definition with multiple default values. keep them all at the end, and refer to them by their external parameter names to not confuse swift
sayHays("Jerry", 21, "triggerville", "holtsville", "looneytuneville") //function with variadic parameter
sayHays1("Jerry", 21, country: "Japan", "triggerville", "holtsville", "looneytuneville") //function with variadic parameter after default parameter value
var name = "Jerry"
var names = ["James", "LeBron"]
sayHoy1(&name, 21)
println(name)
sayHoy2(&names, 21)
println(names)
|
//
// IntroPresenter.swift
// Bank App
//
// Created by Chrystian on 24/11/18.
// Copyright © 2018 Salgado's Productions. All rights reserved.
//
import Foundation
import UIKit
protocol IntroPresentationLogic {
func showHistoryController()
func showError(error: BankError)
func showLoading()
func catchPasswordInvalid()
func abortAutoLogin(error: BankError)
func setDefaultStatusBar()
func enableLoginButton(_ enable: Bool)
}
class IntroPresenter: IntroPresentationLogic {
weak var viewController: IntroDisplayLogic?
func showHistoryController() {
viewController?.presentDetailController()
viewController?.configureLoginAnimationCompletion()
}
func showError(error: BankError) {
if let errorMessage = error.message {
buildAlert(title: "Erro", menssage: errorMessage)
}
viewController?.configureLoginAnimationCompletion()
}
func showLoading() {
viewController?.configureLoginAnimationLoading()
}
func catchPasswordInvalid() {
buildAlert(title: NSLocalizedString("SENHA_INVALIDA", comment: ""), menssage: NSLocalizedString("SENHA_INVALIDA_ERROR_MESSAGE", comment: ""))
viewController?.configureLoginAnimationCompletion()
viewController?.configureInvalidPassword()
}
func abortAutoLogin(error: BankError) {
#if DEBUG
print(error.message)
#endif
}
func setDefaultStatusBar() {
viewController?.setupStatusBar(statusBarStyle: .default, backgroudColor: .clear)
}
func enableLoginButton(_ enable: Bool) {
viewController?.enableLogin(enable)
}
private func buildAlert(title: String, menssage: String) {
let alertBox = UIAlertController(title: title, message: menssage, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default) { (action) in
alertBox.dismiss(animated: true, completion: nil)
}
alertBox.addAction(action)
viewController?.showError(alertBox)
}
}
|
//
// DaySix.swift
// AdventOfCode2017
//
// Created by Shawn Veader on 12/6/17.
// Copyright © 2017 v8logic. All rights reserved.
//
import Foundation
struct DaySix: AdventDay {
struct Memory {
/// Size of the memory bank
let size: Int
/// Value of the memory banks
var banks: [Int]
/// Copy of each previous iteration of memory redistribution
var previousConfigurations = [[Int]]()
init(_ seed: [Int]) {
size = seed.count
banks = seed
}
mutating func redistrubute() -> Int {
previousConfigurations = [[Int]]() // clear any previous configs
// loop until we find our current configuration has been seen before
while !previousConfigurations.contains(where: { $0 == banks }) {
// print(banks)
previousConfigurations.append(banks)
// determine next bank to redistribute
guard let index = indexToRedistribute() else {
print("Unable to determine index.")
break
}
redistribute(index: index)
}
return previousConfigurations.count // -1?
}
private func indexToRedistribute() -> Int? {
let max = banks.max()
// find all indices that match the max
let indices = banks.enumerated().flatMap { (idx, blk) -> Int? in
return blk == max ? idx : nil
}
return indices.min()
}
/// Redistribute the blocks from a given index.
private mutating func redistribute(index: Int) {
// print("\tRedistribute \(index)")
var blockCount = banks[index]
var distributionIndex = index + 1
banks[index] = 0 // remove all blocks from current index
while blockCount > 0 {
// spread blocks around the memory banks
banks[distributionIndex % size] += 1
blockCount -= 1
distributionIndex += 1
}
}
}
// MARK: -
func defaultInput() -> String? {
return "5 1 10 0 1 7 13 14 3 12 8 10 7 12 0 6"
}
func run(_ input: String? = nil) {
guard let runInput = input ?? defaultInput() else {
print("Day 6: 💥 NO INPUT")
exit(10)
}
let initialMemory = runInput.split(separator: " ").flatMap { str -> String? in
let cleanedStr = str.replacingOccurrences(of: " ", with: "")
return cleanedStr.count > 0 ? cleanedStr : nil
}.flatMap(Int.init)
let thing = partOne(input: initialMemory)
guard let answer = thing else {
print("Day 6: (Part 1) 💥 Unable to calculate answer.")
exit(1)
}
print("Day 6: (Part 1) Answer ", answer)
let thing2 = partTwo(input: initialMemory)
guard let answer2 = thing2 else {
print("Day 6: (Part 1) 💥 Unable to calculate answer.")
exit(1)
}
print("Day 6: (Part 2) Answer ", answer2)
}
// MARK: -
func partOne(input: [Int]) -> Int? {
var memory = Memory(input)
return memory.redistrubute()
}
func partTwo(input: [Int]) -> Int? {
var memory = Memory(input)
_ = memory.redistrubute() // finds the end of the loop
return memory.redistrubute() // find the length of the loop by going again till we hit the start
}
}
|
////
//// PastOrderVC.swift
//// Qvafy
////
//// Created by ios-deepak b on 25/08/20.
//// Copyright © 2020 IOS-Aradhana-cat. All rights reserved.
////
import UIKit
class PastOrderVC: UIViewController {
//MARK: Outlets
//@IBOutlet weak var vwHeader: UIView!
// @IBOutlet weak var txtSearch: UITextField!
@IBOutlet weak var vwSearch: UIView!
@IBOutlet weak var vwTable: UIView!
@IBOutlet weak var vwNoData: UIView!
@IBOutlet weak var tblPastOrder: UITableView!
@IBOutlet weak var lblChatCount: UILabel!
// Localisation Outlets -
@IBOutlet weak var lblPastorderHeaders: UILabel!
@IBOutlet weak var lblLONoPastOrderHere: UILabel!
// @IBOutlet weak var vwBottom: UIView!
//MARK: - Variables
var arrPastOrderList:[PastOrderModel] = []
var strRestaurantId = ""
//Searching & pagination
/// var strSearchText = ""
var isDataLoading:Bool=false
var isSearching:Bool=false
var limit:Int=10
var offset:Int=0
var totalRecords = Int()
// Refresh
var pullToRefreshCtrl:UIRefreshControl!
var isRefreshing = false
//MARK: LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
self.setPullToRefresh()
if objAppShareData.isFromBannerNotification == true {
let sb = UIStoryboard(name: "PastOrder", bundle: nil)
let detailVC = sb.instantiateViewController(withIdentifier: "PastOrderDetailVC") as! PastOrderDetailVC
detailVC.strOrderId = objAppShareData.strBannerReferenceID
self.navigationController?.pushViewController(detailVC, animated: false)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.localization()
print("viewWillAppear is called")
self.lblChatCount.layer.cornerRadius = self.lblChatCount.frame.height/2
self.lblChatCount.clipsToBounds = true
objAppShareData.showChatCountFromFirebase(lbl: self.lblChatCount)
self.tabBarController?.tabBar.isHidden = false
self.vwNoData.isHidden = true
self.vwTable.isHidden = true
self.removeAllData()
self.callWsGetPastOrderList()
}
func removeAllData(){
self.arrPastOrderList.removeAll()
self.limit = 10
self.offset = 0
// self.strSearchText = ""
// self.txtSearch.text = ""
self.tblPastOrder.reloadData()
}
func localization(){
self.lblLONoPastOrderHere.text = "No_past_order_here".localize
self.lblPastorderHeaders.text = "Past_Order".localize
}
//MARK: - Button Action
//
// @IBAction func btnBack(_ sender: Any) {
// self.view.endEditing(true)
// self.navigationController?.popViewController(animated: true)
// }
@IBAction func btnChatAction(_ sender: Any) {
self.view.endEditing(true)
let sb = UIStoryboard(name: "Chat", bundle: nil)
let detailVC = sb.instantiateViewController(withIdentifier: "ChatHistoryVC") as! ChatHistoryVC
self.navigationController?.pushViewController(detailVC, animated: true)
}
}
//MARK: - Extension UITableViewDelegate and UITableViewDataSource
extension PastOrderVC : UITableViewDelegate ,UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.arrPastOrderList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tblPastOrder.dequeueReusableCell(withIdentifier: "PastOrderCell")as! PastOrderCell
if arrPastOrderList.count > 0 {
let obj = self.arrPastOrderList[indexPath.row]
// cell.vwContainer.setShadowWithCornerRadius()//
cell.lblRestaurant.text = obj.strRestaurantName.capitalizingFirstLetter()
cell.lblPrice.text = "$" + obj.strTotalAmount
cell.lblCoustomer.text = obj.strCustomerName.capitalizingFirstLetter()
cell.setCorners()
if obj.strCurrentStatus == "6"{
cell.lblStatus.text = " \("Completed".localize) "
cell.vwStatus.backgroundColor = #colorLiteral(red: 0, green: 0.5725490196, blue: 0.02745098039, alpha: 1)
}else if obj.strCurrentStatus == "7" {
cell.lblStatus.text = " \("Cancelled".localize) "
cell.vwStatus.backgroundColor = #colorLiteral(red: 0.9490196078, green: 0.07450980392, blue: 0.07450980392, alpha: 1)
}
//cell.vwProfile.setProfileVerifyView(vwOuter: cell.vwProfile, img: cell.imgCustomer)
cell.vwProfile.setUserProfileView(vwOuter: cell.vwProfile, img: cell.imgCustomer , radius : 4)
let profilePic = obj.strRestaurantImage
if profilePic != "" {
let url = URL(string: profilePic)
cell.imgRestaurant.sd_setImage(with: url, placeholderImage: #imageLiteral(resourceName: "detail_upper_placeholder_img"))
}
let Pic = obj.strCustomerImage
if Pic != "" {
let url = URL(string: Pic)
cell.imgCustomer.sd_setImage(with: url, placeholderImage: #imageLiteral(resourceName: "user_placeholder_img_new"))
}
// let date = objAppShareData.changeDateformatWithDate(strDate: obj.strCreatedAt )
let date = objAppShareData.convertLocalTime(strDateTime: obj.strCreatedAt)
print("date is is \(date)")
if obj.strCreatedAt.isEmpty == false {
// let fullNameArr = date.characters.split{$0 == ", "}.map(String.init)
// let fullNameArr = date.split(separator: ",")
let fullNameArr = date.components(separatedBy: ", ")
cell.lblDate.text = fullNameArr[0]
cell.lblTime.text = fullNameArr[1]
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if arrPastOrderList.count > 0 {
let obj = arrPastOrderList[indexPath.row]
print("obj.strUserID in didselect \(obj.strOrderID)")
let sb = UIStoryboard(name: "PastOrder", bundle: nil)
let detailVC = sb.instantiateViewController(withIdentifier: "PastOrderDetailVC") as! PastOrderDetailVC
detailVC.strOrderId = obj.strOrderID
self.navigationController?.pushViewController(detailVC, animated: true)
}
}
}
extension PastOrderVC {
// TODO: Webservice For getPastOrder
func callWsGetPastOrderList(){
if !objWebServiceManager.isNetworkAvailable(){
objWebServiceManager.StopIndicator()
objAlert.showAlert(message: NoNetwork.localize , title: kAlert.localize , controller: self)
return
}
objWebServiceManager.StartIndicator()
if isRefreshing{
objWebServiceManager.StopIndicator()
}
objWebServiceManager.requestGet(strURL:WsUrl.getPastOrder+"limit="+String(self.limit)+"&offset="+String(self.offset),
Queryparams: [:], body: nil, strCustomValidation: "", success: {response in
print(response)
objWebServiceManager.StopIndicator()
let status = (response["status"] as? String)
let message = (response["message"] as? String)
if self.isRefreshing{
self.arrPastOrderList.removeAll()
}
self.isRefreshing = false
self.pullToRefreshCtrl.endRefreshing()
if status == "success"
{
let dict = response["data"] as? [String:Any]
// self.totalRecords = dict?["total_records"] as? Int ?? 0
if let dataFound = dict?["data_found"] as? Int {
if dataFound == 1 {
self.vwNoData.isHidden = true
self.vwTable.isHidden = false
// self.totalRecords = Int(dict?["total_records"] as? String ?? "") ?? 0
self.totalRecords = dict?["total_records"] as? Int ?? 0
if let arrPastOrderData = dict?["past_order_list"] as? [[String:Any]]{
for dictPastOrderData in arrPastOrderData{
let objPastOrderData = PastOrderModel.init(dict: dictPastOrderData)
self.arrPastOrderList.append(objPastOrderData)
}
print("arrPastOrderList count is \(self.arrPastOrderList.count)")
}
}else{
self.vwNoData.isHidden = false
self.vwTable.isHidden = true
}
}
print("self.totalRecords count is \(self.totalRecords)")
self.tblPastOrder.reloadData()
}else
{
objAlert.showAlert(message:message ?? "", title: kAlert.localize, controller: self)
}
}, failure: { (error) in
print(error)
objWebServiceManager.StopIndicator()
objAlert.showAlert(message:kErrorMessage.localize, title: kAlert.localize, controller: self)
})
}
}
//MARK:- Pagination
extension PastOrderVC {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isDataLoading = false
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if velocity.y < 0 {
print("up")
}else{
if ((self.tblPastOrder.contentOffset.y + self.tblPastOrder.frame.size.height) >= self.tblPastOrder.contentSize.height)
{
if !isDataLoading{
isDataLoading = true
self.offset = self.offset+self.limit
if self.arrPastOrderList.count == self.totalRecords {
}else {
print("api calling in pagination ")
self.callWsGetPastOrderList()
}
}
}
}
}
}
//MARK: - Pull to refresh list
extension PastOrderVC{
func setPullToRefresh(){
pullToRefreshCtrl = UIRefreshControl()
pullToRefreshCtrl.addTarget(self, action: #selector(self.pullToRefreshClick(sender:)), for: .valueChanged)
if #available(iOS 10.0, *) {
self.tblPastOrder.refreshControl = pullToRefreshCtrl
} else {
self.tblPastOrder.addSubview(pullToRefreshCtrl)
}
}
@objc func pullToRefreshClick(sender:UIRefreshControl) {
isRefreshing = true
limit = 10
offset = 0
self.callWsGetPastOrderList()
}
}
|
//
// TappableTextView.swift
// TappableTextView
//
// Created by Willie Johnson on 5/4/18.
// Copyright © 2018 Willie Johnson. All rights reserved.
//
import UIKit
public protocol TappableTextViewDelegate: AnyObject {
func wordViewUpdated(_ wordView: WordView)
func wordViewOpened(_ wordView: WordView)
func wordViewClosed(_ wordView: WordView)
}
open class TappableTextView: UITextView {
public var color: UIColor = .black {
willSet(color) {
updateViews()
}
didSet(color) {
updateViews()
}
}
/// Handles behaviors for the **contentView**.
private var animator: UIDynamicAnimator!
/// The behavior that forces the **wordView** to remain in the center of the **contentView**.
private var snap: UISnapBehavior!
/// The subview that appears when a highlighted word (HighlightView) is pressed.
public var wordView: WordView?
weak var tappableTextViewDelegate: TappableTextViewDelegate?
public weak var rootTappableTextView: TappableTextView?
public override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setupView()
}
public convenience init(frame: CGRect, color: UIColor) {
self.init(frame: frame, textContainer: nil)
self.color = color
updateViews()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
public func setDelegate(_ delegate: TappableTextViewDelegate) {
self.tappableTextViewDelegate = delegate
}
}
@available(iOS 10.0, *)
extension TappableTextView: UITextViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard let wordView = wordView else { return }
let distance = abs(wordView.frame.origin.y - scrollView.contentOffset.y)
guard distance > 80 else { return }
wordView.closeButtonPressed(self)
}
}
// MARK: - Helper methods
@available(iOS 10.0, *)
private extension TappableTextView {
/// Configure the UITextView with the required gestures to make text in the view tappable.
func setupView() {
contentInset = UIEdgeInsets.init(top: 0, left: 16, bottom: 0, right: 16)
let textTapGesture = UITapGestureRecognizer(target: self, action: #selector(textTapped(recognizer:)))
textTapGesture.numberOfTapsRequired = 1
addGestureRecognizer(textTapGesture)
isSelectable = false
isEditable = false
}
func updateViews() {
backgroundColor = color
textColor = color.contrastColor()
font = Style.normalFont.withSize(20)
}
func getRootTappableTextView() -> TappableTextView? {
if rootTappableTextView == nil {
rootTappableTextView = self
}
return rootTappableTextView
}
/// Handle taps on the UITextView.
///
/// - Parameter recognizer: The UITapGestureRecognizer that triggered this handler.
@objc func textTapped(recognizer: UITapGestureRecognizer) {
guard wordView == nil else { return }
Global.softImpactFeedbackGenerator.prepare()
// Grab UITextView and its content.
guard let textView = recognizer.view as? UITextView else {
return
}
// Grab the word.
let tapLocation = recognizer.location(in: textView)
guard let word = getWordAt(point: tapLocation) else { return }
let highlight = HighlightView(word: word, color: .randomColor())
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapOnHighlightView(recognizer:)))
tapGesture.delegate = self
textView.addSubview(highlight)
highlight.addGestureRecognizer(tapGesture)
// Animate highlight
highlight.transform = .init(scaleX: 0.01, y: 1)
highlight.expandAnimation()
Global.softImpactFeedbackGenerator.impactOccurred()
textView.selectedTextRange = nil
}
@objc func handleTapOnHighlightView(recognizer: UIGestureRecognizer) {
guard let highlightView = recognizer.view as? HighlightView else { return }
if let wordView = wordView {
wordView.closeButtonPressed(getRootTappableTextView()!)
}
wordView = WordView(highlightView: highlightView)
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handleSwipeOnWordView(recognizer:)))
panGesture.delegate = self
guard let wordView = wordView else { return }
wordView.addGestureRecognizer(panGesture)
guard let rootTappableTextView = getRootTappableTextView() else { return }
wordView.delegate = rootTappableTextView
wordView.rootTappableTextView = rootTappableTextView
rootTappableTextView.addSubview(wordView)
wordView.openAnimation()
animator = UIDynamicAnimator(referenceView: rootTappableTextView)
snap = UISnapBehavior(item: wordView, snapTo: CGPoint(x: rootTappableTextView.bounds.midX, y: rootTappableTextView.bounds.midY))
snap.damping = 0.9
animator.addBehavior(snap)
guard let tappableTextViewDelegate = rootTappableTextView.tappableTextViewDelegate else { return }
tappableTextViewDelegate.wordViewOpened(wordView)
}
@objc func handleSwipeOnWordView(recognizer: UIPanGestureRecognizer) {
guard let wordView = recognizer.view as? WordView else { return }
guard let wordViewTextView = wordView.superview as? UITextView else { return }
bringSubviewToFront(wordView)
let translation = recognizer.translation(in: wordViewTextView)
wordView.center = CGPoint(x: wordView.center.x + translation.x, y: wordView.center.y + translation.y)
recognizer.setTranslation(CGPoint.zero, in: wordViewTextView)
switch recognizer.state {
case .began:
animator.removeBehavior(snap)
case .ended, .cancelled, .failed:
let velocity = recognizer.velocity(in: wordViewTextView)
let magnitude = sqrt((velocity.x * velocity.x) + (velocity.y * velocity.y))
guard magnitude < 700 else {
wordView.closeButtonPressed(self)
return
}
self.animator.addBehavior(self.snap)
default: break
}
}
}
@available(iOS 10.0, *)
extension TappableTextView: WordViewDelegate {
func wordViewUpdated(_ wordView: WordView) {
guard let tappableTextViewDelegate = tappableTextViewDelegate else { return }
tappableTextViewDelegate.wordViewUpdated(wordView)
}
func closeButtonPressed() {
self.animator.removeAllBehaviors()
guard let tappableTextViewDelegate = tappableTextViewDelegate else { return }
guard let wordView = wordView else { return }
tappableTextViewDelegate.wordViewClosed(wordView)
self.wordView = nil
}
}
@available(iOS 10.0, *)
extension TappableTextView: UIGestureRecognizerDelegate {
}
|
//
// DataSettingsManager.swift
// PlanningPoker
//
// Created by david.gonzalez on 24/10/16.
// Copyright © 2016 BEEVA. All rights reserved.
//
import UIKit
protocol DataSettingsManagerInput {
func setPressToShow(state: Bool)
func setShakeToShow(state: Bool)
func setAppLanguage(language: Language)
func getPressToShowValue() -> Bool
func getShakeToShowValue() -> Bool
func getAppLanguage() -> Language
// func getPressToShowValue(completion: (_ inner: () throws -> Bool?) -> Void)
}
class DataSettingsManager: DataSettingsManagerInput {
var dataSettingsLocal: DataSettingsLocal! = DataSettingsLocal()
func setPressToShow(state: Bool) {
dataSettingsLocal.setPressToShow(state: state)
}
func setShakeToShow(state: Bool) {
dataSettingsLocal.setShakeToShow(state: state)
}
func setAppLanguage(language: Language) {
dataSettingsLocal.setAppLanguage(language: language)
}
func getPressToShowValue() -> Bool {
return dataSettingsLocal.getPressToShowValue()
}
func getShakeToShowValue() -> Bool {
return dataSettingsLocal.getShakeToShowValue()
}
func getAppLanguage() -> Language {
return dataSettingsLocal.getAppLanguage()
}
}
|
//
// BaseTableViewCell.swift
// final-project
//
// Created by Vinsofts on 11/16/20.
// Copyright © 2020 Vinsofts. All rights reserved.
//
import Foundation
import UIKit
class BaseTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
}
func configure<T>(_ item: T?){
guard let _ = item else { return }
}
}
|
import Foundation
public class Matrix<Real: FloatingPoint>: CustomStringConvertible {
var store: [[Real]]
//Calculation Group 0
var _determinant: Real?
var _productOfElementary: Matrix?
var _rowEchelon: Matrix?
var lu: Bool = false
//Calculation Group 1
var fullyInverted: Bool = false
var _inverted: Matrix?
//Calculated Alone
var _transposed: Matrix?
private init(_ array: [[Real]], checked: Bool = true) {
self.store = array
}
convenience public init?(_ array: [[Real]]) {
let column = array[0].count
for vector in array {
if vector.count != column {
return nil
}
}
self.init(array, checked: true)
}
convenience public init?(shape: (rows: Int, columns: Int), array: [Real]) {
if array.count != shape.rows * shape.columns {
return nil
}
var store: [[Real]] = []
for i in 0..<shape.rows {
var row: [Real] = []
for j in 0..<shape.columns {
row.append(array[i * shape.rows + j])
}
store.append(row)
}
self.init(store, checked: true)
}
public subscript(i: Int, j: Int) -> Real {
get {
return store[i][j]
}
set(value) {
contaminate()
store[i][j] = value
}
}
public var description: String {
var string = "[\n"
for i in 0..<store.count {
string += " "
for j in 0..<store[0].count {
string += String(describing: self[i, j])
string += ", "
}
string += "\n"
}
return string + "]"
}
public static func identity(_ n: Int) -> Matrix {
var matrix = [[Real]](repeatElement([Real](repeatElement(Real(0), count: n)), count: n))
for diagonal in 0..<n {
matrix[diagonal][diagonal] = Real(1)
}
return Matrix(matrix)!
}
public static func flippedIdentity(_ n: Int) -> Matrix {
var matrix = [[Real]](repeatElement([Real](repeatElement(Real(0), count: n)), count: n))
for diagonal in 0..<n {
matrix[diagonal][n - 1 - diagonal] = Real(1)
}
return Matrix(matrix)!
}
}
|
//
// TestMIMEType.swift
// GenAPI_Tests
//
// Created by Lucas Best on 12/7/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import XCTest
import struct GenAPI.MIMEType
class TestMIMEType: XCTestCase {
func testApplicationJSON() {
let mimeTypeString = "application/json"
let mimeType = MIMEType(rawValue: mimeTypeString)
XCTAssert(mimeType?.type == .application, "MIMEType.type is \(mimeType?.type.rawValue ?? "nil")")
XCTAssert(mimeType?.subtype == .json, "MIMEType.subtype is \(mimeType?.subtype.rawValue ?? "nil")")
}
func testTextHTMLWithCharSet() {
let mimeTypeString = "text/html; charset=utf8"
let mimeType = MIMEType(rawValue: mimeTypeString)
XCTAssert(mimeType?.type == .text, "MIMEType.type is \(mimeType?.type.rawValue ?? "nil")")
XCTAssert(mimeType?.subtype == .html, "MIMEType.subtype is \(mimeType?.subtype.rawValue ?? "nil")")
if let parameters = mimeType?.parameters {
XCTAssert(parameters == ["charset": "utf8"], "MIMEType.parameters are \(parameters)")
}
else {
XCTAssert(false, "MIMEType is nil")
}
}
func testTextHTMLWithCharSetWithCrazyWhiteSpace() {
let mimeTypeString = "text/html; charset = utf8 "
let mimeType = MIMEType(rawValue: mimeTypeString)
XCTAssert(mimeType?.type == .text, "MIMEType.type is \(mimeType?.type.rawValue ?? "nil")")
XCTAssert(mimeType?.subtype == .html, "MIMEType.subtype is \(mimeType?.subtype.rawValue ?? "nil")")
if let parameters = mimeType?.parameters {
XCTAssert(parameters == ["charset": "utf8"], "MIMEType.parameters are \(parameters)")
}
else {
XCTAssert(false, "MIMEType is nil")
}
}
func testApplicationJSONRawValue() {
let mimeType = MIMEType(.application, .json)
XCTAssert(mimeType.rawValue == "application/json")
}
func testTextHTMLWithCharSetRawValue() {
let mimeType = MIMEType(.text, .html, ["charset": "utf8"])
XCTAssert(mimeType.rawValue == "text/html; charset=utf8", "MIMEType.rawValue is \(mimeType.rawValue)")
}
}
|
//
// MergeTests.swift
// DictionaryTools
//
// Created by James Bean on 2/23/16.
// Copyright © 2016 James Bean. All rights reserved.
//
import XCTest
@testable import DictionaryTools
class MergeTests: XCTestCase {
func testMergeSingleDepthNoOverlap() {
var d1 = ["k1": "v1"]
let d2 = ["k2": "v2"]
d1.merge(with: d2)
XCTAssertEqual(d1, ["k1": "v1", "k2": "v2"])
}
func testMergeSingleDepthOverlap() {
var d1 = ["k1": "v1"]
let d2 = ["k1": "OVERRIDE", "k2": "v2"]
d1.merge(with: d2)
XCTAssertEqual(d1, ["k1": "OVERRIDE", "k2": "v2"])
}
func testArrayTypeValueMerge() {
var d1 = ["k1": [1,2,3]]
let d2 = ["k1": [4,5,6]]
d1.merge(with: d2)
XCTAssertEqual(d1["k1"]!, [4,5,6])
}
func testDoubleDepthDeepMergeOverride() {
var d1 = ["k1": [0: 1], "k2": [0: 1]]
let d2 = ["k2": [0: 2], "k3": [0: 3]]
d1.merge(with: d2)
XCTAssertEqual(d1["k2"]![0], 2)
}
func testDoubleDepthDeepMergeAppend() {
var d1 = ["k1": [0: 1], "k2": [0: 1]]
let d2 = ["k2": [0: 2], "k3": [0: 3]]
d1.merge(with: d2)
XCTAssertEqual(d1["k3"]![0], 3)
}
}
|
//
// DashboardMenuView.swift
// f26
//
// Created by David on 29/08/2017.
// Copyright © 2017 com.smartfoundation. All rights reserved.
//
import UIKit
import f26Core
/// A view class for a DashboardMenuView
public class DashboardMenuView: UIView {
// MARK: - Private Stored Properties
fileprivate var selectedYear: Int = 0
fileprivate var years = [Int]()
// MARK: - Public Stored Properties
public var delegate: ProtocolDashboardMenuViewDelegate?
public var menuViewTopLayoutConstraintOffset: CGFloat = 0
@IBOutlet var contentView: UIView!
@IBOutlet weak var menuViewTopLayoutConstraint: NSLayoutConstraint!
@IBOutlet weak var menuViewHeightLayoutConstraint: NSLayoutConstraint!
@IBOutlet weak var backgroundView: UIView!
@IBOutlet weak var yearPickerView: UIPickerView!
@IBOutlet weak var menuShadowView: UIView!
@IBOutlet weak var elenaButtonView: UIView!
@IBOutlet weak var sofiaButtonView: UIView!
// MARK: - Initializers
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
// MARK: - Public Methods
public func setup() {
self.setupContentView()
self.setupBackgroundView()
self.setupYearPickerView()
self.setupDaughterButtonViews()
}
public func presentMenu() {
self.isHidden = false
// Make sure the menu is at correct position
self.setMenuViewHidden()
self.layoutIfNeeded()
UIView.animate(withDuration: 0.3, animations: {
self.backgroundView.alpha = 0.5
self.menuShadowView.alpha = 0.5
self.menuViewTopLayoutConstraint.constant = 0 + self.menuViewTopLayoutConstraintOffset
self.layoutIfNeeded()
}) { (completedYN) in
// Not required
}
}
public func dismissMenu() {
self.layoutIfNeeded()
UIView.animate(withDuration: 0.3, animations: {
self.backgroundView.alpha = 0
self.menuShadowView.alpha = 0
self.setMenuViewHidden()
self.layoutIfNeeded()
}) { (completedYN) in
self.isHidden = true
// Notify the delegate
self.delegate?.dashboardMenuView(didDismiss: self)
}
}
public func populate(years: [Int]) {
self.years = years
self.yearPickerView.reloadAllComponents()
}
public func set(year: Int) {
self.selectedYear = year
// Determine the row of the specified year
var row: Int = -1
for (index, item) in self.years.enumerated() {
if (item == year) { row = index }
}
// Display selected year
if (row >= 0) {
self.yearPickerView.selectRow(row, inComponent: 0, animated: false)
}
}
// MARK: - Private Methods
fileprivate func setupContentView() {
// Load xib
Bundle.main.loadNibNamed("DashboardMenuView", owner: self, options: nil)
addSubview(contentView)
// Position the contentView to fill the view
contentView.frame = self.bounds
contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
fileprivate func setupBackgroundView() {
// Set backgroundView alpha
self.backgroundView.alpha = 0
// Position menuView out of view
self.setMenuViewHidden()
}
fileprivate func setupYearPickerView() {
self.yearPickerView.delegate = self
self.yearPickerView.dataSource = self
}
fileprivate func setMenuViewHidden() {
self.menuViewTopLayoutConstraint.constant = (0 + self.menuViewTopLayoutConstraintOffset) - self.menuViewHeightLayoutConstraint.constant
self.menuShadowView.alpha = 0
}
fileprivate func setupDaughterButtonViews() {
self.elenaButtonView.layer.cornerRadius = self.elenaButtonView.frame.size.width / 2
self.sofiaButtonView.layer.cornerRadius = self.sofiaButtonView.frame.size.width / 2
}
// MARK: - elenaButton Methods
@IBAction func elenaButtonTapped(_ sender: Any) {
self.dismissMenu()
// Notify the delegate
self.delegate?.dashboardMenuView(sender: self, didSelectDaughter: .elena)
}
// MARK: - sofiaButton Methods
@IBAction func sofiaButtonTapped(_ sender: Any) {
self.dismissMenu()
// Notify the delegate
self.delegate?.dashboardMenuView(sender: self, didSelectDaughter: .sofia)
}
// MARK: - backgroundView Methods
@IBAction func backgroundViewTapped(_ sender: Any) {
self.dismissMenu()
}
}
// MARK: - Extension UIPickerViewDelegate
extension DashboardMenuView: UIPickerViewDelegate {
}
// MARK: - Extension UIPickerViewDataSource
extension DashboardMenuView: UIPickerViewDataSource {
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.years.count
}
public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return String(self.years[row])
}
public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.selectedYear = self.years[row]
// Notify the delegate
self.delegate?.dashboardMenuView(sender: self, didSelectYear: self.selectedYear)
}
}
|
//
// ViewController.swift
// List
//
// Created by Franck Tchouambou on 1/8/19.
// Copyright © 2019 Franck. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBOutlet weak var textField: UITextField!
@IBAction func shouldAdd(_ sender: UIButton) {
let text = textField.text ?? ""
if !text.isEmpty {
itemsController.add(text)
textField.text = ""
}
let joined = itemsController.items.joined(separator: "\n")
label.text = joined
}
@IBOutlet weak var label: UILabel!
@IBAction func shouldReset(_ sender: UIButton) {
itemsController.resetItems()
label.text = ""
}
let itemsController = ItemsController()
}
|
//
// FloorController.swift
// Elevator System
//
// Created by Mike Van Amburg on 11/3/21.
//
import Foundation
import ElevatorKit
class FloorController {
var elevatorController = ElevatorController()
var floor = Floor()
func elevatorIsRequested(requestedFloor: Int) {
if isButtonPressed(atFloor: requestedFloor) {
floor.button.isActivated = true
elevatorController.elevatorQue.append(requestedFloor)
elevatorController.updateElevator()
}
}
func floorIsRequested(requestedFloor: Int) {
if isButtonInsideElevatorPressed(ofFloor: requestedFloor) {
floor.button.isActivated = true
elevatorController.elevatorQue.append(requestedFloor)
elevatorController.updateElevator()
}
}
}
|
//
// Image.swift
//
//
// Created by Artur Gurgul on 20/04/2016.
//
//
import Foundation
import CoreData
class Image: NSManagedObject {
func update(dictionary:NSDictionary, inContext context: NSManagedObjectContext) {
prefix = dictionary["prefix"] as? String
suffix = dictionary["suffix"] as? String
}
}
|
import XCTest
@testable import Polymorphic
class PolymorphicTests: XCTestCase {
static var allTests = [
("testInt", testInt),
("testUInt", testUInt),
("testArray", testArray),
("testObject", testObject),
("testFloat", testFloat),
("testDouble", testDouble),
("testNull", testNull),
("testBool", testBool),
("testDefaults", testDefaults),
]
func testInt() {
let poly = "-123"
XCTAssert(poly.int == -123)
XCTAssert(poly.uint == nil)
XCTAssert(poly.string == "-123")
}
func testUInt() {
let poly = UInt.max.description
XCTAssert(poly.uint == UInt.max)
XCTAssert(poly.int == nil)
}
func testArray() {
let list = "oranges, apples , bananas, grapes"
print(list.array)
let fruits = list.array?.flatMap { $0.string } ?? []
XCTAssert(fruits == ["oranges", "apples", "bananas", "grapes"])
}
func testObject() {
let obstr = "***"
XCTAssert(obstr.object == nil)
}
func testFloat() {
let poly = "3.14159"
XCTAssert(poly.float == 3.14159)
}
func testDouble() {
let poly = "999999.999"
XCTAssert(poly.double == 999_999.999)
}
func testNull() {
XCTAssert("null".isNull == true)
XCTAssert("NULL".isNull == true)
}
func testBool() {
XCTAssert("y".bool == true)
XCTAssert("yes".bool == true)
XCTAssert("t".bool == true)
XCTAssert("true".bool == true)
XCTAssert("1".bool == true)
XCTAssert("n".bool == false)
XCTAssert("no".bool == false)
XCTAssert("f".bool == false)
XCTAssert("false".bool == false)
XCTAssert("0".bool == false)
XCTAssert("nothing".bool == nil)
XCTAssert("to".bool == nil)
XCTAssert("see".bool == nil)
XCTAssert("here".bool == nil)
}
func testDefaults() {
struct Test: Polymorphic {
var int: Int?
var double: Double?
var isNull: Bool { return false }
var bool: Bool? { return nil }
var string: String? { return nil }
var array: [Polymorphic]? { return nil }
var object: [String : Polymorphic]? { return nil }
}
var a = Test(int: 42, double: 3.14159)
XCTAssertEqual(a.uint, 42)
XCTAssertEqual(a.float, 3.14159)
a.double = nil
XCTAssertEqual(a.float, nil)
let b = Test(int: nil, double: nil)
XCTAssert(b.uint == nil)
let c = Test(int: -123, double: nil)
XCTAssert(c.uint == nil)
}
}
|
//
// Router.swift
// desafio-ios-gabriel-leal
//
// Created by Gabriel Sousa on 04/04/20.
// Copyright © 2020 Gabriel Sousa. All rights reserved.
//
import UIKit
import Lottie
class Router {
static func pushCharacterDetailsViewController(viewModel: CharacterDetailsViewModel, navigationController: UINavigationController?) {
let vc = CharacterDetailsViewController(nibName: "CharacterDetailsXib", bundle: Bundle.main)
vc.viewModel = viewModel
navigationController?.pushViewController(vc, animated: true)
}
static func presentCharacterExpensiveComicViewController(viewModel: CharacterExpensiveComicViewModel, navigationController: UINavigationController?) {
let vc = CharacterExpensiveComicViewController(nibName: "CharacterExpensiveComicXib", bundle: Bundle.main)
vc.viewModel = viewModel
navigationController?.topViewController?.present(vc, animated: true)
}
static func showAlert(title: String, message: String, navigationController: UINavigationController?) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
navigationController?.topViewController?.present(alert, animated: true)
let okAction = UIAlertAction(title: "Ok", style: .default) { _ in
alert.dismiss(animated: true)
}
alert.addAction(okAction)
}
static func showErrorAlert(title: String, message: String, navigationController: UINavigationController?, alertAction: UIAlertAction) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
navigationController?.topViewController?.present(alert, animated: true)
alert.addAction(alertAction)
}
static func showLoading(navigationController: UINavigationController?) -> AnimationView {
let animationView = AnimationView(name: StaticStrings.kLoadingAnimationName)
animationView.frame = UIScreen.main.bounds
navigationController?.topViewController?.view.addSubview(animationView)
animationView.loopMode = .loop
animationView.play()
return animationView
}
}
|
//
// Screenshot.swift
// switui_learn
//
// Created by laijihua on 2020/10/26.
//
import SwiftUI
import Combine
import UIKit
import Photos
extension UIView {
var renderedImage: UIImage? {
// rect of capure
let rect = self.bounds
// create the context of bitmap
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
let context: CGContext = UIGraphicsGetCurrentContext()!
self.layer.render(in: context)
// get a image from current context bitmap
let capturedImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return capturedImage
}
}
extension View {
func takeScreenshot(origin: CGPoint, size: CGSize) -> UIImage? {
let window = UIWindow(frame: CGRect(origin: .zero, size: size))
let hosting = UIHostingController(rootView: self)
hosting.view.frame = CGRect(origin: origin, size: size)
window.addSubview(hosting.view)
window.makeKeyAndVisible()
return hosting.view.renderedImage
}
func saveImageToPhotoLibrary(image: UIImage?) {
guard let img = image else {
return
}
// 判断权限
switch PHPhotoLibrary.authorizationStatus() {
case .authorized:
saveImage(image: img)
case .notDetermined:
PHPhotoLibrary.requestAuthorization { (status) in
if status == .authorized {
saveImage(image: img)
} else {
print("User denied")
}
}
case .restricted, .denied:
if let url = URL.init(string: UIApplication.openSettingsURLString) {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
}
}
default:
break;
}
}
private func saveImage(image: UIImage) {
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAsset(from: image)
}, completionHandler: { (isSuccess, error) in
DispatchQueue.main.async {
if isSuccess {// 成功
print("Success")
}
}
})
}
}
|
//
// ASCAPICommunicationModel.swift
// DiscountAsciiWerehouse
//
// Created by Matheus Ruschel on 8/1/16.
// Copyright © 2016 Matheus Ruschel. All rights reserved.
//
import Foundation
typealias DataCallbackCompletionBlock = (() throws -> AnyObject?) -> Void
class ASCAPICommunicationModel {
var session: NSURLSession!
var cache: CustomCache<NSData>!
init() {
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
sessionConfig.timeoutIntervalForRequest = 15
session = NSURLSession(configuration: sessionConfig)
cache = CustomCache<NSData>.sharedInstance()
}
func fetchData(url:NSURL, completion:DataCallbackCompletionBlock) {
// cancels any request if there is on going requests before making a new one
self.cancelDataRequests()
// load from cache
if let cacheObject = self.cache?[url.absoluteString] {
let ndJsonParser = NDJSONParser(data:cacheObject.dataForCache())
if ndJsonParser == nil {
completion({throw Error.ErrorWithCode(errorCode: .NDJSONNotRecognizedError)})
} else {
completion({return ndJsonParser!.content })
}
} else {
self.fetchDataOnline(url,completion:completion)
}
}
func fetchDataOnline(url: NSURL, completion:DataCallbackCompletionBlock) {
let task = session.dataTaskWithURL(url) {
(data, response, error) in
if error == nil {
if let cache = self.cache {
cache[url.absoluteString] = data
}
if let ndJsonParser = NDJSONParser(data:data!) {
completion({return ndJsonParser.content })
} else {
completion({throw Error.ErrorWithCode(errorCode: .NDJSONNotRecognizedError)})
}
} else {
let error = ErrorHandler.handleErrorFromServer(error!.code)
switch error {
case .ErrorWithCode(let errorCode): if errorCode != .CanceledTask { fallthrough }
default: completion({ throw error})
}
}
}
task.resume()
}
func cancelDataRequests() {
if let session = session {
session.getTasksWithCompletionHandler() {
(dataTasks,_,downloadTasks) in
for task in dataTasks {
task.cancel()
}
}
}
}
}
|
//
// BandController.swift
// Acacia Ridge Presents the Band App
//
// Created by Alex Shillingford on 10/15/19.
// Copyright © 2019 Alex Shillingford. All rights reserved.
//
import Foundation
class BandController {
// MARK: - Properties
static var shared = BandController()
private(set) var employee = [EmployeeRepresentation]()
var currentBand: BandRepresentation?
private var persistentFileURL: URL? {
let fm = FileManager.default
guard let dir = fm.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil }
return dir.appendingPathExtension("employee.plist")
}
let baseURL = URL(string: "https://acaciaridgebandapp.firebaseio.com/")!
// MARK: - Networking Methods
func fetchBandInformationFromFirebase(employee: EmployeeRepresentation, completion: @escaping () -> Void = { }) {
let requestURL = baseURL.appendingPathExtension("json")
URLSession.shared.dataTask(with: requestURL) { (data, _, error) in
if let error = error {
NSLog("Error fetching information about band: \(error)")
}
guard let data = data else {
NSLog("No data returned from data task")
completion()
return
}
do {
var bandRepresentations = try JSONDecoder().decode([String: BandRepresentation].self, from: data).map({ $0.value })
for band in bandRepresentations {
if employee.bandID == band.id {
self.currentBand = band
bandRepresentations = []
} else {
continue
}
}
} catch {
}
}.resume()
}
// MARK: - CRUD Methods
@discardableResult func createEmployee(name: String,
position: Position,
email: String,
password: String,
id: UUID,
isAdministrator: Bool,
bandID: UUID) -> EmployeeRepresentation {
let employee = EmployeeRepresentation(name: name,
position: position.rawValue,
email: email,
password: password,
id: id,
isAdministrator: isAdministrator,
bandID: bandID)
let context = CoreDataStack.shared.mainContext
context.performAndWait {
CoreDataStack.shared.save()
}
return employee
}
// MARK: - Persistent Store Methods
func saveToPersistentStore() {
guard let url = persistentFileURL else { return }
do {
let data = try PropertyListEncoder().encode(employee)
try data.write(to: url)
} catch {
NSLog("Error saving employee data to native persistent store: \(error)")
}
}
func loadFromPersistentStore() {
let fm = FileManager.default
guard let url = persistentFileURL,
fm.fileExists(atPath: url.path) else { return }
do {
let data = try Data(contentsOf: url)
employee = try PropertyListDecoder().decode([EmployeeRepresentation].self, from: data)
} catch {
NSLog("Error loading employee data: \(error)")
}
}
}
|
//
// SeverManager.swift
// ServerT
//
// Created by xsj on 2021/2/9.
//
import UIKit
protocol ListenDelegate : class {
func listenStatus(startStatus: Bool,startContent: String)
}
class SeverManager: NSObject {
weak var delete: ListenDelegate?
fileprivate lazy var serverSocket : TCPServer = TCPServer(addr: "192.168.1.11", port: 7878)
fileprivate var isServerRunning : Bool = false
fileprivate lazy var clientMrgs : [ClientManager] = [ClientManager]()
}
extension SeverManager {
func startRunning() {
// 1.开启监听
let tuple = serverSocket.listen()
if let startStatus = Optional(tuple.0) {
print("端口监听成功 \(startStatus)")
}else{
print("端口监听失败 \(tuple.1)")
}
guard tuple.0 else {
return
}
isServerRunning = true
// 2.开始接受客户端
DispatchQueue.global().async {
while self.isServerRunning{
if let client = self.serverSocket.accept() {
DispatchQueue.global().async {
print("接收到一个客户端")
self.handlerClient(client)
}
}
}
}
}
func stopRunning() {
isServerRunning = false
}
}
extension SeverManager {
fileprivate func handlerClient(_ client: TCPClient){
//1.用一个ClientManager管理TCPClient
let mgr = ClientManager(tcpClient: client)
//2.保存客户端
clientMrgs.append(mgr)
//3.用client开始接受消息
mgr.startReadMsg()
mgr.delete = self
}
}
extension SeverManager : ClientManagerDelete {
func sendMsgToClient(data: Data) {
for mgr in clientMrgs {
mgr.tcpClient.send(data: data)
}
}
func removeClient(client: ClientManager) {
guard let index = clientMrgs.firstIndex(of: client) else { return }
clientMrgs.remove(at: index)
}
}
|
//
// RootView.swift
// DesignCode
//
// Created by Alex Ochigov on 8/13/20.
// Copyright © 2020 Alex Ochigov. All rights reserved.
//
import SwiftUI
struct RootView: View {
var body: some View {
TabView {
HomeScreen().tabItem {
Image(systemName: "play.circle.fill")
Text("Home ")
}
CertificatesScreen().tabItem {
Image(systemName: "rectangle.stack.fill")
Text("Certificates")
}
}
}
}
struct RootView_Previews: PreviewProvider {
static var previews: some View {
RootView()
}
}
|
//
// TMRecommendation.swift
// consumer
//
// Created by Vladislav Zagorodnyuk on 2/3/16.
// Copyright © 2016 Human Ventures Co. All rights reserved.
//
import CoreStore
import SwiftyJSON
/// Struct that represent Recommendation JSON keys
public struct TMRecommendationJSON {
static let requestID = "request_id"
static let seen = "seen"
static let status = "status"
static let userID = "user_id"
static let published = "published"
static let items = "items"
static let images = "images"
}
@objc(TMRecommendation)
open class TMRecommendation: _TMRecommendation {
// Get Array of JSON items
var arrayOfJSONItems: [[String: Any]]? {
var resultArray = [[String: Any]]()
for item in itemsArray {
resultArray.append(item.transformToJSON())
}
return resultArray
}
/// Not removed items
var notRemovedItems: [TMItem] {
return itemsArray.filter { $0.feedbackType != .remove }
}
// Selected item
var selectedItem: TMItem?
var itemsArray: [TMItem] {
return self.items.array as! [TMItem]
}
override func updateModel(with source: JSON, transaction: BaseDataTransaction) throws {
try super.updateModel(with: source, transaction: transaction)
// Request ID
self.requestID = source[TMRecommendationJSON.requestID].string
// Seen
self.seen = source[TMRecommendationJSON.seen].number ?? false
// Status
self.statusString = source[TMRecommendationJSON.status].string
// User ID
self.userID = source[TMRecommendationJSON.userID].string
// Published
self.published = source[TMRecommendationJSON.published].number
// Fetch Items
let itemsJSONArray = source[TMRecommendationJSON.items].array ?? []
let tempItems = try transaction.importUniqueObjects(Into<TMItem>(), sourceArray: itemsJSONArray)
self.addItems(NSOrderedSet(array: tempItems))
// Fetch Images
let imagesJSONArray = source[TMRecommendationJSON.images].array ?? []
let tempImages = try transaction.importUniqueObjects(Into<TMImage>(), sourceArray: imagesJSONArray)
self.addImages(NSOrderedSet(array: tempImages))
}
}
|
//
// NewFollowViewController.swift
// Yeah_SalesExpert
//
// Created by DavisChing on 16/5/21.
// Copyright © 2016年 DavisChing. All rights reserved.
//
import UIKit
class NewFollowViewController: UIViewController {
@IBAction func bt_tap(sender: AnyObject) {
tf.resignFirstResponder()
}
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var tf: UITextView!
@IBAction func bt_Add(sender: AnyObject) {
if tf.text == "" {
} else {
let today:NSDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY"
let year = Int(dateFormatter.stringFromDate(today))
dateFormatter.dateFormat = "MM"
let month = Int(dateFormatter.stringFromDate(today))
dateFormatter.dateFormat = "dd"
let day = Int(dateFormatter.stringFromDate(today))
if DataReader.isCreatingFollowFromClient == true {
DataReader.getCurrentClient().appendList(Check.init(YY: year!, MM: month!, DD: day!, _context: tf.text, _userId: DataReader.getCurrentUser().getId()))
DataReader.modifyClient(DataReader.getCurrentClient())
DataReader.isCreatingFollowFromClient = false
} else {
DataReader.getCurrentOppo().appendList(Check.init(YY: year!, MM: month!, DD: day!, _context: tf.text, _userId : DataReader.getCurrentUser().getId()))
DataReader.modifyOppo( DataReader.getCurrentOppo())
let client = DataReader.getClientWithId(DataReader.getCurrentOppo().getClientId())
client.appendList(Check.init(YY: year!, MM: month!, DD: day!, _context: tf.text, _userId : DataReader.getCurrentUser().getId()))
DataReader.modifyClient(client)
}
DataReader.isCreatingFollowFromClient = false
self.navigationController?.popViewControllerAnimated(true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "新增跟进纪录"
transAll()
scrollView.contentSize = CGSize.init(width: UIScreen.mainScreen().bounds.size.width, height: scrollView.frame.height * DataReader.getAwayNaviBarDIVIDEscreen(UIScreen.mainScreen().bounds.size.width))
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
self.tabBarController?.tabBar.hidden = true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
private func transAll(){
trans(scrollView)
}
//Turn one view and all its subviews into suitable size
private func trans(temp : UIView){
temp.frame = remakeFrame(temp.frame.origin.x, y: temp.frame.origin.y, width: temp.frame.size.width, height: temp.frame.size.height)
if(temp.subviews.count != 0){
for i in temp.subviews{
trans(i)
}
}
}
let transX = UIScreen.mainScreen().bounds.size.width / 375
let transY = UIScreen.mainScreen().bounds.size.height / 667
//Turn one view into suitable size
private func remakeFrame(x : CGFloat, y : CGFloat, width : CGFloat, height : CGFloat) -> CGRect{
var rect = CGRect.init()
if(rect.origin.x < 0){
}else{
rect.origin.x = x * transX
}
rect.origin.y = y * transY
rect.size.width = width * transX
rect.size.height = height * transY
return rect
}
}
|
//
// UILabelExpand.swift
// FlagQuiz
//
// Created by Soohan Lee on 2019/10/28.
// Copyright © 2019 이수한. All rights reserved.
//
import Foundation
import UIKit
extension UILabel {
func textWidth() -> CGFloat {
return UILabel.textWidth(label: self)
}
class func textWidth(label: UILabel) -> CGFloat {
return textWidth(label: label, text: label.text!)
}
class func textWidth(label: UILabel, text: String) -> CGFloat {
return textWidth(font: label.font, text: text)
}
class func textWidth(font: UIFont, text: String) -> CGFloat {
let myText = text as NSString
let rect = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
let labelSize = myText.boundingRect(with: rect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
return ceil(labelSize.width)
}
}
|
//
// ProjectDetail.swift
// Epintra
//
// Created by Maxime Junger on 30/01/16.
// Copyright © 2016 Maxime Junger. All rights reserved.
//
import Foundation
import SwiftyJSON
class ProjectDetail: Project {
// var explanations: String?
// var userProjectStatus: String?
// var note: String?
// var userProjectCode: String?
// var userProjectTitle: String?
// var registeredGroups: [ProjectGroup]?
// var projectStatus: String?
// var files: [File]?
//
// override init(dict: JSON) {
// super.init(dict: dict)
//
// explanations = dict["description"].stringValue
// userProjectStatus = dict["user_project_status"].stringValue
// note = dict["note"].stringValue
// userProjectCode = dict["user_project_code"].stringValue
// userProjectTitle = dict["user_project_title"].stringValue
// begin = dict["begin"].stringValue
// end = dict["end"].stringValue
// actiTitle = dict["title"].stringValue
// registered = dict["instance_registered"].boolValue
// projectStatus = dict["user_project_status"].stringValue
// fillProjectGroups(dict["registered"])
// }
//
// func fillProjectGroups(_ dict: JSON) {
// registeredGroups = [ProjectGroup]()
// let arr = dict.arrayValue
// print(arr.count)
// for tmp in arr {
// registeredGroups?.append(ProjectGroup(dict: tmp))
// }
// }
//
// func findGroup(_ code: String) -> ProjectGroup? {
// var res: ProjectGroup?
// for tmp in registeredGroups! {
// if (tmp.code == code) {
// res = tmp
// break
// }
// }
//
// return res
// }
//
// func isRegistered() -> Bool {
// if (projectStatus == "project_confirmed") {
// return true
// }
// return false
// }
}
|
//
// ChannelListViewController.swift
// Douban-Demo
//
// Created by xzysun on 14-7-30.
// Copyright (c) 2014年 AnyApps. All rights reserved.
//
import UIKit
//定义一个切换频道的block,传入一个Int代表频道号,一个String代表频道名称
typealias ChangeChannelBlock = (Int, String) -> Void
class ChannelListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var changeChannel:ChangeChannelBlock?;
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
var failure:failureBlock = {
(resultStr:String) -> Void in
let alert:UIAlertView = UIAlertView(title: "错误", message: resultStr, delegate: nil, cancelButtonTitle: "确定");
alert.show();
};
var success:successBlock = {
self.tableView.reloadData();
};
DoubanService.getService().reloadChannelList(success, failure:failure);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backButtonAction(sender: AnyObject) {
NSLog("取消频道列表");
self.dismissViewControllerAnimated(true, completion: nil);
}
//datasource
func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
return 1;
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
var listCount = DoubanService.getService().channelList.count;
if(listCount == 0) {
return 1;
} else {
return listCount;
}
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell:UITableViewCell! = tableView.dequeueReusableCellWithIdentifier("Douban-channel") as? UITableViewCell;
if(cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Douban-channel");
}
//填充数据
var listCount = DoubanService.getService().channelList.count;
if(listCount == 0) {
cell.textLabel.text = "正在加载...";
} else {
let rowData:NSDictionary=DoubanService.getService().channelList[indexPath.row] as NSDictionary
cell.textLabel.text = rowData["name"] as String;
if(rowData["channel_id"].isEqual(DoubanService.getService().currentChannel)) {
cell.accessoryType = UITableViewCellAccessoryType.Checkmark;
} else {
cell.accessoryType = UITableViewCellAccessoryType.None;
}
}
return cell;
}
//delegate
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
tableView.deselectRowAtIndexPath(indexPath, animated: true);
if(DoubanService.getService().channelList.count == 0) {
//点击的是正在加载...
return;
}
NSLog("选择了%d", indexPath.row);
let rowData:NSDictionary=DoubanService.getService().channelList[indexPath.row] as NSDictionary;
var channel = rowData["channel_id"]as String;
DoubanService.getService().currentChannel = channel;
if let existedBlock = self.changeChannel {
self.changeChannel!(indexPath.row,"");
}
self.dismissViewControllerAnimated(true, completion: nil);
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// ForecastCell.swift
// weather
//
// Created by Baldoph Pourprix on 30/03/2016.
// Copyright © 2016 Baldoph Pourprix. All rights reserved.
//
import UIKit
import WeatherKit
import SwiftDate
private let weekdayFormatter: NSDateFormatter = {
var df = NSDateFormatter()
df.dateFormat = "EEEE"
return df
}()
class ForecastCell: UITableViewCell {
@IBOutlet weak var maxTempLabel: UILabel!
@IBOutlet weak var minTempLabel: UILabel!
@IBOutlet weak var dayLabel: UILabel!
var forecast: DayForecast? {
didSet {
if let forecast = forecast {
dayLabel.text = weekdayFormatter.stringFromDate(forecast.date)
maxTempLabel.text = forecast.temperatureMax.toString()
minTempLabel.text = forecast.temperatureMin.toString()
today = forecast.date.isInToday()
} else {
dayLabel.text = ""
maxTempLabel.text = "-"
minTempLabel.text = "-"
today = false
}
}
}
private var allLabels: [UILabel] {
return [maxTempLabel, minTempLabel, dayLabel]
}
var today: Bool = false {
didSet {
if oldValue == today {
return
}
for label in allLabels {
if today {
label.font = UIFont.boldSystemFontOfSize(label.font.pointSize)
} else {
label.font = UIFont.systemFontOfSize(label.font.pointSize)
}
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
selectionStyle = .None
}
}
|
//
// QuestionViewController.swift
// Movement
//
// Created by Zara Perumal on 11/11/15.
// Copyright © 2015 Parse. All rights reserved.
//
import Foundation
import UIKit
import Parse
class TextFieldQuestionTableViewCell : UITableViewCell, UITextViewDelegate {
var placeholder = "Enter answer here"
@IBOutlet var questionLabel : UILabel!
@IBOutlet var answerField : UITextView!
@IBOutlet var submitButton : UIButton!
@IBOutlet weak var skipButton: UIButton!
func loadItem( question: String, cell : Int) {
questionLabel.text = question
questionLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
questionLabel.numberOfLines = 2
questionLabel.sizeToFit()
submitButton.tag = 99 + (100 * cell)
skipButton.tag = 99 + (100 * cell)
//self.reloadInputViews()
answerField.delegate = self
answerField.text = placeholder
answerField.textColor = UIColor.lightGrayColor()
}
@IBAction func submit(){
}
func textViewShouldBeginEditing(textView: UITextView) -> Bool {
answerField.textColor = UIColor.blackColor()
if answerField.text == placeholder {
answerField.text = ""
}
return true
}
func textViewDidEndEditing(textView: UITextView) {
if(answerField.text == "") {
self.answerField.text = placeholder
self.answerField.textColor = UIColor.lightGrayColor()
}
}
}
class ButtonQuestionTableViewCell : UITableViewCell {
@IBOutlet var questionLabel : UILabel!
@IBOutlet var button1 : UIButton!
@IBOutlet var button2 : UIButton!
@IBOutlet var button3 : UIButton!
@IBOutlet var button4 : UIButton!
@IBOutlet var button5 : UIButton!
@IBOutlet var skipButton : UIButton!
func loadItem( question: String , buttonText : [String] , cell : Int) {
var buttons = [button1,button2,button3,button4,button5,skipButton]
questionLabel.text = question
questionLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
questionLabel.numberOfLines = 2
questionLabel.sizeToFit()
for j in 0...buttons.count-1 {
buttons[j].setTitle(" ", forState: UIControlState.Normal)
}
for i in 0...buttonText.count-1 {
buttons[i].setTitle(buttonText[i], forState: UIControlState.Normal)
buttons[i].tag = i + (100 * cell)
buttons[i].enabled = true
}
skipButton.enabled = true
skipButton.hidden = false
self.reloadInputViews()
}
}
class QuestionViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableView: UITableView!
// var questions : [Question] = [Question(questionText : "test1", buttons: []), Question(questionText : "test2", buttons: []) , Question(questionText : "test2", buttons: ["button 1" , "button 2"])]
var questions : [Question] = []
override func viewDidLoad() {
var nib = UINib(nibName: "TextFieldQuestionTableViewCell", bundle: nil)
var nib2 = UINib(nibName: "ButtonQuestionTableViewCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "TextFieldQuestionTableViewCell")
tableView.registerNib(nib2, forCellReuseIdentifier: "ButtonQuestionTableViewCell")
getQuestions()
// tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
var swipe: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "dismissKeyboard")
swipe.direction = UISwipeGestureRecognizerDirection.Down
self.view.addGestureRecognizer(swipe)
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.view.endEditing(true)
}
func dismissKeyboard() {
// self.view.endEditing(true)
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var q : Question = questions[indexPath.row]
if (q.buttons.count == 0 ){
var cell:TextFieldQuestionTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("TextFieldQuestionTableViewCell") as! TextFieldQuestionTableViewCell
cell.submitButton.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
cell.skipButton.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
// this is how you extract values from a tuple
cell.loadItem(q.questionText,cell: indexPath.row)
return cell
}else{
var cell:ButtonQuestionTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("ButtonQuestionTableViewCell") as! ButtonQuestionTableViewCell
cell.button1.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
cell.button2.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
cell.button3.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
cell.button4.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
cell.button5.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
cell.skipButton.addTarget(self, action: "buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
cell.loadItem(q.questionText, buttonText: q.buttons , cell: indexPath.row )
return cell
}
}
func buttonPressed( sender : UIButton) {
var response = PFObject(className:"Response")
var tag = sender.tag
var buttonIndex : Int = tag%100
var rowIndex : Int = (tag - buttonIndex) / 100
if sender.titleLabel?.text == "Skip" {
questions.removeAtIndex(rowIndex)
tableView.reloadData()
if questions.count == 0{
//getQuestions()
questionsAnswererd(self)
}
return
}
var question = questions[rowIndex]
// question.questionText
var responseText : String
if buttonIndex == -1 || buttonIndex == 99 {
var cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: rowIndex, inSection: 0)) as! TextFieldQuestionTableViewCell
responseText = cell.answerField.text
print (question)
print(responseText)
}else{
responseText = question.buttons[buttonIndex]
}
response["questionText"] = question.questionText
response["responseText"] = responseText
response["user"] = PFUser.currentUser()
response.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
print("Object Saved")
} else {
print("ERROR: save error")
}
}
questions.removeAtIndex(rowIndex)
if questions.count == 0{
//getQuestions()
questionsAnswererd(self)
}
tableView.reloadData()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
print("You selected cell #\(indexPath.row)!")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return questions.count
}
func getQuestions(){
let query = PFQuery(className:"Question")
query.whereKey("active", equalTo: true)
var lastQuestion = PFUser.currentUser()!.valueForKey("lastQuestion")
if lastQuestion == nil {
lastQuestion = 0
}
/*
var answerKeys = ["AnswerA","AnswerB","AnswerC","AnswerD","AnswerE"]
var answers : [String] = []
for a in answerKeys {
//var answer = object[a] as! String
var answer : String = object.objectForKey(a) as! String
if answer != "" {
answers += [answer]
}
}
self.questions += [Question(questionText : question, buttons: answers)]
*/
query.findObjectsInBackgroundWithBlock {
(objects:[PFObject]?, error:NSError?) -> Void in
if error == nil {
//self.questions = []
// The find succeeded.
print("Successfully retrieved \(objects!.count) scores.")
// Do something with the found objects
if let objects = objects {
for object in objects {
let questionObj = object.objectForKey("Question")
if questionObj != nil {
let question = questionObj as! String
var answerKeys = ["AnswerA","AnswerB","AnswerC","AnswerD","AnswerE"]
var answers : [String] = []
for a in answerKeys {
//var answer = object[a] as! String
var answerobj = object.objectForKey(a)
if answerobj != nil {
var answer : String = answerobj as! String
if answer != "" {
answers += [answer]
}
}
}
self.questions += [Question(questionText : question, buttons: answers)]
self.tableView.reloadData()
}
}
}
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
}
func questionsAnswererd(sender: AnyObject) {
let alertController = UIAlertController(title: "All questions answered!", message:
"Thanks!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: {
self.performSegueWithIdentifier("questionToHome", sender: self)
})
}
}
|
//
// SingleEntryViewController.swift
// Travelogue
//
// Created by Melissa Hollingshed on 4/29/19.
// Copyright © 2019 Melissa Hollingshed. All rights reserved.
//
import UIKit
class SingleEntryViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var dateFormatter = DateFormatter()
let imagePicker = UIImagePickerController()
var entry : Entry?
var trip : Trip?
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var descriptionTextView: UITextView!
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
//print(trip)
imagePicker.delegate = self
// Do any additional setup after loading the view.
dateFormatter.timeStyle = .long
dateFormatter.dateStyle = .long
dateFormatter.dateFormat = "EEEE, MMM d yyyy h:mm a"
//EEEE,MMM d yyyy h:mm a
if let entry = entry{
titleTextField.text = entry.entryTitle
descriptionTextView.text = entry.text
dateLabel.text = "Date: \(dateFormatter.string(from: ((entry.date ?? nil) ?? nil)!))"
imageView.image = entry.image ?? nil
}
}
override func viewWillAppear(_ animated: Bool) {
imagePicker.delegate = self
}
@IBAction func saveButtonPressed(_ sender: Any) {
if entry == nil {//new entry
let title = titleTextField.text ?? ""
let text = descriptionTextView.text ?? ""
let date = Date(timeIntervalSinceNow: 0)
let photo = imageView.image
if let entry = Entry(entryTitle: title, text: text, date: date, image: photo){
print("Entry exists")
if let trip = trip {
print("adding entry")
trip.addToRawEntries(entry)
}
// trip?.addToRawEntries(entry)
do{
try entry.managedObjectContext?.save()
self.navigationController?.popViewController(animated: true)
}catch{
print("entry could not be saved")
}
print("Entry should be saved")
}
}else{//update
print("updating")
let title = titleTextField.text ?? ""
let text = descriptionTextView.text ?? ""
let date = Date(timeIntervalSinceNow: 0)
let photo = imageView.image
//print(photo)
entry?.update(entryTitle: title, text: text, date: date, image: photo)
do{
let managedContext = entry?.managedObjectContext
try managedContext?.save()
}catch{
print("The entry could not be saved")
}
self.navigationController?.popViewController(animated: true)
}
}
@IBAction func takePhoto(_ sender: Any) {
if (!UIImagePickerController.isSourceTypeAvailable(.camera)) {
let alertController = UIAlertController(title: "No Camera", message: "The devide does not have a camera", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
} else {
imagePicker.sourceType = .camera
present(imagePicker, animated: true, completion: nil)
}
}
@IBAction func getExistingPhoto(_ sender: Any) {
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true, completion: nil)
}
@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
print("image view must be bad")
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
print("setting imageview")
imageView.image = image
} else {
print("not setting imageview image")
}
dismiss(animated: true, completion: nil)
}
}
|
//
// calendarSeekerClass.swift
// WorkingBeez
//
// Created by Brainstorm on 3/9/17.
// Copyright © 2017 Brainstorm. All rights reserved.
//
import UIKit
class calendarSeekerClass: UIViewController,FSCalendarDataSource, FSCalendarDelegate, FSCalendarDelegateAppearance, UITableViewDataSource, UITableViewDelegate
{
var bottomView : UIView!
@IBOutlet weak var btnCal: UIButton!
private weak var calendar: FSCalendar!
var activeCell : FSCalendarCell = FSCalendarCell()
var activeDate : Date = Date()
var tblCalendarJob : UITableView!
var isAccepted: Bool = true
var selectedDate: String = ""
var selectedMonth: Int = 0
var selectedYear: Int = 0
var arrOfDateOnly: NSMutableArray = NSMutableArray()
var arrOfCalender: NSMutableArray = NSMutableArray()
var arrOfCalenderDetail: NSMutableArray = NSMutableArray()
let fillDefaultColors = ["09/03/2017": "1", "25/03/2017": "2"]
var contentMsg: ContentMessageView!
let custObj: customClassViewController = customClassViewController()
//MARK:- View Cycle
override func viewDidLoad()
{
super.viewDidLoad()
contentMsg = ContentMessageView.CreateView(self.view, strMessage: "No records found", strImageName: "WB_Font", color: UIColor.lightGray)
contentMsg.isHidden = true
btnCal.isHidden = true
self.navigationController?.isNavigationBarHidden = false
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: API.blackColor(), NSFontAttributeName: UIFont(name: font_openSans_regular, size: 14)!]
self.navigationController?.navigationBar.tintColor = UIColor.black
self.navigationController?.navigationBar.barTintColor = API.NavigationbarColor()
let df: DateFormatter = DateFormatter()
df.dateFormat = "M"
var strM: String = df.string(from: Date())
selectedMonth = Int(strM)!
df.dateFormat = "yyyy"
strM = df.string(from: Date())
selectedYear = Int(strM)!
getCalender()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
override func loadView()
{
let view = UIView(frame: UIScreen.main.bounds)
view.frame = CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
view.backgroundColor = API.appBackgroundColor()
self.view = view
let calendar = FSCalendar(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height - 64))
bottomView = UIView.init(frame: CGRect.init(x: 0, y: calendar.frame.origin.y + calendar.frame.size.height, width: self.view.bounds.width, height: 0))
bottomView.backgroundColor = UIColor.clear
bottomView.clipsToBounds = true
let imgBlue : UILabel = UILabel.init(frame: CGRect.init(x: 20, y: 15, width: 20, height: 20))
imgBlue.backgroundColor = API.themeColorBlue()
imgBlue.layer.cornerRadius = imgBlue.frame.size.width / 2
imgBlue.clipsToBounds = true
imgBlue.text = ""
bottomView.addSubview(imgBlue)
let imgBlueText : UILabel = UILabel.init(frame: CGRect.init(x: imgBlue.frame.size.width + imgBlue.frame.origin.x + 10, y: 15, width: 100, height: 20))
imgBlueText.backgroundColor = UIColor.clear
imgBlueText.text = "Completed Job"
imgBlueText.font = UIFont.init(name: "OpenSans", size: 14)
bottomView.addSubview(imgBlueText)
let imgPink : UILabel = UILabel.init(frame: CGRect.init(x: imgBlueText.frame.size.width + imgBlueText.frame.origin.x + 20, y: 15, width: 20, height: 20))
imgPink.backgroundColor = API.themeColorPink()
imgPink.layer.cornerRadius = imgPink.frame.size.width / 2
imgPink.clipsToBounds = true
imgPink.text = ""
bottomView.addSubview(imgPink)
let imgPinkText : UILabel = UILabel.init(frame: CGRect.init(x: imgPink.frame.size.width + imgPink.frame.origin.x + 10, y: 15, width: 100, height: 20))
imgPinkText.backgroundColor = UIColor.clear
imgPinkText.text = "Accepted Job"
imgPinkText.font = UIFont.init(name: "OpenSans", size: 14)
bottomView.addSubview(imgPinkText)
self.view.addSubview(bottomView)
tblCalendarJob = UITableView(frame: CGRect.init(x: 7, y: bottomView.frame.size.height + bottomView.frame.origin.y + 8, width: self.view.bounds.width - 14, height: 0), style: UITableViewStyle.plain)
tblCalendarJob.register(UINib(nibName: "cellAcceptedWithRepeat", bundle: nil), forCellReuseIdentifier: "cellAcceptedWithRepeat")
tblCalendarJob.register(UINib(nibName: "cellAcceptedNoRepeat", bundle: nil), forCellReuseIdentifier: "cellAcceptedNoRepeat")
tblCalendarJob.backgroundColor = UIColor.clear
self.view.addSubview(tblCalendarJob)
tblCalendarJob.dataSource = self
tblCalendarJob.delegate = self
tblCalendarJob.separatorStyle = UITableViewCellSeparatorStyle.none
tblCalendarJob.reloadData()
calendar.dataSource = self
calendar.delegate = self
calendar.calendarHeaderView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.1)
calendar.calendarWeekdayView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.1)
calendar.register(FSCalendarCell.self, forCellReuseIdentifier: "cell")
calendar.appearance.todayColor = UIColor.clear
calendar.appearance.titleTodayColor = UIColor.black
calendar.appearance.selectionColor = UIColor.clear
calendar.appearance.titleSelectionColor = UIColor.black
calendar.appearance.eventDefaultColor = API.onlineColor()
calendar.allowsMultipleSelection = false
calendar.appearance.headerTitleColor = UIColor.darkGray
calendar.appearance.weekdayTextColor = API.themeColorPink()
calendar.appearance.titleFont = UIFont.init(name: "OpenSans", size: 14)
calendar.appearance.headerTitleFont = UIFont.init(name: "OpenSans", size: 16)
calendar.appearance.weekdayFont = UIFont.init(name: "OpenSans", size: 15)
calendar.appearance.titleSelectionColor = UIColor.white
calendar.appearance.titleOffset = CGPoint.init(x: 0, y: 5)
self.calendar = calendar
self.view.addSubview(calendar)
self.calendar.setScope(.month, animated: false)
}
func calendar(_ calendar: FSCalendar, boundingRectWillChange bounds: CGRect, animated: Bool)
{
self.calendar.frame = CGRect.init(x: calendar.frame.origin.x, y: calendar.frame.origin.y, width: calendar.frame.size.width, height: bounds.size.height)
bottomView.frame = CGRect.init(x: 0, y: calendar.frame.origin.y + calendar.frame.size.height, width: self.view.bounds.width, height: 0)
tblCalendarJob.frame = CGRect.init(x: 8, y: bottomView.frame.origin.y + bottomView.frame.size.height + 8, width: self.view.bounds.width - 16, height: self.view.frame.size.height - (bottomView.frame.origin.y + bottomView.frame.size.height) - 8)
self.view.layoutIfNeeded()
}
//MARK:- calendar View Delgate
func calendar(_ calendar: FSCalendar, cellFor date: Date, at position: FSCalendarMonthPosition) -> FSCalendarCell
{
let cell = calendar.dequeueReusableCell(withIdentifier: "cell", for: date, at: position)
cell.titleLabel.center = cell.center
cell.titleLabel.backgroundColor = UIColor.clear
cell.subtitleLabel.isHidden = false
return cell
}
func calendarCurrentMonthDidChange(_ calendar: FSCalendar)
{
print(calendar.currentPage)
let df: DateFormatter = DateFormatter()
df.dateFormat = "M"
var strM: String = df.string(from: calendar.currentPage)
selectedMonth = Int(strM)!
df.dateFormat = "yyyy"
strM = df.string(from: calendar.currentPage)
selectedYear = Int(strM)!
getCalender()
}
func calendar(_ calendar: FSCalendar, subtitleFor date: Date) -> String?
{
return ""
}
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition)
{
selectedDate = self.dateFormatter1.string(from: date)
calendar.appearance.selectionColor = UIColor.clear
calendar.appearance.titleSelectionColor = UIColor.black
calendar.appearance.eventSelectionColor = API.onlineColor()
let key: String = self.dateFormatter1.string(from: date)
if arrOfDateOnly.contains(key)
{
let index: Int = arrOfDateOnly.index(of: key)
let dd: NSDictionary = arrOfCalender.object(at: index) as! NSDictionary
if dd.object(forKey: "IsCompleted") as! Bool == true && dd.object(forKey: "IsAccepeted") as! Bool == true
{
calendar.appearance.titleSelectionColor = UIColor.white
calendar.appearance.selectionColor = API.blackColor()
isAccepted = false
}
else if dd.object(forKey: "IsCompleted") as! Bool == true
{
calendar.appearance.titleSelectionColor = UIColor.white
calendar.appearance.selectionColor = API.themeColorBlue()
isAccepted = false
}
else if dd.object(forKey: "IsAccepeted") as! Bool == true
{
calendar.appearance.titleSelectionColor = UIColor.white
calendar.appearance.selectionColor = API.themeColorPink()
isAccepted = true
}
}
if(self.calendar.scope == .month)
{
self.calendar.setScope(.week, animated: true)
btnCal.isHidden = false
}
getCalenderDetail()
print(calendar.frame)
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle
{
return UIModalPresentationStyle.none
}
var datesWithEvent:[NSDate] = []
func calendar(_ calendar: FSCalendar, hasEventFor date: Date) -> Bool
{
return datesWithEvent.contains(Date() as NSDate)
}
func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int
{
let df : DateFormatter = DateFormatter()
let ddd : Date = Date()
df.dateFormat = "yyyy-MM-dd"
let strDate : String = df.string(from: ddd)
let dd : Date = df.date(from: strDate)!
if(dd.compare(date) == ComparisonResult.orderedSame)
{
return 1
}
return 0
}
func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, fillDefaultColorFor date: Date) -> UIColor?
{
let key: String = self.dateFormatter1.string(from: date)
/*{
Date = "7/4/2017";
DayOfWeek = 5;
IsAccepeted = 0;
IsCompleted = 1;
}*/
if arrOfDateOnly.contains(key)
{
let index: Int = arrOfDateOnly.index(of: key)
let dd: NSDictionary = arrOfCalender.object(at: index) as! NSDictionary
if dd.object(forKey: "IsCompleted") as! Bool == true && dd.object(forKey: "IsAccepeted") as! Bool == true
{
return API.blackColor()
}
else if dd.object(forKey: "IsCompleted") as! Bool == true
{
return API.themeColorBlue()
}
else if dd.object(forKey: "IsAccepeted") as! Bool == true
{
return API.themeColorPink()
}
}
return nil
// if let color = self.fillDefaultColors[key]
// {
// if(color == "1")
// {
// return API.themeColorPink()
// }
// else
// {
// return API.themeColorBlue()
// }
// }
// return nil
}
func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, titleDefaultColorFor date: Date) -> UIColor?
{
// let key = self.dateFormatter1.string(from: date)
// if let color = self.fillDefaultColors[key]
// {
// return UIColor.white
// }
let key: String = self.dateFormatter1.string(from: date)
/*{
Date = "7/4/2017";
DayOfWeek = 5;
IsAccepeted = 0;
IsCompleted = 1;
}*/
if arrOfDateOnly.contains(key)
{
return UIColor.white
}
return nil
}
fileprivate lazy var dateFormatter1: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "d/M/yyyy"
return formatter
}()
@IBAction func btnCancelJob(_ sender: Any)
{
let uiAlert = UIAlertController(title: ABORT_JOB_MESSAGE, message: RATING_INFO, preferredStyle: UIAlertControllerStyle.alert)
uiAlert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { action in
let obj: abortJobClass = self.storyboard?.instantiateViewController(withIdentifier: "abortJobClass") as! abortJobClass
obj.objCalAccepted = self
obj.fromWhere = "CalenderAccepted"
self.present(obj, animated: true, completion: nil)
}))
uiAlert.addAction(UIAlertAction(title: "No", style: .cancel, handler: { action in
}))
self.present(uiAlert, animated: true, completion: nil)
}
//MARK:- tableView delegate
//MARK:- tableView delegate
private func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return arrOfCalenderDetail.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cellAcceptedNoRepeat", for: indexPath as IndexPath) as! cellAcceptedNoRepeat
let dd: NSDictionary = arrOfCalenderDetail.object(at: indexPath.row) as! NSDictionary
if dd.object(forKey: "StatusID") as! Int == 4
{
cell.lblCompleted.isHidden = true
cell.lblRosterTimePeriod.text = dd.object(forKey: "JobTimePeriod") as? String
cell.lblRosterTotalPayment.text = String(format: "%@/hr", dd.object(forKey: "HourlyRate") as! String)
}
else
{
cell.lblCompleted.isHidden = false
cell.lblCompleted.text = dd.object(forKey: "Status") as? String
cell.lblRosterTimePeriod.text = ""
cell.lblRosterTotalPayment.text = String(format: "%@", dd.object(forKey: "HourlyRate") as! String)
}
cell.imgWatchIcon.tintColor = API.themeColorPink()
cell.lblJobId.isHidden = false
cell.lblJobId.text = String(format: "Job ID: %d", dd.object(forKey: "JobPostID") as! Int)
if dd.object(forKey: "IsRepete") as! Bool == false
{
cell.lblRosterDate.text = API.convertDateToString(strDate: dd.object(forKey: "FromDate") as! String, fromFormat: "dd/MM/yyyy", toFormat: "dd MMM yyyy")
cell.lblRosterRepeatStatus.isHidden = false
cell.viewDays.isHidden = true
}
else
{
cell.lblRosterRepeatStatus.isHidden = true
cell.viewDays.isHidden = false
cell.lblRosterDate.text = API.convertDateToString(strDate: dd.object(forKey: "FromDate") as! String, fromFormat: "dd/MM/yyyy", toFormat: "dd MMM yyyy")
let strDays: String = dd.object(forKey: "DayOfWeekIDs") as! String
if strDays.contains("1")
{
cell.btnMon.backgroundColor = API.themeColorBlue()
cell.btnMon.isSelected = true
}
else
{
cell.btnMon.backgroundColor = UIColor.white
cell.btnMon.isSelected = false
}
if strDays.contains("2")
{
cell.btnTue.backgroundColor = API.themeColorBlue()
cell.btnTue.isSelected = true
}
else
{
cell.btnTue.backgroundColor = UIColor.white
cell.btnTue.isSelected = false
}
if strDays.contains("3")
{
cell.btnWed.backgroundColor = API.themeColorBlue()
cell.btnWed.isSelected = true
}
else
{
cell.btnWed.backgroundColor = UIColor.white
cell.btnWed.isSelected = false
}
if strDays.contains("4")
{
cell.btnThu.backgroundColor = API.themeColorBlue()
cell.btnThu.isSelected = true
}
else
{
cell.btnThu.backgroundColor = UIColor.white
cell.btnThu.isSelected = false
}
if strDays.contains("5")
{
cell.btnFri.backgroundColor = API.themeColorBlue()
cell.btnFri.isSelected = true
}
else
{
cell.btnFri.backgroundColor = UIColor.white
cell.btnFri.isSelected = false
}
if strDays.contains("6")
{
cell.btnSat.backgroundColor = API.themeColorBlue()
cell.btnSat.isSelected = true
}
else
{
cell.btnSat.backgroundColor = UIColor.white
cell.btnSat.isSelected = false
}
if strDays.contains("0")
{
cell.btnSun.backgroundColor = API.themeColorBlue()
cell.btnSun.isSelected = true
}
else
{
cell.btnSun.backgroundColor = UIColor.white
cell.btnSun.isSelected = false
}
}
if dd.object(forKey: "IsBreak") as! Bool == false
{
cell.lblRosterBreakPaid.isHidden = true
cell.lblRosterBreak.text = "No Break"
}
else
{
cell.lblRosterBreakPaid.isHidden = false
cell.lblRosterBreak.text = "Break"
if dd.object(forKey: "IsBreakPaid") as! Bool == true
{
cell.lblRosterBreakPaid.text = String(format: "(%d min - Paid)", dd.object(forKey: "BreakMin") as! Int)
}
else
{
cell.lblRosterBreakPaid.text = String(format: "(%d min - Unpaid)", dd.object(forKey: "BreakMin") as! Int)
}
}
cell.lblJobTitle.text = dd.object(forKey: "JobPostTitle") as? String
//cell.lblNoteId.text = String(format: "Job ID: %d", dd.object(forKey: "JobPostID") as! Int)
cell.lblRosterTime.text = String(format: "%@ - %@", dd.object(forKey: "FromTime") as! String,dd.object(forKey: "ToTime") as! String)
//cell.lblJobId.text = String(format: "Job ID: %d", dd.object(forKey: "JobPostID") as! Int)
cell.btnAddress.setTitle(dd.object(forKey: "LocationName") as? String, for: UIControlState.normal)
cell.btnAddress.titleLabel?.adjustsFontSizeToFitWidth = true
cell.btnNotes.tag = indexPath.row
cell.btnNotes.addTarget(self, action: #selector(self.btnNote(_:)), for: UIControlEvents.touchUpInside)
cell.btnStart.isHidden = true
cell.btnCancel.isHidden = true
cell.btnNotes.isHidden = false
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let dd: NSDictionary = arrOfCalenderDetail.object(at: indexPath.row) as! NSDictionary
if dd.object(forKey: "StatusID") as! Int == 4
{
let obj: allJobStatusSeeker = self.storyboard?.instantiateViewController(withIdentifier: "allJobStatusSeeker") as! allJobStatusSeeker
obj.strNavTitle = "Accepted Job"
self.navigationController!.pushViewController(obj, animated: true)
}
else
{
let obj: completedJobSeeker = self.storyboard?.instantiateViewController(withIdentifier: "completedJobSeeker") as! completedJobSeeker
self.navigationController!.pushViewController(obj, animated: true)
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
let dd: NSDictionary = arrOfCalenderDetail.object(at: indexPath.row) as! NSDictionary
if dd.object(forKey: "IsBreak") as! Bool == false
{
return 135
}
else
{
return 147
}
}
//MARK:- PRIVATE METHOD
@IBAction func btnInfo(_ sender: Any)
{
custObj.alertMessage(SEEKER_PAY_INOF)
}
@IBAction func btnNote(_ sender: Any)
{
let tag: Int = (sender as AnyObject).tag
let obj: calendarNotesClass = self.storyboard?.instantiateViewController(withIdentifier: "calendarNotesClass") as! calendarNotesClass
obj.dictFrom = arrOfCalenderDetail.object(at: tag) as! NSDictionary
self.present(obj, animated: true, completion: nil)
}
@IBAction func btnCal(_ sender: Any)
{
self.calendar.setScope(.month, animated: true)
btnCal.isHidden = true
}
//MARK:- Call API
func getCalender()
{
custObj.showSVHud("Loading")
let parameter: NSMutableDictionary = NSMutableDictionary()
parameter.setValue(API.getToken(), forKey: "Token")
parameter.setValue(API.getDeviceToken(), forKey: "DeviceID")
parameter.setValue(API.getUserId(), forKey: "UserID")
parameter.setValue(selectedMonth, forKey: "Month")
parameter.setValue(selectedYear, forKey: "Year")
parameter.setValue(false, forKey: "IsAll")
parameter.setValue(API.getRoleName(), forKey: "RoleName")
print(parameter)
API.callApiPOST(strUrl: API_GetCalender,parameter: parameter, success: { (response) in
self.custObj.hideSVHud()
print(response)
if response.object(forKey: "ReturnCode") as! String == "1"
{
let aa: NSArray = response.object(forKey: "Data") as! NSArray
self.arrOfCalender = NSMutableArray.init(array: aa)
self.arrOfDateOnly = NSMutableArray()
for item in aa
{
let dd: NSDictionary = item as! NSDictionary
self.arrOfDateOnly.add(dd.object(forKey: "Date") ?? "")
}
}
else
{
self.custObj.alertMessage(response.object(forKey: "ReturnMsg") as! String)
}
self.calendar.reloadData()
}, error: { (error) in
print(error)
self.custObj.hideSVHud()
self.custObj.alertMessage(ERROR_MESSAGE)
})
}
func getCalenderDetail()
{
custObj.showSVHud("Loading")
self.arrOfCalenderDetail = NSMutableArray()
let parameter: NSMutableDictionary = NSMutableDictionary()
parameter.setValue(API.getToken(), forKey: "Token")
parameter.setValue(API.getDeviceToken(), forKey: "DeviceID")
parameter.setValue(API.getUserId(), forKey: "UserID")
parameter.setValue(selectedDate, forKey: "Date")
parameter.setValue(API.getRoleName(), forKey: "RoleName")
print(parameter)
API.callApiPOST(strUrl: API_GetRosterCalender,parameter: parameter, success: { (response) in
self.custObj.hideSVHud()
print(response)
if response.object(forKey: "ReturnCode") as! String == "1"
{
let aa: NSArray = response.object(forKey: "Data") as! NSArray
self.arrOfCalenderDetail = NSMutableArray.init(array: aa)
}
else
{
self.custObj.alertMessage(response.object(forKey: "ReturnMsg") as! String)
}
self.tblCalendarJob.reloadData()
}, error: { (error) in
print(error)
self.custObj.hideSVHud()
self.custObj.alertMessage(ERROR_MESSAGE)
self.arrOfCalenderDetail = NSMutableArray()
self.tblCalendarJob.reloadData()
})
}
}
|
//
// RxSwift.swift
// RotomPokedex
//
// Created by Ryo on 2020/01/12.
// Copyright © 2020 Ryoga. All rights reserved.
//
import Foundation
import RxSwift
extension Observable {
/// 空の`Observable`にフラットマップする
public func mapToVoid() -> Observable<Void> {
return map { _ -> Void in () }
}
}
|
//: Playground - noun: a place where people can play
import UIKit
var states = [String: String]()
states["MO"] = "Missouri"
states["PA"] = "Pennsylvania"
states["CA"] = "California"
for (abbrev, state) in states {
print("\(abbrev) is \(state)")
}
let stateAbbre = [String](states.keys)
for item in stateAbbre {
print(item)
}
states["PA"] = nil
states.removeValue(forKey: "MO")
for (abbrev, state) in states {
print("\(abbrev) is \(state)")
}
|
//
// CTFMultipleChoiceIntermediateResult+SBBDataArchiveBuilder.swift
// Impulse
//
// Created by James Kizer on 2/27/17.
// Copyright © 2017 James Kizer. All rights reserved.
//
import Foundation
extension CTFMultipleChoiceIntermediateResult {
//SBBDataArchiveConvertableFunctions
override public var schemaIdentifier: String {
return self.schemaID
}
override public var schemaVersion: Int {
return self.version
}
override public var data: [String: Any] {
return [
"selected": self.choices
]
}
}
|
class Solution {
func climbStairs(_ n: Int) -> Int {
var arr = [1, 1]
if n == 0 || n == 1{
return 1
}
for _ in 2...n {
let result = arr[0] + arr[1]
arr[0] = arr[1]
arr[1] = result
}
return arr[1]
}
}
|
//
// ViewController.swift
// MDAnimationDemo
//
// Created by Alan on 2018/4/27.
// Copyright © 2018年 MD. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var b_btn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
b_btn.isHidden = true
// positionAnimation()
// transformScaleAnimation()
// transformRotationAnimation()
// transformTranslationAnimation()
// transformCornerRadiusAnimation()
// transformBorderWidthAnimation()
// transformBackgroundColorAnimation()
// transformAlphaAnimation()
// positionAnimation()
// groupAnimation()
emitterAnimate1()
// Do any additional setup after loading the view, typically from a nib.
}
func showGif(){
let imageView = UIImageView.init(frame: UIScreen.main.bounds)
imageView.animationImages = resolveGifImage()
imageView.animationDuration = 10
imageView.animationRepeatCount = Int.max
imageView.startAnimating()
self.view.addSubview(imageView)
}
//分解gif图
func resolveGifImage()->[UIImage]{
var images:[UIImage] = []
let gifPath = Bundle.main.path(forResource: "demo", ofType: "gif")
if gifPath != nil{
if let gifData = try? Data(contentsOf: URL.init(fileURLWithPath: gifPath!)){
let gifDataSource = CGImageSourceCreateWithData(gifData as CFData, nil)
let gifcount = CGImageSourceGetCount(gifDataSource!)
for i in 0...gifcount - 1{
let imageRef = CGImageSourceCreateImageAtIndex(gifDataSource!, i, nil)
let image = UIImage(cgImage: imageRef!)
images.append(image)
}
}
}
return images
}
/**
//CABasicAnimation
//位置
func positionAnimation(){
let animation = CABasicAnimation()
animation.keyPath = "position"
animation.toValue = CGPoint(x: b_btn.x - 10, y: b_btn.y - 10)
animation.duration = 2
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
b_btn.layer.add(animation, forKey: nil)
}
//缩放
func transformScaleAnimation(){
let animation = CABasicAnimation()
animation.keyPath = "transform.scale.x"
animation.fromValue = 1.0
animation.toValue = 0.8
animation.duration = 2
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
b_btn.layer.add(animation, forKey: nil)
}
//旋转
func transformRotationAnimation(){
let animation = CABasicAnimation()
animation.keyPath = "transform.rotation"
animation.fromValue = Double.pi / 2
animation.toValue = 2.0
animation.duration = 2
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
b_btn.layer.add(animation, forKey: nil)
}
//位移
func transformTranslationAnimation(){
let animation = CABasicAnimation()
animation.keyPath = "transform.translation.y"
animation.toValue = 100
animation.duration = 2
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
b_btn.layer.add(animation, forKey: nil)
}
//圆角
func transformCornerRadiusAnimation(){
let animation = CABasicAnimation()
animation.keyPath = "cornerRadius"
animation.toValue = 15
animation.duration = 2
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
b_btn.layer.add(animation, forKey: nil)
}
//边框
func transformBorderWidthAnimation(){
let animation = CABasicAnimation()
animation.keyPath = "borderWidth"
animation.toValue = 15
animation.duration = 2
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
b_btn.layer.add(animation, forKey: nil)
}
//颜色渐变
func transformBackgroundColorAnimation(){
let animation = CABasicAnimation()
animation.keyPath = "backgroundColor"
animation.fromValue = UIColor.green.cgColor
animation.toValue = UIColor.red.cgColor
animation.duration = 2
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
b_btn.layer.add(animation, forKey: nil)
}
//淡入淡出
func transformAlphaAnimation(){
let animation = CABasicAnimation()
animation.keyPath = "opacity"
animation.fromValue = 0
animation.toValue = 1.0
animation.duration = 2
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
b_btn.layer.add(animation, forKey: nil)
}
*/
//淡出动画效果
func transformAlphaAnimation(){
let animation = CAKeyframeAnimation()
animation.keyPath = "opacity"
animation.values = [0.9,0.8,0.3,0.0]
animation.duration = 5
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
b_btn.layer.add(animation, forKey: nil)
}
//任意路径动画
func positionAnimation(){
let animation = CAKeyframeAnimation()
animation.keyPath = "position"
let pathLine = CGMutablePath()
pathLine.move(to: CGPoint(x: 10, y: 10))
//直线
// pathLine.addLine(to: CGPoint(x: 100, y: 100))
//圆弧
pathLine.addArc(center: CGPoint(x: 100, y: 100), radius: 100, startAngle: 0, endAngle: CGFloat(Double.pi/2), clockwise: true)
animation.path = pathLine
animation.duration = 5
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
b_btn.layer.add(animation, forKey: nil)
}
//组合动画
func groupAnimation(){
let move = CABasicAnimation()
move.keyPath = "position"
move.toValue = CGPoint(x: b_btn.x - 10, y: b_btn.y - 10)
let scale = CABasicAnimation()
scale.keyPath = "transform.scale.x"
scale.fromValue = 1.0
scale.toValue = 0.8
let ransform = CABasicAnimation()
ransform.keyPath = "transform.rotation"
ransform.fromValue = Double.pi / 2
ransform.toValue = 2.0
let animationGroup = CAAnimationGroup()
animationGroup.animations = [move,scale,ransform]
animationGroup.duration = 5
animationGroup.fillMode = kCAFillModeForwards
animationGroup.isRemovedOnCompletion = false
b_btn.layer.add(animationGroup, forKey: nil)
}
//鬼火效果
func emitterAnimate1(){
self.view.backgroundColor = .black
let emitterCell = CAEmitterCell()
emitterCell.name = "fire"
emitterCell.emissionLongitude = CGFloat(Double.pi)
emitterCell.velocity = -1 //粒子熟读 负数表明向上燃烧
emitterCell.velocityRange = 50 //粒子速度范围
emitterCell.emissionRange = 1.1 //周围发射角度
emitterCell.yAcceleration = -200 //粒子y方向的加速度分量
emitterCell.scaleSpeed = 0.7 //速度缩放比例 超大火苗
emitterCell.birthRate = 500 //粒子生成速度
emitterCell.lifetime = 1 //生命周期
emitterCell.color = UIColor(red: 0 ,green: 0.4 ,blue:0.2 ,alpha:0.1).cgColor
emitterCell.contents = UIImage(named: "fire")!.cgImage
let emitterLayer = CAEmitterLayer()
emitterLayer.position = self.view.center //粒子发射位置
emitterLayer.emitterSize = CGSize(width: 50, height: 10)//控制大小
//渲染模式以及发射源模式
emitterLayer.renderMode = kCAEmitterLayerAdditive
emitterLayer.emitterMode = kCAEmitterLayerOutline
emitterLayer.emitterShape = kCAEmitterLayerLine
emitterLayer.emitterCells = [emitterCell]
self.view.layer.addSublayer(emitterLayer)
}
//霓虹效果
func emitterAnimate2(){
self.view.backgroundColor = UIColor.black
let emitterCell = CAEmitterCell()
emitterCell.name = "nenolight"
emitterCell.emissionLongitude = CGFloat(Double.pi*2)// emissionLongitude:x-y 平面的 发 射方向
emitterCell.velocity = 50// 粒子速度
emitterCell.velocityRange = 50// 粒子速度范围
emitterCell.scaleSpeed = -0.2// 速度缩放比例 超大火苗
emitterCell.scale = 0.1 //缩放比例
//R G B alpha 颜色速度渐变
emitterCell.greenSpeed = -0.1
emitterCell.redSpeed = -0.2
emitterCell.blueSpeed = 0.1
emitterCell.alphaSpeed = -0.2
emitterCell.birthRate = 100 // 一秒钟会产生粒子的个数
emitterCell.lifetime = 4 //粒子生命周期
emitterCell.color = UIColor.white.cgColor
emitterCell.contents = UIImage(named: "neonlight")!.cgImage
let emitterLayer = CAEmitterLayer()
emitterLayer.position = self.view.center// 粒子发射位置
emitterLayer.emitterSize = CGSize(width: 2, height: 2)// 控制粒子大小
emitterLayer.renderMode = kCAEmitterLayerBackToFront
emitterLayer.emitterMode = kCAEmitterLayerOutline// 控制发射源模式 即形状
emitterLayer.emitterShape = kCAEmitterLayerCircle
emitterLayer.emitterCells = [emitterCell]
self.view.layer.addSublayer(emitterLayer)
}
//雪花效果
func emitterAnimate3(){
self.view.backgroundColor = UIColor.black
let emitterCell = CAEmitterCell()
emitterCell.name = "snow"
emitterCell.birthRate = 150
emitterCell.lifetime = 5
//yAcceleration 和 xAcceleration 分别表示颗粒在y和x方向上面运动的加速度
emitterCell.yAcceleration = 70.0
emitterCell.xAcceleration = 10.0
emitterCell.velocity = 20.0 //velocity表示颗粒运动的速度
emitterCell.emissionLongitude = CGFloat(-Double.pi/2);//表示颗粒初始时刻发射的方向(-M_PI_2 表示竖直往上发射)
emitterCell.velocityRange = 200//加上这句代码之后,随机产生的速度范围为 -180(20 - 200) 到 220(20 + 200)
emitterCell.emissionRange = CGFloat(Double.pi/2) //我们可以将发射器的发射角度随机化
//R G B alpha 颜色速度渐变
emitterCell.color = UIColor(red: 0.9 ,green: 1.0 ,blue:1.0 ,alpha:1).cgColor
emitterCell.greenSpeed = 0.3
emitterCell.redSpeed = 0.3
emitterCell.blueSpeed = 0.3
emitterCell.scaleSpeed = -0.03// 速度缩放比例
emitterCell.scale = 0.1 //缩放比例
emitterCell.scaleRange = 0.1
emitterCell.contents = UIImage(named: "snow")!.cgImage
let emitterLayer = CAEmitterLayer()
//确定发射器的位置及尺寸
emitterLayer.position = CGPoint(x: self.view.center.x, y: -70)
emitterLayer.emitterSize = CGSize(width: UIScreen.main.bounds.size.width, height: 50)
emitterLayer.emitterShape = kCAEmitterLayerRectangle
emitterLayer.emitterCells = [emitterCell]
self.view.layer.addSublayer(emitterLayer)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// NewVocabViewController.swift
// Nihongo
//
// Created by Dang Nguyen Vu on 3/9/17.
// Copyright © 2017 Dang Nguyen Vu. All rights reserved.
//
import UIKit
import FirebaseDatabase
import SDWebImage
class NewVocabViewController: UIViewController {
@IBOutlet weak var jpTf: UITextField!
@IBOutlet weak var viTf: UITextField!
@IBOutlet weak var subTf: UITextField!
@IBOutlet weak var kanjiTf: UITextField!
@IBOutlet weak var audioTf: UITextField!
@IBOutlet weak var imageTf: UITextField!
@IBOutlet weak var imageTest: UIImageView!
var cloudRef: FIRDatabaseReference?
override func viewDidLoad() {
super.viewDidLoad()
imageTest.image = UIImage.placeholderImage()
}
@IBAction func addButton(_ sender: UIButton) {
self.addNewVocab(jp: jpTf.text ?? "", vi: viTf.text ?? "", sub: subTf.text ?? "", kanji: kanjiTf.text ?? "", audio: audioTf.text ?? "", image: imageTf.text ?? "", description: "")
}
@IBAction func imageTextField(_ sender: UITextField) {
guard let url = URL(string: sender.text!) else {
return
}
self.imageTest.sd_setImage(with: url)
}
func addNewVocab(jp: String, vi: String, sub: String, kanji: String, audio: String, image: String, description: String) {
let vocab = Vocab(jp: jp, vi: vi, sub: sub, kanji: kanji, audioLink: audio, imageLink: image, description: description)
cloudRef?.childByAutoId().setValue(vocab.toAnyObject())
}
@IBAction func closeButtonAction(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
}
|
//
// WordNode.swift
// WordWar
//
// Created by Valentin Radu on 05/07/16.
// Copyright © 2016 Valentin Radu. All rights reserved.
//
import SpriteKit
class WordNode: SKNode {
let letters:[SKLabelNode]
init(text:String) {
letters = text.characters.map {SKLabelNode(text: String($0))}
super.init()
var prevLabel:SKLabelNode?
letters.enumerate().forEach {
i, label in
addChild(label)
label.fontSize = 40
label.fontName = "SanFranciscoText-Medium"
label.fontColor = .random()
if let prevLabel = prevLabel {
let distance = prevLabel.frame.width / 2 + label.frame.width / 2
label.position = CGPoint(x:prevLabel.position.x + distance,
y: 0)
let range = SKRange(value: distance, variance: distance + 30)
label.constraints = [SKConstraint.distance(range, toNode: prevLabel)]
}
prevLabel = label
}
let width = CGRectGetMaxX(prevLabel?.frame ?? .zero)
letters.forEach {
label in
label.position = CGPoint(x: label.position.x - width/2, y: label.position.y)
}
}
func addPhysics() {
var prevLabel:SKLabelNode?
letters.enumerate().forEach {
i, label in
label.physicsBody = SKPhysicsBody(rectangleOfSize: label.frame.size,
center: CGPoint(x: 0, y: label.frame.size.height / 2))
label.physicsBody?.mass = 1.0;
label.physicsBody?.angularDamping = 0.5
label.physicsBody?.linearDamping = 3.5
label.physicsBody?.friction = 0.85
label.physicsBody?.restitution = 0.7
label.physicsBody?.allowsRotation = false
if let prevLabel = prevLabel {
let spring = SKPhysicsJointSpring.jointWithBodyA(prevLabel.physicsBody!,
bodyB: label.physicsBody!,
anchorA: CGPoint(x: 0.5, y: 0.5),
anchorB:CGPoint(x: 0.5, y: 0.5))
spring.damping = 0.05
spring.frequency = 2
self.scene?.physicsWorld.addJoint(spring)
}
prevLabel = label
}
}
func applyRandomImpulse(limit:CGFloat) {
letters.forEach {
label in
label.physicsBody?.applyImpulse(CGVector(dx: .random(-limit, upper:limit), dy: .random(-limit, upper:limit)))
}
}
func breakOut() {
letters.forEach {
label in
label.physicsBody?.allowsRotation = true
label.physicsBody?.joints.forEach {
joint in
self.scene?.physicsWorld.removeJoint(joint)
}
label.constraints = []
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// partCell.swift
// test
//
// Created by Alex Iakab on 07/12/2018.
// Copyright © 2018 Alex Iakab. All rights reserved.
//
import UIKit
class partCell: UICollectionViewCell {
@IBOutlet weak var descLabel: UILabel!
@IBOutlet weak var bgView: UIView!
@IBOutlet weak var imageView: UIImageView!
}
|
//
// TMDropDownArrowView.swift
// consumer
//
// Created by Gregory Sapienza on 2/8/17.
// Copyright © 2017 Human Ventures Co. All rights reserved.
//
import UIKit
class TMDropDownArrowView: UIView {
//MARK: - Public iVars
/// Color of drop down arrow.
var arrowColor = UIColor.black {
didSet {
setNeedsLayout()
}
}
//MARK: - Private iVars
/// Layer displaying arrow path.
private let arrowLayer = CAShapeLayer()
//MARK: - Public
override init(frame: CGRect) {
super.init(frame: frame)
customInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
customInit()
}
override func layoutSubviews() {
super.layoutSubviews()
backgroundColor = UIColor.clear
arrowLayer.fillColor = arrowColor.cgColor
arrowLayer.path = getDropDownArrowPath(from: bounds)
}
//MARK: - Private
private func customInit() {
layer.addSublayer(arrowLayer)
}
/// Creates a CGPath for a drop down arrow.
///
/// - Parameter frame: Frame containing path.
/// - Returns: Path of arrow within specified frame.
private func getDropDownArrowPath(from frame: CGRect) -> CGPath {
let dropDownArrowPath = UIBezierPath()
dropDownArrowPath.move(to: CGPoint(x: frame.minX + 0.50000 * frame.width, y: frame.minY + 1.00000 * frame.height))
dropDownArrowPath.addLine(to: CGPoint(x: frame.minX + 0.93301 * frame.width, y: frame.minY + 0.25000 * frame.height))
dropDownArrowPath.addLine(to: CGPoint(x: frame.minX + 0.06699 * frame.width, y: frame.minY + 0.25000 * frame.height))
dropDownArrowPath.close()
return dropDownArrowPath.cgPath
}
}
|
//
// SettingsViewController.swift
// London Mosque
//
// Created by Yunus Amer on 2020-12-15.
//
import Foundation
import UIKit
class SettingsViewController : UIViewController, UIPickerViewDelegate, UIPickerViewDataSource{
@IBOutlet weak var lbl_volume: UILabel!
@IBOutlet weak var lbl_vibrate: UILabel!
@IBOutlet weak var lbl_customTimerHeader: UILabel!
@IBOutlet weak var lbl_customTimer: UILabel!
@IBOutlet weak var lbl_athanChoice: UILabel!
@IBOutlet weak var sgmnt_volume: UISegmentedControl!
@IBOutlet weak var sgmnt_vibrate: UISegmentedControl!
@IBOutlet weak var switch_customTimer: UISwitch!
@IBOutlet weak var picker_customTimer: UIPickerView!
@IBOutlet weak var picker_athan: UIPickerView!
@IBOutlet weak var btn_stop: UIButton!
@IBOutlet weak var btn_play: UIButton!
@IBOutlet weak var switch_fajrAthanVib: UISwitch!
@IBOutlet weak var switch_fajrAthanVol: UISwitch!
@IBOutlet weak var switch_fajrIqamaVib: UISwitch!
@IBOutlet weak var switch_dhuhrAthanVib: UISwitch!
@IBOutlet weak var switch_dhuhrAthanVol: UISwitch!
@IBOutlet weak var switch_dhuhrIqamaVib: UISwitch!
@IBOutlet weak var switch_asrAthanVib: UISwitch!
@IBOutlet weak var switch_asrAthanVol: UISwitch!
@IBOutlet weak var switch_asrIqamaVib: UISwitch!
@IBOutlet weak var switch_maghribAthanVib: UISwitch!
@IBOutlet weak var switch_maghribAthanVol: UISwitch!
@IBOutlet weak var switch_maghribIqamaVib: UISwitch!
@IBOutlet weak var switch_ishaAthanVib: UISwitch!
@IBOutlet weak var switch_ishaAthanVol: UISwitch!
@IBOutlet weak var switch_ishaIqamaVib: UISwitch!
let minutesArray = Array(1...60)
let athanArray = ["Athan 0", "Athan 1", "Athan 2", "Athan 3", "Athan 4", "Athan 5"]
override func viewDidLoad() {
super.viewDidLoad()
let statusBarView = UIView(frame: UIApplication.shared.statusBarFrame)
statusBarView.backgroundColor = sharedMasterSingleton.getColor(color: "darkBlue")
view.addSubview(statusBarView)
lbl_volume.text = "Which volume level should we use?"
lbl_vibrate.text = "How long should the phone vibrate?"
lbl_customTimerHeader.text = "Set a reminder X minutes before prayer time."
lbl_customTimer.text = "Use custom timer"
lbl_athanChoice.text = "Select which Athan to use."
picker_customTimer.tag = 0
picker_customTimer.delegate = self
picker_customTimer.dataSource = self
picker_athan.tag = 1
picker_athan.delegate = self
picker_athan.dataSource = self
sgmnt_volume.tag = 0
sgmnt_vibrate.tag = 1
sgmnt_volume.addTarget(self, action: #selector(segmentChanged), for: UIControl.Event.valueChanged)
sgmnt_vibrate.addTarget(self, action: #selector(segmentChanged), for: UIControl.Event.valueChanged)
switch_customTimer.tag = 0
switch_customTimer.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)
switch_fajrAthanVib.tag = 1
switch_fajrAthanVol.tag = 2
switch_fajrIqamaVib.tag = 3
switch_dhuhrAthanVib.tag = 4
switch_dhuhrAthanVol.tag = 5
switch_dhuhrIqamaVib.tag = 6
switch_asrAthanVib.tag = 7
switch_asrAthanVol.tag = 8
switch_asrIqamaVib.tag = 9
switch_maghribAthanVib.tag = 10
switch_maghribAthanVol.tag = 11
switch_maghribIqamaVib.tag = 12
switch_ishaAthanVib.tag = 13
switch_ishaAthanVol.tag = 14
switch_ishaIqamaVib.tag = 15
switch_fajrAthanVib.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)
switch_fajrAthanVol.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)
switch_fajrIqamaVib.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)
switch_dhuhrAthanVib.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)
switch_dhuhrAthanVol.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)
switch_dhuhrIqamaVib.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)
switch_asrAthanVib.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)
switch_asrAthanVol.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)
switch_asrIqamaVib.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)
switch_maghribAthanVib.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)
switch_maghribAthanVol.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)
switch_maghribIqamaVib.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)
switch_ishaAthanVib.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)
switch_ishaAthanVol.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)
switch_ishaIqamaVib.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)
picker_customTimer.selectRow(sharedMasterSingleton.getCustomTimerLength()-1, inComponent: 0, animated: false)
picker_athan.selectRow(sharedMasterSingleton.getAthanChoice(), inComponent: 0, animated: false)
sgmnt_volume.selectedSegmentIndex = sharedMasterSingleton.getVolumeChoice()
sgmnt_vibrate.selectedSegmentIndex = sharedMasterSingleton.getVibrateChoice()
switch_customTimer.isOn = sharedMasterSingleton.isCustomTimerOn()
switch_fajrAthanVib.isOn = sharedMasterSingleton.isPrayerNotifierIsOn(tag: 1)
switch_fajrAthanVol.isOn = sharedMasterSingleton.isPrayerNotifierIsOn(tag: 2)
switch_fajrIqamaVib.isOn = sharedMasterSingleton.isPrayerNotifierIsOn(tag: 3)
switch_dhuhrAthanVib.isOn = sharedMasterSingleton.isPrayerNotifierIsOn(tag: 4)
switch_dhuhrAthanVol.isOn = sharedMasterSingleton.isPrayerNotifierIsOn(tag: 5)
switch_dhuhrIqamaVib.isOn = sharedMasterSingleton.isPrayerNotifierIsOn(tag: 6)
switch_asrAthanVib.isOn = sharedMasterSingleton.isPrayerNotifierIsOn(tag: 7)
switch_asrAthanVol.isOn = sharedMasterSingleton.isPrayerNotifierIsOn(tag: 8)
switch_asrIqamaVib.isOn = sharedMasterSingleton.isPrayerNotifierIsOn(tag: 9)
switch_maghribAthanVib.isOn = sharedMasterSingleton.isPrayerNotifierIsOn(tag: 10)
switch_maghribAthanVol.isOn = sharedMasterSingleton.isPrayerNotifierIsOn(tag: 11)
switch_maghribIqamaVib.isOn = sharedMasterSingleton.isPrayerNotifierIsOn(tag: 12)
switch_ishaAthanVib.isOn = sharedMasterSingleton.isPrayerNotifierIsOn(tag: 13)
switch_ishaAthanVol.isOn = sharedMasterSingleton.isPrayerNotifierIsOn(tag: 14)
switch_ishaIqamaVib.isOn = sharedMasterSingleton.isPrayerNotifierIsOn(tag: 15)
}
@objc func segmentChanged(segment: UISegmentedControl) {
if (segment.tag == 0){
sharedMasterSingleton.setVolumeChoice(val: segment.selectedSegmentIndex)
} else if (segment.tag == 1){
sharedMasterSingleton.setVibrateChoice(val: segment.selectedSegmentIndex)
}
}
@objc func switchChanged(mySwitch: UISwitch) {
if(mySwitch.tag == 0){
sharedMasterSingleton.setCustomTimerOn(val: mySwitch.isOn)
} else{
sharedMasterSingleton.setPrayerNotifierIsOn(val: mySwitch.isOn, tag: mySwitch.tag)
}
}
@IBAction func btn_stop(_ sender: Any) {
sharedMasterSingleton.stopSound()
}
@IBAction func btn_play(_ sender: Any) {
sharedMasterSingleton.playSound()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if (pickerView.tag == 0){
return minutesArray.count
} else {
return athanArray.count
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if (pickerView.tag == 0){
return String(minutesArray[row])
} else {
return athanArray[row]
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow: Int, inComponent component: Int){
if (pickerView.tag == 0){
sharedMasterSingleton.setCustomTimerLength(val: didSelectRow+1)
} else {
sharedMasterSingleton.setAthanChoice(val: didSelectRow)
}
}
}
|
//
// InputView.swift
// YourCityEvents
//
// Created by Yaroslav Zarechnyy on 11/15/19.
// Copyright © 2019 Yaroslav Zarechnyy. All rights reserved.
//
import UIKit
class InputView: XibView {
@IBOutlet private weak var vWhite: UIView!
@IBOutlet private weak var lErrorMassage: UILabel!
@IBOutlet weak var tfContent: UITextField!
@IBOutlet private weak var ivPrivace: UIImageView!
@IBOutlet weak var lHelperText: UILabel!
@IBOutlet weak var lcHelperTextWidth: NSLayoutConstraint!
var validator: PValidator?
@IBInspectable var needHelper: Bool = false {
didSet { lcHelperTextWidth.constant = needHelper ? 50.0 : 0.0 }
}
@IBInspectable var helperText: String? {
set { lHelperText.text = newValue }
get { return lHelperText.text ?? nil }
}
@IBInspectable var isPrivace: Bool {
set { ivPrivace.isHidden = !newValue; tfContent.isSecureTextEntry = newValue }
get { return !ivPrivace.isHidden }
}
@IBInspectable var placeholder: String {
set { tfContent.placeholder = newValue }
get { return tfContent.placeholder ?? "" }
}
@IBInspectable var text: String? {
set { tfContent.text = newValue }
get { return tfContent.text }
}
@IBInspectable var errorMessage: String? {
set { lErrorMassage.text = newValue }
get { return lErrorMassage.text }
}
override func commonInit() {
super.commonInit()
ivPrivace.addTapGestureRecognizer(target: self, action: #selector(changePrivace))
tfContent.delegate = self
vWhite.borderColor = UIColor(named: "BackgroundGrey")
self.translatesAutoresizingMaskIntoConstraints = false
}
@objc private func changePrivace() {
tfContent.isSecureTextEntry = !tfContent.isSecureTextEntry
}
func validateText(_ text: String?) {
guard let currentValidator = validator else { return }
currentValidator.validate(text) ? valideText() : notValideText()
}
func notValideText() {
vWhite.borderColor = UIColor.red
// vWhite.backgroundColor = .white
vWhite.backgroundColor = UIColor(named: "BackgroundGrey")
lErrorMassage.isHidden = false
ivPrivace.image = #imageLiteral(resourceName: "0.2RedEye.pdf")
}
func valideText() {
// vWhite.borderColor = #colorLiteral(red: 0.8745098039, green: 0.8745098039, blue: 0.8745098039, alpha: 1)
// vWhite.backgroundColor = UIColor(named: "PlaceholderColor")
vWhite.borderColor = UIColor(named: "BackgroundGrey")
// vWhite.backgroundColor = .white
vWhite.backgroundColor = UIColor(named: "BackgroundGrey")
lErrorMassage.isHidden = true
ivPrivace.image = #imageLiteral(resourceName: "0.2Eye.pdf")
}
}
extension InputView: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let text = textField.text, let textRange = Range(range, in: text) {
validateText(text.replacingCharacters(in: textRange, with: string))
}
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
endEditing(true)
return true
}
}
|
//
// FileManager+Extension.swift
// SwiftTool
//
// Created by galaxy on 2021/5/16.
// Copyright © 2021 yinhe. All rights reserved.
//
import Foundation
extension GL where Base: FileManager {
/// 获取`Document`文件夹路径
public static var documentDirectory: String {
return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last ?? ""
}
/// 获取`Library`文件夹路径
public static var libraryDirectory: String {
return NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).last ?? ""
}
/// 获取`Caches`文件夹路径
public static var cachesDirectory: String {
return NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last ?? ""
}
/// 创建文件夹
///
/// `path`是文件夹的路径
public func creatDirectory(path: String?) {
guard let path = path else { return }
var isDirectory: ObjCBool = true
if FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) {
return
}
try? FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
}
/// 格式化尺寸
///
/// `length`单位是`B`
public func formatSize(length: Int) -> String {
let KB = 1024
let MB = 1024 * 1024
let GB = 1024 * 1024 * 1024
var length = length
if length >= Int.max - 1 {
length = Int.max - 1
}
if (length < KB) {
return String(format: "%.2f B", length.gl.cgFloat)
} else if (length >= KB && length < MB) {
return String(format: "%.2f KB", length.gl.cgFloat / KB.gl.cgFloat)
} else if (length >= MB && length < GB) {
return String(format: "%.2f MB", length.gl.cgFloat / MB.gl.cgFloat)
} else {
return String(format: "%.2f GB", length.gl.cgFloat / GB.gl.cgFloat)
}
}
}
|
//
// JSONJoySpeedTests.swift
// SwiftJSONSpeed
//
// Created by Miquel, Aram on 28/04/2016.
// Copyright © 2016 Ryanair. All rights reserved.
//
import XCTest
import JSONJoy
class JSONJoySpeedTests: XCTestCase {
func testOneSimpleJSONJoy() {
let data = loadTestData("SimpleJSON")!
self.measure {
do {
let _ = try Person(JSONDecoder(data))
} catch {
print(error)
}
}
}
func testManySimpleJSONJoy() {
let data = loadTestData("SimpleJSON")!
self.measure {
do {
for _ in 0...1000 {
let _ = try Person(JSONDecoder(data))
}
} catch {
print(error)
}
}
}
func testComplexJSONJoy() {
let data = loadTestData("ComplexJSON")!
// We have to add a key so we can parse the JSON: Arrays without keys are not supported
let stringWithPeopleKey = "{\"people\":\n\(String(data: data, encoding: String.Encoding.utf8)!)}"
let dataWithPeopleKey = stringWithPeopleKey.data(using: String.Encoding.utf8)!
self.measure {
do {
let _ = try PersonList(JSONDecoder(dataWithPeopleKey))
} catch {
print(error)
}
}
}
}
|
//
// DetailViewController.swift
// Bookmark
//
// Created by 김희진 on 2021/07/27.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet var lblItem: UILabel!
var receiveItme = ""
override func viewDidLoad() {
super.viewDidLoad()
lblItem.text = receiveItme
}
// 메인 뷰에서 item 을 받아오는 함수
func receiveItem(_ item: String){
receiveItme = item
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.