text stringlengths 8 1.32M |
|---|
//
// EditNameViewController.swift
// BeeHive
//
// Created by Hyper Design on 8/26/18.
// Copyright © 2018 HyperDesign-Gehad. All rights reserved.
//
import UIKit
class EditNameViewController: UIViewController {
@IBOutlet weak var currentNameView: UIView!
@IBOutlet weak var currntNameTF: UITextField!
@IBOutlet weak var newNameView: UIView!
@IBOutlet weak var newNameTF: UITextField!
@IBOutlet weak var submitButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
currntNameTF.text = User().getSavedUser().name
setStyle()
}
@IBAction func submitTapped(_ sender: Any) {
ApiRequests.apisInstance.editUserName(userName: newNameTF.text!) { (user
, msg) in
if let user = user{
user.setSavedUser()
self.navigationController?.popViewController(animated: true)
}else{
self.showAlert(title: "", message:msg, closure: nil)
}
}
}
func setStyle ()
{
currentNameView.addShadowAndCornerRadiusToViewWith()
newNameView.addShadowAndCornerRadiusToViewWith()
submitButton.addShadowAndCornerRadiusToViewWith()
}
}
|
//
// TodoListView.swift
// Examples
//
// Created by Guilherme Souza on 23/12/22.
//
import IdentifiedCollections
import SwiftUI
import SwiftUINavigation
struct TodoListView: View {
@EnvironmentObject var auth: AuthController
@State var todos: IdentifiedArrayOf<Todo> = []
@State var error: Error?
@State var createTodoRequest: CreateTodoRequest?
var body: some View {
List {
if let error {
ErrorText(error)
}
IfLet($createTodoRequest) { $createTodoRequest in
AddTodoListView(request: $createTodoRequest) { result in
withAnimation {
self.createTodoRequest = nil
switch result {
case let .success(todo):
error = nil
_ = todos.insert(todo, at: 0)
case let .failure(error):
self.error = error
}
}
}
}
ForEach(todos) { todo in
TodoListRow(todo: todo) {
Task {
await toggleCompletion(of: todo)
}
}
}
.onDelete { indexSet in
Task {
await delete(at: indexSet)
}
}
}
.animation(.default, value: todos)
.navigationTitle("Todos")
.toolbar {
ToolbarItem(placement: .primaryAction) {
if createTodoRequest == nil {
Button {
withAnimation {
createTodoRequest = .init(
description: "",
isComplete: false,
ownerID: auth.currentUserID
)
}
} label: {
Label("Add", systemImage: "plus")
}
} else {
Button("Cancel", role: .cancel) {
withAnimation {
createTodoRequest = nil
}
}
}
}
}
.task {
do {
error = nil
todos = try await IdentifiedArrayOf(
uniqueElements: supabase.database.from("todos")
.select()
.execute()
.value as [Todo]
)
} catch {
self.error = error
}
}
}
func toggleCompletion(of todo: Todo) async {
var updatedTodo = todo
updatedTodo.isComplete.toggle()
todos[id: todo.id] = updatedTodo
do {
error = nil
let updateRequest = UpdateTodoRequest(
isComplete: updatedTodo.isComplete,
ownerID: auth.currentUserID
)
updatedTodo = try await supabase.database.from("todos")
.update(values: updateRequest, returning: .representation)
.eq(column: "id", value: updatedTodo.id)
.single()
.execute()
.value
todos[id: updatedTodo.id] = updatedTodo
} catch {
// rollback old todo.
todos[id: todo.id] = todo
self.error = error
}
}
func delete(at offset: IndexSet) async {
let oldTodos = todos
do {
error = nil
let todosToDelete = offset.map { todos[$0] }
todos.remove(atOffsets: offset)
try await supabase.database.from("todos")
.delete()
.in(column: "id", value: todosToDelete.map(\.id))
.execute()
} catch {
self.error = error
// rollback todos on error.
todos = oldTodos
}
}
}
struct TodoListView_Previews: PreviewProvider {
static var previews: some View {
NavigationStack {
TodoListView()
}
}
}
|
//
// TableViewDataSource.swift
// TakeUrPill
//
// Created by Alessio Roberto on 17/09/2018.
// Copyright © 2018 Alessio Roberto. All rights reserved.
//
import Foundation
import UIKit
protocol RowUpdateProtocol: class {
func removeModel(at: Int)
}
final class TableViewDataSource<Model>: NSObject, UITableViewDataSource {
typealias CellConfigurator = (Model, UITableViewCell) -> Void
weak var delegate: RowUpdateProtocol?
fileprivate var models: [Model]
private let reuseIdentifier: String
private let cellConfigurator: CellConfigurator
init(models: [Model],
reuseIdentifier: String,
cellConfigurator: @escaping CellConfigurator) {
self.models = models
self.reuseIdentifier = reuseIdentifier
self.cellConfigurator = cellConfigurator
}
func tableView(_ tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return models.count
}
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = models[indexPath.row]
let cell = tableView.dequeueReusableCell(
withIdentifier: reuseIdentifier,
for: indexPath
)
cellConfigurator(model, cell)
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
models.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
delegate?.removeModel(at: indexPath.row)
}
}
func cleanDataSource() {
models.removeAll()
}
}
extension TableViewDataSource where Model == Pill {
static func make(for pills: [Pill],
reuseIdentifier: String = "HistoryCell") -> TableViewDataSource {
return TableViewDataSource(
models: pills,
reuseIdentifier: reuseIdentifier
) { pill, cell in
cell.textLabel?.text = pill.name
cell.detailTextLabel?.text = DateFormatter.localizedString(from: Date(timeIntervalSince1970: pill.timestamp),
dateStyle: .medium,
timeStyle: .medium)
}
}
}
extension TableViewDataSource where Model == PillType {
static func make(for pills: [PillType],
reuseIdentifier: String = "PillTypeCell") -> TableViewDataSource {
return TableViewDataSource(
models: pills,
reuseIdentifier: reuseIdentifier
) { pill, cell in
cell.textLabel?.text = pill.name
cell.detailTextLabel?.text = "\(pill.ammount)"
}
}
}
|
//
// Page3ViewController.swift
// MyNavBar
//
// Created by Jakkawad Chaiplee on 2/15/2559 BE.
// Copyright © 2559 Jakkawad Chaiplee. All rights reserved.
//
import UIKit
import MapleBacon
import Alamofire // connect to server
import SWXMLHash //
import XCDYouTubeKit
class Page3ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//DataSource -> call back , render
var mDataArray:[XMLIndexer] = []
var liveBlur:DKLiveBlurView!
var mRefreshControl:UIRefreshControl!
@IBOutlet weak var mTableView:UITableView!
override func viewWillAppear(animated: Bool) {
self.liveBlur.scrollView = self.mTableView
print("Page3 - viewWillAppear")
}
override func viewDidAppear(animated: Bool) {
print("Page3 - viewDidAppear")
}
override func viewWillDisappear(animated: Bool) {
self.liveBlur.scrollView = nil
print("Page3 - viewWillDisappear")
}
override func viewDidDisappear(animated: Bool) {
print("Page3 - viewDidDisappear")
}
func feedData() {
print("loading...")
let params = ["type":"xml"]
Alamofire.request(.POST, "http://codemobiles.com/adhoc/feed/youtube_feed.php", parameters: params, encoding: .URL, headers: nil).responseString {
(request, response, result) -> Void in
//print(result.value!)
let xml = SWXMLHash.parse(result.value!)
self.mDataArray = xml["youtubes_list"].children
//print(self.mDataArray.description)
self.mTableView.reloadData()
self.mRefreshControl.endRefreshing()
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let item:XMLIndexer = self.mDataArray[indexPath.row]
let youtubeID = item["youtubeID"].element?.text!
let vc = XCDYouTubeVideoPlayerViewController(videoIdentifier: youtubeID)
self.presentViewController(vc, animated: true, completion: nil)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
/*
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let item:XMLIndexer = self.mDataArray[indexPath.row]
let youtubeID = item["youtubeID"].element?.text!
let playerVC = XCDYouTubeVideoPlayerViewController(videoIdentifier: youtubeID)
self.presentViewController(playerVC, animated: true, completion: nil)
}
*/
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//return 100
return self.mDataArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// as = upcast จากลูกไปแม่
// as? = downcast - optional
// as! = downcase = forced
let cell = tableView.dequeueReusableCellWithIdentifier("lek") as? CustomTableViewCell
//cell?.mTitleLabel.text = "CodeMobiles"
let item = self.mDataArray[indexPath.row]
cell?.mTitleLabel.text = item["title"].element?.text
cell?.mSubtitileLabel.text = item["description"].element?.text
let avatarImageString = item["image_link"].element!.text!
let thumbnailImageString = item["youtube_image"].element!.text!
let thumbnailUrl = NSURL(string: thumbnailImageString)!
cell?.mThumbnailImage.setImageWithURL(thumbnailUrl)
let avatarUrl = NSURL(string: avatarImageString)!
cell?.mAvatarImage.setImageWithURL(avatarUrl)
return cell!
}
override func viewDidLoad() {
super.viewDidLoad()
self.feedData()
//add headerView
let headerView = UIView()
headerView.frame = CGRectMake(0, 0, 1, 270)
self.mTableView.tableHeaderView = headerView
//set blur image
self.liveBlur = DKLiveBlurView(frame: self.view.bounds)
self.liveBlur.originalImage = UIImage(named: "listview_iphone.png")
self.mTableView.backgroundView = self.liveBlur
//add refresh control
self.mRefreshControl = UIRefreshControl()
self.mRefreshControl.addTarget(self, action: Selector("feedData"), forControlEvents: .ValueChanged)
self.mTableView.addSubview(self.mRefreshControl)
//self.mTableView.delegate = self
// 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.
}
*/
}
|
//
// ZHelpController.swift
// Seriously
//
// Created by Jonathan Sand on 4/13/17.
// Copyright © 2017 Jonathan Sand. All rights reserved.
//
import Foundation
import SnapKit
#if os(OSX)
import Cocoa
#elseif os(iOS)
import UIKit
#endif
var gHelpWindowController : NSWindowController? // instantiated once, in startupCloudAndUI
var gHelpController : ZHelpController? { return gHelpWindowController?.contentViewController as? ZHelpController }
var gHelpWindow : ZWindow? { return gHelpWindowController?.window }
enum ZHelpMode: String {
case intermedMode = "i"
case mouseMode = "m" // save for later!!!
case basicMode = "b"
case essayMode = "e"
case proMode = "a"
case dotMode = "d"
case noMode = " "
static let all: [ZHelpMode] = [.dotMode, .basicMode, .intermedMode, .proMode, .essayMode] // , .mouseMode]
var title: String {
switch self {
case .intermedMode: return "intermediate keys"
case .essayMode: return "notes & essays"
case .basicMode: return "basic keys"
case .mouseMode: return "mouse"
case .proMode: return "all keys"
case .dotMode: return "dots"
default: return kEmpty
}
}
func isEqual(to mode: ZHelpMode) -> Bool {
return rawValue == mode.rawValue
}
var showsDots: Bool {
switch self {
case .dotMode, .essayMode, .mouseMode: return true
default: return false
}
}
}
class ZHelpController: ZGenericTableController, ZGeometry {
@IBOutlet var clipView : ZView?
@IBOutlet var mapHelpGrid : ZHelpGridView?
@IBOutlet var dotsHelpGrid : ZHelpGridView?
@IBOutlet var essayHelpGrid : ZHelpGridView?
@IBOutlet var mouseHelpGrid : ZHelpGridView?
var helpData : ZHelpData { return helpData(for: gCurrentHelpMode) }
var gridView : ZHelpGridView? { return gridView(for: gCurrentHelpMode) }
var titleBarButtons = ZHelpButtonsView()
let essayHelpData = ZHelpEssayData()
let mouseHelpData = ZHelpMouseData()
let dotsHelpData = ZHelpDotsData()
let mapHelpData = ZHelpMapData()
var isShowing = false
override func handleSignal(_ object: Any?, kind: ZSignalKind) { genericTableUpdate() }
override func shouldHandle(_ kind: ZSignalKind) -> Bool { return super.shouldHandle(kind) && (gHelpWindow?.isVisible ?? false) }
func showHelpFor(_ mode: ZHelpMode) { show(true, mode: mode) } // side-effect: sets gCurrentHelpMode
func tableView(_ tableView: ZTableView, heightOfRow row: Int) -> CGFloat { return helpData.rowHeight }
func tableView(_ tableView: ZTableView, objectValueFor tableColumn: ZTableColumn?, row: Int) -> Any? { return helpData.objectValueFor(row) }
func helpData(for iMode: ZHelpMode) -> ZHelpData {
switch iMode {
case .essayMode: return essayHelpData
case .mouseMode: return mouseHelpData
case .dotMode: return dotsHelpData
default: return mapHelpData
}
}
func gridView(for iMode: ZHelpMode) -> ZHelpGridView? {
switch iMode {
case .essayMode: return essayHelpGrid
case .mouseMode: return mouseHelpGrid
case .dotMode: return dotsHelpGrid
default: return mapHelpGrid
}
}
// MARK: - display
// MARK: -
func helpUpdate() {
view.zlayer.backgroundColor = gBackgroundColor.cgColor
titleBarButtons.updateAndRedraw()
genericTableUpdate()
updateGridVisibility()
}
override func controllerSetup(with mapView: ZMapView?) {
view.zlayer.backgroundColor = .white
let m = gCurrentHelpMode
super .controllerSetup(with: mapView)
essayHelpData.setupForMode(m)
dotsHelpData .setupForMode(m)
mapHelpData .setupForMode(m)
gSignal([.sAppearance]) // redraw dots map
setupGridViews()
setupTitleBar()
if !isShowing {
gCurrentHelpMode = .noMode // set temporarily so show (just below) does not dismiss window
show(mode: m)
}
}
func setupTitleBar() {
if let window = view.window {
let titleBarView = window.standardWindowButton(.closeButton)!.superview!
titleBarButtons.isInTitleBar = true
if !titleBarView.subviews.contains(titleBarButtons) {
titleBarView.addSubview(titleBarButtons)
titleBarButtons.snp.removeConstraints()
titleBarButtons.snp.makeConstraints { make in
make.centerX.top.bottom.equalToSuperview()
}
}
titleBarButtons.updateAndRedraw()
}
}
func show(_ iShow: Bool? = nil, flags: ZEventFlags = ZEventFlags()) {
var nextMode = gCurrentHelpMode
if gIsEssayMode || flags.exactlySplayed {
nextMode = .essayMode
} else if !gIsEssayMode {
if flags.exactlyOtherSpecial {
nextMode = .basicMode
} else if flags.exactlyAll {
nextMode = .proMode
} else {
nextMode = .dotMode // prefer this
}
}
show(iShow, mode: nextMode)
}
func show(_ iShow: Bool? = nil, mode: ZHelpMode?) {
if let next = mode {
let show = iShow ?? (!gIsHelpVisible || next != gCurrentHelpMode)
if !show {
gHelpWindow?.close()
} else {
gCurrentHelpMode = next
isShowing = true // prevent infinite recursion (where update (below) calls show)
gHelpWindow?.close() // workaround to force a call to the dots draw method (perhaps an apple bug?)
gHelpController?.helpData.prepareStrings()
gHelpWindowController?.showWindow(self) // bring to front
helpUpdate()
isShowing = false
}
}
}
// MARK: - events
// MARK: -
func handleKey(_ key: String, flags: ZEventFlags) -> Bool { // false means key not handled
let COMMAND = flags.hasCommand
let SPECIAL = flags.exactlySpecial
switch key {
case "?", "/": show( flags: flags)
case "w": show(false, flags: flags)
case "p": view.printView()
case "q": gApplication?.terminate(self)
case "a": if SPECIAL { gApplication?.showHideAbout() }
case "r": if COMMAND { sendEmailBugReport() }
default: if let arrow = key.arrow {
switch arrow {
case .left, .right: titleBarButtons.showNextHelp(forward: arrow == .right)
default: return false
}
}
}
return true
}
func handleEvent(_ event: ZEvent) -> ZEvent? {
if let key = event.key {
let flags = event.modifierFlags
return handleKey(key, flags: flags) ? nil : event
}
return nil
}
// MARK: - grid
// MARK: -
func setupGridViews() {
if let c = clipView {
c.zlayer.backgroundColor = .clear
for m in ZHelpMode.all {
if let g = gridView(for: m) {
let data = helpData(for: m)
g.helpData = data
g.removeFromSuperview()
c.addSubview(g)
if let t = genericTableView {
g.snp.makeConstraints { make in
make.top.bottom.left.right.equalTo(t) // text and grid scroll together
}
}
g.zlayer.backgroundColor = .clear
g.isHidden = true
}
}
}
}
func updateGridVisibility() {
let graphModes: [ZHelpMode] = [.basicMode, .intermedMode, .proMode]
func shouldShow(_ mode: ZHelpMode) -> Bool {
let sameMode = mode == gCurrentHelpMode
let matchable = sameMode ? [mode] : [mode, gCurrentHelpMode]
let showGraph = matchable.intersection(graphModes) == matchable
return sameMode || showGraph
}
for mode in ZHelpMode.all {
let hide = !shouldShow(mode)
gridView(for: mode)?.isHidden = hide
}
gridView?.setNeedsDisplay()
}
// MARK: - help table
// MARK: -
var clickCoordinates: (Int, Int)? {
#if os(OSX)
if let table = genericTableView,
let row = table.selectedRowIndexes.first {
if let location = table.currentMouseLocation {
let column = Int(floor(location.x / helpData.columnWidth.float))
table.deselectRow(row)
return (row, min(3, column))
}
}
#endif
return nil
}
override func numberOfRows(in tableView: ZTableView) -> Int {
helpData.prepareStrings()
return helpData.countOfRows
}
func tableViewSelectionIsChanging(_ notification: Notification) {
if let (row, column) = clickCoordinates, column >= 0,
let hyperlink = helpData.url(for: row, column: column) {
hyperlink.openAsURL()
}
}
}
|
//
// RadarViewController.swift
// scooby
//
// Created by Lloyd Keijzer on 18-04-16.
// Copyright © 2016 Lloyd Keijzer. All rights reserved.
//
import UIKit
import ionicons
import MapKit
class RadarViewController: BaseViewController, GroupDelegate {
static let DEBUG_MODE = false
var radarView: RadarView!
var stopRadar: Bool = false
private let navigationViewController = NavigationViewController()
override func viewDidLoad() {
super.viewDidLoad()
LocationController.sharedInstance.startLocating()
// initialize view
radarView = RadarView(frame: viewRect)
view.addSubview(radarView)
if RadarViewController.DEBUG_MODE {
radarView.changeNearestScoobyName("Debug")
}
navigationViewController.initialize(view.frame, controller: self)
showMenuButton()
// update radar
updateRadar()
}
func showMenuButton() {
// menu button
let menuButton = UIButton(frame: CGRectMake(0, 0, 44, 44))
menuButton.setImage(IonIcons.imageWithIcon(
ion_navicon_round,
size: 32.0,
color: UIColor(hexString: COLOR_WHITE)
), forState: .Normal)
menuButton.addTarget(self, action: #selector(showMenu), forControlEvents: .TouchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: menuButton)
}
func showCloseButton() {
let closeButton = UIButton(frame: CGRectMake(0, 0, 44, 44))
closeButton.setImage(IonIcons.imageWithIcon(
ion_close_round,
size: 24.0,
color: UIColor(hexString: COLOR_WHITE)
), forState: .Normal)
closeButton.addTarget(self, action: #selector(closeMenu), forControlEvents: .TouchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: closeButton)
}
override func viewWillAppear(animated: Bool) {
GroupViewController.group?.delegate = self
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
stopRadar = true
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
radarView.animateRadar()
}
func memberDidJoin(member: GroupMember) {
if member.circleView == nil {
radarView.circleContainer.addCircle(member)
}
}
func showMenu() {
navigationViewController.navigationView!.alpha = 0
view.addSubview(navigationViewController.navigationView!)
self.showCloseButton()
UIView.animateWithDuration(0.3, animations: {
self.navigationViewController.navigationView!.alpha = 1
})
}
func closeMenu() {
navigationViewController.navigationView!.alpha = 1
showMenuButton()
UIView.animateWithDuration(0.3, animations: {
self.navigationViewController.navigationView!.alpha = 0
}) { (Bool) in
self.navigationViewController.navigationView!.removeFromSuperview()
}
}
func updateRadar() {
let locationController = LocationController.sharedInstance
if (locationController.location == nil || locationController.heading == nil) {
return
}
var distance: Double?
var nearestName: String?
for member: GroupMember in (GroupViewController.group?.members)! {
if (member.location == nil || member.peerId == MultipeerController.sharedInstance.peerId) {
continue
}
if member.circleView == nil {
self.radarView.circleContainer.addCircle(member)
}
let currentDistance = LocationController.distanceBetweenCoordinates(
locationController.location!,
toCoordinates: member.location!
)
member.distance = currentDistance
if (distance == nil || (currentDistance < distance!)) {
distance = currentDistance
nearestName = member.peerId.displayName
}
let degrees = LocationController.getBearingBetweenTwoPoints(
locationController.location!,
point2: member.location!
)
var radarDegrees: Double = locationController.heading! + degrees
while (radarDegrees > 360) {
radarDegrees -= 360
}
while (radarDegrees < 0) {
radarDegrees += 360
}
member.degrees = radarDegrees
if radarView.circleContainer.detailView.member != nil && radarView.circleContainer.detailView.member!.circleView == member.circleView {
radarView.circleContainer.assignMemberToDetail(member.circleView!)
}
self.radarView.circleContainer.moveCircleToDegree(
self.radarView.circleContainer.peerCircles.last!,
degrees: (radarDegrees)
)
}
if nearestName != nil {
self.radarView.changeNearestScoobyName(nearestName!)
}
if !self.stopRadar {
self.performSelector(#selector(self.updateRadar), withObject: nil, afterDelay: 0.034)
}
}
}
|
//
// ImageCell.swift
// SwiftPractic
//
// Created by hiro on 2018. 6. 25..
// Copyright © 2018년 hiro. All rights reserved.
//
import UIKit
class ScrollingImageCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
}
|
//
// CreateMapViewController.swift
// MapBase
//
// Created by Usuário Convidado on 22/03/16.
// Copyright © 2016 Map Base 5. All rights reserved.
//
import UIKit
import RealmSwift
class CreateMapViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var mapName: UITextField!
@IBOutlet weak var typeSegmented: UISegmentedControl!
@IBAction func createMap(sender: UIButton) {
let map: Map = Map()
self.mapName.delegate = self
map.name = mapName.text!
map.id = NSUUID().UUIDString
switch (typeSegmented.selectedSegmentIndex) {
case 0:
map.type = "Private"
case 1:
map.type = "Public"
default:
map.type = "Private"
}
map.isBookmarked = false
//print (map.name)
let realm = try! Realm()
try! realm.write({() -> Void in
realm.add(map)
})
//self.dismissViewControllerAnimated(true, completion: nil)
navigationController?.popViewControllerAnimated(true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
import UIKit
class ImageCell: UICollectionViewCell, UIGestureRecognizerDelegate {
@IBOutlet weak var imageButton: UIButton!
}
|
// Travel Companion
//
// Created by Stefan Jaindl on 27.07.22.
// Copyright © 2022 Stefan Jaindl. All rights reserved.
//
import Foundation
public extension NSMutableAttributedString {
func trimmedAttributedString(set: CharacterSet) -> NSMutableAttributedString {
let invertedSet = set.inverted
var range = (string as NSString).rangeOfCharacter(from: invertedSet)
let loc = range.length > 0 ? range.location : 0
range = (string as NSString).rangeOfCharacter(from: invertedSet, options: .backwards)
let len = (range.length > 0 ? NSMaxRange(range) : string.count) - loc
let r = attributedSubstring(from: NSRange(location: loc, length: len))
return NSMutableAttributedString(attributedString: r)
}
}
|
import Foundation
import RxSwift
import RxCocoa
import Combine
func subscribe<T>(_ disposeBag: DisposeBag, _ driver: Driver<T>, _ onNext: ((T) -> Void)? = nil) {
driver.drive(onNext: onNext).disposed(by: disposeBag)
}
func subscribe<T>(_ disposeBag: DisposeBag, _ signal: Signal<T>, _ onNext: ((T) -> Void)? = nil) {
signal.emit(onNext: onNext).disposed(by: disposeBag)
}
func subscribe<T>(_ disposeBag: DisposeBag, _ observable: Observable<T>?, _ onNext: ((T) -> Void)? = nil) {
observable?
.subscribeOn(ConcurrentDispatchQueueScheduler(qos: .userInitiated))
.observeOn(ConcurrentDispatchQueueScheduler(qos: .userInitiated))
.subscribe(onNext: onNext)
.disposed(by: disposeBag)
}
func subscribeSerial<T>(_ disposeBag: DisposeBag, _ observable: Observable<T>, _ onNext: ((T) -> Void)? = nil) {
observable
.subscribe(onNext: onNext)
.disposed(by: disposeBag)
}
func subscribe<T>(_ scheduler: ImmediateSchedulerType, _ disposeBag: DisposeBag, _ observable: Observable<T>, _ onNext: ((T) -> Void)? = nil) {
observable
.observeOn(scheduler)
.subscribe(onNext: onNext)
.disposed(by: disposeBag)
}
func subscribe<T>(_ cancellables: inout Set<AnyCancellable>, _ publisher: AnyPublisher<T, Never>, _ receiveValue: @escaping ((T) -> Void)) {
publisher
.receive(on: DispatchQueue.main)
.sink(receiveValue: receiveValue)
.store(in: &cancellables)
}
|
//
// EProducts.swift
// exerciseApp
//
// Created by Егор Редько on 23.02.2020.
// Copyright © 2020 necordu. All rights reserved.
//
import Foundation
struct EProducts {
}
|
//
// HHView.swift
// HHUIKit
//
// Created by master on 2019/12/31.
// Copyright © 2019 com.ian.Test. All rights reserved.
//
import UIKit
class HHView: UIView {
}
|
//
// SettingsTableViewController.swift
// LyricLab
//
// Created by Punya Chatterjee on 10/3/17.
// Copyright © 2017 Punya Chatterjee. All rights reserved.
//
import UIKit
class SettingsTableViewController: UITableViewController {
@IBOutlet var fontStepper: UIStepper!
@IBOutlet var fontSizeLabel: UILabel!
@IBOutlet var acSwitch: UISwitch!
@IBAction func switchToggled(_ sender: Any) {
UserDefaults.standard.set(acSwitch.isOn, forKey: "EnableAutocorrect")
}
@IBAction func fontStepped(_ sender: UIStepper) {
fontSizeLabel.text = "\(fontStepper.value) pt"
UserDefaults.standard.set(fontStepper.value, forKey: "FontSize")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
acSwitch.isOn = UserDefaults.standard.bool(forKey: "EnableAutocorrect")
if UserDefaults.standard.object(forKey: "FontSize") == nil {
if UIDevice.current.userInterfaceIdiom == .pad {
UserDefaults.standard.set(22.0, forKey: "FontSize")
} else {
UserDefaults.standard.set(17.0, forKey: "FontSize")
}
}
fontStepper.value = Double(UserDefaults.standard.float(forKey: "FontSize"))
fontSizeLabel.text = "\(fontStepper.value) pt"
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 2
} else {
return 1
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 1 {
let email = "punya@stanford.edu"
if let mailurl = URL(string: "mailto:\(email)") {
UIApplication.shared.openURL(mailurl)
}
}
}
}
|
//
// ViewController.swift
// postCard
//
// Created by Fenkins on 05/02/15.
// Copyright (c) 2015 Fenkins. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var additionalLabel: UILabel!
@IBOutlet weak var enterNameTF: UITextField!
@IBOutlet weak var enterMessageTF: UITextField!
@IBOutlet weak var messageSent: UIButton!
// our button
@IBAction func messageButtonPressed(sender: UIButton) {
var simpleName : String
var simpleText : String
var boolType : Bool
simpleName = enterNameTF.text
simpleText = enterMessageTF.text
messageLabel.text = "Hi, Taylor! Its " + simpleName + "! I am your best fan and I am writing you cuz " + simpleText
enterMessageTF.text = ""
enterNameTF.text = ""
enterMessageTF.resignFirstResponder()
enterNameTF.resignFirstResponder()
messageSent.setTitle("Send Another Mail", forState: UIControlState.Normal)
additionalLabel.text = simpleName
additionalLabel.backgroundColor = UIColor.darkGrayColor()
}
// testing the comments yo
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.
}
}
|
//
// CreateTripVC.swift
// Trip Planner
//
// Created by Fernando on 10/17/17.
// Copyright © 2017 Specialist. All rights reserved.
//
import UIKit
import KeychainSwift
class CreateTripVC: UIViewController {
@IBOutlet weak var destinationTextField: UITextField!
@IBOutlet weak var startDateTextField: UITextField!
@IBOutlet weak var endDateTextField: UITextField!
let keychain = KeychainSwift()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))))
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func saveTripPressed(_ sender: UIButton) {
guard let basicHeader = keychain.get("basicAuth")else {return}
let trip = Trip(completed: false, destination: self.destinationTextField.text!, start_date: self.startDateTextField.text!, end_date: self.endDateTextField.text!, waypoints: [])
Networking.instance.fetch(route: Route.trips, method: "POST", headers: ["Authorization": basicHeader, "Content-Type": "application/json"], data: trip) { (data) in
let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
guard let trip = json else {
return
}
print(trip)
}
self.dismiss(animated: true, completion: nil)
}
}
|
import Foundation
import Yams
import Quick
import Nimble
@testable import SwaggerKit
final class SpecIntegerSchemaTests: QuickSpec {
// MARK: - Instance Methods
override func spec() {
var schema: SpecIntegerSchema!
var schemaYAML: String!
describe("Any integer schema") {
beforeEach {
schema = SpecIntegerSchemaSeeds.any
schemaYAML = SpecIntegerSchemaSeeds.anyYAML
}
it("should be correctly decoded from YAML string") {
do {
let decodedSchema = try YAMLDecoder.test.decode(
SpecIntegerSchema.self,
from: schemaYAML
)
expect(decodedSchema).to(equal(schema))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
it("should be correctly encoded to YAML string") {
do {
let encodedSchemaYAML = try YAMLEncoder.test.encode(schema)
expect(encodedSchemaYAML).to(equal(try schemaYAML.yamlSorted()))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
}
describe("Video duration integer schema") {
beforeEach {
schema = SpecIntegerSchemaSeeds.videoDuration
schemaYAML = SpecIntegerSchemaSeeds.videoDurationYAML
}
it("should be correctly decoded from YAML string") {
do {
let decodedSchema = try YAMLDecoder.test.decode(
SpecIntegerSchema.self,
from: schemaYAML
)
expect(decodedSchema).to(equal(schema))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
it("should be correctly encoded to YAML string") {
do {
let encodedSchemaYAML = try YAMLEncoder.test.encode(schema)
expect(encodedSchemaYAML).to(equal(try schemaYAML.yamlSorted()))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
}
describe("Content rating integer schema") {
beforeEach {
schema = SpecIntegerSchemaSeeds.contentRating
schemaYAML = SpecIntegerSchemaSeeds.contentRatingYAML
}
it("should be correctly decoded from YAML string") {
do {
let decodedSchema = try YAMLDecoder.test.decode(
SpecIntegerSchema.self,
from: schemaYAML
)
expect(decodedSchema).to(equal(schema))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
it("should be correctly encoded to YAML string") {
do {
let encodedSchemaYAML = try YAMLEncoder.test.encode(schema)
expect(encodedSchemaYAML).to(equal(try schemaYAML.yamlSorted()))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
}
describe("UID integer schema") {
beforeEach {
schema = SpecIntegerSchemaSeeds.uid
schemaYAML = SpecIntegerSchemaSeeds.uidYAML
}
it("should be correctly decoded from YAML string") {
do {
let decodedSchema = try YAMLDecoder.test.decode(
SpecIntegerSchema.self,
from: schemaYAML
)
expect(decodedSchema).to(equal(schema))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
it("should be correctly encoded to YAML string") {
do {
let encodedSchemaYAML = try YAMLEncoder.test.encode(schema)
expect(encodedSchemaYAML).to(equal(try schemaYAML.yamlSorted()))
} catch {
fail("Test encountered unexpected error: \(error)")
}
}
}
describe(".format") {
context("when integer format is known") {
beforeEach {
schema = SpecIntegerSchemaSeeds.uid
}
it("should return the format") {
expect(schema.format).to(equal(.int64))
}
it("should set `rawFormat` to `rawValue` of the new format") {
schema.format = .int32
expect(schema.rawFormat).to(equal(SpecIntegerFormat.int32.rawValue))
}
}
context("when integer format is not specified") {
beforeEach {
schema = SpecIntegerSchemaSeeds.any
}
it("should return nil") {
expect(schema.format).to(beNil())
}
it("should set `rawFormat` to `rawValue` of the new format") {
schema.format = .int32
expect(schema.rawFormat).to(equal(SpecIntegerFormat.int32.rawValue))
}
}
}
}
}
|
//
// TagItemModelContainer.swift
// mobiita
//
// Created by 三木俊作 on 2017/01/02.
// Copyright © 2017年 Shunsaku Miki. All rights reserved.
//
import UIKit
class TagItemModelContainer: BaseContainer<TagItemModel> {
// MARK: - Methods
/// データ取得
///
/// - Parameters:
/// - page: ページ
/// - perPage: リクエスト要素数
/// - query: クエリ
/// - completion: データ取得完了後コールバック
func featchData(_ page: String?, perPage: String?, sort: String?, completionHandler: @escaping ConnectionResultHandler) {
ConnectionManager.sharedInstance.getTagListApi(page: page, perPage: perPage, sort: sort) { (data) in
if data.result.isSuccess {
guard let data = data.result.value as? [[String: Any]] else {
completionHandler(.failed)
return
}
data.forEach({
guard let tagItemModel = TagItemModel(data: $0) else {
return
}
self.modelList.append(tagItemModel)
})
completionHandler(.success)
} else {
completionHandler(.failed)
}
}
}
}
|
//
// TestWindow.swift
// PersonalityTest
//
// Created by Mykola Denysyuk on 9/15/17.
// Copyright © 2017 Mykola Denysyuk. All rights reserved.
//
import UIKit
class TestWindow: UIWindow {
enum IsCalled {
case not
case didSetRootController(UIViewController?)
case makeKeyAndVisible
}
fileprivate(set) var isCalled = IsCalled.not {
didSet {
allCalls.append(isCalled)
}
}
fileprivate(set) var allCalls = [IsCalled]()
override var rootViewController: UIViewController? {
didSet {
super.rootViewController = rootViewController
isCalled = .didSetRootController(rootViewController)
}
}
override func makeKeyAndVisible() {
// super.makeKeyAndVisible()
isCalled = .makeKeyAndVisible
}
}
|
//
// SHPlayer.swift
// SHPlayer
//
// Created by ray on 2021/6/29.
//
import IJKMediaFramework
import UIKit
public class SHPlayer: UIView {
public var url:URL?
var player:IJKFFMoviePlayerController?
public override init(frame: CGRect) {
super.init(frame: frame)
self.initCommon()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
self.initCommon()
}
func initCommon() {
self.toPlay()
}
public func play(url:String) {
if url.hasPrefix("http") || url.hasPrefix("rtmp") {
self.url = URL.init(string: url)
}else{
self.url = URL.init(fileURLWithPath: url)
}
self.toPlay()
}
func toPlay() {
IJKFFMoviePlayerController.checkIfFFmpegVersionMatch(true)
guard let options = IJKFFOptions.byDefault() else {
return
}
// options?.setValue("ijklas", forKey: "iformat")
// options?.setValue("ijklas", forKey: "iformat")
// options?.setValue("ijklas", forKey: "iformat")
guard let url = self.url else {
return
}
self.player?.view.removeFromSuperview()
self.player = IJKFFMoviePlayerController.init(contentURL: url, with: options)
self.player?.view.autoresizingMask = [.flexibleWidth,.flexibleHeight]
self.player?.view.frame = self.bounds
self.player?.scalingMode = .aspectFit
self.player?.shouldAutoplay = true;
self.autoresizesSubviews = true
if let view = self.player?.view {
self.backgroundColor = .red
self.addSubview(view)
}
}
public func prepareToPlay() {
self.player?.prepareToPlay()
}
}
|
import Foundation
import SpriteKit
class SSScenarioController {
weak var window: NSWindow!
var windowDelegate: SSMainWindowDelegate!
var view: SKView!
var logController: SSLogController!
var alertController: SSAlertController!
var pathHandle: SSPathHandle!
var audioCenter: SSAudioPlayerCenter!
var videoCenter: SSVideoPlayerCenter!
var imageHandle: SSImageHandle!
var sentences: [SSSentence] = []
var executingIndex = 0
var preConfigs: [SSSentence] = []
var mainScene: SSScenarioScene!
var commandType: [String: (delegate: SSCommandDelegate, timeLineMope: SSSentencesTimeLineMode)]!
init(window: NSWindow) {
self.window = window
self.logController = SSLogController(scenarioController: self)
self.alertController = SSAlertController(scenarioController: self)
self.pathHandle = SSPathHandle(scenarioController: self)
self.audioCenter = SSAudioPlayerCenter(scenarioController: self)
self.videoCenter = SSVideoPlayerCenter(scenarioController: self)
self.imageHandle = SSImageHandle(scenarioController: self)
self.makeView()
self.windowDelegate = SSMainWindowDelegate(window: window, scenarioController: self)
self.window.delegate = self.windowDelegate
}
func loadScenario() -> Bool {
if pathHandle.openDirectory() {
let loadScene = SSLoadScene(size: SSConfigCenter.getConfig().viewSize)
loadScene.scaleMode = .AspectFit
loadScene.transitSceneBlock = { self.view.presentScene(self.mainScene, transition: SKTransition.fadeWithDuration(SSConfigCenter.getConfig().sceneFadeDuration)) }
view.presentScene(loadScene)
let loader = SSScenarioLoader(scenarioController: self)
let scripts = loader.getScripts()
if scripts == [] { return false }
NSOperationQueue().addOperationWithBlock {
self.mainScene = SSScenarioScene(scenarioController: self)
self.mainScene.scaleMode = .AspectFit
loader.loadToController(scripts)
self.makeScenario()
loadScene.hasFinishLoading = true
}
return true
} else { return false }
}
func makeScenario() {
let allSentences = sentences + preConfigs
for sentence in allSentences { sentence.review() }
makeStatistics()
for sentence in allSentences { sentence.prepare() }
sentences.append(SSEndSentence(scenarioController: self))
}
func makeStatistics() {
//todo
}
func executePreConfiguration() {
for command in preConfigs {
command.execute()
}
}
func promoteScenario() {
let sentence = sentences[executingIndex]
sentence.execute()
if sentence.timeLineMode == .End { return }
if sentence.timeLineMode != .Asynchronize { executingIndex++ }
if sentence.timeLineMode == .Continue { promoteScenario() }
}
func freeResource() {
self.view.removeFromSuperview()
self.view = nil
self.mainScene = nil
executingIndex = 0
sentences = []
preConfigs = []
audioCenter.freeResource()
videoCenter.freeResource()
imageHandle.freeResource()
pathHandle.inScenarioPath = false
}
func makeView() {
let viewSize = SSConfigCenter.getConfig().viewSize
self.window.setContentSize(viewSize)
self.window.center()
self.view = SKView(frame: NSRect(origin: CGPoint.zero, size: viewSize))
self.window.contentView!.addSubview(self.view)
}
} |
//
// MJNViewModel.swift
// mojn
//
// Created by Kasper Kronborg on 27/02/2019.
// Copyright © 2019 Casper Rogild Storm. All rights reserved.
//
import Foundation
public protocol ViewModel { }
|
//
// TMDeepLinkParser.swift
// consumer
//
// Created by Vladislav Zagorodnyuk on 8/22/16.
// Copyright © 2016 Human Ventures Co. All rights reserved.
//
import UIKit
import EZSwiftExtensions
let TMInternalURL = "tkn://"
// Path for parsing
struct TMDeepLinkPath {
var pathString: String
var objectID: String?
var action: String?
init(pathString: String, objectID: String?, action: String? = nil) {
self.pathString = pathString
self.objectID = objectID
self.action = action
}
}
class TMDeepLinkParser: NSObject {
// Shared parser
static var sharedParser = TMDeepLinkParser()
var closuresArray: [String: (_ objectID: String?, _ action: String?)->()] = [:]
// Parse path
func parsePath(_ path: TMDeepLinkPath, resultFound: ((_ objectID: String?, _ action: String?)-> ())?) {
// Checking all initialized paths
for (_, key) in closuresArray.keys.enumerated() {
if path.pathString == key {
// Run closure associated with path
let closure = closuresArray[key]
closure?(path.objectID, path.action)
}
}
}
// Initializing path string with closure
func path(_ string: String, resultFound: ((_ objectID: String?, _ action: String?) -> ())?) {
if let resultFound = resultFound {
self.closuresArray[string] = resultFound
}
}
// Handle path url
class func handlePathURL(_ url: URL?, completion: ((_ objectID: String?, _ action: String?)-> Void)?) {
guard let url = url else {
completion?(nil, nil)
return
}
ez.runThisAfterDelay(seconds: 0.1, after: {
// Using absolute string path
self.handlePath(url.absoluteString, completion: completion)
})
}
// Handle path string
class func handlePath(_ string: String?, completion: ((_ objectID: String?, _ action: String?)-> Void)?) {
let parser = self.sharedParser
guard let string = string else {
completion?(nil, nil)
return
}
// Extracting path
let resultPath = TMDeepLinkParser.extractPathFromString(string)
if let resultPath = resultPath {
parser.parsePath(resultPath, resultFound: completion)
return
}
completion?(nil, nil)
return
// Couldn't parse - handle later
}
// MARK: - Utilities
class func extractPathFromString(_ string: String)-> TMDeepLinkPath? {
let resultString = self.getCleanPath(string)
var action = ""
var section = ""
var objectID = ""
// Cleaning path from params
let arrayForPath = resultString.components(separatedBy: "/")
if arrayForPath.count > 0 {
section = arrayForPath.first!
}
if arrayForPath.count >= 1 {
objectID = arrayForPath[1]
}
if arrayForPath.count > 2 {
action = arrayForPath[2]
}
// Creating path
let path = TMDeepLinkPath(pathString: section, objectID: objectID, action: action)
return path
}
class func getCleanPath(_ string: String)-> String {
// Checking for local internal utl - tkn://
if string.contains(TMInternalURL) {
// Removing Base URL
return string.replacingOccurrences(of: TMInternalURL, with: "")
}
return string
}
// MARK: - Parsing notification dict
class func getDeeplinkPathFrom(_ userInfo: [AnyHashable: Any])-> String? {
// Handle transitions here, check for synch loading state
guard let dataDict = userInfo["aps"] as? [String: Any] else {
return nil
}
guard let customData = dataDict["custom_data"] as? [String: Any] else {
return nil
}
guard let userInfo = customData["token_action"] else {
return nil
}
return userInfo as? String
}
}
|
//
// HourlyCVCell.swift
// weatherOrNot
//
// Created by John Gibson on 9/1/19.
// Copyright © 2019 John Gibson. All rights reserved.
//
import UIKit
class HourlyCVCell: UICollectionViewCell {
@IBOutlet weak var TimeLabel: UILabel!
@IBOutlet weak var WeatherIcon: UIImageView!
@IBOutlet weak var TempLabel: UILabel!
@IBOutlet weak var precipLabel: UILabel!
}
|
//
// Constants.swift
// OnlineHomeAssement
//
// Created by Ritesh Patil on 2/5/20.
// Copyright © 2020 Ritesh Patil. All rights reserved.
//
import Foundation
import UIKit
let BASE_URL = "https://connect.mindbodyonline.com/rest"
let kTABLEVIEW_SEPARATOR_COLOR = UIColor(red: 232.0 / 255.0, green: 88.0 / 255.0, blue: 27.0 / 255.0, alpha: 1)
let kTABLEVIEW_SEPARATOR_COLOR_WITH_ALPHA = UIColor(red: 232.0 / 255.0, green: 88.0 / 255.0, blue: 27.0 / 255.0, alpha: 0.5)
|
//
// ViewController.swift
// ByteCoin
//
// Created by Angela Yu on 11/09/2019.
// Copyright © 2019 The App Brewery. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var valueLbl: UILabel!
@IBOutlet weak var currencyLbl: UILabel!
@IBOutlet weak var currencyPckr: UIPickerView!
var coinManager = CoinManager()
override func viewDidLoad() {
super.viewDidLoad()
currencyPckr.dataSource = self
currencyPckr.delegate = self
coinManager.delegate = self
coinManager.getCoinPrice(for: "PHP")
}
}
//MARK: - UIPickerViewDataSource
extension ViewController: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return coinManager.currencyArray.count
}
}
//MARK: - UIPickerViewDelegate
extension ViewController: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return coinManager.currencyArray[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let selectedCurrency = coinManager.currencyArray[row]
coinManager.getCoinPrice(for: selectedCurrency)
}
}
//MARK: - CoinManagerDelegate
extension ViewController: CoinManagerDelegate {
func didFailWithError(error: Error) {
let alert = UIAlertController(title: "ERROR", message: "\(error)", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
DispatchQueue.main.async {
self.present(alert, animated: true, completion: nil)
self.valueLbl.text = ""
self.currencyLbl.text = ""
}
}
func didSucceed(coinManager: CoinManager, response: ResponseModel) {
DispatchQueue.main.async {
self.valueLbl.text = response.rate
self.currencyLbl.text = response.currency
}
}
}
|
// Copyright 2017 IBM RESEARCH. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
import Foundation
/**
Quantum Program Class.
Class internal properties.
Elements that are not python identifiers or string constants are denoted
by "--description (type)--". For example, a circuit's name is denoted by
"--circuit name (string)--" and might have the value "teleport".
Internal::
__quantum_registers (list[dic]): An dictionary of quantum registers
used in the quantum program.
__quantum_registers =
{
--register name (string)--: QuantumRegistor,
}
__classical_registers (list[dic]): An ordered list of classical registers
used in the quantum program.
__classical_registers =
{
--register name (string)--: ClassicalRegistor,
}
__quantum_program (dic): An dictionary of quantum circuits
__quantum_program =
{
--circuit name (string)--: --circuit object --,
}
__init_circuit (obj): A quantum circuit object for the initial quantum
circuit
__ONLINE_BACKENDS (list[str]): A list of online backends
__LOCAL_BACKENDS (list[str]): A list of local backends
*/
//# -- FUTURE IMPROVEMENTS --
//# TODO: for status results make ALL_CAPS (check) or some unified method
//# TODO: Jay: coupling_map, basis_gates will move into a config object
//# only exists once you set the api to use the online backends
public final class QCircuit {
public let name: String
public let circuit: QuantumCircuit
public private(set) var execution: [String:Any] = [:]
init(_ name: String, _ circuit: QuantumCircuit) {
self.name = name
self.circuit = circuit
}
}
public final class QProgram {
public private(set) var circuits: [String: QCircuit] = [:]
func setCircuit(_ name: String, _ circuit: QCircuit) {
self.circuits[name] = circuit
}
}
public final class APIConfig {
public let token: String
public let url: URL
init(_ token: String = "None" , _ url: String = Qconfig.BASEURL) throws {
guard let u = URL(string: url) else {
throw IBMQuantumExperienceError.invalidURL(url: url)
}
self.token = token
self.url = u
}
}
public final class QuantumProgram {
final class JobProcessorData {
let jobProcessor: JobProcessor
let callbackSingle: ((_:Result) -> Void)?
let callbackMultiple: ((_:[Result]) -> Void)?
init(_ jobProcessor: JobProcessor,
_ callbackSingle: ((_:Result) -> Void)?,
_ callbackMultiple: ((_:[Result]) -> Void)?) {
self.jobProcessor = jobProcessor
self.callbackSingle = callbackSingle
self.callbackMultiple = callbackMultiple
}
}
private var jobProcessors: [String: JobProcessorData] = [:]
private var __LOCAL_BACKENDS: Set<String> = Set<String>()
/**
only exists once you set the api to use the online backends
*/
private var __api: IBMQuantumExperience? = nil
private var __api_config: APIConfig
private var __quantum_registers: [String: QuantumRegister] = [:]
private var __classical_registers: [String: ClassicalRegister] = [:]
/**
stores all the quantum programs
*/
private var __quantum_program: QProgram
/**
stores the intial quantum circuit of the program
*/
private var __init_circuit: QuantumCircuit? = nil
private var config: Qconfig
static private func convert(_ name: String) throws -> String {
do {
let first_cap_re = try NSRegularExpression(pattern:"(.)([A-Z][a-z]+)")
let s1 = first_cap_re.stringByReplacingMatches(in: name,
options: [],
range: NSMakeRange(0, name.characters.count),
withTemplate: "\\1_\\2")
let all_cap_re = try NSRegularExpression(pattern:"([a-z0-9])([A-Z])")
return all_cap_re.stringByReplacingMatches(in: s1,
options: [],
range: NSMakeRange(0, s1.characters.count),
withTemplate: "\\1_\\2").lowercased()
} catch {
throw QISKitError.internalError(error: error)
}
}
public init(specs: [String:Any]? = nil) throws {
self.__api_config = try APIConfig()
self.config = try Qconfig()
self.__quantum_program = QProgram()
self.__LOCAL_BACKENDS = BackendUtils.local_backends()
if let s = specs {
try self.__init_specs(s)
}
}
/**
Populate the Quantum Program Object with initial Specs
Args:
specs (dict):
Q_SPECS = {
"circuits": [{
"name": "Circuit",
"quantum_registers": [{
"name": "qr",
"size": 4
}],
"classical_registers": [{
"name": "cr",
"size": 4
}]
}],
verbose (bool): controls how information is returned.
Returns:
Sets up a quantum circuit.
*/
private func __init_specs(_ specs:[String: Any], verbose: Bool=false) throws {
var quantumr:[QuantumRegister] = []
var classicalr:[ClassicalRegister] = []
if let circuits = specs["circuits"] as? [Any] {
for circ in circuits {
if let circuit = circ as? [String:Any] {
if let qregs = circuit["quantum_registers"] as? [[String:Any]] {
quantumr = try self.create_quantum_registers(qregs)
}
if let cregs = circuit["classical_registers"] as? [[String:Any]] {
classicalr = try self.create_classical_registers(cregs)
}
var name: String = "name"
if let n = circuit["name"] as? String {
name = n
}
try self.create_circuit(name,quantumr,classicalr)
}
}
// TODO: Jay: I think we should return function handles for the registers
// and circuit. So that we dont need to get them after we create them
// with get_quantum_register etc
}
}
/**
Create a new Quantum Register.
Args:
name (str): the name of the quantum register
size (int): the size of the quantum register
verbose (bool): controls how information is returned.
Returns:
internal reference to a quantum register in __quantum_registers
*/
@discardableResult
public func create_quantum_register(_ name: String, _ size: Int, verbose: Bool=false) throws -> QuantumRegister {
if let register = self.__quantum_registers[name] {
if size != register.size {
throw QISKitError.registerSize
}
if verbose {
print(">> quantum_register exists: \(name) \(size)")
}
}
else {
if verbose {
print(">> new quantum_register created: \(name) \(size)")
}
try self.__quantum_registers[name] = QuantumRegister(name, size)
}
return self.__quantum_registers[name]!
}
/**
Create a new set of Quantum Registers based on a array of them.
Args:
register_array (list[dict]): An array of quantum registers in
dictionay format::
"quantum_registers": [
{
"name": "qr",
"size": 4
},
...
]
Returns:
Array of quantum registers objects
*/
@discardableResult
public func create_quantum_registers(_ register_array: [[String: Any]]) throws -> [QuantumRegister] {
var new_registers: [QuantumRegister] = []
for register in register_array {
guard let name = register["name"] as? String else {
continue
}
guard let size = register["size"] as? Int else {
continue
}
new_registers.append(try self.create_quantum_register(name,size))
}
return new_registers
}
/**
Create a new Classical Register.
Args:
name (str): the name of the Classical register
size (int): the size of the Classical register
verbose (bool): controls how information is returned.
Returns:
internal reference to a Classical register in __classical_registers
*/
@discardableResult
public func create_classical_register(_ name: String, _ size: Int, verbose: Bool=false) throws -> ClassicalRegister {
if let register = self.__classical_registers[name] {
if size != register.size {
throw QISKitError.registerSize
}
if verbose {
print(">> classical register exists: \(name) \(size)")
}
}
else {
if verbose {
print(">> new classical register created: \(name) \(size)")
}
try self.__classical_registers[name] = ClassicalRegister(name, size)
}
return self.__classical_registers[name]!
}
/**
Create a new set of Classical Registers based on a array of them.
Args:
register_array (list[dict]): An array of classical registers in
dictionay format::
"quantum_registers": [
{
"name": "qr",
"size": 4
},
...
]
Returns:
Array of classical registers objects
*/
@discardableResult
public func create_classical_registers(_ register_array: [[String: Any]]) throws -> [ClassicalRegister] {
var new_registers: [ClassicalRegister] = []
for register in register_array {
guard let name = register["name"] as? String else {
continue
}
guard let size = register["size"] as? Int else {
continue
}
new_registers.append(try self.create_classical_register(name,size))
}
return new_registers
}
/**
Create a empty Quantum Circuit in the Quantum Program.
Args:
name (str): the name of the circuit
qregisters list(object): is an Array of Quantum Registers by object reference
cregisters list(object): is an Array of Classical Registers by
object reference
Returns:
A quantum circuit is created and added to the Quantum Program
*/
@discardableResult
public func create_circuit(_ name: String,
_ qregisters: [QuantumRegister] = [],
_ cregisters: [ClassicalRegister] = []) throws -> QuantumCircuit {
let quantum_circuit = QuantumCircuit()
if self.__init_circuit == nil {
self.__init_circuit = quantum_circuit
}
try quantum_circuit.add(qregisters)
try quantum_circuit.add(cregisters)
try self.add_circuit(name, quantum_circuit)
return self.__quantum_program.circuits[name]!.circuit
}
/**
Add a new circuit based on an Object representation.
Args:
name (str): the name of the circuit to add.
quantum_circuit: a quantum circuit to add to the program-name
Returns:
the quantum circuit is added to the object.
*/
@discardableResult
public func add_circuit(_ name: String, _ quantum_circuit: QuantumCircuit) throws -> QuantumCircuit {
for (qname, qreg) in quantum_circuit.get_qregs() {
try self.create_quantum_register(qname, qreg.size)
}
for (cname, creg) in quantum_circuit.get_cregs() {
try self.create_classical_register(cname, creg.size)
}
self.__quantum_program.setCircuit(name,QCircuit(name, quantum_circuit))
return quantum_circuit
}
/**
Load qasm file into the quantum program.
Args:
qasm_file (str): a string for the filename including its location.
name (str or None, optional): the name of the quantum circuit after
loading qasm text into it. If no name is give the name is of
the text file.
verbose (bool, optional): controls how information is returned.
Retuns:
Adds a quantum circuit with the gates given in the qasm file to the
quantum program and returns the name to be used to get this circuit
*/
func load_qasm(qasm_file: String, name: String? = nil, verbose: Bool = false,
basis_gates: String = "u1,u2,u3,cx,id") throws -> String {
var n: String = ""
if name != nil {
n = name!
}
else {
n = (qasm_file as NSString).lastPathComponent
}
return try self.load_qasm(Qasm(filename:qasm_file),n,verbose,basis_gates)
}
/**
Load qasm string in the quantum program.
Args:
qasm_string (str): a string for the file name.
name (str): the name of the quantum circuit after loading qasm
text into it. If no name is give the name is of the text file.
verbose (bool): controls how information is returned.
Retuns:
Adds a quantum circuit with the gates given in the qasm string to the
quantum program.
*/
public func load_qasm_text(qasm_string: String, name: String? = nil, verbose: Bool = false,
basis_gates: String = "u1,u2,u3,cx,id") throws -> String {
var n: String = ""
if name != nil {
n = name!
}
else {
n = String.randomAlphanumeric(length: 10)
}
return try self.load_qasm(Qasm(data:qasm_string),n,verbose,basis_gates)
}
private func load_qasm(_ qasm: Qasm, _ name: String, _ verbose: Bool, _ basis_gates: String) throws -> String {
let node_circuit = try qasm.parse()
if verbose {
print("circuit name: \(name)")
print("******************************")
print(node_circuit.qasm(15))
}
// current method to turn it a DAG quantum circuit.
let unrolled_circuit = Unroller(node_circuit, CircuitBackend(basis_gates.components(separatedBy:",")))
let circuit_unrolled = try unrolled_circuit.execute() as! QuantumCircuit
try self.add_circuit(name, circuit_unrolled)
return name
}
/**
Return a Quantum Register by name.
Args:
name (str): the name of the register
Returns:
The quantum registers with this name
*/
@discardableResult
public func get_quantum_register(_ name: String) throws -> QuantumRegister {
guard let reg = self.__quantum_registers[name] else {
throw QISKitError.regNotExists(name: name)
}
return reg
}
/**
Return a Classical Register by name.
Args:
name (str): the name of the register
Returns:
The classical registers with this name
*/
@discardableResult
public func get_classical_register(_ name: String) throws -> ClassicalRegister {
guard let reg = self.__classical_registers[name] else {
throw QISKitError.regNotExists(name: name)
}
return reg
}
/**
Return all the names of the quantum Registers.
*/
public func get_quantum_register_names() -> [String] {
return Array(self.__quantum_registers.keys)
}
/**
Return all the names of the classical Registers.
*/
public func get_classical_register_names() -> [String] {
return Array(self.__classical_registers.keys)
}
/**
Return a Circuit Object by name
Args:
name (str): the name of the quantum circuit
Returns:
The quantum circuit with this name
*/
@discardableResult
public func get_circuit(_ name: String) throws -> QuantumCircuit {
guard let qCircuit = self.__quantum_program.circuits[name] else {
throw QISKitError.missingCircuit
}
return qCircuit.circuit
}
/**
Return all the names of the quantum circuits.
*/
public func get_circuit_names() -> [String] {
return Array(self.__quantum_program.circuits.keys)
}
/**
Get qasm format of circuit by name.
Args:
name (str): name of the circuit
Returns:
The quantum circuit in qasm format
*/
public func get_qasm(_ name: String) throws -> String {
let quantum_circuit = try self.get_circuit(name)
return quantum_circuit.qasm()
}
/**
Get qasm format of circuit by list of names.
Args:
list_circuit_name (list[str]): names of the circuit
Returns:
List of quantum circuit in qasm format
*/
public func get_qasms(_ list_circuit_name: [String]) throws -> [String] {
var qasm_source: [String] = []
for name in list_circuit_name {
qasm_source.append(try self.get_qasm(name))
}
return qasm_source
}
/**
Return the initialization Circuit.
*/
public func get_initial_circuit() -> QuantumCircuit? {
return self.__init_circuit
}
/**
Setup the API.
Args:
Token (str): The token used to register on the online backend such
as the quantum experience.
URL (str): The url used for online backend such as the quantum
experience.
Returns:
Nothing but fills __api, and __api_config
*/
public func set_api(token: String, url: String) throws {
self.__api_config = try APIConfig(token,url)
self.__api = try IBMQuantumExperience(self.__api_config.token, try Qconfig(url: self.__api_config.url.absoluteString))
}
/**
Return the program specs
*/
public func get_api_config() -> APIConfig {
return self.__api_config
}
/**
Returns a function handle to the API
*/
public func get_api() -> IBMQuantumExperience? {
return self.__api
}
/**
Save Quantum Program in a Json file.
Args:
file_name (str): file name and path.
beauty (boolean): save the text with indent to make it readable.
Returns:
The dictionary with the result of the operation
*/
public func save(_ file_name: String, _ beauty: Bool = false) throws -> [String:[String:Any]] {
do {
let elements_to_save = self.__quantum_program.circuits
var elements_saved: [String:[String:Any]] = [:]
for (name,value) in elements_to_save {
elements_saved[name] = [:]
elements_saved[name]!["qasm"] = value.circuit.qasm()
}
let options = beauty ? JSONSerialization.WritingOptions.prettyPrinted : []
let data = try JSONSerialization.data(withJSONObject: elements_saved, options: options)
let contents = String(data: data, encoding: .utf8)
try contents?.write(toFile: file_name, atomically: true, encoding: .utf8)
return elements_saved
} catch {
throw QISKitError.internalError(error: error)
}
}
/**
Load Quantum Program Json file into the Quantum Program object.
Args:
file_name (str): file name and path.
Returns:
The result of the operation
*/
public func load(_ file_name: String) throws -> QProgram {
let elements_loaded = QProgram()
do {
let file = FileHandle(forReadingAtPath: file_name)
let data = file!.readDataToEndOfFile()
let jsonAny = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
if let dict = jsonAny as? [String:[String:Any]] {
for (name,value) in dict {
if let qasm_string = value["qasm"] as? String {
let qasm = Qasm(data:qasm_string)
let node_circuit = try qasm.parse()
// current method to turn it a DAG quantum circuit.
let basis_gates = "u1,u2,u3,cx,id" // QE target basis
let unrolled_circuit = Unroller(node_circuit, CircuitBackend(basis_gates.components(separatedBy:",")))
let circuit_unrolled = try unrolled_circuit.execute() as! QuantumCircuit
elements_loaded.setCircuit(name,QCircuit(name,circuit_unrolled))
}
}
}
self.__quantum_program = elements_loaded
return self.__quantum_program
} catch {
throw QISKitError.internalError(error: error)
}
}
/**
All the backends that are seen by QISKIT.
*/
public func available_backends(responseHandler: @escaping ((_:Set<String>, _:IBMQuantumExperienceError?) -> Void)) {
self.online_backends() { (backends,error) in
if error != nil {
responseHandler([],error)
return
}
var ret = backends
ret.formUnion(self.__LOCAL_BACKENDS)
responseHandler(ret,nil)
}
}
/**
Queries network API if it exists.
Returns
-------
List of online backends if the online api has been set or an empty
list of it has not been set.
*/
public func online_backends(responseHandler: @escaping ((_:Set<String>, _:IBMQuantumExperienceError?) -> Void)) {
guard let api = self.get_api() else {
responseHandler(Set<String>(),nil)
return
}
api.available_backends() { (backends,error) in
if error != nil {
responseHandler([],error)
return
}
var ret: Set<String> = []
for backend in backends {
if let name = backend["name"] as? String {
ret.update(with: name)
}
}
responseHandler(ret,nil)
}
}
/**
Gets online simulators via QX API calls.
Returns
-------
List of online simulator names.
*/
public func online_simulators(responseHandler: @escaping ((_:Set<String>, _:IBMQuantumExperienceError?) -> Void)) {
guard let api = self.get_api() else {
responseHandler(Set<String>(),nil)
return
}
api.available_backends() { (backends,error) in
if error != nil {
responseHandler([],error)
return
}
var ret: Set<String> = []
for backend in backends {
guard let simulator = backend["simulator"] as? Bool else {
continue
}
if simulator {
if let name = backend["name"] as? String {
ret.update(with: name)
}
}
}
responseHandler(ret,nil)
}
}
/**
Gets online devices via QX API calls
*/
public func online_devices(responseHandler: @escaping ((_:Set<String>, _:IBMQuantumExperienceError?) -> Void)) {
guard let api = self.get_api() else {
responseHandler(Set<String>(),nil)
return
}
api.available_backends() { (backends,error) in
if error != nil {
responseHandler([],error)
return
}
var ret: Set<String> = []
for backend in backends {
guard let simulator = backend["simulator"] as? Bool else {
continue
}
if !simulator {
if let name = backend["name"] as? String {
ret.update(with: name)
}
}
}
responseHandler(ret,nil)
}
}
/**
Return the online backend status via QX API call or by local
backend is the name of the local or online simulator or experiment
*/
public func get_backend_status(_ backend: String,
responseHandler: @escaping ((_:[String:Any]?, _:IBMQuantumExperienceError?) -> Void)) {
self.online_backends() { (backends,error) in
if error != nil {
responseHandler(nil,error)
return
}
if backends.contains(backend) {
guard let api = self.get_api() else {
responseHandler(nil,IBMQuantumExperienceError.errorBackend(backend: backend))
return
}
api.backend_status(backend: backend,responseHandler: responseHandler)
return
}
if self.__LOCAL_BACKENDS.contains(backend) {
responseHandler(["available" : true],nil)
return
}
responseHandler(nil,IBMQuantumExperienceError.errorBackend(backend: backend))
}
}
/**
Return the configuration of the backend
*/
public func get_backend_configuration(_ backend: String, _ list_format: Bool = false,
responseHandler: @escaping ((_:[String:Any]?, _:IBMQuantumExperienceError?) -> Void)) {
guard let api = self.get_api() else {
do {
responseHandler(try BackendUtils.get_backend_configuration(backend),nil)
}
catch {
responseHandler(nil,IBMQuantumExperienceError.internalError(error: error))
}
return
}
api.available_backends() { (backends,error) in
if error != nil {
responseHandler(nil,error)
return
}
do {
let set = Set<String>(["id", "serial_number", "topology_id", "status", "coupling_map"])
var configuration_edit: [String:Any] = [:]
for configuration in backends {
if let name = configuration["name"] as? String {
if name == backend {
for (key,value) in configuration {
let new_key = try QuantumProgram.convert(key)
// TODO: removed these from the API code
if !set.contains(new_key) {
configuration_edit[new_key] = value
}
if new_key == "coupling_map" {
var conf: String = ""
if let c = value as? String {
conf = c
}
if conf == "all-to-all" {
configuration_edit[new_key] = value
}
else {
var cmap = value
if !list_format {
if let list = value as? [[Int]] {
cmap = Coupling.coupling_list2dict(list)
}
}
configuration_edit[new_key] = cmap
}
}
}
responseHandler(configuration_edit,nil)
return
}
}
}
do {
responseHandler(try BackendUtils.get_backend_configuration(backend),nil)
}
catch {
responseHandler(nil,IBMQuantumExperienceError.internalError(error: error))
}
} catch {
responseHandler(nil,IBMQuantumExperienceError.internalError(error: error))
}
}
}
/**
Return the online backend calibrations via QX API call
backend is the name of the experiment
*/
public func get_backend_calibration(_ backend: String,
responseHandler: @escaping ((_:[String:Any]?, _:IBMQuantumExperienceError?) -> Void)) {
self.online_backends() { (backends,error) in
if error != nil {
responseHandler(nil,error)
return
}
if backends.contains(backend) {
guard let api = self.get_api() else {
responseHandler(nil,IBMQuantumExperienceError.errorBackend(backend: backend))
return
}
api.backend_calibration(backend: backend) { (calibrations,error) in
if error != nil {
responseHandler(nil,error)
return
}
do {
var calibrations_edit: [String:Any] = [:]
for (key, vals) in calibrations! {
let new_key = try QuantumProgram.convert(key)
calibrations_edit[new_key] = vals
}
responseHandler(calibrations_edit,nil)
} catch {
responseHandler(nil,IBMQuantumExperienceError.internalError(error: error))
}
}
return
}
if self.__LOCAL_BACKENDS.contains(backend) {
responseHandler(["backend" : backend],nil)
return
}
responseHandler(nil,IBMQuantumExperienceError.errorBackend(backend: backend))
}
}
/**
Return the online backend parameters via QX API call
backend is the name of the experiment
*/
public func get_backend_parameters(_ backend: String,
responseHandler: @escaping ((_:[String:Any]?, _:IBMQuantumExperienceError?) -> Void)) {
self.online_backends() { (backends,error) in
if error != nil {
responseHandler(nil,error)
return
}
if backends.contains(backend) {
guard let api = self.get_api() else {
responseHandler(nil,IBMQuantumExperienceError.errorBackend(backend: backend))
return
}
api.backend_parameters(backend: backend) { (parameters,error) in
if error != nil {
responseHandler(nil,error)
return
}
do {
var parameters_edit: [String:Any] = [:]
for (key, vals) in parameters! {
let new_key = try QuantumProgram.convert(key)
parameters_edit[new_key] = vals
}
responseHandler(parameters_edit,nil)
} catch {
responseHandler(nil,IBMQuantumExperienceError.internalError(error: error))
}
}
return
}
if self.__LOCAL_BACKENDS.contains(backend) {
responseHandler(["backend" : backend],nil)
return
}
responseHandler(nil,IBMQuantumExperienceError.errorBackend(backend: backend))
}
}
/**
Compile the circuits into the exectution list.
This builds the internal "to execute" list which is list of quantum
circuits to run on different backends.
Args:
name_of_circuits (list[str]): circuit names to be compiled.
backend (str): a string representing the backend to compile to
config (dict): a dictionary of configurations parameters for the
compiler
silent (bool): is an option to print out the compiling information
or not
basis_gates (str): a comma seperated string and are the base gates,
which by default are: u1,u2,u3,cx,id
coupling_map (dict): A directed graph of coupling::
{
control(int):
[
target1(int),
target2(int),
, ...
],
...
}
eg. {0: [2], 1: [2], 3: [2]}
initial_layout (dict): A mapping of qubit to qubit::
{
("q", strart(int)): ("q", final(int)),
...
}
eg.
{
("q", 0): ("q", 0),
("q", 1): ("q", 1),
("q", 2): ("q", 2),
("q", 3): ("q", 3)
}
shots (int): the number of shots
max_credits (int): the max credits to use 3, or 5
seed (int): the intial seed the simulatros use
Returns:
the job id and populates the qobj::
qobj =
{
id: --job id (string),
config: -- dictionary of config settings (dict)--,
{
"max_credits" (online only): -- credits (int) --,
"shots": -- number of shots (int) --.
"backend": -- backend name (str) --
}
circuits:
[
{
"name": --circuit name (string)--,
"compiled_circuit": --compiled quantum circuit (DAG format)--,
"config": --dictionary of additional config settings (dict)--,
{
"coupling_map": --adjacency list (dict)--,
"basis_gates": --comma separated gate names (string)--,
"layout": --layout computed by mapper (dict)--,
"seed": (simulator only)--initial seed for the simulator (int)--,
}
},
...
]
}
*/
@discardableResult
public func compile(_ name_of_circuits: [String],
backend: String = "local_qasm_simulator",
config: [String:Any]? = nil,
silent: Bool = true,
basis_gates: String? = nil,
coupling_map: [Int:[Int]]? = nil,
initial_layout: OrderedDictionary<RegBit,RegBit>? = nil,
shots: Int = 1024,
max_credits: Int = 3,
seed: Int? = nil,
qobj_id: String? = nil) throws -> [String:Any] {
// TODO: Jay: currently basis_gates, coupling_map, initial_layout, shots,
// max_credits and seed are extra inputs but I would like them to go
// into the config.
var qobj: [String:Any] = [:]
let qobjId: String = (qobj_id != nil) ? qobj_id! : String.randomAlphanumeric(length: 30)
qobj["id"] = qobjId
qobj["config"] = ["max_credits": max_credits, "backend": backend, "shots": shots]
qobj["circuits"] = []
if name_of_circuits.isEmpty {
throw QISKitError.missingCircuits
}
for name in name_of_circuits {
guard let qCircuit = self.__quantum_program.circuits[name] else {
throw QISKitError.missingQuantumProgram(name: name)
}
var basis: String = "u1,u2,u3,cx,id" // QE target basis
if basis_gates != nil {
basis = basis_gates!
}
// TODO: The circuit object has to have .qasm() method (be careful)
let compiledCircuit = try OpenQuantumCompiler.compile(qCircuit.circuit.qasm(),
basis_gates: basis,
coupling_map: coupling_map,
initial_layout: initial_layout,
silent: silent,
get_layout: true)
// making the job to be added to qoj
var job: [String:Any] = [:]
job["name"] = name
// config parameters used by the runner
let s: Any = seed != nil ? seed! : NSNull()
if var conf = config {
conf["seed"] = s
job["config"] = conf
}
else {
job["config"] = ["seed":s]
}
// TODO: Jay: make config options optional for different backends
if let map = coupling_map {
job["coupling_map"] = Coupling.coupling_dict2list(map)
}
// Map the layout to a format that can be json encoded
if let layout = compiledCircuit.final_layout {
var list_layout: [[[String:Int]]] = []
for (k,v) in layout {
let kDict = [k.name : k.index]
let vDict = [v.name : v.index]
list_layout.append([kDict,vDict])
}
job["layout"] = layout
}
job["basis_gates"] = basis
// the compuled circuit to be run saved as a dag
job["compiled_circuit"] = try OpenQuantumCompiler.dag2json(compiledCircuit.dag!,basis_gates: basis)
job["compiled_circuit_qasm"] = try compiledCircuit.dag!.qasm(qeflag:true)
// add job to the qobj
if var circuits = qobj["circuits"] as? [Any] {
circuits.append(job)
qobj["circuits"] = circuits
}
}
return qobj
}
/**
Print the compiled circuits that are ready to run.
Args:
verbose (bool): controls how much is returned.
*/
@discardableResult
public func get_execution_list(_ qobj: [String: Any], _ verbose: Bool = false) -> [String] {
var execution_list: [String] = []
if verbose {
if let iden = qobj["id"] as? String {
print("id: \(iden)")
}
if let config = qobj["config"] as? [String:Any] {
if let backend = config["backend"] as? String {
print("backend: \(backend)")
}
print("qobj config:")
for (key,value) in config {
if key != "backend" {
print(" \(key) : \(value)")
}
}
}
}
if let circuits = qobj["circuits"] as? [String:[String:Any]] {
for (_,circuit) in circuits {
if let name = circuit["name"] as? String {
execution_list.append(name)
if verbose {
print(" circuit name: \(name)")
}
}
if verbose {
if let config = circuit["config"] as? [String:Any] {
print(" circuit config:")
for (key,value) in config {
print(" \(key) : \(value)")
}
}
}
}
}
return execution_list
}
/**
Get the compiled layout for the named circuit and backend.
Args:
name (str): the circuit name
qobj (str): the name of the qobj
Returns:
the config of the circuit.
*/
public func get_compiled_configuration(_ qobj: [String: Any], _ name: String) throws -> [String:Any] {
if let circuits = qobj["circuits"] as? [[String:Any]] {
for circuit in circuits {
if let n = circuit["name"] as? String {
if n == name {
if let config = circuit["config"] as? [String:Any] {
return config
}
}
}
}
}
throw QISKitError.missingCompiledConfig
}
/**
Print the compiled circuit in qasm format.
Args:
qobj (str): the name of the qobj
name (str): name of the quantum circuit
*/
public func get_compiled_qasm(_ qobj: [String: Any], _ name: String) throws -> String {
if let circuits = qobj["circuits"] as? [[String:Any]] {
for circuit in circuits {
if let n = circuit["name"] as? String {
if n == name {
if let circuit = circuit["compiled_circuit_qasm"] as? String {
return circuit
}
}
}
}
}
throw QISKitError.missingCompiledQasm
}
/**
Run a program (a pre-compiled quantum program) asynchronously. This
is a non-blocking function, so it will return inmediately.
All input for run comes from qobj.
Args:
qobj(dict): the dictionary of the quantum object to
run or list of qobj.
wait (int): Time interval to wait between requests for results
timeout (int): Total time to wait until the execution stops
silent (bool): If true, prints out the running information
callback (fn(result)): A function with signature:
fn(result):
The result param will be a Result object.
*/
public func run_async(_ qobj: [String:Any],
wait: Int = 5,
timeout: Int = 60,
silent: Bool = true,
_ callback: @escaping ((_:Result) -> Void)) {
self._run_internal([qobj],
wait: wait,
timeout: timeout,
silent: silent,
callbackSingle: callback)
}
/**
Run various programs (a list of pre-compiled quantum program)
asynchronously. This is a non-blocking function, so it will return
inmediately.
All input for run comes from qobj.
Args:
qobj_list (list(dict)): The list of quantum objects to run.
wait (int): Time interval to wait between requests for results
timeout (int): Total time to wait until the execution stops
silent (bool): If true, prints out the running information
callback (fn(results)): A function with signature:
fn(results):
The results param will be a list of Result objects, one
Result per qobj in the input list.
*/
public func run_batch_async(_ qobj_list: [[String:Any]],
wait: Int = 5,
timeout: Int = 120,
silent: Bool = true,
_ callback: ((_:[Result]) -> Void)?) {
self._run_internal(qobj_list,
wait: wait,
timeout: timeout,
silent: silent,
callbackMultiple: callback)
}
private func _run_internal(_ qobj_list: [[String:Any]],
wait: Int,
timeout: Int,
silent: Bool,
callbackSingle: ((_:Result) -> Void)? = nil,
callbackMultiple: ((_:[Result]) -> Void)? = nil) {
do {
var q_job_list: [QuantumJob] = []
for qobj in qobj_list {
q_job_list.append(QuantumJob(qobj))
}
let job_processor = try JobProcessor(q_job_list,
callback: self._jobs_done_callback,
api: self.__api)
SyncLock.synchronized(self) {
let data = JobProcessorData(job_processor,
callbackSingle,
callbackMultiple)
self.jobProcessors[data.jobProcessor.identifier] = data
}
job_processor.submit(wait, timeout, silent)
} catch {
var results: [Result] = []
for qobj in qobj_list {
results.append(Result(["status": "ERROR","result": error.localizedDescription],qobj))
}
DispatchQueue.main.async {
if callbackSingle != nil {
callbackSingle?(results[0])
}
else {
callbackMultiple?(results)
}
}
}
}
/**
This internal callback will be called once all Jobs submitted have
finished. NOT every time a job has finished.
Args:
identifier: JobProcessor unique identifier
jobs_results (list): list of Result objects
*/
private func _jobs_done_callback(_ identifier: String, _ jobs_results: [Result]) {
SyncLock.synchronized(self) {
if let data = self.jobProcessors.removeValue(forKey:identifier) {
DispatchQueue.main.async {
if data.callbackSingle != nil {
data.callbackSingle?(jobs_results[0])
}
else {
data.callbackMultiple?(jobs_results)
}
}
}
}
}
/**
Execute, compile, and run an array of quantum circuits).
This builds the internal "to execute" list which is list of quantum
circuits to run on different backends.
Args:
name_of_circuits (list[str]): circuit names to be compiled.
backend (str): a string representing the backend to compile to
config (dict): a dictionary of configurations parameters for the
compiler
wait (int): wait time is how long to check if the job is completed
timeout (int): is time until the execution stops
silent (bool): is an option to print out the compiling information
or not
basis_gates (str): a comma seperated string and are the base gates,
which by default are: u1,u2,u3,cx,id
coupling_map (dict): A directed graph of coupling::
{
control(int):
[
target1(int),
target2(int),
, ...
],
...
}
eg. {0: [2], 1: [2], 3: [2]}
initial_layout (dict): A mapping of qubit to qubit
{
("q", strart(int)): ("q", final(int)),
...
}
eg.
{
("q", 0): ("q", 0),
("q", 1): ("q", 1),
("q", 2): ("q", 2),
("q", 3): ("q", 3)
}
shots (int): the number of shots
max_credits (int): the max credits to use 3, or 5
seed (int): the intial seed the simulatros use
Returns:
status done and populates the internal __quantum_program with the
data
*/
public func execute(_ name_of_circuits: [String],
backend: String = "local_qasm_simulator",
config: [String:Any]? = nil,
wait: Int = 5,
timeout: Int = 60,
silent: Bool = true,
basis_gates: String? = nil,
coupling_map: [Int:[Int]]? = nil,
initial_layout: OrderedDictionary<RegBit,RegBit>? = nil,
shots: Int = 1024,
max_credits: Int = 3,
seed: Int? = nil,
_ callback: @escaping ((_:Result) -> Void)) {
do {
let qobj = try self.compile(name_of_circuits,
backend: backend,
config: config,
silent: silent,
basis_gates: basis_gates,
coupling_map: coupling_map,
initial_layout: initial_layout,
shots: shots,
max_credits: max_credits,
seed: seed)
self.run_async(qobj,
wait: wait,
timeout: timeout,
silent: silent,
callback)
} catch {
DispatchQueue.main.async {
callback(Result(["status": "ERROR","result": error.localizedDescription],[:]))
}
}
}
}
|
import UIKit
class ButtonCell: UICollectionViewCell {
@IBOutlet weak var containView: UIView!
@IBOutlet weak var textLbl: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.containView.layer.shadowOffset = CGSize(width: 0, height: 0)
self.containView.layer.shadowOpacity = 0.4
self.containView.layer.shadowColor = UIColor.black.cgColor
self.containView.layer.masksToBounds = false
}
func setSymbol(symbolStr:String){
self.textLbl.text = symbolStr
}
}
|
//
// Array-Extension.swift
// ZLHJHelpAPP
//
// Created by 周希财 on 2019/9/17.
// Copyright © 2019 VIC. All rights reserved.
//
import Foundation
import UIKit
extension Array {
static func delLabelNameForKey(changeArr: [Dictionary<String,Any>] ) -> [Dictionary<String,Any>]{
if changeArr.isEmpty {return changeArr}
var resultArr:[Dictionary<String,Any>] = [Dictionary<String,Any>]()
for dic in changeArr {
var resultDic:[String:Any] = [:]
for str in dic.keys {
let value = dic[str] as Any
let key:String = str.contains(".") ? str.components(separatedBy: ".").first! : str
resultDic.updateValue(value, forKey: key )
}
resultArr.append(resultDic)
}
return resultArr
}
func getAllvalues() -> Array<String>{
var temp: Array<String> = []
for dic in self{
temp.append((dic as! Dictionary<String, String>).values.first!)
}
return temp
}
func getAllKeys() -> Array<String>{
var temp: Array<String> = []
for dic in self{
temp.append((dic as! Dictionary<String, String>).keys.first!)
}
return temp
}
}
|
//
// ViewController.swift
// TextView
//
// Created by Plunien, Johannes(AWF) on 11/04/16.
// Copyright © 2016 Johannes Plunien. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
dynamic private func keyboardWillHide(notification: NSNotification) {
guard let userInfo = notification.userInfo as? [String : AnyObject] else { return }
guard let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber else { return }
UIView.animateWithDuration(duration.doubleValue) {
self.scrollView.contentInset = UIEdgeInsetsZero
self.scrollView.scrollIndicatorInsets = UIEdgeInsetsZero
}
}
dynamic private func keyboardWillShow(notification: NSNotification) {
guard let userInfo = notification.userInfo as? [String : AnyObject] else { return }
guard let keyboardFrameValue = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue else { return }
guard let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber else { return }
let keyboardFrame = scrollView.convertRect(keyboardFrameValue.CGRectValue(), fromView: nil)
let intersection = CGRectIntersection(keyboardFrame, scrollView.bounds)
if CGRectIsNull(intersection) {
return
}
UIView.animateWithDuration(duration.doubleValue) {
self.scrollView.contentInset = UIEdgeInsetsMake(0, 0, intersection.size.height, 0)
self.scrollView.scrollIndicatorInsets = self.scrollView.contentInset
}
}
}
|
//
// WriteModel.swift
// practice
//
// Created by SangDo on 2017. 7. 2..
// Copyright © 2017년 SangDo. All rights reserved.
//
import UIKit
struct writeList {
static var list = [Write]()
}
class Write {
// static let sharedInstance = Write()
var title: String?
var content: String?
var date: String?
init(){}
//title
func setTitle(title: String) {
self.title = title
}
func getTitle() -> String? {
return self.title
}
//content
func setContent(content: String) {
self.content = content
}
func getContent() -> String? {
return self.content
}
//date
func setDate(date: String) {
self.date = date
}
func getDate() -> String? {
return self.date
}
}
|
//
// QuestionSet.swift
// quizzy
//
// Description:
// Turns the JSON questions into the QuestionSet Codable struct.
//
// Created by Kristen Chen on 12/2/20.
//
import Foundation
import SwiftUI
struct QuestionSet : Codable {
var response_code: Int
var results: [Question]
struct Question: Codable {
var category: String
var type: String
var difficulty: String
var question: String
var correct_answer: String
var incorrect_answers: [String]
}
}
|
//
// GameScene.swift
// iBeacon_posDisplay_demo
//
// Created by menteadmin on 2015/11/24.
// Copyright © 2015年 menteadmin. All rights reserved.
//
import UIKit
import SpriteKit
class GameScene: SKScene{
let pos = SKShapeNode(circleOfRadius: 30)
var setBeaconList:[SKShapeNode] = []
let setBeaconMaxRow = 3
let setBeaconMaxColumn = 3
var repeatForevrAction: SKAction!
var initiated: Bool = false;
let ap = UIApplication.sharedApplication().delegate as! AppDelegate
var minor = 0
var moveLogList = [Int]()
//-------------------------------------------------------------------------------------------------------
func GetMid()->CGPoint{
return CGPointMake(self.frame.midX, self.frame.midY)
}
//-------------------------------------------------------------------------------------------------------
override func didMoveToView(view: SKView) {
// var timer = NSTimer.scheduledTimerWithTimeInterval(1/60, target: self, selector: "update", userInfo: nil, repeats: true)
_ = NSTimer.scheduledTimerWithTimeInterval(1/60, target: self, selector: "update", userInfo: nil, repeats: true)
if ( !initiated ) {
self.initContent()
self.initiated = true
}
}
//-------------------------------------------------------------------------------------------------------
func update() {
minor = ap.minor
// print(minor)
self.initPos()
}
//-------------------------------------------------------------------------------------------------------
func initContent() {
self.backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1.0)
let field = SKShapeNode(rectOfSize: CGSizeMake(200, 400))
field.fillColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1.0)
field.strokeColor = UIColor(red: 44/255, green: 169/255, blue: 225/255, alpha: 0.8)
field.position = GetMid()
self.addChild(field)
setBeaconList = []
for i in 0..<setBeaconMaxRow {
for j in 0..<setBeaconMaxColumn{
let setBeacon = SKShapeNode(circleOfRadius: 8)
setBeacon.fillColor = UIColor(red: 41/255, green: 128/255, blue: 185/255, alpha: 1)
setBeacon.strokeColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1.0)
setBeacon.position = CGPoint(x: 60 + (100 * i), y: 134 + (150 * j))
self.addChild(setBeacon)
setBeaconList.append(setBeacon)
}
}
}
//-------------------------------------------------------------------------------------------------------
func addShape(location: CGPoint) {
pos.fillColor = UIColor(red: 44/255, green: 169/255, blue: 225/255, alpha: 0.4)
pos.strokeColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1.0)
pos.position = location
let scaleAction1 = SKAction.scaleBy(1.6, duration: 1)
let scaleAction2 = SKAction.scaleBy(10/16, duration: 1)
let sequenceAction = SKAction.sequence([
scaleAction1,
scaleAction2
])
self.addChild(pos)
if pos.hasActions() == false {
repeatForevrAction = SKAction.repeatActionForever(sequenceAction)
pos.runAction(repeatForevrAction)
}
}
//-------------------------------------------------------------------------------------------------------
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if ap.moveLogNow == false {
ap.moveLogNow = true
self.backgroundColor = UIColor(red: 35/255, green: 140/255, blue: 220/255, alpha: 1.0)
}
else if ap.moveLogNow == true {
ap.moveLogNow = false
self.backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1.0)
ap.moveLogList.removeAll()
}
}
//-------------------------------------------------------------------------------------------------------
func initPos() {
self.removeChildrenInArray([pos])
switch minor{
case 64756: let location = CGPointMake(self.frame.midX - 100, self.frame.midY + 150)
addShape(location)
case 8181: let location = CGPointMake(self.frame.midX - 100, self.frame.midY)
addShape(location)
case 28326: let location = CGPointMake(self.frame.midX - 100, self.frame.midY - 150)
addShape(location)
case 50749: let location = CGPointMake(self.frame.midX, self.frame.midY + 150)
addShape(location)
case 12738: let location = CGPointMake(self.frame.midX, self.frame.midY)
addShape(location)
case 41990: let location = CGPointMake(self.frame.midX, self.frame.midY - 150)
addShape(location)
case 40455: let location = CGPointMake(self.frame.midX + 100, self.frame.midY + 150)
addShape(location)
case 8978: let location = CGPointMake(self.frame.midX + 100, self.frame.midY)
addShape(location)
case 7744: let location = CGPointMake(self.frame.midX + 100, self.frame.midY - 150)
addShape(location)
default: print("notihng")
}
}
} |
//
// ViewController.swift
// swiftでtwitterclient app
//
// Created by 有村 琢磨 on 2015/02/17.
// Copyright (c) 2015年 takuma arimura. All rights reserved.
//
import UIKit
import Social
import Accounts
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, NSURLConnectionDelegate{
var myComposeView : SLComposeViewController?
var myTwitterButton : UIButton?
var tweetArray :NSMutableArray!
@IBOutlet var timelineTableview : UITableView!
@IBAction func tweetButton(sender : AnyObject) {
myComposeView = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
self.presentViewController(myComposeView!, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.twitterTimeLine()
//pull to refresh
var refreshControll = UIRefreshControl()
refreshControll.addTarget(self, action: "twitterTimeLine", forControlEvents: UIControlEvents.ValueChanged)
self.timelineTableview.addSubview(refreshControll)
// resize cell height automatically
// self.timelineTableview.estimatedRowHeight = 100
// self.timelineTableview.rowHeight = UITableViewAutomaticDimension
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func refresh(){
self.twitterTimeLine()
}
func twitterTimeLine(){
//tweetArrayの初期化
tweetArray = NSMutableArray()
//ACAccountStoreの初期化
var accountStore : ACAccountStore! = ACAccountStore()
let twitterAccountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
//ユーザーにtiwtter情報を使うことの許可を得る
let handler: ACAccountStoreRequestAccessCompletionHandler = {
granted, error in
if(!granted){
NSLog("ユーザーがアクセスを拒否しました")
return
}
let twitterAccounts = accountStore.accountsWithAccountType(twitterAccountType)
NSLog("twitterAccounts = \(twitterAccounts)")
if(twitterAccounts.count > 0){
let account = twitterAccounts[0] as ACAccount
NSLog("account = \(account)")
}
}
accountStore.requestAccessToAccountsWithType(twitterAccountType, options: nil){
granted, error in
if granted == true {
var arrayOfAccounts = accountStore.accountsWithAccountType(twitterAccountType!)
if arrayOfAccounts.count > 0{
var twitterAccount :ACAccount = arrayOfAccounts.last? as ACAccount
var requestAPI : NSURL = NSURL(string:"https://api.twitter.com/1.1/statuses/home_timeline.json")!
//NSMutableDictionaryの初期化
var parameters :NSMutableDictionary = NSMutableDictionary()
parameters.setValue("100", forKey: "count")
parameters.setValue("1", forKey: "include_entities")
//リクエストを生成
var post :SLRequest = SLRequest(forServiceType: SLServiceTypeTwitter,
requestMethod: SLRequestMethod.GET,
URL: requestAPI,
parameters: parameters)
//リクエストに認証情報を付加
post.account = twitterAccount
//ステータスバーのActivity Indicatorを開始
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
//リクエストを発行
post.performRequestWithHandler({response, urlResponse, urlerror
in
var arrayForRemoteData = NSJSONSerialization.JSONObjectWithData(response, options: NSJSONReadingOptions(), error: nil) as NSMutableArray
println(arrayForRemoteData)
self.tweetArray = arrayForRemoteData
println(self.tweetArray)
if (self.tweetArray.count != 0) {
dispatch_async(dispatch_get_main_queue(), {self.timelineTableview.reloadData()})
}
})
}
//tweet取得完了したらActivity Indicatorを終了
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
} else {
NSLog("%@", error)
}
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweetArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//一旦標準のUITableViewCellにて表示
//TwitterCellクラスに変更
let cell :Twittercell = tableView.dequeueReusableCellWithIdentifier("TweetCell") as Twittercell
if (tweetArray.count > 0) {
var tweet = tweetArray[indexPath.row] as NSDictionary
var userInfo :NSDictionary = tweet["user"] as NSDictionary
cell.twitterIDLabel.text = userInfo["screen_name"] as NSString
cell.twitterNameLabel.text = userInfo["name"] as NSString
cell.tweetTextView.text = tweet["text"] as NSString
var userImagePath :NSString = userInfo["profile_image_url"] as NSString
var userImagePathUrl = NSURL(string: userImagePath)
var userImagepathData = NSData(contentsOfURL: userImagePathUrl!)
cell.twitterIqon.image = UIImage(data: userImagepathData!)
} else {
//FIX: 読み込まれるまで、くるくるを表示させたい所
//なくても良い
}
return cell
}
} |
//
// GeometryReader_SafeAreaInsets.swift
// 100Views
//
// Created by Mark Moeykens on 7/12/19.
// Copyright © 2019 Mark Moeykens. All rights reserved.
//
import SwiftUI
struct GeometryReader_SafeAreaInsets : View {
var body: some View {
VStack(spacing: 10) {
Text("GeometryReader").font(.largeTitle)
Text("SafeAreaInsets")
.font(.title).foregroundColor(.gray)
Text("GeometryReader can also tell you the safe area insets it has.")
.frame(maxWidth: .infinity).padding().font(.title)
GeometryReader { geometry in
VStack {
Text("geometry.safeAreaInsets.leading: \(geometry.safeAreaInsets.leading)")
Text("geometry.safeAreaInsets.trailing: \(geometry.safeAreaInsets.trailing)")
Text("geometry.safeAreaInsets.top: \(geometry.safeAreaInsets.top)")
Text("geometry.safeAreaInsets.bottom: \(geometry.safeAreaInsets.bottom)")
}
}
.font(.title)
.background(Color.pink)
.foregroundColor(.white)
}
}
}
#if DEBUG
struct GeometryReader_SafeAreaInsets_Previews : PreviewProvider {
static var previews: some View {
GeometryReader_SafeAreaInsets()
}
}
#endif
|
//
// Review.swift
// BeeHive
//
// Created by Hyper Design on 9/30/18.
// Copyright © 2018 HyperDesign-Gehad. All rights reserved.
//
import Foundation
class Review : Codable
{
var dateTime : String?
var rate : Int?
var review : String?
var user : User?
enum CodingKeys : String,CodingKey
{
case dateTime = "date_time"
case rate
case review
case user
}
}
|
//
// CitiesResponse.swift
// carWash
//
// Created by Juliett Kuroyan on 09.12.2019.
// Copyright © 2019 VooDooLab. All rights reserved.
//
struct CitiesResponse: Codable {
var cities: [CityResponse]
}
struct CityResponse: Codable {
var city: String
var coordinates: [Double]
var isCurrent: Bool?
}
|
//
// Parameter.swift
// Modeller
//
// Created by Ericsson on 2016-08-03.
// Copyright © 2016 hedgehoglab. All rights reserved.
//
import Foundation
import CoreData
class Parameter: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
convenience init(name: String, value: String, context: NSManagedObjectContext) {
let entity = NSEntityDescription.entityForName("Parameter", inManagedObjectContext: context)
self.init(entity: entity!, insertIntoManagedObjectContext: context)
self.name = name
self.value = value
}
}
|
//
// AddViewController.swift
// Panic Button
//
// Created by Erick Valentin Blanco Puerto on 11/17/16.
// Copyright © 2016 Anexoft. All rights reserved.
//
import UIKit
class AddViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textLabel: UILabel!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var saveBtn: UIBarButtonItem!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var phoneTextField: UITextField!
var index = 0
var data = [Contact]()
override func viewDidLoad() {
super.viewDidLoad()
nameTextField.delegate = self
emailTextField.delegate = self
phoneTextField.delegate = self
if index < data.count {
nameTextField.text = data[index].name
emailTextField.text = data[index].email
phoneTextField.text = data[index].phone
}
else{
nameTextField.text = ""
emailTextField.text = ""
phoneTextField.text = ""
}
saveBtn.isEnabled = false
checkTextFields()
nameTextField.becomeFirstResponder()
emailTextField.becomeFirstResponder()
phoneTextField.becomeFirstResponder()
}
//MARK: Save Button setup
func checkTextFields(){
if nameTextField.text! != "" && emailTextField.text! != "" && phoneTextField.text! != ""{
saveBtn.isEnabled = true
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
checkTextFields()
//saveBtn.isEnabled = true
}
//MARK: Segue way setup
//segue way to return to the contacts view
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ReturnToContacts"{
print("Yes")
dismiss(animated: true, completion: nil)
}
}
//MARK: calling setup
//Used to make phone calls
@IBAction func MakeACall(_ sender: AnyObject) {
if phoneTextField.text != ""{
print("Yes")
if let url = URL(string: "tel://\(phoneTextField.text!)") {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
else{
print("No")
let alert = UIAlertController(title: "Error", message: "There's no phone number", preferredStyle: .alert)
let exit = UIAlertAction(title: "OK", style: .default){
(alertAction: UIAlertAction) in
}
alert.addAction(exit)
self.present(alert, animated: true, completion:nil)
}
}
}
|
import SceneKit
import ARKit
public class Plane: SCNNode {
var planeAnchor: ARPlaneAnchor
var planeGeometry: SCNPlane
var planeNode: SCNNode
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public init(_ anchor: ARPlaneAnchor) {
self.planeAnchor = anchor
let grid = UIImage(named: "grid.png")
let newWidth = CGFloat(anchor.extent.x)
let newHeight = CGFloat(anchor.extent.z)
self.planeGeometry = SCNPlane(width: newWidth, height: newHeight)
let material = SCNMaterial()
material.diffuse.contents = grid
material.diffuse.wrapS = SCNWrapMode.repeat
material.diffuse.wrapT = SCNWrapMode.repeat
// size
material.diffuse.contentsTransform = SCNMatrix4MakeScale(64, 64, 0)
material.transparency = 0.5
self.planeGeometry.materials = [material]
self.planeNode = SCNNode(geometry: planeGeometry)
self.planeNode.eulerAngles.x = -.pi / 2
super.init()
self.addChildNode(planeNode)
self.position = SCNVector3(anchor.center.x, 0, anchor.center.z)
}
public func update(_ anchor: ARPlaneAnchor) {
self.planeAnchor = anchor
self.planeGeometry.width = CGFloat(anchor.extent.x)
self.planeGeometry.height = CGFloat(anchor.extent.z)
self.position = SCNVector3Make(anchor.center.x, 0, anchor.center.z)
}
} |
//
// ViewController.swift
// PhotoPicker
//
// Created by 池川航史 on 2015/07/20.
// Copyright (c) 2015年 池川航史. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet var imageView: UIImageView!
@IBAction func pickButton(sender: UIButton) {
var photoPick = UIImagePickerController()
photoPick.delegate = self;
photoPick.sourceType = .PhotoLibrary;
self.presentViewController(photoPick, animated: true, completion: nil);
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.addSubview(imageView);
self.imageView.backgroundColor = UIColor.blueColor();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//写真選択したら
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]){
imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage;
self.dismissViewControllerAnimated(true, completion: nil);
}
}
|
//
// ExtentReachedViewController.swift
// UCSF
//
// Created by Robert Posada on 4/14/16.
// Copyright © 2016 Jimbus. All rights reserved.
//
import UIKit
let extentReachedKey = "extentReached"
let insertionTimeKey = "insertionTime"
let withdrawlTimeKey = "withdrawlTime"
let prepQualityKey = "prepQuality"
class ExtentReachedViewController: UIViewController, UIPopoverPresentationControllerDelegate, PassBackDelegate {
@IBAction func nextButton(sender: AnyObject) {
if (plist != nil) {
let dict = plist!.getMutablePlistFile()!
dict[extentReachedKey] = extentReachedText.text!
dict[insertionTimeKey] = insertionTime.text!
dict[withdrawlTimeKey] = withdrawlTime.text!
dict[prepQualityKey] = Int(mySlider.value)
do {
try plist!.addValuesToPlistFile(dict)
} catch {
print(error)
}
print(plist!.getValuesInPlistFile())
} else {
print("Unable to get Plist")
}
}
@IBAction func popOver(sender: AnyObject) {
self.performSegueWithIdentifier("showView3", sender: self)
}
@IBOutlet weak var extentReachedButton: UIButton!
@IBOutlet weak var extentReachedText: UITextField!
@IBOutlet weak var mySlider: UISlider!
@IBOutlet weak var insertionTime: UITextField!
@IBOutlet weak var withdrawlTime: UITextField!
@IBAction func sliderChanged(sender: AnyObject) {
sender.setValue(Float(lroundf(mySlider.value)), animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Extent Reached"
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showView3" {
let destination = segue.destinationViewController as! ExtentReachedPopoverViewController
let controller = destination.popoverPresentationController
destination.passBackDelegate = self
// Sets the coordinates of the popover arrow so that it points to the middle of the anchor view.
segue.destinationViewController.popoverPresentationController?.sourceRect = CGRectMake(extentReachedButton.frame.size.width/2, extentReachedButton.frame.size.height, 0, 0)
if controller != nil {
controller?.delegate = self
}
}
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
func sendString(myString: String) {
extentReachedText.text = myString
}
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
import Foundation
/*
Q132 Palindrome Partitioning II (Hard)
Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
For example, given s = "aab",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.
*/
/*
Prep work:
isPalindrome[i][j]: a 2D array recrod is the substring(i, j) a palindrome
minCuts[i]: f(i) minimum cuts to make all substrings palindrome from f[i] - f[n-1]
Initialize minCuts[i] for the worst case: f(i) = n - i - 1, means we cut every place we can
Then we start backword from f[n-1] to optimise and keep updating isPalindrome[i][j] until we reach f[0] which is the final result 0 - the minimum cuts for the whole string to make all substring palindrome.
Two dynamic programming happenning here
1. isPalindrome[i][j] will reuse the result of isPalindrome[i+1][j-1]
2. f(i) will reuse the result of f(i+1), f(i+2)....
if we find isPalindrome[i][j] == true, then we have to update f(i) = min (f(i), 1 + f(j+1))
1 + f(j+1) means: we know we can cut at j | j+1, since i-j is palindrome, so add 1 to f(j+1)
a b c b d d d
0 1 2 3 4 5 6
Asume we at b (i = 1)
bc is not palindrome, go to next step
bcb is palindrome, update f(1) = 1 + f(4)
bcbd is not palindrome.......
O(n * n) time complexity
*/
extension String {
subscript (i: Int) -> Character {
return self[index(startIndex, offsetBy: i)]
}
}
func mininumCuts(string: String) -> Int {
let stringLength = string.count
var minCuts = [Int](repeating: 0, count: stringLength)
for i in 0...string.count - 1 {
minCuts[i] = string.count - 1 - i
}
var isPalindrome = [[Bool]](repeating: [Bool](repeating: false, count: stringLength), count: stringLength)
for i in (0...stringLength - 1).reversed() {
for j in i...stringLength - 1 {
isPalindrome[i][j] = (string[i] == string[j]) && (j - i < 2 || isPalindrome[i+1][j-1] )
if isPalindrome[i][j] {
if j == stringLength - 1 {
minCuts[i] = min(minCuts[i], 0)
} else {
minCuts[i] = min(minCuts[i], 1 + minCuts[j + 1])
}
}
}
}
return minCuts[0]
}
print(mininumCuts(string: "abcbc"))
|
//
// Puck.swift
// Hockey Game
//
// Created by Collin DeWaters on 3/27/17.
// Copyright © 2017 Collin DeWaters. All rights reserved.
//
import GameplayKit
import SpriteKit
public class Puck: GKEntity {
public static let shared = Puck()
override public init() {
super.init()
let puckComponent = PuckComponent()
self.addComponent(puckComponent)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Calculated variables
public var puckComponent: PuckComponent {
return self.component(ofType: PuckComponent.self)!
}
public var node: SKShapeNode {
return self.puckComponent.node
}
public var position: CGPoint {
set {
self.node.position = newValue
}
get {
return self.node.position
}
}
}
|
import Foundation
struct APIResults: Decodable {
let page: Int
let numResults: Int
let numPages: Int
let movies: [Movie]
private enum CodingKeys: String, CodingKey {
case page
case numResults = "total_results"
case numPages = "total_pages"
case movies = "results"
}
}
struct Movie: Decodable {
let id:Int!
let posterPath: String
var videoPath: String?
let backdrop: String
let title: String
var releaseDate: String
var rating: Double
let overview: String
private enum CodingKeys: String, CodingKey {
case id
case posterPath = "poster_path"
case videoPath
case backdrop = "backdrop_path"
case title
case releaseDate = "release_date"
case rating = "vote_average"
case overview
}
}
|
//
// SidebarViewController.swift
// Visualiser
//
// Created by Douglas Finlay on 03/03/2017.
// Copyright © 2017 Douglas Finlay. All rights reserved.
//
import Cocoa
class SidebarViewController: NSSplitViewController {
override var representedObject: Any? {
didSet {
for viewController in self.childViewControllers {
viewController.representedObject = representedObject
}
}
}
var outlinerViewController: OutlinerViewController! = nil
var meshInspectorViewController: MeshInspectorViewController! = nil
override func viewDidLoad() {
super.viewDidLoad()
outlinerViewController = childViewControllers[0] as! OutlinerViewController
meshInspectorViewController = childViewControllers[1] as! MeshInspectorViewController
}
}
|
//
// Userf.swift
// coachApp
//
// Created by ESPRIT on 26/04/2018.
// Copyright © 2018 ESPRIT. All rights reserved.
//
import UIKit
class Userf: NSObject {
var email : String?
var name : String?
}
|
//
// User.swift
// gameofchats
//
// Created by Hoan Tran on 9/20/17.
// Copyright © 2017 Pego Consulting. All rights reserved.
//
import UIKit
import Firebase
class User: NSObject {
@objc var id: String?
@objc var name: String?
@objc var email: String?
@objc var profileImageURL: String?
@objc var profileImageURLHash: String?
init?(_ snapshot: DataSnapshot) {
guard let dictionary = snapshot.value as? [String: Any] else { return nil}
super.init()
setValuesForKeys(dictionary)
id = snapshot.key
}
init(dictionary: [AnyHashable: Any]) {
self.name = dictionary["name"] as? String
self.email = dictionary["email"] as? String
self.profileImageURL = dictionary["profileImageURL"] as? String
self.profileImageURLHash = dictionary["profileImageURLHash"] as? String
}
}
|
// Receiver.swift
// Simplenet Datagram module
// Copyright (c) 2018 Vladimir Raisov. All rights reserved.
// Licensed under MIT License
import Dispatch
import Sockets
import Interfaces
public class Receiver {
private let sources: [DispatchSourceRead]
/// Handler for incoming datagrams and related errors.
public var delegate: DatagramHandler? {
willSet {
guard self.delegate != nil else {return}
self.sources.forEach { source in
source.suspend()
}
}
didSet {
guard let handler = self.delegate else {return}
self.sources.forEach {source in
source.setEventHandler {[handler, source] in
let handle = Int32(source.handle)
let length = Int(source.data)
do {
handler.dataDidRead(try Datagram(handle,
maxDataLength: length,
maxAncillaryLength: 72))
} catch {
handler.errorDidOccur(error)
}
}
source.resume()
}
}
}
/// Creates receiver for unicast and broadcast datagrams.
/// - Parameters:
/// - port: port on wich the receiver will listen.
/// - interface: interface used for receiving.
///
/// If `interface` specified, only unicast datagrams addressed to this interface address (IPv4 or IPv6)
/// will be received; otherwise all datagrams addressed to selected port will be received on all
/// available interfaces.
public convenience init(port: UInt16, interface: Interface? = nil) throws {
var addresses = [InternetAddress]()
if let interface = interface {
addresses.append(contentsOf: interface.addresses.map{$0.with(port: port)})
} else {
addresses.append(contentsOf: Interfaces().flatMap{$0.ip4}.map{$0.with(port: port)})
addresses.append(contentsOf: try getInternetAddresses(port: port))
}
try self.init(port: port, addresses)
}
/// Creates receiver for multicast datagrams.
/// - Parameters:
/// - port: port on wich the receiver will listen.
/// - address: IPv4 or IPv6 multicast group address to join
/// - interface: interface used for receiving;
/// when omitted, operating system select default interface.
public convenience init(port: UInt16, multicast address: String, interface: Interface? = nil) throws {
let addresses = try getInternetAddresses(for: address, port: port, numericHost: true)
assert(addresses.count == 1)
assert(addresses.first!.isMulticast)
try self.init(port: port, addresses)
assert(self.sources.count == 1)
if let source = self.sources.first,
let group = addresses.first?.ip
{
var interfaces = [Interface]()
if let interface = interface {
interfaces.append(interface)
} else {
interfaces.append(contentsOf: Interfaces())
}
let socket = try Socket(Int32(source.handle))
let family = type(of: group).family
try interfaces.filter{
guard $0.options.contains(.multicast) else {return false}
guard !$0.options.contains(.pointopoint) else {return false}
return !$0.addresses.filter{type(of: $0).family == family}.isEmpty
}.forEach {interface in
try socket.joinToMulticast(group, interfaceIndex: interface.index)
}
}
}
/// You don't need to know about it, although it does all the work...
private init(port: UInt16, _ addresses: [InternetAddress]) throws {
self.sources = try addresses.map {address in
let family = type(of: address.ip).family
let socket = try Socket(family: SocketAddressFamily(family), type: .datagram)
switch family {
case .ip4:
try socket.enable(option: IP_RECVDSTADDR, level: IPPROTO_IP) // 16
try socket.enable(option: IP_RECVPKTINFO, level: IPPROTO_IP) // 24
case .ip6:
try socket.enable(option: IPV6_2292PKTINFO, level: IPPROTO_IPV6)
try socket.enable(option: IPV6_V6ONLY, level: IPPROTO_IPV6)
}
try socket.enable(option: SO_REUSEADDR, level: SOL_SOCKET)
try socket.enable(option: SO_REUSEPORT, level: SOL_SOCKET)
socket.nonBlockingOperations = true
try socket.bind(address)
let handle = try socket.duplicateDescriptor()
let source = DispatchSource.makeReadSource(fileDescriptor: handle)
source.setCancelHandler{[source] in
Darwin.close(Int32(source.handle))
}
return source
}
}
deinit {
if self.delegate != nil {
self.sources.forEach {source in
source.cancel()
}
}
}
}
|
//
// SplitViewVC.swift
// MyMacOSApp
//
// Created by steve.ham on 2021/01/01.
//
import Cocoa
class SplitViewVC: NSViewController, NSSplitViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
func splitView(_ splitView: NSSplitView, constrainMinCoordinate proposedMinimumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
proposedMinimumPosition + 100
}
func splitView(_ splitView: NSSplitView, constrainMaxCoordinate proposedMaximumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
proposedMaximumPosition - 100
}
func splitView(_ splitView: NSSplitView, canCollapseSubview subview: NSView) -> Bool {
let left = splitView.subviews[0]
let right = splitView.subviews[2]
if subview == left || subview == right {
return true
} else {
return false
}
}
}
|
//
// RedButton.swift
// Pila
//
// Created by Dev2 on 08/05/2019.
// Copyright © 2019 Dev2. All rights reserved.
//
import UIKit
class MagentaButton: UIButton {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
override func awakeFromNib() {
self.backgroundColor = UIColor.magenta
self.layer.cornerRadius = 10
self.layer.borderColor = UIColor.blue.cgColor
}
}
|
//
// PayLogModel.swift
// EEPCShop
//
// Created by Mac Pro on 2019/5/11.
// Copyright © 2019年 CHENNIAN. All rights reserved.
//
import UIKit
import SwiftyJSON
class PayLogModel: SNSwiftyJSONAble {
var shop_name:String
var main_img:String
var remark:String
var pay_time:String
var pay_num:String
var pay_eepc:String
required init?(jsonData: JSON) {
self.shop_name = jsonData["shop_name"].stringValue
self.main_img = jsonData["main_img"].stringValue
self.remark = jsonData["remark"].stringValue
self.pay_time = jsonData["pay_time"].stringValue
self.pay_num = jsonData["pay_num"].stringValue
self.pay_eepc = jsonData["pay_eepc"].stringValue
}
}
|
// UINavigationItemExtensions.swift - Copyright 2020 SwifterSwift
#if canImport(UIKit) && !os(watchOS)
import UIKit
// MARK: - Methods
public extension UINavigationItem {
/// SwifterSwift: Replace title label with an image in navigation item.
///
/// - Parameter image: UIImage to replace title with.
func replaceTitle(with image: UIImage) {
let logoImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
logoImageView.contentMode = .scaleAspectFit
logoImageView.image = image
titleView = logoImageView
}
}
#endif
|
//
// NavigationViewController.swift
// AnimationTransition
//
// Created by TAO on 2018/1/8.
// Copyright © 2018年 ShaggyT. All rights reserved.
//
import UIKit
class NavigationViewController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.isTranslucent = false
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
if childViewControllers.count > 0 {
viewController.hidesBottomBarWhenPushed = true
}
super.pushViewController(viewController, animated: animated)
}
}
|
//
// Copyright 2014 ESRI
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// You may freely redistribute and use this sample code, with or
// without modification, provided you include the original copyright
// notice and use restrictions.
//
// See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm
//
import Foundation
import UIKit
extension UIViewController {
func showHUDWithStatus(status:String) {
SVProgressHUD.showWithStatus(status)
self.view.userInteractionEnabled = false
}
func dismissHUD() {
SVProgressHUD.dismiss()
self.view.userInteractionEnabled = true
}
} |
//
// EditViewController.swift
// Noted
//
// Created by Michael Andrew Auer on 1/23/16.
// Copyright © 2016 Usonia LLC. All rights reserved.
//
import UIKit
class EditViewController: UIViewController {
@IBOutlet weak var noteTextField: UITextView!
@IBOutlet weak var noteTitleField: UITextField!
var selectedValue: Note!
let dataInterface = DataInterface()
var user: [User] = []
override func viewDidLoad() {
super.viewDidLoad()
// Get rid of that blank space at the top of the text view
self.automaticallyAdjustsScrollViewInsets = false
if (selectedValue != nil) {
// Set the value of the text field to the note that we clicked on in the table view
noteTitleField.text = selectedValue?.noteTitle
noteTextField.text = selectedValue?.note
self.navigationController?.topViewController!.title = "Edit Note"
} else {
self.navigationController?.topViewController!.title = "New Note"
}
// Hide the back button
self.navigationItem.setHidesBackButton(true, animated: false)
user = dataInterface.get("User") as! [User]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "save") {
// If we have a note object update it, if not create a new one
if (selectedValue == nil) {
dataInterface.create("Note", properties: [
"note": noteTextField.text! as NSObject,
"noteTitle": noteTitleField.text! as NSObject,
"dateUpdated": DateTime().setDate() as NSObject,
"userID": (user.first?.id)! as NSObject
])
} else {
selectedValue?.note = noteTextField.text!
selectedValue?.noteTitle = noteTitleField.text!
selectedValue?.dateUpdated = DateTime().setDate()
dataInterface.update(selectedValue)
}
}
}
}
|
//
// ReminderViewController.swift
// HseTimetable
//
// Created by Pavel on 25.04.2020.
// Copyright © 2020 Hse. All rights reserved.
//
import RxSwift
import RxCocoa
import UIKit
final class ReminderViewController: UIViewController, ReminderViewProtocol {
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var notesTextView: UITextView!
@IBOutlet weak var priorityCircleView: UIImageView!
@IBOutlet weak var prioritySlider: UISlider!
@IBOutlet weak var alarmDatePicker: UIDatePicker!
lazy var alertView: AlertView = {
let view = AlertView()
view.delegate = self
return view
}()
var visualEffectView: UIVisualEffectView = {
let blurEffect = UIBlurEffect(style: .dark)
let view = UIVisualEffectView(effect: blurEffect)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var presenter: ReminderPresenterProtocol!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
private func setup() {
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow(notification:)),
name: UIResponder.keyboardWillShowNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillHide(notification:)),
name: UIResponder.keyboardWillHideNotification,
object: nil
)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(closeButtonTouchUpInside))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addButtonTouchUpInside))
self.priorityCircleView.tintColor = .green
self.alarmDatePicker.locale = Locale(identifier: "ru-RU")
self.notesTextView.layer.borderColor = UIColor.gray.cgColor
self.notesTextView.layer.borderWidth = 1.0
self.notesTextView.layer.cornerRadius = 5.0
self.presenter.outputs.viewConfigure.asObserver()
.observeOn(MainScheduler.asyncInstance)
.subscribe(onNext: { [weak self] reminderData in
self?.titleTextField.text = reminderData.title
self?.notesTextView.text = reminderData.notes
self?.prioritySlider.value = Float(reminderData.priority)
self?.alarmDatePicker.date = reminderData.alarmDate ?? Date()
})
.disposed(by: self.disposeBag)
self.presenter.outputs.error.asObserver()
.observeOn(MainScheduler.asyncInstance)
.subscribe(onNext: { [weak self] error in
self?.alertView.setup(
title: "Внимание!",
message: error.localizedDescription,
leftButtonTitle: nil,
rightButtonTitle: "Skip",
alertId: .error
)
self?.animateInAlert()
})
.disposed(by: self.disposeBag)
// First view load
self.presenter.inputs.viewDidLoadTrigger.onNext(())
}
private func setVisualEffect() {
self.navigationController?.view.addSubview(self.visualEffectView)
self.visualEffectView.snp.remakeConstraints{ make in
make.edges.equalToSuperview()
}
}
private func setAlert() {
self.navigationController?.view.addSubview(self.alertView)
self.alertView.snp.remakeConstraints{ make in
make.edges.equalToSuperview()
}
}
// MARK:- Animations
private func animateInAlert() {
setVisualEffect()
self.visualEffectView.alpha = 0.0
setAlert()
self.alertView.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
self.alertView.alpha = 0.0
UIView.animate(withDuration: 0.4) {
self.visualEffectView.alpha = 1.0
self.alertView.alpha = 1.0
self.alertView.transform = CGAffineTransform.identity
}
}
private func animateOutAlert(completion: (() -> Void)?) {
UIView.animate(withDuration: 0.4, animations: {
self.visualEffectView.alpha = 0.0
self.alertView.alpha = 0.0
self.alertView.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
}) { _ in
self.visualEffectView.removeFromSuperview()
self.alertView.removeFromSuperview()
completion?()
}
}
// MARK:- Views events
@IBAction func prioritySliderValueChanged(_ sender: UISlider) {
let color = UIColor.green.toColor(.red, percentage: CGFloat((sender.value - sender.minimumValue) * 100 / (sender.maximumValue - sender.minimumValue)))
self.priorityCircleView.tintColor = color
}
@objc private func closeButtonTouchUpInside() {
self.presenter.inputs.closeButtonTrigger.onNext(())
}
@objc private func addButtonTouchUpInside() {
let dataFromView = ReminderEventData(title: self.titleTextField.text ?? "", priority: Int(self.prioritySlider.value), notes: self.notesTextView.text, alarmDate: self.alarmDatePicker.date)
self.presenter.inputs.addButtonTrigger.onNext(dataFromView)
}
@objc private func keyboardWillShow(notification: NSNotification) {
guard let textViewResponder = self.view.getSelectedTextView() else { return }
guard let positionResponder = self.view.getPositionOfSubview(subview: textViewResponder) else { return }
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let navigationBarHeight = self.navigationController?.navigationBar.frame.height ?? 0
let paddingTextView = self.view.frame.height + navigationBarHeight - (positionResponder.origin.y + positionResponder.height)
if keyboardSize.height > paddingTextView + Size.large.indent {
self.view.frame.origin.y -= (keyboardSize.height - paddingTextView) + Size.large.indent
}
}
}
@objc private func keyboardWillHide(notification: NSNotification) {
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y = 0
}
}
}
// MARK:- Text Field Delegate
extension ReminderViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.endEditing(true)
return true
}
}
// MARK:- Text View Delegate
extension ReminderViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" { textView.endEditing(true) }
return true
}
}
// MARK:- Alert Delegate
extension ReminderViewController: AlertDelegate {
func rightButtonTapped(from alertId: AlertId) {
switch alertId {
case .error:
animateOutAlert(completion: nil)
default: break
}
}
}
// MARK:- Viewable
extension ReminderViewController: Viewable {}
|
//
// EventCard.swift
// SportSpot
//
// Created by Денис Мусатов on 12.11.2020.
//
import SwiftUI
struct EventCard: View {
var body: some View {
ZStack(alignment: .top) {
RoundedRectangle(cornerRadius: 12)
.foregroundColor(.white)
.shadow(color: Color.gray.opacity(0.2), radius: 15.0, x: 0, y: 0)
HStack(alignment: .top, spacing: 0) {
VStack() {
Image("basketball")
.resizable()
.frame(width: 44, height: 44)
ZStack {
RoundedRectangle(cornerRadius: 22)
.foregroundColor(Color("lightBlue"))
.frame(width: 52, height: 25)
Text("200 м")
.font(.caption)
.foregroundColor(Color("skyBlue"))
}
}.padding(.horizontal)
VStack(alignment: .leading, spacing: 6) {
Text("Тренировака здоровых котят")
.foregroundColor(.black)
.font(.subheadline)
.bold()
Text("Мы продолжаем тренироваться и достигать поставленные цели, присоединяйтесь к нам!")
.font(.caption)
.foregroundColor(Color("captionColor"))
Spacer(minLength: 0)
HStack {
Image("calendar")
Text("12 мая, 14:35")
.font(.caption)
.foregroundColor(Color("captionColor"))
Spacer(minLength: 0)
ZStack {
ForEach(0..<4) { index in
Image("tempSportsman")
.resizable()
.scaledToFill()
.clipShape(Circle())
.overlay(Circle().stroke(lineWidth: 0.5).foregroundColor(.white))
.frame(width: 32, height: 32)
.offset(x: CGFloat(-16*index))
}
}
Text("+2")
.foregroundColor(Color("skyBlue"))
.font(.footnote)
}.padding([.bottom,.trailing], 10)
}
}.padding(.top)
}
.frame(height: 145)
.padding(.top)
}
}
struct EventCard_Previews: PreviewProvider {
static var previews: some View {
EventCard()
}
}
|
//
// Scoreboard.swift
// CollegeTennisTracker
//
// Created by Vishnu Joshi on 5/27/19.
// Copyright © 2019 Vishnu Joshi. All rights reserved.
//
import UIKit
class Scoreboard: UIViewController, WeatherFetcherDelegate, UITextFieldDelegate {
var finalhometeam = CollegeTeam();
var finalawayteam = CollegeTeam();
let weatherFetcher = WeatherFetcher()
var currscores = Scores()
var scoreboard_helper = ScoreboardHelper()
@IBOutlet weak var hometeamlabel: UILabel!
@IBOutlet weak var awayteamlabel: UILabel!
@IBOutlet weak var hometeamscore: UILabel!
@IBOutlet weak var awayteamscore: UILabel!
@IBOutlet weak var homed1: UILabel!
@IBOutlet weak var awayd1: UILabel!
@IBOutlet weak var homed2: UILabel!
@IBOutlet weak var awayd2: UILabel!
@IBOutlet weak var homed3: UILabel!
@IBOutlet weak var awayd3: UILabel!
@IBOutlet weak var homes1: UILabel!
@IBOutlet weak var aways1: UILabel!
@IBOutlet weak var homes2: UILabel!
@IBOutlet weak var aways2: UILabel!
@IBOutlet weak var homes3: UILabel!
@IBOutlet weak var aways3: UILabel!
@IBOutlet weak var homes4: UILabel!
@IBOutlet weak var aways4: UILabel!
@IBOutlet weak var homes5: UILabel!
@IBOutlet weak var aways5: UILabel!
@IBOutlet weak var homes6: UILabel!
@IBOutlet weak var aways6: UILabel!
@IBOutlet weak var homed1set1: UITextField!
@IBOutlet weak var homed1set2: UITextField!
@IBOutlet weak var homed1set3: UITextField!
@IBOutlet weak var awayd1set1: UITextField!
@IBOutlet weak var homed2set1: UITextField!
@IBOutlet weak var awayd2set1: UITextField!
@IBOutlet weak var homed3set1: UITextField!
@IBOutlet weak var awayd3set1: UITextField!
@IBOutlet weak var homes1set1: UITextField!
@IBOutlet weak var homes1set2: UITextField!
@IBOutlet weak var homes1set3: UITextField!
@IBOutlet weak var aways1set1: UITextField!
@IBOutlet weak var aways1set2: UITextField!
@IBOutlet weak var aways1set3: UITextField!
@IBOutlet weak var homes2set1: UITextField!
@IBOutlet weak var homes2set2: UITextField!
@IBOutlet weak var homes2set3: UITextField!
@IBOutlet weak var aways2set1: UITextField!
@IBOutlet weak var aways2set2: UITextField!
@IBOutlet weak var aways2set3: UITextField!
@IBOutlet weak var homes3set1: UITextField!
@IBOutlet weak var homes3set2: UITextField!
@IBOutlet weak var homes3set3: UITextField!
@IBOutlet weak var aways3set1: UITextField!
@IBOutlet weak var aways3set2: UITextField!
@IBOutlet weak var aways3set3: UITextField!
@IBOutlet weak var homes4set1: UITextField!
@IBOutlet weak var homes4set2: UITextField!
@IBOutlet weak var homes4set3: UITextField!
@IBOutlet weak var aways4set1: UITextField!
@IBOutlet weak var aways4set2: UITextField!
@IBOutlet weak var aways4set3: UITextField!
@IBOutlet weak var homes5set1: UITextField!
@IBOutlet weak var homes5set2: UITextField!
@IBOutlet weak var homes5set3: UITextField!
@IBOutlet weak var aways5set1: UITextField!
@IBOutlet weak var aways5set2: UITextField!
@IBOutlet weak var aways5set3: UITextField!
@IBOutlet weak var homes6set1: UITextField!
@IBOutlet weak var homes6set2: UITextField!
@IBOutlet weak var homes6set3: UITextField!
@IBOutlet weak var aways6set1: UITextField!
@IBOutlet weak var aways6set2: UITextField!
@IBOutlet weak var aways6set3: UITextField!
@IBOutlet weak var cityName: UITextField!
@IBAction func cityNameEntered(_ sender: Any) {
weatherFetcher.getWeather(cityName.text!)
}
@IBOutlet weak var temperatureValue: UILabel!
func setWeather(weather: WeatherInfo) {
temperatureValue.text = String(weather.temp);
}
func updateSinglesScore(_ sb: inout Scores, _ matchnum: Int, _ home: Bool, _ set1: UITextField, _ set2: UITextField, _ set3: UITextField) {
if (sb.singlesMatches[matchnum]!.setscomplete == 0) {
set1.text = scoreboard_helper.updateSetOne(&sb, matchnum, home)
} else if (sb.singlesMatches[matchnum]!.setscomplete == 1) {
set2.text = scoreboard_helper.updateSetTwo(&sb, matchnum, home)
} else if (sb.singlesMatches[matchnum]!.setscomplete == 2 && !sb.singlesMatches[matchnum]!.matchcomplete) {
set3.text = scoreboard_helper.updateSetThree(&sb, matchnum, home)
}
if (sb.singlesMatches[matchnum]!.matchcomplete) {
return
}
if (scoreboard_helper.homeWins(&sb, matchnum)) {
sb.hometotalcount += 1
hometeamscore.text = String(sb.hometotalcount)
sb.singlesMatches[matchnum]!.matchcomplete = true
} else if (scoreboard_helper.awayWins(&sb, matchnum)) {
sb.awaytotalcount += 1
awayteamscore.text = String(sb.awaytotalcount)
sb.singlesMatches[matchnum]!.matchcomplete = true
}
}
func updateSinglesMinus(_ sb: inout Scores, _ matchnum: Int, _ home: Bool, _ set1: UITextField, _ set2: UITextField, _ set3: UITextField) {
scoreboard_helper.subCompletedIfThird(&sb, matchnum, home)
set3.text = scoreboard_helper.subSetThree(&sb, matchnum, home)
scoreboard_helper.subCompletedIfSecond(&sb, matchnum, home)
set2.text = scoreboard_helper.subSetTwo(&sb, matchnum, home)
set1.text = scoreboard_helper.subSetOne(&sb, matchnum, home)
hometeamscore.text = String(sb.hometotalcount)
sb.singlesMatches[matchnum]!.matchcomplete = false
awayteamscore.text = String(sb.awaytotalcount)
sb.singlesMatches[matchnum]!.matchcomplete = false
}
func updateDoublesOnPlus(_ sb: inout Scores, _ matchnum: Int, _ home: Bool) {
if (scoreboard_helper.dubsMatchCompleted(&sb, matchnum)) {
return
}
if (home) {
if sb.doublesMatches[matchnum]?.homescore != 8 {
sb.doublesMatches[matchnum]?.homescore += 1
if (sb.doublesMatches[matchnum]?.homescore == 8) {
sb.hometotalcount += 1
hometeamscore.text = String(sb.hometotalcount)
}
}
} else {
if sb.doublesMatches[matchnum]?.awayscore != 8 {
sb.doublesMatches[matchnum]?.awayscore += 1
if (sb.doublesMatches[matchnum]?.awayscore == 8) {
sb.awaytotalcount += 1
awayteamscore.text = String(sb.awaytotalcount)
}
}
}
}
func updateDoublesOnMinus(_ sb: inout Scores, _ matchnum: Int, _ home: Bool) {
if (home) {
if sb.doublesMatches[matchnum]?.homescore != 0 {
if (sb.doublesMatches[matchnum]?.homescore == 8) {
sb.hometotalcount -= 1
hometeamscore.text = String(sb.hometotalcount)
}
sb.doublesMatches[matchnum]?.homescore -= 1
}
} else {
if sb.doublesMatches[matchnum]?.awayscore != 0 {
if (sb.doublesMatches[matchnum]?.awayscore == 8) {
sb.awaytotalcount -= 1
awayteamscore.text = String(sb.awaytotalcount)
}
sb.doublesMatches[matchnum]?.awayscore -= 1
}
}
}
@IBAction func homedplus(_ sender: Any) {
updateDoublesOnPlus(&currscores, 0, true)
homed1set1.text = String(currscores.doublesMatches[0]!.homescore)
}
@IBAction func homedminus(_ sender: Any) {
updateDoublesOnMinus(&currscores, 0, true)
homed1set1.text = String(currscores.doublesMatches[0]!.homescore)
}
@IBAction func awaydplus(_ sender: Any) {
updateDoublesOnPlus(&currscores, 0, false)
awayd1set1.text = String(currscores.doublesMatches[0]!.awayscore)
}
@IBAction func awaydminus(_ sender: Any) {
updateDoublesOnMinus(&currscores, 0, false)
awayd1set1.text = String(currscores.doublesMatches[0]!.awayscore)
}
@IBAction func homed2plus(_ sender: Any) {
updateDoublesOnPlus(&currscores, 1, true)
homed2set1.text = String(currscores.doublesMatches[1]!.homescore)
}
@IBAction func homed2minus(_ sender: Any) {
updateDoublesOnMinus(&currscores, 1, true)
homed2set1.text = String(currscores.doublesMatches[1]!.homescore)
}
@IBAction func awayd2plus(_ sender: Any) {
updateDoublesOnPlus(&currscores, 1, false)
awayd2set1.text = String(currscores.doublesMatches[1]!.awayscore)
}
@IBAction func awayd2minus(_ sender: Any) {
updateDoublesOnMinus(&currscores, 1, false)
awayd2set1.text = String(currscores.doublesMatches[1]!.awayscore)
}
@IBAction func homed3plus(_ sender: Any) {
updateDoublesOnPlus(&currscores, 2, true)
homed3set1.text = String(currscores.doublesMatches[2]!.homescore)
}
@IBAction func homed3minus(_ sender: Any) {
updateDoublesOnMinus(&currscores, 2, true)
homed3set1.text = String(currscores.doublesMatches[2]!.homescore)
}
@IBAction func awayd3plus(_ sender: Any) {
updateDoublesOnPlus(&currscores, 2, false)
awayd3set1.text = String(currscores.doublesMatches[2]!.awayscore)
}
@IBAction func awayd3minus(_ sender: Any) {
updateDoublesOnMinus(&currscores, 2, false)
awayd3set1.text = String(currscores.doublesMatches[2]!.awayscore)
}
@IBAction func homes1plus(_ sender: Any) {
updateSinglesScore(&currscores, 0, true, homes1set1, homes1set2, homes1set3)
}
@IBAction func homes1minus(_ sender: Any) {
updateSinglesMinus(&currscores, 0, true, homes1set1, homes1set2, homes1set3)
}
@IBAction func aways1plus(_ sender: Any) {
updateSinglesScore(&currscores, 0, false, aways1set1, aways1set2, aways1set3)
}
@IBAction func aways1minus(_ sender: Any) {
updateSinglesMinus(&currscores, 0, false, aways1set1, aways1set2, aways1set3)
}
@IBAction func homes2plus(_ sender: Any) {
updateSinglesScore(&currscores, 1, true, homes2set1, homes2set2, homes2set3)
}
@IBAction func homes2minus(_ sender: Any) {
updateSinglesMinus(&currscores, 1, true, homes2set1, homes2set2, homes2set3)
}
@IBAction func aways2plus(_ sender: Any) {
updateSinglesScore(&currscores, 1, false, aways2set1, aways2set2, aways2set3)
}
@IBAction func aways2minus(_ sender: Any) {
updateSinglesMinus(&currscores, 1, false, aways2set1, aways2set2, aways2set3)
}
@IBAction func homes3plus(_ sender: Any) {
updateSinglesScore(&currscores, 2, true, homes3set1, homes3set2, homes3set3)
}
@IBAction func homes3minus(_ sender: Any) {
updateSinglesMinus(&currscores, 2, true, homes3set1, homes3set2, homes3set3)
}
@IBAction func aways3plus(_ sender: Any) {
updateSinglesScore(&currscores, 2, false, aways3set1, aways3set2, aways3set3)
}
@IBAction func aways3minus(_ sender: Any) {
updateSinglesMinus(&currscores, 2, false, aways3set1, aways3set2, aways3set3)
}
@IBAction func homes4plus(_ sender: Any) {
updateSinglesScore(&currscores, 3, true, homes4set1, homes4set2, homes4set3)
}
@IBAction func homes4minus(_ sender: Any) {
updateSinglesMinus(&currscores, 3, true, homes4set1, homes4set2, homes4set3)
}
@IBAction func aways4plus(_ sender: Any) {
updateSinglesScore(&currscores, 3, false, aways4set1, aways4set2, aways4set3)
}
@IBAction func aways4minus(_ sender: Any) {
updateSinglesMinus(&currscores, 3, false, aways4set1, aways4set2, aways4set3)
}
@IBAction func homes5plus(_ sender: Any) {
updateSinglesScore(&currscores, 4, true, homes5set1, homes5set2, homes5set3)
}
@IBAction func homes5minus(_ sender: Any) {
updateSinglesMinus(&currscores, 4, true, homes5set1, homes5set2, homes5set3)
}
@IBAction func aways5plus(_ sender: Any) {
updateSinglesScore(&currscores, 4, false, aways5set1, aways5set2, aways5set3)
}
@IBAction func aways5minus(_ sender: Any) {
updateSinglesMinus(&currscores, 4, false, aways5set1, aways5set2, aways5set3)
}
@IBAction func homes6plus(_ sender: Any) {
updateSinglesScore(&currscores, 5, true, homes6set1, homes6set2, homes6set3)
}
@IBAction func homes6minus(_ sender: Any) {
updateSinglesMinus(&currscores, 5, true, homes6set1, homes6set2, homes6set3)
}
@IBAction func aways6plus(_ sender: Any) {
updateSinglesScore(&currscores, 5, false, aways6set1, aways6set2, aways6set3)
}
@IBAction func aways6minus(_ sender: Any) {
updateSinglesMinus(&currscores, 5, false, aways6set1, aways6set2, aways6set3)
}
override func viewDidLoad() {
super.viewDidLoad()
hometeamlabel.text = self.finalhometeam.name;
awayteamlabel.text = self.finalawayteam.name;
homed1.text = self.finalhometeam.doubles_teams[0]
homed2.text = self.finalhometeam.doubles_teams[1]
homed3.text = self.finalhometeam.doubles_teams[2]
homes1.text = self.finalhometeam.singles_teams[0]
homes2.text = self.finalhometeam.singles_teams[1]
homes3.text = self.finalhometeam.singles_teams[2]
homes4.text = self.finalhometeam.singles_teams[3]
homes5.text = self.finalhometeam.singles_teams[4]
homes6.text = self.finalhometeam.singles_teams[5]
awayd1.text = self.finalawayteam.doubles_teams[0]
awayd2.text = self.finalawayteam.doubles_teams[1]
awayd3.text = self.finalawayteam.doubles_teams[2]
aways1.text = self.finalawayteam.singles_teams[0]
aways2.text = self.finalawayteam.singles_teams[1]
aways3.text = self.finalawayteam.singles_teams[2]
aways4.text = self.finalawayteam.singles_teams[3]
aways5.text = self.finalawayteam.singles_teams[4]
aways6.text = self.finalawayteam.singles_teams[5]
self.weatherFetcher.delegate = self;
// Do any additional setup after loading the view.
}
/*
// 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.
}
*/
}
|
//
// Title.swift
// AdjaraNet
//
// Created by Irakli Tchitadze on 2/12/18.
// Copyright © 2018 Irakli Tchitadze. All rights reserved.
//
import UIKit
class Title: NSObject {
let text: String
let language: Language
init (text: String, language: Language) {
self.text = text
self.language = language
}
}
|
//
// Float+Extensions.swift
// EasyGitHubSearch
//
// Created by Yevhen Triukhan on 11.10.2020.
// Copyright © 2020 Yevhen Triukhan. All rights reserved.
//
import Foundation
import CoreGraphics
extension Float {
var cgFloat: CGFloat { CGFloat(self) }
var int: Int { Int(self) }
}
|
//
// FBTableViewModel.swift
// Fahrtenbuch
//
// Created by Benjamin Herzog on 12.04.15.
// Copyright (c) 2015 Benjamin Herzog. All rights reserved.
//
import UIKit
import CoreData
class FBTableViewModel: NSObject, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {
// MARK: - Properties
weak var tableView: UITableView?
private var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!
lazy private var fetchedResultsController: NSFetchedResultsController = {
[weak self] in
if self == nil { return NSFetchedResultsController() }
var fetchRequest = NSFetchRequest()
var entity = NSEntityDescription.entityForName("Fahrt", inManagedObjectContext: self!.context)
fetchRequest.entity = entity
var sortStart = NSSortDescriptor(key: "startDate", ascending: true)
var sortEnd = NSSortDescriptor(key: "endDate", ascending: true)
fetchRequest.sortDescriptors = [sortStart, sortEnd]
fetchRequest.fetchBatchSize = 100
var fetchRequestController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self!.context, sectionNameKeyPath: nil, cacheName: nil)
fetchRequestController.delegate = self
return fetchRequestController
}()
// MARK: - Initializer
init(tableView: UITableView) {
self.tableView = tableView
super.init()
var error: NSError?
if !fetchedResultsController.performFetch(&error) {
FBLogD("Failed to load results from CoreData. Error: \(error?.localizedDescription)")
return
}
}
// MARK: - UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fetchedResultsController.sections?[section].numberOfObjects ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("default") as! FBTableViewCell
configureCell(&cell, atIndexPath: indexPath)
return cell
}
func configureCell(inout cell: FBTableViewCell, atIndexPath indexPath: NSIndexPath) {
if let fahrt = fetchedResultsController.objectAtIndexPath(indexPath) as? Fahrt {
}
}
// MARK: - NSFetchedResultsControllerDelegate
func controllerWillChangeContent(controller: NSFetchedResultsController) {
tableView?.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
break
case .Delete:
break
case .Update:
break
default:
break
}
}
}
|
//
// AddMoneyRequest.swift
// Slidecoin
//
// Created by Oleg Samoylov on 30.01.2020.
// Copyright © 2020 Oleg Samoylov. All rights reserved.
//
import Foundation
import Toolkit
final class AddMoneyRequest: BasePostRequest {
init(userID: Int, amount: Int) {
let endpoint = "\(RequestFactory.endpointRoot)addmoney"
super.init(endpoint: endpoint, parameters: ["id": userID,
"amount": amount])
}
override public var urlRequest: URLRequest? {
var request = super.urlRequest
guard let accessToken = Global.accessToken else { return request }
request?.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
return request
}
}
|
//
// CoreDataManager.swift
// Desafio-Mobile-PicPay
//
// Created by Luiz Hammerli on 25/07/2018.
// Copyright © 2018 Luiz Hammerli. All rights reserved.
//
import Foundation
import CoreData
class CoreDataManager {
let persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "DatabaseModel")
container.loadPersistentStores { (_, error) in
if let error = error {
fatalError("Store failed: \(error)")
}
}
return container
}()
func fetchCards() -> NSFetchedResultsController<Card> {
let fetchRequest = NSFetchRequest<Card>(entityName: "Card")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)]
let fetchedResultController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: "Card")
return fetchedResultController
}
func fetchTransactions() -> [Transaction] {
let fetchRequest = NSFetchRequest<Transaction>(entityName: "Transaction")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)]
guard let transactions = try? persistentContainer.viewContext.fetch(fetchRequest) else {return []}
return transactions
}
func fetchSelectedCard() -> Card? {
guard let selectedCardUrl = UserDefaults.standard.object(forKey: "selectedCardID") as? String else {return nil}
let fetchRequest = NSFetchRequest<Card>(entityName: "Card")
var selectedCard: Card?
guard let result = try? persistentContainer.viewContext.fetch(fetchRequest) else {return nil}
if(result.count == 1){
return result.first
}
let _ = result.filter { (card) -> Bool in
if (card.url_string_id! == selectedCardUrl){
selectedCard = card
return true
}
return false
}
return selectedCard
}
func saveCard(_ cardName: String, cardNumber: String, cvv: String, date: String){
let card = Card(context: persistentContainer.viewContext)
card.name = cardName
card.card_number = cardNumber.replacingOccurrences(of: " ", with: "")
card.cvv = cvv
card.expiry_date = date
card.url_string_id = card.objectID.uriRepresentation().absoluteString
card.date = Date()
self.save()
if(UserDefaults.standard.object(forKey: "selectedCardID") == nil){
UserDefaults.standard.set(card.url_string_id, forKey: "selectedCardID")
NotificationCenter.default.post(name: PaymentViewController.updatePaymentTypeNotificationName, object: self)
UserDefaults.standard.set(0, forKey: "selectedCardIndex")
}
}
func saveTransaction(_ jsonTransactionApiObject: JsonTransactionApiObject){
let transactionUser = self.saveTransactionUser(jsonTransactionApiObject.transaction.destination_user)
let transaction = Transaction(context: persistentContainer.viewContext)
transaction.transaction_user = transactionUser
transaction.date = Date(timeIntervalSince1970: TimeInterval(jsonTransactionApiObject.transaction.timestamp))
transaction.status = jsonTransactionApiObject.transaction.status
transaction.success = jsonTransactionApiObject.transaction.success
transaction.transaction_id = Int64(jsonTransactionApiObject.transaction.id)
transaction.value = jsonTransactionApiObject.transaction.value
self.save()
}
func saveTransactionUser(_ user: Contact)->TransactionUser{
let transactionUser = TransactionUser(context: persistentContainer.viewContext)
transactionUser.user_id = Int64(user.id)
transactionUser.username = user.username
transactionUser.profile_image_url = user .img
self.save()
return transactionUser
}
func save(){
if(persistentContainer.viewContext.hasChanges){
try? persistentContainer.viewContext.save()
}
}
}
|
//
// EpisodesViewController.swift
// PodcastsKo
//
// Created by John Roque Jorillo on 7/30/20.
// Copyright © 2020 JohnRoque Inc. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import PodcastKoCore
protocol EpisodesViewControllerDelegate {
func back(_ vc: EpisodesViewController)
}
class EpisodesViewController: UITableViewController {
// MARK: - dependencies
var podCast: Podcast?
var coordinator: EpisodesViewControllerDelegate?
var viewModel: EpisodesViewViewModel?
// MARK: - Views
private lazy var backButton: UIBarButtonItem = {
let button = UIBarButtonItem(title: "Back", style: .plain, target: self, action: nil)
button.tintColor = .purple
return button
}()
private lazy var favoriteButton: UIBarButtonItem = {
let button = UIBarButtonItem(title: "Favorite", style: .plain, target: self, action: nil)
button.tintColor = .purple
return button
}()
private lazy var hearthButton: UIBarButtonItem = {
let button = UIBarButtonItem(image: UIImage(named: "hearth")!, style: .plain, target: self, action: nil)
button.tintColor = .purple
return button
}()
// MARK: - Private properties
private var data = [Episode]() {
didSet {
self.tableView.reloadData()
}
}
private let cellId = "cellId"
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
configureNavigation()
configureTableView()
setupBindings()
getEpisodes()
}
private func getEpisodes() {
self.viewModel?.getEpisodesViewModel.getEpisodes()
}
private func configureNavigation() {
self.title = podCast?.trackName
self.navigationItem.leftBarButtonItem = backButton
backButton.rx.tap
.asDriver()
.drive(onNext: { [unowned self] in
self.coordinator?.back(self)
})
.disposed(by: self.disposeBag)
guard let podcast = self.podCast, let viewModel = self.viewModel else { return }
if viewModel.checkIfPodcastAlreadyFavorite(podcast: podcast) {
self.navigationItem.rightBarButtonItem = hearthButton
} else {
self.navigationItem.rightBarButtonItem = favoriteButton
}
hearthButton.rx.tap
.asDriver()
.drive(onNext: { [unowned self] in
guard let podcast = self.podCast else { return }
self.viewModel?.removeFavoritePodcast(podcast: podcast)
self.navigationItem.rightBarButtonItem = self.favoriteButton
})
.disposed(by: self.disposeBag)
favoriteButton.rx.tap
.asDriver()
.drive(onNext: { [unowned self] in
guard let podcast = self.podCast else { return }
self.viewModel?.saveFavoritePodcast(podcast: podcast)
self.navigationItem.rightBarButtonItem = self.hearthButton
let window = UIWindow.key
if let nav = window?.rootViewController as? UINavigationController,
let mainTab = nav.viewControllers.first as? MainTabBarController {
mainTab.viewControllers?[0].tabBarItem.badgeValue = "New"
}
})
.disposed(by: self.disposeBag)
}
private func configureTableView() {
tableView.register(EpisodeTableViewCell.self, forCellReuseIdentifier: self.cellId)
tableView.separatorStyle = .none
}
private func setupBindings() {
self.viewModel?
.getEpisodesViewModel
.getOutputs()
.episodes
.asDriver()
.drive(onNext: { [weak self] (data) in
self?.data = data
})
.disposed(by: self.disposeBag)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: self.cellId, for: indexPath) as! EpisodeTableViewCell
let episode = self.data[indexPath.row]
cell.configure(episode: episode)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// TODO: Deprecated keywindow for ios13
// let window = UIApplication.shared.keyWindow
//
// let view = PodcastPlayerUIView(frame: self.view.frame)
// view.episode = self.data[indexPath.row]
//
// window?.addSubview(view)
let window = UIWindow.key
if let nav = window?.rootViewController as? UINavigationController,
let mainTab = nav.viewControllers.first as? MainTabBarController {
mainTab.showPlayer(episode: self.data[indexPath.row], episodes: self.data)
}
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let activityIndicatorView = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.large)
activityIndicatorView.color = .darkGray
activityIndicatorView.startAnimating()
return activityIndicatorView
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return self.data.isEmpty ? 200 : 0
}
// override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
//
// let downloadAction = UITableViewRowAction
//
// }
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let contextItem = UIContextualAction(style: .normal, title: "Download") { [unowned self] (_, _, completion) in
let episode = self.data[indexPath.row]
self.viewModel?.downloadViewModel.downloadEpisode(episode: episode)
let window = UIWindow.key
if let nav = window?.rootViewController as? UINavigationController,
let mainTab = nav.viewControllers.first as? MainTabBarController {
mainTab.viewControllers?[2].tabBarItem.badgeValue = "New"
}
completion(true)
}
let swipeActions = UISwipeActionsConfiguration(actions: [contextItem])
return swipeActions
}
}
|
//
// LoginViewController.swift
// MVVM-SampleTests
//
// Created by lyhonghwa on 2018. 8. 6..
// Copyright © 2018년 lyhonghwa. All rights reserved.
//
import XCTest
import RxSwift
import RxCocoa
@testable import MVVM_Sample
class LoginViewControllerTests: XCTestCase {
typealias LoginStatus = LoginViewModel.LoginStatus
var loginViweModel: StubLoginViewModel!
override func setUp() {
super.setUp()
loginViweModel = StubLoginViewModel()
}
func test_setupBinding_nextFieldInvoked_updateUI() {
//given
let trigger = PublishSubject<Void>()
let output = createOutput(nextField: trigger)
loginViweModel.output = output
let view = LoginViewController.create(with: loginViweModel)
UIApplication.shared.keyWindow?.rootViewController = view
let passwordTextField = view.passwordTextField
//when
trigger.onNext(())
//then
XCTAssertTrue(passwordTextField.isFirstResponder)
}
func test_setupBinding_resetBackgroundColorInvoked_updateUI() {
//given
let trigger = PublishSubject<Void>()
let output = createOutput(resetBackgroundColor: trigger)
loginViweModel.output = output
let view = LoginViewController.create(with: loginViweModel)
//when
trigger.onNext(())
//then
XCTAssertNil(view.usernameTextField.backgroundColor)
XCTAssertNil(view.passwordTextField.backgroundColor)
}
func test_setupBinding_successLoginInvoked_updateUI() {
//given
let trigger = PublishSubject<Void>()
let output = createOutput(successLogin: trigger)
loginViweModel.output = output
let view = LoginViewController.create(with: loginViweModel)
let usernameTextField = view.usernameTextField
let passwordTextField = view.passwordTextField
let loginButton = view.loginButton
let successLabel = view.successLabel
//when
trigger.onNext(())
//then
XCTAssertTrue(usernameTextField.isHidden)
XCTAssertTrue(passwordTextField.isHidden)
XCTAssertTrue(loginButton.isHidden)
XCTAssertFalse(successLabel.isHidden)
}
func test_setupBinding_failedUsernameLoginInvoked_updateUI() {
//given
let trigger = PublishSubject<LoginStatus>()
let output = createOutput(failedLogin: trigger)
loginViweModel.output = output
let view = LoginViewController.create(with: loginViweModel)
UIApplication.shared.keyWindow?.rootViewController = view
let usernameTextField = view.usernameTextField
let originalBackgroundColor = usernameTextField.backgroundColor
//when
trigger.onNext(.wrongUsername)
//then
XCTAssert(usernameTextField.backgroundColor != originalBackgroundColor)
XCTAssertTrue(usernameTextField.isFirstResponder)
}
func test_setupBinding_failedPasswordLoginInvoked_updateUI() {
//given
let trigger = PublishSubject<LoginStatus>()
let output = createOutput(failedLogin: trigger)
loginViweModel.output = output
let view = LoginViewController.create(with: loginViweModel)
UIApplication.shared.keyWindow?.rootViewController = view
let passwordTextField = view.passwordTextField
let originalBackgroundColor = passwordTextField.backgroundColor
//when
trigger.onNext(.wrongPassword)
//then
XCTAssert(passwordTextField.backgroundColor != originalBackgroundColor)
XCTAssertTrue(passwordTextField.isFirstResponder)
}
//convenience method
private func createOutput(nextField: Observable<Void> = Observable.never(),
resetBackgroundColor: Observable<Void> = Observable.never(),
successLogin: Observable<Void> = Observable.never(),
failedLogin: Observable<LoginStatus> = Observable.never()) -> LoginViewModel.Output {
return LoginViewModel.Output(nextField: nextField.asDriverOnErrorJustComplete,
resetBackgroundColor: resetBackgroundColor.asDriverOnErrorJustComplete,
successLogin: successLogin.asDriverOnErrorJustComplete,
failedLogin: failedLogin.asDriverOnErrorJustComplete)
}
}
|
//
// UIViewController+Helpers.swift
// LessLinesDemo
//
// Created by Mustafa Baalbaki on 11/15/18.
// Copyright © 2018 Mustafa. All rights reserved.
//
import UIKit
extension UIViewController {
func add(contentViewController: UIViewController, toContainerView: UIView) {
addChild(contentViewController)
toContainerView.addSubview(contentViewController.view)
contentViewController.view.translatesAutoresizingMaskIntoConstraints = false
contentViewController.view.constrainEdges(toMarginOf: toContainerView)
contentViewController.didMove(toParent: self)
}
func remove(contentViewController: UIViewController) {
contentViewController.willMove(toParent: nil)
contentViewController.view.removeFromSuperview()
contentViewController.removeFromParent()
}
func showStandardQuestionAlert(question: String, action: ((UIAlertAction) -> Swift.Void)? = nil) {
DispatchQueue.main.async { [unowned self] in
let yesAlertAction: UIAlertAction = UIAlertAction(title: String.yes, style: .destructive, handler: action)
let alertController = UIAlertController(title: nil, message: question, preferredStyle: .alert)
alertController.addAction(yesAlertAction)
alertController.addAction(UIAlertAction(title: String.no, style: .cancel, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}
func showStandardForceAlert(question: String, action: ((UIAlertAction) -> Swift.Void)? = nil) {
DispatchQueue.main.async { [unowned self] in
let yesAlertAction: UIAlertAction = UIAlertAction(title: String.okay, style: .default, handler: action)
let alertController = UIAlertController(title: nil, message: question, preferredStyle: .alert)
alertController.addAction(yesAlertAction)
self.present(alertController, animated: true, completion: nil)
}
}
static func showStandardMessageAlert(_ message: String, title: String = "") {
UIApplication.getTopMostViewController()?.showStandardMessageAlert(message, title: title)
}
func showStandardMessageAlert(_ message: String, title: String = "") {
let alertController = UIAlertController(title: (title != "") ? title : nil, message: message, preferredStyle: .alert)
let okayAction = UIAlertAction(title: String.okay, style: .default, handler: nil)
alertController.addAction(okayAction)
self.present(alertController, animated: true, completion: nil)
}
}
|
import UIKit
import SwiftUI
import PlaygroundSupport
// https://facebook.github.io/react-native/docs/style
struct LotsOfStyles: View {
var body: some View {
Group {
Text("just red").foregroundColor(Color.red)
Text("just bigBlue")
.foregroundColor(Color.blue)
.fontWeight(Font.Weight.bold)
.font(Font.system(size: 30))
Text("bigBlue, then red")
.foregroundColor(Color.blue)
.fontWeight(Font.Weight.bold)
.font(Font.system(size: 30))
.foregroundColor(Color.red)
Text("red, then bigBlue")
.foregroundColor(Color.red)
.foregroundColor(Color.blue)
.fontWeight(Font.Weight.bold)
.font(Font.system(size: 30))
}
}
}
PlaygroundPage.current.liveView = UIHostingController(rootView: LotsOfStyles())
|
//
// AuraLocalDeviceManager.swift
// iOS_Aura
//
// Created by Emanuel Peña Aguilar on 12/21/16.
// Copyright © 2016 Ayla Networks. All rights reserved.
//
import UIKit
import CoreBluetooth
import iOS_AylaSDK
class AuraLocalDeviceManager: AylaBLEDeviceManager {
override init() {
super.init(services: [AuraLocalDeviceManager.SERVICE_GRILL_RIGHT, CBUUID(string: SERVICE_AYLA_BLE)])
}
static let PLUGIN_ID_LOCAL_DEVICE = "com.aylanetworks.aylasdk.localdevice"
enum DeviceManagerError: Error {
case emptyServiceArray
}
static let SERVICE_GRILL_RIGHT = CBUUID(string: GrillRightDevice.SERVICE_GRILL_RIGHT)
static let SERVICE_GENERIC_THERMOSTAT = CBUUID(string: SERVICE_AYLA_BLE)
override func deviceClass(forModel model: String, oemModel: String, uniqueId: String) -> AnyClass? {
if model.compare(GrillRightDevice.GRILL_RIGHT_MODEL) == .orderedSame {
return GrillRightDevice.self
} else if model.compare(AylaGenericThermostatDevice.BLE_TSTAT_MODEL) == .orderedSame {
return AylaGenericThermostatDevice.self
}
return super.deviceClass(forModel: model, oemModel: oemModel, uniqueId: uniqueId)
}
override func createLocalCandidate(_ peripheral: CBPeripheral, advertisementData: [String : Any], rssi: Int) -> AylaBLECandidate {
let serviceUUIDs = advertisementData["kCBAdvDataServiceUUIDs"] as! [CBUUID];
for service in serviceUUIDs {
if service.isEqual(AuraLocalDeviceManager.SERVICE_GRILL_RIGHT) {
let device = GrillRightCandidate(peripheral: peripheral,advertisementData: advertisementData,rssi: rssi,bleDeviceManager: self)
return device
} else if service.isEqual(AuraLocalDeviceManager.SERVICE_GENERIC_THERMOSTAT) {
let device = AylaGenericThermostatCandidate(peripheral: peripheral,advertisementData: advertisementData,rssi: rssi,bleDeviceManager: self)
return device
}
}
return super.createLocalCandidate(peripheral, advertisementData: advertisementData, rssi: rssi)
}
}
|
protocol anyPostOwner: anyPostMember{
}
|
//: [Previous](@previous)
class Solution {
func searchInsert(_ nums: [Int], _ target: Int) -> Int {
for (index, num) in nums.enumerated() {
if num >= target {
return index
}
}
return nums.count
}
}
//: [Next](@next)
|
import Foundation
import UIKit
public final class CityCoordinator: Coordinator {
private let navigationController: UINavigationController
init(navigationController: UINavigationController) {
self.navigationController = navigationController
}
public func start() {
let cityVC = CityViewController.instantiate(with: "City")
self.navigationController.navigationBar.isHidden = true
cityVC.doNavigation = doNavigation
navigationController.pushViewController(cityVC, animated: true)
}
private func doNavigation(tappedText: String) {
let cityVC = CityViewController.instantiate(with: "City")
// cityVC.str = tappedText
navigationController.pushViewController(cityVC, animated: true)
}
}
|
import Foundation
/**
A struct that contains decoded Rower Data.
*/
public struct RowerData {
/**
The instantaneous stroke rate in strokes/minute.
*/
public let strokeRate: Double?
/**
The total number of strokes since the beginning of the training session.
*/
public let strokeCount: Int?
/**
The average stroke rate since the beginning of the training session, in
strokes/minute.
*/
public let averageStrokeRate: Double?
/**
The total distance since the beginning of the training session, in meters.
*/
public let totalDistanceMeters: Int?
/**
The value of the pace (time per 500 meters) of the user while exercising,
in seconds.
*/
public let instantaneousPaceSeconds: Int?
/**
The value of the average pace (time per 500 meters) since the beginning of
the training session, in seconds.
*/
public let averagePaceSeconds: Int?
/**
The value of the instantaneous power in Watts.
*/
public let instantaneousPowerWatts: Int?
/**
The value of the average power since the beginning of the training session,
in Watts.
*/
public let averagePowerWatts: Int?
/**
The current value of the resistance level.
*/
public let resistanceLevel: Int?
/**
The total expended energy of a user since the training session has started,
in Kilocalories.
*/
public let totalEnergyKiloCalories: Int?
/**
The average expended energy of a user during a period of one hour, in
Kilocalories.
*/
public let energyPerHourKiloCalories: Int?
/**
The average expended energy of a user during a period of one minute, in
Kilocalories.
*/
public let energyPerMinuteKiloCalories: Int?
/**
The current heart rate value of the user, in beats per minute.
*/
public let heartRate: Int?
/**
The metabolic equivalent of the user.
*/
public let metabolicEquivalent: Double?
/**
The elapsed time of a training session since the training session has
started, in seconds.
*/
public let elapsedTimeSeconds: Int?
/**
The remaining time of a selected training session, in seconds.
*/
public let remainingTimeSeconds: Int?
}
|
//
// Test_answers+CoreDataProperties.swift
// LiraTech
//
// Created by Ira Zozulya on 02.06.2021.
//
//
import Foundation
import CoreData
extension Test_answers {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Test_answers> {
return NSFetchRequest<Test_answers>(entityName: "Test_answers")
}
@NSManaged public var answer: String?
@NSManaged public var answer_id: Int64
@NSManaged public var question_id: Int64
}
extension Test_answers : Identifiable {
}
|
//
// ViewControllerExtension.swift
// J.Todo
//
// Created by JinYoung Lee on 2019/12/20.
// Copyright © 2019 JinYoung Lee. All rights reserved.
//
import Foundation
import UIKit
import SideMenu
extension UIViewController {
func intializeSideMenu() {
SideMenuManager.default.leftMenuNavigationController = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(identifier: "sideMenu") as? SideMenuNavigationController
SideMenuManager.default.leftMenuNavigationController?.settings = sideMenuSetting
SideMenuManager.default.leftMenuNavigationController?.navigationBar.isHidden = true
SideMenuManager.default.addScreenEdgePanGesturesToPresent(toView: view)
}
var LeftSideMenu: SideMenuNavigationController? {
return SideMenuManager.default.leftMenuNavigationController
}
private var sideMenuSetting: SideMenuSettings {
let presentationStyle = SideMenuPresentationStyle.menuSlideIn
presentationStyle.presentingScaleFactor = 0.8
presentationStyle.menuScaleFactor = 1
presentationStyle.presentingEndAlpha = 0.7
var settings = SideMenuSettings()
settings.presentationStyle = presentationStyle
settings.menuWidth = screenWidth * 0.75
settings.blurEffectStyle = .none
settings.dismissWhenBackgrounded = true
return settings
}
@objc func presentLeftSideMenu() {
guard let sideMenu = LeftSideMenu else { return }
present(sideMenu, animated: true, completion: nil)
}
}
|
//
// AdsViewController.swift
// AdManagerMediatonDemo
//
// Created by Gu Chan on 2020/05/20.
// Copyright © 2020 GuChan. All rights reserved.
//
import GoogleMobileAds
import UIKit
class AdsViewController: UIViewController,GADRewardedAdDelegate {
var rewardedAd: GADRewardedAd?
//var mUnitID = "/50378101/gc-test"
var mUnitID = "ca-app-pub-2748478898138855/2704625864"
override func viewDidLoad() {
super.viewDidLoad()
print("viewDidLoad")
//GADMobileAds.sharedInstance().requestConfiguration.testDeviceIdentifiers = ["ab9be09a17cc251676f8e647a02559cd"]
rewardedAd = GADRewardedAd(adUnitID: mUnitID)
//GADMobileAds.sharedInstance().requestConfiguration.testDeviceIdentifiers = ["ab9be09a17cc251676f8e647a02559cd",(kGADSimulatorID as! String)]
//rewardedAd = GADRewardedAd(adUnitID: mUnitID)
}
@IBAction func onCloseBtn(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
@IBAction func loadRewardAd(_ sender: UIButton) {
rewardedAd?.load(GADRequest()) { error in
//self.adRequestInProgress = false
if let error = error {
print("Loading failed: \(error)")
} else {
print("Loading Succeeded")
self.rewardedAd?.present(fromRootViewController: self, delegate:self)
}
}
}
func rewardedAd(_ rewardedAd: GADRewardedAd, userDidEarn reward: GADAdReward) {
print("rewardedAd userDidEarn.")
}
/// Tells the delegate that the rewarded ad was presented.
func rewardedAdDidPresent(_ rewardedAd: GADRewardedAd) {
print("Rewarded ad presented.")
}
/// Tells the delegate that the rewarded ad was dismissed.
func rewardedAdDidDismiss(_ rewardedAd: GADRewardedAd) {
print("Rewarded ad dismissed.")
}
/// Tells the delegate that the rewarded ad failed to present.
func rewardedAd(_ rewardedAd: GADRewardedAd, didFailToPresentWithError error: Error) {
print("Rewarded ad failed to present.")
}
/*
// 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.
}
*/
}
|
import Foundation
protocol SessionDataTaskBuilding {
func buildSessionDataTask(with task: Task,
handler: SessionDataTaskHandling) throws -> URLSessionDataTask
}
|
//
// AddFilmRollViewModel.swift
// FilmRollsMVVM
//
// Created by David Neff on 12/19/17.
// Copyright © 2017 Dave Neff. All rights reserved.
//
import Foundation
// TODO: - Abstract AddFilmRoll business logic into ViewModel
// Need to figure best way to bind VC to VM -- RxSwift? Manually?
struct AddFilmRollViewModel {
}
|
//
// CurrentTransactionsViewController.swift
// Chek It
//
// Created by Mike Kane on 7/1/16.
// Copyright © 2016 Mike Kane. All rights reserved.
import UIKit
import RealmSwift
class CurrentTransactionsViewController: UIViewController {
var transactionSelected: Transaction!
var currentTransactions = RealmHelper.objects(Transaction.self)?.filter("transactionComplete = false")
@IBOutlet weak var transactionsTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "TransactionCellNib", bundle: nil)
transactionsTableView.register(nib, forCellReuseIdentifier: "TransactionCell")
transactionsTableView.dataSource = self
transactionsTableView.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
transactionsTableView.reloadData()
}
@IBAction func unwindToTransactionsSegue(_ segue: UIStoryboardSegue) {
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "viewTransactionSegue" {
let nextVC = segue.destination as! ViewTransactionViewController
nextVC.transactionToView = transactionSelected
}
}
}
extension CurrentTransactionsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if currentTransactions?.count == 0 {
return 1
} else {
return (currentTransactions?.count)!
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TransactionCell", for: indexPath) as! TransactionTableViewCell
if let currentTransactions = currentTransactions {
if currentTransactions.count == 0 {
cell.textLabel?.text = "No items currently checked out."
} else {
cell.textLabel?.text = ""
let transaction = currentTransactions[(indexPath as NSIndexPath).row]
let student = transaction.student!
let item = transaction.item!
let itemImage = UIImage(data: item.picture)
cell.itemImageView.image = itemImage!
cell.itemNameLabel.text = item.itemName
let studentImage = UIImage(data: student.picture)
cell.studentImageView.image = studentImage!
cell.studentNameLabel.text = "\(student.lastName!), \(student.firstName!)"
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
transactionSelected = currentTransactions![(indexPath as NSIndexPath).row]
performSegue(withIdentifier: "viewTransactionSegue", sender: nil)
}
}
|
//
// PlaylistVideo+CoreDataProperties.swift
// udacityProject
//
// Created by Ryan Ballenger on 7/8/16.
// Copyright © 2016 Ryan Ballenger. All rights reserved.
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
import Foundation
import CoreData
extension PlaylistVideo {
@NSManaged var title: String?
@NSManaged var videoId: String?
@NSManaged var details: String?
}
|
//
// Categoria_Articulo.swift
// recetas
//
// Created by Eugenia Perez Velasco on 26/4/15.
// Copyright (c) 2015 Roberto Dehesa. All rights reserved.
//
import Foundation
import CoreData
class Categoria_Articulo: NSManagedObject {
@NSManaged var idcategoria: NSNumber
@NSManaged var nombre: String
@NSManaged var newRelationship: NSSet
}
|
//
// StringExtension.swift
// ScheduleApp
//
// Created by Haroldo Leite on 21/12/18.
// Copyright © 2018 Haroldo Leite. All rights reserved.
//
import Foundation
import UIKit
extension String {
static func localize(_ string: String) -> String {
return NSLocalizedString(string, comment: "")
}
}
|
//: Playground - noun: a place where people can play
import Cocoa
var testString = "Merp"
var name = testString + " LOL"
print(name)
var other :Int
other = 801 - 910 - 5921
print(other)
|
//
// ProfileViewController.swift
// PolyTweet
//
// Created by Nicolas zambrano on 15/02/2017.
// Copyright © 2017 Nicolas zambrano. All rights reserved.
//
import UIKit
import CoreData
class ResetPasswordViewController : UIViewController {
var user:User?=nil;
@IBOutlet weak var oldPassword: UITextField!
@IBOutlet weak var newPassword: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
user=SingleUser.getUser();
}
@IBAction func valider(_ sender: Any) {
if(user?.password == oldPassword.text){
user?.password=newPassword.text
CoreDataManager.save();
dismiss(animated: true, completion: nil)
}else {
self.alert(title:"Erreur", message:" L'ancien mot de passe n'est pas le bon");
}
}
}
|
//
// ViewController.swift
// FinnProject
//
// Created by Emir Kartal on 27.02.2018.
// Copyright © 2018 Emir Kartal. All rights reserved.
//
import UIKit
class AdvertViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var advertCollectionView: UICollectionView!
@IBOutlet weak var favouriteSwitch: UISwitch!
@IBOutlet weak var favouriteLabel: UILabel!
var adModel = AdvertModel()
var cache = NSCache<NSString, AnyObject>()
var favouriteIndex = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
if let array = UserDefaults.standard.object(forKey: "favourite"), let index = UserDefaults.standard.object(forKey: "index") {
adModel.advertArrays.adIsFavouriteArray = array as! [Bool]
favouriteIndex = index as! [Int]
}
customizeCollectionView()
advertCollectionView.delegate = self
advertCollectionView.dataSource = self
DispatchQueue.global(qos: .userInteractive).async {
self.adModel.getApiData()
DispatchQueue.main.async {
self.advertCollectionView.reloadData()
}
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return favouriteSwitch.isOn ? favouriteIndex.count : self.adModel.advertArrays.adLocationArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = advertCollectionView.dequeueReusableCell(withReuseIdentifier: "adCell", for: indexPath) as! AdvertCollectionViewCell
// The codding block shows the favourite adverts thanks to the array which is filled in tapEdit function
if favouriteSwitch.isOn {
let newIndex = favouriteIndex[indexPath.row]
let imageURLString = "https://images.finncdn.no/dynamic/480x360c/\(self.adModel.advertArrays.adImageURLArray[newIndex])"
let imageURL = URL(string: imageURLString)
let data = try! Data(contentsOf: imageURL!)
if let cachedImage = cache.object(forKey: imageURLString as NSString) {
cell.advertImage.image = cachedImage as? UIImage
} else {
cell.advertImage.image = UIImage(data: data)
}
cell.advertLocationLabel.text = self.adModel.advertArrays.adLocationArray[newIndex]
cell.advertDescriptionLabel.text = self.adModel.advertArrays.adDescriptionArray[newIndex]
cell.advertPriceLabel.text = " \(self.adModel.advertArrays.adPriceArray[indexPath.row]),-"
cell.advertFavouriteImage.image = UIImage(named: "favourite.png")
return cell
} else { // The coding block shows all adverts in the collection view
cell.advertLocationLabel.text = self.adModel.advertArrays.adLocationArray[indexPath.row]
cell.advertDescriptionLabel.text = self.adModel.advertArrays.adDescriptionArray[indexPath.row]
cell.advertPriceLabel.text = " \(self.adModel.advertArrays.adPriceArray[indexPath.row]),-"
// This if statement prevent changing icon without tapping favourite icon. Before that, if we tap one of favourite icons, some favourite icons in collection can be selected.
if adModel.advertArrays.adIsFavouriteArray[indexPath.row] {
cell.advertFavouriteImage.image = UIImage(named: "favourite.png")
} else {
cell.advertFavouriteImage.image = UIImage(named: "notFavourite.png")
}
let imageURLString = "https://images.finncdn.no/dynamic/480x360c/\(self.adModel.advertArrays.adImageURLArray[indexPath.row])"
let imageURL = URL(string: imageURLString)
if let cachedImage = cache.object(forKey: imageURLString as NSString) {
cell.advertImage.image = cachedImage as? UIImage
}else {
DispatchQueue.main.async {
do {
let data = try Data(contentsOf: imageURL!)
cell.advertImage.image = UIImage(data: data)
self.cache.setObject(cell.advertImage.image!, forKey: imageURLString as NSString)
}catch {
cell.advertImage.image = UIImage(named: "imageError.png")
}
}
}
let recognizer = UITapGestureRecognizer(target: self, action: #selector(tapEdit(sender:)))
cell.advertFavouriteImage.isUserInteractionEnabled = true
cell.advertFavouriteImage.addGestureRecognizer(recognizer)
return cell
}
}
@IBAction func switchOnOff(_ sender: UISwitch) {
if sender.isOn {
favouriteLabel.text = "Show All"
} else {
favouriteLabel.text = "Show Favourites"
}
DispatchQueue.main.async {
self.advertCollectionView.reloadData()
}
}
@objc func tapEdit(sender: UITapGestureRecognizer){
// This function is about adding action the favourite icon which is in the each cell. Also it provides, adding the indexpath of the collection view to an array to show them in favourites.
let tapLocation = sender.location(in: self.advertCollectionView)
if let tapIndexPath = self.advertCollectionView.indexPathForItem(at: tapLocation){
if let tappedCell = self.advertCollectionView.cellForItem(at: tapIndexPath) as? AdvertCollectionViewCell {
if tappedCell.advertFavouriteImage.image == UIImage(named: "notFavourite.png") {
adModel.advertArrays.adIsFavouriteArray[tapIndexPath.row] = true
favouriteIndex.append(tapIndexPath.row)
tappedCell.advertFavouriteImage.image = UIImage(named: "favourite.png")
} else {
if favouriteSwitch.isOn == false {
tappedCell.advertFavouriteImage.image = UIImage(named: "notFavourite.png")
let removeIndex = favouriteIndex.index(of: tapIndexPath.row)
adModel.advertArrays.adIsFavouriteArray[tapIndexPath.row] = false
favouriteIndex.remove(at: removeIndex!)
}else {
tappedCell.advertFavouriteImage.image = UIImage(named: "notFavourite.png")
adModel.advertArrays.adIsFavouriteArray[favouriteIndex[tapIndexPath.row]] = false
favouriteIndex.remove(at: tapIndexPath.row)
self.advertCollectionView.reloadData()
}
}
UserDefaults.standard.set(adModel.advertArrays.adIsFavouriteArray, forKey: "favourite")
UserDefaults.standard.set(favouriteIndex, forKey: "index")
}
}
}
func customizeCollectionView() {
let layout = UICollectionViewFlowLayout()
advertCollectionView.collectionViewLayout = layout
layout.sectionInset = UIEdgeInsetsMake(7, 7, 7, 7)
let itemWidth = (UIScreen.main.bounds.width-24)/2
layout.itemSize = CGSize(width: itemWidth , height: itemWidth )
layout.minimumLineSpacing = 10
layout.minimumInteritemSpacing = 0
}
}
|
//
// KeyboardMoveListener.swift
// MemeMe
//
// Created by Zhehui Joe Zhou on 7/5/17.
// Copyright © 2017 ZhehuiZhou. All rights reserved.
//
import Foundation
import UIKit
class KeyboardMoveListener: NSObject {
// MARK: Fields
weak var view: UIView?
var elements: [UIResponder] = []
let notificationCenter = NotificationCenter.default
// MARK: Subscribe and Unsubscribe
func subscribe(view: UIView, elements: [UIResponder]) {
self.view = view
self.elements = elements
notificationCenter.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
notificationCenter.addObserver(self, selector: #selector(UIKeyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)
}
func unsubscribe() {
notificationCenter.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
notificationCenter.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
}
// MARK: Keyboard
func keyboardWillShow(_ notification:Notification) {
for element in elements {
if element.isFirstResponder {
view?.frame.origin.y = -getKeyboardHeight(notification)
return
}
}
}
func getKeyboardHeight(_ notification:Notification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.cgRectValue.height
}
func UIKeyboardWillHide(_ notification: NSNotification) {
view?.frame.origin.y = 0
}
}
|
//
// RegisterMood.swift
// Control It WatchKit Extension
//
// Created by Ingra Cristina on 26/02/21.
//
import SwiftUI
struct RegisterMood: View {
var body: some View {
VStack {
Image("checkRegister")
.offset()
.padding()
Text("string!")
// .padding()
.font(.largeTitle)
.padding()
// Text("Continue a nadar!")
// .padding()
Button("OK!") {
// your action here
}
//.padding()
}
}
}
struct RegisterMood_Previews: PreviewProvider {
static var previews: some View {
RegisterMood()
}
}
|
//
// Array+Only.swift
// Lecture 4 Grid + enum + Optionals
//
// Created by Mert Arıcan on 27.06.2020.
// Copyright © 2020 Mert Arıcan. All rights reserved.
//
import Foundation
extension Array {
var only: Element? {
count == 1 ? first : nil
}
}
|
//
// AppDelegate.swift
// WearPizzaIOS
//
// Created by Kale Baiton on 2015-07-15.
// Copyright (c) 2015 Kale Baiton. All rights reserved.
//
import UIKit
import WatchKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(application: UIApplication, handleWatchKitExtensionRequest userInfo: [NSObject : AnyObject]?, reply: (([NSObject : AnyObject]!) -> Void)!) {
if let userInfo = userInfo, orderData = userInfo["order"] as? Dictionary<String, AnyObject> {
println(orderData)
var address = Address()
var store = Store()
let order = Order().genericToOrder(orderData)
let userDefaults = NSUserDefaults(suiteName: "group.wearpizza")!
if let addressData: AnyObject = userDefaults.valueForKey("address") {
var a = addressData as! Dictionary<String, String>
var newAddress = Address().genericToDictionary(a)
address = newAddress
}
if let storeArray: AnyObject = userDefaults.valueForKey("storeArray") {
var s = storeArray as! Array<Dictionary<String, String>>
var stores = Store().genericToArray(s)
store = stores[0]
}
pza.postOrder(store, address: address, pizzas: order.pizzas, amount: order.price, callback: { (response: Bool) -> Void in
reply(["status":response])
})
}
reply(["status":false])
}
}
|
import UIKit
class NetworkState {
class func isConnected() ->Bool {
if Reachability.isConnectedToNetwork(){
return true
}else{
return false
}
}
}
|
//
// ReviewSection.swift
// CookingRecipe
//
// Created by Nil Nguyen on 1/21/21.
//
import SwiftUI
struct ReviewSectionView : View {
@State var index : Int = 0
@StateObject var reviewVM : ReviewViewModel
var body : some View {
Text("Reviews")
.bold()
.font(.title2)
.padding(.horizontal, 7)
.padding(.bottom, 5)
if let yourReview = reviewVM.yourReview {
ReviewEditorView(reviewVM: reviewVM,review: yourReview, isNew : false)
} else{
ReviewEditorView(reviewVM: reviewVM,review: Review(), isNew : true)
}
Divider()
ForEach(reviewVM.reviews){ review in
ReviewCard(review: review)
Divider()
}
}
}
struct ReviewCard : View {
var review : Review
var body: some View{
VStack(alignment: .leading, spacing: 10){
Text(review.username)
.font(.title3)
Text(review.comment)
}
.padding(.horizontal,10)
}
}
struct ReviewEditorView : View {
var reviewVM : ReviewViewModel
@State var review : Review
var isNew : Bool
@State var showingAlert : Bool = false
var body: some View{
VStack (alignment: .trailing){
if !isNew{
Button(action: {
self.showingAlert = true
}, label: {
Image(systemName: "trash")
})
.frame(alignment: .trailing)
.alert(isPresented:$showingAlert) {
Alert(title: Text("Are you sure you want to delete this?"),
message: Text("There is no undo"),
primaryButton: .destructive(Text("Delete")) {
print("Deleting...")
reviewVM.deleteReview(self.review)
}, secondaryButton: .cancel())
}
}
TextField( "some tips?", text: self.$review.comment)
if review.comment != ""{
Button(action : {reviewVM.updateReview(self.review)}){
Text("Save")
.foregroundColor(.blue)
}
}
}
.padding(.horizontal, 10)
}
}
|
//
// RepositoryProvider.swift
// GitXplore
//
// Created by Augusto Cesar do Nascimento dos Reis on 12/12/20.
//
import Foundation
import Moya
enum RepositoryProvider {
case searchRepository(term: String)
}
extension RepositoryProvider: TargetType {
var baseURL: URL {
guard let url = URL(string: "https://api.github.com") else {
return URL(fileURLWithPath: "")
}
return url
}
var path: String {
switch self {
case .searchRepository(term: _):
return "/search/repositories"
}
}
var method: Moya.Method {
return .get
}
var sampleData: Data {
return "{\"total_count\":41510,\"incomplete_results\":false,\"items\":[{\"id\":7508411,\"node_id\":\"MDEwOlJlcG9zaXRvcnk3NTA4NDEx\",\"name\":\"RxJava\",\"full_name\":\"ReactiveX/RxJava\",\"private\":false}]}".data(using: .utf8) ?? Data()
}
var task: Task {
switch self {
case .searchRepository(term: let term):
let parameters = ["q": term]
return .requestParameters(parameters: parameters, encoding: URLEncoding.queryString)
}
}
var headers: [String : String]? {
return ["Content-Type": "application/json"]
}
}
|
//
// KeyboardSpaceKeyContentView.swift
// KeyboardKit
//
// Created by Valentin Shergin on 4/4/16.
// Copyright © 2016 AnchorFree. All rights reserved.
//
import UIKit
public final class KeyboardSpaceKeyContentView: KeyboardKeyContentView {
public var labelView: UILabel!
public var pageControlView: KeyboardSpaceKeyPageControlView!
public override init(frame: CGRect) {
super.init(frame: frame)
self.labelView = UILabel()
self.labelView.text = "Space"
self.addSubview(self.labelView)
self.pageControlView = KeyboardSpaceKeyPageControlView()
self.pageControlView.transform = CGAffineTransformMakeScale(0.5, 0.5);
// self.pageControlView.pageIndicatorTintColor = UIColor.blackColor()
// self.pageControlView.currentPageIndicatorTintColor = UIColor.whiteColor()
// self.pageControlView.backgroundColor = UIColor.brownColor()
self.addSubview(self.pageControlView)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public var appearance: KeyboardKeyAppearance {
didSet {
let color = self.appearance.keycapTextColor
self.pageControlView.pageIndicatorTintColor = color.colorWithAlphaComponent(0.2)
self.pageControlView.currentPageIndicatorTintColor = color
self.labelView.font = appearance.keycapTextFont
self.labelView.textColor = appearance.keycapTextColor
}
}
public override func layoutSubviews() {
super.layoutSubviews()
self.labelView.sizeToFit()
self.labelView.center = CGPoint(x: self.bounds.midX, y: self.bounds.midY - 3.0)
self.pageControlView.frame = CGRect(
origin: CGPointZero,
size: CGSize(width: self.bounds.size.width, height: 4.0))
self.pageControlView.frame.origin.y = self.bounds.size.height - 8.0 - 2.0
}
}
extension KeyboardSpaceKeyContentView {
public override func copyWithZone(zone: NSZone) -> AnyObject {
// TODO: Add required init
//let contentView = self.dynamicType.init(frame: self.frame)
let contentView = KeyboardSpaceKeyContentView(frame: self.frame)
contentView.pageControlView.numberOfPages = self.pageControlView.numberOfPages
contentView.pageControlView.currentPage = self.pageControlView.currentPage
return contentView
}
}
public final class KeyboardSpaceKeyPageControlView: UIPageControl {
public override func sizeForNumberOfPages(pageCount: Int) -> CGSize {
return CGSize(width: pageCount * 30, height: 10)
}
} |
//
// LocationManager.swift
// Myoozik
//
// Created by Alessandro Bolattino on 04/04/18.
// Copyright © 2018 Mussini SAS. All rights reserved.
//
//
// LocationManager.swift
// Diarly
//
// Created by Alessandro Bolattino on 28/03/18.
// Copyright © 2018 Diarly. All rights reserved.
//
import Foundation
import CoreLocation
import UIKit
class LocationManager: NSObject, CLLocationManagerDelegate{
let locationManager = CLLocationManager()
var lastLocation = CLLocation()
public private(set) var acceptableLocationAccuracy: CLLocationAccuracy = 80
static let shared: LocationManager = LocationManager()
override init() {
super.init()
configureLocationManager()
}
func configureLocationManager(){
print("Called ConfigureLocationManager ");
locationManager.delegate = self
// status is not determined
if CLLocationManager.authorizationStatus() == .notDetermined {
print("Called notDetermined");
locationManager.requestAlwaysAuthorization()
}
// authorization were denied
else if CLLocationManager.authorizationStatus() == .denied {
print("Called denied");
print("Location services were previously denied. Please enable location services for this app in Settings.")
}
// we do have authorization
else if CLLocationManager.authorizationStatus() == .authorizedAlways {
print("Called always");
}
locationManager.startMonitoringSignificantLocationChanges()
locationManager.allowsBackgroundLocationUpdates = true
locationManager.desiredAccuracy = kCLLocationAccuracyBest
//locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.distanceFilter = 30;
locationManager.pausesLocationUpdatesAutomatically = true
}
public func requestAlwaysAuthorization() {
locationManager.requestAlwaysAuthorization()
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedAlways {
}else{
//include.dispatchNotif("Accetta localizzazione!");
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
NotificationManager.shared.sendNotification(titled: "didUpdateLocation", containing: "")
if locations.count > 0 {
self.lastLocation = locations.last!
}
}
func locationManager(_ manager: CLLocationManager, didFinishDeferredUpdatesWithError error: Error?) {
print("stop")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
}
private func acceptableLocationAccuracyRetrieved() -> Bool {
if let location = self.lastLocation as? CLLocation {
print("isLocation");
if let accuracy = location.horizontalAccuracy as? CLLocationAccuracy {
print("Location accuracy: \(location.horizontalAccuracy)");
return Double(accuracy) <= acceptableLocationAccuracy ? true : false
}
}
return false
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
print("DidFailWithError()")
NSLog("\(error)")
print("\n\n\n")
}
}
|
//
// PPTransactionViewController.swift
// prkng-ios
//
// Created by Antonino Urbano on 2016-02-25.
// Copyright © 2016 PRKNG. All rights reserved.
//
import UIKit
class PPTransactionViewController: UIViewController, ModalHeaderViewDelegate, UIScrollViewDelegate, UIGestureRecognizerDelegate {
private var transaction: ParkingPandaTransaction //customized based on the presence of the lot
private var lot: Lot?
private var popupVC: PRKPopupViewController?
private var scrollView = UIScrollView()
private var contentView = UIView()
private var topImageView = GMSPanoramaView(frame: CGRectZero)
private var topGradient = UIImageView()
private var directionsButton = ViewFactory.directionsButton()
private var topLabel = UILabel()
private var headerView: ModalHeaderView
private var fromTimeView = UIView()
private var fromTimeIconView = UIImageView(image: UIImage(named: "icon_time_thin"))
private var fromTimeViewLabel = UILabel()
private var separator1 = UIView()
private var toTimeView = UIView()
private var toTimeIconView = UIImageView(image: UIImage(named: "icon_time_thin"))
private var toTimeViewLabel = UILabel()
private var separator2 = UIView()
private var barcodeImageView = UIImageView()
private var payContainerView = UIView()
private var creditCardImageView = ViewFactory.genericImageViewWithImageName("icon_credit_card", andColor: Styles.Colors.red2)
private var payTitleLabel = UILabel()
private var paySubtitleLabel = UILabel()
private var priceLabel = UILabel()
private var separator3 = UIView()
private var separator4 = UIView()
private var attributesView = UIView()
private var attributesViewContainers = [UIView]()
private var attributesViewLabels = [UILabel]()
private var attributesViewImages = [UIImageView]()
//TODO: Localize
private var addToWalletButton = ViewFactory.redRoundedButtonWithHeight(36, font: Styles.FontFaces.bold(12), text: "add_to_wallet".localizedString.uppercaseString)
private let streetViewHeight: CGFloat = 222
private let headerHeight: CGFloat = 70
private(set) var gradientHeight: CGFloat = 65
private let timeViewHeight: CGFloat = 60
private let attributesViewHeight: CGFloat = 52
private let payContainerViewHeight: CGFloat = 60
private let paddingHeight: CGFloat = 5
init(transaction: ParkingPandaTransaction, lot: Lot?) {
self.transaction = transaction
self.lot = lot
headerView = ModalHeaderView()
super.init(nibName: nil, bundle: nil)
contentView = scrollView
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func presentWithVC(vc: UIViewController?, showingSuccessPopup: Bool) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
if let rootVC = vc ?? appDelegate.window?.rootViewController {
if let navVC = rootVC.navigationController {
navVC.pushViewController(self, animated: true)
if showingSuccessPopup {
self.showPopupForReportSuccess()
}
} else {
rootVC.presentViewController(self, animated: true, completion: { () -> Void in
if showingSuccessPopup {
self.showPopupForReportSuccess()
}
})
}
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
setupSubviews()
setupConstraints()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
recalculateScrollView(centerBarcodeImageView: false)
}
func setupSubviews() {
scrollView.delegate = self
scrollView.alwaysBounceVertical = true
self.view.addSubview(scrollView)
contentView.backgroundColor = Styles.Colors.cream1
scrollView.addSubview(topImageView)
topImageView.navigationLinksHidden = true
LotOperations.sharedInstance.findLot(transaction.location.identifier, partnerName: "Parking Panda") { (lot) -> Void in
self.lot = lot
self.lotSetup()
}
scrollView.addSubview(topGradient)
scrollView.addSubview(topLabel)
topLabel.textColor = Styles.Colors.cream1
scrollView.addSubview(headerView)
headerView.topText = transaction.location.address
headerView.showsRightButton = false
headerView.delegate = self
headerView.clipsToBounds = true
directionsButton.addTarget(self, action: "directionsButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside)
scrollView.addSubview(directionsButton)
fromTimeView.backgroundColor = Styles.Colors.cream1
scrollView.addSubview(fromTimeView)
fromTimeIconView.image = fromTimeIconView.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
fromTimeIconView.tintColor = Styles.Colors.midnight1
fromTimeView.addSubview(fromTimeIconView)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE, MMM d, yyyy 'at' HH:mm"
let timeViewLabelTopAttrs = [NSFontAttributeName: Styles.FontFaces.bold(12)]
let timeViewLabelBottomAttrs = [NSFontAttributeName: Styles.FontFaces.regular(14)]
let fromTimeViewLabelTopText = NSMutableAttributedString(string: "from".localizedString.uppercaseString + "\n", attributes: timeViewLabelTopAttrs)
let fromTimeViewLabelBottomText = NSAttributedString(string: dateFormatter.stringFromDate(transaction.startDateAndTime ?? NSDate()), attributes: timeViewLabelBottomAttrs)
fromTimeViewLabelTopText.appendAttributedString(fromTimeViewLabelBottomText)
fromTimeViewLabel.attributedText = fromTimeViewLabelTopText
fromTimeViewLabel.textColor = Styles.Colors.midnight1
fromTimeViewLabel.numberOfLines = 2
fromTimeView.addSubview(fromTimeViewLabel)
separator1.backgroundColor = Styles.Colors.transparentBlack
scrollView.addSubview(separator1)
toTimeView.backgroundColor = Styles.Colors.cream1
scrollView.addSubview(toTimeView)
toTimeIconView.image = toTimeIconView.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
toTimeIconView.tintColor = Styles.Colors.midnight1
toTimeView.addSubview(toTimeIconView)
let toTimeViewLabelTopText = NSMutableAttributedString(string: "to".localizedString.uppercaseString + "\n", attributes: timeViewLabelTopAttrs)
let toTimeViewLabelBottomText = NSAttributedString(string: dateFormatter.stringFromDate(transaction.endDateAndTime ?? NSDate()), attributes: timeViewLabelBottomAttrs)
toTimeViewLabelTopText.appendAttributedString(toTimeViewLabelBottomText)
toTimeViewLabel.attributedText = toTimeViewLabelTopText
toTimeViewLabel.textColor = Styles.Colors.midnight1
toTimeViewLabel.numberOfLines = 2
toTimeView.addSubview(toTimeViewLabel)
separator2.backgroundColor = Styles.Colors.transparentBlack
scrollView.addSubview(separator2)
if let barcodeUrl = NSURL(string: transaction.barcodeUrlString) {
barcodeImageView.sd_setImageWithURL(barcodeUrl, completed: { (image, error, cacheType, url) -> Void in
self.barcodeImageView.image = image.imageTintedWithColor(Styles.Colors.cream1, blendMode: CGBlendMode.Multiply)
let currentDate = NSDate()
if self.transaction.endDateAndTime?.earlierDate(currentDate) == self.transaction.endDateAndTime {
self.barcodeImageView.alpha = 0.2
}
})
}
barcodeImageView.contentMode = .ScaleAspectFit
barcodeImageView.userInteractionEnabled = true
let tapRec = UITapGestureRecognizer(target: self, action: Selector("didTapBarcodeImage"))
tapRec.delegate = self
barcodeImageView.addGestureRecognizer(tapRec)
scrollView.addSubview(barcodeImageView)
contentView.bringSubviewToFront(directionsButton)
separator3.backgroundColor = Styles.Colors.transparentBlack
scrollView.addSubview(separator3)
payContainerView.backgroundColor = Styles.Colors.cream1
scrollView.addSubview(payContainerView)
payContainerView.addSubview(creditCardImageView)
payTitleLabel.text = "paid_with_parking_panda".localizedString
payTitleLabel.textColor = Styles.Colors.red2
payTitleLabel.font = Styles.FontFaces.regular(14)
payTitleLabel.numberOfLines = 1
payContainerView.addSubview(payTitleLabel)
paySubtitleLabel.text = transaction.paymentMaskedCardInfo
paySubtitleLabel.textColor = Styles.Colors.anthracite1
paySubtitleLabel.font = Styles.FontFaces.regular(12)
paySubtitleLabel.numberOfLines = 1
payContainerView.addSubview(paySubtitleLabel)
let remainder = transaction.amount - Float(Int(transaction.amount))
var priceString = String(format: " $%.02f", transaction.amount) //this auto rounds to the 2nd decimal place
if remainder == 0 {
priceString = String(format: " $%.0f", transaction.amount)
}
priceLabel.text = priceString
priceLabel.textColor = Styles.Colors.midnight1
priceLabel.font = Styles.FontFaces.bold(14)
priceLabel.numberOfLines = 1
priceLabel.textAlignment = .Right
payContainerView.addSubview(priceLabel)
separator4.backgroundColor = Styles.Colors.transparentBlack
scrollView.addSubview(separator4)
scrollView.addSubview(attributesView)
attributesView.backgroundColor = Styles.Colors.cream1
}
func setupConstraints() {
scrollView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(self.view)
make.left.equalTo(self.view)
make.right.equalTo(self.view)
make.bottom.equalTo(self.view)
}
topImageView.snp_makeConstraints { (make) -> () in
make.top.equalTo(self.contentView)
make.left.equalTo(self.contentView)
make.right.equalTo(self.contentView)
make.height.equalTo(lot != nil ? streetViewHeight : 0)
make.width.equalTo(self.view)
}
topGradient.snp_makeConstraints { (make) -> () in
make.bottom.equalTo(self.headerView.snp_top)
make.left.equalTo(self.contentView)
make.right.equalTo(self.contentView)
make.height.equalTo(gradientHeight)
make.width.equalTo(self.view)
}
topLabel.snp_makeConstraints { (make) -> () in
make.left.equalTo(self.contentView).offset(34)
make.bottom.equalTo(self.headerView.snp_top).offset(-24)
}
directionsButton.snp_makeConstraints { (make) -> () in
make.right.equalTo(headerView).offset(-30)
make.centerY.equalTo(headerView)
}
headerView.snp_makeConstraints { (make) -> () in
make.top.equalTo(self.topImageView.snp_bottom)
make.left.equalTo(self.contentView)
make.right.equalTo(self.contentView)
make.height.equalTo(headerHeight)
}
payContainerView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(headerView.snp_bottom)
make.left.equalTo(contentView)
make.right.equalTo(contentView)
make.width.equalTo(self.view)
make.height.equalTo(payContainerViewHeight)
}
creditCardImageView.snp_makeConstraints { (make) -> Void in
make.left.equalTo(payContainerView).offset(24)
make.centerY.equalTo(payContainerView).multipliedBy(0.66)
make.size.equalTo(CGSize(width: 20, height: 14))
}
payTitleLabel.snp_makeConstraints { (make) -> Void in
make.left.equalTo(creditCardImageView.snp_right).offset(14)
make.centerY.equalTo(payContainerView).multipliedBy(0.66)
make.right.equalTo(payContainerView).offset(-70)
}
paySubtitleLabel.snp_makeConstraints { (make) -> Void in
make.left.equalTo(payContainerView).offset(24)
make.centerY.equalTo(payContainerView).multipliedBy(1.33)
make.right.equalTo(payContainerView).offset(-70)
}
priceLabel.snp_makeConstraints { (make) -> Void in
make.left.equalTo(payContainerView.snp_right).offset(-70)
make.right.equalTo(payContainerView).offset(-14)
make.centerY.equalTo(payContainerView)
}
separator4.snp_makeConstraints { (make) -> Void in
make.bottom.equalTo(payContainerView)
make.left.equalTo(contentView)
make.right.equalTo(contentView)
make.height.equalTo(1)
}
fromTimeView.snp_makeConstraints { (make) -> () in
make.top.equalTo(payContainerView.snp_bottom)
make.left.equalTo(contentView)
make.right.equalTo(contentView)
make.height.equalTo(timeViewHeight)
make.width.equalTo(self.view)
}
fromTimeIconView.snp_makeConstraints { (make) -> () in
make.left.equalTo(fromTimeView).offset(24)
make.centerY.equalTo(fromTimeView)
make.size.equalTo(CGSize(width: 20, height: 20))
}
fromTimeViewLabel.snp_makeConstraints { (make) -> Void in
make.left.equalTo(fromTimeIconView.snp_right).offset(14)
make.right.equalTo(fromTimeView).offset(-14)
make.centerY.equalTo(fromTimeView)
}
separator1.snp_makeConstraints { (make) -> Void in
make.bottom.equalTo(fromTimeView)
make.left.equalTo(contentView)
make.right.equalTo(contentView)
make.height.equalTo(1)
}
toTimeView.snp_makeConstraints { (make) -> () in
make.top.equalTo(fromTimeView.snp_bottom)
make.left.equalTo(contentView)
make.right.equalTo(contentView)
make.height.equalTo(timeViewHeight)
make.width.equalTo(self.view)
}
toTimeIconView.snp_makeConstraints { (make) -> () in
make.left.equalTo(toTimeView).offset(24)
make.centerY.equalTo(toTimeView)
make.size.equalTo(CGSize(width: 20, height: 20))
}
toTimeViewLabel.snp_makeConstraints { (make) -> Void in
make.left.equalTo(toTimeIconView.snp_right).offset(14)
make.right.equalTo(toTimeView).offset(-14)
make.centerY.equalTo(toTimeView)
}
separator2.snp_makeConstraints { (make) -> Void in
make.bottom.equalTo(toTimeView)
make.left.equalTo(contentView)
make.right.equalTo(contentView)
make.height.equalTo(1)
}
barcodeImageView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(toTimeView.snp_bottom)
make.left.equalTo(contentView)
make.right.equalTo(contentView)
make.width.equalTo(self.view)
make.height.equalTo(120)
}
separator3.snp_makeConstraints { (make) -> Void in
make.bottom.equalTo(barcodeImageView)
make.left.equalTo(contentView)
make.right.equalTo(contentView)
make.height.equalTo(1)
}
}
func lotSetup() {
topImageView.snp_remakeConstraints { (make) -> () in
make.top.equalTo(self.contentView)
make.left.equalTo(self.contentView)
make.right.equalTo(self.contentView)
make.height.equalTo(lot != nil ? streetViewHeight : 0)
make.width.equalTo(self.view)
}
if lot != nil {
if lot!.streetViewPanoramaId == nil {
topImageView.moveNearCoordinate(lot!.coordinate)
} else {
topImageView.moveToPanoramaID(lot!.streetViewPanoramaId!)
}
if let heading = lot!.streetViewHeading {
let cameraUpdate = GMSPanoramaCameraUpdate.setHeading(CGFloat(heading))
topImageView.updateCamera(cameraUpdate, animationDuration: 0.2)
}
let cameraUpdate = GMSPanoramaCameraUpdate.setZoom(3)
topImageView.updateCamera(cameraUpdate, animationDuration: 0.2)
let screenWidth = UIScreen.mainScreen().bounds.width
topGradient.image = UIImage.imageFromGradient(CGSize(width: screenWidth, height: 65.0), fromColor: UIColor.clearColor(), toColor: UIColor.blackColor().colorWithAlphaComponent(0.9))
// if lot!.lotOperator != nil {
// let operatedByString = NSMutableAttributedString(string: "operated_by".localizedString + " ", attributes: [NSFontAttributeName: Styles.FontFaces.light(12)])
// let operatorString = NSMutableAttributedString(string: lot!.lotOperator!, attributes: [NSFontAttributeName: Styles.FontFaces.regular(12)])
// operatedByString.appendAttributedString(operatorString)
// topLabel.attributedText = operatedByString
// } else if lot!.lotPartner != nil {
// let operatedByString = NSMutableAttributedString(string: "operated_by".localizedString + " ", attributes: [NSFontAttributeName: Styles.FontFaces.light(12)])
// let partnerString = NSMutableAttributedString(string: lot!.lotPartner!, attributes: [NSFontAttributeName: Styles.FontFaces.regular(12)])
// operatedByString.appendAttributedString(partnerString)
// topLabel.attributedText = operatedByString
// }
//attributes!
for attribute in lot!.attributes {
let attributesViewContainer = UIView()
attributesViewContainers.append(attributesViewContainer)
let caption = attribute.name(false).localizedString.uppercaseString
let imageName = "icon_attribute_" + attribute.name(true) + (attribute.enabled ? "_on" : "_off" )
let attributeLabel = UILabel()
attributeLabel.text = caption
attributeLabel.textColor = attribute.showAsEnabled ? Styles.Colors.petrol2 : Styles.Colors.greyish
attributeLabel.font = Styles.FontFaces.regular(9)
attributesViewLabels.append(attributeLabel)
let attributeImageView = UIImageView(image: UIImage(named: imageName)!)
attributeImageView.contentMode = .Center
attributesViewImages.append(attributeImageView)
attributesViewContainer.addSubview(attributeLabel)
attributesViewContainer.addSubview(attributeImageView)
attributesView.addSubview(attributesViewContainer)
}
attributesView.snp_makeConstraints { (make) -> () in
make.top.equalTo(self.barcodeImageView.snp_bottom)
make.left.equalTo(self.view)
make.right.equalTo(self.view)
make.height.equalTo(attributesViewHeight)
}
var leftConstraint = self.attributesView.snp_left
for i in 0..<attributesViewContainers.count {
let width = Int(UIScreen.mainScreen().bounds.width)/attributesViewContainers.count
let attributesViewContainer = attributesViewContainers[i]
attributesViewContainer.snp_makeConstraints(closure: { (make) -> () in
make.left.equalTo(leftConstraint)
make.top.equalTo(self.attributesView)
make.bottom.equalTo(self.attributesView)
make.width.equalTo(width)
})
let label = attributesViewLabels[i]
label.snp_makeConstraints(closure: { (make) -> () in
make.centerX.equalTo(attributesViewContainer.snp_centerX)
make.bottom.equalTo(self.attributesView).offset(-4.5)
})
let imageView = attributesViewImages[i]
imageView.snp_makeConstraints(closure: { (make) -> () in
//make.size.equalTo(CGSize(width: 32, height: 32))
make.centerX.equalTo(label.snp_centerX)
make.bottom.equalTo(label.snp_top).offset(-3.5)
})
leftConstraint = attributesViewContainer.snp_right
}
}
}
//MARK: UIScrollViewDelegate
func scrollViewDidScroll(scrollView: UIScrollView) {
let xOffset = 0 - scrollView.contentOffset.y
if xOffset < 0 {
topImageView.snp_remakeConstraints { (make) -> () in
make.top.equalTo(self.contentView)
make.left.equalTo(self.contentView)
make.right.equalTo(self.contentView)
make.height.equalTo(lot != nil ? streetViewHeight : 0)
make.width.equalTo(self.view)
}
} else {
topImageView.snp_remakeConstraints { (make) -> () in
make.top.equalTo(self.view)
make.left.equalTo(self.contentView)
make.right.equalTo(self.contentView)
make.height.equalTo(lot != nil ? streetViewHeight + xOffset : 0)
make.width.equalTo(self.view)
}
}
}
//MARK: PPHeaderViewDelegate functions
func tappedBackButton() {
self.dismissViewControllerAnimated(true, completion: nil)
}
func tappedRightButton() {
directionsButtonTapped(directionsButton)
}
//MARK: Helper methods
func recalculateScrollView(centerBarcodeImageView centerBarcodeImageView: Bool) {
let height = topImageView.frame.size.height + headerHeight + (2*timeViewHeight) + barcodeImageView.frame.size.height + payContainerViewHeight + attributesViewHeight + paddingHeight
scrollView.contentSize = CGSize(width: UIScreen.mainScreen().bounds.width, height: height)
if centerBarcodeImageView {
scrollView.scrollRectToVisible(barcodeImageView.frame, animated: true)
}
}
func didTapBarcodeImage() {
if self.barcodeImageView.frame.size.height == 120 {
self.barcodeImageView.snp_updateConstraints { (make) -> Void in
make.height.equalTo(self.barcodeImageView.image!.size.height)
}
} else {
self.barcodeImageView.snp_updateConstraints { (make) -> Void in
make.height.equalTo(120)
}
}
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.view.layoutIfNeeded()
self.view.updateConstraints()
}) { (finished) -> Void in
self.recalculateScrollView(centerBarcodeImageView: true)
}
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
func directionsButtonTapped(sender: UIButton) {
if lot?.coordinate != nil {
DirectionsAction.perform(onViewController: self, withCoordinate: lot!.coordinate, shouldCallback: false)
}
}
func showPopupForReportSuccess() {
popupVC = PRKPopupViewController(titleIconName: "icon_checkmark", titleText: "", subTitleText: "success".localizedString, messageText: "pp_payment_success".localizedString)
self.addChildViewController(popupVC!)
self.view.addSubview(popupVC!.view)
popupVC!.didMoveToParentViewController(self)
popupVC!.view.snp_makeConstraints(closure: { (make) -> () in
make.edges.equalTo(self.view)
})
let tap = UITapGestureRecognizer(target: self, action: "dismissPopup")
popupVC!.view.addGestureRecognizer(tap)
popupVC!.view.alpha = 0.0
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.popupVC!.view.alpha = 1.0
})
}
func dismissPopup() {
if let popup = self.popupVC {
UIView.animateWithDuration(0.2, animations: { () -> Void in
popup.view.alpha = 0.0
}, completion: { (finished) -> Void in
popup.removeFromParentViewController()
popup.view.removeFromSuperview()
popup.didMoveToParentViewController(nil)
self.popupVC = nil
})
}
}
}
|
//
// TDDTests.swift
// TDDTests
//
// Created by tangyuhua on 2017/4/10.
// Copyright © 2017年 tangyuhua. All rights reserved.
//
import XCTest
@testable import TDD
class TDDTests: XCTestCase {
var viewController: demo!
override func setUp() {
super.setUp()
viewController = demo()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testNumberOfVowelsInString_ShouldReturnNumberOfVowels() {
let string = "Dominik"
let numberOfVowels = viewController.numberOfVowelsInString(string: string)
XCTAssertEqual(numberOfVowels, 3, "should find 3 vowels in Dominik",
file: "FirstDemoTests.swift", line: 24)
}
func testSyntaxDemo (){
XCTAssertEqual(2, 1+1, "2 should be the same as 1+1")
XCTAssertTrue(2 == 1+1, "2 should be the same as 1+1")
}
func testMakeHeadline_ReturnsStringWithEachWordStartCapital() {
let inputString = "this is A test headline"
let expectedHeadline = "This Is A Test Headline"
let result = viewController.makeHeadline(string: inputString)
XCTAssertEqual(result, expectedHeadline)
}
func testMakeHeadline_ReturnsStringWithEachWordStartCapital2() {
let inputString = "Here is another Example"
let expectedHeadline = "Here Is Another Example"
let result = viewController.makeHeadline(string: inputString)
XCTAssertEqual(result, expectedHeadline)
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
|
//
// AppCoordinator.swift
// kurayami
//
// Created by alvin joseph valdez on 08/05/2018.
// Copyright © 2018 alvin joseph valdez. All rights reserved.
//
import Foundation
import UIKit
open class AppCoordinator: AbstractCoordinator {
// MARK: Initializer
public init(window: UIWindow, rootViewController: UINavigationController) {
self.window = window
self.rootViewController = rootViewController
super.init()
self.window.backgroundColor = UIColor.black
self.window.rootViewController = self.rootViewController
self.window.makeKeyAndVisible()
}
// MARK: Stored Properties
private unowned let window: UIWindow
private unowned let rootViewController: UINavigationController
open override func start() {
let mainCoordinator: MainCoordinator = MainCoordinator(
navigationController: self.rootViewController
)
mainCoordinator.start()
self.add(childCoordinator: mainCoordinator)
}
}
|
//
// ViewController.swift
// KoombeaChallengeTest
//
// Created by Renato Mateus De Moura Santos on 25/09/21.
//
import UIKit
import Kingfisher
class HomeViewController: UIViewController {
// MARK: - Outlets
@IBOutlet weak var tableView: UITableView!
// MARK: - Private Properties
internal let viewModel = HomeViewModel(with: PostsService())
private var dataSource: [UserPosts] = []
private var posts: [Post] = []
private var lastUpdated: String?
private let refreshControl = UIRefreshControl()
// MARK: - LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupData()
}
}
// MARK: - SetupUI
extension HomeViewController {
func setupUI() {
tableView.separatorStyle = .none
tableView.backgroundColor = .white
tableView.estimatedRowHeight = 600
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedSectionHeaderHeight = 80
tableView.sectionHeaderHeight = UITableView.automaticDimension
tableView.contentInset = UIEdgeInsets(top: 0,
left: 0,
bottom: 0,
right: 0)
tableView.register(UINib(nibName: MainPostViewCell.identifier,
bundle: nil),
forCellReuseIdentifier: MainPostViewCell.identifier)
tableView.register(UINib(nibName: TableHeaderView.identifier,
bundle: nil),
forHeaderFooterViewReuseIdentifier: TableHeaderView.identifier)
tableView.tableFooterView = UIView()
tableView.showsVerticalScrollIndicator = false
refreshControl.addTarget(self,
action: #selector(self.refresh(_:)),
for: .valueChanged)
tableView.addSubview(refreshControl)
tableView.dataSource = self
tableView.delegate = self
}
}
// MARK: - SetupData
extension HomeViewController {
func setupData() {
viewModel.delegate = self
viewModel.offLineDelegate = self
if dataSource.isEmpty {
tableView.showLoading()
}
viewModel.fetchPosts()
}
}
// MARK: - ViewControllerViewModelDelegate
extension HomeViewController: HomeViewModelDelegate {
func onSuccessFetchingPost(posts: [UserPosts], lastUpdated: Double) {
self.dataSource = posts
self.lastUpdated = self.getDate(sinceTime: lastUpdated)
self.tableView.backgroundView = nil
self.tableView.reloadData()
if self.refreshControl.isRefreshing {
self.refreshControl.endRefreshing()
}
}
func onFailureFetchingPost(error: Error) {
if self.refreshControl.isRefreshing {
self.refreshControl.endRefreshing()
}
self.tableView.backgroundView = self.getEmptyView()
}
}
// MARK: - TableViewDataSource
extension HomeViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let userPost = self.dataSource[indexPath.row]
guard let cell = tableView.dequeueReusableCell(withIdentifier: MainPostViewCell.identifier,
for: indexPath) as? MainPostViewCell else { return UITableViewCell() }
cell.configure(with: userPost)
cell.onDidTapImage = { [weak self] imageView in
guard let self = self else { return }
let vc = DetailPostViewController(with: imageView)
vc.modalPresentationStyle = .overCurrentContext
vc.modalTransitionStyle = .crossDissolve
if let navigationController = self.navigationController {
navigationController.present(vc, animated: true)
}
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let userPost = self.dataSource[indexPath.row]
let height = self.calculateCellHeight(userPost: userPost)
return height
}
}
// MARK: - UITableViewDelegate
extension HomeViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if viewModel.isOffLine {
guard let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: TableHeaderView.identifier) as? TableHeaderView else { return nil }
header.configure(with: self.lastUpdated ?? "")
return header
}
return nil
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return self.calculateHeaderHeight()
}
}
// MARK: - ViewControllerViewModelOffLineDelegate
extension HomeViewController: HomeViewModelOffLineDelegate {
func runningOffLine() {
self.showToast(message: "You're running offline",
font: .systemFont(ofSize: 16, weight: .bold))
}
}
// MARK: - Actions
private extension HomeViewController {
@objc func refresh(_ sender: AnyObject) {
viewModel.fetchPosts()
}
}
// MARK: - Helpers
private extension HomeViewController {
func getEmptyView() -> UIView {
let labelDescription: UILabel = UILabel()
labelDescription.font = .systemFont(ofSize: 20, weight: .regular)
labelDescription.textColor = UIColor.darkGray
labelDescription.numberOfLines = 0
labelDescription.textAlignment = .center
labelDescription.text = "Looks like that you don't have internet. \nPlease check it out and pull to refresh."
labelDescription.translatesAutoresizingMaskIntoConstraints = false
labelDescription.sizeToFit()
return labelDescription
}
func showToast(message : String, font: UIFont) {
let toastLabel = UILabel(frame: CGRect(x: 10,
y: 80,
width: self.view.frame.size.width - 20,
height: 35))
toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
toastLabel.textColor = UIColor.white
toastLabel.font = font
toastLabel.textAlignment = .center;
toastLabel.text = message
toastLabel.alpha = 1.0
toastLabel.layer.cornerRadius = 10;
toastLabel.clipsToBounds = true
self.view.addSubview(toastLabel)
UIView.animate(withDuration: 4.0,
delay: 0.1,
options: .curveEaseOut,
animations: {
toastLabel.alpha = 0.0
}, completion: {(isCompleted) in
toastLabel.removeFromSuperview()
})
}
func getDate(sinceTime: Double) -> String {
let date = Date(timeIntervalSince1970: sinceTime)
let dateFormater = DateFormatter()
dateFormater.timeStyle = .short
dateFormater.dateStyle = .medium
let dateString = dateFormater.string(from: date)
return dateString
}
func calculateCellHeight(userPost: UserPosts) -> CGFloat {
var height: CGFloat = 0
let posts = userPost.posts
for post in posts {
switch post.pics.count {
case 1:
height += viewModel.oneBigImageHeight
case 2:
height += viewModel.twoSmallImagesHeight
case 3:
height += viewModel.threeImagesHeight
default:
height += viewModel.fourMoreImagesHeight
}
}
return height
}
func calculateHeaderHeight() -> CGFloat {
return viewModel.isOffLine ? UITableView.automaticDimension : 0
}
}
|
//
// LevelDataModel.swift
// Sopt-27th-HACKATHON-6th
//
// Created by ✨EUGENE✨ on 2020/11/22.
//
import Foundation
struct levelDataModel {
let id, levelNum: Int
let description: String
let foodType: Int
let levelName: String
}
|
//
// PostStudentInfoViewController.swift
// OnTheMap
//
// Created by Craig Vanderzwaag on 12/2/15.
// Copyright © 2015 blueHula Studios. All rights reserved.
//
import UIKit
class PostStudentInfoViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var urlTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let background = CAGradientLayer().turquoiseColor()
background.frame = self.view.bounds
self.view.layer.insertSublayer(background, atIndex: 0)
}
@IBAction func didTouchPostButton(sender: AnyObject) {
urlTextField.resignFirstResponder()
if (urlTextField.text!.containsString("http://") || urlTextField.text!.containsString("https://")){
UdacityClient.sharedInstance().udacityUser?.mediaURL = self.urlTextField.text!
if((UdacityClient.sharedInstance().isReachable) == false) {
let controller = UIAlertController.showAlertController("Network Unavailable", alertMessage: "Could not Post Location- Try Again")
dispatch_async(dispatch_get_main_queue()){
self.presentViewController(controller, animated: true, completion: nil)
}
} else {
UdacityClient.sharedInstance().postUserLocation(UdacityClient.sharedInstance().udacityUser!, completionHandler: { (result, error) -> Void in
if result != nil {
dispatch_async(dispatch_get_main_queue(), {
self.dismissViewControllerAnimated(true, completion: nil)
})
}
else{
dispatch_async(dispatch_get_main_queue(), {
let controller = UIAlertController.showAlertController("Darn it!", alertMessage: "Could not Post Location- Try Again")
self.presentViewController(controller, animated: true, completion: nil)
})
}
})
}
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.