text
stringlengths
8
1.32M
@testable import App import XCTVapor final class UserTests: XCTestCase { let usersName = "Alice" let usersUsername = "alicea" let usersURI = "/api/users/" var app: Application! override func setUpWithError() throws { app = try Application.testable() } override func tearDownWithError() throws { app.shutdown() } func testUsersCanBeRetrievedFromAPI() throws { let user = try User.create( name: usersName, username: usersUsername, on: app.db) _ = try User.create(on: app.db) try app.test(.GET, usersURI, afterResponse: { response in XCTAssertEqual(response.status, .ok) let users = try response.content.decode([User].self) XCTAssertEqual(users.count, 2) XCTAssertEqual(users[0].name, usersName) XCTAssertEqual(users[0].username, usersUsername) XCTAssertEqual(users[0].id, user.id) }) } func testUserCanBeSavedWithAPI() throws { // 1 let user = User(name: usersName, username: usersUsername) // 2 try app.test(.POST, usersURI, beforeRequest: { req in // 3 try req.content.encode(user) }, afterResponse: { response in // 4 let receivedUser = try response.content.decode(User.self) // 5 XCTAssertEqual(receivedUser.name, usersName) XCTAssertEqual(receivedUser.username, usersUsername) XCTAssertNotNil(receivedUser.id) // 6 try app.test(.GET, usersURI, afterResponse: { secondResponse in // 7 let users = try secondResponse.content.decode([User].self) XCTAssertEqual(users.count, 1) XCTAssertEqual(users[0].name, usersName) XCTAssertEqual(users[0].username, usersUsername) XCTAssertEqual(users[0].id, receivedUser.id) }) }) } func testGettingASingleUserFromTheAPI() throws { // 1 let user = try User.create( name: usersName, username: usersUsername, on: app.db) // 2 try app.test(.GET, "\(usersURI)\(user.id!)", afterResponse: { response in let receivedUser = try response.content.decode(User.self) // 3 XCTAssertEqual(receivedUser.name, usersName) XCTAssertEqual(receivedUser.username, usersUsername) XCTAssertEqual(receivedUser.id, user.id) }) } }
// // Matrix.swift // Raytracer // // Created by Drew Ingebretsen on 12/20/14. // Copyright (c) 2014 Drew Ingebretsen. All rights reserved. // import UIKit struct Matrix{ var x:[[Float]] = [ [0.0,0.0,0.0,0.0], [0.0,0.0,0.0,0.0], [0.0,0.0,0.0,0.0], [0.0,0.0,0.0,0.0] ]; static func identityMatrix() -> Matrix{ var m = Matrix(); m.x = [ [1.0,0.0,0.0,0.0], [0.0,1.0,0.0,0.0], [0.0,0.0,1.0,0.0], [0.0,0.0,0.0,1.0] ]; return m; } static func translate(_ vector:Vector3D) -> Matrix{ var returnMatrix = identityMatrix(); returnMatrix.x[0][3] = vector.x; returnMatrix.x[1][3] = vector.y; returnMatrix.x[2][3] = vector.z; return returnMatrix; } static func rotate(_ axis:Vector3D, angle:Float) -> Matrix{ let axisN:Vector3D = axis.normalized(); var returnMatrix = Matrix(); let x:Float = axisN.x; let y:Float = axisN.y; let z:Float = axisN.z; let cosine:Float = cos(angle); let sine:Float = sin(angle); let t:Float = 1.0 - cosine; returnMatrix.x[0][0] = t * x * x + cosine returnMatrix.x[1][0] = t * x * y - sine * z; returnMatrix.x[2][0] = t * x * z + sine * y; returnMatrix.x[3][0] = 0.0; returnMatrix.x[0][1] = t * x * y + sine * z; returnMatrix.x[1][1] = t * y * y + cosine; returnMatrix.x[2][1] = t * y * z - sine * x; returnMatrix.x[3][1] = 0.0; returnMatrix.x[0][2] = t * x * z - sine * y; returnMatrix.x[1][2] = t * y * z + sine * x; returnMatrix.x[2][2] = t * z * z + cosine; returnMatrix.x[3][2] = 0.0; returnMatrix.x[0][3] = 0.0; returnMatrix.x[1][3] = 0.0; returnMatrix.x[2][3] = 0.0; returnMatrix.x[3][3] = 1.0; return returnMatrix; } static func rotateX(_ angle:Float) -> Matrix { var returnMatrix = identityMatrix(); let cosine:Float = cos(angle); let sine:Float = sin(angle); returnMatrix.x[1][1] = cosine; returnMatrix.x[1][2] = -sine; returnMatrix.x[2][1] = sine; returnMatrix.x[2][2] = cosine; return returnMatrix; } static func rotateY(_ angle:Float) -> Matrix { var returnMatrix = identityMatrix(); let cosine:Float = cos(angle); let sine:Float = sin(angle); returnMatrix.x[0][0] = cosine; returnMatrix.x[0][2] = sine; returnMatrix.x[2][0] = -sine; returnMatrix.x[2][2] = cosine; return returnMatrix } static func rotateZ(_ angle:Float) -> Matrix { var returnMatrix = identityMatrix(); let cosine:Float = cos(angle); let sine:Float = sin(angle); returnMatrix.x[0][0] = cosine; returnMatrix.x[0][1] = -sine; returnMatrix.x[1][0] = sine; returnMatrix.x[1][1] = cosine; return returnMatrix; } static func transformPoint(_ left:Matrix, right:Vector3D) -> Vector3D { return left * right; } static func transformVector(_ left:Matrix, right:Vector3D) -> Vector3D{ var x = (right.x * left.x[0][0] + right.y * left.x[0][1] + right.z * left.x[0][2]); x += left.x[0][3]; var y = (right.x * left.x[1][0] + right.y * left.x[1][1] + right.z * left.x[1][2]); y += left.x[1][3] var z = (right.x * left.x[2][0] + right.y * left.x[2][1] + right.z * left.x[2][2]); z += left.x[2][3] var t = (right.x * left.x[3][0] + right.y * left.x[3][1] + right.z * left.x[3][2]); t += left.x[3][3] let returnVector = Vector3D(x:x, y:y, z:z); return returnVector / t; } } func * (left: Matrix, right: Matrix) -> Matrix { var m = Matrix(); for i in 0...3{ for j in 0...3{ var subt:Float = 0; for k in 0...3{ subt += left.x[i][k] * right.x[k][j]; m.x[i][j] = subt; } } } return m; } func * (left: Vector3D, right: Matrix) -> Vector3D { return right * left; } func * (left: Matrix, right: Vector3D) -> Vector3D { var x:Float x = (right.x * left.x[0][0]) x += (right.y * left.x[0][1]) x += (right.z * left.x[0][2]) x += left.x[0][3]; var y:Float; y = (right.x * left.x[1][0]) y += (right.y * left.x[1][1]) y += (right.z * left.x[1][2]) y += left.x[1][3]; var z:Float; z = (right.x * left.x[2][0]) z += (right.y * left.x[2][1]) z += (right.z * left.x[2][2]) z += left.x[2][3]; var t:Float; t = (right.x * left.x[3][0]) t += (right.y * left.x[3][1]) t += (right.z * left.x[3][2]) t += left.x[3][3]; var returnVector:Vector3D = Vector3D(x:x,y:y,z:z); returnVector = returnVector / t; return returnVector; }
/** * https://github.com/tadija/AEXML * Copyright (c) Marko Tadić 2014-2019 * Licensed under the MIT license. See LICENSE file. */ import Foundation /// A type representing error value that can be thrown or inside `error` property of `AEXMLElement`. public enum AEXMLError: Error { /// This will be inside `error` property of `AEXMLElement` when subscript is used for not-existing element. case elementNotFound(String) /// This will be inside `error` property of `AEXMLDocument` when there is no root element. case rootElementMissing /// `AEXMLDocument` can throw this error on `init` or `loadXMLData` if parsing with `XMLParser` was not successful. case parsingFailed /// This can be thrown when attempting to get value for an element within `AEXMLElement`. case valueNotFound(String) } // MARK: - Equatable extension AEXMLError: Equatable { public static func == (lhs: AEXMLError, rhs: AEXMLError) -> Bool { switch (lhs, rhs) { case (.rootElementMissing, .rootElementMissing), (.parsingFailed, .parsingFailed): return true case (.elementNotFound(let lhsVal), .elementNotFound(let rhsVal)): return lhsVal == rhsVal default: return false } } }
// // CSVWriter.swift // TelemetryRecorder // // Created by Craig Miller on 16/11/2015. // Copyright © 2015 CMSoftware. All rights reserved. // import Foundation public class CSVWriter { private let out : NSOutputStream private let separator : [UInt8] private let newLine : [UInt8] public init(path : String) { separator = [UInt8](",".utf8) newLine = [UInt8]("\n".utf8) out = NSOutputStream(toFileAtPath: path, append: true)! out.open() } deinit { out.close() } public func writeLine(items : [String]) { for i in 0..<items.count { if i > 0 { out.write(separator, maxLength: separator.count) } let item = items[i] let bytes = [UInt8](item.utf8) if bytes.count > 0 { out.write(bytes, maxLength: bytes.count) } } let writtenBytes = out.write(newLine, maxLength: newLine.count) debugPrint("Written: \(writtenBytes)") debugPrint(items, separator: ", ") } public func writeLine(items : String...) { for i in 0..<items.count { if i > 0 { out.write(separator, maxLength: separator.count) } let item = items[i] let bytes = [UInt8](item.utf8) if bytes.count > 0 { out.write(bytes, maxLength: bytes.count) } } out.write(newLine, maxLength: newLine.count) } }
// // KeyspaceSchema.swift // scale // // Created by Adrian Herridge on 17/04/2017. // // import Foundation import SWSQLite class KeyspaceSchema : DataObject, DataObjectProtocol { var keyspace: String? var version: String? var change: String? override func populateFromRecord(_ record: Record) { self.keyspace = record["keyspace"]?.asString() self.version = record["version"]?.asString() self.change = record["change"]?.asString() } override class func GetTables() -> [Action] { return [ Action(createTable: "KeyspaceSchema"), Action(addColumn: "keyspace", type: .String, table: "KeyspaceSchema"), Action(addColumn: "version", type: .String, table: "KeyspaceSchema"), Action(addColumn: "change", type: .String, table: "KeyspaceSchema") ] } class func ToCollection(_ records: [Record]) -> [KeyspaceSchema] { var results: [KeyspaceSchema] = [] for record in records { results.append(KeyspaceSchema(record)) } return results } }
// // RXProgressHUD.swift // RXProgressHUD // // Created by ZP on 16/3/21. // Copyright © 2016年 ZP. All rights reserved. // import UIKit protocol RXHUDAnimating { func startAnimation() func stopAnimation() } public class RXHUDSuccessView: RXHUDSquareBaseView, RXHUDAnimating { var checkmarkShapeLayer: CAShapeLayer = { let checkmarkPath = UIBezierPath() checkmarkPath.moveToPoint(CGPointMake(8.0, 12)) checkmarkPath.addLineToPoint(CGPointMake(15, 20)) checkmarkPath.addLineToPoint(CGPointMake(36, 0.0)) let layer = CAShapeLayer() layer.frame = CGRectMake(3.0, 3.0, 40, 25) layer.path = checkmarkPath.CGPath layer.fillMode = kCAFillModeForwards layer.lineCap = kCALineCapRound layer.lineJoin = kCALineJoinRound layer.fillColor = nil layer.strokeColor = RXHUDHelper.sharedHUD.strokeColor.CGColor layer.lineWidth = 2.0 return layer }() public init(title: String? = nil, subtitle: String? = nil) { super.init(title: title, subtitle: subtitle) layer.addSublayer(checkmarkShapeLayer) checkmarkShapeLayer.position = layer.position } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) layer.addSublayer(checkmarkShapeLayer) checkmarkShapeLayer.position = layer.position } public func startAnimation() { let checkmarkStrokeAnimation = CAKeyframeAnimation(keyPath:"strokeEnd") checkmarkStrokeAnimation.values = [0, 1] checkmarkStrokeAnimation.keyTimes = [0, 1] checkmarkStrokeAnimation.duration = 0.35 checkmarkShapeLayer.addAnimation(checkmarkStrokeAnimation, forKey:"checkmarkStrokeAnim") } public func stopAnimation() { checkmarkShapeLayer.removeAnimationForKey("checkmarkStrokeAnimation") } } public class RXHUDTextView: UIView ,RXHUDAnimating{ public init(text: String!) { let size : CGSize = RXHUDTextView.getTextRectSize(text, font: UIFont.systemFontOfSize(15)) super.init(frame: CGRectMake(0, 0, size.width + 20, size.height + 20)) commonInit(text) } class func getTextRectSize(text:NSString,font:UIFont) -> CGSize { let size = CGSizeMake(200, UIScreen.mainScreen().bounds.height) let attributes = [NSFontAttributeName: font] let option = NSStringDrawingOptions.UsesLineFragmentOrigin let rect:CGRect = text.boundingRectWithSize(size, options: option, attributes: attributes, context: nil) return rect.size; } convenience init() { self.init() self.hidden = true } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit("") } func commonInit(text: String?) { titleLabel.text = text addSubview(titleLabel) let padding: CGFloat = 10.0 titleLabel.frame = CGRectInset(bounds, padding, 0) } public let titleLabel: UILabel = { let label = UILabel() label.textAlignment = .Center label.font = UIFont.systemFontOfSize(15) label.textColor = RXHUDHelper.sharedHUD.strokeColor label.adjustsFontSizeToFitWidth = true label.numberOfLines = 0 return label }() public func startAnimation() {} public func stopAnimation() {} } public final class RXHUDSystemActivityIndicatorView: RXHUDSquareBaseView, RXHUDAnimating { public init() { super.init(frame: RXHUDSquareBaseView.defaultSquareBaseViewFrame) commonInit() } public override init(frame: CGRect) { super.init(frame: frame) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit () { backgroundColor = UIColor.clearColor() alpha = 0.8 self.addSubview(activityIndicatorView) } public override func layoutSubviews() { super.layoutSubviews() activityIndicatorView.center = self.center } let activityIndicatorView: UIActivityIndicatorView = { let activity = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge) activity.color = RXHUDHelper.sharedHUD.strokeColor return activity }() func startAnimation() { activityIndicatorView.startAnimating() } public func stopAnimation() { activityIndicatorView.startAnimating() } } public class RXHUDErrorView: RXHUDSquareBaseView, RXHUDAnimating { var dashOneLayer = RXHUDErrorView.generateDashLayer(true) var dashTwoLayer = RXHUDErrorView.generateDashLayer(false) class func generateDashLayer(upgrade: Bool = false) -> CAShapeLayer { let dash = CAShapeLayer() dash.frame = CGRectMake(0.0, 0.0, 88.0, 88.0) dash.path = { let rate :CGFloat = 0.35 let path = UIBezierPath() if upgrade { path.moveToPoint(CGPointMake(88.0 * rate, 88.0 * rate)) path.addLineToPoint(CGPointMake(88.0 * (1-rate), 88.0 * (1-rate))) } else { path.moveToPoint(CGPointMake(88.0 * (1-rate), 88.0 * rate)) path.addLineToPoint(CGPointMake(88.0 * rate, 88.0 * (1-rate))) } return path.CGPath }() dash.lineCap = kCALineCapRound dash.lineJoin = kCALineJoinRound dash.fillColor = nil dash.strokeColor = RXHUDHelper.sharedHUD.strokeColor.CGColor dash.lineWidth = 2 dash.fillMode = kCAFillModeForwards return dash } public init(title: String? = nil, subtitle: String? = nil) { super.init(title: title, subtitle: subtitle) layer.addSublayer(dashOneLayer) layer.addSublayer(dashTwoLayer) dashOneLayer.position = layer.position dashTwoLayer.position = layer.position } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) layer.addSublayer(dashOneLayer) layer.addSublayer(dashTwoLayer) dashOneLayer.position = layer.position dashTwoLayer.position = layer.position } public func startAnimation() { let checkmarkStrokeAnimation = CAKeyframeAnimation(keyPath:"strokeEnd") checkmarkStrokeAnimation.values = [0, 1] checkmarkStrokeAnimation.keyTimes = [0, 1] checkmarkStrokeAnimation.duration = 0.25 dashTwoLayer.strokeEnd = 0.0 checkmarkStrokeAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) dashOneLayer.addAnimation(checkmarkStrokeAnimation, forKey:"checkmarkStrokeAnim") delay(0.25) { () -> Void in self.dashTwoLayer.addAnimation(checkmarkStrokeAnimation, forKey:"checkmarkStrokeAnim") } delay(0.45) { () -> Void in self.dashTwoLayer.strokeEnd = 1.0 } } public func stopAnimation() { dashOneLayer.removeAnimationForKey("checkmarkStrokeAnimation") dashTwoLayer.removeAnimationForKey("checkmarkStrokeAnimation") } } public class RXHUDRotatingImageView: RXHUDSquareBaseView, RXHUDAnimating { func startAnimation() { imageView.layer.addAnimation(RXHUDAnimation.continuousRotation, forKey: "progressAnimation") } func stopAnimation() { } } public class RXHUDProgressView: RXHUDSquareBaseView, RXHUDAnimating { public init(title: String? = nil, subtitle: String? = nil) { super.init(image: RXHUDAssets.progressActivityImage, title: title, subtitle: subtitle) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func startAnimation() { imageView.layer.addAnimation(RXHUDAnimation.discreteRotation, forKey: "progressAnimation") } func stopAnimation() { } } public final class RXHUDAnimation { static let discreteRotation: CAAnimation = { let animation = CAKeyframeAnimation(keyPath: "transform.rotation.z") animation.values = [ NSNumber(float: 0.0), NSNumber(float: 1.0 * Float(M_PI) / 6.0), NSNumber(float: 2.0 * Float(M_PI) / 6.0), NSNumber(float: 3.0 * Float(M_PI) / 6.0), NSNumber(float: 4.0 * Float(M_PI) / 6.0), NSNumber(float: 5.0 * Float(M_PI) / 6.0), NSNumber(float: 6.0 * Float(M_PI) / 6.0), NSNumber(float: 7.0 * Float(M_PI) / 6.0), NSNumber(float: 8.0 * Float(M_PI) / 6.0), NSNumber(float: 9.0 * Float(M_PI) / 6.0), NSNumber(float: 10.0 * Float(M_PI) / 6.0), NSNumber(float: 11.0 * Float(M_PI) / 6.0), NSNumber(float: 2.0 * Float(M_PI)) ] animation.keyTimes = [ NSNumber(float: 0.0), NSNumber(float: 1.0 / 12.0), NSNumber(float: 2.0 / 12.0), NSNumber(float: 3.0 / 12.0), NSNumber(float: 4.0 / 12.0), NSNumber(float: 5.0 / 12.0), NSNumber(float: 0.5), NSNumber(float: 7.0 / 12.0), NSNumber(float: 8.0 / 12.0), NSNumber(float: 9.0 / 12.0), NSNumber(float: 10.0 / 12.0), NSNumber(float: 11.0 / 12.0), NSNumber(float: 1.0) ] animation.duration = 1.2 animation.calculationMode = "discrete" animation.repeatCount = Float(INT_MAX) return animation }() static let continuousRotation: CAAnimation = { let animation = CABasicAnimation(keyPath: "transform.rotation.z") animation.fromValue = 0 animation.toValue = 2.0 * M_PI animation.duration = 1.2 animation.repeatCount = Float(INT_MAX) return animation }() } public class RXHUDSquareBaseView: UIView { static let defaultSquareBaseViewFrame = CGRect(origin: CGPointZero, size: CGSize(width: 100.0, height: 100.0)) public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public init(image: UIImage? = nil, title: String? = nil, subtitle: String? = nil) { super.init(frame: RXHUDSquareBaseView.defaultSquareBaseViewFrame) self.imageView.image = image titleLabel.text = title subtitleLabel.text = subtitle addSubview(imageView) addSubview(titleLabel) addSubview(subtitleLabel) } public lazy var imageView: UIImageView = { let imageView = UIImageView() // imageView.alpha = 0.85 imageView.clipsToBounds = true imageView.contentMode = .ScaleToFill return imageView }() public let titleLabel: UILabel = { let label = UILabel() label.textAlignment = .Center label.font = UIFont.systemFontOfSize(15.0) label.textColor = RXHUDHelper.sharedHUD.strokeColor return label }() public let subtitleLabel: UILabel = { let label = UILabel() label.textAlignment = .Center label.font = UIFont.systemFontOfSize(14.0) label.textColor = RXHUDHelper.sharedHUD.strokeColor label.adjustsFontSizeToFitWidth = true label.numberOfLines = 2 return label }() public override func layoutSubviews() { super.layoutSubviews() let viewWidth = bounds.size.width let viewHeight = bounds.size.height // let halfHeight = CGFloat(ceilf(CFloat(viewHeight / 2.0))) let quarterHeight = CGFloat(ceilf(CFloat(viewHeight / 4.0))) let threeQuarterHeight = CGFloat(ceilf(CFloat(viewHeight / 4.0 * 3.0))) titleLabel.frame = CGRect(origin: CGPointZero, size: CGSize(width: viewWidth, height: quarterHeight)) imageView.frame = CGRect(origin: CGPoint(x:(viewWidth - 40) * 0.5, y:(viewHeight - 40) * 0.5), size: CGSize(width: 40, height: 40)) subtitleLabel.frame = CGRect(origin: CGPoint(x:0.0, y:threeQuarterHeight - 5), size: CGSize(width: viewWidth, height: quarterHeight)) } deinit { print("RXHUDSquareBaseView:") } } public class RXHUDAssets: NSObject { public class var crossImage: UIImage { let iamge : UIImage = RXHUDAssets.bundledImage(named: "progress") if RXHUDHelper.sharedHUD.style == .Dark { return RXHUDAssets.changeColorWithImage(iamge, color: UIColor.whiteColor()) }else { return iamge } } public class var checkmarkImage: UIImage { let iamge : UIImage = RXHUDAssets.bundledImage(named: "checkmark") if RXHUDHelper.sharedHUD.style == .Dark { return RXHUDAssets.changeColorWithImage(iamge, color: UIColor.whiteColor()) }else { return iamge } } public class var progressActivityImage: UIImage { let iamge : UIImage = RXHUDAssets.bundledImage(named: "progress_activity") if RXHUDHelper.sharedHUD.style == .Dark { return RXHUDAssets.changeColorWithImage(iamge, color: UIColor.whiteColor()) }else { return iamge } } public class var progressCircularImage: UIImage { let iamge : UIImage = RXHUDAssets.bundledImage(named: "progress_circular") if RXHUDHelper.sharedHUD.style == .Dark { return RXHUDAssets.changeColorWithImage(iamge, color: UIColor.whiteColor()) }else { return iamge } } internal class func bundledImage(named name: String) -> UIImage { let bundle = NSBundle(forClass: RXHUDAssets.self) let image = UIImage(named: name, inBundle:bundle, compatibleWithTraitCollection:nil) if let image = image { return image } return UIImage() } class func changeColorWithImage(currentImg: UIImage,color:UIColor) -> UIImage { if let image : UIImage = currentImg { let rect = CGRectMake(0.0, 0.0, image.size.width, image.size.height) UIGraphicsBeginImageContextWithOptions(rect.size, false, image.scale); let c = UIGraphicsGetCurrentContext() image.drawInRect(rect) CGContextSetFillColorWithColor(c,color.CGColor) CGContextSetBlendMode(c, .SourceAtop) CGContextFillRect(c, rect) let tintedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext() return tintedImage } else { return UIImage() } } }
// // StartScene.swift // Skating Friends // // Created by Jake Oscar Te Lem on 6/10/18. // Copyright © 2018 Jake Oscar Te Lem. All rights reserved. // import SpriteKit import GameplayKit class StartScene: SKScene { let swipeRightRec = UISwipeGestureRecognizer() let swipeLeftRec = UISwipeGestureRecognizer() let swipeUpRec = UISwipeGestureRecognizer() let swipeDownRec = UISwipeGestureRecognizer() var play : SKLabelNode? var seeRecords : SKLabelNode? var shop : SKLabelNode? override func didMove(to view: SKView) { if let label : SKLabelNode = self.childNode(withName: "Play") as? SKLabelNode { play = label } if let label : SKLabelNode = self.childNode(withName: "High Score") as? SKLabelNode { seeRecords = label } if let label : SKLabelNode = self.childNode(withName: "Shop") as? SKLabelNode { shop = label } swipeRightRec.addTarget(self, action: #selector(StartScene.swipedRight)) swipeRightRec.direction = .right self.view!.addGestureRecognizer(swipeRightRec) swipeLeftRec.addTarget(self, action: #selector(StartScene.swipedLeft)) swipeLeftRec.direction = .left self.view!.addGestureRecognizer(swipeLeftRec) swipeDownRec.addTarget(self, action: #selector(StartScene.swipedDown)) swipeDownRec.direction = .down self.view!.addGestureRecognizer(swipeDownRec) swipeUpRec.addTarget(self, action: #selector(StartScene.swipedUp)) swipeUpRec.direction = .up self.view!.addGestureRecognizer(swipeUpRec) } @objc func swipedRight() { //print("right") } @objc func swipedLeft() { //print("lft") } @objc func swipedUp() { //print("up") let gameScene = SKScene(fileNamed: "GameScene") gameScene?.scaleMode = SKSceneScaleMode.aspectFill self.scene?.view?.presentScene(gameScene!, transition: SKTransition.flipVertical(withDuration: 5)) /*print("up") let gameScene = GameScene() gameScene.scaleMode = SKSceneScaleMode.aspectFill gameScene.thePlayer = Catoko() self.scene?.view?.presentScene(gameScene, transition: SKTransition.flipVertical(withDuration: 5)) */ } @objc func swipedDown() { // print("down") } deinit { print("deinit startscene") } func touchDown(atPoint pos : CGPoint) { //print("down") if play!.contains(pos) { let charScene = SKScene(fileNamed: "CharacterScene") charScene?.scaleMode = SKSceneScaleMode.aspectFill self.scene?.view?.presentScene(charScene!) } if seeRecords!.contains(pos) { let recordScene = SKScene(fileNamed: "RecordScene") recordScene?.scaleMode = SKSceneScaleMode.aspectFill self.scene?.view?.presentScene(recordScene!) } if shop!.contains(pos) { let recordScene = SKScene(fileNamed: "ShopScene") recordScene?.scaleMode = SKSceneScaleMode.aspectFill self.scene?.view?.presentScene(recordScene!) } } func touchMoved(toPoint pos : CGPoint) { } func touchUp(atPoint pos : CGPoint) { } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchDown(atPoint: t.location(in: self)) } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchMoved(toPoint: t.location(in: self)) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchUp(atPoint: t.location(in: self)) } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchUp(atPoint: t.location(in: self)) } } override func update(_ currentTime: TimeInterval) { } }
// // ViewController.swift // MyWifi // // Created by sqluo on 2017/1/11. // Copyright © 2017年 sqluo. All rights reserved. // import UIKit import SystemConfiguration import CoreTelephony /** 1.https://developer.apple.com/library/content/samplecode/Reachability/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007324-Intro-DontLinkElementID_2 下载demo 2.把里边的 Reachability.h 跟 Reachability.m 导入工程 3.导入类 #import "Reachability.h" 4.导入 oc版: #import <CoreTelephony/CTCarrier.h> #import <CoreTelephony/CTTelephonyNetworkInfo.h> swift版: import SystemConfiguration import CoreTelephony 5.把 NetworkConnectType 导入至工程 6.调用 let type = NetworkConnectType.type */ class NetworkConnectType { public class var type: String{ return NetworkConnectType.getNetconnType().str } fileprivate enum NetconnType { case none //没有网络 case wifi //wifi //自带网络 case gps //GPS case g2 //2G case g3 //3G case g35 //3.5G case hrpd //HRPD case g4 //4G var str:String{ switch self { case .none: return "没有网络" case .wifi: return "wifi" case .gps: return "GPS" case .g2: return "2G" case .g3: return "3G" case .g35: return "3.5G" case .hrpd: return "HRPD" case .g4: return "4G" } } } fileprivate class func getNetconnType() ->NetconnType{ let reach = Reachability(hostName: "www.apple.com") switch reach!.currentReachabilityStatus() { case NetworkStatus(rawValue: 0): return .none case NetworkStatus(rawValue: 1): return .wifi case NetworkStatus(rawValue: 2): let info = CTTelephonyNetworkInfo() if let currentStatus = info.currentRadioAccessTechnology{ switch currentStatus { case CTRadioAccessTechnologyGPRS: return .gps case CTRadioAccessTechnologyEdge: return .g2 case CTRadioAccessTechnologyWCDMA: return .g3 case CTRadioAccessTechnologyHSDPA: return .g35 case CTRadioAccessTechnologyHSUPA: return .g35 case CTRadioAccessTechnologyCDMA1x: return .g2 case CTRadioAccessTechnologyCDMAEVDORevB,CTRadioAccessTechnologyCDMAEVDORev0,CTRadioAccessTechnologyCDMAEVDORevB: return .g3 case CTRadioAccessTechnologyeHRPD: return .hrpd case CTRadioAccessTechnologyLTE: return .g4 default: return .none } } default: break } return .none } } //调用 class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let type = NetworkConnectType.type print(type) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Intents import Foundation // @available(iOS, introduced: 10.0) // @available(OSX, introduced: 10.12) extension INIntentErrorCode : _BridgedNSError { public static var _nsErrorDomain: String { return INIntentErrorDomain } }
import Foundation extension String { func toURL(addPercentEncoding: Bool = false) -> URL? { if addPercentEncoding { return URL.percentEncoded(string: self) } else { return URL(string: self) } } } extension URL { init?(string: String?) { guard let string = string else { return nil } self.init(string: string) } static func percentEncoded(string: String?) -> URL? { self.init(string: string?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)) } }
// // SKTableViewCell.swift // AutoLayoutDemo // // Created by 董知樾 on 2017/3/28. // Copyright © 2017年 董知樾. All rights reserved. // import UIKit class SKTableViewCell: UITableViewCell { var model : SKTableViewCellModel! { didSet { titleLabel.text = model.title authorLabel.text = model.author contentLabel.numberOfLines = model.isExpand ? 0 : 3 contentLabel.text = model.content self.layoutIfNeeded() } } var titleLabel = UILabel() var contentLabel = UILabel() var authorLabel = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none titleLabel.backgroundColor = UIColor.hexValue(0xf8f8f8) titleLabel.textColor = UIColor.hexValue(0x333333) contentView.addSubview(titleLabel) titleLabel.font = UIFont.systemFont(ofSize: 14) titleLabel.snp.makeConstraints { (make) in make.top.equalTo(12) make.centerX.equalTo(contentView) } authorLabel.backgroundColor = UIColor.hexValue(0xf8f8f8) authorLabel.textColor = UIColor.hexValue(0x666666) contentView.addSubview(authorLabel) authorLabel.font = UIFont.systemFont(ofSize: 10) authorLabel.snp.makeConstraints { (make) in make.leading.equalTo(titleLabel.snp.trailing).offset(12) make.top.equalTo(titleLabel.snp.bottom).offset(2) } contentLabel.backgroundColor = UIColor.hexValue(0xf8f8f8) contentLabel.textColor = UIColor.hexValue(0x666666) contentView.addSubview(contentLabel) contentLabel.font = UIFont.systemFont(ofSize: 12) contentLabel.lineBreakMode = .byTruncatingTail contentLabel.numberOfLines = 3 contentLabel.snp.makeConstraints { (make) in make.top.equalTo(authorLabel.snp.bottom).offset(2) make.leading.equalTo(12) make.bottom.trailing.equalTo(-12) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
// // ViewController.swift // SwiftEverlive // // Created by Tony on 21/09/2014. // Copyright (c) 2014 dobrev. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let myApiKey:NSString = "YOUR_API_KEY" Everlive.setApplicationKey(myApiKey) // create an activity var myActivity = Activities() // curently we need to declare the models in Objective-C but can use them as in Swift. Data models created with Swift are not properly mapped to the server entities myActivity.text = "Now coding in Swift" var ds:EVDataStore = EVDataStore.sharedInstance() as EVDataStore ds.create(myActivity) { (result:Bool, error:NSError!) -> Void in if(result) { println("Success") } else { println("Failed to create activity: " + error.domain) } } // retrieve all activities Activities.fetchAll {(activities:Array!, error:NSError!) -> Void in if(error != nil) { println("Failed to retrieve activities: " + error.domain) } else { for item in activities { var activity = item as Activities println("Activity's text: '\(activity.text)', Created at \(activity.createdAt)") } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // Copyright © 2017 Rosberry. All rights reserved. // import UIKit /// Base row item protocol for implementing string/view representable row items. /// /// - note: You shouldn't directly use this protocol. Use `RowStringItemProtocol` and `RowViewItemProtocol` instead. public protocol RowItemProtocol { /// Called by the picker view when the user selects a row in a component. func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) } public extension RowItemProtocol { func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { } }
// // FTPageViewController.swift // FTPageViewController // // Created by liufengting on 2018/8/7. // Copyright © 2018年 liufengting. All rights reserved. // import UIKit open class FTPageViewController: UIPageViewController, UIPageViewControllerDelegate, UIPageViewControllerDataSource { public var currentIndex: NSInteger = 0 { didSet { self.reload() } } public var subViewControllers: Array<UIViewController> = [] { didSet { self.reload() } } public override init(transitionStyle style: UIPageViewControllerTransitionStyle, navigationOrientation: UIPageViewControllerNavigationOrientation, options: [String : Any]? = nil) { super.init(transitionStyle: style, navigationOrientation: navigationOrientation, options: options) self.setup() } required public init?(coder: NSCoder) { super.init(coder: coder) self.setup() } public func setup() { self.view.backgroundColor = UIColor.white self.delegate = self self.dataSource = self } override open func viewDidLoad() { super.viewDidLoad() } public func reload() { if self.subViewControllers.count > 0 && self.currentIndex <= self.subViewControllers.count - 1 { let VC : UIViewController = self.subViewControllers[self.currentIndex] self.setViewControllers([VC], direction: .forward, animated: false) { (completion) in } } } // MARK: - UIPageViewControllerDelegate, UIPageViewControllerDataSource public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { let index = self.subViewControllers.firstIndex(of: viewController) return (index == 0 || index == NSNotFound || index == nil) ? nil : self.subViewControllers[index!-1]; } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { let index = self.subViewControllers.firstIndex(of: viewController) return (index == 0 || index == NSNotFound || index == nil || index! >= self.subViewControllers.count - 1) ? nil : self.subViewControllers[index!+1]; } }
//// //// PaymentOptionsViewController.swift //// tpllifev1 //// //// Created by IMac on 04/03/2019. //// Copyright © 2019 TPL Insurance. All rights reserved. //// // import UIKit //import Alamofire class PaymentOptionsViewController: SecondaryViewController{ } //import UIKit //import Alamofire // //class PaymentOptionsViewController: SecondaryViewController , UITableViewDelegate , UITableViewDataSource { // // var apiHandlerHome = paymentApiHelper() // var numberTextfieldFromSimSim: UITextField? // var simsimOtpTextfield: UITextField? // var numberTextfieldFromJazzCash: UITextField? // let mobileNumber = UserDefaults.standard.object(forKey: TIConstant.userMobileNoKey) as? String // let mobileNumberPass = UserDefaults.standard.object(forKey: TIConstant.userMobileNoPasscode) as? String // var otpText: String? // // func intializeVariableForTravel(){ // // var apiTravel: travelInsuranceDataHandler? // } // // // @IBAction func submitAction(_ sender: UIButton) { // // if isTravelPager!{ // // if isPaymentMethod == false && isPayThroughSimSim == false && isPayThroughJazzcash == false{ // self.view.makeToast("Please select one mode.") // }else if isPaymentMethod && isPayThroughSimSim && isPayThroughJazzcash{ // self.view.makeToast("Please select anyone mode.") // }else if isPaymentMethod{ // if isHomePager ?? false{ // let controller = self.storyboard?.instantiateViewController(withIdentifier: "HIWebKitViewController") as! HIWebKitViewController // // controller.myurl = "https://customer.tplinsurance.com:444/PaymentModel/CustomerDetail.aspx?Type=Home&SalesFormNo=\("result" ?? "")" // print("url passed is: \(controller.myurl)") // self.navigationController?.pushViewController(controller, animated: true) // // }else if isTravelPager ?? false{ // let controller = self.storyboard?.instantiateViewController(withIdentifier: "HIWebKitViewController") as! HIWebKitViewController // // controller.myurl = "https://customer.tplinsurance.com:444/PaymentModel/CustomerDetail.aspx?Type=Travel&SalesFormNo=\(self.apiTravel?.result![0].OrderID ?? "")" // print("url passed is: \(controller.myurl)") // self.navigationController?.pushViewController(controller, animated: true) // // }else{ // self.view.makeToast("Please select which domain") // } // // }else if isPayThroughSimSim{ // if numberTextfieldFromSimSim?.text != nil || numberTextfieldFromSimSim?.text != ""{ // finjaAuthTravel() // // }else{ // self.view.makeToast("Please write your number") // } // // }else if isPayThroughJazzcash{ // if numberTextfieldFromJazzCash?.text != nil || numberTextfieldFromJazzCash?.text != ""{ // JazzCashPayment(PolicyNumber: self.apiTravel!.result![0].OrderID ?? "", Amount: self.apiTravel!.result![0].Premium ?? "", Key: "test121", PayMobileNo: numberTextfieldFromJazzCash?.text ?? "-", Description: "ios description app") // // }else{ // self.view.makeToast("Please write your number") // } // // } // }else if isHomePager!{ // if isPaymentMethod == false && isPayThroughSimSim == false && isPayThroughJazzcash == false{ // self.view.makeToast("Please select one mode.") // }else if isPaymentMethod && isPayThroughSimSim && isPayThroughJazzcash{ // self.view.makeToast("Please select anyone mode.") // }else if isPaymentMethod{ // // let controller = self.storyboard?.instantiateViewController(withIdentifier: "HIWebKitViewController") as! HIWebKitViewController // // controller.myurl = "https://customer.tplinsurance.com:444/PaymentModel/CustomerDetail.aspx?Type=Home&SalesFormNo=\("result" ?? "")" // print("url passed is: \(controller.myurl)") // self.navigationController?.pushViewController(controller, animated: true) // // }else if isPayThroughSimSim{ // if numberTextfieldFromSimSim?.text != nil || numberTextfieldFromSimSim?.text != ""{ // finjaAuthHome() // // }else{ // self.view.makeToast("Please write your number") // } // // }else if isPayThroughJazzcash{ // if numberTextfieldFromJazzCash?.text != nil || numberTextfieldFromJazzCash?.text != ""{ // JazzCashPayment(PolicyNumber: self.apiHome?.HIresult![0].OrderID ?? "", Amount: self.apiHome?.HIresult![0].Premium ?? "", Key: "test121", PayMobileNo: numberTextfieldFromJazzCash?.text ?? "-", Description: "ios description app") // // }else{ // self.view.makeToast("Please write your number") // } // // } // } // // // } // @IBOutlet weak var tableView: UITableView! // var api: Any? // // var paymentApiHelper = paymentApiHelper() // var apiHome: HomeInsuranceDataHandler? // var apiTravel: travelInsuranceDataHandler? // var myurl : String? // var isTravelPager: Bool? // var isHomePager: Bool? // // private var isPaymentMethod: Bool = false // private var isPayThroughSimSim: Bool = false // private var isPayThroughEasyPay: Bool = false // private var isPayThroughJazzcash: Bool = false // // let toolBar = TIHelper.accessoryViewForTextField(target: self, selector: #selector(donePicker)) // // // override func viewDidLoad() { // super.viewDidLoad() // // For removing the extra empty spaces of TableView below // self.navigationItem.title = "Payment Mode" // self.tableView.delegate = self // self.tableView.dataSource = self // tableView.tableFooterView = UIView() // // // self.hideKeyboardWhenTappedAround() // // // self.navigationItem.hidesBackButton = true // let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.back(sender:))) // self.navigationItem.leftBarButtonItem = newBackButton // // let allPreviousViewC = currentViewController.navigationController?.viewControllers // will give array of all pushed VC // // // Can use if condition to check array count and then put below code inside that condition // // for viewC in allPreviousViewC! { // // print("ViewC is \(viewC)") // // } // // let previousController = self.navigationController!.getPreviousViewController() // // if previousController is homePagerViewController { // // self.view.makeToast("Hello this is hisummary") // // }else if previousController is TravelPagerViewController{ // // self.view.makeToast("Hello this is travel summary") // // } // } // // @objc func donePicker() { // self.view.endEditing(true) // } // // override func viewWillAppear(_ animated: Bool) { // navigationController?.navigationBar.barTintColor = UIColor(red: 227.0/255.0, green: 118.0/255.0, blue: 57.0/255.0, alpha: 1.0) // navigationController?.navigationBar.isTranslucent = false // navigationController?.navigationBar.tintColor = UIColor(red: 117.0/255.0, green: 117.0/255.0, blue: 117.0/255.0, alpha: 1.0) // // let previousController = self.navigationController!.getPreviousViewController() // if previousController is homePagerViewController { // // self.view.makeToast("Hello this is hisummary") // self.isHomePager = true // self.isTravelPager = false // self.api = apiHome // // self.apiHome = api as! HomeInsuranceDataHandler // // }else if previousController is TravelPagerViewController{ // // self.view.makeToast("Hello this is travel summary") // self.isTravelPager = true // self.isHomePager = false // self.api = apiTravel // intializeVariableForTravel() // } // } // // @objc func back(sender: UIBarButtonItem) { // // var cancelAlert = UIAlertController(title: "Quit", message: "Are you sure you want to go back to home?", preferredStyle: UIAlertControllerStyle.alert) // // cancelAlert.addAction(UIAlertAction(title: "Confirm", style: .default, handler: { (action: UIAlertAction!) in // self.navigationController!.popToRootViewController(animated: true) // })) // // cancelAlert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action: UIAlertAction!) in // // cancelAlert .dismiss(animated: true, completion: nil) // // })) // // present(cancelAlert, animated: true, completion: nil) // // } // // // func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return 3 // } // // func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // let cell = UITableViewCell() // switch indexPath.row { // case 0: // let cell = tableView.dequeueReusableCell(withIdentifier: "PaymentOptionCell", for: indexPath) as! PaymentOptionCell // cell.selectionStyle = .none // return cell // // case 1: // let cell = tableView.dequeueReusableCell(withIdentifier: "SimSimPaymentCell", for: indexPath) as! SimSimPaymentCell // cell.selectionStyle = .none // cell.numberOutlet.delegate = self // cell.numberOutlet.inputAccessoryView = toolBar // self.numberTextfieldFromSimSim = cell.numberOutlet // return cell // // case 2: // let cell = tableView.dequeueReusableCell(withIdentifier: "JazzCashPaymentCell", for: indexPath) as! JazzCashPaymentCell // cell.selectionStyle = .none // cell.jazzCashNumberField.delegate = self // cell.jazzCashNumberField.inputAccessoryView = toolBar // self.numberTextfieldFromJazzCash = cell.jazzCashNumberField // return cell // // default: // print("invalid selection") // } // return cell // } // // // func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // tableView.deselectRow(at: indexPath, animated: true) // if indexPath.row == 0 { // //check if second row is on // if isPayThroughSimSim{ // isPayThroughSimSim = false // } // if isPayThroughJazzcash{ // isPayThroughJazzcash = false // } // if isPaymentMethod { // isPaymentMethod = false // } else { // isPaymentMethod = true // } // tableView.beginUpdates() // tableView.endUpdates() // } // if indexPath.row == 1 { // //check if first row is on // if isPaymentMethod{ // isPaymentMethod = false // } // if isPayThroughJazzcash{ // isPayThroughJazzcash = false // } // if isPayThroughSimSim { // isPayThroughSimSim = false // } else { // isPayThroughSimSim = true // } // tableView.beginUpdates() // tableView.endUpdates() // } // if indexPath.row == 2 { // // if isPaymentMethod{ // isPaymentMethod = false // } // if isPayThroughSimSim{ // isPayThroughSimSim = false // } // if isPayThroughJazzcash { // isPayThroughJazzcash = false // } else { // isPayThroughJazzcash = true // } // tableView.beginUpdates() // tableView.endUpdates() // } // // } // // func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // if indexPath.row == 0 { // if isPaymentMethod { // return 120 // } else { // return 55 // } // } // if indexPath.row == 1 { // if isPayThroughSimSim { // return 120 // } else { // return 55 // } // } // if indexPath.row == 2 { // if isPayThroughJazzcash { // return 140 // // } else { // return 55 // } // } // // return 55 // } //} // ////MARK :- Api for This Page //extension PaymentOptionsViewController{ // // func finjaAuthHome() { // // if !(numberTextfieldFromSimSim?.text?.isEmpty)! || numberTextfieldFromSimSim?.text != ""{ // self.view.makeToastActivity(.center) // // apiHandlerHome.finajAuthentication(MobileNo: numberTextfieldFromSimSim?.text ?? "-", completionHandler: { (success) in // self.view.hideToastActivity() // if success { // if let codeApi = self.apiHandlerHome.authenticationData?.code{ // if codeApi == "200"{ // self.view.makeToast("OTP send successfully!") // // var cancelAlert = UIAlertController(title: "OTP Verification", message: "We have send you a code on your mobile number, please enter the code below: ", preferredStyle: UIAlertControllerStyle.alert) // // cancelAlert.addTextField { (textField : UITextField!) in // self.simsimOtpTextfield = textField // textField.placeholder = "Verification code" // textField.keyboardType = .numberPad // textField.inputAccessoryView = self.toolBar // textField.delegate = self // } // // cancelAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak cancelAlert] (_) in // let textField = cancelAlert!.textFields![0] // Force unwrapping because we know it exists. // print("Text field: \(textField.text)") // self.otpText = textField.text ?? "0" // if let dataObj = self.apiHandlerHome.authenticationData?.data!{ // print(dataObj) // let TransactionAmount = self.apiHome?.HIresult![0].Premium ?? "" // let PolicyNumber = self.apiHome?.HIresult![0].OrderID ?? "" // self.finjaPaymentHome(data:(self.apiHandlerHome.authenticationData)! ,TransactionAmount: TransactionAmount, PolicyNumber: PolicyNumber, OTP: self.otpText!) // } // // // })) // // cancelAlert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action: UIAlertAction!) in // // cancelAlert .dismiss(animated: true, completion: nil) // // })) // // self.present(cancelAlert, animated: true, completion: nil) // // // // // fillDataSource(fromPolices: self.dataHandler!.areas!) // }else{ // //make new popup with msg and ok click // var failedAlert = UIAlertController(title: "OTP Failed", message: self.apiHandlerHome.authenticationData?.msg ?? "", preferredStyle: UIAlertControllerStyle.alert) // failedAlert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action: UIAlertAction!) in // // failedAlert .dismiss(animated: true, completion: nil) // // })) // // self.present(failedAlert, animated: true, completion: nil) // } // } // // } else { // self.view.makeToast("Failed to send OTP") // // self.fieldForPicker?.resignFirstResponder() // } // }) // }else{ // self.view.makeToast("please enter the proper number") // } // // } // // func finjaAuthTravel() { // // if !(numberTextfieldFromSimSim?.text?.isEmpty)! || numberTextfieldFromSimSim?.text != ""{ // self.view.makeToastActivity(.center) // // paymentApiHelper.sharedInstance.finajAuthentication(MobileNo: numberTextfieldFromSimSim?.text ?? "-", completionHandler: { (success) in // self.view.hideToastActivity() // if success { // if let codeApi = paymentApiHelper.sharedInstance.authenticationData?.code{ // if codeApi == "200"{ // self.view.makeToast("OTP send successfully!") // print(paymentApiHelper.sharedInstance.authenticationData) // // // TIHelper.showAlert(ViewController: self, AlertTitle: "OTP Verification", AlertMessage: "We have send you a code on your mobile number, please enter the code below:", AlertStyle: .alert , Actions: [defaultAction]) // // var cancelAlert = UIAlertController(title: "OTP Verification", message: "We have send you a code on your mobile number, please enter the code below: ", preferredStyle: UIAlertControllerStyle.alert) // // cancelAlert.addTextField { (textField) in // self.simsimOtpTextfield = textField // textField.placeholder = "Verification code" // textField.keyboardType = .numberPad // textField.inputAccessoryView = self.toolBar // textField.delegate = self // } // // // cancelAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak cancelAlert] (_) in // let textField = cancelAlert!.textFields![0] // Force unwrapping because we know it exists. // print("Text field: \(textField.text)") // self.otpText = textField.text ?? "0" // self.finjaPaymentHome(data:(paymentApiHelper.sharedInstance.authenticationData)! ,TransactionAmount: self.apiTravel!.result![0].Premium ?? "", PolicyNumber: self.apiTravel!.result![0].OrderID ?? "000", OTP: self.otpText!) // })) // // cancelAlert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action: UIAlertAction!) in // // cancelAlert .dismiss(animated: true, completion: nil) // // })) // // self.present(cancelAlert, animated: true, completion: nil) // } // else{ // //make new popup with msg and ok click // var failedAlert = UIAlertController(title: "OTP Failed", message: paymentApiHelper.sharedInstance.authenticationData?.msg ?? "", preferredStyle: UIAlertControllerStyle.alert) // failedAlert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action: UIAlertAction!) in // // failedAlert .dismiss(animated: true, completion: nil) // // })) // // self.present(failedAlert, animated: true, completion: nil) // } // // } // // } else { // self.view.makeToast("Failed to send OTP") // } // }) // }else{ // self.view.makeToast("please enter the proper number") // } // // } // // // finajGetToken // func finajGetToken() { // // if !(numberTextfieldFromSimSim?.text?.isEmpty)! || numberTextfieldFromSimSim?.text != "" || paymentApiHelper.sharedInstance.authenticationData != nil { // self.view.makeToastActivity(.center) // // paymentApiHelper.sharedInstance.finajGetToken(UserId: self.mobileNumber ?? "0", Password: self.mobileNumberPass ?? "0", completionHandler: { (Bool, GenerateToken) in // self.view.hideToastActivity() // if Bool { // self.view.makeToast("Token have been stored") // print(paymentApiHelper.sharedInstance.authenticationToken ?? "No token value") // } else { // self.view.makeToast("Failed to get Token") // } // }) // }else{ // self.view.makeToast("please enter the proper number") // } // // } // // func finajGetPolicyAmount() { // // if !(numberTextfieldFromSimSim?.text?.isEmpty)! || numberTextfieldFromSimSim?.text != "" || paymentApiHelper.sharedInstance.authenticationData != nil { // self.view.makeToastActivity(.center) // // paymentApiHelper.sharedInstance.GetAmountOfPolicy(SalesFoamNo: "00", Type: "00", completionHandler: { (Bool, GetAmountOfPolicyModel) in // self.view.hideToastActivity() // if Bool { // self.view.makeToast("Amount have been stored") // print(GetAmountOfPolicyModel.Result) // } else { // self.view.makeToast("Failed to get Token") // } // }) // }else{ // self.showToast(message: "please enter the proper number") // } // // } // //finjaPayment // func finjaPaymentHome(data: FinjaAuthenticationModel, TransactionAmount: String, PolicyNumber:String, OTP:String) { // // if !(numberTextfieldFromSimSim?.text?.isEmpty)! || numberTextfieldFromSimSim?.text != "" || apiHandlerHome.authenticationData != nil { // self.view.makeToastActivity(.center) // apiHandlerHome.finjaPayment1(data: data ,TransactionAmount: TransactionAmount, PolicyNumber: PolicyNumber, OTP: OTP) { (Bool, response) in // self.view.hideToastActivity() // if Bool { // if response.code == "200" { // //MARK: - Previous popup // // var successPopup = UIAlertController(title: "Sim Sim Transaction", message: "\(response.msg ?? "no response")", preferredStyle: UIAlertControllerStyle.alert) // var successPopup = UIAlertController(title: "SimSim Transaction", message: "Thank you , your payment has been received successfully , your policy will be emailed to you shortly", preferredStyle: UIAlertControllerStyle.alert) // // // successPopup.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak successPopup] (_) in // successPopup!.dismiss(animated: true, completion: nil) // self.navigationController!.popToRootViewController(animated: true) // })) // self.present(successPopup, animated: true, completion: nil) // }else{ // self.view.makeToast("\(response.msg ?? "no response")") // print(response.msg ?? "no response") // } // } else { // self.view.makeToast("Failed to get Token") // } // } // // }else{ // self.view.makeToast("please enter the proper number") // } // // } // // //JazzCashPayment // func JazzCashPayment(PolicyNumber: String, Amount:String, Key: String, PayMobileNo:String, Description: String) { // // if !(numberTextfieldFromJazzCash?.text?.isEmpty)! || numberTextfieldFromJazzCash?.text != "" { // self.view.makeToastActivity(.center) // apiHandlerHome.JazzCash(PolicyNumber: PolicyNumber, Amount: Amount, Key: Key, PayMobileNo: PayMobileNo, Description: Description) { (Bool, JazzCashPaymentModel) in // // self.view.hideToastActivity() // if Bool { // if JazzCashPaymentModel.TxCode == "200" || JazzCashPaymentModel.TxCode == "000" || JazzCashPaymentModel.TxCode == "121"{ // var successPopup = UIAlertController(title: "JazzCash Transaction", message: "Thank you , your payment has been received successfully , your policy will be emailed to you shortly", preferredStyle: UIAlertControllerStyle.alert) // // successPopup.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak successPopup] (_) in // successPopup!.dismiss(animated: true, completion: nil) // self.navigationController!.popToRootViewController(animated: true) // })) // // self.present(successPopup, animated: true, completion: nil) // }else{ // self.view.makeToast("\(JazzCashPaymentModel.TxMessage ?? "no response")") // // self.view.makeToast("Amount have been stored") // print(JazzCashPaymentModel.TxMessage ?? "no response") // } // // } else { // self.view.makeToast("Failed to get Token") // } // } // // }else{ // self.view.makeToast("please enter the proper number") // } // // } //} // //extension PaymentOptionsViewController: UITextFieldDelegate{ // func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { // if textField == simsimOtpTextfield as UITextField!{ // 7 characters are allowed on homeValueTextField // guard let text = textField.text else { return true } // let newLength = text.count + string.count - range.length // return newLength <= 6 // Bool // } // return true // } //}
// // LaunchTableViewCell.swift // SpaceX // // Created by Bruno Guedes on 20/10/19. // Copyright © 2019 Bruno Guedes. All rights reserved. // import UIKit class LaunchTableViewCell: UITableViewCell { static let reuseIdentifier = "LaunchTableViewCell" private let nameLabel = UILabel() private let dateLabel = UILabel() private let statusLabel = UILabel() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none addNameLabel() addDateLabel() addStatusLabel() NSLayoutConstraint.activate([ nameLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: .spacing2x), nameLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: .spacing2x), nameLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -.spacing2x), dateLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: .spacing1x), dateLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: .spacing2x), dateLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -.spacing2x), statusLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: .spacing1x), statusLabel.leadingAnchor.constraint(equalTo: dateLabel.trailingAnchor, constant: .spacing2x), statusLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -.spacing2x), statusLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -.spacing2x), ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func addNameLabel() { nameLabel.font = UIFontMetrics(forTextStyle: .title1).scaledFont(for: UIFont.systemFont(ofSize: 20)) nameLabel.numberOfLines = 0 nameLabel.backgroundColor = .clear nameLabel.textColor = .label nameLabel.textAlignment = .left nameLabel.translatesAutoresizingMaskIntoConstraints = false nameLabel.clipsToBounds = true contentView.addSubview(nameLabel) } func addDateLabel() { dateLabel.font = UIFontMetrics(forTextStyle: .title2).scaledFont(for: UIFont.systemFont(ofSize: 16)) dateLabel.numberOfLines = 0 dateLabel.backgroundColor = .clear dateLabel.textColor = .secondaryLabel dateLabel.textAlignment = .left dateLabel.translatesAutoresizingMaskIntoConstraints = false dateLabel.clipsToBounds = true contentView.addSubview(dateLabel) } func addStatusLabel() { statusLabel.font = UIFontMetrics(forTextStyle: .title2).scaledFont(for: UIFont.systemFont(ofSize: 16)) statusLabel.numberOfLines = 0 statusLabel.backgroundColor = .clear statusLabel.textColor = .secondaryLabel statusLabel.textAlignment = .right statusLabel.translatesAutoresizingMaskIntoConstraints = false statusLabel.clipsToBounds = true contentView.addSubview(statusLabel) } public func configure(launchViewModel: LaunchViewModel) { nameLabel.text = launchViewModel.name dateLabel.text = launchViewModel.date statusLabel.text = launchViewModel.status } }
// // Annotation.swift // Map // // Created by Jack on 12/6/15. // Copyright © 2015 William Parker. All rights reserved. // import Foundation import MapKit @objc class Annotation: NSObject, MKAnnotation { var name:String var thecoordinate:CLLocationCoordinate2D var isPin:Bool init(name:String,coordinate:CLLocationCoordinate2D,type:Bool) { self.name = name self.thecoordinate = coordinate self.isPin = type } @objc var coordinate: CLLocationCoordinate2D { get { return self.thecoordinate } } @objc var title: String? { get { return self.name } } }
// // ApplicationDetailViewController.swift // Top Free Apps // // Created by mohammad shatarah on 4/8/19. // Copyright © 2019 mohammad shatarah. All rights reserved. // import UIKit class ApplicationDetailViewController: UIViewController { var application: Application? @IBOutlet weak var appImageView: UIImageView! @IBOutlet weak var rightsLabel: UILabel! @IBOutlet weak var dateReleasedLabel: UILabel! @IBOutlet weak var categoryLabel: UILabel! @IBOutlet weak var descriptionTextView: UITextView! @IBOutlet weak var appNameLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() initView() } func initView() { appNameLabel.text = application?.name.label rightsLabel.text = application?.rights.label categoryLabel.text = application?.category.attributes.label descriptionTextView.text = application?.summary.label dateReleasedLabel.text = application?.releaseDate.attributes.label if ((application?.images.count) != nil) { appImageView.downloadImage(from: URL(string: application?.images[((application?.images.count)!-1)].label ?? "")!) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension ApplicationDetailViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let vc = segue.destination as? AppStoreWebViewController, let link = application?.link.attributes.href { vc.appLink = link }else if let vc = segue.destination as? LargeImageViewController{ if ((application?.images.count) != nil) { vc.imageURL = application?.images[((application?.images.count)!-1)].label ?? "" } } } }
// // ShareHomeViewController.swift // Grubbie // // Created by JABE on 12/4/15. // Copyright © 2015 JABELabs. All rights reserved. // import UIKit // Implementation here just for conformance with requirements of PhotoEditorViewController.delegate; else onSave won't trigger. extension ShareTypeViewController : AppModelEditorDelegate { func didAddInstance<T>(sourceViewController: UIViewController, instance: T) { } func didUpdateInstance<T>(sourceViewController: UIViewController, instance: T) { } } // MARK: PhotoEditorDelegate extension ShareTypeViewController : PhotoEditorDelegate { func onSave(photoEditorData: PhotoEditorData, completionBlock: ((success: Bool, isNewObject: Bool, savedObject: AnyObject?) -> Void)?) { print("ShareHomeViewController : PhotoEditorDelegate -> onSave") self.readyToShare = true // self.photoToShare = photoEditorData self.shareSessionInfo.photos.append(SharePhoto(photoEditorData: photoEditorData)) if let completion = completionBlock { completion(success: true, isNewObject: false, savedObject: nil) } } func onDeletePhoto(photoSource: PhotoSource, completionBlock: (deleted: Bool, postDeleteUserMessage: String?, error: NSError?) -> Void) { assertionFailure("Photos cannnot be deleted through this module.") } func queryCanDeletePhotoSource(photoSource: PhotoSource, completionBlock: (canDelete: Bool, userReason: String, userData: AnyObject?) -> Void) { completionBlock(canDelete: false, userReason: "Photos cannnot be deleted through this module.", userData: nil) } } extension ShareTypeViewController : ShareCommandCellTableViewCellDelegate { func didPressNextButton(indexPath: NSIndexPath) { commands[indexPath.row].invokeCommand(self) } } class ShareTypeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var tableView: UITableView! var shareSessionInfo : ShareSessionInfo! // var photoToShare : PhotoEditorData? var readyToShare = false var commands = [ JLTableCellCommand(mainText: UserMessage.GrubbieShare.rawValue, detailText: UserMessage.GrubbieShareDetailText.rawValue, cellAccessoryType: UITableViewCellAccessoryType?.None, commandType: .Normal) { (settingsVc) -> Void in UIFactory.showStoryboard(settingsVc, storyboardId: StoryboardId.GrubbiePhotoSearchView, configureBlock: { (uiViewController) -> Void in guard let view = uiViewController as? PhotoSearchViewController, shareTypeVc = settingsVc as? ShareTypeViewController else { return } shareTypeVc.shareSessionInfo.shareType = .GrubbieShare view.shareSessionInfo = shareTypeVc.shareSessionInfo }) } , JLTableCellCommand(mainText: UserMessage.AdhocShare.rawValue, detailText: UserMessage.AdhocShareDetailText.rawValue, cellAccessoryType: UITableViewCellAccessoryType?.None, commandType: .Normal) { (uiShareTypeViewController) -> Void in UIFactory.showStoryboard(uiShareTypeViewController, storyboardId: StoryboardId.PhotoEditor) { (uiViewController) -> Void in guard let photoEditorVc = uiViewController as? PhotoEditorViewController, shareTypeVc = uiShareTypeViewController as? ShareTypeViewController else { return } shareTypeVc.shareSessionInfo.shareType = .AdhocShare photoEditorVc.photoEditorDelegate = shareTypeVc photoEditorVc.delegate = shareTypeVc } } ] @IBAction func backButtonPressed(sender: AnyObject) { Util.closeController(self) } override func viewDidAppear(animated: Bool) { if self.readyToShare { self.readyToShare = false UIFactory.showStoryboard(self, storyboardId: .SharingViewController) { (uiViewController) -> Void in if let view = uiViewController as? SharingViewController { view.shareSessionInfo = self.shareSessionInfo } } } } override func viewDidLoad() { super.viewDidLoad() if shareSessionInfo == nil { shareSessionInfo = ShareSessionInfo() } tableView.dataSource = self tableView.delegate = self } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return commands.count } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let command = commands[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! ShareCommandCellTableViewCell cell.commandMainTextLabel.text = command.mainText cell.commandDetailTextView.text = command.detailText! cell.delegate = self cell.indexPath = indexPath return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let command = commands[indexPath.row] command.invokeCommand(self) } }
// // MapViewController.swift // LetsPo // // Created by 溫芷榆 on 2017/7/18. // Copyright © 2017年 Walker. All rights reserved. // import UIKit import MapKit import CoreLocation import UserNotifications import CoreData class MapViewController: UIViewController ,CLLocationManagerDelegate,MKMapViewDelegate { var dataManager:CoreDataManager<BoardData>! var dataManagerCount = Int() let locationManager = CLLocationManager() var location = CLLocation() var places:[SpotAnnotation]! var zoomLevel = CLLocationDegrees() var region = CLCircularRegion() var reUpdate = NSLock() var shouldReUpdate = Bool() var nearbyDictionary = [[String:Any]]() var titleName:String = "" var count: Int = 0 var tttt = UIImage() @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() // 可以選擇永遠定位或者使用時定位 locationManager.requestAlwaysAuthorization() // if CLLocationManager.authorizationStatus() == .authorizedAlways{ // locationManager.requestAlwaysAuthorization() // } // else { // locationManager.requestWhenInUseAuthorization() // } locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.activityType = .automotiveNavigation self.locationManager.startUpdatingLocation() Timer.scheduledTimer(withTimeInterval: 10, repeats: true) { (timer) in // 防止秒數內再度觸發方法 self.doUnlock() self.locationManager.startUpdatingLocation() } mapView.delegate = self mapView.userTrackingMode = .follow mapView.mapType = .standard mapView.showsUserLocation = true dataManager = CoreDataManager(initWithModel: "LetsPoModel", dbFileName: "boardData.sqlite", dbPathURL: nil, sortKey: "board_CreateTime", entityName: "BoardData") dataManagerCount = dataManager.count() places = spot() filterAnnotations(paramPlaces: places) // 回到當前位置 let locationButton = UIButton(type: .custom) let x = UIScreen.main.bounds.size.width * 0.76 let y = UIScreen.main.bounds.size.height * 0.76 locationButton.frame = CGRect(x: x, y: y, width: 80, height: 85) locationButton.addTarget(self, action: #selector(zoomToUserLocation), for: .touchUpInside) let btnImage = UIImage(named: "rightBtn.png") locationButton.imageView?.contentMode = .center locationButton.setImage(btnImage, for: .normal) self.view.addSubview(locationButton) // tmp add location button (press once only) let addlocations = UIButton(type: .custom) addlocations.frame = CGRect(x: 10, y: 10, width: 50, height: 50) addlocations.addTarget(self, action: #selector(addLocation), for: .touchUpInside) addlocations.setImage(UIImage(named: "addNote.png"), for: .normal) self.view.addSubview(addlocations) // let result = dataManager.searchField(field: "board_Privacy", forKeyword: "0") as! [BoardData] //// print(result) // for tmp:BoardData in result{ // print("name: \(String(describing: tmp.board_Creater))Lat:\(String(describing: tmp.board_Lat))Lon:\(String(describing: tmp.board_Lon))time:\(String(describing: tmp.board_CreateTime))Privacy:\(String(describing: tmp.board_Privacy))") // } // } typealias EditItemCompletion = (_ success: Bool , _ result : BoardData?) -> () func editeWithItem(item: BoardData?,withCompletion completion:EditItemCompletion?){ if(completion == nil){ return } var finalItem = item for i in 0...8{ // if(finalItem == nil){ finalItem = self.dataManager.createItem() finalItem?.board_CreateTime = NSDate() // } let nameArr = ["Tom","Jack","Hunter","Lucy","Sandy","Lisa","Jo","Bob","Andraw"] finalItem?.board_Creater = nameArr[i] let lat = [0.33087803,0.331622,0.33045275,0.337566,0.33546547,0.33424,0.33754,0.334643,0.6544343] let lon = [0.0305999,0.030337,0.02953296,0.041202,0.030544,0.03012364,0.0303322,0.0304657,0.9754] finalItem?.board_Lat = 37 + lat[i] finalItem?.board_Lon = -122 + lon[i] let image = ["myNigger.jpg","delete.png","deer.jpg","map.png","rightBtn.png","insert.png","right-arrow.png","BgSettings.png","Trashcan.png"] let iii = image[i] let img = UIImage(named: iii) let imgData = UIImageJPEGRepresentation(img!, 1) finalItem?.board_BgPic = imgData! as NSData finalItem?.board_Privacy = true completion!(true, finalItem) } } func zoomToUserLocation(){ var mapRegion = MKCoordinateRegion() mapRegion.center = self.mapView.userLocation.coordinate mapRegion.span.latitudeDelta = 0.01 mapRegion.span.longitudeDelta = 0.01 mapView.setRegion(mapRegion, animated: true) } func addLocation(){ self.editeWithItem(item: nil) { (success, result) in if(success){ self.dataManager.saveContexWithCompletion(completion: { (success) in if(success){ } }) } } } // mark - pins method func filterAnnotations(paramPlaces:[SpotAnnotation]){ let latDelta = self.mapView.region.span.latitudeDelta / 15 let lonDelta = self.mapView.region.span.longitudeDelta / 15 for p:SpotAnnotation in paramPlaces { p.cleanPlaces() } var spotsToShow = [SpotAnnotation]() for i in 0..<places.count { let currentObject = paramPlaces[i] let lat = currentObject.coordinate.latitude let lon = currentObject.coordinate.longitude var found = false for tempAnnotation:SpotAnnotation in spotsToShow { let tempLat = tempAnnotation.coordinate.latitude - lat let tempLon = tempAnnotation.coordinate.longitude - lon if fabs(tempLat) < latDelta && fabs(tempLon) < lonDelta { self.mapView.removeAnnotation(currentObject) found = true tempAnnotation.addPlasce(place: currentObject) break } } if !found { spotsToShow.append(currentObject) mapView.addAnnotation(currentObject) } } } func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { if zoomLevel != mapView.region.span.longitudeDelta { for ano:Any in mapView.selectedAnnotations { mapView .deselectAnnotation(ano as? MKAnnotation, animated: false) } filterAnnotations(paramPlaces: places) zoomLevel = mapView.region.span.longitudeDelta } } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if (annotation is MKUserLocation) { return nil } let PinIdentifier = "PinIdentifier" var pin = mapView.dequeueReusableAnnotationView(withIdentifier: PinIdentifier) // as? MKPinAnnotationView if (pin == nil){ // pin = MKPinAnnotationView.init(annotation: annotation, reuseIdentifier: PinIdentifier) pin = MKAnnotationView.init(annotation: annotation, reuseIdentifier: PinIdentifier) }else { pin?.annotation = annotation } let rightBtn = UIButton(type: .detailDisclosure) // rightBtn.setImage(UIImage(named: "rightBtn.png"), for: .normal) pin?.rightCalloutAccessoryView = rightBtn let myAnnotation = annotation as! SpotAnnotation let detailImage = UIImageView.init(image: myAnnotation.image) detailImage.layer.cornerRadius = 5.0 detailImage.layer.masksToBounds = true // Detail view 的 Constraint let widthConstraint = NSLayoutConstraint(item: detailImage, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100) let heightConstraint = NSLayoutConstraint(item: detailImage, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 100) detailImage.addConstraint(widthConstraint) detailImage.addConstraint(heightConstraint) detailImage.contentMode = .scaleAspectFill pin?.detailCalloutAccessoryView = detailImage pin?.canShowCallout = true pin?.isEnabled = true if myAnnotation.privacy == true { tttt = UIImage(named: "map.png")! }else { tttt = UIImage(named: "delete.png")! } pin?.image = tttt return pin } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { let myAnnotation = view.annotation as! SpotAnnotation let placeCount = myAnnotation.placesCount() if placeCount <= 0 {return} if placeCount == 1 { titleName = myAnnotation.currentTitle if (control as? UIButton)?.buttonType == .detailDisclosure { performSegue(withIdentifier:"getDetail", sender: self) } print("Press one callout view") }else { print("Press many callout view") } } func doUnlock(){ reUpdate.unlock() if shouldReUpdate{ shouldReUpdate = false } } // mark - Region monitoring method func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if reUpdate.try() == false { shouldReUpdate = true return } monitorRegion(userLocation: locations.last!) locationManager.stopUpdatingLocation() } func locationManager(_ manager: CLLocationManager, didStartMonitoringFor region: CLRegion) { print("CREATED REGION: \(region.identifier) - \(locationManager.monitoredRegions.count)") } func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { print("Enter \(region.identifier)") mutableNotificationContent(title: "You Did Enter My Monitoring Area", body: "CLLocationManager did enter region:\(region.identifier)", indentifier: "DidEnterRegion") } func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) { print("Exit \(region.identifier)") mutableNotificationContent(title: "You Did Exit My Monitoring Area", body: "CLLocationManager did Exit region:\(region.identifier)", indentifier: "DidExitRegion") } func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) { // print("monitoringDidFailForRegion \(String(describing: region)) \(error)") } func mutableNotificationContent(title:String, body:String, indentifier:String){ let content = UNMutableNotificationContent() content.title = title content.body = body content.sound = UNNotificationSound.default() let request = UNNotificationRequest.init(identifier: indentifier, content: content, trigger: nil) UNUserNotificationCenter.current().removeAllPendingNotificationRequests() UNUserNotificationCenter.current().add(request) { (error) in if error != nil { print("UserNotificationCenter Fail:\(String(describing: error))") } } } func monitorRegion(userLocation:CLLocation){ let userLocation = userLocation let dic = getLocations() var distance = CLLocationDistance() count = count + 1 for value in dic { let strName = value["board_Creater"] as! String //let time = value["lastUpdateDateTime"] as! String let lat = value["lat"] as! Double let lon = value["lon"] as! Double let img = value["BgPic"] as! UIImage let alert = value["alert"] as! Bool let pins = CLLocation.init(latitude: lat, longitude: lon) distance = pins.distance(from: userLocation) * 1.09361 // 距離小於 2500 則存回 near if distance < 2500 && alert == true { if count == 1 { nearbyDictionary.append(["name":strName,"lat":lat, "lon":lon, "distance":distance,"BgPic":img]) }else { count = 0 nearbyDictionary.removeAll() nearbyDictionary.append(["name":strName,"lat":lat, "lon":lon, "distance":distance,"BgPic":img]) count = 1 } if nearbyDictionary.count < 20 { if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self){ let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon) region = CLCircularRegion.init(center: coordinate, radius: 150, identifier: strName) // nearbyDictionary 內的定位開始 Monitoring locationManager.startMonitoring(for: region) locationManager.requestState(for: region) // 超過 2300 則停止 Monitoring if distance > 2300 { locationManager.stopMonitoring(for: region) print("stop \(strName)") } } } } } nearbyDictionary.sort { ($0["distance"] as! Double) < ($1["distance"] as! Double) } } func spot() -> [SpotAnnotation] { var result = [SpotAnnotation]() let dic = getLocations() for value in dic { let strName = value["board_Creater"] as! String // let time = value["lastUpdateDateTime"] as! String let lat = value["lat"] as! Double let lon = value["lon"] as! Double let img = value["BgPic"] as! UIImage let privacy = value["privacy"] as! Bool let annotation = SpotAnnotation( atitle: strName, lat: lat, lon: lon, imageName: img,privacyBool: privacy) result.append(annotation) } print("result count \(result.count)") return result } func getLocations() -> [[String:Any]] { var locations = [[String:Any]]() for i in 0..<dataManagerCount { let item = dataManager.itemWithIndex(index: i) let Creater = item.board_Creater let lat = item.board_Lat let lon = item.board_Lon let time = item.board_CreateTime let privacy = item.board_Privacy let alert = item.board_Alert if let img = item.board_BgPic { let imgWithData = UIImage(data: img as Data) locations.append(["board_Creater":Creater!,"lat":lat,"lon":lon,"board_CreateTime":time!,"BgPic":imgWithData!,"privacy":privacy,"alert":alert]) } } // print("locations :\(locations)") print("location count :\(locations.count)") // let UrlString = "http://class.softarts.cc/FindMyFriends/queryFriendLocations.php?GroupName=bp102" // let myUrl = NSURL(string: UrlString) // let optData = try? Data(contentsOf: myUrl! as URL) // guard let data = optData else { // return friends // } // if let jsonArray = try? JSONSerialization.jsonObject(with: data, options:[]) as? [String:AnyObject] { // friends = (jsonArray?["friends"] as? [[String:Any]])! // friends.sort { ($0["lastUpdateDateTime"] as! String) > ($1["lastUpdateDateTime"] as! String) } // // } return locations } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { self.navigationController?.isNavigationBarHidden = true } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "getDetail" { let vc = segue.destination as! MapDetailViewController vc.navigationItem.title = titleName } } }
import UIKit class leftViewController: UITableViewController, SWRevealViewControllerDelegate { let leftMenuCellId = "leftMenuItemCell" var menuItems = ["Left item one", "Left item two", "Left item three", "Left item four", "Left item five"] override func viewDidLoad() { view.backgroundColor = UIColor.white; self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none tableView.register(leftMenuItemCell.self, forCellReuseIdentifier: leftMenuCellId) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuItems.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: leftMenuItemCell = tableView.dequeueReusableCell(withIdentifier: leftMenuCellId, for: indexPath) as! leftMenuItemCell cell.nameLabel.text = self.menuItems[ indexPath.row ] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let menuItemText = menuItems[ (indexPath as NSIndexPath).row ] let frontNavView = frontViewNavController() let frontView = frontViewController() frontView.title = menuItemText frontView.nameLabel.text = menuItemText frontNavView.viewControllers = [frontView] self.revealViewController().pushFrontViewController( frontNavView , animated: true ) } }
// // Created by Daniel Heredia on 2/27/18. // Copyright © 2018 Daniel Heredia. All rights reserved. // // Rotate Matrix import Foundation extension Array where Element == Array<Int> { mutating func swapInCycle(_ positions: [(row: Int, column: Int)]) { if positions.count <= 1 { return } var sub = self[positions[0].row][positions[0].column] for i in 1..<positions.count { let pos = positions[i] let tmp = self[pos.row][pos.column] self[pos.row][pos.column] = sub sub = tmp } self[positions[0].row][positions[0].column] = sub } var isSquare: Bool { let n = self.count for vector in self { if vector.count != n { return false } } return true } } func rotateMatrix(_ matrix: inout [[Int]]) { precondition(matrix.isSquare, "Error: Not an square matrix.") var left = 0 while left < (matrix.count / 2) { let right = matrix[0].count - left - 1 let top = left let bottom = right for i in left..<right { var indexes = [(row: Int, column: Int)]() let j = right - (i - left) indexes.append((top, i)) indexes.append((i, right)) indexes.append((bottom, j)) indexes.append((j, left)) matrix.swapInCycle(indexes) } left += 1 } } //var matrix = [[1,2,3], // [4,5,6], // [7,8,9]] //var matrix = [[1,2,3,4], // [5,6,7,8], // [9,10,11,12], // [13,14,15,16]] var matrix = [[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15], [16,17,18,19,20], [21,22,23,24,25]] print("Input matrix:") for vector in matrix { print("\(vector)") } rotateMatrix(&matrix) print("Rotated matrix:") for vector in matrix { print("\(vector)") }
// // MyPortfolio.swift // crypto-graph // // Created by Александр Пономарев on 05.04.18. // Copyright © 2018 Base team. All rights reserved. // import Foundation protocol PortfolioView: class { func provide(data: [CoinTransactionsViewData]) func append(_ newObject: CoinTransactionsViewData) func updateObject(existingAt index: Int, with object: CoinTransactionsViewData) func updateHeader(with object: TotalTransactionsViewData) func remove(at index: Int) func show(placeholder message: String, isVisible: Bool) }
// // ViewController.swift // mar30_2_2020 // // Created by 王冠之 on 2020/3/30. // Copyright © 2020 Wangkuanchih. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. var km : (Int, String) //tuple km = (98, "Larry Johnson") print( km.1 ) km.1 = "Stevev Job" print( km.1 ) } }
// // ViewController.swift // LNRSimpleNotifications Demo // // LNRSimpleNotifications: Modifications of TSMessages Copyright (c) 2015 LISNR, inc. // TSMessages: Copyright (c) 2014 Toursprung, Felix Krause <krausefx@gmail.com> // import UIKit //import LNRSimpleNotifications // Necessary import to use Pod class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: IB Actions @IBAction func showNotificationButtonPressed(sender: AnyObject) { LNRSimpleNotifications.sharedNotificationManager.notificationsPosition = LNRNotificationPosition.Top LNRSimpleNotifications.sharedNotificationManager.notificationsBackgroundColor = UIColor.whiteColor() LNRSimpleNotifications.sharedNotificationManager.notificationsTitleTextColor = UIColor.blackColor() LNRSimpleNotifications.sharedNotificationManager.notificationsBodyTextColor = UIColor.darkGrayColor() LNRSimpleNotifications.sharedNotificationManager.notificationsSeperatorColor = UIColor.grayColor() LNRSimpleNotifications.sharedNotificationManager.notificationsIcon = UIImage(named: "lisnr-cir-bw-notifications-icon") LNRSimpleNotifications.sharedNotificationManager.showNotification("Hipster Ipsum", body: "Schlitz you probably haven't heard of them raw denim brunch. Twee Kickstarter Truffaut cold-pressed trout banjo. Food truck iPhone normcore whatever selfies, actually ugh cliche PBR&B literally 8-bit. Farm-to-table retro VHS roof party, cold-pressed banh mi next level freegan .", callback: { () -> Void in LNRSimpleNotifications.sharedNotificationManager.dismissActiveNotification({ () -> Void in print("Notification disimissed") }) }) } @IBAction func showSucceedNotificationButtonPressed(sender: AnyObject){ LNRSimpleNotifications.sharedNotificationManager.showSucceedNotification("Action Succeed", body: "Congratulations!") { () -> Void in LNRSimpleNotifications.sharedNotificationManager.dismissActiveNotification({ () -> Void in print("Notification disimissed") }) } } @IBAction func showFailedNotificationButtonPressed(sender: AnyObject){ LNRSimpleNotifications.sharedNotificationManager.showFailedNotification("Action Failed", body: "WTF?!") { () -> Void in LNRSimpleNotifications.sharedNotificationManager.dismissActiveNotification({ () -> Void in print("Notification disimissed") }) } } @IBAction func showInfoNotificationButtonPressed(sender: AnyObject){ LNRSimpleNotifications.sharedNotificationManager.showInfoNotification("Info", body: "Just leave you a message!") { () -> Void in LNRSimpleNotifications.sharedNotificationManager.dismissActiveNotification({ () -> Void in print("Notification disimissed") }) } } }
// // CookieJar.swift // GMapService // // Created by Jose Zarzuela on 28/12/2014. // Copyright (c) 2014 Jose Zarzuela. All rights reserved. // import Foundation import JZBUtils private let JAR_PASSWORD = "JAR_PASSWORD" internal class CacheXsrfToken { //------------------------------------------------------------------------------------------------------------------------ internal class func readXsrfToken(email:String) -> (String, Double)? { var result : (String, Double)? = nil // Si no hay un fichero termina let fileManager = NSFileManager.defaultManager() if !fileManager.fileExistsAtPath(jarPath) { return nil } // Lee el contenido del fichero con las cookies de usuario var error:NSError? = nil if let base64Str = NSString(contentsOfFile:jarPath, encoding:NSUTF8StringEncoding, error: &error) { if let data = Crypto.decriptData(base64Str, passwd: JAR_PASSWORD) { let magicNumber = data.subdataWithRange(NSRange(location:0, length:4)) let xsrfTokenData = data.subdataWithRange(NSRange(location:4, length:data.length-4)) let crcBuffer = CRC32.crc32(xsrfTokenData) if crcBuffer.isEqualToData(magicNumber) { if let dict = NSKeyedUnarchiver.unarchiveObjectWithData(xsrfTokenData) as? NSDictionary { let jarEmail = dict.valueForKey("email") as? String ?? "" let jarXsrfToken = dict.valueForKey("xsrfToken") as? String ?? "" let jarXsrfTokenTime = dict.valueForKey("xsrfTokenTime") as? Double ?? -1.0 if jarEmail == email && jarXsrfToken != "" && jarXsrfTokenTime != -1.0 { result = (jarXsrfToken, jarXsrfTokenTime) } else { log.warning("Error reading cookie jar info (empty or different email") } } } else { log.warning("Error checking CRC for XsrfTokenJar file") } } else { log.warning("Error decryting XsrfTokenJar info") } } else { log.warning("Error reading token from XsrfTokenJar file: \(error)") } // Si ha habido algun problema leyendo el token borra el fichero if result==nil { deleteXsrfTokenJar() } // Retorna el resultado return result } //------------------------------------------------------------------------------------------------------------------------ internal class func writeXsrfToken(email:String, xsrfToken:String, xsrfTokenTime:Double) { let xsrfTokenInfo = NSMutableDictionary() // Guarda el email al que pertenece el XsrfToken xsrfTokenInfo.setValue(email, forKey: "email") // Guarda el valor del token y su expiracion xsrfTokenInfo.setValue(xsrfToken, forKey: "xsrfToken") xsrfTokenInfo.setValue(xsrfTokenTime, forKey: "xsrfTokenTime") // Le pega un "MagicNumber" para saber que es un fichero genuino // Y luego el contenido del token let xsrfTokenData = NSKeyedArchiver.archivedDataWithRootObject(xsrfTokenInfo) let crcBuffer = CRC32.crc32(xsrfTokenData) let fileData = NSMutableData(data: crcBuffer) fileData.appendData(xsrfTokenData) // Cifra el contenido let base64Str = Crypto.encriptData(fileData, passwd: JAR_PASSWORD) // Escribe el resultado a un fichero en base64 var error:NSError? = nil if !base64Str.writeToFile(jarPath, atomically: true, encoding: NSUTF8StringEncoding, error: &error) { log.warning("Error writing XsrfToken to XsrfTokenJar: \(error)") deleteXsrfTokenJar() } } //------------------------------------------------------------------------------------------------------------------------ private class func deleteXsrfTokenJar() { let fileManager = NSFileManager.defaultManager() if fileManager.fileExistsAtPath(jarPath) { var error:NSError? = nil if !fileManager.removeItemAtPath(jarPath, error: &error) { log.warning("Error deleting CookieJar: \(error)") } } } //------------------------------------------------------------------------------------------------------------------------ private class var jarPath : String { // Directorios para almacenar la informacion de la aplicacion let appID = NSBundle.mainBundle().bundleIdentifier! as String let localAppDocsPath : String = NSSearchPathForDirectoriesInDomains(.ApplicationSupportDirectory, .UserDomainMask, true)[0] as String let appDocsPath2 = localAppDocsPath + "/" + appID // ********************************************************* // De momento en el HOME como la aplicacion Java let home = NSHomeDirectory() let appDocsPath = home + "/gmap" // ********************************************************* let fileManager = NSFileManager.defaultManager() if !fileManager.fileExistsAtPath(appDocsPath) { var error : NSError? = nil fileManager.createDirectoryAtPath(appDocsPath, withIntermediateDirectories: true, attributes: nil, error: &error) } // Nombre del fichero en base a la carpeta return appDocsPath+"/xsrfTokenJar.data" } }
// // UIStackView+Extension.swift // IBKit // // Created by NateKim on 2019/12/06. // Copyright © 2019 NateKim. All rights reserved. // import UIKit extension This where View: UIStackView { @available(iOS 11.0, *) @discardableResult public func customSpacing(_ spacing: CGFloat, after arrangedSubview: UIView) -> Self { view.setCustomSpacing(spacing, after: arrangedSubview) return self } @discardableResult public func axis(_ axis: NSLayoutConstraint.Axis) -> Self { view.axis = axis return self } @discardableResult public func distribution(_ distribution: UIStackView.Distribution) -> Self { view.distribution = distribution return self } @discardableResult public func alignment(_ alignment: UIStackView.Alignment) -> Self { view.alignment = alignment return self } @discardableResult public func spacing(_ spacing: CGFloat) -> Self { view.spacing = spacing return self } @discardableResult public func isBaselineRelativeArrangement(_ isBaselineRelativeArrangement: Bool) -> Self { view.isBaselineRelativeArrangement = isBaselineRelativeArrangement return self } @discardableResult public func isLayoutMarginsRelativeArrangement(_ isLayoutMarginsRelativeArrangement: Bool) -> Self { view.isLayoutMarginsRelativeArrangement = isLayoutMarginsRelativeArrangement return self } }
// // FactsViewControllerTests.swift // NorrisTests // // Created by Bárbara Souza on 13/04/20. // Copyright © 2020 Bárbara Souza. All rights reserved. // import Quick import Nimble import Cuckoo @testable import Norris class FactsViewControllerTests: QuickSpec { override func spec() { var sut: FactsViewController! var view: FactsView! var searchView: SearchView! var presenterMock: MockFactsPresenterProtocol! beforeEach { view = FactsView() searchView = SearchView() presenterMock = MockFactsPresenterProtocol() sut = FactsViewController(presenter: presenterMock, contentView: view, suggestionsView: searchView) stub(presenterMock) { stub in when(stub.viewDidLoad()).thenDoNothing() when(stub.didSelectCard(with: any(IndexPath.self))).thenDoNothing() when(stub.wantsToSearch(with: any(IndexPath.self))).thenDoNothing() when(stub.wantsToSearch(text: anyString())).thenDoNothing() when(stub.wantsToShowSuggestions()).thenDoNothing() } _ = sut.view } describe("viewDidLoad") { it("calls presenter viewDidLoad") { verify(presenterMock).viewDidLoad() } } describe("bidLayoutEvents") { context("#didTapShareButton") { it("calls presenter didSelectCard") { let captor = ArgumentCaptor<IndexPath>() view.didTapShareButton?(IndexPath(row: 0, section: 0)) verify(presenterMock).didSelectCard(with: captor.capture()) expect(captor.value).to(equal(IndexPath(row: 0, section: 0))) } } context("didTapSuggestion") { it("calls presenter wantsToSearch") { let captor = ArgumentCaptor<IndexPath>() let index = IndexPath(row: 0, section: 0) searchView.didTapSuggestion?(index) verify(presenterMock).wantsToSearch(with: captor.capture()) expect(captor.value).to(equal(IndexPath(row: 0, section: 0))) } } } describe("searchBarTextDidBeginEditing") { it("calls presenter wantsToShowSuggestions") { sut.searchBarTextDidBeginEditing(UISearchBar()) verify(presenterMock).wantsToShowSuggestions() } } describe("searchBarSearchButtonClicked") { it("calls presenter") { let searchBar = UISearchBar() searchBar.text = "Text" let captor = ArgumentCaptor<String>() sut.searchBarSearchButtonClicked(searchBar) verify(presenterMock).wantsToSearch(text: captor.capture()) expect(captor.value).to(equal("Text")) } } } }
// // Created by 和泉田 領一 on 2020/02/03. // import Foundation enum Step { case increase case decrease }
// // ViewController.swift // TestApp // // Created by Paul Chung on 1/23/18. // Copyright © 2018 Paul Chung. All rights reserved. // import UIKit struct Crypto: Decodable{ let id: String let name: String let symbol: String let rank: String let price_usd: String let price_btc: String // let 24h_volume_usd: String let market_cap_usd: String let available_supply: String let total_supply: String let max_supply: String? let percent_change_1h: String let percent_change_24h: String let percent_change_7d: String let last_updated: String } protocol CryptoCellDelegate { func didTapAddCrypto(name: String) } class ViewController: UITableViewController { let numberOfCellsOnTable = 10 let cellId = "cellId" var cryptoCurrencies = [Crypto]() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.init(red: 18.0/255, green: 28.0/255, blue: 50.0/255, alpha: 1) navigationItem.title = "Cryptocurrency" // navigationItem.titleView?.tintColor = UIColor.white //check this // tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)//took out to include a custom detail label // if #available(iOS 11.0, *) { // navigationController?.navigationBar.prefersLargeTitles = true // } else { // // Fallback on earlier versions // } //API and URL fetching below when loading the app let jsonUrlString = "https://api.coinmarketcap.com/v1/ticker/?limit=100" guard let url = URL(string: jsonUrlString) else { return } URLSession.shared.dataTask(with: url){ (data, response, err) in guard let data = data else { return } do{ self.cryptoCurrencies = try JSONDecoder().decode([Crypto].self, from: data) // print(self.cryptoCurrencies[0]) // print(String(self.cryptoCurrencies.count)) DispatchQueue.main.async { self.tableView.reloadData() } } catch let jsonErr{ print("Error serializing JSON:", jsonErr) } }.resume() /*Button to go to user profile page*/ navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Profile", style: .plain, target: self, action: #selector(buttonAction)) } @objc func buttonAction(sender: UIButton!) { let controller = ProfileController() navigationController?.pushViewController(controller, animated: true) print("Profile tapped") } // override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // let label = UILabel() // label.text = "By rank" //// label.textColor = UIColor.init(red: 189.0/255, green: 199.0/255, blue: 193.0/55, alpha: 1.0) //fix later //// label.font = UIFont(name: "Avenir-Light", size: 25) // return label // } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cryptoCurrencies.count } override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { // doSomethingWithItem(indexPath.row) print(indexPath.row) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) var cell = tableView.dequeueReusableCell(withIdentifier: cellId) if cell == nil { cell = UITableViewCell(style: .value1, reuseIdentifier: cellId) } let bgColorView = UIView() bgColorView.backgroundColor = UIColor.init(red: 8.0/255, green: 18.0/255, blue: 40.0/255, alpha: 1) let priceOfCrypto = Double(cryptoCurrencies[indexPath.row].price_usd) //formating the cells if let this_cell = cell { this_cell.detailTextLabel?.text = "$" + String(format:"%.2f",priceOfCrypto!) this_cell.detailTextLabel?.textColor = UIColor.white this_cell.textLabel?.text = cryptoCurrencies[indexPath.row].name this_cell.textLabel?.textColor = UIColor.init(red: 189.0/255, green: 199.0/255, blue: 193.0/55, alpha: 1.0) this_cell.textLabel?.font = UIFont.systemFont(ofSize: 15) this_cell.backgroundColor = UIColor.init(red: 18.0/255, green: 28.0/255, blue: 50.0/255, alpha: 1) this_cell.layer.borderWidth = 0.3 this_cell.layer.borderColor = UIColor.black.cgColor this_cell.selectedBackgroundView = bgColorView this_cell.accessoryType = .detailDisclosureButton } // if(indexPath.row % 2 == 0) // { // cell!.backgroundColor = UIColor.init(red: 18.0/255, green: 28.0/255, blue: 50.0/255, alpha: 1) // } // else // { // cell!.backgroundColor = UIColor.init(red: 20.0/255, green: 30.0/255, blue: 52.0/255, alpha: 1) // } return cell! } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let controller = MoreDataController() controller.setCryptoData(cryptoDataReference: cryptoCurrencies[indexPath.row]) navigationController?.pushViewController(controller, animated: true) } }
// // MyAccCS_Collection.swift // YumaApp // // Created by Yuma Usa on 2018-06-15. // Copyright © 2018 Yuma Usa. All rights reserved. // import UIKit extension MyAccCS_ViewController: UICollectionViewDelegate, UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return store.creditSlips.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! MyAccCS_Cell cell.values(orderSlip: store.creditSlips[indexPath.item]) if self.view.frame.width > 500 { cell.wideScreen = true } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) UIView.animate(withDuration: 0.12, delay: 0, options: [], animations: { cell!.contentView.backgroundColor = .red }) { (done) in cell?.contentView.backgroundColor = .clear } store.flexView(view: cell!) // let vc = UIStoryboard(name: "CustomerOrders", bundle: nil).instantiateViewController(withIdentifier: "OrderDetailsViewController") as! OrderDetailsViewController if store.creditSlips.count > 0 { // vc.order = store.creditSlips[indexPath.item] // if store.creditSlips.count > 0 // { // vc.details = store.creditSlips[indexPath.item] // } } // self.present(vc, animated: false, completion: nil) } }
// // ArticlePageController.swift // News // // Created by Kirill Kungurov on 14.03.2020. // Copyright © 2020 Kirill Kungurov. All rights reserved. // import Kingfisher import UIKit final class ArticlePageController: UIViewController { var article: Article? @IBOutlet private var articleImage: UIImageView! @IBOutlet private var articleAuthor: UILabel! @IBOutlet private var aritcleDate: UILabel! @IBOutlet private var articleContent: UILabel! override func viewDidLoad() { super.viewDidLoad() guard let article = self.article else { return } aritcleDate.text = article.date articleAuthor.text = article.author articleContent.text = article.description articleImage.kf.setImage(with: article.imageUrl) self.title = article.title } @IBAction private func buttonTapped(_ sender: UIButton) { guard let viewController = UIStoryboard(name: "Main", bundle: nil) .instantiateViewController(withIdentifier: "OriginalArticleController") as? OriginalArticleController else { return } viewController.baseUrl = article?.articleUrl viewController.articleTitle = article?.title navigationController?.pushViewController(viewController, animated: true) } }
// // MenuListView.swift // HuliPizza // // Created by Felix Lin on 5/3/20. // Copyright © 2020 Felix Lin. All rights reserved. // import SwiftUI struct MenuListView: View { var body: some View { VStack { Text("Menu") List(0 ..< 5) { item in HStack(alignment: .top, spacing: 15) { Image("1_100w") VStack { Text("Huli Chicken Pizza") HStack { ForEach(0 ..< 4) { item in Image("Pizza Slice") } } } Spacer() } } } } } struct MenuListView_Previews: PreviewProvider { static var previews: some View { MenuListView() } }
// // Validate.swift // Wasmer / WebAssembly // // Created by Helge Heß. // Copyright © 2021 ZeeZide GmbH. All rights reserved. // import struct Foundation.Data import CWasmer public extension WebAssembly { /** * Validate whether the given `Data` object contains a valid `Wasm` module. * * - Parameters: * - data: A `Data` object containing WebAssembly binary code. * - Returns: `true` if valid, `false` otherwise */ static func validate(_ data: Data) -> Bool { return data.withUnsignedBytes { typed in return wasmer_validate(typed.baseAddress, UInt32(typed.count)) } } /** * Validate whether the given byte array contains a valid `Wasm` module. * * - Parameters: * - data: A `Data` object containing WebAssembly binary code. * - Returns: `true` if valid, `false` otherwise */ static func validate(_ data: [ UInt8 ]) -> Bool { return data.withUnsignedBytes { typed in return wasmer_validate(typed.baseAddress, UInt32(typed.count)) } } }
// // TopVideoController.swift // Tourney // // Created by Will Cohen on 7/30/19. // Copyright © 2019 Will Cohen. All rights reserved. // // View controller after a user clicks on leaderboard icon. Video displays on the // users screen import UIKit import AVKit class TopVideoController: UIViewController { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var previewVideoView: UIView! var post: Post! var player : AVPlayer! var avPlayerLayer : AVPlayerLayer! var timer = Timer() override func viewDidLayoutSubviews() { self.activityIndicator.startAnimating() super.viewDidLayoutSubviews() avPlayerLayer.frame = previewVideoView.layer.bounds; } override func viewDidAppear(_ animated: Bool) { //player.play() self.activityIndicator.stopAnimating() } func scheduledTimerWithTimeInterval(){ // Scheduling timer to Call the function "updateCounting" with the interval of 1 seconds timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: Selector(("updateCounting")), userInfo: nil, repeats: true) } @objc func updateCounting(){ print("sdf") player.play() } override func viewDidLoad() { super.viewDidLoad(); print("what hapepned dude: \(post.videoLink)") /* let playerItem = CachingPlayerItem(url: URL(string: post.videoLink)!) player = AVPlayer(playerItem: playerItem) avPlayerLayer = AVPlayerLayer(player: player); avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill; player.automaticallyWaitsToMinimizeStalling = false previewVideoView.layer.addSublayer(avPlayerLayer); NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player.currentItem, queue: .main) { [weak self] _ in self?.player?.seek(to: CMTime.zero); self?.player?.play(); }*/ let videoURL = URL(string: post.videoLink) player = AVPlayer(url: videoURL!) avPlayerLayer = AVPlayerLayer(player: player) avPlayerLayer.frame = self.previewVideoView.layer.bounds avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill; player.automaticallyWaitsToMinimizeStalling = false self.previewVideoView.layer.addSublayer(avPlayerLayer) player.play() scheduledTimerWithTimeInterval() } @IBAction func backButtonPressed(_ sender: Any) { self.dismiss(animated: true, completion: nil) } }
// // TabViewControllerProtocol.swift // OnTheMap // // Created by Edwin Chia on 6/6/16. // Copyright © 2016 Edwin Chia. All rights reserved. // protocol TabViewControllerProtocol { func enableUI(enabled: Bool) func reloadDataDisplayed() }
// // ColorPhotoVC.swift // Pilly // // Created by Murtaza on 20/04/2019. // Copyright © 2019 Murtaza. All rights reserved. // import UIKit protocol selectedColorDelegate:class { func selectedColor(colorObj : Colours) func selectedImage(image: UIImage) func sendvalue(value:String) } struct Colours { var colorName : String var color : UIColor } class ColorPhotoVC: UIViewController , UITableViewDelegate, UITableViewDataSource,UIImagePickerControllerDelegate , UINavigationControllerDelegate{ var colorslected:Bool = false var nowColurObj:Colours? weak var delegate: selectedColorDelegate! @IBOutlet weak var mainImage: RoundImageView! var photodelegate:selectedColorDelegate? @IBOutlet weak var choosePhotolabel: UILabel! var lastSelection:Int = -1 var imagePicker = UIImagePickerController() @IBOutlet weak var tableView : UITableView!{ didSet{ tableView.delegate = self tableView.dataSource = self } } var coloursArray = [Colours]() override func viewDidLoad() { super.viewDidLoad() mainImage.alpha = 0 choosePhotolabel.alpha = 1 imagePicker.delegate = self coloursArray.append(Colours.init(colorName: "red", color: UIColor.red)) coloursArray.append(Colours.init(colorName: "blue", color: UIColor.blue)) coloursArray.append(Colours.init(colorName: "Orange", color: UIColor.orange)) coloursArray.append(Colours.init(colorName: "black", color: UIColor.black)) coloursArray.append(Colours.init(colorName: "purple", color: UIColor.purple)) coloursArray.append(Colours.init(colorName: "PINK", color: UIColor.PINK)) coloursArray.append(Colours.init(colorName: "green", color: UIColor.green)) coloursArray.append(Colours.init(colorName: "gray", color: UIColor.gray)) coloursArray.append(Colours.init(colorName: "yellow", color: UIColor.yellow)) coloursArray.append(Colours.init(colorName: "Dark", color: UIColor.darkText)) } @IBAction func saveBtn(_ sender: Any) { self.navigationController?.popViewController(animated: true) delegate?.sendvalue(value: "Helo Abc") if colorslected { delegate?.selectedColor(colorObj:self.nowColurObj!) }else{ delegate?.selectedImage(image: mainImage.image!) } } @IBAction func closeBtn(_ sender: Any) { self.dismiss(animated: false, completion: nil) } @IBAction func ChooseBtn(_ sender: Any) { self.openMedia() } } func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "photo" { let dvc = segue.destination as! AddMedicationVC //dvc.seletedImg = mainima } } extension ColorPhotoVC { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return coloursArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! colorCell cell.colorObj = self.coloursArray[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print(self.coloursArray[indexPath.row]) self.mainImage.alpha = 0 self.choosePhotolabel.alpha = 1 colorslected = true self.nowColurObj = self.coloursArray[indexPath.row] self.tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { self.tableView.cellForRow(at: indexPath)?.accessoryType = .none } //<--------------------------- Open Media ----------------------> func openMedia(){ let alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in self.openCamera() })) alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in self.openGallary() })) alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } func openCamera() { if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerController.SourceType.camera)) { imagePicker.sourceType = UIImagePickerController.SourceType.camera imagePicker.allowsEditing = true self.present(imagePicker, animated: true, completion: nil) } else { let alert = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } } func openGallary() { imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary imagePicker.allowsEditing = true self.present(imagePicker, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { var selectedImage: UIImage! if let editedImage = info[.editedImage] as? UIImage { selectedImage = editedImage picker.dismiss(animated: true, completion: nil) } else if let originalImage = info[.originalImage] as? UIImage { selectedImage = originalImage picker.dismiss(animated: true, completion: nil) } mainImage.alpha = 1 choosePhotolabel.alpha = 0 mainImage.image = selectedImage colorslected = false picker.dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } }
// // CountryInfoViewDelegate.swift // FlagQuiz // // Created by Soohan Lee on 2020/01/22. // Copyright © 2020 Soohan Lee. All rights reserved. // import UIKit protocol CountryInfoViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) }
// // AppDelegate.swift // MenubarPopupDemoApp // // Created by Heeseung Seo on 2015. 8. 6.. // Copyright © 2015년 Seorenn. All rights reserved. // import Cocoa import SRStatusItemPopupController @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! var popup: SRStatusItemPopupController? func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application let viewController = ViewController(nibName: "ViewController", bundle: nil) let image = NSImage(named: NSImage.folderName) self.popup = SRStatusItemPopupController(viewController: viewController, image: image, alternateImage: nil, autoHide: true) viewController.popup = self.popup } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } @IBAction func pressedOpenPopoverButton(_ sender: AnyObject) { self.popup!.showPopover() } @IBAction func pressedClosePopoverButton(_ sender: AnyObject) { self.popup!.hidePopover() } }
// // MovieCollectionViewCell.swift // MoviesListingApp // // Created by tanuj on 12/10/19. // Copyright © 2019 Tanuj Sharma. All rights reserved. // import UIKit import SDWebImage class MovieCollectionViewCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var movieTitle: UILabel! func configUIWithData (searchdataSource: Search) { imageView.sd_imageIndicator = SDWebImageActivityIndicator.gray imageView.sd_setImage(with: URL(string: searchdataSource.poster)) movieTitle.text = searchdataSource.title } }
// // SlideMenuController+NODTrasition.swift // NuoDunProject // // Created by redhat' iMac on 15/6/28. // Copyright (c) 2015年 lxzhh. All rights reserved. // import Foundation enum NODSlideMainViewType : String{ case NODSlideMainViewTypeHome = "NODConstructionController" case NODSlideMainViewTypeFinacial = "NODFiancialController" case NODSlideMainViewTypeLabour = "NODLabourController" case NODSlideMainViewTypeSetting = "NODSettingVC" case NODSlideMainViewTypeSchedule = "NODProgressController" } extension SlideMenuController { func slideMainViewWithType(type :NODSlideMainViewType){ let vc : NODBaseMainViewController = UIStoryboard(name: "NODStoryboard", bundle: nil).instantiateViewControllerWithIdentifier(type.rawValue) as! NODBaseMainViewController let navc = UINavigationController(rootViewController: vc) self.slideMenuController()?.changeMainViewController(navc, close: true) } }
// swift-tools-version:5.2 import PackageDescription let package = Package( name: "EmealKit", platforms: [ .macOS(.v10_15), .iOS(.v13) ], products: [ .library( name: "EmealKit", targets: ["EmealKit"]), ], dependencies: [ .package(url: "https://github.com/alexaubry/HTMLString.git", from: "5.0.0"), .package(url: "https://github.com/sharplet/Regex.git", from: "2.1.0"), ], targets: [ .target( name: "EmealKit", dependencies: ["HTMLString", "Regex"]), .testTarget( name: "EmealKitTests", dependencies: ["EmealKit"]), ] )
// // ResultsModel.swift // MemClassifier // // Created by Bao Van on 6/20/20. // Copyright © 2020 Bao Van. All rights reserved. // import Foundation import UIKit class ResultsModel { var image: UIImage var predictionClass: String init(fromImage image: UIImage, withPredictionClass predictionClass: String) { self.image = image self.predictionClass = predictionClass } }
// // FavoritesViewController.swift // Captioned // // Created by Przemysław Pająk on 08.01.2018. // Copyright © 2018 FEARLESS SPIDER. All rights reserved. // import UIKit import Alamofire import AlamofireImage import Bolts import SVPullToRefresh import ZFDragableModalTransition import MHPrettyDate public class FavoritesViewController: UIViewController, FavoritesView { var presenter: FavoritesPresenter? var configurator = FavoritesConfiguratorImplementation() @IBOutlet weak var tableView: UITableView! var tableData:[Post] = [] var animator: ZFModalTransitionAnimator! public override func viewDidLoad() { super.viewDidLoad() configurator.configure(favoritesViewController: self) self.tableView.register(UINib(nibName: "PostViewCell", bundle: nil), forCellReuseIdentifier: "postCell") self.tableView.addPullToRefresh {() -> Void in self.tableData.removeAll() self.tableView.reloadData() self.fetchFavoritePostList().continueOnSuccessWith(block: { (task: BFTask!) -> AnyObject! in if let result = task.result as? [[String: AnyObject]] { print("Post count \(result.count)") for data in result { let post:Post = Post(JSON:data)! self.tableData.append(post) } } self.tableView.setNeedsLayout() self.tableView.layoutIfNeeded() self.tableView.reloadData() self.tableView.pullToRefreshView.stopAnimating() return nil }) } } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tableView.triggerPullToRefresh() } public override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func fetchFavoritePostList() -> BFTask<AnyObject>! { let completionSource = BFTaskCompletionSource<AnyObject>() Alamofire.request(Captioned.Router.favoriteList()).validate().responseJSON { response in switch response.result { case .success(let json): completionSource.set(result: json as AnyObject) case .failure(let error): print("Request failed with error: \(error)") completionSource.set(error: NSError(domain: "captioned.favoriteList", code: 1, userInfo: nil)) } } return completionSource.task } } extension FavoritesViewController: UITableViewDelegate { public func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 635 } public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } } extension FavoritesViewController: UITableViewDataSource { public func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int { return self.tableData.count } public func tableView(_ tableView:UITableView, cellForRowAt indexPath:IndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath as IndexPath) as! PostViewCell cell.delegate = self if let post: Post = self.tableData[indexPath.row] { if let profilePictureURL = post.user().profilePictureURL() { let placeholderImage = UIImage(named: "profile")! cell.avatarView.af_setImage(withURL: profilePictureURL as URL, placeholderImage: placeholderImage) } if let photoURL = post.photoURL() { let placeholderImage = UIImage(named: "profile")! cell.mediaView.af_setImage(withURL: photoURL as URL, placeholderImage: placeholderImage) } cell.likesCountLabel.text = String(post.likes_count) cell.commentsCountLabel.text = String(post.comments_count) cell.shareCountLabel.text = "" cell.userNameLabel.text = post.user().fullname() cell.postDateLabel.text = MHPrettyDate.prettyDate(from: post.postDate() as Date!, with:MHPrettyDateLongRelativeTime) cell.delegate = self cell.post = post var multiplier = post.comments_count if (multiplier! > 2) { multiplier = 2 } let heightConstraint = NSLayoutConstraint(item: cell.commentsTableView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: CGFloat(multiplier!)*40) if (post.comments_count > 0) { cell.commentsTableView.addConstraint(heightConstraint) } else { cell.commentsTableView.removeConstraints(cell.commentsTableView.constraints) } cell.commentsTableView.updateConstraints() cell.commentsTableView.reloadData() cell.layoutIfNeeded() return cell } return cell } } extension FavoritesViewController: PostViewCellDelegate { public func didSelectAvatar(postViewCell: PostViewCell) { } public func didSelectComments(postViewCell: PostViewCell) { //let commentsViewController = Storyboard.commentsViewController() //let post: Post = postViewCell.post //commentsViewController.post = post //navigationController?.pushViewController(commentsViewController, animated: true) } public func didSelectShare(postViewCell: PostViewCell) { let textToShare = "Captioned is awesome! Check out this website about it!" if let myWebsite = NSURL(string: "http://www.captionedapp.com/") { let objectsToShare = [textToShare, myWebsite] as [Any] let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) activityVC.popoverPresentationController?.sourceView = postViewCell self.present(activityVC, animated: true, completion: nil) } } public func didSelectLike(postViewCell: PostViewCell) { Alamofire.request(Captioned.Router.like(id: postViewCell.post.postID())) .validate() .responseJSON { response in switch response.result { case .success(let JSON): print("Success with JSON: \(JSON)") self.presentBasicAlertWithTitle(title: "Liked") self.tableView.triggerPullToRefresh() case .failure(let error): print("Request failed with error: \(error)") self.presentBasicAlertWithTitle(title: "Sent data are incorrect") } } } }
// // GroupType.swift // strolling-of-time-ios // // Created by 강수진 on 2019/08/19. // Copyright © 2019 wiw. All rights reserved. // import UIKit enum GroupType: String, CaseIterable { case study = "스터디" case exercise = "운동" case debate = "토론" case coding = "개발" case writing = "글쓰기" var color: UIColor { switch self { case .study: return #colorLiteral(red: 1, green: 0.3058823529, blue: 0.4705882353, alpha: 1) case .exercise: return #colorLiteral(red: 1, green: 0.8156862745, blue: 0.262745098, alpha: 1) case .debate: return #colorLiteral(red: 0.137254902, green: 0.8235294118, blue: 0.7450980392, alpha: 1) case .coding: return #colorLiteral(red: 0.2196078431, green: 0.5176470588, blue: 1, alpha: 1) case .writing: return #colorLiteral(red: 0.4039215686, green: 0.4392156863, blue: 1, alpha: 1) } } var ovalImage: UIImage { switch self { case .study: return #imageLiteral(resourceName: "ovalPink") default: return #imageLiteral(resourceName: "ovalBlack") } } }
// // DarrellLog.swift // PcapngPrint // // Created by Darrell Root on 2/6/20. // Copyright © 2020 net.networkmom. All rights reserved. // import Foundation import Logging // initially this is a copy of StreamLogHandler built into // the Apple Logging API. My own copy will let me modify public struct DarrellLogHandler: LogHandler { private let label: String public var logLevel: Logger.Level = .error // set to .info or .debug for troubleshooting private var prettyMetadata: String? public var metadata: Logger.Metadata = [:] public subscript(metadataKey metadataKey: String) -> Logger.Metadata.Value? { get { return self.metadata[metadataKey] } set { self.metadata[metadataKey] = newValue } } init(label: String) { self.label = label } public func log(level: Logger.Level, message: Logger.Message, metadata: Logger.Metadata?, file: String, function: String, line: UInt) { print("PcapngPrint: \(level) \(message)") } private func prettify(_ metadata: Logger.Metadata) -> String? { return !metadata.isEmpty ? metadata.map { "\($0)=\($1)" }.joined(separator: " ") : nil } private func timestamp() -> String { var buffer = [Int8](repeating: 0, count: 255) var timestamp = time(nil) let localTime = localtime(&timestamp) strftime(&buffer, buffer.count, "%Y-%m-%dT%H:%M:%S%z", localTime) return buffer.withUnsafeBufferPointer { $0.withMemoryRebound(to: CChar.self) { String(cString: $0.baseAddress!) } } } }
import UIKit import RxSwift import RxCocoa import ThemeKit import SectionsTableView import ComponentKit import HUD protocol IMarketListViewModel { var viewItemDataDriver: Driver<MarketModule.ListViewItemData?> { get } var loadingDriver: Driver<Bool> { get } var syncErrorDriver: Driver<Bool> { get } var scrollToTopSignal: Signal<()> { get } func refresh() } class MarketListViewController: ThemeViewController { private let listViewModel: IMarketListViewModel private let disposeBag = DisposeBag() let tableView = SectionsTableView(style: .plain) private let spinner = HUDActivityView.create(with: .medium24) private let errorView = PlaceholderViewModule.reachabilityView() private let refreshControl = UIRefreshControl() private var viewItems: [MarketModule.ListViewItem]? var viewController: UIViewController? { self } var headerView: UITableViewHeaderFooterView? { nil } var emptyView: UIView? { nil } var refreshEnabled: Bool { true } func topSections(loaded: Bool) -> [SectionProtocol] { [] } init(listViewModel: IMarketListViewModel) { self.listViewModel = listViewModel super.init() if let watchViewModel = listViewModel as? IMarketListWatchViewModel { subscribe(disposeBag, watchViewModel.favoriteDriver) { [weak self] in self?.showAddedToWatchlist() } subscribe(disposeBag, watchViewModel.unfavoriteDriver) { [weak self] in self?.showRemovedFromWatchlist() } subscribe(disposeBag, watchViewModel.failDriver) { error in HudHelper.instance.show(banner: .error(string: error.localized)) } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() refreshControl.tintColor = .themeLeah refreshControl.alpha = 0.6 refreshControl.addTarget(self, action: #selector(onRefresh), for: .valueChanged) view.addSubview(tableView) tableView.snp.makeConstraints { maker in maker.edges.equalToSuperview() } if #available(iOS 15.0, *) { tableView.sectionHeaderTopPadding = 0 } tableView.separatorStyle = .none tableView.backgroundColor = .clear tableView.sectionDataSource = self if let emptyView = emptyView { view.addSubview(emptyView) emptyView.snp.makeConstraints { maker in maker.edges.equalTo(view.safeAreaLayoutGuide) } } view.addSubview(spinner) spinner.snp.makeConstraints { maker in maker.center.equalToSuperview() } spinner.startAnimating() view.addSubview(errorView) errorView.snp.makeConstraints { maker in maker.edges.equalTo(view.safeAreaLayoutGuide) } errorView.configureSyncError(action: { [weak self] in self?.onRetry() }) subscribe(disposeBag, listViewModel.viewItemDataDriver) { [weak self] in self?.sync(viewItemData: $0) } subscribe(disposeBag, listViewModel.loadingDriver) { [weak self] loading in self?.spinner.isHidden = !loading } subscribe(disposeBag, listViewModel.syncErrorDriver) { [weak self] visible in self?.errorView.isHidden = !visible } subscribe(disposeBag, listViewModel.scrollToTopSignal) { [weak self] in self?.scrollToTop() } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if refreshEnabled { tableView.refreshControl = refreshControl } } @objc private func onRetry() { refresh() } @objc private func onRefresh() { refresh() DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in self?.refreshControl.endRefreshing() } } private func refresh() { listViewModel.refresh() } private func sync(viewItemData: MarketModule.ListViewItemData?) { viewItems = viewItemData?.viewItems if let viewItems = viewItems, viewItems.isEmpty { emptyView?.isHidden = false } else { emptyView?.isHidden = true } if let viewItems = viewItems, !viewItems.isEmpty { tableView.bounces = true } else { tableView.bounces = false } if let viewItemData = viewItemData { tableView.reload(animated: viewItemData.softUpdate) } else { tableView.reload() } } func onSelect(viewItem: MarketModule.ListViewItem) { guard let uid = viewItem.uid, let module = CoinPageModule.viewController(coinUid: uid) else { HudHelper.instance.show(banner: .attention(string: "market.project_has_no_coin".localized)) return } viewController?.present(module, animated: true) } private func rowActions(index: Int) -> [RowAction] { guard let watchListViewModel = listViewModel as? IMarketListWatchViewModel else { return [] } guard let isFavorite = watchListViewModel.isFavorite(index: index) else { return [] } let type: RowActionType let iconName: String let action: (UITableViewCell?) -> () if isFavorite { type = .destructive iconName = "star_off_24" action = { _ in watchListViewModel.unfavorite(index: index) } } else { type = .additive iconName = "star_24" action = { _ in watchListViewModel.favorite(index: index) } } return [ RowAction( pattern: .icon(image: UIImage(named: iconName)?.withTintColor(type.iconColor), background: type.backgroundColor), action: action ) ] } private func scrollToTop() { tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .bottom, animated: true) } func showAddedToWatchlist() { HudHelper.instance.show(banner: .addedToWatchlist) } func showRemovedFromWatchlist() { HudHelper.instance.show(banner: .removedFromWatchlist) } } extension MarketListViewController: SectionsDataSource { func buildSections() -> [SectionProtocol] { let headerState: ViewState<UITableViewHeaderFooterView> if let headerView = headerView, let viewItems = viewItems, !viewItems.isEmpty { headerState = .static(view: headerView, height: .heightSingleLineCell) } else { headerState = .margin(height: 0) } return topSections(loaded: viewItems != nil) + [ Section( id: "coins", headerState: headerState, footerState: .marginColor(height: .margin32, color: .clear) , rows: viewItems.map { viewItems in viewItems.enumerated().map { index, viewItem in MarketModule.marketListCell( tableView: tableView, backgroundStyle: .transparent, listViewItem: viewItem, isFirst: false, isLast: index == viewItems.count - 1, rowActionProvider: { [weak self] in self?.rowActions(index: index) ?? [] }, action: { [weak self] in self?.onSelect(viewItem: viewItem) } ) } } ?? [] ) ] } }
//: Playground - noun: a place where people can play import UIKit var favoriteSports = ["football", "basketball", "tennis"] favoriteSports.append("volleyball") favoriteSports
// // OnboardingManagerTests.swift // DeliriumOverTests // // Created by mate.redecsi on 2020. 10. 05.. // Copyright © 2020. rmatesz. All rights reserved. // import Foundation import RxSwift import XCTest @testable import DeliriumOver class OnboardingManagerTests: XCTestCase { private let userDefaults = UserDefaults(suiteName: "unitTest")! private lazy var underTest = OnboardingManager(userDefaults: userDefaults) private var disposeBag = DisposeBag() override func setUp() { userDefaults.removeObject(forKey: "OnboardingFinishedForPage_reports") } func testLoadOnboardingForReports() { let waitingForDispose = expectation(description: "waiting for dipose") var counter = 0 underTest.loadOnboarding(page: .reports) .subscribeOn(MainScheduler()) .observeOn(MainScheduler()) .subscribe(onNext: { (actual) in let expected: [OnboardingManager.Onboarding] switch counter { case 0: expected = [OnboardingManager.Onboarding.addConsumption, .manageConsumptions, .disclaimer, .setupSessionData] case 1: expected = [OnboardingManager.Onboarding.addConsumption, .manageConsumptions, .setupSessionData] default: expected = [] } XCTAssertEqual(expected, actual, "Assertion #\(counter) failed!") counter = counter + 1 if counter == 1 { self.underTest.markFinished(page: .reports, onboarding: .disclaimer) } else if counter > 1 { waitingForDispose.fulfill() } }, onCompleted: { XCTFail() }) .disposed(by: disposeBag) waitForExpectations(timeout: 2) } }
import RxSwift import RxRelay import MarketKit class NftCollectionOverviewService { let blockchainType: BlockchainType private let providerCollectionUid: String private let nftMetadataManager: NftMetadataManager private let marketKit: MarketKit.Kit private var disposeBag = DisposeBag() private let stateRelay = PublishRelay<DataStatus<Item>>() private(set) var state: DataStatus<Item> = .loading { didSet { stateRelay.accept(state) } } init(blockchainType: BlockchainType, providerCollectionUid: String, nftMetadataManager: NftMetadataManager, marketKit: MarketKit.Kit) { self.blockchainType = blockchainType self.providerCollectionUid = providerCollectionUid self.nftMetadataManager = nftMetadataManager self.marketKit = marketKit sync() } private func sync() { disposeBag = DisposeBag() state = .loading nftMetadataManager.collectionMetadataSingle(blockchainType: blockchainType, providerUid: providerCollectionUid) .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .userInitiated)) .subscribe(onSuccess: { [weak self] collection in let item = Item(collection: collection) self?.state = .completed(item) }, onError: { [weak self] error in self?.state = .failed(error) }) .disposed(by: disposeBag) } } extension NftCollectionOverviewService { var stateObservable: Observable<DataStatus<Item>> { stateRelay.asObservable() } var blockchain: Blockchain? { try? marketKit.blockchain(uid: blockchainType.uid) } var providerLink: ProviderLink? { guard let title = nftMetadataManager.providerTitle(blockchainType: blockchainType), let link = nftMetadataManager.collectionLink(blockchainType: blockchainType, providerUid: providerCollectionUid) else { return nil } return ProviderLink(title: title, url: link) } func resync() { sync() } } extension NftCollectionOverviewService { struct Item { let collection: NftCollectionMetadata } }
// // MemoryGame.swift // Memorize // // Created by Elina Mansurova on 2021-09-08. // import Foundation struct MemoryGame<CardContent> where CardContent: Equatable { private(set) var cards: Array<Card> private var indexOfFaceUpCard: Int? { get { cards.indices.filter { cards[$0].isFaceUp }.one } set { cards.indices.forEach { cards[$0].isFaceUp = ($0 == newValue) } } } mutating func choose(_ card: Card) { if let chosenIndex = cards.firstIndex(where: { $0.id == card.id }), !cards[chosenIndex].isFaceUp, !cards[chosenIndex].isMatched { if let potentialMatchIndex = indexOfFaceUpCard { if cards[chosenIndex].content == cards[potentialMatchIndex].content { cards[chosenIndex].isMatched = true cards[potentialMatchIndex].isMatched = true } cards[chosenIndex].isFaceUp = true } else { indexOfFaceUpCard = chosenIndex } } } init(numberOfPairsOfCards: Int, createCardContent: (Int) -> CardContent) { cards = [] // add number of pairs of cards * 2 cards to cards array for pairIndex in 0..<numberOfPairsOfCards { let content: CardContent = createCardContent(pairIndex) cards.append(Card(id: pairIndex*2, content: content)) cards.append(Card(id: pairIndex*2+1, content: content)) } } //by nesting Card struct we put it inside the Memory Game: MemoryGame.Card struct Card: Identifiable { let id: Int var isFaceUp = true var isMatched = false let content: CardContent } } extension Array { var one: Element? { if count == 1 { return first } else { return nil } } }
// // ArcadeScreen.swift // aoc2019 // // Created by Shawn Veader on 12/13/19. // Copyright © 2019 Shawn Veader. All rights reserved. // import Foundation class ArcadeScreen { enum Tile: Int { case empty = 0 case wall = 1 case block = 2 case paddle = 3 case ball = 4 var draw: String { switch self { case .empty: return " " case .wall: return "▓" case .block: return "░" case .paddle: return "═" case .ball: return "◍" } } } var grid: [Coordinate: Tile] = [Coordinate: Tile]() var ballLocation: Coordinate? { grid.filter({ $0.value == .ball }).first?.key } var paddleLocation: Coordinate? { grid.filter({ $0.value == .paddle }).first?.key } var centerX: Int { let maxX = grid.keys.max(by: { $0.x < $1.x })?.x ?? 1 return maxX / 2 } func draw(input: [Int]) { let screenInput = input.chunks(size: 3) for tileInput in screenInput { guard tileInput.count == 3 else { print("Chunk has \(tileInput.count), which isn't right.") continue } if let tile = ArcadeScreen.Tile(rawValue: tileInput[2]) { let location = Coordinate(x: tileInput[0], y: tileInput[1]) draw(tile: tile, at: location) } else { print("Could not draw output: \(tileInput)") } } } /// Draw the a tile at a location func draw(tile: Tile, at location: Coordinate) { grid[location] = tile } /// Is there a "solid" object at the point (ie: block or wall) func solid(at location: Coordinate) -> Bool { guard let tile = grid[location] else { return false } switch tile { case .block, .wall: return true default: return false } } @discardableResult func printScreen() -> String { let ranges = printRanges() let xRange = ranges.0 let yRange = ranges.1 var output = " " xRange.forEach { output += "\($0 % 10)" } output += "\n" for y in yRange { output += "\(y % 10)" for x in xRange { let location = Coordinate(x: x, y: y) if let tile = grid[location] { output += tile.draw } else { output += Tile.empty.draw } } output += "\n" } print(output) return output } func printPath(of ball: PongBall) { let ranges = printRanges() let xRange = ranges.0 let yRange = ranges.1 var output = " " xRange.forEach { output += "\($0 % 10)" } output += "\n" for y in yRange { output += "\(y % 10)" for x in xRange { let location = Coordinate(x: x, y: y) if ball.bounces.contains(location) { output += "*" } else if ball.pathSteps.contains(location) { output += "¤" } else if let tile = grid[location] { output += tile.draw } else { output += Tile.empty.draw } } output += "\n" } print(output) } func printRanges() -> (Range<Int>, Range<Int>) { let usedCoordinates = grid.keys let minX = usedCoordinates.min(by: { $0.x < $1.x })?.x ?? 0 let maxX = usedCoordinates.max(by: { $0.x < $1.x })?.x ?? 0 let minY = usedCoordinates.min(by: { $0.y < $1.y })?.y ?? 0 let maxY = usedCoordinates.max(by: { $0.y < $1.y })?.y ?? 0 let xRange = min(0, minX)..<(maxX + 1) let yRange = min(0, minY)..<(maxY + 1) return (xRange, yRange) } }
import PackageDescription let package = Package( name: "Zeal", dependencies: [ .Package(url: "https://github.com/Zewo/HTTPParser.git", majorVersion: 0, minor: 1), .Package(url: "https://github.com/Zewo/CLibvenice.git", majorVersion: 0, minor: 1), .Package(url: "https://github.com/Zewo/CURIParser.git", majorVersion: 0, minor: 1), .Package(url: "https://github.com/Zewo/CHTTPParser.git", majorVersion: 0, minor: 1), .Package(url: "https://github.com/Zewo/Core.git", majorVersion: 0, minor: 1), .Package(url: "https://github.com/Zewo/Venice.git", majorVersion: 0, minor: 1), .Package(url: "https://github.com/Zewo/HTTP.git", majorVersion: 0, minor: 1), .Package(url: "https://github.com/Zewo/HTTPParser.git", majorVersion: 0, minor: 1) ], targets: [ Target(name: "Zeal", dependencies: []), Target(name: "ZealExample", dependencies: [.Target(name: "Zeal")]) ] )
// // MockSettingsDelegate.swift // WeatherAppTests // // Created by EasyPay on 20/10/18. // Copyright © 2018 Darshan Patel. All rights reserved. // import Foundation import UIKit @testable import WeatherApp class MockSettingsDelegate: SettingDelegate { var viewController: UIViewController! func updateHomeController(_ viewController: SettingsVC) { self.viewController = viewController } }
// // HFVideoView.swift // Pods // // Created by DragonCherry on 7/12/16. // // import UIKit import MediaPlayer import HFUtility import TinyLog open class HFVideoView: UIView { fileprivate var playerLayer: AVPlayerLayer? fileprivate var player: AVPlayer? fileprivate var URL: Foundation.URL? open var resource: Foundation.URL? { set(videoURL) { player?.pause() if let videoURL = videoURL { playerLayer?.removeFromSuperlayer() URL = videoURL player = AVPlayer(playerItem: AVPlayerItem(url: videoURL)) playerLayer = AVPlayerLayer(player: player) playerLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill playerLayer!.masksToBounds = true layer.addSublayer(playerLayer!) } else { URL = nil pause() player = nil } } get { return URL } } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } public override init(frame: CGRect) { super.init(frame: frame) commonInit() } fileprivate func commonInit() { self.loadViews() } open override func layoutSubviews() { super.layoutSubviews() layoutViews() } internal func loadViews() { // load views } internal func layoutViews() { // layout views playerLayer?.frame.size = self.size } } // MARK: HFVideoView APIs extension HFVideoView { public func pause() { log("\(#function)") player?.pause() } public func stop() { log("\(#function)") player?.seek(to: CMTimeMake(0, 1)) player?.pause() } public func play() { log("\(#function)") player?.play() } public func seek(_ time: TimeInterval) { log("\(#function)") } }
// // Copyright 2014 ESRI // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // You may freely redistribute and use this sample code, with or // without modification, provided you include the original copyright // notice and use restrictions. // // See the use restrictions at http://help.arcgis.com/en/sdk/10.0/usageRestrictions.htm // import UIKit import ArcGIS class ResultsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { //results are the attributes of the result of the geocode operation var results:[NSObject:AnyObject]! var tableView:UITableView! override func prefersStatusBarHidden() -> Bool { return true } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - Actions @IBAction func done(sender:AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } //MARK: - //MARK: - Table view methods func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } // Customize the number of rows in the table view. func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //if results is not nil and we have results, return that number return self.results.count ?? 0 } // Customize the appearance of table view cells. func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "Cell" var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: cellIdentifier) } // Set up the cell... //text is the key at the given indexPath let keyAtIndexPath = Array(self.results.keys)[indexPath.row] cell?.textLabel?.text = keyAtIndexPath as? String //detail text is the value associated with the key above if let detailValue: AnyObject? = self.results[keyAtIndexPath] { //figure out if the value is a NSDecimalNumber or NSString if detailValue is String { //value is a NSString, just set it cell?.detailTextLabel?.text = detailValue as? String } else if detailValue is NSDecimalNumber { //value is a NSDecimalNumber, format the result as a double cell?.detailTextLabel?.text = String(format: "%0.0f", detailValue as NSDecimalNumber) } else { //not a NSDecimalNumber or a NSString, cell?.detailTextLabel?.text = "N/A" } } return cell! } }
// // SearchMainStore.swift // GitWorld // // Created by jiaxin on 2019/7/8. // Copyright © 2019 jiaxin. All rights reserved. // import SwiftUI import Combine class SearchMainStore: BindableObject { var users = [FollowUser]() { didSet { didChange.send(self) } } var didChange = PassthroughSubject<SearchMainStore, Never>() func search(key: String) { apolloClient.fetch(query: SearchUserQuery(query: key), cachePolicy: .fetchIgnoringCacheData, queue: DispatchQueue.main) { (result, error) in if let nodes = result?.data?.search.nodes { var result = [FollowUser]() for node in nodes { if let user = node?.asUser { result.append(FollowUser(avatar: user.avatarUrl, name: user.login)) } } self.users = result } } } }
// Playground - noun: a place where people can play import UIKit /*: Say you have an array for which the i-th element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). */
// // ViewController.swift // GitPlayAround // // Created by Jing Li on 7/16/21. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func buttonClicked(_ sender: UIButton) { print("FINALLY 123 This is a Git play around") } }
// // HomeApi.swift // PrediCiclo // // Created by Jason Sa on 2/5/20. // Copyright © 2020 Zublime. All rights reserved. // import Foundation import Alamofire import AlamofireObjectMapper class HomeApi{ public func set_CreaCalendarioSiNoExiste(VC : UIViewController, callback: @escaping (_ success: Bool, _ callback:Create_if_not_exits_Model)->Void){ manager.request(url_PrediCiclo.URL_CREA_CALENDARIO_SINO, method: .post,parameters: aut_Prediciclo.CREDENCIALES_AUTH, encoding: URLEncoding.default, headers: preferencias.headers).responseObject{(response: DataResponse<Create_if_not_exits_Model>) in if let httpStatusCode = response.response?.statusCode { let status_request = Valida_Status.Valida_Status(Status: httpStatusCode, CurrentView: VC, Mensaje: response.error ?? nil) switch(status_request) { case true: switch response.result{ case .failure(let fail): print("Consultar status fail \(fail)") break case .success(let value): if value.status != 200 { callback(false,value) }else{ callback(true,value) } } break case false: break } } } } public func get_ObtenerCalendario(VC : UIViewController, callback: @escaping (_ success: Bool, _ callback:Calendar2_Model)->Void){ manager.request(url_PrediCiclo.URL_OBTENER_CALENDARIO, method: .post,parameters: aut_Prediciclo.CREDENCIALES_AUTH, encoding: URLEncoding.default, headers: preferencias.headers).responseObject{(response: DataResponse<Calendar2_Model>) in if let httpStatusCode = response.response?.statusCode { let status_request = Valida_Status.Valida_Status(Status: httpStatusCode, CurrentView: VC, Mensaje: response.error ?? nil) switch(status_request) { case true: switch response.result{ case .failure(let fail): print("Consultar status fail \(fail)") break case .success(let value): if value.status != 200 { callback(false,value) }else{ callback(true,value) } } break case false: break } } } } }
// // UserTableViewCell.swift // Hipstagram // // Created by MediaLab on 2/28/16. // Copyright © 2016 Bluyam Inc. All rights reserved. // import UIKit import Parse class UserTableViewCell: UITableViewCell { @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var userNameLabel: UILabel! var user: PFUser? { didSet { userNameLabel.text = user?.username if user!.objectForKey("profile_photo") != nil { let profileMedia = user!["profile_photo"] profileMedia.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in if imageData != nil { let image = UIImage(data:imageData!)! self.profileImageView.image = image } } } else { let image = UIImage(named: "default_profile") self.profileImageView.image = image } } } override func awakeFromNib() { super.awakeFromNib() profileImageView.layer.cornerRadius = 24 profileImageView.clipsToBounds = true // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
// // Copyright © 2021 Tasuku Tozawa. All rights reserved. // import UIKit extension UIPasteboard: Pasteboard { func set(_ text: String) { string = text } func get() -> String? { return string } }
// // HomeTableViewCell.swift // // // Created by CHUN MARTHA on 2017/4/2. // // import UIKit class HomeTableViewCell: UITableViewCell { @IBOutlet weak var avatar: UIButton! @IBOutlet weak var author: UILabel! @IBOutlet weak var identifier: UILabel! @IBOutlet weak var smallIcon: UIImageView! @IBOutlet weak var title: UILabel! @IBOutlet weak var detail: UILabel! @IBOutlet weak var category: UIButton! @IBOutlet weak var likeNumber: UILabel! override func awakeFromNib() { contentView.backgroundColor = Color.bgColor super.awakeFromNib() avatar.layer.borderColor = UIColor.lightGray.cgColor detail.textColor = UIColor.black.withAlphaComponent(0.5) } func populateCell(_ cell: HomeTableViewCell, withArticle article: Article) { if (article.author?.avatar != nil) { cell.avatar.sd_setBackgroundImage(with: URL(string: (article.author?.avatar)!), for: .normal) } else { cell.avatar.setBackgroundImage(#imageLiteral(resourceName: "default_avatar"), for: .normal) } cell.identifier.text = article.author?.identifier ?? "" cell.author.text = article.author?.userName ?? "匿名用户" cell.category.setTitle(article.category?.name, for: .normal) cell.smallIcon.sd_setImage(with: URL(string: article.smallIcon!)) cell.title.text = article.title cell.detail.text = article.summary cell.likeNumber.text = "\(article.likeNumber!)" cell.category.setTitle(article.category?.name, for: .normal) } }
// // ViewController.swift // ProjectX // // Created by BrangerBriz Felipe on 26/04/18. // Copyright © 2018 BrangerBriz. All rights reserved. // import UIKit import FirebaseAuth import RxSwift import RxCocoa fileprivate let minimalUsernameLength = 5 fileprivate let minimalPasswordLength = 5 class LoginViewController: UIViewController { var loginMode = false @IBOutlet weak var singupBtn: CustomButton! @IBOutlet weak var emailTF: CustomTextField! @IBOutlet weak var passwordTF: CustomTextField! var disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() emailTF.delegate = self passwordTF.delegate = self let usernameValid = emailTF.rx.text.orEmpty .map { $0.count >= minimalUsernameLength } .share(replay: 1) // without this map would be executed once for each binding, rx is stateless by default let passwordValid = passwordTF.rx.text.orEmpty .map { $0.count >= minimalPasswordLength } .share(replay: 1) let everythingValid = Observable.combineLatest(usernameValid, passwordValid) { $0 && $1 } .share(replay: 1) everythingValid .bind(to: singupBtn.rx.isEnabled) .disposed(by: disposeBag) singupBtn.rx.tap .subscribe({ [weak self] _ in self?.loginIn() }) .disposed(by: disposeBag) refreshView(); } func refreshView(){ if (loginMode) { singupBtn.setTitle("Login", for: UIControlState.normal) } else { singupBtn.setTitle("Sing Up", for: UIControlState.normal) } } func loginIn() { if (loginMode) { AuthService.instance.login(with: emailTF.text!, and: passwordTF.text!, onComplete: onAuthComplete) } else { AuthService.instance.singup(with: emailTF.text!, and: passwordTF.text!, onComplete: onAuthComplete) } } func onAuthComplete(_ errMsg: String?, _ data: Any?) -> Void { guard errMsg == nil else { let authAlert = UIAlertController(title: "Error Authentication", message: errMsg, preferredStyle: .alert) authAlert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) self.present(authAlert, animated: true, completion: nil) return } self.dismiss(animated: true, completion: nil) } } extension LoginViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return false } }
// // SponsersCell.swift // Elshams // // Created by mac on 2/27/19. // Copyright © 2019 mac. All rights reserved. // import UIKit class SponsersCell: UICollectionViewCell { }
// // PokemonListAPI.swift // PokeApp // // Created by Taufik Rohmat on 19/08/21. // import RxSwift protocol PokemonListAPI: ClientAPI { func request(parameters: [String: Any]) -> Single<PokemonListResponse> }
// // GroceryItem.swift // What's for dinner? // // Created by Ewoud Wortelboer on 15/07/2021. // Copyright © 2021 Ewoud Wortelboer. All rights reserved. // import Foundation class GroceryItem { enum GroceryType { case Zuivel case Drinken case Diepvries } let name: String let amount: Int let type: GroceryType let dateAdded: Date init(name: String, amount: Int, type: GroceryType, dateAdded: Date) { self.name = name self.amount = amount self.type = type self.dateAdded = dateAdded } }
// // InputViewController.swift // Todo // // Created by Sakai Aoi on 2021/02/15. // import UIKit import RealmSwift class InputViewController: UIViewController, UITextFieldDelegate { @IBOutlet var titleTextField: UITextField! @IBOutlet var deadlineDatePicker: UIDatePicker! var realm: Realm! var selectedIndexPath: IndexPath! var selectedTitle: String! var selectedDeadline: Date! var isEditable: Bool = false var todoItems: Results<TodoItem>! let formatter = DateFormatter() override func viewDidLoad() { super.viewDidLoad() titleTextField.delegate = self // Do any additional setup after loading the view. deadlineDatePicker.preferredDatePickerStyle = .inline deadlineDatePicker.datePickerMode = .dateAndTime deadlineDatePicker.locale = Locale(identifier: "ja-JP") if isEditable { titleTextField.text = selectedTitle deadlineDatePicker.setDate(selectedDeadline, animated: true) } formatter.dateStyle = .medium formatter.timeStyle = .medium formatter.locale = Locale(identifier: "ja_JP") } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "toView" { save() let vc = segue.destination as! ViewController } } func save() { let optionalTitle: String = titleTextField.text! print(formatter.string(from: deadlineDatePicker.date)) if optionalTitle.isEmpty { print("タイトルが未入力") }else{ print(optionalTitle) let todoItem = TodoItem(title: optionalTitle, deadline: deadlineDatePicker.date) let realm = try! Realm() do { try realm.write { if isEditable { todoItems = realm.objects(TodoItem.self) let selectedTodoItem: TodoItem = todoItems[selectedIndexPath.row] selectedTodoItem.title = todoItem.title selectedTodoItem.deadline = todoItem.deadline isEditable = false }else{ let sortedTodoItems = realm.objects(TodoItem.self).sorted(byKeyPath: "order") print("sorted") print(sortedTodoItems) print(sortedTodoItems.last) todoItem.order = (sortedTodoItems.last?.order ?? -1) + 1 print(sortedTodoItems.last?.order ?? 0) realm.add(todoItem) } print(realm.objects(TodoItem.self)) } } catch let error as NSError { } } } @IBAction func cancel() { self.dismiss(animated: true, completion: nil) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
// // DashLine.swift // Cash Money // // Created by Yin Hua on 17/10/2015. // Copyright © 2015 Yin Hua. All rights reserved. // import UIKit class DashLine: UIView { // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code let context = UIGraphicsGetCurrentContext() CGContextSetLineWidth(context, 10.0) CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor) let dashArray:[CGFloat] = [5,5] CGContextSetLineDash(context, 10, dashArray, 2) CGContextMoveToPoint(context, 0, 0) CGContextAddLineToPoint(context, self.frame.size.width, 0) CGContextStrokePath(context) } }
// // ViewController.swift // trabalho-ios // // Created by pos on 06/09/2019. // Copyright © 2019 br.edu.ifsp.scl.sdm. All rights reserved. // import UIKit import CoreData class ProdutosViewController: UITableViewController { private var produtos: [Produto]? = nil override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) carregarProdutos() tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { print(produtos?.count ?? 0) return produtos?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let produto = produtos?[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "basic", for: indexPath) cell.textLabel?.text = produto?.nome return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "segueDetalhes" { let viewController = segue.destination as! DetalhesViewController let produto = produtos?[tableView.indexPathForSelectedRow!.row] viewController.produto = produto } } private func carregarProdutos() { let appDelegate = UIApplication.shared.delegate as! AppDelegate let context = appDelegate.persistentContainer.viewContext let requisicao = NSFetchRequest<Produto>(entityName: "Produto") let ordenarAZ = NSSortDescriptor(key: "nome", ascending: true) requisicao.sortDescriptors = [ordenarAZ] do { produtos = try context.fetch(requisicao) } catch { let alertController = UIAlertController(title: "Erro", message: "Não foi possível recuperar dados", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Ok", style: .default)) present(alertController, animated: true) } } }
import OverampedCore import Persist import SwiftUI struct IgnoredHostnamesView: View { @PersistStorage(persister: .ignoredHostnames) private(set) var ignoredHostnames: [String] var body: some View { Group { if ignoredHostnames.isEmpty { Text("Overamped has not been disabled on any websites") .font(.title) .multilineTextAlignment(.center) .frame(maxWidth: .infinity) .foregroundColor(Color(.secondaryLabel)) } else { List { ForEach(ignoredHostnames, id: \.self) { ignoredHostname in Text(ignoredHostname) } .onDelete(perform: deleteIgnoredHostnames(atOffsets:)) } } } .background(Color(.systemGroupedBackground)) .navigationTitle("Disabled Websites") } private func deleteIgnoredHostnames(atOffsets offsets: IndexSet) { ignoredHostnames.remove(atOffsets: offsets) } } struct IgnoredHostnamesView_Previews: PreviewProvider { static var previews: some View { IgnoredHostnamesView() } }
// // WelcomeViewController.swift // voxfeed-test // // Created by Alejandro de la Rosa on 2/19/19. // Copyright © 2019 ARC. All rights reserved. // import UIKit class WelcomeViewController: UIViewController { @IBOutlet weak var welcomeMessageLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() self.welcomeMessageLabel.text = "Bienvenido a\nVoxFeed" } }
// // TableViewController.swift // RSS читалка // // Created by Diy2210 on 03.11.14. // Copyright (c) 2014 Diy2210. All rights reserved. // import UIKit class TableViewController: UITableViewController, NSXMLParserDelegate { var parser = NSXMLParser() var feeds = NSMutableArray() var elements = NSMutableDictionary() var element = NSString() var ftitle = NSMutableString() var link = NSMutableString() var fdescription = NSMutableString() override func viewDidLoad() { super.viewDidLoad() self.tableView.rowHeight = 70 feeds = [] let url: NSURL = NSURL(string:"http://www.pravda.com.ua/rus/rss/view_news/")! parser = NSXMLParser(contentsOfURL: url)! parser.delegate = self parser.shouldProcessNamespaces = false parser.shouldReportNamespacePrefixes = false parser.shouldResolveExternalEntities = false parser.parse() } func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { element = elementName if (element as NSString).isEqualToString("item") { elements = NSMutableDictionary() elements = [:] ftitle = NSMutableString() ftitle = "" link = NSMutableString() link = "" fdescription = NSMutableString() fdescription = "" } } func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if (elementName as NSString).isEqualToString("item") { if ftitle != "nil" { elements.setObject(ftitle, forKey: "title") } if link != "nil" { elements.setObject(link, forKey: "link") } if fdescription != "nil" { elements.setObject(fdescription, forKey: "description") } feeds.addObject(elements) } } func parser(parser: NSXMLParser, foundCharacters string: String) { if element.isEqualToString("title") { ftitle.appendString(string) } else if element.isEqualToString("link") { link.appendString(string) } else if element.isEqualToString("description") { fdescription.appendString(string) } } func parserDidEndDocument(parser: NSXMLParser) { self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return feeds.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell cell.textLabel!.text = feeds.objectAtIndex(indexPath.row).objectForKey("title") as? String cell.detailTextLabel?.numberOfLines = 3 cell.detailTextLabel?.text = feeds.objectAtIndex(indexPath.row).objectForKey("description") as? String return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if segue.identifier == "openPage" { let fwpvc: ViewController = segue.destinationViewController as! ViewController element = element.stringByReplacingOccurrencesOfString("", withString:"") element = element.stringByReplacingOccurrencesOfString("\n", withString:"") fwpvc.feedURL = element as String } } }
// // ViewController.swift // WorksManagementApp // // Created by 大原一倫 on 2018/12/25. // Copyright © 2018 oharakazumasa. All rights reserved. // //""" //{ "20181201": // [["subject": "a","homeWork": "c", "date": "d"], // ["subject": "a","homeWork": "c", "date": "d"], // ["subject": "a","homeWork": "c", "date": "d"]] // //"20181203": // [[], [], []] // "sectionNames": ["20181201", ] //} //""" import UIKit import RealmSwift class Data: Object { @objc dynamic var subject = "" @objc dynamic var homeWork = "" @objc dynamic var date = "" } class ViewController: UIViewController { @IBOutlet var subjectTextField: UITextField! @IBOutlet var dateTextField: UITextField! @IBOutlet var homeWorkField: UITextField! var realm :Realm! var taskDictonary: [Dictionary<String, [String: String]>] = [] var parentArray:[[String: String]] = [] var normalArray:[Dictionary<String, String>] = [] var datePicker: UIDatePicker = UIDatePicker() var timeInt: Int = 0 var colorNumber: Int = 0 let saveData = UserDefaults.standard let colorSaveData = UserDefaults.standard @IBAction func selectadd(){ if subjectTextField.text == "" { let alart = UIAlertController(title: "エラー", message: "教科を入力してください", preferredStyle: .alert) alart.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alart, animated: true, completion: nil) }else if dateTextField.text == "" { let alart = UIAlertController(title: "エラー", message: "期限を入力してください", preferredStyle: .alert) alart.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alart, animated: true, completion: nil) }else if homeWorkField.text == ""{ let alart = UIAlertController(title: "エラー", message: "宿題を入力してください", preferredStyle: .alert) alart.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alart, animated: true, completion: nil) }else{ let recordData = Data() recordData.subject = String(subjectTextField.text!) recordData.homeWork = String(homeWorkField.text!) recordData.date = String(dateTextField.text!) try! realm.write { realm.add(recordData) } // let taskData = ["dateTextField.text!": ["subject": subjectTextField.text!,"homeWork": homeWorkField.text!, "date": dateTextField.text!]] // let newData = ["subject": subjectTextField.text!,"homeWork": homeWorkField.text!, "date": dateTextField.text!] // parentArray.append(newData) // saveData.set(parentArray, forKey: dateTextField.text!) // // taskDictonary.append(taskData) // saveData.set(taskDictonary, forKey: "taskData") subjectTextField.text = "" homeWorkField.text = "" dateTextField.text = "" let alart = UIAlertController(title: "完了", message: "保存が完了しました", preferredStyle: .alert) alart.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alart, animated: true, completion: nil) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. datePicker.datePickerMode = UIDatePicker.Mode.date datePicker.timeZone = NSTimeZone.local datePicker.locale = Locale.current dateTextField.inputView = datePicker realm = try! Realm() let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 35)) let spacelItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil) let doneItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(done)) toolBar.setItems([spacelItem, doneItem], animated: true) dateTextField.inputView = datePicker dateTextField.inputAccessoryView = toolBar } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) if colorSaveData.object(forKey: "COLOR") != nil { colorNumber = colorSaveData.object(forKey: "COLOR") as! Int } switch colorNumber { case 0: self.view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) case 1: self.view.backgroundColor = #colorLiteral(red: 0.7931890626, green: 1, blue: 0.5290435264, alpha: 1) case 2: self.view.backgroundColor = #colorLiteral(red: 0.7074827594, green: 0.9915311623, blue: 1, alpha: 1) case 3: self.view.backgroundColor = #colorLiteral(red: 1, green: 0.7012115478, blue: 0.9455770609, alpha: 1) default: break } } func textFieldShouldReturn(_ textField: UITextField) -> Bool{ textField.resignFirstResponder() return true } @objc func done(){ dateTextField.endEditing(true) let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" dateTextField.text = "\(formatter.string(from: datePicker.date))" } }
// // TestViewController.swift // Parlour // // Created by Ron Yi on 2018/12/20. // Copyright © 2018 Ron Yi. All rights reserved. // import UIKit import XCDYouTubeKit import YouTubePlayer import NotificationBannerSwift class TestViewController: UIViewController, YouTubePlayerDelegate { @IBOutlet var videoPlayer: YouTubePlayerView! override func viewDidLoad() { super.viewDidLoad() videoPlayer.delegate = self videoPlayer.playerVars = [ "playsinline": "1", "controls": "1" ] as YouTubePlayerView.YouTubePlayerParameters videoPlayer.loadPlaylistID("PLC6D7B81753E76C5E") } func playerReady(_ videoPlayer: YouTubePlayerView) { //videoPlayer.play() //videoPlayer.seekTo(50, seekAhead: true) } func playerStateChanged(_ videoPlayer: YouTubePlayerView, playerState: YouTubePlayerState) { if playerState.rawValue == "-1" { print("Unstarted") } else if playerState.rawValue == "0" { print("Ended") } else if playerState.rawValue == "1" { print("Playing") } else if playerState.rawValue == "2" { print("Paused") } else if playerState.rawValue == "3" { print("Buffering") } else if playerState.rawValue == "4" { print("Queued") } else { print("Nothing") } } @IBAction func testNotified(_ sender: UIButton) { let banner = NotificationBanner(title: "Test", subtitle: "Content", style: .info) banner.show() print("tap testNotified") } }
// // Rectangular_StrokeBorder.swift // 100Views // // Created by Mark Moeykens on 7/13/19. // Copyright © 2019 Mark Moeykens. All rights reserved. // import SwiftUI struct Rectangular_StrokeBorder : View { var body: some View { VStack(spacing: 10) { Text("Rectangular Shapes").font(.largeTitle) Text("Stroke Border (Inner Stroke)") .font(.title).foregroundColor(.gray) Text("A stroke modifier grows outward from the center of the shape's outline and can cause overlapping issues.") .frame(maxWidth: .infinity).padding() .background(Color.blue) ZStack { RoundedRectangle(cornerRadius: 40) .stroke(Color.orange, lineWidth: 40) RoundedRectangle(cornerRadius: 40) .stroke() // outline } Text("A strokeBorder modifier will grow inward from the shape's outline.") .frame(maxWidth: .infinity).padding() .background(Color.blue) ZStack { RoundedRectangle(cornerRadius: 40) .strokeBorder(Color.orange, lineWidth: 40) RoundedRectangle(cornerRadius: 40) .stroke() // outline } Text("(Notice how .strokeBorder will start to square off inside when the lineWidth increases.)") .font(.body) }.font(.title) } } #if DEBUG struct Rectangular_StrokeBorder_Previews : PreviewProvider { static var previews: some View { Rectangular_StrokeBorder() } } #endif
// // ListViewModelTest.swift // RepositoryFinderTests // // Created by SMMC on 17/10/2021. // import XCTest @testable import RepositoryFinder class ListViewModelTest: XCTestCase { var repositoriesResponse: RepoListResponse? override func setUp() { super.setUp() // Load Stub let data = loadStub(name: "gitHubRespositoryExample", extension: "json") // Initialize JSON Decoder let decoder = JSONDecoder() // Configure JSON Decoder decoder.dateDecodingStrategy = .secondsSince1970 // Initialize repositories Response repositoriesResponse = try! decoder.decode(RepoListResponse.self, from: data) } override func tearDown() { super.tearDown() } func testTotalCount() { XCTAssertEqual(repositoriesResponse?.totalCount, 220066) } func testIncompleteResults() { XCTAssertEqual(repositoriesResponse?.incompleteResults, false) } func testViewModelForFirstIndex() { let data = repositoriesResponse?.items[0] XCTAssertEqual(data?.name, "free-programming-books-zh_CN") XCTAssertEqual(data?.full_name, "justjavac/free-programming-books-zh_CN") XCTAssertEqual(data?.owner?.html_url, "https://github.com/justjavac") } func testViewModelForSecondIndex() { let data = repositoriesResponse?.items[1] XCTAssertEqual(data?.name, "swift") XCTAssertEqual(data?.full_name, "apple/swift") XCTAssertEqual(data?.owner?.html_url, "https://github.com/apple") } }
import UIKit // MARK: - .map // Loops over a collection and applies the same operation to each element in the collection. var myWords = ["Some", "Chick", "Turn", "Around"] var math = [1, 4, 5, 10] var compactZoo = [["🐵", "🐵", "🐵"], ["🦊", "🦊"], ["🦁", "🦁"], nil] let sentence = myWords.map { $0 + " 1" } let sentence4 = myWords.map { value in value + " 4" } print(""" \(sentence) \(sentence4) """) // MARK: - .filter // Loops over a collection and returns an array that contains elements that meet a condition. let fileteredSentence = myWords.filter { $0 == "Chick" || $0 == "Around" } print(fileteredSentence) // MARK: - .reduce // Loops over a collection and Combines all items in a collection to create a single value. aka Glue let calculation = math.reduce(0, +) print(calculation) let glue = myWords.reduce("", { $0 + $1 }) print(glue) // MARK: - .flatMap & .compactMap // Arrays within an array that we would like to combine into a single array. let noNilArray = compactZoo.compactMap { $0 } // Skip nil let merge = compactZoo.compactMap { $0?.joined() } // Merge print(noNilArray) print(merge)
// 2020.06.25 | Birdie - CreatePostButton.swift | Copyright © 2020 Jay Strawn. All rights reserved. import UIKit @IBDesignable class CreatePostButton: UIButton { override init(frame: CGRect) { super.init(frame: frame) setupButton() } required init?(coder: NSCoder) { super.init(coder: coder) setupButton() } func setupButton() { layer.cornerRadius = 10 layer.masksToBounds = true layer.borderWidth = 2 layer.borderColor = UIColor.secondaryLabel.cgColor } }
// // URL+CommonURLs.swift // Claudio // // Created by Michael Pace on 12/2/17. // Copyright © 2017 Michael Pace. All rights reserved. // import Foundation /// An extension on `URL` which provides convenience methods and properties for dealing with common URLs. extension URL { /// The URL to use for user documents. static var userDocumentsDirectory: URL { let possibleURLs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) guard let url = possibleURLs.first else { Logger.log(.error, "Error creating URL to documents directory.") assertionFailure() return URL(fileURLWithPath: "") } return url } }
// // TaskService.swift // GTor // // Created by Safwan Saigh on 14/05/2020. // Copyright © 2020 Safwan Saigh. All rights reserved. // import Foundation import Firebase enum TaskErrors: Error { case noTitle, invalidSatisfaction } extension TaskErrors: LocalizedError {//TODO var errorDescription: String? { switch self { case .noTitle: return NSLocalizedString("titleIsMissing", comment: "") case .invalidSatisfaction: return NSLocalizedString("invalidSatisfaction", comment: "") } } } class TaskService: ObservableObject { @Published var tasks: [Task] = [] { didSet { for task in tasks { CalcService.shared.calcProgress(from: task) } } } static let shared = TaskService() func getLinkedGoals(task: Task) -> [Goal] { return GoalService.shared.goals.filter {task.linkedGoalsIds.contains($0.id)} } func getTasksFromDatabase(completion: @escaping (Result<Void, Error>) -> ()){ FirestoreService.shared.getDocuments(collection: .tasks, documentId: UserService.shared.user.uid) { (result: Result<[Task], Error>) in switch result { case .failure(let error): completion(.failure(error)) case .success(let tasks): DispatchQueue.main.async { self.tasks = tasks.sorted { $0.importance.value > $1.importance.value } completion(.success(())) } } } } func saveTasksToDatabase(task: Task, completion: @escaping (Result<Void, Error>)->()){ FirestoreService.shared.saveDocument(collection: .tasks, documentId: task.id.description, model: task) { result in switch result { case .failure(let error): completion(.failure(error)) case .success(): completion(.success(())) } } } func saveTask(task: Task, completion: @escaping (Result<Void, Error>)->()) { validateTask(task: task) { (result) in switch result { case .failure(let error): completion(.failure(error)) case .success(()): self.saveTasksToDatabase(task: task) { (result) in switch result { case .failure(let error): completion(.failure(error)) case .success(()): completion(.success(())) } } } } } func validateTask(task: Task, completion: @escaping (Result<Void, Error>)->()) { if task.title.isEmpty { completion(.failure(TaskErrors.noTitle)) }else if task.satisfaction > 100 || task.satisfaction < 0 { completion(.failure(TaskErrors.invalidSatisfaction)) }else { completion(.success(())) } } func deleteTask(task: Task, completion: @escaping (Result<Void, Error>)->()) { FirestoreService.shared.deleteDocument(collection: .tasks, documentId: task.id.description) { (result) in switch result { case .failure(let error): completion(.failure(error)) case .success(()): completion(.success(())) } } } }
// // MovieCell.swift // TopMovies2.0 // // Created by Леганов Андрей on 05/08/2019. // Copyright © 2019 Леганов Андрей. All rights reserved. // import Foundation import UIKit protocol MovieCellDelegate { func scheduleButtonPressedAt(index: Int) } class MovieCell: UITableViewCell { @IBOutlet weak var posterView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var releaseDateLabel: UILabel! @IBOutlet weak var overviewLabel: UILabel! @IBOutlet weak var button: UIButton! @IBAction func scheduleButtonPressed(_ sender: Any) { guard let index = index else { return } delegate?.scheduleButtonPressedAt(index: index) } var delegate: MovieCellDelegate? var index: Int? let domainImagePath = "https://image.tmdb.org/t/p/w500/" override func awakeFromNib() { super.awakeFromNib() initialConfigure() } func initialConfigure() { titleLabel.lineBreakMode = .byWordWrapping titleLabel.numberOfLines = 0 titleLabel.textColor = .white overviewLabel.lineBreakMode = .byWordWrapping overviewLabel.numberOfLines = 0 overviewLabel.textColor = .white posterView.contentMode = .scaleAspectFit releaseDateLabel.textColor = .white button.backgroundColor = .white button.setTitleColor(.black, for: []) button.layer.cornerRadius = 5 button.layer.masksToBounds = true } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func prepareForReuse() { super.prepareForReuse() self.posterView.image = nil } // MARK: Cell setup func setupWith(movie: Movie, index: Int) { self.index = index backgroundColor = .black titleLabel.text = movie.title releaseDateLabel.text = movie.releaseDate overviewLabel.text = movie.overview loadImage(path: domainImagePath + movie.posterPath!) } private func loadImage(path: String) { if let imageURL = URL(string: path) { DispatchQueue.global().async { let data = try? Data(contentsOf: imageURL) if let data = data { let image = UIImage(data: data) DispatchQueue.main.async { self.posterView.image = image } } } } } }
// // ImageuploadViewController.swift // YuluDemo // // Created by Admin on 10/25/19. // Copyright © 2019 Admin. All rights reserved. // import UIKit class ImageuploadViewController: UIViewController,StoryboardIdentifiable,UIImagePickerControllerDelegate,UINavigationControllerDelegate { @IBOutlet var imageView: UIImageView! @IBOutlet var chooseBuuton: UIButton! var imagePicker = UIImagePickerController() var viewModel:ImageupLoadViewModel? var imageFile: NSString? override func viewDidLoad() { super.viewDidLoad() self.setUpViewModel() } private func setUpViewModel() { viewModel?.showAlert = { [weak self](message) in if let result = message { self?.showAlert(message: result) } } } @IBAction func btnClicked() { if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){ print("Button capture") imagePicker.delegate = self imagePicker.sourceType = .savedPhotosAlbum imagePicker.allowsEditing = false present(imagePicker, animated: true, completion: nil) } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){ print(info[.imageURL]!) imageView.image = info[.originalImage]! as? UIImage let url = info[.imageURL]! as! NSURL self.imageFile = url.path as NSString? picker.dismiss(animated: true, completion: nil) } class func controller(viewModel: ImageupLoadViewModel) -> ImageuploadViewController { let vc:ImageuploadViewController = UIStoryboard (storyboard: .main).instantiateViewController() vc.viewModel = viewModel return vc } @IBAction func imageUoloadAction(_ sender: Any) { self.viewModel?.uploadImageBy(file: imageFile! as String) //self.navigationController?.popViewController(animated: true) } func checkPermission() { // let photoAuthorizationStatus = PHPhotoLibrary.authorizationStatus() // switch photoAuthorizationStatus { // case .authorized: print("Access is granted by user") // case .notDetermined: // PHPhotoLibrary.requestAuthorization({ (newStatus) in print("status is \(newStatus)") if newStatus == PHAuthorizationStatus.authorized { /do stuff here */ print("success") } }) // case .restricted: / print("User do not have access to photo album.") // case .denied: / print("User has denied the permission.") // // } // } }
import FirebaseStorage import Foundation protocol StorageReferenceable { func child(from path: String) -> StorageReferenceable func downloadImageUrl(completion: @escaping (URL?, Error?) -> Void) }
// // LaunchCell.swift // SpaceXTestApp // // Created by vladikkk on 10/12/2020. // import UIKit class LaunchCell: UICollectionViewCell { // MARK: Properties static let cellID = "LaunchCell" private var launchDetails: LaunchDataResponse? // UI lazy var button: UIButton = { let btn = UIButton(frame: .zero) btn.translatesAutoresizingMaskIntoConstraints = false btn.backgroundColor = .clear btn.layer.masksToBounds = true btn.addTarget(self, action: #selector(self.openLaunchDetails), for: .touchUpInside) return btn }() lazy var delimiterView: UIView = { let view = UIView(frame: .zero) view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = .lightGray return view }() lazy var imageView: UIImageView = { let imgView = UIImageView(frame: .zero) imgView.translatesAutoresizingMaskIntoConstraints = false imgView.contentMode = .scaleAspectFill imgView.clipsToBounds = true imgView.backgroundColor = .clear imgView.layer.borderWidth = 0.7 imgView.layer.cornerRadius = 10 imgView.layer.borderColor = UIColor.white.cgColor return imgView }() lazy var detailsView: LaunchRowDetailsView = { let view = LaunchRowDetailsView(frame: .zero) view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = .clear return view }() // MARK: Initializers override init(frame: CGRect) { super.init(frame: frame) self.setupCell() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setupCell() } // MARK: Methods private func setupCell() { self.addSubview(self.delimiterView) self.addSubview(self.imageView) self.addSubview(self.detailsView) self.addSubview(self.button) self.setupDelimiterViewLayout() self.setupButtonLayout() self.setupImageViewLayout() self.setupDetailsViewLayout() } private func setupButtonLayout() { NSLayoutConstraint.activate([ self.button.centerXAnchor.constraint(equalTo: self.centerXAnchor), self.button.centerYAnchor.constraint(equalTo: self.centerYAnchor), self.button.heightAnchor.constraint(equalTo: self.heightAnchor), self.button.widthAnchor.constraint(equalTo: self.widthAnchor) ]) } private func setupDelimiterViewLayout() { NSLayoutConstraint.activate([ self.delimiterView.topAnchor.constraint(equalTo: self.topAnchor, constant: 5), self.delimiterView.centerXAnchor.constraint(equalTo: self.centerXAnchor), self.delimiterView.heightAnchor.constraint(equalToConstant: 1), self.delimiterView.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.925) ]) } private func setupImageViewLayout() { NSLayoutConstraint.activate([ self.imageView.topAnchor.constraint(equalTo: self.delimiterView.bottomAnchor, constant: 2), self.imageView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 5), self.imageView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -5), self.imageView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.75) ]) } private func setupDetailsViewLayout() { NSLayoutConstraint.activate([ self.detailsView.topAnchor.constraint(equalTo: self.imageView.bottomAnchor, constant: 5), self.detailsView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -5), self.detailsView.leadingAnchor.constraint(equalTo: self.imageView.leadingAnchor), self.detailsView.trailingAnchor.constraint(equalTo: self.imageView.trailingAnchor) ]) } } // Setup Cell Data extension LaunchCell { func setupCellData(withData cellData: LaunchDataResponse) { self.launchDetails = cellData // Check if there are any images from flickr, if not then download image from patch if let originalImageLink = cellData.links.flickr.original.first, !originalImageLink.isEmpty { self.setupImageView(from: originalImageLink) } else if let smallImageLink = cellData.links.flickr.small.first, !smallImageLink.isEmpty { self.setupImageView(from: smallImageLink) } else { if let largeImageLink = cellData.links.patch.large { self.setupImageView(from: largeImageLink) } } self.detailsView.setupLabelTitles(title: cellData.name, date: cellData.date) } // Setup and cache image fileprivate func setupImageView(from urlString: String) { guard let imageUrl = URL(string: urlString) else { NSLog("Error: Invalid image link, \(#function)") return } self.imageView.loadImage(withUrl: imageUrl) } } // Adding Buttons Functionality extension LaunchCell { @objc private func openLaunchDetails() { DispatchQueue.main.async { guard let vc = self.findViewController() else { return } let newVC = LaunchDetailsVC() newVC.launchDetails = self.launchDetails vc.navigationController?.pushViewController(newVC, animated: true) } } }
// // Contact.swift // KCProgrammingChallenge // // Created by Alejandro Villa Cardenas // import Foundation struct Contact: Codable { let name: String let id: String let companyName: String? var isFavorite: Bool let smallImageURL: String let largeImageURL: String let emailAddress: String let birthdate: String let phone: Phone let address: Address enum CodingKeys: String, CodingKey { case name case id case companyName case isFavorite case smallImageURL case largeImageURL case emailAddress case birthdate case phone case address } } extension Contact: Equatable { static func == (lhs: Contact, rhs: Contact) -> Bool { return lhs.id == rhs.id } } extension Array where Element == Contact { mutating func sortByName() { self.sort(by: { $0.name < $1.name }) } }
// // InjectionCenterTests.swift // StarterKitTests // // Created by Emilio Pavia on 22/11/2019. // Copyright © 2019 Emilio Pavia. All rights reserved. // import XCTest @testable import StarterKit private protocol Injectable { var identifier: String { get } } private class InjectableObject: Injectable { let identifier: String = UUID().uuidString } private class InjectableSubclass: InjectableObject { let success = true } class InjectorCenterTests: XCTestCase { var injectionCenter: InjectionCenter! override func setUp() { super.setUp() injectionCenter = InjectionCenter() } override func tearDown() { injectionCenter = nil super.tearDown() } func testInjection() { // given let object = InjectableObject() // when injectionCenter.put(object) // then XCTAssertTrue(object === injectionCenter.get(InjectableObject.self)) } func testObjectCannotBeInsertedTwice() { // given let object1 = InjectableObject() let object2 = InjectableObject() // when injectionCenter.put(object1) injectionCenter.put(object2) // then XCTAssertTrue(object1 === injectionCenter.get(InjectableObject.self)) } func testStaticInjection() { // given let object = InjectableObject() // when InjectionCenter.provide(object) // then XCTAssertTrue(object === InjectionCenter.inject(InjectableObject.self)) } func testSubclassInjection() { // given let object = InjectableSubclass() // when injectionCenter.put(object, as: InjectableObject.self) guard let injectedObject = injectionCenter.get(InjectableObject.self) as? InjectableSubclass else { XCTFail() return } // then XCTAssertTrue(object === injectedObject) XCTAssertTrue(injectedObject.success) } func testProtocolInjection() { // given let object = InjectableObject() // when injectionCenter.put(object, as: Injectable.self) // then let injectedObject: Injectable = injectionCenter.get(Injectable.self) XCTAssertTrue(object.identifier == injectedObject.identifier) } }
// // SecondQuestionViewController.swift // Muve // // Created by Luan Nguyen on 2019-09-19. // Copyright © 2019 Luan Nguyen. All rights reserved. // import UIKit import VerticalCardSwiper class SecondQuestionViewController: UIViewController, VerticalCardSwiperDelegate, VerticalCardSwiperDatasource { let cardSwiper: VerticalCardSwiper = { let cS = VerticalCardSwiper() cS.translatesAutoresizingMaskIntoConstraints = false cS.cardSpacing = 15 cS.register(DaysCell.self, forCellWithReuseIdentifier: "daysCell") return cS }() let questionLabel: UILabel = { let questionLabel = UILabel() questionLabel.translatesAutoresizingMaskIntoConstraints = false questionLabel.font = UIFont.systemFont(ofSize: 25, weight: .heavy) questionLabel.text = "How long will you challenge yourself for?" questionLabel.numberOfLines = 0 questionLabel.textAlignment = .center return questionLabel }() var daysLists: [Days] = [] override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white daysLists = createDays() addToSubView() setLayoutConstraints() cardSwiper.datasource = self cardSwiper.delegate = self } func addToSubView() { view.addSubview(questionLabel) view.addSubview(cardSwiper) } func setLayoutConstraints () { NSLayoutConstraint.activate([ questionLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor), questionLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 30), questionLabel.widthAnchor.constraint(equalToConstant: 300) ]) NSLayoutConstraint.activate([ cardSwiper.centerXAnchor.constraint(equalTo: view.centerXAnchor), cardSwiper.topAnchor.constraint(equalTo: questionLabel.bottomAnchor, constant: 10), cardSwiper.leadingAnchor.constraint(equalTo: view.leadingAnchor), cardSwiper.trailingAnchor.constraint(equalTo: view.trailingAnchor), cardSwiper.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) ]) } func createDays() -> [Days] { let option1 = Days(days: "100", backgroundColor: .magenta) let option2 = Days(days: "90", backgroundColor: .blue) let option3 = Days(days: "60", backgroundColor: .cyan) let option4 = Days(days: "30", backgroundColor: .lightGray) let option5 = Days(days: "10", backgroundColor: .orange) let option6 = Days(days: "7", backgroundColor: .purple) let option7 = Days(days: "3", backgroundColor: .brown) daysLists.append(option1) daysLists.append(option2) daysLists.append(option3) daysLists.append(option4) daysLists.append(option5) daysLists.append(option6) daysLists.append(option7) return daysLists } } //CARD section extension SecondQuestionViewController { func numberOfCards(verticalCardSwiperView: VerticalCardSwiperView) -> Int { return daysLists.count } func cardForItemAt(verticalCardSwiperView: VerticalCardSwiperView, cardForItemAt index: Int) -> CardCell { if let cell = verticalCardSwiperView.dequeueReusableCell(withReuseIdentifier: "daysCell", for: index) as? DaysCell { let item = daysLists[index] cell.getDays(days: item) cell.layer.cornerRadius = 10 cell.layer.masksToBounds = true return cell } return CardCell() } func willSwipeCardAway(card: CardCell, index: Int, swipeDirection: SwipeDirection) { daysLists.remove(at: index) let nextVC = ThirdViewController() self.navigationController?.pushViewController(nextVC, animated: true) } // func didSwipeCardAway(card: CardCell, index: Int, swipeDirection: SwipeDirection) { // let nextVC = ThirdViewController() // self.navigationController?.pushViewController(nextVC, animated: true) // } }
// // SlidingBarTabView.swift // SwiftExtensions // // Created by Divya Mandyam on 3/19/21. // import UIKit import EasyPeasy class SlidingBarTabView: UIControl { private let stackView: UIStackView = { let stackView = UIStackView() stackView.distribution = .fillEqually stackView.isUserInteractionEnabled = false return stackView }() private let slidingBar = UIView() var onTabSelected: ((Int) -> Void)? var barColor = UIColor.red { didSet { slidingBar.backgroundColor = barColor } } override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { backgroundColor = UIColor.white addSubview(stackView) addSubview(slidingBar) slidingBar.backgroundColor = barColor slidingBar.frame = CGRect(x: bounds.origin.x, y: bounds.maxY - 1.0, width: bounds.width, height: 1.0) stackView.easy.layout(Top(8), Left(), Right(), Bottom(1.0)) } func configure(titles: [String]) { titles.enumerated().forEach { (index, text) in let button = createButton(title: text, index: index) stackView.addArrangedSubview(button) } stackView.layoutIfNeeded() } func adjustBar(selectedIndex: Int, animate: Bool = false) { let selectedButton = stackView.arrangedSubviews[selectedIndex] let convertedOrigin = convert(CGPoint(x: selectedButton.frame.minX, y: selectedButton.frame.maxY), from: stackView) // Lower left corner of selected button let newFrame = CGRect(x: convertedOrigin.x, y: convertedOrigin.y, width: selectedButton.frame.width, height: 1.0) if animate { UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: { [weak self] in self?.slidingBar.frame = newFrame }, completion: nil) } else { slidingBar.frame = newFrame } } // Can override to create custom styled UIButton func createButton(title: String, index: Int) -> UIButton { let button = UIButton() button.setTitleColor(UIColor.black, for: .normal) button.titleLabel?.font = UIFont(name: "Helvetica Neue", size: 12.0) button.titleLabel?.numberOfLines = 0 button.titleLabel?.adjustsFontForContentSizeCategory = true button.setTitle(title, for: .normal) button.tag = index return button } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let touchPoint = touches.first?.location(in: stackView), let selectedIndex = stackView.arrangedSubviews.firstIndex(where: { return $0.frame.contains(touchPoint) }) { adjustBar(selectedIndex: selectedIndex, animate: true) onTabSelected?(selectedIndex) } } }
// // ViewControllerCathegories.swift // Monithor // // Created by Cristina Salerno on 16/05/17. // Copyright © 2017 Pipsqueaks. All rights reserved. // import UIKit class ViewControllerCathegories: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { var plugTypes: [Cathegory] = [] var idScelto = 0 func setCathegory() { plugTypes.append(Cathegory(name: "Coffee Machine", image: #imageLiteral(resourceName: "CoffeeMachine"))) plugTypes.append(Cathegory(name: "Washing Machine", image: #imageLiteral(resourceName: "WashingMachine"))) plugTypes.append(Cathegory(name: "Air Cooler", image: #imageLiteral(resourceName: "Cooler"))) plugTypes.append(Cathegory(name: "TV", image: #imageLiteral(resourceName: "TV"))) plugTypes.append(Cathegory(name: "Game Console", image: #imageLiteral(resourceName: "PS4"))) plugTypes.append(Cathegory(name: "Vacuum Cleaner", image: #imageLiteral(resourceName: "Vacuum"))) plugTypes.append(Cathegory(name: "Dish Washer", image: #imageLiteral(resourceName: "Dishwasher"))) plugTypes.append(Cathegory(name: "Printer", image: #imageLiteral(resourceName: "Copymachine"))) plugTypes.append(Cathegory(name: "PC", image: #imageLiteral(resourceName: "PC"))) plugTypes.append(Cathegory(name: "Mobile Phone", image: #imageLiteral(resourceName: "iPhone"))) plugTypes.append(Cathegory(name: "Alarm", image: #imageLiteral(resourceName: "Alarm"))) plugTypes.append(Cathegory(name: "Heater", image: #imageLiteral(resourceName: "Heater"))) plugTypes.append(Cathegory(name: "Lamp", image: #imageLiteral(resourceName: "Lamp"))) plugTypes.append(Cathegory(name: "Name", image: #imageLiteral(resourceName: "Air cond"))) plugTypes.append(Cathegory(name: "Mac Charger", image: #imageLiteral(resourceName: "Mac Charger"))) plugTypes.append(Cathegory(name: "Food Steamer", image: #imageLiteral(resourceName: "Bimby"))) plugTypes.append(Cathegory(name: "Telephone", image: #imageLiteral(resourceName: "Telephone"))) plugTypes.append(Cathegory(name: "CD Player", image: #imageLiteral(resourceName: "CD Player"))) } @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(red: 245/255, green: 254/255, blue: 247/255, alpha: 1.0) self.collectionView.backgroundColor = UIColor(red: 245/255, green: 254/255, blue: 247/255, alpha: 1.0) setCathegory() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return plugTypes.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let aCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cathegoriesCell", for: indexPath) as! CollectionViewCellCathegories aCell.labelNameCathegory.text = plugTypes[indexPath.row].name aCell.imageCathegory.image = plugTypes[indexPath.row].image return aCell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { idScelto = indexPath.row } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? DeviceDetailsTableViewController { destination.idPlug = idScelto } } }
import UIKit class BaseViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.dismissKey() } } extension BaseViewController { func dismissKey() { let tap: UITapGestureRecognizer = UITapGestureRecognizer( target: self, action: #selector(BaseViewController.dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } @objc func dismissKeyboard() { view.endEditing(true) } }
import UIKit import UIExtension import Fiat import OtherPages public class TradeNavigationPresener: NavigationPresener { let root: TradePagePresenter let fiat: FiatPresenter public init() { root = TradePagePresenter() fiat = FiatPresenter() super.init(rootViewController: root) root.coordinator = self tabBarItem = UITabBarItem( title: "Trade", image: UIImage(systemName: "3.square"), selectedImage: UIImage(systemName: "3.square.fill")) } public required init?(coder aDecoder: NSCoder) { return nil } } extension TradeNavigationPresener { public func showConvert() { let convert = root.page1 root.setViewControllers([convert], direction: .reverse, animated: true) root.navigationItem.title = convert.navigationItem.title } } extension TradeNavigationPresener: TradePagePresenterCoordinator { func presenterGoToBuyCrypto(_ presenter: TradePagePresenter) { present(fiat, animated: true) } }
// // CommonAlarm.swift // Waker // // Created by Joe Ciou on 2021/5/27. // import Foundation import RealmSwift class CommonAlarm: Object, ObjectKeyIdentifiable { @objc dynamic var _id: ObjectId = ObjectId.generate() @objc dynamic var hour: Int = 0 @objc dynamic var minute: Int = 0 @objc dynamic var remark: String = "" override class func primaryKey() -> String? { return "_id" } convenience init(hour: Int, minute: Int, remark: String) { self.init() self.hour = hour self.minute = minute self.remark = remark } }
// // hkserverApp.swift // hkserver // // Created by Shaheen Gandhi on 1/17/21. // import ArgumentParser @main struct HKServerCommand : ParsableCommand { @Flag(help: "Verbose logging") var verbose = false @Option(name: .shortAndLong, help: "Port to bind to. Default is 55123") var port: Int? mutating func run() throws { let server = HKServer(host: nil, port: port ?? 55123) server.run() } }
// // main.swift // Deadlock // // Created by Osmar Hernández on 22/11/18. // Copyright © 2018 Operating Systems. All rights reserved. // import Foundation var input: String? let message = """ Instructions: Type 'Update' to change a process resource value Type 'Status' to get program status Type 'Run' to run the program Type 'Exit' to exit the program """ while Program.run { print(message) input = readLine() if let input = input { Program.execute(input) } }
// // OrderInstallLockController.swift // MsdGateLock // // Created by ox o on 2017/7/4. // Copyright © 2017年 xiaoxiao. All rights reserved. // 预约安装门锁 import UIKit import ContactsUI import AddressBookUI class OrderInstallLockController: UITableViewController { @IBOutlet weak var numberTip: UILabel! @IBOutlet weak var numberTF: UITextField! @IBOutlet weak var adressListBtn: UIButton! @IBOutlet weak var contantTip: UILabel! @IBOutlet weak var nameTF: UITextField! @IBOutlet weak var areaTip: UILabel! @IBOutlet weak var areaLabel: UILabel! @IBOutlet weak var detailTip: UILabel! @IBOutlet weak var detailAdressTF: UITextField! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var timeSeletedLabel: UILabel! @IBOutlet weak var infoBackView: UIView! @IBOutlet weak var title1: UILabel! @IBOutlet weak var info1: UILabel! @IBOutlet weak var title2: UILabel! @IBOutlet weak var info2: UILabel! var seletedNumber : String? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.globalBackColor self.title = "预约门锁" setupUI() } //cell线 override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if (self.tableView?.responds(to: #selector(setter: UITableViewCell.separatorInset)))!{ tableView?.separatorInset = UIEdgeInsets.zero } if (tableView?.responds(to: #selector(setter: UIView.layoutMargins)))!{ tableView?.layoutMargins = UIEdgeInsets.zero } } } extension OrderInstallLockController{ func setupUI(){ navigationItem.rightBarButtonItem = UIBarButtonItem(title: "提交", style: .plain, target: self, action: #selector(OrderInstallLockController.commitOrderClick)) numberTip.textColor = UIColor.textBlackColor contantTip.textColor = UIColor.textBlackColor areaTip.textColor = UIColor.textBlackColor detailTip.textColor = UIColor.textBlackColor timeLabel.textColor = UIColor.textBlackColor adressListBtn.backgroundColor = UIColor.textBlueColor numberTF.textColor = UIColor.textGrayColor numberTF.attributedPlaceholder = NSAttributedString.init(string: "请输入成员手机号", attributes: [NSAttributedString.Key.foregroundColor:UIColor.textGrayColor]) nameTF.attributedPlaceholder = NSAttributedString.init(string: "请输入联系人姓名", attributes: [NSAttributedString.Key.foregroundColor:UIColor.textGrayColor]) nameTF.textColor = UIColor.textGrayColor areaLabel.textColor = UIColor.textGrayColor detailAdressTF.textColor = UIColor.textGrayColor detailAdressTF.attributedPlaceholder = NSAttributedString.init(string: "请输入您的详细地址", attributes: [NSAttributedString.Key.foregroundColor:UIColor.textGrayColor]) timeSeletedLabel.textColor = UIColor.textGrayColor infoBackView.backgroundColor = UIColor.globalBackColor title1.textColor = UIColor.textBlackColor title1.font = UIFont.boldSystemFont(ofSize: 14) info1.textColor = UIColor.textGrayColor title2.textColor = UIColor.textBlackColor title2.font = UIFont.boldSystemFont(ofSize: 14) info2.textColor = UIColor.textGrayColor adressListBtn.addTarget(self, action: #selector(OrderInstallLockController.seletedAdressList), for: .touchUpInside) } } extension OrderInstallLockController{ @objc func commitOrderClick(){ if numberTF.text!.count < 5{ SVProgressHUD.showError(withStatus: "请您检查手机号是否正确,方便联系安装") return } if detailAdressTF.text?.count == 0{ SVProgressHUD.showError(withStatus: "请填写详细地址,方便联系安装") return } let numberCode = self.numberTF.text?.replacingOccurrences(of: "-", with: "") let req = BaseReq<CommitOrderReq>() req.action = GateLockActions.ACTION_InsertReserved req.sessionId = UserInfo.getSessionId()! req.sign = LockTools.getSignWithStr(str: "oxo") req.data = CommitOrderReq.init(reservedUsername: self.nameTF.text!, reservedUserTel: numberCode!, reservedArea: self.areaLabel.text!, reservedAddress: self.detailAdressTF.text!, reservedTime: self.timeSeletedLabel.text!) AjaxUtil<CommonResp>.actionPost(req: req) { [weak self](resp) in QPCLog(resp) SVProgressHUD.showSuccess(withStatus: resp.msg) self?.navigationController?.popViewController(animated: true) } } } extension OrderInstallLockController{ override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 20)) headView.backgroundColor = UIColor.globalBackColor let orderNum = UILabel() orderNum.textColor = UIColor.textGrayColor orderNum.text = "订单号: ********" orderNum.font = UIFont.systemFont(ofSize: 12) orderNum.isHidden = true headView.addSubview(orderNum) orderNum.snp.makeConstraints { (make) in make.left.equalTo(14) make.centerY.equalTo(headView) } let orderStatu = UILabel() orderStatu.textColor = UIColor.textBlackColor orderStatu.text = "待确认" orderStatu.font = UIFont.systemFont(ofSize: 12) orderStatu.isHidden = true headView.addSubview(orderStatu) orderStatu.snp.makeConstraints { (make) in make.right.equalTo(-14) make.centerY.equalTo(headView) } return headView } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 20 } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 33 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) self.view.endEditing(true) if indexPath.row == 2 { setupAreaPickerView() }else if indexPath.row == 4 { seletedTimeClick(str: "安装时间") } } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if cell.responds(to: #selector(setter: UIView.layoutMargins)){ cell.layoutMargins = UIEdgeInsets.zero } if cell.responds(to: #selector(setter: UITableViewCell.separatorInset)){ cell.separatorInset = UIEdgeInsets.zero } } } extension OrderInstallLockController : PickerDelegate{ func setupAreaPickerView(){ var contentArray = [LmyPickerObject]() let plistPath:String = Bundle.main.path(forAuxiliaryExecutable: "area.plist") ?? "" let plistArray = NSArray(contentsOfFile: plistPath) let proviceArray = NSArray(array: plistArray!) for i in 0..<proviceArray.count { var subs0 = [LmyPickerObject]() let cityzzz:NSDictionary = proviceArray.object(at: i) as! NSDictionary let cityArray:NSArray = cityzzz.value(forKey: "cities") as! NSArray for j in 0..<cityArray.count { var subs1 = [LmyPickerObject]() let areazzz:NSDictionary = cityArray.object(at: j) as! NSDictionary let areaArray:NSArray = areazzz.value(forKey: "areas") as! NSArray for m in 0..<areaArray.count { let object = LmyPickerObject() object.title = areaArray.object(at: m) as? String subs1.append(object) } let citymmm:NSDictionary = cityArray.object(at: j) as! NSDictionary let cityStr:String = citymmm.value(forKey: "city") as! String let object = LmyPickerObject() object.title = cityStr subs0.append(object) object.subArray = subs1 } let provicemmm:NSDictionary = proviceArray.object(at: i) as! NSDictionary let proviceStr:String? = provicemmm.value(forKey: "state") as! String? let object = LmyPickerObject() object.title = proviceStr object.subArray = subs0 contentArray.append(object) } let picker = LmyPicker(delegate: self, style: .nomal) picker.contentArray = contentArray picker.show() } func chooseElements(picker: LmyPicker, content: [Int : Int]) { var str:String = "" if let array = picker.contentArray { var tempArray = array for i in 0..<content.keys.count { let value:Int! = content[i] if value < tempArray.count { let obj:LmyPickerObject = tempArray[value] let title = obj.title ?? "" if str.count>0 { str = str.appending("-\(title)") }else { str = title; } if let arr = obj.subArray { tempArray = arr } } } QPCLog( str) self.areaLabel.text = str } } func chooseDate(picker: LmyPicker, date: Date) { } func seletedTimeClick(str : String){ let datepicker = WSDatePickerView.init(dateStyle: DateStyleShowYearMonthDayHourMinute) { [weak self](selectDate) in guard let weakSelf = self else {return} let dateStr = selectDate?.string_from(formatter: "yyyy-MM-dd HH:mm") QPCLog("选择的日期:\(String(describing: dateStr))") weakSelf.timeSeletedLabel.text = dateStr } datepicker?.dateLabelColor = UIColor.textBlueColor datepicker?.datePickerColor = UIColor.textBlackColor datepicker?.doneButtonColor = UIColor.textBlueColor datepicker?.show() } } extension OrderInstallLockController:CNContactPickerDelegate{ //通讯录 @objc func seletedAdressList(){ if #available(iOS 9.0, *) { let pickerVC = CNContactPickerViewController() pickerVC.delegate = self self.present(pickerVC, animated: true, completion: nil) } else { let listVC = ABPeoplePickerNavigationController() listVC.peoplePickerDelegate = self self.present(listVC, animated: true, completion: nil) } } @available(iOS 9.0, *) func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) { QPCLog(contact.familyName) //姓 QPCLog(contact.givenName) //名 QPCLog(contact.phoneNumbers) for i in contact.phoneNumbers { let phoneNum = i.value.stringValue //电话号码 seletedNumber = phoneNum } numberTF.text = seletedNumber nameTF.text = contact.familyName + contact.givenName } @available(iOS 9.0, *) func contactPickerDidCancel(_ picker: CNContactPickerViewController) { QPCLog("点击了取消") } } extension OrderInstallLockController :ABPeoplePickerNavigationControllerDelegate{ func peoplePickerNavigationController(_ peoplePicker: ABPeoplePickerNavigationController, didSelectPerson person: ABRecord) { let phoneValues : ABMutableMultiValue? = ABRecordCopyValue(person, kABPersonPhoneProperty).takeRetainedValue() if phoneValues != nil{ print("选中电话:") for i in 0..<ABMultiValueGetCount(phoneValues){ let phoneLabel = ABMultiValueCopyLabelAtIndex(phoneValues, i).takeRetainedValue() as CFString // 转为本地标签名(能看得懂的标签名,比如work、home) let localizedPhoneLabel = ABAddressBookCopyLocalizedLabel(phoneLabel).takeRetainedValue() as String let value = ABMultiValueCopyValueAtIndex(phoneValues, i) let phone = value?.takeRetainedValue() as! String print("---\(localizedPhoneLabel):\(phone)") } } } func peoplePickerNavigationControllerDidCancel(_ peoplePicker: ABPeoplePickerNavigationController) { peoplePicker.dismiss(animated: true, completion: nil) } }
// // AudioError.swift // AVToolkit // // Created by Evan Xie on 2018/9/16. // Copyright © 2018 Dreamer Wings. All rights reserved. // import Foundation import AudioToolbox /** Error codes defined in Audio File Services. */ public enum AudioFileError: Error, CustomDebugStringConvertible { case badPropertySize case endOfFile case fileNotFound case invalidChunk case invalidFile case invalidFilePosition case invalidPacketOffset case notAllow64BitDataSize case notOpen case notOptimized case permissions case unsupportedAudioFileOperation case unsupportedDataFormat case unsupportedFileType case unsupportedProperty case unspecifiedError(OSStatus) public init(_ osstatus: OSStatus) { switch osstatus { case kAudioFileBadPropertySizeError: self = .badPropertySize case kAudioFileEndOfFileError: self = .endOfFile case kAudioFileFileNotFoundError: self = .fileNotFound case kAudioFileInvalidChunkError: self = .invalidChunk case kAudioFileInvalidFileError: self = .invalidFile case kAudioFilePositionError: self = .invalidFilePosition case kAudioFileInvalidPacketOffsetError: self = .invalidPacketOffset case kAudioFileDoesNotAllow64BitDataSizeError: self = .notAllow64BitDataSize case kAudioFileNotOpenError: self = .notOpen case kAudioFileNotOptimizedError: self = .notOptimized case kAudioFilePermissionsError: self = .permissions case kAudioFileOperationNotSupportedError: self = .unsupportedAudioFileOperation case kAudioFileUnsupportedDataFormatError: self = .unsupportedDataFormat case kAudioFileUnsupportedFileTypeError: self = .unsupportedFileType case kAudioFileUnsupportedPropertyError: self = .unsupportedProperty default: self = .unspecifiedError(osstatus) } } public var rawErrorCode: OSStatus { switch self { case .badPropertySize: return kAudioFileBadPropertySizeError case .endOfFile: return kAudioFileEndOfFileError case .fileNotFound: return kAudioFileFileNotFoundError case .invalidChunk: return kAudioFileInvalidChunkError case .invalidFile: return kAudioFileInvalidFileError case .invalidFilePosition: return kAudioFilePositionError case .invalidPacketOffset: return kAudioFileInvalidPacketOffsetError case .notAllow64BitDataSize: return kAudioFileDoesNotAllow64BitDataSizeError case .notOpen: return kAudioFileNotOpenError case .notOptimized: return kAudioFileNotOptimizedError case .permissions: return kAudioFilePermissionsError case .unsupportedAudioFileOperation: return kAudioFileOperationNotSupportedError case .unsupportedDataFormat: return kAudioFileUnsupportedDataFormatError case .unsupportedFileType: return kAudioFileUnsupportedFileTypeError case .unsupportedProperty: return kAudioFileUnsupportedPropertyError case .unspecifiedError(let code): return code } } public var debugDescription: String { switch self { case .badPropertySize: return "The size of the property data was not correct" case .endOfFile: return "End of file" case .fileNotFound: return "File not found" case .invalidChunk: return "Either the chunk does not exist in the file or it is not supported by the file" case .invalidFile: return "The file is malformed, or otherwise not a valid instance of an audio file of its type" case .invalidFilePosition: return "Invalid file position" case .invalidPacketOffset: return "A packet offset was past the end of the file, or not at the end of the file when a VBR format was written, or a corrupt packet size was read when the packet table was built" case .notAllow64BitDataSize: return "The file offset was too large for the file type. The AIFF and WAVE file format types have 32-bit file size limits" case .notOpen: return "The file is closed" case .notOptimized: return "The chunks following the audio data chunk are preventing the extension of the audio data chunk. To write more data, you must optimize the file" case .permissions: return "The operation violated the file permissions. For example, an attempt was made to write to a file opened with the kAudioFileReadPermission constant" case .unsupportedAudioFileOperation: return "The operation cannot be performed. For example, setting the kAudioFilePropertyAudioDataByteCount constant to increase the size of the audio data in a file is not a supported operation. Write the data instead" case .unsupportedDataFormat: return "The data format is not supported by this file type" case .unsupportedFileType: return "The file type is not supported" case .unsupportedProperty: return "The property is not supported" case .unspecifiedError(let code): return "An unspecified error has occurred, error code = \(code)" } } }
private(set) var privateSetGlobal = 0 struct Members { private(set) var privateSetProp = 0 private(set) subscript() -> Int { get { return 0 } set {} } }
// // StringUtils.swift // import Foundation extension String { func containsOnlyCharactersIn(matchCharacters: String) -> Bool { let disallowedCharacterSet = NSCharacterSet(charactersInString: matchCharacters).invertedSet return self.rangeOfCharacterFromSet(disallowedCharacterSet) == nil } func isNumeric() -> Bool { let scanner = NSScanner(string: self) scanner.locale = NSLocale.currentLocale() return scanner.scanDecimal(nil) && scanner.atEnd } }
// // MyCountryListCustomCell.swift // My Canada // // Created by Lexicon on 11/02/18. // Copyright © 2018 Lexicon. All rights reserved. // import UIKit class MyCountryListCustomCell: UITableViewCell { var lblTitle : UILabel! var imgImage: UIImageView! var lblDescription:UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) createControlsForMyCountryList() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func createControlsForMyCountryList() { lblTitle = UILabel() lblTitle.backgroundColor = UIColor.lightGray lblTitle.textAlignment = .center lblTitle.font = UIFont.systemFont(ofSize: 16) lblTitle.translatesAutoresizingMaskIntoConstraints = false self.addSubview(lblTitle) lblDescription = UILabel() lblDescription.numberOfLines = 0 lblDescription.font = UIFont.systemFont(ofSize: 12) lblDescription.translatesAutoresizingMaskIntoConstraints = false self.addSubview(lblDescription) imgImage = UIImageView() imgImage.backgroundColor = UIColor.orange imgImage.translatesAutoresizingMaskIntoConstraints = false self.addSubview(imgImage) } func setConstraints(lblHeight:CGFloat) { let trailing = NSLayoutConstraint(item:lblTitle, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.trailing, multiplier: 1.0, constant: 0.0) let leading = NSLayoutConstraint(item:lblTitle, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.leading, multiplier: 1.0, constant: 0.0) let top = NSLayoutConstraint(item: lblTitle, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0.0) lblTitle.addConstraint(NSLayoutConstraint(item: lblTitle, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 20)) self.addConstraints([trailing, leading, top]) let leadingImage = NSLayoutConstraint(item:imgImage, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.leading, multiplier: 1.0, constant: 5.0) let topImage = NSLayoutConstraint(item: imgImage, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: lblTitle, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 25.0) self.addConstraints([leadingImage,topImage]) imgImage.addConstraint(NSLayoutConstraint(item: imgImage, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 50)) imgImage.addConstraint(NSLayoutConstraint(item: imgImage, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 50)) let trailingDescripion = NSLayoutConstraint(item:lblDescription, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.trailing, multiplier: 1.0, constant: 0.0) let leadingdescription = NSLayoutConstraint(item:lblDescription, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.leading, multiplier: 1.0, constant: 5.0) let topDescription = NSLayoutConstraint(item: lblDescription, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: imgImage, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 55.0) lblDescription.addConstraint(NSLayoutConstraint(item: lblDescription, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: lblHeight)) self.addConstraints([trailingDescripion, leadingdescription, topDescription]) } } extension UIImageView { func downloadImageFrom(link:String, contentMode: UIViewContentMode) { URLSession.shared.dataTask( with: NSURL(string:link)! as URL, completionHandler: { (data, response, error) -> Void in DispatchQueue.main.async { self.contentMode = contentMode if let data = data { self.image = UIImage(data: data) } } }).resume() } }