text stringlengths 8 1.32M |
|---|
//
// TableViewController.swift
// Web(json)App(Lesson10)
//
// Created by iD on 15.04.2020.
// Copyright © 2020 DmitrySedov. All rights reserved.
//
/*
import UIKit
class MainTableViewController: UITableViewController {
// MARK: - Массивы с данными наполняемые из json
var artistList: [Artist] = []
private var filteredArtistList = [Artist]()
// MARK: - Свойства search
private let searchController = UISearchController(searchResultsController: nil)
private var searchArtistList = [SearchResult]()
private var searchBarIsEmpty: Bool {
guard let text = searchController.searchBar.text else { return false }
return text.isEmpty
}
private var isFiltering: Bool {
return searchController.isActive && !searchBarIsEmpty
}
override func viewDidLoad() {
super.viewDidLoad()
setupSearchController()
//заполняем таблицу артистами
NetworkManager.fetchCurrentCharts(apiMethod: getTopArtist, completionHandler: { currentCharts in
guard let temp = currentCharts.artists?.artist else { return }
self.artistList = temp
DispatchQueue.main.async {
self.tableView.reloadData()
}
})
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isFiltering {
return filteredArtistList.count
}
return artistList.count - 40
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
var artist: Artist
if isFiltering {
artist = filteredArtistList[indexPath.row]
} else {
artist = artistList[indexPath.row]
}
cell.textLabel?.text = artist.name
return cell
}
// програмный переход
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var name = ""
if filteredArtistList.count == 0 {
name = artistList[indexPath.row].name ?? ""
} else {
name = filteredArtistList[indexPath.row].name ?? ""
}
self.performSegue(withIdentifier: "123", sender: name)
}
// Отправляем имя на второй экран, чтобы по нему поулчить биографию артиста
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "123" {
let infoVC = segue.destination as! ArtistInfoViewController
infoVC.artistName = sender as? String
}
}
}
// MARK: - UISearchResultsUpdating Delegate
extension MainTableViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
filterContentForSearchText(searchController.searchBar.text!)
}
private func filterContentForSearchText(_ searchText: String) {
filteredArtistList = artistList.filter({ (artistList: Artist) -> Bool in
return (artistList.name?.lowercased().contains(searchText.lowercased()) ?? false)
})
if filteredArtistList.count == 0 {
NetworkManager.fetchSearchArtist(apiMethod: artistSearch, artistName: searchText) { SearchResult in
guard let searchResult = SearchResult.results?.artistmatches?.artist else { return }
self.filteredArtistList += searchResult
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
tableView.reloadData()
}
private func setupSearchController() {
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search"
navigationItem.searchController = searchController
definesPresentationContext = true
}
}
*/
|
//
// DasBoardTableCell.swift
// CureadviserApp
//
// Created by BekGround-2 on 20/03/17.
// Copyright © 2017 BekGround-2. All rights reserved.
//
import UIKit
class DasBoardTableCell: UITableViewCell {
@IBOutlet var lblDetail: UILabel!
@IBOutlet var lblTitle: UILabel!
@IBOutlet var img: UIImageView!
@IBOutlet var cellView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
cellView.layer.cornerRadius = 5
cellView.layer.shadowColor = UIColor.darkGray.cgColor
cellView.layer.shadowOffset = CGSize(width: 0, height: 1.0)
cellView.layer.shadowOpacity = 0.5
cellView.layer.shadowRadius = 2.0
img.layer.cornerRadius = 5
img.clipsToBounds = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// CourseViewModel.swift
// AluDash
//
// Created by Rafael Escaleira on 04/07/21.
//
import Foundation
import UIKit
public class CourseViewModel {
var bind: () -> () = {}
private (set) var course: Course? {
didSet { self.bind() }
}
init(slug: String) {
self.load(slug: slug) { course in
if let course = course { self.course = course }
}
}
func reload(slug: String) {
self.load(slug: slug) { course in
if let course = course { self.course = course }
}
}
func load(slug: String, result: @escaping (Course?) -> ()) {
if let url = URL(string: Course.url + slug) {
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
let decodedData = try? JSONDecoder().decode(Course.self, from: data)
result(decodedData)
}
}.resume()
}
}
}
|
//
// RosterTableViewController.swift
// LoLMessenger
//
// Created by Young Rok Kim on 2015. 9. 26..
// Copyright © 2015년 rokoroku. All rights reserved.
//
import UIKit
import STPopup
class RosterTableViewController : UIViewController {
@IBOutlet weak var tableView: YUTableView!
@IBOutlet weak var addButton: UIBarButtonItem!
var closeOtherNodes = false
var insertRowAnimation: UITableViewRowAnimation = .Fade
var deleteRowAnimation: UITableViewRowAnimation = .Fade
var searchController: UISearchController?
var isSearching: Bool {
if searchController?.active ?? false {
return !(searchController?.searchBar.text?.isEmpty ?? true)
}
return false
}
var allNodes = [YUTableViewNode]()
var filteredNodes = [YUTableViewNode]()
var activeNodes: [YUTableViewNode] {
if isSearching {
return filteredNodes
} else {
return allNodes
}
}
var groupDictionary : [String:GroupNode]!
var showOffline = true
var separateOfflineGroup = true
override func viewDidLoad() {
super.viewDidLoad()
setTableProperties()
setSearchController()
navigationController?.delegate = self
navigationController?.hidesNavigationBarHairline = true
let editButton = self.editButtonItem()
editButton.title = Localized("Edit")
editButton.action = Selector("editAction:")
navigationItem.leftBarButtonItem = editButton
}
func updateLocale() {
navigationItem.title = Localized("Friends")
if tabBarItem != nil { tabBarItem.title = Localized("Friends") }
}
func setSearchController() {
//definesPresentationContext = true
self.searchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.sizeToFit()
controller.delegate = self
self.tableView.tableHeaderView = controller.searchBar
return controller
})()
self.tableView.reloadData()
}
func setTableProperties() {
tableView.expandAllNodeAtFirstTime = true
tableView.allowOnlyOneActiveNodeInSameLevel = closeOtherNodes
tableView.insertRowAnimation = insertRowAnimation
tableView.deleteRowAnimation = deleteRowAnimation
tableView.setDelegate(self)
tableView.backgroundView = UIView()
tableView.backgroundView?.backgroundColor = Theme.PrimaryColor
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
var insets : UIEdgeInsets
if let tabController = tabBarController as? MainTabBarController, let adView = tabController.getAdView() {
insets = UIEdgeInsetsMake(self.topLayoutGuide.length, 0, self.bottomLayoutGuide.length + adView.frame.height, 0)
} else {
insets = UIEdgeInsetsMake(self.topLayoutGuide.length, 0, self.bottomLayoutGuide.length, 0)
}
self.tableView!.contentInset = insets;
self.tableView!.scrollIndicatorInsets = insets;
}
override func viewWillAppear(animated: Bool) {
// Called when the view is about to made visible.
updateLocale()
reloadRosterNodes()
XMPPService.sharedInstance.roster()?.addDelegate(self)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateLocale", name: LCLLanguageChangeNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
if editing {
setEditing(false, animated: animated)
}
searchController?.active = false
}
override func viewDidDisappear(animated: Bool) {
if !(UIApplication.topViewController() is STPopupContainerViewController) {
XMPPService.sharedInstance.roster()?.removeDelegate(self)
NSNotificationCenter.defaultCenter().removeObserver(self, name: LCLLanguageChangeNotification, object: nil)
}
}
@IBAction func addAction(sender: AnyObject) {
DialogUtils.input(
Localized("Add as Friend"),
message: Localized("Please enter summoner name you want to add"),
placeholder: Localized("Summoner Name")) {
if let name = $0 {
RiotACS.getSummonerByName(summonerName: name, region: XMPPService.sharedInstance.region!) {
if let summoner = $0 {
DialogUtils.alert(
Localized("Add as Friend"),
message: Localized("Do you want to send a buddy request to %1$@?", args: summoner.username),
handler: { _ in
XMPPService.sharedInstance.roster()?.addRoster(summoner)
DialogUtils.alert(Localized("Add as Friend"), message: Localized("Request Sent!"))
})
} else {
DialogUtils.alert(
Localized("Error"),
message: Localized("Summoner named %1$@ was not found", args: name))
}
}
}
}
}
@IBAction func editAction(sender: AnyObject) {
if (editing) {
setEditing(false, animated: true)
self.editButtonItem().title = Localized("Edit")
} else {
setEditing(true, animated: true)
self.editButtonItem().title = Localized("Done")
}
}
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
tableView.setEditing(editing, animated: animated)
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the cell that generated the segue.
var roster: LeagueRoster!
if let param = sender as? LeagueRoster {
roster = param
} else if let cell = sender as? RosterTableChildCell, let param = cell.roster {
roster = param
}
if roster != nil {
if let chatViewController = segue.destinationViewController as? ChatViewController,
let chat = XMPPService.sharedInstance.chat()?.getLeagueChatEntryByJID(roster.jid()) {
chatViewController.setInitialChatData(chat)
}
else if let summonerViewController = segue.destinationViewController as? SummonerDialogViewController {
summonerViewController.roster = roster
if segue.identifier == "SummonerModalPreview" {
summonerViewController.hidesBottomButtons = true
} else if segue.identifier == "SummonerModalCommit" {
if let popupSegue = segue as? PopupSegue {
popupSegue.shouldPerform = false
Async.main(after: 0.1) {
self.performSegueWithIdentifier("EnterChat", sender: sender)
}
}
}
}
}
}
}
extension RosterTableViewController : UINavigationControllerDelegate {
func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
if viewController == self.tabBarController {
reloadRosterNodes()
}
}
}
extension RosterTableViewController {
func reloadRosterNodes() {
groupDictionary = [String:GroupNode]()
let offlineGroup = GroupNode(name: Constants.XMPP.OfflineGroup)
let rosterService = XMPPService.sharedInstance.roster()
if let rosterList = rosterService?.getRosterList() {
for roster in rosterList {
let rosterNode = RosterNode(roster: roster)
var groupNode: GroupNode = getGroupNode(roster.group)
groupNode.numOfTotalRoster++
if separateOfflineGroup && !roster.available {
groupNode = offlineGroup
}
groupNode.add(rosterNode)
}
}
var result = Array(groupDictionary.values.sort { $0.name < $1.name })
result.append(offlineGroup)
allNodes = result
tableView.setNodes(activeNodes)
}
func getGroupNode(name: String) -> GroupNode {
var groupName = name
if name == Constants.XMPP.DefaultGroup {
groupName = Constants.XMPP.GeneralGroup
}
if let groupNode = groupDictionary[groupName] {
return groupNode
} else {
let groupNode = GroupNode(name: groupName)
groupDictionary[groupName] = groupNode
return groupNode
}
}
}
extension RosterTableViewController: YUTableViewDelegate {
func setContentsOfCell(cell: UITableViewCell, node: YUTableViewNode) {
cell.selectionStyle = .None
if let rosterNode = node as? RosterNode, let rosterCell = cell as? RosterTableChildCell {
rosterCell.setData(rosterNode.roster)
} else if let groupNode = node as? GroupNode, let groupCell = cell as? RosterTableGroupCell {
groupCell.setData(groupNode)
}
}
func heightForNode(node: YUTableViewNode) -> CGFloat? {
if node.cellIdentifier == "GroupCell" {
return 40.0;
}
return 58.0;
}
func didSelectNode(node: YUTableViewNode, indexPath: NSIndexPath) {
if let _ = node as? GroupNode, let cell = tableView.cellForRowAtIndexPath(indexPath) as? RosterTableGroupCell {
cell.indicator.rotate180Degrees()
}
}
func didMoveNode(node: YUTableViewNode, fromGroup: YUTableViewNode, toGroup: YUTableViewNode) {
if let group = toGroup as? GroupNode, let groupName = group.data as? String {
if groupName == Constants.XMPP.OfflineGroup {
reloadRosterNodes()
} else {
}
}
}
func didEditNode(node: YUTableViewNode, indexPath: NSIndexPath, commitEditingStyle: UITableViewCellEditingStyle) {
if let child = node as? RosterNode, roster = child.data as? LeagueRoster {
if commitEditingStyle == .Delete {
DialogUtils.alert(Localized("Remove Friend"),
message: Localized("Are you sure you want to remove %1$@ from your friend list?", args: roster.username),
handler: { _ in
XMPPService.sharedInstance.roster()?.removeRoster(roster)
self.reloadRosterNodes()
})
}
}
}
}
extension RosterTableViewController: RosterDelegate {
func didReceiveRosterUpdate(sender: RosterService, from: LeagueRoster) {
if !editing {
reloadRosterNodes()
}
}
func didReceiveFriendSubscription(sender: RosterService, from: LeagueRoster) {
}
func didReceiveFriendSubscriptionDenial(sender: RosterService, from: LeagueRoster) {
}
}
extension RosterTableViewController: UISearchResultsUpdating, UISearchControllerDelegate {
func didPresentSearchController(searchController: UISearchController) {
if searchController.searchBar.superview?.isKindOfClass(UITableView) == false {
//searchController.searchBar.removeFromSuperview()
self.tableView.addSubview(searchController.searchBar)
}
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
filteredNodes.removeAll(keepCapacity: false)
for groupNode in allNodes {
if groupNode.childNodes != nil {
let filteredChildNodes = groupNode.childNodes.filter {
if let roster = $0.data as? LeagueRoster,
let keyword = searchController.searchBar.text {
return roster.username.stringByReplacingOccurrencesOfString(" ", withString: "").localizedCaseInsensitiveContainsString(keyword)
}
return false
}
if !filteredChildNodes.isEmpty {
let filteredGroupNode = GroupNode(name: groupNode.data as! String)
filteredGroupNode.childNodes = filteredChildNodes
filteredNodes.append(filteredGroupNode)
}
}
}
tableView.setNodes(activeNodes)
}
}
class GroupNode : YUTableViewNode {
init(name: String) {
super.init(data: name, nodeId: name.hashValue, cellIdentifier: "GroupCell")
self.isEditable = false
}
var numOfTotalRoster = 0
func add(rosterNode: RosterNode) {
if childNodes == nil {
childNodes = [rosterNode] as [RosterNode]
} else {
childNodes.append(rosterNode)
}
}
var name: String {
get {
return data as! String;
}
set {
data = name;
}
}
}
class RosterNode : YUTableViewNode {
init(roster: LeagueRoster) {
super.init(data: roster, nodeId: roster.getNumericUserId(), cellIdentifier: "RosterCell")
self.isEditable = true
}
var roster: LeagueRoster {
get {
return data as! LeagueRoster
}
set {
data = roster
}
}
}
|
//
// NewTasksVC.swift
// Task Manager - Core Data
//
// Created by Nadezda Panchenko on 16/03/16.
// Copyright © 2016 Nadezda Panchenko. All rights reserved.
//
import UIKit
class NewTasksVC: UIViewController {
var indicator = UIActivityIndicatorView()
@IBOutlet weak var newTaskLabel: UITextField!
@IBAction func newTask(sender: AnyObject) {
if newTaskLabel.text != "" {
tasksArray.append(newTaskLabel.text!)
self.newTaskLabel.resignFirstResponder()
self.performSegueWithIdentifier("addedNewTask", sender: self)
} else {
showAlert("Error", message: "Please enter your activity")
self.presentationController
}
}
func showAlert(title: String, message: String) {
if #available(iOS 8.0, *) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
self.indicator.stopAnimating()
}) )
self.presentViewController(alert, animated: true, completion: nil)
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.newTaskLabel.resignFirstResponder()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// Enums.swift
// codeRed
//
// Created by Vik Denic on 9/20/14.
// Copyright (c) 2014 Mobile Makers. All rights reserved.
//
import Foundation
enum ColliderType: UInt32 {
case Spaceship = 1
case Bug = 2
case GoodChallenge = 4
case ProTip = 8
} |
//
// comboBoxButton.swift
// INSSAFI
//
// Created by Pro Retina on 7/21/18.
// Copyright © 2018 Novacomp. All rights reserved.
//
import UIKit
@IBDesignable
class comboBoxButton: UIButton {
var borderWidth = 1.0
var boderColor = UIColor(red: 0/255, green: 113/255, blue: 184/255, alpha: 1).cgColor
@IBInspectable
var titleText: String? {
didSet {
self.setTitle(titleText, for: .normal)
self.setTitleColor(UIColor(red: 0/255, green: 113/255, blue: 184/255, alpha: 1), for: .normal)
}
}
override init(frame: CGRect){
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
//fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
setup()
}
func setup() {
self.clipsToBounds = true
//self.layer.cornerRadius = self.frame.size.width / 1.0
self.layer.borderColor = boderColor
self.layer.borderWidth = CGFloat(borderWidth)
//self.setImage(UIImage(named: "combobox_arrow"), for: .normal)
self.backgroundColor = UIColor.white
imageEdgeInsets = UIEdgeInsets(top: 5, left: (bounds.width - 20), bottom: 5, right: 5)
titleEdgeInsets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0)
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
|
//
// HomeViewModel.swift
// MVVMFramework
//
// Created by lisilong on 2018/12/5.
// Copyright © 2018 lisilong. All rights reserved.
//
import Foundation
class HomeViewModel {
/// 获取首页数据
///
/// - Parameter completion: 数据回调
func loadHomeDataSource(completion: (_ result: RequestResult, _ models: [BaseSectionModel], _ msg: String) -> ()) {
HomeViewModel.loadHomeDataSource { (result, models, msg) in
var sections = [BaseSectionModel]()
switch result {
case .successNotEmpty:
for model in models {
if model.cellIdentifier == HomeCellIDType.oneCellID.rawValue {
let section = HomeViewModel.createOneSection(model)
sections.append(section)
} else if model.cellIdentifier == HomeCellIDType.twoCellID.rawValue {
let section = HomeViewModel.createOneSection(model)
sections.append(section)
} else if model.cellIdentifier == HomeCellIDType.threeCellID.rawValue {
let section = HomeViewModel.createOneSection(model)
sections.append(section)
}
}
case .successEmpty, .networkFail, .serviceFail:
break
}
completion(result, sections, msg)
}
}
private static func createOneSection(_ model: BaseModel) -> BaseSectionModel {
return BaseSectionModel(cellType: model.cellIdentifier,
headerTitle: "",
footerTitle: "",
headerHeight: 8.0,
footerHeight: 0.001,
cellHeight: 0.0,
showCellCount: 1,
items: [model])
}
private static func createTwoSection(_ model: BaseModel) -> BaseSectionModel {
return BaseSectionModel(cellType: model.cellIdentifier,
headerTitle: "",
footerTitle: "",
headerHeight: 8.0,
footerHeight: 0.001,
cellHeight: 0.0,
showCellCount: 1,
items: [model])
}
private static func createThreeSection(_ model: BaseModel) -> BaseSectionModel {
return BaseSectionModel(cellType: model.cellIdentifier,
headerTitle: "",
footerTitle: "",
headerHeight: 8.0,
footerHeight: 0.001,
cellHeight: 0.0,
showCellCount: 1,
items: [model])
}
}
extension HomeViewModel {
private static func loadHomeDataSource(completion: (_ result: RequestResult, _ models: [BaseModel], _ msg: String) -> ()) {
let oneModel = OneModel()
oneModel.cellIdentifier = HomeCellIDType.oneCellID.rawValue
oneModel.name = "One 值"
oneModel.orderPrice = "100元"
oneModel.orderStatus = 1
let twoModel = TwoModel()
twoModel.cellIdentifier = HomeCellIDType.twoCellID.rawValue
twoModel.name = "two"
twoModel.articleContent = "是科学家"
let threeModel = ThreeModel()
threeModel.cellIdentifier = HomeCellIDType.threeCellID.rawValue
threeModel.userId = "20181212"
threeModel.name = "three"
threeModel.icon = "帅气的头像"
let models: [BaseModel] = [oneModel, twoModel, threeModel, oneModel, twoModel, threeModel, oneModel, twoModel, threeModel]
// let models: [BaseModel] = [twoModel, oneModel, threeModel, twoModel, oneModel, threeModel, twoModel, oneModel, threeModel]
completion(RequestResult.successNotEmpty, models, "")
}
}
|
//
// InvestorDefine.swift
// CoAssetsApps
//
// Created by TruongVO07 on 3/1/16.
// Copyright © 2016 TruongVO07. All rights reserved.
//
import Foundation
import UIKit
// MARK: Define
struct InvestorDefine {
static let ClientId = "AoB2Dn2P93FFYkd2Hcd15opIaC9lIn8ciIPNg44O"
static let ClientSecret = "E5SVOzDAICZ2fUJBx8uWFfb7eUZumkZ9QrSoCsLRgvAAQVEdMQ98TWyZdF07rQLbpX0sbJETOxsXJgoy2pUbpYlEQFnvHguPkFEH92fwHiAR2p6Yhxf1hwdTGkCruBKF"
}
extension InvestorDefine {
static let htmlFrame = "<div style='font-size: 13px; font-family: Avenir-Book;'>%@"
}
// MARK: Func
func m_local_string(key: String) -> String {
return NSLocalizedString(key, tableName: "CoAssetsInvestor", bundle: NSBundle.mainBundle(), value: "", comment: "")
}
extension InvestorDefine {
struct USerdefaultKey {
static let kDeviceTockenExitedOnSever = "kDeviceTockenExitedOnSeverAddBySanyi"
}
}
|
//
// TableViewController.swift
// Joke Bank
//
// Created by Julia Debecka on 04/04/2020.
// Copyright © 2020 Julia Debecka. All rights reserved.
//
import UIKit
class TableViewController: UIViewController {
private let jokeCellIdentifier = "Cell"
var tableView: UITableView!
var wineList: Wine!
override func loadView() {
super.loadView()
wineList = Wine()
self.tableView = UITableView()
self.view.addSubview(tableView)
tableView.dataSource = self
loadData()
setUpSnapKit()
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(MainTableViewCell.self, forCellReuseIdentifier: jokeCellIdentifier)
}
func setUpSnapKit(){
tableView.snp.makeConstraints{ make in
make.top.equalTo(view.safeAreaLayoutGuide)
make.bottom.equalTo(view.safeAreaLayoutGuide)
make.leading.equalTo(view)
make.trailing.equalTo(view)
}
}
fileprivate func loadData(){
WineRepository.getAllWines { [weak self] wines, error in
self?.wineList = wines ?? []
self?.tableView.reloadData()
}
}
}
extension TableViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return wineList.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(70)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: jokeCellIdentifier, for: indexPath) as? MainTableViewCell else { return UITableViewCell() }
cell.wineData = wineList[indexPath.row]
return cell
}
}
|
//
// MappableBaseTypeArray.swift
// grapefruit
//
// Created by moon on 16/3/2.
// Copyright © 2016年 Ledong. All rights reserved.
//
import Foundation
import ObjectMapper
class MappableBaseTypeArray<T> : Mappable {
var value = [T]()
required init?(map: Map) {
if let val = map.currentValue as? [T] {
for item in val {
value.append(item)
}
}
}
func mapping(map: Map) {
// nothing
}
}
|
//
// Progress.swift
// Pods
//
// Created by Aleksandr Vdovichenko on 9/5/17.
//
//
import Foundation
import RealmSwift
open class Section: Object {
@objc open dynamic var сhapter: Int = 0
@objc open dynamic var pages: Int = 0
}
open class ProgressModel: Object {
@objc open dynamic var bookId: String = ""
@objc open dynamic var landscapeWidth: Float = 0.0
@objc open dynamic var landscapeHeight: Float = 0.0
@objc open dynamic var portraitWidth: Float = 0.0
@objc open dynamic var portraitHeight: Float = 0.0
@objc open dynamic var fontName: String = ""
@objc open dynamic var fontSize: String = ""
@objc open dynamic var spaceLine: String = ""
@objc open dynamic var totalPageLanscape: Int = 0
@objc open dynamic var totalPagePortrait: Int = 0
@objc open dynamic var pading: Int = 0
open var sectionsLanscape = List<Section>()
open var sectionsPortrait = List<Section>()
override open class func primaryKey()-> String {
return "bookId"
}
}
|
//
// AdvanceSearchModel.swift
// SLP
//
// Created by Hardik Davda on 6/13/17.
// Copyright © 2017 SLP-World. All rights reserved.
//
import Foundation
class AdvanceSearch{
var strLocation: String?
var strPriceMin: String?
var strPriceMax: String?
var strPropertyType: String?
var strInspectionSchedule: String?
var strBedroomsMin: String?
var strBathroomsMin: String?
var strBedroomsMax: String?
var strBathroomsMax: String?
var strLandSizeMin: String?
var strLandSizeMax: String?
var strSort : String?
var strSuburbs: String?
var strSuburbsId: String?
var strPropertyTypeId: String?
var strGarage: String?
var strKeyword: String?
var boolSurroundingSuburb: Bool?
var boolExcludeUnderOffer: Bool?
init(location: String?,priceMin:String?,priceMax:String?,PropertyType: String?,InspectionSchedule: String?,BedroomsMin: String?,BedroomsMax: String?,BathroomMin: String?,BathroomMax: String?,LandMin: String?,LandMax: String?,Sort: String?,Suburbs: String?,SuburbsId: String?,PropertyTypeId:String?,Garage:String?,Keyword:String?,Surrounding:Bool?,Exclude:Bool?) {
self.strLocation = location
self.strPriceMin = priceMin
self.strPriceMax = priceMax
self.strPropertyType = PropertyType
self.strInspectionSchedule = InspectionSchedule
self.strBedroomsMin = BedroomsMin
self.strBedroomsMax = BedroomsMax
self.strBathroomsMin = BathroomMin
self.strBathroomsMax = BathroomMax
self.strLandSizeMin = LandMin
self.strLandSizeMax = LandMax
self.strSort = Sort
self.strSuburbs = Suburbs
self.strSuburbsId = SuburbsId
self.strPropertyTypeId = PropertyTypeId
self.strGarage = Garage
self.strKeyword = Keyword
self.boolSurroundingSuburb = Surrounding
self.boolExcludeUnderOffer = Exclude
}
// func sendObject(object :AdvanceSearch) -> NSArray {
//// var array
//
// return
// }
}
|
//
// HSViewController.swift
// HealthSource
//
// Created by Tamilarasu on 10/02/18.
// Copyright © 2018 Tamilarasu. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
extension UIViewController:NVActivityIndicatorViewable {
//MARK: Activity indicatore views
func startActivitiyIndicator(message:String) {
startAnimating(CGSize(width:self.view.bounds.size.width,height:50),
message:message)
}
func stopAcitivityIndicator() {
stopAnimating()
}
}
|
import Foundation
@_silgen_name("flc_udpsocket_receive") func c_flc_udpsocket_receive(_ fd:Int32,buff:UnsafePointer<Byte>,len:Int32,ip:UnsafePointer<Int8>,port:UnsafePointer<Int32>) -> Int32
open class UDPClient: Socket {
public override init(address: String, port: Int32) {
super.init(address: address, port: port)
let fd = flc_udpsocket_create(address, port)
if fd > 0 {
self.fd = fd
}
}
open func send(ip: String, packet: String) -> Result {
guard let fd = self.fd else { return .failure(SocketError.connectionClosed) }
let sendsize = flc_udpsocket_sendto(fd, packet, Int32(strlen(packet)), ip, port)
if sendsize == Int32(strlen(packet)) {
return .success
} else {
return .failure(SocketError.unknownError)
}
}
open func broadcast(packet: String) -> Result {
guard let fd = self.fd else { return .failure(SocketError.connectionClosed) }
let sendsize = flc_udpsocket_broadcast(fd, packet, Int32(strlen(packet)), address, port)
if sendsize == Int32(strlen(packet)) {
return .success
} else {
return .failure(SocketError.unknownError)
}
}
open func recv(_ expectlen: Int) -> ([Byte]?, String, Int) {
if let fd = self.fd {
var buff: [Byte] = [Byte](repeating: 0x0,count: expectlen)
var remoteipbuff: [Int8] = [Int8](repeating: 0x0,count: 16)
var remoteport: Int32 = 0
let readLen: Int32 = c_flc_udpsocket_receive(fd, buff: buff, len: Int32(expectlen), ip: &remoteipbuff, port: &remoteport)
let port: Int = Int(remoteport)
var address = ""
if let ip = String(cString: remoteipbuff, encoding: String.Encoding.utf8) {
address = ip
}
if readLen <= 0 {
return (nil, address, port)
}
let rs = buff[0...Int(readLen-1)]
let data: [Byte] = Array(rs)
return (data, address, port)
}
return (nil, "no ip", 0)
}
open func close() {
guard let fd = self.fd else { return }
_ = flc_udpsocket_close(fd)
self.fd = nil
}
}
|
//
// List.swift
// Todo
//
// Created by Heather Shelley on 11/4/14.
// Copyright (c) 2014 Mine. All rights reserved.
//
import Foundation
class List: NSObject, NSCoding {
let id: String
var items: [TodoItem]
override init() {
id = NSUUID().UUIDString
items = []
}
required init?(coder aDecoder: NSCoder) {
id = aDecoder.decodeObjectForKey("id") as! String
items = aDecoder.decodeObjectForKey("items") as! [TodoItem]
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(id, forKey: "id")
aCoder.encodeObject(items, forKey: "items")
}
} |
//
// BTService.swift
// Body Vibes Singleton - Import
//
// Created by Alfred Ly on 1/9/17.
// Copyright © 2017 Wagic. All rights reserved.
//
import Foundation
import CoreBluetooth
import UserNotifications
/* Services & Characteristics UUIDs */
//let BLEServiceUUID = CBUUID(string: "5730cd00-dc2a-11e3-aa37-0002a5d5c51b")
//5730cd00-dc2a-11e3-aa37-0002a5d5c51b
let PositionCharUUID = CBUUID(string: "98d240e0-dc2a-11e3-bbff-0002a5d5c51b")
//writechar: 98d240e0-dc2a-11e3-bbff-0002a5d5c51b
let ReadCharUUID = CBUUID(string: "8e20d3a0-dc2a-11e3-8e3b-0002a5d5c51b")
//read-notify: 8e20d3a0-dc2a-11e3-8e3b-0002a5d5c51b
let BLEServiceChangedStatusNotification = "kBLEServiceChangedStatusNotification"
class BTService: NSObject, CBPeripheralDelegate, UNUserNotificationCenterDelegate {
var peripheral: CBPeripheral?
var positionCharacteristic: CBCharacteristic?
var readCharacteristic: CBCharacteristic?
init(initWithPeripheral peripheral: CBPeripheral) {
super.init()
self.peripheral = peripheral
self.peripheral?.delegate = self
}
deinit {
self.reset()
}
func startDiscoveringServices() {
var BLEServiceUUID = CBUUID(string: DataContainerSingleton.custom.bleServiceUUID!)
self.peripheral?.discoverServices([BLEServiceUUID])
}
func reset() {
if peripheral != nil {
peripheral = nil
NSLog("didDisconnect")
}
// Deallocating therefore send notification
self.sendBTServiceNotificationWithIsBluetoothConnected(false)
}
// Mark: - CBPeripheralDelegate
//discovers services of the device
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
var BLEServiceUUID = CBUUID(string: DataContainerSingleton.custom.bleServiceUUID!)
let uuidsForBTService: [CBUUID] = [PositionCharUUID, ReadCharUUID]
if (peripheral != self.peripheral) {
// Wrong Peripheral
return
}
if (error != nil) {
return
}
if ((peripheral.services == nil) || (peripheral.services!.count == 0)) {
// No Services
return
}
for service in peripheral.services! {
if service.uuid == BLEServiceUUID {
peripheral.discoverCharacteristics(uuidsForBTService, for: service)
}
}
}
//discovers characteristics for the service
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
if (peripheral != self.peripheral) {
// Wrong Peripheral
return
}
if (error != nil) {
return
}
// Start to check service characteristics
//scan the characteristics array
for characteristic in service.characteristics! {
switch(characteristic.uuid){
case PositionCharUUID:
self.positionCharacteristic = (characteristic)
peripheral.setNotifyValue(true, for: self.positionCharacteristic!)
print("received positionCharacteristic")
print(self.positionCharacteristic!)
case ReadCharUUID:
self.readCharacteristic = (characteristic)
peripheral.setNotifyValue(true, for: self.readCharacteristic!)
print("received readCharacteristic")
print(self.readCharacteristic!)
default:
break
}
}
// Send notification that Bluetooth is connected and all required characteristics are discovered
self.sendBTServiceNotificationWithIsBluetoothConnected(true)
}
// Mark: - Private
//function that handles writing packet to BLE
func writePosition(_ position: [UInt8]) {
// See if characteristic has been discovered before writing to it
// NSLog("insideWritePosition")
if let positionCharacteristic = self.positionCharacteristic {
// NSLog("made it inside")
let data = Data(bytes: position)
//the actual api-level ble call
self.peripheral?.writeValue(data, for: positionCharacteristic, type: CBCharacteristicWriteType.withResponse)
// NSLog(data)
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
//retrived a characteristic value
NSLog("Received value from peripheral")
print(characteristic.value!)
guard let data = characteristic.value else { return }
print("value is \(UInt8(data:data))")
if(UInt8(data:data) == 1) {
print("low battery warning")
DataContainerSingleton.custom.batteryStatusChange = true
//Set the content of the notification
let content = UNMutableNotificationContent()
content.title = "Low Power Warning"
content.subtitle = ""
content.body = "Charge your Blades soon"
//Set the trigger of the notification -- here a timer.
let trigger = UNTimeIntervalNotificationTrigger(
timeInterval: 1,
repeats: false)
//Set the request for the notification from the above
let request = UNNotificationRequest(
identifier: "10.second.message",
content: content,
trigger: trigger
)
//Add the notification to the currnet notification center
UNUserNotificationCenter.current().add(
request, withCompletionHandler: nil)
}
}
func readPosition() {
self.peripheral!.readValue(for: self.readCharacteristic!)
}
//The peripheral will trigger this method after every successful write
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
//data is in characteristic.value
NSLog("Sent Packet Successfully: Should NSLog 4 times, for 4 packets")
}
func sendBTServiceNotificationWithIsBluetoothConnected(_ isBluetoothConnected: Bool) {
let connectionDetails = ["isConnected": isBluetoothConnected]
NotificationCenter.default.post(name: Notification.Name(rawValue: BLEServiceChangedStatusNotification), object: self, userInfo: connectionDetails)
}
func peripheralDidUpdateName(_ peripheral: CBPeripheral) {
NSLog("in here finally")
switch(peripheral.state){
case .disconnected:
NSLog("disconnected")
break
case .connecting:
NSLog("connecting")
break
case .connected:
NSLog("connected")
break
case .disconnecting:
NSLog("disconnecting")
break
}
}
}
|
//
// ImageCache.swift
// Amarosa
//
// Created by Andrew Foghel on 7/10/17.
// Copyright © 2017 SeanPerez. All rights reserved.
//
import UIKit
let imageCache = NSCache<AnyObject, AnyObject>()
extension UIImageView{
func loadImageUsingCacheWithUrlString(urlString: String){
//check cache for image first
if let cachedImage = imageCache.object(forKey: urlString as AnyObject) as? UIImage{
self.image = cachedImage
return
}
let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if let err = error {
print("there was an error uploading the image",err.localizedDescription)
return
}
DispatchQueue.main.async {
if let downloadedImage = UIImage(data: data!){
imageCache.setObject(downloadedImage, forKey: urlString as AnyObject)
self.image = downloadedImage
}
}
}.resume()
}
func addText(_ drawText: NSString, atPoint: CGPoint, textColor: UIColor?, textFont: UIFont?) -> UIImage {
// Setup the font specific variables
var _textColor: UIColor
if textColor == nil {
_textColor = UIColor.white
} else {
_textColor = textColor!
}
var _textFont: UIFont
if textFont == nil {
_textFont = UIFont.systemFont(ofSize: 16)
} else {
_textFont = textFont!
}
// Setup the image context using the passed image
UIGraphicsBeginImageContext(CGSize(width: width, height: height))
// Setup the font attributes that will be later used to dictate how the text should be drawn
let textFontAttributes = [
NSFontAttributeName: _textFont,
NSForegroundColorAttributeName: _textColor,
] as [String : Any]
// Put the image into a rectangle as large as the original image
draw(CGRect(x: 0, y: 0, width: width, height: height))
// Create a point within the space that is as bit as the image
let rect = CGRect(x: atPoint.x, y: atPoint.y, width: width, height: height)
// Draw the text into an image
drawText.draw(in: rect, withAttributes: textFontAttributes)
// Create a new image out of the images we have created
let newImage = UIGraphicsGetImageFromCurrentImageContext()
// End the context now that we have the image we need
UIGraphicsEndImageContext()
//Pass the image back up to the caller
return newImage!
}
}
|
//
// ImageStore.swift
// Spearmint
//
// Created by Brian Ishii on 5/21/19.
// Copyright © 2019 Brian Ishii. All rights reserved.
//
import Foundation
import UIKit
class ImageStore {
static let documentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static func saveImage(_ image: UIImage, transactionID: TransactionID) {
do {
if let imageData = image.pngData() {
try imageData.write(to: documentsDirectory.appendingPathComponent(transactionID.id + ".png"))
}
} catch {
print(error)
}
}
static func getImage(transactionID: TransactionID) -> UIImage? {
return UIImage(contentsOfFile: URL(fileURLWithPath: documentsDirectory.absoluteString).appendingPathComponent(transactionID.id + ".png").path)
}
static func deleteImage(_ transactionID: TransactionID) {
do {
try FileManager().removeItem(atPath: URL(fileURLWithPath: documentsDirectory.absoluteString).appendingPathComponent(transactionID.id + ".png").path)
} catch {
print(error)
}
}
}
|
//
import UIKit
extension UISearchBar {
var searchField: UITextField? {
if #available(iOS 13.0, *) {
return searchTextField
} else {
return value(forKey: "searchField") as? UITextField
}
}
}
|
//
// LocationController.swift
// RemindMe
//
// Created by Garrett Votaw on 5/18/18.
// Copyright © 2018 Garrett Votaw. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
class LocationController: UITableViewController, MKLocalSearchCompleterDelegate {
@IBOutlet weak var searchBar: UISearchBar!
var locationRequest: MKLocalSearchRequest?
var region: MKCoordinateRegion?
var locations: [MKMapItem] = []
lazy var manager: LocationManager = {
return LocationManager(locationDelegate: self)
}()
var regionID: String?
var monitoredRegion: CLRegion?
var onArrival: Bool?
override func viewDidLoad() {
super.viewDidLoad()
do {
try manager.requestWhenInUseAuthorization()
try manager.requestAlwaysAuthorization()
manager.requestLocation()
} catch {
print(error)
}
searchBar.delegate = self
tableView.estimatedRowHeight = 73.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return locations.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LocationCell", for: indexPath) as! LocationCell
guard !locations.isEmpty else {return cell}
let placemark = locations[indexPath.row].placemark
guard let city = placemark.locality, let state = placemark.administrativeArea, let address = placemark.thoroughfare, let zip = placemark.postalCode else {return cell}
let formattedLocation = "\(address) \(city), \(state) \(zip)"
cell.titleLabel.text = locations[indexPath.row].name
cell.addressLabel.text = formattedLocation
return cell
}
//MARK: - TEST CASE HERE
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let regionID = regionID else {return}
guard let onArrival = onArrival else {return}
//==========================================================================================
let center = locations[indexPath.row].placemark.coordinate
/*Simply uncomment the below line and add it into the below function as the center parameter. Then upon running the app, select the location button just above the console and choose "TestLocations". This will navigate in and out of the Apple Headquarters geofence and trigger continuous notifications ever 5 seconds or so. You can delete the reminder and it will remove monitoring process*/
//let apple = CLLocationCoordinate2D(latitude: 37.331695, longitude: -122.0322801)
monitorRegionAtLocation(center: center, identifier: regionID, onEntry: onArrival)
//==========================================================================================
navigationController?.popViewController(animated: true)
let previousViewController = navigationController?.viewControllers[1] as! ReminderDetailsController
previousViewController.monitoredRegion = monitoredRegion
}
func monitorRegionAtLocation(center: CLLocationCoordinate2D, identifier: String, onEntry: Bool) {
// Make sure the app is authorized.
if CLLocationManager.authorizationStatus() == .authorizedAlways {
// Make sure region monitoring is supported.
if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
// Register the region.
let region = CLCircularRegion(center: center, radius: 100.0, identifier: identifier)
if onEntry {
region.notifyOnEntry = true
region.notifyOnExit = false
} else {
region.notifyOnExit = true
region.notifyOnEntry = false
}
self.monitoredRegion = region
manager.startMonitoring(region)
}
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
print("taco")
let nextVC = segue.destination as! ReminderDetailsController
nextVC.monitoredRegion = monitoredRegion
}
}
// MARK: - Extensions
extension LocationController: LocationManagerDelegate {
func obtainedCoordinates(_ location: CLLocation) {
let region = MKCoordinateRegionMakeWithDistance(location.coordinate, 30000.0, 30000.0)
self.region = region
print("received coordinate")
}
func failedWithError(_ error: LocationError) {
}
func didChangeAuthorizationStatus(_ status: CLAuthorizationStatus) {
}
}
extension LocationController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
guard let region = region else {return}
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = searchText
request.region = region
locationRequest = request
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
guard let request = locationRequest else {return}
let search = MKLocalSearch(request: request)
search.start { response, error in
if let response = response {
self.locations = response.mapItems
self.tableView.reloadData()
}
if let error = error {
self.locations = []
print("Tacos")
print(error)
}
}
}
}
|
//
// ViewController.swift
// Obligatoriov1
//
// Created by SP07 on 14/4/16.
// Copyright © 2016 SP07. All rights reserved.
//
import UIKit
class ViewControllerCupon: UIViewController {
var cupon: String = ""
override func viewDidLoad() {
super.viewDidLoad()
labelCupon.text = cupon
qrImage.image = generateQRCode()
}
@IBOutlet var labelCupon: UILabel!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet var qrImage: UIImageView!
func generateQRCode()->UIImage? {
let data = cupon.dataUsingEncoding(NSISOLatin1StringEncoding)
if let filter = CIFilter(name: "CIQRCodeGenerator") {
filter.setValue(data, forKey: "inputMessage")
filter.setValue("H", forKey: "inputCorrectionLevel")
let transform = CGAffineTransformMakeScale(10, 10)
if let output = filter.outputImage?.imageByApplyingTransform(transform) {
return UIImage(CIImage: output)
}
}
return nil
}
}
|
//
// StickyHeader_TestView.swift
// CustomWidget_SwiftUIApp
//
// Created by MacBook Pro on 2021/6/1.
//
import SwiftUI
struct StickyHeader_TestView: View {
var colors: [Color] = [.blue, .green, .red, .orange, .pink, .yellow, .purple, .primary]
@State var selection: Int = 0
var body: some View {
///1.
// ScrollView(.vertical, showsIndicators: false) {
// StickyHeader {
// ZStack {
// Color(red: 35/255, green: 45/255, blue: 50/255)
// VStack {
// Text("Joshua Tree")
// .font(.title)
// .fontWeight(.bold)
// .foregroundColor(.white)
// Text("California")
// .font(.title2)
// .fontWeight(.semibold)
// .foregroundColor(.white)
// }
// }
// }
// }
///2.
// ScrollView(.vertical, showsIndicators: false) {
// VStack(alignment: .center, spacing: nil, content: {
// StickyHeader(minHeight: 240) {
// StickyHeader {
// Image("h2")
// .resizable()
// .aspectRatio(contentMode: .fill)
// }
// }
// })
//
// }
///3.
// VStack(content: {
// HStack(alignment: .center, spacing: 30) {
//
// // .toggleStyle(MyToggleStyle())
// ForEach(0..<colors.count) { i in
// colors[i]
// .frame(width: 250, height: 350, alignment: .center)
// .cornerRadius(15)
//
// }
// }.modifier(ScrollingHStackModifier(items: colors.count, itemWidth: 250, itemSpacing: 30))
//
// })
// ZStack {
//// Color.gray.opacity(0.8)
// SideMenu(selected: $selection, options: ["NEWEST", "POPULAR", "SALE"])
// }
Button(action: {
// Do stuff when tapped.
}) {
Text("Learn More")
.fontWeight(.heavy)
.foregroundColor(.white)
}
.frame(width: 220, height: 60)
.background(AnimatedBackgroundGradient())
.cornerRadius(12)
// .edgesIgnoringSafeArea(.vertical)
}
}
struct StickyHeader_TestView_Previews: PreviewProvider {
static var previews: some View {
StickyHeader_TestView()
}
}
struct SideMenu: View {
@Binding var selected: Int
var options: [String]
var body: some View {
GeometryReader { geo in
HStack {
ForEach(options.indices) { i in
Button(action: {
withAnimation {
self.selected = i
}
}, label: {
Text(options[i])
.font(.body)
.fontWeight(.bold)
.padding(.horizontal, 10)
.foregroundColor(self.selected == i ? Color.blue : Color.black.opacity(0.6))
}).buttonStyle(PlainButtonStyle())
if i < options.count - 1 {
Divider()
.frame(width: nil, height: 45, alignment: .center)
.opacity(0.7)
}
}
}
.padding(.top, 10)
.padding(.horizontal, 15)
.background(Color.white)
.cornerRadius(8)
.offset(x: geo.size.height * -0.65, y: -10)
.rotationEffect(Angle(degrees: -90), anchor: .topLeading)
}
}
}
struct AnimatedBackgroundGradient: View {
let colors = [Color.blue, Color.purple, Color.pink, Color.pink, Color.red, Color.purple, Color.blue, Color.purple, Color.red, Color.purple, Color.pink, Color.pink]
@State private var start = UnitPoint(x: 0, y: -2)
@State private var end = UnitPoint(x: 4, y: 0)
var body: some View {
LinearGradient(gradient: Gradient(colors: colors), startPoint: start, endPoint: end)
.animation(Animation.easeInOut(duration: 3).repeatForever())
.onAppear {
self.start = UnitPoint(x: 4, y: 0)
self.end = UnitPoint(x: 0, y: 2)
self.start = UnitPoint(x: -4, y: 20)
self.end = UnitPoint(x: 4, y: 0)
}
}
}
|
//
// Settings.swift
// WearableAirQualityMonitor
//
// Created by Bácsi Sándor on 2017. 12. 30..
// Copyright © 2017. Bacsi Sandor. All rights reserved.
//
import BlueCapKit
import CoreBluetooth
import UIKit
class Settings: UIViewController {
@IBOutlet weak var serviceUUID: UITextField!
@IBOutlet weak var dataCharacteristicUUID: UITextField!
@IBAction func connectButtonTouchUpInside(_ sender: Any) {
view.endEditing(true)
self.setupConnection()
}
@IBAction func settingsControlTouchUpInside(_ sender: Any) {
view.endEditing(true)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
func setupConnection(){
let serviceUUID = CBUUID(string:self.serviceUUID.text!)
var peripheral: Peripheral?
let dataCharacteristicUUID = CBUUID(string:self.dataCharacteristicUUID.text!)
//initialize a central manager with a restore key. The restore key allows to resuse the same central manager in future calls
let manager = CentralManager(options: [CBCentralManagerOptionRestoreIdentifierKey : "CentralMangerKey" as NSString])
//A future stram that notifies us when the state of the central manager changes
let stateChangeFuture = manager.whenStateChanges()
//handle state changes and return a scan future if the bluetooth is powered on.
let scanFuture = stateChangeFuture.flatMap { state -> FutureStream<Peripheral> in
switch state {
case .poweredOn:
DispatchQueue.main.async {
//print("start scanning");
}
//scan for peripherlas that advertise the ec00 service
return manager.startScanning(forServiceUUIDs: [serviceUUID])
case .poweredOff:
throw AppError.poweredOff
case .unauthorized, .unsupported:
throw AppError.invalidState
case .resetting:
throw AppError.resetting
case .unknown:
//generally this state is ignored
throw AppError.unknown
}
}
scanFuture.onFailure { error in
guard let appError = error as? AppError else {
return
}
switch appError {
case .invalidState:
break
case .resetting:
manager.reset()
case .poweredOff:
break
case .unknown:
break
default:
break;
}
}
//We will connect to the first scanned peripheral
let connectionFuture = scanFuture.flatMap { p -> FutureStream<Void> in
//stop the scan as soon as we find the first peripheral
manager.stopScanning()
peripheral = p
guard let peripheral = peripheral else {
throw AppError.unknown
}
DispatchQueue.main.async {
print("Found peripheral \(peripheral.identifier.uuidString). Trying to connect")
}
//connect to the peripheral in order to trigger the connected mode
return peripheral.connect(connectionTimeout: 10, capacity: 5)
}
//we will next discover the "ec00" service in order be able to access its characteristics
let discoveryFuture = connectionFuture.flatMap { _ -> Future<Void> in
guard let peripheral = peripheral else {
throw AppError.unknown
}
return peripheral.discoverServices([serviceUUID])
}.flatMap { _ -> Future<Void> in
guard let discoveredPeripheral = peripheral else {
throw AppError.unknown
}
guard let service = discoveredPeripheral.services(withUUID:serviceUUID)?.first else {
throw AppError.serviceNotFound
}
peripheral = discoveredPeripheral
DispatchQueue.main.async {
print("Discovered service \(service.uuid.uuidString). Trying to discover characteristics")
}
//we have discovered the service, the next step is to discover the "ec0e" characteristic
return service.discoverCharacteristics([dataCharacteristicUUID])
}
let dataFuture = discoveryFuture.flatMap { _ -> Future<Void> in
guard let discoveredPeripheral = peripheral else {
throw AppError.unknown
}
guard let dataCharacteristic = discoveredPeripheral.services(withUUID:serviceUUID)?.first?.characteristics(withUUID:dataCharacteristicUUID)?.first else {
throw AppError.dataCharactertisticNotFound
}
BluetoothHelper.sharedInstance.dataCharacteristic=dataCharacteristic
DispatchQueue.main.async {
print("Discovered characteristic \(dataCharacteristic.uuid.uuidString).")
}
//read the data from the characteristic
//Ask the characteristic to start notifying for value change
return dataCharacteristic.startNotifying()
}
//handle any failure in the previous chain
dataFuture.onFailure { error in
switch error {
case PeripheralError.disconnected:
peripheral?.reconnect()
case AppError.serviceNotFound:
break
case AppError.dataCharactertisticNotFound:
break
default:
break
}
}
}
}
|
//
// SelectViewController.swift
// Project2
//
// Created by Alumno on 20/03/2019.
// Copyright © 2019 eii. All rights reserved.
//
import UIKit
import CoreData
class SelectViewController: UITableViewController, NSFetchedResultsControllerDelegate {
var context: NSManagedObjectContext? = nil
var entitySelected: String = "Customer"
var customerSelected: Customer? = nil
var productSelected: Product? = nil
//para un fetched de tipo genérico
//var cosa: NSFetchedResultsController<NSFetchRequestResult>? = nil
//uiapplication.share.delegate as! appdelegate -> persistentStore.context
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func viewDidAppear(_ animated: Bool) {
if(customerSelected != nil){
let indexPath = lookForCustomer(customer: customerSelected!)
self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: UITableView.ScrollPosition.top)
} else if (productSelected != nil){
let indexPath = lookForProduct(product: productSelected!)
self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: UITableView.ScrollPosition.top)
}
}
func lookForCustomer(customer: Customer) -> IndexPath{
var indexPath = NSIndexPath()
for section in 0..<self.tableView.numberOfSections{
for row in 0..<tableView.numberOfRows(inSection: section) {
let indexPathAux = NSIndexPath(row: row, section: section)
if(customerFetched.object(at: indexPathAux as IndexPath) == customer){
indexPath = indexPathAux
}
}
}
return indexPath as IndexPath
}
func lookForProduct(product: Product) -> IndexPath{
var indexPath = NSIndexPath()
for section in 0..<self.tableView.numberOfSections{
for row in 0..<tableView.numberOfRows(inSection: section) {
let indexPathAux = NSIndexPath(row: row, section: section)
if(productFetched.object(at: indexPathAux as IndexPath) == product){
indexPath = indexPathAux
}
}
}
return indexPath as IndexPath
}
@IBAction func doneBtnTapped(_ sender: UIButton) {
if(entitySelected == "Customer"){
customerSelected = customerFetched.object(at: tableView.indexPathForSelectedRow!)
}else{
productSelected = productFetched.object(at: tableView.indexPathForSelectedRow!)
}
performSegue(withIdentifier: "unwindToOrderDetails", sender: self)
}
//MARK: - Operaciones relacionadas con la delegación de de las consultas
var customerFetched: NSFetchedResultsController<Customer> {
if _customerFetched == nil{
let request: NSFetchRequest<Customer> = Customer.fetchRequest()
//Anotamos cómo queremos que se ordenen los campos de la tabla
let name = NSSortDescriptor(key: "name", ascending: true)
//Se los añadimos a la req en el orden que queramos. Primero se ordenarán por año y luego por nombre.
request.sortDescriptors = [name]
//Le podemos aplicamos a la req un filtro. El %@ es un parámetro que se sustituye por lo que pogamos en el segundo parámentro. Tomaría en cuenta solo los campos de la tabla que cumplan con el formato que le pasamos en el predicado.
//request.predicate = NSPredicate(format: "name = %@", [])
//Este es el encargado de hacer la consulta a la base de datos. Nos da los resultados ya de tal manera que fácil poder tratarlos como una tabla. Es mucho mejor que hacer un request.perform() o parecido que me devolvería un array plano. Fetched y _fetched tienen las mismas características (uno está dentro del otro)
_customerFetched = NSFetchedResultsController(
fetchRequest: request,
managedObjectContext: context!,
sectionNameKeyPath: nil,
cacheName: "cache") as? NSFetchedResultsController<NSFetchRequestResult>
//El delegado de la consulta (encargado de hacer las operaciones cuando las consultas se llevan a cabo) dijimos que era esta propia clase (con el fetchedResultControllerDelegate)
_customerFetched?.delegate = self
do{
//Llevamos a cabo la operación
try _customerFetched?.performFetch()
} catch {
//Hay algún problema en el fetch
}
}
return _customerFetched! as! NSFetchedResultsController<Customer>
}
var productFetched: NSFetchedResultsController<Product> {
if _productFetched == nil{
let request: NSFetchRequest<Product> = Product.fetchRequest()
//Anotamos cómo queremos que se ordenen los campos de la tabla
let name = NSSortDescriptor(key: "name", ascending: true)
//Se los añadimos a la req en el orden que queramos. Primero se ordenarán por año y luego por nombre.
request.sortDescriptors = [name]
//Le podemos aplicamos a la req un filtro. El %@ es un parámetro que se sustituye por lo que pogamos en el segundo parámentro. Tomaría en cuenta solo los campos de la tabla que cumplan con el formato que le pasamos en el predicado.
//request.predicate = NSPredicate(format: "name = %@", [])
//Este es el encargado de hacer la consulta a la base de datos. Nos da los resultados ya de tal manera que fácil poder tratarlos como una tabla. Es mucho mejor que hacer un request.perform() o parecido que me devolvería un array plano. Fetched y _fetched tienen las mismas características (uno está dentro del otro)
_productFetched = NSFetchedResultsController(
fetchRequest: request,
managedObjectContext: context!,
sectionNameKeyPath: nil,
cacheName: "cache") as? NSFetchedResultsController<NSFetchRequestResult>
//El delegado de la consulta (encargado de hacer las operaciones cuando las consultas se llevan a cabo) dijimos que era esta propia clase (con el fetchedResultControllerDelegate)
_productFetched?.delegate = self
do{
//Llevamos a cabo la operación
try _productFetched?.performFetch()
} catch {
//Hay algún problema en el fetch
}
}
return _productFetched! as! NSFetchedResultsController<Product>
}
var _customerFetched: NSFetchedResultsController<NSFetchRequestResult>? = nil
var _productFetched: NSFetchedResultsController<NSFetchRequestResult>? = nil
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.reloadData()
}
func setFetch(entity: String){
if(entity == "Customer"){
entitySelected = "Customer"
} else {
entitySelected = "Product"
}
}
func setCustomer(entity: Customer?){
customerSelected = entity
}
func setProduct(entity: Product?){
productSelected = entity
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
if(entitySelected == "Customer"){
return customerFetched.sections?.count ?? 0
}
else{
return productFetched.sections?.count ?? 0
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if(entitySelected == "Customer"){
return customerFetched.sections?[section].numberOfObjects ?? 0
}
else{
return productFetched.sections?[section].numberOfObjects ?? 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "selectorCell", for: indexPath)
// Configure the cell...
if(entitySelected == "Customer"){
cell.textLabel?.text = customerFetched.object(at: indexPath).name
}
else{
cell.textLabel?.text = productFetched.object(at: indexPath).name
}
return cell
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// BotNaming.swift
// Buildasaur
//
// Created by Honza Dvorsky on 16/05/2015.
// Copyright (c) 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import XcodeServerSDK
import BuildaGitServer
class BotNaming {
class func isBuildaBot(bot: Bot) -> Bool {
return bot.name.hasPrefix(self.prefixForBuildaBot())
}
class func isBuildaBotBelongingToRepoWithName(bot: Bot, repoName: String) -> Bool {
return bot.name.hasPrefix(self.prefixForBuildaBotInRepoWithName(repoName))
}
class func nameForBotWithBranch(branch: Branch, repoName: String) -> String {
return "\(self.prefixForBuildaBotInRepoWithName(repoName)) |-> \(branch.name)"
}
class func nameForBotWithPR(pr: PullRequest, repoName: String) -> String {
return "\(self.prefixForBuildaBotInRepoWithName(repoName)) PR #\(pr.number)"
}
class func prefixForBuildaBotInRepoWithName(repoName: String) -> String {
return "\(self.prefixForBuildaBot()) [\(repoName)]"
}
class func prefixForBuildaBot() -> String {
return "BuildaBot"
}
}
|
//
// ShareViewController.swift
// Offline
//
// Created by Daniel Chen on 12/13/17.
// Copyright © 2017 Daniel Chen. All rights reserved.
//
import UIKit
import Social
import MobileCoreServices
class ShareViewController: SLComposeServiceViewController {
override func viewDidLoad() {
super.viewDidLoad()
print(Site.ArchiveURL.path)
}
override func isContentValid() -> Bool {
// Do validation of contentText and/or NSExtensionContext attachments here
return true
}
override func didSelectPost() {
// This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.
let extensionItem = extensionContext?.inputItems.first as! NSExtensionItem
let itemProvider = extensionItem.attachments?.first as! NSItemProvider
let propertyList = String(kUTTypeFileURL)
if itemProvider.hasItemConformingToTypeIdentifier(propertyList) {
itemProvider.loadItem(forTypeIdentifier: propertyList, options: nil, completionHandler: { (decoder, error) -> Void in
if (error != nil) {
print(error)
return
}
guard let url = decoder as? URL else {
print("decoder isn't a url")
return
}
do {
let data = try Data(contentsOf: url)
let str = String(data: data, encoding: .utf8)
let newSite = Site(name: self.contentText, html: str!)!
NSKeyedUnarchiver.setClass(Site.self, forClassName: "Site")
NSKeyedArchiver.setClassName("Site", for: Site.self)
let defaults = UserDefaults(suiteName: "group.offline")
defaults?.synchronize()
let decoded = defaults?.object(forKey: "sites") as? Data
var sites: [Site] = []
if (decoded != nil) {
sites = NSKeyedUnarchiver.unarchiveObject(with: decoded!) as? [Site] ?? []
}
sites.append(newSite)
let encoded = NSKeyedArchiver.archivedData(withRootObject: sites)
defaults?.set(encoded, forKey: "sites")
defaults?.synchronize()
} catch {
print(error)
}
})
} else {
print("error")
}
// Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context.
self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
}
override func configurationItems() -> [Any]! {
// To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
return []
}
}
|
// Maximize A[P] * A[Q] * A[R] for any triplet (P, Q, R).
import PlaygroundSupport
import XCTest
class Tests: XCTestCase {
func testEmpty() {
var a: [Int] = []
let actual = solution(&a)
let expected = -1
XCTAssertEqual(actual, expected)
}
func testPositives() {
var a = [1,2,3,4,5]
let actual = solution(&a)
let expected = 3 * 4 * 5
XCTAssertEqual(actual, expected)
}
func testNegatives() {
var a = [-1,-2,-3,-4,-5]
let actual = solution(&a)
let expected = (-1) * (-2) * (-3)
XCTAssertEqual(actual, expected)
}
func testGiven() {
var a = [-3, 1, 2, -2, 5, 6]
let actual = solution(&a)
let expected = 60
XCTAssertEqual(actual, expected)
}
}
public struct TestRunner {
public init() { }
public func runTests(testClass:AnyClass) {
let tests = testClass as! XCTestCase.Type
let testSuite = tests.defaultTestSuite
testSuite.run()
let run = testSuite.testRun as! XCTestSuiteRun
print("\nRan \(run.executionCount) tests in \(run.testDuration)s with \(run.totalFailureCount) failures")
}
}
public func solution(_ A : inout [Int]) -> Int {
if A.count < 3{
return -1
}
var currentSingleMax = max(A[0], A[1])
var currentSingleMin = min(A[0], A[1])
var currentCoupleMax = A[0] * A[1]
var currentCoupleMin = A[0] * A[1]
var currentMaxProduct = A[0] * A[1] * A[2]
for i in 2..<A.count {
let value = A[i]
// Product
currentMaxProduct = max(currentCoupleMax * value,
currentCoupleMin * value,
currentMaxProduct
)
// Couple
currentCoupleMax = max(currentSingleMax * value,
currentSingleMin * value,
currentCoupleMax
)
currentCoupleMin = min(currentSingleMin * value,
currentSingleMax * value,
currentCoupleMin
)
// Single
currentSingleMax = max(value, currentSingleMax)
currentSingleMin = min(value, currentSingleMin)
}
return currentMaxProduct
}
TestRunner().runTests(testClass: Tests.self)
|
import Cocoa
extension NSNotification.Name {
static let accessibilityApi = NSNotification.Name(rawValue: "com.apple.accessibility.api")
static let listenFor = NSNotification.Name(rawValue: Utils.PrefKeys.listenFor.rawValue)
static let showContrast = NSNotification.Name(rawValue: Utils.PrefKeys.showContrast.rawValue)
static let friendlyName = NSNotification.Name(rawValue: Utils.PrefKeys.friendlyName.rawValue)
static let preferenceReset = NSNotification.Name(rawValue: Utils.PrefKeys.preferenceReset.rawValue)
static let displayListUpdate = NSNotification.Name(rawValue: Utils.PrefKeys.displayListUpdate.rawValue)
}
|
//
// ViewController.swift
// Silly Monks
//
// Created by Sarath on 16/03/16.
// Copyright © 2016 Sarath. All rights reserved.
//
import UIKit
import GoogleMobileAds
import MagicalRecord
import SDWebImage
class HomeViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource,CXDBDelegate{
//MARK: Intialize
var catTableView = UITableView();
var bannerView: DFPBannerView!
var activityIndicatorView: DTIActivityIndicatorView!
var storedOffsets = [Int: CGFloat]()
var resultDic : NSDictionary = NSDictionary()
var categoryList : NSArray = NSArray()
var imageCache:NSCache = NSCache()
var refreshControl: UIRefreshControl!
var singleMalls : NSMutableArray = NSMutableArray()
var malls : NSMutableArray = NSMutableArray()
var mallIDs: NSMutableArray = NSMutableArray()
var splashImageView: UIImageView!
var sidePanelView:UIView!
var transparentView:UIView!
var isPanelOpened:Bool!
var orgID: String!
var strProfile: String!
var profileDPImageView:UIImageView!
var signInBtn:UIButton!
var aboutUsBtn:UIButton!
var profileBtn:UIButton!
var termsConditionsBtn:UIButton!
var contactUsBtn:UIButton!
var advertiseBtn:UIButton!
var shareAppBtn:UIButton!
var fbButton:UIButton!
var twitterButton:UIButton!
var googlePlusButton:UIButton!
let signInView = CXSignInSignUpViewController.init()
override func viewDidLoad() {
super.viewDidLoad()
self.isPanelOpened = false
//self.setUpSplashAnimation()
self.homeViewCustomization()
CXDBSettings.sharedInstance.delegate = self
self.arrangeCategoryListOrder()
NSNotificationCenter.defaultCenter().addObserver(self, selector:Selector(profileUpdateNotif()), name: "UpdateProfilePic", object: nil)
}
// func setUpSplashAnimation() {
// self.navigationController?.setNavigationBarHidden(true, animated: false)
// self.splashImageView = UIImageView.init(frame: self.view.frame)
// let url = NSBundle.mainBundle().URLForResource("silly", withExtension: "gif")
// self.splashImageView.image = UIImage.animatedImageWithAnimatedGIFURL(url!)
// self.view.addSubview(self.splashImageView)
// NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: #selector(HomeViewController.stopImageAnimation), userInfo: nil, repeats: false)
// }
//
// func stopImageAnimation() {
// dispatch_async(dispatch_get_main_queue()) { [unowned self] in
// self.navigationController?.setNavigationBarHidden(false, animated: false)
// self.splashImageView.hidden = true
// self.homeViewCustomization()
// }
// }
func homeViewCustomization() {
self.customizeHeaderView()
self.addGoogleBannerView()
self.imageCache = NSCache.init()
self.view.backgroundColor = UIColor.smBackgroundColor()
self.activityIndicatorView = DTIActivityIndicatorView(frame: CGRect(x:150.0, y:200.0, width:60.0, height:60.0))
if CXDBSettings.sharedInstance.isToday() {
//If this condition was satisfied no need to get the all malls
if CXDBSettings.sharedInstance.getAllMallsInDB().count == 0 {
self.view.addSubview(self.activityIndicatorView)
self.initialSync()
} else {
self.getCategoryItems()
}
}else{1
print("get the lates data ")
//Remove the data in CX_AllMalls and clear the cache data only for all malls
CX_AllMalls.MR_truncateAll()
NSManagedObjectContext.MR_contextForCurrentThread().MR_saveToPersistentStoreAndWait()
CX_SingleMall.MR_truncateAll()
NSManagedObjectContext.MR_contextForCurrentThread().MR_saveToPersistentStoreAndWait()
self.initialSync()
}
dispatch_async(dispatch_get_main_queue()) {
self.designHomeTableView()
self.customizeSidePanelView() }
}
func customizeSidePanelView() {
self.transparentView = UIView.init(frame: CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height))
self.transparentView.backgroundColor = UIColor.blackColor()
self.transparentView.alpha = 0.4
self.view.addSubview(self.transparentView)
self.transparentView.hidden = true
self.sidePanelView = UIView.init(frame: CGRectMake(-250, 0, 250, self.view.frame.size.height))
self.sidePanelView.backgroundColor = UIColor.smBackgroundColor()
self.sidePanelView.alpha = 0.95
self.designSidePanel()
self.view.addSubview(self.sidePanelView)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.isPanelOpened = false
self.moveSideBarToXposition(-250, shouldHideBackView: true)
}
func designSidePanel() {
let signFrame : CGRect = CGRectMake(10, 3, self.sidePanelView.frame.size.width-20, 50)
/* self.signInBtn = self.createButton(CGRectMake(10, 5, self.sidePanelView.frame.size.width-20, 50), title: "SIGN IN", tag: 1, bgColor: UIColor.clearColor())
self.signInBtn.addTarget(self, action: #selector(HomeViewController.signInAction), forControlEvents: UIControlEvents.TouchUpInside)
self.sidePanelView.addSubview(self.signInBtn)*/
// let profileImage = UIImageView.init(frame: CGRectMake(self.signInBtn.frame.size.width+self.signInBtn.frame.origin.x-80, 0, 70, 70))
// let prjTitle = UILabel(frame: CGRectMake(10, 10,150,50))//CGRectMake(20, 80,140,50)
// //prjTitle.backgroundColor = UIColor.yellowColor()
// prjTitle.textAlignment = NSTextAlignment.Right
// prjTitle.font = UIFont(name: "RobotoCondensed-Bold", size: 25)
// prjTitle.textColor = UIColor.blackColor()
// prjTitle.text = "SILLY MONKS"
// self.sidePanelView.addSubview(prjTitle)
// let lImageView = UIImageView(frame: CGRectMake(prjTitle.frame.size.width + prjTitle.frame.origin.x, prjTitle.frame.origin.y, 50, 50))
// lImageView.image = UIImage(named: "smlogo.png")
// self.sidePanelView.addSubview(lImageView)
let profileImage = UIImageView.init(frame: CGRectMake(5,10,self.sidePanelView.frame.size.width-10, 60))
profileImage.image = UIImage(named:"sm_navigation_logo")
profileImage.layer.cornerRadius = 25
profileImage.layer.masksToBounds = true
self.sidePanelView.addSubview(profileImage)
self.profileBtn = self.createButton(CGRectMake(10, signFrame.size.height+signFrame.origin.y+25, self.sidePanelView.frame.size.width-60, 50), title: "SIGN IN", tag: 1, bgColor: UIColor.clearColor())
self.profileBtn.addTarget(self, action: #selector(HomeViewController.signInAction), forControlEvents: UIControlEvents.TouchUpInside)
self.sidePanelView.addSubview(self.profileBtn)
self.profileDPImageView = UIImageView.init(frame: CGRectMake(self.profileBtn.frame.size.width-15,signFrame.size.height+signFrame.origin.y+25,60,60))
self.profileDPImageView .image = UIImage(named: "profile_placeholder.png")
self.profileDPImageView .layer.cornerRadius = self.profileDPImageView.frame.size.width / 2
self.profileDPImageView .clipsToBounds = true
self.profileDPImageView.userInteractionEnabled = true
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(HomeViewController.signInAction))
self.profileDPImageView.addGestureRecognizer(tapRecognizer)
self.sidePanelView.addSubview(self.profileDPImageView )
self.aboutUsBtn = self.createButton(CGRectMake(10, self.profileBtn.frame.size.height+self.profileBtn.frame.origin.y+5, self.sidePanelView.frame.size.width-20, 50), title: "About Sillymonks", tag: 1, bgColor: UIColor.clearColor())
self.aboutUsBtn.addTarget(self, action: #selector(HomeViewController.aboutUsAction), forControlEvents: UIControlEvents.TouchUpInside)
self.sidePanelView.addSubview(self.aboutUsBtn)
self.termsConditionsBtn = self.createButton(CGRectMake(10, self.aboutUsBtn.frame.size.height+self.aboutUsBtn.frame.origin.y+5, self.sidePanelView.frame.size.width-20, 50), title: "Terms & Conditions", tag: 1, bgColor: UIColor.clearColor())
self.termsConditionsBtn.addTarget(self, action: #selector(HomeViewController.termsAndCondAction), forControlEvents: UIControlEvents.TouchUpInside)
self.sidePanelView.addSubview(self.termsConditionsBtn)
self.contactUsBtn = self.createButton(CGRectMake(10, self.termsConditionsBtn.frame.size.height+self.termsConditionsBtn.frame.origin.y+5, self.sidePanelView.frame.size.width-20, 50), title: "Contact Us", tag: 1, bgColor: UIColor.clearColor())
self.contactUsBtn.addTarget(self, action: #selector(HomeViewController.contactUsAction), forControlEvents: UIControlEvents.TouchUpInside)
self.sidePanelView.addSubview(self.contactUsBtn)
self.advertiseBtn = self.createButton(CGRectMake(10, self.contactUsBtn.frame.size.height+self.contactUsBtn.frame.origin.y+5, self.sidePanelView.frame.size.width-20, 50), title: "Advertise With Us", tag: 1, bgColor: UIColor.clearColor())
self.advertiseBtn.addTarget(self, action: #selector(HomeViewController.advertiseWithUsAction), forControlEvents: UIControlEvents.TouchUpInside)
self.sidePanelView.addSubview(self.advertiseBtn)
self.shareAppBtn = self.createButton(CGRectMake(10, self.advertiseBtn.frame.size.height+self.advertiseBtn.frame.origin.y+5, self.sidePanelView.frame.size.width-20, 40), title: "SHARE THE APP", tag: 1, bgColor: UIColor.clearColor())
self.shareAppBtn.addTarget(self, action: #selector(HomeViewController.shareAppAction), forControlEvents: UIControlEvents.TouchUpInside)
self.shareAppBtn.backgroundColor = UIColor.navBarColor()
self.shareAppBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
self.shareAppBtn.layer.cornerRadius = 6.0
self.shareAppBtn.layer.masksToBounds = true
self.shareAppBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center
self.sidePanelView.addSubview(self.shareAppBtn)
let followLbl = UILabel.init(frame: CGRectMake(10, self.shareAppBtn.frame.size.height+self.shareAppBtn.frame.origin.y+10, self.sidePanelView.frame.size.width-20, 30))
followLbl.font = UIFont(name: "Roboto-Bold", size: 15)
followLbl.text = "Follow Us"
self.sidePanelView.addSubview(followLbl)
let dimension = (self.sidePanelView.frame.size.width - 30 - 30)/3
self.fbButton = self.createImageButton(CGRectMake(15, followLbl.frame.size.height+followLbl.frame.origin.y+5, dimension, dimension), tag: 23, bImage: UIImage(named: "Facebook.png")!)
self.fbButton.addTarget(self, action: #selector(HomeViewController.fbAction), forControlEvents: UIControlEvents.TouchUpInside)
self.sidePanelView.addSubview(self.fbButton)
self.twitterButton = self.createImageButton(CGRectMake(self.fbButton.frame.size.width+self.fbButton.frame.origin.x + 15, followLbl.frame.size.height+followLbl.frame.origin.y+10, dimension, dimension), tag: 24, bImage: UIImage(named: "Twitter.png")!)
self.twitterButton.addTarget(self, action: #selector(HomeViewController.twitterAction), forControlEvents: UIControlEvents.TouchUpInside)
self.sidePanelView.addSubview(self.twitterButton)
self.googlePlusButton = self.createImageButton(CGRectMake(self.twitterButton.frame.size.width+self.twitterButton.frame.origin.x + 15, followLbl.frame.size.height+followLbl.frame.origin.y+10, dimension, dimension), tag: 25, bImage: UIImage(named: "Google_Plus.png")!)
self.googlePlusButton.addTarget(self, action: #selector(HomeViewController.googleAction), forControlEvents: UIControlEvents.TouchUpInside)
self.sidePanelView.addSubview(self.googlePlusButton)
let powerLbl = UILabel.init(frame: CGRectMake(10, self.googlePlusButton.frame.size.height+self.googlePlusButton.frame.origin.y+20, 100, 35))
powerLbl.text = "Powered by"
powerLbl.font = UIFont(name:"Roboto-Regular",size: 14)
powerLbl.textColor = UIColor.grayColor()
self.sidePanelView.addSubview(powerLbl)
let logoImage = UIImageView.init(frame: CGRectMake(powerLbl.frame.size.width+powerLbl.frame.origin.x+5, powerLbl.frame.origin.y-10, 110, 40))
logoImage.image = UIImage(named: "storeongo_gray.png")
self.sidePanelView.addSubview(logoImage)
}
func panelBtnAction() {
if self.isPanelOpened == true {
self.isPanelOpened = false
self.moveSideBarToXposition(-250, shouldHideBackView: true)
} else {
self.isPanelOpened = true
self.transparentView.hidden = false
self.moveSideBarToXposition(0, shouldHideBackView: false)
if NSUserDefaults.standardUserDefaults().valueForKey("PROFILE_PIC") != nil {
self.profileBtn.setTitle("MY PROFILE", forState: .Normal)
self.profileBtn.addTarget(self, action: #selector(HomeViewController.signInAction), forControlEvents: UIControlEvents.TouchUpInside)
}else{
if NSUserDefaults.standardUserDefaults().valueForKey("USER_ID") != nil{
self.profileBtn.setTitle("MY PROFILE", forState: .Normal)
self.profileBtn.addTarget(self, action: #selector(HomeViewController.signInAction), forControlEvents: UIControlEvents.TouchUpInside)
}else{
self.profileDPImageView .image = UIImage(named: "profile_placeholder.png")
self.profileBtn.setTitle("SIGN IN", forState: .Normal)
self.profileBtn.addTarget(self, action: #selector(HomeViewController.signInAction), forControlEvents: UIControlEvents.TouchUpInside)
}
}
}
}
func signInAction() {
// NSUserDefaults.standardUserDefaults().setBool(false, forKey: "FIRST_TIME_LOGIN")
self.panelBtnAction()
if NSUserDefaults.standardUserDefaults().valueForKey("USER_ID") != nil {
NSLog("it has an userid")
let profile = CXProfilePageView.init()
self.navigationController?.pushViewController(profile, animated: true)
} else {
self.navigationController?.pushViewController(signInView, animated: true)
}
}
func profileUpdateNotif(){
// self.profileBtn
if NSUserDefaults.standardUserDefaults().valueForKey("PROFILE_PIC") != nil {
self.strProfile = NSUserDefaults.standardUserDefaults().valueForKey("PROFILE_PIC") as? String
let imgURL: NSURL = NSURL(string: strProfile)!
let request: NSURLRequest = NSURLRequest(URL: imgURL)
NSURLConnection.sendAsynchronousRequest(
request, queue: NSOperationQueue.mainQueue(),
completionHandler: {(response: NSURLResponse?,data: NSData?,error: NSError?) -> Void in
if error == nil {
self.profileDPImageView.image = UIImage(data: data!)
}
})
} else {
}
//use this one later to escape the warning!!!!
//dataTaskWithRequest(request: NSURLRequest, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> NSURLSessionDataTask
}
func showAlertView(message:String, status:Int) {
let alert = UIAlertController(title: "Silly Monks", message: message, preferredStyle: UIAlertControllerStyle.Alert)
//alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil))
let okAction = UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default) {
UIAlertAction in
if status == 1 {
//self.navigationController?.popViewControllerAnimated(true)
}
}
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
}
/*NSNotificationCenter.defaultCenter().postNotificationName("profileUpdate", object: nil)
Then I recognized the notification in my viewDidLoad function with this:
Then I made this function under my viewDidLoad function:
*/
func aboutUsAction() {
self.panelBtnAction()
let aboutUsView = CXAboutUsViewController.init()
self.navigationController?.pushViewController(aboutUsView, animated: true)
}
func termsAndCondAction() {
self.panelBtnAction()
let termsView = CXTermsAndConditionsViewController.init()
self.navigationController?.pushViewController(termsView, animated: true)
}
func contactUsAction() {
self.panelBtnAction()
let contactUsView = CXContactUsViewController.init()
self.navigationController?.pushViewController(contactUsView, animated: true)
}
func advertiseWithUsAction() {
self.panelBtnAction()
let advertiseView = CXAdvertiseViewController.init()
self.navigationController?.pushViewController(advertiseView, animated: true)
}
func shareAppAction() {
let infoText = CXConstant.appStoreUrl
let shareItems:Array = [infoText]
let activityViewController:UIActivityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
activityViewController.excludedActivityTypes = [UIActivityTypePrint, UIActivityTypePostToWeibo, UIActivityTypeCopyToPasteboard, UIActivityTypeAddToReadingList, UIActivityTypePostToVimeo]
self.presentViewController(activityViewController, animated: true, completion: nil)
}
func fbAction() {
let path = "https://www.facebook.com/sillymonks/"
let url = NSURL(string: path)
UIApplication.sharedApplication().openURL(url!)
}
func twitterAction() {
let path = "https://twitter.com/SillyMonks"
let url = NSURL(string: path)
UIApplication.sharedApplication().openURL(url!)
}
func googleAction () {
let path = "https://plus.google.com/+SillymonksnetworkDotCom/posts"
let url = NSURL(string: path)
UIApplication.sharedApplication().openURL(url!)
}
func moveSideBarToXposition(iXposition: Float,shouldHideBackView:Bool) {
let convertedXposition = CGFloat(iXposition)
UIView.animateWithDuration(0.5, delay: 0.5, options: UIViewAnimationOptions.TransitionNone, animations: { () -> Void in
self.sidePanelView.frame = CGRectMake(convertedXposition, 0, self.sidePanelView.frame.size.width, self.sidePanelView.frame.size.height)
}, completion: { (finished: Bool) -> Void in
self.transparentView.hidden = shouldHideBackView
})
}
func createButton(frame:CGRect,title: String,tag:Int, bgColor:UIColor) -> UIButton {
let button: UIButton = UIButton()
button.frame = frame
button.setTitle(title, forState: .Normal)
button.titleLabel?.font = UIFont.init(name:"Roboto-Regular", size: 18)
button.titleLabel?.textAlignment = NSTextAlignment.Left
button.setTitleColor(UIColor.grayColor(), forState: UIControlState.Normal)
button.layer.cornerRadius = 5.0
button.layer.masksToBounds = true
button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
button.backgroundColor = bgColor
return button
}
func createImageButton(frame:CGRect,tag:Int,bImage:UIImage) -> UIButton {
let button: UIButton = UIButton()
button.frame = frame
button.backgroundColor = UIColor.yellowColor()
button.setImage(bImage, forState: UIControlState.Normal)
button.backgroundColor = UIColor.clearColor()
button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
return button
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//NSNotificationCenter.defaultCenter().addObserver(self, selector:Selector(profileUpdateNotif()), name: "UpdateProfilePic", object: nil)
self.profileUpdateNotif()
sideMenuController()?.sideMenu?.allowRightSwipe = false
sideMenuController()?.sideMenu?.allowLeftSwipe = false
sideMenuController()?.sideMenu?.allowPanGesture = false
}
func getCategoryItems() {
let categoryListByorder : NSMutableArray = NSMutableArray()
let list : NSArray = CX_AllMalls.MR_findAll()
let itemOrderList : NSArray = ["Silly Monks Tollywood","Silly Monks Bollywood","Silly Monks Kollywood","Silly Monks Mollywood","Silly Monks Hollywood","Creators"]
for orderItem in itemOrderList {
for element in list {
let allMalls : CX_AllMalls = element as! CX_AllMalls
if orderItem as! String == allMalls.name! {
// print("all mall Category Name \(allMalls.name)");
categoryListByorder.addObject(allMalls)
break
}
}
}
self.categoryList = categoryListByorder
self.catTableView.reloadData()
}
func arrangeCategoryListOrder(){
//Tolly,Bolly,Kolly,Molly,Holly,Creaters
// return CX_AllMalls.MR_findAll().count
}
func moveAction(){
self.initialSync()
}
//MARK:Intial Sync
func initialSync() {
//self.activityIndicatorView.startActivity()
LoadingView.show("Loading", animated: true)
SMSyncService.sharedInstance.startSyncProcessWithUrl(CXConstant.ALL_MALLS_URL) { (responseDict) -> Void in
CXDBSettings.sharedInstance.saveAllMallsInDB((responseDict.valueForKey("orgs") as? NSArray)!)
}
CXDBSettings.sharedInstance.saveTheIntialSyncDate()
}
func didFinishAllMallsSaving() {
self.getCategoryItems();
self.mallIDs = CXDBSettings.getAllMallIDs()
self.getSingleMalls()
}
func didFinishSingleMallSaving(mallId:String) {
self.mallIDs.removeObject(mallId)
self.getSingleMalls()
}
func didFinishStoreSaving(mallId:String) {
self.mallIDs.removeObject(mallId)
self.getStores()
}
func didFinishProductCategories() {
}
func didFinishProducts(proName: String) {
}
func getSingleMalls() {
if self.mallIDs.count > 0 {
let mallID = self.mallIDs[0] as? String
self.getSingleMallWithMall(mallID!)
} else {
self.mallIDs = CXDBSettings.getAllMallIDs()
self.getStores()
}
}
func getStores () {
if self.mallIDs.count > 0 {
let mallId : String = self.mallIDs[0] as! String
self.getStoreWithMall(mallId)
} else {
//self.activityIndicatorView.stopActivity()
LoadingView.hide()
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
self.catTableView.reloadData()
self.updateMenuItems()
}
}
}
func updateMenuItems() {
let menuView = self.sideMenuController()?.sideMenu?.menuViewController as? SMMenuViewController
menuView?.updateItems()
}
func getStoreWithMall(mallId:String) {
let storeUrl = CXConstant.STORE_URL+mallId
SMSyncService.sharedInstance.startSyncProcessWithUrl(storeUrl) { (responseDict) -> Void in
if let jobsArray = responseDict.valueForKey("jobs") {
if jobsArray.count > 0 {
CXDBSettings.sharedInstance.saveStoreInDB(jobsArray.objectAtIndex(0) as! NSDictionary)
}
else {
self.mallIDs.removeObject(mallId)
self.getStores()
}
}
}
}
func getSingleMallWithMall(mallId:String) {
let singleMallUrl = CXConstant.SINGLE_MALL_URL+mallId
SMSyncService.sharedInstance.startSyncProcessWithUrl(singleMallUrl) { (responseDict) -> Void in
let orgsArray: NSArray = responseDict.valueForKey("orgs")! as! NSArray
let resDict = orgsArray.objectAtIndex(0) as! NSDictionary
CXDBSettings.sharedInstance.saveSingleMallInDB(resDict)
}
}
func addGoogleBannerView() {
self.bannerView = CXBannerView.init(bFrame: CGRectMake((self.view.frame.size.width - 360)/2, 0, 360, 180), unitID: "/133516651/AppHome", delegate: self)
self.view.addSubview(self.bannerView)
}
func customizeHeaderView() {
self.navigationController?.navigationBar.translucent = false;
self.navigationController?.navigationBar.barTintColor = UIColor.navBarColor()
let lImage = UIImage(named: "men_icon.png") as UIImage?
let button = UIButton (type: UIButtonType.Custom) as UIButton
button.frame = CGRectMake(0, 0, 30, 30)
button.addTarget(self, action: #selector(HomeViewController.panelBtnAction), forControlEvents: UIControlEvents.TouchUpInside)
button.setImage(lImage, forState: .Normal)
self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: button)
let profileImage = UIImageView.init(frame: CGRectMake(0, 0, 5, 40))
profileImage.image = UIImage(named:"TabbarLogo")
profileImage.contentMode = UIViewContentMode.ScaleAspectFit
profileImage.backgroundColor = UIColor.clearColor()
self.navigationItem.titleView = profileImage
// let tLabel : UILabel = UILabel()
// tLabel.frame = CGRectMake(0, 0, 120, 40);
// tLabel.backgroundColor = UIColor.clearColor()
// tLabel.font = UIFont.init(name: "Roboto-Bold", size: 18)
// tLabel.text = "Silly Monks"
// tLabel.textAlignment = NSTextAlignment.Center
// tLabel.textColor = UIColor.whiteColor()
// self.navigationItem.titleView = tLabel
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func designHomeTableView(){
let yAxis = self.bannerView.frame.size.height+self.bannerView.frame.origin.y+5
self.catTableView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
self.catTableView.dataSource = self;
self.catTableView.delegate = self;
self.catTableView.backgroundColor = UIColor.clearColor()
self.catTableView.registerClass(TableViewCell.self, forCellReuseIdentifier: "EventCell")
self.catTableView.separatorStyle = UITableViewCellSeparatorStyle.None
self.catTableView.contentInset = UIEdgeInsetsMake(yAxis, 0,60, 0)//-10
self.catTableView.rowHeight = UITableViewAutomaticDimension
self.view.addSubview(self.catTableView)
}
func customizeRefreshController() {
let loadView:UIView = UIView.init(frame: CGRectMake(0, 0, self.view.frame.width, 60))
self.refreshControl = UIRefreshControl()
self.refreshControl.frame = CGRectMake(0, 0, 100, 50)
self.refreshControl.backgroundColor = UIColor.yellowColor()
self.refreshControl.tintColor = UIColor.blueColor()
self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
self.refreshControl.addTarget(self, action: #selector(HomeViewController.refreshAction), forControlEvents: UIControlEvents.ValueChanged)
self.catTableView.addSubview(refreshControl) // not required when using UITableViewController
///refreshControl.endRefreshing()
}
func refreshAction() {
// print("Screen refreshing")
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.categoryList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = "EventCell"
var cell: TableViewCell! = tableView.dequeueReusableCellWithIdentifier(identifier) as? TableViewCell
if cell == nil {
tableView.registerNib(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: identifier)
cell = tableView.dequeueReusableCellWithIdentifier(identifier) as? TableViewCell
cell.backgroundColor = UIColor.smBackgroundColor()
}
cell.setCollectionViewDataSourceDelegate(self, forRow: indexPath.row)
cell.collectionViewOffset = storedOffsets[indexPath.row] ?? 0
let allMalls:CX_AllMalls = self.categoryList[indexPath.row] as! CX_AllMalls
cell.cellTitlelbl.text = allMalls.name
return cell;
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return CXConstant.homeScreenTableViewHeight-5;
}
//MARK: Arrange The Order
}
extension HomeViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return 1;
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let mall:CX_AllMalls = self.categoryList[collectionView.tag] as! CX_AllMalls
let menuView = SMCategoryViewController.init()
menuView.mall = mall
if collectionView.tag == 0 {
menuView.bannerString = CXConstant.TOLLYWOOD_BANNAER
} else if collectionView.tag == 1 {
menuView.bannerString = CXConstant.BOLLYWOOD_BANNAER
} else if collectionView.tag == 2 {
menuView.bannerString = CXConstant.HOLLYWOOD_BANNAER
} else if collectionView.tag == 3 {
menuView.bannerString = CXConstant.MOLLYWOOD_BANNAER
} else if collectionView.tag == 4 {
menuView.bannerString = CXConstant.KOLLYWOOD_BANNAER
} else {
menuView.bannerString = CXConstant.SANDALWOOD_BANNAER
}
self.navigationController?.pushViewController(menuView, animated: true)
}
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let identifier = "CollectionViewCell"
let cell: CollectionViewItemCell! = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as?CollectionViewItemCell
if cell == nil {
collectionView.registerNib(UINib(nibName: "CollectionViewItemCell", bundle: nil), forCellWithReuseIdentifier: identifier)
}
cell.imageView.image = nil
//cell.imageView.contentMode = UIViewContentMode.ScaleAspectFit
cell.activity.hidden = true
let allMall:CX_AllMalls = self.categoryList[collectionView.tag] as! CX_AllMalls
if allMall.mid != nil {
self.configureCell(allMall, cell: cell, indexPath: indexPath)
} else {
cell.imageView.image = UIImage(named: "smlogo.png")
}
return cell
}
func configureCell(allMall:CX_AllMalls,cell:CollectionViewItemCell,indexPath:NSIndexPath) {
if CXDBSettings.sharedInstance.getSingleMalls(allMall.mid!).count > 0 {
let singleMalls = CXDBSettings.sharedInstance.getSingleMalls(allMall.mid!)
let singleMall:CX_SingleMall = singleMalls[0] as! CX_SingleMall
cell.imageView.sd_setImageWithURL(NSURL(string:singleMall.coverImage!)!, placeholderImage: UIImage(named: "smlogo.png"), options:SDWebImageOptions.RefreshCached)
//cell.textLabel.text = allMall.name
} else {
cell.activity.stopActivity()
cell.activity.hidden = true
cell.imageView.image = UIImage(named: "smlogo.png")
}
}
}
|
//
// CornerRadiusView.swift
// AutoLayout
//
// Created by Taof on 11/21/19.
// Copyright © 2019 Taof. All rights reserved.
//
import UIKit
@IBDesignable
class CornerRadiusView: UIView {
@IBInspectable var radius: CGFloat = 0.0
@IBInspectable var fillColor: UIColor = .cyan
override func draw(_ rect: CGRect) {
let path = UIBezierPath(roundedRect: rect, cornerRadius: radius)
// fillColor.setFill()
path.fill()
}
}
|
//
// SeriesCell.swift
// MarvelComic
//
// Created by Alec Malcolm on 2018-03-22.
// Copyright © 2018 Alec Malcolm. All rights reserved.
//
import UIKit
class SeriesCell : UICollectionViewCell {
@IBOutlet weak var titleLabel: UILabel!
var series: SeriesModel? {
didSet {
guard let series = series else { return }
//guard let title = event.title else { return }
titleLabel.text = series.title
}
}
}
|
//
// InsightsEventResourcesDecodingTests.swift
//
//
// Created by Vladislav Fitc on 21/07/2022.
//
import Foundation
import XCTest
@testable import AlgoliaSearchClient
class InsightsEventResourcesDecodingTests: XCTestCase {
func testDecodeObjectIDs() throws {
try AssertEncodeDecode(InsightsEvent.Resources.objectIDs(["object1", "object2", "object3"]), [
"objectIDs": ["object1", "object2", "object3"],
])
}
func testDecodeObjectIDsWithPositions() throws {
try AssertEncodeDecode(InsightsEvent.Resources.objectIDsWithPositions([("object1", 1), ("object2", 2), ("object3", 3)]), [
"objectIDs": ["object1", "object2", "object3"],
"positions": [1, 2, 3]
])
}
func testDecodeFilters() throws {
try AssertEncodeDecode(InsightsEvent.Resources.filters(["f1", "f2", "f3"]), [
"filters": ["f1", "f2", "f3"]
])
}
func testDecodingFailure() {
let data = """
{
"foo": "bar"
}
""".data(using: .utf8)!
XCTAssertThrowsError(try JSONDecoder().decode(InsightsEvent.Resources.self, from: data), "must throw decoding error") { error in
guard case .dataCorrupted(let context) = error as? DecodingError, context.underlyingError is CompositeError else {
XCTFail("unexpected error thrown")
return
}
}
}
}
|
//
// Review.swift
// RxSwiftSample
//
// Created by nguyen.duc.huyb on 8/9/19.
// Copyright © 2019 nguyen.duc.huyb. All rights reserved.
//
struct Review: Decodable {
let rating: Float?
let reviewText: String?
let id: Int?
let ratingColor: String?
let reviewTimeFriendly: String?
let ratingText: String?
let timestamp: Int?
let likes: Int?
let user: User?
let commentsCount: Int?
enum CodingKeys: String, CodingKey {
case rating = "rating"
case reviewText = "review_text"
case id = "id"
case ratingColor = "rating_color"
case reviewTimeFriendly = "review_time_friendly"
case ratingText = "rating_text"
case timestamp = "timestamp"
case likes = "likes"
case user = "user"
case commentsCount = "comments_count"
}
}
|
//
// AdjustedScrollView.swift
// Swift Test 2
//
// Created by Daniel Katz on 4/17/16.
// Copyright © 2016 OK. All rights reserved.
//
import Foundation
|
//
// ChooseItemView.swift
// RiBoScheduleAssistant
//
// Created by Rin Pham on 5/20/18.
// Copyright © 2018 Rin Pham. All rights reserved.
//
import UIKit
protocol ChooseItemViewDelegate: class {
func eventChoosed(_ chooseItemView: ChooseItemView, event: Event)
func taskChoosed(_ chooseItemView: ChooseItemView, task: Task)
func chooseItemViewClosed()
}
class ChooseItemView: UIView {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var titleLabel: UILabel!
fileprivate var largeView: UIView!
var events = [Event]()
var tasks = [Task]()
weak var delegate: ChooseItemViewDelegate?
enum TypeItem {
case event
case task
}
var type = TypeItem.event
class func instance(ratio: CGFloat, type: ChooseItemView.TypeItem, title: String, events: [Event] = [], tasks: [Task] = []) -> ChooseItemView {
let view = UIView.loadFromNibNamed(nibNamed: "ChooseItemView") as! ChooseItemView
view.events = events
view.tasks = tasks
view.type = type
view.titleLabel.text = title
view.center = CGPoint(x: UIScreen.main.bounds.width/2, y: UIScreen.main.bounds.height/2)
view.frame.size = CGSize(width: UIScreen.main.bounds.width*ratio, height: UIScreen.main.bounds.height*0.7)
view.largeView = UIView.createBlurView(rect: UIScreen.main.bounds, style: .dark)
view.largeView.backgroundColor = UIColor.darkGray
let tap = UITapGestureRecognizer(target: view, action: #selector(view.didTouchUpInsideLargeView(_:)))
view.largeView.addGestureRecognizer(tap)
view.setup()
return view
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func layoutSubviews() {
super.layoutSubviews()
self.layoutIfNeeded()
}
fileprivate func setup() {
self.tableView.dataSource = self
self.tableView.delegate = self
self.backgroundColor = UIColor.white
self.cornerRadius(5, borderWidth: 0, color: .white)
self.tableView.tableFooterView = UIView(frame: CGRect.zero)
self.titleLabel.textColor = App.Color.mainDarkColor
}
func open(supView: UIView, completion: @escaping () -> Void) {
self.center = CGPoint(x: supView.center.x, y: supView.center.y)
supView.addSubview(largeView)
supView.addSubview(self)
largeView.alpha = 0.3
self.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
UIView.animate(withDuration: 0.2, animations: { [weak self] in
self?.largeView.alpha = 1
self?.transform = CGAffineTransform(scaleX: 1, y: 1)
}) { (_) in
completion()
}
}
func close(completion: @escaping () -> Void) {
UIView.animate(withDuration: 0.2, animations: { [weak self] in
self?.largeView.alpha = 0
self?.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
}) { [weak self] (_) in
if self?.superview != nil {
self?.removeFromSuperview()
}
if self?.largeView.superview != nil {
self?.largeView.removeFromSuperview()
}
completion()
}
delegate?.chooseItemViewClosed()
}
//#MARK: - Button Clicked
@objc fileprivate func didTouchUpInsideLargeView(_ gesture: UIGestureRecognizer) {
self.close {}
}
}
extension ChooseItemView: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.type == .event ? self.events.count : self.tasks.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil)
if self.type == .event {
let event = self.events[indexPath.row]
cell.textLabel?.text = event.title
cell.detailTextLabel?.text = "From " + event.startDate.toDateAndTimeString + " to " + event.endDate.toDateAndTimeString
} else {
let task = self.tasks[indexPath.row]
cell.textLabel?.text = task.title
var text = ""
switch task.repeatType {
case .daily, .weekdays, .weekends:
text = task.time.toString(format: "HH:mm")
case .weekly:
text = task.time.toString(format: "EEEE, HH:mm")
default:
text = task.time.toDateAndTimeString
}
text += ", "
if task.repeatType == .none {
text = "No Repeat"
} else {
let repeatStrings = ["None", "Daily", "Weekly", "Weekdays", "Weekends", "Monthly"]
text = repeatStrings[task.repeatType.rawValue]
}
cell.detailTextLabel?.text = text
}
cell.accessoryType = .disclosureIndicator
return cell
}
}
extension ChooseItemView: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if self.type == .event {
self.delegate?.eventChoosed(self, event: self.events[indexPath.row])
} else {
self.delegate?.taskChoosed(self, task: self.tasks[indexPath.row])
}
self.close {
}
}
}
|
//
// Hammer.swift
// Projet_P3
//
// Created by Marques Lucas on 10/10/2018.
// Copyright © 2018 Marques Lucas. All rights reserved.
//
import Foundation
// Hammer class with its initializer
class Hammer: Weapons {
init() {
super.init(name: "Marteau", power: 20)
}
}
|
//
// LearnAnimate.swift
// switui_learn
//
// Created by laijihua on 2020/10/17.
//
import SwiftUI
struct LearnAnimate: View {
@State private var flipFlop = false
let timer = Timer
.publish(every: 1, on: .current, in: .common)
.autoconnect()
var body: some View {
VStack {
ZStack {
Circle().fill(Color.green)
Circle().fill(Color.yellow)
.scaleEffect(0.8)
Circle().fill(Color.orange)
.scaleEffect(0.6)
Circle().fill(Color.red)
.scaleEffect(0.4)
}
.scaleEffect(flipFlop ? 0.2 : 0.8)
.opacity(flipFlop ? 0.1 : 1.0)
.animation(Animation.spring().repeatForever(autoreverses: true))
.onReceive(timer, perform: { _ in
self.flipFlop.toggle()
})
Path(
UIBezierPath(roundedRect:
CGRect(origin: .zero, size: CGSize(width: 100, height: 50)),
byRoundingCorners: [.topRight, .bottomLeft],
cornerRadii: CGSize(width: 15, height: 15)
).cgPath
)
.fill(Color.blue)
.padding(20)
.onTapGesture(count: 1, perform: {
print("was Tap")
})
}
}
}
struct LearnAnimate_Previews: PreviewProvider {
static var previews: some View {
LearnAnimate()
}
}
|
import SwiftUI
import Firebase
import FirebaseAuth
class FirebaseSession: ObservableObject {
//MARK: Properties
@Published var session: User?
@Published var isLoggedIn: Bool?
//@Published var items: [TODOS] = []
//var ref: DatabaseReference = Database.database().reference(withPath: "\(String(describing: Auth.auth().currentUser?.uid ?? "Error"))")
//MARK: Functions
func logIn(email: String, password: String, handler: @escaping AuthDataResultCallback) {
Auth.auth().signIn(withEmail: email, password: password, completion: handler)
}
func logOut() {
try! Auth.auth().signOut()
self.isLoggedIn = false
self.session = nil
}
func signUp(email: String, password: String, handler: @escaping AuthDataResultCallback) {
Auth.auth().createUser(withEmail: email, password: password, completion: handler)
}
}
|
//
// SpellMovementComponent.swift
// Pods
//
// Created by Alexander Skorulis on 19/8/18.
//
import GameplayKit
class SpellMovementComponent: GKComponent {
func spellEntity() -> SpellEntity {
return self.entity as! SpellEntity
}
func setInitialVelocity() {
let spellNode = self.spellEntity().node()
let geometry = spellNode.geometry!
let spell = spellEntity().model
let rX = RandomHelpers.rand(min: -spell.inaccuracy(), max: spell.inaccuracy())
let rY = RandomHelpers.rand(min: -spell.inaccuracy(), max: spell.inaccuracy())
let rZ = RandomHelpers.rand(min: -spell.inaccuracy(), max: spell.inaccuracy())
var direction = (spellEntity().target!.worldPosition - spellNode.worldPosition)
direction = direction.normalized()
direction += SCNVector3(rX,rY,rZ)
let shapeOptions = [SCNPhysicsShape.Option.collisionMargin:0.0]
let physicsShape = SCNPhysicsShape(geometry: geometry, options: shapeOptions)
let physicsBody = SCNPhysicsBody(type: .dynamic, shape: physicsShape)
physicsBody.velocity = direction * Float(spellEntity().model.speed())
physicsBody.damping = 0
physicsBody.isAffectedByGravity = false
physicsBody.categoryBitMask = 1
physicsBody.collisionBitMask = 0
physicsBody.contactTestBitMask = 1
spellNode.physicsBody = physicsBody
}
override func update(deltaTime seconds: TimeInterval) {
let homing = self.spellEntity().model.homingRate()
let node = self.spellEntity().node()
if homing > 0 {
let speed = self.spellEntity().model.speed()
let direction = (self.spellEntity().target!.position - node.presentation.position).normalized()
let change = direction * homing * Float(seconds)
node.physicsBody!.velocity += change
if (node.physicsBody!.velocity.magnitude() > speed) {
node.physicsBody!.velocity = node.physicsBody!.velocity.normalized() * speed
}
}
}
}
|
//
// ViewController.swift
// Eeshaan_Calculator
//
// Created by Guest User on 2018-09-18.
// Copyright © 2018 Guest User. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var display: UILabel!
var userIsInTheMiddleofTyping = false
@IBAction func buttonDigit(_ sender: UIButton) {
let digit = sender.currentTitle!
let textCurrentlyInDisplay = display.text!
if userIsInTheMiddleofTyping{
display.text = textCurrentlyInDisplay + digit
}
else {
display.text = digit
userIsInTheMiddleofTyping = true
}
}
var displayValue: Double{
get{
return Double(display.text!)!
}
set{
display.text = String(newValue)
}
}
private var brain = calcibrain()
@IBAction func performOperation(_ sender: UIButton){
if userIsInTheMiddleofTyping{
brain.setOperand(displayValue)
userIsInTheMiddleofTyping = false
}
if let mathematicalSymbol = sender.currentTitle{
brain.performOperation(mathematicalSymbol)
}
if let result = brain.result
{
displayValue = result
}
}
/* @IBAction func performOperation(_ sender: UIButton) {
userIsInTheMiddleofTyping = false
if let mathematicalSymbol = sender.currentTitle
{
switch mathematicalSymbol {
case "π":
//display.text! = String(Double.pi)
displayValue = Double.pi
case "√":
//let operand = Double(display.text!)!
// display.text = String(sqrt(operand))
displayValue = sqrt(displayValue)
default: break
}
}
} */
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
//
// TasksViewController.swift
// Task Sorter
//
// Created by Beau Young on 2/11/2015.
// Copyright © 2015 Beau Young. All rights reserved.
//
import UIKit
class TasksViewController: UIViewController {
var tasks: [NodeTree] {
return NodeManager.sharedManager.sortedNodes()
}
//Mark: Propeties
@IBOutlet weak var tableView: UITableView!
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerNib(UINib(nibName: "TaskTableViewCell", bundle: nil), forCellReuseIdentifier: "TaskCell")
tableView.tableFooterView = UIView(frame: CGRect.zero)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
//MARK: Actions
}
// MARK: - UITableViewDataSource
extension TasksViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TaskCell", forIndexPath: indexPath) as! TaskTableViewCell
let taskNode = tasks[indexPath.row]
cell.titleLabel.text = taskNode.title
cell.selectionStyle = .None
return cell
}
}
// MARK: - UITableViewDelegate
extension TasksViewController: UITableViewDelegate {
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let node = tasks[indexPath.row]
NodeManager.sharedManager.deleteNode(node.title)
tableView.reloadData()
}
}
|
//
// This source file is part of the Apodini open source project
//
// SPDX-FileCopyrightText: 2019-2021 Paul Schmiedmayer and the Apodini project authors (see CONTRIBUTORS.md) <paul.schmiedmayer@tum.de>
//
// SPDX-License-Identifier: MIT
//
import Foundation
/// A `ReferenceKey` uniquely identifies a `TypeInformation` inside a ``TypeStore`` instance.
public struct ReferenceKey: RawRepresentable, TypeInformationElement {
/// Raw value
public let rawValue: String
/// Initializes self from a rawValue
public init(rawValue: String) {
self.rawValue = rawValue
}
/// Initializes self from a rawValue
public init(_ rawValue: String) {
self.init(rawValue: rawValue)
}
}
// MARK: - Hashable
extension ReferenceKey: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(rawValue)
}
}
// MARK: - Equatable
extension ReferenceKey: Equatable {
public static func == (lhs: ReferenceKey, rhs: ReferenceKey) -> Bool {
lhs.rawValue == rhs.rawValue
}
}
// MARK: - Codable
extension ReferenceKey: Codable {
/// Creates a new instance by decoding from the given decoder.
public init(from decoder: Decoder) throws {
try rawValue = decoder.singleValueContainer().decode(String.self)
}
/// Encodes self into the given encoder.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(rawValue)
}
}
|
//
// MenuLookViewController.swift
// Triton King
//
// Created by Alexander on 31.10.2019.
// Copyright © 2019 Alexander Team. All rights reserved.
//
import UIKit
class MenuLookViewController: UIViewController {
@IBOutlet weak var foodCategoryTableView: UITableView!
private let apiClient = APICLient()
var foodCatalog: FoodCatalog?
var dataToPass: FoodInfo?
override func viewDidLoad() {
super.viewDidLoad()
fetchMenu()
}
private func fetchMenu() {
apiClient.fetchMenu { [weak self] foodCatalog, error in
if let error = error {
if error == .parsingError {
self?.showMessage("Ошибка парсинга данных")
}
return
}
self?.foodCatalog = foodCatalog
self?.foodCategoryTableView.reloadData()
}
}
private func showMessage(_ message: String) {
let alertViewController = UIAlertController(title: "Triton", message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default)
alertViewController.addAction(okAction)
present(alertViewController, animated: true)
}
}
extension MenuLookViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let category = foodCatalog?.foodCategories[section] else { fatalError("KEK") }
let headerView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.frame.width, height: 50))
let block = UIView()
block.frame = CGRect.init(x: 0, y: 0, width: headerView.frame.width, height: headerView.frame.height - 20)
block.backgroundColor = .white
block.alpha = 1.0
let label = UILabel()
label.frame = CGRect.init(x: 15, y: 0, width: headerView.frame.width, height: headerView.frame.height - 20)
label.text = category.categoryName
label.textColor = .brown
block.addSubview(label)
headerView.addSubview(block)
return headerView
}
func numberOfSections(in tableView: UITableView) -> Int {
return foodCatalog?.foodCategories.count ?? 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
guard let category = foodCatalog?.foodCategories[section] else { fatalError("KEK") }
return category.categoryName
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 105.0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CategoryCell", for: indexPath) as! CategoryCell
cell.onProductTap = { [weak self] product in
self?.dataToPass = product
self?.performSegue(withIdentifier: "justSegue", sender: nil)
}
guard let category = foodCatalog?.foodCategories[indexPath.section] else { fatalError("KEK") }
cell.setup(for: category)
let separatorLine = UIView.init(frame: CGRect(x: 0, y: cell.frame.height - 1, width: cell.frame.width, height: 1))
separatorLine.backgroundColor = .black
cell.addSubview(separatorLine)
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! FoodCheckViewController
vc.foodInfoToShow = self.dataToPass
}
}
|
import Foundation
import RxSwift
public struct URLConstants {
static let albumsURL = "https://jsonplaceholder.typicode.com/albums"
static let albumPhotosURL = "https://jsonplaceholder.typicode.com/photos"
}
protocol AlbumServiceType {
func getAlbums() -> Observable<[Album]>
func getPhotos(forAlbum album:Album) -> Observable<[AlbumPhoto]>
}
class AlbumService: AlbumServiceType {
var apiClient:ApiClientType
init(apiClient:ApiClientType){
self.apiClient = apiClient
}
func getAlbums() -> Observable<[Album]> {
let albumsURL: URL = URL(string:URLConstants.albumsURL)!
let resource = Resource(url: albumsURL, parameters: nil)
return apiClient.getEntitiyList(forResource: resource)
}
func getPhotos(forAlbum album:Album) -> Observable<[AlbumPhoto]> {
let albumPhotosURL: URL = URL(string:URLConstants.albumPhotosURL)!
let parameters: ParametersDictionary = ["albumId":album.identifier, "userId":album.userId]
let resource = Resource(url: albumPhotosURL, parameters: parameters)
return apiClient.getEntitiyList(forResource: resource)
}
}
|
import Foundation
import PathKit
import XCTest
@testable import XcodeProj
class PBXBatchUpdaterTests: XCTestCase {
func test_addFile_useMainProjectGroup() {
let sourceRoot = Path.temporary
let mainGroupPath = UUID().uuidString
let proj = fillAndCreateProj(
sourceRoot: sourceRoot,
mainGroupPath: mainGroupPath
)
let project = proj.projects.first!
try! proj.batchUpdate(sourceRoot: sourceRoot) { updater in
let fileName = "file.swift"
let filePath = Path("\(sourceRoot.string)\(mainGroupPath)/\(fileName)")
try createFile(at: filePath)
let file = try updater.addFile(to: project, at: filePath)
let fileFullPath = try file.fullPath(sourceRoot: sourceRoot)
XCTAssertEqual(
fileFullPath,
filePath
)
}
XCTAssertEqual(proj.fileReferences.count, 2)
XCTAssertEqual(proj.groups.count, 1)
}
func test_addFile_withSubgroups() {
let sourceRoot = Path.temporary
let mainGroupPath = UUID().uuidString
let proj = fillAndCreateProj(
sourceRoot: sourceRoot,
mainGroupPath: mainGroupPath
)
let project = proj.projects.first!
let subgroupNames = (0 ... 5).map { _ in UUID().uuidString }
let expectedGroupCount = 1 + subgroupNames.count
try! proj.batchUpdate(sourceRoot: sourceRoot) { updater in
let fileName = "file.swift"
let subgroupPath = subgroupNames.joined(separator: "/")
let filePath = Path("\(sourceRoot.string)\(mainGroupPath)/\(subgroupPath)/\(fileName)")
try createFile(at: filePath)
let file = try updater.addFile(to: project, at: filePath)
let fileFullPath = try file.fullPath(sourceRoot: sourceRoot)
XCTAssertEqual(
fileFullPath,
filePath
)
}
XCTAssertEqual(proj.fileReferences.count, 2)
XCTAssertEqual(proj.groups.count, expectedGroupCount)
}
func test_addFile_byFileName() {
let sourceRoot = Path.temporary
let mainGroupPath = UUID().uuidString
let proj = fillAndCreateProj(
sourceRoot: sourceRoot,
mainGroupPath: mainGroupPath
)
let project = proj.projects.first!
let mainGroup = project.mainGroup!
try! proj.batchUpdate(sourceRoot: sourceRoot) { updater in
let fileName = "file.swift"
let filePath = Path("\(sourceRoot.string)\(mainGroupPath)/\(fileName)")
try createFile(at: filePath)
let file = try updater.addFile(to: mainGroup, fileName: fileName)
let fileFullPath = try file.fullPath(sourceRoot: sourceRoot)
XCTAssertEqual(
fileFullPath,
filePath
)
}
XCTAssertEqual(proj.fileReferences.count, 2)
XCTAssertEqual(proj.groups.count, 1)
}
func test_addFile_alreadyExisted() {
let sourceRoot = Path.temporary
let mainGroupPath = UUID().uuidString
let proj = fillAndCreateProj(
sourceRoot: sourceRoot,
mainGroupPath: mainGroupPath
)
let project = proj.projects.first!
let mainGroup = project.mainGroup!
try! proj.batchUpdate(sourceRoot: sourceRoot) { updater in
let fileName = "file.swift"
let filePath = Path("\(sourceRoot.string)\(mainGroupPath)/\(fileName)")
try createFile(at: filePath)
let firstFile = try updater.addFile(to: project, at: filePath)
let secondFile = try updater.addFile(to: mainGroup, fileName: fileName)
let firstFileFullPath = try firstFile.fullPath(sourceRoot: sourceRoot)
let secondFileFullPath = try secondFile.fullPath(sourceRoot: sourceRoot)
XCTAssertEqual(
firstFileFullPath,
filePath
)
XCTAssertEqual(
secondFileFullPath,
filePath
)
XCTAssertEqual(
firstFile,
secondFile
)
}
XCTAssertEqual(proj.fileReferences.count, 2)
XCTAssertEqual(proj.groups.count, 1)
}
func test_addFile_alreadyExistedWithSubgroups() {
let sourceRoot = Path.temporary
let mainGroupPath = UUID().uuidString
let proj = fillAndCreateProj(
sourceRoot: sourceRoot,
mainGroupPath: mainGroupPath
)
let project = proj.projects.first!
let subgroupNames = (0 ... 5).map { _ in UUID().uuidString }
let expectedGroupCount = 1 + subgroupNames.count
try! proj.batchUpdate(sourceRoot: sourceRoot) { updater in
let fileName = "file.swift"
let subgroupPath = subgroupNames.joined(separator: "/")
let filePath = Path("\(sourceRoot.string)\(mainGroupPath)/\(subgroupPath)/\(fileName)")
try createFile(at: filePath)
let firstFile = try updater.addFile(to: project, at: filePath)
let parentGroup = proj.groups.first(where: { $0.path == subgroupNames.last! })!
let secondFile = try updater.addFile(to: parentGroup, fileName: fileName)
let firstFileFullPath = try firstFile.fullPath(sourceRoot: sourceRoot)
let secondFileFullPath = try secondFile.fullPath(sourceRoot: sourceRoot)
XCTAssertEqual(
firstFileFullPath,
filePath
)
XCTAssertEqual(
secondFileFullPath,
filePath
)
XCTAssertEqual(
firstFile,
secondFile
)
}
XCTAssertEqual(proj.fileReferences.count, 2)
XCTAssertEqual(proj.groups.count, expectedGroupCount)
}
private func fillAndCreateProj(sourceRoot _: Path, mainGroupPath: String) -> PBXProj {
let proj = PBXProj.fixture()
let fileref = PBXFileReference(sourceTree: .group,
fileEncoding: 1,
explicitFileType: "sourcecode.swift",
lastKnownFileType: nil,
path: "path")
proj.add(object: fileref)
let group = PBXGroup(children: [fileref],
sourceTree: .group,
name: "group",
path: mainGroupPath)
proj.add(object: group)
let project = PBXProject.fixture(mainGroup: group)
proj.add(object: project)
return proj
}
private func createFile(at filePath: Path) throws {
let directoryURL = filePath.url.deletingLastPathComponent()
try FileManager.default.createDirectory(
at: directoryURL,
withIntermediateDirectories: true
)
try Data().write(to: filePath.url)
}
}
|
//
// File.swift
//
//
// Created by Mitch Lang on 1/31/20.
//
import Foundation
public protocol XRPWebSocketDelegate {
func onConnected(connection: XRPWebSocket)
func onDisconnected(connection: XRPWebSocket, error: Error?)
func onError(connection: XRPWebSocket, error: Error)
func onResponse(connection: XRPWebSocket, response: XRPWebSocketResponse)
func onStream(connection: XRPWebSocket, object: NSDictionary)
}
public protocol XRPWebSocket {
func send(text: String)
func send(data: Data)
func connect(host: String)
func disconnect()
var delegate: XRPWebSocketDelegate? {
get
set
}
// convenience methods
func subscribe(account: String)
}
class _WebSocket: NSObject {
var delegate: XRPWebSocketDelegate?
internal override init() {}
fileprivate func handleResponse(connection: XRPWebSocket, data: Data) {
if let response = try? JSONDecoder().decode(XRPWebSocketResponse.self, from: data) {
self.delegate?.onResponse(connection: connection, response: response)
} else if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
self.delegate?.onStream(connection: connection, object: json)
}
}
}
#if canImport(WebSocketKit)
import WebSocketKit
class LinuxWebSocket: _WebSocket, XRPWebSocket {
var ws: WebSocket!
func send(text: String) {
if ws != nil && !ws.isClosed {
ws.send(text)
}
}
func send(data: Data) {
if ws != nil && !ws.isClosed {
ws.send([UInt8](data))
}
}
func connect(host: String) {
let client = WebSocketClient(eventLoopGroupProvider: .shared(eventGroup))
try! client.connect(scheme: "wss", host: host, port: 443, onUpgrade: { (_ws) -> () in
self.ws = _ws
}).wait()
self.delegate?.onConnected(connection: self)
self.ws.onText { (ws, text) in
let data = text.data(using: .utf8)!
self.handleResponse(connection: self, data: data)
}
self.ws.onBinary { (ws, byteBuffer) in
fatalError()
}
_ = self.ws.onClose.map {
self.delegate?.onDisconnected(connection: self, error: nil)
}
}
func disconnect() {
_ = ws.close()
}
}
#elseif !os(Linux)
import Foundation
@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
class AppleWebSocket: _WebSocket, XRPWebSocket, URLSessionWebSocketDelegate {
var webSocketTask: URLSessionWebSocketTask!
var urlSession: URLSession!
let delegateQueue = OperationQueue()
var connected: Bool = false
func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) {
self.connected = true
self.delegate?.onConnected(connection: self)
}
func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
self.delegate?.onDisconnected(connection: self, error: nil)
self.connected = false
}
func connect(host: String) {
let url = URL(string: "wss://" + host + "/")!
urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: delegateQueue)
webSocketTask = urlSession.webSocketTask(with: url)
webSocketTask.resume()
self.connected = true
listen()
}
func disconnect() {
webSocketTask.cancel(with: .goingAway, reason: nil)
}
func listen() {
webSocketTask.receive { result in
switch result {
case .failure(let error):
self.delegate?.onError(connection: self, error: error)
case .success(let message):
switch message {
case .string(let text):
let data = text.data(using: .utf8)!
self.handleResponse(connection: self, data: data)
case .data(let data):
self.handleResponse(connection: self, data: data)
@unknown default:
fatalError()
}
self.listen()
}
}
}
func send(text: String) {
if self.connected {
webSocketTask.send(URLSessionWebSocketTask.Message.string(text)) { error in
if let error = error {
self.delegate?.onError(connection: self, error: error)
}
}
}
}
func send(data: Data) {
if self.connected {
webSocketTask.send(URLSessionWebSocketTask.Message.data(data)) { error in
if let error = error {
self.delegate?.onError(connection: self, error: error)
}
}
}
}
}
#endif
|
//
// DictionaryExtension.swift
// FFAdmin
//
// Created by an.trantuan on 10/8/19.
// Copyright © 2019 an.trantuan. All rights reserved.
//
import Foundation
import UIKit
// MARK: API for user define
extension Dictionary {
// swiftlint:disable all
func stringFromHttpParameters() -> String {
let parameterArray = self.map { (key, value) -> String in
let percentEscapedKey = (key as! String).addingPercentEncodingForURLQueryValue()!
let percentEscapedValue = (String(describing: value)).addingPercentEncodingForURLQueryValue()!
return "\(percentEscapedKey)=\(percentEscapedValue)"
}
return self.isEmpty ? parameterArray.joined(separator: "&") : ("?" + parameterArray.joined(separator: "&"))
}
// swiftlint:enable all
}
extension String {
func addingPercentEncodingForURLQueryValue() -> String? {
let allowedCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~")
return self.addingPercentEncoding(withAllowedCharacters: allowedCharacters)
}
func language() -> String? {
let tagger = NSLinguisticTagger(tagSchemes: [NSLinguisticTagScheme.language], options: 0)
tagger.string = self
return tagger.tag(at: 0, scheme: NSLinguisticTagScheme.language, tokenRange: nil, sentenceRange: nil).map { $0.rawValue }
}
func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
return ceil(boundingBox.height)
}
func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
return ceil(boundingBox.width)
}
func getDateFromUTC() -> Date? {
let dateFormater = DateFormatter()
dateFormater.locale = Locale.current
dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormater.date(from: self)
return date
}
func getDateFromUTC2() -> Date? {
let dateFormater = DateFormatter()
dateFormater.locale = Locale.current
dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormater.date(from: self)
return date
}
func getDate() -> Date? {
let dateFormater = DateFormatter()
dateFormater.locale = Locale.current
dateFormater.dateFormat = "yyyy-MM-dd"
let date = dateFormater.date(from: self)
return date
}
}
extension Date {
static var currentTimeStamp: Int64 {
return Int64(Date().timeIntervalSince1970 * 1000)
}
}
protocol Reusable {
static var reuseID: String {get}
}
extension Reusable {
static var reuseID: String {
return String(describing: self)
}
}
extension UITableViewCell: Reusable {}
extension UIViewController: Reusable {}
extension UITableView {
func dequeueReusableCell<T>(ofType cellType: T.Type = T.self, at indexPath: IndexPath) -> T where T: UITableViewCell {
guard let cell = dequeueReusableCell(withIdentifier: cellType.reuseID,
for: indexPath) as? T else {
fatalError()
}
return cell
}
}
extension UIStoryboard {
func instantiateViewController<T>(ofType type: T.Type = T.self) -> T where T: UIViewController {
guard let viewController = instantiateViewController(withIdentifier: type.reuseID) as? T else {
fatalError()
}
return viewController
}
}
extension UITextField {
}
|
//
// DynamoTransaction.swift
// Tipper
//
// Created by Ryan Romanchuk on 6/14/15.
// Copyright (c) 2015 Ryan Romanchuk. All rights reserved.
//
import Foundation
import TwitterKit
import SwiftyJSON
import AWSDynamoDB
class DynamoSettings: AWSDynamoDBObjectModel, AWSDynamoDBModeling, ModelCoredataMapable {
var FundAmount: String?
var TipAmount: String?
var FeeAmount: String?
var Version: String?
static func dynamoDBTableName() -> String! {
return "TipperSettings"
}
static func hashKeyAttribute() -> String! {
return "Version"
}
func lookupProperty() -> String {
return DynamoSettings.lookupProperty()
}
class func lookupProperty() -> String {
return "Version"
}
func lookupValue() -> String {
return self.Version!
}
override func isEqual(anObject: AnyObject?) -> Bool {
return super.isEqual(anObject)
}
}
|
//
// riderView.swift
// ParseStarterProject-Swift
//
// Created by Pedro Neves Alvarez on 5/27/17.
// Copyright © 2017 Parse. All rights reserved.
//
import UIKit
import Parse
import MapKit
import CoreLocation
class riderView: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
struct Alert{
var title: String
var message: String
}
@IBOutlet weak var map: MKMapView!
@IBOutlet weak var callButton: UIButton!
var locationManager = CLLocationManager()
var userLocation: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0, longitude: 0)
var requestActive: Bool = true
var driverOnTheway: Bool = false
private func setUpLocationManager(){
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
public func createAlert(alerting: Alert){
let alert = UIAlertController(title: alerting.title,message: alerting.message,preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
private func cancel(){
self.callButton.setTitle("call", for: [])
requestActive = false
}
@IBAction func call(_ sender: Any) {
if requestActive{
cancel()
let query = PFQuery(className: "riderRequest")
query.whereKey("username", equalTo: PFUser.current()?.username! as Any)
query.findObjectsInBackground(block: { (objects, error) in
if let riderRequests = objects{
for riderRequest in riderRequests{
riderRequest.deleteInBackground()
}
}
})
}
else{
if userLocation.latitude != 0 && userLocation.longitude != 0{
requestActive = true
let riderRequest = PFObject(className: "riderRequest")
self.callButton.setTitle("cancel", for: [])
riderRequest["username"] = PFUser.current()?.username
riderRequest["location"] = PFGeoPoint(latitude: userLocation.latitude, longitude: userLocation.longitude)
riderRequest.saveInBackground(block: { (success, error) in
if success{
print("called an uber")
}
else{
self.cancel()
let alert = Alert(title: "could not call uber", message: "Please try again")
self.createAlert(alerting: alert)
}
})
}
else{
let alert = Alert(title: "could not call uber", message: "cannot access your location")
createAlert(alerting: alert)
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "logoutSegue"{
locationManager.stopUpdatingLocation()
PFUser.logOut()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Did update")
let location = locations[0]
if !driverOnTheway{
userLocation = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
let span = MKCoordinateSpanMake(0.01, 0.01)
let region = MKCoordinateRegionMake(userLocation, span)
self.map.setRegion(region, animated: true)
self.map.removeAnnotations(self.map.annotations)
self.map.showsUserLocation = true
let annotation = MKPointAnnotation()
annotation.coordinate = userLocation
annotation.title = "You are here"
self.map.addAnnotation(annotation)
}
let query = PFQuery(className: "riderRequest")
query.whereKey("username", equalTo: PFUser.current()?.username! as Any)
query.findObjectsInBackground(block: { (objects, error) in
if let riderRequests = objects{
for riderRequest in riderRequests{
riderRequest["location"] = PFGeoPoint(latitude: self.userLocation.latitude, longitude: self.userLocation.longitude)
riderRequest.saveInBackground()
}
}
})
if requestActive{
let query = PFQuery(className: "riderRequest")
query.whereKey("username", equalTo: PFUser.current()?.username as Any)
query.findObjectsInBackground(block: { (objects, error) in
if let riderRequests = objects{
for riderRequest in riderRequests{
if let driverUsername = riderRequest["driverResponded"]{
let query = PFQuery(className: "driverLocation")
query.whereKey("username", equalTo: driverUsername)
query.findObjectsInBackground(block: { (objects, error) in
if let driverLocations = objects{
for driverLocationObject in driverLocations{
if let driverLocation = driverLocationObject["locations"] as? PFGeoPoint{
self.driverOnTheway = true
let driverCLLocation = CLLocation(latitude: driverLocation.latitude, longitude: driverLocation.longitude)
let riderCLLocation = CLLocation(latitude: self.userLocation.latitude, longitude: self.userLocation.longitude)
let distance = riderCLLocation.distance(from: driverCLLocation) / 1000
let roundedDistance = round(distance * 100) / 100
print("\(driverLocation) is printed" )
self.callButton.setTitle("driver is \(roundedDistance) km away", for: [])
let latdelta = abs(driverLocation.latitude - self.userLocation.latitude) * 2 + 0.05
let londelta = abs(driverLocation.longitude - self.userLocation.longitude) * 2 + 0.05
let region = MKCoordinateRegion(center: self.userLocation, span: MKCoordinateSpan(latitudeDelta: latdelta, longitudeDelta: londelta))
self.map.removeAnnotations(self.map.annotations)
self.map.setRegion(region, animated: true)
let userLocationAnnotation = MKPointAnnotation()
userLocationAnnotation.coordinate = self.userLocation
userLocationAnnotation.title = "Your location"
self.map.addAnnotation(userLocationAnnotation)
let driverLocationAnnotation = MKPointAnnotation()
driverLocationAnnotation.coordinate = CLLocationCoordinate2D(latitude: driverLocation.latitude, longitude: driverLocation.longitude)
driverLocationAnnotation.title = "Your driver"
self.map.addAnnotation(driverLocationAnnotation)
}
}
}
})
}
}
}
})
}
}
override func viewDidLoad() {
super.viewDidLoad()
print(userLocation)
cancel()
callButton.isHidden = true
let query = PFQuery(className: "riderRequest")
query.whereKey("username", equalTo: PFUser.current()?.username! as Any)
query.findObjectsInBackground(block: { (objects, error) in
if let object = objects{
if (objects?.count)! > 0{
self.requestActive = true
self.callButton.setTitle("cancel", for: [])
}
}
self.callButton.isHidden = false
})
setUpLocationManager()
//print(locationManager.location!)
// Do any additional setup after loading the view.
}
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.
}
*/
}
|
//
// PSAddBidder.swift
// PayStation
//
// Created by Saravanan on 29/11/17.
// Copyright © 2017 SDI. All rights reserved.
//
import UIKit
class PSAddBidder: UIViewController,TPKeyboardAvoidingScrollViewDelege {
@IBOutlet weak var txtBidder: UITextField!
@IBOutlet weak var txtEmail: UITextField!
@IBOutlet weak var txtName: UITextField!
var bidderType : Int!
var dictBidderObj : NSMutableDictionary?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if(bidderType == 1){
setBorderSytle(isNew: true)
self.title = "Add Bidder"
}else{
setBorderSytle(isNew: false)
self.title = "Check In"
if(dictBidderObj != nil){
txtName.text = dictBidderObj?.value(forKey: "name") as? String
txtBidder.text = dictBidderObj?.value(forKey: "id") as? String
txtEmail.text = dictBidderObj?.value(forKey: "email") as? String
}
}
}
func setBorderSytle(isNew : Bool){
if(isNew == true){
txtBidder.borderStyle = .roundedRect
txtName.borderStyle = .roundedRect
txtEmail.borderStyle = .roundedRect
}else{
txtBidder.borderStyle = .none
txtName.borderStyle = .none
txtEmail.borderStyle = .none
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onSaveSkip(_ sender: Any) {
if(validateFileds() == true){
if(bidderType == 1){
let dictBidder = NSMutableDictionary()
dictBidder.setValue(txtName.text, forKey: "name")
dictBidder.setValue(txtBidder.text, forKey: "id")
dictBidder.setValue(txtEmail.text, forKey: "email")
appDelegate.arrBidder.add(dictBidder)
}else{
dictBidderObj?.setValue(txtName.text?.trim(), forKey: "name")
dictBidderObj?.setValue(txtBidder.text?.trim(), forKey: "id")
dictBidderObj?.setValue(txtEmail.text?.trim(), forKey: "email")
}
appDelegate.saveBidderList()
self.navigationController?.popViewController(animated: true)
}
}
@IBAction func onSaveSwipe(_ sender: Any) {
if(validateFileds() == true){
if(bidderType == 1){
let dictBidder = NSMutableDictionary()
dictBidder.setValue(txtName.text, forKey: "name")
dictBidder.setValue(txtBidder.text, forKey: "id")
dictBidder.setValue(txtEmail.text, forKey: "email")
appDelegate.arrBidder.add(dictBidder)
}else{
dictBidderObj?.setValue(txtName.text?.trim(), forKey: "name")
dictBidderObj?.setValue(txtBidder.text?.trim(), forKey: "id")
dictBidderObj?.setValue(txtEmail.text?.trim(), forKey: "email")
}
appDelegate.saveBidderList()
//Check point of scale insall or not
// appDelegate.makePayment(userInfo: "TestId")
self.navigationController?.popViewController(animated: true)
}
}
@IBAction func onBack(_ sender: Any) {
self.navigationController?.popViewController(animated: true)
}
func textField(_ textField: UITextField!, shouldChangeCharactersIn range: NSRange, replacementString string: String!) -> Bool {
return true
}
func validateFileds()->Bool{
if(txtName.text?.trim().characters.count == 0){
txtName.placeHolderColor = UIColor.red
txtName.placeholder = "Enter name"
return false
}else if(txtEmail.text?.trim().characters.count == 0){
txtEmail.placeHolderColor = UIColor.red
txtEmail.placeholder = "Enter email"
return false
}else if(txtBidder.text?.trim().characters.count == 0){
txtBidder.placeHolderColor = UIColor.red
txtBidder.placeholder = "Enter bidder"
return false
}else if(!((txtEmail.text?.isValidEmail())!)){
appDelegate.showAlert(message: "Invalid Email Id")
return false
}
return true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// SummaryTableViewController.swift
// Stock
//
// Created by Abigail Ng on 10/17/19.
// Copyright © 2019 Abigail Ng. All rights reserved.
//
import UIKit
import Firebase
class SummaryTableViewController: UITableViewController {
var items: [Item] = []
@IBOutlet var SectionTitle: UINavigationItem!
var sectionTitle: String = ""
override func viewDidLoad() {
super.viewDidLoad()
SectionTitle.title = sectionTitle
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return items.count
} else {
return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)
let item = items[indexPath.row]
cell.textLabel?.text = "\(item.name)"
cell.detailTextLabel?.text = "\(item.count)"
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let detailViewController = segue.destination as? DetailViewController,
let index = tableView.indexPathForSelectedRow?.row
{
detailViewController.item = items[index]
}
}
@IBAction func unwindFromDetail(_ sender: UIStoryboardSegue) {
if sender.source is DetailViewController {
if let senderVC = sender.source as? DetailViewController,
let index = tableView.indexPathForSelectedRow?.row {
items[index] = senderVC.item
}
tableView.reloadData()
}
}
@IBAction func unwindFromAdd(_ sender: UIStoryboardSegue) {
if sender.source is AddViewController {
if let senderVC = sender.source as? AddViewController {
senderVC.createItem()
items.append(senderVC.item)
}
tableView.reloadData()
}
}
@IBAction func unwindFromCancel(_ sender: UIStoryboardSegue) {
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
items.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
@IBAction func addButtonPressed(_ sender: Any) {
items.append(Item(name: "new item!", count: 1, description: "the details"))
tableView.reloadData()
}
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
@IBAction func add(_ unwindSegue: UIStoryboardSegue) {
if let detailViewController = unwindSegue.source as? DetailViewController {
items.append(detailViewController.item)
}
}
}
|
//
// DetailViewController.swift
// severyn_katolyk_SimpleBooks
//
// Created by Severyn-Vsewolod Katolyk on 6/25/16.
// Copyright © 2016 Severyn-Vsewolod Katolyk. All rights reserved.
//
import UIKit
import FBSDKShareKit
class DetailViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var authorLabel: UILabel!
@IBOutlet weak var rankLabel: UILabel!
@IBOutlet weak var amazonLabel: UILabel!
@IBOutlet weak var likeButton: UIBarButtonItem!
@IBOutlet weak var shareButton: UIBarButtonItem!
@IBOutlet weak var descriptionTextView: UITextView!
@IBOutlet weak var coverImageView: UIImageView!
enum LikeTitle {
static let kDislike = "Dislike"
static let kLike = "Like"
}
var bookImage: UIImage?
var bookInfo: BookInfo!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if !Reachability.isConnectedToNetwork() {
shareButton.enabled = false
}
if Book.bookExist(bookInfo.title!, author: bookInfo.author!) {
likeButton.title = LikeTitle.kDislike
} else {
likeButton.title = LikeTitle.kLike
}
if let image = bookImage {
coverImageView.image = image
}
if let title = bookInfo?.title {
titleLabel.text = title
} else {
titleLabel.text = "---"
}
if let author = bookInfo?.author {
authorLabel.text = author
} else {
authorLabel.text = "---"
}
if let rank = bookInfo?.rank {
rankLabel.text = "\(rank)"
} else {
rankLabel.text = "---"
}
if let amazonURL = bookInfo?.amazonURL {
amazonLabel.text = "Amazon URL: \n" + amazonURL
} else {
amazonLabel.text = "---"
}
if let description = bookInfo?.description {
descriptionTextView.text = description
} else {
descriptionTextView.text = "---"
}
}
// MARK: - IBActions
@IBAction func sharedTapped(sender: AnyObject) {
let content = FBSDKShareLinkContent()
if coverImageView.image != nil {
content.imageURL = NSURL(string: bookInfo.imageURL!)
}
if let title = bookInfo.title {
content.contentTitle = title
}
var contentDescription = "Author: "
if bookInfo.author != nil {
contentDescription += bookInfo.author!
} else {
contentDescription += "---"
}
contentDescription += ". Description: "
if bookInfo.description != nil {
contentDescription += bookInfo.description!
} else {
contentDescription += "---."
}
content.contentDescription = contentDescription
if let amazonURL = bookInfo.amazonURL {
content.contentURL = NSURL(string: amazonURL)
}
FBSDKShareDialog.showFromViewController(self, withContent: content, delegate: nil)
}
@IBAction func likeTapped(sender: AnyObject) {
if Book.bookExist(bookInfo.title!, author: bookInfo.author!) {
Book.delete(bookInfo.title!, author: bookInfo.author!)
likeButton.title = LikeTitle.kLike
} else {
if let image = coverImageView.image {
ImageManager.saveImage(image, title: bookInfo.title!)
}
Book.save(bookInfo)
likeButton.title = LikeTitle.kDislike
}
}
}
|
//
// MediaTableViewCell.swift
// Blocstagram
//
// Created by Jin Kato on 12/20/15.
// Copyright © 2015 Jin Kato. All rights reserved.
//
import UIKit
protocol FeedCellDelegate {
func imageTapped(cell: FeedCell)
func imageLongPressed()
func imageDoubleTapped(cell: FeedCell)
}
class FeedCell: BaseTableCell {
var cellDelegate: FeedCellDelegate?
var feed:Feed?{
didSet{
let fullName = feed?.user?.fullName as! String
let caption = feed?.caption as! String
let userCaptionString = "\(fullName) \(caption)"
let fullNameCount:Int = fullName.characters.count
let usernameCaptionAttribute = NSMutableAttributedString(string: userCaptionString, attributes: [NSFontAttributeName: Fonts.lightFont])
usernameCaptionAttribute.addAttribute(NSFontAttributeName, value: Fonts.boldFont, range: NSRange(location:0,length:fullNameCount))
usernameCaptionAttribute.addAttribute(NSForegroundColorAttributeName, value: Fonts.linkColor, range: NSRange(location:0,length:fullNameCount))
usernameCaptionAttribute.addAttribute(NSKernAttributeName, value: 2, range: NSRange(location:0,length:fullNameCount))
self.usernameAndCaptionLabel.text = userCaptionString
self.usernameAndCaptionLabel.attributedText = usernameCaptionAttribute
mainImageView.image = nil
let cellImage = feed?.mediaURL as! String
Utils.asyncLoadImageWithAlamofire(cellImage, imageView: mainImageView)
}
}
var commentArray:[Comment]?{
didSet{
self.commentLabel.text = Utils.concatenateCommentArray(commentArray!)
self.commentLabel.font = Fonts.lightFont
self.commentLabel.attributedText = Utils.commentAttribute(commentArray!)
}
}
var mainImageView: UIImageView = {
let imageView = UIImageView()
imageView.backgroundColor = UIColor.blackColor()
return imageView
}()
var usernameAndCaptionLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.backgroundColor = UIColor(red: 0.933, green: 0.933, blue: 0.933, alpha: 1)
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByCharWrapping
return label
}()
var commentLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByCharWrapping
label.backgroundColor = UIColor(red: 0.898, green: 0.898, blue: 0.898, alpha: 1)
return label
}()
// ------------------------------------------------------------------------------------------ //
override func setupView(){
let viewWidth = UIScreen.mainScreen().bounds.width
self.addSubview(self.mainImageView)
self.addSubview(self.usernameAndCaptionLabel)
self.addSubview(self.commentLabel)
let viewDict = ["mainImageView":mainImageView, "usernameAndCaptionLabel":usernameAndCaptionLabel, "commentLabel":commentLabel]
myAddConstraint("H:|[mainImageView]|", view: mainImageView, viewsDictionary: viewDict)
myAddConstraint("V:|[mainImageView(\(viewWidth))]", view: mainImageView, viewsDictionary: viewDict)
myAddConstraint("H:|[usernameAndCaptionLabel]|", view: usernameAndCaptionLabel, viewsDictionary: viewDict)
myAddConstraint("V:[mainImageView]-0-[usernameAndCaptionLabel]", view: usernameAndCaptionLabel, viewsDictionary: viewDict)
myAddConstraint("H:|[commentLabel]|", view: commentLabel, viewsDictionary: viewDict)
myAddConstraint("V:[usernameAndCaptionLabel]-0-[commentLabel]", view: commentLabel, viewsDictionary: viewDict)
self.mainImageView.userInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: "tapFired:")
self.mainImageView.addGestureRecognizer(tap)
let longPress = UILongPressGestureRecognizer(target: self, action: "longPressFired:")
self.mainImageView.addGestureRecognizer(longPress)
let doubleTap = UITapGestureRecognizer(target: self, action: "doubleFired:")
doubleTap.numberOfTapsRequired = 2
self.mainImageView.addGestureRecognizer(doubleTap)
tap.requireGestureRecognizerToFail(doubleTap)
}
// ------------------------------------------------------------------------------------------ //
func longPressFired(gestureRecognizer: UIGestureRecognizer) {
if self.editing == false {
setSelectedFeedValue()
if( gestureRecognizer.state == UIGestureRecognizerState.Began ){
cellDelegate?.imageLongPressed()
}
}
}
func tapFired(gestureRecognizer: UIGestureRecognizer) {
setSelectedFeedValue()
if self.editing == false {
cellDelegate?.imageTapped(self)
}
}
func doubleFired(gestureRecognizer: UIGestureRecognizer) {
if self.editing == false {
cellDelegate?.imageDoubleTapped(self)
}
}
func setSelectedFeedValue(){
DataSource.sharedInstance.selectedFeed = feed
DataSource.sharedInstance.selectedFeed?.image = self.mainImageView.image!
}
}
|
//
// TableViewCell.swift
// UICollectionInsideUITable
//
// Created by Gulsah Altiparmak on 19.02.2021.
//
import UIKit
import Alamofire
protocol CollectionViewCellDelegate: class {
func collectionView(collectionviewcell: CollectionViewCell?, index: Int, didTappedInTableViewCell: TableViewCell)
}
class TableViewCell: UITableViewCell {
static var sender : Result?
weak var cellDelegate: CollectionViewCellDelegate?
var popularMovies = [[Result?]]()
var row = 0
@IBOutlet weak var collectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
if popularMovies.isEmpty{
for item in Constants.sortValue{
self.getMovieList(sort: item)
}
collectionView.reloadData()
}
collectionView.delegate = self
collectionView.dataSource = self
}
func getMovieList(sort:String) {
let url = Constants.baseUrl + "discover/movie"
let params = [ "api_key":Constants.apiKey, "language":"en-US" ,"sort_by": sort,"include_adult":"false","include_video":"true","page":"1"]
AF.request(url,method:.get,parameters:params).responseJSON{ res in
if (res.response?.statusCode == 200){
let movieList = try? JSONDecoder().decode(MovieList.self, from: res.data!)
self.popularMovies.append((movieList?.results!)!)
}
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func configure() {
collectionView.scrollToItem(at: IndexPath(item: 1, section: 0), at: .left, animated: false)
let flowLayout = UICollectionViewFlowLayout()
flowLayout.itemSize = CGSize(width: 355, height: 290)
flowLayout.minimumLineSpacing = 5
flowLayout.minimumInteritemSpacing = 5
flowLayout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
flowLayout.scrollDirection = .horizontal
self.collectionView.setCollectionViewLayout(flowLayout, animated: false)
}
}
extension TableViewCell : UICollectionViewDelegate ,UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "big", for: indexPath) as! CollectionViewCell
row = indexPath.item
print("\(indexPath.row) \(collectionView.tag) \(indexPath.item)")
if !(popularMovies.isEmpty){
let item = popularMovies[collectionView.tag][indexPath.item]
cell.image.contentMode = .scaleAspectFit
cell.title.text = item?.title
cell.descriptionLabel.text = (String((item?.voteAverage!)!))
// cell.configure(with:(item))
if item?.posterPath != nil {
cell.image.load(urlString: (Constants.imageBaseUrl + ((item?.posterPath)!)) )
}else{
cell.image.load(urlString: Constants.defaultImage)
}
}
return cell
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageFloat = (scrollView.contentOffset.x / scrollView.frame.size.width)
let pageInt = Int(round(pageFloat))
switch pageInt {
case 0:
collectionView.scrollToItem(at: [0, 0], at: .right, animated: false)
case 16:
collectionView.scrollToItem(at: [0, 0], at: .left, animated: false)
default:
break
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
TableViewCell.sender = popularMovies[collectionView.tag][indexPath.item]
let cell = collectionView.cellForItem(at: indexPath) as? CollectionViewCell
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyBoard.instantiateViewController(identifier: "MovieDetail") as! MovieDetail
print("I'm tapping the \(indexPath.item)")
print("sender : \(TableViewCell.sender)")
self.cellDelegate?.collectionView(collectionviewcell: cell, index: indexPath.item, didTappedInTableViewCell: self)
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
}
|
//
// ReadWriteLock.swift
//
//
// Created by Carmelo Ruyman on 18/11/2020.
//
import Foundation
class ReadWriteLock: Hashable {
static func == (lhs: ReadWriteLock, rhs: ReadWriteLock) -> Bool {
lhs.concurentQueue.label == rhs.concurentQueue.label
}
func hash(into hasher: inout Hasher) {
hasher.combine(concurentQueue.label)
}
let concurentQueue: DispatchQueue
init(label: String) {
self.concurentQueue = DispatchQueue(label: label, qos: .background, attributes: .concurrent)
}
func read(closure: () -> Void) {
self.concurentQueue.sync {
closure()
}
}
func write(closure: @escaping () -> Void) {
self.concurentQueue.sync(flags: .barrier, execute: {
closure()
})
}
}
|
//
// ViewController.swift
// Hamburguesas en el mundo!
//
// Created by Luis Santamaría on 16/07/16.
// Copyright © 2016 Santamaria Technologies. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var hamburguesa: UILabel!
@IBOutlet weak var pais: UILabel!
@IBOutlet weak var precio: UILabel!
let hamburguesas = ColeccionHamburguesas()
let paises = ColeccionPaises()
let colores = Colores()
let precios = ColeccionPrecios()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func dameHamburguesa(sender: AnyObject) {
let colorLoco = colores.coloresAleatorios()
let paisLoco = paises.paisesAleatorios()
let hamburguesaLoca = hamburguesas.hamburguesaAleatoria()
let preciosLocos = precios.preciosAleatorios()
view.backgroundColor = colorLoco
view.tintColor = colorLoco
hamburguesa.text = hamburguesaLoca
pais.text = paisLoco
precio.text = preciosLocos
}
}
|
//
// VideoPagerCell.swift
// J.YoutubeWatcher
//
// Created by JinYoung Lee on 22/02/2019.
// Copyright © 2019 JinYoung Lee. All rights reserved.
//
import Foundation
import UIKit
class VideoPagerCell: UITableViewCell {
}
|
//
// Copyright (c) 2023 Related Code - https://relatedcode.com
//
// 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 UIKit
//-----------------------------------------------------------------------------------------------------------------------------------------------
class StickersCell: UICollectionViewCell {
@IBOutlet var imageItem: UIImageView!
private var sticker = ""
//-------------------------------------------------------------------------------------------------------------------------------------------
override func prepareForReuse() {
sticker = ""
imageItem.image = nil
}
//-------------------------------------------------------------------------------------------------------------------------------------------
func bindData(_ sticker: String) {
if let path = Media.path(sticker: sticker) {
imageItem.image = UIImage(path: path)
} else {
loadImage(sticker)
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------
func loadImage(_ sticker: String) {
self.sticker = sticker
MediaDownload.sticker(sticker) { [weak self] path, error in
guard let self = self else { return }
if (self.sticker == sticker) {
if (error == nil) {
self.imageItem.image = UIImage(path: path)
} else {
self.loadLater(sticker)
}
}
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------
func loadLater(_ sticker: String) {
DispatchQueue.main.async(after: 0.5) { [weak self] in
guard let self = self else { return }
if (self.sticker == sticker) {
if (self.imageItem.image == nil) {
self.loadImage(sticker)
}
}
}
}
}
|
//
// SHA512.swift
// CryptoKit
//
// Created by Chris Amanse on 01/09/2016.
//
//
import Foundation
public enum SHA512: SHA2Variant {
public static var outputSize: UInt {
return 64
}
public static var blockSize: UInt {
return 128
}
public static var initializationVector: [UInt64] {
return [
0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1,
0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179
]
}
public static var kConstants: [UInt64] {
return [
0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538,
0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe,
0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235,
0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,
0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab,
0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725,
0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed,
0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b,
0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218,
0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53,
0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373,
0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,
0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c,
0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6,
0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc,
0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817
]
}
public static var s0ShiftAndRotateAmounts: (UInt64, UInt64, UInt64) {
return (1, 8, 7)
}
public static var s1ShiftAndRotateAmounts: (UInt64, UInt64, UInt64) {
return (19, 61, 6)
}
public static var S0ShiftAndRotateAmounts: (UInt64, UInt64, UInt64) {
return (28, 34, 39)
}
public static var S1ShiftAndRotateAmounts: (UInt64, UInt64, UInt64) {
return (14, 18, 41)
}
}
|
//
// MenuViewController.swift
// SuperTaxi
//
// Created by Administrator on 6/23/16.
// Copyright © 2016 Jensen Pich. All rights reserved.
//
import UIKit
class MenuViewController: UIViewController {
@IBOutlet var imgPhoto: UIImageView!
@IBOutlet var txtFirstName: UILabel!
var slideOutAnimationEnabled: Bool!
var settingsVC: SettingsViewController!
let UserInformation = UserDefaults.standard
required init?(coder aDecoder: NSCoder) {
self.slideOutAnimationEnabled = true
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.slideOutAnimationEnabled = true
if (UserInformation.string(forKey: UserDetails.THUMBNAIL) != nil){
imgPhoto.load(URL(string: Api.IMAGE_URL + UserInformation.string(forKey: UserDetails.THUMBNAIL)!), placeholderImage: UIImage(named: "user"))
}
imgPhoto.layer.cornerRadius = imgPhoto.frame.size.width / 2
imgPhoto.clipsToBounds = true
txtFirstName.text = UserInformation.string(forKey: UserDetails.NAME)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onHome(_ sender: AnyObject) {
self.revealViewController().revealToggle(animated: true)
}
@IBAction func btnOpenProfile(_ sender: AnyObject) {
if (UserInformation.string(forKey: UserDetails.TYPE)! == "2") {
let viewController = self.storyboard?.instantiateViewController(withIdentifier: "TaxiCreateProfileVC") as? TaxiCreateProfileViewController
viewController?.isEditingProfile = true
self.revealViewController()?.present(viewController!, animated: true, completion: nil)
} else {
let viewController = self.storyboard?.instantiateViewController(withIdentifier: "CreatingUserProfileVC") as? CreatingUserProfileViewController
viewController?.isEditingProfile = true
self.revealViewController()?.present(viewController!, animated: true, completion: nil)
}
self.revealViewController().revealToggle(animated: true)
}
@IBAction func btnSettings(_ sender: AnyObject) {
let viewController = self.storyboard?.instantiateViewController(withIdentifier: "Settings") as? SettingsViewController
self.revealViewController()?.present(viewController!, animated: true, completion: nil)
self.revealViewController().revealToggle(animated: true)
}
@IBAction func btnReportAProblem(_ sender: AnyObject) {
let viewController = self.storyboard?.instantiateViewController(withIdentifier: "ReportID") as? ReportProblemViewController
self.revealViewController()?.present(viewController!, animated: true, completion: nil)
self.revealViewController().revealToggle(animated: true)
}
@IBAction func btnAbout(_ sender: AnyObject) {
let viewController = self.storyboard?.instantiateViewController(withIdentifier: "AboutID") as? AboutViewController
self.revealViewController()?.present(viewController!, animated: true, completion: nil)
self.revealViewController().revealToggle(animated: true)
}
@IBAction func btnHistory(_ sender: AnyObject) {
let viewController = self.storyboard?.instantiateViewController(withIdentifier: "HistoryID") as? HistoryViewController
self.revealViewController()?.present(viewController!, animated: true, completion: nil)
self.revealViewController().revealToggle(animated: true)
}
}
|
class Solution {
func addDigits(_ num: Int) -> Int {
// Solution 1
if num < 10 {
return num
}
var str = String(num)
var result = 0
while str.count > 1 {
result = 0
for char in str {
result += char.wholeNumberValue!
}
str = String(result)
}
return result
// Solution 2
return (num - 1) % 9 + 1
}
}
|
import UIKit
import RealmSwift
class CategoryTableViewController: UITableViewController {
let realm = try! Realm()
var categories: Results<Category>?
override func viewDidLoad() {
super.viewDidLoad()
fetch()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories?.count ?? 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CategoryCell", for: indexPath)
if let category = categories?[indexPath.row] {
cell.textLabel?.text = category.name
cell.accessoryType = .disclosureIndicator
} else {
cell.textLabel?.text = "<Add categories>"
cell.accessoryType = .none
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "goToItems", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationViewController = segue.destination as! TodoListViewController
if let indexPath = tableView.indexPathForSelectedRow {
destinationViewController.category = categories?[indexPath.row]
}
}
@IBAction func addCategory(_ sender: UIBarButtonItem) {
var categoryTextField = UITextField()
let prompt = UIAlertController(title: "New category", message: "", preferredStyle: .alert)
prompt.addTextField { (textField) in
categoryTextField = textField
categoryTextField.placeholder = "Add new category"
}
let add = UIAlertAction(title: "Add", style: .default) { (action) in
let category = Category()
category.name = categoryTextField.text!
self.persist(category: category)
self.tableView.reloadData()
}
prompt.addAction(add)
present(prompt, animated: true, completion: nil)
}
func fetch() {
categories = realm.objects(Category.self)
tableView.reloadData()
}
func persist(category: Category) {
do {
try realm.write {
realm.add(category)
}
} catch {
print("error persisting instances with error: \(error)")
}
}
}
|
//
// RequestViewController.swift
// WeNetwork
//
// Created by Josefina Bustamante on 25/08/2018.
// Copyright © 2018 BiteInc. All rights reserved.
//
import UIKit
class RequestViewController: UIViewController {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var requestTitleLabel: UILabel!
@IBOutlet weak var requestDescriptionLabel: UILabel!
@IBOutlet weak var requestTextView: UITextView!
@IBOutlet weak var dateTitleLabel: UILabel!
@IBOutlet weak var dateDescriptionLabel: UILabel!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var okButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
private func setupUI() {
setupMainView()
setupTitleLabels()
setupDescriptionLabels()
setupRequestTextField()
setupDatePicker()
setupConfirmationButton()
}
private func setupMainView() {
view.backgroundColor = UIColor.lightGray()
containerView.backgroundColor = UIColor.white
containerView.layer.cornerRadius = 8
}
private func setupTitleLabels() {
requestTitleLabel.font = UIFont.mediumFontWithSize(28)
requestTitleLabel.textColor = UIColor.headerTitle()
dateTitleLabel.font = UIFont.mediumFontWithSize(28)
dateTitleLabel.textColor = UIColor.headerTitle()
}
private func setupDescriptionLabels() {
requestDescriptionLabel.font = UIFont.mediumFontWithSize(16)
requestDescriptionLabel.textColor = UIColor.headerSubtitle()
dateDescriptionLabel.font = UIFont.mediumFontWithSize(16)
dateDescriptionLabel.textColor = UIColor.headerSubtitle()
}
private func setupRequestTextField() {
requestTextView.delegate = self
requestTextView.font = UIFont.mediumFontWithSize(18)
requestTextView.textColor = UIColor.userInput()
requestTextView.backgroundColor = UIColor.boxBackground()
requestTextView.layer.borderColor = UIColor.boxBorder().cgColor
requestTextView.layer.borderWidth = 1.0
requestTextView.layer.cornerRadius = 8
requestTextView.clipsToBounds = true
}
private func setupDatePicker() {
datePicker.backgroundColor = UIColor.boxBackground()
datePicker.layer.borderColor = UIColor.boxBorder().cgColor
datePicker.layer.borderWidth = 1.0
datePicker.layer.cornerRadius = 8
}
private func setupConfirmationButton() {
okButton.backgroundColor = UIColor.brand()
okButton.setTitleColor(UIColor.white, for: .normal)
okButton.layer.cornerRadius = okButton.bounds.size.height/2
}
}
extension RequestViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if(text == "\n") {
textView.resignFirstResponder()
return false
}
return true
}
}
|
//
// UsersProvider.swift
// PlatformTests
//
// Created by Łukasz Niedźwiedź on 06/08/2018.
// Copyright © 2018 Niedzwiedz. All rights reserved.
//
import Foundation
import Domain
final class UsersProvider {
static func makeGithubUsers(howManny value: Int) -> [GithubUser] {
var users: [GithubUser] = []
for i in 0..<value {
users.append(GithubUser(username: "No. \(i)", avatarUrl: "https://somepage.pl/someimage.png"))
}
return users
}
static func makeDailymotionUsers(howManny value: Int) -> [DailyMotionUser] {
var users: [DailyMotionUser] = []
for i in 0..<value {
users.append(DailyMotionUser(username: "No. \(i)", avatarUrl: "https://somepage.pl/someimage.png"))
}
return users
}
}
|
//
// Copyright © 2016 Landet. All rights reserved.
//
import UIKit
class SpinnerCollectionViewCell: UICollectionViewCell {
static let reuseIdentifier = "SpinnerCollectionViewCell"
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
override func awakeFromNib() {
super.awakeFromNib()
}
func spin() {
activityIndicator.startAnimating()
}
}
|
///
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
///
public class DFA: CustomStringConvertible {
///
/// A set of all DFA states.
///
public var states = [DFAState: DFAState]()
public var s0: DFAState?
public let decision: Int
///
/// From which ATN state did we create this DFA?
///
public let atnStartState: DecisionState
///
/// `true` if this DFA is for a precedence decision; otherwise,
/// `false`. This is the backing field for _#isPrecedenceDfa_.
///
private let precedenceDfa: Bool
///
/// mutex for states changes.
///
internal private(set) var statesMutex = Mutex()
public convenience init(_ atnStartState: DecisionState) {
self.init(atnStartState, 0)
}
public init(_ atnStartState: DecisionState, _ decision: Int) {
self.atnStartState = atnStartState
self.decision = decision
if let starLoopState = atnStartState as? StarLoopEntryState, starLoopState.precedenceRuleDecision {
let precedenceState = DFAState(ATNConfigSet())
precedenceState.edges = [DFAState]()
precedenceState.isAcceptState = false
precedenceState.requiresFullContext = false
precedenceDfa = true
s0 = precedenceState
}
else {
precedenceDfa = false
s0 = nil
}
}
///
/// Gets whether this DFA is a precedence DFA. Precedence DFAs use a special
/// start state _#s0_ which is not stored in _#states_. The
/// _org.antlr.v4.runtime.dfa.DFAState#edges_ array for this start state contains outgoing edges
/// supplying individual start states corresponding to specific precedence
/// values.
///
/// - returns: `true` if this is a precedence DFA; otherwise,
/// `false`.
/// - seealso: org.antlr.v4.runtime.Parser#getPrecedence()
///
public final func isPrecedenceDfa() -> Bool {
return precedenceDfa
}
///
/// Get the start state for a specific precedence value.
///
/// - parameter precedence: The current precedence.
/// - returns: The start state corresponding to the specified precedence, or
/// `null` if no start state exists for the specified precedence.
///
/// - throws: _ANTLRError.illegalState_ if this is not a precedence DFA.
/// - seealso: #isPrecedenceDfa()
///
public final func getPrecedenceStartState(_ precedence: Int) throws -> DFAState? {
if !isPrecedenceDfa() {
throw ANTLRError.illegalState(msg: "Only precedence DFAs may contain a precedence start state.")
}
guard let s0 = s0, let edges = s0.edges, precedence >= 0, precedence < edges.count else {
return nil
}
return edges[precedence]
}
///
/// Set the start state for a specific precedence value.
///
/// - parameter precedence: The current precedence.
/// - parameter startState: The start state corresponding to the specified
/// precedence.
///
/// - throws: _ANTLRError.illegalState_ if this is not a precedence DFA.
/// - seealso: #isPrecedenceDfa()
///
public final func setPrecedenceStartState(_ precedence: Int, _ startState: DFAState) throws {
if !isPrecedenceDfa() {
throw ANTLRError.illegalState(msg: "Only precedence DFAs may contain a precedence start state.")
}
guard let s0 = s0, let edges = s0.edges, precedence >= 0 else {
return
}
// synchronization on s0 here is ok. when the DFA is turned into a
// precedence DFA, s0 will be initialized once and not updated again
s0.mutex.synchronized {
// s0.edges is never null for a precedence DFA
if precedence >= edges.count {
let increase = [DFAState?](repeating: nil, count: (precedence + 1 - edges.count))
s0.edges = edges + increase
}
s0.edges[precedence] = startState
}
}
///
/// Return a list of all states in this DFA, ordered by state number.
///
public func getStates() -> [DFAState] {
var result = [DFAState](states.keys)
result = result.sorted {
$0.stateNumber < $1.stateNumber
}
return result
}
public var description: String {
return toString(Vocabulary.EMPTY_VOCABULARY)
}
public func toString(_ vocabulary: Vocabulary) -> String {
if s0 == nil {
return ""
}
let serializer = DFASerializer(self, vocabulary)
return serializer.description
}
public func toLexerString() -> String {
if s0 == nil {
return ""
}
let serializer = LexerDFASerializer(self)
return serializer.description
}
}
|
//
// PGPDataExtension.swift
// SwiftPGP
//
// Created by Marcin Krzyzanowski on 05/07/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
import Foundation
extension NSMutableData {
/** Convenient way to append bytes */
internal func appendBytes(arrayOfBytes: [UInt8]) {
self.appendBytes(arrayOfBytes, length: arrayOfBytes.count)
}
}
extension NSData {
public func checksum() -> UInt16 {
var s:UInt32 = 0;
var bytesArray = self.arrayOfBytes()
for (var i = 0; i < bytesArray.count; i++) {
_ = bytesArray[i]
s = s + UInt32(bytesArray[i])
}
s = s % 65536;
return UInt16(s);
}
public func toHexString() -> String {
let count = self.length / sizeof(UInt8)
var bytesArray = [UInt8](count: count, repeatedValue: 0)
self.getBytes(&bytesArray, length:count * sizeof(UInt8))
var s:String = "";
for byte in bytesArray {
s = s + String(format:"%02x", byte)
}
return s
}
public func arrayOfBytes() -> [UInt8] {
let count = self.length / sizeof(UInt8)
var bytesArray = [UInt8](count: count, repeatedValue: 0)
self.getBytes(&bytesArray, length:count * sizeof(UInt8))
return bytesArray
}
class public func withBytes(bytes: [UInt8]) -> NSData {
return NSData(bytes: bytes, length: bytes.count)
}
}
|
import XCTest
@testable import NodeGraph
final class NodeGraphTests: XCTestCase {
func testExample() {
XCTAssertEqual(true, true)
}
static var allTests = [
("testExample", testExample),
]
}
|
/**
* Plot
* Copyright (c) John Sundell 2019
* MIT license, see LICENSE file for details
*/
import XCTest
import PlotTests
var tests = [XCTestCaseEntry]()
tests += PlotTests.allTests()
XCTMain(tests)
|
//
// GLparallelogram.swift
// ChaosKit
//
// Created by Fu Lam Diep on 28.07.15.
// Copyright (c) 2015 Fu Lam Diep. All rights reserved.
//
import Foundation
public struct GLparallelogram : GLGeometry {
// STORED PROPERTIES
// +++++++++++++++++
/// Provides a list of positions of the geometry
public private(set) var values : [vec3] = []
/// Provides the index list
public private(set) var indexlist : [Int] = []
/// Indicates if the vertice are shared (element array) or not (array)
public var sharedVertice : Bool = false
// DERIVED PROPERTIES
// ++++++++++++++++++
/// Provides the size of a vertex
public var size : Int {get {return 3}}
/// Indicates whether the vertices change often or not
public var dynamic : Bool {get {return false}}
/// Provides the count of vertice, which are uploaded to the buffer,
/// depending on `sharedVertice`
public var count : Int {get {return sharedVertice ? values.count : indexlist.count}}
/// Provides a list of line according to value/indexlist
public var lines : [GLline] {get {return getLines(self as GLGeometry)}}
/// Provides a list of triangles according to value/indexlist
public var triangles : [GLtriangle] {get {return GLtriangle.fromGeometry(self as GLGeometry)}}
// INITIALIZERS
// ++++++++++++
/**
Initializes the parallelogram with three vectors. The resulting geometry consists
of the points at p, p + s, p +s + t and p + t
- parameter p: The position to start the parallelogram from
- parameter s:
- parameter t:
*/
public init (_ p: vec3, _ s: vec3, _ t: vec3) {
values = [p, p + s, p + s + t, p + t]
indexlist = [0, 1, 2, 2, 3, 0]
}
/**
Initializes the geometry, so that center of the parallelogram is at vec3(0, 0, 0)
- parameter s:
- parameter t:
*/
public init (_ s: vec3, _ t: vec3) {
self.init(-0.5 * (s + t), s, t)
}
// METHODS
// +++++++
/**
Returns the buffer data for vertex at given index
- parameter atIndex: The index of the vertex as array
- returns:
*/
public func getBufferData(atIndex index: Int) -> [GLfloat] {
return sharedVertice ? values[index].array : values[indexlist[index]].array
}
public func append(value: vec3) -> Int {
return -1
}
public func extend(values: [vec3]) {}
public func indexOf(value: vec3) -> Int? {
return values.indexOf(value)
}
} |
//
// UIImageExtensions.swift
// Object-Segmentation
//
// Created by EchoAR on 6/24/20.
// Copyright © 2020 EchoAR. All rights reserved.
//
import UIKit
import VideoToolbox
extension CVPixelBuffer {
/**
CVPixelBuffer extension to convert CVPixelBuffer to an UIImage:
- Uses:
`let image:UIimage = pixelBuffer.createImage()`
*/
func createImage()->UIImage {
CVPixelBufferLockBaseAddress(self, CVPixelBufferLockFlags(rawValue: 0))
let baseAddress = CVPixelBufferGetBaseAddress(self)
let context = CGContext(data: baseAddress,
width: CVPixelBufferGetWidth(self),
height: CVPixelBufferGetHeight(self),
bitsPerComponent: 8,
bytesPerRow: CVPixelBufferGetBytesPerRow(self),
space: CGColorSpaceCreateDeviceGray(),
bitmapInfo: CGImageAlphaInfo.none.rawValue)
let cgimage = context?.makeImage()
CVPixelBufferUnlockBaseAddress(self, CVPixelBufferLockFlags(rawValue: 0))
return UIImage(cgImage: cgimage!)
}
}
extension UIImage {
/*
Use this UIImage Extension to fix the orientation of UIImage.
While converting UIImage to CGImage for masking, UIImage loses it's orientation so use this function to fix the orientation issues.
- Uses:
`image = image.fixOrientation()`
- return: UIimage with orientation .up
*/
func fixOrientation() -> UIImage? {
switch imageOrientation {
case .up:
return self
default:
return createImageFromContext()
}
}
/*
Use the createImageFromContext() extenstion for creating image from the context.
*/
func createImageFromContext() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.size, false, scale)
draw(in: CGRect(origin: .zero, size: size))
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
/*
Use this function to resize image:
- Parameters:
- size: @CGSize -> size of the new image.
- Returns: UIImage with new size.
*/
func resizeImage(for size: CGSize) -> UIImage? {
let image = self.cgImage
let context = CGContext(data: nil,
width: Int(size.width),
height: Int(size.height),
bitsPerComponent: 8,
bytesPerRow: Int(size.width),
space: CGColorSpaceCreateDeviceGray(),
bitmapInfo: CGImageAlphaInfo.none.rawValue)
context?.interpolationQuality = .high
context?.draw(image!, in: CGRect(origin: .zero, size: size))
guard let scaledImage = context?.makeImage() else { return nil }
return UIImage(cgImage: scaledImage)
}
}
|
//
// Character.swift
// Timberman
//
// Created by Dion Larson on 2/3/15.
// Copyright (c) 2015 Make School. All rights reserved.
//
class Character: CCSprite {
var side: Side = .Left // Character starts on left side
func left() { // triggered by touchBegan on left side
side = .Left
scaleX = 1 // default character sprite
}
func right() { // triggered by touchBegan on right side
side = .Right
scaleX = -1 // flips sprite around anchor point
}
func tap() { // runs the swipe animation for character
animationManager.runAnimationsForSequenceNamed("Tap")
}
}
|
import Foundation
import lwip
/**
The delegate that developer should implement to handle various TCP events.
*/
public protocol TSTCPSocketDelegate: class {
/**
The socket is closed on tx side (FIN received). We will not read any data.
*/
func localDidClose(socket: TSTCPSocket)
/**
The socket is reseted (RST received), it should be released immediately.
*/
func socketDidReset(socket: TSTCPSocket)
/**
The socket is aborted (RST sent), it should be released immediately.
*/
func socketDidAbort(socket: TSTCPSocket)
/**
The socket is closed. This will only be triggered if the socket is closed actively by calling `close()`. It should be released immediately.
*/
func socketDidClose(socket: TSTCPSocket)
/**
Socket read data from local tx side.
- parameter data: The read data.
- parameter from: The socket object.
*/
func didReadData(data: NSData, from: TSTCPSocket)
/**
The socket has sent the specific length of data.
- parameter length: The length of data being ACKed.
- parameter from: The socket.
*/
func didWriteData(length: Int, from: TSTCPSocket)
}
// There is no way the error will be anything but ERR_OK, so the `error` parameter should be ignored.
func tcp_recv_func(arg: UnsafeMutablePointer<Void>, pcb: UnsafeMutablePointer<tcp_pcb>, buf: UnsafeMutablePointer<pbuf>, error: err_t) -> err_t {
assert(error == err_t(ERR_OK))
assert(arg != nil)
guard let socket = SocketDict.lookup(UnsafeMutablePointer<Int>(arg).memory) else {
// we do not know what this socket is, abort it
tcp_abort(pcb)
return err_t(ERR_ABRT)
}
socket.recved(buf)
return err_t(ERR_OK)
}
func tcp_sent_func(arg: UnsafeMutablePointer<Void>, pcb: UnsafeMutablePointer<tcp_pcb>, len: UInt16) -> err_t {
assert(arg != nil)
guard let socket = SocketDict.lookup(UnsafeMutablePointer<Int>(arg).memory) else {
// we do not know what this socket is, abort it
tcp_abort(pcb)
return err_t(ERR_ABRT)
}
socket.sent(Int(len))
return err_t(ERR_OK)
}
func tcp_err_func(arg: UnsafeMutablePointer<Void>, error: err_t) {
assert(arg != nil)
SocketDict.lookup(UnsafeMutablePointer<Int>(arg).memory)?.errored(error)
}
struct SocketDict {
static var socketDict: [Int:TSTCPSocket] = [:]
static func lookup(id: Int) -> TSTCPSocket? {
return socketDict[id]
}
static func newKey() -> Int {
var key = arc4random()
while let _ = socketDict[Int(key)] {
key = arc4random()
}
return Int(key)
}
}
/**
The TCP socket class.
- note: Unless one of `socketDidReset(_:)`, `socketDidAbort(_:)` or `socketDidClose(_:)` delegation methods is called, please do `close()`the socket actively and wait for `socketDidClose(_:)` before releasing it.
- note: This class is thread-safe.
*/
public final class TSTCPSocket {
private var pcb: UnsafeMutablePointer<tcp_pcb>
/// The source IPv4 address.
public let sourceAddress: in_addr
/// The destination IPv4 address
public let destinationAddress: in_addr
/// The source port.
public let sourcePort: UInt16
/// The destination port.
public let destinationPort: UInt16
private let queue: dispatch_queue_t
private var identity: Int
private let identityArg: UnsafeMutablePointer<Int>
private var closedSignalSend = false
var isValid: Bool {
return pcb != nil
}
/// Whether the socket is connected (we can receive and send data).
public var isConnected: Bool {
return isValid && pcb.memory.state.rawValue >= ESTABLISHED.rawValue && pcb.memory.state.rawValue < CLOSED.rawValue
}
/**
The delegate that handles various TCP events.
- warning: This should be set immediately when developer gets an instance of TSTCPSocket from `didAcceptTCPSocket(_:)` on the same thread that calls it. Simply say, just set it when you get an instance of TSTCPSocket.
*/
public weak var delegate: TSTCPSocketDelegate?
init(pcb: UnsafeMutablePointer<tcp_pcb>, queue: dispatch_queue_t) {
self.pcb = pcb
self.queue = queue
// see comments in "lwip/src/core/ipv4/ip.c"
sourcePort = pcb.memory.remote_port
destinationPort = pcb.memory.local_port
sourceAddress = in_addr(s_addr: pcb.memory.remote_ip.addr)
destinationAddress = in_addr(s_addr: pcb.memory.local_ip.addr)
identity = SocketDict.newKey()
identityArg = UnsafeMutablePointer<Int>.alloc(1)
identityArg.memory = identity
SocketDict.socketDict[identity] = self
tcp_arg(pcb, identityArg)
tcp_recv(pcb, tcp_recv_func)
tcp_sent(pcb, tcp_sent_func)
tcp_err(pcb, tcp_err_func)
}
func errored(error: err_t) {
release()
switch Int32(error) {
case ERR_RST:
delegate?.socketDidReset(self)
case ERR_ABRT:
delegate?.socketDidAbort(self)
default:
break
}
}
func sent(length: Int) {
delegate?.didWriteData(length, from: self)
}
func recved(buf: UnsafeMutablePointer<pbuf>) {
if buf == nil {
delegate?.localDidClose(self)
} else {
let data = NSMutableData(length: Int(buf.memory.tot_len))!
pbuf_copy_partial(buf, data.mutableBytes, buf.memory.tot_len, 0)
delegate?.didReadData(data, from: self)
if isValid {
tcp_recved(pcb, buf.memory.tot_len)
}
pbuf_free(buf)
}
}
/**
Send data to local rx side.
- parameter data: The data to send.
*/
public func writeData(data: NSData) {
dispatch_async(queue) {
guard self.isValid else {
return
}
let err = tcp_write(self.pcb, data.bytes, UInt16(data.length), UInt8(TCP_WRITE_FLAG_COPY))
if err != err_t(ERR_OK) {
self.close()
} else {
tcp_output(self.pcb)
}
}
}
/**
Close the socket. The socket should not be read or write again.
*/
public func close() {
dispatch_async(queue) {
guard self.isValid else {
return
}
tcp_arg(self.pcb, nil)
tcp_recv(self.pcb, nil)
tcp_sent(self.pcb, nil)
tcp_err(self.pcb, nil)
assert(tcp_close(self.pcb)==err_t(ERR_OK))
self.release()
// the lwip will handle the following things for us
self.delegate?.socketDidClose(self)
}
}
/**
Reset the socket. The socket should not be read or write again.
*/
public func reset() {
dispatch_async(queue) {
guard self.isValid else {
return
}
tcp_arg(self.pcb, nil)
tcp_recv(self.pcb, nil)
tcp_sent(self.pcb, nil)
tcp_err(self.pcb, nil)
tcp_abort(self.pcb)
self.release()
self.delegate?.socketDidClose(self)
}
}
func release() {
pcb = nil
identityArg.destroy()
identityArg.dealloc(1)
SocketDict.socketDict.removeValueForKey(identity)
}
deinit {
}
}
|
//
// NavigationConfigFactory.swift
// SilofitExam
//
// Created by Piyush Sharma on 2020-05-02.
// Copyright © 2020 Piyush Sharma. All rights reserved.
//
import Foundation
import UIKit
struct NavigationBarModel {
let leftModel: ButtonModel
let righModel: ButtonModel
struct ButtonModel {
let title: String
let image: UIImage?
let action: VoidClosure?
init(title: String = "",
image: UIImage? = nil,
action: VoidClosure?) {
self.title = title
self.image = image
self.action = action
}
static var empty: ButtonModel {
.init(title: "", image: nil, action: nil)
}
}
}
final class NavigationConfigFactory {
private let theme: Theme
init(theme: Theme) {
self.theme = theme
}
func getNavigationConfig(fromModel barModel: NavigationBarModel) -> NavigationConfig {
let leftConfig = getButtonConfig(model: barModel.leftModel)
let rightConfig = getButtonConfig(model: barModel.righModel)
return .init(leftButtonConfig: leftConfig,
rightButtonConfig: rightConfig,
backgroundColor: theme.colorForType(.light))
}
private func getButtonConfig(model: NavigationBarModel.ButtonModel) -> ButtonConfig {
ButtonConfig(title: [.normal: model.title],
titleTextColor: [.normal: theme.colorForType(.main)],
titleFont: theme.fontForName(.mediumBold),
image: [.normal: model.image],
backgroundColor: [.normal: theme.colorForType(.light)],
tintColor: theme.colorForType(.main),
isEnabled: true,
contentVerticalAlignment: .bottom,
tapClosure: model.action)
}
}
|
//
// Post.swift
// iDev Social
//
// Created by Hemanth Devarapalli on 1/19/17.
// Copyright © 2017 Hemanth Devarapalli. All rights reserved.
//
import UIKit
class Post: NSObject {
var text: String = ""
var email: String = ""
var imageUUID: String?
init(dict: Dictionary<String, AnyObject>) {
guard let dText = dict["text"] as? String else {
return
}
self.text = dText
guard let dEmail = dict["user"] as? String else {
return
}
self.email = dEmail
guard let imageUUID = dict["image"] as? String else {
print("No img")
}
self.imageUUID = imageUUID
}
}
|
//
// ViewController3.swift
// count down3
//
// Created by 新井山詠斗 on 2016/12/03.
// Copyright © 2016年 新井山詠斗. All rights reserved.
//
import UIKit
class ViewController4: UIViewController {
@IBOutlet weak var label1: UILabel!
var text1: String = ""
@IBOutlet weak var label2: UILabel!
var text2: String = ""
@IBOutlet weak var label3: UILabel!
var name: String = ""
override func viewDidLoad() {
super.viewDidLoad()
label1.text = text1
label2.text = text2
label3.text = name
}
@IBAction func checked() {
self.performSegue(withIdentifier: "countdown", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "countdown"{
let viewcontroller5 = segue.destination as! ViewController5
viewcontroller5.text1 = self.text1
viewcontroller5.text2 = self.text2
viewcontroller5.name = self.name
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
//
// GalleryViewController.swift
// Hero Guide
//
// Created by Thiago Ferrão on 08/07/18.
// Copyright © 2018 Thiago Ferrão. All rights reserved.
//
import UIKit
import CCBottomRefreshControl
class GalleryViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
private var eventHandler: GalleryViewHandlerInterface?
private let refreshControl = UIRefreshControl()
private var characterList = [CharacterData]()
override func viewDidLoad() {
super.viewDidLoad()
eventHandler = GalleryPresenter(userInterface: self)
eventHandler?.viewDidLoad()
}
// MARK: Private Methods
private func setupSearchController() {
let mainStoryBoard = UIStoryboard(name: Constants.STORYBOARD_IDENTIFIER.MAIN, bundle: nil)
let gallerySearchVC = mainStoryBoard.instantiateViewController(withIdentifier: Constants.VIEW_CONTROLLER_IDENTIFIER.MAIN_STORYBOARD.GALLERY_SEARCH) as! GallerySearchViewController
gallerySearchVC.searchDelegate = self
let searchController = UISearchController(searchResultsController: gallerySearchVC)
searchController.searchBar.placeholder = "Search by Hero Name"
searchController.searchBar.tintColor = UIColor.black
searchController.searchBar.delegate = gallerySearchVC
navigationItem.searchController = searchController
definesPresentationContext = true
}
private func setupBottomRefreshControl() {
refreshControl.tintColor = UIColor(named: Constants.COLOR.ACCENT)
refreshControl.addTarget(self, action: #selector(refreshCollectionRequested), for: .valueChanged)
collectionView.bottomRefreshControl = refreshControl
}
@objc private func refreshCollectionRequested() {
eventHandler?.loadMoreData()
}
// MARK: SEGUE
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.identifier {
case Constants.SEGUE_IDENTIFIER.TO_CHARACTER:
let sendCharacter = sender as? CharacterData
let characterVC = segue.destination as? CharacterViewController
characterVC?.character = sendCharacter
default:
return
}
}
}
// MARK: GalleryViewInterface
extension GalleryViewController: GalleryViewInterface {
func showLoading() {
loadingIndicator.isHidden = false
}
func hideLoading() {
loadingIndicator.isHidden = true
}
func showCollectionView() {
collectionView.isHidden = false
}
func hideCollectionView() {
collectionView.isHidden = true
}
func endRefreshing() {
refreshControl.endRefreshing()
}
func disableRefreshingControl() {
collectionView.bottomRefreshControl = nil
}
func setupContent() {
setupSearchController()
setupBottomRefreshControl()
}
func showAlert(_ alertController: UIAlertController) {
present(alertController, animated: true, completion: nil)
}
func updateCharacterList(_ newCharacterList: [CharacterData]) {
characterList.append(contentsOf: newCharacterList)
collectionView.reloadData()
}
func presentCharacterScreen(send sendCharacter: CharacterData) {
performSegue(withIdentifier: Constants.SEGUE_IDENTIFIER.TO_CHARACTER, sender: sendCharacter)
}
}
// MARK: UICollectionViewDataSource
extension GalleryViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return characterList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.REUSABLE_IDENTIFIER.GALLERY_CELL, for: indexPath) as! GalleryCollectionViewCell
cell.character = characterList[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionFooter:
let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: Constants.REUSABLE_IDENTIFIER.COPYRIGHT_FOOTER_VIEW, for: indexPath)
return footerView
default:
return UICollectionReusableView()
}
}
}
// MARK: UICollectionViewDelegateFlowLayout
extension GalleryViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width / 3, height: 150)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
eventHandler?.characterSelected(characterList[indexPath.row])
}
}
// MARK: SearchDelegate
extension GalleryViewController: SearchDelegate {
func showCharacterScreen(send sendCharacter: CharacterData) {
presentCharacterScreen(send: sendCharacter)
}
}
|
import Foundation
final class EnchantedMazeFactory: IMazeFactory {
func makeRoom(number: Int) -> IRoom {
return EnchantedRoom(roomNumber: number, spell: self.castSpell(number))
}
func makeDoor(room1: IRoom, room2: IRoom) -> IDoor {
return DoorNeedingSpell(room1: room1, room2: room2)
}
private func castSpell(_ number: Int) -> Spell {
return (number % 2 == 0) ? .earth : .air
}
}
private struct EnchantedRoom: IRoom {
private var sides: [Direction: IMapSite]
private let spell: Spell
let roomNumber: Int
init(roomNumber: Int) {
self.init(roomNumber: roomNumber, spell: .earth)
}
init(roomNumber: Int, spell: Spell) {
self.roomNumber = roomNumber
self.spell = spell
self.sides = [:]
}
subscript(direction: Direction) -> IMapSite? {
get { return self.sides[direction] }
set { self.sides[direction] = newValue }
}
func enter() {
print("Entered into the room")
}
}
private struct DoorNeedingSpell: IDoor {
private let room1: IRoom
private let room2: IRoom
init(room1: IRoom, room2: IRoom) {
self.room1 = room1
self.room2 = room2
}
func otherSideFrom(room: IRoom) -> IRoom {
return room
}
func enter() {
print("Opened the door")
}
}
private enum Spell {
case fire
case water
case earth
case air
}
|
//
// POST.swift
// UCSF
//
// Created by Jisoo Kim on 4/6/16.
// Copyright © 2016 Jimbus. All rights reserved.
//
import Foundation
func readPlist() -> NSDictionary {
var plistdata: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("data", ofType: "plist") {
plistdata = NSDictionary(contentsOfFile: path)
}
return plistdata!
}
func emptyPOST() {
}
func savePOST() -> NSString {
let data = readPlist()
//let dataKeys = data.allKeys
//let dataValues = data.allValues
let objectJSON: Dictionary<String, NSObject> = [
"formID":[
"user": NSNull(),
"docID": NSNull()
],
"properties":[
],
"pID":[
"hosID":[
"Trainee": data.valueForKey("traineeName") as! String,
"caseID": data.valueForKey("caseID") as! String,
"hospitalVal": data.valueForKey("hospital") as! Int
],
"insID":[
"instructor": data.valueForKey("instructor") as! Int
],
"procID":[
"procedure": data.valueForKey("procedure") as! Int,
"date": data.valueForKey("procedureDate") as! String
],
"extID":[
"extent": data.valueForKey("extentReached") as! String, //change to Int
"insertTime": data.valueForKey("insertionTime") as! String,
"withdrawTime": data.valueForKey("withdrawlTime") as! String,
"prepQuality": data.valueForKey("prepQuality") as! Int
],
"findID":[
NSNull()
]
]
]
var submitJSON: NSString = ""
if NSJSONSerialization.isValidJSONObject(objectJSON) {
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(objectJSON, options: .PrettyPrinted)
submitJSON = NSString(data: jsonData, encoding: NSUTF8StringEncoding)!
} catch {
//some exception handling goes here
}
}
return submitJSON
}
func submitPOST() -> NSString { //incomplete!!!!!!
let data = readPlist()
//var trainee: String = "", caseID: String = "", hospVal: Int = 0
if (data.valueForKey("traineeName") == nil) {
//set "traineeName" to ""
}
if (data.valueForKey("caseID") == nil) {
//caseID = data.valueForKey("CaseID") as! String
}
if (data.valueForKey("hospital") == nil) {
//hospVal = data.valueForKey("hospital") as! Int
}
let objectJSON: Dictionary<String, NSObject> = [
"formID":[
"user": NSNull(),
"docID": NSNull()
],
"properties":[
"submissionDate": NSNull(),
"completed": NSNull()
],
"pID":[
"hosID":[
"Trainee": data.valueForKey("traineeName") as! String,
"caseID": data.valueForKey("caseID") as! String,
"hospitalVal": data.valueForKey("hospital") as! Int
],
"insID":[
NSNull()
],
"procID":[
NSNull()
],
"extID":[
NSNull()
],
"findID":[
NSNull()
]
]
]
//["HospitalPage":["Trainee":trainee, "caseID":caseID, "hospitalVal": hospVal]] //this is very incomplete
var submitJSON: NSString = ""
if NSJSONSerialization.isValidJSONObject(objectJSON) {
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(objectJSON, options: .PrettyPrinted)
submitJSON = NSString(data: jsonData, encoding: NSUTF8StringEncoding)!
} catch {
//some exception handling goes here
}
}
return submitJSON
}
func regPOST(user: String, pw: String) -> NSString {
return "" as NSString
}
func authPOST(user: String, pw: String) -> NSString{
return "" as NSString
} |
//
// JugAnimator.swift
// WaterJugChallenge
//
// Created by David Jackman on 4/28/19.
// Copyright © 2019 David Jackman. All rights reserved.
//
import Foundation
import UIKit //TODO: Get rid of this dependency
//TODO: Implement this as a random access collection
class JugAnimator {
let viewModel: JugViewModel
/**
Used to pace the animation of the solution.
*/
var timer: Timer?
var button: UIButton?
init(viewModel: JugViewModel, button: UIButton? = nil) {
self.viewModel = viewModel
self.button = button
}
func toggleAnimation() {
if button?.titleLabel?.text == "Auto Play Solution" {
viewModel.reset()
}
if let t = timer {
t.invalidate()
timer = nil
button?.setTitle("Continue Animating", for: .normal)
}
else {
button?.setTitle("Stop Animating", for: .normal)
timer = Timer.scheduledTimer(timeInterval: 0.75, target: self, selector: #selector(nextFrame), userInfo: nil, repeats: true)
}
}
/**
Attempts to advance the animation or cancels the animation
*/
@objc
func nextFrame() {
if !next() {
timer?.invalidate()
timer = nil
button?.setTitle("Auto Play Solution", for: .normal)
}
}
/**
Updates the `stepIndex` to the next index
*/
@discardableResult
func next() -> Bool {
if viewModel.hasMoreSteps { viewModel.advance(); return true }
return false
}
/**
Updates the `stepIndex` to the previous index
*/
@discardableResult
func previous() -> Bool {
if !viewModel.isAtBeginning { viewModel.retreat(); return true }
return false
}
}
|
//
// CalculatorUITests.swift
// CalculatorUITests
//
// Created by Mikhail Ladutska on 5/11/20.
// Copyright © 2020 Mikhail Ladutska. All rights reserved.
//
import XCTest
class CalculatorUITests: XCTestCase {
func testFactorial() {
let app = XCUIApplication()
app.launch()
app.buttons["5"].tap()
app.buttons["x!"].tap()
XCTAssertEqual(app.staticTexts.element(matching:.any, identifier: "result").label, "120.0")
}
func testLaunchPerformance() {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
|
//
// InfoFilmTableViewController.swift
// StarWarsWiki
//
// Created by Виталий on 11.03.19.
// Copyright © 2019 vlad. All rights reserved.
//
import Reusable
import UIKit
class InfoFilmTableViewController: UITableViewController {
@IBOutlet private var titleLabel: UILabel!
@IBOutlet private var dateLabel: UILabel!
@IBOutlet private var ratingLabel: UILabel!
@IBOutlet private var descriptionTextView: UITextView!
@IBOutlet private var actorsCollectionView: UICollectionView!
@IBOutlet private var actorsCollectionHeightConstraint: NSLayoutConstraint!
@IBOutlet private var errorActorLoadLabel: UILabel!
// swiftlint:disable:next implicitly_unwrapped_optional
private var infoFilmViewModel: InfoFilmViewModelProtocol!
private var actors = [Actor]() {
didSet {
DispatchQueue.main.async { [weak self] in
self?.actorsCollectionView.reloadData()
}
}
}
var film: Film? {
didSet {
guard let film = film else { return }
infoFilmViewModel = InfoFilmViewModel(infoFilmService: CreditsServiceNetwork(withMovieId: film.id))
}
}
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.text = film?.title
dateLabel.text = film?.releaseDate
ratingLabel.text = "\(film?.voteAverage ?? 0)"
descriptionTextView.text = film?.overview
infoFilmViewModel.onActorsNotUploaded = { [weak self] in
self?.actorsCollectionHeightConstraint.constant = 0
self?.errorActorLoadLabel.isHidden = false
}
infoFilmViewModel?.onActorsChanged = { [weak self] actors in
self?.actors = actors
}
infoFilmViewModel?.loadMore()
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
}
// MARK: UICollectionViewDataSource
extension InfoFilmTableViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return actors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(for: indexPath) as ActorsCollectionViewCell
cell.set(actor: actors[indexPath.row])
return cell
}
}
// MARK: UICollectionViewDelegate
extension InfoFilmTableViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let actorViewController = ActorWebViewController.instantiate()
actorViewController.actorName = actors[indexPath.row].name
navigationController?.pushViewController(actorViewController, animated: true)
}
}
// MARK: StoryboardSceneBased
extension InfoFilmTableViewController: StoryboardSceneBased {
static var sceneStoryboard: UIStoryboard {
return UIStoryboard(name: "FilmInfo", bundle: nil)
}
}
|
//
// MockAppTests.swift
// MockAppTests
//
// Created by Egor Gorskikh on 07.09.2021.
//
import XCTest
import Mockingbird
@testable import MockApp
class MockAppTests: XCTestCase {
var sut: Person!
var mockBirdble: Birdble!
override func setUp() {
super.setUp()
sut = Person()
mockBirdble = mock(Birdble.self)
}
override func tearDown() {
sut = nil
super.tearDown()
}
func test_example() {
// given
// when
// then
}
func test_init_mock() {
XCTAssertNotNil(mockBirdble)
}
func test_can_fly() {
// Given
given(mockBirdble.canFly).willReturn(true)
// When
sut.release(mockBirdble)
// Then
verify(mockBirdble.fly()).wasCalled(1)
}
func test_cant_fly() {
// Given
given(mockBirdble.canFly).willReturn(false)
// When
sut.release(mockBirdble)
// Then
verify(mockBirdble.fly()).wasNeverCalled()
}
}
|
//
// AppSettings.swift
// Pruebas
//
// Created by Julio Banda on 8/8/19.
// Copyright © 2019 Julio Banda. All rights reserved.
//
import Foundation
class AppSettings {
// MARK: Keys
private struct Keys {
static let questionStrategy: String = "questionStrategy"
}
// MARK: Static properties
static let shared = AppSettings()
// Mark: Instance Properties
public var questionStrategyType: QuestionStrategyType {
get {
let rawValue = UserDefaults.standard.integer(forKey: Keys.questionStrategy)
return QuestionStrategyType(rawValue: rawValue)!
} set {
UserDefaults.standard.set(newValue.rawValue, forKey: Keys.questionStrategy)
}
}
// MARK: Instance Methods
public func questionStrategy(for questionGroupCaretaker: QuestionGroupCaretaker) -> QuestionStrategy {
return questionStrategyType.questionStrategy(for: questionGroupCaretaker)
}
// MARK: Object lifecycle
private init() { }
}
// MARK: Question Strategy Type
public enum QuestionStrategyType: Int, CaseIterable {
case random, sequential
// MARK: Instance Methods
public func title() -> String {
switch self {
case .random:
return "Random"
case .sequential:
return "Sequential"
}
}
public func questionStrategy(for questionGroupCaretaker: QuestionGroupCaretaker) -> QuestionStrategy {
switch self {
case .random:
return RandomQuestionStrategy(questionGroupCaretaker: questionGroupCaretaker)
case .sequential:
return SequentialQuestionStrategy(questionGroupCaretaker: questionGroupCaretaker)
}
}
}
|
//
// SecondViewController.swift
// stv50_mrmt_24
//
// Created by 丸本聡 on 2019/08/19.
// Copyright © 2019 丸本聡. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController {
// 引数(文字列)
var argString = ""
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// 引数をラベルにセット
label.text = argString
}
@IBAction func backView(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
|
import UIKit
class ViewController: UIViewController {
var users = [User](){
didSet{
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(tableView)
loadUpUser()
setConstraints()
}
lazy var tableView: UITableView = {
let theTableView = UITableView()
theTableView.dataSource = self
theTableView.delegate = self
theTableView.register(UserTableViewCell.self, forCellReuseIdentifier: "UserCell")
return theTableView
}()
func setConstraints() {
self.tableView.translatesAutoresizingMaskIntoConstraints = false
self.tableView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
self.tableView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
self.tableView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
self.tableView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
}
func loadUpUser(){
UsersFetchingService.manager.getUsers { (result) in
DispatchQueue.main.async {
switch result{
case .success(let user):
self.users = user
case .failure(let error):
print(error)
}
}
}
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = self.tableView.dequeueReusableCell(withIdentifier: "UserCell", for:indexPath) as? UserTableViewCell else {return UITableViewCell()}
let userData = users[indexPath.row]
cell.userName.text = "\(userData.name.first) \(userData.name.last) "
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("h")
let vc: UserDetailViewController = UserDetailViewController()
vc.user = users[indexPath.row]
self.navigationController?.pushViewController(vc, animated: true)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 140
}
}
|
//
// UserDefault.swift
// Breeze
//
// Created by Alex Littlejohn on 26/04/2020.
// Copyright © 2020 zero. All rights reserved.
//
import Foundation
@propertyWrapper
class UserDefault<Value> {
let key: String
let defaults: UserDefaults
let defaultValue: Value
var wrappedValue: Value {
get { defaults.object(forKey: key) as? Value ?? defaultValue }
set { defaults.set(newValue, forKey: key) }
}
convenience init<T: RawRepresentable>(wrappedValue: Value, _ key: T, defaults: UserDefaults = UserDefaults.standard) where T.RawValue == String {
self.init(wrappedValue: wrappedValue, key.rawValue, defaults: defaults)
}
init(wrappedValue: Value, _ key: String, defaults: UserDefaults = UserDefaults.standard) {
self.key = key
self.defaults = defaults
self.defaultValue = wrappedValue
}
}
@propertyWrapper
class CodableUserDefault<Value: Codable> {
let key: String
let defaults: UserDefaults
let defaultValue: Value
let encoder = PropertyListEncoder()
let decoder = PropertyListDecoder()
var wrappedValue: Value {
get {
guard let data = defaults.data(forKey: key), let response = try? decoder.decode(Value.self, from: data) else { return defaultValue }
return response
}
set {
guard let data = try? encoder.encode(newValue) else {
defaults.set(nil, forKey: key)
return
}
defaults.set(data, forKey: key)
}
}
convenience init<T: RawRepresentable>(wrappedValue: Value, _ key: T, defaults: UserDefaults = UserDefaults.standard) where T.RawValue == String {
self.init(wrappedValue: wrappedValue, key.rawValue, defaults: defaults)
}
init(wrappedValue: Value, _ key: String, defaults: UserDefaults = UserDefaults.standard) {
self.key = key
self.defaults = defaults
self.defaultValue = wrappedValue
}
}
|
//
// MyVideoViewController.swift
// MyVideoController
//
// Created by WangHui on 16/6/12.
// Copyright © 2016年 WangHui. All rights reserved.
//
import UIKit
import AVKit
import AVFoundation
class MyVideoViewController: UIViewController {
var isLoop: Bool!
var isContinue: Bool!
override func viewDidLoad() {
super.viewDidLoad()
isLoop = getLoopMode()
isContinue = getNewVCPlayMode()
createPlayer()
}
override func viewWillAppear(animated: Bool) {
// 监听完成事件
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyVideoViewController.playbackFinished(_:)), name: AVPlayerItemDidPlayToEndTimeNotification, object: nil)
// 监听失败事件
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyVideoViewController.playbackError(_:)), name: AVPlayerItemFailedToPlayToEndTimeNotification, object: nil)
// 监听屏幕旋转
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyVideoViewController.orientationChanged(_:)) , name: UIDeviceOrientationDidChangeNotification, object: nil)
// 监听进入后台
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyVideoViewController.willEnterBackground(_:)), name: UIApplicationWillResignActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyVideoViewController.willBecomeActive(_:)), name: UIApplicationWillEnterForegroundNotification, object: nil)
// 添加Player
addPlayer()
if isContinue == true {
play()
} else {
replay()
}
}
override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: AVPlayerItemDidPlayToEndTimeNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: AVPlayerItemFailedToPlayToEndTimeNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDeviceOrientationDidChangeNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillEnterForegroundNotification, object: nil)
pause()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func orientationChanged(notification: NSNotification) {
MyPlayer.shareInstance.playerLayer?.frame = view.layer.bounds // 全屏旋转时改变frame
}
func willEnterBackground(notification: NSNotification) {
pause()
}
func willBecomeActive(notification: NSNotification) {
play()
}
// 播放完成
func playbackFinished(notification: NSNotification) {
if isLoop == true {
replay()
}
}
// 播放失败
func playbackError(notification: NSNotification) {
replay()
}
}
// MARK: - Player Method
extension MyVideoViewController {
class MyPlayer {
static var shareInstance = MyPlayer()
private init() {}
var playerLayer: AVPlayerLayer?
}
// 创建PlayerLayer
func createPlayer() {
var playerLayer = MyPlayer.shareInstance.playerLayer
if playerLayer == nil {
let urlString = getVideoUrl()
var url: NSURL?
if urlString.hasPrefix("https://") || urlString.hasPrefix("http://") {
url = NSURL(string: urlString)
} else {
url = NSBundle.mainBundle().URLForResource(urlString, withExtension: getVideoType())
}
guard let _ = url else {
fatalError("请正确配置URL")
}
// AVPlayer
let item = AVPlayerItem(URL: url!)
playerLayer = AVPlayerLayer(player: AVPlayer(playerItem: item))
playerLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
playerLayer?.frame = view.layer.bounds
// 保存playerLayer
MyPlayer.shareInstance.playerLayer = playerLayer
}
}
// 添加AVPlayerLayer
func addPlayer() {
var isAdd = false
if view.layer.sublayers?.count > 0 {
for layer in view.layer.sublayers! {
if layer is AVPlayerLayer {
isAdd = true
break
}
}
}
if !isAdd {
// 添加 执行过releasePlayer后playerLayer = nil
if let playerLayer = MyPlayer.shareInstance.playerLayer {
playerLayer.zPosition = -1
view.layer.addSublayer(playerLayer)
}
}
}
// 播放
func play() {
MyPlayer.shareInstance.playerLayer?.player?.play()
}
// 重新播放
func replay() {
// 跳到最新的时间点开始播放
let myPlayer = MyPlayer.shareInstance.playerLayer?.player
myPlayer?.seekToTime(CMTimeMake(0, 1))
myPlayer?.play()
}
// 暂停
func pause() {
MyPlayer.shareInstance.playerLayer?.player?.pause()
}
// release 方法 当不需要再显示Video的时候可以调用释放资源
func releasePlayer() {
let myPlayer = MyPlayer.shareInstance
myPlayer.playerLayer?.player?.pause()
myPlayer.playerLayer?.player = nil
myPlayer.playerLayer?.removeFromSuperlayer()
myPlayer.playerLayer = nil
}
}
// MARK: - VideoInfo Method
extension MyVideoViewController {
enum VideoInfo: String {
case URL // 设置播放Video的名称或路径 网络Video可以设置网址
case VideoType // Video类型 MP4
case LoopMode // 是否循环播放 默认为true
case NewVCPlayContinue // 当弹出新页面的时候 是否接着上一个页面的播放时间 继续播放 默认为true
}
private func getUserInfo() -> NSDictionary {
let _path = NSBundle.mainBundle().pathForResource("video-info", ofType: "plist")
guard let path = _path else {
fatalError("没有找到video-info.plist,请确认正确配置了")
}
let dict = NSDictionary(contentsOfFile: path)!
return dict
}
private func getVideoUrl() -> String {
let videoUrl = getUserInfo().objectForKey(VideoInfo.URL.rawValue)
guard let url = videoUrl as? String else {
fatalError("请配置URL")
}
return url
}
private func getVideoType() -> String {
let videoType = getUserInfo().objectForKey(VideoInfo.VideoType.rawValue)
guard let type = videoType as? String else {
fatalError("请配置VideoType")
}
return type
}
private func getLoopMode() -> Bool {
let loopMode = getUserInfo().objectForKey(VideoInfo.LoopMode.rawValue)
guard let loop = loopMode as? Bool else {
return true
}
return loop
}
private func getNewVCPlayMode() -> Bool {
let playContinue = getUserInfo().objectForKey(VideoInfo.NewVCPlayContinue.rawValue)
guard let play = playContinue as? Bool else {
return true
}
return play
}
} |
//
// VirtualObjectCollectionViewFlowLayout.swift
// ARKitExample
//
// Created by Hans De Smedt on 07/08/2017.
// Copyright © 2017 Apple. All rights reserved.
//
import UIKit
protocol CollectionViewFlowLayoutProtocol: class {
var minimumLineSpacing: CGFloat { get }
var frame: CGRect? { get set }
var numberOfItems: Int? { get set }
var itemSize: CGSize { get }
var itemLength: CGFloat { get }
func getFrameForIndexPath(_ indexPath: IndexPath) -> CGRect
func getCollectionViewContentSize(_ superContentSize: CGSize) -> CGSize
func getLayoutAttributesForItemAtIndexPath(_ index: Int, offset: CGPoint, layoutAttributes: VirtualObjectCollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes?
func getTargetContentOffsetForCenterItem(_ centerItemIndex: Int) -> CGPoint
func getTargetContentOffsetForVelocity(_ velocity: CGPoint, offset: CGPoint) -> CGPoint
func getCenterIndexForOffset(_ offset: CGPoint) -> Int
}
enum LayoutState: Int {
case horizontal
}
class VirtualObjectCollectionViewFlowLayout: UICollectionViewFlowLayout {
var layoutState: LayoutState = LayoutState.horizontal {
didSet {
scrollDirection = .horizontal
invalidateLayout()
}
}
var centerItemIndex: Int = 0
var layoutInfo: [IndexPath:UICollectionViewLayoutAttributes] = [IndexPath:UICollectionViewLayoutAttributes]()
var layoutHorizontal: CollectionViewFlowLayoutProtocol?
var layout: CollectionViewFlowLayoutProtocol? {
get {
switch layoutState {
case .horizontal:
return layoutHorizontal
}
}
}
override init() {
super.init()
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
fileprivate func setup() {
layoutHorizontal = VirtualObjectCollectionViewFlowLayoutHorizontal()
guard let layout = layout else { return }
minimumInteritemSpacing = 0
minimumLineSpacing = layout.minimumLineSpacing
}
override func prepare() {
guard let layout = layout, let collectionView = collectionView else {
super.prepare()
return
}
layout.numberOfItems = collectionView.numberOfItems(inSection: 0)
layout.frame = collectionView.frame
minimumLineSpacing = layout.minimumLineSpacing
itemSize = layout.itemSize
super.prepare()
layoutInfo = getLayoutInfo()
}
override var collectionViewContentSize : CGSize {
let contentSize = super.collectionViewContentSize
guard let layout = layout else { return CGSize.zero }
return layout.getCollectionViewContentSize(contentSize)
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var allAttributes: [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()
for (indexPath, attributes) in layoutInfo {
if rect.intersects(attributes.frame) {
if let attributes = layoutAttributesForItem(at: indexPath) {
allAttributes.append(attributes)
}
}
}
return allAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard let layoutAttributes = layoutInfo[indexPath], let layout = layout, let collectionView = collectionView else { return nil }
let homeLayoutAttributes = VirtualObjectCollectionViewLayoutAttributes(forCellWith: indexPath)
homeLayoutAttributes.frame = layoutAttributes.frame
let index = collectionView.itemIndexForIndexPath(indexPath)
let offset = collectionView.contentOffset
return layout.getLayoutAttributesForItemAtIndexPath(index, offset: offset, layoutAttributes: homeLayoutAttributes)
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint {
guard let layout = layout else { return proposedContentOffset }
return layout.getTargetContentOffsetForCenterItem(centerItemIndex)
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
guard let layout = layout, let collectionView = collectionView else { return proposedContentOffset }
let contentOffset = collectionView.contentOffset
let offset = layout.getTargetContentOffsetForVelocity(velocity, offset: contentOffset)
centerItemIndex = layout.getCenterIndexForOffset(offset)
return offset
}
fileprivate func getLayoutInfo() -> [IndexPath:UICollectionViewLayoutAttributes] {
var layoutInfo = [IndexPath:UICollectionViewLayoutAttributes]()
guard let collectionView = collectionView, let layout = layout, collectionView.numberOfItems(inSection: 0) - 1 >= 0 else { return layoutInfo }
for i in 0...collectionView.numberOfItems(inSection: 0) - 1 {
let indexPath = IndexPath(row: i, section: 0)
let itemAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
itemAttributes.frame = layout.getFrameForIndexPath(indexPath)
layoutInfo[indexPath] = itemAttributes
}
return layoutInfo
}
func setLayoutToVertical(_ frame: CGRect, animated: Bool) {
guard let layoutVertical = layoutHorizontal else { return }
setLayoutTo(layoutVertical, frame: frame, animated: animated)
}
fileprivate func setLayoutTo(_ layout: CollectionViewFlowLayoutProtocol, frame: CGRect, animated: Bool) {
guard let collectionView = collectionView else { return }
layout.frame = frame
collectionView.contentSize = layout.getCollectionViewContentSize(frame.size)
let offset = layout.getTargetContentOffsetForCenterItem(centerItemIndex)
collectionView.setContentOffset(offset, animated: animated)
}
}
|
//
// DatabaseConstraintError.swift
// RepoDB
//
// Created by Groot on 13.09.2020.
// Copyright © 2020 K. All rights reserved.
//
import Foundation
struct DatabaseConstraintError: RepoDatabaseError {
var code: Int { return 19 }
var message: String { return ErrorLocalizer.error_code_19.localize() }
}
|
//
// ListNotesTableViewController.swift
// MakeSchoolNotes
//
// Created by Chris Orcutt on 1/10/16.
// Copyright © 2016 MakeSchool. All rights reserved.
//
import UIKit
class ListNotesTableViewController: UITableViewController {
var notes = [Note](){
didSet{
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
notes = CoreDataHelper.retrieveNotes().reversed()
}
@IBAction func unwindForSegue(_ segue: UIStoryboardSegue){
notes = CoreDataHelper.retrieveNotes().reversed()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return notes.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ListCell", for: indexPath) as! ListNotesTableViewCell
let note = notes[indexPath.row]
cell.noteTitleLabel.text = note.title
cell.lastModifiedTimeStampLabel.text = note.modificationTime?.convertToString() ?? ""
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let noteToRemove = notes[indexPath.row]
CoreDataHelper.deleteNote(note: noteToRemove)
notes = CoreDataHelper.retrieveNotes().reversed()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let identifier = segue.identifier else {return}
switch identifier{
case "displayNote":
print("transitioning to detailvc")
guard let indexPath = tableView.indexPathForSelectedRow else{return}
let note = notes[indexPath.row]
let destination = segue.destination as! DisplayNoteViewController
destination.note = note
case "addNote":
print("add new note button pressed")
default:
print("no such segue")
}
}
}
|
//
// Trace.swift
// KinokiKit
//
// Created by Ari on 7/19/15.
// Copyright © 2015 The EMIW. All rights reserved.
//
import Foundation
public protocol TraceType {}
final public class TraceItem<Type> {
public let type: Type;
public let data: Any;
init(type: Type, data: Any){
self.type = type;
self.data = data;
}
} |
//
// AlarmModificationViewPresenter.swift
// vkmelnikPW3
//
// Created by Vsevolod Melnik on 19.10.2021.
//
import UIKit
protocol AlarmModificationViewPresentationLogic: AnyObject {
func setupTime(time: Int)
func setupSound(sound: Int)
func setupTitle(title: String)
}
final class AlarmModificationViewPresenter: NSObject {
let sounds: [String] = ["Sound 1", "Sound 2", "Sound 3"]
var viewController: AlarmModificationViewDisplayLogic?
}
extension AlarmModificationViewPresenter: AlarmModificationViewPresentationLogic {
func setupTime(time: Int) {
viewController?.setupTime(time: time)
}
func setupSound(sound: Int) {
viewController?.setupSound(sound: sound)
}
func setupTitle(title: String) {
viewController?.setupTitle(title: title)
}
}
extension AlarmModificationViewPresenter: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
sounds.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return sounds[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
viewController?.setChosenSound(soundNumber: row)
}
}
|
//
// ShopEntity.swift
// Training3
//
// Created by Yuki Okudera on 2019/10/27.
// Copyright © 2019 Yuki Okudera. All rights reserved.
//
import Foundation
import RealmSwift
import RxSwift
final class ShopEntity: RealmSwift.Object {
/// id
@objc dynamic var shopId = ""
/// 店名
@objc dynamic var name = ""
/// 住所
@objc dynamic var address = ""
/// アクセス
@objc dynamic var mobileAccess = ""
/// キャッチ
@objc dynamic var `catch` = ""
/// コースの有無
@objc dynamic var course = ""
/// パーキングの有無
@objc dynamic var parking = ""
/// 個室有無
@objc dynamic var privateRoom = ""
/// 禁煙席
@objc dynamic var nonSmoking = ""
/// 営業時間
@objc dynamic var open = ""
/// 定休日
@objc dynamic var close = ""
/// クレジットカード利用可否
@objc dynamic var card = ""
/// ロゴURL
@objc dynamic var logoImage = ""
/// 平均予算
@objc dynamic var budgetAverage = ""
/// 予算
@objc dynamic var budgetName = ""
/// クーポンURL
@objc dynamic var couponUrls = ""
override static func primaryKey() -> String? {
return "shopId"
}
convenience init(shop: Shop) {
self.init()
self.shopId = shop.id
self.name = shop.name
self.address = shop.address
self.mobileAccess = shop.mobileAccess
self.catch = shop.catch
self.course = shop.course
self.parking = shop.parking
self.privateRoom = shop.privateRoom
self.nonSmoking = shop.nonSmoking
self.open = shop.open
self.close = shop.close
self.card = shop.card
self.logoImage = shop.logoImage
self.budgetAverage = shop.budget.average
self.budgetName = shop.budget.name
self.couponUrls = shop.couponUrls.pc
}
convenience init(shopId: String,
name: String,
address: String,
mobileAccess: String,
catchString: String,
course: String,
parking: String,
privateRoom: String,
nonSmoking: String,
open: String,
close: String,
card: String,
logoImage: String,
budgetAverage: String,
budgetName: String,
couponUrls: String) {
self.init()
self.shopId = shopId
self.name = name
self.address = address
self.mobileAccess = mobileAccess
self.catch = catchString
self.course = course
self.parking = parking
self.privateRoom = privateRoom
self.nonSmoking = nonSmoking
self.open = open
self.close = close
self.card = card
self.logoImage = logoImage
self.budgetAverage = budgetAverage
self.budgetName = budgetName
self.couponUrls = couponUrls
}
}
|
//
// UIButton-Extension.swift
// ZLHJHelpAPP
//
// Created by 周希财 on 2019/9/22.
// Copyright © 2019 VIC. All rights reserved.
//
import Foundation
extension UIButton {
func countDownWithInterval(interval: Int = 60, text:String){
// func countDownWithInterval(interval: Int = 60, text:String){
var timeCount = interval
// 创建时间源
let timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
timer.schedule(deadline: .now(), repeating: .seconds(1))
timer.setEventHandler {
timeCount -= 1
if timeCount <= 0 {
main {
self.setTitle(text, for: .normal)
self.setTitleColor(.white, for: .normal)
self.backgroundColor = systemColor
self.isEnabled = true
timer.cancel()
}
}else {
main {
print("\(timeCount)s")
self.setTitle("\(timeCount)s", for: .normal)
self.setTitleColor(.white, for: .normal)
self.backgroundColor = textGrayColor
self.isEnabled = false
}
}
}
// 启动时间源
timer.resume()
}
// 图片和文字 共存,你懂的
// 使用样例 https://blog.csdn.net/u013406800/article/details/55506039
@objc func set(image anImage: UIImage?, title: String,
titlePosition: UIView.ContentMode, additionalSpacing: CGFloat, state: UIControl.State){
self.imageView?.contentMode = .center
self.setImage(anImage, for: state)
positionLabelRespectToImage(title: title, position: titlePosition, spacing: additionalSpacing)
self.titleLabel?.contentMode = .center
self.setTitle(title, for: state)
}
private func positionLabelRespectToImage(title: String, position: UIView.ContentMode,
spacing: CGFloat) {
let imageSize = self.imageRect(forContentRect: self.frame)
let titleFont = self.titleLabel?.font!
let titleSize = title.size(withAttributes: [NSAttributedString.Key.font: titleFont!])
var titleInsets: UIEdgeInsets
var imageInsets: UIEdgeInsets
switch (position){
case .top:
titleInsets = UIEdgeInsets(top: -(imageSize.height + titleSize.height + spacing),
left: -(imageSize.width), bottom: 0, right: 0)
imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)
case .bottom:
titleInsets = UIEdgeInsets(top: (imageSize.height + titleSize.height + spacing),
left: -(imageSize.width), bottom: 0, right: 0)
imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width)
case .left:
titleInsets = UIEdgeInsets(top: 0, left: -(imageSize.width * 2), bottom: 0, right: 0)
imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0,
right: -(titleSize.width * 2 + spacing))
case .right:
titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -spacing)
imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
default:
titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
self.titleEdgeInsets = titleInsets
self.imageEdgeInsets = imageInsets
}
}
|
//
// ViewController.swift
// map
//
// Created by user on 2020/08/03.
// Copyright © 2020 user. All rights reserved.
//
import UIKit
import GoogleMaps
import GooglePlaces
import FirebaseDatabase
struct Path{
static var positionArray = Array<CLLocationCoordinate2D>()
}
struct Markers{
static var markerArray = Array<GMSMarker>()
}
public let DATUM_POINT = CLLocation(latitude: 37.590597, longitude: 127.035898)
class ViewController: UIViewController, GMSMapViewDelegate {
// MARK: Properties
@IBOutlet var mapView: GMSMapView!
// database
var database: DatabaseReference = Database.database().reference()
var databaseHandler: DatabaseHandle!
let databaseName: String = "cities"
var objects: [[String:Int]]! = []
var recordCount: Int = 0
// marker handler
var tappedMarker: GMSMarker?
var markerIndex: Int = 0 // marker key for updates
// path handler
var path:GMSMutablePath?
var polyline: GMSPolyline?
var showPolyline: Bool = false
var distance: Double = 0
override func viewDidLoad() {
super.viewDidLoad()
// inital camera frame
let camera = GMSCameraPosition.camera(withLatitude: DATUM_POINT.coordinate.latitude, longitude: DATUM_POINT.coordinate.longitude, zoom: 14.5)
// 초기 설정
let rect = CGRect(origin: .zero, size: CGSize(width: 100, height: 100))
let mapView = GMSMapView.map(withFrame: rect, camera: camera)
view = mapView
mapView.settings.compassButton = true
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
mapView.delegate = self
configureDatabase()
// track tappedMarker
self.tappedMarker = GMSMarker()
// add path button
createPathButton()
}
func drawPath(){
self.path = GMSMutablePath()
for marker in Markers.markerArray{
self.path?.add(marker.position)
}
self.polyline?.map = nil
self.polyline = GMSPolyline(path: self.path)
self.polyline!.strokeColor = UIColor(displayP3Red:115/255, green: 200/255 , blue: 153/255, alpha: 1)
self.polyline!.strokeWidth = 5
if (self.showPolyline){
self.polyline?.map = self.view as? GMSMapView
}
}
func updatePath() {
var count = 0
for marker in Markers.markerArray{
marker.accessibilityValue = String(count) //path Index
count = count+1
}
}
//MARK: Load Data
func configureDatabase() {
databaseHandler = self.database.child(databaseName).observe(.value, with: { (snapshot) -> Void in
guard let records = snapshot.value as? [[String: Any]] else { return }
if (records.count == self.recordCount){
print("all")
return
}
//init
var count = 0
Markers.markerArray.removeAll()
for record in records{
self.recordCount+=1
guard let lat = record["latitude"], let long = record["longitude"], let distance = record["total_distance"] as? String else {return }
guard let totalDistance = Double(distance) else {return}
self.distance = totalDistance
let marker: GMSMarker = GMSMarker()
let position: CLLocationCoordinate2D = CLLocationCoordinate2D( latitude: lat as! CLLocationDegrees, longitude: long as! CLLocationDegrees)
guard let markerId: Int = record["id"] as? Int else { return }
marker.position = position
marker.snippet = String(markerId)
if let _:Int = record["isDeleted"] as? Int {
marker.icon = UIImage(named: "untrash")
marker.isTappable = false
}else{
Markers.markerArray.append(marker)
marker.accessibilityValue = String(count) //path Index
marker.icon = UIImage(named: "newtrash")
count+=1
}
marker.map = self.view as? GMSMapView
}
print(records.count)
self.drawPath()
self.createPathLabel()
}) { (error) in
print(error.localizedDescription)
}
}
//MARK: MarkerTap Event
//empty default
func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
return UIView()
}
func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
tappedMarker = marker
let markerId: String! = tappedMarker?.snippet
let pathId: String! = self.tappedMarker?.accessibilityValue
let alert = UIAlertController(title: "쓰레기를 수거하셨나요?", message: "확인 버튼을 누르면 마커가 비활성화됩니다.", preferredStyle: UIAlertController.Style.alert)
let okAction = UIAlertAction(title: "확인", style: .default){ (action) in
self.tappedMarker?.icon = UIImage(named: "untrash")
self.tappedMarker?.isTappable = false
//delete
if let id: Int = Int(markerId){
self.database.child(self.databaseName).child(String(id-1)).updateChildValues(["isDeleted":1])
if let index: Int = Int(pathId){
Markers.markerArray.remove(at: index)
}
}
//update path
self.updatePath()
self.drawPath()
}
let cancel = UIAlertAction(title: "취소", style: .destructive, handler : nil)
alert.addAction(cancel)
alert.addAction(okAction)
present(alert, animated: true)
return false
}
//MARK : SHOW PATH BUTTON
func createPathButton() {
let button: UIButton = UIButton(type: UIButton.ButtonType.roundedRect)
if let image = UIImage(named: "pathnew") {
button.setImage(image.withRenderingMode(.alwaysOriginal), for: .normal)
}
button.imageView?.clipsToBounds = true
button.imageView?.layer.masksToBounds = true
button.imageView?.layer.cornerRadius = 25
button.addTarget(self, action: #selector(buttonClicked(_:)), for: .touchUpInside)
self.view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
button.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -8).isActive = true
button.topAnchor.constraint(equalTo: view.topAnchor, constant: 65).isActive = true
button.heightAnchor.constraint(equalToConstant: 70).isActive = true
button.widthAnchor.constraint(equalToConstant: 70).isActive = true
// button.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -100).isActive = true
// button.frame = CGRect(x: 309, y: 535, width: 70, height: 70)
// button.backgroundColor = UIColor(displayP3Red:64/255, green: 179/255 , blue: 112/255, alpha: 1)
}
func createPathLabel() {
// let label: UILabel = UILabel(frame: CGRect(x: 20, y: 25, width: 200, height: 30))
let label: UILabel = UILabel()
label.backgroundColor = UIColor.white
label.center = CGPoint(x: 110, y: 40)
label.textAlignment = .center
label.text = "최단 경로 거리 \(self.distance)m"
label.layer.cornerRadius = 5
label.textColor = UIColor.darkGray
// label.font = UIFont(name: "NanumBarunpen", size:12)
label.font = UIFont.systemFont(ofSize: 13.0)
self.view.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 40).isActive = true
label.topAnchor.constraint(equalTo: view.topAnchor, constant: 80).isActive = true
label.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -90).isActive = true
label.heightAnchor.constraint(equalToConstant: 35).isActive = true
label.layer.shadowColor = UIColor.gray.cgColor
label.layer.shadowRadius = 2.0
label.layer.shadowOpacity = 0.5
label.layer.shadowOffset = CGSize(width: 4, height: 4)
label.layer.masksToBounds = false // true: round
}
@IBAction func buttonClicked(_ sender: UIButton) {
if (!showPolyline) {
self.polyline?.map = self.view as? GMSMapView
showPolyline = true
return
}
self.polyline?.map = nil
showPolyline = false
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
}
|
//
// popupView.swift
// onin-nihonsi
//
// Created by 内藤綜志 on 2018/11/24.
// Copyright © 2018 内藤綜志. All rights reserved.
//
import UIKit
class popupView: UIView {
@IBOutlet weak var left: NSLayoutConstraint!
@IBOutlet weak var top: NSLayoutConstraint!
@IBOutlet weak var baseView: UIView!
@IBOutlet weak var backview: UIView!
@IBOutlet weak var frontview: UIView!
@IBOutlet weak var backbutton: UIButton!
let screenHeight: CGFloat = UIScreen.main.bounds.height
@IBOutlet weak var photo: UIImageView!
@IBOutlet weak var nextname: UILabel!
@IBOutlet weak var nextninki: UILabel!
let backipad:UIImage = UIImage(named:"戻るipad")!
static var Count: Int?
// static var a: UIImage?
@IBAction func back(_ sender: Any) {
self.removeFromSuperview()
}
@IBAction func back2(_ sender: Any) {
self.removeFromSuperview()
}
struct Syusyos {
var name:String;
var age:String;
}
struct Tokugawas {
var name:String!;
var age:String!;
}
//構造体に内閣総理大臣の情報をセットする
func SouriLoad(){
//画面サイズを取得し制約を変更
if screenHeight >= 667 {
// iPhone 4S の場合 (Unit is Point.)
print("4")
}
else if screenHeight >= 736 {
// iPhone plus の場合
print("plus")
left.constant = 65
top.constant = 150
}
else if screenHeight >= 812 {
// iPhone X の場合
print("10")
}
else if screenHeight >= 1024 {
//ipadの場合
baseView.frame = CGRect(x: 39, y: 82, width: 690, height: 860)
backview.frame = CGRect(x: 0, y: 0, width: 690, height: 860)
frontview.frame = CGRect(x: 5, y: 5, width: 680, height: 850)
nextname.frame = CGRect(x: 103, y: 25, width: 475, height: 65)
nextname.font = UIFont(name: "aoyagireisyo2", size: 60)
nextninki.frame = CGRect(x: 69, y: 667, width: 543, height: 57)
nextninki.font = UIFont(name: "aoyagireisyo2", size: 40)
photo.frame = CGRect(x: 152, y: 116, width: 375, height: 511)
backbutton.setImage(backipad, for: .normal)
backbutton.frame = CGRect(x: 305, y: 740, width: 80, height: 80)
}
switch popupView.Count {
case 1:
nextname.text! = SouriViewController.ito.name
nextninki.text! = SouriViewController.ito.age
photo.image = UIImage(named: "ito.png")
case 2: nextname.text! = SouriViewController.kuroda.name
nextninki.text! = SouriViewController.kuroda.age
photo.image = UIImage(named: "kuroda.png")
case 3: nextname.text! = SouriViewController.yamagata.name
nextninki.text! = SouriViewController.yamagata.age
photo.image = UIImage(named: "yamagata.png")
case 4: nextname.text! = SouriViewController.matukata.name
nextninki.text! = SouriViewController.matukata.age
photo.image = UIImage(named: "matukata.png")
case 5: nextname.text! = SouriViewController.ito2.name
nextninki.text! = SouriViewController.ito2.age
photo.image = UIImage(named: "ito.png")
case 6: nextname.text! = SouriViewController.matukata2.name
nextninki.text! = SouriViewController.matukata2.age
photo.image = UIImage(named: "matukata.png")
case 7: nextname.text! = SouriViewController.ito3.name
nextninki.text! = SouriViewController.ito3.age
photo.image = UIImage(named: "ito.png")
case 8: nextname.text! = SouriViewController.okuma.name
nextninki.text! = SouriViewController.okuma.age
photo.image = UIImage(named: "okuma.png")
case 9: nextname.text! = SouriViewController.yamagata2.name
nextninki.text! = SouriViewController.yamagata2.age
photo.image = UIImage(named: "yamagata.png")
case 10: nextname.text! = SouriViewController.ito4.name
nextninki.text! = SouriViewController.ito4.age
photo.image = UIImage(named: "ito.png")
case 11: nextname.text! = SouriViewController.katura.name
nextninki.text! = SouriViewController.katura.age
photo.image = UIImage(named: "katura.png")
case 12: nextname.text! = SouriViewController.saionzi.name
nextninki.text! = SouriViewController.saionzi.age
photo.image = UIImage(named: "saionzi.png")
case 13: nextname.text! = SouriViewController.katura2.name
nextninki.text! = SouriViewController.katura2.age
photo.image = UIImage(named: "katura.png")
case 14: nextname.text! = SouriViewController.saionzi2.name
nextninki.text! = SouriViewController.saionzi2.age
photo.image = UIImage(named: "saionzi.png")
case 15: nextname.text! = SouriViewController.katura3.name
nextninki.text! = SouriViewController.katura3.age
photo.image = UIImage(named: "katura.png")
case 16: nextname.text! = SouriViewController.yamamoto.name
nextninki.text! = SouriViewController.yamamoto.age
photo.image = UIImage(named: "yamamoto.png")
case 17: nextname.text! = SouriViewController.okuma2.name
nextninki.text! = SouriViewController.okuma2.age
photo.image = UIImage(named: "okuma.png")
case 18: nextname.text! = SouriViewController.terauti.name
nextninki.text! = SouriViewController.terauti.age
photo.image = UIImage(named: "terauti.png")
case 19: nextname.text! = SouriViewController.hara.name
nextninki.text! = SouriViewController.hara.age
photo.image = UIImage(named: "hara.png")
case 20: nextname.text! = SouriViewController.takahasi.name
nextninki.text! = SouriViewController.takahasi.age
photo.image = UIImage(named: "takahasi.png")
case 21: nextname.text! = SouriViewController.katoy.name
nextninki.text! = SouriViewController.katoy.age
photo.image = UIImage(named: "katoy.png")
case 22: nextname.text! = SouriViewController.yamamoto2.name
nextninki.text! = SouriViewController.yamamoto2.age
photo.image = UIImage(named: "yamamoto.png")
case 23: nextname.text! = SouriViewController.kiyoura.name
nextninki.text! = SouriViewController.kiyoura.age
photo.image = UIImage(named: "kiyoura.png")
case 24: nextname.text! = SouriViewController.katot.name
nextninki.text! = SouriViewController.katot.age
photo.image = UIImage(named: "katot.png")
case 25: nextname.text! = SouriViewController.wakatuki.name
nextninki.text! = SouriViewController.wakatuki.age
photo.image = UIImage(named: "wakatuki.png")
case 26: nextname.text! = SouriViewController.tanaka.name
nextninki.text! = SouriViewController.tanaka.age
photo.image = UIImage(named: "tanaka.png")
case 27: nextname.text! = SouriViewController.hamaguti.name
nextninki.text! = SouriViewController.hamaguti.age
photo.image = UIImage(named: "hamaguti.png")
case 28: nextname.text! = SouriViewController.wakatuki2.name
nextninki.text! = SouriViewController.wakatuki2.age
photo.image = UIImage(named: "wakatuki.png")
case 29: nextname.text! = SouriViewController.inukai.name
nextninki.text! = SouriViewController.inukai.age
photo.image = UIImage(named: "inukai.png")
case 30: nextname.text! = SouriViewController.saito.name
nextninki.text! = SouriViewController.saito.age
photo.image = UIImage(named: "saito.png")
case 31: nextname.text! = SouriViewController.okada.name
nextninki.text! = SouriViewController.okada.age
photo.image = UIImage(named: "okada.png")
case 32: nextname.text! = SouriViewController.hirota.name
nextninki.text! = SouriViewController.hirota.age
photo.image = UIImage(named: "hirota.png")
case 33: nextname.text! = SouriViewController.hayasi.name
nextninki.text! = SouriViewController.hayasi.age
photo.image = UIImage(named: "hayasi.png")
case 34: nextname.text! = SouriViewController.konoe.name
nextninki.text! = SouriViewController.konoe.age
photo.image = UIImage(named: "konoe.png")
case 35: nextname.text! = SouriViewController.hiranuma.name
nextninki.text! = SouriViewController.hiranuma.age
photo.image = UIImage(named: "hiranuma.png")
case 36: nextname.text! = SouriViewController.abe.name
nextninki.text! = SouriViewController.abe.age
photo.image = UIImage(named: "abe.png")
case 37: nextname.text! = SouriViewController.yonai.name
nextninki.text! = SouriViewController.yonai.age
photo.image = UIImage(named: "yonai.png")
case 38: nextname.text! = SouriViewController.konoe2.name
nextninki.text! = SouriViewController.konoe2.age
photo.image = UIImage(named: "konoe.png")
case 39: nextname.text! = SouriViewController.konoe3.name
nextninki.text! = SouriViewController.konoe3.age
photo.image = UIImage(named: "konoe.png")
case 40: nextname.text! = SouriViewController.tozyo.name
nextninki.text! = SouriViewController.tozyo.age
photo.image = UIImage(named: "tozyo.png")
case 41: nextname.text! = SouriViewController.koiso.name
nextninki.text! = SouriViewController.koiso.age
photo.image = UIImage(named: "koiso.png")
case 42: nextname.text! = SouriViewController.suzuki.name
nextninki.text! = SouriViewController.suzuki.age
photo.image = UIImage(named: "suzuki.png")
default: return
}
}
//構造体に徳川家の情報をセットする
func TokugawaLoad(){
//画面サイズを取得し制約を変更
if screenHeight == 667 {
// iPhone 4S の場合 (Unit is Point.)
print("4")
}
else if screenHeight >= 736 {
// iPhone plus の場合
print("plus")
left.constant = 65
top.constant = 150
}
else if screenHeight >= 812 {
// iPhone X の場合
print("10")
}
else if screenHeight >= 1024 {
//ipadの場合
baseView.frame = CGRect(x: 39, y: 82, width: 690, height: 860)
backview.frame = CGRect(x: 0, y: 0, width: 690, height: 860)
frontview.frame = CGRect(x: 5, y: 5, width: 680, height: 850)
nextname.frame = CGRect(x: 103, y: 25, width: 475, height: 65)
nextname.font = UIFont(name: "aoyagireisyo2", size: 60)
nextninki.frame = CGRect(x: 69, y: 667, width: 543, height: 57)
nextninki.font = UIFont(name: "aoyagireisyo2", size: 40)
photo.frame = CGRect(x: 152, y: 116, width: 375, height: 511)
backbutton.setImage(backipad, for: .normal)
backbutton.frame = CGRect(x: 305, y: 740, width: 80, height: 80)
}
switch popupView.Count {
case 1:
nextname.text! = TokugawaViewController.ieyasu.name
nextninki.text! = TokugawaViewController.ieyasu.age
photo.image = UIImage(named: "ieyasu.jpg")
case 2:
nextname.text! = TokugawaViewController.hidetada.name
nextninki.text! = TokugawaViewController.hidetada.age
photo.image = UIImage(named: "hidetada.jpg")
case 3:
nextname.text! = TokugawaViewController.iemitu.name
nextninki.text! = TokugawaViewController.iemitu.age
photo.image = UIImage(named: "iemitu.jpg")
case 4:
nextname.text! = TokugawaViewController.ietuna.name
nextninki.text! = TokugawaViewController.ietuna.age
photo.image = UIImage(named: "ietuna.jpg")
case 5:
nextname.text! = TokugawaViewController.tunayosi.name
nextninki.text! = TokugawaViewController.tunayosi.age
photo.image = UIImage(named: "tunayosi.jpg")
case 6:
nextname.text! = TokugawaViewController.ienobu.name
nextninki.text! = TokugawaViewController.ienobu.age
photo.image = UIImage(named: "ienobu.jpg")
case 7:
nextname.text! = TokugawaViewController.ietugu.name
nextninki.text! = TokugawaViewController.ietugu.age
photo.image = UIImage(named: "ietugu.jpg")
case 8:
nextname.text! = TokugawaViewController.yosimune.name
nextninki.text! = TokugawaViewController.yosimune.age
photo.image = UIImage(named: "yosimune.jpg")
case 9:
nextname.text! = TokugawaViewController.iesige.name
nextninki.text! = TokugawaViewController.iesige.age
photo.image = UIImage(named: "iesige.jpg")
case 10:
nextname.text! = TokugawaViewController.ieharu.name
nextninki.text! = TokugawaViewController.ieharu.age
photo.image = UIImage(named: "ieharu.jpg")
case 11:
nextname.text! = TokugawaViewController.ienari.name
nextninki.text! = TokugawaViewController.ienari.age
photo.image = UIImage(named: "ienari.jpg")
case 12:
nextname.text! = TokugawaViewController.ieyosi.name
nextninki.text! = TokugawaViewController.ieyosi.age
photo.image = UIImage(named: "ieyosi.jpg")
case 13:
nextname.text! = TokugawaViewController.iesada.name
nextninki.text! = TokugawaViewController.iesada.age
photo.image = UIImage(named: "iesada.jpg")
case 14:
nextname.text! = TokugawaViewController.iemoti.name
nextninki.text! = TokugawaViewController.iemoti.age
photo.image = UIImage(named: "iemoti.jpg")
case 15:
nextname.text! = TokugawaViewController.yosinobu.name
nextninki.text! = TokugawaViewController.yosinobu.age
photo.image = UIImage(named: "yosinobu.jpg")
default: return
}
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
|
//
// ContactViewModel.swift
// Appointment
//
// Created by Jeffrey Moran on 10/31/21.
// Copyright © 2021 Jeff Moran. All rights reserved.
//
import Foundation
class ContactViewModel {
// MARK: - Private Properties
private let appointment: Appointment
// MARK: - Internal Properties
var contactName: String {
return appointment.client.name
}
var contactPhone: String {
return appointment.client.phoneNumber
}
var contactEmail: String {
return appointment.client.emailAddress
}
var successText: String {
return "\(appointment.client.name) saved to Contacts!"
}
var failureText: String {
return "Contact not Saved"
}
// MARK: - Initializers
init(_ appointment: Appointment) {
self.appointment = appointment
}
}
|
//
// LoadStatus.swift
// FreightOneIos
//
// Created by Vasil Panov on 16.12.20.
//
import Foundation
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.