text stringlengths 8 1.32M |
|---|
//
// AudioRecorderController.swift
// Experiences
//
// Created by Claudia Maciel on 7/17/20.
// Copyright © 2020 thecoderpilot. All rights reserved.
//
import UIKit
import AVFoundation
protocol AudioRecorderControllerDelegate {
func didNotReceivePermission() -> Void
}
class AudioRecorderController {
// MARK: - Properties
var audioPlayer: AVAudioPlayer? {
didSet {
guard let audioPlayer = audioPlayer else { return }
audioPlayer.isMeteringEnabled = true
}
}
var recordingURL: URL?
var audioRecorder: AVAudioRecorder?
var delegate: AudioRecorderControllerDelegate?
// MARK: - Playback
// var isPlaying: Bool {
// audioPlayer?.isPlaying ?? false
// }
//
// func loadAudio() {
// let songURL = Bundle.main.url(forResource: "piano", withExtension: "mp3")!
//
// do {
// audioPlayer = try AVAudioPlayer(contentsOf: songURL)
// } catch {
// preconditionFailure("Failure to load audio file \(error)")
// }
// }
//
// func prepareAudioSession() throws {
// let session = AVAudioSession.sharedInstance()
// try session.setCategory(.playAndRecord, options: [.defaultToSpeaker])
// try session.setActive(true, options: []) // can fail if on a phone call, for instance
// }
//
// func play() {
// do {
// try prepareAudioSession()
// audioPlayer?.play()
// updateViews()
// startTimer()
// } catch {
// print("Cannot play audio: \(error)")
// }
// }
//
// func pause() {
// audioPlayer?.pause()
// updateViews()
// cancelTimer()
// }
// MARK: - Recording
var isRecording: Bool {
audioRecorder?.isRecording ?? false
}
func createNewRecordingURL() -> URL {
let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let name = ISO8601DateFormatter.string(from: Date(), timeZone: .current, formatOptions: .withInternetDateTime)
let file = documents.appendingPathComponent(name, isDirectory: false).appendingPathExtension("caf")
// print("recording URL: \(file)")
return file
}
func requestPermissionOrStartRecording() {
switch AVAudioSession.sharedInstance().recordPermission {
case .undetermined:
AVAudioSession.sharedInstance().requestRecordPermission { granted in
guard granted == true else {
print("We need microphone access")
return
}
print("Recording permission has been granted!")
// NOTE: Invite the user to tap record again, since we just interrupted them, and they may not have been ready to record
}
case .denied:
delegate?.didNotReceivePermission()
case .granted:
startRecording()
@unknown default:
break
}
}
func startRecording() {
recordingURL = createNewRecordingURL()
let format = AVAudioFormat(standardFormatWithSampleRate: 44_100, channels: 1)!
do {
audioRecorder = try AVAudioRecorder(url: recordingURL!, format: format)
audioRecorder?.isMeteringEnabled = true
audioRecorder?.record()
} catch {
preconditionFailure("The audio recorder could not be created with \(recordingURL!) and \(format): \(error)")
}
}
func stopRecording() {
audioRecorder?.stop()
}
func toggleRecording() {
if isRecording {
stopRecording()
} else {
requestPermissionOrStartRecording()
}
}
//
// // MARK: - Actions
//
// @IBAction func togglePlayback(_ sender: Any) {
// if isPlaying {
// pause()
// } else {
// play()
// }
// }
//
// @IBAction func updateCurrentTime(_ sender: UISlider) {
// if isPlaying {
// pause()
// }
//
// audioPlayer?.currentTime = TimeInterval(sender.value)
// updateViews()
// }
//
}
|
//
// GitHubReference.swift
// GitHubAPICommand
//
// Created by Wayne Hsiao on 2018/9/23.
//
import Foundation
import ObjectMapper
public struct GitHubReference: GitHubAPIResponse {
public fileprivate(set) var ref: String?
public fileprivate(set) var nodeId: String?
public fileprivate(set) var url: String?
public fileprivate(set) var object: GitHubReference.Object?
public struct Object: GitHubAPIResponse {
public fileprivate(set) var type: String?
public fileprivate(set) var sha: String?
public fileprivate(set) var url: String?
public init?(map: Map) {
// NO-OP
}
public mutating func mapping(map: Map) {
type <- map["type"]
sha <- map["sha"]
url <- map["url"]
}
}
public init?(map: Map) {
// NO-OP
}
public mutating func mapping(map: Map) {
ref <- map["ref"]
nodeId <- map["node_id"]
url <- map["url"]
object <- map["object"]
}
}
|
//
// QuestionController.swift
// Honest Badger
//
// Created by Steve Cox on 7/18/16.
// Copyright © 2016 stevecoxio. All rights reserved.
//
import Foundation
class QuestionController {
var questions: [Question] = []
static let sharedController = QuestionController()
static func submitQuestion(_ questionText: String, timeLimit: Date, completion: @escaping (_ success: Bool, _ questionID: String?) -> Void){
var question = Question(questionText: questionText, timeLimit: timeLimit, authorID: UserController.shared.currentUserID)
question.save()
if let questionID = question.identifier {
completion(true, questionID)
}
else {
completion(false, nil)
}
}
func deleteQuestionFromDatabase(_ question: Question){
if let identifier = question.identifier {
FirebaseController.ref.child("users").child(UserController.shared.currentUserID).child("asked").child(identifier).removeValue()
question.delete()
}
}
func deleteAskedQuestionFromList(_ question: Question){
if let identifier = question.identifier {
FirebaseController.ref.child("users").child(UserController.shared.currentUserID).child("asked").child(identifier).removeValue()
}
}
func deleteAnsweredQuestionFromList(_ question: Question){
if let identifier = question.identifier {
FirebaseController.ref.child("users").child(UserController.shared.currentUserID).child("answered").child(identifier).removeValue()
}
}
static func fetchQuestions(_ completion: @escaping (_ questions: [Question]) -> Void){
FirebaseController.ref.child("questions").observe(.value, with: { (dataSnapshot) in
guard let dataDictionary = dataSnapshot.value as? [String: [String: AnyObject]] else {
completion([])
return
}
let questions = dataDictionary.flatMap { Question(dictionary: $1, identifier: $0) }
completion(questions)
})
}
static func fetch200Questions(_ completion: @escaping (_ questions: [Question]) -> Void){
FirebaseController.ref.child("questions").queryLimited(toLast: 200).observe(.value, with: { (dataSnapshot) in
guard let dataDictionary = dataSnapshot.value as? [String: [String: AnyObject]] else {
completion([])
return
}
let questions = dataDictionary.flatMap { Question(dictionary: $1, identifier: $0) }
completion(questions)
})
}
static func fetchAskedQuestionsForUserID(uid: String, completion: @escaping (_ questions: [Question]?) -> Void) {
let users = FirebaseController.ref.child("users")
users.child(UserController.shared.currentUserID).child("asked").observeSingleEvent(of: .value, with: { (snapshot) in
if let questionDictionary = snapshot.value as? [String : AnyObject] {
let questionIDs = questionDictionary.flatMap({ ($0.0) })
fetchQuestionsThatMatchQuery(questionIDs: questionIDs, completion: { (questions) in
completion(questions)
})
} else {
completion(nil)
}
})
}
static func fetchAnsweredQuestionsForUserID(uid: String, completion: @escaping (_ questions: [Question]?) -> Void) {
let users = FirebaseController.ref.child("users")
users.child(UserController.shared.currentUserID).child("answered").observeSingleEvent(of: .value, with: { (snapshot) in
if let questionDictionary = snapshot.value as? [String : AnyObject] {
let questionIDs = questionDictionary.flatMap({ ($0.0) })
fetchQuestionsThatMatchQuery(questionIDs: questionIDs, completion: { (questions) in
completion(questions)
})
} else {
completion(nil)
}
})
}
static func fetchQuestionsThatMatchQuery(questionIDs: [String], completion: @escaping (_ questions: [Question]?) -> Void) {
var questions: [Question] = []
let questionFetchGroup = DispatchGroup()
for questionID in questionIDs {
questionFetchGroup.enter()
FirebaseController.ref.child("questions").child(questionID).observeSingleEvent(of: .value, with: { (snapshot) in
if let questionDictionary = snapshot.value as? [String : AnyObject], let question = Question(dictionary: questionDictionary, identifier: questionID) {
questions.append(question)
}
questionFetchGroup.leave()
})
}
questionFetchGroup.notify(queue: DispatchQueue.main) {
completion(questions)
}
}
}
|
//
// ViewController.swift
// Twilio Voice Quickstart - Swift
//
// Copyright © 2016 Twilio, Inc. All rights reserved.
//
import UIKit
import AVFoundation
import PushKit
import TwilioVoiceClient
import UserNotifications
let baseURLString = GlobalVariables.rootURL
let accessTokenEndpoint = "pusher/ios_auth.json?environment=\(GlobalVariables.environment)&user_id="+BottleGlobal.userID()
class TwilioViewController: UIViewController {
var deviceTokenString:String?
var speaker = false
var incomingCall:TVOIncomingCall?
var outgoingCall:TVOOutgoingCall?
var conversationUserPair: ConversationUserPair?
@IBOutlet var mainLabel: UILabel!
@IBOutlet var subLabel: UILabel!
@IBOutlet var leftButton: UIButton!
@IBOutlet var rightButton: UIButton!
@IBOutlet var bottomButton: UIButton!
@IBOutlet var middleLeftButton: UIButton!
@IBOutlet var middleRightButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.setupAppearance()
NotificationCenter.default.addObserver(self, selector: #selector(TwilioViewController.applicationDidBecomeActive(notification:)), name: NSNotification.Name(rawValue: "applicationDidBecomeActive"), object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.setupAppearance()
self.setLabels()
UIDevice.current.isProximityMonitoringEnabled = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIDevice.current.isProximityMonitoringEnabled = false
}
deinit {
print("deinit TwilioViewController")
NotificationCenter.default.removeObserver(self)
}
func applicationDidBecomeActive(notification: Notification) {
if let incomingCall = self.incomingCall {
if incomingCall.state == TVOIncomingCallState.disconnected || incomingCall.state == TVOIncomingCallState.cancelled {
self.endCall()
}
} else if let outgoingCall = self.outgoingCall {
if outgoingCall.state == TVOOutgoingCallState.disconnected {
self.endCall()
}
}
}
func assign(incomingCall: TVOIncomingCall, conversationUserPair: ConversationUserPair? = nil) {
self.conversationUserPair = conversationUserPair
self.incomingCall = incomingCall
//self.incomingCall?.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(TwilioViewController.callConnected(_:)), name: Notification.Name("callConnected"), object: self.incomingCall)
NotificationCenter.default.addObserver(self, selector: #selector(TwilioViewController.callDisconnected(_:)), name: Notification.Name("callDisconnected"), object: self.incomingCall)
}
func assign(outgoingCall: TVOOutgoingCall, conversationUserPair: ConversationUserPair? = nil) {
self.conversationUserPair = conversationUserPair
self.outgoingCall = outgoingCall
//self.outgoingCall?.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(TwilioViewController.callConnected(_:)), name: Notification.Name("callConnected"), object: self.outgoingCall)
NotificationCenter.default.addObserver(self, selector: #selector(TwilioViewController.callDisconnected(_:)), name: Notification.Name("callDisconnected"), object: self.outgoingCall)
}
func setLabels() {
if let title = self.conversationUserPair?.conversationTitle {
self.mainLabel.text = title
} else {
self.mainLabel.text = "New Bottle Caller"
}
if let _ = self.incomingCall {
self.subLabel.text = "is calling..."
} else if let _ = self.outgoingCall {
self.subLabel.text = "calling..."
}
}
func callConnected(_ notification: Notification) {
self.beginCall()
}
func callDisconnected(_ notification: Notification) {
self.endCall()
}
//actions
func beginCall() {
self.answeredAnimation()
self.subLabel.text = "connected"
}
func endCall() {
self.incomingCall?.disconnect()
self.outgoingCall?.disconnect()
self.subLabel.text = "disconnected"
self.dismiss(animated: true, completion: nil)
}
// MARK: UI actions
@IBAction func leftButtonAction(_ sender: Any) {
if let incomingCall = self.incomingCall {
incomingCall.reject()
}
self.endCall()
}
@IBAction func rightButtonAction(_ sender: Any) {
if let incomingCall = self.incomingCall {
incomingCall.accept(with: TwilioCoordinator.sharedInstance)
}
}
@IBAction func bottomButtonAction(_ sender: Any) {
self.endCall()
}
@IBAction func middleLeftButtonAction(_ sender: Any) {
if let incomingCall = self.incomingCall {
self.mute(!incomingCall.isMuted)
}
if let outgoingCall = self.outgoingCall {
self.mute(!outgoingCall.isMuted)
}
}
@IBAction func middleRightButtonAction(_ sender: Any) {
do {
try self.setSpeaker(!speaker)
} catch {
}
}
// MARK: helpers
func setupAppearance() {
self.leftButton.backgroundColor = UIColor.red.withAlphaComponent(0.8)
self.leftButton.layer.cornerRadius = self.leftButton.bounds.width/2.0
self.leftButton.titleLabel?.text = nil
self.rightButton.backgroundColor = UIColor.green.withAlphaComponent(0.8)
self.rightButton.layer.cornerRadius = self.leftButton.bounds.width/2.0
self.rightButton.titleLabel?.text = nil
self.middleLeftButton.setImage(UIImage(named: "mute.png")?.withRenderingMode(.alwaysTemplate), for: .normal)
self.middleRightButton.setImage(UIImage(named: "speaker.png")?.withRenderingMode(.alwaysTemplate), for: .normal)
self.middleLeftButton.tintColor = UIColor.white
self.middleRightButton.tintColor = UIColor.white
self.middleLeftButton.imageView?.tintColor = UIColor.white
self.middleRightButton.imageView?.tintColor = UIColor.white
self.bottomButton.setTitle("End", for: UIControlState.normal)
self.bottomButton.backgroundColor = UIColor.red.withAlphaComponent(0.8)
self.bottomButton.layer.cornerRadius = 8.0
self.bottomButton.titleLabel?.textColor = UIColor.white
self.bottomButton.setTitleColor(UIColor.white, for: UIControlState.normal)
if let _ = self.incomingCall {
self.leftButton.alpha = 1.0
self.rightButton.alpha = 1.0
self.bottomButton.alpha = 0.0
} else if let _ = self.outgoingCall {
self.leftButton.alpha = 0.0
self.rightButton.alpha = 0.0
self.bottomButton.alpha = 1.0
}
}
func answeredAnimation() {
self.rightButton.alpha = 0.0
self.leftButton.alpha = 0.0
self.bottomButton.alpha = 1.0
}
// MARK: audio
func setSpeaker(_ enabled: Bool) throws {
if enabled {
try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.speaker);
self.middleRightButton.setImage(UIImage(named: "unspeaker.png")?.withRenderingMode(.alwaysTemplate), for: .normal)
speaker = true
} else {
try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.none);
self.middleRightButton.setImage(UIImage(named: "speaker.png")?.withRenderingMode(.alwaysTemplate), for: .normal)
speaker = false
}
}
func mute(_ isMuted: Bool) {
self.incomingCall?.isMuted = isMuted
self.outgoingCall?.isMuted = isMuted
if let incomingCall = self.incomingCall {
if incomingCall.isMuted {
self.middleLeftButton.setImage(UIImage(named: "unmute.png")?.withRenderingMode(.alwaysTemplate), for: .normal)
} else {
self.middleLeftButton.setImage(UIImage(named: "mute.png")?.withRenderingMode(.alwaysTemplate), for: .normal)
}
}
if let outgoingCall = self.outgoingCall {
if outgoingCall.isMuted {
self.middleLeftButton.setImage(UIImage(named: "unmute.png")?.withRenderingMode(.alwaysTemplate), for: .normal)
} else {
self.middleLeftButton.setImage(UIImage(named: "mute.png")?.withRenderingMode(.alwaysTemplate), for: .normal)
}
}
}
}
|
import CoreLocation
internal final class Decoder {
/**
Special handling for the decoding of the encoded points string.
- paramter encoded: The encoded string of points.
- paramter is3D: Specifies if the points in the encoded string also contains elevation.
*/
class func decodePoints(_ encoded: String, is3D: Bool = false) -> [CLLocation] {
var points = [CLLocation]()
let enc = encoded.unicodeScalars
let len = enc.count
var index = 0
var lat: CLLocationDegrees = 0, lng: CLLocationDegrees = 0, alt: CLLocationDegrees = 0
while (index < len) {
// latitude
var b = 0, shift = 0, result = 0
repeat {
let subscriptIndex = enc.index(enc.startIndex, offsetBy: index)
let char = enc[subscriptIndex]
b = Int(char.value) - 63
result |= (b & 0x1f) << shift
shift += 5
index = index + 1
} while(b >= 0x20)
let deltaLatitude = Double(((result & 1) != 0 ? ~(result >> 1) : (result >> 1)))
lat = lat + deltaLatitude
// longitude
shift = 0
result = 0
repeat {
let subscriptIndex = enc.index(enc.startIndex, offsetBy: index)
let char = enc[subscriptIndex]
b = Int(char.value) - 63
result |= (b & 0x1f) << shift
shift += 5
index = index + 1
} while(b >= 0x20)
let deltaLongitude = Double(((result & 1) != 0 ? ~(result >> 1) : (result >> 1)))
lng = lng + deltaLongitude
if is3D {
// altitude
shift = 0
result = 0
repeat {
let subscriptIndex = enc.index(enc.startIndex, offsetBy: index)
let char = enc[subscriptIndex]
b = Int(char.value) - 63
result |= (b & 0x1f) << shift
shift += 5
index = index + 1
} while(b >= 0x20)
let deltaAltitude = Double(((result & 1) != 0 ? ~(result >> 1) : (result >> 1)))
alt = alt + deltaAltitude
}
let point = CLLocation(latitude: lat / 1e5, longitude: lng / 1e5, altitude: alt / 100)
points.append(point)
}
return points
}
}
|
//
// ContactTableViewCell.swift
// Fabric
//
// Created by Samantha Lauer on 2016-06-23.
// Copyright © 2016 Samantha Lauer. All rights reserved.
//
import UIKit
class ContactTableViewCell: UITableViewCell {
//MARK Properties
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var nickNameLabel: 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
}
}
|
//
// Constants.swift
// ios_starter_kit
//
// Created by 星川 健介 on 2016/06/27.
// Copyright © 2016年 star__hoshi. All rights reserved.
//
import Foundation
struct Constants {
struct SONETORE {
struct URL {
#if DEBUG
static let INDEX = NSURL(string: "https://musiced-dev.herokuapp.com/")!
#elseif STAGING
static let INDEX = NSURL(string: "https://musiced-st.herokuapp.com/")!
#else
static let INDEX = NSURL(string: "https://musiced.herokuapp.com/")!
#endif
static let LOGIN = NSURL(string: "\(Constants.SONETORE.URL.INDEX)users/login/")!
struct API {
static let V1 = NSURL(string: "\(Constants.SONETORE.URL.INDEX)api/v1/")!
}
}
}
struct STARHOSHI {
struct URL {
static let GITHUB = NSURL(string: "https://github.com/starhoshi")!
static let TWITTER = NSURL(string: "https://twitter.com/star__hoshi")!
}
}
}
|
//
// GPX436Document.swift
// assign4
//
// Created by Kevin Nogales on 4/22/20.
// Copyright © 2020 Kevin Nogales. All rights reserved.
//
import Foundation
import UIKit
class GPX436Document: UIDocument {
var container: GPX436Container?
override func contents(forType typeName: String) throws -> Any {
//Encode document with an instance of NSData or NSFileWrapper.
return container?.json ?? Data()
}
override func load(fromContents contents: Any, ofType typeName: String?) throws {
// Load document from contents.
if let data = contents as? Data {
container = GPX436Container(json: data)
}
}
}
|
//
// BookmarksTests.swift
//
//
// Created by Stephen Beitzel on 11/25/22.
// Copyright © 2022 MastodonKit. All rights reserved.
//
import XCTest
@testable import MastodonKit
final class BookmarksTests: XCTestCase {
func testRequestAllDefaultLimit() throws {
let request = Bookmarks.all()
// Endpoint
XCTAssertEqual(request.path, "/api/v1/bookmarks")
// Method
XCTAssertEqual(request.method.name, "GET")
XCTAssertNil(request.method.httpBody)
XCTAssertNil(request.method.queryItems)
}
}
|
//
// Lens+UITabBarItem.swift
// IDPDesign
//
// Created by Oleksa 'trimm' Korin on 9/2/17.
// Copyright © 2017 Oleksa 'trimm' Korin. All rights reserved.
//
import UIKit
public func badgeTextAttributes<Object: UITabBarItem>(for state: UIControl.State) -> Lens<Object, [NSAttributedString.Key : Any]?> {
return Lens(
get: { $0.badgeTextAttributes(for: state) },
setter: { $0.setBadgeTextAttributes($1, for: state) }
)
}
|
//
// ContactsCell.swift
// Contacts Test Application
//
// Created by Dmitry Grusha on 01.06.2018.
// Copyright © 2018 Dmitry Grusha. All rights reserved.
//
import UIKit
class ContactsCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// ParallaxItem.swift
// Genealogy
//
// Created by xiao huama on 15/8/30.
// Copyright (c) 2015年 xiao huama. All rights reserved.
//
import UIKit
class RMParallaxItem:NSObject {
var image: UIImage!
var text: String!
init(image: UIImage, text: String) {
self.image = image
self.text = text
}
}
|
//
// Day8ViewController.swift
// DailyiOSAnimations
//
// Created by jinsei shima on 2018/07/12.
// Copyright © 2018 Jinsei Shima. All rights reserved.
//
import UIKit
class Day8ViewController: UIViewController {
let controlButtonView = UIView()
var scaleAnimator: UIViewPropertyAnimator!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
controlButtonView.frame = CGRect(x: 0, y: 0, width: 80, height: 80)
controlButtonView.center = view.center
controlButtonView.backgroundColor = UIColor.darkGray
controlButtonView.layer.cornerRadius = 8.0
controlButtonView.clipsToBounds = true
view.addSubview(controlButtonView)
if traitCollection.forceTouchCapability == .available {
let forceGesture = ForceTouchGestureRecognizer(target: self, action: #selector(self.forceTouchAction(_:)))
controlButtonView.addGestureRecognizer(forceGesture)
}
else {
print("force touch capability unabailable")
}
}
var initialBounds: CGRect = .zero
@objc func forceTouchAction(_ sender: ForceTouchGestureRecognizer) {
switch sender.state {
case .began:
initialBounds = controlButtonView.bounds
scaleAnimator = UIViewPropertyAnimator(duration: 0.16, curve: UIViewAnimationCurve.easeInOut, animations: {
self.controlButtonView.transform = CGAffineTransform(scaleX: 2.0, y: 2.0)
})
scaleAnimator.startAnimation()
scaleAnimator.pauseAnimation()
case .changed:
scaleAnimator.fractionComplete = sender.progress
case .ended,.cancelled, .failed, .possible:
scaleAnimator.isReversed = true
scaleAnimator.startAnimation()
}
}
}
class ForceTouchGestureRecognizer: UIGestureRecognizer {
var forceValue: CGFloat = 0.0
var maximumForceValue: CGFloat = 0.0
var progress: CGFloat {
return forceValue / maximumForceValue
}
// override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
// super.touchesBegan(touches, with: event)
// self.state = .began
// forceTouch(touches: touches)
// }
//
// override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
// super.touchesMoved(touches, with: event)
// self.state = .changed
// forceTouch(touches: touches)
//
// if forceValue >= maximumForceValue {
// self.state = .ended
// }
// }
//
// override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
// super.touchesEnded(touches, with: event)
// self.state = .ended
// forceTouch(touches: touches)
// }
//
// private func forceTouch(touches: Set<UITouch>) {
//
// guard (touches.count == 1), let touch = touches.first else {
// state = .failed
// return
// }
//
// forceValue = touch.force
// maximumForceValue = touch.maximumPossibleForce
//
// print(forceValue, maximumForceValue, progress)
// }
//
// override func reset() {
// super.reset()
// forceValue = 0.0
// maximumForceValue = 0.0
// }
}
|
//
// WebViewController.swift
// GTMRouterExample
//
// Created by 骆扬 on 2018/6/26.
// Copyright © 2018年 luoyang. All rights reserved.
//
import UIKit
import WebKit
class WebViewController: UIViewController, WKNavigationDelegate {
public var isTreatMemeryCrushWithReload = false
var urlString: String?
private var webUrl: URL? {
return urlString?.url()
}
public var webView: WKWebView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupWkWebView()
loadWebPage()
}
func setupWkWebView() {
// init weakScriptHandler
let configuration = WKWebViewConfiguration() // 配置
configuration.processPool = WKProcessPool() // WkWebView 实例间共享Cookies
configuration.preferences.minimumFontSize = 10
configuration.preferences.javaScriptEnabled = true
configuration.allowsInlineMediaPlayback = true // 允许视频播放回退
configuration.userContentController = WKUserContentController() // 交互对象
// configuration.userContentController.add(self.weakScriptHandler, name: "GTMWebKitAPI")
let wkWebV = WKWebView(frame: .zero, configuration: configuration) // WKWebView
// wkWebV.uiDelegate = self
wkWebV.navigationDelegate = self
wkWebV.allowsBackForwardNavigationGestures = true
self.view.addSubview(wkWebV)
// wkWebV.frame = self.view.bounds//CGRect(x: 0, y: 0, width: 320, height: 640)
self.webView = wkWebV
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.webView?.frame = self.view.bounds
}
// MARK: - Private
func loadWebPage() {
guard let url = self.webUrl else {
fatalError("GTMWebKit ----->没有为GTMWebViewController提供网页的URL")
}
self.loadWithUrl(url: url)
}
func loadWithUrl(url: URL) {
self.webView?.load(URLRequest.init(url: url))
}
// MARK: - WKNavigationDelegate
public func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
}
// MARK: Initiating the Navigation
public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
}
// MARK: Responding to Server Actions
public func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
print(navigation.description)
}
// Authentication Challenges
public func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
var disposition: URLSession.AuthChallengeDisposition = URLSession.AuthChallengeDisposition.performDefaultHandling
var credential: URLCredential?
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
disposition = URLSession.AuthChallengeDisposition.useCredential
credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
}
completionHandler(disposition, credential)
}
// MARK: Tracking Load Progress
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("GTMWebKit ----->webView didFinish")
}
public func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
// 如果出现频繁刷新的情况,说明页面占用内存确实过大,需要前端作优化处理
if self.isTreatMemeryCrushWithReload {
webView.reload() // 解决内存消耗过度出现白屏的问题
}
}
// MARK: Permitting Navigation
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
// self.updateButtonItems() // 更新导航按钮状态
decisionHandler(.allow)
}
public func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
print("GTMWebKit ----->decidePolicyFor navigationResponse")
decisionHandler(.allow)
}
// MARK: Reacting to Errors
public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
let nserror = error as NSError
if nserror.code == NSURLErrorCancelled {
return
}
}
public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
let nserror = error as NSError
if nserror.code == NSURLErrorCancelled {
return
}
}
}
public protocol URLConvertible {
func url() -> URL?
}
extension String: URLConvertible {
public func url() -> URL? {
return URL.init(string: self)
}
}
extension URL: URLConvertible {
public func url() -> URL? {
return self
}
}
|
//
// FlickrPhotosPage.swift
// Virtual Tour
//
// Created by Rudy James Jr on 6/9/20.
// Copyright © 2020 James Consutling LLC. All rights reserved.
//
import Foundation
struct FlickrPhotosPage: Codable {
let page: Int
let pages: Int
let perPage: Int
let total: String
let photos: [FlickrPhoto]
enum CodingKeys: String, CodingKey {
case page
case pages
case perPage = "perpage"
case total
case photos = "photo"
}
}
|
//
// ViewController.swift
// IpLocationFinder
//
// Created by Алексей Чигарских on 01.06.2020.
// Copyright © 2020 Алексей Чигарских. All rights reserved.
import UIKit
import Alamofire
class MainViewController: UIViewController {
@IBOutlet weak var ipTFOut: UITextField!
@IBOutlet weak var regionOut: UILabel!
@IBOutlet weak var countryOut: UILabel!
@IBOutlet weak var cityOut: UILabel!
@IBOutlet weak var infoLabelMain: UILabel!
@IBOutlet weak var showMapButtonOut: UIButton!
@IBOutlet weak var searchButtonOut: UIButton!
@IBOutlet weak var countryLbl: UILabel!
@IBOutlet weak var regionLbl: UILabel!
@IBOutlet weak var cityLbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
showOrHideUiElements(state: .hide, elementsArray: arrayOfOutlets)
}
override func viewDidLayoutSubviews() {
allAnchorsTurnOn()
}
@IBAction func showMapAct(_ sender: Any) {
}
//MARK: - Logic
fileprivate func requestWithLogic() {
// подгружаем данне, вкидиваем картинки
if ipTFOut.text != "" {
let textFieldWithfixComma = ipTFOut.text!.replacingOccurrences(of: ",", with: ".") // заменяем запятую на точку
// проверяем допустимые символы в айпи адресе
let characterset = CharacterSet(charactersIn: " 0123456789.")
if textFieldWithfixComma.rangeOfCharacter(from: characterset.inverted) != nil {
self.showOrHideUiElements(state: .hide, elementsArray: arrayOfOutlets)
self.infoLabelMain.text = "🙅🏾♂️You entered invalid characters 🙅♀️"
return
}
// Сетевой запрос
IpLocationNetworkService.getIpInfo(ip: textFieldWithfixComma) { (json) in
let response = GetResponse(json: json)
searchResults = SearchResults(dict: response.finalJsonFile)
if searchResults != nil {
self.countryOut.text = searchResults?.country
// это ветвление сделано для того чтобы подставить вместо "" "-"
if searchResults?.region != "" {
self.regionOut.text = searchResults?.region
} else { self.regionOut.text = "-"}
if searchResults?.city != "" {
self.cityOut.text = searchResults?.city
} else { self.cityOut.text = "-"}
self.infoLabelMain.text = "🥳 Success! 🥳 "
self.showOrHideUiElements(state: .show, elementsArray: self.arrayOfOutlets)
} else {
self.infoLabelMain.text = """
Sorry, we did not find
😐information about this address.😐
"""
self.infoLabelMain.textAlignment = .center
self.showOrHideUiElements(state: .hide, elementsArray: self.arrayOfOutlets)
}}
ipTFOut.resignFirstResponder()
} else {
self.showAlert(title: "Write IP adress!", message: "") {
self.infoLabelMain.text = "👇Write Ip adress here👇"
self.showOrHideUiElements(state: .hide, elementsArray: self.arrayOfOutlets)
}
}
}
@IBAction func searchBtnAct(_ sender: Any) {
requestWithLogic()
}
// MARK: - UIFunctions
// Outlets to hide
lazy var arrayOfOutlets: [AnyObject] = [countryOut, countryLbl, cityOut, cityLbl, regionOut, regionLbl, showMapButtonOut]
// Show or Hide UIElements
func showOrHideUiElements(state: showOrHide, elementsArray: [AnyObject] ) {
switch state {
case .hide :
let _ = arrayOfOutlets.map { (uiElement) in
(uiElement as! UIView).isHidden = true
}
case .show :
let _ = arrayOfOutlets.map { (uiElement) in
(uiElement as! UIView).isHidden = false
}
}
}
// Margins
lazy var mView = view.layoutMarginsGuide
}
|
//
// ContentView.swift
// DataChangeComponent
//
// Created by Vegesna, Vijay V EX1 on 7/28/20.
// Copyright © 2020 Vegesna, Vijay V. All rights reserved.
//
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
ScrollView(.vertical) {
VStack {
DropDownCell()
DropDownCell()
}
}
.navigationBarTitle("DataChanges history")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
//
// ProfilePresenterDelegate.swift
// FundooApp
//
// Created by admin on 04/06/20.
// Copyright © 2020 admin. All rights reserved.
//
import Foundation
protocol ProfilePresenterDelegate {
func updateLabel(name: String,email:String)
}
|
import Kitura
import HeliumLogger
import Foundation
// Initialize HeliumLogger
HeliumLogger.use()
// Create a new router
let router = Router()
// Handle HTTP GET requests to /
router.get("/") {
request, response, next in
response.send("Hello, Swift Developers!\n")
next()
}
let port: String = ProcessInfo.processInfo.environment["PORT"] ?? "8080"
print("kitura port is : \(port)")
// Add an HTTP server and connect it to the router
Kitura.addHTTPServer(onPort: Int(port)!, with: router)
// Start the Kitura runloop (this call never returns)
Kitura.run()
|
//
// ___FILENAME___
//
import Foundation
import ObjectMapper
public struct ___FILEBASENAMEASIDENTIFIER___ {
}
extension ___FILEBASENAMEASIDENTIFIER___: Mappable {
public init?(map: Map) {
}
public mutating func mapping(map: Map) {
}
}
|
//
// LogOutViewController.swift
// Reimagine
//
// Created by Vishwam Pandya on 10/28/20.
//
import UIKit
import Amplify
import AmplifyPlugins
class LogOutViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Amplify.Auth.signOut() { result in
switch result {
case .success:
self.goToLoginPage()
case .failure(let error):
print("LogOut Error\(error)")
}
}
// Do any additional setup after loading the view.
}
func goToLoginPage() {
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
DispatchQueue.main.async {
let vc = storyBoard.instantiateViewController(identifier: "ViewController") as? ViewController
self.view.window?.rootViewController = vc
self.view.window?.makeKeyAndVisible()
}
}
/*
// 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.
}
*/
}
|
//
// RSSActionSheet.swift
// Feedit
//
// Created by Tyler D Lawrence on 2/23/21.
//
//import SwiftUI
//
//struct RSSActionSheet: View {
//
// @State var unread = false
// @State var starred = false
// @State var show3 = false
// @State var show4 = false
// @State var count = 0
//
// enum FeedSettings: CaseIterable {
// case webView
// }
// @State private var isSelected: Bool = false
// @State var notificationsEnabled: Bool = false
//// @Binding var fetchContentTime: String
//
// var body : some View{
//
// VStack(spacing: 15){
//
//// Picker(selection: $fetchContentTime, label:
//// Text("Fetch content time")) {
//// ForEach(ContentTimeType.allCases, id: \.self.rawValue) { type in
//// Text(type.rawValue)
//// }
//// }
//
// Toggle(isOn: self.$unread) {
// Text("Unread Only")
// }.toggleStyle(CheckboxStyle())
//
// Toggle(isOn: self.$starred) {
// Text("Starred Only")
// }.toggleStyle(StarStyle())
//
// Divider()
//
// Toggle(isOn: self.$notificationsEnabled) {
// Text("Notifications")
// }.toggleStyle(SwitchToggleStyle(tint: .blue))
//
// ForEach([FeedSettings.webView], id: \.self) { _ in
// Toggle("Safari Reader", isOn: self.$isSelected)
// }.toggleStyle(SwitchToggleStyle(tint: .blue))
//
// Divider()
//
// Stepper(onIncrement: {
// self.count += 1
// }, onDecrement: {
// if self.count != 0{
// self.count -= 1
// }
// }) {
// Text("Line Limit \(self.count)")
// }
// }
// .padding(.bottom, (UIApplication.shared.windows.last?.safeAreaInsets.bottom)! + 10)
// .padding(.horizontal)
// .padding(.top,20)
//// .background(Color(UIColor.systemBackground))
// .background(Color("secondary"))
//// .cornerRadius(25)
//
// }
//}
//
//struct RSSActionSheet_Previews: PreviewProvider {
// static var previews: some View {
// RSSActionSheet()
// }
//}
|
import Foundation
public struct StylesEndpoint: BaseEndpoint {
public typealias Content = [Style]
private let fileId: String
public init(fileId: String) {
self.fileId = fileId
}
func content(from root: StylesResponse) -> Content {
return root.meta.styles
}
public func makeRequest(baseURL: URL) -> URLRequest {
let url = baseURL
.appendingPathComponent("files")
.appendingPathComponent(fileId)
.appendingPathComponent("styles")
return URLRequest(url: url)
}
}
|
//
// ViewUtilities.swift
// braincode-ios
//
// Created by Kacper Harasim on 18.03.2016.
// Copyright © 2016 Kacper Harasim. All rights reserved.
//
import Foundation
import UIKit
extension CGRect {
func translateBy(x: CGFloat, _ y: CGFloat) -> CGRect {
return CGRect(x: self.origin.x + x, y: self.origin.y + y, width: self.width, height: self.height)
}
} |
//
// TriviaTests.swift
// Introduction-to-Unit-Testing-LabTests
//
// Created by Maitree Bain on 12/4/19.
// Copyright © 2019 Maitree Bain. All rights reserved.
//
import XCTest
@testable import Introduction_to_Unit_Testing_Lab
class TriviaTests: XCTestCase {
let filename = "Trivia"
let ext = "json"
func dataStorage() {
let data = Bundle.readRawJsonData(filename: filename, ext: ext)
}
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testTriviaData() {
let data = dataStorage
XCTAssertNotNil(data)
}
func testTriviaQuestions() {
let firstQuestion = TriviaDataLoad.getTrivia().first?.question
let expectedQuestion = "Who%20wrote%20and%20directed%20the%201986%20film%20%27Platoon%27%3F"
XCTAssertEqual(firstQuestion, expectedQuestion, "\(firstQuestion ?? "") should be \(expectedQuestion)")
}
}
|
import Foundation
/// Witness for the `NonEmptyArray<A>` data type. To be used in simulated Higher Kinded Types.
public final class ForNonEmptyArray {}
/// Partial application of the NonEmptyArray type constructor, omitting the last type parameter.
public typealias NonEmptyArrayPartial = ForNonEmptyArray
/// Higher Kinded Type alias to improve readability over `Kind<ForNonEmptyArray, A>`.
public typealias NonEmptyArrayOf<A> = Kind<ForNonEmptyArray, A>
/// Abbreviation for `NonEmptyArray`.
public typealias NEA<A> = NonEmptyArray<A>
/// Abbrebiation for `NonEmptyArrayPartial`.
public typealias NEAPartial = NonEmptyArrayPartial
/// A NonEmptyArray is an array of elements that guarantees to have at least one element.
public final class NonEmptyArray<A>: NonEmptyArrayOf<A> {
/// First element of the array.
public let head: A
/// Elements of the array, excluding the firs one.
public let tail: [A]
/// Concatenates two non-empty arrays.
///
/// - Parameters:
/// - lhs: Left hand side of the concatenation.
/// - rhs: Right hand side of the concatenation.
/// - Returns: A non-empty array that contains the elements of the two arguments in the same order.
public static func +(lhs: NonEmptyArray<A>, rhs: NonEmptyArray<A>) -> NonEmptyArray<A> {
NEA(head: lhs.head, tail: lhs.tail + [rhs.head] + rhs.tail)
}
/// Concatenates a non-empty array with a Swift array.
///
/// - Parameters:
/// - lhs: A non-empty array.
/// - rhs: A Swift array.
/// - Returns: A non-empty array that contains the elements of the two arguments in the same order.
public static func +(lhs: NonEmptyArray<A>, rhs: [A]) -> NonEmptyArray<A> {
NEA(head: lhs.head, tail: lhs.tail + rhs)
}
/// Appends an element to a non-empty array.
///
/// - Parameters:
/// - lhs: A non-empty array.
/// - rhs: An element.
/// - Returns: A non-empty array that has the new element at the end.
public static func +(lhs: NonEmptyArray<A>, rhs: A) -> NonEmptyArray<A> {
NEA(head: lhs.head, tail: lhs.tail + [rhs])
}
/// Creates a non-empty array from several values.
///
/// - Parameters:
/// - head: First element for the non-empty array.
/// - tail: Variable number of values for the rest of the non-empty array.
/// - Returns: A non-empty array that contains all elements in the specified order.
public static func of(_ head: A, _ tail: A...) -> NonEmptyArray<A> {
NEA(head: head, tail: tail)
}
/// Creates a non-empty array from a Swift array.
///
/// - Parameter array: A Swift array.
/// - Returns: An optional non-empty array with the contents of the argument, or `Option.none` if it was empty.
public static func fromArray(_ array: [A]) -> Option<NonEmptyArray<A>> {
array.isEmpty ? Option.none() : Option.some(NEA(all: array))
}
/// Unsafely creates a non-empty array from a Swift array.
///
/// This function may cause a fatal error if the argument is an empty error.
///
/// - Parameter array: A Swift array.
/// - Returns: A non-empty array with the contents of the argument.
public static func fromArrayUnsafe(_ array: [A]) -> NonEmptyArray<A> {
NEA(all: array)
}
/// Safe downcast.
///
/// - Parameter fa: Value in higher-kind form.
/// - Returns: Value cast to NonEmptyArray.
public static func fix(_ fa: NonEmptyArrayOf<A>) -> NonEmptyArray<A> {
fa as! NEA<A>
}
/// Initializes a non-empty array.
///
/// - Parameters:
/// - head: First element for the array.
/// - tail: An array with the rest of elements.
public init(head: A, tail: [A]) {
self.head = head
self.tail = tail
}
private init(all: [A]) {
self.head = all[0]
self.tail = [A](all.dropFirst(1))
}
/// Obtains a Swift array with the elements in this value.
///
/// - Returns: A Swift array with the elements in this value.
public func all() -> [A] {
[head] + tail
}
/// Obtains an element from its position in this non-empty array.
///
/// - Parameter i: Index of the object to obtain.
/// - Returns: An optional value with the object at the indicated position, if any.
public func getOrNone(_ i: Int) -> Option<A> {
let a = all()
if i >= 0 && i < a.count {
return .some(a[i])
} else {
return .none()
}
}
/// Obtains an element from its position in this non-empty array.
///
/// - Parameter index: Index of the object to obtain.
public subscript(index: Int) -> Option<A> {
getOrNone(index)
}
}
/// Safe downcast.
///
/// - Parameter fa: Value in higher-kind form.
/// - Returns: Value cast to NonEmptyArray.
public postfix func ^<A>(_ fa: NonEmptyArrayOf<A>) -> NonEmptyArray<A> {
NonEmptyArray.fix(fa)
}
public extension NonEmptyArray where A: Equatable {
/// Checks if an element appears in this array.
///
/// - Parameter element: Element to look for in the array.
/// - Returns: Boolean value indicating if the element appears in the array or not.
func contains(element: A) -> Bool {
head == element || tail.contains(where: { $0 == element })
}
/// Checks if all the elements of an array appear in this array.
///
/// - Parameter elements: Elements to look for in the array.
/// - Returns: Boolean value indicating if all elements appear in the array or not.
func containsAll(elements: [A]) -> Bool {
elements.map(contains).reduce(true, and)
}
}
// MARK: Conformance of NonEmptyArray to CustomStringConvertible
extension NonEmptyArray: CustomStringConvertible {
public var description: String {
"NonEmptyArray(\(self.all()))"
}
}
// MARK: Conformance of NonEmptyArray to CustomDebugStringConvertible
extension NonEmptyArray: CustomDebugStringConvertible where A: CustomDebugStringConvertible {
public var debugDescription: String {
let contentsString = self.all().map { x in x.debugDescription }.joined(separator: ", ")
return "NonEmptyArray(\(contentsString))"
}
}
// MARK: Instance of EquatableK for NonEmptyArray
extension NonEmptyArrayPartial: EquatableK {
public static func eq<A: Equatable>(
_ lhs: NonEmptyArrayOf<A>,
_ rhs: NonEmptyArrayOf<A>) -> Bool {
lhs^.all() == rhs^.all()
}
}
// MARK: Instance of HashableK for NonEmptyArray
extension NonEmptyArrayPartial: HashableK {
public static func hash<A>(_ fa: NonEmptyArrayOf<A>, into hasher: inout Hasher) where A : Hashable {
hasher.combine(fa^.head)
hasher.combine(fa^.tail)
}
}
// MARK: Instance of Functor for NonEmptyArray
extension NonEmptyArrayPartial: Functor {
public static func map<A, B>(
_ fa: NonEmptyArrayOf<A>,
_ f: @escaping (A) -> B) -> NonEmptyArrayOf<B> {
NEA.fromArrayUnsafe(fa^.all().map(f))
}
}
// MARK: Instance of Applicative for NonEmptyArray
extension NonEmptyArrayPartial: Applicative {
public static func pure<A>(_ a: A) -> NonEmptyArrayOf<A> {
NEA(head: a, tail: [])
}
}
// MARK: Instance of Selective for NonEmptyArray
extension NonEmptyArrayPartial: Selective {}
// MARK: Instance of Monad for NonEmptyArray
extension NonEmptyArrayPartial: Monad {
public static func flatMap<A, B>(
_ fa: NonEmptyArrayOf<A>,
_ f: @escaping (A) -> NonEmptyArrayOf<B>) -> NonEmptyArrayOf<B> {
f(fa^.head)^ + fa^.tail.flatMap{ a in f(a)^.all() }
}
private static func go<A, B>(
_ buf: [B],
_ f: @escaping (A) -> NonEmptyArrayOf<Either<A, B>>,
_ v: NonEmptyArray<Either<A, B>>) -> Trampoline<[B]> {
.defer {
let head = v.head
return head.fold({ a in go(buf, f, NonEmptyArray.fix(f(a)) + v.tail) },
{ b in
let newBuf = buf + [b]
let x = NEA<Either<A, B>>.fromArray(v.tail)
return x.fold({ .done(newBuf) },
{ value in go(newBuf, f, value) })
})
}
}
public static func tailRecM<A, B>(
_ a: A,
_ f: @escaping (A) -> NonEmptyArrayOf<Either<A, B>>) -> NonEmptyArrayOf<B> {
NEA.fromArrayUnsafe(go([], f, f(a)^).run())
}
}
// MARK: Instance of Comonad for NonEmptyArray
extension NonEmptyArrayPartial: Comonad {
public static func coflatMap<A, B>(_ fa: NonEmptyArrayOf<A>, _ f: @escaping (NonEmptyArrayOf<A>) -> B) -> NonEmptyArrayOf<B> {
func consume(_ array: [A], _ buf: [B] = []) -> [B] {
if array.isEmpty {
return buf
} else {
let tail = [A](array.dropFirst())
let newBuf = buf + [f(NonEmptyArray(head: array[0], tail: tail))]
return consume(tail, newBuf)
}
}
return NEA(head: f(fa^), tail: consume(fa^.tail))
}
public static func extract<A>(_ fa: NonEmptyArrayOf<A>) -> A {
fa^.head
}
}
// MARK: Instance of Bimonad for NonEmptyArray
extension NonEmptyArrayPartial: Bimonad {}
// MARK: Instance of Foldable for NonEmptyArray
extension NonEmptyArrayPartial: Foldable {
public static func foldLeft<A, B>(
_ fa: NonEmptyArrayOf<A>,
_ b: B,
_ f: @escaping (B, A) -> B) -> B {
fa^.tail.reduce(f(b, fa^.head), f)
}
public static func foldRight<A, B>(
_ fa: NonEmptyArrayOf<A>,
_ b: Eval<B>,
_ f: @escaping (A, Eval<B>) -> Eval<B>) -> Eval<B> {
fa^.all().k().foldRight(b, f)
}
}
// MARK: Instance of Traverse for NonEmptyArray
extension NonEmptyArrayPartial: Traverse {
public static func traverse<G: Applicative, A, B>(
_ fa: NonEmptyArrayOf<A>,
_ f: @escaping (A) -> Kind<G, B>) -> Kind<G, NonEmptyArrayOf<B>> {
let arrayTraverse = fa^.all().k().traverse(f)
return G.map(arrayTraverse, { x in NEA.fromArrayUnsafe(x^.asArray) })
}
}
public extension NEA {
func traverse<G: Applicative, B>(_ f: @escaping (A) -> Kind<G, B>) -> Kind<G, NEA<B>> {
ForNonEmptyArray.traverse(self, f).map { $0^ }
}
}
// MARK: Instance of SemigroupK for NonEmptyArray
extension NonEmptyArrayPartial: SemigroupK {
public static func combineK<A>(
_ x: NonEmptyArrayOf<A>,
_ y: NonEmptyArrayOf<A>) -> NonEmptyArrayOf<A> {
x^ + y^
}
}
// MARK: Instance of Semigroup for NonEmptyArray
extension NonEmptyArray: Semigroup {
public func combine(_ other: NonEmptyArray<A>) -> NonEmptyArray<A> {
self + other
}
}
|
//Variables - are used to store information to be referenced and manipulated in a computer program.
import UIKit
var message = "Hello, playground"; //"=" assignment operator which assigns the right side value to the left side
//Unary, Binary, Ternary operators
//The above line of code is binary because it works on two targets
//Urany operator (one target)
var isEmpty = true;
isEmpty = !isEmpty;
//Ternary operator (Three targets)
//Example 1
var feelGoodAboutmYSELF = true;
feelGoodAboutmYSELF = isEmpty ? true : false
//Example 2
var bankAccountBalance = 100;
var cashResgisterMessage = bankAccountBalance >= 50 ? "Processing payment" : "Not enough balance"; |
//
// CompanyListController.swift
// Favorites Food
//
// Created by Pavel Kurilov on 30.10.2018.
// Copyright © 2018 Pavel Kurilov. All rights reserved.
//
import UIKit
import SnapKit
class CompanyListController: UIViewController {
// MARK: - Init/ Deintit
private var viewModel: TableListViewModelProtocool?
private let companyCellReuseIdentifier = "companyCellId"
private let tableView = UITableView()
// MARK: - Init FoodListViewController
init(viewModel: CompanyListViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
self.view.backgroundColor = .lightGrayishPink
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
configureTableView()
}
override func viewWillAppear(_ animated: Bool) {
self.tableView.reloadData()
}
// MARK: - Configure contact list
private func configureTableView() {
self.view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.top.equalTo(self.view.snp.top).offset(Constant.offsetValue)
make.left.right.bottom.equalTo(self.view)
}
tableView.backgroundColor = .lightGrayishPink
tableView.register(CompanyCell.self,
forCellReuseIdentifier: companyCellReuseIdentifier)
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
}
}
// MARK: UITableView dataSource
extension CompanyListController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return viewModel?.numberOfSections() ?? 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel?.numberOfRows(numberOfRowsInSection: section) ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: companyCellReuseIdentifier,
for: indexPath)
as? CompanyCell else { return UITableViewCell(style: .default,
reuseIdentifier: companyCellReuseIdentifier) }
guard let cellViewModel = viewModel?.cellViewModel(forIndexPath: indexPath) else { return cell }
cell.configure(with: cellViewModel)
cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let viewModel = viewModel else {
return
}
viewModel.selectRow(atIndexPath: indexPath)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return Constant.cellHeight
}
}
|
//
// CustomsForm.swift
// aoc2020
//
// Created by Shawn Veader on 12/6/20.
//
import Foundation
struct CustomsForm {
let groupSize: Int
let reponses: [String]
let answers: [String: Int]
/// Count of questions that anyone in the group answered "yes" to
var yesQuestions: Int {
answers.keys.count
}
/// Count of questions that all members of the group answered "yes" to
var groupYesQuestions: Int {
answers.filter({ $1 == groupSize }).keys.count
}
init(_ input: String) {
let people = input.split(separator: "\n").map(String.init)
groupSize = people.count
reponses = people
var tmpAnswers = [String: Int]()
for person in people {
Array(person).map(String.init).forEach { q in
tmpAnswers[q] = (tmpAnswers[q] ?? 0) + 1
}
}
answers = tmpAnswers
}
}
|
//
// File.swift
//
//
// Created by leerie simpson on 10/13/20.
//
import Foundation
import GameplayKit
/// Used to represent objects that announce and observe game events.
public typealias Broadcaster = BroadcastAnnouncer & BroadcastObserver
/// Used by components on declaration so that we can provide a reaction to events when creating the GameEventListenerComponent.
public typealias EventReaction = (GKEntity, GKComponent, Broadcast, BroadcastAnnouncer, Any?) -> ()
public typealias Broadcasts = Set<Broadcast>
|
//
// ViewController.swift
// FirstApp
//
// Created by Valentina Vențel on 05/04/2019.
// Copyright © 2019 Valentina Vențel. All rights reserved.
//
import UIKit
import Foundation
class LoginViewController: UIViewController, UserModelProtocol {
@IBOutlet weak var pukText: UITextField!
@IBOutlet weak var userText: UITextField!
@IBOutlet weak var loginButton: UIButton!
var feedItems: NSArray = NSArray()
var selectedUser: User = User()
override func viewDidLoad() {
super.viewDidLoad()
// let homeModel = HomeModel()
// homeModel.delegate = self
// homeModel.downloadItems()
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillShow),
name: UIResponder.keyboardWillShowNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillHide),
name: UIResponder.keyboardWillHideNotification,
object: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
@IBAction func loginTap(_ sender: UIButton) {
guard let user = userText.text,
let puk = pukText.text else {
return
}
// MARK: Test
// if user.lowercased() == "test" {
// self.performSegue(withIdentifier: "mainSegue", sender: nil)
// }
HTTPClient.login(user: user,
puk: puk) { (result, err) in
if err == nil {
for dict in result as! [[String: Any]] {
let nume = dict["UserID"] as! String
if nume == user {
DispatchQueue.main.async {
self.performSegue(withIdentifier: "mainSegue", sender: nil)
}
}
}
} else {
// ...
}
}
}
@objc func keyboardWillShow(notification: NSNotification) {
guard let userInfo = notification.userInfo,
let keyboardSize = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
return
}
let keyboardFrame = keyboardSize.cgRectValue
if view.frame.origin.y <= 100 {
view.frame.origin.y -= keyboardFrame.height
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if view.frame.origin.y != 0 {
view.frame.origin.y = 0
}
}
//TODO: remove this shit
func itemsDownloaded(items: NSArray) {
feedItems = items
}
func returnUser(feedItems: NSArray) -> User {
var index = 0
let user = User()
while index < feedItems.count {
let user: User = feedItems[index] as! User
if (user.userID == userText.text) && (user.puk == pukText.text) {
return user
}
index += 1
}
return user
}
}
|
//
// EditorViewController.swift
// JYVideoEditor
//
// Created by aha on 2021/2/19.
//
import UIKit
import AVKit
class EditorViewController: UIViewController {
var sourcePath: String!
@IBOutlet private weak var playerView: UIView!
@IBOutlet weak var trackPreviewView: TrackPreviewView!
private var player: AVPlayer!
private var editorManager: EditorManager!
private var playerTimerToken: Any?
static func instance(sourcePath: String) -> EditorViewController {
let editorVC = EditorViewController.loadInstanceFromSB() as! EditorViewController
editorVC.sourcePath = sourcePath
return editorVC
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
}
extension EditorViewController {
private func setupUI() {
let asset = AVAsset(url: URL(fileURLWithPath: sourcePath))
editorManager = EditorManager(asset: asset, delegate: self)
trackPreviewView.manager = editorManager
trackPreviewView.delegate = self
let playerVC = AVPlayerViewController()
playerVC.player = AVPlayer(playerItem: .init(asset: editorManager.getComposition()!))
self.player = playerVC.player
addChild(playerVC)
playerView.addSubview(playerVC.view)
playerVC.view.translatesAutoresizingMaskIntoConstraints = false
playerVC.view.leadingAnchor.constraint(equalTo: playerView.leadingAnchor).isActive = true
playerVC.view.trailingAnchor.constraint(equalTo: playerView.trailingAnchor).isActive = true
playerVC.view.topAnchor.constraint(equalTo: playerView.topAnchor).isActive = true
playerVC.view.bottomAnchor.constraint(equalTo: playerView.bottomAnchor).isActive = true
}
}
extension EditorViewController {
private func updatePlayer() {
if let composition = editorManager.getComposition() {
let item = AVPlayerItem(asset: composition)
player.replaceCurrentItem(with: item)
if let token = self.playerTimerToken {
player.removeTimeObserver(token)
}
if let timeRange = editorManager.getTimeRange() {
self.playerTimerToken = player.addPeriodicTimeObserver(forInterval: .init(seconds: 0.01, preferredTimescale: timeRange.duration.timescale), queue: .main) {[weak self] (time) in
self?.trackPreviewView.progress = time.seconds / timeRange.duration.seconds
}
}
}
}
}
extension EditorViewController: TrackPreviewViewDelegate {
func trackPreviewDidScroll(progress: Double) {
//正在播放
if self.player.rate != 0 && player.error == nil {
player.pause()
}
if let timeRange = editorManager.getTimeRange() {
let playTime = timeRange.duration
let p = min(1.0, max(0, progress))
let time = CMTime(seconds: playTime.seconds * p, preferredTimescale: playTime.timescale)
player.seek(to: time, toleranceBefore: .zero, toleranceAfter: .zero)
}
}
}
extension EditorViewController: EditorManagerDelegate {
func managerDidInsertNewTrack(_ track: Track) {
let currentTime = self.player.currentTime()
if let totalSeconds = editorManager.getTimeRange()?.duration.seconds {
let progress = currentTime.seconds / totalSeconds
trackPreviewView.insertTrack(track: track, progress: progress)
}else {
trackPreviewView.insertTrack(track: track, progress: 0)
}
updatePlayer()
}
func managerDidClipEnd() {
// trackPreviewView.clip()
// updatePlayer()
}
}
extension EditorViewController {
@IBAction private func clickPlay() {
if self.player.status == .readyToPlay {
debugPrint("ready for play")
player.play()
}
}
@IBAction private func clickClip() {
let currentTime = self.player.currentTime()
if let totalSeconds = editorManager.getTimeRange()?.duration.seconds {
let progress = currentTime.seconds / totalSeconds
trackPreviewView.split(at: progress)
}
}
@IBAction private func clickInsertV1() {
let path = Bundle.main.path(forResource: "insert.MOV", ofType: nil)!
let asset = AVAsset(url: URL(fileURLWithPath: path))
let currentTime = player.currentTime()
do {
try editorManager.insertTrack(asset, type: .video, at: currentTime)
print("插入新的视频")
}catch {
print("插入新的视频出错: \(error)")
}
}
@IBAction private func clickInsertV2WithPic() {
let image = UIImage(named: "image_0")!
[image].convertToVideos { (url) in
let asset = AVAsset(url: url)
let currentTime = self.player.currentTime()
do {
try self.editorManager.insertTrack(asset, type: .video, at: currentTime)
print("插入新的视频图片合成视频")
}catch {
print("插入新的视频图片合成视频出错: \(error)")
}
}
}
@IBAction private func clickInsertOriginAudio() {
do {
try editorManager.insertTrack(editorManager.originAsset, type: .audio, at: .zero)
print("插入原声音频")
}catch {
print("插入原声音频出错: \(error)")
}
}
@IBAction private func clickRemoveV1() {
}
@IBAction private func clickRemoveV2() {
}
@IBAction private func clickRemoveOriginAudio() {
}
}
|
//
// LoginController.swift
// firebaseDemo
//
// Created by mhy on 17/5/15.
// Copyright © 2017年 mhy. All rights reserved.
//
import UIKit
import Firebase
class LoginController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(red:34/255, green: 163/255,blue: 64/255, alpha: 1)
view.addSubview(inputContainerView)
view.addSubview(loginRegisterButton)
view.addSubview(profileImageView)
view.addSubview(loginRegisterSegmentedControl)
setInputContainerView()
setLoginButton()
setProfileImageView()
setSegmentedControl()
}
let loginRegisterSegmentedControl: UISegmentedControl = {
let sc = UISegmentedControl(items: ["Login", "Register"])
sc.translatesAutoresizingMaskIntoConstraints = false
sc.tintColor = UIColor.white
sc.selectedSegmentIndex = 1
sc.addTarget(self, action: #selector(handleLoginRegisterChange), for: .valueChanged)
return sc
}()
func handleLoginRegisterChange(){
let title = loginRegisterSegmentedControl.titleForSegment(at: loginRegisterSegmentedControl.selectedSegmentIndex)
loginRegisterButton.setTitle(title, for: .normal )
inputContainerHeightConstraint?.constant = loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 100 : 150
nameTextField.isHidden = loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? true : false
nameTextFieldHeightConstraint?.isActive = false
nameTextFieldHeightConstraint = nameTextField.heightAnchor.constraint(equalTo: inputContainerView.heightAnchor, multiplier: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 0 : 1/3)
nameTextFieldHeightConstraint?.isActive = true
emailTextFieldHeightConstraint?.isActive = false
emailTextFieldHeightConstraint = emailTextField.heightAnchor.constraint(equalTo: inputContainerView.heightAnchor, multiplier: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 1/2 : 1/3)
emailTextFieldHeightConstraint?.isActive = true
PWTextFieldHeightConstraint?.isActive = false
PWTextFieldHeightConstraint = PWTextField.heightAnchor.constraint(equalTo: inputContainerView.heightAnchor, multiplier: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 1/2 : 1/3)
PWTextFieldHeightConstraint?.isActive = true
}
let inputContainerView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.white
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 5
view.layer.masksToBounds = true
return view
}()
let loginRegisterButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = UIColor(red:80/255, green: 101/255,blue: 161/255, alpha: 1)
button.setTitle("Register", for: .normal)
button.setTitleColor(.white ,for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
button.layer.cornerRadius = 5
button.layer.masksToBounds = true
button.addTarget(self, action: #selector(handleRegisterLogin), for: .touchUpInside)
return button
}()
func handleRegisterLogin(){
if loginRegisterSegmentedControl.selectedSegmentIndex == 0{
handleLogin()
}else{
handleRegister()
}
}
func handleLogin(){
guard let email = emailTextField.text, let password = PWTextField.text
else{
print("Form is not vaild")
return
}
FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: {(user,error) in
if error != nil {
print(error!)
return
}
print("login success")
self.dismiss(animated: true, completion: nil)
})
}
func handleRegister(){
guard let email = emailTextField.text, let password = PWTextField.text, let name = nameTextField.text
else {
print("Form is not vaild")
return
}
let profileImage = ""
FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: {(user: FIRUser?, error) in
if error != nil {
print(error!)
return
}
guard let uid = user?.uid else{
return
}
//let storageRef = FIRStorage.storage().reference()
let ref = FIRDatabase.database().reference(fromURL: "https://fir-demo-480e3.firebaseio.com/")
let userRef = ref.child("User").child(uid)
let values = ["name" : name, "email": email, "profileImageUrl": profileImage]
userRef.updateChildValues(values, withCompletionBlock: {(err, ref) in
if err != nil {
print(err!)
return
}
self.dismiss(animated: true, completion: nil)
//print("Saved user successfully into Firebase DB")
})
})
}
let nameTextField : UITextField = {
let tf = UITextField()
tf.placeholder = "Name"
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
let nameSeperaterView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(red:220/255, green: 220/255,blue: 220/255, alpha: 1)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let emailTextField : UITextField = {
let tf = UITextField()
tf.placeholder = "Email"
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
let emailSeperaterView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(red:220/255, green: 220/255,blue: 220/255, alpha: 1)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let PWTextField : UITextField = {
let tf = UITextField()
tf.placeholder = "Password"
tf.translatesAutoresizingMaskIntoConstraints = false
tf.isSecureTextEntry = true
return tf
}()
let profileImageView: UIView = {
let view = UIImageView()
view.image = UIImage(named: "Icon-60")
view.translatesAutoresizingMaskIntoConstraints = false
view.contentMode = .scaleAspectFill
return view
}()
func setProfileImageView(){
profileImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
profileImageView.bottomAnchor.constraint(equalTo: inputContainerView.topAnchor, constant: -50).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 150).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 120).isActive = true
}
func setSegmentedControl(){
loginRegisterSegmentedControl.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
loginRegisterSegmentedControl.bottomAnchor.constraint(equalTo: inputContainerView.topAnchor, constant: -12).isActive = true
loginRegisterSegmentedControl.widthAnchor.constraint(equalTo: inputContainerView.widthAnchor).isActive = true
loginRegisterSegmentedControl.heightAnchor.constraint(equalToConstant: 36).isActive = true
}
var inputContainerHeightConstraint: NSLayoutConstraint?
var nameTextFieldHeightConstraint: NSLayoutConstraint?
var emailTextFieldHeightConstraint: NSLayoutConstraint?
var PWTextFieldHeightConstraint: NSLayoutConstraint?
func setInputContainerView(){
inputContainerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
inputContainerView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
inputContainerHeightConstraint = inputContainerView.heightAnchor.constraint(equalToConstant: 150)
inputContainerHeightConstraint?.isActive = true
inputContainerView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -24).isActive = true
inputContainerView.addSubview(nameTextField)
inputContainerView.addSubview(nameSeperaterView)
inputContainerView.addSubview(emailTextField)
inputContainerView.addSubview(emailSeperaterView)
inputContainerView.addSubview(PWTextField)
nameTextField.leftAnchor.constraint(equalTo: inputContainerView.leftAnchor, constant: 12).isActive = true
nameTextField.topAnchor.constraint(equalTo: inputContainerView.topAnchor).isActive = true
nameTextField.widthAnchor.constraint(equalTo: inputContainerView.widthAnchor).isActive = true
nameTextFieldHeightConstraint = nameTextField.heightAnchor.constraint(equalTo: inputContainerView.heightAnchor, multiplier: 1/3)
nameTextFieldHeightConstraint?.isActive = true
nameSeperaterView.leftAnchor.constraint(equalTo: inputContainerView.leftAnchor).isActive = true
nameSeperaterView.topAnchor.constraint(equalTo: nameTextField.bottomAnchor).isActive = true
nameSeperaterView.widthAnchor.constraint(equalTo: inputContainerView.widthAnchor).isActive = true
nameSeperaterView.heightAnchor.constraint(equalToConstant: 1).isActive = true
emailTextField.leftAnchor.constraint(equalTo: inputContainerView.leftAnchor, constant: 12).isActive = true
emailTextField.topAnchor.constraint(equalTo: nameTextField.bottomAnchor).isActive = true
emailTextField.widthAnchor.constraint(equalTo: inputContainerView.widthAnchor).isActive = true
emailTextFieldHeightConstraint = emailTextField.heightAnchor.constraint(equalTo: inputContainerView.heightAnchor, multiplier: 1/3)
emailTextFieldHeightConstraint?.isActive = true
emailSeperaterView.leftAnchor.constraint(equalTo: inputContainerView.leftAnchor).isActive = true
emailSeperaterView.topAnchor.constraint(equalTo: emailTextField.bottomAnchor).isActive = true
emailSeperaterView.widthAnchor.constraint(equalTo: inputContainerView.widthAnchor).isActive = true
emailSeperaterView.heightAnchor.constraint(equalToConstant: 1).isActive = true
PWTextField.leftAnchor.constraint(equalTo: inputContainerView.leftAnchor, constant: 12).isActive = true
PWTextField.topAnchor.constraint(equalTo: emailTextField.bottomAnchor).isActive = true
PWTextField.widthAnchor.constraint(equalTo: inputContainerView.widthAnchor).isActive = true
PWTextFieldHeightConstraint = PWTextField.heightAnchor.constraint(equalTo: inputContainerView.heightAnchor, multiplier: 1/3)
PWTextFieldHeightConstraint?.isActive = true
}
func setLoginButton(){
loginRegisterButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
loginRegisterButton.topAnchor.constraint(equalTo: inputContainerView.bottomAnchor, constant: 12).isActive = true
loginRegisterButton.widthAnchor.constraint(equalTo: inputContainerView.widthAnchor).isActive = true
loginRegisterButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
override var preferredStatusBarStyle: UIStatusBarStyle{
return .lightContent
}
}
|
//
// DescriptionCardView.swift
// berkeley-mobile
//
// Created by Kevin Hu on 10/3/20.
// Copyright © 2020 ASUC OCTO. All rights reserved.
//
import UIKit
fileprivate let kCardPadding: UIEdgeInsets = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
fileprivate let kViewMargin: CGFloat = 16
/// A card with a label displaying the description for some resource.
class DescriptionCardView: CardView {
/// A label for the bolded title of the card ("Description").
private var cardTitle: UILabel!
/// The label displaying the description.
private var descriptionLabel: UILabel!
public init?(description: String?) {
guard let description = description?.trimmingCharacters(in: .whitespacesAndNewlines),
!description.isEmpty else { return nil }
super.init(frame: .zero)
// Default padding for the card
layoutMargins = kCardPadding
cardTitle = UILabel()
cardTitle.font = Font.bold(16)
cardTitle.text = "Description"
addSubview(cardTitle)
cardTitle.translatesAutoresizingMaskIntoConstraints = false
cardTitle.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor).isActive = true
cardTitle.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor).isActive = true
cardTitle.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor).isActive = true
descriptionLabel = UILabel()
descriptionLabel.font = Font.light(12)
descriptionLabel.numberOfLines = 0
descriptionLabel.text = description
addSubview(descriptionLabel)
descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
descriptionLabel.topAnchor.constraint(equalTo: cardTitle.bottomAnchor, constant: kViewMargin).isActive = true
descriptionLabel.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor).isActive = true
descriptionLabel.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor).isActive = true
descriptionLabel.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// SearchTextField.swift
// JISHO
//
// Created by Alex on 02/05/2020.
// Copyright © 2020 Alex McMillan. All rights reserved.
//
import Foundation
import UIKit
class SearchTextField: UITextField {
override init(frame: CGRect) {
super.init(frame: frame)
selfInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
selfInit()
}
fileprivate func selfInit() {
borderStyle = .none
layer.borderColor = UIColor.backgroundContrast2?.cgColor
layer.cornerRadius = 8
layer.borderWidth = 1
keyboardType = .alphabet
returnKeyType = .search
autocorrectionType = .no
autocapitalizationType = .none
spellCheckingType = .no
textAlignment = .center
clearButtonMode = .whileEditing
placeholder = "Search"
font = .regular(size: 14)
}
}
|
//
// GirlSentCell.swift
// NasiShadchanHelper
//
// Created by username on 12/17/20.
// Copyright © 2020 user. All rights reserved.
//
import UIKit
class GirlSentCell: UITableViewCell {
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var ageCityLabel: UILabel!
@IBOutlet weak var heightSeminaryLabel: UILabel!
@IBOutlet weak var categoryLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
profileImageView.layer.cornerRadius = 8
profileImageView.layer.masksToBounds = true
profileImageView.contentMode = .scaleAspectFit
}
func configureCellFor(currentGirl: NasiGirl) {
profileImageView.loadImageFromUrl(strUrl: currentGirl.imageDownloadURLString, imgPlaceHolder: "")
//profileImageView.image = currentGirl.imageDownloadURLString
let customFont = UIFont(name: "SBLHebrew", size: 18)
//nameLabel.font = customFont
nameLabel.textAlignment = .left
nameLabel.text = currentGirl.nameSheIsCalledOrKnownBy + " " + currentGirl.lastNameOfGirl
//ageCityLabel.font = customFont
ageCityLabel.text = "\(currentGirl.age)" + " - " + "\(currentGirl.cityOfResidence)"
//heightSeminaryLabel.font = customFont
heightSeminaryLabel.text = currentGirl.heightInFeet + " Ft" + " " + currentGirl.heightInInches + " Inch" + " - " + currentGirl.seminaryName
//categoryLabel.font = customFont
categoryLabel.text = currentGirl.category
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Initialization code
let selection = UIView(frame: CGRect.zero)
selection.backgroundColor = UIColor(white: 1.0, alpha: 0.3)
selectedBackgroundView = selection
// Rounded corners for images
//profileImageView.layer.cornerRadius = profileImageView.bounds.size.width / 2
//profileImageView.clipsToBounds = true
}
}
|
//
// ViewController.swift
// Common
//
// Created by CoderZcc on 03/02/2021.
// Copyright (c) 2021 CoderZcc. All rights reserved.
//
import UIKit
import Common
import CTMediator
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.lightGray
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let vc = CTMediator.sharedInstance().jumpToTest(["test": "aaaa"]) {
self.present(vc, animated: true, completion: nil)
} else {
print("初始化失败!!!")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// SocketIOManager.swift
// BeeHive
//
// Created by HyperDesign-Gehad on 8/30/18.
// Copyright © 2018 HyperDesign-Gehad. All rights reserved.
//
import UIKit
import SocketIO
class SocketIOManager: NSObject {
static let sharedInstance = SocketIOManager()
var connectParamsString : String!
var socket : SocketIOClient!
var manager : SocketManager!
override init() {
super.init()
}
func establishConnection(userId : String , userName : String, myList : String) {
manager = SocketManager(socketURL: URL(string: "http://inbeehive.com:5000")!, config: [.log(true), .compress,.connectParams(["user_id": userId,"username":userName,"status": "online","mylist":myList])])
// socket = SocketIOClient(manager: manager, nsp: "/swift")
socket = manager.defaultSocket
socket.onAny {print("Got event: \($0.event), with items: \($0.items!)")}
socket.on(clientEvent: .connect) {data, ack in
print("socket connected \(data)")
// let id:Int = UserDefaults.standard.getUserID()
// self.socket.emit(
// "client join", ["id":id]
// )
}
// socket.on("new_private_msg") { dataArray, ack in
// print("socket connected \(dataArray)")
// }
socket.connect()
}
func closeConnection() {
if socket != nil {
socket.disconnect()
}
}
func sendMessage(message: String,otherUserID : Int) {
socket.emit("send_private_msg", ["message": message,"to":"user_\(otherUserID)"])
}
func getChatMessage(completionHandler: @ escaping (Message) -> Void) {
socket.on("new_private_msg") { (dataArray, socketAck) -> Void in
print(dataArray)
if let messageJson = dataArray[1] as? Message{
completionHandler(messageJson)
}
}
}
}
|
// Created by Sergii Mykhailov on 22/11/2017.
// Copyright © 2017 Sergii Mykhailov. All rights reserved.
//
import Foundation
class BTCTradeUABalanceProvider : BTCTradeUAProviderBase {
typealias BalanceCompletionCallback = ([BalanceItem]) -> Void
// MARK: Public methods and properties
public func retriveBalanceAsync(withPublicKey publicKey:String,
privateKey:String,
onCompletion:@escaping BalanceCompletionCallback) {
super.performUserRequestAsync(withSuffix:BTCTradeUABalanceProvider.BalanceSuffix,
publicKey:publicKey,
privateKey:privateKey) { [weak self] (items, error) in
if self != nil {
let balanceItems = self!.balance(fromResponseItems:items)
onCompletion(balanceItems)
}
}
}
// MARK: Internal methods
fileprivate func balance(fromResponseItems items:[String : Any]) -> [BalanceItem] {
var result = [BalanceItem]()
let accounts = items[BTCTradeUABalanceProvider.AccountsKey]
if accounts != nil {
if let accountsDictionary = accounts as? [[String : Any]] {
retrieveBalanceValue(fromJSONItems:accountsDictionary,
forCurrency:.UAH,
andStoreInCollection:&result)
retrieveBalanceValue(fromJSONItems:accountsDictionary,
forCurrency:.BTC,
andStoreInCollection:&result)
retrieveBalanceValue(fromJSONItems:accountsDictionary,
forCurrency:.ETH,
andStoreInCollection:&result)
retrieveBalanceValue(fromJSONItems:accountsDictionary,
forCurrency:.LTC,
andStoreInCollection:&result)
retrieveBalanceValue(fromJSONItems:accountsDictionary,
forCurrency:.XMR,
andStoreInCollection:&result)
retrieveBalanceValue(fromJSONItems:accountsDictionary,
forCurrency:.DOGE,
andStoreInCollection:&result)
retrieveBalanceValue(fromJSONItems:accountsDictionary,
forCurrency:.DASH,
andStoreInCollection:&result)
retrieveBalanceValue(fromJSONItems:accountsDictionary,
forCurrency:.SIB,
andStoreInCollection:&result)
retrieveBalanceValue(fromJSONItems:accountsDictionary,
forCurrency:.KRB,
andStoreInCollection:&result)
retrieveBalanceValue(fromJSONItems:accountsDictionary,
forCurrency:.USDT,
andStoreInCollection:&result)
retrieveBalanceValue(fromJSONItems:accountsDictionary,
forCurrency:.ZEC,
andStoreInCollection:&result)
retrieveBalanceValue(fromJSONItems:accountsDictionary,
forCurrency:.BCH,
andStoreInCollection:&result)
retrieveBalanceValue(fromJSONItems:accountsDictionary,
forCurrency:.ETC,
andStoreInCollection:&result)
retrieveBalanceValue(fromJSONItems:accountsDictionary,
forCurrency:.NVC,
andStoreInCollection:&result)
}
}
return result;
}
fileprivate func retrieveBalanceValue(fromJSONItems items:[[String : Any]],
forCurrency currency:Currency,
andStoreInCollection sink:inout [BalanceItem]) {
let balance = balanceItem(fromJSONItems:items, forCurrency:currency)
appendBalanceItem(item:balance, toCollection: &sink)
}
fileprivate func balanceItem(fromJSONItems items:[[String : Any]],
forCurrency currency:Currency) -> BalanceItem? {
for item in items {
let currencyName = item[BTCTradeUABalanceProvider.CurrencyKey] as? String
if currencyName != nil && currencyName! == currency.rawValue as String {
let balanceString = item[BTCTradeUABalanceProvider.BalanceKey] as? String
if balanceString != nil {
if let balanceValue = Double(balanceString!) {
return BalanceItem(currency:currency, amount:balanceValue)
}
}
}
}
return nil;
}
fileprivate func appendBalanceItem(item:BalanceItem?, toCollection sink:inout [BalanceItem]) {
if item != nil {
sink.append(item!)
}
}
// MARK: Internal fields and properties
private static let BalanceSuffix = "balance"
private static let AccountsKey = "accounts"
private static let CurrencyKey = "currency"
private static let BalanceKey = "balance"
}
|
//
// Int Extension.swift
// Rate Compare App
//
// Created by Jojo Destreza on 9/16/19.
// Copyright © 2019 Jojo Destreza. All rights reserved.
//
import UIKit
extension Int {
func timeIntervalToFormatedDate(format: String) -> String {
let currentDate = Date(timeIntervalSince1970: TimeInterval(self))
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
// print("CONVERT TIME : \(self) == \(dateFormatter.string(from: currentDate))")
return dateFormatter.string(from: currentDate)
}
}
|
//
// ChatOccupantViewController.swift
// LoLMessenger
//
// Created by Kim Young Rok on 2015. 11. 10..
// Copyright © 2015년 rokoroku. All rights reserved.
//
import UIKit
import STPopup
import XMPPFramework
class ChatOccupantViewController: UITableViewController {
var roomId: XMPPJID?
var occupants = [LeagueRoster]()
var numOfRows: Int {
if isSearching {
return filteredNodes.count
} else {
return occupants.count
}
}
var searchController: UISearchController?
var isSearching: Bool {
if searchController?.active ?? false {
return !(searchController?.searchBar.text?.isEmpty ?? true)
}
return false
}
var filteredNodes = [LeagueRoster]()
var activeNodes: [LeagueRoster] {
if isSearching {
return filteredNodes
} else {
return occupants
}
}
func reloadOccupants() {
if let roomId = roomId, let occupantEntries = XMPPService.sharedInstance.chat()?.getOccupantsByJID(roomId) {
occupants = occupantEntries.sort { $0.username < $1.username }
}
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundView = UIView()
tableView.backgroundView?.backgroundColor = Theme.PrimaryColor
let adjustInsets = UIEdgeInsetsMake(16, 0, 0, 0)
tableView.contentInset = adjustInsets;
tableView.scrollIndicatorInsets = adjustInsets;
//setSearchController()
}
func setSearchController() {
//definesPresentationContext = true
self.searchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.sizeToFit()
controller.delegate = self
self.tableView.tableHeaderView = controller.searchBar
return controller
})()
self.tableView.reloadData()
}
override func viewWillAppear(animated: Bool) {
// Load occupants
reloadOccupants()
// Add delegates
XMPPService.sharedInstance.chat()?.addDelegate(self)
}
override func viewDidDisappear(animated: Bool) {
// Remove delegates
if UIApplication.topViewController()?.isKindOfClass(STPopupContainerViewController) == false {
XMPPService.sharedInstance.chat()?.removeDelegate(self)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the cell that generated the segue.
var roster: LeagueRoster!
if let param = sender as? LeagueRoster {
roster = param
} else if let cell = sender as? RosterTableChildCell, let param = cell.roster {
roster = param
}
if roster != nil {
let friend = XMPPService.sharedInstance.roster()?.getRosterList()?.filter {
return roster.username == $0.username
}.first
if friend != nil {
roster = friend
}
if let chatViewController = segue.destinationViewController as? ChatViewController,
let chat = XMPPService.sharedInstance.chat()?.getLeagueChatEntryByJID(roster.jid()) {
chatViewController.setInitialChatData(chat)
}
else if let summonerViewController = segue.destinationViewController as? SummonerDialogViewController {
summonerViewController.roster = roster
if segue.identifier == "SummonerModalPreview" {
summonerViewController.hidesBottomButtons = true
} else if segue.identifier == "SummonerModalCommit" {
if let popupSegue = segue as? PopupSegue {
popupSegue.shouldPerform = false
Async.main(after: 0.1) {
self.performSegueWithIdentifier("EnterChat", sender: sender)
}
}
}
}
}
}
}
// MARK: Table view delegate
extension ChatOccupantViewController {
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numOfRows
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 60
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Table view cells are reused and should be dequeued using a cell identifier.
let cellIdentifier = "RosterCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! RosterTableChildCell
// Fetches the appropriate meal for the data source layout.
let occupant = activeNodes[indexPath.row]
cell.setData(occupant)
cell.backgroundColor = UIColor.clearColor()
return cell
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return !isSearching
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
//
}
}
}
extension ChatOccupantViewController : UISearchResultsUpdating, UISearchControllerDelegate {
func didPresentSearchController(searchController: UISearchController) {
if searchController.searchBar.superview?.isKindOfClass(UITableView) == false {
//searchController.searchBar.removeFromSuperview()
self.tableView.addSubview(searchController.searchBar)
}
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
filteredNodes = occupants.filter {
if let keyword = searchController.searchBar.text {
return $0.username.stringByReplacingOccurrencesOfString(" ", withString: "").localizedCaseInsensitiveContainsString(keyword)
}
return false
}
tableView.reloadData()
}
}
extension ChatOccupantViewController : ChatDelegate {
func didReceiveOccupantUpdate(sender: ChatService, from: LeagueChat, occupant: LeagueRoster) {
if from.jid.user == self.roomId {
if self.occupants.isEmpty {
self.reloadOccupants()
} else {
Async.background {
let leaved = !occupant.available
var index = 0
for entry in self.occupants {
index++
if entry.username == occupant.username {
entry.parsePresence(occupant.getPresenceElement())
break
}
}
if leaved {
self.occupants.removeAtIndex(index)
}
Async.main {
self.tableView.reloadData()
}
}
}
}
}
} |
import Foundation
import Quick
import Nimble
import Carlos
struct FutureSharedExamplesContext {
static let Future = "future"
static let Promise = "promise"
}
class FutureSharedExamplesConfiguration: QuickConfiguration {
override class func configure(configuration: Configuration) {
sharedExamples("a Future") { (sharedExampleContext: SharedExampleContext) in
var future: Future<String>!
var promise: Promise<String>!
var successSentinel: String?
var errorSentinel: ErrorType?
var cancelSentinel = false
var completionValueSentinel: String?
var completionErrorSentinel: ErrorType?
var completionWasCalled = false
beforeEach {
successSentinel = nil
errorSentinel = nil
cancelSentinel = false
completionWasCalled = false
completionErrorSentinel = nil
completionValueSentinel = nil
future = sharedExampleContext()[FutureSharedExamplesContext.Future] as? Future<String>
promise = sharedExampleContext()[FutureSharedExamplesContext.Promise] as? Promise<String>
future
.onSuccess { value in
successSentinel = value
}
.onFailure { error in
errorSentinel = error
}
.onCancel {
cancelSentinel = true
}
.onCompletion { result in
completionWasCalled = true
switch result {
case .Success(let value):
completionValueSentinel = value
case .Error(let error):
completionErrorSentinel = error
default:
break
}
}
}
context("when the promise succeeds") {
let value = "this is a success value"
beforeEach {
promise.succeed(value)
}
it("should call the completion closure") {
expect(completionWasCalled).to(beTrue())
}
it("should pass the right value") {
expect(completionValueSentinel).to(equal(value))
}
it("should not pass any error") {
expect(completionErrorSentinel).to(beNil())
}
it("should not call the error closure") {
expect(errorSentinel).to(beNil())
}
it("should call the success closure") {
expect(successSentinel).notTo(beNil())
}
it("should pass the right value") {
expect(successSentinel).to(equal(value))
}
it("should not call the cancel closure") {
expect(cancelSentinel).to(beFalse())
}
}
context("when the promise fails") {
let error = TestError.AnotherError
beforeEach {
promise.fail(error)
}
it("should call the completion closure") {
expect(completionWasCalled).to(beTrue())
}
it("should not pass any value") {
expect(completionValueSentinel).to(beNil())
}
it("should pass the right error") {
expect(completionErrorSentinel as? TestError).to(equal(error))
}
it("should call the error closure") {
expect(errorSentinel).notTo(beNil())
}
it("should pass the right error") {
expect(errorSentinel as? TestError).to(equal(error))
}
it("should not call the success closure") {
expect(successSentinel).to(beNil())
}
it("should not call the cancel closure") {
expect(cancelSentinel).to(beFalse())
}
}
context("when the promise is canceled") {
beforeEach {
promise.cancel()
}
it("should call the completion closure") {
expect(completionWasCalled).to(beTrue())
}
it("should not pass any value") {
expect(completionValueSentinel).to(beNil())
}
it("should not pass any error") {
expect(completionErrorSentinel).to(beNil())
}
it("should not call the error closure") {
expect(errorSentinel).to(beNil())
}
it("should not call the success closure") {
expect(successSentinel).to(beNil())
}
it("should call the cancel closure") {
expect(cancelSentinel).to(beTrue())
}
}
context("when the future is canceled") {
beforeEach {
future.cancel()
}
it("should call the completion closure") {
expect(completionWasCalled).to(beTrue())
}
it("should not pass any value") {
expect(completionValueSentinel).to(beNil())
}
it("should not pass any error") {
expect(completionErrorSentinel).to(beNil())
}
it("should not call the error closure") {
expect(errorSentinel).to(beNil())
}
it("should not call the success closure") {
expect(successSentinel).to(beNil())
}
it("should call the cancel closure") {
expect(cancelSentinel).to(beTrue())
}
}
}
}
}
class FutureTests: QuickSpec {
override func spec() {
describe("Future") {
var future: Future<String>!
var associatedPromise: Promise<String>!
beforeEach {
associatedPromise = Promise<String>()
future = associatedPromise.future
}
itBehavesLike("a Future") {
[
FutureSharedExamplesContext.Future: future,
FutureSharedExamplesContext.Promise: associatedPromise
]
}
}
}
} |
//
// Daily.swift
// Nalssi
//
// Created by Farah Nedjadi on 28/06/2018.
// Copyright © 2018 mti. All rights reserved.
//
import Foundation
import ObjectMapper
public class Daily: Mappable {
var id: Int?
var city: CityWeather?
var cnt: Int?
var list: [List]?
required public init?(map: Map) {
}
public func mapping(map: Map) {
self.id <- map["id"]
self.city <- map["city"]
self.cnt <- map["cnt"]
self.list <- map["list"]
}
}
|
//
// LeafTextureType.swift
// florafinder
//
// Created by Andrew Tokeley on 11/01/16.
// Copyright © 2016 Andrew Tokeley . All rights reserved.
//
import Foundation
import CoreData
class LeafTextureType: NSManagedObject {
override var description: String
{
if (name != nil)
{
return "The top side of the leaf has a \(name!.lowercaseString) texture."
}
return ""
}
}
|
//
// TypeDetailViewController.swift
// TestToDoApp3
//
// Created by Kriz Zhao on 2016/12/3.
// Copyright © 2016年 Kriz. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class TypeDetailViewController : UITableViewController, UITextFieldDelegate {
@IBOutlet weak var doneButton: UIBarButtonItem!
@IBOutlet weak var nameText: UITextField!
@IBOutlet weak var descText: UITextField!
@IBOutlet weak var diffText: UITextField!
@IBOutlet weak var dueDateText: UILabel!
@IBOutlet weak var switchControl: UISwitch!
var star = 0
var typeItem = TypeItem(name : "")
var isAdd = true
var datePickerVisible = false
@IBAction func done(_ sender: Any) {
let difficulty = { () -> Int in
switch self.diffText.text! {
case "easy": return 0
case "medium": return 1
case "hard": return 2
case "nightmare": return 3
default: return -1
}
}
let urlStr = "http://127.0.0.1:8080/create/todo?todoName=\(nameText.text!)&todoDesc=\(descText.text!)&uid=\(userId!)&star=\(star)&difficulty=\(difficulty)"
pushNewTodo(urlStr: urlStr)
}
func pushNewTodo(urlStr: String) {
print(urlStr)
let url: URL = URL(string: urlStr)!
Alamofire.request(url).validate().responseJSON { response in
switch response.result.isSuccess {
case true:
print("Json convert successful!")
if let value = response.result.value {
let json = JSON(value)
if json["result"].string != "SUCCESS" {
print("Something wrong!")
return
}
if let uid = json["list"]["userId"].string {
userId = uid
print(uid)
self.typeItem.name = self.nameText.text!
self.typeItem.desc = self.descText.text!
self.typeItem.shouldRemind = self.switchControl.isOn
if self.isAdd {
toDoModel.onAddType(type: self.typeItem)
}
// self.present(UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "typeViewController"), animated: true, completion: nil)
let navigation = self.tabBarController?.viewControllers?[4] as! UINavigationController
let typeView = navigation.viewControllers.first as? TypeViewController
typeView?.todosTableView.reloadData()
_ = self.navigationController?.popViewController(animated: false)
self.onAddType()
toDoModel.saveData()
print(toDoModel.typeList.count)
}
}
case false:
print("Json convert error!")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
if ViewBag != nil {
onEditType(item: ViewBag as! TypeItem)
ViewBag = nil
} else {
onAddType()
}
NotificationCenter.default.addObserver(self, selector: #selector(getValue), name: NSNotification.Name(rawValue: "value"), object: nil)
updateDueDateLabel()
nameText.delegate = self
descText.delegate = self
diffText.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
onUpdate()
doneButton.isEnabled = nameText!.text != ""
}
func onAddType() {
isAdd = true
typeItem = TypeItem(name: "")
self.title = "添加"
}
func onEditType(item : TypeItem) {
isAdd = false
self.title = "编辑分类"
self.typeItem = item
}
func onUpdate() {
self.nameText.text = typeItem.name
self.descText.text = typeItem.desc
self.diffText.text = typeItem.diff
}
func updateDueDateLabel() {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy年MM月dd日 HH:mm:ss"
self.dueDateText.text = formatter.string(from: typeItem.dueDate as Date)
}
func getValue(notification : NSNotification) {
self.diffText.text = notification.object as! String?
}
func showDatePicker() {
datePickerVisible = true
self.tableView.beginUpdates()
self.tableView.insertRows(at: [IndexPath(row: 2, section: 2)], with: .automatic)
self.tableView.endUpdates()
}
func hideDatePicker() {
if datePickerVisible {
datePickerVisible = false
self.tableView.beginUpdates()
self.tableView.deleteRows(at: [IndexPath(row: 2, section: 2)], with: .fade)
self.tableView.endUpdates()
}
}
func dateChanged(_ datePicker : UIDatePicker) {
typeItem.dueDate = datePicker.date as NSDate
updateDueDateLabel()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath, animated: true)
view.endEditing(true)
print("\(indexPath.section) \(indexPath.row)")
if indexPath.section == 2 && indexPath.row == 1 {
if !datePickerVisible {
self.showDatePicker()
} else {
self.hideDatePicker()
}
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 2 && indexPath.row == 2 {
return 217.0
} else {
return super.tableView(tableView, heightForRowAt: indexPath)
}
}
override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {
if indexPath.section == 2 && indexPath.row == 2 {
let newIndexPath = NSIndexPath(row: 0, section: indexPath.section)
return super.tableView(tableView, indentationLevelForRowAt: newIndexPath as IndexPath)
} else {
return super.tableView(tableView, indentationLevelForRowAt: indexPath)
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 2 && datePickerVisible {
return 3
} else {
return super.tableView(tableView, numberOfRowsInSection: section)
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 2 && indexPath.row == 2 {
var cell = tableView.dequeueReusableCell(withIdentifier: "DatePickerCell") as UITableViewCell?
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "DatePickerCell")
cell?.selectionStyle = .none
let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: 320, height: 216))
datePicker.tag = 100
datePicker.locale = Locale(identifier: "zh_CN")
cell?.contentView.addSubview(datePicker)
datePicker.addTarget(self, action: #selector(dateChanged(_:)), for: .valueChanged)
}
return cell!
} else {
return super.tableView(tableView, cellForRowAt: indexPath)
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField.tag == 0 {
let newText = textField.text!.replacingCharacters(in: range.toRange(string: textField.text!), with: string)
doneButton.isEnabled = newText.characters.count > 0
}
return true
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
print("\(textField.tag)")
if textField.tag == 1 {
nameText.resignFirstResponder()
let picker = DiffPickerView()
picker.show()
return false
} else if textField.tag == 2 {
if nameText.text != "" {
typeItem.name = nameText.text!
}
typeItem.diff = diffText.text!
nameText.resignFirstResponder()
ViewBag = typeItem
self.performSegue(withIdentifier: "showDescEditView", sender: nil)
return false
} else {
return true
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
view.endEditing(true)
return true
}
}
extension NSRange {
func toRange(string : String) -> Range<String.Index> {
let startIndex = string.index(string.startIndex, offsetBy: self.location)
let endIndex = string.index(startIndex, offsetBy: self.length)
return startIndex..<endIndex
}
}
|
//
// CustomTableViewCell.swift
// radio
//
// Created by MacBook 13 on 7/18/18.
// Copyright © 2018 MacBook 13. All rights reserved.
//
import UIKit
class GenresViewCell: UITableViewCell {
@IBOutlet weak var leftImage: UIImageView!
@IBOutlet weak var rigthImage: UIImageView!
@IBOutlet weak var labelLeft: UILabel!
@IBOutlet weak var labelRigth: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.autoresizingMask = UIViewAutoresizing(rawValue: UIViewAutoresizing.RawValue(UInt8(UIViewAutoresizing.flexibleBottomMargin.rawValue) | UInt8(UIViewAutoresizing.flexibleHeight.rawValue) | UInt8(UIViewAutoresizing.flexibleRightMargin.rawValue) | UInt8(UIViewAutoresizing.flexibleLeftMargin.rawValue) | UInt8(UIViewAutoresizing.flexibleTopMargin.rawValue) | UInt8(UIViewAutoresizing.flexibleWidth.rawValue)))
self.contentMode = UIViewContentMode.scaleAspectFit
/*
Rounded corners in both images
*/
self.leftImage.layer.cornerRadius = 10
self.leftImage.clipsToBounds = true
self.rigthImage.layer.cornerRadius = 10
self.rigthImage.clipsToBounds = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// CollectViewController.swift
// LimitFree Created by ice on 16/9/29.
// Copyright © 2016年 k. All rights reserved.
//
import UIKit
//收藏app 的页面
class CollectViewController: LFNavViewController {
//数据源---收藏的app
private var dataArray: NSMutableArray?
private var scrollView: UIScrollView?
private var pageCtrl: UIPageControl?
//是否删除的状态
private var isDelete = false
override func viewDidLoad() {
super.viewDidLoad()
createMyNav()
automaticallyAdjustsScrollViewInsets = false
scrollView = UIScrollView(frame: CGRectMake(0, 64, kScreenWidth, kScreenHeight-64))
scrollView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
scrollView?.pagingEnabled = true
view.addSubview(scrollView!)
//分页控件
pageCtrl = UIPageControl(frame: CGRectMake(80, kScreenHeight-60, 200, 20))
//pageCtrl?.backgroundColor = UIColor.redColor()
pageCtrl?.pageIndicatorTintColor = UIColor.blackColor()
view.addSubview(pageCtrl!)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//查询数据
let dbManager = LFDBManger()
//执行函数,.执行完后会执行闭包的代码 //相当搜索完后 给闭包赋值(就是将的搜索到的数组 传过来,在此页面进行一些操作)
dbManager.searchAllCollectiData { (array) -> Void in
self.dataArray = NSMutableArray(array: array)
//显示UI //显示收藏的app
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.showCollectData()
})
}
}
//显示收藏的数据
func showCollectData(){
//清空一下之前的子视图 // 否则重复创建子视图
for tmpView in (scrollView?.subviews)!{
if tmpView.isKindOfClass(CollectButton){
tmpView.removeFromSuperview()
}
}
//遍历数据源数组显示
if dataArray?.count > 0{
let cnt = (dataArray?.count)!
for i in 0..<cnt{
//计算页数
let page = i / 9
let colNumber = 3
let btnW: CGFloat = 80
let btnH: CGFloat = 100
let offsetX: CGFloat = 30 //第一列的x值
let spaceX: CGFloat = (kScreenWidth-CGFloat(colNumber)*btnW-offsetX*2-20)/CGFloat(colNumber-1) //列间距
let offsetY: CGFloat = 66 //第一行的y值
let spaceY: CGFloat = 60 //行间距
//计算按钮的行和列
let rowAndCol = i%9
let row = rowAndCol/colNumber
let col = rowAndCol%colNumber
let btnX = offsetX + CGFloat(col) * (btnW + spaceX) + kScreenWidth * CGFloat(page)
let btnY = offsetY + CGFloat(row) * (btnH + spaceY)
let btn = CollectButton(frame: CGRectMake(btnX, btnY, 0, 0))
//显示数据 //改变model的值,会对视图和albel赋值
btn.model = dataArray![i] as? CollectModel
//设置 按钮的 删除状态
btn.isDelete = isDelete
btn.addTarget(self, action: "clickBtn:", forControlEvents: .TouchUpInside)
scrollView!.addSubview(btn)
//设置代理
btn.delegate = self
btn.btnIndex = i
}
//滚动范围
let pageCnt = (cnt + 8) / 9
scrollView?.contentSize = CGSizeMake(CGFloat(pageCnt)*kScreenWidth, 0)
scrollView?.delegate = self
//设置分页控件的总数,和开始的显示
pageCtrl?.numberOfPages = pageCnt
pageCtrl?.currentPage = 0
}else{
//没有收藏
MyUtil.showAllertMsg("还没有任何收藏的数据", onViewController: self)
}
}
//点击收藏的app进入到app详情
func clickBtn(btn: CollectButton){
if isDelete == false{ //非编辑状态才可以进入app详情
let detailCtrl = DetailViewController()
detailCtrl.appId = btn.model?.applicationId
hidesBottomBarWhenPushed = true
navigationController?.pushViewController(detailCtrl, animated: true)
hidesBottomBarWhenPushed = false
}
}
func createMyNav(){
addBackBtn()
addNavTitle("我的收藏")
addNavButton("编辑", target: self, action: "editAction:", isLeft: false)
}
//哪个调用了 addtaget 方法 就传过来是哪种参数
func editAction(btn: UIButton){
if isDelete == false{
//进入删除状态
btn.setTitle("完成", forState: .Normal)
//改变按钮的属性
for tmpView in (scrollView?.subviews)!{
//滑动视图的子视图中会有 水平和竖直的提示条
if tmpView.isKindOfClass(CollectButton){
let btn = tmpView as! CollectButton
btn.isDelete = true
}
}
isDelete = true
}else{
//退出删除状态
if isDelete == true{
//进入删除状态
btn.setTitle("编辑", forState: .Normal)
//改变按钮的属性
for tmpView in (scrollView?.subviews)!{
//滑动视图的子视图中会有 水平和竖直的提示条
if tmpView.isKindOfClass(CollectButton){
let btn = tmpView as! CollectButton
btn.isDelete = false
}
}
isDelete = false
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
//MARK: CollectButtonDelegate
extension CollectViewController: CollectButtonDelegate{
func didDeleteBtnAtIndex(index: Int) {
//1...从数据库删除
let model = dataArray![index] as! CollectModel
let dbManager = LFDBManger()
dbManager.deleteWithAppId(model.applicationId!) { (flag) -> Void in
if flag == true{
//2...从数据源数组中删除
self.dataArray?.removeObjectAtIndex(index)
//3...重新显示
self.showCollectData()
}else{
MyUtil.showAllertMsg("删除失败", onViewController: self)
}
}
}
}
//MARK: UIScrollViewDelegate
extension CollectViewController: UIScrollViewDelegate {
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let index = Int(scrollView.contentOffset.x / scrollView.bounds.width)
pageCtrl?.currentPage = index
}
} |
/*:
### 7. Reverse Integer
[LeetCode](https://leetcode.com/problems/reverse-integer/description/)
Given a 32-bit signed integer, reverse digits of an integer.
**Example 1:**
```
Input: 123
Output: 321
```
**Example 2:**
```
Input: -123
Output: -321
```
**Example 3:**
```
Input: 120
Output: 21
```
**Note:**\
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2<sup>31</sup>, 2<sup>31</sup> − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
*/
class Solution {
func reverse1(_ x: Int) -> Int {
if x > Int32.max || x < Int32.min {
return 0
}
var string = String(x)
var ten = x > 0 ? 1 : -1
var result = 0
for (_, element) in string.characters.enumerated() {
if let number = Int(String(element)) {
result += number * ten
ten *= 10
}
}
if result > Int32.max || result < Int32.min {
return 0
}
return result
}
func reverse2(_ x: Int) -> Int {
if x > Int32.max || x < Int32.min {
return 0
}
var number = abs(x)
var nums = [Int]()
while number != 0 {
nums.append(number % 10)
number = number / 10
}
var result = 0
var multi = 1
for num in nums.reversed() {
result += num * multi
multi *= 10
}
if result > Int32.max || result < Int32.min {
return 0
}
return result * (x < 0 ? -1 : 1)
}
func reverse3(_ x: Int) -> Int {
if x > Int32.max || x < Int32.min {
return 0
}
var number = abs(x)
var nums = [Int]()
while number != 0 {
nums.append(number % 10)
number = number / 10
}
var result = 0
var multi = 1
let count = nums.count
for index in 0..<count {
result += nums[count - index - 1] * multi
multi *= 10
}
if result > Int32.max || result < Int32.min {
return 0
}
return result * (x < 0 ? -1 : 1)
}
func reverse4(_ x: Int) -> Int {
if x > Int32.max || x < Int32.min {
return 0
}
var number = x
var result = 0
while number != 0 {
result = result * 10 + number % 10
number = number / 10
}
if result > Int32.max || result < Int32.min {
return 0
}
return result
}
}
Solution().reverse1(-1011)
Solution().reverse2(-1011)
Solution().reverse3(-1011)
Solution().reverse4(-1011)
/*:
**Submissions:**
1. reverse1: 40 ms
2. reverse2: 32 ms
3. reverse3: 28 ms
4. reverse4: 28 ms
*/
//: [Previous](@previous)|
//: [Next](@next)
|
//
// DayCellView.swift
// Recircle
//
// Created by synerzip on 06/04/17.
// Copyright © 2017 synerzip. All rights reserved.
//
import UIKit
import JTAppleCalendar
class DayCellView: JTAppleDayCellView {
@IBOutlet weak var textDate: UILabel!
@IBOutlet weak var selectedView: UIView!
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
|
//
// Feedback.swift
// JEM_CarPool_iOS
//
// Created by Aleksandr Shoshiashvili on 13.02.16.
// Copyright © 2016 JEM_CarPool_iOS. All rights reserved.
//
import Foundation
class Category: NSObject {
var id = NSNumber()
var title = ""
var teams = [Team]()
convenience override init() {
self.init([String:AnyObject]())
}
init (_ dictionary: [String:AnyObject]) {
if let newId = dictionary["id"] as? NSNumber {
id = newId
}
if let newTitle = dictionary["title"] as? String {
title = newTitle
}
if let newTeams = dictionary["teams"] as? [[String:AnyObject]] {
for team in newTeams {
teams.append(Team(team))
}
}
}
} |
//
// ViewController.swift
// MacEnigma
//
// Created by Leo Mehlig on 2/21/15.
// Copyright (c) 2015 Leo Mehlig. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
rotorb()
}
func creatPossibleOrders(values: [Int]) -> [[Int]] {
var possibleOrders = [[Int]]()
for (idx, val) in enumerate(values) {
var newValues = values
newValues.removeAtIndex(idx)
if newValues.count > 0 {
for order in creatPossibleOrders(newValues) {
possibleOrders.append([val] + order)
}
} else {
possibleOrders.append([val])
}
}
return possibleOrders
}
func loop() {
let testText = "wearethewatchersonthewall"
let enigma = Enigma(ref: .A, rotors: .I, .II, .III)
let encodedText = enigma.encodeText(testText)
if let loops = PlugboardBombe.LoopCreater.loopConnectionsFrom(encodedStr: testText, decodedStr: encodedText) {
for (loop, range, closed) in loops {
println(loop)
println(range)
println(closed)
}
}
}
func pb() {
let testText = "wearethewatchersonthewall"
let enigma = Enigma(ref: .C, rotors: .II, .I, .III)
enigma.rotor(0)?.rotorPositionLetter = "f"
enigma.rotor(1)?.rotorPositionLetter = "q"
enigma.rotor(2)?.rotorPositionLetter = "c"
// enigma.rotorI.offsetLetter = "d"
// enigma.rotorII.offsetLetter = "g"
// enigma.rotorIII.offsetLetter = "k"
enigma.plugboard.pairs = [PlugboardPair("a","v"), PlugboardPair("d", "m"), PlugboardPair("f", "t"), PlugboardPair("h", "i"), PlugboardPair("k", "o"), PlugboardPair("p", "s"), PlugboardPair("q", "x"), PlugboardPair("r", "w")]
let encodedText = enigma.encodeText(testText)
let bombe = PlugboardBombe(enigma: enigma)
if let loops = PlugboardBombe.LoopCreater.loopConnectionsFrom(encodedStr: testText, decodedStr: encodedText) {
for loop in loops {
println(loop)
}
println(bombe.plugboardForLoops(loops, text: testText, enText: encodedText))
}
}
func rotorb() {
let startDate = NSDate()
println(NSDate())
let testText = "wearethewatchersonthewall"
let enigma = Enigma(ref: .C, rotors: .II, .II, .I)
enigma.rotor(0)?.rotorPositionLetter = "f"
enigma.rotor(1)?.rotorPositionLetter = "q"
enigma.rotor(2)?.rotorPositionLetter = "c"
// enigma.rotorI.offsetLetter = "d"
// enigma.rotorII.offsetLetter = "g"
// enigma.rotorIII.offsetLetter = "k"
enigma.plugboard.pairs = [PlugboardPair("y","v"), PlugboardPair("d", "m"), PlugboardPair("f", "t"), PlugboardPair("h", "i"), PlugboardPair("k", "o"), PlugboardPair("p", "s"), PlugboardPair("q", "x"), PlugboardPair("r", "w")]
let bombe = PlugboardBombe(enigma: enigma)
let encodedText = enigma.encodeText(testText)
if let loops = PlugboardBombe.LoopCreater.loopConnectionsFrom(encodedStr: testText, decodedStr: encodedText) {
for loop in loops {
println(loop)
}
println(encodedText)
let rb = RotorBombe()
rb.encodedString = testText
rb.decodedString = encodedText
rb.testRotors = { (e) in
let bombe = PlugboardBombe(enigma: e)
return bombe.plugboardForLoops(loops, text: testText, enText: encodedText)
}
while rb.running { }
println(NSDate())
println(startDate.timeIntervalSinceNow)
}
}
}
|
//
// EggPlantEggTableViewCell.swift
// EggPlantEggVideo
//
// Created by 粘辰晧 on 2021/4/18.
//
import UIKit
class EggPlantEggTableViewCell: UITableViewCell {
@IBOutlet weak var eggPlantEggImageView: UIImageView!
@IBOutlet weak var eggPlantEggLabel: UILabel!
@IBOutlet weak var eggPlantEggIntro: 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
}
}
|
//
// DraggableView.swift
// iOSWindow
//
// Created by Luke on 2019-07-28.
// Copyright © 2019 Luke. All rights reserved.
//
import UIKit
public protocol UIWindowsDelegate {
func closeWindow()
func enterfullscreen()
func exitfullscreen()
func toggleFullScreen()
}
public class UIWindowsWindow: UIView {
public var config: UIWindowsConfig
var topGap: NSLayoutConstraint!
var leftGap: NSLayoutConstraint!
var heightConstant: NSLayoutConstraint!
var widthConstant: NSLayoutConstraint!
var topGapBackup: CGFloat?
var leftGapBackup: CGFloat?
var heightConstantBackup: CGFloat?
var widthConstantBackup: CGFloat?
public var title: String = "" {
didSet {
titleLabel.text = title
}
}
var oWidth: CGFloat = 0
var oHeight: CGFloat = 0
var oLeft: CGFloat = 0
var oTop: CGFloat = 0
var nWidth: CGFloat = 0
var nHeight: CGFloat = 0
var offsetX: CGFloat = 0
var offsetY: CGFloat = 0
var leftTopView = UIView()
var leftBotView = UIView()
var rightTopView = UIView()
var rightBotView = UIView()
var titleLabel = UILabel()
let containerView = UIView()
let windowBarView = UIWindowBarView(frame: CGRect(x: 0, y: 0, width: 100, height: 22))
public var childVC: UIViewController
weak var parentVC: UIViewController?
weak var desktop: UIDesktop?
enum TouchEvent {
case moveWindow
case resize(left: Bool, top: Bool)
}
public init(childVC: UIViewController, with config: UIWindowsConfig?) {
if let config = config {
self.config = config
} else {
self.config = UIWindowsConfig.defaultConfig
}
self.childVC = childVC
super.init(frame: CGRect(x: 10, y: 10, width: self.config.minWidth, height: self.config.minHeight))
self.addSubview(containerView)
self.backgroundColor = .clear
containerView.addSubview(windowBarView)
windowBarView.windowDelegate = self
windowBarView.addSubview(titleLabel)
fix(this: titleLabel, into: windowBarView, horizontal: .fill(leading: 0, trailing: 0), vertical: .fill(leading: 0, trailing: 0))
titleLabel.textAlignment = .center
self.setUpCornerGestureView()
fix(this: containerView, into: self, horizontal: .fill(leading: 0, trailing: 0), vertical: .fill(leading: 0, trailing: 0))
containerView.backgroundColor = .clear
containerView.clipsToBounds = true
containerView.layer.cornerRadius = 8
containerView.layer.borderColor = UIColor.systemGray3.cgColor
containerView.layer.borderWidth = 1/UIScreen.main.scale
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width: 0, height: 10)
self.layer.shadowRadius = 30
self.layer.shadowOpacity = 0.5
fix(this: windowBarView, into: self, horizontal: .fill(leading: 0, trailing: 0), vertical: .fixLeading(leading: 0, intrinsic: self.config.barHeight))
containerView.addSubview(childVC.view)
fix(this: childVC.view, into: containerView, horizontal: .fill(leading: self.config.windowEdgeWidth, trailing: self.config.windowEdgeWidth), vertical: .fill(leading: self.config.barHeight, trailing: self.config.windowEdgeWidth))
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.handlePan))
windowBarView.addGestureRecognizer(panGesture)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func getPreview() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0.0)
defer { UIGraphicsEndImageContext() }
if let context = UIGraphicsGetCurrentContext() {
self.layer.render(in: context)
let image = UIGraphicsGetImageFromCurrentImageContext()
return image
}
return nil
}
override public func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let view = super.hitTest(point, with: event)
if view != nil {
self.desktop?.set(focus: self)
}
return view
}
private var resizing: Bool = false {
didSet {
if resizing {
containerView.layer.borderColor = config.tintColor.withAlphaComponent(0.6).cgColor
containerView.layer.borderWidth = 3
} else {
containerView.layer.borderColor = UIColor.systemGray3.cgColor
containerView.layer.borderWidth = 1/UIScreen.main.scale
}
}
}
private var focus: Bool = false {
didSet {
if self.focus {
parentVC?.view.bringSubviewToFront(self)
self.layer.shadowOpacity = 0.5
self.layer.shadowRadius = 30
self.layer.shadowOffset = CGSize(width: 0, height: 10)
} else {
self.layer.shadowOpacity = 0.2
self.layer.shadowRadius = 5
self.layer.shadowOffset = CGSize(width: 0, height: 3)
}
}
}
private var fullScreen: Bool = false {
didSet {
if fullScreen {
backupPosition()
topGap.constant = (desktop?.view?.safeAreaInsets.top ?? 0)
leftGap.constant = 0
heightConstant.constant = desktop?.view?.frame.height ?? 400 - (desktop?.view?.safeAreaInsets.top ?? 0)
widthConstant.constant = desktop?.view?.frame.width ?? 300
} else {
recoverPosition()
}
UIView.animate(withDuration: 0.3) {
self.desktop?.view?.layoutSubviews()
}
}
}
func backupPosition(){
if !fullScreen {
topGapBackup = topGap.constant
leftGapBackup = leftGap.constant
heightConstantBackup = heightConstant.constant
widthConstantBackup = widthConstant.constant
}
}
func recoverPosition(){
topGap.constant = topGapBackup ?? 0
leftGap.constant = leftGapBackup ?? 0
heightConstant.constant = heightConstantBackup ?? 300
widthConstant.constant = widthConstantBackup ?? 400
}
func set(constraint top: CGFloat, left: CGFloat, superView: UIView) {
self.topGap.constant = top
self.leftGap.constant = left
self.transform = .identity
superView.layoutSubviews()
}
func set(focus: Bool) {
self.focus = focus
}
func set(viewControllerMoveTo parent: UIViewController) {
self.childVC.didMove(toParent: parent)
}
func handle(touchEvent: UIWindowsWindow.TouchEvent, from sander: UIPanGestureRecognizer) {
guard let parentVC = self.parentVC else {
return
}
switch touchEvent {
case .moveWindow:
switch sander.state {
case .began:
backupPosition()
case .changed:
desktop?.handlePan(changed: self, offsetX: sander.translation(in: parentVC.view).x, offsetY: sander.translation(in: parentVC.view).y)
case .ended:
desktop?.handlePan(end: self, offsetX: sander.translation(in: parentVC.view).x, offsetY: sander.translation(in: parentVC.view).y)
backupPosition()
if self.fullScreen {self.fullScreen = false}
self.layoutSubviews()
default:
self.transform = .identity
}
case .resize(let left, let top):
self.resizing = sander.state == .changed
switch sander.state {
case .began:
oWidth = widthConstant.constant
oHeight = heightConstant.constant
backupPosition()
case .changed:
self.nWidth = oWidth + sander.translation(in: self).x * (left ? (-1) : (1))
self.nHeight = oHeight + sander.translation(in: self).y * (top ? (-1) : (1))
if left { self.offsetX = sander.translation(in: parentVC.view).x }
if top { self.offsetY = sander.translation(in: parentVC.view).y }
if nHeight < parentVC.view.frame.height, nHeight > self.config.minHeight {
self.heightConstant.constant = nHeight
} else {
if nHeight > parentVC.view.frame.height {
offsetY = oHeight - parentVC.view.frame.height
} else {
offsetY = oHeight - self.config.minHeight
}
}
if nWidth < parentVC.view.frame.width, nWidth > self.config.minWidth {
self.widthConstant.constant = nWidth
} else {
if nWidth > parentVC.view.frame.width {
offsetX = oWidth - parentVC.view.frame.width
} else {
offsetX = oWidth - self.config.minWidth
}
}
desktop?.handlePan(changed: self, offsetX: left ? offsetX : 0, offsetY: top ? offsetY : 0)
self.layoutSubviews()
case .ended:
desktop?.handlePan(end: self, offsetX: left ? offsetX : 0, offsetY: top ? offsetY : 0)
backupPosition()
self.layoutSubviews()
default:
self.transform = .identity
widthConstant.constant = oWidth
heightConstant.constant = oHeight
self.layoutSubviews()
}
}
}
@objc func handlePan(_ sander: UIPanGestureRecognizer){
self.handle(touchEvent: .moveWindow, from: sander)
}
@objc func handlePanTL(_ sander: UIPanGestureRecognizer){
self.handle(touchEvent: .resize(left: true, top: true), from: sander)
}
@objc func handlePanTR(_ sander: UIPanGestureRecognizer){
self.handle(touchEvent: .resize(left: false, top: true), from: sander)
}
@objc func handlePanBL(_ sander: UIPanGestureRecognizer){
self.handle(touchEvent: .resize(left: true, top: false), from: sander)
}
@objc func handlePanBR(_ sander: UIPanGestureRecognizer){
self.handle(touchEvent: .resize(left: false, top: false), from: sander)
}
func transformWindows(transform x: CGFloat, y:CGFloat) {
self.transform = CGAffineTransform(translationX: x, y: y)
}
func setUpCornerGestureView(){
self.addSubview(leftBotView)
self.addSubview(leftTopView)
self.addSubview(rightBotView)
self.addSubview(rightTopView)
let panGestureTL = UIPanGestureRecognizer(target: self, action: #selector(handlePanTL))
let panGestureTR = UIPanGestureRecognizer(target: self, action: #selector(handlePanTR))
let panGestureBL = UIPanGestureRecognizer(target: self, action: #selector(handlePanBL))
let panGestureBR = UIPanGestureRecognizer(target: self, action: #selector(handlePanBR))
leftBotView.addGestureRecognizer(panGestureBL)
leftTopView.addGestureRecognizer(panGestureTL)
rightBotView.addGestureRecognizer(panGestureBR)
rightTopView.addGestureRecognizer(panGestureTR)
leftBotView.backgroundColor = .clear
leftTopView.backgroundColor = .clear
rightBotView.backgroundColor = .clear
rightTopView.backgroundColor = .clear
fix(this: leftTopView, into: self, horizontal: .fixLeading(leading: 0, intrinsic: config.cornerResponsRadius), vertical: .fixLeading(leading: 0, intrinsic: config.cornerResponsRadius))
fix(this: leftBotView, into: self, horizontal: .fixLeading(leading: 0, intrinsic: config.cornerResponsRadius), vertical: .fixTrailing(trailing: 0, intrinsic: config.cornerResponsRadius))
fix(this: rightBotView, into: self, horizontal: .fixTrailing(trailing: 0, intrinsic: config.cornerResponsRadius), vertical: .fixTrailing(trailing: 0, intrinsic: config.cornerResponsRadius))
fix(this: rightTopView, into: self, horizontal: .fixTrailing(trailing: 0, intrinsic: config.cornerResponsRadius), vertical: .fixLeading(leading: 0, intrinsic: config.cornerResponsRadius))
}
}
extension UIWindowsWindow: UIWindowsDelegate {
public func enterfullscreen(){
self.fullScreen = true
}
public func exitfullscreen(){
self.fullScreen = false
}
public func closeWindow(){
if self.fullScreen {
self.fullScreen = false
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.desktop?.remove(window: self)
}
} else {
self.desktop?.remove(window: self)
}
}
public func toggleFullScreen() {
self.fullScreen = !self.fullScreen
}
}
|
import UIKit
public func filter(image: UIImage?) -> UIImage? {
guard let image = image else { return .none }
sleep(1)
let mask = topAndBottomGradient(size: image.size)
return image.applyBlur(radius: 6, maskImage: mask)
}
func filterAsync(image: UIImage?, callback: @escaping (UIImage?) ->()) {
OperationQueue().addOperation {
let result = filter(image: image)
callback(result)
}
}
public class Filter: ImageTakeOperation {
override public func main() {
if isCancelled { return }
guard let inputImage = inputImage else { return }
if isCancelled { return }
let mask = topAndBottomGradient(size: inputImage.size)
if isCancelled { return }
outputImage = inputImage.applyBlurWithRadius(6, maskImage: mask)
}
}
|
//
// HardDependenciesTests.swift
// HardDependenciesTests
//
// Created by Ataias Pereira Reis on 11/01/21.
//
import XCTest
class HardDependenciesTests: XCTestCase {
}
|
//
// SignUpViewController.swift
// HireTalent
//
// Created by Ricardo Luna Guerrero on 06/04/20.
// Copyright © 2020 Dream Team. All rights reserved.
//
import UIKit
class SignUpViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var lastNameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var rfcTextField: UITextField!
@IBOutlet weak var companyTextField: UITextField!
@IBOutlet weak var address1TextField: UITextField!
@IBOutlet weak var address2TextField: UITextField!
@IBOutlet weak var cityTexField: UITextField!
@IBOutlet weak var signUpButton: UIButton!
@IBOutlet weak var errorLabel: UILabel!
@IBOutlet weak var departmentPicker: UIPickerView!
@IBOutlet weak var stateTextField: UITextField!
// Variables used for the department picker
var departmentData: [String] = [String]()
var department: String = "Sales"
override func viewDidLoad() {
super.viewDidLoad()
// Stylize the UI elements
setUpElements()
// Initialize the PickerView
initPickerViews()
}
// Specify the number of columns in the PickerView
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
// Specify the number of rows in the PickerView
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return departmentData.count
}
// Display the rowth element of the departmentData array in the PickerView
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return departmentData[row]
}
// Return the current value of the PickerView
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
department = departmentData[row]
}
// Stylize the UI elements
func setUpElements() {
// Hide the error label
errorLabel.alpha = 0
// Style the elements
Utilities.styleFormTextField(firstNameTextField)
Utilities.styleFormTextField(lastNameTextField)
Utilities.styleFormTextField(emailTextField)
Utilities.styleFormTextField(passwordTextField)
Utilities.styleFormTextField(rfcTextField)
Utilities.styleFormTextField(companyTextField)
Utilities.styleFormTextField(address1TextField)
Utilities.styleFormTextField(address2TextField)
Utilities.styleFormTextField(cityTexField)
Utilities.styleFormTextField(stateTextField)
Utilities.styleFilledButton(signUpButton)
}
// Initialize the PickerView
func initPickerViews(){
// Department
self.departmentPicker.delegate = self
self.departmentPicker.dataSource = self
departmentData = ["Sales", "Export", "IT", "Marketing", "Financial", "Human Resources", "Purchasing", "Logistics"]
}
// Check the fields and validate that the data is correct. If everything is correct, this method returns nil.
// Otherwise, it returns the error message.
func validateFields() -> String? {
// Check that all fields are filled in
if firstNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || lastNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || emailTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || passwordTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || rfcTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || companyTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || address1TextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || address2TextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || cityTexField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || stateTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
return "Please fill in all the fields"
}
// Check if the password is secure
if Utilities.isPasswordValid(passwordTextField.text!) == false {
return "Please make sure your password is at least 8 characters, contains a special character and a number"
}
return nil
}
// Some error ocurred, show the error message
func showError(_ message: String){
errorLabel.text = message
errorLabel.alpha = 1
}
// When Sign Up button tapped then...
@IBAction func signUpTapped(_ sender: Any) {
// Validate the fields
let error = validateFields()
// Check for errors
if error != nil {
// There's something wrong with the fields, show error message
showError(error!)
}
else {
// Call the function to create a user
EmployerDAO.createUser(emailTextField.text!, passwordTextField.text!) { (userRetrieved) in
// If the user was not created correctly
if userRetrieved == nil {
self.showError("There was an error creating the user")
}
else {
self.addUserInformation(userRetrieved)
self.addEmployerInformation(userRetrieved)
}
}
}
}
}
extension SignUpViewController {
// Call the function to add a new user and their type
func addUserInformation(_ userRetrieved: String?) {
UserDAO.addUserInformation(userRetrieved!){ (userErrorHandler) in
// If there was an error storing the user information
if userErrorHandler != nil {
self.showError(userErrorHandler!)
}
}
}
// Call the function to insert the user extra data
func addEmployerInformation(_ userRetrieved: String?) {
EmployerDAO.addEmployerInformation(userRetrieved!, self.firstNameTextField.text!, self.lastNameTextField.text!, self.emailTextField.text!, self.department, self.rfcTextField.text!) { (employerErrorHandler) in
// If there was an error storing the employer information
if employerErrorHandler != nil {
self.showError(employerErrorHandler!)
}
else {
self.addCompanyInformation()
}
}
}
// Call the function to add the company information
func addCompanyInformation() {
CompanyDAO.addCompanyInformation(self.rfcTextField.text!, self.companyTextField.text!, self.address1TextField.text!, self.address2TextField.text!, self.cityTexField.text!, self.stateTextField.text!) { (companyErrorHandler) in
// If there was an error storing the company information
if companyErrorHandler != nil {
self.showError(companyErrorHandler!)
}
else {
self.performSegue(withIdentifier: "signedInEmployer", sender: nil)
}
}
}
}
|
//
// TabBarBadgeManager.swift
// Dash
//
// Created by Yuji Nakayama on 2020/12/01.
// Copyright © 2020 Yuji Nakayama. All rights reserved.
//
import UIKit
class TabBarBadgeManager {
enum TabBarItemTag: Int {
case inbox = 2
}
let tabBarController: UITabBarController
private var sharedItemDatabaseObservation: NSKeyValueObservation?
var tabBarItems: [UITabBarItem] {
guard let viewControllers = tabBarController.viewControllers else { return [] }
return viewControllers.map { $0.tabBarItem }
}
lazy var inboxTabBarItem: UITabBarItem = tabBarItems.first { TabBarItemTag(rawValue: $0.tag) == .inbox }!
init(tabBarController: UITabBarController) {
self.tabBarController = tabBarController
sharedItemDatabaseObservation = Firebase.shared.observe(\.sharedItemDatabase, options: .initial) { [weak self] (firebase, change) in
self?.sharedItemDatabaseDidChange()
}
NotificationCenter.default.addObserver(self, selector: #selector(sharedItemDatabaseDidUpdateItems), name: .SharedItemDatabaseDidUpdateItems, object: nil)
}
func sharedItemDatabaseDidChange() {
if Firebase.shared.sharedItemDatabase == nil {
inboxTabBarItem.badgeValue = nil
}
}
@objc func sharedItemDatabaseDidUpdateItems(notification: Notification) {
guard let database = Firebase.shared.sharedItemDatabase else { return }
let unopenedCount = database.items.filter { !$0.hasBeenOpened }.count
inboxTabBarItem.badgeValue = (unopenedCount == 0) ? nil : "\(unopenedCount)"
}
}
|
//
// Node.swift
// json2model
//
// Created by lcl on 16/9/7.
// Copyright © 2016年 Vulpes. All rights reserved.
//
import Foundation
enum NodeType : String {
case ObjectNode = "Object"
case ArrayNode = "Array"
case StringNode = "String"
case NumberNode = "Number"
case BoolNode = "Bool"
case NullNode = "Null"
}
protocol Node {
var type : NodeType { get }
var subnodes : Array<Node>? { get }
var parentNode : Node? { get }
var originalData : AnyObject { get }
} |
//
// Skater.swift
// Skating Friends
//
// Created by Jake Oscar Te Lem on 6/11/18.
// Copyright © 2018 Jake Oscar Te Lem. All rights reserved.
//
import Foundation
import SpriteKit
class Mewna : Skater {
var spinPower: Double = 4
var spiralPower : Double = 3.5
var artistry: Double = 10
var reputation: Double = 10
var rotationSpeed: Double = 0.4
var size : Double = 280
var airTime : Double = 0.9
var jumpHeight : Double = 200
var control : Double = 0.7
var maxSpeed : Double = 2000
var sprite = SKSpriteNode(imageNamed: "Mewna_0")
var midair: SKAction!
var rotate : SKAction!
let skaterName = "Kim Mewna"
var upStep = SKAction(named:"MewnaSkating", duration: 0.45)!
var spiral = SKAction(named:"MewnaSpiral", duration: 1.5)!
var spiralEntrance = SKAction(named:"MewnaSpiralEntrance", duration: 0.2)!
var leftStep = SKAction(named:"MewnaSkating", duration: 0.45)!
var rightStep = SKAction(named:"MewnaSkating")!
var downStep = SKAction(named:"MewnaSkating")!
let skating = SKAction(named:"MewnaSkating")!
let backTurn = SKAction(named:"MewnaBackTurn", duration: 0.3)!
let lutzTakeoff = SKAction(named:"MewnaLutz", duration: 0.2)!
let flipTakeoff = SKAction(named:"MewnaLutz", duration: 0.2)!
let loopTakeoff = SKAction(named:"MewnaLoop", duration: 0.2)!
let toeTakeoff = SKAction(named:"MewnaToe", duration: 0.2)!
let salTakeoff = SKAction(named:"MewnaSal", duration: 0.2)!
let axelTakeoff = SKAction(named:"MewnaAxel", duration: 0.2)!
var spin = SKAction(named:"MewnaSpiral", duration: 1.5)!
var footDiv: Double = 2.7
let landing = SKAction(named:"MewnaLanding", duration: 0.5)!
let fall = SKAction(named:"MewnaFall", duration: 1)!
let bow = SKAction(named:"MewnaBow", duration: 2)!
let jumpTrans = SKAction(named:"MewnaRotate", duration: 0)!
required init () {
sprite.name = "Kim Mew-Na"
sprite.size = CGSize (width: size, height: size)
sprite.position = CGPoint(x: -200, y:-200 )
sprite.physicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "Mewna_0"), size: sprite.size)
sprite.physicsBody?.allowsRotation = false
sprite.physicsBody!.affectedByGravity = true
midair = SKAction(named:"MewnaMidair", duration: airTime)!
rotate = SKAction(named:"MewnaRotate", duration: rotationSpeed)!
}
func setSize(withSize: Double) {
size = withSize
sprite.size = CGSize (width: size, height: size)
}
func setRotationSpeed(withTime: Double) {
if withTime < 0.12 {
rotationSpeed = 0.12
} else {
rotationSpeed = withTime
}
rotate = SKAction(named:"MewnaRotate", duration: rotationSpeed)!
}
func setAirTime (withTime: Double) {
midair = SKAction(named:"MewnaMidair", duration: withTime)!
}
func setSpinTrans(spinType: Tech, stage: Int) {
switch spinType {
case .Layback:
switch stage {
case 0:
spin = SKAction(named:"MewnaSpinTrans0")!
print("0")
case 1:
spin = SKAction(named:"MewnaSpinTrans0")!
print("1")
case 2:
let trans = SKAction(named:"MewnaSpinTrans1", duration: 0.15)!
spin = trans
case 3:
spin = SKAction(named:"MewnaSpinTrans2", duration: 0.2)!
case 4:
spin = SKAction(named:"MewnaSpinTrans3", duration: 0.3)!
case 5:
spin = SKAction(named:"MewnaSpin4", duration: 0.3)!
default:
print("EXIt")
spin = SKAction(named:"MewnaSpinExit", duration: 0.3)!
}
case .ComboSpin:
break
default:
break
}
}
func setSpin(spinType: Tech, stage: Int) -> Bool {
switch spinType {
case .Layback:
switch stage {
case 1:
spin = SKAction.sequence([SKAction(named:"MewnaSpinTrans0", duration: 0.2)!, SKAction.repeatForever(SKAction(named:"MewnaSpin1", duration: 0.3)!)])
return false
case 2:
spin = SKAction.repeatForever(SKAction(named:"MewnaSpin2", duration: 0.3)!)
return false
case 3:
spin = SKAction.repeatForever(SKAction(named:"MewnaSpin3", duration: 0.3)!)
return false
case 4:
spin = SKAction.repeatForever(SKAction(named:"MewnaSpin4", duration: 0.3)!)
return false
default:
return true
}
case .ComboSpin:
break
default:
break
}
return true
}
func executeMove (withName: Move) {
switch withName {
case .lutzTakeoff:
sprite.run(SKAction.sequence([lutzTakeoff,midair]))
case .rotate :
sprite.run(SKAction(named:"CatokoRotate")!)
case .backTurn :
sprite.run(backTurn)
case .landing :
sprite.run(landing)
default:
sprite.run(SKAction(named:"CatokoSkating")!)
}
}
}
|
//
// NasaCollectionViewCell.swift
// CMoney
//
// Created by 黃仕杰 on 2021/7/24.
//
import UIKit
class NasaCollectionViewCell: UICollectionViewCell {
static let identifier = "cell"
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
func config(nasa: Nasa) {
imageView.isUserInteractionEnabled = false
titleLabel.isUserInteractionEnabled = false
titleLabel.text = nasa.title ?? ""
imageView.load(urlString: nasa.url ?? "")
}
}
|
//
// ElectricalDivisionsViewController.swift
// EFI
//
// Created by LUIS ENRIQUE MEDINA GALVAN on 8/9/18.
// Copyright © 2018 LUIS ENRIQUE MEDINA GALVAN. All rights reserved.
//
import Foundation
import AsyncDisplayKit
class ElectricalDivisionsViewController:ASViewController<ASTableNode> {
var tableNode:ASTableNode!
var dataManager:ElectricalDivisionDataManager!
weak var delegate:RateSelectionDelegate!
var state:State!
var county:County!
weak var networkService:CCTApiService!
init(delegate:RateSelectionDelegate,state:State,county:County,networkService:CCTApiService,data:[ElectricalDivision]) {
self.delegate = delegate
self.state = state
self.county = county
self.networkService = networkService
tableNode = ASTableNode()
super.init(node: tableNode)
dataManager = ElectricalDivisionDataManager(tableNode: tableNode,delegate: self, data: data)
tableNode.dataSource = dataManager
tableNode.delegate = dataManager
fetchData()
}
func fetchData(){
networkService.fetchElectricalDivision(by: state, county: county) { [weak self] (divisions, responseError) in
if let error = responseError {
print(error)
} else {
self?.dataManager.electricalDivisions = divisions!
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableNode.backgroundColor = .white
tableNode.view.separatorStyle = .singleLine
title = "Divisiones Electricas"
let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancel))
navigationItem.setRightBarButton(cancelButton, animated: true)
}
@objc func cancel(){
dismiss(animated: true, completion: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension ElectricalDivisionsViewController: ElectricalDivisionDelegate {
func continueWithSelected(electricalDivision: ElectricalDivision) {
let loadingView = UIView(frame: UIScreen.main.bounds)
let window = UIApplication.shared.keyWindow
loadingView.backgroundColor = .black
loadingView.alpha = 0
window?.addSubview(loadingView)
UIWindow.animate(withDuration: 0.5) {
loadingView.alpha = 0.7
}
networkService.fetchCRERates { [weak self] (rates, error) in
if error != nil {
return
}
var requestParameters = RateForLocationRequestParameters()
requestParameters.ClaveEstado = self?.state.Clave
requestParameters.ClaveMunicipio = self?.county.Clave
requestParameters.ClaveDivisionElectrica = electricalDivision.Clave
let vc = CRERatesViewController(delegate: (self?.delegate)!, networkService: (self?.networkService)!, data: rates!,requestParameter:requestParameters)
self?.navigationController?.pushViewController(vc, animated: true)
UIWindow.animate(withDuration: 0.5) {
loadingView.alpha = 0
}
}
}
}
|
//
// WFTitleButton.swift
// niinfor
//
// Created by 王孝飞 on 2018/9/21.
// Copyright © 2018年 孝飞. All rights reserved.
//
import UIKit
class WFTitleButton: UIButton {
init() {
super.init(frame: CGRect())
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
guard let titleLabel = titleLabel, let imageView = imageView else {
return
}
imageView.frame = CGRect.init(x: (bounds.width - imageView.frame.width) / 2.0, y: (bounds.height - imageView.bounds.height - titleLabel.bounds.height - 8) / 2, width: imageView.frame.width, height: imageView.bounds.height)
titleLabel.frame = CGRect.init(x: (bounds.width - titleLabel.frame.width) / 2.0, y: imageView.frame.origin.y + imageView.bounds.height + 8, width: titleLabel.frame.width, height: titleLabel.bounds.height)
//titleLabel.frame.offsetBy(dx: -titleLabel.bounds.width/2, dy: titleLabel.bounds.height/2 )
//imageView.frame.offsetBy(dx: imageView.bounds.width/2, dy: -imageView.bounds.height/2 )
}
}
|
//
// ProfileViewController.swift
// FindOrOfferAJobApp
//
// Created by Haroldo on 19/02/20.
// Copyright © 2020 HaroldoLeite. All rights reserved.
//
import UIKit
import GoogleSignIn
class ProfileViewController: UIViewController {
enum ProfileItems: String, CaseIterable {
case UserResumeCard
case EditPersonalData = "Dados Pessoais"
// case EditProfessionalData = "Dados Profissionais"
case Settings = "Configurações"
case Logout = "Sair"
}
// MARK: - IBOutlets
@IBOutlet weak var tableView: UITableView! {
didSet {
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.register(UserResumeTableViewCell.self, forCellReuseIdentifier: String(describing: UserResumeTableViewCell.self))
self.tableView.register(UINib(nibName: String(describing: UserResumeTableViewCell.self), bundle: nil), forCellReuseIdentifier: String(describing: UserResumeTableViewCell.self))
self.tableView.register(SettingsTableViewCell.self, forCellReuseIdentifier: String(describing: SettingsTableViewCell.self))
self.tableView.register(UINib(nibName: String(describing: SettingsTableViewCell.self), bundle: nil), forCellReuseIdentifier: String(describing: SettingsTableViewCell.self))
self.tableView.separatorStyle = .none
}
}
// MARK: - Variables
var userProfileViewModel = UserProfileViewModel()
var userProfile: UserProfile = UserProfile()
// MARK: - Lifecycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.topItem?.title = String.localize("profile_nav_bar")
self.userProfileViewModel = UserProfileViewModel()
}
private func loadUserProfileValues() {
let userViewModel = self.userProfileViewModel
self.userProfile = UserProfile(userId: userViewModel.userId, firstName: userViewModel.firstName, lastName: userViewModel.lastName, email: userViewModel.email, cellphone: userViewModel.cellphone, phone: userViewModel.phone, birthDate: userViewModel.birthDate, accountType: userViewModel.accountType, userImageURL: userViewModel.userImageURL, userImageData: userViewModel.userImageData, professionalCards: [])
}
// MARK: - Methods
func logoutUser() {
switch self.userProfileViewModel.accountType {
case .DefaultAccount:
FirebaseAuthManager().signOut { [weak self] (success) in
if success {
PreferencesManager.sharedInstance().deleteUserProfile()
self?.navigationController?.popToRootViewController(animated: true)
} else {
print("Error Logout")
}
}
case .GoogleAccount:
GIDSignIn.sharedInstance()?.signOut()
PreferencesManager.sharedInstance().deleteUserProfile()
self.navigationController?.popToRootViewController(animated: true)
}
}
}
extension ProfileViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0 {
return 150
} else {
return 70
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.userProfileViewModel.profileOptions.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: UserResumeTableViewCell.self), for: indexPath) as? UserResumeTableViewCell else {
fatalError("UserResumeTableViewCell not found!")
}
if let dataImage = self.userProfileViewModel.userImageData {
cell.userImageView.image = UIImage(data: dataImage)
}
cell.selectionStyle = .none
return cell
} else {
guard let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: SettingsTableViewCell.self), for: indexPath) as? SettingsTableViewCell else {
fatalError("SettingsTableViewCell not found!")
}
let settingsItem = self.userProfileViewModel.profileOptions[indexPath.row]
switch settingsItem {
case .UserResumeCard:
break
case .EditPersonalData:
cell.nameLabel.text = ProfileViewController.ProfileItems.EditPersonalData.rawValue
cell.imageView?.image = ImageConstants.Profile
case .Settings:
cell.nameLabel.text = ProfileViewController.ProfileItems.Settings.rawValue
cell.imageView?.image = ImageConstants.Settings
case .Logout:
cell.nameLabel.text = ProfileViewController.ProfileItems.Logout.rawValue
cell.imageView?.image = ImageConstants.Logout
}
cell.selectionStyle = .none
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let profileItem = self.userProfileViewModel.profileOptions[indexPath.row]
switch profileItem {
case .UserResumeCard:
break
case .EditPersonalData:
self.performSegue(withIdentifier: "EditPersonalDataViewController", sender: nil)
case .Settings:
self.performSegue(withIdentifier: "SettingsViewController", sender: nil)
case .Logout:
self.logoutUser()
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let settingsViewController = segue.destination as? SettingsViewController {
settingsViewController.userProfileViewModel = self.userProfileViewModel
}
if let editPersonalDataViewController = segue.destination as? EditPersonalDataViewController {
editPersonalDataViewController.userProfileViewModel = self.userProfileViewModel
}
}
}
|
//
// BinaryMap.swift
// TestingOMaps
//
// Created by Ethan Zhang on 11/12/18.
// Copyright © 2018 NepinNep. All rights reserved.
//
import Foundation
class BinaryMap<K: Comparable, V>: FakeMap<K, V>{
var keys = [K]()
var values = [V]()
override func set(_ k: K, v: V){
var index = 0
if count == 0{
keys.append(k)
values.append(v)
count += 1
return
}
if let index = findKeyIndex(k){
values[index] = v
return
}
for key in keys{
if k > key{
index += 1
} else {
keys.insert(k, at: index)
values.insert(v, at: index)
count += 1
return
}
if index == keys.count{
keys.insert(k, at: index)
values.insert(v, at: index)
count += 1
}
}
}
override func remove(_ k: K){
let keyIndex = findKeyIndex(k)
if keyIndex == nil{
print("Could not find \(k)")
return
}
keys.remove(at: keyIndex!)
values.remove(at: keyIndex!)
count -= 1
}
override func get(_ k: K)-> V?{
let index = findKeyIndex(k)
if index == nil{
return(nil)
} else {
return(values[index!])
}
}
func findKeyIndex(_ k: K)-> Int?{
return(binarySearch(keys, key: k, range: 0..<keys.count))
}
override subscript(index: K) -> V? {
get {
return(get(index))
}
set(newValue) {
set(index, v: newValue!)
}
}
func binarySearch(_ a: [K], key: K, range: Range<Int>) -> Int? {
if range.lowerBound >= range.upperBound {
// If we get here, then the search key is not present in the array.
return nil
} else {
// Calculate where to split the array.
let midIndex = range.lowerBound + (range.upperBound - range.lowerBound) / 2
// Is the search key in the left half?
if a[midIndex] > key {
return binarySearch(a, key: key, range: range.lowerBound ..< midIndex)
// Is the search key in the right half?
} else if a[midIndex] < key {
return binarySearch(a, key: key, range: midIndex + 1 ..< range.upperBound)
// If we get here, then we've found the search key!
} else {
return midIndex
}
}
}
override var description: String{
var desc = "["
for n in 0..<keys.count{
desc += "\(keys[n]): \(values[n]), "
}
if desc.count != 1{
desc = String(desc.dropLast(2))
}
return desc + "]"
}
}
|
//
// ListEntry.swift
// TODOList
//
// Created by Artem Evdokimov on 05.11.2020.
//
import SwiftUI
struct ListEntry: View {
var entry: ListObject
@EnvironmentObject var model: ListModel
@Environment(\.editMode) var editMode
var bgColor: String;
var body: some View {
GeometryReader { geometry in
HStack {
Text(entry.title)
.foregroundColor(.black)
.frame(width: geometry.size.width, height: geometry.size.width)
.background(
RoundedRectangle(cornerRadius: 20, style: .continuous).fill(Color(hex: bgColor))
)
Spacer()
}
}
}
}
|
//
// Data.swift
// LinEqua
//
// Created by Miroslav Milivojevic on 7/5/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import LinEqua
class Data: NSObject {
static let shared = Data()
var matrix: Matrix? {
if insertedMatrix != nil {
return insertedMatrix
}
return generatedMatrix
}
var generatedMatrix: Matrix?
var insertedMatrix: Matrix?
var resultsGauss: [Double]? = []
var resultsGaussJordan: [Double]? = []
private override init() {}
func calculateGausError() -> Double {
guard let resultsGauss = resultsGauss else { return 0.0 }
let gaussResultsVector = Vector(withArray: resultsGauss)
guard let matrix = generatedMatrix else {return 0.0}
var sumGausErrors = 0.0
for row in matrix.elements {
let rowVector = Vector(withArray: row)
let result = rowVector.popLast()
sumGausErrors += result! - (rowVector * gaussResultsVector).sum()
}
let rv = sumGausErrors / Double(gaussResultsVector.count)
print("Gauss error: \(rv)")
return abs(rv)
}
func calculateGausJordanError() -> Double {
guard let resultsGauss = resultsGaussJordan else { return 0.0 }
let gaussJordanResultsVector = Vector(withArray: resultsGauss)
guard let matrix = generatedMatrix else {return 0.0}
var sumGausJordanErrors = 0.0
for row in matrix.elements {
let rowVector = Vector(withArray: row)
let result = rowVector.popLast()
sumGausJordanErrors += result! - (rowVector * gaussJordanResultsVector).sum()
}
let rv = sumGausJordanErrors / Double(gaussJordanResultsVector.count)
print("Gauss Jordan error: \(rv)")
return abs(rv)
}
}
|
//
// HotViewModel.swift
// inke
//
// Created by bb on 2017/8/3.
// Copyright © 2017年 bb. All rights reserved.
//
import UIKit
class HotViewModel {
lazy var live_NodesModel: Live_NodesModel = Live_NodesModel()
lazy var liveArray: [LiveModel] = [LiveModel]()
lazy var cycleModelArray: [CycleModel] = [CycleModel]()
}
extension HotViewModel {
func loadData(finishedCallback: @escaping ()->()) {
let dGroup: DispatchGroup = DispatchGroup()
// MARK: 第一组
// http://116.211.167.106/api/live/theme_guide?keyword=REMENABC&cv=IK4.0.90_Iphone
let liveNodelUrlString = "http://116.211.167.106/api/live/theme_guide"
let liveNodelParam = ["keyword": "REMENABC", "cv": "IK4.0.90_Iphone"]
// 进入组
dGroup.enter()
NetworkTools.requestData(type: .GET, URLString: liveNodelUrlString, parameters: liveNodelParam) { (result) in
guard let resultDict = result as? [String: NSObject] else { return }
self.live_NodesModel = Live_NodesModel(dict: resultDict)
// 离开组
dGroup.leave()
}
// MARK: 第二组
// http://116.211.167.106/api/live/simpleall?cv=IK4.0.90_Iphone
let liveUrlString = "http://116.211.167.106/api/live/simpleall"
let liveParam = ["cv": "IK4.0.90_Iphone"]
// 进入组
dGroup.enter()
NetworkTools.requestData(type: .GET, URLString: liveUrlString, parameters: liveParam) { (result) in
guard let resultDict = result as? [String: NSObject] else { return }
guard let dataArray = resultDict["lives"] as? [[String : NSObject]] else { return }
for dict in dataArray {
self.liveArray.append(LiveModel(dict: dict))
}
// 离开组
dGroup.leave()
}
// MARK: 第三组
let cycleUrlString = "http://120.55.238.158/api/live/ticker"
let cycleParam = ["cv": "IK4.0.90_Iphone"]
// 进入组
dGroup.enter()
NetworkTools.requestData(type: .GET, URLString: cycleUrlString, parameters: cycleParam) { (result) in
guard let resultDict = result as? [String: NSObject] else { return }
guard let dataArray = resultDict["ticker"] as? [[String : NSObject]] else {
print("轮播数据-请求失败")
// 离开组
dGroup.leave()
return
}
for dict in dataArray {
self.cycleModelArray.append(CycleModel(dict: dict))
}
// 离开组
dGroup.leave()
}
dGroup.notify(queue: DispatchQueue.main) {
print("热门-所有数据接收完成")
finishedCallback()
}
}
}
|
//
// GameViewController.swift
// XO-game
//
// Created by Evgeny Kireev on 25/02/2019.
// Copyright © 2019 plasmon. All rights reserved.
//
import UIKit
class GameViewController: UIViewController {
@IBOutlet var gameboardView: GameboardView!
@IBOutlet var firstPlayerTurnLabel: UILabel!
@IBOutlet var secondPlayerTurnLabel: UILabel!
@IBOutlet var winnerLabel: UILabel!
@IBOutlet var restartButton: UIButton!
@IBOutlet weak var gameModeLabel: UILabel!
private lazy var referee = Referee(gameboard: self.gameboard)
// Если что-то пойдет не так по-умолчанию режим игры pvp
public var gameMode: GameMode = .pvp
private let gameboard = Gameboard()
// Максимальное число ходов на игрока в режиме по очереди
let maxMovePerPlayerQue = 5
private var currentState: GameState! {
didSet {
if let currentState = self.currentState {
currentState.begin()
}
}
}
private let moveInvoker = MoveInvoker.shared
override func viewDidLoad() {
super.viewDidLoad()
self.goToFirstState()
// Навигационная строка не нужна, будем возвращать в главное меню кнопкой
navigationController?.navigationBar.isHidden = true
// Выставляем название текущего режима
switch gameMode {
case .pvc:
gameModeLabel.text = "PvC"
case .que:
gameModeLabel.text = "Queue"
default:
gameModeLabel.text = "PvP"
}
// Обрабатываем нажатие на поле
gameboardView.onSelectPosition = { [weak self] position in
guard let self = self else { return }
// Если режим que и количество команд равно 6, выполним их всех
if let position = position {
let maxCommandToPerform = ((self.maxMovePerPlayerQue * 2) - 1)
if (self.gameMode == .que && self.moveInvoker.commands.count == maxCommandToPerform) {
self.currentState.addMark(at: position)
self.moveInvoker.perform()
}
} else {
// Закончим ход
self.currentState.complete()
}
if let winner = self.referee.determineWinner() {
self.currentState = GameEndedState(winner: winner, gameViewController: self)
return
}
if let position = position {
self.currentState.addMark(at: position)
}
if self.currentState.isCompleted {
self.goToNextState()
}
}
}
@IBAction func goToMainMenu(_ sender: Any) {
navigationController?.popToRootViewController(animated: true)
}
// Данная функция просто логическая, т.е. она запускается только один раз
// в первый, когда currentState - nil, т.е. игра только началась
private func goToFirstState() {
// Текущий стейт должен быть пустым
currentState = nil
goToNextState()
}
private func goToNextState() {
var player: Player
if let currentState = self.currentState,
let nextPlayer = currentState.getNextPlayer()
{
player = nextPlayer
} else {
player = .first
}
// В зависимости от выбранного режима стартуем тот или иной стэйт
if gameMode == .pvp {
self.currentState = PlayerInputState(player: player,
gameViewController: self,
gameboard: gameboard,
gameboardView: gameboardView,
markViewPrototype: player.markViewPrototype)
} else if gameMode == .que {
self.currentState = QueueInputState(player: player,
gameViewController: self,
gameboard: gameboard,
gameboardView: gameboardView,
markViewPrototype: player.markViewPrototype, maxMovePerPlayer: maxMovePerPlayerQue)
} else {
self.currentState = ComputerInputState(player: player,
gameViewController: self,
gameboard: gameboard,
gameboardView: gameboardView,
markViewPrototype: player.markViewPrototype)
}
}
@IBAction func restartButtonTapped(_ sender: UIButton) {
gameboardView.clear()
gameboard.clear()
moveInvoker.reset()
goToFirstState()
LogAction.log(.restartGame)
}
}
|
struct Album: Decodable, Equatable {
let id: Int
let title: String
let coverMedium: String
let coverXl: String
}
|
//
// ViewController.swift
// Reddit
//
// Created by Jordan Dumlao on 12/17/18.
// Copyright © 2018 Jordan Dumlao. All rights reserved.
//
import UIKit
class RedditViewController: UIViewController {
let mainDataSource = MainDataSource()
let menuDataSource = MenuDataSource()
@IBOutlet weak var menuBarView: UIView!
var phoneWidth: CGFloat?
@IBOutlet weak var menuCollectionView: UICollectionView!
@IBOutlet weak var mainCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
phoneWidth = view.frame.width
if let menuCollectionView = menuCollectionView { configure(menuCollectionView, with: menuDataSource) }
if let mainCollectionView = mainCollectionView { configure(mainCollectionView, with: mainDataSource) }
menuCollectionView.selectItem(at: [0, 0], animated: true, scrollPosition: .centeredHorizontally)
}
func configure(_ collectionView: UICollectionView, with dataSource: UICollectionViewDataSource) {
collectionView.dataSource = dataSource
collectionView.delegate = self
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
}
}
}
extension RedditViewController: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = phoneWidth ?? 00
switch collectionView {
case mainCollectionView:
let height = mainCollectionView.frame.height
return CGSize(width: width, height: height)
case menuCollectionView:
return CGSize(width: width / 3, height: menuCollectionView?.frame.height ?? 0)
default: return CGSize.zero
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == menuCollectionView {
let x = (collectionView.frame.width / 3) * CGFloat(indexPath.item)
UIView.animate(withDuration: 0.2, animations: { [weak self] in
guard let self = self else { return }
self.menuBarView?.transform = CGAffineTransform(translationX: x, y: 0)
})
mainCollectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let xOffset = scrollView.contentOffset.x
menuBarView.transform = CGAffineTransform(translationX: xOffset / 3, y: 0)
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let x = targetContentOffset.pointee.x
let item = x / view.frame.width
let indexPath = IndexPath(item: Int(item), section: 0)
menuCollectionView?.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
}
}
|
//
// MusicTheoryTests.swift
// MusicTheoryTests
//
// Created by Cem Olcay on 30/12/2016.
// Copyright © 2016 prototapp. All rights reserved.
//
import MusicTheory
import XCTest
class MusicTheoryTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
}
// MARK: - Note Tests
extension MusicTheoryTests {
func testIntervals() {
let key = Key(type: .c)
let pitch = Pitch(key: key, octave: 1)
XCTAssert((pitch + 12).octave == pitch.octave + 1)
XCTAssert((pitch + 1).key == Key(type: .c, accidental: .sharp))
XCTAssert((pitch - 1) == Pitch(key: Key(type: .b), octave: 0))
let c1 = Pitch(key: Key(type: .c), octave: 1)
let d1 = Pitch(key: Key(type: .d), octave: 1)
XCTAssert(d1 - c1 == .M2)
}
func testAccidentals() {
XCTAssert(Accidental.flat * 2 == Accidental.doubleFlat)
XCTAssert(Accidental.doubleFlat / 2 == Accidental.flat)
XCTAssert(Accidental.sharps(amount: 2) - 2 == Accidental.natural)
XCTAssert(Accidental.flats(amount: 2) + 2 == 0)
XCTAssert(Accidental.sharps(amount: 2) + Accidental.sharps(amount: 1) == Accidental.sharps(amount: 3))
XCTAssert(Accidental(integerLiteral: -3) + Accidental(rawValue: 3)! == 0)
}
func testKeys() {
let d = Key.KeyType.d
XCTAssert(d.key(at: -2) == .b)
XCTAssert(d.key(at: -19) == .f)
XCTAssert(d.key(at: 12) == .b)
XCTAssert(d.key(at: 0) == .d)
XCTAssert(d.key(at: 1) == .e)
XCTAssert(d.key(at: 2) == .f)
XCTAssert(d.key(at: -3) == .a)
XCTAssert(d.key(at: -301) == .d)
let f = Key.KeyType.f
XCTAssert(f.key(at: -3) == .c)
let k: Key = "a##b"
XCTAssert(k.accidental == .sharp && k.type == .a)
let b = Key(type: .b, accidental: .natural)
XCTAssert(Key(type: .c, accidental: .flat) == b)
XCTAssert(Key(type: .c, accidental: .sharps(amount: 23)) == b)
XCTAssert(Key(type: .c, accidental: .flats(amount: 13)) == b)
XCTAssert(Key(type: .c, accidental: .flats(amount: 25)) == b)
XCTAssert(Key(type: .c, accidental: .flats(amount: 24)) != b)
}
func testPitches() {
let c0: Pitch = 12
XCTAssert(c0.octave == 0 && c0.key.accidental == .natural && c0.key.type == .c)
XCTAssert(c0 - 12 == 0)
var pitch = Pitch(midiNote: 127)
XCTAssert(pitch.key == Key(type: .g))
pitch = Pitch(midiNote: 0)
XCTAssert(pitch.key == Key(type: .c))
pitch = Pitch(midiNote: 66, preferSharps: false)
XCTAssert(pitch.key == Key(type: .g, accidental: .flat))
let c1 = Pitch(key: Key(type: .c), octave: 1)
XCTAssert(c1 + .m2 == Pitch(key: Key(type: .d, accidental: .flat), octave: 1))
XCTAssert(c1 + .M2 == Pitch(key: Key(type: .d, accidental: .natural), octave: 1))
XCTAssert(c1 + .m3 == Pitch(key: Key(type: .e, accidental: .flat), octave: 1))
XCTAssert(c1 + .M3 == Pitch(key: Key(type: .e, accidental: .natural), octave: 1))
XCTAssert(c1 + .P8 == Pitch(key: Key(type: .c, accidental: .natural), octave: 2))
let d1 = Pitch(key: Key(type: .d), octave: 1)
XCTAssert(d1 - .m2 == Pitch(key: Key(type: .c, accidental: .sharp), octave: 1))
XCTAssert(d1 - .M2 == Pitch(key: Key(type: .c, accidental: .natural), octave: 1))
let p: Pitch = "f#-5"
XCTAssert(p.key === Key(type: .f, accidental: .sharp))
XCTAssert(p.octave == -5)
let uppercasePitch: Pitch = "A#3"
XCTAssert(uppercasePitch.key === Key(type: .a, accidental: .sharp))
XCTAssert(uppercasePitch.octave == 3)
let uppercasePitch2: Pitch = "F4"
XCTAssert(uppercasePitch2.key === Key(type: .f, accidental: .natural))
XCTAssert(uppercasePitch2.octave == 4)
}
func testFrequency() {
let note = Pitch(key: Key(type: .a), octave: 4)
XCTAssertEqual(note.frequency, 440.0)
let a4 = Pitch.nearest(frequency: 440.0)
XCTAssertEqual(note, a4)
}
}
// MARK: - Tempo Tests
extension MusicTheoryTests {
func testNoteValueConversions() {
let noteValue = NoteValue(type: .half, modifier: .dotted)
XCTAssertEqual(noteValue / NoteValueType.sixteenth, 12)
XCTAssertEqual(noteValue / NoteValueType.whole, 0.75)
}
func testDurations() {
let timeSignature = TimeSignature(beats: 4, noteValue: .quarter) // 4/4
let tempo = Tempo(timeSignature: timeSignature, bpm: 120) // 120BPM
var noteValue = NoteValue(type: .quarter)
var duration = tempo.duration(of: noteValue)
XCTAssert(duration == 0.5)
noteValue.modifier = .dotted
duration = tempo.duration(of: noteValue)
XCTAssert(duration == 0.75)
}
func testSampleLengthCalcuation() {
let rates = [
NoteValue(type: .whole, modifier: .default),
NoteValue(type: .half, modifier: .default),
NoteValue(type: .half, modifier: .dotted),
NoteValue(type: .half, modifier: .triplet),
NoteValue(type: .quarter, modifier: .default),
NoteValue(type: .quarter, modifier: .dotted),
NoteValue(type: .quarter, modifier: .triplet),
NoteValue(type: .eighth, modifier: .default),
NoteValue(type: .eighth, modifier: .dotted),
NoteValue(type: .sixteenth, modifier: .default),
NoteValue(type: .sixteenth, modifier: .dotted),
NoteValue(type: .thirtysecond, modifier: .default),
NoteValue(type: .sixtyfourth, modifier: .default),
]
let tempo = Tempo()
let sampleLengths = rates
.map({ tempo.sampleLength(of: $0) })
.map({ round(100 * $0) / 100 })
let expected: [Double] = [
88200.0,
44100.0,
66150.0,
29401.47,
22050.0,
33075.0,
14700.73,
11025.0,
16537.5,
5512.5,
8268.75,
2756.25,
1378.13,
]
XCTAssertEqual(sampleLengths, expected)
}
func testTempoHashable() {
let t1 = Tempo(timeSignature: TimeSignature(beats: 1, noteValue: .whole), bpm: 1)
var t2 = Tempo(timeSignature: TimeSignature(beats: 2, noteValue: .half), bpm: 2)
XCTAssertNotEqual(t1.timeSignature.noteValue, t2.timeSignature.noteValue)
XCTAssertNotEqual(t1.timeSignature, t2.timeSignature)
XCTAssertNotEqual(t1, t2)
t2.timeSignature = TimeSignature(beats: 1, noteValue: .whole)
t2.bpm = 1
XCTAssertEqual(t1.timeSignature.noteValue, t2.timeSignature.noteValue)
XCTAssertEqual(t1.timeSignature, t2.timeSignature)
XCTAssertEqual(t1, t2)
}
}
// MARK: - Scale Tests
extension MusicTheoryTests {
func testScale() {
let cMaj: [Key] = [
Key(type: .c),
Key(type: .d),
Key(type: .e),
Key(type: .f),
Key(type: .g),
Key(type: .a),
Key(type: .b),
]
let cMajScale = Scale(type: .major, key: Key(type: .c))
XCTAssert(cMajScale.keys == cMaj)
let cMin: [Key] = [
Key(type: .c),
Key(type: .d),
Key(type: .e, accidental: .flat),
Key(type: .f),
Key(type: .g),
Key(type: .a, accidental: .flat),
Key(type: .b, accidental: .flat),
]
let cMinScale = Scale(type: .minor, key: Key(type: .c))
XCTAssert(cMinScale.keys == cMin)
}
func testHarmonicFields() {
let cmaj = Scale(type: .major, key: Key(type: .c))
let triads = cmaj.harmonicField(for: .triad)
let triadsExpected = [
Chord(type: ChordType(third: .major), key: Key(type: .c)),
Chord(type: ChordType(third: .minor), key: Key(type: .d)),
Chord(type: ChordType(third: .minor), key: Key(type: .e)),
Chord(type: ChordType(third: .major), key: Key(type: .f)),
Chord(type: ChordType(third: .major), key: Key(type: .g)),
Chord(type: ChordType(third: .minor), key: Key(type: .a)),
Chord(type: ChordType(third: .minor, fifth: .diminished), key: Key(type: .b)),
]
XCTAssert(triads.enumerated().map({ $1 == triadsExpected[$0] }).filter({ $0 == false }).count == 0)
}
}
// MARK: - Chord Tests
extension MusicTheoryTests {
func testChords() {
let cmajNotes: [Key] = [Key(type: .c), Key(type: .e), Key(type: .g)]
let cmaj = Chord(type: ChordType(third: .major), key: Key(type: .c))
XCTAssert(cmajNotes == cmaj.keys)
let cminNotes: [Key] = [
Key(type: .c),
Key(type: .e, accidental: .flat),
Key(type: .g),
]
let cmin = Chord(type: ChordType(third: .minor), key: Key(type: .c))
XCTAssert(cminNotes == cmin.keys)
let c13Notes: [Pitch] = [
Pitch(key: Key(type: .c), octave: 1),
Pitch(key: Key(type: .e), octave: 1),
Pitch(key: Key(type: .g), octave: 1),
Pitch(key: Key(type: .b, accidental: .flat), octave: 1),
Pitch(key: Key(type: .d), octave: 2),
Pitch(key: Key(type: .f), octave: 2),
Pitch(key: Key(type: .a), octave: 2),
]
let c13 = Chord(
type: ChordType(
third: .major,
seventh: .dominant,
extensions: [
ChordExtensionType(type: .thirteenth),
]
),
key: Key(type: .c)
)
XCTAssert(c13.pitches(octave: 1) === c13Notes)
let cm13Notes: [Pitch] = [
Pitch(key: Key(type: .c), octave: 1),
Pitch(key: Key(type: .e, accidental: .flat), octave: 1),
Pitch(key: Key(type: .g), octave: 1),
Pitch(key: Key(type: .b, accidental: .flat), octave: 1),
Pitch(key: Key(type: .d), octave: 2),
Pitch(key: Key(type: .f), octave: 2),
Pitch(key: Key(type: .a), octave: 2),
]
let cm13 = Chord(
type: ChordType(
third: .minor,
seventh: .dominant,
extensions: [
ChordExtensionType(type: .thirteenth),
]
),
key: Key(type: .c)
)
XCTAssert(cm13.pitches(octave: 1) === cm13Notes)
let minorIntervals: [Interval] = [.P1, .m3, .P5]
guard let minorChord = ChordType(intervals: minorIntervals.map({ $0 })) else { return XCTFail() }
XCTAssert(minorChord == ChordType(third: .minor))
let majorIntervals: [Interval] = [.P1, .M3, .P5]
guard let majorChord = ChordType(intervals: majorIntervals.map({ $0 })) else { return XCTFail() }
XCTAssert(majorChord == ChordType(third: .major))
let cmadd13Notes: [Pitch] = [
Pitch(key: Key(type: .c), octave: 1),
Pitch(key: Key(type: .e, accidental: .flat), octave: 1),
Pitch(key: Key(type: .g), octave: 1),
Pitch(key: Key(type: .a), octave: 2),
]
let cmadd13 = Chord(
type: ChordType(
third: .minor,
extensions: [ChordExtensionType(type: .thirteenth)]
),
key: Key(type: .c)
)
XCTAssert(cmadd13.pitches(octave: 1) === cmadd13Notes)
}
func testRomanNumerics() {
let cmaj = Scale(type: .major, key: Key(type: .c))
let cmin = Scale(type: .minor, key: Key(type: .c))
let cmajNumerics = ["I", "ii", "iii", "IV", "V", "vi", "vii°"]
let cminNumerics = ["i", "ii°", "III", "iv", "v", "VI", "VII"]
let cmajChords = cmaj.harmonicField(for: .triad)
let cminChords = cmin.harmonicField(for: .triad)
XCTAssertEqual(cmajNumerics, cmajChords.compactMap({ $0?.romanNumeric(for: cmaj) }))
XCTAssertEqual(cminNumerics, cminChords.compactMap({ $0?.romanNumeric(for: cmin) }))
}
func testInversions() {
let c7 = Chord(
type: ChordType(third: .major, seventh: .dominant),
key: Key(type: .c)
)
let c7Inversions = [
[
Pitch(key: Key(type: .c), octave: 1),
Pitch(key: Key(type: .e), octave: 1),
Pitch(key: Key(type: .g), octave: 1),
Pitch(key: Key(type: .b, accidental: .flat), octave: 1),
],
[
Pitch(key: Key(type: .e), octave: 1),
Pitch(key: Key(type: .g), octave: 1),
Pitch(key: Key(type: .b, accidental: .flat), octave: 1),
Pitch(key: Key(type: .c), octave: 2),
],
[
Pitch(key: Key(type: .g), octave: 1),
Pitch(key: Key(type: .b, accidental: .flat), octave: 1),
Pitch(key: Key(type: .c), octave: 2),
Pitch(key: Key(type: .e), octave: 2),
],
[
Pitch(key: Key(type: .b, accidental: .flat), octave: 1),
Pitch(key: Key(type: .c), octave: 2),
Pitch(key: Key(type: .e), octave: 2),
Pitch(key: Key(type: .g), octave: 2),
],
]
for (index, chord) in c7.inversions.enumerated() {
XCTAssert(chord.pitches(octave: 1) === c7Inversions[index])
}
}
}
// MARK: - [Pitch] Extension
// A function for checking pitche arrays exactly equal in terms of their pitches keys and octaves.
func === (lhs: [Pitch], rhs: [Pitch]) -> Bool {
guard lhs.count == rhs.count else { return false }
for i in 0 ..< lhs.count {
if lhs[i] === rhs[i] {
continue
} else {
return false
}
}
return true
}
|
//
// ZMobileKeyInput.swift
// Seriously
//
// Created by Jonathan Sand on 4/28/19.
// Copyright © 2019 Jonathan Sand. All rights reserved.
//
import UIKit
class ZMobileKeyInput : UIControl, UIKeyInput {
var hasText = false
override var canBecomeFirstResponder: Bool {return true}
func deleteBackward() {}
public func insertText(_ text: String) {
gMapEditor.handleKey(text, flags: ZEventFlags(), isWindow: true)
}
}
|
//
// ProjectsTableViewController.swift
// Schematic Capture
//
// Created by Gi Pyo Kim on 2/7/20.
// Copyright © 2020 GIPGIP Studio. All rights reserved.
//
import UIKit
import CoreData
class ProjectsTableViewController: UITableViewController {
var loginController: LogInController?
var projectController: ProjectController?
lazy var fetchedResultsController: NSFetchedResultsController<Project> = {
let fetchRequest: NSFetchRequest<Project> = Project.fetchRequest()
fetchRequest.sortDescriptors = [ NSSortDescriptor(key: "clientId", ascending: true),
NSSortDescriptor(key: "name", ascending: true)]
let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: CoreDataStack.shared.mainContext, sectionNameKeyPath: "clientId", cacheName: nil)
frc.delegate = self
do {
try frc.performFetch() // Fetch the tasks
} catch {
fatalError("Error performing fetch for frc: \(error)")
}
return frc
}()
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return fetchedResultsController.sections?.count ?? 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return fetchedResultsController.sections?[section].numberOfObjects ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ProjectCell", for: indexPath) as? ProjectTableViewCell else { return UITableViewCell() }
cell.project = fetchedResultsController.object(at: indexPath)
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "JobSheetSegue" {
if let jobSheetsTVC = segue.destination as? JobSheetsTableViewController,
let indexPath = tableView.indexPathForSelectedRow {
guard let jobSheetsSet = fetchedResultsController.object(at: indexPath).jobSheets,
let jobSheets = jobSheetsSet.sortedArray(using: [NSSortDescriptor(key: "id", ascending: true)]) as? [JobSheet] else {
print("No jobsheets found in \(fetchedResultsController.object(at: indexPath))")
return
}
jobSheetsTVC.jobSheets = jobSheets
}
}
}
}
extension ProjectsTableViewController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
guard let newIndexPath = newIndexPath else { return }
tableView.insertRows(at: [newIndexPath], with: .automatic)
case .delete:
guard let indexPath = indexPath else { return }
tableView.deleteRows(at: [indexPath], with: .automatic)
case .move:
guard let indexPath = indexPath, let newIndexPath = newIndexPath else { return }
tableView.moveRow(at: indexPath, to: newIndexPath)
case .update:
guard let indexPath = indexPath else { return }
tableView.reloadRows(at: [indexPath], with: .automatic)
@unknown default:
fatalError()
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
let indexSet = IndexSet(integer: sectionIndex)
switch type {
case .insert:
tableView.insertSections(indexSet, with: .automatic)
case .delete:
tableView.deleteSections(indexSet, with: .automatic)
default:
return
}
}
}
|
//
// Meme.swift
// MemeMe
//
// Created by Johan Smet on 22/05/15.
// Copyright (c) 2015 Justcode.be. All rights reserved.
//
import Foundation
import UIKit
struct Meme {
let topText : String
let bottomText : String
let image : UIImage
let memedImage : UIImage
init(topText : String, bottomText : String, image : UIImage, memedImage : UIImage) {
self.topText = topText
self.bottomText = bottomText
self.image = image
self.memedImage = memedImage
}
} |
//
// TargetModel.swift
// Climbing
//
// Created by Leo on 8/10/16.
// Copyright © 2016 Leo. All rights reserved.
//
import UIKit
import AVFoundation
class TargetModel: NSObject, UIGestureRecognizerDelegate {
var image: UIImageView
var imageName: String
var id: UInt32?
let systemSoundID: SystemSoundID = 1016
var modeDetection: Bool
var position: TargetPosition?
func tapBubbleOnce(sender: UITapGestureRecognizer?) {
if position != nil{
if image.backgroundColor == UIColor.whiteColor() {
image.image = UIImage(named: "Smile")
image.backgroundColor = UIColor.clearColor()
image.layer.sublayers?.removeAll()
AudioServicesPlaySystemSound (systemSoundID)
}
if position == .Left {
NSNotificationCenter.defaultCenter().postNotificationName("tapBubbleFromLeftView:", object: nil)
}else {
NSNotificationCenter.defaultCenter().postNotificationName("tapBubbleFromRightView:", object: nil)
}
}else {
if image.backgroundColor == UIColor.whiteColor() {
image.image = UIImage(named: "Smile")
image.backgroundColor = UIColor.clearColor()
image.layer.sublayers?.removeAll()
AudioServicesPlaySystemSound (systemSoundID)
// image.image = UIImage(named: "pika")
//TargetHouse.shareInstance.currentPoint += 1
NSNotificationCenter.defaultCenter().postNotificationName("tapBubbleOnce:", object: nil)
}
}
}
func tapBubbleTwice(sender: UITapGestureRecognizer?) {
if image.image == UIImage(named: "smile") {
image.backgroundColor = UIColor.whiteColor()
// image.image = UIImage(named: "pokeball")
//TargetHouse.shareInstance.currentPoint -= 1
}
}
func longPressBubble(sender: UILongPressGestureRecognizer?) {
NSNotificationCenter.defaultCenter().postNotificationName("deleteTarget:", object: nil)
}
let mainView = UIApplication.sharedApplication().keyWindow?.superview
let mainFrame = UIApplication.sharedApplication().keyWindow?.bounds
func dragTarget(recognizer: UIPanGestureRecognizer) {
let point = recognizer.locationInView(mainView);
if point.y < (mainFrame?.minY)! + 30 || point.x > (mainFrame?.maxX)! - 20 || point.x < (mainFrame?.minX)! + 35 {
// let newframe = CGRectMake(point.x, point.y, 60, 60)
// image.frame = newframe
}else{
image.center.x = point.x
image.center.y = point.y
}
}
init(image: UIImageView, imageName: String, id: UInt32?, modeDetection: Bool){
self.imageName = imageName
self.image = image
self.image.image = UIImage(named: imageName)
self.id = id
self.modeDetection = modeDetection
super.init()
image.userInteractionEnabled = true
if modeDetection {
let tapOne = UITapGestureRecognizer(target: self, action: #selector(TargetModel.tapBubbleOnce(_:)))
tapOne.numberOfTapsRequired = 1
image.addGestureRecognizer(tapOne)
let tapTwo = UITapGestureRecognizer(target: self, action: #selector(TargetModel.tapBubbleTwice(_:)))
tapTwo.numberOfTapsRequired = 2
image.addGestureRecognizer(tapTwo)
tapOne.delegate = self
tapTwo.delegate = self
}
let dragBall = UIPanGestureRecognizer(target: self, action: #selector(TargetModel.dragTarget(_:)))
image.addGestureRecognizer(dragBall)
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(TargetModel.longPressBubble(_:)))
image.addGestureRecognizer(longPress)
dragBall.delegate = self
}
//sound setting
func playSound(soundName: String)
{
let coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundName, ofType: "m4a")!)
do{
let audioPlayer = try AVAudioPlayer(contentsOfURL:coinSound)
audioPlayer.prepareToPlay()
audioPlayer.play()
}catch {
print("Error getting the audio file")
}
}
}
enum TargetPosition {
case Left
case Right
}
|
//
// RxProgressHUD.swift
// RxSwiftDemo
//
// Created by tangyin on 06/03/2018.
// Copyright © 2018 ytang. All rights reserved.
//
import Foundation
import SVProgressHUD
enum HUDType {
case success
case error
case loading
case info
case progress
}
class RxProgressHUD: NSObject {
class func initRxProgressHUD() {
SVProgressHUD.setFont(UIFont.systemFont(ofSize: 14.0))
SVProgressHUD.setDefaultMaskType(.none)
SVProgressHUD.setMinimumDismissTimeInterval(1.5)
}
class func showSuccess(_ status: String) {
self.showRxProgressHUD(type: .success, status: status)
}
class func showError(_ status: String) {
self.showRxProgressHUD(type: .error, status: status)
}
class func showLoading(_ status: String) {
self.showRxProgressHUD(type: .loading, status: status)
}
class func showInfo(_ status: String) {
self.showRxProgressHUD(type: .info, status: status)
}
class func showProgress(_ status: String, _ progress: CGFloat) {
self.showRxProgressHUD(type: .success, status: status, progress: progress)
}
class func dismissHUD(_ delay: TimeInterval = 0) {
SVProgressHUD.dismiss(withDelay: delay)
}
}
extension RxProgressHUD {
class func showRxProgressHUD(type:HUDType, status: String, progress: CGFloat = 0) {
switch type {
case .success:
SVProgressHUD.showSuccess(withStatus: status)
case .error:
SVProgressHUD.showError(withStatus: status)
case .loading:
SVProgressHUD.show(withStatus: status)
case .info:
SVProgressHUD.showInfo(withStatus: status)
case .progress:
SVProgressHUD.showProgress(Float(progress), status: status)
}
}
}
|
//
// Created by Robert Petras
// SwiftUI Masterclass ♥ Better Apps. Less Code.
// https://swiftuimasterclass.com
//
import Foundation
import AVFoundation
var audioPlayer: AVAudioPlayer?
func playSound(sound: String, type: String) {
if let path = Bundle.main.path(forResource: sound, ofType: type) {
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
audioPlayer?.play()
} catch {
print("Could not find and play the sound file.")
}
feedback.notificationOccurred(.success)
}
}
func playAVSpeechSound(text: String) {
let utterance = AVSpeechUtterance(string: text)
utterance.voice = AVSpeechSynthesisVoice(language: "th-TH")
utterance.rate = 0.5
let synthesizer = AVSpeechSynthesizer()
synthesizer.speak(utterance)
}
|
// Automatically forks a generator on copy
struct ValueCopyGenerator<Element>: GeneratorType {
private var backing: ForkableGenerator<Element>
init(_ backing: ForkableGenerator<Element>) {
self.backing = backing
}
// Note that it is illegal to call next on a generator after bridging it
init<G: GeneratorType where G.Element == Element>(bridgedFromGenerator generator: G) {
backing = ForkableGenerator(bridgedFromGenerator: generator)
}
mutating func next() -> Element? {
if !isUniquelyReferencedNonObjC(&backing) { backing = backing.fork() }
return backing.next()
}
}
|
//
// SecondViewController.swift
// CopyKakaoTalk
//
// Created by YooBin Jo on 09/03/2019.
// Copyright © 2019 YooBin Jo. All rights reserved.
//
import UIKit
class MessageViewController: UIViewController {
@IBOutlet weak var messageTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
messageTable.delegate = self
messageTable.dataSource = self
let messageNibName = UINib(nibName: "KakaotalkChattingRoomCell", bundle: nil)
messageTable.register(messageNibName, forCellReuseIdentifier: "chattingRoomCell")
}
}
extension MessageViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return UITableViewCell()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
|
//
// RecipeDisplayable.swift
// Qantas-Recipes
//
// Created by Enver, Kemal on 25/6/18.
//
import Foundation
protocol RecipeDisplayable {
var recipeViewModel: RecipeViewModel? { get set }
}
|
//
// StatusPictureView.swift
// 小峰微博
//
// Created by apple on 18/5/4.
// Copyright © 2018年 Student. All rights reserved.
//
import UIKit
class StatusPictureView: UICollectionView {
public let StatusPictureViewItemMargin:CGFloat = 8
init()
{
let layout=UICollectionViewFlowLayout()
layout.minimumInteritemSpacing=StatusPictureViewItemMargin
layout.minimumLineSpacing=StatusPictureViewItemMargin
super.init(frame: CGRect.zero, collectionViewLayout: layout)
backgroundColor=UIColor(white: 0.8, alpha: 1.0)
// 设置数据源 - 自己当自己的数据源
// 应用场景:自定义视图的小框架
dataSource = self
//注册可重用的cell
register(StatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureCellId)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var viewModel:StatusViewModel?
{
didSet
{
sizeToFit()//让配图有个合适的尺寸
reloadData()
}
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
return cacViewSize()//CGSize(width: 150, height: 120)
}
}
extension StatusPictureView:UICollectionViewDataSource
{
public func cacViewSize()->CGSize
{
let rowCount:CGFloat=3
let maxWidth=UIScreen.main.bounds.width-2*StatusCellMargin
let itemWidth=(maxWidth-2*StatusPictureViewItemMargin)/rowCount
let layout=collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize=CGSize(width: itemWidth, height: itemWidth)
let count=viewModel?.thumbnailUrls?.count ?? 0
///没有图片
if count==0
{
return CGSize.zero
}
///1张图片
if count==1
{
var size=CGSize(width: 150, height: 120)
//layout.itemSize=size
//return size
if let key = viewModel?.thumbnailUrls?.first?.absoluteString{
let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: key)
print(key)
size = image?.size ?? CGSize.zero
}
size.width = size.width < 40 ? 40 : size.width
if size.width > 300{
let w:CGFloat = 300
let h = size.height
size = CGSize(width:w,height:h)
}
layout.itemSize = size
return size
}
///4张图片2*2
if count==4
{
let w=2*itemWidth+StatusPictureViewItemMargin
return CGSize(width: w, height: w)
}
///其它图片按照九宫格来显示
///计算出行数
let row=CGFloat((count-1)/Int(rowCount)+1)
let h=row*itemWidth+(row-1)*StatusPictureViewItemMargin+1
let w=rowCount*itemWidth+(rowCount-1)*StatusPictureViewItemMargin+1
return CGSize(width: w, height: h)
}
//返回thumbnailUrls个数,就是图片的个数
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel?.thumbnailUrls?.count ?? 0
}
//设置格子的内容
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell=collectionView.dequeueReusableCell(withReuseIdentifier: StatusPictureCellId, for: indexPath) as! StatusPictureViewCell
//cell.backgroundColor=UIColor.red
cell.imageURL = viewModel!.thumbnailUrls![indexPath.item]
return cell
}
}
let StatusPictureCellId="StatusPictureCellId"
import SDWebImage
class StatusPictureViewCell: UICollectionViewCell {
public lazy var gifIconView:UIImageView=UIImageView(imageName:"timeline_image_gif")
public lazy var iconView:UIImageView = {//UIImageView()
let iv = UIImageView()
iv.contentMode = .scaleAspectFill// 完全填充模式
iv.clipsToBounds=true//局限于试图边界
return iv
}()
var imageURL:NSURL?{
didSet
{
iconView.sd_setImage(with:imageURL as URL?, placeholderImage: nil, options: [SDWebImageOptions.retryFailed,SDWebImageOptions.refreshCached])//重试,刷新缓存
let ext = ((imageURL?.absoluteString ?? "") as NSString).pathExtension.lowercased()
gifIconView.isHidden = (ext != "gif")
}
}
override init(frame:CGRect)
{
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func setupUI()
{
contentView.addSubview(iconView)
iconView.addSubview(gifIconView)
iconView.snp.makeConstraints{
(make)->Void in
make.edges.equalTo(contentView.snp.edges)
}
gifIconView.snp.makeConstraints{
(make)->Void in
make.right.equalTo(iconView.snp.right)
make.bottom.equalTo(iconView.snp.bottom)
}
}
}
|
// AbstractCell.swift
// MusicList
//
// Created by Artem Kislitsyn on 17.02.2019.
// Copyright © 2019 3. All rights reserved.
//
import UIKit
protocol ReuseIdentifierProtocol where Self: UITableViewCell { }
extension ReuseIdentifierProtocol {
static var cellIdentifier: String {
return String(describing: self)
}
}
|
//
// AppStreamVideoSource.swift
// ScreenMeetSDK
//
// Created by Vasyl Morarash on 28.08.2020.
//
import Foundation
import ReplayKit
import WebKit
extension DispatchQueue {
static let screenCaptureQueue = DispatchQueue(label: "com.screenmeet.screencapturequeue", qos: .userInitiated)
}
final class AppStreamVideoSource: LocalVideoSource {
var frameProcessor: FrameProcessor = AppStreamFrameProcessor()
private let screenRecorder = RPScreenRecorder.shared()
private var frameProcessingTimes = [TimeInterval]()
private var frameProcessingTimesTimer: Timer?
func startCapture(success: @escaping ((CVPixelBuffer) -> Void), failure: @escaping (() -> Void)) {
guard !screenRecorder.isRecording else { return }
// Timer should be scheduled in main thread
frameProcessingTimesTimer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(printAverageFrameProcessingTime), userInfo: nil, repeats: true)
DispatchQueue.screenCaptureQueue.async { [unowned self] in
screenRecorder.startCapture(handler: { (sampleBuffer, sampleBufferType, error) in
guard sampleBufferType == .video else { return }
guard error == nil else { return }
guard let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
let startFrameProcessingTime = Date.timeIntervalSinceReferenceDate
frameProcessor.processFrame(pixelBuffer: pixelBuffer) { (processedPixelBuffer) in
frameProcessingTimes.append(Date.timeIntervalSinceReferenceDate - startFrameProcessingTime)
success(pixelBuffer)
}
}, completionHandler: { (error) in
if error != nil {
failure()
}
})
}
}
func stopCapture(completion: @escaping (() -> Void)) {
guard screenRecorder.isRecording else {
completion()
return
}
frameProcessingTimesTimer?.invalidate()
frameProcessingTimesTimer = nil
screenRecorder.stopCapture { (error) in
completion()
}
}
@objc private func printAverageFrameProcessingTime() {
guard frameProcessingTimes.count > 0 else { return }
let avgValue = frameProcessingTimes.reduce(0.0, +) / Double(frameProcessingTimes.count)
Logger.log.info("Average Frame processing time: \(String(format: "Value: %.3f", (avgValue * 1000))) ms")
frameProcessingTimes.removeAll()
}
}
/// - Tag: AppStreamFrameProcessor
public final class AppStreamFrameProcessor: FrameProcessor {
private var views = [AppStreamView]()
private var webViews = [AppStreamWebView]()
private var overlayImage = UIImage(color: .red)
private let ciContext: CIContext = CIContext(options: nil)
public func processFrame(pixelBuffer: CVPixelBuffer, completion: @escaping (CVPixelBuffer) -> Void) {
guard views.count > 0 || webViews.count > 0 else {
completion(pixelBuffer)
return
}
DispatchQueue.main.async { [unowned self] in
var confidentialRects = views.compactMap { $0.getRect() }
DispatchQueue.screenCaptureQueue.async { [unowned self] in
webViews.forEach { webView in
webView.getRects { (rects) in
confidentialRects.append(contentsOf: rects)
}
}
guard confidentialRects.count > 0 else {
completion(pixelBuffer)
return
}
let ciImage: CIImage = CIImage(cvPixelBuffer: pixelBuffer)
var outputImage: CIImage = ciImage
let wScale = ciImage.extent.width / UIScreen.main.bounds.size.width
let hScale = ciImage.extent.height / UIScreen.main.bounds.size.height
confidentialRects.forEach { rect in
let width = rect.width * wScale
let height = rect.height * hScale
let x = rect.origin.x * wScale
let y = ciImage.extent.height - height - (rect.origin.y * hScale)
let rect = CGRect(x: x, y: y, width: width, height: height)
outputImage = self.applyFilter(rect: rect, ciImage: outputImage)
}
self.ciContext.render(outputImage, to: pixelBuffer)
completion(pixelBuffer)
}
}
}
public func setConfidential<T: UIView>(view: T) {
self.views.removeAll(where: { $0.value == nil })
guard !self.views.contains(where: { $0.value == view }) else { return }
views.append(AppStreamView(view))
}
public func unsetConfidential<T: UIView>(view: T) {
self.views.removeAll(where: { $0.value == view || $0.value == nil })
}
public func setConfidentialWeb<T: WKWebView>(view: T) {
self.webViews.removeAll(where: { $0.value == nil })
guard !self.webViews.contains(where: { $0.value == view }) else { return }
let webView = AppStreamWebView(view)
webViews.append(webView)
}
public func unsetConfidentialWeb<T: WKWebView>(view: T) {
self.webViews.removeAll(where: { $0.value == view || $0.value == nil })
}
private func applyFilter(rect: CGRect, ciImage: CIImage) -> CIImage {
guard let overlayCIImage = CIImage(image: overlayImage) else { return ciImage }
guard let cropFilter = CIFilter(name: "CICrop") else { return ciImage }
cropFilter.setValue(overlayCIImage, forKey: kCIInputImageKey)
cropFilter.setValue(CIVector(cgRect: rect), forKey: "inputRectangle")
guard let overCompositingFilter = CIFilter(name: "CISourceOverCompositing") else { return ciImage }
overCompositingFilter.setValue(cropFilter.outputImage, forKey: kCIInputImageKey)
overCompositingFilter.setValue(ciImage, forKey: kCIInputBackgroundImageKey)
guard let outputImage = overCompositingFilter.outputImage else { return ciImage }
return outputImage
}
}
extension UIView {
var globalRect: CGRect? {
guard let origin = self.layer.presentation()?.frame.origin,
let globalPoint = self.superview?.layer.presentation()?.convert(origin, to: nil) else { return nil }
return CGRect(origin: globalPoint, size: self.frame.size)
}
var globalTransform: CATransform3D? {
guard let presentation = self.layer.presentation() else { return nil }
return presentation.transform
}
}
|
//
// VehiclesViewController.swift
// StarTrivia
//
// Created by Juan Francisco Dorado Torres on 5/18/19.
// Copyright © 2019 Juan Francisco Dorado Torres. All rights reserved.
//
import UIKit
import MBProgressHUD
class VehiclesViewController: UIViewController, CharacterProtocol {
// MARK: - Outlets
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var modelLabel: UILabel!
@IBOutlet weak var manufacturerLabel: UILabel!
@IBOutlet weak var costLabel: UILabel!
@IBOutlet weak var lengthLabel: UILabel!
@IBOutlet weak var speedLabel: UILabel!
@IBOutlet weak var crewLabel: UILabel!
@IBOutlet weak var passengersLabel: UILabel!
@IBOutlet weak var previousButton: UIButton!
@IBOutlet weak var nextButton: UIButton!
// MARK: - Public Properties
var character: Character!
// MARK: - Private Properties
private let vehicleAPI = VehicleAPI()
private var vehicles = [String]()
private var currentVehicle = 0
// MARK: - View cycle
override func viewDidLoad() {
super.viewDidLoad()
if character != nil, !character.vehicleUrls.isEmpty {
vehicles = character.vehicleUrls
nextButton.isEnabled = vehicles.count > 1
previousButton.isEnabled = false
getVehicleData(with: vehicles.first!)
}
}
// MARK: Actions
@IBAction func previousButtonTapped() {
currentVehicle -= 1
setButtonState()
}
@IBAction func nextButtonTapped() {
currentVehicle += 1
setButtonState()
}
// MARK: - Private Methods
private func getVehicleData(with vehicleURL: String) {
let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
hud.label.text = "Looking for Vehicle..."
vehicleAPI.getVehicle(url: vehicleURL) { [weak self] (vehicle) in
if let strongSelf = self, let vehicle = vehicle {
strongSelf.updateUI(with: vehicle)
}
hud.hide(animated: true)
}
}
private func updateUI(with vehicle: Vehicle) {
nameLabel.text = vehicle.name
modelLabel.text = vehicle.model
manufacturerLabel.text = vehicle.manufacturer
costLabel.text = vehicle.cost
lengthLabel.text = vehicle.length
speedLabel.text = vehicle.speed
crewLabel.text = vehicle.crew
passengersLabel.text = vehicle.passengers
}
private func setButtonState() {
previousButton.isEnabled = !(currentVehicle == 0)
nextButton.isEnabled = !(currentVehicle == vehicles.count - 1)
getVehicleData(with: vehicles[currentVehicle])
}
}
|
//
// Users.swift
// SwiftTest3
//
// Created by Rustam N on 23.02.17.
// Copyright © 2017 com.personal.ildar. All rights reserved.
//
import UIKit
class Users: UITableViewController {
var primaryArrWithUsers: [UserProfile] = []
var arrWithUsers: [UserProfile] = []
var sortBy: Int = -1
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(UsersCell.nib, forCellReuseIdentifier: UsersCell.cellIdentifier)
self.tableView.allowsSelection = false
primaryArrWithUsers = GetArrWithUsers()
}
override func viewWillAppear(_ animated: Bool) {
sortUsers()
self.tableView.reloadData()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SettingsSegue" {
let destination = segue.destination as! Settings
destination.delegate = self
destination.selectedSwitchAtRow = sortBy
}
}
}
extension Users {
// MARK: - My
func sortUsers(){
guard sortBy != -1 else {
arrWithUsers = primaryArrWithUsers
return
}
switch sortBy {
case 0:
arrWithUsers = primaryArrWithUsers.sorted (by: { $0.firstName < $1.firstName })
case 1:
arrWithUsers = primaryArrWithUsers.sorted (by: { $0.lastName < $1.lastName })
case 2:
arrWithUsers = primaryArrWithUsers.sorted (by: { $0.dateBorn < $1.dateBorn })
case 3:
arrWithUsers = primaryArrWithUsers.sorted (by: { $0.gender < $1.gender })
default:
break
}
}
}
extension Users {
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrWithUsers.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: UsersCell.cellIdentifier, for: indexPath) as! UsersCell
let user: UserProfile = arrWithUsers[indexPath.row]
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy"
cell.fullNameLabel.text = user.getFullName()
cell.dateLabel.text = formatter.string(from: user.dateBorn)
cell.genderLabel.text = user.gender
return cell
}
}
extension Users: SettingsDelegate{
func sortByThis(sortBy: Int) {
self.sortBy = sortBy
}
}
|
//
// SyncPair_BotLogic.swift
// Buildasaur
//
// Created by Honza Dvorsky on 19/05/15.
// Copyright (c) 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import XcodeServerSDK
import BuildaGitServer
import BuildaUtils
public class SyncPairResolver {
public init() {
//
}
public func resolveActionsForCommitAndIssueWithBotIntegrations(
commit: String,
issue: Issue?,
bot: Bot,
integrations: [Integration]) -> SyncPair.Actions {
var integrationsToCancel: [Integration] = []
let startNewIntegration: Bool = false
//------------
// Split integrations into two groups: 1) for this SHA, 2) the rest
//------------
let uniqueIntegrations = Set(integrations)
//1) for this SHA
let headCommitIntegrations = Set(self.headCommitIntegrationsFromAllIntegrations(commit, allIntegrations: integrations))
//2) the rest
let otherCommitIntegrations = uniqueIntegrations.subtract(headCommitIntegrations)
let noncompletedOtherCommitIntegrations: Set<Integration> = otherCommitIntegrations.filterSet {
return $0.currentStep != .Completed
}
//2.1) Ok, now first cancel all unfinished integrations of the non-current commits
integrationsToCancel += Array(noncompletedOtherCommitIntegrations)
//------------
// Now we're resolving Integrations for the current commit only
//------------
/*
The resolving logic goes like this now. We have an array of integrations I for the latest commits.
A. is array empty?
A1. true -> there are no integrations for this commit. kick one off! we're done.
A2. false -> keep resolving (all references to "integrations" below mean only integrations of the current commit
B. take all pending integrations, keep the most recent one, if it's there, cancel all the other ones.
C. take the running integration, if it's there
D. take all completed integrations
resolve the status of the PR as follows
E. is there a latest pending integration?
E1. true -> status is ["Pending": "Waiting on the queue"]. also, if there's a running integration, cancel it.
E2. false ->
F. is there a running integration?
F1. true -> status is ["Pending": "Integration in progress..."]. update status and do nothing else.
F2. false ->
G. are there any completed integrations?
G1. true -> based on the result of the integrations create the PR status
G2. false -> this shouldn't happen, print a very angry message.
*/
//A. is this array empty?
if headCommitIntegrations.count == 0 {
//A1. - it's empty, kick off an integration for the latest commit
return SyncPair.Actions(
integrationsToCancel: integrationsToCancel,
githubStatusToSet: nil,
startNewIntegrationBot: bot
)
}
//A2. not empty, keep resolving
//B. get pending Integrations
let pending = headCommitIntegrations.filterSet {
$0.currentStep == .Pending
}
var latestPendingIntegration: Integration?
if pending.count > 0 {
//we should cancel all but the most recent one
//turn the pending set into an array and sort by integration number in ascending order
var pendingSortedArray: Array<Integration> = Array(pending).sort({ (integrationA, integrationB) -> Bool in
return integrationA.number < integrationB.number
})
//keep the latest, which will be the last in the array
//let this one run, it might have been a force rebuild.
latestPendingIntegration = pendingSortedArray.removeLast()
//however, cancel the rest of the pending integrations
integrationsToCancel += pendingSortedArray
}
//Get the running integration, if it's there
let runningIntegration = headCommitIntegrations.filterSet {
$0.currentStep != .Completed && $0.currentStep != .Pending
}.first
//Get all completed integrations for this commit
let completedIntegrations = headCommitIntegrations.filterSet {
$0.currentStep == .Completed
}
//resolve to a status
let actions = self.resolveCommitStatusFromLatestIntegrations(
commit,
issue: issue,
pending: latestPendingIntegration,
running: runningIntegration,
completed: completedIntegrations)
//merge in nested actions
return SyncPair.Actions(
integrationsToCancel: integrationsToCancel + (actions.integrationsToCancel ?? []),
githubStatusToSet: actions.githubStatusToSet,
startNewIntegrationBot: actions.startNewIntegrationBot ?? (startNewIntegration ? bot : nil)
)
}
func headCommitIntegrationsFromAllIntegrations(headCommit: String, allIntegrations: [Integration]) -> [Integration] {
let uniqueIntegrations = Set(allIntegrations)
//1) for this SHA
let headCommitIntegrations = uniqueIntegrations.filterSet {
(integration: Integration) -> Bool in
//if it's not pending, we need to take a look at the blueprint and inspect the SHA.
if let blueprint = integration.blueprint, let sha = blueprint.commitSHA {
return sha == headCommit
}
//when an integration is Pending, Preparing or Checking out, it doesn't have a blueprint, but it is, by definition, a headCommit
//integration (because it will check out the latest commit on the branch when it starts running)
if
integration.currentStep == .Pending ||
integration.currentStep == .Preparing ||
integration.currentStep == .Checkout
{
return true
}
if integration.currentStep == .Completed {
if let result = integration.result {
//if the result doesn't have a SHA yet and isn't pending - take a look at the result
//if it's a checkout-error, assume that it is a malformed SSH key bot, so don't keep
//restarting integrations - at least until someone fixes it (by closing the PR and fixing
//their SSH keys in Buildasaur so that when the next bot gets created, it does so with the right
//SSH keys.
if result == .CheckoutError {
Log.error("Integration #\(integration.number) finished with a checkout error - please check that your SSH keys setup in Buildasaur are correct! If you need to fix them, please do so and then you need to recreate the bot - e.g. by closing the Pull Request, waiting for a sync (bot will disappear) and then reopening the Pull Request - should do the job!")
return true
}
if result == .Canceled {
//another case is when the integration gets doesn't yet have a blueprint AND was cancelled -
//we should assume it belongs to the latest commit, because we can't tell otherwise.
return true
}
}
}
return false
}
let sortedHeadCommitIntegrations = Array(headCommitIntegrations).sort {
(a: Integration, b: Integration) -> Bool in
return a.number > b.number
}
return sortedHeadCommitIntegrations
}
func resolveCommitStatusFromLatestIntegrations(
commit: String,
issue: Issue?,
pending: Integration?,
running: Integration?,
completed: Set<Integration>) -> SyncPair.Actions {
let statusWithComment: HDGitHubXCBotSyncer.GitHubStatusAndComment
var integrationsToCancel: [Integration] = []
//if there's any pending integration, we're ["Pending" - Waiting in the queue]
if let _ = pending {
//TODO: show how many builds are ahead in the queue and estimate when it will be
//started and when finished? (there is an average running time on each bot, it should be easy)
let status = HDGitHubXCBotSyncer.createStatusFromState(.Pending, description: "Build waiting in the queue...")
statusWithComment = (status: status, comment: nil)
//also, cancel the running integration, if it's there any
if let running = running {
integrationsToCancel.append(running)
}
} else {
//there's no pending integration, it's down to running and completed
if let running = running {
//there is a running integration.
//TODO: estimate, based on the average running time of this bot and on the started timestamp, when it will finish. add that to the description.
let currentStepString = running.currentStep.rawValue
let status = HDGitHubXCBotSyncer.createStatusFromState(.Pending, description: "Integration step: \(currentStepString)...")
statusWithComment = (status: status, comment: nil)
} else {
//there no running integration, we're down to completed integration.
if completed.count > 0 {
//we have some completed integrations
statusWithComment = self.resolveStatusFromCompletedIntegrations(completed)
} else {
//this shouldn't happen.
Log.error("LOGIC ERROR! This shouldn't happen, there are no completed integrations!")
let status = HDGitHubXCBotSyncer.createStatusFromState(.Error, description: "* UNKNOWN STATE, Builda ERROR *")
statusWithComment = (status: status, "Builda error, unknown state!")
}
}
}
return SyncPair.Actions(
integrationsToCancel: integrationsToCancel,
githubStatusToSet: (status: statusWithComment, commit: commit, issue: issue),
startNewIntegrationBot: nil
)
}
private func statusAndCommentFromLines(lines: [String], status: Status) -> HDGitHubXCBotSyncer.GitHubStatusAndComment {
let comment: String?
if lines.count == 0 {
comment = nil
} else {
comment = lines.joinWithSeparator("\n")
}
return (status: status, comment: comment)
}
func resolveStatusFromCompletedIntegrations(
integrations: Set<Integration>) -> HDGitHubXCBotSyncer.GitHubStatusAndComment {
//get integrations sorted by number
let sortedDesc = Array(integrations).sort { $0.number > $1.number }
let resultString = "*Result*: "
//if there are any succeeded, it wins - iterating from the end
if let passingIntegration = sortedDesc.filter({
(integration: Integration) -> Bool in
switch integration.result! {
case Integration.Result.Succeeded, Integration.Result.Warnings, Integration.Result.AnalyzerWarnings:
return true
default:
return false
}
}).first {
var lines = HDGitHubXCBotSyncer.baseCommentLinesFromIntegration(passingIntegration)
let status = HDGitHubXCBotSyncer.createStatusFromState(.Success, description: "Build passed!")
let summary = passingIntegration.buildResultSummary!
if passingIntegration.result == .Succeeded {
let testsCount = summary.testsCount
lines.append(resultString + "**Perfect build!** All \(testsCount) " + "test".pluralizeStringIfNecessary(testsCount) + " passed. :+1:")
} else if passingIntegration.result == .Warnings {
let warningCount = summary.warningCount
lines.append(resultString + "All \(summary.testsCount) tests passed, but please **fix \(warningCount) " + "warning".pluralizeStringIfNecessary(warningCount) + "**.")
} else {
let analyzerWarningCount = summary.analyzerWarningCount
lines.append(resultString + "All \(summary.testsCount) tests passed, but please **fix \(analyzerWarningCount) " + "analyzer warning".pluralizeStringIfNecessary(analyzerWarningCount) + "**.")
}
//and code coverage
let codeCoveragePercentage = summary.codeCoveragePercentage
if codeCoveragePercentage > 0 {
lines.append("*Test Coverage*: \(codeCoveragePercentage)%.")
}
return self.statusAndCommentFromLines(lines, status: status)
}
//ok, no succeeded, warnings or analyzer warnings, get down to test failures
if let testFailingIntegration = sortedDesc.filter({
$0.result! == Integration.Result.TestFailures
}).first {
var lines = HDGitHubXCBotSyncer.baseCommentLinesFromIntegration(testFailingIntegration)
let status = HDGitHubXCBotSyncer.createStatusFromState(.Failure, description: "Build failed tests!")
let summary = testFailingIntegration.buildResultSummary!
let testFailureCount = summary.testFailureCount
lines.append(resultString + "**Build failed \(testFailureCount) " + "test".pluralizeStringIfNecessary(testFailureCount) + "** out of \(summary.testsCount)")
return self.statusAndCommentFromLines(lines, status: status)
}
//ok, the build didn't even run then. it either got cancelled or failed
if let erroredIntegration = sortedDesc.filter({
$0.result! != Integration.Result.Canceled
}).first {
var lines = HDGitHubXCBotSyncer.baseCommentLinesFromIntegration(erroredIntegration)
let errorCount: Int = erroredIntegration.buildResultSummary?.errorCount ?? -1
let status = HDGitHubXCBotSyncer.createStatusFromState(.Error, description: "Build error!")
lines.append(resultString + "**\(errorCount) " + "error".pluralizeStringIfNecessary(errorCount) + ", failing state: \(erroredIntegration.result!.rawValue)**")
return self.statusAndCommentFromLines(lines, status: status)
}
//cool, not even build error. it must be just canceled ones then.
if let canceledIntegration = sortedDesc.filter({
$0.result! == Integration.Result.Canceled
}).first {
var lines = HDGitHubXCBotSyncer.baseCommentLinesFromIntegration(canceledIntegration)
let status = HDGitHubXCBotSyncer.createStatusFromState(.Error, description: "Build canceled!")
//TODO: find out who canceled it and add it to the comment?
lines.append("Build was **manually canceled**.")
return self.statusAndCommentFromLines(lines, status: status)
}
//hmm no idea, if we got all the way here. just leave it with no state.
let status = HDGitHubXCBotSyncer.createStatusFromState(.NoState, description: nil)
return (status: status, comment: nil)
}
}
|
//
// ContentView.swift
// Recipes
//
// Created by Fábio Salata on 19/10/20.
//
import SwiftUI
struct ContentView: View {
@StateObject var manager = RecipeManager()
@Namespace private var viewSpace
var body: some View {
ZStack {
Color.lightBackground
.ignoresSafeArea()
RecipeOverview(manager: manager, viewSpace: viewSpace)
.padding(.horizontal)
if manager.selectedRecipe != nil {
RecipeDetailView(manager: manager, viewSpace: viewSpace)
}
}
}
}
struct RecipeOverview: View {
@ObservedObject var manager: RecipeManager
var viewSpace: Namespace.ID
var body: some View {
VStack(alignment: .leading, spacing: 1) {
Spacer()
TitleView(manager: manager)
ZStack {
RecipeInteractionView(recipe: manager.data[manager.currentRecipeIndex],
index: manager.currentRecipeIndex,
count: manager.data.count,
showArrow: true,
manager: manager,
viewSpace: viewSpace)
.rotationEffect(.degrees(Double(-manager.swipeHeight)))
.offset(x: UIScreen.screenWidth / 2)
HStack {
SummaryView(recipe: manager.data[manager.currentRecipeIndex])
Spacer()
}
}
DescriptionView(manager: manager)
Spacer()
}
}
}
struct TitleView: View {
@ObservedObject var manager: RecipeManager
var body: some View {
Text("Daily Cooking Quest")
.font(.system(size: 16, weight: .bold))
.foregroundColor(.gray)
Spacer()
Text(manager.data[manager.currentRecipeIndex].title)
.font(.system(size: 24, weight: .bold))
.foregroundColor(.black)
}
}
struct SummaryView: View {
let recipe: RecipeItem
var body: some View {
VStack(alignment: .leading, spacing: 24) {
ForEach(recipe.summary.sorted(by: <), id: \.key) { key, value in
HStack(spacing: 12) {
Image(systemName: Data.summaryImageName[key] ?? "")
.foregroundColor(.green)
Text(value)
}
}
HStack(spacing: 12) {
Image(systemName: "chart.bar.doc.horizontal")
.foregroundColor(.green)
Text("Healthy")
}
}
.font(.system(size: 17, weight: .semibold))
}
}
struct DescriptionView: View {
@ObservedObject var manager: RecipeManager
var body: some View {
HStack(spacing: 12) {
Text(manager.data[manager.currentRecipeIndex].description)
.font(.system(size: 14, weight: .semibold))
Button(action: {
withAnimation {
manager.selectedRecipe = manager.data[manager.currentRecipeIndex]
}
}, label: {
ZStack {
RoundedRectangle(cornerRadius: 10)
.fill(Color.green)
.frame(width: 50, height: 50)
.rotationEffect(.degrees(45))
Image(systemName: "arrow.right")
.font(.system(size: 20, weight: .semibold))
.foregroundColor(.white)
}
})
Spacer()
}
}
}
struct RecipeInteractionView: View {
let recipe: RecipeItem
let index: Int
let count: Int
let showArrow: Bool
@ObservedObject var manager: RecipeManager
var viewSpace: Namespace.ID
var body: some View {
ZStack {
Circle()
.stroke(
LinearGradient(gradient: Gradient(colors: [Color.lightBackground, Color.green]),
startPoint: .leading,
endPoint: .trailing),
lineWidth: 4
)
.scaleEffect(1.15)
.matchedGeometryEffect(id: "borderId", in: viewSpace, isSource: true)
if showArrow {
ArrowShape(reachedTop: index == 0, reachedBottom: index == count - 1)
.stroke(Color.gray, style: StrokeStyle(lineWidth: 2.5, lineCap: .round, lineJoin: .round))
.frame(width: UIScreen.screenWidth - 32, height: UIScreen.screenWidth - 32)
.scaleEffect(1.15)
.matchedGeometryEffect(id: "arrowId", in: viewSpace, isSource: true)
}
Image(recipe.imageName)
.resizable()
.scaledToFit()
.matchedGeometryEffect(id: "imageId", in: viewSpace, isSource: true)
Circle()
.fill(Color.black.opacity(0.001))
.scaleEffect(1.2)
.gesture(
DragGesture(minimumDistance: 10)
.onChanged({ value in
withAnimation {
manager.changeSwipeValue(value: value.translation.height)
}
})
.onEnded({ value in
withAnimation {
manager.swipeEnded(value: value.translation.height)
}
})
)
}
}
}
struct ArrowShape: Shape {
let reachedTop: Bool
let reachedBottom: Bool
func path(in rect: CGRect) -> Path {
var path = Path()
let startAngle: CGFloat = 160
let endAngle: CGFloat = 200
let radius = rect.width / 2
let startAngleRadians = startAngle * CGFloat.pi / 180
let endAngleRadians = endAngle * CGFloat.pi / 180
let startPoint1 = CGPoint.pointOnCircle(center: CGPoint(x: radius, y: radius), radius: radius, angle: startAngleRadians)
let endPoint1 = CGPoint.pointOnCircle(center: CGPoint(x: radius, y: radius), radius: radius, angle: endAngleRadians)
path.addArc(center: CGPoint(x: radius, y: radius),
radius: radius,
startAngle: .degrees(Double(startAngle)),
endAngle: .degrees(Double(endAngle)),
clockwise: false)
if !reachedTop {
let startAngleRadians2 = (startAngle + 4) * CGFloat.pi / 180
let startPoint2 = CGPoint.pointOnCircle(center: CGPoint(x: radius, y: radius), radius: radius + 8, angle: startAngleRadians2)
let startPoint3 = CGPoint.pointOnCircle(center: CGPoint(x: radius, y: radius), radius: radius - 8, angle: startAngleRadians2)
path.move(to: startPoint1)
path.addLine(to: startPoint2)
path.move(to: startPoint1)
path.addLine(to: startPoint3)
}
if !reachedBottom {
let endAngleRadians2 = (endAngle - 4) * CGFloat.pi / 180
let endPoint2 = CGPoint.pointOnCircle(center: CGPoint(x: radius, y: radius), radius: radius + 8, angle: endAngleRadians2)
let endPoint3 = CGPoint.pointOnCircle(center: CGPoint(x: radius, y: radius), radius: radius - 8, angle: endAngleRadians2)
path.move(to: endPoint1)
path.addLine(to: endPoint2)
path.move(to: endPoint1)
path.addLine(to: endPoint3)
}
return path
}
}
extension CGPoint {
static func pointOnCircle(center: CGPoint, radius: CGFloat, angle: CGFloat) -> CGPoint {
let x = center.x + radius * cos(angle)
let y = center.y + radius * sin(angle)
return CGPoint(x: x, y: y)
}
}
extension Color {
static let lightBackground = Color(red: 243/255, green: 243/255, blue: 243/255)
static let darkBackground = Color(red: 34/255, green: 51/255, blue: 68/255)
}
extension UIScreen {
static let screenWidth = UIScreen.main.bounds.size.width
static let screenHeight = UIScreen.main.bounds.size.height
static let screenSize = UIScreen.main.bounds.size
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
//
// BaseVC.swift
// VoiceMemoVIPER
//
// Created by Quang Ha on 3/10/16.
// Copyright © 2016 QH. All rights reserved.
//
import Foundation
import UIKit
class BaseVC: UIViewController {
class func loadFromStoryBoard <T: AnyObject> (sbName: String) -> T?{
let identifier = BaseVC.getName(T.self)
let sb = UIStoryboard(name: sbName, bundle: nil)
return sb.instantiateViewControllerWithIdentifier(identifier) as? T
}
class func getName(classType: AnyClass) -> String {
let classString = NSStringFromClass(classType.self)
let range = classString.rangeOfString(".", options: NSStringCompareOptions.CaseInsensitiveSearch, range: Range<String.Index>(start:classString.startIndex, end: classString.endIndex), locale: nil)
return classString.substringFromIndex(range!.endIndex)
}
} |
//
// EmployeeCellViewModel.swift
// Employee
//
// Created by mahabaleshwar hegde on 03/12/19.
// Copyright © 2019 mahabaleshwar hegde. All rights reserved.
//
import Foundation
struct EmployeeCellViewModel {
var name: String?
var email: String?
var avatar: URL?
init(employee: EmployeeDisplayble) {
self.name = employee.fullName
self.email = employee.email
self.avatar = employee.imageURL
}
}
|
//
// WorkoutDetailViewController.swift
// iOS-TraningsDagboken
//
// Created by Eddy Garcia on 2018-09-23.
// Copyright © 2018 Eddy Garcia. All rights reserved.
//
import UIKit
class WorkoutDetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableView: UITableView!
@IBOutlet var headerView: WorkoutDetailHeaderView!
var workoutPost : WorkoutPostMO!
//var workoutPost : WorkoutPost = WorkoutPost()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
navigationItem.largeTitleDisplayMode = .never
// Configure header view
headerView.nameLabel.text = workoutPost.name
headerView.locationLabel.text = workoutPost.location
if let workoutPostImage = workoutPost.image{
headerView.headerImageView.image = UIImage(data: workoutPostImage as Data)
}
headerView.heartImageView.isHidden = (workoutPost.isGood) ? false : true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - TableViewDataSource Protocol
// return the number of sections
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
// return the number of rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
// Custom cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: WorkoutDateAdressCell.self), for: indexPath) as! WorkoutDateAdressCell
cell.iconImageView.image = UIImage(named: "calendar")
cell.shortTextLabel.text = workoutPost.date
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: WorkoutDateAdressCell.self), for: indexPath) as! WorkoutDateAdressCell
cell.iconImageView.image = UIImage(named: "map")
cell.shortTextLabel.text = workoutPost.adress
return cell
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: WorkoutDescriptionCell.self), for: indexPath) as! WorkoutDescriptionCell
cell.descriptionLabel.text = workoutPost.summary
return cell
case 3:
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: WorkoutDetailSeparatorCell.self ), for: indexPath) as! WorkoutDetailSeparatorCell
cell.titleLabel.text = NSLocalizedString("HOW TO GET THERE", comment: "HOW TO GET THERE")
return cell
case 4:
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: WorkoutDetailMapCell.self), for: indexPath) as! WorkoutDetailMapCell
if let workoutPostAdress = workoutPost.adress {
cell.configure(location: workoutPostAdress)
}
return cell
default:
fatalError("Failed to instantiate tableViewCell for detailViewController")
}
}
//Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showMap" {
let destinationController = segue.destination as! MapViewController
destinationController.workoutPost = workoutPost
}
}
}
|
//
// Copyright © 2020 Tasuku Tozawa. All rights reserved.
//
import Combine
import Common
import UIKit
public protocol ImageLoaderProtocol {
func load(from source: ImageSource) -> Future<ImageLoaderResult, ImageLoaderError>
}
public class ImageLoader {
private var subscriptions = Set<AnyCancellable>()
// MARK: - Methods
private static func fetchImage(for url: URL) -> AnyPublisher<ImageLoaderResult, ImageLoaderError> {
let request: URLRequest
if let provider = WebImageProviderPreset.resolveProvider(by: url),
provider.shouldModifyRequest(for: url)
{
request = provider.modifyRequest(URLRequest(url: url))
} else {
request = URLRequest(url: url)
}
return URLSession.shared.dataTaskPublisher(for: request)
.map { data, response in
return ImageLoaderResult(usedUrl: url, mimeType: response.mimeType, data: data)
}
.mapError { ImageLoaderError.networkError($0) }
.eraseToAnyPublisher()
}
}
extension ImageLoader: ImageLoaderProtocol {
// MARK: - ImageLoaderProtocol
public func load(from source: ImageSource) -> Future<ImageLoaderResult, ImageLoaderError> {
switch source.value {
case let .rawData(data):
return Future { promise in
promise(.success(ImageLoaderResult(usedUrl: nil, mimeType: nil, data: data)))
}
case let .urlSet(urlSet):
return Future { [weak self] promise in
guard let self = self else {
promise(.failure(.internalError))
return
}
if let alternativeUrl = urlSet.alternativeUrl {
Self.fetchImage(for: alternativeUrl)
.catch { _ in
return Self.fetchImage(for: urlSet.url)
.eraseToAnyPublisher()
}
.sink { completion in
switch completion {
case let .failure(error):
promise(.failure(error))
default:
break
}
} receiveValue: { result in
promise(.success(result))
}
.store(in: &self.subscriptions)
} else {
Self.fetchImage(for: urlSet.url)
.sink { completion in
switch completion {
case let .failure(error):
promise(.failure(error))
default:
break
}
} receiveValue: { result in
promise(.success(result))
}
.store(in: &self.subscriptions)
}
}
}
}
}
|
///
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
///
//
// LookupATNConfig.swift
// objc2swiftwithswith
//
// Created by janyou on 15/9/22.
//
import Foundation
public class LookupATNConfig: Hashable {
public let config: ATNConfig
public init(_ old: ATNConfig) {
// dup
config = old
}
public func hash(into hasher: inout Hasher) {
hasher.combine(config.state.stateNumber)
hasher.combine(config.alt)
hasher.combine(config.semanticContext)
}
}
public func ==(lhs: LookupATNConfig, rhs: LookupATNConfig) -> Bool {
if lhs.config === rhs.config {
return true
}
return lhs.config.state.stateNumber == rhs.config.state.stateNumber &&
lhs.config.alt == rhs.config.alt &&
lhs.config.semanticContext == rhs.config.semanticContext
}
|
//
// ViewController.swift
// LabelChanger
//
// Created by Robert Stjacques Jr on 9/12/16.
// Copyright © 2016 Mobile Application Development. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// the label changer model used to determine which strings to display
private let model = LCModel()
@IBOutlet var firstLabel: UILabel!
@IBOutlet var secondLabel: UILabel!
@IBAction func firstButtonClicked(sender: AnyObject) {
// this label uses absolute positioning and size. it
// will not be centered on most screens, and it will
// not resize for content, so the content is sometimes
// cut off.
firstLabel.text = model.getFirstLabel()
}
@IBAction func secondButtonClicked(sender: AnyObject) {
// this label uses autolayout positioning so that it will
// remain centered on the screen and its size will adjust
// to fit the content as it changes
secondLabel.text = model.getSecondLabel()
}
override func viewDidLoad() {
super.viewDidLoad()
// init both labels to starting strings
firstLabel.text = model.getFirstLabel()
secondLabel.text = model.getSecondLabel()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// Location.swift
// Skoolivin
//
// Created by Namrata A on 5/5/18.
// Copyright © 2018 Namrata A. All rights reserved.
//
import Foundation
import MapKit
import SwiftyJSON
class Location: NSObject, MKAnnotation {
let coordinate: CLLocationCoordinate2D
let locName: String?
init(coordinate: CLLocationCoordinate2D, locName: String) {
self.coordinate = coordinate
self.locName = locName
super.init()
}
var subtitle: String?{
return locName
}
class func from(json: JSON) -> Location?
{
var title: String
if let unwrappedTitle = json["name"].string {
title = unwrappedTitle
} else {
title = ""
}
let lat = json["location"]["lat"].doubleValue
let long = json["location"]["lng"].doubleValue
let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
return Location(coordinate: coordinate, locName: title)
}
}
|
import UIKit
class BackupRequiredRouter {
private let account: Account
private let predefinedAccountType: PredefinedAccountType
private weak var sourceViewController: UIViewController?
init(account: Account, predefinedAccountType: PredefinedAccountType, sourceViewController: UIViewController?) {
self.account = account
self.predefinedAccountType = predefinedAccountType
self.sourceViewController = sourceViewController
}
func showBackup() {
sourceViewController?.present(BackupRouter.module(account: account, predefinedAccountType: predefinedAccountType), animated: true)
}
}
extension BackupRequiredRouter {
static func module(account: Account, predefinedAccountType: PredefinedAccountType, sourceViewController: UIViewController?, text: String) -> UIViewController {
let router = BackupRequiredRouter(account: account, predefinedAccountType: predefinedAccountType, sourceViewController: sourceViewController)
let viewController = BackupRequiredViewController(
router: router,
subtitle: predefinedAccountType.title,
text: text
)
return viewController.toBottomSheet
}
}
|
//
// ListsVC.swift
// random
//
// Created by Agent X on 1/12/18.
// Copyright © 2018 Andrii Halabuda. All rights reserved.
//
import UIKit
class ListsVC: UIViewController, UITextFieldDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var selectedLbl: CustomLabel!
@IBOutlet weak var addItemTextField: CustomTextField!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.addItemTextField.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
itemArray.removeAll()
tableView.reloadData()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
if addItemTextField.text == nil || addItemTextField.text == "" || addItemTextField.text == " " {
print(itemArray)
} else {
itemArray.append(addItemTextField.text!)
tableView.reloadData()
print(itemArray)
}
addItemTextField.text = nil
return true
}
@IBAction func generateTapped(_ sender: CustomButton) {
let randomNumber: Int
if itemArray.count != 0 {
randomNumber = Int.random(range: 0..<(itemArray.count))
selectedLbl.isHidden = false
selectedLbl.text = itemArray[randomNumber]
generateFeedback()
} else {
selectedLbl.isHidden = true
}
}
func generateFeedback() {
let generator = UIImpactFeedbackGenerator(style: .light)
generator.prepare()
generator.impactOccurred()
}
}
extension ListsVC: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemArray.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCell.EditingStyle.delete {
itemArray.remove(at: indexPath.row)
tableView.reloadData()
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as? ItemCell {
cell.itemLbl.text = itemArray[indexPath.row]
return cell
} else {
return ItemCell()
}
}
}
|
//
// DetailedViewController.swift
// GameOfThrones
//
// Created by Olimpia on 11/18/18.
// Copyright © 2018 Pursuit. All rights reserved.
//
import UIKit
class DetailedViewController: UIViewController {
@IBOutlet weak var episodePicture: UIImageView!
@IBOutlet weak var nameOfEpisode: UILabel!
@IBOutlet weak var numberOfTheSeason: UILabel!
@IBOutlet weak var episodeNumber: UILabel!
@IBOutlet weak var duration: UILabel!
@IBOutlet weak var airDate: UILabel!
@IBOutlet weak var episodeDescription: UITextView!
var episode: GOTEpisode?
override func viewDidLoad() {
super.viewDidLoad()
updateEpisodeUI()
}
private func updateEpisodeUI() {
episodePicture.image = UIImage(named: episode?.mediumImageID ?? "")
numberOfTheSeason.text = "Season: \(episode?.season ?? 0)"
episodeNumber.text = "Episode: \(episode?.number ?? 0)"
duration.text = "Runtime: \(episode?.runtime ?? 0)"
airDate.text = "Airdate: \(episode?.airdate ?? "")"
episodeDescription.text = episode?.summary
nameOfEpisode.text = episode?.name
}
}
|
//
// UserInfoModel.swift
// SuperTaxi
//
// Created by Jurica Mlinarić on 25/07/16.
// Copyright © 2016 Jensen Pich. All rights reserved.
//
import Foundation
import ObjectMapper
open class UserInfoModel: Mappable {
var name: String!
var age: NSInteger!
var note: String!
required public init?(map: Map) {
}
open func mapping(map: Map) {
name <- map["name"]
age <- map["age"]
note <- map["note"]
}
}
|
//
// ViewController.swift
// Section04_Assignment
//
// Created by seungjin on 2020/01/13.
// Copyright © 2020 Jinnify. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
//MARK:- UI Properties
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var ageLabel: UILabel!
@IBOutlet weak var ageTextField: UITextField!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var emailTextField: UITextField!
//MARK:- Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
//MARK:- Methods
private func setupUI() {
self.nameTextField.delegate = self
self.ageTextField.delegate = self
self.emailTextField.delegate = self
}
private func dismissKeyboard() {
view.endEditing(true)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
dismissKeyboard()
}
//MARK:- Actions
@IBAction func move(_ sender: UIButton) {
if let secondVC = storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as? SecondViewController {
secondVC.userInfo = [
"name" : nameTextField.text ?? "",
"age" : ageTextField.text ?? "",
"email" : emailTextField.text ?? ""
]
navigationController?.pushViewController(secondVC, animated: true)
}
}
}
//MARK:- Delegate
extension ViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
dismissKeyboard()
return true
}
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
// 방법 1
switch textField {
case nameTextField:
let name = (nameTextField.text ?? "") + string
nameLabel.didChangeColor(by: name.count >= 2)
case ageTextField:
let age = (ageTextField.text ?? "") + string
if let age = Int(age) {
ageLabel.didChangeColor(by: age >= 20)
}
case emailTextField:
let email = (emailTextField.text ?? "") + string
emailLabel.didChangeColor(by: email.contains("@"))
default:
return false
}
/*
방법 2
let name = (nameTextField.text ?? "") + string
let age = (ageTextField.text ?? "") + string
let email = (emailTextField.text ?? "") + string
if textField.isEqual(nameTextField) {
if name.count >= 2 {
nameLabel.textColor = .green
} else {
nameLabel.textColor = .red
}
} else if textField.isEqual(ageTextField) {
if let age = Int(age) {
if age >= 20 {
ageLabel.textColor = .green
} else {
ageLabel.textColor = .red
}
}
} else {
if email.contains("@") {
emailLabel.textColor = .green
} else {
emailLabel.textColor = .red
}
}
*/
return true
}
}
|
//
// TodayTodayInitializer.swift
// Weather
//
// Created by KONSTANTIN KUSAINOV on 21/03/2018.
// Copyright © 2018 Konstantin. All rights reserved.
//
import UIKit
class TodayModuleInitializer: NSObject {
//Connect with object on storyboard
@IBOutlet weak var todayViewController: TodayViewController!
override func awakeFromNib() {
let configurator = TodayModuleConfigurator()
configurator.configureModuleForViewInput(viewInput: todayViewController)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.