text stringlengths 8 1.32M |
|---|
//
// AppDelegate.swift
// se_iOS_client
//
// Created by syon on 2021/03/23.
//
import UIKit
import CoreData
import Firebase
import FirebaseMessaging
import UserNotifications
import Alamofire
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var isLogin : Bool!
var postList = [Post]()
let gcmMessageIDKey = "gcm.message_id"
var window: UIWindow?
var myFCMToken: String?
let alarmURL = "http://114.201.165.30:8090/notice/save-token"
let dataDict:[String: String]? = ["" : ""]
let uinfo = UserInfoManager()
let ud = UserDefaults.standard
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//로딩화면 딜레이주기
Thread.sleep(forTimeInterval: 0.6)
FirebaseApp.configure()
Messaging.messaging().delegate = self
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
// [END register_for_notifications]
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
}
// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
let notificationContent = UNMutableNotificationContent()
let receivedTitle = userInfo["title"]
let receivedBody = userInfo["content"]
notificationContent.title = receivedTitle as! String
notificationContent.body = receivedBody as! String
let request = UNNotificationRequest(identifier: "testNotification", content: notificationContent, trigger: nil)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("notification error: ", error)
}
}
completionHandler(UIBackgroundFetchResult.newData)
print("가나다라마바사")
}
// [END receive_message]
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the FCM registration token.
/*func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")
// With swizzling disabled you must set the APNs token here.
// Messaging.messaging().apnsToken = deviceToken
}*/
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
func application(application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Messaging.messaging().apnsToken = deviceToken
}
// MARK: - Core Data stack
var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "se_iOS_client")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
extension UIViewController {
func hideKeyboard() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self,
action: #selector(UIViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
}
extension String {
func htmlToAttributedString(font: UIFont, color: UIColor, lineHeight: CGFloat) -> NSAttributedString? {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
let _ = color.getRed(&red, green: &green, blue: &blue, alpha: nil)
let rgb = "rgb(\(red * 255),\(green * 255),\(blue * 255))"
let newLineHeight = lineHeight / font.pointSize
let newHTML = String(format:"<span style=\"font-family: '-apple-system', '\(font.fontName)'; font-size: \(font.pointSize); color: \(rgb); line-height: \(newLineHeight);\">%@</span>", self)
guard let data = newHTML.data(using: .utf8) else {
return NSAttributedString()
}
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
}
func htmlToAttributedString(myHtml: String) -> NSAttributedString? {
guard let data = myHtml.data(using: .utf8) else {
return NSAttributedString()
}
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// [START_EXCLUDE]
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// [END_EXCLUDE]
// Print full message.
print(userInfo)
print("여기다222222")
// Change this to your preferred presentation option
completionHandler([[.banner, .sound]])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// [START_EXCLUDE]
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
print("여기다222222")
}
// [END_EXCLUDE]
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print full message.
print(userInfo)
completionHandler()
}
}
// [END ios_10_message_handling]
extension AppDelegate : MessagingDelegate {
// [START refresh_token]
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
print("Firebase registration token: \(String(describing: fcmToken))")
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
self.uinfo.getMyAcoount()
print(ud.integer(forKey: "accountId"))
let longAccountId = ud.integer(forKey: "accountId")
let tempAccount = String(longAccountId)
if let tempToken = String(describing: fcmToken) as String? {
let param: Parameters = [
"accountId" : tempAccount,
"token" : tempToken
]
let call = AF.request(alarmURL, method: HTTPMethod.post, parameters: param, encoding: URLEncoding.default)
call.responseJSON { res in }
}
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
}
}
|
//
// LoadingView.swift
// LetSing
//
// Created by MACBOOK on 2018/5/14.
// Copyright © 2018年 MACBOOK. All rights reserved.
//
import Foundation
import UIKit
class LoadingView: UIView {
@IBOutlet weak var loadingLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
setLoadingAnimation()
}
func removeView() {
UIView.animate(withDuration: 0.5, animations: { () in
self.alpha = 0
}) { (_) in
self.removeFromSuperview()
}
}
func setLoadingAnimation() {
UIView.animate(withDuration: 0.85, delay: 0, options: [.autoreverse, .repeat], animations: { () in
self.loadingLabel.alpha = 0
})
}
}
|
//
// DatabaseService.swift
// neversitup
//
// Created by Kasidid Wachirachai on 23/1/21.
//
import Foundation
import RealmSwift
class DatabaseService {
let realm = try? Realm()
func addCustomers(customers: [Customer], _ complete: @escaping ((_ complete: Bool) -> ())) {
guard let realm = realm else {
print("Realm is nil.")
complete(false)
return
}
do {
try realm.write {
customers.forEach {
realm.add($0, update: .all)
}
complete(true)
}
} catch {
print(error)
complete(false)
}
// print(realm.configuration.fileURL)
}
func clearAllCustomers() {
guard let realm = realm else {
print("Realm is nil.")
return
}
do {
try realm.write {
let results = realm.objects(Customer.self)
realm.delete(results)
}
} catch {
print(error)
}
}
func getCustomers() -> [Customer] {
guard let realm = realm else {
print("Realm is nil.")
return []
}
let results = realm.objects(Customer.self)
return Array(results)
}
}
|
//
// InterviewController.swift
// App
//
// Created by Louis de Beaumont on 31/10/2019.
//
import Vapor
import Fluent
struct InterviewController: RouteCollection {
func boot(routes: RoutesBuilder) {
let route = routes.grouped("api", "interview")
route.get(use: get)
let auth = route.grouped([
// User.sessionAuthenticator(),
RedirectMiddleware(),
])
auth.post(use: create)
auth.post(":interviewID", "delete", use: delete)
}
func get(req: Request) -> EventLoopFuture<[InterviewResponse]> {
let interviewsQuery = Interview.query(on: req.db).sort("date", .descending).all()
return interviewsQuery.flatMap { interviews in
return interviews.map { interview in
let artistsQuery = interview.$artists.query(on: req.db).all()
return artistsQuery.flatMap { artists in
return artists.map { artist in
return artist.getPreview(db: req.db)
}
.flatten(on: req.eventLoop)
.map { artistPreviews in
return InterviewResponse(interview: interview, artists: artistPreviews)
}
}
}
.flatten(on: req.eventLoop)
}
}
func create(req: Request) -> EventLoopFuture<Interview> {
let body = req.body.description
guard let data = body.data(using: .utf8) else {
return req.eventLoop.makeFailedFuture(CreateError.runtimeError("Bad request body"))
}
let json: Dictionary<String, Any>
do {
guard let _json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? Dictionary<String, Any> else {
throw CreateError.runtimeError("Could not parse request body as JSON")
}
json = _json
} catch {
return req.eventLoop.makeFailedFuture(error)
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.timeZone = TimeZone(secondsFromGMT: 0)
guard let name = json["name"] as? String else {
return req.eventLoop.makeFailedFuture(CreateError.runtimeError("Invalid interview name"))
}
guard let dateJSON = json["date"] as? String else {
return req.eventLoop.makeFailedFuture(CreateError.runtimeError("Bad date value"))
}
guard let date = formatter.date(from: dateJSON) else {
return req.eventLoop.makeFailedFuture(CreateError.runtimeError("Date value could not be converted to DateTime obejct"))
}
let shortDescription = json["short-description"] as? String
let description = json["description"] as? String
let imageURL = json["imageURL"] as? String
let videoURL = json["videoURL"] as? String
let interview = Interview(
name: name,
date: date,
shortDescription: shortDescription,
description: description,
imageURL: imageURL,
videoURL: videoURL
)
let artistsQuery = Artist.query(on: req.db).all()
guard let artistNames = json["artists"] as? [String] else {
return req.eventLoop.makeFailedFuture(CreateError.runtimeError("[artists] was not a valid array"))
}
if json["id"] != nil {
guard let _id = json["id"] as? String else {
return req.eventLoop.makeFailedFuture(CreateError.runtimeError("Bad id value"))
}
guard let id = UUID(uuidString: _id) else {
return req.eventLoop.makeFailedFuture(CreateError.runtimeError("Id was not a valid UUID"))
}
return artistsQuery.flatMap { artists in
let artists = artists.filter { artistNames.contains($0.name) }
return self.update(req: req, id: id, updatedInterview: interview, artists: artists)
}
}
let interviewSaveRequest = interview.save(on: req.db)
return artistsQuery.and(interviewSaveRequest).flatMap { (artists, _) in
let artists = artists.filter { artistNames.contains($0.name) }
return artists.map { artist in
return interview.$artists.attach(artist, on: req.db)
}
.flatten(on: req.eventLoop)
.transform(to: interview)
}
}
func update(req: Request, id: UUID, updatedInterview: Interview, artists: [Artist]) -> EventLoopFuture<Interview> {
Interview.find(id, on: req.db)
.unwrap(or: Abort(.notFound))
.flatMap { interview in
interview.name = updatedInterview.name
interview.date = updatedInterview.date
interview.shortDescription = updatedInterview.shortDescription
interview.description = updatedInterview.description
interview.imageURL = updatedInterview.imageURL
interview.videoURL = updatedInterview.videoURL
let artistsDetachRequest = interview.$artists.detach(artists, on: req.db)
let interviewSaveRequest = interview.save(on: req.db)
return artistsDetachRequest.and(interviewSaveRequest).flatMap { (_, _) in
return artists.map { artist in
return interview.$artists.attach(artist, on: req.db)
}
.flatten(on: req.eventLoop)
.transform(to: interview)
}
}
}
func delete(req: Request) -> EventLoopFuture<Response> {
let redirect = req.redirect(to: "/app/interviews")
return Interview.find(req.parameters.get("interview"), on: req.db)
.unwrap(or: Abort(.notFound))
.flatMap { interview in
return interview.delete(on: req.db).transform(to: redirect)
}
}
}
|
//
// Consent.swift
// ResearchKit Tut
//
// Created by UKIBEE on 2021-02-11.
//
import Foundation
import ResearchKit
extension ORKConsentSection {
public convenience init(type: ORKConsentSectionType, summary: String?, content: String?) {
self.init(type: type)
self.summary = summary
self.content = content
}
}
extension ORKConsentReviewStep {
public convenience init(identifier: String, document: ORKConsentDocument, text: String?, reason: String?) {
guard let signature = document.signatures?.first else {
fatalError("Cannot create a review step without a signature")
}
self.init(identifier: identifier, signature: signature, in: document)
self.text = text
self.reasonForConsent = reason
}
}
class ATConsentTask: ORKTaskFactory {
func makeTask() -> ORKTask {
let consentDocument = ORKConsentDocument()
consentDocument.title = "Study Consent"
consentDocument.sections = [
ORKConsentSection(type: .overview,
summary: "Random study",
content: "Some general info about the study"),
ORKConsentSection(type: .dataGathering,
summary: "We'll collect some data",
content: "We're going to collect some data from you for scientific purposes"),
ORKConsentSection(type: .privacy,
summary: "Your privacy is important to us",
content: "We'll protect your privacy and won't sell your data"),
ORKConsentSection(type: .dataUse,
summary: "We need some data",
content: "Your data will only be used for research purposes"),
ORKConsentSection(type: .timeCommitment,
summary: "You'll spend some time",
content: "You will spend roughly 15 minutes a week"),
ORKConsentSection(type: .studySurvey,
summary: "Study survey",
content: "You'll be filling out some surveys"),
ORKConsentSection(type: .studyTasks,
summary: "Study tasks",
content: "Some of the tasks might require you to move around"),
ORKConsentSection(type: .withdrawing,
summary: "Withdrawing",
content: "You can always leave the survey")
]
consentDocument.addSignature(ORKConsentSignature(forPersonWithTitle: nil, dateFormatString: nil, identifier: "ParticipantSignature"))
return ORKOrderedTask(identifier: "consentTaskID",
steps: [
ORKVisualConsentStep(identifier: "visualConsentStepID",
document: consentDocument),
ORKConsentReviewStep(identifier: "consentReviewStepID",
document: consentDocument,
text: "Review",
reason: "Review the consent")
])
}
}
|
//
// DayEleven.swift
// aoc2020
//
// Created by Shawn Veader on 12/11/20.
//
import Foundation
struct DayEleven2020: AdventDay {
var year = 2020
var dayNumber = 11
var dayTitle = "Seating System"
var stars = 2
func parse(_ input: String?) -> SeatMap? {
SeatMap(input)
}
func partOne(input: String?) -> Any {
guard let map = parse(input) else { return -1 }
let modeler = SeatMapModeler(map: map)
let finalGen = modeler.findFinalGeneration()
return finalGen.occupiedSeats
}
func partTwo(input: String?) -> Any {
guard let map = parse(input) else { return -1 }
let modeler = SeatMapModeler(map: map)
let finalGen = modeler.findFinalGeneration(visible: true)
return finalGen.occupiedSeats
}
}
|
// Normal Class
class NormalClass {
var h: Int?
init() {
}
}
// Define Singleton
class MySingleton {
static let sharedInstance = MySingleton()
var instanceVar: String?
init() {
println("singleton")
}
}
let a = NormalClass()
let b = NormalClass()
// two different references to different objects of the same class
let check = (a===b)
let c = MySingleton.sharedInstance
let d = MySingleton.sharedInstance
let check2 = (c===d)
|
//
// ViewController.swift
// JobSpot-iOS
//
// Created by Krista Appel and Marlow Fernandez on 9/26/17.
// Copyright © 2017-2018 JobSpot. All rights reserved.
//
import UIKit
import Firebase
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var emailAddress: UITextField!
@IBOutlet weak var inputPassword: UITextField!
let mainToCreateAcc = "mainToCreateAcc"
let mainToHome = "mainToHome"
var handle: FIRAuthStateDidChangeListenerHandle?
var email : String = " "
var rootRef: FIRDatabaseReference!
@IBOutlet weak var loginOutlet: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
rootRef = FIRDatabase.database().reference()
loginOutlet.backgroundColor = UIColor(hex: "CC0000")
self.navigationItem.setHidesBackButton(true, animated: false)
self.dismissKeyboardTapped()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonLogin(_ sender: UIButton) {
debugPrint("button login pressed")
email = emailAddress.text!
let password = inputPassword.text
if email != "" && password != "" {
FIRAuth.auth()?.signIn(withEmail: email, password: password!) { (user, error) in
if error != nil {
debugPrint("not able to login")
let loginError = UIAlertController(title: "Login Error", message: "Error logging in: "+(error?.localizedDescription)!+" Do you have an account? Please register", preferredStyle: UIAlertControllerStyle.alert)
loginError.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(loginError, animated: true, completion: nil)
return
}
debugPrint("able to login")
//self.performSegue(withIdentifier: self.mainToHome, sender: nil)
}
debugPrint(email,password!)
emailAddress.text = ""
inputPassword.text = ""
} else {
let emptyFields = UIAlertController(title: "Error", message: "Enter text into email and/or password fields", preferredStyle: UIAlertControllerStyle.alert)
emptyFields.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(emptyFields, animated: true, completion: nil)
}
}
@IBAction func registerButtonAction(_ sender: Any) {
self.performSegue(withIdentifier: self.mainToCreateAcc, sender: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
debugPrint("viewWillAppear")
handle = FIRAuth.auth()?.addStateDidChangeListener() { (auth, user) in
if user != nil {
let userID = FIRAuth.auth()?.currentUser?.uid
let usersRef = self.rootRef.child("users")
let idRef = usersRef.child(userID!)
let listRef = idRef.child("email")
//TODO: check if email name is already there before setting...
//listRef.setValue(self.email)
self.performSegue(withIdentifier: self.mainToHome, sender: nil)
debugPrint(user?.email! as Any)
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
debugPrint("viewWillDisappear")
FIRAuth.auth()?.removeStateDidChangeListener(handle!)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return true
}
}
extension UIViewController {
func dismissKeyboardTapped() {
let tapBG: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tapBG.cancelsTouchesInView = false
view.addGestureRecognizer(tapBG)
}
func dismissKeyboard() {
view.endEditing(true)
}
}
|
//
// main.swift
// Wii Fit Data
//
// Created by Tristan Beaton on 8/01/18.
// Copyright © 2018 Tristan Beaton. All rights reserved.
//
import Foundation
let path = "/Users/tristanbeaton/Desktop/0001000452465050/FitPlus0.dat"
let profiles = WiiFitProfile.extract(file: path)
profiles.forEach { print(); print($0) }
|
/*
First-in first-out queue (FIFO)
New elements are added to the end of the queue. Dequeuing pulls elements from
the front of the queue.
Enqueuing is an O(1) operation, dequeuing is O(n). Note: If the queue had been
implemented with a linked list, then both would be O(1).
Tried to make it as similar as possible to java.util Queue:
https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html
*/
public struct Queue<T> {
fileprivate var array = [T]()
public var count: Int {
return array.count
}
public var isEmpty: Bool {
return array.isEmpty
}
public mutating func add(_ element: T) {
array.append(element)
}
public mutating func remove() throws -> T {
if isEmpty {
throw QueueError.NoSuchElementException
} else {
return array.removeFirst()
}
}
public func element() throws -> T {
guard let first = array.first else{
throw QueueError.NoSuchElementException
}
return first
}
public mutating func offer(_ element: T) -> Bool {
do{
try array.append(element)
}catch{
return false
}
return true
}
public mutating func poll() -> T? {
if isEmpty {
return nil
} else {
return array.removeFirst()
}
}
public func peek() -> T? {
if isEmpty {
return nil
} else {
return array.first
}
}
}
enum QueueError: Error{
case NoSuchElementException
}
|
//
// UIButton.swift
// ShapeApp
//
// Created by Sam on 15/09/2016.
// Copyright © 2016 Sam Payne. All rights reserved.
//
import UIKit
public extension UIButton {
convenience init(title:String, font:UIFont){
self.init(title: title)
self.titleLabel?.font = font
self.titleLabel?.sizeToFit()
self.sizeToFit()
}
func setImage(image:UIImage) {
setImage(image, for: UIControlState.normal)
}
func setImage(named imageName:String){
setImage(UIImage(named: imageName), for: UIControlState.normal)
}
convenience init(title:String, font:UIFont, colour:UIColor){
self.init(title: title, font: font)
self.setTitleColor(colour, for: UIControlState())
self.titleLabel?.sizeToFit()
self.sizeToFit()
}
convenience init(title:String){
self.init(frame: CGRect.zero)
self.setTitle(title, for: UIControlState())
self.titleLabel?.sizeToFit()
self.sizeToFit()
}
}
|
//
// File.swift
// NavigationSystem
//
// Created by Marcelo Martimiano Junior on 23/03/2018.
// Copyright © 2018 Marcelo. All rights reserved.
//
import Foundation
import SpriteKit
class Overlay: SKScene {
public var speedLabel: SKLabelNode!
public var angle: SKLabelNode!
public var left: SKSpriteNode!
public var right: SKSpriteNode!
public var brake: SKSpriteNode!
public var speedNode: SKSpriteNode!
public var controlDelegate: control!
override func didMove(to view: SKView) {
self.initialize()
self.left = self.childNode(withName: "left") as! SKSpriteNode
self.left.isUserInteractionEnabled = true
self.speedNode = self.childNode(withName: "speedbutton") as! SKSpriteNode
self.speedNode.isUserInteractionEnabled = true
self.right = self.childNode(withName: "right") as! SKSpriteNode
self.right.isUserInteractionEnabled = true
self.brake = self.childNode(withName: "brake") as! SKSpriteNode
self.brake.isUserInteractionEnabled = true
}
func initialize() {
self.speedLabel = self.childNode(withName: "speed") as! SKLabelNode
self.angle = self.childNode(withName: "angle") as! SKLabelNode
}
}
extension SKSpriteNode {
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let radius: Float = 10
if let overlay = self.parent as? Overlay {
if self.name == "brake"{
overlay.controlDelegate.brake()
}
else if self.name == "speedbutton" {
overlay.controlDelegate.setSpeed(a: 30)
}
else if self.name == "left" {
overlay.controlDelegate.turnCar(radius: radius, side: .left, a: 90)
}
else {
overlay.controlDelegate.turnCar(radius: radius, side: .right, a: 90)
}
}
}
}
|
//
// KingfisherViewController.swift
// RXSwiftDemo
//
// Created by mkrq-yh on 2019/8/30.
// Copyright © 2019 mkrq-yh. All rights reserved.
//
import UIKit
import Kingfisher
class KingfisherViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://img8.zol.com.cn/bbs/upload/17400/17399809.JPG")
// self.imageView.kf.setImage(with: url)
// self.imageView.kf.setImage(with: url,placeholder: UIImage(named: "lyf"))
self.imageView.kf.setImage(with: url, options: [.transition(.fade(0.5))])
}
}
|
//
// Builder.swift
// Uala
//
// Created by Miguel Angel Olmedo Perez on 02/03/21.
//
import Foundation
protocol BuilderProtocol {
associatedtype ViewController
}
extension BuilderProtocol where Self.ViewController: ViewControllerProtocol {
static func build(with dataSource: ViewController.ViewModel.DataSource) -> Self.ViewController {
let viewController = ViewController.instantiate()
let router = ViewController.ViewModel.Router(viewController: viewController)
viewController.configure(with: ViewController.ViewModel(dataSource: dataSource, router: router))
return viewController
}
}
|
//
// ColorsCollectionViewDelegate.swift
// Photo Editor
//
// Created by Mohamed Hamed on 5/1/17.
// Copyright © 2017 Mohamed Hamed. All rights reserved.
//
import UIKit
class ColorsCollectionViewDelegate: NSObject, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
var colorDelegate: ColorDelegate?
/**
Array of Colors that will show while drawing or typing
*/
var colors = [UIColor.black,
UIColor.darkGray,
UIColor.gray,
UIColor.lightGray,
UIColor.white,
UIColor.blue,
UIColor.green,
UIColor.red,
UIColor.yellow,
UIColor.orange,
UIColor.purple,
UIColor.cyan,
UIColor.brown,
UIColor.magenta]
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return colors.count
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
colorDelegate?.didSelectColor(color: colors[indexPath.item])
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ColorCollectionViewCell", for: indexPath) as! ColorCollectionViewCell
cell.colorView.backgroundColor = colors[indexPath.item]
return cell
}
}
extension UICollectionView {
func deselectAllItems(animated: Bool) {
guard let selectedItems = indexPathsForSelectedItems else { return }
for indexPath in selectedItems { deselectItem(at: indexPath, animated: animated) }
}
}
|
//
// MultiplicationTests.swift
// RDHDecimalNumberOperations
//
// Created by Richard Hodgkins on 29/11/2014.
// Copyright (c) 2014 Rich H. All rights reserved.
//
import Foundation
#if os(watchOS)
// No testing supported
@testable import RDHDecimalNumberOperations
#else
import XCTest
#if DEBUG
@testable import RDHDecimalNumberOperations
#else
import RDHDecimalNumberOperations
#endif
class MultiplicationTests: XCTestCase {
// MARK: - Infix
func testPositiveNumbers() {
XCTAssertEqual(NSDecimalNumber.one() * NSDecimalNumber.one(), NSDecimalNumber.one().decimalNumberByMultiplyingBy(NSDecimalNumber.one()), "Incorrect")
XCTAssertEqual(NSDecimalNumber.one() * NSDecimalNumber.zero(), NSDecimalNumber.one().decimalNumberByMultiplyingBy(NSDecimalNumber.zero()), "Incorrect")
let leftNumber = NSDecimalNumber(string: "4")
let rightNumber = NSDecimalNumber(string: "6.5")
XCTAssertEqual(leftNumber * rightNumber, leftNumber.decimalNumberByMultiplyingBy(rightNumber), "Incorrect")
// Associativity
XCTAssertEqual(rightNumber * leftNumber, rightNumber.decimalNumberByMultiplyingBy(leftNumber), "Incorrect")
XCTAssertEqual(leftNumber * NSDecimalNumber.one(), leftNumber, "Should not change")
XCTAssertEqual(leftNumber * NSDecimalNumber.zero(), NSDecimalNumber.zero(), "Should not change")
XCTAssertEqual(NSDecimalNumber.zero() * NSDecimalNumber.zero(), NSDecimalNumber.zero(), "Should be zero")
}
func testNegativeNumbers() {
XCTAssertEqual(NSDecimalNumber.minusOne * NSDecimalNumber.minusOne, NSDecimalNumber.minusOne.decimalNumberByMultiplyingBy(NSDecimalNumber.minusOne), "Incorrect")
let leftNumber = NSDecimalNumber(string: "-8")
let rightNumber = NSDecimalNumber(string: "-7.9")
XCTAssertEqual(leftNumber * rightNumber, leftNumber.decimalNumberByMultiplyingBy(rightNumber), "Incorrect")
// Associativity
XCTAssertEqual(rightNumber * leftNumber, rightNumber.decimalNumberByMultiplyingBy(leftNumber), "Incorrect")
XCTAssertEqual(leftNumber * NSDecimalNumber.one(), leftNumber, "Should not change")
XCTAssertEqual(leftNumber * NSDecimalNumber.zero(), NSDecimalNumber.zero(), "Should not change")
}
func testPostiveToNegativeNumbers() {
XCTAssertEqual(NSDecimalNumber.one() * NSDecimalNumber.minusOne, NSDecimalNumber.one().decimalNumberByMultiplyingBy(NSDecimalNumber.minusOne), "Incorrect")
let leftNumber = NSDecimalNumber(string: "12")
let rightNumber = NSDecimalNumber(string: "-90.1")
XCTAssertEqual(leftNumber * rightNumber, leftNumber.decimalNumberByMultiplyingBy(rightNumber), "Incorrect")
// Associativity
XCTAssertEqual(rightNumber * leftNumber, rightNumber.decimalNumberByMultiplyingBy(leftNumber), "Incorrect")
}
func testNegativeToPostiveNumbers() {
XCTAssertEqual(NSDecimalNumber.minusOne * NSDecimalNumber.one(), NSDecimalNumber.minusOne.decimalNumberByMultiplyingBy(NSDecimalNumber.one()), "Incorrect")
let leftNumber = NSDecimalNumber(string: "-12122.32")
let rightNumber = NSDecimalNumber(string: "23")
XCTAssertEqual(leftNumber * rightNumber, leftNumber.decimalNumberByMultiplyingBy(rightNumber), "Incorrect")
// Associativity
XCTAssertEqual(rightNumber * leftNumber, rightNumber.decimalNumberByMultiplyingBy(leftNumber), "Incorrect")
}
// MARK: - Assignment
func testAssignmentWithPositiveNumbers() {
let leftNumber = NSDecimalNumber(string: "4")
let rightNumber = NSDecimalNumber(string: "6.5")
var result = leftNumber
result *= rightNumber
XCTAssertEqual(result, leftNumber.decimalNumberByMultiplyingBy(rightNumber), "Incorrect")
result *= NSDecimalNumber.one()
XCTAssertEqual(result, result, "Should not change")
result *= NSDecimalNumber.zero()
XCTAssertEqual(result, NSDecimalNumber.zero(), "Should be zero")
}
func testAssignmentWithNegativeNumbers() {
let leftNumber = NSDecimalNumber(string: "-8")
let rightNumber = NSDecimalNumber(string: "-7.9")
var result = leftNumber
result *= rightNumber
XCTAssertEqual(result, leftNumber.decimalNumberByMultiplyingBy(rightNumber), "Incorrect")
result *= NSDecimalNumber.one()
XCTAssertEqual(result, result, "Should not change")
result *= NSDecimalNumber.zero()
XCTAssertEqual(result, NSDecimalNumber.zero(), "Should be zero")
}
func testAssignmentWithPostiveToNegativeNumbers() {
let leftNumber = NSDecimalNumber(string: "12")
let rightNumber = NSDecimalNumber(string: "-90.1")
var result = leftNumber
result *= rightNumber
XCTAssertEqual(result, leftNumber.decimalNumberByMultiplyingBy(rightNumber), "Incorrect")
result *= NSDecimalNumber.one()
XCTAssertEqual(result, result, "Should not change")
result *= NSDecimalNumber.zero()
XCTAssertEqual(result, NSDecimalNumber.zero(), "Should be zero")
}
func testAssignmentWithNegativeToPostiveNumbers() {
let leftNumber = NSDecimalNumber(string: "-12122.32")
let rightNumber = NSDecimalNumber(string: "23")
var result = leftNumber
result *= rightNumber
XCTAssertEqual(result, leftNumber.decimalNumberByMultiplyingBy(rightNumber), "Incorrect")
result *= NSDecimalNumber.one()
XCTAssertEqual(result, result, "Should not change")
result *= NSDecimalNumber.zero()
XCTAssertEqual(result, NSDecimalNumber.zero(), "Should be zero")
}
// MARK: - Overflow
func testOverflow() {
let leftNumber = NSDecimalNumber.maximumDecimalNumber()
let rightNumber = NSDecimalNumber.maximumDecimalNumber()
XCTAssertEqual(leftNumber &* rightNumber, NSDecimalNumber.notANumber(), "Should not throw an exception and be NaN")
}
}
#endif
|
//
// This is a generated file, do not edit!
// Generated by R.swift, see https://github.com/mac-cain13/R.swift
//
import Foundation
import Rswift
import UIKit
/// This `R` struct is generated and contains references to static resources.
struct R: Rswift.Validatable {
fileprivate static let applicationLocale = hostingBundle.preferredLocalizations.first.flatMap { Locale(identifier: $0) } ?? Locale.current
fileprivate static let hostingBundle = Bundle(for: R.Class.self)
/// Find first language and bundle for which the table exists
fileprivate static func localeBundle(tableName: String, preferredLanguages: [String]) -> (Foundation.Locale, Foundation.Bundle)? {
// Filter preferredLanguages to localizations, use first locale
var languages = preferredLanguages
.map { Locale(identifier: $0) }
.prefix(1)
.flatMap { locale -> [String] in
if hostingBundle.localizations.contains(locale.identifier) {
if let language = locale.languageCode, hostingBundle.localizations.contains(language) {
return [locale.identifier, language]
} else {
return [locale.identifier]
}
} else if let language = locale.languageCode, hostingBundle.localizations.contains(language) {
return [language]
} else {
return []
}
}
// If there's no languages, use development language as backstop
if languages.isEmpty {
if let developmentLocalization = hostingBundle.developmentLocalization {
languages = [developmentLocalization]
}
} else {
// Insert Base as second item (between locale identifier and languageCode)
languages.insert("Base", at: 1)
// Add development language as backstop
if let developmentLocalization = hostingBundle.developmentLocalization {
languages.append(developmentLocalization)
}
}
// Find first language for which table exists
// Note: key might not exist in chosen language (in that case, key will be shown)
for language in languages {
if let lproj = hostingBundle.url(forResource: language, withExtension: "lproj"),
let lbundle = Bundle(url: lproj)
{
let strings = lbundle.url(forResource: tableName, withExtension: "strings")
let stringsdict = lbundle.url(forResource: tableName, withExtension: "stringsdict")
if strings != nil || stringsdict != nil {
return (Locale(identifier: language), lbundle)
}
}
}
// If table is available in main bundle, don't look for localized resources
let strings = hostingBundle.url(forResource: tableName, withExtension: "strings", subdirectory: nil, localization: nil)
let stringsdict = hostingBundle.url(forResource: tableName, withExtension: "stringsdict", subdirectory: nil, localization: nil)
if strings != nil || stringsdict != nil {
return (applicationLocale, hostingBundle)
}
// If table is not found for requested languages, key will be shown
return nil
}
/// Load string from Info.plist file
fileprivate static func infoPlistString(path: [String], key: String) -> String? {
var dict = hostingBundle.infoDictionary
for step in path {
guard let obj = dict?[step] as? [String: Any] else { return nil }
dict = obj
}
return dict?[key] as? String
}
static func validate() throws {
try intern.validate()
}
#if os(iOS) || os(tvOS)
/// This `R.segue` struct is generated, and contains static references to 1 view controllers.
struct segue {
/// This struct is generated for `MainViewController`, and contains static references to 1 segues.
struct mainViewController {
/// Segue identifier `DetailView`.
static let detailView: Rswift.StoryboardSegueIdentifier<UIKit.UIStoryboardSegue, MainViewController, DetailsViewController> = Rswift.StoryboardSegueIdentifier(identifier: "DetailView")
#if os(iOS) || os(tvOS)
/// Optionally returns a typed version of segue `DetailView`.
/// Returns nil if either the segue identifier, the source, destination, or segue types don't match.
/// For use inside `prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)`.
static func detailView(segue: UIKit.UIStoryboardSegue) -> Rswift.TypedStoryboardSegueInfo<UIKit.UIStoryboardSegue, MainViewController, DetailsViewController>? {
return Rswift.TypedStoryboardSegueInfo(segueIdentifier: R.segue.mainViewController.detailView, segue: segue)
}
#endif
fileprivate init() {}
}
fileprivate init() {}
}
#endif
#if os(iOS) || os(tvOS)
/// This `R.storyboard` struct is generated, and contains static references to 3 storyboards.
struct storyboard {
/// Storyboard `DetailsViewController`.
static let detailsViewController = _R.storyboard.detailsViewController()
/// Storyboard `LaunchScreen`.
static let launchScreen = _R.storyboard.launchScreen()
/// Storyboard `MainViewController`.
static let mainViewController = _R.storyboard.mainViewController()
#if os(iOS) || os(tvOS)
/// `UIStoryboard(name: "DetailsViewController", bundle: ...)`
static func detailsViewController(_: Void = ()) -> UIKit.UIStoryboard {
return UIKit.UIStoryboard(resource: R.storyboard.detailsViewController)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIStoryboard(name: "LaunchScreen", bundle: ...)`
static func launchScreen(_: Void = ()) -> UIKit.UIStoryboard {
return UIKit.UIStoryboard(resource: R.storyboard.launchScreen)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIStoryboard(name: "MainViewController", bundle: ...)`
static func mainViewController(_: Void = ()) -> UIKit.UIStoryboard {
return UIKit.UIStoryboard(resource: R.storyboard.mainViewController)
}
#endif
fileprivate init() {}
}
#endif
/// This `R.color` struct is generated, and contains static references to 1 colors.
struct color {
/// Color `AccentColor`.
static let accentColor = Rswift.ColorResource(bundle: R.hostingBundle, name: "AccentColor")
#if os(iOS) || os(tvOS)
/// `UIColor(named: "AccentColor", bundle: ..., traitCollection: ...)`
@available(tvOS 11.0, *)
@available(iOS 11.0, *)
static func accentColor(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIColor? {
return UIKit.UIColor(resource: R.color.accentColor, compatibleWith: traitCollection)
}
#endif
fileprivate init() {}
}
/// This `R.image` struct is generated, and contains static references to 4 images.
struct image {
/// Image `back`.
static let back = Rswift.ImageResource(bundle: R.hostingBundle, name: "back")
/// Image `bike`.
static let bike = Rswift.ImageResource(bundle: R.hostingBundle, name: "bike")
/// Image `dot`.
static let dot = Rswift.ImageResource(bundle: R.hostingBundle, name: "dot")
/// Image `padlock`.
static let padlock = Rswift.ImageResource(bundle: R.hostingBundle, name: "padlock")
#if os(iOS) || os(tvOS)
/// `UIImage(named: "back", bundle: ..., traitCollection: ...)`
static func back(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.back, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "bike", bundle: ..., traitCollection: ...)`
static func bike(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.bike, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "dot", bundle: ..., traitCollection: ...)`
static func dot(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.dot, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "padlock", bundle: ..., traitCollection: ...)`
static func padlock(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.padlock, compatibleWith: traitCollection)
}
#endif
fileprivate init() {}
}
/// This `R.nib` struct is generated, and contains static references to 2 nibs.
struct nib {
/// Nib `TableViewCell`.
static let tableViewCell = _R.nib._TableViewCell()
/// Nib `TopBar`.
static let topBar = _R.nib._TopBar()
#if os(iOS) || os(tvOS)
/// `UINib(name: "TableViewCell", in: bundle)`
@available(*, deprecated, message: "Use UINib(resource: R.nib.tableViewCell) instead")
static func tableViewCell(_: Void = ()) -> UIKit.UINib {
return UIKit.UINib(resource: R.nib.tableViewCell)
}
#endif
#if os(iOS) || os(tvOS)
/// `UINib(name: "TopBar", in: bundle)`
@available(*, deprecated, message: "Use UINib(resource: R.nib.topBar) instead")
static func topBar(_: Void = ()) -> UIKit.UINib {
return UIKit.UINib(resource: R.nib.topBar)
}
#endif
static func tableViewCell(owner ownerOrNil: AnyObject?, options optionsOrNil: [UINib.OptionsKey : Any]? = nil) -> TableViewCell? {
return R.nib.tableViewCell.instantiate(withOwner: ownerOrNil, options: optionsOrNil)[0] as? TableViewCell
}
static func topBar(owner ownerOrNil: AnyObject?, options optionsOrNil: [UINib.OptionsKey : Any]? = nil) -> UIKit.UIView? {
return R.nib.topBar.instantiate(withOwner: ownerOrNil, options: optionsOrNil)[0] as? UIKit.UIView
}
fileprivate init() {}
}
/// This `R.reuseIdentifier` struct is generated, and contains static references to 1 reuse identifiers.
struct reuseIdentifier {
/// Reuse identifier `tableViewCell`.
static let tableViewCell: Rswift.ReuseIdentifier<TableViewCell> = Rswift.ReuseIdentifier(identifier: "tableViewCell")
fileprivate init() {}
}
fileprivate struct intern: Rswift.Validatable {
fileprivate static func validate() throws {
try _R.validate()
}
fileprivate init() {}
}
fileprivate class Class {}
fileprivate init() {}
}
struct _R: Rswift.Validatable {
static func validate() throws {
#if os(iOS) || os(tvOS)
try nib.validate()
#endif
#if os(iOS) || os(tvOS)
try storyboard.validate()
#endif
}
#if os(iOS) || os(tvOS)
struct nib: Rswift.Validatable {
static func validate() throws {
try _TableViewCell.validate()
try _TopBar.validate()
}
struct _TableViewCell: Rswift.NibResourceType, Rswift.ReuseIdentifierType, Rswift.Validatable {
typealias ReusableType = TableViewCell
let bundle = R.hostingBundle
let identifier = "tableViewCell"
let name = "TableViewCell"
func firstView(owner ownerOrNil: AnyObject?, options optionsOrNil: [UINib.OptionsKey : Any]? = nil) -> TableViewCell? {
return instantiate(withOwner: ownerOrNil, options: optionsOrNil)[0] as? TableViewCell
}
static func validate() throws {
if UIKit.UIImage(named: "bike", in: R.hostingBundle, compatibleWith: nil) == nil { throw Rswift.ValidationError(description: "[R.swift] Image named 'bike' is used in nib 'TableViewCell', but couldn't be loaded.") }
if UIKit.UIImage(named: "dot", in: R.hostingBundle, compatibleWith: nil) == nil { throw Rswift.ValidationError(description: "[R.swift] Image named 'dot' is used in nib 'TableViewCell', but couldn't be loaded.") }
if UIKit.UIImage(named: "padlock", in: R.hostingBundle, compatibleWith: nil) == nil { throw Rswift.ValidationError(description: "[R.swift] Image named 'padlock' is used in nib 'TableViewCell', but couldn't be loaded.") }
if #available(iOS 11.0, tvOS 11.0, *) {
}
}
fileprivate init() {}
}
struct _TopBar: Rswift.NibResourceType, Rswift.Validatable {
let bundle = R.hostingBundle
let name = "TopBar"
func firstView(owner ownerOrNil: AnyObject?, options optionsOrNil: [UINib.OptionsKey : Any]? = nil) -> UIKit.UIView? {
return instantiate(withOwner: ownerOrNil, options: optionsOrNil)[0] as? UIKit.UIView
}
static func validate() throws {
if UIKit.UIImage(named: "back", in: R.hostingBundle, compatibleWith: nil) == nil { throw Rswift.ValidationError(description: "[R.swift] Image named 'back' is used in nib 'TopBar', but couldn't be loaded.") }
if #available(iOS 11.0, tvOS 11.0, *) {
}
}
fileprivate init() {}
}
fileprivate init() {}
}
#endif
#if os(iOS) || os(tvOS)
struct storyboard: Rswift.Validatable {
static func validate() throws {
#if os(iOS) || os(tvOS)
try detailsViewController.validate()
#endif
#if os(iOS) || os(tvOS)
try launchScreen.validate()
#endif
#if os(iOS) || os(tvOS)
try mainViewController.validate()
#endif
}
#if os(iOS) || os(tvOS)
struct detailsViewController: Rswift.StoryboardResourceWithInitialControllerType, Rswift.Validatable {
typealias InitialController = DetailsViewController
let bundle = R.hostingBundle
let detailsViewControllerv = StoryboardViewControllerResource<DetailsViewController>(identifier: "DetailsViewControllerv")
let name = "DetailsViewController"
func detailsViewControllerv(_: Void = ()) -> DetailsViewController? {
return UIKit.UIStoryboard(resource: self).instantiateViewController(withResource: detailsViewControllerv)
}
static func validate() throws {
if UIKit.UIImage(named: "bike", in: R.hostingBundle, compatibleWith: nil) == nil { throw Rswift.ValidationError(description: "[R.swift] Image named 'bike' is used in storyboard 'DetailsViewController', but couldn't be loaded.") }
if UIKit.UIImage(named: "dot", in: R.hostingBundle, compatibleWith: nil) == nil { throw Rswift.ValidationError(description: "[R.swift] Image named 'dot' is used in storyboard 'DetailsViewController', but couldn't be loaded.") }
if UIKit.UIImage(named: "padlock", in: R.hostingBundle, compatibleWith: nil) == nil { throw Rswift.ValidationError(description: "[R.swift] Image named 'padlock' is used in storyboard 'DetailsViewController', but couldn't be loaded.") }
if #available(iOS 11.0, tvOS 11.0, *) {
}
if _R.storyboard.detailsViewController().detailsViewControllerv() == nil { throw Rswift.ValidationError(description:"[R.swift] ViewController with identifier 'detailsViewControllerv' could not be loaded from storyboard 'DetailsViewController' as 'DetailsViewController'.") }
}
fileprivate init() {}
}
#endif
#if os(iOS) || os(tvOS)
struct launchScreen: Rswift.StoryboardResourceWithInitialControllerType, Rswift.Validatable {
typealias InitialController = UIKit.UIViewController
let bundle = R.hostingBundle
let name = "LaunchScreen"
static func validate() throws {
if #available(iOS 11.0, tvOS 11.0, *) {
}
}
fileprivate init() {}
}
#endif
#if os(iOS) || os(tvOS)
struct mainViewController: Rswift.StoryboardResourceWithInitialControllerType, Rswift.Validatable {
typealias InitialController = UIKit.UINavigationController
let bundle = R.hostingBundle
let name = "MainViewController"
static func validate() throws {
if #available(iOS 11.0, tvOS 11.0, *) {
}
}
fileprivate init() {}
}
#endif
fileprivate init() {}
}
#endif
fileprivate init() {}
}
|
//
// ALKit.swift
// AutolayoutPlayground
//
// Created by Cem Olcay on 22/10/15.
// Copyright © 2015 prototapp. All rights reserved.
//
// https://www.github.com/cemolcay/ALKit
//
import UIKit
public extension UIEdgeInsets {
/// Equal insets for all edges.
init(inset: CGFloat) {
self.init()
top = inset
bottom = inset
left = inset
right = inset
}
}
public extension UIView{
/// Auto layout wrapper function to pin a view's edge to another view's edge.
///
/// - Parameters:
/// - edge: View's edge is going to be pinned.
/// - toEdge: Pinning edge of other view.
/// - ofView: The view to be pinned.
/// - withInset: Space between pinning edges.
func pin(
edge: NSLayoutConstraint.Attribute,
toEdge: NSLayoutConstraint.Attribute,
ofView: UIView?,
withInset: CGFloat = 0) {
guard let view = superview else {
return assertionFailure("view must be added as subview in view hierarchy")
}
view.addConstraint(NSLayoutConstraint(
item: self,
attribute: edge,
relatedBy: .equal,
toItem: ofView,
attribute: toEdge,
multiplier: 1,
constant: withInset))
}
// MARK: Pin Super
/// Pins right edge of view to other view's right edge.
///
/// - Parameters:
/// - view: The view going to be pinned.
/// - inset: Space between edges.
func pinRight(to view: UIView, inset: CGFloat = 0) {
pin(edge: .right, toEdge: .right, ofView: view, withInset: -inset)
}
/// Pins left edge of view to other view's left edge.
///
/// - Parameters:
/// - view: The view going to be pinned.
/// - inset: Space between edges.
func pinLeft(to view: UIView, inset: CGFloat = 0) {
pin(edge: .left, toEdge: .left, ofView: view, withInset: inset)
}
/// Pins top edge of view to other view's top edge.
///
/// - Parameters:
/// - view: The view going to be pinned.
/// - inset: Space between edges.
func pinTop(to view: UIView, inset: CGFloat = 0) {
pin(edge: .top, toEdge: .top, ofView: view, withInset: inset)
}
/// Pins bottom edge of view to other view's bottom edge.
///
/// - Parameters:
/// - view: The view going to be pinned.
/// - inset: Space between edges.
func pinBottom(to view: UIView, inset: CGFloat = 0) {
pin(edge: .bottom, toEdge: .bottom, ofView: view, withInset: -inset)
}
// MARK: Pin To Another View In Super
/// Pins left edge of view to other view's right edge.
///
/// - Parameters:
/// - view: The view going to be pinned.
/// - inset: Space between edges.
func pinToRight(of view: UIView, offset: CGFloat = 0) {
pin(edge: .left, toEdge: .right, ofView: view, withInset: offset)
}
/// Pins right edge of view to other view's left edge.
///
/// - Parameters:
/// - view: The view going to be pinned.
/// - inset: Space between edges.
func pinToLeft(of view: UIView, offset: CGFloat = 0) {
pin(edge: .right, toEdge: .left, ofView: view, withInset: -offset)
}
/// Pins bottom edge of view to other view's top edge.
///
/// - Parameters:
/// - view: The view going to be pinned.
/// - inset: Space between edges.
func pinToTop(of view: UIView, offset: CGFloat = 0) {
pin(edge: .bottom, toEdge: .top, ofView: view, withInset: -offset)
}
/// Pins top edge of view to other view's bottom edge.
///
/// - Parameters:
/// - view: The view going to be pinned.
/// - inset: Space between edges.
func pinToBottom(of view: UIView, offset: CGFloat = 0) {
pin(edge: .top, toEdge: .bottom, ofView: view, withInset: offset)
}
// MARK: Fill In Super
/// Pins all edges of the view to other view's edges with insets.
///
/// - Parameters:
/// - view: The view is going to be pinned.
/// - insets: Spaces between edges.
func fill(to view: UIView, insets: UIEdgeInsets = .zero) {
pinLeft(to: view, inset: insets.left)
pinRight(to: view, inset: insets.right)
pinTop(to: view, inset: insets.top)
pinBottom(to: view, inset: insets.bottom)
}
/// Pins left and right edges of the view to other view's left and right edges with equal insets.
///
/// - Parameters:
/// - view: The view is going to be pinned.
/// - insets: Equal insets between left and right edges.
func fillHorizontal(to view: UIView, insets: CGFloat = 0) {
pinRight(to: view, inset: insets)
pinLeft(to: view, inset: insets)
}
/// Pins top and bottom edges of the view to other view's top and bottom edges with equal insets.
///
/// - Parameters:
/// - view: The view is going to be pinned.
/// - insets: Equal insets between top and bottom edges.
func fillVertical(to view: UIView, insets: CGFloat = 0) {
pinTop(to: view, inset: insets)
pinBottom(to: view, inset: insets)
}
// MARK: Size
/// Pins width and height of the view to constant width and height values.
///
/// - Parameters:
/// - width: Width constant.
/// - height: Height constant.
func pinSize(width: CGFloat, height: CGFloat) {
pinWidth(width: width)
pinHeight(height: height)
}
/// Pins width of the view to constant width value.
///
/// - Parameter width: Width constant.
func pinWidth(width: CGFloat) {
pin(edge: .width, toEdge: .notAnAttribute, ofView: nil, withInset: width)
}
/// Pins height of the view to constant width value.
///
/// - Parameter height: Height constant.
func pinHeight(height: CGFloat) {
pin(edge: .height, toEdge: .notAnAttribute, ofView: nil, withInset: height)
}
// MARK: Center
/// Pins center of the view to other view's center.
///
/// - Parameter view: The view is going to be pinned.
func pinCenter(to view: UIView) {
pinCenterX(to: view)
pinCenterY(to: view)
}
/// Pins horizontally center the view to other view's center.
///
/// - Parameter view: The view is going to be pinned.
func pinCenterX(to view: UIView) {
pin(edge: .centerX, toEdge: .centerX, ofView: view)
}
/// Pins vertically center of the view to other view's center.
///
/// - Parameter view: The view is going to be pinned.
func pinCenterY(to view: UIView) {
pin(edge: .centerY, toEdge: .centerY, ofView: view)
}
}
|
import Foundation
struct LSRange<Bound: Comparable & Numeric>: Equatable {
var begin: Bound
var end: Bound
init(begin: Bound, length: Bound) {
assert(length >= 0)
self.init(begin: begin, end: begin + length)
}
init(begin: Bound, end: Bound) {
assert(end >= begin)
self.begin = begin
self.end = end
}
var length: Bound {
return end - begin
}
func contains(_ value: Bound) -> Bool {
return value >= begin && value < end
}
func contains(_ otherRange: LSRange<Bound>) -> Bool {
return begin <= otherRange.begin && end >= otherRange.end
}
func intersects(_ otherRange: LSRange<Bound>) -> Bool {
return contains(otherRange.begin) || contains(otherRange.end) || otherRange.contains(self)
}
func intersection(_ otherRange: LSRange<Bound>) -> LSRange<Bound>? {
guard intersects(otherRange) else {
return nil
}
var begin = self.begin
var end = self.end
if contains(otherRange.begin) {
begin = otherRange.begin
}
if contains(otherRange.end) {
end = otherRange.end
}
return LSRange(begin: begin, end: end)
}
func subtract(_ otherRange: LSRange<Bound>) -> [LSRange<Bound>] {
if !intersects(otherRange) || otherRange.contains(self) {
return [self]
}
var ranges = [LSRange<Bound>]()
if begin < otherRange.begin {
ranges.append(LSRange(begin: begin, end: otherRange.begin))
}
if end > otherRange.end {
ranges.append(LSRange(begin: otherRange.end, end: end))
}
return ranges
}
}
extension CGSSRankedSkill {
func getUpRanges(lastNoteSec sec: Float) -> [LSRange<Float>] {
let condition: Int = skill.condition
let count = Int(ceil((sec - 3) / Float(condition)))
var ranges = [LSRange<Float>]()
for i in 0..<count {
if i == 0 { continue }
let range = LSRange(begin: Float(i * condition), length: Float(length) / 100)
ranges.append(range)
}
return ranges
}
}
|
//
// ViewController.swift
// News
//
// Created by Viacheslav Goroshniuk on 9/23/19.
// Copyright © 2019 Viacheslav Goroshniuk. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func loadNewsButtonTapped(_ sender: Any) {
let vc = NewsViewController.init(nibName: nil, bundle: nil)
self.present(vc, animated: true, completion: nil)
}
}
|
//
// CropProfileCore+CoreDataProperties.swift
//
//
// Created by Bowen He on 2018-07-30.
//
//
import Foundation
import CoreData
extension CropProfileCore {
@nonobjc public class func fetchRequest() -> NSFetchRequest<CropProfileCore> {
return NSFetchRequest<CropProfileCore>(entityName: "CropProfileCore")
}
@NSManaged public var cropName: String?
@NSManaged public var plotLength: Int16
@NSManaged public var plotWidth: Int16
@NSManaged public var profName: String?
}
|
//
// BoardViewController.swift
// se_iOS_client
//
// Created by syon on 2021/06/01.
//
import UIKit
class BoardViewController: UIViewController {
var boardList: [Board] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func getBoard() {
let url = ""
}
}
|
//
// UIImageEx.swift
// SEngage
//
// Created by Yan Wu on 5/19/16.
// Copyright © 2016 Avaya. All rights reserved.
//
import Foundation
import UIKit
extension UIImage {
enum Asset : String {
// LoinView
case Login_background = "AvayaLogoBackground"
case Login_owl = "owl-login"
case Login_owl_left_arm = "owl-login-arm-left"
case Login_owl_right_arm = "owl-login-arm-right"
case Login_owl_unhide_arm = "icon_hand"
case Login_user_handle = "iconfont-user"
case Login_password = "iconfont-password"
// Tab bar
case Tabbar_chat_unselected = "tabbar_mainframe"
case Tabbar_chat_selected = "tabbar_mainframeHL"
case Tabbar_contacts_unselected = "tabbar_contacts"
case Tabbar_contacts_selected = "tabbar_contactsHL"
case Tabbar_me_unselected = "tabbar_me"
case Tabbar_me_selected = "tabbar_meHL"
// Contacts part
case Contact_cell_unpicked = "CellGreySelected"
case Contact_cell_picked = "CellBlueSelected"
// Team Creation new team default photo is abbar_me_unselected)
// FloatView
case FloatView_background = "FloatViewBg"
case FloatView_creatTeam = "contacts_add_newmessage"
case FloatView_addContact = "barbuttonicon_add_cube"
// Chat-shareMore view
case Sharemore_pic = "sharemore_pic" // picture
case Sharemore_videovoip = "sharemore_videovoip" // videocall
case Sharemore_location = "sharemore_location" // location
case Sharemore_sight = "sharemore_sight" // sight
case Sharemore_video = "sharemore_video" // camera
case Sharemore_timeSpeak = "sharemore_wxtalk" // voice
case Sharemore_myfav = "sharemore_myfav" // favorite
case SharemorePay = "sharemorePay" // pay
case Sharemore_friendcard = "sharemore_friendcard" // friendcard
case Sharemore_other = "sharemore_otherDown"
case Sharemore_other_HL = "sharemore_otherDownHL"
// Tool Bar
case ToolBar_voicebtn = "ToolViewInputVoice"
case ToolBar_voicebtn_HL = "ToolViewInputVoiceHL"
case ToolBar_emotionbtn = "ToolViewEmotion"
case ToolBar_emotionbtn_HL = "ToolViewEmotionHL"
case ToolBar_morebtn = "TypeSelectorBtn_Black"
case ToolBar_morebtn_HL = "TypeSelectorBtnHL_Black"
case ToolBar_keyboard = "ToolViewKeyboard"
case ToolBar_keyboard_HL = "ToolViewKeyboardHL"
// Chat
case Chat_senderBackground = "SenderTextNodeBkg"
case Chat_senderBackground_HL = "SenderTextNodeBkgHL"
case Chat_receiverBackground = "ReceiverTextNodeBkg"
case Chat_receiverBackground_HL = "ReceiverTextNodeBkgHL"
case Chat_background = "bg3"
case Chat_fail = "share_auth_fail"
// Bar Buttons
case Back_icon = "back_icon"
case Barbuttonicon_add = "barbuttonicon_add"
case Barbuttonicon_addfriends = "barbuttonicon_addfriends"
case Barbuttonicon_back = "barbuttonicon_back"
case Barbuttonicon_back_cube = "barbuttonicon_back_cube"
case Barbuttonicon_call = "barbuttonicon_call"
case Barbuttonicon_Camera = "barbuttonicon_Camera"
case Barbuttonicon_Camera_Golden = "barbuttonicon_Camera_Golden"
case Barbuttonicon_delete = "barbuttonicon_delete"
case Barbuttonicon_InfoMulti = "barbuttonicon_InfoMulti"
case Barbuttonicon_InfoSingle = "barbuttonicon_InfoSingle"
case Barbuttonicon_Luckymoney = "barbuttonicon_Luckymoney"
case Barbuttonicon_mini_cube = "barbuttonicon_mini_cube"
case Barbuttonicon_more = "barbuttonicon_more"
case Barbuttonicon_more_black = "barbuttonicon_more_black"
case Barbuttonicon_more_cube = "barbuttonicon_more_cube"
case Barbuttonicon_Operate = "barbuttonicon_Operate"
case Barbuttonicon_question = "barbuttonicon_question"
case Barbuttonicon_set = "barbuttonicon_set"
var image: UIImage {
return UIImage(asset: self)
}
}
convenience init!(asset: Asset) {
self.init(named: asset.rawValue)
}
}
|
// TestHelpers.swift - Copyright 2020 SwifterSwift
enum Season: String {
case summer
case autumn
case winter
case spring
}
/**
These structs used to test ArrayExtensions and RangeReplaceableCollection.
Feel free to use it for your needs.
*/
struct SimplePerson: Equatable {
let forename, surname: String
let age: Int
}
struct Person: Equatable {
var name: String
var age: Int?
var location: Location?
var isStudent: Bool
init(name: String, age: Int?, location: Location? = nil, isStudent: Bool = false) {
self.name = name
self.age = age
self.location = location
self.isStudent = isStudent
}
}
struct Location: Equatable {
let city: String
}
struct TestStruct: ExpressibleByIntegerLiteral, Equatable {
var testField: Int = 0
typealias IntegerLiteralType = Int
init(integerLiteral value: Int) {
testField = value
}
}
|
//
// ArtsViewController.swift
// NAMU_Torch
//
// Created by Danil Kurilo on 9/26/19.
// Copyright © 2019 Danil Kurilo. All rights reserved.
//
import UIKit
import SDWebImage
class ArtsViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
let popUpContentManager = PopUpContentManager.shared
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "cell")
}
@IBAction func backButtonPressed(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
extension ArtsViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return artObjects.count
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let flowayout = collectionViewLayout as? UICollectionViewFlowLayout
let space: CGFloat = (flowayout?.minimumInteritemSpacing ?? 0.0) + (flowayout?.sectionInset.left ?? 0.0) + (flowayout?.sectionInset.right ?? 0.0)
let size:CGFloat = (collectionView.frame.size.width - space) / 2.0
return CGSize(width: size, height: size)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let row = artObjects[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCollectionViewCell
cell.isUserInteractionEnabled = false
if let artURL = row.image {
cell.artImageView.sd_setImage(with: URL(string: artURL), placeholderImage: UIImage(named: "loadingIcon"), completed: { (image, error, cacheType, imageURL) in
cell.isUserInteractionEnabled = true
})
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let vc = storyboard?.instantiateViewController(withIdentifier: "ArtDetailViewController") as? ArtDetailViewController
let rawTexts = [artObjects[indexPath.row].trigger1description, artObjects[indexPath.row].trigger2description, artObjects[indexPath.row].trigger3description, artObjects[indexPath.row].trigger4description, artObjects[indexPath.row].trigger5description]
var description = ""
for item in rawTexts {
if item != "nil" {
description = description + " " + item!
}
}
vc?.artNameText = artObjects[indexPath.row].name!
vc?.descriptionText = description
vc?.imageURL = artObjects[indexPath.row].image!
vc?.author_yearText = artObjects[indexPath.row].authoryear!
vc!.modalPresentationStyle = .fullScreen
self.present(vc!, animated: true, completion: nil)
}
}
|
//
// PhotoLoaderCellCollectionViewCell.swift
// CollectionViewWithCleanCode
//
// Created by sunil.kumar1 on 12/8/19.
// Copyright © 2019 sunil.kumar1. All rights reserved.
//
import UIKit
class LoaderCollectionCell: UICollectionViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
|
//
// ApiClient.swift
// VBD_Sample_Task
//
// Created by Rajeswari on 04/04/21.
// Copyright © 2021 Rajeswari. All rights reserved.
//
import Foundation
import RealmSwift
public struct ApiClient {
static func getDataFromServer(url: URL, completion: @escaping (_ success: Bool, _ data: [ListData]? )->()){
let request = NSMutableURLRequest(url: url as URL)
request.setValue("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", forHTTPHeaderField: "Authorization") //**
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let mData = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
if let data = data {
let decoder = JSONDecoder()
do {
let result = try decoder.decode([ListData].self, from: data)
completion(true, result)
} catch {
print(error)
}
}
}
mData.resume()
}
}
|
//
// ViewController.swift
// Quizzler-iOS13
//
// Created by Angela Yu on 12/07/2019.
// Copyright © 2019 The App Brewery. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var falseButton: UIButton!
@IBOutlet weak var trueButton: UIButton!
@IBOutlet weak var middleButton: UIButton!
@IBOutlet weak var progressBar: UIProgressView!
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
var quiz = QuizBrain()
var questionNumber = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
middleButton.isHidden = true
updateUI()
}
@IBAction func answerButtonPressed(_ sender: UIButton) {
let userAnswer = sender.currentTitle!
if(quiz.checkAnswer(userAnswer)){
sender.backgroundColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)
}
else{
sender.backgroundColor = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1)
}
DispatchQueue.main.asyncAfter(deadline: .now()+0.2){
sender.backgroundColor = UIColor.clear
}
updateUI()
}
func updateUI(){
questionLabel.text = quiz.getText()
if(quiz.getIsMultiple()){
let a = quiz.getAnswers()
trueButton.setTitle(a[0], for: .normal)
middleButton.setTitle(a[1], for: .normal)
falseButton.setTitle(a[2], for: .normal)
middleButton.isHidden = false
}
else{
trueButton.setTitle("True", for: .normal)
falseButton.setTitle("False", for: .normal)
middleButton.isHidden = true
}
progressBar.progress = quiz.getProgress()
scoreLabel.text = "Score: \(quiz.getScore())"
}
}
|
//
// InfoViewController.swift
// Container
//
// Created by Bree Jeune on 2/13/20.
// Copyright © 2020 Young. All rights reserved.
//
import UIKit
class InfoViewController: UIViewController {
@IBAction func unwindToMainInfoScreen(_ sender: UIStoryboardSegue) {
navigationController?.popToRootViewController(animated: true)
}
}
|
//
// EndpointProtocol.swift
// ios-charts-api-demo
//
// Created by Joshua de Guzman on 20/04/2018.
// Copyright © 2018 Joshua de Guzman. All rights reserved.
//
import Alamofire
protocol EndpointProtocol:URLRequestConvertible{
var method: HTTPMethod { get }
var path: String { get }
var parameters: Parameters? { get }
var headers: HTTPHeaders? { get }
}
|
//
// SelectSortOrderView.swift
// ExpenseTrackerMac
//
// Created by Alfian Losari on 28/04/20.
// Copyright © 2020 Alfian Losari. All rights reserved.
//
import SwiftUI
struct FilterCategoriesView: View {
@Binding var selectedCategories: Set<Category>
private let categories = Category.allCases
var body: some View {
ScrollView(.horizontal) {
HStack(spacing: 8) {
ForEach(categories) { category in
FilterButtonView(
category: category,
isSelected: self.selectedCategories.contains(category),
onTap: self.onTap
)
.padding(.leading, category == self.categories.first ? 16 : 0)
.padding(.trailing, category == self.categories.last ? 16 : 0)
}
}
}
}
func onTap(category: Category) {
if selectedCategories.contains(category) {
selectedCategories.remove(category)
} else {
selectedCategories.insert(category)
}
}
}
struct FilterButtonView: View {
var category: Category
var isSelected: Bool
var onTap: (Category) -> ()
var body: some View {
HStack(spacing: 4) {
Text(category.rawValue.capitalized)
.fixedSize(horizontal: true, vertical: true)
}
.padding(.horizontal, 16)
.padding(.vertical, 4)
.overlay(
RoundedRectangle(cornerRadius: 16)
.stroke(isSelected ? category.color : Color.gray, lineWidth: 1))
.frame(height: 44)
.onTapGesture {
self.onTap(self.category)
}
.foregroundColor(isSelected ? category.color : Color.gray)
}
}
struct FilterCategoriesView_Previews: PreviewProvider {
static var previews: some View {
FilterCategoriesView(selectedCategories: .constant(Set()))
}
}
|
//
// BaseModel.swift
// OneCopy
//
// Created by Mac on 16/10/8.
// Copyright © 2016年 DJY. All rights reserved.
//
import UIKit
class BaseModel: AnyObject {
}
|
//
// Copyright © 2020 Tasuku Tozawa. All rights reserved.
//
import Combine
/// @mockable
public protocol ClipItemQuery {
var clipItem: CurrentValueSubject<ClipItem, Error> { get }
}
|
//
// ViewController.swift
// DailyGrail
//
// Created by Clean Mac on 4/17/20.
// Copyright © 2020 LambdaStudent. All rights reserved.
//
import UIKit
class POIsTableViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
// Outlets and Variables
var grailCells: [POI] = []
override func viewDidLoad() {
super.viewDidLoad()
// Load data and redisplay
}
//Actions and methods
}
|
//
// ValidationErrorType.swift
// RxSignInExample
//
// Created by 洪东 on 2017/7/11.
// Copyright © 2017年 ERStone. All rights reserved.
//
import Foundation
struct ValidationError: Swift.Error {
public let message: String
public init(message m: String) {
message = m
}
}
|
//
// ThirdLibsManager.swift
// SwiftDemo
//
// Created by sam on 2020/4/7.
// Copyright © 2020 sam . All rights reserved.
//
import UIKit
/// 统一管理第三方库
final class ThirdLibsManager: NSObject {
static let shared = ThirdLibsManager()
func setup() {
}
}
|
//
// HCRecommandViewModel.swift
// HCPoems
//
// Created by cgtn on 2018/9/21.
// Copyright © 2018年 houcong. All rights reserved.
//
import UIKit
import RxSwift
struct HCRecommandViewModel: ViewModelType {
struct Input {
let page: Observable<Int>
}
struct Output {
let poemsList: Observable<[HCPoemModel]>
}
func transform(input: HCRecommandViewModel.Input) -> HCRecommandViewModel.Output {
let output = input.page.flatMap { (pageNum) -> Observable<[HCPoemModel]> in
return HCProvider.poemsList(page: pageNum)
}
return Output(poemsList: output)
}
}
|
//
// NSError.swift
// desafio-ios-thiago-sivirino
//
// Created by Thiago Augusto on 24/07/20.
// Copyright © 2020 objectivesev. All rights reserved.
//
import Foundation
extension NSError {
class func from(code: Int, data: Data, description: String) -> NSError {
let domain = Bundle.main.bundleIdentifier ?? "undefined"
let userInfo = [NSLocalizedDescriptionKey : description]
let error = NSError(domain: domain, code: code, userInfo: userInfo)
return error
}
}
|
//
// LoginController+UserActions.swift
// MobileTestPR
//
// Created by Derek Bronston on 12/18/18.
// Copyright © 2018 Freshly. All rights reserved.
//
import UIKit
extension LoginController {
@IBAction func login() {
loader(show: true)
_ = viewModel.login(email: emailField.text!, password: passwordField.text!)
}
}
|
//
// SectionHeaderView.swift
// Adcov8
//
// Created by Syafiq Mastor on 7/30/17.
// Copyright © 2017 syafiqmastor. All rights reserved.
//
import UIKit
class SectionHeaderView: UITableViewHeaderFooterView {
@IBOutlet weak var titleLabel: UILabel!
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
static var identifier: String {
return String(describing: self)
}
static var nib : UINib {
return UINib(nibName: identifier, bundle: nil)
}
}
|
import UIKit
extension UIColor{
static let colorGreen = #colorLiteral(red: 0.137254902, green: 0.7254901961, blue: 0, alpha: 1)
static let colorRed = #colorLiteral(red: 0.9176470588, green: 0.1176470588, blue: 0.1529411765, alpha: 1)
static let colorWhite = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
static let colorOffWhite = #colorLiteral(red: 0.9725490196, green: 0.9725490196, blue: 0.9725490196, alpha: 1)
static let colorBlackLighTheme = #colorLiteral(red: 0.1725490196, green: 0.1725490196, blue: 0.1921568627, alpha: 1)
static let colorCellEdit = #colorLiteral(red: 0.2235294118, green: 0.2235294118, blue: 0.2431372549, alpha: 1)
static let colorCellDelete = #colorLiteral(red: 0.2235294118, green: 0.2235294118, blue: 0.2431372549, alpha: 1)
static let colorLightGray = #colorLiteral(red: 0.5176470588, green: 0.5176470588, blue: 0.5176470588, alpha: 1)
static let colorOffLightGray = #colorLiteral(red: 0.8509803922, green: 0.8509803922, blue: 0.8509803922, alpha: 1)
static let placeHolder = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
static let bottomLine = #colorLiteral(red: 0.8470588235, green: 0.8470588235, blue: 0.8470588235, alpha: 1)
static let colorCellBG = #colorLiteral(red: 0.3803921569, green: 0.4156862745, blue: 0.4470588235, alpha: 1)
static let colorRedButton = #colorLiteral(red: 0.6745098039, green: 0.1137254902, blue: 0.137254902, alpha: 1)
static let colorLightCellBG = #colorLiteral(red: 0.8078431373, green: 0.8431372549, blue: 0.8745098039, alpha: 1)
static let colorLightGrayBG = #colorLiteral(red: 0.9450980392, green: 0.9450980392, blue: 0.9450980392, alpha: 1)
convenience init?(hexString: String) {
var chars = Array(hexString.hasPrefix("#") ? hexString.dropFirst() : hexString[...])
let red, green, blue, alpha: CGFloat
switch chars.count {
case 3:
chars = chars.flatMap { [$0, $0] }
fallthrough
case 6:
chars = ["F","F"] + chars
fallthrough
case 8:
alpha = CGFloat(strtoul(String(chars[0...1]), nil, 16)) / 255
red = CGFloat(strtoul(String(chars[2...3]), nil, 16)) / 255
green = CGFloat(strtoul(String(chars[4...5]), nil, 16)) / 255
blue = CGFloat(strtoul(String(chars[6...7]), nil, 16)) / 255
default:
return nil
}
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
|
//
// SimpleTimer.swift
// SimpleTimer
//
// Created by 刘栋 on 2018/5/4.
// Copyright © 2018年 yidongyunshi.com. All rights reserved.
//
import Dispatch
public class SimpleTimer {
public typealias SimpleTimerHandler = (SimpleTimer) -> Void
private let _timer: DispatchSourceTimer
private var _isRunning = false
private var _handler: SimpleTimerHandler
public let repeats: Bool
public init(interval: DispatchTimeInterval, repeats: Bool = false, leeway: DispatchTimeInterval = .seconds(0), queue: DispatchQueue = .main, handler: @escaping SimpleTimerHandler) {
self._handler = handler
self.repeats = repeats
_timer = DispatchSource.makeTimerSource(queue: queue)
_timer.setEventHandler { [weak self] in
guard let strongSelf = self else { return }
handler(strongSelf)
}
if repeats {
_timer.schedule(deadline: .now() + interval, repeating: interval, leeway: leeway)
} else {
_timer.schedule(deadline: .now() + interval, leeway: leeway)
}
}
deinit {
if !self._isRunning {
_timer.resume()
}
}
public func fire() {
if repeats {
_handler(self)
} else {
_handler(self)
_timer.cancel()
}
}
public func start() {
if !_isRunning {
_timer.resume()
_isRunning = true
}
}
public func suspend() {
if _isRunning {
_timer.suspend()
_isRunning = false
}
}
public func reschedule(repeating interval: DispatchTimeInterval) {
if repeats {
_timer.schedule(deadline: .now() + interval, repeating: interval)
}
}
public func reschedule(handler: @escaping SimpleTimerHandler) {
self._handler = handler
_timer.setEventHandler { [weak self] in
guard let strongSelf = self else { return }
handler(strongSelf)
}
}
}
// MARK: - Repeating Helper
extension SimpleTimer {
public static func repeating(interval: DispatchTimeInterval, leeway: DispatchTimeInterval = .seconds(0), queue: DispatchQueue = .main , handler: @escaping SimpleTimerHandler) -> SimpleTimer {
return SimpleTimer(interval: interval, repeats: true, leeway: leeway, queue: queue, handler: handler)
}
}
// MARK: - Throttle Helper
extension SimpleTimer {
private static var _timers = [String: DispatchSourceTimer]()
public static func throttle(interval: DispatchTimeInterval, identifier: String, queue: DispatchQueue = .main , handler: @escaping () -> Void) {
if let previousTimer = _timers[identifier] {
previousTimer.cancel()
_timers.removeValue(forKey: identifier)
}
let timer = DispatchSource.makeTimerSource(queue: queue)
_timers[identifier] = timer
timer.schedule(deadline: .now() + interval)
timer.setEventHandler {
handler()
timer.cancel()
_timers.removeValue(forKey: identifier)
}
timer.resume()
}
public static func cancelThrottlingTimer(identifier: String) {
if let previousTimer = _timers[identifier] {
previousTimer.cancel()
_timers.removeValue(forKey: identifier)
}
}
}
|
import UIKit
class ServiceBasicCell: EditableBasicTableViewCell {}
extension ServiceBasicCell : ServiceViewDataItemConfigurable, ServiceViewDataItemEditable {
func configure(serviceViewDataItem item: ServiceViewDataItem) {
self.textLabel?.text = item.title
self.textField.text = item.title
self.textField.placeholder = item.title
self.imageView?.image = item.icon
}
}
|
//
// FileProviderItem.swift
// SaneScanner-FileProvider
//
// Created by Stanislas Chevallier on 25/05/2021.
// Copyright © 2021 Syan. All rights reserved.
//
import FileProvider
import MobileCoreServices
extension URL {
func path(relativeTo otherURL: URL) -> String? {
guard pathComponents.count >= otherURL.pathComponents.count else { return nil }
guard Array(pathComponents[0..<otherURL.pathComponents.count]) == otherURL.pathComponents else { return nil }
return pathComponents.dropFirst(otherURL.pathComponents.count).joined(separator: "/")
}
}
class FileProviderItem: NSObject {
// MARK: Init
init(path: String) {
self.path = path
}
convenience init?(url: URL) {
guard let path = url.path(relativeTo: FileManager.galleryURL) else { return nil }
self.init(path: path)
}
convenience init?(itemIdentifier: NSFileProviderItemIdentifier) {
if itemIdentifier == .rootContainer {
self.init(path: "")
}
else {
self.init(path: itemIdentifier.rawValue)
}
}
// MARK: Properties
private let path: String
var url: URL {
FileManager.galleryURL.appendingPathComponent(path)
}
var isRoot: Bool {
return path.isEmpty
}
var isDirectory: Bool {
return (try? url.resourceValues(forKeys: Set([.isDirectoryKey])).isDirectory) == true
}
override var description: String {
return "<FileProviderItem path=\(path), isRoot=\(isRoot)>"
}
// MARK: Actions
func rename(to filename: String) throws -> FileProviderItem {
let newURL = url.deletingLastPathComponent().appendingPathComponent(filename)
guard let newItem = FileProviderItem(url: newURL) else {
throw NSFileProviderError(.noSuchItem)
}
guard !FileManager.default.fileExists(atPath: newURL.absoluteURL.path) else {
throw NSFileProviderError(.filenameCollision)
}
newItem.tagData = tagData
tagData = nil
try FileManager.default.moveItem(at: url, to: newURL)
return newItem
}
func delete() throws {
tagData = nil
try FileManager.default.removeItem(at: url)
}
}
extension FileProviderItem: NSFileProviderItem {
var itemIdentifier: NSFileProviderItemIdentifier {
if isRoot {
return .rootContainer
}
return NSFileProviderItemIdentifier(path)
}
var parentItemIdentifier: NSFileProviderItemIdentifier {
return FileProviderItem(path: (path as NSString).deletingLastPathComponent).itemIdentifier
}
var capabilities: NSFileProviderItemCapabilities {
if isRoot {
return [.allowsContentEnumerating, .allowsReading, .allowsAddingSubItems]
}
return [.allowsContentEnumerating, .allowsReading, .allowsAddingSubItems, .allowsRenaming, .allowsDeleting]
}
var filename: String {
if isRoot {
return "SaneScanner"
}
return (path as NSString).lastPathComponent
}
var creationDate: Date? {
return try? url.resourceValues(forKeys: Set([URLResourceKey.creationDateKey])).creationDate
}
var contentModificationDate: Date? {
return try? url.resourceValues(forKeys: Set([URLResourceKey.contentModificationDateKey])).contentModificationDate
}
var lastUsedDate: Date? {
return try? url.resourceValues(forKeys: Set([URLResourceKey.contentAccessDateKey])).contentAccessDate
}
var documentSize: NSNumber? {
guard !isDirectory else { return nil }
return try? url.resourceValues(forKeys: Set([URLResourceKey.fileSizeKey])).fileSize as NSNumber?
}
var typeIdentifier: String {
guard !isDirectory else { return kUTTypeFolder as String }
return (try? url.resourceValues(forKeys: Set([.typeIdentifierKey])).typeIdentifier) ?? (kUTTypeItem as String)
}
var tagData: Data? {
get { UserDefaults(suiteName: "group.me.syan.SaneScanner")?.data(forKey: path) }
set { UserDefaults(suiteName: "group.me.syan.SaneScanner")?.set((newValue?.isEmpty ?? true) ? nil : newValue, forKey: path) }
}
}
|
//
// GDTableView.swift
// Todo
//
// Created by Buse ERKUŞ on 12.03.2019.
// Copyright © 2019 Buse ERKUŞ. All rights reserved.
//
import UIKit
class GDTableView:UITableView{
override init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
checkIfAutoLayout()
backgroundColor = .clear
separatorStyle = .none
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// AddTransactionSegue.swift
// Spearmint
//
// Created by Brian Ishii on 5/7/19.
// Copyright © 2019 Brian Ishii. All rights reserved.
//
import UIKit
class AddTransactionSegueOld: UIStoryboardSegue, SegueIdentifier {
override init(identifier: String?, source: UIViewController, destination: UIViewController) {
if identifier != nil {
super.init(identifier: identifier, source: source, destination: destination)
} else {
super.init(identifier: AddTransactionSegue.SegueIdentifier, source: source, destination: destination)
}
}
}
|
//
// Sequence.swift
// swift-utils
//
// Created by Sven Schmidt on 15/12/2014.
//
//
import Foundation
struct TakeSequence<T: SequenceType>: SequenceType {
private var numberOfItems: Int
private var sequence: T
init(_ numberOfItems: Int, _ sequence: T) {
self.numberOfItems = numberOfItems
self.sequence = sequence
}
func generate() -> AnyGenerator<T.Generator.Element> {
var count = 0
var generator = self.sequence.generate()
return AnyGenerator {
if count < self.numberOfItems {
count += 1
return generator.next()
} else {
return nil
}
}
}
}
extension AnySequence {
func take(n: Int) -> AnySequence<Element> {
return AnySequence(TakeSequence(n, self))
}
}
|
//
// Reminder+CoreDataClass.swift
//
//
// Created by Hoang Duc on 8/1/19.
//
//
import Foundation
import CoreData
@objc(Reminder)
public class Reminder: NSManagedObject {
}
|
// SwiftUIPlayground
// https://github.com/ralfebert/SwiftUIPlayground/
import SwiftUI
struct Contact: Identifiable {
var id = UUID()
var name: String
var subscribed: Bool
var birthday: Date
static let alice = Contact(name: "Alice", subscribed: false, birthday: Date(year: 1970, month: 7, day: 8))
static let bob = Contact(name: "Bob", subscribed: true, birthday: Date(year: 1980, month: 3, day: 4))
}
struct ContactFormView: View {
@State var contact = Contact.bob
var body: some View {
Form {
Section(header: Text("Personal information")) {
HStack {
Text("Name")
TextField("Username", text: $contact.name)
.multilineTextAlignment(.trailing)
}
Toggle(isOn: $contact.subscribed) {
Text("Subscribed")
}
DatePicker(selection: $contact.birthday, label: { Text("Birthday") })
}
PickerExampleView()
}
.navigationBarTitle("Contact")
}
}
struct ContactFormView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
ContactFormView()
}
}
}
|
import UIKit
import Amani
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var cardNumTextField: UITextField!
@IBOutlet weak var kycBtn: UIButton!
@IBOutlet weak var lbl1: UILabel!
@IBOutlet weak var lbl2: UILabel!
let backgroundColor:UIColor = #colorLiteral(red: 0.1450980392, green: 0.2352941176, blue: 0.3490196078, alpha: 1)
let foregroundColor:UIColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
//MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.initialSetup()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.navigationController?.navigationBar.isHidden = true
}
//MARK: - Initial Setup for UI
func initialSetup() {
self.view.backgroundColor = backgroundColor
self.navigationController?.navigationBar.barTintColor = #colorLiteral(red: 0.05882352941, green: 0.1411764706, blue: 0.2078431373, alpha: 1)
cardNumTextField.inputAccessoryView = setToolBar()
cardNumTextField.attributedPlaceholder = NSAttributedString(string: "TCK ID Number",
attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
cardNumTextField.layer.borderWidth = 1
cardNumTextField.layer.borderColor = UIColor.white.cgColor
kycBtn.layer.cornerRadius = 10
kycBtn.clipsToBounds = true
lbl1.textColor = foregroundColor
lbl2.textColor = foregroundColor
cardNumTextField.layer.cornerRadius = 10
cardNumTextField.clipsToBounds = true
self.dismissKeyboard()
}
//MARK: - Submit Button
@IBAction func go(_ sender: Any) {
self.view.endEditing(true)
let customer = CustomerRequestModel(name: "", email: "", phone: "", idCardNumber: cardNumTextField.text ?? "")
if #available(iOS 11, *) {
let amaniSDK = AmaniSDK.sharedInstance
amaniSDK.set(server: "SERVER_URL", token: "TOKEN", customer: customer)
/*
if dont want to use location permissions please provide with useGeoLocation parameter
amaniSDK.set(server: "SERVER_URL", token: "TOKEN", customer: customer,useGeoLocation: false)
select showing language with language parameter
amaniSDK.set(server: "SERVER_URL", token: "TOKEN", customer: customer,language: "tr")
amaniSDK.set(server: "SERVER_URL", token: "TOKEN", customer: customer,useGeoLocation: false,language: "tr")
for use nfcOnly option you need to provide nviData
let nviData = NviModel(documentNo: "DocumentNo", dateOfBirth: "YYMMDD", dateOfExpire: "YYMMDD")
amaniSDK.set(server: "SERVER_URL", token: "TOKEN", customer: customer,nvi:nvidata)
*/
amaniSDK.setDelegate(delegate: self)
amaniSDK.showSDK(overParent: self)
} else {
// Fallback on earlier versions
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func setToolBar() -> UIToolbar {
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.tintColor = .blue
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.done, target: self, action: #selector(self.donePressOnPicker))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
toolBar.setItems([spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
return toolBar
}
@objc func donePressOnPicker() {
self.view.endEditing(true)
go(self)
}
}
//MARK: - Keyboard dismiss functionality
extension UIViewController {
func dismissKeyboard() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.keyboardDismiss))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
@objc func keyboardDismiss() {
view.endEditing(true)
}
}
extension ViewController:AmaniSDKDelegate {
func onEvent(name: String, Parameters: [String]?, type: String) {
}
func onConnectionError(error: String?) {
}
func onNoInternetConnection() {
}
func onKYCSuccess(CustomerId: Int) {
}
func onKYCFailed(CustomerId: Int, Rules: [[String : String]]?) {
}
func onTokenExpired() {
}
}
|
import ProjectDescription
let config = Config(
generationOptions: [
.organizationName("Sandbox"),
.disableAutogeneratedSchemes,
]
)
|
import PlaygroundSupport
import SpriteKit
import AVFoundation
public class ProcessScene: SKScene {
private var cover1: SKSpriteNode!
private var cover2: SKSpriteNode!
private var cover3: SKSpriteNode!
private var separationFruitsRed: SKSpriteNode!
private var separationFruits: SKSpriteNode!
private var separationDirt: SKSpriteNode!
private var sky: SKSpriteNode!
private var sunAndMoon: SKSpriteNode!
private var yard: SKSpriteNode!
private var ground: SKSpriteNode!
private var fruits: SKSpriteNode!
private var peelingMachine: SKSpriteNode!
private var peelingFruits: SKSpriteNode!
private var continueLabel: SKLabelNode!
private var messageBubble: SKSpriteNode!
private var isDay = true
private var step = 0
private var actionRunning = true
var musicPlayer: AVAudioPlayer?
public override func didMove(to view: SKView) {
cover1 = childNode(withName: "//cover1") as? SKSpriteNode
cover2 = childNode(withName: "//cover2") as? SKSpriteNode
cover3 = childNode(withName: "//cover3") as? SKSpriteNode
separationFruitsRed = childNode(withName: "//separationFruitsRed") as? SKSpriteNode
separationFruits = childNode(withName: "//separationFruits") as? SKSpriteNode
separationDirt = childNode(withName: "//separationDirt") as? SKSpriteNode
sky = childNode(withName: "//sky") as? SKSpriteNode
ground = childNode(withName: "//ground") as? SKSpriteNode
yard = childNode(withName: "//yard") as? SKSpriteNode
fruits = childNode(withName: "//fruits") as? SKSpriteNode
sunAndMoon = childNode(withName: "//sunAndMoon") as? SKSpriteNode
peelingMachine = childNode(withName: "//peelingMachine") as? SKSpriteNode
peelingFruits = childNode(withName: "//peelingFruits") as? SKSpriteNode
continueLabel = childNode(withName: "//continueLabel") as? SKLabelNode
messageBubble = childNode(withName: "//messageBubble") as? SKSpriteNode
continueLabel.alpha = 0.0
messageBubble.run(.sequence([.wait(forDuration: 1), .move(to: CGPoint(x: 130.5, y: 27.0), duration: 0.5), .playSoundFileNamed("processSceneMessage1Audio.m4a", waitForCompletion: false), .wait(forDuration: 5), .run {
self.messageBubble.childNode(withName: "messageLabel1")?.alpha = 0
self.messageBubble.childNode(withName: "messageLabel2")?.alpha = 1
}, .playSoundFileNamed("processSceneMessage2Audio.m4a", waitForCompletion: false), .wait(forDuration: 5), .move(to: CGPoint(x: 400, y: 27.0), duration: 0.5), .run {
self.messageBubble.childNode(withName: "messageLabel2")?.alpha = 0
}]))
// message audio
cover1.run(.sequence([.wait(forDuration: 11.5), .fadeAlpha(to: 0, duration: 0.5)]))
separationDirt.run(.sequence([.wait(forDuration: 12.5), .move(to: CGPoint(x: 126.0, y: 320.0), duration: 1)]))
self.run(.sequence([.wait(forDuration: 12.5), .playSoundFileNamed("harvestSound.m4a", waitForCompletion: false), .wait(forDuration: 1.5), .playSoundFileNamed("harvestSound.m4a", waitForCompletion: false)]))
separationFruits.run(.sequence([.wait(forDuration: 14), .move(to: CGPoint(x: 139.95, y: 201.5), duration: 1)]))
actionTimer(time: 15, callback: {
self.showTapToContinue()
})
}
private func dryingCoffeeFruits() {
cover1.run(.fadeAlpha(to: 0.9, duration: 0.5))
messageBubble.run(.sequence([.move(to: CGPoint(x: 130.5, y: 27.0), duration: 0.5), .run {
self.messageBubble.childNode(withName: "messageLabel3")?.alpha = 1
}, .playSoundFileNamed("processSceneMessage3Audio.m4a", waitForCompletion: false), .wait(forDuration: 4), .move(to: CGPoint(x: 400, y: 27.0), duration: 0.5), .run {
self.messageBubble.childNode(withName: "messageLabel3")?.alpha = 0
}]))
let _ = Timer.scheduledTimer(withTimeInterval: 5, repeats: false) { [self] timer in
playSound(fileName: "farmBackgroundMusic.mp3", volume: 0.5)
}
cover2.run(.sequence([.wait(forDuration: 5), .fadeAlpha(to: 0, duration: 0.5)]))
let skyColor = UIColor(red: 0.61586, green: 0.886274, blue: 0.996078, alpha: 1)
sunAndMoon.run(.sequence([.wait(forDuration: 6), .rotate(byAngle: -CGFloat(Double.pi), duration: 1)]))
sky.run(.sequence([.wait(forDuration: 6), .colorize(with: .black, colorBlendFactor: 0.7, duration: 1)]))
ground.run(.sequence([.wait(forDuration: 6), .colorize(with: .black, colorBlendFactor: 0.7, duration: 1)]))
yard.run(.sequence([.wait(forDuration: 6), .colorize(with: .black, colorBlendFactor: 0.7, duration: 1)]))
sunAndMoon.run(.sequence([.wait(forDuration: 7.5), .rotate(byAngle: -CGFloat(Double.pi), duration: 1)]))
sky.run(.sequence([.wait(forDuration: 7.5), .colorize(with: skyColor, colorBlendFactor: 0, duration: 1)]))
ground.run(.sequence([.wait(forDuration: 7.5), .colorize(with: .black, colorBlendFactor: 0, duration: 1)]))
yard.run(.sequence([.wait(forDuration: 7.5), .colorize(with: .black, colorBlendFactor: 0, duration: 1)]))
sunAndMoon.run(.sequence([.wait(forDuration: 9), .rotate(byAngle: -CGFloat(Double.pi), duration: 1)]))
sky.run(.sequence([.wait(forDuration: 9), .colorize(with: .black, colorBlendFactor: 0.7, duration: 1)]))
ground.run(.sequence([.wait(forDuration: 9), .colorize(with: .black, colorBlendFactor: 0.7, duration: 1)]))
yard.run(.sequence([.wait(forDuration: 9), .colorize(with: .black, colorBlendFactor: 0.7, duration: 1)]))
sunAndMoon.run(.sequence([.wait(forDuration: 10.5), .rotate(byAngle: -CGFloat(Double.pi), duration: 1)]))
sky.run(.sequence([.wait(forDuration: 10.5), .colorize(with: skyColor, colorBlendFactor: 0, duration: 1)]))
ground.run(.sequence([.wait(forDuration: 10.5), .colorize(with: .black, colorBlendFactor: 0, duration: 1)]))
yard.run(.sequence([.wait(forDuration: 10.5), .colorize(with: .black, colorBlendFactor: 0, duration: 1)]))
fruits.run(.sequence([.wait(forDuration: 10.5), .colorize(with: .black, colorBlendFactor: 0.7, duration: 1)]))
dismissTapToContinue()
actionTimer(time: 12, callback: {
self.musicPlayer?.stop()
self.step += 1
self.showTapToContinue()
})
}
private func peelingCoffeeFruits() {
cover2.run(.fadeAlpha(to: 0.9, duration: 0.5))
messageBubble.run(.sequence([.move(to: CGPoint(x: 130.5, y: 27.0), duration: 0.5), .run {
self.messageBubble.childNode(withName: "messageLabel4")?.alpha = 1
}, .playSoundFileNamed("processSceneMessage4Audio.m4a", waitForCompletion: false), .wait(forDuration: 4), .move(to: CGPoint(x: 400, y: 27.0), duration: 0.5)]))
cover3.run(.sequence([.wait(forDuration: 5), .fadeAlpha(to: 0, duration: 0.5)]))
peelingFruits.run(.sequence([.wait(forDuration: 6), .move(to: CGPoint(x: -126.253, y: -231.5), duration: 6)]))
dismissTapToContinue()
peelingMachine.run(.sequence([.wait(forDuration: 5), .playSoundFileNamed("machineSound.m4a", waitForCompletion: false)]))
let _ = Timer.scheduledTimer(withTimeInterval: 6, repeats: false) { [self] timer in
shakeSprite(layer: peelingMachine, duration: 6)
generateCoffeeGrainUnroasted(originPos: CGPoint(x: -71.5, y: -342.205), destinationPosition: CGPoint(x: 129.768, y: -222.415), waitTime: 0.5)
generateCoffeeGrainUnroasted(originPos: CGPoint(x: -71.5, y: -342.205), destinationPosition: CGPoint(x: 120, y: -252.5), waitTime: 1)
generateCoffeeGrainUnroasted(originPos: CGPoint(x: -71.5, y: -342.205), destinationPosition: CGPoint(x: 96.268, y: -260.414), waitTime: 1.2)
generateCoffeeGrainUnroasted(originPos: CGPoint(x: -71.5, y: -342.205), destinationPosition: CGPoint(x: 113.268, y: -233.707), waitTime: 1.6)
generateCoffeeGrainUnroasted(originPos: CGPoint(x: -71.5, y: -342.205), destinationPosition: CGPoint(x: 141.5, y: -292.415), waitTime: 1.9)
generateCoffeeGrainUnroasted(originPos: CGPoint(x: -71.5, y: -342.205), destinationPosition: CGPoint(x: 161.638, y: -267), waitTime: 2.4)
generateCoffeeGrainUnroasted(originPos: CGPoint(x: -71.5, y: -342.205), destinationPosition: CGPoint(x: 124.5, y: -270.883), waitTime: 2.6)
generateCoffeeGrainUnroasted(originPos: CGPoint(x: -71.5, y: -342.205), destinationPosition: CGPoint(x: 121.5, y: -290), waitTime: 3)
generateCoffeeGrainUnroasted(originPos: CGPoint(x: -71.5, y: -342.205), destinationPosition: CGPoint(x: 104.5, y: -274.414), waitTime: 3.4)
generateCoffeeGrainUnroasted(originPos: CGPoint(x: -71.5, y: -342.205), destinationPosition: CGPoint(x: 156.5, y: -230.695), waitTime: 3.8)
generateCoffeeGrainUnroasted(originPos: CGPoint(x: -71.5, y: -342.205), destinationPosition: CGPoint(x: 144.638, y: -276), waitTime: 4)
generateCoffeeGrainUnroasted(originPos: CGPoint(x: -71.5, y: -342.205), destinationPosition: CGPoint(x: 163.268, y: -284.883), waitTime: 4.5)
generateCoffeeGrainUnroasted(originPos: CGPoint(x: -71.5, y: -342.205), destinationPosition: CGPoint(x: 137, y: -238.5), waitTime: 4.7)
generateCoffeeGrainUnroasted(originPos: CGPoint(x: -71.5, y: -342.205), destinationPosition: CGPoint(x: 98.5, y: -242.883), waitTime: 5)
generateCoffeeGrainUnroasted(originPos: CGPoint(x: -71.5, y: -342.205), destinationPosition: CGPoint(x: 141.5, y: -256.883), waitTime: 5.4)
generateCoffeeGrainUnroasted(originPos: CGPoint(x: -71.5, y: -342.205), destinationPosition: CGPoint(x: 161.638, y: -249.823), waitTime: 6)
actionTimer(time: 8, callback: {
self.step += 1
self.showTapToContinue()
})
}
}
func shakeSprite(layer: SKSpriteNode, duration: Float) {
let position = layer.position
let amplitudeX:Float = 10
let amplitudeY:Float = 6
let numberOfShakes = duration / 0.04
var actionsArray:[SKAction] = []
for _ in 1...Int(numberOfShakes) {
let moveX = Float(arc4random_uniform(UInt32(amplitudeX))) - amplitudeX / 2
let moveY = Float(arc4random_uniform(UInt32(amplitudeY))) - amplitudeY / 2
let shakeAction = SKAction.moveBy(x: CGFloat(moveX), y: CGFloat(moveY), duration: 0.02)
shakeAction.timingMode = SKActionTimingMode.easeOut
actionsArray.append(shakeAction)
actionsArray.append(shakeAction.reversed())
}
actionsArray.append(SKAction.move(to: position, duration: 0.0))
let actionSeq = SKAction.sequence(actionsArray)
layer.run(actionSeq)
}
private func generateCoffeeGrainUnroasted(originPos: CGPoint, destinationPosition: CGPoint, waitTime: TimeInterval) {
let coffeeGrainUnroasted = SKSpriteNode(imageNamed: "coffeeGrainUnroasted")
coffeeGrainUnroasted.position = originPos
coffeeGrainUnroasted.zPosition = 30
coffeeGrainUnroasted.run(SKAction.sequence([.wait(forDuration: waitTime), .move(to: destinationPosition, duration: 1)]))
self.addChild(coffeeGrainUnroasted)
}
private func showTapToContinue() {
continueLabel.run(.repeatForever(SKAction.sequence([.fadeIn(withDuration: 1.5), .fadeOut(withDuration: 1.5)])))
}
private func dismissTapToContinue() {
continueLabel.removeAllActions()
continueLabel.alpha = 0.0
}
private func actionTimer(time: Double, callback: @escaping () -> Void) {
actionRunning = true
let _ = Timer.scheduledTimer(withTimeInterval: time, repeats: false) { [self] timer in
actionRunning = false
callback()
}
}
private func playSound(fileName: String, volume: Float) {
let path = Bundle.main.path(forResource: fileName, ofType:nil)!
let url = URL(fileURLWithPath: path)
do {
musicPlayer = try AVAudioPlayer(contentsOf: url)
musicPlayer?.volume = volume
musicPlayer?.play()
} catch {
print("Problem loading file named: " + fileName)
}
}
@objc static public override var supportsSecureCoding: Bool {
// SKNode conforms to NSSecureCoding, so any subclass going
// through the decoding process must support secure coding
get {
return true
}
}
func touchDown(atPoint pos: CGPoint) {
if actionRunning {
return
}
switch step {
case 0:
dryingCoffeeFruits()
case 1:
peelingCoffeeFruits()
case 2:
let newScene = RoastScene(fileNamed: "RoastScene")!
newScene.scaleMode = .aspectFit
let transition = SKTransition.crossFade(withDuration: 5)
self.view?.presentScene(newScene, transition: transition)
default:
return
}
}
func touchMoved(toPoint pos: CGPoint) {
}
func touchUp(atPoint pos : CGPoint) {
}
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { touchDown(atPoint: t.location(in: self)) }
}
public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { touchMoved(toPoint: t.location(in: self)) }
}
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { touchUp(atPoint: t.location(in: self)) }
}
public override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches { touchUp(atPoint: t.location(in: self)) }
}
public override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
}
|
//
// PreviewImageViewController.swift
// openImagepopUp
//
// Created by Gerardo Herrera on 7/18/17.
// Copyright © 2017 Software. All rights reserved.
//
import UIKit
import AVKit
import AVFoundation
class PreviewImageViewController: UIViewController {
@IBOutlet weak var showButtonYouTubeButton: UIButton!
@IBOutlet weak var descriptionTextView: UITextView!
@IBOutlet weak var titleEnglishLabel: UILabel!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var imagePreview: UIImageView!
@IBOutlet weak var TittleJapaneseLabel: UILabel!
@IBOutlet weak var totalEpisodiesLabel: UILabel!
@IBOutlet weak var popularityLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var typeLabel: UILabel!
var image : UIImage = UIImage()
var tittleJapanese = ""
var tittleEnglish = ""
var totalEpisodies = ""
var popularity = ""
var type = ""
var score = ""
var id : Int = 0
var youTubeID: String = ""
override func viewDidLoad() {
super.viewDidLoad()
scrollView.alwaysBounceVertical = false
scrollView.alwaysBounceHorizontal = false
scrollView.showsVerticalScrollIndicator = true
scrollView.flashScrollIndicators()
scrollView.minimumZoomScale = 1
scrollView.maximumZoomScale = 10
let blurEffect = UIBlurEffect(style: .dark)
let blurEfffectView = UIVisualEffectView(effect: blurEffect)
blurEfffectView.frame = self.view.bounds
let vibrancyEffect = UIVibrancyEffect(blurEffect: blurEffect)
let vibrancyEffectView = UIVisualEffectView(effect: vibrancyEffect)
blurEfffectView.addSubview(vibrancyEffectView)
imagePreview.image = image
TittleJapaneseLabel.text = "" + tittleJapanese
totalEpisodiesLabel.text = "Episodios: " + totalEpisodies
popularityLabel.text = "Popularidad: " + popularity
typeLabel.text = "Emision: " + type
scoreLabel.text = "Score: " + score
titleEnglishLabel.text = tittleEnglish
self.view.subviews[0].insertSubview(blurEfffectView,at:0)
WebServiceAPI.animeDetail(idAnime: id) { (band, animeObj) in
if band == true
{
DispatchQueue.main.async {
self.descriptionTextView.text = animeObj.descriptionAnime
if (animeObj.youtube_id != "")
{
self.showButtonYouTubeButton.alpha = 1
self.youTubeID = animeObj.youtube_id
self.showButtonYouTubeButton.isEnabled = true
}
}
}
}
}
@IBAction func showButtonYoutubeButtonAction(_ sender: Any) {
let videoURL = URL(string: "https://www.youtube.com/embed/\(self.youTubeID)")
// UIApplication.shared.openURL(videoURL!)
let storyBoard = UIStoryboard(name: "PreviewYoutube", bundle: nil)
let viewcontroller = storyBoard.instantiateViewController(withIdentifier: "youview") as! previewYoutubeViewController
viewcontroller.urlVideo = videoURL
self.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
self.present(viewcontroller, animated: true, completion: nil)
}
func clicOutSide(sender : UITapGestureRecognizer)
{
self.dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func dissmissButton(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
}
|
//
// StringExtensions.swift
// GAToDoList
//
// Created by bradheintz on 3/21/15.
// Copyright (c) 2015 bradheintz. All rights reserved.
//
import Foundation
public extension String {
func trim() -> String {
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
} |
@testable import TMDb
import XCTest
final class TVShowSeasonServiceTests: XCTestCase {
var service: TVShowSeasonService!
var apiClient: MockAPIClient!
var locale: Locale!
override func setUp() {
super.setUp()
apiClient = MockAPIClient()
locale = Locale(identifier: "en_GB")
service = TVShowSeasonService(apiClient: apiClient, localeProvider: { [unowned self] in locale })
}
override func tearDown() {
apiClient = nil
service = nil
super.tearDown()
}
func testDetailsReturnsTVShowSeason() async throws {
let tvShowID = Int.randomID
let expectedResult = TVShowSeason.mock()
let seasonNumber = expectedResult.seasonNumber
apiClient.result = .success(expectedResult)
let result = try await service.details(forSeason: seasonNumber, inTVShow: tvShowID)
XCTAssertEqual(result, expectedResult)
XCTAssertEqual(apiClient.lastPath,
TVShowSeasonsEndpoint.details(tvShowID: tvShowID, seasonNumber: seasonNumber).path)
}
func testImagesReturnsImages() async throws {
let seasonNumber = Int.randomID
let tvShowID = Int.randomID
let expectedResult = TVShowSeasonImageCollection.mock()
apiClient.result = .success(expectedResult)
let result = try await service.images(forSeason: seasonNumber, inTVShow: tvShowID)
XCTAssertEqual(result, expectedResult)
XCTAssertEqual(
apiClient.lastPath,
TVShowSeasonsEndpoint.images(tvShowID: tvShowID, seasonNumber: seasonNumber,
languageCode: locale.languageCode).path
)
}
func testVideosReturnsVideos() async throws {
let seasonNumber = Int.randomID
let tvShowID = Int.randomID
let expectedResult = VideoCollection.mock()
apiClient.result = .success(expectedResult)
let result = try await service.videos(forSeason: seasonNumber, inTVShow: tvShowID)
XCTAssertEqual(result, expectedResult)
XCTAssertEqual(
apiClient.lastPath,
TVShowSeasonsEndpoint.videos(tvShowID: tvShowID, seasonNumber: seasonNumber,
languageCode: locale.languageCode).path
)
}
}
|
//
// waitingVC.swift
// paintme
//
// Created by Megan Worrel on 12/18/20.
//
import UIKit
import SwiftyJSON
class waitingVC: UIViewController {
@IBOutlet weak var waitingText: UILabel!
@IBOutlet weak var indicator:
UIActivityIndicatorView!
@IBOutlet weak var finishedText: UILabel!
@IBOutlet weak var image: UIImageView!
var inputImage: UIImage!
var styleImage: UIImage!
@IBOutlet weak var downloadText: UILabel!
@IBOutlet weak var downloadButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let url = URL(string: "http://localhost:8000/paintme/")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
guard let contentData = inputImage.pngData() else { return }
let content_image = contentData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
guard let styleData = styleImage.pngData() else { return }
let style_image = styleData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
let parameters: [String: Any] = [
"content_img": content_image,
"style_img": style_image
]
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
let task = URLSession.shared.dataTask(with: request) { data, response, error in
DispatchQueue.main.async{
guard let data = data,
let response = response as? HTTPURLResponse,
error == nil else {
print("error", error ?? "Unknown error")
return
}
guard (200 ... 299) ~= response.statusCode else {
print("statusCode should be 2xx, but is \(response.statusCode)")
print("response = \(response)")
let alert = UIAlertController(title: "Error", message: "Error loading the image", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
self.present(alert, animated: true)
return
}
do {
let json = try JSON(data: data, options: .allowFragments)
let imageBase64 = json["img"].string
let imageData = Data(base64Encoded: imageBase64 ?? "", options: .ignoreUnknownCharacters)!
self.image.image = UIImage(data: imageData)
}
catch{
print("Error with JSON conversion")
}
self.waitingText.isHidden = true
self.indicator.isHidden = true
self.finishedText.isHidden = false
self.image.isHidden = false
self.downloadText.isHidden = false
self.downloadButton.isHidden = false
}
}
task.resume()
}
@IBAction func startoverClicked(_ sender: Any) {
self.navigationController?.popToRootViewController(animated: true)
}
@IBAction func saveImageClicked(_ sender: Any) {
UIImageWriteToSavedPhotosAlbum(image.image!, nil, nil, nil)
let alert = UIAlertController(title: "Image Saved", message: nil, preferredStyle: .alert)
self.present(alert, animated: true)
alert.dismiss(animated: true, completion: nil)
}
/*
// 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.
}
*/
}
|
//
// GGWorkCell.swift
// Project 01 - GGArtistry
//
// Created by viethq on 4/12/17.
// Copyright © 2017 viethq. All rights reserved.
//
import UIKit
class GGWorkCell: UICollectionViewCell, GGBaseCellProtocol {
@IBOutlet weak var iconImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
}
}
|
/* Copyright Airship and Contributors */
import Foundation
import UIKit
protocol BackgroundTasksProtocol {
#if !os(watchOS)
func beginTask(_ name: String, expirationHandler: @escaping () -> Void) throws -> Disposable
#endif
}
class BackgroundTasks: BackgroundTasksProtocol {
#if !os(watchOS)
func beginTask(_ name: String, expirationHandler: @escaping () -> Void) throws -> Disposable {
let application = UIApplication.shared
var taskID = UIBackgroundTaskIdentifier.invalid
let disposable = Disposable {
if (taskID != UIBackgroundTaskIdentifier.invalid) {
AirshipLogger.trace("Ending background task: \(name)")
application.endBackgroundTask(taskID)
taskID = UIBackgroundTaskIdentifier.invalid
}
}
taskID = application.beginBackgroundTask(withName: name) {
expirationHandler()
disposable.dispose()
}
if (taskID == UIBackgroundTaskIdentifier.invalid) {
throw AirshipErrors.error("Unable to request background time.")
}
AirshipLogger.trace("Background task started: \(name)")
return disposable
}
#endif
}
|
//
// CurrentWeather.swift
// Meteo
//
// Created by Mário Silva on 12/12/14.
// Copyright (c) 2014 Mário Silva. All rights reserved.
//
import Foundation
import UIKit
struct CurrentWeather {
var time: Int
var temperature: Int
var humidity: Double
var windSpeed: Double
var summary: String
var icon: String
init(time: Int, temperature: Int, humidity: Double, windSpeed: Double, summary: String, icon: String) {
self.time = time
self.temperature = temperature
self.humidity = humidity
self.windSpeed = windSpeed
self.summary = summary
self.icon = icon
}
func getDate() -> String {
let unixtime = NSTimeInterval(time)
let date = NSDate(timeIntervalSince1970: unixtime)
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = .ShortStyle
return dateFormatter.stringFromDate(date)
}
func getIcon() -> UIImage {
return UIImage(named: getIconFileName())!
}
private func getIconFileName() -> String {
switch icon {
case "clear-day":
return "clear-day"
case "clear-night":
return "clear-night"
case "rain":
return "rain"
case "snow":
return "snow"
case "sleet":
return "sleet"
case "wind":
return "wind"
case "fog":
return "fog"
case "cloudy":
return "cloudy"
case "partly-cloudy-day":
return "partly-cloudy"
case "partly-cloudy-night":
return "cloudy-night"
default:
return "default"
}
}
} |
//: [Previous](@previous)
import Foundation
struct FizzBuzz: Collection{
//We need an associated type for the index.
//The requirment is that it is comparable
//Let's make it explicit by using the typealias
typealias Index = Int
//Continuing with comforming to the Collection protocol
//We need to define an start and an end index
var startIndex: Index {
return 1
}
//For this particular example, we know that we will go from 1 to 100 element
//thus the end index should be ONE PAST THE LAST INDEX (= 101)
var endIndex: Index {
return 101
}
//Define the method for advancing the index
//Remember to keep things under O(1) complexity
func index(after i: Index) -> Index{
return i + 1
}
//Define the subscript operator
subscript(index:Index)-> String {
precondition(indices.contains(index), "out of range")
switch(index.isMultiple(of: 3), index.isMultiple(of: 5)){
case (false, false):
return String(describing: index)
case (false, true):
return "Buzz"
case (true, false):
return "Fizz"
case (true, true):
return "FizzBuzz"
}
}
}
//You know have a fizzBuzz collection and you can iterate through it:
for element in FizzBuzz(){
print(element)
}
//: [Next](@next)
|
import Foundation
// MARK: Time
private let dateFormatterCache = DateFormatterCache()
struct DateFactory {
/// Shorthand for the day offsets.
enum Day: Int {
// NSDatComponents.weekday starts from sunday
case sunday = 1
case monday = 2
case tuesday = 3
case wednesday = 4
case thursday = 5
case friday = 6
case saturday = 7
}
static func dateForNext(day: Day, hour: Int) -> Date? {
let now: Date = Date()
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
// First, find the day offset for the next occurance of Day.
let units: NSCalendar.Unit = [.year, .month, .weekOfMonth, .weekday, .hour]
let components: DateComponents = (calendar as NSCalendar).components(units,
from: now)
let weekdayToday = components.weekday
let daysTil = (7 + day.rawValue - weekdayToday!) % 7
let dayDifference = (60*60*24) * Double(daysTil)
// Then calculate the hour offset. Target hour + time zone offset - current hour (mod 24)
let hourOffset = (hour - components.hour!) % 24
let hourDifference = Double(hourOffset) * (60*60)
return now.addingTimeInterval(dayDifference + hourDifference)
}
}
extension Date {
/**
- parameter formatString: [String] which format time string is in. Defaults to 6:00pm format
- parameter timeZone: [NSTimeZone?] Time zone the date should be displayed in.
*/
func toString(_ formatString: String, timeZone: TimeZone? = nil) -> String
{
return dateFormatterCache.getFormatter(formatString, timeZone: timeZone).string(from: self)
}
}
extension String {
/**
- parameter format: [DateFormat] which format time string is in. Defaults to UTC (API standard)
*/
func toDate(_ format: DateFormat) -> Date? {
if let date
= dateFormatterCache.getFormatter(format.rawValue).date(from: self)
{
return date
} else {
return nil
}
}
}
extension Date {
/**
Compares based on year, month, and day but not time of day
*/
func isSameDay(_ other: Date) -> Bool {
let calendar = Calendar.current
let flags: NSCalendar.Unit = [.year, .month, .day]
let components = (calendar as NSCalendar).components(flags, from: self)
let otherComponents = (calendar as NSCalendar).components(flags, from: other)
return components.year == otherComponents.year
&& components.month == otherComponents.month
&& components.day == otherComponents.day
}
}
extension Date {
func hours(from date: Date) -> Int {
return Calendar.current.dateComponents([.hour], from: date, to: self).hour ?? 0
}
}
class DateFormatterCache {
fileprivate var formatterCache = [String: DateFormatter]()
init() {
formatterCache = buildFormatters()
}
fileprivate func buildFormatters() -> [String : DateFormatter] {
let dateFormats = [DateFormat.kUTCFormat, DateFormat.kTimeFormat, DateFormat.kDateFormat]
var formatterDict = [String: DateFormatter]()
for format in dateFormats {
let formatter = DateFormatter()
formatter.dateFormat = format.rawValue
formatterDict[format.rawValue] = formatter
}
return formatterDict
}
func getFormatter(_ format: String, timeZone: TimeZone? = nil) -> DateFormatter {
if let dateFormatter = formatterCache[format] {
dateFormatter.timeZone = timeZone
return dateFormatter
} else {
let dateFormatter = DateFormatter()
formatterCache[format] = dateFormatter
dateFormatter.timeZone = timeZone
dateFormatter.dateFormat = format
return dateFormatter
}
}
}
|
//
// RealmExtension.swift
// TimeTable
//
// Created by Ryuhei Kaminishi on 2017/04/17.
// Copyright © 2017 kaminisea. All rights reserved.
//
import Foundation
import RealmSwift
extension Realm {
static func execute(_ completion: (Realm) -> Void) {
autoreleasepool {
let realm = try! Realm()
try! realm.write {
completion(realm)
}
}
}
}
|
//
// SWBVisitPropertyCell.swift
// SweepBright
//
// Created by Kaio Henrique on 4/5/16.
// Copyright © 2016 madewithlove. All rights reserved.
//
import Foundation
class SWBVisitPropertyCell: PropertyTableViewCell {
override var property: SWBProperty! {
didSet {
self.statusLabel.text = "Current location"
self.costLabel.text = "€ \(self.property.price!.valueFormated) \(self.property.status == SWBPropertyNegotiation.ToLet ? "/ month" : "")"
self.addressLabel.text = self.property.address
}
}
}
|
import UIKit
/// :nodoc:
public class StudentViewController: UserViewController {
let lectureQuizzesButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Lecture Quizzes", for: .normal)
button.setTitleColor(.white, for: .normal)
button.backgroundColor = UIColor.AppColors.main.rawValue
button.clipsToBounds = true
button.layer.cornerRadius = 5
return button
}()
override public func viewDidLoad() {
super.viewDidLoad()
lectureQuizzesButton.addTarget(self, action: #selector(lectureQuizzesTapped), for: .touchUpInside)
}
override public func setupViews() {
super.setupViews()
lastStackView.addArrangedSubview(lectureQuizzesButton)
lectureQuizzesButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
}
@objc
private func lectureQuizzesTapped() {
let viewController = MyLecturesViewController()
self.navigationController?.pushViewController(viewController, animated: true)
}
}
|
import UIKit
import ThemeKit
import SnapKit
import ComponentKit
class ResendPasteInputView: UIView {
private let formValidatedView: FormValidatedView
private let inputStackView = InputStackView()
private let deleteView = InputSecondaryCircleButtonWrapperView()
private let pasteView = InputSecondaryButtonWrapperView(style: .default)
let resendView = InputSecondaryButtonWrapperView(style: .default)
var isEnabled: Bool = true {
didSet {
if isEnabled {
inputStackView.isEditable = true
inputStackView.textColor = .themeLeah
deleteView.button.isEnabled = true
} else {
inputStackView.isEditable = false
inputStackView.textColor = .themeGray
deleteView.button.isEnabled = false
}
}
}
var onChangeText: ((String?) -> ())?
var onFetchText: ((String?) -> ())?
var onResend: (() -> ())?
init() {
formValidatedView = FormValidatedView(contentView: inputStackView, padding: UIEdgeInsets(top: 0, left: .margin16, bottom: 0, right: .margin16))
super.init(frame: .zero)
backgroundColor = .clear
addSubview(formValidatedView)
formValidatedView.snp.makeConstraints { maker in
maker.edges.equalToSuperview()
}
deleteView.button.set(image: UIImage(named: "trash_20"))
deleteView.onTapButton = { [weak self] in self?.onTapDelete() }
resendView.button.setTitle("button.resend".localized, for: .normal)
resendView.onTapButton = { [weak self] in self?.onTapResend() }
resendView.button.setContentHuggingPriority(.defaultHigh, for: .horizontal)
pasteView.button.setTitle("button.paste".localized, for: .normal)
pasteView.onTapButton = { [weak self] in self?.onTapPaste() }
pasteView.button.setContentHuggingPriority(.defaultHigh, for: .horizontal)
inputStackView.autocapitalizationType = .none
inputStackView.autocorrectionType = .no
inputStackView.appendSubview(deleteView)
inputStackView.appendSubview(resendView)
inputStackView.appendSubview(pasteView)
inputStackView.onChangeText = { [weak self] text in
self?.handleChange(text: text)
}
syncButtonStates()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func onTapDelete() {
inputStackView.text = nil
handleChange(text: nil)
}
private func onTapPaste() {
guard let text = UIPasteboard.general.string?.replacingOccurrences(of: "\n", with: " ") else {
return
}
onFetchText?(text)
}
private func onTapResend() {
onResend?()
}
private func handleChange(text: String?) {
onChangeText?(text)
syncButtonStates()
}
private func syncButtonStates() {
if let text = inputStackView.text, !text.isEmpty {
deleteView.isHidden = false
resendView.isHidden = true
pasteView.isHidden = true
} else {
deleteView.isHidden = true
resendView.isHidden = false
pasteView.isHidden = false
}
}
}
extension ResendPasteInputView {
var inputPlaceholder: String? {
get { inputStackView.placeholder }
set { inputStackView.placeholder = newValue }
}
var keyboardType: UIKeyboardType {
get { inputStackView.keyboardType }
set { inputStackView.keyboardType = newValue }
}
var inputText: String? {
get { inputStackView.text }
set {
inputStackView.text = newValue
syncButtonStates()
}
}
var isEditable: Bool {
get { inputStackView.isEditable }
set { inputStackView.isEditable = newValue }
}
func set(cautionType: CautionType?) {
formValidatedView.set(cautionType: cautionType)
}
var onChangeEditing: ((Bool) -> ())? {
get { inputStackView.onChangeEditing }
set { inputStackView.onChangeEditing = newValue }
}
var onChangeHeight: (() -> ())? {
get { formValidatedView.onChangeHeight }
set { formValidatedView.onChangeHeight = newValue }
}
func height(containerWidth: CGFloat) -> CGFloat {
formValidatedView.height(containerWidth: containerWidth)
}
}
|
//
// ContentView.swift
// Grillhome
//
// Created by Евгений Григорьян on 27.04.2021.
// Copyright © 2021 Евгений Григорьян. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@State private var selectedItem: Int = 0
@State private var isHeaderAnimated = false
@ObservedObject var homeViewModel: HomeViewModel
var body: some View {
VStack {
if selectedItem == 0 {
HomeView(isHeaderAnimated: $isHeaderAnimated).environmentObject(homeViewModel)
}
else if selectedItem == 1{
SearchView().environmentObject(homeViewModel)
}
else if selectedItem == 2{
ShoppingCartView().environmentObject(homeViewModel)
}
else if selectedItem == 3{
WishlistView()
}
else {
UserPageView()
}
CustomTabView(selectedItem: $selectedItem)
}
}
}
//struct ContentView_Previews: PreviewProvider {
// static var previews: some View {
// ContentView()
// }
//}
|
//
// perfilAdminController.swift
// VisitMe
//
// Created by Ángel Andrade García on 16/11/17.
// Copyright © 2017 Oscar Allan Ruiz Toledo . All rights reserved.
//
import UIKit
class PerfilAdminController: UIViewController{
}
|
import UIKit
class LastPageViewController : UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
var stimeMain : Int = 0 //타이머에서 사용
var totaltimeMain : Int = 0
var transferTimeSchedulCount : Int = 0
var notiStartTm : String = ""
var notiNextTm : Int = 0
var timer = NSTimer()//타이머 관련
var info : Array<SubwayInfo> = []//경로 분석 정보
var setTransTimeBtnText1 : String = ""
var setTransTimeBtnText2 : String = ""
//알림 관련 변수
var setAlertTime : Int = 0 //x분전 알림
var setAlertMessage : String = ""//x분전 알림 문구
var datePickerSource : Array<Schedule> = []
var datePickerBool : Bool = false
var checkTouchAlert : Bool = false
var checkWhile : Bool = false
var checkReturnBtn : Bool = false
var fvo = FavoriteVO()//사용자 함수를 위해
@IBOutlet var mainView: UIView!
@IBOutlet var spinner: UIActivityIndicatorView!
@IBOutlet var fastExitLabel: UILabel!
@IBOutlet var infoNextTopCon: NSLayoutConstraint!
@IBOutlet var bottomBarCon: NSLayoutConstraint!
@IBOutlet var completeBtnOutlet: UIBarButtonItem!
@IBAction func completeBtn(sender: AnyObject) {
self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
@IBOutlet var viewAllRouteBtn: UIButton!
// 경로 취소 버튼
@IBOutlet var cancelBtn: UIButton!
@IBAction func cancelBtnAct(sender: AnyObject) {
let alert = UIAlertController(title: "현재 경로를 취소하시겠습니까?", message: nil, preferredStyle: .ActionSheet)
let okAction = UIAlertAction(title: "예", style: .Default){ (_) in
self.timer.invalidate()//타이머 종료
UIApplication.sharedApplication().cancelAllLocalNotifications()//모든 알람 종료
self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)//페이지 닫기
}
let cancelAction = UIAlertAction(title: "아니오", style: .Cancel, handler: nil)
alert.addAction(okAction)
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true, completion: nil)
}
// 알림 해제버튼
@IBAction func cancelNotification(sender: AnyObject) {
let alert = UIAlertController(title: "확인", message: "해당 경로의 모든 알림이 해제됩니다.\n모든 알림을 해제하시겠습니까?", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "확인", style: .Default){ (_) in
UIApplication.sharedApplication().cancelAllLocalNotifications()
}
let cancelAction = UIAlertAction(title: "취소", style: .Cancel, handler: nil)
alert.addAction(okAction)
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true, completion: nil)
}
// 이전역으로 돌아가기 위한 버튼
@IBOutlet var returnTransferBtn: UIButton!
@IBAction func returnTransfer(sender: AnyObject) {
if Reachability.isConnectedToNetwork() == true {
self.checkReturnBtn = true
self.transferTimeSchedulCount -= 2
//self.info[transferTimeSchedulCount+1].expressYN = false
//self.info[transferTimeSchedulCount+1].navigateTm = []
transferAct1(ButtonNumber: 3)
if(countTimeAct.text == "환승역 도착"){
timer.invalidate()
}
self.checkReturnBtn = false
}else {
networkAlert(0)
}
}
// 최근경로에 저장하기 위한 함수
func addRecentList(){
let name : String = self.info[0].navigate[0] + "," + self.info[self.info.count-1].navigate[self.info[self.info.count-1].navigate.count-1]
var list : Array<String> = self.fvo.config.objectForKey("RecentArray") as! Array<String>
var check : Bool = false
for ce in list{
if(ce == name){
check = true
list.removeAtIndex(list.indexOf(ce)!)
list.append(ce)
self.fvo.config.setObject(list, forKey: "RecentArray")
break;
}
}
if(check == false){
if(list.count >= 20){
list.removeAtIndex(0)
}
list.append(name)
self.fvo.config.setObject(list, forKey: "RecentArray")
}
}
// 스와이프 관련
func swipedViewRight(){
timer.invalidate()
UIApplication.sharedApplication().cancelAllLocalNotifications()//모든 알람 종료
navigationController?.popViewControllerAnimated(true)
}
override func viewDidLoad() {
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.transferInfo.setFontSize(settingFontSize(0))
self.transferBtn1.setFontSize(settingFontSize(0))
self.transferBtn2.setFontSize(settingFontSize(0))
self.transferBtn3.setFontSize(settingFontSize(0))
self.finishTime.setFontSize(settingFontSize(0))
self.returnTransferBtn.setFontSize(settingFontSize(1))
self.infoNextST.setFontSize(settingFontSize(4))
self.countTimeAct.setFontSize(settingFontSize(5))
self.fastExitLabel.setFontSize(settingFontSize(1)-1)
self.infoNextTopCon.constant = settingFontSize(3)
self.viewAllRouteBtn.setFontSize(settingFontSize(1))
self.cancelBtn.setFontSize(settingFontSize(1))
self.bottomBarCon.constant = settingFontSize(6)
pickerView.hidden = true
tabBar.hidden = true
returnTransferBtn.hidden = true
returnTransferBtn.enabled = false
self.pickerView.dataSource = self;
self.pickerView.delegate = self;
completeBtnOutlet.tintColor = UIColor(red: 230/255.0, green: 70.0/255.0, blue: 70.0/255.0, alpha: 0.0)
completeBtnOutlet.enabled = false
let swipeRec = UISwipeGestureRecognizer()
swipeRec.direction = .Right
swipeRec.addTarget(self, action: #selector(LastPageViewController.swipedViewRight))
mainView.addGestureRecognizer(swipeRec)
mainView.userInteractionEnabled = true
let fvo = FavoriteVO()
self.setAlertTime = fvo.config.objectForKey("setAlertTime") as! Int
switch setAlertTime{
case 0:
self.setAlertTime = 30
self.setAlertMessage = "역까지 약 30초 남았습니다."
break;
case 1:
self.setAlertTime = 60
self.setAlertMessage = "역까지 약 1분 남았습니다."
break;
case 2:
self.setAlertTime = 90
self.setAlertMessage = "역까지 약 90초 남았습니다."
break;
case 3:
self.setAlertTime = 120
self.setAlertMessage = "역까지 약 2분 남았습니다."
break;
default:
break;
}
timer.invalidate()
UIApplication.sharedApplication().cancelAllLocalNotifications()//모든 알람 종료
self.transferTimeSchedulCount = 0
countTimeAct.text = "00분 00초"
addRecentList()//최근경로에 추가
self.checkTouchAlert = false
if(self.info.count != 1){ //환승역이 있을 경우
infoNextST.text = "환승역(" + String(self.info[transferTimeSchedulCount+1].navigate[0]) + ")까지" + "\n" + "남은 시간"
transferInfo.text = self.info[transferTimeSchedulCount+1].navigate[0] + "역 출발 시간 설정"
transferStationTimeSchduel(StartTime: self.info[0].startTime)
if(convertStringToSecond(countTimeAct.text!, Mode: 3) <= 0){
countTimeAct.text = "환승역 도착"
}else{
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(LastPageViewController.updateCounter), userInfo: nil, repeats: true)
}
}else { //환승역이 없을 경우
self.transferTimeSchedulCount = 1
infoNextST.text = "목적지(" + String(self.info[self.info.count-1].navigate[self.info[self.info.count-1].navigate.count-1]) + ")까지" + "\n" + "남은 시간"
transferInfo.text = "다음 환승역 없음"
transferBtn1.setTitle("없음", forState: .Normal)
transferBtn2.setTitle("없음", forState: .Normal)
transferBtn3.setTitle("없음", forState: .Normal)
transferBtn1.enabled = false
transferBtn2.enabled = false
transferBtn3.enabled = false
let currentTime : Int = returnCurrentTime()
let fTime : Int = self.info[0].navigateTm[self.info[0].navigateTm.count-1]
if((fTime - currentTime) <= 0){
countTimeAct.text = "00분 00초"
}else{
stimeMain = self.info[0].navigateTm[0]//convertStringToSecond(self.startTimeText, Mode: 2)
totaltimeMain = fTime - self.info[0].navigateTm[0]
countTimeAct.text = convertSecondToString(fTime - currentTime, Mode: 4)
}
if(convertStringToSecond(countTimeAct.text!, Mode: 3) <= 0){
countTimeAct.text = "목적지 도착"
returnTransferBtn.hidden = true
returnTransferBtn.enabled = false
completeBtnOutlet.enabled = true
completeBtnOutlet.tintColor = UIColor.whiteColor()
}else{
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(LastPageViewController.updateCounter), userInfo: nil, repeats: true)
}
finishTime.text = "목적지 예상 도착 시간 : " + convertSecondToString(fTime, Mode: 2)
}
}
//푸시알림관련====================================
func localNotificationFunc(FinishTime finishTm : Int, StationName stationNm : String, FirstSchedule first : String, SecondSchedule second : String, FastExit fastExit : String){
let fvo = FavoriteVO()
if(fvo.config.objectForKey("SetAlert") as! Bool == true){
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LastPageViewController.notificationAct1(_:)), name: "actionOnePressed", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LastPageViewController.notificationAct2(_:)), name: "actionTwoPressed", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LastPageViewController.notificationAct3(_:)), name: "actionThreePressed", object: nil)
let now = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "ko_KR") // 로케일 설정
dateFormatter.dateFormat = "HH:mm:ss" // 날짜 형식 설정
let current : Int = returnCurrentTime()
let alertTime : Int = current + finishTm - self.setAlertTime//%%60 //
if(current < alertTime){ //현재시간보다 알람시간이 더 큰 경우 알람 설정
let hour : Int = Int(alertTime/3600)
let min : Int = (alertTime - (hour*3600))/60
let sec : Int = alertTime - hour*3600 - min*60
let dateComp:NSDateComponents = NSDateComponents()
dateFormatter.dateFormat = "yyyy"
var currentTime : Int = Int(dateFormatter.stringFromDate(now))!
dateComp.year = currentTime//local notification 설정
dateFormatter.dateFormat = "MM"
currentTime = Int(dateFormatter.stringFromDate(now))!
dateComp.month = currentTime//local notification 설정
dateFormatter.dateFormat = "dd"
currentTime = Int(dateFormatter.stringFromDate(now))!
dateComp.day = currentTime//local notification 설정
dateComp.hour = hour//local notification 설정
dateComp.minute = min//local notification 설정
dateComp.second = sec//local notification 설정
dateComp.timeZone = NSTimeZone.systemTimeZone()
let calender:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let date:NSDate = calender.dateFromComponents(dateComp)!
let notification:UILocalNotification = UILocalNotification()
var fastExitText : String = ""
if (first == ""){
notification.alertBody = stationNm + self.setAlertMessage//%%"역까지 1분 남았습니다."
notification.soundName = UILocalNotificationDefaultSoundName
}else{
if(fastExit == ""){
fastExitText = ""
}else{
fastExitText = "\n빠른환승 : " + fastExit
}
notification.category = "FIRST_CATEGORY"
notification.soundName = UILocalNotificationDefaultSoundName
notification.alertBody = stationNm + "\(self.setAlertMessage)\n첫번째 : \(first)\n두번째 : \(second)\(fastExitText)\n다음 시간표 미설정시 첫번째로 설정됩니다."
}
notification.fireDate = date
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}else{ //아닐경우 알람설정 안함
if(checkTouchAlert == false && checkReturnBtn == false){
var message : String = ""
switch fvo.config.objectForKey("setAlertTime") as! Int{
case 0:
message = "남은 시간이 30초 미만이라 알림을 설정하지 않습니다."
break;
case 1:
message = "남은 시간이 1분 미만이라 알림을 설정하지 않습니다."
break;
case 2:
message = "남은 시간이 1분 30초 미만이라 알림을 설정하지 않습니다."
break;
case 3:
message = "남은 시간이 2분 미만이라 알림을 설정하지 않습니다."
break;
default:
break;
}
let alert = UIAlertController(title: "확인", message: message, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "확인", style: .Default, handler: nil)
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true, completion: nil)
}
}
}
}
//타이머 관련 함수 ========================================
func updateCounter() {
let currentTime : Int = returnCurrentTime()
let sec : Int = convertStringToSecond(countTimeAct.text!, Mode: 3) - 1
//print("sec : \(sec)")
if(sec >= 0){
if(stimeMain + totaltimeMain - currentTime < 0){
countTimeAct.text = "0분 0초"
}else{
countTimeAct.text = convertSecondToString(stimeMain + totaltimeMain - currentTime, Mode: 4)
//print(countTimeAct.text)
}
}else{
//timer.invalidate()
countTimeAct.text = "0분 0초"
if(currentTime >= self.notiNextTm){
timer.invalidate()
self.checkTouchAlert = true
transferAct1(ButtonNumber: 1)
while currentTime > self.notiNextTm{
//currentTime = convertStringToSecond(dateFormatter.stringFromDate(now), Mode: 1)
timer.invalidate()
self.checkTouchAlert = true
transferAct1(ButtonNumber: 1)
if(countTimeAct.text! == "목적지 도착" || checkWhile == true){
break;
}
}
self.checkTouchAlert = false
}
}
}
//끝 ==================================================
// 로컬알림 첫번째 버튼이 눌렸을때 동작하는 함수(첫번째 시간표 기준 이후 알림 설정)
func notificationAct1(notification:NSNotification){
if Reachability.isConnectedToNetwork() == true {
let index : Int = self.transferTimeSchedulCount
for i in index..<self.info.count{
if(self.info[i].navigateTm[self.info[i].navigateTm.count-1] - self.setAlertTime > returnCurrentTime()){
break;
}else{
self.checkReturnBtn = true
transferAct1(ButtonNumber: 1)
self.checkReturnBtn = false
}
}
transferAct1(ButtonNumber: 1)
}else {
setlocalNotificationWhenNotNetworkConnection()
//networkAlert(0)
}
}
// 로컬알림 두번째 버튼이 눌렸을때 동작하는 함수(두번째 시간표 기준 이후 알림 설정)
func notificationAct2(notification:NSNotification){
if Reachability.isConnectedToNetwork() == true {
let index : Int = self.transferTimeSchedulCount
for i in index..<self.info.count{
if(self.info[i].navigateTm[self.info[i].navigateTm.count-1] - self.setAlertTime > returnCurrentTime()){
break;
}else{
self.checkReturnBtn = true
transferAct1(ButtonNumber: 1)
self.checkReturnBtn = false
}
}
transferAct1(ButtonNumber: 2)
}else {
setlocalNotificationWhenNotNetworkConnection()
//networkAlert(0)
}
}
// 없어도됨
func notificationAct3(notification:NSNotification){
transferActPicker()
}
// 로컬 알림의 버튼을 눌렀지만 네트워크에 연결이 안되어있을 경우 경고 알림을 설정하는 함수
func setlocalNotificationWhenNotNetworkConnection(){
UIApplication.sharedApplication().cancelAllLocalNotifications()//모든 알람 종료
let now = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "ko_KR") // 로케일 설정
dateFormatter.dateFormat = "HH:mm:ss" // 날짜 형식 설정
let current : Int = returnCurrentTime()
let hour : Int = Int(current/3600)
let min : Int = (current - (hour*3600))/60
let sec : Int = current - hour*3600 - min*60 + 2 //현재시간 2초뒤 알림 설정
let dateComp:NSDateComponents = NSDateComponents()
dateFormatter.dateFormat = "yyyy"
var currentTime : Int = Int(dateFormatter.stringFromDate(now))!
dateComp.year = currentTime//local notification 설정
dateFormatter.dateFormat = "MM"
currentTime = Int(dateFormatter.stringFromDate(now))!
dateComp.month = currentTime//local notification 설정
dateFormatter.dateFormat = "dd"
currentTime = Int(dateFormatter.stringFromDate(now))!
dateComp.day = currentTime//local notification 설정
dateComp.hour = hour//local notification 설정
dateComp.minute = min//local notification 설정
dateComp.second = sec//local notification 설정
dateComp.timeZone = NSTimeZone.systemTimeZone()
let calender:NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let date:NSDate = calender.dateFromComponents(dateComp)!
let notification:UILocalNotification = UILocalNotification()
notification.alertBody = "네트워크가 연결되지 않아 알림이 설정되지 않았습니다.\n네트워크를 연결 후 시간표를 다시 선택해주세요.\n미설정시 남은 경로의 알림이 제공되지 않습니다."
notification.soundName = UILocalNotificationDefaultSoundName
notification.fireDate = date
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
// 시간표 버튼이 눌렸을때 실행될 함수(몇번째 버튼인지를 인자로 받음)
func transferAct1(ButtonNumber number : Int){
if(self.info.count - 1 < transferTimeSchedulCount){
if(convertStringToSecond(countTimeAct.text!, Mode: 3) <= 0){
countTimeAct.text = "목적지 도착"
returnTransferBtn.hidden = true
returnTransferBtn.enabled = false
completeBtnOutlet.enabled = true
completeBtnOutlet.tintColor = UIColor.whiteColor()
}
else{
self.checkWhile = true
timer.invalidate()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(LastPageViewController.updateCounter), userInfo: nil, repeats: true)
}
}else{
switch number{
case 1:
transferStationTimeSchduel(StartTime: convertStringToSecond(/*(transferBtn1.titleLabel?.text)!*/self.setTransTimeBtnText1, Mode: 2))
break;
case 2:
transferStationTimeSchduel(StartTime: convertStringToSecond(/*(transferBtn2.titleLabel?.text)!*/self.setTransTimeBtnText2, Mode: 2))
break;
case 3:
transferStationTimeSchduel(StartTime: self.info[transferTimeSchedulCount].startTime)
break;
default:
break;
}
if(self.transferTimeSchedulCount >= self.info.count){
self.infoNextST.text = "목적지(" + self.info[self.transferTimeSchedulCount-1].navigate[self.info[self.transferTimeSchedulCount-1].navigate.count-1] + ")까지\n남은 시간"
self.transferInfo.text = "다음 환승역 없음"
}else{
self.infoNextST.text = "환승역(" + self.info[self.transferTimeSchedulCount].navigate[0] + ")까지" + "\n" + "남은 시간"
self.transferInfo.text = self.info[self.transferTimeSchedulCount].navigate[0] + "역 출발 시간 설정"
}
if(convertStringToSecond(countTimeAct.text!, Mode: 3) <= 0){
countTimeAct.text = "환승역 도착"
}else{
timer.invalidate()
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(LastPageViewController.updateCounter), userInfo: nil, repeats: true)
}
}
}
func transferActPicker(){ //기타 버튼
if(datePickerBool == true){
//if Reachability.isConnectedToNetwork() == true {
let alert = UIAlertController(title: "해당 시간표로 설정하시겠습니까?", message: "\((transferBtn3.titleLabel?.text)!)", preferredStyle: .ActionSheet)
let okAction = UIAlertAction(title: "설정", style: UIAlertActionStyle.Default){ (_) in
if Reachability.isConnectedToNetwork() == true {
self.datePickerBool = false
if(self.info.count - 1 < self.transferTimeSchedulCount){
if(convertStringToSecond(self.countTimeAct.text!, Mode: 3) <= 0){
self.countTimeAct.text = "목적지 도착"
self.returnTransferBtn.hidden = true
self.returnTransferBtn.enabled = false
self.completeBtnOutlet.enabled = true
self.completeBtnOutlet.tintColor = UIColor.whiteColor()
}else{
self.timer.invalidate()
self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(LastPageViewController.updateCounter), userInfo: nil, repeats: true)
}
}else{
self.transferStationTimeSchduel(
StartTime: convertStringToSecond((self.transferBtn3.titleLabel?.text)!, Mode: 2))
if(self.transferTimeSchedulCount >= self.info.count){
self.infoNextST.text = "목적지(" + self.info[self.transferTimeSchedulCount-1].navigate[self.info[self.transferTimeSchedulCount-1].navigate.count-1] + ")까지\n남은 시간"
self.transferInfo.text = "다음 환승역 없음"
}else{
self.infoNextST.text = "환승역(" + self.info[self.transferTimeSchedulCount].navigate[0] + ")까지" + "\n" + "남은 시간"
self.transferInfo.text = self.info[self.transferTimeSchedulCount].navigate[0] + "역 출발 시간 설정"
}
if(convertStringToSecond(self.countTimeAct.text!, Mode: 3) <= 0){
self.countTimeAct.text = "환승역 도착"
}else{
self.timer.invalidate()
self.timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(LastPageViewController.updateCounter), userInfo: nil, repeats: true)
}
}
}else {
self.networkAlert(0)
}
}
let okAction2 = UIAlertAction(title:"재설정", style: .Destructive){(_) in
self.pickerView.hidden = false
self.tabBar.hidden = false
}
let cancelAction = UIAlertAction(title: "취소", style: .Cancel){ (_) in
}
alert.addAction(cancelAction)
alert.addAction(okAction)
alert.addAction(okAction2)
self.presentViewController(alert, animated: true, completion: nil)
}else{
if(self.transferBtn3.titleLabel?.text == "기타" && self.datePickerSource.count >= 3){
if(self.datePickerSource[2].expressYN == "Y"){
transferBtn3.setTitle(convertSecondToString(self.datePickerSource[2].arriveTime, Mode: 1) + " " + self.datePickerSource[2].directionNm + "행 (급행)", forState: .Normal)
}else{
transferBtn3.setTitle(convertSecondToString(self.datePickerSource[2].arriveTime, Mode: 1) + " " + self.datePickerSource[2].directionNm + "행", forState: .Normal)
}
self.datePickerBool = true
}
pickerView.hidden = false
tabBar.hidden = false
}
}
// 알림을 설정하는 함수 호출과 이후 이동시간, 시간표 등 시간표 버튼이 눌렸을경우 실행되야하는 모든 과정을 처리
func transferStationTimeSchduel(StartTime sTime : Int) {
UIApplication.sharedApplication().cancelAllLocalNotifications()//모든 알람 종료
self.datePickerBool = false
//info에 시작시간 추가
if(self.info[transferTimeSchedulCount].startTime != sTime){
self.info[transferTimeSchedulCount].startTime = sTime
info = setAllTimeToInfo(Info: info, Index: transferTimeSchedulCount)
}
if(self.info[self.transferTimeSchedulCount].fastExit == ""){
self.fastExitLabel.text = ""
}else{
self.fastExitLabel.text = "빠른환승\n\(self.info[self.transferTimeSchedulCount].fastExit)"
}
let viaTime : Int = self.info[transferTimeSchedulCount].navigateTm[self.info[transferTimeSchedulCount].navigateTm.count-1] - self.info[transferTimeSchedulCount].navigateTm[0]
//여기까지 전역의 시작시간과 이동시간 끝나는 시간을 구하기 위한 구문임
//----------------------------------------------------------------
//여기부터 다음역의 시간표를 가져오기 위한 구문임
transferTimeSchedulCount += 1
if(transferTimeSchedulCount >= 2){
returnTransferBtn.enabled = true
returnTransferBtn.hidden = false
}else{
returnTransferBtn.hidden = true
returnTransferBtn.enabled = false
}
if(self.info.count != transferTimeSchedulCount){//만약 다음역이 있다면
var schedule = self.info[transferTimeSchedulCount].startSchedule //다음역의 시간표
let indexTemp : Int = self.info[transferTimeSchedulCount].startScheduleIndex //다음역의 출발 시간 인덱스
self.datePickerSource = schedule
self.datePickerSource.removeRange(0..<indexTemp)
if(schedule.count - 1 >= indexTemp){
transferBtn1.enabled = true
if(schedule[indexTemp].expressYN == "Y"){
self.setTransTimeBtnText1 = convertSecondToString(schedule[indexTemp].arriveTime, Mode: 1) + " " + schedule[indexTemp].directionNm + "행 (급행)"
}else{
self.setTransTimeBtnText1 = convertSecondToString(schedule[indexTemp].arriveTime, Mode: 1) + " " + schedule[indexTemp].directionNm + "행"
}
transferBtn1.setTitle(self.setTransTimeBtnText1, forState: .Normal)
self.notiStartTm = self.setTransTimeBtnText1//schedule1 //다다음 출발 시간을 설정하기 위함
let fTime : Int = self.info[transferTimeSchedulCount].navigateTm[self.info[transferTimeSchedulCount].navigateTm.count-1] //다음역의 도착시간
let currentTime : Int = returnCurrentTime()
if((fTime - currentTime) <= 0){
self.notiNextTm = 0
}else{
self.notiNextTm = fTime - (self.setAlertTime + 10)//%%70
}
}else{
transferBtn1.setTitle("없음", forState: .Normal)
transferBtn1.enabled = false
}
if(schedule.count - 2 >= indexTemp){
transferBtn2.enabled = true
if(schedule[indexTemp+1].expressYN == "Y"){
self.setTransTimeBtnText2 = convertSecondToString(schedule[indexTemp+1].arriveTime, Mode: 1) + " " + schedule[indexTemp+1].directionNm + "행 (급행)"
}else{
self.setTransTimeBtnText2 = convertSecondToString(schedule[indexTemp+1].arriveTime, Mode: 1) + " " + schedule[indexTemp+1].directionNm + "행"
}
transferBtn2.setTitle(self.setTransTimeBtnText2, forState: .Normal)
}else{
transferBtn2.setTitle("없음", forState: .Normal)
transferBtn2.enabled = false
}
transferBtn3.enabled = true
transferBtn3.setTitle("기타", forState: .Normal)
if(datePickerSource.count >= 3){
pickerView.selectRow(2, inComponent: 0, animated: true)
}
pickerView.reloadAllComponents()
}else{//다음역이 없을 경우 (마지막 열차 라인일 경우)
self.setTransTimeBtnText1 = ""
self.setTransTimeBtnText2 = ""
transferBtn1.setTitle("없음", forState: .Normal)
transferBtn2.setTitle("없음", forState: .Normal)
transferBtn3.setTitle("기타", forState: .Normal)
transferBtn1.enabled = false
transferBtn2.enabled = false
transferBtn3.enabled = false
}
let currentTime : Int = returnCurrentTime()
//sTime과 viaTime은 현재 라인의 출발시간과 이동시간임
if((sTime + viaTime - currentTime) <= 0){//비정상적인 경우
countTimeAct.text = "00분 00초"
//self.notiNextTm = sTime + viaTime
}else{//정상적인 경우 - 화면에 표시되는 카운트 다운을 위한 설정 구문
stimeMain = sTime
totaltimeMain = viaTime
countTimeAct.text = convertSecondToString(stimeMain + totaltimeMain - currentTime, Mode: 4)
}
if(self.info.count == transferTimeSchedulCount){ // 다음 역이 없을 경우
//finishTime.numberOfLines = 1
finishTime.text = "목적지 예상 도착 시간 : " + convertSecondToString(sTime + viaTime, Mode: 2)
localNotificationFunc(FinishTime: convertStringToSecond(countTimeAct.text!, Mode: 3), StationName: self.info[transferTimeSchedulCount-1].navigate[self.info[transferTimeSchedulCount-1].navigate.count - 1], FirstSchedule: /*schedule1*/self.setTransTimeBtnText1, SecondSchedule: /*schedule2*/self.setTransTimeBtnText2, FastExit: self.info[transferTimeSchedulCount-1].fastExit)
}else{ //다음 역이 있는 경우
finishTime.text = String(transferTimeSchedulCount) + "번째 환승역 예상 도착 시간 : " + convertSecondToString(sTime + viaTime, Mode: 2)
localNotificationFunc(FinishTime: convertStringToSecond(countTimeAct.text!, Mode: 3), StationName: self.info[transferTimeSchedulCount].navigate[0], FirstSchedule: /*schedule1*/self.setTransTimeBtnText1, SecondSchedule: /*schedule2*/self.setTransTimeBtnText2,FastExit: self.info[transferTimeSchedulCount-1].fastExit)
}
pickerView.hidden = true
tabBar.hidden = true
pickerView.reloadAllComponents()
for i in self.transferTimeSchedulCount..<self.info.count{
self.checkTouchAlert = true
transferStationTimeSchduel2(StartTime: convertStringToSecond(self.notiStartTm, Mode: 2), Index: i)
self.checkTouchAlert = false
}
}
// 전체적으로 알림을 설정하기 위한 함수
func transferStationTimeSchduel2(StartTime sTime : Int, Index index : Int) {
let fTime : Int = self.info[index].navigateTm[self.info[index].navigateTm.count-1]
var schedule1 : String = ""
var schedule2 : String = ""
var countTimeActTemp : String = ""
//여기부터 다음 역에 대한 구문임
if(self.info.count != index+1){//다음역이 있을경우
let schedule = self.info[index+1].startSchedule
let indexTemp : Int = self.info[index+1].startScheduleIndex
if(schedule.count - 1 > indexTemp){
if(schedule[indexTemp].expressYN == "Y"){
schedule1 = convertSecondToString(schedule[indexTemp].arriveTime, Mode: 1) + " " + schedule[indexTemp].directionNm + "행 (급행)"
}else{
schedule1 = convertSecondToString(schedule[indexTemp].arriveTime, Mode: 1) + " " + schedule[indexTemp].directionNm + "행"
}
}else{
schedule1 = ""
}
self.notiStartTm = schedule1
if(schedule.count - 2 > indexTemp){
if(schedule[indexTemp+1].expressYN == "Y"){
schedule2 = convertSecondToString(schedule[indexTemp+1].arriveTime, Mode: 1) + " " + schedule[indexTemp+1].directionNm + "행 (급행)"
}else{
schedule2 = convertSecondToString(schedule[indexTemp+1].arriveTime, Mode: 1) + " " + schedule[indexTemp+1].directionNm + "행"
}
}else{
schedule2 = ""
}
}
let currentTime : Int = returnCurrentTime()
if((fTime - currentTime) <= 0){
countTimeActTemp = "00분 00초"
}else{
countTimeActTemp = convertSecondToString(fTime - currentTime, Mode: 4)
}
if(index+1 == self.info.count){
localNotificationFunc(FinishTime: convertStringToSecond(countTimeActTemp, Mode: 3), StationName: self.info[index].navigate[self.info[index].navigate.count - 1], FirstSchedule: schedule1, SecondSchedule: schedule2, FastExit: self.info[index].fastExit)
}else{
localNotificationFunc(FinishTime: convertStringToSecond(countTimeActTemp, Mode: 3), StationName: self.info[index+1].navigate[0], FirstSchedule: schedule1, SecondSchedule: schedule2, FastExit: self.info[index].fastExit)
}
}
// 네트워크 경고창을 띄우는 함수
func networkAlert(mode : Int){
let alert = UIAlertController(title: "오류", message: "네트워크 연결을 확인해주세요.", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "확인", style: .Cancel){(_) in
if(mode == 1){
self.navigationController?.popViewControllerAnimated(true)
}
}
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true, completion: nil)
}
@IBOutlet var transferInfo: UILabel!
// 첫번째 시간표 버튼
@IBOutlet var transferBtn1: UIButton!
@IBAction func transferBtnAct1(sender: AnyObject) {
transferAct1(ButtonNumber: 1)
}
// 두번째 시간표 버튼
@IBOutlet var transferBtn2: UIButton!
@IBAction func transferBtnAct2(sender: AnyObject) {
transferAct1(ButtonNumber: 2)
}
// 기타 시간표 버튼
@IBOutlet var transferBtn3: UIButton!
@IBAction func transferBtnAct3(sender: AnyObject) {
transferActPicker()
}
@IBOutlet var infoNextST: UILabel!
@IBOutlet var countTimeAct: UILabel!
@IBOutlet var finishTime: UILabel!
@IBOutlet var pickerView: UIPickerView!
@IBOutlet var tabBar: UIToolbar!
@IBAction func doneBtn(sender: AnyObject) {
pickerView.hidden = true
tabBar.hidden = true
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.datePickerSource.count;
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if(self.datePickerSource[row].expressYN == "Y"){
return convertSecondToString(self.datePickerSource[row].arriveTime, Mode: 1) + " " + self.datePickerSource[row].directionNm + "행 (급행)"
}else{
return convertSecondToString(self.datePickerSource[row].arriveTime, Mode: 1) + " " + self.datePickerSource[row].directionNm + "행"
}
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
if(self.datePickerSource[row].expressYN == "Y"){
transferBtn3.setTitle(convertSecondToString(self.datePickerSource[row].arriveTime, Mode: 1) + " " + self.datePickerSource[row].directionNm + "행 (급행)", forState: .Normal)
}else{
transferBtn3.setTitle(convertSecondToString(self.datePickerSource[row].arriveTime, Mode: 1) + " " + self.datePickerSource[row].directionNm + "행", forState: .Normal)
}
self.datePickerBool = true
}
func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
var titleData : String = ""
if(self.datePickerSource[row].expressYN == "Y"){
titleData = convertSecondToString(self.datePickerSource[row].arriveTime, Mode: 1) + " " + self.datePickerSource[row].directionNm + "행(급행)"
}else{
titleData = convertSecondToString(self.datePickerSource[row].arriveTime, Mode: 1) + " " + self.datePickerSource[row].directionNm + "행"
}
let myTitle = NSAttributedString(string: titleData, attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()])
return myTitle
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "viewToRoute2") {
let navController = segue.destinationViewController as! NavigationController
let detailController = navController.topViewController as! AllRouteViewController
detailController.info = self.info
detailController.lastPageCheck = true
}
}
} |
//
// AppDelegate.swift
// Creating folder on Disk
//
// Created by Domenico on 27/05/15.
// License MIT
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func createFolder(){
let tempPath = NSTemporaryDirectory()
let imagesPath = tempPath.stringByAppendingPathComponent("images")
var error:NSError?
let fileManager = NSFileManager()
if fileManager.createDirectoryAtPath(imagesPath,
withIntermediateDirectories: true,
attributes: nil,
error: nil){
println("Created the directory")
} else {
println("Could not create the directory")
}
}
}
|
@testable import TMDb
import XCTest
final class ImageMetadataTests: XCTestCase {
func testIDReturnsFilePath() {
XCTAssertEqual(imageMetadata.id, imageMetadata.filePath)
}
func testDecodeReturnsImageMetadata() throws {
let result = try JSONDecoder.theMovieDatabase.decode(ImageMetadata.self, fromResource: "image-metadata")
XCTAssertEqual(result.filePath, imageMetadata.filePath)
XCTAssertEqual(result.width, imageMetadata.width)
XCTAssertEqual(result.height, imageMetadata.height)
XCTAssertEqual(result.aspectRatio, imageMetadata.aspectRatio)
XCTAssertEqual(result.voteAverage, imageMetadata.voteAverage)
XCTAssertEqual(result.voteCount, imageMetadata.voteCount)
XCTAssertEqual(result.languageCode, imageMetadata.languageCode)
}
private let imageMetadata = ImageMetadata(
filePath: URL(string: "/fCayJrkfRaCRCTh8GqN30f8oyQF.jpg")!,
width: 1280,
height: 720,
aspectRatio: 1.77777777777778,
voteAverage: 5.7,
voteCount: 957,
languageCode: "en"
)
}
|
import UIKit
//task1: Решить квадратное уравнение ax^2 + bx + c = 0. Даны переменные a, b,c - нужно получить x1,x2
func findRootsOfQuadraticEquation(a: Double, b: Double, c: Double) {
let d = pow(b, 2) - (4*a*c)
if d > 0 {
let x1 = ((-b) + Double(d.squareRoot())) / (2*a)
let x2 = (b + Double((d.squareRoot()))) / (2*a)
print("The equation has 2 roots. x1 = \(x1) and x2 = \(x2).")
}
else if d == 0
{
let x = (-b)/(2*a)
print("The equation has only 1 root: \(x).")
}
else {
print("The equation has no roots.")
}
}
findRootsOfQuadraticEquation(a: 2, b: 4, c: 2)
//task2: Даны катеты прямоугольного треугольника. Найти площадь, периметр и гипотенузу треугольника.
func findHypotenuse (leg1: Double, leg2: Double) -> Double {
let hypotenuse = (pow((leg1), 2) + pow((leg2), 2)).squareRoot()
print("The hypotenuse is \(hypotenuse).")
return hypotenuse.rounded()
}
func findPerimeter (leg1: Double, leg2: Double) {
let perimeter = leg1 + leg2 + findHypotenuse(leg1: leg1, leg2: leg2)//hypotenuse
print("The perimeter is equal to \(perimeter)")
}
func findAreaOfTriangle (leg1: Double, leg2: Double) {
let area = leg1 * leg2 / 2
print("The area of triangle is equal to \(area)")
}
print(findHypotenuse(leg1: 3,leg2: 4), findPerimeter(leg1: 3,leg2: 4), findAreaOfTriangle(leg1: 3,leg2: 4))
/*task3: Пользователь вводит сумму вклада в банк и годовой процент.
Найти сумму вклада через 5 лет.
Написать через функцию, количество лет вклада может меняться.
Учитывайте сложный процент*/
func countMyMoney(initalSum: Float, percent: Float, years: Float){
let totalSum = initalSum * pow((1 + 0.01 * percent), years)
print("If you save your sum of \(initalSum) for the next \(years) years then you'll have \(totalSum)")
}
countMyMoney(initalSum: 50000, percent: 10, years: 5)
//task4: Написать функцию, которая определяет четное число или нет.
func checkIfNumberIsEven(number: Int) {
if number % 2 == 0 {
print("\(number) is an even number.")
}
else {
print("\(number) is an odd number.")
}
}
checkIfNumberIsEven(number: 2)
//task5: Написать функцию, которая определяет, делится ли число без остатка на 3.
func checkIfNumberHasReminder(dividend: Int) {
let divisor = 3
if dividend % divisor == 0 {
print("The number \(dividend) has not reminder.")
}
else {
print("Oops. The number \(dividend) has reminder.")
}
}
checkIfNumberHasReminder(dividend: 10)
//task6: Создать возрастающий массив из 100 чисел.
var numbers = [Int] ()
var number = 0
while number < 100 {
numbers.append(number+1)
number += 1
}
//task7: Удалить из этого массива все четные числа и все числа, которые не делятся на 3.
for number in numbers
where (number % 2 == 0) || (number % 3 == 0)
{
numbers.remove(at: (numbers.firstIndex(of: number)!))
}
print(numbers)
|
//
// FromTopSecondVC.swift
// ViewControllerTransition
//
// Created by landixing on 2017/7/5.
// Copyright © 2017年 WJQ. All rights reserved.
//
import UIKit
class FromTopSecondVC: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
updatePreferredContentSizeWithTraitCollection(traitCollection: self.traitCollection)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
}
func updatePreferredContentSizeWithTraitCollection(traitCollection: UITraitCollection) {
self.preferredContentSize = CGSize(width: self.view.bounds.size.width, height: traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.compact ? 270 : 270);
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// ContentView.swift
// SwiftUIForAllDevice-WatchOS Extension
//
// Created by Moh Zinnur Atthufail Addausi on 08/09/20.
// Copyright © 2020 Moh Zinnur Atthufail Addausi. All rights reserved.
//
import SwiftUI
struct ContentView: View {
private let peopleservice = PeopleService.getAll()
var body: some View {
List{
ForEach(peopleservice, id: \.name){ people in
NavigationLink(destination: SharedDetailView(people: people)){
PeopleCell(people: people)
}
}
}.listStyle(CarouselListStyle())
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct PeopleCell: View {
let people : People
var body: some View {
VStack(alignment: .center){
Image(people.image)
.resizable()
.frame(width: 100, height: 100)
Text(people.name)
.font(.system(size : 12))
}.frame(minWidth: 0, maxWidth: .infinity)
}
}
|
class Solution {
var cache = [[Int]: Int]()
func rob(_ nums: [Int]) -> Int {
let results = [
robMax(from: 0, in: nums, size: nums.count-1),
robMax(from: 1, in: nums, size: nums.count),
robMax(from: 2, in: nums, size: nums.count)
]
return results.max()!
}
func robMax(from start: Int, in houses: [Int], size: Int) -> Int {
guard start < size else { return 0 }
if let cached = cache[[start, size]] { return cached }
let nextMax = max(
robMax(from: start+2, in: houses, size: size),
robMax(from: start+3, in: houses, size: size)
)
let result = houses[start] + nextMax
cache[[start, size]] = result
return result
}
}
|
//
// CountingCell.swift
// RPG_Health_Tracker
//
// Created by steven Hoover on 8/16/17.
// Copyright © 2017 steven Hoover. All rights reserved.
//
import UIKit
class CountingCell: UICollectionViewCell
{
@IBOutlet weak var label: UILabel!
}
|
//
// ViewController.swift
// MemeMe 1.0 Test
//
// Created by Lucas Cotta on 5/2/17.
// Copyright © 2017 Talem. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate,
UINavigationControllerDelegate, UITextFieldDelegate {
// MARK: Outlets
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var cameraButton: UIBarButtonItem!
@IBOutlet weak var topText: UITextField!
@IBOutlet weak var bottomText: UITextField!
@IBOutlet weak var shareButton: UIBarButtonItem!
// MARK: Constructor
func save() {
let memedImage = generateMemedImage()
let _ = Meme(topText: topText.text!, bottomText: bottomText.text!, originalImage: imageView.image!, memedImage: memedImage)
}
// MARK: Cycle Methods
override func viewDidLoad() {
super.viewDidLoad()
// Delegates
topText.delegate = self
bottomText.delegate = self
// Initial settings
configureTextField(textField: topText, text: "TOP", defaultAttributes: memeTextAttributes)
configureTextField(textField: bottomText, text: "BOTTOM", defaultAttributes: memeTextAttributes)
// Hide share button
shareButton.isEnabled = false
}
override func viewDidAppear(_ animated: Bool) {
// In case of the device doesn't have a camera
cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera)
}
// Sliding the view up
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
subscribeToKeyboardNotifications()
}
// Sliding the view back to the original position
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeFromKeyboardNotifications()
}
// MARK: Delegates
// Camera method selection
func presentImagePickerWith(sourceType: UIImagePickerControllerSourceType){
let pickerController = UIImagePickerController()
pickerController.sourceType = sourceType
self.present(pickerController, animated: true, completion: nil)
pickerController.delegate = self
}
// MARK: Attributes (Keyboard + TextField)
// Textfield attributes
let memeTextAttributes:[String:Any] = [
NSStrokeColorAttributeName: UIColor.black,
NSForegroundColorAttributeName: UIColor.white,
NSFontAttributeName: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSStrokeWidthAttributeName: -3.0]
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.text = ""
}
func configureTextField(textField: UITextField, text: String, defaultAttributes: [String:Any]){
textField.defaultTextAttributes = defaultAttributes
textField.textAlignment = .center
textField.text = text
}
// Keyboard attributes
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// MARK: Notifications
func subscribeToKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)
}
func unsubscribeFromKeyboardNotifications() {
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.removeObserver(self, name: .UIKeyboardWillHide, object: nil)
}
// Notification sender to slide the view up on the bottom text field
func keyboardWillShow(_ notification:Notification) {
if bottomText.isFirstResponder {
view.frame.origin.y -= getKeyboardHeight(notification)
}
}
//
// Notification sender to slide the view back in the original position
func keyboardWillHide(_ notification:Notification) {
view.frame.origin.y = 0
}
// Getting the keyboard height
func getKeyboardHeight(_ notification:Notification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue // of CGRect
return keyboardSize.cgRectValue.height
}
// MARK: Actions
// Picking the image from the album
@IBAction func pickImageFromAlbum(_ sender: Any) {
presentImagePickerWith(sourceType: .photoLibrary)
}
// Taking a picture as a image
@IBAction func pickImageFromCamera(_ sender: Any) {
presentImagePickerWith(sourceType: .camera)
}
// Canceling the current meme and returning to inital state
@IBAction func cancelMeme(_ sender: Any) {
topText.text = "TOP"
bottomText.text = "BOTTOM"
shareButton.isEnabled = false
imageView.image = nil
// In case of the user cancel a Meme with the keyboard open
view.endEditing(true)
}
// Sharing the current Meme
@IBAction func shareMeme(_ sender: Any) {
let image = generateMemedImage()
let controller = UIActivityViewController(activityItems: [image], applicationActivities: nil)
// If the user finish the Meme, save the memed image and dismiss the activity view
controller.completionWithItemsHandler = {
activity, completed, items, error in
if completed {
self.save()
self.dismiss(animated: true, completion: nil)
}
}
self.present(controller, animated: true, completion: nil)
}
// MARK: Help Fuctions
// If the "cancel" button is pressed on the album selection
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
// Sending the selected picture to UIImageView
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageView.image = image
}
shareButton.isEnabled = true
self.dismiss(animated: true, completion: nil)
}
// Generating memed image
func generateMemedImage() -> UIImage {
self.navigationController?.setNavigationBarHidden(true, animated: false)
self.navigationController?.setToolbarHidden(true, animated: false)
// Render view to an image
UIGraphicsBeginImageContext(self.view.frame.size)
view.drawHierarchy(in: self.view.frame, afterScreenUpdates: true)
let memedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.navigationController?.setNavigationBarHidden(true, animated: false)
self.navigationController?.setToolbarHidden(true, animated: false)
return memedImage
}
}
|
//
// SongsTableViewController.swift
// newsic
//
// Created by Andreas Schulz on 16.08.16.
// Copyright © 2016 Andreas Schulz. All rights reserved.
//
import UIKit
import MediaPlayer
class AlbumsTableViewController: UITableViewController {
var albums: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
if let albums = MPMediaQuery.albums().collections {
for album in albums {
self.albums.append(album.representativeItem!.albumTitle!)
}
}
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let insets = UIEdgeInsetsMake(topLayoutGuide.length, 0, bottomLayoutGuide.length, 0)
tableView.contentInset = insets
tableView.scrollIndicatorInsets = insets
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return albums.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "albumCell", for: indexPath)
cell.textLabel!.text = albums[indexPath.row]
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// BasicViewController.swift
// SnapperDemo
//
// Created by Yuma Matsune on 2018/01/20.
// Copyright © 2018年 matsune. All rights reserved.
//
import UIKit
import SnapGestureRecognizer
final class BasicViewController: UIViewController {
let snapView = UIView(frame: .zero)
var initPosition: CGPoint!
let snapGesture = SnapGestureRecognizer()
var decay: CGFloat = 0.0
override func viewDidLoad() {
super.viewDidLoad()
snapView.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
snapView.layer.masksToBounds = true
snapView.layer.cornerRadius = 8.0
snapView.center = CGPoint(x: view.center.x, y: 255)
initPosition = snapView.center
snapView.backgroundColor = .orange
view.insertSubview(snapView, at: 0)
let snapPoints = [
SnapPoint(x: 50, y: 150),
SnapPoint(x: view.bounds.width - 50, y: 150),
SnapPoint(x: 50, y: 360),
SnapPoint(x: view.bounds.width - 50, y: 360)
]
for i in 0..<4 {
let v = createSnapPointView(center: snapPoints[i])
view.insertSubview(v, at: 0)
}
snapGesture.anchorPoint = .center
snapGesture.snapPoints = snapPoints
snapGesture.snapDelegate = self
snapView.addGestureRecognizer(snapGesture)
bindSetting()
}
private func createSnapPointView(center: SnapPoint) -> UIView {
let v = UIView(frame: CGRect(x: 0, y: 0, width: 60, height: 60))
v.backgroundColor = .gray
v.center = center.cgPoint
v.layer.masksToBounds = true
v.layer.cornerRadius = 8.0
return v
}
private func bindSetting() {
guard let settingVC = childViewControllers.first(where: {$0 is BasicConfigTableViewController}) as? BasicConfigTableViewController else {
return
}
settingVC.onChangeSnapTo = { row in
self.snapGesture.snapTo = [SnapTo.direction, SnapTo.nearest, SnapTo.custom][row]
}
settingVC.onChangePanDirection = { row in
self.snapGesture.panDirection = [PanDirection.diagonal, PanDirection.horizontal, PanDirection.vertical][row]
}
settingVC.onChangeDecay = { value in
self.decay = CGFloat(value)
}
settingVC.onChangeDuration = { value in
self.snapGesture.duration = TimeInterval(value)
}
settingVC.onChangeDelay = { value in
self.snapGesture.delay = TimeInterval(value)
}
settingVC.onChangeSpring = { value in
self.snapGesture.springVelocity = CGFloat(value)
}
settingVC.onChangeDamping = { value in
self.snapGesture.dampingRatio = CGFloat(value)
}
}
}
extension BasicViewController: SnapGestureRecognizerDelegate {
func snapRecognizer(_ snapRecognizer: SnapGestureRecognizer, decayAt point: CGPoint) -> CGFloat {
return decay
}
func snapRecognizer(_ snapRecognizer: SnapGestureRecognizer, towardSnapPointAt point: CGPoint) -> CGPoint {
// In this case, always snap to initial position when `snapTo` is `.custom`.
return initPosition
}
func snapRecognizerWillBeginPan(_ snapRecognizer: SnapGestureRecognizer) {
print("willBeginPan")
}
func snapRecognizerDidPan(_ snapRecognizer: SnapGestureRecognizer) {
print("didPan")
}
func snapRecognizerDidEndPan(_ snapRecognizer: SnapGestureRecognizer) {
print("DidEndPan")
}
func snapRecognizerWillBeginSnap(_ snapRecognizer: SnapGestureRecognizer, began: SnapPoint, toward: SnapPoint) {
print("willBeginSnap")
}
func snapRecognizerDidEndSnap(_ snapRecognizer: SnapGestureRecognizer, began: SnapPoint, toward: SnapPoint) {
print("didEndSnap")
}
}
|
//
// SortingStuff.swift
// ClosuresAreGreat
//
// Created by Jim Campagno on 10/25/16.
// Copyright © 2016 Gamesmith, LLC. All rights reserved.
//
import Foundation
struct ToyBin {
var ships: [Ship] = []
var books: [Book] = []
var bowlingPins: [BowlingPin] = []
var musicCDs: [MusicCD] = []
func sortShps() {
ships.sorted { (ship1:Ship, ship2:Ship) -> Bool in
return ship1.age > ship2.age
}
}
func sortBooks() {
books.sorted {
return ($0).name < ($1).name
}
}
func sortBowlingPins() {
bowlingPins.sorted {
return ($0).color.rawValue < ($1).color.rawValue
}
}
func sortMusicCDs() {
musicCDs.sorted { (cd1: MusicCD, cd2: MusicCD) -> Bool in
if cd1.name < cd2.name {
return true
}
if cd1.name == "Drake" {
musicCDs.dropFirst()
return true
}
return false
}
}
func changeColorOfAllPins(to color: Color) {
bowlingPins.map { (bow1: BowlingPin) -> [BowlingPin] in
var newArray: [BowlingPin] = []
newArray.append(BowlingPin(name: bow1.name, film: bow1.film, color: color))
return newArray
}
}
// TODO: Implement all of the sort functions (lets organize this toy bin!)
}
struct Ship {
var name: String
var age: Int
}
struct Book {
var name: String
var year: Int
var author: String
}
struct BowlingPin {
var name: String
var film: String
var color: Color
}
enum Color: Int {
case red, organe, yellow, green, blue, indigo, violet
}
struct MusicCD {
var name: String
var year: Int
var songs: [String]
}
|
import Foundation
import Combine
import MarketKit
import CurrencyKit
import HsExtensions
class MarketGlobalTvlMetricService {
typealias Item = DefiCoin
private let marketKit: MarketKit.Kit
private let currencyKit: CurrencyKit.Kit
private var tasks = Set<AnyTask>()
private var cancellables = Set<AnyCancellable>()
weak var chartService: MetricChartService? {
didSet {
subscribeChart()
}
}
private var internalState: State = .loading {
didSet {
syncState()
}
}
@PostPublished private(set) var state: MarketListServiceState<DefiCoin> = .loading
var sortDirectionAscending: Bool = false {
didSet {
syncIfPossible(reorder: true)
}
}
@PostPublished var marketPlatformField: MarketModule.MarketPlatformField = .all {
didSet {
syncIfPossible(reorder: true)
}
}
var marketTvlField: MarketModule.MarketTvlField = .diff {
didSet {
syncIfPossible()
}
}
private(set) var priceChangePeriod: HsTimePeriod = .day1 {
didSet {
syncIfPossible()
}
}
init(marketKit: MarketKit.Kit, currencyKit: CurrencyKit.Kit) {
self.marketKit = marketKit
self.currencyKit = currencyKit
syncDefiCoins()
}
private func syncDefiCoins() {
tasks = Set()
if case .failed = state {
internalState = .loading
}
Task { [weak self, marketKit, currency] in
do {
let defiCoins = try await marketKit.defiCoins(currencyCode: currency.code)
self?.internalState = .loaded(defiCoins: defiCoins)
} catch {
self?.internalState = .failed(error: error)
}
}.store(in: &tasks)
}
private func syncState(reorder: Bool = false) {
switch internalState {
case .loading:
state = .loading
case .loaded(let defiCoins):
let defiCoins = defiCoins
.filter { defiCoin in
switch marketPlatformField {
case .all: return true
default: return defiCoin.chains.contains(marketPlatformField.chain)
}
}
.sorted { lhsDefiCoin, rhsDefiCoin in
let lhsTvl = lhsDefiCoin.tvl(marketPlatformField: marketPlatformField) ?? 0
let rhsTvl = rhsDefiCoin.tvl(marketPlatformField: marketPlatformField) ?? 0
return sortDirectionAscending ? lhsTvl < rhsTvl : lhsTvl > rhsTvl
}
state = .loaded(items: defiCoins, softUpdate: false, reorder: reorder)
case .failed(let error):
state = .failed(error: error)
}
}
private func syncIfPossible(reorder: Bool = false) {
guard case .loaded = internalState else {
return
}
syncState(reorder: reorder)
}
private func subscribeChart() {
cancellables = Set()
guard let chartService = chartService else {
return
}
chartService.$interval
.sink { [weak self] in self?.priceChangePeriod = $0 }
.store(in: &cancellables)
}
}
extension MarketGlobalTvlMetricService {
var currency: Currency {
currencyKit.baseCurrency
}
}
extension MarketGlobalTvlMetricService: IMarketListService {
var statePublisher: AnyPublisher<MarketListServiceState<Item>, Never> {
$state
}
func refresh() {
syncDefiCoins()
}
}
extension MarketGlobalTvlMetricService: IMarketListCoinUidService {
func coinUid(index: Int) -> String? {
guard case .loaded(let defiCoins, _, _) = state, index < defiCoins.count else {
return nil
}
switch defiCoins[index].type {
case .fullCoin(let fullCoin): return fullCoin.coin.uid
default: return nil
}
}
}
extension MarketGlobalTvlMetricService {
private enum State {
case loading
case loaded(defiCoins: [DefiCoin])
case failed(error: Error)
}
}
extension DefiCoin {
func tvl(marketPlatformField: MarketModule.MarketPlatformField) -> Decimal? {
switch marketPlatformField {
case .all: return tvl
default: return chainTvls[marketPlatformField.chain]
}
}
}
|
//
// RepositoryTests.swift
// RepositoryTests
//
// Created by Fernando Moya de Rivas on 01/09/2019.
// Copyright © 2019 Fernando Moya de Rivas. All rights reserved.
//
import XCTest
import Mockingjay
@testable import Repository
class RepositoryTests: XCTestCase {
// Fetches the first page of the Food2ForkAPI and checks the results are not empty
func testFetchRecipesFirstPage() {
let dataStore = Food2ForkWebservice()
let expectation = XCTestExpectation(description: "Fetching recipes. Page 1")
dataStore.fetchRecipes(at: 1) { (response) in
guard let recipes = try? response.get() else {
return XCTFail()
}
XCTAssertFalse(recipes.isEmpty)
expectation.fulfill()
}
wait(for: [expectation], timeout: 3)
}
// Mocks a Forbidden response and asserts the error raised is the expected
func testFetchRecipesForbidden() {
let dataStore = Food2ForkWebservice()
let page: UInt = 3
stub(uri(Food2ForkEndpoint.search(dataStore.apiKey, page).url),
http(403))
let expectation = XCTestExpectation(description: "Mocking Forbidden response")
dataStore.fetchRecipes(at: page) { (response) in
switch response {
case .success:
XCTFail()
case .failure(let error):
XCTAssertEqual(error, .forbidden)
}
expectation.fulfill()
}
wait(for: [expectation], timeout: 3)
}
}
|
//
// MessageViewModel.swift
// Seatmates
//
// Created by Jansen Ducusin on 4/21/21.
//
import UIKit
struct MessageViewModel {
private let message: Conversation
var messageBackgroundColor: UIColor{
return message.isFromCurrentUser ? .systemTeal : .darkGray
}
var rightAnchorActive: Bool {
return message.isFromCurrentUser
}
var leftAnchorActive: Bool {
return !message.isFromCurrentUser
}
var shouldHideProfileImage: Bool {
return message.isFromCurrentUser
}
init(message:Conversation){
self.message = message
}
}
|
//
// Breakdown.swift
// Simplicity
//
// Created by Anthony Lai on 11/22/17.
// Copyright © 2017 LikeX4Y. All rights reserved.
//
import Foundation
class Breakdown {
// MARK: Properties
var category: String
var amounts: [Double]
// MARK: Initialization
init?(category: String, amounts: [Double]) {
if (category.isEmpty || amounts.isEmpty) {
return nil
}
self.category = category
self.amounts = amounts
}
}
|
//
// Match.swift
// TG
//
// Created by Andrii Narinian on 7/10/17.
// Copyright © 2017 ROLIQUE. All rights reserved.
//
import Foundation
class GameMode: Model {
required init(dict: [String : Any?]) {
super.init(dict: dict)
type = "GameMode"
name = dict["name"] as? String
id = dict["id"] as? String
}
required init(id: String, type: ModelType) {
super.init(id: id, type: type)
}
override var encoded: [String : Any?] {
return [
"name": name,
"id": id,
"type": type
]
}
}
enum GameModeType: String {
case casual_aral, casual, ranked, blitz_pvp_ranked
var description: String {
switch self {
case .casual: return "casual match"
case .casual_aral: return "royal battle"
case .ranked: return "ranked match"
case .blitz_pvp_ranked: return "blitz pvp"
}
}
}
class Match: Model, Equatable, Comparable {
var gameMode: GameMode?
var titleId: String?
var createdAt: Date?
var patchVersion: String?
var shardId: String?
var duration: Int?
var endGameReason: String?
var queue: String?
var rosters = [Roster]()
var assets = [Asset]()
var description: String?
var userWon: Bool?
var is5v5:Bool {
return (rosters.first?.participants?.count ?? 0) > 3
}
required init(dict: [String: Any?]) {
self.gameMode = GameMode(id: dict["gameMode"] as? String ?? kEmptyStringValue, type: .gamemode)
self.titleId = dict["titleId"] as? String
self.createdAt = TGDateFormats.iso8601WithoutTimeZone.date(from: dict["createdAt"] as? String ?? "")
self.patchVersion = dict["patchVersion"] as? String
self.shardId = dict["shardId"] as? String
self.endGameReason = dict["endGameReason"] as? String
self.queue = dict["queue"] as? String
self.duration = dict["duration"] as? Int
self.assets = (dict["assets"] as? [[String: Any]] ?? [[String: Any]]()).map { Asset(dict: $0) }
self.rosters = (dict["rosters"] as? [[String: Any]] ?? [[String: Any]]()).map { Roster(dict: $0) }
self.description = dict["description"] as? String
self.userWon = dict["userWon"] as? Bool
super.init(dict: dict)
}
required init(id: String, type: ModelType) {
super.init(id: id, type: type)
}
override var encoded: [String : Any?] {
let dict: [String: Any?] = [
"id": id,
"type": type,
"gameMode": gameMode?.id,
"titleId": titleId,
"createdAt": TGDateFormats.iso8601WithoutTimeZone.string(from: createdAt ?? Date()),
"patchVersion": patchVersion,
"shardId": shardId,
"endGameReason": endGameReason,
"queue": queue,
"duration": duration,
"assets": assets.map { $0.encoded },
"rosters": rosters.map { $0.encoded },
"description": description,
"userWon": userWon
]
return dict
}
}
func ==(lhs: Match, rhs: Match) -> Bool {
return lhs.id == rhs.id
}
func <(lhs: Match, rhs: Match) -> Bool {
return lhs.createdAt ?? Date() > rhs.createdAt ?? Date()
}
func <=(lhs: Match, rhs: Match) -> Bool {
return lhs.createdAt ?? Date() >= rhs.createdAt ?? Date()
}
func >=(lhs: Match, rhs: Match) -> Bool {
return lhs.createdAt ?? Date() <= rhs.createdAt ?? Date()
}
func >(lhs: Match, rhs: Match) -> Bool {
return lhs.createdAt ?? Date() < rhs.createdAt ?? Date()
}
|
//
// AppDelegate.swift
// Nihongo
//
// Created by Dang Nguyen Vu on 3/2/17.
// Copyright © 2017 Dang Nguyen Vu. All rights reserved.
//
import UIKit
import Firebase
import FirebaseAuth
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FIRApp.configure()
FIRAuth.auth()
return true
}
// MARK: - App Lifecycle
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
}
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
enum Emotion{
case 😊, 😔, 😶
}
// ==== Lets define Humans
class Human{
var context: Any? = nil
var name:String = ""{
didSet{
print("\(self): is named \"\(name)\".")
}
}
var age = 0{
didSet{
print("\(self): is now \(age) years old.")
}
}
var feeling:Emotion = .😶{
didSet{
print("\(self): is now \(feeling).")
}
}
convenience init(_ name:String, context: Any? = nil) {
self.init()
self.name = name
print("CREATED " + "\(self)")
}
}
extension Human: CustomStringConvertible {
var description: String {
return "Human:name:\(self.name)"
}
}
// ==== Lets define Family
class Family{
var members:[Human] = []
init(firstPerson:Human,secondPerson:Human) {
members.append(contentsOf: [firstPerson,secondPerson])
print("Family started: \(self.members)")
}
func makeLove(){
// Some complex logic unknown to mortals
let luck = arc4random_uniform(100)
switch luck {
case 100:
self.members.append(contentsOf: self.createChildren(number: 3)) // Triplets
print("Congratulations! you have triplets!")
case 80...90:
self.members.append(contentsOf: self.createChildren(number: 3)) // Twins
print("Congratulations! you have twins!")
case 50...60:
self.members.append(contentsOf: self.createChildren(number: 3)) // Single child
print("Congratulations! you have a child")
default: break // I'm sorry
}
}
private func createChildren(number:Int) -> [Human]{
var children:[Human] = []
for child in 0..<number{
children.append(Human())
}
return children
}
}
extension Family: CustomStringConvertible {
var description: String {
return "Family: \(self.members)"
}
}
prefix operator +++
postfix operator ☺︎
postfix operator ☹
infix operator ♡: AdditionPrecedence
extension Human{
static prefix func +++(someGuy: inout Human){
someGuy.age += 1
}
static postfix func ☺︎(someGuy: inout Human) {
someGuy.feeling = .😊
}
static postfix func ☹(someGuy: inout Human) {
someGuy.feeling = .😔
}
static func ♡(someGuy: inout Human, otherGuy: inout Human) -> Family {
let family = Family(firstPerson: someGuy, secondPerson: otherGuy)
// After marriage both are happy...
someGuy☺︎
otherGuy☺︎
return family
}
}
// MAIN()
print("lets create a human being..")
var adam = Human("Adam")
print("He should age in the course of time..")
+++adam
switch adam.feeling{
case .😊: break // all seems good
case .😔,.😶:
print("Something is wrong with adam. I think its time to create a companion for adam, so lets create eve keeping adam in mind")
var eve = Human("Eve",context:adam)
// Bone of my bone and flesh of my flesh, Lets make the Both of them start a family
let 👫 = adam ♡ eve
👫.makeLove()
}
|
//
// AddContactViewController.swift
// ContactsApplication
//
// Created by Hiba on 03/12/2020.
//
import UIKit
import CoreData
class AddContactViewController: UIViewController {
var titleText = "Add Contact"
var contact : NSManagedObject? = nil
var indexPathForContact: IndexPath? = nil
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.text = titleText
if let contact = self.contact{
nameTextField.text = contact.value(forKey: "name") as? String
phoneNumberTextField.text = contact.value(forKey: "phoneNumber") as? String
emailTextField.text = contact.value(forKey: "email") as? String
adressTextField.text = contact.value(forKey: "adress") as? String
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var phoneNumberTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var adressTextField: UITextField!
@IBAction func saveAndClose(_ sender: Any) {
performSegue(withIdentifier : "unwindToContactList", sender :self)
}
@IBAction func close(_ sender: Any) {
nameTextField.text = nil
phoneNumberTextField.text = nil
emailTextField.text = nil
adressTextField.text = nil
performSegue(withIdentifier : "unwindToContactList", sender :self)
}
}
|
/*
Calculate LCM
*/
import Foundation
print("Enter the first number: ", terminator: "")
var num1 = Int(readLine()!)
print("Enter the second number:", terminator: "")
var num2 = Int(readLine()!)
var check = 0;
if num1! > num2! {
check = num1!
} else {
check = num2!
}
var startTime: Date = Date();
for n in (check ..< num1! * num2! + 1) where n % check == 0 {
if n % num1! == 0 && n % num2! == 0 {
print("The LCM for \(num1!) and \(num2!) is \(n)")
break
}
}
var finishTime: Date = Date();
var duration = finishTime.timeIntervalSince(startTime)
print("The time took is \(duration) seconds")
|
//
// UIViewControllerPassValueDelegate.swift
// YuQinClient
//
// Created by ksn_cn on 16/3/18.
// Copyright © 2016年 YuQin. All rights reserved.
//
import Foundation
@objc protocol UIViewControllerPassValueDelegate {
optional func passValue(valueForBMKPoiInfo: BMKPoiInfo)
} |
//
// Configuration.swift
// OmiseGO
//
// Created by Mederic Petit on 9/10/2017.
// Copyright © 2017-2018 Omise Go Pte. Ltd. All rights reserved.
//
/// Protocol containing the required variable for the initialization of a Client
protocol Configuration {
/// The current SDK version
var apiVersion: String { get }
/// The base URL of the wallet server:
/// When initializing the HTTPAPI, this needs to be an http(s) url
/// When initializing the SocketClient, this needs to be a ws(s) url
var baseURL: String { get }
/// The credential object containing the authentication info if needed
var credentials: Credential { get set }
/// A boolean indicating if the debug logs should be printed to the console
var debugLog: Bool { get }
}
|
//
// Images+CoreDataProperties.swift
//
//
// Created by Tianxiao Yang on 12/10/16.
//
// This file was automatically generated and should not be edited.
//
import Foundation
import CoreData
extension Images {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Images> {
return NSFetchRequest<Images>(entityName: "Images");
}
@NSManaged public var imageId: String?
@NSManaged public var imageData: NSData?
}
|
//
// URLCompositionTests.swift
// testTests
//
// Created by leon on 12/07/2021.
//
import XCTest
@testable import test
class URLCompositionTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testMakingAURL() throws {
for path in URL.Path.allCases {
let url = URL.make(path: path)
XCTAssertTrue(url != nil)
}
}
}
|
protocol Fighter { init() }
struct XWing: Fighter { init(){} }
struct YWing: Fighter { init(){} }
func launchFighter() -> some Fighter {
return XWing()
}
let red5 = launchFighter()
func Bla (x:Fighter)
{
}
|
//
// ZYImageViewController.swift
// ZYImageChince-Swift
//
// Created by ybon on 2016/12/7.
// Copyright © 2016年 ybon. All rights reserved.
//
import UIKit
import Photos
class ZYImageViewController: UIViewController ,UICollectionViewDelegate,UICollectionViewDataSource{
var maxCount = 0;
var selectImageFaction:((_ imageArr:Array<UIImage>)->Void)?;
private var dataArray:Array<UIImage>?;
private var selectedArray:Array<UIImage>?;
private var _collectionView:UICollectionView?;
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false;
self.view.backgroundColor = UIColor.white;
if maxCount <= 0{
maxCount = 3;
}
self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "取消", style: UIBarButtonItemStyle.plain, target: self, action: #selector(cancelBarItemAction));
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "确定", style: UIBarButtonItemStyle.plain, target: self, action: #selector(sureBarItemAction));
let layout = UICollectionViewFlowLayout.init();
layout.minimumLineSpacing = 10;
layout.minimumInteritemSpacing = 0;
layout.sectionInset = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10);
layout.itemSize = CGSize.init(width: (UIScreen.main.bounds.size.width-40)/3, height: (UIScreen.main.bounds.size.width-40)/3);
layout.scrollDirection = UICollectionViewScrollDirection.vertical;
_collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 64, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height-64), collectionViewLayout: layout);
_collectionView?.register(object_getClass(ZYImageCollectionViewCell()), forCellWithReuseIdentifier: "zyitem");
//设置滑动速度
// _collectionView?.decelerationRate = UIScrollViewDecelerationRateFast;
_collectionView?.delegate = self;
_collectionView?.dataSource = self;
_collectionView?.backgroundColor = UIColor.lightGray;
self.view.addSubview(_collectionView!);
loadData();
}
//取消按钮
func cancelBarItemAction(item:UIBarButtonItem){
self.dismiss(animated: true, completion: nil);
}
//确定按钮
func sureBarItemAction(item:UIBarButtonItem){
self.dismiss(animated: true, completion: nil);
if selectImageFaction != nil {
selectImageFaction!(selectedArray!);
}
}
//dataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if dataArray == nil {
return 0;
}
return (dataArray?.count)!;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "zyitem", for: indexPath) as? ZYImageCollectionViewCell;
cell?.imageV?.image = dataArray?[indexPath.row];
if (selectedArray?.contains((cell?.imageV?.image)!))! == true{
cell?.selectedImageV?.isHidden = false;
}else{
cell?.selectedImageV?.isHidden = true;
}
return cell!;
}
//delegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as? ZYImageCollectionViewCell;
if cell?.selectedImageV?.isHidden == true{
if (selectedArray?.count)! >= maxCount {
self.showAlert(title: "图片超过数量", message: "无法再选取");
return;
}
}
cell?.selectedImageV?.isHidden = !(cell?.selectedImageV?.isHidden)!;
if cell?.selectedImageV?.isHidden == false{
selectedArray?.append((dataArray?[indexPath.row])!);
}else{
var i = 0;
for asset in selectedArray!{
if asset == dataArray?[indexPath.row]{
selectedArray?.remove(at: i);
return;
}
i = i + 1;
}
}
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
}
func loadData(){
ZYImageManager.GetAllImagePhasset { (asetArray) in
self.selectedArray = Array.init();
self.dataArray = asetArray;
self._collectionView?.reloadData();
}
}
}
|
//
// NoInternet.swift
// SoleFinder
//
// Created by Vinay Kolwankar on 06/03/19.
// Copyright © 2019 Vinay Kolwankar. All rights reserved.
//
import UIKit
class NoInternet: UIViewController {
let reachability = Reachability()!
override func viewDidLoad() {
super.viewDidLoad()
reachability.whenReachable = { _ in
DispatchQueue.main.async {
self.performSegue(withIdentifier: "whenInternet", sender: self)
}
}
reachability.whenUnreachable = { _ in
DispatchQueue.main.async {
let Message = ""
let alert = UIAlertController(title: "Connection Lost", message: Message, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.destructive, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
NotificationCenter.default.addObserver(self, selector: #selector(internetChanged), name: Notification.Name.reachabilityChanged , object: reachability)
do{
try reachability.startNotifier()
} catch {
print("Could not strat notifier")
}
}
@objc func internetChanged(note:Notification) {
let reachability = note.object as! Reachability
if reachability.connection == .none{
if reachability.connection == .wifi{
self.performSegue(withIdentifier: "whenInternet", sender: self)
}
else{
DispatchQueue.main.async {
self.performSegue(withIdentifier: "whenInternet", sender: self)
}
}
} else{
DispatchQueue.main.async {
let Message = ""
let alert = UIAlertController(title: "Connection Lost", message: Message, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.destructive, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
}
|
//
// DBActor.swift
// ActorKit
//
// Created by Dmitriy Safarov on 16/09/2019.
// Copyright © 2019 SimpleCode. All rights reserved.
//
import Foundation
// Фейковый актор по работе с БД, все работает в асинхронном режиме
class DBActor: Actor {
private var totalSaves: Int = 0
private var counter: ActorRef?
// Получаем и обрабатываем сообщение
override func onReceive(_ msg: AKMessage) {
switch msg {
case let message as MailServiceOutputMessages:
handleMessage(message)
case let message as DBActorMessages:
switch message {
case .registerCounter(let actor):
counter = actor
}
default:
unhandled(msg)
}
}
}
extension DBActor: MailServiceMessageOutputHandler {
// Фиксируем запись в базу данных
func handleDocument(_ document: Document) {
totalSaves += 1
counter?.tell(StatisticsMessages.updateDBCounter(count: totalSaves))
}
}
enum DBActorMessages: AKMessage {
case registerCounter(actor: ActorRef)
}
|
//
// LoginFormSampleApp.swift
// LoginFormSample
//
// Created by Yusuke Hasegawa on 2021/06/04.
//
import SwiftUI
@main
struct LoginFormSampleApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
|
//
// EquipmentModel.swift
// Jup-Jup
//
// Created by 조주혁 on 2021/02/04.
//
import Foundation
struct EquipmentModel: Codable {
let code: Int
let list: [EquipmentList]
let msg: String
let success: Bool
}
struct EquipmentList: Codable {
let content: String
let count: Int
let img_equipment: String
let name: String
}
|
//
// EventPageHeaderViewController.swift
// Reached
//
// Created by John Wu on 2016-07-20.
// Copyright © 2016 ReachedTechnologies. All rights reserved.
//
class EventPageHeaderViewController: UIViewController, CLLocationManagerDelegate {
var isUserReaching = false
var hasUserReached = false
var usersReaching: Array<User>? = Array<User>()
var finalReachingValue = 0
var crowdListMapping: [[String]]?
var locationManager: CLLocationManager!
var distanceFromLocation = 100.0
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
//loading these in advance to allow for fast processing later
getRewardList()
getRewards()
getCrowdListMapping()
getReachingUsers()
self.locationManager = CLLocationManager()
locationManager.requestAlwaysAuthorization()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startMonitoringSignificantLocationChanges()
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
let currentLocation = CLLocation(latitude: locValue.latitude, longitude: locValue.longitude)
let eventLocation = CLLocation(latitude: Double(event.Latitude!)! , longitude: Double(event.Longitude!)!)
distanceFromLocation = currentLocation.distanceFromLocation(eventLocation)
}
var backgroundImage: UIImageView = {
let imageView = UIImageView()
imageView.sd_setImageWithURL(NSURL(string: event.Image!))
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
let shadow: UIImageView = {
let image = UIImageView()
image.image = UIImage(named: "Shadow.png")
image.clipsToBounds = true
image.translatesAutoresizingMaskIntoConstraints = false
return image
}()
lazy var backButton: UIButton = {
let button = UIButton()
button.setImage(UIImage(named: "BackButton.png"), forState: UIControlState.Normal)
button.clipsToBounds = true
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(backButtonPressed), forControlEvents: .TouchUpInside)
return button
}()
let eventTitle: UILabel = {
let label = UILabel()
label.textColor = UIColor.whiteColor()
label.text = event.Name!
label.font = UIFont(name: "Montserrat-SemiBold", size: 17.0)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let venue: UILabel = {
let label = UILabel()
label.textColor = UIColor.whiteColor()
label.text = event.Venue!
label.font = UIFont(name: "Montserrat-Light", size: 15.0)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let pin: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "LocationPin.png")
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
let address: UILabel = {
let label = UILabel()
label.textColor = UIColor.whiteColor()
label.text = event.Address!
label.font = UIFont(name: "Montserrat-Light", size: 10.0)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var reachButton: UIButton = {
let button = UIButton()
if event.Reaching != nil {
for x in event.Reaching! {
if x == facebookId! {
self.isUserReaching = true
}
}
}
if (self.isUserReaching) {
button.setImage(UIImage(named: "ReachedButton.png"), forState: UIControlState.Normal)
} else {
button.setImage(UIImage(named: "ReachButton.png"), forState: UIControlState.Normal)
}
button.clipsToBounds = true
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(reachButtonPressed), forControlEvents: .TouchUpInside)
return button
}()
let litMeterText: UILabel = {
let label = UILabel()
label.textColor = UIColor.whiteColor()
label.text = "LIT-OMETER"
label.font = UIFont(name: "Montserrat-Light", size: 10.0)
label.textAlignment = NSTextAlignment.Center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let meter: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "LitMeter.png")
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
let triangle: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "Triangle.png")
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
lazy var checkinButton: UIButton = {
let button = UIButton()
button.backgroundColor = UIColor.whiteColor()
button.clipsToBounds = true
button.layer.borderColor = UIColor(red: 232/255, green: 159/255, blue: 56/255, alpha: 1).CGColor
button.layer.borderWidth = 1
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(checkinButtonPressed), forControlEvents: .TouchUpInside)
return button
}()
lazy var checkinText: UILabel = {
let label = UILabel()
label.textColor = UIColor(red: 232/255, green: 159/255, blue: 56/255, alpha: 1)
if event.Reached != nil {
for x in event.Reached! {
if x == facebookId! {
self.hasUserReached = true
}
}
}
if (self.hasUserReached) {
label.text = "REACHED!"
} else {
label.text = "Check In For Rewards"
}
label.textAlignment = NSTextAlignment.Center
label.font = UIFont(name: "Montserrat-Light", size: 10.0)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var errorText: UILabel = {
let label = UILabel()
label.textColor = UIColor.whiteColor()
label.numberOfLines = 0
label.layoutIfNeeded()
label.textAlignment = NSTextAlignment.Center
label.font = UIFont(name: "Montserrat-Light", size: 10.0)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
func getCrowdListMapping() {
var school = [String]()
if (crowdList.Schools![0]) { school.append("Concordia") }
if (crowdList.Schools![1]) { school.append("McGill") }
var faculty = [String]()
if (crowdList.Faculties![0]) { faculty.append("Arts") }
if (crowdList.Faculties![1]) { faculty.append("Arts & Sciences") }
if (crowdList.Faculties![2]) { faculty.append("Engineering") }
if (crowdList.Faculties![3]) { faculty.append("Education") }
if (crowdList.Faculties![4]) { faculty.append("Management") }
if (crowdList.Faculties![5]) { faculty.append("Music") }
if (crowdList.Faculties![6]) { faculty.append("Nursing") }
if (crowdList.Faculties![7]) { faculty.append("Sciences") }
var year = [String]()
if (crowdList.Years![0]) { year.append("1") }
if (crowdList.Years![1]) { year.append("2") }
if (crowdList.Years![2]) { year.append("3") }
if (crowdList.Years![3]) { year.append("4+") }
crowdListMapping = [school, faculty, year]
}
func getReachingUsers() {
if (event!.Reaching != nil) {
for user in event!.Reaching! {
dynamoDBObjectMapper.load(User.self, hashKey: user , rangeKey: nil).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: { (task:AWSTask!) -> AnyObject! in
if (task.error == nil) {
if (task.result != nil) {
let currentUser = task.result as! User
self.usersReaching?.append(currentUser)
self.calculateCrowdList()
}
} else {
print("Error: \(task.error)")
let alertController = UIAlertController(title: "Failed to get item from table.", message: task.error!.description, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: { (action:UIAlertAction) -> Void in
})
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
return nil
})
}
} else {
setupViews()
}
}
func calculateCrowdList() {
var count = 0
var isUserPartOfCrowd = true
for user in usersReaching! {
if !crowdListMapping![0].contains(user.School!) {
isUserPartOfCrowd = false
}
if !crowdListMapping![1].contains(user.Faculty!) {
isUserPartOfCrowd = false
}
if !crowdListMapping![2].contains(user.Year!) {
isUserPartOfCrowd = false
}
if isUserPartOfCrowd {
count += 1
}
}
finalReachingValue = count
setupViews()
}
func setupViews() {
view.addSubview(backgroundImage)
view.addSubview(shadow)
view.addSubview(backButton)
view.addSubview(eventTitle)
view.addSubview(venue)
view.addSubview(pin)
view.addSubview(address)
view.addSubview(reachButton)
view.addSubview(litMeterText)
view.addSubview(meter)
view.addSubview(triangle)
view.addSubview(checkinButton)
view.addSubview(checkinText)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":backgroundImage]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[v0]-1.5-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":backgroundImage]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":shadow]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[v0]-1.5-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":shadow]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-15-[v0(40)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":backButton]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[v0(40)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":backButton]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-15-[v0(200)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":eventTitle]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0(30)]-40-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":eventTitle]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-15-[v0(200)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":venue]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0(25)]-20-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":venue]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-15-[v0(12)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":pin]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0(15)]-5-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":pin]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-35-[v0(200)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":address]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0(15)]-5-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":address]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[v0(80)]-15-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":reachButton]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0(40)]-5-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":reachButton]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[v0(80)]-15-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":litMeterText]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0(10)]-66-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":litMeterText]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[v0(80)]-15-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":meter]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0(12)]-48-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":meter]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[v0(125)]-10-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":checkinButton]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-25-[v0(35)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":checkinButton]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[v0(125)]-10-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":checkinText]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-25-[v0(35)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":checkinText]))
if (finalReachingValue > 5) {
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[v0(30)]-11-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":triangle]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0(30)]-45-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":triangle]))
}
else if (finalReachingValue == 4) {
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[v0(30)]-25.5-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":triangle]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0(30)]-45-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":triangle]))
}
else if (finalReachingValue == 3) {
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[v0(30)]-40.5-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":triangle]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0(30)]-45-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":triangle]))
}
else if (finalReachingValue == 2) {
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[v0(30)]-56-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":triangle]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0(30)]-45-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":triangle]))
}
else {
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[v0(30)]-70-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":triangle]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0(30)]-45-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":triangle]))
}
}
func setupErrorView() {
view.addSubview(errorText)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[v0(125)]-10-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":errorText]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-55-[v0(35)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0":errorText]))
}
//functionality for when the Reach button is pressed
func reachButtonPressed(sender: UIButton!) {
if (checkinText.text != "REACHED!") {
if (self.isUserReaching) {
let numberUsersReaching = event.Reaching!.count
if numberUsersReaching == 1 {
let aNewEvent = Event()
aNewEvent.EventId = event.EventId
aNewEvent.Name = event.Name
aNewEvent.Address = event.Address
aNewEvent.Date = event.Date
aNewEvent.Description = event.Description
aNewEvent.Image = event.Image
aNewEvent.Latitude = event.Latitude
aNewEvent.Longitude = event.Longitude
aNewEvent.Time = event.Time
aNewEvent.Venue = event.Venue
if event.Reached != nil {
aNewEvent.Reached = event.Reached
}
event = aNewEvent
} else {
for i in 0..<numberUsersReaching {
if event.Reaching![i] == facebookId! {
event.Reaching!.removeAtIndex(i)
break
}
}
}
updateEvent(event)
self.isUserReaching = false
reachButton.setImage(UIImage(named: "ReachButton.png"), forState: UIControlState.Normal)
} else {
if event.Reaching != nil {
event.Reaching!.append(facebookId!)
} else {
event.Reaching = [facebookId!]
}
updateEvent(event)
reachButton.setImage(UIImage(named: "ReachedButton.png"), forState: UIControlState.Normal)
self.isUserReaching = true
sendReachingNotificationToFriends()
}
}
}
func updateEvent(aEvent: Event) {
dynamoDBObjectMapper.save(aEvent).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: { (task:AWSTask!) -> AnyObject! in
if (task.error == nil) {
print("Successfuly stored Event")
} else {
print("Error storing User")
print("Error: \(task.error)")
}
return nil
})
}
func sendReachingNotificationToFriends() {
let message = createReachingNewsFeedMessage(user, aEvent: event)
for friend in friendsList.Friends! {
if friend != facebookId! {
sendNewsFeedMessage(friend, aMessage: message)
}
}
}
func createReachingNewsFeedMessage(aUser:User, aEvent:Event) -> [String] {
let currentDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
let date = dateFormatter.stringFromDate(currentDate)
let index0 = aUser.Name
let index1 = "REACHING"
let index2 = "false"
let index3 = aEvent.Venue
let index4 = date
let index5 = aUser.PictureUrl
var message: Array<String> = Array<String>()
message.append(index0!)
message.append(index1)
message.append(index2)
message.append(index3!)
message.append(index4)
message.append(index5!)
return message
}
func sendNewsFeedMessage(aUserFacebookId: String, aMessage: [String]) {
dynamoDBObjectMapper.load(NewsFeed.self, hashKey: aUserFacebookId , rangeKey: nil).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: { (task:AWSTask!) -> AnyObject! in
if (task.error == nil) {
if (task.result != nil) {
let lUsersNewsFeed = task.result as! NewsFeed
lUsersNewsFeed.Feed?.append(aMessage)
self.updateNewsFeed(lUsersNewsFeed)
}
} else {
print("Error: \(task.error)")
let alertController = UIAlertController(title: "Failed to get item from table.", message: task.error!.description, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: { (action:UIAlertAction) -> Void in
})
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
return nil
})
}
func updateNewsFeed(aNewsFeed: NewsFeed) {
dynamoDBObjectMapper.save(aNewsFeed).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: { (task:AWSTask!) -> AnyObject! in
if (task.error == nil) {
print("Successfuly sent invite")
} else {
print("Error storing User")
print("Error: \(task.error)")
}
return nil
})
}
func backButtonPressed() {
navigationController?.popToRootViewControllerAnimated(true)
}
func checkinButtonPressed() {
if (checkinText.text != "REACHED!") {
if (distanceFromLocation < 50.0) {
if (isUserReaching) {
checkinText.text = "REACHED!"
checkinText.font = UIFont(name: "Montserrat-SemiBold", size: 10.0)
if (event.Reached != nil) {
event.Reached?.append(facebookId!)
} else {
event.Reached = [facebookId!]
}
updateEvent(event)
let currentDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
if (rewardList.LastReward != nil) {
let lastRewardDate = dateFormatter.dateFromString(rewardList.LastReward!)
let hoursSince = currentDate.hoursFrom(lastRewardDate!)
if (hoursSince > 12) {
rewardList.LastReward = dateFormatter.stringFromDate(currentDate)
storeRewardList(rewardList)
}
} else {
rewardList.LastReward = dateFormatter.stringFromDate(currentDate)
}
if (rewardList.LastReward == dateFormatter.stringFromDate(currentDate)) {
assignAward()
}
sendReachedNotificationToFriends()
setupViews()
} else {
errorText.text = "Click reach first before checking in."
setupErrorView()
}
} else {
errorText.text = "You must reach the event to check in."
setupErrorView()
}
}
}
func assignAward() {
let rewardsCount: UInt32 = UInt32((rewards?.count)!) - 1
let randomAwardIndex = arc4random_uniform(rewardsCount) + 0
if rewardList.Rewards != nil {
rewardList.Rewards?.append(rewards![Int(randomAwardIndex)].RewardId!)
} else {
rewardList.Rewards = [rewards![Int(randomAwardIndex)].RewardId!]
}
var numberThisRewardDistributed = Int(rewards![Int(randomAwardIndex)].TimesDistributed!)
numberThisRewardDistributed = numberThisRewardDistributed! + 1
rewards![Int(randomAwardIndex)].TimesDistributed = String(numberThisRewardDistributed!)
storeReward(rewards![Int(randomAwardIndex)])
storeRewardList(rewardList)
}
func sendReachedNotificationToFriends() {
let message = createReachedNewsFeedMessage(user, aEvent: event)
for friend in friendsList.Friends! {
if friend != facebookId! {
sendNewsFeedMessage(friend, aMessage: message)
}
}
}
func createReachedNewsFeedMessage(aUser:User, aEvent:Event) -> [String] {
let currentDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
let date = dateFormatter.stringFromDate(currentDate)
let index0 = aUser.Name
let index1 = "REACHED"
let index2 = "false"
let index3 = aEvent.Venue
let index4 = date
let index5 = aUser.PictureUrl
var message: Array<String> = Array<String>()
message.append(index0!)
message.append(index1)
message.append(index2)
message.append(index3!)
message.append(index4)
message.append(index5!)
return message
}
func getRewardList() {
dynamoDBObjectMapper.load(RewardList.self, hashKey: facebookId!, rangeKey: nil).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: { (task:AWSTask!) -> AnyObject! in
if (task.error == nil) {
if (task.result != nil) {
rewardList = task.result as? RewardList
}
} else {
print("Error: \(task.error)")
let alertController = UIAlertController(title: "Failed to get item from table.", message: task.error!.description, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: { (action:UIAlertAction) -> Void in
})
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
return nil
})
}
func getRewards() {
dynamoDBObjectMapper.scan(Reward.self, expression: queryExpression).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: { (task:AWSTask!) -> AnyObject! in
if task.result != nil {
rewards?.removeAll()
let databaseEvents = task.result as! AWSDynamoDBPaginatedOutput
for item in databaseEvents.items as! [Reward] {
if (Int(item.TimesDistributed!)! < Int(item.Maximum!)!) {
rewards?.append(item)
}
}
}
if ((task.error) != nil) {
print("Error: \(task.error)")
}
return nil
})
}
func storeRewardList(aRewardList:RewardList) {
dynamoDBObjectMapper.save(aRewardList).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: { (task:AWSTask!) -> AnyObject! in
if (task.error == nil) {
print("Successfuly stored reward list!")
} else {
print("Error storing reward list")
print("Error: \(task.error)")
}
return nil
})
}
func storeReward(aReward:Reward) {
dynamoDBObjectMapper.save(aReward).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: { (task:AWSTask!) -> AnyObject! in
if (task.error == nil) {
print("Successfuly stored reward!")
} else {
print("Error storing reward")
print("Error: \(task.error)")
}
return nil
})
}
}
|
//
// CountryTableViewCell.swift
// OnlineHomeAssement
//
// Created by Ritesh Patil on 2/5/20.
// Copyright © 2020 Ritesh Patil. All rights reserved.
//
import UIKit
class CountryTableViewCell: UITableViewCell {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var flagImage: UIImageView!
@IBOutlet weak var phoneNumber: UILabel!
@IBOutlet weak var code: UILabel!
@IBOutlet weak var name: 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
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.