text stringlengths 8 1.32M |
|---|
//
// APIRouter.swift
// UsersApp-SwiftUI
//
// Created by Jorge Luis Rivera Ladino on 4/09/21.
//
import Foundation
enum APIRouter {
case Users
case Posts([String: Any])
private var method: HTTPMethod {
switch self {
case .Users,
.Posts:
return .GET
}
}
private var path: String {
switch self {
case .Users:
return "users"
case .Posts:
return "posts"
}
}
private var url: String {
APIManagerConstants.endpoint
}
private var urlRequest: URLRequest? {
guard let url = URL(string: url) else {
return nil
}
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
urlRequest.allHTTPHeaderFields = APIManager.defaultHeaders as? [String: String]
return urlRequest
}
private var nsUrlRequest: URLRequest? {
guard let nsUrl = NSURL(string: self.url + path) else {
return nil
}
var urlRequest = URLRequest(url: nsUrl as URL)
urlRequest.httpMethod = method.rawValue
urlRequest.allHTTPHeaderFields = APIManager.defaultHeaders as? [String: String]
return urlRequest
}
var request: URLRequest? {
switch self {
case .Users,
.Posts:
return nsUrlRequest
}
}
}
|
//
// ViewController.swift
// Emocia
//
// Created by Sanchitha Dinesh on 6/26/21.
//
import UIKit
import ARKit
import CoreML
class ViewController: UIViewController {
private let sceneView = ARSCNView(frame: UIScreen.main.bounds)
private let model = try! VNCoreMLModel(for: harshsikka_big().model)
private var angerButton: UIButton = UIButton()
private var disgustButton: UIButton = UIButton()
private var fearButton: UIButton = UIButton()
private var happyButton: UIButton = UIButton()
private var neutralButton: UIButton = UIButton()
private var sadButton: UIButton = UIButton()
private var surprisedButton: UIButton = UIButton()
private var classificationObservation: VNClassificationObservation?
private var score: UILabel = UILabel()
private var angerNode: SCNNode?
private var disgustNode: SCNNode?
private var fearNode: SCNNode?
private var happyNode: SCNNode?
private var neutralNode: SCNNode?
private var sadNode: SCNNode?
private var surprisedNode: SCNNode?
override func viewDidLoad() {
super.viewDidLoad()
guard ARWorldTrackingConfiguration.isSupported else { return }
view.addSubview(sceneView)
sceneView.delegate = self
sceneView.showsStatistics = true
sceneView.session.run(ARFaceTrackingConfiguration(), options: [.resetTracking, .removeExistingAnchors])
var scoreAmount = 0
score.text = "\(scoreAmount)"
angerButton.translatesAutoresizingMaskIntoConstraints = false
//angerButton.addTarget(self, action: #selector(angerButtonTapped(_:)), for: .touchUpInside)
self.angerButton = UIButton(type: .system, primaryAction: UIAction(title: "Anger", handler: { _ in
if let firstResult = self.classificationObservation, firstResult.confidence > 0.5 && firstResult.identifier == "angry" {
print("Correct!")
let alert = UIAlertController(title: "That's correct!", message: "+5 points", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
scoreAmount+=5
self.score.text = "\(scoreAmount)"
}
else {
let alert = UIAlertController(title: "Nice try! Keep trying!", message: "You'll get it next time", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}))
angerButton.backgroundColor = UIColor(red: 240/255, green: 164/255, blue: 164/255, alpha: 1)
angerButton.setTitleColor(UIColor.white, for: .normal)
angerButton.layer.cornerRadius = 4
self.disgustButton = UIButton(type: .system, primaryAction: UIAction(title: "Disgust", handler: { _ in
if let firstResult = self.classificationObservation, firstResult.confidence > 0.5 && firstResult.identifier == "disgust" {
print("Button tapped!")
let alert = UIAlertController(title: "That's correct!", message: "+5 points", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
scoreAmount+=5
self.score.text = "\(scoreAmount)"
}
else {
let alert = UIAlertController(title: "Nice try! Keep trying!", message: "You'll get it next time", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}))
disgustButton.backgroundColor = UIColor(red: 208/255, green: 240/255, blue: 169/255, alpha: 1)
disgustButton.setTitleColor(UIColor.white, for: .normal)
disgustButton.layer.cornerRadius = 4
self.fearButton = UIButton(type: .system, primaryAction: UIAction(title: "Fear", handler: { _ in
if let firstResult = self.classificationObservation, firstResult.confidence > 0.5 && firstResult.identifier == "fear" {
print("Button tapped!")
let alert = UIAlertController(title: "That's correct!", message: "+5 points", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
scoreAmount+=5
self.score.text = "\(scoreAmount)"
}
else {
let alert = UIAlertController(title: "Nice try! Keep trying!", message: "You'll get it next time", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}))
fearButton.backgroundColor = UIColor(red: 220/255, green: 190/255, blue: 254/255, alpha: 1)
fearButton.setTitleColor(UIColor.white, for: .normal)
fearButton.layer.cornerRadius = 4
self.happyButton = UIButton(type: .system, primaryAction: UIAction(title: "Happy", handler: { _ in
if let firstResult = self.classificationObservation, firstResult.confidence > 0.5 && firstResult.identifier == "happy" {
print("Button tapped!")
let alert = UIAlertController(title: "That's correct!", message: "+5 points", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
scoreAmount+=5
self.score.text = "\(scoreAmount)"
}
else {
let alert = UIAlertController(title: "Nice try! Keep trying!", message: "You'll get it next time", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}))
happyButton.backgroundColor = UIColor(red: 255/255, green: 240/255, blue: 147/255, alpha: 1)
happyButton.setTitleColor(UIColor.white, for: .normal)
happyButton.layer.cornerRadius = 4
self.neutralButton = UIButton(type: .system, primaryAction: UIAction(title: "Neutral", handler: { _ in
if let firstResult = self.classificationObservation, firstResult.confidence > 0.5 && firstResult.identifier == "neutral" {
print("Button tapped!")
let alert = UIAlertController(title: "That's correct!", message: "+5 points", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
scoreAmount+=5
self.score.text = "\(scoreAmount)"
}
else {
let alert = UIAlertController(title: "Nice try! Keep trying!", message: "You'll get it next time", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}))
neutralButton.backgroundColor = UIColor(red: 209/255, green: 209/255, blue: 204/255, alpha: 1)
neutralButton.setTitleColor(UIColor.white, for: .normal)
neutralButton.layer.cornerRadius = 4
self.sadButton = UIButton(type: .system, primaryAction: UIAction(title: "Sad", handler: { _ in
if let firstResult = self.classificationObservation, firstResult.confidence > 0.5 && firstResult.identifier == "sad" {
print("Button tapped!")
let alert = UIAlertController(title: "That's correct!", message: "+5 points", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
scoreAmount+=5
self.score.text = "\(scoreAmount)"
}
else {
let alert = UIAlertController(title: "Nice try! Keep trying!", message: "You'll get it next time", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}))
sadButton.setTitleColor(UIColor.white, for: .normal)
sadButton.layer.cornerRadius = 4
sadButton.backgroundColor = UIColor(red: 121/255, green: 215/255, blue: 213/255, alpha: 1)
self.surprisedButton = UIButton(type: .system, primaryAction: UIAction(title: "Surprise", handler: { _ in
if let firstResult = self.classificationObservation, firstResult.confidence > 0.65 && firstResult.identifier == "surprise" {
print("Button tapped!")
let alert = UIAlertController(title: "That's correct!", message: "+5 points", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
scoreAmount+=5
self.score.text = "\(scoreAmount)"
}
else {
let alert = UIAlertController(title: "Nice try! Keep trying!", message: "You'll get it next time", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}))
surprisedButton.backgroundColor = UIColor(red: 255/255, green: 198/255, blue: 140/255, alpha: 1)
surprisedButton.setTitleColor(UIColor.white, for: .normal)
surprisedButton.layer.cornerRadius = 4
view.addSubview(angerButton)
view.addSubview(disgustButton)
view.addSubview(happyButton)
view.addSubview(fearButton)
view.addSubview(happyButton)
view.addSubview(neutralButton)
view.addSubview(sadButton)
view.addSubview(surprisedButton)
view.addSubview(score)
let anger = SCNScene(named: "art.scnassets/anger.scn")
let disgust = SCNScene(named: "art.scnassets/disgust.scn")
let fear = SCNScene(named: "art.scnassets/fear.scn")
let happy = SCNScene(named: "art.scnassets/happy.scn")
let neutral = SCNScene(named: "art.scnassets/neutral.scn")
let sad = SCNScene(named: "art.scnassets/sad.scn")
let surprised = SCNScene(named: "art.scnassets/surprised.scn")
angerNode = anger?.rootNode.childNodes[0]
disgustNode = disgust?.rootNode.childNodes[0]
fearNode = fear?.rootNode.childNodes[0]
happyNode = happy?.rootNode.childNodes[0]
neutralNode = neutral?.rootNode.childNodes[0]
sadNode = sad?.rootNode.childNodes[0]
surprisedNode = surprised?.rootNode.childNodes[0]
// sceneView.scene = scene
// sceneView.pointOfView?.addChildNode(scene.rootNode)
}
override func viewWillLayoutSubviews() {
let height = self.view.frame.height
let frame = CGRect(x: 100, y: height - 200, width: 100, height: 40)
angerButton.frame = frame
angerButton.setNeedsLayout()
angerButton.layoutIfNeeded()
let frame1 = CGRect(x: 220, y: height - 200, width: 100, height: 40)
disgustButton.frame = frame1
disgustButton.setNeedsLayout()
disgustButton.layoutIfNeeded()
let frame2 = CGRect(x: 100, y: height - 150, width: 100, height: 40)
happyButton.frame = frame2
happyButton.setNeedsLayout()
happyButton.layoutIfNeeded()
let frame3 = CGRect(x: 220, y: height - 150, width: 100, height: 40)
fearButton.frame = frame3
fearButton.setNeedsLayout()
fearButton.layoutIfNeeded()
let frame4 = CGRect(x: 100, y: height - 250, width: 100, height: 40)
sadButton.frame = frame4
sadButton.setNeedsLayout()
sadButton.layoutIfNeeded()
let frame5 = CGRect(x: 220, y: height - 250, width: 100, height: 40)
surprisedButton.frame = frame5
surprisedButton.setNeedsLayout()
surprisedButton.layoutIfNeeded()
let frame6 = CGRect(x: 160, y: height - 300, width: 100, height: 40)
neutralButton.frame = frame6
neutralButton.setNeedsLayout()
neutralButton.layoutIfNeeded()
let frame7 = CGRect(x: 50, y: 50, width: 50, height: 50)
score.frame = frame7
score.setNeedsLayout()
score.layoutIfNeeded()
}
}
extension ViewController: ARSCNViewDelegate {
func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
guard let device = sceneView.device else { return nil }
let node = SCNNode(geometry: ARSCNFaceGeometry(device: device))
//Projects the white lines on the face.
node.geometry?.firstMaterial?.transparency = 0
return node
}
func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
guard let faceAnchor = anchor as? ARFaceAnchor,
let faceGeometry = node.geometry as? ARSCNFaceGeometry,
let pixelBuffer = self.sceneView.session.currentFrame?.capturedImage
else {
return
}
faceGeometry.update(from: faceAnchor.geometry)
let cameraNode = sceneView.pointOfView
//Creates Vision Image Request Handler using the current frame and performs an MLRequest.
try? VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: .right, options: [:]).perform([VNCoreMLRequest(model: model) { [weak self] request, error in
guard let firstResult = (request.results as? [VNClassificationObservation])?.first else { return }
self?.classificationObservation = firstResult
var emojiNode:SCNNode? = nil
if firstResult.confidence > 0.8 {
//self?.label?.text = firstResult.identifier
switch firstResult.identifier {
case "angry":
emojiNode = self?.angerNode ?? nil
case "disgust":
emojiNode = self?.disgustNode ?? nil
case "fear":
emojiNode = self?.fearNode ?? nil
case "happy":
emojiNode = self?.happyNode ?? nil
case "neutral":
emojiNode = self?.neutralNode ?? nil
case "sad":
emojiNode = self?.sadNode ?? nil
case "surprise":
emojiNode = self?.surprisedNode ?? nil
default:
emojiNode = self?.neutralNode ?? nil
}
if let emojiNode = emojiNode {
// Check for the existing emojiNode and remove it
let childCount = cameraNode?.childNodes.count ?? 0
if childCount > 0 {
if let childEmojiNode = cameraNode?.childNodes[0] {
childEmojiNode.removeAllActions()
childEmojiNode.removeFromParentNode()
}
}
emojiNode.removeAllActions()
cameraNode?.addChildNode(emojiNode)
emojiNode.position = SCNVector3(x: 1.25, y: 3.5, z: -10)
let action = SCNAction.rotateBy(x: 0, y: CGFloat(2 * Double.pi), z: 0, duration: 7)
let repAction = SCNAction.repeatForever(action)
emojiNode.runAction(repAction, forKey: "myrotate")
}
}
}])
}
}
|
//
// ViewController.swift
// Jouzu
//
// Created by Johann Diedrick on 3/28/15.
// Copyright (c) 2015 Johann Diedrick. All rights reserved.
//
import UIKit
var flashCardGame = FlashCardGameModel()
var callLabel = UITextView()
var responseBox = UITextField()
var respondButton = UIButton()
class ViewController: UIViewController, UITextFieldDelegate, FlashCardGameModelDelegate {
var delegate: FlashCardGameModelDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupFlashCardGame()
setupUI();
setupTap();
setupNotificaitons();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Flashcard Game
func setupFlashCardGame(){
flashCardGame.delegate = self
if let rs = FlashCardDatabaseManager.instance.getCallAndResponse(){
while rs.next() {
let call = rs.stringForColumn("call")
let response = rs.stringForColumn("response")
println("vc call = \(call); vc response = \(response);")
let card = FlashCardModel(call: call, response: response)
flashCardGame.flashCardDeck.addFlashCard(card)
}
}
flashCardGame.getNextCard()
}
func guessAction(sender:UIButton!){
flashCardGame.respond(responseBox.text)
updateUI();
}
// MARK: UI
func setupUI(){
//question label
callLabel = UITextView(frame:
CGRectMake(
30,
(self.view.frame.size.height/2)-30-50,
self.view.frame.size.width-60,
50))
callLabel.text = flashCardGame.flashCardDeck.deck[flashCardGame.currentCard].call
callLabel.layer.borderColor = UIColor.greenColor().CGColor
callLabel.layer.borderWidth = 2.0
callLabel.textContainerInset = UIEdgeInsetsMake(15, 0, 15, 0)
callLabel.editable = false
self.view.addSubview(callLabel)
//answer label
responseBox = UITextField(frame:
CGRectMake(
30,
(self.view.frame.size.height/2)+30,
self.view.frame.size.width-60,
50))
responseBox.layer.borderColor = UIColor.greenColor().CGColor
responseBox.layer.borderWidth = 2.0
responseBox.delegate = self
self.view.addSubview(responseBox)
let midLine = UIView(frame: CGRectMake(0, self.view.frame.size.height/2, self.view.frame.size.width, 3))
midLine.backgroundColor = UIColor.purpleColor()
self.view.addSubview(midLine)
/*
respondButton = UIButton(frame: CGRectMake(self.view.frame.size.width/2, 300, 100, 100))
respondButton.backgroundColor = UIColor.orangeColor()
respondButton.addTarget(self, action: "guessAction:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(respondButton)
*/
}
func updateUI(){
callLabel.text = flashCardGame.flashCardDeck.deck[flashCardGame.currentCard].call
}
//MARK: Tap Gesture
func setupTap(){
var tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
view.addGestureRecognizer(tap)
}
//Calls this function when the tap is recognized.
func DismissKeyboard(){
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
//MARK: TextField Delegate Methods
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
responseBox.text = textField.text
flashCardGame.respond(responseBox.text)
updateUI();
return false;
}
func textFieldDidBeginEditing(textField: UITextField) {
animateViewMoving(true, moveValue: 100)
}
func textFieldDidEndEditing(textField: UITextField) {
println("\(textField.text)")
animateViewMoving(false, moveValue: 100)
}
func animateViewMoving (up:Bool, moveValue :CGFloat){
var movementDuration:NSTimeInterval = 0.3
var movement:CGFloat = ( up ? -moveValue : moveValue)
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(movementDuration )
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
UIView.commitAnimations()
}
// MARK: Alert
func displayAlert(alert: UIAlertController) {
presentViewController(alert, animated: true, completion: nil)
responseBox.text = ""
}
// MARK: Notifications
func setupNotificaitons(){
//cancel all previous notifications
UIApplication.sharedApplication().cancelAllLocalNotifications()
//setup a new notification
var localNotification:UILocalNotification = UILocalNotification()
localNotification.alertAction = "Study Reminder"
localNotification.alertBody = "Take a 5 minute break to practice!"
localNotification.fireDate = NSDate(timeIntervalSinceNow: 60*60) //one hour
localNotification.repeatInterval = .CalendarUnitHour
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
} |
//
// AlmostThereModelView.swift
// imagefy
//
// Created by Alan on 5/22/16.
// Copyright © 2016 Alan M. Lira. All rights reserved.
//
import Foundation
class AlmostThereModelView: NSObject {
var productImage: UIImage?
var brief: String = ""
var priceValue: Float = 0.0
init(productImage: UIImage?, brief: String, priceValue: Float) {
super.init()
self.productImage = productImage
self.brief = brief
self.priceValue = priceValue
}
} |
import UIKit
final class TotalTableViewCell : UITableViewCell {
@IBOutlet weak var totalPrice: UILabel!
}
|
//
// LHConstants.swift
// XcodeLocalizationHelperPlugin
//
// Created by Tim Freiheit on 22.07.15.
// Copyright (c) 2015 Tim Freiheit. All rights reserved.
//
import Foundation
class PrefKeys {
static let RunOnBuild = "XcodeLocalizationHelperPlugin_RunOnBuild"
static let SplitOutput = "XcodeLocalizationHelperPlugin_SplitOutput"
static let OutputPath = "XcodeLocalizationHelperPlugin_OutputPath"
static let IgnoredPaths = "XcodeLocalizationHelperPlugin_IgnoredPaths"
}
let kRegularExpressionPattern: String = "(\"(\\S+.*\\S+)\"|(\\S+.*\\S+))\\s*=\\s*\"(.*)\";$"
let stringLineRegularExpression = NSRegularExpression(pattern: kRegularExpressionPattern, options: nil, error: nil)!
let kVariablePattern : String = "[a-zA-Z_][a-zA-Z_]*"
let variableRegularExpression = NSRegularExpression(pattern: kVariablePattern, options: nil, error: nil)!
let kValidNamePattern : String = "[a-zA-Z_][a-zA-Z_\\.\\-]*"
let validNameRegularExpression = NSRegularExpression(pattern: kValidNamePattern, options: nil, error: nil)!
let BASE_LANGUAGE = "Base" |
//
// BadgeViews.swift
// Prayer App
//
// Created by tomrunnels on 3/5/21.
//
import SwiftUI
struct PrayerBadge: View {
let type: PrayerBadgeType
var body: some View{
return ZStack {
switch (type) {
case .saved:
PrayerBadgeIcon(image: Image(systemName: "checkmark.circle"))
case .twoOrMore:
PrayerBadgeIcon(image: Image(systemName: "person.3"))
case .answered:
PrayerBadgeIcon(image: Image(systemName: "sun.max"))
default:
PrayerBadgeIcon(image: Image(systemName: "xmark.octagon"))
}
}
}
}
enum PrayerBadgeType {
case saved
case twoOrMore
case answered
case inGroup
case inPrivate
case inBody
case inFriends
}
struct PrayerBadgeIcon: View {
let image: Image
var body: some View{
return ZStack {
// RoundedRectangle(cornerRadius: 4)
// .fill(Color.gray)
// .frame(width: 25, height: 25, alignment:.center)
image
.colorMultiply(.yellow)
}
}
}
|
//
// DemoCollectionViewController.swift
// CollectionTransitionDemo
//
// Created by 黎明 on 2017/8/14.
// Copyright © 2017年 黎明. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class DemoCollectionViewController: UICollectionViewController {
var isPush: Bool = true
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = .white
self.collectionView!.register(ImageCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 15
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ImageCollectionViewCell
cell.imageView.image = UIImage(named: "Wechat-\(indexPath.item)")
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if !self.isPush {
return
}
let width = self.view.bounds.width
let flowLayout = UICollectionViewFlowLayout()
flowLayout.itemSize = CGSize(width: width, height: width)
flowLayout.scrollDirection = .horizontal
flowLayout.minimumLineSpacing = 0
flowLayout.minimumInteritemSpacing = 0
flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
let nextVC = DemoCollectionViewController(collectionViewLayout: flowLayout)
nextVC.collectionView?.isPagingEnabled = true
nextVC.isPush = false
nextVC.useLayoutToLayoutNavigationTransitions = true
navigationController?.pushViewController(nextVC, animated: true)
}
}
|
//
// MenuVC.swift
// DailyLifeV2
//
// Created by Lý Gia Liêm on 6/25/19.
// Copyright © 2019 LGL. All rights reserved.
//
import UIKit
class SideMenuVC: UIViewController {
@IBOutlet var menuCollectionView: UICollectionView!
@IBOutlet var visualEffectView: UIVisualEffectView!
@IBOutlet var myTextField: UITextField!
@IBOutlet var blurEffectView: UIVisualEffectView!
@IBOutlet var addView: UIView!
var effect: UIVisualEffect!
override func viewDidLoad() {
super.viewDidLoad()
configureMenuCollectionView()
closeSideMenuByPan()
configureAddView()
let tap = UITapGestureRecognizer(target: self, action: #selector
(handleTapToDimissAddView))
self.visualEffectView.addGestureRecognizer(tap)
}
func configureAddView() {
effect = visualEffectView.effect
visualEffectView.isHidden = true
visualEffectView.effect = nil
addView.layer.cornerRadius = 10
}
func closeSideMenuByPan() {
let panEdge = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(handleEdgePan(gesture:)))
panEdge.edges = .right
view.addGestureRecognizer(panEdge)
}
func animateAddViewIn() {
visualEffectView.isHidden = false
self.view.addSubview(addView)
addView.frame.origin.x = (self.view.frame.width - addView.frame.width) / 2
addView.frame.origin.y = 20 + 44 + 30
addView.layer.borderColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)
addView.layer.borderWidth = 2
addView.alpha = 0
myTextField.becomeFirstResponder()
UIView.animate(withDuration: 0.5) {
self.visualEffectView.effect = self.effect
self.addView.alpha = 1
self.addView.transform = CGAffineTransform.identity
}
}
func animateAddViewOut() {
UIView.animate(withDuration: 0.5, animations: {
self.visualEffectView.effect = nil
self.addView.alpha = 0
self.visualEffectView.isHidden = true
}) { (_) in
self.addView.removeFromSuperview()
}
}
func configureMenuCollectionView() {
menuCollectionView.delegate = self
menuCollectionView.dataSource = self
menuCollectionView.showsVerticalScrollIndicator = false
}
}
extension SideMenuVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return LibraryAPI.instance.TOPIC_NEWSAPI.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: R.reuseIdentifier.cellOfSideMenu, for: indexPath)!
cell.imageName = LibraryAPI.instance.TOPIC_NEWSAPI[indexPath.row]
cell.topicName = LibraryAPI.instance.TOPIC_NEWSAPI[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (self.view.frame.width - 15 - 15 - 15) / 2
return CGSize(width: width, height: width * 40 / 33)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 15
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
NotificationCenter.default.post(name: .MoveToTopic, object: nil, userInfo: ["data": indexPath])
NotificationCenter.default.post(name: .OpenOrCloseSideMenu, object: nil)
NotificationCenter.default.post(name: .MoveToTabbarIndex0, object: nil)
}
}
// @objc function:
extension SideMenuVC {
@objc func handleEdgePan(gesture: UIScreenEdgePanGestureRecognizer) {
NotificationCenter.default.post(name: .CloseSideMenyByEdgePan, object: nil, userInfo: ["data": gesture])
}
@objc func handleTapToDimissAddView() {
myTextField.resignFirstResponder()
animateAddViewOut()
}
}
// Button Action:
extension SideMenuVC {
@IBAction func CloseMenuByPressed(_ sender: Any) {
NotificationCenter.default.post(name: .OpenOrCloseSideMenu, object: nil)
}
@IBAction func AddNewTopicButton(_ sender: Any) {
animateAddViewIn()
}
@IBAction func cancleButton(_ sender: Any) {
myTextField.resignFirstResponder()
animateAddViewOut()
}
}
|
//
// Search.swift
// WeatherApp
//
// Created by Dzhek on 08.09.2020.
// Copyright © 2020 Dzhek. All rights reserved.
//
import Foundation
import Combine
final class Search: ObservableObject {
@Published private(set) var state = State.inactive
private var bag = Set<AnyCancellable>()
private let input = PassthroughSubject<Event, Never>()
init() {
Publishers
.system(initial: state,
reduce: Self.reduce,
scheduler: RunLoop.main,
feedbacks: [
Self.startSearch(),
Self.userInput(input: input.eraseToAnyPublisher()),
])
.sink { [weak self] in self?.state = $0 }
.store(in: &bag)
}
deinit {
bag.removeAll()
}
func send(_ event: Event) {
input.send(event)
}
}
extension Search {
static func reduce(_ state: State, _ event: Event) -> State {
switch (state, event) {
case (_ , .onCancel):
return .inactive
case (_ , let .onCommit(text)):
return .loading(text)
case (.loading, let .successSearch(town)):
return .loaded(town)
case (.loading, .failedSearch):
return .error
default: return state
}
}
static func startSearch() -> Feedback<State, Event> {
Feedback { (state: State) -> AnyPublisher<Event, Never> in
guard case let .loading(text) = state,
text.trimmingCharacters(in: .whitespaces).count > 0
else { return Empty().eraseToAnyPublisher() }
let formatedText = text
.trimmingCharacters(in: .whitespaces)
return Store.searchTown(by: formatedText)
.map(Model.init)
.map(Event.successSearch)
.catch{ Just(Event.failedSearch($0)) }
.eraseToAnyPublisher()
}
}
static func userInput(input: AnyPublisher<Event, Never>) -> Feedback<State, Event> {
Feedback(run: { _ in return input })
}
}
// MARK: - Nested Types
extension Search {
enum State {
case inactive
case loading(String)
case loaded(Model)
case error
}
enum Event {
case onCancel
case onCommit(String)
case successSearch(Model)
case failedSearch(Error)
}
struct Model: Identifiable {
let id: UUID
let title: String
init(_ town: Town) {
id = town.id
title = town.name
}
}
}
|
import SwiftCheck
import Bow
import BowGenerators
public class EquatableKLaws<F: EquatableK & ArbitraryK, A: Arbitrary & Equatable> {
public static func check() {
identity()
commutativity()
transitivity()
}
private static func identity() {
property("Identity: Every object is equal to itself") <~ forAll { (fa: KindOf<F, A>) in
fa.value == fa.value
}
}
private static func commutativity() {
property("Equality is commutative") <~ forAll { (fa: KindOf<F, A>, fb: KindOf<F, A>) in
(fa.value == fb.value)
==
(fb.value == fa.value)
}
}
private static func transitivity() {
property("Equality is transitive") <~ forAll { (fa: KindOf<F, A>, fb: KindOf<F, A>, fc: KindOf<F, A>) in
// fa == fb && fb == fc --> fa == fc
not((fa.value == fb.value) && (fb.value == fc.value)) || (fa.value == fc.value)
}
}
}
|
//
// EntriesTableViewController.swift
// JournalCoreData
//
// Created by scott harris on 2/24/20.
// Copyright © 2020 scott harris. All rights reserved.
//
import UIKit
class EntriesTableViewController: UITableViewController {
let entryController = EntryController()
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return entryController.entries.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "EntryCell", for: indexPath) as? EntryTableViewCell else { return UITableViewCell() }
let entry = entryController.entries[indexPath.row]
cell.entry = entry
return cell
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let entry = entryController.entries[indexPath.row]
entryController.delete(entry: entry)
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "AddEntryModalSegue" {
if let createDetailVC = segue.destination as? EntryDetailViewController {
createDetailVC.entryController = entryController
}
} else if segue.identifier == "ShowEntrySegue" {
if let showDetailVC = segue.destination as? EntryDetailViewController {
showDetailVC.entryController = entryController
if let selectedIndex = tableView.indexPathForSelectedRow {
showDetailVC.entry = entryController.entries[selectedIndex.row]
}
}
}
}
}
|
////
//// Socket.swift
//// oneone
////
//// Created by levi.luo on 2017/10/9.
//// Copyright © 2017年 levi.luo. All rights reserved.
////
//
//import UIKit
//import Starscream
//@objc public protocol DSWebSocketDelegate: NSObjectProtocol{
// /**websocket 连接成功*/
// func websocketDidConnect(sock: DSWebSocket)
// /**websocket 连接失败*/
// func websocketDidDisconnect(socket: DSWebSocket, error: NSError?)
// /**websocket 接受文字信息*/
// func websocketDidReceiveMessage(socket: DSWebSocket, text: String)
// /**websocket 接受二进制信息*/
// func websocketDidReceiveData(socket: DSWebSocket, data: NSData)
//}
//public class DSWebSocket: NSObject,WebSocketDelegate {
//
// var socket:WebSocket!
// weak var webSocketDelegate: DSWebSocketDelegate?
// //单例
// class func sharedInstance() -> DSWebSocket
// {
// return manger
// }
// static let manger: DSWebSocket = {
// return DSWebSocket()
// }()
//
// //MARK:- 链接服务器
// func connectSever(){
// socket = WebSocket(url: URL(string:NetService.indexPath)!)
// socket.delegate = self
// socket.connect()
// }
//
// //发送文字消息
// func sendBrandStr(brandID:String){
//// socket.writeString(brandID)
// }
// //MARK:- 关闭消息
// func disconnect(){
// socket.disconnect()
// }
//
// //MARK: - WebSocketDelegate
// public func websocketDidConnect(socket: WebSocket){
//// debugPrint("连接成功了: \(error?.localizedDescription)")
// webSocketDelegate?.websocketDidConnect(sock: self)
// }
// public func websocketDidDisconnect(socket: WebSocket, error: NSError?){
// debugPrint("连接失败了: \(error?.localizedDescription)")
// webSocketDelegate?.websocketDidDisconnect(socket: self, error: error)
// }
// //注:一般返回的都是字符串
// public func websocketDidReceiveMessage(socket: WebSocket, text: String){
//// debugPrint("接受到消息了: \(error?.localizedDescription)")
// webSocketDelegate?.websocketDidReceiveMessage(socket: self, text: text)
// }
//
// public func websocketDidReceiveData(socket: WebSocket, data: Data){
// debugPrint("data数据")
// webSocketDelegate?.websocketDidReceiveData(socket: self, data: data as NSData)
// }
//}
//
|
//
// main.swift
// LinkedList
//
// Created by Qingchuan Zhu on 8/24/18.
// Copyright © 2018 Qingchuan Zhu. All rights reserved.
//
import Foundation
let list2:List = [3,2,1]
print(list2)
let list:List = ["1", "2", "3"]
for x in list{
print("\(x)")
}
for x in list{
print("\(x)")
}
//let joinedList = list.joined(separator: ",")
//print(joinedList)
|
//
// ItemManager.swift
// TDD
//
// Created by tangyuhua on 2017/4/10.
// Copyright © 2017年 tangyuhua. All rights reserved.
//
import Foundation
class ItemManager: NSObject {
var toDoCount: Int { return toDoItems.count }
var doneCount: Int { return doneItems.count }
private var toDoItems = [ToDoItem]()
private var doneItems = [ToDoItem]()
var toDoPathURL: URL {
let fileURLs = FileManager.default.urls(
for: .documentDirectory, in: .userDomainMask)
guard let documentURL = fileURLs.first else {
print("Something went wrong. Documents url could not be found")
fatalError()
}
return documentURL.appendingPathComponent("toDoItems.plist")
}
override init() {
super.init()
NotificationCenter.default.addObserver(self, selector: Selector(("save")), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
save()
}
func addItem(_ item: ToDoItem) {
if !toDoItems.contains(item) {
toDoItems.append(item)
}
}
func itemAtIndex(_ index: Int) -> ToDoItem {
return toDoItems[index]
}
func checkItemAtIndex(_ index: Int) {
let item = toDoItems.remove(at: index)
doneItems.append(item)
}
func uncheckItemAtIndex(_ index: Int) {
let item = doneItems.remove(at: index)
toDoItems.append(item)
}
func doneItemAtIndex(_ index: Int) -> ToDoItem {
return doneItems[index]
}
func removeAllItems() {
toDoItems.removeAll()
doneItems.removeAll()
}
func save() {
var nsToDoItems = [AnyObject]()
for item in toDoItems {
nsToDoItems.append(item.plistDict)
}
if nsToDoItems.count > 0 {
(nsToDoItems as NSArray).write(to: toDoPathURL,
atomically: true)
} else {
do {
try FileManager.default.removeItem(at: toDoPathURL)
} catch {
print(error)
}
}
}
}
|
//
// Network.swift
// 8ball_testproject
//
// Created by Станислав on 31/08/2019.
// Copyright © 2019 Stanislav Buryan. All rights reserved.
//
import Foundation
class Network {
let ANSWER_URL = "https://8ball.delegator.com/magic/JSON/question"
func getQuestionResponse() {
guard let url = URL(string: ANSWER_URL) else { return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
if let err = err {
print("Failed to get data from URL: ", err)
self.sendingData(data: UserDefaults.standard.string(forKey: "answer")!)
}
guard let data = data else { return }
do {
let data = try JSONDecoder().decode(Magic.self, from: data)
self.sendingData(data: data.magic.answer!)
} catch let jsonErr {
print(jsonErr)
self.sendingData(data: UserDefaults.standard.string(forKey: "answer")!)
}
}.resume()
}
func sendingData(data: String) {
NotificationCenter.default.post(name: Notification.Name("didReceiveData"), object: data)
}
}
|
//: [Previous](@previous)
import Foundation
let a = "hello"
let b = "world"
let c = "Andy"
print(a, b, c) // print multiple items with space separator, newline at end
print(a+b+c) // print multiple strings concateanted together with a newline at end. No separator.
print("\(a), \(b). \(c)") // Interpolation of expressions into a string. Provides fine grained control without concat performance hit.
print(a, b, c, separator:";")
print(a, b, c, terminator:"")
print(a, b, c, "\n", terminator:"")
// Print wrapper behavior
func myprint(_ args: Any...) {
print(args)
}
myprint("hello", "world")
//: [Next](@next)
|
//
// PodfileViewController.swift
// YEFlyGo
//
// Created by yongen on 17/4/11.
// Copyright © 2017年 yongen. All rights reserved.
//
import UIKit
let kPodfileCellID = "kPodfileCellID"
class PodfileViewController: UIViewController {
let imgArr = ["address", "message", "evaluate", "member_card", "collect", "password_setting", "set"]
let titleArr = ["我的收货地址", "我的消息", "我的评价", "会员卡", "我的收藏", "密码设置", "设置"]
fileprivate lazy var tableView : UITableView = {
let tableView = UITableView(frame: self.view.bounds, style: .plain)
tableView.separatorColor = UIColor.orange
tableView.rowHeight = 70
tableView.delegate = self
tableView.dataSource = self
tableView.register(UINib(nibName: "PodfileViewCell", bundle: nil), forCellReuseIdentifier: kPodfileCellID)
tableView.tableFooterView = UIView()
return tableView
}()
var userName : UILabel!
var userImg : UIImageView!
var isLogin : Bool?
fileprivate lazy var headView : UIView = {
let view = UIView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: 185))
view.backgroundColor = UIColor.colorFromHex(0x989898)
let stateView = UIView(frame: CGRect(x: 0, y: -20, width: kScreenW, height: 20))
stateView.backgroundColor = UIColor.colorFromHex(0x989898)
view.addSubview(stateView)
self.userImg = UIImageView(frame: CGRect(x: kScreenW/2 - 49, y: 185/2 - 40, width: 98 , height: 98))
self.userImg.kf.setImage(with: URL(string: "https://source.unsplash.com/random/320x320"))
self.userImg.layer.masksToBounds = true
self.userImg.layer.cornerRadius = 49
view.addSubview(self.userImg)
self.userName = UILabel(frame: CGRect(x: 20, y: 185/2 + 49 + 5, width: kScreenW - 40, height: 28))
self.userName.textColor = UIColor.colorFromHex(0x383838)
self.userName.text = "登录"
self.userName.textAlignment = .center
self.userName.font = UIFont.systemFont(ofSize: 14)
view.addSubview(self.userName)
let tap = UITapGestureRecognizer(target: self, action: #selector(pushLogin))
view.addGestureRecognizer(tap)
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
//MARK: - 设置UI界面内容
extension PodfileViewController {
func setupUI() {
self.navigationController?.navigationBar.isHidden = true
self.tableView.tableHeaderView = headView
view.addSubview(tableView)
}
func pushLogin(){
print("pushLogin")
}
}
//MARK: - 数据请求
extension PodfileViewController {
func loadData() {
}
}
extension PodfileViewController : UITableViewDelegate {
}
extension PodfileViewController : UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titleArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: kPodfileCellID, for: indexPath) as! PodfileViewCell
cell.podfileLabel.text = titleArr[indexPath.row]
cell.podfileIcon.image = UIImage(named: imgArr[indexPath.row])
return cell
}
}
|
//
// VideoView.swift
// Plugin
//
// Created by taras.melko on 08.06.2021.
// Copyright © 2021 Max Lynch. All rights reserved.
//
import Foundation
import UIKit
struct CallState {
var hasDevicesSelected = true
var cameraMuted = false
var connected = false
}
struct ConnectOptions {
let portal: String
let roomKey: String
let pin: String
let name: String
let maxParticipants: Int
let logLevel: String
let debug: Bool
}
class VidyoClientWrapper : NSObject {
var connector: VCConnector?
var videoView: UIView?
var options: ConnectOptions!
var callState = CallState()
weak var delegate: IPluginEventHandler?
init(view: inout UIView, delegate: IPluginEventHandler, options: ConnectOptions) {
super.init()
self.videoView = view
self.delegate = delegate
self.options = options
connector = VCConnector(&view,
viewStyle: .default,
remoteParticipants: UInt32(options.maxParticipants),
logFileFilter: options.logLevel.cString(using: .utf8),
logFileName: "".cString(using: .utf8),
userData: 0)
// Orientation change observer
NotificationCenter.default.addObserver(self, selector: #selector(onOrientationChanged),
name: UIDevice.orientationDidChangeNotification, object: nil)
// Foreground mode observer
NotificationCenter.default.addObserver(self, selector: #selector(onForeground),
name: UIApplication.didBecomeActiveNotification, object: nil)
// Background mode observer
NotificationCenter.default.addObserver(self, selector: #selector(onBackground),
name: UIApplication.willResignActiveNotification, object: nil)
if options.debug {
self.connector?.registerLogEventListener(self, filter: options.logLevel)
}
self.connector?.registerParticipantEventListener(self)
self.connector?.reportLocalParticipant(onJoined: true)
self.refreshUI()
self.delegate?.onInitialized(status: true)
}
@objc func onForeground() {
guard let connector = connector else {
return
}
if !callState.hasDevicesSelected {
callState.hasDevicesSelected = true
connector.selectDefaultCamera()
connector.selectDefaultMicrophone()
connector.selectDefaultSpeaker()
}
connector.setMode(.foreground)
connector.setCameraPrivacy(callState.cameraMuted)
}
@objc func onBackground() {
guard let connector = connector else {
return
}
if isInCallingState() {
connector.setCameraPrivacy(true)
} else {
callState.hasDevicesSelected = false
connector.select(nil as VCLocalCamera?)
connector.select(nil as VCLocalMicrophone?)
connector.select(nil as VCLocalSpeaker?)
}
connector.setMode(.background)
}
@objc func onOrientationChanged() {
self.refreshUI();
}
}
// MARK: Public API
extension VidyoClientWrapper {
func connectOrDisconnect(state: Bool) -> Bool {
if (state) {
print("Start connection: \(options.portal):\(options.roomKey) with pin '\(options.pin)' and name: \(options.name)");
return self.connector?.connectToRoom(asGuest: options.portal,
displayName: options.name,
roomKey: options.roomKey,
roomPin: options.pin,
connectorIConnect: self) ?? false
} else {
return self.connector?.disconnect() ?? false
}
}
func setCameraPrivacy(privacy: Bool) {
self.connector?.setCameraPrivacy(privacy)
self.callState.cameraMuted = privacy
}
func setMicrophonePrivacy(privacy: Bool) {
self.connector?.setMicrophonePrivacy(privacy)
}
func cycleCamera() {
self.connector?.cycleCamera()
}
func destroy() {
self.delegate = nil
connector?.select(nil as VCLocalCamera?)
connector?.select(nil as VCLocalMicrophone?)
connector?.select(nil as VCLocalSpeaker?)
connector?.unregisterLogEventListener()
connector?.unregisterParticipantEventListener()
connector?.hideView(&videoView)
connector?.disable()
connector = nil
NotificationCenter.default.removeObserver(self)
}
}
// MARK: IConnect Interface
extension VidyoClientWrapper: VCConnectorIConnect {
func onSuccess() {
print("Connection Successful.")
DispatchQueue.main.async {
[weak self] in
guard let this = self else {
print("Error: Can't maintain self reference.")
return
}
this.delegate?.onConnected()
}
}
func onFailure(_ reason: VCConnectorFailReason) {
DispatchQueue.main.async {
[weak self] in
guard let this = self else {
print("Error: Can't maintain self reference.")
return
}
this.delegate?.onFailure(reason: "\(reason)")
this.callState.connected = false
}
}
func onDisconnected(_ reason: VCConnectorDisconnectReason) {
DispatchQueue.main.async {
[weak self] in
guard let this = self else {
print("Error: Can't maintain self reference.")
return
}
this.delegate?.onDisconnected(reason: "\(reason)")
this.callState.connected = false
}
}
}
// MARK: Participant Events Callback
extension VidyoClientWrapper: VCConnectorIRegisterParticipantEventListener {
func onParticipantJoined(_ participant: VCParticipant!) {
self.delegate?.onParticipantJoined(participant: participant)
}
func onParticipantLeft(_ participant: VCParticipant!) {
self.delegate?.onParticipantLeft(participant: participant)
}
func onDynamicParticipantChanged(_ participants: NSMutableArray!) {}
func onLoudestParticipantChanged(_ participant: VCParticipant!, audioOnly: Bool) {}
}
// MARK: Private API
extension VidyoClientWrapper {
private func refreshUI() {
DispatchQueue.main.async {
[weak self] in
guard let this = self else { return }
this.connector?.showView(at: &this.videoView,
x: 0,
y: 0,
width: UInt32(this.videoView?.frame.size.width ?? 0),
height: UInt32(this.videoView?.frame.size.height ?? 0))
}
}
private func isInCallingState() -> Bool {
if let connector = connector {
let state = connector.getState()
return state != .idle && state != .ready
}
return false
}
}
// MARK: Log Event Listener - Required for Debug Console logging
extension VidyoClientWrapper: VCConnectorIRegisterLogEventListener {
func onLog(_ logRecord: VCLogRecord!) {}
}
|
//
// DetailViewController.swift
// BPM
//
// Created by 夏 on 2020/07/16.
// Copyright © 2020 akane.com. All rights reserved.
//
import UIKit
import NCMB
import PKHUD
class DetailViewController: UIViewController {
var selectedMemo: NCMBObject!
@IBOutlet var memoTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
memoTextView.text = selectedMemo.object(forKey: "memo") as! String
}
@IBAction func update() {
selectedMemo.setObject(memoTextView.text, forKey: "memo")
selectedMemo.saveInBackground { (error) in
if error != nil {
HUD.flash(.error, delay: 1.0)
} else {
// 成功
self.navigationController?.popViewController(animated: true)
}
}
}
@IBAction func delete() {
selectedMemo.deleteInBackground { (error) in
if error != nil {
HUD.flash(.error, delay: 1.0)
} else {
// 削除成功
self.navigationController?.popViewController(animated: true)
}
}
}
}
|
//
// HTTPMessage.swift
// WEBServiceDemo
//
// Created by Eden on 2021/8/23.
//
import Foundation
public typealias HTTPMessage = CFHTTPMessage
public extension HTTPMessage
{
// MARK: - Properties -
var requestURL: URL? {
let url: URL? = CFHTTPMessageCopyRequestURL(self).map({ $0.takeRetainedValue() as URL })
return url
}
var rootURL: URL? {
guard let requestURL: URL = self.requestURL,
let scheme: String = requestURL.scheme,
let host: String = requestURL.host,
let port: Int = requestURL.port else {
return nil
}
let rootURL = URL(string: "\(scheme)://\(host):\(port)")
return rootURL
}
var requestMethod: HTTPMethod? {
let method: HTTPMethod? = CFHTTPMessageCopyRequestMethod(self).flatMap {
let rawValue: String = $0.takeRetainedValue() as String
let method = HTTPMethod(rawValue: rawValue)
return method
}
return method
}
var data: Data? {
let data: Data? = CFHTTPMessageCopyBody(self).map({ $0.takeRetainedValue() as Data })
return data
}
// MARK: - Methods -
static func request(withData data: Data) -> HTTPMessage?
{
let message: HTTPMessage = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, true).takeRetainedValue()
let bytes: Array = Array(data)
let result: Bool = CFHTTPMessageAppendBytes(message, bytes, data.count)
return result ? message : nil
}
static func response(statusCode: StatusCode, htmlString: String) -> HTTPMessage
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE',' dd' 'MMM' 'yyyy HH':'mm':'ss zzz"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
let dateString = dateFormatter.string(from: Date())
var httpHeaders: Array<HTTPHeader> = []
httpHeaders.append(HTTPHeader(field: "Date", value: dateString))
httpHeaders.append(HTTPHeader(field: "Server", value: "Swift HTTP Server"))
httpHeaders.append(HTTPHeader(field: "Connection", value: "close"))
httpHeaders.append(HTTPHeader.contentType("text/html"))
httpHeaders.append(HTTPHeader(field: "Content-Length", value: "\(htmlString.count)"))
let body: Data? = htmlString.data(using: .utf8)
let message: HTTPMessage = CFHTTPMessageCreateResponse(kCFAllocatorDefault, statusCode.rawValue, statusCode.description as CFString, kCFHTTPVersion1_1).takeRetainedValue()
message.setHttpHeaders(httpHeaders)
message.setBody(body)
return message
}
func setBody(_ data: Data?)
{
guard let data = data else {
return
}
CFHTTPMessageSetBody(self, data as CFData)
}
func httpHeaders() -> Array<HTTPHeader>
{
guard let allHTTPHeaderFields: Dictionary = CFHTTPMessageCopyAllHeaderFields(self).flatMap({ $0.takeRetainedValue() as? Dictionary<String, String> }) else {
return []
}
let headers: Array<HTTPHeader> = HTTPHeader.dictionary(allHTTPHeaderFields)
return headers
}
func value(forHeadField headField: String) -> String?
{
let value: String? = CFHTTPMessageCopyHeaderFieldValue(self, headField as CFString).map({ $0.takeRetainedValue() as String })
return value
}
func setValue(_ value: String?, forHeadField headField: String)
{
CFHTTPMessageSetHeaderFieldValue(self, headField as CFString, value as CFString?)
}
func setValue(by header: HTTPHeader)
{
self.setValue(header.value, forHeadField: header.field)
}
func setHttpHeaders(_ httpHeaders: Array<HTTPHeader>)
{
httpHeaders.forEach(self.setValue)
}
}
// MARK: - HTTPMessage.StatusCode -
public extension HTTPMessage
{
enum StatusCode: Int
{
// 100 Informational
case `continue` = 100
case switchingProtocols
case processing
// 200 Success
case ok = 200
case created
case accepted
case nonAuthoritativeInformation
case noContent
case resetContent
case partialContent
case multiStatus
case alreadyReported
case iMUsed = 226
// 300 Redirection
case multipleChoices = 300
case movedPermanently
case found
case seeOther
case notModified
case useProxy
case switchProxy
case temporaryRedirect
case permanentRedirect
// 400 Client Error
case badRequest = 400
case unauthorized
case paymentRequired
case forbidden
case notFound
case methodNotAllowed
case notAcceptable
case proxyAuthenticationRequired
case requestTimeout
case conflict
case gone
case lengthRequired
case preconditionFailed
case payloadTooLarge
case uriTooLong
case unsupportedMediaType
case rangeNotSatisfiable
case expectationFailed
case imATeapot
case misdirectedRequest = 421
case unprocessableEntity
case locked
case failedDependency
case upgradeRequired = 426
case preconditionRequired = 428
case tooManyRequests
case requestHeaderFieldsTooLarge = 431
case unavailableForLegalReasons = 451
// 500 Server Error
case internalServerError = 500
case notImplemented
case badGateway
case serviceUnavailable
case gatewayTimeout
case httpVersionNotSupported
case variantAlsoNegotiates
case insufficientStorage
case loopDetected
case notExtended = 510
case networkAuthenticationRequired
}
}
extension HTTPMessage.StatusCode: CustomStringConvertible
{
public var description: String {
let description: String
switch self {
case .`continue`:
description = "Countiune"
case .switchingProtocols:
description = "Switching Protocols"
case .processing:
description = "Processing"
case .ok:
description = "OK"
case .created:
description = "Created"
case .accepted:
description = "Accepted"
case .nonAuthoritativeInformation:
description = "Non Authoritative Information"
case .noContent:
description = "No Content"
case .resetContent:
description = "Reset Content"
case .partialContent:
description = "Rartial Content"
case .multiStatus:
description = "Multi Status"
case .alreadyReported:
description = "Already Reported"
case .iMUsed:
description = "IM Used"
case .multipleChoices:
description = "Multiple Choices"
case .movedPermanently:
description = "Moved Permanently"
case .found:
description = "Found"
case .seeOther:
description = "See Other"
case .notModified:
description = "Not Modified"
case .useProxy:
description = "Use Proxy"
case .switchProxy:
description = "Switch Proxy"
case .temporaryRedirect:
description = "Temporary Redirect"
case .permanentRedirect:
description = "Permanent Redirect"
case .badRequest:
description = "Bad Request"
case .unauthorized:
description = "Unauthorized"
case .paymentRequired:
description = "Payment Required"
case .forbidden:
description = "Forbidden"
case .notFound:
description = "Not Found"
case .methodNotAllowed:
description = "Method Not Allowed"
case .notAcceptable:
description = "Not Acceptable"
case .proxyAuthenticationRequired:
description = "Proxy Authentication Required"
case .requestTimeout:
description = "Request Timeout"
case .conflict:
description = "Conflict"
case .gone:
description = "Gone"
case .lengthRequired:
description = "Length Required"
case .preconditionFailed:
description = "Precondition Failed"
case .payloadTooLarge:
description = "Payload Too Large"
case .uriTooLong:
description = "URI Too Long"
case .unsupportedMediaType:
description = "Unsupported Media Type"
case .rangeNotSatisfiable:
description = "Range Not Satisfiable"
case .expectationFailed:
description = "ExpectationFailed"
case .imATeapot:
description = "I'm a teapot"
case .misdirectedRequest:
description = "Misdirected Request"
case .unprocessableEntity:
description = "Unprocessable Entity"
case .locked:
description = "Locked"
case .failedDependency:
description = "Failed Dependency"
case .upgradeRequired:
description = "Upgrade Required"
case .preconditionRequired:
description = "Precondition Required"
case .tooManyRequests:
description = "Too Many Requests"
case .requestHeaderFieldsTooLarge:
description = "Request Header Fields Too Large"
case .unavailableForLegalReasons:
description = "Unavailable For Legal Reasons"
case .internalServerError:
description = "Internal Server Error"
case .notImplemented:
description = "Not Implemented"
case .badGateway:
description = "Bad Gateway"
case .serviceUnavailable:
description = "Service Unavailable"
case .gatewayTimeout:
description = "Gateway Timeout"
case .httpVersionNotSupported:
description = "Http Version Not Supported"
case .variantAlsoNegotiates:
description = "Variant Also Negotiates"
case .insufficientStorage:
description = "Insufficient Storage"
case .loopDetected:
description = "Loop Detected"
case .notExtended:
description = "Not Extended"
case .networkAuthenticationRequired:
description = "Network Authentication Required"
}
return description
}
}
|
// Generated using Sourcery 0.9.0 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
import UIKit
public func text<Object: UILabel>() -> Lens<Object, String?> {
return Lens(
get: { $0.text },
setter: { $0.text = $1 }
)
}
public func font<Object: UILabel>() -> Lens<Object, UIFont?> {
return Lens(
get: { $0.font },
setter: { $0.font = $1 }
)
}
public func textColor<Object: UILabel>() -> Lens<Object, UIColor?> {
return Lens(
get: { $0.textColor },
setter: { $0.textColor = $1 }
)
}
public func shadowColor<Object: UILabel>() -> Lens<Object, UIColor?> {
return Lens(
get: { $0.shadowColor },
setter: { $0.shadowColor = $1 }
)
}
public func shadowOffset<Object: UILabel>() -> Lens<Object, CGSize> {
return Lens(
get: { $0.shadowOffset },
setter: { $0.shadowOffset = $1 }
)
}
public func textAlignment<Object: UILabel>() -> Lens<Object, NSTextAlignment> {
return Lens(
get: { $0.textAlignment },
setter: { $0.textAlignment = $1 }
)
}
public func lineBreakMode<Object: UILabel>() -> Lens<Object, NSLineBreakMode> {
return Lens(
get: { $0.lineBreakMode },
setter: { $0.lineBreakMode = $1 }
)
}
public func attributedText<Object: UILabel>() -> Lens<Object, NSAttributedString?> {
return Lens(
get: { $0.attributedText },
setter: { $0.attributedText = $1 }
)
}
public func highlightedTextColor<Object: UILabel>() -> Lens<Object, UIColor?> {
return Lens(
get: { $0.highlightedTextColor },
setter: { $0.highlightedTextColor = $1 }
)
}
public func isHighlighted<Object: UILabel>() -> Lens<Object, Bool> {
return Lens(
get: { $0.isHighlighted },
setter: { $0.isHighlighted = $1 }
)
}
public func isEnabled<Object: UILabel>() -> Lens<Object, Bool> {
return Lens(
get: { $0.isEnabled },
setter: { $0.isEnabled = $1 }
)
}
public func numberOfLines<Object: UILabel>() -> Lens<Object, Int> {
return Lens(
get: { $0.numberOfLines },
setter: { $0.numberOfLines = $1 }
)
}
public func adjustsFontSizeToFitWidth<Object: UILabel>() -> Lens<Object, Bool> {
return Lens(
get: { $0.adjustsFontSizeToFitWidth },
setter: { $0.adjustsFontSizeToFitWidth = $1 }
)
}
public func baselineAdjustment<Object: UILabel>() -> Lens<Object, UIBaselineAdjustment> {
return Lens(
get: { $0.baselineAdjustment },
setter: { $0.baselineAdjustment = $1 }
)
}
public func minimumScaleFactor<Object: UILabel>() -> Lens<Object, CGFloat> {
return Lens(
get: { $0.minimumScaleFactor },
setter: { $0.minimumScaleFactor = $1 }
)
}
public func allowsDefaultTighteningForTruncation<Object: UILabel>() -> Lens<Object, Bool> {
return Lens(
get: { $0.allowsDefaultTighteningForTruncation },
setter: { $0.allowsDefaultTighteningForTruncation = $1 }
)
}
public func preferredMaxLayoutWidth<Object: UILabel>() -> Lens<Object, CGFloat> {
return Lens(
get: { $0.preferredMaxLayoutWidth },
setter: { $0.preferredMaxLayoutWidth = $1 }
)
}
|
//
// StatisticsViewModel.swift
// Control It WatchKit Extension
//
// Created by Gonzalo Ivan Santos Portales on 27/02/21.
//
import Foundation
import SwiftUI // to importando só por conta do CGFloat, vou ver se mudo isso
class StatisticsViewModel : ObservableObject {
@Published var habits : [Habit] = []
@Published var yLabels : [Int] = [0,5,10,15,20] // dps posso até fazer um cálculo pra saber esses valores, mas por enquanto vai isso msm
@Published var xLabels : [String] = Calendar.current.veryShortWeekdaySymbols
@Published var barHeights : [Int] = [0,0,0,0,0,0,0]
var repository : HabitRepository
init(repository : HabitRepository) {
self.repository = repository
loadAllHabits()
}
func loadAllHabits() {
repository.getAllHabit { (result) in
DispatchQueue.main.async {
withAnimation {
switch result {
case .success(let newHabits):
self.habits = self.getCurrentWeek(habits: newHabits)
self.barHeights = self.computeBarHeights()
case .failure(let error):
print(error)
}
}
}
}
}
private func getCurrentWeek(habits newHabits : [Habit]) -> [Habit] {
return newHabits.filter { (habit) -> Bool in
Calendar.current.isDayInCurrentWeek(date: habit.date)!
}
}
private func computeBarHeights() -> [Int] {
var barHeights : [Int] = [0,0,0,0,0,0,0]
if habits.isEmpty {
return barHeights
}
let calendar = Calendar.current
var newHabits = habits
var currentDate = newHabits.removeFirst().date
var count : Int = 1
for habit in newHabits {
if calendar.isDate(habit.date, inSameDayAs: currentDate) {
//if calendar.isDate(habit.date, onTheSameWeekDayOf: currentDate) {
count += 1
} else {
let index = calendar.getWeekDayIndexOf(date: currentDate)
barHeights[index] += count
currentDate = habit.date
count = 1
}
}
let index = calendar.getWeekDayIndexOf(date: currentDate)
barHeights[index] += count
return barHeights
}
}
extension Calendar {
func isDayInCurrentWeek(date: Date) -> Bool? {
let currentComponents = Calendar.current.dateComponents([.weekOfYear], from: Date())
let dateComponents = Calendar.current.dateComponents([.weekOfYear], from: date)
guard let currentWeekOfYear = currentComponents.weekOfYear, let dateWeekOfYear = dateComponents.weekOfYear else { return nil }
return currentWeekOfYear == dateWeekOfYear
}
func getWeekDayIndexOf(date : Date) -> Int {
Calendar.current.dateComponents([.weekday], from: date).weekday! - 1
}
func isDate(_ date : Date, onTheSameWeekDayOf secondDate : Date) -> Bool {
let firstComponents = Calendar.current.dateComponents([.weekday], from: date)
let secondComponents = Calendar.current.dateComponents([.weekday], from: secondDate)
return firstComponents.weekday == secondComponents.weekday
}
}
/*extension Sequence where Iterator.Element == Habit {
// ...
}*/
|
//
// HomeTabViewModel.swift
// WatNi
//
// Created by 홍창남 on 2020/02/08.
// Copyright © 2020 hcn1519. All rights reserved.
//
import Foundation
/// Home의 Tab별 ViewModel 공통 구현
protocol HomeTabViewModel {
var userGroups: [WNGroup] { get }
var tabTitle: String { get }
var shouldHideCollectionView: Bool { get }
var shouldHideManagerEmptyView: Bool { get }
var shouldHideParticipantEmptyView: Bool { get }
}
extension HomeTabViewModel {
var shouldHideCollectionView: Bool {
guard let conferences = userGroups.first?.conferences.future else {
return false
}
return conferences.isEmpty
}
var shouldHideManagerEmptyView: Bool {
let isManager = MemberAccess.default.memberMeta?.isManager ?? false
guard isManager else {
return true
}
return !shouldHideCollectionView
}
var shouldHideParticipantEmptyView: Bool {
let isManager = MemberAccess.default.memberMeta?.isManager ?? false
guard !isManager else {
return true
}
return !shouldHideCollectionView
}
}
|
//
// WeekChartCollectionViewCell.swift
// TimeTracker
//
// Created by Hoang Tung on 2/23/20.
// Copyright © 2020 Hoang Tung. All rights reserved.
//
import UIKit
class WeekChartCollectionViewCell: UICollectionViewCell {
var hour: CGFloat?
var maxHour: CGFloat?
let eightLineView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = hexStringToUIColor(hex: "C3C3C3")
return view
}()
let fourLineView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = hexStringToUIColor(hex: "C3C3C3")
return view
}()
let zeroLineView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = hexStringToUIColor(hex: "C3C3C3")
return view
}()
let hourView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 8
view.backgroundColor = hexStringToUIColor(hex: "66A8FB")
let gradient = CAGradientLayer()
gradient.colors = [hexStringToUIColor(hex: "66A8FB").cgColor, hexStringToUIColor(hex: "3B84F1").cgColor]
gradient.locations = [0.0, 1.0]
gradient.frame = view.bounds
view.layer.addSublayer(gradient)
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .white
setupView()
}
override func layoutSubviews() {
super.layoutSubviews()
setupLayout()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupView() {
self.addSubview(eightLineView)
self.addSubview(fourLineView)
self.addSubview(zeroLineView)
self.addSubview(hourView)
}
func setupLayout() {
let height = self.bounds.height
eightLineView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -(height / maxHour! * 8)).isActive = true
eightLineView.heightAnchor.constraint(equalToConstant: 1).isActive = true
eightLineView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true
eightLineView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0).isActive = true
fourLineView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -(height / maxHour! * 4)).isActive = true
fourLineView.heightAnchor.constraint(equalToConstant: 1).isActive = true
fourLineView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true
fourLineView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0).isActive = true
zeroLineView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
zeroLineView.heightAnchor.constraint(equalToConstant: 1).isActive = true
zeroLineView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true
zeroLineView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0).isActive = true
hourView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
hourView.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0).isActive = true
hourView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.6).isActive = true
hourView.heightAnchor.constraint(equalToConstant: height / self.maxHour! * self.hour!).isActive = true
}
}
|
//
// ViewController.swift
// CoreMotionAccelerometer
//
// Created by Andreas Oscar Olsson on 2020-05-31.
// Copyright © 2020 Andreas Oscar Olsson. All rights reserved.
//
import UIKit
import CoreMotion
class ViewController: UIViewController {
@IBOutlet weak var xAcc: UITextField!
@IBOutlet weak var yAcc: UITextField!
@IBOutlet weak var zAcc: UITextField!
var motion = CMMotionManager()
override func viewDidLoad() {
super.viewDidLoad()
self.view.bringSubviewToFront(xAcc)
myAccelerometer()
}
func myAccelerometer() {
motion.accelerometerUpdateInterval = 0.5
motion.startAccelerometerUpdates(to: OperationQueue.current!) { (data,error) in
print(data as Any)
if let trueData = data {
self.view.reloadInputViews()
let x = trueData.acceleration.x
let y = trueData.acceleration.y
let z = trueData.acceleration.z
self.xAcc.text = "x: \(Double(x).rounded(toPlaces: 3))"
self.yAcc.text = "y: \(Double(y).rounded(toPlaces: 3))"
self.zAcc.text = "z: \(Double(z).rounded(toPlaces: 3))"
}
}
}
}
extension Double {
func rounded(toPlaces places:Int) -> Double {
let divisior = pow(10.0, Double(places))
return (self * divisior).rounded() / divisior
}
}
|
//: Header 使用简单的样式匹配方式
//: [Previous](@previous)
import Foundation
//: 匹配值的方式
let orgin = (x: 0, y: 0)
let pt1 = (x: 0, y: 0);
if pt1.x == orgin.x && pt1.y == orgin.y{
print("@Origin")
}
if case (0, 0) == pt1 {
print("@Origin")
}
switch pt1 {
case (0, 0):
print("@origin")
case (_, 0):
print("on x axis")
case (0, _):
print("on y axis")
case (-1...1, -1...1):
print("inside 1x1 square")
default:
break
}
//let array1 = [1, 1, 2, 2, 2]
//
//for case 2 in array1 {
// print("found two") // Three times
//}
//
//////:2.把匹配的内容绑定到变量
//
//switch pt1 {
//case (let x, 0):
// print("(\(x), 0) is on x axis")
//case (0, let y):
// print("(0, \(y)) is on y axis")
//default:
// break
//}
//
//
//enum Direction {
// case north, south, east, west(abbr: String)
//}
//
//let west = Direction.west(abbr: "W")
//
//
//if case .west = west {
// print(west) // west("W")
//}
//
//if case .west(let direction) = west {
// print(direction) // W
//}
//
////:3.自动提取optional的值
//
//let skills: [String?] =
// ["Swift", nil, "PHP", "JavaScirpt", nil]
//
//for case let skill? in skills {
// print(skill) // Swift PHP JavaScript
//}
//
//
////:4.自动绑定类型转换的结果
//
//let someValues: [Any] = [1, 1.0, "One"]
//for value in someValues {
// switch value {
// case let v as Int: //判断类型
// print("Integer \(v)")
// case let v as Double:
// print("Double \(v)")
// case let v as String:
// print("String \(v)")
// default:
// print("Invalid value")
// }
//}
//// Integer 1
//// Double 1.0
//// String One
//for value in someValues {
// switch value {
// case is Int: // 判断类型
// print("Integer")
// // omit for simplicity...
//}
//
//: [Next](@next)
|
//
// RegisterController.swift
// CharityChecker
//
// Created by Philip Tam on 2018-04-19.
// Copyright © 2018 CharityDonate. All rights reserved.
//
import UIKit
import GoogleMaps
import GooglePlaces
import BigInt
import web3swift
class RegisterController: UIViewController {
var type : String!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var pickerView: UIPickerView!
@IBOutlet weak var firstLabel: UILabel!
@IBOutlet weak var secondLabel: UILabel!
@IBOutlet weak var thirdLabel: UILabel!
@IBOutlet weak var firstField: UITextField!
@IBOutlet weak var secondField: UITextField!
@IBOutlet weak var thirdField: UITextField!
@IBOutlet var charityLabels: [UILabel]!
@IBOutlet var charityField: [UITextField]!
@IBOutlet weak var mapButton: UIButton!
@IBOutlet weak var addressLabel: UILabel!
var address : String?
var latitude : CLLocationDegrees?
var longitude : CLLocationDegrees?
let operatorTypeArray = ["Charity","Charity-Authorized","Unaffiliated Collector"]
var operatorType : String = ""
override func viewDidLoad() {
super.viewDidLoad()
firstField.delegate = self
secondField.delegate = self
thirdField.delegate = self
pickerView.delegate = self
pickerView.dataSource = self
updateUI(type: type)
view.sendSubview(toBack: imageView)
addressLabel.adjustsFontSizeToFitWidth = true
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func handleRegister(_ sender: UIButton) {
let userDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let keystoreManager = KeystoreManager.managerForPath(userDir + "/keystore")
var ks : EthereumKeystoreV3?
ks = keystoreManager?.walletForAddress((keystoreManager?.addresses![0])!) as! EthereumKeystoreV3
if type == "Charity"{
//TO DO: RegistrationKey & Name
let registrationKey = UInt(firstField.text!)
let name = secondField.text
guard let sender = ks?.addresses?.first else {return}
let web3Rinkeby = Web3.InfuraRinkebyWeb3()
web3Rinkeby.addKeystoreManager(keystoreManager)
var options = Web3Options.defaultOptions()
options.gasLimit = BigUInt(10000000)
options.from = ks?.addresses?[0]
options.value = 0
print("arrived")
let platform = web3Rinkeby.contract(jsonString, at: contractAddress, abiVersion: 2)
let parameters = [name!, registrationKey!] as [AnyObject]
let error = platform?.method("createCharity", parameters: parameters, options: options)?.send(password: "Whocares").error
if error == nil{
performSegue(withIdentifier: "goToMainMenu", sender: self)
}else{
print(error)
}
}
else if type == "Operator"{
//TO DO: Name & Telephone & Type
let name = secondField.text
let telephone = UInt(thirdField.text!)
let type = operatorType
guard let sender = ks?.addresses?.first else {return}
let web3Rinkeby = Web3.InfuraRinkebyWeb3()
web3Rinkeby.addKeystoreManager(keystoreManager)
var options = Web3Options.defaultOptions()
options.gasLimit = BigUInt(10000000)
options.from = ks?.addresses?[0]
options.value = 0
let platform = web3Rinkeby.contract(jsonString, at: contractAddress, abiVersion: 2)
let parameters = [name!, telephone!, type] as [AnyObject]
let error = platform?.method("createOperator", parameters: parameters, options: options)?.send(password: "Whocares").error
if error == nil{
performSegue(withIdentifier: "goToMainMenu", sender: self)
}else{
print(error)
}
}
else{
//TO DO: Address & Name
var coordinatesIsAddress : Bool
if address != nil{
coordinatesIsAddress = true
}
else{
coordinatesIsAddress = false
}
let name = secondField.text
let latitude = (self.latitude) as! Double
let longitude = (self.longitude) as! Double
guard let sender = ks?.addresses?.first else {return}
let web3Rinkeby = Web3.InfuraRinkebyWeb3()
web3Rinkeby.addKeystoreManager(keystoreManager)
var options = Web3Options.defaultOptions()
options.gasLimit = BigUInt(10000000)
options.from = ks?.addresses?[0]
options.value = 0
let platform = web3Rinkeby.contract(jsonString, at: contractAddress, abiVersion: 2)
let parameters = [name!, String(latitude), String(longitude) ] as [AnyObject]
let error = platform?.method("createOwner", parameters: parameters, options: options)?.send(password: "Whocares").error
if error == nil{
performSegue(withIdentifier: "goToMainMenu", sender: self)
}else{
print(error)
}
}
}
override func viewWillAppear(_ animated: Bool) {
if longitude != nil{
addressLabel.text = "Google Coordinates: longitude: \(longitude!), latitude: \(latitude!)"
}
if address != nil{
addressLabel.text = "Address: \(address!)"
}
}
func updateUI(type : String){
if type == "Charity"{
firstLabel.text = "Registration Number:"
charityLabels.forEach { (label) in
label.isHidden = true
}
charityField.forEach { (textfield) in
textfield.isHidden = true
}
addressLabel.isHidden = true
pickerView.isHidden = true
mapButton.isHidden = true
}
else if type == "Owner"{
charityLabels.forEach { (label) in
label.isHidden = true
}
charityField.forEach { (textfield) in
textfield.isHidden = true
}
pickerView.isHidden = true
firstField.isHidden = true
}
else if type == "Operator"{
mapButton.isHidden = true
addressLabel.isHidden = true
firstLabel.isHidden = true
firstField.isHidden = true
}
navigationItem.title = type
}
@IBAction func mapButtonPressed(_ sender: Any) {
performSegue(withIdentifier: "goToMap", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToMap"{
address = nil
longitude = nil
latitude = nil
}
if segue.identifier == "goToMainMenu"{
let destinationVC = segue.destination as! MainMenuController
destinationVC.type = type
}
}
}
extension RegisterController : UIPickerViewDelegate, UIPickerViewDataSource{
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return operatorTypeArray.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return operatorTypeArray[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
operatorType = operatorTypeArray[row]
}
}
extension RegisterController : UITextFieldDelegate{
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
|
//
// Rank.swift
// iosFinal
//
// Created by User02 on 2019/12/26.
// Copyright © 2019 tflee. All rights reserved.
//
import SwiftUI
struct Rank: View {
var body: some View {
NavigationView {
ZStack {
LinearGradient(gradient: Gradient(colors: [Color.black,Color.red,Color.black]), startPoint: UnitPoint(x:0,y:0), endPoint: UnitPoint(x:1,y:1))
VStack{
NavigationLink(destination: dcardlist())
{
Image("Western")
.renderingMode(.original)
.resizable().frame(width: 300, height: 300)
.clipShape(Circle())
.overlay(Circle().stroke(Color.yellow ,lineWidth:4))
.shadow(radius: 40)
}
NavigationLink(destination: youtubeview())
{
Image("Eastern")
.renderingMode(.original)
.resizable().frame(width: 300, height: 300)
.clipShape(Circle())
.overlay(Circle().stroke(Color.yellow ,lineWidth:4))
.shadow(radius: 40)
}
}
}.navigationBarTitle("Conferences")
}
}
}
struct Rank_Previews: PreviewProvider {
static var previews: some View {
Rank()
}
}
|
// SwiftCurriculum: https://github.com/brennanMKE/SwiftCurriculum
// Blog Post: https://medium.com/swift-curriculum/swift-weak-vars-9aac18751f00
// Swift Version: 3.0
// A weak var allows for preventing circular references which would result in memory leaks.
// Below a person can have a reference to an apartment and an apartment has a tentant
// property referencing a person.
class Person {
let name: String
var apartment: Apartment?
init(name: String) { self.name = name }
deinit { print("\(name) is being deinitialized") }
}
class Apartment {
let number: Int
weak var tenant: Person?
init(number: Int) { self.number = number }
deinit { print("Apartment #\(number) is being deinitialized") }
}
var person: Person? = Person(name: "Tim")
var apartment: Apartment? = Apartment(number: 101)
// set apartment in person to the apartment
person?.apartment = apartment
// set the tenant with the optional value for person
apartment?.tenant = person
// now there are weak references between both variables
// clear person value which is a weak reference in apartment
person = nil
// show that person is now nil because it is a weak var
apartment?.tenant
// clear out apartment
apartment = nil
|
//
// CarSharingOperations.swift
// prkng-ios
//
// Created by Antonino Urbano on 2015-10-16.
// Copyright © 2015 PRKNG. All rights reserved.
//
import Foundation
class CarSharingOperations {
static func getCarShares(location location: CLLocationCoordinate2D, radius: Float, nearest: Int, completion: ((carShares: [NSObject], mapMessage: String?) -> Void)) {
let url = APIUtility.rootURL() + "carshares"
let radiusStr = NSString(format: "%.0f", radius)
let companies: [String?] = [
!Settings.hideCar2Go() ? "car2go" : nil,
!Settings.hideCommunauto() ? "communauto" : nil,
!Settings.hideAutomobile() ? "auto-mobile" : nil,
!Settings.hideZipcar() ? "zipcar" : nil,
]
let companiesString = Array.filterNils(companies).joinWithSeparator(",")
if companiesString == "" {
let mapMessage = MapMessageView.createMessage(count: 0, response: nil, error: nil, origin: .Cars)
completion(carShares: [], mapMessage: mapMessage)
return
}
let params = [
"latitude": location.latitude,
"longitude": location.longitude,
"radius" : radiusStr,
"company" : companiesString,
"permit" : "all",
"nearest": nearest
]
APIUtility.authenticatedManager().request(.GET, url, parameters: params).responseSwiftyJSONAsync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), options: NSJSONReadingOptions.AllowFragments) {
(request, response, json, error) in
DDLoggerWrapper.logVerbose(String(format: "Request: %@", request))
DDLoggerWrapper.logVerbose(String(format: "Response: %@", response ?? ""))
// DDLoggerWrapper.logVerbose(String(format: "Json: %@", json.description))
DDLoggerWrapper.logVerbose(String(format: "error: %@", error ?? ""))
let carShareJsons: Array<JSON> = json["features"].arrayValue
let carShares = carShareJsons.map({ (carShareJson) -> CarShare in
CarShare(json: carShareJson)
})
let mapMessage = MapMessageView.createMessage(count: carShares.count, response: response, error: error, origin: .Cars)
dispatch_async(dispatch_get_main_queue(), {
() -> Void in
completion(carShares: carShares, mapMessage: mapMessage)
if response != nil && response?.statusCode == 401 {
DDLoggerWrapper.logError(String(format: "Error: Could not authenticate. Reason: %@", json.description))
Settings.logout()
}
})
}
}
static func getCarShareLots(location location: CLLocationCoordinate2D, radius: Float, nearest: Int, completion: ((carShareLots: [NSObject], mapMessage: String?) -> Void)) {
let url = APIUtility.rootURL() + "carshare_lots"
let radiusStr = NSString(format: "%.0f", radius)
let companies: [String?] = [
!Settings.hideCar2Go() ? "car2go" : nil,
!Settings.hideCommunauto() ? "communauto" : nil,
!Settings.hideAutomobile() ? "auto-mobile" : nil,
!Settings.hideZipcar() ? "zipcar" : nil,
]
let companiesString = Array.filterNils(companies).joinWithSeparator(",")
let params = [
"latitude": location.latitude,
"longitude": location.longitude,
"radius" : radiusStr,
"company" : companiesString,
"permit" : "all",
"nearest": nearest
]
APIUtility.authenticatedManager().request(.GET, url, parameters: params).responseSwiftyJSONAsync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), options: NSJSONReadingOptions.AllowFragments) {
(request, response, json, error) in
DDLoggerWrapper.logVerbose(String(format: "Request: %@", request))
DDLoggerWrapper.logVerbose(String(format: "Response: %@", response ?? ""))
// DDLoggerWrapper.logVerbose(String(format: "Json: %@", json.description))
DDLoggerWrapper.logVerbose(String(format: "error: %@", error ?? ""))
let carShareLotJsons: Array<JSON> = json["features"].arrayValue
let carShareLots = carShareLotJsons.map({ (carShareLotJson) -> CarShareLot in
CarShareLot(json: carShareLotJson)
})
let mapMessage = MapMessageView.createMessage(count: carShareLots.count, response: response, error: error, origin: .Spots)
dispatch_async(dispatch_get_main_queue(), {
() -> Void in
completion(carShareLots: carShareLots, mapMessage: mapMessage)
if response != nil && response?.statusCode == 401 {
DDLoggerWrapper.logError(String(format: "Error: Could not authenticate. Reason: %@", json.description))
Settings.logout()
}
})
}
}
static func login(carSharingType: CarSharingType) {
switch carSharingType {
case .CommunautoAutomobile, .Communauto:
//open the web view
let vc = CarSharingOperations.CommunautoAutomobile.loginVC
(UIApplication.sharedApplication().delegate as! AppDelegate).window?.rootViewController?.presentViewController(vc, animated: true, completion: { () -> Void in
})
case .Car2Go:
CarSharingOperations.Car2Go.getAndSaveCar2GoToken({ (token, tokenSecret) -> Void in
})
case .Zipcar, .Generic:
break
}
}
static func reserveCarShare(carShare: CarShare, fromVC: UIViewController, completion: (Bool) -> Void) {
let reservationCompletion = { (reserveResult: ReturnStatus) -> Void in
switch reserveResult {
case .Success:
Settings.saveReservedCarShare(carShare)
SpotOperations.checkout({ (completed) -> Void in
Settings.checkOut()
})
AnalyticsOperations.reservedCarShareEvent(carShare, completion: { (completed) -> Void in })
completion(true)
case .FailedError:
let alert = UIAlertView()
alert.message = "could_not_reserve".localizedString
alert.addButtonWithTitle("OK")
alert.show()
completion(false)
case .FailedNotLoggedIn:
let alert = UIAlertView()
alert.message = "could_not_reserve_not_logged_in".localizedString
alert.addButtonWithTitle("OK")
alert.show()
CarSharingOperations.login(carShare.carSharingType)
completion(false)
}
SVProgressHUD.dismiss()
}
switch carShare.carSharingType {
case .CommunautoAutomobile:
SVProgressHUD.show()
CarSharingOperations.CommunautoAutomobile.reserveAutomobile(carShare, completion: reservationCompletion)
case .Communauto:
//open the web view
let carID = carShare.partnerId ?? ""
let vc = PRKWebViewController(englishUrl: CommunautoAutomobile.communautoReserveUrlEnglish + carID, frenchUrl: CommunautoAutomobile.communautoReserveUrlFrench + carID)
fromVC.presentViewController(vc, animated: true, completion: nil)
completion(false)
case .Zipcar:
//open the zip car app if applicable
Zipcar.goToAppOrAppStore()
completion(false)
case .Car2Go:
//open the zip car app if applicable
SVProgressHUD.show()
CarSharingOperations.Car2Go.reserveCar(carShare, completion: reservationCompletion)
case .Generic:
print("This car share type cannot be reserved.")
completion(false)
}
}
static func cancelCarShare(carShare: CarShare, fromVC: UIViewController, completion: (Bool) -> Void) {
let cancelationCompletion = { (cancelResult: ReturnStatus) -> Void in
switch cancelResult {
case .Success:
let alert = UIAlertView()
alert.message = "cancelled_reservation".localizedString
alert.addButtonWithTitle("OK")
alert.show()
Settings.saveReservedCarShare(nil)
completion(true)
case .FailedError:
let alert = UIAlertView()
alert.message = "could_not_cancel_reservation".localizedString
alert.addButtonWithTitle("OK")
alert.show()
completion(false)
case .FailedNotLoggedIn:
let alert = UIAlertView()
alert.message = "could_not_cancel_not_logged_in".localizedString
alert.addButtonWithTitle("OK")
alert.show()
let vc = CarSharingOperations.CommunautoAutomobile.loginVC
fromVC.presentViewController(vc, animated: true, completion: nil)
completion(false)
}
SVProgressHUD.dismiss()
}
switch carShare.carSharingType {
case .CommunautoAutomobile:
SVProgressHUD.show()
CarSharingOperations.CommunautoAutomobile.cancelAutomobile(carShare, completion: cancelationCompletion)
case .Car2Go:
SVProgressHUD.show()
CarSharingOperations.Car2Go.cancelCar(carShare, completion: cancelationCompletion)
case .Communauto, .Zipcar, .Generic:
print("This car share type cannot be cancelled.")
completion(false)
}
}
struct Car2Go {
static let consumerKey = "prkng"
static let consumerSecret = "crUKsH0t4RQeyKYOy%3E%5D6"
static let callbackURLString = "ng.prk.prkng-ios://oauth-car2go-success"
static let endpointsHostUrlString = "www.car2go.com/api/v2.1"
static func goToAppOrAppStore() {
let url = NSURL(string: "car2go://")!
let isUrlSupported = UIApplication.sharedApplication().canOpenURL(url)
if isUrlSupported {
UIApplication.sharedApplication().openURL(url)
} else {
UIApplication.sharedApplication().openURL(NSURL(string: "itms-apps://itunes.apple.com/app/id514921710")!)
}
}
static func isLoggedInSynchronous(shouldValidateToken validateToken: Bool) -> Bool {
let token = Settings.car2GoAccessToken()
let tokenSecret = Settings.car2GoAccessTokenSecret()
if token != nil && tokenSecret != nil {
if validateToken {
//just a test to see if we're logged in... note: ulm is NOT a valid location
let testLoginRequest = TDOAuth.URLRequestForPath("/accounts", GETParameters: ["format": "json", "loc": "ulm"], scheme: "https", host: endpointsHostUrlString, consumerKey: consumerKey, consumerSecret: consumerSecret, accessToken: token, tokenSecret: tokenSecret)
var response: NSURLResponse?
do {
let _ = try NSURLConnection.sendSynchronousRequest(testLoginRequest, returningResponse: &response)
let success = (response as! NSHTTPURLResponse).statusCode < 400
return success
} catch {
return false
}
}
return true
}
return false
}
static func isLoggedInAsynchronous(shouldValidateToken validateToken: Bool, completion: ((loggedIn: Bool) -> Void)) {
let token = Settings.car2GoAccessToken()
let tokenSecret = Settings.car2GoAccessTokenSecret()
if token != nil && tokenSecret != nil {
if validateToken {
//just a test to see if we're logged in... note: ulm is NOT a valid location
let testLoginRequest = TDOAuth.URLRequestForPath("/accounts", GETParameters: ["format": "json", "loc": "ulm"], scheme: "https", host: endpointsHostUrlString, consumerKey: consumerKey, consumerSecret: consumerSecret, accessToken: token, tokenSecret: tokenSecret)
NSURLConnection.sendAsynchronousRequest(testLoginRequest, queue: NSOperationQueue.mainQueue(), completionHandler: { (response, data, error) -> Void in
let success = error == nil || (response as! NSHTTPURLResponse).statusCode < 400
completion(loggedIn: success)
})
} else {
completion(loggedIn: true)
}
} else {
completion(loggedIn: false)
}
}
static func logout() {
Settings.setCar2GoBookingID(nil)
Settings.setCar2GoAccessToken(nil)
Settings.setCar2GoAccessTokenSecret(nil)
}
static func getAccountID(completion: (accountID: String?) -> Void) {
let token = Settings.car2GoAccessToken()
let tokenSecret = Settings.car2GoAccessTokenSecret()
var cityName = ""
switch Settings.selectedCity().name {
case "newyork":
cityName = "newyorkcity"
default:
cityName = Settings.selectedCity().name
}
let testLoginRequest = TDOAuth.URLRequestForPath("/accounts", GETParameters: ["format": "json", "loc": cityName], scheme: "https", host: endpointsHostUrlString, consumerKey: consumerKey, consumerSecret: consumerSecret, accessToken: token, tokenSecret: tokenSecret)
NSURLConnection.sendAsynchronousRequest(testLoginRequest, queue: NSOperationQueue.mainQueue(), completionHandler: { (response, data, error) -> Void in
let success = error == nil || (response as! NSHTTPURLResponse).statusCode < 400
if success && data != nil {
let json = JSON(data: data!)
let accountID = json["account"][0]["accountId"].rawString()
completion(accountID: accountID == "null" ? nil : accountID)
return
}
completion(accountID: nil)
})
}
static func getAndSaveCar2GoToken(completion: (token: String?, tokenSecret: String?) -> Void) {
let tokenDict = ["oauth_callback": "oob"] //type is [NSObject : AnyObject]()
let tokenRequest = TDOAuth.URLRequestForPath("/reqtoken", POSTParameters: tokenDict, host: "www.car2go.com/api", consumerKey: consumerKey, consumerSecret: consumerSecret, accessToken: nil, tokenSecret: nil)
NSURLConnection.sendAsynchronousRequest(tokenRequest, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
if data != nil {
var params = [NSObject : AnyObject]()
let stringData = String(data: data!, encoding: NSUTF8StringEncoding)
let stringArray = stringData?.componentsSeparatedByString("&") ?? []
for substring in stringArray {
let secondArray = substring.componentsSeparatedByString("=")
params[secondArray[0]] = secondArray[1]
}
let token1 = params["oauth_token"] as? String ?? ""
let tokenSecret = params["oauth_token_secret"] as? String ?? ""
//we have the token and token request, now open Safari View Controller to get the user to authenticate
let authUrlString = String(format:"https://www.car2go.com/api/authorize?oauth_token=%@&token_secret=%@", token1, tokenSecret)
let authVC = PRKWebViewController(url: authUrlString)
authVC.willLoadRequestCallback = { (vc, request) -> () in
if (request.URL?.relativeString ?? "").containsString(callbackURLString + "?") {
vc.backButtonTapped()
var params = [NSObject : AnyObject]()
let paramsString = (request.URL?.relativeString ?? "").stringByReplacingOccurrencesOfString(callbackURLString + "?", withString: "")
let stringArray = paramsString.componentsSeparatedByString("&") ?? []
for substring in stringArray {
let secondArray = substring.componentsSeparatedByString("=")
params[secondArray[0]] = secondArray[1]
}
let token2 = params["oauth_token"] as? String ?? ""
let verifier = params["oauth_verifier"] as? String ?? ""
let accessTokenDict = ["oauth_verifier": verifier] //type is [NSObject : AnyObject]()
let accessTokenRequest = TDOAuth.URLRequestForPath("/accesstoken", POSTParameters: accessTokenDict, host: "www.car2go.com/api", consumerKey: consumerKey, consumerSecret: consumerSecret, accessToken: token2, tokenSecret: tokenSecret)
NSURLConnection.sendAsynchronousRequest(accessTokenRequest, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
if data != nil {
var params = [NSObject : AnyObject]()
let stringData = String(data: data!, encoding: NSUTF8StringEncoding)
let stringArray = stringData?.componentsSeparatedByString("&") ?? []
for substring in stringArray {
let secondArray = substring.componentsSeparatedByString("=")
params[secondArray[0]] = secondArray[1]
}
//save these two!
let finalToken = params["oauth_token"] as? String ?? ""
let finalTokenSecret = params["oauth_token_secret"] as? String ?? ""
Settings.setCar2GoAccessToken(finalToken)
Settings.setCar2GoAccessTokenSecret(finalTokenSecret)
AnalyticsOperations.carShareLoginEvent("car2go", completion: { (completed) -> Void in })
completion(token: finalToken, tokenSecret: finalTokenSecret)
}
if error != nil {
completion(token: nil, tokenSecret: nil)
}
}
}
}
(UIApplication.sharedApplication().delegate as! AppDelegate).window?.rootViewController?.presentViewController(authVC, animated: true, completion: { () -> Void in
})
}
if error != nil {
DDLoggerWrapper.logError(error!.description)
completion(token: nil, tokenSecret: nil)
}
}
}
static func reserveCar(carShare: CarShare, completion: (ReturnStatus) -> Void) {
getAccountID { (accountID) -> Void in
if accountID != nil {
let token = Settings.car2GoAccessToken()
let tokenSecret = Settings.car2GoAccessTokenSecret()
let params = ["format": "json",
"vin": carShare.vin! ?? "",
"account": accountID!,
]
let testLoginRequest = TDOAuth.URLRequestForPath("/bookings", parameters: params, host: endpointsHostUrlString, consumerKey: consumerKey, consumerSecret: consumerSecret, accessToken: token, tokenSecret: tokenSecret, scheme: "https", requestMethod: "POST", dataEncoding: TDOAuthContentType.UrlEncodedForm, headerValues: nil, signatureMethod: TDOAuthSignatureMethod.HmacSha1)
NSURLConnection.sendAsynchronousRequest(testLoginRequest, queue: NSOperationQueue.mainQueue(), completionHandler: { (response, data, error) -> Void in
let success = error == nil || (response as! NSHTTPURLResponse).statusCode < 400
if success && data != nil {
let json = JSON(data: data!)
let returnCode = json["returnValue"]["code"].intValue
let bookingID = json["booking"][0]["bookingId"].rawString()
if returnCode == 0 {
Settings.setCar2GoBookingID(bookingID)
completion(ReturnStatus.Success)
} else {
completion(ReturnStatus.FailedError)
}
} else {
completion(ReturnStatus.FailedError)
}
})
} else {
completion(ReturnStatus.FailedNotLoggedIn)
}
}
}
static func cancelCar(carShare: CarShare, completion: (ReturnStatus) -> Void) {
let token = Settings.car2GoAccessToken()
let tokenSecret = Settings.car2GoAccessTokenSecret()
let bookingID = Settings.car2GoBookingID() ?? ""
let params = ["format": "json", "bookingId": bookingID]
let testLoginRequest = TDOAuth.URLRequestForPath("/booking/"+bookingID, parameters: params, host: endpointsHostUrlString, consumerKey: consumerKey, consumerSecret: consumerSecret, accessToken: token, tokenSecret: tokenSecret, scheme: "https", requestMethod: "DELETE", dataEncoding: TDOAuthContentType.UrlEncodedForm, headerValues: nil, signatureMethod: TDOAuthSignatureMethod.HmacSha1)
NSURLConnection.sendAsynchronousRequest(testLoginRequest, queue: NSOperationQueue.mainQueue(), completionHandler: { (response, data, error) -> Void in
let success = error == nil || (response as! NSHTTPURLResponse).statusCode < 400
if success && data != nil {
let json = JSON(data: data!)
let returnCode = json["returnValue"]["code"].intValue
if returnCode == 0 {
completion(ReturnStatus.Success)
Settings.setCar2GoBookingID(nil)
} else {
completion(ReturnStatus.FailedError)
}
} else {
completion(ReturnStatus.FailedError)
}
})
}
}
struct Zipcar {
static func goToAppOrAppStore() {
let url = NSURL(string: "zipcar://")!
let isUrlSupported = UIApplication.sharedApplication().canOpenURL(url)
if isUrlSupported {
UIApplication.sharedApplication().openURL(url)
} else {
UIApplication.sharedApplication().openURL(NSURL(string: "itms-apps://itunes.apple.com/app/id329384702")!)
}
}
}
struct CommunautoAutomobile {
static let loginApiUrl = "https://www.reservauto.net/Scripts/Client/Ajax/Mobile/Login.asp"
static let loginWebUrl = "https://www.reservauto.net/Scripts/Client/Mobile/Login.asp"
static let loginWebUrlEnglish = "https://www.reservauto.net/Scripts/Client/Mobile/Login.asp?BranchID=1&CurrentLanguageID=2"
static let loginWebUrlFrench = "https://www.reservauto.net/Scripts/Client/Mobile/Login.asp?BranchID=1&CurrentLanguageID=1"
static let communautoReserveUrlEnglish = "https://www.reservauto.net/Scripts/Client/Mobile/ReservationAdd.asp?BranchID=1&CurrentLanguageID=2"
static let communautoReserveUrlFrench = "https://www.reservauto.net/Scripts/Client/Mobile/ReservationAdd.asp?BranchID=1&CurrentLanguageID=1"
//these next 2 require CarID to be appended
let communautoReserveUrlEnglish = "https://www.reservauto.net/Scripts/Client/ReservationAdd.asp?Step=2&CurrentLanguageID=2&IgnoreError=False&NbrStation=0&CarID="
let communautoReserveUrlFrench = "https://www.reservauto.net/Scripts/Client/ReservationAdd.asp?Step=2&CurrentLanguageID=1&IgnoreError=False&NbrStation=0&CarID="
// static let communautoReserveUrl = "https://www.reservauto.net/Scripts/Client/ReservationAdd.asp?Step=2&CurrentLanguageID="+ lang +"&IgnoreError=False&NbrStation=0&ReservationCityID="+ iRes[0] +"&CarID="+ lngCarID +"&StartYear="+ sD[2] +"&StartMonth="+ sD[1] +"&StartDay="+ sD[0] +"&StartHour="+ iRes[2] +"&StartMinute="+ iRes[3] +"&EndYear="+ eD[2] +"&EndMonth="+ eD[1] +"&EndDay="+ eD[0] +"&EndHour="+ iRes[5] +"&EndMinute="+ iRes[6] +"&StationID="+ StationID +"&OrderBy=2&Accessories="+ iRes[7] +"&Brand="+ iRes[8] +"&ShowGrid=False&ShowMap=True&FeeType="+ iRes[9] +"&DestinationID="+ iRes[10] +"&CustomerLocalizationID="
//note: customerID is actually providerNo
static let automobileCurrentBookingUrl = "https://www.reservauto.net/WCF/LSI/LSIBookingService.asmx/GetCurrentBooking"//?CustomerID=%@"
static let automobileCreateBookingUrl = "https://www.reservauto.net/WCF/LSI/LSIBookingService.asmx/CreateBooking"//?CustomerID=%@&VehicleID=%@"
static let automobileCancelBookingUrl = "https://www.reservauto.net/WCF/LSI/LSIBookingService.asmx/CancelBooking"//?CustomerID=%@&VehicleID=%@"
static var loginVC: PRKWebViewController {
let vc = PRKWebViewController(englishUrl: loginWebUrlEnglish, frenchUrl: loginWebUrlFrench)
vc.didFinishLoadingCallback = { (vc, webView) -> () in
webView.stringByEvaluatingJavaScriptFromString("document.getElementById(\"RememberMe\").checked = true; document.getElementById(\"RememberMe\").parentElement.hidden = true;")
self.getAndSaveCommunautoCustomerID({ (id) -> Void in
if id != nil {
vc.backButtonTapped()
}
})
}
return vc
}
static func getAndSaveCommunautoCustomerID(completion: (String?) -> Void) {
let url = NSURL(string: loginApiUrl)
let request = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
if error != nil || data == nil {
DDLoggerWrapper.logError("Either there was an error with the request or there was no data returned")
deleteCommunautoCustomerID()
completion(nil)
return
}
if data != nil {
var json = JSON(data: data!)
if json == JSON.null {
var stringData = String(data: data!, encoding: NSUTF8StringEncoding) ?? " "
stringData = stringData[1..<stringData.length()-1]
if let properData = stringData.dataUsingEncoding(NSUTF8StringEncoding) {
json = JSON(data: properData)
}
}
//if the id string is present, then return true, else return false
var returnString: String?
if let providerNo = json["data"][0]["ProviderNo"].string {
if providerNo != "" {
print("Auto-mobile ProviderNo is ", providerNo)
Settings.setAutomobileProviderNo(providerNo)
saveCommunautoCookies()
returnString = providerNo
}
}
if let customerID = json["data"][0]["CustomerID"].string {
if customerID != "" {
if (Settings.communautoCustomerID() ?? "") != customerID {
AnalyticsOperations.carShareLoginEvent("communauto-auto-mobile", completion: { (completed) -> Void in })
}
print("Communauto/Auto-mobile Customer ID is ", customerID)
Settings.setCommunautoCustomerID(customerID)
saveCommunautoCookies()
if returnString == nil {
returnString = customerID
}
}
}
if returnString != nil {
completion(returnString)
return
}
}
deleteCommunautoCustomerID()
completion(nil)
return
}
}
static func deleteCommunautoCustomerID() {
Settings.setCommunautoCustomerID(nil)
deleteCommunautoCookies()
}
private static func saveCommunautoCookies() {
//this part is to save cookies, but because we set our cache policy properly any UIWebView and NSURLConnection will use the cookie jar!
let capturedCookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(NSURL(string: loginWebUrl)!) ?? []
for i in 0..<capturedCookies.count {
let cookie = capturedCookies[i]
NSUserDefaults.standardUserDefaults().setObject(cookie.properties, forKey: "prkng_communauto_cookie_"+String(i))
}
NSUserDefaults.standardUserDefaults().setInteger(capturedCookies.count, forKey: "prkng_communauto_cookie_count")
}
private static func deleteCommunautoCookies() {
let capturedCookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(NSURL(string: loginWebUrl)!) ?? []
for cookie in capturedCookies {
NSHTTPCookieStorage.sharedHTTPCookieStorage().deleteCookie(cookie)
}
//this commented out part is to put saved cookies back into the cookie jar, but because we set our cache policy properly any UIWebView and NSURLConnection will use the cookie jar!
// let cookieCount = NSUserDefaults.standardUserDefaults().integerForKey("prkng_communauto_cookie_count")
// for i in 0..<cookieCount {
// if let cookieProperties = NSUserDefaults.standardUserDefaults().objectForKey("prkng_communauto_cookie_"+String(i)) as? [String : AnyObject] {
//// if cookieProperties["Name"] as? String ?? "" == "mySession" {
//// NSLog("MY SESH")
//// }
// if let cookie = NSHTTPCookie(properties: cookieProperties) {
// NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(cookie)
// }
// }
// }
}
// static func reserveCommunauto() -> ReturnStatus {
//
// if let customerID = getAndSaveCommunautoCustomerID() {
// //we are logged in, let's goooo
// //this is where we do the actual reservation
// return .Success
// } else {
// //we are not logged in, present a login screen to the user
// return .FailedNotLoggedIn
// }
//
// return .FailedError
// }
static func reserveAutomobile(carShare: CarShare, completion: (ReturnStatus) -> Void) {
automobileCustomerIDVehicleIDOperation(automobileCreateBookingUrl, carShare: carShare, completion: completion)
}
static func cancelAutomobile(carShare: CarShare, completion: (ReturnStatus) -> Void) {
automobileCustomerIDVehicleIDOperation(automobileCancelBookingUrl, carShare: carShare, completion: completion)
}
private static func automobileCustomerIDVehicleIDOperation(urlString: String, carShare: CarShare, completion: (ReturnStatus) -> Void) {
getAndSaveCommunautoCustomerID { (providerNo) -> Void in
if providerNo != nil {
//we are logged in, let's goooo
//this is where we do the actual reservation
let url = NSURL(string: String(format: urlString))//, providerNo, carShare.vin ?? ""))
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.HTTPBody = String(format:"CustomerID=%@&VehicleID=%@", providerNo!, carShare.vin ?? "").dataUsingEncoding(NSUTF8StringEncoding)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: { (response, data, error) -> Void in
if error != nil || data == nil {
DDLoggerWrapper.logError("Either there was an error with the request or there was no data returned")
completion(.FailedError)
}
if data != nil {
let stringData = (String(data: data!, encoding: NSUTF8StringEncoding) ?? " ").lowercaseString
if !stringData.containsString("true") {
DDLoggerWrapper.logError(stringData)
completion(.FailedError)
} else {
completion(.Success)
}
}
})
} else {
//we are not logged in, present a login screen to the user
completion(.FailedNotLoggedIn)
}
}
}
}
enum ReturnStatus {
case FailedNotLoggedIn
case FailedError
case Success
}
} |
//
// MovieMakup.swift
// OneMovie
//
// Created by Ahmet Celikbas on 20/06/2017.
// Copyright © 2017 Ahmet Celikbas. All rights reserved.
//
import Foundation
class MovieMakup {
var id: Int = 0
var title: String
var poster_path: String
init (id: Int, title: String, poster_path: String) {
self.id = id
self.title = title
if(poster_path == "no_poster") {
self.poster_path = Config.url_no_poster_available
} else {
self.poster_path = Config.url_poster_path + poster_path
}
}
}
|
//
// Metadata.swift
// Mitter
//
// Created by Rahul Chowdhury on 16/11/18.
// Copyright © 2018 Chronosphere Technologies Pvt. Ltd. All rights reserved.
//
import Foundation
import Mapper
public struct Metadata {
public let key: String
public let value: String
}
extension Metadata: Mappable {
public init(map: Mapper) throws {
key = try map.from("key")
value = try map.from("value")
}
}
|
//
// NameTableViewCell.swift
// Your Projects
//
// Created by Carlos Modinez on 05/06/19.
// Copyright © 2019 Carlos Modinez. All rights reserved.
//
import UIKit
class NameTableViewCell: UITableViewCell {
@IBOutlet weak var lblactivityName: UILabel!
}
|
//
// ReserveCarVC.swift
// NewSwift
//
// Created by gail on 2019/7/5.
// Copyright © 2019 NewSwift. All rights reserved.
//
import UIKit
class ReserveCarVC: UITableViewController {
var currentPage = 1
var page:Page?
lazy var array = [ReserveModel]()
var loginModel:LoginModel?
override func viewDidLoad() {
super.viewDidLoad()
UserDefaults.standard.removeObject(forKey: "Date")//解决约车时间只能上传一天
view.backgroundColor = grayBackColor
tableView.register(UINib(nibName: "CoachListCell", bundle: nil), forCellReuseIdentifier: "CoachListCell")
tableView.separatorStyle = .none
setUpHeaderReFresh()
setUpFootReFresh()
self.navigationItem.title = "选择约车教练"
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.array.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 110
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CoachListCell", for: indexPath) as! CoachListCell
let model = self.array[indexPath.row]
cell.icon.sd_setImage(with: URL(string: model.CoachImage)!)
cell.applyBtn.isHidden = true
cell.coachNameLabel.text = model.Name
cell.fromShoolLabel.text = model.SchoolName
cell.starView.rating = CGFloat((model.StarLevel as NSString).doubleValue)
cell.accessoryType = .disclosureIndicator
let lineView = UIView(frame: CGRect(x: 0, y: 110-1, width: SCREEN_WIDTH, height: 1))
lineView.backgroundColor = grayBackColor
cell.addSubview(lineView)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let model = self.array[indexPath.row]
getTimeData(model: model)
}
}
extension ReserveCarVC {
fileprivate func getHomeData(firstGet: Bool){
HomeNetTool.getReserveCoachList(currentPage: currentPage, UserId: loginModel?.userId ?? "", stuId: loginModel?.userId ?? "", Success: {[weak self] (page, array) in
self?.page = page
if firstGet == true {
self?.array = array
}else{
self?.array.append(contentsOf: array)
}
self?.tableView.mj_footer.isHidden = page.totalPage == 1 || self?.array.count == 0
self?.tableView.reloadData()
self?.tableView.mj_header.endRefreshing()
self?.tableView.mj_footer.endRefreshing()
}) {[weak self] (error) in
self?.tableView.mj_footer.isHidden = self?.array.count == 0
self?.tableView.mj_header.endRefreshing()
self?.tableView.mj_footer.endRefreshing()
}
}
}
extension ReserveCarVC {
fileprivate func setUpHeaderReFresh() {
tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
self?.currentPage = 1
self?.getHomeData(firstGet: true)
})
tableView.mj_header.beginRefreshing()
}
fileprivate func setUpFootReFresh() {
tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[weak self] in
if self?.array.count != 0 {
self?.currentPage += 1
}
if self?.page?.currentPage==self?.page?.totalPage {
self?.tableView.mj_footer.endRefreshingWithNoMoreData()
}else{
self?.getHomeData(firstGet: false)
}
})
}
}
extension ReserveCarVC {
func getTimeData(model:ReserveModel) {
SVProgressHUD.setDefaultMaskType(.black)
SVProgressHUD.setDefaultAnimationType(.native)
SVProgressHUD.show()
HomeNetTool.GetTimeData(coachId: model.CoachId , UserId: loginModel?.userId ?? "", stuId: loginModel?.userId ?? "") {(array) in
let vc = SchedulingRecordsVC()
vc.loginModel = self.loginModel
vc.timeModelArray = array
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
|
protocol IUnlinkView: class {
func set(accountTypeTitle: String)
func set(viewItems: [UnlinkModule.ViewItem])
func set(deleteButtonEnabled: Bool)
func showSuccess()
}
protocol IUnlinkViewDelegate {
func onLoad()
func onTapViewItem(index: Int)
func onTapDelete()
func onTapClose()
}
protocol IUnlinkInteractor {
func delete(account: Account)
}
protocol IUnlinkRouter {
func close()
}
class UnlinkModule {
struct ViewItem {
let type: ItemType
var checked: Bool
init(type: ItemType) {
self.type = type
checked = false
}
}
enum ItemType {
case deleteAccount(accountTypeTitle: String)
case disableCoins(coinCodes: String)
case loseAccess
}
}
|
//
// TestClasses.swift
// SailingThroughHistory
//
// Created by Herald on 20/4/19.
// Copyright © 2019 Sailing Through History Team. All rights reserved.
//
/**
* A class that holds static constructors that are used for testing.
*/
class TestClasses {
static let baseYear: Int = 1800
static let team: String = "British"
static let buyPrice: Int = 100
static let sellPrice: Int = 100
static func createMap() -> Map {
let map = Map(map: "test map", bounds: Rect())
let port = PortStub(buyValueOfAllItems: buyPrice, sellValueOfAllItems: sellPrice)
let nextId = port.identifier + 1
let node = NodeStub(name: "node", identifier: nextId)
map.addNode(port)
map.addNode(node)
map.add(path: Path(from: port, to: node))
map.add(path: Path(from: node, to: port))
return map
}
static func createLevel() -> GenericLevel {
return GameParameter(map: createMap(), teams: [team])
}
static func createGame(numPlayers: Int) -> GenericGameState {
return GameState(baseYear: baseYear,
level: createLevel(),
players: createPlayers(numPlayers: numPlayers))
}
static func createTurnSystem() -> GenericTurnSystem {
return TestTurnSystem()
}
static func createEventPresets() -> EventPresets {
let testSystem = createTurnSystem()
return EventPresets(gameState: testSystem.gameState, turnSystem: testSystem)
}
static func createTestState(numPlayers: Int) -> TurnSystemState {
return TurnSystemState(
gameState: createGame(numPlayers: numPlayers), joinOnTurn: 0)
}
static func createNetworkInfo() -> NetworkInfo {
return NetworkInfo("testDevice", false)
}
static func createTestSystemNetwork(numPlayers: Int) -> TurnSystemNetwork {
return TurnSystemNetwork(roomConnection: TestRoomConnection(),
playerActionAdapterFactory:
PlayerActionAdapterFactory(),
networkInfo: createNetworkInfo(),
turnSystemState: createTestState(numPlayers: numPlayers))
}
static func createTestSystemNetwork(numPlayers: Int, callback: @escaping () -> Void) -> TurnSystemNetwork {
let connection = TestRoomConnection()
connection.testCallback = callback
return TurnSystemNetwork(roomConnection: connection,
playerActionAdapterFactory:
PlayerActionAdapterFactory(),
networkInfo: createNetworkInfo(),
turnSystemState: createTestState(numPlayers: numPlayers))
}
static func createTestSystem(numPlayers: Int) -> TurnSystem {
return TurnSystem(network: createTestSystemNetwork(numPlayers: numPlayers),
playerInputControllerFactory: PlayerInputControllerFactory())
}
static func createPlayers(numPlayers: Int) -> [RoomMember] {
var result: [RoomMember] = []
for index in 0..<numPlayers {
result.append(RoomMember(identifier: String(index), playerName: String(index),
teamName: team, deviceId: "testDevice"))
}
return result
}
static func createInputController(timer: Double, callback: @escaping () -> Void)
-> PlayerInputController {
let network = createTestSystemNetwork(numPlayers: 2, callback: callback)
let controller = PlayerInputController(
network: network,
data: network.data)
controller.duration = timer
return controller
}
static func createTestEvent(identifier: Int) -> TurnSystemEvent {
let event = TurnSystemEvent(triggers: [], conditions: [], actions: [],
parsable: { "Test event" }, displayName: "Test event")
event.identifier = identifier
return event
}
static func createPresetEvent(identifier: Int) -> PresetEvent {
let result = TaxChangeEvent(gameState: TestClasses.createGame(numPlayers: 1),
genericOperator: AddOperator<Int>(), modifier: 1)
result.identifier = identifier
return result
}
}
|
//
// GetTripsUseCase.swift
// EmpireMobileApp
//
// Created by Rodrigo Nunes on 10/13/19.
// Copyright © 2019 Rodrigo Nunes Gil. All rights reserved.
//
import Foundation
typealias TripsUseCaseReponse = ([Trip]?, Error?) -> Void
//sourcery: AutoMockable
protocol GetTripsUseCaseApi {
func execute(completion: @escaping TripsUseCaseReponse)
}
final class GetTripsUseCase: GetTripsUseCaseApi {
private let repository: TripRepository
init() {
self.repository = TripRepositoryImpl()
}
func execute(completion: @escaping TripsUseCaseReponse) {
repository.tripList { (tripList, error) in
completion(tripList, error)
}
}
}
|
//
// AddOrDetailsViewController.swift
// Notes
//
// Created by Dima Opalko on 4/28/19.
// Copyright © 2019 Dima Opalko. All rights reserved.
//
import UIKit
class AddViewController: UIViewController, UITextViewDelegate {
var previousVC = NotesTableViewController()
@IBOutlet weak var textView: UITextView!
@IBAction func saveButton(_ sender: Any) {
if textView.text != "Enter text here!" {
if let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext{
let note = NoteCoreData(entity: NoteCoreData.entity(), insertInto: context)
if let text = textView.text {
note.noteDescription = text
try? context.save()
navigationController?.popViewController(animated: true)
}
}
} else {
let alertController = UIAlertController(title: "Enter text or I will punch you in the neck!", message: nil, preferredStyle: UIAlertController.Style.alert)
let cancelAction = UIAlertAction(title: "Ok!", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = "New Note"
textView.text = "Enter text here!"
textView.textColor = UIColor.lightGray
textView.delegate = self
}
func textViewDidBeginEditing(_ textView: UITextView) {
if textView.textColor == UIColor.lightGray {
textView.text = ""
textView.textColor = UIColor.black
}
}
func textViewDidEndEditing(_ textView: UITextView) {
if textView.text.isEmpty {
textView.text = "Enter text here!"
textView.textColor = UIColor.lightGray
}
}
}
|
import UIKit
class SignUpViewController: UIViewController , UITextFieldDelegate {
@IBOutlet weak var signInButton: UIButton!
@IBOutlet weak var userNameTxt: UITextField_BottomBorder!
@IBOutlet weak var emailTxt: UITextField_BottomBorder!
@IBOutlet weak var phoneNoTxt: UITextField_BottomBorder!
@IBOutlet weak var passwordTxt: UITextField_BottomBorder!
@IBOutlet weak var confirmPassTxt: UITextField_BottomBorder!
@IBOutlet weak var signUpScrollOutlet: UIScrollView!
//properties
var userName = ""
var email = ""
var phoneNo = ""
var password = ""
var URLforSignIn = "http://192.168.1.222/mobil_app/user_add_api.php"
override func viewDidLoad() {
super.viewDidLoad()
userNameTxt.delegate = self
emailTxt.delegate = self
phoneNoTxt.delegate = self
passwordTxt.delegate = self
confirmPassTxt.delegate = self
//for border
signInButton.layer.borderColor = UIColor.white.cgColor
signInButton.layer.borderWidth = 1.0
}
//delegate for textfields
func textFieldDidEndEditing(_ textField: UITextField) {
signUpScrollOutlet.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
signUpScrollOutlet.setContentOffset(CGPoint(x: 0, y: 250), animated: true)
}
@IBAction func SignInButtonAction(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func SignUPButtonAction(_ sender: Any) {
userName = userNameTxt.text!
email = emailTxt.text!
phoneNo = phoneNoTxt.text!
guard passwordTxt.text! == confirmPassTxt.text! else {
print("give password again")
return
}
password = passwordTxt.text!
let params = "email=\(email)&username=\(userName)&password=\(password)&customer_contact=\(phoneNo)"
print(URLforSignIn)
let jsonCall = APlCall()
jsonCall.getDataFromJson(url: URLforSignIn, parameter: params, completion: { response in
//print("ahib")
print(response)
let status = response["status"] as! String
print(status)
})
}
}
|
//
// FavouriteService.swift
// BitcoinLog
//
// Created by Viktor Rutberg on 09/11/15.
// Copyright © 2015 Viktor Rutberg. All rights reserved.
//
import UIKit
protocol FavouritesService {
func getAll() -> [String]
func isFavourite(ticker: String) -> Bool
func addFavourite(ticker: String)
func removeFavourite(ticker: String)
}
class FavouritesServiceFactory {
private static let instance = FavouritesServiceImpl()
static func get() -> FavouritesService {
return instance
}
}
class FavouritesServiceImpl: FavouritesService {
private let STORAGE_KEY = "favouriteExchangeRates"
private func getUserDefaults() -> NSUserDefaults {
return NSUserDefaults.standardUserDefaults()
}
func getAll() -> [String] {
return getUserDefaults().objectForKey(STORAGE_KEY) as? [String] ?? [String]()
}
func isFavourite(ticker: String) -> Bool {
return getAll().contains(ticker)
}
func addFavourite(ticker: String) {
var favourites = getAll()
if !favourites.contains(ticker) {
favourites.append(ticker)
let userDefaults = getUserDefaults()
userDefaults.setObject(favourites, forKey: STORAGE_KEY)
userDefaults.synchronize()
}
}
func removeFavourite(ticker: String) {
let favourites = getAll()
let filteredFavourites = favourites.filter() { $0 != ticker }
let userDefaults = getUserDefaults()
userDefaults.setObject(filteredFavourites, forKey: STORAGE_KEY)
userDefaults.synchronize()
}
} |
//
// PointsOfInterest.swift
// KrisR
//
// Created by Kris Reid on 19/06/2021.
//
import Foundation
struct PointsOfInterest: Identifiable {
var id = UUID().uuidString
let name: String
let latitude, longitude: Double
}
|
//
// SettingsTableViewController.swift
// logU
//
// Created by Brett Alcox on 1/24/16.
// Copyright © 2016 Brett Alcox. All rights reserved.
//
import UIKit
import Eureka
import CoreLocation
import MapKit
class SettingsTableViewController: FormViewController, CLLocationManagerDelegate {
let defaults = NSUserDefaults.standardUserDefaults()
var locationManager: CLLocationManager!
var currentLocation: CLLocation?
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
form +++ Section("Settings")
<<< SegmentedRow<String>("Unit") { (row1 : SegmentedRow) -> Void in
row1.title = "Unit"
row1.options = ["Pounds", "Kilograms"]
if Reachability.isConnectedToNetwork() {
if String(defaults.valueForKey("Unit")!) == "1" {
row1.value = "Pounds"
}
if String(defaults.valueForKey("Unit")!) == "0" {
row1.value = "Kilograms"
}
}
row1.onChange { row in
self.form.rowByTag("Save Changes")?.disabled = false
self.form.rowByTag("Save Changes")?.evaluateDisabled()
self.form.rowByTag("Save Changes")?.updateCell()
}
}
<<< SegmentedRow<String>("Gender") { (row2 : SegmentedRow) -> Void in
row2.title = "Gender"
row2.options = ["Male", "Female"]
if Reachability.isConnectedToNetwork() {
if String(defaults.valueForKey("Gender")!) == "M" {
row2.value = "Male"
}
if String(defaults.valueForKey("Gender")!) == "F" {
row2.value = "Female"
}
}
row2.onChange { row in
self.form.rowByTag("Save Changes")?.disabled = false
self.form.rowByTag("Save Changes")?.evaluateDisabled()
self.form.rowByTag("Save Changes")?.updateCell()
}
}
<<< DecimalRow("Current Weight") {
$0.title = "Current Weight"
if Reachability.isConnectedToNetwork() {
$0.value = defaults.valueForKey("Bodyweight")! as! Double
}
$0.onChange { row in
self.form.rowByTag("Save Changes")?.disabled = false
self.form.rowByTag("Save Changes")?.evaluateDisabled()
self.form.rowByTag("Save Changes")?.updateCell()
}
}
<<< ButtonRow("Save Changes") { (row4 : ButtonRow) -> Void in
row4.title = "Save Changes"
row4.disabled = true
row4.onCellSelection(self.saveTapped)
}
+++ Section("Location")
<<< LocationRow("Map") {
$0.title = "My Gym Location"
if let loadedData = NSUserDefaults.standardUserDefaults().dataForKey("gym_loc") {
if let loadedLocation = NSKeyedUnarchiver.unarchiveObjectWithData(loadedData) as? CLLocation {
$0.value = loadedLocation
}
} else {
if (CLLocationManager.locationServicesEnabled()) {
if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
$0.value = CLLocation(latitude: 0, longitude: 0)
} else {
$0.value = CLLocation(latitude: 0, longitude: 0)
}
} else {
$0.value = CLLocation(latitude: 0, longitude: 0)
}
}
}.onChange({ row in
let locationData = NSKeyedArchiver.archivedDataWithRootObject(row.value!)
NSUserDefaults.standardUserDefaults().setObject(locationData, forKey: "gym_loc")
})
<<< SwitchRow("GPS") {
$0.title = "Log GPS on Community Map"
if Int(String((defaults.valueForKey("GPS"))!)) == 1 {
$0.value = true
} else {
$0.value = false
}
}.onChange({ row in
if row.value == true {
self.defaults.setInteger(1, forKey: "GPS")
}
else {
self.defaults.setInteger(0, forKey: "GPS")
}
})
<<< TextAreaRow(){
$0.disabled = true
$0.value = "If these options are disabled, turn on Location Services."
}.cellSetup({ (cell, row) -> () in
cell.textView.font = UIFont .systemFontOfSize(9)
cell.userInteractionEnabled = false
row.cell.height = {
return 35
}
})
+++ Section("Privacy")
<<< ButtonRow("Privacy") {
$0.title = "Privacy Policy"
$0.onCellSelection(self.viewPrivacy)
}
+++ Section("Current Session")
<<< ButtonRow("Logout") {
$0.title = "Logout"
$0.onCellSelection(self.buttonTapped)
}
+++ Section("Account Management")
<<< ButtonRow("Delete Account") {
$0.title = "Delete Account"
$0.onCellSelection(self.deleteAccount)
}
}
override func viewDidAppear(animated: Bool) {
globalUser = defaults.valueForKey("USERNAME") as! String
if CLLocationManager.locationServicesEnabled().boolValue == false || CLLocationManager.authorizationStatus() == .Denied || CLLocationManager.authorizationStatus() == .NotDetermined || CLLocationManager.authorizationStatus() == .Restricted {
self.form.rows[4].disabled = true
self.form.rows[5].disabled = true
self.form.rows[4].evaluateDisabled()
self.form.rows[5].evaluateDisabled()
} else {
self.form.rows[4].disabled = false
self.form.rows[5].disabled = false
self.form.rows[4].evaluateDisabled()
self.form.rows[5].evaluateDisabled()
}
}
func buttonTapped(cell: ButtonCellOf<String>, row: ButtonRow) {
performSegueWithIdentifier("loggingOut", sender: nil)
self.navigationController?.navigationBarHidden = true
globalUser = ""
defaults.setObject("", forKey: "USERNAME")
defaults.setValue(0, forKey: "ISLOGGEDIN")
defaults.synchronize()
shouldUpdateDash = true
shouldUpdatePoundage = true
shouldUpdateMax = true
shouldUpdateWeek = true
shouldUpdateStats = true
shouldUpdateFrequency = true
}
func viewPrivacy(cell: ButtonCellOf<String>, row: ButtonRow) {
performSegueWithIdentifier("showPrivacyPolicy", sender: nil)
}
func deleteAccount(cell: ButtonCellOf<String>, row: ButtonRow) {
let actionSheetController: UIAlertController = UIAlertController(title: "Delete Account?", message: "This will delete account and all lifts! Cannot be undone!", preferredStyle: .Alert)
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
//Do some stuff
}
let deleteAction: UIAlertAction = UIAlertAction(title: "Delete", style: .Default) { action -> Void in
let actionSheetController: UIAlertController = UIAlertController(title: "Are you sure?", message: "Cannot be undone!", preferredStyle: .Alert)
let cancelAction: UIAlertAction = UIAlertAction(title: "No", style: .Cancel) { action -> Void in
//Do some stuff
}
let deleteAction: UIAlertAction = UIAlertAction(title: "Yes", style: .Default) { action -> Void in
DeleteAccount().delete_request(globalUser!)
globalUser = ""
self.defaults.setObject("", forKey: "USERNAME")
self.defaults.setValue(0, forKey: "ISLOGGEDIN")
self.defaults.synchronize()
self.performSegueWithIdentifier("loggingOut", sender: nil)
self.navigationController?.navigationBarHidden = true
}
actionSheetController.addAction(cancelAction)
actionSheetController.addAction(deleteAction)
self.presentViewController(actionSheetController, animated: true, completion: nil)
}
actionSheetController.addAction(cancelAction)
actionSheetController.addAction(deleteAction)
self.presentViewController(actionSheetController, animated: true, completion: nil)
}
func saveTapped(cell: ButtonCellOf<String>, row: ButtonRow) {
if form.rowByTag("Save Changes")?.isDisabled == false {
form.rowByTag("Save Changes")?.disabled = true
form.rowByTag("Save Changes")?.evaluateDisabled()
form.rowByTag("Save Changes")?.updateCell()
if String((form.values()["Unit"]!)!) == "Pounds" {
self.defaults.setInteger(1, forKey: "Unit")
}
if String((form.values()["Unit"]!)!) == "Kilograms" {
self.defaults.setInteger(0, forKey: "Unit")
}
if String((form.values()["Gender"]!)!) == "Male" {
self.defaults.setValue("M", forKey: "Gender")
}
if String((form.values()["Gender"]!)!) == "Female" {
self.defaults.setValue("F", forKey: "Gender")
}
defaults.setValue(String((form.values()["Current Weight"]!)!), forKey: "Bodyweight")
Settings().updateUnit(String(defaults.valueForKey("Unit")!), gender: String(defaults.valueForKey("Gender")!), bodyweight: String(defaults.valueForKey("Bodyweight")!))
shouldUpdateDash = true
shouldUpdatePoundage = true
shouldUpdateMax = true
shouldUpdateWeek = true
shouldUpdateStats = true
}
}
func locationManager(manager: CLLocationManager,
didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case CLAuthorizationStatus.Restricted:
self.form.rows[4].disabled = true
self.form.rows[5].disabled = true
self.form.rows[4].evaluateDisabled()
self.form.rows[5].evaluateDisabled()
case CLAuthorizationStatus.Denied:
self.form.rows[4].disabled = true
self.form.rows[5].disabled = true
self.form.rows[4].evaluateDisabled()
self.form.rows[5].evaluateDisabled()
case CLAuthorizationStatus.NotDetermined:
self.form.rows[4].disabled = true
self.form.rows[5].disabled = true
self.form.rows[4].evaluateDisabled()
self.form.rows[5].evaluateDisabled()
locationManager.requestWhenInUseAuthorization()
default:
self.form.rows[4].disabled = false
self.form.rows[5].disabled = false
self.form.rows[4].evaluateDisabled()
self.form.rows[5].evaluateDisabled()
locationManager.requestWhenInUseAuthorization()
}
}
}
|
/* Copyright Airship and Contributors */
@testable
import AirshipChat
class MockChatOpenDelegate : ChatOpenDelegate {
var openCalled = false
var lastOpenMessage: String?
func openChat(message: String?) {
openCalled = true
lastOpenMessage = message
}
}
|
//
// MineViewController.swift
// huicheng
//
// Created by lvxin on 2018/3/5.
// Copyright © 2018年 lvxin. All rights reserved.
// 我的
import UIKit
let MINEID = "MINE_ID"
let mine_cell_height = CGFloat(60)
class MineViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource,MineHeadViewDelegate,MineRequestVCDelegate,MineFooterViewDelegate {
/// 列表
let mainTabelView : UITableView = UITableView()
/// 头部b
let headView : MineHeadView = MineHeadView.loadNib()
/// 底部
let footerView : MineFooterView = MineFooterView.loadNib()
let request : MineRequestVC = MineRequestVC()
var model : user_getinfoModel = user_getinfoModel()
var userDataModel : LoginModel!
var nameArr : [String] = []
// MARK: - life
override func viewWillLayoutSubviews() {
mainTabelView.snp.makeConstraints { (make) in
make.top.equalTo(self.view).offset(0)
make.left.right.equalTo(self.view).offset(0)
make.bottom.equalTo(self.view).offset(0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = viewBackColor
self.navigationBar_leftBtn_image(image: #imageLiteral(resourceName: "mes_logo"))
self.navigation_title_fontsize(name: "我的", fontsize: 18)
userDataModel = UserInfoLoaclManger.getsetUserWorkData()
nameArr = (userDataModel.power.last?.childrens)!
HCLog(message: userDataModel?.power.count)
self.creatUI()
headView.delegate = self
footerView.delegate = self
request.delegate = self
request.user_getinfoRequest()
}
// MARK: - UI
func creatUI() {
mainTabelView.backgroundColor = UIColor.clear
mainTabelView.delegate = self;
mainTabelView.dataSource = self;
mainTabelView.tableFooterView = UIView()
mainTabelView.separatorStyle = .none
mainTabelView.showsVerticalScrollIndicator = false
mainTabelView.showsHorizontalScrollIndicator = false
mainTabelView.backgroundView?.backgroundColor = .clear
mainTabelView.register(UINib.init(nibName: "MineTableViewCell", bundle: nil), forCellReuseIdentifier: MINEID)
self.view.addSubview(mainTabelView)
}
// MARK: - delegate
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nameArr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell : MineTableViewCell! = tableView.dequeueReusableCell(withIdentifier: MINEID, for: indexPath) as! MineTableViewCell
if indexPath.row < nameArr.count {
cell.setData(name: nameArr[indexPath.row])
}
return cell
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return UIView()
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return headView
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row < nameArr.count {
let nameStr = nameArr[indexPath.row]
switch nameStr {
case "备忘录":
//备忘录
let vc = MemoViewController()
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
case "报销申请":
//报销申请
let vc = ExpenseViewController()
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
case "发票申请":
//发票申请
let vc = InvoiceViewController()
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
case "我的收款":
//我的收款
let vc = FinanceViewController()
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
case "工作日志":
//工作日志
let vc = WorkBookViewController()
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
case "设置":
//工作日志
let vc = SetViewController()
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
default:
HCLog(message: "咩有")
}
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return mine_cell_height
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 105
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0
}
func iconClick() {
let vc = InfoViewController()
vc.hidesBottomBarWhenPushed = true
vc.model = model
self.navigationController?.pushViewController(vc, animated: true)
}
func viewTap() {
let vc = SetViewController()
vc.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(vc, animated: true)
}
func requestSucceed_mine(data: Any,type : MineRequestVC_enum) {
model = data as! user_getinfoModel
headView.setData(model: model)
}
func requestFail_mine() {
}
// MARK: - event response
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// FeedbackViewController.swift
// ddx0513
//
// Created by ejian on 15/6/4.
// Copyright (c) 2015年 jiang yongbin. All rights reserved.
//
import UIKit
class FeedbackViewController: UIViewController, UITextViewDelegate {
var textPlacehold = true
var hud: MBProgressHUD?
@IBOutlet weak var countLabel: UILabel!
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
textView.text = "欢迎提出您的意见或遇到的问题,我们会及时帮您解决"
textView.textColor = UIColor.darkGrayColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func viewTapGuesture(sender: AnyObject) {
self.textView.resignFirstResponder()
}
func textViewDidBeginEditing(textView: UITextView) {
if (textPlacehold) {
textPlacehold = false
textView.text = ""
textView.textColor = UIColor.blackColor()
}
}
func textViewDidEndEditing(textView: UITextView) {
if (!textPlacehold && count(textView.text) == 0) {
textPlacehold = true
textView.text = "欢迎提出您的意见或遇到的问题,我们会及时帮您解决"
textView.textColor = UIColor.darkGrayColor()
}
}
func textViewDidChange(textView: UITextView) {
if (textPlacehold) {
countLabel.text = "还可以输入240个字"
} else {
var str = textView.text
var num = count(str)
if (num > 240) {
let range = Range(start: str.startIndex, end: advance(str.startIndex, 240))
self.textView.text = str.substringWithRange(range)
countLabel.text = "还可以输入0个字"
} else {
countLabel.text = "还可以输入\(240 - num)个字"
}
}
}
@IBAction func submitButtonPressed(sender: AnyObject) {
if (textPlacehold || self.textView.text == "") {
ViewUtils.popMessage(self, title: "", message: "反馈意见不能为空")
return
}
startIndicator()
let a = ["userid": DBUtils.mem.userId, "token": DBUtils.mem.token, "context": self.textView.text]
NetUtils.netRequest(Method.POST, URLString: NetUtils.getURLFeedback(), parameters: (a as! [String : AnyObject]), view: self.view, responseHandler: stopIndicator, successHandler: save)
}
@IBAction func backButtonPressed(sender: AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
}
//MARK: - 网络回调函数
func startIndicator() {
hud = MBProgressHUD(view: self.view)
self.view.addSubview(hud!)
hud?.labelText = "提交中.."
hud?.show(true)
}
func stopIndicator() {
// hud?.hide(false)
}
func save(json: JSON) {
hud!.mode = MBProgressHUDMode.Text
hud!.labelText = "提交成功"
hud!.margin = 10.0
hud!.removeFromSuperViewOnHide = true
hud!.square = true
hud?.showWhileExecuting(Selector("save2"), onTarget: self, withObject: nil, animated: true)
}
func save2() {
sleep(1)
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
self.navigationController?.popViewControllerAnimated(true)
})
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// AppSingleton.swift
// iOSBoilerplate
//
// Created by sadman samee on 8/17/19.
// Copyright © 2019 sadman samee. All rights reserved.
//
import Foundation
import SwiftKeychainWrapper
import SwiftyJSON
final class UserService {
static let shared: UserService = {
let instance = UserService()
// Setup code
return instance
}()
init() {
user = fetchUser()
}
private var user: User?
func isAuthonticated() -> Bool {
if loadToken() != nil {
return true
} else {
return false
}
}
func save(token: String) {
KeychainWrapper.standard.set(token, forKey: "token")
}
func loadToken() -> String? {
return KeychainWrapper.standard.string(forKey: "token")
}
func fetchUser() -> User? {
var user: User?
if let usr = UserDefaults.standard.value(forKey: "user") {
let usrDictionary = usr as! [String: Any]
let json = JSON(parseJSON: usrDictionary.json)
user = User(fromJson: json)
}
return user
}
func saveUser(user: User) {
UserDefaults.standard.set(user.toDictionary(), forKey: "user")
self.user = user
}
func logout() {
let defaults = UserDefaults.standard
defaults.removeObject(forKey: "user")
KeychainWrapper.standard.removeObject(forKey: "token")
defaults.synchronize()
user = nil
}
}
|
//
// File.swift
// Seman06
//
// Created by Jeferson Bujaico on 4/2/19.
// Copyright © 2019 Jeferson Bujaico Rodriguez. All rights reserved.
//
import Foundation
|
//
// CollectionVC.swift
// PTJ5_BoxOffice
//
// Created by mong on 08/03/2019.
// Copyright © 2019 mong. All rights reserved.
//
import Foundation
import UIKit
class CollectionVC: UIViewController, UICollectionViewDataSource {
@IBOutlet var collectionView: UICollectionView!
@IBOutlet var navigationBar: UINavigationItem!
var movies: [Movie] = []
@IBAction func sortBtn(_ sender: Any) {
let alert: UIAlertController = UIAlertController.init(title: "", message: "어떤 방법으로 정렬할까요?", preferredStyle: .actionSheet)
let rate = UIAlertAction.init(title: "예매율", style: .default, handler: {(_) in
requestType = 0
self.requestMovieList(type: requestType)
self.navigationBar.title = "예매율순"
})
let curation = UIAlertAction.init(title: "큐레이션", style: .default, handler: {(_) in
requestType = 1
self.requestMovieList(type: requestType)
self.navigationBar.title = "큐레이션"
})
let releaseDate = UIAlertAction.init(title: "개봉일", style: .default, handler: {(_) in
requestType = 2
self.requestMovieList(type: requestType)
self.navigationBar.title = "개봉일순"
})
let cancel = UIAlertAction.init(title: "취소", style: .cancel, handler: nil)
alert.addAction(rate)
alert.addAction(curation)
alert.addAction(releaseDate)
alert.addAction(cancel)
present(alert, animated: true, completion: nil)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.movies.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: collectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath) as! collectionViewCell
let movie: Movie = movies[indexPath.row]
cell.poster.image = UIImage(named: "img_placeholder")
cell.movieTitle.text = movie.title
cell.movieDescription.text = movie.descriptionForCollection
cell.releaseDate.text = movie.date
cell.movieGrade.image = setGradeImage(grade: movie.grade)
guard let imageURL: URL = URL(string: movie.thumb) else { return cell }
guard let imageData: Data = try? Data(contentsOf: imageURL) else { return cell }
cell.poster.image = UIImage(data: imageData)
return cell
}
func requestMovieList(type: Int){
let listType: String = baseURL + "\(type)"
print(listType)
guard let url: URL = URL(string: listType) else { return }
let session: URLSession = URLSession(configuration: .default)
let dataTask: URLSessionDataTask = session.dataTask(with: url) {(data: Data?, response: URLResponse?, error: Error?) in
if let error = error{
print(error.localizedDescription)
return
}
guard let data = data else {return}
do{
let apiResponse: APIResonse = try JSONDecoder().decode(APIResonse.self, from: data)
self.movies = apiResponse.movies
DispatchQueue.main.async {
self.collectionView.reloadData()
}
} catch(let err){
print(err.localizedDescription)
}
}
dataTask.resume()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let detailVC: DetailVC = segue.destination as! DetailVC
let indexPath = collectionView.indexPathsForSelectedItems
print(movies[(indexPath?.first?.first)!].title)
let currentMovie = movies[(indexPath?.first?.first)!]
detailVC.movieID = currentMovie.id
}
override func viewDidAppear(_ animated: Bool) {
requestMovieList(type: requestType)
navigationBar.title = changeTitle(requestType: requestType)
}
override func viewDidLoad() {
self.collectionView.dataSource = self
navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
let flowLayout: UICollectionViewFlowLayout
flowLayout = UICollectionViewFlowLayout()
let cellWidth = UIScreen.main.bounds.width / 2 - 20
let cellHeight = UIScreen.main.bounds.height / 2 - 30
flowLayout.itemSize = CGSize(width: cellWidth, height: cellHeight)
flowLayout.minimumInteritemSpacing = 20
flowLayout.minimumLineSpacing = 10
flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
self.collectionView.collectionViewLayout = flowLayout
}
}
|
//
// UDPBuffer.swift
// UdpStreamer
//
// Created by Osman Mesut Özcan on 1/9/2017.
// Copyright © 2017 Osman Mesut Özcan. All rights reserved.
//
import Foundation
import AVFoundation
class UDPBuffer: NSObject {
func pixelToData (buffer: CVPixelBuffer) -> NSData {
let bytesPerRow = CVPixelBufferGetBytesPerRow(buffer)
let height = CVPixelBufferGetHeight(buffer)
let width = CVPixelBufferGetWidth(buffer)
var srcBuffer = CVPixelBufferGetBaseAddress(buffer)
let dataBuffer: NSData = NSData(bytes: &srcBuffer, length: bytesPerRow)
CVPixelBufferUnlockBaseAddress(buffer, CVPixelBufferLockFlags(rawValue: 0))
return dataBuffer
}
}
|
// Copyright 2017 Omni Development, Inc. All rights reserved.
//
// $Id$
public extension ODOEditingContext {
public func fetchObject<T: ODOObject>(with objectID: ODOObjectID) throws -> T {
precondition(objectID.entity.instanceClass.isSubclass(of: T.self))
let result = try __fetchObject(with: objectID)
return result as! T
}
}
|
//
// User.swift
// PicassoHouse
//
// Created by Antony Alkmim on 20/03/17.
// Copyright © 2017 CoderUP. All rights reserved.
//
import Foundation
import SwiftyJSON
struct User {
let username : String
let displayName : String
//let mail : String
}
//MARK: - JSONAbleType
extension User : JSONAbleType {
static func fromJSON(_ json:[String: Any]) -> User? {
let json = JSON(json)
return User(username: json["username"].stringValue,
displayName: json["displayName"].stringValue)
}
}
|
//
// HydrantMapViewController.swift
// hwIOSApp
//
// Created by Brian Nelson on 10/18/15.
// Copyright © 2015 Brian Nelson. All rights reserved.
//
import Foundation
import UIKit
import MapKit
public class HydrantMapViewController : UIViewController, MKMapViewDelegate, ILocationUpdated
{
public var user:User?;
var locationManager:LocationManager!
var NavBar: UINavigationBar!
var CancelButton: UIBarButtonItem!
var TableViewButton: UIBarButtonItem!
var HydrantMap: MKMapView!
override public func viewDidLoad()
{
super.viewDidLoad()
CancelButton = UIFormatHelper.CreateNavBarButton("Cancel", targetView: self, buttonAction: #selector(HydrantMapViewController.CancelSent(_:)));
TableViewButton = UIFormatHelper.CreateNavBarButton("Table View", targetView: self, buttonAction: #selector(HydrantMapViewController.TableViewButtonPressed(_:)));
NavBar = UIFormatHelper.CreateNavBar("HydrantWiki", leftButton: CancelButton, rightButton: TableViewButton);
view.addSubview(NavBar);
//Add TextView
let mapFrame = CGRect(
x: 0,
y: 0,
width: Int(UIFormatHelper.GetScreenWidth()),
height: Int(UIFormatHelper.GetScreenHeight()) - 50
);
HydrantMap = MKMapView(frame: mapFrame);
HydrantMap.delegate = self;
HydrantMap.frame.origin.x = 0;
HydrantMap.frame.origin.y = 50;
HydrantMap.zoomEnabled = true;
HydrantMap.showsUserLocation = false;
view.addSubview(HydrantMap);
UIFormatHelper.Format(NavBar);
UIFormatHelper.Format(CancelButton);
UIFormatHelper.Format(TableViewButton);
UIFormatHelper.Format(HydrantMap)
//Start the location manager
locationManager = LocationManager();
locationManager.locationUpdated = self;
locationManager!.Start();
}
public func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool)
{
GetHydrants();
}
public func mapView(
mapView: MKMapView,
viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView?
{
if (annotation is MKUserLocation) { return nil }
let reuseID = "hydrant";
var v = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseID);
if v != nil {
v!.annotation = annotation;
} else {
v = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseID);
v!.image = UIImage(named:"HydrantPin");
}
return v;
}
func ZoomToCurrentLocation(latitude:Double, longitude:Double)
{
let spanX = 0.0125;
let spanY = 0.0125;
let location = CLLocationCoordinate2D(
latitude: latitude,
longitude: longitude
);
let span = MKCoordinateSpanMake(spanX, spanY);
let region = MKCoordinateRegion(center: location, span: span);
HydrantMap.setRegion(region, animated: false);
GetHydrants();
}
func GetHydrants()
{
let edgePoints = HydrantMap.edgePoints();
let minLat = edgePoints.sw.latitude;
let maxLat = edgePoints.ne.latitude;
let minLon = edgePoints.sw.longitude;
let maxLon = edgePoints.ne.longitude;
let service = HydrantService();
service.GetHydrantsInBox(minLat, maxLatitude: maxLat, minLongitude: minLon, maxLongitude: maxLon)
{ (response) -> Void in
if (response != nil
&& response!.Success
&& response!.Hydrants != nil)
{
self.AddHydrantsToMap((response?.Hydrants!)!);
}
}
}
func AddHydrantsToMap(hydrants:[HydrantDTO])
{
HydrantMap.removeAnnotations( HydrantMap.annotations )
for hydrant in hydrants {
if (hydrant.Position != nil)
{
let hydAnn = HydrantAnnotation(
title: "",
subtitle: "",
coordinate: CLLocationCoordinate2D(
latitude: (hydrant.Position?.Latitude)!,
longitude: (hydrant.Position?.Longitude)!));
HydrantMap.addAnnotation(hydAnn);
}
}
}
func TableViewButtonPressed(sender: UIBarButtonItem)
{
locationManager.Stop();
self.performSegueWithIdentifier("ShowNearbyTable", sender: nil);
}
func CancelSent(sender: UIBarButtonItem)
{
locationManager.Stop();
self.performSegueWithIdentifier("returnToHomeSegue", sender: nil);
}
public func NewLocation(
count: Int,
latitude: Double,
longitude: Double,
elevation: Double,
accuracy: Double)
{
locationManager.Stop();
ZoomToCurrentLocation(latitude, longitude: longitude);
}
} |
//
// ReMVVMDriven.swift
// ReMVVM
//
// Created by Dariusz Grzeszczak on 10/12/2019.
// Copyright © 2019 Dariusz Grzeszczak. All rights reserved.
//
import Foundation
/// Marks object is driven by ReMVVM
public protocol ReMVVMDriven {
/// type of the ReMVVMDriven object
associatedtype Base
/// ReMVVM object to be used by ReMVVMDriven
var remvvm: ReMVVM<Base> { get }
/// ReMVVM object to be used by ReMVVMDriven
static var remvvm: ReMVVM<Base> { get }
}
extension ReMVVMDriven {
/// ReMVVM object to be used by ReMVVMDriven
public var remvvm: ReMVVM<Self> { ReMVVM() }
/// ReMVVM object to be used by ReMVVMDriven
public static var remvvm: ReMVVM<Self> { ReMVVM() }
}
|
//
// UIView+Extension.swift
// SwiftTest
//
// Created by Mekor on 2016/11/27.
// Copyright © 2016年 Mekor. All rights reserved.
//
import Foundation
extension UIView {
class func instanceFromNibBundle() -> UIView? {
let nib = UINib(nibName: String(describing: self), bundle: nil)
let views = nib.instantiate(withOwner: nil, options: nil)
for view in views {
if (view as AnyObject).isMember(of: self) {
return view as? UIView
}
}
assert(false, "Exepect file:\(String(describing: self)).xib")
return nil
}
}
|
import Foundation
class SwapInputModule {
static func cell(service: UniswapService, tradeService: UniswapTradeService, switchService: AmountTypeSwitchService) -> SwapInputCell {
let fromCoinCardService = SwapFromCoinCardService(service: service, tradeService: tradeService)
let toCoinCardService = SwapToCoinCardService(service: service, tradeService: tradeService)
let fromFiatService = FiatService(switchService: switchService, currencyKit: App.shared.currencyKit, marketKit: App.shared.marketKit)
let toFiatService = FiatService(switchService: switchService, currencyKit: App.shared.currencyKit, marketKit: App.shared.marketKit)
switchService.add(toggleAllowedObservable: fromFiatService.toggleAvailableObservable)
switchService.add(toggleAllowedObservable: toFiatService.toggleAvailableObservable)
let fromViewModel = SwapCoinCardViewModel(coinCardService: fromCoinCardService, fiatService: fromFiatService)
let toViewModel = SwapCoinCardViewModel(coinCardService: toCoinCardService, fiatService: toFiatService)
let fromAmountInputViewModel = AmountInputViewModel(
service: fromCoinCardService,
fiatService: fromFiatService,
switchService: switchService,
decimalParser: AmountDecimalParser()
)
let toAmountInputViewModel = AmountInputViewModel(
service: toCoinCardService,
fiatService: toFiatService,
switchService: switchService,
decimalParser: AmountDecimalParser()
)
return SwapInputCell(fromViewModel: fromViewModel,
fromAmountInputViewModel: fromAmountInputViewModel,
toViewModel: toViewModel,
toAmountInputViewModel: toAmountInputViewModel
)
}
static func cell(service: UniswapV3Service, tradeService: UniswapV3TradeService, switchService: AmountTypeSwitchService) -> SwapInputCell {
let fromCoinCardService = SwapV3FromCoinCardService(service: service, tradeService: tradeService)
let toCoinCardService = SwapV3ToCoinCardService(service: service, tradeService: tradeService)
let fromFiatService = FiatService(switchService: switchService, currencyKit: App.shared.currencyKit, marketKit: App.shared.marketKit)
let toFiatService = FiatService(switchService: switchService, currencyKit: App.shared.currencyKit, marketKit: App.shared.marketKit)
switchService.add(toggleAllowedObservable: fromFiatService.toggleAvailableObservable)
switchService.add(toggleAllowedObservable: toFiatService.toggleAvailableObservable)
let fromViewModel = SwapCoinCardViewModel(coinCardService: fromCoinCardService, fiatService: fromFiatService)
let toViewModel = SwapCoinCardViewModel(coinCardService: toCoinCardService, fiatService: toFiatService)
let fromAmountInputViewModel = AmountInputViewModel(
service: fromCoinCardService,
fiatService: fromFiatService,
switchService: switchService,
decimalParser: AmountDecimalParser()
)
let toAmountInputViewModel = AmountInputViewModel(
service: toCoinCardService,
fiatService: toFiatService,
switchService: switchService,
decimalParser: AmountDecimalParser()
)
return SwapInputCell(fromViewModel: fromViewModel,
fromAmountInputViewModel: fromAmountInputViewModel,
toViewModel: toViewModel,
toAmountInputViewModel: toAmountInputViewModel
)
}
static func cell(service: OneInchService, tradeService: OneInchTradeService, switchService: AmountTypeSwitchService) -> SwapInputCell {
let fromCoinCardService = SwapFromCoinCardOneInchService(service: service, tradeService: tradeService)
let toCoinCardService = SwapToCoinCardOneInchService(service: service, tradeService: tradeService)
let fromFiatService = FiatService(switchService: switchService, currencyKit: App.shared.currencyKit, marketKit: App.shared.marketKit)
let toFiatService = FiatService(switchService: switchService, currencyKit: App.shared.currencyKit, marketKit: App.shared.marketKit)
switchService.add(toggleAllowedObservable: fromFiatService.toggleAvailableObservable)
switchService.add(toggleAllowedObservable: toFiatService.toggleAvailableObservable)
let fromViewModel = SwapCoinCardViewModel(coinCardService: fromCoinCardService, fiatService: fromFiatService)
let toViewModel = SwapCoinCardViewModel(coinCardService: toCoinCardService, fiatService: toFiatService)
let fromAmountInputViewModel = AmountInputViewModel(
service: fromCoinCardService,
fiatService: fromFiatService,
switchService: switchService,
decimalParser: AmountDecimalParser()
)
let toAmountInputViewModel = AmountInputViewModel(
service: toCoinCardService,
fiatService: toFiatService,
switchService: switchService,
decimalParser: AmountDecimalParser()
)
return SwapInputCell(fromViewModel: fromViewModel,
fromAmountInputViewModel: fromAmountInputViewModel,
toViewModel: toViewModel,
toAmountInputViewModel: toAmountInputViewModel
)
}
}
|
//
// MyRecipesScene.swift
// Free Cooking
//
// Created by Goncalves, Rafael on 19/05/21.
//
import SwiftUI
struct MyRecipesScene: View {
var body: some View {
NavigationView {
ZStack {
Color.defaultBackground
.ignoresSafeArea()
ScrollView(showsIndicators: false) {
SearchNavigationView()
Spacer(minLength: 48)
ZStack {
HStack {
Spacer()
VStack {
Spacer(minLength: 50)
RecipesView(title: "Italian pasta",
description: "Tasty traditional dish. Not only for Italian who went to Malta",
time: "5 min",
people: "1 pers")
RecipesView(title: "Italian pasta",
description: "Tasty traditional dish. Not only for Italian who went to Malta",
time: "5 min",
people: "1 pers")
RecipesView(title: "Italian pasta",
description: "Tasty traditional dish. Not only for Italian who went to Malta",
time: "5 min",
people: "1 pers")
RecipesView(title: "Italian pasta",
description: "Tasty traditional dish. Not only for Italian who went to Malta",
time: "5 min",
people: "1 pers")
}
.frame(width: (UIScreen.main.bounds.size.width - 32) / 2 - 8)
}
HStack {
VStack {
RecipesView(title: "Italian pasta",
description: "Tasty traditional dish. Not only for Italian who went to Malta",
time: "5 min",
people: "1 pers")
RecipesView(title: "Italian pasta",
description: "Tasty traditional dish. Not only for Italian who went to Malta",
time: "5 min",
people: "1 pers")
RecipesView(title: "Italian pasta",
description: "Tasty traditional dish. Not only for Italian who went to Malta",
time: "5 min",
people: "1 pers")
RecipesView(title: "Italian pasta",
description: "Tasty traditional dish. Not only for Italian who went to Malta",
time: "5 min",
people: "1 pers")
Spacer(minLength: 50)
}
.frame(width: (UIScreen.main.bounds.size.width - 32) / 2 - 8)
Spacer()
}
}
Spacer(minLength: 16)
}
.padding([.leading, .trailing], 16)
}
.navigationBarBackButtonHidden(true)
.navigationBarHidden(true)
}
}
}
private struct RecipesView: View {
private let title: String
private let description: String
private let time: String
private let people: String
init(title: String, description: String, time: String, people: String) {
self.title = title
self.description = description
self.time = time
self.people = people
}
var body: some View {
VStack(alignment: .leading) {
Image("recommendation-section")
.resizable()
.aspectRatio(contentMode: .fill)
Spacer(minLength: 8)
Text(title)
.fontWeight(.medium)
.font(.system(size: 16))
.multilineTextAlignment(.leading)
.lineLimit(2)
Spacer(minLength: 8)
Text(description)
.fontWeight(.thin)
.font(.system(size: 14))
.multilineTextAlignment(.leading)
.lineLimit(3)
.foregroundColor(.secondary)
Spacer()
TimeAndPeopleView(time: time, people: people, spaced: true)
}
.padding()
.background(Color.cardBackground)
.cornerRadius(8)
}
}
struct MyRecipes_Previews: PreviewProvider {
static var previews: some View {
MyRecipesScene()
.preferredColorScheme(.dark)
MyRecipesScene()
}
}
|
/*
* @lc app=leetcode.cn id=297 lang=swift
*
* [297] 二叉树的序列化与反序列化
*/
// @lc code=start
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
// public class TreeNode {
// public var val: Int
// public var left: TreeNode?
// public var right: TreeNode?
// public init(_ val: Int) {
// self.val = val
// self.left = nil
// self.right = nil
// }
// }
// 层序遍历
class Codec1 {
let NULL = "#"
let SEP = ","
func serialize(_ root: TreeNode?) -> String {
if root == nil {
return ""
}
var q = [TreeNode?]()
var res = ""
q.append(root)
while !q.isEmpty {
var node = q.removeFirst()
if node == nil {
res += NULL + SEP
continue
}
res = res + String(node!.val) + SEP
q.append(node?.left)
q.append(node?.right)
}
return res
}
func deserialize(_ data: String) -> TreeNode? {
if data.isEmpty {
return nil
}
var array = data.split(separator: ",")
print(array)
var root = TreeNode.init(Int(array[0])!)
var q = [TreeNode?]()
q.append(root)
var i = 1
while i < array.count {
var node = q.removeFirst()
var left = array[i]
if left != NULL {
node?.left = TreeNode.init(Int(left)!)
q.append(node?.left)
} else {
node?.left = nil
}
i += 1
var right = array[i]
if right != NULL {
node?.right = TreeNode.init(Int(right)!)
q.append(node?.right)
} else {
node?.right = nil
}
i += 1
}
return root
}
}
// 前序遍历
class Codec2 {
let NULL = "#"
let SEP = ","
func serialize(_ root: TreeNode?) -> String {
if root == nil {
return NULL + SEP
}
var res = String(root!.val) + SEP
res += serialize(root?.left)
res += serialize(root?.right)
return res
}
func deserialize(_ data: String) -> TreeNode? {
var array = [String]()
for s in data.split(separator: ",") {
array.append(String(s))
}
return deserialize(array: &array)
}
func deserialize(array: inout [String]) -> TreeNode? {
if array.isEmpty {
return nil
}
var first = array.removeFirst()
if first == NULL {
return nil
}
var node: TreeNode? = TreeNode.init(Int(first)!)
node?.left = deserialize(array: &array)
node?.right = deserialize(array: &array)
return node
}
}
// 后序遍历
class Codec {
let NULL = "#"
let SEP = ","
func serialize(_ root: TreeNode?) -> String {
if root == nil {
return NULL + SEP
}
var res = ""
res += serialize(root?.left)
res += serialize(root?.right)
res += String(root!.val) + SEP
return res
}
func deserialize(_ data: String) -> TreeNode? {
var array = [String]()
for s in data.split(separator: ",") {
array.append(String(s))
}
return deserialize(array: &array)
}
func deserialize(array: inout [String]) -> TreeNode? {
if array.isEmpty {
return nil
}
var last = array.removeLast()
if last == NULL {
return nil
}
var node: TreeNode? = TreeNode.init(Int(last)!)
node?.right = deserialize(array: &array)
node?.left = deserialize(array: &array)
return node
}
}
// Your Codec object will be instantiated and called as such:
// var ser = Codec()
// var deser = Codec()
// deser.deserialize(ser.serialize(root))
// @lc code=end
|
//
// PayCardsSuccessView.swift
// StarbucksImitation
//
// Created by lh on 16/6/19.
// Copyright © 2016年 codwam. All rights reserved.
//
import UIKit
final class PayCardsSuccessView: PageView {
private var combinedImageView: UIImageView!
private var backCupView: UIView!
private var cupImageView: UIImageView!
private var hurryLabel: UILabel!
var finishedButton: UIButton!
override func constructView() {
super.constructView()
// combined
self.combinedImageView = UIImageView(image: UIImage(named: "combined"))
// Cup
self.backCupView = UIView()
self.backCupView.backgroundColor = UIColor(hexString: "6C5247").flatten()
self.cupImageView = UIImageView(image: UIImage(named: "cup"))
// hurry
self.hurryLabel = UILabel()
self.hurryLabel.text = "HURRY!"
self.hurryLabel.textColor = UIColor(hexString: "CC9966").flatten()
self.hurryLabel.font = UIFont.systemFontOfSize(32)
// Finished
self.finishedButton = UIButton(type: .Custom)
self.finishedButton.setTitle("Finished", forState: .Normal)
self.finishedButton.setTitleColor(UIColor.flatWhiteColor(), forState: .Normal)
self.finishedButton.titleLabel?.font = UIFont.systemFontOfSize(18)
self.finishedButton.backgroundColor = UIColor(hexString: "6C5247").flatten()
self.addSubview(self.combinedImageView)
self.addSubview(self.backCupView)
self.backCupView.addSubview(self.cupImageView)
self.addSubview(self.hurryLabel)
self.addSubview(self.finishedButton)
}
override func constructLayout() {
// combined
let combinedImage = self.combinedImageView.image!
self.combinedImageView.snp_makeConstraints { (make) in
make.top.equalTo(10)
make.centerX.equalTo(self)
make.width.equalTo(combinedImage.size.width / 2)
make.height.equalTo(combinedImage.size.height / 2)
}
// Cup
self.backCupView.snp_makeConstraints { (make) in
make.center.equalTo(self).offset(CGPointMake(0, -60))
make.width.equalTo(180)
make.height.equalTo(180)
}
self.cupImageView.snp_makeConstraints { (make) in
make.center.equalTo(self.backCupView)
make.width.equalTo(67)
make.height.equalTo(107)
}
// hurry
self.hurryLabel.snp_makeConstraints { (make) in
make.top.equalTo(self.backCupView.snp_bottom).offset(20)
make.centerX.equalTo(self)
}
// Done
self.finishedButton.snp_makeConstraints { (make) in
make.left.right.bottom.equalTo(self)
make.height.equalTo(68)
}
}
override func layoutSubviews() {
super.layoutSubviews()
if self.backCupView.layer.cornerRadius == 0 {
self.backCupView.layer.cornerRadius = self.backCupView.bounds.width / 2
}
}
override func prepareForAnimation() {
self.backCupView.alpha = 0
self.cupImageView.alpha = 0
self.hurryLabel.alpha = 0
self.finishedButton.alpha = 0
}
override func commitAnimation() {
self.layoutIfNeeded()
let scaleAnimation = self.backCupView.addCardScaleAnimation()
scaleAnimation.completionBlock = { (_, isFinish) in
if isFinish {
self.cupImageView.addCardFlyAppearAnimationFromPositionY(self.cupImageView.center.y + self.cupImageView.bounds.height)
self.hurryLabel.addAppearAnimationWithVelocity()
self.finishedButton.addAppearAnimationWithVelocity()
}
}
}
}
|
//
// HSCYCameraInfoTableViewController.swift
// hscy
//
// Created by dingjianxin on 2017/9/6.
// Copyright © 2017年 melodydubai. All rights reserved.
//
import Alamofire
import SwiftyJSON
protocol CameraCoordinateProperty{
var cameraName:String{get set}
}
class HSCYCameraInfoTableViewController:UITableViewController{
var delegate:CameraCoordinateProperty!
var cameraInfoDic:Dictionary<String,String>!
let keysOfCameraInfo=["cameraName","lng","lat","camera_address","camera_type","pitch","tilt","build_factory","expire_date","remark","kmdata","ip_addr","northangle"]
let nameOfCameraInfo=["监控名称","经度","纬度","位置","监控类型","俯仰角","监控摆角","生产产家","使用期限","备注信息","公里数","IP地址","朝向偏北角"]
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title="监控信息"
// 设置代理
self.tableView.delegate = self
// 设置数据源
self.tableView.dataSource = self
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.register(UINib.init(nibName: "HSCYLeftRightTableCellView", bundle: nil), forCellReuseIdentifier: "cell")
self.tableView.tableFooterView=UIView()
// self.delegate.bridgeName
let param = [
"cameraName":self.delegate.cameraName
]
Alamofire.request("http://218.94.74.231:9999/SeaProject/getCameraInfo", method: .post, parameters: param).responseJSON{
(returnResult) in
if let response=returnResult.result.value{
var info=JSON(response).dictionaryObject! as Dictionary<String, AnyObject>
if !info.isEmpty
{
print("-----info\(info)")
let lng=info["lng"] as! Double
info["lng"]=String(format:"%.6f",lng) as AnyObject
let lat=info["lat"] as! Double
info["lat"]=String(format:"%.6f",lat) as AnyObject
self.cameraInfoDic=info as! Dictionary<String, String>
self.tableView.reloadData()
}
}
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if cameraInfoDic==nil {
return 0
}
return nameOfCameraInfo.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! HSCYLeftRightTableCellView
cell.selectionStyle=UITableViewCellSelectionStyle.none
cell.leftLabel?.text=nameOfCameraInfo[indexPath.row]
let key=keysOfCameraInfo[indexPath.row]
if cameraInfoDic[key] != nil&&cameraInfoDic[key] != ""{
cell.rightLabel?.text=cameraInfoDic[key]!
}else {
cell.rightLabel?.text="暂无数据"
}
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 40
}
}
|
//
// ViewController.swift
// face_detection
//
// Created by A.S.D.Vinay on 21/01/17.
// Copyright © 2017 A.S.D.Vinay. All rights reserved.
//
import UIKit
import ProjectOxfordFace
class ViewController: UIViewController {
@IBOutlet weak var imageVC: UIImageView!
@IBOutlet weak var imageVC1: UIImageView!
var faceFromPhoto1: MPOFace!
var faceFromPhoto2: MPOFace!
override func viewDidLoad() {
super.viewDidLoad()
findface()
// 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.
}
func findface(){
let client = MPOFaceServiceClient(subscriptionKey: "8f16684192cc4dca9b6264f7128c00a7")!
let data1 = UIImageJPEGRepresentation(imageVC.image!, 0.8)
let data2 = UIImageJPEGRepresentation(imageVC1.image!, 0.8)
client.detect(with: data2!, returnFaceId: true, returnFaceLandmarks: true, returnFaceAttributes: [], completionBlock: { (faces, error) in
if error != nil{
print(error!)
return
}
if faces!.count == 0 {
print("no faces atall")
return
}
self.faceFromPhoto2 = faces![0]
client.detect(with: data1!, returnFaceId: true, returnFaceLandmarks: true, returnFaceAttributes: [], completionBlock: {(faces,error) in
if error != nil{
print(error!)
return
}
if faces!.count == 0 {
print("no faces atall")
return
}
self.faceFromPhoto1 = faces![0]
client.verify(withFirstFaceId: self.faceFromPhoto1.faceId, faceId2: self.faceFromPhoto2.faceId, completionBlock: {(result,error) in
if error != nil{
print(error!)
return
}
if result!.isIdentical{
print("same")
}
else{
print("not same")
}
})
})
})
}
}
|
//
// ViewController.swift
// tableView_section
//
// Created by 新井岩生 on 2018/04/29.
// Copyright © 2018年 新井岩生. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var pList:NSMutableDictionary = [:]
var wrap:NSArray = []
override func viewDidLoad() {
super.viewDidLoad()
let filePath = Bundle.main.path(forResource: "Property List.plist", ofType: nil)
pList = NSMutableDictionary(contentsOfFile: filePath!)!
wrap = pList.object(forKey: "Wrap") as! NSArray
}
}
extension ViewController : UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
print(wrap.count)
return wrap.count
}
/**
セクション毎のタイトルをヘッダーに表示
*/
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let title = (wrap[section] as! [String:Any])["Title"]! as! String
return title
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let rows:NSArray = (wrap[section] as! [String:Any])["Row"]! as! NSArray
return rows.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// セルを取得する
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.numberOfLines = 0
let wrapItem:NSMutableDictionary = wrap[indexPath.section] as! NSMutableDictionary
let row:NSArray = wrapItem["Row"] as! NSArray
let rowItem:NSMutableDictionary = row[indexPath.row] as! NSMutableDictionary
print(rowItem["text"]!)
cell.textLabel?.text = rowItem["text"]! as? String
cell.imageView?.image = UIImage(named: rowItem["image"]! as! String)
return cell
}
}
|
//
// Joins.swift
// CouchbaseLite
//
// Copyright (c) 2017 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
/// A Joins component represents a collection of the joins clauses of the query statement.
public final class Joins: Query, WhereRouter, OrderByRouter, LimitRouter {
/// Creates and chains a Where object for specifying the WHERE clause of the query.
///
/// - Parameter expression: The where expression.
/// - Returns: The Where object that represents the WHERE clause of the query.
public func `where`(_ expression: ExpressionProtocol) -> Where {
return Where(query: self, impl: expression.toImpl())
}
/// Creates and chains an OrderBy object for specifying the orderings of the query result.
///
/// - Parameter orderings: The Ordering objects.
/// - Returns: The OrderBy object that represents the ORDER BY clause of the query.
public func orderBy(_ orderings: OrderingProtocol...) -> OrderBy {
return orderBy(orderings)
}
/// Creates and chains an OrderBy object for specifying the orderings of the query result.
///
/// - Parameter orderings: The Ordering objects.
/// - Returns: The OrderBy object that represents the ORDER BY clause of the query.
public func orderBy(_ orderings: [OrderingProtocol]) -> OrderBy {
return OrderBy(query: self, impl: QueryOrdering.toImpl(orderings: orderings))
}
/// Creates and chains a Limit object to limit the number query results.
///
/// - Parameter limit: The limit expression.
/// - Returns: The Limit object that represents the LIMIT clause of the query.
public func limit(_ limit: ExpressionProtocol) -> Limit {
return self.limit(limit, offset: nil)
}
/// Creates and chains a Limit object to skip the returned results for the given offset
/// position and to limit the number of results to not more than the given limit value.
///
/// - Parameters:
/// - limit: The limit expression.
/// - offset: The offset expression.
/// - Returns: The Limit object that represents the LIMIT clause of the query.
public func limit(_ limit: ExpressionProtocol, offset: ExpressionProtocol?) -> Limit {
return Limit(query: self, limit: limit, offset: offset)
}
// MARK: Internal
init(query: Query, impl: [CBLQueryJoin]) {
super.init()
self.copy(query)
self.joinsImpl = impl
}
}
|
import Foundation
import MarketKit
struct NftCollectionMetadata {
let blockchainType: BlockchainType
let providerUid: String
let contracts: [NftContractMetadata]
let name: String
let description: String?
let imageUrl: String?
let thumbnailImageUrl: String?
let externalLink: String?
let discordLink: String?
let twitterUsername: String?
let count: Int?
let ownerCount: Int?
let totalSupply: Int?
let totalVolume: Decimal?
let floorPrice: NftPrice?
let marketCap: NftPrice?
let royalty: Decimal?
let inceptionDate: Date?
let volume1d: NftPrice?
let change1d: Decimal?
let sales1d: Int?
let averagePrice1d: NftPrice?
let volume7d: NftPrice?
let change7d: Decimal?
let sales7d: Int?
let averagePrice7d: NftPrice?
let volume30d: NftPrice?
let change30d: Decimal?
let sales30d: Int?
let averagePrice30d: NftPrice?
}
|
//
// MainMenuViewController.swift
// Skyward Jump
//
// Created by Petr Zvoníček on 16.03.15.
// Copyright (c) 2015 NTNU. All rights reserved.
//
import UIKit
import GameKit
class MainMenuViewController: UIViewController {
@IBOutlet var singlePlayerButton: UIButton!
@IBOutlet var multiPlayerButton: UIButton!
var negotiatedWorld: World?
override func viewDidLoad() {
super.viewDidLoad()
MultiplayerManager.sharedInstance.comm.authenticate(self, callback: { (world) -> Void in
self.negotiatedWorld = world
self.performSegueWithIdentifier("multiplayerSegue", sender: self)
})
}
@IBAction func didClickMultiplayerButton(sender: UIButton) {
MultiplayerManager.sharedInstance.comm.findMatch(self, callback: { (world) -> Void in
self.negotiatedWorld = world
self.performSegueWithIdentifier("multiplayerSegue", sender: self)
})
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if let dest = segue.destinationViewController as? GameViewController {
if segue.identifier == "multiplayerSegue" {
dest.multiplayerMode = true
if let world = self.negotiatedWorld {
dest.negotiatedWorld = world
}
}
}
}
}
|
//
// TrendAnRowStatisticsView.swift
// DaLeTou
//
// Created by 刘明 on 2017/3/18.
// Copyright © 2017年 刘明. All rights reserved.
//
import UIKit
class TrendAnRowStatisticsView: UIView {
let titleLabel = UILabel()
var numberLabels = [UILabel]()
override init(frame: CGRect) {
super.init(frame: frame)
titleLabel.frame = CGRect(x: 0, y: 0, width: 65, height: 25)
titleLabel.font = UIFont.systemFont(ofSize: 11.0)
titleLabel.textAlignment = .center
titleLabel.layer.borderWidth = 0.5
titleLabel.layer.borderColor = Common.grayColor.cgColor
self.addSubview(titleLabel)
for i in 1...47 {
let numberLabel = UILabel(frame: CGRect(x: 65 + (i - 1) * 25,
y: 0,
width: 25,
height: 25))
numberLabel.layer.borderWidth = 0.5
numberLabel.layer.borderColor = Common.grayColor.cgColor
numberLabel.textAlignment = .center
numberLabel.font = UIFont.systemFont(ofSize: 11.0)
self.addSubview(numberLabel)
numberLabels.append(numberLabel)
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setStatisticsData(data: [Int]) {
if data.count == numberLabels.count {
var i = 0
for numberLabel in numberLabels {
numberLabel.text = String(data[i])
i += 1
}
}
}
func setState(state: Int) {
var textColor = UIColor.gray
switch state {
case 0:
textColor = UIColor.purple
break
case 1:
textColor = UIColor.cyan
break
case 2:
textColor = UIColor.brown
break
case 3:
textColor = UIColor.green
break
default:
textColor = UIColor.gray
break
}
titleLabel.backgroundColor = UIColor(colorLiteralRed: 235.0/255.0,
green: 231.0/255.0,
blue: 219.0/255.0,
alpha: 1.0)
titleLabel.textColor = textColor
if state % 2 == 1 {
titleLabel.backgroundColor = UIColor(colorLiteralRed: 246.0/255.0,
green: 240.0/255.0,
blue: 240.0/255.0,
alpha: 1.0)
}
for numberLabel in numberLabels {
numberLabel.textColor = textColor
numberLabel.backgroundColor = UIColor.white
if state % 2 == 1 {
numberLabel.backgroundColor = UIColor.groupTableViewBackground
}
}
}
}
|
//
// WeightLabel.swift
// KayakFirst Ergometer E2
//
// Created by Balazs Vidumanszki on 2017. 07. 08..
// Copyright © 2017. Balazs Vidumanszki. All rights reserved.
//
import Foundation
class WeightLabel: UILabel {
//MARK: properties
private let weight: CGFloat
//MARK: init
init(weight: CGFloat) {
self.weight = weight
super.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: size
override var intrinsicContentSize: CGSize {
get {
return CGSize(width: weight * 100, height: 0)
}
}
}
|
//
// MassTransferTransaction+Mapper.swift
// WavesWallet-iOS
//
// Created by mefilt on 30.08.2018.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import Foundation
import WavesSDKExtensions
import WavesSDK
import DomainLayer
extension MassTransferTransaction {
convenience init(transaction: DomainLayer.DTO.MassTransferTransaction) {
self.init()
type = transaction.type
id = transaction.id
sender = transaction.sender
senderPublicKey = transaction.senderPublicKey
fee = transaction.fee
timestamp = transaction.timestamp
version = transaction.version
height = transaction.height
modified = transaction.modified
assetId = transaction.assetId
attachment = transaction.attachment
transferCount = transaction.transferCount
totalAmount = transaction.totalAmount
if let proofs = transaction.proofs {
self.proofs.append(objectsIn: proofs)
}
let transfers = transaction
.transfers
.map { model -> MassTransferTransactionTransfer in
let info = MassTransferTransactionTransfer()
info.recipient = model.recipient
info.amount = model.amount
return info
}
self.transfers.append(objectsIn: transfers)
status = transaction.status.rawValue
}
}
extension DomainLayer.DTO.MassTransferTransaction {
init(transaction: NodeService.DTO.MassTransferTransaction,
status: DomainLayer.DTO.TransactionStatus,
environment: WalletEnvironment) {
let transfers: [DomainLayer.DTO.MassTransferTransaction.Transfer] = transaction
.transfers
.map { .init(recipient: $0.recipient.normalizeAddress(environment: environment),
amount: $0.amount) }
self.init(type: transaction.type,
id: transaction.id,
sender: transaction.sender.normalizeAddress(environment: environment),
senderPublicKey: transaction.senderPublicKey,
fee: transaction.fee,
timestamp: transaction.timestamp,
version: transaction.version,
height: transaction.height ?? 0,
proofs: transaction.proofs,
assetId: transaction.assetId.normalizeAssetId,
attachment: transaction.attachment,
transferCount: transaction.transferCount,
totalAmount: transaction.totalAmount,
transfers: transfers,
modified: Date(),
status: status)
self.status = status
}
init(transaction: MassTransferTransaction) {
let transfers = transaction
.transfers
.toArray()
.map { DomainLayer.DTO.MassTransferTransaction.Transfer(recipient: $0.recipient,
amount: $0.amount) }
self.init(type: transaction.type,
id: transaction.id,
sender: transaction.sender,
senderPublicKey: transaction.senderPublicKey,
fee: transaction.fee,
timestamp: transaction.timestamp,
version: transaction.version,
height: transaction.height,
proofs: transaction.proofs.toArray(),
assetId: transaction.assetId.normalizeAssetId,
attachment: transaction.attachment,
transferCount: transaction.transferCount,
totalAmount: transaction.totalAmount,
transfers: transfers,
modified: transaction.modified,
status: DomainLayer.DTO.TransactionStatus(rawValue: transaction.status) ?? .completed)
}
}
|
//
// ProtocolGalleryItemDisplayViewAccessStrategy.swift
// f26View
//
// Created by David on 19/08/2017.
// Copyright © 2017 com.smartfoundation. All rights reserved.
//
import f26Core
/// Defines a class which provides a strategy for accessing the GalleryItemDisplay view
public protocol ProtocolGalleryItemDisplayViewAccessStrategy {
// MARK: - Methods
/// Display artwork
///
func display(artwork: ArtworkWrapper)
func displayNumberofLikes(numberofLikes: Int)
func clearLatestArtworkComment()
func displayLatestArtworkComment(text: String, postedByName: String, datePosted: Date)
}
|
//
// ItemsDataSource.swift
// Recruitment-iOS
//
// Created by Oleksandr Bambulyak on 18/03/2020.
// Copyright © 2020 Untitled Kingdom. All rights reserved.
//
import Foundation
import UIKit
protocol ItemsDataSourceDelegate: class {
func reloadData()
}
class ItemsDataSource {
private var items = [ItemData]()
weak var delegate: ItemsDataSourceDelegate?
func getNumbersOfSections() -> Int {
return 1
}
func getNumberOfItems(at section: Int) -> Int {
return self.items.count
}
func getModelBy(index: Int) -> ItemData? {
return items[index]
}
func getCell(for collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "itemCell", for: indexPath) as? ItemCollectionViewCell else { return UICollectionViewCell() }
let model = self.items[indexPath.row]
cell.display(model: model)
return cell
}
func insertItems(_ items: [ItemData]) {
self.updateWithItems(items)
}
private func updateWithItems(_ items: [ItemData]) {
self.items = items
DispatchQueue.main.async {
self.delegate?.reloadData()
}
}
}
|
//
// BaseModel.swift
// 天猫抽屉
//
// Created by bingoogol on 14/10/2.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
class BaseModel: NSObject {
var image:UIImage!
var name:NSString!
init(dict:NSDictionary) {
self.name = dict["name"] as NSString
self.image = UIImage(named: dict["imageName"] as NSString)
}
} |
//
// NSObject+ClassName.swift
// Piicto
//
// Created by OkuderaYuki on 2018/01/07.
// Copyright © 2018年 SmartTech Ventures Inc. All rights reserved.
//
import Foundation
extension NSObject {
/// クラス名を取得する
static var className: String {
return String(describing: self)
}
}
|
//
// User.swift
// Foodie
//
// Created by Justine Breuch on 8/31/15.
// Copyright (c) 2015 Justine Breuch. All rights reserved.
//
import Foundation
import Parse
struct User {
let id: String
private let pfUser: PFUser
}
func pfUserToUser(user: PFUser) -> User {
return User(id: user.objectId!, pfUser: user)
}
//func currentUser() -> User? {
// if let user = PFUser.currentUser() {
// return pfUserToUser(user)
// }
// return nil
//}
//
//func saveSkip(user: User) {
// let skip = PFObject(className: "Action")
// skip.setObject(PFUser.currentUser()!.objectId!, forKey: "byUser")
// skip.setObject(place.id, forKey: "toPlace")
// skip.setObject("skipped", forKey: "type")
// skip.saveInBackgroundWithBlock(nil)
//}
//
//func saveLike(user: User) {
//
// PFQuery(className: "Action")
// .whereKey("byUser", equalTo: user.id)
// // set after you make Place.swift
// .whereKey("toPlace", equalTo: PFUser.currentUser().objectId)
// .whereKey("type", equalTo: "liked")
// .getFirstObjectInBackgroundWithBlock({
// object, error in
//
// var matched = false
//
// if object != nil {
// matched = true
// object.setObject("matched", forKey: "type")
// object.saveInBackgroundWithBlock(nil)
// }
//
// let match = PFObject(className: "Action")
// match.setObject(PFUser.currentUser().objectId, forKey: "byUser")
// match.setObject(user.id, forKey: "toUser")
// match.setObject(matched ? "matched" : "liked", forKey: "type")
// match.saveInBackgroundWithBlock(nil)
//
// })
//}
|
//
// ScrollableTextField.swift
// SwiftSamples
//
// Created by Tsukasa Hasegawa on 2018/12/30.
// Copyright © 2018 Tsukasa Hasegawa. All rights reserved.
//
import UIKit
class ScrollableTextFieldViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var upperTextField: UITextField!
@IBOutlet weak var lowerTextField: UITextField!
private var activeTextField = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
upperTextField.delegate = self
lowerTextField.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(ScrollableTextFieldViewController.didReceiveTextFieldShownNotification(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(ScrollableTextFieldViewController.didReceiveTextFieldHiddenNotification(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
let notificationCenter = NotificationCenter.default
notificationCenter.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
notificationCenter.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@objc private func didReceiveTextFieldShownNotification(_ notification: Notification) {
let userInfo = notification.userInfo
let keyboardScreenEndFrame = (userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let boundsSize = UIScreen.main.bounds.size
let textLowerY = activeTextField.frame.origin.y + activeTextField.frame.height + 8.0
let keyboardUpperY = boundsSize.height - keyboardScreenEndFrame.size.height
print("textLowerY: \(textLowerY)")
print("keyboardUpperY: \(keyboardUpperY)")
let statusbarHeight: CGFloat = UIApplication.shared.statusBarFrame.height
let navigationBarHeight: CGFloat = self.navigationController?.navigationBar.frame.size.height ?? 0.0
if textLowerY >= keyboardUpperY {
scrollView.contentOffset.y = textLowerY - keyboardUpperY + statusbarHeight + navigationBarHeight
}
}
@objc private func didReceiveTextFieldHiddenNotification(_ notification: Notification) {
scrollView.contentOffset.y = 0
}
}
extension ScrollableTextFieldViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.activeTextField.resignFirstResponder()
// self.view.endEditing(true)
return true
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
self.activeTextField = textField
return true
}
}
|
//
// SideBarDelegate.swift
// SideBarDemo
//
// Created by thierryH24 on 25/10/2017.
// Copyright © 2017 thierryH24. All rights reserved.
//
import AppKit
public protocol THSideBarViewDelegate : class
{
/// Called when a value has been selected inside the outline.
func changeView( item : Item)
}
extension THSideBarViewController: NSOutlineViewDelegate {
/// When a row is clicked on should it be selected
public func outlineView(_ outlineView: NSOutlineView, shouldSelectItem item: Any) -> Bool
{
return !isSourceGroupItem(item)
}
/// Height of each row
func outlineView(_ outlineView: NSOutlineView, heightOfRowByItem item: Any) -> CGFloat {
if isSourceGroupItem(item) == true {
return 30.0
}
return 20.0
}
/// Whether a row should be collapsed
func outlineView(_ outlineView: NSOutlineView, shouldCollapseItem item: Any) -> Bool {
return isSourceGroupItem(item)
}
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
if let section = item as? Section
{
let cell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "FeedCellHeader"), owner: self) as! KSHeaderCellView
// cell.fillColor = self.colorBackGround
cell.wantsLayer = true
cell.layer?.backgroundColor = self.colorBackGround.cgColor
cell.textField!.stringValue = section.section.name.uppercased()
// cell.imageView!.image = section.icon
return cell
}
else if let account = item as? Item
{
let cell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "FeedCell"), owner: self) as? THSideBarCellView
// cell?.imageView!.image = account.icon
// cell?.backgroundColor = account.colorBadge.cgColor
var attribut = [NSAttributedString.Key : Any]()
attribut[.foregroundColor] = NSColor.gray
attribut[ .font] = NSFont.boldSystemFont(ofSize: 12.0)
let attributText = NSMutableAttributedString(string: account.name )
attributText.setAttributes(attribut, range: NSMakeRange(0, attributText.length))
cell?.textField!.delegate = self
cell?.textField!.attributedStringValue = attributText
cell?.textField!.textColor = colorText
cell?.button.isHidden = account.isHidden
cell?.title = account.badge
// cell?.backgroundColor = account.colorBadge.cgColor
cell?.button?.bezelStyle = .inline // Make it appear as a normal label and not a button
cell?.needsDisplay = true
return cell
}
return nil
}
public func outlineViewSelectionDidChange(_ notification: Notification)
{
guard let outlineView = notification.object as? NSOutlineView else { return }
let selectedIndex = outlineView.selectedRow
if let item = outlineView.item(atRow: selectedIndex) as? Item
{
delegate?.changeView( item : item)
}
}
}
|
enum CircularBufferError: Error {
case bufferEmpty
case bufferFull
}
class CircularBuffer<T>: CustomStringConvertible {
var description: String {
var output = ""
_buffer.forEach {
if let e = $0 {
output += "[ \(e) ]"
} else {
output += "[ ]"
}
}
return output
}
private struct Index {
var last = 0
var oldest = 0
mutating public func reset() {
last = 0
oldest = 0
}
}
private var _buffer: ContiguousArray<T?> = []
private var _capacity: Int
private var _used = 0
private var _indices = Index()
private var _bufferIsFull: Bool { return _used == _capacity }
private var _bufferIsEmpty: Bool { return _used == 0 }
init(capacity: Int) {
_buffer.reserveCapacity(capacity)
_capacity = capacity
for _ in 0..<capacity { _buffer.append(nil) }
}
public func write(_ data: T) throws {
guard _bufferIsFull == false else {
throw CircularBufferError.bufferFull
}
_buffer[_indices.last] = data
_indices.last = (_indices.last + 1) % _capacity
_used += 1
}
public func read() throws -> T {
guard _bufferIsEmpty == false else {
throw CircularBufferError.bufferEmpty
}
let data = _buffer[_indices.oldest]
_used -= 1
_indices.oldest = (_indices.oldest + 1) % _capacity
return data!
}
public func clear() {
_indices.reset()
_used = 0
}
public func overwrite(_ withData: T) {
_buffer[_indices.oldest] = withData
_indices.oldest = (_indices.oldest + 1) % _capacity
if _bufferIsFull == false {
_used += 1
}
}
}
|
import UIKit
class AlertRouter {
weak var viewController: UIViewController?
}
extension AlertRouter: IAlertRouter {
func close(completion: (() -> Void)? = nil) {
DispatchQueue.main.async { [weak self] in
self?.viewController?.dismiss(animated: true, completion: completion)
}
}
}
extension AlertRouter {
static func module(title: String, viewItems: [AlertViewItem], afterClose: Bool = false, onSelect: @escaping (Int) -> ()) -> UIViewController {
let router = AlertRouter()
let presenter = AlertPresenter(viewItems: viewItems, onSelect: onSelect, router: router, afterClose: afterClose)
let viewController = AlertViewController(alertTitle: title, delegate: presenter)
presenter.view = viewController
router.viewController = viewController
return viewController.toAlert
}
}
|
import SwiftUI
import Network
var userDict = User()
let monitor = NWPathMonitor()
let queue = DispatchQueue(label: "Monitor")
struct LoginView: View {
@ObservedObject var profile = UserData()
@State var inputID: String = ""
@State var inputPassword: String = ""
@State var errorMessage: String = ""
@State var isActiveOperationInitialSettingView = false
@State var tokenDict = Token()
@State var communicationAlert = false
@State var apiErrorAlert = false
var body: some View {
NavigationView {
VStack(alignment: .center,spacing: UIScreen.main.bounds.height/32) {
Text("三間地区コミュニティバス\n乗降者数管理システム")
.font(.system(size: 48,
weight: .heavy))
.frame(height: UIScreen.main.bounds.height * 8 / 32)
.multilineTextAlignment(.center)
.fixedSize()
Text(errorMessage)
.foregroundColor(Color.red)
.frame(height: UIScreen.main.bounds.height / 32)
TextField("ユーザーID", text: $profile.userid)
.textFieldStyle(RoundedBorderTextFieldStyle())
.frame(maxWidth: 500)
.frame(height: UIScreen.main.bounds.height / 32)
SecureField("パスワード", text: $inputPassword)
.textFieldStyle(RoundedBorderTextFieldStyle())
.frame(maxWidth: 500)
.frame(height: UIScreen.main.bounds.height / 32)
VStack {
//コード上のイベントで遷移したい場合は、LabelにEmptyViewを指定する
NavigationLink(destination: OperationInitialSettingView( isActiveOperationInitialSettingView: $isActiveOperationInitialSettingView),
isActive: $isActiveOperationInitialSettingView) {
EmptyView()
}
.onAppear {
monitor.start(queue: queue)
}
Button(action: {
// トークンのダミーデータをuserdefaultで保存
if let encodedValue = try? JSONEncoder().encode(self.tokenDict) {
UserDefaults.standard.set(encodedValue, forKey: "token")
}
let callAPI = CallAPI.init()
// トークンの取得
let tokenDict: [String: Any] = [
"email": self.profile.userid,
"password": self.inputPassword
]
do{
if monitor.currentPath.status == .unsatisfied{
communicationAlert = true
throw NSError(domain: "errorメッセージ", code: -1, userInfo: nil)
}
let jsonDataToken = callAPI.requestData(url: "/login/", dict: tokenDict, type: "POST")
if apiErrorFlag == true{
apiErrorAlert = true
apiErrorFlag = false
throw NSError(domain: "errorメッセージ", code: -1, userInfo: nil)
}
self.tokenDict = try JSONDecoder().decode(Token.self, from: jsonDataToken)
// トークンの保存
if let encodedValue = try? JSONEncoder().encode(self.tokenDict) {
UserDefaults.standard.set(encodedValue, forKey: "token")
}
// ユーザ情報の取得
let jsonDataUser = callAPI.requestData(url: "/user/info/", dict: [:], type: "GET")
userDict = try JSONDecoder().decode(User.self, from: jsonDataUser)
self.errorMessage = ""
self.isActiveOperationInitialSettingView.toggle()
} catch{
if communicationAlert == false && apiErrorAlert == false{
self.errorMessage = "IDまたはパスワードが間違っています"
}
}
},
label: {
Text("ログイン")
.fontWeight(.medium)
.frame(minWidth: 160)
.foregroundColor(.white)
.padding(12)
.background(Color.accentColor)
.cornerRadius(8)
.padding(UIScreen.main.bounds.height / 32)
})
}.alert(isPresented: $communicationAlert){
Alert.init(
title: Text("通信エラー"),
message: Text("アカウント情報の送信に失敗しました"))
}
Text("")
.alert(isPresented: $apiErrorAlert){
Alert(
title: Text("送信に失敗しました"),
message: Text("もう一度お試しください")
)
}
}
.navigationBarTitle("ログイン画面", displayMode: .inline)
}.navigationViewStyle(StackNavigationViewStyle())
}
}
class UserData: ObservableObject {
/// ユーザ名
@Published var userid: String {
didSet {
UserDefaults.standard.set(userid, forKey: "userid")
}
}
/// 初期化処理
init() {
userid = UserDefaults.standard.string(forKey: "userid") ?? ""
}
}
struct Token: Codable{
var access_token: String = ""
var token_type: String = ""
var expire_in: Int = 0
}
struct User: Codable {
var id: String = ""
var name: String = ""
var phone_number: String = ""
var email: String = ""
}
struct LoginView_Previews: PreviewProvider {
static var previews: some View {
LoginView()
}
}
|
//
// Country.swift
// Corona MVVM
//
// Created by Frederic Orlando on 30/07/20.
// Copyright © 2020 Frederic Orlando. All rights reserved.
//
import Foundation
class Country : Count {
var name : String = ""
var code : String = ""
var slug : String = ""
private enum CodingKeys: String, CodingKey {
case name = "Country"
case code = "CountryCode"
case slug = "Slug"
}
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
code = try container.decode(String.self, forKey: .code)
slug = try container.decode(String.self, forKey: .slug)
}
}
|
// Mission.swift
import Foundation
struct Mission: Codable,
Identifiable {
// MARK: - NESTED TYPES
struct CrewRole: Codable {
let name: String
let role: String
}
// MARK: - PROPERTIES -
let id: Int
let launchDate: Date?
let crew: [CrewRole]
let description: String
// MARK: - COMPUTED PROPERTIES -
var displayName: String {
return "Apollo \(id)"
}
var imageName: String {
return "apollo\(id)"
}
var formattedLaunchDate: String {
guard let _launchDate = launchDate
else {
return "N/A"
}
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
return dateFormatter.string(from: _launchDate)
}
}
|
//
// Elt.swift
// Excercism
//
// Created by Hai Nguyen on 8/19/15.
// Copyright © 2015 Hai Nguyen. All rights reserved.
//
struct ETL {
static func transform(old: [Int: [String]]) -> [String: Int] {
var result = [String: Int]()
for (score, array) in old {
result = array.reduce(result) { (var dict, elem) in
dict[elem.lowercaseString] = score
return dict
}
}
return result
}
} |
import Foundation
import CocoaLumberjack
// MARK: - Jack.ScopeRoster
extension Jack {
internal enum ScopeRoster {
static let lock = NSRecursiveLock()
static var items = [String: Item]()
}
}
// MARK: - Jack.ScopeRoster.Item
extension Jack.ScopeRoster {
struct Item {
var level: DDLogLevel?
var options: Jack.Format?
init() {
level = nil
options = nil
}
}
}
// MARK: - Lookup in ScopeRoster
internal extension Jack.ScopeRoster {
enum LookupResult<T: HasFallback>: Equatable {
case set(T)
case inherit(T, from: String)
case fallback
var value: T {
switch self {
case let .set(lvl):
return lvl
case .inherit(let lvl, from: _):
return lvl
case .fallback:
return T.fallback
}
}
}
static func lookup<T: HasFallback>(_: T.Type, scope: Jack.Scope, keyPath: KeyPath<Item, T?>) -> LookupResult<T> {
lock.lock(); defer { lock.unlock() }
if let value = items[scope.string]?[keyPath: keyPath] {
return .set(value)
}
for scopeString in scope.superScopeStrings.dropFirst() {
if let value = items[scopeString]?[keyPath: keyPath] {
return .inherit(value, from: scopeString)
}
}
return .fallback
}
static func set<T: HasFallback>(_ value: T?, scope: Jack.Scope, keyPath: WritableKeyPath<Item, T?>) {
lock.lock()
items[scope.string, default: Item()][keyPath: keyPath] = value
lock.unlock()
}
}
|
//
// HomeCVCell.swift
// Movie
//
// Created by Elattar on 8/21/19.
// Copyright © 2019 Elattar. All rights reserved.
//
import UIKit
import Gemini
class HomeCVCell: GeminiCell {
@IBOutlet weak var movieRate_lbl: UILabel!
@IBOutlet weak var movieTitle_lbl: UILabel!
@IBOutlet weak var moviePoster_img: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
moviePoster_img.layer.cornerRadius = 10.0
moviePoster_img.layer.masksToBounds = true
}
override func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = 3.0
layer.shadowRadius = 10
layer.shadowOpacity = 0.2
layer.shadowOffset = CGSize(width: 5, height: 10)
self.clipsToBounds = false
}
}
|
//
// DogAPI.swift
// Randog-1.0
//
// Created by Wolfgang Sigel on 29.03.20.
// Copyright © 2020 Wolfgang Sigel. All rights reserved.
//
import Foundation
class DogAPI {
enum Endpoint: String {
case randomImageFromAllDogsCollection = "https://dog.ceo/api/breeds/image/random"
var url: URL {
return URL(string: self.rawValue)!
}
}
}
|
//
// ViewController.swift
// NotiMe
//
// Created by Olarn U. on 23/6/2564 BE.
//
import UIKit
import UserNotifications
class ViewController: UIViewController {
@IBOutlet weak var requestToggle: UISwitch!
@IBOutlet weak var pushPermissionLabel: UILabel!
@IBOutlet weak var soundLabel: UILabel!
@IBOutlet weak var badgeLabel: UILabel!
@IBOutlet weak var alertLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(
self,
selector: #selector(getNotificationSettings),
name: UIApplication.didBecomeActiveNotification,
object: nil)
}
@objc func getNotificationSettings() {
UNUserNotificationCenter
.current()
.getNotificationSettings { [weak self] settings in
DispatchQueue.main.async {
if settings.authorizationStatus == .authorized {
self?.requestToggle.isOn = LocalStore().pushIsEnabled
} else {
self?.requestToggle.isOn = false
}
self?.pushPermissionLabel.text = "Push noti Permission: " + settings.authorizationStatus.toString()
self?.alertLabel.text = "Alert: \(settings.alertSetting == .enabled ? "Yes" : "No")"
self?.soundLabel.text = "Sound: \(settings.soundSetting == .enabled ? "Yes" : "No")"
self?.badgeLabel.text = "Badge: \(settings.badgeSetting == .enabled ? "Yes" : "No")"
}
}
}
@IBAction func toggleValueChanged(_ sender: Any) {
LocalStore().set(pushEnable: requestToggle.isOn)
if !requestToggle.isOn {
// call server to set noti OFF
return
}
UNUserNotificationCenter
.current()
.requestAuthorization(options: [.sound, .alert, .badge]) { [weak self] granted, _ in
self?.getNotificationSettings()
if granted {
// call server to set noti ON
} else {
DispatchQueue.main.async {
let alert = UIAlertController(
title: "Permission Denined",
message: "Permission Denined. You can enable in App Settings.",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Settings", style: .default) { action in
// navigate to home
// and ...
if let appSettings = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(appSettings, options: [:], completionHandler: nil)
}
})
self?.present(alert, animated: true)
}
}
}
}
}
extension UNAuthorizationStatus {
func toString() -> String {
switch self {
case .authorized:
return "Permitted"
case .denied:
return "Denined"
case .notDetermined:
return "Not Determind"
default:
return "Unknow"
}
}
}
|
//
// DetailViewModel.swift
// WBNewsApp
//
// Created by ShaunMacPro on 16/09/2018.
// Copyright © 2018 ShaunMacPro. All rights reserved.
//
import Foundation
class DetailViewModel {
//Input
var viewDidLoad: () -> Void = { }
// Output
var displayError: (String) -> Void = { _ in }
var numberOfRows = 0
var title = ""
private var tableDataSource = [PostCellDataModel]()
init(data: [PostCellDataModel]) {
self.tableDataSource = data
configureOutput()
}
private func configureOutput() {
title = tableDataSource[0].title
numberOfRows = tableDataSource.count
}
func tableCellDataModelForIndexPath(_ indexPath: IndexPath) -> PostCellDataModel {
return tableDataSource[indexPath.row]
}
}
|
//
// MuscleCollectionViewCell.swift
// BalancedGym
//
// Created by Pablo Pesce on 13/01/2018.
// Copyright © 2018 Pablou. All rights reserved.
//
import UIKit
class MuscleCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView : UIImageView!;
@IBOutlet weak var muscleLabel: UILabel!
var muscle: Muscle?
func setMuscle(muscle: Muscle) {
self.muscle = muscle
setMuscleURL(imageUrlString: muscle.muscleURL)
muscleLabel.text = muscle.name
}
func setMuscleURL(imageUrlString : String) {
if (imageUrlString != "") {
let imageUrl:URL = URL(string: imageUrlString)!
// Start background thread so that image loading does not make app unresponsive
DispatchQueue.global(qos: .userInitiated).async {
let imageData:NSData = NSData(contentsOf: imageUrl)!
// When from background thread, UI needs to be updated on main_queue
DispatchQueue.main.async {
let image = UIImage(data: imageData as Data)
self.imageView.image = image
}
}
}
}
}
|
//
// ExamplesApp.swift
// Examples
//
// Created by Makoto Aoyama on 2020/09/24.
//
import SwiftUI
@main
struct ExamplesApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
|
/*
* Copyright (c) 2015 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
class GamePickerViewController: UITableViewController {
var selectedDay = [Bool](count: 7, repeatedValue: false)
var games:[String] = [
"Su",
"Mo",
"Tu",
"We",
"Th",
"Fr",
"Sa"]
/* var selectedGame:String? {
didSet {
if let game = selectedGame {
selectedGameIndex = games.indexOf(game)!
}
}
}*/
var selectedGame:String = ""
var selectedGameIndex:Int?
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return games.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("GameCell", forIndexPath: indexPath)
cell.textLabel?.text = games[indexPath.row]
if indexPath.row == selectedGameIndex {
cell.accessoryType = .Checkmark
} else {
cell.accessoryType = .None
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
// //Other row is selected - need to deselect it
// if let index = selectedGameIndex {
// let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: index, inSection: 0))
// cell?.accessoryType = .None
// }
// let cell1 = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: indexPath.row, inSection: 0))
//
// if cell1?.accessoryType == .None {
// cell1?.accessoryType = .Checkmark
// } else if cell1?.accessoryType == .Checkmark{
// cell1?.accessoryType = .None
// }
selectedGame = games[indexPath.row]
//update the checkmark for the current row
let cell = tableView.cellForRowAtIndexPath(indexPath)
if cell?.accessoryType != .Checkmark {
selectedDay[indexPath.row] = true
cell?.accessoryType = .Checkmark
}
else if cell?.accessoryType == .Checkmark{
selectedDay[indexPath.row] = false
cell?.accessoryType = .None
}
// print(selectedDay)
//cell?.accessoryType = .Checkmark
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
//print("1")
/* if segue.identifier == "SaveSelectedGame" {
if let cell = sender as? UITableViewCell {
let indexPath = tableView.indexPathForCell(cell)
if let index = indexPath?.row {
selectedGame = games[index]
}
}
}*/
var strA:[String] = [String]()
for i in 0...6{
if(selectedDay[i]){
strA.append(games[i])
}
}
let stringRep = strA.joinWithSeparator(", ") // "Sunday, Monday, Tuesday"
selectedGame = stringRep
// print(stringRep)
}
}
|
//
// MetronomeView.swift
// Metronome
//
// Created by luca strazzullo on 30/9/19.
// Copyright © 2019 luca strazzullo. All rights reserved.
//
import SwiftUI
struct MetronomeView: View {
private(set) var viewModel: SessionViewModel
var body: some View {
ZStack {
Color(Palette.black).edgesIgnoringSafeArea(.all)
VStack(alignment: .center, spacing: 24) {
BeatsView(viewModel: buildBeatsViewModel())
ControlsView(viewModel: buildControlsViewModel())
}
}
.gesture(TapGesture()
.onEnded { gesture in
self.viewModel.toggleIsRunning()
})
}
// MARK: Private helper methods
private func buildBeatsViewModel() -> BeatsViewModel {
return BeatsViewModel(sessionController: viewModel.controller)
}
private func buildControlsViewModel() -> ControlsViewModel {
return ControlsViewModel(controller: viewModel.controller)
}
}
|
//
// UIVIewController+Ext.swift
// ViperSample
//
// Created by InKwon Devik Kim on 20/03/2019.
// Copyright © 2019 InKwon Devik Kim. All rights reserved.
//
import UIKit
extension UIViewController {
func confirmationAlert(title: String, message: String, confirmTitle: String, style: UIAlertAction.Style = .destructive, confirmAction: @escaping () -> Void) {
let deleteActionSheetController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let deleteAction = UIAlertAction(title: confirmTitle, style: style) {
action -> Void in
confirmAction()
}
let cancelAction = UIAlertAction(title: "cancel_text", style: .cancel) { action -> Void in
}
deleteActionSheetController.addAction(deleteAction)
deleteActionSheetController.addAction(cancelAction)
self.present(deleteActionSheetController, animated: true, completion: nil)
}
func alert(message: String?, title: String? = "alert_text", okAction: (()->())? = nil) {
let alertController = getAlert(message: message, title: title)
alertController.addAction(title: "ok_text", handler: okAction)
self.present(alertController, animated: true, completion: nil)
}
func alertWithOkCancel(message: String?, title: String? = "Error", okTitle: String? = "ok_text", style: UIAlertController.Style? = .alert, cancelTitle: String? = "cancel_text", OkStyle: UIAlertAction.Style = .default, cancelStyle: UIAlertAction.Style = .default, okAction: (()->())? = nil, cancelAction: (()->())? = nil) {
let alertController = getAlert(message: message, title: title, style: style)
alertController.addAction(title: okTitle,style: OkStyle, handler: okAction)
alertController.addAction(title: cancelTitle, style: cancelStyle, handler: cancelAction)
self.present(alertController, animated: true, completion: nil)
}
func alertWithOk(message: String?, title: String? = "Error", okTitle: String? = "ok_text", style: UIAlertController.Style? = .alert, OkStyle: UIAlertAction.Style = .default, okAction: (()->())? = nil) {
let alertController = getAlert(message: message, title: title, style: style)
alertController.addAction(title: okTitle,style: OkStyle, handler: okAction)
self.present(alertController, animated: true, completion: nil)
}
private func getAlert(message: String?, title: String?, style: UIAlertController.Style? = .alert) -> UIAlertController {
return UIAlertController(title: title, message: message, preferredStyle: style ?? .alert)
}
func present(_ alert: UIAlertController, asActionsheetInSourceView sourceView: Any) {
if UI_USER_INTERFACE_IDIOM() == .pad {
alert.modalPresentationStyle = .popover
if let presenter = alert.popoverPresentationController {
if sourceView is UIBarButtonItem {
presenter.barButtonItem = sourceView as? UIBarButtonItem
}else if sourceView is UIView {
let view = sourceView as! UIView
presenter.sourceView = view
presenter.sourceRect = view.bounds
}
}
}
self.present(alert, animated: true, completion: nil)
}
}
extension UIAlertController {
func addAction(title: String?, style: UIAlertAction.Style = .default, handler: (()->())? = nil) {
let action = UIAlertAction(title: title, style: style, handler: {_ in
handler?()
})
self.addAction(action)
}
}
|
@testable import TMDb
import XCTest
final class TVShowsEndpointTests: XCTestCase {
func testTVShowDetailsEndpointReturnsURL() throws {
let expectedURL = try XCTUnwrap(URL(string: "/tv/1"))
let url = TVShowsEndpoint.details(tvShowID: 1).path
XCTAssertEqual(url, expectedURL)
}
func testTVShowCreditsEndpointReturnsURL() throws {
let expectedURL = try XCTUnwrap(URL(string: "/tv/1/credits"))
let url = TVShowsEndpoint.credits(tvShowID: 1).path
XCTAssertEqual(url, expectedURL)
}
func testTVShowReviewsEndpointReturnsURL() throws {
let expectedURL = try XCTUnwrap(URL(string: "/tv/1/reviews"))
let url = TVShowsEndpoint.reviews(tvShowID: 1).path
XCTAssertEqual(url, expectedURL)
}
func testTVShowReviewsEndpointWithPageReturnsURL() throws {
let expectedURL = try XCTUnwrap(URL(string: "/tv/1/reviews?page=2"))
let url = TVShowsEndpoint.reviews(tvShowID: 1, page: 2).path
XCTAssertEqual(url, expectedURL)
}
func testTVShowImagesEndpointReturnsURL() throws {
let languageCode = "en"
let expectedURL = try XCTUnwrap(URL(string: "/tv/1/images?include_image_language=\(languageCode),null"))
let url = TVShowsEndpoint.images(tvShowID: 1, languageCode: languageCode).path
XCTAssertEqual(url, expectedURL)
}
func testTVShowVideosEndpointReturnsURL() throws {
let languageCode = "en"
let expectedURL = try XCTUnwrap(URL(
string: "/tv/1/videos?include_video_language=\(languageCode),null"
))
let url = TVShowsEndpoint.videos(tvShowID: 1, languageCode: languageCode).path
XCTAssertEqual(url, expectedURL)
}
func testTVShowRecommendationsEndpointReturnsURL() throws {
let expectedURL = try XCTUnwrap(URL(string: "/tv/1/recommendations"))
let url = TVShowsEndpoint.recommendations(tvShowID: 1).path
XCTAssertEqual(url, expectedURL)
}
func testTVShowRecommendationsEndpointWithPageReturnsURL() throws {
let expectedURL = try XCTUnwrap(URL(string: "/tv/1/recommendations?page=2"))
let url = TVShowsEndpoint.recommendations(tvShowID: 1, page: 2).path
XCTAssertEqual(url, expectedURL)
}
func testTVShowSimilarEndpointReturnsURL() throws {
let expectedURL = try XCTUnwrap(URL(string: "/tv/1/similar"))
let url = TVShowsEndpoint.similar(tvShowID: 1).path
XCTAssertEqual(url, expectedURL)
}
func testTVShowSimilarEndpointWithPageReturnsURL() throws {
let expectedURL = try XCTUnwrap(URL(string: "/tv/1/similar?page=2"))
let url = TVShowsEndpoint.similar(tvShowID: 1, page: 2).path
XCTAssertEqual(url, expectedURL)
}
func testTVShowPopularEndpointReturnsURL() throws {
let expectedURL = try XCTUnwrap(URL(string: "/tv/popular"))
let url = TVShowsEndpoint.popular().path
XCTAssertEqual(url, expectedURL)
}
func testTVShowPopularEndpointWithPageReturnsURL() throws {
let expectedURL = try XCTUnwrap(URL(string: "/tv/popular?page=1"))
let url = TVShowsEndpoint.popular(page: 1).path
XCTAssertEqual(url, expectedURL)
}
}
|
//
// InformationViewController.swift
// GV24
//
// Created by HuyNguyen on 5/31/17.
// Copyright © 2017 admin. All rights reserved.
//
import UIKit
import IoniconsSwift
import Kingfisher
import Alamofire
class InformationViewController: BaseViewController {
let point = UserDefaultHelper.currentUser?.workInfor?.evaluation_point
@IBOutlet weak var tbInformation: UITableView!
var user:User?
var page: Int = 1
var limit: Int = 10
var list: [Comment] = []
var workTypeList: [WorkType] = []
let imageFirst = Ionicons.androidStarOutline.image(32).maskWithColor(color: UIColor(red: 253/255, green: 179/255, blue: 53/255, alpha: 1))
override func viewDidLoad() {
super.viewDidLoad()
tbInformation.register(UINib(nibName:NibInforCell,bundle:nil), forCellReuseIdentifier: inforCellID)
tbInformation.register(UINib(nibName:NibInfoCommentCell,bundle:nil), forCellReuseIdentifier: infoCommentCellID)
tbInformation.register(UINib(nibName: NibWorkInfoCell, bundle: nil), forCellReuseIdentifier: workInfoCellID)
self.user = UserDefaultHelper.currentUser
//customBarLeftButton()
self.tbInformation.rowHeight = UITableViewAutomaticDimension
self.tbInformation.estimatedRowHeight = 100.0
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(InformationViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
getOwnerComments()
getWorkType()
}
//Calls this function when the tap is recognized.
func dismissKeyboard() {
view.endEditing(true)
}
override func setupViewBase() {
self.title = "Applicantprofile".localize
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
func selectButton() {
//navigationController?.pushViewController(DetailViewController(), animated: true)
}
func setImageAvatar(cell:UITableViewCell,imgView:UIImage) {
let url = URL(string: (user?.image)!)
let data = try? Data(contentsOf: url!)
if let imageData = data {
let image = UIImage(data: imageData)
DispatchQueue.main.async {
cell.imageView?.image = image
}
}
}
/*
/maid/getComment
params: - id: userId
*/
func getOwnerComments() {
guard let id = self.user?.id else {return}
var params:[String:Any] = [:]
params["id"] = "\(id)"
params["page"] = self.page
params["limit"] = self.limit
let headers: HTTPHeaders = ["hbbgvauth": "\(UserDefaultHelper.getToken()!)"]
CommentServices.sharedInstance.getProfileCommentsWith(url: APIPaths().urlGetProfileComments(), param: params, header: headers) { (data, error) in
switch error {
case .Success:
self.list.append(contentsOf: data!)
break
default:
break
}
self.tbInformation.reloadData()
}
}
/* https://yukotest123.herokuapp.com/vi/maid/getAbility
no params
*/
func getWorkType() {
guard let token = UserDefaultHelper.getToken() else {return}
let params: [String:Any] = [:]
let header: HTTPHeaders = ["hbbgvauth":"\(token)"]
HistoryServices.sharedInstance.getWorkAbility(url: APIPaths().urlGetWorkAbility(), param: params, header: header) { (data, err) in
if (self.net?.isReachable)! {
switch err{
case .Success:
if self.page != 1{
self.workTypeList.append(contentsOf: data!)
}else {
self.workTypeList = data!
}
DispatchQueue.main.async {
let indexPath = IndexPath(item: 0, section: 1)
self.tbInformation.reloadRows(at: [indexPath], with: .fade)
}
break
case .EmptyData:
DispatchQueue.main.async {
let alertController = AlertHelper().showAlertError(title: "Announcement".localize, message: "NoDataFound".localize)
self.present(alertController, animated: true, completion: nil)
}
break
default:
self.doTimeoutExpired()
break
}
}else {
self.doNetworkIsDisconnected()
}
}
}
func doTimeoutExpired() {
AlertStandard.sharedInstance.showAlert(controller: self, title: "Announcement".localize, message: "TimeoutExpiredPleaseLoginAgain".localize)
}
func doNetworkIsDisconnected() {
AlertStandard.sharedInstance.showAlert(controller: self, title: "Announcement".localize, message: "NetworkIsLost".localize)
}
func InforCell(cell:InforCell) {
let image = Ionicons.star.image(32).maskWithColor(color: UIColor(red: 253/255, green: 179/255, blue: 53/255, alpha: 1))
guard let tag = point else {return}
for i in cell.btRating!{
if i.tag <= tag {
i.setImage(image, for: .normal)
}else{
i.setImage(imageFirst, for: .normal)
}
}
}
}
extension InformationViewController:UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 2 {
return list.count
}
return 1
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell:InforCell = (tbInformation.dequeueReusableCell(withIdentifier: inforCellID, for: indexPath) as? InforCell)!
InforCell(cell: cell)
if user?.gender == 0 {
cell.lbGender.text = "Girl".localize
}else{
cell.lbGender.text = "Boy".localize
}
let url = URL(string: user!.image!)
if url == nil {
cell.avatar.image = UIImage(named: "avatar")
}else{
DispatchQueue.main.async {
cell.avatar?.kf.setImage(with: url)
}
}
cell.imageProfile.kf.setImage(with: url)
cell.lbName.text = user?.name
cell.lbPhone.text = user?.phone
cell.lbAddress.text = user?.nameAddress
cell.lbAge.text = "\(user?.age ?? 0)"
return cell
}else if indexPath.section == 1{
let cell: WorkInfoCell = tbInformation.dequeueReusableCell(withIdentifier: workInfoCellID, for: indexPath) as! WorkInfoCell
cell.data = workTypeList
cell.priceLabel.text = String().numberFormat(number: UserDefaultHelper.currentUser?.workInfor?.price ?? 0) + " VND" + " / " + "hour".localize
cell.topLabel.text = "WorkCapacity".localize.uppercased()
cell.llbAssessment.text = "Assessment".localize.uppercased()
return cell
}else{
let cell:InfoCommentCell = (tbInformation.dequeueReusableCell(withIdentifier: infoCommentCellID, for: indexPath) as? InfoCommentCell)!
let comment = list[indexPath.row]
let url = URL(string: (comment.fromId?.image)!)
if url == nil {
cell.imageAvatar.image = UIImage(named: "avatar")
}else{
DispatchQueue.main.async {
cell.imageAvatar.kf.setImage(with: url)
}
}
cell.userName.text = comment.fromId?.name
let creatAt = String.convertISODateToString(isoDateStr: comment.createAt!, format: "dd/MM/yyyy")
cell.createAtLabel.text = creatAt
cell.content.allowsEditingTextAttributes = true
cell.content.text = comment.content
cell.workTitle.text = comment.task?.title
return cell
}
}
}
extension InformationViewController:UITableViewDelegate{
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
|
//
// PhotoListViewCell.swift
// Photo Gallery
//
// Created by Andrea on 27/02/2018.
// Copyright © 2018 Andrea Stevanato. All rights reserved.
//
import UIKit
class PhotoListTableViewCell: UITableViewCell {
@IBOutlet weak var mainImageView: UIImageView!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
}
|
//
// EmailValidator.swift
// YourCityEvents
//
// Created by Yaroslav Zarechnyy on 11/15/19.
// Copyright © 2019 Yaroslav Zarechnyy. All rights reserved.
//
import Foundation
class EmailValidator: PValidator {
private static let predicate = NSPredicate(format: "SELF MATCHES %@",
"^[a-z-A-Z-0-9_+-]+(?:\\.[a-z-A-Z-0-9_+-]+)*@(?:[a-z-A-Z-0-9](?:[a-z-A-Z-0-9-_]*[a-z-A-Z-0-9])?\\.)+[a-z-A-Z-0-9](?:[a-z-A-Z-0-9-]*[a-z-A-Z-0-9])?$")
func validate(_ text: String?) -> Bool {
guard let currentText = text else { return false }
guard EmailValidator.predicate.evaluate(with: text) else { return false }
guard !currentText.isEmpty else { return false }
return true
}
}
|
//
// ImageDownloadableModel.swift
// Saturdays
//
// Created by Said Ozcan on 3/4/17.
// Copyright © 2017 Said Ozcan. All rights reserved.
//
import Foundation
protocol ImageDownloadableModel {
var imageURL : URL { get }
}
|
//
// AnyObservable.swift
// APIPlayground
//
// Created by Mai Mai on 4/6/19.
// Copyright © 2019 maimai. All rights reserved.
//
import Foundation
import RxSwift
class AnyObservable<E>: ObservableType {
private let _subscribe: (AnyObserver<E>) -> Disposable
init<O>(_ observer: O) where O : ObservableType, O.E == E {
self._subscribe = observer.subscribe(_:)
}
func subscribe<O>(_ observer: O) -> Disposable where O : ObserverType, O.E == E {
return self._subscribe(observer.asObserver())
}
}
|
//
// CoreDataStack.swift
// HairCare
//
// Created by Taylor Lyles on 8/27/19.
// Copyright © 2019 Taylor Lyles. All rights reserved.
//
//
//import Foundation
//import CoreData
//
//class CoreDataStack {
//
// static let shared = CoreDataStack()
//
// lazy var container: NSPersistentContainer = {
// // Give the container the name of your data model file
// let container = NSPersistentContainer(name: "HairSylist")
//
// container.loadPersistentStores(completionHandler: { (_, error) in
// if let error = error {
// fatalError("Failed to load persistent stores: \(error)")
// }
// })
//
// return container
// }()
//
// // This should help you remember to use the viewContext on the main thread only
// var mainContext: NSManagedObjectContext {
// return container.viewContext
// }
//}
|
//
// DataCell.swift
// App
//
// Created by developer on 06.06.16.
// Copyright © 2016 developer. All rights reserved.
//
import UIKit
class DataCell: UITableViewCell {
var onChange: ((value: AnyObject?, indexPath: NSIndexPath) -> Void)?
var indexPath: NSIndexPath?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func onChange(onChange change: ((value: AnyObject?, indexPath: NSIndexPath) -> Void)?) {
self.onChange = change
}
func updateUI(attribute: Attribute) -> DataCell {
switch attribute.type {
case .String:
if let cell = self as? StringTableViewCell, attribute = attribute as? StringAttribute {
let value = attribute.value as? String
cell.updateUI(attribute.name, value: value)
.cellSetup { cell in
cell.dataTextField.placeholder = attribute.placeholder
}
}
case .Number:
if let cell = self as? NumberTableViewCell, attribute = attribute as? NumberAttribute {
let value = attribute.value as? Int
cell.updateUI(attribute.name, value: value)
.cellSetup { cell in
cell.dataTextField.placeholder = attribute.placeholder
}
}
case .RangeTime:
if let cell = self as? RangeTimeTableViewCell, attribute = attribute as? RangeTimeAttribute {
let value = attribute.value as? RangeTime
cell.updateUI(attribute.name, rangeTime: value)
.cellSetup { cell in
cell.startTime.placeholder = attribute.placeholder
cell.endTime.placeholder = attribute.secondPlaceholder
}
}
case .AccountantType:
if let cell = self as? AccountantTypeTableViewCell, attribute = attribute as? AccountantAttribute {
let value = attribute.value as? Int
cell.updateUI(attribute.name, value: value)
.cellSetup { cell in
cell.dataTextField.placeholder = attribute.placeholder
}
}
}
return self
}
}
extension DataCell: UITextFieldDelegate {
func addToolBar(textField: UITextField) {
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.Default
toolBar.translucent = true
toolBar.tintColor = UIColor(red: 90/255, green: 100/255, blue: 217/255, alpha: 1)
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: #selector(DataCell.donePressed))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
toolBar.setItems([spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true
toolBar.sizeToFit()
textField.delegate = self
textField.inputAccessoryView = toolBar
}
func donePressed() {
self.contentView.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.contentView.endEditing(true)
return true
}
}
|
//
// PullToAddItem.swift
// Hive
//
// Created by Leon Luo on 11/7/17.
// Copyright © 2017 leonluo. All rights reserved.
//
import UIKit
import PullToRefresh
class PullToAddItem: PullToRefresh {
// init(refreshView: UIView, animator: RefreshViewAnimator, position: Position) {
// let height: CGFloat = 100
// refreshView.backgroundColor = UIColor.white
// refreshView.translatesAutoresizingMaskIntoConstraints = false
// refreshView.autoresizingMask = [.flexibleWidth]
// refreshView.frame.size.height = height
//
// super.init(refreshView: refreshView, animator: animator, height: height, position: position)
// }
var pullToAddView: PullToAddView!
override init(refreshView: UIView, animator: RefreshViewAnimator, height: CGFloat, position: Position) {
self.pullToAddView = refreshView as! PullToAddView
super.init(refreshView: refreshView, animator: animator, height: height, position: position)
}
convenience init(at position: Position) {
let height: CGFloat = 100
let view = PullToAddView.init(height: height, iconMaximizeSize: 40)
view.backgroundColor = UIColor.white
let animator = PullToAddAnimator(pullToAddView: view)
self.init(refreshView: view, animator: animator, height: height, position: position)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.