text stringlengths 8 1.32M |
|---|
//
// AVTextField.swift
// AppVenture
//
// Created by Ashish Chauhan on 07/07/18.
// Copyright © 2018 AppVenturez. All rights reserved.
//
import UIKit
protocol AVTextDelegate: UITextFieldDelegate {
func backspacePressed(textField: UITextField)
}
class AVTextField: UITextField {
override func deleteBackward() {
super.deleteBackward()
guard let avDelete = self.delegate as? AVTextDelegate else { return }
avDelete.backspacePressed(textField: self)
}
}
|
//
// ContentView.swift
// Slot Machine
//
// Created by Jaime Uribe on 10/12/20.
//
import SwiftUI
struct ContentView: View {
//MARK: - PROPERTIES
@State private var highscore: Int = 0
@State private var coins: Int = 100
@State private var betAmount: Int = 10
@State private var showingInfoView: Bool = false
@State private var reels: Array = [0, 1, 2]
@State private var isActiveBet10: Bool = true
@State private var isActiveBet20: Bool = false
let symbols = ["gfx-bell", "gfx-cherry", "gfx-coin", "gfx-grape", "gfx-seven", "gfx-strawberry"]
//MARK: - FUNCTIONS
func spinReels(){
// reels[0] = Int.random(in: 0...symbols.count - 1)
// reels[1] = Int.random(in: 0...symbols.count - 1)
// reels[2] = Int.random(in: 0...symbols.count - 1)
reels = reels.map({_ in
Int.random(in: 0...symbols.count - 1)
})
}
func checkWinning(){
if reels[0] == reels[1] && reels[1] == reels[2] && reels[0] == reels[2]{
// PLAYER WINS
playerWins()
// NEW HIGHSCORE
if coins > highscore{
newHighscore()
}
}else{
// PLAYER LOSES
playerLoses()
}
}
func playerWins(){
coins += betAmount * 10
}
func newHighscore(){
highscore = coins
}
func playerLoses(){
coins -= betAmount
}
func activateBet20(){
betAmount = 20
isActiveBet20 = true
isActiveBet10 = false
}
func activateBet10(){
betAmount = 10
isActiveBet10 = true
isActiveBet20 = false
}
//MARK: - BODY
var body: some View {
ZStack {
//MARK: - BACKGROUND
//El linearGradient permite mezclar los colores
LinearGradient(gradient: Gradient(colors: [Color("ColorPink"), Color("ColorPurple")]), startPoint: .top, endPoint: .bottom).edgesIgnoringSafeArea(.all)
//MARK: - INTERFACE
VStack(alignment: .center, spacing: 5) {
//MARK: - HEADER
LogoView()
Spacer()
//MARK: - SCORE
HStack {
HStack{
Text("Your\nCoint".uppercased())
.scoreLabelStyle()
.multilineTextAlignment(.trailing)
Text("\(coins)")
.scoreNumberStyle()
.modifier(SocoreNumberModifier())
}
.modifier(ScoreConteinerModifier())
Spacer()
HStack{
Text("\(highscore)")
.scoreNumberStyle()
.modifier(SocoreNumberModifier())
Text("Your\nCoint".uppercased())
.scoreLabelStyle()
.multilineTextAlignment(.leading)
}
.modifier(ScoreConteinerModifier())
}
//MARK: - SLOT MACHINE
VStack(alignment: .center, spacing: 0, content: {
//MARK: - REEL #1
ZStack{
ReelView()
Image(symbols[reels[0]])
.resizable()
.modifier(ImageModifier())
}
HStack(alignment: .center, spacing: 0, content: {
//MARK: - REEL #2
ZStack{
ReelView()
Image(symbols[reels[1]])
.resizable()
.modifier(ImageModifier())
}
Spacer()
//MARK: - REEL #3
ZStack{
ReelView()
Image(symbols[reels[2]])
.resizable()
.modifier(ImageModifier())
}
})
//MARK: - REEL # SPIN BUTTON
Button(action: {
// SPIN THE REELS
self.spinReels()
// CHECK THE WINNING
self.checkWinning()
}, label: {
Image("gfx-spin")
.renderingMode(.original)
.resizable()
.modifier(ImageModifier())
})
})// Slot Machine(
.layoutPriority(2)
//MARK: - FOOTER
Spacer()
HStack(alignment: .center, spacing: 5){
HStack {
//MARK: - BET 20
Button(action: {
self.activateBet20()
}, label: {
Text("20")
.fontWeight(.heavy)
.foregroundColor(isActiveBet20 ? Color("ColorYellow") : Color.white)
.modifier(BetNumberModifier())
})
.modifier(BetCapsuleModifier())
Image("gfx-casino-chips")
.resizable()
.opacity(isActiveBet20 ? 1 : 0)
.modifier(CasinoChipsMofifier())
//MARK: - BET 10
Image("gfx-casino-chips")
.resizable()
.opacity(isActiveBet10 ? 1 : 0)
.modifier(CasinoChipsMofifier())
Button(action: {
self.activateBet10()
}, label: {
Text("10")
.fontWeight(.heavy)
.foregroundColor(isActiveBet10 ? Color("ColorYellow") : Color.white)
.modifier(BetNumberModifier())
})
.modifier(BetCapsuleModifier())
}
}
}
//MARK: - BUTTONS
.overlay(
// RESET
Button(action: {
print("Reset image")
}, label: {
Image(systemName: "arrow.2.circlepath.circle")
})
.modifier(ButtonModifier()), alignment: .topLeading
)
.overlay(
// INFO
Button(action: {
self.showingInfoView = true
}, label: {
Image(systemName: "info.circle")
})
.modifier(ButtonModifier()), alignment: .topTrailing
)
.padding()
.frame(maxWidth: 720)
//MARK: -POPUP
}// ZSTACK
.sheet(isPresented: $showingInfoView, content: {
InfoView()
})
}
}
//MARK: - PREVIEW
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
//: Playground - noun: a place where people can play
/*
Write code to find a 8 letter string of characters that contains only letters from
acdegilmnoprstuw
such that the hash(the_string) is
25377615533200
if hash is defined by the following pseudo-code:
Int64 hash (String s) {
Int64 h = 7
String letters = "acdegilmnoprstuw"
for(Int32 i = 0; i < s.length; i++) {
h = (h * 37 + letters.indexOf(s[i]))
}
return h
}
For example, if we were trying to find the 7 letter string where hash(the_string) was 680131659347, the answer would be "leepadg".
*/
import Foundation
extension String {
public func indexOfCharacter(char: Character) -> Int? {
if let idx = self.characters.indexOf(char) {
return self.startIndex.distanceTo(idx)
}
return nil
}
subscript (i: Int) -> Character {
return self[self.startIndex.advancedBy(i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
subscript (r: Range<Int>) -> String {
return substringWithRange(Range(start: startIndex.advancedBy(r.startIndex), end: startIndex.advancedBy(r.endIndex)))
}
}
let letters = "acdegilmnoprstuw"
func hash2(string: String) -> UInt64 {
var h: UInt64 = 7
for s in string.characters {
let index = UInt64((letters.indexOfCharacter(s) ?? 0))
h = h * 37 + index
}
return h
}
func dehash2(hash: UInt64) -> String {
var currentHash = hash
var positionsInSet = [Int: Int]()
for var i=0; currentHash > 37; ++i {
let r = currentHash % 37
positionsInSet[i] = Int(r)
currentHash /= 37
}
var result = ""
for var i=positionsInSet.count - 1; i >= 0; --i {
let index = positionsInSet[i]!
result += letters[index]
}
return result
}
let result = dehash2(25377615533200)
assert(result == "nsanswer")
|
//
// PhotoCell.swift
// MyFbPhotos
//
// Created by Mohamed BOUNAJMA on 10/21/17.
// Copyright © 2017 Mohamed BOUNAJMA. All rights reserved.
//
import UIKit
class PhotoCell: UICollectionViewCell {
@IBOutlet weak var photo: UIImageView!
var photoId: String?
override func awakeFromNib() {
super.awakeFromNib()
}
}
|
//
// HelpViewController.swift
// StockNewsFilter
//
// Created by Aaron Sargento on 4/18/17.
// Copyright © 2017 Aaron Sargento. All rights reserved.
//
import UIKit
class HelpViewController: UIViewController {
@IBOutlet weak var helpTextView: UITextView!
let themeColor = UIColor(red: 95/255, green: 207/255, blue: 153/255, alpha: 1)
let menuManager = MenuManager()
//this will be our tips for 'How To Use FlTR'
let htmlString: String = "<font face=\"MarkerFelt\"><font size =\"6\"><font color=\"themeColor\">Introduction" + "\n" +
"<br /><font face=\"HelveticaNeue\"><font size =\"4\"><font color=\"white\">Let this guide be an updatable and work-in-progress as the strategy gets finely tuned over the progression and development of this strategy. The two main components of this strategy will serve as a starting guide to the journey of any novice stock trader. These two main components are the: Press Releases and Leaderboard." + "\n\n" +
"<br /><br /><font face=\"MarkerFelt\"><font size =\"6\"><font color=\"themeColor\">Press Releases" + "\n" +
"<br /><font face=\"HelveticaNeue\"><font size =\"4\"><font color=\"white\">What is the "Press Releases" section? This section is a curated list of press releases that are hand crafted and curated using a proprietary algorithm which we built to find press releases that meet a certain criteria of "keywords" within the title. These keywords are generally known to spike a stock easily from 50 cents to a few dollars over the course of a few days. We've hand selected the keywords that will be filtered through the apps curation process for now, and have futures updates that will allow you to enter the keywords of your choice." + "\n\n" +
"<br /><br /><font face=\"MarkerFelt\"><font size =\"6\"><font color=\"themeColor\">Leaderboard" + "\n" +
"<br /><font face=\"HelveticaNeue\"><font size =\"4\"><font color=\"white\">What is the "Leaderboard"? The leaderboard is a compilation of stocks that are likely to have risen and had volatile movement on the price of their stock today by 3 simple criteria: i) Low float (under 50,000,000 shares), ii) 5 Percent Change or more on the day, and iii) Volume greater than 250,000 shares traded for that day." + "\n\n" +
"<br /><br /><font face=\"HelveticaNeue\"><font size =\"4\"><font color=\"white\">The reason why these stocks show up in the Leaderboard section is because these generally have the highest odds of making these biggest moves of subsequent days that follow. Again, these criteria usually pick stocks that are volatile, have already shown a big percent gain, and have a user interest by the sheer amount of volume that has been traded on it for the day." + "\n\n" +
"<br /><br /><font face=\"MarkerFelt\"><font size =\"6\"><font color=\"themeColor\">Watch Lists" + "\n" +
"<br /><font face=\"HelveticaNeue\"><font size =\"4\"><font color=\"white\">This section is here for you to pick or add stocks that you feel want to highlight out from the Leaderboard and/or Press Releases. This is strictly as a tool to help make these features more predominant." + "\n\n" +
"<br /><br /><font face=\"MarkerFelt\"><font size =\"6\"><font color=\"themeColor\">Purpose of FLTR" + "\n" +
"<br /><font face=\"HelveticaNeue\"><font size =\"4\"><font color=\"white\">This section and scope really goes beyond the ability of this application. This application can only serve as a vehicle for delivering content that "becomes playable", meaning, stocks that you should be watching. However, identifying exactly when to trade in and out of these plays is something that cannot be easily conveyed through reading of the paragraphs, and it is more important to focus on the overall strategy at large: each morning press releases come out, and certain press releases contain more "weight" in terms of activity and volatility. It is solely up to your discretion whether you feel this press release has enough validity in order to trade."
/*
This function will allow the user to use the Menu
*/
@IBAction func MenuPressed(_ sender: Any) {
menuManager.openMenu()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
navigationController?.navigationBar.barTintColor = themeColor
//preload the tips into the view controller
let encodedData = htmlString.data(using: String.Encoding.utf8)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
helpTextView.attributedText = attributedString
} catch _ {
print("Cannot create attributed String")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// OSTConfiguration.swift
// OnestapSDK
//
// Created by Munir Wanis on 18/08/17.
// Copyright © 2017 Stone Payments. All rights reserved.
//
import Foundation
/// Configuration necessary to initialize the SDK
public struct OSTConfiguration {
/**
All your configuration before start using the SDK should be in here.
- parameters:
- environment: If nothing is passed the default value is **.sandbox**
- clientId: Your Client ID
- clientSecret: Your Client Secret
- host: The `host` registered on URL Types of the application
- scheme: The desired `scheme` to appear on redirect URL
- fingerPrintId: The ID given by **RexLab** to make anti-fraud security. Default value is `nil`
- temporaryProfile: Used to make easier registration of your user. Default value is `nil`
*/
@available(*, deprecated, message: "Fingerprint is not used anymore.")
public init(environment: OSTEnvironmentEnum = .sandbox,
clientId: String,
clientSecret: String,
scheme: String, host: String,
@available(*, deprecated)
fingerPrintId: String? = nil,
temporaryProfile: TemporaryProfile? = nil,
primaryColor: UIColor? = nil,
secondaryColor: UIColor? = nil,
isLogEnabled: Bool = false) {
self.init(environment: environment, clientId: clientId, clientSecret: clientSecret, scheme: scheme, host: host, temporaryProfile: temporaryProfile, primaryColor: primaryColor, secondaryColor: secondaryColor, isLogEnabled: isLogEnabled)
}
/**
All your configuration before start using the SDK should be in here.
- parameters:
- environment: If nothing is passed the default value is **.sandbox**
- clientId: Your Client ID
- clientSecret: Your Client Secret
- host: The `host` registered on URL Types of the application
- scheme: The desired `scheme` to appear on redirect URL
- temporaryProfile: Used to make easier registration of your user. Default value is `nil`
*/
public init(environment: OSTEnvironmentEnum = .sandbox,
clientId: String,
clientSecret: String,
scheme: String, host: String,
temporaryProfile: TemporaryProfile? = nil,
primaryColor: UIColor? = nil,
secondaryColor: UIColor? = nil,
isLogEnabled: Bool = false) {
self.environment = environment
self.clientId = clientId
self.clientSecret = clientSecret
self.scheme = scheme
self.host = host
self.temporaryProfile = temporaryProfile
self.primaryColor = primaryColor
self.secondaryColor = secondaryColor
self.isLogEnabled = isLogEnabled
}
/// Your Client ID
public let clientId: String
/// Your Client Secret
public let clientSecret: String
/// Encoded Client ID and Secret
internal var encodedClient: String {
let clientIdSecret = "\(self.clientId):\(self.clientSecret)"
return clientIdSecret.toBase64()
}
/// Your app host registered on URL Types (e.g.: **somescheme**://somehost), where scheme is everything before `://`.
public let scheme: String
/// Your app scheme (e. g.: somescheme://**somehost**), where host is everything after `://`. You can use anything on host.
public let host: String
/// Redirect Uri created from `scheme` + `host` combination (e.g.: `scheme://host`)
internal var redirectUri: String {
get {
return "\(scheme)://\(host)"
}
}
/// The primary color of your app
public let primaryColor: UIColor?
/// The secondary color of your app
public let secondaryColor: UIColor?
/// Your Finger Print ID if you want to send data to our anti-fraud.
@available(*, deprecated, message: "Fingerprint is not used anymore.")
public let fingerPrintId: String? = nil
/// The environment you want to use our SDK, the options are `sandbox` and `production` environments. The default value is **sandbox**
public let environment: OSTEnvironmentEnum
/// When `temporaryProfile` is not nil it'll complete registration steps for the user
public let temporaryProfile: TemporaryProfile?
/// If temporaryProfile is set, the DataKey should be filled
internal var temporaryProfileDataKey: String? = nil
internal let isLogEnabled: Bool
}
|
//
// CookieShopViewModel.swift
// cookie-jar
//
// Created by Gabriel Siu on 2019-08-22.
// Copyright © 2019 Gabriel Siu. All rights reserved.
//
import Foundation
final class CookieShopViewModel {
private let dataService: DataService
private let cookieService: CookieService
init(dataService: DataService, cookieService: CookieService) {
self.dataService = dataService
self.cookieService = cookieService
}
// MARK: Methods
func getCurrentPointsString() -> String {
let numPoints = dataService.points
return "Points: \(numPoints)"
}
func getCookies() -> [Cookie] {
return cookieService.cookies
}
}
|
//
// String.swift
// SurpriseMe
//
// Created by Evan Grossman on 9/10/16.
// Copyright © 2016 Evan Grossman. All rights reserved.
//
import Foundation
extension String {
var localized: String {
return NSLocalizedString(self, tableName: nil, bundle: NSBundle.mainBundle(), value: "", comment: "")
}
func localized(interpolatedArguments: [CVarArgType]) -> String {
return String(format: self.localized, arguments: interpolatedArguments)
}
} |
//
// CountryWeatherCell.swift
// CCW
//
// Created by seungbong on 2020/02/03.
// Copyright © 2020 한승희. All rights reserved.
//
import UIKit
class CountryWeatherCell: UITableViewCell {
@IBOutlet weak var countryImg: UIImageView!
@IBOutlet weak var countryName: 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
}
}
|
//
// Response2.swift
// Musinic
//
// Created by Student on 5/2/19.
// Copyright © 2019 Student. All rights reserved.
//
import Foundation
class Response2 : Codable {
var tracks : [Tracks2]?
}
|
//
// ViewController.swift
// Obligatoriov1
//
// Created by SP07 on 14/4/16.
// Copyright © 2016 SP07. All rights reserved.
//
import UIKit
class ViewControllerTarjeta: UIViewController {
let defaults = NSUserDefaults.standardUserDefaults()
var puntos : Int = 1001
@IBOutlet weak var labelPuntos: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
labelPuntos.text = "Puntos: " + puntos.description
let email = defaults.stringForKey("Email")
let password = defaults.stringForKey("Password")
if email == nil || password == nil{
self.performSegueWithIdentifier("toLogin", sender: nil)
}
let myTimer = NSTimer(timeInterval: 15.0, target: self, selector: #selector(ViewControllerTarjeta.refresh), userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(myTimer, forMode: NSDefaultRunLoopMode)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func refresh() {
puntos += 1
labelPuntos.text = "Puntos: " + puntos.description
}
var cambio : Int = 1
@IBOutlet var btnCambio: UIButton!
@IBAction func btnTarjeta(sender: AnyObject) {
if (cambio == 1){
btnCambio.setImage(generateQRCode(), forState: .Normal)
cambio = 2
}else{
btnCambio.setImage(UIImage (named: "tarjeta_puntos_ds_y_wii"), forState: .Normal)
cambio = 1
}
}
func generateQRCode()->UIImage? {
let data = "ucu@ucu.com".dataUsingEncoding(NSISOLatin1StringEncoding)
if let filter = CIFilter(name: "CIQRCodeGenerator") {
filter.setValue(data, forKey: "inputMessage")
filter.setValue("H", forKey: "inputCorrectionLevel")
let transform = CGAffineTransformMakeScale(10, 10)
if let output = filter.outputImage?.imageByApplyingTransform(transform) {
return UIImage(CIImage: output)
}
}
return nil
}
} |
//
// LoginViewController.swift
// DemoLoginFirebase
//
// Created by Rangga Djatikusuma Lukman on 08/10/19.
// Copyright © 2019 Codekinian. All rights reserved.
//
import UIKit
import Firebase
class LoginViewController: UIViewController {
@IBOutlet weak var identityTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var messageErrorLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setUpElement()
}
func setUpElement() {
messageErrorLabel.alpha = 0
Utilities.styleTextField(identityTextField)
Utilities.styleTextField(passwordTextField)
Utilities.styleFilledButton(loginButton)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
@IBAction func loginTapped(_ sender: Any) {
// Validate
// data clean
let identity = identityTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let password = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
// Signin
Auth.auth().signIn(withEmail: identity, password: password) { (res, err) in
if err != nil {
self.showError(err!.localizedDescription)
}else{
self.redirectToHome()
}
}
}
func redirectToHome() {
let homeViewController = storyboard?.instantiateViewController(identifier: Constants.Storyboard.homeViewController) as? HomeViewController
view.window?.rootViewController = homeViewController
view.window?.makeKeyAndVisible()
}
func showError(_ message: String) {
messageErrorLabel.alpha = 1
messageErrorLabel.text = message
}
}
|
//
// GroupMembersView.swift
// berkeley-mobile
//
// Created by Patrick Cui on 1/30/21.
// Copyright © 2021 ASUC OCTO. All rights reserved.
//
import UIKit
fileprivate let kViewMargin: CGFloat = 10
/// View holding a CollectionView to display all members of the input study group
class GroupMembersView: UIView {
static let cellsPerRow = 2
var studyGroupMembers: [StudyGroupMember] = []
var parentView: UIViewController = UIViewController()
private var collectionHeightConstraint: NSLayoutConstraint!
private let collection: UICollectionView = {
let collection = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout.init())
collection.translatesAutoresizingMaskIntoConstraints = false
collection.register(GroupMemberCell.self, forCellWithReuseIdentifier: GroupMemberCell.kCellIdentifier)
collection.backgroundColor = .clear
collection.showsVerticalScrollIndicator = false
collection.layer.masksToBounds = true
collection.contentInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
collection.contentInsetAdjustmentBehavior = .never
return collection
}()
public init(studyGroupMembers: [StudyGroupMember], parentView: UIViewController) {
super.init(frame: .zero)
self.studyGroupMembers = studyGroupMembers
self.parentView = parentView
collection.delegate = self
collection.dataSource = self
self.addSubview(collection)
collection.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
collection.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
collection.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
collection.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
collectionHeightConstraint = collection.heightAnchor.constraint(equalToConstant: 120)
collectionHeightConstraint.priority = .defaultLow
collectionHeightConstraint.isActive = true
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = UICollectionViewFlowLayout()
let width = Int(collection.frame.width - 20) / GroupMembersView.cellsPerRow
let heightOfCellRatio = UIScreen.main.bounds.width / 375
layout.itemSize = CGSize(width: width, height: Int(160 * heightOfCellRatio))
layout.minimumLineSpacing = 10
collection.collectionViewLayout = layout
collection.reloadData()
let height = collection.collectionViewLayout.collectionViewContentSize.height + 16
collectionHeightConstraint.constant = height
self.layoutIfNeeded()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension GroupMembersView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.studyGroupMembers.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GroupMemberCell.kCellIdentifier, for: indexPath)
let index = indexPath.row
if let groupMemberCell = cell as? GroupMemberCell {
groupMemberCell.configure(groupMember: studyGroupMembers[index], parentView: parentView)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
}
/// Cell displaying information for members of a single study view
class GroupMemberCell: UICollectionViewCell {
static let kCellIdentifier = "groupMemberCell"
private var _member: StudyGroupMember!
private var _parentView: UIViewController!
private var profileRadius: CGFloat {
get {
return frame.width * 0.2
}
}
// MARK: UI Elements
let nameLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = Font.regular(12)
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.6
return label
}()
let avatar: UIImageView = {
let imgView = UIImageView()
imgView.translatesAutoresizingMaskIntoConstraints = false
imgView.contentMode = .scaleAspectFill
return imgView
}()
var emailButton: QuickActionButton!
var msgButton: QuickActionButton!
var callButton: QuickActionButton!
@objc func emailTapped() {
UIPasteboard.general.string = _member.email
_parentView.presentSuccessAlert(title: "Email copied to clipboard.")
}
@objc func msgTapped() {
if _member.facebookUsername != nil {
if let url = URL(string: "https://m.me/" + _member.facebookUsername!) {
UIApplication.shared.open(url)
}
} else {
_parentView.presentFailureAlert(title: "Failed to launch messenger", message: "This user did not input their facebook user name.")
}
}
@objc func callTapped() {
if _member.phoneNumber != nil {
UIPasteboard.general.string = _member.phoneNumber
_parentView.presentSuccessAlert(title: "Phone number copied to clipboard.")
} else {
_parentView.presentFailureAlert(title: "Failed to copy phone number", message: "This user did not input their phone number.")
}
}
// MARK: Setup
override init(frame: CGRect) {
super.init(frame: frame)
let card = CardView()
card.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(card)
card.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
card.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
card.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
card.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
card.addSubview(nameLabel)
nameLabel.centerXAnchor.constraint(equalTo: card.centerXAnchor).isActive = true
nameLabel.centerYAnchor.constraint(equalTo: card.centerYAnchor, constant: kViewMargin).isActive = true
nameLabel.leftAnchor.constraint(greaterThanOrEqualTo: card.leftAnchor, constant: 5).isActive = true
nameLabel.rightAnchor.constraint(lessThanOrEqualTo: card.rightAnchor, constant: 5).isActive = true
card.addSubview(avatar)
avatar.centerXAnchor.constraint(equalTo: card.centerXAnchor).isActive = true
avatar.bottomAnchor.constraint(equalTo: nameLabel.topAnchor, constant: -kViewMargin / 2).isActive = true
avatar.widthAnchor.constraint(equalTo: card.widthAnchor, multiplier: 0.4).isActive = true
avatar.heightAnchor.constraint(equalTo: card.widthAnchor, multiplier: 0.4).isActive = true
avatar.layer.cornerRadius = profileRadius
avatar.backgroundColor = UIColor.lightGray
avatar.clipsToBounds = true
avatar.layer.masksToBounds = true
emailButton = QuickActionButton(iconImage: UIImage(named:"email"))
emailButton.translatesAutoresizingMaskIntoConstraints = false
card.addSubview(emailButton)
emailButton.centerXAnchor.constraint(equalTo: card.centerXAnchor).isActive = true
emailButton.widthAnchor.constraint(equalToConstant: frame.width * 0.25).isActive = true
emailButton.heightAnchor.constraint(equalToConstant: frame.width * 0.25).isActive = true
emailButton.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: kViewMargin).isActive = true
emailButton.addTarget(self, action: #selector(emailTapped), for: .touchUpInside)
msgButton = QuickActionButton(iconImage: UIImage(named:"messenger"))
msgButton.translatesAutoresizingMaskIntoConstraints = false
card.addSubview(msgButton)
msgButton.rightAnchor.constraint(equalTo: emailButton.leftAnchor, constant: -kViewMargin / 2).isActive = true
msgButton.widthAnchor.constraint(equalToConstant: frame.width * 0.25).isActive = true
msgButton.heightAnchor.constraint(equalToConstant: frame.width * 0.25).isActive = true
msgButton.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: kViewMargin).isActive = true
msgButton.addTarget(self, action: #selector(msgTapped), for: .touchUpInside)
callButton = QuickActionButton(iconImage: UIImage(named:"phone-studyPact"))
callButton.translatesAutoresizingMaskIntoConstraints = false
card.addSubview(callButton)
callButton.leftAnchor.constraint(equalTo: emailButton.rightAnchor, constant: kViewMargin / 2).isActive = true
callButton.widthAnchor.constraint(equalToConstant: frame.width * 0.25).isActive = true
callButton.heightAnchor.constraint(equalToConstant: frame.width * 0.25).isActive = true
callButton.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: kViewMargin).isActive = true
callButton.addTarget(self, action: #selector(callTapped), for: .touchUpInside)
//PLACEHOLDER CODE FOR PING BUTTON
// let memberPingButton = RoundedActionButton(title: "Ping to Study", font: Font.regular(8), color: UIColor(red: 0.984, green: 0.608, blue: 0.557, alpha: 1), iconImage: UIImage(named: "studyGroupBell"), iconSize: 14, cornerRadius: 12, iconOffset: -30)
// memberPingButton.translatesAutoresizingMaskIntoConstraints = false
// card.addSubview(memberPingButton)
// memberPingButton.leftAnchor.constraint(equalTo: card.leftAnchor, constant: 20).isActive = true
// memberPingButton.rightAnchor.constraint(equalTo: card.rightAnchor, constant: -20).isActive = true
// memberPingButton.topAnchor.constraint(equalTo: emailButton.bottomAnchor, constant: kViewMargin).isActive = true
// memberPingButton.bottomAnchor.constraint(equalTo: card.bottomAnchor, constant: -kViewMargin).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func configure(groupMember: StudyGroupMember, parentView: UIViewController) {
_member = groupMember
_parentView = parentView
nameLabel.text = groupMember.name
msgButton.isEnabled = _member.facebookUsername != nil
callButton.isEnabled = _member.phoneNumber != nil
let placeholderLetter = String(_member.name.first ?? "O").uppercased()
let placeholderView = ProfileLabel(text: placeholderLetter, radius: profileRadius, fontSize: 25)
avatar.addSubview(placeholderView)
placeholderView.translatesAutoresizingMaskIntoConstraints = false
placeholderView.leftAnchor.constraint(equalTo: avatar.leftAnchor).isActive = true
placeholderView.rightAnchor.constraint(equalTo: avatar.rightAnchor).isActive = true
placeholderView.topAnchor.constraint(equalTo: avatar.topAnchor).isActive = true
placeholderView.bottomAnchor.constraint(equalTo: avatar.bottomAnchor).isActive = true
if let url = groupMember.profilePictureURL {
ImageLoader.shared.getImage(url: url) { result in
switch result {
case .success(let image):
DispatchQueue.main.async {
self.avatar.image = image
placeholderView.isHidden = true
}
case .failure(let error):
print(error)
}
}
}
}
}
class QuickActionButton: UIButton {
override var isEnabled: Bool {
didSet {
iconView.tintColor = isEnabled ? Color.StudyPact.StudyGroups.enabledButton :
Color.StudyPact.StudyGroups.disabledButton
}
}
private var iconView: UIImageView!
init(iconImage: UIImage?) {
super.init(frame: .zero)
contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
backgroundColor = UIColor(red: 0.692, green: 0.687, blue: 0.687, alpha: 0.24)
// Set rounded corners and drop shadow
layer.cornerRadius = 4
layer.shadowRadius = 1
layer.shadowOpacity = 0.1
layer.shadowOffset = .zero
layer.shadowColor = UIColor.black.cgColor
layer.shadowPath = UIBezierPath(rect: layer.bounds.insetBy(dx: 4, dy: 4)).cgPath
iconView = UIImageView()
if iconImage != nil {
iconView.image = iconImage?.withRenderingMode(.alwaysTemplate)
iconView.tintColor = Color.StudyPact.StudyGroups.enabledButton
iconView.contentMode = .scaleAspectFit
addSubview(iconView)
iconView.translatesAutoresizingMaskIntoConstraints = false
iconView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
iconView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
iconView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.6).isActive = true
iconView.heightAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.6).isActive = true
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// TriviaController.swift
// Examen
//
// Created by macbook on 4/29/19.
// Copyright © 2019 nidem. All rights reserved.
//
import UIKit
class TriviaController: UICollectionViewCell {
@IBOutlet weak var switchQ1: UISwitch!
@IBOutlet weak var switchQ2: UISwitch!
@IBOutlet weak var switchQ3: UISwitch!
@IBAction func btnCheck(_ sender: Any) {
if(switchQ1.isOn && switchQ2.isOn && switchQ3.isOn == false){
} else {
}
}
}
|
//
// Tweet.swift
// Twitter
//
// Created by Wenn Huang on 2/25/17.
// Copyright © 2017 Wenn Huang. All rights reserved.
//
import UIKit
class Tweet: NSObject {
var text : String?
var timestamp : Date?
var retweetCount : Int = 0
var favouriteCount : Int = 0
var followingName : String?
var userDict : NSDictionary!
var userImageUrl : URL?
var dateString : String?
var retweet : NSDictionary!
var favourite :NSDictionary!
var wasRetweet = false
var wasFavor = false
private var dateFormatter : DateFormatter = {
let dFormatter = DateFormatter()
dFormatter.dateFormat = "EEE MMM d HH:mm:ss Z y"
return dFormatter
}()
init (dictionary : NSDictionary) {
userDict = dictionary["user"] as! NSDictionary
followingName = userDict["name"] as? String
let imageURLString = userDict["profile_image_url_https"] as? String
if imageURLString != nil {
print("url: \(imageURLString)")
userImageUrl = URL(string: imageURLString!)!
} else {
userImageUrl = nil
}
text = dictionary["text"] as? String
retweetCount = (dictionary["retweet_count"] as? Int ) ?? 0
favouriteCount = (dictionary["favourite_count"] as? Int) ?? 0
if let timestampString = dictionary["created_at"] as? String {
timestamp = dateFormatter.date(from: timestampString)
}
let dateFormat = DateFormatter()
dateFormat.dateFormat = "EEEE-MMM-d"
dateString = dateFormat.string(from: timestamp!)
}
class func tweetsWithArray(dictionaries: [NSDictionary]) -> [Tweet] {
var tweets = [Tweet]()
dictionaries.forEach {
(dictionary) in tweets.append(Tweet(dictionary: dictionary))
}
return tweets
}
}
|
//
// ReplyCell.swift
// CommentTestProject
//
// Created by Frank on 12/12/18.
//
import UIKit
class ReplyCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var contentTextView: UITextView!
var reply: Reply? = nil{
didSet{
if let reply = reply{
nameLabel.text = reply.author
contentTextView.text = reply.content
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
contentTextView.isScrollEnabled = false
contentTextView.textContainerInset = .zero
contentTextView.textContainer.lineFragmentPadding = 0
contentTextView.isSelectable = false
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
|
//
// DetailViewController.swift
// HW3
//
// Created by lisa on 2017/5/18.
// Copyright © 2017年 lisa. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var nev: UINavigationItem!
@IBOutlet weak var picture: UIImageView!
@IBOutlet weak var cityName: UILabel!
@IBOutlet weak var country: UILabel!
@IBOutlet weak var airportName: UILabel!
var passDetail : [String:String]? {
didSet{
if self.isViewLoaded{
self.updateUIElements()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
nev.title = passDetail!["IATA"]
self.updateUIElements()
// Do any additional setup after loading the view.
}
func updateUIElements() {
self.airportName.text = passDetail!["Airport"]
self.airportName.numberOfLines = 0
self.airportName.lineBreakMode = NSLineBreakMode.byWordWrapping
self.airportName.font = UIFont.systemFont(ofSize: 35)
self.cityName.text = passDetail!["ServedCity"]
self.cityName.font = UIFont.systemFont(ofSize: 17)
self.picture.frame = CGRect(
x: 0, y: 350, width: 420, height: 400)
self.picture.image = UIImage(named:"Airports Data/"+passDetail!["IATA"]!+".jpg")
self.country.text = passDetail!["Country"]
self.country.font = UIFont.systemFont(ofSize: 17)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// HistoryVC.swift
// FinWS
//
// Created by Madison on 5/3/19.
// Copyright © 2019 Madison. All rights reserved.
//
import Foundation
import UIKit
class HistoryVC: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
}
}
|
import Foundation
enum SegueType: String {
case presentSignUpViewController
case showCreateAwardViewController
case showFriendDetailViewController
case showCreateFriendViewController
case unwindToHomeViewController
case showInfoViewController
}
|
//
// Expense.swift
// Quota
//
// Created by Marcin Włoczko on 24/11/2018.
// Copyright © 2018 Marcin Włoczko. All rights reserved.
//
import Foundation
struct Expense: Encodable {
let description: String
let amount: Double
let tip: Double?
let date: Date
let currency: Currency
let payer: Member
let borrowers: [Member]
var contributions: [Contribution]
var items: [BillItem]
private enum CodingKeys: String, CodingKey {
case description
case amount
case payer
case contributions
}
func toCellData() -> SystemTableCellViewModel {
return SystemTableCellViewModelImp(title: description,
detailTitle: String(format: "%.2f", amount) + " " + currency.code)
}
}
|
//
// articleListController.swift
// newsApp
//
// Created by Rohan Sharma on 10/3/18.
// Copyright © 2018 Rohan Sharma. All rights reserved.
//
import UIKit
import FirebaseFirestore
class articleListController: UITableViewController {
// var db: Firestore!
//var array = ["one", "two", "three", "four", "five", "six"];
// var studentLife: [String: String] = getData();
var studKeys = ["one", "TWO"]
// = [String](studentLife.keys);
// override init(style: UITableViewStyle) {
// print("hi")
// }
// self.getData();
private let dataModel = DataModel()
override func viewDidLoad() {
super.viewDidLoad()
// dataModel.requestData { [weak self] (data: String) in
// self?.useData(data: data)
// }
// print("2")
// print(self.studentLife);
let db = Firestore.firestore();
let settings = db.settings
settings.areTimestampsInSnapshotsEnabled = true
db.settings = settings
// let studentLife = db.collection("studentLife");
//
db.collection("studentLife").getDocuments { (snapshot, error) in
if error != nil {
//print(error)
} else {
for document in (snapshot?.documents)! {
if let title = document.data()["title"] as? String, let body = document.data()["body"] as? String {
self.studentLife[title] = body;
// print(self.studentLife);
}
}
}
print("hello3");
self.studKeys = [String](self.studentLife.keys);
}
// print(studentLife);
// print(self.studentLife.keys);
// print(studentLife.values);
// self.studKeys = [String](studentLife.values);
// print (self.studKeys);
}
// private func useData(data: String) {
// print(data)
// }
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
// print("hello");
return self.studKeys.count;
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// print("hello2");
let cell = UITableViewCell()
cell.textLabel?.text = studKeys[indexPath.row];
// print (self.studKeys);
return cell
}
// func getData() -> Dictionary<String,String>{
// var data = [String: String]();
//
// let db = Firestore.firestore();
// let settings = db.settings
// settings.areTimestampsInSnapshotsEnabled = true
// db.settings = settings
//
// db.collection("studentLife").getDocuments { (snapshot, error) in
// if error != nil {
// //print(error)
// } else {
// for document in (snapshot?.documents)! {
// if let title = document.data()["title"] as? String, let body = document.data()["body"] as? String {
// data[title] = body;
// // print(self.studentLife);
//
// }
// }
//
//// print(data);
//// return (data);
// }
//// print(data);
//// print("1")
//
// }
//// print("2")
//// print(data);
// return data;
//
//
// }
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
|
//
// MusicState.swift
// ArchitectureDemo
//
// Created by khoi tran on 5/20/20.
// Copyright © 2020 khoi tran. All rights reserved.
//
import Foundation
import ReSwift
import RxSwift
struct MusicState: StateType {
var currentSongName: String?
}
extension MusicState {
}
|
//
// FindViewController.swift
// Trip
//
// Created by haojunhua on 15/3/24.
// Copyright (c) 2015年 kidsedu. All rights reserved.
//
import UIKit
class FindViewController: UIViewController,MAMapViewDelegate{
@IBOutlet weak var _mapView: MAMapView!
var _jqId:Int=0
var _jq:JQ?
override func viewDidLoad() {
super.viewDidLoad()
_mapView.centerCoordinate=CLLocationCoordinate2D(latitude: 39.90618095,longitude: 116.40546799)
_mapView.zoomLevel=13
_mapView.showsCompass=false
_mapView.showsScale=false
_mapView.delegate = self
for jq in DataSource().JQDatas {
var annotation = MAPointAnnotation()
annotation.coordinate = jq.location
annotation.title="\(jq.id)"
_mapView.addAnnotation(annotation)
}
}
override func viewWillDisappear(animated: Bool) {
println("viewWillDisappear\(NSDate().timeIntervalSince1970)")
}
override func viewDidDisappear(animated: Bool) {
println("viewDidDisappear\(NSDate().timeIntervalSince1970)")
}
func mapView(mapView: MAMapView!, regionDidChangeAnimated animated: Bool) {
}
func mapView(mapView: MAMapView!, didSelectAnnotationView view: MAAnnotationView!) {
println(NSDate().timeIntervalSince1970)
_jqId=view.annotation.title!.toInt()!
_jq=DataSource().JQDatas[view.annotation.title!.toInt()!-1]
self.performSegueWithIdentifier("findToJQ", sender: self)
mapView.deselectAnnotation(view.annotation, animated: false)
println(NSDate().timeIntervalSince1970)
}
func mapView(mapView: MAMapView!, viewForAnnotation annotation: MAAnnotation!) -> MAAnnotationView! {
let AnnotationViewID = "JQAnnotaionView";
var annotationView:MAPPAnnotationView! = mapView.dequeueReusableAnnotationViewWithIdentifier(AnnotationViewID) as! MAPPAnnotationView!
if (annotationView == nil) {
annotationView = MAPPAnnotationView(annotation: annotation, reuseIdentifier: AnnotationViewID)
var jq:JQ=DataSource().JQDatas[annotation.title!.toInt()!-1]
annotationView.setThumb(jq.picPath)
}
return annotationView
}
@IBAction func backToFind(segue:UIStoryboardSegue!) {
dismissViewControllerAnimated(true, completion: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var jqViewController:JQViewController = segue.destinationViewController as! JQViewController;
jqViewController._jq=_jq
}
}
|
//
// LikerView.swift
// Brizeo
//
// Created by Roman Bayik on 2/6/17.
// Copyright © 2017 Kogi Mobile. All rights reserved.
//
import UIKit
class LikerView: UIView {
// MARK: - Properties
@IBOutlet weak var diclineButton: UIButton!
@IBOutlet weak var approveButton: UIButton!
@IBOutlet weak var matchedLabel: UILabel!
var isMatched: Bool {
get {
return !matchedLabel.isHidden
}
set {
diclineButton.isHidden = newValue
approveButton.isHidden = newValue
matchedLabel.isHidden = !newValue
}
}
var isDeclined: Bool {
get {
return diclineButton.isHidden && approveButton.isHidden && matchedLabel.isHidden
}
set {
diclineButton.isHidden = newValue
approveButton.isHidden = newValue
matchedLabel.isHidden = newValue
}
}
var isActionHidden: Bool {
get {
return diclineButton.isHidden && approveButton.isHidden
}
set {
diclineButton.isHidden = newValue
approveButton.isHidden = newValue
}
}
// MARK: - Public methods
func hideEverything() {
matchedLabel.isHidden = true
isActionHidden = true
}
func operateStatus(status: MatchingStatus) {
switch status {
case .isMatched:
isActionHidden = true
matchedLabel.isHidden = true
case .isRejectedByCurrentUser, .didRejectEachOther, .didApproveButCurrentReject, .didRejectCurrentUser, .didRejectButCurrentApprove, .isApprovedByCurrentUser:
isActionHidden = true
matchedLabel.isHidden = true
default:
isActionHidden = false
matchedLabel.isHidden = true
}
}
}
|
//
// UINavigationControllerExtension.swift
// desafio-ios-gabriel-leal
//
// Created by Gabriel Sousa on 05/04/20.
// Copyright © 2020 Gabriel Sousa. All rights reserved.
//
import UIKit
extension UINavigationController {
func setNavBarTransparent() {
navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
navigationBar.shadowImage = UIImage()
navigationBar.isTranslucent = true
view.backgroundColor = .clear
navigationBar.tintColor = UIColor.red
}
func hideNavBar() {
isNavigationBarHidden = true
}
func showNavBar() {
isNavigationBarHidden = false
}
open override var preferredStatusBarStyle: UIStatusBarStyle {
return topViewController?.preferredStatusBarStyle ?? .default
}
}
|
//
// LeafColorTypeService.swift
// florafinder
//
// Created by Andrew Tokeley on 11/01/16.
// Copyright © 2016 Andrew Tokeley . All rights reserved.
//
import Foundation
enum LeafColorTypeEnum: String
{
case VeryDarkGreen = "Very Dark Green"
case DarkGreen = "Dark Green"
case Green = "Green"
case LightGreen = "Light Green"
case MultiColored = "Multi-Colored"
static let allValues = [VeryDarkGreen, DarkGreen, Green, LightGreen, MultiColored]
static func getByName(name: String) -> LeafColorTypeEnum?
{
return LeafColorTypeEnum.allValues.filter( { $0.rawValue.lowercaseString == name.lowercaseString } ).first
}
func order() -> Int
{
return LeafColorTypeEnum.allValues.indexOf(self)!
}
func color() -> UIColor
{
switch self {
case .VeryDarkGreen: return UIColor.leafVeryDarkGreen()
case .DarkGreen: return UIColor.leafDarkGreen()
case .Green: return UIColor.leafGreen()
case .LightGreen: return UIColor.leafLightGreen()
case .MultiColored: return UIColor.leafVeryDarkGreen()
}
}
}
class LeafColorTypeService: EnumService<LeafColorType>, EnumServiceDelegate, LeafColorTypeProtocol {
//MARK: Initialisers
override init(controller: CoreDataController, entityName: NSString) {
super.init(controller: controller, entityName: entityName)
// Must set the EnumService delegate here so that syncEnumerations gets called on initialisation
delegate = self
}
//MARK: - Syncing
/**
Ensures the enumerations and records in the datastore are the same
*/
func syncEnumerationsToDatastore()
{
// Add missing or update existing records to datastore
for enumeration in LeafColorTypeEnum.allValues
{
// Ignore errors for now
let _ = try? addOrUpdate(enumeration)
}
// find out if there are any datastore entries that are no longer defined in the enumerator
for data in getAll()
{
if let typeName = data.name
{
if (LeafColorTypeEnum(rawValue: typeName) == nil)
{
// The record in the datastore doesn't match any enum so remove it (if you can)
do
{
try data.validateForDelete()
coreDataController.managedObjectContext.deleteObject(data)
}
catch
{
// LOG - probaby not fatal, just means the user will have to change this property to something else if editing.
}
}
//
}
}
}
func reset()
{
super.resetDatastore()
}
private func addOrUpdate(type: LeafColorTypeEnum) throws -> LeafColorType
{
if let existing = getObject(type.rawValue)
{
existing.order = type.order()
existing.color = type.color()
try save()
return existing
}
else
{
let new = add()
new.name = type.rawValue
new.color = type.color()
new.order = type.order()
try save()
return new
}
}
//MARK: - Service Overrides
override func getAll() -> [LeafColorType]
{
// sort by order ascending
let sort = NSSortDescriptor(key: "order", ascending: true)
return super.getObjects(nil, sortDescriptors: [sort])
}
override func getObjects(predicate: NSPredicate?) -> [LeafColorType] {
return super.getObjects(predicate)
}
override func getObjects(predicate: NSPredicate?, sortDescriptors: [NSSortDescriptor]?) -> [LeafColorType] {
return super.getObjects(predicate, sortDescriptors: sortDescriptors)
}
func getObject(name: String) -> LeafColorType?
{
return super.getObjects(NSPredicate(format: "name ==[c] %@", name)).first
}
func getObject(type: LeafColorTypeEnum) -> LeafColorType?
{
return getObject(type.rawValue)
}
} |
//
// ListView.swift
// ShuffleSongs
//
// Created by Gilson Gil on 22/03/19.
// Copyright © 2019 Gilson Gil. All rights reserved.
//
import UIKit
import Cartography
protocol ListViewLogic: class {
var viewInteractions: ListViewInteractions? { get set }
var tableView: UITableView { get }
var activityIndicator: UIActivityIndicatorView { get }
var rightBarButtonItems: [UIBarButtonItem] { get }
}
protocol ListViewInteractions: class {
func didTapShuffle(at view: ListView)
}
final class ListView: UIView, ListViewLogic {
public private(set) var activityIndicator: UIActivityIndicatorView = {
let activity = UIActivityIndicatorView(style: .whiteLarge)
activity.color = .defaultTint
activity.hidesWhenStopped = true
return activity
}()
public private(set) var tableView: UITableView = {
let tableView = UITableView()
tableView.backgroundColor = .clear
tableView.separatorColor = UIColor.darkGray
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 80
tableView.allowsSelection = false
return tableView
}()
public private(set) lazy var rightBarButtonItems: [UIBarButtonItem] = {
let button = UIBarButtonItem(image: UIImage.List.shuffleButton,
style: .plain,
target: self,
action: #selector(shuffleTapped))
return [button]
}()
weak var viewInteractions: ListViewInteractions?
init() {
super.init(frame: .zero)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(frame: .zero)
setup()
}
// MARK: - Setup
private func setup() {
addSubviews()
addConstraints()
}
private func addSubviews() {
addSubview(activityIndicator)
addSubview(tableView)
}
private func addConstraints() {
constrain(self, activityIndicator, tableView) { view, activityIndicator, tableView in
activityIndicator.center == view.center
tableView.edges == view.edges
}
}
}
// MARK: - Actions
@objc
extension ListView {
func shuffleTapped() {
viewInteractions?.didTapShuffle(at: self)
}
}
|
//
// UserProfileViewController.swift
// Boatell-x-v2
//
// Created by Austin Potts on 3/26/20.
// Copyright © 2020 Potts Evolvements. All rights reserved.
//
import UIKit
class UserProfileViewController: UIViewController {
// Table View
// User Values
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var userImage: UIImageView!
// UIViews for User Options
@IBOutlet weak var scheduleView: UIView!
@IBOutlet weak var serviceView: UIView!
@IBOutlet weak var yourBoatsView: UIView!
@IBOutlet weak var settingsView: UIView!
// Model Controller
let serviceController = ServiceController()
override func viewDidLoad() {
super.viewDidLoad()
// User Views v1
// userImage.layer.cornerRadius = 82
userImage.layer.borderWidth = 1
userImage.layer.borderColor = UIColor.white.cgColor
userImage.contentMode = .scaleAspectFill
userImage.layer.cornerRadius = userImage.frame.height / 2
userImage.layer.masksToBounds = false
userImage.clipsToBounds = true
// UIViews for User Options v2
scheduleView.layer.cornerRadius = 20
serviceView.layer.cornerRadius = 20
yourBoatsView.layer.cornerRadius = 20
settingsView.layer.cornerRadius = 20
// Shadows for UIViews
scheduleView.layer.shadowColor = UIColor.white.cgColor
scheduleView.layer.shadowOpacity = 0.5
scheduleView.layer.shadowOffset = .zero
scheduleView.layer.shadowRadius = 10
yourBoatsView.layer.shadowColor = UIColor.white.cgColor
yourBoatsView.layer.shadowOpacity = 0.5
yourBoatsView.layer.shadowOffset = .zero
yourBoatsView.layer.shadowRadius = 10
settingsView.layer.shadowColor = UIColor.white.cgColor
settingsView.layer.shadowOpacity = 0.5
settingsView.layer.shadowOffset = .zero
settingsView.layer.shadowRadius = 10
serviceView.layer.shadowColor = UIColor.white.cgColor
serviceView.layer.shadowOpacity = 0.5
serviceView.layer.shadowOffset = .zero
serviceView.layer.shadowRadius = 10
// Borders for UIViews
scheduleView.layer.borderWidth = 1
scheduleView.layer.borderColor = UIColor.blue.cgColor
serviceView.layer.borderWidth = 1
serviceView.layer.borderColor = UIColor.blue.cgColor
settingsView.layer.borderWidth = 1
settingsView.layer.borderColor = UIColor.blue.cgColor
yourBoatsView.layer.borderWidth = 1
yourBoatsView.layer.borderColor = UIColor.blue.cgColor
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
//MARK: Old Table View for v1 of user layout
// func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return serviceController.service.count
// }
//
// func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let cell = historyTableView.dequeueReusableCell(withIdentifier: "ServiceCell", for: indexPath) as! ServiceHistoryTableViewCell
//
// // Configure the cell
// // let part = partController.part[indexPath.item]
// let service = serviceController.service[indexPath.row]
//
// cell.servicePriceLabel.text = service.price
// cell.serviceDateLabel.text = service.date
//
//
//
// return cell
// }
}
|
//
// MovieDetailsViewController.swift
// PopuMov
//
// Created by Shouri on 27/03/16.
// Copyright © 2016 Shouri. All rights reserved.
//
import UIKit
class MovieDetailsViewController: UIViewController, UIScrollViewDelegate{
var mainView = UIView()
var scrollView = UIScrollView()
var movie = MovieClass()
var titleString = UILabel(frame: CGRectMake(10,100,100,30))
var nameString = UILabel()
var overviewLabel = UILabel()
var overview = UILabel()
var languageLabel = UILabel()
var language = UILabel()
var releaseDateLabel = UILabel()
var releaseDate = UILabel()
var image=UIImage()
var imageView = UIImageView()
override func viewDidLoad() {
self.navigationController?.hidesBarsOnSwipe = true
mainView = self.view
scrollView = UIScrollView(frame: mainView.bounds)
var sz = scrollView.bounds.size
sz.height = movie.image.size.height + 250
scrollView.contentSize = sz
scrollView.translatesAutoresizingMaskIntoConstraints = false
imageView = UIImageView(image: movie.image)
scrollView.addSubview(imageView)
scrollView.addSubview(titleString)
mainView.addSubview(scrollView)
titleString.translatesAutoresizingMaskIntoConstraints = false
setLabelsAttributes()
updateConstraints()
}
func setLabelsAttributes(){
titleString.text = "Title:"
nameString.numberOfLines = 0
nameString.text = movie.title
overviewLabel.text = "Overview:"
overview.numberOfLines = 0
overview.text = movie.overview
languageLabel.text = "Language:"
language.text = movie.original_language
releaseDateLabel.text = "Release Date:"
releaseDate.text = movie.releaseDate
}
func updateConstraints(){
// let image_top_constraint = NSLayoutConstraint(item: imageView, attribute: .Top, relatedBy: .Equal, toItem: scrollView, attribute: .Top, multiplier: 1, constant: 65)
// scrollView.addConstraint(image_top_constraint)
// let image_trailing_constraint = NSLayoutConstraint(item: imageView, attribute: .Trailing , relatedBy: .Equal, toItem: scrollView, attribute: .Trailing, multiplier: 1, constant: 0)
// scrollView.addConstraint(image_trailing_constraint)
// let image_leading_constraint = NSLayoutConstraint(item: imageView, attribute: .Leading , relatedBy: .Equal, toItem: scrollView, attribute: .Leading, multiplier: 1, constant: 0)
// scrollView.addConstraint(image_leading_constraint)
let titleLabelContraint = NSLayoutConstraint(item: titleString, attribute: .Top, relatedBy: .Equal, toItem: imageView, attribute: .Bottom, multiplier: 1, constant: 10)
}
func displayDetails(){
}
}
|
//
// Models.swift
// AppStore
//
// Created by David Rodrigues on 09/09/2018.
// Copyright © 2018 David Rodrigues. All rights reserved.
//
import UIKit
class Featured: Codable {
var bannerCategory: AppCategory?
var categories: [AppCategory]?
}
class App: Codable {
var Id: Int?
var Name: String?
var Category: String?
var ImageName: String?
var Price: Float?
var Screenshots: [String]?
var description: String?
var appInformation: [AppInformation]?
}
class AppCategory: Codable {
var name: String?
var apps: [App]?
var type: String?
}
class AppInformation: Codable {
var Name: String?
var Value: String?
}
public enum Result<Value> {
case success(Value)
case failure(Error)
}
class Network {
var urlString = ""
static let shared = Network()
let session = URLSession.shared
private init() {}
func fetchedGenericData<T: Codable>(id: Int? = nil,
onComplete: @escaping (Result<T>) -> ()) {
if let id = id {
urlString = "https://api.letsbuildthatapp.com/appstore/appdetail?id=\(id)"
} else {
urlString = "https://api.letsbuildthatapp.com/appstore/featured"
}
guard let url = URL(string: urlString) else {
onComplete(.failure(NSError(domain: "URL String Invalid", code: -1, userInfo: nil)))
return
}
let task = session.dataTask(with: url) { (data, response, error) in
guard (error == nil) else {
onComplete(.failure(error ?? NSError(domain: "Error - Network", code: -1, userInfo: nil)))
return
}
guard let data = data else {
onComplete(.failure(error ?? NSError(domain: "Data - Network", code: -1, userInfo: nil)))
return
}
do {
let result = try JSONDecoder().decode(T.self, from: data)
DispatchQueue.main.async {
onComplete(.success(result))
}
} catch let error {
onComplete(.failure(error))
}
}
task.resume()
}
}
|
//
// MainTabBarController.swift
// TWGSampleApp
//
// Created by Arsh Aulakh BHouse on 16/07/16.
// Copyright © 2016 BHouse. All rights reserved.
//
import UIKit
//MARK:- Interface
class MainTabController: UITabBarController {
//MARK: Deinitilization
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
//MARK:- Implementation
extension MainTabController {
//MARK: System
override func viewDidLoad() {
super.viewDidLoad()
applyInitialConfigurations()
//Handle Configurations
applyConfigurations()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(applyConfigurations), name: ConfigurationUpdatedKey, object: nil)
}
//MARK: Initial Configurations
func applyInitialConfigurations() {
//Configure Tab Bar
//Set Translucency
tabBar.translucent = false
applyConfigurations()
}
//MARK: Apply Configurations
func applyConfigurations() {
//Set Tab Bar Colors
tabBar.barTintColor = configuration.secondaryThemeColor
tabBar.tintColor = configuration.mainThemeColor
//Set Updated Title Attributes
setTabBarItemsColor(configuration.secondaryThemeColor != Color.Gray.values.color ? Color.Gray.values.color : UIColor.darkTextColor().colorWithAlphaComponent(0.25), forState: .Normal)
setTabBarItemsColor(configuration.mainThemeColor, forState: .Selected)
//Update Status Bar
if configuration.secondaryThemeColor == Color.White.values.color {
UIApplication.sharedApplication().setStatusBarStyle(.Default, animated: false)
} else {
UIApplication.sharedApplication().setStatusBarStyle(.LightContent, animated: false)
}
}
}
extension MainTabController {
//MARK: Additionals
//Set Title Color for TabBar Items
func setTabBarItemsColor(color: UIColor, forState state: UIControlState) {
if let items = tabBar.items {
for item in items as [UITabBarItem] {
item.setTitleTextAttributes([NSFontAttributeName: UIFont.thinFontOfSize(11), NSForegroundColorAttributeName: color], forState: state)
}
}
}
} |
//
// ViewController.swift
// AudioRecordingDemo
//
// Created by Mindbowser on 17/12/18.
// Copyright © 2018 Mindbowser. All rights reserved.
//
import UIKit
import AVFoundation
import Firebase
import FirebaseDatabase
class ViewController: UIViewController, AVAudioRecorderDelegate, AVAudioPlayerDelegate {
@IBOutlet weak var recordBtn: UIButton!
@IBOutlet weak var playBtn: UIButton!
var fDBRef:DatabaseReference!
var uploadAudioTask: StorageUploadTask!
var storageRef:StorageReference!
var soundRecorder: AVAudioRecorder!
var soundPlayer:AVAudioPlayer!
let fileName = "/myaudio.m4a"
override func viewDidLoad() {
super.viewDidLoad()
fDBRef = Database.database().reference()
self.storageRef = Storage.storage().reference()
self.setupAudioRecorder()
self.readMessagesFromFDB()
}
// Writing messages to Firebase - Realtime Database
func saveMessageToFirebase() {
let textMsg:String = "India is a very good country."
FUploadTaskManager.sharedInstance.saveMessage(message: textMsg)
}
// Saving image urls to Firebase - Realtime Database
func saveImageUrlToFDB() {
let imgurlStr = "https://pixabay.com/en/flower-branch-twig-autumn-color-3876195/"
FUploadTaskManager.sharedInstance.saveImageUrl(urlString: imgurlStr)
}
// Read data from Firebase - Realtime Database
func readMessagesFromFDB() {
fDBRef.child("messages").observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
let allKeys = value!.allKeys as! NSArray
for key in allKeys {
let element = value![key as! String] as! NSDictionary
let text:String = element["content"] as! String
print("text msg for \(key): \(text)")
}
}) { (error) in
print(error.localizedDescription)
}
}
// Upload local audio to Firebase - Cloud storage bucket
@IBAction func uploadAudioToFirebase(_ sender: Any) {
FUploadTaskManager.sharedInstance.uploadAudioWithUrl(fileUrl: self.getFileURL(), fileName: "liveaudio.mp4") { (success, metadata, downloadUrl) in
if success {
print("Audio file successfully uploaded to Firebase.")
print("Download url for uploaded audio is: \(String(describing: downloadUrl))")
} else {
print("Failed to upload an audio file to Firebase.")
}
}
}
// Upload an image data to Firebase - Cloud storage bucket
@IBAction func uploadImageToFirebase(_ sender: Any) {
let flowerimg:UIImage! = UIImage(named: "flower")!
let imageData:Data = flowerimg.pngData()!
FUploadTaskManager.sharedInstance.uploadImageWithData(imageData: imageData, fileName: "currentimg.png") { (success, metadata, downloadUrl) in
if success {
print("Image Data is uploaded to Firebase.")
print("Download url for uploaded image data is: \(String(describing: downloadUrl!))")
} else {
print("Failed to upload an image data to Firebase.")
}
}
}
@IBAction func recordAudioClicked(_ sender: Any) {
if (recordBtn.titleLabel?.text == "Record Audio"){
soundRecorder.record()
recordBtn.setTitle("Stop Audio", for: .normal)
playBtn.isEnabled = false
} else {
soundRecorder.stop()
recordBtn.setTitle("Record Audio", for: .normal)
}
}
@IBAction func playAudioClicked(_ sender: Any) {
if (playBtn.titleLabel?.text == "Play Audio"){
recordBtn.isEnabled = false
playBtn.setTitle("Stop Audio", for: .normal)
preparePlayer()
soundPlayer.play()
} else {
soundPlayer.stop()
playBtn.setTitle("Play Audio", for: .normal)
}
}
func setupAudioRecorder() {
do {
let session = AVAudioSession.sharedInstance()
try session.setCategory(.playAndRecord, mode: .default, options: .defaultToSpeaker)
try session.setActive(true)
let recordSettings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC),AVSampleRateKey: 44100,AVNumberOfChannelsKey: 2,AVEncoderAudioQualityKey:AVAudioQuality.high.rawValue]
soundRecorder = try AVAudioRecorder(url: getFileURL(), settings: recordSettings)
soundRecorder.delegate = self
soundRecorder.prepareToRecord()
} catch let error {
print("AVAudioRecorder error: \(error.localizedDescription)")
}
}
func getFileURL() -> URL {
let documents: AnyObject = NSSearchPathForDirectoriesInDomains( FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as AnyObject
let strng = (documents as! NSString).appending(fileName)
let fileurl:URL = NSURL.fileURL(withPath: strng as String)
return fileurl
}
func preparePlayer() {
do {
soundPlayer = try AVAudioPlayer(contentsOf: getFileURL())
soundPlayer.delegate = self
soundPlayer.prepareToPlay()
soundPlayer.volume = 1.0
} catch let error {
print("AVAudioPlayer error: \(error.localizedDescription)")
}
}
// AVAudioRecorderDelegate
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
playBtn.isEnabled = true
recordBtn.setTitle("Record Audio", for: .normal)
}
func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
print("Error while recording audio \(String(describing: error?.localizedDescription))")
}
// AVAudioPlayerDelegate
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
recordBtn.isEnabled = true
playBtn.setTitle("Play Audio", for: .normal)
}
private func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer!, error: NSError!) {
print("Error while playing audio \(error.localizedDescription)")
}
}
|
/*
AuthView.swift
View For User Authentication
*/
import SwiftUI
struct AuthView: View {
var body: some View {
VStack{
NavigationView{
VStack{
Spacer()
Group(){
NavigationLink(destination: SigninView()){
SigninViewButtonView()
}
NavigationLink(destination: SignupView()){
SignupViewButtonView()
}
}.padding(.top, -8)
}
}
}.edgesIgnoringSafeArea(.all).padding(.bottom,40)
}
}
struct AuthView_Previews: PreviewProvider {
static var previews: some View {
AuthView()
}
}
|
//
// WorldChatDidacApp.swift
// WorldChatDidac
//
// Created by Dídac Edo Gibert on 14/4/21.
//
import SwiftUI
import Firebase
@main
struct WorldChatDidacApp: App {
init() {
FirebaseApp.configure()
}
var body: some Scene {
WindowGroup {
ContentView().environmentObject(AuthViewModel.shared)
}
}
}
|
//
// ColorSlider.swift
// RGBSwiftUI
//
// Created by Evgenia Shipova on 19.10.2020.
//
import SwiftUI
struct ColorSliderStack: View {
@Binding var sliderValue: Double
@State var textFieldValue: String
@State var showAlert = false
private var stringSliderValue: String {
getString(value: sliderValue)
}
let color: Color
var body: some View {
HStack(spacing: 10) {
Text(stringSliderValue)
.frame(width: 40)
Slider(value: $sliderValue, in: 0...255, step: 1, onEditingChanged: { _ in textFieldValue = stringSliderValue })
.accentColor(color)
// TextForSliderValue(textFieldValue: $textFieldValue, showAlert: $showAlert, action: changeSliderValue())
TextField("", text: $textFieldValue, onEditingChanged: { _ in
changeSliderValue()
})
.frame(width: 40)
.background(Color.white)
.cornerRadius(5)
.alert(isPresented: $showAlert, content: {
Alert(title: Text("Wrong format!"), message: Text("Enter number from 0 to 255"))
})
}
.padding()
}
private func changeSliderValue() {
guard let number = Double(textFieldValue) else { showAlert = true; return }
if number > 255 {
showAlert = true
textFieldValue = getString(value: sliderValue)
return
}
sliderValue = number
}
private func getString(value: Double) -> String {
String(Int(value))
}
}
struct ColorSlider_Previews: PreviewProvider {
static var previews: some View {
ColorSliderStack(sliderValue: .constant(13.0), textFieldValue: "18", color: .red)
}
}
|
//
// ViewController.swift
// Module6-1
//
// Created by Sergey Chistov on 04.05.2020.
// Copyright © 2020 Sergey Chistov. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var namesLabel: UILabel!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var addButton: UIButton!
@IBAction func onTextChanged() {
let text = nameTextField.text ?? ""
addButton.isEnabled = !text.isEmpty
}
@IBAction func onButtonTouch() {
guard let text = nameTextField.text else {
return
}
var str = namesLabel.text ?? ""
str += str.isEmpty ? text : " " + text
namesLabel.text = str
nameTextField.text = ""
addButton.isEnabled = false
}
override func viewDidLoad() {
addButton.isEnabled = false
}
}
|
//1. Выведите в консоль минимальные и максимальные значения базовых типов, не ленитесь
print("Int.min: \(Int.min) Int.max: \(Int.max)")
print("Int8.min: \(Int8.min) Int8.max: \(Int8.max)")
print("Int16.min: \(Int16.min) Int16.max: \(Int16.max)")
print("Int32.min: \(Int32.min) Int32.max: \(Int32.max)")
print("Int64.min: \(Int64.min) Int.max: \(Int64.max)")
print("UInt.min: \(UInt.min) UInt.max: \(UInt.max)")
print("UInt8.min: \(UInt8.min) UInt8.max: \(UInt8.max)")
print("UInt16.min: \(UInt16.min) UInt16.max: \(UInt16.max)")
print("UInt32.min: \(UInt32.min) UInt32.max: \(UInt32.max)")
print("UInt64.min: \(UInt64.min) UInt.max: \(UInt64.max)")
//2. Создайте 3 константы с типами Int, Float и Double
//Создайте другие 3 константы, тех же типов: Int, Float и Double,
//при чем каждая из них это сумма первых трех, но со своим типом
let aInt : Int = 3
let aFloat : Float = 4.3
let aDouble : Double = 4.543356674
let bInt = aInt + Int(aFloat) + Int(aDouble)
let bFloat = Float(aInt) + aFloat + Float(aDouble)
let bDouble = Double(aInt) + Double(aFloat) + aDouble
//3. Сравните Int результат суммы с Double и выведите отчет в консоль
if Double(bInt) > bDouble {
print("Int const greater than double const")
}
else if Double(bInt) == bDouble {
print("Int const is equal to double const")
}
else{
print("Double const greater than int const")
}
|
//
// MapAnnotation.swift
// MVVM_Uber
//
// Created by Nestor Hernandez on 03/08/22.
//
import Foundation
import CoreLocation
class MapAnnotation: NSObject {
// MARK: - Properties
let id: String
let coordinate: CLLocationCoordinate2D
let type: MapAnnotationType
let imageName: String?
let imageURL: URL?
let imageIdentifier: String
// MARK: - Methods
init(id: String, latitude: CLLocationDegrees, longitude: CLLocationDegrees, type: MapAnnotationType, imageName: String) {
self.id = id
self.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
self.type = type
self.imageName = imageName
self.imageURL = nil
self.imageIdentifier = imageName
}
init(id: String, latitude: CLLocationDegrees, longitude: CLLocationDegrees, type: MapAnnotationType, imageURL: URL) {
self.id = id
self.coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
self.type = type
self.imageName = nil
self.imageURL = imageURL
self.imageIdentifier = imageURL.absoluteString
}
}
extension MapAnnotation {
override var hash: Int {
return id.hash ^ type.rawValue.hash
}
override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? MapAnnotation else {
return false
}
return id == object.id && type == object.type
}
}
enum MapAnnotationType: String {
case pickupLocation
case dropoffLocation
case availableRide
static func makePickupLocationAnnotation(`for` location: Location) -> MapAnnotation {
return MapAnnotation(id: location.id,
latitude: location.latitude,
longitude: location.longitude,
type: .pickupLocation,
imageName: "MapMarkerPickupLocation")
}
static func makeDropoffLocationAnnotation(`for` location: Location?) -> MapAnnotation? {
guard let location = location else { return nil }
return MapAnnotation(id: location.id,
latitude: location.latitude,
longitude: location.longitude,
type: .dropoffLocation,
imageName: "MapMarkerDropoffLocation")
}
}
|
//
// UIBarButtonItem+Extension.swift
// swiftWEBO
//
// Created by AVGD on 17/1/14.
// Copyright © 2017年 JFF. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
//使用自定义视图 重写返回按钮
convenience init(title:String, fontsize:Float = 16, taget:AnyObject?, action:Selector , isBackbutton:Bool = false) {
/// UIButtonType.DetailDisclosure:前面带“!”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效果
/// UIButtonType.System:前面不带图标,默认文字颜色为蓝色,有触摸时的高亮效果
/// UIButtonType.Custom:定制按钮,前面不带图标,默认文字颜色为白色,无触摸时的高亮效果
/// UIButtonType.ContactAdd:前面带“+”图标按钮,默认文字颜色为蓝色,有触摸时的高亮效果
let button = UIButton(type: .custom)
if isBackbutton {
let imageName = "hotweibo_back_icon"
button.setImage( UIImage(named: imageName), for: .normal)
button.setImage( UIImage(named: imageName+"_highlighted"), for: .highlighted)
}
button.setTitle(title, for: .normal)
button.setTitleColor(UIColor.darkGray, for: .normal)
button.setTitleColor(UIColor.orange, for: .highlighted)
button.titleLabel?.font = UIFont.systemFont(ofSize: CGFloat(fontsize))
button.addTarget(taget, action: action, for: .touchUpInside)
button.sizeToFit()
//self.init 实例化UIBarButtonItem
self.init(customView:button)
}
}
|
import XCTest
@testable import Quick
import Nimble
class FunctionalTests_ItSpec: QuickSpec {
override func spec() {
var exampleMetadata: ExampleMetadata?
beforeEach { metadata in exampleMetadata = metadata }
it("") {
expect(exampleMetadata!.example.name).to(equal(""))
}
it("has a description with セレクター名に使えない文字が入っている 👊💥") {
let name = "has a description with セレクター名に使えない文字が入っている 👊💥"
expect(exampleMetadata!.example.name).to(equal(name))
}
#if canImport(Darwin) && !SWIFT_PACKAGE
describe("when an example has a unique name") {
it("has a unique name") {}
it("doesn't add multiple selectors for it") {
let allSelectors = [String](
FunctionalTests_ItSpec.allSelectors()
.filter { $0.hasPrefix("when_an_example_has_a_unique_name__") })
.sorted(by: <)
expect(allSelectors) == [
"when_an_example_has_a_unique_name__doesn_t_add_multiple_selectors_for_it",
"when_an_example_has_a_unique_name__has_a_unique_name"
]
}
}
describe("when two examples have the exact name") {
it("has exactly the same name") {}
it("has exactly the same name") {}
it("makes a unique name for each of the above") {
let allSelectors = [String](
FunctionalTests_ItSpec.allSelectors()
.filter { $0.hasPrefix("when_two_examples_have_the_exact_name__") })
.sorted(by: <)
expect(allSelectors) == [
"when_two_examples_have_the_exact_name__has_exactly_the_same_name",
"when_two_examples_have_the_exact_name__has_exactly_the_same_name_2",
"when_two_examples_have_the_exact_name__makes_a_unique_name_for_each_of_the_above"
]
}
}
describe("error handling when misusing ordering") {
it("an it") {
expect {
it("will throw an error when it is nested in another it") { }
}.to(raiseException { (exception: NSException) in
expect(exception.name).to(equal(NSExceptionName.internalInconsistencyException))
expect(exception.reason).to(equal("'it' cannot be used inside 'it', 'it' may only be used inside 'context' or 'describe'. "))
})
}
describe("behavior with an 'it' inside a 'beforeEach'") {
var exception: NSException?
beforeEach {
let capture = NMBExceptionCapture(handler: ({ e in
exception = e
}), finally: nil)
capture.tryBlock {
it("a rogue 'it' inside a 'beforeEach'") { }
return
}
}
it("should have thrown an exception with the correct error message") {
expect(exception).toNot(beNil())
expect(exception!.reason).to(equal("'it' cannot be used inside 'beforeEach', 'it' may only be used inside 'context' or 'describe'. "))
}
}
describe("behavior with an 'it' inside an 'afterEach'") {
var exception: NSException?
afterEach {
let capture = NMBExceptionCapture(handler: ({ e in
exception = e
expect(exception).toNot(beNil())
expect(exception!.reason).to(equal("'it' cannot be used inside 'afterEach', 'it' may only be used inside 'context' or 'describe'. "))
}), finally: nil)
capture.tryBlock {
it("a rogue 'it' inside an 'afterEach'") { }
return
}
}
it("should throw an exception with the correct message after this 'it' block executes") { }
}
}
#endif
}
}
final class ItTests: XCTestCase, XCTestCaseProvider {
static var allTests: [(String, (ItTests) -> () throws -> Void)] {
return [
("testAllExamplesAreExecuted", testAllExamplesAreExecuted)
]
}
#if canImport(Darwin) && !SWIFT_PACKAGE
func testAllExamplesAreExecuted() {
let result = qck_runSpec(FunctionalTests_ItSpec.self)
XCTAssertEqual(result?.executionCount, 10)
}
#else
func testAllExamplesAreExecuted() {
let result = qck_runSpec(FunctionalTests_ItSpec.self)
XCTAssertEqual(result?.executionCount, 2)
}
#endif
}
|
//
// PersonalDetailsViewController.swift
// PaymentsApp
//
// Created by Chinmay Bapna on 25/07/20.
// Copyright © 2020 Chinmay Bapna. All rights reserved.
//
import UIKit
class PersonalDetailsViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var DOBTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var checkBoxImageView : UIImageView!
@IBOutlet weak var termsAndConditionsLabel : UILabel!
@IBOutlet weak var privacyPolicyLabel : UILabel!
var isCheckBoxChecked = false
private var datePicker : UIDatePicker?
@IBOutlet weak var continueButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
if let name = UserDefaults.standard.string(forKey: "nameTextFieldInput"), let DOB = UserDefaults.standard.string(forKey: "DOBTextFieldInput"), let email = UserDefaults.standard.string(forKey: "emailTextFieldInput") {
nameTextField.text = name
DOBTextField.text = DOB
emailTextField.text = email
}
let tapGesture1 = UITapGestureRecognizer(target: self, action: #selector(showCheckMark))
checkBoxImageView.isUserInteractionEnabled = true
checkBoxImageView.addGestureRecognizer(tapGesture1)
let tapGesture2 = UITapGestureRecognizer(target: self, action: #selector(showTermsAndConditions))
termsAndConditionsLabel.isUserInteractionEnabled = true
termsAndConditionsLabel.addGestureRecognizer(tapGesture2)
let tapGesture3 = UITapGestureRecognizer(target: self, action: #selector(showPrivacyPolicy))
privacyPolicyLabel.isUserInteractionEnabled = true
privacyPolicyLabel.addGestureRecognizer(tapGesture3)
nameTextField.delegate = self
DOBTextField.delegate = self
emailTextField.delegate = self
datePicker = UIDatePicker()
datePicker?.datePickerMode = .date
DOBTextField.inputView = datePicker
datePicker?.addTarget(self, action: #selector(dateChanged(datePicker:)), for: .valueChanged)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
view.addGestureRecognizer(tapGesture)
continueButton.layer.cornerRadius = 20
nameTextField.layer.cornerRadius = 10
DOBTextField.layer.cornerRadius = 10
emailTextField.layer.cornerRadius = 10
nameTextField.backgroundColor = #colorLiteral(red: 0.7373645306, green: 0.9292912483, blue: 0.7189010978, alpha: 1)
DOBTextField.backgroundColor = #colorLiteral(red: 0.7373645306, green: 0.9292912483, blue: 0.7189010978, alpha: 1)
emailTextField.backgroundColor = #colorLiteral(red: 0.7373645306, green: 0.9292912483, blue: 0.7189010978, alpha: 1)
nameTextField.attributedPlaceholder = NSAttributedString(string: "Name", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
DOBTextField.attributedPlaceholder = NSAttributedString(string: "Date of Birth", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
emailTextField.attributedPlaceholder = NSAttributedString(string: "Email", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
}
@objc func showCheckMark(tapGestureRecognizer: UITapGestureRecognizer) {
let tappedImage = tapGestureRecognizer.view as! UIImageView
if !isCheckBoxChecked {
isCheckBoxChecked = true
tappedImage.image = #imageLiteral(resourceName: "ticked_checkbox")
} else {
isCheckBoxChecked = false
tappedImage.image = #imageLiteral(resourceName: "checkBox")
}
}
@objc func showTermsAndConditions(tapGestureRecognizer: UITapGestureRecognizer) {
if nameTextField.text != "" || DOBTextField.text != "" || emailTextField.text != "" {
UserDefaults.standard.set(nameTextField.text, forKey: "nameTextFieldInput")
UserDefaults.standard.set(DOBTextField.text, forKey: "DOBTextFieldInput")
UserDefaults.standard.set(emailTextField.text, forKey: "emailTextFieldInput")
}
performSegue(withIdentifier: "show_t&c", sender: nil)
}
@objc func showPrivacyPolicy(tapGestureRecognizer: UITapGestureRecognizer) {
if nameTextField.text != "" || DOBTextField.text != "" || emailTextField.text != "" {
UserDefaults.standard.set(nameTextField.text, forKey: "nameTextFieldInput")
UserDefaults.standard.set(DOBTextField.text, forKey: "DOBTextFieldInput")
UserDefaults.standard.set(emailTextField.text, forKey: "emailTextFieldInput")
}
performSegue(withIdentifier: "show_privacy_policy", sender: nil)
}
@objc func viewTapped(gestureRecogniser : UITapGestureRecognizer) {
view.endEditing(true)
}
@objc func dateChanged(datePicker : UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
DOBTextField.text = dateFormatter.string(from: datePicker.date)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
view.endEditing(true)
return true
}
@IBAction func continueButtonPressed() {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
var date: Date = Date()
if let selectedDate = DOBTextField.text {
date = dateFormatter.date(from: selectedDate)!
}
if nameTextField.text == "" || DOBTextField.text == "" || emailTextField.text == "" {
let alert = UIAlertController(title: "Invaild Input", message: "Please give valid inputs.", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
alert.view.backgroundColor = #colorLiteral(red: 0.8423798084, green: 1, blue: 0.8301133513, alpha: 1)
alert.view.tintColor = #colorLiteral(red: 0.275267005, green: 0.482419312, blue: 0, alpha: 1)
alert.view.layer.cornerRadius = 0.5 * alert.view.bounds.size.width
present(alert, animated: true, completion: nil)
nameTextField.text = ""
DOBTextField.text = ""
emailTextField.text = ""
}
else if yearsBetweenDate(startDate: date, endDate: Date()) < 18 {
DOBTextField.text = ""
let alert = UIAlertController(title: "", message: "You should be above 18 years to register to the app.", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
else if !isCheckBoxChecked {
let alert = UIAlertController(title: "", message: "Please agree to terms and conditions and privacy policy.", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
alert.view.backgroundColor = #colorLiteral(red: 0.8423798084, green: 1, blue: 0.8301133513, alpha: 1)
alert.view.tintColor = #colorLiteral(red: 0.275267005, green: 0.482419312, blue: 0, alpha: 1)
alert.view.layer.cornerRadius = 0.5 * alert.view.bounds.size.width
present(alert, animated: true, completion: nil)
}
else {
if let name = nameTextField.text {
UserDefaults.standard.set(name, forKey: "name")
}
if let dob = DOBTextField.text {
UserDefaults.standard.set(dob, forKey: "dob")
}
if let email = emailTextField.text {
UserDefaults.standard.set(email, forKey: "email")
}
if nameTextField.text != "" || DOBTextField.text != "" || emailTextField.text != "" {
UserDefaults.standard.set(nameTextField.text, forKey: "nameTextFieldInput")
UserDefaults.standard.set(DOBTextField.text, forKey: "DOBTextFieldInput")
UserDefaults.standard.set(emailTextField.text, forKey: "emailTextFieldInput")
}
performSegue(withIdentifier: "personal_details_validated", sender: nil)
}
}
func yearsBetweenDate(startDate: Date, endDate: Date) -> Int {
let calendar = Calendar.current
let components = calendar.dateComponents([.year], from: startDate, to: endDate)
return components.year!
}
}
|
//
// CustomClass.swift
// poplearning
//
// Created by Vineeth Vijayan on 27/04/16.
// Copyright © 2016 creativelogics. All rights reserved.
//
import Foundation
import UIKit
import pop
class GSSimpleImageView: UIImageView, POPAnimationDelegate {
var tempRect: CGRect?
var bgView: UIView!
var animated: Bool = true
//MARK: Life cycle
override func drawRect(rect: CGRect) {
super.drawRect(rect)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.addTapGesture()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.addTapGesture()
// fatalError("init(coder:) has not been implemented")
}
//MARK: Private methods
func addTapGesture() {
let tap = UITapGestureRecognizer(target: self, action: #selector(GSSimpleImageView.fullScreenMe))
self.addGestureRecognizer(tap)
self.userInteractionEnabled = true
}
//MARK: Actions of Gestures
func exitFullScreen () {
let imageV = bgView.subviews[0] as! UIImageView
let springAnimation = POPSpringAnimation(propertyNamed: kPOPViewFrame)
springAnimation.toValue = NSValue(CGRect: tempRect!)
springAnimation.name = "SomeAnimationNameYouChooseEnding"
springAnimation.springBounciness = 5.0
springAnimation.delegate = self
imageV.pop_addAnimation(springAnimation, forKey: "SomeAnimationNameYouChooseEnding")
let basicAnimation = POPSpringAnimation(propertyNamed: kPOPLayerOpacity)
basicAnimation.toValue = 0
basicAnimation.name = "SomeAnimationNameYouChooseEnd"
basicAnimation.delegate = self
bgView.layer.pop_addAnimation(basicAnimation, forKey: "SomeAnimationNameYouChooseEnd")
}
func pop_animationDidReachToValue(anim: POPAnimation!) {
if anim.name == "SomeAnimationNameYouChooseEnd" {
bgView.removeFromSuperview()
}
}
func pop_animationDidStop(anim: POPAnimation!, finished: Bool) {
if anim.name == "SomeAnimationNameYouChooseEnd" {
bgView.removeFromSuperview()
}
}
func fullScreenMe() {
if let window = UIApplication.sharedApplication().delegate?.window {
let parentView = self.findParentViewController(self)!.view
bgView = UIView(frame: UIScreen.mainScreen().bounds)
bgView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(GSSimpleImageView.exitFullScreen)))
bgView.backgroundColor = UIColor.blackColor()
let imageV = UIImageView(image: self.image)
let point = self.convertRect(self.bounds, toView: parentView)
imageV.frame = point
tempRect = point
imageV.contentMode = .ScaleAspectFit
self.bgView.addSubview(imageV)
window?.addSubview(bgView)
if animated {
let springAnimation = POPSpringAnimation(propertyNamed: kPOPViewFrame)
springAnimation.toValue = NSValue(CGRect: CGRectMake(0, 0, (parentView?.frame.width)!, (parentView?.frame.height)!))
springAnimation.name = "SomeAnimationNameYouChoose"
springAnimation.springBounciness = 10.0
springAnimation.delegate = self
imageV.pop_addAnimation(springAnimation, forKey: "SomeAnimationNameYouChoose")
}
}
}
func findParentViewController(view: UIView) -> UIViewController? {
var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.nextResponder()
if let viewController = parentResponder as? UIViewController {
return viewController
}
}
return nil
}
}
//extension UIView {
// var parentViewController: UIViewController? {
// var parentResponder: UIResponder? = self
// while parentResponder != nil {
// parentResponder = parentResponder!.nextResponder()
// if let viewController = parentResponder as? UIViewController {
// return viewController
// }
// }
// return nil
// }
//}
|
//
// FilterCardHeaderView.swift
// Fid
//
// Created by CROCODILE on 25.03.2021.
//
import UIKit
class FilterCardHeaderView: UITableViewHeaderFooterView {
@IBOutlet weak var sectionTitleLabel: UILabel!
}
|
//
// DeviceInfo.swift
// WalkAbout
//
// Created by Hannes Sverrisson on 17/11/2018.
// Copyright © 2018 Hannes Sverrisson. All rights reserved.
//
import Foundation
import SystemConfiguration
class DeviceInfo {
static func platform() -> String? {
var systemInfo = utsname()
uname(&systemInfo)
let modelCode = withUnsafePointer(to: &systemInfo.machine) {
$0.withMemoryRebound(to: CChar.self, capacity: 1) {
ptr in String.init(validatingUTF8: ptr)
}
}
return modelCode
}
static func deviceType() -> String {
if let platform = platform(), let device = deviceDict[platform] {
return device
}
return "unknown"
}
static let deviceDict: Dictionary<String, String> = [
"iPhone1,1" : "iPhone (1st generation)",
"iPhone1,2" : "iPhone 3G",
"iPhone2,1" : "iPhone 3GS",
"iPhone3,1" : "iPhone 4 (GSM)",
"iPhone3,2" : "iPhone 4 (GSM, 2nd revision)",
"iPhone3,3" : "iPhone 4 (Verizon)",
"iPhone4,1" : "iPhone 4S",
"iPhone5,1" : "iPhone 5 (GSM)",
"iPhone5,2" : "iPhone 5 (GSM+CDMA)",
"iPhone5,3" : "iPhone 5c (GSM)",
"iPhone5,4" : "iPhone 5c (GSM+CDMA)",
"iPhone6,1" : "iPhone 5s (GSM)",
"iPhone6,2" : "iPhone 5s (GSM+CDMA)",
"iPhone7,2" : "iPhone 6",
"iPhone7,1" : "iPhone 6 Plus",
"iPhone8,1" : "iPhone 6s",
"iPhone8,2" : "iPhone 6s Plus",
"iPhone8,4" : "iPhone SE",
"iPhone9,1" : "iPhone 7 (GSM+CDMA)",
"iPhone9,3" : "iPhone 7 (GSM)",
"iPhone9,2" : "iPhone 7 Plus (GSM+CDMA)",
"iPhone9,4" : "iPhone 7 Plus (GSM)",
"iPhone10,1" : "iPhone 8 (GSM+CDMA)",
"iPhone10,4" : "iPhone 8 (GSM)",
"iPhone10,2" : "iPhone 8 Plus (GSM+CDMA)",
"iPhone10,5" : "iPhone 8 Plus (GSM)",
"iPhone10,3" : "iPhone X (GSM+CDMA)",
"iPhone10,6" : "iPhone X (GSM)",
"iPhone11,1" : "iPhone XR (GSM+CDMA)",
"iPhone11,2" : "iPhone XS (GSM+CDMA)",
"iPhone11,3" : "iPhone XS (GSM)",
"iPhone11,4" : "iPhone XS Max (GSM+CDMA)",
"iPhone11,5" : "iPhone XS Max (GSM, Dual Sim, China)",
"iPhone11,6" : "iPhone XS Max (GSM)",
"iPhone11,8" : "iPhone XR (GSM)",
"iPod1,1" : "iPod Touch 1G",
"iPod2,1" : "iPod Touch 2G",
"iPod3,1" : "iPod Touch 3G",
"iPod4,1" : "iPod Touch 4G",
"iPod5,1" : "iPod Touch 5G",
"iPod7,1" : "iPod Touch 6G",
"iPad1,1" : "iPad",
"iPad2,1" : "iPad 2 (WiFi)",
"iPad2,2" : "iPad 2 (GSM)",
"iPad2,3" : "iPad 2 (CDMA)",
"iPad2,4" : "iPad 2 (WiFi)",
"iPad2,5" : "iPad Mini (WiFi)",
"iPad2,6" : "iPad Mini (GSM)",
"iPad2,7" : "iPad Mini (CDMA)",
"iPad3,1" : "iPad 3 (WiFi)",
"iPad3,2" : "iPad 3 (CDMA)",
"iPad3,3" : "iPad 3 (GSM)",
"iPad3,4" : "iPad 4 (WiFi)",
"iPad3,5" : "iPad 4 (GSM)",
"iPad3,6" : "iPad 4 (CDMA)",
"iPad4,1" : "iPad Air (WiFi)",
"iPad4,2" : "iPad Air (GSM)",
"iPad4,3" : "iPad Air (CDMA)",
"iPad4,4" : "iPad Mini 2 (WiFi)",
"iPad4,5" : "iPad Mini 2 (Cellular)",
"iPad4,6" : "iPad Mini 2 (Cellular)",
"iPad4,7" : "iPad Mini 3 (WiFi)",
"iPad4,8" : "iPad Mini 3 (Cellular)",
"iPad4,9" : "iPad Mini 3 (Cellular)",
"iPad5,1" : "iPad Mini 4 (WiFi)",
"iPad5,2" : "iPad Mini 4 (Cellular)",
"iPad5,3" : "iPad Air 2 (WiFi)",
"iPad5,4" : "iPad Air 2 (Cellular)",
"iPad6,3" : "iPad Pro 9.7-inch (WiFi)",
"iPad6,4" : "iPad Pro 9.7-inch (Cellular)",
"iPad6,7" : "iPad Pro 12.9-inch (WiFi)",
"iPad6,8" : "iPad Pro 12.9-inch (Cellular)",
"iPad6,11" : "iPad 5 (WiFi)",
"iPad6,12" : "iPad 5 (Cellular)",
"iPad7,1" : "iPad Pro 12.9-inch 2 (WiFi)",
"iPad7,2" : "iPad Pro 12.9-inch 2 (Cellular)",
"iPad7,3" : "iPad Pro 10.5-inch (WiFi)",
"iPad7,4" : "iPad Pro 10.5-inch (Cellular)",
"iPad7,5" : "iPad 6 (WiFi)",
"iPad7,6" : "iPad 6 (Cellular)",
"iPad8,1" : "iPad Pro 11-inch (WiFi)",
"iPad8,2" : "iPad Pro 11-inch (WiFi, 1TB)",
"iPad8,3" : "iPad Pro 11-inch (Cellular)",
"iPad8,4" : "iPad Pro 11-inch (Cellular, 1TB)",
"iPad8,5" : "iPad Pro 12.9-inch 3 (WiFi)",
"iPad8,6" : "iPad Pro 12.9-inch 3 (WiFi, 1TB)",
"iPad8,7" : "iPad Pro 12.9-inch 3 (Cellular)",
"iPad8,8" : "iPad Pro 12.9-inch 3 (Cellular, 1TB)",
"i386" : "Simulator",
"x86_64" : "Simulator",
]
}
|
/* Copyright (c) 2018 PaddlePaddle Authors. 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 Foundation
fileprivate var singletons : [String : Any] = [:]
class OpCreator<P: PrecisionProtocol> {
static var shared : OpCreator<P> {
let key = String(describing: P.self)
if let singleton = singletons[key] {
return singleton as! OpCreator<P>
} else {
let newSingleton = OpCreator<P>()
singletons[key] = newSingleton
return newSingleton
}
}
func creat(device: MTLDevice, opDesc: PMOpDesc, scope: Scope, initContext: InitContext) throws -> Runable & InferShaperable {
guard let opCreator = opCreators[opDesc.type] else {
throw PaddleMobileError.opError(message: "there is no " + opDesc.type + " yet")
}
do {
return try opCreator(device, opDesc, scope, initContext)
} catch let error {
throw error
}
}
let opCreators: [String : (MTLDevice, PMOpDesc, Scope, InitContext) throws -> Runable & InferShaperable] =
[gConvType : ConvOp<P>.creat,
gBatchNormType : BatchNormOp<P>.creat,
gReluType : ReluOp<P>.creat,
gElementwiseAddType : ElementwiseAddOp<P>.creat,
gFeedType : FeedOp<P>.creat,
gFetchType : FetchOp<P>.creat,
gConvAddBatchNormReluType : ConvAddBatchNormReluOp<P>.creat,
gPooType : PoolOp<P>.creat,
gSoftmaxType : SoftmaxOp<P>.creat,
gReshapeType : ReshapeOp<P>.creat,
gConvAddType : ConvAddOp<P>.creat,
gDepthConvType : DepthConvOp<P>.creat,
gConcatType : ConcatOp<P>.creat,
gBoxcoderType : BoxcoderOp<P>.creat,
gConvBnReluType : ConvBNReluOp<P>.creat,
gDwConvBnReluType : DwConvBNReluOp<P>.creat,
gMulticlassNMSType : MulticlassNMSOp<P>.creat,
gTransposeType : TransposeOp<P>.creat,
gPriorBoxType : PriorBoxOp<P>.creat,
gPreluType : PreluOp<P>.creat,
gConv2dTransposeType : ConvTransposeOp<P>.creat,
gBilinearInterpType : BilinearInterpOp<P>.creat,
gSplit : SplitOp<P>.creat,
gShape : ShapeOp<P>.creat,
gFlatten : FlattenOp<P>.creat,
gConvAddPreluType : ConvAddPreluOp<P>.creat,
gConvAddAddPreluType : ConvAddAddPreluOp<P>.creat,
gElementwiseAddPreluType : ElementwiseAddPreluOp<P>.creat,
gFusionConvAddType : ConvAddOp<P>.creat]
private init(){}
}
|
//
// APIManager.swift
// Study
//
// Created by Gabriel Palhares on 17/06/19.
// Copyright © 2019 Gabriel Palhares. All rights reserved.
//
import Foundation
struct
|
//
// CommonFunction.swift
// pkh0225
//
// Created by pkh on 2021/07/11.
//
import UIKit
typealias AlertActionHandler = ((UIAlertAction) -> Void)
/// only 'title' is required parameter. you can ignore rest of them
///
/// - Parameters:
/// - title: Title string. required.
/// - message: Message for alert.
/// - okTitle: Title for confirmation action. If you don't probide 'okHandler', this will be ignored.
/// - okHandler: Closure for confirmation action. If it's implemented, alertController will have two alertAction.
/// - cancelTitle: Title for cancel/dissmis action.
/// - cancelHandler: Closure for cancel/dissmis action.
/// - completion: Closure will be called right after the alertController presented.
func alert(title: String,
message: String? = nil,
okTitle: String = "OK",
okHandler: AlertActionHandler? = nil,
cancelTitle: String? = nil,
cancelHandler: AlertActionHandler? = nil,
completion: (() -> Void)? = nil) {
let alert: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
if let okClosure = okHandler {
let okAction: UIAlertAction = UIAlertAction(title: okTitle, style: .default, handler: okClosure)
alert.addAction(okAction)
let cancelAction: UIAlertAction = UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler)
alert.addAction(cancelAction)
}
else {
if let cancelTitle = cancelTitle {
let cancelAction: UIAlertAction = UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler)
alert.addAction(cancelAction)
}
else {
let cancelAction: UIAlertAction = UIAlertAction(title: "확인", style: .cancel, handler: cancelHandler)
alert.addAction(cancelAction)
}
}
// self.present(alert, animated: true, completion: completion)
UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
}
|
//
// File.swift
// UserDefaultsHelper
//
// Created by Andrii Vitvitskyi on 1/11/19.
// Copyright © 2019 mac. All rights reserved.
//
import Foundation
protocol BoolUserDefaultable: KeyNamespaceable {
associatedtype BoolDefaultKey: RawRepresentable
}
protocol StringDefaultable: KeyNamespaceable {
associatedtype StringDefaultKey: RawRepresentable
}
protocol DoubleDefaultable: KeyNamespaceable {
associatedtype DoubleDefaultKey: RawRepresentable
}
protocol FloatDefautable: KeyNamespaceable {
associatedtype FloatDefaultKey: RawRepresentable
}
protocol URLDefautable: KeyNamespaceable {
associatedtype URLDefaultKey: RawRepresentable
}
protocol AnyDefautable: KeyNamespaceable {
associatedtype AnyDefaultKey: RawRepresentable
}
protocol KeyNamespaceable {
}
extension KeyNamespaceable {
static func namespace<T>(_ key: T) -> String
where T: RawRepresentable {
print("\(self).\(key.rawValue)")
return "\(self).\(key.rawValue)"
}
}
// MARK: - UserDefault - Bool
extension BoolUserDefaultable where BoolDefaultKey.RawValue == String {
static func set(_ value: Bool, forKey key: BoolDefaultKey) {
let key = namespace(key)
UserDefaults.standard.set(value, forKey: key)
}
static func bool(forKey key: BoolDefaultKey) -> Bool {
let key = namespace(key)
return UserDefaults.standard.bool(forKey: key)
}
}
// MARK: - UserDefault - String
extension StringDefaultable where StringDefaultKey.RawValue == String {
static func set(_ value: String, forKey key: StringDefaultKey) {
let key = namespace(key)
UserDefaults.standard.set(value, forKey: key)
}
static func string(forKey key: StringDefaultKey) -> String? {
let key = namespace(key)
return UserDefaults.standard.string(forKey: key)
}
}
// MARK: - UserDefault - Double
extension DoubleDefaultable where DoubleDefaultKey.RawValue == String {
static func set(_ value: Double, forKey key: DoubleDefaultKey) {
let key = namespace(key)
UserDefaults.standard.set(value, forKey: key)
}
static func double(forKey key: DoubleDefaultKey) -> Double {
let key = namespace(key)
return UserDefaults.standard.double(forKey: key)
}
}
// MARK: - UserDefault - Float
extension FloatDefautable where FloatDefaultKey.RawValue == String {
static func set(_ value: Float, forKey key: FloatDefaultKey) {
let key = namespace(key)
UserDefaults.standard.set(value, forKey: key)
}
static func float(forKey key: FloatDefaultKey) -> Float {
let key = namespace(key)
return UserDefaults.standard.float(forKey: key)
}
}
// MARK: - UserDefault - URL?
extension URLDefautable where URLDefaultKey.RawValue == String {
static func set(_ value: URL?, forKey key: URLDefaultKey) {
let key = namespace(key)
UserDefaults.standard.set(value, forKey: key)
}
static func url(forKey key: URLDefaultKey) -> URL? {
let key = namespace(key)
return UserDefaults.standard.url(forKey: key)
}
}
// MARK: - UserDefault - Any?
extension AnyDefautable where AnyDefaultKey.RawValue == String {
static func set(_ value: Any?, forKey key: AnyDefaultKey) {
let key = namespace(key)
UserDefaults.standard.set(value, forKey: key)
}
static func any(forKey key: AnyDefaultKey) -> Any? {
let key = namespace(key)
return UserDefaults.standard.object(forKey: key)
}
}
typealias UserDefaultsAllTypes = BoolUserDefaultable & StringDefaultable
|
//: [Previous](@previous)
import Foundation
import RxSwift
let subject1 = BehaviorSubject<Int>(value: 0)
let subject2 = BehaviorSubject<Int>(value: 10)
Observable
.zip(subject1, subject2)
.subscribe(onNext: { (value1,value2) in
print("subject1 : \(value1), subject2 : \(value2)")
})
subject1.onNext(50)
subject1.onNext(40)
print("------------------------------------------------")
subject1.onNext(1)
subject2.onNext(10)
print("------------------------------------------------")
subject1.onNext(2)
subject2.onNext(20)
print("------------------------------------------------")
subject1.onNext(30)
subject2.onNext(40)
print("------------------------------------------------")
subject2.onNext(50)
subject2.onNext(40)
/* -- Output --
subject1 : 0, subject2 : 10
------------------------------------------------
subject1 : 50, subject2 : 10
------------------------------------------------
subject1 : 40, subject2 : 20
------------------------------------------------
subject1 : 1, subject2 : 40
------------------------------------------------
subject1 : 2, subject2 : 50
subject1 : 30, subject2 : 40
*/
//: [Next](@next)
|
//
// DemoTodoListApp.swift
// DemoTodoList
//
// Created by David Mardashev on 25.09.2020.
//
import SwiftUI
@main
struct DemoTodoListApp: App {
var body: some Scene {
WindowGroup {
TodoListView()
}
}
}
|
//
// RecorderViewController.swift
// VoiceRecorder
//
// Created by hwjoy on 10/04/2018.
// Copyright © 2018 redant. All rights reserved.
//
import UIKit
import AVFoundation
public let AudioLevel: Float = 120.0
public let AudioAcceptLevel: Float = -20.0
class RecorderViewController: UIViewController, AVAudioRecorderDelegate {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var pauseButton: UIButton!
@IBOutlet weak var stopButton: UIButton!
var audioRecorder: AVAudioRecorder?
lazy var currentAudioFilePath: String = {
let filename = dateFormatter.string(from: Date()) + ".m4a"
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
return NSString(string: documentDirectory).appendingPathComponent(filename)
}()
lazy var currentAudioDirectoryPath: String = {
let filename = dateFormatter.string(from: Date())
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
return NSString(string: documentDirectory).appendingPathComponent(filename)
}()
let recorderSettings = [
AVFormatIDKey : kAudioFormatMPEG4AAC, //编码格式
AVSampleRateKey : 44100.0, //声音采样率
AVNumberOfChannelsKey : 2, //采集音轨
AVEncoderAudioQualityKey : AVAudioQuality.medium.rawValue] as [String : Any]
lazy var updateMetersTimer: Timer = {
return Timer.scheduledTimer(withTimeInterval: WaveformView.SampleRate, repeats: true, block: { (timer) in
self.audioRecorder?.updateMeters()
if var powerChannel0 = self.audioRecorder?.averagePower(forChannel: 0) {
powerChannel0 += 160
self.performSelector(onMainThread: #selector(self.updateWaveform(_:)), with: [NSNumber(value: powerChannel0), UIColor.black.withAlphaComponent(0.8)], waitUntilDone: false)
// print("currentTime = \(self.audioRecorder?.currentTime ?? 0), deviceCurrentTime = \(self.audioRecorder?.deviceCurrentTime ?? 0)")
self.performSelector(onMainThread: #selector(self.updateBarPlot(_:)), with: NSNumber(value: (self.audioRecorder?.currentTime != nil) ? (self.audioRecorder?.currentTime)! : 0.0), waitUntilDone: false)
}
if let currentPeakPower = self.audioRecorder?.peakPower(forChannel: 0),
currentPeakPower > self.peakPower {
print("[D] Update peakPower = \(currentPeakPower), maxAveragePower = \(self.powerArray.max() ?? -160)")
self.peakPower = currentPeakPower
}
})
}()
lazy var dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter
}()
var powerArray: Array<Float> = []
var waveformView: WaveformView?
var barPlotView: BarPlotView?
var scrollView: UIScrollView?
var recordSequence = 1
var peakPower: Float = -160
var barData = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
initButtons()
initAudio()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if waveformView == nil {
initViews()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Init
fileprivate func initButtons() {
startButton.setTitle(NSLocalizedString("Start", comment: ""), for: .normal)
pauseButton.setTitle(NSLocalizedString("Pause", comment: ""), for: .normal)
stopButton.setTitle(NSLocalizedString("Stop", comment: ""), for: .normal)
startButton.isEnabled = false
pauseButton.isEnabled = false
stopButton.isEnabled = false
startButton.addTarget(self, action: #selector(startButtonAction(_:)), for: .touchUpInside)
pauseButton.addTarget(self, action: #selector(pauseButtonAction(_:)), for: .touchUpInside)
stopButton.addTarget(self, action: #selector(stopButtonAction(_:)), for: .touchUpInside)
}
fileprivate func initViews() {
let waveformViewHeight = CGFloat(100.0)
waveformView = WaveformView(frame: CGRect(x: 0, y: 0, width: containerView.frame.width, height: waveformViewHeight))
waveformView?.backgroundColor = UIColor.black.withAlphaComponent(0.2)
waveformView?.layer.cornerRadius = 8
waveformView?.layer.masksToBounds = true
containerView.addSubview(waveformView!)
scrollView = UIScrollView(frame: CGRect(x: 0, y: waveformViewHeight + 16, width: containerView.frame.width, height: containerView.frame.height - waveformViewHeight - 16))
scrollView?.backgroundColor = UIColor.black.withAlphaComponent(0.2)
scrollView?.layer.cornerRadius = 8
scrollView?.layer.masksToBounds = true
containerView.addSubview(scrollView!)
barPlotView = BarPlotView(frame: CGRect(x: 0, y: 0, width: scrollView!.frame.width, height: 0))
scrollView?.addSubview(barPlotView!)
barPlotView?.setBarData(barData)
scrollView?.contentSize = (barPlotView?.frame.size)!
}
fileprivate func initAudio() {
let audioSession = AVAudioSession.sharedInstance()
audioSession.requestRecordPermission { (granted) in
if granted {
self.performSelector(onMainThread: #selector(self.setupAudio(_:)), with: audioSession, waitUntilDone: true)
} else {
}
}
}
@objc func setupAudio(_ audioSession: AVAudioSession) {
startButton.isEnabled = true
do {
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try audioSession.setActive(true)
} catch {
print(error)
}
}
// MARK: - Display Waveform
@objc func updateWaveform(_ params: [Any]) {
// print("[I] \(Date()) \(NSString(string: #file).lastPathComponent) \(#function) \(params)")
guard params.count > 1 else {
return
}
powerArray.append((params.first as! NSNumber).floatValue)
waveformView?.dataSource = powerArray
waveformView?.lineColor = params[1] as! UIColor
waveformView?.setNeedsDisplay()
}
@objc func updateBarPlot(_ params: NSNumber) {
// print("[I] \(Date()) \(NSString(string: #file).lastPathComponent) \(#function) \(params)")
if barData.count < recordSequence {
barData.append(params.intValue)
} else {
barData[barData.count - 1] = params.intValue
}
barPlotView?.setBarData(barData)
}
// MARK: - User Action
@objc func startButtonAction(_ sender: UIButton) {
sender.isEnabled = false
pauseButton.isEnabled = true
stopButton.isEnabled = true
do {
try FileManager.default.createDirectory(atPath: currentAudioDirectoryPath, withIntermediateDirectories: true, attributes: nil)
recordSequence = 1
peakPower = -160
barData = [Int]()
try audioRecorder = AVAudioRecorder(url: URL(fileURLWithPath: NSString(string: currentAudioDirectoryPath).appendingPathComponent("Part-\(recordSequence).m4a")), settings: recorderSettings)
audioRecorder?.delegate = self
audioRecorder?.isMeteringEnabled = true
// Delay Record, For Meter accurately
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0, execute: {
if (self.audioRecorder?.isRecording)! {
return
}
self.audioRecorder?.record(forDuration: 60)
self.updateMetersTimer.fireDate = Date.distantPast
})
} catch {
print(error)
}
}
@objc func pauseButtonAction(_ sender: UIButton) {
sender.isEnabled = false
startButton.isEnabled = true
if (audioRecorder?.isRecording)! {
audioRecorder?.pause()
updateMetersTimer.fireDate = Date.distantFuture
}
}
@objc func stopButtonAction(_ sender: UIButton) {
sender.isEnabled = false
startButton.isEnabled = true
pauseButton.isEnabled = false
audioRecorder?.stop()
if (peakPower < AudioAcceptLevel) {
audioRecorder?.deleteRecording()
}
audioRecorder = nil
updateMetersTimer.fireDate = Date.distantFuture
powerArray.removeAll()
}
fileprivate func startNewRecorder() {
if let _ = audioRecorder {
audioRecorder?.stop()
if (peakPower < AudioAcceptLevel) {
audioRecorder?.deleteRecording()
} else {
recordSequence += 1
}
audioRecorder = nil
peakPower = -160
}
do {
try audioRecorder = AVAudioRecorder(url: URL(fileURLWithPath: NSString(string: currentAudioDirectoryPath).appendingPathComponent("Part-\(recordSequence).m4a")), settings: recorderSettings)
audioRecorder?.delegate = self
audioRecorder?.isMeteringEnabled = true
if (audioRecorder?.isRecording)! {
return
}
audioRecorder?.record(forDuration: 60)
} catch {
print(error)
}
}
// MARK: - AVAudioRecorderDelegate
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
print("[I] \(NSString(string: #file).lastPathComponent) \(#function) \(flag)")
if stopButton.isEnabled {
startNewRecorder()
}
}
func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) {
print("[I] \(NSString(string: #file).lastPathComponent) \(#function) \(error?.localizedDescription ?? "")")
startButton.isEnabled = true
pauseButton.isEnabled = false
stopButton.isEnabled = false
recorder.stop()
if (peakPower < AudioAcceptLevel) {
recorder.deleteRecording()
}
audioRecorder = nil
updateMetersTimer.fireDate = Date.distantFuture
powerArray.removeAll()
}
/*
// 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.
}
*/
}
|
import Foundation
/// A MonadCombine has the capabilities of `MonadFilter` and `Alternative` together.
public protocol MonadCombine: MonadFilter, Alternative {}
public extension MonadCombine {
/// Fold over the inner structure to combine all of the values with our combine method inherited from `MonoidK.
///
/// - Parameter fga: Nested contexts value.
/// - Returns: A value in the context implementing this instance where the inner context has been folded.
static func unite<G: Foldable, A>(_ fga: Kind<Self, Kind<G, A>>) -> Kind<Self, A> {
flatMap(fga, { ga in
G.foldLeft(ga, empty(), { acc, a in
combineK(acc, pure(a))
})
})
}
}
// MARK: Syntax for MonadCombine
public extension Kind where F: MonadCombine {
/// Fold over the inner structure to combine all of the values with our combine method inherited from `MonoidK.
///
/// This is a convenience method to call `MonadCombine.unite` as a static method of this type.
///
/// - Parameter fga: Nested contexts value.
/// - Returns: A value in the context implementing this instance where the inner context has been folded.
static func unite<G: Foldable>(_ fga: Kind<F, Kind<G, A>>) -> Kind<F, A> {
F.unite(fga)
}
}
|
//
// ViewController.swift
// ShoeConverterApp
//
// Created by Development on 2/6/15.
// Copyright (c) 2015 COC Group. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// These are the Outlet Connections from the View Controller
@IBOutlet weak var mensShoeSizeTextField: UITextField!
@IBOutlet weak var mensConvertedShoeSizeLabel: UILabel!
@IBOutlet weak var womensShoeSizeTextField: UITextField!
@IBOutlet weak var womensConvertedShoeSizeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Call the actions when a convert button is pushed.
@IBAction func convertButtonPressed(sender: UIButton) {
// let sizeFromTextField = mensShoeSizeTextField.text
// let numberFromTextField = sizeFromTextField.toInt()
// var integerFromTextField = numberFromTextField!
// The previous code is combined into the following code:
let sizeFromTextField = mensShoeSizeTextField.text.toInt()!
// setup the constants and unhide the converted label
let conversionConstant = 30
mensConvertedShoeSizeLabel.hidden=false
// integerFromTextField += conversionConstant
// let stringWithUpdatedShoeSize = "\(integerFromTextField)"
// mensConvertedShoeSizeLabel.text = stringWithUpdatedShoeSize
// The previous code is combined into the following code:
mensConvertedShoeSizeLabel.text = "\(sizeFromTextField + conversionConstant)" + " in European Shoe Size"
}
@IBAction func convetWomensShoeSizeButtonPressed(sender: UIButton) {
let sizeFromTextField = Double((womensShoeSizeTextField.text as NSString).doubleValue)
let conversionConstant = 30.5
womensConvertedShoeSizeLabel.hidden=false
womensConvertedShoeSizeLabel.text = "\(sizeFromTextField + conversionConstant)" + " in European Shoe Size"
}
}
|
//
// RootTabBar.swift
// Captioned
//
// Created by Przemysław Pająk on 08.01.2018.
// Copyright © 2018 FEARLESS SPIDER. All rights reserved.
//
import UIKit
import ColorWithHex
import Material
extension RootTabBarItem {
override public var badgeValue: String? {
get {
return badge?.text
}
set(newValue) {
if newValue == nil {
badge?.removeFromSuperview()
badge = nil;
return
}
if badge == nil {
badge = RootBadge.bage()
if let contanerView = self.iconView!.icon.superview {
badge!.addBadgeOnView(onView: contanerView)
}
}
badge?.text = newValue
}
}
}
public class RootTabBarItem: UITabBarItem {
public var textFont: UIFont = UIFont.systemFont(ofSize: 10)
@IBInspectable public var textColor: UIColor = UIColor.black
@IBInspectable public var iconColor: UIColor = UIColor.black // if alpha color is 0 color ignoring
@IBInspectable var bgDefaultColor: UIColor = UIColor.white // background color
@IBInspectable var bgSelectedColor: UIColor = UIColor.white
@IBInspectable var highlight: Bool = false
public var badge: RootBadge? // use badgeValue to show badge
public var iconView: (icon: UIImageView, textLabel: UILabel)?
}
extension RootTabBar {
public func changeSelectedColor(textSelectedColor:UIColor, iconSelectedColor:UIColor) {
let items = tabBar.items as! [RootTabBarItem]
for index in 0..<items.count {
let item = items[index]
if item == self.tabBar.selectedItem {
//item.selectedState()
}
}
}
public func animationTabBarHidden(isHidden:Bool) {
guard let items = tabBar.items as? [RootTabBarItem] else {
fatalError("items must inherit RootTabBarItem")
}
for item in items {
if let iconView = item.iconView {
iconView.icon.superview?.isHidden = isHidden
}
}
self.tabBar.isHidden = isHidden;
}
public func setSelectIndex(from: Int, to: Int) {
selectedIndex = to
guard let items = tabBar.items as? [RootTabBarItem] else {
fatalError("items must inherit RootTabBarItem")
}
let containerFrom = items[from].iconView?.icon.superview
containerFrom?.backgroundColor = items[from].bgDefaultColor
items[from].iconView?.icon.tintColor = UIColor.black
let containerTo = items[to].iconView?.icon.superview
containerTo?.backgroundColor = items[to].bgSelectedColor
items[to].iconView?.icon.tintColor = UIColor.colorWithHex("2196F3")!
}
}
public class RootTabBar: UITabBarController {
public static let ShowedLoginDefault = "Defaults.ShowedLogin"
var selectedDefaultTabOnce = false
var chechedForNotificationsOnce = false
private var didInit: Bool = false
private var didLoadView: Bool = false
/* public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.didInit = true
self.initializeContainers()
}*/
public init(viewControllers: [UIViewController]) {
super.init(nibName: nil, bundle: nil)
self.didInit = true
// Set initial items
self.setViewControllers(viewControllers, animated: false)
self.initializeContainers()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.didInit = true
self.initializeContainers()
}
override public func viewDidLoad() {
super.viewDidLoad()
delegate = self
self.didLoadView = true
self.initializeContainers()
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if !selectedDefaultTabOnce {
selectedDefaultTabOnce = true
if let value = UserDefaults.standard.value(forKey: DefaultLoadingScreen) as? String {
switch value {
case "Search":
selectedIndex = 1
default:
break
}
}
}
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
private func initializeContainers() {
if !self.didInit || !self.didLoadView {
return
}
let containers = self.createViewContainers()
self.createCustomIcons(containers: containers)
}
// MARK: create methods
private func createCustomIcons(containers : NSDictionary) {
guard let items = self.tabBar.items as? [RootTabBarItem] else {
fatalError("items must inherit RootTabBarItem")
}
var index = 0
for item in items {
guard let itemImage = item.image else {
fatalError("add image icon in UITabBarItem")
}
guard let container = containers["container\(items.count - 1 - index)"] as? UIView else {
fatalError()
}
container.tag = index
let renderMode = UIImageRenderingMode.alwaysTemplate
let icon = UIImageView(image: item.image?.withRenderingMode(renderMode))
icon.translatesAutoresizingMaskIntoConstraints = false
icon.tintColor = item.iconColor
// text
let textLabel = UILabel()
textLabel.isHidden = true
/* textLabel.text = item.title
textLabel.backgroundColor = UIColor.clearColor()
textLabel.textColor = item.textColor
textLabel.font = item.textFont
textLabel.textAlignment = NSTextAlignment.Center
textLabel.translatesAutoresizingMaskIntoConstraints = false
*/
container.backgroundColor = (items as [RootTabBarItem])[index].bgDefaultColor
container.addSubview(icon)
createConstraints(view: icon, container: container, size: itemImage.size, yOffset: 0)
//container.addSubview(textLabel)
//let textLabelWidth = tabBar.frame.size.width / CGFloat(items.count) - 5.0
//createConstraints(textLabel, container: container, size: CGSize(width: textLabelWidth , height: 10), yOffset: 16)
item.iconView = (icon:icon, textLabel:textLabel)
if 0 == index { // selected first elemet
//item.selectedState()
container.backgroundColor = (items as [RootTabBarItem])[index].bgSelectedColor
let border = UIView()
border.frame = CGRect(x:0, y:icon.frame.height+2, width:icon.frame.width+10, height:2)
border.backgroundColor = UIColor.colorWithHex("2196F3")!
container.addSubview(border)
container.bringSubview(toFront: border)
icon.tintColor = UIColor.colorWithHex("2196F3")!
}
item.image = nil
item.title = ""
index += 1
}
}
private func createConstraints(view:UIView, container:UIView, size:CGSize, yOffset:CGFloat) {
let constX = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.centerX,
relatedBy: NSLayoutRelation.equal,
toItem: container,
attribute: NSLayoutAttribute.centerX,
multiplier: 1,
constant: 0)
container.addConstraint(constX)
let constY = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.centerY,
relatedBy: NSLayoutRelation.equal,
toItem: container,
attribute: NSLayoutAttribute.centerY,
multiplier: 1,
constant: yOffset)
container.addConstraint(constY)
let constW = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: size.width)
view.addConstraint(constW)
let constH = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: size.height)
view.addConstraint(constH)
}
private func createViewContainers() -> NSDictionary {
guard let items = self.tabBar.items else {
fatalError("add items in tabBar")
}
var containersDict = [String: AnyObject]()
for index in 0..<items.count {
let viewContainer = createViewContainer()
containersDict["container\(index)"] = viewContainer
}
var formatString = "H:|-(0)-[container0]"
for index in 1..<items.count {
formatString += "-(0)-[container\(index)(==container0)]"
}
formatString += "-(0)-|"
let constranints = NSLayoutConstraint.constraints(withVisualFormat: formatString,
options:NSLayoutFormatOptions.directionRightToLeft,
metrics: nil,
views: (containersDict as [String : AnyObject]))
view.addConstraints(constranints)
return containersDict as NSDictionary
}
private func createViewContainer() -> UIView {
let viewContainer = UIView();
viewContainer.backgroundColor = UIColor.clear // for test
viewContainer.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(viewContainer)
// add gesture
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(RootTabBar.tapHandler(gesture:)))
tapGesture.numberOfTouchesRequired = 1
viewContainer.addGestureRecognizer(tapGesture)
// add constrains
let constY = NSLayoutConstraint(item: viewContainer,
attribute: NSLayoutAttribute.bottom,
relatedBy: NSLayoutRelation.equal,
toItem: view,
attribute: NSLayoutAttribute.bottom,
multiplier: 1,
constant: 0)
view.addConstraint(constY)
let constH = NSLayoutConstraint(item: viewContainer,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: nil,
attribute: NSLayoutAttribute.notAnAttribute,
multiplier: 1,
constant: tabBar.frame.size.height)
viewContainer.addConstraint(constH)
return viewContainer
}
// MARK: actions
@objc func tapHandler(gesture:UIGestureRecognizer) {
guard let items = tabBar.items as? [RootTabBarItem] else {
fatalError("items must inherit RootTabBarItem")
}
guard let gestureView = gesture.view else {
return
}
let currentIndex = gestureView.tag
let controller = self.childViewControllers[currentIndex]
if let shouldSelect = delegate?.tabBarController?(self, shouldSelect: controller), !shouldSelect {
return
}
if selectedIndex != currentIndex {
let animationItem : RootTabBarItem = items[currentIndex]
let deselectItem = items[selectedIndex]
let containerPrevious : UIView = deselectItem.iconView!.icon.superview!
//containerPrevious.backgroundColor = items[currentIndex].bgDefaultColor
let borderPrevious = UIView()
borderPrevious.frame = CGRect(x:0, y:containerPrevious.frame.height - 2, width:containerPrevious.frame.width, height:2)
if (!deselectItem.highlight) {
borderPrevious.backgroundColor = UIColor.white
deselectItem.iconView!.icon.tintColor = UIColor.black
} else {
borderPrevious.backgroundColor = UIColor.colorWithHex("2196F3")!
deselectItem.iconView!.icon.tintColor = UIColor.white
}
containerPrevious.addSubview(borderPrevious)
let container : UIView = animationItem.iconView!.icon.superview!
//container.backgroundColor = items[currentIndex].bgSelectedColor
let border = UIView()
border.frame = CGRect(x:0, y:container.frame.height - 2, width:container.frame.width, height:2)
border.backgroundColor = UIColor.colorWithHex("2196F3")!
container.addSubview(border)
if (!animationItem.highlight) {
animationItem.iconView!.icon.tintColor = UIColor.colorWithHex("2196F3")!
} else {
animationItem.iconView!.icon.tintColor = UIColor.white
}
selectedIndex = gestureView.tag
delegate?.tabBarController?(self, didSelect: controller)
} else if selectedIndex == currentIndex {
if let navVC = self.viewControllers![selectedIndex] as? UINavigationController {
navVC.popToRootViewController(animated: true)
}
}
}
}
extension RootTabBar: UITabBarControllerDelegate {
public func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
_ = viewController as! UINavigationController
return true
}
}
|
//
// MyBall.swift
// BouncingBall
//
// Created by Son Vu L.L on 6/22/17.
// Copyright © 2017 Son Vu L.L. All rights reserved.
//
import UIKit
struct Size {
let width: Int
let height: Int
}
class MyBall: UIView {
private var colorBall: UIColor
private var speedBall: Double = 0
private var sizeBall: Size
var x = 50.0
var y = 50.0
var dx: Double = 10
var dy: Double = 10 * Double(Float(arc4random()) / Float(UINT32_MAX))
init(frame: CGRect, colorBall: UIColor, speddBall: Double, sizeBall: Size) {
self.colorBall = colorBall
self.speedBall = speddBall
self.sizeBall = sizeBall
super.init(frame: frame)
configBall()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configBall() {
self.backgroundColor = colorBall
self.layer.cornerRadius = CGFloat(sizeBall.width / 2)
self.frame.size = CGSize(width: sizeBall.width, height: sizeBall.height)
// var timer = selector: #selector(self.update), userInfo: nil, repeats: true)
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in
UIView.animate(withDuration: 0.1) {
self.x += self.dx * self.speedBall
self.y += self.dy * self.speedBall
self.center = CGPoint(x: self.x, y: self.y)
if self.x > Double(UIScreen.main.bounds.maxX - (self.bounds.width / 2)) || self.x < Double(self.bounds.width / 2) {
self.dx = -self.dx
}
if self.y > Double(UIScreen.main.bounds.maxY - (self.bounds.height / 2)) || self.y < Double(self.bounds.width / 2) {
self.dy = -self.dy
}
}
}
}
}
// @objc func update() {
//
//
// }
|
//
// ImageCellCollectionViewCell.swift
// RMImageLoader
//
// Created by Robert D. Mogos.
// Copyright © 2017 Robert D. Mogos. All rights reserved.
//
import UIKit
class ImageCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
func load(withURL URL: URL) {
imageView.image = nil
imageView.load(url: URL)
}
}
|
//
// Users.swift
// SimplySiamApplication
//
// Created by student on 2/11/18.
// Copyright © 2018 student. All rights reserved.
//
import Foundation
@objcMembers
class Users : NSObject {
var objectId:String? // optional, if we need access to this
var name:String?
var email:String?
var address:String?
var state:String?
var city:String?
var zip:String?
var phone:String?
override var description: String {
return "name: \(String(describing:name))"
}
init(name:String,email:String,address:String,state:String,city:String,zip:String,phone:String){
self.name = name
self.email = email
self.address = address
self.state = state
self.city = city
self.zip = zip
self.phone = phone
}
override init() {
super.init()
}
}
|
public struct ParCoreModule {
public static let version = "0.0.1"
}
|
//
// DeckCardsViewModel.swift
// DeckCards
//
// Created by Leandro de Sousa on 04/11/20.
// Copyright © 2020 Leandro de Sousa. All rights reserved.
//
import Foundation
// MARK: - Delegates
protocol DeckCardsViewModelCoordinatorDelegate: AnyObject {
func goToCardInfoScreen(_ viewModel: DeckCardsViewModel, deckId: String)
}
protocol DeckCardsViewModelViewDelegate: AnyObject {
func cardsSuccess(_ viewModel: DeckCardsViewModel)
func cardsFailure(_ viewModel: DeckCardsViewModel, error: Error)
func cardsPartialSuccess(_ viewModel: DeckCardsViewModel, deckId: String)
}
class DeckCardsViewModel {
// MARK: - Properties
var service: DeckService
var model: DeckModel
// MARK: - Delegates Properties
weak var coordinatorDelegate: DeckCardsViewModelCoordinatorDelegate?
weak var viewDelegate: DeckCardsViewModelViewDelegate?
// MARK: - Initializers
init() {
self.model = DeckModel(success: false, deck_id: "", remaining: 0, shuffled: nil, cards: nil, piles: nil)
self.service = DeckService()
}
// MARK: - Computer Variables Methods
var cards: [String] {
guard let cards = model.cards else { return [] }
return cards.map { $0.image }
}
var numberLinesOfCards: Int {
(cards.count + 1) / 2
}
// MARK: - Methods
func isTheLastCard(_ index: Int) -> Bool {
cards.count == index + 1
}
func getCodeCards() -> String {
var codesCards: [String] = []
guard let cards = model.cards else { return ""}
for index in 0..<5 {
codesCards.append(cards[index].code)
}
codesCards.append(cards[10].code)
return codesCards.joined(separator: ",")
}
// MARK: - Service Methods
func shuffleTheCards(_ dispatchSemaphore: DispatchSemaphore) {
dispatchSemaphore.wait()
service.shuffleTheCards { (result) in
switch result {
case .success(let model):
self.model = model
case .failure(let error):
self.viewDelegate?.cardsFailure(self, error: error)
}
dispatchSemaphore.signal()
}
}
func drawACard(_ dispatchSemaphore: DispatchSemaphore) {
dispatchSemaphore.wait()
service.drawCards(deckId: model.deck_id, count: 11) { (result) in
switch result {
case .success(let model):
self.model = model
self.viewDelegate?.cardsSuccess(self)
case .failure(let error):
self.viewDelegate?.cardsFailure(self, error: error)
}
dispatchSemaphore.signal()
}
}
func aPartialDeck() {
service.aPartialDeck(cards: getCodeCards()) { (result) in
switch result {
case .success(let model):
self.viewDelegate?.cardsPartialSuccess(self, deckId: model.deck_id)
case .failure(let error):
self.viewDelegate?.cardsFailure(self, error: error)
}
}
}
func fetchDeckCards() {
let semaphore = DispatchSemaphore(value: 1)
shuffleTheCards(semaphore)
drawACard(semaphore)
}
// MARK: - Coordinator Delegates Methods
func goToCardInfoScreen(deckId: String) {
coordinatorDelegate?.goToCardInfoScreen(self, deckId: deckId)
}
}
|
import UIKit
import AVFoundation
class ViewController: UIViewController,AVAudioPlayerDelegate{
var audioPlayer : AVAudioPlayer!
let soundArray = ["note1","note2","note3","note4","note5","note6","note7"]
var selectedSoundFileName : String = "";
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func notePressed(_ sender: UIButton) {
selectedSoundFileName = soundArray[sender.tag - 1]
playSound()
}
func playSound(){
// let soundURL = Bundle.main.url(forResource:"note\(sender.tag)", withExtension:"wav" )!
let soundURL = Bundle.main.url(forResource:selectedSoundFileName , withExtension:"wav" )!
do {
//try! audioPlayer = try AVAudioPlayer(contentsOf : soundURL)
try audioPlayer = try AVAudioPlayer(contentsOf : soundURL)
} catch {
print(error )
}
audioPlayer.play()
}
}
|
//
// ViewController.swift
// AliveCorAssignment
//
// Created by abhinay varma on 30/10/20.
// Copyright © 2020 abhinay varma. All rights reserved.
//
import UIKit
import SDWebImage
class MainViewController: UIViewController {
@IBOutlet weak var mainTableView: UITableView!
let mainViewModel = MainViewModel()
override func viewDidLoad() {
super.viewDidLoad()
mainViewModel.delegate = self
mainViewModel.getMovies()
setupTableView()
}
private func setupTableView() {
mainTableView.register(UINib(nibName: "MovieTableViewCell", bundle: nil), forCellReuseIdentifier: "MovieTableViewCell")
mainTableView.delegate = self
mainTableView.dataSource = self
}
@IBAction func refreshButtonClicked(_ sender: Any) {
mainViewModel.reloadDataOnRefresh()
}
@IBAction func onClickFav(_ sender: Any) {
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "FavViewController") as? FavViewController
self.navigationController?.pushViewController(vc!,animated:true)
}
}
extension MainViewController:UITableViewDataSource,UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mainViewModel.models.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MovieTableViewCell", for: indexPath) as? MovieTableViewCell
let model = mainViewModel.models[indexPath.row]
cell?.updateCell(model)
cell?.favClicked = {
self.mainViewModel.updateFav(model)
}
if indexPath.row == mainViewModel.models.count - 1 && mainViewModel.currentPage < mainViewModel.totalPages {
mainViewModel.currentPage += 1
mainViewModel.getMovies()
}
return cell ?? UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 60.0
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0.0, y: 0.0, width: UIScreen.main.bounds.size.width, height: 60.0))
view.backgroundColor = UIColor(displayP3Red: 25.0/255.0, green: 25.0/255.0, blue: 25.0/255.0, alpha: 1.0)
let titleLabel = UILabel(frame: CGRect(x: 16.0, y: 5.0, width: view.frame.size.width, height: 50.0))
titleLabel.textAlignment = .left
titleLabel.text = "Most Popular Movies"
titleLabel.font = UIFont(name: "", size: 40.0)
titleLabel.textColor = UIColor.white
view.addSubview(titleLabel)
return view
}
}
extension MainViewController:UIUpdateDelegate {
func reloadTableView() {
DispatchQueue.main.async {
self.mainTableView.reloadData()
}
}
}
|
//
// label.swift
// MSconverter
//
// Created by Alexander Nazarov on 31.03.2021.
//
import UIKit
class Label: UIView {
var rub: Double?
@IBAction func buttonOk(_ sender: Any) {
//Проверка на текст
if let text = usdText.text, let rubble = rub, !text.isEmpty
{
rubText.text = String(format:"%.2f", Double(text)! * rubble)
} else {
print("error")
}
}
@IBOutlet weak var usdText: UITextField!
@IBOutlet weak var rubText: UITextField!
}
|
import UIKit
import RxSwift
import RxCocoa
import SnapKit
import SectionsTableView
import ComponentKit
import ThemeKit
class ManageWalletsViewController: ThemeSearchViewController {
private let viewModel: ManageWalletsViewModel
private let restoreSettingsView: RestoreSettingsView
private let disposeBag = DisposeBag()
private let tableView = SectionsTableView(style: .grouped)
private let notFoundPlaceholder = PlaceholderView(layoutType: .keyboard)
private var viewItems: [ManageWalletsViewModel.ViewItem] = []
private var isLoaded = false
init(viewModel: ManageWalletsViewModel, restoreSettingsView: RestoreSettingsView) {
self.viewModel = viewModel
self.restoreSettingsView = restoreSettingsView
super.init(scrollViews: [tableView])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "manage_wallets.title".localized
navigationItem.searchController?.searchBar.placeholder = "manage_wallets.search_placeholder".localized
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "button.done".localized, style: .done, target: self, action: #selector(onTapDoneButton))
if viewModel.addTokenEnabled {
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(onTapAddTokenButton))
}
view.addSubview(tableView)
tableView.snp.makeConstraints { maker in
maker.edges.equalToSuperview()
}
tableView.backgroundColor = .clear
tableView.separatorStyle = .none
tableView.sectionDataSource = self
view.addSubview(notFoundPlaceholder)
notFoundPlaceholder.snp.makeConstraints { maker in
maker.edges.equalTo(view.safeAreaLayoutGuide)
}
notFoundPlaceholder.image = UIImage(named: "not_found_48")
notFoundPlaceholder.text = "manage_wallets.not_found".localized
restoreSettingsView.onOpenController = { [weak self] controller in
self?.open(controller: controller)
}
subscribe(disposeBag, viewModel.viewItemsDriver) { [weak self] in self?.onUpdate(viewItems: $0) }
subscribe(disposeBag, viewModel.notFoundVisibleDriver) { [weak self] in self?.setNotFound(visible: $0) }
subscribe(disposeBag, viewModel.disableItemSignal) { [weak self] in self?.setToggle(on: false, index: $0) }
subscribe(disposeBag, viewModel.showInfoSignal) { [weak self] in self?.showInfo(viewItem: $0) }
subscribe(disposeBag, viewModel.showBirthdayHeightSignal) { [weak self] in self?.showBirthdayHeight(viewItem: $0) }
subscribe(disposeBag, viewModel.showContractSignal) { [weak self] in self?.showContract(viewItem: $0) }
tableView.buildSections()
isLoaded = true
}
private func open(controller: UIViewController) {
navigationItem.searchController?.dismiss(animated: true)
present(controller, animated: true)
}
@objc private func onTapDoneButton() {
dismiss(animated: true)
}
@objc private func onTapAddTokenButton() {
guard let module = AddTokenModule.viewController() else {
return
}
present(module, animated: true)
}
private func onUpdate(viewItems: [ManageWalletsViewModel.ViewItem]) {
let animated = self.viewItems.map { $0.uid } == viewItems.map { $0.uid }
self.viewItems = viewItems
if isLoaded {
tableView.reload(animated: animated)
}
}
private func setNotFound(visible: Bool) {
notFoundPlaceholder.isHidden = !visible
}
private func showInfo(viewItem: ManageWalletsViewModel.InfoViewItem) {
showBottomSheet(viewItem: viewItem.coin, items: [
.description(text: viewItem.text)
])
}
private func showBirthdayHeight(viewItem: ManageWalletsViewModel.BirthdayHeightViewItem) {
showBottomSheet(viewItem: viewItem.coin, items: [
.copyableValue(title: "birthday_height.title".localized, value: viewItem.height)
])
}
private func showContract(viewItem: ManageWalletsViewModel.ContractViewItem) {
showBottomSheet(viewItem: viewItem.coin, items: [
.contractAddress(imageUrl: viewItem.blockchainImageUrl, value: viewItem.value, explorerUrl: viewItem.explorerUrl)
])
}
private func showBottomSheet(viewItem: ManageWalletsViewModel.CoinViewItem, items: [BottomSheetModule.Item]) {
let viewController = BottomSheetModule.viewController(
image: .remote(url: viewItem.coinImageUrl, placeholder: viewItem.coinPlaceholderImageName),
title: viewItem.coinCode,
subtitle: viewItem.coinName,
items: items
)
present(viewController, animated: true)
}
override func onUpdate(filter: String?) {
viewModel.onUpdate(filter: filter ?? "")
}
private func onToggle(index: Int, enabled: Bool) {
if enabled {
viewModel.onEnable(index: index)
} else {
viewModel.onDisable(index: index)
}
}
func setToggle(on: Bool, index: Int) {
guard let cell = tableView.cellForRow(at: IndexPath(row: index, section: 0)) as? BaseThemeCell else {
return
}
CellBuilderNew.buildStatic(cell: cell, rootElement: rootElement(index: index, viewItem: viewItems[index], forceToggleOn: on))
}
}
extension ManageWalletsViewController: SectionsDataSource {
private func rootElement(index: Int, viewItem: ManageWalletsViewModel.ViewItem, forceToggleOn: Bool? = nil) -> CellBuilderNew.CellElement {
.hStack([
.image32 { component in
component.setImage(
urlString: viewItem.imageUrl,
placeholder: viewItem.placeholderImageName.flatMap { UIImage(named: $0) }
)
},
.vStackCentered([
.hStack([
.textElement(text: .body(viewItem.title), parameters: .highHugging),
.margin8,
.badge { component in
component.isHidden = viewItem.badge == nil
component.badgeView.set(style: .small)
component.badgeView.text = viewItem.badge
},
.margin0,
.text { _ in }
]),
.margin(1),
.textElement(text: .subhead2(viewItem.subtitle))
]),
.secondaryCircleButton { [weak self] component in
component.isHidden = !viewItem.hasInfo
component.button.set(image: UIImage(named: "circle_information_20"), style: .transparent)
component.onTap = {
self?.viewModel.onTapInfo(index: index)
}
},
.switch { component in
if let forceOn = forceToggleOn {
component.switchView.setOn(forceOn, animated: true)
} else {
component.switchView.isOn = viewItem.enabled
}
component.onSwitch = { [weak self] enabled in
self?.onToggle(index: index, enabled: enabled)
}
}
])
}
func buildSections() -> [SectionProtocol] {
[
Section(
id: "coins",
headerState: .margin(height: .margin4),
footerState: .margin(height: .margin32),
rows: viewItems.enumerated().map { index, viewItem in
let isLast = index == viewItems.count - 1
return CellBuilderNew.row(
rootElement: rootElement(index: index, viewItem: viewItem),
tableView: tableView,
id: "token_\(viewItem.uid)",
hash: "token_\(viewItem.enabled)_\(viewItem.hasInfo)_\(isLast)",
height: .heightDoubleLineCell,
autoDeselect: true,
bind: { cell in
cell.set(backgroundStyle: .transparent, isLast: isLast)
}
)
}
)
]
}
}
|
//
// HomePage+LocationControl.swift
// Task
//
// Created by mac on 3/3/18.
// Copyright © 2018 NermeenTomoum. All rights reserved.
//
import UIKit
import CoreLocation
// Location
extension HomePage : LocationServiceProtocol
{
// MARK: - variable
// MARK: - function
func updateLocationRespose(_ placeMarks: CLPlacemark?) {
LocationService.shared.locationManager.stopUpdatingLocation()
if let containsPlacemark = placeMarks {
let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
let isoCountry = (containsPlacemark.isoCountryCode != nil) ? containsPlacemark.isoCountryCode : ""
if citiesArray.count == 1
{
citiesArray.removeAll()
citiesArray.append(LocationModel(citiyName: administrativeArea!, ISOcountryCode: isoCountry!))
}
print( "===========>",administrativeArea ?? "" )
outletOfSearchResultTableView.reloadData()
}
else
{
}
}
func updateLocationdidFailWithError(errorMessage: String) {
}
}
|
//
// Assignment2Tests.swift
// Assignment2Tests
//
// Created by Megan Hayes on 10/5/18.
// Copyright © 2018 Sweta. All rights reserved.
//
import XCTest
class Assignment2Tests: XCTestCase {
var filename: String = "test.json"
//var alltypesFilename: String = "automatically-generated-test-alltypes.json"
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// var home = FileManager.default.homeDirectoryForCurrentUser
// home.appendPathComponent(filename)
//
// var current = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
// current.appendPathComponent(filename)
//
// //var alltypes = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
// //alltypes.appendPathComponent(alltypesFilename)
//
// do {
// try singleDocumentValid.write(to: home, atomically: true, encoding: String.Encoding.utf8)
// try singleDocumentValid.write(to: current, atomically: true, encoding: String.Encoding.utf8)
// //try allTypesValid.write(to: alltypes, atomically: true, encoding: String.Encoding.utf8)
// } catch {
// // failed to write file – bad permissions, bad filename,
// // missing permissions, or more likely it can't be converted to the encoding
// XCTFail("something went wrong writing files ... \(error)")
// }
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testFromFullPath() {
// var current = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
// current.appendPathComponent(filename)
//
// let loader = JSONImporter()
// do {
// let result = try loader.read(filename: current.path)
// XCTAssert(result.count > 0, "Expected to read *some* data")
// } catch {
// XCTFail("Generated un expected exception")
// }
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
|
//
// Locationer.swift
// Locationer
//
// Created by Ruslan Alikhamov on 27.02.19.
// Copyright © 2019 Imagemaker. All rights reserved.
//
import Foundation
import CoreLocation
public class Locationer : NSObject {
fileprivate var callback : ((CLLocationCoordinate2D?, Error?) -> Void)
private var locationManager : CLLocationManager?
public init(callback: @escaping (CLLocationCoordinate2D?, Error?) -> Void) {
self.callback = callback
super.init()
self.setupLocationManager()
}
func setupLocationManager() {
let retVal = CLLocationManager()
retVal.activityType = .fitness
retVal.allowsBackgroundLocationUpdates = true
retVal.delegate = self
retVal.desiredAccuracy = kCLLocationAccuracyHundredMeters
retVal.distanceFilter = 100
self.locationManager = retVal
}
public func start() {
if CLLocationManager.authorizationStatus() == .authorizedAlways {
self.locationManager?.startUpdatingLocation()
} else {
self.locationManager?.requestAlwaysAuthorization()
}
}
public func stop() {
self.locationManager?.stopUpdatingLocation()
}
}
extension Locationer : CLLocationManagerDelegate {
public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status != .authorizedAlways && status != .notDetermined {
fatalError("unable to work with such authorization")
} else if status == .authorizedAlways {
self.locationManager?.startUpdatingLocation()
}
}
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let mostRecent = locations.last
// TODO: filter out old location updates by -[CLLocation date]
self.callback(mostRecent?.coordinate, nil)
}
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
self.callback(nil, error)
fatalError("failed to fetch location! \(error)")
}
}
|
//
// TransactionTableViewCell.swift
// Bank
//
// Created by Junior Obici on 13/01/20.
// Copyright © 2020 Junior Obici. All rights reserved.
//
import UIKit
class TransactionTableViewCell: UITableViewCell {
//MARK: - Componentes
@IBOutlet weak var viewTransaction: UIView!
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var labelDesc: UILabel!
@IBOutlet weak var labelDate: UILabel!
@IBOutlet weak var labelValue: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
//MARK: - Prepare
func prepareTransactionCell(with transaction: Transaction) {
labelTitle.text = transaction.title
labelDesc.text = transaction.desc
labelDate.text = transaction.date.toShortDate
labelValue.text = Decimal(transaction.value).Currency
}
}
|
//
// UserDataFirestoreTests.swift
// PD_PALTests
//
// Created by William Huong on 2019-11-11.
// Copyright © 2019 WareOne. All rights reserved.
//
/*
Revision History
- 11/11/2019 : William Huong
Created file, read test
- 15/11/2019 : William Huong
Implemented test for UserInfo update
- 16/11/2019 : William Huong
Implemented tests for Get_Routines() and Get_ExerciseData()
- 16/11/2019 : William Huong
Updated tests to handle asynchronous nature of functions
- 16/11/2019 : William Huong
Implemented test for Update_Routines()
- 17/11/2019 : William Huong
Each test method now uses its own instance of the UserData class
*/
/*
Known Bugs
- 16/11/2019 : William Huong --- Fixed
The functions being tested are asynchronous, so it is possible for any test function to return before an XTCAssert() has had a chance to throw.
When an XTCAssert() throws after the function it is inside of has already returned, we get a hard SIGABRT error which crashes the app.
- 17/11/2019 : William Huong
The test methods all start at the same time, but also all use the global_UserData instance of the UserData class. This causes an issue where some functions will not do anything because a different test method cleared the database.
- 17/11/2019 : William Huong --- Fixed
Get_Routines(), Get_ExerciseData(), Routines() all throw an error : API violation - multiple calls made to -[XCTestExpectation fulfill]
*/
import XCTest
import Firebase
@testable import PD_PAL
class UserDataFirestoreTests: XCTestCase {
override func 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.
}
func test_Get_UserInfo() {
//Initialize a new UserData class that only this method will interact with, along with a UserDataFirestore class using that Database
let Get_UserInfoDB = UserData(DatabaseIdentifier: "Get_UserInfo")
let Get_UserInfoFirestore = UserDataFirestore(sourceGiven: Get_UserInfoDB)
var nullUserAsyncExpectation: XCTestExpectation? = expectation(description: "Get_UserInfo(\"nullUser\") async block started")
DispatchQueue.main.async {
//Check reading a non-existant user returns as expected
Get_UserInfoFirestore.Get_UserInfo(targetUser: "nullUser") { remoteUserData in
XCTAssert( remoteUserData.Status == "NO_DOCUMENT" )
XCTAssert( remoteUserData.UserName == "DEFAULT_NAME" )
XCTAssert( remoteUserData.QuestionsAnswered == false )
XCTAssert( remoteUserData.WalkingDuration == 0 )
XCTAssert( remoteUserData.ChairAccessible == false )
XCTAssert( remoteUserData.WeightsAccessible == false )
XCTAssert( remoteUserData.ResistBandAccessible == false )
XCTAssert( remoteUserData.PoolAccessible == false )
XCTAssert( remoteUserData.Intensity == "Light" )
XCTAssert( remoteUserData.PushNotifications == false )
nullUserAsyncExpectation?.fulfill()
nullUserAsyncExpectation = nil
}
}
var emptyUserAsyncExpectation: XCTestExpectation? = expectation(description: "Get_UserInfo(\"Empty\") async block started")
DispatchQueue.main.async {
//Check reading an empty user returns as expected
Get_UserInfoFirestore.Get_UserInfo(targetUser: "Empty") { remoteUserData in
XCTAssert( remoteUserData.Status == "NO_DATA" )
XCTAssert( remoteUserData.UserName == "USERNAME_NIL" )
XCTAssert( remoteUserData.QuestionsAnswered == false )
XCTAssert( remoteUserData.WalkingDuration == -1 )
XCTAssert( remoteUserData.ChairAccessible == false )
XCTAssert( remoteUserData.WeightsAccessible == false )
XCTAssert( remoteUserData.ResistBandAccessible == false )
XCTAssert( remoteUserData.PoolAccessible == false )
XCTAssert( remoteUserData.Intensity == "INTENSITY_NIL" )
XCTAssert( remoteUserData.PushNotifications == false )
emptyUserAsyncExpectation?.fulfill()
emptyUserAsyncExpectation = nil
}
}
var testerUserAsyncExpectation: XCTestExpectation? = expectation(description: "Get_UserInfo(\"tester\") async block started")
DispatchQueue.main.async {
//Check reading a properly filled user returns as expected
Get_UserInfoFirestore.Get_UserInfo(targetUser: "tester") { remoteUserData in
//These values are pre-defined in the Firestore.
XCTAssert( remoteUserData.Status == "SUCCESS" )
XCTAssert( remoteUserData.UserName == "tester" )
XCTAssert( remoteUserData.QuestionsAnswered == true )
XCTAssert( remoteUserData.WalkingDuration == 30 )
XCTAssert( remoteUserData.ChairAccessible == true )
XCTAssert( remoteUserData.WeightsAccessible == true )
XCTAssert( remoteUserData.ResistBandAccessible == true )
XCTAssert( remoteUserData.PoolAccessible == true )
XCTAssert( remoteUserData.Intensity == "Intense" )
XCTAssert( remoteUserData.PushNotifications == true )
testerUserAsyncExpectation?.fulfill()
testerUserAsyncExpectation = nil
}
}
waitForExpectations(timeout: 2, handler: nil)
}
func test_Get_ExercisesData() {
//Initialize a new UserData class that only this method will interact with, along with a UserDataFirestore class using that Database
let Get_ExerciseDataDB = UserData(DatabaseIdentifier: "Get_ExerciseData")
let ExerciseDataFirestore = UserDataFirestore(sourceGiven: Get_ExerciseDataDB)
var nullUserAsyncExpectation: XCTestExpectation? = expectation(description: "Get_ExerciseData(\"nullUser\") async block started")
DispatchQueue.main.async {
ExerciseDataFirestore.Get_ExerciseData(targetUser: "nullUser") { remoteExerciseData in
XCTAssert( remoteExerciseData.first?.ExercisesDone.first == "NO_DOCUMENTS" )
nullUserAsyncExpectation?.fulfill()
nullUserAsyncExpectation = nil
}
}
var emptyAsyncExpectation: XCTestExpectation? = expectation(description: "Get_ExerciseData(\"Empty\") async block started")
DispatchQueue.main.async {
ExerciseDataFirestore.Get_ExerciseData(targetUser: "Empty") { remoteExerciseData in
//XCTAssert( remoteExerciseData[0].ExercisesDone[0] == "NO_DOCUMENTS" )
emptyAsyncExpectation?.fulfill()
emptyAsyncExpectation = nil
}
}
var testerAsyncExpectation: XCTestExpectation? = expectation(description: "Get_ExerciseData(\"tester\") async block started")
DispatchQueue.main.async {
ExerciseDataFirestore.Get_ExerciseData(targetUser: "tester") { remoteExerciseData in
XCTAssert( remoteExerciseData.count == 2 )
XCTAssert( remoteExerciseData[0].Year == 2018 )
XCTAssert( remoteExerciseData[0].Month == 10 )
XCTAssert( remoteExerciseData[0].Day == 31 )
XCTAssert( remoteExerciseData[0].Hour == 19 )
XCTAssert( remoteExerciseData[0].ExercisesDone == ["Quad Stretch", "Walking", "Single Leg Stance"] )
XCTAssert( remoteExerciseData[0].StepsTaken == 456 )
XCTAssert( remoteExerciseData[1].Year == 2019 )
XCTAssert( remoteExerciseData[1].Month == 11 )
XCTAssert( remoteExerciseData[1].Day == 16 )
XCTAssert( remoteExerciseData[1].Hour == 12 )
XCTAssert( remoteExerciseData[1].ExercisesDone == ["Walking", "Single Leg Stance", "Wall Push-up"] )
XCTAssert( remoteExerciseData[1].StepsTaken == 123)
testerAsyncExpectation?.fulfill()
testerAsyncExpectation = nil
}
}
waitForExpectations(timeout: 2, handler: nil)
}
func test_UserInfo() {
//Create a Firebase reference for use
let FirestoreRef = Firestore.firestore()
//Initialize a new UserData class that only this method will interact with, along with a UserDataFirestore class using that Database
let UserInfoDB = UserData(DatabaseIdentifier: "UserInfo")
let UserInfoFirestore = UserDataFirestore(sourceGiven: UserInfoDB)
//Create a UUID to use as a guaranteed user name
let currentUser = UUID().uuidString
//Create the User Info document reference
let userDocRef = FirestoreRef.collection("User").document(currentUser)
UserInfoDB.Update_User_Data(nameGiven: currentUser, questionsAnswered: true, walkingDuration: 10, chairAvailable: false, weightsAvailable: false, resistBandAvailable: false, poolAvailable: false, intensityDesired: "Moderate", pushNotificationsDesired: false, firestoreOK: true)
//Push the user to Firebase
UserInfoFirestore.Update_UserInfo()
//Wait 10 seconds for the push to finish
sleep(10)
//Make sure the push actually went through
let initialExpecation = expectation(description: "Initial User Info push")
userDocRef.getDocument() { (document, error) in
guard let document = document, document.exists else {
//The user did not exist.
return
}
let dataReturned = document.data()
//Grab the data, unwrap it.
let returnedUserName = dataReturned?["UserName"] as? String ?? "USERNAME_NIL"
let returnedQuestionsAnswered = dataReturned?["QuestionsAnswered"] as? Bool ?? false
let returnedWalkingDuration = dataReturned?["WalkingDuration"] as? Int ?? -1
let returnedChairAccessible = dataReturned?["ChairAccessible"] as? Bool ?? false
let returnedWeightsAccessible = dataReturned?["WeightsAccessible"] as? Bool ?? false
let returnedResistBandAccessible = dataReturned?["ResistBandAccessible"] as? Bool ?? false
let returnedPoolAccessible = dataReturned?["PoolAccessible"] as? Bool ?? false
let returnedIntensity = dataReturned?["Intensity"] as? String ?? "INTENSITY_NIL"
let returnedPushNotifications = dataReturned?["PushNotifications"] as? Bool ?? false
XCTAssert( returnedUserName == currentUser )
XCTAssert( returnedQuestionsAnswered == true )
XCTAssert( returnedWalkingDuration == 10 )
XCTAssert( returnedChairAccessible == false )
XCTAssert( returnedWeightsAccessible == false )
XCTAssert( returnedResistBandAccessible == false )
XCTAssert( returnedPoolAccessible == false )
XCTAssert( returnedIntensity == "Moderate" )
XCTAssert( returnedPushNotifications == false )
initialExpecation.fulfill()
}
wait(for: [initialExpecation], timeout: 10)
//Update the user info
UserInfoDB.Update_User_Data(nameGiven: nil, questionsAnswered: true, walkingDuration: 30, chairAvailable: true, weightsAvailable: true, resistBandAvailable: true, poolAvailable: true, intensityDesired: "Intense", pushNotificationsDesired: true, firestoreOK: true)
UserInfoFirestore.Update_UserInfo()
//Wait 10 seconds for the push to finish
sleep(10)
//make sure the update actually went through
let updateExpecation = expectation(description: "Update User Info push")
userDocRef.getDocument() { (document, error) in
guard let document = document, document.exists else {
//The user did not exist.
return
}
let dataReturned = document.data()
//Grab the data, unwrap it.
let returnedUserName = dataReturned?["UserName"] as? String ?? "USERNAME_NIL"
let returnedQuestionsAnswered = dataReturned?["QuestionsAnswered"] as? Bool ?? false
let returnedWalkingDuration = dataReturned?["WalkingDuration"] as? Int ?? -1
let returnedChairAccessible = dataReturned?["ChairAccessible"] as? Bool ?? false
let returnedWeightsAccessible = dataReturned?["WeightsAccessible"] as? Bool ?? false
let returnedResistBandAccessible = dataReturned?["ResistBandAccessible"] as? Bool ?? false
let returnedPoolAccessible = dataReturned?["PoolAccessible"] as? Bool ?? false
let returnedIntensity = dataReturned?["Intensity"] as? String ?? "INTENSITY_NIL"
let returnedPushNotifications = dataReturned?["PushNotifications"] as? Bool ?? false
XCTAssert( returnedUserName == currentUser )
XCTAssert( returnedQuestionsAnswered == true )
XCTAssert( returnedWalkingDuration == 30 )
XCTAssert( returnedChairAccessible == true )
XCTAssert( returnedWeightsAccessible == true )
XCTAssert( returnedResistBandAccessible == true )
XCTAssert( returnedPoolAccessible == true )
XCTAssert( returnedIntensity == "Intense" )
XCTAssert( returnedPushNotifications == true )
updateExpecation.fulfill()
}
wait(for: [updateExpecation], timeout: 10)
}
func test_Name_Check() {
//Instantiate the class for this test
let nameCheckFirestore = UserDataFirestore(sourceGiven: global_UserData)
//Check looking for a name in use returns false.
let falseExpectation = expectation(description: "False check")
nameCheckFirestore.Name_Available(nameToCheck: "tester") { returnVal in
XCTAssert( returnVal == false )
falseExpectation.fulfill()
}
//Check looking for a name not in use returns true.
let trueExpectation = expectation(description: "True check")
nameCheckFirestore.Name_Available(nameToCheck: "Mr. Non-existant") { returnVal in
XCTAssert( returnVal == true )
trueExpectation.fulfill()
}
wait(for: [falseExpectation, trueExpectation], timeout: 2)
}
}
|
//
// IParser.swift
// Parrot
//
// Created by Const. on 18.04.2020.
// Copyright © 2020 Oleginc. All rights reserved.
//
import Foundation
protocol IParser {
associatedtype Model
func parse(data: Data) -> Model?
}
|
///
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
///
///
/// Provides an empty default implementation of _org.antlr.v4.runtime.ANTLRErrorListener_. The
/// default implementation of each method does nothing, but can be overridden as
/// necessary.
///
/// - Sam Harwell
///
open class BaseErrorListener: ANTLRErrorListener {
public init() {
}
open func syntaxError<T>(_ recognizer: Recognizer<T>,
_ offendingSymbol: AnyObject?,
_ line: Int,
_ charPositionInLine: Int,
_ msg: String,
_ e: AnyObject?
) {
}
open func reportAmbiguity(_ recognizer: Parser,
_ dfa: DFA,
_ startIndex: Int,
_ stopIndex: Int,
_ exact: Bool,
_ ambigAlts: BitSet,
_ configs: ATNConfigSet) {
}
open func reportAttemptingFullContext(_ recognizer: Parser,
_ dfa: DFA,
_ startIndex: Int,
_ stopIndex: Int,
_ conflictingAlts: BitSet?,
_ configs: ATNConfigSet) {
}
open func reportContextSensitivity(_ recognizer: Parser,
_ dfa: DFA,
_ startIndex: Int,
_ stopIndex: Int,
_ prediction: Int,
_ configs: ATNConfigSet) {
}
}
|
//
// NewsArticleViewModel.swift
// SwiftUIINewsFeed
//
// Created by Saman Badakhshan on 10/11/2019.
// Copyright © 2019 Nonisoft. All rights reserved.
//
import Foundation
class NewsArticleViewModel: ObservableObject
{
@Published private(set) var title: String
@Published private(set) var subtitle: String
@Published private(set) var imageUrl: URL?
init(title: String, subtitle: String, imageUrl: URL?)
{
self.title = title
self.subtitle = subtitle
self.imageUrl = imageUrl
}
}
|
//
// VolumeViewController.swift
// NeCTARClient
//
// Created by XuMiao on 17/4/29.
// Copyright © 2017年 Xinrui Xu. All rights reserved.
//
import UIKit
import MBProgressHUD
class VolumeViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet var tableview: UITableView!
var refreshControl: UIRefreshControl!
var hudParentView = UIView()
var pickerSet: [String] = []
var serverId: [String] = []
var serverZone: [String] = []
// load data
func commonInit() {
if let user = UserService.sharedService.user{
pickerSet = []
serverId = []
NeCTAREngine.sharedEngine.listInstances(user.computeServiceURL, token: user.tokenID).then{ (json) -> Void in
let servers = json["servers"].arrayValue
InstanceService.sharedService.clear()
for server in servers {
let instance = Instance(json: server)
InstanceService.sharedService.instances.append(instance!)
self.pickerSet.append((instance?.name)!)
self.serverId.append((instance?.id)!)
self.serverZone.append((instance?.zone)!)
}
}.error{(err) -> Void in
var errorMessage:String = "Action Failed."
switch err {
case NeCTAREngineError.CommonError(let msg):
errorMessage = msg!
case NeCTAREngineError.ErrorStatusCode(let code):
if code == 401 {
loginRequired()
} else {
errorMessage = "Fail to get all instances."
}
default:
errorMessage = "Fail to get all instances."
}
PromptErrorMessage(errorMessage, viewController: self)
}
let url = user.volumeV3ServiceURL
let token = user.tokenID
NeCTAREngine.sharedEngine.listVolume(user.tenantID, url: url, token: token).then{ (json) -> Void in
let volumes = json["volumes"].arrayValue
VolumeService.sharedService.clear()
print(json)
print(volumes.count)
if volumes.count == 0 {
let msg = "There is no volume."
let alert = UIAlertController(title: "No Volume", message: msg, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { Void in
self.dismissViewControllerAnimated(false, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
MBProgressHUD.hideAllHUDsForView(self.hudParentView, animated: true)
} else {
for oneV in volumes {
let volume = Volume(json: oneV)
VolumeService.sharedService.volumes.append(volume!)
}
for (index, one) in VolumeService.sharedService.volumes.enumerate(){
if one.attachToId != "-" {
NeCTAREngine.sharedEngine.queryInstances(one.attachToId, url: user.computeServiceURL, token: token).then{(json2) -> Void in
let attachName = json2["server"]["name"].stringValue
print(index)
VolumeService.sharedService.volumes[index].attachToName = attachName
//index += 1
}.error{(err) -> Void in
var errorMessage:String = "Action Failed."
switch err {
case NeCTAREngineError.CommonError(let msg):
errorMessage = msg!
case NeCTAREngineError.ErrorStatusCode(let code):
if code == 401 {
loginRequired()
} else {
errorMessage = "Fail to get all the volume detail"
}
default:
errorMessage = "Fail to get all the volume detail"
}
PromptErrorMessage(errorMessage, viewController: self)
}
}
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1.5 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
//index += 1
//print(index)
self.tableview.reloadData()
self.refreshControl.endRefreshing()
MBProgressHUD.hideHUDForView(self.hudParentView, animated: true)
print(self.pickerSet)
}
}
//print(VolumeService.sharedService.volumes)
}
}.error{(err) -> Void in
var errorMessage:String = "Action Failed."
switch err {
case NeCTAREngineError.CommonError(let msg):
errorMessage = msg!
case NeCTAREngineError.ErrorStatusCode(let code):
if code == 401 {
loginRequired()
} else {
errorMessage = "Fail to get all volumes."
}
default:
errorMessage = "Fail to get all volumes."
}
PromptErrorMessage(errorMessage, viewController: self)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
hudParentView = self.view
MBProgressHUD.showHUDAddedTo(hudParentView, animated: true)
refreshControl = UIRefreshControl()
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl.addTarget(self, action: #selector(SecurityViewController.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
tableview.addSubview(refreshControl)
commonInit()
self.tableview.contentInset = UIEdgeInsetsMake(0, 0, 60, 0)
}
func refresh(sender:AnyObject) {
// Code to refresh table view
commonInit()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return VolumeService.sharedService.volumes.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if VolumeService.sharedService.volumes.count != 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("VolumeDetail") as! VolumeDetailCell
cell.setContent(indexPath.row)
return cell
}
return UITableViewCell()
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]?
{
let action = UITableViewRowAction(style: .Normal, title: "Actions") {
action, index in
let alertController = UIAlertController(title: "Actions", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
let deleteAction = UIAlertAction(title: "Delete", style: UIAlertActionStyle.Destructive, handler: {action in self.deleteVolume(indexPath.row)})
let attachAction = UIAlertAction(title: "Attach To", style: UIAlertActionStyle.Default, handler: {action in self.attach(indexPath.row)})
let detachAction = UIAlertAction(title: "Detach", style: UIAlertActionStyle.Default, handler: {action in self.detach(indexPath.row)})
let snapshotAction = UIAlertAction(title: "Create Snapshot", style: UIAlertActionStyle.Default, handler: {action in self.createSnapshot(indexPath.row)})
let editAction = UIAlertAction(title: "Edit", style: UIAlertActionStyle.Default, handler: {action in self.edit(indexPath.row)})
let extendAction = UIAlertAction(title: "Extend", style: UIAlertActionStyle.Default, handler: {action in self.extend(indexPath.row)})
alertController.addAction(cancelAction)
if VolumeService.sharedService.volumes[indexPath.row].status == "in-use" {
alertController.addAction(detachAction)
alertController.addAction(snapshotAction)
alertController.addAction(editAction)
} else if VolumeService.sharedService.volumes[indexPath.row].status == "available" {
alertController.addAction(deleteAction)
alertController.addAction(attachAction)
alertController.addAction(extendAction)
alertController.addAction(snapshotAction)
alertController.addAction(editAction)
}
self.presentViewController(alertController, animated: true, completion: nil)
}
action.backgroundColor = UIColor.blueColor()
return [action]
}
func deleteVolume(index: Int){
let alertController = UIAlertController(title: "Confirm Delete volume", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: {
(action: UIAlertAction!) -> Void in
self.dismissViewControllerAnimated(false, completion: nil)
})
let okAction = UIAlertAction(title: "Delete", style: UIAlertActionStyle.Destructive, handler: {
(action: UIAlertAction!) -> Void in
if let user = UserService.sharedService.user {
MBProgressHUD.showHUDAddedTo(self.hudParentView, animated: true)
let url = user.volumeV3ServiceURL
let volumeId = VolumeService.sharedService.volumes[index].id
print(user.owner)
print("delete")
NeCTAREngine.sharedEngine.deleteVolume(user.tenantID, volumeId: volumeId, url: url, token: user.tokenID).then {
(json) -> Void in
print("delete")
print (json)
let msg = "Please refresh."
let alert = UIAlertController(title: "Delete Success", message: msg, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { Void in
self.dismissViewControllerAnimated(false, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}.always{
MBProgressHUD.hideHUDForView(self.hudParentView, animated: true)
}.error{ (err) -> Void in
print(err)
var errorMessage:String = "Action Failed."
switch err {
case NeCTAREngineError.CommonError(let msg):
errorMessage = msg!
case NeCTAREngineError.ErrorStatusCode(let code):
if code == 401 {
loginRequired()
} else {
errorMessage = "Action failed."
}
default:
errorMessage = "Action failed."
}
PromptErrorMessage(errorMessage, viewController: self)
}
}
})
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 }
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerSet.count }
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerSet[row] }
func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView
{
let pickerLabel = UILabel()
pickerLabel.textColor = UIColor.blackColor()
pickerLabel.text = self.pickerSet[row]
// pickerLabel.font = UIFont(name: pickerLabel.font.fontName, size: 15)
pickerLabel.font = UIFont(name: pickerLabel.font.fontName, size: 15) // In this use your custom font
pickerLabel.textAlignment = NSTextAlignment.Center
return pickerLabel
}
func doSomethingWithValue(index: Int, serverId: String, serverZone: String) {
print(serverId)
print(serverZone)
if serverZone != VolumeService.sharedService.volumes[index].zone {
PromptErrorMessage("Unable to attach volume. Inconsistent Availability Zone.", viewController: self)
} else {
if let user = UserService.sharedService.user{
MBProgressHUD.showHUDAddedTo(self.hudParentView, animated: true)
NeCTAREngine.sharedEngine.attachVolume(VolumeService.sharedService.volumes[index].id, instanceId: serverId, url: user.computeServiceURL, token: user.tokenID).then {
(json) -> Void in
print("delete")
print (json)
let msg = "Please refresh."
let alert = UIAlertController(title: "Attach Success", message: msg, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { Void in
self.dismissViewControllerAnimated(false, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}.always{
MBProgressHUD.hideHUDForView(self.hudParentView, animated: true)
}.error{ (err) -> Void in
print(err)
var errorMessage:String = "Action Failed."
switch err {
case NeCTAREngineError.CommonError(let msg):
errorMessage = msg!
case NeCTAREngineError.ErrorStatusCode(let code):
if code == 401 {
loginRequired()
} else {
errorMessage = "Action failed."
}
default:
errorMessage = "Action failed."
}
PromptErrorMessage(errorMessage, viewController: self)
}
}
}
}
func attach(index: Int){
if pickerSet.isEmpty {
let msg = "There is no instance."
let alert = UIAlertController(title: "No Instance", message: msg, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { Void in
self.dismissViewControllerAnimated(false, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
} else {
let message = "\n\n\n\n\n\n\n\n"
let alert = UIAlertController(title: "", message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.modalInPopover = true
let attributedString = NSAttributedString(string: "Please select a instance", attributes: [
NSFontAttributeName : UIFont.systemFontOfSize(20), //your font here,
NSForegroundColorAttributeName : UIColor(red:0.29, green:0.45, blue:0.74, alpha:1.0) ])
alert.setValue(attributedString, forKey: "attributedTitle")
//Create a frame (placeholder/wrapper) for the picker and then create the picker
let pickerFrame: CGRect = CGRectMake(35, 52, 200, 140) // CGRectMake(left, top, width, height) - left and top are like margins
let picker: UIPickerView = UIPickerView(frame: pickerFrame)
//picker.backgroundColor = UIColor(red:0.29, green:0.45, blue:0.74, alpha:1.0)
//set the pickers datasource and delegate
picker.delegate = self
picker.dataSource = self
//Add the picker to the alert controller
alert.view.addSubview(picker)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alert.addAction(cancelAction)
let okAction = UIAlertAction(title: "Attach", style: .Default, handler: {
(alert: UIAlertAction!) -> Void in self.doSomethingWithValue(index, serverId: self.serverId[picker.selectedRowInComponent(0)], serverZone: self.serverZone[picker.selectedRowInComponent(0)]) })
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
}
}
func detach(index: Int){
let alertController = UIAlertController(title: "Confirm Detach volume", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: {
(action: UIAlertAction!) -> Void in
self.dismissViewControllerAnimated(false, completion: nil)
})
let okAction = UIAlertAction(title: "Detach", style: UIAlertActionStyle.Default, handler: {
(action: UIAlertAction!) -> Void in
if let user = UserService.sharedService.user {
let url = user.computeServiceURL
let volumeId = VolumeService.sharedService.volumes[index].id
MBProgressHUD.showHUDAddedTo(self.hudParentView, animated: true)
print("detach")
NeCTAREngine.sharedEngine.deleteAttachment(VolumeService.sharedService.volumes[index].attachToId, volumeId: volumeId, url: url, token: user.tokenID).then {
(json) -> Void in
print("detach")
print (json)
let msg = "Please refresh."
let alert = UIAlertController(title: "Detach Success", message: msg, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { Void in
self.dismissViewControllerAnimated(false, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}.always{
MBProgressHUD.hideHUDForView(self.hudParentView, animated: true)
}.error{ (err) -> Void in
print(err)
var errorMessage:String = "Action Failed."
switch err {
case NeCTAREngineError.CommonError(let msg):
errorMessage = msg!
case NeCTAREngineError.ErrorStatusCode(let code):
if code == 401 {
loginRequired()
} else {
errorMessage = "Action failed."
}
default:
errorMessage = "Action failed."
}
PromptErrorMessage(errorMessage, viewController: self)
}
}
})
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
func createSnapshot(index: Int){
let alertController = UIAlertController(title: "Create Volume Snapshot", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addTextFieldWithConfigurationHandler {
(textField: UITextField) -> Void in
textField.placeholder = "Snapshot Name"
}
alertController.addTextFieldWithConfigurationHandler {
(textField: UITextField) -> Void in
textField.placeholder = "Description"
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: {
(action: UIAlertAction!) -> Void in
self.dismissViewControllerAnimated(false, completion: nil)
})
let okAction = UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler: {
(action: UIAlertAction!) -> Void in
let nameField = (alertController.textFields?.first)! as UITextField
let descritptionField = (alertController.textFields?.last)! as UITextField
let name = nameField.text
let descritption = descritptionField.text
let whitespace = NSCharacterSet.whitespaceAndNewlineCharacterSet()
if let user = UserService.sharedService.user{
if name!.stringByTrimmingCharactersInSet(whitespace).isEmpty {
PromptErrorMessage("Snapshot name is invalid.", viewController: self)
} else {
MBProgressHUD.showHUDAddedTo(self.hudParentView, animated: true)
NeCTAREngine.sharedEngine.createVolumeSnapshot(VolumeService.sharedService.volumes[index].id, projectId: user.tenantID, description: descritption!, url: user.volumeV3ServiceURL, name: name!, token: user.tokenID).then{
(json) -> Void in
print("create snapshot")
let msg = "Please refresh."
let alert = UIAlertController(title: "Create Success", message: msg, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { Void in
self.dismissViewControllerAnimated(false, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}.always{
MBProgressHUD.hideHUDForView(self.hudParentView, animated: true)
}.error {
(err) -> Void in
print(err)
var errorMessage:String = "Action Failed."
switch err {
case NeCTAREngineError.CommonError(let msg):
errorMessage = msg!
default:
errorMessage = "Fail to create the snapshot."
}
PromptErrorMessage(errorMessage, viewController: self)
}
}
}
})
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
func edit(index: Int){
print("edit")
let alertController = UIAlertController(title: "Edit Volume", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addTextFieldWithConfigurationHandler {
(textField: UITextField) -> Void in
textField.placeholder = "Volume Name"
textField.text = VolumeService.sharedService.volumes[index].name
}
alertController.addTextFieldWithConfigurationHandler {
(textField: UITextField) -> Void in
textField.placeholder = "Description"
textField.text = VolumeService.sharedService.volumes[index].description
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: {
(action: UIAlertAction!) -> Void in
self.dismissViewControllerAnimated(false, completion: nil)
})
let okAction = UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler: {
(action: UIAlertAction!) -> Void in
let nameField = (alertController.textFields?.first)! as UITextField
let descritptionField = (alertController.textFields?.last)! as UITextField
let name = nameField.text
let descritption = descritptionField.text
let whitespace = NSCharacterSet.whitespaceAndNewlineCharacterSet()
if let user = UserService.sharedService.user{
if name!.stringByTrimmingCharactersInSet(whitespace).isEmpty {
PromptErrorMessage("Volume name is invalid.", viewController: self)
} else {
MBProgressHUD.showHUDAddedTo(self.hudParentView, animated: true)
NeCTAREngine.sharedEngine.updateVolume(user.tenantID, volumeId: VolumeService.sharedService.volumes[index].id, name: name!, description: descritption!, url: user.volumeV3ServiceURL, token: user.tokenID).then{
(json) -> Void in
print("edit volume")
let msg = "Please refresh."
let alert = UIAlertController(title: "Edit Success", message: msg, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { Void in
self.dismissViewControllerAnimated(false, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}.always{
MBProgressHUD.hideHUDForView(self.hudParentView, animated: true)
}.error {
(err) -> Void in
print(err)
var errorMessage:String = "Action Failed."
switch err {
case NeCTAREngineError.CommonError(let msg):
errorMessage = msg!
default:
errorMessage = "Fail to edit the volume."
}
PromptErrorMessage(errorMessage, viewController: self)
}
}
}
})
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
func extend(index: Int){
print("extend")
let alertController = UIAlertController(title: "Extend Volume", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addTextFieldWithConfigurationHandler {
(textField: UITextField) -> Void in
textField.placeholder = "Volume Name"
textField.text = VolumeService.sharedService.volumes[index].name
textField.enabled = false
}
alertController.addTextFieldWithConfigurationHandler {
(textField: UITextField) -> Void in
textField.placeholder = "Current Size (GB)"
textField.text = VolumeService.sharedService.volumes[index].size
textField.enabled = false
}
alertController.addTextFieldWithConfigurationHandler {
(textField: UITextField) -> Void in
textField.placeholder = "New Size (GB)"
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: {
(action: UIAlertAction!) -> Void in
self.dismissViewControllerAnimated(false, completion: nil)
})
let okAction = UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler: {
(action: UIAlertAction!) -> Void in
let sizeField = (alertController.textFields?.last)! as UITextField
let size = sizeField.text
let whitespace = NSCharacterSet.whitespaceAndNewlineCharacterSet()
if let user = UserService.sharedService.user{
if size!.stringByTrimmingCharactersInSet(whitespace).isEmpty {
PromptErrorMessage("New size is invalid.", viewController: self)
} else {
MBProgressHUD.showHUDAddedTo(self.hudParentView, animated: true)
NeCTAREngine.sharedEngine.extendVolume(user.tenantID, volumeId: VolumeService.sharedService.volumes[index].id, size: Int(size!)!, url: user.volumeV3ServiceURL, token: user.tokenID).then{
(json) -> Void in
print("extend volume")
let msg = "Please refresh."
let alert = UIAlertController(title: "Extend Success", message: msg, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { Void in
self.dismissViewControllerAnimated(false, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}.always{
MBProgressHUD.hideHUDForView(self.hudParentView, animated: true)
}.error {
(err) -> Void in
print(err)
var errorMessage:String = "Action Failed."
switch err {
case NeCTAREngineError.CommonError(let msg):
errorMessage = msg!
default:
errorMessage = "Fail to extend the volume."
}
PromptErrorMessage(errorMessage, viewController: self)
}
}
}
})
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowVolumeDetail" {
let cell = sender as! VolumeDetailCell
let path = self.tableview.indexPathForCell(cell)
let detailVC = segue.destinationViewController as! VolumeDetailViewController
detailVC.navigationItem.title = "Volume Detail"
detailVC.volume = VolumeService.sharedService.volumes[(path?.row)!]
detailVC.index = path?.row
}
}
}
|
//
// MovieTableViewController.swift
// MovieList
//
// Created by Rohan Taylor on 12/13/19.
// Copyright © 2019 Rohan Taylor. All rights reserved.
//
import UIKit
class MovieTableViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var movies: [Movie] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
}
// 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?) {
if segue.identifier == "AddMovieSegue" {
if let destinationVC = segue.destination as? MovieViewController {
destinationVC.delegate = self
}
}
}
}
extension MovieTableViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movies.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "MovieCell", for: indexPath) as? MovieTableViewCell else {
fatalError()
}
let movie = movies[indexPath.row]
cell.movie = movie
return cell
}
}
extension MovieTableViewController : MovieDelegate {
func newMovie(movie: Movie) {
movies.append(movie)
tableView.reloadData()
}
}
|
//
// Log+NodeLogDestination.swift
// Alicerce
//
// Created by Meik Schutz on 07/04/2017.
// Copyright © 2017 Mindera. All rights reserved.
//
import Foundation
public extension Log {
public class NodeLogDestination : LogDestination, LogDestinationFallible {
public enum Error: Swift.Error {
case httpError(statusCode: Int)
case network(Swift.Error)
}
public let queue: Queue
public let minLevel: Level
public let formatter: LogItemFormatter
public private(set) var writtenItems: Int = 0
public var errorClosure: ((LogDestination, Item, Swift.Error) -> ())?
private let serverURL: URL
private let urlSession: URLSession
private let requestTimeout: TimeInterval
//MARK:- lifecycle
public init(serverURL: URL,
minLevel: Level = .error,
formatter: LogItemFormatter = StringLogItemFormatter(),
urlSession: URLSession = URLSession.shared,
queue: Queue = Queue(label: "com.mindera.alicerce.log.destination.node"),
requestTimeout: TimeInterval = 60) {
self.serverURL = serverURL
self.minLevel = minLevel
self.formatter = formatter
self.urlSession = urlSession
self.queue = queue
self.requestTimeout = requestTimeout
}
//MARK:- public methods
public func write(item: Item) {
queue.dispatchQueue.async { [weak self] in
guard let strongSelf = self else { return }
let formattedItem = strongSelf.formatter.format(logItem: item)
if let payloadData = formattedItem.data(using: .utf8) {
strongSelf.send(payload: payloadData) { error in
guard let error = error else {
strongSelf.writtenItems += 1
return
}
strongSelf.errorClosure?(strongSelf, item, error)
}
}
}
}
//MARK:- private methods
private func send(payload: Data, completion: @escaping (_ error: Swift.Error?) -> Void) {
var request = URLRequest(url: serverURL,
cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: requestTimeout)
// setup the request's method and headers
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
// setup the request's body
request.httpBody = payload
// send request async to server on destination queue
let task = urlSession.dataTask(with: request) { _, response, error in
if let error = error {
print("Error sending log item to the server \(self.serverURL) with error \(error.localizedDescription)")
completion(Error.network(error))
}
else {
guard let response = response as? HTTPURLResponse else { return }
switch HTTP.StatusCode(response.statusCode) {
case .success:
break
default:
print("Error sending log item to the server \(self.serverURL) with HTTP status \(response.statusCode)")
completion(Error.httpError(statusCode: response.statusCode))
}
}
}
task.resume()
}
}
}
|
//
// AlarmNotificationViewController.swift
// AppleAlarm
//
// Created by Gabriel Mara Isserlis on 1/31/16.
// Copyright © 2016 Antar Vasi, Alexander McLean, Gabriel Isserlis. All rights reserved.
//
import UIKit
class AlarmNotificationViewController: UIViewController {
@IBOutlet weak var ImageGIF: UIImageView!
@IBAction func dismiss(sender: UIButton) {
self.dismissViewControllerAnimated(true, completion: nil)
//let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
//appDelegate?.window?.rootViewController = ListViewController()
}
}
|
//
// ResultsCareTaker.swift
// Quiz
//
// Created by NIKOLAI BORISOV on 06.08.2021.
//
import Foundation
final class ResultsCareTaker {
enum Keys: String {
case result = "result"
}
static let encoder = JSONEncoder()
static let decoder = JSONDecoder()
static func save(results: [Result]) {
do {
let data = try self.encoder.encode(results)
UserDefaults.standard.setValue(data, forKey: Keys.result.rawValue)
} catch {
print(error)
}
}
static func retrieveResults() -> [Result] {
guard let data = UserDefaults.standard.data(forKey: Keys.result.rawValue) else {
return []
}
do {
return try self.decoder.decode([Result].self, from: data)
} catch {
print(error)
return []
}
}
static func delete(row: Int) {
guard var data = UserDefaults.standard.data(forKey: Keys.result.rawValue) else { return }
data.remove(at: row)
}
}
|
//
// Constants.swift
// TeamworkTest
//
// Created by Oscar Alvarez on 30/7/17.
// Copyright © 2017 Oscar Alvarez. All rights reserved.
//
import UIKit
enum AwesomeFontSize {
static let small: CGFloat = 15
static let medium: CGFloat = 20
static let big: CGFloat = 30
}
enum Card {
static let cornerRadius: CGFloat = 6
}
enum Storyboard {
static let main: String = "Main"
}
enum Teamwork {
static let projectsKey: String = "projects"
static let tastksKey: String = "todo-items"
static let baseUrl: String = "https://yat.teamwork.com" //For this demo we use a given user's site
static let projectsUrl: String = "https://yat.teamwork.com/projects"
}
enum ErrorMessage {
static let unknown: String = "Unknown Error"
}
enum TaskPriority {
static let high: String = "high"
static let medium: String = "medium"
static let low: String = "low"
}
enum ProjectsTitle {
static let loading: String = "Loading Projects..."
static let projects: String = "Yat's Projects"
}
enum DetailsTitle {
static let loading: String = "Loading Tasks..."
static let projects: String = "Yat's Projects"
}
enum ImageName {
static let placeholer: String = "placeholer"
}
enum Identifier {
static let projectCell: String = "ProjectCell"
static let detailsController: String = "DetailsViewController"
static let taskCell: String = "TaskCell"
}
enum Responsable {
static let anyone: String = "Anyone"
}
enum TaskKey {
static let content: String = "content"
static let responsibleSum: String = "responsible-party-summary"
static let priority: String = "priority"
static let following: String = "userFollowingChanges"
static let startDate: String = "start-date"
static let dueDate: String = "due-date"
}
enum ProjectKey {
static let name: String = "name"
static let description: String = "description"
static let status: String = "status"
static let subStatus: String = "subStatus"
static let logo: String = "logo"
static let id: String = "id"
static let starred: String = "starred"
static let tags: String = "tags"
static let lastChanged: String = "last-changed-on"
static let created: String = "created-on"
static let company: String = "company"
}
enum CompanyKey {
static let name: String = "name"
static let id: String = "id"
static let owner: String = "is-owner"
}
|
//
// MuseumsArray.swift
// Just Maps
//
// Created by Robert Blundell on 11/12/2017.
// Copyright © 2017 Robert Blundell. All rights reserved.
//
import Foundation
var Museums: [Place] = [britishMuseum, nationalGallery, victoriaAndAlbertMuseum, naturalHistoryMuseum, cabinetWarRooms, tateGallery, HMSBelfast, londonMuseum, madamTussauds]
private var britishMuseum = Place(latitude: 51.519369,
longitude: -0.126988,
title: "British Museum",
placeDescription: "Showcase of antiquities from all over the globe",
longPlaceDescription: """
💵 Free
🕒 Every day 10:00 to 17:30. Fri 10:00 to 20:30
The British Museum is dedicated to global human history, art and culture. It's huge collection of over 8 million curiosities originate from all over the world, and many of the artefacts in the museum are there as a consequence of British colonization.
Some of the artefacts you can visit are the egyptian Mummy of Katebet, the Rosetta Stone, the huge Assyrian winged bulls from Khorsabad, greek parthenon sculptures and so much more.
""",
placeType: .museum,
placeImage: #imageLiteral(resourceName: "placeholder"))
private var nationalGallery = Place(latitude: 51.508675,
longitude: -0.128302,
title: "National Gallery",
placeDescription: "Wide ranging western art collection, from 'Giotto' to Cézanne",
longPlaceDescription: """
💵 Free
🕒 Every day 10:00 to 18:00. Fri 10 am to 9pm
The National Gallery displays some 2300 Western European paintings dating from the Middle Ages to the 20th century. The museum displays a vast extent of works by both British aritists such as Gainsborough, Constable and Turner as well as by other western artists like Botticelli, Leonardo da Vinci, Rembrandt, Renoir and Van Gogh.
""",
placeType: .museum,
placeImage: #imageLiteral(resourceName: "placeholder"))
private var victoriaAndAlbertMuseum = Place(latitude: 51.496601,
longitude: -0.172096,
title: "Victoria and Alberts Museum",
placeDescription: "World's largest museum of decorative arts and and design",
longPlaceDescription: """
💵 Free
🕒 Every day 10:00 to 17:45. Fri 10:00 to 22:00
Founded in 1852, the V&A is part of Prince Albert's legacy and is named after himself and Queen Victoria. The numerous galleries show off textiles, ceramics, statues from the 8th century up until WW1.
The different galleries are mostly themed by cultures and include japan, the Islamic Middle East, Medieval and renaissance, britain, jewellery and photography.
""",
placeType: .museum,
placeImage: #imageLiteral(resourceName: "placeholder"))
private var naturalHistoryMuseum = Place(latitude: 51.496236,
longitude: -0.176453,
title: "Natural History Museum",
placeDescription: "Animals, natural phenomena, hands-on exhibits and animatronic dinosaurs",
longPlaceDescription: """
💵 Free
🕒 Every day 10:00 to 17:30
The building delivers a cathedral-like sense of grandeur, and the exhibits themselves have set the standard for natural history displays for centuries.
The various galleries portray skeletons, animatronics and casts of Mammals, Dinosaurs and insects. The Darwin centre holds millions of species and explains the research done by the museum. The earth galleries show off minerals, moon rocks and has an earthquake simulator. A recent addition to the collection is Sophie, the best preserved stegasaurous fossil in the world.
""",
placeType: .museum,
placeImage: #imageLiteral(resourceName: "placeholder"))
private var cabinetWarRooms = Place(latitude: 51.502224,
longitude: -0.129308,
title: "Churchill war rooms",
placeDescription: "Museum about the leadership in WW2",
longPlaceDescription: """
💵 £19 adults, £9.50 under 15
🕒 Every day 9:30 to 18:00
The museum comprises the Cabinet War Rooms, a historic underground complex that housed a British government command centre throughout the Second World War, and the Churchill Museum, a biographical museum exploring the life and accomplishements of British statesman Winston Churchill.
Construction of the Cabinet War Rooms began in 1938 and they became operational in August 1939, shortly before the outbreak of war in Europe. They remained in operation throughout the Second World War, before being abandoned in August 1945 after the surrender of Japan.
""",
placeType: .museum,
placeImage: #imageLiteral(resourceName: "Cabinet war rooms"))
private var tateGallery = Place(latitude: 51.507612,
longitude: -0.099394,
title: "Modern Art Tate Gallery",
placeDescription: "Modern and contemporary art museum.",
longPlaceDescription: """
💵 Free
🕒 Sun to Thu 10:00 to 18:00. Fri & Sat 10:00 to 22:00
Tate is is a network of four art museums displaying the United Kingdom's national collection of British art, and international modern and contemporary art. The wildly popular tate modern is a vigorous statement of modernity and accessibility.
""",
placeType: .museum,
placeImage: #imageLiteral(resourceName: "Tate modern"))
private var HMSBelfast = Place(latitude: 51.506557,
longitude: -0.081348,
title: "HMS Belfast",
placeDescription: "A museum ship dating from WW2.",
longPlaceDescription: """
💵 £18 adults, £8 under 15s
🕒 Every day 10:00 to 17:00
HMS Belfast is a museum ship permanently moored on the River Thames in London. Originally a light cruiser built for the Royal Navy, the HMS Belfast served during world war II, helped sink German battleship Sharnhorst, shelled the Normandy coast on D-day and later participated in the korean war.
""",
placeType: .museum,
placeImage:#imageLiteral(resourceName: "HMS belfast"))
private var londonMuseum = Place(latitude: 51.517581,
longitude: -0.096884,
title: "Museum of London",
placeDescription: "This Museum illustrates the rich history of London.",
longPlaceDescription: """
💵 Free
🕒 Every day 10:00 to 18:00
The Museum of London retraces the history of London from 450,000 BC to the Romans to present day London. It hosts the largest urban history collection in the world. The building is part of the striking brutalist Barbican complex, built after the war over bomb-damaged London.
""",
placeType: .museum,
placeImage: #imageLiteral(resourceName: "London Museum"))
private var madamTussauds = Place(latitude: 51.522783,
longitude: -0.154907,
title: "Madam Tussauds",
placeDescription: "Wax figures of famous people",
longPlaceDescription: """
💵 £35 adults, £30 under 15 (save £6 by booking online)
🕒 Mon to Fri 10:00 to 16:00, Sat & Sun 9:00 to 16:00
⚠️ To avoid queues, guarantee entry and save money on the ticket it is best to book online. The venue is commercial and you will have spending opportunities in every room.
Madame Tussauds displays a wide array of life-like wax figures of world leaders, athletes, A-list movie-stars and celebrities.
The museum itself has an interesting origin story, being founded by Marie Tussaud who made death masks of people guillotined during the French revolution. She arrived in London in 1803 to display 30 wax figures of celebrities near Baker street, a true novelty in a time before photography existed. The London museum opened it's doors in 1835, and the madam tussauds brand now has 26 locations around the globe.
""",
placeType: .museum,
placeImage: #imageLiteral(resourceName: "placeholder"))
|
//
// Appearance.swift
// FoodPinApp
//
// Created by zombietux on 06/03/2019.
// Copyright © 2019 zombietux. All rights reserved.
//
import UIKit
struct Appearance {
static func setGlobalAppearance() {
UINavigationBar.appearance().backgroundColor = UIColor(red: 255.0 / 255.0, green: 205.0 / 255.0, blue: 0.0, alpha: 1.0)
UITabBar.appearance().barTintColor = UIColor(red: 255.0 / 255.0, green: 205.0 / 255.0, blue: 0.0, alpha: 1.0)
UINavigationBar.appearance().tintColor = UIColor(red: 231.0/255.0, green: 76.0/255.0, blue: 60.0/255.0, alpha: 1.0)
}
}
|
import UIKit
import ThemeKit
struct SwapSelectProviderModule {
static func viewController(dexManager: ISwapDexManager) -> UIViewController {
let service = SwapSelectProviderService(dexManager: dexManager, evmBlockchainManager: App.shared.evmBlockchainManager)
let viewModel = SwapSelectProviderViewModel(service: service)
return SwapSelectProviderViewController(viewModel: viewModel)
}
}
|
//
// ViewControllerViewModel.swift
// Cars
//
// Created by Suhas on 9/25/17.
// Copyright © 2017 Suhas. All rights reserved.
//
import Foundation
import UIKit
/*ViewController view model*/
class ViewControllerViewModel: NSObject {
var items = [Any]()
weak var carDelegate: carInfoCellDelegate?
func refreshWith(data: Array<Any>, _ completionBlock : @escaping ()->()) {
self.items = data
completionBlock()
}
}
extension ViewControllerViewModel: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = items[indexPath.row]
if let cell = tableView.dequeueReusableCell(withIdentifier: carInfoCell.identifier, for: indexPath) as? carInfoCell {
cell.item = item as? CarInfoViewModel
cell.carDelegate = self
return cell
}
return UITableViewCell()
}
}
extension ViewControllerViewModel : carInfoCellDelegate{
func showOnMap(cell:carInfoCell){
self.carDelegate?.showOnMap(cell: cell)
}
}
/* Cell view model */
class CarInfoViewModel: NSObject {
var modelName: String?
var name: String?
var make: String?
var fuelType: String?
var fuelLevel: String?
var licensePlate: String?
var latitude: Double
var longitude: Double
var imageURL: String?
init?(data: Car) { //Can add any thing extra which is needed for UI population like - section titles etc.
self.make = data.make
self.modelName = data.modelName
self.name = data.name
self.fuelType = data.fuelType
self.licensePlate = data.licensePlate
self.fuelLevel = String(format:"%f", data.fuelLevel)
self.imageURL = data.imageUrl
self.latitude = data.latitude
self.longitude = data.longitude
}
}
|
import UIKit
struct TransactionResponseViewData {
var section : [TransactionResponseViewDataSection]
}
struct TransactionResponseViewDataSection {
var title : String
var item : [TransactionResponseViewDataItem]
}
struct TransactionResponseViewDataItem {
var refID : String = ""
var cellID : String = ""
var title : String?
var detail : String?
var icon : UIImage?
var accessory : UITableViewCellAccessoryType = .none
var sizing : Sizing = .default
enum Sizing {
case auto, fixed, `default`
var tableRowHeight: CGFloat {
switch (self) {
case .auto: return UITableViewAutomaticDimension
case .fixed: return 36.0
case .default: return 55.0
}
}
}
}
extension TransactionResponseViewDataItem : ViewDataItem {}
extension TransactionResponseViewData : Equatable {}
func == (lhs: TransactionResponseViewData, rhs: TransactionResponseViewData) -> Bool {
return (lhs.section == rhs.section)
}
extension TransactionResponseViewDataSection : Equatable {}
func == (lhs: TransactionResponseViewDataSection, rhs: TransactionResponseViewDataSection) -> Bool {
return (lhs.title == rhs.title
&& lhs.item == rhs.item)
}
extension TransactionResponseViewDataItem : Equatable {}
func == (lhs: TransactionResponseViewDataItem, rhs: TransactionResponseViewDataItem) -> Bool {
return (lhs.refID == rhs.refID
&& lhs.cellID == rhs.cellID
&& lhs.title == rhs.title
&& lhs.detail == rhs.detail)
}
protocol TransactionResponseViewDataItemConfigurable : class {
func configure(transactionResponseViewDataItem item: TransactionResponseViewDataItem)
}
|
//
// Page.swift
// Programmatic Contraints Testing
//
// Created by macbook on 7/13/20.
// Copyright © 2020 WilmaRodriguez. All rights reserved.
//
import Foundation
struct Page {
let imageName: String
let headerText: String
}
|
//
// DayTwelve2021.swift
// AdventOfCode
//
// Created by Shawn Veader on 12/12/21.
//
import Foundation
struct DayTwelve2021: AdventDay {
var year = 2021
var dayNumber = 12
var dayTitle = "Passage Pathing"
var stars = 2
func parse(_ input: String?) -> [CavePath] {
(input ?? "").split(separator: "\n").map(String.init).compactMap { CavePath($0) }
}
func partOne(input: String?) -> Any {
let map = CaveMap(paths: parse(input))
let paths = map.findAllPaths()
paths.sorted(by: { $0.count < $1.count }).forEach { path in
print(path.joined(separator: ","))
}
return paths.count
}
func partTwo(input: String?) -> Any {
let map = CaveMap(paths: parse(input))
let paths = map.findAllPaths(allowDoubleSmall: true)
// paths.sorted(by: { $0.count < $1.count }).forEach { path in
// print(path.joined(separator: ","))
// }
return paths.count
}
}
|
//
// ChequImageView.swift
// Deposits
//
// Created by Sayooj Krishnan on 18/07/21.
//
import UIKit
protocol ChequImageViewDelegate : AnyObject {
func didRequestToOpenCamera(for chequeSide: ChequeSide)
}
class ChequImageView : UIView {
var chequeSide : ChequeSide? {
didSet {
chequePostionLabel.text = chequeSide?.description
}
}
private var dummyImage : UIImage {
let sizeConf = UIImage.SymbolConfiguration(pointSize: 340)
return UIImage(systemName: "camera",withConfiguration: sizeConf)!
}
var chequeImage : UIImage? {
didSet {
updateImage()
}
}
weak var delegate : ChequImageViewDelegate?
let chequeImageView : UIImageView = {
let chequeImageView = UIImageView()
chequeImageView.translatesAutoresizingMaskIntoConstraints = false
chequeImageView.contentMode = .scaleAspectFit
chequeImageView.tintColor = .systemGray3
return chequeImageView
}()
let chequePostionLabel : UILabel = {
let chequePostionLabel = UILabel()
chequePostionLabel.translatesAutoresizingMaskIntoConstraints = false
chequePostionLabel.text = "Front of the cheque"
chequePostionLabel.font = .systemFont(ofSize: 14)
chequePostionLabel.textColor = .systemGray2
chequePostionLabel.textAlignment = .center
return chequePostionLabel
}()
@objc private func didTapToView(tap : UITapGestureRecognizer) {
guard let side = chequeSide else {return}
delegate?.didRequestToOpenCamera(for: side)
}
private func updateImage() {
DispatchQueue.main.async {
if let image = self.chequeImage {
self.chequeImageView.contentMode = .scaleAspectFill
self.chequeImageView.image = image
}else {
self.chequeImageView.contentMode = .scaleAspectFit
self.chequeImageView.image = self.dummyImage
}
}
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
self.layer.cornerRadius = 8
self.clipsToBounds = true
self.backgroundColor = .tertiarySystemGroupedBackground
self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapToView(tap:))))
chequeImageView.image = dummyImage
addSubview(chequeImageView)
addSubview(chequePostionLabel)
NSLayoutConstraint.activate([
chequeImageView.topAnchor.constraint(equalTo: topAnchor),
chequeImageView.leadingAnchor.constraint(equalTo: leadingAnchor),
chequeImageView.trailingAnchor.constraint(equalTo: trailingAnchor),
chequeImageView.bottomAnchor.constraint(equalTo: chequePostionLabel.topAnchor ,constant: -10),
chequePostionLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
chequePostionLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
chequePostionLabel.bottomAnchor.constraint(equalTo: bottomAnchor , constant: -5),
chequePostionLabel.heightAnchor.constraint(equalToConstant: 20)
])
}
}
|
//
// PostViewModel.swift
// RedditClient
//
// Created by Matias Bzurovski on 01/11/2020.
//
import Foundation
struct PostViewModel: Equatable {
let title: String
let username: String
let thumbnail: String?
let fullSizeImage: String?
let dateTime: Date
let comments: Int
let isUnread: Bool
}
|
//
// ContentView.swift
// MultiTable
//
// Created by Andrei Chenchik on 17/6/21.
//
import SwiftUI
struct QuestionStatusView: View {
@StateObject var question: Question
var body: some View {
if let userAnswer = question.userAnswer {
if userAnswer == question.rightAnswer {
return Image(systemName: "checkmark.seal.fill").foregroundColor(.green)
} else {
return Image(systemName: "xmark").foregroundColor(.red)
}
} else {
return Image(systemName: "questionmark").foregroundColor(.blue)
}
}
}
struct QuestionView: View {
@StateObject var question: Question
var body: some View {
HStack {
Text("\(question.description)")
Text("=")
Text("\(question.userAnswerDescription)")
Spacer()
QuestionStatusView(question: question)
}
}
}
struct TableView: View {
@StateObject var table: Table
@State private var alertQuestion: Question? = nil
@State private var isAlertShowing = false
var body: some View {
List {
ForEach(table.questions) { question in
Button(action: {
if question.userAnswer == nil {
self.alertQuestion = question
self.isAlertShowing = true
}
}, label: {
QuestionView(question: question)
})
}
}
.alert(isPresented: $isAlertShowing, TextAlert(title: self.alertQuestion?.description ?? "", message: "How much will it be?", keyboardType: .numberPad) { result in
guard let text = result else { return }
guard let question = alertQuestion else { fatalError("No question provided") }
guard let userNumber = Int(text) else {
self.isAlertShowing = true
return
}
question.userAnswer = userNumber
})
.navigationTitle("MultiTable")
}
}
struct TableView_Previews: PreviewProvider {
static var previews: some View {
TableView(table: Table(lowerBound: 1, upperBound: 12))
}
}
|
//
// PersonTableController.swift
// MsdGateLock
//
// Created by ox o on 2017/6/15.
// Copyright © 2017年 xiaoxiao. All rights reserved.
//
import UIKit
class PersonTableController: UITableViewController {
@IBOutlet weak var iconImgView: UIImageView!
@IBOutlet weak var nickName: UILabel!
@IBOutlet weak var phoneLabel: UILabel!
@IBOutlet weak var lockPass: UILabel!
@IBOutlet weak var orderLock: UILabel!
// @IBOutlet weak var useInfo: UILabel!
@IBOutlet weak var aboutUs: UILabel!
@IBOutlet weak var loginOut: UILabel!
var userInfo : UserInfoResp?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "个人中心"
self.view.backgroundColor = UIColor.globalBackColor
setupUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
getUserInfo()
}
//cell线
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if (self.tableView?.responds(to: #selector(setter: UITableViewCell.separatorInset)))!{
tableView?.separatorInset = UIEdgeInsets.zero
}
if (tableView?.responds(to: #selector(setter: UIView.layoutMargins)))!{
tableView?.layoutMargins = UIEdgeInsets.zero
}
}
}
extension PersonTableController{
func setupUI(){
nickName.textColor = UIColor.textBlackColor
phoneLabel.textColor = UIColor.textBlackColor
lockPass.textColor = UIColor.textBlackColor
orderLock.textColor = UIColor.textBlackColor
// useInfo.textColor = UIColor.textBlackColor
aboutUs.textColor = UIColor.textBlackColor
loginOut.textColor = UIColor.textBlackColor
}
}
//MARK:- 响应事件
extension PersonTableController{
func gotoProfiel(){
QPCLog("profile")
let personVC = UIStoryboard(name: "PersonInfoController", bundle: nil).instantiateViewController(withIdentifier: "PersonInfoController") as! PersonInfoController
personVC.model = self.userInfo
navigationController?.pushViewController(personVC, animated: true)
}
func gotoLockPassword(){
navigationController?.pushViewController(SetPassWordController(), animated: true)
}
func gotoOrderLock(){
let req = BaseReq<CommonReq>()
req.action = GateLockActions.ACTION_ReservedList
req.sessionId = UserInfo.getSessionId() ?? ""
req.sign = LockTools.getSignWithStr(str: "oxo")
req.data = CommonReq()
AjaxUtil<OrderLockResp>.actionArrPost(req: req) { [weak self](resp) in
QPCLog(resp.msg)
guard let weakSelf = self else {return}
if resp.data != nil,(resp.data?.count)! > 0 {
let orderListVC = OrderLockListController()
orderListVC.title = "预约门锁"
orderListVC.listModel = resp.data
weakSelf.navigationController?.pushViewController(orderListVC, animated: true)
}else{
let orderVC = UIStoryboard(name: "OrderInstallLockController", bundle: nil).instantiateViewController(withIdentifier: "OrderInstallLockController")
weakSelf.navigationController?.pushViewController(orderVC, animated: true)
}
}
}
func gotoInstructions(){
let webVC = LockWebViewContrller()
webVC.urlStr = GateLockActions.H5_Instructions
webVC.title = "问题反馈"
navigationController?.pushViewController(webVC, animated: true)
}
func gotoAbountMe(){
let webVC = LockWebViewContrller()
webVC.urlStr = GateLockActions.H5_Abount
webVC.title = "关于我们"
navigationController?.pushViewController(webVC, animated: true)
}
// func gotoFeedBack(){
// let webVC = LockWebViewContrller()
// webVC.urlStr = GateLockActions.H5_FeedBack
// webVC.title = "使用说明"
// navigationController?.pushViewController(webVC, animated: true)
// }
func gotoLogout(){
QPCLog("Logout")
let alertVC = UIAlertController(title: "退出登录", message: "亲,您确定退出", preferredStyle: .alert)
let acSure = UIAlertAction(title: "确定", style: .destructive) { (UIAlertAction) in
QPCLog("点击了确定")
let req = BaseReq<CommonReq>()
req.action = GateLockActions.ACTION_Logout
req.sessionId = UserInfo.getSessionId() ?? ""
AjaxUtil<CommonResp>.actionPost(req: req, backJSON: { (resp) in
QPCLog(resp)
})
//清除
UserInfo.removeUserInfo()
UIApplication.shared.keyWindow?.rootViewController = LockNavigationController(rootViewController: LoginController())
}
let acCancle = UIAlertAction(title: "取消", style: .cancel) { (UIAlertAction) in
QPCLog("点击了取消")
}
alertVC.addAction(acSure)
alertVC.addAction(acCancle)
self.present(alertVC, animated: true, completion: nil)
}
}
//MARK:- 请求
extension PersonTableController{
func getUserInfo(){
let req = BaseReq<UserInfoReq>()
req.action = GateLockActions.ACTION_GetUserInfo
req.sessionId = UserInfo.getSessionId() ?? ""
req.sign = LockTools.getSignWithStr(str: "oxo")
req.data = UserInfoReq.init(UserInfo.getPhoneNumber() ?? "")
QPCLog(NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask,true).last)
AjaxUtil<UserInfoResp>.actionPost(req: req){
[weak self] (resp) in
guard let weakSelf = self else {return}
let imageUrl = URL(string: (resp.data?.userImage) ?? "")
weakSelf.iconImgView.kf.setImage(with: imageUrl, placeholder: UIImage(named : "user2"), options: nil, progressBlock: nil)
weakSelf.nickName.text = resp.data?.userName
weakSelf.phoneLabel.text = resp.data?.userTel
weakSelf.userInfo = resp.data
weakSelf.tableView.rect(forSection: 0)
}
}
}
extension PersonTableController{
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.001;
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
if indexPath.section == 0 {
gotoProfiel()
}else if indexPath.section == 1{
if indexPath.row == 0{
gotoLockPassword()
}else{
gotoOrderLock()
}
}else if indexPath.section == 2{
if indexPath.row == 0{
gotoInstructions()
}else{
gotoAbountMe()
}
}else{
gotoLogout()
}
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if cell.responds(to: #selector(setter: UIView.layoutMargins)){
cell.layoutMargins = UIEdgeInsets.zero
}
if cell.responds(to: #selector(setter: UITableViewCell.separatorInset)){
cell.separatorInset = UIEdgeInsets.zero
}
}
}
|
//
// main.swift
// Zoi
//
// Created by kikuchy on 2014/08/15.
// Copyright (c) 2014年 kikuchy. All rights reserved.
//
import Cocoa
NSApplicationMain(C_ARGC, C_ARGV)
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
//Integer
var mybankAccount:Int = 40000
var myAge:UInt = 29
var anotherBankAccount:Double = 55.5
var someNumber:Float = 33.3
|
//
// Country.swift
// FinaleProject
//
// Created by Arber Basha on 17/07/2019.
// Copyright © 2019 Arber Basha. All rights reserved.
//
import UIKit
import SwiftyJSON
//"name":"Afghanistan"
//"capital":"Kabul"
//"altSpellings":[...]2 items
//"relevance":"0"
//"region":"Asia"
class Country: NSObject {
var name:String?
var capital:String?
var region:String?
static func createCountry(json: JSON) -> Country?{
let country = Country()
if let name = json["name"].string{
country.name = name
if let capital = json["capital"].string{
country.capital = capital
}
if let region = json["region"].string{
country.region = region
}
return country
}
return nil
}
static func createUsersArray(jsonArray: [JSON]) -> [Country]? {
var countryArray: [Country] = []
for jsonObj in jsonArray{
if let country = Country.createCountry(json: jsonObj){
countryArray.append(country)
}
}
return countryArray
}
}
|
//
// AnswerCollectionViewFlowLayout.swift
// Swift Against Humanity
//
// Created by Daniel Valencia on 9/27/14.
// Copyright (c) 2014 Daniel Valencia. All rights reserved.
//
import UIKit
//class AnswerCollectionViewFlowLayout: UICollectionViewFlowLayout {
//
// override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
// let collectionViewSize:CGSize? = self.collectionView?.bounds.size
// let width:CGFloat = self.collectionView?.bounds.size.width ?? 0.0
//
// let proposedContentOffsetCenterX = proposedContentOffset.x + width * 0.5
// let proposedRect = self.collectionView?.bounds
//
// let attributesArray: [AnyObject]? = self.layoutAttributesForElementsInRect(proposedRect!)
// var candidateAttributes: UICollectionViewLayoutAttributes
// let attributesArrayUnwrapped: [AnyObject] = attributesArray ?? []
//
// for attributes:UICollectionViewLayoutAttributes in attributesArrayUnwrapped {
// if attributes.representedElementCategory! == UICollectionElementCategory.Cell {
// continue
// }
//
// candidateAttributes = candidateAttributes ?? attributes
// continue;
// }
//// if attributes
// }
// }
//}
|
//
// MovieMapper.swift
// filmania
//
// Created by Matheus Fróes on 16/10/19.
// Copyright © 2019 Matheus Fróes. All rights reserved.
//
import Foundation
/**
Converts from the network `MovieResponse` to the app `Movie` model
*/
struct MovieMapper {
static func map(response: MovieResponse, genres: [Genre]) -> Movie? {
guard let releaseDate = response.releaseDate.toDate(usingFormat: "yyyy-MM-dd") else {
return nil
}
return Movie(
title: response.title,
posterPath: response.posterPath,
overview: response.overview,
genres: genres.filter { genre in response.genreIds.contains(genre.id) },
releaseDate: releaseDate,
backdropPath: response.backdropPath
)
}
static func map(response: [MovieResponse], genres: [Genre]) -> [Movie] {
return response.compactMap { map(response: $0, genres: genres) }
}
}
|
//
// StoryBrain.swift
// offBeatenPath_CYOA
//
// Created by Freed, Margo on 10/16/20.
//
import Foundation
struct StoryBrain {
var storyNumber: Int = 0
let stories = [
//0
Story(
title: "Alright, it’s time for an adventure! Well, on a typical walking path to get some good exercise in. You’re at the beginning and there’s 2 ways to go. Take your pick!",
choice1: "North", choice2: "South",
storyDestination1: 1, storyDestination2: 2),
//1
Story(
title: "Onward! It’s mostly woods on the way, but after about 10 minutes of walking, you spot a friendly cat along the way. He begins to follow you. You...",
choice1: "Let him follow", choice2: "Shoo him away",
storyDestination1: 3, storyDestination2: 4),
//2
Story(
title: "After about 15 minutes you begin to feel hungry. Of course you forgot to eat before your walk. Maybe there’s some berries in the woods off the path? You...",
choice1: "Stray from Path", choice2: "Keep Walking",
storyDestination1: 5, storyDestination2: 6),
//3
Story(title: "A minute or two passes and the cat meows which turns your attention to a small trail off to the right. Do you continue to follow the cat down the narrow path? ", choice1: "Yes", choice2: "No thanks", storyDestination1: 7, storyDestination2: 8),
//4
Story(title: "Once you reach the 1.5 mile marker, you contemplate whether you should turn around or keep going. If you head back you’ll have time for homework. Or do you want to push harder?", choice1: "Turn around", choice2: "Keep going for gains!", storyDestination1: 9, storyDestination2: 10),
//5
Story(title: "Upon encountering a bush of what looks to be elderberries, you see a hunter atop of a hill telling you he knows of a better place for food. You?", choice1: "Ignore him and eat", choice2: "Follow him", storyDestination1: 11, storyDestination2: 12),
//6
Story(title: "Around the first mile marker you start to regret your decision as the hunger hits harder. You’re 2 miles away from the start and there are a few fast food restaurants. Take your pick.", choice1: "Subway", choice2: "Taco Bell", storyDestination1: 13, storyDestination2: 14),
//7
Story(title: "You follow the cat down the pathway until you come across a magical slide that brings you into an alternate dimension. The cat grants you magical powers and the two of you go questing on every path walk.", choice1: "The", choice2: "End", storyDestination1: 0, storyDestination2: 0),
//8
Story(title: "10 minutes pass and you feel bad for the stray cat. The 2nd mile marker has a gas station so you go inside, buy a can of tuna, then open it and feed to the cat on your walk back. Good deed for the day done! ", choice1: "The", choice2: "End", storyDestination1: 0, storyDestination2: 0),
//9
Story(title: "Wow, nice job getting your workout in. It was uneventful, but that’s okay. You managed to get that 8-page essay done afterwards so definitely an accomplished day. ", choice1: "The", choice2: "End", storyDestination1: 0, storyDestination2: 0),
//10
Story(title: "You get to mile marker 3 until you realize it’s almost getting dark out and you sprint back to the start. Once there, you’re dead tired so it’ll be harder to focus on homework in a shorter time frame.", choice1: "The", choice2: "End", storyDestination1: 0, storyDestination2: 0),
//11
Story(title: "Ooops, those elderberries turned out to be hemlock. You’re lucky the hunter was around to call 911. Unfortunately you got your stomach pumped and a massive hospital bill.", choice1: "The", choice2: "End", storyDestination1: 0, storyDestination2: 0),
//12
Story(title: "As shady as the whole thing sounded, he led you to a McDonald’s that happened to be on the top of the hill. You and the hunter became pals and decided to meet at the trail every week.", choice1: "The", choice2: "End", storyDestination1: 0, storyDestination2: 0),
//13
Story(title: "Nice choice since you’re working out. Not to mention a footlong sub can last for 2 meals. You eat half and walk back to the start of the trail without feeling any regret. ", choice1: "The", choice2: "End", storyDestination1: 0, storyDestination2: 0),
//14
Story(title: "Gave into the temptation, huh? Though it is good for the wallet, you ate one gordita too many and had a slow walk back after it hit like a rock.", choice1: "The", choice2: "End", storyDestination1: 0, storyDestination2: 0)
]
mutating func nextStory(userChoice: String) {
let currentStory = stories[storyNumber]
if userChoice == stories[storyNumber].c1 {
storyNumber = stories[storyNumber].s1
} else if userChoice == stories[storyNumber].c2 {
storyNumber = stories[storyNumber].s2
}
}
func getStoryTitle() -> String {
return stories[storyNumber].t
}
func getChoice1() -> String {
return stories[storyNumber].c1
}
func getChoice2() -> String {
return stories[storyNumber].c2
}
}
|
//
// Category.swift
// LBCOffers
//
// Created by Mohamed Derkaoui on 12/04/2020.
// Copyright © 2020 Mohamed Derkaoui. All rights reserved.
//
import Foundation
struct Category: Decodable {
var id: Int
var name: String
}
|
//
// HomeExpericeCollectionView.swift
// SpecialTraining
//
// Created by yintao on 2018/12/14.
// Copyright © 2018 youpeixun. All rights reserved.
//
import UIKit
import RxSwift
import RxDataSources
class HomeExpericeCollectionView: UICollectionView {
private let disposeBag = DisposeBag()
private var carouseDatas = [AdvertListModel]()
public let datasource = Variable(([SectionModel<Int, HomeCellSize>](), [AdvertListModel]()))
public let itemDidSelected = PublishSubject<ExperienceCourseItemModel>()
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
setupUI()
rxBind()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func setupUI() {
if #available(iOS 11, *) {
contentInsetAdjustmentBehavior = .never
}
showsVerticalScrollIndicator = false
backgroundColor = .white
register(HomeHeaderExperienceView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HomeHeaderExperienceViewID")
register(UINib.init(nibName: "CourseDisplayMinuteCell", bundle: Bundle.main), forCellWithReuseIdentifier: "CourseDisplayMinuteCellID")
}
private func rxBind() {
rx.setDelegate(self)
.disposed(by: disposeBag)
let datasourceSignal = RxCollectionViewSectionedReloadDataSource<SectionModel<Int, HomeCellSize>>.init(configureCell: { (_, col, indexPath, model) -> UICollectionViewCell in
let cell = col.dequeueReusableCell(withReuseIdentifier: "CourseDisplayMinuteCellID", for: indexPath) as! CourseDisplayMinuteCell
cell.model = (model as! ExperienceCourseItemModel)
return cell
}, configureSupplementaryView: { [unowned self] (_, col, kind, indexPath) -> UICollectionReusableView in
let colHeader = col.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "HomeHeaderExperienceViewID", for: indexPath) as! HomeHeaderExperienceView
colHeader.setData(source: self.carouseDatas)
return colHeader
}, moveItem: { _,_,_ in
}) { _,_ -> Bool in
return false
}
datasource.asDriver()
.map ({ [weak self] data -> [SectionModel<Int, HomeCellSize>] in
self?.carouseDatas = data.1
return data.0
})
.drive(rx.items(dataSource: datasourceSignal))
.disposed(by: disposeBag)
rx.modelSelected(ExperienceCourseItemModel.self)
.asDriver()
.drive(itemDidSelected)
.disposed(by: disposeBag)
}
}
extension HomeExpericeCollectionView: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
let carouselHeader = HomeHeaderExperienceView.init(frame: .init(x: 0, y: 0, width: PPScreenW, height: 200))
return .init(width: PPScreenW, height: carouselHeader.actualHeight)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return datasource.value.0[section].items.first?.minimumLineSpacing ?? 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return datasource.value.0[section].items.first?.minimumInteritemSpacing ?? 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return datasource.value.0[section].items.first?.sectionInset ?? .zero
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return datasource.value.0[indexPath.section].items[indexPath.row].size ?? .zero
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
}
|
//
// HiringViewController.swift
// Fixee
//
// Created by Haydn Joel Gately on 09/02/2017.
// Copyright © 2017 Fixee. All rights reserved.
//
import UIKit
import SwiftyJSON
import Firebase
import FirebaseAuthUI
import FirebaseDatabaseUI
import FirebaseGoogleAuthUI
import FirebaseFacebookAuthUI
import MapKit
import CoreLocation
class HiringViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UITextViewDelegate, UIPickerViewDelegate, MKMapViewDelegate, CLLocationManagerDelegate {
let ref = FIRDatabase.database().reference(withPath: "hires")
@IBOutlet weak var noResults: UIView!
var refreshControl: UIRefreshControl!
@IBOutlet weak var loadingView: UIView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var tableView: UITableView!
var id : Int = 0
var hires : Array<Hire> = []
var values:NSDictionary = [:]
override func viewDidLoad() {
super.viewDidLoad()
sortList(row: 0)
tableView.delegate = self
tableView.dataSource = self
noResults.isHidden = true
loadingView.isHidden = false
activityIndicator.startAnimating()
DispatchQueue.global(qos: .background).async {
self.getHires()
//self.activityIndicator.stopAnimating()
DispatchQueue.main.async {
self.checkIfResults()
self.tableView.reloadData()
self.loadingView.isHidden = true
self.activityIndicator.stopAnimating()
self.pickerTextField.isUserInteractionEnabled = true
self.pickerView.isUserInteractionEnabled = true
}
}
UISetup()
// Do any additional setup after loading the view.
// Do any additional setup after loading the view.
refreshControl = UIRefreshControl()
refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
refreshControl.addTarget(self, action: Selector("refresh"), for: UIControlEvents.valueChanged)
tableView.addSubview(refreshControl) // not required when using UITableViewController
self.addDoneButtonOnKeyboard()
//search.returnKeyType = UIReturnKeyType.done
// Do any additional setup after loading the view.
}
func checkIfResults() {
if(hires.count > 0){
noResults.isHidden = true
tableView.isHidden = false
}
else{
noResults.isHidden = false
tableView.isHidden = true
}
}
func addDoneButtonOnKeyboard()
{
let doneToolbar: UIToolbar = UIToolbar(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 320, height: 50)))
doneToolbar.barStyle = UIBarStyle.default
let flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(MessageViewController.doneButtonAction))
var items = [UIBarButtonItem]()
items.append(flexSpace)
items.append(done)
doneToolbar.items = items
doneToolbar.sizeToFit()
//self.search.inputAccessoryView = doneToolbar
}
var tokenToSend: String = ""
func doneButtonAction()
{
//self.search.resignFirstResponder()
}
//@IBOutlet weak var search: UISearchBar!
func refresh() {
// Code to refresh table view
DispatchQueue.global(qos: .background).async {
self.getHires()
DispatchQueue.main.async {
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for : indexPath) as! HiringViewCell
//cell.selectionStyle = .default
let bgColorView = UIView()
//bgColorView.backgroundColor = UIColor.clear.withAlphaComponent(0.15)
//bgColorView.backgroundColor = UIColor.red
//cell.selectedBackgroundView = bgColorView
if indexPath.row % 2 == 0
{
if(indexPath.row == 0){
cell.textLabelHire?.text = hires[(indexPath as NSIndexPath).row].getTitle()
cell.detailTextLabelHire?.text = "£\(Int(hires[(indexPath as NSIndexPath).row].getPrice()))"
if(hires[(indexPath as NSIndexPath).row].distance == 1000){
cell.distanceLabelHire.text = ""
}
else{
cell.distanceLabelHire.text = "\(hires[(indexPath as NSIndexPath).row].distance)km away"
}
cell.selectionStyle = .default
cell.backgroundColor = UIColor.white
cell.imageViewHire.image = #imageLiteral(resourceName: "NoImage")
if(hires[(indexPath as NSIndexPath).row].imageURL != ""){
print("runs imageeee")
var storage = FIRStorage.storage()
// This is equivalent to creating the full reference
let storagePath = "http://firebasestorage.googleapis.com\(hires[(indexPath as NSIndexPath).row].imageURL)"
var storageRef = storage.reference(forURL: storagePath)
// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
storageRef.data(withMaxSize: 30 * 1024 * 1024) { data, error in
if let error = error {
// Uh-oh, an error occurred!
} else {
// Data for "images/island.jpg" is returned
DispatchQueue.main.async {
cell.imageViewHire.image = UIImage(data: data!)!
self.hires[(indexPath as NSIndexPath).row].image = UIImage(data: data!)!
}
print("returned image")
}
}
}
else{
cell.imageViewHire.image = #imageLiteral(resourceName: "NoImage")
}
}else{
cell.textLabelHire?.text = hires[(indexPath as NSIndexPath).row - indexPath.row / 2].getTitle()
cell.detailTextLabelHire?.text = "£\(Int(hires[(indexPath as NSIndexPath).row - indexPath.row / 2].getPrice()))"
if(hires[(indexPath as NSIndexPath).row - indexPath.row / 2].distance == 1000){
cell.distanceLabelHire.text = ""
}
else{
cell.distanceLabelHire.text = "\(hires[(indexPath as NSIndexPath).row - indexPath.row / 2].distance)km away"
}
cell.selectionStyle = .default
cell.backgroundColor = UIColor.white
cell.imageViewHire.image = #imageLiteral(resourceName: "NoImage")
if(hires[(indexPath as NSIndexPath).row - indexPath.row / 2].imageURL != ""){
print("runs imageeee")
var storage = FIRStorage.storage()
// This is equivalent to creating the full reference
let storagePath = "http://firebasestorage.googleapis.com\(hires[(indexPath as NSIndexPath).row - indexPath.row / 2].imageURL)"
var storageRef = storage.reference(forURL: storagePath)
// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
storageRef.data(withMaxSize: 30 * 1024 * 1024) { data, error in
if let error = error {
// Uh-oh, an error occurred!
} else {
// Data for "images/island.jpg" is returned
DispatchQueue.main.async {
cell.imageViewHire.image = UIImage(data: data!)!
self.hires[(indexPath as NSIndexPath).row - indexPath.row / 2].image = UIImage(data: data!)!
}
print("returned image")
}
}
}
else{
cell.imageViewHire.image = #imageLiteral(resourceName: "NoImage")
}
}
}
else{
cell.textLabelHire?.text = ""
cell.detailTextLabelHire?.text = ""
cell.backgroundColor = UIColor.clear
cell.imageViewHire?.image = nil
cell.selectionStyle = .none
}
// cell.titleLabel.text = hires[(indexPath as NSIndexPath).row].getTitle()
//cell.descriptionLabel.text = hires[(indexPath as NSIndexPath).row].getMessage()
//cell.problemImage.image = UIImage(named: "NoImage")
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var count : Int = 0
if tableView == self.tableView {
count = hires.count * 2
}
return count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
if tableView == self.tableView {
if indexPath.row % 2 == 0
{
return 65 //cell height
}
else
{
return 7 //space heigh
}
}
return 80
}
func getHires() -> Array<Hire> {
var hireList = Array<Hire>()
//let id = 1
let url = URL(string: "https://fixee-164914.firebaseio.com/hires.json")!
var data = try? Data(contentsOf: url as URL)
var isnil = false
//data = JSON(data: data!)
print("data is \(data!)")
if data == nil{
isnil = true
}
print("is nill is \(isnil)")
if(data == nil){
print("network error")
hireList = []
return hireList
}
// else if(data == "null"){
// print("network error")
// hireList = []
// return hireList
// }
else{
values = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
}
let json = JSON(values)
var i = 0;
for (key, value) in json{
var hireReceived = json[key]
let newHire = Hire(id: "", user_id: "", title: "", imageURL: "", description: "", price: 0, distance: 0, latitude: 0, longitude: 0, category: 0)
newHire.id = hireReceived["id"].stringValue
newHire.user_id = hireReceived["user_id"].stringValue
newHire.title = hireReceived["title"].stringValue
newHire.description = hireReceived["description"].stringValue
newHire.distance = hireReceived["distance"].doubleValue
newHire.imageURL = hireReceived["image_url"].stringValue
newHire.latitude = hireReceived["latitude"].doubleValue
newHire.longitude = hireReceived["longitude"].doubleValue
newHire.price = hireReceived["price"].intValue
newHire.category = hireReceived["category"].intValue
newHire.postcode = hireReceived["postcode"].stringValue
//newHire.downloadImage()
var distanceBetween: Double = 0;
var i: Int = 0
//coords of problem
let hireLat = newHire.latitude
let hireLong = newHire.longitude
//print("lat \(tempArray[i].longitude)")
///current location coords53.401210,
//uncomment this to get the users current location
//let locValue:CLLocationCoordinate2D = locationManager.location!.coordinate
//turn them into coordinate variables
let coord1 = CLLocation(latitude: hireLat, longitude: hireLong)
let coord2 = CLLocation(latitude: UserSingleton.sharedInstance.lat, longitude: UserSingleton.sharedInstance.lng)
//distance between them in metres from cooord2
distanceBetween = coord1.distance(from: coord2)
//round to 1dp for KM output
distanceBetween = (round(distanceBetween/100)/10)
//set the distance between in the tempAray establishment 'object'
newHire.distance = Double(distanceBetween)
//establishments[i][1] = String(distanceBetween)
if((newHire.latitude == 0) || (newHire.longitude == 0)){
newHire.distance = 1000
}
hireList.append(newHire)
}
hires = hireList
globalHire = hireList
print(hireList.count)
//self.tableView.reloadData()
return hireList
}
var pickOption = ["Nearest", "Furthest", "Price (Asc)", "Price (Desc)"]
@IBOutlet weak var pickerTextField: UITextField!
var pickerView = UIPickerView()
func UISetup(){
pickerTextField.layer.borderColor = UIColor( red: 255/255, green: 255/255, blue:255/255, alpha: 1.0 ).cgColor
pickerTextField.layer.borderWidth = 1.0
pickerTextField.layer.cornerRadius = 5.0
pickerTextField.text = "Nearest"
pickerTextField.tintColor = UIColor.clear
var toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.bordered, target: self, action: "donePicker")
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let spaceButton2 = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
toolBar.setItems([spaceButton2, spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
pickerTextField.inputAccessoryView = toolBar
pickerView.delegate = self
pickerTextField.inputView = pickerView
pickerTextField.isUserInteractionEnabled = false
pickerView.isUserInteractionEnabled = false
}
func textFieldShouldBeginEditing(pickerTextField: UITextField) -> Bool {
pickerTextField.resignFirstResponder();
view.endEditing(true)
return false
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickOption.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickOption[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
//print(row)
pickerTextField.text = pickOption[row]
rowHolder = row
}
var rowHolder: Int = 0
func donePicker () //Create an IBAction
{
//problems = holdProblems
pickerTextField.endEditing(true);
//subSelect(row: rowHolder)
print("row holdr is \(rowHolder)")
sortList(row: rowHolder)
print("all sorted")
}
var sorter: Int = 0
var globalHire = Array<Hire>()
func sortList(row: Int){
sorter = row
//print("sorter is:\(sorter)")
hires = globalHire
var tempHires = Array<Hire>()
if(hires.count > 0){
if(sorter == 0){
for _ in 0..<hires.count - 1{
//print(tempArray.count)
for i in 0..<hires.count - 1{
if(Double(hires[i].distance) > Double(hires[i+1].distance)){
let temp = hires[i]
hires[i] = hires[i+1]
hires[i+1] = temp
}
}
}
tempHires = hires
}
else if (sorter == 1){
for _ in 0..<hires.count - 1{
//print(tempArray.count)
for i in 0..<hires.count - 1{
if(Double(hires[i].distance) < Double(hires[i+1].distance)){
let temp = hires[i]
hires[i] = hires[i+1]
hires[i+1] = temp
}
}
}
tempHires = hires
}
else if (sorter == 2){
for _ in 0..<hires.count - 1{
//print(tempArray.count)
for i in 0..<hires.count - 1{
if(Double(hires[i].price) > Double(hires[i+1].price)){
let temp = hires[i]
hires[i] = hires[i+1]
hires[i+1] = temp
}
}
}
tempHires = hires
}
else if (sorter == 3){
for _ in 0..<hires.count - 1{
//print(tempArray.count)
for i in 0..<hires.count - 1{
if(Double(hires[i].price) < Double(hires[i+1].price)){
let temp = hires[i]
hires[i] = hires[i+1]
hires[i+1] = temp
}
}
}
tempHires = hires
}
//print("SWAPPED")
//print("after")
//print(establishments)
}
hires = []
tableView.reloadData()
hires = tempHires
tableView.reloadData()
print("sorted and reloaded table")
}
override func prepare(for segue: UIStoryboardSegue!, sender: Any!) {
if (segue.identifier == "HireToUploadHire") {
}
else{
var rowIndex : Int = 0
var row : Int = 0
rowIndex = (tableView.indexPathForSelectedRow?.row)!
row = rowIndex
row = row - row/2
print(row)
let hire = hires[row]
//donePicker()
let theDestination = (segue.destination as! ViewHireViewController)
//var objectList: [String] = ["13", "Travis Fire Station"]
// if(establishment.image != ""){
//
// establishment.getImage()
//
// }
theDestination.hire = hire
}
}
var indexPathGlobal : Int = 0
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(indexPath)
pickerTextField.endEditing(true);
//haveLocation = checkNetwork()
//if(checkNetwork() == false){
//timer.invalidate()
/*
let alertController = UIAlertController(title: "Location Services Disabled", message: "Update in Settings->Privacy->Location Services.", preferredStyle: UIAlertControllerStyle.alert) //Replace UIAlertControllerStyle.Alert by UIAlertControllerStyle.alert
// Replace UIAlertActionStyle.Default by UIAlertActionStyle.default
let okAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
//self.doRewind()
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
//}
//else{
if Reachability.isConnectedToNetwork() == false {
//timer.invalidate()
let alertController = UIAlertController(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", preferredStyle: UIAlertControllerStyle.alert) //Replace UIAlertControllerStyle.Alert by UIAlertControllerStyle.alert
// Replace UIAlertActionStyle.Default by UIAlertActionStyle.default
let okAction = UIAlertAction(title: "Close", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
//self.doRewind()
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
else{
*/
if tableView == self.tableView {
self.performSegue(withIdentifier: "ViewHire", sender: indexPath);
}
tableView.deselectRow(at: indexPath, animated: true)
//}
}
func doRewind(){
_ = navigationController?.popViewController(animated: true)
}
// func checkNetwork()->Bool{
//
// if CLLocationManager.locationServicesEnabled() {
// switch(CLLocationManager.authorizationStatus()) {
// case .notDetermined, .restricted, .denied:
// print("No access")
//
//
// return false
// case .authorizedAlways, .authorizedWhenInUse:
// print("Access")
// return true
// }
// } else {
// print("Location services are not enabled")
// return false
// }
//
// }
/*
// 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.
}
*/
}
|
//
// EmptyItemListCell.swift
// countit
//
// Created by David Grew on 10/02/2019.
// Copyright © 2019 David Grew. All rights reserved.
//
import Foundation
import UIKit
class EmptyItemListCell: UITableViewCell {
let BORDER_PADDING_TOP: CGFloat = 15
let BORDER_PADDING_LEFT: CGFloat = 15
let BORDER_PADDING_RIGHT: CGFloat = -15
let TEXT_PADDING_LEFT: CGFloat = 40
let TEXT_PADDING_RIGHT: CGFloat = -40
let ARROW_PADDING_TOP: CGFloat = 5
let ARROW_PADDING_BOTTOM: CGFloat = -5
let ARROW_PADDING_RIGHT: CGFloat = -10
let ARROW_WIDTH: CGFloat = 25
let ARROW_HEIGHT: CGFloat = 50
private let CELL_TEXT = "Create a target to start"
init() {
super.init(style: .default, reuseIdentifier: "EmptyItemListCell")
backgroundColor = Colors.TABLE_BACKGROUND
selectionStyle = .none
accessibilityIdentifier = AccessibilityIdentifiers.EMPTY_ITEM_LIST_CELL
let border = Border()
let text = UILabel()
let arrow = UIImageView(image: UIImage(named: "EmptyCellArrow"))
text.text = CELL_TEXT
text.font = UIFont.boldSystemFont(ofSize: 18)
text.textColor = UIColor.lightGray
text.numberOfLines = 0
text.textAlignment = .center
addSubview(border)
addSubview(text)
addSubview(arrow)
border.translatesAutoresizingMaskIntoConstraints = false
text.translatesAutoresizingMaskIntoConstraints = false
arrow.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
border.leftAnchor.constraint(equalTo: leftAnchor, constant: BORDER_PADDING_LEFT),
border.rightAnchor.constraint(equalTo: rightAnchor, constant: BORDER_PADDING_RIGHT),
border.topAnchor.constraint(equalTo: topAnchor, constant: BORDER_PADDING_TOP),
border.bottomAnchor.constraint(equalTo: bottomAnchor),
text.centerYAnchor.constraint(equalTo: arrow.centerYAnchor),
text.leftAnchor.constraint(equalTo: leftAnchor, constant: TEXT_PADDING_LEFT),
text.rightAnchor.constraint(equalTo: rightAnchor, constant: TEXT_PADDING_RIGHT),
arrow.topAnchor.constraint(equalTo: border.topAnchor, constant: ARROW_PADDING_TOP),
arrow.bottomAnchor.constraint(equalTo: border.bottomAnchor, constant: ARROW_PADDING_BOTTOM),
arrow.rightAnchor.constraint(equalTo: border.rightAnchor, constant: ARROW_PADDING_RIGHT),
arrow.heightAnchor.constraint(equalToConstant: ARROW_HEIGHT),
arrow.widthAnchor.constraint(equalToConstant: ARROW_WIDTH)
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// BaseDialogelementTextField.swift
// KayakFirst Ergometer E2
//
// Created by Balazs Vidumanszki on 2018. 01. 02..
// Copyright © 2018. Balazs Vidumanszki. All rights reserved.
//
import Foundation
class BaseDialogElementTextField<E: ViewDialogElementTextFieldLayout>: CustomUi<E>, UITextFieldDelegate {
var title: String? {
get {
return contentLayout!.valueTextField.placeholder
}
set {
contentLayout!.valueTextField.placeholder = newValue
}
}
var keyBoardType: UIKeyboardType? {
get {
return contentLayout!.valueTextField.keyboardType
}
set {
contentLayout!.valueTextField.keyboardType = newValue!
}
}
var secureTextEntry: Bool {
get {
return contentLayout!.valueTextField.isSecureTextEntry
}
set {
contentLayout!.valueTextField.isSecureTextEntry = newValue
}
}
var error: String? {
get {
return contentLayout!.errorLabel.text
}
set {
if let value = newValue {
contentLayout!.errorLabel.isHidden = false
contentLayout!.errorLabel.text = value
} else {
contentLayout!.errorLabel.isHidden = true
}
}
}
var required: Bool? {
get {
return false
}
set {
if let titleText = title {
title = titleText + " *"
}
}
}
var clickCallback: (() -> ())?
private var _editable = true
var isEditable: Bool {
get {
return _editable
}
set {
_editable = newValue
}
}
var text: String? {
get {
return contentLayout!.valueTextField.text
}
set {
contentLayout!.valueTextField.text = newValue
self.error = nil
}
}
var active: Bool {
get {
return true
}
set {
if newValue {
contentLayout!.valueTextField.alpha = 1
} else {
contentLayout!.valueTextField.alpha = 0.5
}
isEditable = newValue
}
}
var clickable: Bool = true
var textChangedListener: (() -> ())?
//MARK: size
override var intrinsicContentSize: CGSize {
get {
return CGSize(width: 0, height: 65)
}
}
//MARK: init view
override func initView() {
super.initView()
contentLayout!.valueTextField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
contentLayout!.valueTextField.delegate = self
}
@objc private func textFieldDidChange() {
self.error = nil
if let listener = textChangedListener {
listener()
}
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if clickable {
if let click = clickCallback {
click()
}
}
return _editable
}
}
|
//
// MyPickViewModel.swift
// projectForm
//
// Created by 林信沂 on 2020/12/28.
//
import Foundation
struct MyPickViewModel {
var arr = ["1","2","3","4","5","6","7","8","9","10"]
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.