text stringlengths 8 1.32M |
|---|
//
// ItemCreatingController.swift
// Inventory Management System
//
// Created by 邱凯 on 24/8/19.
// Copyright © 2019 MountainPeak. All rights reserved.
//
import Foundation
import UIKit
class ItemCreatingController: UIViewController{
let userDefaults = UserDefaults.standard
var name:String = ""
var price:Float = 0.0
var amount:Int = 0
@IBOutlet weak var barcodeTextField: UITextField!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var priceTextField: UITextField!
@IBOutlet weak var amountLabel: UILabel!
@IBOutlet weak var totalPriceLabel: UILabel!
@IBOutlet weak var backBtn: UIButton!
@IBOutlet weak var saveBtn: UIButton!
@IBOutlet weak var slider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
backBtn.layer.cornerRadius = 4
saveBtn.layer.cornerRadius = 4
setupTextFields_Barcode()
setupTextFields_Name()
setupTextFields_Price()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(true)
userDefaults.setValue("", forKey: "newBarcode")
}
//This would show a Done button when user click the BarcodeTextField
func setupTextFields_Barcode() {
let toolbar = UIToolbar(frame: CGRect(origin: .zero, size: .init(width: view.frame.size.width, height: 30)))
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneBtn = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(doneButtonAction_Barcode))
toolbar.setItems([flexSpace, doneBtn], animated: false)
toolbar.sizeToFit()
barcodeTextField.inputAccessoryView = toolbar
}
@objc func doneButtonAction_Barcode(){
self.view.endEditing(true)
}
@IBAction func barcodeTextFieldOnEndEditing(_ sender: Any) {
if(!barcodeValidation()){
barcodeTextFieldAlert()
barcodeTextField.text = ""
barcodeTextField.becomeFirstResponder()
}
}
private func barcodeValidation() -> Bool {
let checker:String = "1234567890"
let checkString:String = barcodeTextField.text!
for char in checkString{
if !checker.contains(char){
return false
}
}
return true
}
private func barcodeTextFieldAlert(){
let alert = UIAlertController(title: "Invalid Input!", message: "Only number is valid, please retry.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
}
//This would show a Done button when user click the BarcodeTextField
func setupTextFields_Name() {
let toolbar = UIToolbar(frame: CGRect(origin: .zero, size: .init(width: view.frame.size.width, height: 30)))
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneBtn = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(doneButtonAction_Name))
toolbar.setItems([flexSpace, doneBtn], animated: false)
toolbar.sizeToFit()
nameTextField.inputAccessoryView = toolbar
}
@objc func doneButtonAction_Name(){
self.view.endEditing(true)
}
//This would show a Done button when user click the BarcodeTextField
func setupTextFields_Price() {
let toolbar = UIToolbar(frame: CGRect(origin: .zero, size: .init(width: view.frame.size.width, height: 30)))
let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneBtn = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(doneButtonAction_Price))
toolbar.setItems([flexSpace, doneBtn], animated: false)
toolbar.sizeToFit()
priceTextField.inputAccessoryView = toolbar
}
@objc func doneButtonAction_Price(){
self.view.endEditing(true)
}
@IBAction func priceTextFieldOnEndEditing(_ sender: Any) {
let validationResult = priceTextFieldValidation()
if(validationResult != "Valid"){
priceTextFieldAlert(alertType: validationResult)
priceTextField.text = "0.0"
}
if(priceTextField.text == ""){
priceTextField.text = "0.0"
}
refreshAmountAndTotalPrice()
}
private func priceTextFieldValidation() -> String {
let checker:String = "1234567890."
let checkString:String = priceTextField.text!
for char in checkString{
if !checker.contains(char){
return "Not Number"
}
}
let periodAppearanceTimes = priceTextField.text!.filter { $0 == "." }.count
if(periodAppearanceTimes > 1){
return "Multiply Period"
}
return "Valid"
}
private func priceTextFieldAlert(alertType:String) {
switch alertType {
case "Not Number":
let alert = UIAlertController(title: "Invalid Input!", message: "Only number is valid, please retry.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
case "Multiply Period":
let alert = UIAlertController(title: "Invalid Input!", message: "Only one period is allowed, please retry.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
default:
return
}
}
@IBAction func onSlide(_ sender: Any) {
refreshAmountAndTotalPrice()
}
private func refreshAmountAndTotalPrice(){
amount = Int(slider.value)
price = Float(priceTextField.text!) as! Float
amountLabel.text = String(amount)
totalPriceLabel.text = String(format: "%.2f", Float(amount) * price)
}
@IBAction func onTapSaveBtn(_ sender: Any) {
var incomplete:Bool = false
var incompleteString:String = ""
if(barcodeTextField.text == ""){
incompleteString.append("Barcode, ")
incomplete = true
}
if(nameTextField.text == ""){
incompleteString.append("Name, ")
incomplete = true
}
if(priceTextField.text == "0.0"){
incompleteString.append("Price, ")
incomplete = true
}
if(amountLabel.text == "0"){
incompleteString.append("Amount, ")
incomplete = true
}
if(incomplete){
incompleteString.remove(at: incompleteString.index(before: incompleteString.endIndex))
incompleteString.remove(at: incompleteString.index(before: incompleteString.endIndex))
let alert = UIAlertController(title: "Form is incomplete!", message: "Please check: "+incompleteString, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
}else{
Utils.tempPurchaseList.append([barcodeTextField.text!,nameTextField.text!,String(price),String(amount),""])
// userDefaults.synchronize()
}
}
}
|
//
// ViewController.swift
// ARKitDemoApp
//
// Created by Nitin Chauhan on 5/2/18.
// Copyright © 2018 Nitin Chauhan. All rights reserved.
//
import UIKit
import ARKit
class ViewController: UIViewController {
@IBOutlet weak var sceneView: ARSCNView!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
//camera is going to be launch and start Tracking Our Environment
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = .horizontal
sceneView.session.run(configuration)
}
}
|
//
// GistFile.swift
// HistsApp
//
// Created by Arkadiy Grigoryanc on 31.07.2019.
// Copyright © 2019 Arkadiy Grigoryanc. All rights reserved.
//
import Foundation
struct GistFile: Decodable {
let fileName: String
let type: String
let language: String?
let size: Int
enum CodingKeys: String, CodingKey {
case fileName = "filename"
case type
case language
case size
}
}
|
//
// ViewController.swift
// apiTest
//
// Created by Maruf Khan on 26/5/21.
//
import UIKit
import Alamofire
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 188
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TVCell", for: indexPath) as! TableViewCell
return cell
}
// var id = 0
// var ttl = ""
// var image_type = ""
// var image_link = ""
@IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib.init(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "TVCell")
self.tableView.dataSource = self
self.tableView.delegate = self
//getData(from: url)
}
// private func getData(from url : String){
// AF.request(url, method: .get,encoding: JSONEncoding.default).responseJSON { (response) in
// guard let data = response.data
// else{
// return
// }
// do{
// let jsonData = try JSONDecoder().decode(ResponseData.self, from: data)
//
// print(jsonData[1].archieves!.count)
// for index in 0..<jsonData[1].archieves!.count{
// self.image_link = jsonData[1].archieves![index].video_url
// print(self.image_link)
// }
//
// for index in 0..<jsonData[0].banners!.count{
// self.ttl = jsonData[0].banners![index].title
// print(self.ttl)
// }
//
//
// }
// catch{
// print("error decoding: \(error)")
//
// }
//
// }
// }
}
|
//
// SceneCoordinator.swift
// Zadatak
//
// Created by dejan kraguljac on 09/03/2020.
//
import UIKit
final class SceneCoordinator: SceneCoordinatorType {
private var window: UIWindow
var currentViewController: UIViewController!
init(window: UIWindow) {
self.window = window
}
func transition(to scene: Scene, transitionType: SceneTransition = .root(true), completion: VoidCompletion = nil) {
transition(to: scene.viewController, type: transitionType, completion: completion)
}
func transition(to viewController: UIViewController, type: SceneTransition, completion: VoidCompletion) {
switch type {
case let .root(animated):
window.rootViewController = viewController
window.makeKeyAndVisible()
completion?()
case let .push(animated):
guard let navigationController = currentViewController.navigationController else {
fatalError("There is no navigation stack to push new VC")
}
navigationController.pushViewController(viewController, animated: animated)
completion?()
default:
print("will update")
}
currentViewController = viewController.actualViewController()
}
func pop(_ toRoot: Bool = false, animated: Bool = true, completion: VoidCompletion = nil) {
if let navigationViewController = currentViewController.navigationController, navigationViewController.viewControllers.isEmpty == false {
navigationViewController.popViewController(animated: true)
self.currentViewController = navigationViewController.viewControllers.last!
} else {
self.window.rootViewController?.dismiss(animated: animated, completion: completion)
self.currentViewController = window.rootViewController
}
}
}
|
//
// Canvas.swift
// SelectScribbles
// Created by Florentin Lupascu on 29/04/2019.
// Copyright © 2019 Florentin Lupascu. All rights reserved.
//
import UIKit
/// A class which allow the user to draw inside a UIView which will inherit this class.
class CanvasView: UIView {
/// Closure to run on changes to drawing state
var isDrawingHandler: ((Bool) -> Void)?
/// The cached image drawn onto the canvas
var image: UIImage?
/// Caches the path for a line between touch down and touch up.
public var damageItems: [DamageItem] = [] { didSet { invalidateCachedImage() } }
/// The current scribble
public var currentScribble: [[CGPoint]]? {
didSet {
if currentScribble == nil || (currentScribble?.count ?? 0) == 0 {
predictivePoints = nil
isDrawingHandler?(false)
}
setNeedsDisplay()
}
}
private var predictivePoints: [CGPoint]?
/// Which path is currently selected
public var selectedDamageIndex: Int? { didSet { invalidateCachedImage() } }
/// The colour to use for drawing
public var strokeColor: UIColor = .black
public var selectedStrokeColor: UIColor = .orange
/// Width of drawn lines
private var lineWidth: CGFloat = 2 { didSet { invalidateCachedImage() } }
override func awakeFromNib() {
isMultipleTouchEnabled = false
}
override func draw(_ rect: CGRect) {
strokePaths()
}
}
// private utility methods
private extension CanvasView {
func strokePaths() {
if image == nil {
cacheImage()
}
image?.draw(in: bounds)
if let scribble = currentScribble {
let lastIndex = scribble.count - 1
for (index, points) in scribble.enumerated() {
var points = points
if index == lastIndex, let predictivePoints = predictivePoints {
points += predictivePoints
}
strokePath(points, isSelected: true)
}
}
}
func strokePath(_ points: [CGPoint], isSelected: Bool = false) {
let path = UIBezierPath(simpleSmooth: points)
let color = isSelected ? selectedStrokeColor : strokeColor
path?.lineCapStyle = .round
path?.lineJoinStyle = .round
path?.lineWidth = lineWidth
color.setStroke()
path?.stroke()
}
func invalidateCachedImage() {
image = nil
setNeedsDisplay()
}
/// caches just the damages, but not the current scribble
func cacheImage() {
guard damageItems.count > 0 else { return }
image = UIGraphicsImageRenderer(bounds: bounds).image { _ in
for (index, damage) in damageItems.enumerated() {
for points in damage.scribbles {
strokePath(points, isSelected: selectedDamageIndex == index)
}
}
}
}
func append(_ touches: Set<UITouch>, with event: UIEvent?, includePredictive: Bool = false) {
guard
let touch = touches.first,
let count = currentScribble?.count,
count > 0
else { return }
let index = count - 1
// probably should capture coalesced touches, too
if let touches = event?.coalescedTouches(for: touch) {
currentScribble?[index].append(contentsOf: touches.map { $0.location(in: self) })
}
currentScribble?[index].append(touch.location(in: self))
if includePredictive {
predictivePoints = event?
.predictedTouches(for: touch)?
.map { $0.location(in: self) }
} else {
predictivePoints = nil
}
setNeedsDisplay()
}
}
// UIResponder methods
extension CanvasView {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let point = touch.location(in: self)
if currentScribble == nil {
currentScribble = [[point]]
} else {
currentScribble?.append([point])
}
selectedDamageIndex = nil
isDrawingHandler?(true)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
append(touches, with: event)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
append(touches, with: event, includePredictive: false)
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
touchesEnded(touches, with: event)
}
}
|
//
// MPConstants.swift
// MessagePosting
//
// Created by Nicolas Flacco on 9/7/14.
// Copyright (c) 2014 Nicolas Flacco. All rights reserved.
//
import Foundation
let coreDataEntityPost = "Post"
let coreDataEntityComment = "Comment"
let parseClassNamePost = "Post"
let parseClassNameComment = "Comment"
// Provided by parse
let parseKeyNameId = "id"
let parseKeyNameParent = "parent" // for the children in a one-to-many relationship
// TODO: May want to have separate keys for post and for comment
let parseKeyNamePost = "post"
let parseKeyNameText = "text"
let parseKeyNameDate = "updatedAt"
let parseKeyNameComments = "comments"
let parseKeyNameNumberComments = "numberComments" |
//
// NumberExtension.swift
// Fuot
//
// Created by Zoom Nguyen on 1/2/16.
// Copyright © 2016 Zoom Nguyen. All rights reserved.
//
import Foundation
struct Number {
static let formatterWithSepator: NSNumberFormatter = {
let formatter = NSNumberFormatter()
formatter.groupingSeparator = " "
formatter.numberStyle = .DecimalStyle
return formatter
}()
}
extension IntegerType {
var stringFormatedWithSepator: String {
return Number.formatterWithSepator.stringFromNumber(hashValue) ?? ""
}
} |
import UIKit
func searchInsert(_ nums: [Int], _ target: Int) -> Int {
var index_start = 0
var index_end = nums.count - 1
if nums[index_end] < target {
return nums.count
}
while index_start <= index_end {
let index_mid = Int((index_start + index_end) / 2)
let num_mid = nums[index_mid]
if num_mid == target {
return index_mid
} else if target < num_mid {
index_end = index_mid - 1
} else {
index_start = index_mid + 1
}
}
return index_start
}
let array = [1,3,5,6]
let num = 2
let index = searchInsert(array, num)
print(index)
//let array = [1, 3, 2, 5, 7, 7, 9]
//
//func getK(nums: [Int]) -> [Int] {
//
// var k_array: [Int] = []
// for (index, num) in nums[1..<(nums.count-1)].enumerated() {
// let l_nums = nums[0...(index - 1)]
// let r_nums = nums[(index + 1)...(nums.count - 1)]
//
// print("l_nums : \(l_nums) r_nums:\(r_nums) ")
//
// var l_max = -1
// for l_num in l_nums {
// if l_num > l_max {
// l_max = l_num
// }
// }
//
// var r_max = -1
// for r_num in r_nums {
// if r_num > r_max {
// r_max = r_num
// }
// }
//
// if num > l_max && num < r_max {
// k_array.append(num)
// }
// }
// return k_array
//}
|
//
// PSLoginViewController.swift
// PhotoSlice
//
// Created by 雷永麟 on 2019/12/25.
// Copyright © 2019 leiyonglin. All rights reserved.
//
import UIKit
class PSLoginViewController: BaseViewController {
//MARK: lazyLoad
lazy var contentView: PSLoginContentView = {
let contentView = PSLoginContentView.init(frame: self.view.bounds)
return contentView
}()
//MARK: lifeCycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//MARK: UISet
override func configUISet() {
super.configUISet()
self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "close_icon"), style: .plain, target: self, action: #selector(dismissCurrentController))
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "密码登陆", style: .plain, target: self, action: #selector(gotoPasswordLogin))
self.view.addSubview(contentView)
}
//MARK: delegate & dataSource
//MARK: notification & observer
override func addNotificationObserver() {
super.addNotificationObserver()
}
override func removeNotificationObserver() {
NotificationCenter.default.removeObserver(self)
}
//MARK: action
@objc private func dismissCurrentController() {
self.dismiss(animated: true, completion: nil)
}
@objc private func gotoPasswordLogin() {
}
//MARK: dealloc
deinit {
removeNotificationObserver()
}
}
extension PSLoginViewController {
}
|
//
// RoadMapItem.swift
// Essentials
//
// Created by Sébastien De Pauw on 21/12/2020.
//
import Foundation
struct RoadMapItem: Codable {
public let id: Int
public let title: String
public let assessment: Assessment?
public let done: Bool
public let startDate: String
public let endDate: String
// public init?(id: Int, title: String, assessment: Assessment?, done: Bool, startDate: String, endDate: String) {
// if id < 0 || title.isEmpty || assessment == nil || startDate.isEmpty || endDate.isEmpty {
// return nil
// }
// self.id = id
// self.title = title
// self.assessment = assessment
// self.done = done
// self.startDate = startDate
// self.endDate = endDate
// }
public enum CodingKeys: String, CodingKey {
case id = "id"
case title = "title"
case assessment = "assessment"
case done = "done"
case startDate = "startDate"
case endDate = "endDate"
}
}
|
//
// ViewController+Load.swift
// SugarLumpUIKit
//
// Created by Mario Chinchilla on 10/10/18.
//
//
import Foundation
public extension UIViewController{
/// Declares the nib name from where to load an instance of this kind of UIViewController
class var loadNibName:String{ return String(describing: self) }
class var loadBundle:Bundle{ return Bundle(for: self) }
}
|
//
// FileSystemUtils.swift
// SlickData
//
// Created by Fernando Rodríguez Romero on 04/12/15.
// Copyright © 2015 Udacity. All rights reserved.
//
import Foundation
// creates a folder at a certain URL, as long as it doesn't
// exist previously
func createFolder(at:NSURL) throws ->Bool{
let fm = NSFileManager.defaultManager()
guard let path = at.path else{
throw SlickDataErrors.GenericError(description: "\(at) is not a local url")
}
guard !fm.fileExistsAtPath(path) else{
throw SlickDataErrors.FileExists(url: at)
}
do{
try fm.createDirectoryAtURL(at, withIntermediateDirectories: true, attributes: nil)
}catch let err as NSError{
throw SlickDataErrors.FileSystemError(err: err)
}
return true
}
//MARK: - FileManager extensions
extension NSFileManager{
func cachesURL()->NSURL{
return urlForDirectory(.CachesDirectory)
}
func documentsURL()->NSURL{
return urlForDirectory(.DocumentDirectory)
}
func urlForDirectory(directory: NSSearchPathDirectory) ->NSURL{
let urls = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: NSSearchPathDomainMask.UserDomainMask)
return urls.first!
}
} |
//
// NewProject
// Copyright (c) Yuichi Nakayasu. All rights reserved.
//
import UIKit
protocol TodoDetailAdapterDelegate: class {
func todoDetailAdapter(_ adapter: TodoDetailAdapter, didTapComplete todo: TodoModel?)
func todoDetailAdapter(_ adapter: TodoDetailAdapter, didTapEditTitle todo: TodoModel?)
func todoDetailAdapter(_ adapter: TodoDetailAdapter, didTapEditSummery todo: TodoModel?)
func todoDetailAdapter(_ adapter: TodoDetailAdapter, didChangePriority priority: TodoPriority, todo: TodoModel?)
func todoDetailAdapter(_ adapter: TodoDetailAdapter, didSelectLimit todo: TodoModel?)
func todoDetailAdapter(_ adapter: TodoDetailAdapter, didSelectNotify todo: TodoModel?)
func todoDetailAdapter(_ adapter: TodoDetailAdapter, didTapAsset asset: AssetModel?, todo: TodoModel?)
func todoDetailAdapter(_ adapter: TodoDetailAdapter, didTapAddAsset todo: TodoModel?)
func todoDetailAdapter(_ adapter: TodoDetailAdapter, didTapDelete todo: TodoModel?)
}
class TodoDetailAdapter: NSObject, UITableViewDelegate, UITableViewDataSource {
enum RowItem {
case title
case summery
case limit
case priority
case registered
case notify
case asset(model: AssetModel)
case addAsset
case delete
var assetModel: AssetModel? {
switch self { case .asset(let model): return model; default: return nil }
}
var title: String {
switch self {
case .limit: return "期限"
case .registered: return "登録日時"
case .notify: return "通知"
default: return ""
}
}
}
weak var tableView: UITableView!
weak var delegate: TodoDetailAdapterDelegate!
private var todo: TodoModel?
convenience init(_ tableView: UITableView, todo: TodoModel?, delegate: TodoDetailAdapterDelegate) {
self.init()
self.todo = todo
self.tableView = tableView
self.delegate = delegate
tableView.delegate = self
tableView.dataSource = self
}
func numberOfSections(in tableView: UITableView) -> Int {
return sectionsItems.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sectionsItems[section].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let rowItem = rowItemAt(indexPath)
let cellIdentifier = cellIdentifierOf(rowItem)
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
bind(cell: cell, at: indexPath)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 6
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 2
}
}
extension TodoDetailAdapter {
private var sectionsItems: [[RowItem]] {
var ret: [[RowItem]] = [
[.title, .limit, .summery],
[.priority, .registered],
[.notify]
]
if let assets = todo?.assets, !assets.isEmpty {
let assetsItems = assets.map { asset -> RowItem in
RowItem.asset(model: asset)
}
ret.append(assetsItems)
} else {
ret.append([.addAsset])
}
if todo != nil {
ret.append([.delete])
}
return ret
}
private func cellIdentifierOf(_ rowItem: RowItem) -> String {
switch rowItem {
case .title: return "title"
case .summery: return "summery"
case .limit, .registered, .notify: return "key-value"
case .priority: return "priority"
case .asset(_): return "asset"
case .addAsset: return "add-asset"
case .delete: return "delete"
}
}
private func rowItemAt(_ indexPath: IndexPath) -> RowItem {
return sectionsItems[indexPath.section][indexPath.row]
}
private func bind(cell original: UITableViewCell, at indexPath: IndexPath) {
if let cell = original as? TodoDetailCell {
cell.delegate = self
}
if let cell = original as? TodoDetailTitleCell {
cell.check = true
cell.title = todo?.title ?? ""
}
else if let cell = original as? TodoDetailSummeryCell {
cell.summery = todo?.summery ?? ""
}
else if let cell = original as? TodoDetailKeyValueCell {
cell.indexPath = indexPath
let rowItem = rowItemAt(indexPath)
bindKeyValue(cell: cell, rowItem: rowItem)
}
else if let cell = original as? TodoDetailPriorityCell {
cell.priority = todo?.priority ?? .normal
}
else if let cell = original as? TodoDetailAssetCell {
cell.indexPath = indexPath
cell.assetImage = nil
}
}
private func bindKeyValue(cell: TodoDetailKeyValueCell, rowItem: RowItem) {
cell.title = rowItem.title
cell.editable = keyValueEditable(rowItem: rowItem)
switch rowItem {
case .limit:
cell.value = TodoModel.limitText(model: todo)
case .registered:
cell.value = "TODO:登録日時"
case .notify:
cell.value = "TODO:通知"
default:
return
}
}
private func keyValueEditable(rowItem: RowItem) -> Bool {
switch rowItem {
case .limit, .notify: return true
default: return false
}
}
}
extension TodoDetailAdapter: TodoDetailCellDelegate {
func didTapComplete(at cell: TodoDetailCell) {
delegate.todoDetailAdapter(self, didTapComplete: todo)
}
func didTapEditTitle(at cell: TodoDetailCell) {
delegate.todoDetailAdapter(self, didTapEditTitle: todo)
}
func didTapEditSummery(at cell: TodoDetailCell) {
delegate.todoDetailAdapter(self, didTapEditSummery: todo)
}
func didChangePriority(at cell: TodoDetailCell, priority: TodoPriority) {
delegate.todoDetailAdapter(self, didChangePriority: .normal, todo: todo) // TODO: priorityがnormal固定になっているのを直す
}
func didSelectKeyValue(at cell: TodoDetailCell, indexPath: IndexPath) {
switch rowItemAt(indexPath) {
case .limit:
delegate.todoDetailAdapter(self, didSelectLimit: todo)
case .notify:
delegate.todoDetailAdapter(self, didSelectNotify: todo)
default:
return
}
}
func didSelectNotify(at cell: TodoDetailCell) {
delegate.todoDetailAdapter(self, didSelectNotify: todo)
}
func didTapAsset(at cell: TodoDetailCell, indexPath: IndexPath) {
if let asset = rowItemAt(indexPath).assetModel {
delegate.todoDetailAdapter(self, didTapAsset: asset, todo: todo)
}
}
func didTapAddAsset(at cell: TodoDetailCell) {
delegate.todoDetailAdapter(self, didTapAddAsset: todo)
}
func didTapDelete(at cell: TodoDetailCell) {
delegate.todoDetailAdapter(self, didTapDelete: todo)
}
}
|
//
// HomeViewController.swift
// BackYard
//
// Created by icbrahimc on 6/18/17.
// Copyright © 2017 BackYard. All rights reserved.
//
import FirebaseAuth
import LBTAComponents
import UIKit
class UserDataSource: Datasource {
let words = ["user"]
override func headerClasses() -> [DatasourceCell.Type]? {
return [UserHeader.self]
}
override func cellClasses() -> [DatasourceCell.Type] {
return [UserCell.self]
}
override func item(_ indexPath: IndexPath) -> Any? {
return words[indexPath.item]
}
override func numberOfItems(_ section: Int) -> Int {
return words.count
}
}
class HomeViewController: DatasourceController {
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.isNavigationBarHidden = false
self.navigationItem.hidesBackButton = true
view.backgroundColor = .white
let settingsBar = UIBarButtonItem(title: "\u{2699}", style: .plain, target: self, action: #selector(openSettings))
self.navigationItem.rightBarButtonItem = settingsBar
let userDataSource = UserDataSource()
self.datasource = userDataSource
}
override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: 150)
}
func openSettings() -> Void {
let settingsViewController = SettingsViewController()
self.navigationController?.pushViewController(settingsViewController, animated: true)
}
}
|
//
// MapViewController.swift
// itslitt
//
// Created by Gage Swenson on 3/25/17.
// Copyright © 2017 juicyasf. All rights reserved.
//
import UIKit
import GoogleMaps
import MessageUI
class MapViewController: UIViewController, GMSMapViewDelegate {
var mapView: GMSMapView!
var timer: Timer?
var oldMarkers: [String: GMSMarker]?
override func loadView() {
let camera = GMSCameraPosition.camera(withLatitude: 0.0, longitude: 0.0, zoom: 1.0)
mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
mapView.delegate = self
view = mapView
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Do any additional setup after loading the view, typically from a nib.
timer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true, block: {(olTimer) in
self.getlit()
})
}
override func viewWillDisappear(_ animated: Bool) {
if let timr = timer {
timr.invalidate()
timer = nil
}
}
func mapView(_ mapView: GMSMapView, didTapInfoWindowOf marker: GMSMarker) {
mapView.selectedMarker = nil
}
func mapView(_ mapView: GMSMapView, didLongPressInfoWindowOf marker: GMSMarker) {
let fname = marker.snippet?.components(separatedBy: "\n\n")[0]
if (MFMessageComposeViewController.canSendText()) {
let viewController = MFMessageComposeViewController()
viewController.recipients = [fname!]
self.present(viewController, animated: true, completion: nil)
}
}
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
var newZoom = mapView.camera.zoom
if newZoom < 7.2 {
newZoom = 10.0
}
else if newZoom < 10.3 {
newZoom = 18.0
}
mapView.moveCamera(GMSCameraUpdate.setTarget(marker.position, zoom: newZoom))
mapView.selectedMarker = marker
return true
}
func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) {
mapView.moveCamera(GMSCameraUpdate.setTarget(coordinate, zoom: 3.0))
}
func mapView(_ mapView: GMSMapView, markerInfoContents marker: GMSMarker) -> UIView? {
return nil
}
func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
let nib = UINib(nibName: "InfoWindo", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! InfoWindo
let nameFname = marker.title?.components(separatedBy: "\n")
nib.tvName.text = nameFname?[0]
nib.tvFname.text = nameFname?[1]
nib.tvStatus.text = marker.snippet
return nib
}
func getlit() {
DispatchQueue.global(qos: DispatchQoS.background.qosClass).async {
let json = ["uname": Const.uname, "passwd": Const.passwd]
let auth = try? JSONSerialization.data(withJSONObject: json)
let url = URL(string: Const.server("getlit"))
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.httpBody = auth
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = URLSession.shared.dataTask(with: request) { data, resp, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
let response = try? JSONSerialization.jsonObject(with: data)
if let response = response as? [String: Any] {
if let err = response["error"] {
DispatchQueue.main.async {
self.view.makeToast(err as! String, duration: Const.tt(), position: .top)
}
}
else if let friends = response["friends"] as? [[String: Any]] {
DispatchQueue.main.async {
var markers: [String: GMSMarker] = [:]
for friend in friends {
let name = friend["name"] as! String
let phone = friend["fname"] as! String
var icon: UIImage!
if let img = Const.faces[phone] {
icon = img
}
else {
icon = UIImage(named: "nullpicsmall")
let json = ["uname": Const.uname, "passwd": Const.passwd, "fname": phone]
let auth = try? JSONSerialization.data(withJSONObject: json)
let url = URL(string: Const.server("getpic"))
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.httpBody = auth
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/octet-stream", forHTTPHeaderField: "Accept")
let task = URLSession.shared.dataTask(with: request) { data, resp, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")
return
}
if let img = UIImage(data: data) {
Const.faces[phone] = img
}
}
task.resume()
}
icon = icon.scaleFor(zoom: self.mapView.camera.zoom)!.circleMasked!
let status = friend["status"] as! String
let lat = friend["lat"] as! Double
let lon = friend["lon"] as! Double
var queued = true
if let oldLit = self.oldMarkers {
for fren in oldLit {
if fren.key == phone {
let oldStatus = fren.value.snippet
let newStatus = friend["status"] as! String
let oldLat = fren.value.position.latitude
let oldLon = fren.value.position.longitude
let newLat = friend["lat"] as! Double
let newLon = friend["lon"] as! Double
if oldLat == newLat && oldLon == newLon && oldStatus == newStatus {
var iconAfterZoom: UIImage!
if let img = Const.faces[phone] {
iconAfterZoom = img
}
else {
iconAfterZoom = UIImage(named: "nullpicsmall")
}
fren.value.icon = iconAfterZoom.scaleFor(zoom: self.mapView.camera.zoom)!.circleMasked!
markers[phone] = fren.value
queued = false
}
else {
fren.value.map = nil
}
}
}
}
if queued {
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: lat, longitude: lon)
marker.title = name + "\n" + phone
marker.snippet = status
marker.icon = icon
markers[phone] = marker
}
var indx = 0
while indx < Const.friends.count {
if Const.friends[indx]["fname"] as! String == phone {
Const.friends[indx]["status"] = status
}
indx = indx + 1
}
}
if let oldLit = self.oldMarkers {
for oldMarker in oldLit {
var burn = true
for marker in markers {
if oldMarker.key == marker.key {
burn = false
}
}
if burn {
oldMarker.value.map = nil
}
}
}
for mrkr in markers.values {
mrkr.map = self.mapView
}
self.oldMarkers = markers
}
}
else {
print("error getlit(): server responded without friends")
}
} else {
print("error getlit(): response was not json")
}
}
task.resume()
}
}
}
|
//
// ViewController.swift
// SimpleOfflineMapBrowser
//
// Created by Jakub Calik on 15/08/2019.
// Copyright © 2019 Jakub Calik. All rights reserved.
//
import UIKit
import SygicMaps
import SygicUIKit
import SygicMapsKit
class ViewController: UIViewController, SYMKModulePresenter {
let sdkKey = ""
let sdkSecret = ""
let sdkRouteS = ""
let pathToCustomMaps = Bundle.main.bundlePath + "/customMaps"
var presentedModules = [SYMKModuleViewController]()
lazy var browseMap: SYMKBrowseMapViewController = {
let browseMap = SYMKBrowseMapViewController()
browseMap.useCompass = true
browseMap.useZoomControl = true
browseMap.useRecenterButton = true
browseMap.mapSelectionMode = .all
browseMap.mapState.zoom = 3
browseMap.mapState.cameraMovementMode = .followGpsPosition
return browseMap
}()
let mapButton: SYUIActionButton = {
let button = SYUIActionButton()
button.icon = SYUIIcon.map
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
loadCustomMaps()
SYMKApiKeys.set(appKey: sdkKey, appSecret: sdkSecret, routingKey: sdkRouteS)
SYMKSdkManager.shared.onlineMapsEnabled = false
browseMap.setupActionButton(with: nil, icon: SYUIIcon.map) {
self.showManageMapsViewController()
}
presentModule(browseMap)
}
@objc func showManageMapsViewController() {
present(UINavigationController(rootViewController: ManageMapsViewController()), animated: true, completion: nil)
}
func loadCustomMaps() {
let fileManager = FileManager()
let mapsPaths = try? fileManager.contentsOfDirectory(atPath: pathToCustomMaps)
let pathToDoc = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first!
try? fileManager.createDirectory(at: URL(fileURLWithPath: "\(pathToDoc)/sygic/maps", isDirectory: true), withIntermediateDirectories: true, attributes: [:])
guard let maps = mapsPaths else { return }
for map in maps {
let fromPath = "\(pathToCustomMaps)/\(map)"
let toPath = "\(pathToDoc)/sygic/maps/\(map)"
do {
try fileManager.copyItem(atPath: fromPath, toPath: toPath)
} catch {
print(error)
}
}
}
}
|
//
// ViewControllerQuizDistancia.swift
// ProyectoFinal
//
// Created by user168624 on 4/22/20.
// Copyright © 2020 user168624. All rights reserved.
//
import UIKit
class preguntaD: NSObject {
var respuesta : Int
var img : UIImage!
init(respuesta: Int, img: UIImage){
self.respuesta = respuesta
self.img = img
}
}
class ViewControllerQuizDistancia: UIViewController {
@IBOutlet weak var imgRegla: UIImageView!
@IBOutlet weak var suitch: UISwitch!
@IBOutlet weak var imgPregunta: UIImageView!
@IBOutlet weak var tfRespuesta: UITextField!
@IBOutlet weak var lblResultado: UILabel!
@IBOutlet weak var lblErrores: UILabel!
@IBAction func quitarTeclado() {
view.endEditing(true)
}
@IBAction func btnRevisar(_ sender: Any) {
if contador < 5 {
if tfRespuesta.text == String(preguntas[contador].respuesta) && contador < 4 {
lblResultado.text = "Correcto"
contador = contador + 1
imgPregunta.image = preguntas[contador].img
} else if tfRespuesta.text == String(preguntas[contador].respuesta) && contador == 4 {
lblResultado.text = "Correcto, haz completado el quiz!"
lblErrores.text = "Errores: " + String(errores)
contador = contador + 1
} else {
lblResultado.text = "Incorrecto"
errores = errores + 1
}
tfRespuesta.text = ""
}
}
var preguntas = [preguntaD]()
var contador : Int = 0
var errores : Int = 0
override func viewDidLoad() {
super.viewDidLoad()
let pregunta1 = preguntaD(respuesta: 3, img: UIImage(named: "D1")!)
let pregunta2 = preguntaD(respuesta: 2, img: UIImage(named: "D2")!)
let pregunta3 = preguntaD(respuesta: 3, img: UIImage(named: "D3")!)
let pregunta4 = preguntaD(respuesta: 2, img: UIImage(named: "D4")!)
let pregunta5 = preguntaD(respuesta: 4, img: UIImage(named: "D5")!)
preguntas.append(pregunta1)
preguntas.append(pregunta2)
preguntas.append(pregunta3)
preguntas.append(pregunta4)
preguntas.append(pregunta5)
preguntas = preguntas.shuffled()
contador = 0
errores = 0
imgPregunta.image = preguntas[contador].img
// Do any additional setup after loading the view
//imgRegla.isHidden = true
// suitch.isOn = false
}
@IBAction func activaRegla(_ sender: UISwitch) {
if suitch.isOn {
imgRegla.isHidden = false
}
else {
imgRegla.isHidden = true
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// MockDataClient.swift
// Antino Labs Task
//
// Created by Ajay Choudhary on 23/05/20.
// Copyright © 2020 Ajay Choudhary. All rights reserved.
//
import UIKit
class MockDataClient {
static let placeholder = UIImage(named: "placeholder")!
class func fetchPersonData(completion: @escaping ([Person], ErrorMessage?) -> Void) {
let urlString = "http://demo8716682.mockable.io/cardData"
guard let url = URL(string: urlString) else {
completion([], .invalidRequest)
return
}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
completion([], .unableToComplete)
return
}
guard let data = data else {
completion([], .invalidData)
return
}
do {
let responseObject = try JSONDecoder().decode([Person].self, from: data)
completion(responseObject, nil)
} catch {
completion([], .invalidResponse)
}
}
task.resume()
}
class func fetchProfileImage(urlString: String, completion: @escaping (UIImage, Error?) -> Void) {
guard let url = URL(string: urlString) else { return }
if let imageFromCache = imageCache[urlString] {
completion(imageFromCache, nil)
return
}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
completion(placeholder, error)
return
}
guard let data = data else {
completion(placeholder, error)
return
}
let image = UIImage(data: data)
imageCache[urlString] = image
completion(image ?? placeholder, nil)
}
task.resume()
}
}
var imageCache = [String: UIImage]()
|
import HTTP
extension Request {
convenience init(url: URL, xml: String) {
self.init(url: url, method: .post)
self.contentType = .xml
self.body = .output(xml)
}
}
|
//
// SettingsNavigationItem.swift
// TipCalc2
//
// Created by Baddam, Rohan(AWF) on 9/2/14.
// Copyright (c) 2014 Baddam, Rohan(AWF). All rights reserved.
//
import UIKit
class SettingsNavigationItem: UINavigationItem {
}
|
//
// FakeCountries.swift
// Daft CountriesTests
//
// Created by Karol Struniawski on 09/05/2019.
// Copyright © 2019 Karol Struniawski. All rights reserved.
//
import UIKit
@testable import Daft_Countries
class CountriesProviderSpy: CountriesProviding {
func fetchCountries(completion: @escaping (Result<[Country], NetworkError>) -> Void) {
self.capturedCompletion = completion
numberOfCalls += 1
}
private (set) var numberOfCalls = 0
private (set) var capturedCompletion : ((Result<[Country],NetworkError>) -> Void)?
func simmulateCompletion(country: [Country]) {
capturedCompletion?(.success(country))
}
func simmulateCompletion(error: NetworkError) {
capturedCompletion?(.failure(error))
}
}
|
//
// DayTenTests.swift
// AdventOfCode2017
//
// Created by Shawn Veader on 12/10/17.
// Copyright © 2017 v8logic. All rights reserved.
//
import Foundation
extension DayTen: Testable {
func runTests() {
guard
testValue(12, equals: partOne(input: "3, 4, 1, 5", count: 5)),
true
else {
print("Part 1 Tests Failed!")
return
}
guard
testValue("33efeb34ea91902bb2f59c9920caa6cd", equals: partTwo(input: "AoC 2017")),
testValue("a2582a3a0e66e6e86e3812dcb672a272", equals: partTwo(input: "")),
testValue("3efbe78a8d82f29979031a4aa0b16a9d", equals: partTwo(input: "1,2,3")),
testValue("63960835bcdc130f0b66d7ff4f6a5a8e", equals: partTwo(input: "1,2,4")),
true
else {
print("Part 2 Tests Failed!")
return
}
print("Done with tests... all pass")
}
}
|
//
// Warrior.swift
// Projet_P3
//
// Created by Marques Lucas on 10/10/2018.
// Copyright © 2018 Marques Lucas. All rights reserved.
//
import Foundation
// Warrior class with its initializer
class Warrior: Character {
init(name: String) {
super.init(name: name, hp: 170, species: "Guerrier", weapon: Sword(), isWizard: nil)
}
}
|
//
// File.swift
//
//
// Created by RedPanda on 25-Sep-19.
//
import XCTest
import Foundation
import Combine
import StrictlySwiftLib
import StrictlySwiftTestLib
@testable import Dyno
struct Mockosaur : Codable, Equatable {
let id: String
let name: String
let colours: [String]
let teeth: Int
}
struct MockosaurDiscovery : Codable {
let id: String
let dinoId: String
let when: Date
}
struct MockComplexObject {
let dinos: [Mockosaur]?
let data: Data
let date: Date
let double: [Double]
let float: [Float]
let bool: Bool
}
struct MockObjectCustomEncoding {
let date: Date
static func encoding(v:MockObjectCustomEncoding) -> [String: DynoAttributeValue] {
return ["date":.N( "\(v.date.timeIntervalSinceReferenceDate)" )]
}
}
struct MockosaurSize : Codable {
let id: String
let dinoId: String
let size: Double
}
// Helper conversion
extension BlockingError {
func asDynoError() -> DynoError {
switch self {
case .timeoutError(let i): return DynoError("Timed out after \(i) seconds: \(self)")
case .otherError(let e): return DynoError("\(e)")
}
}
}
extension DateFormatter {
static func date(fromAWSStringDate date: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyyMMdd'T'HHmmssZZZZZ"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
return dateFormatter.date(from: date)!
}
}
final class DynoTests: XCTestCase {
override func setUp() {
}
// See: https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html
func testCalculateSigningKeyAndSignature() throws {
let asofDate = Date(year: 2015, month: 08, day: 30, isUTC: true)!
let signer = AWSSignatureGenerator(secretKeyLocation: getTestCredentialsURL1(), log: true)
let key = signer?.calculateSigningKey(for: asofDate, region: "us-east-1", service: "iam")
XCTAssertNotNil(key)
let keyData = key!.hexEncodedString
XCTAssertEqual(keyData, "c4afb1cc5771d871763a393e44b703571b55cc28424d1a5e86da6ed3c154a4b9")
let stringToSign =
"""
AWS4-HMAC-SHA256
20150830T123600Z
20150830/us-east-1/iam/aws4_request
f536975d06c0309214f805bb90ccff089219ecd68b2577efef23edd43b7e1a59
"""
let signature = signer?.do_sign(signingKey: key!, stringToSign: stringToSign)
XCTAssertEqual(signature, "5d672d79c15b13162d9279b0855cfba6789a8edb4c82c400e06b5924a6f2b5d7")
}
func testSHA256Hash() throws {
XCTAssertEqual(AWSSignatureGenerator.sha256Hash(payload: ""), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
}
// from test on here: https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html
func testCanonicalRequest() {
let awsReq = AWSSignableRequest(
date: DateFormatter.date(fromAWSStringDate: "20130524T000000Z"),
verb: .GET,
host: "examplebucket.s3.amazonaws.com",
path: "/test.txt",
region: "examplebucket",
service: "s3",
queryParameters: [:],
headers: ["range":"bytes=0-9"],
payload: "")
let req = awsReq.canonicalRequest()
XCTAssertEqual( req,
"""
GET
/test.txt
host:examplebucket.s3.amazonaws.com
range:bytes=0-9
x-amz-content-sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
x-amz-date:20130524T000000Z
host;range;x-amz-content-sha256;x-amz-date
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
"""
)
XCTAssertEqual(AWSSignatureGenerator.sha256Hash(payload: req), "7344ae5b7ee6c3e7e6b0fe0640412a37625d1fbfff95c48bbb2dc43964946972")
}
func testStringToSign() {
let asofDate = DateFormatter.date(fromAWSStringDate: "20130524T000000Z")
let signer = AWSSignatureGenerator(secretKeyLocation: getTestCredentialsURL2(), log: true)
let awsReq = AWSSignableRequest(
date:asofDate,
verb: .GET,
host: "examplebucket.s3.amazonaws.com",
path: "/test.txt",
region: "us-east-1",
service: "s3",
queryParameters: [:],
headers: ["range":"bytes=0-9", "x-amz-date":"20130524T000000Z"],
payload: "")
let req = signer?.createStringToSign(request: awsReq)
XCTAssertEqual(req,
"""
AWS4-HMAC-SHA256
20130524T000000Z
20130524/us-east-1/s3/aws4_request
7344ae5b7ee6c3e7e6b0fe0640412a37625d1fbfff95c48bbb2dc43964946972
"""
)
}
func test_doSign() {
let asofDate = DateFormatter.date(fromAWSStringDate: "20130524T000000Z")
let signer = AWSSignatureGenerator(secretKeyLocation: getTestCredentialsURL2(), log: true)
let awsReq = AWSSignableRequest(
date: asofDate,
verb: .GET,
host: "examplebucket.s3.amazonaws.com",
path: "/test.txt",
region: "us-east-1",
service: "s3",
queryParameters: [:],
headers: ["range":"bytes=0-9"],
payload: "")
let req = signer?.createStringToSign(request: awsReq) ?? ""
let signingKey = signer?.calculateSigningKey(for: asofDate, region: "us-east-1", service: "s3")
XCTAssert(signingKey != nil, "Cannot create signing key")
let nonNilSigningKey = signingKey!
XCTAssertEqual(signer?.do_sign(signingKey: nonNilSigningKey, stringToSign: req),
"f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41")
}
func testNoQueryParameterSignatureCalculation() {
let asofDate = DateFormatter.date(fromAWSStringDate: "20130524T000000Z")
let signer = AWSSignatureGenerator(secretKeyLocation: getTestCredentialsURL2(), log: true )
let awsReq = AWSSignableRequest(
date: asofDate,
verb: .GET,
host: "examplebucket.s3.amazonaws.com",
path: "/test.txt",
region: "us-east-1",
service: "s3",
queryParameters: [:],
headers: ["range":"bytes=0-9"],
payload: "")
XCTAssertNotNil(signer)
let nonNilSigner = signer!
XCTAssertEqual(nonNilSigner.sign(request: awsReq),
.success("f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"))
}
func testWithQueryParameterSignatureCalculation() {
let asofDate = DateFormatter.date(fromAWSStringDate: "20130524T000000Z")
let signer = AWSSignatureGenerator(secretKeyLocation: getTestCredentialsURL2(), log: true )
let awsReq = AWSSignableRequest(
date: asofDate,
verb: .GET,
host: "examplebucket.s3.amazonaws.com",
path: "/",
region: "us-east-1",
service: "s3",
queryParameters: ["lifecycle":""],
headers: [:],
payload: "")
XCTAssertNotNil(signer)
let nonNilSigner = signer!
XCTAssertEqual(nonNilSigner.sign(request: awsReq),
.success("fea454ca298b7da1c68078a5d1bdbfbbe0d65c699e0f91ac7a200a0136783543"))
}
func testWithPutSignatureCalculation() {
let asofDate = DateFormatter.date(fromAWSStringDate: "20130524T000000Z")
let signer = AWSSignatureGenerator(secretKeyLocation: getTestCredentialsURL2(), log: true)
let awsReq = AWSSignableRequest(
date: asofDate,
verb: .PUT,
host: "examplebucket.s3.amazonaws.com",
path: "/test$file.text",
region: "us-east-1",
service: "s3",
queryParameters: [:],
headers: [
"date":"Fri, 24 May 2013 00:00:00 GMT",
"x-amz-storage-class":"REDUCED_REDUNDANCY"],
payload: "Welcome to Amazon S3.")
XCTAssertNotNil(signer)
let nonNilSigner = signer!
XCTAssertEqual(nonNilSigner.sign(request: awsReq),
.success("98ad721746da40c64f1a55b78f14c238d841ea1380cd77a1b5971af0ece108bd"))
}
func testNoQueryParameterAuthorization() {
let asofDate = DateFormatter.date(fromAWSStringDate: "20130524T000000Z")
let signer = AWSSignatureGenerator(secretKeyLocation: getTestCredentialsURL2(), log: true )
let awsReq = AWSSignableRequest(
date: asofDate,
verb: .GET,
host: "examplebucket.s3.amazonaws.com",
path: "/test.txt",
region: "us-east-1",
service: "s3",
queryParameters: [:],
headers: ["range":"bytes=0-9"],
payload: "")
XCTAssertNotNil(signer)
let nonNilSigner = signer!
XCTAssertEqual(nonNilSigner.authorize(request: awsReq),
.success("AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request,SignedHeaders=host;range;x-amz-content-sha256;x-amz-date,Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"))
}
func testDinosaurScanRequest() {
let asofDate = DateFormatter.date(fromAWSStringDate: "20191015T231704Z")
let signer = AWSSignatureGenerator(secretKeyLocation: getTestCredentialsURL2(), log: true )
let awsReq = AWSSignableRequest(
date: asofDate,
verb: .POST,
host: "dynamodb.us-east-2.amazonaws.com",
path: "/",
region: "us-east-2",
service: "dynamodb",
queryParameters: [:],
headers: [
"content-type":"application/x-amz-json-1.0",
"x-amz-target":"DynamoDB_20120810.Scan"],
payload: """
{"TableName": "Dinosaurs"}
""",
test_no_content_sha: true)
XCTAssertEqual(awsReq.canonicalRequest(),
"""
POST
/
content-type:application/x-amz-json-1.0
host:dynamodb.us-east-2.amazonaws.com
x-amz-date:20191015T231704Z
x-amz-target:DynamoDB_20120810.Scan
content-type;host;x-amz-date;x-amz-target
2b9107816baf4b22a43cf18a2c3ceb95ac69632991a10efae4af99f87347c68e
""")
let s2s = signer!.createStringToSign(request: awsReq)
XCTAssertEqual(s2s,
"""
AWS4-HMAC-SHA256
20191015T231704Z
20191015/us-east-2/dynamodb/aws4_request
a2cae71621a09375e098f483d435417cca5db737eb755ced1c3d1c3fd315689b
""")
let signature = signer!.sign(request: awsReq)
XCTAssertEqual(signature, .success("fd6b8a79f737f24b85258be0e71517f192a92b125c4c7993ed35445402dd220f"))
}
func testDecoder() {
let decoder = JSONDecoder()
let json1 = #"{"Count":2,"Items":[],"LastEvaluatedKey":{"id":{"S":"6"}},"ScannedCount":3, "ConsumedCapacity":{}}"#
let decoded1 = try? decoder.decode(DynoScanResponse.self, from: json1.data(using: .utf8)!)
XCTAssertNotNil(decoded1)
XCTAssertEqual(decoded1?.Count,2)
XCTAssertEqual(decoded1?.Items,[])
XCTAssertEqual(decoded1?.LastEvaluatedKey,["id":.S("6")])
XCTAssertEqual(decoded1?.ScannedCount,3)
let json2 = #"{"Count":2,"Items":[{"teeth":{"N":"158"},"id":{"S":"2"},"colours":{"L":[{"S":"green"},{"S":"black"}]},"name":{"S":"Tyrannosaurus"}},{"teeth":{"N":"40"},"id":{"S":"6"},"colours":{"L":[{"S":"pink"}]},"name":{"S":"Pinkisaur"}}],"LastEvaluatedKey":{"id":{"S":"6"}},"ScannedCount":3, "ConsumedCapacity":{}}"#
let decoded2 = try? decoder.decode(DynoScanResponse.self, from: json2.data(using: .utf8)!)
XCTAssertNotNil(decoded2)
XCTAssertEqual(decoded2?.Count,2)
XCTAssertEqual(decoded2?.Items,[["teeth":.N("158"), "id":.S("2"), "colours":.L([.S("green"),.S("black")]), "name":.S("Tyrannosaurus")],
["teeth":.N("40"), "id":.S("6"), "colours":.L([.S("pink")]), "name":.S("Pinkisaur")]])
XCTAssertEqual(decoded2?.LastEvaluatedKey,["id":.S("6")])
XCTAssertEqual(decoded2?.ScannedCount,3)
}
func testFilters() {
let filter1 = DynoCondition.betweenValue(of:"teeth", from: 50, to: 4000)
let eavFilter1 = filter1.toPayload()
XCTAssertEqual(filter1.description, #"teeth BETWEEN N("50") AND N("4000")"#)
XCTAssertEqual(eavFilter1.toDynoFilterExpression(),"#n0 BETWEEN :v0 AND :v1")
NSLog("\(eavFilter1.toDynoExpressionAttributeNames())")
NSLog("\(eavFilter1.toDynoExpressionAttributeValues())")
XCTAssertEqual(eavFilter1.toDynoExpressionAttributeNames(), ["#n0":"teeth"])
XCTAssertEqualDictionaries(item: eavFilter1.toDynoExpressionAttributeValues(), refDict: [":v0":.N("50"),":v1":.N("4000")])
let filter2 = DynoCondition.compare("teeth", .ge, 40)
let eavFilter2 = filter2.toPayload()
XCTAssertEqual(filter2.description, #"teeth >= N("40")"#)
XCTAssertEqual(eavFilter2.toDynoFilterExpression(),"#n0 >= :v0")
XCTAssertEqual(eavFilter2.toDynoExpressionAttributeNames(), ["#n0":"teeth"])
XCTAssertEqualDictionaries(item: eavFilter2.toDynoExpressionAttributeValues(), refDict: [":v0":.N("40")])
let filter3 = DynoCondition.in("colour", ["green","aqua"])
let eavFilter3 = filter3.toPayload()
XCTAssertEqual(filter3.description, #""colour" IN (S("green"), S("aqua"))"#)
XCTAssertEqual(eavFilter3.toDynoFilterExpression(), "#n0 IN (:v0,:v1)")
XCTAssertEqual(eavFilter3.toDynoExpressionAttributeNames(),["#n0":"colour"])
XCTAssertEqualDictionaries(item: eavFilter3.toDynoExpressionAttributeValues(),refDict: [":v0":.S("green"),":v1":.S("aqua")])
let filter4 = DynoCondition.compare("teeth", .ge, 10.5)
let eavFilter4 = filter4.toPayload()
XCTAssertEqual(filter4.description, #"teeth >= N("10.5")"#)
XCTAssertEqual(eavFilter4.toDynoFilterExpression(), "#n0 >= :v0")
XCTAssertEqual(eavFilter4.toDynoExpressionAttributeNames(),["#n0":"teeth"])
XCTAssertEqualDictionaries(item: eavFilter4.toDynoExpressionAttributeValues(),refDict: [":v0":.N("10.5")])
let filter5 = DynoCondition.compare("bool",.ne , false)
let eavFilter5 = filter5.toPayload()
XCTAssertEqual(filter5.description, #"bool <> BOOL(false)"#)
XCTAssertEqual(eavFilter5.toDynoFilterExpression(), "#n0 <> :v0")
XCTAssertEqual(eavFilter5.toDynoExpressionAttributeNames(),["#n0":"bool"])
XCTAssertEqualDictionaries(item: eavFilter5.toDynoExpressionAttributeValues(),refDict: [":v0":.BOOL(false)])
let filter6 = DynoCondition.compare("data",.eq, Data(base64Encoded: "0000000000000000")!)
let eavFilter6 = filter6.toPayload()
XCTAssertEqual(filter6.description, #"data = B(12 bytes)"#)
XCTAssertEqual(eavFilter6.toDynoFilterExpression(), "#n0 = :v0")
XCTAssertEqual(eavFilter6.toDynoExpressionAttributeNames(),["#n0":"data"])
XCTAssertEqualDictionaries(item: eavFilter6.toDynoExpressionAttributeValues(),refDict: [":v0":.B(Data(base64Encoded: "0000000000000000")!)])
let filter7 = DynoCondition.compare("array",.eq, ["hi","bye"])
let eavFilter7 = filter7.toPayload()
XCTAssertEqual(filter7.description, #"array = SS(["hi", "bye"])"#)
XCTAssertEqual(eavFilter7.toDynoFilterExpression(), "#n0 = :v0")
XCTAssertEqual(eavFilter7.toDynoExpressionAttributeNames(),["#n0":"array"])
XCTAssertEqualDictionaries(item: eavFilter7.toDynoExpressionAttributeValues(),refDict: [":v0":.SS(["hi","bye"])])
let filter8 = DynoCondition.compare("array",.eq, [1,2])
let eavFilter8 = filter8.toPayload()
XCTAssertEqual(filter8.description, #"array = NS(["1", "2"])"#)
XCTAssertEqual(eavFilter8.toDynoFilterExpression(), "#n0 = :v0")
XCTAssertEqual(eavFilter8.toDynoExpressionAttributeNames(),["#n0":"array"])
XCTAssertEqualDictionaries(item: eavFilter8.toDynoExpressionAttributeValues(),refDict: [":v0":.NS(["1","2"])])
let filter9 = DynoCondition.compare("array",.eq, [0.1,0.2])
let eavFilter9 = filter9.toPayload()
XCTAssertEqual(filter9.description, #"array = NS(["0.1", "0.2"])"#)
XCTAssertEqual(eavFilter9.toDynoFilterExpression(), "#n0 = :v0")
XCTAssertEqual(eavFilter9.toDynoExpressionAttributeNames(),["#n0":"array"])
XCTAssertEqualDictionaries(item: eavFilter9.toDynoExpressionAttributeValues(),refDict: [":v0":.NS(["0.1","0.2"])])
let filter10 = DynoCondition.compare("array",.eq, [Data(base64Encoded: "0000000000000000")!])
let eavFilter10 = filter10.toPayload()
XCTAssertEqual(filter10.description, #"array = BS([12 bytes])"#)
XCTAssertEqual(eavFilter10.toDynoFilterExpression(), "#n0 = :v0")
XCTAssertEqual(eavFilter10.toDynoExpressionAttributeNames(),["#n0":"array"])
XCTAssertEqualDictionaries(item: eavFilter10.toDynoExpressionAttributeValues(),refDict: [":v0":.BS([Data(base64Encoded: "0000000000000000")!])])
let filter11 = DynoCondition.compare("dict",.eq, ["a":1234])
let eavFilter11 = filter11.toPayload()
// XCTAssertEqual(filter11.description, #"dict = M(["a":"1234"])"#)
XCTAssertEqual(eavFilter11.toDynoFilterExpression(), "#n0 = :v0")
XCTAssertEqual(eavFilter11.toDynoExpressionAttributeNames(),["#n0":"dict"])
XCTAssertEqualDictionaries(item: eavFilter11.toDynoExpressionAttributeValues(),refDict: [":v0":.M(["a":.N("1234")])])
let filter12 = DynoCondition.compare("uint",.gt, UInt(123))
let eavFilter12 = filter12.toPayload()
XCTAssertEqual(eavFilter12.toDynoFilterExpression(), "#n0 > :v0")
XCTAssertEqual(eavFilter12.toDynoExpressionAttributeNames(),["#n0":"uint"])
XCTAssertEqualDictionaries(item: eavFilter12.toDynoExpressionAttributeValues(),refDict: [":v0":.N("123")])
let filterAndOrNot = DynoCondition.and(filter1, DynoCondition.or(filter2,DynoCondition.not(filter3)))
let eavFilterAndOrNot = filterAndOrNot.toPayload()
XCTAssertEqual(filterAndOrNot.description, #"(teeth BETWEEN N("50") AND N("4000")) AND ((teeth >= N("40")) OR (NOT ("colour" IN (S("green"), S("aqua")))))"#)
XCTAssertEqual(eavFilterAndOrNot.toDynoFilterExpression(),"(#n0 BETWEEN :v0 AND :v1 AND (#n2 >= :v2 OR NOT #n3 IN (:v3,:v4)))")
XCTAssertEqualDictionaries(item: eavFilter3.toDynoExpressionAttributeValues(), refDict: [":v0":.S("green"),":v1":.S("aqua")])
}
@available(OSX 15.0, *)
func testAWSHTTPRequest() {
// This makes a call to AWS but with dummy credentials.
let signer = AWSSignatureGenerator(secretKeyLocation: getTestCredentialsURL2() , log: true)
let awsHttpRequest = AWSHTTPRequest(
region: "us-east-2",
action: MockAction(),
signer: signer!,
log: true)
let result = XCTWaitForPublisherFailure {
awsHttpRequest.request(forSession: URLSession.shared)
}
if let failure = (result as? AWSRequestError),
case AWSRequestError.invalidResponse(400,
"""
{\"__type\":\"com.amazon.coral.service#UnrecognizedClientException\",\"message\":\"The security token included in the request is invalid.\"}
""") = failure {
} else {
XCTFail("Expected 400, got \(String(describing: result))")
}
}
@available(OSX 15.0, *)
func testDefaultAWSEncodeObject() {
let dino = Mockosaur(id: "123", name: "Bob", colours: ["silver","grey"], teeth: 5)
let encoded = DynoAttributeValue.fromTypedObject(dino)
NSLog("\(encoded)")
XCTAssertEqualDictionaries(item: encoded, refDict: ["name":.S("Bob"), "teeth":.N("5"), "id":.S("123"), "colours":.L([.S("silver"),.S("grey")])])
}
func testDefaultAWSEncodeComplexObject() {
let dinoA = Mockosaur(id: "123", name: "Bob", colours: ["silver","grey"], teeth: 5)
let dinoB = Mockosaur(id: "456", name: "Sally", colours: ["yellow","blue","white"], teeth: 50)
let complex = MockComplexObject(dinos: [dinoA,dinoB], data: Data(repeating: 33, count: 10), date: Date(year: 2019, month: 12, day: 1)!, double: [12.34], float: [56.78], bool: true)
let encoded = DynoAttributeValue.fromTypedObject(complex)
NSLog("\(encoded)")
XCTAssertEqualDictionaries(item: encoded, refDict: [
"date":.S("2019-12-01T05:00:00Z"),
"dinos":.L([ .M(["colours":.L([.S("silver"),.S("grey")]),
"name":.S("Bob"),
"teeth":.N("5"),
"id":.S("123")]),
.M(["colours":.L([.S("yellow"),.S("blue"),.S("white")]),
"name":.S("Sally"),
"teeth":.N("50"),
"id":.S("456")])
]),
"data":.B(Data(repeating: 33, count: 10)),
"double":.NS(["12.34"]),
"float":.NS(["56.78"]),
"bool":.BOOL(true)
])
}
func testCustomAWSEncodebject() {
let dt = MockObjectCustomEncoding(date: Date(year: 2019, month: 12, day: 1)!)
let encoded = MockObjectCustomEncoding.encoding(v: dt)
NSLog("\(encoded)")
XCTAssertEqualDictionaries(item: encoded, refDict:
["date": .N("596869200.0")]
)
}
/* ************************************************************************************************************ */
func getTestCredentialsURL1() -> URL {
return getTestResourceDirectory().appendingPathComponent("test_credentials1.txt")
}
func getTestCredentialsURL2() -> URL {
// argh, Amazon documentation uses 2 SLIGHTLY different keys for some reason
return getTestResourceDirectory().appendingPathComponent("test_credentials2.txt")
}
}
public func XCTAssertEqualDictionaries( item:[String:DynoAttributeValue],
refDict:[String:DynoAttributeValue],
file: StaticString = #file,
line: UInt = #line) {
XCTAssertEqual(item.count, refDict.count, "Different size dictionaries", file: file, line: line)
for key in item.keys {
let refValue = refDict[key] ?? DynoAttributeValue.NULL(true)
XCTAssertEqual(item[key], refDict[key], "Dictionaries differ for \(key): Original dictionary has \(refValue), test has \(item[key]!)", file: file, line: line)
}
}
|
//
// RobinhoodPageViewModel.swift
// RHLinePlotExample
//
// Created by Wirawit Rueopas on 4/11/20.
// Copyright © 2020 Wirawit Rueopas. All rights reserved.
//
import Combine
import SwiftUI
class RobinhoodPageViewModel: ObservableObject {
typealias PlotData = [(time: Date, price: CGFloat)]
private let logic: RobinhoodPageBusinessLogic
@Published var isLoading = false
@Published var intradayPlotData: PlotData?
@Published var dailyPlotData: PlotData?
@Published var weeklyPlotData: PlotData?
@Published var monthlyPlotData: PlotData?
// For displaying segments
var segmentsDataCache: [TimeDisplayOption: [Int]] = [:]
let symbol: String
private var storage = Set<AnyCancellable>()
init(symbol: String) {
self.symbol = symbol
self.logic = RobinhoodPageBusinessLogic(symbol: symbol)
StocksAPI.networkActivity
.receive(on: RunLoop.main)
.assign(to: \.isLoading, on: self)
.store(in: &storage)
let publishers = [
logic.$intradayResponse,
logic.$dailyResponse,
logic.$weeklyResponse,
logic.$monthlyResponse
]
let assignees: [ReferenceWritableKeyPath<RobinhoodPageViewModel, PlotData?>] = [
\.intradayPlotData,
\.dailyPlotData,
\.weeklyPlotData,
\.monthlyPlotData
]
let timeDisplayOptions: [TimeDisplayOption] = [.hourly, .daily, .weekly, .monthly]
zip(publishers, assignees).enumerated()
.forEach { (i, tup) in
let (publisher, assignee) = tup
let displayOption = timeDisplayOptions[i]
publisher
.compactMap(mapToPlotData)
.receive(on: RunLoop.main)
.sink(receiveValue: { (plotData) in
self[keyPath: assignee] = plotData
// Cache segments
let segments: [Int]
switch displayOption {
case .hourly:
segments = Self.segmentByHours(values: plotData)
case .daily:
segments = Self.segmentByMonths(values: plotData)
case .weekly, .monthly:
segments = Self.segmentByYears(values: plotData)
}
self.segmentsDataCache[displayOption] = segments
})
.store(in: &storage)
}
}
static func segmentByHours(values: PlotData) -> [Int] {
let calendar = Calendar.current
var segments = [Int]()
let lastStopper = calendar.endOfDay(for: values.last!.time)
// Work backward from last day
let breakpoints = (0..<values.count).map {
calendar.date(byAdding: .hour, value: -$0, to: lastStopper)!
}.reversed() // Reverse to be ascending
segments.append(0)
var currentRecords = ArraySlice(values)
for upper in breakpoints {
// Jump to first index of next segment
if let ind = currentRecords.firstIndex(where: { $0.time > upper }), ind != segments.last {
segments.append(ind)
// Cut off, and continue
currentRecords = currentRecords[ind...]
}
}
return segments
}
static func segmentByMonths(values: PlotData) -> [Int] {
let calendar = Calendar.current
var segments = [Int]()
let lastStopper = calendar.startOfMonth(for: values.last!.time)
// Work backward from last day
let breakpoints = (0..<values.count).map {
calendar.date(byAdding: .month, value: -$0, to: lastStopper)!
}.reversed() // Reverse to be ascending
segments.append(0)
var currentRecords = ArraySlice(values)
for upper in breakpoints {
// Jump to first index of next segment
if let ind = currentRecords.firstIndex(where: { $0.time > upper }), ind != segments.last {
segments.append(ind)
// Cut off, and continue
currentRecords = currentRecords[ind...]
}
}
return segments
}
static func segmentByYears(values: PlotData) -> [Int] {
let calendar = Calendar.current
var segments = [Int]()
let lastStopper = calendar.startOfYear(for: values.last!.time)
// Work backward from last day
let breakpoints = (0..<values.count).map {
calendar.date(byAdding: .year, value: -$0, to: lastStopper)!
}.reversed() // Reverse to be ascending
segments.append(0)
var currentRecords = ArraySlice(values)
for upper in breakpoints {
// Jump to first index of next segment
if let ind = currentRecords.firstIndex(where: { $0.time > upper }), ind != segments.last {
segments.append(ind)
// Cut off, and continue
currentRecords = currentRecords[ind...]
}
}
return segments
}
private func mapToPlotData(_ response: StockAPIResponse?) -> PlotData? {
response?.timeSeries.map { tup in (tup.time, CGFloat(tup.info.closePrice)) }
}
func fetchOnAppear() {
logic.fetch(timeSeriesType: .intraday)
logic.fetch(timeSeriesType: .daily)
logic.fetch(timeSeriesType: .weekly)
logic.fetch(timeSeriesType: .monthly)
}
func cancelAllFetchesOnDisappear() {
logic.storage.forEach { (c) in
c.cancel()
}
}
}
|
import Foundation
import Blindside
class UseCasesModule: BSModule {
func configure(_ binder: BSBinder) {
binder.bind(FetchArticlesUseCase.self) { args, injector in
return FetchArticlesUseCase.init(
articlesService: injector.getInstance(ArticlesService.self) as! ArticlesServiceProtocol
)
}
}
}
|
//
// Alarm.swift
// Wake Forsure
//
// Created by Jeanlouis Rebello on 2016-12-05.
// Copyright © 2016 DistinctApps. All rights reserved.
//
import UIKit
import Foundation
import MediaPlayer
import AVFoundation
class Alarm: NSObject, NSCoding {
var alarmName: String!
var timeUntilAlarm: String!
var alarmTime: String!
var alarmDate: Date!
var alarmSong: MPMediaItemCollection!
var defaultAlarmSong: [String: URL]!
//Initializer for when the user choses custom Song
init(alarmName: String?, timeUntilAlarm: String?, alarmTime: String?, alarmDate: Date?, alarmSong: MPMediaItemCollection?) {
self.alarmName = alarmName
self.timeUntilAlarm = timeUntilAlarm
self.alarmTime = alarmTime
self.alarmDate = alarmDate
self.alarmSong = alarmSong
}
//Intializer for when the user choses a default Song
init(alarmName: String?, timeUntilAlarm: String?, alarmTime: String?, alarmDate: Date?, defaultAlarmSong: [String: URL]?) {
self.alarmName = alarmName
self.timeUntilAlarm = timeUntilAlarm
self.alarmTime = alarmTime
self.alarmDate = alarmDate
self.defaultAlarmSong = defaultAlarmSong
}
//Initializer for when the user has not chosen a song yet
init(alarmName: String?, timeUntilAlarm: String?, alarmTime: String?, alarmDate: Date?) {
self.alarmName = alarmName
self.timeUntilAlarm = timeUntilAlarm
self.alarmTime = alarmTime
self.alarmDate = alarmDate
}
override init(){}
required init(coder decoder: NSCoder) {
self.alarmName = decoder.decodeObject(forKey: "alarmName") as! String
self.timeUntilAlarm = decoder.decodeObject(forKey: "timeUntilAlarm") as! String
self.alarmTime = decoder.decodeObject(forKey: "alarmTime") as! String
self.alarmDate = decoder.decodeObject(forKey: "alarmDate") as! Date
self.alarmSong = decoder.decodeObject(forKey: "alarmSong") as? MPMediaItemCollection
self.defaultAlarmSong = decoder.decodeObject(forKey: "defaultAlarmSong") as? [String: URL]
}
func encode(with aCoder: NSCoder) {
if let alarmName = alarmName { aCoder.encode(alarmName, forKey: "alarmName") }
if let timeUntilAlarm = timeUntilAlarm { aCoder.encode(timeUntilAlarm, forKey: "timeUntilAlarm") }
if let alarmTime = alarmTime { aCoder.encode(alarmTime, forKey: "alarmTime") }
if let alarmDate = alarmDate { aCoder.encode(alarmDate, forKey: "alarmDate") }
if let alarmSong = alarmSong { aCoder.encode(alarmSong, forKey: "alarmSong") }
if let defaultAlarmSong = defaultAlarmSong { aCoder.encode(defaultAlarmSong, forKey: "defaultAlarmSong") }
}
func timeUntilAlarm(userDate: TimeInterval) -> String {
var timeUntilAlarmGoesOff = ""
//One day forward
if (userDate < 0) {
timeUntilAlarmGoesOff = convertTime(userTime: userDate, forwards: false)
} else if (userDate > 0 && userDate < 60) {
timeUntilAlarmGoesOff = "0h 1m"
} else if (userDate >= 60 && userDate < 3600) {
if (lround(userDate/60)==60) {
timeUntilAlarmGoesOff = "1h 0m"
} else {
timeUntilAlarmGoesOff = "0h " + String(lround(userDate/60)) + "m"
}
} else if(userDate >= 3600) {
timeUntilAlarmGoesOff = convertTime(userTime: userDate, forwards: true)
}
return timeUntilAlarmGoesOff
}
func convertTime(userTime: Double, forwards: Bool) -> String {
var numberOfSeconds = 86400.0;
var timeUntilAlarmGoesOff = 0.0
var finalString = ""
//Seconds are positive
if (forwards) {
timeUntilAlarmGoesOff = userTime
//Seconds are negative - going back.
} else {
timeUntilAlarmGoesOff = numberOfSeconds + userTime
}
//Number of hours
timeUntilAlarmGoesOff = timeUntilAlarmGoesOff / (3600)
// ** Next step is to convert decimal time to normal time **
//If Number of hours is a perfect number that has 0 minutes
if (timeUntilAlarmGoesOff.truncatingRemainder(dividingBy: 3600.0) == 0) {
let hour = String(timeUntilAlarmGoesOff / 3600)
finalString = hour + "h 0m"
//If not we have to split the hour and the minute part and convert
} else {
var hourAndMinute = String(timeUntilAlarmGoesOff).components(separatedBy: ".")
var hour = hourAndMinute[0]
finalString = hour + "h"
var minute = hourAndMinute[1]
minute = "0" + "." + minute
//If the new string minute when converted to a double is actually a Double then convert to minute
if let aMinute = Double(minute) {
if (lround(aMinute*60) == 60) {
var tempHour = Int(hour)
tempHour = tempHour!+1
hour = String(tempHour!)
finalString = hour + "h" + " 0m"
} else {
finalString += " \(lround(aMinute*60))m"
}
}
}
return finalString
}
//Previous method using AVAsset. However using a dictionary with song title and its respective URL was much easier.
/*
func getAlarmSongTitle(theSongUrl: URL) -> String {
var asset = AVURLAsset(url: theSongUrl, options: nil)
var alarmSongTitle: String? = nil
for format: String in asset.availableMetadataFormats {
for item: AVMetadataItem in asset.metadata(forFormat: format) {
if (item.commonKey == "title") {
//alarmSongTitle = UIImage(data: item.value.copy(withZone: nil))!
print("Doing the meta data stuff")
alarmSongTitle = item.value?.copy(with: nil) as! String?
print(alarmSongTitle ?? "not working" )
return alarmSongTitle!
}
}
}
return alarmSongTitle!
}
*/
}
|
//
// EmailTemplateUpdate.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** Model for Email Templates */
public struct EmailTemplateUpdate: Codable {
/** The intended name for the template. */
public var templateName: String?
/** Your template body. */
public var body: String
public init(templateName: String?, body: String) {
self.templateName = templateName
self.body = body
}
public enum CodingKeys: String, CodingKey {
case templateName = "template_name"
case body
}
}
|
import Foundation
public enum FeatureType : String, Codable {
case Float
}
public protocol Items : Codable {
}
public protocol InputOutputItems : Items {
var name: String { get }
var shape: [UInt] { get }
var featureType: FeatureType { get }
}
public struct Input : InputOutputItems {
public let name: String
public let shape: [UInt]
public let featureType: FeatureType
public init(name: String, shape: [UInt], featureType: FeatureType = .Float) {
self.name = name
self.shape = shape
self.featureType = featureType
}
}
public struct Output : InputOutputItems {
public let name: String
public let shape: [UInt]
public let featureType: FeatureType
public init(name: String, shape: [UInt], featureType: FeatureType = .Float) {
self.name = name
self.shape = shape
self.featureType = featureType
}
}
public struct TrainingInput : InputOutputItems {
public let name: String
public let shape: [UInt]
public let featureType: FeatureType
public init(name: String, shape: [UInt], featureType: FeatureType = .Float) {
self.name = name
self.shape = shape
self.featureType = featureType
}
}
@_functionBuilder
public struct ItemBuilder {
public static func buildBlock(_ children: Items...) -> [Items] {
children.compactMap{ $0 }
}
}
public struct Model {
public let version: UInt
public let shortDescription: String?
public let author: String?
public let license: String?
public let userDefined: [String : String]?
public var inputs: [String : Input]
public var outputs: [String : Output]
public var trainingInputs: [String : TrainingInput]
public var neuralNetwork: NeuralNetwork
let items: [Items]
fileprivate init(version: UInt,
shortDescription: String?,
author: String?,
license: String?,
userDefined: [String : String]?,
items: [Items]) {
self.version = version
self.shortDescription = shortDescription
self.author = author
self.license = license
self.userDefined = userDefined
self.items = items
self.inputs = [String : Input]()
self.outputs = [String : Output]()
self.trainingInputs = [String : TrainingInput]()
self.neuralNetwork = NeuralNetwork()
for item in items {
switch item {
case let input as Input:
self.inputs[input.name] = input
case let output as Output:
self.outputs[output.name] = output
case let trainingInput as TrainingInput:
self.trainingInputs[trainingInput.name] = trainingInput
case let neuralNetwork as NeuralNetwork:
self.neuralNetwork = neuralNetwork
default:
break
}
}
}
public init(version: UInt = 4,
shortDescription: String? = nil,
author: String? = nil,
license: String? = nil,
userDefined: [String : String]? = [:]) {
self.init(version: version,
shortDescription: shortDescription,
author: author,
license: license,
userDefined: userDefined,
items: [Items]())
}
public init(version: UInt = 4,
shortDescription: String? = nil,
author: String? = nil,
license: String? = nil,
userDefined: [String : String]? = [:],
@ItemBuilder _ builder: () -> Items) {
self.init(version: version,
shortDescription: shortDescription,
author: author,
license: license,
userDefined: userDefined,
items: [builder()])
}
public init(version: UInt = 4,
shortDescription: String? = nil,
author: String? = nil,
license: String? = nil,
userDefined: [String : String]? = [:],
@ItemBuilder _ builder: () -> [Items]) {
self.init(version: version,
shortDescription: shortDescription,
author: author,
license: license,
userDefined: userDefined,
items: builder())
}
public mutating func addInput(_ input: Input) {
inputs[input.name] = input
}
public mutating func addOutput(_ output: Output) {
outputs[output.name] = output
}
public mutating func addTrainingInput(_ trainingInput: TrainingInput) {
trainingInputs[trainingInput.name] = trainingInput
}
}
extension Model : Codable {
private enum CodingKeys : CodingKey {
case version, shortDescription, author, license, userDefined, inputs, outputs, trainingInputs, neuralNetwork
}
public init(from decoder: Swift.Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.version = try container.decode(UInt.self, forKey: .version)
self.shortDescription = try container.decode(String?.self, forKey: .shortDescription)
self.author = try container.decode(String?.self, forKey: .author)
self.license = try container.decode(String?.self, forKey: .license)
self.userDefined = try container.decode([String : String]?.self, forKey: .userDefined)
self.inputs = try container.decode([String : Input].self, forKey: .inputs)
self.outputs = try container.decode([String : Output].self, forKey: .outputs)
self.trainingInputs = try container.decode([String : TrainingInput].self, forKey: .trainingInputs)
self.neuralNetwork = try container.decode(NeuralNetwork.self, forKey: .neuralNetwork)
self.items = [Items]()
}
}
|
//
// ViewController.swift
// ServerDemo
//
// Created by C on 16/1/28.
// Copyright © 2016年 YoungKook. All rights reserved.
//
import Cocoa
let WELCOME_MSG = 0
let ECHO_MSG = 1
class ViewController: NSViewController {
@IBOutlet var textView: NSTextView!
var listenSocket: AsyncSocket!
var connectedSockets = NSMutableArray()
var isRunning: Bool = false
@IBOutlet weak var portField: NSTextField!
@IBOutlet weak var startStop: NSButton!
override func viewDidLoad() {
super.viewDidLoad()
listenSocket = AsyncSocket(delegate: self)
listenSocket.setRunLoopModes([NSRunLoopCommonModes])
self.title = ""
textView.editable = false
portField.editable = false
// let vc = ServerController().viewDidLoad()
}
@IBAction func startAndStop(sender: AnyObject) {
if !isRunning {
var port = portField.integerValue
if port < 0 && port > 65535 {
port = 0
}
do {
try listenSocket.acceptOnPort(uint16(8888))
} catch let error as NSError {
logError(String(format: "Error starting server: %@", error.localizedDescription))
return
}
logInfo(String(format: "Echo server started on port %hu", listenSocket.localHost()))
isRunning = true
// portField.editable = true
startStop.title = "Stop"
} else {
listenSocket.disconnect()
for (i, _) in connectedSockets.enumerate() {
connectedSockets[i].disconnect()
}
logInfo("Stopped Echo server")
isRunning = false
// portField.enabled = true
startStop.title = "Start"
}
}
override func onSocket(sock: AsyncSocket!, didAcceptNewSocket newSocket: AsyncSocket!) {
connectedSockets.addObject(newSocket)
}
// MARK: 客户端连接成功
override func onSocket(sock: AsyncSocket!, didConnectToHost host: String!, port: UInt16) {
logInfo(String(format: "Accepted client %@:%hu", host, port))
portField.placeholderString = String(port)
let successMsg = "Welcome to youngkook Server"
let data = successMsg.dataUsingEncoding(NSUTF8StringEncoding)
sock.writeData(data, withTimeout: -1, tag: WELCOME_MSG)
}
override func onSocket(sock: AsyncSocket!, didWriteDataWithTag tag: Int) {
sock.readDataWithTimeout(-1, tag: 0)
}
// MARK: 接收数据
override func onSocket(sock: AsyncSocket!, didReadData data: NSData!, withTag tag: Int) {
// let strData = data.subdataWithRange(NSMakeRange(0, data.length - 2))
let recvMsg = String(data: data, encoding: NSUTF8StringEncoding)
guard let msg = recvMsg else {
logError("Error converting recived data into UTF-8 encode")
return
}
logMessage(msg)
var str: String!
for (_, socket) in connectedSockets.enumerate() {
if sock.isEqual(socket) {
str = "我说: \(msg)"
} else {
str = "他说: \(msg)"
}
}
// 回发数据
let backData = str.dataUsingEncoding(NSUTF8StringEncoding)
sock.writeData(backData, withTimeout: -1, tag: ECHO_MSG)
}
override func onSocket(sock: AsyncSocket!, willDisconnectWithError err: NSError!) {
logInfo(String(format: "Client willDisconnected: %@:%hu", sock.connectedHost(), sock.connectedPort()))
if let e = err {
print(e.localizedDescription)
}
}
override func onSocketDidDisconnect(sock: AsyncSocket!) {
connectedSockets.removeObject(sock)
}
func logError(msg: String) {
print(msg)
}
func logInfo(msg: String) {
print(msg)
}
func logMessage(msg: String) {
print(msg)
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
|
//
// DataError.swift
//
// Created by Igor Shelopaev on 30.04.2021.
//
import Foundation
/// Data error
public protocol DataError: Error {
/// Get error description
func getDescription() -> String
}
|
//
// LearnObservableObject.swift
// switui_learn
//
// Created by laijihua on 2020/10/17.
//
import SwiftUI
import Combine
class BookingStore: ObservableObject {
var objectWillChange = PassthroughSubject<Void, Never>()
var bookingName: String = "" {
didSet { updateUI() }
}
var seats: Int = 1 {
didSet {
updateUI()
}
}
func updateUI() {
objectWillChange.send()
}
}
struct LearnObservableObject: View {
@ObservedObject var model = BookingStore()
var body: some View {
VStack{
Text(model.bookingName)
TextField("Your Name", text: $model.bookingName)
Stepper("Seats: \(model.seats)", value: $model.seats, in: 1...5)
}.navigationTitle(Text("ObservableObject"))
}
}
struct LearnObservableObject_Previews: PreviewProvider {
static var previews: some View {
NavigationView(content: {
LearnObservableObject()
})
}
}
|
//
// AudioControllerViewModel.swift
// AudioController
//
// Created by Admin on 11/11/17.
// Copyright © 2017 newbeeCorp. All rights reserved.
//
import UIKit
import AVFoundation
class AudioControllerViewModel {
fileprivate let audioPlayer:AudioPlayerProtocol!
class func create () -> AudioControllerViewModel {
let audioPlayerService = AudioPlayerService(audioSession: AVAudioSession.sharedInstance())
let fileAdapter = IOFileAdapter()
let audioPlayer = AudioPlayer(audioPlayerService: audioPlayerService,
fileAdapter: fileAdapter)
return AudioControllerViewModel(audioPlayer: audioPlayer)
}
init(audioPlayer: AudioPlayerProtocol) {
self.audioPlayer = audioPlayer;
}
func recordButtonTapped() {
self.audioPlayer.record()
}
func playButtonTapped() {
self.audioPlayer.play()
}
func stopRecordButtonTapped() {
self.audioPlayer.stopRecord()
}
}
|
//
// BaseScreen.swift
// ObserverAndNotificatinPractice
//
// Created by Lane Faison on 7/30/17.
// Copyright © 2017 Lane Faison. All rights reserved.
//
import UIKit
let yankeesNotificationKey = "co.lanefasion.yankees"
let redsoxNotificationKey = "co.lanefaison.redsox"
class BaseScreen: UIViewController {
@IBOutlet weak var chooseButton: UIButton!
@IBOutlet weak var choiceImage: UIImageView!
@IBOutlet weak var teamNameLabel: UILabel!
let yankees = Notification.Name(rawValue: yankeesNotificationKey)
let redsox = Notification.Name(rawValue: redsoxNotificationKey)
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
chooseButton.layer.cornerRadius = chooseButton.frame.height/2
createObservers()
}
func createObservers() {
// Yankees
NotificationCenter.default.addObserver(self, selector: #selector(BaseScreen.updateTeamImage(notification:)), name: yankees, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(BaseScreen.updateNameLabel(notification:)), name: yankees, object: nil)
// Red Sox
NotificationCenter.default.addObserver(self, selector: #selector(BaseScreen.updateTeamImage(notification:)), name: redsox, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(BaseScreen.updateNameLabel(notification:)), name: redsox, object: nil)
}
func updateTeamImage(notification: NSNotification) {
let isYankees = notification.name == yankees
let image = isYankees ? UIImage(named: "yankees")! : UIImage(named: "redsox")!
choiceImage.image = image
}
func updateNameLabel(notification: NSNotification) {
let isYankees = notification.name == yankees
let name = isYankees ? "New York Yankees" : "Boston Red Sox"
teamNameLabel.text = name
}
@IBAction func chooseButtonTapped(_ sender: Any) {
let selectionVC = storyboard?.instantiateViewController(withIdentifier: "SelectionScreen") as! SelectionScreen
present(selectionVC, animated: true, completion: nil)
}
}
|
//
// ProductRepo.swift
// ToDoList
//
// Created by njliu on 1/25/15.
// Copyright (c) 2015 Naijia Liu. All rights reserved.
//
import Foundation
class ProductRepo {
class var sharedInstance: ProductRepo {
struct Static {
static var instance: ProductRepo?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = ProductRepo()
}
return Static.instance!
}
let products: [Product]
var allNames: [String] {
return products.map{$0.name}
}
private init() {
let path = NSBundle.mainBundle().pathForResource("products", ofType: "json")
var jsonData = NSData(contentsOfFile: path!, options: nil, error: nil)
var jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData!, options: nil, error: nil) as? [NSDictionary]
products = Product.parse(jsonDict)
}
func getAll() -> [Product] {
return products
}
func getByName(name: String) -> Product? {
return ProductRepo.getByName(products, name: name)
}
func getByCode(code: String) -> Product? {
return products.filter({$0.code == code}).first
}
class func getByName(products:[Product], name: String) -> Product? {
for partOfName in expendName(name) {
let posibbleProducts = products.filter{$0.name.rangeOfString(partOfName, options: .CaseInsensitiveSearch) != nil}
if let product = posibbleProducts.first {
return product
}
}
return nil
}
private class func expendName(name: String) -> [String] {
var results = [String]()
results.append(name)
let words = split(name) {$0 == " "}
results += words.filter{$0 != " "}
return results
}
} |
//
// StrikeTableViewCell.swift
// DroneStrike
//
// Created by Ron Lane on 7/25/16.
// Copyright © 2016 Ron Lane. All rights reserved.
//
import UIKit
class StrikeTableViewCell: UITableViewCell {
// MARK: - Outlets
@IBOutlet weak var countryLabel: UILabel!
@IBOutlet weak var townLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var targetLabel: UILabel!
@IBOutlet weak var deathsLabel: UILabel!
}
|
//
// ArticleViewController.swift
// NYT
//
// Created by Rupesh Jaiswal on 26/1/20.
// Copyright © 2019 Rupesh Jaiswal. All rights reserved.
//
import UIKit
import CoreData
class ArticleViewController: UIViewController {
@IBOutlet private weak var articleTableView: UITableView!
@IBOutlet private weak var activityIndicatorView: UIActivityIndicatorView!
private var articleTableViewDataSource = ArticleTableViewDataSource()
var popularType: PopularType = .emailed
var offset = 0
var isFetchInProgress = false
private let appDelegate = UIApplication.shared.delegate as! AppDelegate
private let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var articleData: [ArticleData] = []
var popularTypeString: String {
if popularType == .emailed { return "Most Emailed" }
else if popularType == .shared {
return "Most Shared"
} else {
return "Most Viewed"
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = popularTypeString
setUpUIComponents()
fetchArticleFromDB()
articleData.isEmpty ? fetchArticles() : buidRowsFromArticleData()
}
func fetchArticleFromDB() {
let request = ArticleData.fetchRequest() as NSFetchRequest<ArticleData>
request.predicate = NSPredicate(format: "type CONTAINS[cd] %@", popularTypeString)
do {
articleData = try context.fetch(request)
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
}
private func buidRowsFromArticleData() {
var results: [ArticleResult] = []
for (_, element) in articleData.enumerated() {
let article = ArticleResult()
article.abstract = element.abstract
article.byline = element.byline
article.source = element.source
article.publishedDate = element.publishedDate
article.title = element.title
results.append(article)
}
articleTableViewDataSource.isOfflineMode = true
articleTableViewDataSource.articleResult = results
}
private func setUpUIComponents() {
activityIndicatorView.hidesWhenStopped = true
articleTableView?.dataSource = articleTableViewDataSource
articleTableView?.delegate = articleTableViewDataSource
articleTableViewDataSource.delegate = self
articleTableView.rowHeight = UITableView.automaticDimension
articleTableView.estimatedRowHeight = UITableView.automaticDimension
articleTableView?.register(UINib(nibName: ArticleTableViewCell.xibName, bundle: nil), forCellReuseIdentifier: ArticleTableViewCell.reuseIdentifier)
articleTableView?.tableFooterView = UIView()
}
private func saveArticles(articleResults: [ArticleResult]) {
for articleResult in articleResults {
let article = ArticleData(entity: ArticleData.entity(), insertInto: context)
article.title = articleResult.title ?? ""
article.publishedDate = articleResult.publishedDate ?? ""
article.source = articleResult.source ?? ""
article.abstract = articleResult.abstract ?? ""
article.byline = articleResult.byline ?? ""
article.type = popularTypeString
appDelegate.saveContext()
}
}
}
extension ArticleViewController: ArticleTableViewDataSourceDelegate {
func navigateToArticleDetailVC(articleResult: ArticleResult) {
let articleDetailViewController = ArticleDetailViewController()
articleDetailViewController.articleResult = articleResult
navigationController?.pushViewController(articleDetailViewController, animated: true)
}
func onbuildRowsCompleted() {
articleTableView.reloadData()
}
func fetchArticles() {
guard !isFetchInProgress else { return }
isFetchInProgress = true
activityIndicatorView.startAnimating()
ArticleRequest().getArticles(for: popularType, offset: offset, { [weak self] (article) in
guard let weakSelf = self else { return }
weakSelf.activityIndicatorView.stopAnimating()
weakSelf.articleTableViewDataSource.totalCount = article.count ?? 0
weakSelf.articleTableViewDataSource.articleResult = article.results
weakSelf.isFetchInProgress = false
weakSelf.offset = weakSelf.offset + 20
weakSelf.saveArticles(articleResults: article.results)
}, failure: {
[weak self] (error) in
guard let weakSelf = self else { return }
weakSelf.isFetchInProgress = false
weakSelf.activityIndicatorView.stopAnimating()
ErrorHandler.showError(error: error, viewController: self!)
})
}
}
|
//
// PostCommentsViewModel.swift
// RedditLiveCoding
//
// Created by Vadim Bulavin on 8/19/20.
//
import Combine
class PostCommentsViewModel: ObservableObject {
init(postID: String, subreddit: String) {
self.postID = postID
self.subreddit = subreddit
}
@Published var comments: [Comment]?
let postID: String
let subreddit: String
private var subscriptions = Set<AnyCancellable>()
func fetchComments() {
RedditAPI.fetchComments(subreddit: subreddit, postID: postID)
.sink(receiveCompletion: { _ in },
receiveValue: { [weak self] comments in
self?.comments = comments
})
.store(in: &subscriptions)
}
}
|
//
// PageControllerManager.swift
// OrgTech
//
// Created by Maksym Balukhtin on 30.04.2020.
// Copyright © 2020 Maksym Balukhtin. All rights reserved.
//
import UIKit
enum PageControllerManagerEvent {
case onPageChanged(Int)
}
class PageControllerManager: NSObject {
private let pageController: UIPageViewController
private var viewControllers = [UIViewController]()
private var lastKnownController: UIViewController?
var eventHandler: EventHandler<PageControllerManagerEvent>?
init(_ pageController: UIPageViewController) {
self.pageController = pageController
super.init()
pageController.dataSource = self
pageController.delegate = self
}
func populateControllers(relatedTo data: [MainModelProtocol]) {
let topModel = data.filter { $0.top != nil }
let saleModel = data.filter { $0.sale != nil }
viewControllers = [topModel, saleModel].map { model -> UIViewController in
var module = HomeBuilder.create()
module.presenter.insertedData = model
return module.view.viewController
}
pageController.setViewControllers([viewControllers[0]], direction: .forward, animated: false, completion: nil)
}
func selectPage(at index: Int) {
let direction: UIPageViewController.NavigationDirection = index < viewControllers.count - 1 ? .reverse : .forward
pageController.setViewControllers([viewControllers[index]], direction: direction, animated: true, completion: nil)
}
}
extension PageControllerManager: UIPageViewControllerDataSource {
func presentationCount(for pageViewController: UIPageViewController) -> Int {
return 2
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
if let index = viewControllers.firstIndex(of: viewController) {
if index == 0 {
return viewControllers.last
} else {
return viewControllers[index - 1]
}
}
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
if let index = viewControllers.firstIndex(of: viewController) {
if index < viewControllers.count - 1 {
return viewControllers[index + 1]
} else {
return viewControllers.first
}
}
return nil
}
}
extension PageControllerManager: UIPageViewControllerDelegate {
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if let controllers = pageViewController.viewControllers, let index = self.viewControllers.firstIndex(of: controllers[0]) {
eventHandler?(.onPageChanged(index))
}
}
}
|
import Foundation
import CryptoKit
public typealias TransactionId = String
public typealias Base64EncodedString = String
public extension Transaction {
struct PriceRequest {
public init(bytes: Int = 0, target: Address? = nil) {
self.bytes = bytes
self.target = target
}
public var bytes: Int = 0
public var target: Address?
}
struct Tag: Codable {
public let name: String
public let value: String
public init(name: String, value: String) {
self.name = name
self.value = value
}
}
}
public struct Transaction: Codable {
public var id: TransactionId = ""
public var last_tx: TransactionId = ""
public var owner: String = ""
public var tags = [Tag]()
public var target: String = ""
public var quantity: String = "0"
public var data: String = ""
public var reward: String = ""
public var signature: String = ""
private enum CodingKeys: String, CodingKey {
case id, last_tx, owner, tags, target, quantity, data, reward, signature
}
public var priceRequest: PriceRequest {
PriceRequest(bytes: rawData.count, target: Address(address: target))
}
public var rawData = Data()
}
public extension Transaction {
init(data: Data) {
self.rawData = data
}
init(amount: Amount, target: Address) {
self.quantity = String(describing: amount)
self.target = target.address
}
func sign(with wallet: Wallet) async throws -> Transaction {
var tx = self
tx.last_tx = try await Transaction.anchor()
tx.data = rawData.base64URLEncodedString()
let priceAmount = try await Transaction.price(for: priceRequest)
tx.reward = String(describing: priceAmount)
tx.owner = wallet.ownerModulus
let signedMessage = try wallet.sign(tx.signatureBody())
tx.signature = signedMessage.base64URLEncodedString()
tx.id = SHA256.hash(data: signedMessage).data
.base64URLEncodedString()
return tx
}
func commit() async throws {
guard !signature.isEmpty else {
throw "Missing signature on transaction."
}
let commit = Arweave.shared.request(for: .commit(self))
_ = try await HttpClient.request(commit)
}
private func signatureBody() -> Data {
return [
Data(base64URLEncoded: owner),
Data(base64URLEncoded: target),
rawData,
quantity.data(using: .utf8),
reward.data(using: .utf8),
Data(base64URLEncoded: last_tx),
tags.combined.data(using: .utf8)
]
.compactMap { $0 }
.combined
}
}
public extension Transaction {
static func find(_ txId: TransactionId) async throws -> Transaction {
let findEndpoint = Arweave.shared.request(for: .transaction(id: txId))
let response = try await HttpClient.request(findEndpoint)
return try JSONDecoder().decode(Transaction.self, from: response.data)
}
static func data(for txId: TransactionId) async throws -> Base64EncodedString {
let target = Arweave.shared.request(for: .transactionData(id: txId))
let response = try await HttpClient.request(target)
return String(decoding: response.data, as: UTF8.self)
}
static func status(of txId: TransactionId) async throws -> Transaction.Status {
let target = Arweave.shared.request(for: .transactionStatus(id: txId))
let response = try await HttpClient.request(target)
var status: Transaction.Status
if response.statusCode == 200 {
let data = try JSONDecoder().decode(Transaction.Status.Data.self, from: response.data)
status = .accepted(data: data)
} else {
status = Transaction.Status(rawValue: .status(response.statusCode))!
}
return status
}
static func price(for request: Transaction.PriceRequest) async throws -> Amount {
let target = Arweave.shared.request(for: .reward(request))
let response = try await HttpClient.request(target)
let costString = String(decoding: response.data, as: UTF8.self)
guard let value = Double(costString) else {
throw "Invalid response"
}
return Amount(value: value, unit: .winston)
}
static func anchor() async throws -> String {
let target = Arweave.shared.request(for: .txAnchor)
let response = try await HttpClient.request(target)
let anchor = String(decoding: response.data, as: UTF8.self)
return anchor
}
}
extension Array where Element == Transaction.Tag {
var combined: String {
reduce(into: "") { str, tag in
str += tag.name
str += tag.value
}
}
}
|
//
// Modifiers.swift
// sugaX
//
// Created by Nicolas Ott on 14.06.21.
//
import SwiftUI
import Foundation
extension Color {
public static var prime: Color {
return Color("prime")
}
}
extension Color {
public static var primeInverted: Color {
return Color("primeInverted")
}
}
|
//
// XPubView.swift
// BCWallet
//
// Created by Miroslav Djukic on 20/07/2020.
// Copyright © 2020 Miroslav Djukic. All rights reserved.
//
import SwiftUI
import BCWalletModel
struct XPubView: View {
@ObservedObject var xPubViewModel: XPubViewModel
@State var xPub: String = "xpub6CfLQa8fLgtouvLxrb8EtvjbXfoC1yqzH6YbTJw4dP7srt523AhcMV8Uh4K3TWSHz9oDWmn9MuJogzdGU3ncxkBsAC9wFBLmFrWT9Ek81kQ"
@State var selectedTx: TransactionViewModel? = nil
var body: some View {
VStack {
HeaderXPubView(xPub: $xPub,
xPubViewModel: xPubViewModel)
.padding()
List(self.xPubViewModel.transactions, id: \.transactionID) { transaction in
Button(action: {
self.selectedTx = transaction
}) {
TransactionRow(transaction: transaction)
.padding([.top, .bottom])
}
}
Spacer()
}
.loading(isLoading: $xPubViewModel.isLoading)
.alert(item: $xPubViewModel.alertMessage) { message in
Alert(title: Text(message.message), dismissButton: .cancel())
}
.onAppear() {
self.xPubViewModel.fetchWalletData(xPub: self.xPub)
}
.sheet(item: $selectedTx, onDismiss: {
self.selectedTx = nil
}) { _ in
TransactionDetails(transaction: self.$selectedTx)
}
}
}
|
//
// ViewController.swift
// BullsEye
//
// Created by Nelson Jaimes Gonzales on 30/08/18.
// Copyright © 2018 UNMSM. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var currentValue : Int = 0
var targerValue : Int = 0
var score : Int = 0
var round: Int = 0
@IBOutlet weak var lbRandom: UILabel!
@IBOutlet weak var slProgress: UISlider!
@IBOutlet weak var lbScore: UILabel!
@IBOutlet weak var lbRound: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
onClickStartOver()
slProgress.setThumbImage(#imageLiteral(resourceName: "SliderThumb-Normal"), for: .normal)
slProgress.setThumbImage(#imageLiteral(resourceName: "SliderThumb-Highlighted"), for: .highlighted)
let insets = UIEdgeInsets.init(top: 0, left: 14, bottom: 0, right: 14)
let trackLeftRezisable = #imageLiteral(resourceName: "SliderTrackLeft").resizableImage(withCapInsets: insets)
let trackRigthtRezisable = #imageLiteral(resourceName: "SliderTrackRight").resizableImage(withCapInsets: insets)
slProgress.setMaximumTrackImage(trackRigthtRezisable, for: .normal)
slProgress.setMinimumTrackImage(trackLeftRezisable, for: .normal)
}
func startNewRound(){
currentValue = 50
targerValue = Int(arc4random_uniform(101))
slProgress.value = Float(currentValue)
round += 1
self.updateLabels()
}
func updateLabels(){
lbRandom.text = String(targerValue)
lbScore.text = String(score)
lbRound.text = String(round)
}
@IBAction func onClickStartOver(){
round = 0
score = 0
startNewRound()
}
@IBAction func onClickHitMe() {
var difference :Int
var title : String
difference = abs(currentValue - targerValue)
var points = 100 - difference
if difference == 0{
title = "Congratulations \u{1F389}"
points += 100
}else if difference < 5 {
title = "You almost had it! \u{1F60A}"
if (difference == 1){
points += 50
}
}else if difference < 10{
title = "Pretty good ! \u{1F601}"
}else {
title = "Not even close \u{1F614}"
}
self.score += points
let message = "New score : \(score) points"
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: {
action in
self.startNewRound()
})
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
@IBAction func sliderMove(_ slider : UISlider){
currentValue = Int(slider.value.rounded())
print("progress:\(currentValue)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
//
// ViewController.swift
// Exercise2
//
// Created by Anhnguyen on 09/10/2021.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var inputTextField: UITextField!
@IBOutlet weak var resultLabel: UILabel!
var range: [Int] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func randomAction(_ sender: UIButton) {
for i in 0...100 {
range.append(i)
}
let input: Int? = Int(inputTextField.text ?? "")
let result = range.randomElement()
if input == result {
resultLabel.text = "kết quả là: \(String(describing: result ?? 0)) chúc mừng"
} else if (input ?? 0) < (result ?? 0) {
resultLabel.text = "kết quả là: \(String(describing: result ?? 0)) bé quá"
} else {
resultLabel.text = "kết quả là: \(String(describing: result ?? 0)) lớn quá"
}
}
}
|
//
// DetailsPresenter.swift
// CleanSwiftTest
//
// Created by Dave on 5/19/21.
// Copyright (c) 2021 ___ORGANIZATIONNAME___. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
protocol DetailsPresentationLogic
{
func sendData(item: DetailsModel.Item.Response)
func itemDeleted()
}
class DetailsPresenter: DetailsPresentationLogic
{
weak var viewController: DetailsDisplayLogic?
// MARK: Do something
func sendData(item: DetailsModel.Item.Response) {
let item = DetailsModel.Item.ViewModel.init(title: item.title, details: item.details, image: item.image)
viewController?.displayData(item: item)
}
func itemDeleted() {
viewController?.routeToMain()
}
}
|
//
// Statistics.swift
// Workout app
//
// Created by Łukasz Uranowski on 03/05/2020.
// Copyright © 2020 Łukasz Uranowski. All rights reserved.
//
import SwiftUI
struct Statistics: View {
var body: some View {
VStack {
Image(systemName: "person.crop.square")
.font(.system(size: 100))
.foregroundColor(Color("DarkRed"))
.padding(.bottom, 20)
Text("STATISTICS PAGE")
}
}
}
struct Statistics_Previews: PreviewProvider {
static var previews: some View {
Statistics()
}
}
|
//
// WeiboTableViewCell.swift
// 新浪微博
//
// Created by 李旭飞 on 15/10/17.
// Copyright © 2015年 lee. All rights reserved.
//
import UIKit
let margin:CGFloat = 8.0
class WeiboTableViewCell: UITableViewCell {
/// 创建用于接收微博数据的对象
var statuses:WeiboData?{
didSet{
topView.status = statuses
contentLabel.text = statuses?.text
pictureView.status = statuses
pictureWidthCon?.constant = pictureView.bounds.width
pictureHeightCon?.constant=pictureView.bounds.height
pictureTopCon?.constant = pictureView.bounds.height==0 ? 0 : margin
}
}
///配图宽度约束
var pictureWidthCon:NSLayoutConstraint?
///配图高度约束
var pictureHeightCon:NSLayoutConstraint?
///配图顶部约束
var pictureTopCon:NSLayoutConstraint?
//MARK:- 计算行高
func rowHeightAuto(status:WeiboData)->CGFloat{
statuses=status
//强制更新,所有控件的布局都会变化
layoutIfNeeded()
return CGRectGetMaxY(bottomView.frame)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupInterface()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK:- 添加并布局控件
func setupInterface(){
contentView.addSubview(topSeparateView)
contentView.addSubview(topView)
contentView.addSubview(contentLabel)
contentView.addSubview(pictureView)
contentView.addSubview(bottomView)
topSeparateView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: contentView, size: CGSize(width:UIScreen.mainScreen().bounds.width , height: margin))
topView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: topSeparateView, size: nil)
contentView.addConstraint(NSLayoutConstraint(item: topView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Height, multiplier: 1.0, constant: 51))
contentLabel.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: topView, size: nil ,offset:CGPoint(x: margin, y: 4))
// contentView.addConstraint(NSLayoutConstraint(item: contentLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: -2 * margin))
// ///配图的约束
// let constraintsList = pictureView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: contentLabel, size: CGSize(width: 300, height: 300), offset: CGPoint(x: 0, y: margin))
//
// pictureWidthCon = pictureView.ff_Constraint(constraintsList, attribute: NSLayoutAttribute.Width)
// pictureHeightCon = pictureView.ff_Constraint(constraintsList, attribute: NSLayoutAttribute.Height)
// pictureTopCon = pictureView.ff_Constraint(constraintsList, attribute: NSLayoutAttribute.Top)
bottomView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44),offset:CGPoint(x: -margin, y: margin))
}
//MARK:- 懒加载控件
private lazy var topView:StatusesTopView = StatusesTopView()
/// 子类中需要的属性
lazy var contentLabel:UILabel={
let label=UILabel(color: UIColor.darkGrayColor(), fontSize: 15)
label.numberOfLines=0
label.preferredMaxLayoutWidth=UIScreen.mainScreen().bounds.width - 2 * margin
return label
}()
lazy var bottomView:StatusesBottomView = StatusesBottomView()
lazy var pictureView:StatusesPictureView = StatusesPictureView()
///增加cell分隔视图
private lazy var topSeparateView:UIView={
let separate = UIView()
separate.backgroundColor=UIColor.lightGrayColor()
return separate
}()
///配图视图
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
//MARK:- 微博顶部视图
private class StatusesTopView:UIView{
private var status:WeiboData?{
didSet{
iconview.image=nil
if let url = status?.user!.profile_image_url{
NSURLSession.sharedSession().downloadTaskWithURL(NSURL(string: url)!, completionHandler: { (location, _, error) -> Void in
if error != nil{
print("网络错误")
return
}
let data = NSData(contentsOfURL: location!)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.iconview.image = UIImage(data:data!)
})
}).resume()
}else{
iconview.image=UIImage(named: "avatar_default_big")
}
iconview.layer.cornerRadius = 5
iconview.layer.masksToBounds = true
nameLabel.text=status?.user?.name ?? ""
vipIconView.image=status?.user?.vipImage
memberIconView.image=status?.user?.memberImage
//TODO:
// let timeStr = status?.created_at?.componentsSeparatedByString(" ")[3]
// timeLabel.text = timeStr!
if status?.created_at != nil && status!.created_at != ""{
timeLabel.text = NSDate.Date(status!.created_at)!.dateDescription()
}
if status?.source != nil && status!.source != ""{
// var sourceStr:String? = status?.source?.componentsSeparatedByString("<")[1]
// sourceStr = sourceStr?.componentsSeparatedByString(">").las
// sourceLabel.text = "来自 " + sourceStr!
sourceLabel.text = "来自 " + status!.source!
}
// source -> "<a href=\"http://app.weibo.com/t/feed/2o92Kh\" rel=\"nofollow\">vivo_X5Max</a>"
// time -> "Sun Oct 18 12:40:06 +0800 2015"
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
private func setupUI(){
addSubview(iconview)
addSubview(nameLabel)
addSubview(vipIconView)
addSubview(memberIconView)
addSubview(timeLabel)
addSubview(sourceLabel)
//布局
iconview.ff_AlignInner(type: ff_AlignType.TopLeft, referView: self, size: CGSizeMake(35, 35), offset: CGPointMake(margin , margin))
nameLabel.ff_AlignHorizontal(type: ff_AlignType.TopRight, referView: iconview, size: nil, offset: CGPointMake(margin, 0))
timeLabel.ff_AlignHorizontal(type: ff_AlignType.BottomRight, referView: vipIconView, size: nil, offset: CGPointMake(margin, 0))
vipIconView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: iconview, size: nil, offset: CGPointMake(3, 2))
memberIconView.ff_AlignHorizontal(type: ff_AlignType.TopRight, referView: nameLabel, size: nil, offset: CGPointMake( margin,0 ))
sourceLabel.ff_AlignHorizontal(type: ff_AlignType.BottomRight, referView: timeLabel, size: nil, offset: CGPointMake(margin, 0))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK:- 顶部视图懒加载控件
///头像
private lazy var iconview=UIImageView()
///昵称
private lazy var nameLabel:UILabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 14)
///vip图标
private lazy var vipIconView = UIImageView()
///会员图标
private lazy var memberIconView:UIImageView = UIImageView(image: UIImage(named: "common_icon_membership_level1"))
///时间
private lazy var timeLabel = UILabel(color: UIColor.orangeColor(), fontSize: 10)
///来源
private lazy var sourceLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 10)
}
//MARK:- 微博底部视图
class StatusesBottomView:UIView{
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
private func setupUI(){
backgroundColor=UIColor(white: 0.97, alpha: 0.9)
addSubview(retweet)
addSubview(like)
addSubview(comment)
ff_HorizontalTile([like,retweet,comment], insets: UIEdgeInsets(top: 2, left: 20, bottom: 2, right: 20))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private lazy var retweet:UIButton = UIButton(image: "timeline_icon_retweet", title: " 评论", fontSize: 13, titleColor: UIColor.lightGrayColor())
private lazy var like:UIButton = UIButton(image: "timeline_icon_unlike", title: " 赞", fontSize: 13, titleColor: UIColor.lightGrayColor())
private lazy var comment:UIButton = UIButton(image: "timeline_icon_comment", title: " 回复", fontSize: 13, titleColor: UIColor.lightGrayColor())
}
|
//
// ChatViewController.swift
// Discover
//
// Created by Sowndharya on 19/11/16.
// Copyright © 2016 Sowndharya. All rights reserved.
//
import UIKit
import Foundation
import MediaPlayer
import Parse
import JSQMessagesViewController
class ChatViewController: JSQMessagesViewController, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var timer: Timer = Timer()
var isLoading: Bool = false
var groupId: String = ""
var users = [PFUser]()
var messages = [JSQMessage]()
var avatars = Dictionary<String, JSQMessagesAvatarImage>()
var bubbleFactory = JSQMessagesBubbleImageFactory()
var outgoingBubbleImage: JSQMessagesBubbleImage!
var incomingBubbleImage: JSQMessagesBubbleImage!
var blankAvatarImage: JSQMessagesAvatarImage!
var senderImageUrl: String!
var batchMessages = true
override func viewDidLoad() {
super.viewDidLoad()
if let user = PFUser.current() {
self.senderId = user.objectId
self.senderDisplayName = user[PF_USER_FULLNAME] as! String
}
outgoingBubbleImage = bubbleFactory?.outgoingMessagesBubbleImage(with: UIColor.jsq_messageBubbleBlue())
incomingBubbleImage = bubbleFactory?.incomingMessagesBubbleImage(with: UIColor.jsq_messageBubbleLightGray())
blankAvatarImage = JSQMessagesAvatarImageFactory.avatarImage(with: UIImage(named: "profile_blank"), diameter: 30)
isLoading = false
self.loadMessages()
Messages.clearMessageCounter(groupId);
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.collectionView.collectionViewLayout.springinessEnabled = true
timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(ChatViewController.loadMessages), userInfo: nil, repeats: true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
timer.invalidate()
}
// Mark: - Backend methods
func loadMessages() {
if self.isLoading == false {
self.isLoading = true
let lastMessage = messages.last
let query = PFQuery(className: PF_CHAT_CLASS_NAME)
query.whereKey(PF_CHAT_GROUPID, equalTo: groupId)
if let lastMessage = lastMessage {
query.whereKey(PF_CHAT_CREATEDAT, greaterThan: lastMessage.date)
}
query.includeKey(PF_CHAT_USER)
query.order(byDescending: PF_CHAT_CREATEDAT)
query.limit = 50
query.findObjectsInBackground(block: { (objects: [PFObject]?, error: Error?) -> Void in
if error == nil {
self.automaticallyScrollsToMostRecentMessage = false
for object in (objects as [PFObject]!).reversed() {
self.addMessage(object)
}
if objects!.count > 0 {
self.finishReceivingMessage()
self.scrollToBottom(animated: false)
}
self.automaticallyScrollsToMostRecentMessage = true
} else {
let alertController = UIAlertController(title: "Error", message: "\(error)", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
print("OK")
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
self.isLoading = false;
})
}
}
func addMessage(_ object: PFObject) {
var message: JSQMessage!
let user = object[PF_CHAT_USER] as! PFUser
let name = user[PF_USER_FULLNAME] as! String
let videoFile = object[PF_CHAT_VIDEO] as? PFFile
let pictureFile = object[PF_CHAT_PICTURE] as? PFFile
if videoFile == nil && pictureFile == nil {
message = JSQMessage(senderId: user.objectId, senderDisplayName: name, date: object.createdAt, text: (object[PF_CHAT_TEXT] as? String))
}
if let videoFile = videoFile {
let mediaItem = JSQVideoMediaItem(fileURL: URL(string: videoFile.url!), isReadyToPlay: true)
mediaItem?.appliesMediaViewMaskAsOutgoing = (user.objectId == self.senderId)
message = JSQMessage(senderId: user.objectId, senderDisplayName: name, date: object.createdAt, media: mediaItem)
}
if let pictureFile = pictureFile {
let mediaItem = JSQPhotoMediaItem(image: nil)
mediaItem?.appliesMediaViewMaskAsOutgoing = (user.objectId == self.senderId)
message = JSQMessage(senderId: user.objectId, senderDisplayName: name, date: object.createdAt, media: mediaItem)
pictureFile.getDataInBackground(block: { (imageData: Data?, error: Error?) -> Void in
if error == nil {
mediaItem?.image = UIImage(data: imageData!)
self.collectionView.reloadData()
}
})
}
users.append(user)
messages.append(message)
}
func sendMessage(_ text: String, video: URL?, picture: UIImage?) {
var text = text
var videoFile: PFFile!
var pictureFile: PFFile!
if let video = video {
text = "[Video message]"
videoFile = PFFile(name: "video.mp4", data: FileManager.default.contents(atPath: video.path)!)
videoFile.saveInBackground(block: { (succeeed: Bool, error: Error?) -> Void in
if error != nil {
let alertController = UIAlertController(title: "Error", message: "\(error)", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
print("OK")
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
})
}
if let picture = picture {
text = "[Picture message]"
pictureFile = PFFile(name: "picture.jpg", data: UIImageJPEGRepresentation(picture, 0.6)!)
pictureFile.saveInBackground(block: { (suceeded: Bool, error: Error?) -> Void in
if error != nil {
let alertController = UIAlertController(title: "Picture Save Error", message: "\(error)", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
print("OK")
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
})
}
let object = PFObject(className: PF_CHAT_CLASS_NAME)
object[PF_CHAT_USER] = PFUser.current()
object[PF_CHAT_GROUPID] = self.groupId
object[PF_CHAT_TEXT] = text
if let videoFile = videoFile {
object[PF_CHAT_VIDEO] = videoFile
}
if let pictureFile = pictureFile {
object[PF_CHAT_PICTURE] = pictureFile
}
object.saveInBackground{ (succeeded: Bool, error: Error?) -> Void in
if error == nil {
JSQSystemSoundPlayer.jsq_playMessageSentSound()
self.loadMessages()
} else {
let alertController = UIAlertController(title: "Network Error", message: "\(error)", preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
print("OK")
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
}
PushNotication.sendPushNotification(groupId, text: text)
Messages.updateMessageCounter(groupId, lastMessage: text)
self.finishSendingMessage()
}
// MARK: - JSQMessagesViewController method overrides
override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) {
self.sendMessage(text, video: nil, picture: nil)
}
override func didPressAccessoryButton(_ sender: UIButton!) {
self.view.endEditing(true)
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! {
return self.messages[indexPath.item]
}
override func collectionView(_ collectionView: JSQMessagesCollectionView, messageBubbleImageDataForItemAt indexPath: IndexPath) -> JSQMessageBubbleImageDataSource {
let message = self.messages[indexPath.item]
if message.senderId == self.senderId {
return outgoingBubbleImage
}
return incomingBubbleImage
}
override func collectionView(_ collectionView: JSQMessagesCollectionView, avatarImageDataForItemAt indexPath: IndexPath) -> JSQMessageAvatarImageDataSource? {
let user = self.users[indexPath.item]
if self.avatars[user.objectId!] == nil {
let thumbnailFile = user[PF_USER_THUMBNAIL] as? PFFile
thumbnailFile?.getDataInBackground(block: { (imageData: Data?, error: Error?) -> Void in
if error == nil {
self.avatars[user.objectId!] = JSQMessagesAvatarImageFactory.avatarImage(with: UIImage(data: imageData!), diameter: 30)
self.collectionView.reloadData()
}
})
return blankAvatarImage
} else {
return self.avatars[user.objectId!]
}
}
override func collectionView(_ collectionView: JSQMessagesCollectionView, attributedTextForCellTopLabelAt indexPath: IndexPath) -> NSAttributedString? {
if indexPath.item % 3 == 0 {
let message = self.messages[indexPath.item]
return JSQMessagesTimestampFormatter.shared().attributedTimestamp(for: message.date)
}
return nil;
}
override func collectionView(_ collectionView: JSQMessagesCollectionView, attributedTextForMessageBubbleTopLabelAt indexPath: IndexPath) -> NSAttributedString? {
let message = self.messages[indexPath.item]
if message.senderId == self.senderId {
return nil
}
if indexPath.item > 0 {
let previousMessage = self.messages[indexPath.item - 1]
if previousMessage.senderId == message.senderId {
return nil
}
}
return NSAttributedString(string: message.senderDisplayName)
}
// MARK: - UICollectionView DataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.messages.count
}
// MARK: - UICollectionView flow layout
override func collectionView(_ collectionView: JSQMessagesCollectionView, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout, heightForCellTopLabelAt indexPath: IndexPath) -> CGFloat {
if indexPath.item % 3 == 0 {
return kJSQMessagesCollectionViewCellLabelHeightDefault
}
return 0
}
override func collectionView(_ collectionView: JSQMessagesCollectionView, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout, heightForMessageBubbleTopLabelAt indexPath: IndexPath) -> CGFloat {
let message = self.messages[indexPath.item]
if message.senderId == self.senderId {
return 0
}
if indexPath.item > 0 {
let previousMessage = self.messages[indexPath.item - 1]
if previousMessage.senderId == message.senderId {
return 0
}
}
return kJSQMessagesCollectionViewCellLabelHeightDefault
}
// MARK: - Responding to CollectionView tap events
override func collectionView(_ collectionView: JSQMessagesCollectionView!, header headerView: JSQMessagesLoadEarlierHeaderView!, didTapLoadEarlierMessagesButton sender: UIButton!) {
print("didTapLoadEarlierMessagesButton")
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, didTapAvatarImageView avatarImageView: UIImageView!, at indexPath: IndexPath!) {
print("didTapAvatarImageview")
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, didTapMessageBubbleAt indexPath: IndexPath!) {
let message = self.messages[indexPath.item]
if message.isMediaMessage {
if let mediaItem = message.media as? JSQVideoMediaItem {
let moviePlayer = MPMoviePlayerViewController(contentURL: mediaItem.fileURL)
self.presentMoviePlayerViewControllerAnimated(moviePlayer)
moviePlayer?.moviePlayer.play()
}
}
}
override func collectionView(_ collectionView: JSQMessagesCollectionView!, didTapCellAt indexPath: IndexPath!, touchLocation: CGPoint) {
print("didTapCellAtIndexPath")
}
}
|
// SaveObjectsOperation.swift
// OpenLibrary
//
// Created by Bob Wakefield on 4/16/16.
// Copyright © 2016 Bob Wakefield. All rights reserved.
//
// Modified from code in the Apple sample app Earthquakes in the Advanced NSOperations project
import Foundation
import CoreData
//import BNRCoreDataStack
import PSOperations
/// An `Operation` to parse works out of a query from OpenLibrary.
class SaveObjectsOperation: PSOperation {
let objectID: NSManagedObjectID
let context: NSManagedObjectContext
/**
- parameter cacheFile: The file `NSURL` from which to load author query data.
- parameter context: The `NSManagedObjectContext` that will be used as the
basis for importing data. The operation will internally
construct a new `NSManagedObjectContext` that points
to the same `NSPersistentStoreCoordinator` as the
passed-in context.
*/
init( objectID: NSManagedObjectID, dataStack: OLDataStack ) {
/*
Use the overwrite merge policy, because we want any updated objects
to replace the ones in the store.
*/
self.objectID = objectID
self.context = dataStack.newChildContext( name: "saveObjects" )
self.context.mergePolicy = NSOverwriteMergePolicy
super.init()
name = "Parse Language Codes"
}
override func execute() {
let objectID = self.objectID
context.perform {
if let object = self.context.object( with: objectID ) as? OLGeneralSearchResult {
_ = object.saveProvisionalObjects()
let error = self.saveContext()
self.finishWithError( error )
}
}
}
/**
Save the context, if there are any changes.
- returns: An `NSError` if there was an problem saving the `NSManagedObjectContext`,
otherwise `nil`.
- note: This method returns an `NSError?` because it will be immediately
passed to the `finishWithError()` method, which accepts an `NSError?`.
*/
fileprivate func saveContext() -> NSError? {
var error: NSError?
do {
try context.save()
}
catch let saveError as NSError {
error = saveError
}
return error
}
}
|
//
// ForecastCell.swift
// WeatherAppv2
//
// Created by Ömer Şahin on 2.07.2019.
// Copyright © 2019 Ömer Şahin. All rights reserved.
//
import UIKit
class ForecastCell : UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
private let cellId = "cellId"
private let mcellId = "mcellId"
private let bcellId = "bcellId"
var Forecastitem : [Page] = []
var page : Page? {
didSet {
guard let unwrappedPage = page else { return}
let ForecastItems = Page(imageName: unwrappedPage.imageName, headerText: unwrappedPage.headerText, bodyText: unwrappedPage.bodyText, temperature: unwrappedPage.temperature, pressure: unwrappedPage.pressure, windspeed: unwrappedPage.windspeed, humidity: unwrappedPage.humidity, maxTemp: unwrappedPage.maxTemp, minTemp: unwrappedPage.minTemp)
Forecastitem.append(ForecastItems)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let appCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor(red: 236/255.0, green: 240/255.0, blue: 241/255.0, alpha: 1.0)
collectionView.translatesAutoresizingMaskIntoConstraints = false
return collectionView
}()
func setupViews() {
backgroundColor = UIColor(red: 236/255.0, green: 240/255.0, blue: 241/255.0, alpha: 1.0)
addSubview(appCollectionView)
appCollectionView.dataSource = self
appCollectionView.delegate = self
appCollectionView.register(TopCell.self, forCellWithReuseIdentifier: cellId)
appCollectionView.register(MidCell.self, forCellWithReuseIdentifier: mcellId)
appCollectionView.register(BottomCell.self, forCellWithReuseIdentifier: bcellId)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["v0": appCollectionView]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["v0": appCollectionView]))
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.item == 1 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: mcellId, for: indexPath) as! MidCell
return cell
}
else if indexPath.item == 2 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: bcellId, for: indexPath) as! BottomCell
let page = Forecastitem[0]
cell.page = page
return cell
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! TopCell
let page = Forecastitem[indexPath.item]
cell.page = page
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.item == 1 {
return CGSize(width: frame.width, height: 150)
}
else if indexPath.item == 0{
return CGSize(width: frame.width, height: 300)
}
return CGSize(width: frame.width, height: 496)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
|
//
// LocationService.swift
// reactive-running-app
//
// Created by Michal Klein on 16/01/2017.
// Copyright © 2017 Michal Klein. All rights reserved.
//
import CoreLocation
import ReactiveSwift
enum LocationError: Error {
case auth(CLAuthorizationStatus)
}
enum PermittedLocationAuthorization {
case whenInUse
case always
}
protocol LocationServicing {
func requestAuthorization(_ auth: PermittedLocationAuthorization)
func isAuthorizedWhenInUse() -> Bool
func requestLocation()
func startLocationUpdates(allowsBackgroundUpdates: Bool)
func stopLocationUpdates()
var locations: Signal<CLLocation, LocationError> { get }
}
final class LocationService: NSObject, LocationServicing {
enum Constants {
static let distanceFilter: CLLocationDistance = 5
static let cacheThreshold: TimeInterval = 5
}
private let locationManager: CLLocationManager = {
let locationManager = CLLocationManager()
locationManager.activityType = .fitness
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = Constants.distanceFilter
locationManager.pausesLocationUpdatesAutomatically = false
return locationManager
}()
fileprivate var skipLocation = true
let (locations, locationsSink) = Signal<CLLocation, LocationError>.pipe()
// MARK: Initializers
override init() {
super.init()
self.locationManager.delegate = self
}
deinit {
locationManager.stopUpdatingLocation()
}
func requestLocation() {
let s = CLLocationManager.authorizationStatus()
guard isAuthorizedWhenInUse() else {
locationsSink.send(error: .auth(s))
return
}
locationManager.requestLocation()
}
func isAuthorizedWhenInUse() -> Bool {
return CLLocationManager.authorizationStatus() == .authorizedWhenInUse
}
func requestAuthorization(_ auth: PermittedLocationAuthorization) {
switch auth {
case .always:
locationManager.requestAlwaysAuthorization()
case .whenInUse:
locationManager.requestWhenInUseAuthorization()
}
}
func startLocationUpdates(allowsBackgroundUpdates: Bool) {
guard isAuthorizedWhenInUse() else {
locationsSink.send(error: .auth(CLLocationManager.authorizationStatus()))
return
}
locationManager.allowsBackgroundLocationUpdates = allowsBackgroundUpdates
locationManager.startUpdatingLocation()
}
func stopLocationUpdates() {
locationManager.stopUpdatingLocation()
}
}
// MARK: CLLocationManagerDelegate
extension LocationService: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard skipLocation == false else { skipLocation = false; return }
for location in locations {
locationsSink.send(value: location)
}
}
}
|
//
// ViewController.swift
// Movie-GLI
//
// Created by Muhammad Faruuq Qayyum on 14/01/21.
//
import UIKit
import SDWebImage
import Alamofire
class ViewController: UICollectionViewController {
typealias DataSource = UICollectionViewDiffableDataSource<Int, Results>
typealias Snapshot = NSDiffableDataSourceSnapshot<Int, Results>
let searchController: UISearchController = {
let search = UISearchController()
search.searchBar.placeholder = "Search movie"
return search
}()
enum BaseUrl {
case discoverMovie, searchMovie
}
private var dataSource: DataSource!
private var fetchingMore = false
private var pageNumber = 1
var item: [Results] = []
var selectedItem: Results?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "IMDB Movie"
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
searchController.searchBar.delegate = self
configureDataSource()
applySnapshot(item: item)
initialData()
}
}
extension ViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
discoverMovies(url: .searchMovie, query: searchBar.searchTextField.text, page: nil) { (result) in
switch result {
case .failure(let error):
print(error.localizedDescription)
return
case .success(let data):
self.item = []
data.results.forEach { (item) in
let newItem = Results(id: item.id, title: item.title, image: item.image, overview: item.overview, youtube: nil, imageLandscape: item.imageLandscape, content: nil)
self.item.append(newItem)
self.applySnapshot(item: self.item)
}
}
}
searchController.isActive = false
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
discoverMovies(url: .searchMovie, query: searchBar.searchTextField.text, page: nil) { (result) in
switch result {
case .failure(let error):
print(error.localizedDescription)
return
case .success(let data):
self.item = []
data.results.forEach { (item) in
let newItem = Results(id: item.id, title: item.title, image: item.image, overview: item.overview, youtube: nil, imageLandscape: item.imageLandscape, content: nil)
self.item.append(newItem)
self.applySnapshot(item: self.item)
}
}
}
}
}
extension ViewController {
fileprivate func configureDataSource() {
collectionView.register(UINib(nibName: "HomeCell", bundle: nil), forCellWithReuseIdentifier: "cell")
collectionView.collectionViewLayout = createLayout()
dataSource = DataSource(collectionView: collectionView, cellProvider: { (collectionView, indexPath, item) -> UICollectionViewCell? in
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HomeCell
let imageUrl = "https://image.tmdb.org/t/p/w300\(item.image ?? "")"
cell.moviePoster.sd_setImage(with: URL(string: imageUrl), completed: nil)
cell.movieTitle.text = item.title
return cell
})
}
fileprivate func createLayout() -> UICollectionViewLayout {
let layout = UICollectionViewCompositionalLayout { (sectionIndex: Int,
layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection in
let contentSize = layoutEnvironment.container.effectiveContentSize
let columns = contentSize.width > 800 ? 3 : 2
let spacing = CGFloat(10)
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
heightDimension: .fractionalHeight(1.0))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
heightDimension: .absolute(300))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitem: item, count: columns)
group.interItemSpacing = .fixed(spacing)
let section = NSCollectionLayoutSection(group: group)
section.interGroupSpacing = spacing
section.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 10, bottom: 10, trailing: 10)
return section
}
return layout
}
fileprivate func applySnapshot(item: [Results]) {
var snapshot = Snapshot()
snapshot.appendSections([0])
snapshot.appendItems(item)
dataSource.apply(snapshot, animatingDifferences: false)
}
func discoverMovies(url: BaseUrl, query: String?, page: Int?, completion: @escaping (Result<Root, Error>) ->()) {
let headers: HTTPHeaders = ["Accept": "application/json"]
let baseUrl = "https://api.themoviedb.org/3"
var getUrl: String?
var parameters: [String: String]?
switch url {
case .discoverMovie:
getUrl = "/discover/movie?sort_by=popularity.desc"
parameters = ["api_key" : "88a8b9b29d2fd7cd6c976f0b79c01ca3",
"page" : "\(page ?? 1)"]
case .searchMovie:
getUrl = "/search/movie"
parameters = [
"api_key" : "88a8b9b29d2fd7cd6c976f0b79c01ca3",
"query" : query!,
"page" : "\(page ?? 1)"
]
}
AF.request(baseUrl + getUrl!, parameters: parameters, headers: headers).responseDecodable(of: Root.self) { (result) in
if let error = result.error {
completion(.failure(error))
}
print(result.response!.statusCode)
guard result.response!.statusCode == 200 else { return }
completion(.success(result.value!))
}
}
fileprivate func initialData() {
discoverMovies(url: .discoverMovie, query: nil, page: nil) { (result) in
switch result {
case .failure(let error):
print(error.localizedDescription)
case .success(let data):
self.item = []
data.results.forEach { (item) in
let newItem = Results(id: item.id, title: item.title, image: item.image, overview: item.overview, youtube: nil, imageLandscape: item.imageLandscape, content: nil)
self.item.append(newItem)
self.applySnapshot(item: self.item)
}
}
}
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetY = scrollView.contentOffset.y
let contentHeight = scrollView.contentSize.height
if offsetY > contentHeight - scrollView.frame.height * 1.5 {
if !fetchingMore {
beginBatchFetch()
} else {
print("stopping")
}
}
}
func beginBatchFetch() {
fetchingMore = true
print("fetching begin")
pageNumber += 1
discoverMovies(url: .discoverMovie, query: nil, page: pageNumber) { (result) in
switch result {
case .failure(let error):
print(error.localizedDescription)
case .success(let data):
data.results.forEach { (item) in
let newItem = Results(id: item.id, title: item.title, image: item.image, overview: item.overview, youtube: nil, imageLandscape: nil, content: nil)
self.item.append(newItem)
self.applySnapshot(item: self.item)
}
}
}
fetchingMore = false
}
}
extension ViewController {
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedItem = dataSource.itemIdentifier(for: indexPath)
performSegue(withIdentifier: "toDetail", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let detailVC = segue.destination as! DetailVC
detailVC.movieId = selectedItem?.id ?? 0
detailVC.movieTitle = selectedItem?.title ?? ""
detailVC.movieBackdrop = "https://image.tmdb.org/t/p/w300\(selectedItem?.imageLandscape ?? selectedItem?.image ?? "")"
detailVC.movieOverview = selectedItem?.overview ?? ""
}
}
|
//
// ViewController.swift
// IMC
//
// Created by Kaled Jamal El Azanki on 11/02/20.
// Copyright © 2020 Kaled Azanki. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tfPeso: UITextField!
@IBOutlet weak var tfAltura: UITextField!
@IBOutlet weak var lbResultado: UILabel!
@IBOutlet weak var ivResultado: UIImageView!
@IBOutlet weak var viResultado: UIView!
var imc: Double = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func calculate(_ sender: Any) {
if let peso = Double(tfPeso.text!), let altura = Double(tfAltura.text!){
imc = peso / pow(altura,2)
showResult()
}
}
func showResult() {
var result: String = ""
var image: String = ""
switch imc{
case 0..<16:
result = "Magreza"
image = "abaixo"
case 16..<18.5:
result = "Abaixo do peso"
image = "abaixo"
case 18.5..<25:
result = "Peso ideal"
image = "ideal"
case 25..<30:
result = "Sobrepeso"
image = "sobre"
default:
result = "Obesidade"
image = "obesidade"
}
lbResultado.text = result
ivResultado.image = UIImage(named: image)
viResultado.isHidden = false
}
}
|
import UIKit
//Operadores
//Operadores de asignacion
let a = 5; // el "=" asigna valores
var b = 3
b=a//aginamos el valor de b a a
//Operador ternario
//operador equivalente a un if else pero mas corto
let anchura = 40
let tieneCabecera = true
//supongamos que la altura de la culumna es en funcion de si tiene cabecera y de la anchura
var alturaColumna = anchura + (tieneCabecera ? 50 : 20)
//
// 01.Operadores.swift
//
//
// Created by Alumno on 28/10/2020.
//
import Foundation
//continuacion de lo que ya tengo en el ordenador de sobremesa
//operador nil-coalescing (nil-fusionado)
//sintaxis (a??b)
//se utiliza mucho con optionals
//En caso de que el optional "A" tenga un valor, entonces devuelve el valor de "A"
//En caso de que el optional de "A" sea nulo, entonces devuelve el valor de "B"
let colorPorDefecto = "Azul"
var colorDefinidoPosUsuario : String? //Lo definimos como un optional porque es posible que el usuario no lo defina
var color = (colorDefinidoPosUsuario ?? colorPorDefecto)
print(color)
//operadores logicos
//logicla NOT (variable)
//logical AND (variable1 && variable2)
//Logical OR (vairbale1 || variable2)
var verdad = true;
var mentira = false;
print(verdad)
print(mentira)
print(verdad && mentira)
print(verdad && mentira)
//Ej1. Calcular el perímetro y área de un rectángulo dada su base y su altura.
//Ej2. Dados los catetos de un triángulo rectángulo, calcular su hipotenusa.
//Ej3. Dados dos números, mostrar la suma, resta, división y multiplicación de ambos.
//Ej4. Escribir un programa que convierta un valor dado en grados Fahrenheit a grados
// Celsius.
//Ej5. Calcular la media de tres números
//Ej1
var base = 5
var altura = 10
var perimetro = 0
perimetro = 2 * base + 2 * altura
print(perimetro)
var area = base * altura
print(area)
//Ej2
var cat1 = 5.0
var cat2 = 3.0
var hipo = sqrt(cat1*cat1 + cat2*cat2)
print(hipo)
//Ej3
var suma = base + altura
var resta = altura - base
var multiplicacion = base * altura
var division = altura / base
print(suma, resta, multiplicacion, division)
//Ej4
var gradosf = 5.0
var gradosC = (gradosf - 32)/1.8
print(gradosC)
//Ej5
var num1 = 1
var num2 = 2
var num3 = 3
var media = (num1+num2+num3)/3
print(media)
//Ej6. Un vendedor recibe un sueldo base mas un 10% extra por comision de sus ventas,
// el vendedor desea saber cuanto dinero obtendrá por concepto de comisiones por
// las tres ventas que realiza en el mes y el total que recibirá en el mes tomando
// en cuenta su sueldo base y comisiones.
//Ej7. Un alumno desea saber cual será su calificación final en la materia de IOS
// Dicha calificación se compone de los siguientes porcentajes:
// * 55% del promedio de sus tres calificaciones parciales.
// * 30% de la calificación del examen final.
// * 15% de la calificación de un trabajo final.
//Ej8. Escribir un algoritmo para calcular la nota final de un estudiante, considerando que:
// por cada respuesta correcta 5 puntos, por una incorrecta -1 y por respuestas en
// blanco 0. Imprime el resultado obtenido por el estudiante.
//Ej9. Calcula el sueldo de un trabajador, cuyo valor es su sueldo base más un numero de horas
//extra trabajadas, pero teniendo en cuenta que el dicho numero de horas puede ser nulo
var sueldo = 3000.0
var mes1 = 1223.0
print("2:")
var mes2 = 2000.0
print("3:")
var mes3 = 1455.0
var comision = (mes1+mes2+mes3)*0.1
print("Calculando su comision por sus ventas...")
print("Comision: ", comision)
print("Sueldo total: ", comision+sueldo)
//Ej8. Escribir un algoritmo para calcular la nota final de un estudiante, considerando que:
// por cada respuesta correcta 5 puntos, por una incorrecta -1 y por respuestas en
// blanco 0. Imprime el resultado obtenido por el estudiante.
var respC = 5
var respI = -1
var respB = 0
var result = (respC*7 + respI*2 + respB*1)
print(result)
//Ej9. Calcula el sueldo de un trabajador, cuyo valor es su sueldo base más un numero de horas
//extra trabajadas, pero teniendo en cuenta que el dicho numero de horas puede ser nulo
var numHE = 20
var sueldoHE = 18
var sueldoB = 1000
print(numHE*18 + 1000)
|
/*
* Copyright (c) 2012-2020 MIRACL UK Ltd.
*
* This file is part of MIRACL Core
* (see https://github.com/miracl/core).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// rom.swift
//
public struct ROM{
#if D32
// Base Bits= 29
// bls24 Curve Modulus
static let Modulus:[Chunk] = [0xA06152B,0x2260B3A,0xB4C36BE,0x5FFC5D0,0xBDB6A64,0x5B78E2E,0x1C1A28CA,0x10E6441B,0x1F244061,0xB4704F0,0x141E5CCD,0x9837504,0x3F2E77E,0xD763740,0x1316EA0E,0xF0079,0x555C]
static let ROI:[Chunk] = [0xA06152A,0x2260B3A,0xB4C36BE,0x5FFC5D0,0xBDB6A64,0x5B78E2E,0x1C1A28CA,0x10E6441B,0x1F244061,0xB4704F0,0x141E5CCD,0x9837504,0x3F2E77E,0xD763740,0x1316EA0E,0xF0079,0x555C]
static let R2modp:[Chunk] = [0x8533EA9,0x6A02789,0x183B24DE,0x1E45ECF8,0xC8F8F37,0x10CAD209,0x4C0C4B8,0x9B1FABD,0xDEBE4C0,0xDC353F9,0x18A18E26,0x10F489BB,0x31206A5,0x19673BBF,0x6BE69F9,0xB091169,0x9CD]
static let MConst:Chunk = 0x95FE7D
static let SQRTm3:[Chunk] = [0x11A91428,0x199C660C,0x1A2D6663,0x12E8FC7D,0x1E691154,0x15F983E8,0x186F2A5,0x10DE5323,0x1D4AF96A,0x1B991E67,0xF573372,0x145BE4FE,0xE24A1,0x1B6DFA0C,0xB165A04,0xF0079,0x555C]
static public let Fra:[Chunk] = [0x1BF96F1D,0xAE53A55,0x31BFEEB,0x183FF17A,0x6237469,0x12A4F4F1,0x12101FE3,0x16E79D94,0xFF59267,0x5EB4EB4,0x78CC49F,0x274BA33,0x149184F3,0x16C6DCBA,0x1C90B694,0x10F729CE,0x4BBC]
static public let Frb:[Chunk] = [0xE0CA60E,0x1740D0E4,0x83037D2,0xDBFD456,0x5B7F5FA,0x1312993D,0xA0A08E6,0x19FEA687,0xF2EADF9,0x55BB63C,0xC91982E,0x70EBAD1,0xF61628B,0x16AF5A85,0x16863379,0xF17D6AA,0x99F]
static public let TWK:[Chunk] = [0x16EA62F3,0x52C4905,0x17CF5F35,0x13967138,0x16BCA61B,0xF766FBB,0x9B547D6,0x11625BCD,0x1AFF154D,0xDE4D18C,0xF9C3EF8,0x84619DC,0x15E18EE4,0x1D55B149,0xED04681,0x64CDD9E,0x337A]
static let CURVE_Cof_I:Int = 0
static let CURVE_B_I:Int = 19
static public let CURVE_B:[Chunk] = [0x13,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static public let CURVE_Order:[Chunk] = [0x10000001,0xD047FF,0x1FD54464,0x1E3CE067,0xE322DDA,0x1D356F3F,0x7433B44,0x49091F9,0x1729CC2,0x250286C,0x16E62ED,0xB403E1E,0x1001000,0x80,0x0,0x0,0x0]
static public let CURVE_Gx:[Chunk] = [0xBE3CCD4,0x33B07AF,0x1B67D159,0x3DFC5B5,0xEBA1FCC,0x1A3C1F84,0x56BE204,0xEF8DF1B,0x11AE2D84,0x5FEE546,0x161B3BF9,0x183B20EE,0x1EA5D99B,0x14F0C5BF,0xBE521B7,0x17C682F9,0x1AB2]
static public let CURVE_Gy:[Chunk] = [0x121E5245,0x65D2E56,0x11577DB1,0x16DACC11,0x14F39746,0x459F694,0x12483FCF,0xC828B04,0xFD63E5A,0x7B1D52,0xAFDE738,0xF349254,0x1A4529FF,0x10E53353,0xF91DEE1,0x16E18D8A,0x47FC]
static public let CURVE_HTPC:[Chunk] = [0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static public let CURVE_Bnx:[Chunk] = [0x11FF80,0x80010,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static public let CURVE_Cof:[Chunk] = [0x11FF7F,0x80010,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
//static public let CURVE_Cof:[Chunk] = [0x19F415AB,0x1E0FFDFF,0x15AAADFF,0xAA,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static public let CRu:[Chunk] = [0xDD794A9,0x1DE138A3,0x2BCCE90,0xC746127,0x15223DDC,0x1DD8890B,0xED08DB7,0xE24B9F,0xE379CE6,0x37011AC,0x11BAC820,0x1EEFAD01,0x200860F,0x147218A6,0xF16A209,0xF0079,0x555C]
static public let CURVE_Pxaa:[Chunk] = [0x14E24678,0x1F149A9B,0x9609022,0x1C186868,0xCDEFC69,0x1C87BB2E,0x14A2235F,0x7586755,0x5896747,0x159BFE92,0x3B5572E,0x1710A521,0x71EB14A,0xC643C33,0x12581DE5,0x1BCA747D,0x959]
static public let CURVE_Pxab:[Chunk] = [0x1FB099B8,0x3FCF5D7,0x4A91C0E,0xC6EEB40,0x11FC2385,0x11B5AE8D,0x1A9CC3E7,0x194FE144,0x185DB2A5,0x930E1C7,0x14F85F9A,0x1F2ED4E,0x1D1BE5AD,0xF26169C,0xCF7F194,0x1DA1062E,0x3B0D]
static public let CURVE_Pxba:[Chunk] = [0x11AD15D3,0xD0E6F38,0x17DB85BB,0x30A62F1,0x1EA3E09A,0x17B25FA1,0x1B7959AC,0x1165B19A,0x6C74FDB,0x18F790E1,0x12278FDA,0x1E008F79,0x103F329,0x14619FF1,0x1EBCAA8,0xFF5A9CA,0x3EC2]
static public let CURVE_Pxbb:[Chunk] = [0x1EE0F480,0x3D5943A,0xF5B12E3,0x128AADC8,0x180E1CB9,0x1EFD916F,0x48BC7F,0x1D5EE1FA,0x5698EF5,0x11D6AED9,0x1386BC6E,0x196E900B,0x1CE2E465,0xC2A8ED3,0x1E67DF99,0x71B7940,0xA5B]
static public let CURVE_Pyaa:[Chunk] = [0x14781AA0,0xC324C98,0xEDC2AC,0x16C13B46,0x145FC44B,0x12529530,0x1310A8C4,0x1768C5C0,0xE19AE68,0x56E1C1D,0x13DAF93F,0x17E94366,0xF901AD0,0x76800CC,0x10250D8B,0x1E6BAE6D,0x5057]
static public let CURVE_Pyab:[Chunk] = [0xEAE08FA,0xDDF62BF,0xA97E5AB,0xF0EE97,0x99A42CA,0x1C326578,0xF33DC11,0x8B913F7,0xFEF8552,0x19F35B90,0x58DDBDE,0xFC32FF2,0x1587B5DF,0xB5EB07A,0x1A258DE0,0x1692CC3D,0x2CE2]
static public let CURVE_Pyba:[Chunk] = [0x5F0CC41,0xB9813B5,0x14C2A87D,0xFF1264A,0x19AF8A14,0x6CE6C3,0x2A7F8A2,0x121DCA7D,0x7D37153,0x19D21078,0x15466DC7,0x1362982B,0x1DD3CB5B,0x1CFC0D1C,0x18C69AF8,0x8CC7DC,0x1807]
static public let CURVE_Pybb:[Chunk] = [0x115C1CAE,0x78D9732,0x16C26237,0x5A81A6A,0x1C38A777,0x56121FE,0x4DAD9D7,0x1BEBA670,0xA1D72FC,0xD60B274,0x19734258,0x1D621775,0x4691771,0x14206B68,0x17B22DE4,0x29D5B37,0x499D]
#endif
#if D64
// Base Bits= 56
static let Modulus:[Chunk] = [0x44C1674A06152B,0xFFE2E82D30DAF8,0x6F1C5CBDB6A642,0x3220DF068A328B,0xE09E1F24406187,0xBA825079733568,0x6E803F2E77E4C1,0x3CCC5BA839AEC,0x555C0078]
static let ROI:[Chunk] = [0x44C1674A06152A,0xFFE2E82D30DAF8,0x6F1C5CBDB6A642,0x3220DF068A328B,0xE09E1F24406187,0xBA825079733568,0x6E803F2E77E4C1,0x3CCC5BA839AEC,0x555C0078]
static let R2modp:[Chunk] = [0x6A4A1FE013DF5B,0xE8E46D4D1BDE65,0x1F841391F45C67,0x9148A4516FB28,0x4398524EDF4C88,0x41C0E241B6DCE8,0xE42C208C19411,0xA7FE6FD73A7B1C,0xFCCCA76]
static let MConst:Chunk = 0xBD5D7D8095FE7D
static let SQRTm3:[Chunk] = [0x338CC191A91428,0x747E3EE8B5998F,0xF307D1E6911549,0xF2991861BCA96B,0x23CCFD4AF96A86,0xF27F3D5CCDCB73,0xF41800E24A1A2D,0x3CAC5968136DB,0x555C0078]
static public let Fra:[Chunk] = [0x5CA74ABBF96F1D,0x1FF8BD0C6FFBAD,0x49E9E26237469C,0x3CECA48407F8E5,0x69D68FF59267B7,0x5D199E33127CBD,0xB97549184F313A,0x4E77242DA52D8D,0x4BBC87B9]
static public let Frb:[Chunk] = [0xE81A1C8E0CA60E,0xDFEA2B20C0DF4A,0x25327A5B7F5FA6,0xF5343A828239A6,0x76C78F2EADF9CF,0x5D68B24660B8AB,0xB50AF61628B387,0xB555A18CDE6D5E,0x99F78BE]
static public let TWK:[Chunk] = [0xA58920B6EA62F3,0xCB389C5F3D7CD4,0xECDF776BCA61B9,0x12DE6A6D51F59E,0x9A319AFF154D8B,0xCEE3E70FBE1BC,0x62935E18EE4423,0xECF3B411A07AAB,0x337A3266]
static let CURVE_Cof_I:Int = 0
static let CURVE_B_I:Int = 19
static public let CURVE_B:[Chunk] = [0x13,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static public let CURVE_Order:[Chunk] = [0x1A08FFF0000001,0x1E7033FF551190,0x6ADE7EE322DDAF,0x848FC9D0CED13A,0x50D81729CC224,0x1F0F05B98BB44A,0x10010010005A0,0x0,0x0]
static public let CURVE_Gx:[Chunk] = [0x6760F5EBE3CCD4,0xEFE2DAED9F4564,0x783F08EBA1FCC1,0xC6F8D95AF88134,0xDCA8D1AE2D8477,0x9077586CEFE4BF,0x8B7FEA5D99BC1D,0x17CAF9486DE9E1,0x1AB2BE34]
static public let CURVE_Gy:[Chunk] = [0xCBA5CAD21E5245,0x6D6608C55DF6C4,0xB3ED294F39746B,0x145824920FF3C8,0x63AA4FD63E5A64,0x492A2BF79CE00F,0x66A7A4529FF79A,0x6C53E477B861CA,0x47FCB70C]
static public let CURVE_HTPC:[Chunk] = [0x1,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static public let CURVE_Bnx:[Chunk] = [0x100020011FF80,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static public let CURVE_Cof:[Chunk] = [0x100020011FF7F,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
//static public let CURVE_Cof:[Chunk] = [0xC1FFBFF9F415AB,0x5556AAB7FF,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static public let CRu:[Chunk] = [0xBC27146DD794A9,0x3A30938AF33A43,0xB112175223DDC6,0x125CFBB4236DFB,0x2358E379CE607,0xD680C6EB20806E,0x314C200860FF77,0x3CBC5A88268E4,0x555C0078]
static public let CURVE_Pxaa:[Chunk] = [0xE2935374E24678,0xC34342582408B,0xF765CCDEFC69E,0xC33AAD2888D7F9,0x7FD2458967473A,0x52908ED55CBAB3,0x786671EB14AB88,0xA3EC96077958C8,0x959DE53]
static public let CURVE_Pxab:[Chunk] = [0x7F9EBAFFB099B8,0x3775A012A47038,0x6B5D1B1FC23856,0x7F0A26A730F9E3,0x1C38F85DB2A5CA,0x76A753E17E6926,0x2D39D1BE5AD0F9,0x31733DFC651E4C,0x3B0DED08]
static public let CURVE_Pxba:[Chunk] = [0xA1CDE711AD15D3,0x853178DF6E16ED,0x64BF43EA3E09A1,0x2D8CD6DE566B2F,0xF21C26C74FDB8B,0x47BCC89E3F6B1E,0x3FE2103F329F00,0x4E507AF2AA28C3,0x3EC27FAD]
static public let CURVE_Pxbb:[Chunk] = [0x7AB2875EE0F480,0x4556E43D6C4B8C,0xFB22DF80E1CB99,0xF70FD0122F1FFD,0xD5DB25698EF5EA,0x4805CE1AF1BA3A,0x1DA7CE2E465CB7,0xCA0799F7E65855,0xA5B38DB]
static public let CURVE_Pyaa:[Chunk] = [0x86499314781AA0,0x609DA303B70AB1,0xA52A6145FC44BB,0x462E04C42A3124,0xC383AE19AE68BB,0xA1B34F6BE4FCAD,0x198F901AD0BF4,0x736C094362CED0,0x5057F35D]
static public let CURVE_Pyab:[Chunk] = [0xBBEC57EEAE08FA,0x78774BAA5F96AD,0x64CAF099A42CA0,0xC89FBBCCF70478,0x6B720FEF855245,0x97F916376F7B3E,0x60F5587B5DF7E1,0x61EE89637816BD,0x2CE2B496]
static public let CURVE_Pyba:[Chunk] = [0x730276A5F0CC41,0xF89325530AA1F5,0xD9CD879AF8A147,0xEE53E8A9FE2880,0x420F07D3715390,0x4C15D519B71F3A,0x1A39DD3CB5B9B1,0x3EE631A6BE39F8,0x18070466]
static public let CURVE_Pybb:[Chunk] = [0xF1B2E6515C1CAE,0xD40D355B0988DC,0xC243FDC38A7772,0x5D338136B675CA,0x164E8A1D72FCDF,0xBBAE5CD0961AC,0xD6D04691771EB1,0xD9BDEC8B792840,0x499D14EA]
#endif
}
|
import UIKit
class JoinViewController: UIViewController {
var msg : String?
var result_code : String?
var gender = String("남")
@IBOutlet var id_text: UITextField!
@IBOutlet var password_text: UITextField!
@IBOutlet var password_text2: UITextField!
@IBOutlet var error_id_label: UILabel!
@IBOutlet var name_text: UITextField!
@IBOutlet var birth_text: UITextField!
@IBOutlet var name_error_label: UILabel!
@IBOutlet var pw_error_label: UILabel!
@IBOutlet var birth_error_label: UILabel!
@IBOutlet var tel_error_label: UILabel!
@IBOutlet var address_error_label: UILabel!
@IBOutlet var email_error_label: UILabel!
@IBOutlet var tel_text: UITextField!
@IBOutlet var email_text: UITextField!
@IBOutlet var gender_segement: UISegmentedControl!
@IBAction func checked_id(_ sender: Any) {
if id_text.text!.count == 0 {
error_id_label.text = "아이디를 입력하세요"
} else {
let defaultSession = URLSession(configuration: .default)
var dataTask: URLSessionDataTask?
let urlComponents = URLComponents(string: "http://localhost:8080/OurMeal/checkId")
guard let url = urlComponents?.url else {return}
// POST 방식의 요청을 처리하기 위한 URLRequest 객체 생성
var request = URLRequest(url: url)
// 요청 방식 설정
request.httpMethod = "POST"
// 요청 데이터 설정
let body = "joinReq_id=\(id_text.text!)".data(using:String.Encoding.utf8)
request.httpBody = body
dataTask = defaultSession.dataTask(with: request){ data, response, error in
if let error = error {
NSLog("통신 에러 발생")
NSLog("에러 메세지 : " + error.localizedDescription)
} else if let data = data, let response = response as? HTTPURLResponse,
response.statusCode == 200{
var check_id_map : Check_id_map?
check_id_map = try! JSONDecoder().decode(Check_id_map.self, from: data)
self.msg = (check_id_map?.msg)!
self.result_code = (check_id_map?.result_code)!
DispatchQueue.main.async {
if self.result_code! == "1" {
self.error_id_label.textColor = UIColor.red
self.error_id_label.text = self.msg!
} else {
self.error_id_label.textColor = UIColor.blue
self.error_id_label.text = self.msg!
}
}
}
}
dataTask?.resume()
}
}
@IBAction func submit_btn_clicked(_ sender: Any) {
if id_text.text!.count == 0 {
NSLog("아이디")
error_id_label.text = "아이디를 입력하세요"
} else if password_text.text!.count == 0 || password_text2.text!.count == 0 {
NSLog("비번1")
pw_error_label.text = "비밀번호를 입력하세요"
} else if password_text2.text!.count == 0 || password_text2.text!.count == 0 {
NSLog("비번2")
pw_error_label.text = "비밀번호를 입력하세요"
}else if name_text.text!.count == 0 {
NSLog("이름")
name_error_label.text = "이름을 입력하세요"
} else if birth_text.text!.count == 0 {
NSLog("생일")
birth_error_label.text = "생년월일을 입력하세요"
} else if tel_text.text!.count == 0 {
NSLog("전화")
tel_error_label.text = "전화번호를 입력하세요"
} else if email_text.text!.count == 0 {
NSLog("메일")
email_error_label.text = "이메일을 입력하세요"
} else if address_text.text!.count == 0 {
NSLog("주소")
address_error_label.text = "주소를 입력하세요"
} else if password_text.text! != password_text2.text!{
NSLog("비번 안일치")
pw_error_label.text = "비밀번호가 일치하지 않습니다"
}
else {
// 디비 인서트
let defaultSession = URLSession(configuration: .default)
var dataTask: URLSessionDataTask?
let urlComponents = URLComponents(string: "http://localhost:8080/OurMeal/ios_join")
guard let url = urlComponents?.url else {return}
// POST 방식의 요청을 처리하기 위한 URLRequest 객체 생성
var request = URLRequest(url: url)
// 요청 방식 설정
request.httpMethod = "POST"
// 요청 데이터 설정
let body = "id=\(id_text.text!)&pw=\(password_text2.text!)&name=\(name_text.text!)&birth=\(birth_text.text!)&sex=\(gender)&tel=\(tel_text.text!)&email=\(email_text.text!)&address=\(address_text.text!)".data(using:String.Encoding.utf8)
request.httpBody = body
dataTask = defaultSession.dataTask(with: request){ data, response, error in
if let error = error {
NSLog("통신 에러 발생")
NSLog("에러 메세지 : " + error.localizedDescription)
} else if let data = data, let response = response as? HTTPURLResponse,
response.statusCode == 200{
NSLog(String( data: data, encoding: .utf8)!)
var join_ok : Join_ok?
join_ok = try! JSONDecoder().decode(Join_ok.self, from: data)
DispatchQueue.main.async {
if join_ok!.join! {
let alert = UIAlertController(title: "회원가입 완료", message: "회원가입이 완료되었습니다.", preferredStyle: UIAlertController.Style.alert)
let defaultAction = UIAlertAction(title: "확인", style: UIAlertAction.Style.destructive) { (action) in
let storyboard: UIStoryboard = self.storyboard!
let nextView = storyboard.instantiateViewController(withIdentifier: "login")
self.present(nextView, animated: true, completion: nil)
}
alert.addAction(defaultAction)
self.present(alert, animated: false, completion: nil)
}
}
}
}
dataTask?.resume()
}
}
@IBAction func name_editing(_ sender: Any) {
name_error_label.text = ""
}
@IBAction func birth_editing(_ sender: Any) {
birth_error_label.text = ""
}
@IBAction func tel_editing(_ sender: Any) {
tel_error_label.text = ""
}
@IBAction func email_editing(_ sender: Any) {
email_error_label.text = ""
}
@IBAction func change_address(_ sender: Any) {
address_error_label.text = ""
}
@IBAction func cheched_pw(_ sender: Any) {
if password_text.text! != password_text2.text! {
pw_error_label.text = "비밀번호가 일치하지 않습니다."
} else {
pw_error_label.text = ""
}
}
@IBOutlet var address_text: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
class Check_id_map : Codable {
var msg : String?
var result_code : String?
}
class Join_ok : Codable {
var join : Bool?
}
@IBAction func cancle_btn_clicked(_ sender: Any) {
let storyboard: UIStoryboard = self.storyboard!
let nextView = storyboard.instantiateViewController(withIdentifier: "login")
present(nextView, animated: true, completion: nil)
}
@IBAction func gender_change(_ sender: Any) {
if gender_segement.selectedSegmentIndex == 0
{
gender = "남"
}
else
{
gender = "여"
}
}
}
|
//
// TodayViewController.swift
// todayWidget
//
// Created by Drew Lanning on 10/20/17.
// Copyright © 2017 Drew Lanning. All rights reserved.
//
import UIKit
import NotificationCenter
import CoreData
class TodayViewController: UIViewController, NCWidgetProviding, UITableViewDelegate, UITableViewDataSource {
// MARK: Properties
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var emptyDataLbl: UILabel!
var activities: [Activity]?
let appGroup: String = "group.com.drewlanning.It-Happened.todayWidget"
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "It_Happened")
var persistentStoreDescriptions: NSPersistentStoreDescription
let storeURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup)?.appendingPathComponent("It_Happened.sqlite")
let description = NSPersistentStoreDescription()
description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true
description.url = storeURL
container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: storeURL!)]
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.stalenessInterval = 0
return container
}()
var frc: NSFetchedResultsController<Activity>?
// MARK: Methods
override func viewDidLoad() {
super.viewDidLoad()
self.extensionContext?.widgetLargestAvailableDisplayMode = .expanded
tableView.dataSource = self
tableView.delegate = self
frc = getFrc()
do {
try frc?.performFetch()
} catch {
print("stop trying to make fetch happen")
}
updateView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
do {
try frc?.performFetch()
} catch {
print("stop trying to make fetch happen")
}
completionHandler(NCUpdateResult.newData)
}
func configure(cell: TodayViewCell, at indexPath: IndexPath, withContext context: NSManagedObjectContext) {
cell.configureCell(with: frc!.object(at: indexPath), inContext: context)
}
fileprivate func updateView() {
var hasActivities = false
if let activities = frc?.fetchedObjects {
hasActivities = activities.count > 0
}
tableView.isHidden = !hasActivities
emptyDataLbl.isHidden = hasActivities
}
// MARK: CoreData
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
print("did not save, error")
}
}
}
func getFrc() -> NSFetchedResultsController<Activity> {
let context = persistentContainer.viewContext
let fetchRequest: NSFetchRequest<Activity> = Activity.fetchRequest()
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "sortOrder", ascending: true),NSSortDescriptor(key: "created", ascending: true)]
let fetchedResultsController: NSFetchedResultsController<Activity> = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultsController
}
// MARK: Tableview methods
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return frc?.fetchedObjects?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "todayViewCell") as! TodayViewCell
configure(cell: cell, at: indexPath, withContext: persistentContainer.viewContext)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// print("going back to app")
if let url: URL = URL(string: "It-Happened://") {
self.extensionContext?.open(url, completionHandler: nil)
}
}
// MARK: Widget Protocol Methods
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
switch activeDisplayMode {
case .expanded:
let items = frc?.fetchedObjects?.count ?? 0
preferredContentSize = CGSize(width: 0, height: Int(tableView.rowHeight) * items)
case .compact:
preferredContentSize = maxSize
}
}
}
|
//
// VoteViewController.swift
// Werewolf
//
// Created by macbook_user on 11/2/17.
// Copyright © 2017 CS4980-Werewolf. All rights reserved.
//
import Foundation
import UIKit
import MultipeerConnectivity
class VoteViewController: UIViewController, MCSessionDelegate, UITableViewDelegate, UITableViewDataSource {
var villageList : [[String]] = []
var countArray : [[String]] = []
var mcSession: MCSession!
var voteList = [[String]]()
var tempVillageList = [[String]]()
var killedList = GameSession.active.killedList
var tempKilledList = [String]()
var resultList = [String]()
var myVote : Int!
var myRole : String?
var killedVillager : String?
var timer: Timer!
@IBOutlet weak var voteButton: UIButton!
@IBOutlet weak var abstainButton: UIButton!
@IBOutlet weak var VoteTableView: UITableView!
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return GameSession.active.voteList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellNum:Int = indexPath.row
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "customcell")! as UITableViewCell
cell.textLabel!.text = GameSession.active.voteList[cellNum][0]
if (cellNum == 0) {
tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
}
cell.textLabel!.font = UIFont (name: "Luminari-Regular", size: 17.0)
return cell
}
override func viewDidLoad() {
super.viewDidLoad()
let width = UIScreen.main.bounds.size.width
let height = UIScreen.main.bounds.size.height
let imageViewBackground = UIImageView(frame: CGRect(x: 0, y: 0, width: width, height: height))
imageViewBackground.image = UIImage(named: "AfternoonBackground.png")
imageViewBackground.alpha = 0.3
// you can change the content mode:
imageViewBackground.contentMode = UIViewContentMode.scaleAspectFill
self.view.addSubview(imageViewBackground)
self.view.sendSubview(toBack: imageViewBackground)
mcSession.delegate = self
// Do any additional setup after loading the view, typically from a nib.
timer = Timer.scheduledTimer(timeInterval:1.0, target:self, selector:#selector(NominationViewController.updateStatus), userInfo: nil, repeats: true)
let character = GameSession.active.myCharacter
myRole = character?.role
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
}
// Do not need to edit
func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {
}
// Do not need to edit
func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {
}
// Do not need to edit
func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) {
}
// Do not need to edit
func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
dismiss(animated: true)
}
// Do not need to edit
func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
dismiss(animated: true)
}
// This code will execute when there's a change in state and it will update the block accordingly
func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
switch state {
case MCSessionState.connected:
print("Connected: \(peerID.displayName)")
case MCSessionState.connecting:
print("Connecting: \(peerID.displayName)")
case MCSessionState.notConnected:
print("Not Connected: \(peerID.displayName)")
}
}
// This function checks for if you are recieving data and if you are it executes
func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
Networking.shared.session(session, didReceive: data, fromPeer: peerID)
}
@objc func updateStatus() {
print(GameSession.active.villageList!.count)
print(GameSession.active.killedList.count)
if GameSession.active.villageList!.count == GameSession.active.killedList.count {
finalTally()
}
}
func finalTally() {
timer.invalidate()
var countingVotes = [Int]()
for _ in GameSession.active.villageList! {
countingVotes.append(0)
}
var maxVotes = countingVotes.max()!
print("maxvotes")
print(maxVotes)
var maxVotesLocation = countingVotes.index(of: maxVotes)!
resultList.append(String(maxVotesLocation))
GameSession.active.killedList.forEach { item in
if(item != "Abstain" ){
tempKilledList.append(item)
}
else{
killedVillager = "Abstain"
}
}
GameSession.active.killedList = tempKilledList
let countedSet = NSCountedSet(array: GameSession.active.killedList)
let mostFrequent = countedSet.max { countedSet.count(for: $0) < countedSet.count(for: $1) }
GameSession.active.villageList!.forEach { item in
if(String(describing: mostFrequent) != "Optional(" + item[0] + ")") {
tempVillageList.append(item)
}
else{
killedVillager = item[0]
}
}
GameSession.active.villageList = tempVillageList
performSegue(withIdentifier: "toResults", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
print("preparing for segue: \(String(describing: segue.identifier))")
let destVC: ExecuteViewController = segue.destination as! ExecuteViewController
destVC.mcSession = mcSession
destVC.villageList = GameSession.active.villageList!
print(villageList)
destVC.killedVillager = self.killedVillager!
print(killedVillager)
}
@IBAction func voteButtonPressed(_ sender: Any) {
let voteIndex:Int = (VoteTableView.indexPathForSelectedRow! as NSIndexPath).row
myVote = voteIndex
let vote:String = GameSession.active.voteList[voteIndex][0]
print("vote is" + vote)
VoteTableView.allowsSelection = false
GameSession.active.killedList.append(vote)
Networking.shared.sendText(vote, prefixCode: "Vote")
voteButton.isEnabled = false
abstainButton.isEnabled = false
}
@IBAction func abstainButtonPressed(_ sender: Any) {
let vote:String = "Abstain"
print("vote is" + vote)
VoteTableView.allowsSelection = false
GameSession.active.killedList.append(vote)
Networking.shared.sendText(vote, prefixCode: "Vote")
voteButton.isEnabled = false
abstainButton.isEnabled = false
}
}
|
//
// PhotoListTableView.swift
// ListPhotoGallery
//
// Created by Ionut Baciu on 24/07/2018.
// Copyright © 2018 Ionut Baciu. All rights reserved.
//
import UIKit
class PhotoListTableView: UITableView {
var tabelContent = [Photo]()
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
|
//
// ContactsViewController.swift
// SEngage
//
// Created by Yan Wu on 3/23/16.
// Copyright © 2016 Avaya. All rights reserved.
//
import UIKit
class ContactsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,UISearchBarDelegate {
let contactIndexTitleList:[String] = [
"A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N",
"O", "P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"]
// MARK: Properties
var contacts = [Contact]()
var teams = [Group]()
// search results DataSource
var resultContacts = [Contact]()
var resultTeams = [Group]()
var segment = 0
var isSearch = false
var segmentedControl:UISegmentedControl!
var actionFloatView: ActionFloatView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
loadData()
//navigationItem.leftBarButtonItem = editButtonItem()
segmentedSetting()
self.searchBar.placeholder = "Search"
self.searchBar.delegate = self
self.tableView.delegate = self
self.tableView.dataSource = self
initNavigationBarItem()
initActionFloatView()
// setTableViewFooter()
// Register the gesture for dismissing the keyboard
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action:#selector(ContactsViewController.handleTap(_:))))
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.actionFloatView.hide(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadData() {
contacts = GenerateData.generateContacts(10)
contacts.sortInPlace({$0.name < $1.name})
self.resultContacts = self.contacts
teams = GenerateData.generateTeams(15)
teams.sortInPlace({$0.name < $1.name})
self.resultTeams = self.teams
}
func initNavigationBarItem() {
let button: UIButton = UIButton(type: UIButtonType.Custom)
button.setImage(UIImage(asset:.Barbuttonicon_addfriends), forState: .Normal)
button.frame = CGRectMake(0, 0, 40, 30)
button.imageView!.contentMode = .ScaleAspectFit;
button.contentHorizontalAlignment = .Right
button.ngl_addAction(forControlEvents: .TouchUpInside, withCallback: {
(Void) -> Void in
self.actionFloatView.hide(!self.actionFloatView.hidden)
})
let barButton = UIBarButtonItem(customView: button)
let gapItem = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: nil, action: nil)
gapItem.width = -7 //fix the space
self.navigationItem.setRightBarButtonItems([gapItem, barButton], animated: true)
}
func initActionFloatView() {
//Init ActionFloatView
self.actionFloatView = ActionFloatView()
self.actionFloatView.delegate = self
self.view.addSubview(self.actionFloatView)
self.actionFloatView.snp_makeConstraints { (make) -> Void in
make.edges.equalTo(UIEdgeInsetsMake(64, 0, 0, 0))
}
}
func segmentedSetting() {
segmentedControl = UISegmentedControl(items: ["Contacts","Teams"])
segmentedControl.selectedSegmentIndex = 0
segmentedControl.center=self.view.center
segmentedControl.addTarget(self, action: #selector(ContactsViewController.segmentedControlAction(_:)), forControlEvents: .ValueChanged)
self.navigationItem.titleView = segmentedControl
}
func segmentedControlAction(sender: UISegmentedControl) {
switch segmentedControl.selectedSegmentIndex
{
case 0:
segment = 0
clearSearchContent()
break
case 1:
segment = 1
clearSearchContent()
break
default:
break;
}
tableView.reloadData()
// setTableViewFooter()
}
// func setTableViewFooter() {
// let footerView:UIView = UIView(frame:
// CGRectMake(0,0,tableView!.frame.size.width,60))
// let footerlabel:UILabel = UILabel(frame: footerView.bounds)
// footerlabel.textColor = UIColor.whiteColor()
// footerlabel.backgroundColor = AppTheme.AVAYA_RED_COLOR
// footerlabel.font = UIFont.systemFontOfSize(16)
// footerView.addSubview(footerlabel)
// footerView.backgroundColor = UIColor.blackColor()
// tableView?.tableFooterView = footerView
// if segment == 0 {
// if resultContacts.count != 0 {
// footerlabel.text = "\(resultContacts.count) Contacts"
// } else {
// footerlabel.text = "No Results"
// }
// } else {
// if resultTeams.count != 0 {
// footerlabel.text = "\(resultTeams.count) Teams"
// } else {
// footerlabel.text = "No Results"
// }
// }
// }
// MARK: - Table view data source
// set the number of sections
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
// // set titles for each section
// override func tableView(tableView:UITableView, titleForHeaderInSection section:Int)->String {
// var headers = self.contactIndexTitleList;
// return headers[section];
// }
// set rows in section
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if segment == 0 {
return resultContacts.count
} else {
return resultTeams.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var retCell: UITableViewCell
if segment == 0 {
// Table view cells are reused and should be dequeued using a cell identifier.
let cellIdentifier = "ContactsTableViewCell"
let cell = self.tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ContactsTableViewCell
// Fetches the appropriate contact for the data source layout.
let contact = resultContacts[indexPath.row]
cell.nameLabel.text = contact.name
cell.photoImageView.image = contact.photo
if contact.status == "idle" {
cell.statusImageView.backgroundColor = AppTheme.STATUS_IDEL_COLOR
} else if contact.status == "available" {
cell.statusImageView.backgroundColor = AppTheme.STATUS_ONLINE_COLOR
} else if contact.status == "busy" {
cell.statusImageView.backgroundColor = AppTheme.STATUS_BUSY_COLOR
} else {
cell.statusImageView.backgroundColor = AppTheme.STATUS_OFFLINE_COLOR
}
retCell = cell
} else {
// Table view cells are reused and should be dequeued using a cell identifier.
let cellIdentifier = "TeamTableViewCell"
let cell = self.tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! TeamTableViewCell
// Fetches the appropriate contact for the data source layout.
let group = resultTeams[indexPath.row]
cell.teamNameLabel.text = group.name
cell.teamImageView.image = group.photo
retCell = cell
}
return retCell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return AppTheme.CONTACT_CELL_HEIGHT
}
// //right side index bar: "A" ... "Z"
// override func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
// return contactIndexTitleList
// }
//
// override func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
// var tpIndex:Int = 0
// // traverse the value of indexes
// for character in contactIndexTitleList{
// // if the index equals the tile, return the value
// if character == title{
// return tpIndex
// }
// tpIndex += 1
// }
// return 0
// }
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
contacts.removeAtIndex(indexPath.row)
// need to save the new contacts array in the db
save()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
func save() {
}
// *Search Result
// Method of UISearchBarDelegate,called when the search text changed
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if segment == 0 {
// show all the cell when there's no input
if searchText == "" {
self.resultContacts = self.contacts
}
else { // Match the input regardless of the Uppercase
self.resultContacts = []
for contact in self.contacts {
if contact.name.lowercaseString.hasPrefix(searchText.lowercaseString) {
self.resultContacts.append(contact)
}
}
}
} else {
// show all the cell when there's no input
if searchText == "" {
self.resultTeams = self.teams
}
else { // Match the input regardless of the Uppercase
self.resultTeams = []
for group in self.teams {
if group.name.lowercaseString.hasPrefix(searchText.lowercaseString) {
self.resultTeams.append(group)
}
}
}
}
self.tableView.reloadData()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
isSearch = true;
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
isSearch = false;
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
clearSearchContent()
}
func clearSearchContent() {
isSearch = false
// Clear the search bar text
searchBar.text=""
// Close the virtual keyboard
searchBar.resignFirstResponder()
// Reload data
if segment == 0 {
self.resultContacts = self.contacts
} else {
self.resultTeams = self.teams
}
self.tableView.reloadData()
}
// Hide the keyboard when click the blank
func handleTap(sender: UITapGestureRecognizer) {
if sender.state == .Ended {
searchBar.resignFirstResponder()
}
sender.cancelsTouchesInView = false
}
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
searchBar.resignFirstResponder()
}
// *Prepare for segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
let contactDetailTableViewController = segue.destinationViewController as! ContactDetailTableViewController
// Get the cell that generated this segue
if let selectedContactCell = sender as? ContactsTableViewCell {
let indexPath = tableView.indexPathForCell(selectedContactCell)!
let selectedContact = contacts[indexPath.row]
contactDetailTableViewController.contact = selectedContact
}
}
else if segue.identifier == "addContact" {
print("Adding new contact.")
}
else if segue.identifier == "teamDetail" {
let teamDetailTableViewController = segue.destinationViewController as! TeamDetailTableViewController
// Get the cell that generated this segue
if let selectedContactCell = sender as? TeamTableViewCell {
let indexPath = tableView.indexPathForCell(selectedContactCell)!
let selectedTeam = teams[indexPath.row]
teamDetailTableViewController.group = selectedTeam
}
}
}
}
// MARK: - @protocol ActionFloatViewDelegate
extension ContactsViewController: ActionFloatViewDelegate {
func floatViewTapItemIndex(type: ActionFloatViewItemType) {
// log.info("floatViewTapItemIndex:\(type)")
switch type {
case .CreateTeams:
self.hidesBottomBarWhenPushed = true
let sb = UIStoryboard(name: "contactsSB", bundle: nil)
let skip = sb.instantiateViewControllerWithIdentifier("TeamCreation")
self.navigationController?.pushViewController(skip, animated: true)
self.hidesBottomBarWhenPushed = false
break
case .AddContacts:
self.hidesBottomBarWhenPushed = true
let sb = UIStoryboard(name: "contactsSB", bundle: nil)
let skip = sb.instantiateViewControllerWithIdentifier("AddContact")
self.navigationController?.pushViewController(skip, animated: true)
// let addContactTableViewController = AddContactTableViewController()
// self.navigationController?.pushViewController(addContactTableViewController, animated: true)
self.hidesBottomBarWhenPushed = false
break
}
}
}
/*
Block of UIControl
*/
public class ClosureWrapper1 : NSObject {
let _callback : Void -> Void
init(callback : Void -> Void) {
_callback = callback
}
public func invoke() {
_callback()
}
}
var AssociatedClosure1: UInt8 = 0
extension UIControl {
private func ngl_addAction(forControlEvents events: UIControlEvents, withCallback callback: Void -> Void) {
let wrapper = ClosureWrapper1(callback: callback)
addTarget(wrapper, action:#selector(ClosureWrapper1.invoke), forControlEvents: events)
objc_setAssociatedObject(self, &AssociatedClosure1, wrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
|
import UIKit
class _PrevButton : SMButton{
override func initView(){
name = "PrevButton"
}
} |
//
// Array+Extensions.swift
// EasyGitHubSearch
//
// Created by Yevhen Triukhan on 11.10.2020.
// Copyright © 2020 Yevhen Triukhan. All rights reserved.
//
import Foundation
extension Array {
func object(at index: Int) -> Element? {
return index < self.count ? self[index] : nil
}
}
|
//
// ViewController.swift
// Egg Timer
//
// Created by Julia Debecka on 07/05/2020.
// Copyright © 2020 Julia Debecka. All rights reserved.
//
import UIKit
import SnapKit
class ViewController: UIViewController {
var eggSize: String!
var preference: String!
@IBOutlet weak var cookEggsButon: UIButton!
@IBOutlet weak var largeButton: UIButton!
@IBOutlet weak var mediumButton: UIButton!
@IBOutlet weak var smallButton: UIButton!
@IBOutlet weak var soft: UIButton!
@IBOutlet weak var medium: UIButton!
@IBOutlet weak var hard: UIButton!
var sizeButtons: [UIButton] = []
var prefrenceButtons: [UIButton] = []
override func viewDidLoad() {
super.viewDidLoad()
setUpGradient()
sizeButtons.append(contentsOf: [largeButton, mediumButton, smallButton])
prefrenceButtons.append(contentsOf: [soft, medium, hard])
roundCorders()
}
@IBAction func largeTapped(_ sender: Any) {
animateTap(largeButton)
}
@IBAction func mediumTapped(_ sender: Any) {
animateTap(mediumButton)
}
@IBAction func smallTapped(_ sender: Any) {
animateTap(smallButton)
}
@IBAction func softTapped(_ sender: Any) {
animateTap(soft)
}
@IBAction func mediumCookTapped(_ sender: Any) {
animateTap(medium)
}
@IBAction func hardTapped(_ sender: Any) {
animateTap(hard)
}
@IBAction func startCookingTapped(_ sender: Any) {
if (eggSize == nil) || (preference == nil) {
let didNotSelectedAlert = UIAlertController(title: "Select Your Egg Size and Preference", message: "I will calculate time based on these two parameters", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "Okay", style: .default, handler: nil)
didNotSelectedAlert.addAction(alertAction)
self.present(didNotSelectedAlert, animated: true, completion: nil)
}else {
let cookEggVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CookEggViewContoller") as! CookEggsViewController
cookEggVC.eggKind = preference
cookEggVC.eggSize = eggSize
navigationController?.pushViewController(cookEggVC, animated: true)
}
}
}
fileprivate extension ViewController {
func setUpGradient() {
let colors = [UIColor.white.cgColor, CGColor(srgbRed: 0.9764705896, green: 0.850980401, blue: 0.5490196347, alpha: 1), CGColor(srgbRed: 0.9686274529, green: 0.78039217, blue: 0.3450980484, alpha: 1), CGColor(srgbRed: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)]
let gradientLayer = self.view.getGradientLayer(with: colors, for: [0.2, 0.6, 0.8, 1.0])
let animation = makeAnimation()
gradientLayer.add(animation, forKey: nil)
self.view.layer.insertSublayer(gradientLayer, at: 0)
}
func roundCorders() {
sizeButtons.forEach { $0.roundCorners() }
prefrenceButtons.forEach { $0.roundCorners() }
cookEggsButon.roundCorners()
}
func animateTap(_ sender: UIButton) {
UIView.animate(withDuration: 0.05, delay: 0.0, options: .transitionCrossDissolve, animations: {
sender.backgroundColor = .white
}) { (completed) in
self.createListOfDiselected(sender)
}
}
func createListOfDiselected(_ sender: UIButton) {
var list: [UIButton] = []
if self.sizeButtons.contains(sender) {
eggSize = sender.titleLabel?.text
list = self.sizeButtons.filter { $0 != sender }
}
else if self.prefrenceButtons.contains(sender) {
preference = sender.titleLabel?.text
list = self.prefrenceButtons.filter { $0 != sender }
}
self.diselectButton(list)
}
func diselectButton(_ buttons: [UIButton]) {
UIView.animate(withDuration: 0.05, delay: 0.0, options: .transitionCrossDissolve, animations: {
buttons.forEach { $0.backgroundColor = .systemYellow }
}, completion: nil)
}
func makeAnimation() -> CABasicAnimation {
let animation = CABasicAnimation(keyPath: "locations")
animation.fromValue = [0.2, 0.6, 0.8, 1.0]
animation.toValue = [0.0, 0.2, 0.4, 1.0]
animation.duration = 2.5
animation.autoreverses = true
animation.repeatCount = Float.infinity
return animation
}
}
|
//
// AppAuthenticationVC.swift
// Telemed
//
// Created by Erik Grosskurth on 6/2/17.
// Copyright © 2017 Caduceus USA. All rights reserved.
//
import UIKit
class AppAuthenticationVC: UIViewController, UIAlertViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
let appBuild = Bundle.main.infoDictionary?["CFBundleVersion"] as? String
DataModel.sharedInstance.accessNetworkData(
vc: self,
loadModal: false,
params: [
"sAppVersion": appVersion!,
"sBuildVersion": appBuild!
],
wsURLPath: "Telemed.asmx/isAppValid",
completion: {(response: AnyObject) -> Void in
print(DataModel.sharedInstance.testWSResponse(vc: self, response))
if (DataModel.sharedInstance.testWSResponse(vc: self, response)) {
let alertController = UIAlertController(title: "Title", message: "This app is experiencing connectivity issues. Please check your internet connection. If the problem persists, please contact a Caduceus IT professional to help sort out the problems, Thanks.", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { UIAlertAction in
self.viewDidLoad()
self.viewWillAppear(true)
})
self.present(alertController, animated: true, completion: nil)
return
}
print("An update is required? - " + String(describing: response.value(forKey: "status") as! Bool))
if ( response.value(forKey: "status") as! Bool ) {
self.performSegue(withIdentifier: "UserLogin", sender: AnyObject.self)
}else {
self.performSegue(withIdentifier: "updateRequired", sender: AnyObject.self)
}
}
)
}
override func prepare(for segue: UIStoryboardSegue, sender: (Any)?) {
if (segue.destination.isKind(of: LoginVC.self)) {
//let vc = segue.destination as! ProviderDashboardVC
}else if (segue.destination.isKind(of: updateRequiredVC.self)) {
//let vc = segue.destination as! SafetyManagerDashboardVC
}else {
//let vc = segue.destination as! PatientSortingRoomVC
}
}
}
|
//
// Seasons.swift
// Westeros
//
// Created by JOSE LUIS BUSTOS ESTEBAN on 28/7/17.
// Copyright © 2017 Keepcoding. All rights reserved.
//
import XCTest
@testable import Westeros
class Seasons: XCTestCase {
var temporadas : [Season]!
override func setUp() {
super.setUp()
//las Temporadas
temporadas = Repository.localSesion.Seasons
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testnoNil() {
let temp1 = Season(name: "temp1", dateSeason: Date.getDateFromString("01/01/2010"), descrip: "", image: UIImage(named: "default.png")!)
XCTAssertNotNil(temp1)
}
func testtemporadasNoCero() {
XCTAssertNotEqual(temporadas.count, 0)
}
func testHouseEquality(){
// Identidad
XCTAssertEqual(temporadas[0], temporadas[0])
// Desigualdad
XCTAssertNotEqual(temporadas[0], temporadas[1])
}
func testHashable() {
XCTAssertNotNil(temporadas[0].hashValue)
}
func testEpisodios(){
//deben tener episodios
XCTAssertNotEqual(temporadas[0].count,0)
XCTAssertNotEqual(temporadas[1].count,0)
}
func testHouseComparison(){
XCTAssertLessThan(temporadas[0], temporadas[1])
}
}
|
//
// FlashcardViewController.swift
// flashcards
//
// Created by Bryan Workman on 7/20/20.
// Copyright © 2020 Bryan Workman. All rights reserved.
//
import UIKit
class FlashcardViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//MARK: - Outlets
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var flashpileSubjectTextField: UITextField!
@IBOutlet weak var flashpileSubjectLabel: UILabel!
@IBOutlet weak var editButtonLabel: UIButton!
@IBOutlet weak var quizButtonOutlet: UIButton!
@IBOutlet weak var subjectViewView: UIView!
@IBOutlet weak var loadingView: UIView!
@IBOutlet weak var addButton: UIBarButtonItem!
//MARK: - Properties
var flashpile: Flashpile?
let searchController = UISearchController(searchResultsController: nil)
var filteredFlashcards: [Flashcard] = []
var titleIsEditing = false
var isSearchBarEmpty: Bool {
return searchController.searchBar.text?.isEmpty ?? true
}
var isFiltering: Bool {
return searchController.isActive && !isSearchBarEmpty
}
//MARK: - Lifecycles
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
setupSearchBar()
loadingView.isHidden = false
fetchFlashcards()
let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing))
view.addGestureRecognizer(tap)
tap.cancelsTouchesInView = false
updateOrCreate()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.tableView.reloadData()
enableQuizButton()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(true)
guard let flashpile = flashpile else {return}
print(flashpile.flashcards.count)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.view.backgroundColor = .bgTan
tableView.separatorColor = #colorLiteral(red: 0, green: 0.5898008943, blue: 1, alpha: 0.2607020548)
tableView.layer.cornerRadius = 15.0
tableView.clipsToBounds = true
quizButtonOutlet.layer.cornerRadius = 20.0
quizButtonOutlet.clipsToBounds = true
quizButtonOutlet.layer.shadowColor = UIColor.gray.cgColor
quizButtonOutlet.layer.shadowOffset = CGSize(width: 0, height: 1.5)
quizButtonOutlet.layer.shadowRadius = 2.0
quizButtonOutlet.layer.shadowOpacity = 1.0
quizButtonOutlet.layer.masksToBounds = false
quizButtonOutlet.layer.shadowPath = UIBezierPath(roundedRect: quizButtonOutlet.bounds, cornerRadius: quizButtonOutlet.layer.cornerRadius).cgPath
loadingView.layer.cornerRadius = 20.0
loadingView.clipsToBounds = true
tableView.layer.borderWidth = 2.0
tableView.layer.cornerRadius = 15.0
//guard let canvaBlue = UIColor.canvaBlue else {return}
tableView.layer.borderColor = UIColor.canvaBlue.cgColor
let containerView:UIView = UIView(frame: self.tableView.frame)
self.view.addSubview(containerView)
self.view.addSubview(subjectViewView)
self.view.addSubview(tableView)
self.view.addSubview(quizButtonOutlet)
self.view.addSubview(loadingView)
}
//MARK: - Actions
@IBAction func saveButtonTapped(_ sender: Any) {
guard let flashpile = flashpile else {return}
if !FlashpileController.shared.fauxFlashpileIDs.contains(flashpile.recordID) {
if flashpile.flashcards.count == 0 && (flashpile.subject == "" || flashpile.subject == "Subject") {
FlashpileController.shared.deleteFlashpile(flashpile: flashpile) { (result) in
DispatchQueue.main.async {
switch result {
case .success(_):
self.navigationController?.popViewController(animated: true)
case .failure(let error):
print("There was an error deleting flashpile -- \(error) -- \(error.localizedDescription)")
}
}
}
} else {
FlashpileController.shared.updateFlashpile(flashpile: flashpile) { (result) in
DispatchQueue.main.async {
switch result {
case .success(_):
self.navigationController?.popViewController(animated: true)
case .failure(let error):
print("There was an error creating a new flashpile -- \(error) -- \(error.localizedDescription)")
}
}
}
}
} else {
self.navigationController?.popViewController(animated: true)
}
}
@IBAction func editButtonTapped(_ sender: Any) {
guard let flashpile = flashpile else {return}
titleIsEditing = !titleIsEditing
if titleIsEditing {
editButtonLabel.setTitle("Done", for: .normal)
flashpileSubjectTextField.isHidden = false
if flashpile.subject == "Subject" {
flashpileSubjectTextField.text = ""
} else {
flashpileSubjectTextField.text = flashpile.subject
}
flashpileSubjectLabel.isHidden = true
} else {
guard let text = flashpileSubjectTextField.text else {return}
editButtonLabel.setTitle("Edit", for: .normal)
flashpileSubjectTextField.isHidden = true
if text == "" {
flashpile.subject = "Subject"
} else {
flashpile.subject = text
flashpileSubjectLabel.text = flashpile.subject
}
flashpileSubjectLabel.isHidden = false
}
}
@IBAction func quizButtonTapped(_ sender: Any) {
guard let flashpile = flashpile else {return}
guard flashpile.flashcards.count > 0 else {return}
if !FlashpileController.shared.fauxFlashpileIDs.contains(flashpile.recordID) {
FlashpileController.shared.updateFlashpile(flashpile: flashpile) { (result) in
DispatchQueue.main.async {
switch result {
case .success(_):
FlashcardController.shared.totalFlashcards = flashpile.flashcards
case .failure(_):
print("Error updating flashpile")
}
}
}
} else {
FlashcardController.shared.totalFlashcards = flashpile.flashcards
}
}
//MARK: - Helper Methods
func updateOrCreate() {
if let flashpile = flashpile {
updateViews(flashpile: flashpile)
} else {
FlashpileController.shared.createFlashpile(subject: "") { (result) in
DispatchQueue.main.async {
switch result {
case .success(let flashpile):
self.loadingView.isHidden = true
self.flashpile = flashpile
self.enableQuizButton()
case .failure(let error):
print("There was an error creating a new flashpile -- \(error) -- \(error.localizedDescription)")
}
}
}
flashpileSubjectTextField.isHidden = true
flashpileSubjectLabel.text = "Subject"
}
}
func enableQuizButton() {
guard let flashpile = flashpile else {return}
if flashpile.flashcards.count == 0 {
quizButtonOutlet.isEnabled = false
} else {
quizButtonOutlet.isEnabled = true
}
}
func fetchFlashcards() {
guard let flashpile = flashpile else {return}
if !FlashpileController.shared.fauxFlashpileIDs.contains(flashpile.recordID) {
FlashcardController.shared.fetchFlashcards(for: flashpile) { (result) in
DispatchQueue.main.async {
switch result {
case .success(_):
self.loadingView.isHidden = true
self.tableView.reloadData()
FlashcardController.shared.totalFlashcards = flashpile.flashcards
self.enableQuizButton()
case .failure(let error):
print("There was an error fetching flashcards for this flashpile -- \(error) -- \(error.localizedDescription)")
}
}
}
} else {
self.loadingView.isHidden = true
self.addButton.isEnabled = false
self.editButtonLabel.isEnabled = false
self.tableView.allowsSelection = false
FlashcardController.shared.totalFlashcards = flashpile.flashcards
}
}
func updateViews(flashpile: Flashpile) {
if flashpile.subject == "" {
flashpileSubjectLabel.text = "Subject"
} else {
flashpileSubjectLabel.text = flashpile.subject
}
flashpileSubjectTextField.isHidden = true
tableView.reloadData()
}
//search functions
func setupSearchBar() {
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search flashcards"
navigationItem.searchController = searchController
definesPresentationContext = true
searchController.hidesNavigationBarDuringPresentation = false
}
func filterContentForSearchText(_ searchText: String) {
guard let flashpile = flashpile else {return}
filteredFlashcards = flashpile.flashcards.filter { (flashcard: Flashcard) -> Bool in
var frontString: String = ""
var backString: String = ""
if let front = flashcard.frontString {
frontString = front
}
if let back = flashcard.backString {
backString = back
}
return frontString.lowercased().contains(searchText.lowercased()) || backString.lowercased().contains(searchText.lowercased())
}
tableView.reloadData()
}
//MARK: - Table view data source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isFiltering {
return filteredFlashcards.count
}
guard let flashpile = flashpile else {return 0}
return flashpile.flashcards.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "flashCell", for: indexPath) as? FlashcardTableViewCell else {return UITableViewCell()}
guard let flashpile = flashpile else {return UITableViewCell()}
let flashcard: Flashcard
if isFiltering {
flashcard = filteredFlashcards[indexPath.row]
} else {
flashcard = flashpile.flashcards[indexPath.row]
}
cell.flashcard = flashcard
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
guard let flashpile = flashpile else {return}
let flashcardToDelete = flashpile.flashcards[indexPath.row]
guard let index = flashpile.flashcards.firstIndex(of: flashcardToDelete) else {return}
FlashcardController.shared.deleteFlashcard(flashcard: flashcardToDelete) { (result) in
DispatchQueue.main.async {
switch result {
case .success(_):
flashpile.flashcards.remove(at: index)
self.enableQuizButton()
FlashcardController.shared.totalFlashcards = flashpile.flashcards
self.tableView.reloadData()
case .failure(let error):
print("There was an error deleting this flashcard -- \(error) -- \(error.localizedDescription)")
}
}
}
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toDetailVC" {
guard let indexPath = tableView.indexPathForSelectedRow else {return}
guard let destinationVC = segue.destination as? FlashcardDetailViewController else {return}
guard let flashpile = flashpile else {return}
let flashcard: Flashcard
if isFiltering {
flashcard = filteredFlashcards[indexPath.row]
} else {
flashcard = flashpile.flashcards[indexPath.row]
}
destinationVC.flashcard = flashcard
destinationVC.flashpile = flashpile
} else if segue.identifier == "toAddFC" {
guard let destinationVC = segue.destination as? FlashcardDetailViewController else {return}
guard let flashpile = flashpile else {return}
destinationVC.flashpile = flashpile
}
}
} //End of Class
extension FlashcardViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
let searchBar = searchController.searchBar
guard let text = searchBar.text else {return}
filterContentForSearchText(text)
}
} //End of extension
|
//
// CitiesResource.swift
// LoadIt
//
// Created by Luciano Marisi on 25/06/2016.
// Copyright © 2016 Luciano Marisi. All rights reserved.
//
import Foundation
import LoadIt
private let baseURL = NSURL(string: "http://localhost:8000/")!
struct CitiesResource: NetworkJSONResourceType, DiskJSONResourceType {
typealias Model = [City]
let url: NSURL
let filename: String
init(continent: String) {
url = baseURL.URLByAppendingPathComponent("\(continent).json")
filename = continent
}
//MARK: JSONResource
func modelFrom(jsonDictionary jsonDictionary: [String: AnyObject]) -> [City]? {
guard let
citiesJSONArray = jsonDictionary["cities"] as? [[String: AnyObject]]
else {
return []
}
return citiesJSONArray.flatMap(City.init)
}
} |
//
// AsteroidDetailViewController.swift
// Asterank
//
// Created by Sascha Müllner on 25.01.16.
// Copyright © 2016 Sascha Muellner. All rights reserved.
//
import UIKit
class AsteroidDetailViewController: UITableViewController {
var asteroid :Asteroid?
@IBOutlet weak var asteroidClassLabel: UILabel!
@IBOutlet weak var asteroidTypeLabel: UILabel!
@IBOutlet weak var closenessLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var profitLabel: UILabel!
override func viewWillAppear(animated: Bool) {
self.title = self.asteroid!.fullName
self.asteroidClassLabel.text = String(self.asteroid!.asteroidClass)
self.asteroidTypeLabel.text = String(self.asteroid!.asteroidType)
self.closenessLabel.text = String(self.asteroid!.closeness)
self.priceLabel.text = String(self.asteroid!.price)
self.profitLabel.text = String(self.asteroid!.profit)
}
}
|
//
// JSONDecodable.swift
// ComicList
//
// Created by Eric Risco de la Torre on 11/03/2017.
// Copyright © 2017 Guille Gonzalez. All rights reserved.
//
import Foundation
public func decode<T: JSONDecodable>(jsonDictionary: JSONDictionary) throws -> T {
return try T(jsonDictionary: jsonDictionary)
}
public func decode<T: JSONDecodable>(jsonArray: JSONArray) throws -> [T] {
return try jsonArray.map { try decode(jsonDictionary: $0) }
}
public func decode<T: JSONDecodable>(data: Data) throws -> T {
let object = try JSONSerialization.jsonObject(with: data, options: [])
guard let dict = object as? JSONDictionary else {
throw JSONError.invalidData
}
return try decode(jsonDictionary: dict)
}
public func unpack<T>(key: String, jsonDictionary: JSONDictionary) throws -> T {
guard let raw = jsonDictionary[key] else {
throw JSONError.notFound(key)
}
guard let value = raw as? T else {
throw JSONError.invalidValue(raw, key)
}
return value
}
public func unpack<T: JSONValueDecodable>(keyPath: String, jsonDictionary: JSONDictionary) throws -> T {
guard let raw = (jsonDictionary as NSDictionary).value(forKeyPath: keyPath) else{
throw JSONError.notFound(keyPath)
}
guard let value = raw as? T.Value else {
throw JSONError.invalidValue(raw, keyPath)
}
guard let decodedValue = try T(raw: value) else {
throw JSONError.invalidValue(raw, keyPath)
}
return decodedValue
}
public func unpackDictionary<T: JSONDecodable>(key: String, jsonDictionary: JSONDictionary) throws -> T {
let rawValue: JSONDictionary = try unpack(key: key, jsonDictionary: jsonDictionary)
return try decode(jsonDictionary: rawValue)
}
public func unpackDictionary<T: JSONDecodable>(key: String, jsonDictionary: JSONDictionary) throws -> [T] {
let rawValues: JSONArray = try unpack(key: key, jsonDictionary: jsonDictionary)
return try decode(jsonArray: rawValues)
}
|
//
// AppDelegate.swift
// CartographyPractice
//
// Created by Jonathan Crossley on 6/20/15
// Copyright (c) 2015 CCS. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
|
//
// CKService.swift
// iCloud & Push Notification
//
// Created by Ivan Ivanov on 4/25/21.
//
import Foundation
import CloudKit
class CKService {
private init () {}
static let shared = CKService()
let privateDatabase = CKContainer.default().privateCloudDatabase
func save(record: CKRecord) {
privateDatabase.save(record) { (record, error) in
print(error ?? "no ck save error")
print(record ?? "No ck record saved")
}
}
func query(recordType: String, completion: @escaping ([CKRecord]) -> Void) {
let query = CKQuery(recordType: recordType, predicate: NSPredicate(value: true))
privateDatabase.perform(query, inZoneWith: nil) { (records, error) in
print(error ?? "no ck query error")
guard let records = records else { return }
DispatchQueue.main.async {
completion(records)
}
}
}
func subscribe(){
let subscription = CKQuerySubscription(recordType: Notes.recordType, predicate: NSPredicate(value: true), options: .firesOnRecordCreation)
let notificationInfo = CKSubscription.NotificationInfo()
notificationInfo.shouldSendContentAvailable = true
subscription.notificationInfo = notificationInfo
privateDatabase.save(subscription) { (sub, error) in
print(error ?? "No CK subError")
print(sub ?? "Unable to subscribe")
}
}
func subscribeUI(){
let subscription = CKQuerySubscription(recordType: Notes.recordType, predicate: NSPredicate(value: true), options: .firesOnRecordCreation)
let notificationInfo = CKSubscription.NotificationInfo()
notificationInfo.title = "This is cool"
notificationInfo.subtitle = "A Whole new iClould"
notificationInfo.soundName = "default"
notificationInfo.alertBody = "A bet ya didnt know a power of the coluld"
notificationInfo.shouldBadge = true
subscription.notificationInfo = notificationInfo
privateDatabase.save(subscription) { (sub, error) in
print(error ?? "No CK subError")
print(sub ?? "Unable to subscribe")
}
}
func fetchRecord(with recordID: CKRecord.ID) {
privateDatabase.fetch(withRecordID: recordID) { (record, error) in
print(error ?? "NO CK fetch Error")
guard let record = record else { return }
DispatchQueue.main.async {
NotificationCenter.default.post(name: NSNotification.Name("internalNotification.fetchRecord"), object: record)
}
}
}
func handleNotification(with userInfo: [AnyHashable: Any]){
let notification = CKNotification(fromRemoteNotificationDictionary: userInfo)
switch notification?.notificationType {
case .query:
guard let queryNotification = notification as? CKQueryNotification, let recordID = queryNotification.recordID
else { return }
fetchRecord(with: recordID)
default: return
}
}
}
|
//
// MovieListViewController.swift
// TopMovies2.0
//
// Created by Леганов Андрей on 02/08/2019.
// Copyright © 2019 Леганов Андрей. All rights reserved.
//
import UIKit
class MovieListViewController: UITableViewController {
let service = MovieService()
private var movies = [Movie]()
override func viewDidLoad() {
super.viewDidLoad()
service.fetchMovies { (loadedMovies) in
if loadedMovies.count == 0 {
return
}
self.movies = loadedMovies
self.tableView.reloadData()
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "MovieCell") as? MovieCell else { return UITableViewCell() }
let index = indexPath.row
let movie = movies[index]
cell.setupWith(movie: movie, index: index)
cell.delegate = self
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movies.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 250
}
}
extension MovieListViewController: MovieCellDelegate {
func scheduleButtonPressedAt(index: Int) {
let movie = movies[index]
openCreateEventScreen(movie: movie)
}
func openCreateEventScreen(movie: Movie) {
let createEventSB = UIStoryboard(name: "CreateEvent", bundle: nil)
guard let createEventVC = createEventSB.instantiateInitialViewController() as? CreateEventViewController else { return }
createEventVC.setup(movie: movie)
self.present(createEventVC, animated: true)
}
}
|
//
// main.swift
// ml_chars
//
// Created by Ryan Bernstein on 1/23/16.
// Copyright © 2016 Ryan Bernstein. All rights reserved.
//
import Foundation
// Hardcoding these for now because why not
let trainingDataPath = "/Users/rlb/Documents/School (Current)/CS 545 Machine Learning/Multilayer Character Recognition/training_data.csv"
let testDataPath = "/Users/rlb/Documents/School (Current)/CS 545 Machine Learning/Multilayer Character Recognition/test_data.csv"
let outputDirectory = "/Users/rlb/Documents/School (Current)/CS 545 Machine Learning/Multilayer Character Recognition"
let client = MLClient()
print("Loading data...")
try! client.loadTrainingData(trainingDataPath)
try! client.loadTestData(testDataPath)
print("Done.")
print("Scaling data...")
client.scaleData()
print("Done.")
// Experiments!
let epochLimit = 100
print("Running experiment 1...")
client.testWithParameters(4, learningRate: 0.3, momentum: 0.3, epochLimit: epochLimit).writeToCSV("\(outputDirectory)/exp1.csv")
print("Done. Running experiment 2a...")
client.testWithParameters(4, learningRate: 0.05, momentum: 0.3, epochLimit: epochLimit).writeToCSV("\(outputDirectory)/exp2a.csv")
print("Done. Running experiment 2b...")
client.testWithParameters(4, learningRate: 0.6, momentum: 0.3, epochLimit: epochLimit).writeToCSV("\(outputDirectory)/exp2b.csv")
print("Done. Running experiment 3a...")
client.testWithParameters(4, learningRate: 0.3, momentum: 0.05, epochLimit: epochLimit).writeToCSV("\(outputDirectory)/exp3a.csv")
print("Done. Running experiment 3b...")
client.testWithParameters(4, learningRate: 0.3, momentum: 0.6, epochLimit: epochLimit).writeToCSV("\(outputDirectory)/exp3b.csv")
print("Done. Running experiment 4a...")
client.testWithParameters(2, learningRate: 0.3, momentum: 0.3, epochLimit: epochLimit).writeToCSV("\(outputDirectory)/exp4a.csv")
print("Done. Running experiment 4b...")
client.testWithParameters(8, learningRate: 0.3, momentum: 0.3, epochLimit: epochLimit).writeToCSV("\(outputDirectory)/exp4b.csv")
print("Done.") |
//
// Functions.swift
// Memoji
//
// Created by Nika on 12/6/16.
// Copyright © 2016 Nika. All rights reserved.
//
import Foundation
var scores: [Int] = []
var bestScore = 0
var savedScores = SavedScores()
struct SavedScores {
func returnBestScore() -> Int {
let defaults = UserDefaults.standard
if(defaults.value(forKey: "bestScore") != nil) {
bestScore = defaults.value(forKey: "bestScore") as! Int
}
return bestScore
}
func returnScoresArray() -> [Int] {
let defaults = UserDefaults.standard
if(defaults.object(forKey: "score") != nil) {
scores = defaults.value(forKey: "score") as? [Int] ?? [Int]()
}
return scores
}
}
|
//
// SortableObjectMigrationTool.swift
// RealmIssueReportExample
//
// Created by linjj on 2018/12/20.
// Copyright © 2018 linjj. All rights reserved.
//
import Foundation
import RealmSwift
class SortableObjectMigrationTool {
static let shared = SortableObjectMigrationTool()
var supportStartDBVersion = 1
var registeredClasses = [AnyClass]()
func register(class cls: SortableObject.Type) {
registeredClasses.append(cls)
}
/// 给对应的config设置迁移回调
///
/// - Parameter config: Realm.Configuration
fileprivate func setMigration( with config: inout Realm.Configuration) {
config.migrationBlock = {[weak self] (migration, oldSchemaVersion) in
guard let strongSelf = self else { return }
if oldSchemaVersion < strongSelf.supportStartDBVersion {
IndexManager.shared.migrated = true
for item in strongSelf.registeredClasses {
if let cls = item as? SortableObject.Type {
cls.doMigration(with: migration)
}
}
}
}
}
/// 初始化,包括设置数据迁移执行闭包,初始化索引管理器,注册需要使用到索引管理器的类
/// 并尝试触发迁移,migrationBlock中有检查是否需要迁移的判断
/// - Parameter config: Realm.Configuration
func setupAndMigration(for config: Realm.Configuration) {
var configForMigration = config
setMigration(with: &configForMigration)
IndexManager.shared.setup(forConfiguration: configForMigration)//初始化自增长索引管理器,可传入configuration,默认为Realm.Configuration.defaultConfiguration
// 在索引管理器中注册需要使用到索引管理器的类
for item in registeredClasses {
if let cls = item as? SortableObject.Type {
IndexManager.shared.register(cls.className())
}
}
let _ = try! Realm(configuration: configForMigration)//调用Realm初始化方法,尝试触发旧数据迁移
//如果发生迁移,则对索引进行整理
if IndexManager.shared.migrated {
for item in registeredClasses {
if let cls = item as? SortableObject.Type {
cls.organizeIndex(forConfiguration: configForMigration, true)//给对应的索引进行整理,传入true为逆序
}
}
}
}
}
|
//
// BaseModel.swift
// Customer Peripheral
//
// Created by Fabio Oliveira on 23/10/2014.
// Copyright (c) 2014 Olive 3 Consulting Ltd. All rights reserved.
//
import Foundation
import CoreBluetooth
class BaseModel: NSObject {
let observers: [ModelObserver]!
let sessionManager: AnyObject!
init(sessionManager: AnyObject!, observers: [ModelObserver]!) {
super.init()
self.sessionManager = sessionManager
self.observers = observers
}
/* state management */
var _state: [String:AnyObject]?
func saveState() {
}
func restoreState() {
assert(_state != nil)
for (k,v) in _state! {
self.setValue(v, forKey: k)
}
}
func discardSavedState() {
_state = nil
}
var timestamp: String {
var formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.FullStyle
formatter.timeStyle = NSDateFormatterStyle.FullStyle
return formatter.stringFromDate(NSDate())
}
}
|
//
// ContentView.swift
// SwiftUITest
//
// Created by Tasin Zarkoob on 14/12/2019.
// Copyright © 2019 Taazuh. All rights reserved.
//
import SwiftUI
struct SubHeadlineTextStyle: ViewModifier {
func body(content: Content) -> some View {
content
.font(.largeTitle)
.foregroundColor(.blue)
}
}
extension View {
func headlineFont() -> some View{
self.modifier(SubHeadlineTextStyle())
}
}
struct ContentView: View {
@State private var checkedAmount = ""
@State private var numOfPeople = 2
@State private var tipPercentage = 2
var totalA: Double {
let tipPercent = Double(self.tipPercentageValue[tipPercentage])
let orderAmount = Double(checkedAmount) ?? 0.0
let tipAmount = orderAmount / 100 * tipPercent
return orderAmount + tipAmount
}
var tipPercentageValue = [0, 10, 15, 20, 25]
var totalAmount : Double {
let totalPeople = Double(numOfPeople + 2)
let tipPercent = Double(self.tipPercentageValue[tipPercentage])
let orderAmount = Double(checkedAmount) ?? 0.0
let tipAmount = orderAmount / 100 * tipPercent
let total = orderAmount + tipAmount
return total / totalPeople
}
var body: some View {
NavigationView {
Form {
Section {
TextField("Billing Amount", text: $checkedAmount)
.keyboardType(.decimalPad)
Picker("Number of People", selection: $numOfPeople) {
ForEach(2 ..< 50) {
Text("\($0) people")
}
}
}
Section(header: Text("How much tips would you like to give")) {
Picker("Tip Percentage", selection: $tipPercentage) {
ForEach(0 ..< tipPercentageValue.count) {
Text("\(self.tipPercentageValue[$0])%")
}
}.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("Total Amount")) {
Text("£\(totalA, specifier: "%.2f")")
.foregroundColor(tipPercentage == 0 ? .red : .black)
}
Section(header: Text("Amount per person")) {
Text("£\(totalAmount, specifier: "%.2f")")
.headlineFont()
}
}
.navigationBarTitle("WeSplit")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
//
// Created by Efe Ejemudaro on 12/04/2021.
// Copyright (c) 2021 TopTier labs. All rights reserved.
//
import Foundation
struct RegisterUserResponse: Codable {
let tokenData: TokenData
let user: User
private enum CodingKeys: String, CodingKey {
case tokenData
case user = "profile"
}
}
|
//
// Pokemon.swift
// pokedox
//
// Created by Tushar Katyal on 06/08/17.
// Copyright © 2017 Tushar Katyal. All rights reserved.
//
import Foundation
import Alamofire
class Pokemon {
private var _name : String!
private var _PokedoxId : Int!
private var _description : String!
private var _weight : String!
private var _height : String!
private var _type : String!
private var _defense : String!
private var _attack : String!
private var _pokemonUrl : String!
private var _nextEvolutionName : String!
private var _nextEvolutionId : String!
private var _nextEvolutionLvl : String!
var nextEvolName : String {
if _nextEvolutionName == nil {
_nextEvolutionName = ""
}
return _nextEvolutionName
}
var nextEvolId : String {
if _nextEvolutionId == nil {
_nextEvolutionId = ""
}
return _nextEvolutionId
}
var nextEvolLvl : String {
if _nextEvolutionLvl == nil {
_nextEvolutionLvl = ""
}
return _nextEvolutionLvl
}
var description : String {
if _description == nil {
_description = ""
}
return _description
}
var weight : String {
if _weight == nil {
_weight = ""
}
return _weight
}
var height : String {
if _height == nil {
_height = ""
}
return _height
}
var type : String {
if _type == nil {
_type = ""
}
return _type
}
var defense : String {
if _defense == nil {
_defense = ""
}
return _defense
}
var attack : String {
if _attack == nil {
_attack = ""
}
return _attack
}
var name : String {
return _name
}
var pokedoxId : Int {
return _PokedoxId
}
init(name : String , pokedoxId : Int) {
self._name = name
self._PokedoxId = pokedoxId
self._pokemonUrl = "\(URL_BASE)\(URL_POKEMON)\(self.pokedoxId)/"
}
// parsing API data using Alamofire here
func downloadPokemonDetail(completed : @escaping DownloadComplete){
Alamofire.request(_pokemonUrl).responseJSON { (response) in
if let dict = response.result.value as? Dictionary<String, AnyObject> {
if let weight = dict["weight"] as? String {
self._weight = weight
}
if let height = dict["height"] as? String {
self._height = height
}
if let attack = dict["attack"] as? Int {
self._attack = "\(attack)"
}
if let defense = dict["defense"] as? Int {
self._defense = "\(defense)"
}
if let types = dict["types"] as? [Dictionary<String, String>] , types.count > 0{
if let name = types[0]["name"] {
self._type = name.capitalized
if types.count > 1 {
for x in 1..<types.count {
if let name = types[x]["name"] {
self._type! += "/\(name.capitalized)"
}
}
}
}
}
if let descArr = dict["descriptions"] as? [Dictionary<String,String>], descArr.count>0 {
if let url = descArr[0]["resource_uri"] {
let decURL = "\(URL_BASE)\(url)"
Alamofire.request(decURL).responseJSON(completionHandler: { (response) in
if let descDict = response.result.value as? Dictionary<String,AnyObject> {
if let description = descDict["description"] as? String {
let newDesc = description.replacingOccurrences(of: "POKMON", with: "Pokemon")
self._description = newDesc
print(self._description)
}
}
completed()
})
}
}
if let evolDict = dict["evolutions"] as? [Dictionary<String,AnyObject>],evolDict.count > 0 {
if let nextEvo = evolDict[0]["to"] as? String {
// checking condtion because mega's resources not available
if nextEvo.range(of: "mega") == nil {
self._nextEvolutionName = nextEvo
}
}
if let uri = evolDict[0]["resource_uri"] as? String {
let newStr = uri.replacingOccurrences(of: "/api/v1/pokemon/", with: "")
let nextEvolId = newStr.replacingOccurrences(of: "/", with: "")
self._nextEvolutionId = nextEvolId
}
if let levelExist = evolDict[0]["level"] {
if let level = levelExist as? Int {
self._nextEvolutionLvl = "\(level)"
}
}
else {
self._nextEvolutionLvl = ""
}
}
}
completed()
}
}
}
|
//
// WithUnretained.swift
// CombineExt
//
// Created by Robert on 01/09/2021.
// Copyright © 2020 Combine Community. All rights reserved.
//
#if canImport(Combine)
import Combine
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public extension Publisher {
/**
Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events published by the publisher.
In the case the provided object cannot be retained successfully, the publisher will complete.
- parameter obj: The object to provide an unretained reference on.
- parameter resultSelector: A function to combine the unretained referenced on `obj` and the value of the observable sequence.
- returns: A publisher that contains the result of `resultSelector` being called with an unretained reference on `obj` and the values of the upstream.
*/
func withUnretained<UnretainedObject: AnyObject, Output>(_ obj: UnretainedObject, resultSelector: @escaping (UnretainedObject, Self.Output) -> Output) -> Publishers.WithUnretained<UnretainedObject, Self, Output> {
Publishers.WithUnretained(unretainedObject: obj, upstream: self, resultSelector: resultSelector)
}
/**
Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events published by the publisher.
In the case the provided object cannot be retained successfully, the publisher will complete.
- parameter obj: The object to provide an unretained reference on.
- returns: A publisher that publishes a sequence of tuples that contains both an unretained reference on `obj` and the values of the upstream.
*/
func withUnretained<UnretainedObject: AnyObject>(_ obj: UnretainedObject) -> Publishers.WithUnretained<UnretainedObject, Self, (UnretainedObject, Output)> {
Publishers.WithUnretained(unretainedObject: obj, upstream: self) { ($0, $1) }
}
/// Attaches a subscriber with closure-based behavior.
///
/// Use ``Publisher/sink(unretainedObject:receiveCompletion:receiveValue:)`` to observe values received by the publisher and process them using a closure you specify.
/// This method creates the subscriber and immediately requests an unlimited number of values, prior to returning the subscriber.
/// The return value should be held, otherwise the stream will be canceled.
///
/// - parameter obj: The object to provide an unretained reference on.
/// - parameter receiveComplete: The closure to execute on completion.
/// - parameter receiveValue: The closure to execute on receipt of a value.
/// - Returns: A cancellable instance, which you use when you end assignment of the received value. Deallocation of the result will tear down the subscription stream.
func sink<UnretainedObject: AnyObject>(unretainedObject obj: UnretainedObject, receiveCompletion: @escaping ((Subscribers.Completion<Self.Failure>) -> Void), receiveValue: @escaping ((UnretainedObject, Self.Output) -> Void)) -> AnyCancellable {
withUnretained(obj)
.sink(receiveCompletion: receiveCompletion, receiveValue: receiveValue)
}
}
// MARK: - Publisher
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public extension Publishers {
struct WithUnretained<UnretainedObject: AnyObject, Upstream: Publisher, Output>: Publisher {
public typealias Failure = Upstream.Failure
private weak var unretainedObject: UnretainedObject?
private let upstream: Upstream
private let resultSelector: (UnretainedObject, Upstream.Output) -> Output
public init(unretainedObject: UnretainedObject, upstream: Upstream, resultSelector: @escaping (UnretainedObject, Upstream.Output) -> Output) {
self.unretainedObject = unretainedObject
self.upstream = upstream
self.resultSelector = resultSelector
}
public func receive<S: Combine.Subscriber>(subscriber: S) where Failure == S.Failure, Output == S.Input {
upstream.subscribe(Subscriber(unretainedObject: unretainedObject, downstream: subscriber, resultSelector: resultSelector))
}
}
}
// MARK: - Subscriber
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
private extension Publishers.WithUnretained {
class Subscriber<Downstream: Combine.Subscriber>: Combine.Subscriber where Downstream.Input == Output, Downstream.Failure == Failure {
typealias Input = Upstream.Output
typealias Failure = Downstream.Failure
private weak var unretainedObject: UnretainedObject?
private let downstream: Downstream
private let resultSelector: (UnretainedObject, Input) -> Output
init(unretainedObject: UnretainedObject?, downstream: Downstream, resultSelector: @escaping (UnretainedObject, Input) -> Output) {
self.unretainedObject = unretainedObject
self.downstream = downstream
self.resultSelector = resultSelector
}
func receive(subscription: Subscription) {
if unretainedObject == nil { return }
downstream.receive(subscription: subscription)
}
func receive(_ input: Input) -> Subscribers.Demand {
guard let unretainedObject = unretainedObject else { return .none }
return downstream.receive(resultSelector(unretainedObject, input))
}
func receive(completion: Subscribers.Completion<Failure>) {
if unretainedObject == nil {
return downstream.receive(completion: .finished)
}
downstream.receive(completion: completion)
}
}
}
#endif
|
//
// DispatchGlobalViewController.swift
// GcdExecutor
//
// Created by bin on 2018/12/29.
// Copyright © 2018年 BinHuang. All rights reserved.
//
import UIKit
class DispatchSuspendViewController: UIViewController {
lazy var label : UILabel! = {
let label = UILabel.init(frame: CGRect.init(x: 10, y: 130, width: 320, height: 500));
label.numberOfLines = 0;
label.font = UIFont.systemFont(ofSize: 14);
label.textColor = UIColor.black
label.text = "在这里显示运行结果:";
label.sizeToFit();
return label;
}();
lazy var btn : UIButton! = {
let btn : UIButton = UIButton.init(type: .system);
btn.frame = CGRect.init(x: 10, y: 70, width: 100, height: 50);
btn.layer.masksToBounds = true;
btn.layer.cornerRadius = 3;
btn.setTitle("执行queue", for: .normal);
btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
btn.setTitleColor(UIColor.white, for: .normal);
btn.backgroundColor = UIColor.blue;
return btn;
}();
lazy var btn2 : UIButton! = {
let btn : UIButton = UIButton.init(type: .system);
btn.frame = CGRect.init(x: 120, y: 70, width: 100, height: 50);
btn.layer.masksToBounds = true;
btn.layer.cornerRadius = 3;
btn.setTitle("suspend", for: .normal);
btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
btn.setTitleColor(UIColor.white, for: .normal);
btn.backgroundColor = UIColor.blue;
return btn;
}();
lazy var btn3 : UIButton! = {
let btn : UIButton = UIButton.init(type: .system);
btn.frame = CGRect.init(x: 230, y: 70, width: 100, height: 50);
btn.layer.masksToBounds = true;
btn.layer.cornerRadius = 3;
btn.setTitle("resume", for: .normal);
btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
btn.setTitleColor(UIColor.white, for: .normal);
btn.backgroundColor = UIColor.blue;
return btn;
}();
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Apply";
self.view.backgroundColor = UIColor.white;
self.view.addSubview(self.label);
self.view.addSubview(self.btn);
self.view.addSubview(self.btn2);
self.view.addSubview(self.btn3);
self.btn.addTarget(self, action: #selector(self.execAction(_:)), for: .touchUpInside);
self.btn2.addTarget(self, action: #selector(self.execAction(_:)), for: .touchUpInside);
self.btn3.addTarget(self, action: #selector(self.execAction(_:)), for: .touchUpInside);
}
@objc func execAction(_ btn : UIButton){
if(btn == self.btn){
self.label.text = "在这里显示运行结果:";
self.executeSync1();
}
else if(btn == self.btn2){
self.label.text = "will suspend";
self.executeSync2();
}
else if(btn == self.btn3){
self.label.text = "will resume";
self.executeSync3();
}
}
func log(_ text : String,_ thread : Thread){
print(text + ": 当前线程的hash为\(thread.hash)")
DispatchQueue.main.async {
if((self.label.text! as NSString).length >= 100){
self.label.text = "在这里显示运行结果:";
}
self.label.text = self.label.text! + "\n" + text;
self.label.sizeToFit();
var newframe = self.label.frame;
newframe.size.width = 320;
self.label.frame = newframe;
}
}
var concurrentQueue : DispatchQueue! = DispatchQueue(label: "com.dianbo.concurrentQueue", attributes: .concurrent)
func executeSync1(){
for index in 0...5{
concurrentQueue.async {
self.log("\(index)", Thread.current);
sleep(2)
}
}
}
func executeSync2(){
concurrentQueue.suspend()
for index in 6...10{
concurrentQueue.async {
self.log("\(index)", Thread.current);
sleep(2)
}
}
}
func executeSync3(){
concurrentQueue.resume()
}
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.
}
*/
}
|
//
// UIView+RoundCorner.swift
// RoundCornerProgressView
//
// Created by Chi-Quyen Le on 12/10/16.
// Copyright © 2016 Phuc Nguyen. All rights reserved.
//
import UIKit
extension UIView {
func roundCorner(roundingCorners: UIRectCorner, cornerRadius: CGSize) {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: roundingCorners, cornerRadii: cornerRadius)
let maskLayer = CAShapeLayer()
maskLayer.path = path.cgPath
layer.mask = maskLayer
}
}
|
//
// MainScreenTableViewCell.swift
// IKTestTask
//
// Created by Kukshtel I. on 8/5/19.
// Copyright © 2019 Kukshtel I. All rights reserved.
//
import UIKit
final class MainScreenTableViewCell: UITableViewCell {
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var firstLabel: UILabel!
@IBOutlet weak var secondLabel: UILabel!
override func prepareForReuse() {
super.prepareForReuse()
icon.image = nil
}
}
|
//
// WelcomeViewController.swift
// Owly
//
// Created by Sung on 4/11/19.
// Copyright © 2019 carolaguivel. All rights reserved.
//
import UIKit
class WelcomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
//
// SafariViewController.swift
// DemoUIKit
//
// Created by SHIH-YING PAN on 2019/12/4.
// Copyright © 2019 SHIH-YING PAN. All rights reserved.
//
import Foundation
import SafariServices
import SwiftUI
struct SafariViewController: UIViewControllerRepresentable {
var url: URL
func makeUIViewController(context: Context) -> SFSafariViewController {
SFSafariViewController(url: url)
}
func updateUIViewController(_ uiViewController: SFSafariViewController, context: Context) {
}
}
|
//
// GitAPI.swift
// SwivlTest
//
// Created by Oleksandr Marchenko on 8/25/18.
// Copyright © 2018 Oleksandr Marchenko. All rights reserved.
//
import Foundation
import RxSwift
import HTTPStatusCodes
//{
// "login": "octocat",
// "id": 1,
// "node_id": "MDQ6VXNlcjE=",
// "avatar_url": "https://github.com/images/error/octocat_happy.gif",
// "gravatar_id": "",
// "url": "https://api.github.com/users/octocat",
// "html_url": "https://github.com/octocat",
// "followers_url": "https://api.github.com/users/octocat/followers",
// "following_url": "https://api.github.com/users/octocat/following{/other_user}",
// "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",
// "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",
// "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",
// "organizations_url": "https://api.github.com/users/octocat/orgs",
// "repos_url": "https://api.github.com/users/octocat/repos",
// "events_url": "https://api.github.com/users/octocat/events{/privacy}",
// "received_events_url": "https://api.github.com/users/octocat/received_events",
// "type": "User",
// "site_admin": false
//}
class GitUser: Decodable {
private enum CodingKeys: String, CodingKey {
case login
case htmlURL = "html_url"
case avatarURL = "avatar_url"
case followersURL = "followers_url"
}
let login: String
let htmlURL: URL
let avatarURL: URL
let followersURL: URL
}
typealias GitUsersPage = (users: [GitUser], nextPageUrl: URL?)
class GitAPI {
private static let usersURL = URL(string: "https://api.github.com/users")!
enum Error: Swift.Error {
case networkError(underlyingError: Swift.Error)
case serverError(statusCode: HTTPStatusCode, response: String)
case parsingError(underlyingError: Swift.Error)
case unknownError
}
static func getUsers(url: URL? = nil) -> Single<GitUsersPage> {
let url = url ?? GitAPI.usersURL
print("Retrieving \(url))")
return Single.create { observer in
let task = URLSession.shared.dataTask(with: url) { data, response, error in
DispatchQueue.main.async {
if let error = error {
observer(.error(Error.networkError(underlyingError: error)))
return
}
guard let httpResponse = response as? HTTPURLResponse else { fatalError("Should never happen") }
guard let data = data else {
observer(.error(Error.serverError(statusCode: httpResponse.statusCodeEnum, response: "Empty response")))
return
}
guard httpResponse.statusCodeEnum.isSuccess else {
let responseString = String(data: data, encoding: .utf8) ?? "Empty response"
observer(.error(Error.serverError(statusCode: httpResponse.statusCodeEnum, response: responseString)))
return
}
do {
let decoder = JSONDecoder()
let users = try decoder.decode([GitUser].self, from: data)
let result = GitUsersPage(users: users, nextPageUrl: httpResponse.linkForNext())
observer(.success(result))
} catch {
observer(.error(Error.parsingError(underlyingError: error)))
}
}
}
task.resume()
return Disposables.create()
}
}
}
extension HTTPURLResponse {
func linkForNext() -> URL? {
guard let linkHeader = allHeaderFields["Link"] as? String else {
return nil
}
let pattern = "<([^<>]*)>; rel=\"next\""
guard let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive) else { fatalError("Invalid regex pattern") }
guard let match = regex.firstMatch(in: linkHeader, range: NSRange(location: 0, length: linkHeader.count)) else {
return nil
}
guard match.numberOfRanges == 2 else {
return nil
}
guard let range = Range(match.range(at: 1), in: linkHeader) else {
return nil
}
guard let url = URL(string: String(linkHeader[range])) else {
return nil
}
return url
}
}
|
// RUN: rm -rf %t && mkdir %t
// RUN: %target-build-swift -c -force-single-frontend-invocation -parse-as-library -emit-module -emit-module-path %t/PrintTestTypes.swiftmodule -o %t/PrintTestTypes.o %S/Inputs/PrintTestTypes.swift
// RUN: %target-build-swift %s -Xlinker %t/PrintTestTypes.o -I %t -L %t -o %t/main
// RUN: %target-run %t/main
// REQUIRES: executable_test
import StdlibUnittest
import PrintTestTypes
let PrintTests = TestSuite("PrintString")
PrintTests.test("Printable") {
let s0: String = "abc"
expectPrinted("abc", s0)
expectDebugPrinted("\"abc\"", s0)
let s1: String = "\\ \' \" \0 \n \r \t \u{05}"
expectDebugPrinted("\"\\\\ \\\' \\\" \\0 \\n \\r \\t \\u{05}\"", s1)
let ch: Character = "a"
expectPrinted("a", ch)
expectDebugPrinted("\"a\"", ch)
let us0: UnicodeScalar = "a"
expectPrinted("a", us0)
expectDebugPrinted("\"a\"", us0)
let us1: UnicodeScalar = "\\"
expectPrinted("\\", us1)
expectEqual("\"\\\\\"", us1.description)
expectDebugPrinted("\"\\\\\"", us1)
let us2: UnicodeScalar = "あ"
expectPrinted("あ", us2)
expectEqual("\"あ\"", us2.description)
expectDebugPrinted("\"\\u{3042}\"", us2)
}
PrintTests.test("Printable") {
expectPrinted("Optional(\"meow\")", String?("meow"))
}
PrintTests.test("CustomStringInterpolation") {
let s = ("aaa\(1)bbb" as MyString).value
expectEqual("<segment aaa><segment 1><segment bbb>", s)
}
runAllTests()
|
//
// TabBar.swift
// CustomTabBar
//
// Created by Fabrizio Duroni on 06.03.20.
//
import SwiftUI
struct TabBar: View {
@Binding private var currentView: TabPosition
@Binding private var showModal: Bool
private let tabItemsProperties: [TabItemProperties]
private let modal: TabModal
private let tabItemColors: TabItemsColors
init(
currentView: Binding<TabPosition>,
showModal: Binding<Bool>,
tabItemColors: TabItemsColors,
tabItems: [TabItemProperties],
modal: TabModal
) {
self._currentView = currentView
self._showModal = showModal
self.tabItemColors = tabItemColors
self.tabItemsProperties = tabItems
self.modal = modal
}
var body: some View {
HStack(alignment: .center, spacing: 0) {
Spacer()
TabItemsList(
currentView: $currentView,
tabItemsProperties: firstHalfTabItems(),
tabItemColors: tabItemColors
)
TabBarModalItem(modalTabBarItemContent: modal.modalTabBarItemContent) { showModal.toggle() }
Spacer()
TabItemsList(
currentView: $currentView,
tabItemsProperties: secondHalfTabItems(),
tabItemColors: tabItemColors
)
}
.frame(minHeight: 70)
.sheet(isPresented: $showModal) { modal }
.accessibilityElement(children: .contain)
.accessibility(identifier: "TabBar")
}
func firstHalfTabItems() -> [TabItemProperties] {
return Array(tabItemsProperties[0..<tabItemsProperties.count/2])
}
func secondHalfTabItems() -> [TabItemProperties] {
return Array(tabItemsProperties[tabItemsProperties.count/2..<tabItemsProperties.count])
}
}
|
//
// UIKit+Extension.swift
// StoryReader
//
// Created by 020-YinTao on 2017/5/8.
// Copyright © 2017年 020-YinTao. All rights reserved.
//
import UIKit
extension NSObject {
public var visibleViewController: UIViewController? {
get {
guard let rootVC = UIApplication.shared.delegate?.window??.rootViewController else{
return nil
}
return getVisibleViewController(from: rootVC)
}
}
private func getVisibleViewController(from: UIViewController?) ->UIViewController? {
if let nav = from as? UINavigationController {
// return getVisibleViewController(from:nav.visibleViewController)
return getVisibleViewController(from:nav.viewControllers.last)
}else if let tabBar = from as? UITabBarController {
return getVisibleViewController(from: tabBar.selectedViewController)
}else {
guard let presentedVC = from?.presentedViewController else {
return from
}
return getVisibleViewController(from: presentedVC)
}
}
}
|
/* Copyright Airship and Contributors */
import XCTest
@testable
import AirshipCore
class ChannelRegistrarTest: XCTestCase {
private let dataStore = PreferenceDataStore(appKey: UUID().uuidString)
private let client = TestChannelRegistrationClient()
private let delegate = TestChannelRegistrarDelegate()
private let date = UATestDate()
private let taskManager = TestTaskManager()
private let dispatcher = TestDispatcher()
private let appStateTracker = AppStateTracker()
private var channelRegistrar: ChannelRegistrar!
override func setUpWithError() throws {
self.channelRegistrar = ChannelRegistrar(dataStore: self.dataStore,
channelAPIClient: self.client,
date: self.date,
dispatcher: self.dispatcher,
taskManager: self.taskManager,
appStateTracker: self.appStateTracker)
self.client.defaultCallback = { method in
XCTFail("Method \(method) called unexpectedly")
}
channelRegistrar.delegate = self.delegate
}
func testRegister() throws {
XCTAssertEqual(0, self.taskManager.enqueuedRequestsCount)
self.channelRegistrar.register(forcefully: false)
XCTAssertEqual(1, self.taskManager.enqueuedRequestsCount)
let extras = ["forcefully": false]
let options = TaskRequestOptions(conflictPolicy: UATaskConflictPolicy.keep, requiresNetwork: true, extras: extras)
let task = self.taskManager.enqueuedRequests[0]
XCTAssertEqual("UAChannelRegistrar.registration", task.taskID)
XCTAssertEqual(options, task.options)
XCTAssertEqual(0, task.minDelay)
}
func testRegisterForcefully() throws {
XCTAssertEqual(0, self.taskManager.enqueuedRequestsCount)
self.channelRegistrar.register(forcefully: true)
XCTAssertEqual(1, self.taskManager.enqueuedRequestsCount)
let options = TaskRequestOptions(conflictPolicy: UATaskConflictPolicy.replace, requiresNetwork: true, extras: ["forcefully": true])
let task = self.taskManager.enqueuedRequests[0]
XCTAssertEqual(ChannelRegistrar.taskID, task.taskID)
XCTAssertEqual(options, task.options)
XCTAssertEqual(0, task.minDelay)
}
func testCreateChannel() throws {
let payload = ChannelRegistrationPayload()
payload.channel.deviceModel = UUID().uuidString
self.delegate.channelPayload = payload
let expectation = XCTestExpectation(description: "callback called")
self.client.createCallback = { channelPayload, callback in
XCTAssertEqual(channelPayload, payload)
callback(ChannelCreateResponse(status: 201, channelID: "some-channel-id"), nil)
expectation.fulfill()
}
let task = self.taskManager.launchSync(taskID: ChannelRegistrar.taskID)
XCTAssertTrue(task.completed)
wait(for: [expectation], timeout: 10.0)
XCTAssertTrue(self.delegate.didRegistrationSucceed!)
XCTAssertEqual("some-channel-id", self.delegate.channelCreatedResponse!.0)
XCTAssertFalse(self.delegate.channelCreatedResponse!.1)
}
func testCreateChannelExisting() throws {
let payload = ChannelRegistrationPayload()
payload.channel.deviceModel = UUID().uuidString
self.delegate.channelPayload = payload
let expectation = XCTestExpectation(description: "callback called")
self.client.createCallback = { channelPayload, callback in
XCTAssertEqual(channelPayload, payload)
callback(ChannelCreateResponse(status: 200, channelID: "some-channel-id"), nil)
expectation.fulfill()
}
let task = self.taskManager.launchSync(taskID: ChannelRegistrar.taskID)
XCTAssertTrue(task.completed)
wait(for: [expectation], timeout: 10.0)
XCTAssertTrue(self.delegate.didRegistrationSucceed!)
XCTAssertEqual("some-channel-id", self.delegate.channelCreatedResponse!.0)
XCTAssertTrue(self.delegate.channelCreatedResponse!.1)
}
func testCreateChannelFailed() {
let payload = ChannelRegistrationPayload()
payload.channel.deviceModel = UUID().uuidString
let error = AirshipErrors.error("Some error")
self.delegate.channelPayload = payload
let expectation = XCTestExpectation(description: "callback called")
self.client.createCallback = { channelPayload, callback in
XCTAssertEqual(channelPayload, payload)
callback(nil, error)
expectation.fulfill()
}
let task = self.taskManager.launchSync(taskID: ChannelRegistrar.taskID)
XCTAssertTrue(task.failed)
wait(for: [expectation], timeout: 10.0)
XCTAssertFalse(self.delegate.didRegistrationSucceed!)
XCTAssertNil(self.delegate.channelCreatedResponse)
}
func testUpdateChannel() {
let someChannelID = UUID().uuidString
let payload = ChannelRegistrationPayload()
payload.channel.deviceModel = UUID().uuidString
// Create the channel
self.delegate.channelPayload = payload
createChannel(channelID: someChannelID)
// Modify the payload so the update happens
payload.channel.deviceModel = UUID().uuidString
let expectation = XCTestExpectation(description: "callback called")
self.client.updateCallback = { channelID, channelPayload, callback in
XCTAssertEqual(someChannelID, channelID)
XCTAssertEqual(channelPayload, payload)
callback(HTTPResponse(status: 200), nil)
expectation.fulfill()
}
let options = TaskRequestOptions(conflictPolicy: UATaskConflictPolicy.replace, requiresNetwork: true, extras: ["forcefully": false])
let task = self.taskManager.launchSync(taskID: ChannelRegistrar.taskID, options: options)
XCTAssertTrue(task.completed)
wait(for: [expectation], timeout: 10.0)
XCTAssertTrue(self.delegate.didRegistrationSucceed!)
XCTAssertNil(self.delegate.channelCreatedResponse)
}
func testSkipUpdateChannelUpToDate() {
let someChannelID = UUID().uuidString
let payload = ChannelRegistrationPayload()
payload.channel.deviceModel = UUID().uuidString
// Create the channel
self.delegate.channelPayload = payload
createChannel(channelID: someChannelID)
// Try to update
let options = TaskRequestOptions(conflictPolicy: UATaskConflictPolicy.replace, requiresNetwork: true, extras: ["forcefully": false])
let task = self.taskManager.launchSync(taskID: ChannelRegistrar.taskID, options: options)
XCTAssertTrue(task.completed)
XCTAssertNil(self.delegate.didRegistrationSucceed)
XCTAssertNil(self.delegate.channelCreatedResponse)
}
func testUpdateNotConfigured() {
self.client.isURLConfigured = false
self.channelRegistrar.register(forcefully: true)
self.channelRegistrar.register(forcefully: false)
XCTAssertEqual(0, self.taskManager.enqueuedRequestsCount)
self.client.isURLConfigured = true
self.channelRegistrar.register(forcefully: true)
self.channelRegistrar.register(forcefully: false)
XCTAssertEqual(2, self.taskManager.enqueuedRequestsCount)
}
func testUpdateForcefully() {
let someChannelID = UUID().uuidString
let payload = ChannelRegistrationPayload()
payload.channel.deviceModel = UUID().uuidString
// Create the channel
self.delegate.channelPayload = payload
createChannel(channelID: someChannelID)
// Do not update the payload, should still update
let expectation = XCTestExpectation(description: "callback called")
self.client.updateCallback = { channelID, channelPayload, callback in
XCTAssertEqual(someChannelID, channelID)
// will use the minimized payload
XCTAssertEqual(channelPayload, payload.minimizePayload(previous: payload))
callback(HTTPResponse(status: 200), nil)
expectation.fulfill()
}
let options = TaskRequestOptions(conflictPolicy: UATaskConflictPolicy.replace, requiresNetwork: true, extras: ["forcefully": true])
let task = self.taskManager.launchSync(taskID: ChannelRegistrar.taskID, options: options)
XCTAssertTrue(task.completed)
wait(for: [expectation], timeout: 10.0)
XCTAssertTrue(self.delegate.didRegistrationSucceed!)
XCTAssertNil(self.delegate.channelCreatedResponse)
}
func testFullUpdate() {
let someChannelID = UUID().uuidString
let payload = ChannelRegistrationPayload()
payload.channel.deviceModel = UUID().uuidString
// Create the channel
self.delegate.channelPayload = payload
createChannel(channelID: someChannelID)
self.channelRegistrar.performFullRegistration()
XCTAssertEqual(1, self.taskManager.enqueuedRequestsCount)
let expectation = XCTestExpectation(description: "callback called")
self.client.updateCallback = { channelID, channelPayload, callback in
XCTAssertEqual(someChannelID, channelID)
// will use the full
XCTAssertEqual(channelPayload, payload)
callback(HTTPResponse(status: 200), nil)
expectation.fulfill()
}
let options = TaskRequestOptions(conflictPolicy: UATaskConflictPolicy.replace, requiresNetwork: true, extras: ["forcefully": true])
let task = self.taskManager.launchSync(taskID: ChannelRegistrar.taskID, options: options)
XCTAssertTrue(task.completed)
wait(for: [expectation], timeout: 10.0)
XCTAssertTrue(self.delegate.didRegistrationSucceed!)
XCTAssertNil(self.delegate.channelCreatedResponse)
}
func testUpdateMinimizedPayload() throws {
let someChannelID = UUID().uuidString
let payload = ChannelRegistrationPayload()
payload.channel.deviceModel = UUID().uuidString
payload.channel.appVersion = "1.0.0"
let updatePayload = ChannelRegistrationPayload()
updatePayload.channel.deviceModel = payload.channel.deviceModel
payload.channel.appVersion = "2.0.0"
let minimized = updatePayload.minimizePayload(previous: payload)
XCTAssertNotEqual(minimized, updatePayload)
// Create the channel with first payload
self.delegate.channelPayload = payload
createChannel(channelID: someChannelID)
// Update with updated payload
self.delegate.channelPayload = updatePayload
let expectation = XCTestExpectation(description: "callback called")
self.client.updateCallback = { channelID, channelPayload, callback in
XCTAssertEqual(someChannelID, channelID)
// Verify it uses minimized payload
XCTAssertEqual(channelPayload, minimized)
callback(HTTPResponse(status: 200), nil)
expectation.fulfill()
}
let options = TaskRequestOptions(conflictPolicy: UATaskConflictPolicy.replace, requiresNetwork: true, extras: ["forcefully": false])
let task = self.taskManager.launchSync(taskID: ChannelRegistrar.taskID, options: options)
XCTAssertTrue(task.completed)
wait(for: [expectation], timeout: 10.0)
XCTAssertTrue(self.delegate.didRegistrationSucceed!)
XCTAssertNil(self.delegate.channelCreatedResponse)
}
func testUpdateAfter24Hours() {
self.date.dateOverride = Date()
let someChannelID = UUID().uuidString
let payload = ChannelRegistrationPayload()
payload.channel.deviceModel = UUID().uuidString
// Create the channel
self.delegate.channelPayload = payload
createChannel(channelID: someChannelID)
// Try to update
let options = TaskRequestOptions(conflictPolicy: UATaskConflictPolicy.replace, requiresNetwork: true, extras: ["forcefully": false])
XCTAssertTrue(self.taskManager.launchSync(taskID: ChannelRegistrar.taskID, options: options).completed)
XCTAssertNil(self.delegate.didRegistrationSucceed)
// Forward to almost 1 second before 24 hours
self.date.offset = 24 * 60 * 60 - 1
// Should still not update
XCTAssertTrue(self.taskManager.launchSync(taskID: ChannelRegistrar.taskID, options: options).completed)
XCTAssertNil(self.delegate.didRegistrationSucceed)
// 24 hours
self.date.offset += 1
// Expect an update
let expectation = XCTestExpectation(description: "callback called")
self.client.updateCallback = { channelID, channelPayload, callback in
XCTAssertEqual(someChannelID, channelID)
XCTAssertEqual(channelPayload, payload.minimizePayload(previous: payload))
callback(HTTPResponse(status: 200), nil)
expectation.fulfill()
}
XCTAssertTrue(self.taskManager.launchSync(taskID: ChannelRegistrar.taskID, options: options).completed)
wait(for: [expectation], timeout: 10.0)
XCTAssertTrue(self.delegate.didRegistrationSucceed!)
}
func testUpdateFailed() {
let someChannelID = UUID().uuidString
let payload = ChannelRegistrationPayload()
payload.channel.deviceModel = UUID().uuidString
self.delegate.channelPayload = payload
// Create a channel
createChannel(channelID: someChannelID)
// Expect an update
let expectation = XCTestExpectation(description: "callback called")
self.client.updateCallback = { channelID, channelPayload, callback in
XCTAssertEqual(someChannelID, channelID)
XCTAssertEqual(channelPayload, payload.minimizePayload(previous: payload))
callback(nil, AirshipErrors.error("failed!"))
expectation.fulfill()
}
let options = TaskRequestOptions(conflictPolicy: UATaskConflictPolicy.replace, requiresNetwork: true, extras: ["forcefully": true])
XCTAssertTrue(self.taskManager.launchSync(taskID: ChannelRegistrar.taskID, options: options).failed)
wait(for: [expectation], timeout: 10.0)
XCTAssertFalse(self.delegate.didRegistrationSucceed!)
XCTAssertNil(self.delegate.channelCreatedResponse)
}
private func createChannel(channelID: String) {
self.client.createCallback = { channelPayload, callback in
callback(ChannelCreateResponse(status: 200, channelID: channelID), nil)
}
let task = self.taskManager.launchSync(taskID: ChannelRegistrar.taskID)
XCTAssertTrue(task.completed)
// Clear state
self.client.createCallback = nil
self.delegate.didRegistrationSucceed = nil
self.delegate.channelCreatedResponse = nil
}
}
internal class TestChannelRegistrarDelegate : ChannelRegistrarDelegate {
var channelCreatedResponse: (String, Bool)?
var didRegistrationSucceed: Bool?
var channelPayload: ChannelRegistrationPayload?
func channelCreated(channelID: String, existing: Bool) {
self.channelCreatedResponse = (channelID, existing)
}
func createChannelPayload(completionHandler: @escaping (ChannelRegistrationPayload) -> ()) {
completionHandler(self.channelPayload!)
}
func registrationFailed() {
self.didRegistrationSucceed = false
}
func registrationSucceeded() {
self.didRegistrationSucceed = true
}
}
internal class TestChannelRegistrationClient : ChannelAPIClientProtocol {
var createCallback: ((ChannelRegistrationPayload, ((ChannelCreateResponse?, Error?) -> Void)) -> Void)?
var updateCallback: ((String, ChannelRegistrationPayload, ((HTTPResponse?, Error?) -> Void)) -> Void)?
var defaultCallback: ((String) -> Void)?
var isURLConfigured: Bool = true
@discardableResult
func createChannel(withPayload payload: ChannelRegistrationPayload, completionHandler: @escaping (ChannelCreateResponse?, Error?) -> Void) -> Disposable {
if let callback = createCallback {
callback(payload, completionHandler)
} else {
defaultCallback?("createChannel")
}
return Disposable()
}
@discardableResult
func updateChannel(withID channelID: String, withPayload payload: ChannelRegistrationPayload, completionHandler: @escaping (HTTPResponse?, Error?) -> Void) -> Disposable {
if let callback = updateCallback {
callback(channelID, payload, completionHandler)
} else {
defaultCallback?("updateChannel")
}
return Disposable()
}
}
|
//
// NavSysCmd.swift
// AdventOfCode
//
// Created by Shawn Veader on 12/10/21.
//
import Foundation
struct NavSysCmd {
enum ChunkDelimiter {
enum DelimitedDirection {
case open
case close
}
case parens(direction: DelimitedDirection)
case squareBrackets(direction: DelimitedDirection)
case curlyBraces(direction: DelimitedDirection)
case angles(direction: DelimitedDirection)
case invalid
var isOpen: Bool {
if case .parens(let direction) = self, case .open = direction {
return true
} else if case .squareBrackets(let direction) = self, case .open = direction {
return true
} else if case .curlyBraces(let direction) = self, case .open = direction {
return true
} else if case .angles(let direction) = self, case .open = direction {
return true
}
return false
}
var isClose: Bool {
!isOpen
}
func sameType(as del: ChunkDelimiter) -> Bool {
switch (self, del) {
case (.parens, .parens):
return true
case (.squareBrackets, .squareBrackets):
return true
case (.curlyBraces, .curlyBraces):
return true
case (.angles, .angles):
return true
default:
return false
}
}
static func parse(_ input: String) -> ChunkDelimiter {
switch input {
case "(":
return .parens(direction: .open)
case ")":
return .parens(direction: .close)
case "[":
return .squareBrackets(direction: .open)
case "]":
return .squareBrackets(direction: .close)
case "{":
return .curlyBraces(direction: .open)
case "}":
return .curlyBraces(direction: .close)
case "<":
return .angles(direction: .open)
case ">":
return .angles(direction: .close)
default:
return .invalid
}
}
}
struct ParseResult {
let isOpen: Bool
let isCorrupt: Bool
let corruptIndex: Int?
let corruptValue: String?
let openChunks: [ChunkDelimiter]
}
let command: String
let parseResult: ParseResult
/// Is the command corrupted? (ie: has a closing character out of place)
var isCorrupted: Bool {
parseResult.isCorrupt
}
/// Is the command open? (ie: not terminated correctly)
var isOpen: Bool {
parseResult.isOpen
}
init(command: String) {
self.command = command
self.parseResult = NavSysCmd.parse(command: command)
}
/// Parse the command and determine if it is valid, "open", or corrupt.
static func parse(command: String) -> ParseResult {
var openChunks = [ChunkDelimiter]()
for (i,s) in command.map(String.init).enumerated() {
let delimiter = ChunkDelimiter.parse(s)
if delimiter.isOpen {
// if we are opening a new chunk, just add it to our open pile
openChunks.append(delimiter)
} else {
// if it's closing, see if it matches the last open delimiter
guard let last = openChunks.last else {
// print("\(s) @ \(i) : No open chunks! ")
return ParseResult(isOpen: false, isCorrupt: true, corruptIndex: i, corruptValue: s, openChunks: openChunks)
}
if delimiter.sameType(as: last) {
_ = openChunks.removeLast()
} else {
// print("\(s) @ \(i) : Does not match open chunk! ")
return ParseResult(isOpen: false, isCorrupt: true, corruptIndex: i, corruptValue: s, openChunks: openChunks)
}
}
}
return ParseResult(isOpen: !openChunks.isEmpty, isCorrupt: false, corruptIndex: nil, corruptValue: nil, openChunks: openChunks)
}
func closingString() -> String {
parseResult.openChunks.reversed().map { delimiter -> String in
switch delimiter {
case .parens:
return ")"
case .squareBrackets:
return "]"
case .curlyBraces:
return "}"
case .angles:
return ">"
default:
return "*"
}
}.joined()
}
}
|
//
// TermList.swift
// FlashCards
//
// Created by Pedro Sousa on 20/10/20.
//
import UIKit
class TermList: UIView {
public let tableView: UITableView = {
let tableview = UITableView()
return tableview
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupLayout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupLayout() {
self.backgroundColor = .white
self.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor).isActive = true
tableView.leftAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leftAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: self.safeAreaLayoutGuide.rightAnchor).isActive = true
}
}
|
//
// DataManager.swift
// TODO
//
// Created by Marcin Jucha on 27.06.2017.
// Copyright © 2017 Marcin Jucha. All rights reserved.
//
import Foundation
import CoreData
class TaskDataManager: CoreDataManager<Task> {
private var request: NSFetchRequest<Task> {
let req: NSFetchRequest<Task> = Task.fetchRequest()
let sortByDate = NSSortDescriptor(key: "createdDate", ascending: false)
let sortByCompleted = NSSortDescriptor(key: "completed", ascending: true)
req.sortDescriptors = [sortByDate, sortByCompleted]
if isPriority {
req.predicate = NSPredicate(format: "favorite == \(isPriority)")
}
return req
}
override func getAll() -> [Task] {
let req = request
req.predicate = nil
return fetchData(req)
}
override func getList() -> [Task] {
return fetchData(request)
}
override init() {
super.init()
isPriority = true
}
}
let taskManager: CoreDataManager = TaskDataManager()
|
// swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "CryptoCore",
platforms: [
.macOS(.v10_15),
.iOS(.v13),
],
products: [
.library(name: "CryptoCore", type: .static, targets: ["CryptoCore"]),
],
dependencies: [
// 🔑 Hashing (BCrypt, SHA2, HMAC), encryption (AES), public-key (RSA), and random data generation.
.package(url: "https://github.com/apple/swift-crypto.git", .branch("main")),
],
targets: [
// 👀 C helpers
.target(name: "keccaktiny", cSettings: [
.define("memset_s(W,WL,V,OL)=memset(W,V,OL)", .when(platforms: [.linux], configuration: nil))
]),
.target(name: "secp256k1", cSettings: [
.define("ENABLE_MODULE_ECDH"),
.define("ENABLE_MODULE_RECOVERY"),
]),
// 🎯 Target -- Base58
.target(name: "Base58", dependencies: [
.product(name: "Crypto", package: "swift-crypto"),
]),
// 🎯 Target -- CryptoCore
.target(name: "CryptoCore", dependencies: [
"keccaktiny",
"secp256k1",
"Base58",
]),
// Test -- CryptoCore
.testTarget(name: "CryptoCoreTests", dependencies: [
"CryptoCore"
]),
],
swiftLanguageVersions : [.v5]
)
|
//
// HealthStore.swift
// Just Do It
//
// Created by Pavel Shadrin on 31/05/2017.
// Copyright © 2017 Pavel Shadrin. All rights reserved.
//
import Foundation
import HealthKit
extension HKHealthStore {
static let shared = HKHealthStore()
static let allTypes = Set([HKObjectType.workoutType(),
HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned)!,
HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.basalEnergyBurned)!,
HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!])
class func requestAccessToHealthKit() {
self.shared.requestAuthorization(toShare: HKHealthStore.allTypes, read: HKHealthStore.allTypes) { (success, error) in
// success == true – user responded (but NO information if granted or not)
// success == false – user dismissed
if !success, let e = error {
// TODO: error handling, call back
print(e)
}
}
}
}
|
//
// Content.swift
// FudanNews
//
// Created by Lotus on 2017/1/23.
// Copyright © 2017年 Fudan University. All rights reserved.
//
import UIKit
import AlamofireImage
import MJRefresh
class ActivityContent: UITableViewController {
var now = 0
var tag = ""
var dataArray = [Activity]()
var dataArrayAll = [Activity]()
var type = 0
var str = ""
var selectType = 0
var rootView: ActivityViewController!
var noResultLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView!.delegate = self
self.tableView!.dataSource = self
self.tableView!.separatorStyle = .none
self.tableView!.register(UINib(nibName:"ActivityCell",bundle:nil), forCellReuseIdentifier: "ActivityCell")
self.tableView.estimatedRowHeight = 500
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.backgroundColor = UIColor(red:248/255,green:248/255,blue:248/255,alpha:1)
let header:MJRefreshGifHeader = MJRefreshGifHeader(refreshingTarget: self,refreshingAction:#selector(self.headerRefresh))
self.tableView!.mj_header = header
self.tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self,refreshingAction:#selector(self.headerRefresh))
self.tableView.mj_footer = MJRefreshBackFooter(refreshingTarget: self, refreshingAction: #selector(self.footerRefresh))
}
func footerRefresh() {
refresh()
}
func headerRefresh() {
dataArrayAll.removeAll()
now = 0
refresh()
}
func refresh(){
if type == 1 {
if noResultLabel != nil {
noResultLabel.removeFromSuperview()
noResultLabel = nil
}
NetworkManager.searchActivity(withKeyword: str, startedFrom: now, withLimit: 15) { activityList in
if let activityList = activityList, activityList.count > 0 {
for activity in activityList {
self.dataArrayAll.append(activity)
self.now = activity.id
}
self.dataArray = self.dataArrayAll
self.tableView.mj_header.endRefreshing()
self.tableView.mj_footer.endRefreshing()
self.tableView.reloadData()
}
else {
self.tableView.mj_header.endRefreshing()
self.tableView.mj_footer.endRefreshing()
if self.tableView.numberOfRows(inSection: 0) == 0 {
self.noResultLabel = UILabel()
self.noResultLabel.text = "无结果"
self.noResultLabel.textColor = .gray
self.noResultLabel.sizeToFit()
self.noResultLabel.center = CGPoint(x: self.view.center.x, y: self.view.center.y - 49)
self.view.addSubview(self.noResultLabel)
}
}
}
}
else {
NetworkManager.getActivityList(forModule: tag, startedFrom: now, withLimit: 15) { activityList in
if let activityList = activityList {
for activity in activityList {
self.dataArrayAll.append(activity)
self.now = activity.id
}
self.dataArray = self.dataArrayAll
self.tableView.mj_header.endRefreshing()
self.tableView.mj_footer.endRefreshing()
self.tableView.reloadData()
}
else {
self.tableView.mj_header.endRefreshing()
self.tableView.mj_footer.endRefreshing()
}
}
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ActivityCell") as! ActivityCell
cell.title.text = dataArray[indexPath.row].title
cell.introduction.text = dataArray[indexPath.row].summary
cell.time.text = "时间:\(dataArray[indexPath.row].displayDurTime)\n地点:\(dataArray[indexPath.row].address)"
cell.extolNum.text = String(dataArray[indexPath.row].raiseCount)
cell.commentNum.text = String(dataArray[indexPath.row].commentCount)
cell.sponsor.text = dataArray[indexPath.row].sponsor
cell.stateLabel.text = dataArray[indexPath.row].state.displayName
if (cell.stateLabel.text == "报名中") {cell.stateLabel.backgroundColor = UIColor(red:253/255,green:108/255,blue:60/255,alpha:1)}
else if (cell.stateLabel.text == "进行中") {cell.stateLabel.backgroundColor = UIColor(red:253/255,green:70/255,blue:72/255,alpha:1)}
else {cell.stateLabel.backgroundColor = UIColor(red: 102/255, green: 102/255, blue:102/255, alpha: 1)}
cell.introduction.lineBreakMode = NSLineBreakMode.byWordWrapping
cell.introduction.numberOfLines = 0
cell.title.lineBreakMode = NSLineBreakMode.byWordWrapping
cell.title.numberOfLines = 0
cell.time.lineBreakMode = NSLineBreakMode.byWordWrapping
cell.time.numberOfLines = 0
cell.logo.af_setImage(withURL: dataArray[indexPath.row].sponsorAvatar!, placeholderImage: #imageLiteral(resourceName: "default_avatar"))
cell.topicImage.af_setImage(withURL: dataArray[indexPath.row].coverImg, placeholderImage: #imageLiteral(resourceName: "default_news_img"))
cell.selectionStyle = .none
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
rootView.performSegue(withIdentifier: "ShowDetail", sender: dataArray[indexPath.row].id)
}
}
|
//
// TableViewController.swift
// DemoAPISimple
//
// Created by Hoàng Anh on 6/24/19.
// Copyright © 2019 Hoàng Anh. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
var dataCategory = [RingTone]()
override func viewDidLoad() {
super.viewDidLoad()
setDataFromAPI()
}
func setDataFromAPI() {
DataService.sharedInstance.getCategoryMusic { data in
self.dataCategory = data
print(self.dataCategory.count)
self.tableView.reloadData()
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataCategory.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomTableViewCell
cell.idLabel.text = String(dataCategory[indexPath.row].id)
cell.artistLabel.text = dataCategory[indexPath.row].artist
cell.genreLabel.text = dataCategory[indexPath.row].genre
cell.durationLabel.text = String(dataCategory[indexPath.row].duration)
cell.titleLabel.text = dataCategory[indexPath.row].title
return cell
}
}
|
//
// JiraNetworkModel.swift
//
// Copyright © 2020 Steamclock Software.
//
// 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 Alamofire
import Foundation
import Netable
import SwiftyUserDefaults
import Valet
struct JiraAuthInfo {
let user: String
let domain: String
}
class JiraNetworkModel: SourceNetworkModel {
private var api: JiraAPI?
func authenticateUser(token: String, jiraAuthInfo: JiraAuthInfo? = nil, onSuccess: @escaping (String, String?) -> Void, onFailure: @escaping (NetableError) -> Void) {
guard let jiraInfo = jiraAuthInfo else {
onFailure(NetableError.noData)
return
}
if api == nil { initApi(token: token, info: jiraInfo) }
api!.request(JiraAPI.AuthRequest()) { result in
switch result {
case .success(let user):
// don't need to check for permissions like on GitLab, JIRA doesn't care
onSuccess(user.username, jiraInfo.domain)
case .failure(let error):
LogManager.shared.log("JIRA auth error: \(error)")
onFailure(error)
}
}
}
func testToken(token: String, username: String, onSuccess: @escaping () -> Void, onFailure: @escaping (NetableError) -> Void) {
onSuccess()
}
func getWatchedRepos(token: Token, onSuccess: @escaping ([Repository]) -> Void, onFailure: @escaping (NetableError) -> Void) {
// Not sure JIRA has the concept of repos like we want. Will revisit when we add JIRA support back.
onSuccess([])
}
func getTickets(token: Token, onSuccess: @escaping ([Repository: [Ticket]]) -> Void, onFailure: @escaping (NetableError) -> Void) {
guard let tokenString = try? Valet.shared.string(forKey: token.key),
let domain = token.domain else {
onFailure(NetableError.noData)
return
}
let auth = JiraAuthInfo(user: token.username, domain: domain)
if api == nil { initApi(token: tokenString, info: auth) }
api!.request(JiraAPI.GetIssues()) { result in
switch result {
case .success(let response):
var newTickets = [Repository: [Ticket]]()
var ignoredStatuses = Defaults[.ignoredJIRAStatuses]
if Defaults[.ignoreJIRADone] { ignoredStatuses.append("done") }
for issue in response.issues {
// Ignore tickets with banned statuses
guard !ignoredStatuses.contains(issue.fields.status.name.uppercased()) else {
continue
}
newTickets.insert(ticket: issue.toTicket(domain: domain), forKey: issue.fields.project.toRepo(domain: domain))
}
onSuccess(newTickets)
case .failure(let error):
onFailure(error)
}
}
}
// MARK: Helper Functions
internal func initApi(token: String, info: JiraAuthInfo) {
api = JiraAPI(domain: info.domain)
let authEncodedString = Data("\(info.user):\(token)".utf8).base64EncodedString()
api?.headers["Authorization"] = "Basic \(authEncodedString)"
}
}
|
//
// GoogleVC.swift
// login_example
//
// Created by ahmedxiio on 7/26/18.
// Copyright © 2018 ahmedxiio. All rights reserved.
//
//655850931174-k9cd5otbep2jp8kaq25ruesg89kqlt8c.apps.googleusercontent.com
import UIKit
import GoogleSignIn
class DetailVC: UIViewController {
var type: String?
@IBOutlet weak var userInfo: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
userInfo.text = type!
}
@IBAction func didTapSignOut(_ sender: AnyObject) {
signOut()
}
//signOut
func signOut() {
let FirstStep = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "FirstStep") as! FirstStep
present(FirstStep, animated: true) {
GIDSignIn.sharedInstance().signOut()
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.