text
stringlengths 8
1.32M
|
|---|
//
// DownloadTransactionCountOperation.swift
// monster-chase
//
// Created by Pabel Nunez Landestoy on 1/28/19.
// Copyright © 2019 Pocket Network. All rights reserved.
//
import Foundation
import PocketSwift
import BigInt
public enum DownloadTransactionCountOperationError: Error {
case responseParsing
}
public class DownloadTransactionCountOperation: AsynchronousOperation {
public var address: String
public var transactionCount: BigInt?
public init(address: String) {
self.address = address
super.init()
}
open override func main() {
guard let aionNetwork = PocketAion.shared?.defaultNetwork else {
self.error = DownloadTransactionCountOperationError.responseParsing
self.finish()
return
}
aionNetwork.eth.getTransactionCount(address: address, blockTag: nil, callback: { (error, result) in
if error != nil {
self.error = error
self.finish()
return
}
self.transactionCount = result
self.finish()
})
}
}
|
//
// CharacterCollectionViewCell.swift
// MarvelEssentials
//
// Created by Nigel Mestach on 29/11/2018.
// Copyright © 2018 Nigel Mestach. All rights reserved.
//
import UIKit
class CharacterCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var image: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
var position: Int?
}
|
//
// Cacheable.swift
// SwiftyCache
//
// Created by lihao on 16/5/21.
// Copyright © 2016年 Egg Swift. All rights reserved.
//
import Foundation
public protocol Cacheable {
associatedtype CacheType
func archive() -> NSData?
static func unarchive(data: NSData) -> CacheType?
}
|
//
// UserCell.swift
// SmartLock
//
// Created by Sam Davies on 21/11/2015.
// Copyright © 2015 Sam Davies. All rights reserved.
//
import UIKit
class UserCell: UITableViewCell {
@IBOutlet var name: UILabel!
@IBOutlet var email: UILabel!
@IBOutlet var addFriendButton: UIButton!
var user: User!
@IBAction func addFriend(sender: UIButton) {
User.addFriend(user.id).then {
user -> Void in
debugPrint("adding friend")
dispatch_async(dispatch_get_main_queue(), {
self.addFriendButton.enabled = false
})
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
func create(user: User) {
self.user = user
name.text = user.firstName + " " + user.lastName
email.text = user.email
}
}
|
//
// TimedRecord.swift
// Timer
//
// Created by Saga on 9/27/14.
// Copyright (c) 2014 Charles. All rights reserved.
//
import Foundation
import UIKit
class TimedRecord {
var tag: String!
var date: NSDate!
var seconds: Double!
var parent: TimedItem!
init(tag: String, date: NSDate, seconds: Double, parent: TimedItem) {
self.tag = tag
self.date = date
self.seconds = seconds
self.parent = parent
}
}
|
//
// DriverPageController.swift
// ShuttleServiceApp
//
// Created by Nikhil Prashar on 11/28/16.
// Copyright © 2016 Nikhil Prashar. All rights reserved.
//
import UIKit
class DriverPageController: UITableViewController {
var noofRowsInSection: [Int] = [1]
//var itemStore = ItemStore()
var regItemStore = RegisteredItemStore() //creates an instance of registeredItemStore
override func viewDidLoad() {
super.viewDidLoad()
}
//Returns number of sections in table view
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
//return RegisterItem.sectionBasedOntime.count
return 1
}
//Returns number of rows in sections
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
// return noofRowsInSection[section]
return regItemStore.allRegisteredItems.count + 2
}
//Function called when segue is initiated
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let vc = segue.destinationViewController as! InformationViewController //instantiating destination view controller
if (segue.identifier == "NavigateToInfo")
{ //Checking for segue identifier
if let row = tableView.indexPathForSelectedRow?.row
{ //transferring name,suid,address and time to destination view controller
let item = regItemStore.allRegisteredItems[row-2]
let selectedSuid = item.suid
let selectedTime = item.time
vc.suid = String(selectedSuid)
vc.time = selectedTime
var indexCount = -1
for regItem in regItemStore.allRegisteredItems
{
indexCount = indexCount + 1
if(selectedSuid == regItem.suid)
{
if(regItem.time == selectedTime)
{
vc.name = regItem.name
vc.address = regItem.address
break
}
}
}
}
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
print("indexpathrow: \(indexPath.row)")
if indexPath.row == 0
{ //For first defualt row
let hc = tableView.dequeueReusableCellWithIdentifier("HeadingCell", forIndexPath: indexPath) as! HeadingCell
hc.headingLabel.text = "Registrations"
return hc
}
else if indexPath.row == 1
{ //For second default row
let hc = tableView.dequeueReusableCellWithIdentifier("ItemHeadingCell", forIndexPath: indexPath) as! HeadingCell
hc.suid_heading.text = "SUID"
hc.time_heading.text = "TIME"
hc.suid_heading.font = UIFont.boldSystemFontOfSize(16)
hc.time_heading.font = UIFont.boldSystemFontOfSize(16)
return hc
}
//Adds rows to table view
let contentCell = tableView.dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: indexPath) as! ItemCell
contentCell.suid.text = String(regItemStore.allRegisteredItems[indexPath.row - 2].suid)
contentCell.time.text = regItemStore.allRegisteredItems[indexPath.row - 2].time
return contentCell
}
}
|
import SwiftUI
struct ContentView: View {
var body: some View {
Group {
Image(uiImage: UIImage(named:"Lenna.png")!).resizable()
.scaledToFit()
}
.maskedCameraBlur()
.frame(width: BlurredEdgesViewApp.imageBounds.width, height: BlurredEdgesViewApp.imageBounds.height)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
//
// CommentCell.swift
// GV24
//
// Created by HuyNguyen on 5/31/17.
// Copyright © 2017 admin. All rights reserved.
//
import UIKit
class CommentCell: CustomTableViewCell {
@IBOutlet weak var topLabelHeight: NSLayoutConstraint!
@IBOutlet weak var topLabel: UILabel!
@IBOutlet weak var content: UITextView!
@IBOutlet weak var userName: UILabel!
@IBOutlet weak var imageAvatar: UIImageView!
@IBOutlet weak var createAtLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
imageAvatar.layer.cornerRadius = imageAvatar.frame.size.width/2
imageAvatar.clipsToBounds = true
}
}
|
/**
* Copyright IBM Corporation 2018
*
* 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
/** Entity. */
public struct Entity {
/// The name of the entity.
public var entityName: String
/// The timestamp for creation of the entity.
public var created: String?
/// The timestamp for the last update to the entity.
public var updated: String?
/// The description of the entity.
public var description: String?
/// Any metadata related to the entity.
public var metadata: [String: JSON]?
/// Whether fuzzy matching is used for the entity.
public var fuzzyMatch: Bool?
/**
Initialize a `Entity` with member variables.
- parameter entityName: The name of the entity.
- parameter created: The timestamp for creation of the entity.
- parameter updated: The timestamp for the last update to the entity.
- parameter description: The description of the entity.
- parameter metadata: Any metadata related to the entity.
- parameter fuzzyMatch: Whether fuzzy matching is used for the entity.
- returns: An initialized `Entity`.
*/
public init(entityName: String, created: String? = nil, updated: String? = nil, description: String? = nil, metadata: [String: JSON]? = nil, fuzzyMatch: Bool? = nil) {
self.entityName = entityName
self.created = created
self.updated = updated
self.description = description
self.metadata = metadata
self.fuzzyMatch = fuzzyMatch
}
}
extension Entity: Codable {
private enum CodingKeys: String, CodingKey {
case entityName = "entity"
case created = "created"
case updated = "updated"
case description = "description"
case metadata = "metadata"
case fuzzyMatch = "fuzzy_match"
static let allValues = [entityName, created, updated, description, metadata, fuzzyMatch]
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
entityName = try container.decode(String.self, forKey: .entityName)
created = try container.decodeIfPresent(String.self, forKey: .created)
updated = try container.decodeIfPresent(String.self, forKey: .updated)
description = try container.decodeIfPresent(String.self, forKey: .description)
metadata = try container.decodeIfPresent([String: JSON].self, forKey: .metadata)
fuzzyMatch = try container.decodeIfPresent(Bool.self, forKey: .fuzzyMatch)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(entityName, forKey: .entityName)
try container.encodeIfPresent(created, forKey: .created)
try container.encodeIfPresent(updated, forKey: .updated)
try container.encodeIfPresent(description, forKey: .description)
try container.encodeIfPresent(metadata, forKey: .metadata)
try container.encodeIfPresent(fuzzyMatch, forKey: .fuzzyMatch)
}
}
|
//
// UICollectionViewCell+.swift
// MEOKit
//
// Created by Mitsuhau Emoto on 2019/01/14.
// Copyright © 2019 Mitsuharu Emoto. All rights reserved.
//
import UIKit
public extension MeoExtension where T: UICollectionViewCell {
/// 自身をaddしたUICollectionViewを取得する
var collectionView: UICollectionView? {
return self.base.parent(type: UICollectionView.self)
}
/// 自身のIndexPathを取得する
var indexPath: IndexPath? {
guard let cv: UICollectionView = self.collectionView else {
return nil
}
return cv.indexPath(for: self.base)
}
/// 自身を reloadItems() する
///
/// - Returns: 成功したらtrue(例外はキャッチできない).
@discardableResult
func reload() -> Bool{
guard
let cv: UICollectionView = self.collectionView,
let ip = cv.indexPath(for: self.base) else {
return false
}
var result: Bool = false
let sections: Int = cv.numberOfSections
let rows: Int = cv.numberOfItems(inSection: sections)
let hasIndexPath: Bool = (ip.section < sections) && (ip.row < rows)
if cv.indexPathsForVisibleItems.contains(ip) && hasIndexPath{
cv.reloadItems(at: [ip])
result = true
}
return result
}
}
|
//
// MovieMenu.swift
// playr
//
// Created by Michel Balamou on 5/21/18.
// Copyright © 2018 Michel Balamou. All rights reserved.
//
import Foundation
class MovieMenu: UIViewController{
var categories = ["Viewed", "Movies", "Series"]
var viewRow = 0
var movieRow = 1
var seriesRow = 2
var net = NetworkModel()
@IBOutlet weak var categoryTable: UITableView!
//----------------------------------------------------------------------
// METHODS
//----------------------------------------------------------------------
override func viewDidLoad()
{
super.viewDidLoad()
let dummyViewHeight = CGFloat(40)
// Disable flotable headers:
// https://stackoverflow.com/questions/1074006/is-it-possible-to-disable-floating-headers-in-uitableview-with-uitableviewstylep
self.categoryTable.tableHeaderView = UIView(frame: CGRect(0, 0, self.categoryTable.bounds.size.width, dummyViewHeight))
self.categoryTable.contentInset = UIEdgeInsetsMake(-dummyViewHeight, 0, 0, 0)
net.displayInfo = self.openSeriesInfo
net.play = self.openVideoPlayer
net.loadViewed(completion: self.reloadView)
net.loadMovies(completion: self.reloadMovies)
net.loadSeries(completion: self.reloadSeries)
}
// MARK: On completion
func reloadView(err: String)
{
let viewedRow = categoryTable.cellForRow(at: IndexPath(row:0, section: viewRow)) as! ViewedRow
viewedRow.collectionCell.reloadData()
}
func reloadMovies(err: String)
{
let categoryRow = categoryTable.cellForRow(at: IndexPath(row:0, section: movieRow)) as! CategoryRow
categoryRow.collectionCell.reloadData()
}
func reloadSeries(err: String)
{
let categoryRow = categoryTable.cellForRow(at: IndexPath(row:0, section: seriesRow)) as! CategoryRow
categoryRow.collectionCell.reloadData()
}
override func viewDidAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
}
// STOP ROTATION ANIMATION
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)
{
coordinator.animate(alongsideTransition: nil) { (_) in
UIView.setAnimationsEnabled(true)
}
UIView.setAnimationsEnabled(false)
super.viewWillTransition(to: size, with: coordinator)
}
// MARK: OPEN VIDEO PLAYER
func openVideoPlayer(_ viewed: Viewed)
{
let videoPlayer = self.storyboard?.instantiateViewController(withIdentifier: "ViewController") as! ViewController
videoPlayer.url = viewed.URL
videoPlayer.stoppedAt = viewed.stoppedAt ?? 0
videoPlayer.duration = viewed.duration
self.navigationController?.pushViewController(videoPlayer, animated: true)
}
// MARK: DISPLAY SERIES INFO
func openSeriesInfo(_ viewed: Any){
if let ep = viewed as? Episode,
let series = ep.mainSeries
{
let seriesController = self.storyboard?.instantiateViewController(withIdentifier: "SeriesController") as! SeriesController
seriesController.series_id = series.series_id
seriesController.net = net
self.navigationController?.pushViewController(seriesController, animated: true)
}
else if let series = viewed as? Series
{
let seriesController = self.storyboard?.instantiateViewController(withIdentifier: "SeriesController") as! SeriesController
seriesController.series_id = series.series_id
seriesController.net = net
self.navigationController?.pushViewController(seriesController, animated: true)
}
else if let movie = viewed as? Movie
{
return
}
}
}
extension MovieMenu: UITableViewDataSource, UITableViewDelegate
{
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return categories[section]
}
func numberOfSections(in tableView: UITableView) -> Int {
return categories.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return 148
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
if indexPath.section == viewRow {
let viewedCell = tableView.dequeueReusableCell(withIdentifier: "ViewedRow") as! ViewedRow
viewedCell.net = net
return viewedCell
}
else
{
let categoryCell = tableView.dequeueReusableCell(withIdentifier: "CategoryRow") as! CategoryRow
categoryCell.net = net
if indexPath.section == movieRow {
categoryCell.rowType = "Movie"
}
else if indexPath.section == seriesRow {
categoryCell.rowType = "Series"
}
return categoryCell
}
}
}
|
//
// RoundedButton.swift
// Animal House
//
// Created by Roy Geagea on 8/1/19.
// Copyright © 2019 Roy Geagea. All rights reserved.
//
import SwiftUI
struct RoundedButton : View {
let title: String!
let action: () -> Void
var isDisabled: Bool = false
var isLoading: Bool = false
init(title: String, isDisabled: Bool, isLoading: Bool = false, action: @escaping () -> Void) {
self.title = title
self.action = action
self.isDisabled = isDisabled
self.isLoading = isLoading
}
var body: some View {
Button(action: self.action) {
ZStack(alignment: .center) {
HStack {
Spacer()
Text(self.title)
.font(.headline)
.foregroundColor(Color.white)
.padding(.horizontal, 50)
.padding(.vertical, 10.0)
Spacer()
}
if isLoading {
RGActivityIndicator(isAnimating: .constant(true), style: .large)
}
}
}
.background(isDisabled || isLoading ? Color.gray : Color.green)
.cornerRadius(8.0)
.frame(height: 48)
.padding(.horizontal, 24)
.disabled(self.isDisabled || isLoading)
}
}
#if DEBUG
struct RoundedButton_Previews: PreviewProvider {
static var previews: some View {
RoundedButton(title: "Preview", isDisabled: false, action: {})
}
}
#endif
|
//
// StatusBarView_Safari.swift
// ReaderTranslator
//
// Created by Viktor Kushnerov on 10/5/19.
// Copyright © 2019 Viktor Kushnerov. All rights reserved.
//
import SwiftUI
struct StatusBarView_Safari: View {
@ObservedObject var store = Store.shared
var body: some View {
Group {
#if os(macOS)
// Text("Safari plugin: \(store.canSafariSendSelectedText ? "on" : "off")")
// .foregroundColor(store.canSafariSendSelectedText ? .green : .red)
// .onTapGesture { self.store.canSafariSendSelectedText.toggle() }
#endif
}
}
}
|
//
// GradientView.swift
// Weather
//
// Created by Alexsandre kikalia on 2/6/21.
//
import UIKit
class GradientView: UIView{
var gradientLayer: CAGradientLayer?
var top = UIColor.white
var bottom = UIColor.white
func setGradientBG(top: UIColor?, bottom: UIColor?) {
if let top = top{
if let bottom = bottom{
self.top = top
self.bottom = bottom
gradientLayer = CAGradientLayer()
gradientLayer!.colors = [top.cgColor, bottom.cgColor]
gradientLayer!.locations = [0.0, 1.0]
gradientLayer!.frame = self.bounds
// self.backgroundColor = .clear
self.layer.insertSublayer(gradientLayer!, at:0)
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
self.updateGradient(nil, nil)
}
func updateGradient(_ top: UIColor?,_ bottom: UIColor?){
if let gradient = gradientLayer{
if let top = top?.cgColor{
if let bottom = bottom?.cgColor{
gradient.colors = [top, bottom]
}
}
gradient.frame = self.bounds
}
}
}
|
//
// RequestStatusCellLayout.swift
// consumer
//
// Created by Vladislav Zagorodnyuk on 3/9/17.
// Copyright © 2017 Human Ventures Co. All rights reserved.
//
import Foundation
/// Used for a status layout type where a width must be defined to set correct insets.
struct RequestStatusCellProtocol {
/// Layout for status.
var layout: Layout
/// Width of status in layout.
var width: CGFloat
}
/// Layout to assemble a request cell.
struct RequestStatusCellLayout: Layout {
/// Image for request.
var image: Layout
/// Name of user.
var name: Layout
/// Request Info layout.
var info: Layout
init(image: Layout, name: Layout, info: Layout) {
self.image = image
self.name = name
self.info = info
}
/// Will layout image and content for request cell..
///
/// - Parameter rect: Rect of main content. Image will use the top half of the rect and other info will be near the bottom.
mutating func layout(in rect: CGRect) {
let imageViewLayout = SquareLayout(content: image).withInsets(bottom: 5)
let infoContents: [Layout] = [name, info]
let infoLayout = VerticalLayout(contents: infoContents, verticalSeperatingSpace: 0).withInsets(top: 10, bottom: 0)
var layout = VerticalLayout(contents: [imageViewLayout, infoLayout], verticalSeperatingSpace: 0).withInsets(top: 10, bottom: 20)
layout.layout(in: rect)
}
}
|
//
// UserVM.swift
// ScooterRental
//
// Created by ios on 08/10/18.
// Copyright © 2018 ios28. All rights reserved.
//
import Foundation
class UserVM {
public static let shared = UserVM()
private init() {}
var userDetails: User!
func signup(dict: JSONDictionary, response: @escaping responseCallBack) {
APIManager.signup(dict: dict, successCallback: { (responseDict) in
let message = responseDict[APIKeys.kMessage] as? String ?? APIManager.OTHER_ERROR
response(message, nil)
}) { (errorReason, error) in
response(nil, APIManager.errorForNetworkErrorReason(errorReason: errorReason!))
}
}
func login(dict: JSONDictionary, response: @escaping responseCallBack) {
APIManager.login(dict: dict, successCallback: { (responseDict) in
let message = responseDict[APIKeys.kMessage] as? String ?? APIManager.OTHER_ERROR
self.parseLoginData(response: responseDict)
response(message, nil)
}) { (errorReason, error) in
response(nil, APIManager.errorForNetworkErrorReason(errorReason: errorReason!))
}
}
func forgotPassword(email: String, response: @escaping responseCallBack) {
APIManager.forgotPassword(email: email, successCallback: { (responseDict) in
let message = responseDict[APIKeys.kMessage] as? String ?? APIManager.OTHER_ERROR
response(message, nil)
}) { (errorReason, error) in
response(nil, APIManager.errorForNetworkErrorReason(errorReason: errorReason!))
}
}
func getProfile(response: @escaping responseCallBack) {
APIManager.getProfile(successCallback: { (responseDict) in
let message = responseDict[APIKeys.kMessage] as? String ?? APIManager.OTHER_ERROR
self.parseLoginData(response: responseDict, isGet: true)
response(message, nil)
}) { (errorReason, error) in
response(nil, APIManager.errorForNetworkErrorReason(errorReason: errorReason!))
}
}
func updateProfile(dict: JSONDictionary, response: @escaping responseCallBack) {
APIManager.updateProfile(dict: dict, successCallback: { (responseDict) in
let message = responseDict[APIKeys.kMessage] as? String ?? APIManager.OTHER_ERROR
self.parseLoginData(response: responseDict, isGet: true)
response(message, nil)
}) { (errorReason, error) in
response(nil, APIManager.errorForNetworkErrorReason(errorReason: errorReason!))
}
}
}
|
class Solution {
func isInterleave(_ s1: String, _ s2: String, _ s3: String) -> Bool {
let s1 = Array(s1), s2 = Array(s2), s3 = Array(s3)
guard s1.count + s2.count == s3.count else { return false }
var result = [Bool](repeating: false, count: s2.count + 1)
result[0] = true
for i in 0...s1.count {
for j in 0...s2.count {
if i > 0 {
result[j] = result[j] && s1[i - 1] == s3[i - 1 + j]
}
if j > 0 {
result[j] = result[j] || (result[j - 1] && s2[j - 1] == s3[i - 1 + j])
}
}
}
return result.last ?? false
}
}
|
//
// webview.swift
// ETBAROON
//
// Created by imac on 10/12/17.
// Copyright © 2017 IAS. All rights reserved.
//
import UIKit
class webview: UIViewController {
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
getVideo(videoCode:"http://rshankar.com/swift-webview-demo/")
// Do any additional setup after loading the view.
}
func getVideo(videoCode:String) {
let url = URL(string:"\(videoCode)")
webView.loadRequest(URLRequest(url: url!))
}
}
|
//
// CalculatorViewController.swift
// HoursCalculator
//
// Created by Sean McCue on 11/27/14.
// Copyright (c) 2014 Sean McCue. All rights reserved.
//
import UIKit
class CalculatorViewController: UIViewController, UITextViewDelegate {
//instance variables
var numString: String = ""
var numDouble: Double = 0.0
var logHistory = ""
let calculator = SMDurarionCalculator()
var operatorOn = false
var plusOperatorOn = false
var minusOperatorOn = false
var multOperatorOn = false
var equalsOperatorOn = false
var lastNumberStr: String = ""
var currentNumberStr: String = ""
var newNumbers = false
var operators:[Bool] = []
//IBOulet references
@IBOutlet var topView: UIView!
@IBOutlet var numberWindowLabel: UILabel!
@IBOutlet var numberpadeButtons: [UIButton]!
@IBOutlet var mathSymbolLabel: UILabel!
@IBOutlet var logTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
operators = [plusOperatorOn, minusOperatorOn, multOperatorOn]
//set label to resize font based on characters
numberWindowLabel.adjustsFontSizeToFitWidth = true
//Set up all inital border styles of buttons
for btn in numberpadeButtons{
btn.layer.borderWidth = 0.3
btn.layer.borderColor = UIColor(red: 74.0/255.0, green: 71.0/255.0, blue: 71.0/255.0, alpha: 0.5).CGColor
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Hide status bar
override func prefersStatusBarHidden() -> Bool {
return true
}
//When a number is pressed
@IBAction func numberPressed(sender: AnyObject) {
//Reset all border colors and widths back to normal
for btn in numberpadeButtons{
btn.layer.borderColor = UIColor(red: 74.0/255.0, green: 71.0/255.0, blue: 71.0/255.0, alpha: 0.5).CGColor
btn.layer.borderWidth = 0.3
//check for "AC" title button to change to "C"
if(btn.titleLabel?.text == "AC"){
btn.titleLabel?.text = "C"
}
}
//grab reference to button touched
var button: AnyObject = sender
//no operator has been touched
operatorOn = false
//set title of button being pressed to white
button.setTitleColor(UIColor.whiteColor(), forState:UIControlState.Highlighted)
//which button was pressed? + ADD character limit of 9 in the window
if(countElements(numString) < 10){
switch(button.tag){
case(0):
println("0")
numString += "0"
self.updateNumberView()
case(1):
println("1")
numString += "1"
self.updateNumberView()
case(2):
println("2")
numString += "2"
self.updateNumberView()
case(3):
println("3")
numString += "3"
self.updateNumberView()
case(4):
println("4")
numString += "4"
self.updateNumberView()
case(5):
println("5")
numString += "5"
self.updateNumberView()
case(6):
println("6")
numString += "6"
self.updateNumberView()
case(7):
println("7")
numString += "7"
self.updateNumberView()
case(8):
println("8")
numString += "8"
self.updateNumberView()
case(9):
println("9")
numString += "9"
self.updateNumberView()
default:
println("default")
}
}
}
//update UI of window after a number is pressed
func updateNumberView(){
//update window based on how many numbers are needing to be displayed to handle ":" placement
switch(countElements(numString)){
case(0):
println("0")
numberWindowLabel.text = "0:0" + numString
case(1):
println("1")
numberWindowLabel.text = "0:0" + numString
case(2):
println("2")
numberWindowLabel.text = "0:" + numString
default:
println("default")
var count = countElements(numString)
let newStrLeftColon: String = (numString as NSString).substringToIndex((count - 2))
let newStrRightColon: String = (numString as NSString).substringFromIndex((count-2))
numberWindowLabel.text = newStrLeftColon + ":" + newStrRightColon
}
}
//Plus operator pressed
@IBAction func addDuration(sender: AnyObject) {
plusOperatorOn = true
minusOperatorOn = false
multOperatorOn = false
self.updateNumberKeypadUI("+")
}
//Minus operator pressed
@IBAction func minusDuration(sender: AnyObject) {
plusOperatorOn = false
minusOperatorOn = true
multOperatorOn = false
self.updateNumberKeypadUI("-")
}
//Multiplication operator pressed
@IBAction func multiplyDuration(sender: AnyObject) {
plusOperatorOn = false
minusOperatorOn = false
multOperatorOn = true
self.updateNumberKeypadUI("*")
}
//Clear number window and reset values
@IBAction func clearNumbers(sender: AnyObject) {
numString = ""
numberWindowLabel.text = "0:00"
mathSymbolLabel.text = ""
logHistory = ""
logTextView.text = ""
lastNumberStr = ""
//change all other button to normal border outlines
for btn in numberpadeButtons{
btn.layer.borderColor = UIColor(red: 74.0/255.0, green: 71.0/255.0, blue: 71.0/255.0, alpha: 0.5).CGColor
btn.layer.borderWidth = 0.3
//When user clears, change back to "AC"
if(btn.titleLabel?.text == "C"){
btn.titleLabel?.text = "AC"
}
}
}
//Equal button pressed
@IBAction func equalsAction(sender: AnyObject) {
mathSymbolLabel.text = ""
if(plusOperatorOn){
if(lastNumberStr == ""){
lastNumberStr = numberWindowLabel.text!;
if(!operatorOn){
logHistory += numberWindowLabel.text! + " + "
updateLogView()
}
//else grab the second value to be added
}else{
currentNumberStr = numberWindowLabel.text!
numberWindowLabel.text = calculator.addTwoDurations(lastNumberStr, operandTwo:
currentNumberStr)
if(!operatorOn){
logHistory += currentNumberStr + " = " + numberWindowLabel.text!
//Don't forget the last value before adding another if user adding multile values
lastNumberStr = numberWindowLabel.text!
updateLogView()
}
}
}else if(minusOperatorOn){
if(lastNumberStr == ""){
lastNumberStr = numberWindowLabel.text!;
if(!operatorOn){
logHistory += numberWindowLabel.text! + " - "
updateLogView()
}
//else grab the second value to be added
}else{
currentNumberStr = numberWindowLabel.text!
numberWindowLabel.text = calculator.subtractTwoDurations(lastNumberStr, operandTwo:
currentNumberStr)
if(!operatorOn){
logHistory += currentNumberStr + " = " + numberWindowLabel.text!
//Don't forget the last value before adding another if user adding multile values
lastNumberStr = numberWindowLabel.text!
updateLogView()
}
}
}else if(multOperatorOn){
if(lastNumberStr == ""){
lastNumberStr = numberWindowLabel.text!;
if(!operatorOn){
logHistory += numberWindowLabel.text! + " - "
updateLogView()
}
//else grab the second value to be added
}else{
currentNumberStr = numberWindowLabel.text!
numberWindowLabel.text = calculator.multiplyTwoDurations(lastNumberStr, operandTwo:
currentNumberStr)
if(!operatorOn){
logHistory += currentNumberStr + " = " + numberWindowLabel.text!
//Don't forget the last value before adding another if user adding multile values
lastNumberStr = numberWindowLabel.text!
updateLogView()
}
}
}
lastNumberStr = ""
}
//Handle UI for log view of history
func updateLogView(){
operatorOn = true
logTextView.text = logHistory
numString = ""
}
//Handle UI for log view of history
func updateNumberKeypadUI(operators:String){
//If first number entered into the window grab it
if(lastNumberStr == ""){
lastNumberStr = numberWindowLabel.text!;
if(!operatorOn){
logHistory += numberWindowLabel.text! + " + "
updateLogView()
}
//else grab the second value to be added
}else{
currentNumberStr = numberWindowLabel.text!
if(operators == "+"){
//addition
//set "+" symbol in window
mathSymbolLabel.text = "+"
numberWindowLabel.text = calculator.addTwoDurations(lastNumberStr, operandTwo:
currentNumberStr)
}
else if(operators == "-"){
//subtraction
//set "+" symbol in window
mathSymbolLabel.text = "-"
numberWindowLabel.text = calculator.subtractTwoDurations(lastNumberStr, operandTwo:
currentNumberStr)
}
else{
//multiplication
//set "+" symbol in window
mathSymbolLabel.text = "*"
numberWindowLabel.text = calculator.multiplyTwoDurations(lastNumberStr, operandTwo:
currentNumberStr)
}
if(!operatorOn){
logHistory += currentNumberStr + " = " + numberWindowLabel.text!
//Don't forget the last value before adding another if user adding multile values
lastNumberStr = numberWindowLabel.text!
updateLogView()
}
}
for btn in numberpadeButtons{
//check for "+" button and outline button so it stands out
if(btn.titleLabel?.text == "+"){
btn.layer.borderColor = UIColor.blackColor().CGColor
btn.layer.borderWidth = 2
}
//Keep button as "C"
if(btn.titleLabel?.text == "AC"){
btn.titleLabel?.text = "C"
}
}
}
}
|
//
// UserDefaults + extension.swift
// MusicPlayer
//
// Created by Vlad Tkachuk on 27.05.2020.
// Copyright © 2020 Vlad Tkachuk. All rights reserved.
//
import Foundation
extension UserDefaults {
static let favoriteTrackKey = "favoriteTrackKey"
func getSavedTracks() -> [SearchViewModel.Cell] {
let defaults = UserDefaults.standard
guard let savedTracks = defaults.object(forKey: UserDefaults.favoriteTrackKey) as? Data else { return [] }
guard let decodedTracks = try? NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(savedTracks) as? [SearchViewModel.Cell] else { return [] }
return decodedTracks
}
func saveTracks(track: [SearchViewModel.Cell]) {
if let savedData = try? NSKeyedArchiver.archivedData(withRootObject: track, requiringSecureCoding: false) {
UserDefaults.standard.set(savedData, forKey: UserDefaults.favoriteTrackKey)
}
}
}
|
//
// ConsoleLogger.swift
// CouchbaseLite
//
// Copyright (c) 2018 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/// Console logger for writing log messages to the system console.
/// Log domain options that can be enabled in the console logger.
public struct LogDomains: OptionSet {
/// Raw value.
public let rawValue: Int
/// Constructor with the raw value.
public init(rawValue: Int) {
self.rawValue = rawValue
}
/// All domains.
public static let all = LogDomains(rawValue: Int(LogDomain.all.rawValue))
/// Database domain.
public static let database = LogDomains(rawValue: Int(LogDomain.database.rawValue))
/// Database domain.
public static let query = LogDomains(rawValue: Int(LogDomain.query.rawValue))
/// Replicator domain.
public static let replicator = LogDomains(rawValue: Int(LogDomain.replicator.rawValue))
/// Network domain.
public static let network = LogDomains(rawValue: Int(LogDomain.network.rawValue))
}
public class ConsoleLogger {
/// The minimum log level of the log messages to be logged. The default log level for
/// console logger is warning.
public var level: LogLevel = .warning {
didSet {
CBLDatabase.log().console.level = CBLLogLevel(rawValue: UInt(level.rawValue))!
}
}
/// The set of log domains of the log messages to be logged. By default, the log
/// messages of all domains will be logged.
public var domains: LogDomains = .all {
didSet {
CBLDatabase.log().console.domains = CBLLogDomain(rawValue: UInt(domains.rawValue))
}
}
// MARK: Internal
init() { }
}
|
//
// AddSkillSectionNetworking.swift
// OSOM_app
//
// Created by Miłosz Bugla on 18.12.2017.
//
import Foundation
import SwiftyJSON
import Alamofire
protocol AddSkillsSectionNetworking: class {
weak var delegate: AddSkillsSectionNetworkingDelegate? { get set }
func setAddSkillsSectionData(parameters: [String: Any])
func updateWorkData(parameters: [String : Any])
}
protocol AddSkillsSectionNetworkingDelegate: class {
func unknownErrorOccured()
func noInternetConnection()
func success(_ json: JSON)
}
final class AddSkillsSectionNetworkingImpl: BaseNetworking {
weak var delegate: AddSkillsSectionNetworkingDelegate?
override func handleUnknownError() {
delegate?.unknownErrorOccured()
}
override func handleResponseNoInternetConnection() {
delegate?.noInternetConnection()
}
override func handleResponseBadRequest(json: JSON?) {
delegate?.unknownErrorOccured()
}
override func handleResponseSuccess(json: JSON?) {
if let json = json {
delegate?.success(json)
} else {
delegate?.unknownErrorOccured()
}
}
}
extension AddSkillsSectionNetworkingImpl: AddSkillsSectionNetworking {
func setAddSkillsSectionData(parameters: [String : Any]) {
makeRequest(request: getRequest(parameters))
}
func updateWorkData(parameters: [String : Any]) {
makeRequest(request: getRequest(parameters, method: .put))
}
fileprivate func getRequest(_ parameters: [String: Any]? = nil, method: HTTPMethod = .post) -> HTTPRequest {
return HTTPRequest(url: getUrl(), method: method, parameters: parameters, encoding: JSONEncoding.default)
}
fileprivate func getUrl() -> String {
return Endpoints.baseUrl + Endpoints.section
}
}
|
//
// Delegates.swift
// Westeros
//
// Created by JOSE LUIS BUSTOS ESTEBAN on 18/7/17.
// Copyright © 2017 Keepcoding. All rights reserved.
//
import UIKit
final class Delegates {
static func housesDelegate ( model: [House]) -> ArrayTableViewDelegate<House>{
// Creamos el objeto y la cluasura a ejecutar
let del = ArrayTableViewDelegate(model: model, delegateMaker: {(house, IndexPath, UITableView) -> UIViewController in
let vc = HouseViewController(model: house)
return vc
})
return del
}
static func SeasonsDelegate ( model: [Season]) -> ArrayTableViewDelegate<Season>{
// Creamos el objeto y la cluasura a ejecutar
let del = ArrayTableViewDelegate(model: model, delegateMaker: {(season, IndexPath, UITableView) -> UIViewController in
let vc = EpisodesTableViewController.init(modelo: season.getSortedEpisodes())
return vc
})
return del
}
static func PersonsDelegate ( model: [Person]) -> ArrayTableViewDelegate<Person>{
// Creamos el objeto y la cluasura a ejecutar
let del = ArrayTableViewDelegate(model: model, delegateMaker: {(person, IndexPath, UITableView) -> UIViewController in
let vc = CharacterViewController.init(model: person)
return vc
})
return del
}
}
|
import Foundation
import Alamofire
class PhotosService {
static var shared = PhotosService()
func fetchPhotos(page: Int, completion: @escaping (Result<PagingResponce<Photo>, AFError>) -> ()) {
AF.request("\(ApiConstants.baseApiUrl)photo/type?page=\(page)")
.validate()
.responseDecodable(of: PagingResponce<Photo>.self) { completion($0.result) }
}
func uploadPhoto(photo: PhotoUploadModel,
completion: @escaping (Result<PhotoUploadModelResponce, AFError>) -> ()) {
AF.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(photo.photo.jpegData(compressionQuality: 1),
withName: "photo",
fileName: "image.jpeg",
mimeType: "image/jpeg")
for (key, value) in ["name": photo.name, "typeId": photo.typeId] {
multipartFormData.append(value.data(using: String.Encoding.utf8), withName: key)
}
}, to: "\(ApiConstants.baseApiUrl)photo")
.validate()
.responseDecodable(of: PhotoUploadModelResponce.self,
completionHandler: { completion($0.result) })
}
}
|
//
// RepositoryManagedObject+CoreDataProperties.swift
// SCTestTask
//
// Created by Aleksey Kornienko on 20/05/2018.
// Copyright © 2018 Aleksey Kornienko. All rights reserved.
//
//
import Foundation
import CoreData
extension RepositoryManagedObject {
@nonobjc public class func fetchRequest() -> NSFetchRequest<RepositoryManagedObject> {
return NSFetchRequest<RepositoryManagedObject>(entityName: "RepositoryManagedObject")
}
@NSManaged public var id: Int64
@NSManaged public var name: String
@NSManaged public var fullName: String
@NSManaged public var repoDescription: String?
@NSManaged public var forksCount: Int32
@NSManaged public var createdDate: NSDate
@NSManaged public var updatedDate: NSDate
@NSManaged public var language: String?
@NSManaged public var license: LicenseManagedObject?
}
extension RepositoryManagedObject: ManagedObjectProtocol {
typealias Entity = Repository
func toEntity() -> Repository? {
return Repository(
id: Int(id),
name: name,
fullName: fullName,
description: repoDescription,
license: license?.toEntity(),
created: createdDate as Date,
updated: updatedDate as Date,
language: language
)
}
}
extension Repository: ManagedObjectConvertible {
typealias ManagedObject = RepositoryManagedObject
func toManagedObject(in context: NSManagedObjectContext) -> RepositoryManagedObject? {
guard let entity = NSEntityDescription.entity(forEntityName: "RepositoryManagedObject", in: context) else {
return nil
}
let repository = RepositoryManagedObject(entity: entity, insertInto: context)
repository.id = Int64(self.id)
repository.name = self.name
repository.fullName = self.fullName
repository.repoDescription = self.description
repository.forksCount = Int32(self.forksCount)
repository.createdDate = self.created as NSDate
repository.updatedDate = self.updated as NSDate
repository.language = self.language
repository.license = self.license?.toManagedObject(in: context)
return repository
}
}
|
//
// DetailGarmentPresenter.swift
// MyWardrobe
//
// Created by Tim Johansson on 2018-12-08.
// Copyright © 2018 Tim Johansson. All rights reserved.
//
import Foundation
import UIKit
class DetailGarmentPresenter: DetailGarmentPresenterProtocol {
var interactor: DetailGarmentInteractorInputProtocol?
var view: DetailGarmentViewProtocol?
var wireframe: DetailGarmentWireFrameProtocol?
var garment: Garment?
func viewDidLoad() {
view?.showGarmentDetail(with: garment!)
}
func backButtonPressed(from view: UIViewController) {
wireframe?.goBackToAllGarmentsListView(from: view)
}
func removeGarment(garment: Garment) {
interactor?.removeGarment(garment: garment)
NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: "clothesListChanged"), object: nil))
}
}
|
//
// AppDelegate.swift
// MovieSearch
//
// Created by Jordan Bryant on 9/25/20.
// Copyright © 2020 Jordan Bryant. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//Instantiating shared instance and loading favorite movies from memory
let movieController = MovieController.shared
movieController.loadFromPersistentStore()
return true
}
}
|
//
// WalletBalanceHistoryCell.swift
// WavesWallet-iOS
//
// Created by Pavel Gubin on 4/30/18.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import UIKit
import Extensions
private enum Constants {
static let height: CGFloat = 56
}
final class WalletHistoryCell: UITableViewCell, NibReusable {
typealias Model = Void
@IBOutlet private var viewContainer: UIView!
@IBOutlet private var titleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
viewContainer.addTableCellShadowStyle()
setupLocalization()
}
class func cellHeight() -> CGFloat {
return Constants.height
}
}
// MARK: ViewConfiguration
extension WalletHistoryCell: ViewConfiguration {
func update(with model: Void) {
titleLabel.text = Localizable.Waves.Wallet.Label.viewHistory
}
}
// MARK: Localization
extension WalletHistoryCell: Localization {
func setupLocalization() {
titleLabel.text = Localizable.Waves.Wallet.Label.viewHistory
}
}
|
//
// StoreMapService.swift
// ToDoList
//
// Created by njliu on 1/26/15.
// Copyright (c) 2015 Naijia Liu. All rights reserved.
//
import Foundation
class StoreMapService {
private var storeMarkers = [StoreMarker]()
private let mapView: GMSMapView
init(mapView: GMSMapView) {
self.mapView = mapView
}
func fetchNearbyStores() {
let coordinate = mapView.camera.target
let radius = getMapVisibleRegionRadius()
// let mapService = MapService()
// mapService.fetchStores(coordinate, radius:radius) { results in
// for result: NearBySearchResult in results.reverse() {
// self.createStoreMarker(mapView, result: result)
// }
// }
let storeService = StoreService()
storeService.fetchStores(coordinate, radius: radius) {stores in
for store in stores {
self.drawStoreMarker(store)
}
}
}
private func getMapVisibleRegionRadius() -> Double {
let region = mapView.projection.visibleRegion()
// let verticalDistance = GMSGeometryDistance(region.farLeft, region.nearLeft)
// let horizontalDistance = GMSGeometryDistance(region.farLeft, region.farRight)
// return max(horizontalDistance, verticalDistance) * 0.5
return max(
abs(region.farLeft.latitude - region.nearRight.latitude),
abs(region.farLeft.longitude - region.nearRight.longitude))
* 0.5
}
private func drawStoreMarker(store: Store){
// if result is already exists in the markers, move the related marker to the end
if let existingMarkerIndex = storeMarkers.find({$0.store.storeNo == store.storeNo}) {
let existingMarker = storeMarkers.removeAtIndex(existingMarkerIndex)
storeMarkers.append(existingMarker)
return
}
// otherwise, create a new marker
let marker = StoreMarker(store: store)
marker.map = mapView
storeMarkers.append(marker)
// check marker array is full
let maxDisplayedMarker = 30
if (storeMarkers.count > maxDisplayedMarker){
let removedMarker = storeMarkers.removeAtIndex(0)
removedMarker.map = nil
}
}
}
|
// ItemsViewController.swift
// Copyright (c) 2010-2015 Bill Weinman. All rights reserved.
import UIKit
class ItemsViewController: UITableViewController {
var rssdb : RSSDB!
var feedID : NSNumber!
var feedRecord : Dictionary<NSObject, AnyObject>?
var itemRowIDs : NSArray?
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tableView.rowHeight = 55.0
rssdb.deleteOldItems(feedID)
loadFeedRecord()
if let title = feedRecord?[kRSSDB.feedTitle] as! String? {
self.title = title
} else {
self.title = "Feed"
}
}
override func viewDidLoad() {
super.viewDidLoad()
loadFeed()
self.refreshControl = UIRefreshControl()
self.refreshControl?.tintColor = RSSDefaultTint
self.refreshControl?.backgroundColor = UIColor(white: 0.75, alpha: 0.25)
self.refreshControl?.addTarget(self, action: "doRefresh:", forControlEvents: UIControlEvents.ValueChanged)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "DetailSegue" {
//let detailViewController = segue.destinationViewController.topViewController as! DetailViewController
let detailViewController = DetailViewController ()
let path = self.tableView.indexPathForSelectedRow
let itemRec = rssdb.getItemRow(itemRowIDs![path!.row] as! NSNumber) as NSDictionary
detailViewController.detailItem = (itemRec[kRSSDB.itemURL] as! String)
detailViewController.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
detailViewController.navigationItem.leftItemsSupplementBackButton = true
detailViewController.primaryVC = self.parentViewController
// set display mode for iPad
if self.splitViewController?.displayMode == UISplitViewControllerDisplayMode.PrimaryOverlay {
let svc = self.splitViewController
svc?.preferredDisplayMode = UISplitViewControllerDisplayMode.PrimaryHidden
}
}
}
// MARK: Table view
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
itemRowIDs = rssdb.getItemIDs(feedID)
return itemRowIDs!.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: indexPath)
// Get the feed item
let itemID = itemRowIDs![indexPath.row] as! NSNumber
let thisFeedItem = rssdb.getItemRow(itemID)
// Clever variable font size trick
let systemFontSize = UIFont.labelFontSize()
let headFontSize = systemFontSize * 0.9
let smallFontSize = systemFontSize * 0.8
let widthOfCell = tableView.rectForRowAtIndexPath(indexPath).size.width - 40.0
if let itemText = thisFeedItem[kRSSDB.itemTitle] as? String {
cell.textLabel?.numberOfLines = 2
if itemText.sizeWithAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(headFontSize)]).width > widthOfCell {
cell.textLabel?.font = UIFont.boldSystemFontOfSize(smallFontSize)
} else {
cell.textLabel?.font = UIFont.boldSystemFontOfSize(headFontSize)
}
cell.textLabel?.text = itemText
}
// Format the date -- this goes in the detailTextLabel property, which is the "subtitle" of the cell
cell.detailTextLabel?.font = UIFont.systemFontOfSize(smallFontSize)
cell.detailTextLabel?.text = dateToLocalizedString(SQLDateToDate(thisFeedItem[kRSSDB.itemPubDate] as! String))
cell.layoutIfNeeded()
return cell
}
// MARK: UIRefreshControl
func doRefresh(sender : UIRefreshControl) {
loadFeed()
sender.endRefreshing()
}
// MARK: Support functions
private func loadFeed() {
let loaditems = LoadItems(db: rssdb, feedID: feedID, tableView: self)
}
private func loadFeedRecord() -> NSDictionary {
if feedRecord == nil { feedRecord = rssdb.getFeedRow(feedID) }
return feedRecord!
}
// MARK: Error Handling
func handleError(error: NSError) {
let errorMessage = error.localizedDescription
if error.domain == NSXMLParserErrorDomain && error.code >= 10 {
alertMessage("Cannot parse feed: \(errorMessage)")
} else {
alertMessage(errorMessage)
}
}
func alertMessage(message: String) {
let alertView = UIAlertView(title: "BW RSS", message: message, delegate: nil, cancelButtonTitle: "OK")
alertView.show()
navigationController?.popViewControllerAnimated(true)
}
}
|
//
// Created by maxime on 26/07/2018.
// Copyright (c) 2018 maxime. All rights reserved.
//
import UIKit
public class BoxDropLauncher {
public static func startGame(in viewController: UIViewController,
with model: GameUploadingModelProtocol,
navigator: GameUploadingNavigator,
action: GameUploadingCompletion?) {
let board = UIStoryboard(name: "GameViewController",
bundle: Bundle(for: BoxDropLauncher.self))
guard let gameViewController = board.instantiateInitialViewController() as? GameViewController else { return }
let presenter = GamePresenter(model: model, view: gameViewController, navigator: navigator, action: action)
gameViewController.modalPresentationStyle = .overCurrentContext
gameViewController.presenter = presenter
viewController.present(gameViewController, animated: true)
}
}
|
import UIKit
import ThemeKit
import MarketKit
class ContactBookAddressModule {
static func viewController(contactUid: String?, existAddresses: [ContactAddress], currentAddress: ContactAddress? = nil, onSaveAddress: @escaping (ContactAddress?) -> ()) -> UIViewController? {
let service: ContactBookAddressService
let addressService: AddressService
if let currentAddress {
guard let blockchain = try? App.shared.marketKit.blockchain(uid: currentAddress.blockchainUid) else {
return nil
}
addressService = AddressService(mode: .blockchainType, marketKit: App.shared.marketKit, contactBookManager: nil, blockchainType: blockchain.type)
service = ContactBookAddressService(marketKit: App.shared.marketKit, addressService: addressService, contactBookManager: App.shared.contactManager, currentContactUid: contactUid, mode: .edit(currentAddress), blockchain: blockchain)
} else {
let blockchainUids = BlockchainType
.supported
.map { $0.uid }
.filter { uid in
!existAddresses.contains(where: { address in address.blockchainUid == uid })
}
let allBlockchains = ((try? App.shared.marketKit.blockchains(uids: blockchainUids)) ?? [])
.sorted { $0.type.order < $1.type.order }
guard let firstBlockchain = allBlockchains.first else {
return nil
}
addressService = AddressService(mode: .blockchainType, marketKit: App.shared.marketKit, contactBookManager: nil, blockchainType: firstBlockchain.type)
service = ContactBookAddressService(marketKit: App.shared.marketKit, addressService: addressService, contactBookManager: App.shared.contactManager, currentContactUid: contactUid, mode: .create(existAddresses), blockchain: firstBlockchain)
}
let viewModel = ContactBookAddressViewModel(service: service)
let addressViewModel = RecipientAddressViewModel(service: addressService, handlerDelegate: nil)
let controller = ContactBookAddressViewController(viewModel: viewModel, addressViewModel: addressViewModel, onUpdateAddress: onSaveAddress)
return ThemeNavigationController(rootViewController: controller)
}
}
extension ContactBookAddressModule {
enum Mode {
case create([ContactAddress])
case edit(ContactAddress)
}
}
|
//
// ViewControllerAdd.swift
// Projecte
//
// Created by 1181432 on 4/2/16.
// Copyright © 2016 FIB. All rights reserved.
//
import UIKit
import CoreData
import MobileCoreServices
class ViewControllerAdd: UIViewController, UITableViewDataSource, UITableViewDelegate, linksDelegate, linkAddDelegate, UIImagePickerControllerDelegate, UIActionSheetDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
@IBOutlet weak var linksTable: UITableView!
@IBOutlet weak var manualName: UITextField!
@IBOutlet weak var imageView: UIImageView!
/* CoreData */
var appDelegate: AppDelegate!
var managedObjectsContext: NSManagedObjectContext!
var entityManualDescription:NSEntityDescription! //descripció d'entitat, no instacia!!
var entityLinkDescription:NSEntityDescription! //descripció d'entitat, no instacia!!
/* image */
var fileManager:NSFileManager!
var fileURL:NSURL?
var newPicture:Bool!
var image:UIImage!
var lastAddLinkView:ViewControllerAddLink!
var manual: Manual!
var links = [Link]()
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "FIB.Projecte" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
override func viewDidLoad() {
super.viewDidLoad()
self.manualName.delegate = self //Per poder amagar el teclat
imageView.image = UIImage(named: "Book")
newPicture = false
appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
managedObjectsContext = appDelegate.managedObjectContext
entityManualDescription = NSEntityDescription.entityForName("Manual", inManagedObjectContext: managedObjectsContext) //descripció d'entitat, no instacia!!
entityLinkDescription = NSEntityDescription.entityForName("Link", inManagedObjectContext: managedObjectsContext) //descripció d'entitat, no instacia!!
manual = Manual(entity: entityManualDescription!, insertIntoManagedObjectContext: managedObjectsContext )
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
/* Table functions */
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return links.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
if let cell = tableView.dequeueReusableCellWithIdentifier("linkCell", forIndexPath: indexPath) as? TableViewCellLink {
cell.delegate = self
cell.linkText.text = links[indexPath.row].link
cell.languageText.text = links[indexPath.row].language
cell.which = indexPath
return cell
}
return UITableViewCell()
}
/* Segue */
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard let segueIdentifier = segue.identifier else {
return
}
print(segueIdentifier)
switch segueIdentifier {
case "linkAdd":
let destination = segue.destinationViewController as! ViewControllerAddLink
destination.delegate = self
lastAddLinkView = destination
case "newManual":
let destination = segue.destinationViewController as! ViewController
destination.newManualAdded(manual, addView: self)
default: break
}
}
/* Add links */
@IBAction func onAddLinksClicked() {
performSegueWithIdentifier("linkAdd", sender: self)
}
func saveNewDownloadLinkSelected(link:String, language:String) {
lastAddLinkView.dismissViewControllerAnimated(true) {
let newLink = Link(entity: self.entityLinkDescription!, insertIntoManagedObjectContext: self.managedObjectsContext )
newLink.manual = self.manual
newLink.language = language
newLink.link = link
self.links.append(newLink)
let indexPath = NSIndexPath(forRow: self.links.count-1, inSection: 0)
self.linksTable.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Bottom)
}
}
/* Delete links */
func deleteButtonSelected(which: NSIndexPath) {
print("Delete from " + String(which.row) + " selected")
let actionSheetController: UIAlertController = UIAlertController(title: "Action Sheet", message: "Swiftly Now! Choose an option!", preferredStyle: .Alert)
//Create and add the Cancel action
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
//Just dismiss the action sheet
}
actionSheetController.addAction(cancelAction)
//Create and add first option action
let takePictureAction: UIAlertAction = UIAlertAction(title: "Take Picture", style: .Default) { action -> Void in
//Code for launching the camera goes here
}
actionSheetController.addAction(takePictureAction)
//Create and add a second option action
let choosePictureAction: UIAlertAction = UIAlertAction(title: "Choose From Camera Roll", style: .Default) { action -> Void in
//Code for picking from camera roll goes here
}
actionSheetController.addAction(choosePictureAction)
//Present the AlertController
self.presentViewController(actionSheetController, animated: true, completion: nil)
}
/*Add image */
@IBAction func onImageAddClicked(sender: UIButton) {
let alert = UIAlertController(title: "Choose an image", message: "", preferredStyle: .Alert) // 1
let firstAction = UIAlertAction(title: "From camera", style: .Default) { (alert: UIAlertAction!) -> Void in
self.cameraOptionSelected()
}
alert.addAction(firstAction)
let secondAction = UIAlertAction(title: "From file", style: .Default) { (alert: UIAlertAction!) -> Void in
self.cameraRollOptionSelected()
}
alert.addAction(secondAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { (alert: UIAlertAction!) -> Void in
//discard
}
alert.addAction(cancelAction)
presentViewController(alert, animated: true, completion:nil)
}
func cameraOptionSelected() {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
newPicture = true
}
}
func cameraRollOptionSelected() {
if UIImagePickerController.isSourceTypeAvailable( UIImagePickerControllerSourceType.SavedPhotosAlbum) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
newPicture = true
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let mediaType = info[UIImagePickerControllerMediaType] as! String
self.dismissViewControllerAnimated(true, completion: nil)
if mediaType == kUTTypeImage as String {
image = info[UIImagePickerControllerOriginalImage] as! UIImage
if (newPicture == true) {
UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
} else if mediaType == kUTTypeMovie as String {
// Code to support video here
}
}
}
func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) {
if error != nil {
let ac = UIAlertController(title: "Save error", message: error?.localizedDescription, preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
else {
}
}
func saveImageToDocuments(image: UIImage, name:String){
let dataImag = UIImagePNGRepresentation(image)
let fileURL = applicationDocumentsDirectory.URLByAppendingPathComponent(name)
if let data = dataImag {
print("guardem al path: " + fileURL.path!)
data.writeToFile(fileURL.path!, atomically: true)
manual.imagePath = fileURL.path
}
}
/* SAVE */
@IBAction func onSaveClicked() {
if let nameManual = manualName.text {
if links.count > 0 {
manual.name = nameManual
if let newImage = image {
saveImageToDocuments(newImage, name: nameManual)
}
//no passa res si no posen foto
performSegueWithIdentifier("newManual", sender: self)
}
else {
//alert falten links
}
}
else {
//alert falta nom
}
}
@IBAction func onCancelClicked() {
self.dismissViewControllerAnimated(true, completion: nil)
}
/*
// 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.
}
*/
}
|
// NSColorExtensions.swift - Copyright 2020 SwifterSwift
#if canImport(AppKit) && !targetEnvironment(macCatalyst)
import AppKit
public extension NSColor {
/// SwifterSwift: Create an NSColor with different colors for light and dark mode.
///
/// - Parameters:
/// - light: Color to use in light/unspecified mode.
/// - dark: Color to use in dark mode.
@available(OSX 10.15, *)
convenience init(light: NSColor, dark: NSColor) {
self.init(name: nil, dynamicProvider: { $0.name == .darkAqua ? dark : light })
}
}
#endif
|
//
// RFC822DateFormatter.swift
// Feedit
//
// Created by Tyler D Lawrence on 8/26/20.
//
import Foundation
/// Converts date and time textual representations within the RFC822
/// date specification into `Date` objects
class RFC822DateFormatter: DateFormatter {
let dateFormats = [
"MMM d, h:mm a"
//"EEE, d MMM yyyy HH:mm:ss zzz",
//"EEE, d MMM yyyy HH:mm zzz",
//"d MMM yyyy HH:mm:ss Z",
//"yyyy-MM-dd HH:mm:ss Z"
]
let backupFormats = [
"MMM d, h:mm a"
//"d MMM yyyy HH:mm:ss zzz",
//"d MMM yyyy HH:mm zzz"
]
override init() {
super.init()
self.timeZone = TimeZone(secondsFromGMT: 0)
self.locale = Locale(identifier: "en_US_POSIX")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) not supported")
}
private func attemptParsing(from string: String, formats: [String]) -> Date? {
for dateFormat in formats {
self.dateFormat = dateFormat
if let date = super.date(from: string) {
return date
}
}
return nil
}
override func date(from string: String) -> Date? {
let string = string.trimmingCharacters(in: .whitespacesAndNewlines)
if let parsedDate = attemptParsing(from: string, formats: dateFormats) {
return parsedDate
}
// See if we can lop off a text weekday, as DateFormatter does not
// handle these in full compliance with Unicode tr35-31. For example,
// "Tues, 6 November 2007 12:00:00 GMT" is rejected because of the "Tues",
// even though "Tues" is used as an example for EEE in tr35-31.
let trimRegEx = try! NSRegularExpression(pattern: "^[a-zA-Z]+, ([\\w :+-]+)$")
let trimmed = trimRegEx.stringByReplacingMatches(in: string, options: [],
range: NSMakeRange(0, string.count), withTemplate: "$1")
return attemptParsing(from: trimmed, formats: backupFormats)
}
}
|
//
// ContentView.swift
// SVGViewboxPathTest
//
// Created by Noah Gilmore on 7/25/20.
//
import SwiftUI
struct ContentView: View {
var body: some View {
ViewboxPathView(
viewboxPath: ViewboxPath(
viewbox: CGRect(x: 0, y: 0, width: 384, height: 512),
pathString: ViewboxPathView.string
),
height: 100
)
.frame(width: 512, height: 512)
.padding()
.background(Color.white)
}
}
|
//
// AppDetailResult.swift
// Assignment
//
// Created by Jae Kyung Lee on 27/04/2018.
// Copyright © 2018 Jae Kyung Lee. All rights reserved.
//
import Foundation
struct DetailInfo: Codable {
let trackCensoredName: String
let screenshotUrls: [String]
let contentAdvisoryRating: String
let artworkUrl100: String
let releaseNotes: String
let version: String
let artistName: String
let description: String
let averageUserRating: Double
let userRatingCount: Int
let sellerUrl: String?
// MARK: - DetailInfo as dictionay
var dictionary: [String: Any] {
return ["trackCensoredName": trackCensoredName,
"screenshotUrls": screenshotUrls,
"contentAdvisoryRating": contentAdvisoryRating,
"artworkUrl100": artworkUrl100,
"releaseNotes": releaseNotes,
"version": version,
"artistName": artistName,
"description": description,
"averageUserRating": averageUserRating,
"userRatingCount": userRatingCount,
// missing sellerUrl validation
"sellerUrl": sellerUrl ?? ""]
}
}
struct AppDetailResult: Decodable {
let results: [DetailInfo]
enum CodingKeys: String, CodingKey {
case results
}
}
|
//
// Signal.swift
// analog
//
// Created by Philip Kronawetter on 2020-05-05.
// Copyright © 2020 Philip Kronawetter. All rights reserved.
//
import UIKit
protocol Signal {
var timeRange: ClosedRange<TimeInterval> { get }
var valueRange: ClosedRange<Double> { get }
func value(at time: TimeInterval) -> OpaqueSignalValue
func path(for size: CGSize) -> UIBezierPath
func x(for time: TimeInterval, width: CGFloat) -> CGFloat
func y(for value: Double, height: CGFloat) -> CGFloat
}
extension Signal {
func x(for time: TimeInterval, width: CGFloat) -> CGFloat {
CGFloat((time - timeRange.lowerBound) / (timeRange.upperBound - timeRange.lowerBound)) * width
}
func y(for value: Double, height: CGFloat) -> CGFloat {
CGFloat((value - valueRange.lowerBound) / (valueRange.upperBound - valueRange.lowerBound)) * height
}
}
|
//
// Email.swift
// OnTheMap
//
// Created by Cristhian Recalde on 1/26/20.
// Copyright © 2020 Cristhian Recalde. All rights reserved.
//
import Foundation
struct Email: Codable {
let verificationCodeSent: Bool
let verified: Bool
let address: String
enum CodingKeys: String, CodingKey {
case verificationCodeSent = "_verification_code_sent"
case verified = "_verified"
case address
}
}
|
//
// ZGNormalNoTitleAlert.swift
// Pods
//
// Created by zhaogang on 2017/8/25.
//
//
import UIKit
class ZGNormalNoTitleAlert: ZGAlertView {
weak var contentLabel:UILabel!
var vLineLayer:CALayer!
var contentVerticalMargin:CGFloat = 28 //如果文字高度+上下间距大于topMinHeight, 则文字垂直拒中
//最多只支持两个按钮
override func setItem(_ item:ZGAlertItem) {
super.setItem(item)
self.backgroundColor = UIColor.white
self.layer.cornerRadius = 12
guard let content = item.content else {
return
}
self.contentLabel = self.addLabel()
self.addButtons(item: item)
self.contentLabel.text = content
self.contentLabel.lineBreakMode = .byCharWrapping
self.lineLayer = self.addLineLayer()
self.vLineLayer = self.addLineLayer()
if let items = item.buttonItems {
self.vLineLayer.isHidden = items.count < 2
}
self.contentLabel.textColor = UIColor.color(withHex: 0x666666)
self.layoutSubviews()
}
override func layoutSubviews() {
super.layoutSubviews()
guard let content = self.contentLabel.text else {
return
}
let marginLeft:CGFloat = 14
let topMinHeight:CGFloat = 108 //内容部分的最低高度
let labelWidth:CGFloat = self.width - marginLeft*2
var labelSize = CGSize.init(width: labelWidth, height: CGFloat(Int.max))
if let font = self.contentLabel.font {
let attributes = [NSAttributedString.Key.font:font]
labelSize = content.textSize(attributes: attributes, constrainedToSize: labelSize)
}
//布局文字
var rect = self.contentLabel.frame
rect.origin.x = (self.width - rect.width) / 2
var contentHeight:CGFloat = labelSize.height + contentVerticalMargin*2
if contentHeight < topMinHeight {
contentHeight = topMinHeight
}
rect.origin.y = (contentHeight - labelSize.height) / 2
rect.size = labelSize
self.contentLabel.frame = rect
var lineRect = self.lineLayer.frame
lineRect.origin.x = 0
lineRect.size.width = self.width
lineRect.size.height = 0.5
lineRect.origin.y = contentHeight
var vlineRect = self.vLineLayer.frame
vlineRect.origin.x = self.width / 2
vlineRect.size.width = 0.5
vlineRect.size.height = self.buttonHeight
vlineRect.origin.y = contentHeight
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
self.lineLayer.frame = lineRect
self.vLineLayer.frame = vlineRect
CATransaction.commit()
self.realHeight = contentHeight + self.buttonHeight
}
}
|
import Foundation
protocol TicketsScreenViewInput: ViewInput {
func setupInitialState()
func show(_ tickets: [TicketCellViewModel])
}
|
import UIKit
extension UIContextualAction {
/// Convenience init to build a UIAction from a `MenuAction`
/// to be used in a `UISwipeActionsConfiguration`.
convenience init(action: MenuAction,
handler: @escaping Block) {
let handler: Handler = { _,_, completion in
handler()
completion(true)
}
self.init(style: action.swipeActionStyle,
title: action.title,
handler: handler)
self.image = action.image
self.backgroundColor = action.swipeActionBackgroundColor
}
}
|
//
// BaseUIViewController.swift
// Merchant Central
//
// Created by Fabio Oliveira on 31/10/2014.
// Copyright (c) 2014 Olive 3 Consulting Ltd. All rights reserved.
//
import Foundation
import UIKit
class BaseUIViewController: UIViewController, CentralUserInterfaceDelegate {
var facade: CentralFacade? {
return appDelegate.facade
}
var appDelegate: AppDelegate {
return UIApplication.sharedApplication().delegate as AppDelegate
}
// MARK - CentralUserInterfaceDelegate protocol implementation
func notifyError(info: [String:AnyObject]?) {
logEvent("ERROR", info: info)
println("\ndumping context: \(info)\n")
}
func notifySuccess(info: [String:AnyObject]?) {
// logEvent("SUCCESS", info: info)
}
func notifyConnection(info: [String:AnyObject]?) {
logEvent("CONNECTED", info: info)
}
func notifyConnectionWillBegin(info: [String:AnyObject]?) {
logEvent("CONNECTION WILL BEGIN", info: info)
}
func notifyNewSession(info: [String:AnyObject]?) {
logEvent("SESSION INITIATING", info: info)
}
func notifySessionInvalidated(info: [String:AnyObject]?) {
logEvent("SESSION TERMINATED", info: info)
}
func notifyConnectionAlive(info: [String:AnyObject]?) {
logEvent("CONNECTION ALIVE", info: info)
}
func notifyConnectionClosed(info: [String:AnyObject]?) {
logEvent("CONNECTION CLOSED", info: info)
}
func notifyConnectionInfoUpdated(info: [String:AnyObject]?) {
logEvent("CONNECTION INFO UPDATE", info: info)
}
func notifyScanningStatus(status: Bool, info: [String:AnyObject]?) {
logEvent("SCANNING STATUS CHANGED", info: info)
}
func notifyDeviceConnected(info: [String:AnyObject]?) {
logEvent("DEVICE CONNECTED", info: info)
}
func notifyDeviceDisconnected(info: [String:AnyObject]?) {
logEvent("DEVICE DISCONNECTED", info: info)
}
func notifyDeviceConnectionFailed(info: [String:AnyObject]?) {
logEvent("DEVICE CONNECTION FAILED", info: info)
}
func notifyRejectedPeripheral(info: [String:AnyObject]?) {
logEvent("PERIPHERAL REJECTED", info: info)
}
func heartbeatReceived(data: String!, info: [String:AnyObject]?) {
logEvent("HEARTBEAT RECEIVED", info: info)
}
func userNameReceived(data: String!, info: [String:AnyObject]?) {
logEvent("USERNAME RECEIVED", info: info)
}
func otherInfoReceived(data: String!, info: [String:AnyObject]?) {
logEvent("OTHERINFO RECEIVED", info: info)
}
func userImageReceived(data: UIImage!, info: [String:AnyObject]?) {
logEvent("USERIMAGE RECEIVED", info: info)
}
func paymentAuthorizationReceived(data: String!, info: [String:AnyObject]?) {
logEvent("PAYMTAUTH RECEIVED", info: info)
}
func notifyTokenToSend(info: [String:AnyObject]?) {
logEvent("TOKEN TO SEND", info: info)
}
func notifyTokenSent(info: [String:AnyObject]?) {
logEvent("TOKEN SENT", info: info)
}
// MARK: Other convenience methods and properties
var timestamp: String {
return BluetoothUtils.timestamp()
}
func logEvent(prefix: String, info: [String:AnyObject]?) {
BluetoothUtils.logEvent(prefix, info: info)
}
func formatAmount(_amount: String) -> String {
return BluetoothUtils.formatAmount(_amount)
}
}
|
//
// ViewController.swift
// IP Locator
//
// Created by Patrick Zawadzki on 5/11/15.
// Copyright (c) 2015 PatZawadzki. All rights reserved.
//
import UIKit
import Foundation
import MapKit
class LoadingViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imageView.userInteractionEnabled = false
self.load()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func load(){
imageView.animationImages = [UIImage]()
imageView.animationRepeatCount = 1
for var index = 1; index < 36; index += 1{
let frameName = String(format: "%d", index)
imageView.animationImages?.append(UIImage(named: frameName)!)
}
imageView.animationDuration = 1
imageView.startAnimating()
let triggerTime = (Int64(NSEC_PER_SEC) * 1)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
self.performSegueWithIdentifier("finishedAnimatingSegue", sender: self)
})
}
}
|
import UIKit
import CPaaSSDK
class AddressbookViewController: BaseViewController, AddressBookAddUpdateDelegate {
@IBOutlet weak var tblVw: UITableView!
var addressbook = AddressbookBO()
@IBOutlet weak var lblNoRecord: UILabel!
var isToUpdate: Bool = false
@IBOutlet weak var btnAddUpdate: UIButton!
var cpaas: CPaaS!
var address_Handler = AddressBookModule()
override func viewDidLoad() {
super.viewDidLoad()
self.setNavigationBarColorForViewController(viewController: self, type: 1, titleString: "")
self.tblVw.register(UINib(nibName: "AddressbookTableViewCell", bundle: nil), forCellReuseIdentifier: "AddressbookTableViewCell")
NotificationCenter.default.addObserver(self, selector: #selector(AddressbookViewController.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(AddressbookViewController.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
address_Handler.cpaas = self.cpaas
address_Handler.delegate_AddUpdateAddressBook = self
if isToUpdate {
btnAddUpdate.setTitle("UPDATE CONTACT", for: UIControl.State.normal)
}else{
btnAddUpdate.setTitle("ADD CONTACT", for: UIControl.State.normal)
}
}
@IBAction func btnAddUpdateTapped(sender: UIButton){
let indexPath = IndexPath(row: 0, section: 0)
let cell = tblVw.cellForRow(at: indexPath) as! AddressbookTableViewCell
let object = AddressbookBO()
object.contactId = cell.txtContactId.text
object.primaryContact = cell.txtPrimaryContact.text
object.firstName = cell.txtFirstName.text
object.lastName = cell.txtLastName.text
object.email = cell.txtEmail.text
object.homePhoneNumber = cell.txtHomePhoneNumber.text
object.businessPhoneNumber = cell.txtBusinessPhoneNumber.text
if isToUpdate {
object.isBuddy = addressbook.isBuddy
address_Handler.updateContact(model: object)
}else{
object.isBuddy = cell.btnBuddy.isSelected
address_Handler.createContact(model: object)
}
}
func addedContact(isSuccess: Bool){
if isSuccess{
LoaderClass.sharedInstance.showActivityIndicator()
self.navigationController?.popViewController(animated: true)
}else{
Alert.instance.showAlert(msg: "Unable to Add Contact. Please try again later.", title: "", sender: self)
}
}
func updatedContact(isSuccess: Bool){
if isSuccess{
LoaderClass.sharedInstance.showActivityIndicator()
self.navigationController?.popViewController(animated: true)
}else{
Alert.instance.showAlert(msg: "Unable to Update Contact. Please try again later.", title: "", sender: self)
}
}
@objc func buddyTapped(sender: UIButton) {
let indexPath = IndexPath(row: 0, section: 0)
let cell = tblVw.cellForRow(at: indexPath) as! AddressbookTableViewCell
if isToUpdate {
if addressbook.isBuddy{
addressbook.isBuddy = false
}else{
addressbook.isBuddy = true
}
cell.imgBuddy.image = addressbook.isBuddy ? UIImage.init(named: "selected"):UIImage.init(named: "unSelected")
}else{
if cell.btnBuddy.isSelected{
cell.btnBuddy.isSelected = false
}else{
cell.btnBuddy.isSelected = true
}
cell.imgBuddy.image = cell.btnBuddy.isSelected ? UIImage.init(named: "selected"):UIImage.init(named: "unSelected")
}
}
@objc func keyboardWillShow(notification: Notification) {
let kbrect: CGRect? = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue
let heightOffset: CGFloat = self.tblVw.frame.origin.y + self.tblVw.frame.size.height
if heightOffset > (kbrect?.origin.y ?? 00) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.3)
self.tblVw.contentOffset = CGPoint(x: 0, y: heightOffset - (kbrect?.origin.y)! )
UIView.commitAnimations()
} else {
}
}
@objc func keyboardWillHide(notification: Notification) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.3)
self.tblVw.contentOffset = CGPoint(x: 0, y: 0)
UIView.commitAnimations()
}
}
extension AddressbookViewController:UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "AddressbookTableViewCell", for: indexPath) as! AddressbookTableViewCell
cell.selectionStyle = UITableViewCell.SelectionStyle.none
cell.btnBuddy.addTarget(self, action: #selector(buddyTapped(sender:)), for: UIControl.Event.touchUpInside)
cell.displayContentType(object: addressbook)
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return AddressbookTableViewCell.height()
}
}
//MARK:- UITextFieldDelegate....
extension AddressbookViewController :UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
|
//
// GameViewController.swift
// Pierre The Penguin
//
// Created by Gerard Byrne on 02/11/2019.
// Copyright © 2019 Gerard Byrne. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if let view = self.view as! SKView?
{
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene")
{
// Set the scale mode to fit the window:
scene.scaleMode = .aspectFill
// Size our scene to fit the view exactly:
scene.size = view.bounds.size
// Show the new scene
view.presentScene(scene)
} // End if scene construct
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
} // End of if view construct
} // End of function viewWillLayoutSubviews
override var supportedInterfaceOrientations:
UIInterfaceOrientationMask
{
return .landscape
}
} // End of class
|
import UIKit
import SnapKit
import ComponentKit
import ThemeKit
import HUD
class IndicatorAdviceCell: BaseThemeCell {
static let height: CGFloat = 229
private let headerWrapperView = UIView()
private let nameLabel = UILabel()
private let infoButton = SecondaryCircleButton()
private var adviceViews = [IndicatorAdviceView]()
private let spinner = HUDActivityView.create(with: .medium24)
var onTapInfo: (() -> ())?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
wrapperView.backgroundColor = .clear
backgroundColor = .clear
wrapperView.addSubview(headerWrapperView)
headerWrapperView.snp.makeConstraints { maker in
maker.top.equalToSuperview()
maker.leading.trailing.equalToSuperview()
}
headerWrapperView.addSubview(nameLabel)
nameLabel.snp.makeConstraints { maker in
maker.top.equalToSuperview().offset(CGFloat.margin12)
maker.leading.equalToSuperview().inset(CGFloat.margin16)
maker.bottom.equalToSuperview().inset(9)
}
nameLabel.font = .subhead1
nameLabel.textColor = .gray
nameLabel.text = "coin_analytics.indicators.title".localized
headerWrapperView.addSubview(infoButton)
infoButton.snp.makeConstraints { make in
make.leading.equalTo(nameLabel.snp.trailing).offset(CGFloat.margin12)
make.top.equalToSuperview().inset(CGFloat.margin12)
make.trailing.equalToSuperview().inset(CGFloat.margin16)
}
infoButton.set(image: UIImage(named: "circle_information_20"), style: .transparent)
infoButton.addTarget(self, action: #selector(onTapInfoButton), for: .touchUpInside)
var lastView: UIView = headerWrapperView
for _ in 0..<3 {
let view = IndicatorAdviceView()
adviceViews.append(view)
wrapperView.addSubview(view)
view.snp.makeConstraints { maker in
maker.top.equalTo(lastView.snp.bottom).offset(CGFloat.margin24)
maker.leading.trailing.equalToSuperview().inset(CGFloat.margin16)
}
lastView = view
}
wrapperView.addSubview(spinner)
spinner.snp.makeConstraints { maker in
maker.center.equalToSuperview()
}
spinner.set(hidden: true)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func onTapInfoButton() {
onTapInfo?()
}
}
extension IndicatorAdviceCell {
func set(loading: Bool) {
adviceViews.forEach { $0.isHidden = loading }
spinner.isHidden = !loading
if loading {
spinner.startAnimating()
} else {
spinner.stopAnimating()
}
}
func setEmpty(value: String) {
CoinIndicatorViewItemFactory.sectionNames.enumerated().forEach { index, element in
guard let view = adviceViews.at(index: index) else {
return
}
view.title = element
view.setEmpty(title: element, value: value)
}
}
func set(viewItems: [CoinIndicatorViewItemFactory.ViewItem]) {
viewItems.enumerated().forEach { index, element in
guard let view = adviceViews.at(index: index) else {
return
}
view.title = element.name
view.set(advice: element.advice)
}
}
}
|
//
// NotebooksView.swift
// StudyPad
//
// Created by Roman Levinzon on 21/01/2019.
// Copyright © 2019 Roman Levinzon. All rights reserved.
//
import Foundation
protocol NotebooksView : BaseView {
func showNotebooks(notebooks: [Notebook])
func showEmptyView()
func showLoadingError()
func showError(_ error: Error)
}
protocol NotebooksCoordinatorDelegate: class {
func showNotesView(notebook: Notebook)
}
|
import Foundation
struct CategoryCodable: Codable {
var id: Int
var name: String
}
|
//
// AssetsViewController.swift
// DevBoostItau-Project1
//
// Created by bruna on 9/5/20.
// Copyright © 2020 DevBoost-Itau. All rights reserved.
//
import UIKit
import CoreData
class AssetsViewController: BaseViewController, HasCodeView {
typealias CustomView = AssetsView
// MARK: Properties
lazy var viewModel = AssetsViewModel(context: context)
weak var coordinator: AssetsCoordinator?
// MARK: Overrides
override func loadView() {
view = AssetsView(delegate: self)
}
override func viewDidLoad() {
super.viewDidLoad()
viewModel.investmentsDidUpdate = investmentsDidUpdate
customView.tableView.delegate = self
customView.tableView.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.customView.applyGradient(style: .vertical, colors: [UIColor.itiOrange, UIColor.itiPink])
viewModel.loadInvestments()
}
// MARK: Methods
func investmentsDidUpdate(){
DispatchQueue.main.async {
self.customView.tableView.reloadData()
self.customView.showTotalBalanceWith(value: self.viewModel.getTotalBalance())
}
}
}
extension AssetsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
viewModel.count == 0 ? tableView.setEmptyMessage(Localization.assetsEmpty) : tableView.restore()
return viewModel.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "AssetCell", for: indexPath) as? AssetTableViewCell else{
return UITableViewCell()
}
cell.selectionStyle = .none
let investmentCellViewModel = viewModel.cellViewModelFor(indexPath: indexPath)
cell.configure(with: investmentCellViewModel, percent: viewModel.getInvestmentPercentFor(indexPath))
return cell
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let editAction = UITableViewRowAction(style: .default, title: Localization.edit, handler: { (action, indexPath) in
self.coordinator?.editInvestment(investment: self.viewModel.getEditInvestment(indexPath))
})
editAction.backgroundColor = UIColor.lightGray
let deleteAction = UITableViewRowAction(style: .default, title: Localization.delete, handler: { (action, indexPath) in
self.viewModel.deleteInvestment(at: indexPath)
})
return [editAction, deleteAction]
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let assetDetailViewModel = viewModel.getAssetViewModelFor(indexPath)
coordinator?.showInvestment(viewModel: assetDetailViewModel)
}
}
extension AssetsViewController: AssetsViewDelegate {
func showBalance() {
self.customView.showTotalBalanceWith(value: viewModel.getTotalBalance())
}
func goToNewInvestment() {
self.coordinator?.editInvestment(investment: nil)
}
}
|
//
// SystemTableCellViewModel.swift
// Quota
//
// Created by Marcin Włoczko on 06/11/2018.
// Copyright © 2018 Marcin Włoczko. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
protocol SystemTableCellViewModel {
var title: String { get }
var detailTitle: String? { get }
var accessoryType: UITableViewCell.AccessoryType { get }
var isSelected: BehaviorRelay<Bool> { get }
var isSelectable: Bool { get }
}
final class SystemTableCellViewModelImp: SystemTableCellViewModel {
let title: String
let detailTitle: String?
let accessoryType: UITableViewCell.AccessoryType
let isSelected: BehaviorRelay<Bool>
let isSelectable: Bool
init(title: String,
detailTitle: String? = nil,
accessoryType: UITableViewCell.AccessoryType = .none,
isSelected: Bool = false,
isSelectable: Bool = false) {
self.title = title
self.detailTitle = detailTitle
self.accessoryType = accessoryType
self.isSelected = BehaviorRelay<Bool>(value: isSelected)
self.isSelectable = isSelectable
}
}
|
//
// BeerDetailView.swift
// Paging
//
// Created by Evgeniya Bubnova on 08.04.2020.
// Copyright © 2020 Evgeniya Bubnova. All rights reserved.
//
import SwiftUI
struct BeerDetailView: View {
var beer: Beer
var body: some View {
VStack(alignment: .leading) {
PopButton {
Text("< Back")
.foregroundColor(.blue)
}
.padding(20)
Text(beer.name ?? "")
.font(.largeTitle)
.padding(20)
HStack(alignment: .top) {
ZStack {
AsyncImage(
url: beer.imageURL,
placeholder: Image(systemName: "slowmo")
)
.aspectRatio(contentMode: .fit)
}
.frame(maxHeight: 200)
VStack(alignment: .leading) {
Text(beer.firstBrewed ?? "")
.font(.callout)
Text(beer.description ?? "")
}
}
.padding(20)
PushButton(destination: IngredientsView(beer: beer)) {
ZStack {
RoundedRectangle(cornerRadius: 30)
.foregroundColor(.green)
Text("Ingredients")
}
.frame(height: 40)
}
.padding(20)
Spacer()
}
}
}
struct BeerDetailView_Previews: PreviewProvider {
static var previews: some View {
BeerDetailView(beer: Beer(id: 0, name: "123", description: nil, firstBrewed: nil, imageUrl: nil, ingredients: nil))
}
}
|
//
// AEReceivedMsgDetailVC.swift
// AESwiftWorking_Example
//
// Created by Adam on 2021/4/29.
// Copyright © 2021 CocoaPods. All rights reserved.
//
import UIKit
class AEReceivedMsgDetailVC: ICMineViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func configEvent() {
super.configEvent()
dataArray = []
var infoArray: [ICShowInfoModel] = []
var infoModel = ICShowInfoModel()
infoModel.title = "发布类型:"
infoModel.detailInfo = "提醒类"
infoArray.append(infoModel)
infoModel = ICShowInfoModel()
infoModel.title = "主题:"
infoModel.detailInfo = "关于中国光大银行信用卡增值服务业务调整的公告关于中国光大银行信用卡增值服务业务调整的公告"
infoModel.boldFont = true
infoArray.append(infoModel)
infoModel = ICShowInfoModel()
infoModel.title = "编号:"
infoModel.detailInfo = "20190103140511oO4qDV"
infoArray.append(infoModel)
infoModel = ICShowInfoModel()
infoModel.title = "发布人:"
infoModel.detailInfo = "移动互联网业务部 李努力"
infoArray.append(infoModel)
infoModel = ICShowInfoModel()
infoModel.title = "发布时间:"
infoModel.detailInfo = "2021-03-02"
infoArray.append(infoModel)
infoModel = ICShowInfoModel()
infoModel.title = "完成期限:"
infoModel.detailInfo = "2021-03-03"
infoArray.append(infoModel)
infoModel = ICShowInfoModel()
infoModel.title = "发布等级:"
infoModel.detailInfo = "高级"
infoArray.append(infoModel)
infoModel = ICShowInfoModel()
infoModel.title = "是否回复:"
infoModel.detailInfo = "否"
infoArray.append(infoModel)
infoModel = ICShowInfoModel()
infoModel.title = "发送人:"
infoModel.detailInfo = "移动互联网业务部 王努力;移动互联网业务部 张努力; 移动互联网业务部 刘努力;移动互联网业务部 郑努力;移动互联网业务部 周努力。"
infoArray.append(infoModel)
infoModel = ICShowInfoModel()
infoModel.title = "发布详情:"
infoModel.detailInfo = "关于中国光大银行信用卡增值服务业务调整的公告,关于中国光大银行信用卡增值服务业务调整的公告,关于中国光大银行信用卡增值服务业务调整的公告,关于中国光大银行信用卡增值服务业务调整的公告。"
infoArray.append(infoModel)
dataArray?.append(infoArray)
/// 第二组
infoArray = []
infoModel = ICShowInfoModel()
infoModel.title = "立即回复"
infoModel.type = .action
infoArray.append(infoModel)
dataArray?.append(infoArray)
customClosure = {(data) in
print("立即回复")
let vc = AEFormReplyMessageVC()
// vc.style = .grouped
vc.separatorStyle = .none
self.navigationController?.pushViewController(vc, animated: true)
}
}
override func configUI() {
super.configUI()
navigationItem.title = "消息详情"
}
}
|
//
// DefaultCompletionHandler.swift
// BasicNetwork
//
// Created by Theis Egeberg on 17/05/2017.
// Copyright © 2017 Theis Egeberg. All rights reserved.
//
import Foundation
public let defaultCompletionHandler: CompletionHandler = {
(response) in
switch response {
case .error(let error, let report):
print("Error")
print(error)
print(report?.prettyPrint() ?? "No report generated")
case .success(let data, let report):
print("Success")
print(String(data: data, encoding: .utf8) ?? "Can't decode data: \(data)")
print(report?.prettyPrint() ?? "No report generated")
}
}
|
//
// View1.swift
// project 10
//
// Created by Anisha Lamichhane on 5/29/21.
//
import SwiftUI
class User: ObservableObject, Codable {
// every case in our enum is the name of a property we want to load and save
enum CodingKeys: CodingKey {
case name
}
@Published var name = "somebody"
// This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid.
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
}
}
struct View1: View {
var body: some View {
Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
}
}
struct View1_Previews: PreviewProvider {
static var previews: some View {
View1()
}
}
|
//import SwiftWebSocket
import Foundation
typealias CentrifugeBlockingHandler = ([CentrifugeServerMessage]?, NSError?) -> Void
class CentrifugeClientImpl: NSObject {
var ws: CentrifugeWebSocket!
var creds: CentrifugeCredentials!
var conf: CentrifugeConfig!
var builder: CentrifugeClientMessageBuilder!
var parser: CentrifugeServerMessageParser!
var clientId: String?
weak var delegate: CentrifugeClientDelegate!
var messageCallbacks = [String : CentrifugeMessageHandler]()
var subscription = [String : CentrifugeChannelDelegate]()
/** Handler is used to process websocket delegate method.
If it is not nil, it blocks default actions. */
var blockingHandler: CentrifugeBlockingHandler?
var connectionCompletion: CentrifugeMessageHandler?
private var isAuthBatching = false
private var channelsForAuth: [String: CentrifugeMessageHandler] = [:]
func stopAuthBatching() {
isAuthBatching = false
authChannels()
}
//MARK: - Helpers
func unsubscribeFrom(channel: String) {
subscription[channel] = nil
}
func send(message: CentrifugeClientMessage) {
try! ws.send(centrifugeMessage: message)
}
func setupConnectedState() {
blockingHandler = defaultProcessHandler
}
func resetState() {
blockingHandler = nil
connectionCompletion = nil
messageCallbacks.removeAll()
subscription.removeAll()
}
//MARK: - Handlers
/**
Handler is using while connecting to server.
*/
func connectionProcessHandler(messages: [CentrifugeServerMessage]?, error: NSError?) -> Void {
guard let handler = connectionCompletion else {
print("Error: No connectionCompletion")
return
}
resetState()
if let err = error {
handler(nil, err)
return
}
guard let message = messages?.first else {
print("Error: Empty messages array")
// print("%@", "Error: Empty messages array without error")
return
}
if message.error == nil {
clientId = message.body?["client"] as? String
setupConnectedState()
handler(message, nil)
} else {
let error = NSError.errorWithMessage(message: message)
handler(nil, error)
}
}
//Handler is using while normal working with server.
func defaultProcessHandler(messages: [CentrifugeServerMessage]?, error: NSError?) {
if let err = error {
delegate?.client(self, didReceiveError: err)
return
}
guard let msgs = messages else {
print("Error: Empty messages array without error")
// NSLog("%@", "Error: Empty messages array without error")
return
}
for message in msgs {
defaultProcessHandler(message: message)
}
}
func defaultProcessHandler(message: CentrifugeServerMessage) {
var handled = false
if let uid = message.uid, messageCallbacks[uid] == nil {
print("Error: Untracked message is received")
return
}
if let uid = message.uid, let handler = messageCallbacks[uid], message.error != nil {
let error = NSError.errorWithMessage(message: message)
handler(nil, error)
messageCallbacks[uid] = nil
return
}
if let uid = message.uid, let handler = messageCallbacks[uid] {
handler(message, nil)
messageCallbacks[uid] = nil
handled = true
}
if (handled && (message.method != .Unsubscribe && message.method != .Disconnect)) {
return
}
switch message.method {
// Channel events
case .Message:
guard let channel = message.body?["channel"] as? String, let delegate = subscription[channel] else {
print("Error: Invalid \(message.method) handler")
return
}
delegate.client(self, didReceiveMessageInChannel: channel, message: message)
case .Join:
guard let channel = message.body?["channel"] as? String, let delegate = subscription[channel] else {
print("Error: Invalid \(message.method) handler")
return
}
delegate.client(self, didReceiveJoinInChannel: channel, message: message)
case .Leave:
guard let channel = message.body?["channel"] as? String, let delegate = subscription[channel] else {
print("Error: Invalid \(message.method) handler")
return
}
delegate.client(self, didReceiveLeaveInChannel: channel, message: message)
case .Unsubscribe:
guard let channel = message.body?["channel"] as? String, let delegate = subscription[channel] else {
print("Error: Invalid \(message.method) handler")
return
}
delegate.client(self, didReceiveUnsubscribeInChannel: channel, message: message)
unsubscribeFrom(channel: channel)
// Client events
case .Disconnect:
delegate?.client(self, didDisconnect: message)
ws.close()
resetState()
case .Refresh:
delegate?.client(self, didReceiveRefresh: message)
default:
print("Error: Invalid method type")
}
}
}
//MARK:- CentrifugeClient
extension CentrifugeClientImpl: CentrifugeClient {
func setAuthRequest(request: URLRequest) {
self.conf.authRequest = request
}
//MARK: - Public interface
//MARK: Server related method
func connect(withCompletion completion: @escaping CentrifugeMessageHandler) {
blockingHandler = connectionProcessHandler
connectionCompletion = completion
ws = CentrifugeWebSocket(conf.url)
ws.delegate = self
}
func disconnect() {
ws.delegate = nil
ws.close()
}
func ping(withCompletion completion: @escaping CentrifugeMessageHandler) {
let message = builder.buildPingMessage()
messageCallbacks[message.uid] = completion
send(message: message)
}
//MARK: Channel related method
func subscribe(toChannel channel: String,
delegate: CentrifugeChannelDelegate,
completion: @escaping CentrifugeMessageHandler) {
if channel.hasPrefix(Centrifuge.privateChannelPrefix) {
subscription[channel] = delegate
authChanel(chanel: channel, handler: completion)
}
else {
let message = builder.buildSubscribeMessageTo(channel: channel)
subscription[channel] = delegate
messageCallbacks[message.uid] = completion
send(message: message)
}
}
func subscribe(toChannel channel: String,
delegate: CentrifugeChannelDelegate,
lastMessageUID uid: String,
completion: @escaping CentrifugeMessageHandler) {
if channel.hasPrefix(Centrifuge.privateChannelPrefix) {
subscription[channel] = delegate
authChanel(chanel: channel, handler: completion)
}
else {
let message = builder.buildSubscribeMessageTo(channel: channel, lastMessageUUID: uid)
subscription[channel] = delegate
messageCallbacks[message.uid] = completion
send(message: message)
}
}
func publish(toChannel channel: String, data: [String : Any], completion: @escaping CentrifugeMessageHandler) {
let message = builder.buildPublishMessageTo(channel: channel, data: data)
messageCallbacks[message.uid] = completion
send(message: message)
}
func unsubscribe(fromChannel channel: String, completion: @escaping CentrifugeMessageHandler) {
let message = builder.buildUnsubscribeMessageFrom(channel: channel)
messageCallbacks[message.uid] = completion
send(message: message)
}
func presence(inChannel channel: String, completion: @escaping CentrifugeMessageHandler) {
let message = builder.buildPresenceMessage(channel: channel)
messageCallbacks[message.uid] = completion
send(message: message)
}
func history(ofChannel channel: String, completion: @escaping CentrifugeMessageHandler) {
let message = builder.buildHistoryMessage(channel: channel)
messageCallbacks[message.uid] = completion
send(message: message)
}
func startAuthBatching() {
isAuthBatching = true
}
}
//MARK: - WebSocketDelegate
extension CentrifugeClientImpl: WebSocketDelegate {
func webSocketOpen() {
let message = builder.buildConnectMessage(credentials: creds)
send(message: message)
}
func webSocketMessageText(_ text: String) {
let data = text.data(using: String.Encoding.utf8)!
let messages = try! parser.parse(data: data)
if let handler = blockingHandler {
handler(messages, nil)
}
}
func webSocketClose(_ code: Int, reason: String, wasClean: Bool) {
if let handler = blockingHandler {
let error = NSError(domain: CentrifugeWebSocketErrorDomain, code: code, userInfo: [NSLocalizedDescriptionKey : reason])
handler(nil, error)
}
}
func webSocketError(_ error: NSError) {
if let handler = blockingHandler {
handler(nil, error)
}
}
//MARK: - Authorization
func authChanel(chanel: String, handler: @escaping CentrifugeMessageHandler) {
if chanel.characters.count < 2 { return }
if !chanel.hasPrefix(Centrifuge.privateChannelPrefix) { return }
channelsForAuth[chanel] = handler
if isAuthBatching == false {
stopAuthBatching()
}
}
private func authChannels() {
guard self.channelsForAuth.count > 0,
let clientId = clientId,
let request = conf.authRequest else { return }
let channelsForAuth = self.channelsForAuth
self.channelsForAuth = [:]
URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
guard let s = self else { return }
guard let data = data, error == nil else {
channelsForAuth.forEach { (channel, handler) in
s.subscription[channel] = nil
handler(nil, error as NSError?)
}
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
let error = NSError(domain: CentrifugeAuthErrorDomain,
code: 0,
userInfo: ["data" : data,
NSLocalizedDescriptionKey: "Server error: \(httpStatus.statusCode)"])
channelsForAuth.forEach { (channel, handler) in
s.subscription[channel] = nil
handler(nil, error)
}
return
}
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
let error = NSError(domain: CentrifugeAuthErrorDomain,
code: 1,
userInfo: ["data" : data,
NSLocalizedDescriptionKey: "Cannot parse json"])
channelsForAuth.forEach { (channel, handler) in
s.subscription[channel] = nil
handler(nil, error)
}
return
}
for (channel, handler) in channelsForAuth {
guard let channelData = json?[channel] as? [String: Any],
let sign = channelData["sign"] as? String else {
let error = NSError(domain: CentrifugeAuthErrorDomain,
code: 2,
userInfo: ["data" : data,
NSLocalizedDescriptionKey: "Channel not found in authorization response"])
channelsForAuth.forEach { (channel, handler) in
s.subscription[channel] = nil
handler(nil, error)
}
continue
}
let info = channelData["info"] as! String;
let message = s.builder.buildSubscribeMessageTo(channel: channel, clientId: clientId, info: info, sign: sign)
s.messageCallbacks[message.uid] = handler
s.send(message: message)
}
}.resume()
}
}
|
struct AuthMethod {
let type: AuthType
let displayName: String
let url: String
class DisplayNames {
static let basic = "Basic Auth"
static let gitHub = "GitHub"
static let uaa = "UAA"
}
init(type: AuthType, displayName: String, url: String) {
self.type = type
self.displayName = displayName
self.url = url
}
}
extension AuthMethod: Equatable {}
func ==(lhs: AuthMethod, rhs: AuthMethod) -> Bool {
return lhs.type == rhs.type &&
lhs.displayName == rhs.displayName &&
lhs.url == rhs.url
}
|
//
// FlickrPhotoViewController.swift
// FlickrSearch
//
// Created by Jeff Norton on 11/20/16.
// Copyright © 2016 JeffCryst. All rights reserved.
//
import UIKit
class FlickrPhotoViewController: UIViewController {
//==================================================
// MARK: - _Properties
//==================================================
let cellReuseIdentifier = "resultPhotoCell"
fileprivate let itemsPerRow: CGFloat = 3
var largePhotoIndexPath: NSIndexPath? {
didSet {
var indexPaths = [IndexPath]()
if let largePhotoIndexPath = self.largePhotoIndexPath {
indexPaths.append(largePhotoIndexPath as IndexPath)
}
if let oldValue = oldValue {
indexPaths.append(oldValue as IndexPath)
}
self.resultsCollectionView.performBatchUpdates({
self.resultsCollectionView.reloadItems(at: indexPaths)
}) { (completed) in
if let largePhotoIndexPath = self.largePhotoIndexPath {
self.resultsCollectionView.selectItem(at: largePhotoIndexPath as IndexPath, animated: true, scrollPosition: .centeredVertically)
}
}
}
}
fileprivate let photoController = PhotoController()
@IBOutlet weak var resultsCollectionView: UICollectionView!
@IBOutlet weak var searchBar: UISearchBar!
fileprivate var searches = [PhotoSearchResults]()
fileprivate let sectionInsets = UIEdgeInsets(top: 50.0, left: 20.0, bottom: 50.0, right: 20.0)
//==================================================
// MARK: - General
//==================================================
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
private extension FlickrPhotoViewController {
func photo(forIndexPath indexPath: IndexPath) -> Photo {
return searches[(indexPath as NSIndexPath).section].searchResults[(indexPath as NSIndexPath).row]
}
}
// MARK: - UICollectionViewDataSource
extension FlickrPhotoViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return searches.count
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return searches[section].searchResults.count
}
func collectionView(_ collectionView: UICollectionView,
viewForSupplementaryElementOfKind kind: String,
at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind,
withReuseIdentifier: "PhotoHeaderView",
for: indexPath) as! PhotoHeaderView
headerView.sectionLabel.text = searches[(indexPath as NSIndexPath).section].searchTerm
return headerView
default:
assert(false, "Unexpected element kind")
}
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier,
for: indexPath) as! PhotoCollectionViewCell
let currentPhoto = photo(forIndexPath: indexPath)
cell.activityIndicator.stopAnimating()
guard indexPath as NSIndexPath? == largePhotoIndexPath else {
cell.photo = currentPhoto
return cell
}
guard currentPhoto.largeImage == nil else {
cell.photoImageView.image = currentPhoto.largeImage
return cell
}
cell.photoImageView.image = currentPhoto.thumbnail
cell.activityIndicator.startAnimating()
currentPhoto.loadLargeImage { (loadedPhoto, error) in
cell.activityIndicator.stopAnimating()
guard loadedPhoto?.largeImage != nil && error == nil else {
return
}
if let cell = collectionView.cellForItem(at: indexPath) as? PhotoCollectionViewCell
, indexPath == self.largePhotoIndexPath as? IndexPath {
cell.photo = loadedPhoto
}
}
return cell
}
}
// MARK: - UICollectionViewDelegate
extension FlickrPhotoViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
largePhotoIndexPath = largePhotoIndexPath == indexPath as NSIndexPath? ? nil : indexPath as NSIndexPath?
return false
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension FlickrPhotoViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath as NSIndexPath? == largePhotoIndexPath {
let currentPhoto = photo(forIndexPath: indexPath)
var size = collectionView.bounds.size
size.height -= topLayoutGuide.length
size.height -= (sectionInsets.top + sectionInsets.right)
size.width -= (sectionInsets.left + sectionInsets.right)
return currentPhoto.sizeToFillWidths(ofSize: size)
}
let paddingSpace = sectionInsets.left * (self.itemsPerRow + 1)
let availableWidth = view.frame.width - paddingSpace
let widthPerItem = availableWidth / itemsPerRow
return CGSize(width: widthPerItem, height: widthPerItem)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return sectionInsets
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return sectionInsets.left
}
}
// MARK: - UISearchBarDelegate
extension FlickrPhotoViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if let searchTerm = searchBar.text, searchTerm.characters.count > 0 {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
searchBar.addSubview(activityIndicator)
activityIndicator.frame = searchBar.bounds
activityIndicator.startAnimating()
photoController.searchFlickr(forSearchTerm: searchTerm) { (results, error) in
DispatchQueue.main.async {
activityIndicator.removeFromSuperview()
if let error = error {
NSLog("Error: \(error.localizedDescription)")
return
}
if let results = results {
NSLog("Found \(results.searchResults.count) results matching \"\(results.searchTerm)\"")
self.searches.insert(results, at: 0)
self.resultsCollectionView.reloadData()
}
// self.resultsCollectionView.reloadData()
}
}
}
searchBar.text = nil
}
}
|
import UIKit
import UserNotifications
import UserNotificationsUI
import SharedManager
import MapboxStatic
import CleverTapAppEx
class NotificationViewController: UIViewController, UNNotificationContentExtension {
@IBOutlet var mapImageView: UIImageView!
@IBOutlet var loadingIndicator: UIActivityIndicatorView!
@IBOutlet var textLabel: UILabel!
private lazy var cleverTap: CleverTap = CleverTap.sharedInstance()
private lazy var sharedManager: SharedManager = {
return SharedManager(forAppGroup: "group.com.clevertap.demo10")
}()
override func viewDidLoad() {
super.viewDidLoad()
CleverTap.setDebugLevel(1)
if let userId = sharedManager.userId {
cleverTap.onUserLogin(["Identity":userId])
}
self.loadingIndicator.startAnimating()
}
func didReceive(_ notification: UNNotification) {
sharedManager.persistLastPushNotification(withContent: notification.request.content)
let content = notification.request.content
guard
let latString = content.userInfo["latitude"] as? String,
let latitude = Double(latString),
let lonString = content.userInfo["longitude"] as? String,
let longitude = Double(lonString)
else { return }
self.textLabel.text = "Location (\(latString), \(lonString))"
let mapboxCoordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
let options = SnapshotOptions(
mapIdentifiers: ["mapbox.streets"],
centerCoordinate: mapboxCoordinate,
zoomLevel: 13,
size: CGSize(width: 200, height: 200))
let markerOverlay = Marker(
coordinate: mapboxCoordinate,
size: .small,
iconName: "rocket"
)
markerOverlay.color = .purple
options.overlays = [markerOverlay]
let mapboxAccessToken = Bundle.main.infoDictionary!["MGLMapboxAccessToken"] as! String
let snapshot = Snapshot(options: options, accessToken: mapboxAccessToken)
let _ = snapshot.generateImage(completionHandler: { (image, error) in
self.loadingIndicator.stopAnimating()
self.mapImageView.image = image
})
cleverTap.recordEvent("NotificationDidShowLocation",
withProps: ["lat": "\(mapboxCoordinate.latitude)", "lon":"\(mapboxCoordinate.longitude)"])
}
func didReceive(_ response: UNNotificationResponse,
completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Void){
let action = response.actionIdentifier
switch (action) {
case "accept":
self.textLabel.textColor = UIColor.green
self.textLabel.text = "You accepted!"
case "decline":
self.textLabel.textColor = UIColor.red
self.textLabel.text = "You declined :("
case "dismiss":
completion(.dismiss)
default:
break
}
}
}
|
// All credit to Codecademy
// Declaring all variables
var dogAge: Int = 10
var earlyYears: Int = 0
var laterYears: Int = 0
var humanYears = 0
//Early Years assigned a value
earlyYears = 21
//Later years is calculated
laterYears = (dogAge - 2) * 4
//early years and later years together
//makes human years
humanYears = earlyYears + laterYears
// Cute little printoff
print("My name is Butch. Ruff, ruff, I am \(humanYears) years old in human years.")
|
import Foundation
import Shared
extension Rating {
static let fixture = Rating.init(source: "test_source", value: "test_value")
}
|
//
// PinFriend.swift
// Pin
//
// Created by Ken on 6/21/14.
// Copyright (c) 2014 Bacana. All rights reserved.
//
import Foundation
class PinFriend: NSObject {
var name: NSString? = nil
var number: NSString? = nil
var location: Location? = nil
var map: UIImage? = nil
var city: NSString? = nil
// MARK: - Public Methods -
init(friendNumber: NSString?, friendLocation: Location?) {
super.init()
name = friendNumber
number = friendNumber
location = friendLocation
if friendLocation?.location.coordinate.latitude == 0 ||
friendLocation?.location.coordinate.latitude == nil { return }
map = MapUtil().makeMapThumb(cellImageSize, location: friendLocation, zoom: 16)
MapUtil().getCity(location, gotCity: { (cityname: NSString?) in
self.city = cityname
})
}
init(friendName: NSString?, friendNumber: NSString?, friendLocation: Location?) {
super.init()
name = friendName
number = friendNumber
location = friendLocation
if friendLocation?.location.coordinate.latitude == 0 ||
friendLocation?.location.coordinate.latitude == nil { return }
map = MapUtil().makeMapThumb(cellImageSize, location: friendLocation, zoom: 16)
MapUtil().getCity(location, gotCity: { (cityname: NSString?) in
self.city = cityname
})
}
func updateLocation(newLocation: Location?) {
if !(isLocationValid(newLocation)) { return }
map = MapUtil().makeMapThumb(cellImageSize, location: newLocation, zoom: 16)
MapUtil().getCity(newLocation, gotCity: { (cityname: NSString?) in
self.city = cityname
})
location = newLocation
}
// MARK: - Private Methods -
init(coder aDecoder: NSCoder!) {
super.init()
name = aDecoder.decodeObjectForKey("name") as? NSString
number = aDecoder.decodeObjectForKey("number") as? NSString
location = aDecoder.decodeObjectForKey("location") as? Location
map = aDecoder.decodeObjectForKey("map") as? UIImage
city = aDecoder.decodeObjectForKey("city") as? NSString
}
func encodeWithCoder(aCoder: NSCoder!) {
aCoder.encodeObject(name!, forKey: "name")
aCoder.encodeObject(number!, forKey: "number")
if (location != nil) {
aCoder.encodeObject(location!, forKey: "location")
}
if (map != nil) {
aCoder.encodeObject(map!, forKey: "map")
}
if (city != nil) {
aCoder.encodeObject(city!, forKey: "city")
}
}
private func isLocationValid(location: Location?) -> Bool {
return !(location?.location.coordinate.latitude == 0.0 || location? == nil)
}
}
|
//
// UIHelper.swift
// RBC Money Coach
//
// Created by Applied Innovation on 2015-06-19.
// Copyright (c) 2015 Applied Innovation. All rights reserved.
//
import UIKit
class UIHelper: UIStoryboardSegue {
func prettyButtons(button: AnyObject, radius: Float, maskToBounds: Bool){
}
}
|
//
// GenreModel.swift
// radio
//
// Created by MacBook 13 on 7/10/18.
// Copyright © 2018 MacBook 13. All rights reserved.
//
import Foundation
class GenreModel {
var id:Int?=nil
var name:String?=nil
var img:String?=nil
}
|
public protocol ResolveDependency {
func resolve<Service>(_: Service.Type, name: String?) -> Service?
}
public extension ResolveDependency {
func resolve<Service>(name: String? = nil) -> Service? {
resolve(Service.self, name: name)
}
}
|
//
// HistoryViewController.swift
// TakeUrPill
//
// Created by Alessio Roberto on 14/07/2018.
// Copyright © 2018 Alessio Roberto. All rights reserved.
//
import IntentsUI
import UIKit
struct ConfigureHistory {
let controller: HistoryController
}
final class HistoryViewController: BaseViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var viewContainer: UIView!
var presenter: HistoryManageable?
var configure: ConfigureHistory?
private var siriVC: INUIAddVoiceShortcutViewController?
private lazy var notification = NotificationCenter.default
private var dataSource: TableViewDataSource<Pill>?
override func viewDidLoad() {
super.viewDidLoad()
notification.addUniqueObserver(self,
selector: #selector(reload),
name: UIApplication.willEnterForegroundNotification,
object: nil)
self.title = NSLocalizedString("history.title", comment: "")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let history = presenter?.getUserHistory() {
pillsDidLoad(history)
}
let siriButton: INUIAddVoiceShortcutButton = INUIAddVoiceShortcutButton(style: INUIAddVoiceShortcutButtonStyle.white)
siriButton.frame.size = self.viewContainer.frame.size
siriButton.addTarget(self, action: #selector(showSiri), for: .touchUpInside)
viewContainer.addSubview(siriButton)
viewContainer.sizeToFit()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let information = presenter?.information {
activitySetup(information)
}
}
deinit {
notification.removeObserver(self)
}
@IBAction func closeButtonPressed(_ sender: Any) {
configure?.controller.dismiss()
}
@IBAction func eraseHistoryButtonPressed(_ sender: Any) {
if let presenter = presenter, presenter.eraseUserHistory() {
dataSource?.cleanDataSource()
tableView.reloadData()
} else {
logger("Error erasing file")
}
}
@objc func reload() {
if let history = presenter?.getUserHistory() {
pillsDidLoad(history)
tableView.reloadData()
}
}
@objc func showSiri() {
siriVC = presenter?.showSiriViewController()
if let siriVC = siriVC {
siriVC.delegate = self
self.present(siriVC, animated: true, completion: nil)
}
}
private func pillsDidLoad(_ pills: [Pill]) {
dataSource = .make(for: pills)
tableView.dataSource = dataSource
}
}
extension HistoryViewController: INUIAddVoiceShortcutViewControllerDelegate {
func addVoiceShortcutViewController(_ controller: INUIAddVoiceShortcutViewController,
didFinishWith voiceShortcut: INVoiceShortcut?,
error: Error?) {
if let error = error {
logger(error)
} else {
logger(voiceShortcut?.invocationPhrase)
}
siriVC?.dismiss(animated: true, completion: nil)
}
func addVoiceShortcutViewControllerDidCancel(_ controller: INUIAddVoiceShortcutViewController) {
logger("no shortcut created")
siriVC?.dismiss(animated: true, completion: nil)
}
}
|
//
// ViewController.swift
// nuevatarea
//
// Created by John Balcazar on 9/05/16.
// Copyright © 2016 JohnBalcazar. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var name: UITextField!
@IBOutlet weak var city: UITextField!
@IBOutlet weak var country: UITextField!
@IBOutlet weak var mensaje: UILabel!
@IBOutlet weak var lastName: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func nombre(sender: AnyObject) { mensaje.text! = "tu nombre es \(name.text!)"
}
@IBAction func apellido(sender: AnyObject) { mensaje.text! =
"tu apellido es \(lastName.text!)"
}
@IBAction func ciudad(sender: AnyObject) { mensaje.text! = "tu ciudad es \(city.text!)"
}
@IBAction func pais(sender: AnyObject) { mensaje.text! = "tu pais es \(country.text!)"
view.endEditing(true)
}
}
//comentario
|
//
// PaymentCell.swift
// TaxiApp
//
// Created by Hundily Cerqueira on 18/05/20.
// Copyright © 2020 Hundily Cerqueira. All rights reserved.
//
import UIKit
class PaymentCell: UITableViewCell {
@IBOutlet weak var viewCamera: UIView!
override func awakeFromNib() {
super.awakeFromNib()
self.selectionStyle = .none
viewCamera.addShandowView(radius: 8, cornerRadius: 16)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
extension PaymentCell: UITextFieldDelegate {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.endEditing(true)
}
}
|
//
// APIKeys.swift
// desafio-ios-gabriel-leal
//
// Created by Gabriel Sousa on 02/04/20.
// Copyright © 2020 Gabriel Sousa. All rights reserved.
//
import Foundation
import CryptoSwift
struct ParamKeys {
static let apikey = "apikey"
static let hash = "hash"
static let timeStamp = "ts"
static let limit = "limit"
static let offset = "offset"
static let searchName = "nameStartsWith"
}
struct ApiKeys {
static func getCharactersParams(offset: Int = 0) -> [String: Any] {
let timeStamp = Int(Date().timeIntervalSince1970)
let hash = "\(timeStamp)\(StaticStrings.kApiPrivatKey)\(StaticStrings.kApiPublicKey)"
return [
ParamKeys.apikey : StaticStrings.kApiPublicKey,
ParamKeys.timeStamp : timeStamp,
ParamKeys.hash : hash.md5(),
ParamKeys.offset : offset
]
}
static func getComicsParams() -> [String: Any] {
let timeStamp = Int(Date().timeIntervalSince1970)
let hash = "\(timeStamp)\(StaticStrings.kApiPrivatKey)\(StaticStrings.kApiPublicKey)"
return [
ParamKeys.apikey : StaticStrings.kApiPublicKey,
ParamKeys.timeStamp : timeStamp,
ParamKeys.hash : hash.md5()
]
}
}
|
//
// Visual.swift
// imagefy
//
// Created by Alan Magalhães Lira on 21/05/16.
// Copyright © 2016 Alan M. Lira. All rights reserved.
//
import UIKit
public class UIDesign {
class func viewShadowPath(layer: CALayer, bounds: CGRect, radius: CGFloat, shadowOffset: CGSize, masksToBounds: Bool) {
let shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: radius)
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowOffset = shadowOffset
layer.shadowOpacity = 0.4
layer.cornerRadius = radius
layer.masksToBounds = masksToBounds
layer.shadowPath = shadowPath.CGPath
}
class func viewCornerRadius(layer: CALayer, bounds: CGRect, byRoundingCorners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: byRoundingCorners, cornerRadii: CGSizeMake(radius, radius))
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = path.CGPath
layer.mask = maskLayer
layer.masksToBounds = true
}
}
|
//
// LanguageInfo.swift
// Westeros Translator
//
// Created by Raymond An on 4/6/20.
// Copyright © 2020 Raymond An. All rights reserved.
//
import Foundation
struct LanguageInfo {
var translated: String?
var text: String?
}
|
public protocol SettingsStoreProtocol {
var settings: Settings { get set }
}
|
// SwiftUIPlayground
// https://github.com/ralfebert/SwiftUIPlayground/
import SwiftUI
struct CounterView: View {
let name: String
@State var count = 1
var body: some View {
Button("Counter \(name) \(count)") { self.count += 1 }
.padding()
.border(Color.blue)
}
}
/// Demonstrates that SwiftUI state is coupled to view appearance / disappearance
struct StateExampleView: View {
@State var outerCount = 1
@State var showB = false
var body: some View {
VStack {
Button("Outer Counter \(outerCount)") { self.outerCount += 1 }
.padding()
Toggle(isOn: $showB) {
Text("Toggle A/B")
}
if showB {
CounterView(name: "B")
} else {
CounterView(name: "A")
}
if showB {
CounterView(name: "B")
} else {
CounterView(name: "A")
}
CounterView(name: "C")
}
.border(Color.red)
.padding()
}
}
struct StateExampleView_Previews: PreviewProvider {
static var previews: some View {
StateExampleView()
}
}
|
//
// MenuViewController.swift
// MenuBar
//
// Created by Luka Kerr on 27/3/17.
// Copyright © 2017 Luka Kerr. All rights reserved.
//
import Cocoa
class MenuViewController: NSViewController {
let fieldBackgroundColor = NSColor(red:0.15, green:0.15, blue:0.15, alpha:1.0)
let fieldBorderColor = NSColor(red:0.15, green:0.15, blue:0.15, alpha:1.0)
let fieldTextColor = NSColor(red:0.43, green:0.43, blue:0.43, alpha:1.0)
@IBOutlet weak var hex: NSTextField!
@IBOutlet weak var red: NSTextField!
@IBOutlet weak var green: NSTextField!
@IBOutlet weak var blue: NSTextField!
@IBOutlet weak var hexOutput: NSTextField!
@IBOutlet weak var rgbOutput: NSTextField!
@IBOutlet weak var UIColorLabel: NSTextField!
@IBOutlet weak var NSColorLabel: NSTextField!
func setTextDesign(textField: NSTextField) {
textField.wantsLayer = true
let textFieldLayer = CALayer()
textField.layer = textFieldLayer
textField.backgroundColor = fieldBackgroundColor
textField.layer?.backgroundColor = fieldBackgroundColor.cgColor
textField.layer?.borderColor = fieldBorderColor.cgColor
textField.layer?.borderWidth = 1
textField.layer?.cornerRadius = 5
textField.textColor = fieldTextColor
}
override func viewDidLoad() {
super.viewDidLoad()
setTextDesign(textField: hex)
setTextDesign(textField: red)
setTextDesign(textField: green)
setTextDesign(textField: blue)
}
override func viewWillAppear() {
self.view.window?.appearance = NSAppearance(named: NSAppearanceNameVibrantDark)
}
// HEX to RGB
func hexToRgb(hex: String) -> (String, String, String) {
if hex != "" {
if hex.characters.count == 6 {
let bigint = Int(hex, radix: 16)
if bigint != nil {
let r = (bigint! >> 16) & 255
let g = (bigint! >> 8) & 255
let b = bigint! & 255
let hexUIColor = "UIColor(red: " + String(format: "%.2f", Double(r)/255) + ", green: " + String(format: "%.2f", Double(g)/255) + ", blue: " + String(format: "%.2f", Double(b)/255) + ", alpha: 1)"
let hexNSColor = "NSColor(red: " + String(format: "%.2f", Double(r)/255) + ", green: " + String(format: "%.2f", Double(g)/255) + ", blue: " + String(format: "%.2f", Double(b)/255) + ", alpha: 1)"
let rgbResult = "rgb(" + String(r) + ", " + String(g) + ", " + String(b) + ")"
return(hexUIColor, hexNSColor, rgbResult)
}
}
}
return("", "", "")
}
// RGB to HEX
func rgbToHex(r: String, g: String, b: String) -> (String, String, String) {
if let r = Int(r), let g = Int(g), let b = Int(b) {
if (0 ... 255 ~= r) && (0 ... 255 ~= g) && (0 ... 255 ~= b) {
var result = String(((1 << 24) + (r << 16) + (g << 8) + b), radix: 16)
result.remove(at: result.startIndex)
let hexResult = "#" + result
let rgbUIColor = "UIColor(red: " + String(format: "%.2f", Double(r)/255) + ", green: " + String(format: "%.2f", Double(g)/255) + ", blue: " + String(format: "%.2f", Double(b)/255) + ", alpha: 1)"
let rgbNSColor = "NSColor(red: " + String(format: "%.2f", Double(r)/255) + ", green: " + String(format: "%.2f", Double(g)/255) + ", blue: " + String(format: "%.2f", Double(b)/255) + ", alpha: 1)"
return(hexResult, rgbUIColor, rgbNSColor)
}
}
return ("", "", "")
}
override func keyUp(with event: NSEvent) {
let r = red.stringValue
let g = green.stringValue
let b = blue.stringValue
let (hexUIColor, hexNSColor, rgbResult) = hexToRgb(hex: hex.stringValue)
let (hexResult, rgbUIColor, rgbNSColor) = rgbToHex(r: r, g: g, b: b)
// Show hexUIColor if rgbUIColor doesnt exists
if rgbUIColor == "" {
UIColorLabel.stringValue = hexUIColor
} else {
UIColorLabel.stringValue = rgbUIColor
}
// Show hexNSColor if rgbNSColor doesnt exist
if rgbNSColor == "" {
NSColorLabel.stringValue = hexNSColor
} else {
NSColorLabel.stringValue = rgbNSColor
}
// Show rgb input value if converted hex value doesnt exists
if (r.characters.count > 0 && r.characters.count < 4) && (g.characters.count > 0 && g.characters.count < 4) && (b.characters.count > 0 && b.characters.count < 4) {
rgbOutput.stringValue = "rgb(" + red.stringValue + ", " + green.stringValue + ", " + blue.stringValue + ")"
} else {
rgbOutput.stringValue = rgbResult
}
// Show hex input value if converted rgb value doesnt exists
if hexResult == "" {
if hex.stringValue.characters.count == 6 {
hexOutput.stringValue = "#" + hex.stringValue.uppercased()
} else {
hexOutput.stringValue = ""
}
} else {
hexOutput.stringValue = hexResult.uppercased()
}
}
@IBAction func quit(_ sender: NSButton) {
NSApplication.shared().terminate(self)
}
// Clear all input and labels when button pressed
@IBAction func clear(_ sender: NSButton) {
hex.stringValue = ""
red.stringValue = ""
green.stringValue = ""
blue.stringValue = ""
hexOutput.stringValue = ""
rgbOutput.stringValue = ""
UIColorLabel.stringValue = ""
NSColorLabel.stringValue = ""
}
}
|
//
// FirebaseClient.swift
// Flykeart App
//
// Created by Akhil Pothana on 5/28/19.
// Copyright © 2019 Federico Brandt. All rights reserved.
//
// A singleton for performing all interactions with Firebase
import Foundation
import FirebaseDatabase
struct FirebaseClient {
static let currentOrdersRef = Database.database().reference().child("CurrentOrders")
static let servedOrdersRef = Database.database().reference().child("ServedOrders")
static func uploadMenuSelection(seat: String, name: String, snack: String, drink: String) {
let orderItem = ["seat" : seat, "name" : name, "snack" : snack, "drink" : drink] as [String : Any]
currentOrdersRef.child("seat-\(seat)").updateChildValues(orderItem) { (error, ref) in
if let error = error {
print(error.localizedDescription)
return
}
}
}
static func uploadServed(seat: String, name: String, snack: String, drink: String) {
let orderItem = ["seat" : seat, "name" : name, "snack" : snack, "drink" : drink] as [String : Any]
servedOrdersRef.child("seat-\(seat)").updateChildValues(orderItem) { (error, ref) in
if let error = error {
print(error.localizedDescription)
return
}
}
}
// Download the current list of orders as a dictionary
// With .observer, we are listening for new orders so the Flight attendant
// view is automatically updated
static func getNewOrders(completion : @escaping (Order?) -> ()) -> Void {
//MARK: - LISTENERS FIREBASE
currentOrdersRef.observe(.childAdded, with: { (snapshot) in
let postDict = snapshot.value as! [String : String]
let order = Order(orderItems: postDict)
completion(order)
})
currentOrdersRef.observe(.childRemoved, with: { (snapshot) in
})
}
static func getServedOrders(completion : @escaping (Order?) -> ()) -> Void {
//MARK: - LISTENERS FIREBASE
servedOrdersRef.observe(.childAdded, with: { (snapshot) in
let postDict = snapshot.value as! [String : String]
let order = Order(orderItems: postDict)
completion(order)
})
servedOrdersRef.observe(.childRemoved, with: { (snapshot) in
})
}
// Delete an order from the list
static func deleteOrder(seatNumber : String) {
currentOrdersRef.child("seat-\(seatNumber)").removeValue()
}
}
|
//
// HistorySummaryViewController.swift
// Coremelysis
//
// Created by Artur Carneiro on 21/09/20.
// Copyright © 2020 Rafael Galdino. All rights reserved.
//
import UIKit
/// The representation of the History screen summary
final class HistorySummaryViewController: UIViewController {
// - MARK: Properties
@AutoLayout private var numberOfEntriesLabel: UILabel
@AutoLayout private var positiveEntriesLabel: UILabel
@AutoLayout private var negativeEntriesLabel: UILabel
@AutoLayout private var neutralEntriesLabel: UILabel
/// The ViewModel bound to this type.
private var viewModel: HistorySummaryViewModel
// - MARK: Init
init(viewModel: HistorySummaryViewModel = HistorySummaryViewModel()) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// - MARK: Life cycle
override func viewDidLoad() {
super.viewDidLoad()
setupNumberOfEntriesLabel()
setupEntriesLabels()
layoutConstraints()
}
// - MARK: Update
func update(with viewModel: HistorySummaryViewModel) {
self.viewModel = viewModel
self.numberOfEntriesLabel.text = viewModel.numberOfEntries
self.positiveEntriesLabel.text = viewModel.numberOfPositiveEntries
self.negativeEntriesLabel.text = viewModel.numberOfNegativeEntries
self.neutralEntriesLabel.text = viewModel.numberOfNeutralEntries
}
// - MARK: Layout
private func setupNumberOfEntriesLabel() {
numberOfEntriesLabel.text = viewModel.numberOfEntries
numberOfEntriesLabel.font = .preferredFont(forTextStyle: .largeTitle)
numberOfEntriesLabel.numberOfLines = 0
numberOfEntriesLabel.textColor = .coremelysisAccent
numberOfEntriesLabel.textAlignment = .center
view.addSubview(numberOfEntriesLabel)
}
private func setupEntriesLabels() {
positiveEntriesLabel.backgroundColor = .coremelysisPositive
negativeEntriesLabel.backgroundColor = .coremelysisNegative
neutralEntriesLabel.backgroundColor = .coremelysisNeutral
positiveEntriesLabel.font = .preferredFont(forTextStyle: .title1)
negativeEntriesLabel.font = .preferredFont(forTextStyle: .title1)
neutralEntriesLabel.font = .preferredFont(forTextStyle: .title1)
positiveEntriesLabel.textColor = .coremelysisBackground
negativeEntriesLabel.textColor = .coremelysisBackground
neutralEntriesLabel.textColor = .coremelysisBackground
positiveEntriesLabel.text = viewModel.numberOfPositiveEntries
negativeEntriesLabel.text = viewModel.numberOfNegativeEntries
neutralEntriesLabel.text = viewModel.numberOfNeutralEntries
positiveEntriesLabel.textAlignment = .center
negativeEntriesLabel.textAlignment = .center
neutralEntriesLabel.textAlignment = .center
view.addSubview(positiveEntriesLabel)
view.addSubview(negativeEntriesLabel)
view.addSubview(neutralEntriesLabel)
}
private func layoutConstraints() {
NSLayoutConstraint.activate([
numberOfEntriesLabel.topAnchor.constraint(equalTo: view.topAnchor),
numberOfEntriesLabel.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.5),
numberOfEntriesLabel.widthAnchor.constraint(equalTo: view.widthAnchor),
numberOfEntriesLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
positiveEntriesLabel.topAnchor.constraint(equalTo: numberOfEntriesLabel.bottomAnchor),
positiveEntriesLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor),
positiveEntriesLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor,
constant: -DesignSystem.Spacing.default),
positiveEntriesLabel.trailingAnchor.constraint(equalTo: neutralEntriesLabel.leadingAnchor),
neutralEntriesLabel.topAnchor.constraint(equalTo: numberOfEntriesLabel.bottomAnchor),
neutralEntriesLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
neutralEntriesLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor,
constant: -DesignSystem.Spacing.default),
neutralEntriesLabel.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.34),
negativeEntriesLabel.topAnchor.constraint(equalTo: numberOfEntriesLabel.bottomAnchor),
negativeEntriesLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor),
negativeEntriesLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor,
constant: -DesignSystem.Spacing.default ),
negativeEntriesLabel.leadingAnchor.constraint(equalTo: neutralEntriesLabel.trailingAnchor)
])
}
}
|
//
// CampsDetailTableCell.swift
// CureadviserApp
//
// Created by BekGround-2 on 24/03/17.
// Copyright © 2017 BekGround-2. All rights reserved.
//
import UIKit
class CampsDetailTableCell: UITableViewCell {
@IBOutlet var iconImgbtn: UIButton!
@IBOutlet var lblText: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// GroupLoader.swift
// AdvancedCodable
//
// Created by Felipe Costa on 9/13/19.
// Copyright © 2019 Felipe Costa. All rights reserved.
//
import Foundation
class GroupLoader {
class func load(jsonFileName: String) -> Response? {
var response: Response?
let jsonDecoder = JSONDecoder()
// jsonDecoder.dateDecodingStrategy = .iso8601
if let jsonFileUrl = Bundle.main.url(forResource: jsonFileName, withExtension: ".json"),
let jsonData = try? Data(contentsOf: jsonFileUrl) {
print(jsonData)
response = try? jsonDecoder.decode(Response.self, from: jsonData)
}
return response
}
}
|
//
// AudioViewController.swift
// Spot
//
// Created by george on 27/01/2017.
// Copyright © 2017 george. All rights reserved.
//
import UIKit
import AVFoundation
class AudioViewController: UIViewController
{
var post: Post! = nil
@IBOutlet weak var background: UIImageView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var button: UIButton!
override func viewDidLoad()
{
background.image = post.image
imageView.image = post.image
label.text = post.name
button.setTitle("Pause", for: .normal)
downloadFileFromUrl(url: URL(string: post.previewUrl)!)
}
func downloadFileFromUrl(url: URL)
{
var downloadTask = URLSessionDownloadTask()
downloadTask = URLSession.shared.downloadTask(with: url, completionHandler:
{
customURL, response, error in
self.playSong(url: customURL!)
})
downloadTask.resume()
}
func playSong(url: URL)
{
do{
player = try AVAudioPlayer(contentsOf: url)
player.prepareToPlay()
player.play()
}
catch{
print(error)
}
}
@IBAction func playOrPause(_ sender: AnyObject)
{
if player.isPlaying
{
player.pause()
button.setTitle("Play", for: .normal)
}
else
{
player.play()
button.setTitle("Pause", for: .normal)
}
}
}
|
//
// PIXSprite.swift
// PixelKit
//
// Created by Anton Heestand on 2018-08-28.
// Open Source - MIT License
//
import RenderKit
import Resolution
import SpriteKit
import PixelColor
open class PIXSprite: PIXContent, NODEResolution {
override open var shaderName: String { return "spritePIX" }
// MARK: - Public Properties
@LiveResolution("resolution") public var resolution: Resolution = ._128 { didSet { reSize(); applyResolution { [weak self] in self?.render() } } }
@available(*, deprecated, renamed: "backgroundColor")
public var bgColor: PixelColor {
get { backgroundColor }
set { backgroundColor = newValue }
}
public var backgroundColor: PixelColor = .black {
didSet {
#if os(macOS)
scene?.backgroundColor = backgroundColor.nsColor
#else
scene?.backgroundColor = backgroundColor.uiColor
#endif
render()
}
}
var scene: SKScene?
var sceneView: SKView?
open override var liveList: [LiveWrap] {
[_resolution] + super.liveList
}
required public init(at resolution: Resolution = .auto(render: PixelKit.main.render)) {
fatalError("Please use PIXSprite Sub Classes.")
}
public init(at resolution: Resolution = .auto(render: PixelKit.main.render), name: String, typeName: String) {
self.resolution = resolution
super.init(name: name, typeName: typeName)
setupSprite()
}
public required init(from decoder: Decoder) throws {
try super.init(from: decoder)
setupSprite()
}
func setupSprite() {
let size = (resolution / Resolution.scale).size
scene = SKScene(size: size)
#if os(macOS)
scene!.backgroundColor = backgroundColor.nsColor
#else
scene!.backgroundColor = backgroundColor.uiColor
#endif
sceneView = SKView(frame: CGRect(origin: .zero, size: size))
sceneView!.allowsTransparency = true
sceneView!.presentScene(scene!)
applyResolution { [weak self] in
self?.render()
}
}
func reSize() {
let size = (resolution / Resolution.scale).size
scene?.size = size
sceneView?.frame = CGRect(origin: .zero, size: size)
}
}
|
//
// LimitPickerTableViewCell.swift
// SimpleAgricolaScorer
//
// Created by Benjamin Wishart on 2015-04-22.
// Copyright (c) 2015 Benjamin Wishart. All rights reserved.
//
import UIKit
protocol LimitPickerDelegate {
func limitPickerView(limitPicker: UIPickerView, didSelectRow row: Int)
}
class LimitPickerTableViewCell: UITableViewCell, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet var LimitPicker: UIPickerView!
var upperLimit: Int = 1;
var chosenValue: Int?;
var delegate: LimitPickerDelegate?
override func awakeFromNib() {
super.awakeFromNib()
LimitPicker.delegate = self;
LimitPicker.dataSource = self;
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return String(row);
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
chosenValue = row;
delegate?.limitPickerView(LimitPicker, didSelectRow: row)
NSNotificationCenter.defaultCenter().postNotificationName("limitPickerDidChange", object: nil)
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return upperLimit;
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1;
}
}
|
//
// ViewController.swift
// Pursuit-Core-iOS-CocoaPods-Lab
//
// Created by Oscar Victoria Gonzalez on 3/3/20.
// Copyright © 2020 Oscar Victoria Gonzalez . All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var firstView = mainView()
var randomUsers = [User]() {
didSet {
DispatchQueue.main.async {
self.firstView.tableView.reloadData()
}
}
}
override func loadView() {
view = firstView
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .red
configureTableView()
fetchUsers()
}
private func configureTableView() {
firstView.tableView.dataSource = self
firstView.tableView.delegate = self
firstView.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "userCell")
}
private func fetchUsers() {
APIClient.getUsers { (result) in
switch result {
case .failure(let appError):
print("app Error \(appError)")
case .success(let user):
self.randomUsers = user
}
}
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return randomUsers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath)
cell = UITableViewCell(style: .subtitle, reuseIdentifier: "userCell")
let users = randomUsers[indexPath.row]
cell.textLabel?.text = "\(users.name.first) \(users.name.last)"
cell.detailTextLabel?.text = users.email
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let users = randomUsers[indexPath.row]
let detailVC = DetailViewController()
detailVC.users = users
navigationController?.pushViewController(detailVC, animated: true)
}
}
|
//
// ViewController.swift
// Game2048
//
// Created by admin on 10/26/16.
// Copyright © 2016 admin. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var score: UILabel!
var b = Array(repeating: Array(repeating: 0, count: 4), count: 4)
override func viewDidLoad() {
super.viewDidLoad()
let directions: [UISwipeGestureRecognizerDirection] = [.right, .left, .up, .down]
for directions in directions {
let gesture = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGesture(gesture:)))
gesture.direction = directions
self.view.addGestureRecognizer(gesture)
}
randomNum(type: -1)
}
func respondToSwipeGesture(gesture : UIGestureRecognizer) {
if let swipeGesture = gesture as? UISwipeGestureRecognizer {
switch swipeGesture.direction {
case UISwipeGestureRecognizerDirection.left: randomNum(type: 0)
case UISwipeGestureRecognizerDirection.right: randomNum(type: 1)
case UISwipeGestureRecognizerDirection.up: randomNum(type: 2)
case UISwipeGestureRecognizerDirection.down: randomNum(type: 3)
default:
break
}
}
}
func convertNumberLabel(numLabel : Int, value : String) {
let label = self.view.viewWithTag(numLabel) as! UILabel
label.text = value
}
func changeBackColor(numLabel : Int, color : UIColor) {
let label = self.view.viewWithTag(numLabel) as! UILabel
label.backgroundColor = color
}
func transfer() {
for i in 0..<4 {
for j in 0..<4 {
let numLabel = 100 + (i * 4) + j
convertNumberLabel(numLabel: numLabel, value: String(b[i][j]))
switch (b[i][j]) {
case 2,4:
changeBackColor(numLabel: numLabel, color: UIColor.cyan)
case 8,16:
changeBackColor(numLabel: numLabel, color: UIColor.green)
case 32:
changeBackColor(numLabel: numLabel, color: UIColor.orange)
case 64:
changeBackColor(numLabel: numLabel, color: UIColor.red)
default:
changeBackColor(numLabel: numLabel, color: UIColor.brown)
}
}
}
}
func randomNum(type : Int) {
switch (type) {
case 0: left()
case 1: right()
case 2: up()
case 3: down()
default: break
}
if (checkWin()) {
let messBox = UIAlertController(title: "You Win", message: "2048", preferredStyle: .alert)
messBox.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
messBox.addAction(UIAlertAction(title: "Reset", style: .default, handler: {(action:UIAlertAction!) in self.resetAll()
}))
self.present(messBox, animated: true, completion: nil)
}
if (checkRandom()) {
var rnlabelX = arc4random_uniform(4)
var rnlabelY = arc4random_uniform(4)
let rdNum = arc4random_uniform(2) == 0 ? 2 : 4
while (b[Int(rnlabelX)][Int(rnlabelY)] != 0) {
rnlabelX = arc4random_uniform(4)
rnlabelY = arc4random_uniform(4)
}
b[Int(rnlabelX)][Int(rnlabelY)] = rdNum
let numLabel = 100 + (Int(rnlabelX) * 4) + Int(rnlabelY)
convertNumberLabel(numLabel: numLabel , value: String(rdNum))
transfer()
} else if checkGameOver() {
let messBox = UIAlertController(title: "You Lose", message: "You can't move", preferredStyle: .alert)
messBox.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
self.present(messBox, animated: true, completion: nil)
}
}
func checkRandom() -> Bool {
for i in 0..<4 {
for j in 0..<4 {
if b[i][j] == 0 {
return true
}
}
}
return false
}
func up() {
for col in 0..<4 {
var check = false
for row in 1..<4 {
var tx = row
if (b[row][col]) == 0 {
continue
}
for rowc in stride(from: row - 1, to: -1, by: -1) {
if (rowc != -1) {
if (b[rowc][col] != 0 && (b[rowc][col] != b[row][col] || check)) {
break
} else {
tx = rowc
}
}
}
if (tx == row) {
continue
}
if (b[row][col] == b[tx][col]) {
check = true
getScore(value: b[tx][col])
b[tx][col] *= 2
} else {
b[tx][col] = b[row][col]
}
b[row][col] = 0
}
}
}
func down() {
for col in 0..<4 {
var check = false
for row in 0..<4 {
var tx = row
if(b[row][col]) == 0 {
continue
}
for rowc in stride(from: row + 1, to: 4, by: 1) {
if (b[rowc][col] != 0 && (b[rowc][col] != b[row][col] || check)) {
break
} else {
tx = rowc
}
}
if (tx == row) {
continue
}
if (b[row][col] == b[tx][col]) {
check = true
getScore(value: b[tx][col])
b[tx][col] *= 2
} else {
b[tx][col] = b[row][col]
}
b[row][col] = 0
}
}
}
func left() {
for row in 0..<4 {
var check = false
for col in 1..<4 {
var ty = col
if (b[row][col] == 0) {
continue
}
for colc in stride(from: col - 1, to: -1, by: -1) {
if (b[row][colc] != 0 && (b[row][colc] != b[row][col] || check)) {
break
} else {
ty = colc
}
}
if (ty == col) {
continue
}
if (b[row][ty] == b[row][col]) {
check = true
getScore(value: b[row][ty])
b[row][ty] *= 2
} else {
b[row][ty] = b[row][col]
}
b[row][col] = 0
}
}
}
func right() {
for row in 0..<4 {
var check = false
for col in stride(from: 3, to: -1, by: -1) {
var ty = col
if (b[row][col] == 0) {
continue
}
for colc in stride(from: col + 1, to: 4, by: 1) {
if (b[row][colc] != 0 && (b[row][colc] != b[row][col] || check)) {
break
} else {
ty = colc
}
}
if (ty == col) {
continue
}
if (b[row][ty] == b[row][col]) {
check = true
getScore(value: b[row][ty])
b[row][ty] *= 2
} else {
b[row][ty] = b[row][col]
}
b[row][col] = 0
}
}
}
func getScore(value : Int) {
score.text = String(Int(score.text!)! + value)
}
//Check theo 4 chieu
func checkUp(row : Int, col : Int) -> Bool {
var check = false
if b[row][col] == b[row+1][col] {
check = true
}
return check
}
func checkDown(row : Int, col : Int) -> Bool {
var check = false
if b[row][col] == b[row-1][col] {
check = false
}
return check
}
func checkLeft(row : Int, col : Int) -> Bool {
var check = false
if b[row][col] == b[row][col+1] {
check = true
}
return check
}
func checkRight(row : Int, col : Int) -> Bool {
var check = false
if b[row][col] == b[row][col-1] {
check = true
}
return check
}
func checkFull() -> Bool {
var check : Bool = false
for i in 0..<4 {
for j in 0..<4 {
if b[i][j] == 0 {
check = false
break
} else {
check = true
}
}
}
return check
}
func checkGameOver() -> Bool {
var check = true
if checkFull() {
for row in 0..<4 {
for col in 0..<4 {
if (row < 3 && checkUp(row: row, col: col)) {
return false
}
if (row > 0 && checkDown(row: row, col: col)) {
return false
}
if (col < 3 && checkLeft(row: row, col: col)) {
return false
}
if (col > 0 && checkRight(row: row, col: col)) {
return false
}
}
}
} else {
check = false
}
return check
}
@IBAction func action_Reset(_ sender: UIButton) {
resetAll()
}
func checkWin() -> Bool{
for i in 0..<4 {
for j in 0..<4 {
if b[i][j] == 128 {
return true
}
}
}
return false
}
func resetAll() {
b = Array(repeating: Array(repeating: 0, count: 4), count: 4)
randomNum(type: -1)
score.text = "0"
}
}
|
//
// SafariExtensionViewController.swift
// ReaderTranslatorSafari
//
// Created by Viktor Kushnerov on 10/2/19.
// Copyright © 2019 Viktor Kushnerov. All rights reserved.
//
import SafariServices
class SafariExtensionViewController: SFSafariExtensionViewController {
static let shared: SafariExtensionViewController = {
let shared = SafariExtensionViewController()
shared.preferredContentSize = NSSize(width: 320, height: 240)
return shared
}()
}
|
//
// Mood.swift
// MoodTracker
//
// Created by Kevin Blom on 07/07/2019.
// Copyright © 2019 Atomische Droeftoeters. All rights reserved.
//
import SwiftUI
struct EnterableMood: Hashable, Codable, Identifiable {
var id: Int32
var moodName: String
}
class EnterableMoods {
var veryGood: EnterableMood = EnterableMood(id: 1, moodName: "Very good")
var good: EnterableMood = EnterableMood(id: 2, moodName: "Good")
var okay: EnterableMood = EnterableMood(id: 3, moodName: "Okay")
var bad: EnterableMood = EnterableMood(id: 4, moodName: "Bad")
var veryBad: EnterableMood = EnterableMood(id: 5, moodName: "Very bad")
var noMood: EnterableMood = EnterableMood(id: 0, moodName: "No mood")
var list:[EnterableMood]
init() {
list = [veryGood, good, okay, bad, veryBad]
}
func moodNameForId(id: Int32) -> String {
switch id {
case 1:
return veryGood.moodName
case 2:
return good.moodName
case 3:
return okay.moodName
case 4:
return bad.moodName
case 5:
return veryBad.moodName
default:
return noMood.moodName
}
}
}
|
//
// ItemList-CoreDataHelpers.swift
// SimpleGoceryList
//
// Created by Payton Sides on 7/13/21.
//
import CloudKit
import CoreData
import Foundation
import SwiftUI
extension ItemList {
//MARK: - Wrapped Properties
var titleDisplay: String {
title ?? ""
}
enum colors {
}
var listItems: [ListItem] {
let itemsArray = items?.allObjects as? [ListItem] ?? []
return itemsArray
}
var unpickedItems: [ListItem] {
let itemsArray = items?.allObjects as? [ListItem] ?? []
return itemsArray.filter({!$0.isPicked}).sorted(by: {$0.order < $1.order})
}
var pickedItems: [ListItem] {
let itemsArray = items?.allObjects as? [ListItem] ?? []
return itemsArray.filter({$0.isPicked}).sorted(by: {$0.order < $1.order})
}
func prepareCDToCKRecords(zoneID: CKRecordZone.ID) -> [CKRecord] {
// let parentName = objectID.uriRepresentation().absoluteString
let parentID = CKRecord.ID(zoneID: zoneID)
let parent = CKRecord(recordType: Config.itemListRecord, recordID: parentID)
parent["title"] = titleDisplay
parent["id"] = id?.uuidString
parent["timestamp"] = timestamp
var records = listItems.map { item -> CKRecord in
let childName = item.objectID.uriRepresentation().absoluteString
let childID = CKRecord.ID(recordName: childName)
let child = CKRecord(recordType: Config.itemRecord, recordID: childID)
child["name"] = item.nameDisplay
child["image"] = item.image
child["isPicked"] = item.isPicked
child["isUrgent"] = item.isUrgent
child["lastModified"] = item.lastModified
child["order"] = item.order
child["quantity"] = item.quantity
child["tiemstamp"] = item.timestamp
child["list"] = CKRecord.Reference(recordID: parentID, action: .deleteSelf)
return child
}
records.append(parent)
return records
}
}
|
//
// Auto+CoreDataProperties.swift
// gestioneParcheggi
//
// Created by atrak on 11/10/21.
//
//
import Foundation
import CoreData
extension Auto {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Auto> {
return NSFetchRequest<Auto>(entityName: "Auto")
}
@NSManaged public var nome: String?
@NSManaged public var cognome: String?
@NSManaged public var telefono: String?
@NSManaged public var targa: String?
@NSManaged public var email: String?
}
extension Auto : Identifiable {
}
|
/// Represents a Top-Level entity that has a static address
/// in the compiled binary.
protocol TopLevelEntity {
/// The label that will resolve to this entity.
var label: String { get }
}
|
//
// ViewController.swift
// Quizzler
//
// Created by Juan Rodriguez on 2020-06-24.
// Copyright © 2020 Juan Rodriguez. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var trueButton: UIButton!
@IBOutlet weak var falseButton: UIButton!
@IBOutlet weak var progressBar: UIProgressView!
@IBOutlet weak var scoreLabel: UILabel!
var quizBrain = QuizBrain() // all properties of struct immutable when declared with let
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
progressBar.progress = quizBrain.getProgress()
updateUI()
}
@IBAction func buttonPressed(_ sender: UIButton) {
let userAnswer = sender.titleLabel!.text!
let userCorrect = quizBrain.checkAnswer(answer: userAnswer)
if userCorrect {
sender.backgroundColor = UIColor.green
}
else {
sender.backgroundColor = UIColor.red
}
quizBrain.increment() // cycles to next question
progressBar.progress = quizBrain.getProgress()
Timer.scheduledTimer(timeInterval: 0.2, target:self, selector: #selector(updateUI), userInfo: nil, repeats: false)
}
@objc func updateUI() {
questionLabel.text = quizBrain.getQuestionText()
scoreLabel.text = "Score: \(quizBrain.getScore())"
trueButton.backgroundColor = UIColor.clear
falseButton.backgroundColor = UIColor.clear
}
}
|
func findUniques(_ arr: [Int]) -> [Int] {
guard arr.count != 0 else {
print("The array is empty")
return []
}
var uniques = [Int]()
let checkForDupes = Set(arr)
var runningTally = [Int : Int]()
for item in checkForDupes {
runningTally[item] = 0
}
for item in arr {
runningTally[item]! += 1
}
for (key,val) in runningTally where val == 1 {
uniques.append(key)
}
return uniques
}
|
//
// CoreDataStackManager.swift
// CoreDataSwift
//
// Created by cxjwin on 10/27/14.
// Copyright (c) 2014 cxjwin. All rights reserved.
//
import Foundation
import CoreData
import UIKit
class CoreDataStackManager: NSObject {
class var sharedInstance: CoreDataStackManager {
struct Singleton {
static var instance: CoreDataStackManager = {
var _instance: CoreDataStackManager = CoreDataStackManager()
return _instance
}()
}
return Singleton.instance
}
lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = NSBundle.mainBundle().URLForResource("WBModel", withExtension:"momd")
return NSManagedObjectModel(contentsOfURL:modelURL!)!
}()
var persistentStoreCoordinator: NSPersistentStoreCoordinator! {
if _persistentStoreCoordinator != nil {
return _persistentStoreCoordinator
}
let url = self.storeURL
if url == nil {
return nil
}
let psc = NSPersistentStoreCoordinator(managedObjectModel:self.managedObjectModel)
let options = [NSMigratePersistentStoresAutomaticallyOption : 1, NSInferMappingModelAutomaticallyOption : 1]
var error: NSError?
if (psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration:nil, URL:url, options:options, error:&error) == nil) {
fatalError("Could not add the persistent store")
return nil
}
_persistentStoreCoordinator = psc
return _persistentStoreCoordinator
}
var _persistentStoreCoordinator: NSPersistentStoreCoordinator?
var storeURL: NSURL! {
if _storeURL != nil {
return _storeURL
}
let fileManager = NSFileManager.defaultManager()
let URLs = fileManager.URLsForDirectory(.ApplicationSupportDirectory, inDomains:.UserDomainMask)
var applicationSupportDirectory = URLs[0] as NSURL
applicationSupportDirectory = applicationSupportDirectory.URLByAppendingPathComponent("com.github.cxjwin")
var error: NSError?
let properties = applicationSupportDirectory.resourceValuesForKeys([NSURLIsDirectoryKey!], error:&error)
if (properties != nil) {
let number: NSNumber = properties![NSURLIsDirectoryKey] as NSNumber
if !number.boolValue {
let description = NSLocalizedString("Could not access the application data folder.", comment: "Failed to initialize the PSC")
let reason = NSLocalizedString("Found a file in its place.", comment: "Failed to initialize the PSC")
let dict = [NSLocalizedDescriptionKey : description, NSLocalizedFailureReasonErrorKey : reason]
error = NSError(domain: "EARTHQUAKES_ERROR_DOMAIN", code:101, userInfo:dict)
fatalError("Could not access the application data folder")
return nil
}
} else {
var ok = false
if error!.code == NSFileReadNoSuchFileError {
ok = fileManager.createDirectoryAtPath(applicationSupportDirectory.path!, withIntermediateDirectories:true, attributes:nil, error:&error)
}
if !ok {
fatalError("Could not create the application data folder")
return nil
}
}
_storeURL = applicationSupportDirectory.URLByAppendingPathComponent("Weibo.storedata")
return _storeURL
}
var _storeURL: NSURL?
}
|
import UIKit
class shopdetailsViewController: UIViewController {
var info : [userinfo]? = []
@IBOutlet var shop_image: UIImageView!
@IBOutlet var shop_name: UILabel!
@IBOutlet var address: UILabel!
@IBOutlet var mobile: UILabel!
@IBOutlet var whatsapp: UILabel!
@IBOutlet var email: UILabel!
@IBOutlet var phone: UILabel!
@IBOutlet var website: UILabel!
@IBOutlet var descriptions: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
loaddata()
}
func loaddata (){
self.shop_image.getlogofromurl(info![0].logo ?? "")
shop_name.text = info![0].shopName ?? ""
address.text = info![0].address ?? ""
mobile.text = info![0].mobile ?? ""
whatsapp.text = info![0].whatsapp ?? ""
email.text = info![0].email ?? ""
phone.text = info![0].phone ?? ""
website.text = info![0].website ?? ""
descriptions.text = info![0].generalDescription ?? ""
}
}
|
//
// LocationViewModel.swift
// Weather
//
// Created by 진재명 on 8/18/19.
// Copyright © 2019 Jaemyeong Jin. All rights reserved.
//
import CoreData
import Foundation
import os
class LocationViewModel: NSObject {
let fetchedResultsController: NSFetchedResultsController<Location>
@objc dynamic var results: [LocationTableViewCellViewModel] = []
let weatherAPI: YahooWeatherAPI
init(managedObjectContext: NSManagedObjectContext, weatherAPI: YahooWeatherAPI) {
self.weatherAPI = weatherAPI
let fetchRequest: NSFetchRequest = Location.fetchRequest()
fetchRequest.sortDescriptors = [
NSSortDescriptor(key: "createdAt", ascending: true),
]
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: managedObjectContext,
sectionNameKeyPath: nil,
cacheName: nil)
self.fetchedResultsController = fetchedResultsController
super.init()
fetchedResultsController.delegate = self
NotificationCenter.default.addObserver(self,
selector: #selector(self.managedObjectContextDidSave(_:)),
name: .NSManagedObjectContextDidSave,
object: nil)
}
func performFetch() throws {
try self.fetchedResultsController.performFetch()
let fetchedObjects: [Location]! = self.fetchedResultsController.fetchedObjects
assert(fetchedObjects != nil)
self.results = fetchedObjects.enumerated().map { LocationTableViewCellViewModel(index: $0.offset, location: $0.element, weatherAPI: self.weatherAPI) }
}
@objc func managedObjectContextDidSave(_ notification: Notification) {
self.fetchedResultsController.managedObjectContext.mergeChanges(fromContextDidSave: notification)
}
var changeIsUserDriven = false
func deleteLocation(at indexPath: IndexPath, completion: @escaping (Result<Void, Error>) -> Void) {
let managedObjectContext = self.fetchedResultsController.managedObjectContext
managedObjectContext.delete(self.results[indexPath.row].location)
self.results.remove(at: indexPath.row)
completion(Result { try managedObjectContext.save() })
}
func updateLocation(at indexPath: IndexPath, completion: @escaping (Result<Void, Error>) -> Void) {
self.results[indexPath.row].updateLocation { result in
completion(result)
}
}
}
extension LocationViewModel: NSFetchedResultsControllerDelegate {
static let willChangeContentNotification = Notification.Name(rawValue: "LocationViewModelWillChangeContentNotification")
static let didChangeContentNotification = Notification.Name(rawValue: "LocationViewModelDidChangeContentNotification")
static let didInsertObjectNotification = Notification.Name(rawValue: "LocationViewModelDidInsertObjectNotification")
static let didMoveObjectNotification = Notification.Name(rawValue: "LocationViewModelDidMoveObjectNotification")
static let didDeleteObjectNotification = Notification.Name(rawValue: "LocationViewModelDidDeleteObjectNotification")
static let didUpdateObjectNotification = Notification.Name(rawValue: "LocationViewModelDidUpdateObjectNotification")
static let controllerUserInfoKey = "LocationViewModelControllerUserInfoKey"
static let objectUserInfoKey = "LocationViewModelObjectUserInfoKey"
static let indexPathUserInfoKey = "LocationViewModelIndexPathUserInfoKey"
static let newIndexPathUserInfoKey = "LocationViewModelNewIndexPathUserInfoKey"
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
NotificationCenter.default.post(name: LocationViewModel.willChangeContentNotification,
object: self,
userInfo: [LocationViewModel.controllerUserInfoKey: controller])
}
func controller(_: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
guard !self.changeIsUserDriven else {
return
}
let object: Location! = anObject as? Location
assert(object != nil)
switch type {
case .insert:
let newIndexPath: IndexPath! = newIndexPath
assert(newIndexPath != nil)
self.results.insert(LocationTableViewCellViewModel(index: newIndexPath.row, location: object, weatherAPI: self.weatherAPI), at: newIndexPath.row)
NotificationCenter.default.post(name: LocationViewModel.didInsertObjectNotification,
object: self,
userInfo: [
LocationViewModel.controllerUserInfoKey: controller,
LocationViewModel.objectUserInfoKey: object!,
LocationViewModel.newIndexPathUserInfoKey: newIndexPath!,
])
case .delete:
let indexPath: IndexPath! = indexPath
assert(indexPath != nil)
self.results.remove(at: indexPath.row)
NotificationCenter.default.post(name: LocationViewModel.didDeleteObjectNotification,
object: self,
userInfo: [
LocationViewModel.controllerUserInfoKey: controller,
LocationViewModel.objectUserInfoKey: object!,
LocationViewModel.indexPathUserInfoKey: indexPath!,
])
case .move:
let indexPath: IndexPath! = indexPath
assert(indexPath != nil)
let newIndexPath: IndexPath! = newIndexPath
assert(newIndexPath != nil)
self.results.remove(at: indexPath.row)
self.results.insert(LocationTableViewCellViewModel(index: newIndexPath.row, location: object, weatherAPI: self.weatherAPI), at: newIndexPath.row)
NotificationCenter.default.post(name: LocationViewModel.didMoveObjectNotification,
object: self,
userInfo: [
LocationViewModel.controllerUserInfoKey: controller,
LocationViewModel.objectUserInfoKey: object!,
LocationViewModel.indexPathUserInfoKey: indexPath!,
LocationViewModel.newIndexPathUserInfoKey: newIndexPath!,
])
case .update:
let indexPath: IndexPath! = indexPath
assert(indexPath != nil)
let newIndexPath: IndexPath! = newIndexPath
assert(newIndexPath != nil)
self.results[indexPath.row] = LocationTableViewCellViewModel(index: newIndexPath.row, location: object, weatherAPI: self.weatherAPI)
NotificationCenter.default.post(name: LocationViewModel.didUpdateObjectNotification,
object: self,
userInfo: [
LocationViewModel.controllerUserInfoKey: controller,
LocationViewModel.objectUserInfoKey: object!,
LocationViewModel.indexPathUserInfoKey: indexPath!,
LocationViewModel.newIndexPathUserInfoKey: newIndexPath!,
])
@unknown default:
fatalError()
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
NotificationCenter.default.post(name: LocationViewModel.didChangeContentNotification,
object: self,
userInfo: [LocationViewModel.controllerUserInfoKey: controller])
}
}
|
//
// OfferPage.swift
// Yelnur
//
// Created by Дастан Сабет on 27.03.2018.
// Copyright © 2018 Дастан Сабет. All rights reserved.
//
import UIKit
import SwiftMessages
class OfferPage: UIViewController {
enum reuseIdentifiers: String {
case offer = "offerCell"
}
var order: Order!
lazy var offers = [Offers]()
lazy var refreshControl: UIRefreshControl = {
let refresher = UIRefreshControl()
refresher.addTarget(self, action: #selector(getOffers), for: .valueChanged)
return refresher
}()
lazy var tableView: UITableView = {
let tableview = UITableView(frame: .zero, style: .grouped)
tableview.delegate = self
tableview.dataSource = self
tableview.separatorStyle = .none
tableview.addSubview(refreshControl)
tableview.register(OfferCell.self, forCellReuseIdentifier: reuseIdentifiers.offer.rawValue)
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: Size.shared.width, height: 15))
tableview.tableHeaderView = headerView
tableview.backgroundColor = .white
return tableview
}()
override func viewDidLoad() {
super.viewDidLoad()
// navigationItem.title = "№\(order.id)"
// navigationItem.title = order.title
let label = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: UIScreen.main.bounds.width, height: 60))
label.backgroundColor = UIColor.clear
label.numberOfLines = 0
label.textAlignment = NSTextAlignment.center
label.textColor = UIColor(hex: "333536")
label.font = UIFont.boldSystemFont(ofSize: 17)
label.text = Strings.offers
navigationItem.titleView = label
getOffers()
setupUI()
}
private func setupUI() {
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
navigationController?.addShadow()
}
@objc fileprivate func getOffers() {
refreshControl.beginRefreshing()
API.shared.fetch(with: Router.Client.OrderAccept.get(parameter: "\(order.id)/offers/"), onSuccess: { (response) in
switch response {
case .raw(let data):
do {
let json = try JSONDecoder().decode([Offers].self, from: data)
self.offers = json
if json.isEmpty {
Message.view.show(body: Strings.noCouriers)
}
DispatchQueue.main.async {
self.tableView.reloadData()
self.refreshControl.endRefreshing()
}
}catch let jsonError {
Alert.alert(message: jsonError.localizedDescription, controller: self)
DispatchQueue.main.async {
self.refreshControl.endRefreshing()
}
}
}
}) { (error) in
Alert.alert(message: error.message, controller: self)
DispatchQueue.main.async {
self.tableView.reloadData()
self.refreshControl.endRefreshing()
}
}
}
}
extension OfferPage: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return offers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let offerCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifiers.offer.rawValue, for: indexPath) as! OfferCell
let offer = offers[indexPath.row]
offerCell.avatar.kf.setImage(with: URL(string: offer.transport.owner.avatar!))
offerCell.username.text = offer.transport.owner.name
offerCell.typeOfUser.text = "\(offer.transport.owner.courier_type!.courierType) • \(offer.transport.owner.rating!.rating)"
offerCell.comment.text = offer.comment
// offerCell.car_icon.image = #imageLiteral(resourceName: "sedan")
if let url = offer.transport.type_icon {
offerCell.car_icon.kf.setImage(with: URL(string: url)) { (image, error, _, _) in
if let image = image {
offerCell.car_icon.image = image.withRenderingMode(.alwaysTemplate)
}
}
}else {
offerCell.car_icon.image = #imageLiteral(resourceName: "truck").withRenderingMode(.alwaysTemplate)
}
offerCell.car_name.text = "\(offer.transport.mark_name) \(offer.transport.model_name)"
// offerCell.car_description.text = "\(offer.transport.body_name) • \(offer.transport.shipping_type_name)"
offerCell.priceOfService.text = "\(offer.price) тг"
offerCell.delegate = self
offerCell.indexPath = indexPath
return offerCell
}
func cancelOffer(indexPath: IndexPath) {
let params = ["offer" : "\(offers[indexPath.row].id)" ]
API.shared.fetch(with: Router.Client.Order.delete(params: "\(order.id)/offers/", parameters: params), onSuccess: { (response) in
switch response {
case .raw(_):
self.offers.remove(at: indexPath.row)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}) { (error) in
Alert.alert(message: error.message, controller: self)
}
}
}
extension OfferPage: OfferActionHandler {
// func call(indexPath: IndexPath) {
// let profile = offers[indexPath.row].transport
// if let url = URL(string: "tel://\(profile.owner.phone)") {
// if #available(iOS 10.0, *) {
// UIApplication.shared.open(url, options: [:], completionHandler: nil)
// }else {
// UIApplication.shared.openURL(url)
// }
// }
// }
func reject(indexPath: IndexPath) {
let alert = UIAlertController(title: nil, message: Strings.reject, preferredStyle: .alert)
let ok = UIAlertAction(title: Strings.yes, style: .cancel) { (_) in
self.cancelOffer(indexPath: indexPath)
}
let cancel = UIAlertAction(title: Strings.no, style: .default, handler: nil)
alert.addAction(ok)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
func accept(indexPath: IndexPath) {
let alert = UIAlertController(title: nil, message: Strings.accept, preferredStyle: .alert)
let ok = UIAlertAction(title: Strings.yes, style: .cancel) { (_) in
self.acceptOffer(indexPath: indexPath)
}
let cancel = UIAlertAction(title: Strings.no, style: .default, handler: nil)
alert.addAction(ok)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
func acceptOffer(indexPath: IndexPath) {
let params = ["offer" : offers[indexPath.row].id]
API.shared.fetch(with: Router.Client.OrderAccept.create(endPoint: "\(order!.id)/offers/", params: params), onSuccess: { (response) in
DispatchQueue.main.async {
let alert = UIAlertController(title: nil, message: Strings.acceptedCourierService, preferredStyle: .alert)
let ok = UIAlertAction(title: Strings.ok, style: .cancel) { (_) in
if let controller = self.navigationController?.viewControllers.first as? ClientOrders {
if let subController = controller.client_controllers[0] as? OrderPage {
subController.getOrders()
}
self.navigationController?.popToViewController(controller, animated: true)
}
}
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
}
}) { (error) in
Alert.alert(message: error.message, controller: self)
}
}
}
|
//
// DataSource.swift
// CollectionViewDemo
//
// Created by Xueliang Zhu on 6/9/16.
// Copyright © 2016 kotlinchina. All rights reserved.
//
import UIKit
class DataSource: NSObject, UICollectionViewDataSource {
var images = [0, 1, 2, 3, 4, 5 ,6 ,7 ,8 ,9 ,10 ,11]
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CELL", forIndexPath: indexPath) as! CollectionCell
cell.imageView.image = UIImage(named: "\(images[indexPath.row])")
return cell
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionHeader {
return collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "HEADER", forIndexPath: indexPath)
} else {
return collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "FOOTER", forIndexPath: indexPath)
}
}
}
|
//
// FileController+GetUploadsResults.swift
// Server
//
// Created by Christopher G Prince on 8/9/20.
//
import Foundation
import ServerShared
import LoggerAPI
extension FileController {
func getUploadsResults(params:RequestProcessingParameters) {
guard let getUploadsRequest = params.request as? GetUploadsResultsRequest else {
let message = "Did not receive GetUploadsResultsRequest"
Log.error(message)
params.completion(.failure(.message(message)))
return
}
let key:DeferredUploadRepository.LookupKey
if let deferredUploadId = getUploadsRequest.deferredUploadId {
key = DeferredUploadRepository.LookupKey.deferredUploadId(deferredUploadId)
}
else if let batchUUID = getUploadsRequest.batchUUID {
key = DeferredUploadRepository.LookupKey.batchUUID(batchUUID: batchUUID)
}
else {
let message = "Did not have deferredUploadId or batchUUID."
Log.error(message)
params.completion(.failure(.message(message)))
return
}
guard let signedInUserId = params.currentSignedInUser?.userId else {
let message = "Could not get signedInUserId."
Log.error(message)
params.completion(.failure(.message(message)))
return
}
let deferredUploadResult = params.repos.deferredUpload.lookup(key: key, modelInit: DeferredUpload.init)
switch deferredUploadResult {
case .found(let model):
guard let deferredUpload = model as? DeferredUpload else {
let message = "Problem coercing to DeferredUpload."
Log.error(message)
params.completion(.failure(.message(message)))
return
}
guard deferredUpload.userId == signedInUserId else {
let message = "Attempting to get DeferredUpload record for different user."
Log.error(message)
params.completion(.failure(.message(message)))
return
}
let response = GetUploadsResultsResponse()
response.status = deferredUpload.status
params.completion(.success(response))
case .noObjectFound:
let response = GetUploadsResultsResponse()
params.completion(.success(response))
case .error(let error):
let message = "Problem with deferredUpload.lookup: \(error)"
Log.error(message)
params.completion(.failure(.message(message)))
}
}
}
|
//
// Member.swift
// MeetupRemainder
//
// Created by Vegesna, Vijay V EX1 on 9/12/20.
// Copyright © 2020 Vegesna, Vijay V. All rights reserved.
//
import SwiftUI
import MapKit
struct Member: Codable {
let name: String
let icon: CodableImage
var instance: CodableMKPointAnnotation?
init(name: String, image: UIImage, instance: CodableMKPointAnnotation?) {
self.name = name
let photoData = image.jpegData(compressionQuality: 0.8)!
self.icon = CodableImage(photoData)
self.instance = instance
}
var image: Image {
guard let uiImage = UIImage(data: icon.photoData) else {
return Image(systemName: "person")
}
return Image(uiImage: uiImage)
}
var location: CLLocationCoordinate2D? {
instance?.coordinate
}
}
class CodableImage: Codable {
enum CodingKeys: CodingKey {
case photoData
}
let photoData: Data
init(_ photoData: Data) {
self.photoData = photoData
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
photoData = try container.decode(Data.self, forKey: .photoData)
}
}
|
//
// WashResponse.swift
// carWash
//
// Created by Juliett Kuroyan on 09.12.2019.
// Copyright © 2019 VooDooLab. All rights reserved.
//
import Foundation
struct WashResponse: Codable {
var id: Int
var city: String
var address: String
var coordinates: [Double]
var cashback: Int
var seats: Int
var stocks: [StockResponse]?
var pivot: Pivot?
var happyHours: HappyHours?
var systemId: String
private enum CodingKeys : String, CodingKey {
case id, city, address, coordinates, cashback, seats, stocks, pivot, happyHours = "happy-hours", systemId = "system_id"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
city = try container.decode(String.self, forKey: .city)
address = try container.decode(String.self, forKey: .address)
coordinates = try container.decode([Double].self, forKey: .coordinates)
cashback = try container.decode(Int.self, forKey: .cashback)
seats = try container.decode(Int.self, forKey: .seats)
stocks = try? container.decode([StockResponse]?.self, forKey: .stocks)
pivot = try? container.decode(Pivot?.self, forKey: .pivot)
happyHours = try? container.decode(HappyHours?.self, forKey: .happyHours)
systemId = try container.decode(String.self, forKey: .systemId)
}
}
struct StockResponse: Codable {
var id: Int
var status: String
var started_at: String
var finished_at: String
var cashback: Int
var title: String
var text: String
var pivot: Pivot
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(Int.self, forKey: .id)
self.status = try container.decode(String.self, forKey: .status)
let dateFormatter = DateFormatter()
if let startedString = try? container.decode(String?.self, forKey: .started_at) {
started_at = dateFormatter.string(dateString: startedString,
fromFormat: Constants.fromFormat,
toHourFormat: nil)
} else {
started_at = ""
}
if let finishedString = try? container.decode(String?.self, forKey: .finished_at) {
finished_at = dateFormatter.string(dateString: finishedString,
fromFormat: Constants.fromFormat,
toHourFormat: nil)
} else {
finished_at = ""
}
self.cashback = try container.decode(Int.self, forKey: .cashback)
self.title = try container.decode(String.self, forKey: .title)
self.text = try container.decode(String.self, forKey: .text)
self.pivot = try container.decode(Pivot.self, forKey: .pivot)
}
}
struct Pivot: Codable {
var wash_id: Int
var stock_id: Int
}
struct HappyHours: Codable {
var active: Bool
var isEnabled: Bool
var start: String
var end: String
private enum CodingKeys : String, CodingKey {
case active, start, end, isEnabled = "switch"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
active = try container.decode(Bool.self, forKey: .active)
start = try container.decode(String.self, forKey: .start)
end = try container.decode(String.self, forKey: .end)
isEnabled = try container.decode(Bool.self, forKey: .isEnabled)
}
}
|
//
// ViewController.swift
// eggplant-brownie
//
// Created by Raphael Freitas dos Santos on 25/12/16.
// Copyright © 2016 Raphael Freitas dos Santos. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var nameField: UITextField?;
@IBOutlet var happinesFiled: UITextField?;
@IBAction func add() {
let name: String = nameField.text!
let happines:Int! = Int(happinesFiled.text!);
print("eaten \(name) with happiness \(happines)");
let meal = Meal(name:name, happy:happines);
print("eaten \(meal.name) with happiness \(meal.happy)");
if (nameField == nil || happinesFiled == nil) {
return
}
if let happy = Int(happinesFiled.text!) {
print("eaten \(name) with happiness \(happy)");
let meal = Meal(name:name, happy:happy);
print("eaten \(meal.name) with happiness \(meal.happy)");
}
}
}
|
//
// FindpasswordTableViewCell.swift
// test
//
// Created by Asianark on 16/1/22.
// Copyright © 2016年 Asianark. All rights reserved.
//
import UIKit
class FindpasswordTableViewCell: UITableViewCell {
@IBOutlet weak var SmallLabel: UILabel!
@IBOutlet weak var BigLabel: UILabel!
@IBOutlet weak var Imagelogo: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.