text stringlengths 8 1.32M |
|---|
import UIKit
public typealias SoapParameters = [String: Any]
public typealias SOAPHeaders = [String: String]
enum RequestError: Error {
case invalidBaseURL
case noParametersAtRequest
}
public protocol SOAPRequest {
var parameters: SoapParameters? { get }
var urn: String { get }
var baseURL: URL? { get }
var headers: SOAPHeaders? { get }
var timeout: TimeInterval { get }
var image: UIImage? { get }
var httpMethod: HTTPMethod { get }
}
extension SOAPRequest {
public var timeout: TimeInterval { return 60 }
public var image: UIImage? { return .none }
public var baseURL: URL? { return URL(string: "https://st463.gaiadesign.com.mx/index.php/api/v2_soap/") }
public var httpMethod: HTTPMethod { return .post }
public var headers: SOAPHeaders? { return .none }
public func toRequest()throws -> URLRequest {
guard let url = baseURL else {
throw RequestError.invalidBaseURL
}
var request = URLRequest(url: url)
request.timeoutInterval = timeout
request.httpMethod = httpMethod.rawValue.uppercased()
var bodyString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
guard let parameters = parameters else { throw RequestError.noParametersAtRequest }
let parametersInXML = parameters.toXML()
let body = ["soap:Body": [ urn: parametersInXML].toXML()]
bodyString += body.toXML()
bodyString += "</soap:Envelope>"
print(bodyString)
request.httpBody = bodyString.data(using: .utf8)
var defaultHeaders = SOAPHeaders()
defaultHeaders["Host"] = url.host
defaultHeaders["Content-Length"] = String(bodyString.count)
if let headers = headers {
headers.keys.forEach { defaultHeaders[$0] = headers[$0] }
}
return request
}
}
|
//
// NewGameViewController.swift
// game
//
// Created by Fredrik Carlsson on 2018-01-15.
// Copyright © 2018 Fredrik Carlsson. All rights reserved.
//
import UIKit
class NewGameViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var nrOfTeamsPicker: UIPickerView!
@IBOutlet weak var addPlayersToTeamLabel: UILabel!
@IBOutlet weak var scrollImage: UIImageView!
@IBOutlet weak var helpView: UIView!
var tapGesture = UITapGestureRecognizer()
let nrSelection = [2,3,4,5]
var teamsSelected = 0
var pictureArray = [#imageLiteral(resourceName: "Team_work_icon_purple"), #imageLiteral(resourceName: "Team_work_yellow"), #imageLiteral(resourceName: "Team_work_blue"), #imageLiteral(resourceName: "Team_work_iconpink"), #imageLiteral(resourceName: "Team_work_green")]
let team1 = UIButton()
let team2 = UIButton()
let team3 = UIButton()
let team4 = UIButton()
let team5 = UIButton()
let team1CheckView = UIImageView()
let team2CheckView = UIImageView()
let team3CheckView = UIImageView()
let team4CheckView = UIImageView()
let team5CheckView = UIImageView()
let team1Label = UILabel()
let team2Label = UILabel()
let team3Label = UILabel()
let team4Label = UILabel()
let team5Label = UILabel()
var rotationAngle:CGFloat!
var teamID: Int?
var random: Int?
@IBOutlet weak var helpViewTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
helpViewTextView.text = NSLocalizedString("newGameHelpText", comment: "")
scrollView.isScrollEnabled = true
scrollView.contentSize = CGSize(width: scrollView.frame.width, height: CGFloat(150*teamsSelected))
rotationAngle = -90 * (.pi/180)
let y = nrOfTeamsPicker.frame.origin.y
nrOfTeamsPicker.transform = CGAffineTransform(rotationAngle: rotationAngle)
self.nrOfTeamsPicker.frame = CGRect(x: -100, y: y, width: view.frame.width + 200, height: 70
)
nrOfTeamsPicker.selectRow(2, inComponent: 0, animated: true)
nrOfTeamsPicker.delegate = self
nrOfTeamsPicker.dataSource = self
if (teamsSelected>0){
nrOfTeamsPicker.selectRow(teamsSelected-2, inComponent: 0, animated: true)
}
team1.setBackgroundImage(#imageLiteral(resourceName: "Team_work_icon_purple"), for: .normal)
team2.setBackgroundImage(#imageLiteral(resourceName: "Team_work_yellow"), for: .normal)
team3.setBackgroundImage(#imageLiteral(resourceName: "Team_work_blue"), for: .normal)
team4.setBackgroundImage(#imageLiteral(resourceName: "Team_work_iconpink"), for: .normal)
team5.setBackgroundImage(#imageLiteral(resourceName: "Team_work_green"), for: .normal)
team1.layer.shadowColor = UIColor(red:0/255.0, green:0/255.0, blue:0/255.0, alpha:1.0).cgColor
team1.layer.shadowOffset = CGSize(width:0, height:2.75)
team1.layer.shadowRadius = 1.75
team1.layer.shadowOpacity = 0.55
team2.layer.shadowColor = UIColor(red:0/255.0, green:0/255.0, blue:0/255.0, alpha:1.0).cgColor
team2.layer.shadowOffset = CGSize(width:0, height:2.75)
team2.layer.shadowRadius = 1.75
team2.layer.shadowOpacity = 0.55
team3.layer.shadowColor = UIColor(red:0/255.0, green:0/255.0, blue:0/255.0, alpha:1.0).cgColor
team3.layer.shadowOffset = CGSize(width:0, height:2.75)
team3.layer.shadowRadius = 1.75
team3.layer.shadowOpacity = 0.55
team4.layer.shadowColor = UIColor(red:0/255.0, green:0/255.0, blue:0/255.0, alpha:1.0).cgColor
team4.layer.shadowOffset = CGSize(width:0, height:2.75)
team4.layer.shadowRadius = 1.75
team4.layer.shadowOpacity = 0.55
team5.layer.shadowColor = UIColor(red:0/255.0, green:0/255.0, blue:0/255.0, alpha:1.0).cgColor
team5.layer.shadowOffset = CGSize(width:0, height:2.75)
team5.layer.shadowRadius = 1.75
team5.layer.shadowOpacity = 0.55
if(teamsSelected == 0){
teamsSelected = 2
removeButtonsFromScreen()
var i = 0
for team in 1...teamsSelected{
i = i+1
let tmpString = NSLocalizedString("team_names", comment: "")
let newTeam = Team(name: String(format: tmpString, i), points: 0, id: team-1, isUp: false)
LocalDataBase.teamArray.append(newTeam)
}
random = Int(arc4random_uniform(UInt32(LocalDataBase.teamArray.count)))
selectStartingTeam()
}
if(teamsSelected>2){
scrollImage.isHidden = false
}
else{
scrollImage.isHidden = true
}
addButtonsToScreen()
}
func selectStartingTeam(){
if let rand = random{
LocalDataBase.teamArray[rand].isUp = true
}
}
@objc func buttonAction(sender: UIButton!) {
let btnTag: UIButton = sender
teamID = btnTag.tag
performSegue(withIdentifier: "selectPlayerSegue", sender: self)
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 80
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
label.text = String(nrSelection[row])
label.font = UIFont.systemFont(ofSize: 40, weight: .thin)
label.textAlignment = .center
view.addSubview(label)
view.transform = CGAffineTransform(rotationAngle: (90 * (.pi/180)))
return view
}
public func numberOfComponents(in pickerView: UIPickerView) -> Int{
return 1
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
return nrSelection.count
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
LocalDataBase.teamArray.removeAll()
removeButtonsFromScreen()
teamsSelected = Int(nrSelection[row])
if(teamsSelected>2){
scrollImage.isHidden = false
}
else{
scrollImage.isHidden = true
}
var i = 1
for team in 1...teamsSelected{
let tmpString = NSLocalizedString("team_names", comment: "")
let newTeam = Team(name: String(format: tmpString, i), points: 0, id: team-1, isUp: false)
LocalDataBase.teamArray.append(newTeam)
i = i+1
}
random = Int(arc4random_uniform(UInt32(LocalDataBase.teamArray.count)))
selectStartingTeam()
addButtonsToScreen()
}
func addButtonsToScreen(){
let scrollWidth = scrollView.frame.size.width
scrollView.contentSize = CGSize(width: scrollView.frame.width, height: CGFloat(150*teamsSelected))
team1.frame = CGRect(x: scrollWidth/2-50, y: 0, width: 100, height: 100)
team2.frame = CGRect(x: scrollWidth/2-50 , y: 150, width: 100, height: 100)
team3.frame = CGRect(x: scrollWidth/2-50, y: 300, width: 100, height: 100)
team4.frame = CGRect(x: scrollWidth/2-50, y: 450, width: 100, height: 100)
team5.frame = CGRect(x: scrollWidth/2-50, y: 600, width: 100, height: 100)
team1Label.frame = CGRect(x: scrollWidth/2-50, y: 105, width: 100, height: 25)
team1Label.text = NSLocalizedString("team", comment: "") + " 1"
team1Label.textAlignment = .center
team1Label.layer.masksToBounds = true
team1Label.layer.cornerRadius = 12
team1Label.textAlignment = .center
team1Label.font = UIFont.boldSystemFont(ofSize: 17)
team1Label.layer.borderColor = UIColor.black.cgColor
team1Label.layer.borderWidth = 1
team1CheckView.frame = CGRect(x: scrollWidth-40, y: 30, width: 40, height: 40)
team2CheckView.frame = CGRect(x: scrollWidth-40 , y: 180, width: 40, height: 40)
team3CheckView.frame = CGRect(x: scrollWidth-40, y: 339, width: 40, height: 40)
team4CheckView.frame = CGRect(x: scrollWidth-40, y: 480, width: 40, height: 40)
team5CheckView.frame = CGRect(x: scrollWidth-40, y: 630, width: 40, height: 40)
if(LocalDataBase.teamArray.count == 2){
if(LocalDataBase.teamArray[0].players.count >= 2){
team1CheckView.image = #imageLiteral(resourceName: "checkMark")
}
if(LocalDataBase.teamArray[1].players.count >= 2){
team2CheckView.image = #imageLiteral(resourceName: "checkMark")
}
}
if(LocalDataBase.teamArray.count == 3){
if(LocalDataBase.teamArray[0].players.count >= 2){
team1CheckView.image = #imageLiteral(resourceName: "checkMark")
}
if(LocalDataBase.teamArray[1].players.count >= 2){
team2CheckView.image = #imageLiteral(resourceName: "checkMark")
}
if(LocalDataBase.teamArray[2].players.count >= 2){
team3CheckView.image = #imageLiteral(resourceName: "checkMark")
}
}
if(LocalDataBase.teamArray.count == 4){
if(LocalDataBase.teamArray[0].players.count >= 2){
team1CheckView.image = #imageLiteral(resourceName: "checkMark")
}
if(LocalDataBase.teamArray[1].players.count >= 2){
team2CheckView.image = #imageLiteral(resourceName: "checkMark")
}
if(LocalDataBase.teamArray[2].players.count >= 2){
team3CheckView.image = #imageLiteral(resourceName: "checkMark")
}
if(LocalDataBase.teamArray[3].players.count >= 2){
team4CheckView.image = #imageLiteral(resourceName: "checkMark")
}
}
if(LocalDataBase.teamArray.count == 5){
if(LocalDataBase.teamArray[0].players.count >= 2){
team1CheckView.image = #imageLiteral(resourceName: "checkMark")
}
if(LocalDataBase.teamArray[1].players.count >= 2){
team2CheckView.image = #imageLiteral(resourceName: "checkMark")
}
if(LocalDataBase.teamArray[2].players.count >= 2){
team3CheckView.image = #imageLiteral(resourceName: "checkMark")
}
if(LocalDataBase.teamArray[3].players.count >= 2){
team4CheckView.image = #imageLiteral(resourceName: "checkMark")
}
if(LocalDataBase.teamArray[4].players.count >= 2){
team5CheckView.image = #imageLiteral(resourceName: "checkMark")
}
}
team2Label.frame = CGRect(x: scrollWidth/2-50, y: 255, width: 100, height: 25)
team2Label.text = NSLocalizedString("team", comment: "") + " 2"
team2Label.textAlignment = .center
team2Label.layer.masksToBounds = true
team2Label.layer.cornerRadius = 12
team2Label.textAlignment = .center
team2Label.font = UIFont.boldSystemFont(ofSize: 17)
team2Label.layer.borderColor = UIColor.black.cgColor
team2Label.layer.borderWidth = 1
team3Label.frame = CGRect(x: scrollWidth/2-50, y: 405, width: 100, height: 25)
team3Label.text = NSLocalizedString("team", comment: "") + " 3"
team3Label.textAlignment = .center
team3Label.layer.masksToBounds = true
team3Label.layer.cornerRadius = 12
team3Label.textAlignment = .center
team3Label.font = UIFont.boldSystemFont(ofSize: 17)
team3Label.layer.borderColor = UIColor.black.cgColor
team3Label.layer.borderWidth = 1
team4Label.frame = CGRect(x: scrollWidth/2-50, y: 555, width: 100, height: 25)
team4Label.text = NSLocalizedString("team", comment: "") + " 4"
team4Label.textAlignment = .center
team4Label.layer.masksToBounds = true
team4Label.layer.cornerRadius = 12
team4Label.textAlignment = .center
team4Label.font = UIFont.boldSystemFont(ofSize: 17)
team4Label.layer.borderColor = UIColor.black.cgColor
team4Label.layer.borderWidth = 1
team5Label.frame = CGRect(x: scrollWidth/2-50, y: 705, width: 100, height: 25)
team5Label.text = NSLocalizedString("team", comment: "") + " 5"
team5Label.textAlignment = .center
team5Label.layer.masksToBounds = true
team5Label.layer.cornerRadius = 12
team5Label.textAlignment = .center
team5Label.font = UIFont.boldSystemFont(ofSize: 17)
team5Label.layer.borderColor = UIColor.black.cgColor
team5Label.layer.borderWidth = 1
team1.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
team2.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
team3.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
team4.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
team5.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
team1.tag = 1
team2.tag = 2
team3.tag = 3
team4.tag = 4
team5.tag = 5
if(teamsSelected == 2){
scrollView.addSubview(team1)
scrollView.addSubview(team2)
scrollView.addSubview(team1Label)
scrollView.addSubview(team2Label)
scrollView.addSubview(team1CheckView)
scrollView.addSubview(team2CheckView)
}
if(teamsSelected == 3){
scrollView.addSubview(team1)
scrollView.addSubview(team2)
scrollView.addSubview(team3)
scrollView.addSubview(team1Label)
scrollView.addSubview(team2Label)
scrollView.addSubview(team3Label)
scrollView.addSubview(team1CheckView)
scrollView.addSubview(team2CheckView)
scrollView.addSubview(team3CheckView)
}
if(teamsSelected == 4){
scrollView.addSubview(team1)
scrollView.addSubview(team2)
scrollView.addSubview(team3)
scrollView.addSubview(team4)
scrollView.addSubview(team1Label)
scrollView.addSubview(team2Label)
scrollView.addSubview(team3Label)
scrollView.addSubview(team4Label)
scrollView.addSubview(team1CheckView)
scrollView.addSubview(team2CheckView)
scrollView.addSubview(team3CheckView)
scrollView.addSubview(team4CheckView)
}
if(teamsSelected == 5){
scrollView.addSubview(team1)
scrollView.addSubview(team2)
scrollView.addSubview(team3)
scrollView.addSubview(team4)
scrollView.addSubview(team5)
scrollView.addSubview(team1Label)
scrollView.addSubview(team2Label)
scrollView.addSubview(team3Label)
scrollView.addSubview(team4Label)
scrollView.addSubview(team5Label)
scrollView.addSubview(team1CheckView)
scrollView.addSubview(team2CheckView)
scrollView.addSubview(team3CheckView)
scrollView.addSubview(team4CheckView)
scrollView.addSubview(team5CheckView)
}
}
func removeButtonsFromScreen(){
if(teamsSelected == 2){
team1.removeFromSuperview()
team2.removeFromSuperview()
team1Label.removeFromSuperview()
team2Label.removeFromSuperview()
team1CheckView.removeFromSuperview()
team2CheckView.removeFromSuperview()
}
if(teamsSelected == 3){
team1.removeFromSuperview()
team2.removeFromSuperview()
team3.removeFromSuperview()
team1Label.removeFromSuperview()
team2Label.removeFromSuperview()
team3Label.removeFromSuperview()
team1CheckView.removeFromSuperview()
team2CheckView.removeFromSuperview()
team3CheckView.removeFromSuperview()
}
if(teamsSelected == 4){
team1.removeFromSuperview()
team2.removeFromSuperview()
team3.removeFromSuperview()
team4.removeFromSuperview()
team1Label.removeFromSuperview()
team2Label.removeFromSuperview()
team3Label.removeFromSuperview()
team4Label.removeFromSuperview()
team1CheckView.removeFromSuperview()
team2CheckView.removeFromSuperview()
team3CheckView.removeFromSuperview()
team4CheckView.removeFromSuperview()
}
if(teamsSelected == 5){
team1.removeFromSuperview()
team2.removeFromSuperview()
team3.removeFromSuperview()
team4.removeFromSuperview()
team5.removeFromSuperview()
team1Label.removeFromSuperview()
team2Label.removeFromSuperview()
team3Label.removeFromSuperview()
team4Label.removeFromSuperview()
team5Label.removeFromSuperview()
team1CheckView.removeFromSuperview()
team2CheckView.removeFromSuperview()
team3CheckView.removeFromSuperview()
team4CheckView.removeFromSuperview()
team5CheckView.removeFromSuperview()
}
}
func createAlert(message: String){
let alert = UIAlertController(title: NSLocalizedString("missing_info_in_alert", comment: ""), message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
@IBOutlet weak var menuButton: FloatingActionButton!
@objc func handleTap(_ sender: UITapGestureRecognizer) {
UIView.animate(withDuration: 0.3, animations: {
if(self.menuButton.transform != .identity){
self.menuButton.transform = .identity
self.helpView.isHidden = true
}
})
}
@IBAction func helpButton(_ sender: FloatingActionButton) {
if(self.menuButton.transform != .identity){
helpView.isHidden = false
self.tapGesture = UITapGestureRecognizer(target: self, action: #selector(StartingPage.handleTap))
self.tapGesture.numberOfTapsRequired = 1
self.tapGesture.numberOfTouchesRequired = 1
self.view.addGestureRecognizer(self.tapGesture)
}
else{
UIView.animate(withDuration: 0.3, animations: {
self.menuButton.transform = .identity
self.helpView.isHidden = true
})
}
}
@IBAction func closeHelpView(_ sender: UIButton) {
self.menuButton.transform = .identity
self.helpView.isHidden = true
}
@IBAction func startGameButton(_ sender: UIButtonX) {
var hasTwoPlayersOrMore = true
if(LocalDataBase.teamArray.count > 0){
for team in LocalDataBase.teamArray{
if(team.players.count<2){
hasTwoPlayersOrMore = false
break
}
}
}
if(teamsSelected==0){
createAlert(message: NSLocalizedString("select_at_least_2_teams", comment: ""))
}
else if(hasTwoPlayersOrMore == false){
createAlert(message: NSLocalizedString("select_at_least_2_players", comment: ""))
}
else {
performSegue(withIdentifier: "startGameSegue", sender: self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? AddPlayerViewController {
destination.number = teamID
destination.nrOfTeams = teamsSelected
}
}
}
|
//
// Extensions.swift
// Extensions
//
// Created by Patrick O'Leary on 2/4/17.
// Copyright © 2017 Flatiron School. All rights reserved.
//
import Foundation
extension String{
func whisper() -> String{
let whisperedString = self
return whisperedString.lowercased()
}
func shout() -> String{
let shoutedString = self
return shoutedString.uppercased()
}
func pigLatin() -> String{
let normalSpeechString:String = self
let normalSpeechArray = normalSpeechString.characters.split{$0 == " "}.map(String.init)
var pigLatinString: String = ""
for (index, value) in normalSpeechArray.enumerated(){
let pigifiedWord = convertWordToPigLatin(pigify: value)
if index < (normalSpeechArray.count - 1){
pigLatinString = pigLatinString + pigifiedWord + " "
} else {
pigLatinString = pigLatinString + pigifiedWord
}
}
return pigLatinString
}
func convertWordToPigLatin(pigify: String) -> String{
var pigified: String = ""
let pigifyArray: [Character] = Array(pigify.characters)
var characterHold: Character = " "
for (index,value) in pigifyArray.enumerated(){
if index == 0{
characterHold = value
} else if index == 1 {
pigified = pigified + String(value).uppercased()
} else {
pigified = pigified + String(value).lowercased()
}
}
pigified = pigified + String(characterHold).lowercased() + "ay"
return pigified
}
var points: Int{
var x: Int = 0
var pointsArray = self.characters
for value in pointsArray{
switch value{
case "a":
x = x + 2
case "e":
x = x + 2
case "i":
x = x + 2
case "o":
x = x + 2
case "u":
x = x + 2
case "y":
x = x + 2
case "A":
x = x + 2
case "E":
x = x + 2
case "I":
x = x + 2
case "O":
x = x + 2
case "U":
x = x + 2
case "Y":
x = x + 2
case " ":
print("Space not counted")
default:
x = x + 1
}
}
return x
}
var unicornLevel: String{
var oldBoringString = self
var oldBoringArray: [Character]
var awesomeNewString: String = ""
oldBoringArray = Array(oldBoringString.characters)
print(oldBoringArray)
for (index, value) in oldBoringArray.enumerated(){
if value != " "{
awesomeNewString = awesomeNewString + "🦄"
} else {
awesomeNewString = awesomeNewString + " "
}
}
return awesomeNewString
}
}
extension Int{
var halved: Int {
return self/2
}
var squared: Int{
return self*self
}
func half() -> Int {
return self/2
}
func isDivisible(by: Int) -> Bool{
var isDivisibleBy = false
if self%by == 0{
isDivisibleBy = true
}
return isDivisibleBy
}
}
|
//
// Deaths.swift
// BreakingBadHBCUC2
//
// Created by Computer Science on 8/11/21.
//
import SwiftUI
struct Deaths: View{
@State var deaths = [BBDeaths]()
var body: some View{
ScrollView{
HStack(alignment: .top, spacing: 12) {
Image("breakingbad")
.resizable()
.frame(width: 90, height: 50, alignment: .trailing)
Text("Deaths")
.font(.system(size: 30))
.fontWeight(.bold)
.foregroundColor(Color("Color.green"))
}
ForEach(deaths){ deaths in
FlashcardSmall(front: {
VStack{
Text("Season #" + String(deaths.season))
.font(.system(size: 40))
.fontWeight(.bold)
.foregroundColor(.black)
Text("Episode #" + String(deaths.episode))
.font(.system(size: 40))
.fontWeight(.bold)
.foregroundColor(.black)
Text("More Info >")
.fontWeight(.bold)
.foregroundColor(.white)
.padding()
.background(Color("Color.green"))
.clipShape(Capsule())
.padding()
}
}, back: {
VStack{
Text("Died: " + deaths.death)
.font(.system(size: 22))
Text("Cause: " + deaths.cause)
.font(.system(size: 22))
Text("Responsible: " + deaths.responsible)
.font(.system(size: 22))
Text("Last Words: " + deaths.last_words)
.font(.system(size: 22))
Text("HOME")
.fontWeight(.bold)
.foregroundColor(.white)
.padding()
.background(Color("Color.green"))
.clipShape(Capsule())
.padding()
}
})
}
}
//navigationTitle("Braking Bad Deaths")
.onAppear(perform: {
let url = URL(string: "https://breakingbadapi.com/api/deaths")!
URLSession.shared.dataTask(with: url){ data, _, error in
if let error = error{
print(error.localizedDescription)
}else{
if let data = data{
let decoder = JSONDecoder()
do{
let deaths = try decoder.decode([BBDeaths].self, from: data)
DispatchQueue.main.async {
self.deaths = deaths
}
}catch {
print(error.localizedDescription)
}
}
}
} .resume()
})
}
}
struct BBDeaths: Decodable {
var death_id: Int
var death: String
var cause: String
var responsible: String
var last_words: String
var season: Int
var episode: Int
var number_of_deaths: Int
}
extension BBDeaths: Identifiable{
var id: Int{
return death_id
}
var numdeaths: Int{
return number_of_deaths
}
}
|
// OpenSooqTask
//
// Created by Qais Alnammari on 7/6/19.
// Copyright © 2019 Qais Alnammari. All rights reserved.
//
import Alamofire
//MARK: - ApiEndPoints
public enum ApiEndPoints: String{
static let baseUrl = "https://api.foursquare.com/"
case getVenues = "v2/venues/explore"
}
//MARK: - Endpoint
protocol EndPointProtocol {
var address: String { get set }
var httpMethod: HTTPMethod { get set }
var headers: [String:String]? { get set }
}
struct EndPoint: EndPointProtocol {
//MARK: - Properties
var address: String
var httpMethod: HTTPMethod
var headers: [String:String]?
//MARK: - Initializers
/// Initializes an Endpoint object.
///
/// - Parameters:
/// - address: TIAApiEndPoints Enum
/// - httpMethod: HTTPMethod
/// - headers: [[String: String]], Optional with nil as default value.
init(address: ApiEndPoints, httpMethod: HTTPMethod, headers: [String:String]? = nil) {
self.address = address.rawValue
self.httpMethod = httpMethod
self.headers = headers
}
init(address: String, httpMethod: HTTPMethod, headers: [String:String]? = nil) {
self.address = address
self.httpMethod = httpMethod
self.headers = headers
}
}
|
//
// Message.swift
// handyUserDefaults
//
// Created by KimYong Gyun on 12/2/17.
// Copyright © 2017 haruair. All rights reserved.
//
import Foundation
class Message : NSObject {
var text = ""
var koala = "Koooo alaaaa"
var age = 100
let decimal: Int = 1
init(text: String) {
self.text = text
}
override init() {
}
}
|
//
// ClanCell.swift
// iClanBattles
//
// Created by ALEXIS-PC on 10/23/18.
// Copyright © 2018 ALEXIS-PC. All rights reserved.
//
import Foundation
import UIKit
import AlamofireImage
class ClanCell : UICollectionViewCell {
@IBOutlet weak var LogoClan: UIImageView!
@IBOutlet weak var NameClan: UILabel!
func updateValues(fromClan clan: Clan) {
if let url = URL(string: clan.urlToImage) {
LogoClan.af_setImage(withURL: url)
}
NameClan.text = clan.name
}
}
|
import Foundation
import UIKit
enum AppStoryBoard: String {
case Login, Main, Home, About, Contact, DetailView
var instance: UIStoryboard {
return UIStoryboard(name: self.rawValue, bundle: Bundle.main)
}
func viewController<T: UIViewController>(viewControllerClass: T.Type) -> T {
let storyBoardID = viewControllerClass.storyBoardID
return instance.instantiateViewController(withIdentifier: storyBoardID) as! T
}
}
|
//
// PaymentCoordinator.swift
// productsApp
//
// Created by Samanta Clara Coutinho Rondon do Nascimento on 2019-07-04.
// Copyright © 2019 Sam. All rights reserved.
//
import Foundation
import UIKit
protocol PaymentCDelegate: class {
func moveToHomeFlow(_ coordinator: PaymentCoordinator)
}
class PaymentCoordinator: Coordinator {
weak var delegate: PaymentCDelegate?
var childCoordinators: [Coordinator] = []
var rootViewController: UIViewController { return navigationController }
private lazy var navigationController: UINavigationController = {
let navigationController = UINavigationController()
navigationController.setNavigationBarHidden(true, animated: false)
return navigationController
}()
func start(cart: CartRealm) {
let viewModel = PaymentViewModel(cart: cart)
viewModel.coordinator = self
let payment = PaymentController(viewModel: viewModel)
navigationController.viewControllers.append(payment)
}
}
extension PaymentCoordinator: PaymentVMCoordinatorDelegate {
func moveForwardToHome(_ controller: PaymentController) {
delegate?.moveToHomeFlow(self)
}
}
|
//
// FoodHistoryTableViewController.swift
// CalorieMacroTracker
//
// Created by Faisal Syed on 12/26/15.
// Copyright © 2015 Faisal Syed. All rights reserved.
//
import UIKit
import CoreData
class FoodHistoryTableViewController: UITableViewController {
@IBOutlet var myTableVew: UITableView!
var foods : [Food] = []
override func viewDidLoad()
{
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "loadList:", name: "load", object: nil)
//Basic TableView setup
title = "Food Items"
myTableVew.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
//Grab the Entity
let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context = delegate.managedObjectContext
let request = NSFetchRequest(entityName: "Food")
var err: NSError?
do
{
foods = try context.executeFetchRequest(request) as! [Food]
}
catch let err1 as NSError
{
err = err1;
}
if(err != nil)
{
print("Problem with loading the data")
}
else
{
print("Successfully loaded the data")
myTableVew.reloadData()
}
}
func loadList(notification: NSNotification)
{
self.myTableVew.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return foods.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cellIdentifier = "Cell"
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: cellIdentifier)
let foodName = foods[indexPath.row].name
let foodProtein = foods[indexPath.row].protein
let foodCarbs = foods[indexPath.row].carbs
let foodFats = foods[indexPath.row].fats
let foodCalories = foods[indexPath.row].calories
//Update the cell
cell.textLabel?.text = foodName
cell.detailTextLabel?.text = "\(foodCalories!) calories \(foodCarbs!)g carbs \(foodFats!)g fats \(foodProtein!)g protein"
//cell.detailTextLabel?.text = "test label 123"
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
import Foundation
extension String
{
var length : Int {
return self.characters.count
}
var isValidEmail: Bool {
let emailRegex = "^([a-zA-Z0-9_\\-\\.+]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"
return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: self)
}
var isPhoneNumber: Bool {
let PHONE_REGEX = "^(?:(?:\\+?1\\s*(?:[.-]\\s*)?)?(?:\\(\\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\\s*\\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\\s*(?:[.-]\\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\\s*(?:[.-]\\s*)?([0-9]{4})(?:\\s*(?:#|x\\.?|ext\\.?|extension)\\s*(\\d+))?$"
return self.matchPattern(pattern: PHONE_REGEX, andOption: NSRegularExpression.Options.caseInsensitive)
}
func matchPattern(pattern : String, andOption option : NSRegularExpression.Options) -> Bool {
if(self.length == 0 || pattern.length == 0) {
return false
}
do {
let regex : NSRegularExpression = try NSRegularExpression(pattern: pattern,options: option)
let numberMatches = regex.numberOfMatches(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.length))
if(numberMatches == 1){
return true
}
else{
return false
}
}
catch let error as NSError {
print(error.localizedDescription)
return false
}
// return true
}
var isPassword:Bool {
let passwordRegEx = "^.*(?=.{8,})(?=..*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$"
return NSPredicate(format: "SELF MATCHES %@", passwordRegEx).evaluate(with: self)
}
func stringByRemovingAll(characters: [Character]) -> String {
return String(self.characters.filter({ !characters.contains($0) }))
}
}
|
//
// AlertUntil.swift
// AddContact
//
// Created by Huong Nguyen on 3/3/21.
//
import Foundation
import UIKit
class AlertUtil {
class func showAlertSave(from viewController: UIViewController, with title: String, message: String, completionYes: (@escaping (UIAlertAction) -> Void), completionNo: (@escaping (UIAlertAction) -> Void)) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let doneAction = UIAlertAction(title: "YES", style: .default, handler: completionYes)
alert.addAction(doneAction)
let cancelAction = UIAlertAction(title: "NO", style: .default, handler: completionNo)
alert.addAction(cancelAction)
viewController.present(alert, animated: true, completion: nil)
}
}
class func showAlert(from viewController: UIViewController, with title: String, message: String) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let doneAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(doneAction)
viewController.present(alert, animated: true, completion: nil)
}
}
class func showAlert(from viewController: UIViewController, with title: String, message: String, completion : (@escaping (UIAlertAction) -> Void)) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let doneAction = UIAlertAction(title: "OK", style: .cancel, handler: completion)
alert.addAction(doneAction)
viewController.present(alert, animated: true, completion: nil)
}
}
class func showAlertConfirm(from viewController: UIViewController, with title: String, message: String, completion : (@escaping (UIAlertAction) -> Void)) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let doneAction = UIAlertAction(title: "YES", style: .default, handler: completion)
alert.addAction(doneAction)
let cancelAction = UIAlertAction(title: "NO", style: .destructive, handler: nil)
alert.addAction(cancelAction)
viewController.present(alert, animated: true, completion: nil)
}
}
class func logout(from viewController: UIViewController, with title: String, message: String, completion : (@escaping (UIAlertAction) -> Void)) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let doneAction = UIAlertAction(title: "OK", style: .default, handler: completion)
alert.addAction(doneAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)
alert.addAction(cancelAction)
viewController.present(alert, animated: true, completion: nil)
}
}
class func showImagePicker(from viewController: UIViewController, with title: String, message: String, completionCamera: (@escaping (UIAlertAction) -> Void), completionPicture: (@escaping (UIAlertAction) -> Void)) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
let presentCamera = UIAlertAction(title: "Take Photo", style: .default, handler: completionCamera)
alert.addAction(presentCamera)
let presentPicture = UIAlertAction(title: "Choose Photo", style: .default, handler: completionPicture)
alert.addAction(presentPicture)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(cancel)
viewController.present(alert, animated: true, completion: nil)
}
}
class func deleteContact(from viewController: UIViewController, completion: (@escaping (UIAlertAction) -> Void)) {
DispatchQueue.main.async {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let delete = UIAlertAction(title: "Delete Contact", style: .destructive, handler: completion)
alert.addAction(delete)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(cancel)
viewController.present(alert, animated: true, completion: nil)
}
}
}
|
//
// ApiStore.swift
// TableViewTest
//
// Created by Gina Adamova on 2016-03-07.
// Copyright © 2016 Greenly. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
class APIStore{
private enum URL{
case BaseURL
case TargetURL
case ParamLimit
case ParamOffset
var part: String{
switch self{
case BaseURL:
return "https://api.twitch.tv/kraken"
case TargetURL:
return "/games/top"
case ParamLimit:
return "?limit="
case ParamOffset:
return "&offset="
}
}
}
static let sharedInstance = APIStore()
private init(){}
func fetchAllGamesForElement(element: Int, completion: (success: Bool, games: [Game]?) ->()){
Alamofire.request(
.GET,
"\(URL.BaseURL.part)\(URL.TargetURL.part)\(URL.ParamLimit.part)10\(URL.ParamOffset.part)\(element)")
.responseJSON { response in
guard response.result.isSuccess else {
completion(success: false, games: nil)
return
}
guard let dict = response.result.value as? [String: AnyObject], gameArray = dict["top"] as? [AnyObject] else { return }
var games = [Game]()
gameArray.forEach(){ element in
if let dictionary = element as? [String : AnyObject], game = self.gameFromDictionary(dictionary){
games.append(game)
}
}
completion(success: true, games: games)
}
}
func imageForString(string: String, with completion:((image: UIImage) ->())){
Alamofire.request(.GET, string)
.response(){
(_, _, data, error) in
if error == nil{
completion(image: UIImage(data: data!)!)
}
}
}
func gameFromDictionary(dictionary: [String: AnyObject]) -> Game?{
let game = Game()
guard let viewers = dictionary["viewers"]?.integerValue,
channels = dictionary["channels"]?.integerValue,
name = dictionary["game"]?["name"] as? String,
url = dictionary["game"]?["logo"]??["small"] as? String
else { return nil }
game.imageUrl = url
game.name = name
game.channels = channels
game.viewers = viewers
return game
}
} |
//
// FeedPostCell.swift
// Captioned
//
// Created by Przemysław Pająk on 22.06.2016.
// Copyright © 2016 Fearless Spider. All rights reserved.
//
import Foundation
import Material
import AlamofireImage
import MHPrettyDate
public protocol PostViewCellDelegate: class {
func didSelectAvatar(postViewCell: PostViewCell)
func didSelectLike(postViewCell: PostViewCell);
func didSelectComments(postViewCell: PostViewCell);
func didSelectShare(postViewCell: PostViewCell);
}
public class PostViewCell: UITableViewCell {
@IBOutlet var userNameLabel: UILabel!
@IBOutlet var postDateLabel: UILabel!
@IBOutlet var likesCountLabel: UILabel!
@IBOutlet var commentsCountLabel: UILabel!
@IBOutlet var shareCountLabel: UILabel!
@IBOutlet var avatarView: UIImageView!
@IBOutlet var mediaView: UIImageView!
@IBOutlet var likeButton: Button!
@IBOutlet var commentsButton: Button!
@IBOutlet var shareButton: Button!
@IBOutlet var commentsTableView: UITableView!
var post: Post!
public weak var delegate: PostViewCellDelegate?
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.post = nil
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
override public func awakeFromNib() {
super.awakeFromNib()
self.mediaView.clipsToBounds = true
if let postDateLabel = postDateLabel {
if let font = UIFont(name: "Lato-Italic.ttf", size: 10) {
postDateLabel.font = font
}
}
if let userNameLabel = userNameLabel {
if let font = UIFont(name: "Lato-Bold.ttf", size: 15) {
userNameLabel.font = font
}
}
if let likesCountLabel = likesCountLabel {
if let font = UIFont(name: "Lato-Bold.ttf", size: 11) {
likesCountLabel.font = font
}
}
if let commentsCountLabel = commentsCountLabel {
if let font = UIFont(name: "Lato-Bold.ttf", size: 11) {
commentsCountLabel.font = font
}
}
if let shareCountLabel = shareCountLabel {
if let font = UIFont(name: "Lato-Bold.ttf", size: 11) {
shareCountLabel.font = font
}
}
if let commentsTableView = commentsTableView {
commentsTableView.register(UINib(nibName: "CommentViewCell", bundle: nil), forCellReuseIdentifier: "comment")
}
if (avatarView != nil) {
avatarView.layer.cornerRadius = avatarView.frame.size.width / 2
avatarView.clipsToBounds = true
}
}
class func updateCellHeight(post: Post) -> CGFloat {
return 40 * CGFloat(post.comments_count)
}
@IBAction func likePressed(sender: AnyObject) {
delegate?.didSelectLike(postViewCell: self)
likeButton.backgroundColor = UIColor(red: 33/255, green: 150/255, blue: 243/255, alpha: 1)
}
@IBAction func commentsPressed(sender: AnyObject) {
delegate?.didSelectComments(postViewCell: self)
}
@IBAction func sharePressed(sender: AnyObject) {
delegate?.didSelectShare(postViewCell: self)
}
}
extension PostViewCell: UITableViewDelegate {
public func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 40
}
}
extension PostViewCell: UITableViewDataSource {
public func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
if self.post != nil {
return self.post.comments_count
}
return 0
}
public func tableView(_ tableView:UITableView, cellForRowAt indexPath:IndexPath) -> UITableViewCell {
let cell = self.commentsTableView.dequeueReusableCell(withIdentifier: "comment", for: indexPath as IndexPath) as! CommentViewCell
let comment: Comment = self.post.comments()[indexPath.row] as! Comment
let trimmedText: NSString = comment.content!.trimmingCharacters(in:NSCharacterSet.whitespacesAndNewlines) as NSString
//let textCheckingResults: NSMutableArray = NSMutableArray();
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.left
var fontBold = UIFont.boldSystemFont(ofSize: 15.0)
if let font = UIFont(name: "Lato-Bold.ttf", size: 15.0) {
fontBold = font
}
var fontRegular = UIFont.systemFont(ofSize: 15.0)
if let font = UIFont(name: "Lato-Regular.ttf", size: 15.0) {
fontRegular = font
}
let blue:UIColor = UIColor(red: 33/255, green: 150/255, blue: 243/255, alpha: 1)
let gray:UIColor = UIColor.colorWithHex("A2A2A2")!
let black:UIColor = UIColor.black
let muttableString = NSMutableAttributedString()
let nameAttributes = [NSAttributedStringKey.paragraphStyle:paragraphStyle,
NSAttributedStringKey.font:fontBold,
NSAttributedStringKey.foregroundColor:blue] as [NSAttributedStringKey : Any]
let contentAttributes = [NSAttributedStringKey.paragraphStyle:paragraphStyle,
NSAttributedStringKey.font:fontRegular,
NSAttributedStringKey.foregroundColor:black] as [NSAttributedStringKey : Any]
let dateAttributes = [NSAttributedStringKey.paragraphStyle:paragraphStyle,
NSAttributedStringKey.font:fontRegular,
NSAttributedStringKey.foregroundColor:gray] as [NSAttributedStringKey : Any]
let nameString = NSAttributedString(
string: comment.from().fullname(),
attributes: nameAttributes)
muttableString.append(nameString)
let contentString = NSAttributedString(
string: " " + (trimmedText as String) + " ",
attributes: contentAttributes)
muttableString.append(contentString)
let dateString = NSAttributedString(
string: MHPrettyDate.prettyDate(from: comment.postDate() as Date!, with:MHPrettyDateLongRelativeTime),
attributes: dateAttributes)
muttableString.append(dateString)
cell.commentContentLabel.setText(muttableString)
cell.layoutIfNeeded()
return cell
}
}
|
import Foundation
extension NSObject {
static var typeName: String {
return String(describing: self)
}
}
|
//
// CardCollectionService.swift
// DB
//
// Created by Danny Huang on 3/6/15.
// Copyright (c) 2015 Chugga. All rights reserved.
//
import Foundation
class CardCollectionService: NSObject {
/**
a class method to get a whole card collection
it will get the amount of classes back from the initial query, loop through the classes and add it to card collection
:param: completion a block to run after getting the collection
*/
class func wholeCardCollection(completion: (collection: Collection, error: NSError!) -> Void) {
var classQuery = PFQuery(className: "Collection")
classQuery.findObjectsInBackgroundWithBlock { (classes:[AnyObject]?, error:NSError?) -> Void in
if error == nil {
var collection = Collection()
for classType in classes! {
let setClass = classType as! PFObject
self.getCardsWithClass(setClass, completion: { (cardSet: CardSet!, error: NSError!) -> Void in
if error == nil {
collection.wholeCardSet.append(cardSet)
if collection.wholeCardSet.count == 9 {
completion(collection: collection, error: nil)
}
}
})
}
}
}
}
/**
receives a PFObject and run a query to parse to get back the cards for given class
:param: setClass the given class to get cards to
:param: completion a block with a return of Cardset
*/
class func getCardsWithClass(setClass: PFObject, completion: (cardSet: CardSet!, error: NSError!) -> Void) {
var query = PFQuery(className: setClass["setName"] as! String!)
query.findObjectsInBackgroundWithBlock { (cards: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
var cardSet = CardSet()
cardSet.cards = cards as! Array
cardSet.setName = setClass["setName"] as! String!
completion(cardSet: cardSet, error: nil)
}
else {
completion(cardSet: nil, error: error)
}
}
}
override init () {
}
}
|
//
// LoginViewController.swift
// Hipstagram
//
// Created by Kyle Wilson on 2/24/16.
// Copyright © 2016 Bluyam Inc. All rights reserved.
//
import UIKit
import Parse
class LoginViewController: UIViewController {
@IBOutlet var userNameField: UITextField!
@IBOutlet var passwordField: UITextField!
@IBOutlet var signInButton: UIButton!
@IBAction func textBoxDeselected(sender: AnyObject) {
view.endEditing(true)
}
@IBAction func signInPressed(sender: AnyObject) {
PFUser.logInWithUsernameInBackground(userNameField.text!, password: passwordField.text!) { (user:PFUser?, error: NSError?) -> Void in
if user != nil {
print("Login successful!")
self.performSegueWithIdentifier("LoginSegue", sender: nil)
}
else {
print("Login unsuccessful: \(error!.localizedDescription)")
}
}
}
@IBAction func signUpPressed(sender: AnyObject) {
let user = PFUser()
user.username = userNameField.text
user.password = passwordField.text
user.signUpInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
if success {
print("We created a user!")
self.performSegueWithIdentifier("LoginSegue", sender: nil)
}
else {
print("Failed to create a user: \(error!.localizedDescription)")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// set status bar appearance
self.setNeedsStatusBarAppearanceUpdate()
// set background image to background color
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "land")!)
// styling text fields and placeholders
let usernameBorder = CALayer()
let uwidth = CGFloat(1)
usernameBorder.borderColor = UIColor.lightGrayColor().CGColor
usernameBorder.frame = CGRect(x: 0, y: userNameField.frame.size.height - uwidth, width: userNameField.frame.size.width, height: userNameField.frame.size.height)
usernameBorder.borderWidth = uwidth
userNameField.layer.addSublayer(usernameBorder)
userNameField.layer.masksToBounds = true
let passwordBorder = CALayer()
let pwidth = CGFloat(1)
passwordBorder.borderColor = UIColor.lightGrayColor().CGColor
passwordBorder.frame = CGRect(x: 0, y: userNameField.frame.size.height - pwidth, width: userNameField.frame.size.width, height: userNameField.frame.size.height)
passwordBorder.borderWidth = pwidth
passwordField.layer.addSublayer(passwordBorder)
passwordField.layer.masksToBounds = true
let usernamePlaceholder = NSAttributedString(string: "Username", attributes: [NSForegroundColorAttributeName:UIColor.lightGrayColor()])
userNameField.attributedPlaceholder = usernamePlaceholder
let passwordPlaceholder = NSAttributedString(string: "Password", attributes: [NSForegroundColorAttributeName:UIColor.lightGrayColor()])
passwordField.attributedPlaceholder = passwordPlaceholder
// styling sign in button
signInButton.layer.cornerRadius = 20
signInButton.clipsToBounds = true
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// SpeechToTextVCTest.swift
// iASLUITests
//
// Created by Likhon Gomes on 4/18/20.
// Copyright © 2020 Y Media Labs. All rights reserved.
//
import XCTest
class SpeechToTextVCTest: 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.
}
///Test to check if the speech to text can recognize voice and turn it to text by populating it to the text view
func testSoundRecorder(){
}
///Test the path back to the main view controller by tapping on live buton
func testGoingBackToTheMainViewControllerByButtonTap(){
}
///Test the path back to the main view controller by changing device orientation
func testGoingBackToTheMainViewControllerByOrientationChange(){
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
|
//
// EventMarkerView.swift
// Volunteer Opportunity Tracker
//
// Created by Cindy Zhang on 3/7/18.
// Copyright © 2018 Cindy Zhang. All rights reserved.
//
import Foundation
import MapKit
class EventMarkerView: MKMarkerAnnotationView {
override var annotation: MKAnnotation? {
willSet {
// 1
guard let event = newValue as? EventAnnotation else { return }
canShowCallout = true
calloutOffset = CGPoint(x: -5, y: 5)
rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
// 2
markerTintColor = event.markerTintColor
// glyphText = String(artwork.discipline.first!)
if let imageName = event.imageName {
glyphImage = UIImage(named: imageName)
} else {
glyphImage = nil
}
}
}
}
class EventView: MKAnnotationView {
override var annotation: MKAnnotation? {
willSet {
guard let eventAnnotation = newValue as? EventAnnotation else {return}
canShowCallout = true
calloutOffset = CGPoint(x: -5, y: 5)
let mapsButton = UIButton(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 30, height: 30)))
mapsButton.setBackgroundImage(UIImage(named: "GetDirectionsIcon"), for: UIControlState())
rightCalloutAccessoryView = mapsButton
if let imageName = eventAnnotation.imageName { image = UIImage(named: imageName) }
else { image = nil }
}
}
}
|
//
// OrderService.swift
// caffinho-iOS
//
// Created by Rafael M. A. da Silva on 09/06/16.
// Copyright © 2016 venturus. All rights reserved.
//
import Foundation
import ObjectMapper
class OrderService:SessionService {
//TODO turn this variable private us only get to fetch it
var order:Order?
let preferences = NSUserDefaults.standardUserDefaults()
struct ServiceKey {
static let href = "href"
static let orderURL = 2
static let allReceipts = "ALL_RECEIPTS"
static let customerName = "CUSTOMER_NAME"
}
private let orderLimitValue = 500
private var menu = Menu()
private var loaded = false
private var restaurant = Restaurant()
private var task: NSURLSessionDataTask?
private func createNewOrderWithItem(item:Item) {
order = Order(customer: Customer(), deliveryType: "takeAway", restaurant: restaurant.name, customName: "Hard Coded", deliveryTime: "0", currency: restaurant.currency, pin: nil)
order?.items = [Item]()
order?.customer.name = loadCustomerName()
order?.items.append(item)
}
func numberOfOrderItems() -> Int {
if let _ = order {
return order!.items.count
}else{
return 0
}
}
func addItem(item:Item) -> Bool {
let itemCopy = item.copy() as! Item
loadVariant(itemCopy)
if let _ = order {
order?.items.append(itemCopy)
} else {
createNewOrderWithItem(itemCopy)
}
let capability = checkOrderCapabilityLimit(true)
return capability
}
func checkOrderCapabilityLimit(menuItem: Bool) -> Bool{
let orderPrice = Int(totalOrderPrice())
if orderPrice > orderLimitValue {
if menuItem {
let itemsCount = order?.items.count
let lastIndexPath = NSIndexPath(forRow: itemsCount! - 1, inSection: 0)
removeItemAtIndexPath(lastIndexPath.row)
}
return false
}
return true
}
private func loadVariant(item:Item){
if (item.variant != nil){
if let variant = preferences.valueForKey(item.name) as? String {
item.variant?.chosen = Mapper<Option>().map(variant)!
print("LOADED: " + (item.variant?.chosen.name)!)
}
}
}
func getOrderItemAtIndexPath(indexPath:NSIndexPath) -> Item? {
if let _ = order {
return order!.items[indexPath.row]
}else{
return nil
}
}
func removeItemAtIndexPath(indexPath: Int) {
order?.items.removeAtIndex(indexPath)
totalOrderPrice()
}
func totalOrderPrice() -> String {
if let items = order?.items {
let prices = items.map{totalPriceforItem($0)}.filter({$0 != nil}).map{$0!}
let totalPrice = prices.reduce(0, combine: +)
order?.price = String(totalPrice)
return String(totalPrice)
} else {
order?.price = "0"
return "0"
}
}
func orderCurrency() -> String {
return restaurant.currency
}
private func totalPriceforItem(item: Item) -> Int? {
if Int(item.takeAwayPrice) == nil { return nil }
let extras = item.extras
.filter{ $0.checked }
.map{ Int($0.price) }
.filter{ $0 != nil }
.map{ $0! }
if item.variant != nil && item.variant!.chosen.name != "" {
return Int(item.takeAwayPrice)! + extras.reduce(0, combine: +) + Int((item.variant?.chosen.price)!)!
}else{
return Int(item.takeAwayPrice)! + extras.reduce(0, combine: +)
}
}
init(sessionManager: SessionManager, restaurant:Restaurant) {
super.init(sessionManager: sessionManager)
self.restaurant = restaurant
}
private func removeUncheckedExtras() {
if let _ = order?.items {
for item in (order?.items)! {
item.extras = item.extras.filter({$0.checked == true})
}
}
}
func postCheckout() {
removeUncheckedExtras()
print("\(self.order?.toJSONString())")
let url = URLBuilder().build(restaurant.links[ServiceKey.orderURL][ServiceKey.href].string!)
let request = Request(urlString: url, parameters: nil, body: order?.toJSONString(), method: Request.Method.POSTWITHJSON)
task = dispatchRequest(request)
}
override func handleSuccess(task: NSURLSessionDataTask, response: AnyObject) {
saveOrderAsReceiptAndClean()
handleResponse(response)
}
override func handleFailure(task: NSURLSessionDataTask, error: NSError) {
dispatch_async(dispatch_get_main_queue()) {
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.postNotificationName(OrderServiceNotification.failed, object: error)
}
}
private func handleResponse(response: AnyObject) {
loaded = true
dispatch_async(dispatch_get_main_queue()) {
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.postNotificationName(OrderServiceNotification.success, object: nil)
}
}
}
// MARK: - Persist Customer Name
extension OrderService {
func saveCustomerName() {
self.preferences.setValue(self.order?.customer.name, forKey: ServiceKey.customerName)
}
func loadCustomerName() -> String {
return ((preferences.valueForKey(ServiceKey.customerName) as? String) != nil) ? (preferences.valueForKey(ServiceKey.customerName) as? String)! : ""
}
}
// MARK: - Receipts
extension OrderService {
func clearOrderWhenRestaurantChanges(restaurant:Restaurant) {
self.restaurant = restaurant
order = nil
}
func saveOrderAsReceiptAndClean() {
print("save order receipt")
let receiptService = ReceiptService()
order?.orderPlaceTime = generatePlaceOrderTimeStamp()
receiptService.saveOrderAsReceiptAndClean(order!)
order = nil
}
func generatePlaceOrderTimeStamp() -> String {
let now = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm"
return formatter.stringFromDate(now)
}
}
// MARK: - Notifications
struct OrderServiceNotification {
static let success = "OrderServiceSuccessNotification"
static let failed = "OrderServiceFailedNotification"
}
|
//
// DataTableViewCell.swift
// BasicTableView
//
// Created by Ryo Makabe on 2016-08-04.
// Copyright © 2016 ryomakabe. All rights reserved.
//
import UIKit
class DataTableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: 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
}
}
|
//
// MasterView.swift
// SpaceX
//
// Created by Paul Manser on 2/12/19.
// Copyright © 2019 Paul Manser. All rights reserved.
//
import SwiftUI
struct MasterView: View {
@ObservedObject var launchRepository: LaunchRepositoryModel
var body: some View {
List {
Section(header: Text("Options"))
{
SortView(launchRepository: launchRepository)
FilterView(launchRepository: launchRepository)
}
ForEach(launchRepository.groupedLaunches) { grp in
Section(header: Text(grp.name))
{
ForEach(grp.items) { launch in
if ((self.launchRepository.filterIndex == 0) ||
((self.launchRepository.filterIndex == 1) && launch.launchSuccess) ||
((self.launchRepository.filterIndex == 2) && !launch.launchSuccess))
{
NavigationLink(
destination: DetailView(selectedLaunch: launch)
) {
Text("\(launch.missionName)")
}
}
}
}
}
}
}
}
|
// Copyright 2018, Oath Inc.
// Licensed under the terms of the MIT License. See LICENSE.md file in project root for terms.
import Foundation
import CoreMedia
import PlayerCore
import VideoRenderer
public typealias Progress = PlayerCore.Progress
extension Player {
public struct Properties {
public struct Playlist {
public let hasNextVideo: Bool
public let hasPrevVideo: Bool
public let count: Int
public let currentIndex: Int
}
public let playlist: Playlist
let isPlaybackInitiated: Bool
let dimensions: CGSize?
public let isAutoplayEnabled: Bool
public let isMuted: Bool
public let isVPAIDMuted: Bool
public let isSessionCompleted: Bool
let session: PlayerSession
let adSessionID: UUID
let vpaidDocument: URL
struct PlayerSession {
let age: Age
struct Age {
let seconds: TimeInterval
let milliseconds: String
}
let playback: Playback
struct Playback {
let id: UUID
let duration: TimeInterval
let stallRecords: [StallRecord]
struct StallRecord {
// miliseconds
let duration: Int
let timestamp: TimeInterval
}
let intentTime: TimeInterval?
let intentElapsedTime: TimeInterval?
}
}
public enum PlaybackItem {
public struct Available {
public let model: PlayerCore.Model.Video.Item
public let hasActiveAds: Bool
public let midrollPrefetchingOffset: Int
public let playedAds: Set<UUID>
public let midrolls: [PlayerCore.Ad.Midroll]
public let adSkipOffset: Int?
let mp4AdCreative: PlayerCore.AdCreative.MP4?
let vpaidAdCreative: PlayerCore.AdCreative.VPAID?
public let isAdPlaying: Bool
public let content: Video
public let ad: Video
public let url: URL
public let title: String
public let videoAngles: (horizontal: Float, vertical: Float)?
let isClickThroughToggled: Bool
let vpaidClickthrough: URL?
public let isLastVideo: Bool
public let isReplayable: Bool
}
public struct Video {
public let isStreamPlaying: Bool
public let isPlaying: Bool
public let isPaused: Bool
public let isSeeking: Bool
public let isSeekable: Bool
public let isLoading: Bool
public let isBuffering: Bool
public enum ActionInitiated { case play, pause, unknown }
public let actionInitiated: ActionInitiated
public enum Status {
case undefined
case ready
case failed(Error)
var isDefined: Bool {
guard case .undefined = self else { return true }
return false
}
var isReady: Bool {
guard case .ready = self else { return false }
return true
}
var isUndefined: Bool {
guard case .undefined = self else { return false }
return true
}
}
public let status: Status
// Average video bitrate measured in kbit per seconds
public let averageBitrate: Double?
/// `Time` information about video.
public enum Time {
case unknown
public var isUnknown: Bool {
guard case .unknown = self else { return false }
return true
}
case live(Live)
public var live: Live? {
guard case let .live(live) = self else { return nil }
return live
}
public var isLive: Bool {
return live != nil
}
case `static`(Static)
public var `static`: Static? {
guard case let .`static`(`static`) = self else { return nil }
return `static`
}
public var isStatic: Bool {
return `static` != nil
}
public struct Live {
public let isFinished: Bool
}
public struct Static {
public let progress: Progress
public let currentCMTime: CMTime?
public let current: Double?
public let duration: Double
public let hasDuration: Bool
public let remaining: Double
public let lastPlayedDecile: Int
public let lastPlayedQuartile: Int
public let isFinished: Bool
}
}
public let time: Time
public struct BufferInfo {
let progress: Progress
let time: CMTime
let milliseconds: Int
}
public let bufferInfo: BufferInfo
public enum PictureInPictureMode {
case unsupported, possible, impossible, active
}
public let pictureInPictureMode: PictureInPictureMode
public let controlsAnimationSupport: Bool
public enum ContentFullScreenMode {
case inactive, active, disabled
}
public let contentFullScreen: ContentFullScreenMode
public enum AirPlay {
case inactive, restricted, active, disabled
public var isAble: Bool {
return self != .restricted && self != .disabled
}
}
public let airPlay: AirPlay
public enum Subtitles {
case `internal`(MediaGroup?)
case external(External)
public struct External {
public let isActive: Bool
public let isLoading: Bool
public let isLoaded: Bool
public let text: String
public let group: MediaGroup
}
}
public struct MediaGroup {
public let options: [Option]
public struct Option {
public let id: UUID
public let displayName: String
public let selected: Bool
}
public static func empty() -> MediaGroup {
return MediaGroup(options: [])
}
public var selectedOption: Option? {
return options.first { $0.selected }
}
}
public let audible: MediaGroup
public let legible: Subtitles
}
case available(Available)
public struct Unavailable {
public let reason: String
}
case unavailable(Unavailable)
}
public let item: PlaybackItem
public var playbackItem: PlaybackItem.Available? {
guard case .available(let available) = item else { return nil }
return available
}
public var errorItem: PlaybackItem.Unavailable? {
guard case .unavailable(let unavailable) = item else { return nil }
return unavailable
}
// Measured from 0 - 100
public let volume: Int
}
}
func perform<T>(code: () throws -> T) rethrows -> T {
return try code()
}
|
//
// RegisterViewController.swift
// Lex
//
// Created by nbcb on 2016/12/13.
// Copyright © 2016年 ZQC. All rights reserved.
//
import UIKit
class RegisterViewController: BaseViewController {
@IBOutlet weak var mobileField: UITextField!
@IBOutlet weak var vertifyButton: UIButton!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
mobileField.becomeFirstResponder()
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// HomeTestsTableViewCell.swift
// AdventistEduc
//
// Created by Andre Luiz Pimentel on 12/07/16.
// Copyright © 2016 Andre Pimentel. All rights reserved.
//
import UIKit
class HomeTestsTableViewCell: UITableViewCell {
@IBOutlet weak var labelDiscipline: UILabel!
@IBOutlet weak var labelDateTest: UILabel!
@IBOutlet weak var labelTest: 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
}
}
|
//
// GroupFitCellTableViewCell.swift
// runnur
//
// Created by Sonali on 04/07/16.
// Copyright © 2016 Sonali. All rights reserved.
//
import UIKit
class GroupFitCellTableViewCell: UITableViewCell
{
@IBOutlet var questionLabel: UILabel!
@IBOutlet var answerLabel: UILabel!
@IBOutlet var expandCollapseImageView: UIImageView!
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
}
}
|
//
// AboutView.swift
// MenuBarTimeTracker
//
// Created by Aiur on 28.05.2021.
//
import SwiftUI
struct AboutView: View {
var body: some View {
Text("Made via SwiftUI 2")
.padding()
}
}
|
//
// File.swift
// MapBoxTest
//
// Created by YanQi on 2020/04/28.
// Copyright © 2020 Prageeth. All rights reserved.
//
import RxSwift
import RxCocoa
class GetUserLocationsViewModel: ViewModelType {
struct Input {
let groupIdBeginTrigger: Driver<String?>
}
struct Output {
let locations: Driver<[Location]>
let error: Driver<Error>
}
struct State {
let error = ErrorTracker()
}
private let locationModel: LocationModel
init(with locationModel: LocationModel) {
self.locationModel = locationModel
}
func transform(input: GetUserLocationsViewModel.Input) -> GetUserLocationsViewModel.Output {
let state = State()
let locations: Driver<[Location]> = input.groupIdBeginTrigger
.flatMapLatest { [unowned self] _ in
return self.locationModel
.getUserLocations()
.trackError(state.error)
.asDriverOnSkipError()
}
return GetUserLocationsViewModel.Output(locations: locations, error: state.error.asDriver())
}
}
|
//
// CGViewLayout.swift
// CGPhoto
//
// Created by DY on 2017/11/27.
// Copyright © 2017年 DY. All rights reserved.
//
/**
// 创建约束
// 添加到视图
*/
import Foundation
@available(iOS 9.0, *)
// MARK: - NSLayoutXAxisAnchor 类型约束
extension UIView {
func cg_x_constraint(anthorType1: CGViewLayoutXAxisAnchorType, targetView: UIView, anthorType2: CGViewLayoutXAxisAnchorType, relation: CGViewLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
self.setupSupportAutoLayout()
var axisAnchor1 = self.cg_layoutXAxisAnchor(type: anthorType1)
var axisAnchor2 : NSLayoutXAxisAnchor
let constraint : NSLayoutConstraint
if #available(iOS 11.0, *) {
axisAnchor2 = targetView.safeAreaLayoutGuide.cg_layoutXAxisAnchor(type: anthorType2)
} else {
axisAnchor2 = targetView.cg_layoutXAxisAnchor(type: anthorType2)
}
if anthorType1 == .trailing || anthorType1 == .right {
swap(&axisAnchor1, &axisAnchor2)
}
switch relation {
case .lessThanOrEqual:
constraint = axisAnchor1.constraint(lessThanOrEqualTo: axisAnchor2, constant: constant)
case .equal:
constraint = axisAnchor1.constraint(equalTo: axisAnchor2, constant: constant)
case .greaterThanOrEqual:
constraint = axisAnchor1.constraint(greaterThanOrEqualTo: axisAnchor2, constant: constant)
}
constraint.isActive = true
return constraint
}
}
@available (iOS 9.0, *)
// MARK: - NSLayoutYAxisAnchor 类型约束
extension UIView {
func cg_y_constraint(anthorType1: CGViewLayoutYAxisAnchorType, targetView: UIView, anthorType2: CGViewLayoutYAxisAnchorType, relation: CGViewLayoutRelation, constant: CGFloat) -> NSLayoutConstraint {
self.setupSupportAutoLayout()
var axisAnchor1 = self.cg_layoutYAxisAnchor(type: anthorType1)
var axisAnchor2 : NSLayoutYAxisAnchor
let constraint : NSLayoutConstraint
if #available(iOS 11.0, *) {
axisAnchor2 = targetView.safeAreaLayoutGuide.cg_layoutYAxisAnchor(type: anthorType2)
} else {
axisAnchor2 = targetView.cg_layoutYAxisAnchor(type: anthorType2)
}
if anthorType1 == .bottom {
swap(&axisAnchor1, &axisAnchor2)
}
switch relation {
case .lessThanOrEqual:
constraint = axisAnchor1.constraint(lessThanOrEqualTo: axisAnchor2, constant: constant)
case .equal:
constraint = axisAnchor1.constraint(equalTo: axisAnchor2, constant: constant)
case .greaterThanOrEqual:
constraint = axisAnchor1.constraint(greaterThanOrEqualTo: axisAnchor2, constant: constant)
}
constraint.isActive = true
return constraint
}
}
@available (iOS 9.0, *)
// MARK: - NSLayoutDimension 类型约束
extension UIView {
func cg_constraint(dimensionType1: CGViewLayoutDimension, targetView: UIView, dimensionType2: CGViewLayoutDimension, relation: CGViewLayoutRelation, multiplier: CGFloat, constant: CGFloat) -> NSLayoutConstraint {
self.setupSupportAutoLayout()
let dimension1 = self.cg_layout(dimension: dimensionType1)
let dimension2 : NSLayoutDimension
let constraint : NSLayoutConstraint
if #available(iOS 11.0, *) {
dimension2 = targetView.safeAreaLayoutGuide.cg_layout(dimension: dimensionType2)
} else {
dimension2 = targetView.cg_layout(dimension: dimensionType2)
}
switch relation {
case .lessThanOrEqual:
constraint = dimension1.constraint(lessThanOrEqualTo: dimension2, multiplier: multiplier, constant: constant)
case .equal:
constraint = dimension1.constraint(equalTo: dimension2, multiplier: multiplier, constant: constant)
case .greaterThanOrEqual:
constraint = dimension1.constraint(greaterThanOrEqualTo: dimension2, multiplier: multiplier, constant: constant)
}
constraint.isActive = true
return constraint
}
}
@available (iOS 6.0, *)
// MARK: - 直接使用 NSLayoutConstraint
extension UIView {
/// 使用 NSLayoutConstraint 类来处理约束
func cg_constraint(type1: CGViewLayoutAnchorType, targetView: UIView, type2: CGViewLayoutAnchorType, relation: CGViewLayoutRelation, multiplier: CGFloat, constant: CGFloat) -> NSLayoutConstraint? {
guard let commonView = self.cg_searchCommonSuperview(with: targetView) else {
assert(false, "视图self和targetView需要公共视图")
return nil
}
self.setupSupportAutoLayout()
let constraint = self.cg_constraint(type1: type1, targetObject: targetView, type2: type2, relation: relation, multiplier: multiplier, constant: constant)
commonView.addConstraint(constraint)
return constraint
}
}
// MARK: - 一般在 iOS 7 到 iOS 11
@available(iOS, introduced: 7.0, deprecated: 11.0)
// MARK: - 设置UIView 与 UIViewController 之间的约束
extension UIView {
enum CGLayoutGuideType {
case top
case bottom
}
func cg_layoutGuide(type: CGLayoutGuideType, viewController: UIViewController, relation: CGViewLayoutRelation, multiplier: CGFloat, constant: CGFloat) -> NSLayoutConstraint? {
guard let commonView = self.cg_searchCommonSuperview(with: viewController.view) else {
return nil
}
self.setupSupportAutoLayout()
let layoutGuide : Any
let type2 : CGViewLayoutAnchorType
if type == .top {
layoutGuide = viewController.topLayoutGuide
type2 = .bottom
}else {
layoutGuide = viewController.bottomLayoutGuide
type2 = .top
}
let constraint = self.cg_constraint(type1: .top, targetObject: layoutGuide, type2: type2, relation: relation, multiplier: multiplier, constant: constant)
commonView.addConstraint(constraint)
return constraint
}
}
fileprivate extension UIView {
func cg_constraint(type1: CGViewLayoutAnchorType, targetObject: Any, type2: CGViewLayoutAnchorType, relation: CGViewLayoutRelation, multiplier: CGFloat, constant: CGFloat) -> NSLayoutConstraint {
let attribute1 = type1.layoutAttribute()
let attribute2 = type2.layoutAttribute()
let constantValue : CGFloat
var relationValue = relation.relation()
if attribute1 == .trailing || attribute1 == .right || attribute1 == .bottom {
constantValue = constant * -1
if relationValue != .equal {
relationValue = (relationValue == .greaterThanOrEqual ? .lessThanOrEqual : .greaterThanOrEqual)
}
}else {
constantValue = constant
}
let constraint = NSLayoutConstraint.init(item: self, attribute: attribute1, relatedBy: relationValue, toItem: targetObject, attribute: attribute2, multiplier: multiplier, constant: constantValue)
return constraint
}
}
extension UIView {
func setupSupportAutoLayout() {
if self.translatesAutoresizingMaskIntoConstraints {
self.translatesAutoresizingMaskIntoConstraints = false
}
}
}
|
//
// BackgroundView.swift
// pang
//
// Created by 김종원 on 2020/11/17.
//
import SwiftUI
struct BackgroundView: View {
var body: some View {
GlassBackgroundStyle()
.onTapGesture {
self.hideKeyboard()
}
}
}
struct BackgroundView_Previews: PreviewProvider {
static var previews: some View {
BackgroundView()
}
}
|
//
// Observable.swift
// CoreDataKit
//
// Created by Mathijs Kadijk on 31-10-14.
// Copyright (c) 2014 Mathijs Kadijk. All rights reserved.
//
import CoreData
public enum ObservedAction<T:NSManagedObject> {
case updated(T)
case refreshed(T)
case inserted(T)
case deleted
public func value() -> T? {
switch self {
case let .updated(val):
return val
case let .refreshed(val):
return val
case let .inserted(val):
return val
case .deleted:
return nil
}
}
}
public class ManagedObjectObserver<T:NSManagedObject>: NSObject {
public typealias Subscriber = (ObservedAction<T>) -> Void
public let observedObject: T
let context: NSManagedObjectContext
var notificationObserver: NSObjectProtocol?
var subscribers: [Subscriber]
/**
Start observing changes on a `NSManagedObject` in a certain context.
- parameter observeObject: Object to observe
- parameter inContext: Context to observe the object in
*/
public init(observeObject originalObserveObject: T, inContext context: NSManagedObjectContext) {
// Try to convert the observee to the given context, may fail because it's not yet saved
let observeObject = try? context.find(T.self, managedObjectID: originalObserveObject.objectID)
self.observedObject = observeObject ?? originalObserveObject
self.context = context
self.subscribers = [Subscriber]()
super.init()
notificationObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name.NSManagedObjectContextObjectsDidChange, object: context, queue: nil) { [weak self] notification in
guard let strongSelf = self else {
return
}
context.perform {
if strongSelf.subscribers.isEmpty {
return
}
do {
let convertedObject = try context.find(T.self, managedObjectID: strongSelf.observedObject.objectID)
if let updatedObjects = (notification as NSNotification).userInfo?[NSUpdatedObjectsKey] as? NSSet {
if updatedObjects.contains(convertedObject) {
strongSelf.notifySubscribers(.updated(convertedObject))
}
}
if let refreshedObjects = (notification as NSNotification).userInfo?[NSRefreshedObjectsKey] as? NSSet {
if refreshedObjects.contains(convertedObject) {
strongSelf.notifySubscribers(.refreshed(convertedObject))
}
}
if let insertedObjects = (notification as NSNotification).userInfo?[NSInsertedObjectsKey] as? NSSet {
if insertedObjects.contains(convertedObject) {
strongSelf.notifySubscribers(.inserted(convertedObject))
}
}
if let deletedObjects = (notification as NSNotification).userInfo?[NSDeletedObjectsKey] as? NSSet {
if deletedObjects.contains(convertedObject) {
strongSelf.notifySubscribers(.deleted)
}
}
}
catch {
}
}
}
}
deinit {
if let notificationObserver = notificationObserver {
NotificationCenter.default.removeObserver(notificationObserver)
}
}
fileprivate func notifySubscribers(_ action: ObservedAction<T>) {
for subscriber in self.subscribers {
subscriber(action)
}
}
/**
Subscribe a block that gets called when the observed object changes
- parameter changeHandler: The handler to call on change
- returns: Token you can use to unsubscribe
*/
public func subscribe(_ subscriber: @escaping Subscriber) -> Int {
subscribers.append(subscriber)
return subscribers.count - 1
}
/**
Unsubscribe a previously subscribed block
- parameter token: The token obtained when subscribing
*/
public func unsubscribe(token: Int) {
subscribers[token] = { _ in }
}
@available(*, unavailable, renamed: "unsubscribe(token:)")
public func unsubscribe(_ token: Int) {
fatalError()
}
}
|
//
// MountainRepositoryTest.swift
// MountainChallengeTests
//
// Created by Gustavo Miyamoto on 26/12/18.
// Copyright © 2018 Gustavo Miyamoto. All rights reserved.
//
import XCTest
import RxBlocking
@testable import MountainChallenge
class MountainRepositoryTest: XCTestCase {
private var repository: MountainRepository?
override func setUp() {
repository = YamapProvider.mountainDataSource
}
// MARK: Get mountains unit test
func testGetMountains() throws {
// Given
// ---
// When
let result = try repository?.getMountains().toBlocking().first()
// Then
XCTAssertEqual(result?.count, 50)
}
// MARK: Get mountain image unit test
func testGetMountainImage() throws {
// Given
let url = "https://cdn.yamap.co.jp/public/image2.yamap.co.jp/production/26250373"
// When
let result = try repository?.getMountainImage(url: url).toBlocking().first()
// Then
XCTAssertNotEqual(result, nil)
}
}
|
//
// ListIdeasUsecaseFactory.swift
// MyIdeas
//
// Created by Ronan Rodrigo Nunes on 06/12/15.
// Copyright © 2015 Ronan Rodrigo Nunes. All rights reserved.
//
import Foundation
import UIKit
class ListIdeasUsecaseFactory {
var gateway: IdeaGatewayProtocol
var presenter: ListIdeasPresenterProtocol
init() {
self.gateway = IdeaGatewayRealm()
self.presenter = ListIdeasPresenter()
}
func make() -> ListIdeasUsecase {
return ListIdeasUsecase(gateway: self.gateway, presenter: self.presenter)
}
} |
//
// ArtObjectsNetworkTests.swift
// RijksMuseumTests
//
// Created by Alexander Vorobjov on 1/2/21.
//
import XCTest
@testable import RijksMuseum
class ArtObjectsNetworkTests: XCTestCase {
func testEmpty() throws {
let session = try MockSession(json: "empty_art_objects")
let network = ArtObjectsNetworkImpl(session: session)
network.fetchHome { result in
switch result {
case .failure:
XCTAssert(false, "Failed to parse response")
case .success(let response):
XCTAssertTrue(response.isEmpty)
}
}
network.fetchSearch(query: "any") { result in
switch result {
case .failure:
XCTAssert(false, "Failed to parse response")
case .success(let response):
XCTAssertTrue(response.isEmpty)
}
}
}
func testSingle() throws {
let session = try MockSession(json: "single_art_object")
let network = ArtObjectsNetworkImpl(session: session)
network.fetchHome { result in
switch result {
case .failure:
XCTAssert(false, "Failed to parse response")
case .success(let response):
XCTAssertEqual(response.count, 1)
}
}
network.fetchSearch(query: "any") { result in
switch result {
case .failure:
XCTAssert(false, "Failed to parse response")
case .success(let response):
XCTAssertEqual(response.count, 1)
}
}
}
func testError() throws {
let requiredError = SessionError.connectionError
let session = MockSession { $0(.failure(requiredError)) }
let network = ArtObjectsNetworkImpl(session: session)
network.fetchHome { result in
switch result {
case .failure(let error):
XCTAssertEqual(error, requiredError)
case .success:
XCTAssert(false, "Should return error")
}
}
network.fetchSearch(query: "any") { result in
switch result {
case .failure(let error):
XCTAssertEqual(error, requiredError)
case .success:
XCTAssert(false, "Should return error")
}
}
}
func testDetails() throws {
let session = try MockSession(json: "details_night_watch")
let network = ArtObjectsNetworkImpl(session: session)
network.fetchDetails(objectNumber: ArtObjectNumber(stringLiteral: "-")) { result in
switch result {
case .failure:
XCTAssert(false, "Failed to parse response")
case .success(let response):
XCTAssertEqual(response.id, "en-SK-C-5")
XCTAssertEqual(response.title, "Night Watch, Militia Company of District II under the Command of Captain Frans Banninck Cocq")
XCTAssertEqual(response.credit, "On loan from the City of Amsterdam")
XCTAssertEqual(response.size, "h 379.5cm × w 453.5cm × w 337kg")
XCTAssertEqual(response.authorYearMaterial, "Rembrandt van Rijn (1606-1669), oil on canvas, 1642")
XCTAssertEqual(response.copyright, "test copyrightHolder")
}
}
}
}
|
//
// AlbumViewController.swift
// Nike RSS
//
// Created by Brodi Beartusk on 12/2/19.
// Copyright © 2019 Brodi Beartusk. All rights reserved.
//
import UIKit
/// Controller for showing Album details and button for viewing artist in iTunes
class AlbumViewController: UIViewController {
@IBOutlet weak var album: UILabel!
@IBOutlet weak var artist: UILabel!
@IBOutlet weak var genre: UILabel!
@IBOutlet weak var releaseDate: UILabel!
@IBOutlet weak var copyright: UILabel!
@IBOutlet weak var albumArt: UIImageView!
var result: Result?
/// open artist url in iTunes
@IBAction func viewInItunes(_ sender: Any) {
if let artistURL = result?.artistUrl {
NSLog("Opening artist URL: \(artistURL)")
if let musicURL = URL(string: artistURL) {
if UIApplication.shared.canOpenURL(musicURL) {
UIApplication.shared.open(musicURL, options: [:])
}
}
}
}
/// set result for album detail
func setAlbumDetail(result: Result) {
self.result = result
}
override func viewDidLoad() {
super.viewDidLoad()
// set view fields from result
if let result = self.result {
album.text = result.name
artist.text = result.artistName
// combine genres
let genresStrings = result.genres.map {$0.name}
let genres = genresStrings.joined(separator: ", ")
genre.text = genres
releaseDate.text = result.releaseDate
copyright.text = result.copyright
if let artworkURL = URL(string: result.artworkUrl100) {
albumArt.load(url: artworkURL)
}
}
}
}
|
//
// HomeViewController.swift
// eSponsorship
//
// Created by Jeremy Tay on 27/09/2017.
// Copyright © 2017 Jeremy Tay. All rights reserved.
//
import UIKit
import Firebase
import SideMenu
class HomeViewController: UIViewController {
@IBAction func signOut(_ sender: Any) {
self.navigationController?.navigationBar.barTintColor = UIColor.orange
confirmSignOutHandler()
}
// MARK: Category Selected
@IBAction func gamersButtonTapped(_ sender: Any) {
}
@IBAction func teamsButtonTapped(_ sender: Any) {
}
@IBAction func tournamentsButtonTapped(_ sender: Any) {
}
@IBAction func menuButtonTapped(_ sender: Any) {
print("Menu Button Tapped")
}
override func viewDidLoad() {
super.viewDidLoad()
sideMenuHandler()
self.title = "Game Ship"
}
}
extension HomeViewController {
func confirmSignOutHandler () {
let alert = UIAlertController(title: "Confirm Sign Out", message: "You are signing out from the application", preferredStyle: .alert)
let confirm = UIAlertAction(title: "Sign Out", style: .default) { (action) in
self.signOutHandler()
}
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(confirm)
alert.addAction(cancel)
present(alert,animated: true,completion: nil)
}
func signOutHandler(){
let mainStoryboard = UIStoryboard(name: "Auth", bundle: nil)
guard let targetVC = mainStoryboard.instantiateViewController(withIdentifier: "LoginViewController") as? LoginViewController else { return }
dismiss(animated: true, completion: nil)
self.present(targetVC, animated: true, completion: nil)
}
func sideMenuHandler () {
// Define the menus
let menuLeftNavigationController = UISideMenuNavigationController(rootViewController: MenuListViewController())
menuLeftNavigationController.leftSide = true
SideMenuManager.menuLeftNavigationController = menuLeftNavigationController
SideMenuManager.menuAddPanGestureToPresent(toView: self.navigationController!.navigationBar)
SideMenuManager.menuAddScreenEdgePanGesturesToPresent(toView: self.navigationController!.view)
}
/*
func pageMenuHandler(){
// Array to keep track of controllers in page menu
var controllerArray : [UIViewController] = []
// Create variables for all view controllers you want to put in the
// page menu, initialize them, and add each to the controller array.
// (Can be any UIViewController subclass)
// Make sure the title property of all view controllers is set
var gamersFeed : UIViewController = UIViewController(nibName: "GamersViewController", bundle: Bundle.main)
gamersFeed.title = "Gamers"
controllerArray.append(gamersFeed)
var tournamentsFeed : UIViewController = UIViewController(nibName: "TournamentsViewController", bundle: Bundle.main)
tournamentsFeed.title = "Tournament"
controllerArray.append(tournamentsFeed)
var teamsFeed : UIViewController = UIViewController(nibName: "TeamsViewController", bundle: Bundle.main)
teamsFeed.title = "Teams"
controllerArray.append(teamsFeed)
// Customize page menu to your liking (optional) or use default settings by sending nil for 'options' in the init
// Example:
var parameters: [CAPSPageMenuOption] = [
.menuItemSeparatorWidth(4.3),
.useMenuLikeSegmentedControl(true),
.menuItemSeparatorPercentageHeight(0.1)
]
// Initialize page menu with controller array, frame, and optional parameters
// pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRect (0.0, 0.0, self.view.frame.width, self.view.frame.height), pageMenuOptions: parameters)
let cgrectfigures = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: cgrectfigures , pageMenuOptions: parameters)
// Lastly add page menu as subview of base view controller view
// or use pageMenu controller in you view hierachy as desired
self.view.addSubview(pageMenu!.view)
}
*/
}
|
/*:
## App Exercise - Workout Functions
>These exercises reinforce Swift concepts in the context of a fitness tracking app.
A `RunningWorkout` struct has been created for you below. Add a method on `RunningWorkout` called `postWorkoutStats` that prints out the details of the run. Then create an instance of `RunningWorkout` and call `postWorkoutStats()`.
*/
struct RunningWorkout {
var distance: Double
var time: Double
var elevation: Double
func postWorkoutStats() {
print(distance, time, elevation)
}
}
var stats = RunningWorkout(distance: 3, time: 3, elevation: 3)
stats.postWorkoutStats()
/*:
A `Steps` struct has been created for you below, representing the day's step-tracking data. It has the goal number of steps for the day and the number of steps taken so far. Create a method on `Steps` called `takeStep` that increments the value of `steps` by one. Then create an instance of `Steps` and call `takeStep()`. Print the value of the instance's `steps` property before and after the method call.
*/
struct Steps {
var steps: Int
var goal: Int
mutating func takeSteps() {
steps += 1
}
}
var StepCount = Steps(steps: 4, goal: 600)
print(StepCount.steps)
let takeSteps = StepCount.takeSteps()
print(StepCount.steps)
//: [Previous](@previous) | page 6 of 10 | [Next: Exercise - Computed Properties and Property Observers](@next)
|
//
// OakTestCase.swift
// OakTests
//
// Created by Alex Catchpole on 16/05/2021.
//
import XCTest
import Resolver
class OakTestCase: XCTestCase {
override func setUp() {
Resolver.resetUnitTestRegistrations()
}
override func tearDown() {
Resolver.root = .test
}
}
|
//
// Currencies.swift
// Currencies
//
// Created by Jakub Hutny on 15.12.2016.
// Copyright © 2016 Jakub Hutny. All rights reserved.
//
import Foundation
struct Currency {
var name: String
var value: Double
}
|
//
// HopperAPIGetSignalByIdRequest.swift
// Cryptohopper-iOS-SDK
//
// Created by Kaan Baris Bayrak on 04/11/2020.
//
import Foundation
class HopperAPIGetSignalByIdRequest: HopperAPIRequest<HopperAPIGetSignalByIdResponse> {
convenience init(hopperId : String,signalId: Int) {
self.init()
self.changeUrlPath(path: "/v1" + "/hopper/\(hopperId)/signal")
}
override var httpMethod: HopperAPIHttpMethod {
return .GET
}
override var needsAuthentication: Bool {
return true
}
}
|
//
// TimePicker.swift
// J.Todo
//
// Created by JinYoung Lee on 2020/02/20.
// Copyright © 2020 JinYoung Lee. All rights reserved.
//
import Foundation
import UIKit
class TimePicker: UIView {
@IBOutlet private weak var datePicker: UIDatePicker?
private var backgroundDarkView: UIView?
var SelectDate: Date?
var SelectListener: ((Date) -> Void)?
override func awakeFromNib() {
datePicker?.setDate(Date(), animated: true)
}
func present() {
backgroundDarkView = UIView(frame: screenBounds)
backgroundDarkView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(hide)))
backgroundDarkView?.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.2)
screenRootViewController?.view.addSubview(backgroundDarkView ?? UIView(frame: screenBounds))
screenRootViewController?.view.addSubview(self)
backgroundDarkView?.alpha = 0
alpha = 0
frame.origin = CGPoint(x: 0 ,y: screenHeight/2)
UIView.animate(withDuration: 0.3, animations: {
self.alpha = 1
self.backgroundDarkView?.alpha = 1
}, completion: nil)
}
@objc private func hide() {
UIView.animate(withDuration: 0.3, animations: {
self.alpha = 0
self.backgroundDarkView?.alpha = 0
}, completion: { (success) in
self.backgroundDarkView?.removeFromSuperview()
self.removeFromSuperview()
})
}
@IBAction func selectTime() {
guard let selDate = SelectDate else { return }
let dateformatter = DateFormatter()
dateformatter.dateStyle = .none
dateformatter.timeStyle = .short
if let date = datePicker?.date {
let component = Calendar.current.dateComponents(in: TimeZone.current, from: date)
SelectListener?(Calendar.current.date(bySettingHour: component.hour!, minute: component.minute!, second: 0, of: selDate) ?? Date())
}
hide()
}
}
|
import Quick
import Nimble
@testable import BestPractices
class SoundTableViewCellSpec: QuickSpec {
override func spec() {
var subject: SoundTableViewCell!
var titleLabel: UILabel!
beforeEach {
subject = SoundTableViewCell()
titleLabel = UILabel()
subject.titleLabel = titleLabel
}
describe("Configuring a cell with a sound") {
beforeEach {
let sound = Sound(value: ["name": "title"])
subject.configureWithSound(sound: sound)
}
it("sets the title label for the cell") {
expect(subject.titleLabel.text).to(equal("title"))
}
}
}
}
|
//
// BillPayment.swift
// TrocoSimples
//
// Created by gustavo r meyer on 8/16/17.
// Copyright © 2017 gustavo r meyer. All rights reserved.
//
import Foundation
class BillPayment {
internal struct Keys {
static let barcode = "barcode"
static let amount = "amount"
static let dueDate = "dueDate"
static let promotionalCode = "promotionalCode"
}
// MARK: - Intance Properties
public var barcode: String
public var amount: Double
public var dueDate: Date?
public var promotionalCode: String
public init(barcode:String, amount: Double, dueDate: Date?
, promotionalCode: String) {
self.barcode = barcode
self.amount = amount
self.dueDate = dueDate
self.promotionalCode = promotionalCode
}
// MARK: - Object Lifecycle
public convenience init?(jsonData data: Data) {
guard let jsonObject = try? JSONSerialization.jsonObject(with: data),
let dictionary = jsonObject as? [String: Any] else {
return nil
}
self.init(dictionary: dictionary)
}
public required init?(dictionary: [String: Any]) {
guard let barcode = dictionary[Keys.barcode] as? String,
let amount = dictionary[Keys.amount] as? Double
else {
return nil
}
if let dueDateString = dictionary[Keys.dueDate] as? String,
let dueDate = Convert.stringToDate(from: dueDateString, dateFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ") {
self.dueDate = dueDate
}
self.barcode = barcode
self.amount = amount
self.promotionalCode = dictionary[Keys.promotionalCode] as? String ?? ""
}
// MARK: - Class Constructors
public class func array(jsonArray: [[String: Any]]) -> [MobileRechargeProducts] {
var array: [MobileRechargeProducts] = []
for json in jsonArray {
guard let item = MobileRechargeProducts(dictionary: json) else { continue }
array.append(item)
}
return array
}
public func toRegisterDictionary() -> [String : Any] {
return [
Keys.barcode: barcode,
Keys.amount: amount ,
Keys.dueDate: Convert.dateToString(from: dueDate!, dateFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"),
Keys.promotionalCode: promotionalCode
]
}
}
|
//
// Service.swift
// CardSharkiOS
//
// Created by Kenny Dang on 4/11/18.
//
import Foundation
protocol ServiceAPI {
var path: String { get }
var headers: [String: Any] { get }
var baseURL: URL? { get }
var method: HTTPMethod { get }
var parameters: [URLQueryItem]? { get }
}
enum HTTPMethod: String {
case get = "GET"
}
enum Service {
case getDeckOfCardsID
case shuffleDeckOfCards(withID: String)
case getDeckOfCards(withID: String)
}
extension Service: ServiceAPI {
var path: String {
switch self {
case .getDeckOfCardsID:
return "/api/deck/new/"
case .shuffleDeckOfCards(let id):
return "/api/deck/\(id)/shuffle"
case .getDeckOfCards(let id):
return "/api/deck/\(id)/draw"
}
}
var headers: [String : Any] {
switch self {
default:
return ["Accept": "application/json"]
}
}
var baseURL: URL? {
guard let url = URL(string: "https://deckofcardsapi.com") else { return nil }
return url
}
var method: HTTPMethod {
switch self {
default:
return .get
}
}
var parameters: [URLQueryItem]? {
switch self {
case .getDeckOfCards:
return [URLQueryItem(name: "count", value: "52")]
default:
return nil
}
}
var request: URLRequest? {
guard let baseURL = baseURL else { return nil }
guard var urlComponents = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) else { return nil }
urlComponents.path = path
urlComponents.queryItems = parameters
guard let headerValue = headers.values.first as? String else { return nil }
guard let headerField = headers.keys.first else { return nil }
guard let url = urlComponents.url else { return nil }
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = method.rawValue
urlRequest.addValue(headerValue, forHTTPHeaderField: headerField)
return urlRequest
}
}
|
//
// CollectionViewCell.swift
// BottleRocketTest
//
// Created by Vlastimir Radojevic on 3/1/20.
// Copyright © 2020 Vlastimir. All rights reserved.
//
import UIKit
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var backgroundImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var categoryLabel: UILabel!
var restaurant: Restaurant? {
didSet {
updateView()
}
}
fileprivate func updateView() {
if let imageUrl = restaurant?.backgroundImageURL {
backgroundImage.loadImage(fromURL: imageUrl)
}
nameLabel.text = restaurant?.name
categoryLabel.text = restaurant?.category
}
override func prepareForReuse() {
nameLabel.text = ""
categoryLabel.text = ""
backgroundImage.image = nil
}
override func awakeFromNib() {
super.awakeFromNib()
}
}
|
//
// AsteroidDetailPresenter.swift
// TestApp
//
// Created by Михаил Красильник on 19.05.2021.
//
import Foundation
protocol AsteroidDetailPresentationLogic: AnyObject {
}
class AsteroidDetailPresenter: AsteroidDetailPresentationLogic {
weak var viewController: AsteroidDetailDisplayLogic?
}
|
//有個大叔他叫老鎮,今年34歲
let name = "老鎮"
var age = 34
//明年他就35歲啦
age = 35
//他想改名叫小鎮
//name = "eko"
|
//
// FirstViewController.swift
// shutomend
//
// Created by Wicca on 15/5/16.
// Copyright (c) 2015年 Wi. All rights reserved.
//
import UIKit
import CoreLocation
class FirstViewController: UIViewController ,CLLocationManagerDelegate,UIAlertViewDelegate,LVConnGetDataDelegate{
let locationManager:CLLocationManager=CLLocationManager()
var lastLocation:CLLocation?
var counterFlag=false
var distanceCounter=0.0
var durationCounter=0
var btnStartPause:UIButton!
var btnStop:UIButton!
var conn:LVConnection!
var username:String?
var userWeight:Float=60
var canStop=false
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var durationLabel: UILabel!
@IBOutlet weak var speedLabel: UILabel!
@IBOutlet weak var kcalLabel: UILabel!
enum RuleType:Int{
case Normal=0
case Duration=1
case Distance=2
}
@IBOutlet weak var signalLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.initializeData()
self.initializeConn()
self.initializeUserInterface()
self.initializeLocation()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
self.initializeData()
// self.addtestData()
}
//====================testData====================
func addtestData(){
for var i=0;i<22;i++ {
var conn=LVConnection()
conn.saveRecord("bella", distance: 0.5*Double(i), duration: 1)
}
}
//====================testData====================
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getData(data: AnyObject) {
var isSucc:Bool=data as! Bool
println("\(isSucc)")
if isSucc{
self.resetCounter()
self.canStop=false
}else{
var alert=UIAlertView(title: "Attation", message: "data update failed", delegate: nil, cancelButtonTitle: "okay")
alert.show()
}
}
func refreshLabelWith(rule:RuleType){
self.distanceLabel.text=NSString(format: "%.3f KM", distanceCounter/1000) as String
self.durationLabel.text="\(self.durationCounter/3600)h \((self.durationCounter%3600)/60)m \(self.durationCounter%60)s"
self.speedLabel.text=NSString(format: "%.3f m/s", (self.distanceCounter/Double(self.durationCounter))) as String
self.kcalLabel.text=NSString(format: "%.2f kcal", Double(self.userWeight) * (self.distanceCounter/1000) * Double(1.036)) as String
}
func btnControl(sender:UIButton){
switch sender{
case self.btnStartPause:
self.btnStartPause.selected = !self.btnStartPause.selected
self.counterFlag = !self.counterFlag
self.canStop=true
case self.btnStop:
if self.canStop {
self.btnStartPause.selected=false
stopCounter()
}else{
return
}
default:
break
}
}
func stopCounter(){
self.counterFlag=false
var distance=NSString(format: "%.3fkm.", distanceCounter/1000) as String
var duration="\(self.durationCounter/3600)h \((self.durationCounter%3600)/60)m \(self.durationCounter%60)s"
var alertView=UIAlertView(
title: "Update",
message: "distance:\(distance)\nduration:\(duration)",
delegate: self,
cancelButtonTitle: "clear",
otherButtonTitles: "sure"
)
alertView.show()
}
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
switch buttonIndex{
case 0:
println("cancel")
self.resetCounter()
case 1:
println("update")
if self.username==nil{
var alertView=UIAlertView(title: "Attation", message: "you have no Login", delegate: nil, cancelButtonTitle: "Sure")
alertView.show()
}else{
self.conn.saveRecord(self.username!, distance: self.distanceCounter, duration: self.durationCounter)
}
default:
break
}
}
func resetCounter(){
self.distanceCounter=0.0
self.durationCounter=0
self.refreshLabelWith(RuleType.Normal)
}
func initializeUserInterface(){
var btnContainer=UIView(frame: CGRectMake(0, 0, 200, 200))
btnContainer.center=CGPointMake(UIScreen.mainScreen().bounds.width/2, UIScreen.mainScreen().bounds.height-100-64)
self.view.addSubview(btnContainer)
self.btnStartPause=UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
self.btnStartPause.frame=CGRectMake(0, 0, 200, 200);
self.btnStartPause.layer.cornerRadius=100;
self.btnStartPause.setImage(UIImage(named: "startImg"), forState: UIControlState.Normal)
self.btnStartPause.setImage(UIImage(named: "pauseImg"), forState: UIControlState.Selected)
self.btnStartPause.addTarget(self, action: "btnControl:", forControlEvents: UIControlEvents.TouchUpInside)
btnContainer.addSubview(self.btnStartPause)
self.btnStop=UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
self.btnStop.frame=CGRectMake(0, 0, 80, 80)
self.btnStop.center=CGPointMake(160, 160)
self.btnStop.setImage(UIImage(named: "stopImg.png"), forState: UIControlState.Normal)
self.btnStop.addTarget(self, action: "btnControl:", forControlEvents: UIControlEvents.TouchUpInside)
btnContainer.addSubview(self.btnStop)
}
func initializeData(){
var bUser=BmobUser.getCurrentUser()
if bUser==nil{
self.username=nil
self.userWeight=60
}else{
self.username=bUser.objectForKey("username") as? String
self.userWeight=bUser.objectForKey("weight").floatValue
}
}
func initializeConn(){
self.conn=LVConnection()
conn.getDataDelegate=self
}
func initializeLocation(){
if (UIDevice.currentDevice().systemVersion as NSString).floatValue>=8.0{
self.locationManager.requestWhenInUseAuthorization()
}
locationManager.delegate=self
locationManager.desiredAccuracy=kCLLocationAccuracyBest
locationManager.distanceFilter=0.3
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
self.signalLabel.text = (self.lastLocation != nil) ? "📡":"⌛️"
var currLocation=locations.last as! CLLocation
if self.counterFlag{
var meters=currLocation.distanceFromLocation(self.lastLocation)
self.durationCounter++
self.distanceCounter+=meters
self.lastLocation=currLocation
self.refreshLabelWith(RuleType.Normal)
}else{
self.lastLocation=currLocation
}
}
}
|
//
// Created by Daniel Heredia on 2/27/18.
// Copyright © 2018 Daniel Heredia. All rights reserved.
//
// Find Duplicates
import Foundation
let maxValue = UInt.bitWidth // The max value that can have a number (substract 1 to include 0)
let numbersCount = 500
let bitBufferLimit = UInt.bitWidth // The limit in bits for the buffer used for the solution
func createNumbers() -> [Int] {
var numbers = [Int]()
for _ in 0..<numbersCount {
numbers.append(Int(arc4random()) % maxValue)
}
return numbers
}
func printDuplicates(numbers: [Int]) {
var bitVector = [UInt](repeating: 0, count: bitBufferLimit / UInt.bitWidth)
if bitBufferLimit % UInt.bitWidth > 0 {
bitVector.append(0)
}
for number in numbers {
let containerIndex = number / UInt.bitWidth
let container = bitVector[containerIndex]
let bitIndex = number % UInt.bitWidth
let mask: UInt = 1 << bitIndex
if container & mask != 0 {
print("\(number)")
} else {
bitVector[containerIndex] = container | mask
}
}
}
let numbers = createNumbers()
print("All the numbers:")
print(numbers)
print("Duplicates:")
printDuplicates(numbers: numbers)
|
struct Response: Decodable {
let results: [Character]
}
|
//
// HomeViewController.swift
// CountriesTask
//
// Created by Marwan Ihab on 5/28/19.
// Copyright © 2019 Marwan Ihab. All rights reserved.
//
import UIKit
import Firebase
import FBSDKLoginKit
import FBSDKCoreKit
import GoogleSignIn
import Alamofire
import SwiftyJSON
import Foundation
import SVProgressHUD
class HomeViewController: UIViewController, UITableViewDelegate ,UITableViewDataSource{
var listOfCountries = [String]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listOfCountries.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = listOfCountries[indexPath.row]
return(cell)
}
let url2 = "https://restcountries.eu/rest/v2/all"
@IBOutlet weak var myTableView: UITableView!
override func viewDidLoad() {
SVProgressHUD.show()
self.getCountries()
super.viewDidLoad()
self.navigationItem.hidesBackButton = true
}
func getCountries() {
Alamofire.request(url2).responseJSON { response in
switch response.result {
case .success:
if let data = response.data{
self.sendJSONFILE(file:data)
}
case .failure(let error):
print(error)
}
}
}
func sendJSONFILE(file:Data) {
do{
let json = try JSONSerialization.jsonObject(with: file, options: [])
guard let jsonArray = json as? [[String: Any]] else {
return
}
for dic in jsonArray{
guard let title = dic["name"] as? String else { return }
listOfCountries.append(title)
}
self.myTableView.reloadData()
SVProgressHUD.dismiss()
} catch{
print("error")
}
}
@IBAction func logOutPressed(_ sender: UIButton) {
do {
try Auth.auth().signOut()
if (AccessToken.current != nil) {
let fbLoginManager = LoginManager()
fbLoginManager.logOut()
}
GIDSignIn.sharedInstance().signOut()
navigationController?.popToRootViewController(animated: true)
} catch {
print("Error in logging out")
}
}
}
|
//
// OLSearchResultsTableViewController.swift
// OpenLibrary
//
// Created by Bob Wakefield on 2/24/16.
// Copyright © 2016 Bob Wakefield. All rights reserved.
//
import UIKit
import CoreData
class OLSearchResultsTableViewController: UIViewController {
// MARK: Properties
var sortButton: UIBarButtonItem?
var searchButton: UIBarButtonItem?
lazy var generalSearchCoordinator: GeneralSearchResultsCoordinator = self.buildQueryCoordinator()
var searchController = UISearchController( searchResultsController: nil )
var touchedCellIndexPath: IndexPath?
var savedSearchKeys = [String: String]()
var savedIndexPath: IndexPath?
var savedAuthorKey: String?
var immediateSegueName: String?
var indexPathSavedForTransition: IndexPath?
var beginningOffset: CGFloat = 0.0
@IBAction func presentGeneralSearch(_ sender: UIBarButtonItem) {
performSegue( withIdentifier: "openBookSearch", sender: sender )
}
@IBAction func presentSearchResultsSort(_ sender: UIBarButtonItem) {
performSegue( withIdentifier: "openBookSort", sender: sender )
}
@IBOutlet var tableView: UITableView!
@IBOutlet fileprivate var refreshControl: UIRefreshControl?
@IBOutlet fileprivate var activityView: UIActivityIndicatorView!
deinit {
if let tableView = self.tableView {
SegmentedTableViewCell.emptyCellHeights( tableView )
generalSearchCoordinator.saveState()
}
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
GeneralSearchResultSegmentedTableViewCell.registerCell( tableView )
OLTableViewHeaderFooterView.registerCell( tableView )
SegmentedTableViewCell.emptyCellHeights( tableView )
// Do any additional setup after loading the view, typically from a nib.
let sortImage = UIImage(named: "rsw-sort-20x28")!
let searchImage = UIImage(named: "708-search")!
sortButton =
UIBarButtonItem(
image: sortImage,
style: .plain,
target: self,
action: #selector( OLSearchResultsTableViewController.presentSearchResultsSort( _: ) )
)
sortButton?.tintColor = UIColor.white
searchButton =
UIBarButtonItem(
image: searchImage,
style: .plain,
target: self,
action: #selector(OLSearchResultsTableViewController.presentGeneralSearch( _: ) )
)
searchButton?.tintColor = UIColor.white
navigationItem.rightBarButtonItems = [searchButton!, sortButton!]
navigationItem.leftBarButtonItem?.tintColor = UIColor.white
self.tableView.estimatedRowHeight = SegmentedTableViewCell.estimatedCellHeight
// self.tableView.rowHeight = UITableViewAutomaticDimension
if let tableFooterView = OLTableViewHeaderFooterView.createFromNib() as? OLTableViewHeaderFooterView {
self.tableView.tableFooterView = tableFooterView
tableFooterView.footerLabel.text = NSLocalizedString( "Tap the Search Button to Look for Books", comment: "" )
}
// generalSearchCoordinator = buildQueryCoordinator()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear( animated )
generalSearchCoordinator.updateUI()
}
override func viewDidAppear(_ animated: Bool) {
// navigationController?.hidesBarsOnSwipe = true
if let indexPath = savedIndexPath {
tableView.selectRow( at: indexPath, animated: true, scrollPosition: .none )
savedIndexPath = nil
}
if let segueName = immediateSegueName {
performSegue( withIdentifier: segueName, sender: self )
immediateSegueName = nil
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
generalSearchCoordinator.saveState()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Dynamic sizing for the header view
if let footerView = tableView.tableFooterView {
let height = footerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
var footerFrame = footerView.frame
// If we don't have this check, viewDidLayoutSubviews() will get
// repeatedly, causing the app to hang.
if height != footerFrame.size.height {
footerFrame.size.height = height
footerView.frame = footerFrame
tableView.tableFooterView = footerView
}
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition( to: size, with: coordinator )
SegmentedTableViewCell.emptyCellHeights( tableView )
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange( previousTraitCollection )
guard let visible = tableView.indexPathsForVisibleRows else { return }
guard let indexPath = tableView.indexPathForSelectedRow else { return }
guard visible.contains( indexPath ) else { return }
guard let cell = tableView.cellForRow( at: indexPath ) as? SegmentedTableViewCell else { return }
guard !cell.key.isEmpty else { return }
expandCell( tableView, segmentedCell: cell, key: cell.key )
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let segueName = segue.identifier else { assert( false ); return }
if segueName == "openBookSearch" {
if let destVC = segue.destination as? OLBookSearchViewController {
destVC.initialSearchKeys( generalSearchCoordinator.searchKeys )
destVC.saveSearchDictionary = saveSearchKeys
}
} else if segueName == "openBookSort" {
if let destVC = segue.destination as? OLBookSortViewController {
destVC.sortFields = generalSearchCoordinator.sortFields
destVC.saveSortFields = self.saveSortFields
}
} else if let indexPath = tableView.indexPathForSelectedRow {
savedIndexPath = indexPath
indexPathSavedForTransition = indexPath
switch segueName {
case "displayGeneralSearchAuthorDetail":
var destVC: OLAuthorDetailViewController?
destVC = segue.destination as? OLAuthorDetailViewController
if nil == destVC {
if let navVC = segue.destination as? UINavigationController {
destVC = navVC.topViewController as? OLAuthorDetailViewController
}
}
if let destVC = destVC {
if let key = savedAuthorKey {
generalSearchCoordinator.installAuthorDetailCoordinator( destVC, authorKey: key )
savedAuthorKey = nil
} else {
generalSearchCoordinator.installAuthorDetailCoordinator( destVC, indexPath: indexPath )
}
}
case "displayGeneralSearchAuthorList":
if let destVC = segue.destination as? OLAuthorsTableViewController {
generalSearchCoordinator.installAuthorsTableViewCoordinator( destVC, indexPath: indexPath )
destVC.saveAuthorKey = self.saveAuthorKey
}
case "displayGeneralSearchWorkDetail":
var destVC: OLWorkDetailViewController?
destVC = segue.destination as? OLWorkDetailViewController
if nil == destVC {
if let navVC = segue.destination as? UINavigationController {
destVC = navVC.topViewController as? OLWorkDetailViewController
}
}
if let destVC = destVC {
if let delegate = splitViewController?.delegate as? SplitViewControllerDelegate {
delegate.collapseDetailViewController = false
}
generalSearchCoordinator.installWorkDetailCoordinator( destVC, indexPath: indexPath )
}
case "zoomLargeImage":
var destVC: OLPictureViewController?
destVC = segue.destination as? OLPictureViewController
if nil == destVC {
if let navVC = segue.destination as? UINavigationController {
destVC = navVC.topViewController as? OLPictureViewController
}
}
if let destVC = destVC {
generalSearchCoordinator.installCoverPictureViewCoordinator( destVC, indexPath: indexPath )
}
case "displayWorkEBooks":
var destVC: OLWorkDetailViewController?
destVC = segue.destination as? OLWorkDetailViewController
if nil == destVC {
if let navVC = segue.destination as? UINavigationController {
destVC = navVC.topViewController as? OLWorkDetailViewController
}
}
if let destVC = destVC {
generalSearchCoordinator.installWorkDetailCoordinator( destVC, indexPath: indexPath )
}
case "displayAuthorDetail":
var destVC: OLAuthorDetailViewController?
destVC = segue.destination as? OLAuthorDetailViewController
if nil == destVC {
if let navVC = segue.destination as? UINavigationController {
destVC = navVC.topViewController as? OLAuthorDetailViewController
}
}
if let destVC = destVC {
generalSearchCoordinator.installAuthorDetailCoordinator( destVC, indexPath: indexPath )
}
case "displayBlank":
break
default:
assert( false )
}
}
}
// MARK: Utility
func buildQueryCoordinator() -> GeneralSearchResultsCoordinator {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.getGeneralSearchCoordinator( self )
}
// MARK: Search
func getFirstSearchResults( _ authorName: String, scopeIndex: Int, userInitiated: Bool = true ) {
self.title = "Search"
tableView.reloadData()
}
func clearSearchResults() {
generalSearchCoordinator.clearQuery()
}
fileprivate func updateUI() {
generalSearchCoordinator.updateUI()
}
// MARK: Search View Controller
func presentSearch() -> Void {
performSegue( withIdentifier: "openBookSearch", sender: self )
}
func saveSearchKeys( _ searchKeys: [String: String] ) -> Void {
self.savedSearchKeys = searchKeys
}
@IBAction func dismissSearch( _ segue: UIStoryboardSegue ) {
if segue.identifier == "beginBookSearch" {
if !savedSearchKeys.isEmpty {
// searchType = .searchGeneral
SegmentedTableViewCell.emptyCellHeights( tableView )
generalSearchCoordinator.newQuery( savedSearchKeys, userInitiated: true, refreshControl: nil )
let indexPath = IndexPath( row: Foundation.NSNotFound, section: 0 )
tableView.scrollToRow( at: indexPath, at: .top, animated: true )
if !(splitViewController?.isCollapsed ?? true) {
performSegue(withIdentifier: "displayBlank", sender: self )
}
}
savedIndexPath = nil
}
}
// MARK: Sort View Controller
func presentSort() -> Void {
performSegue( withIdentifier: "openBookSort", sender: self )
}
func saveSortFields( _ sortFields: [SortField] ) -> Void {
generalSearchCoordinator.sortFields = sortFields
}
@IBAction func dismissSort(_ segue: UIStoryboardSegue) {
if segue.identifier == "beginBookSort" {
savedIndexPath = nil
tableView.reloadData()
}
}
// MARK: Authors Table View Controller
func presentAuthors() -> Void {
performSegue( withIdentifier: "displayGeneralSearchAuthorList", sender: self )
}
func saveAuthorKey( _ authorKey: String ) -> Void {
savedAuthorKey = authorKey
}
@IBAction func dismissAuthors(_ segue: UIStoryboardSegue) {
if segue.identifier == "beginAuthorDetail" {
if nil != savedAuthorKey {
// start the next segue AFTER the current segue finishes
immediateSegueName = "displayGeneralSearchAuthorDetail"
}
}
}
// MARK: query in progress
func coordinatorIsBusy() -> Void {
activityView?.startAnimating()
sortButton?.isEnabled = false
searchButton?.isEnabled = false
SegmentedTableViewCell.emptyIndexPathToKeyLookup( tableView )
}
func coordinatorIsNoLongerBusy() -> Void {
activityView?.stopAnimating()
sortButton?.isEnabled = true
searchButton?.isEnabled = true
}
// MARK: cell expansion and contraction
fileprivate func expandCell( _ tableView: UITableView, segmentedCell: SegmentedTableViewCell, key: String ) {
let duration = 0.3
segmentedCell.setOpen( tableView, key: key )
UIView.animate(
withDuration: duration, delay: 0, options: .curveLinear,
animations: {
() -> Void in
tableView.beginUpdates()
tableView.endUpdates()
}
) {
(finished) -> Void in
_ = segmentedCell.selectedAnimation( tableView, key: key, expandCell: true, animated: true ) {
SegmentedTableViewCell.animationComplete()
}
}
}
fileprivate func contractCell( _ tableView: UITableView, segmentedCell: SegmentedTableViewCell, key: String ) {
let duration = 0.1 // isOpen ? 0.3 : 0.1 // isOpen ? 1.1 : 0.6
_ = segmentedCell.selectedAnimation( tableView, key: key, expandCell: false, animated: true ) {
UIView.animate(
withDuration: duration, delay: 0.0, options: .curveLinear,
animations: {
() -> Void in
tableView.beginUpdates()
tableView.endUpdates()
}
) {
(finished) -> Void in
SegmentedTableViewCell.animationComplete()
}
}
}
}
extension OLSearchResultsTableViewController: TransitionImage {
var transitionRectImageView: UIImageView? {
if let indexPath = indexPathSavedForTransition {
if let cell = tableView.cellForRow( at: indexPath ) as? GeneralSearchResultSegmentedTableViewCell {
return cell.transitionSourceRectView()
}
} else if let indexPath = tableView.indexPathForSelectedRow {
if let cell = tableView.cellForRow( at: indexPath ) as? GeneralSearchResultSegmentedTableViewCell {
return cell.transitionSourceRectView()
}
}
return nil
}
}
extension OLSearchResultsTableViewController: TransitionCell {
func transitionRectCellView() -> UITableViewCell? {
var sourceRectView: UITableViewCell?
assert( nil != indexPathSavedForTransition )
if let indexPath = indexPathSavedForTransition {
sourceRectView = tableView.cellForRow( at: indexPath )
indexPathSavedForTransition = nil
}
return sourceRectView
}
}
// MARK: UIScrollViewDelegate
extension OLSearchResultsTableViewController: UIScrollViewDelegate {
func scrollViewDidEndDragging( _ scrollView: UIScrollView, willDecelerate decelerate: Bool ) {
// UITableView only moves in one direction, y axis
let currentOffset = scrollView.contentOffset.y
let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height
// Change 10.0 to adjust the distance from bottom
if maximumOffset - currentOffset <= -10.0 {
generalSearchCoordinator.nextQueryPage()
} else if currentOffset <= -10.0 {
navigationController?.setNavigationBarHidden( false, animated: true )
}
}
func scrollViewWillEndDragging( _ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint> ) {
// up
if velocity.y < -1.5 {
navigationController?.setNavigationBarHidden( false, animated: true )
}
}
}
// MARK: UITableViewDelegate
extension OLSearchResultsTableViewController: UITableViewDelegate {
// do not implement this function! The overhead involved in getting the key isn't worth it
func tableView( _ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath ) -> CGFloat {
let height = SegmentedTableViewCell.estimatedCellHeight
// print( "estimatedHeightForRowAtIndexPath \(indexPath.row) \(height)" )
return height
}
func tableView( _ tableView: UITableView, heightForRowAt indexPath: IndexPath ) -> CGFloat {
assert( Thread.isMainThread )
var height = SegmentedTableViewCell.estimatedCellHeight
let cell = tableView.cellForRow( at: indexPath ) as? SegmentedTableViewCell
if let cell = cell {
height = cell.height( tableView )
} else {
height = SegmentedTableViewCell.cachedHeightForRowAtIndexPath( tableView, indexPath: indexPath )
}
// print( "heightForRowAtIndexPath: \(cell?.key ?? "nil") \(indexPath.row) \(height)" )
return height
}
func tableView( _ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath ) {
if let cell = cell as? GeneralSearchResultSegmentedTableViewCell {
_ = cell.selectedAnimation( tableView, key: cell.key )
// print( "willDisplayCell forRowAtIndexPath \(indexPath.row) \(cell.key)" )
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow( at: indexPath ) as? SegmentedTableViewCell {
if !cell.isExpanded( in: tableView ) {
if !(splitViewController?.isCollapsed ?? true) && indexPath != indexPathSavedForTransition {
performSegue( withIdentifier: "displayBlank", sender: self )
}
generalSearchCoordinator.didSelectRowAtIndexPath( indexPath )
expandCell( tableView, segmentedCell: cell, key: cell.key )
}
tableView.scrollToRow( at: indexPath, at: .none, animated: true )
// print( "didSelectRowAtIndexPath \(indexPath.row) \(cell.key)" )
indexPathSavedForTransition = indexPath
}
}
func tableView( _ tableView: UITableView, didDeselectRowAt indexPath: IndexPath ) {
SegmentedTableViewCell.setClosed( tableView, indexPath: indexPath )
if let cell = tableView.cellForRow( at: indexPath ) as? SegmentedTableViewCell {
cell.setClosed( tableView )
contractCell( tableView, segmentedCell: cell, key: cell.key )
// print( "didDeselectRowAtIndexPath \(indexPath.row) \(cell.key)" )
}
}
}
// MARK: UITableviewDataSource
extension OLSearchResultsTableViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return generalSearchCoordinator.numberOfSections()
}
func tableView( _ tableView: UITableView, numberOfRowsInSection section: Int ) -> Int {
return generalSearchCoordinator.numberOfRowsInSection( section )
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell? = nil
if let expandingCell = tableView.dequeueReusableCell( withIdentifier: GeneralSearchResultSegmentedTableViewCell.nameOfClass ) as? GeneralSearchResultSegmentedTableViewCell {
if let object = generalSearchCoordinator.objectAtIndexPath( indexPath ) {
expandingCell.tableVC = self
expandingCell.configure( tableView, indexPath: indexPath, key: object.key, data: object )
generalSearchCoordinator.displayThumbnail( object, cell: expandingCell )
}
// print( "cellForRowAtIndexPath \(indexPath.row) \(expandingCell.key)" )
cell = expandingCell
}
return cell!
}
}
|
//
// Query+Limiting.swift
// SwiftServePostgres
//
// Created by Andrew J Wagner on 12/6/17.
//
extension SelectQuery {
public func limited(to limit: Int) -> SelectQuery<T> {
var new = self
new.limit = limit
return new
}
}
|
//
// addListForButton.swift
// TestAssignment
//
// Created by preeti dhankar on 01/08/20.
// Copyright © 2020 Viks. All rights reserved.
//
import Foundation
import UIKit
import DropDown
extension AddListViewController {
func forHeaderViewCell(_ cell: FilterNavigationTableViewCell, indexpath: IndexPath) {
cell.SelectdateBtn.addTarget(self, action: #selector(datebtnAction(sender:)), for: .touchUpInside)
cell.SelectdateBtn.tag = indexpath.row
cell.selectitamBtn.addTarget(self, action: #selector(selectitamBtnAction(sender:)), for: .touchUpInside)
cell.selectitamBtn.tag = indexpath.row
self.dateButton = cell.SelectdateBtn
cell.applyfilterBtn.addTarget(self, action: #selector(applyfilterBtnAction(sender:)), for: .touchUpInside)
cell.applyfilterBtn.tag = indexpath.row
}
////////////////////////Button Action Header Cell //////////////////////////////////////////
@objc func applyfilterBtnAction (sender : UIButton) {
// var dict = Dictionary<String, Array<String>>()
//// // print("\(dict)")
// dict["Aarry"] = [dateString,itamTitle,LocationStr]
// if var arr = dict["Aarry"] {
// arr.append(dateString)
// }
////
// var myDictionary:[String:String] = [:]
//
// if var arr = myDictionary["Aarry"] {
// arr.append(dateString)
// }
//
// for (key, value) in myDictionary {
// print("\(key) : \(value)")
// }
//
// print("\(myDictionary)")
var dict = Dictionary<String, String>()
dict["A"] = String()
dict["B"] = String()
// dict["C"] = [301]
if var arr = dict["A"] {
arr.append(dateString)
dict["A"] = arr
}
if var arr = dict["B"] {
arr.append(itamTitle)
dict["B"] = arr
}
print("\(dict)")
let storyBord : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let nextViewController = storyBord.instantiateViewController(withIdentifier: "ViewController") as! ViewController
nextViewController.data = dict
self.navigationController?.pushViewController(nextViewController, animated: true)
//
}
@objc func selectitamBtnAction (sender : UIButton) {
let buttonTag = sender.tag
let indexPath = IndexPath.init(item: buttonTag, section: 0)
if (AddListTableView.cellForRow(at: indexPath) as? FilterNavigationTableViewCell) != nil {
self.categoryDrop.anchorView = sender
self.categoryDrop.bottomOffset = CGPoint(x: 0, y: sender.bounds.height)
self.categoryDrop.dataSource.removeAll()
self.categoryDrop.dataSource.append(contentsOf: self.arrVehical)
self.categoryDrop.selectionAction = { [unowned self] (index, item) in
sender.setTitle(item, for: .normal)
self.itamTitle = item
debugPrint(self.itamTitle)
}
self.categoryDrop.show()
}
}
@objc func datebtnAction (sender : UIButton) {
let buttonTag = sender.tag
let indexPath = IndexPath.init(item: buttonTag, section: 0)
if (AddListTableView.cellForRow(at: indexPath) as? FilterNavigationTableViewCell) != nil {
let selector = UIStoryboard(name: "WWCalendarTimeSelector", bundle: nil).instantiateInitialViewController() as! WWCalendarTimeSelector
selector.delegate = self
selector.optionCurrentDate = singleDate
selector.optionCurrentDates = Set(multipleDates)
selector.optionCurrentDateRange.setStartDate(multipleDates.first ?? singleDate)
selector.optionCurrentDateRange.setEndDate(multipleDates.last ?? singleDate)
selector.optionStyles.showDateMonth(true)
selector.optionStyles.showMonth(false)
selector.optionStyles.showYear(true)
selector.optionStyles.showTime(false)
present(selector, animated: true, completion: nil)
}
}
func WWCalendarTimeSelectorDone(_ selector: WWCalendarTimeSelector, date: Date) {
let dateString = date.stringFromFormat("dd MMMM yyyy'")
self.dateString = "\(dateString)"
self.dateButton.setTitle("\(dateString)", for: .normal)
}
}
|
//
// AlbumsViewController.swift
// PhotosApp
//
// Created by Allison Lindner on 28/07/20.
// Copyright (c) 2020 Allison Lindner. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
protocol AlbumsDisplayLogic: class {
func displaySomething(viewModel: Albums.Something.ViewModel)
}
class AlbumsViewController: UIViewController, AlbumsDisplayLogic {
var interactor: AlbumsBusinessLogic?
var router: (NSObjectProtocol & AlbumsRoutingLogic & AlbumsDataPassing)?
// MARK: Object lifecycle
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
// MARK: Setup
private func setup() {
let viewController = self
let interactor = AlbumsInteractor()
let presenter = AlbumsPresenter()
let router = AlbumsRouter()
viewController.interactor = interactor
viewController.router = router
interactor.presenter = presenter
presenter.viewController = viewController
router.viewController = viewController
router.dataStore = interactor
}
// MARK: Routing
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let scene = segue.identifier {
let selector = NSSelectorFromString("routeTo\(scene)WithSegue:")
if let router = router, router.responds(to: selector) {
router.perform(selector, with: segue)
}
}
}
// MARK: View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
doSomething()
}
// MARK: Do something
//@IBOutlet weak var nameTextField: UITextField!
func doSomething() {
let request = Albums.Something.Request()
interactor?.doSomething(request: request)
}
func displaySomething(viewModel: Albums.Something.ViewModel) {
//nameTextField.text = viewModel.name
}
}
|
//
// ModelViewController.swift
// IndianBibles
//
// Created by Admin on 27/04/21.
// Copyright © 2021 Rajeev Kalangi. All rights reserved.
//
import UIKit
class ModelViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
let inset: CGFloat = 10
let minimumLineSpacing: CGFloat = 10
let minimumInteritemSpacing: CGFloat = 10
let cellsPerRow = 2
var db = DBHandler()
var selectedBible: String?
var bibleBooks = BibleBooks()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
collectionView.delegate = self
}
// MARK: UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return bibleBooks.bibleLanguages.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ModelCell", for: indexPath) as! ModelViewCell
cell.bibleLabel?.text = bibleBooks.bibleLanguages[indexPath.item]
return cell
}
}
// Mark: Delegate
extension ModelViewController{
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
dismiss(animated: true, completion: {
BooksSingleton.booksSingleton.selectBible(self.bibleBooks.biblesInDB[indexPath.row])
})
}
}
extension ModelViewController : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return minimumLineSpacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return minimumInteritemSpacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let marginsAndInsets = inset * 2 + collectionView.safeAreaInsets.left + collectionView.safeAreaInsets.right + minimumInteritemSpacing * CGFloat(cellsPerRow - 1)
let itemWidth = ((collectionView.bounds.size.width - marginsAndInsets) / CGFloat(cellsPerRow)).rounded(.down)
return CGSize(width: itemWidth, height: itemWidth)
}
}
|
//
// Constants.swift
// TinkoffProject
//
// Created by Anvar Karimov on 23.02.2020.
// Copyright © 2020 tinkoff-group-5. All rights reserved.
//
import Foundation
// MARK: - Typealiases
typealias CompletionBlock = () -> Void
|
//
// FallDownTests.swift
// Match3-Line
//
// Created by Ann Michelsen on 06/01/15.
// Copyright (c) 2015 Ann Michelsen. All rights reserved.
//
import UIKit
import XCTest
class FallDownTests: XCTestCase {
var rows = 3
var columns = 3
var gameplay = GamePlay()
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
gameplay.nbrOfRows = rows
gameplay.nbrOfColums = columns
var grid = Grid<Gem>(rows: rows, colums: columns)
/* O = gem x = empty
X O O
O X O
X X X
*/
grid[1,0] = Gem(row: 1, column: 0, gemType: GemType.Blue)
grid[2,1] = Gem(row: 2, column: 1, gemType: GemType.Blue)
grid[1,2] = Gem(row: 1, column: 2, gemType: GemType.Blue)
grid[2,2] = Gem(row: 2, column: 2, gemType: GemType.Blue)
gameplay.grid = grid
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testRemoveGems() {
/* result should be: O = gem, X = empty spot
X X X
X X O
O O O
*/
let gem = gameplay.grid[1,0]!
gameplay.getFallingGems()
XCTAssertNil(gameplay.grid[1,0], "should be nil, gem should have fallen down")
XCTAssertNil(gameplay.grid[2,0], "should be nil, gem should have fallen down")
XCTAssertNotNil(gameplay.grid[0,0], "should not be nil, gem should have filled spot")
XCTAssertNil(gameplay.grid[1,1], "should be nil, gem should have filled spot")
XCTAssertNil(gameplay.grid[2,1], "should be nil, gem should have filled spot")
XCTAssertNotNil(gameplay.grid[0,1], "should not be nil, gem should have filled spot")
XCTAssertNil(gameplay.grid[2,2], "should be nil, gem should have filled spot")
XCTAssertNotNil(gameplay.grid[0,2], "should not be nil, gem should have filled spot")
XCTAssertNotNil(gameplay.grid[1,2], "should not be nil, gem should have filled spot")
XCTAssertEqual(gem.row, 0, "The gem was moved, should be 0")
XCTAssertEqual(gem.column, 0, "The gem was moved, should be 0")
}
} |
//
// Result.swift
// Sealion
//
// Copyright (c) 2016 Dima Bart
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those
// of the authors and should not be interpreted as representing official policies,
// either expressed or implied, of the FreeBSD Project.
//
import Foundation
public enum FailureReason {
case unknown
case cancelled
case badURL
case timedOut
case unsupportedURL
case cannotFindHost
case cannotConnectToHost
case networkConnectionLost
case dNSLookupFailed
case HTTPTooManyRedirects
case resourceUnavailable
case notConnectedToInternet
case redirectToNonExistentLocation
case badServerResponse
case userCancelledAuthentication
case userAuthenticationRequired
case zeroByteResource
case cannotDecodeRawData
case cannotDecodeContentData
case cannotParseResponse
case fileDoesNotExist
case fileIsDirectory
case noPermissionsToReadFile
case dataLengthExceedsMaximum
case requiresSecureConnection
init(code: Int?) {
guard let code = code else {
self = .unknown
return
}
switch code {
case NSURLErrorUnknown: self = .unknown
case NSURLErrorCancelled: self = .cancelled
case NSURLErrorBadURL: self = .badURL
case NSURLErrorTimedOut: self = .timedOut
case NSURLErrorUnsupportedURL: self = .unsupportedURL
case NSURLErrorCannotFindHost: self = .cannotFindHost
case NSURLErrorCannotConnectToHost: self = .cannotConnectToHost
case NSURLErrorNetworkConnectionLost: self = .networkConnectionLost
case NSURLErrorDNSLookupFailed: self = .dNSLookupFailed
case NSURLErrorHTTPTooManyRedirects: self = .HTTPTooManyRedirects
case NSURLErrorResourceUnavailable: self = .resourceUnavailable
case NSURLErrorNotConnectedToInternet: self = .notConnectedToInternet
case NSURLErrorRedirectToNonExistentLocation: self = .redirectToNonExistentLocation
case NSURLErrorBadServerResponse: self = .badServerResponse
case NSURLErrorUserCancelledAuthentication: self = .userCancelledAuthentication
case NSURLErrorUserAuthenticationRequired: self = .userAuthenticationRequired
case NSURLErrorZeroByteResource: self = .zeroByteResource
case NSURLErrorCannotDecodeRawData: self = .cannotDecodeRawData
case NSURLErrorCannotDecodeContentData: self = .cannotDecodeContentData
case NSURLErrorCannotParseResponse: self = .cannotParseResponse
case NSURLErrorFileDoesNotExist: self = .fileDoesNotExist
case NSURLErrorFileIsDirectory: self = .fileIsDirectory
case NSURLErrorNoPermissionsToReadFile: self = .noPermissionsToReadFile
case NSURLErrorDataLengthExceedsMaximum: self = .dataLengthExceedsMaximum
case NSURLErrorAppTransportSecurityRequiresSecureConnection: self = .requiresSecureConnection
default:
self = .unknown
}
}
}
public enum Result<T> {
case success(object: T?)
case failure(error: RequestError?, reason: FailureReason)
}
|
//
// MealViewController.swift
// FoodTracker
//
// Created by Wizard on 6/3/20.
// Copyright © 2020 Wizard. All rights reserved.
//
import UIKit
import os.log
class MealViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: Properties
@IBOutlet weak var nameTextField: UITextField!
// @IBOutlet weak var mealNameLabel: UILabel!
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var ratingControl: RatingControl!
@IBOutlet weak var saveButton: UIBarButtonItem!
/// This value is either passed by 'MealTableViewController' in 'prepare(for:sender:)'
/// or constructed as part of adding a new Meal
var meal: Meal?;
override func viewDidLoad() {
super.viewDidLoad();
// Handle the text field's user input through delegate callbacks
nameTextField.delegate = self;
// Setup views if editing an existing meal
if let meal = meal {
navigationItem.title = meal.name;
nameTextField.text = meal.name;
photoImageView.image = meal.photo;
ratingControl.rating = meal.rating;
}
// Enable the save button only if the text field has a valid meal name
updateSaveButtonState();
}
// MARK: UITextFieldDelegate
// Asks the delegate if the text field should process the pressing of the return button.
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// hide the keyboard
nameTextField.resignFirstResponder();
return true;
}
// tells the delegate that editing began in the specified text field
func textFieldDidBeginEditing(_ textField: UITextField) {
saveButton.isEnabled = false;
}
// Tells the delegate that editing stopped for the specified text field.
func textFieldDidEndEditing(_ textField: UITextField) {
// mealNameLabel.text = textField.text;
updateSaveButtonState();
navigationItem.title = textField.text;
}
// MARK: UIImagePickerControllerDelegate
// Tells the delegate that the user cancelled the pick operation.
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// dismiss the picker if the user canceled
dismiss(animated: true, completion: nil); // this dismiss all modal views triggered by this view controller
}
// Tells the delegate that the user picked a still image or movie.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// The info dictionary may contain multiple representations of the image.
// You want to use the original.
guard let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else {
fatalError("Expected a dictionary containg an image, but was provided the following: \(info)");
}
// set photoImageView to display the selected image.
photoImageView.image = selectedImage;
// Dismiss the image picker
dismiss(animated: true, completion: nil);
}
// MARK: Navigation
/// this method lets you configure a view controller before it's presented
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender);
// the UIViewController class's implementation doesn't do anything, but it's a good
// habit to always call super.prepare(for:sender:) whenever you override it.
// that way you won't forget it when you subclass a different class
// configure the destination view controller only when the save button is pressed
guard let button = sender as? UIBarButtonItem, button === saveButton else {
os_log("The save button was not pressed, cancelling", log: OSLog.default, type: .debug)
return;
}
let name = nameTextField.text ?? "";
let photo = photoImageView.image;
let rating = ratingControl.rating;
// set the meal to be passed to MealTableViewController after the unwind segue.
meal = Meal(name: name, photo: photo, rating: rating);
// this code configure the meal property with the appropriate values before segue executes
}
// MARK: Actions
@IBAction func cancel(_ sender: UIBarButtonItem) {
// the type of simissal depends on how the scene was presented
// You'll implemt a check that detremines how the current scene was presented when the user taps
// the cancel button, if it was presented modally (the user tapped the addButton)
// it'll be dismissed using dismiss(animated:completion:).
// if it was presented with push navigation (the user tapped a table view cell).
// it will be dismissed by the navigation controller that presented it
// depending on style of presentation (modal or push presentation), this view controller
// needs to be dismissed in two different ways.
// this code creates a boolean value, that indicates whether the view controller that
// presented this scene is of type UINavigationController. As the constant name
// isPresentingInAddMealMode indicates, this means that the meal detail scene is
// presented by the user tapping the add button.
// this is because the meal detail scene is embedded in its own navigation controller
// when it's presented in this manner, which means that the naavigation controller is what presents it.
let isPresentingInAddMealMode = presentingViewController is UINavigationController;
if isPresentingInAddMealMode {
dismiss(animated: true, completion: nil);
} else if let owningNavigationController = navigationController {
owningNavigationController.popViewController(animated: true);
} else {
fatalError("The MealViewController is not inside a navigation controller");
}
}
@IBAction func selectImageFromPhotoLibrary(_ sender: UITapGestureRecognizer) {
// hide the keyboard
nameTextField.resignFirstResponder();
// UIImagePickerController is a view controller that lets a user pick a media from their photo library
let imagePickerController = UIImagePickerController();
// only allow photos to be picked, not tacken
imagePickerController.sourceType = .photoLibrary;
// make sure ViewController is notified when the user picks an image
imagePickerController.delegate = self;
present(imagePickerController, animated: true, completion: nil);
}
// MARK: Private methods
private func updateSaveButtonState() {
// disable the save button if the text field is empty
let text = nameTextField.text ?? "";
saveButton.isEnabled = !text.isEmpty;
}
}
|
//
// RestaurantExperiencePhotoEditorDelegate.swift
// grubber
//
// Created by JABE on 11/20/15.
// Copyright © 2015 JABELabs. All rights reserved.
//
class RestaurantExperiencePhotoEditorDelegate : PhotoEditorDelegate {
func queryCanDeletePhotoSource(photoSource: PhotoSource, completionBlock: (canDelete: Bool, userReason: String, userData: AnyObject?) -> Void) {
completionBlock(canDelete: true, userReason: "", userData: nil)
}
func onDeletePhoto(photoSource: PhotoSource, completionBlock: (deleted: Bool, postDeleteUserMessage: String?, error: NSError?) -> Void) {
guard let reviewPhoto = photoSource as? ExperiencePhoto else {
return
}
ExperiencePhoto.remove(reviewPhoto.id, completionBlock: { (success, error) -> Void in
if error == nil {
EventPublisher.sharedAppEventPublisher().emit(.RestaurantPhotoDeleted, userData: reviewPhoto.id)
}
completionBlock(deleted: error == nil, postDeleteUserMessage: "", error: error)
})
}
func onSave(photoEditorData : PhotoEditorData, completionBlock: ((success: Bool, isNewObject: Bool, savedObject: AnyObject?) -> Void)?) {
var updatedReviewPhoto : ExperiencePhoto?
var isNew = true
if let photoSource = photoEditorData.photoSource {
isNew = photoSource.isNew()
}
var success = false
var savedObject : AnyObject!
if isNew {
guard let review = photoEditorData.objectContext as? RestaurantExperience else {
return
}
updatedReviewPhoto = ExperiencePhoto.insert({(reviewPhoto: ExperiencePhoto)
in
reviewPhoto.comments = photoEditorData.caption!
reviewPhoto.experienceId = review.id
reviewPhoto.photo = photoEditorData.image
if let audio = photoEditorData.audio {
reviewPhoto.audio = audio
}
})
success = true
savedObject = updatedReviewPhoto!
if let newPhoto = updatedReviewPhoto {
EventPublisher.sharedAppEventPublisher().emit(.ExperiencePhotoAdded, userData: newPhoto.id)
}
} else {
let photoChanged = photoEditorData.photoSource?.getPhoto() != photoEditorData.image!
var updateCount = 0
if let reviewPhoto = photoEditorData.objectContext as? ExperiencePhoto {
updateCount = ExperiencePhoto.update(reviewPhoto.id, updatePhoto: photoChanged, updateValuesAssignmentBlock: { (experiencePhoto) -> Void in
experiencePhoto.experienceId = reviewPhoto.experienceId
if let caption = photoEditorData.caption {
experiencePhoto.comments = caption
}
if photoChanged {
if let image = photoEditorData.image {
experiencePhoto.photo = image
}
}
if let audio = photoEditorData.audio {
experiencePhoto.audio = audio
}
})
success = updateCount == 1
savedObject = reviewPhoto
EventPublisher.sharedAppEventPublisher().emit(.ExperiencePhotoModified, userData: reviewPhoto.id)
}
}
if let completion = completionBlock {
completion(success: success, isNewObject: isNew, savedObject: savedObject)
}
}
} |
//
// JKMessageDetailsViewController.swift
// JKAppBadgeCounter
//
// Created by Jayesh Kawli Backup on 5/11/16.
// Copyright © 2016 Jayesh Kawli Backup. All rights reserved.
//
import UIKit
class JKMessageDetailsViewController: UIViewController {
let message: JKMessage?
init(message: JKMessage) {
self.message = message
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
self.view.backgroundColor = UIColor.whiteColor()
self.view.addSubview(label)
self.title = message?.messageSubject
label.text = message?.messageBody;
let topLayoutGuide = self.topLayoutGuide
let views: [String: AnyObject] = ["label": label, "topLayoutGuide": topLayoutGuide]
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[topLayoutGuide]-[label]-(>=0)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
}
}
|
//
// UIColor+GVAdditions.swift
//
// Generated by Zeplin on 6/6/17.
// Copyright (c) 2017 __MyCompanyName__. All rights reserved.
//
import UIKit
extension UIColor {
public final func alpha(_ alpha: CGFloat) -> UIColor {
return withAlphaComponent(alpha)
}
}
|
//
// Data+Extensions.swift
// NGTools
//
// Created by Fournier, Olivier on 2019-01-04.
// Copyright © 2019 Nuglif. All rights reserved.
//
import Foundation
import CommonCrypto
public extension Data {
enum DataError: Error {
case randomBytesError
}
var sha1: String {
let digest: [UInt8] = withUnsafeBytes {
var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
CC_SHA1($0.baseAddress, CC_LONG(count), &digest)
return digest
}
return digest
.map { String(format: "%02hhx", $0) }
.joined()
}
var md5: String {
let digest: [UInt8] = withUnsafeBytes {
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5($0.baseAddress, CC_LONG(count), &digest)
return digest
}
return digest
.map { String(format: "%02hhx", $0) }
.joined()
}
var sha256: String {
let digest: [UInt8] = withUnsafeBytes {
var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
CC_SHA256($0.baseAddress, CC_LONG(count), &digest)
return digest
}
return digest.map {
String(format: "%02x", $0)
}.joined()
}
func toHexadecimal() -> String {
return reduce("", { $0 + String(format: "%02X", $1) })
.lowercased()
}
static func randomBytes(length: Int = 32) throws -> Data {
var randomData = Data(count: length)
let result = try randomData.withUnsafeMutableBytes { pointer in
guard let baseAddress = pointer.baseAddress else {
throw DataError.randomBytesError
}
return SecRandomCopyBytes(kSecRandomDefault, length, baseAddress)
}
guard result == errSecSuccess else {
throw DataError.randomBytesError
}
return randomData
}
}
|
//
// SMUserDetails.swift
// Silly Monks
//
// Created by Sarath on 21/05/16.
// Copyright © 2016 Sarath. All rights reserved.
//
import UIKit
private var _SingletonSharedInstance:SMUserDetails! = SMUserDetails()
class SMUserDetails: NSObject {
var userFirstName: String!
var userLastName: String!
var mobileNumber:String!
var emailAddress:String!
var userID:String!
var macID:String!
var macJobID:String!
var orgID: String!
var gender:String!
class var sharedInstance : SMUserDetails {
return _SingletonSharedInstance
}
fileprivate override init() {
}
func destory () {
_SingletonSharedInstance = nil
}
}
|
//
// TransferViewController.swift
// Slidecoin
//
// Created by Oleg Samoylov on 22.12.2019.
// Copyright © 2019 Oleg Samoylov. All rights reserved.
//
import Toolkit
import UIKit
final class TransferViewController: UIViewController {
// MARK: Private Properties
private let currentUser: User
private let receiver: User
private let withdrawMe: Bool
private let alertService = Assembly.alertService
private let requestSender = Assembly.requestSender
private var formValidationHelper: FormValidationHelper?
// MARK: Outlets
@IBOutlet private weak var amountField: UITextField!
@IBOutlet private weak var scrollView: UIScrollView!
@IBOutlet private weak var stackView: UIStackView!
@IBOutlet private weak var submitButton: BigButton!
var completionHandler: ((Int) -> ())?
// MARK: Lifecycle
init(currentUser: User, receiver: User, withdrawMe: Bool) {
self.currentUser = currentUser
self.receiver = receiver
self.withdrawMe = withdrawMe
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar()
setupFormValidationHelper()
}
// MARK: Private
@IBAction private func submit() {
guard
let amount = amountField.text,
let sum = Int(amount), sum > 0
else {
let alert = self.alertService.alert("В поле ввода суммы допущена ошибка. Убедитесь, что число является целым, положительным и не превышает текущий баланс.")
present(alert, animated: true)
return
}
self.submitButton.showLoading()
if withdrawMe {
let config = RequestFactory.transfer(receiver: receiver, amount: sum)
requestSender.send(config: config) { [weak self] result in
guard let self = self else { return }
self.submitButton.hideLoading()
DispatchQueue.main.async {
switch result {
case .success(let message):
self.completionHandler?(sum)
let alert = self.alertService.alert(message,
title: .info,
isDestructive: false) { _ in
if message.contains("Transaction") {
self.dismiss(animated: true)
}
}
self.present(alert, animated: true)
case .failure(let error):
let alert = self.alertService.alert(error.localizedDescription)
self.present(alert, animated: true)
}
}
}
} else {
let config = RequestFactory.addMoney(userID: receiver.id, amount: sum)
requestSender.send(config: config) { [weak self] result in
guard let self = self else { return }
self.submitButton.hideLoading()
DispatchQueue.main.async {
switch result {
case .success(let message):
self.completionHandler?(sum)
let alert = self.alertService.alert(message,
title: .info,
isDestructive: false) { _ in
if message.contains("success") {
self.dismiss(animated: true)
}
}
self.present(alert, animated: true)
case .failure(let error):
let alert = self.alertService.alert(error.localizedDescription)
self.present(alert, animated: true)
}
}
}
}
}
private func setupFormValidationHelper() {
let textFields: [UITextField] = [amountField]
formValidationHelper = FormValidationHelper(textFields: textFields,
button: submitButton,
stackView: stackView)
}
private func setupNavigationBar() {
navigationItem.title = withdrawMe ? "Перевод" : "Пополнение"
let closeButton = UIBarButtonItem(barButtonSystemItem: .close,
target: self,
action: #selector(close))
navigationItem.rightBarButtonItem = closeButton
}
@objc private func close() {
dismiss(animated: true)
}
}
|
//
// Activity.swift
// Banana
//
// Created by musharraf on 4/19/16.
// Copyright © 2016 StarsDev. All rights reserved.
//
import UIKit
import AFNetworking
class Activity: NSObject
{
var ID = ""
var name = ""
var date = ""
var time = ""
var activity_challange = ""
var desc = ""
var participants = ""
var age = ""
var skill = ""
var gender = ""
var owner_id = ""
var latitude = 0.0
var longitude = 0.0
var formatted_address = ""
var sports_title = ""
var avatar = ""
var sports_id = ""
var request_status = ""
var user_message = ""
var sponsored = 0
var is_owner = false
static func initWithDictionary(dict: Dictionary<String, AnyObject>) -> Activity
{
let activty = Activity()
if let value = dict["activity_id"]
{
activty.ID = String(format: "%d", value as! Int)
}
if let value = dict["date"]
{
activty.date = value as! String
}
if let value = dict["time"]
{
activty.time = value as! String
}
if let value = dict["activity"]
{
activty.activity_challange = value as! String
}
if let value = dict["description"]
{
activty.desc = value as! String
}
if let value = dict["number"]
{
activty.participants = value as! String
}
if let value = dict["start_age"]
{
activty.age = value as! String
}
if let value = dict["skill"]
{
activty.skill = value as! String
}
if let value = dict["gender"]
{
activty.gender = value as! String
}
if let value = dict["latitude"]
{
activty.latitude = value as! Double
}
if let value = dict["longitude"]
{
activty.longitude = value as! Double
}
if let value = dict["formatted_address"]
{
activty.formatted_address = value as! String
}
if let value = dict["sports_title"]
{
activty.sports_title = value as! String
}
if let value = dict["name"]
{
activty.name = value as! String
}
if let value = dict["avatar"]
{
activty.avatar = String(format: "\(restApiUrl)%@", value as! String)
}
if let value = dict["owner_id"]
{
activty.owner_id = String(format: "%d", value as! Int)
}
if let value = dict["sports_id"]
{
activty.sports_id = String(format: "%d", value as! Int)
}
if let value = dict["category_id"]
{
activty.sports_id = String(format: "%d", value as! Int)
}
if let value = dict["request_status"]
{
if !(value is NSNull)
{
activty.request_status = String(format: "%d", value as! Int)
}
}
if let value = dict["user_message"]
{
if !(value is NSNull)
{
activty.user_message = value as! String
}
}
if let value = dict["user_id"]
{
if !(value is NSNull)
{
activty.user_message = value as! String
}
}
if let value = dict["sponsored"]
{
activty.sponsored = value as! Int
}
if let value = dict["is_owner"]
{
if !(value is NSNull)
{
activty.is_owner = value as! Bool
}
}
return activty
}
class func createActivityServiceWithBlock(paramsDict: [String : String] , api_key: String, response:(activity_id: String,created: Bool, error: NSError?) -> Void)
{
let method = "activity"
let urlString = "\(restApiUrl)\(method)"
let manager = AFHTTPSessionManager()
manager.requestSerializer.setValue(api_key, forHTTPHeaderField: "Authorizuser")
manager.responseSerializer = AFJSONResponseSerializer()
manager.POST(urlString, parameters: paramsDict, constructingBodyWithBlock: { (formData) in
for key in paramsDict.keys
{
let tempData = NSMutableData()
tempData.appendData((paramsDict[key]?.dataUsingEncoding(NSUTF8StringEncoding))!)
formData.appendPartWithFormData(tempData, name: key)
}
}, progress: { (progress) in
}, success: { (task, data) in
print("JSON: \(data)")
let activity_id = numberFormater.stringFromNumber((data?.objectForKey("activity_id"))! as! NSNumber)
response(activity_id: activity_id!,created: true, error: nil)
}, failure: { (task, error) in
print(error.localizedDescription)
print(error.userInfo)
response(activity_id: "0",created: false, error: error)
})
}
class func getActivitiesServiceWithBlock(paramsDict: [String : String]? , api_key: String, response:(activities: [Activity], error: NSError?) -> Void)
{
let method = "activities"
let urlString = "\(restApiUrl)\(method)"
let manager = AFHTTPSessionManager()
manager.requestSerializer.setValue(api_key, forHTTPHeaderField: "Authorizuser")
manager.responseSerializer = AFJSONResponseSerializer()
manager.POST(urlString, parameters: paramsDict, constructingBodyWithBlock: { (formData) in
if paramsDict?.keys.count > 0
{
for key in paramsDict!.keys
{
let tempData = NSMutableData()
tempData.appendData((paramsDict![key]?.dataUsingEncoding(NSUTF8StringEncoding))!)
formData.appendPartWithFormData(tempData, name: key)
}
}
}, progress: { (progress) in
}, success: { (task, data) in
print("JSON: \(data)")
var actArray : [Activity] = []
let acts = data?.valueForKey("activities") as! [Dictionary<String, AnyObject>]
for dict in acts
{
let act = Activity.initWithDictionary(dict)
actArray.append(act)
}
response(activities: actArray, error: nil)
}, failure: { (task, error) in
print(error.localizedDescription)
print(error.userInfo)
response(activities: [], error: error)
})
}
class func getOtherUserActivitiesServiceWithBlock(paramsDict: [String : String] , api_key: String, response:(activities: [Activity], error: NSError?) -> Void)
{
let method = "profileactivities"
let urlString = "\(restApiUrl)\(method)"
let manager = AFHTTPSessionManager()
manager.requestSerializer.setValue(api_key, forHTTPHeaderField: "Authorizuser")
manager.responseSerializer = AFJSONResponseSerializer()
manager.GET(urlString, parameters: paramsDict, progress: { (progress) in
}, success: { (task, data) in
print("JSON: \(data)")
var actArray : [Activity] = []
let acts = data?.valueForKey("activities") as! [Dictionary<String, AnyObject>]
for dict in acts
{
let act = Activity.initWithDictionary(dict)
actArray.append(act)
}
response(activities: actArray, error: nil)
}, failure: { (task, error) in
print(error.localizedDescription)
print(error.userInfo)
response(activities: [], error: error)
})
}
class func getActDetailServiceWithBlock(paramsDict: [String : String] , api_key: String, response:(activity: Activity?, error: NSError?) -> Void)
{
let method = "getactivity"
let urlString = "\(restApiUrl)\(method)"
let manager = AFHTTPSessionManager()
manager.requestSerializer.setValue(api_key, forHTTPHeaderField: "Authorizuser")
manager.responseSerializer = AFJSONResponseSerializer()
manager.GET(urlString, parameters: paramsDict, progress: { (progress) in
}, success: { (task, data) in
print("JSON: \(data)")
let act = Activity.initWithDictionary(data?.valueForKey("activities") as! Dictionary<String, AnyObject>)
//print(act);
response(activity: act, error: nil)
}, failure: { (task, error) in
print(error.localizedDescription)
print(error.userInfo)
response(activity: nil, error: nil)
})
}
class func askToJoinServiceWithBlock(paramsDict: [String : String]? , api_key: String, response:(success: Bool , error: NSError?) -> Void)
{
let method = "joinrequest"
let urlString = "\(restApiUrl)\(method)"
let manager = AFHTTPSessionManager()
manager.requestSerializer.setValue(api_key, forHTTPHeaderField: "Authorizuser")
manager.responseSerializer = AFJSONResponseSerializer()
manager.POST(urlString, parameters: paramsDict, constructingBodyWithBlock: { (formData) in
if paramsDict?.keys.count > 0
{
for key in paramsDict!.keys
{
let tempData = NSMutableData()
tempData.appendData((paramsDict![key]?.dataUsingEncoding(NSUTF8StringEncoding))!)
formData.appendPartWithFormData(tempData, name: key)
}
}
}, progress: { (progress) in
}, success: { (task, data) in
print("JSON: \(data)")
response(success: true, error: nil)
}, failure: { (task, error) in
print(error.localizedDescription)
print(error.userInfo)
response(success: false, error: error)
})
}
class func cancelRequestServiceWithBlock(paramsDict: [String : String]? , api_key: String, response:(success: Bool , error: NSError?) -> Void)
{
let method = "cancelrequest"
let urlString = "\(restApiUrl)\(method)"
let manager = AFHTTPSessionManager()
manager.requestSerializer.setValue(api_key, forHTTPHeaderField: "Authorizuser")
manager.responseSerializer = AFJSONResponseSerializer()
manager.POST(urlString, parameters: paramsDict, constructingBodyWithBlock: { (formData) in
if paramsDict?.keys.count > 0
{
for key in paramsDict!.keys
{
let tempData = NSMutableData()
tempData.appendData((paramsDict![key]?.dataUsingEncoding(NSUTF8StringEncoding))!)
formData.appendPartWithFormData(tempData, name: key)
}
}
}, progress: { (progress) in
}, success: { (task, data) in
print("JSON: \(data)")
response(success: true, error: nil)
}, failure: { (task, error) in
print(error.localizedDescription)
print(error.userInfo)
response(success: false, error: error)
})
}
class func getMyActivitiesServiceWithBlock(paramsDict: [String : String]? , api_key: String, response:(allActivities: [[Activity]] , error: NSError?) -> Void)
{
let method = "myactivities"
let urlString = "\(restApiUrl)\(method)"
let manager = AFHTTPSessionManager()
manager.requestSerializer.setValue(api_key, forHTTPHeaderField: "Authorizuser")
manager.responseSerializer = AFJSONResponseSerializer()
manager.GET(urlString, parameters: paramsDict, progress: { (progress) in
}, success: { (task, data) in
print("JSON: \(data)")
if let error = data?.valueForKey("error")
{
if error as! Bool == false
{
var toBeReturnedAllActs : [[Activity]] = []
var tempArray : [Activity] = []
let pending = data?.valueForKey("pendingactivities") as! [Dictionary<String, AnyObject>]
for dict in pending
{
let act = Activity.initWithDictionary(dict)
tempArray.append(act)
}
toBeReturnedAllActs.append(tempArray)
tempArray = []
let current = data?.valueForKey("currentactivities") as! [Dictionary<String, AnyObject>]
for dict in current
{
let act = Activity.initWithDictionary(dict)
tempArray.append(act)
}
toBeReturnedAllActs.append(tempArray)
tempArray = []
let followed = data?.valueForKey("followedactivities") as! [Dictionary<String, AnyObject>]
for dict in followed
{
let act = Activity.initWithDictionary(dict)
tempArray.append(act)
}
toBeReturnedAllActs.append(tempArray)
tempArray = []
let past = data?.valueForKey("pastactivities") as! [Dictionary<String, AnyObject>]
for dict in past
{
let act = Activity.initWithDictionary(dict)
tempArray.append(act)
}
toBeReturnedAllActs.append(tempArray)
response(allActivities: toBeReturnedAllActs, error: nil)
}
else
{
response(allActivities: [], error: nil)
}
}
}, failure: { (task, error) in
print(error.localizedDescription)
print(error.userInfo)
response(allActivities: [], error: error)
})
}
class func getActivityRequestsServiceWithBlock(paramsDict: [String : String]? , api_key: String, response:(allActivities: [[Activity]] , error: NSError?) -> Void)
{
let method = "activityrequests"
let urlString = "\(restApiUrl)\(method)"
let manager = AFHTTPSessionManager()
manager.requestSerializer.setValue(api_key, forHTTPHeaderField: "Authorizuser")
manager.responseSerializer = AFJSONResponseSerializer()
manager.GET(urlString, parameters: paramsDict, progress: { (progress) in
}, success: { (task, data) in
print("JSON: \(data)")
if let error = data?.valueForKey("error")
{
if error as! Bool == false
{
var toBeReturnedAllActs : [[Activity]] = []
if let requests = data?.valueForKey("requests") as? Dictionary<String, [AnyObject]>
{
var tempArray : [Activity] = []
if let pending = requests["pending"] as? [Dictionary<String, AnyObject>]
{
for dict in pending
{
let act = Activity.initWithDictionary(dict)
tempArray.append(act)
}
toBeReturnedAllActs.append(tempArray)
}
tempArray = []
if let accepted = requests["accepted"] as? [Dictionary<String, AnyObject>]
{
for dict in accepted
{
let act = Activity.initWithDictionary(dict)
tempArray.append(act)
}
toBeReturnedAllActs.append(tempArray)
}
tempArray = []
if let rejected = requests["rejected"] as? [Dictionary<String, AnyObject>]
{
for dict in rejected
{
let act = Activity.initWithDictionary(dict)
tempArray.append(act)
}
toBeReturnedAllActs.append(tempArray)
}
response(allActivities: toBeReturnedAllActs, error: nil)
}
}
else
{
response(allActivities: [], error: nil)
}
}
}, failure: { (task, error) in
print(error.localizedDescription)
print(error.userInfo)
response(allActivities: [], error: error)
})
}
static let numberFormater: NSNumberFormatter = {
let formatter = NSNumberFormatter()
formatter.formatterBehavior = .BehaviorDefault
return formatter
}()
class func deleteActivityServiceWithBlock(paramsDict: [String : String] , api_key: String, response:(message: String, deleted: Bool , error: NSError?) -> Void)
{
let method = "deleteactivity"
let urlString = "\(restApiUrl)\(method)"
let manager = AFHTTPSessionManager()
manager.requestSerializer.setValue(api_key, forHTTPHeaderField: "Authorizuser")
manager.responseSerializer = AFJSONResponseSerializer()
manager.POST(urlString, parameters: nil, constructingBodyWithBlock: { (formData) in
for key in paramsDict.keys
{
let tempData = NSMutableData()
tempData.appendData((paramsDict[key]?.dataUsingEncoding(NSUTF8StringEncoding))!)
formData.appendPartWithFormData(tempData, name: key)
}
}, progress: { (progress) in
}, success: { (task, data) in
print("JSON: \(data)")
let message = data?.objectForKey("message") as? String
response(message: message!,deleted: true, error: nil)
}, failure: { (task, error) in
print(error.localizedDescription)
print(error.userInfo)
response(message: "Failed to delete activity",deleted: false, error: error)
})
}
}
|
//
// ViewController.swift
// See-Food
//
// Created by Chaitanya Ramji on 9/18/17.
// Copyright © 2017 Chaitanya Ramji. All rights reserved.
//
import UIKit
import CoreML
import LBTAComponents
class ViewController: UIViewController, AVCapturePhotoCaptureDelegate {
lazy var captureButton : UIButton = {
let button = UIButton(type: .system)
button.setImage(#imageLiteral(resourceName: "capture_photo").withRenderingMode(.alwaysOriginal), for: .normal)
button.addTarget(self, action: #selector(handleCaptureButton), for: .touchUpInside)
return button
}()
let output = AVCapturePhotoOutput()
let model = SeeFood()
override var prefersStatusBarHidden: Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
prepareCameraSession()
preparecaptureButton()
}
func preparecaptureButton()
{
let val = w/2 - 40
view.addSubview(captureButton)
_ = captureButton.anchorWithReturnAnchors(nil, left: nil, bottom: view.bottomAnchor, right: nil, topConstant: 0, leftConstant: 0, bottomConstant: 24, rightConstant: 0, widthConstant: 80, heightConstant: 80)
captureButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
view.addSubview(mediaButton)
_ = mediaButton.anchorWithReturnAnchors(captureButton.topAnchor, left: view.leftAnchor, bottom: captureButton.bottomAnchor, right: captureButton.leftAnchor, topConstant: 15, leftConstant: val/2 - 25, bottomConstant: 15, rightConstant: val/2 - 25, widthConstant: 0, heightConstant: 0)
view.addSubview(scanButton)
_ = scanButton.anchorWithReturnAnchors(captureButton.topAnchor, left: captureButton.rightAnchor, bottom: captureButton.bottomAnchor, right: view.rightAnchor, topConstant: 15, leftConstant: val/2 - 25, bottomConstant: 15, rightConstant: val/2 - 25, widthConstant: 0, heightConstant: 0)
}
fileprivate func prepareCameraSession()
{
let captureSession = AVCaptureSession()
let mediaType = AVMediaTypeVideo
let device = AVCaptureDevice.defaultDevice(withMediaType: mediaType)
do
{
let input = try AVCaptureDeviceInput(device: device)
if captureSession.canAddInput(input)
{
captureSession.addInput(input)
}
}
catch let error
{
print("Couldn't setup camera input: ",error)
}
if captureSession.canAddOutput(output)
{
captureSession.addOutput(output)
}
guard let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) else {return}
previewLayer.frame = view.frame
view.layer.addSublayer(previewLayer)
captureSession.startRunning()
}
func handleCaptureButton()
{
let settings = AVCapturePhotoSettings()
output.capturePhoto(with: settings, delegate: self)
imageView.isHidden = true
}
}
extension ViewController {
func capture(_ output: AVCapturePhotoOutput, didFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?, previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) {
guard let imageData = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: photoSampleBuffer!, previewPhotoSampleBuffer: previewPhotoSampleBuffer) else {return}
let previewImage = UIImage(data: imageData)
guard let input = model.preprocess(image: previewImage!) else {
print("preprocessing failed")
return
}
guard let result = try? model.prediction(image: input) else {
print("prediction failed")
return
}
let confidence = result.foodConfidence["\(result.classLabel)"]! * 100.0
let converted = String(format: "%.2f", confidence)
print("Prediciton is: \(result.classLabel) - \(converted) %")
}
}
|
//
// User.swift
// PetPicker
//
// Created by Steven Schwedt on 10/3/18.
// Copyright © 2018 Steven Schwedt. All rights reserved.
//
import Foundation
class User {
var id = 0
var name = ""
var key = ""
var speciesToAdopt = ""
var description = ""
var pic = ""
var role = ""
init(data: [String: Any]) {
id = data["id"] as? Int ?? 0
name = data["name"] as? String ?? ""
key = data["key"] as? String ?? ""
speciesToAdopt = data["species_to_adopt"] as? String ?? ""
description = data["description"] as? String ?? ""
pic = data["pic"] as? String ?? ""
role = data["role"] as? String ?? ""
}
func setAsDefault() {
let defaults = UserDefaults.standard
let userData = ["id": id, "name": name, "description": description, "pic": pic, "role": role, "sepcies_to_adopt": speciesToAdopt, "key": key] as [String : Any]
defaults.set(userData, forKey: "user")
}
class func getUserFromDefault() -> User {
let defaults = UserDefaults.standard
if let userInfo = defaults.dictionary(forKey: "user") {
let user = User(data: userInfo )
return user
}
return User(data: ["id": 0])
}
}
|
//
// ViewController.swift
// ZeroTier One
//
// Created by Grant Limberg on 8/27/15.
// Copyright © 2015 Zero Tier, Inc. All rights reserved.
//
import UIKit
import NetworkExtension
class NetworkListViewController: UITableViewController {
var _deviceId: String? = nil
var vpnManagers: [ZTVPN] = [] {
willSet {
if !newValue.isEmpty {
for mgr in vpnManagers {
mgr.removeConfigObserver(self)
mgr.removeStatusOserver(self)
}
}
}
didSet {
for mgr in vpnManagers {
mgr.addConfigObserver(self, selector: #selector(NetworkListViewController.onVPNConfigChanged(_:)))
mgr.addStatusObserver(self, selector: #selector(NetworkListViewController.onManagerStateChanged(_:)))
}
tableView.reloadData()
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
navigationItem.leftBarButtonItem = editButtonItem
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 75
navigationController!.navigationBar.tintColor = UIColor(red: 35.0/255.0, green: 68.0/255.0, blue: 71.0/255.0, alpha: 1.0)
let defaults = UserDefaults.standard
if var deviceId = defaults.string(forKey: "com.zerotier.one.deviceId") {
while deviceId.characters.count < 10 {
deviceId = "0\(deviceId)"
}
_deviceId = deviceId
let idButton = UIBarButtonItem(title: deviceId, style: .plain, target: self, action: #selector(NetworkListViewController.showCopy(_:)))
idButton.tintColor = UIColor.white
self.setToolbarItems([idButton], animated: true)
}
//print(RouteTableManager.formatRouteTable())
//print("\(NSSearchPathForDirectoriesInDomains(Foundation.FileManager.SearchPathDirectory.cachesDirectory, Foundation.FileManager.SearchPathDomainMask.userDomainMask, true).first)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//PiwikTracker.sharedInstance().sendView("Network List");
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.vpnManagers.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "NetworkTableCell", for: indexPath) as! NetworkTableCell
let manager = vpnManagers[indexPath.row]
let networkId = manager.getNetworkID()
cell.networkIdLabel.text = String(networkId.uint64Value, radix: 16)
cell.networkNameLabel.text = manager.getNetworkName()
cell.onOffSwitch.setOn(false, animated: true)
cell.vpnManager = manager
cell.tableViewController = self
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let network = vpnManagers[indexPath.row]
let title = "Delete \(network.getNetworkName()!)?"
let message = "Are you sure you want to delete this network?"
let ac = UIAlertController(title: title,
message: message,
preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "Cancel",
style: .cancel, handler: nil)
ac.addAction(cancelAction)
let deleteAction = UIAlertAction(title: "Delete",
style: .destructive,
handler: { (action) -> Void in
network.remove() { (error) -> Void in
if error != nil {
////DDLogError("Error removing network: \(String(describing: error))")
return
}
let index = self.vpnManagers.index(of: network)
self.vpnManagers.remove(at: index!)
OperationQueue.main.addOperation() {
tableView.reloadData()
}
}
})
ac.addAction(deleteAction)
let view = tableView.cellForRow(at: indexPath) as! NetworkTableCell
ac.popoverPresentationController?.sourceView = view.networkNameLabel
present(ac, animated: true, completion: nil)
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let nw = indexPath.row
let mgr = vpnManagers[nw]
if mgr.status() == .connected {
self.performSegue(withIdentifier: "ShowNetworkInfo", sender: self)
}
else {
self.performSegue(withIdentifier: "ShowNetworkNotConnected", sender: self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let id = segue.identifier {
switch id {
case "NewNetwork":
break
//DDLogDebug("Adding a new network")
case "ShowNetworkInfo":
//DDLogDebug("Showing network info")
if let row = tableView.indexPathForSelectedRow?.row {
let network = vpnManagers[row]
let networkInfoView = segue.destination as! NetworkInfoViewController
networkInfoView.manager = network
}
case "ShowNetworkNotConnected":
//DDLogDebug("Show Network: Not Connected")
if let row = tableView.indexPathForSelectedRow?.row {
let network = vpnManagers[row]
let networkInfoView = segue.destination as! NotConnectedViewController
networkInfoView.manager = network
}
default:
break
}
}
else {
////DDLogError("Unknown segue identifier")
}
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
switch identifier {
case "NewNetwork":
return true
case "ShowNetworkInfo":
if let row = tableView.indexPathForSelectedRow?.row {
let mgr = vpnManagers[row]
if mgr.status() == .connected {
return true
}
else {
return false
}
}
else {
return false
}
case "ShowNetworkNotConnected":
if let row = tableView.indexPathForSelectedRow?.row {
let mgr = vpnManagers[row]
if mgr.status() == .connected {
return false
}
else {
return true
}
}
else {
return true
}
default:
return false
}
}
func addNetwork(_ networkId: UInt64, name: String, allowDefault: Bool = false) {
for mgr in vpnManagers {
let curNetworkId = mgr.getNetworkID().uint64Value
if networkId == curNetworkId {
//DDLogWarn("Configuration with network id \(networkId) already exists")
TWStatus.show("Network already exists!")
TWStatus.dismiss(after: 3.0)
return
}
}
let newManager = NETunnelProviderManager()
let proto = NETunnelProviderProtocol()
proto.providerBundleIdentifier = "com.tunnel.unique.ZeroTierPTP"
proto.serverAddress = "127.0.0.1"
var config = [String:NSObject]()
config["networkid"] = NSNumber(value: networkId as UInt64)
config["allowDefault"] = NSNumber(value: allowDefault as Bool)
proto.providerConfiguration = config
newManager.protocolConfiguration = proto
newManager.localizedDescription = name
newManager.isEnabled = false
newManager.saveToPreferences() { error in
if error != nil {
////DDLogError("Error adding new network: \(String(describing: error))")
}
ZTVPNManager.sharedManager().loadVpnSettings() { newManagers, error in
if error != nil {
////DDLogError("\(String(describing: error))")
return
}
if let vpnManagers = newManagers {
OperationQueue.main.addOperation() {
self.vpnManagers = vpnManagers
}
}
else {
////DDLogError("No managers loaded")
}
}
}
}
func onVPNConfigChanged(_ note: Notification) {
}
func onManagerStateChanged(_ note: Notification) {
if let connection = note.object as? NETunnelProviderSession {
// get
let requestDict : NSDictionary = ["request": "deviceid"]
TunnelCommunication.sendRequest(connection, message: requestDict) { (responseDict) in
if let dict = responseDict {
OperationQueue.main.addOperation() {
var deviceId = String( (dict["deviceid"] as! NSNumber).uint64Value, radix: 16)
while deviceId.characters.count < 10 {
deviceId = "0\(deviceId)"
}
//DDLogDebug("Got device id: \(deviceId)")
self._deviceId = deviceId
let defaults = UserDefaults.standard
if let savedDeviceId = defaults.string(forKey: "com.zerotier.one.deviceId") {
if savedDeviceId != deviceId {
let idButton = UIBarButtonItem(title: deviceId, style: .plain, target: self, action: #selector(NetworkListViewController.showCopy(_:)))
idButton.tintColor = UIColor.white
self.setToolbarItems([idButton], animated: true)
defaults.setValue(deviceId, forKey: "com.zerotier.one.deviceId")
defaults.synchronize()
}
}
else {
let idButton = UIBarButtonItem(title: deviceId, style: .plain, target: self, action: #selector(NetworkListViewController.showCopy(_:)))
idButton.tintColor = UIColor.white
self.setToolbarItems([idButton], animated: true)
defaults.setValue(deviceId, forKey: "com.zerotier.one.deviceId")
defaults.synchronize()
}
}
}
}
if connection.status == .connected {
updateConnectedNetworkName()
}
}
}
func showCopy(_ sender: AnyObject) {
if let id = _deviceId {
//DDLogDebug("id \(id) copied!")
let pb = UIPasteboard.general
pb.string = id
}
}
func findConnectedNetwork() -> ZTVPN? {
for mgr in vpnManagers {
if mgr.status() == .connected {
return mgr
}
}
return nil
}
func updateConnectedNetworkName() {
let connectedManager = findConnectedNetwork()
if let mgr = connectedManager {
let nwid = mgr.getNetworkID()
let requestDict = ["request": "networkinfo", "networkid": nwid] as [String : Any]
if let m = mgr as? ZTVPN_Device {
TunnelCommunication.sendRequest(m.mgr.connection as! NETunnelProviderSession, message: requestDict as NSDictionary) { (responseDict) in
if let dict = responseDict {
if mgr.getNetworkName() == nil || mgr.getNetworkName()!.isEmpty {
m.mgr.localizedDescription = dict["name"] as? String
m.saveWithCompletionHandler() { (error) in
if error != nil {
////DDLogError("\(String(describing: error))")
}
else {
ZTVPNManager.sharedManager().loadVpnSettings() { newManagers, error in
if error != nil {
////DDLogError("\(String(describing: error))")
return
}
if let vpnManagers = newManagers {
OperationQueue.main.addOperation() {
self.vpnManagers = vpnManagers
}
}
else {
////DDLogError("No managers loaded")
}
}
}
}
}
}
}
}
}
}
}
|
//
// UIViewController+StoryboardIdentifier.swift
// cosmos
//
// Created by HieuiOS on 2/4/17.
// Copyright © 2017 Savvycom. All rights reserved.
//
import UIKit
extension ViewController : StoryboardIdentifiable { }
|
//
// ItemAttributes.swift
// Recruitment-iOS
//
// Created by Oleksandr Bambulyak on 19/03/2020.
// Copyright © 2020 Untitled Kingdom. All rights reserved.
//
import Foundation
import UIKit
class ItemAttributes {
var name: String = ""
var color: UIColor = UIColor.white
var preview: String?
var desc: String?
init(name: String, color: UIColor, preview: String, desc: String) {
self.name = name
self.color = color
self.preview = preview
self.desc = desc
}
static func convert(from model: ItemAttributesApiResponseModel) -> ItemAttributes {
let color: UIColor!
switch model.color {
case "Red": color = UIColor.red
case "Green": color = UIColor.green
case "Blue": color = UIColor.blue
case "Yellow": color = UIColor.yellow
case "Purple": color = UIColor.purple
default: color = UIColor.black
}
let model = ItemAttributes(name: model.name,
color: color,
preview: model.preview ?? "",
desc: model.desc ?? ""
)
return model
}
}
|
//
// APIKey.swift
// Snacktacular
//
// Created by Kyle Gangi on 4/10/20.
// Copyright © 2020 John Gallaugher. All rights reserved.
//
import Foundation
struct APIKey {
static let googlePlacesKey = "AIzaSyBfer2jZU2p5K-oMgfNrA8GpBVfO5_-5L8"
}
|
//
// ListThemes.swift
// radio
//
// Created by MacBook 13 on 8/21/18.
// Copyright © 2018 MacBook 13. All rights reserved.
//
import Foundation
class ListThemes : ModelRequest{
/*
Contains the radio list
*/
var listThemes:[ThemeModel]! = []
}
|
//
// EditSymtompDetail.swift
// KindCer
//
// Created by Muhammad Tafani Rabbani on 21/11/19.
// Copyright © 2019 Muhammad Tafani Rabbani. All rights reserved.
//
import SwiftUI
struct EditSymtompDetail: View {
@State var title = "demam"
@State var status = "Pilih suhu badan"
@State var isSheet : Bool = false
@State var sheetId = 0
@State var sympthoms : SymptompModel = SymptompModel(type: .lainnya)
@State var kondisi = ""
@State var catatan = ""
@State var obat = ""
@State var catatan_obat = ""
@ObservedObject var recordModel : RecordModel
@Binding var recordDetail : RecordType
@Binding var homeSheet : Bool
@State var cDate : Date = Date()
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View{
GeometryReader { geometry in
VStack {
ZStack(alignment: .center) {
Rectangle().foregroundColor(Color("Primary")).frame( height: 70)
VStack {
Rectangle().foregroundColor(.white).opacity(0.3).frame(width: 50, height: 5).cornerRadius(10)
Text("Ubah Gejala").font(.system(size: 24, design: .default)).bold().foregroundColor(.white)
}
HStack{
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Tutup").foregroundColor(.white).padding(4)
}.padding(16)
Spacer()
}
HStack{
Spacer()
Button(action: {
self.recordModel.updateInId(id: self.recordDetail.id, key: "kondisi", value: self.kondisi, tgl: self.recordDetail.tanggal)
self.recordModel.updateInId(id: self.recordDetail.id, key: "catatan_record", value: self.catatan, tgl: self.recordDetail.tanggal)
self.recordModel.updateInId(id: self.recordDetail.id, key: "obat", value: self.obat, tgl: self.recordDetail.tanggal)
self.recordModel.updateInId(id: self.recordDetail.id, key: "catatan_obat", value: self.catatan_obat, tgl: self.recordDetail.tanggal)
self.recordDetail.kondisi = self.kondisi
self.recordDetail.catatan_record = self.catatan
self.recordDetail.obat = self.obat
self.recordDetail.catatan_obat = self.catatan_obat
self.homeSheet = false
}) {
Text("Simpan").foregroundColor(.white)
}//.padding(.init(top: 16, leading: 0, bottom: 0, trailing: 0))
}.padding(.horizontal)
}.padding(.bottom,40).offset(y: -1)
// headerModal(title: "Edit Symtomp")
if !(self.title == "Lainnya"){
formLargeSizePath(title1: "Kondisi", title2: self.recordDetail.type, status: self.$kondisi, icon: "termometer", width: 15, height: 28).frame( height: 89).onTapGesture {
self.isSheet = true
self.sheetId = 0
}.onAppear{
self.kondisi = self.recordDetail.kondisi
}
}
formLargeSizePath(title1: "Catatan", title2: "", status: self.$catatan, icon: "pensil", width: 25, height: 25).frame( height: 89).onTapGesture {
self.isSheet = true
self.sheetId = 1
}.onAppear{
self.catatan = self.recordDetail.catatan_record
}
formLargeSizePath(title1: "Obat", title2: "", status: self.$obat, icon: "obat", width: 26, height: 26).frame( height: 89).onTapGesture {
self.isSheet = true
self.sheetId = 2
}.onAppear{
self.obat = self.recordDetail.obat
}
Spacer()
// Button(action: {
//
// self.recordModel.updateInId(id: self.recordDetail.id, key: "kondisi", value: self.kondisi, tgl: self.recordDetail.tanggal)
// self.recordModel.updateInId(id: self.recordDetail.id, key: "catatan_record", value: self.catatan, tgl: self.recordDetail.tanggal)
// self.recordModel.updateInId(id: self.recordDetail.id, key: "obat", value: self.obat, tgl: self.recordDetail.tanggal)
// self.recordModel.updateInId(id: self.recordDetail.id, key: "catatan_obat", value: self.catatan_obat, tgl: self.recordDetail.tanggal)
//
// self.recordDetail.kondisi = self.kondisi
// self.recordDetail.catatan_record = self.catatan
// self.recordDetail.obat = self.obat
// self.recordDetail.catatan_obat = self.catatan_obat
// // self.recordModel.readData(date: self.recordDetail.tanggal)
// self.homeSheet = false
// // print(self.recordModel.recordAtIndex(id: self.recordDetail.id))
// }) {
// ZStack{
// Rectangle().foregroundColor(Color.init(#colorLiteral(red: 0.9137254902, green: 0.262745098, blue: 0.4901960784, alpha: 1))).frame(width: geometry.frame(in: .global).width/1.3, height: geometry.frame(in: .global).height/13.3).cornerRadius(10)
// HStack {
// Text("Simpan").foregroundColor(.white)
// }
// }.padding(.bottom, 40)
// }.disabled(self.kondisi.isEmpty).opacity(self.kondisi.isEmpty ? 0.4:1)
}.background(Rectangle().foregroundColor(Color.init(#colorLiteral(red: 0.9450980392, green: 0.937254902, blue: 0.9490196078, alpha: 1))).edgesIgnoringSafeArea(.all))
.sheet(isPresented: self.$isSheet) {
if self.sheetId == 0{
PickerForm(title: self.title, record: $recordDetail)
}else if self.sheetId == 1{
TambahCatatanView(catatan: self.$catatan,isSheet: self.$isSheet)
}else{
TambahCatatanPengobatan(obat: self.$obat, catatan_obat: self.$catatan_obat,isSheet: self.$isSheet)
}
}
}
}
}
|
//
// ScreenSize.swift
// StashMob
//
// Created by Scott Jones on 8/20/16.
// Copyright © 2016 Scott Jones. All rights reserved.
//
import UIKit
public struct ScreenSize {
public static let SCREEN_WIDTH = UIScreen.mainScreen().bounds.size.width
public static let SCREEN_HEIGHT = UIScreen.mainScreen().bounds.size.height
public static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
public static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}
public struct DeviceType {
public static let IS_IPHONE_4_OR_LESS = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0
public static let IS_IPHONE_5 = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0
public static let IS_IPHONE_6 = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0
public static let IS_IPHONE_6P = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0
public static let IS_IPHONE_6_OR_GREATER = UIDevice.currentDevice().userInterfaceIdiom == .Phone && ScreenSize.SCREEN_MAX_LENGTH >= 667.0
} |
//
// COSStoryboard.swift
// CoffeeOrderSystem
//
// Created by 尚靖 on 2018/6/18.
// Copyright © 2018年 尚靖. All rights reserved.
//
import Foundation
import UIKit
extension UIStoryboard {
static func mainStoryboatd() -> UIStoryboard {
return UIStoryboard(name: "Main", bundle: nil)
}
static func listStoryboatd() -> UIStoryboard {
return UIStoryboard(name: "OrderList", bundle: nil)
}
static func tabBarStoryboatd() -> UIStoryboard {
return UIStoryboard(name: "TabBar", bundle: nil)
}
}
|
//
// BaseViewController.swift
// renrendai-swift
//
// Created by 周希财 on 2019/8/7.
// Copyright © 2019 VIC. All rights reserved.
//
import UIKit
import Toast_Swift
import RxCocoa
import RxSwift
import HEPhotoPicker
import PKHUD
typealias BarBlock = () -> ()
typealias camera = (Array<Dictionary<String,Any>>, [UIImage]) -> ()
class BaseViewController: UIViewController {
var block:camera?
var disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
AudioManager.shared.openBackgroundAudioAutoPlay = true
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
func setupRightBarButtonItemSelectorName(text: String, block: @escaping BarBlock) -> UIButton{
let button : UIButton = UIButton.init(type: UIButton.ButtonType.system)
button.frame = CGRect(x: -20, y: 0, width: 90, height: 30)
button.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.left
button.setTitleColor(systemColor, for: UIControl.State.normal)
button.setTitle(text, for: UIControl.State.normal)
button.setTitle(text, for: UIControl.State.highlighted)
button.rx.tap
.subscribe(onNext: {
block()
})
.disposed(by: disposeBag)
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: button)
return button
}
func setupRightBarButtonItemSelectorName(imageName: String, block: @escaping BarBlock) -> UIButton {
let button : UIButton = UIButton.init(type: UIButton.ButtonType.system)
button.frame = CGRect(x: -20, y: 0, width: 30, height: 30)
button.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.left
button.setTitleColor(systemColor, for: UIControl.State.normal)
button.setImage(UIImage(named: imageName)!.withRenderingMode(.alwaysOriginal), for: .normal)
button.setImage(UIImage(named: imageName)!.withRenderingMode(.alwaysOriginal), for: .selected)
button.rx.tap
.subscribe(onNext: {
block()
})
.disposed(by: disposeBag)
button.isHidden = true
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: button)
return button
}
func setupBarButtonItemSelectorName(text:String = "返回", block: @escaping BarBlock){
let button : UIButton = UIButton.init(type: UIButton.ButtonType.system)
let barButton = UIBarButtonItem.init(customView: button)
button.contentEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 0);
self.navigationItem.leftBarButtonItem = barButton
button.setTitle(text, for: UIControl.State.normal)
button.setTitle(text, for: UIControl.State.highlighted)
button.setTitleColor(systemColor, for: UIControl.State.normal)
button.setImage(UIImage(named: "ic_turn")!.withRenderingMode(.alwaysOriginal), for: .normal)
button.setImage(UIImage(named: "ic_turn")!.withRenderingMode(.alwaysOriginal), for: .selected)
button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
button.rx.tap
.subscribe(onNext: {
block()
})
.disposed(by: disposeBag)
}
// 获取当前显示的ViewController
class func currentViewController(base: UIViewController? = Window!.rootViewController) -> BaseViewController?
{
if let nav = base as? UINavigationController
{
return currentViewController(base: nav.visibleViewController)
}
if let tab = base as? UITabBarController
{
return currentViewController(base: tab.selectedViewController)
}
if let presented = base?.presentedViewController
{
return currentViewController(base: presented)
}
return base as? BaseViewController
}
deinit {
print("==============","\(self)","被销毁")
}
func showToast(_ message: String?){
main {
self.view.makeToast(message,position:.top)
}
}
func showHUD(){
main{
HUD.show(.progress)
}
}
func hideHUD(){
main{
HUD.hide()
}
}
}
extension BaseViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate, HEPhotoPickerViewControllerDelegate{
func open(maxCountOfImage:Int = 9, result: @escaping camera){
block = result
let alertVC = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertController.Style.actionSheet)
if isPad {
alertVC.popoverPresentationController?.sourceView = self.view
alertVC.popoverPresentationController?.permittedArrowDirections = []
alertVC.popoverPresentationController?.sourceRect = CGRect(origin:self.view.center, size: CGSize(width:1, height: 1))
}
let action1 = UIAlertAction(title: "拍照", style:.default) { (action) in
if PhotoTool.IsOpenCamera(){
self.openCamera()
}else{
PhotoTool.requestAccess(authorized: {
self.openCamera()
}, rejected: {
Alert.showAlert2(self, title: "提示", message: "请开启相机功能", alertTitle1: "开启", style1: .default, confirmCallback1: {
PhotoTool.openIphoneSetting()
}, alertTitle2: "取消", style2: .cancel, confirmCallback2: {
});
})
}
}
let action2 = UIAlertAction(title: "从相册选择", style:.default) { (action) in
if PhotoTool.canAccessPhotoLib(){
self.openAlbum(maxCountOfImage:maxCountOfImage)
}else{
PhotoTool.requestAuthorizationForPhotoAccess(authorized: {
self.openAlbum(maxCountOfImage:maxCountOfImage)
}, rejected: {
Alert.showAlert2(self, title: "提示", message: "请开启相册功能", alertTitle1: "开启", style1: .default, confirmCallback1: {
PhotoTool.openIphoneSetting()
}, alertTitle2: "取消", style2: .cancel, confirmCallback2: {
});
})
}
}
let action3 = UIAlertAction(title: "取消", style:.cancel) { (action) in
}
alertVC.addAction(action1)
alertVC.addAction(action2)
alertVC.addAction(action3)
self.present(alertVC, animated: true, completion: nil)
}
func openAlbum(maxCountOfImage:Int){
// 配置项
let option = HEPickerOptions.init()
// 图片和视频只能选择一种
option.mediaType = .image
// 选择图片的最大个数
option.maxCountOfImage = maxCountOfImage
// 创建选择器
let picker = HEPhotoPickerViewController.init(delegate: self, options: option)
picker.modalPresentationStyle = .fullScreen
// 弹出
self.hePresentPhotoPickerController(picker: picker, animated: true)
}
func openCamera(){
let IPC = UIImagePickerController()
IPC.sourceType = .camera
IPC.allowsEditing = true
IPC.delegate = self
self.present(IPC, animated: true) {}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let imagePickerc = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
UIImage.imgaetoByte(imageArr: [imagePickerc]) { (result) in
main {
self.block!(result, [imagePickerc])
}
}
self.dismiss(animated: true, completion: nil)
}
func pickerController(_ picker: UIViewController, didFinishPicking selectedImages: [UIImage], selectedModel: [HEPhotoAsset]) {
UIImage.imgaetoByte(imageArr: selectedImages) { (result) in
main {
self.block!(result, selectedImages)
}
}
}
}
|
import UIKit
import RxSwift
import ThemeKit
import SnapKit
import SectionsTableView
import ComponentKit
import HUD
class MarketDiscoveryViewController: ThemeSearchViewController {
private let viewModel: MarketDiscoveryViewModel
private let disposeBag = DisposeBag()
private let headerView: MarketSingleSortHeaderView
private let spinner = HUDActivityView.create(with: .medium24)
private let errorView = PlaceholderViewModule.reachabilityView()
private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
private let tableView = SectionsTableView(style: .grouped)
private let notFoundPlaceholder = PlaceholderView(layoutType: .keyboard)
private var discoveryViewItems = [MarketDiscoveryViewModel.DiscoveryViewItem]()
private var searchViewItems = [MarketDiscoveryViewModel.SearchViewItem]()
private var isLoaded = false
init(viewModel: MarketDiscoveryViewModel, sortHeaderViewModel: MarketSingleSortHeaderViewModel) {
self.viewModel = viewModel
headerView = MarketSingleSortHeaderView(viewModel: sortHeaderViewModel)
super.init(scrollViews: [collectionView, tableView])
hidesBottomBarWhenPushed = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "market_discovery.title".localized
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "market_discovery.filters".localized, style: .plain, target: self, action: #selector(onTapFilters))
view.addSubview(headerView)
headerView.snp.makeConstraints { maker in
maker.top.equalTo(view.safeAreaLayoutGuide)
maker.leading.trailing.equalToSuperview()
maker.height.equalTo(MarketSingleSortHeaderView.height)
}
view.addSubview(collectionView)
collectionView.snp.makeConstraints { maker in
maker.top.equalTo(headerView.snp.bottom)
maker.leading.trailing.bottom.equalToSuperview()
}
collectionView.backgroundColor = .clear
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(MarketDiscoveryCell.self, forCellWithReuseIdentifier: String(describing: MarketDiscoveryCell.self))
collectionView.register(MarketDiscoveryTitleCell.self, forCellWithReuseIdentifier: String(describing: MarketDiscoveryTitleCell.self))
view.addSubview(spinner)
spinner.snp.makeConstraints { maker in
maker.center.equalToSuperview()
}
spinner.startAnimating()
view.addSubview(errorView)
errorView.snp.makeConstraints { maker in
maker.edges.equalTo(view.safeAreaLayoutGuide)
}
errorView.configureSyncError(action: { [weak self] in self?.onRetry() })
view.addSubview(tableView)
tableView.snp.makeConstraints { maker in
maker.edges.equalToSuperview()
}
tableView.sectionDataSource = self
tableView.backgroundColor = .clear
tableView.separatorStyle = .none
view.addSubview(notFoundPlaceholder)
notFoundPlaceholder.snp.makeConstraints { maker in
maker.edges.equalTo(view.safeAreaLayoutGuide)
}
notFoundPlaceholder.image = UIImage(named: "not_found_48")
notFoundPlaceholder.text = "market_discovery.not_found".localized
subscribe(disposeBag, viewModel.discoveryViewItemsDriver) { [weak self] in self?.sync(discoveryViewItems: $0) }
subscribe(disposeBag, viewModel.searchViewItemsDriver) { [weak self] in self?.sync(searchViewItems: $0) }
subscribe(disposeBag, viewModel.discoveryLoadingDriver) { [weak self] loading in
self?.spinner.isHidden = !loading
if loading {
self?.spinner.startAnimating()
} else {
self?.spinner.stopAnimating()
}
}
subscribe(disposeBag, viewModel.discoveryErrorDriver) { [weak self] in self?.errorView.isHidden = $0 == nil }
subscribe(disposeBag, viewModel.favoritedDriver) { HudHelper.instance.show(banner: .addedToWatchlist) }
subscribe(disposeBag, viewModel.unfavoritedDriver) { HudHelper.instance.show(banner: .removedFromWatchlist) }
subscribe(disposeBag, viewModel.failDriver) { HudHelper.instance.show(banner: .error(string: "alert.unknown_error".localized)) }
isLoaded = true
}
@objc private func onTapFilters() {
let viewController = MarketAdvancedSearchModule.viewController()
navigationController?.pushViewController(viewController, animated: true)
}
private func sync(discoveryViewItems: [MarketDiscoveryViewModel.DiscoveryViewItem]?) {
if let discoveryViewItems = discoveryViewItems {
self.discoveryViewItems = discoveryViewItems
collectionView.reloadData()
collectionView.isHidden = false
headerView.isHidden = false
} else {
collectionView.isHidden = true
headerView.isHidden = true
}
}
private func sync(searchViewItems: [MarketDiscoveryViewModel.SearchViewItem]?) {
if let searchViewItems = searchViewItems {
self.searchViewItems = searchViewItems
reloadTable()
tableView.isHidden = false
notFoundPlaceholder.isHidden = !searchViewItems.isEmpty
} else {
tableView.isHidden = true
notFoundPlaceholder.isHidden = true
}
}
@objc private func onRetry() {
viewModel.refresh()
}
override func onUpdate(filter: String?) {
viewModel.onUpdate(filter: filter ?? "")
}
private func reloadTable() {
tableView.buildSections()
if isLoaded {
tableView.reload()
}
}
private func onSelect(viewItem: MarketDiscoveryViewModel.SearchViewItem) {
guard let module = CoinPageModule.viewController(coinUid: viewItem.uid) else {
return
}
present(module, animated: true)
}
private func rowActions(index: Int) -> [RowAction] {
let type: RowActionType
let iconName: String
let action: (UITableViewCell?) -> ()
if viewModel.isFavorite(index: index) {
type = .destructive
iconName = "star_off_24"
action = { [weak self] _ in
self?.viewModel.unfavorite(index: index)
}
} else {
type = .additive
iconName = "star_24"
action = { [weak self] _ in
self?.viewModel.favorite(index: index)
}
}
return [
RowAction(
pattern: .icon(image: UIImage(named: iconName)?.withTintColor(type.iconColor), background: type.backgroundColor),
action: action
)
]
}
}
extension MarketDiscoveryViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
2
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
section == 0 ? 1 : discoveryViewItems.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: indexPath.section == 0 ? MarketDiscoveryTitleCell.self : MarketDiscoveryCell.self), for: indexPath)
}
}
extension MarketDiscoveryViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if let cell = cell as? MarketDiscoveryCell {
cell.set(viewItem: discoveryViewItems[indexPath.item])
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard indexPath.section != 0 else {
return
}
switch discoveryViewItems[indexPath.item].type {
case .topCoins:
let viewController = MarketTopModule.viewController()
present(viewController, animated: true)
case .category(let category):
let viewController = MarketCategoryModule.viewController(category: category)
present(viewController, animated: true)
}
}
}
extension MarketDiscoveryViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
indexPath.section == 0 ?
CGSize(width: collectionView.width, height: .heightSingleLineCell) :
CGSize(width: (collectionView.width - .margin16 * 2 - .margin12) / 2, height: MarketDiscoveryCell.cellHeight)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
section == 0 ?
.zero :
UIEdgeInsets(top: .margin12, left: .margin16, bottom: .margin32, right: .margin16)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
.margin12
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
.margin12
}
}
extension MarketDiscoveryViewController: SectionsDataSource {
func buildSections() -> [SectionProtocol] {
[
Section(
id: "coins",
headerState: .margin(height: .margin12),
footerState: .margin(height: .margin32),
rows: searchViewItems.enumerated().map { index, viewItem in
let isLast = index == searchViewItems.count - 1
return CellBuilderNew.row(
rootElement: .hStack([
.image32 { component in
component.setImage(urlString: viewItem.imageUrl, placeholder: UIImage(named: viewItem.placeholderImageName))
},
.vStackCentered([
.text { component in
component.font = .body
component.textColor = .themeLeah
component.text = viewItem.code
},
.margin(3),
.text { component in
component.font = .subhead2
component.textColor = .themeGray
component.text = viewItem.name
}
])
]),
tableView: tableView,
id: "coin_\(viewItem.uid)",
hash: "\(viewItem.favorite)",
height: .heightDoubleLineCell,
autoDeselect: true,
rowActionProvider: { [weak self] in self?.rowActions(index: index) ?? [] },
bind: { cell in
cell.set(backgroundStyle: .transparent, isLast: isLast)
},
action: { [weak self] in
self?.onSelect(viewItem: viewItem)
}
)
}
)
]
}
}
|
//
// Copyright © 2021 Tasuku Tozawa. All rights reserved.
//
import Domain
enum ClipPreviewPageViewCacheAction: Action {
// MARK: View Life-Cycle
case viewWillDisappear
case viewDidAppear
// MARK: Transition
case pageChanged(Clip.Identity, ClipItem.Identity)
}
|
//
// ExpensesListViewController.swift
// PleoCodeExercise
//
// Created by Lucas on 24/09/2019.
// Copyright © 2019 Lucas. All rights reserved.
//
import UIKit
import PleoCore
import ImageSlideshow
import Alamofire
class ExpensesListViewController: UIViewController {
var expenses : [ExpenseViewModel] = []
var filteredExpenses : [ExpenseViewModel] = []
var filterApplied = false
var limitReached = false
let pageSize : Int = 10
var ongoingRequest : Request?
@IBOutlet weak var tableView: UITableView!
// MARK: UIViewLifecycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadExpenses(offset: 0)
}
// MARK: Private Helpers
private func loadExpenses(offset: Int) {
if offset == 0 {
expenses = []
limitReached = false
}
ongoingRequest = APIManager.getExpenses(limit: pageSize, offset: offset) { (response) in
self.ongoingRequest = nil
switch response.result {
case let .success(expenseReport):
let expensesViewModels = expenseReport.expenses!.map{ExpenseViewModel(expense: $0)}
self.expenses += expensesViewModels
self.limitReached = self.expenses.count == expenseReport.total
self.showAllExpenses()
case let .failure(error):
print(error.localizedDescription)
}
}
}
// MARK: Button Actions
@IBAction func filtersButtonPressed(_ sender: Any) {
let alertView = UIAlertController(title: NSLocalizedString("filters", comment: ""), message: nil, preferredStyle: .actionSheet)
let receiptsWithImageAction = UIAlertAction(title: NSLocalizedString("show_expenses_with_image", comment: ""), style: .default) { (action) in
self.showExpensesWithImages()
}
let receiptsWithCommentAction = UIAlertAction(title: NSLocalizedString("show_expenses_with_comments", comment: ""), style: .default) { (action) in
self.showExpensesWithComments()
}
let allReceiptsAction = UIAlertAction(title: NSLocalizedString("show_all_expenses", comment: ""), style: .default) { (action) in
self.showAllExpenses()
}
alertView.addAction(receiptsWithImageAction)
alertView.addAction(receiptsWithCommentAction)
alertView.addAction(allReceiptsAction)
present(alertView, animated: true, completion: nil)
}
// MARK: - Filters methods -
private func showExpensesWithImages() {
filteredExpenses = expenses.filter { $0.hasReceipts }
filterApplied = true
tableView.reloadData()
}
private func showExpensesWithComments() {
filteredExpenses = expenses.filter { !$0.comment.isEmpty }
filterApplied = true
tableView.reloadData()
}
private func showAllExpenses() {
filteredExpenses = expenses
filterApplied = false
tableView.reloadData()
}
}
extension ExpensesListViewController : UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredExpenses.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: ExpenseTableViewCell.identifier) as? ExpenseTableViewCell else { return UITableViewCell() }
cell.setupWithExpense(filteredExpenses[indexPath.row])
cell.delegate = self
return cell
}
/**
* This is a very simple solution to implement infinite scrolling since the API response is quite fast. A better solution would be to add a mock cell at the end with an activity indicator, and when that cell appears we load the next page. We could also use tableView:willDisplay:forRowAt: method.
*
* Note: Since the filters are applied locally, we only request more pages if we're showing all the expenses, otherwise we might have unexpected results like getting expenses from the API and not displaying anything because they're filtered.
*/
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if !filterApplied {
let actualPosition = scrollView.contentOffset.y
let contentHeightTrigger = scrollView.contentSize.height - 100 - tableView.bounds.height
if actualPosition >= contentHeightTrigger && ongoingRequest == nil && !limitReached {
loadExpenses(offset: expenses.count)
}
}
}
}
extension ExpensesListViewController : ExpenseTableViewCellDelegate {
func didTapExpenseSlideshow(imageSlideshow: ImageSlideshow) {
guard let fullScreenVC = storyboard?.instantiateViewController(identifier: "FullScreenImagesViewController") as? FullScreenImagesViewController else { return }
fullScreenVC.images = imageSlideshow.images
present(fullScreenVC, animated: true, completion: nil)
}
func didTapExpenseEdit(expenseID: String) {
guard let editExpenseVC = storyboard?.instantiateViewController(identifier: "EditExpenseViewController") as? EditExpenseViewController else { return }
editExpenseVC.expenseId = expenseID
editExpenseVC.modalPresentationStyle = .fullScreen
present(editExpenseVC, animated: true, completion: nil)
}
}
|
//
// doWorkViewController.swift
// mcwa
//
// Created by XingfuQiu on 15/10/15.
// Copyright © 2015年 XingfuQiu. All rights reserved.
//
import UIKit
class doWorkViewController: UIViewController, PlayerDelegate {
var countDownTimer: NSTimer?
var countDownNum: Float = 100 //到计时时间 10秒
var currentQuestion: Int = 0 //当前做到的题目Idx
var questionId: Int!
var rightAnswer: String? //当前题目的正确答案
var rightBtn: UIButton?
var questionSource: Int? //当前题目的分数
var totalSource: Int = 0 //总得分
var questions: Array<JSON>? //题目数组
var answerStatus = Dictionary<Int, Int>() //用户答题的结果
let arrAnswer = ["answerOne":1, "answerTwo":2, "answerThree":3, "answerFour":4]
let manager = AFHTTPRequestOperationManager()
var sourceResult: Array<JSON>?
var json: JSON! {
didSet {
if "ok" == self.json["state"].stringValue {
print(self.json["dataObject"])
if let re = self.json["dataObject"].array {
print(re)
self.sourceResult = re
}
}
}
}
@IBOutlet weak var lb_addSource: UILabel!
@IBOutlet weak var lb_Source: UILabel!
@IBOutlet weak var iv_avatar: UIImageView!
@IBOutlet weak var lb_time: UILabel!
@IBOutlet weak var lb_contributionUser: UILabel!
@IBOutlet weak var lb_Ques_Title: UILabel!
@IBOutlet weak var v_Ques_Image: UIView!
@IBOutlet weak var iv_Ques_Image: UIImageView!
@IBOutlet weak var btn_Ques_One: UIButton!
@IBOutlet weak var btn_Ques_Two: UIButton!
@IBOutlet weak var btn_Ques_Three: UIButton!
@IBOutlet weak var btn_Ques_Four: UIButton!
@IBOutlet weak var co_Ques_One: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
lb_addSource.hidden = true
lb_Source.text = "0"
iv_avatar.layer.masksToBounds = true
iv_avatar.layer.cornerRadius = 18
iv_avatar.layer.borderColor = UIColor(hexString: "#493568")?.CGColor
iv_avatar.layer.borderWidth = 1.5
if appUserLogined {
iv_avatar.yy_setImageWithURL(NSURL(string: appUserAvatar!), placeholder: UIImage(named: "avatar_default"))
} else {
iv_avatar.image = UIImage(named: "avatar_default")
}
player_click.delegate = self
player_click.forever = false
self.navigationController?.navigationBarHidden = true
}
override func viewDidAppear(animated: Bool) {
self.refresh(currentQuestion)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//传消息到下一个界面
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showSource" {
let receive = segue.destinationViewController as! sourceViewController
receive.sourceResult = self.sourceResult
receive.totalSource = self.totalSource
}
}
//加载/刷新界面
func refresh(Idx: Int) {
if let singleQuestion = self.questions?[Idx] {
rightBtn = nil
rightAnswer = ""
v_Ques_Image.hidden = true
btn_Ques_One.hidden = false
btn_Ques_Two.hidden = false
btn_Ques_Three.hidden = false
btn_Ques_Four.hidden = false
btn_Ques_One.tag = 0
btn_Ques_Two.tag = 0
btn_Ques_Three.tag = 0
btn_Ques_Four.tag = 0
btn_Ques_One.backgroundColor = UIColor(hexString: "#676598")
btn_Ques_Two.backgroundColor = UIColor(hexString: "#676598")
btn_Ques_Three.backgroundColor = UIColor(hexString: "#676598")
btn_Ques_Four.backgroundColor = UIColor(hexString: "#676598")
let questionType = singleQuestion["questionType"].stringValue
rightAnswer = singleQuestion["rightAnswer"].stringValue
lb_Ques_Title.text = singleQuestion["title"].stringValue
// questionSource = singleQuestion["score"].intValue
questionId = singleQuestion["id"].intValue
//是否显示图片
if let icon = singleQuestion["icon"].string {
//有图
print("有图")
v_Ques_Image.hidden = false
self.co_Ques_One.constant = 10
iv_Ques_Image.yy_setImageWithURL(NSURL(string: icon), options: [.SetImageWithFadeAnimation, .ProgressiveBlur])
} else {
print("无图")
v_Ques_Image.hidden = true
self.co_Ques_One.constant = -v_Ques_Image.bounds.size.height
}
//题目类型
if questionType == "judge" {
//判断题目
btn_Ques_One.setTitle("对", forState: .Normal)
btn_Ques_Two.setTitle("错", forState: .Normal)
btn_Ques_Three.hidden = true
btn_Ques_Four.hidden = true
if rightAnswer == "对" {
btn_Ques_One.tag = 1
rightBtn = btn_Ques_One
} else {
btn_Ques_Two.tag = 1
rightBtn = btn_Ques_Two
}
} else {
//选择题目
for (name, btnidx) in arrAnswer {
let answer = singleQuestion[name].stringValue
switch btnidx {
case 1:
if answer == rightAnswer {
btn_Ques_One.tag = 1
rightBtn = btn_Ques_One
}
btn_Ques_One.setTitle(answer, forState: .Normal)
case 2:
if answer == rightAnswer {
btn_Ques_Two.tag = 1
rightBtn = btn_Ques_Two
}
btn_Ques_Two.setTitle(answer, forState: .Normal)
case 3:
if answer == rightAnswer {
btn_Ques_Three.tag = 1
rightBtn = btn_Ques_Three
}
btn_Ques_Three.setTitle(answer, forState: .Normal)
case 4:
if answer == rightAnswer {
btn_Ques_Four.tag = 1
rightBtn = btn_Ques_Four
}
btn_Ques_Four.setTitle(answer, forState: .Normal)
default:
print("加载答案失败")
}
}
}
self.lb_contributionUser.text = "贡献者:"+singleQuestion["authorName"].stringValue
//这里应该要等一下,有个加载过程
//开始倒计时
countDownNum = 100
//做题目倒计时
self.countDownTimer = NSTimer.new(every: 0.1.second, { () -> Void in
self.countDownNum--
if self.countDownNum <= 40 {
self.lb_time.textColor = UIColor.redColor()
} else {
self.lb_time.textColor = UIColor.whiteColor()
}
self.lb_time.text = "\(self.countDownNum / 10)"
//时间到了,没有选出答案,取下一到题目
if self.countDownNum == 0 {
self.countDownTimer?.invalidate()
//做题结果写入字典
self.answerStatus[self.questionId] = 0
NSTimer.after(1.5) {
self.currentQuestion++
print(self.currentQuestion)
if self.currentQuestion < self.questions?.count {
self.refresh(self.currentQuestion)
} else {
print("做完了,自动!")
print("做完,总计得分:\(self.totalSource)")
self.showSourcePage()
}
}
}
})
self.countDownTimer?.start()
}
}
//用户做的题目
@IBAction func chooseAnswer(sender: UIButton) {
//点了按钮,先停计时器
self.countDownTimer?.invalidate()
//设置按钮不能点击
btn_Ques_One.enabled = false
btn_Ques_Two.enabled = false
btn_Ques_Three.enabled = false
btn_Ques_Four.enabled = false
//判断对错,颜色区分
if (sender.tag == 1) {
player_click.playFileAtPath(right_click)
//回答正确,加分
self.answerStatus[self.questionId] = 1
sender.backgroundColor = UIColor(hexString: "#5BB524")
let str = lb_time.text!
//剩余时间四舍五入
questionSource = lroundf(Float(str)!)
print("questionSource:\(questionSource)")
self.totalSource = self.totalSource + self.questionSource!
self.lb_Source.text = "\(self.totalSource)"
self.lb_addSource.text = "+\(self.questionSource!)"
self.lb_addSource.hidden = false
} else {
player_click.playFileAtPath(error_click)
self.answerStatus[self.questionId] = 0
//回答错误,不加分
sender.backgroundColor = UIColor.redColor()
//显示正确答案
rightBtn?.backgroundColor = UIColor(hexString: "#5BB524")
}
//刷新题目,准备下一题
NSTimer.after(2) { () -> Void in
//设置按钮不能点击
self.btn_Ques_One.enabled = true
self.btn_Ques_Two.enabled = true
self.btn_Ques_Three.enabled = true
self.btn_Ques_Four.enabled = true
self.currentQuestion++
print(self.currentQuestion)
if self.currentQuestion < self.questions?.count {
self.lb_addSource.hidden = true
self.refresh(self.currentQuestion)
} else {
print("做完啦,手动")
print("做完,总计得分:\(self.totalSource)")
self.showSourcePage()
}
}
}
//显示用户做题的结果页
func showSourcePage() {
self.pleaseWait()
//act=report&userId=1&allScore=200&correct=4,5,6,7,8&error=1,2,3
var correct: String = ""
var error: String = ""
print(answerStatus)
for (qid, answer) in answerStatus {
if answer != 0 {
correct = String(qid)+","+correct
} else {
error = String(qid)+","+error
}
}
print("correct:\(correct)")
print("error:\(error)")
let dict = [
"act":"report",
"userId": appUserIdSave,
"allScore": totalSource,
"correct": correct,
"error": error ]
manager.GET(URL_MC,
// manager.GET("http://192.168.10.104/interface.do?",
parameters: dict,
success: {
(operation, responseObject) -> Void in
print(responseObject)
self.json = JSON(responseObject)
self.clearAllNotice()
//收到数据,跳转到准备页面
self.performSegueWithIdentifier("showSource", sender: self)
}) { (operation, error) -> Void in
self.clearAllNotice()
self.noticeError("提交出错", autoClear: true, autoClearTime: 3)
print(error)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
func soundFinished(sender: AnyObject) {
print("play finished!")
}
override func viewWillAppear(animated: Bool) {
MobClick.beginLogPageView("doWorkViewController")
}
override func viewWillDisappear(animated: Bool) {
MobClick.endLogPageView("doWorkViewController")
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
}
|
//
// Formatters.swift
// TastingNotes
//
// Created by David Burke on 8/6/17.
// Copyright © 2017 amberfire. All rights reserved.
//
import Foundation
class Formatters {
let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
return dateFormatter
} ()
let currencyFormatter: NumberFormatter = {
let currencyFormatter = NumberFormatter ()
currencyFormatter.numberStyle = .currency
currencyFormatter.locale = Locale(identifier: "en-us")
return currencyFormatter
} ()
let backToNumberFormatter: NumberFormatter = {
let backToNumberFormatter = NumberFormatter ()
backToNumberFormatter.generatesDecimalNumbers = true
backToNumberFormatter.numberStyle = NumberFormatter.Style.currency
return backToNumberFormatter
}()
}
|
//
// GameScene.swift
// Flappy Gator
//
// Created by Peter Lin on 4/7/18.
// Copyright © 2018 690FinalProject. All rights reserved.
//
import SpriteKit
import GameplayKit
class GameScene: SKScene , SKPhysicsContactDelegate{
var isGameStarted = Bool(false)
var isDied = Bool(false)
var score = Int(0)
var scoreLabel = SKLabelNode()
var highscoreLabel = SKLabelNode()
var tapToPlayLabel = SKSpriteNode()
var restartButton = SKSpriteNode()
var pauseButton = SKSpriteNode()
var logoImage = SKSpriteNode()
var pipePair = SKNode()
var moveAndRemove = SKAction()
//Create the gator atlas for animation
let gatorAtlas = SKTextureAtlas(named:"player")
var gatorSprites = Array<Any>()
var gator = SKSpriteNode()
var repeatActionGator = SKAction()
override func didMove(to view: SKView){
createScene()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if isGameStarted == false {
isGameStarted = true
gator.physicsBody?.affectedByGravity = true
//remove logo and play button when the game starts
logoImage.run(SKAction.scale(to: 0.5, duration: 0.3), completion: {
self.logoImage.removeFromParent()
})
tapToPlayLabel.removeFromParent()
self.gator.run(repeatActionGator)
//create pipes
let spawn = SKAction.run({
() in
self.pipePair = self.createPipes()
self.addChild(self.pipePair)
})
//delay when the pipes start appearing
let delay = SKAction.wait(forDuration: 1.5)
let spawnDelay = SKAction.sequence([spawn, delay])
let spawnDelayForever = SKAction.repeatForever(spawnDelay)
self.run(spawnDelayForever)
//distance between pipes and how fast they go
let distance = CGFloat(self.frame.width + pipePair.frame.width)
let movePipes = SKAction.moveBy(x: -distance - 50, y: 0, duration: TimeInterval(0.008 * distance))
let removePipes = SKAction.removeFromParent()
moveAndRemove = SKAction.sequence([movePipes, removePipes])
gator.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
gator.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 75))
}
else{
if isDied == false {
gator.physicsBody?.velocity = CGVector(dx: 0, dy: 0)
gator.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 75))
}
}
for touch in touches{
let location = touch.location(in: self)
if isDied == true{
if restartButton.contains(location){
if UserDefaults.standard.object(forKey: "highestScore") != nil {
let hscore = UserDefaults.standard.integer(forKey: "highestScore")
if hscore < Int(scoreLabel.text!)!{
UserDefaults.standard.set(scoreLabel.text, forKey: "highestScore")
}
}
else {
UserDefaults.standard.set(0, forKey: "highestScore")
}
restartScene()
}
}
}
}
override func update(_ currentTime: TimeInterval){
//called before each frame is rendered
if isGameStarted == true{
if isDied == false{
enumerateChildNodes(withName: "background", using: ({
(node, error) in
let background = node as! SKSpriteNode
background.position = CGPoint(x: background.position.x - 2, y: background.position.y)
if background.position.x <= -background.size.width {
background.position = CGPoint(x:background.position.x + background.size.width * 2, y:background.position.y)
}
}))
}
}
}
func createScene(){
self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame) //create a physics body around entire scene
self.physicsBody?.categoryBitMask = CollisionBitMask.groundCategory //defines which categories this physics body belongs to
self.physicsBody?.collisionBitMask = CollisionBitMask.gatorCategory //defines which categories of physics can collide with this physics body
self.physicsBody?.contactTestBitMask = CollisionBitMask.gatorCategory //defines which categories of bodies cause intersection notifications with this physics body
self.physicsBody?.isDynamic = false
self.physicsBody?.affectedByGravity = false //prevents player from falling off the scene
self.physicsWorld.contactDelegate = self
//self.backgroundColor = SKColor(red: 80.0/225, green: 192.0/225, blue: 203.0/225)
for i in 0..<2{
let background = SKSpriteNode(imageNamed: "background")
background.anchorPoint = CGPoint.init(x: 0, y: 0)
background.position = CGPoint(x:CGFloat(i) * self.frame.width, y: 0)
background.name = "background"
background.size = (self.view?.bounds.size)!
self.addChild(background)
}
gatorSprites.append(gatorAtlas.textureNamed("gator")) //add sprites to the gator atlas
//initialize everything
self.gator = createGator()
self.addChild(gator)
scoreLabel = createScoreLabel()
self.addChild(scoreLabel)
highscoreLabel = createHighScoreLabel()
self.addChild(highscoreLabel)
createLogo()
createTapToPlayLabel()
}
//when game begins, detect collisions
func didBegin(_ contact: SKPhysicsContact) {
let firstBody = contact.bodyA
let secondBody = contact.bodyB
//if the gator hits the ground or pipe he dies
if firstBody.categoryBitMask == CollisionBitMask.gatorCategory &&
secondBody.categoryBitMask == CollisionBitMask.pipeCategory ||
firstBody.categoryBitMask == CollisionBitMask.pipeCategory &&
secondBody.categoryBitMask == CollisionBitMask.gatorCategory ||
firstBody.categoryBitMask == CollisionBitMask.gatorCategory &&
secondBody.categoryBitMask == CollisionBitMask.groundCategory ||
firstBody.categoryBitMask == CollisionBitMask.groundCategory &&
secondBody.categoryBitMask == CollisionBitMask.gatorCategory {
enumerateChildNodes(withName: "pipePair", using: ({(node, error) in
node.speed = 0
self.removeAllActions()
}))
//when he dies remove all action and show restart button
if isDied == false{
isDied = true
createRestartButton()
self.gator.removeAllActions()
}
}
//maybe a way to add score?
}
//restart the game and set everything to default
func restartScene(){
self.removeAllChildren()
self.removeAllActions()
isDied = false
isGameStarted = false
score = 0
createScene()
}
}
|
//
// ViewController.swift
// Favloc
//
// Created by Kordian Ledzion on 03/01/2018.
// Copyright © 2018 KordianLedzion. All rights reserved.
//
import UIKit
class MainCollectionViewController: UIViewController {
weak var coordinator: MainCoordinator?
private lazy var defaultBottomInset: CGFloat = {
return layoutContextValue(base: CGFloat(17.0),
contextMapping: [.iPhone5_5: CGFloat(8.0 * 17.0),
.iPhone4_7: CGFloat(6.0 * 17.0),
.iPhone4_0: CGFloat(4.0 * 17.0),
.iPhone3_5: CGFloat(2.0 * 17.0)])
}()
private let deleteButton = UIBarButtonItem()
private let addButton = UIButton()
private let collectionView: UICollectionView
private let cellIdentifier = "collectionViewCell"
private let defaultInset: CGFloat = 17.0
private var longPressGesture: UILongPressGestureRecognizer!
private let viewModel: DataSource
private var deleting = false
init(viewModel: DataSource) {
let collectionLayout = UICollectionViewFlowLayout()
collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionLayout)
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
setUpCollectionView(with: collectionLayout)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setUpNavBar()
setUpAddButton()
setUpGestureRecognizers()
layoutSubviews()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
private func setUpNavBar() {
navigationItem.title = "FAVLOC"
deleteButton.style = .plain
deleteButton.title = "Select"
deleteButton.action = #selector(deletionProcess)
deleteButton.target = self
navigationItem.leftBarButtonItem = deleteButton
}
private func setUpAddButton() {
addButton.setImage(#imageLiteral(resourceName: "addButton"), for: .normal)
addButton.addTarget(self, action: #selector(addNewPlace), for: .touchUpInside)
}
@objc private func addNewPlace() {
viewModel.add {
DispatchQueue.main.async { [unowned self] in
self.collectionView.reloadData()
self.scrollToBottom()
}
}
}
@objc private func deletionProcess() {
if deleting {
if let selectedItems = collectionView.indexPathsForSelectedItems {
view.isUserInteractionEnabled = false
for index in selectedItems {
self.collectionView.deselectItem(at: index, animated: true)
}
viewModel.delete(itemsAt: selectedItems) {
DispatchQueue.main.async { [unowned self] in
self.collectionView.reloadData()
self.view.isUserInteractionEnabled = true
}
}
}
}
deleteButton.style = deleting ? .plain : .done
deleteButton.title = deleting ? "Select" : "Delete"
addButton.isEnabled = deleting
deleting = !deleting
collectionView.allowsMultipleSelection = deleting
}
private func setUpGestureRecognizers() {
longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongGesture(gesture:)))
self.collectionView.addGestureRecognizer(longPressGesture)
}
@objc private func handleLongGesture(gesture: UILongPressGestureRecognizer) {
switch(gesture.state) {
case UIGestureRecognizerState.began:
guard let selectedIndexPath = self.collectionView.indexPathForItem(at: gesture.location(in: self.collectionView)) else {
break
}
collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
case UIGestureRecognizerState.changed:
collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
case UIGestureRecognizerState.ended:
collectionView.endInteractiveMovement()
default:
collectionView.cancelInteractiveMovement()
}
}
private func layoutSubviews() {
collectionView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor),
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
collectionView.topAnchor.constraint(equalTo: topLayoutGuide.topAnchor)
])
addButton.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(addButton)
NSLayoutConstraint.activate([
addButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
addButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -24.0)
])
}
private func setUpCollectionView(with layout: UICollectionViewFlowLayout) {
layout.itemSize = layoutContextValue(base: CGSize(width: 160, height: 210),
contextMapping: [.iPhone4_0: CGSize(width: 270, height: 210),
.iPhone3_5: CGSize(width: 215, height: 210)])
layout.minimumLineSpacing = defaultInset
layout.minimumInteritemSpacing = defaultInset
collectionView.backgroundColor = .paleGrey
collectionView.register(MainCollectionViewControllerCell.self, forCellWithReuseIdentifier: cellIdentifier)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.isPrefetchingEnabled = true
}
private func scrollToBottom() {
let lastSectionIndex = collectionView.numberOfSections - 1
let lastItemIndex = collectionView.numberOfItems(inSection: lastSectionIndex) - 1
let indexPath = NSIndexPath(item: lastItemIndex, section: lastSectionIndex)
collectionView.scrollToItem(at: indexPath as IndexPath, at: UICollectionViewScrollPosition.bottom, animated: true)
}
}
extension MainCollectionViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if !deleting {
let selectResult = viewModel.select(itemAt: indexPath.row)
switch selectResult {
case .success(let place):
coordinator?.presentDetails(for: place) {
DispatchQueue.main.async { [unowned self] in
self.collectionView.deselectItem(at: indexPath, animated: true)
self.collectionView.reloadData()
}
}
case .failure:
break
}
} else {
let cell = collectionView.cellForItem(at: indexPath) as! MainCollectionViewControllerCell
cell.toggleBorder()
}
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! MainCollectionViewControllerCell
cell.toggleBorder()
}
}
extension MainCollectionViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier,
for: indexPath) as! MainCollectionViewControllerCell
let selectResult = viewModel.select(itemAt: indexPath.row)
switch selectResult {
case .success(let place):
cell.setUp(with: place)
case .failure:
break
}
return cell
}
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
viewModel.insert(itemAt: sourceIndexPath.row, into: destinationIndexPath.row)
}
}
extension MainCollectionViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: defaultInset, left: defaultInset, bottom: defaultBottomInset, right: defaultInset)
}
}
|
//
// GlanceController.swift
// AirRecipe WatchKit Extension
//
// Created by Fuji on 2015/05/27.
// Copyright (c) 2015年 FromF. All rights reserved.
//
import WatchKit
import Foundation
class GlanceController: WKInterfaceController {
//Keys
let CatalogSlectImageName:String = "SlectImageName"
//UI
@IBOutlet weak var imageView: WKInterfaceImage!
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
WKInterfaceController.openParentApplication(["getinfo": ""],
reply: {replyInfo, error in
//self.propertyDictionary.removeAll(keepCapacity: false)
var relyInfokeys = Array(replyInfo.keys)
for relyInfokey in relyInfokeys {
if relyInfokey == self.CatalogSlectImageName {
let imagename:String = replyInfo["\(relyInfokey)"] as! String + "_Watch.jpg"
self.imageView.setImage(UIImage(named: imagename))
}
}
})
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
|
//
// Listing.swift
// Helios
//
// Created by Lars Stegman on 30-12-16.
// Copyright © 2016 Stegman. All rights reserved.
//
import Foundation
public struct Listing: Kindable, Decodable {
let before: String?
let after: String?
let modhash: String?
var source: URL?
public let children: [KindWrapper]
public static let kind = Kind.listing
init(before: String?, after: String?, modhash: String?, source: URL?, children: [KindWrapper]) {
self.before = before
self.after = after
self.modhash = modhash
self.source = source
self.children = children
}
/// Whether there are pages before this one.
public var hasPrevious: Bool {
return before != nil
}
/// Whether there are more pages.
public var hasNext: Bool {
return after != nil
}
public init(from decoder: Decoder) throws {
let dataContainer = try decoder.container(keyedBy: CodingKeys.self)
source = try dataContainer.decodeIfPresent(URL.self, forKey: .source)
after = try dataContainer.decodeIfPresent(String.self, forKey: .after)
before = try dataContainer.decodeIfPresent(String.self, forKey: .before)
modhash = try dataContainer.decodeIfPresent(String.self, forKey: .modhash)
children = try dataContainer.decode([KindWrapper].self, forKey: .children)
}
enum CodingKeys: String, CodingKey {
case before
case after
case children
case modhash
case source
}
}
|
//
// ViewController.swift
// Tipsy
//
// Created by Angela Yu on 09/09/2019.
// Copyright © 2019 The App Brewery. All rights reserved.
//
import UIKit
class CalculatorViewController: UIViewController {
@IBOutlet weak var billTextField: UITextField!
@IBOutlet weak var zeroPctButton: UIButton!
@IBOutlet weak var tenPctButton: UIButton!
@IBOutlet weak var twentyPctButton: UIButton!
@IBOutlet weak var splitNumberLable: UILabel!
var tip = "0.0"
var people = "0.0"
var valueBillTextField: Float = 0.0
var resultLast = "0.0"
override func viewDidLoad() {
people = splitNumberLable.text!
tip = "0.1"
tenPctButton.isSelected = true
zeroPctButton.isSelected = false
twentyPctButton.isSelected = false
}
@IBAction func tipChanged(_ sender: UIButton) {
billTextField.endEditing(true)
let userPressed = sender.currentTitle!
if userPressed == "0%" {
tip = "0"
zeroPctButton.isSelected = true
tenPctButton.isSelected = false
twentyPctButton.isSelected = false
} else if userPressed == "10%" {
tip = "0.1"
zeroPctButton.isSelected = false
tenPctButton.isSelected = true
twentyPctButton.isSelected = false
} else {
tip = "0.2"
zeroPctButton.isSelected = false
tenPctButton.isSelected = false
twentyPctButton.isSelected = true
}
}
@IBAction func stepperValueChanged(_ sender: UIStepper) {
splitNumberLable.text = "\(Int(sender.value))"
people = splitNumberLable.text!
}
@IBAction func calculatePressed(_ sender: UIButton) {
valueBillTextField = Float(billTextField.text!) ?? 0.0
let tipmoney = valueBillTextField * Float(tip)!
let result = (valueBillTextField + tipmoney) / Float(people)!
resultLast = String(format: "%.2f", result)
self.performSegue(withIdentifier: "goToResult", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToResult" {
let destinationVC = segue.destination as! ResultsViewController
destinationVC.result = resultLast
destinationVC.people = people
destinationVC.tip = tip
}
}
}
|
//
// Move.swift
// TikiTacToe
//
// Created by Pro on 15.02.2021.
//
import GameplayKit
@objc(Move)
class Step: NSObject, GKGameModelUpdate {
var value: Int = 0
var cell: Int
init(cell: Int) {
self.cell = cell
super.init()
}
}
|
import Foundation
protocol CategoryRepository {
func getCategories(success: @escaping Success<[Category]>, failure: @escaping Failure)
}
|
//
// Shopping.swift
// SpecialTraining
//
// Created by 尹涛 on 2018/11/17.
// Copyright © 2018 youpeixun. All rights reserved.
//
import UIKit
class ShopingNameModel: HJModel, ShopingModelAdapt {
var height: CGFloat {
get {
return 50.0
}
}
var isShopping: Bool {
get {
return false
}
}
}
class ShoppingListModel: HJModel, ShopingModelAdapt {
var isLastRow: Bool = false
convenience init(isLastRow: Bool) {
self.init()
self.isLastRow = isLastRow
}
var height: CGFloat {
get {
return 110.0
}
}
var isShopping: Bool {
get {
return true
}
}
}
protocol ShopingModelAdapt {
var height: CGFloat { get }
var isShopping: Bool { get }
}
|
//
// ViewController.swift
// FetchRewardsCookbook
//
// Created by Wesley Luntsford on 11/9/21.
//
import UIKit
class RecipeBrowserViewController: UITableViewController {
@IBOutlet weak var mealLabel: UILabel!
var recipeFetcher: RecipeFetcher?
// Optional meal tapped by the user.
var selectedMeal: Meal?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Fetch Rewards' Recipes"
navigationItem.hidesBackButton = true
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == K.SegueID.showMeal {
let mealVC = segue.destination as! RecipeViewController
mealVC.meal = selectedMeal
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return recipeFetcher!.categories[section]
}
override func numberOfSections(in tableView: UITableView) -> Int {
return recipeFetcher!.categories.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return recipeFetcher!.allMeals[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return createMealCell(for: tableView, at: indexPath)
}
func createMealCell(for tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: K.CellID.mealCell, for: indexPath)
let label = cell.textLabel!
label.text = recipeFetcher!.allMeals[indexPath.section][indexPath.row].name
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedMeal = recipeFetcher!.allMeals[indexPath.section][indexPath.row]
// Waits to fetch meal details from database until the meal is tapped.
recipeFetcher!.setupMealDetails(for: selectedMeal!)
self.performSegue(withIdentifier: K.SegueID.showMeal, sender: self)
}
}
|
//
// GZEUserAnnotation.swift
// Gooze
//
// Created by Yussel Paredes Perez on 5/3/18.
// Copyright © 2018 Gooze. All rights reserved.
//
import UIKit
import MapKit
import ReactiveSwift
class GZEUserAnnotation: NSObject, MKAnnotation {
dynamic var coordinate = CLLocationCoordinate2D()
var user: GZEChatUser?
override init() {
super.init()
}
}
|
//
// GroupTabBarBuilder.swift
// Quota
//
// Created by Marcin Włoczko on 24/11/2018.
// Copyright © 2018 Marcin Włoczko. All rights reserved.
//
import UIKit
protocol GroupTabBarBuilder: class {
func buildGroupTabBarController() -> GroupTabBarController
func buildExpensesFlow(with group: Group) -> ExpensesCoordinator
func buildMembersFlow(with group: Group) -> MembersCoordinator
func buildAddExpenseFlow(with group: Group) -> AddExpenseCoordinator
}
final class GroupTabBarBuilderImp: GroupTabBarBuilder {
func buildGroupTabBarController() -> GroupTabBarController {
let tabBarController = GroupTabBarController()
tabBarController.viewModel = GroupTabBarViewModelImp()
return tabBarController
}
func buildExpensesFlow(with group: Group) -> ExpensesCoordinator {
let builder = ExpensesBuilderImp()
let coordinator = ExpensesCoordinator(group: group, builder: builder)
return coordinator
}
func buildMembersFlow(with group: Group) -> MembersCoordinator {
let builder = MembersBuilderImp()
let coordinator = MembersCoordinator(group: group, builder: builder)
return coordinator
}
func buildAddExpenseFlow(with group: Group) -> AddExpenseCoordinator {
let builder = AddExpenseBuilderImp()
let coordiantor = AddExpenseCoordinator(builder: builder, group: group)
return coordiantor
}
}
|
typealias Modifier = (String)->String
func uppercase() -> Modifier {
return { string in
return string.uppercased()
}
}
func removeLast() -> Modifier {
return { string in
return String(string.characters.dropLast())
}
}
func addSuffix(suffix: String) -> Modifier {
return { string in
return string + suffix
}
}
func compose(_ left: @escaping Modifier, _ right: @escaping Modifier) -> Modifier {
return { string in
left(right(string))
}
}
for i in 0...1000000000 {
let a = compose(compose(uppercase(), removeLast()), addSuffix(suffix: "Abc"))("IntitialValue")
}
|
//
// File.swift
//
//
// Created by Mason Phillips on 6/14/20.
//
import Foundation
import RxSwift
struct PeopleCombinedCreditsEndpoint: APIRequest {
typealias Response = PeopleCombinedCreditsModel
var endpoint: String { "/person/\(id)/combined_credits" }
var parameters: Dictionary<String, String> {
if let language = language {
return ["language": language]
} else {
return [:]
}
}
let id: Int
let language: String?
}
public extension API {
func peopleCombinedCredits(_ id: Int, language: String? = nil) -> Single<PeopleCombinedCreditsModel> {
return _fetch(PeopleCombinedCreditsEndpoint(id: id, language: language))
}
}
|
//
// HorizonRequests.swift
// StellarKitTests
//
// Created by Kin Foundation.
// Copyright © 2018 Kin Foundation. All rights reserved.
//
import XCTest
@testable import StellarKit
class HorizonRequestsTests: XCTestCase {
let account = "GBDYQPNVH7DGKD6ZNBTZY5BZNO2GRHAY7KO3U33UZRBXJDVLBF2PCF6M"
let txId1 = "79f0cdf85b407b6dd4f342a37a18c6617880192cbeb0c67b5a449bc50df9d52c"
let txId2 = "aea5d5ef484e729836f28fd090e3600b5e83f0344e8dc053015cd52dfb3a7c45"
let base = URL(string: "http://localhost:8000")!
func test_accounts_request() {
let e = expectation(description: "")
Endpoint.account(account).get(from: base)
.then({
XCTAssert($0.id == self.account)
})
.error { print($0); XCTFail() }
.finally { e.fulfill() }
wait(for: [e], timeout: 3)
}
func test_accounts_transactions_request() {
let e = expectation(description: "")
Endpoint.account(account).transactions().get(from: base)
.then({ (response: Responses.Transactions) in
XCTAssert(response.transactions.filter { $0.id == self.txId1 }.count == 1)
})
.error { print($0); XCTFail() }
.finally { e.fulfill() }
wait(for: [e], timeout: 3)
}
func test_simultaneous_requests() {
let e1 = expectation(description: "")
let e2 = expectation(description: "")
let requestor = Horizon()
requestor.get(url: Endpoint.transaction(txId1).url(with: base))
.then({ (response: Responses.Transaction) in
XCTAssert(response.id == self.txId1)
})
.error { print($0); XCTFail() }
.finally { e1.fulfill() }
requestor.get(url: Endpoint.account(account).transactions().url(with: base))
.then({ (response: Responses.Transactions) in
XCTAssert(response.transactions.filter { $0.id == self.txId2 }.count == 1)
})
.error { print($0); XCTFail() }
.finally { e2.fulfill() }
wait(for: [e1, e2], timeout: 3)
}
}
|
//
// CheckEmailViewController.swift
// PasswordBook
//
// Created by LiangMinglong on 19/08/2016.
// Copyright © 2016 LiangMinglong. All rights reserved.
//
import UIKit
class CheckEmailViewController: UIViewController {
@IBAction func BackToLogin(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
|
//
// CityTemp.swift
// WeatherMap
//
// Copyright © 2018 ncarmine. All rights reserved.
//
import Foundation
import MapKit
// Annotation class for a city's current temperature
class CityTemp: NSObject, MKAnnotation {
var title: String? // title of annotation - current temp
var coordinate: CLLocationCoordinate2D // lat, long of annotation
// Initialize class with given values
init(title: String, coordinate: CLLocationCoordinate2D) {
self.title = title
self.coordinate = coordinate
super.init()
}
}
|
//
// Collection.swift
// CouchbaseLite
//
// Copyright (c) 2022 Couchbase, Inc 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
/// A `Collection` represent a collection which is a container for documents.
///
/// A collection can be thought as a table in the relational database. Each collection belongs to
/// a scope which is simply a namespce, and has a name which is unique within its scope.
///
/// When a new database is created, a default collection named `_default` will be automatically
/// created. The default collection is created under the default scope named `_default`.
/// The name of the default collection and scope can be referenced by using
/// `Collection.defaultCollectionName` and `Scope.defaultScopeName` constant.
///
/// - Note: The default collection cannot be deleted.
///
/// When creating a new collection, the collection name, and the scope name are required.
/// The naming rules of the collections and scopes are as follows:
/// - Must be between 1 and 251 characters in length.
/// - Can only contain the characters A-Z, a-z, 0-9, and the symbols _, -, and %.
/// - Cannot start with _ or %.
/// - Both scope and collection names are case sensitive.
///
/// ## CBLCollection Lifespan
/// A `Collection` object and its reference remain valid until either
/// the database is closed or the collection itself is deleted, in that case it will
/// throw an NSError with the CBLError.notOpen code while accessing the collection APIs.
///
/// ## Legacy Database and API
/// When using the legacy database, the existing documents and indexes in the database will be
/// automatically migrated to the default collection.
///
/// Any pre-existing database functions that refer to documents, listeners, and indexes without
/// specifying a collection such as `database.document(id:)` will implicitly operate on
/// the default collection. In other words, they behave exactly the way they used to, but
/// collection-aware code should avoid them and use the new Collection API instead.
/// These legacy functions are deprecated and will be removed eventually.
///
public final class Collection : CollectionChangeObservable, Indexable, Equatable, Hashable {
/// The default scope name constant
public static let defaultCollectionName: String = kCBLDefaultCollectionName
/// Collection name.
public var name: String { impl.name }
/// The scope of the collection.
public let scope: Scope
// MARK: Document Management
/// Total number of documents in the collection.
public var count: UInt64 { impl.count }
/// Get an existing document by document ID.
///
/// Throws an NSError with the CBLError.notOpen code, if the collection is deleted or
/// the database is closed.
public func document(id: String) throws -> Document? {
var error: NSError?
let doc = impl.document(withID: id, error: &error)
if let err = error {
throw err
}
if let implDoc = doc {
return Document(implDoc, collection: self)
}
return nil
}
/// Gets document fragment object by the given document ID.
public subscript(key: String) -> DocumentFragment {
return DocumentFragment(impl[key], collection: self)
}
/// Save a document into the collection. The default concurrency control, lastWriteWins,
/// will be used when there is conflict during save.
///
/// When saving a document that already belongs to a collection, the collection instance of
/// the document and this collection instance must be the same, otherwise, the InvalidParameter
/// error will be thrown.
///
/// Throws an NSError with the CBLError.notOpen code, if the collection is deleted or
/// the database is closed.
public func save(document: MutableDocument) throws {
try impl.save(document.impl as! CBLMutableDocument)
}
/// Save a document into the collection with a specified concurrency control. When specifying
/// the failOnConflict concurrency control, and conflict occurred, the save operation will fail with
/// 'false' value returned.
///
/// When saving a document that already belongs to a collection, the collection instance of the
/// document and this collection instance must be the same, otherwise, the InvalidParameter
/// error will be thrown.
///
/// Throws an NSError with the CBLError.notOpen code, if the collection is deleted or
/// the database is closed.
public func save(document: MutableDocument, concurrencyControl: ConcurrencyControl) throws -> Bool {
var error: NSError?
let cc = concurrencyControl == .lastWriteWins ?
CBLConcurrencyControl.lastWriteWins : CBLConcurrencyControl.failOnConflict
let result = impl.save(document.impl as! CBLMutableDocument, concurrencyControl: cc, error: &error)
if let err = error {
if err.code == CBLErrorConflict {
return false
}
throw err
}
return result
}
/// Save a document into the collection with a specified conflict handler. The specified conflict handler
/// will be called if there is conflict during save. If the conflict handler returns 'false', the save operation
/// will be canceled with 'false' value returned.
///
/// When saving a document that already belongs to a collection, the collection instance of the
/// document and this collection instance must be the same, otherwise, the InvalidParameter error
/// will be thrown.
///
/// Throws an NSError with the CBLError.notOpen code, if the collection is deleted or
/// the database is closed.
public func save(document: MutableDocument,
conflictHandler: @escaping (MutableDocument, Document?) -> Bool) throws -> Bool {
var error: NSError?
let result = impl.save(
document.impl as! CBLMutableDocument,
conflictHandler: { (cur: CBLMutableDocument, old: CBLDocument?) -> Bool in
return conflictHandler(document, old != nil ? Document(old!, collection: self) : nil)
}, error: &error)
if let err = error {
if err.code == CBLErrorConflict {
return false
}
throw err
}
return result
}
/// Delete a document from the collection. The default concurrency control, lastWriteWins, will be used
/// when there is conflict during delete. If the document doesn't exist in the collection, the NotFound
/// error will be thrown.
///
/// When deleting a document that already belongs to a collection, the collection instance of
/// the document and this collection instance must be the same, otherwise, the InvalidParameter error
/// will be thrown.
///
/// Throws an NSError with the CBLError.notOpen code, if the collection is deleted or
/// the database is closed.
public func delete(document: Document) throws {
try impl.delete(document.impl)
}
/// Delete a document from the collection with a specified concurrency control. When specifying
/// the failOnConflict concurrency control, and conflict occurred, the delete operation will fail with
/// 'false' value returned.
///
/// When deleting a document, the collection instance of the document and this collection instance
/// must be the same, otherwise, the InvalidParameter error will be thrown.
///
/// Throws an NSError with the CBLError.notOpen code, if the collection is deleted or
/// the database is closed.
public func delete(document: Document, concurrencyControl: ConcurrencyControl) throws -> Bool {
let cc = concurrencyControl == .lastWriteWins ?
CBLConcurrencyControl.lastWriteWins : CBLConcurrencyControl.failOnConflict
var error: NSError?
let result = impl.delete(document.impl, concurrencyControl: cc, error: &error)
if let err = error {
if err.code == CBLErrorConflict {
return false
}
throw err
}
return result
}
/// When purging a document, the collection instance of the document and this collection instance
/// must be the same, otherwise, the InvalidParameter error will be thrown.
///
/// Throws an NSError with the CBLError.notOpen code, if the collection is deleted or
/// the database is closed.
public func purge(document: Document) throws {
try impl.purgeDocument(document.impl)
}
/// Purge a document by id from the collection. If the document doesn't exist in the collection,
/// the NotFound error will be thrown.
///
/// Throws an NSError with the CBLError.notOpen code, if the collection is deleted or
/// the database is closed.
public func purge(id: String) throws {
try impl.purgeDocument(withID: id)
}
// MARK: Document Expiry
/// Set an expiration date to the document of the given id. Setting a nil date will clear the expiration.
///
/// Throws an NSError with the CBLError.notOpen code, if the collection is deleted or
/// the database is closed.
public func setDocumentExpiration(id: String, expiration: Date?) throws {
try impl.setDocumentExpirationWithID(id, expiration: expiration)
}
/// Get the expiration date set to the document of the given id.
///
/// Throws an NSError with the CBLError.notOpen code, if the collection is deleted or
/// the database is closed.
public func getDocumentExpiration(id: String) throws -> Date? {
var error: NSError?
let date = impl.getDocumentExpiration(withID: id, error: &error)
if let err = error {
throw err
}
return date
}
// MARK: Document Change Publisher
/// Add a change listener to listen to change events occurring to a document of the given document id.
/// To remove the listener, call remove() function on the returned listener token.
///
/// If the collection is deleted or the database is closed, a warning message will be logged.
@discardableResult public func addDocumentChangeListener(id: String,
listener: @escaping (DocumentChange) -> Void) -> ListenerToken {
return self.addDocumentChangeListener(id: id, queue: nil, listener: listener)
}
/// Add a change listener to listen to change events occurring to a document of the given document id.
/// If a dispatch queue is given, the events will be posted on the dispatch queue. To remove the listener,
/// call remove() function on the returned listener token.
///
/// If the collection is deleted or the database is closed, a warning message will be logged.
@discardableResult public func addDocumentChangeListener(id: String, queue: DispatchQueue?,
listener: @escaping (DocumentChange) -> Void) -> ListenerToken {
let token = impl.addDocumentChangeListener(withID: id, queue: queue)
{ [weak self] (change) in
guard let self = self else {
Log.log(domain: .database, level: .warning, message: "Unable to notify changes as the collection object was released")
return
}
listener(DocumentChange(database: self.db,
documentID: change.documentID,
collection: self))
}
return ListenerToken(token)
}
/// Add a change listener to listen to change events occurring to any documents in the collection.
/// To remove the listener, call remove() function on the returned listener token
///.
/// If the collection is deleted or the database is closed, a warning message will be logged.
@discardableResult public func addChangeListener(listener: @escaping (CollectionChange) -> Void) -> ListenerToken {
return self.addChangeListener(queue: nil, listener: listener)
}
/// Add a change listener to listen to change events occurring to any documents in the collection.
/// If a dispatch queue is given, the events will be posted on the dispatch queue.
/// To remove the listener, call remove() function on the returned listener token.
///
/// If the collection is deleted or the database is closed, a warning message will be logged.
@discardableResult public func addChangeListener(queue: DispatchQueue?,
listener: @escaping (CollectionChange) -> Void) -> ListenerToken {
let token = impl.addChangeListener(with: queue) { [unowned self] (change) in
listener(CollectionChange(collection: self, documentIDs: change.documentIDs))
}
return ListenerToken(token)
}
// MARK: Indexable
/// Return all index names
public func indexes() throws -> [String] {
return try impl.indexes()
}
/// Create an index with the index name and config.
public func createIndex(withName name: String, config: IndexConfiguration) throws {
try impl.createIndex(withName: name, config: config.toImpl())
}
/// Create an index with the index name and index instance.
public func createIndex(_ index: Index, name: String) throws {
try impl.createIndex(index.toImpl(), name: name)
}
/// Delete an index by name.
public func deleteIndex(forName name: String) throws {
try impl.deleteIndex(withName: name)
}
// MARK: Equatable
public static func == (lhs: Collection, rhs: Collection) -> Bool {
return lhs.impl == rhs.impl
}
// MARK: Hashable
public func hash(into hasher: inout Hasher) {
hasher.combine(impl.hash)
}
// MARK: Internal
init(_ impl: CBLCollection, db: Database) {
self.impl = impl
self.db = db
self.scope = Scope(impl.scope, db: db)
}
var isValid: Bool { impl.isValid }
let impl: CBLCollection
let db: Database
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.