text stringlengths 8 1.32M |
|---|
import UIKit
import ThemeKit
import SnapKit
class StackViewCell: UITableViewCell {
private let stackView = UIStackView()
override init(style: CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = .clear
selectionStyle = .none
contentView.addSubview(stackView)
stackView.snp.makeConstraints { maker in
maker.leading.trailing.equalToSuperview().inset(CGFloat.margin4x)
maker.top.bottom.equalToSuperview()
}
stackView.distribution = .fillEqually
stackView.axis = .horizontal
stackView.spacing = .margin2x
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func add(view: UIView) {
stackView.addArrangedSubview(view)
}
}
|
//
// getLevelService.swift
// Sopt-27th-HACKATHON-6th
//
// Created by ✨EUGENE✨ on 2020/11/22.
//
import Foundation
import Alamofire
import SwiftyJSON
struct getLevelService {
static let shared = getLevelService()
func getLevel(foodType: Int,
completion: @escaping (NetworkResult<Any>) -> Void) {
let url = APIConstants.levelURL + "/\(foodType)"
let dataRequest = AF.request(url,
method : .get,
encoding: JSONEncoding.default)
dataRequest.responseData { dataResponse in
switch dataResponse.result {
case .success:
guard let statusCode = dataResponse.response?.statusCode else { return }
guard let value = dataResponse.value else { return }
let json = JSON(value)
let networkResult = self.judge(by: statusCode, json)
completion(networkResult)
case .failure:
completion(.networkFail)
}
}
}
private func judge(by statusCode: Int, _ json: JSON) -> NetworkResult<Any> {
switch statusCode {
case 200...299: return getLevel(by: json)
case 400...499: return .pathErr
case 500: return .serverErr
default: return .networkFail
}
}
private func getLevel(by json: JSON) -> NetworkResult<Any> {
let data = json["data"] as JSON
var levelData = levelDataModel(id: data[0]["id"].intValue, levelNum: data[0]["levelNum"].intValue, description: data[0]["description"].stringValue, foodType: data[0]["foodType"].intValue, levelName: data[0]["levelName"].stringValue)
return .success(levelData)
}
}
|
//
// ViewController.swift
// Calculator
//
// Created by macbook on 11/22/19.
// Copyright © 2019 bolattleubayev. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var display: UILabel!
@IBOutlet weak var sequence: UILabel!
var userIsInTheMiddleOfTyping = false // "flag" variable to remove initial 0
@IBAction func touchDigit(_ sender: UIButton) {
let digit = sender.currentTitle!
if userIsInTheMiddleOfTyping {
let textCurrentlyInDisplay = display.text!
if digit == ".", !textCurrentlyInDisplay.contains(".") {
display.text = textCurrentlyInDisplay + digit
} else if digit != "." {
display.text = textCurrentlyInDisplay + digit
}
} else {
display.text = digit
userIsInTheMiddleOfTyping = true
}
}
var displayValue: Double {
get {
return Double(display.text!)!
}
set {
display.text = numberFormatter(String(newValue))
}
}
private var brain = CalculatorBrain() // model, no initializers as we dont have uninitialized vars
@IBAction func performOperation(_ sender: UIButton) {
if userIsInTheMiddleOfTyping {
brain.setOperand(displayValue)
userIsInTheMiddleOfTyping = false
}
if let mathematicalSymbol = sender.currentTitle {
brain.performOperation(mathematicalSymbol)
}
if let result = brain.result {
displayValue = result
}
if let resultDescription = brain.sequence {
print(brain.resultIsPending)
if brain.resultIsPending {
sequence.text = resultDescription + "..."
} else {
sequence.text = resultDescription + "="
}
}
if sender.currentTitle == "C" {
brain = CalculatorBrain()
display.text = numberFormatter("0")
sequence.text = "0"
}
}
func numberFormatter(_ value: String?) -> String {
guard value != nil else { return "0.00" }
let doubleValue = Double(value!) ?? 0.0
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 6
return formatter.string(from: NSNumber(value: doubleValue)) ?? "\(doubleValue)"
}
}
|
//
// Constants.swift
// olxItems
//
// Created by Daniel Torres on 6/25/17.
// Copyright © 2017 dansTeam. All rights reserved.
//
import Foundation
struct Constants {
// MARK: Constants
struct Domain {
// MARK: URLs
static let apiScheme = "http"
static let apiHost = "api-v2.olx.com"
static let location = "www.olx.com.ar"
}
// MARK: Methods
struct Methods {
static let searchItems = "/items"
}
// MARK: URL Keys
struct UrlKeys {
// Locations
static let location = "location"
static let searchTerm = "searchTerm"
static let pageSize = "pageSize"
static let offset = "offset"
}
// MARK: JSON Body Keys
struct JSONBodyKeys {
}
// MARK: JSON Body Response Keys
struct JSONBodyResponseKeys {
//items
static let data = "data"
//item
static let id = "id"
static let title = "title"
static let date = "date"
//date it's a dict
static let timestamp = "year"
static let timezone = "Z"
static let description = "description"
static let priceTypeData = "priceTypeData"
static let price = "price"
//price it's a dict
static let concurrency = "preCurrency"
static let amount = "amount"
static let mediumImage = "mediumImage"
static let thumbnail = "thumbnail"
static let fullImage = "fullImage"
static let sold = "sold"
}
}
|
//
// APIService.swift
// YuluDemo
//
// Created by Admin on 10/19/19.
// Copyright © 2019 Admin. All rights reserved.
//
import Foundation
public protocol APIService: class {
associatedtype Model where Model:Decodable
func load(withCompletion completion: @escaping ([Model]?, Error?) -> Void)
func decode(_ data: Data) -> [Model]?
func cancelLoad()
}
extension APIService {
fileprivate func load(_ url: URL, withCompletion completion: @escaping ([Model]?, Error?) -> Void) -> URLSessionTask {
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: url, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in
guard let data = data else {
//completion(nil, error)
completion(nil,error)
return
}
completion(self.decode(data), error)
//completion(error)
})
task.resume()
return task
}
}
public protocol APIResource {
associatedtype Model where Model:Decodable
var methodPath: String { get }
var queryItems: String { get }
func decodeData(data:Data) ->[Model]?
}
extension APIResource {
var url: URL {
let baseUrl = "http://35.154.73.71/api"
let components = URLComponents(string: baseUrl + methodPath)!
return components.url!
}
func decodeData(data:Data) -> [Model]? {
let decoder = JSONDecoder()
do {
let jsondata = try decoder.decode([Model].self, from: data)
return jsondata //try decoder.decode(Model.self, from: data)
}
catch {
print(error)
return nil
}
}
}
public class APIRequest<Resource: APIResource> {
let resource: Resource
init(resource: Resource) {
self.resource = resource
}
var tasks:[URL:URLSessionTask] = [:]
}
extension APIRequest: APIService {
public typealias Model = Resource.Model
public func load(withCompletion completion: @escaping ([Resource.Model]?, Error?) -> Void) {
let task = load(resource.url, withCompletion: completion)
tasks [resource.url] = task
}
public func decode(_ data: Data) -> [Resource.Model]? {
return resource.decodeData(data: data)
}
public func cancelLoad() {
tasks[resource.url]?.cancel()
}
// public func load(withCompletion completion: @escaping (Resource.Model?, Error?) -> Void) {
// load(resource.url, withCompletion: completion)
//
// }
}
|
//
// Created by Nikolay Sohryakov on 03.08.2020.
// Copyright (c) 2020 Storytelling Software. All rights reserved.
//
import Foundation
enum RepositoryError: Error {
case failedToParseJSON
case unknown
case custom(message: String)
}
|
import Domain
import Foundation
import RxSwift
import RxCocoa
final class RepositoryViewModel {
private let useCase: RepositoryUseCase
private let navigator: MainNavigator
init(useCase: RepositoryUseCase, navigator: MainNavigator) {
self.useCase = useCase
self.navigator = navigator
}
}
extension RepositoryViewModel {
struct Input {
let apiUrl: URL?
let initTrigger: Driver<Void>
}
struct Output {
let data: Driver<(Repository, ReadMe?)>
let loading: Driver<Bool>
}
}
extension RepositoryViewModel: ViewModelType {
func transform(input: Input) -> Output {
let loadingActivityIndicator = ActivityIndicator()
let loading = loadingActivityIndicator.asDriver()
let dataResponse = input.initTrigger
.flatMapLatest { (_) -> Driver<Repository> in
guard let url = input.apiUrl else { return Driver.empty() }
return self.useCase
.repository(apiUrl: url.absoluteString)
.map { Repository(with: $0) }
.asDriverOnErrorJustComplete()
}
.flatMapLatest { repository -> Driver<(Repository, ReadMe?)> in
guard let owner = repository.owner else { return Driver.empty() }
return self.useCase
.readme(owner: owner.login, repo: repository.name)
.map { (repository, ReadMe(with: $0)) }
.trackActivity(loadingActivityIndicator)
.asDriver(onErrorJustReturn: (repository, nil))
}
return Output(data: dataResponse, loading: loading)
}
}
|
//
// DateTableViewCell.swift
// MyApp2
//
// Created by Anıl Demirci on 3.08.2021.
//
import UIKit
class DateTableViewCell: UITableViewCell {
@IBOutlet weak var dateLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func prepareForReuse() {
super.prepareForReuse()
isUserInteractionEnabled=true
}
}
|
//
// WatchConnection.swift
// Group8Application
//
// Created by Sven Andersson on 2/28/21.
//
import Foundation
import WatchConnectivity
class WatchConnection : NSObject, WCSessionDelegate, FibaroObserver, HueObserver{
var session : WCSession!
var fibaro : Fibaro?
var hue : HueClient?
//var con : Connection?
init(fib : Fibaro/*, hue : HueClient*/){
super.init()
//self.con = con
self.fibaro = fib
//self.hue = hue
}
//If get request sent from watch -> call that objects recMsgFromWatch!
//Else (no data to return to watch) simply call requested function in respective object.
func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
print("Vi tog emot meddelandet")
//DispatchQueue.main.async {
for (key,value) in message{
print("RECIEVED \(key) \(value) in phone.")
}
//<!----------------- FIBARO --------------------!>//
if let fibaroReq = message["FIBARO"]{
if let GET = message["GET"]{
return self.fibaro!.msgCodeRecieved(code: message["CODE"] as! Int)
}
//If not get request -> post request, performe some action in the lab.
switch message["CODE"] as! Int{
case 0:
//Code 0 -> turn off "NODE" binarySwitch.
self.fibaro!.turnOffSwitch(id: message["NODE"] as! Int)
case 1:
//Code 1 -> turn on "NODE" binarySwitch.
self.fibaro!.turnOnSwitch(id: message["NODE"] as! Int)
case 2:
print("Läs kommentar, har flyttat skiten.")
//Code 2 -> retrive all outlets in the network.
/*
print("Vi är i watchConnection för att hämta listan") meddelandet ska komma in i get. dvs medelandet ska
var list = [String: Any]() skickas från klockan med message["GET"] = true, se recMsgFromWatch i Homekit klassen
list["FIBARO"] = true
list["CODE"] = 0
list["BODY"] = self.fibaro!.watchGetOutlets()
*/
default :
print("No more actions to be taken for fibaro, call your lokal developper noob.")
}
return
}
//<!----------------- PHILIP HUE --------------------!>//
if let hueReq = message["HUE"]{
if let GET = message["GET"]{
return self.hue!.msgCodeRecieved(code: message["CODE"] as! Int)
}
//If not get request -> post request, perform some action in the lab.
switch message["CODE"] as! Int{
case 0:
//Code 0 -> turn off "NODE" light.
self.hue!.turnOffLight(light : message["NODE"] as! String)
case 1:
//Code 1 -> turn off "NODE" light.
self.hue!.turnOnLight(light : message["NODE"] as! String)
default:
print("No more actions to be taken for philip hue, call your lokal developper noob.")
}
return
}
//<!---------------- BUG TESTING -------------------!>//
print("Recieved following msg in phone without a handler:")
for (key,value) in message{
print("Key: \(key) value: \(value)")
}
//}
}
//Send msg to watch for processing.
func send(message : [String : Any]){
if !(session.isReachable){
return
}
session.sendMessage(message, replyHandler: nil, errorHandler: {
error in
print(error.localizedDescription)
})
}
//Varför internal?
internal func fibNotification(_ msg :[String : Any]){
print("Fib response recieved with the msg:")
for(key,value) in msg{
print("Key: \(key), value: \(value)")
}
DispatchQueue.main.async{
//self.send(message: msg)
print("Recieved msg from Fib in phoneConnection")
//self.con!.fibBS.recieveFibSwitches(switches: msg["BODY"] as! [Dictionary<String, Any>])
}
}
func hueNotification(_ msg: [String : Any]) {
/*
print("Hue response recieved with the msg:")
for(key,value) in msg{
print("Key: \(key), value: \(value)")
}
*/
DispatchQueue.main.async{
self.send(message : msg)
}
}
//To be implemented.
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {}
//func sessionDidBecomeInactive(_ session: WCSession) {}
//func sessionDidDeactivate(_ session: WCSession) {}
}
|
// LetterControl.swift
// IvVk
// Created by Iv on 16/03/2019.
// Copyright © 2019 Iv. All rights reserved.
import UIKit
class LetterControl: UIControl {
@IBInspectable var scrollable: Bool = false // TODO: stackView in scrollView is not centered
// available letters array
var Letters: [String] = [] {
didSet {
for button in buttons {
stackView.removeArrangedSubview(button)
button.removeFromSuperview()
}
buttons.removeAll()
for val in Letters {
let button = UIButton(type: .system)
button.setTitle(val, for: .normal)
button.setTitleColor(self.tintColor, for: .normal)
button.setTitleColor(.white, for: .selected)
button.addTarget(self, action: #selector(selectLetter(_:)), for: .touchUpInside)
buttons.append(button)
stackView.addArrangedSubview(button)
}
}
}
var selectedLetter: String? = nil {
didSet {
self.updateSelectedChar()
self.sendActions(for: .valueChanged)
}
}
var changeLetterHandler: ((String) -> Void)? = nil
private var buttons: [UIButton] = []
private var stackView: UIStackView!
private var scrollView: UIScrollView!
override init(frame: CGRect) {
super.init(frame: frame)
self.setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupView()
}
private func setupView() {
if scrollable {
scrollView = UIScrollView()
scrollView.showsVerticalScrollIndicator = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(scrollView)
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|", options: .init(rawValue: 0), metrics: nil, views: ["scrollView": scrollView!]))
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[scrollView]|", options: .init(rawValue: 0), metrics: nil, views: ["scrollView": scrollView!]))
}
stackView = UIStackView()
stackView.spacing = 0
stackView.axis = .vertical
stackView.alignment = .center
stackView.distribution = .fillEqually
if scrollable {
stackView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(stackView)
scrollView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[stackView]|", options: .init(rawValue: 0), metrics: nil, views: ["stackView": stackView!]))
scrollView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[stackView]|", options: .init(rawValue: 0), metrics: nil, views: ["stackView": stackView!]))
scrollView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[stackView(==scrollView)]", options: .init(rawValue: 0), metrics: nil, views: ["stackView": stackView!, "scrollView": scrollView!]))
} else {
self.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[stackView]|", options: .init(rawValue: 0), metrics: nil, views: ["stackView": stackView!]))
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[stackView]|", options: .init(rawValue: 0), metrics: nil, views: ["stackView": stackView!]))
}
}
// set buttons status according to selected letter
private func updateSelectedChar() {
for button in self.buttons {
if let sl = selectedLetter {
button.isSelected = sl == button.titleLabel?.text
} else {
button.isSelected = false
}
}
}
// button tap handler
@objc private func selectLetter(_ sender: UIButton) {
self.selectedLetter = sender.titleLabel?.text
// if external handler assigned call it
if let handler = changeLetterHandler,
let letter = selectedLetter
{
handler(letter)
}
}
/*
override func layoutSubviews() {
super.layoutSubviews()
if !scrollable {
stackView.frame = bounds
}
scrollView.contentSize = CGSize(width: stackView.frame.width, height: stackView.frame.height)
}
*/
}
|
//
// LoanPage.swift
// MyBank
//
// Created by Sathriyan on 01/07/21.
//
import SwiftUI
struct LoanPage: View {
@State var addMoney : String = ""
@State var showAlert : Bool = false
@State var educationLoanToggle : Bool = true
@State var personalLoanToggle : Bool = true
@State var homeLoanToggle : Bool = true
@State var carLoanToggle : Bool = true
@State var tOne : Bool = true
@State var tTwo : Bool = true
@State var tThree : Bool = true
@State var tFour : Bool = true
@State var tFive : Bool = true
var body: some View {
NavigationView {
GeometryReader { geo in
ScrollView {
VStack {
VStack {
Text("Loan Request")
.foregroundColor(Color("CardBg"))
.font(Font.system(size: geo.size.width * 0.075))
.fontWeight(.semibold)
.frame(maxWidth : .infinity, alignment: .leading)
.padding(.top, geo.size.height * 0.065)
.padding(.leading, geo.size.width * 0.065)
Text("Select type of loan")
.foregroundColor(Color.black)
.font(Font.system(size: geo.size.width * 0.057))
.fontWeight(.semibold)
.frame(maxWidth : .infinity, alignment: .leading)
.padding(.top, geo.size.height * 0.015)
.padding(.leading, geo.size.width * 0.065)
VStack {
HStack(spacing : geo.size.width * 0.065){
Button(action: {
educationLoanToggle.toggle()
personalLoanToggle = true
homeLoanToggle = true
carLoanToggle = true
}, label: {
Text("Education")
.font(Font.system(size: geo.size.height * 0.025))
.fontWeight(.semibold)
.foregroundColor(.black)
.frame(width : geo.size.width * 0.4, height: geo.size.height * 0.07)
.background( educationLoanToggle ? Color.black.opacity(0.12) : Color.accentColor.opacity(0.7))
.cornerRadius(geo.size.width * 0.015)
.opacity(0.9)
})
Button(action: {
personalLoanToggle.toggle()
educationLoanToggle = true
homeLoanToggle = true
carLoanToggle = true
}, label: {
Text("Personal")
.font(Font.system(size: geo.size.height * 0.025))
.fontWeight(.semibold)
.foregroundColor(.black)
.frame(width : geo.size.width * 0.4, height: geo.size.height * 0.07)
.background( personalLoanToggle ? Color.black.opacity(0.12) : Color.accentColor.opacity(0.7))
.cornerRadius(geo.size.width * 0.015)
.opacity(0.9)
})
}
.padding(.top , geo.size.height * 0.01)
HStack(spacing : geo.size.width * 0.065){
Button(action: {
homeLoanToggle.toggle()
educationLoanToggle = true
personalLoanToggle = true
carLoanToggle = true
}, label: {
Text("Home")
.font(Font.system(size: geo.size.height * 0.025))
.fontWeight(.semibold)
.foregroundColor(.black)
.frame(width : geo.size.width * 0.4, height: geo.size.height * 0.07)
.background( homeLoanToggle ? Color.black.opacity(0.12) : Color.accentColor.opacity(0.7))
.cornerRadius(geo.size.width * 0.015)
.opacity(0.9)
})
Button(action: {
carLoanToggle.toggle()
educationLoanToggle = true
personalLoanToggle = true
homeLoanToggle = true
}, label: {
Text("Car / Bike")
.font(Font.system(size: geo.size.height * 0.025))
.fontWeight(.semibold)
.foregroundColor(.black)
.frame(width : geo.size.width * 0.4, height: geo.size.height * 0.07)
.background( carLoanToggle ? Color.black.opacity(0.12) : Color.accentColor.opacity(0.7))
.cornerRadius(geo.size.width * 0.015)
.opacity(0.9)
})
}
.padding(.top , geo.size.height * 0.01)
}
VStack{
Text("Enter Loan Amount")
.foregroundColor(Color.black)
.font(Font.system(size: geo.size.width * 0.057))
.fontWeight(.semibold)
.frame(maxWidth : .infinity, alignment: .leading)
.padding(.top, geo.size.height * 0.02)
.padding(.leading, geo.size.width * 0.065)
Text("Enter loan amount between 1000 to 50,000")
.foregroundColor(Color.black)
.font(Font.system(size: geo.size.width * 0.04))
.frame(maxWidth : .infinity, alignment: .leading)
.padding(.top, geo.size.height * 0.001)
.padding(.leading, geo.size.width * 0.065)
TextField("Enter Amount", text: $addMoney)
.padding(.leading, geo.size.width * 0.05)
.disableAutocorrection(true)
.font(Font.system(size: geo.size.width * 0.06))
.frame(height : geo.size.width * 0.13)
.frame(maxWidth : .infinity, alignment: .leading)
.background(Color.black.opacity(0.1))
.frame(width : geo.size.width * 0.85)
.cornerRadius(geo.size.width * 0.015)
.padding(.top, geo.size.height * 0.015)
}
VStack{
Text("or")
.font(Font.system(size: geo.size.height * 0.027))
.foregroundColor(.secondary)
HStack(spacing : geo.size.width * 0.05){
Button(action: {
addMoney = "10000"
}, label: {
Text("10,000")
.font(Font.system(size: geo.size.height * 0.025))
.fontWeight(.semibold)
.foregroundColor(.black)
.frame(width : geo.size.width * 0.25, height: geo.size.height * 0.07)
.background(Color.black.opacity(0.12))
.cornerRadius(geo.size.width * 0.015)
.opacity(0.9)
})
Button(action: {
addMoney = "250000"
}, label: {
Text("25,000")
.font(Font.system(size: geo.size.height * 0.025))
.fontWeight(.semibold)
.foregroundColor(.black)
.frame(width : geo.size.width * 0.25, height: geo.size.height * 0.07)
.background(Color.black.opacity(0.12))
.cornerRadius(geo.size.width * 0.015)
.opacity(0.9)
})
Button(action: {
addMoney = "500000"
}, label: {
Text("50,000")
.font(Font.system(size: geo.size.height * 0.025))
.fontWeight(.semibold)
.foregroundColor(.black)
.frame(width : geo.size.width * 0.25, height: geo.size.height * 0.07)
.background(Color.black.opacity(0.12))
.cornerRadius(geo.size.width * 0.015)
.opacity(0.9)
})
}
.padding(.top , geo.size.height * 0.01)
}
VStack{
Text("Select Loan Tenure")
.foregroundColor(Color.black)
.font(Font.system(size: geo.size.width * 0.057))
.fontWeight(.semibold)
.frame(maxWidth : .infinity, alignment: .leading)
.padding(.top, geo.size.height * 0.025)
.padding(.leading, geo.size.width * 0.065)
HStack(spacing : geo.size.width * 0.035){
Button(action: {
tOne.toggle()
tTwo = true
tThree = true
tFour = true
tFive = true
}, label: {
Text("6")
.font(Font.system(size: geo.size.height * 0.025))
.fontWeight(.semibold)
.foregroundColor(.black)
.frame(width : geo.size.width * 0.14, height: geo.size.height * 0.07)
.background( tOne ? Color.black.opacity(0.12) : Color.accentColor.opacity(0.7))
.cornerRadius(geo.size.width * 0.015)
.opacity(0.9)
})
Button(action: {
tOne = true
tTwo.toggle()
tThree = true
tFour = true
tFive = true
}, label: {
Text("12")
.font(Font.system(size: geo.size.height * 0.025))
.fontWeight(.semibold)
.foregroundColor(.black)
.frame(width : geo.size.width * 0.14, height: geo.size.height * 0.07)
.background( tTwo ? Color.black.opacity(0.12) : Color.accentColor.opacity(0.7))
.cornerRadius(geo.size.width * 0.015)
.opacity(0.9)
})
Button(action: {
tOne = true
tTwo = true
tThree.toggle()
tFour = true
tFive = true
}, label: {
Text("18")
.font(Font.system(size: geo.size.height * 0.025))
.fontWeight(.semibold)
.foregroundColor(.black)
.frame(width : geo.size.width * 0.14, height: geo.size.height * 0.07)
.background( tThree ? Color.black.opacity(0.12) : Color.accentColor.opacity(0.7))
.cornerRadius(geo.size.width * 0.015)
.opacity(0.9)
})
Button(action: {
tOne = true
tTwo = true
tThree = true
tFour.toggle()
tFive = true
}, label: {
Text("24")
.font(Font.system(size: geo.size.height * 0.025))
.fontWeight(.semibold)
.foregroundColor(.black)
.frame(width : geo.size.width * 0.14, height: geo.size.height * 0.07)
.background( tFour ? Color.black.opacity(0.12) : Color.accentColor.opacity(0.7))
.cornerRadius(geo.size.width * 0.015)
.opacity(0.9)
})
Button(action: {
tOne = true
tTwo = true
tThree = true
tFour = true
tFive.toggle()
}, label: {
Text("30")
.font(Font.system(size: geo.size.height * 0.025))
.fontWeight(.semibold)
.foregroundColor(.black)
.frame(width : geo.size.width * 0.14, height: geo.size.height * 0.07)
.background( tFive ? Color.black.opacity(0.12) : Color.accentColor.opacity(0.7))
.cornerRadius(geo.size.width * 0.015)
.opacity(0.9)
})
}
.padding(.top , geo.size.height * 0.015)
}
Button(action: {
showAlert.toggle()
}, label: {
Text("Request Loan")
.font(Font.system(size: geo.size.height * 0.027))
.fontWeight(.semibold)
.foregroundColor(.white)
.frame(width : geo.size.width * 0.7, height: geo.size.height * 0.065)
.background(Color("CardBg"))
.cornerRadius(geo.size.width * 0.03)
.opacity(0.9)
.padding(.top , geo.size.height * 0.04)
})
.alert(isPresented: $showAlert,
content: {
Alert(title: Text("Notice"), message: Text("Please Upload required loan documents in settings section"), dismissButton: .default(Text("Got it!")))
})
}
}
.frame(maxWidth : .infinity, maxHeight: .infinity , alignment: .top)
}
}
.background(Color("BgColor"))
.edgesIgnoringSafeArea(.top)
.ignoresSafeArea(.keyboard)
.navigationBarHidden(true)
}
}
}
struct LoanPage_Previews: PreviewProvider {
static var previews: some View {
LoanPage()
}
}
|
//
// CircleLineView.swift
// Block 8
//
// Created by Фёдор on 28.01.16.
// Copyright © 2016 Фёдор. All rights reserved.
//
import Foundation
import UIKit
class CircleLineView: UIView {
var callback: (() -> ())?
var screenWidth: CGFloat = 0
var screenHeight: CGFloat = 0
var lineWidth: CGFloat = 0
var lineHeight: CGFloat = 0
var squareWidth: CGFloat = 0
let blockDistance: CGFloat = 2
var circleDistance: CGFloat = 0
var circleRadius: CGFloat = 0
var circles: Array<UIView> = []
let rect = UIView()
init() {
super.init(frame: CGRectZero)
}
init(screenWidth: CGFloat, screenHeight: CGFloat) {
self.screenWidth = screenWidth
self.screenHeight = screenHeight
self.squareWidth = (screenWidth - 4 * blockDistance) / 5 / 2
//self.lineHeight = squareWidth * 0.5
self.lineHeight = 20
self.lineWidth = screenWidth * 0.88
self.circleRadius = lineHeight / 2
self.circleDistance = (self.lineWidth - 9 * circleRadius * 2) / 8
//super.init(frame: CGRect(x: 0.7 * screenWidth, y: /*(self.infoHeight - 0.8 * self.infoHeight) / 2*/ 0.1 * screenHeight, width: self.taskWidth, height: self.taskHeight))
super.init(frame: CGRect(x: 0.06 * screenWidth, y: /*(self.infoHeight - 0.8 * self.infoHeight) / 2*/ /*0.95 * screenHeight*/ screenHeight - 34, width: self.lineWidth, height: self.lineHeight))
//self.backgroundColor = UIColor.blackColor()
self.createCircles()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
func animateCircles(pause pause: Bool, wait: Double, duration: Double) {
for _ in 0..<self.circles.count {
//self.circles[circleNumber].frame.origin.y = 1.2 * self.screenHeight
//print("circleNumber ", circleNumber, "frame", self.circles[circleNumber].frame)
}
//print("screenHeight * 0.95 ", 0.95 * screenHeight)
if pause {
for circleNumber in 0..<self.circles.count {
UIView.animateWithDuration(duration, delay: wait + Double(circleNumber) * 0.02, options: .CurveLinear, animations: {
//self.circleLine.frame.origin.y = 1.2 * self.screenHeight
//self.circles[circleNumber].frame.origin.y = 1.2 * self.screenHeight
self.circles[circleNumber].frame.origin.y = 200
}, completion: {finished in
})
}
}
else {
for circleNumber in 0..<self.circles.count {
UIView.animateWithDuration(duration, delay: wait + Double(circleNumber) * 0.02, options: .CurveLinear, animations: {
//self.circleLine.frame.origin.y = 0.95 * self.screenHeight
//self.circles[circleNumber].frame.origin.y = 0.95 * self.screenHeight
self.circles[circleNumber].frame.origin.y = 0
}, completion: {finished in
})
}
}
for _ in 0..<self.circles.count {
//self.circles[circleNumber].frame.origin.y = 1.2 * self.screenHeight
//print("finish circleNumber ", circleNumber, "frame", self.circles[circleNumber].frame)
}
}
private func createCircles() {
for numbCircle in 0...9 {
let circle = UIView(frame: CGRectMake(0 + CGFloat(numbCircle) * (circleRadius * 2 + circleDistance), 0 , circleRadius * 2, circleRadius * 2))
circle.layer.cornerRadius = circleRadius
circle.backgroundColor = UIColor.getSquareColor(numbCircle + 1)
circles.append(circle)
self.addSubview(circle)
}
//rect.frame = CGRectMake(taskWidth - squareWidth, 0, squareWidth, taskHeight)
/*rect.frame = CGRectMake(0, 0, taskWidth, squareWidth * 0.5)
//rect.backgroundColor = UIColor.greenColor()
rect.backgroundColor = UIColor.whiteColor()
rect.addSubview(letterLabel)
rect.layer.cornerRadius = squareWidth * 0.5 / 2*/
//self.addSubview(rect)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
callback!()
}
} |
//
// LocalTodoTrunk.swift
// Swiftodo
//
// Created by Cody on 2014. 8. 13..
// Copyright (c) 2014년 swift. All rights reserved.
//
import Foundation
class LocalTodoTrunk : TodoTrunk {
} |
//
// Created by Ivano Bilenchi on 14/03/18.
// Copyright © 2018 Ivano Bilenchi. All rights reserved.
//
typealias FaceModel = OCVFaceModel
|
//
// DeleteFromMyList.swift
// GoApp
//
// Created by X on 12/9/16.
// Copyright © 2016 Brenda Kaing. All rights reserved.
//
import Foundation
protocol DeleteFromMyListDelegate: class {
func deletedAnEvent(controller: tableViewController)
}
|
//
// DetailController.swift
// swift-news
//
// Created by watanabe_kenichiro on 2016/09/29.
// Copyright © 2016年 nabeen. All rights reserved.
//
import UIKit
class DetailController: UIViewController {
@IBOutlet weak var webView: UIWebView!
var entry = NSDictionary()
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: self.entry["link"] as! String)
let request = NSURLRequest(URL: url!)
webView.loadRequest(request)
}
}
|
// Card.swift
class Card {
let suit: Suits
let number: Int
init(suit: Suits, number: Int) {
self.suit = suit
self.number = number
}
static func < (lhs: Card, rhs: Card) -> Bool {
return lhs.number < rhs.number
}
} |
//
// TextFieldRounded.swift
// TextFieldRounded
//
// Created by An Nguyen 2 on 9/9/21.
// Copyright © 2021 orgName. All rights reserved.
//
import SwiftUI
struct TextFieldRounded: View {
let placeholder: String
var iconName: String
var text: Binding<String>
var isScureField: Bool = false
@State private var isScureFieldState: Bool = false
init(placeholder: String = "", iconName: String, text: Binding<String>, isScureField: Bool = false) {
self.placeholder = placeholder
self.iconName = iconName
self.isScureField = isScureField
self.text = text
self.isScureFieldState = isScureField
}
var body: some View {
HStack {
Label(
title: {
if isScureFieldState {
SecureField(placeholder, text: text)
} else {
TextField(placeholder, text: text)
}
},
icon: { Image(systemName: iconName).frame(width: 30) }
)
if isScureField {
Button(action: {
isScureFieldState.toggle()
}, label: {
Image(systemName: !isScureFieldState ? "eye.fill": "eye.slash.fill")
})
.foregroundColor(.gray)
}
}
.frame(minHeight: 40)
.padding(.horizontal, 6)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(.gray, lineWidth: 1)
)
}
}
|
//
// Codable+Helpers.swift
// SwiftUIINewsFeed
//
// Created by Saman Badakhshan on 10/11/2019.
// Copyright © 2019 Nonisoft. All rights reserved.
//
import Foundation
extension Encodable
{
func asJsonData() -> Data?
{
return try? JSONEncoder().encode(self)
}
}
|
//
// DBManager.swift
// StakesApp
//
// Created by Hemen Gohil on 6/23/16.
// Copyright © 2016 Hemen Gohil. All rights reserved.
//
import UIKit
let sharedInstanceDB = DBManager()
let DB_NAME = "WealthTrustDB.sqlite"
let DB_TBL_USER_MASTER = "User"
let DB_TBL_AOFStatus_MASTER = "AOFStatus"
let DB_TBL_ORDER_MASTER = "OrderMaster"
let DB_TBL_ORDER_SYSTEMATIC_MASTER = "SystematicOrderDetail"
let DB_TBL_MF_ACCOUNT = "MF_Account"
let DB_TBL_MF_TRANSACTION = "MF_Transaction"
let DB_TBL_MANUAL_MF_ACCOUNT = "Manual_MF_Account"
let DB_TBL_MANUAL_MF_TRANSACTION = "Manual_MF_Transaction"
let DB_TBL_DYNAMIC_TEXT = "Dynamictext"
let DB_TBL_PAY_EZZ_MANDATE = "PayEzzMandate"
let DB_TBL_mfuPortfolioWorthTable = "mfuPortfolioWorthTable"
let DB_TBL_mfuPortfolioManualWorthTable = "mfuPortfolioManualWorthTable"
let date = NSDate()
let dateFormatter = NSDateFormatter()
let calendar = NSCalendar.currentCalendar()
let unitFlags: NSCalendarUnit = [.Year,.Month]
class DBManager: NSObject {
var database: FMDatabase? = nil
class func getInstance() -> DBManager
{
if(sharedInstanceDB.database == nil)
{
sharedInstanceDB.database = FMDatabase(path: SharedManager.getPath(DB_NAME))
}
return sharedInstanceDB
}
func getMyOrdersData() -> NSMutableArray {
var clientId = "0";
let allUser = getAllUser()
if allUser.count>0
{
let objUser = allUser.objectAtIndex(0) as! User
clientId = objUser.ClientID
}
sharedInstanceDB.database!.open()
let SQL = "SELECT OrderMaster.*,MF_Transaction.TxnpucharseUnits,MF_Transaction.TxnpuchaseNAV,MF_Transaction.TxnPurchaseAmount,MF_Transaction.ExecutaionDateTime,MF_Transaction.TxtType FROM OrderMaster LEFT JOIN MF_Transaction ON OrderMaster.ServerOrderID=MF_Transaction.OrderId WHERE CartFlag=0 AND OrderMaster.ClientID=\(clientId)"
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery(SQL, withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let userInfo : Order = Order()
userInfo.AppOrderID = resultSet.stringForColumn(kAppOrderID)
userInfo.ServerOrderID = resultSet.stringForColumn(kServerOrderID)
userInfo.ClientID = resultSet.stringForColumn(kClientID)
userInfo.FolioNo = resultSet.stringForColumn(kFolioNo)
userInfo.FolioCheckDigit = resultSet.stringForColumn(kFolioCheckDigit)
userInfo.RtaAmcCode = resultSet.stringForColumn(kRtaAmcCode)
userInfo.SrcSchemeCode = resultSet.stringForColumn(kSrcSchemeCode)
userInfo.SrcSchemeName = resultSet.stringForColumn(kSrcSchemeName)
userInfo.TarSchemeCode = resultSet.stringForColumn(kTarSchemeCode)
userInfo.TarSchemeName = resultSet.stringForColumn(kTarSchemeName)
userInfo.DividendOption = resultSet.stringForColumn(kDividendOption)
userInfo.VolumeType = resultSet.stringForColumn(kVolumeType)
userInfo.Volume = resultSet.stringForColumn(kVolume)
userInfo.OrderType = resultSet.stringForColumn(kOrderType)
userInfo.OrderStatus = resultSet.stringForColumn(kOrderStatus)
userInfo.AppOrderTimeStamp = resultSet.stringForColumn(kAppOrderTimeStamp)
userInfo.CartFlag = resultSet.stringForColumn(kCartFlag)
userInfo.UpdateTime = resultSet.stringForColumn(kUpdateTime)
userInfo.txnPurchaseUnits = resultSet.stringForColumn(kTxnpucharseUnits)
userInfo.txnPurchaseNav = resultSet.stringForColumn(kTxnpuchaseNAV)
userInfo.txnPurchaseAmount = resultSet.stringForColumn(kTxnPurchaseAmount)
userInfo.executionDateTime = resultSet.stringForColumn(kExecutaionDateTime)
marrStakeInfo.addObject(userInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func addUser(UserInfo : User) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("INSERT INTO \(DB_TBL_USER_MASTER) (\(kClientID), \(kName), \(kEmail), \(kMob), \(kPassword), \(kCAN), \(kSignupStatus), \(kInvestmentAofStatus)) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", withArgumentsInArray: [UserInfo.ClientID,UserInfo.Name,UserInfo.email,UserInfo.mob,UserInfo.password,UserInfo.CAN,UserInfo.SignupStatus,UserInfo.InvestmentAofStatus])
sharedInstanceDB.database?.close()
return isInserted!
}
func updateUser(UserInfo : User) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("UPDATE \(DB_TBL_USER_MASTER) SET \(kName)=?, \(kEmail)=?, \(kMob)=?, \(kCAN)=?, \(kSignupStatus)=?, \(kInvestmentAofStatus)=? WHERE \(kClientID)=?", withArgumentsInArray: [UserInfo.Name,UserInfo.email,UserInfo.mob,UserInfo.CAN,UserInfo.SignupStatus,UserInfo.InvestmentAofStatus,UserInfo.ClientID])
sharedInstanceDB.database?.close()
return isInserted!
}
func deleteAllUser() -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("DELETE FROM \(DB_TBL_USER_MASTER)", withArgumentsInArray: nil)
sharedInstanceDB.database?.close()
return isInserted!
}
func getAllUser() -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_USER_MASTER)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let userInfo : User = User()
userInfo.ClientID = resultSet.stringForColumn(kClientID)
userInfo.Name = resultSet.stringForColumn(kName)
userInfo.email = resultSet.stringForColumn(kEmail)
userInfo.mob = resultSet.stringForColumn(kMob)
userInfo.password = resultSet.stringForColumn(kPassword)
userInfo.CAN = resultSet.stringForColumn(kCAN)
userInfo.SignupStatus = resultSet.stringForColumn(kSignupStatus)
userInfo.InvestmentAofStatus = resultSet.stringForColumn(kInvestmentAofStatus)
marrStakeInfo.addObject(userInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func getLoggedInUserDetails() -> User {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_USER_MASTER)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let userInfo : User = User()
userInfo.ClientID = resultSet.stringForColumn(kClientID)
userInfo.Name = resultSet.stringForColumn(kName)
userInfo.email = resultSet.stringForColumn(kEmail)
userInfo.mob = resultSet.stringForColumn(kMob)
userInfo.password = resultSet.stringForColumn(kPassword)
userInfo.CAN = resultSet.stringForColumn(kCAN)
userInfo.SignupStatus = resultSet.stringForColumn(kSignupStatus)
userInfo.InvestmentAofStatus = resultSet.stringForColumn(kInvestmentAofStatus)
marrStakeInfo.addObject(userInfo)
}
}
sharedInstanceDB.database!.close()
if marrStakeInfo.count==0 {
return User()
}else{
return marrStakeInfo.objectAtIndex(0) as! User
}
}
// AOFStatus Table Methods....
func addAOFStatus(UserAOFStatus : AOFStatus) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("INSERT INTO \(DB_TBL_AOFStatus_MASTER) (\(kClientID), \(kPanCopy), \(kChequeCopy), \(kSelfie), \(kDobmismatch), \(kNameMismatch), \(kSignaturemismatch), \(kBanckaccmismatch), \(kIFSCmismatch), \(kPannummismatch), \(kAOFtype), \(kIdS)) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", withArgumentsInArray: [UserAOFStatus.ClientID,UserAOFStatus.pancopy,UserAOFStatus.chequecopy,UserAOFStatus.selfie,UserAOFStatus.dobmismatch,UserAOFStatus.namemismatch,UserAOFStatus.signaturemismatch,UserAOFStatus.banckaccmismatch,UserAOFStatus.ifscmismatch,UserAOFStatus.pannummismatch,UserAOFStatus.aoftype,UserAOFStatus.idS])
sharedInstanceDB.database?.close()
return isInserted!
}
func updateAOFStatus(UserAOFStatus : AOFStatus) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("UPDATE \(DB_TBL_AOFStatus_MASTER) SET \(kPanCopy)=?, \(kChequeCopy)=?, \(kSelfie)=?, \(kDobmismatch)=?, \(kNameMismatch)=?, \(kSignaturemismatch)=?, \(kBanckaccmismatch)=?, \(kIFSCmismatch)=?, \(kPannummismatch)=?, \(kIdS)=? WHERE \(kAOFtype)=? AND \(kClientID)=?", withArgumentsInArray: [UserAOFStatus.pancopy,UserAOFStatus.chequecopy,UserAOFStatus.selfie,UserAOFStatus.dobmismatch,UserAOFStatus.namemismatch,UserAOFStatus.signaturemismatch,UserAOFStatus.banckaccmismatch,UserAOFStatus.ifscmismatch,UserAOFStatus.pannummismatch,UserAOFStatus.idS,UserAOFStatus.aoftype,UserAOFStatus.ClientID])
sharedInstanceDB.database?.close()
return isInserted!
}
func deleteAllAOFStatus() -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("DELETE FROM \(DB_TBL_AOFStatus_MASTER)", withArgumentsInArray: nil)
sharedInstanceDB.database?.close()
return isInserted!
}
func getAllAOFStatus() -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_AOFStatus_MASTER)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let UserAOFStatus : AOFStatus = AOFStatus()
UserAOFStatus.ClientID = resultSet.stringForColumn(kClientID)
UserAOFStatus.pancopy = resultSet.stringForColumn(kPanCopy)
UserAOFStatus.chequecopy = resultSet.stringForColumn(kChequeCopy)
UserAOFStatus.selfie = resultSet.stringForColumn(kSelfie)
UserAOFStatus.dobmismatch = resultSet.stringForColumn(kDobmismatch)
UserAOFStatus.namemismatch = resultSet.stringForColumn(kNameMismatch)
UserAOFStatus.signaturemismatch = resultSet.stringForColumn(kSignaturemismatch)
UserAOFStatus.banckaccmismatch = resultSet.stringForColumn(kBanckaccmismatch)
UserAOFStatus.ifscmismatch = resultSet.stringForColumn(kIFSCmismatch)
UserAOFStatus.pannummismatch = resultSet.stringForColumn(kPannummismatch)
UserAOFStatus.aoftype = resultSet.stringForColumn(kAOFtype)
UserAOFStatus.idS = resultSet.stringForColumn(kIdS)
marrStakeInfo.addObject(UserAOFStatus)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func checkSignUpStatusAlreadyExist(UserAOFStatus : AOFStatus) -> Bool {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_AOFStatus_MASTER) WHERE \(kClientID)=\(UserAOFStatus.ClientID) AND \(kAOFtype)=0", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let UserAOFStatus : AOFStatus = AOFStatus()
UserAOFStatus.ClientID = resultSet.stringForColumn(kClientID)
UserAOFStatus.pancopy = resultSet.stringForColumn(kPanCopy)
UserAOFStatus.chequecopy = resultSet.stringForColumn(kChequeCopy)
UserAOFStatus.selfie = resultSet.stringForColumn(kSelfie)
UserAOFStatus.dobmismatch = resultSet.stringForColumn(kDobmismatch)
UserAOFStatus.namemismatch = resultSet.stringForColumn(kNameMismatch)
UserAOFStatus.signaturemismatch = resultSet.stringForColumn(kSignaturemismatch)
UserAOFStatus.banckaccmismatch = resultSet.stringForColumn(kBanckaccmismatch)
UserAOFStatus.ifscmismatch = resultSet.stringForColumn(kIFSCmismatch)
UserAOFStatus.pannummismatch = resultSet.stringForColumn(kPannummismatch)
UserAOFStatus.aoftype = resultSet.stringForColumn(kAOFtype)
UserAOFStatus.idS = resultSet.stringForColumn(kIdS)
marrStakeInfo.addObject(UserAOFStatus)
}
}
sharedInstanceDB.database!.close()
if marrStakeInfo.count==0 {
return false
}else{
return true
}
}
func checkInvetmentAOFAlreadyExist(UserAOFStatus : AOFStatus) -> Bool {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_AOFStatus_MASTER) WHERE \(kClientID)=\(UserAOFStatus.ClientID) AND \(kAOFtype)=1", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let UserAOFStatus : AOFStatus = AOFStatus()
UserAOFStatus.ClientID = resultSet.stringForColumn(kClientID)
UserAOFStatus.pancopy = resultSet.stringForColumn(kPanCopy)
UserAOFStatus.chequecopy = resultSet.stringForColumn(kChequeCopy)
UserAOFStatus.selfie = resultSet.stringForColumn(kSelfie)
UserAOFStatus.dobmismatch = resultSet.stringForColumn(kDobmismatch)
UserAOFStatus.namemismatch = resultSet.stringForColumn(kNameMismatch)
UserAOFStatus.signaturemismatch = resultSet.stringForColumn(kSignaturemismatch)
UserAOFStatus.banckaccmismatch = resultSet.stringForColumn(kBanckaccmismatch)
UserAOFStatus.ifscmismatch = resultSet.stringForColumn(kIFSCmismatch)
UserAOFStatus.pannummismatch = resultSet.stringForColumn(kPannummismatch)
UserAOFStatus.aoftype = resultSet.stringForColumn(kAOFtype)
UserAOFStatus.idS = resultSet.stringForColumn(kIdS)
marrStakeInfo.addObject(UserAOFStatus)
}
}
sharedInstanceDB.database!.close()
if marrStakeInfo.count==0 {
return false
}else{
return true
}
}
func getSignUpStatusRecord(UserAOFStatus : AOFStatus) -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_AOFStatus_MASTER) WHERE \(kClientID)=\(UserAOFStatus.ClientID) AND \(kAOFtype)=0", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let UserAOFStatus : AOFStatus = AOFStatus()
UserAOFStatus.ClientID = resultSet.stringForColumn(kClientID)
UserAOFStatus.pancopy = resultSet.stringForColumn(kPanCopy)
UserAOFStatus.chequecopy = resultSet.stringForColumn(kChequeCopy)
UserAOFStatus.selfie = resultSet.stringForColumn(kSelfie)
UserAOFStatus.dobmismatch = resultSet.stringForColumn(kDobmismatch)
UserAOFStatus.namemismatch = resultSet.stringForColumn(kNameMismatch)
UserAOFStatus.signaturemismatch = resultSet.stringForColumn(kSignaturemismatch)
UserAOFStatus.banckaccmismatch = resultSet.stringForColumn(kBanckaccmismatch)
UserAOFStatus.ifscmismatch = resultSet.stringForColumn(kIFSCmismatch)
UserAOFStatus.pannummismatch = resultSet.stringForColumn(kPannummismatch)
UserAOFStatus.aoftype = resultSet.stringForColumn(kAOFtype)
UserAOFStatus.idS = resultSet.stringForColumn(kIdS)
marrStakeInfo.addObject(UserAOFStatus)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func getInvetmentAOFRecord(UserAOFStatus : AOFStatus) -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_AOFStatus_MASTER) WHERE \(kClientID)=\(UserAOFStatus.ClientID) AND \(kAOFtype)=1", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let UserAOFStatus : AOFStatus = AOFStatus()
UserAOFStatus.ClientID = resultSet.stringForColumn(kClientID)
UserAOFStatus.pancopy = resultSet.stringForColumn(kPanCopy)
UserAOFStatus.chequecopy = resultSet.stringForColumn(kChequeCopy)
UserAOFStatus.selfie = resultSet.stringForColumn(kSelfie)
UserAOFStatus.dobmismatch = resultSet.stringForColumn(kDobmismatch)
UserAOFStatus.namemismatch = resultSet.stringForColumn(kNameMismatch)
UserAOFStatus.signaturemismatch = resultSet.stringForColumn(kSignaturemismatch)
UserAOFStatus.banckaccmismatch = resultSet.stringForColumn(kBanckaccmismatch)
UserAOFStatus.ifscmismatch = resultSet.stringForColumn(kIFSCmismatch)
UserAOFStatus.pannummismatch = resultSet.stringForColumn(kPannummismatch)
UserAOFStatus.aoftype = resultSet.stringForColumn(kAOFtype)
UserAOFStatus.idS = resultSet.stringForColumn(kIdS)
marrStakeInfo.addObject(UserAOFStatus)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func addOrder(OrderInfo : Order) -> Bool {
sharedInstanceDB.database!.open()
// OrderInfo.AppOrderID = "1234"
// OrderInfo.ServerOrderID = "Default"
// OrderInfo.ClientID = "Default"
// OrderInfo.FolioNo = "Default"
// OrderInfo.FolioCheckDigit = "Default"
// OrderInfo.RtaAmcCode = "Default"
// OrderInfo.SrcSchemeCode = "Default"
// OrderInfo.SrcSchemeName = "Default"
// OrderInfo.TarSchemeCode = "Default"
// OrderInfo.TarSchemeName = "Default"
// OrderInfo.DividendOption = "Default"
// OrderInfo.VolumeType = "Default"
// OrderInfo.Volume = "Default"
// OrderInfo.OrderType = "Default"
// OrderInfo.OrderStatus = "Default"
// OrderInfo.AppOrderTimeStamp = "Default"
// OrderInfo.CartFlag = "Default"
// OrderInfo.UpdateTime = "Default"
let isInserted = sharedInstanceDB.database?.executeUpdate("INSERT INTO \(DB_TBL_ORDER_MASTER) (\(kServerOrderID), \(kClientID), \(kFolioNo), \(kFolioCheckDigit), \(kRtaAmcCode), \(kSrcSchemeCode), \(kSrcSchemeName), \(kTarSchemeCode), \(kTarSchemeName), \(kDividendOption), \(kVolumeType), \(kVolume), \(kOrderType), \(kOrderStatus), \(kAppOrderTimeStamp), \(kCartFlag), \(kUpdateTime)) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", withArgumentsInArray: [OrderInfo.ServerOrderID,OrderInfo.ClientID,OrderInfo.FolioNo,OrderInfo.FolioCheckDigit,OrderInfo.RtaAmcCode,OrderInfo.SrcSchemeCode,OrderInfo.SrcSchemeName,OrderInfo.TarSchemeCode,OrderInfo.TarSchemeName,OrderInfo.DividendOption,OrderInfo.VolumeType,OrderInfo.Volume,OrderInfo.OrderType,OrderInfo.OrderStatus,OrderInfo.AppOrderTimeStamp,OrderInfo.CartFlag,OrderInfo.UpdateTime])
sharedInstanceDB.database?.close()
return isInserted!
}
func updateOrder(OrderInfo : Order) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("UPDATE \(DB_TBL_ORDER_MASTER) SET \(kServerOrderID)=?, \(kClientID)=?, \(kFolioNo)=?, \(kFolioCheckDigit)=?, \(kRtaAmcCode)=?, \(kSrcSchemeCode)=?, \(kSrcSchemeName)=?, \(kTarSchemeCode)=?, \(kTarSchemeName)=?, \(kDividendOption)=?, \(kVolumeType)=?, \(kVolume)=?, \(kOrderType)=?, \(kOrderStatus)=?, \(kAppOrderTimeStamp)=?, \(kCartFlag)=?, \(kUpdateTime)=? WHERE \(kAppOrderID)=?", withArgumentsInArray: [OrderInfo.ServerOrderID,OrderInfo.ClientID,OrderInfo.FolioNo,OrderInfo.FolioCheckDigit,OrderInfo.RtaAmcCode,OrderInfo.SrcSchemeCode,OrderInfo.SrcSchemeName,OrderInfo.TarSchemeCode,OrderInfo.TarSchemeName,OrderInfo.DividendOption,OrderInfo.VolumeType,OrderInfo.Volume,OrderInfo.OrderType,OrderInfo.OrderStatus,OrderInfo.AppOrderTimeStamp,OrderInfo.CartFlag,OrderInfo.UpdateTime,OrderInfo.AppOrderID])
sharedInstanceDB.database?.close()
return isInserted!
}
func getAllOrder() -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_ORDER_MASTER)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let userInfo : Order = Order()
userInfo.AppOrderID = resultSet.stringForColumn(kAppOrderID)
userInfo.ServerOrderID = resultSet.stringForColumn(kServerOrderID)
userInfo.ClientID = resultSet.stringForColumn(kClientID)
userInfo.FolioNo = resultSet.stringForColumn(kFolioNo)
userInfo.FolioCheckDigit = resultSet.stringForColumn(kFolioCheckDigit)
userInfo.RtaAmcCode = resultSet.stringForColumn(kRtaAmcCode)
userInfo.SrcSchemeCode = resultSet.stringForColumn(kSrcSchemeCode)
userInfo.SrcSchemeName = resultSet.stringForColumn(kSrcSchemeName)
userInfo.TarSchemeCode = resultSet.stringForColumn(kTarSchemeCode)
userInfo.TarSchemeName = resultSet.stringForColumn(kTarSchemeName)
userInfo.DividendOption = resultSet.stringForColumn(kDividendOption)
userInfo.VolumeType = resultSet.stringForColumn(kVolumeType)
userInfo.Volume = resultSet.stringForColumn(kVolume)
userInfo.OrderType = resultSet.stringForColumn(kOrderType)
userInfo.OrderStatus = resultSet.stringForColumn(kOrderStatus)
userInfo.AppOrderTimeStamp = resultSet.stringForColumn(kAppOrderTimeStamp)
userInfo.CartFlag = resultSet.stringForColumn(kCartFlag)
userInfo.UpdateTime = resultSet.stringForColumn(kUpdateTime)
marrStakeInfo.addObject(userInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func getLatestOrder() -> NSMutableArray {
sharedInstanceDB.database!.open()
// SELECT * FROM OrderMaster ORDER BY AppOrderID DESC LIMIT 1
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_ORDER_MASTER) ORDER BY AppOrderID DESC LIMIT 1", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let userInfo : Order = Order()
userInfo.AppOrderID = resultSet.stringForColumn(kAppOrderID)
userInfo.ServerOrderID = resultSet.stringForColumn(kServerOrderID)
userInfo.ClientID = resultSet.stringForColumn(kClientID)
userInfo.FolioNo = resultSet.stringForColumn(kFolioNo)
userInfo.FolioCheckDigit = resultSet.stringForColumn(kFolioCheckDigit)
userInfo.RtaAmcCode = resultSet.stringForColumn(kRtaAmcCode)
userInfo.SrcSchemeCode = resultSet.stringForColumn(kSrcSchemeCode)
userInfo.SrcSchemeName = resultSet.stringForColumn(kSrcSchemeName)
userInfo.TarSchemeCode = resultSet.stringForColumn(kTarSchemeCode)
userInfo.TarSchemeName = resultSet.stringForColumn(kTarSchemeName)
userInfo.DividendOption = resultSet.stringForColumn(kDividendOption)
userInfo.VolumeType = resultSet.stringForColumn(kVolumeType)
userInfo.Volume = resultSet.stringForColumn(kVolume)
userInfo.OrderType = resultSet.stringForColumn(kOrderType)
userInfo.OrderStatus = resultSet.stringForColumn(kOrderStatus)
userInfo.AppOrderTimeStamp = resultSet.stringForColumn(kAppOrderTimeStamp)
userInfo.CartFlag = resultSet.stringForColumn(kCartFlag)
userInfo.UpdateTime = resultSet.stringForColumn(kUpdateTime)
marrStakeInfo.addObject(userInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func checkOrderAlreadyExist(OrderInfo : Order) -> Bool {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_ORDER_MASTER) WHERE \(kServerOrderID)='\(OrderInfo.ServerOrderID)'", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let userInfo : Order = Order()
userInfo.AppOrderID = resultSet.stringForColumn(kAppOrderID)
userInfo.ServerOrderID = resultSet.stringForColumn(kServerOrderID)
marrStakeInfo.addObject(userInfo)
}
}
sharedInstanceDB.database!.close()
if marrStakeInfo.count==0 {
return false
}else{
return true
}
}
//MF_ACCOUNT
func addMFAccount(mfAccountInfo : MFAccount) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("INSERT INTO \(DB_TBL_MF_ACCOUNT) (\(kAccId), \(kclientid), \(kFolioNo), \(kRTAamcCode), \(kAmcName), \(kSchemeCode), \(kSchemeName), \(kDivOption), \(kpucharseUnits), \(kpuchaseNAV), \(kInvestmentAmount), \(kCurrentNAV), \(kNAVDate), \(kisDeleted)) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", withArgumentsInArray: [mfAccountInfo.AccId,mfAccountInfo.clientid,mfAccountInfo.FolioNo,mfAccountInfo.RTAamcCode,mfAccountInfo.AmcName,mfAccountInfo.SchemeCode,mfAccountInfo.SchemeName,mfAccountInfo.DivOption,mfAccountInfo.pucharseUnits,mfAccountInfo.puchaseNAV,mfAccountInfo.InvestmentAmount,mfAccountInfo.CurrentNAV,mfAccountInfo.NAVDate,mfAccountInfo.isDeleted])
sharedInstanceDB.database?.close()
return isInserted!
}
func updateMFAccount(mfAccountInfo : MFAccount) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("UPDATE \(DB_TBL_MF_ACCOUNT) SET \(kclientid)=?, \(kFolioNo)=?, \(kRTAamcCode)=?, \(kAmcName)=?, \(kSchemeCode)=?, \(kSchemeName)=?, \(kDivOption)=?, \(kpucharseUnits)=?, \(kpuchaseNAV)=?, \(kInvestmentAmount)=?, \(kCurrentNAV)=?, \(kNAVDate)=?, \(kisDeleted)=? WHERE \(kAccId)=?", withArgumentsInArray: [mfAccountInfo.clientid,mfAccountInfo.FolioNo,mfAccountInfo.RTAamcCode,mfAccountInfo.AmcName,mfAccountInfo.SchemeCode,mfAccountInfo.SchemeName,mfAccountInfo.DivOption,mfAccountInfo.pucharseUnits,mfAccountInfo.puchaseNAV,mfAccountInfo.InvestmentAmount,mfAccountInfo.CurrentNAV,mfAccountInfo.NAVDate,mfAccountInfo.isDeleted,mfAccountInfo.AccId])
sharedInstanceDB.database?.close()
return isInserted!
}
func getMFAccounts() -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MF_ACCOUNT) WHERE pucharseUnits<>0 AND isDeleted=0", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFAccount = MFAccount()
mfAccountInfo.AccId = resultSet.stringForColumn(kAccId)
mfAccountInfo.clientid = resultSet.stringForColumn(kclientid)
mfAccountInfo.FolioNo = resultSet.stringForColumn(kFolioNo)
mfAccountInfo.RTAamcCode = resultSet.stringForColumn(kRTAamcCode)
mfAccountInfo.AmcName = resultSet.stringForColumn(kAmcName)
mfAccountInfo.SchemeCode = resultSet.stringForColumn(kSchemeCode)
mfAccountInfo.SchemeName = resultSet.stringForColumn(kSchemeName)
mfAccountInfo.DivOption = resultSet.stringForColumn(kDivOption)
mfAccountInfo.pucharseUnits = resultSet.stringForColumn(kpucharseUnits)
mfAccountInfo.puchaseNAV = resultSet.stringForColumn(kpuchaseNAV)
mfAccountInfo.InvestmentAmount = resultSet.stringForColumn(kInvestmentAmount)
mfAccountInfo.CurrentNAV = resultSet.stringForColumn(kCurrentNAV)
mfAccountInfo.NAVDate = resultSet.stringForColumn(kNAVDate)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func getMFAccountsForRedeemCondition() -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MF_ACCOUNT) WHERE pucharseUnits<>0 AND isDeleted=0", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFAccount = MFAccount()
mfAccountInfo.AccId = resultSet.stringForColumn(kAccId)
mfAccountInfo.clientid = resultSet.stringForColumn(kclientid)
mfAccountInfo.FolioNo = resultSet.stringForColumn(kFolioNo)
mfAccountInfo.RTAamcCode = resultSet.stringForColumn(kRTAamcCode)
mfAccountInfo.AmcName = resultSet.stringForColumn(kAmcName)
mfAccountInfo.SchemeCode = resultSet.stringForColumn(kSchemeCode)
mfAccountInfo.SchemeName = resultSet.stringForColumn(kSchemeName)
mfAccountInfo.DivOption = resultSet.stringForColumn(kDivOption)
mfAccountInfo.pucharseUnits = resultSet.stringForColumn(kpucharseUnits)
mfAccountInfo.puchaseNAV = resultSet.stringForColumn(kpuchaseNAV)
mfAccountInfo.InvestmentAmount = resultSet.stringForColumn(kInvestmentAmount)
mfAccountInfo.CurrentNAV = resultSet.stringForColumn(kCurrentNAV)
mfAccountInfo.NAVDate = resultSet.stringForColumn(kNAVDate)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func checkMFAccountAlreadyExist(mfAccountInfo : MFAccount) -> Bool {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MF_ACCOUNT) WHERE \(kAccId)=\(mfAccountInfo.AccId)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFAccount = MFAccount()
mfAccountInfo.AccId = resultSet.stringForColumn(kAccId)
mfAccountInfo.clientid = resultSet.stringForColumn(kclientid)
mfAccountInfo.FolioNo = resultSet.stringForColumn(kFolioNo)
mfAccountInfo.RTAamcCode = resultSet.stringForColumn(kRTAamcCode)
mfAccountInfo.AmcName = resultSet.stringForColumn(kAmcName)
mfAccountInfo.SchemeCode = resultSet.stringForColumn(kSchemeCode)
mfAccountInfo.SchemeName = resultSet.stringForColumn(kSchemeName)
mfAccountInfo.DivOption = resultSet.stringForColumn(kDivOption)
mfAccountInfo.pucharseUnits = resultSet.stringForColumn(kpucharseUnits)
mfAccountInfo.puchaseNAV = resultSet.stringForColumn(kpuchaseNAV)
mfAccountInfo.InvestmentAmount = resultSet.stringForColumn(kInvestmentAmount)
mfAccountInfo.CurrentNAV = resultSet.stringForColumn(kCurrentNAV)
mfAccountInfo.NAVDate = resultSet.stringForColumn(kNAVDate)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
if marrStakeInfo.count==0 {
return false
}else{
return true
}
}
// func checkMFAccountAlreadyExistForSchemeCode(schemCode : String) -> Bool
// {
//
// sharedInstanceDB.database!.open()
//
// let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MF_ACCOUNT) WHERE \(kSchemeCode)=\(schemCode)", withArgumentsInArray: nil)
//
// let marrStakeInfo : NSMutableArray = NSMutableArray()
// if (resultSet != nil) {
// while resultSet.next() {
//
// let mfAccountInfo : MFAccount = MFAccount()
//
// mfAccountInfo.AccId = resultSet.stringForColumn(kAccId)
// mfAccountInfo.clientid = resultSet.stringForColumn(kclientid)
// mfAccountInfo.FolioNo = resultSet.stringForColumn(kFolioNo)
// mfAccountInfo.RTAamcCode = resultSet.stringForColumn(kRTAamcCode)
// mfAccountInfo.AmcName = resultSet.stringForColumn(kAmcName)
// mfAccountInfo.SchemeCode = resultSet.stringForColumn(kSchemeCode)
// mfAccountInfo.SchemeName = resultSet.stringForColumn(kSchemeName)
// mfAccountInfo.DivOption = resultSet.stringForColumn(kDivOption)
// mfAccountInfo.pucharseUnits = resultSet.stringForColumn(kpucharseUnits)
// mfAccountInfo.puchaseNAV = resultSet.stringForColumn(kpuchaseNAV)
// mfAccountInfo.InvestmentAmount = resultSet.stringForColumn(kInvestmentAmount)
// mfAccountInfo.CurrentNAV = resultSet.stringForColumn(kCurrentNAV)
// mfAccountInfo.NAVDate = resultSet.stringForColumn(kNAVDate)
// mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
//
// marrStakeInfo.addObject(mfAccountInfo)
// }
// }
//
// sharedInstanceDB.database!.close()
//
//
// if marrStakeInfo.count==0 {
// return false
// }else{
// return true
// }
// }
func checkMFAccountAlreadyExistForSchemeCode(schemCode : String, fundCode : String, ClientId : String) -> Bool
{
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MF_ACCOUNT) WHERE \(kSchemeCode)=\(schemCode) AND \(kRTAamcCode)=\(fundCode) AND \(kclientid)=\(ClientId)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFAccount = MFAccount()
mfAccountInfo.AccId = resultSet.stringForColumn(kAccId)
mfAccountInfo.clientid = resultSet.stringForColumn(kclientid)
mfAccountInfo.FolioNo = resultSet.stringForColumn(kFolioNo)
mfAccountInfo.RTAamcCode = resultSet.stringForColumn(kRTAamcCode)
mfAccountInfo.AmcName = resultSet.stringForColumn(kAmcName)
mfAccountInfo.SchemeCode = resultSet.stringForColumn(kSchemeCode)
mfAccountInfo.SchemeName = resultSet.stringForColumn(kSchemeName)
mfAccountInfo.DivOption = resultSet.stringForColumn(kDivOption)
mfAccountInfo.pucharseUnits = resultSet.stringForColumn(kpucharseUnits)
mfAccountInfo.puchaseNAV = resultSet.stringForColumn(kpuchaseNAV)
mfAccountInfo.InvestmentAmount = resultSet.stringForColumn(kInvestmentAmount)
mfAccountInfo.CurrentNAV = resultSet.stringForColumn(kCurrentNAV)
mfAccountInfo.NAVDate = resultSet.stringForColumn(kNAVDate)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
if marrStakeInfo.count==0 {
return false
}else{
return true
}
}
func getMFAccountDetailsFromAccID(mfAccountInfo : MFAccount) -> MFAccount {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MF_ACCOUNT) WHERE \(kAccId)=\(mfAccountInfo.AccId)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFAccount = MFAccount()
mfAccountInfo.AccId = resultSet.stringForColumn(kAccId)
mfAccountInfo.clientid = resultSet.stringForColumn(kclientid)
mfAccountInfo.FolioNo = resultSet.stringForColumn(kFolioNo)
mfAccountInfo.RTAamcCode = resultSet.stringForColumn(kRTAamcCode)
mfAccountInfo.AmcName = resultSet.stringForColumn(kAmcName)
mfAccountInfo.SchemeCode = resultSet.stringForColumn(kSchemeCode)
mfAccountInfo.SchemeName = resultSet.stringForColumn(kSchemeName)
mfAccountInfo.DivOption = resultSet.stringForColumn(kDivOption)
mfAccountInfo.pucharseUnits = resultSet.stringForColumn(kpucharseUnits)
mfAccountInfo.puchaseNAV = resultSet.stringForColumn(kpuchaseNAV)
mfAccountInfo.InvestmentAmount = resultSet.stringForColumn(kInvestmentAmount)
mfAccountInfo.CurrentNAV = resultSet.stringForColumn(kCurrentNAV)
mfAccountInfo.NAVDate = resultSet.stringForColumn(kNAVDate)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
if marrStakeInfo.count==0 {
return MFAccount()
}else{
return marrStakeInfo.objectAtIndex(0) as! MFAccount
}
}
//MF_TRANSACTIONS
func addMFTransaction(mfAccountInfo : MFTransaction) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("INSERT INTO \(DB_TBL_MF_TRANSACTION) (\(kTxnID), \(kAccID), \(kOrderId), \(kTxnOrderDateTime), \(kTxtType), \(kTxnpucharseUnits), \(kTxnpuchaseNAV), \(kTxnPurchaseAmount), \(kExecutaionDateTime), \(kisDeleted)) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", withArgumentsInArray: [mfAccountInfo.TxnID,mfAccountInfo.AccID,mfAccountInfo.OrderId,mfAccountInfo.TxnOrderDateTime,mfAccountInfo.TxtType,mfAccountInfo.TxnpucharseUnits,mfAccountInfo.TxnpuchaseNAV,mfAccountInfo.TxnPurchaseAmount,mfAccountInfo.ExecutaionDateTime,mfAccountInfo.isDeleted])
sharedInstanceDB.database?.close()
return isInserted!
}
func updateMFTransaction(mfAccountInfo : MFTransaction) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("UPDATE \(DB_TBL_MF_TRANSACTION) SET \(kAccID)=?, \(kOrderId)=?, \(kTxnOrderDateTime)=?, \(kTxtType)=?, \(kTxnpucharseUnits)=?, \(kTxnpuchaseNAV)=?, \(kTxnPurchaseAmount)=?, \(kExecutaionDateTime)=?, \(kisDeleted)=? WHERE \(kTxnID)=?", withArgumentsInArray: [mfAccountInfo.AccID,mfAccountInfo.OrderId,mfAccountInfo.TxnOrderDateTime,mfAccountInfo.TxtType,mfAccountInfo.TxnpucharseUnits,mfAccountInfo.TxnpuchaseNAV,mfAccountInfo.TxnPurchaseAmount,mfAccountInfo.ExecutaionDateTime,mfAccountInfo.isDeleted,mfAccountInfo.TxnID])
sharedInstanceDB.database?.close()
return isInserted!
}
func getMFTransactions() -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MF_TRANSACTION) WHERE isDeleted=0", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFTransaction = MFTransaction()
mfAccountInfo.TxnID = resultSet.stringForColumn(kTxnID)
mfAccountInfo.AccID = resultSet.stringForColumn(kAccID)
mfAccountInfo.OrderId = resultSet.stringForColumn(kOrderId)
mfAccountInfo.TxnOrderDateTime = resultSet.stringForColumn(kTxnOrderDateTime)
mfAccountInfo.TxtType = resultSet.stringForColumn(kTxtType)
mfAccountInfo.TxnpucharseUnits = resultSet.stringForColumn(kTxnpucharseUnits)
mfAccountInfo.TxnpuchaseNAV = resultSet.stringForColumn(kTxnpuchaseNAV)
mfAccountInfo.TxnPurchaseAmount = resultSet.stringForColumn(kTxnPurchaseAmount)
mfAccountInfo.ExecutaionDateTime = resultSet.stringForColumn(kExecutaionDateTime)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func getMFTransactionsGroupByDate(mfAccountInfo : MFAccount) -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MF_TRANSACTION) WHERE isDeleted=0 AND \(kAccID)=\(mfAccountInfo.AccId) GROUP BY \(kExecutaionDateTime)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFTransaction = MFTransaction()
mfAccountInfo.TxnID = resultSet.stringForColumn(kTxnID)
mfAccountInfo.AccID = resultSet.stringForColumn(kAccID)
mfAccountInfo.OrderId = resultSet.stringForColumn(kOrderId)
mfAccountInfo.TxnOrderDateTime = resultSet.stringForColumn(kTxnOrderDateTime)
mfAccountInfo.TxtType = resultSet.stringForColumn(kTxtType)
mfAccountInfo.TxnpucharseUnits = resultSet.stringForColumn(kTxnpucharseUnits)
mfAccountInfo.TxnpuchaseNAV = resultSet.stringForColumn(kTxnpuchaseNAV)
mfAccountInfo.TxnPurchaseAmount = resultSet.stringForColumn(kTxnPurchaseAmount)
mfAccountInfo.ExecutaionDateTime = resultSet.stringForColumn(kExecutaionDateTime)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func getMFUTransactionsByAccountIDAndAfterDate(accId : String, date : String) -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MF_TRANSACTION) WHERE \(kAccID)=? AND \(kExecutaionDateTime)>? AND \(kisDeleted)=0 ORDER BY \(kExecutaionDateTime)", withArgumentsInArray: [accId, date])
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFTransaction = MFTransaction()
mfAccountInfo.TxnID = resultSet.stringForColumn(kTxnID)
mfAccountInfo.AccID = resultSet.stringForColumn(kAccID)
mfAccountInfo.OrderId = resultSet.stringForColumn(kOrderId)
mfAccountInfo.TxnOrderDateTime = resultSet.stringForColumn(kTxnOrderDateTime)
mfAccountInfo.TxtType = resultSet.stringForColumn(kTxtType)
mfAccountInfo.TxnpucharseUnits = resultSet.stringForColumn(kTxnpucharseUnits)
mfAccountInfo.TxnpuchaseNAV = resultSet.stringForColumn(kTxnpuchaseNAV)
mfAccountInfo.TxnPurchaseAmount = resultSet.stringForColumn(kTxnPurchaseAmount)
mfAccountInfo.ExecutaionDateTime = resultSet.stringForColumn(kExecutaionDateTime)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func getMFUTransactionsByAccountID(accId : String) -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MF_TRANSACTION) WHERE \(kAccID)=? AND \(kisDeleted)=0 ORDER BY \(kExecutaionDateTime)", withArgumentsInArray: [accId])
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFTransaction = MFTransaction()
mfAccountInfo.TxnID = resultSet.stringForColumn(kTxnID)
mfAccountInfo.AccID = resultSet.stringForColumn(kAccID)
mfAccountInfo.OrderId = resultSet.stringForColumn(kOrderId)
mfAccountInfo.TxnOrderDateTime = resultSet.stringForColumn(kTxnOrderDateTime)
mfAccountInfo.TxtType = resultSet.stringForColumn(kTxtType)
mfAccountInfo.TxnpucharseUnits = resultSet.stringForColumn(kTxnpucharseUnits)
mfAccountInfo.TxnpuchaseNAV = resultSet.stringForColumn(kTxnpuchaseNAV)
mfAccountInfo.TxnPurchaseAmount = resultSet.stringForColumn(kTxnPurchaseAmount)
mfAccountInfo.ExecutaionDateTime = resultSet.stringForColumn(kExecutaionDateTime)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func getManualMFUTransactionsByAccountID(accId : String) -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MANUAL_MF_TRANSACTION) WHERE \(kAccID)=? AND \(kisDeleted)=0 ORDER BY \(kExecutaionDateTime)", withArgumentsInArray: [accId])
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFTransaction = MFTransaction()
mfAccountInfo.TxnID = resultSet.stringForColumn(kTxnID)
mfAccountInfo.AccID = resultSet.stringForColumn(kAccID)
mfAccountInfo.OrderId = resultSet.stringForColumn(kOrderId)
mfAccountInfo.TxnOrderDateTime = resultSet.stringForColumn(kTxnOrderDateTime)
mfAccountInfo.TxtType = resultSet.stringForColumn(kTxtType)
mfAccountInfo.TxnpucharseUnits = resultSet.stringForColumn(kTxnpucharseUnits)
mfAccountInfo.TxnpuchaseNAV = resultSet.stringForColumn(kTxnpuchaseNAV)
mfAccountInfo.TxnPurchaseAmount = resultSet.stringForColumn(kTxnPurchaseAmount)
mfAccountInfo.ExecutaionDateTime = resultSet.stringForColumn(kExecutaionDateTime)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func getMFTransactionsByDate(date : String, mfAccountInfo : MFAccount) -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MF_TRANSACTION) WHERE isDeleted=0 AND \(kAccID)=\(mfAccountInfo.AccId) AND \(kExecutaionDateTime)='\(date)'", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFTransaction = MFTransaction()
mfAccountInfo.TxnID = resultSet.stringForColumn(kTxnID)
mfAccountInfo.AccID = resultSet.stringForColumn(kAccID)
mfAccountInfo.OrderId = resultSet.stringForColumn(kOrderId)
mfAccountInfo.TxnOrderDateTime = resultSet.stringForColumn(kTxnOrderDateTime)
mfAccountInfo.TxtType = resultSet.stringForColumn(kTxtType)
mfAccountInfo.TxnpucharseUnits = resultSet.stringForColumn(kTxnpucharseUnits)
mfAccountInfo.TxnpuchaseNAV = resultSet.stringForColumn(kTxnpuchaseNAV)
mfAccountInfo.TxnPurchaseAmount = resultSet.stringForColumn(kTxnPurchaseAmount)
mfAccountInfo.ExecutaionDateTime = resultSet.stringForColumn(kExecutaionDateTime)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func getMFTransactionsByServerOrderId(ordeRId : String) -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MF_TRANSACTION) WHERE \(kOrderId)='\(ordeRId)'", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFTransaction = MFTransaction()
mfAccountInfo.TxnID = resultSet.stringForColumn(kTxnID)
mfAccountInfo.AccID = resultSet.stringForColumn(kAccID)
mfAccountInfo.OrderId = resultSet.stringForColumn(kOrderId)
mfAccountInfo.TxnOrderDateTime = resultSet.stringForColumn(kTxnOrderDateTime)
mfAccountInfo.TxtType = resultSet.stringForColumn(kTxtType)
mfAccountInfo.TxnpucharseUnits = resultSet.stringForColumn(kTxnpucharseUnits)
mfAccountInfo.TxnpuchaseNAV = resultSet.stringForColumn(kTxnpuchaseNAV)
mfAccountInfo.TxnPurchaseAmount = resultSet.stringForColumn(kTxnPurchaseAmount)
mfAccountInfo.ExecutaionDateTime = resultSet.stringForColumn(kExecutaionDateTime)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func checkMFTransactionAlreadyExist(mfAccountInfo : MFTransaction) -> Bool {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MF_TRANSACTION) WHERE \(kTxnID)=\(mfAccountInfo.TxnID)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFTransaction = MFTransaction()
mfAccountInfo.TxnID = resultSet.stringForColumn(kTxnID)
mfAccountInfo.AccID = resultSet.stringForColumn(kAccID)
mfAccountInfo.OrderId = resultSet.stringForColumn(kOrderId)
mfAccountInfo.TxnOrderDateTime = resultSet.stringForColumn(kTxnOrderDateTime)
mfAccountInfo.TxtType = resultSet.stringForColumn(kTxtType)
mfAccountInfo.TxnpucharseUnits = resultSet.stringForColumn(kTxnpucharseUnits)
mfAccountInfo.TxnpuchaseNAV = resultSet.stringForColumn(kTxnpuchaseNAV)
mfAccountInfo.TxnPurchaseAmount = resultSet.stringForColumn(kTxnPurchaseAmount)
mfAccountInfo.ExecutaionDateTime = resultSet.stringForColumn(kExecutaionDateTime)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
if marrStakeInfo.count==0 {
return false
}else{
return true
}
}
// Manual MF Account
//MF_ACCOUNT
func addManualMFAccount(mfAccountInfo : MFAccount) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("INSERT INTO \(DB_TBL_MANUAL_MF_ACCOUNT) (\(kAccId), \(kclientid), \(kFolioNo), \(kRTAamcCode), \(kAmcName), \(kSchemeCode), \(kSchemeName), \(kDivOption), \(kpucharseUnits), \(kpuchaseNAV), \(kInvestmentAmount), \(kCurrentNAV), \(kNAVDate), \(kisDeleted)) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", withArgumentsInArray: [mfAccountInfo.AccId,mfAccountInfo.clientid,mfAccountInfo.FolioNo,mfAccountInfo.RTAamcCode,mfAccountInfo.AmcName,mfAccountInfo.SchemeCode,mfAccountInfo.SchemeName,mfAccountInfo.DivOption,mfAccountInfo.pucharseUnits,mfAccountInfo.puchaseNAV,mfAccountInfo.InvestmentAmount,mfAccountInfo.CurrentNAV,mfAccountInfo.NAVDate,mfAccountInfo.isDeleted])
sharedInstanceDB.database?.close()
return isInserted!
}
func updateManualMFAccount(mfAccountInfo : MFAccount) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("UPDATE \(DB_TBL_MANUAL_MF_ACCOUNT) SET \(kclientid)=?, \(kFolioNo)=?, \(kRTAamcCode)=?, \(kAmcName)=?, \(kSchemeCode)=?, \(kSchemeName)=?, \(kDivOption)=?, \(kpucharseUnits)=?, \(kpuchaseNAV)=?, \(kInvestmentAmount)=?, \(kCurrentNAV)=?, \(kNAVDate)=?, \(kisDeleted)=? WHERE \(kAccId)=?", withArgumentsInArray: [mfAccountInfo.clientid,mfAccountInfo.FolioNo,mfAccountInfo.RTAamcCode,mfAccountInfo.AmcName,mfAccountInfo.SchemeCode,mfAccountInfo.SchemeName,mfAccountInfo.DivOption,mfAccountInfo.pucharseUnits,mfAccountInfo.puchaseNAV,mfAccountInfo.InvestmentAmount,mfAccountInfo.CurrentNAV,mfAccountInfo.NAVDate,mfAccountInfo.isDeleted,mfAccountInfo.AccId])
sharedInstanceDB.database?.close()
return isInserted!
}
func deleteManualMFAccount(mfAccountInfo : MFAccount) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("UPDATE \(DB_TBL_MANUAL_MF_ACCOUNT) SET \(kisDeleted)=1 WHERE \(kAccId)=?", withArgumentsInArray: [mfAccountInfo.AccId])
sharedInstanceDB.database?.close()
return isInserted!
}
func getManualMFAccounts() -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MANUAL_MF_ACCOUNT) WHERE pucharseUnits<>0 AND isDeleted=0", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFAccount = MFAccount()
mfAccountInfo.AccId = resultSet.stringForColumn(kAccId)
mfAccountInfo.clientid = resultSet.stringForColumn(kclientid)
mfAccountInfo.FolioNo = resultSet.stringForColumn(kFolioNo)
mfAccountInfo.RTAamcCode = resultSet.stringForColumn(kRTAamcCode)
mfAccountInfo.AmcName = resultSet.stringForColumn(kAmcName)
mfAccountInfo.SchemeCode = resultSet.stringForColumn(kSchemeCode)
mfAccountInfo.SchemeName = resultSet.stringForColumn(kSchemeName)
mfAccountInfo.DivOption = resultSet.stringForColumn(kDivOption)
mfAccountInfo.pucharseUnits = resultSet.stringForColumn(kpucharseUnits)
mfAccountInfo.puchaseNAV = resultSet.stringForColumn(kpuchaseNAV)
mfAccountInfo.InvestmentAmount = resultSet.stringForColumn(kInvestmentAmount)
mfAccountInfo.CurrentNAV = resultSet.stringForColumn(kCurrentNAV)
mfAccountInfo.NAVDate = resultSet.stringForColumn(kNAVDate)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func checkManualMFAccountAlreadyExist(mfAccountInfo : MFAccount) -> Bool {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MANUAL_MF_ACCOUNT) WHERE \(kAccId)=\(mfAccountInfo.AccId)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFAccount = MFAccount()
mfAccountInfo.AccId = resultSet.stringForColumn(kAccId)
mfAccountInfo.clientid = resultSet.stringForColumn(kclientid)
mfAccountInfo.FolioNo = resultSet.stringForColumn(kFolioNo)
mfAccountInfo.RTAamcCode = resultSet.stringForColumn(kRTAamcCode)
mfAccountInfo.AmcName = resultSet.stringForColumn(kAmcName)
mfAccountInfo.SchemeCode = resultSet.stringForColumn(kSchemeCode)
mfAccountInfo.SchemeName = resultSet.stringForColumn(kSchemeName)
mfAccountInfo.DivOption = resultSet.stringForColumn(kDivOption)
mfAccountInfo.pucharseUnits = resultSet.stringForColumn(kpucharseUnits)
mfAccountInfo.puchaseNAV = resultSet.stringForColumn(kpuchaseNAV)
mfAccountInfo.InvestmentAmount = resultSet.stringForColumn(kInvestmentAmount)
mfAccountInfo.CurrentNAV = resultSet.stringForColumn(kCurrentNAV)
mfAccountInfo.NAVDate = resultSet.stringForColumn(kNAVDate)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
if marrStakeInfo.count==0 {
return false
}else{
return true
}
}
//MF_TRANSACTIONS
func getMFTransactionsGroupByDateFromManual(mfAccountInfo : MFAccount) -> NSMutableArray { // NEWLY
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MANUAL_MF_TRANSACTION) WHERE isDeleted=0 AND \(kAccID)=\(mfAccountInfo.AccId) GROUP BY \(kExecutaionDateTime)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFTransaction = MFTransaction()
mfAccountInfo.TxnID = resultSet.stringForColumn(kTxnID)
mfAccountInfo.AccID = resultSet.stringForColumn(kAccID)
mfAccountInfo.OrderId = resultSet.stringForColumn(kOrderId)
mfAccountInfo.TxnOrderDateTime = resultSet.stringForColumn(kTxnOrderDateTime)
mfAccountInfo.TxtType = resultSet.stringForColumn(kTxtType)
mfAccountInfo.TxnpucharseUnits = resultSet.stringForColumn(kTxnpucharseUnits)
mfAccountInfo.TxnpuchaseNAV = resultSet.stringForColumn(kTxnpuchaseNAV)
mfAccountInfo.TxnPurchaseAmount = resultSet.stringForColumn(kTxnPurchaseAmount)
mfAccountInfo.ExecutaionDateTime = resultSet.stringForColumn(kExecutaionDateTime)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func deleteManualMFTransaction(mfAccountInfo : MFTransaction) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("UPDATE \(DB_TBL_MANUAL_MF_TRANSACTION) SET \(kisDeleted)=1 WHERE \(kTxnID)=?", withArgumentsInArray: [mfAccountInfo.TxnID])
sharedInstanceDB.database?.close()
return isInserted!
}
func addManualMFTransaction(mfAccountInfo : MFTransaction) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("INSERT INTO \(DB_TBL_MANUAL_MF_TRANSACTION) (\(kTxnID), \(kAccID), \(kOrderId), \(kTxnOrderDateTime), \(kTxtType), \(kTxnpucharseUnits), \(kTxnpuchaseNAV), \(kTxnPurchaseAmount), \(kExecutaionDateTime), \(kisDeleted)) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", withArgumentsInArray: [mfAccountInfo.TxnID,mfAccountInfo.AccID,mfAccountInfo.OrderId,mfAccountInfo.TxnOrderDateTime,mfAccountInfo.TxtType,mfAccountInfo.TxnpucharseUnits,mfAccountInfo.TxnpuchaseNAV,mfAccountInfo.TxnPurchaseAmount,mfAccountInfo.ExecutaionDateTime,mfAccountInfo.isDeleted])
sharedInstanceDB.database?.close()
return isInserted!
}
func updateManualMFTransaction(mfAccountInfo : MFTransaction) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("UPDATE \(DB_TBL_MANUAL_MF_TRANSACTION) SET \(kAccID)=?, \(kOrderId)=?, \(kTxnOrderDateTime)=?, \(kTxtType)=?, \(kTxnpucharseUnits)=?, \(kTxnpuchaseNAV)=?, \(kTxnPurchaseAmount)=?, \(kExecutaionDateTime)=?, \(kisDeleted)=? WHERE \(kTxnID)=?", withArgumentsInArray: [mfAccountInfo.AccID,mfAccountInfo.OrderId,mfAccountInfo.TxnOrderDateTime,mfAccountInfo.TxtType,mfAccountInfo.TxnpucharseUnits,mfAccountInfo.TxnpuchaseNAV,mfAccountInfo.TxnPurchaseAmount,mfAccountInfo.ExecutaionDateTime,mfAccountInfo.isDeleted,mfAccountInfo.TxnID])
sharedInstanceDB.database?.close()
return isInserted!
}
func getManualMFTransactions() -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MANUAL_MF_TRANSACTION)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFTransaction = MFTransaction()
mfAccountInfo.TxnID = resultSet.stringForColumn(kTxnID)
mfAccountInfo.AccID = resultSet.stringForColumn(kAccID)
mfAccountInfo.OrderId = resultSet.stringForColumn(kOrderId)
mfAccountInfo.TxnOrderDateTime = resultSet.stringForColumn(kTxnOrderDateTime)
mfAccountInfo.TxtType = resultSet.stringForColumn(kTxtType)
mfAccountInfo.TxnpucharseUnits = resultSet.stringForColumn(kTxnpucharseUnits)
mfAccountInfo.TxnpuchaseNAV = resultSet.stringForColumn(kTxnpuchaseNAV)
mfAccountInfo.TxnPurchaseAmount = resultSet.stringForColumn(kTxnPurchaseAmount)
mfAccountInfo.ExecutaionDateTime = resultSet.stringForColumn(kExecutaionDateTime)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func getMFUTransactionsByAccountIDFromManual(accId : String) -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MANUAL_MF_TRANSACTION) WHERE \(kAccID)=? AND \(kisDeleted)=0 ORDER BY \(kExecutaionDateTime)", withArgumentsInArray: [accId])
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFTransaction = MFTransaction()
mfAccountInfo.TxnID = resultSet.stringForColumn(kTxnID)
mfAccountInfo.AccID = resultSet.stringForColumn(kAccID)
mfAccountInfo.OrderId = resultSet.stringForColumn(kOrderId)
mfAccountInfo.TxnOrderDateTime = resultSet.stringForColumn(kTxnOrderDateTime)
mfAccountInfo.TxtType = resultSet.stringForColumn(kTxtType)
mfAccountInfo.TxnpucharseUnits = resultSet.stringForColumn(kTxnpucharseUnits)
mfAccountInfo.TxnpuchaseNAV = resultSet.stringForColumn(kTxnpuchaseNAV)
mfAccountInfo.TxnPurchaseAmount = resultSet.stringForColumn(kTxnPurchaseAmount)
mfAccountInfo.ExecutaionDateTime = resultSet.stringForColumn(kExecutaionDateTime)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func getMFTransactionsByDateFromManual(date : String, mfAccountInfo : MFAccount) -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MANUAL_MF_TRANSACTION) WHERE isDeleted=0 AND \(kAccID)=\(mfAccountInfo.AccId) AND \(kExecutaionDateTime)='\(date)'", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFTransaction = MFTransaction()
mfAccountInfo.TxnID = resultSet.stringForColumn(kTxnID)
mfAccountInfo.AccID = resultSet.stringForColumn(kAccID)
mfAccountInfo.OrderId = resultSet.stringForColumn(kOrderId)
mfAccountInfo.TxnOrderDateTime = resultSet.stringForColumn(kTxnOrderDateTime)
mfAccountInfo.TxtType = resultSet.stringForColumn(kTxtType)
mfAccountInfo.TxnpucharseUnits = resultSet.stringForColumn(kTxnpucharseUnits)
mfAccountInfo.TxnpuchaseNAV = resultSet.stringForColumn(kTxnpuchaseNAV)
mfAccountInfo.TxnPurchaseAmount = resultSet.stringForColumn(kTxnPurchaseAmount)
mfAccountInfo.ExecutaionDateTime = resultSet.stringForColumn(kExecutaionDateTime)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func checkManualMFTransactionAlreadyExist(mfAccountInfo : MFTransaction) -> Bool {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_MANUAL_MF_TRANSACTION) WHERE \(kTxnID)=\(mfAccountInfo.TxnID)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MFTransaction = MFTransaction()
mfAccountInfo.TxnID = resultSet.stringForColumn(kTxnID)
mfAccountInfo.AccID = resultSet.stringForColumn(kAccID)
mfAccountInfo.OrderId = resultSet.stringForColumn(kOrderId)
mfAccountInfo.TxnOrderDateTime = resultSet.stringForColumn(kTxnOrderDateTime)
mfAccountInfo.TxtType = resultSet.stringForColumn(kTxtType)
mfAccountInfo.TxnpucharseUnits = resultSet.stringForColumn(kTxnpucharseUnits)
mfAccountInfo.TxnpuchaseNAV = resultSet.stringForColumn(kTxnpuchaseNAV)
mfAccountInfo.TxnPurchaseAmount = resultSet.stringForColumn(kTxnPurchaseAmount)
mfAccountInfo.ExecutaionDateTime = resultSet.stringForColumn(kExecutaionDateTime)
mfAccountInfo.isDeleted = resultSet.stringForColumn(kisDeleted)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
if marrStakeInfo.count==0 {
return false
}else{
return true
}
}
// GET Systematic Order Details
func addOrderSystematic(OrderInfo : OrderSystematic) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("INSERT INTO \(DB_TBL_ORDER_SYSTEMATIC_MASTER) (\(kAppOrderID), \(kFrequency), \(kDay), \(kStart_Month), \(kStart_Year), \(kEnd_Month), \(kEnd_Year), \(kNoOfInstallments), \(kFirstPaymentAmount), \(kFirstPaymentFlag)) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", withArgumentsInArray: [OrderInfo.AppOrderID,OrderInfo.Frequency,OrderInfo.Day,OrderInfo.Start_Month,OrderInfo.Start_Year,OrderInfo.End_Month,OrderInfo.End_Year,OrderInfo.NoOfInstallments,OrderInfo.FirstPaymentAmount,OrderInfo.FirstPaymentFlag])
sharedInstanceDB.database?.close()
return isInserted!
}
func updateOrderSystematic(OrderInfo : OrderSystematic) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("UPDATE \(DB_TBL_ORDER_SYSTEMATIC_MASTER) SET \(kFrequency)=?, \(kDay)=?, \(kStart_Month)=?, \(kStart_Year)=?, \(kEnd_Month)=?, \(kEnd_Year)=?, \(kNoOfInstallments)=?, \(kFirstPaymentAmount)=?, \(kFirstPaymentFlag)=? WHERE \(kAppOrderID)=?", withArgumentsInArray: [OrderInfo.Frequency,OrderInfo.Day,OrderInfo.Start_Month,OrderInfo.Start_Year,OrderInfo.End_Month,OrderInfo.End_Year,OrderInfo.NoOfInstallments,OrderInfo.FirstPaymentAmount,OrderInfo.FirstPaymentFlag,OrderInfo.AppOrderID])
sharedInstanceDB.database?.close()
return isInserted!
}
func getAllOrderSystematic() -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_ORDER_SYSTEMATIC_MASTER)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let userInfo : OrderSystematic = OrderSystematic()
userInfo.AppOrderID = resultSet.stringForColumn(kAppOrderID)
userInfo.Frequency = resultSet.stringForColumn(kFrequency)
userInfo.Day = resultSet.stringForColumn(kDay)
userInfo.Start_Month = resultSet.stringForColumn(kStart_Month)
userInfo.Start_Year = resultSet.stringForColumn(kStart_Year)
userInfo.End_Month = resultSet.stringForColumn(kEnd_Month)
userInfo.End_Year = resultSet.stringForColumn(kEnd_Year)
userInfo.NoOfInstallments = resultSet.stringForColumn(kNoOfInstallments)
userInfo.FirstPaymentAmount = resultSet.stringForColumn(kFirstPaymentAmount)
userInfo.FirstPaymentFlag = resultSet.stringForColumn(kFirstPaymentFlag)
marrStakeInfo.addObject(userInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func getSystematicOrderByAppOrderId(objOrder : Order) -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_ORDER_SYSTEMATIC_MASTER) WHERE \(kAppOrderID)=\(objOrder.AppOrderID)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let userInfo : OrderSystematic = OrderSystematic()
userInfo.AppOrderID = resultSet.stringForColumn(kAppOrderID)
userInfo.Frequency = resultSet.stringForColumn(kFrequency)
userInfo.Day = resultSet.stringForColumn(kDay)
userInfo.Start_Month = resultSet.stringForColumn(kStart_Month)
userInfo.Start_Year = resultSet.stringForColumn(kStart_Year)
userInfo.End_Month = resultSet.stringForColumn(kEnd_Month)
userInfo.End_Year = resultSet.stringForColumn(kEnd_Year)
userInfo.NoOfInstallments = resultSet.stringForColumn(kNoOfInstallments)
userInfo.FirstPaymentAmount = resultSet.stringForColumn(kFirstPaymentAmount)
userInfo.FirstPaymentFlag = resultSet.stringForColumn(kFirstPaymentFlag)
marrStakeInfo.addObject(userInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func checkOrderSystematicAlreadyExist(OrderInfo : OrderSystematic) -> Bool {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_ORDER_SYSTEMATIC_MASTER) WHERE \(kAppOrderID)=\(OrderInfo.AppOrderID)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : OrderSystematic = OrderSystematic()
mfAccountInfo.AppOrderID = resultSet.stringForColumn(kAppOrderID)
mfAccountInfo.Frequency = resultSet.stringForColumn(kFrequency)
mfAccountInfo.Day = resultSet.stringForColumn(kDay)
mfAccountInfo.Start_Month = resultSet.stringForColumn(kStart_Month)
mfAccountInfo.Start_Year = resultSet.stringForColumn(kStart_Year)
mfAccountInfo.End_Month = resultSet.stringForColumn(kEnd_Month)
mfAccountInfo.End_Year = resultSet.stringForColumn(kEnd_Year)
mfAccountInfo.NoOfInstallments = resultSet.stringForColumn(kNoOfInstallments)
mfAccountInfo.FirstPaymentAmount = resultSet.stringForColumn(kFirstPaymentAmount)
mfAccountInfo.FirstPaymentFlag = resultSet.stringForColumn(kFirstPaymentFlag)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
if marrStakeInfo.count==0 {
return false
}else{
return true
}
}
// Dynamic Text
func addDynamiText(dynamicText : DynamicText) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("INSERT INTO \(DB_TBL_DYNAMIC_TEXT) (\(kText_type), \(kTitle), \(kText)) VALUES (?, ?, ?)", withArgumentsInArray: [dynamicText.text_type,dynamicText.title,dynamicText.text])
sharedInstanceDB.database?.close()
return isInserted!
}
func updateDynamicText(dynamicText : DynamicText) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("UPDATE \(DB_TBL_DYNAMIC_TEXT) SET \(kTitle)=?, \(kText)=? WHERE \(kText_type)=?", withArgumentsInArray: [dynamicText.title,dynamicText.text,dynamicText.text_type])
sharedInstanceDB.database?.close()
return isInserted!
}
func getDynamicText(textType : SyncDynamicTextType) -> DynamicText {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_DYNAMIC_TEXT) WHERE \(kText_type) = \(textType.hashValue)" , withArgumentsInArray: nil)
let dynamicText : DynamicText = DynamicText()
if (resultSet != nil) {
while resultSet.next() {
dynamicText.text_type = resultSet.stringForColumn(kText_type)
dynamicText.title = resultSet.stringForColumn(kTitle)
dynamicText.text = resultSet.stringForColumn(kText)
}
}
sharedInstanceDB.database!.close()
return dynamicText
}
func getAllDynamicText() -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_DYNAMIC_TEXT)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : DynamicText = DynamicText()
mfAccountInfo.text_type = resultSet.stringForColumn(kText_type)
mfAccountInfo.title = resultSet.stringForColumn(kTitle)
mfAccountInfo.text = resultSet.stringForColumn(kText)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func checkDynamicTextAlreadyExist(dynamicText : DynamicText) -> Bool {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_DYNAMIC_TEXT) WHERE \(kText_type)=\(dynamicText.text_type)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : DynamicText = DynamicText()
mfAccountInfo.text_type = resultSet.stringForColumn(kText_type)
mfAccountInfo.title = resultSet.stringForColumn(kTitle)
mfAccountInfo.text = resultSet.stringForColumn(kText)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
if marrStakeInfo.count==0 {
return false
}else{
return true
}
}
// PayEzzMandate
func addPayEzzMandate(payMandate : PayEzzMandate) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("INSERT INTO \(DB_TBL_PAY_EZZ_MANDATE) (\(kMandateID), \(kclientID), \(ksubSeq_invAccType),\(ksubSeq_invAccNo),\(ksubSeq_micrNo),\(ksubSeq_ifscCode),\(ksubSeq_bankId),\(ksubSeq_maximumAmount),\(ksubSeq_perpetualFlag),\(ksubSeq_startDate),\(ksubSeq_endDate),\(ksubSeq_paymentRefNo),\(kFilePath),\(kAndroidAppSync),\(kPayEzzStatus)) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", withArgumentsInArray: [payMandate.MandateID,payMandate.clientID,payMandate.subSeq_invAccType,payMandate.subSeq_invAccNo,payMandate.subSeq_micrNo,payMandate.subSeq_ifscCode,payMandate.subSeq_bankId,payMandate.subSeq_maximumAmount,payMandate.subSeq_perpetualFlag,payMandate.subSeq_startDate,payMandate.subSeq_endDate,payMandate.subSeq_paymentRefNo,payMandate.FilePath,payMandate.AndroidAppSync,payMandate.PayEzzStatus])
sharedInstanceDB.database?.close()
return isInserted!
}
func updatePayEzzMandate(payMandate : PayEzzMandate) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("UPDATE \(DB_TBL_PAY_EZZ_MANDATE) SET \(kclientID)=?, \(ksubSeq_invAccType)=?,\(ksubSeq_invAccNo)=?,\(ksubSeq_micrNo)=?,\(ksubSeq_ifscCode)=?,\(ksubSeq_bankId)=?,\(ksubSeq_maximumAmount)=?,\(ksubSeq_perpetualFlag)=?,\(ksubSeq_startDate)=?,\(ksubSeq_endDate)=?,\(ksubSeq_paymentRefNo)=?,\(kFilePath)=?,\(kAndroidAppSync)=?,\(kPayEzzStatus)=? WHERE \(kMandateID)=?", withArgumentsInArray: [payMandate.clientID,payMandate.subSeq_invAccType,payMandate.subSeq_invAccNo,payMandate.subSeq_micrNo,payMandate.subSeq_ifscCode,payMandate.subSeq_bankId,payMandate.subSeq_maximumAmount,payMandate.subSeq_perpetualFlag,payMandate.subSeq_startDate,payMandate.subSeq_endDate,payMandate.subSeq_paymentRefNo,payMandate.FilePath,payMandate.AndroidAppSync,payMandate.PayEzzStatus,payMandate.MandateID])
sharedInstanceDB.database?.close()
return isInserted!
}
func getAllPayEzzMandate() -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_PAY_EZZ_MANDATE)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : PayEzzMandate = PayEzzMandate()
mfAccountInfo.MandateID = resultSet.stringForColumn(kMandateID)
mfAccountInfo.clientID = resultSet.stringForColumn(kclientID)
mfAccountInfo.subSeq_invAccType = resultSet.stringForColumn(ksubSeq_invAccType)
mfAccountInfo.subSeq_invAccNo = resultSet.stringForColumn(ksubSeq_invAccNo)
mfAccountInfo.subSeq_micrNo = resultSet.stringForColumn(ksubSeq_micrNo)
mfAccountInfo.subSeq_ifscCode = resultSet.stringForColumn(ksubSeq_ifscCode)
mfAccountInfo.subSeq_bankId = resultSet.stringForColumn(ksubSeq_bankId)
mfAccountInfo.subSeq_maximumAmount = resultSet.stringForColumn(ksubSeq_maximumAmount)
mfAccountInfo.subSeq_perpetualFlag = resultSet.stringForColumn(ksubSeq_perpetualFlag)
mfAccountInfo.subSeq_startDate = resultSet.stringForColumn(ksubSeq_startDate)
mfAccountInfo.subSeq_endDate = resultSet.stringForColumn(ksubSeq_endDate)
mfAccountInfo.subSeq_paymentRefNo = resultSet.stringForColumn(ksubSeq_paymentRefNo)
mfAccountInfo.FilePath = resultSet.stringForColumn(kFilePath)
mfAccountInfo.AndroidAppSync = resultSet.stringForColumn(kAndroidAppSync)
mfAccountInfo.PayEzzStatus = resultSet.stringForColumn(kPayEzzStatus)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
func checkPayEzzMandateAlreadyExist(payMandate : PayEzzMandate) -> Bool {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_PAY_EZZ_MANDATE) WHERE \(kMandateID)=\(payMandate.MandateID)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : PayEzzMandate = PayEzzMandate()
mfAccountInfo.MandateID = resultSet.stringForColumn(kMandateID)
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
if marrStakeInfo.count==0 {
return false
}else{
return true
}
}
// WORTH TABLE ENTRY.......MARK: COMMENT
func addorUpdateMFU_WORTH(mfAccountInfo : MfuPortfolioWorth) -> Bool {
sharedInstanceDB.database!.open()
var isInserted = sharedInstanceDB.database?.executeUpdate("INSERT INTO \(DB_TBL_mfuPortfolioWorthTable) (\(kportfolio_date), \(kAccID), \(kpucharseUnits), \(kCurrentNAV), \(kCurrentValue), \(kIsTransaction)) VALUES (?, ?, ?, ?, ?, ?)", withArgumentsInArray: [mfAccountInfo.portfolio_date, mfAccountInfo.AccId, mfAccountInfo.pucharseUnits,mfAccountInfo.CurrentNAV,mfAccountInfo.CurrentValue,mfAccountInfo.isTransaction])
if !isInserted!
{
isInserted = sharedInstanceDB.database?.executeUpdate("UPDATE \(DB_TBL_mfuPortfolioWorthTable) SET \(kpucharseUnits) = ?, \(kCurrentNAV) = ?, \(kCurrentValue) = ?, \(kIsTransaction) = ? WHERE \(kportfolio_date) = ? AND \(kAccID) = ?",withArgumentsInArray: [mfAccountInfo.pucharseUnits,mfAccountInfo.CurrentNAV,mfAccountInfo.CurrentValue, mfAccountInfo.isTransaction, mfAccountInfo.portfolio_date, mfAccountInfo.AccId])
}
sharedInstanceDB.database?.close()
return isInserted!
}
func addorUpdateManualMFU_WORTH(mfAccountInfo : MfuPortfolioWorth) -> Bool {
sharedInstanceDB.database!.open()
var isInserted = sharedInstanceDB.database?.executeUpdate("INSERT INTO \(DB_TBL_mfuPortfolioManualWorthTable) (\(kportfolio_date), \(kAccID), \(kpucharseUnits), \(kCurrentNAV), \(kCurrentValue), \(kIsTransaction)) VALUES (?, ?, ?, ?, ?, ?)", withArgumentsInArray: [mfAccountInfo.portfolio_date, mfAccountInfo.AccId, mfAccountInfo.pucharseUnits,mfAccountInfo.CurrentNAV,mfAccountInfo.CurrentValue,mfAccountInfo.isTransaction])
if !isInserted!
{
isInserted = sharedInstanceDB.database?.executeUpdate("UPDATE \(DB_TBL_mfuPortfolioManualWorthTable) SET \(kpucharseUnits) = ?, \(kCurrentNAV) = ?, \(kCurrentValue) = ?, \(kIsTransaction) = ? WHERE \(kportfolio_date) = ? AND \(kAccID) = ?",withArgumentsInArray: [mfAccountInfo.pucharseUnits,mfAccountInfo.CurrentNAV,mfAccountInfo.CurrentValue, mfAccountInfo.isTransaction, mfAccountInfo.portfolio_date, mfAccountInfo.AccId])
}
sharedInstanceDB.database?.close()
return isInserted!
}
/* func updateMFU_WORTH(mfAccountInfo : MfuPortfolioWorth) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("UPDATE \(DB_TBL_mfuPortfolioWorthTable) SET \(kAccID)=?, \(kOrderId)=?, \(kTxnOrderDateTime)=?, \(kTxtType)=?, \(kTxnpucharseUnits)=?, \(kTxnpuchaseNAV)=?, \(kTxnPurchaseAmount)=?, \(kExecutaionDateTime)=?, \(kisDeleted)=? WHERE \(kTxnID)=?", withArgumentsInArray: [mfAccountInfo.AccID,mfAccountInfo.OrderId,mfAccountInfo.TxnOrderDateTime,mfAccountInfo.TxtType,mfAccountInfo.TxnpucharseUnits,mfAccountInfo.TxnpuchaseNAV,mfAccountInfo.TxnPurchaseAmount,mfAccountInfo.ExecutaionDateTime,mfAccountInfo.isDeleted,mfAccountInfo.TxnID])
sharedInstanceDB.database?.close()
return isInserted!
}
*/
func updateMFUMutualFundAccountNAVAndDate(accId : String, currentNAV : String, lastUpdatedDate : String) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("UPDATE \(DB_TBL_mfuPortfolioWorthTable) SET \(kCurrentNAV)=?, \(kportfolio_date)=? WHERE \(kAccID)=?", withArgumentsInArray: [currentNAV,lastUpdatedDate,accId])
sharedInstanceDB.database?.close()
return isInserted!
}
func getMFU_WORTH() -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_mfuPortfolioWorthTable)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MfuPortfolioWorth = MfuPortfolioWorth()
mfAccountInfo.portfolio_date = resultSet.stringForColumn(kportfolio_date)
mfAccountInfo.AccId = resultSet.stringForColumn(kAccID)
mfAccountInfo.pucharseUnits = Double(resultSet.stringForColumn(kpucharseUnits))
mfAccountInfo.CurrentNAV = Double(resultSet.stringForColumn(kCurrentNAV))
mfAccountInfo.CurrentValue = Double(resultSet.stringForColumn(kCurrentValue))
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
//Get for 3 Months from today's date.
//Wealth
func getMFUPortfolioWorthByAccountIDFor3Months(accId : Int) -> NSMutableArray {
dateFormatter.dateFormat = "yyyy-MM-dd"
let todaysDate = dateFormatter.stringFromDate(date)
let previous3Months = calendar.dateByAddingUnit(.Month, value: -2, toDate:date, options: [])
let dateComponent = calendar.components(unitFlags, fromDate: previous3Months!)
let startOfMonth = calendar.dateFromComponents(dateComponent)
let previousDate = dateFormatter.stringFromDate(startOfMonth!)
print(previousDate)
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_mfuPortfolioWorthTable) WHERE \(kAccID)=? AND \(kportfolio_date) BETWEEN '\(previousDate)' AND '\(todaysDate)'", withArgumentsInArray: [accId])
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MfuPortfolioWorth = MfuPortfolioWorth()
mfAccountInfo.portfolio_date = resultSet.stringForColumn(kportfolio_date)
mfAccountInfo.AccId = resultSet.stringForColumn(kAccID)
mfAccountInfo.pucharseUnits = Double(resultSet.stringForColumn(kpucharseUnits))
mfAccountInfo.CurrentNAV = Double(resultSet.stringForColumn(kCurrentNAV))
mfAccountInfo.CurrentValue = Double(resultSet.stringForColumn(kCurrentValue))
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
//Manual
func getManualMFUPortfolioWorthByAccountIDFor3Months(accId : Int) -> NSMutableArray {
dateFormatter.dateFormat = "yyyy-MM-dd"
let todaysDate = dateFormatter.stringFromDate(date)
let previous3Months = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: -2, toDate:date, options: [])
let dateComponent = calendar.components(unitFlags, fromDate: previous3Months!)
let startOfMonth = calendar.dateFromComponents(dateComponent)
let previousDate = dateFormatter.stringFromDate(startOfMonth!)
print(previousDate)
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_mfuPortfolioManualWorthTable) WHERE \(kAccID)=? AND \(kportfolio_date) BETWEEN '\(previousDate)' AND '\(todaysDate)'", withArgumentsInArray: [accId])
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MfuPortfolioWorth = MfuPortfolioWorth()
mfAccountInfo.portfolio_date = resultSet.stringForColumn(kportfolio_date)
mfAccountInfo.AccId = resultSet.stringForColumn(kAccID)
mfAccountInfo.pucharseUnits = Double(resultSet.stringForColumn(kpucharseUnits))
mfAccountInfo.CurrentNAV = Double(resultSet.stringForColumn(kCurrentNAV))
mfAccountInfo.CurrentValue = Double(resultSet.stringForColumn(kCurrentValue))
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
//Get for 1 Year from today's date.
//Wealth
func getMFUPortfolioWorthByAccountIDFor1Year(accId : Int) -> NSMutableArray {
dateFormatter.dateFormat = "yyyy-MM-dd"
let todaysDate = dateFormatter.stringFromDate(date)
let previous1Year = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: -11, toDate:date, options: [])
let dateComponent = calendar.components(unitFlags, fromDate: previous1Year!)
let startOfMonth = calendar.dateFromComponents(dateComponent)
let previousDate = dateFormatter.stringFromDate(startOfMonth!)
print(previousDate)
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_mfuPortfolioWorthTable) WHERE \(kAccID)=? AND \(kportfolio_date) BETWEEN '\(previousDate)' AND '\(todaysDate)'", withArgumentsInArray: [accId])
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MfuPortfolioWorth = MfuPortfolioWorth()
mfAccountInfo.portfolio_date = resultSet.stringForColumn(kportfolio_date)
mfAccountInfo.AccId = resultSet.stringForColumn(kAccID)
mfAccountInfo.pucharseUnits = Double(resultSet.stringForColumn(kpucharseUnits))
mfAccountInfo.CurrentNAV = Double(resultSet.stringForColumn(kCurrentNAV))
mfAccountInfo.CurrentValue = Double(resultSet.stringForColumn(kCurrentValue))
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
//Manual
func getManualMFUPortfolioWorthByAccountIDFor1Year(accId : Int) -> NSMutableArray {
dateFormatter.dateFormat = "yyyy-MM-dd"
let todaysDate = dateFormatter.stringFromDate(date)
let previous1Year = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: -11, toDate:date, options: [])
let dateComponent = calendar.components(unitFlags, fromDate: previous1Year!)
let startOfMonth = calendar.dateFromComponents(dateComponent)
let previousDate = dateFormatter.stringFromDate(startOfMonth!)
print(previousDate)
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_mfuPortfolioManualWorthTable) WHERE \(kAccID)=? AND \(kportfolio_date) BETWEEN '\(previousDate)' AND '\(todaysDate)'", withArgumentsInArray: [accId])
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MfuPortfolioWorth = MfuPortfolioWorth()
mfAccountInfo.portfolio_date = resultSet.stringForColumn(kportfolio_date)
mfAccountInfo.AccId = resultSet.stringForColumn(kAccID)
mfAccountInfo.pucharseUnits = Double(resultSet.stringForColumn(kpucharseUnits))
mfAccountInfo.CurrentNAV = Double(resultSet.stringForColumn(kCurrentNAV))
mfAccountInfo.CurrentValue = Double(resultSet.stringForColumn(kCurrentValue))
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
//Get for All records
//Wealth
func getMFUPortfolioWorthByAccountIDForAll(accId : Int) -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_mfuPortfolioWorthTable) WHERE \(kAccID)=? AND \(kportfolio_date) ORDER BY \(kportfolio_date) ", withArgumentsInArray: [accId])
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MfuPortfolioWorth = MfuPortfolioWorth()
mfAccountInfo.portfolio_date = resultSet.stringForColumn(kportfolio_date)
mfAccountInfo.AccId = resultSet.stringForColumn(kAccID)
mfAccountInfo.pucharseUnits = Double(resultSet.stringForColumn(kpucharseUnits))
mfAccountInfo.CurrentNAV = Double(resultSet.stringForColumn(kCurrentNAV))
mfAccountInfo.CurrentValue = Double(resultSet.stringForColumn(kCurrentValue))
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
//Manual
func getManualMFUPortfolioWorthByAccountIDForAll(accId : Int) -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_mfuPortfolioManualWorthTable) WHERE \(kAccID)=? AND \(kportfolio_date) ORDER BY \(kportfolio_date)", withArgumentsInArray: [accId])
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MfuPortfolioWorth = MfuPortfolioWorth()
mfAccountInfo.portfolio_date = resultSet.stringForColumn(kportfolio_date)
mfAccountInfo.AccId = resultSet.stringForColumn(kAccID)
mfAccountInfo.pucharseUnits = Double(resultSet.stringForColumn(kpucharseUnits))
mfAccountInfo.CurrentNAV = Double(resultSet.stringForColumn(kCurrentNAV))
mfAccountInfo.CurrentValue = Double(resultSet.stringForColumn(kCurrentValue))
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
//ADD MANUAL TABLE
func addMFUManual_WORTH(mfAccountInfo : MfuPortfolioWorth) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("INSERT INTO \(DB_TBL_mfuPortfolioManualWorthTable) (\(kportfolio_date), \(kAccID), \(kpucharseUnits), \(kCurrentNAV), \(kCurrentValue)) VALUES (?, ?, ?, ?, ?, ?, ?)", withArgumentsInArray: [mfAccountInfo.portfolio_date,mfAccountInfo.AccId,mfAccountInfo.pucharseUnits,mfAccountInfo.CurrentNAV,mfAccountInfo.CurrentValue])
sharedInstanceDB.database?.close()
return isInserted!
}
/* func updateMFU_WORTH(mfAccountInfo : MfuPortfolioWorth) -> Bool {
sharedInstanceDB.database!.open()
let isInserted = sharedInstanceDB.database?.executeUpdate("UPDATE \(DB_TBL_mfuPortfolioWorthTable) SET \(kAccID)=?, \(kOrderId)=?, \(kTxnOrderDateTime)=?, \(kTxtType)=?, \(kTxnpucharseUnits)=?, \(kTxnpuchaseNAV)=?, \(kTxnPurchaseAmount)=?, \(kExecutaionDateTime)=?, \(kisDeleted)=? WHERE \(kTxnID)=?", withArgumentsInArray: [mfAccountInfo.AccID,mfAccountInfo.OrderId,mfAccountInfo.TxnOrderDateTime,mfAccountInfo.TxtType,mfAccountInfo.TxnpucharseUnits,mfAccountInfo.TxnpuchaseNAV,mfAccountInfo.TxnPurchaseAmount,mfAccountInfo.ExecutaionDateTime,mfAccountInfo.isDeleted,mfAccountInfo.TxnID])
sharedInstanceDB.database?.close()
return isInserted!
}
*/
func getMFUManual_WORTH() -> NSMutableArray {
sharedInstanceDB.database!.open()
let resultSet: FMResultSet! = sharedInstanceDB.database!.executeQuery("SELECT * FROM \(DB_TBL_mfuPortfolioManualWorthTable)", withArgumentsInArray: nil)
let marrStakeInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
while resultSet.next() {
let mfAccountInfo : MfuPortfolioWorth = MfuPortfolioWorth()
mfAccountInfo.portfolio_date = resultSet.stringForColumn(kportfolio_date)
mfAccountInfo.AccId = resultSet.stringForColumn(kAccID)
mfAccountInfo.pucharseUnits = Double(resultSet.stringForColumn(kpucharseUnits))
mfAccountInfo.CurrentNAV = Double(resultSet.stringForColumn(kCurrentNAV))
mfAccountInfo.CurrentValue = Double(resultSet.stringForColumn(kCurrentValue))
marrStakeInfo.addObject(mfAccountInfo)
}
}
sharedInstanceDB.database!.close()
return marrStakeInfo
}
}
|
//
// ContactsVC.swift
// MyCV
//
// Created by Dima Dobrovolskyy on 4/26/19.
// Copyright © 2019 Dima Dobrovolskyy. All rights reserved.
//
import UIKit
class ContactsVC: UITableViewController {
// MARK: - Constants
private let contacts = Contacts()
private let reusableIdetifier = "ContactCell"
private let titles = [
"Address",
"E-mail",
"Skype",
"Mobile",
"Github",
"Facebook"
]
// MARK: - Properties
private var data = [String: String]()
// MARK: - Life cyrcle
override func viewDidLoad() {
super.viewDidLoad()
sleep(1)
addBackButton()
tableView.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
DispatchQueue.global().async {
self.configure()
}
}
// MARK: - Configuration
private func configure() {
self.save(contacts: contacts)
DispatchQueue.main.async {
self.title = self.contacts.title
self.tableView.reloadData()
}
}
private func save(contacts data: Contacts) {
self.data[titles[0]] = data.address
self.data[titles[1]] = data.email
self.data[titles[2]] = data.skype
self.data[titles[3]] = data.mobile
self.data[titles[4]] = data.git
self.data[titles[5]] = data.facebook
}
// MARK: - Back button configuration
private func addBackButton() {
let backbutton = UIButton(type: .custom)
backbutton.setTitle("Back", for: .normal)
backbutton.setTitleColor(.white, for: .normal)
backbutton.addTarget(self, action: #selector(backAction), for: .touchUpInside)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backbutton)
}
@objc func backAction() -> Void {
dismiss(animated: true, completion: nil)
}
// MARK: - Status bar configuration
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
// MARK: - Table view cells configuration
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: reusableIdetifier, for: indexPath) as? ContactCell else { return UITableViewCell() }
let title = titles[indexPath.row]
guard let details = data[title] else { return UITableViewCell() }
switch indexPath.row {
case 0...2:
cell.configure(title: title, details: details, image: nil)
cell.isUserInteractionEnabled = false
case 3:
cell.configure(title: title, details: details, image: #imageLiteral(resourceName: "call"))
case 4...5:
cell.configure(title: title, details: details, image: #imageLiteral(resourceName: "web"))
default:
break
}
return cell
}
// MARK: - Selection configuration
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ContactCell", for: indexPath) as? ContactCell else { return }
if
let selectedCell = tableView.cellForRow(at: indexPath),
indexPath.row > 2
{
selectedCell.isSelected = false
}
switch indexPath.row {
case 3:
cell.call(number: data[titles[indexPath.row]] ?? "")
case 4...5:
cell.open(url: data[titles[indexPath.row]] ?? "")
default:
break
}
}
// MARK: - Footer configuration
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.4
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footer = UIView(frame: .zero)
footer.backgroundColor = .lightGray
return footer
}
// MARK: - Header configuration
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.4
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = UIView(frame: .zero)
header.backgroundColor = .lightGray
return header
}
}
|
//
// AuthHandlers.swift
// COpenSSL
//
// Created by Georgie Ivanov on 1.11.19.
//
import PerfectHTTPServer
import PerfectHTTP
class AuthHandlers {
static func loginForm(request: HTTPRequest, _ response: HTTPResponse) {
do {
let loginForm: String = try Authentication().loginForm(request: request, response: response)
response.setBody(string: loginForm)
} catch {
response.status = .custom(code: 503, message: "\(error)")
}
response.completed()
}
static func registrationForm(request: HTTPRequest, _ response: HTTPResponse) {
do {
let registrationForm: String = try Authentication().registrationForm(request: request, response: response)
response.setBody(string: registrationForm)
} catch {
response.status = .custom(code: 503, message: "\(error)")
}
response.completed()
}
static func passwordResetForm(request: HTTPRequest, _ response: HTTPResponse) {
do {
let passwordResetForm: String = try Authentication().passwordResetForm(request: request, response: response)
response.setBody(string: passwordResetForm)
} catch {
response.status = .custom(code: 503, message: "\(error)")
}
response.completed()
}
static func registration(request: HTTPRequest, _ response: HTTPResponse) {
do {
try Authentication().registration(request: request, response: response)
} catch {
response.status = .custom(code: 401, message: "\(error)")
response.completed()
}
}
static func validateEmail(request: HTTPRequest, _ response: HTTPResponse) {
do {
try Authentication().validateEmail(request: request, response: response)
} catch {
response.status = .custom(code: 510, message: "\(error)")
response.completed()
}
}
static func resetPassword(request: HTTPRequest, _ response: HTTPResponse) {
do {
try Authentication().passwordReset(request: request, response: response)
} catch {
response.status = .custom(code: 510, message: "\(error)")
response.completed()
}
}
static func changePassword(request: HTTPRequest, _ response: HTTPResponse) {
do {
try Authentication().passwordChange(request: request, response: response)
} catch {
response.status = .custom(code: 510, message: "\(error)")
response.completed()
}
}
static func resendVaidationEmail(request: HTTPRequest, _ response: HTTPResponse) {
do {
try Authentication().resendVaidationEmail(request: request, response: response)
} catch {
response.status = .custom(code: 510, message: "\(error)")
response.completed()
}
}
static func login(request: HTTPRequest, _ response: HTTPResponse) {
do {
try Authentication().login(request: request, response: response)
} catch {
response.status = .custom(code: 403, message: "\(error)")
response.completed()
}
}
static func bearerLogin(request: HTTPRequest, _ response: HTTPResponse) {
do {
try Authentication().bearerLogin(request: request, response: response)
} catch {
response.status = .custom(code: 403, message: "\(error)")
response.completed()
}
}
static func logout(request: HTTPRequest, _ response: HTTPResponse) {
do {
let sessionManager = try CSSessionManager()
sessionManager.destroy(request, response)
response.setHeader(.location, value: "../")
response.status = .movedPermanently
response.completed()
} catch {
response.status = .custom(code: 403, message: "\(error)")
response.completed()
}
}
}
|
//
// CoreDataManager.swift
// Core Data Tutorial
//
// Created by Jorge Henrique P. Garcia on 10/21/15.
// Copyright © 2015 Jhpg. All rights reserved.
//
import UIKit
import CoreData
class CoreDataManager: NSObject {
static let sharedInstance = CoreDataManager()
var entityObj: NSManagedObject! //Recebe o objeto do managedContext
lazy var managedContext: NSManagedObjectContext = {
var appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var c = appDelegate.managedObjectContext
return c
}()
//MARK: - CRUD -
/// Cria nova entidade no managedContext
func new(entityName: String) -> NSManagedObject{
return NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: managedContext)
}
func saveObj(obj: NSManagedObject) {
do {
try obj.managedObjectContext?.save()
} catch let error as NSError {
print("Could not save. Error: \(error), \(error.userInfo)")
}
}
/// Delete an object
func deleteObj(obj: NSManagedObject) {
managedContext.deleteObject(obj)
do {
try managedContext.save()
} catch let error as NSError {
print("Could not delete. Error: \(error), \(error.userInfo)")
}
}
/// Custom - All searches can use it
func customSearch(entityName: String, predicate: NSPredicate, sortDescriptor: NSSortDescriptor) -> [NSManagedObject]? {
let fetchRequest = NSFetchRequest(entityName: entityName)
fetchRequest.sortDescriptors = [sortDescriptor] // Sort descriptor object that sorts ( ORDER BY )
fetchRequest.predicate = predicate // Predicate filters out ( WHERE )
var fetchedResults: [NSManagedObject]?
do {
try fetchedResults = self.managedContext.executeFetchRequest(fetchRequest) as? [NSManagedObject]
} catch let error as NSError {
print("Error: \(error)")
}
return fetchedResults
}
}
|
//: [Previous](@previous)
import Foundation
//extension Int {
// func clamp(low: Int, high: Int) -> Int {
// if (self > high) {
// // if we are higher than the upper bound, return the upper bound
// return high
// } else if (self < low) {
// // if we are lower than the lower bound, return the lower bound
// return low
// }
//
// // we are inside the range, so return our value
// return self
// }
//}
extension BinaryInteger {
func clamp(low: Self, high: Self) -> Self {
if (self > high) {
return high
} else if (self < low) {
return low
}
return self
}
}
let i: Int = 8
print(i.clamp(low: 0, high: 5))
protocol Employee {
var name: String { get set }
var jobTitle: String { get set }
func doWork()
}
extension Employee {
func doWork() {
print("I'm busy!")
}
}
//: [Next](@next)
|
//
// articleViewController.swift
// 0302
//
// Created by H.W. Hsiao on 2020/3/15.
// Copyright © 2020 H.W. Hsiao. All rights reserved.
//
import UIKit
import AVFoundation
class articleViewController: UIViewController {
@IBOutlet weak var articleA: UILabel!
let synth = AVSpeechSynthesizer()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func speakA(_ sender: Any) {
if synth.isPaused == true {
synth.continueSpeaking()
} else if synth.isSpeaking == true {
synth.pauseSpeaking(at: .word)
} else if synth.isSpeaking == false {
if let textA = articleA.text {
let speakA = AVSpeechUtterance(string: textA)
synth.speak(speakA)
}
}
}
}
|
//
// HexUtils.swift
// Bluefruit
//
// Created by Antonio García on 15/10/16.
// Copyright © 2015 Adafruit. All rights reserved.
//
import Foundation
struct HexUtils {
static func hexDescription(data: Data, prefix: String = "", postfix: String = " ") -> String {
return data.reduce("") {$0 + String(format: "%@%02X%@", prefix, $1, postfix)}
}
static func hexDescription(bytes: [UInt8], prefix: String = "", postfix: String = " ") -> String {
return bytes.reduce("") {$0 + String(format: "%@%02X%@", prefix, $1, postfix)}
}
static func decimalDescription(data: Data, prefix: String = "", postfix: String = " ") -> String {
return data.reduce("") {$0 + String(format: "%@%ld%@", prefix, $1, postfix)}
}
}
|
//
// HelloScene.swift
// SpriteWalkthrough
//
// Created by Moin Uddin on 6/10/15.
// Copyright (c) 2015 Moin Uddin. All rights reserved.
//
import SpriteKit
class HelloScene: SKScene {
var contentCreated: Bool = false
override func didMoveToView(view: SKView) {
if !self.contentCreated{
self.createSceneContents()
self.contentCreated = true
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * Int64(NSEC_PER_SEC)), dispatch_get_main_queue()){
self.bringNextScene()
}
}
}
func createSceneContents(){
self.backgroundColor = SKColor.blueColor()
self.scaleMode = SKSceneScaleMode.AspectFit
self.addChild(self.newHelloNode())
}
func newHelloNode()->SKLabelNode{
let helloNode: SKLabelNode = SKLabelNode(fontNamed: "Chalkduster")
helloNode.name = "helloNode"
helloNode.text = "Space Ship"
helloNode.fontSize = 42
helloNode.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
return helloNode
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
if let helloNode: SKNode = self.childNodeWithName("helloNode"){
helloNode.name = nil
let moveUp: SKAction = SKAction.moveByX(0, y: 100, duration: 0.5)
let zoom: SKAction = SKAction.scaleTo(2, duration: 0.25)
let pause: SKAction = SKAction.waitForDuration(0.5)
let fadeAway: SKAction = SKAction.fadeOutWithDuration(0.25)
let remove: SKAction = SKAction.removeFromParent()
let moveSequence: SKAction = SKAction.sequence([moveUp,zoom,pause,fadeAway,remove])
//helloNode.runAction(moveSequence)
helloNode.runAction(moveSequence, completion: { () -> Void in
let spaceshipScene: SpaceshipScene = SpaceshipScene()
spaceshipScene.size = self.size
let doors: SKTransition = SKTransition.doorsOpenVerticalWithDuration(0.5)
self.view?.presentScene(spaceshipScene, transition: doors)
})
}//else{
//self.addChild(self.newHelloNode())
//}
}
func bringNextScene(){
if let helloNode: SKNode = self.childNodeWithName("helloNode"){
helloNode.name = nil
let moveUp: SKAction = SKAction.moveByX(0, y: 100, duration: 0.5)
let zoom: SKAction = SKAction.scaleTo(2, duration: 0.25)
let pause: SKAction = SKAction.waitForDuration(0.5)
let fadeAway: SKAction = SKAction.fadeOutWithDuration(0.25)
let remove: SKAction = SKAction.removeFromParent()
let moveSequence: SKAction = SKAction.sequence([moveUp,zoom,pause,fadeAway,remove])
//helloNode.runAction(moveSequence)
helloNode.runAction(moveSequence, completion: { () -> Void in
let spaceshipScene: SpaceshipScene = SpaceshipScene()
spaceshipScene.size = self.size
let doors: SKTransition = SKTransition.doorsOpenVerticalWithDuration(0.5)
self.view?.presentScene(spaceshipScene, transition: doors)
})
}
}
}
|
//
// SiteRatingScoreExtensionTests.swift
// DuckDuckGo
//
// Copyright © 2017 DuckDuckGo. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import XCTest
@testable import Core
class SiteRatingScoreExtensionTests: XCTestCase {
override func setUp() {
SiteRatingCache.shared.reset()
}
func testWhenHttpThenScoreIsOne() {
let testee = SiteRating(url: httpUrl)!
XCTAssertEqual(1, testee.siteScore)
}
func testWhenHttpsThenScoreIsZero() {
let testee = SiteRating(url: httpsUrl)!
XCTAssertEqual(0, testee.siteScore)
}
func testWhenOneStandardTrackerThenScoreIsTwo() {
let testee = SiteRating(url: httpUrl)!
addTrackers(siteRating: testee, qty: 1)
XCTAssertEqual(2, testee.siteScore)
}
func testWhenOneMajorTrackerThenScoreIsThree() {
let testee = SiteRating(url: httpUrl)!
addTrackers(siteRating: testee, qty: 0, majorQty: 1)
XCTAssertEqual(3, testee.siteScore)
}
func testWhenTenStandardTrackersThenScoreIsTwo() {
let testee = SiteRating(url: httpUrl)!
addTrackers(siteRating: testee, qty: 10)
XCTAssertEqual(2, testee.siteScore)
}
func testWhenTenTrackerIncludingMajorThenScoreIsThree() {
let testee = SiteRating(url: httpUrl)!
addTrackers(siteRating: testee, qty: 5, majorQty: 5)
XCTAssertEqual(3, testee.siteScore)
}
func testWhenElevenStandardTrackersThenScoreIsThree() {
let testee = SiteRating(url: httpUrl)!
addTrackers(siteRating: testee, qty: 11)
XCTAssertEqual(3, testee.siteScore)
}
func testWhenElevenTrackersIncludingMajorThenScoreIsFour() {
let testee = SiteRating(url: httpUrl)!
addTrackers(siteRating: testee, qty: 6, majorQty: 5)
XCTAssertEqual(4, testee.siteScore)
}
func testWhenNewRatingIsLowerThanCachedRatingThenCachedRatingIsUsed() {
_ = SiteRatingCache.shared.add(domain: httpUrl.host!, score: 100)
let testee = SiteRating(url: httpUrl)!
XCTAssertEqual(100, testee.siteScore)
}
func addTrackers(siteRating: SiteRating, qty: Int, majorQty: Int = 0) {
for _ in 0..<qty {
siteRating.trackerDetected(tracker, blocked: true)
}
for _ in 0..<majorQty {
siteRating.trackerDetected(majorTracker, blocked: true)
}
}
var httpUrl: URL {
return URL(string: "http://example.com")!
}
var httpsUrl: URL {
return URL(string: "https://example.com")!
}
var tracker: Tracker {
return Tracker(url: "aurl.com", parentDomain: "someSmallAdNetwork.com")
}
var majorTracker: Tracker {
return Tracker(url: "aurl.com", parentDomain: "facebook.com")
}
}
|
//
// FriendsVC.swift
// FaceBook
//
// Created by Administrator on 10/5/16.
// Copyright © 2016 ITP344. All rights reserved.
//
import UIKit
import FBSDKCoreKit
class FriendsVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var friendsArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
if(FBSDKAccessToken.current().hasGranted("user_friends")){
// perform graph request
let graphRequest = FBSDKGraphRequest(graphPath: "/me/taggable_friends?limit=10000" , parameters: nil)
graphRequest?.start(completionHandler: {
(connection, result, error) -> Void in
print(connection)
if (error == nil){
//print(result)
// cast result data as a dictrionary
let resultDict = result as! [String:Any]
// get the "data" value from the dictionary and cast as an array of dictionaries
let friends = resultDict["data"] as! [[String:Any]]
// iterate through each item
for friend in friends {
let name = friend["name"]
// ***add to your own array***
self.friendsArray.append(name as! String)
}
//print(self.friendsArray.count)
self.tableView.reloadData()
}
})
}else{
print("user_freinds access not granted")
}
}
@IBAction func closeButtonTouched(_ sender: AnyObject) {
self.dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.friendsArray.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "friendCell", for: indexPath)
cell.textLabel?.text = self.friendsArray[indexPath.row]
return cell
}
/*
// 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.
}
*/
}
|
//
// Item.swift
// Viewtest
//
// Created by 鳥嶋晃次 on 2019/10/31.
// Copyright © 2019 鳥嶋晃次. All rights reserved.
//
import Foundation
import Pring
@objcMembers
class Item: Object {
dynamic var name: String?
dynamic var image: File?
dynamic var images: [File] = []
}
|
import Artsy_UILabels
/// Pretty weird case where the labels for "About this Show" and
/// the press release, were always double the height that they needed
/// Couldn't figure out the reason...
/// I tried every version of the Garamond font we have
/// and still got bad behavior.
class HalfIntrinsicHeightSerifLabel: ARSerifLabel {
override func intrinsicContentSize() -> CGSize {
let size = super.intrinsicContentSize()
let guestiHeight = size.height/2.73
let height = guestiHeight.roundUp(30)
return CGSize(width: size.width, height: height)
}
}
extension CGFloat {
/// Rounds up current value to the nearest x
func roundUp(divisor: CGFloat) -> CGFloat {
let rem = self % divisor
return rem == 0 ? self : self + divisor - rem
}
}
|
//
// NotificationFactory.swift
// AcapulcoSample
//
// Created by Nicolo' on 26/02/15.
// Copyright (c) 2015 Dimension s.r.l. All rights reserved.
//
import Foundation
/// Factory class to lessen the burden of writing NSNotification boilerplate code.
public class NotificationFactory {
public struct Names {
static let PushReceivedNotificationName : String = "PushReceivedNotification"
}
/**
Given an userInfo dictionary, it returns an NSNotification named
PushReceivedNotification with the dictionary as object.
:userInfo: The dictionary.
:returns: The NSNotification
*/
public class func PushReceivedNotification(userInfo:[NSObject : AnyObject]) -> NSNotification {
let notification = NSNotification(name:Names.PushReceivedNotificationName, object:userInfo)
return notification
}
} |
import UIKit
class MainTabbarViewController: UITabBarController, UITabBarControllerDelegate {
// var newsNavigationViewcontroller : UINavigationController?
// var radioNavigationViewcontroller : UINavigationController?
// var tvNavigationViewcontroller : UINavigationController?
// var topNowNavigationViewController : UINavigationController?
// var moreNewsNavigationViewcontroller : UINavigationController?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init() {
super.init(nibName: nil, bundle: nil)
self.createTabViews()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self;
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func createTabViews() {
var tabbars = [UINavigationController]()
// newsNavigationViewcontroller = UINavigationController.init(rootViewController: NewsViewController())
// newsNavigationViewcontroller?.tabBarItem = tabbarItem(title: "News", unSelectedImageString: "ic_tabbar_news_off", selectedImageString: "ic_tabbar_news_on")
// tabbars.append(newsNavigationViewcontroller!)
//
// tvNavigationViewcontroller = UINavigationController.init(rootViewController: TVViewController())
// tvNavigationViewcontroller?.tabBarItem = tabbarItem(title: "TV", unSelectedImageString: "ic_tabbar_tv_off", selectedImageString: "ic_tabbar_tv_on")
// tabbars.append(tvNavigationViewcontroller!)
//
// radioNavigationViewcontroller = UINavigationController.init(rootViewController: RadioViewController())
// radioNavigationViewcontroller?.tabBarItem = tabbarItem(title: "Radio", unSelectedImageString: "ic_tabbar_radio_off", selectedImageString: "ic_tabbar_radio_on")
// tabbars.append(radioNavigationViewcontroller!)
//
// topNowNavigationViewController = UINavigationController.init(rootViewController: TopNowViewController())
// topNowNavigationViewController?.tabBarItem = tabbarItem(title: "Top Now", unSelectedImageString: "ic_tabbar_top_now_off", selectedImageString: "ic_tabbar_top_now_on")
// tabbars.append(topNowNavigationViewController!)
//
// moreNewsNavigationViewcontroller = UINavigationController.init(rootViewController: MoreViewController())
// moreNewsNavigationViewcontroller?.tabBarItem = tabbarItem(title: "More", unSelectedImageString: "ic_tabbar_more_off", selectedImageString: "ic_tabbar_more_on")
// tabbars.append(moreNewsNavigationViewcontroller!)
//
// self.viewControllers = tabbars
// self.selectedViewController = newsNavigationViewcontroller
}
func tabbarItem(title: String, unSelectedImageString: String, selectedImageString: String) -> UITabBarItem {
let selectedImage = UIImage.init(named: selectedImageString)
let unselectedImage = UIImage.init(named: unSelectedImageString)
return UITabBarItem.init(title: title, image: unselectedImage, selectedImage: selectedImage)
}
/*
// 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.
}
*/
}
|
//
// MatchTests.swift
// marcadores
//
// Created by Pereiro, Delfin on 18/06/16.
// Copyright © 2016 Pereiro, Delfin. All rights reserved.
//
import XCTest
class MatchTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testValidMatch() {
let matchData = ["id":1989061,"tournamentId":47,"name":"Chelsea - Tottenham","statusShortDesc":"FT","teams":getTeamsMock()] as [String:AnyObject]
let match = Match(matchData: matchData)
XCTAssertNotNil(match)
XCTAssertEqual(match?.id, matchData["id"] as? NSInteger)
XCTAssertEqual(match?.tournamentId, matchData["tournamentId"] as? NSInteger)
XCTAssertEqual(match?.name, matchData["name"] as? String)
XCTAssertEqual(match?.statusShortDesc, matchData["statusShortDesc"] as? String)
XCTAssertNotNil(match?.homeTeam)
XCTAssertNotNil(match?.visitorTeam)
}
func testInvalidId() {
let matchData = ["id":"1989061","tournamentId":47,"name":"Chelsea - Tottenham","statusShortDesc":"FT","teams":getTeamsMock()] as [String:AnyObject]
XCTAssertNil(Match(matchData: matchData))
}
func testNoId() {
let matchData = ["tournamentId":47,"name":"Chelsea - Tottenham","statusShortDesc":"FT","teams":getTeamsMock()] as [String:AnyObject]
XCTAssertNil(Match(matchData: matchData))
}
func testNoTournamentId() {
let matchData = ["id":1989061,"name":"Chelsea - Tottenham","statusShortDesc":"FT","teams":getTeamsMock()] as [String:AnyObject]
XCTAssertNil(Match(matchData: matchData))
}
func testNoName() {
let matchData = ["id":1989061,"tournamentId":47,"statusShortDesc":"FT","teams":getTeamsMock()] as [String:AnyObject]
XCTAssertNil(Match(matchData: matchData))
}
func testNoShortDescription() {
let matchData = ["id":1989061,"tournamentId":47,"name":"Chelsea - Tottenham","teams":getTeamsMock()] as [String:AnyObject]
XCTAssertNil(Match(matchData: matchData))
}
func testNoTeams() {
let matchData = ["id":1989061,"tournamentId":47,"name":"Chelsea - Tottenham","statusShortDesc":"FT","teams":[]] as [String:AnyObject]
XCTAssertNil(Match(matchData: matchData))
}
// MARK: - Private methods
private func getTeamsMock()->[[String:AnyObject]]{
let team1Data = ["id":8455,"name":"Chelsea","shortName":"Chelsea","logoUrl":"http://medias.whatsthescore.com/logos/icons/app-teams-large-ios-retina/8455.png"]
let team2Data = ["id":8455,"name":"Chelsea","shortName":"Chelsea","logoUrl":"http://medias.whatsthescore.com/logos/icons/app-teams-large-ios-retina/8455.png"]
return [team1Data,team2Data]
}
}
|
//
// GlobalConstants.swift
// Adamant
//
// Created by Anokhov Pavel on 10.01.2018.
// Copyright © 2018 Adamant. All rights reserved.
//
import UIKit
extension UIColor {
// MARK: Global colors
/// Main dark gray, ~70% gray
static let adamantPrimary = UIColor(red: 0.29, green: 0.29, blue: 0.29, alpha: 1)
/// Secondary color, ~50% gray
static let adamantSecondary = UIColor(red: 0.478, green: 0.478, blue: 0.478, alpha: 1)
/// Chat icons color, ~40% gray
static let adamantChatIcons = UIColor(red: 0.62, green: 0.62, blue: 0.62, alpha: 1)
// MARK: Chat colors
/// User chat bubble background, ~4% gray
static let adamantChatRecipientBackground = UIColor(red: 0.965, green: 0.973, blue: 0.981, alpha: 1)
static let adamantPendingChatBackground = UIColor(white: 0.98, alpha: 1.0)
static let adamantFailChatBackground = UIColor(white: 0.8, alpha: 1.0)
/// Partner chat bubble background, ~8% gray
static let adamantChatSenderBackground = UIColor(red: 0.925, green: 0.925, blue: 0.925, alpha: 1)
// MARK: Pinpad
/// Pinpad highligh button background, 12% gray
static let adamantPinpadHighlightButton = UIColor(red: 0.88, green: 0.88, blue: 0.88, alpha: 1)
}
extension UIFont {
static func adamantPrimary(size: CGFloat) -> UIFont {
return UIFont(name: "Exo 2", size: size)!
}
static func adamantPrimaryLight(size: CGFloat) -> UIFont {
return UIFont(name: "Exo 2 Light", size: size)!
}
static func adamantPrimaryThin(size: CGFloat) -> UIFont {
return UIFont(name: "Exo 2 Thin", size: size)!
}
static var adamantChatDefault = UIFont.systemFont(ofSize: 17)
}
extension Date {
static let adamantNullDate = Date(timeIntervalSince1970: 0)
}
|
import class AppKit.NSApplication
public protocol ApplicationAdapter {
@discardableResult
func setActivationPolicy(_ activationPolicy: NSApplication.ActivationPolicy) -> Bool
func activate(ignoringOtherApps flag: Bool)
}
public extension ApplicationAdapter {
}
extension NSApplication: ApplicationAdapter {}
|
// This source file is part of the Print open source project
//
// Copyright 2021 Gustavo Verdun and the ghv/print project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt file for license information
//
import Files
import Foundation
import SotoS3
import XCTest
@testable import PrintKit
final class DeployerTests: XCTestCase {
var client: AWSClient!
override func setUp() {
let credentials: AWSCredentials
if let data = try? KeychainAccess.read(item: "AWS"), let decdoded: AWSCredentials = try? data.decoded() {
credentials = decdoded
} else {
print("Error: Could not read AWS credentials")
credentials = AWSCredentials(keyId: "", secret: "")
}
client = AWSClient(
credentialProvider: credentials.provider,
httpClientProvider: .createNew)
}
override func tearDown() {
try? client.syncShutdown()
}
func testPublisher() {
print(Folder.current)
let env = ProcessInfo.processInfo.environment
for (key, value) in env {
print("\(key) - \(value)")
}
print("==============================================")
if let root = Bundle.module.path(forResource: "TestSite", ofType: nil) {
if let publisher = S3CloudFrontDeployer(client: client, inFolder: root ) {
let future = publisher.run()
do {
let result = try future.wait()
XCTAssertGreaterThanOrEqual(result, 0)
} catch let error {
dump(error)
print("threw error \"\(error)\"")
XCTFail("threw error \"\(error)\"")
}
} else {
XCTFail("Could not create publisher")
}
} else {
XCTFail("Could not get bundle resource path to TestSite")
}
}
}
|
//
// ModelViewController.swift
// CodeName
//
// Created by Maree Williams on 1/10/2016.
// Copyright © 2016 Maree Williams. All rights reserved.
//
import UIKit
class ModelViewController: UIViewController {
@IBOutlet weak var viewer: UIImageView!
@IBOutlet weak var codeNameLabel: UILabel!
var circleCenter: CGPoint!
var circleAnimator: UIViewPropertyAnimator!
override func viewDidLoad() {
super.viewDidLoad()
loadArraysToRandomize()
codeNameLabel.text = word1Generated + " " + word2Generated + " " + word3Generated
/*
*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
codeNameLabel.center.x -= view.bounds.width
UIView.animate(withDuration: 0.5, animations: {
let circle = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0))
let animationDuration = 10.0
circle.center = self.view.center
circle.layer.cornerRadius = 50.0
circle.backgroundColor = UIColor.purple
self.circleAnimator = UIViewPropertyAnimator(duration: animationDuration, curve: .easeInOut, animations: {
[unowned circle] in
// 3x scale
circle.transform = CGAffineTransform(scaleX: 3.0, y: 3.0)
})
self.view.addSubview(circle)
})
UIView.animate(withDuration: 0.5, delay: 0.3, options: [], animations: {
self.codeNameLabel.center.x += self.view.bounds.width
}, completion: nil)
}
}
|
//
// TableDataSourceModel.swift
// Biirr
//
// Created by Ana Márquez on 06/03/2021.
//
import UIKit
///Control dataSource and delegate of a table that handle data of type GenericDataSource<Beer>
class TableDataSourceModel: GenericDataSource<Beer>, UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.value.count + (moreDataAvailable.value ? 1 : 0)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == data.value.count {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "MoreBeerCell", for: indexPath) as? MoreBeerTableViewCell else { return UITableViewCell() }
return cell
}
guard let cell = tableView.dequeueReusableCell(withIdentifier: "BeerCell", for: indexPath) as? BeerTableViewCell else { return UITableViewCell() }
cell.beer = data.value[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == data.value.count {
selectedData.value = Beer.empty
} else {
selectedData.value = data.value[indexPath.row]
}
}
}
|
//
// ViewController.swift
// FinalProject
//
// Created by yespinoza on 2020/08/08
//
import UIKit
class LoginViewController: AppBaseController {
@IBOutlet weak var txtUsername: UITextField!
@IBOutlet weak var txtPassword: UITextField!
@IBOutlet weak var switchDummy: UISwitch!
@IBOutlet weak var btnSignUp: UIButton!
@IBOutlet weak var switchRememberUser: UISwitch!
var viewModel:LoginViewModel!
var hasChanged:Bool = false
var savePassword:Bool = false
override func viewDidLoad() {
super.viewDidLoad()
viewModel = LoginViewModel.init()
initViewController()
}
func initViewController(){
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipes))
swipeLeft.direction = .left
self.view.addGestureRecognizer(swipeLeft)
if let userNameRemembered = UserDefaults.standard.string(forKey: "UserName"){
switchRememberUser.isOn = true
txtUsername.text = userNameRemembered
if let passwordRemembered = UserDefaults.standard.string(forKey: "Password"){
savePassword = true
txtPassword.text = passwordRemembered
}
}
_DummyResponse.IsDummyEnabled = UserDefaults.standard.bool(forKey: "IsDummyEnabled")
switchDummy.isOn = _DummyResponse.IsDummyEnabled
}
@objc func handleSwipes(_ sender:UISwipeGestureRecognizer)
{
if self.navigationController == nil{
goTo("Main", identifier: "CreateUserViewController")
}else{
navigationController?.pushViewController(getViewController("Main", identifier: "CreateUserViewController"), animated: true)
}
}
@IBAction func actionHasChanged(_ sender: Any) {
hasChanged = true
switchRememberUser.isOn = false
savePassword = false
}
@IBAction func actionLogin(_ sender: Any) {
print("UI => [Login]")
viewModel.LoginValidate(txtUsername.text, password: txtPassword.text, _protocol:self)
}
@IBAction func actionDummySwitch(_ sender: UISwitch) {
_DummyResponse.IsDummyEnabled = sender.isOn
UserDefaults.standard.set(sender.isOn, forKey: "IsDummyEnabled")
}
@IBAction func actionRemberSwitch(_ sender: UISwitch) {
self.savePassword = false
if sender.isOn {
showConfirmAlert(ConstantUtil.RememberPasswordConfirmationMessage, acceptButton: ConstantUtil.AcceptOption) { _ in
self.savePassword = true
}
}
}
}
extension LoginViewController: LoginProtocol{
func login(_ userName:String, password:String) {
self.showLoader()
viewModel.LoginApply(userName, password: password, rememberUser:switchRememberUser.isOn, rememberPassword: savePassword,_protocol: self)
}
func onSuccess(_ user:User) {
print("UI => [Login] => SUCCESS")
viewModel.SaveUserDefaults(user.UserName, password: txtPassword.text, rememberUser: switchRememberUser.isOn, rememberPassword: savePassword)
self.setCurrentUser(user)
if switchRememberUser.isOn && !savePassword
{
self.txtPassword.text = ""
}else{
self.txtUsername.text = ""
self.txtPassword.text = ""
}
self.goHome()
}
func onError() {
print("UI => [Login] => ERROR")
self.dismissLoader({self.showDefaultError()})
}
func onError(_ title: String?, message: String?) {
print("UI => [Login] => ERROR")
dismissLoader({ self.showErrorAlert(title, message: message) })
}
}
|
//
// UITableView+Extension.swift
// NOC-App
//
// Created by Hassan El Desouky on 3/5/19.
// Copyright © 2019 Hassan El Desouky. All rights reserved.
//
import UIKit
// Obtained from https://stackoverflow.com/a/41513178/5025731
extension UITableView {
func reloadData(with animation: UITableView.RowAnimation) {
reloadSections(IndexSet(integersIn: 0..<numberOfSections), with: animation)
}
}
|
import Foundation
import Kitura
import KituraContracts
import KituraNet
import LoggerAPI
class HttpEncoder {
static var `default` = JSONEncoder()
}
// MARK: - Public GET
extension Router {
// GET
public func get<O: Codable>(_ route: String, handler: @escaping CodableArrayClosureEx<O>) {
getSafely(route, handler: handler)
}
public func get<O: Codable>(_ route: String, handler: @escaping SimpleCodableClosureEx<O>) {
getSafely(route, handler: handler)
}
public func get<Id: Identifier, O: Codable>(_ route: String, handler: @escaping IdentifierSimpleCodableClosureEx<Id, O>) {
getSafely(route, handler: handler)
}
public func get<Q: QueryParams, O: Codable>(_ route: String, handler: @escaping (Q, @escaping CodableArrayResultClosureEx<O>) -> Void) {
getSafely(route, handler: handler)
}
}
// MARK: - Public POST
extension Router {
public func post<I: Codable, O: Codable>(_ route: String, handler: @escaping CodableClosureEx<I, O>) {
postSafely(route, handler: handler)
}
public func post<I: Codable, Id: Identifier, O: Codable>(_ route: String, handler: @escaping CodableIdentifierClosureEx<I, Id, O>) {
postSafelyWithId(route, handler: handler)
}
}
// MARK: - Public PUT
extension Router {
public func put<Id: Identifier, I: Codable, O: Codable>(_ route: String, handler: @escaping IdentifierCodableClosureEx<Id, I, O>) {
putSafely(route, handler: handler)
}
}
// MARK: - Public PATCH
extension Router {
public func patch<Id: Identifier, I: Codable, O: Codable>(_ route: String, handler: @escaping IdentifierCodableClosureEx<Id, I, O>) {
patchSafely(route, handler: handler)
}
}
// MARK: - Private POST
extension Router {
private func postSafely<I: Codable, O: Codable>(_ route: String, handler: @escaping CodableClosureEx<I, O>) {
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
guard self.isContentTypeJson(request) else {
response.status(.unsupportedMediaType)
next()
return
}
guard !request.hasBodyParserBeenUsed else {
Log.error("No data in request. Codable routes do not allow the use of a BodyParser.")
response.status(.internalServerError)
return
}
do {
// Process incoming data from client
let param = try request.read(as: I.self)
// Define handler to process result from application
let resultHandler: CodableResultClosureEx<O> = { result in
do {
switch result {
case let .failure(error):
let status = self.httpStatusCode(from: error)
response.status(status)
case let .success(content):
let encoded = try HttpEncoder.default.encode(content)
response.status(.created)
response.headers.setType("json")
response.send(data: encoded)
}
} catch {
// Http 500 error
response.status(.internalServerError)
}
next()
}
// Invoke application handler
handler(param, resultHandler)
} catch {
// Http 400 error
//response.status(.badRequest)
// Http 422 error
response.status(.unprocessableEntity)
next()
}
}
}
private func postSafelyWithId<I: Codable, Id: Identifier, O: Codable>(
_ route: String, handler: @escaping CodableIdentifierClosureEx<I, Id, O>) {
post(route) { request, response, next in
Log.verbose("Received POST type-safe request")
guard self.isContentTypeJson(request) else {
response.status(.unsupportedMediaType)
next()
return
}
guard !request.hasBodyParserBeenUsed else {
Log.error("No data in request. Codable routes do not allow the use of a BodyParser.")
response.status(.internalServerError)
return
}
do {
// Process incoming data from client
let param = try request.read(as: I.self)
// Define handler to process result from application
let resultHandler: IdentifierCodableResultClosureEx<Id, O> = { id, result in
do {
switch result {
case let .failure(error):
let status = self.httpStatusCode(from: error)
response.status(status)
case let .success(content):
guard let id = id else {
Log.error("No id (unique identifier) value provided.")
response.status(.internalServerError)
next()
return
}
let encoded = try HttpEncoder.default.encode(content)
response.status(.created)
response.headers["Location"] = id.value
response.headers.setType("json")
response.send(data: encoded)
}
} catch {
// Http 500 error
response.status(.internalServerError)
}
next()
}
// Invoke application handler
handler(param, resultHandler)
} catch {
// Http 422 error
response.status(.unprocessableEntity)
next()
}
}
}
}
// MARK: - Private PUT
extension Router {
// PUT with Identifier
private func putSafely<Id: Identifier, I: Codable, O: Codable>(_ route: String, handler: @escaping IdentifierCodableClosureEx<Id, I, O>) {
if parameterIsPresent(in: route) {
return
}
put(join(path: route, with: ":id")) { request, response, next in
Log.verbose("Received PUT type-safe request")
guard self.isContentTypeJson(request) else {
response.status(.unsupportedMediaType)
next()
return
}
guard !request.hasBodyParserBeenUsed else {
Log.error("No data in request. Codable routes do not allow the use of a BodyParser.")
response.status(.internalServerError)
return
}
do {
// Process incoming data from client
let id = request.parameters["id"] ?? ""
let identifier = try Id(value: id)
let param = try request.read(as: I.self)
let resultHandler: CodableResultClosureEx<O> = { result in
do {
switch result {
case let .failure(error):
let status = self.httpStatusCode(from: error)
response.status(status)
case let .success(content):
let encoded = try HttpEncoder.default.encode(content)
response.status(.OK)
response.headers.setType("json")
response.send(data: encoded)
}
} catch {
// Http 500 error
response.status(.internalServerError)
}
next()
}
// Invoke application handler
handler(identifier, param, resultHandler)
} catch {
response.status(.unprocessableEntity)
next()
}
}
}
}
// MARK: - Private PATCH
extension Router {
// PATCH
private func patchSafely<Id: Identifier, I: Codable, O: Codable>(_ route: String, handler: @escaping IdentifierCodableClosureEx<Id, I, O>) {
if parameterIsPresent(in: route) {
return
}
patch(join(path: route, with: ":id")) { request, response, next in
Log.verbose("Received PATCH type-safe request")
guard self.isContentTypeJson(request) else {
response.status(.unsupportedMediaType)
next()
return
}
guard !request.hasBodyParserBeenUsed else {
Log.error("No data in request. Codable routes do not allow the use of a BodyParser.")
response.status(.internalServerError)
return
}
do {
// Process incoming data from client
let id = request.parameters["id"] ?? ""
let identifier = try Id(value: id)
let param = try request.read(as: I.self)
// Define handler to process result from application
let resultHandler: CodableResultClosureEx<O> = { result in
do {
switch result {
case let .failure(error):
let status = self.httpStatusCode(from: error)
response.status(status)
case let .success(content):
let encoded = try HttpEncoder.default.encode(content)
response.status(.OK)
response.headers.setType("json")
response.send(data: encoded)
}
} catch {
// Http 500 error
response.status(.internalServerError)
}
next()
}
// Invoke application handler
handler(identifier, param, resultHandler)
} catch {
// Http 422 error
response.status(.unprocessableEntity)
next()
}
}
}
}
// MARK: - Private GET
extension Router {
// Get single
private func getSafely<O: Codable>(_ route: String, handler: @escaping SimpleCodableClosureEx<O>) {
get(route) { _, response, next in
Log.verbose("Received GET (single no-identifier) type-safe request")
// Define result handler
let resultHandler: CodableResultClosureEx<O> = { result in
do {
switch result {
case let .failure(error):
let status = self.httpStatusCode(from: error)
response.status(status)
case let .success(content):
let encoded = try HttpEncoder.default.encode(content)
response.status(.OK)
response.headers.setType("json")
response.send(data: encoded)
}
} catch {
// Http 500 error
response.status(.internalServerError)
}
next()
}
handler(resultHandler)
}
}
// Get array
private func getSafely<O: Codable>(_ route: String, handler: @escaping CodableArrayClosureEx<O>) {
get(route) { _, response, next in
Log.verbose("Received GET (plural) type-safe request")
// Define result handler
let resultHandler: CodableArrayResultClosureEx<O> = { result in
do {
switch result {
case let .failure(error):
let status = self.httpStatusCode(from: error)
response.status(status)
case let .success(content):
let encoded = try HttpEncoder.default.encode(content)
response.status(.OK)
response.headers.setType("json")
response.send(data: encoded)
}
} catch {
// Http 500 error
response.status(.internalServerError)
}
next()
}
handler(resultHandler)
}
}
// Get w/Query Parameters
private func getSafely<Q: QueryParams, O: Codable>(
_ route: String,
handler: @escaping (Q, @escaping CodableArrayResultClosureEx<O>) -> Void) {
get(route) { request, response, next in
Log.verbose("Received GET (plural) type-safe request with Query Parameters")
// Define result handler
let resultHandler: CodableArrayResultClosureEx<O> = { result in
do {
switch result {
case let .failure(error):
let status = self.httpStatusCode(from: error)
response.status(status)
case let .success(content):
let encoded = try HttpEncoder.default.encode(content)
response.status(.OK)
response.headers.setType("json")
response.send(data: encoded)
}
} catch {
// Http 500 error
response.status(.internalServerError)
}
next()
}
Log.verbose("Query Parameters: \(request.queryParameters)")
do {
let query: Q = try QueryDecoder(dictionary: request.queryParameters).decode(Q.self)
handler(query, resultHandler)
} catch {
// Http 400 error
response.status(.badRequest)
next()
}
}
}
// GET single identified element
private func getSafely<Id: Identifier, O: Codable>(_ route: String, handler: @escaping IdentifierSimpleCodableClosureEx<Id, O>) {
if parameterIsPresent(in: route) {
return
}
get(join(path: route, with: ":id")) { request, response, next in
Log.verbose("Received GET (singular with identifier) type-safe request")
do {
// Define result handler
let resultHandler: CodableResultClosureEx<O> = { result in
do {
switch result {
case let .failure(error):
let status = self.httpStatusCode(from: error)
response.status(status)
case let .success(content):
let encoded = try HttpEncoder.default.encode(content)
response.status(.OK)
response.headers.setType("json")
response.send(data: encoded)
}
} catch {
// Http 500 error
response.status(.internalServerError)
}
next()
}
// Process incoming data from client
let id = request.parameters["id"] ?? ""
let identifier = try Id(value: id)
handler(identifier, resultHandler)
} catch {
// Http 422 error
response.status(.unprocessableEntity)
next()
}
}
}
}
// MARK: - Private Helpers
extension Router {
private func parameterIsPresent(in route: String) -> Bool {
if route.contains(":") {
let paramaterString = route.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false)
let parameter = !paramaterString.isEmpty ? paramaterString[1] : ""
Log.error("Erroneous path '\(route)', parameter ':\(parameter)' is not allowed. Codable routes do not allow parameters.")
return true
}
return false
}
private func isContentTypeJson(_ request: RouterRequest) -> Bool {
guard let contentType = request.headers["Content-Type"] else {
return false
}
return (contentType.hasPrefix("application/json"))
}
private func httpStatusCode(from error: RequestError) -> HTTPStatusCode {
let status: HTTPStatusCode = HTTPStatusCode(rawValue: error.rawValue) ?? .unknown
return status
}
private func join(path base: String, with component: String) -> String {
let strippedBase = base.hasSuffix("/") ? String(base.dropLast()) : base
let strippedComponent = component.hasPrefix("/") ? String(component.dropFirst()) : component
return "\(strippedBase)/\(strippedComponent)"
}
}
|
//
// MapViewModel.swift
// MVVM_Uber
//
// Created by Nestor Hernandez on 03/08/22.
//
import Foundation
struct MapViewModel {
// MARK: - Properties
var pickupLocationAnnotations: [MapAnnotation]
var dropoffLocationAnnotations: [MapAnnotation]
var availableRideLocationAnnotations: [MapAnnotation]
// MARK: - Methods
init(pickupLocationAnnotations: [MapAnnotation] = [],
dropoffLocationAnnotations: [MapAnnotation] = [],
availableRideLocationAnnotations: [MapAnnotation] = []) {
self.pickupLocationAnnotations = pickupLocationAnnotations
self.dropoffLocationAnnotations = dropoffLocationAnnotations
self.availableRideLocationAnnotations = availableRideLocationAnnotations
}
}
|
//
// timeConversion.swift
// Friday-algorithm
//
// Created by zombietux on 2020/11/20.
// Copyright © 2020 zombietux. All rights reserved.
//
/*
import Foundation
/*
* Complete the timeConversion function below.
*/
func timeConversion(s: String) -> String {
var timeArray = [Int]()
let sArray = s.components(separatedBy: ":")
if let seconds = Int(sArray[2].components(separatedBy: CharacterSet.decimalDigits.inverted).joined()) {
timeArray.append(Int(sArray[0])!)
timeArray.append(Int(sArray[1])!)
timeArray.append(seconds)
}
if s.contains("PM") {
timeArray[0] = timeArray[0] == 12 ? timeArray[0] : (timeArray[0] + 12) % 24
} else {
timeArray[0] = timeArray[0] % 12
}
return timeArray.map{String.init(format: "%02d", $0)}.joined(separator: ":")
}
let fileName = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: fileName, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: fileName)!
guard let s = readLine() else { fatalError("Bad input") }
let result = timeConversion(s: s)
fileHandle.write(result.data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)
*/
|
//
// About.swift
// energyio
//
// Created by Earl Justin Encarnacion on 4/22/16.
// Copyright © 2016 CSUN. All rights reserved.
//
import Foundation
import UIKit
class About : UIViewController{
@IBOutlet weak var somelabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
} |
//
// CrashType.swift
// AppDynamics
//
// Created by Bojan Savic on 5/6/19.
// Copyright © 2019 Bojan Savic. All rights reserved.
//
import Foundation
import RealmSwift
class CrashType: Object {
dynamic var id: String = UUID().uuidString
dynamic var name: String = ""
override static func primaryKey() -> String? {
return "id"
}
}
|
//
// PodInsulinMeasurements.swift
// OmniKit
//
// Created by Pete Schwamb on 9/5/18.
// Copyright © 2018 Pete Schwamb. All rights reserved.
//
import Foundation
public struct PodInsulinMeasurements: RawRepresentable, Equatable {
public typealias RawValue = [String: Any]
public let validTime: Date
public let delivered: Double
public let notDelivered: Double
public let reservoirVolume: Double?
public init(statusResponse: StatusResponse, validTime: Date) {
self.validTime = validTime
self.delivered = statusResponse.insulin
self.notDelivered = statusResponse.insulinNotDelivered
self.reservoirVolume = statusResponse.reservoirLevel
}
// RawRepresentable
public init?(rawValue: RawValue) {
guard
let validTime = rawValue["validTime"] as? Date,
let delivered = rawValue["delivered"] as? Double,
let notDelivered = rawValue["notDelivered"] as? Double,
let reservoirVolume = rawValue["reservoirVolume"] as? Double
else {
return nil
}
self.validTime = validTime
self.delivered = delivered
self.notDelivered = notDelivered
self.reservoirVolume = reservoirVolume
}
public var rawValue: RawValue {
var rawValue: RawValue = [
"validTime": validTime,
"delivered": delivered,
"notDelivered": notDelivered
]
if let reservoirVolume = reservoirVolume {
rawValue["reservoirVolume"] = reservoirVolume
}
return rawValue
}
}
|
/// Created by Alberto Talaván on 05/07/20
/// Copyright © 2020 Alberto Talaván. All rights reserved.
///
import UIKit
class MyTabBarController: UITabBarController, UITabBarControllerDelegate {
let whereAmI = WhereAmI.shared
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
}
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
if item.title == "Compact View" {
if whereAmI.getPosition() != .compactViewController {
whereAmI.changePosition()
}
} else if item.title == "Large View" {
if whereAmI.getPosition() != .largeViewController {
whereAmI.changePosition()
}
}else {
if whereAmI.getPosition() != .compactViewController {
whereAmI.changePosition()
}
}
}
}
|
//
// URLProtocolMock.swift
//
//
// Created by Anton Pomozov on 22.07.2021.
//
import Foundation
class URLProtocolMock: URLProtocol {
static var mockURLs: [URL: (error: Error?, data: Data?, response: HTTPURLResponse?)] = [:]
override class func canInit(with request: URLRequest) -> Bool { true }
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
override func startLoading() {
guard let url = request.url else { return }
if let (error, data, response) = URLProtocolMock.mockURLs[url] {
if let responseStrong = response {
client?.urlProtocol(self, didReceive: responseStrong, cacheStoragePolicy: .notAllowed)
}
if let dataStrong = data {
client?.urlProtocol(self, didLoad: dataStrong)
}
if let errorStrong = error {
client?.urlProtocol(self, didFailWithError: errorStrong)
}
}
client?.urlProtocolDidFinishLoading(self)
}
override func stopLoading() {}
}
|
//
// TextChatTableViewCell.swift
// ContactTest
//
// Created by CHUN MARTHA on 28/04/2017.
// Copyright © 2017 CHUN MARTHA. All rights reserved.
//
import UIKit
class TextChatTableViewCell: UITableViewCell {
@IBOutlet weak var chatView: TextChatView!
override func awakeFromNib() {
super.awakeFromNib()
}
func setMsg(msg: BmobIMMessage, withUserInfo userInfo: BmobIMUserInfo) {
chatView.setMessage(msg, user: userInfo)
}
func populateCell(_ cell: TextChatTableViewCell, withMessage message: BmobIMMessage, info: BmobIMUserInfo) {
if BmobUser.current().objectId == message.fromId {
setMsg(msg: message, withUserInfo: BmobIMUserInfo())
}
else {
setMsg(msg: message, withUserInfo: info)
}
}
}
|
// Copyright 2019-2022 Spotify AB.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import MobiusCore
import MobiusThrowableAssertion
import Nimble
import Quick
@testable import MobiusExtras
class ConnectableTests: QuickSpec {
// swiftlint:disable function_body_length
override func spec() {
describe("ConnectableClass") {
beforeEach {
MobiusHooks.setErrorHandler { message, file, line in
MobiusThrowableAssertion(message: message, file: "\(file)", line: line).throw()
}
}
afterEach {
MobiusHooks.setDefaultErrorHandler()
}
func catchError(in closure: () -> Void) -> Bool {
let exception = MobiusThrowableAssertion.catch(in: closure)
return exception != nil
}
context("when creating a connection") {
var sut: SubclassedConnectableClass!
var connection: Connection<String>!
beforeEach {
sut = SubclassedConnectableClass()
connection = sut.connect({ _ in })
}
it("should call onConnect") {
expect(sut.connectCounter).to(equal(1))
}
context("when a connection has already been created") {
it("should fail") {
let errorThrown = catchError {
_ = sut.connect({ _ in })
}
expect(errorThrown).to(beTrue())
}
}
context("when some input is sent") {
it("should call handle in the subclass with the input") {
let testData = "a string"
connection.accept(testData)
expect(sut.handledStrings).to(equal([testData]))
}
}
context("when dispose is called") {
it("should call onDispose in the subclass") {
connection.dispose()
expect(sut.disposeCounter).to(equal(1))
}
it("should have removed the consumer") {
let errorThrown = catchError {
connection.dispose()
connection.accept("Pointless")
}
expect(errorThrown).to(beTrue())
}
}
}
context("when attempting to send some data back to the loop") {
context("when the consumer is set") {
var sut: SubclassedConnectableClass!
var consumerReceivedData: String?
beforeEach {
sut = SubclassedConnectableClass()
_ = sut.connect({ (data: String) in
consumerReceivedData = data
})
}
it("should send that data to the consumer") {
let testData = "some data"
sut.send(testData)
expect(consumerReceivedData).to(equal(testData))
}
}
}
}
}
}
// A class used to make sure that the ConnectableClass behaves correctly with regards to accepting data and
// disposing of the connection
private class SubclassedConnectableClass: ConnectableClass<String, String> {
var handledStrings = [String]()
override func handle(_ input: String) {
handledStrings.append(input)
}
var connectCounter = 0
override func onConnect() {
connectCounter += 1
}
var disposeCounter = 0
override func onDispose() {
disposeCounter += 1
}
}
|
//
// EncounterTreasure.swift
// MC3
//
// Created by Aghawidya Adipatria on 05/08/20.
// Copyright © 2020 Aghawidya Adipatria. All rights reserved.
//
import SwiftUI
struct EncounterTreasure: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
@EnvironmentObject var moduleInfo: ModuleInfo
var body: some View {
VStack {
if self.moduleInfo.currentModule.content.encounters[self.moduleInfo.encounterIndex].treasure?.isEmpty ?? true {
EncounterTreasureEdit(editMode: .add)
} else {
EncounterTreasureList()
}
}
.navigationBarTitle("")
.navigationBarHidden(true)
.navigationBarBackButtonHidden(true)
}
}
struct EncounterTreasure_Preview: PreviewProvider {
static var previews: some View {
EncounterTreasure().environmentObject(ModuleInfo())
}
}
|
//
// File.swift
// SampleTutorial
//
// Created by Boris Angelov on 1/30/17.
// Copyright © 2017 Boris Angelov. All rights reserved.
//
import Foundation
extension Notification.Name {
public static let onRestaurantsLoaded = Notification.Name("onRestaurantsLoaded")
public static let onCategoriesLoaded = Notification.Name("onCategoriesLoaded")
public static let onProductsLoaded = Notification.Name("onProductsLoaded")
public static let onIngredientsLoaded = Notification.Name("onIngredientsLoaded")
}
|
//
// NetworkTools.swift
// 测试-05-AFN Swift
//
// Created by male on 15/10/15.
// Copyright © 2015年 itheima. All rights reserved.
//
import UIKit
import Alamofire
// MARK: 网络工具
class NetworkTools {
// MARK: - 应用程序信息
private let appKey = "3863118655"
private let appSecret = "b94c088ad2cdae8c3b9641852359d28c"
private let redirectUrl = "http://www.baidu.com"
/// 网络请求完成回调,类似于 OC 的 typeDefine
typealias HMRequestCallBack = (result: AnyObject?, error: NSError?)->()
// 单例
static let sharedTools = NetworkTools()
}
// MARK: - 发布微博
extension NetworkTools {
/// 发布微博
///
/// - parameter status: 微博文本
/// - parameter image: 微博配图
/// - parameter finished: 完成回调
/// - see: [http://open.weibo.com/wiki/2/statuses/update](http://open.weibo.com/wiki/2/statuses/update)
/// - see: [http://open.weibo.com/wiki/2/statuses/upload](http://open.weibo.com/wiki/2/statuses/upload)
func sendStatus(status: String, image: UIImage?, finished: HMRequestCallBack) {
// 1. 创建参数字典
var params = [String: AnyObject]()
// 2. 设置参数
params["status"] = status
// 3. 判断是否上传图片
if image == nil {
let urlString = "https://api.weibo.com/2/statuses/update.json"
tokenRequest(.POST, URLString: urlString, parameters: params, finished: finished)
} else {
let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
let data = UIImagePNGRepresentation(image!)
upload(urlString, data: data!, name: "pic", parameters: params, finished: finished)
}
}
}
// MARK: - 微博数据相关方法
extension NetworkTools {
/// 加载微博数据
///
/// - parameter since_id: 若指定此参数,则返回ID比since_id大的微博(即比since_id时间晚的微博),默认为0。
/// - parameter max_id: 若指定此参数,则返回ID`小于或等于max_id`的微博,默认为0
/// - parameter finished: 完成回调
/// - see: [http://open.weibo.com/wiki/2/statuses/home_timeline](http://open.weibo.com/wiki/2/statuses/home_timeline)
func loadStatus(since_id since_id: Int, max_id: Int, finished: HMRequestCallBack) {
// 1. 创建参数字典
var params = [String: AnyObject]()
// 判断是否下拉
if since_id > 0 {
params["since_id"] = since_id
} else if max_id > 0 { // 上拉参数
params["max_id"] = max_id - 1
}
// 2. 准备网络参数
let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
// 3. 发起网络请求
tokenRequest(.GET, URLString: urlString, parameters: params, finished: finished)
}
}
// MARK: - 用户相关方法
extension NetworkTools {
/// 加载用户信息
///
/// - parameter uid: uid
/// - parameter finished: 完成回调
/// - see: [http://open.weibo.com/wiki/2/users/show](http://open.weibo.com/wiki/2/users/show)
func loadUserInfo(uid: String, finished: HMRequestCallBack) {
// 1. 创建参数字典
var params = [String: AnyObject]()
// 2. 处理网络参数
let urlString = "https://api.weibo.com/2/users/show.json"
params["uid"] = uid
tokenRequest(.GET, URLString: urlString, parameters: params, finished: finished)
}
}
// MARK: - OAuth 相关方法
extension NetworkTools {
/// OAuth 授权 URL
/// - see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
var oauthURL: NSURL {
let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
return NSURL(string: urlString)!
}
/// 加载 AccessToken
func loadAccessToken(code: String, finished: HMRequestCallBack) {
let urlString = "https://api.weibo.com/oauth2/access_token"
let params = ["client_id": appKey,
"client_secret": appSecret,
"grant_type": "authorization_code",
"code": code,
"redirect_uri": redirectUrl]
request(.POST, URLString: urlString, parameters: params, finished: finished)
// 测试返回的数据内容 - AFN 默认的响应格式是 JSON,会直接反序列化
// 如果要确认数据格式的问题
// 如果是 NSNumber,则没有引号!在做 KVC 指定属性类型非常重要!
// // 1> 设置相应数据格式是二进制的
// responseSerializer = AFHTTPResponseSerializer()
//
// // 2> 发起网络请求
// POST(urlString, parameters: params, success: { (_, result) -> Void in
//
// // 将二进制数据转换成字符串
// let json = NSString(data: result as! NSData, encoding: NSUTF8StringEncoding)
//
// print(json)
//
// // {"access_token":"2.00ml8IrF6dP8NEb33e7215aeRhrcdB",
// // "remind_in":"157679999",
// // "expires_in":157679999,
// // "uid":"5365823342"}
//
// }, failure: nil)
}
}
// MARK: - 封装 Alamofire 网络方法
extension NetworkTools {
/// 向 parameters 字典中追加 token 参数
///
/// - parameter parameters: 参数字典
///
/// - returns: 是否追加成功
/// - 默认情况下,关于函数参数,在调用时,会做一次 copy,函数内部修改参数值,不会影响到外部的数值
/// - inout 关键字,相当于在 OC 中传递对象的地址
private func appendToken(inout parameters: [String: AnyObject]?) -> Bool {
// 1> 判断 token 是否为nil
guard let token = UserAccountViewModel.sharedUserAccount.accessToken else {
return false
}
// 2> 判断参数字典是否有值
if parameters == nil {
parameters = [String: AnyObject]()
}
// 3> 设置 token
parameters!["access_token"] = token
return true
}
/// 使用 token 进行网络请求
///
/// - parameter method: GET / POST
/// - parameter URLString: URLString
/// - parameter parameters: 参数字典
/// - parameter finished: 完成回调
private func tokenRequest(method: Alamofire.Method, URLString: String, var parameters: [String: AnyObject]?, finished: HMRequestCallBack) {
// 1> 如果追加 token 失败,直接返回
if !appendToken(¶meters) {
finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
return
}
// 2. 发起网络请求
request(method, URLString: URLString, parameters: parameters, finished: finished)
}
/// 网络请求
///
/// - parameter method: GET / POST
/// - parameter URLString: URLString
/// - parameter parameters: 参数字典
/// - parameter finished: 完成回调
private func request(method: Alamofire.Method, URLString: String, parameters: [String: AnyObject]?, finished: HMRequestCallBack) {
// 显示网络指示菊花
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
Alamofire.request(method, URLString, parameters: parameters).responseJSON { (response) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
// 判断是否失败
if response.result.isFailure {
// 在开发网络应用的时候,错误不要提示给用户,但是错误一定要输出!
QL4Error("网络请求失败 \(response.result.error)")
}
// 完成回调
finished(result: response.result.value, error: response.result.error)
}
}
/// 上传文件
private func upload(URLString: String, data: NSData, name: String, var parameters: [String: AnyObject]?, finished: HMRequestCallBack) {
// 1> 如果追加 token 失败,直接返回
if !appendToken(¶meters) {
finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
return
}
// 2> Alamofire 上传文件
/**
appendBody...方法中,如果带 mimeType 是拼接上传文件的方法
appendBody,如果不带 mimeType 是拼接普通的二进制参数方法!
*/
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
Alamofire.upload(.POST, URLString, multipartFormData: { (formData) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
// 拼接上传文件的二进制数据
formData.appendBodyPart(data: data, name: name, fileName: "xxx", mimeType: "application/octet-stream")
// 遍历参数字典,生成对应的参数数据
if let parameters = parameters {
for (k, v) in parameters {
let str = v as! String
let strData = str.dataUsingEncoding(NSUTF8StringEncoding)!
// data 是 v 的二进制数据,name 是 k
formData.appendBodyPart(data: strData, name: k)
}
}
}, encodingMemoryThreshold: 5 * 1024 * 1024) { (encodingResult) -> Void in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON(completionHandler: { (response) -> Void in
// 判断是否失败
if response.result.isFailure {
// 在开发网络应用的时候,错误不要提示给用户,但是错误一定要输出!
print("网络请求失败 \(response.result.error)")
}
// 完成回调
finished(result: response.result.value, error: response.result.error)
})
case .Failure(let error):
print("上传文件编码错误 \(error)")
}
}
}
}
|
//
// IntroViewController.swift
// prkng-ios
//
// Created by Cagdas Altinkaya on 7/5/15.
// Copyright (c) 2015 PRKNG. All rights reserved.
//
import UIKit
class FirstUseViewController: AbstractViewController, TutorialViewControllerDelegate {
var backgroundImageView : UIImageView
var logoView : UIImageView
var parkNowButton : UIButton
var tourButton : UIButton
init() {
backgroundImageView = UIImageView()
logoView = UIImageView()
parkNowButton = ViewFactory.redRoundedButton()
tourButton = ViewFactory.bigRedRoundedButton()
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
override func loadView() {
self.view = UIView()
setupViews()
setupConstraints()
}
override func viewDidLoad() {
super.viewDidLoad()
self.screenName = "Intro - First Use View"
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
SVProgressHUD.dismiss()
// GiFHUD.dismiss()
}
func setupViews () {
view.backgroundColor = Styles.Colors.petrol1
backgroundImageView.image = UIImage(named: "bg_opening")
backgroundImageView.contentMode = UIViewContentMode.ScaleAspectFill
view.addSubview(backgroundImageView)
logoView.image = UIImage(named: "logo_opening")
view.addSubview(logoView)
parkNowButton.setTitle(NSLocalizedString("park_now", comment : ""), forState: UIControlState.Normal)
parkNowButton.addTarget(self, action: "didFinishTutorial", forControlEvents: UIControlEvents.TouchUpInside)
view.addSubview(parkNowButton)
parkNowButton.hidden = true
tourButton.setTitle("take_the_tour".localizedString.uppercaseString, forState: UIControlState.Normal)
tourButton.addTarget(self, action: "tourButtonTapped", forControlEvents: UIControlEvents.TouchUpInside)
view.addSubview(tourButton)
}
func setupConstraints () {
backgroundImageView.snp_makeConstraints { (make) -> () in
make.edges.equalTo(self.view)
}
logoView.snp_makeConstraints { (make) -> () in
make.centerX.equalTo(self.view)
make.centerY.equalTo(self.view).multipliedBy(0.5)
}
parkNowButton.snp_makeConstraints { (make) -> () in
make.centerX.equalTo(self.view)
make.size.equalTo(CGSizeMake(100, 26))
make.bottom.equalTo(self.tourButton.snp_top).offset(-20)
}
tourButton.snp_makeConstraints { (make) -> () in
make.left.equalTo(self.view).offset(Styles.Sizes.bigRoundedButtonSideMargin)
make.right.equalTo(self.view).offset(-Styles.Sizes.bigRoundedButtonSideMargin)
make.bottom.equalTo(self.view).offset(-60)
make.height.equalTo(Styles.Sizes.bigRoundedButtonHeight)
}
}
func didFinishAndDismissTutorial() {
self.presentViewControllerWithFade(viewController: LoginViewController()) { () -> Void in
Settings.setTutorialPassed(true)
}
}
func tourButtonTapped() {
if Settings.tutorialPassed() {
self.didFinishAndDismissTutorial()
} else {
let tutorial = TutorialViewController()
tutorial.delegate = self
self.presentViewController(tutorial, animated: true) { () -> Void in
}
}
}
}
|
import struct Foundation.Data
import class Foundation.NSDictionary
import class Foundation.JSONSerialization
import RxSwift
class TeamsDataDeserializer {
func deserialize(_ data: Data) -> Observable<[String]> {
var teamsJSONObject: Any?
do {
teamsJSONObject = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
} catch { }
var teamNames = [String]()
guard let teamsJSON = teamsJSONObject as? Array<NSDictionary> else {
return Observable.error(DeserializationError(details: "Could not interpret data as JSON dictionary", type: .invalidInputFormat))
}
for teamsDictionary in teamsJSON {
guard let nameString = teamsDictionary["name"] as? String else { continue }
teamNames.append(nameString)
}
return Observable.from(optional: teamNames)
}
}
|
import UIKit
import RxSwift
class LoginVC: UIViewController {
//MARK:- Outlets
@IBOutlet var txtEmail: UITextField!
@IBOutlet var txtPassword: UITextField!
@IBOutlet var btnLogin: UIButton!
//MARK:- VARS
let viewModel = LoginViewModel()
let disposeBag = DisposeBag()
//MARK:- Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupInitialUI()
setupViewModelBinding();
setupCallbacks()
}
//MARK:- Other Methods
func setupInitialUI(){
txtEmail.text = "test@imaginato.com"
txtPassword.text = "Imaginato2020"
btnLogin.layer.cornerRadius = 10.0
}
func setupViewModelBinding(){
txtEmail.rx.text.orEmpty
.bind(to: viewModel.emailIdViewModel.data)
.disposed(by: disposeBag)
txtPassword.rx.text.orEmpty
.bind(to: viewModel.passwordViewModel.data)
.disposed(by: disposeBag)
btnLogin.rx.tap.do(onNext: { [unowned self] in
self.txtEmail.resignFirstResponder()
self.txtPassword.resignFirstResponder()
}).subscribe(onNext: { [unowned self] in
if self.viewModel.validateCredentials() {
self.viewModel.loginUser()
}
}).disposed(by: disposeBag)
}
func setupCallbacks (){
// success
viewModel.isSuccess.asObservable()
.bind{ isSuccess in
if isSuccess{
self.handleLoginResponse(self.viewModel.modelResponse!)
}
}.disposed(by: disposeBag)
// errors
viewModel.errorMsg.asObservable()
.bind { errorMessage in
if errorMessage != ""{
alertView(viewController: self, title: kAppName, message: errorMessage, buttons: [AlertButtonTitle.OK], alertViewStyle: .alert) { (index) in
}
}
}.disposed(by: disposeBag)
}
func handleLoginResponse(_ model:LoginBaseModel){
if model.result == 1{
CoreDataManager.sharedIntance.createDataFor((model.data?.user!)!)
let ctrl:UserVC = UIStoryboard(storyboard: .Main).instantiateViewController()
ctrl.userId = "\(model.data?.user?.userId ?? 0)"
self.navigationController?.pushViewController(ctrl, animated: true)
}else{
alertView(viewController: self, title: kAppName, message: model.error_message ?? "", buttons: [AlertButtonTitle.OK], alertViewStyle: .alert) { (index) in
}
}
}
}
|
//
// InviteViewController.swift
// time2assemble
//
// Created by Hana Pearlman on 3/11/18.
// Copyright © 2018 Julia Chun. All rights reserved.
//
import UIKit
//After user has created an event and filled availability, allow user to send event code to invitees
class InviteViewController: UIViewController {
var user: User!
var event: Event!
@IBOutlet weak var eventCodeTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
let index = event.id.index(event.id.startIndex, offsetBy: 1) //event id in form "-XXXXXX...", remove first "-"
let eventSubstring = event.id.suffix(from: index)
let eventIdString = String(eventSubstring)
eventCodeTextView.text = eventIdString
}
override func viewDidAppear(_ animated: Bool) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func onDoneButtonClick(_ sender: Any) {
self.performSegue(withIdentifier: "toEvents", sender: event)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dashboardView = segue.destination as? EventDashboardController {
dashboardView.user = user
}
}
}
|
//
// FavoritesViewController.swift
// intermine-ios
//
// Created by Nadia on 5/8/17.
// Copyright © 2017 Nadia. All rights reserved.
//
import UIKit
import StoreKit
class FavoritesViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView?
private var failedView: FailedRegistryView?
private var savedSearches: [FavoriteSearchResult]? {
didSet {
if let savedSearches = self.savedSearches, savedSearches.count > 0 {
self.tableView?.reloadData()
if let failedView = self.failedView {
failedView.removeFromSuperview()
self.failedView = nil
}
} else {
let failedView = FailedRegistryView.instantiateFromNib()
failedView.messageText = String.localize("Favorites.NothingFound")
failedView.frame = self.view.bounds
self.tableView?.addSubview(failedView)
self.failedView = failedView
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
super.setNavBarTitle(title: String.localize("Favorites.Title"))
super.showMenuButton()
tableView?.dataSource = self
tableView?.delegate = self
tableView?.rowHeight = UITableViewAutomaticDimension
tableView?.estimatedRowHeight = 140
tableView?.allowsMultipleSelectionDuringEditing = true
let fetchedCellNib = UINib(nibName: "FetchedCell", bundle: nil)
self.tableView?.register(fetchedCellNib, forCellReuseIdentifier: FetchedCell.identifier)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.updateSavedSearches()
}
// MARK: Private methods
private func updateSavedSearches() {
self.savedSearches = CacheDataStore.sharedCacheDataStore.getSavedSearchResults()
if let savedSearches = self.savedSearches, savedSearches.count >= 5 {
if #available(iOS 10.3, *) {
SKStoreReviewController.requestReview()
}
}
}
// MARK: Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let searches = self.savedSearches {
return searches.count
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: FetchedCell.identifier, for: indexPath) as! FetchedCell
if let searches = self.savedSearches {
let search = searches[indexPath.row]
cell.representedData = search.viewableRepresentation()
cell.typeColor = TypeColorDefine.getBackgroundColor(categoryType: search.type)
}
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete) {
guard let savedSearches = self.savedSearches else {
return
}
let removingSearch = savedSearches[indexPath.row]
if let id = removingSearch.id {
CacheDataStore.sharedCacheDataStore.unsaveSearchResult(withId: id)
var info: [String: Any] = [:]
info = ["id": id]
NotificationCenter.default.post(name: NSNotification.Name(rawValue: Notifications.unfavorited), object: self, userInfo: info)
}
self.savedSearches?.remove(at: indexPath.row)
}
}
// Table view delegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let searches = self.savedSearches {
let search = searches[indexPath.row]
if let mineName = search.mineName, let mine = CacheDataStore.sharedCacheDataStore.findMineByName(name: mineName), let mineUrl = mine.url, let id = search.id {
var url = mineUrl + Endpoints.searchResultReport + "?id=\(id)"
if let pubmedId = search.getPubmedId() {
url = Endpoints.pubmed + pubmedId
}
if let webVC = WebViewController.webViewController(withUrl: url) {
AppManager.sharedManager.shouldBreakLoading = true
self.navigationController?.pushViewController(webVC, animated: true)
}
}
}
}
}
|
import Foundation
import PromiseKit
public enum LoginState: Int {
case ValidUser = 0
case LoggedOut = 1
}
class AuthManager {
private class func getAuthenticatedUser() -> Bool {
return UserDefaults.standard.bool(forKey: "authenticated")
}
private class func setAuthenticatedUser(authenticated : Bool){
UserDefaults.standard.set(authenticated, forKey: "authenticated")
}
class func getLoginState() -> LoginState {
if AuthManager.getAuthenticatedUser() {
return .ValidUser
}
return .LoggedOut
}
class func isValidUser() -> Bool {
return getLoginState() == .ValidUser
}
class func logout(){
CacheManager.sharedManager.clearAllCaches()
Context.clearAccessToken()
AuthManager.setAuthenticatedUser(authenticated: false)
}
// MARK: - Data, API calls
class func requestAccessToken(_ authorizationCode: String, source: String) -> Promise<Token> {
return Promise { seal in
_ = AuthService.requestAccessToken(authorizationCode, source: source, completion: { token in
Context.saveAccessToken(token.accessToken)
AuthManager.setAuthenticatedUser(authenticated: true)
seal.fulfill(token)
}, fail: { error in
seal.reject(error)
})
}
}
// MARK: - UI, Flow Control
class func goToDashboardPage(){
// let appDelegate = UIApplication.shared.delegate as! AppDelegate
// let storyBoard = UIStoryboard(name: "Main", bundle: nil)
// appDelegate.window!.rootViewController = storyBoard.instantiateViewController(withIdentifier: Constants.StoryboardID.DashboardVC)
// appDelegate.window!.makeKeyAndVisible()
}
class func goToLoginPage(){
// let appDelegate = UIApplication.shared.delegate as! AppDelegate
// let storyBoard = UIStoryboard(name: "Main", bundle: nil)
// appDelegate.window!.rootViewController = storyBoard.instantiateViewController(withIdentifier: Constants.StoryboardID.LoginVC)
// appDelegate.window!.makeKeyAndVisible()
}
}
|
//
// DeckCardsViewController.swift
// DeckCards
//
// Created by Leandro de Sousa on 04/11/20.
// Copyright © 2020 Leandro de Sousa. All rights reserved.
//
import UIKit
class DeckCardsViewController: UIViewController {
// MARK: - Properties
var viewModel: DeckCardsViewModel!
var isForShuffle = false
// MARK: - Outlets
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var backgroundView: UIView!
// MARK: - Initializers
init(_ viewModel: DeckCardsViewModel) {
super.init(nibName: nil,bundle: nil)
self.viewModel = viewModel
viewModel.viewDelegate = self
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
title = "Deck Cards"
fechtServices()
}
// MARK: - Private Methods
private func setupTableView() {
tableView.delegate = self
tableView.dataSource = self
tableView.register(UINib(nibName: "CardsViewCell", bundle: nil), forCellReuseIdentifier: "CardsViewCell")
tableView.register(UINib(nibName: "RotationCardViewCell", bundle: nil), forCellReuseIdentifier: "RotationCardViewCell")
tableView.register(UINib(nibName: "SubmitFooterView", bundle: nil),
forHeaderFooterViewReuseIdentifier: "SubmitFooterView")
}
private func setupAlertView() {
let alert = UIAlertController(title: "Bem vindo!!",
message: "Essas são as suas cartas e uma carta de rotação",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
private func fechtServices() {
self.startIndicator(false)
DispatchQueue.global(qos: .userInitiated).async {
self.viewModel.fetchDeckCards()
}
}
private func startIndicator(_ isHidden: Bool) {
DispatchQueue.main.async {
!isHidden ? self.activityIndicator.startAnimating() : self.activityIndicator.stopAnimating()
self.activityIndicator.isHidden = isHidden
self.backgroundView.isHidden = isHidden
}
}
}
// MARK: - UITableViewDelegate
extension DeckCardsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
116
}
}
// MARK: - UITableViewDataSource
extension DeckCardsViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard let footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SubmitFooterView")
as? SubmitFooterView else { return UIView() }
footerView.onActionSubmitButton = {
self.startIndicator(false)
DispatchQueue.main.async {
self.viewModel.aPartialDeck()
}
}
footerView.onActionShuffleButton = {
self.startIndicator(false)
self.isForShuffle = true
DispatchQueue.global(qos: .userInitiated).async {
self.viewModel.fetchDeckCards()
}
}
return footerView
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
viewModel.numberLinesOfCards
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cards = viewModel.cards
let cell = tableView.dequeueReusableCell(withIdentifier: "CardsViewCell", for: indexPath) as! CardsViewCell
let index = indexPath.row * 2
if !(viewModel.isTheLastCard(index)) {
cell.addCards(cards[index], cards[index + 1])
} else {
cell.addCards(cards[index], nil)
}
return cell
}
}
//MARK: - DeckCardsViewModelViewDelegate
extension DeckCardsViewController: DeckCardsViewModelViewDelegate {
func cardsPartialSuccess(_ viewModel: DeckCardsViewModel, deckId: String) {
print("Success")
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.startIndicator(true)
viewModel.goToCardInfoScreen(deckId: deckId)
}
}
func cardsSuccess(_ viewModel: DeckCardsViewModel) {
print("Success")
startIndicator(true)
DispatchQueue.main.async {
self.setupTableView()
self.tableView.reloadData()
if !self.isForShuffle {
self.setupAlertView()
}
}
}
func cardsFailure(_ viewModel: DeckCardsViewModel, error: Error) {
print("Failure")
}
}
|
/*
The MIT License (MIT)
Copyright (c) 2016 Bertrand Marlier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
*/
import Foundation
public class PlaybackOrder: GenericOrder, Order
{
public func modify(change parameters: [OrderParameter], completion: @escaping (RequestStatus) -> ())
{
let playbackInstrument = instrument as! PlaybackInstrument
guard let tick = playbackInstrument.currentTick else
{
completion(PlaybackStatus.noTick)
return
}
for param in parameters
{
switch param
{
case .stopLoss(let price): self.stopLoss = price
case .takeProfit(let price): self.takeProfit = price
case .entry(let price): self.entry = price!
case .expiry(let time): self.expiry = time! // expiry is mandatory in working orders
}
}
modify(atTime: tick.time, parameters: parameters)
completion(PlaybackStatus.success)
}
public override func cancel(_ completion: @escaping (RequestStatus) -> ())
{
let playbackInstrument = instrument as! PlaybackInstrument
guard let tick = playbackInstrument.currentTick else
{
completion(PlaybackStatus.noTick)
return
}
super.cancel(completion)
genericInstrument.notify(tradeEvent: .orderClosed(info: OrderClosure(orderId: id, time: tick.time, reason: .cancelled)))
completion(PlaybackStatus.success)
}
}
|
//
// ETCDataStore.swift
// Dash
//
// Created by Yuji Nakayama on 2019/07/12.
// Copyright © 2019 Yuji Nakayama. All rights reserved.
//
import Foundation
import CoreData
enum ETCDataStoreError: Error {
case currentCardMustBeSet
}
class ETCDataStore: NSObject {
let persistentContainer: NSPersistentContainer
@objc dynamic var viewContext: NSManagedObjectContext?
lazy var backgroundContext = persistentContainer.newBackgroundContext()
var currentCard: ETCCardManagedObject?
init(name: String) {
persistentContainer = NSPersistentContainer(name: name)
persistentContainer.persistentStoreDescriptions.forEach { (persistentStoreDescription) in
persistentStoreDescription.shouldAddStoreAsynchronously = true
}
}
func loadPersistantStores(completionHandler: @escaping (NSPersistentStoreDescription, Error?) -> Void) {
persistentContainer.loadPersistentStores { [weak self] (persistentStoreDescription, error) in
guard let self = self else { return }
self.viewContext = self.persistentContainer.viewContext
self.viewContext!.automaticallyMergesChangesFromParent = true
completionHandler(persistentStoreDescription, error)
}
}
func performBackgroundTask(block: @escaping (NSManagedObjectContext) -> Void) {
backgroundContext.perform { [unowned self] in
block(self.backgroundContext)
}
}
func insert(payment: ETCPayment, unlessExistsIn context: NSManagedObjectContext) throws -> ETCPaymentManagedObject? {
if try checkExistence(of: payment, in: context) {
return nil
}
return try insert(payment: payment, into: context)
}
func insert(payment: ETCPayment, into context: NSManagedObjectContext) throws -> ETCPaymentManagedObject {
guard let card = currentCard else {
throw ETCDataStoreError.currentCardMustBeSet
}
let managedObject = insertNewPayment(into: context)
managedObject.amount = payment.amount
managedObject.date = payment.date
managedObject.entranceTollboothID = payment.entranceTollboothID
managedObject.exitTollboothID = payment.exitTollboothID
managedObject.vehicleClassification = payment.vehicleClassification
managedObject.card = card
return managedObject
}
func insertNewPayment(into context: NSManagedObjectContext) -> ETCPaymentManagedObject {
return NSEntityDescription.insertNewObject(forEntityName: ETCPaymentManagedObject.entityName, into: context) as! ETCPaymentManagedObject
}
func checkExistence(of payment: ETCPayment, in context: NSManagedObjectContext) throws -> Bool {
let fetchRequest: NSFetchRequest<ETCPaymentManagedObject> = ETCPaymentManagedObject.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "date == %@", payment.date as NSDate)
return try context.count(for: fetchRequest) > 0
}
func findOrInsertCard(uuid: UUID, in context: NSManagedObjectContext) throws -> ETCCardManagedObject {
if let card = try findCard(uuid: uuid, in: context) {
return card
}
let card = insertNewCard(into: context)
card.uuid = uuid
return card
}
func findCard(uuid: UUID, in context: NSManagedObjectContext) throws -> ETCCardManagedObject? {
let request: NSFetchRequest<ETCCardManagedObject> = ETCCardManagedObject.fetchRequest()
request.predicate = NSPredicate(format: "uuid == %@", uuid as CVarArg)
request.fetchLimit = 1
let cards = try context.fetch(request)
return cards.first
}
func insertNewCard(into context: NSManagedObjectContext) -> ETCCardManagedObject {
return NSEntityDescription.insertNewObject(forEntityName: ETCCardManagedObject.entityName, into: context) as! ETCCardManagedObject
}
}
|
//
// APIManager.swift
// MarvelsApp
//
// Created by aliunco on 3/11/19.
// Copyright © 2019 Zibazi. All rights reserved.
//
import Foundation
fileprivate struct MarvelKeys {
var privateKey: String = "5b7b02b7cc48e6cf0e8f5738dbdc49b86c2f4376"
var publicKey: String = "b266b93f61a3d794cab44558525b1e63"
}
fileprivate struct MarvelAPIConfig {
fileprivate static let keys = MarvelKeys()
static let privatekey = keys.privateKey
static let apikey = keys.publicKey
static let ts = Date().timeIntervalSince1970.description
static let hash = "\(ts)\(privatekey)\(apikey)".MD5()
static let authParameters: [String: String] = [
"apikey": MarvelAPIConfig.apikey,
"ts": MarvelAPIConfig.ts,
"hash": MarvelAPIConfig.hash
]
}
enum MarvelApi {
case characters(name: String?, limit: Int?, offset: Int?)
case character(characterID: String)
case characterComics(characterID: String, limit: Int?)
case characterEvents(characterID: String, limit: Int?)
case characterSeries(characterID: String, limit: Int?)
case characterStories(characterID: String, limit: Int?)
//TODO: continue for the rest of the content apis
}
extension MarvelApi {
var path: String {
switch self {
case .characters:
return "/public/characters"
case .character(let characterId):
return "/public/characters/\(characterId)"
case .characterComics(let characterID, _):
return "/public/characters/\(characterID)/comics"
case .characterEvents(let characterID, _):
return "/public/characters/\(characterID)/events"
case .characterSeries(let characterID, _):
return "/public/characters/\(characterID)/series"
case .characterStories(let characterID, _):
return "/public/characters/\(characterID)/stories"
}
}
var parameters: [String: Any] {
switch self {
case .characters(let name, let limit, let offset):
var params: [String: Any] = [:]
if let name = name { params = params.merge(dict: ["nameStartsWith": name])}
if let limit = limit { params = params.merge(dict: ["limit": limit])}
if let offset = offset { params = params.merge(dict: ["offset": offset])}
return (MarvelAPIConfig.authParameters as [String: Any]).merge(dict: params)
case .characterComics( _, let limit),
.characterEvents( _, let limit),
.characterSeries( _, let limit),
.characterStories( _, let limit):
if let limitValue = limit {
return (MarvelAPIConfig.authParameters as [String: Any]).merge(dict: ["limit": limitValue])
}
return MarvelAPIConfig.authParameters
default:
return MarvelAPIConfig.authParameters
}
}
}
|
// Auto layout in a Swift Playground (for iOS).
// https://gist.github.com/fdstevex/af1c0a13a5e6ce696bf0
import UIKit
var v = UIView()
v.frame = CGRectMake(0, 0, 200, 200)
var b1 = UIButton()
b1.setTitle("Click Me", forState:UIControlState.Normal)
b1.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
b1.setTranslatesAutoresizingMaskIntoConstraints(false)
v.addSubview(b1)
var b2 = UIButton()
b2.setTitle("Click Me Too", forState:UIControlState.Normal)
b2.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
b2.setTranslatesAutoresizingMaskIntoConstraints(false)
v.addSubview(b2)
var views = Dictionary<String, UIView>()
views["b1"] = b1
views["b2"] = b2
v.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[b1]-|", options: nil, metrics: nil, views: views))
v.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[b2]-|", options: nil, metrics: nil, views: views))
v.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[b1]-[b2]", options: nil, metrics: nil, views: views))
v.layoutIfNeeded()
b1.frame
b2.frame
v.frame
v
|
//
// RestaurantTabBarViewProtocol.swift
// myEats
//
// Created by JABE on 11/9/15.
// Copyright © 2015 JABELabs. All rights reserved.
//
protocol RestaurantTabBarViewProtocol {
var restaurant : Restaurant! { get set}
var location : CLLocation! { get set}
var appModelEventsDelegate : AppModelEditorDelegate? {get set}
func onReady()
}
|
//
// ViewController.swift
// GooglemapTest
//
// Created by Cyberk on 3/9/17.
// Copyright © 2017 Cyberk. All rights reserved.
//
import UIKit
import GoogleMaps
import GooglePlaces
import Alamofire
import ObjectMapper
class ViewController: UIViewController, CLLocationManagerDelegate , GMSMapViewDelegate{
var locationManager = CLLocationManager()
var currentLocation: CLLocation?
var mapView: GMSMapView!
@IBOutlet weak var MyView: UIView!
var resultsViewController: GMSAutocompleteResultsViewController?
var searchController: UISearchController?
var resultView: UITextView?
override func viewDidLoad() {
super.viewDidLoad()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.distanceFilter = 50
locationManager.startUpdatingLocation()
locationManager.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func searchAutocomplete(_ sender: Any) {
// let autocompleteController = GMSAutocompleteViewController()
// autocompleteController.delegate = self
// let filter = GMSAutocompleteFilter()
// filter.type = .city
// filter.country = "KH"
// autocompleteController.autocompleteFilter = filter
// present(autocompleteController, animated: true, completion: nil)
let GoogleAutoCompletevc = GoogleAutoComplete(nibName: "GoogleAutoComplete", bundle: nil)
GoogleAutoCompletevc.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
GoogleAutoCompletevc.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
present(GoogleAutoCompletevc, animated: true, completion: nil)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations.last! as CLLocation
let long = userLocation.coordinate.longitude;
let lat = userLocation.coordinate.latitude;
print(lat)
print(long)
LATITUDE = lat
LONGITUDE = long
locationManager.stopUpdatingLocation()
showMapView(LATITUDE, LONGITUDE)
}
func showMapView(_ latitude:Double,_ longitude:Double){
let camera = GMSCameraPosition.camera(withLatitude: LATITUDE, longitude: LONGITUDE, zoom: zoomLevel)
let mapView = GMSMapView.map(withFrame: MyView.bounds, camera: camera)
mapView.settings.setAllGesturesEnabled(true)
mapView.settings.myLocationButton = true
mapView.isMyLocationEnabled = true
mapView.settings.compassButton = true
mapView.delegate = self
MyView.addSubview(mapView)
}
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
print("You tapped at \(coordinate.latitude), \(coordinate.longitude)")
mapView.clear()
let originMarker = GMSMarker()
originMarker.position = CLLocationCoordinate2DMake(coordinate.latitude, coordinate.longitude)
originMarker.map = mapView
originMarker.icon = GMSMarker.markerImage(with: UIColor.black)
originMarker.title = originAddress
}
// func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
// print("markerInfoWindow")
// return self.view
// }
//
// func mapView(_ mapView: GMSMapView, willMove gesture: Bool) {
//
// }
}
extension ViewController: GMSAutocompleteViewControllerDelegate {
// Handle the user's selection.
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
print("Place name: \(place.name)")
navigationController?.navigationItem.title = "\(place.name)"
print("Place address: \(place.formattedAddress)")
// place.placeID
print("Place attributions: \(place.attributions)")
dismiss(animated: true, completion: nil)
DESTLATITUDE = place.coordinate.latitude
DESTLONGITUDE = place.coordinate.longitude
let showDestVC = showDestinationVC()
present(showDestVC, animated: false, completion: nil)
}
func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
// TODO: handle the error.
print("Error: ", error.localizedDescription)
}
// User canceled the operation.
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
dismiss(animated: true, completion: nil)
}
// Turn the network activity indicator on and off again.
func didRequestAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
func didUpdateAutocompletePredictions(_ viewController: GMSAutocompleteViewController) {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
//func gotoMyLocationAction(sender: UIButton)
//{
// guard let lat = self.mapView.myLocation?.coordinate.latitude,
// let lng = self.mapView.myLocation?.coordinate.longitude else { return }
//
// let camera = GMSCameraPosition.camera(withLatitude: lat ,longitude: lng , zoom: zoom)
// self.mapView.animate(to: camera)
//}
//var cameraPosition = GMSCameraPosition.camera(withLatitude: 18.5203, longitude: 73.8567, zoom: 12)
//self.mapView = GMSMapView.map(withFrame: CGRect.zero, camera: cameraPosition)
//self.mapView.myLocationEnabled = true
//var marker = GMSMarker()
//marker.position = CLLocationCoordinate2DMake(18.5203, 73.8567)
//marker.icon = UIImage(named: "aaa.png")
//marker.groundAnchor = CGPoint(x: CGFloat(0.5), y: CGFloat(0.5))
//marker.map = self.mapView
//var path = GMSMutablePath.path
//path?.addCoordinate(CLLocationCoordinate2DMake(CDouble((18.520)), CDouble((73.856))))
//path?.addCoordinate(CLLocationCoordinate2DMake(CDouble((16.7)), CDouble((73.8567))))
//var rectangle = GMSPolyline(path)
//rectangle.strokeWidth = 2.0
//rectangle.map = self.mapView
//self.view = self.mapView
|
//
// ViewController.swift
// Photo Editor
//
// Created by Mohamed Hamed on 4/23/17.
// Copyright © 2017 Mohamed Hamed. All rights reserved.
//
import UIKit
public protocol PhotoEditorDelegate {
/**
- Parameter image: edited Image
*/
func doneEditing(image: UIImage)
/**
StickersViewController did Disappear
*/
func canceledEditing()
}
enum PhotoEditorMode {
case normal
case freeDrawing
case shapeDrawing
case shapePositioning
case labelInput
case labelPositioning
}
public final class PhotoEditorViewController: UIViewController {
/** holding the 2 imageViews original image and drawing & stickers */
@IBOutlet weak var canvasView: UIView!
//To hold the image
@IBOutlet var imageView: UIImageView!
@IBOutlet weak var imageViewHeightConstraint: NSLayoutConstraint!
//To hold the drawings and stickers
@IBOutlet weak var canvasImageView: UIImageView!
@IBOutlet weak var topToolbar: UIView!
@IBOutlet weak var bottomToolbar: UIView!
@IBOutlet weak var topGradient: UIView!
@IBOutlet weak var bottomGradient: UIView!
@IBOutlet weak var doneButton: UIButton!
@IBOutlet weak var undoButton: UIButton!
@IBOutlet weak var deleteView: UIView!
@IBOutlet weak var colorsCollectionView: UICollectionView!
@IBOutlet weak var shapeCollectionView: UICollectionView!
@IBOutlet weak var colorPickerView: UIView!
@IBOutlet weak var shapePickerView: UIView!
@IBOutlet weak var shapeToolsPickerView: UIView!
@IBOutlet weak var colorPickerViewBottomConstraint: NSLayoutConstraint!
//Controls
@IBOutlet weak var cropButton: UIButton!
@IBOutlet weak var drawButton: UIButton!
@IBOutlet weak var shapesButton: UIButton!
@IBOutlet weak var textButton: UIButton!
@IBOutlet weak var saveButton: UIButton!
@IBOutlet weak var shareButton: UIButton!
@IBOutlet weak var clearButton: UIButton!
public var image: UIImage?
/**
Array of Stickers -UIImage- that the user will choose from
*/
public var stickers: [UIImage] = []
/**
Array of Colors that will show while drawing or typing
*/
public var colors: [UIColor] = []
public var shapes: [PhotoEditorShape] = []
var shapeLayers: [UIImageView] = []
public var photoEditorDelegate: PhotoEditorDelegate?
var colorsCollectionViewDelegate: ColorsCollectionViewDelegate!
var shapeCollectionViewDelegate: ShapeCollectionViewDelegate!
// list of controls to be hidden
public var hiddenControls: [PhotoEditorControl] = []
var drawColor: UIColor = UIColor.black
var textColor: UIColor = UIColor.white
var selectedShape: PhotoEditorShape?
var initialImage: UIImage?
var firstPoint: CGPoint!
var lastPoint: CGPoint!
var lastPanPoint: CGPoint?
var lastTextViewTransCenter: CGPoint?
var swiped = false
var lastTextViewTransform: CGAffineTransform?
var lastTextViewFont: UIFont?
var activeTextView: UITextView?
var imageViewToPan: UIImageView?
var mode: PhotoEditorMode = .normal {
didSet {
switch mode {
case .normal:
view.endEditing(true)
doneButton.isHidden = true
undoButton.isHidden = true
colorPickerView.isHidden = true
shapePickerView.isHidden = true
canvasImageView.isUserInteractionEnabled = true
hideToolbar(hide: false)
deleteView.isHidden = true
case .freeDrawing:
canvasImageView.isUserInteractionEnabled = false
doneButton.isHidden = false
undoButton.isHidden = true
colorPickerView.isHidden = false
shapePickerView.isHidden = true
hideToolbar(hide: true)
deleteView.isHidden = true
case .labelInput:
doneButton.isHidden = false
undoButton.isHidden = true
colorPickerView.isHidden = false
shapePickerView.isHidden = true
hideToolbar(hide: true)
deleteView.isHidden = true
case .labelPositioning:
view.endEditing(true)
canvasImageView.isUserInteractionEnabled = true
doneButton.isHidden = true
undoButton.isHidden = true
colorPickerView.isHidden = true
shapePickerView.isHidden = true
hideToolbar(hide: false)
deleteView.isHidden = false
case .shapeDrawing:
canvasImageView.isUserInteractionEnabled = false
doneButton.isHidden = false
undoButton.isHidden = false
shapePickerView.isHidden = false
colorPickerView.isHidden = false
hideToolbar(hide: true)
deleteView.isHidden = true
case .shapePositioning:
canvasImageView.isUserInteractionEnabled = true
shapeCollectionView.deselectAllItems(animated: true)
selectedShape = nil
doneButton.isHidden = true
undoButton.isHidden = true
shapePickerView.isHidden = true
colorPickerView.isHidden = true
hideToolbar(hide: false)
deleteView.isHidden = false
}
}
}
override public func viewDidLoad() {
super.viewDidLoad()
self.setImageView(image: image!)
deleteView.layer.cornerRadius = deleteView.bounds.height / 2
deleteView.layer.borderWidth = 2.0
deleteView.layer.borderColor = UIColor.white.cgColor
deleteView.clipsToBounds = true
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardDidShow),
name: UIResponder.keyboardDidShowNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillHide),
name: UIResponder.keyboardWillHideNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillChangeFrame(_:)),
name: UIResponder.keyboardWillChangeFrameNotification,
object: nil)
configureColorCollectionView()
configureShapeCollectionView()
hideControls()
}
func configureColorCollectionView() {
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 30, height: 30)
layout.scrollDirection = .horizontal
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
colorsCollectionView.collectionViewLayout = layout
colorsCollectionViewDelegate = ColorsCollectionViewDelegate()
colorsCollectionViewDelegate.colorDelegate = self
if !colors.isEmpty {
colorsCollectionViewDelegate.colors = colors
}
colorsCollectionView.delegate = colorsCollectionViewDelegate
colorsCollectionView.dataSource = colorsCollectionViewDelegate
colorsCollectionView.register(
UINib(nibName: "ColorCollectionViewCell", bundle: Bundle(for: ColorCollectionViewCell.self)),
forCellWithReuseIdentifier: "ColorCollectionViewCell")
}
func configureShapeCollectionView() {
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 50, height: 50)
layout.scrollDirection = .horizontal
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 4
shapeCollectionView.collectionViewLayout = layout
shapeCollectionViewDelegate = ShapeCollectionViewDelegate()
shapeCollectionViewDelegate.shapeDelegate = self
if !shapes.isEmpty {
shapeCollectionViewDelegate.shapes = shapes
}
shapeCollectionView.delegate = shapeCollectionViewDelegate
shapeCollectionView.dataSource = shapeCollectionViewDelegate
shapeCollectionView.register(
UINib(nibName: "ShapeCollectionViewCell", bundle: Bundle(for: ShapeCollectionViewCell.self)),
forCellWithReuseIdentifier: "ShapeCollectionViewCell")
}
func setImageView(image: UIImage) {
imageView.image = image
let size = image.suitableSize(widthLimit: UIScreen.main.bounds.width)
imageViewHeightConstraint.constant = (size?.height)!
}
func hideToolbar(hide: Bool) {
topToolbar.isHidden = hide
topGradient.isHidden = hide
bottomToolbar.isHidden = hide
bottomGradient.isHidden = hide
}
}
extension PhotoEditorViewController: ColorDelegate {
func didSelectColor(color: UIColor) {
switch mode {
case .freeDrawing, .shapeDrawing, .shapePositioning, .normal:
self.drawColor = color
case .labelInput, .labelPositioning:
activeTextView?.textColor = color
textColor = color
}
}
}
|
//
// Module.swift
// Epintra
//
// Created by Maxime Junger on 30/01/16.
// Copyright © 2016 Maxime Junger. All rights reserved.
//
import Foundation
import SwiftyJSON
class Module: BasicInformation {
var title: String?
var semester: String?
var grade: String?
var credits: String?
var begin: String?
var end: String?
var endRegister: String?
var registered: Bool?
var activities = [Project]()
var registeredStudents: [RegisteredStudent]?
override init(dict: JSON) {
super.init(dict: dict)
title = dict["title"].stringValue
semester = dict["semester"].stringValue
grade = dict["grade"].stringValue
credits = dict["credits"].stringValue
}
func setAllData(detail: JSON) {
self.begin = detail["begin"].stringValue
self.end = detail["end"].stringValue
self.endRegister = detail["end_register"].stringValue
self.registered = detail["student_registered"].boolValue
self.activities = [Project]()
let arr = detail["activites"].arrayValue
for tmp in arr {
let proj = Project(detail: tmp)
proj.addModuleData(module: self)
self.activities.append(proj)
}
}
func getDetails(completion: @escaping (Result<Any?>) -> Void) {
modulesRequests.details(forModule: self) { (result) in
switch (result) {
case .success(_):
completion(Result.success(nil))
case .failure(let err):
completion(Result.failure(type: err.type, message: err.message))
break
}
}
}
}
|
/* Copyright Airship and Contributors */
import Foundation
import UIKit
#if canImport(AirshipCore)
import AirshipCore
#endif
/**
* Chat style.
*/
@objc(UAChatStyle)
public class ChatStyle : NSObject {
/**
* The title text.
*/
@objc public var title: String?
/**
* The title font.
*/
@objc public var titleFont: UIFont?
/**
* The title color.
*/
@objc public var titleColor: UIColor?
/**
* The outgoing text color.
*/
@objc public var outgoingTextColor: UIColor?
/**
* The incoming text color.
*/
@objc public var incomingTextColor: UIColor?
/**
* The message text font.
*/
@objc public var messageTextFont: UIFont?
/**
* The outgoing chat bubble color.
*/
@objc public var outgoingChatBubbleColor: UIColor?
/**
* The incoming chat bubble color.
*/
@objc public var incomingChatBubbleColor: UIColor?
/**
* The date color.
*/
@objc public var dateColor: UIColor?
/**
* The date font.
*/
@objc public var dateFont: UIFont?
/**
* The background color.
*/
@objc public var backgroundColor: UIColor?
/**
* The navigation bar color.
*/
@objc public var navigationBarColor: UIColor?
/**
* The tint color.
*/
@objc public var tintColor: UIColor?
/**
* Chat style initializer
*/
public override init() {
super.init()
}
/**
* Chat style initializer for parsing from a plist.
*
* @param file The plist file to read from.
*/
public init(file: String) {
super.init()
if let path = Bundle.main.path(forResource: file, ofType: "plist") {
do {
var format = PropertyListSerialization.PropertyListFormat.xml
let xml = FileManager.default.contents(atPath: path)!
let styleDict = try PropertyListSerialization.propertyList(from: xml, options: .mutableContainersAndLeaves, format: &format) as! [String:AnyObject]
let normalized = normalize(keyedValues: styleDict)
setValuesForKeys(normalized)
} catch {
AirshipLogger.error("Error reading chat style plist: \(error)")
}
} else {
AirshipLogger.error("Unable to find chat plist file: \(file)")
}
}
public override func setValue(_ value: Any?, forUndefinedKey key: String) {
// Do not crash on undefined keys
AirshipLogger.debug("Ignoring invalid chat style key: \(key)")
}
private func normalize(keyedValues: [String : AnyObject]) -> [String : AnyObject] {
var normalized: [String : AnyObject] = [:]
for (key, value) in keyedValues {
var normalizedValue: AnyObject?
// Trim whitespace
if let stringValue = value as? String {
normalizedValue = stringValue.trimmingCharacters(in: .whitespaces) as AnyObject
}
// Normalize colors
if key.hasSuffix("Color") {
if let colorString = value as? String {
normalizedValue = createColor(string: colorString)
normalized[key] = normalizedValue
}
continue
}
// Normalize fonts
if key.hasSuffix("Font") {
if let fontDict = value as? [String : String] {
normalizedValue = createFont(dict: fontDict)
normalized[key] = normalizedValue
}
continue
}
normalized[key] = normalizedValue
}
return normalized
}
private func createColor(string: String) -> UIColor? {
let hexColor = ColorUtils.color(string)
let namedColor = UIColor(named: string)
guard hexColor != nil || namedColor != nil else {
AirshipLogger.error("Color must be a valid string representing either a valid color hexidecimal or a named color corresponding to a color asset in the main bundle.")
return nil
}
return namedColor != nil ? namedColor : hexColor
}
private func createFont(dict: [String : String]) -> UIFont? {
let name = dict["fontName"]
let size = dict["fontSize"]
guard name != nil && size != nil else {
AirshipLogger.error("Font name must be a valid string under the key \"fontName\". Font size must be a valid string under the key \"fontSize\"")
return nil
}
let sizeNum = CGFloat(Double(size!) ?? 0)
guard sizeNum > 0 else {
AirshipLogger.error("Font size must represent a double greater than 0")
return nil
}
let font = UIFont(name: name!, size: sizeNum)
guard font != nil else {
AirshipLogger.error("Font must exist in app bundle")
return nil;
}
return font
}
}
|
//
// CastableTests.swift
// Castable
//
// Created by Andrei Hogea on 02/07/2018.
// Copyright © 2018 Castable. All rights reserved.
//
import Foundation
import XCTest
import Castable
class CastableTests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
//// XCTAssertEqual(Castable().text, "Hello, World!")
}
static var allTests = [
("testExample", testExample),
]
}
|
import Foundation
/// A type to generate code for.
class ASTTypeUsed: Codable {
class Field: Codable {
// The name of the field
let name: String
/// The type of the field
let type: ASTVariableType
/// [optional] A description of the field.
let description: String?
}
/// TODO What are the other possible kinds?
enum Kind: String, Codable {
case EnumType
case InputObjectType
}
let kind: ASTTypeUsed.Kind
/// The name of the type
let name: String
/// The description of the type
let description: String
let values: [ASTEnumValue]?
/// [optional] Any fields used on this type
let fields: [ASTTypeUsed.Field]?
}
|
//
// Corner.swift
// cactus-teacher-ios
//
// Created by zhaogang on 2018/4/9.
//
import UIKit
open class ZGDateStyle {
/// 日期字符串转化为Date类型
///
/// - Parameters:
/// - string: 日期字符串
/// - dateFormat: 格式化样式,默认为“yyyy-MM-dd HH:mm:ss”
/// - Returns: Date类型
open class func getTodayDateTime() -> String{
let date = Date.init()
let timeFormatter = DateFormatter.init()
timeFormatter.dateFormat="yyyy-MM-dd"
return timeFormatter.string(from: date)
}
open class func yearStringConvertDate(string:String, dateFormat:String="yyyy-MM-dd") -> Int {
let dateFormatter = DateFormatter.init()
dateFormatter.dateFormat = "yyyy-MM-dd"
let date = dateFormatter.date(from: string)
let calendar = Calendar.current
let dateComponents = calendar.dateComponents([.year,.month,.day], from: date!)
let newDate = dateComponents.year
return newDate!
}
open class func monthStringConvertDate(string:String, dateFormat:String="yyyy-MM-dd") -> Int {
let dateFormatter = DateFormatter.init()
dateFormatter.dateFormat = "yyyy-MM-dd"
let calendar = Calendar.current
var newDate:Int?
if let date = dateFormatter.date(from: string) {
let dateComponents = calendar.dateComponents([.year,.month,.day], from: date)
newDate = dateComponents.month
}
return newDate!
}
open class func monthStringConvertDate1(string:String, dateFormat:String="MM-dd") -> Int {
let dateFormatter = DateFormatter.init()
dateFormatter.dateFormat = "MM-dd"
let calendar = Calendar.current
var newDate:Int?
if let date = dateFormatter.date(from: string) {
let dateComponents = calendar.dateComponents([.month,.day], from: date)
newDate = dateComponents.month
}
return newDate!
}
open class func dayStringConvertDate(string:String, dateFormat:String="yyyy-MM-dd") -> Int {
let dateFormatter = DateFormatter.init()
dateFormatter.dateFormat = "yyyy-MM-dd"
let calendar = Calendar.current
var newDate:Int?
if let date = dateFormatter.date(from: string) {
let dateComponents = calendar.dateComponents([.year,.month,.day], from: date)
newDate = dateComponents.day
}
return newDate!
}
open class func dayStringConvertDate1(string:String, dateFormat:String="MM-dd") -> Int {
let dateFormatter = DateFormatter.init()
dateFormatter.dateFormat = "MM-dd"
var newDate:Int?
let calendar = Calendar.current
if let date = dateFormatter.date(from: string) {
let dateComponents = calendar.dateComponents([.month,.day], from: date)
newDate = dateComponents.day
}
return newDate!
}
open class func timeDifferenceFromDate(startTime:String,endTime:String ) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
guard let date1 = dateFormatter.date(from: startTime),
let date2 = dateFormatter.date(from: endTime) else {
return ""
}
let components = NSCalendar.current.dateComponents([.day,.hour,.minute], from: date1, to: date2)
guard let day = components.day else {
return ""
}
guard let hour = components.hour else {
return ""
}
guard let minute = components.minute else {
return ""
}
var time_str = ""
if day > 0 {
time_str += ("\(day)" + "天")
}
if hour > 0 {
time_str += ("\(hour)" + "小时")
}
if minute > 0 {
time_str += ("\(minute)" + "分")
}
if day == 0 && hour == 0 && minute == 0 {
time_str = "1分钟"
}
//如果需要返回月份间隔,分钟间隔等等,只需要在dateComponents第一个参数后面加上相应的参数即可,示例如下:
// let components = NSCalendar.current.dateComponents([.month,.day,.hour,.minute], from: date1, to: date2)
return time_str
}
}
|
//
// StaticDataSource.swift
// TeamworkTest
//
// Created by Paweł Nużka on 04/01/2017.
// Copyright © 2017 Pawel Nuzka Mobile Developers. All rights reserved.
//
import Foundation
import UIKit
protocol StaticCellModel {
var cellType: BaseCell.Type { get }
var viewModel: CellModel { get }
}
class StaticDataSource<T: StaticCellModel>: DataSource<T> {
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cellRow = data(at: indexPath) else {
fatalError("Should not modify static cells")
}
let cell = tableView.dequeueReusableCell(cellRow.cellType, forIndexPath: indexPath)
cell.load(viewModel: cellRow.viewModel)
return cell
}
}
|
//
// registerViewController.swift
//
//
// Created by LiangMinglong on 3/08/2016.
//
//
import UIKit
import LeanCloud
class registerViewController: UIViewController {
@IBOutlet weak var NameLabel: UITextField!
@IBOutlet weak var EmailAddressLabel: UITextField!
@IBOutlet weak var PasswordLabel: UITextField!
@IBOutlet weak var ConfirmPasswordLabel: UITextField!
@IBAction func loginNowButtonPressed(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func RegisterButtonPressed(sender: AnyObject) {
if NameLabel.text!.isEmpty {
print("Username Can Not be Empty")
return
}
if EmailAddressLabel.text!.isEmpty {
print("EmailAddress Can Not be Empty!")
return
}
if PasswordLabel.text!.isEmpty{
print("Password Can Not be Empty!")
return
}
if ConfirmPasswordLabel.text!.isEmpty{
print("Confirm Password Can Not be Empty!")
return
}
if PasswordLabel.text != ConfirmPasswordLabel.text {
print("Wrong Password!!")
return
}
let randomUser = LCUser()
randomUser.set("nick_name", value: LCString(NameLabel.text!))
randomUser.username = LCString(EmailAddressLabel.text!)
randomUser.email = LCString(EmailAddressLabel.text!)
randomUser.password = LCString(PasswordLabel.text!)
randomUser.signUp { (result) in
if result.isSuccess {
print("Register Successfully!")
self.alertAction("Register Successfully, Do you need Touch ID?")
}else{
print("Register UnSuccessfully! \(result.error)")
}
}
}
//添加一个提示框
func alertAction(info_string: String){
let alertController = UIAlertController(title: "Mention:", message: info_string, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
let okAction = UIAlertAction(title: "OK", style: .Default,
handler: {
action in
self.goToTouchID()
})
alertController.addAction(cancelAction)
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
func goToTouchID(){
print("you click ok, then go to the TouchID page")
performSegueWithIdentifier("showTouchID", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// DataManager.swift
// MMWallet
//
// Created by Dmitry Muravev on 14.07.2018.
// Copyright © 2018 micromoney. All rights reserved.
//
import Foundation
import RealmSwift
class DataManager {
static let shared = DataManager()
private init() {
}
var isNeedReloadWallet = false
var isNeedReloadAssets = false
var isNeedReloadAddress = false
var isNeedReloadContacts = false
func signIn(email: String, password: String, complete: ((AuthModel?, ApiError?, String?) -> ())?) {
let params: [String: Any] = ["email" : email, "password" : password]
ApiManager.shared.signIn(params: params) { (authModel, error, errorString) in
if authModel != nil {
StorageManager.shared.deleteAllUsers()
StorageManager.shared.save(object: authModel!.user!, update: true)
KeychainManager.shared.setSessionToken(value: authModel!.token!)
complete?(authModel, nil, nil)
} else {
complete?(nil, error, errorString)
}
}
}
func signFacebook(token: String, complete: ((AuthModel?, ApiError?, String?) -> ())?) {
let params: [String: Any] = ["token" : token]
ApiManager.shared.signFacebook(params: params) { (authModel, error, errorString) in
if authModel != nil {
StorageManager.shared.deleteAllUsers()
StorageManager.shared.save(object: authModel!.user!, update: true)
KeychainManager.shared.setSessionToken(value: authModel!.token!)
complete?(authModel, nil, nil)
} else {
complete?(nil, error, errorString)
}
}
}
func signGoogle(token: String, complete: ((AuthModel?, ApiError?, String?) -> ())?) {
let params: [String: Any] = ["token" : token]
ApiManager.shared.signGoogle(params: params) { (authModel, error, errorString) in
if authModel != nil {
StorageManager.shared.deleteAllUsers()
StorageManager.shared.save(object: authModel!.user!, update: true)
KeychainManager.shared.setSessionToken(value: authModel!.token!)
complete?(authModel, nil, nil)
} else {
complete?(nil, error, errorString)
}
}
}
func signSocial(networkType: SocialNetworkType , token: String, userId: String?, complete: ((AuthModel?, ApiError?, String?) -> ())?) {
var params: [String: Any] = ["token" : token]
if userId != nil {
params["id"] = userId!
}
ApiManager.shared.signSocial(network: networkType.rawValue, params: params) { (authModel, error, errorString) in
if authModel != nil {
StorageManager.shared.deleteAllUsers()
StorageManager.shared.save(object: authModel!.user!, update: true)
KeychainManager.shared.setSessionToken(value: authModel!.token!)
complete?(authModel, nil, nil)
} else {
complete?(nil, error, errorString)
}
}
}
func signUp(email: String, password: String, complete: ((AuthModel?, ApiError?, String?) -> ())?) {
let params: [String: Any] = ["email" : email, "password" : password]
ApiManager.shared.signUp(params: params) { (authModel, error, errorString) in
if authModel != nil {
StorageManager.shared.deleteAllUsers()
StorageManager.shared.save(object: authModel!.user!, update: true)
KeychainManager.shared.setSessionToken(value: authModel!.token!)
complete?(authModel, nil, nil)
} else {
complete?(nil, error, errorString)
}
}
}
func logout(complete: ((String?, ApiError?) -> ())?) {
ApiManager.shared.logout() { (error, errorString) in
if error == nil {
StorageManager.shared.deleteAllUsers()
complete?(nil, nil)
} else {
complete?(nil, error)
}
}
}
func getUser(complete: ((UserModel?, _ error: ApiError?) -> ())?) {
ApiManager.shared.getUser { (userModel, error) in
if userModel != nil {
StorageManager.shared.deleteAllUsers()
StorageManager.shared.save(object: userModel!, update: true)
//let userModelFromCache = StorageManager.shared.getUsers()
//complete?(userModelFromCache, nil)
} else {
complete?(nil, error)
}
}
//let userModelFromCache = StorageManager.shared.getUsers()
//complete?(userModelFromCache, nil)
}
func getWallet(isNeedFromCache: Bool, complete: ((WalletModel?, _ error: ApiError?) -> ())?) {
ApiManager.shared.getWallet { (walletModel, error) in
if walletModel != nil {
StorageManager.shared.deleteWallet()
StorageManager.shared.save(object: walletModel!, update: true)
let walletFromCache = StorageManager.shared.getWallet()
complete?(walletFromCache, nil)
} else {
complete?(nil, error)
}
}
if isNeedFromCache {
let walletFromCache = StorageManager.shared.getWallet()
complete?(walletFromCache, nil)
}
}
func createWallet(password: String, complete: ((WalletModel?, _ error: ApiError?) -> ())?) {
let params: [String: Any] = ["password" : password]
ApiManager.shared.createWallet(params: params) { (walletModel, error) in
if walletModel != nil {
SessionManager.shared.start(words: password)
StorageManager.shared.save(object: walletModel!, update: true)
let walletFromCache = StorageManager.shared.getWallet()
complete?(walletFromCache, nil)
} else {
complete?(nil, error)
}
}
}
func getAsset(id: Int, complete: ((AssetDetailModel?, _ error: ApiError?) -> ())?) {
ApiManager.shared.getAsset(id: id) { (assetModel, error) in
if assetModel != nil {
StorageManager.shared.save(object: assetModel!, update: true)
let assetFromCache = StorageManager.shared.getAssetDetail(id: id)
complete?(assetFromCache, nil)
} else {
complete?(nil, error)
}
}
let assetFromCache = StorageManager.shared.getAssetDetail(id: id)
complete?(assetFromCache, nil)
}
func createAsset(name:String, currency:String, password: String, complete: ((AssetModel?, _ error: ApiError?, String?) -> ())?) {
let params: [String: Any] = ["name": name, "currency": currency, "password" : password]
ApiManager.shared.createAsset(params: params) { (assetModel, error, errorString) in
if assetModel != nil {
SessionManager.shared.start(words: password)
StorageManager.shared.save(object: assetModel!, update: true)
let assetFromCache = StorageManager.shared.getAsset(id: assetModel!.id)
complete?(assetFromCache, nil, nil)
} else {
complete?(nil, error, errorString)
}
}
}
func importTokenAsset(name:String, currency:String, password: String, key: String?, address: String?, complete: ((AssetModel?, _ error: ApiError?, String?) -> ())?) {
var params: [String: Any] = ["name": name, "currency": currency, "password" : password]
if key != nil {
params["key"] = key
}
if address != nil {
params["token"] = address
}
ApiManager.shared.importAsset(params: params) { (assetModel, error, errorString) in
if assetModel != nil {
SessionManager.shared.start(words: password)
StorageManager.shared.save(object: assetModel!, update: true)
let assetFromCache = StorageManager.shared.getAsset(id: assetModel!.id)
complete?(assetFromCache, nil, nil)
} else {
complete?(nil, error, errorString)
}
}
}
func getCurrencyRates(complete: (([CurrencyRateModel]?, _ error: ApiError?) -> ())?) {
let startDate = Date()
let components = DateComponents(day: -7)
let endDate = Calendar.current.date(byAdding: components, to: startDate)!
let dateFromFormatter = DateFormatter()
dateFromFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFromFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let startDateString = dateFromFormatter.string(from: startDate)
let endDateString = dateFromFormatter.string(from: endDate)
let params: [String: Any] = ["start" : endDateString, "end" : startDateString, "rates": "BTC,ETH"]
ApiManager.shared.getCurrencyRates(params: params) { (currencyRateModels, error) in
if currencyRateModels != nil {
StorageManager.shared.save(objects: currencyRateModels!, update: true)
let currencyRatesFromCache = StorageManager.shared.getCurrencyRates()
complete?(currencyRatesFromCache, nil)
} else {
complete?(nil, error)
}
}
let currencyRatesFromCache = StorageManager.shared.getCurrencyRates()
complete?(currencyRatesFromCache, nil)
}
func getTransaction(id: Int, complete: ((TransactionDetailModel?, _ error: ApiError?) -> ())?) {
ApiManager.shared.getTransaction(id: id) { (transactionDetailModel, error) in
if transactionDetailModel != nil {
StorageManager.shared.save(object: transactionDetailModel!, update: true)
let assetFromCache = StorageManager.shared.getTransactionDetail(id: id)
complete?(assetFromCache, nil)
} else {
complete?(nil, error)
}
}
let assetFromCache = StorageManager.shared.getTransactionDetail(id: id)
complete?(assetFromCache, nil)
}
func getTransactions(complete: (([TransactionModel]?, _ error: ApiError?) -> ())?) {
ApiManager.shared.getTransactions { (transactionModels, error) in
if transactionModels != nil {
StorageManager.shared.save(objects: transactionModels!, update: true)
let transactionsFromCache = StorageManager.shared.getTransactions()
complete?(transactionsFromCache, nil)
} else {
complete?(nil, error)
}
}
let transactionsFromCache = StorageManager.shared.getTransactions()
complete?(transactionsFromCache, nil)
}
func getContactTransactions(contactId: Int, complete: (([TransactionModel]?, _ error: ApiError?) -> ())?) {
ApiManager.shared.getContactTransactions(contactId: contactId) { (transactionModels, error) in
if transactionModels != nil {
StorageManager.shared.save(objects: transactionModels!, update: true)
//let transactionsFromCache = StorageManager.shared.getTransactions()
//complete?(transactionsFromCache, nil)
complete?(transactionModels, nil)
} else {
complete?(nil, error)
}
}
//let transactionsFromCache = StorageManager.shared.getTransactions()
//complete?(transactionsFromCache, nil)
}
func deleteAsset(assetId: Int, complete: ((String?, ApiError?) -> ())?) {
ApiManager.shared.deleteAsset(assetId: assetId) { (error, errorString) in
if error == nil {
StorageManager.shared.deleteAsset(assetId: assetId)
complete?(nil, nil)
} else {
complete?(nil, error)
}
}
}
func getTransactionCost(currency: String, complete: ((SpeedPriceModel?, _ error: ApiError?) -> ())?) {
let params: [String: Any] = ["currency" : currency]
ApiManager.shared.getTransactionCost(params: params) { (speedPriceModel, error) in
if speedPriceModel != nil {
speedPriceModel!.id = currency
speedPriceModel!.low?.id = currency + ":" + "low"
speedPriceModel!.medium?.id = currency + ":" + "medium"
speedPriceModel!.high?.id = currency + ":" + "high"
StorageManager.shared.save(object: speedPriceModel!, update: true)
let speedPriceFromCache = StorageManager.shared.getSpeedPrice(id: currency)
complete?(speedPriceFromCache, nil)
} else {
complete?(nil, error)
}
}
let speedPriceFromCache = StorageManager.shared.getSpeedPrice(id: currency)
complete?(speedPriceFromCache, nil)
}
func getTransactionTokenCost(password: String, symbol: String, tokenAddress: String, toAddress: String, amount: Int, complete: ((SpeedPriceModel?, _ error: ApiError?) -> ())?) {
let params: [String: Any] = ["password" : password, "token" : tokenAddress, "address" : toAddress, "amount" : amount]
ApiManager.shared.getTransactionTokenCost(params: params) { (speedPriceModel, error) in
if error == nil {
SessionManager.shared.start(words: password)
}
if speedPriceModel != nil {
speedPriceModel!.id = symbol
speedPriceModel!.low?.id = symbol + ":" + "low"
speedPriceModel!.medium?.id = symbol + ":" + "medium"
speedPriceModel!.high?.id = symbol + ":" + "high"
StorageManager.shared.save(object: speedPriceModel!, update: true)
let speedPriceFromCache = StorageManager.shared.getSpeedPrice(id: symbol)
complete?(speedPriceFromCache, nil)
} else {
complete?(nil, error)
}
}
let speedPriceFromCache = StorageManager.shared.getSpeedPrice(id: symbol)
complete?(speedPriceFromCache, nil)
}
func sendMoney(assetId: Int, address: String, speed: String, password: String, value: String, complete: ((TransactionModel?, _ error: ApiError?, String?) -> ())?) {
let params: [String: Any] = ["to": address, "value": value, "speed": speed, "password": password]
ApiManager.shared.sendMoney(id: assetId, params: params) { (transactionModel, error, errorString) in
if transactionModel != nil {
SessionManager.shared.start(words: password)
StorageManager.shared.save(object: transactionModel!, update: true)
let transactionFromCache = StorageManager.shared.getTransaction(id: transactionModel!.id)
complete?(transactionFromCache, nil, nil)
} else {
complete?(nil, error, errorString)
}
}
}
func getConverter(from: String, to: String, amount: Double, complete: ((ConverterModel?, _ error: ApiError?) -> ())?) {
var params: [String: Any] = [:]
params["from"] = from
params["to"] = to
params["amount"] = amount
let newId: String = from + ":" + to
ApiManager.shared.getConverter(params: params) { (converterModel, error) in
if converterModel != nil {
converterModel!.id = newId
converterModel!.from = from
converterModel!.to = to
StorageManager.shared.save(object: converterModel!, update: true)
let converterModelFromCache = StorageManager.shared.getConverter(id: newId)
complete?(converterModelFromCache, nil)
} else {
complete?(nil, error)
}
}
let converterModelFromCache = StorageManager.shared.getConverter(id: newId)
complete?(converterModelFromCache, nil)
}
func exportPrivateKey(assetId: Int, password: String, complete: (([ExportKeyModel]?, _ error: ApiError?, String?) -> ())?) {
let params: [String: Any] = ["password": password, "type": "privateKey"]
ApiManager.shared.exportPrivateKey(id: assetId, params: params) { (exportKeyModels, error, errorString) in
if exportKeyModels != nil {
SessionManager.shared.start(words: password)
//StorageManager.shared.save(object: exportKeyModel!, update: true)
//let transactionFromCache = StorageManager.shared.getTransaction(id: transactionModel!.id)
complete?(exportKeyModels, nil, nil)
} else {
complete?(nil, error, errorString)
}
}
}
func exportKeystore(assetId: Int, pass: String, password: String, complete: (([ExportKeystoreModel]?, _ error: ApiError?, String?) -> ())?) {
let params: [String: Any] = ["password": password, "type": "keystore", "pass": pass]
ApiManager.shared.exportKeystore(id: assetId, params: params) { (exportKeystoreModels, error, errorString) in
if exportKeystoreModels != nil {
SessionManager.shared.start(words: password)
complete?(exportKeystoreModels, nil, nil)
} else {
complete?(nil, error, errorString)
}
}
}
func importKeystore(name:String, currency:String, password: String, keystore: String, pass: String, complete: ((AssetModel?, _ error: ApiError?, String?) -> ())?) {
let params: [String: Any] = ["name": name, "password": password, "currency": currency, "keystore" : keystore, "pass": pass]
ApiManager.shared.importAsset(params: params) { (assetModel, error, errorString) in
if assetModel != nil {
SessionManager.shared.start(words: password)
StorageManager.shared.save(object: assetModel!, update: true)
let assetFromCache = StorageManager.shared.getAsset(id: assetModel!.id)
complete?(assetFromCache, nil, nil)
} else {
complete?(nil, error, errorString)
}
}
}
func checkAddress(address: String, complete: ((String?, _ error: ApiError?) -> ())?) {
let params: [String: Any] = ["address": address]
ApiManager.shared.checkAddress(params: params) { (currencyString, error) in
if currencyString != nil {
complete?(currencyString, nil)
} else {
complete?(nil, error)
}
}
}
func findTokenByAddress(address: String, complete: (([TokenInfoModel]?, _ error: ApiError?) -> ())?) {
let params: [String: Any] = ["text": address]
ApiManager.shared.findTokenByAddress(params: params) { (tokenInfoModels, error) in
if tokenInfoModels != nil {
StorageManager.shared.save(objects: tokenInfoModels!, update: true)
complete?(tokenInfoModels, nil)
} else {
complete?(nil, error)
}
}
}
func resendEmailToVerify(complete: ((UserModel?, _ error: ApiError?) -> ())?) {
ApiManager.shared.resendEmailToVerify() { (userModel, error) in
if userModel != nil {
StorageManager.shared.save(object: userModel!, update: true)
complete?(userModel, nil)
} else {
complete?(nil, error)
}
}
}
func sendEmailToVerify(email:String, complete: ((UserModel?, _ error: ApiError?) -> ())?) {
let params: [String: Any] = ["email": email]
ApiManager.shared.sendEmailToVerify(params: params) { (userModel, error) in
if userModel != nil {
StorageManager.shared.save(object: userModel!, update: true)
complete?(userModel, nil)
} else {
complete?(nil, error)
}
}
}
func getFirstAsset(currency: String) -> AssetModel? {
return StorageManager.shared.getAssets(currency: currency)?.first
}
func testEmailConfirmation() {
if let user = StorageManager.shared.getUsers()?.first {
if user.confirmed == false {
if user.email.isEmpty {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
let verifyEmailView = R.nib.sendVerifyEmailView.firstView(owner: nil)
UIApplication.shared.keyWindow?.addSubview(verifyEmailView!)
verifyEmailView!.snp.makeConstraints { (make) -> Void in
make.top.equalTo(0)
make.left.equalTo(0)
make.width.equalTo(UIScreen.main.bounds.width)
make.height.equalTo(UIScreen.main.bounds.height)
}
verifyEmailView!.configureView(userId: user.id)
}
} else {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
let verifyEmailView = R.nib.verifyEmailView.firstView(owner: nil)
UIApplication.shared.keyWindow?.addSubview(verifyEmailView!)
verifyEmailView!.snp.makeConstraints { (make) -> Void in
make.top.equalTo(0)
make.left.equalTo(0)
make.width.equalTo(UIScreen.main.bounds.width)
make.height.equalTo(UIScreen.main.bounds.height)
}
verifyEmailView!.configureView(userId: user.id)
}
}
}
}
}
func testPasswordConfirmation() {
if let user = StorageManager.shared.getUsers()?.first {
if !user.secret.isEmpty {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
let passwordView = R.nib.passwordView.firstView(owner: nil)
UIApplication.shared.keyWindow?.addSubview(passwordView!)
passwordView!.snp.makeConstraints { (make) -> Void in
make.top.equalTo(0)
make.left.equalTo(0)
make.width.equalTo(UIScreen.main.bounds.width)
make.height.equalTo(UIScreen.main.bounds.height)
}
passwordView!.configureView(password: user.secret)
}
}
}
}
}
|
//
// File.swift
//
//
// Created by Nickolay Truhin on 31.03.2021.
//
import Foundation
func openUrl(_ port: Int = 80) -> String {
let command = "ssh -R 80:localhost:\(port) localhost.run"
let task = Process()
let pipe = Pipe()
task.standardOutput = pipe
task.arguments = ["-c", command]
task.launchPath = "/bin/zsh"
task.launch()
sleep(5)
task.interrupt()
let bgTask = Process()
bgTask.arguments = ["-c", command]
bgTask.launchPath = "/bin/zsh"
bgTask.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)!
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: text,
range: NSRange(text.startIndex..., in: text))
return results.map {
String(text[Range($0.range, in: text)!])
}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
let res = matches(for: "\\S+(localhost.run)", in: output).last!
return res
}
|
//
// FirstView.swift
// SwiftUIApp
//
// Created by Artem Pecherukin on 09.03.2020.
// Copyright © 2020 pecherukin. All rights reserved.
//
import SwiftUI
struct FirstView: View {
@Binding var destinationTabIndex: Int
@Binding var shouldShowFoodItem: Bool
var body: some View {
Button(action: {
self.destinationTabIndex = 1
self.shouldShowFoodItem = true
}) {
Text("Go to Food List first item")
}
}
}
|
//
// BarChartViewController.swift
// ChartsDemo-OSX
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// Copyright © 2017 thierry Hentic.
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
import Foundation
import Cocoa
import Charts
open class BubbleChartViewController: NSViewController, ChartViewDelegate
{
@IBOutlet var chartView: BubbleChartView!
var mytitle = "Bubble Chart"
override open func viewDidAppear()
{
super.viewDidAppear()
view.window!.title = "Bubble Chart"
}
override open func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// MARK: General
chartView.delegate = self
chartView.pinchZoomEnabled = false
chartView.doubleTapToZoomEnabled = false
chartView.drawGridBackgroundEnabled = true
chartView.drawBordersEnabled = true
// MARK: xAxis
let xAxis = chartView.xAxis
xAxis.labelPosition = .bottom
xAxis.drawGridLinesEnabled = true
xAxis.granularity = 1
xAxis.axisMaximum = 120.0
xAxis.axisMinimum = 0.0
// xAxis.nameAxis = "Impact"
// xAxis.nameAxisEnabled = true
// MARK: leftAxis
let leftAxis = chartView.leftAxis
leftAxis.drawGridLinesEnabled = true
leftAxis.drawZeroLineEnabled = true
leftAxis.axisMaximum = 10.0
// leftAxis.nameAxis = "Probability"
// leftAxis.nameAxisEnabled = true
// MARK: rightAxis
let rightAxis = chartView.rightAxis
rightAxis.enabled = false
// chartView.leftAxis1.enabled = false
// chartView.rightAxis1.enabled = false
// MARK: legend
let legend = chartView.legend
legend.enabled = true
legend.verticalAlignment = .center
legend.horizontalAlignment = .right
legend.orientation = .vertical
legend.form = .line
// MARK: description
chartView.chartDescription?.enabled = false
self.updateChartData()
}
func updateChartData()
{
setDataCount(7, range: 100.0)
}
func setDataCount(_ count: Int, range: Double)
{
// MARK: BubbleChartDataEntry
let datas = [[10.0,6.0,60.0],[30.0,8.0,240.0],[90.0,5.0,450.0],[50.0,2.0,100.0]]
let label = ["Foo", "Baz","Bar", "Spong"]
var entries = [BubbleChartDataEntry]()
let data = BubbleChartData()
let colors = [#colorLiteral(red: 0.01680417731, green: 0.1983509958, blue: 1, alpha: 1),#colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1),#colorLiteral(red: 0.5843137503, green: 0.8235294223, blue: 0.4196078479, alpha: 1),#colorLiteral(red: 0.9764705896, green: 0.850980401, blue: 0.5490196347, alpha: 1)]
for index in 0..<4
{
entries.removeAll()
let x = datas[index][0]
let y = datas[index][1]
let size = datas[index][2] / 10
entries.append(BubbleChartDataEntry(x: x, y: y, size: CGFloat(size)))
// MARK: BubbleChartDataSet
let set = BubbleChartDataSet(values: entries, label: label[index])
set.setColor(colors[index])
set.valueTextColor = NSUIColor.black
set.valueFont = NSUIFont.systemFont(ofSize: CGFloat(10.0))
set.drawValuesEnabled = true
set.normalizeSizeEnabled = false
set.formSize = 30.0
data.addDataSet(set)
}
chartView.data = data
}
public func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
print("Bubble selected")
}
}
//// MARK: - ChartViewDelegate
//extension BarChartViewController: ChartViewDelegate
//{
// public func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight)
// {
// print("chartValueSelected : x = \(highlight.x)")
// }
//
// public func chartValueNothingSelected(_ chartView: ChartViewBase)
// {
// print("chartValueNothingSelected")
// }
//}
|
let b = 1
let c: Int = 1
let d: Int = 1, e = 2
let f: [Int], g:[Int:Int], h:[Double:[Bool:String]]
var dict = [12:34, 45:56]
print(dict)
|
// RUN: rm -rf %t && mkdir %t
// RUN: cp %s %t/main.swift
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -primary-file %t/main.swift -emit-reference-dependencies-path - > %t.swiftdeps
// RUN: FileCheck %s < %t.swiftdeps
// RUN: FileCheck -check-prefix=NEGATIVE %s < %t.swiftdeps
// REQUIRES: objc_interop
import Foundation
// CHECK-LABEL: provides-dynamic-lookup:
@objc class Base : NSObject {
// CHECK-DAG: - "foo"
func foo() {}
// CHECK-DAG: - "bar"
func bar(_ x: Int, y: Int) {}
// FIXME: We don't really need this twice, but de-duplicating is effort.
// CHECK-DAG: - "bar"
func bar(_ str: String) {}
// CHECK-DAG: - "prop"
var prop: String?
// CHECK-DAG: - "unusedProp"
var unusedProp: Int = 0
// CHECK-DAG: - "classFunc"
class func classFunc() {}
}
func getAnyObject() -> AnyObject? { return nil }
// CHECK-LABEL: depends-dynamic-lookup:
func testDynamicLookup(_ obj: AnyObject) {
// CHECK-DAG: - !private "foo"
obj.foo()
// CHECK-DAG: - !private "bar"
obj.bar(1, y: 2)
obj.bar("abc")
// CHECK-DAG: - !private "classFunc"
obj.dynamicType.classFunc()
// CHECK-DAG: - !private "prop"
_ = obj.prop
// CHECK-DAG: - !private "description"
_ = obj.description
// CHECK-DAG: - !private "method"
_ = obj.method(5, with: 5.0 as Double)
// CHECK-DAG: - !private "subscript"
_ = obj[2] as AnyObject
_ = obj[2] as AnyObject!
}
// CHECK-DAG: - "counter"
let globalUse = getAnyObject()?.counter
// NEGATIVE-LABEL: depends-dynamic-lookup:
// NEGATIVE-NOT: "cat1Method"
// NEGATIVE-NOT: "unusedProp"
|
//
// Utils.swift
// CoreDataStack
//
// Created by Ryan Yan on 1/19/18.
// Copyright © 2018 Jiaqi Yan. All rights reserved.
//
import Foundation
class Utils {
static func randomString(length: Int) -> String {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let len = UInt32(letters.length)
var randomString = ""
for _ in 0 ..< length {
let rand = arc4random_uniform(len)
var nextChar = letters.character(at: Int(rand))
randomString += NSString(characters: &nextChar, length: 1) as String
}
return randomString
}
static func randomNumber(min: Int, max: Int) -> Int{
return Int(arc4random_uniform(UInt32(max - min))) + min
}
static func randomName() -> String{
return Utils.randomString(length: Utils.randomNumber(min:1, max:10))
}
static func randomGender() -> Gender{
return Utils.randomNumber(min: 0, max: 2) == 1 ? Gender.Female : Gender.Male
}
}
|
import UIKit
class TagEntryController: UIViewController {
@IBOutlet private weak var tagTable: UITableView! {
didSet {
self.tagTable.registerNibWithTitle(TagTitleCell.nameString, withBundle: Bundle.tagBundle)
self.tagTable.dataSource = self.tableDataSource
self.tableDataSource.tableView = self.tagTable
self.tagTable.delegate = self
}
}
private lazy var tableDataSource: TableArrayDataSource<Tag> = {
let temp = TableArrayDataSource<Tag>(anArray: [], withCellIdentifier: TagTitleCell.nameString, andCustomizeClosure: self.setupCell)
return temp
}()
private lazy var datePicker: UIDatePicker = {
let picker = UIDatePicker()
picker.minimumDate = Date()
return picker
}()
private lazy var datePickerToolbar: UIToolbar = {
let toolBarFrame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 35)
let toolbar = UIToolbar(frame: toolBarFrame)
toolbar.items = ([.cancel(self), .flexibleSpace, .done(self)] as [BarButtonHelper]).map { $0.button }
return toolbar
}()
private lazy var suggestionView: SuggestionView = SuggestionView(suggestion: self.setSuggestion)
private var currentTextField: UITextField? {
return UIResponder.first as? UITextField
}
var suggestions: ((String, (([Tag]) -> Void)) -> Void)?
var tagPassBack: (([Tag]) -> Void)?
var tags: TagContainer = TagContainer(tags: []) {
didSet {
self.tags.set = self.set
}
}
private func set(Tags tags: OrderedSet<Tag>) {
tableDataSource.updateData([tags.contents])
}
// Data Picker Buttons
@objc
func done(_ button: UIBarButtonItem) {
// current cell tag execute
currentTextField?.resignFirstResponder()
}
@objc
func cancel(_ button: UIBarButtonItem) {
if let ctf = currentTextField {
presentSuggestionView(ctf)
}
}
// End Data Picker Buttons
@IBAction func close(_ sender: UIBarButtonItem) {
if let text = currentTextField?.text, text != "" {
tags.insert(Tag: Tag.tag(text))
}
let final = self.tags.removeAddTag()
self.tagPassBack?(final)
self.dismiss(animated: true, completion: nil)
}
private func setupCell(cell: UITableViewCell, item: Tag, path: IndexPath) {
(cell as? TagTitleCell)?.tagValue = item
(cell as? TagTitleCell)?.fieldDelegate = self
}
private func presentSuggestionView(_ textField: UITextField) {
let shouldReset = textField.inputAccessoryView != nil
textField.inputView = nil
textField.inputAccessoryView = suggestionView
resetInputViews(shouldReset)
}
private func resetInputViews(_ reset: Bool) {
if reset {
currentTextField?.reloadInputViews()
}
}
private func setSuggestion(ByTag tag: Tag) {
self.tags.currentTag = tag
currentTextField?.text = tag.value
}
private func getCurrentCell(FromTextField textfield: UITextField) -> TagTitleCell? {
guard let index = self.getIndex(FromTextField: textfield)
else { return nil }
return self.tagTable.cellForRow(at: index) as? TagTitleCell
}
}
@available(iOS 11.0, *)
extension TagEntryController: UITableViewDelegate {
func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let action = UIContextualAction(style: .destructive, title: "Remove") { (_, _, success) in
self.tags.remove(AtIndex: indexPath.row-1)
self.tableDataSource.removeItemAt(IndexPath: indexPath)
success(true)
}
action.backgroundColor = .red
return UISwipeActionsConfiguration(actions: [action])
}
}
extension TagEntryController: UITextFieldDelegate {
private func getSuggestions(byText text: String) {
suggestions?(text) { suggestions in
self.suggestionView.suggestions = suggestions
}
}
private func getIndex(FromTextField textField: UITextField) -> IndexPath? {
let point = textField.convert(textField.frame.origin, to: self.tagTable)
return self.tagTable.indexPathForRow(at: point)
}
func textFieldDidBeginEditing(_ textField: UITextField) {
getSuggestions(byText: "")
if let index = getIndex(FromTextField: textField) {
tags.startEditing(AtIndex: index.row)
presentSuggestionView(textField)
if tags.currentTag == .addTag {
textField.text = ""
}
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
if let index = getIndex(FromTextField: textField) {
self.tags.doneEditing(AtIndex: index.row)
}
if !(textField.text?.isEmpty ?? false) {
tagTable.reloadData()
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let tagText: String = NSString(string: textField.text ?? "").replacingCharacters(in: range, with: string)
self.tags.currentTag = Tag.tag(tagText)
getSuggestions(byText: tagText)
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
|
//
// EZBrickApp.swift
// EZBrick
//
// Created by Leozítor Floro on 03/09/20.
//
import SwiftUI
@main
struct EZBrickApp: App {
var body: some Scene {
WindowGroup {
let app = EZBrickViewModel()
EZBrickView(viewModel: app)
}
}
}
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
A view controller that demonstrates how to present a search controller's search bar within a navigation bar.
*/
import UIKit
class SearchBarEmbeddedInNavigationBarViewController: SearchControllerBaseViewController, UISearchBarDelegate {
// MARK: Properties
// `searchController` is set in viewDidLoad(_:).
var searchController: UISearchController!
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// Create the search results view controller and use it for the UISearchController.
let searchResultsController = storyboard!.instantiateViewControllerWithIdentifier(SearchResultsViewController.StoryboardConstants.identifier) as! SearchResultsViewController
// Create the search controller and make it perform the results updating.
searchController = UISearchController(searchResultsController: searchResultsController)
searchController.searchResultsUpdater = searchResultsController
searchController.hidesNavigationBarDuringPresentation = false
// Configure the search controller's search bar. For more information on how to configure
// search bars, see the "Search Bar" group under "Search".
searchController.searchBar.searchBarStyle = .Minimal
searchController.searchBar.placeholder = NSLocalizedString("Search", comment: "")
searchController.searchBar.showsCancelButton = true;
for v in searchController.searchBar.subviews[0].subviews{
if ( v.isKindOfClass(UIButton) ){
let cancelButton = v as! UIButton;
cancelButton.setTitle("Cancel", forState: UIControlState.Normal);
cancelButton.tintColor = UIColor.whiteColor();
cancelButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal);
}
if (v.isKindOfClass(UITextField))
{
let searchField = v as! UITextField
searchField.tintColor = UIColor.whiteColor()
searchField.textColor = UIColor.whiteColor()
}
}
// var searchField = searchController.searchBar.valueForKey("_searchField")
// UITextField *searchField = [searchBar valueForKey:"_searchField"]
// Change search bar text color
// searchField?.color = UIColor.whiteColor()
// searchField?.color = UIColor.whiteColor()
// Change the search bar placeholder text color
// [searchField setValue:[UIColor blackColor] forKeyPath:@"_placeholderLabel.textColor"];
// searchController.searchBar.
searchController.searchBar.delegate = self
// Include the search bar within the navigation bar.
navigationItem.titleView = searchController.searchBar
definesPresentationContext = true
}
func searchBarSearchButtonClicked( searchBar: UISearchBar)
{
var searcharray:NSArray
var userDefault = NSUserDefaults.standardUserDefaults()
searchhistory.addObject(searchController.searchBar.text)
searcharray = searchhistory
userDefault.setObject(searcharray, forKey: "search history")
userDefault.synchronize()
println( searchController.searchBar.text)
}
@IBAction func goBack(sender: AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
rootController.navigationController?.setNavigationBarHidden(true, animated: true)
}
override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
}
override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 40))
// footerView.backgroundColor = UIColor.blackColor()
var x = tableView.frame.size.width
x -= 120
x = x/2
var searchresetbutton:UIButton = UIButton(frame: CGRectMake(x, 0, 120, 30))
searchresetbutton.titleLabel?.font = UIFont.boldSystemFontOfSize(15)
searchresetbutton.setTitleColor(UIColor.grayColor(),forState:UIControlState.Normal)
searchresetbutton.setTitle("清空搜索记录", forState:UIControlState.Normal)
searchresetbutton.setBackgroundImage(UIImageView(image: UIImage(named: "清空搜索记录.png")).image, forState: UIControlState.Normal)
searchresetbutton.addTarget(self, action:Selector("searchresetbuttonClicked:"), forControlEvents:UIControlEvents.TouchDown)
if(searchhistory.count != 0)
{
footerView.addSubview(searchresetbutton)
}
return footerView
}
func searchresetbuttonClicked(sender:UIButton)
{
searchhistory.removeAllObjects()
var searcharray:NSArray = searchhistory
var userDefault = NSUserDefaults.standardUserDefaults()
userDefault.setObject(searcharray, forKey: "search history")
userDefault.synchronize()
tableView.reloadData()
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//searchString = tableView.cellForRowAtIndexPath(indexPath)?.textLabel?.text
var str = tableView.cellForRowAtIndexPath(indexPath)?.textLabel?.text
GlobalData.searchstring = str!
//searchString = str!
// println(tableView.cellForRowAtIndexPath(indexPath)?.textLabel?.text)
println(str)
/*
let searchResultsController = storyboard!.instantiateViewControllerWithIdentifier(SearchResultsViewController.StoryboardConstants.identifier) as! SearchResultsViewController
// Create the search controller and make it perform the results updating.
searchControllerbase = UISearchController(searchResultsController: searchResultsController)
searchControllerbase.searchResultsUpdater = searchResultsController
searchControllerbase.hidesNavigationBarDuringPresentation = false
// Configure the search controller's search bar. For more information on how to configure
// search bars, see the "Search Bar" group under "Search".
searchControllerbase.searchBar.searchBarStyle = .Minimal
searchControllerbase.searchBar.placeholder = NSLocalizedString("Search", comment: "")
searchControllerbase.searchBar.delegate = self
var str = tableView.cellForRowAtIndexPath(indexPath)?.textLabel?.text
// println(tableView.cellForRowAtIndexPath(indexPath)?.textLabel?.text)
println(str)
// searchResultsController.baseResult(str!) // Include the search bar within the navigation bar.
navigationItem.titleView = searchControllerbase.searchBar
definesPresentationContext = true
self.navigationController?.pushViewController(searchControllerbase, animated: true)*/
}
/*
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 40.0
}
*/
/*
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
let destinationController = segue.destinationViewController as! QuickSearchResultViewController
destinationController.searchString = searchString //传值
}
}
*/
}
|
import PetriKit
/// Analyzes a bounded Petri net to determine some of its properties.
func analyze<PlaceSet>(
_ model: PTNet<PlaceSet>,
withInitialMarking initialMarking: Marking<PlaceSet, UInt>)
{
guard let states = computeGraph(of: model, from: initialMarking) else { //calcul ensemble de graphes de marquages
print("The model is unbounded") //non borné
return
}
print("There are \(states.count) state(s) accessible from the initial marking.") //le nombre d etats dans le réseau
// What is the bound of the model?
model.transitions
let bound = states.map( { state in state.marking.map({ (_, token) in token }).max()! }).max()! //states : noeuds de graphe
print("The model is \(bound)-bounded.")
// Ou la deuxieme sol
// var bound: UInt = 0
// for state in states {
// for(_, token) in state.marking {
// bound = max(bound, token)
// }
// }
// Is the model L3-live (i.e. "vivant")? L3-Live : est-ce que le rés est vivant
let isL3 = model.transitions.allSatisfy({ transition in
states.allSatisfy({ m in
m.contains(where: { transition.isFireable(from: $0.marking)})
})
})
print("The model is\(!isL3 ? " not" : "") L3-live.")
// Is the model L1-live (i.e. "quasi-vivant")?
let isL1 = model.transitions.allSatisfy({ transition in
states.contains(where: { transition.isFireable(from: $0.marking)})
})
print("The model is\(!isL1 ? " not" : "") L1-live.")
// Is the model dead?
let isDead = states.contains(where: { state in state.successors.isEmpty })
//2eme sol
//let isDead2 = states.allSatisfy ({ state in
// models.transitions.contains(where: { $0.isFireable(from: state.marking) })
// })
print("The model is\(!isDead ? " not" : "") dead.")
let deadState = states.first(where: { state in state.successors.isEmpty })!
print(deadState.marking)
}
|
//
// MapViewController.swift
// iOS-TraningsDagboken
//
// Created by Eddy Garcia on 2018-09-25.
// Copyright © 2018 Eddy Garcia. All rights reserved.
//
import UIKit
import MapKit
class MapViewController: UIViewController {
@IBOutlet var mapView : MKMapView!
//var workoutPost = WorkoutPost()
var workoutPost : WorkoutPostMO!
override func viewDidLoad() {
super.viewDidLoad()
//forward geocoding
let geoCoder = CLGeocoder()
geoCoder.geocodeAddressString(workoutPost.adress ?? "", completionHandler: {placemarks, error in
if let error = error {
print(error)
return
}//get placemark
if let placemarks = placemarks {
let placemark = placemarks[0]
//add annotation
let annotation = MKPointAnnotation()
annotation.title = self.workoutPost.location
annotation.subtitle = self.workoutPost.adress
if let location = placemark.location{
annotation.coordinate = location.coordinate
//display annotation
self.mapView.showAnnotations([annotation], animated: true)
self.mapView.selectAnnotation(annotation, animated: true)
}
}
})
mapView.showsScale = true
mapView.showsCompass = true
mapView.showsPointsOfInterest = true
mapView.showsBuildings = true
mapView.showsUserLocation = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// TestViewController.swift
// carolina_fever_0
//
// Created by Caleb Kang on 7/31/19.
// Copyright © 2019 Caleb Kang. All rights reserved.
//
import UIKit
import Parse
/*This view controller is the parent view controller
of CalendarView and the ListView. This view has a segmental
control that switches between the two views so that users can
view the schedule in list form and in calenar form*/
class ScheduleViewController: UIViewController {
// MARK: - Properties
var schedule = [Game]()
var hasScrolled = false
var isParent = true
// MARK: - Outlets
// this switches the schedule type
@IBOutlet var scheduleSwitcher: UISegmentedControl!
// MARK: - Schedule View Controllers
// ListView controller
lazy var listViewController: ListScheduleViewController = {
// get list view and add to this view as a child
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
var viewController = storyboard.instantiateViewController(withIdentifier: "ListScheduleViewController") as! ListScheduleViewController
viewController.schedule = self.schedule
self.addChild(viewController)
return viewController
}()
// CalendarView controller
lazy var calendarViewController: CalendarScheduleViewController = {
// get calendar view and add to this view as a child
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
var viewController = storyboard.instantiateViewController(withIdentifier: "CalendarScheduleViewController") as! CalendarScheduleViewController
viewController.schedule = self.schedule;
self.addChild(viewController)
return viewController
}()
lazy var gameViewController: GameViewController = {
// get GameController and add to the view
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
var viewController = storyboard.instantiateViewController(withIdentifier: "GameController") as! GameViewController
self.addChild(viewController)
return viewController
}()
override func viewDidLoad() {
super.viewDidLoad()
// Make Title 'Schedule'
self.navigationController?.navigationBar.topItem?.title = "Schedule"
/*Queries server for all FEVER games*/
let gamesQuery = PFQuery(className: "Game")
gamesQuery.whereKey("student", equalTo: "")
gamesQuery.findObjectsInBackground(block: { (objects: [PFObject]?, error: Error?) in
if let games = objects {
var i = 0;
while i < games.count {
let game = games[i]
do {
try game.fetchIfNeeded()
self.schedule.append(Game("", game["date"] as! NSDate, game["description"] as! NSString, game["points"] as! NSNumber, game["location"] as! NSString, game["sport"] as! NSString))
} catch {
print("couldnt fetch game object")
}
i += 1
}
/*sorts games by date*/
self.schedule.sort(by: { (first: Game, second: Game) -> Bool in
let result = first.getDate().compare(second.getDate() as Date)
return result == ComparisonResult.orderedAscending
})
/*set the initial view is the LIST schedule view*/
self.scheduleSwitcher.selectedSegmentIndex = 0
self.addChild(self.listViewController)
self.removeChild(viewController: self.calendarViewController)
self.removeChild(viewController: self.gameViewController)
}
})
}
// MARK: - Actions
@IBAction @ objc func scheduleSwitched(_ sender: UISegmentedControl) {
if scheduleSwitcher.selectedSegmentIndex == 0 { // user chooses ListView so display list view
listViewController.schedule = schedule
listViewController.tableView.reloadData()
addChild(listViewController)
removeChild(viewController: gameViewController)
removeChild(viewController: calendarViewController)
} else { // user choose calendar view so display calendar view
addChild(calendarViewController)
removeChild(viewController: listViewController)
removeChild(viewController: gameViewController)
}
}
// MARK: - Helper Methods
override func addChild(_ childController: UIViewController) {
super.addChild(childController)
// child view is added as subview. bounds should match with parent's
view.addSubview(childController.view)
childController.view.frame = view.bounds
childController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
childController.didMove(toParent: self)
}
/*remove subview from the superview*/
func removeChild(viewController: UIViewController) {
viewController.willMove(toParent: nil)
viewController.view.removeFromSuperview()
viewController.removeFromParent()
}
}
|
//
// ViewController.swift
// tips
//
// Created by VietCas on 2/21/16.
// Copyright © 2016 VietCas. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var billTextField: UITextField!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var tipPercentLabel: UILabel!
@IBOutlet weak var resultView: UIView!
var tipPercentage = 0.18
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tipLabel.text = "$0.00"
totalLabel.text = "$0.00"
billTextField.textColor = UIColor.whiteColor()
billTextField.delegate = self
let defaults = NSUserDefaults.standardUserDefaults()
if let lastDateActiveObj = defaults.objectForKey("last_date_active") {
let billValue = defaults.objectForKey("bill_value") as! String
let lastDateActive = lastDateActiveObj as! NSDate
let date = NSDate()
if date.timeIntervalSinceDate(lastDateActive) < 60 {
billTextField.text = billValue
}
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationWillResignActive", name: UIApplicationWillResignActiveNotification, object: nil)
}
//MARK: - Observe Notification Application State
func applicationWillResignActive() {
let defaults = NSUserDefaults.standardUserDefaults()
let date = NSDate()
defaults.setValue(date, forKey: "last_date_active")
if let billText = billTextField.text {
defaults.setValue(billText, forKey: "bill_value")
}
defaults.synchronize()
}
override func viewWillAppear(animated: Bool) {
let defaults = NSUserDefaults.standardUserDefaults()
let isDarkTheme = defaults.boolForKey("is_dark_theme")
if isDarkTheme {
view.backgroundColor = UIColor.darkGrayColor()
resultView.backgroundColor = UIColor.blueColor()
} else {
view.backgroundColor = UIColor.lightGrayColor()
resultView.backgroundColor = UIColor.orangeColor()
}
let tips = [0.18, 0.2, 0.25]
let tipIndex = defaults.integerForKey("tip_segment_index")
tipPercentage = tips[tipIndex]
billTextField.becomeFirstResponder()
updateTip()
showViewOrInputOnly()
}
//MARK: - Handle ViewInput
func showInputViewOnly() {
UIView.animateWithDuration(0.4) { () -> Void in
self.updateChildFramePosition(350, billsFrameY: 190)
}
}
func showResultView() {
UIView.animateWithDuration(0.4) { () -> Void in
self.updateChildFramePosition(200, billsFrameY: 100)
}
}
func updateChildFramePosition(resultsFrameY: CGFloat, billsFrameY: CGFloat) {
var resultFrame = self.resultView.frame
resultFrame.origin.y = resultsFrameY
self.resultView.frame = resultFrame
var billFrame = self.billTextField.frame
billFrame.origin.y = billsFrameY
self.billTextField.frame = billFrame
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func updateTip() {
let billAmount = NSString(string: billTextField.text!).doubleValue
let tip = billAmount * tipPercentage
let total = billAmount + tip
tipLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", total)
tipPercentLabel.text = String(format: "%.f%%", tipPercentage * 100)
}
func showViewOrInputOnly() {
if billTextField.text != nil {
if(billTextField.text!.isEmpty) {
showInputViewOnly()
} else {
showResultView()
updateTip()
}
}
}
// MARK: - UITextFieldDelegate
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if(!string.isEmpty) {
let number = Int(string)
if number == nil {
return false
}
}
return true;
}
@IBAction func onEditingChanged(sender: AnyObject) {
showViewOrInputOnly()
}
@IBAction func onTap(sender: AnyObject) {
}
}
|
import MarketKit
class PredefinedBlockchainService {
private let restoreSettingsManager: RestoreSettingsManager
init(restoreSettingsManager: RestoreSettingsManager) {
self.restoreSettingsManager = restoreSettingsManager
}
}
extension PredefinedBlockchainService {
func prepareNew(account: Account, blockchainType: BlockchainType) {
var restoreSettings: RestoreSettings = [:]
switch blockchainType {
case .zcash:
if let birthdayHeight = RestoreSettingType.birthdayHeight.createdAccountValue(blockchainType: blockchainType) {
restoreSettings[.birthdayHeight] = birthdayHeight
}
default: ()
}
if !restoreSettings.isEmpty {
restoreSettingsManager.save(settings: restoreSettings, account: account, blockchainType: blockchainType)
}
}
}
|
import UIKit
import Alamofire
var emprestimos = [Emprestimo]()
var celulaHistorico = "CelulaHistorico"
class HistoricoTableViewController: UITableViewController {
var item = Item()
let basicCellIdentifier = "CelulaHistorico"
@IBOutlet var tabelaHistorico: UITableView!
override func viewWillAppear(_ animated: Bool) {
tableView.tableFooterView = UIView(frame: CGRect.zero)
buscarHistorico { (lista) in
if lista.count > 0 {
self.tabelaHistorico.reloadData()
} else {
print("Lista Vazia")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
configureTableView()
}
func configureTableView() {
tabelaHistorico.rowHeight = UITableViewAutomaticDimension
tabelaHistorico.estimatedRowHeight = 135.0
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return emprestimos.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return basicCellAtIndexPath(indexPath)
}
func basicCellAtIndexPath(_ indexPath:IndexPath) -> HistoricoTableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: basicCellIdentifier) as! HistoricoTableViewCell
setDataEmprestimo(cell, indexPath: indexPath)
setResponsavel(cell, indexPath: indexPath)
setDataDevolucao(cell, indexPath: indexPath)
return cell
}
func setDataEmprestimo(_ cell:HistoricoTableViewCell, indexPath:IndexPath) {
let dataEmprestimo = emprestimos[indexPath.row].dataEmprestimo
cell.dataEmprestimo.text = "Data empréstimo : \(dataEmprestimo)"
}
func setResponsavel(_ cell:HistoricoTableViewCell, indexPath:IndexPath) {
let item = emprestimos[indexPath.row].responsavel
cell.responsavel.text = "Responsável: \(item) "
}
func setDataDevolucao(_ cell:HistoricoTableViewCell, indexPath:IndexPath) {
let dataDevolucao = emprestimos[indexPath.row].dataDevolucao
let dataPrevistaDevolucao = emprestimos[indexPath.row].dataPrevistaDevolucao
if dataDevolucao.isEmpty {
cell.dataDevolucao.text = "Data prevista Devolucão : \(dataPrevistaDevolucao) "
} else {
cell.dataDevolucao.text = "Data de Devolucão : \(dataDevolucao) "
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (emprestimos.count > 0) {
// Enviar o dado que está no Array e não na tabela.
if segue.identifier == "segueToDetalhe" {
if let _ = segue.destination as? DetalheViewController {
if let indexTabela = tabelaHistorico.indexPathForSelectedRow?.row {
let emprestimo = emprestimos[indexTabela]
item.id = emprestimo.idItem
buscarItem { (item) in
if item.id != "" {
self.tabelaHistorico.reloadData()
} else {
print("")
}
}
}
}
}
}
}
func buscarItem(_ completionHandler: @escaping (Item) -> ()) -> () {
let item : Item = Item();
_ = "\(Endereco().enderecoConexao)/item/buscar/\(item.id)"
Alamofire.request(.GET, "http://httpbin.org/get")
.responseJSON { JSON in
let retorno = JSON.2.value as! NSArray;
for it in retorno {
item.id = it.valueForKey("id") as! String
item.nome = it.valueForKey("nome") as! String
item.idCategoria = it.valueForKey("idCategoria") as! String
}
completionHandler(item)
}
}
func buscarHistorico(_ completionHandler: @escaping ([Emprestimo]) -> ()) -> () {
emprestimos.removeAll(keepingCapacity: true)
let urlJson = "\(Endereco().enderecoConexao)/emprestimo/buscar/\(item.id)"
Alamofire.request(.GET, urlJson).responseJSON {JSON in
let retorno = JSON.2.value as! NSArray;
for it in retorno {
let item : Emprestimo = Emprestimo();
item.id = it.valueForKey("id") as! String
item.dataEmprestimo = it.valueForKey("dataEmprestimo") as! String
let dataDevolucao: AnyObject? = it.valueForKey("dataDevolucao")
if (dataDevolucao != nil) {
item.dataDevolucao = dataDevolucao as! String
}
item.dataPrevistaDevolucao = it.valueForKey("dataPrevistaDevolucao") as! String
item.responsavel = it.valueForKey("responsavel") as! String
item.idItem = it.valueForKey("idItem") as! String
emprestimos.append(item)
}
completionHandler(emprestimos)
}
}
}
|
//
// ProjectController.swift
// Schematic Capture
//
// Created by Gi Pyo Kim on 2/12/20.
// Copyright © 2020 GIPGIP Studio. All rights reserved.
//
import Foundation
import CoreData
import FirebaseStorage
class ProjectController {
var bearer: Bearer?
var user: User?
var projects: [ProjectRepresentation] = []
// private let baseURL = URL(string: "https://sc-be-production.herokuapp.com/api")!
// private let baseURL = URL(string: "https://sc-be-staging.herokuapp.com/api")!
// private let baseURL = URL(string: "https://sc-test-be.herokuapp.com/api")!
private let baseURL = URL(string: "http://localhost:5000/api")!
// Download assigned jobs (get client, project, job, csv as json)
func downloadAssignedJobs(completion: @escaping (NetworkingError?) -> Void = { _ in }) {
guard let bearer = self.bearer else {
completion(.noBearer)
return
}
let requestURL = self.baseURL.appendingPathComponent("jobsheets").appendingPathComponent("assigned")
var request = URLRequest(url: requestURL)
request.httpMethod = HTTPMethod.get.rawValue
request.setValue("Bearer \(bearer.token)", forHTTPHeaderField: HeaderNames.authorization.rawValue)
request.setValue("application/json", forHTTPHeaderField: HeaderNames.contentType.rawValue)
URLSession.shared.dataTask(with: request) { (data, _, error) in
if let error = error {
print("Error getting assigned jobs: \(error)")
completion(.serverError(error))
return
}
guard let data = data else {
print("No data returned from data task")
completion(.noData)
return
}
//TODO: debug statement
print("\ninside download assigned jobs\n \(String(data: data, encoding: .utf8)!) \n\n")
// decode projects
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
do {
let projectsRep = try decoder.decode([ProjectRepresentation].self, from: data)
self.updateProjects(with: projectsRep)
self.projects = projectsRep
self.projects.sort { $0.id < $1.id }
print("\n\nPROJECTS: \(self.projects)\n\n")
} catch {
print("Error decoding the jobs: \(error)")
completion(.badDecode)
}
completion(nil)
}.resume()
print("0. Last line of downloadAssigned Jobs Executed")
}
private func updateProjects(with representations: [ProjectRepresentation]) {
let identifiersToFetch = representations.map({ $0.id })
// [UUID: TaskRepresentation]
let representationsByID = Dictionary(uniqueKeysWithValues: zip(identifiersToFetch, representations))
// Make a mutable copy of the dictionary above
var projectsToCreate = representationsByID
let context = CoreDataStack.shared.container.newBackgroundContext()
context.performAndWait {
do {
// Figure out which ones are new
let fetchRequest: NSFetchRequest<Project> = Project.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "id IN %@", identifiersToFetch)
// We need to run the context.fetch on the main queue, because the context is the main context
let existingProjects = try context.fetch(fetchRequest)
// Update the ones we do have
for project in existingProjects {
// Grab the ProjectRepresentation that corresponds to this Project
let id = Int(project.id)
// guard let representation = representationsByID[id] else { continue }
// // update the ones that are in core data
// project.name = representation.name
// //project.clientId = representation.clientId
// project.clientId = Int32(representation.clientId)
// let jobSheetArr = representation.jobSheets
// project.jobSheets = jobSheetArr != nil ? NSSet(array: jobSheetArr!) : nil
//
// // We just updated a task, we don't need to create a new Task for this identifier
projectsToCreate.removeValue(forKey: id)
}
// Figure out which ones we don't have
for representation in projectsToCreate.values {
// Create Projects from project representations
let project = Project(projectRepresentation: representation, context: context)
// Connect JobSheet to Project relationship
if let jobSheetsSet = project.jobSheets,
let jobSheets = jobSheetsSet.sortedArray(using: [NSSortDescriptor(key: "id", ascending: true)]) as? [JobSheet] {
for jobSheet in jobSheets{
jobSheet.ownedProject = project
// Connect Component to JobSheet relationship
if let componentsSet = jobSheet.components,
let components = componentsSet.sortedArray(using: [NSSortDescriptor(key: "id", ascending: true)]) as? [Component] {
for component in components {
component.ownedJobSheet = jobSheet
// Connect Photo to Component relationship
if let photo = component.photo {
photo.ownedComponent = component
}
}
}
}
}
}
// Persist all the changes (updating and creating of tasks) to Core Data
CoreDataStack.shared.save(context: context)
} catch {
NSLog("Error fetching tasks from persistent store: \(error)")
}
}
print("1.Last line of updateProjects executed")
}
// Download schematic from firebase storage
func downloadSchematics(completion: @escaping (NetworkingError?) -> Void = { _ in }) {
guard let user = user, let _ = bearer else {
completion(.noBearer)
return
}
let maxSize: Int64 = 1073741824 // 1GB
let storage = Storage.storage()
let storageRef = storage.reference()
for project in projects {
guard var jobSheets = project.jobSheets else {
completion(.error("No job sheets found"))
return
}
jobSheets.sort { $0.id < $1.id }
for jobSheet in jobSheets {
var pdfRef: String?
let schematicRef = storageRef.child("\(project.clientId)")
.child("\(project.id)")
.child("\(jobSheet.id)")
schematicRef.listAll { (listResult, error) in
if let error = error {
completion(.error("\(error)"))
return
}
let listFullPaths = listResult.items.map { $0.fullPath }
for path in listFullPaths {
if path.contains(".PDF") || path.contains(".pdf") {
pdfRef = path
break
}
}
// guard let pdfRef = pdfRef else {
// completion(.error("No PDF file found in \(schematicRef.fullPath)"))
// return
// }
// commenting out so that no pdf wont break function
// let start = pdfRef.lastIndex(of: "/")!
// let newStart = pdfRef.index(after: start)
// let range = newStart..<pdfRef.endIndex
// let pdfNameString = String(pdfRef[range])
//
// schematicRef.child(pdfNameString).getData(maxSize: maxSize) { (data, error) in
// if let error = error {
// print("\(error)")
// completion(.serverError(error))
// return
// }
// guard let data = data else {
// print("No schematic pdf returned")
// completion(.noData)
// return
// }
// self.updateSchematic(pdfData: data, name: pdfNameString, jobSheetRep: jobSheet)
// completion(nil)
// }
// }
}
}
print("2. Last line of DownloadSchematics executed")
}
//
func updateSchematic(pdfData: Data, name: String, jobSheetRep: JobSheetRepresentation) {
let context = CoreDataStack.shared.container.newBackgroundContext()
context.performAndWait {
do {
// Figure out which ones are new
let fetchRequest: NSFetchRequest<JobSheet> = JobSheet.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "projectId == %@ AND id == %@", NSNumber(value: jobSheetRep.projectId), NSNumber(value: jobSheetRep.id))
// We need to run the context.fetch on the main queue, because the context is the main context
let jobSheets = try context.fetch(fetchRequest)
// There should only one job sheet with the given ID
if let jobSheet = jobSheets.first {
//jobSheet.schematicData = pdfData
jobSheet.schematicName = name
CoreDataStack.shared.save(context: context)
}
} catch {
NSLog("Error fetching tasks from persistent store: \(error)")
}
}
}
print("3.last line of update schematics executed")
// Upload jobs in core data (check the status of the jobs)
}
}
|
//
// SteppView.swift
// computerelements
//
// Created by Vladimir Malinovskiy on 20.04.2021.
//
import SwiftUI
import AVKit
struct SteppView: View {
var stepID: Int
var preStepID: Int
var desc: String
var videoName: String
@Binding var videoPl: AVPlayer
var body: some View {
Button(action: {
if videoName != "" {
videoPl = AVPlayer(url: Bundle.main.url(forResource: "\(videoName)", withExtension: "m4v")!)
}
}) {
Text("\(desc)")
}.buttonStyle(PlainButtonStyle())
.onAppear() {
if preStepID == 1 || videoName != "" {
videoPl = AVPlayer(url: Bundle.main.url(forResource: "\(videoName)", withExtension: "m4v")!)
}
}
}
}
struct SteppView_Previews: PreviewProvider {
static var previews: some View {
SteppView(stepID: 1, preStepID: 1, desc: "Достаньте материнскую плату из коробки, вытащите её из антистатического пакета.", videoName: "testAnim", videoPl: Binding.constant(AVPlayer(url: Bundle.main.url(forResource: "testAnim", withExtension: "m4v")!)))
}
}
|
//
// BillsListController.swift
// Jenin Residences
//
// Created by Ahmed Khalaf on 23/4/17.
// Copyright © 2017 pxlshpr. All rights reserved.
//
import UIKit
import FontAwesome
import TinyConstraints
//import BouncyLayout
import RealmSwift
class BillsListController: UIViewController {
var notificationToken: NotificationToken? = nil
//MARK: - Views
lazy var tableView: UITableView = {
let view = UITableView(frame: .zero, style: .grouped)
view.translatesAutoresizingMaskIntoConstraints = false
view.delegate = self
view.dataSource = self
return view
}()
//MARK: - Private
fileprivate var viewModel: BillsListViewModel!
//MARK: - Lifecycle
required convenience init(viewModel: BillsListViewModel) {
self.init(nibName: nil, bundle: nil)
self.viewModel = viewModel
self.setupNavigationAndTabItems()
}
override func viewDidLoad() {
super.viewDidLoad()
self.viewModel.billViewModelsTypes.forEach { $0.registerCell(tableView: tableView) }
self.bindToViewModel()
self.reloadData()
self.addTableView()
view.backgroundColor = .white
view.clipsToBounds = true
NotificationCenter.default.addObserver(self, selector: #selector(realmDidConnect(_:)), name: .RealmConnected, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(dataUpdated(_:)), name: .BillsListUpdated, object: nil)
}
func dataUpdated(_ notification: Notification) {
guard let userInfo = notification.userInfo as? [String: [Int]],
//TODO: use constants for keys
let insertions = userInfo["insertions"],
let deletions = userInfo["deletions"],
let modifications = userInfo["modificatins"] else {
return
}
//TODO: we need to convert the indexes into row and section
tableView.beginUpdates()
tableView.insertRows(at: insertions.map({ IndexPath(row: $0, section: 0) }), with: .automatic)
tableView.deleteRows(at: deletions.map({ IndexPath(row: $0, section: 0)}), with: .automatic)
tableView.reloadRows(at: modifications.map({ IndexPath(row: $0, section: 0) }), with: .automatic)
tableView.endUpdates()
}
func indexPathForBillAtIndex(_ index: Int, fromArray array: [Bill]) -> IndexPath {
//first ensure that the list of bills in addition to the groupings are stored in the viewModel as well\
//group rows based on .currentDate
//create indexPath based on which section and row it's in
return IndexPath(row: 0, section: 0)
}
deinit {
//remove observers here
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let indexPath = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: indexPath, animated: animated)
}
//NEXT: remove this auto refreshing code for now
// refresh()
}
func refresh() {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4), execute: {
self.reloadData()
self.refresh()
})
}
func realmDidConnect(_ notification: Notification) {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(4), execute: {
self.reloadData()
})
}
//MARK: - Helpers
private func setupNavigationAndTabItems() {
self.title = self.viewModel.title
let newButton = UIBarButtonItem(
barButtonSystemItem: .add,
target: self,
action: #selector(tappedNew)
)
newButton.accessibilityLabel = UI.Bills.new
self.navigationItem.rightBarButtonItem = newButton
self.tabBarItem = UITabBarItem(fontAwesomeIconName: self.viewModel.tabBarImageFontAwesome, title: self.viewModel.tabBarTitle)
}
//MARK: - ViewModel
private func bindToViewModel() {
self.viewModel.didUpdate = { [weak self] _ in
self?.viewModelDidUpdate()
}
}
private func viewModelDidUpdate() {
self.navigationItem.title = self.viewModel.title
self.tableView.reloadData()
}
//MARK: - Actions
func reloadData() {
self.viewModel.reloadData()
}
func tappedNew() {
self.viewModel.didSelectAddBill?()
}
//MARK: - Helpers
private func addTableView() {
self.view.addSubview(self.tableView)
self.tableView.edges(to: self.view)
}
}
//MARK: - UITableViewDataSource
extension BillsListController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.viewModel.billViewModels.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return self.viewModel.billViewModels[indexPath.row].dequeueCell(tableView: tableView, indexPath: indexPath)
}
}
//MARK: - UITableViewDelegate
extension BillsListController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.viewModel.billViewModels[indexPath.row].cellSelected()
}
}
extension BillsListController {
enum Pixels {
static let cellHeight: CGFloat = 55.0
}
}
|
//
// MainWindowController.swift
// SpeedReader
//
// Created by Kay Yin on 7/3/17.
// Copyright © 2017 Kay Yin. All rights reserved.
//
import Cocoa
class MainWindowController: NSWindowController, NSSharingServicePickerDelegate {
@IBOutlet weak var shareButton: NSButton!
var detailWindow: ReadDetailWindow?
var prefVC: SRPreferencesViewController?
@IBOutlet weak var readButton: NSButton!
override func windowDidLoad() {
super.windowDidLoad()
self.window?.titleVisibility = NSWindow.TitleVisibility.hidden;
self.window?.styleMask.insert(.fullSizeContentView)
shareButton.sendAction(on: .leftMouseDown)
}
@IBAction func historyClicked(_ sender: Any) {
if let spvc = self.contentViewController as? SRSplitViewController {
spvc.splitViewItems[0].isCollapsed = !spvc.splitViewItems[0].isCollapsed
}
}
@IBAction func addClicked(_ sender: NSView) {
if let vc = storyboard?.instantiateController(withIdentifier: "BlankDocument") as? NSViewController {
self.contentViewController?.present(vc, asPopoverRelativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY, behavior: .transient)
}
}
@IBAction func readClicked(_ sender: Any) {
openReaderWindow()
}
func openReaderWindow() {
detailWindow = nil
if let contentVC = self.contentViewController as? SRSplitViewController {
if let textVC = contentVC.splitViewItems[1].viewController as? ArticleViewController {
detailWindow = storyboard?.instantiateController(withIdentifier: "ReadDetailWindow") as? ReadDetailWindow
if let readVC = detailWindow?.contentViewController as? ReadViewController {
if let article = textVC.article {
readVC.article = article
readVC.articlePreference = article.preference
if let speed = article.preference?.speed {
readVC.readingSliderValue = speed
} else {
readVC.readingSliderValue = 0.7
}
readVC.textToRead = textVC.contentTextView.string
if let font = article.preference?.font as? NSFont {
readVC.font = font
}
if let isDark = article.preference?.isDark {
readVC.enableDark = isDark
}
}
}
detailWindow?.showWindow(self)
}
}
}
@IBAction func shareClicked(_ sender: NSView) {
var shareArray: [String] = []
if let contentVC = self.contentViewController as? SRSplitViewController {
if let textVC = contentVC.splitViewItems[1].viewController as? ArticleViewController {
let article = textVC.contentTextView.string
shareArray.append(article)
}
}
let sharePicker = NSSharingServicePicker.init(items: shareArray)
sharePicker.delegate = self
sharePicker.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
}
@IBAction func preferenceSwapped(_ sender: NSSegmentedControl) {
if let spvc = self.contentViewController as? SRSplitViewController {
spvc.splitViewItems[2].isCollapsed = !spvc.splitViewItems[2].isCollapsed
sender.setSelected(!spvc.splitViewItems[2].isCollapsed, forSegment: 0)
}
}
@IBAction func historySwapped(_ sender: NSSegmentedControl) {
if let spvc = self.contentViewController as? SRSplitViewController {
spvc.splitViewItems[0].isCollapsed = !spvc.splitViewItems[0].isCollapsed
sender.setSelected(!spvc.splitViewItems[0].isCollapsed, forSegment: 0)
}
}
}
|
//
// Socket.swift
// Publius
//
// Created by Ethan Czahor on 10/24/14.
// Copyright (c) 2014 Project Publius. All rights reserved.
//
import Foundation
#if DEBUG
let kSocketHost = "http://192.168.0.5:5000"
#else
let kSocketHost = "ws://projectpublius.com:8080"
#endif
class Socket {
var socket: SIOSocket?
var isConnected: Bool = false
var onNewMessage: ((object: AnyObject!) -> Void)?
class var sharedInstance : Socket {
struct Static {
static let instance : Socket = Socket()
}
return Static.instance
}
func connect(success: (() -> Void)?) {
if !isConnected {
SIOSocket.socketWithHost(kSocketHost) { (socket: SIOSocket!) in
self.socket = socket
self.socket!.onConnect = {
println("socket: connected")
self.isConnected = true
success?()
}
self.socket!.onError = { (error: [NSObject : AnyObject]!) in
println("socket: error")
self.isConnected = false
}
self.socket!.onDisconnect = {
println("socket: disconnected")
self.isConnected = false
}
self.socket!.onReconnect = { (numberOfAttempts: Int) in
println("socket: reconnected, \(numberOfAttempts) attempts")
self.isConnected = true
}
self.socket!.on("new_message", callback: { (data: [AnyObject]!) -> Void in
println("socket: new_message:")
let object: AnyObject! = data[0]
self.onNewMessage?(object: object)
})
}
} else {
success?()
}
}
func join(room:String!) {
println("socket: join: \(room)")
self.socket!.emit("join", args: [room])
}
func leave(room:String!) {
println("socket: leave: \(room)")
self.socket!.emit("leave", args: [room])
}
}
|
import Foundation
public enum ViberBotError: Swift.Error {
case statusCodeError(HTTPURLResponse)
case transportError(Swift.Error)
case decodingError(Swift.Error)
}
|
import UIKit
import XCTest
import TNExtension
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
let string = "Hello"
// let md5Data = string
//
// let md5Hex = md5Data.map { String(format: "%02hhx", $0) }.joined()
// print("md5Hex: \(md5Hex)")
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
|
//
// BookEdit.swift
// Bookworm
//
// Created by Tino on 27/4/21.
//
import SwiftUI
struct BookEdit: View {
let book: Book
@State private var selectedImage: UIImage? = nil
@State private var imageURL: URL? = nil
@Binding var bookInfo: BookInfo
var body: some View {
let urlBinding = Binding<URL?>(
get: { imageURL },
set: {
imageURL = $0
bookInfo.imagePath = imageURL!.lastPathComponent
})
return ZStack {
Color("background")
.ignoresSafeArea()
ScrollView {
VStack(alignment: .leading) {
ImageSelectionView("Tap to select a new book cover", selectedImage: $selectedImage, imageURL: urlBinding)
.floatView(to: .center)
Group {
Text("Title")
TextField(bookInfo.title, text: $bookInfo.title)
}
Group {
Text("Author")
TextField(bookInfo.author, text: $bookInfo.author)
.disableAutocorrection(true)
}
Group {
Text("Genre")
Picker("Genre", selection: $bookInfo.genre) {
ForEach(Genre.allCases) { genre in
Text(genre.rawValue)
}
}
}
Group {
Text("Rating")
HStack {
RatingView(rating: $bookInfo.rating)
Spacer()
LikeButton(isLiked: $bookInfo.isFavourite)
}
}
Group {
Text("Review")
TextView("What are your thoughts on this book", text: $bookInfo.review)
.frame(minHeight: 400)
}
}
.textFieldStyle(MyTextFieldStyle())
.foregroundColor(Color("fontColour"))
}
}
}
}
|
//
// GradesPerQuarter.swift
// ios-charts-api-demo
//
// Created by Joshua de Guzman on 20/04/2018.
// Copyright © 2018 Joshua de Guzman. All rights reserved.
//
import ObjectMapper
struct GradesPerQuarter {
var firstQuarter: Double?
var secondQuarter: Double?
var thirdQuarter: Double?
var fourthQuarter: Double?
}
extension GradesPerQuarter: Mappable{
init?(map: Map) {
//
}
mutating func mapping(map: Map) {
firstQuarter <- map["first_quarter"]
secondQuarter <- map["second_quarter"]
thirdQuarter <- map["third_quarter"]
fourthQuarter <- map["fourth_quarter"]
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.