text stringlengths 8 1.32M |
|---|
//
// DetailPresenter.swift
// axiata
//
// Created by docotel on 15/10/20.
// Copyright © 2020 Affandy Murad. All rights reserved.
//
import Foundation
import UIKit
class DetailPresenter: BasePresenter<DetailDelegates> {
var reviewList: [ReviewList] = []
let apiKey = "f002c90cf2d54e6b83801cbe9408e82b"
var movieDetail: MovieDetail?
func getMovieDetail(id: String){
self.view.taskDidBegin()
let url = URL(string: "https://api.themoviedb.org/3/movie/\(id)?api_key=\(apiKey)&append_to_response=videos")
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "GET"
// request.addValue(apiKey, forHTTPHeaderField: "api_key")
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
guard let _: Data = data, let _: URLResponse = response, error == nil else {
self.view.taskDidError(txt: error?.localizedDescription ?? "Unknown")
return
}
do{
let movieDetail = try JSONDecoder().decode(MovieDetail.self, from: data!)
self.movieDetail = movieDetail
self.view.loadMovieDetail(movieDetail: self.movieDetail)
} catch _ {
do{
let errors = try JSONDecoder().decode(Errors.self, from: data!)
self.view.taskDidError(txt: errors.status_message)
} catch DecodingError.keyNotFound(let key, let context) {
self.view.taskDidError(txt: "could not find key \(key) in JSON: \(context.debugDescription)")
} catch DecodingError.valueNotFound(let type, let context) {
self.view.taskDidError(txt: "could not find type \(type) in JSON: \(context.debugDescription)")
} catch DecodingError.typeMismatch(let type, let context) {
self.view.taskDidError(txt: "type mismatch for type \(type) in JSON: \(context.debugDescription)")
} catch DecodingError.dataCorrupted(let context) {
self.view.taskDidError(txt: "data found to be corrupted in JSON: \(context.debugDescription)")
} catch let error as NSError {
self.view.taskDidError(txt: "Error in read(from:ofType:) domain= \(error.domain), description= \(error.localizedDescription)")
}
}
})
task.resume()
}
func getMovieReview(id: String){
self.view.taskDidBegin()
let url = URL(string: "https://api.themoviedb.org/3/movie/\(id)/reviews?api_key=\(apiKey)")
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "GET"
// request.addValue(apiKey, forHTTPHeaderField: "api_key")
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
guard let _: Data = data, let _: URLResponse = response, error == nil else {
self.view.taskDidError(txt: error?.localizedDescription ?? "Unknown")
return
}
do{
let review = try JSONDecoder().decode(Review.self, from: data!)
self.reviewList = review.results ?? []
self.view.loadMovieReviewList(reviewList: self.reviewList)
} catch _ {
do{
let errors = try JSONDecoder().decode(Errors.self, from: data!)
self.view.taskDidError(txt: errors.status_message)
} catch DecodingError.keyNotFound(let key, let context) {
self.view.taskDidError(txt: "could not find key \(key) in JSON: \(context.debugDescription)")
} catch DecodingError.valueNotFound(let type, let context) {
self.view.taskDidError(txt: "could not find type \(type) in JSON: \(context.debugDescription)")
} catch DecodingError.typeMismatch(let type, let context) {
self.view.taskDidError(txt: "type mismatch for type \(type) in JSON: \(context.debugDescription)")
} catch DecodingError.dataCorrupted(let context) {
self.view.taskDidError(txt: "data found to be corrupted in JSON: \(context.debugDescription)")
} catch let error as NSError {
self.view.taskDidError(txt: "Error in read(from:ofType:) domain= \(error.domain), description= \(error.localizedDescription)")
}
}
})
task.resume()
}
}
protocol DetailDelegates: BaseDelegate {
func loadMovieDetail(movieDetail: MovieDetail?)
func loadMovieReviewList(reviewList: [ReviewList]?)
}
|
//
// PresentableUIViewController.swift
// hackernews
//
// Created by Daniel Grech on 12/10/2015.
// Copyright © 2015 DGSD. All rights reserved.
//
import UIKit
class PresentableViewController<T: Presenter> : UIViewController {
let presenter: T
init(presenter: T) {
self.presenter = presenter
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("Use from storyboard not supported")
}
override func viewDidLoad() {
super.viewDidLoad()
presenter.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
presenter.viewWillAppear()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
presenter.viewWillDisappear()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
presenter.viewDidAppear()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
presenter.viewDidDisappear()
}
} |
//
// ProgressButton.swift
// AnimationDemo_Swift
//
// Created by mosquito on 2017/7/3.
// Copyright © 2017年 mosquito. All rights reserved.
//
import UIKit
protocol ProgressAnimationDelegate: class {
func animationDidStop()
}
class ProgressButton: UIButton, LoadingCircleLayerProtocol, RectangleProtocol, CAAnimationDelegate {
private var rectangleLayer = RectangleLayer()
private var labelLayer = LabelLayer()
private var loadingLayer = LoadingCircleLayer()
weak var progressDelegate: ProgressAnimationDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
layer.masksToBounds = true
backgroundColor = UIColor.clear
rectangleLayer.delegateAnimation = self
layer.addSublayer(rectangleLayer)
layer.addSublayer(labelLayer)
loadingLayer.loadingDelegate = self
layer.addSublayer(loadingLayer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func layoutSubviews() {
super.layoutSubviews()
rectangleLayer.fillProperties(parentBounds: bounds, color: UIColor.red)
labelLayer.fillProperties(parentBounds: bounds, text: "Sign In")
loadingLayer.fillProperties(parentBounds: bounds, radius: CGFloat(circleRadius))
}
var circleRadius: CFloat {
return ceil(CFloat(min(self.frame.height, self.frame.width)/2.0))
}
func animate() {
hideLabel()
rectangleLayer.animate()
}
func hideLabel() {
labelLayer.fadeIn()
}
func rectangleAnimationDidStop() {
loadingLayer.loadingAnimate()
}
func loadingAnimationDidStop() {
loadingLayer.fadeIn()
rectangleLayer.animateInitialState()
labelLayer.fadeOut()
progressDelegate?.animationDidStop()
}
}
|
//
// Tasks.swift
// TaskManager
//
// Created by Caleb Ogles on 9/18/18.
// Copyright © 2018 Caleb Ogles. All rights reserved.
//
import Foundation
class Task {
//This is the class for the tasks that the user will be entering into their list of tasks to do. It will be taking in the data presented by the user and creating a task out of it as shown below.
var title: String
var detailsOfTask: String
var completionStatus: Bool = false
var completionDate: Date?
init(title: String, detailsOfTask: String) {
self.title = title
self.detailsOfTask = detailsOfTask
}
}
|
//
// File.swift
//
//
// Created by Erkut Demirhan on 29/03/2020.
//
import Foundation
class NewClass {
let stringVariable: String
}
|
//
// Persistence.swift
// Tally
//
// Created by Eric Fritz on 12/23/16.
// Copyright © 2016 Eric Fritz. All rights reserved.
//
import UIKit
import SQLite
class PersistenceError: Error {}
class Database {
static let instance = Database()
private let db: Connection?
private let tasks = Table("tasks")
private let durations = Table("durations")
private let taskId = Expression<Int64>("taskId")
private let durationId = Expression<Int64>("durationId")
private let name = Expression<String>("name")
private let first = Expression<Date>("first")
private let final = Expression<Date?>("final")
private let note = Expression<String?>("note")
private init() {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
do {
db = try Connection("\(path)/tally.sqlite3")
} catch let ex {
db = nil
// better recovery
print("Unable to open database (\(ex)).")
}
do {
try db!.run(tasks.create(temporary: false, ifNotExists: true, block: { table in
table.column(self.taskId, primaryKey: true)
table.column(self.name)
}))
try db!.run(durations.create(temporary: false, ifNotExists: true, block: { table in
table.column(self.durationId, primaryKey: true)
table.column(self.taskId, references: self.tasks, self.taskId)
table.column(self.first)
table.column(self.final)
table.column(self.note)
}))
} catch let ex {
// better recovery
print("Unable to create table (\(ex)).")
}
}
func allTasks() -> [TimedTask]? {
if let db = self.db, let rows = try? db.prepare(self.tasks) {
var results = [TimedTask]()
for row in rows {
let task = TimedTask(id: row[self.taskId], name: row[self.name], durations: [], color: makeRandomColor(mix: UIColor.white))
if let durations = self.durations(for: task) {
for duration in durations {
task.durations.append(duration)
}
} else {
return nil
}
results.append(task)
}
return results.sorted { $0.elapsed() >= $1.elapsed() }
}
return nil
}
func durations(for task: TimedTask) -> [Duration]? {
let query = self.durations.filter(self.taskId == task.id)
if let db = self.db, let rows = try? db.prepare(query) {
var results = [Duration]()
for row in rows {
results.append(Duration(id: row[self.durationId], task: task, first: row[self.first], final: row[self.final], note: row[self.note]))
}
return results.sorted { $0.first <= $1.first }
}
return nil
}
func createTask(name: String) -> TimedTask? {
let insert = self.tasks.insert(self.name <- name)
if let db = self.db {
if let id = try? db.run(insert) {
return TimedTask(id: id, name: name, color: makeRandomColor(mix: UIColor.white))
}
}
return nil
}
func update(task: TimedTask, name: String) -> Bool {
let update = self.tasks.filter(self.taskId == task.id).update(self.name <- name)
if let db = self.db {
if let _ = try? db.run(update) {
task.name = name
return true
}
}
return false
}
func delete(task: TimedTask) -> Bool {
let deletions = [
self.tasks.filter(self.taskId == task.id).delete(),
self.durations.filter(self.taskId == task.id).delete()
]
if let db = self.db {
for query in deletions {
if (try? db.run(query)) == nil {
return false
}
}
return true
}
return false
}
func createDuration(for task: TimedTask) -> Duration? {
return self.createDuration(for: task, first: Date())
}
func createDuration(for task: TimedTask, first: Date, final: Date? = nil) -> Duration? {
let insert = self.durations.insert(self.taskId <- task.id, self.first <- first, self.final <- final)
if let db = self.db {
if let id = try? db.run(insert) {
return Duration(id: id, task: task, first: first, final: final)
}
}
return nil
}
func update(duration: Duration) -> Bool {
let final = Date()
let update = self.durations.filter(self.durationId == duration.id).update(self.final <- final)
if let db = self.db {
if let _ = try? db.run(update) {
duration.final = final
return true
}
}
return false
}
func update(duration: Duration, withNote note: String?) -> Bool {
let update = self.durations.filter(self.durationId == duration.id).update(self.note <- note)
if let db = self.db {
if let _ = try? db.run(update) {
duration.note = note
return true
}
}
return false
}
func delete(duration: Duration) -> Bool {
if let db = self.db {
if let _ = try? db.run(self.durations.filter(self.durationId == duration.id).delete()) {
return true
}
}
return false
}
}
|
//
// MyCarCheckedInViewController.swift
// prkng-ios
//
// Created by Cagdas Altinkaya on 15/05/15.
// Copyright (c) 2015 PRKNG. All rights reserved.
//
import UIKit
class MyCarReservedCarShareViewController: MyCarAbstractViewController, UIGestureRecognizerDelegate, POPAnimationDelegate {
var carShare: CarShare?
var backgroundImageView: UIImageView
// var shareButton: UIButton
var logoView: UIImageView
var containerView: UIView
var locationTitleLabel: UILabel
var locationLabel: UILabel
var availableTitleLabel: UILabel
var availableTimeLabel: UILabel //ex: 24+
var bigButtonContainer: UIView
var mapButton: UIButton
var leaveButton: UIButton
var delegate: MyCarAbstractViewControllerDelegate?
private var timer: NSTimer?
private let SMALL_VERTICAL_MARGIN = 5
private let MEDIUM_VERTICAL_MARGIN = 10
private let LARGE_VERTICAL_MARGIN = 20
private var smallerVerticalMargin: Int = 0
private var largerVerticalMargin: Int = 0
private let BUTTONS_TRANSLATION_X = CGFloat(2*36 + 20 + 14)
let BOTTOM_BUTTON_HEIGHT: CGFloat = 36
init() {
backgroundImageView = UIImageView(image: UIImage(named:"bg_mycar"))
// shareButton = ViewFactory.shareButton()
logoView = UIImageView()
containerView = UIView()
locationTitleLabel = ViewFactory.formLabel()
locationLabel = ViewFactory.bigMessageLabel()
availableTitleLabel = ViewFactory.formLabel()
availableTimeLabel = UILabel()
bigButtonContainer = UIView()
mapButton = ViewFactory.roundedButtonWithHeight(BOTTOM_BUTTON_HEIGHT, backgroundColor: Styles.Colors.stone, font: Styles.FontFaces.regular(12), text: "show_on_map".localizedString.uppercaseString, textColor: Styles.Colors.petrol2, highlightedTextColor: Styles.Colors.petrol1)
leaveButton = ViewFactory.redRoundedButtonWithHeight(BOTTOM_BUTTON_HEIGHT, font: Styles.FontFaces.regular(12), text: "cancel".localizedString.uppercaseString)
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
override func loadView() {
self.view = UIView()
setupViews()
setupConstraints()
//add a tap gesture recognizer
let tapRecognizer1 = UITapGestureRecognizer(target: self, action: Selector("mapButtonTapped"))
let tapRecognizer2 = UITapGestureRecognizer(target: self, action: Selector("mapButtonTapped"))
let tapRecognizer3 = UITapGestureRecognizer(target: self, action: Selector("mapButtonTapped"))
tapRecognizer1.delegate = self
tapRecognizer2.delegate = self
tapRecognizer3.delegate = self
containerView.addGestureRecognizer(tapRecognizer1)
backgroundImageView.addGestureRecognizer(tapRecognizer2)
backgroundImageView.userInteractionEnabled = true
logoView.addGestureRecognizer(tapRecognizer3)
logoView.userInteractionEnabled = true
}
override func viewDidLoad() {
super.viewDidLoad()
self.screenName = "My Car - Reserved Car Share"
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if (carShare == nil) {
if #available(iOS 8.0, *) {
logoView.alpha = 0
containerView.alpha = 0
// bigButtonContainer.layer.transform = CATransform3DMakeTranslation(CGFloat(0), BUTTONS_TRANSLATION_X, CGFloat(0))
}
}
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
self.timer?.invalidate()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if (carShare == nil) {
let setCarShare = {(carShare: CarShare?) -> () in
self.carShare = carShare
self.setDefaultTimeDisplay()
SVProgressHUD.dismiss()
if (carShare != nil) {
if #available(iOS 8.0, *) {
self.animateAndShow()
}
}
}
if let reservedCarShare = Settings.getReservedCarShare() {
setCarShare(reservedCarShare)
}
} else {
self.updateValues()
}
}
func setupViews () {
backgroundImageView.contentMode = .ScaleAspectFill
view.addSubview(backgroundImageView)
segmentedControl.setPressedHandler(segmentedControlTapped)
self.view.addSubview(segmentedControl)
// shareButton.addTarget(self, action: "shareButtonTapped", forControlEvents: UIControlEvents.TouchUpInside)
// self.view.addSubview(shareButton)
logoView.image = UIImage(named: "icon_carshare")
view.addSubview(logoView)
view.addSubview(containerView)
locationTitleLabel.text = "reserved_car_share_message".localizedString.uppercaseString
containerView.addSubview(locationTitleLabel)
locationLabel.text = "PRKNG"
containerView.addSubview(locationLabel)
containerView.addSubview(availableTitleLabel)
availableTimeLabel.textColor = Styles.Colors.red2
availableTimeLabel.text = "0:00"
availableTimeLabel.textAlignment = NSTextAlignment.Center
containerView.addSubview(availableTimeLabel)
view.addSubview(bigButtonContainer)
mapButton.addTarget(self, action: "mapButtonTapped", forControlEvents: UIControlEvents.TouchUpInside)
bigButtonContainer.addSubview(mapButton)
leaveButton.addTarget(self, action: "leaveButtonTapped", forControlEvents: UIControlEvents.TouchUpInside)
bigButtonContainer.addSubview(leaveButton)
}
func setupConstraints () {
smallerVerticalMargin = MEDIUM_VERTICAL_MARGIN
largerVerticalMargin = LARGE_VERTICAL_MARGIN
if UIScreen.mainScreen().bounds.size.height == 480 {
smallerVerticalMargin = SMALL_VERTICAL_MARGIN
largerVerticalMargin = MEDIUM_VERTICAL_MARGIN
}
backgroundImageView.snp_makeConstraints { (make) -> () in
make.edges.equalTo(self.view)
}
segmentedControl.snp_makeConstraints { (make) -> Void in
make.size.equalTo(CGSize(width: 240, height: 24))
make.top.equalTo(self.snp_topLayoutGuideBottom).offset(30)
make.centerX.equalTo(self.view)
}
// shareButton.snp_makeConstraints { (make) -> Void in
// make.top.equalTo(self.snp_topLayoutGuideBottom).offset(30)
// make.centerY.equalTo(self.segmentedControl)
// make.right.equalTo(self.view).offset(-50)
// }
logoView.snp_makeConstraints { (make) -> () in
make.size.equalTo(CGSizeMake(68, 68))
make.centerX.equalTo(self.view)
make.top.equalTo(self.segmentedControl.snp_bottom).offset(40)
}
containerView.snp_makeConstraints { (make) -> () in
make.top.equalTo(self.logoView.snp_bottom).offset(self.largerVerticalMargin)
make.left.equalTo(self.view)
make.right.equalTo(self.view)
}
locationTitleLabel.snp_makeConstraints { (make) -> () in
make.top.equalTo(self.containerView)
make.left.equalTo(self.containerView)
make.right.equalTo(self.containerView)
make.height.equalTo(20)
}
locationLabel.snp_makeConstraints { (make) -> () in
make.top.equalTo(self.locationTitleLabel.snp_bottom).offset(self.smallerVerticalMargin)
make.left.equalTo(self.containerView).offset(15)
make.right.equalTo(self.containerView).offset(-15)
}
availableTitleLabel.snp_makeConstraints { (make) -> () in
make.top.equalTo(self.locationLabel.snp_bottom).offset(self.largerVerticalMargin)
make.left.equalTo(self.containerView)
make.right.equalTo(self.containerView)
}
availableTimeLabel.snp_makeConstraints { (make) -> () in
make.top.equalTo(self.availableTitleLabel.snp_bottom).offset(self.smallerVerticalMargin)
make.left.equalTo(self.containerView)
make.right.equalTo(self.containerView)
make.bottom.equalTo(self.containerView)
}
bigButtonContainer.snp_makeConstraints { (make) -> () in
make.left.equalTo(self.view)
make.right.equalTo(self.view)
make.bottom.equalTo(self.view)
make.height.equalTo(self.BUTTONS_TRANSLATION_X)
}
mapButton.snp_makeConstraints { (make) -> () in
make.height.equalTo(BOTTOM_BUTTON_HEIGHT)
make.bottom.equalTo(self.leaveButton.snp_top).offset(-14)
make.left.equalTo(self.bigButtonContainer).offset(50)
make.right.equalTo(self.bigButtonContainer).offset(-50)
}
leaveButton.snp_makeConstraints { (make) -> () in
make.height.equalTo(BOTTOM_BUTTON_HEIGHT)
make.bottom.equalTo(self.bigButtonContainer).offset(-20)
make.left.equalTo(self.bigButtonContainer).offset(50)
make.right.equalTo(self.bigButtonContainer).offset(-50)
}
}
func updateValues () {
locationLabel.text = (carShare?.carSharingType.name ?? "") + " - " + (carShare?.name ?? "")
if self.carShare != nil {
logoView.image = UIImage(named: "icon_carshare")
let interval = Settings.getReservedCarShareTime()?.timeIntervalSinceNow ?? 0
availableTimeLabel.text = String(Int(interval / 60)) + " minutes".localizedString
availableTimeLabel.font = Styles.Fonts.h1r
}
//update the values every 2 seconds
if self.timer == nil {
self.timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "updateValues", userInfo: nil, repeats: true)
}
}
func mapButtonTapped() {
if let reservedCarShare = carShare {
self.delegate?.goToCoordinate(reservedCarShare.coordinate, named: reservedCarShare.name, showing: false)
}
}
func leaveButtonTapped() {
let tracker = GAI.sharedInstance().defaultTracker
tracker.send(GAIDictionaryBuilder.createEventWithCategory("My Car - Reserved Car Share", action: "Cancel Button Tapped", label: nil, value: nil).build() as [NSObject: AnyObject])
CarSharingOperations.cancelCarShare(self.carShare!, fromVC: self, completion: { (completed) -> Void in
if completed {
self.delegate?.reloadMyCarTab()
}
})
}
func reportButtonTapped(sender: UIButton) {
}
func setDefaultTimeDisplay() {
if self.carShare != nil {
availableTitleLabel.text = "available_for".localizedString.uppercaseString
}
updateValues()
}
func toggleTimeDisplay() {
//toggle between available until and available for
let fadeAnimation = CATransition()
fadeAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
fadeAnimation.type = kCATransitionFade
fadeAnimation.duration = 0.4
availableTitleLabel.layer.addAnimation(fadeAnimation, forKey: "fade")
availableTimeLabel.layer.addAnimation(fadeAnimation, forKey: "fade")
//update values just in case we've run out of time since the last tap...
updateValues()
}
//MARK- gesture recognizer delegate
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func animateAndShow() {
let logoFadeInAnimation = POPBasicAnimation(propertyNamed: kPOPLayerOpacity)
logoFadeInAnimation.fromValue = NSNumber(int: 0)
logoFadeInAnimation.toValue = NSNumber(int: 1)
logoFadeInAnimation.duration = 0.3
logoView.layer.pop_addAnimation(logoFadeInAnimation, forKey: "logoFadeInAnimation")
let logoSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerScaleXY)
logoSpringAnimation.fromValue = NSValue(CGPoint: CGPoint(x: 0.5, y: 0.5))
logoSpringAnimation.toValue = NSValue(CGPoint: CGPoint(x: 1, y: 1))
logoSpringAnimation.springBounciness = 20
logoView.layer.pop_addAnimation(logoSpringAnimation, forKey: "logoSpringAnimation")
let containerFadeInAnimation = POPBasicAnimation(propertyNamed: kPOPLayerOpacity)
containerFadeInAnimation.fromValue = NSNumber(int: 0)
containerFadeInAnimation.toValue = NSNumber(int: 1)
containerFadeInAnimation.duration = 0.6
containerFadeInAnimation.beginTime = CACurrentMediaTime() + 0.15
containerFadeInAnimation.completionBlock = {(anim, finished) in
// // Slide in buttons once container fully visible
// let buttonSlideAnimation = POPBasicAnimation(propertyNamed: kPOPLayerTranslationY)
// buttonSlideAnimation.fromValue = NSNumber(float: Float(self.BUTTONS_TRANSLATION_X))
// buttonSlideAnimation.toValue = NSNumber(int: 0)
// buttonSlideAnimation.duration = 0.2
// self.bigButtonContainer.layer.pop_addAnimation(buttonSlideAnimation, forKey: "buttonSlideAnimation")
}
self.containerView.layer.pop_addAnimation(containerFadeInAnimation, forKey: "containerFadeInAnimation")
}
}
|
func rotate(_ matrix: inout [[Int]]) {
let n = matrix.count
for i in 0..<n/2 {
for j in 0..<(n+1)/2 {
let temp = matrix[i][j]
matrix[i][j] = matrix[n - j - 1][i]
matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1]
matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1]
matrix[j][n - i - 1] = temp
}
}
}
func rotate2(_ matrix: inout [[Int]]) {
let n = matrix.count
for i in 0..<n/2 {
for j in 0..<n {
(matrix[i][j], matrix[n-1-i][j]) = (matrix[n-1-i][j], matrix[i][j])
}
}
for i in 0..<n {
for j in 0..<i {
(matrix[i][j], matrix[j][i]) = (matrix[j][i], matrix[i][j])
}
}
}
var m = [[1,2,3],[4,5,6],[7,8,9]]
rotate2(&m)
print(m)
|
/*
* Copyright (c) 2020 Elastos Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import Foundation
import PromiseKit
/// DID is a globally unique identifier that does not require a centralized registration authority.
/// It includes method specific string. (elastos:id:ixxxxxxxxxx).
public class DID {
private static let TAG = "DID"
private var _method: String?
private var _methodSpecificId: String?
private var _metadata: DIDMeta?
public static let METHOD: String = "elastos"
init() {}
init(_ method: String, _ methodSpecificId: String) {
self._method = method
self._methodSpecificId = methodSpecificId
}
/// Create a new DID according to method specific string.
/// - Parameter did: A pointer to specific string. The method-specific-id value should be globally unique by itself.
/// - Throws: Language is empty or error occurs.
public init(_ did: String) throws {
guard !did.isEmpty else {
throw DIDError.illegalArgument("empty did string")
}
do {
try ParserHelper.parse(did, true, DID.Listener(self))
} catch {
Log.e(DID.TAG, "Parsing did error: malformed did string \(did)")
let didError = error as? DIDError
var errmsg = "Parsing did error: malformed did string \(did)"
if didError != nil {
errmsg = DIDError.desription(didError!)
}
throw DIDError.malformedDID(errmsg)
}
}
/// Get method of DID.
public var method: String {
return _method!
}
func setMethod(_ method: String) {
self._method = method
}
/// Get method specific string of DID.
public var methodSpecificId: String {
return _methodSpecificId!
}
func setMethodSpecificId(_ methodSpecificId: String) {
self._methodSpecificId = methodSpecificId
}
/// Get DID MetaData from did.
/// - Returns: Return the handle to DIDMetaData. Otherwise
public func getMetadata() -> DIDMeta {
if self._metadata == nil {
self._metadata = DIDMeta()
}
return _metadata!
}
func setMetadata(_ newValue: DIDMeta) {
self._metadata = newValue
}
/// Save DID MetaData.
/// - Throws: If error occurs, throw error.
public func saveMetadata() throws {
if (_metadata != nil && _metadata!.attachedStore) {
try _metadata?.store?.storeDidMetadata(self, _metadata!)
}
}
/// Check deactivated
public var isDeactivated: Bool {
return getMetadata().isDeactivated
}
/// Get the newest DID Document from chain.
/// - Parameter force: Indicate if load document from cache or not.
/// force = true, document gets only from chain. force = false, document can get from cache,
/// if no document is in the cache, resolve it from chain.
/// - Throws: If error occurs, throw error.
/// - Returns: Return the handle to DID Document.
public func resolve(_ force: Bool) throws -> DIDDocument? {
let doc = try DIDBackend.resolve(self, force)
if doc != nil {
setMetadata(doc!.getMetadata())
}
return doc
}
/// Get the newest DID Document from chain.
/// - Throws: If error occurs, throw error.
/// - Returns: Return the handle to DID Document
public func resolve() throws -> DIDDocument? {
return try resolve(false)
}
/// Get the newest DID Document asynchronously from chain.
/// - Parameter force: Indicate if load document from cache or not.
/// force = true, document gets only from chain. force = false, document can get from cache,
/// if no document is in the cache, resolve it from chain.
/// - Returns: Return the handle to DID Document.
public func resolveAsync(_ force: Bool) -> Promise<DIDDocument?> {
return Promise<DIDDocument?> { resolver in
do {
resolver.fulfill(try resolve(force))
} catch let error {
resolver.reject(error)
}
}
}
/// Get the newest DID Document asynchronously from chain.
/// - Returns: Return the handle to DID Document.
public func resolveAsync() -> Promise<DIDDocument?> {
return resolveAsync(false)
}
/// Get all DID Documents from chain.
/// - Throws: If error occurs, throw error.
/// - Returns: return the handle to DID Document.
public func resolveHistory() throws -> DIDHistory {
return try DIDBackend.resolveHistory(self)
}
/// Get all DID Documents from chain.
/// - Returns: return the handle to DID Document asynchronously.
public func resolveHistoryAsync() -> Promise<DIDHistory> {
return Promise<DIDHistory> { resolver in
do {
resolver.fulfill(try resolveHistory())
} catch let error {
resolver.reject(error)
}
}
}
}
extension DID: CustomStringConvertible {
func toString() -> String {
return String("did:\(_method!):\(_methodSpecificId!)")
}
/// Get id string from DID.
public var description: String {
return toString()
}
}
extension DID: Equatable {
func equalsTo(_ other: DID) -> Bool {
return methodSpecificId == other.methodSpecificId
}
func equalsTo(_ other: String) -> Bool {
return toString() == other
}
public static func == (lhs: DID, rhs: DID) -> Bool {
return lhs.equalsTo(rhs)
}
public static func != (lhs: DID, rhs: DID) -> Bool {
return !lhs.equalsTo(rhs)
}
}
extension DID: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(self.toString())
}
}
// Parse Listener
extension DID {
private class Listener: DIDURLBaseListener {
private var did: DID
init(_ did: DID) {
self.did = did
super.init()
}
public override func exitMethod(_ ctx: DIDURLParser.MethodContext) {
let method = ctx.getText()
if (method != Constants.METHOD){
// can't throw , print...
Log.e(DID.TAG, "unsupported method: \(method)")
}
self.did._method = Constants.METHOD
}
public override func exitMethodSpecificString(
_ ctx: DIDURLParser.MethodSpecificStringContext) {
self.did._methodSpecificId = ctx.getText()
}
}
}
|
//
// NavigationConfigurator.swift
// MarvelCharacters
//
// Created by Osamu Chiba on 9/26/21.
//
import SwiftUI
struct NavigationConfigurator: UIViewControllerRepresentable {
let configure: (UINavigationController) -> Void
func makeUIViewController(
context: UIViewControllerRepresentableContext<NavigationConfigurator>
) -> NavigationConfigurationViewController {
NavigationConfigurationViewController(configure: configure)
}
func updateUIViewController(
_ uiViewController: NavigationConfigurationViewController,
context: UIViewControllerRepresentableContext<NavigationConfigurator>
) { }
}
final class NavigationConfigurationViewController: UIViewController {
let configure: (UINavigationController) -> Void
init(configure: @escaping (UINavigationController) -> Void) {
self.configure = configure
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let navigationController = navigationController {
configure(navigationController)
}
}
}
|
//
// UIImageExtensions.swift
// CryptoList
//
// Created by Aral Atpulat on 5.02.2019.
// Copyright © 2019 Aral Atpulat. All rights reserved.
//
import Foundation
import UIKit
extension UIImageView {
func rounded(){
self.layer.masksToBounds = false
self.layer.cornerRadius = self.frame.height/2
self.clipsToBounds = true
}
}
|
//
// TutorialCell.swift
// RWDevCon
//
// Created by Mic Pringle on 27/02/2015.
// Copyright (c) 2015 Ray Wenderlich. All rights reserved.
//
import UIKit
class InspirationCell: UICollectionViewCell {
@IBOutlet private weak var imageView: UIImageView!
@IBOutlet private weak var imageCoverView: UIView!
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var timeAndRoomLabel: UILabel!
@IBOutlet private weak var speakerLabel: UILabel!
var inspiration: Inspiration? {
didSet {
if let inspiration = inspiration {
imageView.image = inspiration.backgroundImage
titleLabel.text = inspiration.title
timeAndRoomLabel.text = inspiration.roomAndTime
speakerLabel.text = inspiration.speaker
}
}
}
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
super.apply(layoutAttributes)
let featuredHeight = UltravisualLayoutConstants.Cell.featuredHeight
let standardHeight = UltravisualLayoutConstants.Cell.standardHeight
let delta = 1 - ((featuredHeight - frame.height) / (featuredHeight - standardHeight))
let minAlpha: CGFloat = 0.3
let maxAlpha: CGFloat = 0.75
imageCoverView.alpha = maxAlpha - (delta * (maxAlpha - minAlpha))
let scale = max(delta, 0.5)
titleLabel.transform = CGAffineTransform(scaleX: scale, y: scale)
timeAndRoomLabel.alpha = delta
speakerLabel.alpha = delta
}
}
|
import Vapor
import Fluent
// swiftlint:disable identifier_name
/// A protocol that defines bearer authentication tokens, similar to
/// `ModelTokenAuthenticatable`.
public protocol CorvusModelTokenAuthenticatable: CorvusModel, Authenticatable {
/// The `User` type the token belongs to.
associatedtype User: CorvusModel & Authenticatable
/// The `String` value of the token.
var value: String { get set }
/// The `User` associated with the token.
var user: User { get set }
/// A boolean that deletes tokens if they're not in use.
var isValid: Bool { get }
}
/// An extension to provide a default initializer to tokens so that they can
/// be initialized manually in module code.
extension CorvusModelTokenAuthenticatable {
/// Initializes a token.
/// - Parameters:
/// - id: The unique identifier of the token.
/// - value: The `String` value of the token.
/// - userId: The id of the `User` the token belongs to.
init(id: Self.IDValue? = nil, value: String, userId: User.IDValue) {
self.init()
self.value = value
_$user.id = userId
}
}
/// An extension to provide an authenticator for the token that can be
/// registered to the `Vapor` application, and field accessors for `value` and
/// `user`.
extension CorvusModelTokenAuthenticatable {
/// Provides a `Vapor` authenticator defined below.
/// - Parameter database: The database to authenticate.
/// - Returns: A `CorvusModelTokenAuthenticator`.
public static func authenticator(
database: DatabaseID? = nil
) -> CorvusModelTokenAuthenticator<Self> {
CorvusModelTokenAuthenticator<Self>(database: database)
}
/// Provides access to the `value` attribute.
var _$value: Field<String> {
guard let mirror = Mirror(reflecting: self).descendant("_value"),
let token = mirror as? Field<String> else {
fatalError("value property must be declared using @Field")
}
return token
}
/// Provides access to the `user` attribute.
var _$user: Parent<User> {
guard let mirror = Mirror(reflecting: self).descendant("_user"),
let user = mirror as? Parent<User> else {
fatalError("user property must be declared using @Parent")
}
return user
}
}
/// Provides a `BearerAuthenticator` struct that defines how tokens are
/// authenticated.
public struct CorvusModelTokenAuthenticator<T: CorvusModelTokenAuthenticatable>:
BearerAuthenticator
{
/// The token's user.
public typealias User = T.User
/// The database the token is saved in.
public let database: DatabaseID?
/// Authenticates a token.
/// - Parameters:
/// - bearer: The bearer token passed in the request.
/// - request: The `Request` to be authenticated.
/// - Returns: An empty `EventLoopFuture`.
public func authenticate(
bearer: BearerAuthorization,
for request: Request
) -> EventLoopFuture<Void> {
let db = request.db(self.database)
return T.query(on: db)
.filter(\._$value == bearer.token)
.first()
.flatMap
{ token -> EventLoopFuture<Void> in
guard let token = token else {
return request.eventLoop.makeSucceededFuture(())
}
guard token.isValid else {
return token.delete(on: db)
}
request.auth.login(token)
return token._$user.get(on: db).map {
request.auth.login($0)
}
}
}
}
|
//
// CenterViewControllerDelegate.swift
// Hitcher
//
// Created by Kelvin Fok on 11/2/18.
// Copyright © 2018 Kelvin Fok. All rights reserved.
//
import UIKit
protocol CenterViewControllerDelegate {
func toggleLeftPanel()
}
|
//
// LoadingView.swift
// Movies
//
// Created by Consultor on 12/17/18.
// Copyright © 2018 Mavzapps. All rights reserved.
//
import UIKit
import Lottie
class LoadingView: UIView {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
convenience init(){
self.init(frame: UIScreen.main.bounds)
loadAnimationView()
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
//fatalError("init(coder:) has not been implemented")
}
func loadAnimationView(){
let animationView = LOTAnimationView(name: "movie_loading")
addSubview(animationView)
animationView.addConstraintsToCenter(scale: 0.5)
animationView.contentMode = .scaleAspectFit
animationView.loopAnimation = true
animationView.play{ (finished) in
// Do Something
}
}
func hideAnimationView(){
self.removeFromSuperview()
}
}
|
//
// AssistanceModalViewController.swift
// Weekender
//
// Created by Konstantine Mushegian on 5/8/16.
// Copyright © 2016 Konstantine Mushegian. All rights reserved.
//
import UIKit
class AssistanceModalViewController: UIViewController {
let C = Constants()
var doneButton: UIButton?
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
override func prefersStatusBarHidden() -> Bool {
return true
}
func setup() {
self.view.backgroundColor = UIColor.magentaColor()
addDoneButton()
}
func addDoneButton() {
doneButton = UIButton()
doneButton?.frame = CGRectMake(C.doneButtonX, C.doneButtonY, C.doneButtonWidth, C.doneButtonHeight)
doneButton?.setTitle(C.backButtonTitle, forState: .Normal)
doneButton?.setTitleColor(UIColor.whiteColor(), forState: .Normal)
doneButton?.setTitleColor(UIColor.grayColor(), forState: .Selected)
doneButton?.backgroundColor = UIColor.purpleColor()
doneButton?.layer.cornerRadius = C.doneButtonCornerRadius
doneButton?.addTarget(self, action: #selector(WellnessTipsModalViewController.dismiss), forControlEvents: .TouchUpInside)
self.view.addSubview(doneButton!)
}
func dismiss(sender: UIButton) {
dismissViewControllerAnimated(true, completion: nil)
}
}
|
//
// User.swift
// PublisherSubscriber
//
// Created by Thongchai Subsaidee on 18/6/2564 BE.
//
import SwiftUI
struct UserModel: Identifiable, Decodable {
let id: Int
let name: String
}
|
//
// chatViewControllerExtension.swift
// ChatApp
//
// Created by Kashif Rizwan on 9/5/19.
// Copyright © 2019 Dima Nikolaev. All rights reserved.
//
import Foundation
import AVFoundation
extension chatViewController: AVAudioRecorderDelegate{
func playSound(soundUrl: String)
{
let audioSession = AVAudioSession.sharedInstance()
do {
try! audioSession.setCategory(AVAudioSession.Category.playAndRecord)
try audioSession.setMode(AVAudioSession.Mode.spokenAudio)
try audioSession.setActive(true, options: .notifyOthersOnDeactivation)
let currentRoute = AVAudioSession.sharedInstance().currentRoute
for description in currentRoute.outputs {
if description.portType == AVAudioSession.Port.headphones {
try audioSession.overrideOutputAudioPort(AVAudioSession.PortOverride.none)
} else {
try audioSession.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
}
}
} catch {
print("audioSession properties weren't set because of an error.")
}
let url = URL(string: soundUrl)
let item = AVPlayerItem(url: url!)
NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying(sender:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item)
self.audioPlayer = AVPlayer(playerItem: item)
}
@objc func playerDidFinishPlaying(sender: NSNotification) {
self.audioButton.setImage(self.play, for: .normal)
}
func recordAudio(){
let fileName = self.getDirectory().appendingPathComponent("myRecording.m4a")
do{
self.audioRecorder = try AVAudioRecorder(url: fileName, settings: self.settings)
self.audioRecorder.delegate = self
self.audioRecorder.record()
}catch{
self.showErrorAlert(message: "Recording Failed")
}
}
func setupAudioSession(){
self.recordingSession = AVAudioSession.sharedInstance()
AVAudioSession.sharedInstance().requestRecordPermission({(hasPermission) in
if hasPermission{
print("Permission Granted")
}
})
}
func getDirectory() -> URL{
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentDirectory = paths[0]
return documentDirectory
}
func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int) {
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
}
|
//
// LibraryViewController.swift
// Pokedex
//
// Created by David Yang on 16/01/2019.
// Copyright © 2019 David Yang. All rights reserved.
//
import UIKit
final class LibraryViewController: UIViewController {
let model = PokemonModel()
}
extension LibraryViewController {
@IBAction func selectPicture(_ sender: Any) {
openMediaPicker()
}
func openMediaPicker() {
guard UIImagePickerController.isSourceTypeAvailable(.photoLibrary) else {
return
}
let pickerController = UIImagePickerController()
pickerController.sourceType = .photoLibrary
pickerController.delegate = self
self.present(pickerController, animated: true)
}
func displayResult(for image: UIImage) {
guard let rescaledImage = image.scaleImage(newSize: CGSize(width: 299, height: 299)),
let imagePixelBuffer = rescaledImage.buffer(),
let prediction = try? model.prediction(image: imagePixelBuffer) else {
presentAlert(message: "could not load model")
return
}
let predictedValue = prediction.classLabel
let predictedProb = prediction.classLabelProbs[predictedValue]!
let resultText = "\(predictedValue): \(round(predictedProb * 100))%"
presentAlert(message: resultText)
}
private func presentAlert(with title: String = "", message: String?) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let dismissAction = UIAlertAction(title: "OK", style: .default)
alertController.addAction(dismissAction)
present(alertController, animated: true)
}
}
extension LibraryViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
dismiss(animated: true) { [weak self] in
guard let `self` = self else { return }
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
self.displayResult(for: image)
}
}
}
}
|
//
// CellLoading.swift
// Test
//
// Created by user149331 on 3/10/19.
// Copyright © 2019 Ostap. All rights reserved.
//
import UIKit
class CellLoading: UITableViewCell {
static let reuseIdentifier = "CellLoading"
@IBOutlet weak var spinner: UIActivityIndicatorView!
}
|
//
// List+Extension.swift
// PizzaDemo
//
// Created by Pietro Gandolfi on 02/01/2019.
// Copyright © 2019 Pietro Gandolfi. All rights reserved.
//
import Foundation
import Realm
import RealmSwift
extension List {
func toArray() -> [List.Iterator.Element] {
return map { $0 }
}
}
|
//
// UserSM.swift
// Etbaroon
//
// Created by dev tl on 1/28/18.
// Copyright © 2018 dev tl. All rights reserved.
//
import UIKit
class UserSM: NSObject {
}
|
//
// LinePIX.swift
// PixelKit
//
// Created by Anton Heestand on 2019-03-28.
//
import SwiftUI
import Foundation
import CoreGraphics
import RenderKit
import Resolution
// TODO: Square Caps
final public class LinePIX: PIXGenerator, PIXViewable {
override public var shaderName: String { return "contentGeneratorLinePIX" }
// MARK: - Public Properties
@LivePoint("positionFrom") public var positionFrom: CGPoint = CGPoint(x: -0.5, y: 0.0)
@LivePoint("positionTo") public var positionTo: CGPoint = CGPoint(x: 0.5, y: 0.0)
@LiveFloat("lineWidth", range: 0.0...0.05, increment: 0.005) public var lineWidth: CGFloat = 0.01
public enum Cap: String, Enumable {
case square
case round
case diamond
public var index: Int {
switch self {
case .square:
return 0
case .round:
return 1
case .diamond:
return 2
}
}
public var name: String {
switch self {
case .square:
return "Square"
case .round:
return "Round"
case .diamond:
return "Diamond"
}
}
public var typeName: String { rawValue }
}
@LiveEnum("cap") public var cap: Cap = .square
// MARK: - Property Helpers
public override var liveList: [LiveWrap] {
super.liveList + [_positionFrom, _positionTo, _lineWidth, _cap]
}
override public var values: [Floatable] {
[positionFrom, positionTo, lineWidth, cap, super.color, super.backgroundColor]
}
// MARK: - Life Cycle
public required init(at resolution: Resolution = .auto(render: PixelKit.main.render)) {
super.init(at: resolution, name: "Line", typeName: "pix-content-generator-line")
}
public convenience init(at resolution: Resolution = .auto(render: PixelKit.main.render),
positionFrom: CGPoint = CGPoint(x: -0.25, y: -0.25),
positionTo: CGPoint = CGPoint(x: 0.25, y: 0.25),
scale: CGFloat = 0.01) {
self.init(at: resolution)
self.positionFrom = positionFrom
self.positionTo = positionTo
self.lineWidth = lineWidth
}
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
PixelView(pix: LinePIX())
}
}
|
//
// MixedTalViewController.swift
// POP
//
// Created by 陈刚 on 16/9/4.
// Copyright © 2016年 陈刚. All rights reserved.
//
import UIKit
class MixedTalViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var data = FirstDemoDataModel()
override func viewDidLoad() {
super.viewDidLoad()
//去除tableview顶部的留白
automaticallyAdjustsScrollViewInsets = false
//为了使用一下 DispatchTime ,强行加了一个刷新方法
DispatchQueue.main.asyncAfter(deadline: 3.5) {
self.tableView.reloadData()
print("刷新了一下")
}
}
}
extension MixedTalViewController:UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.mixedArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:FirstDemoTableViewCell = tableView.dequeueReusableCell(forIndexPath: indexPath)
switch data.mixedArray[indexPath.row] {
case .event(let event):
cell.get(data: event)
case .festival(let festival):
cell.get(data: festival)
}
cell.buttonPressedClouse = {[unowned self] cell in
if let indexPath = self.tableView.indexPath(for: cell){
//把Cell绑定的旧数据赋值到一个新的可变对象中
if case .event(var event) = self.data.mixedArray[indexPath.row] {
//这里只是模拟,不会修改数据源中的值
//修改该对象中的值
event.warning = false
//通过赋值的方法替换掉旧数据
self.data.mixedArray[indexPath.row] = .event(event)
//因为Cell是引用类型,可以通过重新绑定刷新页面,替代tableview的刷新方法
cell.get(data:event)
//你也可以用下面的系统方法
self.tableView.reloadRows(at: [indexPath], with: .none)
//打印数据,查看效果
print(self.data.mixedArray)
}
}
}
return cell
}
}
|
//
// Data.swift
// MarvelComic
//
// Created by Alec Malcolm on 2018-03-06.
// Copyright © 2018 Alec Malcolm. All rights reserved.
//
import Foundation
extension Data {
var hexString: String {
return map { String(format: "%02hhx", $0) }.joined()
}
var md5: Data {
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
self.withUnsafeBytes({
_ = CC_MD5($0, CC_LONG(self.count), &digest)
})
return Data(bytes: digest)
}
}
|
//
// UserPhotoCollectionViewController.swift
// SocialApp
//
// Created by Иван Казанцев on 17.01.2021.
//
import UIKit
class UserProfileCollectionViewController: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
}
|
//
// HomeFooter.swift
// Exclusiv
//
// Created by Thanh Tran on 11/1/16.
// Copyright © 2016 SotaTek. All rights reserved.
//
import Foundation
import UIKit
@objc protocol HomeFooterDelegate: class {
func onSelectTab(_ footer: HomeFooter, index: Int)
func onShowMain()
}
@IBDesignable
class HomeFooter: XibView {
@IBOutlet weak var delegate: HomeFooterDelegate?
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!
@IBOutlet weak var button4: UIButton!
private var buttons: [UIButton] = []
override func awakeFromNib() {
super.awakeFromNib()
buttons = [button1, button2, button3, button4]
}
@IBAction func onSelectTab(_ sender: UIButton) {
sender.isSelected = true
buttons.forEach {
if $0 != sender {
$0.isSelected = false
}
}
delegate?.onSelectTab(self, index: sender.tag)
}
@IBAction func onSelectCenter(_ sender: UIButton) {
delegate?.onShowMain()
}
override func layoutSubviews() {
super.layoutSubviews()
layoutButtons()
}
private func layoutButtons() {
button1.centerVertically()
button2.centerVertically()
button3.centerVertically()
button4.centerVertically()
}
}
|
//
// EntryViewController.swift
// Tone
//
// Created by Christopher Aziz on 7/8/17.
// Copyright © 2017 Christopher Aziz. All rights reserved.
//
import UIKit
import ToneAnalyzerV3
class EntryViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
var recordedText: String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
textView.text = recordedText
print(textView.text)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension EntryViewController {
func getTones(recordedText: String) -> [[String : Double]] {
var tones = [[String : Double]]()
let toneAnalyzer = ToneAnalyzer(username: Constants.ToneAnalyzer.username, password: Constants.ToneAnalyzer.password, version: Constants.ToneAnalyzer.version)
let failure = { (error: Error) in print(error) }
toneAnalyzer.getTone(ofText: recordedText, failure: failure) { result in
for type in 0..<result.documentTone.count {
for tone in result.documentTone[type].tones {
tones[type][tone.name] = tone.score
}
}
}
return tones
}
}
|
//
// ViewController.swift
// test5
//
// Created by Huy on 3/13/20.
// Copyright © 2020 Huy. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let imageCT : UIImageView = {
let imageCT = UIImageView()
imageCT.translatesAutoresizingMaskIntoConstraints = false
imageCT.image = UIImage(named: "login")
imageCT.contentMode = .scaleToFill
return imageCT
}()
let Logintk : UITextField = {
let Logintk = UITextField()
Logintk.translatesAutoresizingMaskIntoConstraints = false
Logintk.backgroundColor = .white
Logintk.placeholder = "👤 Nhập tài khoản"
Logintk.textAlignment = .center
Logintk.font = .boldSystemFont(ofSize: 18)
return Logintk
}()
let Label1 : UILabel = {
let Label1 = UILabel()
Label1.translatesAutoresizingMaskIntoConstraints = false
Label1.text = "Trip Way"
Label1.textColor = UIColor.init(named: "xanhdam")
Label1.textAlignment = .center
Label1.font = .boldSystemFont(ofSize: 90)
Label1.alpha = 0.7
return Label1
}()
let Loginmk : UITextField = {
let Logintk = UITextField()
Logintk.translatesAutoresizingMaskIntoConstraints = false
Logintk.backgroundColor = .white
Logintk.placeholder = "🔓 Mật khẩu"
Logintk.textAlignment = .center
Logintk.font = .boldSystemFont(ofSize: 18)
return Logintk
}()
let buttonlogin : UIButton = {
let buttonFind = UIButton()
buttonFind.translatesAutoresizingMaskIntoConstraints = false
buttonFind.setTitle("Đăng nhập", for: .normal)
buttonFind.contentHorizontalAlignment = .center
buttonFind.backgroundColor = UIColor.init(named: "xanh")
return buttonFind
}()
let LabelWh : UILabel = {
let LabelWh = UILabel()
LabelWh.translatesAutoresizingMaskIntoConstraints = false
LabelWh.text = "Bạn chưa có tài khoản ?"
LabelWh.textColor = .white
LabelWh.textAlignment = .center
LabelWh.font = .boldSystemFont(ofSize: 16)
return LabelWh
}()
let buttonForget : UIButton = {
let buttonForget = UIButton()
buttonForget.translatesAutoresizingMaskIntoConstraints = false
buttonForget.setTitle("Quên mật khẩu ?", for: .normal)
buttonForget.contentHorizontalAlignment = .center
buttonForget.setTitleColor(.red, for: .normal)
return buttonForget
}()
let buttonRes : UIButton = {
let buttonRes = UIButton()
buttonRes.translatesAutoresizingMaskIntoConstraints = false
buttonRes.setTitle("Đăng kí tài khoản.", for: .normal)
buttonRes.setTitleColor(.yellow, for: .normal)
buttonRes.contentHorizontalAlignment = .center
return buttonRes
}()
// @IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
setup()
// Do any additional setup after loading the view.
// button.addTarget(self, action: #selector(search), for: .touchUpInside)
}
func setup(){
view.addSubview(imageCT)
// imageCT.alpha = 0.7
imageCT.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
imageCT.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
imageCT.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
imageCT.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
view.addSubview(Label1)
Label1.topAnchor.constraint(equalTo: view.topAnchor, constant: 150).isActive = true
Label1.bottomAnchor.constraint(equalTo: Label1.topAnchor, constant: 100).isActive = true
Label1.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 20).isActive = true
Label1.leftAnchor.constraint(equalTo: view.leftAnchor, constant: -20).isActive = true
Label1.alpha = 0.5
view.addSubview(Logintk)
Logintk.topAnchor.constraint(equalTo: Label1.bottomAnchor, constant: 50).isActive = true
Logintk.bottomAnchor.constraint(equalTo: Logintk.topAnchor, constant: 50).isActive = true
Logintk.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -30).isActive = true
Logintk.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30).isActive = true
Logintk.layer.cornerRadius = 5
view.addSubview(Loginmk)
Loginmk.topAnchor.constraint(equalTo: Logintk.bottomAnchor, constant: 30).isActive = true
Loginmk.bottomAnchor.constraint(equalTo: Loginmk.topAnchor, constant: 50).isActive = true
Loginmk.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -30).isActive = true
Loginmk.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 30).isActive = true
Loginmk.layer.cornerRadius = 5
view.addSubview(buttonlogin)
buttonlogin.topAnchor.constraint(equalTo: Loginmk.bottomAnchor, constant: 50).isActive = true
buttonlogin.heightAnchor.constraint(equalToConstant: 50).isActive = true
buttonlogin.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -40).isActive = true
buttonlogin.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 40).isActive = true
buttonlogin.layer.cornerRadius = 5
buttonlogin.addTarget(self, action: #selector(outLogin), for: .touchUpInside)
view.addSubview(buttonForget)
buttonForget.topAnchor.constraint(equalTo: view.bottomAnchor, constant: -100).isActive = true
buttonForget.heightAnchor.constraint(equalToConstant: 20).isActive = true
buttonForget.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true
buttonForget.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.4).isActive = true
buttonForget.addTarget(self, action: #selector(register), for: .touchUpInside)
view.addSubview(LabelWh)
LabelWh.topAnchor.constraint(equalTo: buttonForget.bottomAnchor, constant: 10).isActive = true
LabelWh.heightAnchor.constraint(equalToConstant: 20).isActive = true
LabelWh.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.44).isActive = true
LabelWh.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: -80).isActive = true
view.addSubview(buttonRes)
buttonRes.topAnchor.constraint(equalTo: buttonForget.bottomAnchor, constant: 10).isActive = true
buttonRes.heightAnchor.constraint(equalToConstant: 20).isActive = true
buttonRes.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5).isActive = true
buttonRes.leftAnchor.constraint(equalTo: LabelWh.rightAnchor, constant: -20).isActive = true
buttonRes.addTarget(self, action: #selector(register), for: .touchUpInside)
}
@objc func outLogin(){
let secondVC = TabbarCT()
secondVC.modalPresentationStyle = .fullScreen
present(secondVC, animated: true, completion: nil)
}
@objc func register(){
let secondVC = TabbarCT()
secondVC.modalPresentationStyle = .fullScreen
present(secondVC, animated: true, completion: nil)
}
@objc func forgetPa(){
let secondVC = TabbarCT()
secondVC.modalPresentationStyle = .fullScreen
present(secondVC, animated: true, completion: nil)
}
}
|
//
// DotaServiceProtocol.swift
// Dotabase
//
// Created by zhussupov on 26.05.2021.
//
protocol DotaServiceProtocol {
func getHeroes(_ completion: @escaping ([String: Hero]) -> Void)
func getHeroLore(_ completion: @escaping (([String: String]) -> Void))
}
|
//: [Previous](@previous)
import Foundation
struct TimesTable {
subscript(index: Int) -> Int {
return 1
}
}
let timeTable = TimesTable()
timeTable[1] // return 1
timeTable[33] // also returns 1
//: [Next](@next)
|
//
// CRPresentationController.swift
// CRSwiftWB
//
// Created by Apple on 16/8/31.
// Copyright © 2016年 Apple. All rights reserved.
// 转场控制器
import UIKit
class CRPresentationController: UIPresentationController {
/// 设置modal出来View的Frame
var presentedFrame :CGRect = CGRect.zero
fileprivate lazy var coverView : UIView = UIView()
//modal出来的控件,底部都有个containerView
override func containerViewWillLayoutSubviews() {
super.containerViewWillLayoutSubviews()
// 1.设置弹出View的尺寸
presentedView?.frame = presentedFrame
//2.添加蒙版
self.setupCoverView()
}
}
//MARK:---------- 设置UI界面 ----------
extension CRPresentationController {
fileprivate func setupCoverView(){
//添加蒙版
containerView?.insertSubview(coverView, at: 0)
coverView.backgroundColor = UIColor(white: 0.5, alpha: 0.4)
coverView.frame = containerView!.bounds
//添加手势
let ges = UITapGestureRecognizer(target: self, action: #selector(CRPresentationController.coverViewClick))
coverView.addGestureRecognizer(ges)
}
}
//MARK:---------- 时间监听 ----------
extension CRPresentationController {
@objc fileprivate func coverViewClick() {
presentedViewController.dismiss(animated: true, completion: nil)
}
}
|
import UIKit
class CoursesViewController: UITableViewController {
private let jsonUrlOne = "https://swiftbook.ru//wp-content/uploads/api/api_course"
private let jsonUrlTwo = "https://swiftbook.ru//wp-content/uploads/api/api_courses"
private let jsonUrlhree = "https://swiftbook.ru//wp-content/uploads/api/api_website_description"
private let jsonUrlFour = "https://swiftbook.ru//wp-content/uploads/api/api_missing_or_wrong_fields"
private var courses: [Course] = []
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return courses.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CourseCell
let course = courses[indexPath.row]
cell.configure(with: course)
return cell
}
// MARK: - TableViewDelegate
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func fetchDataV1() {
guard let url = URL(string: jsonUrlOne) else { return }
URLSession.shared.dataTask(with: url) { (data, _, _) in
guard let data = data else { return }
do {
let course = try JSONDecoder().decode(Course.self, from: data)
print(course.name ?? "")
print(course.imageUrl ?? "")
} catch let error {
print(error)
}
}.resume()
}
func fetchDataV2() {
guard let url = URL(string: jsonUrlTwo) else { return }
URLSession.shared.dataTask(with: url) { (data, _, _) in
guard let data = data else { return }
do {
let courses = try JSONDecoder().decode([Course].self, from: data)
print(courses)
} catch let error {
print(error)
}
}.resume()
}
func fetchDataV3() {
guard let url = URL(string: jsonUrlhree) else { return }
URLSession.shared.dataTask(with: url) { (data, _, _) in
guard let data = data else { return }
do {
let websiteDescription = try JSONDecoder().decode(WebsiteDescription.self, from: data)
print(websiteDescription.courses ?? [])
print(websiteDescription.websiteDescription ?? "")
print(websiteDescription.websiteName ?? "")
} catch let error {
print(error)
}
}.resume()
}
func fetchDataV4() {
guard let url = URL(string: jsonUrlFour) else { return }
URLSession.shared.dataTask(with: url) { (data, _, _) in
guard let data = data else { return }
do {
let websiteDescription = try JSONDecoder().decode(WebsiteDescription.self, from: data)
print(websiteDescription.courses ?? [])
print(websiteDescription.websiteDescription ?? "nil")
print(websiteDescription.websiteName ?? "nil")
} catch let error {
print(error)
}
}.resume()
}
func fetchData() {
guard let url = URL(string: jsonUrlTwo) else { return }
URLSession.shared.dataTask(with: url) { (data, _, _) in
guard let data = data else { return }
do {
self.courses = try JSONDecoder().decode([Course].self, from: data)
} catch let error {
print(error)
}
}.resume()
}
}
|
//
// ViewController.swift
// inAppPurchase
//
// Created by Alexis Saint-Jean on 7/4/15.
// Copyright (c) 2015 Alexis Saint-Jean. All rights reserved.
//
import UIKit
import StoreKit
class ViewController: UIViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver {
@IBOutlet weak var lblAd: UILabel!
@IBOutlet weak var resultLabel: UILabel!
@IBOutlet weak var outRemoveAds: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
outRemoveAds.enabled = false
if(SKPaymentQueue.canMakePayments()) {
println("In App Purchase enabled. Loading...")
var productID:NSSet = NSSet(objects: "asjdev.inAppPurchase.vocabulary", "asjdev.inAppPurchase.removeAds")
var request:SKProductsRequest = SKProductsRequest(productIdentifiers: productID as Set<NSObject>)
request.delegate = self
request.start()
} else {
println("Please enable in app purchases")
resultLabel.text = "Please enable in app purchases"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btnRemoveAds(sender: UIButton) {
for product in list {
var prodID = product.productIdentifier
if(prodID == "asjdev.inAppPurchase.vocabulary"){
p = product
buyProduct()
break
}
}
}
func removeAds() {
println("Removing Ads")
resultLabel.text = "Removing Ads"
}
func addCoins() {
println("Adding coins")
resultLabel.text = "Adding Coins"
}
@IBAction func RestorePurchases(sender: UIButton) {
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
}
var list = [SKProduct]()
var p = SKProduct()
func buyProduct() {
println(" buy " + p.productIdentifier)
var pay = SKPayment(product: p)
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
SKPaymentQueue.defaultQueue().addPayment(pay as SKPayment)
}
func productsRequest(request: SKProductsRequest!, didReceiveResponse response: SKProductsResponse!) {
println("product request")
var myProduct = response.products
for product in myProduct {
println("product added")
println(product.productIdentifier)
println(product.localizedTitle)
println(product.localizedDescription)
println(product.price)
list.append(product as! SKProduct)
}
outRemoveAds.enabled = true
}
func paymentQueueRestoreCompletedTransactionsFinished(queue: SKPaymentQueue!) {
println("Transactions restored.")
var purchasedItemIDs = []
for transaction in queue.transactions {
var t:SKPaymentTransaction = transaction as! SKPaymentTransaction
let prodID = t.payment.productIdentifier as String
switch prodID {
case "asjdev.inAppPurchase.vocabulary":
println("add vocabulary")
removeAds()
case "asjdev.inAppPurchase.removeAds":
println("remove Ads")
addCoins()
default:
println("ID not set up")
}
}
}
func paymentQueue(queue: SKPaymentQueue!, updatedTransactions transactions: [AnyObject]!) {
println("add payment")
for transaction:AnyObject in transactions {
var trans = transaction as! SKPaymentTransaction
println(trans.error)
switch trans.transactionState {
case .Purchased:
println("buy, OK to unlock")
println(p.productIdentifier)
let prodID = p.productIdentifier as String
switch prodID {
case "asjdev.inAppPurchase.vocabulary":
println("add vocabulary")
removeAds()
case "asjdev.inAppPurchase.removeAds":
println("remove Ads")
addCoins()
default:
println("ID not set up")
}
queue.finishTransaction(trans)
break
case .Failed:
println("Buy error")
queue.finishTransaction(trans)
break
default:
println("default")
break
}
}
}
func finishTransaction(trans:SKPaymentTransaction){
println("finish trans")
}
func paymentQueue(queue: SKPaymentQueue!, removedTransactions transactions: [AnyObject]!) {
println("remove trans")
}
}
|
//
// Storage.swift
// TipWorks
//
// Created by Tuan-Lung Wang on 8/12/17.
// Copyright © 2017 Tuan-Lung Wang. All rights reserved.
//
import Foundation
class Storage {
class func save(key: String, value: Any) {
let defaults = UserDefaults.standard
defaults.set(NSKeyedArchiver.archivedData(withRootObject: value), forKey: key)
defaults.synchronize()
}
class func load(key: String) -> Any? {
let defaults = UserDefaults.standard
if let data = defaults.object(forKey: key) as? NSData {
return NSKeyedUnarchiver.unarchiveObject(with: data as Data)
}
return nil
}
}
|
//
// Preloading.swift
// swiftTest
//
// Created by X on 15/3/10.
// Copyright (c) 2015年 swiftTest. All rights reserved.
//
import Foundation
class Preloading: NSObject{
static let Share = Preloading()
private override init() {
super.init()
}
func CheckToken()
{
if DataCache.Share.User.token == "" {return}
let url = APPURL+"Public/Found/?service=user.getOrLine&token="+DataCache.Share.User.token
XHttpPool.requestJson(url, body: nil, method: .GET) { (res) in
if res?["data"]["code"].int == 1
{
NSNotificationCenter.defaultCenter().postNotificationName("AccountLogout", object: nil)
}
}
}
}
|
//
// PreviewCell.swift
// BrackIt
//
// Created by Justin Galang on 5/9/20.
// Copyright © 2020 Justin Galang. All rights reserved.
//
import UIKit
class PreviewCell: UITableViewCell {
static let identifier = "PreviewCell"
@IBOutlet weak var optionOne: UILabel!
@IBOutlet weak var optionTwo: UILabel!
func setOptions(node: Node) {
optionOne.text = node.optionOne.label
optionTwo.text = node.optionTwo.label
}
func setOptions(optionOneText: String, optionTwoText: String) {
optionOne.text = optionOneText
optionTwo.text = optionTwoText
}
// 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
// }
}
|
//
// Bool+toggle.swift
// SwiftToolBox
//
// Created by 李杰 on 2018/10/27.
// Copyright © 2018年 李杰. All rights reserved.
//
extension Bool {
/// Toggle Bool value --- 切换 Bool 值
mutating func toggle() {
self = !self
}
}
|
//
// SimpleHaptics.swift
//
// Created by Tianwei Zhang on 4/2/21.
//
import UIKit
/// Generates haptics on supported devices.
///
/// Will silently fail if unsupported on the device,
/// so compatibility check could be skipped.
public enum Haptics {
/// Types of different haptics.
///
/// Selection Haptic - is used to give user feedback when a selection changes.
/// - `selection`: Generates a gentle tap to the user indicating a selection has changed.
///
/// Notification Haptic - is used to give user feedback when an notification is displayed.
/// - `success`: Indicates an action completed successfully to the user.
/// - `warning`: Indicates to the user that a warning has occurred, or that something is about to happen.
/// - `error`: Indicates an error has occurred to the user.
///
/// Impact Haptic - is used to give user feedback when an impact between UI elements occurs.
/// - `light`: A light impact. Slightly stronger than HapticType.selection
/// - `medium`: An impact stronger than HapticType.light
/// - `heavy`: An impact stronger than HapticType.medium
/// - `soft`: A soft impact.
/// - `rigid`: A rigid impact.
public enum HapticType {
case selection
case success
case warning
case error
case light
case medium
case heavy
case soft
case rigid
}
// swiftlint:disable:next cyclomatic_complexity
/// Generates a haptic feedback.
///
/// It is safe to call this function on any version of iOS without checking availability.
/// On devices that don't support the specified haptic type, this function silently fails.
///
/// - Parameter hapticType: The type of haptics to generate.
/// Notice that the soft impact and rigid impact are only supported since iOS 13.
public static func generate(_ hapticType: HapticType) {
guard #available(iOS 10.0, *) else { return }
DispatchQueue.main.async {
switch hapticType {
case .selection:
UISelectionFeedbackGenerator().selectionChanged()
case .success:
UINotificationFeedbackGenerator().notificationOccurred(.success)
case .warning:
UINotificationFeedbackGenerator().notificationOccurred(.warning)
case .error:
UINotificationFeedbackGenerator().notificationOccurred(.error)
case .light:
UIImpactFeedbackGenerator(style: .light).impactOccurred()
case .medium:
UIImpactFeedbackGenerator(style: .medium).impactOccurred()
case .heavy:
UIImpactFeedbackGenerator(style: .heavy).impactOccurred()
case .soft:
guard #available(iOS 13.0, *) else { return }
UIImpactFeedbackGenerator(style: .soft).impactOccurred()
case .rigid:
guard #available(iOS 13.0, *) else { return }
UIImpactFeedbackGenerator(style: .rigid).impactOccurred()
}
}
}
}
|
//
// UILabel+Extension.swift
// IBKit
//
// Created by NateKim on 2019/11/06.
// Copyright © 2019 NateKim. All rights reserved.
//
import UIKit
extension UILabel {
@discardableResult public func text(_ text: String?) -> Self {
self.text = text
return self
}
@discardableResult public func font(_ font: UIFont) -> Self {
self.font = font
return self
}
@discardableResult public func textColor(_ textColor: UIColor) -> Self {
self.textColor = textColor
return self
}
@discardableResult public func shadowColor(_ shadowColor: UIColor?) -> Self {
self.shadowColor = shadowColor
return self
}
@discardableResult public func shadowOffset(_ shadowOffset: CGSize) -> Self {
self.shadowOffset = shadowOffset
return self
}
@discardableResult public func textAlignment(_ textAlignment: NSTextAlignment) -> Self {
self.textAlignment = textAlignment
return self
}
@discardableResult public func lineBreakMode(_ lineBreakMode: NSLineBreakMode) -> Self {
self.lineBreakMode = lineBreakMode
return self
}
@discardableResult public func attributedText(_ attributedText: NSAttributedString?) -> Self {
self.attributedText = attributedText
return self
}
@discardableResult public func highlightedTextColor(_ highlightedTextColor: UIColor?) -> Self {
self.highlightedTextColor = highlightedTextColor
return self
}
@discardableResult public func isHighlighted(_ isHighlighted: Bool) -> Self {
self.isHighlighted = isHighlighted
return self
}
@discardableResult public func isEnabled(_ isEnabled: Bool) -> Self {
self.isEnabled = isEnabled
return self
}
@discardableResult public func numberOfLines(_ numberOfLines: Int) -> Self {
self.numberOfLines = numberOfLines
return self
}
@discardableResult public func adjustsFontSizeToFitWidth(_ adjustsFontSizeToFitWidth: Bool) -> Self {
self.adjustsFontSizeToFitWidth = adjustsFontSizeToFitWidth
return self
}
@discardableResult public func baselineAdjustment(_ baselineAdjustment: UIBaselineAdjustment) -> Self {
self.baselineAdjustment = baselineAdjustment
return self
}
@discardableResult public func minimumScaleFactor(_ minimumScaleFactor: CGFloat) -> Self {
self.minimumScaleFactor = minimumScaleFactor
return self
}
@discardableResult public func allowsDefaultTighteningForTruncation(_ allowsDefaultTighteningForTruncation: Bool) -> Self {
self.allowsDefaultTighteningForTruncation = allowsDefaultTighteningForTruncation
return self
}
@discardableResult public func preferredMaxLayoutWidth(_ preferredMaxLayoutWidth: CGFloat) -> Self {
self.preferredMaxLayoutWidth = preferredMaxLayoutWidth
return self
}
}
|
// This file was generated from JSON Schema using quicktype, do not modify it directly.
// To parse the JSON, add this file to your project and do:
//
// let webThreeData = try? newJSONDecoder().decode(WebThreeData.self, from: jsonData)
import Foundation
// This file was generated from JSON Schema using quicktype, do not modify it directly.
// To parse the JSON, add this file to your project and do:
//
// let webThreeData = try? newJSONDecoder().decode(WebThreeData.self, from: jsonData)
import Foundation
// MARK: - WebThreeData
struct WebThreeData: Codable {
let latestAvgBlockTime: Double
let latestDifficulty, latestBlockNumber: Int
let lastBlockAt: String
let difficultyHistory: [DifficultyHistory]
let blockTimeHistory: [BlockHistory]
var networkHashRate: Int {
get{
return Int(Double(latestDifficulty) / latestAvgBlockTime)
}
}
}
// MARK: - Block History
struct BlockHistory: Codable {
// let avgBlockTime: String;
let blockNumber: Int;
let blockTime: Int;
let time: String;
}
// MARK: - Difficulty History
struct DifficultyHistory: Codable {
let difficulty: Double;
let time: String;
}
extension WebThreeData {
init? (dictionary: [String: Any]) throws {
self = try JSONDecoder().decode(WebThreeData.self, from: JSONSerialization.data(withJSONObject: dictionary))
}
}
extension Double{
func abbreviateNumber()-> String {
let SI_SYMBOL = ["", "k", "M", "G", "T", "P", "E"];
// what tier? (determines SI symbol)
let tier = (Int(log10(abs(self))) / 3) | 0;
// if zero, we don't need a suffix
if (tier == 0) {
return String(self)
}
// get suffix and determine scale
let suffix = SI_SYMBOL[tier];
let scale = pow(10, tier * 3);
// scale the number
let scaled = self / Double(truncating: scale as NSNumber);
// format number and add suffix
return "\(scaled)\(suffix)"
}
}
|
//
// FilmLocation.swift
// FamilyHouse
//
// Created by Marie Park on 10/10/16.
// Copyright © 2016 Flatiron School. All rights reserved.
//
import UIKit
struct FilmLocation {
let name: String
let address: String
var tvSeries: TVSeries
}
|
//
// PlayerRow.swift
// SwiftUITest
//
// Created by Borja Saez de Guinoa Vilaplana on 26/06/2019.
// Copyright © 2019 Borja Saez de Guinoa Vilaplana. All rights reserved.
//
import SwiftUI
struct PlayerRow : View {
var player: Player
var body: some View {
HStack {
Image(player.imageName).resizable()
.scaledToFit()
.clipShape(Circle())
.frame(width: 50.0, height: 50.0)
.background(Circle())
.foregroundColor(player.team.color)
Text(player.name).font(.largeTitle)
.bold()
.minimumScaleFactor(0.5)
Spacer()
}
}
}
#if DEBUG
struct PlayerRow_Previews : PreviewProvider {
static var previews: some View {
PlayerRow(player: players[2]).previewLayout(.sizeThatFits)
}
}
#endif
|
//
// Request.swift
// CatFacts
//
// Created by Serhii PERKHUN on 1/8/19.
// Copyright © 2019 Serhii PERKHUN. All rights reserved.
//
import Foundation
import Alamofire
struct Request {
let url = "https://cat-fact.herokuapp.com/facts"
func getFacts(completion: @escaping ((Result<CatFacts>) -> Void)) {
request(url).validate().responseData { response in
switch response.result {
case .success:
if let value = response.result.value {
var result: CatFacts?
do {
result = try JSONDecoder().decode(CatFacts.self, from: value)
}
catch let error {
completion(.failure(error))
}
completion(.success(result!))
}
case .failure(let error):
completion(.failure(error))
}
}
}
}
|
//
// Created by Daniel Heredia on 2/27/18.
// Copyright © 2018 Daniel Heredia. All rights reserved.
//
// Chat Server
import Foundation
class Message {
let id: Int
let content: String
let date: Date
init(content: String) {
self.id = 1 // aleatory selection of id insuring unicity
self.content = content
self.date = Date()
}
}
class Conversation {
private(set) var participants: [User]
private(set) var messages: [Message]
let id: Int
init(id: Int) {
self.id = id
participants = [User]()
messages = [Message]()
}
func addMessage(message: Message) -> Bool {
// Add a message to the conversation
return false
}
}
class GroupChat: Conversation {
func addParticipant(_ participant: User) {
// Adds a participant
}
func removeParticipant(_ participant: User) {
// Removes a participant
}
}
class PrivateChat: Conversation {
init(user1: User, user2: User) {
let id = 1 // aleatory selection of id insuring unicity
super.init(id: id)
}
func getTheOtherParticipant(_ user: User) -> User {
// get the other participant of the conversation
return User(id: 1, accountName: "Example") // It's just a placeholder user
}
}
enum UserStatusType {
case offline
case idle
case away
case available
case busy
}
struct UserStatus {
var description: String
var type: UserStatusType
init(type: UserStatusType, description: String) {
self.type = type
self.description = description
}
}
class User {
let id: Int
let accountName: String
private(set) var status: UserStatus
private(set) var privateChats: [Int: PrivateChat]
private(set) var groupChats: [Int: GroupChat]
init(id: Int, accountName: String) {
self.id = id
self.accountName = accountName
self.status = UserStatus(type: .available, description: "Default")
self.privateChats = [Int: PrivateChat]()
self.groupChats = [Int: GroupChat]()
}
func sendMessage(toUserId id: Int, message: String) {}
func sendMessage(toGroupId id: Int, message: String) {}
func addContact(_ user: User) {}
func receivedAddRequest(_ addRequest: AddRequest) {}
func sendAddRequest(_ addRequest: AddRequest) {}
func removeAddrequest(_ addRequest: AddRequest) {}
func requestAddUser(userId: Int) {}
func addConversation(privateChat: PrivateChat) {}
func addConversation(groupChat: GroupChat) {}
}
enum AddRequestStatus {
case Unread
case Read
case Accepted
case Rejected
}
struct AddRequest {
let fromUser: User
let toUser: User
let date: Date
var status: AddRequestStatus
init(fromUser: User, toUser: User, date: Date, status: AddRequestStatus) {
self.fromUser = fromUser
self.toUser = toUser
self.date = date
self.status = status
}
}
class UserManager {
let userManager: UserManager = {
return UserManager()
}()
private var usersById: [Int: User]
private var usersByAccount: [String: User]
private var onlineUsers: [Int: User]
private init() {
self.usersById = [Int: User]()
self.usersByAccount = [String: User]()
self.onlineUsers = [Int: User]()
}
func addUser(fromUser: User, accountName: String) {
// Adds a new user
}
func approveAddRequest(_ request: AddRequest) {
// The add request was accepted
}
func rejectAddRequest(_ request: AddRequest) {
// The add request was rejected
}
func userSignedOn(_ id: Int) {
// The user signed on
}
func userSignedOff(_ id: Int) {
// The userd signed off
}
}
|
//
// ViewController.swift
// ClassCreator
//
// Created by Scott Mehus on 8/27/19.
// Copyright © 2019 Scott Mehus. All rights reserved.
//
import UIKit
import CoreData
@objc protocol Mamal {
var name: String! { get set }
var species: String! { get set }
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
ivars()
properties()
}
}
extension ViewController {
private func properties() {
let creator: FlyweightCreator<Person> = FlyweightCreator(className: "PersonFlyweight", inspectionType: .property)
let flyweight = creator.generate()
flyweight.firstName = "Scott"
flyweight.lastName = "Mehus"
print("firstName: \(flyweight.firstName!) lastName: \(flyweight.lastName!)")
}
}
class Dog: Mamal {
var name: String!
var species: String!
}
extension ViewController {
private func ivars() {
let creator: FlyweightCreator<Dog> = FlyweightCreator(className: "DogFlyweight", inspectionType: .ivar)
let flyweight = creator.generate()
flyweight.name = "Ginger"
flyweight.species = "Poodle"
print("name \(flyweight.name!) species: \(flyweight.species!)")
}
}
struct FlyweightCreator<T: AnyObject> {
enum ClassInspectionType {
case ivar
case property
}
private let inspectionType: ClassInspectionType
private let className: String
init(className: String, inspectionType: ClassInspectionType) {
self.className = className
self.inspectionType = inspectionType
}
func generate() -> Flyweight {
var count: UInt32 = 0
let allocatedClass: AnyClass = objc_allocateClassPair(Flyweight.classForCoder(), className, 0)!
let ivars = inspectionType == .ivar ? class_copyIvarList(T.self, &count)! : class_copyPropertyList(T.self, &count)
for ivar in UnsafeBufferPointer(start: ivars, count: Int(count)) {
let namePointer = inspectionType == .ivar ? ivar_getName(ivar)! : property_getName(ivar)
let name = String(cString: namePointer)
print("name: \(name)")
let encoding = "@"
var size = 0
var alignment = 0
NSGetSizeAndAlignment(encoding, &size, &alignment)
class_addIvar(allocatedClass, name, size, UInt8(alignment), encoding)
}
free(ivars)
// class_addProtocol(allocatedClass, Mamal.self)
objc_registerClassPair(allocatedClass)
return allocatedClass.alloc() as! Flyweight
}
}
@dynamicMemberLookup class Flyweight: NSObject {
subscript(dynamicMember member: String) -> String? {
get {
return value(forKey: member) as? String
}
set {
setValue(newValue, forKey: member)
}
}
}
|
//
// LetterCreator.swift
// WordyYosha
//
// Created by Jacob O'Donnell on 6/12/14.
// Copyright (c) 2014 Jacob O'Donnell. All rights reserved.
//
import Foundation
import SpriteKit
var id = 0
let boxWidth = 36
let boxHeight = 39
let boxWidthWithPadding = boxWidth + 1
let padding = 30
class LetterCreator {
class func create(point: Point) -> BoardLetter {
let label = self.createLetterSprite(self.randomLetter(), fontSize: 20, point: CGPoint(x: 0, y: -15))
let box = self.createBox(SKColor.greenColor(), point: point, label: label)
let boardLetter = BoardLetter(sprite: box, id: self.newId(), point: point)
let myLabel = self.createLetterSprite(String(boardLetter.points()), fontSize: 12, point: CGPoint(x: 10, y: 8))
box.addChild(myLabel)
return boardLetter
}
class func createWithLetter(point: Point, letter: String) -> BoardLetter {
let label = self.createLetterSprite(letter, fontSize: 20, point: CGPoint(x: 0, y: -15))
let box = self.createBox(SKColor.greenColor(), point: point, label: label)
return BoardLetter(sprite: box, id: self.newId(), point: point)
}
class func createWordString(point: Point, letter: Letter) -> Letter {
let label = self.createLetterSprite(letter.letter, fontSize: 37, point: CGPoint(x: 0, y: -15))
let box = self.createBox(SKColor.yellowColor(), point: point, label: label)
return Letter(sprite: box, id: letter.id)
}
class func createBox(color: SKColor, point: Point, label: SKLabelNode) -> SKSpriteNode {
let box = SKSpriteNode(color: color, size: self.boxSize())
box.position = CGPoint(x: point.x * boxWidthWithPadding + padding, y: point.y * (boxWidthWithPadding + 3) + padding)
box.addChild(label)
return box
}
class func createLetterSprite(letter: String, fontSize: Int, point: CGPoint) -> SKLabelNode {
let myLabel = SKLabelNode(fontNamed:"Al Nile")
myLabel.text = letter
myLabel.fontSize = CGFloat(fontSize)
myLabel.fontColor = SKColor.blackColor()
myLabel.position = point
return myLabel
}
class func boxSize() -> CGSize {
return CGSizeMake(CGFloat(boxWidth), CGFloat(boxHeight))
}
class func newId() -> Int {
id++
return id
}
class func randomLetter() -> String {
let cower = arc4random() % 100000
if cower < 8167 { return "A" }
if cower < 9659 { return "B" }
if cower < 12441 { return "C" }
if cower < 16694 { return "D" }
if cower < 29694 { return "E" }
if cower < 31922 { return "F" }
if cower < 33937 { return "G" }
if cower < 40031 { return "H" }
if cower < 46997 { return "I" }
if cower < 47150 { return "J" }
if cower < 47922 { return "K" }
if cower < 51947 { return "L" }
if cower < 54353 { return "M" }
if cower < 61102 { return "N" }
if cower < 68609 { return "O" }
if cower < 70538 { return "P" }
if cower < 70633 { return "Q" }
if cower < 76620 { return "R" }
if cower < 82947 { return "S" }
if cower < 92003 { return "T" }
if cower < 94761 { return "U" }
if cower < 95739 { return "V" }
if cower < 98099 { return "W" }
if cower < 98249 { return "X" }
if cower < 99930 { return "Y" }
return "Z"
}
}
|
//
// MarketPulseWidgetSettingsRepositoryProtocol.swift
// DomainLayer
//
// Created by Pavel Gubin on 29.07.2019.
// Copyright © 2019 Waves Platform. All rights reserved.
//
import Foundation
import RxSwift
public protocol MarketPulseWidgetSettingsRepositoryProtocol {
func settings() -> Observable<DomainLayer.DTO.MarketPulseSettings>
}
|
//
// NoteViewController.swift
// Notes
//
// Created by nimik on 05/08/2018.
// Copyright © 2018 nimik. All rights reserved.
//
import UIKit
class NoteViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var deleteBtn: UIBarButtonItem!
@IBOutlet weak var saveBtn: UIBarButtonItem!
@IBOutlet weak var textView: UITextView!
var noteId = Int()
var lastId = Int()
var itemsCount = [NoteModel]()
var item: NoteModel?
var fromAllNotes = false
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
saveBtn.title = "saveBtn".localized
navigationItem.largeTitleDisplayMode = .never
self.view.backgroundColor = UIColor.white
NetworkLayer.shared.getAllNotes { (item, error) in
if let count = item {
for i in 0 ..< count.count{
self.lastId = count[i].id
}
}
}
if fromAllNotes{
NetworkLayer.shared.getNote(id: noteId) { (note) in
self.textView.text = note?.title
}
}
else{
textView.becomeFirstResponder()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func doneBtnAction(_ sender: UIBarButtonItem) {
if fromAllNotes == false{
NetworkLayer.shared.postNote(note: NoteModel(id: lastId + 1, title: textView.text)) { (noteResponse, error) in
self.textView.text = noteResponse?.title
self.textView.resignFirstResponder()
}
}
else if fromAllNotes == true{
NetworkLayer.shared.putNote(note: NoteModel(id: noteId, title: textView.text), completion: { (noteResponse, error) in
self.textView.text = noteResponse?.title
self.textView.resignFirstResponder()
print(noteResponse?.title ?? "")
})
}
}
}
|
// @copyright German Autolabs Assignment
import Foundation
final class TranscriptionParserImpl: TranscriptionParser {
func parse(transcription: String) -> VoiceCommand? {
if transcription.lowercased().contains("weather") {
// TODO: parse city and date if any
return .weather(city: nil, date: nil)
}
return nil
}
}
|
//
// BaseTableViewHeaderFooterView.swift
// ComicSwift
//
// Created by 曹来东 on 2020/7/6.
// Copyright © 2020 曹来东. All rights reserved.
//
import UIKit
class BaseTableViewHeaderFooterView: UITableViewHeaderFooterView {
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
configUI()
}
func configUI() { }
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
import Vapor
import Foundation
import MongoKitten
import BSON
// MARK: Mongo
// Get real password, change database, and use heroku config variable https://devcenter.heroku.com/articles/mongolab
let mongoUrl = "mongodb://test-user:test-password@ds015859.mlab.com"
let collection: MongoKitten.Collection?
let errorMessage: String?
do {
let server = try MongoKitten.Server(at: "ds015859.mlab.com", port: 15859, using: (username: "test-user", password: "test-password"))
try server.connect()
collection = server["heroku_fdl1swgg"]["hello-names"]
errorMessage = ""
} catch {
collection = nil
print(error)
errorMessage = "ERROR: \(error)"
}
print("Err: \(errorMessage)")
print("")
// Create:
//try collection.insert(["username": "henk", "age": 245])
//
//// Read:
//try collection.find("username" == "henk") // Cursor<Document>
//try collection.findOne("username" == "henk") // Document?
//
//// Update:
//try collection.update("username" == "henk", ["$set": ["username": "fred"]], flags: [.Upsert])
//
//// Delete:
//try collection.remove("age" > 24)
// MARK: Vapor
typealias Byte = UInt8
extension NSData {
internal func arrayOfBytes() -> [Byte] {
let count = self.length / sizeof(Byte)
var bytesArray = [Byte](repeating: 0, count: count)
self.getBytes(&bytesArray, length:count * sizeof(Byte))
return bytesArray
}
}
public enum Error: ErrorProtocol {
case Failure
}
let up = Error.Failure
extension Swift.Collection where Iterator.Element == UInt8 {
public func toString() throws -> String {
var utf = UTF8()
#if swift(>=3.0)
var gen = self.makeIterator()
#else
var gen = self.generate()
#endif
var str = String()
#if swift(>=3.0)
while true {
switch utf.decode(&gen) {
case .emptyInput: //we're done
return str
case .error: //error, can't describe what however
throw up
// throw Error.ParseStringFromCharsFailed(Array(self))
case .scalarValue(let unicodeScalar):
str.append(unicodeScalar)
}
}
#else
while true {
switch utf.decode(&gen) {
case .EmptyInput: //we're done
return str
case .Error: //error, can't describe what however
throw Error.ParseStringFromCharsFailed(Array(self))
case .Result(let unicodeScalar):
str.append(unicodeScalar)
}
}
#endif
}
}
// MARK: Application
let app = Application()
public func loadResource(name: String) -> NSData? {
let path = app.workDir + "Resources" + "/\(name.uppercased()).xml"
return NSData(contentsOfFile: path)
}
//
app.get("query", String.self) { req, name in
let cursor = try collection?.query(matching: "name" == name)
let doc: Document! = nil
if let person = cursor?.makeIterator().next()?["name"] {
print("Name: \(person)")
let data = person.bsonData
let d = NSData(bytes: data, length: data.count)
let s = String(data: d, encoding: NSUTF8StringEncoding) ?? "OH NO"
return Response(status: .OK, data: "You found: \(s)".utf8, contentType: .Html)
} else {
let _ = try collection?.insert(["name" : name])
return Response(status: .OK, text: "Machine Broke: \(errorMessage)")
}
}
app.get("ota/:product-id") { request in
guard let name = request.parameters["product-id"], let resource = loadResource(name) else {
throw up
}
return Response(status: .OK, data: resource.arrayOfBytes(), contentType: .Other("application/xml"))
}
app.get("test") { req in
return "Test Successful"
}
app.get("json") { req in
return Json([
"dict" : [
"name" : "Vapor",
"lang" : "Swift"
],
"number" : 123,
"array" : [
0,
1,
2,
3
],
"string" : "test"
])
}
extension String {
init?(bytes: [UInt8]) {
let signedData = bytes.map { byte in
return Int8(byte)
}
guard let string = String(validatingUTF8: signedData) else {
return nil
}
self = string
}
}
func insertIfNecessary(name: String) throws {
if let _ = try collection?.queryOne(matching: "name" == name)?["name"] {
} else {
let _ = try collection?.insert(["name" : name])
}
}
func allPeople() throws -> [String] {
let cursor = try collection?.query().makeIterator()
var people: [String] = []
while let data = cursor?.next()?["name"]?.bsonData {
// let d = NSData(bytes: data, length: data.count)
// let s = NSString(data: d, encoding: NSUTF8StringEncoding) ?? "OH NO"
// let s = try data.string()
people.append(try data.toString())
}
return people
}
app.get("hello") { req in
let peeps = try allPeople().map { Json($0) }
return Json.array(peeps)
}
app.get("hello", String.self) { req, name in
let br = "<br>"
var message = "Hello, \(name)!\(br)\(br)"
let people = try allPeople()
var peopleMsg = "I've also said hello to:\(br)\(br)"
peopleMsg += people
.map { name -> String in return "\t\(name),\(br)" }
.reduce("", combine: +)
print("Will insert")
try insertIfNecessary(name)
print("Did Insert")
let html = "<p>" + message + peopleMsg + "</p>"
return Response.init(status: .OK, html: html)
}
app.start(port: 9090)
|
//
// Gameplay.swift
// OtherSpriteKitGame
//
// Created by Juan Morillo on 11/12/17.
// Copyright © 2017 Juan Morillo. All rights reserved.
//
import SpriteKit
class Gameplay: SKScene {
override func didMove(to view: SKView) {
print("Dentro del Gameplay")
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
if touch == touches.first {
print("Ir a la Scena Menu")
OSGManager.shared.transition(self, toScene: .MainMenu, transition: SKTransition.moveIn(with: .right, duration: 0.5))
}
}
}
}
|
//
// MapViewController.swift
// WeatherForecast
//
// Created by Shivani Dosajh on 06/08/17.
// Copyright © 2017 Shivani Dosajh. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class MapViewController: UIViewController , MKMapViewDelegate , CLLocationManagerDelegate{
// To get the pin for location
private var pointAnnotation:MKPointAnnotation!
private var pinAnnotationView:MKPinAnnotationView!
// URL string for calling the API
private var requestString :String? = ""
// To get the user's current location
let locationManager = CLLocationManager()
var initialLocation : CLLocation!
var flag = true
// MARK: view life cyle methods
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
self.mapView.delegate = self
// Ask for Authorisation from the User.
self.locationManager.requestAlwaysAuthorization()
// For use in foreground
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.distanceFilter = 3000
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
configureInitialPinLocation()
initializeAPIData()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
initialLocation = CLLocation(latitude: manager.location!.coordinate.latitude, longitude: manager.location!.coordinate.longitude)
configureInitialPinLocation()
fetchPinLocation(cordinate: manager.location!.coordinate)
print("locations = \(initialLocation.coordinate.latitude) \(initialLocation.coordinate.longitude)")
}
// MARK: Initialization Functions
func configureInitialPinLocation()
{
if initialLocation == nil{
initialLocation = CLLocation(latitude: 28.7 , longitude: 77.1025)
}
if self.mapView.annotations.count > 0{
self.mapView.removeAnnotation(self.pinAnnotationView.annotation!)
}
// setting up location pin and visible map region
self.pointAnnotation = MKPointAnnotation()
let regionRadius: CLLocationDistance = 3000
self.pointAnnotation.coordinate = initialLocation.coordinate
self.pinAnnotationView = MKPinAnnotationView(annotation: self.pointAnnotation, reuseIdentifier: nil)
let coordinateRegion = MKCoordinateRegionMakeWithDistance(initialLocation.coordinate,regionRadius, regionRadius)
mapView.setRegion(coordinateRegion, animated: true)
self.mapView.addAnnotation(self.pinAnnotationView.annotation!)
self.pointAnnotation.title = "Location"
self.pointAnnotation.subtitle = "(\(self.pointAnnotation.coordinate.latitude), \(self.pointAnnotation.coordinate.longitude))"
}
func initializeAPIData()
{
if (requestString?.isEmpty )!
{
let request = URLObject(latitude: self.pointAnnotation.coordinate.latitude , longitude: self.pointAnnotation.coordinate.longitude)
self.requestString = request.getURLString()!
}
WeatherDataModel.sharedInstance.setWeatherData(urlString: requestString!)
}
// MARK: Map View Delegate Methods
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
switch newState {
case .starting:
view.dragState = .dragging
case .ending, .canceling:
view.dragState = .none
default: break
}
// Set up after drag ends
if(view.dragState == .none)
{
fetchPinLocation(cordinate: (view.annotation?.coordinate)!)
self.pointAnnotation.title = "Location"
self.pointAnnotation.subtitle = "(\(self.pointAnnotation.coordinate.latitude), \(self.pointAnnotation.coordinate.longitude))"
}
}
func mapView(_ mapView: MKMapView,
viewFor annotation: MKAnnotation) -> MKAnnotationView?{
self.pinAnnotationView.isDraggable = true
self.pinAnnotationView.canShowCallout = true
return self.pinAnnotationView
}
//MARK:- Fetching Location
/* To retrieve the current location after any change
*/
func fetchPinLocation(cordinate:CLLocationCoordinate2D){
let request = URLObject(latitude: cordinate.latitude , longitude: cordinate.longitude)
requestString = request.getURLString()
WeatherDataModel.sharedInstance.setWeatherData(urlString: requestString!)
// print(requestString ?? "fetch request")
}
}
|
//
// Folder.swift
// IsisCalendar
//
// Created by jorge Sanmartin on 9/9/15.
// Copyright (c) 2015 isis. All rights reserved.
//
import Foundation
class EventFolder{
var name:NSString!
var items:NSArray!
static func parseFolder(item:NSDictionary) -> EventFolder{
let folder = EventFolder()
folder.name = item["name"] as! String
if let items = item["items"] as? NSArray{
let folderItems = NSMutableArray.new()
for item in items{
let folderItem = EventFolderItem.parseItem(item as! NSDictionary)
folderItems.addObject(folderItem)
}
var sortedArray = folderItems.sortedArrayUsingComparator {
(obj1, obj2) -> NSComparisonResult in
let p1 = obj1 as! EventFolderItem
let p2 = obj2 as! EventFolderItem
let result = p1.startDate.compare(p2.startDate)
return result
}
folder.items = sortedArray
}
return folder
}
} |
func strStr(_ haystack: String, _ needle: String) -> Int {
if haystack == needle || needle.count == 0 {
return 0
}
if haystack.count < needle.count{
return -1
}
var a: String = haystack
for i in 0...(a.count - needle.count) {
if a.hasPrefix(needle) {
return i
}
a.remove(at: a.startIndex)
}
return -1
}
print(strStr("mississippi", "issip"))
|
//
// ThirdViewController.swift
// No Storyboards Exercise
//
// Created by Sean Perez on 4/24/16.
// Copyright © 2016 Awsome. All rights reserved.
//
import UIKit
class ThirdViewController: UIViewController {
var secondVC: SecondViewController!
var firstVC: FirstViewController!
@IBAction func secondViewController(sender: AnyObject) {
secondVC = SecondViewController(printMe: "Fuck My Neighbor")
self.presentViewController(secondVC, animated: true, completion: nil)
}
@IBAction func loadFirstViewController(sender: AnyObject) {
firstVC = FirstViewController(printMe: "We are coming from the Third View!")
self.presentViewController(firstVC, animated: true, completion: nil)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
import XCTest
import Bow
import BowGeneric
class GenericTest : XCTestCase {
}
|
import XCTest
#if GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
#if SWIFT_PACKAGE
import CSQLite
#else
import SQLite3
#endif
import GRDB
#endif
private struct Parent: TableRecord, FetchableRecord, Decodable, Equatable {
static let children = hasMany(Child.self)
var id: Int64
var name: String
}
private struct Child: TableRecord, FetchableRecord, Decodable, Equatable {
var id: Int64
var parentId: Int64
var name: String
}
private struct ParentInfo: FetchableRecord, Decodable, Equatable {
var parent: Parent
var children: [Child]
}
class ValueObservationQueryInterfaceRequestTests: GRDBTestCase {
override func setup(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { db in
try db.create(table: "parent") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent", onDelete: .cascade)
t.column("name", .text)
}
try db.execute(sql: """
INSERT INTO parent (id, name) VALUES (1, 'foo');
INSERT INTO parent (id, name) VALUES (2, 'bar');
INSERT INTO child (id, parentId, name) VALUES (1, 1, 'fooA');
INSERT INTO child (id, parentId, name) VALUES (2, 1, 'fooB');
INSERT INTO child (id, parentId, name) VALUES (3, 2, 'barA');
""")
}
}
func testOneRowWithPrefetchedRowsDeprecated() throws {
let dbQueue = try makeDatabaseQueue()
var results: [Row?] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
let request = Parent
.including(all: Parent.children.orderByPrimaryKey())
.orderByPrimaryKey()
.asRequest(of: Row.self)
let observation = ValueObservation.trackingOne(request)
let observer = try observation.start(in: dbQueue) { row in
results.append(row)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "DELETE FROM child")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results.count, 2)
XCTAssertEqual(results[0]!.unscoped, ["id": 1, "name": "foo"])
XCTAssertEqual(results[0]!.prefetchedRows["children"], [
["id": 1, "parentId": 1, "name": "fooA", "grdb_parentId": 1],
["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]])
XCTAssertEqual(results[1]!.unscoped, ["id": 1, "name": "foo"])
XCTAssertEqual(results[1]!.prefetchedRows["children"], [])
}
}
func testOneRowWithPrefetchedRows() throws {
let dbQueue = try makeDatabaseQueue()
var results: [Row?] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
let request = Parent
.including(all: Parent.children.orderByPrimaryKey())
.orderByPrimaryKey()
.asRequest(of: Row.self)
let observation = request.observationForFirst()
let observer = try observation.start(in: dbQueue) { row in
results.append(row)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "DELETE FROM child")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results.count, 2)
XCTAssertEqual(results[0]!.unscoped, ["id": 1, "name": "foo"])
XCTAssertEqual(results[0]!.prefetchedRows["children"], [
["id": 1, "parentId": 1, "name": "fooA", "grdb_parentId": 1],
["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]])
XCTAssertEqual(results[1]!.unscoped, ["id": 1, "name": "foo"])
XCTAssertEqual(results[1]!.prefetchedRows["children"], [])
}
}
func testAllRowsWithPrefetchedRowsDeprecated() throws {
let dbQueue = try makeDatabaseQueue()
var results: [[Row]] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
let request = Parent
.including(all: Parent.children.orderByPrimaryKey())
.orderByPrimaryKey()
.asRequest(of: Row.self)
let observation = ValueObservation.trackingAll(request)
let observer = try observation.start(in: dbQueue) { rows in
results.append(rows)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "DELETE FROM child")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results.count, 2)
XCTAssertEqual(results[0].count, 2)
XCTAssertEqual(results[0][0].unscoped, ["id": 1, "name": "foo"])
XCTAssertEqual(results[0][0].prefetchedRows["children"], [
["id": 1, "parentId": 1, "name": "fooA", "grdb_parentId": 1],
["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]])
XCTAssertEqual(results[0][1].unscoped, ["id": 2, "name": "bar"])
XCTAssertEqual(results[0][1].prefetchedRows["children"], [
["id": 3, "parentId": 2, "name": "barA", "grdb_parentId": 2]])
XCTAssertEqual(results[1].count, 2)
XCTAssertEqual(results[1][0].unscoped, ["id": 1, "name": "foo"])
XCTAssertEqual(results[1][0].prefetchedRows["children"], [])
XCTAssertEqual(results[1][1].unscoped, ["id": 2, "name": "bar"])
XCTAssertEqual(results[1][1].prefetchedRows["children"], [])
}
}
func testAllRowsWithPrefetchedRows() throws {
let dbQueue = try makeDatabaseQueue()
var results: [[Row]] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
let request = Parent
.including(all: Parent.children.orderByPrimaryKey())
.orderByPrimaryKey()
.asRequest(of: Row.self)
let observation = request.observationForAll()
let observer = try observation.start(in: dbQueue) { rows in
results.append(rows)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "DELETE FROM child")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results.count, 2)
XCTAssertEqual(results[0].count, 2)
XCTAssertEqual(results[0][0].unscoped, ["id": 1, "name": "foo"])
XCTAssertEqual(results[0][0].prefetchedRows["children"], [
["id": 1, "parentId": 1, "name": "fooA", "grdb_parentId": 1],
["id": 2, "parentId": 1, "name": "fooB", "grdb_parentId": 1]])
XCTAssertEqual(results[0][1].unscoped, ["id": 2, "name": "bar"])
XCTAssertEqual(results[0][1].prefetchedRows["children"], [
["id": 3, "parentId": 2, "name": "barA", "grdb_parentId": 2]])
XCTAssertEqual(results[1].count, 2)
XCTAssertEqual(results[1][0].unscoped, ["id": 1, "name": "foo"])
XCTAssertEqual(results[1][0].prefetchedRows["children"], [])
XCTAssertEqual(results[1][1].unscoped, ["id": 2, "name": "bar"])
XCTAssertEqual(results[1][1].prefetchedRows["children"], [])
}
}
func testOneRecordWithPrefetchedRowsDeprecated() throws {
let dbQueue = try makeDatabaseQueue()
var results: [ParentInfo?] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
let request = Parent
.including(all: Parent.children.orderByPrimaryKey())
.orderByPrimaryKey()
.asRequest(of: ParentInfo.self)
let observation = ValueObservation.trackingOne(request)
let observer = try observation.start(in: dbQueue) { parentInfo in
results.append(parentInfo)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "DELETE FROM child")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results, [
ParentInfo(
parent: Parent(id: 1, name: "foo"),
children: [
Child(id: 1, parentId: 1, name: "fooA"),
Child(id: 2, parentId: 1, name: "fooB"),
]),
ParentInfo(
parent: Parent(id: 1, name: "foo"),
children: []),
])
}
}
func testOneRecordWithPrefetchedRows() throws {
let dbQueue = try makeDatabaseQueue()
var results: [ParentInfo?] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
let request = Parent
.including(all: Parent.children.orderByPrimaryKey())
.orderByPrimaryKey()
.asRequest(of: ParentInfo.self)
let observation = request.observationForFirst()
let observer = try observation.start(in: dbQueue) { parentInfo in
results.append(parentInfo)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "DELETE FROM child")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results, [
ParentInfo(
parent: Parent(id: 1, name: "foo"),
children: [
Child(id: 1, parentId: 1, name: "fooA"),
Child(id: 2, parentId: 1, name: "fooB"),
]),
ParentInfo(
parent: Parent(id: 1, name: "foo"),
children: []),
])
}
}
func testAllRecordsWithPrefetchedRowsDeprecated() throws {
let dbQueue = try makeDatabaseQueue()
var results: [[ParentInfo]] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
let request = Parent
.including(all: Parent.children.orderByPrimaryKey())
.orderByPrimaryKey()
.asRequest(of: ParentInfo.self)
let observation = ValueObservation.trackingAll(request)
let observer = try observation.start(in: dbQueue) { parentInfos in
results.append(parentInfos)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "DELETE FROM child")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results, [
[
ParentInfo(
parent: Parent(id: 1, name: "foo"),
children: [
Child(id: 1, parentId: 1, name: "fooA"),
Child(id: 2, parentId: 1, name: "fooB"),
]),
ParentInfo(
parent: Parent(id: 2, name: "bar"),
children: [
Child(id: 3, parentId: 2, name: "barA"),
]),
],
[
ParentInfo(
parent: Parent(id: 1, name: "foo"),
children: []),
ParentInfo(
parent: Parent(id: 2, name: "bar"),
children: []),
],
])
}
}
func testAllRecordsWithPrefetchedRows() throws {
let dbQueue = try makeDatabaseQueue()
var results: [[ParentInfo]] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
let request = Parent
.including(all: Parent.children.orderByPrimaryKey())
.orderByPrimaryKey()
.asRequest(of: ParentInfo.self)
let observation = request.observationForAll()
let observer = try observation.start(in: dbQueue) { parentInfos in
results.append(parentInfos)
notificationExpectation.fulfill()
}
try withExtendedLifetime(observer) {
try dbQueue.inDatabase { db in
try db.execute(sql: "DELETE FROM child")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(results, [
[
ParentInfo(
parent: Parent(id: 1, name: "foo"),
children: [
Child(id: 1, parentId: 1, name: "fooA"),
Child(id: 2, parentId: 1, name: "fooB"),
]),
ParentInfo(
parent: Parent(id: 2, name: "bar"),
children: [
Child(id: 3, parentId: 2, name: "barA"),
]),
],
[
ParentInfo(
parent: Parent(id: 1, name: "foo"),
children: []),
ParentInfo(
parent: Parent(id: 2, name: "bar"),
children: []),
],
])
}
}
}
|
//
// Timer.swift
// UPomodoroTimer
//
// Created by sxexesx on 12/19/16.
// Copyright © 2016 sxexesx. All rights reserved.
//
import Foundation
import UIKit
enum TimerStatus{
case work
case rest
case standBy
}
var timer = Timer()
class MyTimer{
var timerStatus: TimerStatus = .standBy
var timerLabel: UILabel!
var timerTypeLabel: UILabel!
// var seconds: Int = 59
var seconds: Int = 10
// var workMinutes: Int = 24
var workMinutes: Int = 4
// var restMinutes: Int = 4
var restMinutes: Int = 2
init(timerLabel: UILabel, timerTypeLabel: UILabel) {
self.timerLabel = timerLabel
self.timerTypeLabel = timerTypeLabel
}
func startTimer(){
timerStatus = .work
timer = Timer.scheduledTimer(timeInterval: 1,
target: self,
selector: #selector(startMainTimer),
userInfo: nil,
repeats: true)
}
func startRestTimer(){
timerStatus = .rest
setUpRestMessage()
}
func stopTimer(){
timerStatus = .standBy
timer.invalidate()
setUpStandByMessage()
print("Таймер остановлен")
}
@objc func startMainTimer() {
var min: Int = 0
switch timerStatus {
case .work:
min = workMinutes
case .rest:
min = restMinutes
case .standBy:
print("StandBy")
}
if (seconds > 0) {
seconds = seconds - 1
displayTime(timeToDisplay: prepareTimeForDisplay(minutes: min, seconds: seconds))
}
else{
// seconds = 60
seconds = 10
if (min > 0) {
min = min - 1
timerStatus == .work ? (workMinutes = min) : (restMinutes = min)
} else if (timerStatus == .rest && min == 0) {
print("Останавливаем таймер")
stopTimer()
} else {
print("Запускаем таймер отдыха")
startRestTimer()
}
}
}
func prepareTimeForDisplay(minutes: Int, seconds: Int) -> String{
let secondsToShow: String = seconds >= 10 ? String(seconds) : "0\(String(seconds))"
let minutesToShow: String = minutes >= 10 ? String(minutes) : "0\(String(minutes))"
return "\(minutesToShow) : \(secondsToShow)"
}
func displayTime(timeToDisplay: String){
timerLabel.text = timeToDisplay;
}
// var currentTime : Date {
// return Date.init(timeIntervalSinceNow: 40)
// }
func setUpWorkMessage(){
timerTypeLabel.isHidden = false
timerTypeLabel.text = "Время поработать"
}
func setUpRestMessage(){
timerTypeLabel.isHidden = false
timerTypeLabel.text = "Время отдохнуть"
}
func setUpStandByMessage(){
timerTypeLabel.isHidden = true
timerTypeLabel.text = "Станд Бай"
timerLabel.text = prepareTimeForDisplay(minutes: 25, seconds: 0)
}
}
|
//
// VideoCollectionViewController.swift
// kdb3
//
// Created by Benny Pollak on 4/23/23.
// Copyright © 2023 Alben Software. All rights reserved.
//
import Foundation
// VideoCollectionViewController.swift
import UIKit
import AVKit
import AVFoundation
import UIKit
import UniformTypeIdentifiers // For iOS 14 and later
class VideoCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate {
var playerStatusObserver: NSKeyValueObservation?
let videoURLs = [
"nothing", "talkingtoamachine", "alwayshaveparis", "buellerf", "handlethetruth"
, "cantdothat", "frankly", "tomorow", "biggerboat", "iwantmore", "richman", "notworthy"
]
override func viewDidLoad() {
super.viewDidLoad()
// Register cell class
// collectionView?.register(UINib(nibName: "VideoCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "VideoCell")
collectionView?.register(UICollectionViewCell.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "VideoCell")
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
longPressGesture.minimumPressDuration = 0.7
longPressGesture.allowableMovement = 30
self.collectionView.addGestureRecognizer(longPressGesture)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap))
tapGestureRecognizer.delegate = self
collectionView?.addGestureRecognizer(tapGestureRecognizer)
}
@objc func handleLongPress(gesture: UILongPressGestureRecognizer) {
let p = gesture.location(in: self.collectionView)
if let indexPath = self.collectionView.indexPathForItem(at: p) {
let videoURL = Bundle.main.url(forResource: videoURLs[indexPath.row], withExtension: "mp4")!
// copyVideoToClipboard(videoURL: videoURL)
shareVideo(videoURL: videoURL)
} else {
// print("couldn't find index path")
}
}
func shareVideo(videoURL: URL) {
let activityViewController = UIActivityViewController(activityItems: [videoURL], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
self.present(activityViewController, animated: true, completion: nil)
}
@objc func handleTap(gesture: UITapGestureRecognizer) {
let p = gesture.location(in: self.collectionView)
if let indexPath = self.collectionView.indexPathForItem(at: p) {
let cell:VideoCollectionViewCell = collectionView.cellForItem(at: indexPath) as! VideoCollectionViewCell
cell.player?.seek(to: .zero)
cell.player?.play()
// cell.addEndOfVideoObserver()
} else {
// print("couldn't find index path")
}
}
func copyVideoToClipboard(videoURL: URL) {
do {
// Read the video data from the URL
let videoData = try Data(contentsOf: videoURL)
#if canImport(UniformTypeIdentifiers)
let videoItem: [String: Any] = [
UTType.movie.identifier: videoData
]
#else
let videoItem: [String: Any] = [
kUTTypeMovie as String: videoData
]
#endif
// Set the clipboard items
UIPasteboard.general.setItems([videoItem])
} catch {
print("Error reading video data: \(error)")
}
}
// MARK: - UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return videoURLs.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "VideoCell", for: indexPath) as! VideoCollectionViewCell
let videoURL = Bundle.main.url(forResource: videoURLs[indexPath.row], withExtension: "mp4")!
// let videoURL = URL(string: videoURLs[indexPath.row])!
cell.player = AVPlayer(url: videoURL)
let playerLayer = AVPlayerLayer(player: cell.player)
playerLayer.frame = cell.videoView.bounds
playerLayer.videoGravity = .resizeAspect // Adjust the videoGravity as needed
// Remove any previous player layer from the videoView
cell.videoView.layer.sublayers?.forEach { $0.removeFromSuperlayer() }
// Add the player layer to the videoView
cell.videoView.layer.addSublayer(playerLayer)
return cell
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = 128 //view.frame.width / 3
// print("\(width) \(view.frame.width)")
return CGSize(width: width, height: width)
// return CGSize(width: view.frame.width, height: 128)
}
}
|
//
// AppDelegate.swift
// iOSDemo
//
// Created by Zhu Shengqi on 26/11/2017.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let mainWindow = UIWindow()
self.window = mainWindow
mainWindow.rootViewController = UINavigationController(rootViewController: RootViewController())
mainWindow.makeKeyAndVisible()
return true
}
}
|
//
// SecondViewController.swift
// CircularRevealAnimator
//
// Created by Kosuke Kito on 2015/06/23.
// Copyright (c) 2015年 Kosuke Kito. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController {
public var transitioner: Transitioner?
class func instantiate(point: CGPoint) -> SecondViewController {
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let viewController: SecondViewController = storyboard.instantiateViewController(withIdentifier: "Second") as! SecondViewController
viewController.transitioner = Transitioner(style: .Circular(point))
return viewController
}
override func viewDidLoad() {
super.viewDidLoad()
self.transitioningDelegate = self
}
}
extension SecondViewController {
@IBAction func buttonTapped(sender: UIButton) {
self.transitioner = Transitioner(style: .Circular(sender.center))
dismiss(animated: true, completion: nil)
}
}
extension SecondViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self.transitioner?.style.presentTransitioning
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self.transitioner?.style.dismissTransitioning
}
}
|
//
// ClassroomDetailViewController.swift
// homework
//
// Created by Liu, Naitian on 7/27/16.
// Copyright © 2016 naitianliu. All rights reserved.
//
import UIKit
import ZLSwipeableViewSwift
class ClassroomDetailViewController: UIViewController {
@IBOutlet weak var homeworkCountLabel: UILabel!
@IBOutlet weak var swipeView: ZLSwipeableView!
@IBOutlet weak var homeworkActionView: UIView!
var classroomUUID: String!
let homeworkViewModel = HomeworkViewModel()
let homeworkKeys = GlobalKeys.HomeworkKeys.self
let role = UserDefaultsHelper().getRole()!
var currentIndex = 0
var currentShiftIndex = 0
var numberOfLayoutCalls = 0
var cardDataArray = [[String: AnyObject]]()
var cardNumberOfActiveView: UInt = 1
override func viewDidLoad() {
super.viewDidLoad()
self.cardDataArray = self.homeworkViewModel.getCurrentHomeworksData(self.classroomUUID)
self.countHomeworkNumber()
numberOfLayoutCalls = 0
swipeView.didTap = {view, location in
// action when tap view
self.showHomeworkDetailVC()
}
swipeView.didEnd = {view, location in
// count
self.countHomeworkNumber()
}
APIHomeworkGetHomeworkList(vc: self).run(self.classroomUUID)
// self.reloadHomeworks()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.tabBar.hidden = true
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
dispatch_async(dispatch_get_main_queue()) {
self.numberOfLayoutCalls += 1
if self.numberOfLayoutCalls > 1 {
self.swipeView.numberOfActiveView = self.cardNumberOfActiveView
self.swipeView.nextView = {
return self.nextCardView()
}
}
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if self.role == "t" {
self.renderHomeworkActionView()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func resetNumberOfActiveViews() {
let cardNumber = UInt(self.cardDataArray.count)
let limit: UInt = 6
if cardNumber >= limit {
self.cardNumberOfActiveView = limit
} else {
self.cardNumberOfActiveView = cardNumber
}
}
func reloadHomeworks() {
dispatch_async(dispatch_get_main_queue()) {
self.cardDataArray = self.homeworkViewModel.getCurrentHomeworksData(self.classroomUUID)
self.resetNumberOfActiveViews()
self.swipeView.discardViews()
self.swipeView.numberOfActiveView = self.cardNumberOfActiveView
self.currentShiftIndex = 0
self.swipeView.loadViews()
self.currentIndex = 0
self.countHomeworkNumber()
}
}
private func countHomeworkNumber() {
if self.cardDataArray.count > 0 {
homeworkCountLabel.text = "当前作业 (\(currentIndex+1)/\(self.cardDataArray.count))"
} else {
homeworkCountLabel.text = "当前作业: 暂无"
}
}
func nextCardView() -> UIView? {
if self.cardDataArray.count > 0 {
let cardView = HomeworkCardView(frame: self.swipeView.bounds)
let contentView = NSBundle.mainBundle().loadNibNamed("HomeworkCardContentView", owner: self, options: nil)!.first! as! HomewordCardContentView
contentView.configurate(self.cardDataArray[currentShiftIndex])
currentShiftIndex += 1
currentIndex += 1
contentView.translatesAutoresizingMaskIntoConstraints = false
cardView.addSubview(contentView)
self.constrain(cardView, view2: contentView)
if currentShiftIndex >= cardDataArray.count {
currentShiftIndex = 0
}
if currentIndex >= cardDataArray.count {
currentIndex = 0
}
print(self.currentIndex)
return cardView
} else {
return nil
}
}
private func constrain(view1: UIView, view2: UIView) {
let metrics = ["width":view1.bounds.width, "height": view1.bounds.height]
let views = ["view2": view2, "view1": view1]
view1.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view2(width)]", options: .AlignAllLeft, metrics: metrics, views: views))
view1.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view2(height)]", options: .AlignAllLeft, metrics: metrics, views: views))
}
private func showHomeworkDetailVC() {
let rowDict = self.cardDataArray[currentIndex]
let homeworkUUID: String = rowDict[self.homeworkKeys.homeworkUUID]! as! String
if self.role == "t" {
let homeworkDetailVC = HomeworkDetailViewController(nibName: "HomeworkDetailViewController", bundle: nil)
homeworkDetailVC.homeworkUUID = homeworkUUID
homeworkDetailVC.didCloseHomeworkBlockSetter({
self.reloadHomeworks()
})
self.navigationController?.pushViewController(homeworkDetailVC, animated: true)
} else if self.role == "s" {
let studentHWDetailVC = StudentHomeworkDetailViewController(nibName: "StudentHomeworkDetailViewController", bundle: nil)
studentHWDetailVC.homeworkUUID = homeworkUUID
self.navigationController?.pushViewController(studentHWDetailVC, animated: true)
}
}
private func renderHomeworkActionView() {
let viewWidth = self.homeworkActionView.frame.width
let viewHeight = self.homeworkActionView.frame.height
let btnWidth: CGFloat = 150
let btnHeight: CGFloat = 30
let x: CGFloat = (viewWidth - btnWidth) / 2
let y: CGFloat = (viewHeight - btnHeight) / 2
let btnFrame = CGRect(x: x, y: y, width: btnWidth, height: btnHeight)
let button = UIButton(type: .System)
button.frame = btnFrame
button.setTitle("发布新的作业", forState: .Normal)
button.setTitleColor(GlobalConstants.themeColor, forState: .Normal)
button.layer.borderColor = GlobalConstants.themeColor.CGColor
button.layer.borderWidth = 1
button.layer.cornerRadius = 8
button.addTarget(self, action: #selector(self.newHomeworkButtonOnClick), forControlEvents: .TouchUpInside)
self.homeworkActionView.addSubview(button)
}
func newHomeworkButtonOnClick(sender: AnyObject!) {
PresentVCUtility(vc: self).showSelectHWTypeVC(self.classroomUUID, completion: {
self.reloadHomeworks()
})
}
@IBAction func moreInfoButtonOnClick(sender: AnyObject) {
let classroomInfoVC = ClassroomInfoViewController(nibName: "ClassroomInfoViewController", bundle: nil)
classroomInfoVC.classroomUUID = classroomUUID
self.navigationController?.pushViewController(classroomInfoVC, animated: true)
}
@IBAction func homeworkButtonOnClick(sender: AnyObject) {
/*
let homeworkListVC = HomeworkListViewController(nibName: "HomeworkListViewController", bundle: nil)
homeworkListVC.classroomUUID = classroomUUID
self.navigationController?.pushViewController(homeworkListVC, animated: true)
*/
let calendarHWVC = CalendarHWViewController(nibName: "CalendarHWViewController", bundle: nil)
calendarHWVC.classroomUUID = classroomUUID
self.navigationController?.pushViewController(calendarHWVC, animated: true)
}
@IBAction func teacherButtonOnClick(sender: AnyObject) {
self.showMemberListVC("t")
}
@IBAction func studentButtonOnClick(sender: AnyObject) {
self.showMemberListVC("s")
}
@IBAction func notificationButtonOnClick(sender: AnyObject) {
let notificationListVC = NotificationListViewController(nibName: "NotificationListViewController", bundle: nil)
self.navigationController?.pushViewController(notificationListVC, animated: true)
}
private func showMemberListVC(type: String) {
let memberListVC = MemberListViewController(nibName: "MemberListViewController", bundle: nil)
memberListVC.classroomUUID = classroomUUID
memberListVC.type = type
self.navigationController?.pushViewController(memberListVC, animated: true)
}
}
|
//
// WeatherManager.swift
// MyWeather
//
// Created by Matteo Cipone on 15.10.21.
//
import Foundation
import SwiftUI
import CoreLocation
class WeatherManager: ObservableObject {
@Published var weatherModel = WeatherModel(conditionId: 800, cityName: "Vienna", temperature: 0.0)
func fetchCityName(with location: String) {
let url = "https://api.openweathermap.org/data/2.5/weather?q=\(location)&units=metric&appid=\(K.apiKey)"
performRequest(url)
}
func fetchCurrentLocation(latitude: CLLocationDegrees, longitude: CLLocationDegrees) {
let url = "https://api.openweathermap.org/data/2.5/weather?lat=\(latitude)&lon=\(longitude)&units=metric&appid=\(K.apiKey)"
performRequest(url)
}
private func performRequest(_ url: String) {
if let safeUrl = URL(string: url) {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: safeUrl) { data, response, error in
if error == nil {
let decoder = JSONDecoder()
if let safeData = data {
do {
let decodedData = try decoder.decode(WeatherData.self, from: safeData)
DispatchQueue.main.async {
self.weatherModel.cityName = decodedData.name
self.weatherModel.conditionId = decodedData.weather[0].id
self.weatherModel.temperature = decodedData.main.temp
}
} catch {
print(error)
}
}
}
}
task.resume()
}
}
}
|
//
// ViewController.swift
// outaTime
//
// Created by Ennui on 10/8/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
@objc protocol DatePickerDelegate
{
func dateWasChosen(destDate: NSDate)
}
class TimeCircuitsViewController: UIViewController, DatePickerDelegate //we agree to fulfill any conditions in the function that are non-optional. must implement datewaschosen func
{
@IBOutlet var destTime: UILabel!
@IBOutlet var presTime: UILabel!
@IBOutlet var lastTimeDep: UILabel!
@IBOutlet var speedLabel: UILabel!
@IBOutlet var travBack: UIButton!
@IBOutlet var errorLabel: UILabel!
@IBOutlet var setDestTime: UIButton!
var baseSpeed = 0 //setting base speed to 0
var currentSpeed = 0
var accelerate: NSTimer? //setting timer up
var decelerate: NSTimer?
var presTimeBak = ""
let date = NSDate()
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
presTime.text = formatTime(NSDate())
destTime.text = "NOT SET"
presTimeBak = presTime.text!
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
//runs any time we segue out of timecircuits
//take datepickerviewcontroller
if segue.identifier == "ShowDatePickerSegue"
{
let datePickerVC = segue.destinationViewController as! DatePickerViewController
//data type will be uiviewcontroller. there is no data type delegate in uiviewcontroller. "i know that this is an instance of my datepickerviewcontroller" "cast"
datePickerVC.delegate = self
//self referring to the class that we're in. we're setting this class as the value for delegate
//does self conform to protocol? Yes, because we've signed up for it and fulfilled the conract by using the function dateWasChosen
}
}
//MARK: - delegate
func dateWasChosen(destDate: NSDate)
{
destTime.text = formatTime(destDate)
//take the date from the date picker, format it, then assign it as the text in desTime
errorLabel.text = ""
//set the error label back to blank when going back to the main view
}
//MARK: - THE ACTION HANDLERS
//coming soon to a theater near you
@IBAction func travBackTapped(sender: UIButton)
{
travelBackPressed()
}
//MARK: - private
func formatTime(timeToFormat: NSDate) -> String
{
let formatter = NSDateFormatter()
formatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("MMM dd YYYY", options: 0, locale: NSLocale(localeIdentifier: "en-US"))
let formattedTime = formatter.stringFromDate(timeToFormat)
return formattedTime
}
func travelBackPressed()
{
if destTime.text == "NOT SET"
{
errorLabel.text = "ERROR: SET DESTINATION TIME"
}
else if destTime.text == presTime.text
{
errorLabel.text = "ERROR: DESTINATION SAME AS PRESENT"
}
else
{
view.backgroundColor = UIColor.blackColor()
errorLabel.text = "ACCELERATING"
presTimeBak = presTime.text!
//storing the value of the current presTime so I can put it in lastTimeDep
if accelerate == nil
{
accelTimer(0.15)
travBack.setTitle("", forState: UIControlState.Normal)
setDestTime.setTitle("", forState: UIControlState.Normal)
}
}
}
//MARK: - timer stuff
func destroyTimer()
{
accelerate?.invalidate()
accelerate = nil
decelerate?.invalidate()
decelerate = nil
}
func accelTimer(tickInterval: Double)
{
accelerate = NSTimer.scheduledTimerWithTimeInterval(tickInterval, target: self, selector: "updateSpeed", userInfo: nil, repeats: true)
}
func decelTimer(tickInterval: Double)
{
decelerate = NSTimer.scheduledTimerWithTimeInterval(tickInterval, target: self, selector: "updateBrake", userInfo: nil, repeats: true)
}
//MARK: - SPEED
//with keanu reeves
func stopSpeed()
{
destroyTimer()
travBack.setTitle("TRAVEL BACK", forState: UIControlState.Normal)
setDestTime.setTitle("SET DESTINATION TIME", forState: UIControlState.Normal)
baseSpeed = 0
lastTimeDep.text = presTimeBak
speedLabel.text = ("\(baseSpeed) MPH")
errorLabel.text = "ARRIVED"
}
//sloppy
func accelerateSpeed(currentSpeed: Int)
{
if currentSpeed == 7
{
destroyTimer()
accelTimer(0.09)
}
if currentSpeed == 20
{
destroyTimer()
accelTimer(0.1)
}
else if currentSpeed == 30
{
destroyTimer()
accelTimer(0.12)
}
else if currentSpeed == 50
{
destroyTimer()
accelTimer(0.15)
}
else if currentSpeed == 60
{
destroyTimer()
accelTimer(0.18)
}
else if currentSpeed == 70
{
destroyTimer()
accelTimer(0.22)
}
else if currentSpeed == 80
{
destroyTimer()
accelTimer(0.28)
}
}
func updateSpeed()
{
currentSpeed = baseSpeed + 1
baseSpeed = currentSpeed
accelerateSpeed(currentSpeed)
if currentSpeed < 88
{
speedLabel.text = ("\(baseSpeed) MPH")
}
if currentSpeed == 88
{
speedLabel.text = "88 MPH"
errorLabel.text = "SPEED REACHED"
view.backgroundColor = UIColor.blackColor()
}
if currentSpeed == 92
{
errorLabel.text = "TRAVELING"
}
if currentSpeed == 100
{
presTime.text = destTime.text
currentSpeed = 88
destroyTimer()
decelTimer(0.005)
errorLabel.text = "DECELERATING"
}
}
//MARK:- brake
//(but stay above 60 mph)
func updateBrake()
{
speedLabel.text = ("\(baseSpeed) MPH")
baseSpeed = currentSpeed
currentSpeed = baseSpeed - 1
if currentSpeed == 0
{
view.backgroundColor = UIColor.darkGrayColor()
stopSpeed()
}
}
// :^)
} |
//
// SearchAlbumConstant.swift
// ScanPayGo
//
// Created by Ajay Odedra on 03/09/20.
// Copyright © 2020 Ajay Odedra. All rights reserved.
//
import UIKit
public struct CartConstants {
struct JSON {
static let productJsonName = "cartData"
}
struct ScanView {
static let navigationTitle = NSLocalizedString("cart_navigation_bar_title",
comment: "Cart navigation large title")
static let checkOutText = NSLocalizedString("cart_navigation_bar_checkout_title",
comment: "Cart navigation check-out title")
}
struct Identifier {
static let tableViewCellReuseIdentifier = "TableViewCartItemCell"
}
struct AlertView {
static let defaultMessgae = NSLocalizedString("cart_api_failure",
comment: "Default api failure message")
static let alertTitle = NSLocalizedString("cart_alert_error_title",
comment: "Alert title for failure")
static let alertOkayButtonTitle = NSLocalizedString("cart_alert_okay_title",
comment: "Alert okay button title for failure")
}
}
|
//
// BaseViewController.swift
// v2ex
//
// Created by zhenwen on 5/11/15.
// Copyright (c) 2015 zhenwen. All rights reserved.
//
import UIKit
import Kingfisher
class BaseViewController: UIViewController {
var loadingView: UIActivityIndicatorView!
var reloadView: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// 加载中
self.loadingView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
loadingView.center = self.view.center
loadingView.hidesWhenStopped = true
self.view.addSubview(loadingView)
// 重新加载按钮
self.reloadView = UIButton(type: .Custom)
reloadView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 100, height: 40))
reloadView.center = self.view.center
reloadView.setTitle("点我重新加载", forState: UIControlState.Normal)
reloadView.setTitleColor(UIColor.colorWithHexString("#333344"), forState: UIControlState.Normal)
reloadView.titleLabel?.font = UIFont.systemFontOfSize(13.0)
reloadView.hidden = true
reloadView.addTarget(self, action: #selector(reloadViewTapped(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(reloadView)
}
func reloadViewTapped(sender: UIButton!) {
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
}
|
//
// PerformerDetailController.swift
// Capital Pride
//
// Created by John Cloutier on 5/11/15.
// Copyright (c) 2015 John Cloutier. All rights reserved.
//
import Foundation
import UIKit
class PerformerDetailController: UIViewController {
@IBOutlet weak var name: UITextField!
@IBOutlet weak var facebook: UITextView!
@IBOutlet weak var startTime: UITextField!
@IBOutlet weak var image: UIImageView!
@IBOutlet weak var bio: UITextView!
@IBOutlet weak var stage: UITextField!
var performer: Performer?
override func viewDidLoad() {
super.viewDidLoad()
name.text = performer!.name
facebook.text = performer!.facebook
startTime.text = performer!.startTime
stage.text = performer!.stage
image.image = UIImage(named: performer!.image)
bio.text = performer!.bio
self.title = performer!.name
}
override func viewDidLayoutSubviews() {
bio.setContentOffset(CGPointZero, animated: false)
}
} |
//
// Created by Jim Wilenius on 2020-06-22.
//
import Foundation
/**
* An abstract base for builders of msgpack events, see subclasses.
*
* @param <T> a subclass of MDCommonBuilder<T>
*/
public class MDCommonBuilder<T> {
var iDeviceId : [UInt8]? = Optional.none
var iBssid : [UInt8]? = Optional.none
var iAnid : String? = Optional.none
var iTimeStamp : MsgPackSpecificationV2.TimeStamp? = Optional.none
/// This class should never be constructed in any other way than through a subclass.
/// If T is not a subclass of MDCommonBuilder<T> then a fatalError is raised.
public init() {
// The type sytem does not let me define class MDCommonBuilder<T : MDCommonBuilder>
// Which means we must make sure that T is a subclass of MDCommonBuilder<T> in some other way
let a = self as? T
if (a == nil) {
fatalError("Usage error! Generic Type T \(String(describing: T.self)) must inherit MDCommonBuilder<T>")
}
}
/**
* @param id a byte array of size 6
* @return a builder of type T
*/
@discardableResult
public func withDeviceId6Byte(_ id : [UInt8]) -> T {
iDeviceId = id
return self as! T
}
/**
* @param anid a string of numeric characters, length 24
* @return a builder of type T
*/
@discardableResult
public func withAnid(_ anid : String) -> T {
iAnid = anid
return self as! T
}
/**
* @param bssid a byte array of size 6
* @return a builder of type T
*/
@discardableResult
public func withBssid6Byte(_ bssid : [UInt8]) -> T {
iBssid = bssid
return self as! T
}
///
/// - seconds since 1970-01-01T00:00:00Z
/// - nanos part of the second
///
@discardableResult
public func withTimeStamp(secondsSince1970 : UInt64, nanos : Int ) -> T {
iTimeStamp = MsgPackSpecificationV2.TimeStamp(secondsSince1970, nanos)
return self as! T
}
///
/// The current time measured from 1970-01-01T00:00:00Z
///
@discardableResult
public func withTimeStampNow() -> T {
let now : Double = NSDate().timeIntervalSince1970
let seconds : Double = floor(now)
let nanos : Int = Int(round((now - seconds) * 1.0e9))
iTimeStamp = MsgPackSpecificationV2.TimeStamp(UInt64(seconds), nanos)
return self as! T
}
@discardableResult
public func withTimeStamp(_ timeStamp : MsgPackSpecificationV2.TimeStamp) -> T {
iTimeStamp = timeStamp
return self as! T
}
/// throws IllegalArgumentException if any of the members are Optiona.none
func checkAllFieldsSetSinceAPIVersion2DoesNotHandleOptional() throws {
let fields : [(Any?, String)] = [
(iDeviceId, "DeviceId"),
(iAnid, "Anid"),
(iBssid, "Bssid"),
(iTimeStamp, "TimeStamp")
]
try checkAllFields(fields: fields)
}
}
|
//
// Constants.swift
// MsgApp
//
// Created by hardik aghera on 24/12/16.
// Copyright © 2016 hardik aghera. All rights reserved.
//
struct Constants {
// MARK: NotificationKeys
struct NotificationKeys {
static let SignedIn = "onSignInCompleted"
}
// MARK: MessageFields
struct MessageFields {
static let name = "name"
static let text = "text"
static let imageUrl = "photoUrl"
}
}
|
//
// SceneDelegate.swift
// CombineCollection
//
//
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
private let client: HTTPClient = URLSessionHTTPClient(session: .shared)
private lazy var dogWebAPI = DogWebAPI(client: client)
private lazy var imageDataLoader = ImageDataWebLoader(client: client)
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let scene = scene as? UIWindowScene else { return }
let window = UIWindow(windowScene: scene)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(
identifier: String(describing: BreedListViewController.self)) { [self] coder in
BreedListViewController(coder: coder,
viewModel: .init(loader: dogWebAPI.breedListLoader),
breedTypeSelected: moveToImagesGrid(breedType:))
}
let navigationController = UINavigationController(rootViewController: viewController)
window.rootViewController = navigationController
self.window = window
window.makeKeyAndVisible()
}
private func moveToImagesGrid(breedType: BreedType) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(
identifier: String(describing: BreedImagesGridViewController.self)) { [self] coder in
BreedImagesGridViewController(coder: coder,
breedType: breedType,
viewModel: .init(loader: dogWebAPI.dogImageListLoader),
imageDataLoader: imageDataLoader.loader)
}
guard let navigationContoller = window?.rootViewController as? UINavigationController else {
return
}
navigationContoller.pushViewController(viewController, animated: true)
}
}
|
import UIKit
import NetworkExtension
class TBCMain: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
reloadTabBarBadge()
NotifyVPNStateChanged.observe(call: #selector(reloadTabBarBadge), on: self)
if !Prefs.DidShowTutorial.Welcome {
self.perform(#selector(showWelcomeMessage), with: nil, afterDelay: 0.5)
}
if #available(iOS 10.0, *) {
initNotifications()
}
}
@objc private func reloadTabBarBadge() {
let stateView = self.tabBar.items?.last
switch GlassVPN.state {
case .on: stateView?.badgeValue = "✓"
case .inbetween: stateView?.badgeValue = "⋯"
case .off: stateView?.badgeValue = "✗"
}
if #available(iOS 10.0, *) {
switch GlassVPN.state {
case .on: stateView?.badgeColor = .systemGreen
case .inbetween: stateView?.badgeColor = .systemYellow
case .off: stateView?.badgeColor = .systemRed
}
}
}
@objc private func showWelcomeMessage() {
let x = TutorialSheet()
x.addSheet().addArrangedSubview(TinyMarkdown.load("tut-welcome-1"))
x.addSheet().addArrangedSubview(TinyMarkdown.load("tut-welcome-2"))
x.present(didClose: {
Prefs.DidShowTutorial.Welcome = true
})
}
}
extension TBCMain {
/// Open tab and pop to root view controller.
@discardableResult func openTab(_ index: Int) -> UIViewController? {
selectedIndex = index
guard let nav = selectedViewController as? UINavigationController else {
return selectedViewController
}
nav.popToRootViewController(animated: false)
return nav.topViewController
}
}
// MARK: - Push Notifications
@available(iOS 10.0, *)
extension TBCMain: UNUserNotificationCenterDelegate {
func initNotifications() {
UNUserNotificationCenter.current().delegate = self
guard Prefs.RecordingReminder.Enabled else {
return
}
PushNotification.allowed {
switch $0 {
case .NotDetermined:
PushNotification.requestProvisionalOrDoNothing { success in
guard success else { return }
PushNotification.scheduleRecordingReminder(force: false)
}
case .Denied:
break
case .Authorized, .Provisional:
PushNotification.scheduleRecordingReminder(force: false)
}
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound]) // in-app notifications
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
defer { completionHandler() }
if isFrontmostModal() {
return // dont intervene user actions
}
switch response.notification.request.identifier {
case PushNotification.Identifier.YouShallRecordMoreReminder.rawValue:
selectedIndex = 1 // open recordings tab
case PushNotification.Identifier.CantStopMeNowReminder.rawValue:
(openTab(2) as! TVCSettings).openRestartVPNSettings()
//case PushNotification.Identifier.RestInPeaceTombstoneReminder // only badge
case let x: // domain notification
(openTab(0) as! TVCDomains).pushOpen(domain: x) // open requests tab
}
}
@available(iOS 12.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
(openTab(2) as! TVCSettings).openNotificationSettings()
}
func isFrontmostModal() -> Bool {
var x = selectedViewController!
while let tmp = x.presentedViewController {
x = tmp
}
if x is UIAlertController {
return true
} else if #available(iOS 13.0, *) {
return x.isModalInPresentation
} else {
return x.modalPresentationStyle == .custom
}
}
}
|
// swift-tools-version:5.2
import PackageDescription
#if os(macOS)
let linkedGL = LinkerSetting.linkedFramework("OpenGL")
#elseif os(Linux)
let linkedGL = LinkerSetting.linkedLibrary("GL")
#endif
let package = Package(
name: "Cnanovg",
products: [
.library(
name: "CnanovgGL3",
targets: ["CnanovgGL3"]
)
],
targets: [
.target(
name: "Cnanovg",
sources: ["nanovg/src/nanovg.c"]),
.target(
name: "CnanovgGL3",
dependencies: ["Cnanovg"],
linkerSettings: [linkedGL])
]
)
|
//
// Chapter5NextNumber.swift
// CtCI
//
// Created by Jordan Doczy on 2/28/21.
//
import Foundation
class Chapter5NextNumber {
static func findNextNumbers(_ value: UInt) -> (low: Int, high: Int) {
guard value.nonzeroBitCount > 0 else {
return (-1,-1)
}
let lsb: UInt = 1 << value.trailingZeroBitCount
let msb: UInt = 1 << (value.bitWidth - value.leadingZeroBitCount - 1)
// if our firstZero is greater than our most significant bit, we can not find a lower value
guard let firstZero = findNextZero(value: value, from: 1),
firstZero < msb else {
return (-1,-1)
}
let firstBit = lsb
guard let firstZeroFollowingBit = firstZero > 1 ?
firstZero :
findNextZero(value: value, from: firstBit) else {
return (-1,-1)
}
guard let firstBitFollowingZero = firstBit > firstZero ?
firstBit :
findNextBit(value: value, from: firstZeroFollowingBit << 1) else {
return (-1,-1)
}
// print("firstBit= \(String(firstBit, radix: 2))")
// print("firstZero= \(String(firstZero, radix: 2))")
// print("firstZeroFollowingBit= \(String(firstZeroFollowingBit, radix: 2))")
// print("firstBitFollowingZero= \(String(firstBitFollowingZero, radix: 2))")
//
var mask = (firstZeroFollowingBit - 1) // mask of 11111s
var upper = value
upper |= firstZeroFollowingBit // flip 0 bit
upper &= ~mask // remove values from right side of 0 bit
upper += (value & (mask >> 1)) >> value.trailingZeroBitCount // shift values of right side of 0 bit and add them back to upper
mask = (firstBitFollowingZero - 1) // mask of 11111s
var lower = value
lower = value
lower &= ~firstBitFollowingZero // flip bit to 0
lower += (firstBitFollowingZero >> 1) // flip bit preceding to 1
lower &= ~(mask >> 1) // remove values from right side of 0 bit
let remainingValues = (value & (mask >> 1))
let shift = mask.nonzeroBitCount - remainingValues.nonzeroBitCount - 1
lower += remainingValues << shift
return (Int(lower), Int(upper))
}
static func findNextZero(value: UInt, from: UInt) -> UInt? {
var nsb: UInt = from
while nsb & value > 0 && nsb.trailingZeroBitCount < UInt64.bitWidth - 1 {
nsb <<= 1
}
return nsb & value == 0 ? nsb : nil
}
static func findNextBit(value: UInt, from: UInt) -> UInt? {
var nsb: UInt = from
while nsb & value <= 0 && nsb.trailingZeroBitCount < UInt64.bitWidth - 1 {
nsb <<= 1
}
return nsb & value > 0 ? nsb : nil
}
static func runTest(_ test: (value: UInt, low: Int, high: Int)) -> Bool {
print("NEW TEST")
print(String(test.value, radix: 2))
let result = findNextNumbers(test.value)
print(test.value, result, String(result.low, radix: 2), String(result.high, radix: 2))
return result.low == test.low && result.high == test.high
}
static func runTests() -> Bool {
var tests: [(value: UInt, low: Int, high: Int)] = []
tests.append((value: 0b1000111, low: 60, high: 75))
tests.append((value: 0b1001110, low: 77, high: 83))
tests.append((value: 0b100011100, low: 282, high: 291))
tests.append((value: 0b101, low: 3, high: 6))
tests.append((value: 0b1, low: -1, high: -1))
tests.append((value: 0b10, low: 1, high: 4))
for test in tests {
if runTest(test) == false {
return false
}
}
return true
}
}
|
//
// DIYScrollView.swift
// Pruebas
//
// Created by Julio Banda on 2/15/19.
// Copyright © 2019 Julio Banda. All rights reserved.
//
import UIKit
class DIYScrollView: UIView {
@IBAction func handlePan(_ recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translation(in: self)
bounds.origin.y = bounds.origin.y - translation.y
recognizer.setTranslation(.zero, in: self)
}
}
|
//
// ActionSheetView.swift
// schedules
//
// Created by H. Kamran on 1/21/20.
// Copyright © 2020 H. Kamran. All rights reserved.
//
import UIKit
import SnapKit
class ActionSheetView: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(TableViewCell.self, forCellReuseIdentifier: "cell_id")
view.addSubview(tableView)
view.backgroundColor = #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1)
tableView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return schedules.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell_id", for: indexPath) as! TableViewCell
for row in indexPath {
cell.label.text = schedules[indexPath.row].name
}
return cell
}
}
class TableViewCell: UITableViewCell {
let label = UILabel()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = UIColor.systemBackground
contentView.addSubview(label)
label.snp.makeConstraints { (make) in
make.center.equalToSuperview()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// TabBarViewController.swift
// OntPass
//
// Created by Ross Krasner on 12/8/18.
// Copyright © 2018 Ryu. All rights reserved.
//
import UIKit
class TabBarViewController: UITabBarController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationItem.hidesBackButton = true
self.navigationItem.hidesBackButton = true
navigationItem.hidesBackButton = true
}
}
|
//
// DataManager.swift
// PersonsList
//
// Created by Artem Pavlov on 08.09.2021.
//
class DataManager {
static let shared = DataManager() // создаем единственный объект класса внутри самого класса и делаем статическим, чтобы на него можно было ссылаться из других частей кода.
let realNames = [
"John",
"Steven",
"Misha",
"Boris",
"Melanie",
"Bred",
"Ted",
"Sharon"
]
let realSecondNames = [
"Smith",
"Karter",
"White",
"Brown",
"Willis",
"Trump",
"Pitt",
"Dancher"
]
let realNumbersPhones = [
"8-900-600-80-80",
"8-900-555-55-40",
"8-800-100-55-55",
"8-999-640-80-10",
"8-950-600-40-44",
"8-955-440-42-22",
"8-900-220-20-20",
"8-800-200-33-33"
]
let realEmails = [
"222@swiftbook.ru",
"tit@mail.ru",
"pholik@mail.ru",
"dodds@icloud.com",
"my@gmail.com",
"biggi@rambler.ru",
"cat@swiftbook.ru",
"works@mail.ru"
]
private init() {} // делаем пустой инициализатор, чтобы нельзя было создать лишние объекты класса DataManager
}
|
//
// Transaction.swift
// Desafio-Mobile-PicPay
//
// Created by Luiz Hammerli on 28/07/2018.
// Copyright © 2018 Luiz Hammerli. All rights reserved.
//
import Foundation
struct JsonTransaction:Codable {
let id: Int
let timestamp: Double
let value: Double
let destination_user: Contact
let success: Bool
let status:String
}
|
//
// TotalTableViewController.swift
// FRCScouting
//
// Created by Bajaj, Ayush on 3/28/19.
// Copyright © 2019 Takahashi, Alex. All rights reserved.
//
import UIKit
import Foundation
import SAPFiori
import SAPFoundation
class TotalTableViewController: FUIFormTableViewController {
var gameData = ModelObject.shared
var netPoints = 0
var endLevelPlaceholder = 0
var RocketCargoT = 0
var RocketCargoM = 0
var RocketCargoB = 0
var RocketHatchT = 0
var RocketHatchM = 0
var RocketHatchB = 0
var numCargoShipCargo = 0
var numCargoShipHatch = 0
func flattenArray(someArray: [[Int]]) -> String {
var flattenedArray = [Int]()
for row in someArray {
for column in row {
flattenedArray.append(column)
}
}
let rocketString = flattenedArray.map({"\($0)"}).joined(separator: ",")
return rocketString
}
func RocketCalc(r1: [[Int]], r2: [[Int]]) -> (Int,Int,Int){
var Top = 0
var Mid = 0
var Bot = 0
var counter = 0
var num = 0
for row in r1{
num = 0
for column in row {
num += column
}
if counter == 0 {
Top += num
}
if counter == 1{
Mid += num
}
if counter == 2{
Bot += num
}
counter += 1
}
counter = 0
for row in r2{
num = 0
for column in row {
num += column
}
if counter == 0 {
Top += num
}
if counter == 1{
Mid += num
}
if counter == 2{
Bot += num
}
counter += 1
}
//print (Top)
//print (Mid)
//print (Bot)
return (Top,Mid,Bot)
}
func endingPlatformScore(endingLevel: Int) {
self.gameData.endingLevelIndex = endingLevel
if (endingLevel == 0) {
self.gameData.endingLevel = "None"
self.gameData.grandTotal = self.netPoints - self.endLevelPlaceholder
self.endLevelPlaceholder = 0
self.gameData.grandTotal = self.netPoints + self.endLevelPlaceholder
}
else if (endingLevel == 1) {
self.gameData.endingLevel = "1"
self.gameData.grandTotal = self.netPoints - self.endLevelPlaceholder
self.endLevelPlaceholder = 0
self.endLevelPlaceholder += 3
self.gameData.grandTotal = self.netPoints + self.endLevelPlaceholder
}
else if (endingLevel == 2) {
self.gameData.endingLevel = "2"
self.gameData.grandTotal = self.netPoints - self.endLevelPlaceholder
self.endLevelPlaceholder = 0
self.endLevelPlaceholder += 6
self.gameData.grandTotal = self.netPoints + self.endLevelPlaceholder
}
else {
self.gameData.endingLevel = "3"
self.gameData.grandTotal = self.netPoints - self.endLevelPlaceholder
self.endLevelPlaceholder = 0
self.endLevelPlaceholder += 12
self.gameData.grandTotal = self.netPoints + self.endLevelPlaceholder
}
}
/* @objc func shareCSV(sender: UIButton) {
let fileName = "Q_\(gameData?.match ?? 0)_\(gameData?.teamName ?? "").csv"
guard
let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName),
let gameData = self.gameData
else { preconditionFailure()}
var csvText = "Team Name, Match Number, Ally Collision, Attempt Sandstorm, Starting Level, Successful Descent, Sandstorm Hatches, Sandstorm Cargo, Sandstorm Misses, Rocket Hatch Top, Rocket Hatch Mid, Rocket Hatch Bottom, Rocket Cargo Top, Rocket Cargo Mid, Rocket Cargo Bottom, Cargo Ship Hatch, Cargo Ship Cargo, Ending Level, Penalty, Notes, Attempted Defense, Defense Effective, Failed Climb, Disconnect, Defended Against, Total\n"
print(csvText)
// We need to remove the commas from the 2D array and notes
// TODO: Figure out the CSV escaping so we do not have to do this!
/*let r1RocketHatchString = "\(gameData.r1RocketHatch)".replacingOccurrences(of: ",", with: "")
let r1RocketCargoString = "\(gameData.r1RocketCargo)".replacingOccurrences(of: ",", with: "")
let r2RocketHatchString = "\(gameData.r2RocketHatch)".replacingOccurrences(of: ",", with: "")
let r2RocketCargoString = "\(gameData.r2RocketCargo)".replacingOccurrences(of: ",", with: "")
let cargoShipHatchString = "\(gameData.cargoShipHatch)".replacingOccurrences(of: ",", with: "")
let cargoShipCargoString = "\(gameData.cargoShipCargo)".replacingOccurrences(of: ",", with: "")*/
numCargoShipHatch = calcCargoShip(_matrix: gameData.cargoShipHatch)
print("Before: \(numCargoShipHatch)")
numCargoShipCargo = calcCargoShip(_matrix: gameData.cargoShipCargo)
print("Before: \(numCargoShipCargo)")
let fixedNotes = "\(gameData.notes)".replacingOccurrences(of: ",", with: "").replacingOccurrences(of: "\n", with: " ")
let newLine = """
\(gameData.teamName), \(gameData.match), \(gameData.allyCollision), \(gameData.attemptSandstorm), \(gameData.startingLevel), \(gameData.successfulDescent), \(gameData.sandstormHatch), \(gameData.sandstormCargo), \(gameData.misses), \(RocketHatchT), \(RocketHatchM), \(RocketHatchB), \(RocketCargoT), \(RocketCargoM), \(RocketCargoB), \(numCargoShipHatch), \(numCargoShipCargo), \(gameData.endingLevel), \(gameData.penaltyPoints), \(fixedNotes), \(gameData.attemptedDefense), \(gameData.effectiveDefense), \(gameData.failedLevel), \(gameData.disconnect), \(gameData.defendedAgainst), \(gameData.grandTotal)
"""
print(newLine)
/*let newLine = """
\(gameData.teamName), \(gameData.match), \(gameData.crossedLine), \(gameData.allyCollision), \(flattenArray(someArray: gameData.r1RocketHatch)), \(flattenArray(someArray: gameData.r1RocketCargo)), \(flattenArray(someArray: gameData.r2RocketHatch)), \(flattenArray(someArray: gameData.r2RocketCargo)), \(flattenArray(someArray: gameData.cargoShipHatch)), \(flattenArray(someArray: gameData.cargoShipCargo)), \(gameData.penaltyPoints), \(fixedNotes), \(gameData.aggressiveDefense), \(gameData.failedClimb), \(gameData.disconnect), \(gameData.defendedAgainst), \(gameData.grandTotal)q
""" */
// let newLine = """
// \(gameData.grandTotal), \(gameData.penaltyPoints), \(gameData.aggressiveDefense), \(gameData.allyCollision), \(gameData.failedClimb), \(gameData.disconnect), \(gameData.defendedAgainst), "\(gameData.notes)"
// """
csvText.append(contentsOf: newLine)
do {
try csvText.write(to: path, atomically: true, encoding: String.Encoding.utf8)
print("It worked")
} catch {
print("Failed to create file")
}
let vc = UIActivityViewController(activityItems: [path], applicationActivities: [])
present(vc, animated: true, completion: nil)
} */
@objc func alert(sender: UIButton) {
let alertController = UIAlertController(title: "Are You Sure", message: "Going back home will erase any entered data", preferredStyle: .alert)
let action1 = UIAlertAction(title: "Yes", style: .default) { (action:UIAlertAction) in
self.navigationController?.popToRootViewController(animated: true)
}
let action2 = UIAlertAction(title: "Cancel", style: .cancel) { (action:UIAlertAction) in
return
}
alertController.addAction(action1)
alertController.addAction(action2)
self.present(alertController, animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// TODO: Return the number of cells
if self.gameData == nil {
return 0
} else {
return 10
}
}
@objc func pushNextViewController(sender: UIButton) {
let nextVC = ReViewController()
nextVC.gameData = self.gameData
numCargoShipHatch = calcCargoShip(_matrix: gameData.cargoShipHatch)
print("Before: \(numCargoShipHatch)")
numCargoShipCargo = calcCargoShip(_matrix: gameData.cargoShipCargo)
print("Before: \(numCargoShipCargo)")
gameData.numCargoShipCargo = self.numCargoShipCargo
print("After: \(numCargoShipCargo)")
gameData.numCargoShipHatch = self.numCargoShipHatch
print("After: \(numCargoShipHatch)")
gameData.RocketCargoT = self.RocketCargoT
gameData.RocketCargoM = self.RocketCargoM
gameData.RocketCargoB = self.RocketCargoB
gameData.RocketHatchT = self.RocketHatchT
gameData.RocketHatchM = self.RocketHatchM
gameData.RocketHatchB = self.RocketHatchB
self.navigationController?.pushViewController(nextVC, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Totals"
let nextButton = UIBarButtonItem(title: "Finish", style: .done, target: self, action: #selector(pushNextViewController(sender:)))
self.navigationItem.rightBarButtonItem = nextButton
tableView.register(FUISwitchFormCell.self, forCellReuseIdentifier: FUISwitchFormCell.reuseIdentifier)
tableView.register(FUITextFieldFormCell.self, forCellReuseIdentifier: FUITextFieldFormCell.reuseIdentifier)
tableView.register(FUINoteFormCell.self, forCellReuseIdentifier: FUINoteFormCell.reuseIdentifier)
tableView.register(FUIMapDetailPanel.ButtonTableViewCell.self, forCellReuseIdentifier: FUIMapDetailPanel.ButtonTableViewCell.reuseIdentifier)
tableView.register(FUISegmentedControlFormCell.self, forCellReuseIdentifier: FUISegmentedControlFormCell.reuseIdentifier)
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableView.automaticDimension
tableView.separatorStyle = .none
//self.gameData?.rocketCargo = [[true,true],[false,true]]
(RocketCargoT,RocketCargoM,RocketCargoB) = RocketCalc(r1: self.gameData.r1RocketCargo , r2: self.gameData.r2RocketCargo )
(RocketHatchT,RocketHatchM,RocketHatchB) = RocketCalc(r1: self.gameData.r1RocketHatch , r2: self.gameData.r2RocketHatch )
print ("Cargo: ")
print (RocketCargoT)
print (RocketCargoM)
print (RocketCargoB)
print ("Hatch: ")
print (RocketHatchT)
print (RocketHatchM)
print (RocketHatchB)
// Adding Cargo Points
for row in self.gameData.r1RocketCargo {
for column in row {
if column == 1 {
self.netPoints += 3
}
}
}
for row in self.gameData.r2RocketCargo {
for column in row {
if column == 1 {
self.netPoints += 3
}
}
}
for row in self.gameData.cargoShipCargo {
for column in row {
if column == 1 {
self.netPoints += 3
}
}
}
//
// Adding Hatch points
for row in self.gameData.r1RocketHatch {
for column in row {
if column == 1 {
self.netPoints += 2
}
}
}
for row in self.gameData.r2RocketHatch {
for column in row {
if column == 1 {
self.netPoints += 2
}
}
}
for row in self.gameData.cargoShipHatch {
for column in row {
if column == 1 {
self.netPoints += 2
}
}
}
//
if (gameData.successfulDescent == true) {
if (gameData.startingLevel == 1) {
self.netPoints += 3
}
else {
self.netPoints += 6
}
}
gameData.grandTotal = netPoints
//tableView.reloadRows(at: [[0,0]], with: UITableView.RowAnimation.none)
}
func calcCargoShip (_matrix:[[Int]]) -> Int {
var numHatches = 0
for (rowIndex, row) in _matrix.enumerated() {
for (columnIndex, _) in row.enumerated() {
if (_matrix[rowIndex][columnIndex] == 1) {
numHatches += 1
}
}
}
return numHatches
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// TODO: Implement FUI Form Cells
/* let cell = UITableViewCell()
cell.textLabel?.text = "TODO: Add FUI Form Cells"
return cell */
let switchFormCell = tableView.dequeueReusableCell(withIdentifier: FUISwitchFormCell.reuseIdentifier, for: indexPath) as! FUISwitchFormCell
let grandTextFieldCell = tableView.dequeueReusableCell(withIdentifier: FUITextFieldFormCell.reuseIdentifier, for: indexPath) as! FUITextFieldFormCell
let penaltyPoints = tableView.dequeueReusableCell(withIdentifier: FUITextFieldFormCell.reuseIdentifier, for: indexPath) as! FUITextFieldFormCell
let noteCell = tableView.dequeueReusableCell(withIdentifier: FUINoteFormCell.reuseIdentifier, for: indexPath) as! FUINoteFormCell
let multipleOptionCell = self.tableView.dequeueReusableCell(withIdentifier: FUISegmentedControlFormCell.reuseIdentifier, for: indexPath) as! FUISegmentedControlFormCell
let endingOptions = ["None", "1", "2", "3"]
/* guard let gameData = self.gameData else {
switchFormCell.value = true
switchFormCell.keyName = "Error"
return switchFormCell
} */
switch indexPath.section {
case 0:
switch indexPath.row {
case 0:
self.endingPlatformScore(endingLevel: gameData.endingLevelIndex)
multipleOptionCell.valueOptions = endingOptions
multipleOptionCell.keyName = "Ending Platform"
switch gameData.endingLevel {
case "None":
gameData.endingLevelIndex = 0
default:
gameData.endingLevelIndex = Int(gameData.endingLevel)!
}
multipleOptionCell.value = gameData.endingLevelIndex
multipleOptionCell.isEditable = true
multipleOptionCell.onChangeHandler = { newValue in
self.endingPlatformScore(endingLevel: newValue)
tableView.reloadRows(at: [[0,2]], with: UITableView.RowAnimation.none)
grandTextFieldCell.value = "\(self.gameData.grandTotal)"
}
return multipleOptionCell
case 1:
multipleOptionCell.valueOptions = endingOptions
multipleOptionCell.keyName = "Failed Climb Platform"
switch gameData.failedLevel {
case "None":
gameData.failedLevelIndex = 0
default:
gameData.failedLevelIndex = Int(gameData.failedLevel)!
}
multipleOptionCell.value = gameData.failedLevelIndex
multipleOptionCell.isEditable = true
multipleOptionCell.onChangeHandler = { newValue in
self.gameData.failedLevelIndex = newValue
if (newValue == 0) {
self.gameData.failedLevel = "None"
}
else if (newValue == 1) {
self.gameData.failedLevel = "1"
}
else if (newValue == 2) {
self.gameData.failedLevel = "2"
}
else {
self.gameData.failedLevel = "3"
}
}
return multipleOptionCell
case 2:
grandTextFieldCell.keyName = "Grand Total"
grandTextFieldCell.value = "\(gameData.grandTotal)"
grandTextFieldCell.isTrackingLiveChanges = true
grandTextFieldCell.onChangeHandler = { [unowned self] newTotal in
self.gameData.grandTotal = Int(newTotal)!
}
let temporaryIndexPath = IndexPath(item: 2, section: 0)
tableView.reloadRows(at: [temporaryIndexPath], with: UITableView.RowAnimation.none)
grandTextFieldCell.isEditable = false
return grandTextFieldCell
case 3:
penaltyPoints.isEditable = true
penaltyPoints.keyName = "Penalty Points Earned"
penaltyPoints.placeholderText = "Enter Points Here"
penaltyPoints.keyboardType = .numberPad
penaltyPoints.isTrackingLiveChanges = true
penaltyPoints.value = String(gameData.penaltyPoints)
penaltyPoints.onChangeHandler = { [unowned self] newValue in
let penalty = Int(newValue)
if penalty != nil {
self.gameData.penaltyPoints = penalty ?? 0
}
else {
self.gameData.penaltyPoints = 0
}
//self.gameData?.grandTotal = self.netPoints - (penalty ?? 0)
//tableView.reloadRows(at: [IndexPath.init(row: 3, section: 0)], with: UITableView.RowAnimation.none)
}
return penaltyPoints
case 4:
switchFormCell.keyName = "Attempted Defense?"
switchFormCell.value = gameData.attemptedDefense
switchFormCell.onChangeHandler = { [unowned self] newValue in
self.gameData.attemptedDefense = newValue
}
return switchFormCell
case 5:
switchFormCell.keyName = "If so, was it effective?"
switchFormCell.value = gameData.effectiveDefense
switchFormCell.onChangeHandler = { [unowned self] newValue in
self.gameData.effectiveDefense = newValue
}
return switchFormCell
case 6:
switchFormCell.keyName = "Terrible Collision with Ally?"
switchFormCell.value = gameData.allyCollision
switchFormCell.onChangeHandler = { [unowned self] newValue in
self.gameData.allyCollision = newValue
}
return switchFormCell
case 7:
switchFormCell.keyName = "Disconnection"
switchFormCell.value = gameData.disconnect
switchFormCell.onChangeHandler = { [unowned self] newValue in
self.gameData.disconnect = newValue
}
return switchFormCell
case 8:
switchFormCell.keyName = "Defended Against?"
switchFormCell.value = gameData.defendedAgainst
switchFormCell.onChangeHandler = { [unowned self] newValue in
self.gameData.defendedAgainst = newValue
}
return switchFormCell
case 9:
noteCell.isEditable = true
noteCell.value = gameData.notes
noteCell.placeholder.text = "Enter Additional Thoughts Here"
noteCell.maxNumberOfLines = 12
noteCell.onChangeHandler = { [unowned self] newValue in
self.gameData.notes = newValue
}
noteCell.isTrackingLiveChanges = true
return noteCell
default:
switchFormCell.value = true
switchFormCell.keyName = "Error"
return switchFormCell
}
default:
switchFormCell.value = true
switchFormCell.keyName = "Error"
return switchFormCell
}
}
}
|
//
// RecipeObjectServiceTests.swift
// RecipleaseTests
//
// Created by Raphaël Payet on 28/06/2021.
//
import XCTest
@testable import Reciplease
class RecipeObjectServiceTests: XCTestCase {
func testGivenCorrectDict_WhenTransformingToRecipeObject_ThenRecipeIsNotNil() {
let service = RecipeObjectService.shared
let recipe = service.transformFromDict(FakeRecipeObjectData.correctDict)
let url = URL(string: "http://www.seriouseats.com/recipes/2008/04/essentials-how-to-cook-rice.html")
let imageURL = URL(string: "https://www.edamam.com/web-img/b71/b716942f16e3e9490829f7da8dba509e.jpg")
XCTAssertNotNil(recipe)
XCTAssertEqual(recipe?.label, "Essentials: Rice")
XCTAssertEqual(recipe?.calories, 3000.0)
XCTAssertEqual(recipe?.cookTime, 0.0)
XCTAssertEqual(recipe?.cuisineType, "indian")
XCTAssertEqual(recipe?.url, url)
XCTAssertEqual(recipe?.imageURL, imageURL)
XCTAssertEqual(recipe?.ingredients, ["1 cup long-grain white rice"])
}
func testGivenIncorrectDict_WhenTransformingToRecipeObject_ThenRecipeIsNil() {
let service = RecipeObjectService.shared
let recipe = service.transformFromDict(FakeRecipeObjectData.incorrectDict)
XCTAssertNil(recipe)
XCTAssertNil(recipe?.label)
XCTAssertNil(recipe?.calories)
XCTAssertNil(recipe?.cookTime)
XCTAssertNil(recipe?.cuisineType)
XCTAssertNil(recipe?.url)
XCTAssertNil(recipe?.imageURL)
XCTAssertNil(recipe?.ingredients)
}
func testGivenCorrectRecipeInCoreData_WhenTransformingToRecipeObject_ThenObjectIsNotNil() {
let coreDataStack = FakeCoreDataStack()
let recipeService = RecipeDataModelService(managedObjectContext: coreDataStack.viewContext, coreDataStack: coreDataStack)
let service = RecipeObjectService.shared
let object = RecipeObject(id: UUID(), label: "Rice", cuisineType: "Chinese", ingredients: ["Ing1"], calories: 3000, cookTime: 20, url: FakeRecipeData.url, imageURL: FakeRecipeData.imageURL)
let recipe = recipeService.addRecipeToFavorite(object)
let newObject = service.transformFromCoreData(recipe: recipe)
XCTAssertNotNil(newObject)
XCTAssertEqual(newObject?.id, object.id)
XCTAssertEqual(newObject?.label, object.label)
XCTAssertEqual(newObject?.cuisineType, object.cuisineType)
XCTAssertEqual(newObject?.ingredients, object.ingredients)
XCTAssertEqual(newObject?.calories, object.calories)
XCTAssertEqual(newObject?.cookTime, object.cookTime)
XCTAssertEqual(newObject?.url, object.url)
XCTAssertEqual(newObject?.imageURL, object.imageURL)
}
func testGivenNoRecipeInCoreData_WhenTransformingToRecipeObject_ThenObjectIsNIl() {
let service = RecipeObjectService.shared
let newObject = service.transformFromCoreData(recipe: nil)
XCTAssertNil(newObject)
XCTAssertNil(newObject?.id)
XCTAssertNil(newObject?.label)
XCTAssertNil(newObject?.calories)
XCTAssertNil(newObject?.cookTime)
XCTAssertNil(newObject?.cuisineType)
XCTAssertNil(newObject?.ingredients)
XCTAssertNil(newObject?.url)
XCTAssertNil(newObject?.imageURL)
}
}
|
//
// ViewController.swift
// Destini
//
// Created by Philipp Muellauer on 01/09/2015.
// Completed and redone/revamped by Vikas Shukla on 06/23/2019
// Copyright (c) 2015 London App Brewery. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// Our stories
var storyOne = Story(story: "Your car has blown a tire on a winding road in the middle of nowhere with no cell phone reception. You decide to hitchhike. A rusty pickup truck rumbles to a stop next to you. A man with a wide brimmed hat with soulless eyes opens the passenger door for you and asks: \"Need a ride, boy?\".", answer1: "I\'ll hop in. Thanks for the help!", answer2: "Better ask him if he\'s a murderer first.")
var storyTwo = Story(story: "He nods slowly, unphased by the question.", answer1: "At least he\'s honest. I\'ll climb in.", answer2: "Wait, I know how to change a tire.")
var storyThree = Story(story: "As you begin to drive, the stranger starts talking about his relationship with his mother. He gets angrier and angrier by the minute. He asks you to open the glovebox. Inside you find a bloody knife, two severed fingers, and a cassette tape of Elton John. He reaches for the glove box.", answer1: "I love Elton John! Hand him the cassette tape.", answer2: "It\'s him or me! You take the knife and stab him.")
let story4 = "What? Such a cop out! Did you know traffic accidents are the second leading cause of accidental death for most adult age groups?"
let story5 = "As you smash through the guardrail and careen towards the jagged rocks below you reflect on the dubious wisdom of stabbing someone while they are driving a car you are in."
let story6 = "You bond with the murderer while crooning verses of \"Can you feel the love tonight\". He drops you off at the next town. Before you go he asks you if you know any good places to dump bodies. You reply: \"Try the pier.\""
// UI Elements linked to the storyboard
@IBOutlet weak var topButton: UIButton! // Has TAG = 1
@IBOutlet weak var bottomButton: UIButton! // Has TAG = 2
@IBOutlet weak var storyTextView: UILabel!
var depth: Int = 0;
override func viewDidLoad() {
super.viewDidLoad()
storyOneScreen()
}
// User presses one of the buttons
@IBAction func buttonPressed(_ sender: UIButton) {
if depth == 0{
if sender.tag == 1{
storyThreeScreen()
}else if sender.tag == 2{
storyTwoScreen()
}
depth += 1
}
else if depth == 1 && storyTextView.text == storyTwo.story{
if sender.tag == 1{
storyThreeScreen()
}else if sender.tag == 2{
storyTextView.text = story4
}
depth += 1
}else if depth == 1 && storyTextView.text == storyThree.story{
if(sender.tag == 1 ){
storyTextView.text = story6
}else if (sender.tag == 2){
storyTextView.text = story5
}
depth += 1
}else if depth == 2 && storyTextView.text == storyThree.story{
if sender.tag == 1{
storyTextView.text = story6
}else if sender.tag == 2{
storyTextView.text = story5
}
depth += 1
}else{
showRestartAlert()
depth = 0
}
}
//Operations to do if story restarted
func startOver(){
storyTextView.text = storyOne.story
topButton.setTitle(storyOne.answer1, for: .normal)
bottomButton.setTitle(storyOne.answer2, for: .normal)
}
//Set up the UI with story 1 + Options
func storyOneScreen(){
storyTextView.text = storyOne.story;
topButton.setTitle(storyOne.answer1, for: .normal)
bottomButton.setTitle(storyOne.answer2, for: .normal)
}
//Set up the UI with story 2 + Options
func storyTwoScreen(){
storyTextView.text = storyTwo.story;
topButton.setTitle(storyTwo.answer1, for: .normal)
bottomButton.setTitle(storyTwo.answer2, for: .normal)
}
//Set up the UI with story 3 + Options
func storyThreeScreen(){
storyTextView.text = storyThree.story;
topButton.setTitle(storyThree.answer1, for: .normal)
bottomButton.setTitle(storyThree.answer2, for: .normal)
}
//Alert that prompts user if they want to restart the story
func showRestartAlert(){
let alert = UIAlertController(title: "The End", message: "Your story has ended, do you want to start over? ", preferredStyle: .alert)
let restartAction = UIAlertAction(title: "Restart", style: .default) { (UIAlertAction) in
self.startOver()
}
alert.addAction(restartAction)
present(alert, animated: true, completion: nil)
}
}
|
//
// DefinitionViewController.swift
// SwiftVocabulary
//
// Created by Casualty on 7/24/19.
// Copyright © 2019 Thomas Dye. All rights reserved.
//
import UIKit
class DefinitionViewController: UIViewController {
// Create var cellWord of optional type VocabularyWord
// We are using cellWord to load the definition page with the word, definition, and example
var cellWord: VocabularyWord?
override func viewDidLoad() {
super.viewDidLoad()
updateView()
}
func updateView() {
if let cellWord = cellWord {
title = cellWord.word
wordLabel.text = cellWord.word
wordDefinitionTextView.text = cellWord.definition
wordExampleLabel.text = cellWord.example
}
}
@IBOutlet weak var wordLabel: UILabel!
@IBOutlet weak var wordDefinitionTextView: UITextView!
@IBOutlet weak var wordExampleLabel: UILabel!
}
|
//
// CustomButton.swift
// FirebaseAuthenticationExample
//
// Created by Luis Manuel Ramirez Vargas on 19/07/17.
// Copyright © 2017 Luis Manuel Ramirez Vargas. All rights reserved.
//
import UIKit
@IBDesignable
class CustomButton: UIButton {
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
}
|
//
// TopinInfoApi.swift
// TemplateSwiftAPP
//
// Created by wenhua on 2018/9/2.
// Copyright © 2018年 wenhua yu. All rights reserved.
//
import Foundation
class TopicInfo_Get: BaseRestApi {
var topic: Topic = Topic()
init(topicID: String) {
super.init(url: "topic/info?topicID=\(topicID)", httpMethod: .HttpMethods_Get)
}
override func parseResponseJsonString(json: Data) -> Bool {
if let result = try? JSONDecoder().decode(Topic.self, from: json) {
// 解析成功,赋值给:users对象
self.topic = result
return true;
}
return false
}
override func mockFile() -> String {
return "topicInfo"
}
override func mockType() -> MockType {
return .MockFile
}
}
|
//
// WADetailsService.swift
// WatchApp
//
// Created by Marcio Mortarino on 27/06/2019.
// Copyright © 2019 Marcio Mortarino. All rights reserved.
//
import UIKit
class WADetailsService: WABaseService<[WADetailsModel]> {
let serviceUri = "?api_key=76334afb9cfc0e241f3252ee50d98c41&language=en-US"
init(movieId: Int, _ video: Bool = false) {
super.init()
if !video {
path = String(format: "%@" + serviceUri, String(movieId))
} else {
path = String(format: "%@" + "/videos" + serviceUri, String(movieId))
}
}
}
|
//
// SWBEditTableViewController.swift
// SweepBright
//
// Created by Kaio Henrique on 4/5/16.
// Copyright © 2016 madewithlove. All rights reserved.
//
import Foundation
class SWBEditTableViewController: PropertyTableViewController {
override var cellNib: UINib! {
return UINib(nibName: "SWBEditPropertyCell", bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(showProperty), name: SWBNewPropertyAddedNotification.newPropertyNotificationName, object: nil)
}
func showProperty(notification: NSNotification) {
if let id = notification.object as? PropertyID, let property = self.realm.objectForPrimaryKey(SWBPropertyModel.self, key: id) {
self.selectedProperty = property
self.performSegueWithIdentifier("OverviewSegue", sender: nil)
}
}
}
|
//
// global.swift
// sample_test
//
// Created by Catalina Diaz on 12/17/19.
// Copyright © 2019 CleverSolve. All rights reserved.
//
import Foundation
import UIKit
import Firebase
extension UIViewController{
func navPush(Storyboard: String, Identifier: String)
{
let storyboard: UIStoryboard = UIStoryboard(name: Storyboard, bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: Identifier)
self.navigationController?.pushViewController(vc, animated: false)
}
func navPop()
{
self.navigationController?.popViewController(animated: true)
}
}
var list_animals: [animals] = []
|
//
// ConfigExtension.swift
// RijksMuseumApp
//
// Created by Alexandre Mantovani Tavares on 17/05/20.
//
import Foundation
extension Config {
static func fromBundle() -> Self {
guard let path = Bundle.main.path(forResource: "config", ofType: "json") else {
fatalError("config.json file not found")
}
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path))
return try JSONDecoder().decode(Config.self, from: data)
} catch {
fatalError("\(error)")
}
}
func localizedHost(from locale: Locale = .current) -> String {
let currentLanguage = locale.languageCode
.flatMap { language in
availableLanguages.contains(language) ? language : nil
}
return host + "/\(currentLanguage ?? defaultLanguage)"
}
}
|
//
// USCommentTableViewCell.swift
// Usth System
//
// Created by Serx on 2017/5/29.
// Copyright © 2017年 Serx. All rights reserved.
//
import UIKit
import SnapKit
@objc protocol USCommentTableViewCellDelegate: NSObjectProtocol {
@objc optional func commentTableViewCell(commentCell: USCommentTableViewCell, didClickReplyBtn: UIButton)
@objc optional func commentTableViewCell(commentCell: USCommentTableViewCell, didClickDiggBtn: UIButton)
@objc optional func commentTableViewCellTapHeader(commentCell: USCommentTableViewCell)
}
let commentCellMinHeight: CGFloat = 64.0
let replyCommentShorterThanCommentWidth: CGFloat = 22.0
let commentTextViewShorterThanCellWidth: CGFloat = 66.0
class USCommentTableViewCell: UITableViewCell {
weak var delegate: USCommentTableViewCellDelegate?
private var _headerImgView: UIImageView?
private var _publishTimeLab: UILabel?
private var _replyBtn: UIButton?
private var _diggBtn: UIButton?
private var _diggNumLab: UILabel?
private var _commentTextView: UITextView?
private var _replyCommentTextView: UITextView?
var commentWidth: Float? = 0.0
var replyCommentWidth: Float? = 0.0
//MARK: - ------Life Circle------
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
self.contentView.addSubview(self.headerImgView!)
self.contentView.addSubview(self.commentTextView!)
self.contentView.addSubview(self.replyCommentTextView!)
self.contentView.addSubview(self.publishTimeLab!)
self.contentView.addSubview(self.diggBtn!)
self.contentView.addSubview(self.diggNumLab!)
self.contentView.addSubview(self.replyBtn!)
self.layoutPageSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
//MARK: - ------Methods------
func layoutPageSubviews() {
let line = UIView()
line.backgroundColor = UIColor.lineGray()
self.contentView.addSubview(line)
line.snp.makeConstraints { (make) in
make.height.equalTo(0.5)
make.left.right.bottom.equalTo(self.contentView)
}
self.headerImgView!.snp.makeConstraints { (make) in
make.height.width.equalTo(50.0)
make.top.left.equalTo(self.contentView).offset(10.0)
}
self.commentTextView!.snp.makeConstraints { (make) in
make.left.equalTo(self.headerImgView!.snp.right).offset(10.0)
make.top.equalTo(self.contentView).offset(10.0)
make.right.equalTo(self.contentView).offset(-15.0)
make.height.equalTo(10.0)
}
self.replyCommentTextView!.snp.makeConstraints { (make) in
make.top.equalTo(self.commentTextView!.snp.bottom)
make.right.equalTo(self.contentView).offset(-15.0)
make.left.equalTo(self.commentTextView!).offset(replyCommentShorterThanCommentWidth)
make.height.equalTo(10.0)
}
self.publishTimeLab!.snp.makeConstraints { (make) in
make.left.equalTo(self.commentTextView!)
make.bottom.equalTo(self.contentView).offset(-6.0)
make.right.equalTo(self.diggBtn!.snp.left)
make.height.equalTo(22.0)
}
self.replyBtn!.snp.makeConstraints { (make) in
make.right.equalTo(self.contentView).offset(-10.0)
make.width.equalTo(30.0)
make.height.equalTo(24.0)
make.centerY.equalTo(self.publishTimeLab!.snp.centerY)
}
self.diggNumLab!.snp.makeConstraints { (make) in
make.width.equalTo(30.0)
make.height.equalTo(17.0)
make.right.equalTo(self.replyBtn!.snp.left)
make.centerY.equalTo(self.publishTimeLab!.snp.centerY)
}
self.diggBtn!.snp.makeConstraints { (make) in
make.width.height.equalTo(15.0)
make.right.equalTo(self.diggNumLab!.snp.left).offset(-3.0)
make.centerY.equalTo(self.publishTimeLab!.snp.centerY)
}
}
func setCommentTextView(authorName: String, commentStr: String) {
self.layoutIfNeeded()
let width = self.commentTextView?.bounds.size.width
let rect = self.commentTextView?.commentTextViewAttributedText(withCommentStr: commentStr, andAuthorName: authorName, withWidth: width!)
self.commentTextView!.snp.updateConstraints { (make) in
make.height.equalTo(ceilf(Float(rect!.height + 10.0)))
}
}
func setReplyCommentTextView(authorName: String, commentStr: String) {
self.layoutIfNeeded()
let width = self.replyCommentTextView?.bounds.size.width
let rect = self.replyCommentTextView?.commentTextViewAttributedText(withCommentStr: commentStr, andAuthorName: authorName, withWidth: width!)
self.replyCommentTextView!.snp.updateConstraints { (make) in
make.height.equalTo(ceilf(Float(rect!.height + 10.0)))
}
}
static func getCellHeight(commentData: USComment?) -> CGFloat {
var cellHeight: CGFloat = 10.0 + 10.0 + 25.0 + 10.0
let commentRect = UITextView.commentTextViewAttributedText(withCommentStr: commentData!.content, andAuthorName: commentData!.authorName, withWidth: SCREEN_WIDTH - commentTextViewShorterThanCellWidth)
cellHeight = cellHeight + CGFloat(ceilf(Float(commentRect.height)))
if (!commentData!.refedContent.isEmpty) {
let commentRect = UITextView.commentTextViewAttributedText(withCommentStr: commentData!.refedContent, andAuthorName: commentData?.refedAuthor, withWidth: SCREEN_WIDTH - commentTextViewShorterThanCellWidth - replyCommentShorterThanCommentWidth)
cellHeight = cellHeight + CGFloat(ceilf(Float(commentRect.height))) + 10.0
}
return cellHeight > commentCellMinHeight ? cellHeight : commentCellMinHeight
}
func diggNumLabSizeToFit() {
self.diggNumLab!.sizeToFit()
self.diggNumLab!.snp.updateConstraints { (make) in
make.width.equalTo(self.diggNumLab!.bounds.size.width)
}
}
//MARK: - ------Delegate View------
//MARK: - ------Delegate Model------
//MARK: - ------Delegate Table------
//MARK: - ------Delegate Other------
//MARK: - ------Event Response------
func replyBtnDidClick(button: UIButton) {
self.delegate?.commentTableViewCell!(commentCell: self, didClickReplyBtn: button)
}
func diggBtnDidClick(button: UIButton) {
self.delegate?.commentTableViewCell!(commentCell: self, didClickDiggBtn: button)
}
func headerImgDidTap(gesture: UITapGestureRecognizer) {
self.delegate?.commentTableViewCellTapHeader!(commentCell: self)
}
//MARK: - ------Getters and Setters------
var headerImgView: UIImageView? {
get {
if (_headerImgView != nil) {
return _headerImgView
}
let imgView = UIImageView()
imgView.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(self.headerImgDidTap(gesture:)))
imgView.addGestureRecognizer(tapGesture)
_headerImgView = imgView
return _headerImgView
}
}
var publishTimeLab: UILabel? {
get {
if (_publishTimeLab != nil) {
return _publishTimeLab
}
let label = UILabel()
label.backgroundColor = UIColor.clear
label.textColor = UIColor.myinforGray()
label.font = UIFont.systemFont(ofSize: 12.0)
_publishTimeLab = label
return _publishTimeLab
}
}
var replyBtn: UIButton? {
get {
if (_replyBtn != nil) {
return _replyBtn
}
let button = UIButton()
button.addTarget(self, action: #selector(self.replyBtnDidClick(button:)), for: .touchUpInside)
button.setImage(UIImage.init(named: "replyIcon"), for: .normal)
_replyBtn = button
return _replyBtn
}
}
var diggBtn: UIButton? {
get {
if (_diggBtn != nil) {
return _diggBtn
}
let button = UIButton()
button.addTarget(self, action: #selector(self.diggBtnDidClick(button:)), for: .touchUpInside)
button.setImage(UIImage.init(named: "blackHeart"), for: .normal)
_diggBtn = button
return _diggBtn
}
}
var diggNumLab: UILabel? {
get {
if (_diggNumLab != nil) {
return _diggNumLab
}
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 12.0)
label.textAlignment = .left
_diggNumLab = label
return _diggNumLab
}
}
var commentTextView: UITextView? {
get {
if (_commentTextView != nil) {
return _commentTextView
}
let textView = UITextView()
//textView.backgroundColor = UIColor.orange
textView.isScrollEnabled = false
textView.showsVerticalScrollIndicator = false
textView.showsHorizontalScrollIndicator = false
textView.isEditable = false
textView.isSelectable = false
textView.isUserInteractionEnabled = false
_commentTextView = textView
return _commentTextView
}
}
var replyCommentTextView: UITextView? {
get {
if (_replyCommentTextView != nil) {
return _replyCommentTextView
}
let textView = UITextView()
textView.backgroundColor = UIColor.lightGray
textView.isScrollEnabled = false
textView.showsVerticalScrollIndicator = false
textView.showsHorizontalScrollIndicator = false
textView.isEditable = false
textView.isSelectable = false
textView.isUserInteractionEnabled = false
textView.layer.cornerRadius = 2.0
_replyCommentTextView = textView
return _replyCommentTextView
}
}
//MARK: - ------Serialize and Deserialize------
}
|
//
// Extensions.swift
// Coding Challange
//
// Created by Faisal Ikwal on 20/11/18.
// Copyright © 2018 Exilant Technologies. All rights reserved.
//
import Foundation
extension String {
func character(at position: Int) -> Character? {
//MARK: Recap
guard
position >= 0,
let indexPostition = index(startIndex, offsetBy: position, limitedBy: endIndex)
else { return nil }
return self[indexPostition]
}
}
extension Bundle {
static func urlFor(filename: String) -> URL? {
let pathArray = filename.components(separatedBy: ".")
return Bundle.main.url(forResource: pathArray[safe: 0] ?? "", withExtension: pathArray[safe: 1] ?? "")
}
}
extension FileManager {
static var documentDirectory: URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
}
}
extension BinaryInteger {
var onesCount: Int {
return String(self, radix: 2).reduce(0) { $1 == "1" ? $0 + 1 : $0 }
}
}
extension MutableCollection where Index == Int {
subscript(safe index: Index) -> Element? {
guard self.count > index else { return nil }
return self[index]
}
}
extension Collection where Element == Int, Index == Int {
func count(of char: Character) -> Int {
/*return reduce(0) {
$0 + String($1).filter { $0 == char }.count
}*/
//return NSCountedSet(array: Array(map(String.init).joined())).count(for: char)
var count = 0
forEach {
for c in String($0) {
guard c == char else { continue }
count += 1
}
}
return count
}
var median: Double? {
guard count != 0 else { return nil }
let middle = count / 2
if count % 2 == 0 {
return Double((self[middle - 1] + self[middle]) / 2)
} else {
return Double(self[middle])
}
}
}
extension Collection where Element == String {
var sortedByElementLength: [String] {
return sorted { $0.count > $1.count }
}
}
extension Collection where Element: Comparable {
func sorted(count: Int) -> [Element] {
return Array(self.sorted().prefix(count))
}
func myMin() -> Element? {
guard self.count > 0 else { return nil }
return reduce(first!) { $0 < $1 ? $0 : $1 }
}
}
extension Collection where Element: Equatable {
func indexOf(_ searchitem: Element) -> Int? {
for (index, item) in self.enumerated() {
if item == searchitem {
return index
}
}
return nil
}
}
extension Collection {
func myMap<T>(_ transform: (Element) throws -> T) rethrows -> [T] {
var result = [T]()
for item in self {
result.append(try transform(item))
}
return result
}
}
extension Array where Element: Comparable {
func bubbleSorted() -> [Element] {
guard count > 1 else { return self }
var result = self
/*for i in 0 ..< count-1 {
for j in 0 ..< count-i-1 {
if result[j] > result[j+1] {
result.swapAt(j+1, j)
}
}
}
return result*/
var isSwapped = false
var sortedCount = 0
repeat {
isSwapped = false
for index in 1..<count-sortedCount {
if result[index-1] > result[index] {
result.swapAt(index-1, index)
isSwapped = true
}
}
sortedCount += 1
} while isSwapped
return result
}
func insertionSorted() -> [Element] {
guard count > 1 else { return self }
var result = self
for index in 1..<count {
let currentValue = result[index]
for i in (0..<index).reversed() {
if currentValue < result[i] {
result.swapAt(i, i+1)
}
}
}
return result
}
//O(N^2)
func quickSorted() -> [Element] {
guard count > 1 else { return self }
let pivot = self[count/2]
let lesserThanPivot = filter { $0 < pivot }
let equalToPivot = filter { $0 == pivot }
let greaterThanPivot = filter { $0 > pivot }
return lesserThanPivot.quickSorted() + equalToPivot + greaterThanPivot.quickSorted()
}
mutating func qSort() {
self.quickSort(left: 0, right: count-1)
}
mutating func quickSort(left: Int, right: Int) {
guard left < right else { return }
let pivot = self[right]
var splitPoint = left
for i in left ..< right {
if self[i] < pivot {
swapAt(i, splitPoint)
splitPoint += 1
}
}
swapAt(right, splitPoint)
quickSort(left: left, right: splitPoint - 1)
quickSort(left: splitPoint + 1, right: right)
}
}
|
//
// ViewController.swift
// Financial App
//
// Created by BS126 on 11/7/18.
// Copyright © 2018 BS23. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var centerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//self.centerView.layer.cornerRadius = self.centerView.frame.size.width / 2
//self.centerView.layer.cornerRadius = self.centerView.frame.size.height / 2
//self.centerView.layer.masksToBounds = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let width: CGFloat = self.view.bounds.width
let height: CGFloat = self.view.bounds.height / 2 + 100
let upperTransparentView = UpperTransparentView(frame: CGRect(x: 0, y: 0, width: width, height: height))
self.view.addSubview(upperTransparentView)
}
}
|
//
// Constants.swift
// ImageGallery
//
// Created by Anum Qudsia on 26/07/2017.
// Copyright © 2017 anum.qudsia. All rights reserved.
//
import Foundation
struct Constants {
static let feed = "feed"
static let entry = "entry"
static let title = "title"
static let link = "link"
static let href = "href"
static let rel = "rel"
static let enclosure = "enclosure"
static let category = "category"
static let scheme = "scheme"
static let tagsUrl = "https://www.flickr.com/photos/tags/"
static let imageUrl = "imageUrl"
static let tags = "tags"
static let image = "image"
static let term = "term"
}
struct Entity {
static let FlickrImage = "FlickrImage"
}
struct Failed {
static let getImageData = "Failed to get image data from url"
static let saveImage = "Error saving flickrImage entity"
static let fetchImages = "Failed to fetch images"
static let deleteImages = "Failed to delete all images"
static let toParse = "Failed to parse "
static let toCreateURL = "Failed to create URL from "
}
struct Success {
static let imageSaved = "Saved FlickrImage sucessfully"
}
|
//
// ViewController.swift
// QLPreviewSample
//
// Created by Aikawa Kenta on 2020/07/11.
// Copyright © 2020 Aikawa Kenta. All rights reserved.
//
import UIKit
import QuickLook
// 以下のサイトからリソースを使用させて頂いています
// https://www.irasutoya.com/
// http://onocom.net/blog/public-domain-sample-file/#i-2
// https://maoudamashii.jokersounds.com/archives/bgm_maoudamashii_fantasy15.html
class ViewController: UIViewController {
let previewItemNameList = [("food_kani_guratan_koura", "png"),
("movie_refuban_man", "png"),
("music_castanet_girl", "png"),
("school_tsuugaku_woman", "png"),
("syoujou_kaikinsyou", "png"),
("bgm_maoudamashii_fantasy15", "mp3"),
("sample-pdf", "pdf")]
var previewItemURLList: [URL] {
let itemURLList = previewItemNameList.map { Bundle.main.url(forResource: $0.0, withExtension: $0.1)! }
return itemURLList
}
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func goToPreview(_ sender: Any) {
let previewController = QLPreviewController()
previewController.dataSource = self
previewController.delegate = self
present(previewController, animated: true)
}
}
extension ViewController: QLPreviewControllerDataSource {
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return previewItemURLList.count
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return previewItemURLList[index] as QLPreviewItem
}
}
extension ViewController: QLPreviewControllerDelegate {
func previewControllerDidDismiss(_ controller: QLPreviewController) {
let alert = UIAlertController(title: "DidDismiss", message: nil, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
present(alert, animated: true)
}
}
|
//
// DoMeditationVC.swift
// Meditation App
//
// Created by Burhanuddin Shakir on 07/10/18.
// Copyright © 2018 meditation-app. All rights reserved.
//
import UIKit
import AVFoundation
class DoMeditationVC: UIViewController, UIGestureRecognizerDelegate {
@IBOutlet weak var meditationImage : UIImageView!
@IBOutlet weak var homeBtn : UIButton!
@IBOutlet weak var nextBtn : UIButton!
@IBOutlet weak var muteBtn : UIButton!
public var meditation : Meditation!
var meditationImageAsset : UIImage! = nil
var meditationSetting : String!
var isSongAllowed : Bool = true;
var meditationSoundEffect: AVAudioPlayer?
// Default timer for Chakra Cuning meditations
var timer = 120
// Default value for landscape settings
var isLandscapeLockEnabled = true
// Selected Meditation of Image
var selectedMeditationIndex = 0
var meditationTime : Date!
var isButtonsDisplayed : Bool = false
var isMute : Bool = false
var imageBtnTapTimer : Timer?
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
meditationTime = Date()
meditationImageAsset = UIImage(named: meditation.subMeditations[meditation.selectedMeditationIndex].imageName)!
// Play song even if silent (hardware) switch is on
do
{
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: .defaultToSpeaker)
}
catch
{
// report for an error
}
loadSettings()
// Add Gesture to dismiss image
addGestures()
//Storing latest meditation
storeLatestMeditationUserDefaults()
// TODO:- Show next and home button on Source Code Meditations
}
// MARK:- Loading and saving settings
func storeLatestMeditationUserDefaults()
{
// Setting latest meditation name
UserDefaults.standard.set(meditation.title, forKey: UserDefaultKeyNames.LatestMeditation.meditationName)
// Setting latest meditation desc
UserDefaults.standard.set(meditation.description, forKey: UserDefaultKeyNames.LatestMeditation.meditationDescription)
// Storing Meditation Streak
let todaysDate = Date()
var lastMeditationDate = UserDefaults.standard.object(forKey: UserDefaultKeyNames.LatestMeditation.meditationDate) as? Date
var meditationStreak = UserDefaults.standard.integer(forKey: UserDefaultKeyNames.LatestMeditation.meditationStreak)
if lastMeditationDate != nil
{
// Checking if the meditation dates are consecutive
let diff = todaysDate.interval(ofComponent: .day, fromDate: lastMeditationDate!)
// If dates are consecutive, increase the counter else set the counter to 1
if diff == 1
{
meditationStreak = meditationStreak + 1
}
else
{
meditationStreak = 1
}
}
else
{
// Storing the counter for the first time
meditationStreak = 1
}
lastMeditationDate = todaysDate
// Storing the latest values for streak
UserDefaults.standard.set(lastMeditationDate, forKey: UserDefaultKeyNames.LatestMeditation.meditationDate)
UserDefaults.standard.set(meditationStreak, forKey: UserDefaultKeyNames.LatestMeditation.meditationStreak)
}
func loadSettings()
{
if(meditation.title.contains("Chakra Cuning"))
{
meditationSetting = UserDefaultKeyNames.Settings.chakraCuningSetting
}
else if(meditation.title.contains("Source Code"))
{
meditationSetting = UserDefaultKeyNames.Settings.sourceCodeSetting
}
else
{
meditationSetting = UserDefaultKeyNames.Settings.gspaceSetting
}
var settings = UserDefaults.standard.dictionary(forKey: meditationSetting)
if(settings != nil)
{
if (settings!["music"] as! Bool)
{
playSong()
isMute = false
}
else
{
isMute = true
}
if(settings!["landscape"] as! Bool)
{
isLandscapeLockEnabled = true
}
else
{
isLandscapeLockEnabled = false
}
displayImageBasedOnSetting()
timer = settings!["timer"] as! Int
}
else // If no settings present set everything as default
{
// Music will be played by default
playSong()
// Orientation will be checked by default
checkForOrientation()
}
var _ = Timer.scheduledTimer(timeInterval: TimeInterval(timer), target: self, selector: #selector(DoMeditationVC.changeImageBasedOnTimer), userInfo: nil, repeats: true)
}
func storeMeditationTime(timeDone : TimeInterval)
{
//Storing time
var meditationTimeUserDefaults = [String : Any]()
if(UserDefaults.standard.dictionary(forKey: UserDefaultKeyNames.MeditationTime.totalMeditationTime) != nil)
{
meditationTimeUserDefaults = UserDefaults.standard.dictionary(forKey: UserDefaultKeyNames.MeditationTime.totalMeditationTime)!
}
var totalMeditationTime: TimeInterval = timeDone
if(meditationTimeUserDefaults[UserDefaultKeyNames.MeditationTime.time] != nil)
{
totalMeditationTime = totalMeditationTime.advanced(by: meditationTimeUserDefaults[UserDefaultKeyNames.MeditationTime.time] as! TimeInterval)
}
meditationTimeUserDefaults[UserDefaultKeyNames.MeditationTime.time] = totalMeditationTime
// Storing frequency
var totalMeditationDone = 1
if(meditationTimeUserDefaults[UserDefaultKeyNames.MeditationTime.total] != nil)
{
totalMeditationDone = meditationTimeUserDefaults[UserDefaultKeyNames.MeditationTime.total] as! Int + 1
}
meditationTimeUserDefaults[UserDefaultKeyNames.MeditationTime.total] = totalMeditationDone
//Storing count for meditation type
if(meditationSetting.contains("Cuning"))
{
let count : Int? = meditationTimeUserDefaults[UserDefaultKeyNames.MeditationTime.chakraCuning] as? Int ?? 0
meditationTimeUserDefaults[UserDefaultKeyNames.MeditationTime.chakraCuning] = count! + 1
}
else if(meditationSetting.contains("Space"))
{
let count : Int? = meditationTimeUserDefaults[UserDefaultKeyNames.MeditationTime.gSpace] as? Int ?? 0
meditationTimeUserDefaults[UserDefaultKeyNames.MeditationTime.gSpace] = count! + 1
}
else
{
let count : Int? = meditationTimeUserDefaults[UserDefaultKeyNames.MeditationTime.sourceCode] as? Int ?? 0
meditationTimeUserDefaults[UserDefaultKeyNames.MeditationTime.sourceCode] = count! + 1
}
UserDefaults.standard.set(meditationTimeUserDefaults, forKey: UserDefaultKeyNames.MeditationTime.totalMeditationTime)
}
// MARK:- Gestures
func addGestures()
{
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(dismissScreen))
swipe.direction = .down
self.view.addGestureRecognizer(swipe)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped))
meditationImage.isUserInteractionEnabled = true
meditationImage.addGestureRecognizer(tapGestureRecognizer)
}
@objc func imageTapped()
{
if(isButtonsDisplayed)
{
doHide(view: homeBtn, hidden: true)
doHide(view: nextBtn, hidden: true)
doHide(view: muteBtn, hidden: true)
}
else
{
doHide(view: homeBtn, hidden: false)
// Show next button only if more images are left
if(selectedMeditationIndex < meditation.subMeditations.count - 1)
{
doHide(view: nextBtn, hidden: false)
}
doHide(view: muteBtn, hidden: false)
setTimerForButtonsToHide()
}
isButtonsDisplayed = !isButtonsDisplayed
}
func setTimerForButtonsToHide()
{
imageBtnTapTimer = Timer.scheduledTimer(timeInterval: TimeInterval(5), target: self, selector: #selector(DoMeditationVC.hideBtnsAfterTap), userInfo: nil, repeats: true)
}
// Hide/Show button with animation
func doHide(view: UIView, hidden: Bool)
{
UIView.transition(with: view, duration: 0.5, options: .transitionCrossDissolve, animations:
{
view.isHidden = hidden
})
}
@objc func dismissScreen()
{
// Stopping song
stopSong()
let meditationEnd = Date()
let executionTime = meditationEnd.timeIntervalSince(meditationTime)
// Storing time of meditation
storeMeditationTime(timeDone: executionTime)
// Adding animation
let transition: CATransition = CATransition()
transition.duration = 0.5
transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeIn)
transition.type = CATransitionType.reveal
transition.subtype = CATransitionSubtype.fromBottom
self.view.window!.layer.add(transition, forKey: nil)
self.navigationController?.popViewController(animated: false)
self.dismiss(animated: false, completion: nil)
}
// MARK:- IBActions
@IBAction func homePressed(_ sender: Any)
{
dismissScreen()
}
@IBAction func nextPressed(_ sender: Any)
{
changeImageBasedOnTimer()
deleteButtonTapTimer()
setTimerForButtonsToHide()
}
@IBAction func muteBtnPressed(_ sender: Any)
{
// If mute pressed
if isMute == false
{
muteBtn.setImage(UIImage(named: "speaker"), for: .normal)
stopSong()
isMute = true
}
else
{
muteBtn.setImage(UIImage(named: "mute"), for: .normal)
playSong()
isMute = false
}
deleteButtonTapTimer()
setTimerForButtonsToHide()
}
// MARK:- Meditation Image Display
private func displayImageBasedOnSetting()
{
if(isLandscapeLockEnabled)
{
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
displayImageInLandscape()
}
else
{
checkForOrientation()
}
}
override var shouldAutorotate: Bool {
if(isLandscapeLockEnabled)
{
return true
}
return false
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if(isLandscapeLockEnabled)
{
return .landscapeLeft
}
return .portrait
}
// On Orientation Changed
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)
{
super.viewWillTransition(to: size, with: coordinator)
displayImageBasedOnSetting()
}
private func checkForOrientation()
{
if UIDevice.current.orientation.isLandscape
{
displayImageInLandscape()
}
else
{
displayImageInPortrait()
}
}
// TODO:- The half part of image is not being displayed
private func displayImageInPortrait()
{
let imageSizeForPortrait = CGRect(x: 0.0, y: 0.0, width: meditationImageAsset.size.width, height: meditationImageAsset.size.height * 2)
var cgImageMeditation = meditationImageAsset.cgImage
cgImageMeditation = cgImageMeditation?.cropping(to: imageSizeForPortrait)
let result: UIImage = UIImage(cgImage: cgImageMeditation!, scale: 0.0, orientation: meditationImageAsset.imageOrientation)
setImage(image: result, orientation: "portrait")
}
private func displayImageInLandscape()
{
//Displaying image as is
setImage(image: meditationImageAsset, orientation: "landscape")
}
private func setImage(image : UIImage, orientation : String)
{
// Resizing image based on screen size
let resizedImage = image.resizeImageWith(viewSize: meditationImage.frame.size, orientation: orientation)
UIView.transition(with: self.meditationImage,
duration: 0.75,
options: .transitionCrossDissolve,
animations: { self.meditationImage.image = resizedImage },
completion: nil)
}
@objc private func changeImageBasedOnTimer()
{
if(selectedMeditationIndex < meditation.subMeditations.count - 1)
{
meditationImageAsset = UIImage(named: meditation.subMeditations[selectedMeditationIndex+1].imageName)!
displayImageBasedOnSetting()
selectedMeditationIndex = selectedMeditationIndex + 1
}
else
{
dismissScreen()
}
}
@objc private func hideBtnsAfterTap()
{
doHide(view: homeBtn, hidden: true)
doHide(view: nextBtn, hidden: true)
doHide(view: muteBtn, hidden: true)
deleteButtonTapTimer()
isButtonsDisplayed = !isButtonsDisplayed
}
func deleteButtonTapTimer()
{
if imageBtnTapTimer != nil
{
imageBtnTapTimer?.invalidate()
imageBtnTapTimer = nil
}
}
// MARK:- Play Audio File
private func playSong()
{
guard let url = Bundle.main.url(forResource: "spaceambientmix", withExtension: "mp3") else { return }
do
{
meditationSoundEffect = try AVAudioPlayer(contentsOf: url)
guard let meditationSound = meditationSoundEffect else { return }
meditationSound.prepareToPlay()
meditationSound.play()
}
catch let error
{
print(error.localizedDescription)
}
}
private func stopSong()
{
if(meditationSoundEffect != nil)
{
meditationSoundEffect?.stop()
}
}
// TODO:- Add watery animation on the meditation screen
}
|
//
// ModelsTableViewController.swift
// ARToolkitAppDemo
//
// Created by Andrey Vasilev on 22.03.2018.
// Copyright © 2018 Quentin Fasquel. All rights reserved.
//
import UIKit
class ModelsTableViewController: UITableViewController {
let models = ["car.dae",
"car.scn",
"candle.scn",
"vase.scn",
"lamp.scn",
"cup.scn",
"chair.scn"]
var selectedModel: String?
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return models.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
cell.textLabel?.text = models[indexPath.row]
return cell
}
// MARK: - Navigation
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedModel = models[indexPath.row]
self.performSegue(withIdentifier: "segue", sender: nil)
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let controller = segue.destination as? KitsTableViewController, let model = selectedModel {
controller.modelName = model
}
}
}
|
//
// PaymentMethod.swift
// Driveo
//
// Created by Admin on 6/6/18.
// Copyright © 2018 ITI. All rights reserved.
//
import Foundation
public struct PaymentMethods: Codable {
let paymentMethods: [PaymentMethod]?
let message: String?
enum CodingKeys: String, CodingKey {
case paymentMethods = "Payment_methods"
case message
}
}
public struct PaymentMethod {
var id: Int?
var name: String?
var image: Image?
var isSelected: Bool = false
init() {}
}
// MARK : Encoding and Decoding
extension PaymentMethod : Codable {
enum CodingKeys: String, CodingKey {
case id
case name
case image
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
name = try container.decode(String.self, forKey: .name)
image = try container.decode(Image.self, forKey: .image)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encode(name, forKey: .name)
try container.encode(image, forKey: .image)
}
}
|
import Cocoa
import Quick
import Nimble
import Paranormal
import Foundation
class AppDelegateTests: QuickSpec {
override func spec() {
describe("AppDelegate") {
describe("applicationDidLoad") {
func editDoesNotContainString(name : String) {
let sharedApp = NSApplication.sharedApplication()
let emptyNotification = NSNotification(name: "Blank", object: nil)
let delegate = sharedApp.delegate as AppDelegate
delegate.applicationDidFinishLaunching(emptyNotification)
let edit = NSApplication.sharedApplication().mainMenu?.itemWithTitle("Edit")
let submenu = edit?.submenu;
for item in submenu!.itemArray {
let cast_item = item as NSMenuItem
expect(cast_item.title).toNot(contain(name))
}
}
it("Menu bar does not have the 'Edit --> Start Dictation' item") {
editDoesNotContainString("Start Dictation")
}
it("Menu bar does not have 'Edit --> Special Characters' item") {
editDoesNotContainString("Special Characters")
}
}
}
}
}
|
//
// Comparable+Mimik.swift
// Mimik
//
// Created by Mike MacDougall on 7/26/18.
//
import Foundation
public extension Comparable {
/// Passes receiver into `action` closure and will return
/// itself if condition is met
///
/// - Parameter action: Closure with receiver as argument
/// - Returns: Receiver if condition is met
func takeIf<T: Comparable>(_ action: ((T) -> Bool)) -> T? {
guard let safeSelf = self as? T else { return nil }
if (action(safeSelf)) {
return self as? T
}
return nil
}
/// Passes receiver into `action` closure and will return
/// itself if condition is not met
///
/// - Parameter action: Closure with receiver as argument
/// - Returns: Receiver if condition is not met
func takeUnless<T: Comparable>(_ action: ((T) -> Bool)) -> T? {
return takeIf {
!action($0)
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.