text
stringlengths
8
1.32M
// // BusinessCollectionCell.swift // RoadTripPlanner // // Created by Deepthy on 10/19/17. // Copyright © 2017 Deepthy. All rights reserved. // import UIKit import YelpAPI import AFNetworking class BusinessCollectionCell: UICollectionViewCell { // @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var businessName: UILabel! @IBOutlet weak var ratingsCountLabel: UILabel! var business: YLPBusiness! { didSet { businessName.text = business.name // imageView?.clipsToBounds = true if let businessImageUrl = business.imageURL { // imageView?.setImageWith(businessImageUrl) let backgroundImageView = UIImageView() let backgroundImage = UIImage() backgroundImageView.setImageWith(businessImageUrl) self.backgroundView = backgroundImageView//setImageWith(businessImageUrl) } let ratingsCount = business.rating if ratingsCount >= 4 { ratingsCountLabel.backgroundColor = UIColor.green } else if ratingsCount >= 3 && ratingsCount < 4 { ratingsCountLabel.backgroundColor = UIColor.green } else { ratingsCountLabel.backgroundColor = UIColor.yellow } ratingsCountLabel.text = "\(business.rating)" } } }
// // Message.swift // chat // // Created by Charles Bethin on 12/7/17. // Copyright © 2017 Charles Bethin. All rights reserved. // import Foundation import MultipeerConnectivity class Message: NSObject, NSCoding { let sourceID : String let destinationID : String let type : MessageType let number : Int let data : String var didSend : Bool init(sourceID: String, destinationID: String, number: Int, type: MessageType, data: String) { self.sourceID = sourceID self.destinationID = destinationID self.type = type self.number = number self.data = data self.didSend = false } required convenience init(coder aDecoder: NSCoder) { let sourceID = aDecoder.decodeObject(forKey: "sourceID") as! String let destinationID = aDecoder.decodeObject(forKey: "destinationID") as! String let type = aDecoder.decodeObject(forKey: "type") as! String let number = aDecoder.decodeInteger(forKey: "number") let data = aDecoder.decodeObject(forKey: "data") as! String self.init(sourceID: sourceID, destinationID: destinationID, number: number, type: MessageType(rawValue: type)!, data: data) } func encode(with aCoder: NSCoder) { aCoder.encode(self.sourceID, forKey: "sourceID") aCoder.encode(self.destinationID, forKey: "destinationID") aCoder.encode(self.type.rawValue, forKey: "type") aCoder.encode(self.number, forKey: "number") aCoder.encode(self.data, forKey: "data") } } class MessageList { var messages: [Message] init() { self.messages = [] } func addMessage(message: Message) { self.messages.append(message) } func hasMessage(message: Message) -> Bool { for msgInArray in messages { if msgInArray.number == message.number && msgInArray.sourceID == message.sourceID && msgInArray.data == message.data { return true } else { // Do nothing } } return false } } enum MessageType: String { case message = "message" case ack = "ack" case newUser = "newUser" }
// // PairPodSetupViewController.swift // OmniKitUI // // Created by Pete Schwamb on 9/18/18. // Copyright © 2018 Pete Schwamb. All rights reserved. // import UIKit import LoopKit import LoopKitUI import RileyLinkKit import OmniKit class PairPodSetupViewController: SetupTableViewController { var rileyLinkPumpManager: RileyLinkPumpManager! private var podComms: PodComms? private var podState: PodState? private var cancelErrorCount = 0 var pumpManagerState: OmnipodPumpManagerState? { get { guard let podState = podState else { return nil } return OmnipodPumpManagerState( podState: podState, rileyLinkConnectionManagerState: self.rileyLinkPumpManager.rileyLinkConnectionManagerState ) } } var pumpManager: OmnipodPumpManager? { guard let pumpManagerState = pumpManagerState else { return nil } return OmnipodPumpManager( state: pumpManagerState, rileyLinkDeviceProvider: rileyLinkPumpManager.rileyLinkDeviceProvider, rileyLinkConnectionManager: rileyLinkPumpManager.rileyLinkConnectionManager) } // MARK: - @IBOutlet weak var activityIndicator: SetupIndicatorView! @IBOutlet weak var loadingLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() continueState = .initial } override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard continueState != .pairing else { return } tableView.deselectRow(at: indexPath, animated: true) } // MARK: - Navigation private enum State { case initial case pairing case paired } private var continueState: State = .initial { didSet { switch continueState { case .initial: activityIndicator.state = .hidden footerView.primaryButton.isEnabled = true footerView.primaryButton.setConnectTitle() case .pairing: activityIndicator.state = .loading footerView.primaryButton.isEnabled = false footerView.primaryButton.setConnectTitle() lastError = nil case .paired: activityIndicator.state = .completed footerView.primaryButton.isEnabled = true footerView.primaryButton.resetTitle() lastError = nil } } } private var lastError: Error? { didSet { guard oldValue != nil || lastError != nil else { return } var errorText = lastError?.localizedDescription if let error = lastError as? LocalizedError { let localizedText = [error.errorDescription, error.failureReason, error.recoverySuggestion].compactMap({ $0 }).joined(separator: ". ") + "." if !localizedText.isEmpty { errorText = localizedText } } tableView.beginUpdates() loadingLabel.text = errorText let isHidden = (errorText == nil) loadingLabel.isHidden = isHidden tableView.endUpdates() // If we changed the error text, update the continue state if !isHidden { continueState = .initial } } } override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { return continueState == .paired } override func continueButtonPressed(_ sender: Any) { if case .paired = continueState { super.continueButtonPressed(sender) } else if case .initial = continueState { if podState == nil { continueState = .pairing pair() } else { configurePod() } } } override func cancelButtonPressed(_ sender: Any) { if case .paired = continueState, let pumpManager = self.pumpManager { let confirmVC = UIAlertController(pumpDeletionHandler: { let deviceSelector = pumpManager.rileyLinkDeviceProvider.firstConnectedDevice pumpManager.podComms.runSession(withName: "Deactivate Pod", using: deviceSelector, { (result) in do { switch result { case .success(let session): let _ = try session.changePod() DispatchQueue.main.async { super.cancelButtonPressed(sender) } case.failure(let error): throw error } } catch let error { DispatchQueue.main.async { self.cancelErrorCount += 1 self.lastError = error if self.cancelErrorCount >= 2 { super.cancelButtonPressed(sender) } } } }) }) present(confirmVC, animated: true) {} } else { super.cancelButtonPressed(sender) } } func pair() { guard podComms == nil else { return } let deviceSelector = rileyLinkPumpManager.rileyLinkDeviceProvider.firstConnectedDevice // TODO: Let user choose between current and previously used timezone? PodComms.pair(using: deviceSelector, timeZone: .currentFixed, completion: { (result) in DispatchQueue.main.async { switch result { case .success(let podState): self.podState = podState self.podComms = PodComms(podState: podState, delegate: self) self.configurePod() case .failure(let error): self.lastError = error } } }) } func configurePod() { guard let podComms = podComms else { return } let deviceSelector = rileyLinkPumpManager.rileyLinkDeviceProvider.firstConnectedDevice podComms.runSession(withName: "Configure pod", using: deviceSelector) { (result) in switch result { case .success(let session): do { try session.configurePod() DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(55)) { self.finishPrime() } } catch let error { DispatchQueue.main.async { self.lastError = error } } case .failure(let error): DispatchQueue.main.async { self.lastError = error } } } } func finishPrime() { guard let podComms = podComms else { return } let deviceSelector = rileyLinkPumpManager.rileyLinkDeviceProvider.firstConnectedDevice podComms.runSession(withName: "Finish Prime", using: deviceSelector) { (result) in switch result { case .success(let session): do { try session.finishPrime() DispatchQueue.main.async { self.continueState = .paired } } catch let error { DispatchQueue.main.async { self.lastError = error } } case .failure(let error): DispatchQueue.main.async { self.lastError = error } } } } } extension PairPodSetupViewController: PodCommsDelegate { public func podComms(_ podComms: PodComms, didChange state: PodState) { self.podState = state } } private extension SetupButton { func setConnectTitle() { setTitle(LocalizedString("Pair", comment: "Button title to pair with pod during setup"), for: .normal) } } private extension UIAlertController { convenience init(pumpDeletionHandler handler: @escaping () -> Void) { self.init( title: nil, message: NSLocalizedString("Are you sure you want to shutdown this pod?", comment: "Confirmation message for shutting down a pod"), preferredStyle: .actionSheet ) addAction(UIAlertAction( title: NSLocalizedString("Deactivate Pod", comment: "Button title to deactivate pod"), style: .destructive, handler: { (_) in handler() } )) let exit = NSLocalizedString("Continue", comment: "The title of the continue action in an action sheet") addAction(UIAlertAction(title: exit, style: .default, handler: nil)) } }
// Copyright (c) 2020-2022 InSeven Limited // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import SwiftUI struct SelectionSheetHandler: ViewModifier { struct IdentifiableError: Identifiable { var id = UUID() var error: Error } @Environment(\.manager) var manager @ObservedObject var selection: BookmarksSelection @State var error: IdentifiableError? = nil func body(content: Content) -> some View { content .sheet(item: $selection.sheet) { sheet in switch sheet { case .addTags(let bookmarks): EditView(tagsView: manager.tagsView, bookmarks: bookmarks) } } .alert(item: $error) { error in return Alert(title: Text("Error"), message: Text(error.error.localizedDescription)) } .onReceive(selection.$lastError) { error in guard let error = error else { return } self.error = IdentifiableError(error: error) } } } extension View { func handlesSelectionSheets(_ selection: BookmarksSelection) -> some View { modifier(SelectionSheetHandler(selection: selection)) } }
// // InfoRouter.swift // Movie // // Created by Воробьев Александр on 08/10/2019. // Copyright © 2019 Levin Ivan. All rights reserved. // import UIKit protocol InfoListDataPassing: class { func routerToInfoScene(movieID id: Int) } class InfoRouter: InfoListDataPassing { weak var viewController: InfoViewController? func routerToInfoScene(movieID id: Int) { let viewController = InfoBuilder.build(movieID: id) self.viewController?.show(viewController, sender: nil) // self.viewController?.present(viewController, animated: true) } }
// // LocationTracker.swift // LocationSwift // // Created by Emerson Carvalho on 5/21/15. // Copyright (c) 2015 Emerson Carvalho. All rights reserved. // import UIKit import CoreLocation let LATITUDE = "latitude" let LONGITUDE = "longitude" let ACCURACY = "theAccuracy" let IS_OS_8_OR_LATER : Bool = ( (UIDevice.currentDevice().systemVersion as NSString).floatValue >= 8.0) class LocationTracker : NSObject, CLLocationManagerDelegate, UIAlertViewDelegate { var myLastLocation : CLLocationCoordinate2D! var myLastLocationAccuracy : CLLocationAccuracy! var shareModel : LocationShareModel! var myLocation : CLLocationCoordinate2D! var myLocationAcuracy : CLLocationAccuracy! var myLocationAltitude : CLLocationDistance! override init() { super.init() self.shareModel = LocationShareModel() self.shareModel!.myLocationArray = NSMutableArray() NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationEnterBackground", name: UIApplicationDidEnterBackgroundNotification, object: nil) } class func sharedLocationManager()-> CLLocationManager! { struct Static { static var _locationManager : CLLocationManager? } objc_sync_enter(self) if Static._locationManager == nil { Static._locationManager = CLLocationManager() Static._locationManager!.desiredAccuracy = kCLLocationAccuracyBestForNavigation } objc_sync_exit(self) return Static._locationManager! } // MARK: Application in background func applicationEnterBackground() { println("applicationEnterBackground") var locationManager : CLLocationManager = LocationTracker.sharedLocationManager()! locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation locationManager.distanceFilter = kCLDistanceFilterNone locationManager.startUpdatingLocation() self.shareModel!.bgTask = BackgroundTaskManager.sharedBackgroundTaskManager() self.shareModel?.bgTask?.beginNewBackgroundTask() } func restartLocationUpdates() { print("restartLocationUpdates\n") if self.shareModel?.timer != nil { self.shareModel?.timer?.invalidate() self.shareModel!.timer = nil } var locationManager : CLLocationManager = LocationTracker.sharedLocationManager()! locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation locationManager.distanceFilter = kCLDistanceFilterNone locationManager.startUpdatingLocation() } func startLocationTracking() { print("startLocationTracking\n") if CLLocationManager.locationServicesEnabled() == false { print("locationServicesEnabled false\n") var servicesDisabledAlert : UIAlertView = UIAlertView(title: "Location Services Disabled", message: "You currently have all location services for this device disabled", delegate: nil, cancelButtonTitle: "OK") servicesDisabledAlert.show() } else { var authorizationStatus : CLAuthorizationStatus = CLLocationManager.authorizationStatus() if (authorizationStatus == CLAuthorizationStatus.Denied) || (authorizationStatus == CLAuthorizationStatus.Restricted) { print("authorizationStatus failed") } else { println("startLocationTracking authorized") var locationManager : CLLocationManager = LocationTracker.sharedLocationManager()! locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.distanceFilter = kCLDistanceFilterNone if IS_OS_8_OR_LATER { locationManager.requestAlwaysAuthorization() } locationManager.startUpdatingLocation() } } } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { print("locationManager didUpdateLocations\n") for (var i : Int = 0; i < locations.count; i++) { var newLocation : CLLocation! = locations[i] as! CLLocation var theLocation : CLLocationCoordinate2D = newLocation.coordinate var theAltitude : CLLocationDistance = newLocation.altitude var theAccuracy : CLLocationAccuracy = newLocation.horizontalAccuracy var locationAge : NSTimeInterval = newLocation.timestamp.timeIntervalSinceNow if locationAge > 30.0 { continue } // Select only valid location and also location with good accuracy if (newLocation != nil) && (theAccuracy > 0) && (theAccuracy < 2000) && !((theLocation.latitude == 0.0) && (theLocation.longitude == 0.0)) { println("Good location with good accuracy \(theLocation.latitude) & \(theLocation.longitude)") self.myLastLocation = theLocation self.myLastLocationAccuracy = theAccuracy var dict : NSMutableDictionary = NSMutableDictionary() dict.setObject(Float(theLocation.latitude), forKey: "latitude") dict.setObject(Float(theLocation.longitude), forKey: "longitude") dict.setObject(Float(theAccuracy), forKey: "theAccuracy") dict.setObject(Float(theAltitude), forKey: "theAltitude") // Add the vallid location with good accuracy into an array // Every 1 minute, I will select the best location based on accuracy and send to server self.shareModel!.myLocationArray!.addObject(dict) } } // If the timer still valid, return it (Will not run the code below) if self.shareModel!.timer != nil { return } self.shareModel!.bgTask = BackgroundTaskManager.sharedBackgroundTaskManager() self.shareModel!.bgTask!.beginNewBackgroundTask() // Restart the locationManager after 1 minute let restartLocationUpdates : Selector = "restartLocationUpdates" self.shareModel!.timer = NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: restartLocationUpdates, userInfo: nil, repeats: false) // Will only stop the locationManager after 10 seconds, so that we can get some accurate locations // The location manager will only operate for 10 seconds to save battery let stopLocationDelayBy10Seconds : Selector = "stopLocationDelayBy10Seconds" var delay10Seconds : NSTimer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: stopLocationDelayBy10Seconds, userInfo: nil, repeats: false) } //MARK: Stop the locationManager func stopLocationDelayBy10Seconds() { var locationManager : CLLocationManager = LocationTracker.sharedLocationManager()! locationManager.stopUpdatingLocation() print("locationManager stop Updating after 10 seconds\n") } func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { println("locationManager Error: \(error.localizedDescription)") switch (error.code) { case CLError.Network.rawValue: println("locationManager Error: Please check your network connection.") restartAfterMinutes(1) var alert : UIAlertView = UIAlertView(title: "Network Error", message: "Please check your network connection.", delegate: self, cancelButtonTitle: "OK") alert.show() break case CLError.Denied.rawValue: println("locationManager Error: Please check your network connection.") restartAfterMinutes(1) var alert : UIAlertView = UIAlertView(title: "Network Error", message: "Please check your network connection.", delegate: self, cancelButtonTitle: "OK") alert.show() break default: println("locationManager Error: Uncaught error") restartAfterMinutes(1) break } } func restartAfterMinutes(minutes : NSTimeInterval) -> Void { println("restartAfterMinutes \(minutes)") self.shareModel!.bgTask = BackgroundTaskManager.sharedBackgroundTaskManager() self.shareModel!.bgTask!.beginNewBackgroundTask() // Restart the locationManager after 1 minute let restartLocationUpdates : Selector = "restartLocationUpdates" self.shareModel!.timer = NSTimer.scheduledTimerWithTimeInterval(60 * minutes, target: self, selector: restartLocationUpdates, userInfo: nil, repeats: false) } func stopLocationTracking () { print("stopLocationTracking\n") if self.shareModel!.timer != nil { self.shareModel!.timer!.invalidate() self.shareModel!.timer = nil } var locationManager : CLLocationManager = LocationTracker.sharedLocationManager()! locationManager.stopUpdatingLocation() } // MARK: Update location to server func updateLocationToServer() { // print("updateLocationToServer\n") // Find the best location from the array based on accuracy var myBestLocation : NSMutableDictionary = NSMutableDictionary() for (var i : Int = 0 ; i < self.shareModel!.myLocationArray!.count ; i++) { var currentLocation : NSMutableDictionary = self.shareModel!.myLocationArray!.objectAtIndex(i) as! NSMutableDictionary if i == 0 { myBestLocation = currentLocation } else { if (currentLocation.objectForKey(ACCURACY) as! Float) <= (myBestLocation.objectForKey(ACCURACY) as! Float) { myBestLocation = currentLocation } } } //print("My Best location \(myBestLocation)\n") // If the array is 0, get the last location // Sometimes due to network issue or unknown reason, // you could not get the location during that period, the best you can do is // sending the last known location to the server if self.shareModel!.myLocationArray!.count == 0 { print("Unable to get location, use the last known location\n") self.myLocation = self.myLastLocation self.myLocationAcuracy = self.myLastLocationAccuracy } else { var lat : CLLocationDegrees = myBestLocation.objectForKey(LATITUDE) as! CLLocationDegrees var lon : CLLocationDegrees = myBestLocation.objectForKey(LONGITUDE) as! CLLocationDegrees var theBestLocation = CLLocationCoordinate2D(latitude: lat, longitude: lon) self.myLocation = theBestLocation self.myLocationAcuracy = myBestLocation.objectForKey(ACCURACY) as! CLLocationAccuracy! } print("Send to server: latitude \(self.myLocation.latitude) longitude \(self.myLocation?.longitude) accuracy \(self.myLocationAcuracy)\n") //TODO: Your code to send the self.myLocation and self.myLocationAccuracy to your server // After sending the location to the server successful, // remember to clear the current array with the following code. It is to make sure that you clear up old location in the array // and add the new locations from locationManager self.shareModel!.myLocationArray!.removeAllObjects() self.shareModel!.myLocationArray = nil self.shareModel!.myLocationArray = NSMutableArray() } func getBestLocationForServer() -> NSDictionary? { print("getBestLocationForServer\n") // Find the best location from the array based on accuracy var myBestLocation : NSMutableDictionary = NSMutableDictionary() for (var i : Int = 0 ; i < self.shareModel!.myLocationArray!.count ; i++) { var currentLocation : NSMutableDictionary = self.shareModel!.myLocationArray!.objectAtIndex(i) as! NSMutableDictionary if i == 0 { myBestLocation = currentLocation } else { if (currentLocation.objectForKey(ACCURACY) as! Float) <= (myBestLocation.objectForKey(ACCURACY) as! Float) { myBestLocation = currentLocation } } } print("My Best location \(myBestLocation)\n") // If the array is 0, get the last location // Sometimes due to network issue or unknown reason, // you could not get the location during that period, the best you can do is // sending the last known location to the server if self.shareModel!.myLocationArray!.count == 0 { print("Unable to get location, use the last known location\n") self.myLocation = self.myLastLocation self.myLocationAcuracy = self.myLastLocationAccuracy } else { var lat : CLLocationDegrees = myBestLocation.objectForKey(LATITUDE) as! CLLocationDegrees var lon : CLLocationDegrees = myBestLocation.objectForKey(LONGITUDE) as! CLLocationDegrees var theBestLocation = CLLocationCoordinate2D(latitude: lat, longitude: lon) self.myLocation = theBestLocation self.myLocationAcuracy = myBestLocation.objectForKey(ACCURACY) as! CLLocationAccuracy! } var returnType : NSMutableDictionary = NSMutableDictionary() returnType.setValue(self.myLocation.latitude, forKey: "lat") returnType.setValue(self.myLocation.longitude, forKey: "lon") returnType.setValue(self.myLocationAcuracy, forKey: "acc") print("Send to server: latitude \(self.myLocation.latitude) longitude \(self.myLocation.longitude) accuracy \(self.myLocationAcuracy)\n") //TODO: Your code to send the self.myLocation and self.myLocationAccuracy to your server // After sending the location to the server successful, // remember to clear the current array with the following code. It is to make sure that you clear up old location in the array // and add the new locations from locationManager self.shareModel!.myLocationArray!.removeAllObjects() self.shareModel!.myLocationArray = nil self.shareModel!.myLocationArray = NSMutableArray() return returnType } }
// // Levels.swift // TikiTacToe // // Created by Pro on 26.02.2021. // import SpriteKit class LevelsScene: SKScene { override func didMove(to view: SKView) { super.didMove(to: view) setup() } func setup() { var winsArr = UserDefaults.standard.array(forKey: "winsArr") as? [Int] ?? [] print("wins array is \(winsArr)") // archivements let completed = UserDefaults.standard.integer(forKey: "completedLevel") // arch 1 - complete all levels if completed == 9 { UserDefaults.standard.setValue(1, forKey: "arch1") print("hello arch 1") } // arch 2 - win 3 levels in a row var counter = 0 for elem in winsArr { if elem == 1 { counter += 1 } else { counter = 0 } } if counter == 3 { UserDefaults.standard.setValue(1, forKey: "arch2"); print("hello arch 2") } // arch 3 - beat tiki idol if winsArr.count >= 9 { if winsArr[8] == 1 { UserDefaults.standard.setValue(1, forKey: "arch3") print("hello arch 3") } } // set background behind all other elements let back = self.childNode(withName: "BackSpriteNode") as? SKSpriteNode back?.zPosition = -1 // levels guard let level1 = self.childNode(withName: "1LevelSpriteNode") as? SKSpriteNode else { print("error level 1"); return } guard let level2 = self.childNode(withName: "2LevelSpriteNode") as? SKSpriteNode else { print("error level 2"); return } guard let level3 = self.childNode(withName: "3LevelSpriteNode") as? SKSpriteNode else { print("error level 3"); return } guard let level4 = self.childNode(withName: "4LevelSpriteNode") as? SKSpriteNode else { print("error level 4"); return } guard let level5 = self.childNode(withName: "5LevelSpriteNode") as? SKSpriteNode else { print("error level 5"); return } guard let level6 = self.childNode(withName: "6LevelSpriteNode") as? SKSpriteNode else { print("error level 6"); return } guard let level7 = self.childNode(withName: "7LevelSpriteNode") as? SKSpriteNode else { print("error level 7"); return } guard let level8 = self.childNode(withName: "8LevelSpriteNode") as? SKSpriteNode else { print("error level 8"); return } guard let level9 = self.childNode(withName: "9LevelSpriteNode") as? SKSpriteNode else { print("error level 9"); return } let completedLevel = UserDefaults.standard.integer(forKey: "completedLevel") print("completed \(completedLevel)") if completedLevel == 9 { winsArr = [] UserDefaults.standard.setValue(nil, forKey: "winsArr") } switch completedLevel { case 1: setCurrImg(level2, 2) level2.alpha = 1 case 2: setCurrImg(level3, 3) level3.alpha = 1 case 3: setCurrImg(level4, 4) level4.alpha = 1 case 4: setCurrImg(level5, 5) level5.alpha = 1 case 5: setCurrImg(level6, 6) level6.alpha = 1 case 6: setCurrImg(level7, 7) level7.alpha = 1 case 7: setCurrImg(level8, 8) level8.alpha = 1 case 8: setCurrImg(level9, 9) level9.alpha = 1 default: setCurrImg(level1, 1) level1.alpha = 1 } if winsArr.count >= 1 { if winsArr[0] == 1 { setWinImg(level1, 1) } else if winsArr[0] == 0 { setLoseImg(level1, 1) } } if winsArr.count >= 2 { if winsArr[1] == 1 { setWinImg(level2, 2) } else if winsArr[1] == 0 { setLoseImg(level2, 2) } } if winsArr.count >= 3 { if winsArr[2] == 1 { setWinImg(level3, 3) } else if winsArr[2] == 0 { setLoseImg(level3, 3) } } if winsArr.count >= 4 { if winsArr[3] == 1 { setWinImg(level4, 4) } else if winsArr[3] == 0 { setLoseImg(level4, 4) } } if winsArr.count >= 5 { if winsArr[4] == 1 { setWinImg(level5, 5) } else if winsArr[4] == 0 { setLoseImg(level5, 5) } } if winsArr.count >= 6 { if winsArr[5] == 1 { setWinImg(level6, 6) } else if winsArr[5] == 0 { setLoseImg(level6, 6) } } if winsArr.count >= 7 { if winsArr[6] == 1 { setWinImg(level7, 7) } else if winsArr[6] == 0 { setLoseImg(level7, 7) } } if winsArr.count >= 8 { if winsArr[7] == 1 { setWinImg(level8, 8) } else if winsArr[7] == 0 { setLoseImg(level8, 8) } } if winsArr.count == 9 { if winsArr[8] == 1 { setWinImg(level9, 9) } else if winsArr[8] == 0 { setLoseImg(level9, 9) } } if winsArr.count > 9 { setCurrImg(level1, 1) level1.alpha = 1 } } func setCurrImg(_ node: SKSpriteNode, _ imgNum: Int) { node.texture = SKTexture(imageNamed: "image\(imgNum)h") } func setWinImg(_ node: SKSpriteNode, _ levelNum: Int) { node.texture = SKTexture(imageNamed: "\(levelNum)w") } func setLoseImg(_ node: SKSpriteNode, _ levelNum: Int) { node.texture = SKTexture(imageNamed: "\(levelNum)l") } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let completedLevel = UserDefaults.standard.integer(forKey: "completedLevel") for touch in touches { let location = touch.location(in: self) let selectedNode = self.atPoint(location) if let name = selectedNode.name { if name == Consts.level1 && completedLevel == 0 { goToGame() } else if name == Consts.level2 && completedLevel == 1 { goToGame() } else if name == Consts.level3 && completedLevel == 2 { goToGame() } else if name == Consts.level4 && completedLevel == 3 { goToGame() } else if name == Consts.level5 && completedLevel == 4 { goToGame() } else if name == Consts.level6 && completedLevel == 5 { goToGame() } else if name == Consts.level7 && completedLevel == 6 { goToGame() } else if name == Consts.level8 && completedLevel == 7 { goToGame() } else if name == Consts.level9 && completedLevel == 8 { goToGame() } else if name == Consts.level1 && completedLevel == 9 { goToGame() } } } } func goToGame() { let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "gameVC") vc.view.frame = (self.view?.frame)! vc.view.layoutIfNeeded() UIView.transition(with: self.view!, duration: 0.01, options: .transitionCrossDissolve, animations: { self.view?.window?.rootViewController = vc }, completion: { completed in }) } override func update(_ currentTime: TimeInterval) {} }
// // AANetManager.swift // weibo // // Created by dh on 16/8/31. // Copyright © 2016年 mac. All rights reserved. // import UIKit import AFNetworking enum AAHTTPMethod: String { case Get = "GET" case Post = "POST" } class AANetManager: AFHTTPSessionManager { static let sharedManager: AANetManager = { let manager = AANetManager() manager.responseSerializer.acceptableContentTypes?.insert("text/html") manager.responseSerializer.acceptableContentTypes?.insert("text/plain") return manager }() typealias AARequestBack = @escaping (Any?, Error?) -> () func request(method: AAHTTPMethod, URLString: String, parameters: Any?, completion: AARequestBack) { let successClosure: (URLSessionDataTask, Any?) -> () = { (_, responseObject) in completion(responseObject, nil) } let failureClosure: (URLSessionDataTask?, Error) -> () = { (_, error) in completion(nil, error) } if method == .Get { self.get(URLString, parameters: parameters, progress: nil, success: successClosure, failure: failureClosure) } else { self.post(URLString, parameters: parameters, progress: nil, success: successClosure, failure: failureClosure) } } }
// // UIViewController+Camera.swift // photobomb // // Created by BJ Griffin on 7/25/15. // Copyright © 2015 mojo. All rights reserved. // import UIKit extension SearchTableViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate { func getImagePicker() -> UIImagePickerController { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.allowsEditing = false return imagePicker } func showPhotoActionSheet() { let actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in //Just dismiss the action sheet } actionSheetController.addAction(cancelAction) let imagePicker = getImagePicker() let takePictureAction = UIAlertAction(title: "Take Picture", style: .Default) { action -> Void in imagePicker.sourceType = .Camera dispatch_async(dispatch_get_main_queue()) { actionSheetController.dismissViewControllerAnimated(false, completion: nil) self.presentViewController(imagePicker, animated: true, completion: nil) } } actionSheetController.addAction(takePictureAction) let choosePictureAction = UIAlertAction(title: "Choose From Camera Roll", style: .Default) { action -> Void in imagePicker.sourceType = .PhotoLibrary dispatch_async(dispatch_get_main_queue()) { actionSheetController.dismissViewControllerAnimated(false, completion: nil) self.presentViewController(imagePicker, animated: true, completion: nil) } } actionSheetController.addAction(choosePictureAction) //We need to provide a popover sourceView when using it on iPad actionSheetController.popoverPresentationController?.sourceView = view //Present the AlertController self.presentViewController(actionSheetController, animated: true, completion: nil) } }
// // RelatedKeywordsViewController.swift // appstoreSearch // // Created by Elon on 17/03/2019. // Copyright © 2019 Elon. All rights reserved. // import UIKit import RxSwift import RxCocoa final class RelatedKeywordsViewController: ResultTypeController { @IBOutlet weak var relatedResultTableView: UITableView! @IBOutlet weak var tableViewHaderSpaceView: UIView! private let disposeBag = DisposeBag() private var relatedResults = [String]() lazy var rx_searchText = BehaviorRelay(value: String()) lazy var dataSource = BehaviorRelay(value: relatedResults) deinit { Log.verbose("deinit") } override func viewDidLoad() { super.viewDidLoad() setRelatedResultTableView() dataBinding() searchText() selectCellItem() } } extension RelatedKeywordsViewController { private func setRelatedResultTableView() { relatedResultTableView.delegate = nil relatedResultTableView.dataSource = nil } private func searchText() { rx_searchText .filter { !$0.isEmpty } .distinctUntilChanged() .observeOn(MainScheduler.instance) .bind { [unowned self] text in let history = SearchHistory.get() self.relatedResults = history.filter { $0.hasCaseInsensitivePrefix(text) } self.dataSource.accept(self.relatedResults) } .disposed(by: disposeBag) } private func dataBinding() { dataSource .asDriver() .drive(relatedResultTableView.rx.items( cellIdentifier: RelatedResultCell.identifier, cellType: RelatedResultCell.self)) { [unowned self] row, model, cell in let searchText = self.rx_searchText.value cell.setTitle(text: model, with: searchText) } .disposed(by: disposeBag) } private func selectCellItem() { relatedResultTableView .rx.itemSelected .asDriver() .drive(onNext: { [unowned self] indexPath in let text = self.dataSource.value[indexPath.row] self.selectItem(text) self.relatedResultTableView.deselectRow(at: indexPath, animated: false) }) .disposed(by: disposeBag) } }
// // EditStudentViewController.swift // HireTalent // // Created by Andres Ruiz Navejas on 09/05/20. // Copyright © 2020 Dream Team. All rights reserved. // import UIKit class EditStudentViewController: UIViewController { var student: Student? var delegate: StudentDelegate? @IBOutlet weak var errotLabel: UILabel! @IBOutlet weak var firstNameLabel: UITextField! @IBOutlet weak var lastNameLabel: UITextField! @IBOutlet weak var cityLabel: UITextField! @IBOutlet weak var stateLabel: UITextField! @IBOutlet weak var schoolLabel: UITextField! @IBOutlet weak var majorLabel: UITextField! @IBOutlet weak var semesterLabel: UITextField! @IBOutlet weak var experienceTextArea: UITextView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setupViews() } func setupViews(){ firstNameLabel.text = student?.firstName lastNameLabel.text = student?.lastName cityLabel.text = student?.city stateLabel.text = student?.state schoolLabel.text = student?.school majorLabel.text = student?.major semesterLabel.text = student?.semester experienceTextArea.text = student?.experience } @IBAction func savePressed(_ sender: UIBarButtonItem) { if infoMissing(){ errotLabel.isHidden = false errotLabel.text = "can't leave empty" return } readData() saveData() } func saveData(){ StudentDAO.editStudent(id: StudentDAO.getStudentId(), student: student!){ (error) in if(error != nil){ print("error editing user") self.errotLabel.text = "error with firebase" }else{ self.delegate?.updateStudentProfile(controller: self, newStudent: self.student!) self.navigationController?.popViewController(animated: true) } } } func readData(){ student?.firstName = firstNameLabel.text! student?.lastName = lastNameLabel.text! student?.city = cityLabel.text! student?.state = stateLabel.text! student?.school = schoolLabel.text! student?.major = majorLabel.text! student?.semester = semesterLabel.text! student?.experience = experienceTextArea.text } func infoMissing()-> Bool{ if (firstNameLabel.text!.isEmpty || lastNameLabel.text!.isEmpty || cityLabel.text!.isEmpty || stateLabel.text!.isEmpty || schoolLabel.text!.isEmpty || majorLabel.text!.isEmpty || semesterLabel.text!.isEmpty || experienceTextArea.text!.isEmpty){ return true }else{ return false } } /* // 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. } */ }
// // Order.swift // Flykeart App // // Created by Akhil Pothana on 5/29/19. // Copyright © 2019 Federico Brandt. All rights reserved. // import Foundation class Order{ let name: String let seat: String let drinkChoice: String let snackChoice: String init(orderItems : [String:String]) { self.name = orderItems["name"]! self.seat = orderItems["seat"]! self.drinkChoice = orderItems["drink"]! self.snackChoice = orderItems["snack"]! } public func getName() -> String { return self.name } public func getSeat() -> String { return self.seat } public func getDrinkChoice() -> String { return self.drinkChoice } public func getSnackChoice() -> String { return self.snackChoice } }
// // User.swift // DroneDeployViper // // Created by James Talano on 6/7/21. // Copyright © 2021 James. All rights reserved. // import Foundation class User: NSObject { var username: String var password: String override init() { username = "" password = "" } init(username: String, password: String) { self.username = username self.password = password } }
// // Category.swift // caffinho-iOS // // Created by Rafael M. A. da Silva on 06/06/16. // Copyright © 2016 venturus. All rights reserved. // import Foundation class Category:Model { var categoryName = "" var items = [Item]() }
import Foundation extension Array { ///Returns an array containing only the non-nil results public static func nonNil(_ array: [Element?]) -> [Element] { return array.flatMap { $0 } } } extension Collection where Indices.Iterator.Element == Index { /// Returns the element at the specified index if it is within bounds, otherwise nil. subscript (safe index: Index) -> Generator.Element? { return indices.contains(index) ? self[index] : nil } } protocol GenericCollection : Hashable {} extension GenericCollection { static func cases() -> AnySequence<Self> { typealias S = Self return AnySequence { () -> AnyIterator<S> in var raw = 0 return AnyIterator { let current : Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: S.self, capacity: 1) { $0.pointee } } guard current.hashValue == raw else { return nil } raw += 1 return current } } } }
// // AppCollectionViewCell.swift // SweetHealth // // Created by Miguel Jaimes on 18/02/2020. // Copyright © 2020 Miguel Jaimes. All rights reserved. // import UIKit class AppCollectionViewCell: UICollectionViewCell { @IBOutlet weak var imageApp: UIImageView! @IBOutlet weak var nameApp: UILabel! @IBOutlet weak var opacity: UIImageView! override func awakeFromNib() { imageApp.roundImage() opacity.roundImage() opacity.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) opacity.alpha = 0.5 self.imageApp.alpha = 0.0 UIView.animate(withDuration: 0.5, delay: 0.2, options: .curveEaseOut, animations: { self.imageApp.alpha = 1 }, completion: nil) } }
/* Copyright 2011-present Samuel GRAU Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // // FluableView : TableSection.swift // import Foundation public struct TableSection<Element>: SectionType { public var elements: [Element] { return self.innerStorage } public init(arrayLiteral elements: Element...) { self.innerStorage = elements } // Readwrite storage private var innerStorage: [Element] }
// // LoginViewController.swift // test // // Created by Alex Iakab on 29/11/2018. // Copyright © 2018 Alex Iakab. All rights reserved. // import UIKit import Firebase class LoginViewController: UIViewController { @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var usernameField: UITextField! @IBOutlet var viewController: UIView! @IBOutlet weak var button: UIButton! @IBOutlet weak var registerButton: UIButton! @IBOutlet weak var guestButton: UIButton! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var loginButton: UIButton! var currentUser: User? override func viewDidLoad() { super.viewDidLoad() imageView.image = imageView.image!.withRenderingMode(.alwaysTemplate) imageView.tintColor = UIColor.goodGreen button.setCorner(8) button.layer.borderWidth = 1 button.layer.borderColor = UIColor.goodGreen.cgColor guestButton.setCorner(8) guestButton.layer.borderWidth = 1 guestButton.layer.borderColor = UIColor.goodGreen.cgColor registerButton.setCorner(8) registerButton.layer.borderWidth = 1 registerButton.layer.borderColor = UIColor.goodGreen.cgColor passwordField.setBorderBottom(false) usernameField.setBorderBottom(false) viewController.backgroundColor = UIColor(patternImage: UIImage(named: "BackgroundD")!) currentUser = Auth.auth().currentUser } @IBAction func editingBegin(_ sender: UITextField) { sender.setBorderBottom(true) } @IBAction func editingEnd(_ sender: UITextField) { sender.setBorderBottom(false) } @IBAction func registerPressed(_ sender: UIButton) { performSegue(withIdentifier: "registerPressed", sender: self) } @IBAction func guestLoginPressed(_ sender: UIButton) { Auth.auth().signInAnonymously() { (authResult, error) in self.performSegue(withIdentifier: "loginPressed", sender: self) } } @IBAction func loginPressed(_ sender: UIButton) { // performSegue(withIdentifier: "loginPressed", sender: self) let emailInput = usernameField.text let passwordInput = passwordField.text if self.currentUser == nil { if ((emailInput?.isEmpty)!) || ((passwordInput?.isEmpty)!) { alert(title: "Zonk", message: "Please fill in all the fields", option: "Try Again") } else { loginUser(email: emailInput!, password: passwordInput!) } } else { let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() alert(title: "Zonk", message: "You were somehow logged in so we logged you out", option: "Log In Again") } catch let signOutError as NSError { print ("Error signing out: %@", signOutError) } } } func loginUser(email: String, password: String) { Auth.auth().signIn(withEmail: email, password: password) { (user, error) in self.currentUser = user?.user //print(error) if self.currentUser != nil { self.performSegue(withIdentifier: "loginPressed", sender: self) } else { self.alert(title: "Zonk", message: "Email or Password incorrect", option: "Try Again") } } } func alert(title: String, message: String, option: String) { let alert = UIAlertController(title: title, message: message , preferredStyle: .alert) let action = UIAlertAction(title: option, style: .default, handler: nil) alert.addAction(action) present(alert, animated: true, completion: nil) } }
// // ViewController.swift // NoStoryBoardsTables // // Created by Macbook on 02/05/2017. // Copyright © 2017 Chappy-App. All rights reserved. // import UIKit class ViewController: UITableViewController { let names = ["Mandy", "Paul", "Michael", "Harry"] let images = ["burger", "pizza", "sandwich", "taco"] override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tableView.register(NameCell.self, forCellReuseIdentifier: "cell") } override func numberOfSections(in tableView: UITableView) -> Int { return 4 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return names.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! NameCell cell.nameLabel.text = names[indexPath.row] cell.profileImageView.image = UIImage(named: images[indexPath.row]) return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 70 } }
// // BranchTermDetailViewController.swift // Branch Terms // // Created by Michael Horn on 5/19/20. // Copyright © 2020 Mike Horn. All rights reserved. // import UIKit import Branch class BranchTermDetailViewController: UIViewController { var branchTermName: String = "" var branchDefinition: String = "" var buo = BranchUniversalObject() var lp = BranchLinkProperties() @IBOutlet weak var branchTermNameLabel: UILabel! @IBOutlet weak var branchDefinitionLabel: UILabel! // load up your UILabels with data set from either your TableViewController or the Branch link data returned from initSession in AppDelegate override func viewDidLoad() { super.viewDidLoad() branchTermNameLabel.text = branchTermName branchDefinitionLabel.text = branchDefinition createContentReference(name: branchTermName, def: branchDefinition) } // function call to generate your buo with the data to get it ready for sharing func createContentReference(name: String, def: String) { buo = BranchUniversalObject.init(canonicalIdentifier: "branchterm/12345") buo.title = name buo.contentDescription = def buo.imageUrl = "https://banner2.cleanpng.com/20180516/icw/kisspng-branch-metrics-mobile-deep-linking-logo-marketing-leaflets-5afcab538a7c23.7609386415265083715672.jpg" buo.publiclyIndex = true buo.locallyIndex = true buo.contentMetadata.customMetadata["branch_term_name"] = name buo.contentMetadata.customMetadata["branch_definition"] = def lp.channel = "sms" lp.feature = "sharing" lp.campaign = "COVID" lp.tags = [branchTermName, "share-term", "covid"] lp.addControlParam("$desktop_url", withValue: "https://branch.io/glossary/") } // tie an action to your button and show share sheet to generate a Branch link for sharing @IBAction func shareBranchTerm(sender: UIButton) { let message = "Learn about \(branchTermName)!" print(buo.contentMetadata) buo.showShareSheet(with: lp, andShareText: message, from: self) { (activityType, completed) in print(activityType ?? "") } } /* // 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. } */ }
// // MercariTests.swift // MercariTests // import XCTest @testable import Mercari class MercariTests: XCTestCase { private var sessionUnderTest: URLSession! private let urlString = "https://www.google.com/" // URL that stored the json files. We will use google.com as an example here. override func setUp() { super.setUp() sessionUnderTest = URLSession(configuration: .default) } override func tearDown() { sessionUnderTest = nil super.tearDown() } func testCallToWebGetsHttpStatusCode200() { let url = URL(string: urlString) let expect = expectation(description: "Completion handler invokved") var statusCode: Int? var responseError: Error? let dataTask = sessionUnderTest.dataTask(with: url!) { (data, response, error) in statusCode = (response as? HTTPURLResponse)?.statusCode responseError = error expect.fulfill() } dataTask.resume() waitForExpectations(timeout: 5, handler: nil) // Setting for 5 s to fetch the url, if not failed here. XCTAssertNil(responseError) XCTAssertEqual(statusCode, 200) } func testParseJsonInBundle() { let path = Bundle.main.path(forResource: "all", ofType: "json") let dataToParse = try? Data(contentsOf: URL(fileURLWithPath: path!)) let parsedData = ParseJsonManager.parseJSONData(data: dataToParse) let data = parsedData?["data"] let count = data != nil ? 1 : 0 XCTAssertEqual(count, 1, "Parsed data failed. Data does not exist in json") } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
// // MagicModel.swift // ForcedPairProject // // Created by Alfredo Barragan on 1/9/19. // Copyright © 2019 Alfredo Barragan. All rights reserved. // import Foundation struct MagicCards: Codable { let cards: [MagicCardInfo] } struct MagicCardInfo: Codable { let foreignNames: [ForeignNames] let imageUrl: URL? } struct ForeignNames: Codable { let name: String let text: String let language: String let imageUrl: String }
// // PortfolioController.swift // crypto-graph // // Created by Александр Пономарев on 05.04.18. // Copyright © 2018 Base team. All rights reserved. // import Foundation protocol PortfolioDataControllerDelegate: class { func controller(_ controller: PortfolioDataController, didChange coinTransactionsObject: CoinTransactionsData, at index: Int) func controller(_ controller: PortfolioDataController, didAdd coinTransactionsObject: CoinTransactionsData) func controller(_ controller: PortfolioDataController, didRemove coinTransactionsObject: CoinTransactionsData, from index: Int) } class PortfolioDataController { var objects: [CoinTransactionsData] = [] weak var delegate: PortfolioDataControllerDelegate? func setupWithTransactions(_ transactions: [Transaction]?) { guard let t = transactions else { objects = [] return } t.forEach { addTransaction($0, notifying: false) } } func addTransaction(_ transaction: Transaction) { addTransaction(transaction, notifying: true) } func removeTransaction(_ transaction: Transaction) { let _targetIndex = objects.index { $0.coin == transaction.coin } guard let targetIndex = _targetIndex else { return } let target = objects[targetIndex] do { try target.subtract(transaction: transaction) } catch { } if target.isEmpty { delegate?.controller(self, didRemove: target, from: targetIndex) objects.remove(at: targetIndex) } else { delegate?.controller(self, didChange: target, at: targetIndex) } } private func addTransaction(_ transaction: Transaction, notifying: Bool) { let _targetIndex = objects.index { $0.coin == transaction.coin } guard let targetIndex = _targetIndex else { let data = CoinTransactionsData(transaction: transaction) objects.append(data) if notifying { delegate?.controller(self, didAdd: data) } return } let target = objects[targetIndex] try! target.concat(with: transaction) if notifying { delegate?.controller(self, didChange: target, at: targetIndex) } } } class CoinTransactionsData { let coin: Coin var markets: String { var markets: [String] = [] history.forEach { hist in if !markets.contains(where: { market in market.lowercased() == hist.market.lowercased() }) { markets.append(hist.market) } } return markets.joined(separator: ", ") } var amount: Float { return history.reduce(0, { switch $1.type { case .buy: return $0 + $1.quantity case .sell: return $0 - $1.quantity } }) } var avgBuyPrice: Float { var buyQuantity = history.filter({ $0.type == .buy }).reduce(0, { $0 + $1.quantity }) let buyValue = history.filter({ $0.type == .buy }).reduce(0, { $0 + $1.value }) if buyQuantity == 0 { buyQuantity = 1 } return buyValue/buyQuantity } var cost: Float { return history.reduce(0, { switch $1.type { case .buy: return $0 + $1.value case .sell: return $0 - $1.value } }) } var currentCost: Float? { guard let price = coin.price else { return nil } return price * amount } var profit: Float? { guard let curCost = currentCost else { return nil } if cost == 0 { return 0 } return ((curCost - cost) * 100.0)/cost } var isEmpty: Bool { return amount == 0 && avgBuyPrice == 0 && cost == 0 } struct History { let id: String let type: Transaction.TransactionType let price: Float let quantity: Float let market: String var value: Float { return price * quantity } } private var history: [History] = [] init(transaction: Transaction) { self.coin = transaction.coin let id = transaction.objectID.uriRepresentation().absoluteString history.append(History(id: id, type: transaction.type, price: transaction.price.value, quantity: transaction.quantity, market: transaction.market)) } func concat(with transaction: Transaction) throws { guard self.coin.symbol == transaction.coin.symbol else { throw ConcatError.transactionCoinDoesntCorresponds } let id = transaction.objectID.uriRepresentation().absoluteString guard !history.contains(where: { $0.id == id }) else { throw ConcatError.transactionAlreadyConcatenated } history.append(History(id: id, type: transaction.type, price: transaction.price.value, quantity: transaction.quantity, market: transaction.market)) } func subtract(transaction: Transaction) throws { guard self.coin.symbol == transaction.coin.symbol else { throw SusbtractError.transactionCoinDoesntCorresponds } let id = transaction.objectID.uriRepresentation().absoluteString guard let index = history.index(where: { $0.id == id }) else { throw SusbtractError.transactionWasntConcatenatedBefore } history.remove(at: index) } enum ConcatError: Error { case concatError case transactionCoinDoesntCorresponds case transactionAlreadyConcatenated } enum SusbtractError: Error { case transactionCoinDoesntCorresponds case transactionWasntConcatenatedBefore } }
import UIKit //funciones //func calculaIMC(PesoIntegral peso: Double, altura:Double) ->(imcCalculado :Double,mensaje:String){ // // // let imc=peso / (altura*altura) // // // var mensaje = "" // if(imc > 18.50 && imc < 25.00){ // mensaje="Peso normal" // }else{ // mensaje="Debes de acudir con tu medico" // } // // //tupla para regresar mas de un tipo de dato // let resultado=(imc,mensaje) // return resultado //} // //let (imc,mensaje)=calculaIMC(PesoIntegral:66.0, altura:1.6) // //mensaje //imc ////print("hello \(imc)") // ////imc.0 ////imc.1 // ////tupla por fuera //let imcTupla=calculaIMC(PesoIntegral:66.0, altura:1.6) // //imcTupla.imcCalculado //imcTupla.mensaje // //var pelicula : (nombre:String,añoSalida:Int,calificacion:Double)=("El tigre",1990,100.6) // //pelicula.añoSalida // //// opcionales // var numero:Bool? = nil // // //numero=6 // //if numero != nil { // let numeroString: String = String(numero!) // // print(numeroString) //} func profesores( id: String )->String?{ let diccionarioDeProfesores=["007":"David","008":"Martin","009":"Rafa","0010":"Victor"] let nombre : String? = diccionarioDeProfesores[id] return nombre } if let nombre=profesores(id: "0078"){ nombre }else{ // print("No existe el profesor") } let nombreDos=profesores(id: "0089") if nombreDos != nil{ nombreDos }else{ // print("No existe el profesor") } //enumeracion let ciudades=["Cancun","Guadalajara","DF","Monterrey"] enum Ciudad{ case Cancun, Guadalajara, DF, Monterrey } func obtenerCiudades(ciudad:Ciudad)->String{ switch ciudad { case .Cancun: return "Ciudad de playa" case .Guadalajara,.DF,.Monterrey: return "Ciudad sin playa" default: return "Opcion invalida" } } obtenerCiudades(ciudad: Ciudad.Cancun) enum CiudadType:Int{ case Cancun=450, Guadalajara=10, DF=78, Monterrey=512 , Merida } func calcularDistancia (ciudad:CiudadType)->Int{ return CiudadType.Cancun.rawValue-ciudad.rawValue } calcularDistancia(ciudad: CiudadType.Monterrey) //valores dentro de una enumeracion enum lecturaDeDatos{ case Digitos(Int,Int,Int) case QrCodigo(String) } var entradaDatos = lecturaDeDatos.Digitos(3, 4, 5) entradaDatos = .QrCodigo("AABBCC") switch entradaDatos { case .Digitos(let uno, let dos, let tres): print("\(uno) \(dos) \(tres) ") case .QrCodigo(let qr): print("\(qr) ") }
// // NavMenu.swift // AirTicket // // Created by Rauan Kussembayev on 10/6/17. // Copyright © 2017 kuzya. All rights reserved. // import UIKit protocol NavMenuDelegate: class { func thereAction() func backAction() } class NavMenu: UIView { // MARK: - Outlets @IBOutlet var contentView: UIView! @IBOutlet weak var stepsLabel: UILabel! @IBOutlet weak var thereButton: UIButton! @IBOutlet weak var steperView: UIView! // MARK: - Properties(Private) fileprivate let navMenu = "NavMenu" weak var delegate: NavMenuDelegate? // MARK: - Lifecycle override init(frame: CGRect) { super.init(frame: frame) xibSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) xibSetup() } override func awakeFromNib() { } func xibSetup() { Bundle.main.loadNibNamed(navMenu, owner: self, options: nil) addSubview(contentView) contentView.frame = self.bounds contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth] _ = steperView.addBorder(edges: [.bottom], colour: UIColor.lightGray.withAlphaComponent(0.5), thickness: 0.5) } @IBAction func thereAction(_ sender: UIButton) { print("There action") delegate?.thereAction() } @IBAction func backAction(_ sender: UIButton) { print("Back action") delegate?.backAction() } }
// // MainCoordinator.swift // FindMeGame // // Created by jjurlits on 4/24/21. // import UIKit import WebKit class MainCoordinator: Coordinator { var navigationController: UINavigationController init(navigationController: UINavigationController) { self.navigationController = navigationController setupNavigationBar() } func start() { let vc = LoadingViewController.instantiate() vc.coordinator = self navigationController.pushViewController(vc, animated: false) } func showHome() { let vc = HomeViewController.instantiate() vc.coordinator = self navigationController.pushViewController(vc, animated: true) } func showGame() { let vc = GameViewController.instantiate() navigationController.pushViewController(vc, animated: true) } func showWebView(_ url: URL) { let vc = WebViewController.instantiate() vc.url = url navigationController.pushViewController(vc, animated: true) } func showAbout() { let vc = AboutViewController.instantiate() navigationController.pushViewController(vc, animated: true) } } extension MainCoordinator { private func setupNavigationBar() { let navigationBarAppearance = UINavigationBarAppearance() navigationBarAppearance.configureWithOpaqueBackground() navigationBarAppearance.backgroundColor = .clear navigationController.navigationBar.standardAppearance = navigationBarAppearance navigationController.navigationBar.scrollEdgeAppearance = navigationBarAppearance navigationController.navigationBar.compactAppearance = navigationBarAppearance navigationController.navigationBar.prefersLargeTitles = false } }
// // ViewController.swift // Spot // // Created by george on 26/01/2017. // Copyright © 2017 george. All rights reserved. // import UIKit import Alamofire import AVFoundation var player = AVAudioPlayer() var indicator = UIActivityIndicatorView() class TableViewController: UITableViewController, UISearchBarDelegate { @IBOutlet weak var searchBar: UISearchBar! var searchUrl = String() typealias JSONStandard = [String: AnyObject] var posts = [Post]() let loadingPage : UIView = { let v = UIView() v.backgroundColor = UIColor.white v.translatesAutoresizingMaskIntoConstraints = false return v }() override func viewDidLoad() { super.viewDidLoad() searchBar.delegate = self indicatorSetup() //INDICATOR INIT!!! } } //MARK:- SearchBar extension TableViewController { func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { let keywords = searchBar.text let finalKeywords = keywords?.replacingOccurrences(of: " ", with: "+") searchUrl = "https://api.spotify.com/v1/search?q=\(finalKeywords!)&type=track" indStart() //INDICATOR ON!!!! callAlamo(url: searchUrl) self.view.endEditing(true) } } //MARK:- Indicator extension TableViewController { func indicatorSetup() { indicator.hidesWhenStopped = true indicator.activityIndicatorViewStyle = .gray self.tableView.addSubview(indicator) var point = tableView.center point.y = point.y - 50 indicator.center = point } func indStart() { indicator.startAnimating() //UIApplication.shared.beginIgnoringInteractionEvents() } func indStop() { //UIApplication.shared.endIgnoringInteractionEvents() indicator.stopAnimating() } } //MARK:- Alamofire extension TableViewController { func callAlamo(url: String) { Alamofire.request(url).responseJSON(completionHandler: { response in self.parseData(JSONData: response.data!) }) } func parseData(JSONData: Data) { posts.removeAll() do { var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONStandard //print(readableJSON) if let tracks = readableJSON["tracks"] as? JSONStandard { if let items = tracks["items"] as? [JSONStandard] { for i in 0 ..< items.count { let item = items[i] //print(item) let name = item["name"] as! String let previewUrl = item["preview_url"] as! String if let album = item["album"] as? JSONStandard { if let images = album["images"] as? [JSONStandard] { let imageInfo = images[0] let imageUrl = URL(string: imageInfo["url"] as! String) let imageData = NSData(contentsOf: imageUrl!) as! Data let image = UIImage(data: imageData) posts.append(Post.init(image: image, name: name, previewUrl: previewUrl)) DispatchQueue.main.async(execute: { self.tableView.reloadData() self.indStop() // INDICATOR OFF!!!!!! }) } } } } } } catch { print(error) } } } //MARK:- Table extension TableViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return posts.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") let imageView = cell?.viewWithTag(2) as! UIImageView let labelView = cell?.viewWithTag(1) as! UILabel imageView.image = posts[indexPath.row].image labelView.text = posts[indexPath.row].name return cell! } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let indexPath = self.tableView.indexPathForSelectedRow?.row let vc = segue.destination as! AudioViewController vc.post = posts[indexPath!] } }
// // TrainerViewController+TextViewDelegate.swift // JapaneseTrainer // // Created by Luca Gramaglia on 23/05/16. // Copyright © 2016 Luca Gramaglia. All rights reserved. // import Foundation extension TrainerViewController :UITextFieldDelegate { func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if textField.text?.characters.count > 0 { actionButton.enabled = true } else { actionButton.enabled = false } return true } }
// // ProfileBackupPhraseCell.swift // WavesWallet-iOS // // Created by Prokofev Ruslan on 03/10/2018. // Copyright © 2018 Waves Platform. All rights reserved. // import UIKit import Extensions private enum Constants { static let cornerRadii = CGSize(width: 2, height: 2) static let height: CGFloat = 56 } final class ProfileBackupPhraseCell: UITableViewCell, Reusable { struct Model { let isBackedUp: Bool let title: String } @IBOutlet private weak var labelTitle: UILabel! @IBOutlet private weak var viewContainer: UIView! @IBOutlet private weak var viewColorState: UIView! @IBOutlet private weak var iconState: UIImageView! private let maskForColorState = CAShapeLayer() override func awakeFromNib() { super.awakeFromNib() viewContainer.addTableCellShadowStyle() viewColorState.layer.mask = maskForColorState } override func layoutSubviews() { super.layoutSubviews() let maskPath = UIBezierPath(roundedRect: viewColorState.bounds, byRoundingCorners: [.topLeft, .bottomLeft], cornerRadii: Constants.cornerRadii) maskForColorState.path = maskPath.cgPath } class func cellHeight() -> CGFloat { return Constants.height } } // MARK: ViewConfiguration extension ProfileBackupPhraseCell: ViewConfiguration { func update(with model: ProfileBackupPhraseCell.Model) { labelTitle.text = model.title if model.isBackedUp { viewColorState.backgroundColor = .success400 iconState.image = Images.check18Success400.image } else { viewColorState.backgroundColor = .error500 iconState.image = Images.info18Error500.image } } }
// // SFSymbolsHelper.swift // BooksManager // // Created by Sebastian Staszczyk on 19/03/2021. // import Foundation import SwiftUI enum SFSymbol: String { case noInternet = "wifi.slash" case someError = "exclamationmark.shield" var image: Image { Image(systemName: rawValue) } }
// // DoodleCollectionViewCell.swift // DoodleFun // // Created by 江柏毅 on 2021/1/7. // Copyright © 2021 AppCoda. All rights reserved. // import UIKit class DoodleCollectionViewCell: UICollectionViewCell { @IBOutlet var imageView: UIImageView! }
// // UINavigationBarExtension.swift // 100 Percent Calculator // // Created by Thomas Andre Johansen on 05/04/2020. // Copyright © 2020 Appkokeriet. All rights reserved. // //import Foundation //import UIKit // // //extension UINavigationController { // override open func viewDidLoad() { // let navBarAppearance = UINavigationBarAppearance() // navBarAppearance.configureWithOpaqueBackground() // navBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.init(red: 255/255.0, green: 254/255.0, blue: 226/255.0, alpha: 1.0)] // navBarAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.init(red: 255/255.0, green: 254/255.0, blue: 226/255.0, alpha: 1.0)] // navBarAppearance.backgroundColor = UIColor.init(red: 38/255.0, green: 0/255.0, blue: 255/255.0, alpha: 1.0) // navBarAppearance.shadowColor = .clear // navigationBar.standardAppearance = navBarAppearance // navigationBar.scrollEdgeAppearance = navBarAppearance // navigationBar.tintColor = UIColor.init(red: 255/255.0, green: 254/255.0, blue: 226/255.0, alpha: 1.0) // //navigationBar.tintColor = .white // } //}
// // ProfileViewController.swift // obrero_final // // Created by boubakerjouini on 18/6/2021. // import UIKit import Alamofire class ProfileViewController: UIViewController { @IBOutlet weak var emailLabel: UILabel! @IBOutlet weak var nomLabel: UILabel! @IBOutlet weak var prenomLabel: UILabel! @IBOutlet weak var phoneLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() nomLabel.text = UserDefaults.standard.object(forKey: "lastname") as? String; // nomLabel.text = String(x!) emailLabel.text = UserDefaults.standard.object(forKey: "email") as? String; prenomLabel.text = UserDefaults.standard.object(forKey: "firstname") as? String; phoneLabel.text = UserDefaults.standard.object(forKey: "phoneUser") as? String; // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { } @IBAction func getPro(_ sender: Any) { Register() } func Register(){ let parameters = ["id": UserDefaults.standard.object(forKey: "idUser") as? String] let idu = UserDefaults.standard.object(forKey: "idUser") as? Int; let x = String(idu!) AF.request("http://localhost:3000/getpro/"+x, method: .post, parameters: parameters as Parameters, encoding: JSONEncoding.default) .responseJSON { response in switch response.result { case .success(let value): if let json = value as? [String: Any] { print(json["message"] as! String) let msg = json["message"] as! String if(msg == "You're Registerd Successfully"){ // self.performSegue(withIdentifier: "addphone", sender: self) self.performSegue(withIdentifier: "addPrest", sender: self) print("hello") } else { print("already pro") } } case .failure(let error): print(error) } } } @IBAction func log(_ sender: Any) { print("bouba") if let appDomain = Bundle.main.bundleIdentifier { UserDefaults.standard.removePersistentDomain(forName: appDomain) } self.performSegue(withIdentifier: "logginout", sender: self) print("skhat") } @IBAction func logout(_ sender: Any) { } }
// // GraphTableCell.swift // MyLoqta // // Created by Shivansh Jaitly on 9/8/18. // Copyright © 2018 AppVenturez. All rights reserved. // import UIKit class GraphTableCell: BaseTableViewCell, NibLoadableView, ReusableView { //MARK: - IBOutlets @IBOutlet weak var graphCollectionView: UICollectionView! //MARK: - Variables var graphDataSource = [GraphView]() var filterDuration = FilterDuration.lastWeek.rawValue override func awakeFromNib() { super.awakeFromNib() self.registerCell() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } private func registerCell() { self.graphCollectionView.register(GraphCollectionCell.self) self.graphCollectionView.dataSource = self self.graphCollectionView.delegate = self } //MARK: - Public Methods func configureView(graphData: [GraphView], filterType: Int) { self.graphDataSource = graphData self.filterDuration = filterType self.graphCollectionView.reloadData() } } //MARK: - CollectionViewDataSourceAndDelegates extension GraphTableCell: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.graphDataSource.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: GraphCollectionCell = collectionView.dequeueReusableCell(forIndexPath: indexPath) let graphData = self.graphDataSource[indexPath.row] cell.configureView(graphData: graphData, filterType: self.filterDuration) cell.viewDashedLeft.isHidden = indexPath.row > 0 ? true : false return cell } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let width: CGFloat = collectionView.frame.size.width/7 let height = collectionView.frame.size.height return CGSize(width: width, height: height) } }
// // LoginViewController.swift // Driveo // // Created by Admin on 6/2/18. // Copyright © 2018 ITI. All rights reserved. // import UIKit import SkyFloatingLabelTextField class LoginViewController: UIViewController , LoginViewProtocol { var lp:LoginPresenterProtocol! var spinner:UIView! @IBOutlet weak var passTxt: SkyFloatingLabelTextField! @IBOutlet weak var emailTxt: SkyFloatingLabelTextField! @IBAction func loginBut(_ sender: Any) { if validateEmail() { lp.login(withUserName: emailTxt.text!, andPassword: passTxt.text!) showLoading() } } @IBAction func forgotPass(_ sender: Any) { let forgotPassView = self.storyboard?.instantiateViewController(withIdentifier: "forgotPass") self.present(forgotPassView!, animated: true, completion: nil) } @IBAction func registerBut(_ sender: Any) { let signupStoryboard = UIStoryboard(name: "SignupStoryboard", bundle: nil) let signup = signupStoryboard.instantiateViewController(withIdentifier: "SignupView") self.present(signup, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() lp = LoginPresenter(withController: self) emailTxt.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func showErrorLabel(withString str:String){ emailTxt.errorMessage = str } func goToScreen(withScreenName name:String){ if name == "next"{ let screen = ScreenController.sourceScreen let sourceScreenStoryboard = UIStoryboard(name: screen.storyBoardName(), bundle: nil) let sourceScreen = sourceScreenStoryboard.instantiateViewController(withIdentifier: screen.rawValue) sourceScreen.modalTransitionStyle = .crossDissolve self.present(sourceScreen, animated: true, completion: nil) } if name == "verification"{ print("verification") let signupStoryboard = UIStoryboard(name: "SignupStoryboard", bundle: nil) let signup = signupStoryboard.instantiateViewController(withIdentifier: "VerifyView") self.present(signup, animated: true, completion: nil) } } func showLoading() { spinner = UIViewController.displaySpinner(onView: self.view) } func dismissLoading() { UIViewController.removeSpinner(spinner: spinner!) } func showAlert(withTitle title :String , andMessage msg:String){ var alert:UIAlertController = UIViewController.getCustomAlertController(ofErrorType: msg, withTitle: title) self.present(alert, animated: true, completion: nil) let dismissAlertAction:UIAlertAction = UIAlertAction(title: "OK", style: .default) alert.addAction(dismissAlertAction) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } func validateEmail() -> Bool{ if (emailTxt.text?.validate(regex: String.regexes.email.rawValue))! { showErrorLabel(withString: "") return true } else{ showErrorLabel(withString: "Invalid Email") return false } } func loginFailed(withMessage message:String){ showAlert(withTitle: "Failed", andMessage: message) } } extension LoginViewController : UITextFieldDelegate{ func textFieldDidEndEditing(_ textField: UITextField){ switch textField { case emailTxt: validateEmail() default: break } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { return textField.resignFirstResponder() } }
// // VideoSegmentCell.swift // Whale // // Created by Eliel A. Gordon on 3/16/17. // Copyright © 2017 Eliel A. Gordon. All rights reserved. // import UIKit class VideoSegmentCell: UICollectionViewCell { @IBOutlet weak var thumbnailImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() layer.cornerRadius = 6 clipsToBounds = true } }
// // DetailViewController.swift // OmniNews // // Created by Filip on 18/04/2019. // Copyright © 2019 Filip. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var detailTextView: UITextView! var detailText = "" override func viewDidLoad() { super.viewDidLoad() title = "Detail" detailTextView.text = detailText } }
// // DeviceScanCell.swift // CosRemote // // Created by 郭 又鋼 on 2016/3/3. // Copyright © 2016年 郭 又鋼. All rights reserved. // import Foundation import UIKit class DeviceScanCell: UITableViewCell { @IBOutlet var lbDeviceName: UILabel! @IBOutlet var lbIsConnect: UILabel! }
// // StudioGhibliListViewController.swift // GettingDataOnlineExercises // // Created by C4Q on 11/27/17. // Copyright © 2017 Melissa He @ C4Q. All rights reserved. // import UIKit class StudioGhibliListViewController: UIViewController { @IBOutlet weak var filmTableView: UITableView! var studioGhibliFilms: [StudioGhibliFilm] = [] override func viewDidLoad() { super.viewDidLoad() loadData() filmTableView.delegate = self filmTableView.dataSource = self } func loadData() { let urlStr = "https://ghibliapi.herokuapp.com/films" StudioGhibliAPIClient.manager.getMovies( from: urlStr, completionHandler: {(studioGhibliFilmArray: [StudioGhibliFilm]) in self.studioGhibliFilms = studioGhibliFilmArray DispatchQueue.main.async { self.filmTableView.reloadData() } }, errorHandler: {print($0)}) } //Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if sender is UITableViewCell, let selectedIndexPath = filmTableView.indexPathForSelectedRow, let destinationVC = segue.destination as? StudioGhibliDetailViewController { let selectedFilm = studioGhibliFilms[selectedIndexPath.row] destinationVC.studioGhibliFilm = selectedFilm } } } //Table View Methods extension StudioGhibliListViewController: UITableViewDelegate, UITableViewDataSource { //Table View Delegate Methods func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: "detailedSegue", sender: tableView.cellForRow(at: tableView.indexPathForSelectedRow!)) } //Table View Data Source Methods func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return studioGhibliFilms.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "filmCell", for: indexPath) let currentFilm = studioGhibliFilms[indexPath.row] cell.textLabel?.text = currentFilm.title cell.detailTextLabel?.text = currentFilm.releaseDate return cell } }
// // Loader.swift // Ashish Chauhan // // Created by Ashish Chauhan on 15/11/17. // Copyright © 2017 Ashish Chauhan. All rights reserved. // import Foundation import ReachabilitySwift import SVProgressHUD class Loader { // MARK: - Loading Indicator static let thickness = CGFloat(6.0) static let radius = CGFloat(22.0) class func showLoader(title: String = "Loading...") { DispatchQueue.main.async { // UIApplication.shared.beginIgnoringInteractionEvents() SVProgressHUD.setBackgroundColor(UIColor.clear) SVProgressHUD.setDefaultMaskType(.clear) SVProgressHUD.setRingThickness(thickness) SVProgressHUD.setRingRadius(radius) SVProgressHUD.setForegroundColor(UIColor.gray) if !SVProgressHUD.isVisible() { SVProgressHUD.show() } } } class func showLoaderInView(title: String = "Loading...", view: UIView) { DispatchQueue.main.async { SVProgressHUD.setBackgroundColor(UIColor.clear) SVProgressHUD.setDefaultMaskType(.clear) SVProgressHUD.setRingThickness(thickness) SVProgressHUD.setRingRadius(radius) if !SVProgressHUD.isVisible() { SVProgressHUD.show() } } } class func hideLoader() { DispatchQueue.main.async { // UIApplication.shared.endIgnoringInteractionEvents() SVProgressHUD.dismiss() } } class func hideLoaderInView(view: UIView) { DispatchQueue.main.async { SVProgressHUD.dismiss() } } // MARK: - Reachability method class func isReachabile() -> Bool { let reachability = Reachability(hostname: "www.google.com") return reachability!.isReachable } } let isDebugModeOn = true class Debug { class func Log<T>(message: T, functionName: String = #function, fileNameWithPath: String = #file, lineNumber: Int = #line ) { Threads.performTaskInBackground { if isDebugModeOn { let fileNameWithoutPath:String = NSURL(fileURLWithPath: fileNameWithPath).lastPathComponent ?? "" let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm:ss.SSS" let output = "\r\n❗️\(fileNameWithoutPath) => \(functionName) (line \(lineNumber), at \(dateFormatter.string(from: NSDate() as Date)))\r\n => \(message)\r\n" print(output) } } } }
//: [Previous](@previous) import Foundation func join<Element: Equatable>(elements: [Element], separator: String) -> String { return elements.reduce("") { initial, element in let aSeparator = (element == elements.last) ? "" : separator return "\(initial)\(element)\(aSeparator)" } } let items = ["First", "Second", "Third"] let commaSeparatedItems = join(elements: items, separator: ", ") //: [Next](@next)
// // SlackAttachmentAction.swift // PerfectSlackAPIClient // // Created by Sven Tiigi on 11.01.18. // import ObjectMapper // MARK: SlackAttachment Extension public extension SlackAttachment { /// The actions you provide will be rendered as message buttons or menus to users. struct Action { /// Provide a string to give this specific action a name. /// The name will be returned to your Action URL along with the message's callback_id when this action is invoked. /// Use it to identify this particular response path. If multiple actions share the same name, /// only one of them can be in a triggered state. public var name: String /// The user-facing label for the message button or menu representing this action. /// Cannot contain markup. Best to keep these short and decisive. /// Use a maximum of 30 characters or so for best results across form factors. public var text: String /// Provide button when this action is a message button or provide select when the action is a message menu. public var type: ActionType /// Provide a string identifying this specific action. /// It will be sent to your Action URL along with the name and attachment's callback_id. /// If providing multiple actions with the same name, value can be strategically used to differentiate intent. /// Your value may contain up to 2000 characters. public var value: String? /// If you provide the confirmation fields, your button or menu will pop up a dialog /// with your indicated text and choices, giving them one last chance /// to avoid a destructive action or other undesired outcome. public var confirm: Confirmation? /// Used only with message buttons, this decorates buttons with extra visual importance, /// which is especially useful when providing logical default action or highlighting a destructive activity. /// default — Yes, it's the default. Buttons will look simple. /// primary — Use this sparingly, when the button represents a key action to accomplish. /// You should probably only ever have one primary button within a set. /// danger — Use this when the consequence of the button click will result in the destruction of something, /// like a piece of data stored on your servers. Use even more sparingly than primary. public var style: Style? /// Used only with message menus. The individual options to appear in this menu, /// provided as an array of option fields. Required when data_source is static or otherwise unspecified. /// A maximum of 100 options can be provided in each menu. public var options: [Option]? /// Used only with message menus. An alternate, semi-hierarchal way to list available options. /// Provide an array of option group definitions. This replaces and supersedes the options array. public var optionGroups: [Option]? /// Accepts static, users, channels, conversations, or external. /// Our clever default behavior is default, which means the menu's options are /// provided directly in the posted message under options. Defaults to static. public var dataSource: DataSource? /// If provided, the first element of this array will be set as the pre-selected option for this menu. // Any additional elements will be ignored. /// The selected option's value field is contextual based on menu type and is always required: /// For menus of type static (the default) this should be in the list of options included in the action. /// For menus of type users, channels, or conversations, this should be a valid ID of the corresponding type. /// For menus of type external this can be any value, up to a couple thousand characters. public var selectedOptions: [Option]? /// Only applies when data_source is set to external. If present, Slack will wait till the specified /// number of characters are entered before sending a request to your app's external /// suggestions API endpoint. Defaults to 1. public var minQueryLength: Int? /// Default initializer /// /// - Parameters: /// - name: The name /// - text: The text /// - type: The type public init(name: String, text: String, type: ActionType) { self.name = name self.text = text self.type = type } } } // MARK: Enums public extension SlackAttachment.Action { /// SlackAttachmentAction.ActionType enum ActionType: String { /// Button case button /// Selection case select } /// SlackAttachmentAction.Style enum Style: String { /// Default case `default` /// Primary Style case primary /// Danger (Red) case danger } /// SlackAttachmentAction.DataSource enum DataSource: String { /// Default case `default` /// Static case `static` /// Users case users /// Channels case channels /// Conversation case conversation /// External case external } } // MARK: Mappable extension SlackAttachment.Action: Mappable { /// ObjectMapper initializer public init?(map: Map) { let json = map.JSON guard let name = json["name"] as? String, let text = json["text"] as? String, let typeString = json["type"] as? String, let type = ActionType(rawValue: typeString) else { return nil } self.name = name self.text = text self.type = type } /// Mapping public mutating func mapping(map: Map) { self.escapeStringValues() self.name <- map["name"] self.text <- map["text"] self.type <- map["type"] self.value <- map["value"] self.confirm <- map["confirm"] self.style <- map["style"] self.options <- map["options"] self.optionGroups <- map["optionGroups"] self.dataSource <- map["dataSource"] self.selectedOptions <- map["selectedOptions"] self.minQueryLength <- map["minQueryLength"] } /// Escape Strings before mapping private mutating func escapeStringValues() { self.name.escapeSlackCharacters() self.text.escapeSlackCharacters() self.value?.escapeSlackCharacters() } }
import Foundation var x = NSUTF8StringEncoding var d : AnyIterator<Int> func foo1(_ a : inout [Int]) { a = a.sorted() a.append(1) } struct S1 {} func foo2(_ a : inout [S1]) { a = a.sorted(isOrderedBefore: { (a, b) -> Bool in return false }) a.append(S1()) } import Swift func foo3(a: Float, b: Bool) {} // RUN: %sourcekitd-test -req=cursor -pos=3:18 %s -- %s %mcp_opt %clang-importer-sdk | FileCheck -check-prefix=CHECK-OVERLAY %s // CHECK-OVERLAY: source.lang.swift.ref.var.global // CHECK-OVERLAY-NEXT: NSUTF8StringEncoding // CHECK-OVERLAY-NEXT: s:v10Foundation20NSUTF8StringEncodingSu // CHECK-OVERLAY-NEXT: UInt // CHECK-OVERLAY-NEXT: <Declaration>public let NSUTF8StringEncoding: <Type usr="s:Su">UInt</Type></Declaration> // RUN: %sourcekitd-test -req=cursor -pos=5:13 %s -- %s %mcp_opt %clang-importer-sdk | FileCheck -check-prefix=CHECK-ITERATOR %s // CHECK-ITERATOR-NOT: _AnyIteratorBase // CHECK-ITERATOR: <Group>Collection/Type-erased</Group> // RUN: %sourcekitd-test -req=cursor -pos=8:10 %s -- %s %mcp_opt %clang-importer-sdk | FileCheck -check-prefix=CHECK-REPLACEMENT1 %s // CHECK-REPLACEMENT1: <Group>Collection/Array</Group> // CHECK-REPLACEMENT1: <Declaration>func sorted() -&gt; [<Type usr="s:Si">Int</Type>]</Declaration> // CHECK-REPLACEMENT1: RELATED BEGIN // CHECK-REPLACEMENT1: sorted(isOrderedBefore: @noescape (Int, Int) -&gt; Bool) -&gt; [Int]</RelatedName> // CHECK-REPLACEMENT1: sorted() -&gt; [Int]</RelatedName> // CHECK-REPLACEMENT1: sorted(isOrderedBefore: @noescape (Int, Int) -&gt; Bool) -&gt; [Int]</RelatedName> // CHECK-REPLACEMENT1: RELATED END // RUN: %sourcekitd-test -req=cursor -pos=9:8 %s -- %s %mcp_opt %clang-importer-sdk | FileCheck -check-prefix=CHECK-REPLACEMENT2 %s // CHECK-REPLACEMENT2: <Group>Collection/Array</Group> // CHECK-REPLACEMENT2: <Declaration>mutating func append(_ newElement: <Type usr="s:Si">Int</Type>)</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=15:10 %s -- %s %mcp_opt %clang-importer-sdk | FileCheck -check-prefix=CHECK-REPLACEMENT3 %s // CHECK-REPLACEMENT3: <Group>Collection/Array</Group> // CHECK-REPLACEMENT3: func sorted(isOrderedBefore: @noescape (<Type usr="s:V13cursor_stdlib2S1">S1</Type> // CHECK-REPLACEMENT3: sorted() -&gt; [S1]</RelatedName> // CHECK-REPLACEMENT3: sorted() -&gt; [S1]</RelatedName> // CHECK-REPLACEMENT3: sorted(isOrderedBefore: @noescape (S1, S1) -&gt; Bool) -&gt; [S1]</RelatedName> // RUN: %sourcekitd-test -req=cursor -pos=18:8 %s -- %s %mcp_opt %clang-importer-sdk | FileCheck -check-prefix=CHECK-REPLACEMENT4 %s // CHECK-REPLACEMENT4: <Group>Collection/Array</Group> // CHECK-REPLACEMENT4: <Declaration>mutating func append(_ newElement: <Type usr="s:V13cursor_stdlib2S1">S1</Type>)</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=21:10 %s -- %s %mcp_opt %clang-importer-sdk | FileCheck -check-prefix=CHECK-MODULE-GROUP1 %s // CHECK-MODULE-GROUP1: MODULE GROUPS BEGIN // CHECK-MODULE-GROUP1-DAG: Math // CHECK-MODULE-GROUP1-DAG: Collection // CHECK-MODULE-GROUP1-DAG: Collection/Array // CHECK-MODULE-GROUP1: MODULE GROUPS END // RUN: %sourcekitd-test -req=cursor -pos=22:17 %s -- %s %mcp_opt %clang-importer-sdk | FileCheck -check-prefix=CHECK-FLOAT1 %s // CHECK-FLOAT1: s:Sf // RUN: %sourcekitd-test -req=cursor -pos=22:25 %s -- %s %mcp_opt %clang-importer-sdk | FileCheck -check-prefix=CHECK-BOOL1 %s // CHECK-BOOL1: s:Sb
// // PostDetailsViewController.swift // RedditClient // // Created by Luis Romero on 6/6/21. // import UIKit import Photos class PostDetailsViewController: UIViewController { @IBOutlet weak var contentView: PostDetailsContentView! var viewModel: PostDetailsViewModel? override func viewDidLoad() { super.viewDidLoad() self.setupView() } @IBAction func saveImage(_ sender: Any) { self.viewModel?.savePostImage(completion: { (error) in if let error = error { DialogHelper.displayAlert(title: "Error", message: error.localizedDescription, controller: self) } else { DialogHelper.displayAlert(title: "Information", message: "Image saved successfully", controller: self) } }) } private func setupView() { guard self.viewModel != nil else { return } self.contentView.userLabel.text = self.viewModel?.author self.contentView.subRedditLabel.text = self.viewModel?.subReddit self.contentView.contentLabel.text = self.viewModel?.title // Load image FetchImagesHelper.fetchImage(url: self.viewModel?.post.url ?? "", into: self.contentView.imageView) } }
// // SearchVC.swift // GithubFollowers // // Created by Mac OS on 6/20/20. // Copyright © 2020 Ahmed Eid. All rights reserved. // import UIKit class SearchVC: UIViewController { let logoImageView = UIImageView() let usernameTextField = GFTextField() let getFollowersButton = GFButton(backgroundColor: .systemGreen, title: "Get Followers") var isUsernameEntered: Bool { return !usernameTextField.text!.isEmpty } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground configureLogoImageView() configureUsernameTextField() configuerGetFollowersButtton() createDismissKeyboardTabGesture() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) usernameTextField.text = "" navigationController?.setNavigationBarHidden(true, animated: true) } private func createDismissKeyboardTabGesture() { let tap = UITapGestureRecognizer(target: view, action: #selector(view.endEditing)) view.addGestureRecognizer(tap) } @objc private func pushFollowersVC() { guard isUsernameEntered else { presentGFAlertOnTheMainThread(title: "Empty Username", message: "Please enter a username. we need to know who to look for 😀", buttonTitle: "Ok") return } usernameTextField.resignFirstResponder() let followersVC = FollowersVC(username: usernameTextField.text!) navigationController?.pushViewController(followersVC, animated: true) } private func configureLogoImageView() { view.addSubview(logoImageView) logoImageView.translatesAutoresizingMaskIntoConstraints = false logoImageView.image = Images.ghLogo let topHeightContant: CGFloat = DeviceTypes.isiPhoneSE || DeviceTypes.isiPhone8Zoomed ? 20 : 80 logoImageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: topHeightContant).isActive = true NSLayoutConstraint.activate([ logoImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor), logoImageView.heightAnchor.constraint(equalToConstant: 200), logoImageView.widthAnchor.constraint(equalToConstant: 200) ]) } private func configureUsernameTextField() { view.addSubview(usernameTextField) usernameTextField.delegate = self NSLayoutConstraint.activate([ usernameTextField.topAnchor.constraint(equalTo: logoImageView.bottomAnchor, constant: 48), usernameTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 50), usernameTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -50), usernameTextField.heightAnchor.constraint(equalToConstant: 50) ]) } private func configuerGetFollowersButtton() { view.addSubview(getFollowersButton) getFollowersButton.addTarget(self, action: #selector(pushFollowersVC), for: .touchUpInside) NSLayoutConstraint.activate([ getFollowersButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -50), getFollowersButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 50), getFollowersButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -50), getFollowersButton.heightAnchor.constraint(equalToConstant: 50) ]) } } extension SearchVC: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { pushFollowersVC() return true } }
// // ViewController.swift // DatingApp // // Created by Choudhury, Apratim (201) on 25.05.17. // Copyright © 2017 Apro. All rights reserved. // import UIKit import RxSwift import RxCocoa import MDCSwipeToChoose private let kCardsToShow = 3 private let kMargin: CGFloat = 10 private let kTopBottomMargin: CGFloat = 100 private let kCardHeightDiff: CGFloat = 5 final class ViewController: UIViewController { private let disposeBag = DisposeBag() fileprivate let viewModel = ViewProvider.viewModel fileprivate var swipeViews = [PersonSwipeView]() // TODO: - use/implement a queue @IBOutlet private var wildCardLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. viewModel.fetchWildCards() setupNetworkActivityIndicator() setupWildCardLabel() setupSwipeView() } private func setupSwipeView() { let options = MDCSwipeToChooseViewOptions() options.delegate = self options.likedText = NSLocalizedString("Like", comment: "") options.likedColor = UIColor.green options.nopeText = NSLocalizedString("Nope", comment: "") options.nopeColor = UIColor.red let rect = self.view.bounds viewModel.people.asDriver().drive(onNext: { [unowned self] people in for (index, person) in people.prefix(3).enumerated() { let swipeView = PersonSwipeView(person: person, frame: CGRect(x: kMargin, y: CGFloat(kTopBottomMargin - (CGFloat(index) * kCardHeightDiff)), width: rect.width - (2 * kMargin), height: rect.height - (2 * kTopBottomMargin)), options: options) self.view.insertSubview(swipeView, at: 0) self.swipeViews.append(swipeView) } self.wildCardLabel.text = NSLocalizedString("\(people.count) wildcard matches remaining.", comment: "") }).addDisposableTo(disposeBag) viewModel.currentPersonIndex.asDriver() .filter({ [unowned self] idx in self.viewModel.people.value.count >= idx + kCardsToShow }).drive(onNext: { [unowned self] idx in for (idx, view) in self.swipeViews.enumerated() { view.frame.origin = CGPoint(x: kMargin, y: kTopBottomMargin - (CGFloat(idx) * kCardHeightDiff)) } let swipeView = PersonSwipeView(person: self.viewModel.people.value[idx + kCardsToShow - 1], frame: CGRect(x: kMargin, y: (kTopBottomMargin - kMargin), width: rect.width - (2 * kMargin), height: rect.height - (2 * kTopBottomMargin)), options: options) self.swipeViews.append(swipeView) self.view.insertSubview(swipeView, at: 0) }).addDisposableTo(disposeBag) } private func setupNetworkActivityIndicator() { viewModel.networkReqOngoing.asDriver() .drive(onNext: { ongoing in UIApplication.shared.isNetworkActivityIndicatorVisible = ongoing }).addDisposableTo(disposeBag) } private func setupWildCardLabel() { viewModel.currentPersonIndex.asDriver().drive(onNext: { [unowned self] idx in self.wildCardLabel.text = NSLocalizedString("\(self.viewModel.people.value.count - idx) wildcard matches remaining.", comment: "") }).addDisposableTo(disposeBag) } } extension ViewController: MDCSwipeToChooseDelegate { func view(_ view: UIView!, wasChosenWith direction: MDCSwipeDirection) { swipeViews.remove(at: 0) view.removeFromSuperview() viewModel.currentPersonIndex.value += 1 } }
// // UserModel.swift // TJQS // // Created by X on 16/8/22. // Copyright © 2016年 QS. All rights reserved. // import UIKit var UID:String { return DataCache.Share.User.uid } var SID:String { return DataCache.Share.User.shopid } var UMob:String { return DataCache.Share.User.mobile } class UserModel: Reflect { var uid="" var username="" var mobile="" var truename="" var shopid="" var shopname="" var password = "" var logo = "" var tel = "" var address = "" var info = "" var banner="" var token = "" func registNotice() { if token != "" { CloudPushSDK.bindAccount(token) {[weak self] (res) in} } } func unRegistNotice() { CloudPushSDK.unbindAccount({ (res) in}) } var power = "" { didSet { powerArr = power.split(",") } } var jobname = "" var shopcategory = "" var powerArr:[String] = [] override func excludedKey() -> [String]? { return ["power","powerArr"] } func reset() { uid="" username="" mobile="" truename="" shopid="" shopname="" password = "" logo = "" tel = "" address = "" info = "" power = "" jobname = "" shopcategory = "" token = "" powerArr.removeAll(keepCapacity: false) save() } func doLogin() { // if mobile == "" || pass == "" {return} // // let url = "http://api.0539cn.com/index.php?c=User&a=login&mob=\(mobile)&pass=\(pass)&type=1" // // XHttpPool.requestJson(url, body: nil, method: .GET) {[weak self] (res) in // // if res?["code"].int == 200 // { // let model = UserModel.parse(json: res!["datas"], replace: nil) // // self?.reset(model) // // return // } // // } } func getPower() { if shopid == "" || uid == "" {return} self.powerArr.removeAll(keepCapacity: false) self.power = "" let url = APPURL+"Public/Found/?service=user.getuserpower&shopid="+shopid+"&uid="+uid XHttpPool.requestJson(url, body: nil, method: .POST) { [weak self](o) -> Void in if let p = o?["data"]["info"][0]["power"].string { self?.power = p } } } func save() { UserModel.save(obj: self, name: "UserModel") NoticeWord.UserChanged.rawValue.postNotice(self) } }
// // ZDataDetailsController.swift // Seriously // // Created by Jonathan Sand on 4/13/17. // Copyright © 2017 Jonathan Sand. All rights reserved. // import Foundation #if os(OSX) import Cocoa #elseif os(iOS) import UIKit #endif class ZDataDetailsController: ZGenericController { @IBOutlet var modificationDateLabel: ZTextField? @IBOutlet var cloudStatusLabel: ZTextField? @IBOutlet var totalCountLabel: ZTextField? @IBOutlet var recordNameLabel: ZTextField? @IBOutlet var synopsisLabel: ZTextField? var currentZone: Zone? { return gSelecting.rootMostMoveable } override var controllerID: ZControllerID { return .idDataDetails } override func handleSignal(_ object: Any?, kind: ZSignalKind) { if gDetailsViewIsVisible(for: .vData) { modificationDateLabel?.text = modificationDateText cloudStatusLabel? .text = statusText recordNameLabel? .text = zoneRecordNameText totalCountLabel? .text = totalCountsText synopsisLabel? .text = synopsisText } } var modificationDateText: String { var text = kEmpty if let zone = currentZone, let date = zone.modificationDate { text = date.easyToReadDateTime } return text } var versionText: String { if let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String, let buildNumber = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String { return "version \(version), build \(buildNumber)" } return "BUILD ERROR --- NO VERSION" } var totalCountsText: String { let root = gRecords.rootZone let depth = gCloud?.maxLevel ?? 0 let count = (root?.progenyCount ?? 0) + 1 // add one for root let suffix = count != 1 ? "s" : kEmpty let result = "\(count) idea\(suffix), \(depth) deep" return result } var statusText: String { let cdStatus = gCoreDataStack.statusText let opStatus = gBatches.statusText let timerStatus = gTimers.statusText let text = cdStatus ?? opStatus ?? timerStatus ?? "all data synchronized\(gCloudStatusIsActive ? kEmpty : " locally")" return text } var zoneRecordNameText: String { var text = kEmpty if let zone = currentZone, let name = zone.recordName { let type = zone.widgetType.identifier.uppercased() text = name if gDebugInfo, type.count > 0 { text = "\(type) \(text)" } } return text } var synopsisText: String { guard let current = currentZone, gIsReadyToShowUI else { return kEmpty } current.updateAllProgenyCounts() var text = "level \(current.level + 1)" let grabs = gSelecting.currentMapGrabs if grabs.count > 1 { text.append(" (\(grabs.count) selected)") } else { let p = current.progenyCount let c = current.count let n = current.zonesWithNotes.count if c > 0 { text.append(" (\(c) in list") if p > c { text.append(", \(p) total") } text.append(")") } if n > 0 { text.append(" and \(n) note") if n > 1 { text.append("s") } } } return text } }
// // CoursesCollectionCell.swift // companion // // Created by Uchenna Aguocha on 10/17/18. // Copyright © 2018 Yves Songolo. All rights reserved. // import UIKit class CoursesCollectionCell: UICollectionViewCell { // MARK: - Properties static var cellId = "coursesCollectionCellId" // MARK: - UI Elements let courseTitleLabel: UILabel = { let label = UILabel() label.text = "DS 1.1" label.textColor = MakeSchoolDesignColor.faintBlue label.font = UIFont(name: "AvenirNext-DemiBold", size: 19) label.textAlignment = .center return label }() let courseSubtitleLabel: UILabel = { let label = UILabel() label.text = "Data Analysis & Visualization" label.textColor = MakeSchoolDesignColor.faintBlue label.font = UIFont(name: "AvenirNext-Medium", size: 17) label.textAlignment = .center label.numberOfLines = 2 return label }() let containerView: UIView = { let view = UIView() view.layer.cornerRadius = 6 view.layer.shadowColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).cgColor view.layer.shadowOffset = CGSize.zero view.layer.shadowOpacity = 0.25 view.layer.shadowRadius = 5 view.backgroundColor = MakeSchoolDesignColor.darkBlue return view }() // MARK: - Initializers override init(frame: CGRect) { super.init(frame: frame) } override func layoutSubviews() { containerView.backgroundColor = MakeSchoolDesignColor.red setupAutoLayout() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Methods private func setupAutoLayout() { contentView.addSubviews(views: containerView) containerView.anchor( top: contentView.topAnchor, right: contentView.rightAnchor, bottom: contentView.bottomAnchor, left: contentView.leftAnchor) containerView.addSubviews(views: courseTitleLabel, courseSubtitleLabel) courseTitleLabel.anchor( centerX: containerView.centerXAnchor, centerY: nil, top: containerView.topAnchor, right: containerView.rightAnchor, bottom: nil, left: containerView.leftAnchor, topPadding: 39, rightPadding: 43, bottomPadding: 0, leftPadding: 43, height: 23, width: 0) courseSubtitleLabel.anchor( centerX: containerView.centerXAnchor, centerY: nil, top: courseTitleLabel.bottomAnchor, right: containerView.rightAnchor, bottom: nil, left: containerView.leftAnchor, topPadding: 0, rightPadding: 10, bottomPadding: 0, leftPadding: 10, height: 49, width: 0) } }
// // NotebookViewController+.swift // Prynote2 // // Created by tongyi on 12/10/19. // Copyright © 2019 tongyi. All rights reserved. // import UIKit extension NotebookViewController { override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { // if editingStyle == .delete { // let notebook = storage.notebooks[indexPath.row] // storage.remove(notebook) // displayWaitingView(msg: "Deleting") // } } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return indexPath.section == 1 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // switch indexPath { // case IndexPath(row: 0, section: 0): // let notesViewController = NotesViewController() // notesViewController.storage = storage // notesViewController.notes = storage.allNotes() // notesViewController.stateCoordinator = stateCoordinator // navigationController?.pushViewController(notesViewController, animated: true) // case IndexPath(row: 1, section: 0): // navigationController?.pushViewController(SharedViewController(), animated: true) // default: // let notesViewController = NotesViewController() // let notebook = storage.notebooks[indexPath.row] // notesViewController.storage = storage // notesViewController.notes = storage.notes(in: notebook) // notesViewController._notebook = notebook // notesViewController.stateCoordinator = stateCoordinator // navigationController?.pushViewController(notesViewController, animated: true) // } } override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 2 } else { if storage.isLoadingAllNotebooks { return 0 } else { return open ? storage.numberOfNotebooks() : 0 } } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: Constant.Identifier.NOTEBOOKCELL) as! NotebookCell switch indexPath { case IndexPath(row: 0, section: 0): cell.titleLabel?.text = "All Notes" cell.notesCountLabel?.text = "\(storage.numberOfAllNotes())" cell.isLoading = storage.isLoadingAllNotes case IndexPath(row: 1, section: 0): cell.titleLabel?.text = "Shared With Me" cell.notesCountLabel?.text = "0" cell.isLoading = false default: let notebook = storage.notebook(at: indexPath.row) cell.titleLabel?.text = notebook?.title cell.notesCountLabel?.text = "\(notebook?.numberOfNotes() ?? 0)" cell.isLoading = notebook?.isLoading ?? true } return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 56 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 0 } else { return 56 } } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.01 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard section != 0 else { return nil } let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: Constant.Identifier.NOTEBOOKHEADER) as! NotebookHeader header.configure(title: "All Notebooks", section: section, delegate: self) return header } } extension NotebookViewController: NotebookHeaderDelegate { func notebookHeaderDidOpen(_ header: NotebookHeader, in section: Int) { var insertIndexPaths: [IndexPath] = [] for row in 0..<storage.numberOfNotebooks() { insertIndexPaths.append(IndexPath(row: row, section: section)) } open = true tableView.beginUpdates() tableView.insertRows(at: insertIndexPaths, with: .fade) tableView.endUpdates() } func notebookHeaderDidClose(_ header: NotebookHeader, in section: Int) { var deleteIndexPaths: [IndexPath] = [] for row in 0..<tableView.numberOfRows(inSection: section) { deleteIndexPaths.append(IndexPath(row: row, section: section)) } open = false tableView.beginUpdates() tableView.deleteRows(at: deleteIndexPaths, with: .fade) tableView.endUpdates() } }
// // InfoListView.swift // Movie // // Created by Levin Ivan on 24/09/2019. // Copyright © 2019 Levin Ivan. All rights reserved. // import UIKit import AVKit import AVFoundation import TinyConstraints class InfoView: UIView { var isPlaying = true var player: AVPlayer? var movieTrailer: UIView? lazy var collectionCast = InfoCastCollection() lazy var collectionSimilar = InfoSimilarCollection() lazy var scrollView: UIScrollView = { let scroll = UIScrollView() return scroll }() lazy var titleOriginMovie: UILabel = { let origTitle = UILabel() origTitle.numberOfLines = 0 origTitle.textColor = .lightGray origTitle.textAlignment = NSTextAlignment.left origTitle.font = UIFont.systemFont(ofSize: 17, weight: .semibold) return origTitle }() lazy var genreMovie: UILabel = { let genre = UILabel() genre.numberOfLines = 0 genre.font = UIFont.systemFont(ofSize: 19, weight: .semibold) return genre }() lazy var ratingMovie: UILabel = { let rating = UILabel(frame: CGRect(x: 0, y: 0, width: 160, height: 170)) rating.width(35) rating.height(20) rating.textColor = .white rating.textAlignment = .center rating.font = UIFont.systemFont(ofSize: 13, weight: .semibold) return rating }() lazy var titleMovie: UILabel = { let title = UILabel() title.numberOfLines = 0 title.textAlignment = NSTextAlignment.left title.font = UIFont.systemFont(ofSize: 25, weight: .bold) return title }() lazy var stackView: UIStackView = { let view = UIStackView() view.spacing = 5 view.axis = .vertical view.alignment = .leading view.distribution = .equalCentering return view }() lazy var backdropView: UIImageView = { let view = UIImageView() view.layer.zPosition = 1 return view }() lazy var pausePlayButton: UIButton = { let button = PlayView() button.width(50) button.height(50) button.isHidden = false button.layer.zPosition = 3 return button }() lazy var pausePlayButtonCircle: UIButton = { let button = CircleView() button.width(50) button.height(50) button.isHidden = false button.layer.zPosition = 2 return button }() lazy var overvieMovie: UILabel = { let overview = UILabel() overview.sizeToFit() overview.numberOfLines = 0 overview.font = UIFont.systemFont(ofSize: 17, weight: .regular) return overview }() lazy var castLabel: UILabel = { let cast = UILabel() cast.height(23) cast.font = UIFont.systemFont(ofSize: 19, weight: .bold) return cast }() lazy var similarLabel: UILabel = { let similar = UILabel() similar.numberOfLines = 0 similar.textAlignment = NSTextAlignment.left similar.font = UIFont.systemFont(ofSize: 19, weight: .bold) return similar }() lazy var movieTrailerView: UIView = { let view = UIView() return view }() lazy var activityIndicator: UIActivityIndicatorView = { let activityIndicator = UIActivityIndicatorView(style: .whiteLarge) activityIndicator.color = .lightGray activityIndicator.hidesWhenStopped = true return activityIndicator }() init() { super.init(frame: .zero) setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { configutation() backgroundColor = .groupTableViewBackground } } // MARK: - СОЗДАНИЕ И ВЕРСТКА UI extension InfoView { // MARK: - Конфигурация func configutation() { movieTrailerView.addSubview(backdropView) movieTrailerView.addSubview(pausePlayButton) movieTrailerView.addSubview(pausePlayButtonCircle) addSubview(scrollView) addSubview(activityIndicator) scrollView.addSubview(stackView) activityIndicator.center(in: self) backdropView.top(to: movieTrailerView) backdropView.left(to: movieTrailerView) backdropView.right(to: movieTrailerView) backdropView.bottom(to: movieTrailerView) pausePlayButton.centerX(to: movieTrailerView) pausePlayButton.centerY(to: movieTrailerView) pausePlayButtonCircle.centerX(to: movieTrailerView) pausePlayButtonCircle.centerY(to: movieTrailerView) scrollView.left(to: self) scrollView.right(to: self) scrollView.bottom(to: self) scrollView.top(to: self.safeAreaLayoutGuide) stackView.left(to: self, offset: 16) stackView.right(to: self, offset: -16) stackView.top(to: scrollView, offset: 16) stackView.bottom(to: scrollView, offset: -33) } // MARK: - Pause func pauseButtonAction() { pausePlayButton.setTitle("", for: .normal) pausePlayButton.isHidden = false pausePlayButtonCircle.isHidden = false pausePlayButton.layer.zPosition = 2 pausePlayButtonCircle.layer.zPosition = 1 } // MARK: - Play func playButtonAction() { guard let moviePlayer = player else { return } pausePlayButton.layer.zPosition = 0 pausePlayButtonCircle.layer.zPosition = 0 backdropView.layer.zPosition = 0 movieTrailerView.layer.zPosition = 3 pausePlayButton.isHidden = true pausePlayButtonCircle.isHidden = true if isPlaying { moviePlayer.play() pausePlayButton.setTitle("", for: .normal) } else { moviePlayer.pause() pausePlayButton.layer.zPosition = 2 pausePlayButtonCircle.layer.zPosition = 1 pausePlayButton.setTitle("", for: .normal) } self.isPlaying = !isPlaying pausePlayButton.isHidden = false pausePlayButtonCircle.isHidden = false } // MARK: - Создание кнопки на трейлере private func createPlayerAndButtonPlay(_ url: URL, _ trailer: UIView) { player = AVPlayer(url: url) let playerLayer = AVPlayerLayer(player: player) movieTrailer = trailer trailer.layer.zPosition = 0 playerLayer.frame = trailer.bounds playerLayer.videoGravity = .resizeAspectFill trailer.layer.addSublayer(playerLayer) } // MARK: - CreateTrailerMovie func createTrailerMovie(_ url: URL, _ offset: Int, _ index: Int, _ backdrop: URL) { stackView.addArrangedSubview(movieTrailerView) backdropView.kf.setImage(with: backdrop) movieTrailerView.left(to: stackView) movieTrailerView.right(to: stackView) movieTrailerView.heightToWidth(of: movieTrailerView, multiplier: 0.53) movieTrailerView.top(to: stackView.arrangedSubviews[index], offset: 16) movieTrailerView.layoutIfNeeded() createPlayerAndButtonPlay(url, movieTrailerView) } // MARK: - CreateTitleMovie func createTitleMovie(_ title: String, _ offset: Int, _ index: Int) { titleMovie.text = title stackView.addArrangedSubview(titleMovie) if index - 1 >= 0 { titleMovie.topToBottom(of: stackView.arrangedSubviews[index - 1], offset: CGFloat(offset)) } else { titleMovie.top(to: stackView.arrangedSubviews[index], offset: 20) } } // MARK: - CreateOriginalTitle func createOriginalTitle(_ originalTitle: String, _ offset: Int, _ index: Int) { titleOriginMovie.text = originalTitle stackView.addArrangedSubview(titleOriginMovie) if index - 1 >= 0 { titleOriginMovie.topToBottom(of: stackView.arrangedSubviews[index - 1], offset: CGFloat(offset)) } else { titleOriginMovie.top(to: stackView.arrangedSubviews[index], offset: CGFloat(offset)) } } // MARK: - CreateGenreAndCountre func createGenreAndCountre(_ genreAndCountre: String, _ offset: Int, _ index: Int) { genreMovie.text = genreAndCountre stackView.addArrangedSubview(genreMovie) if index - 1 >= 0 { genreMovie.topToBottom(of: stackView.arrangedSubviews[index - 1], offset: CGFloat(offset)) } else { genreMovie.top(to: stackView.arrangedSubviews[index], offset: CGFloat(offset)) } } // MARK: - CreateVoteAverage func createVoteAverage(_ voteAverage: Double,_ offset: Int, _ index: Int, _ color: UIColor) { stackView.addArrangedSubview(ratingMovie) ratingMovie.backgroundColor = color ratingMovie.text = String(voteAverage) ratingMovie.left(to: stackView) ratingMovie.topToBottom(of: stackView.arrangedSubviews[index - 1], offset: CGFloat(offset)) if index - 1 >= 0 { ratingMovie.topToBottom(of: stackView.arrangedSubviews[index - 1], offset: CGFloat(offset)) } else { ratingMovie.top(to: stackView.arrangedSubviews[index], offset: CGFloat(offset)) } } // MARK: - CreateOverview func createOverview(_ overview: String, _ offset: Int, _ index: Int) { overvieMovie.text = overview stackView.addArrangedSubview(overvieMovie) if index - 1 >= 0 { overvieMovie.topToBottom(of: stackView.arrangedSubviews[index - 1], offset: CGFloat(offset)) } else { overvieMovie.top(to: stackView.arrangedSubviews[index], offset: CGFloat(offset)) } } // MARK: - CreateCastLabel func createCastLabel(_ castLabelMovie: String, _ offset: Int, _ index: Int) { castLabel.text = castLabelMovie stackView.addArrangedSubview(castLabel) if index - 1 >= 0 { castLabel.topToBottom(of: stackView.arrangedSubviews[index - 1], offset: CGFloat(offset)) } else { castLabel.top(to: stackView.arrangedSubviews[index], offset: CGFloat(offset)) } } // MARK: - CreateCastMovie func createCastMovie(_ cast: [Cast], _ offset: Int, _ index: Int) { collectionCast.collectionViewCast(castMovie: cast) stackView.addArrangedSubview(collectionCast) collectionCast.leading(to: self, offset: CGFloat(offset) - 16) collectionCast.trailing(to: self) collectionCast.heightToWidth(of: collectionCast, multiplier: 0.25, offset: 28) if index - 1 >= 0 { collectionCast.topToBottom(of: stackView.arrangedSubviews[index - 1], offset: CGFloat(offset)) } else { collectionCast.topToBottom(of: stackView.arrangedSubviews[index], offset: CGFloat(offset)) } collectionCast.collectionViewCast.reloadData() } // MARK: - CreateSimilarLabel func createSimilarLabel(_ similarLabelMovie: String, _ offset: Int, _ index: Int) { similarLabel.text = similarLabelMovie stackView.addArrangedSubview(similarLabel) similarLabel.left(to: stackView) similarLabel.right(to: stackView) } // MARK: - CreatePosterPath func createPosterPath(_ poster: [URL], _ offset: Int, _ index: Int, _ similar: [ResultSimilar]) { collectionSimilar.collectionViewSimilar(similarMovie: similar, posterSimilarMovie: poster) stackView.addArrangedSubview(collectionSimilar) collectionSimilar.leading(to: self, offset: CGFloat(offset) - 16) collectionSimilar.trailing(to: self) collectionSimilar.bottom(to: stackView, offset: CGFloat(-offset)) collectionSimilar.heightToWidth(of: collectionSimilar, multiplier: 0.43, offset: 10) if index - 1 >= 0 { collectionSimilar.topToBottom(of: stackView.arrangedSubviews[index - 1], offset: CGFloat(offset)) } else { collectionSimilar.topToBottom(of: stackView.arrangedSubviews[index], offset: CGFloat(offset)) } collectionSimilar.collectionViewSimilar.reloadData() } } extension InfoView { override func layoutSubviews() { let cornerRadiusTrailer = 16 let maskLayerTrailer = CAShapeLayer() maskLayerTrailer.path = UIBezierPath( roundedRect: movieTrailerView.bounds, byRoundingCorners: [.bottomLeft, .bottomRight, .topLeft, .topRight], cornerRadii: CGSize(width: cornerRadiusTrailer, height: cornerRadiusTrailer)).cgPath movieTrailerView.layer.mask = maskLayerTrailer let cornerRadius = 4 let maskLayer = CAShapeLayer() maskLayer.path = UIBezierPath( roundedRect: ratingMovie.bounds, byRoundingCorners: [.bottomLeft, .bottomRight, .topLeft, .topRight], cornerRadii: CGSize(width: cornerRadius, height: cornerRadius)).cgPath ratingMovie.layer.mask = maskLayer } }
// // NumbersLightService.swift // NumbersLight // // Created by guillaume sabatié on 28/01/2020. // Copyright © 2020 Guillaume Sabatie. All rights reserved. // import Foundation import Alamofire enum JapaneseNumeralAPIRouter: URLRequestConvertible { static let baseURLString = "https://dev.tapptic.com" case japaneseNumerals case japaneseNumeral(arabicRepresentation: String) func asURLRequest() throws -> URLRequest { let result: (path: String, parameters: Parameters?) = { switch self { case .japaneseNumerals: return ("/test/json.php", nil) case let .japaneseNumeral(arabicRepresentation): let path: String = "/test/json.php" let parammeter: Parameters = ["name" : arabicRepresentation] return (path, parammeter) } }() let url = try JapaneseNumeralAPIRouter.baseURLString.asURL() let urlRequest = URLRequest(url: url.appendingPathComponent(result.path)) return try URLEncoding.default.encode(urlRequest, with: result.parameters) } }
// // TMRequestStyle // TMRequestStyleCollectionViewCell.swift // consumer // // Created by Vladislav Zagorodnyuk on 3/15/17. // Copyright © 2017 Human Ventures Co. All rights reserved. // import UIKit class TMRequestStyleCollectionViewCell: UICollectionViewCell { /// Style text label @IBOutlet weak var styleTitleLabel: UILabel! /// Max width constraint @IBOutlet weak var maxWidthConstraint: NSLayoutConstraint! var gradientBorder = CAGradientLayer() override func layoutSubviews() { super.layoutSubviews() clipsToBounds = true layer.masksToBounds = true layer.cornerRadius = bounds.midY addShadow(cornerRadius: bounds.midY) } func addCellGradientBorder() { guard let sublayers = layer.sublayers else { return } if !sublayers.contains(self.gradientBorder) { gradientBorder = addInnerGradientBorder(bounds.midY, lineWidth: 1.0) } } func removeGradientLayer() { gradientBorder.removeFromSuperlayer() } }
// // StartScreen.swift // KinopoiskApplication // // Created by Danil on 07/01/17. // Copyright © 2017 Not exist. All rights reserved. // import UIKit class StartScreen: UIViewController { @IBOutlet weak var stackView: UIStackView! override func viewDidLoad() { super.viewDidLoad() //Кнопка отправляющая на страницу с поиском и фильтрами let searchButton = UIButton(type: UIButtonType.system) searchButton.setTitle("Искать", for: UIControlState.normal) stackView.addArrangedSubview(searchButton) for _ in 0..<3 { createViewElement(name: "Кнопка") } // Do any additional setup after loading the view. } // override func didReceiveMemoryWarning() { // super.didReceiveMemoryWarning() // // Dispose of any resources that can be recreated. // } // /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ func createViewElement(name: String) -> () { let button = UIButton(type: UIButtonType.system) button.setTitle(name, for: UIControlState.normal) stackView.addArrangedSubview(button) } }
/* Copyright Airship and Contributors */ import Foundation import SwiftUI /// - Note: for internal use only. :nodoc: @objc(UAThomasDelegate) public protocol ThomasDelegate { /// Called when a form is submitted /// - Parameters: /// - formResult: The form result. /// - layoutContext: The layout context. func onFormSubmitted(formResult: ThomasFormResult, layoutContext: ThomasLayoutContext) /// Called when a form is displayed for the first time /// - Parameters: /// - formInfo: The form info. /// - layoutContext: The layout context. func onFormDisplayed(formInfo: ThomasFormInfo, layoutContext: ThomasLayoutContext) /// Called when a button is tapped. /// - Parameters: /// - buttonIdentifier: The button id. /// - layoutContext: The layout context. func onButtonTapped(buttonIdentifier: String, layoutContext: ThomasLayoutContext) /// Called when the view is dismissed. /// - Parameters: /// - layoutContext: The layout context. func onDismissed(layoutContext: ThomasLayoutContext?) /// Called when the view is dismissed from a button tap. /// - Parameters: /// - buttonIdentifier: The button id. /// - buttonDescription: The button description. /// - cancel: If the view should be cancelled. /// - layoutContext: The layout context. func onDismissed(buttonIdentifier: String, buttonDescription: String, cancel: Bool, layoutContext: ThomasLayoutContext) /// Called when a form is dismissed beceuse it timed out. /// - Parameters: /// - layoutContext: The layout context. func onTimedOut(layoutContext: ThomasLayoutContext?) /// Called when a pager page is viewed. /// - Parameters: /// - pagerInfo: The pager info. /// - layoutContext: The layout context. func onPageViewed(pagerInfo: ThomasPagerInfo, layoutContext: ThomasLayoutContext) /// Called when a pager page changed due to a swipe. /// - Parameters: /// - from: The originated pager info /// - to: The resulting pager info /// - layoutContext: The layout context. func onPageSwiped(from: ThomasPagerInfo, to: ThomasPagerInfo, layoutContext: ThomasLayoutContext) /// Called when actions should be ran. /// - Parameters: /// - actions: The actions. /// - layoutContext: The layout context. func onRunActions(actions: [String : Any], layoutContext: ThomasLayoutContext) } /// - Note: for internal use only. :nodoc: @objc(UAThomasPagerInfo) public class ThomasPagerInfo : NSObject { @objc public let identifier: String @objc public let pageIndex: Int @objc public let pageIdentifier: String @objc public let pageCount: Int @objc public let completed: Bool @objc public init(identifier: String, pageIndex: Int, pageIdentifier: String, pageCount: Int, completed: Bool) { self.identifier = identifier self.pageIndex = pageIndex self.pageIdentifier = pageIdentifier self.pageCount = pageCount self.completed = completed } public override var description: String { "ThomasPagerInfo{identifier=\(identifier), pageIndex=\(pageIndex)}, pageIdentifier=\(pageIdentifier), pageCount=\(pageCount), completed=\(completed)}" } } /// - Note: for internal use only. :nodoc: @objc(UAThomasFormResult) public class ThomasFormResult : NSObject { @objc public let identifier: String @objc public let formData: [String : Any] @objc public init(identifier: String, formData: [String : Any]) { self.identifier = identifier self.formData = formData } public override var description: String { "ThomasFormResult{identifier=\(identifier), formData=\(formData)}" } } /// - Note: for internal use only. :nodoc: @objc(UAThomasButtonInfo) public class ThomasButtonInfo : NSObject { @objc public let identifier: String @objc public init(identifier: String) { self.identifier = identifier } public override var description: String { "ThomasButtonInfo{identifier=\(identifier)}" } } /// - Note: for internal use only. :nodoc: @objc(UAThomasFormInfo) public class ThomasFormInfo : NSObject { @objc public let identifier: String @objc public let submitted: Bool @objc public let formType: String @objc public let formResponseType: String? @objc public init(identifier: String, submitted: Bool, formType: String, formResponseType: String?) { self.identifier = identifier self.submitted = submitted self.formType = formType self.formResponseType = formResponseType } public override var description: String { "ThomasFormInfo{identifier=\(identifier), submitted=\(submitted), formType=\(formType), formResponseType=\(formResponseType ?? "")}" } } /// - Note: for internal use only. :nodoc: @objc(UAThomasLayoutContext) public class ThomasLayoutContext : NSObject { @objc public let formInfo: ThomasFormInfo? @objc public let pagerInfo: ThomasPagerInfo? @objc public let buttonInfo: ThomasButtonInfo? @objc public init(formInfo: ThomasFormInfo?, pagerInfo: ThomasPagerInfo?, buttonInfo: ThomasButtonInfo?) { self.formInfo = formInfo self.pagerInfo = pagerInfo self.buttonInfo = buttonInfo } public override var description: String { "ThomasLayoutContext{formInfo=\(String(describing: formInfo)), pagerInfo=\(String(describing: pagerInfo)), buttonInfo=\(String(describing: buttonInfo))}" } }
// // PatientInformationController.swift // HISmartPhone // // Created by Huỳnh Công Thái on 1/24/18. // Copyright © 2018 MACOS. All rights reserved. // import UIKit // This class display information of patient class PatientInformationController: BaseViewController { // MARK: Define controls private let scrollView: BaseScrollView = BaseScrollView(frame: .zero) private let headerPatientInfoView: HeaderPatientInfoView = HeaderPatientInfoView() private let infoPatientView: InfoPatientView = InfoPatientView() private let patientMedicalInfoView: PatientMedicalInfoView = PatientMedicalInfoView() private let patientBloodPressureWarningView: PatientBloodPressureWarningView = PatientBloodPressureWarningView() // MARK: Setup layout override func setupView() { self.view.addSubview(self.scrollView) self.scrollView.snp.makeConstraints { (make) in make.top.left.right.equalToSuperview() if #available(iOS 11.0, *) { make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom) } else { make.bottom.equalToSuperview() } } self.setTitle() self.setupViewNavigationBar() self.setupHeaderPatientInfoView() self.setupInfoPatientView() self.setupPatientMedicalInfoView() self.setupPatientBloodPressureWarningView() self.headerPatientInfoView.mainDoctor = HISMartManager.share.currentDoctor PatientInfomationFacade.getAddressForCurrentPatient { self.infoPatientView.address = HISMartManager.share.currentPatient.address?.getDescription() self.headerPatientInfoView.users = HISMartManager.share.currentPatient.doctorsFollow ?? [User]() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.patientBloodPressureWarningView.patient = HISMartManager.share.currentPatient } private func setupViewNavigationBar() { self.navigationItem.addLeftBarItem( with: UIImage(named: "back_white"), target: self, selector: #selector(PatientInformationController.handleBackButton), title: nil ) } private func setTitle() { let nameLabel = UILabel() nameLabel.text = "Thông tin bệnh nhân" nameLabel.textColor = Theme.shared.defaultTextColor nameLabel.frame = CGRect(x: 0, y: 0, width: 130, height: 30) nameLabel.font = UIFont.systemFont(ofSize: Dimension.shared.titleFontSize, weight: UIFont.Weight.medium) self.navigationItem.titleView = nameLabel } private func setupHeaderPatientInfoView() { self.scrollView.view.addSubview(self.headerPatientInfoView) self.headerPatientInfoView.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(Dimension.shared.mediumVerticalMargin) make.left.right.equalToSuperview() make.width.equalTo(self.view) } } private func setupInfoPatientView() { self.scrollView.view.addSubview(self.infoPatientView) self.infoPatientView.snp.makeConstraints { (make) in make.top.equalTo(self.headerPatientInfoView.snp.bottom).offset(Dimension.shared.mediumVerticalMargin) make.width.equalTo(self.headerPatientInfoView) } } private func setupPatientMedicalInfoView() { self.scrollView.view.addSubview(self.patientMedicalInfoView) self.patientMedicalInfoView.snp.makeConstraints { (make) in make.top.equalTo(self.infoPatientView.snp.bottom).offset(Dimension.shared.mediumVerticalMargin) make.width.equalTo(self.infoPatientView) } } private func setupPatientBloodPressureWarningView() { self.scrollView.view.addSubview(self.patientBloodPressureWarningView) self.patientBloodPressureWarningView.snp.makeConstraints { (make) in make.top.equalTo(self.patientMedicalInfoView.snp.bottom) .offset(Dimension.shared.mediumVerticalMargin) make.width.equalTo(self.patientMedicalInfoView) make.bottom.equalToSuperview().offset(-Dimension.shared.mediumVerticalMargin) } self.patientBloodPressureWarningView.delegate = self } // MARK: Action @objc private func handleBackButton() { self.navigationController?.popViewController(animated: true) } } // MARK: Extension extension PatientInformationController: PatientBloodPressureWarningDelegate { func editingPatientBloodPressure() { let editPatientBloodPressureController = EditPatientBloodPressureController() self.navigationController?.pushViewController(editPatientBloodPressureController, animated: true) } }
// // PeopleModel.swift // SwiftUI_Test // // Created by Andres Felipe Ocampo Eljaiesk on 01/11/2019. // Copyright © 2019 icologic. All rights reserved. // // This file was generated from JSON Schema using quicktype, do not modify it directly. // To parse the JSON, add this file to your project and do: // // let peopleModel = try? newJSONDecoder().decode(PeopleModel.self, from: jsonData) import Foundation // MARK: - PeopleModelElement struct PeopleModelElement: Identifiable, Codable { let id = UUID() let name: String? let email, city: String? let mac, timestamp: String? let creditcard: String? } typealias PeopleModel = [PeopleModelElement]
// // PinchToPresentInteractionController.swift // PinchToOpen // // Created by Mat Schmid on 2021-11-17. // import UIKit class PinchToPresentInteractionController: NSObject, InteractionControlling { typealias ModalViewControllerDelegate = UIViewController & ModalControllerDelegate var interactionInProgress = false private var currentScale: CGFloat = 0 private var initialFrame: CGRect? private var finalFrame: CGRect? private var cancellationAnimator: UIViewPropertyAnimator? private weak var parentController: ModalViewControllerDelegate! private weak var modalController: PinchPresentable! private weak var transitionContext: UIViewControllerContextTransitioning? init(parentController: ModalViewControllerDelegate, modalController: PinchPresentable) { self.parentController = parentController self.modalController = modalController super.init() preparePinchGesture(in: parentController.view) // TODO: Add pan gesture // TODO: Handle scroll view } private func preparePinchGesture(in view: UIView) { let gesture = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(_:))) view.addGestureRecognizer(gesture) } @objc private func handlePinch(_ gestureRecognizer : UIPinchGestureRecognizer) { switch gestureRecognizer.state { case .began: gestureBegan() gestureRecognizer.scale = 1 case .changed: gestureChanged(scale: gestureRecognizer.scale, velocity: gestureRecognizer.velocity) gestureRecognizer.scale = 1 case .cancelled: gestureCancelled(velocity: gestureRecognizer.velocity) case .ended: gestureEnded(scale: gestureRecognizer.scale, velocity: gestureRecognizer.velocity) default: break } print(currentScale) } func gestureBegan() { disableOtherTouches() cancellationAnimator?.stopAnimation(true) if !interactionInProgress { interactionInProgress = true parentController.presentModal() } } func gestureChanged(scale: CGFloat, velocity: CGFloat) { let delta = scale - 1 currentScale += delta currentScale = max(0, min(1.05, currentScale)) // TODO: Adjust progress to ease out when transition is nearing the end update(progress: max(0, min(1, currentScale))) } func gestureCancelled(velocity: CGFloat) { cancel(initialVelocity: velocity) } func gestureEnded(scale: CGFloat, velocity: CGFloat) { if scale <= 1 { finish(initialVelocity: velocity) } else { cancel(initialVelocity: velocity) } } // MARK: - Transition controlling func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) { guard let presentedViewController = transitionContext.viewController(forKey: .to) else { return } initialFrame = transitionContext.initialFrame(for: presentedViewController) finalFrame = transitionContext.finalFrame(for: presentedViewController) self.transitionContext = transitionContext } func update(progress: CGFloat) { guard let transitionContext = transitionContext else { return } transitionContext.updateInteractiveTransition(progress) guard let presentedViewController = transitionContext.viewController(forKey: .to) else { return } presentedViewController.view.transform = CGAffineTransform(scaleX: currentScale, y: currentScale) presentedViewController.view.alpha = currentScale // TODO: Adjust view's `y` value towards the center of the screen here if let modalPresentationController = presentedViewController.presentationController as? PinchModalPresentationController { modalPresentationController.dimmedView.alpha = progress } } func cancel(initialVelocity: CGFloat) { guard let transitionContext = transitionContext, let initialFrame = initialFrame else { return } guard let presentedViewController = transitionContext.viewController(forKey: .to) else { return } let timingParameters = UISpringTimingParameters(dampingRatio: 0.8, initialVelocity: CGVector(dx: 0, dy: initialVelocity)) cancellationAnimator = UIViewPropertyAnimator(duration: 0.5, timingParameters: timingParameters) cancellationAnimator?.addAnimations { presentedViewController.view.frame = initialFrame if let modalPresentationController = presentedViewController.presentationController as? PinchModalPresentationController { modalPresentationController.dimmedView.alpha = 0 } } cancellationAnimator?.addCompletion { _ in transitionContext.cancelInteractiveTransition() transitionContext.completeTransition(false) self.interactionInProgress = false self.enableOtherTouches() } cancellationAnimator?.startAnimation() } func finish(initialVelocity: CGFloat) { guard let transitionContext = transitionContext else { return } guard let presentedViewController = transitionContext.viewController(forKey: .to) as? PinchPresentable else { return } guard let finalFrame = finalFrame else { return } let timingParameters = UISpringTimingParameters(dampingRatio: 0.8, initialVelocity: CGVector(dx: 0, dy: initialVelocity)) let finishAnimator = UIViewPropertyAnimator(duration: 0.5, timingParameters: timingParameters) finishAnimator.addAnimations { presentedViewController.view.frame = finalFrame if let modalPresentationController = presentedViewController.presentationController as? PinchModalPresentationController { modalPresentationController.dimmedView.alpha = 1.0 } } finishAnimator.addCompletion { _ in transitionContext.finishInteractiveTransition() transitionContext.completeTransition(true) self.interactionInProgress = false } finishAnimator.startAnimation() } // MARK: - Helpers private func disableOtherTouches() { parentController.view.subviews.forEach { $0.isUserInteractionEnabled = false } } private func enableOtherTouches() { parentController.view.subviews.forEach { $0.isUserInteractionEnabled = true } } }
// // Credentials.swift // RookMotionFrancisco // // Created by Francisco Guerrero Escamilla on 06/03/21. // import Foundation struct Credentials { let email: String let password: String }
// // Reporter.swift // App // import Vapor class Reporter { static let baseURL = "https://api.telegram.org/bot" static var sendMessageURL: URL? { guard let token = Environment.get("TOKEN"), let sendMessage = URL(string: baseURL + token + "/sendMessage") else { return nil} return sendMessage } class func update(_ elements: [House], in app: Application) { print("\(#function)") guard elements.count > 0 else { return } report("*Latest Houses*", in: app) elements.forEach { let text = content(from: $0) report(text, in: app) } } class func report(_ text: String, in app: Application) { guard let sendMessageURL = self.sendMessageURL, let chatId = Environment.get("CHAT_ID") else { return } _ = try? app.client().get(sendMessageURL) { get in try get.query.encode([ "chat_id": chatId, "text": text, "parse_mode":"Markdown"]) }.do { response in print(response.http.body) } } class func content(from elements: [House]) -> String { return (["*Latest Houses*"] + elements.map(content)).joined(separator: "\n\n") } class func content(from element: House) -> String { return """ \(element.title) _\(element.price)_ \(element.url) """ } }
class person{ var name:String private var age:Int var phoneNumber:String? var weight:Int = 0 { // property observer -- willSet과 didSet을 가짐, 스스로 값을 가질 수 있음 // willSet은 들어오는 값 체크 didSet은 값 쓰여지고 나서 하는... willSet{ print("현재 값: \(self.weight) 새로운 값 : \(newValue)") // 새로운 값은 newValue로 접근 } didSet{ print("이전 값 : \(oldValue) 현재 값: \(self.weight)") // 이전 값은 oldValue로 접근 } } var koreaaAge:Int{ // 연산 property -- get과 set을 가질 수 있음 // 스스로 값을 가지지는 못하지만 연산만.. get{ return self.age + 1 } set{ self.age = newValue - 1 // newValue keyword : 들어오는 값 의미 } } init(name:String, age:Int, phoneNumber:String?) { self.name = name self.age = age self.phoneNumber = phoneNumber } func walk() { print("talk") } } let p1 = person(name: "홍길동", age: 21, phoneNumber: nil) print(p1.koreaaAge) //p1.age = 20 // private로 설정되어서 접근할 수 없음 //print(p1.age) p1.koreaaAge = 33 // newValue에 33 할당 //print(p1.age) print(p1.koreaaAge) // 접근제어자 -- private, internal(default값 -- project 안에서..), // property oberserver -- property 값 체크, 얜 저장 property임 p1.weight = 30 print(p1.weight) class Shape{ var x:Float var y:Float init(x:Float, y:Float){ self.x = x self.y = y } func draw() { print("Draw") } } class Rectangle:Shape{ var height:Float var width:Float init(x:Float, y:Float, width:Float, height:Float) { self.height = height self.width = width super.init(x: 0, y: 0) } override func draw() { super.draw() print("new Draw") } } let shape = Shape(x: 10, y: 10) let rectangle = Rectangle(x:10, y:10, width: 20, height: 20) shape.draw() rectangle.draw()
// // AppDelegate.swift // Stardust // // Created by sakamoto kazuhiro on 2017/03/04. // Copyright © 2017年 Stardust. All rights reserved. // import UIKit import UserNotifications import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { FIRApp.configure() self.requestSendNotification() // 画像付きlocal notificationのサンプル // LocalNotificationPublisher.publish(withUserName: "foo", userImage: UIImage(named: "GitHub-Mark"), timeInterval: 5) // LocalNotificationPublisher.publish(withUserName: "shikata", imageSubPath: "3538619.png", timeInterval: 5) return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } // MARK: - Notification extension AppDelegate { func requestSendNotification() { let center = UNUserNotificationCenter.current() // center.delegate = self center.requestAuthorization(options: [.badge, .sound, .alert], completionHandler: { (granted, error) in if error != nil { return } if granted { debugPrint("granted") } else { debugPrint("declined") } }) } }
// // main.swift // Stacks // // Created by Andrei Chenchik on 29/7/21. // import Foundation struct Stack<Element> { fileprivate var array = [Element]() var count: Int { array.count } var isEmpty: Bool { array.isEmpty } init(_ items: [Element]) { self.array = items } init() { } mutating func push(_ element: Element) { array.append(element) } mutating func pop() -> Element? { array.popLast() } func peek() -> Element? { array.last } mutating func removeAll() { array.removeAll() } func contains(_ element: Element) -> Bool where Element: Equatable { array.firstIndex(of: element) != nil } } extension Stack: ExpressibleByArrayLiteral { init(arrayLiteral elements: Element...) { self.array = elements } } extension Stack: CustomDebugStringConvertible { var debugDescription: String { var result = "[" var first = true for item in array { if first { first = false } else { result += ", " } debugPrint(item, terminator: "", to: &result) } result += "]" return result } } extension Stack: Equatable where Element: Equatable { } extension Stack: Hashable where Element: Hashable { } extension Stack: Decodable where Element: Decodable { } extension Stack: Encodable where Element: Encodable { } extension Array { init(from stack: Stack<Element>) { self = stack.array } } let stackA = Stack([1, 2, 3]) let stackB = Stack([1, 2, 3]) print(stackA == stackB) var numbers: Stack = [1, 2, 3, 4, 5] print(numbers) print(numbers.pop() ?? "") print(numbers.pop() ?? "") print(numbers.pop() ?? "") print(numbers.pop() ?? "") var names = Stack<String>() names.push("Leonardo") names.push("Michelangelo") names.push("Donatello") names.push("Raphael") print(names) print(names.pop() ?? "") print(names.pop() ?? "") print(names.pop() ?? "") print(names.pop() ?? "") let stack = Stack([1, 2, 3]) let array = Array(from: stack) print(array)
// // DiaryListViewController.swift // DiaryApp // // Created by Dhara Patel on 08/12/20. // Copyright © 2020 Dhara Patel. All rights reserved. // import UIKit import RxSwift import RxCocoa import CoreData class DiaryListViewController: UIViewController { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var diaryTableView: UITableView! private let bag = DisposeBag() let diaryData = BehaviorSubject(value: [NSManagedObject]()) override func viewDidLoad() { super.viewDidLoad() diaryTableView.estimatedRowHeight = 250 diaryTableView.rowHeight = UITableView.automaticDimension } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) bindDiaryToTableview() } func bindDiaryToTableview() { diaryTableView.delegate = nil diaryTableView.dataSource = nil diaryData.bind(to: diaryTableView.rx.items(cellIdentifier: CellIdentifier.diaryListTableViewCell, cellType: DiaryListTableViewCell.self)) { (row,item,cell) in if let diary = item as? Diary { cell.diary = diary cell.delegate = self cell.configureCell(diary: diary) } }.disposed(by: bag) if isEntityEmpty() { //call API only first time fetchDiaryList() } else { //get data from coredata let context = CoreDataStack.sharedInstance.persistentContainer.viewContext let records = fetchRecordsForEntity(Constant.entityName, inManagedObjectContext: context) self.diaryData.onNext(records) } } func fetchDiaryList() { activityIndicator.startAnimating() if Connectivity.isConnectedToInternet() { APIService().fetchData { (result) in self.activityIndicator.stopAnimating() switch result { case .Success(let data): self.clearData() self.saveInCoreDataWith(diary: data) case .Error(let message): DispatchQueue.main.async { print(message) } } } } else { self.activityIndicator.stopAnimating() UIAlertController.showAlert(self, message: UserMessage.NoInternet,title: Constant.networkError) } } } extension DiaryListViewController : UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } } //MARK:- Coredata method extension DiaryListViewController { private func isEntityEmpty() -> Bool { do { let context = CoreDataStack.sharedInstance.persistentContainer.viewContext let request = NSFetchRequest<NSFetchRequestResult>(entityName: Constant.entityName) let count = try context.count(for: request) return count == 0 } catch { return true } } private func fetchRecordsForEntity(_ entity: String, inManagedObjectContext managedObjectContext: NSManagedObjectContext) -> [NSManagedObject] { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity) do { let records = try managedObjectContext.fetch(fetchRequest) if let records = records as? [NSManagedObject] { return records } } catch { print("Unable to fetch managed objects for entity \(entity).") } return [] } private func clearData() { do { let context = CoreDataStack.sharedInstance.persistentContainer.viewContext let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: Diary.self)) do { let objects = try context.fetch(fetchRequest) as? [NSManagedObject] _ = objects.map{$0.map{context.delete($0)}} CoreDataStack.sharedInstance.saveContext() } catch let error { print("ERROR DELETING : \(error)") } } } private func saveInCoreDataWith(diary: [[String: AnyObject]]) { let diaries = diary.map{self.addIn(diary: $0 )} self.diaryData.onNext(diaries) do { try CoreDataStack.sharedInstance.persistentContainer.viewContext.save() } catch let error { print(error) } } private func addIn(diary: [String: AnyObject]) -> NSManagedObject { let context = CoreDataStack.sharedInstance.persistentContainer.viewContext if let diaryEntity = NSEntityDescription.insertNewObject(forEntityName: Constant.entityName, into: context) as? Diary { diaryEntity.id = diary[WSParams.id] as? String diaryEntity.title = diary[WSParams.title] as? String diaryEntity.content = diary[WSParams.content] as? String diaryEntity.date = diary[WSParams.date] as? String return diaryEntity } return NSManagedObject() } private func deleteDiary(diary: Diary) { do { let context = CoreDataStack.sharedInstance.persistentContainer.viewContext let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: Diary.self)) fetchRequest.predicate = NSPredicate(format: "\(WSParams.id) = %@",diary.id ?? "") do { let record = try context.fetch(fetchRequest) if let records = record as? [NSManagedObject] { if records.count > 0 { context.delete(records.first ?? NSManagedObject()) CoreDataStack.sharedInstance.saveContext() bindDiaryToTableview() } } } catch let error { print("ERROR DELETING : \(error)") } } } } extension DiaryListViewController: DiaryListActionDelegate { func edit(diary: Diary) { let editVC = EditDiaryViewController.instantiate(from: .Main) editVC.diary = diary self.navigationController?.pushViewController(editVC, animated: true) } func delete(diary: Diary) { UIAlertController.showAlertWithMultipleOption(self, message: UserMessage.deleteDiary, clickAction: { self.deleteDiary(diary: diary) }, cancelAction: {}) } }
// // API_TeamRate.swift // ETBAROON // // Created by imac on 10/16/17. // Copyright © 2017 IAS. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class API_TeamRate: NSObject { class func getTeamRate(fldAppTeamID:String , completion: @escaping (_ error: Error?, _ success: Bool, _ getTeamRate: tRate?)->Void) { let url = DomainInfo.getDomainUrl()+"Rating/apiAppGetTeamRating.php" let parameters: [String: Any] = [ "fldAppTeamID": fldAppTeamID ] Alamofire.request(url, method: .post, parameters:parameters, encoding: URLEncoding.default, headers: nil) //.validate(statusCode: 200..<300) .responseJSON { response in switch response.result { case .failure(let error): completion(error,false, nil) print(error) case .success(let value): let json = JSON(value) completion(nil, true,nil) print("----------------------------------") print(json) guard let data = json.dictionary else { completion(nil, false ,nil) return } if (data["fldAppTeamRating"] != nil){ let rate = tRate() rate.fldAppTeamRating = data["fldAppTeamRating"]?.string ?? "" completion(nil,true, rate) } else { completion(nil,false, nil) } } } } class func setTeamRate(fldAppUserID:String ,fldAppTeamID:String ,fldAppTeamRate:String , completion: @escaping (_ error: Error?, _ success: Bool, _ setTeamRate: res?)->Void) { let url = DomainInfo.getDomainUrl()+"Rating/apiAppSetTeamRating.php" let parameters: [String: Any] = [ "fldAppUserID": fldAppUserID , "fldAppTeamID": fldAppTeamID , "fldAppTeamRate": fldAppTeamRate ] Alamofire.request(url, method: .post, parameters:parameters, encoding: URLEncoding.default, headers: nil) //.validate(statusCode: 200..<300) .responseJSON { response in switch response.result { case .failure(let error): completion(error,false, nil) print(error) case .success(let value): let json = JSON(value) let resp = res() resp.message = json["message"].string ?? "" completion(nil, true, resp) print(json) } } } }
// // MenuTransitionManager.swift // LoLMyGame // // Created by Jack on 2/5/15. // Copyright (c) 2015 Jackson Jessup. All rights reserved. // import UIKit class MenuTransitionManager: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { private var presenting = false private let topRowOffset :CGFloat = 50 private let middleRowOffset :CGFloat = 150 private let bottomRowOffset :CGFloat = 300 internal let titleOffset = CGAffineTransformMakeTranslation(0, -50) internal func offStage(row: Int, neg:Bool) -> CGAffineTransform { var offset = topRowOffset if row == 1 { offset = middleRowOffset } else if row == 2 { offset = bottomRowOffset } if neg { offset = -offset } return CGAffineTransformMakeTranslation(offset, 0) } // MARK: UIViewControllerAnimatedTransitioning protocol methods // animate a change from one viewcontroller to another func animateTransition(transitionContext: UIViewControllerContextTransitioning) { // get reference to our fromView, toView and the container view that we should perform the transition in let container = transitionContext.containerView() // create a tuple of our screens let screens : (from:UIViewController, to:UIViewController) = (transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!, transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!) // assign references to our menu view controller and the 'bottom' view controller from the tuple // remember that our menuViewController will alternate between the from and to view controller depending if we're presenting or dismissing let menuViewController = !self.presenting ? screens.from as MenuVC : screens.to as MenuVC let bottomViewController = !self.presenting ? screens.to as UIViewController : screens.from as UIViewController let menuView = menuViewController.view let bottomView = bottomViewController.view // prepare the menu if (self.presenting){ menuView.alpha = 0 } // add the both views to our view controller container.addSubview(bottomView) container.addSubview(menuView) let duration = self.transitionDuration(transitionContext) // perform the animation! UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: nil, animations: { // either fade in or fade out if (self.presenting){ // fade in menuView.alpha = 1 // onstage items: slide in menuViewController.viwHeader.transform = CGAffineTransformIdentity menuViewController.btnRefreshImages.transform = CGAffineTransformIdentity menuViewController.btnAboutVersion.transform = CGAffineTransformIdentity menuViewController.btnSetRegion.transform = CGAffineTransformIdentity menuViewController.btnBugsAndErrors.transform = CGAffineTransformIdentity } else { // fade out menuView.alpha = 0 // onstage items: slide in menuViewController.viwHeader.transform = self.titleOffset menuViewController.btnRefreshImages.transform = self.offStage(0, neg:true) menuViewController.btnAboutVersion.transform = self.offStage(1, neg:true) menuViewController.btnSetRegion.transform = self.offStage(0, neg:false) menuViewController.btnBugsAndErrors.transform = self.offStage(1, neg:false) } }, completion: { finished in // tell our transitionContext object that we've finished animating transitionContext.completeTransition(true) // bug: we have to manually add our 'to view' back http://openradar.appspot.com/radar?id=5320103646199808 UIApplication.sharedApplication().keyWindow!.addSubview(screens.to.view) }) } // return how many seconds the transiton animation will take func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval { return 0.5 } // MARK: UIViewControllerTransitioningDelegate protocol methods // return the animataor when presenting a viewcontroller // rememeber that an animator (or animation controller) is any object that aheres to the UIViewControllerAnimatedTransitioning protocol func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = true return self } // return the animator used when dismissing from a viewcontroller func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = false return self } }
// // Utils.swift // iTunes Music Video Player // // Created by Gabriel on 23/05/2021. // import Foundation import UIKit extension UIColor { static let customWhite = UIColor(named: "customWhite") static let customBlack = UIColor(named: "customBlack") } @nonobjc extension UIViewController { func add(_ child: UIViewController) { addChild(child) view.addSubview(child.view) child.didMove(toParent: self) } func remove() { guard parent != nil else { return } willMove(toParent: nil) removeFromParent() view.removeFromSuperview() } }
// // Pets+CoreDataProperties.swift // // // Created by Julio Banda on 5/7/19. // // import Foundation import CoreData extension Pets { @nonobjc public class func fetchRequest() -> NSFetchRequest<Pets> { return NSFetchRequest<Pets>(entityName: "Pets") } @NSManaged public var name: String? @NSManaged public var kind: NSData? @NSManaged public var picture: String? @NSManaged public var dob: NSDate? @NSManaged public var owner: Friend? }
// // NetworkManager.swift // BucketList // // Created by Tino on 30/4/21. // import Foundation import Combine enum NetworkError: Error { case url, server(Error), response(URLResponse), decoding(Error) } func loadJSON<T>(from urlString: String, completion: @escaping (Result<T, NetworkError>) -> Void) where T: Decodable { guard let url = URL(string: urlString) else { completion(.failure(.url)) return } let task = URLSession.shared.dataTask(with: url) { data, response, error in if let error = error { DispatchQueue.main.async { completion(.failure(.server(error))) } return } if let data = data { let decoder = JSONDecoder() do { let decodedData = try decoder.decode(T.self, from: data) DispatchQueue.main.async { completion(.success(decodedData)) } return } catch { DispatchQueue.main.async { completion(.failure(.decoding(error))) } } } } task.resume() }
// // AppDelegate.swift // FastCommentLine // // Created by Eric Baker on 28Sep2016. // Copyright © 2016 DuneParkSoftware, LLC. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! }
// // InfoModel.swift // Movie // // Created by Levin Ivan on 25/09/2019. // Copyright © 2019 Levin Ivan. All rights reserved. // import UIKit import AVKit enum InfoModel { struct DisplayedInfo { var genreAndCountre: String? var originalTitle: String? var overview: String? var castMovie: [Cast]? var title: String? var voteAverage: Double? var colorOfRating: UIColor? var key: String? var castLabel: String? var posterPath: [URL]? var similarLabel: String? var trailerURL: URL? var backdropPath: URL? var similarMovie: [ResultSimilar]? enum ListUIMovie { case trailerURL(url: URL, offset: Int, backdropPath: URL) case title(title: String, offset: Int) case originalTitle(originalTitle: String, offset: Int) case genreAndCountre(genreAndCountre: String, offset: Int) case voteAverage(voteAverage: Double, offset: Int, color: UIColor) case overview(overview: String, offset: Int) case castLabel(castLabel: String, offset: Int) case castMovie(castMovie: [Cast], offset: Int) case similarLabel(similarLabel: String, offset: Int) case similarMovie(posterPath: [URL], offset: Int, similar: [ResultSimilar]) } } struct DisplayedSimilarInfo { var posterPath: [URL]? var similarMovie: [ResultSimilar]? } enum Fetching { struct Request { var movieID: Int } struct Response { var movie: FullMovieInfo } struct ViewModel { var displayedMovie: [DisplayedInfo.ListUIMovie] } } enum FetchingSimilar { struct Request { } struct Response { var similarMovie: [ResultSimilar] } struct ViewModel { var displayedMovie: DisplayedSimilarInfo } } enum StartLoading { struct Request { } struct Response { } struct ViewModel { } } enum StopLoading { struct Request { } struct Response { } struct ViewModel { } } }
// // FullNameCell.swift // TestTaskApp // // Created by Pavel Samsonov on 01.03.17. // Copyright © 2017 Pavel Samsonov. All rights reserved. // import UIKit class FullNameCell: UITableViewCell { @IBOutlet weak var title: UILabel! @IBOutlet weak var textView: UITextView! override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = .none } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
// // GroupService.swift // splitwork // // Created by Vivek Madhusudan Badrinarayan on 4/26/18. // Copyright © 2018 Vivek Badrinarayan. All rights reserved. // import Foundation import UIKit class GroupService { let httpService: HTTPService private static var sharedService: GroupService = { let service = GroupService() return service }() private init() { self.httpService = HTTPService.shared() print("GroupService initialized..") } class func shared() -> GroupService { return sharedService } func syncGroups(onSync: (() -> ())?) { Business.shared().groups?.clear() let completionHandler: (String, [String: Any]) -> () = { error, data in if(error != "") { print("Error in GroupService.suncGroups()") } else { if let groups = data["data"] as? [String: Any] { print("received groups from server, group count = \(groups.count)") for _group in groups { let group = _group.value as! [String: Any] let id = _group.key let name = group["name"] as! String let desc = group["desc"] as! String let adminUsername = group["adminUsername"] as! String var memberUsernames = [String]() if let _memberUsernames = group["memberUsernames"] as? [String: Any] { for _memberUsername in _memberUsernames { if let __memberUsername = _memberUsername.value as? [String: Any] { memberUsernames.append(__memberUsername["username"] as! String) } } } var taskIds = [String]() if let _taskIds = group["taskIds"] as? [String: Any] { print("_taskIds= \(_taskIds)") for _taskId in _taskIds { if let __taskId = _taskId.value as? [String: Any] { taskIds.append(__taskId["taskId"] as! String) } } } var billIds = [String]() if let _billIds = group["billIds"] as? [String: Any] { for _billId in _billIds { if let __billId = _billId.value as? [String: Any] { billIds.append(__billId["billId"] as! String) } } } // add group to model Business.shared().groups?.addGroup(id: id, name: name, desc: desc, adminUsername: adminUsername, memberUsernames: memberUsernames, taskIds: taskIds, billIds: billIds) } } } print("synced groups from server, group count = \((Business.shared().groups?.groups.count)!)") onSync?() } httpService.get(url: "groups", completionHandler: completionHandler) } func addGroup(name: String, desc: String, adminUsername: String, memberUsernames: [String]) { var group = [String: Any]() group["name"] = name group["desc"] = desc group["adminUsername"] = adminUsername let completionHandler: (String, [String: Any]) -> () = { error, data in if(error != "") { print("Error in adding group to firebase, error = \(error)") } else { print("Success in adding group to firebase") print("data = \(data)") if let res = data["data"] as? [String: Any] { if let groupId = res["name"] as? String { print("groupId = \(groupId)") self.addMemberToGroup(groupId: groupId, memberUsername: adminUsername) for memberUsername in memberUsernames { self.addMemberToGroup(groupId: groupId, memberUsername: memberUsername) } } } self.syncGroups(onSync: nil) } } httpService.post(url: "groups", data: group, completionHandler: completionHandler) } func addMemberToGroup(groupId: String, memberUsername: String) { var member = [String: Any]() member["username"] = memberUsername let completionHandler: (String, [String: Any]) -> () = { error, data in if(error != "") { print("Error adding member to group in firebase, error = \(error)") } else { print("Success in adding member to group in firebase") if let user = Business.shared().users?.getUser(username: memberUsername) { let userId = user.id // add group to user UserService.shared().addGroupToUser(userId: userId!, groupId: groupId) } self.syncGroups(onSync: nil) } } httpService.post(url: "groups/\(groupId)/memberUsernames", data: member, completionHandler: completionHandler) } func addTaskToGroup(groupId: String, taskId: String) { var task = [String: Any]() task["taskId"] = taskId let completionHandler: (String, [String: Any]) -> () = { error, data in if(error != "") { print("Error adding task to group in firebase, error = \(error)") } else { print("Success in adding task to group in firebase") self.syncGroups(onSync: nil) } } httpService.post(url: "groups/\(groupId)/taskIds", data: task, completionHandler: completionHandler) } func addBillToGroup(groupId: String, billId: String) { var bill = [String: Any]() bill["billId"] = billId let completionHandler: (String, [String: Any]) -> () = { error, data in if(error != "") { print("Error adding bill to group in firebase, error = \(error)") } else { print("Success in adding bill to group in firebase") self.syncGroups(onSync: nil) } } httpService.post(url: "groups/\(groupId)/billIds", data: bill, completionHandler: completionHandler) } }
// // matchesdetTVC.swift // LOL4YOU // // Created by Emanuel Root on 24/04/17. // Copyright © 2017 Emanuel Root. All rights reserved. // import UIKit import SVProgressHUD import GoogleMobileAds import FirebaseAnalytics class matchesdetTVC: UITableViewController, GADBannerViewDelegate{ let rt = rootclass.sharedInstance let admob = rootadmob.sharedInstance var matchdet = rootclass.BEMatch() var matchdetsmall = rootclass.BEMatchSmall() var sections = ["Winning Team","Losing Team"] let static_cell_rows_count = 9 override func viewDidLoad() { super.viewDidLoad() self.initAdMob() self.initView() } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { admob.addCountAdMobInterstitial(); if admob.showAdMobInterstitial() { if let adMobInterstitial = admob.getAdInterstitial() { adMobInterstitial.present(fromRootViewController: self) return } } switch indexPath.row { case (9...13): if let cell = tableView.cellForRow(at: indexPath) { let participant = matchdet.participants.filter{ p in p.participantId == cell.tag } let summoner = matchdet.participantsIdentities.filter{ p in p.participantId == cell.tag } if participant.count > 0 { let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "matchesstatsdet") as! matchesstatsdetTVC vc.participant = participant[0] if summoner.count > 0 { if summoner[0].summonerName.isEmpty { let champ = rt.listaChamp(id: participant[0].championId) vc.title = champ.name } else { vc.title = "\(summoner[0].summonerName)" } } self.navigationController?.pushViewController(vc, animated: true) } } default: print("ROOT - DEFAULT - DIDSELCT") } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let twinner = matchdet.teams.filter{p in p.win == "Win" } let tlosing = matchdet.teams.filter{p in p.win == "Fail" } switch indexPath.section { case 0: switch indexPath.row { case 0: //First Blood let cell = Bundle.main.loadNibNamed("infoTVCC", owner: self, options: nil)?.first as! infoTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none cell.item.text = "First Blood" if twinner.count > 0 { if twinner[0].firstBlood { cell.valor.text = "Yes" } else { cell.valor.text = "No" } } else { cell.valor.text = "No" } return cell case 1: //First Tower let cell = Bundle.main.loadNibNamed("infoTVCC", owner: self, options: nil)?.first as! infoTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none cell.item.text = "First Tower" if twinner.count > 0 { if twinner[0].firstTower { cell.valor.text = "Yes" } else { cell.valor.text = "No" } } else { cell.valor.text = "No" } return cell case 2: //First Baron let cell = Bundle.main.loadNibNamed("infoTVCC", owner: self, options: nil)?.first as! infoTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none cell.item.text = "First Baron" if twinner.count > 0 { if twinner[0].firstBaron { cell.valor.text = "Yes" } else { cell.valor.text = "No" } } else { cell.valor.text = "No" } return cell case 3: //First Dragon let cell = Bundle.main.loadNibNamed("infoTVCC", owner: self, options: nil)?.first as! infoTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none cell.item.text = "First Dragon" if twinner.count > 0 { if twinner[0].firstDragon { cell.valor.text = "Yes" } else { cell.valor.text = "No" } } else { cell.valor.text = "No" } return cell case 4: //Inhibitor Kills let cell = Bundle.main.loadNibNamed("infoTVCC", owner: self, options: nil)?.first as! infoTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none cell.item.text = "Inhibitor Kills" if twinner.count > 0 { cell.valor.text = "\(twinner[0].inhibitorKills)" } else { cell.valor.text = rt.const_zeros_s } return cell case 5: //Tower Kills let cell = Bundle.main.loadNibNamed("infoTVCC", owner: self, options: nil)?.first as! infoTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none cell.item.text = "Tower Kills" if twinner.count > 0 { cell.valor.text = "\(twinner[0].towerKills)" } else { cell.valor.text = rt.const_zeros_s } return cell case 6: //Baron Kills let cell = Bundle.main.loadNibNamed("infoTVCC", owner: self, options: nil)?.first as! infoTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none cell.item.text = "Baron Kills" if twinner.count > 0 { cell.valor.text = "\(twinner[0].baronKills)" } else { cell.valor.text = rt.const_zeros_s } return cell case 7: //Dragon Kills let cell = Bundle.main.loadNibNamed("infoTVCC", owner: self, options: nil)?.first as! infoTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none cell.item.text = "Dragon Kills" if twinner.count > 0 { cell.valor.text = "\(twinner[0].dragonKills)" } else { cell.valor.text = rt.const_zeros_s } return cell case 8: //Bans Champions let cell = Bundle.main.loadNibNamed("matchesdetbansTVCC", owner: self, options: nil)?.first as! matchesdetbansTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none if twinner.count > 0 { if twinner[0].bans.count > 0 { for i in 0 ..< twinner[0].bans.count { switch i { case 0: let champ = rt.listaChamp(id: twinner[0].bans[0].championId) cell.imgchamp1.sd_setImage(with: URL(string: "\(rootclass.images.champion)\(champ.imagefull)"), placeholderImage: UIImage(named: "static_null_all")) cell.imgchamp1.layer.borderWidth = 1 cell.imgchamp1.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_BRILHANTE.rawValue).cgColor case 1: let champ = rt.listaChamp(id: twinner[0].bans[1].championId) cell.imgchamp2.sd_setImage(with: URL(string: "\(rootclass.images.champion)\(champ.imagefull)"), placeholderImage: UIImage(named: "static_null_all")) cell.imgchamp2.layer.borderWidth = 1 cell.imgchamp2.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_BRILHANTE.rawValue).cgColor case 2: let champ = rt.listaChamp(id: twinner[0].bans[2].championId) cell.imgchamp3.sd_setImage(with: URL(string: "\(rootclass.images.champion)\(champ.imagefull)"), placeholderImage: UIImage(named: "static_null_all")) cell.imgchamp3.layer.borderWidth = 1 cell.imgchamp3.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_BRILHANTE.rawValue).cgColor case 3: let champ = rt.listaChamp(id: twinner[0].bans[3].championId) cell.imgchamp4.sd_setImage(with: URL(string: "\(rootclass.images.champion)\(champ.imagefull)"), placeholderImage: UIImage(named: "static_null_all")) cell.imgchamp4.layer.borderWidth = 1 cell.imgchamp4.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_BRILHANTE.rawValue).cgColor case 4: let champ = rt.listaChamp(id: twinner[0].bans[4].championId) cell.imgchamp5.sd_setImage(with: URL(string: "\(rootclass.images.champion)\(champ.imagefull)"), placeholderImage: UIImage(named: "static_null_all")) cell.imgchamp5.layer.borderWidth = 1 cell.imgchamp5.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_BRILHANTE.rawValue).cgColor default: continue } } } else { cell.imgchamp1.isHidden = true cell.imgchamp2.isHidden = true cell.imgchamp3.isHidden = true cell.imgchamp4.isHidden = true cell.imgchamp5.isHidden = true } } else { cell.imgchamp1.isHidden = true cell.imgchamp2.isHidden = true cell.imgchamp3.isHidden = true cell.imgchamp4.isHidden = true cell.imgchamp5.isHidden = true } return cell default: let cell = Bundle.main.loadNibNamed("matchesdetplayersTVCC", owner: self, options: nil)?.first as! matchesdetplayersTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none let tstats = matchdet.participants.filter{ p in p.stats.win == true } if tstats.count > 0 { if (indexPath.row - static_cell_rows_count) < tstats.count { let summoner = rt.listaChamp(id: tstats[indexPath.row - static_cell_rows_count].championId) let tsummonername = matchdet.participantsIdentities.filter{ p in p.participantId == tstats[indexPath.row - static_cell_rows_count].participantId } cell.tag = tstats[indexPath.row - static_cell_rows_count].participantId if tsummonername.count > 0 { if tsummonername[0].summonerName.isEmpty { cell.summonername.text = summoner.name } else { cell.summonername.text = tsummonername[0].summonerName } } cell.kda.text = "\(tstats[indexPath.row - static_cell_rows_count].stats.kills)/\(tstats[indexPath.row - static_cell_rows_count].stats.deaths)/\(tstats[indexPath.row - static_cell_rows_count].stats.assists)" cell.minions.text = "\(tstats[indexPath.row - static_cell_rows_count].stats.totalMinionsKilled + tstats[indexPath.row - static_cell_rows_count].stats.neutralMinionsKilled)" if tstats[indexPath.row - static_cell_rows_count].stats.goldEarned >= 1000 { cell.gold.text = String(format:"%.1f K", Double(tstats[indexPath.row - static_cell_rows_count].stats.goldEarned) / Double(1000)) } else { cell.gold.text = String(format:"%.1f K", Double(tstats[indexPath.row - static_cell_rows_count].stats.goldEarned)) } if tstats[indexPath.row - static_cell_rows_count].stats.champLevel > 0 { cell.imglvl.isHidden = false cell.lvl.isHidden = false cell.lvl.text = "\(tstats[indexPath.row - static_cell_rows_count].stats.champLevel)" cell.imglvl.backgroundColor = UIColor(hex: rootclass.colors.FUNDO.rawValue) cell.imglvl.layer.borderWidth = 1 cell.imglvl.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor } cell.imgchampion.sd_setImage(with: URL(string: summoner.imagelink), placeholderImage: UIImage(named: "static_null_all")) cell.imgchampion.layer.borderWidth = 2 cell.imgchampion.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_BRILHANTE.rawValue).cgColor cell.imgitem0.sd_setImage(with: URL(string: tstats[indexPath.row - static_cell_rows_count].stats.item0imagelink), placeholderImage: UIImage(named: "static_null")) cell.imgitem0.layer.borderWidth = 1 cell.imgitem0.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor cell.imgitem1.sd_setImage(with: URL(string: tstats[indexPath.row - static_cell_rows_count].stats.item1imagelink), placeholderImage: UIImage(named: "static_null")) cell.imgitem1.layer.borderWidth = 1 cell.imgitem1.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor cell.imgitem2.sd_setImage(with: URL(string: tstats[indexPath.row - static_cell_rows_count].stats.item2imagelink), placeholderImage: UIImage(named: "static_null")) cell.imgitem2.layer.borderWidth = 1 cell.imgitem2.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor cell.imgitem3.sd_setImage(with: URL(string: tstats[indexPath.row - static_cell_rows_count].stats.item3imagelink), placeholderImage: UIImage(named: "static_null")) cell.imgitem3.layer.borderWidth = 1 cell.imgitem3.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor cell.imgitem4.sd_setImage(with: URL(string: tstats[indexPath.row - static_cell_rows_count].stats.item4imagelink), placeholderImage: UIImage(named: "static_null")) cell.imgitem4.layer.borderWidth = 1 cell.imgitem4.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor cell.imgitem5.sd_setImage(with: URL(string: tstats[indexPath.row - static_cell_rows_count].stats.item5imagelink), placeholderImage: UIImage(named: "static_null")) cell.imgitem5.layer.borderWidth = 1 cell.imgitem5.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor cell.imgtrinket.sd_setImage(with: URL(string: tstats[indexPath.row - static_cell_rows_count].stats.item6imagelink), placeholderImage: UIImage(named: "static_null")) cell.imgtrinket.layer.borderWidth = 1 cell.imgtrinket.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor let spell1 = rt.listaSpeel(id: tstats[indexPath.row - static_cell_rows_count].spell1Id) cell.imgtlt0.sd_setImage(with: URL(string: "\(spell1.imagelink)"), placeholderImage: UIImage(named: "static_null")) cell.imgtlt0.layer.borderWidth = 1 cell.imgtlt0.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor let spell2 = rt.listaSpeel(id: tstats[indexPath.row - static_cell_rows_count].spell2Id) cell.imgtlt1.sd_setImage(with: URL(string: "\(spell2.imagelink)"), placeholderImage: UIImage(named: "static_null")) cell.imgtlt1.layer.borderWidth = 1 cell.imgtlt1.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor let masterys = tstats[indexPath.row - static_cell_rows_count].masterys let masteryf = masterys.filter{ if ($0.masteryId == 6161 || $0.masteryId == 6162 || $0.masteryId == 6164 || $0.masteryId == 6363 || $0.masteryId == 6362 || $0.masteryId == 6361 || $0.masteryId == 6263 || $0.masteryId == 6262 || $0.masteryId == 6261 ) { return true } else { return false } } if masteryf.count > 0 { let mastery = rt.listaMastery(id: masteryf[0].masteryId) cell.imgtltmast.sd_setImage(with: URL(string: "\(mastery.imagelink)"), placeholderImage: UIImage(named: "static_null")) cell.imgtltmast.layer.borderWidth = 1 cell.imgtltmast.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor } else { cell.imgtltmast.isHidden = true } } } return cell } case 1: switch indexPath.row { case 0: //First Blood let cell = Bundle.main.loadNibNamed("infoTVCC", owner: self, options: nil)?.first as! infoTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none cell.item.text = "First Blood" if tlosing.count > 0 { if tlosing[0].firstBlood { cell.valor.text = "Yes" } else { cell.valor.text = "No" } } else { cell.valor.text = "No" } return cell case 1: //First Tower let cell = Bundle.main.loadNibNamed("infoTVCC", owner: self, options: nil)?.first as! infoTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none cell.item.text = "First Tower" if tlosing.count > 0 { if tlosing[0].firstTower { cell.valor.text = "Yes" } else { cell.valor.text = "No" } } else { cell.valor.text = "No" } return cell case 2: //First Baron let cell = Bundle.main.loadNibNamed("infoTVCC", owner: self, options: nil)?.first as! infoTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none cell.item.text = "First Baron" if tlosing.count > 0 { if tlosing[0].firstBaron { cell.valor.text = "Yes" } else { cell.valor.text = "No" } } else { cell.valor.text = "No" } return cell case 3: //First Dragon let cell = Bundle.main.loadNibNamed("infoTVCC", owner: self, options: nil)?.first as! infoTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none cell.item.text = "First Dragon" if tlosing.count > 0 { if tlosing[0].firstDragon { cell.valor.text = "Yes" } else { cell.valor.text = "No" } } else { cell.valor.text = "No" } return cell case 4: //Inhibitor Kills let cell = Bundle.main.loadNibNamed("infoTVCC", owner: self, options: nil)?.first as! infoTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none cell.item.text = "Inhibitor Kills" if tlosing.count > 0 { cell.valor.text = "\(tlosing[0].inhibitorKills)" } else { cell.valor.text = rt.const_zeros_s } return cell case 5: //Tower Kills let cell = Bundle.main.loadNibNamed("infoTVCC", owner: self, options: nil)?.first as! infoTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none cell.item.text = "Tower Kills" if tlosing.count > 0 { cell.valor.text = "\(tlosing[0].towerKills)" } else { cell.valor.text = rt.const_zeros_s } return cell case 6: //Baron Kills let cell = Bundle.main.loadNibNamed("infoTVCC", owner: self, options: nil)?.first as! infoTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none cell.item.text = "Baron Kills" if tlosing.count > 0 { cell.valor.text = "\(tlosing[0].baronKills)" } else { cell.valor.text = rt.const_zeros_s } return cell case 7: //Dragon Kills let cell = Bundle.main.loadNibNamed("infoTVCC", owner: self, options: nil)?.first as! infoTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none cell.item.text = "Dragon Kills" if tlosing.count > 0 { cell.valor.text = "\(tlosing[0].dragonKills)" } else { cell.valor.text = rt.const_zeros_s } return cell case 8: //Bans Champions //Bans Champions let cell = Bundle.main.loadNibNamed("matchesdetbansTVCC", owner: self, options: nil)?.first as! matchesdetbansTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none if tlosing.count > 0 { if tlosing[0].bans.count > 0 { for i in 0 ..< tlosing[0].bans.count { switch i { case 0: let champ = rt.listaChamp(id: tlosing[0].bans[0].championId) cell.imgchamp1.sd_setImage(with: URL(string: "\(rootclass.images.champion)\(champ.imagefull)"), placeholderImage: UIImage(named: "static_null_all")) cell.imgchamp1.layer.borderWidth = 1 cell.imgchamp1.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_BRILHANTE.rawValue).cgColor case 1: let champ = rt.listaChamp(id: tlosing[0].bans[1].championId) cell.imgchamp2.sd_setImage(with: URL(string: "\(rootclass.images.champion)\(champ.imagefull)"), placeholderImage: UIImage(named: "static_null_all")) cell.imgchamp2.layer.borderWidth = 1 cell.imgchamp2.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_BRILHANTE.rawValue).cgColor case 2: let champ = rt.listaChamp(id: tlosing[0].bans[2].championId) cell.imgchamp3.sd_setImage(with: URL(string: "\(rootclass.images.champion)\(champ.imagefull)"), placeholderImage: UIImage(named: "static_null_all")) cell.imgchamp3.layer.borderWidth = 1 cell.imgchamp3.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_BRILHANTE.rawValue).cgColor case 3: let champ = rt.listaChamp(id: tlosing[0].bans[3].championId) cell.imgchamp4.sd_setImage(with: URL(string: "\(rootclass.images.champion)\(champ.imagefull)"), placeholderImage: UIImage(named: "static_null_all")) cell.imgchamp4.layer.borderWidth = 1 cell.imgchamp4.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_BRILHANTE.rawValue).cgColor case 4: let champ = rt.listaChamp(id: tlosing[0].bans[4].championId) cell.imgchamp5.sd_setImage(with: URL(string: "\(rootclass.images.champion)\(champ.imagefull)"), placeholderImage: UIImage(named: "static_null_all")) cell.imgchamp5.layer.borderWidth = 1 cell.imgchamp5.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_BRILHANTE.rawValue).cgColor default: continue } } } else { cell.imgchamp1.isHidden = true cell.imgchamp2.isHidden = true cell.imgchamp3.isHidden = true cell.imgchamp4.isHidden = true cell.imgchamp5.isHidden = true } } else { cell.imgchamp1.isHidden = true cell.imgchamp2.isHidden = true cell.imgchamp3.isHidden = true cell.imgchamp4.isHidden = true cell.imgchamp5.isHidden = true } return cell default: let cell = Bundle.main.loadNibNamed("matchesdetplayersTVCC", owner: self, options: nil)?.first as! matchesdetplayersTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none let tstats = matchdet.participants.filter{ p in p.stats.win == false } if tstats.count > 0 { if (indexPath.row - static_cell_rows_count) < tstats.count { let summoner = rt.listaChamp(id: tstats[indexPath.row - static_cell_rows_count].championId) let tsummonername = matchdet.participantsIdentities.filter{ p in p.participantId == tstats[indexPath.row - static_cell_rows_count].participantId } cell.tag = tstats[indexPath.row - static_cell_rows_count].participantId if tsummonername.count > 0 { if tsummonername[0].summonerName.isEmpty { cell.summonername.text = summoner.name } else { cell.summonername.text = tsummonername[0].summonerName } } cell.kda.text = "\(tstats[indexPath.row - static_cell_rows_count].stats.kills)/\(tstats[indexPath.row - static_cell_rows_count].stats.deaths)/\(tstats[indexPath.row - static_cell_rows_count].stats.assists)" cell.minions.text = "\(tstats[indexPath.row - static_cell_rows_count].stats.totalMinionsKilled + tstats[indexPath.row - static_cell_rows_count].stats.neutralMinionsKilled)" if tstats[indexPath.row - static_cell_rows_count].stats.goldEarned >= 1000 { cell.gold.text = String(format:"%.1f K", Double(tstats[indexPath.row - static_cell_rows_count].stats.goldEarned) / Double(1000)) } else { cell.gold.text = String(format:"%.1f K", Double(tstats[indexPath.row - static_cell_rows_count].stats.goldEarned)) } if tstats[indexPath.row - static_cell_rows_count].stats.champLevel > 0 { cell.imglvl.isHidden = false cell.lvl.isHidden = false cell.lvl.text = "\(tstats[indexPath.row - static_cell_rows_count].stats.champLevel)" cell.imglvl.backgroundColor = UIColor(hex: rootclass.colors.FUNDO.rawValue) cell.imglvl.layer.borderWidth = 1 cell.imglvl.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor } cell.imgchampion.sd_setImage(with: URL(string: summoner.imagelink), placeholderImage: UIImage(named: "static_null_all")) cell.imgchampion.layer.borderWidth = 2 cell.imgchampion.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_BRILHANTE.rawValue).cgColor cell.imgitem0.sd_setImage(with: URL(string: tstats[indexPath.row - static_cell_rows_count].stats.item0imagelink), placeholderImage: UIImage(named: "static_null")) cell.imgitem0.layer.borderWidth = 1 cell.imgitem0.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor cell.imgitem1.sd_setImage(with: URL(string: tstats[indexPath.row - static_cell_rows_count].stats.item1imagelink), placeholderImage: UIImage(named: "static_null")) cell.imgitem1.layer.borderWidth = 1 cell.imgitem1.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor cell.imgitem2.sd_setImage(with: URL(string: tstats[indexPath.row - static_cell_rows_count].stats.item2imagelink), placeholderImage: UIImage(named: "static_null")) cell.imgitem2.layer.borderWidth = 1 cell.imgitem2.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor cell.imgitem3.sd_setImage(with: URL(string: tstats[indexPath.row - static_cell_rows_count].stats.item3imagelink), placeholderImage: UIImage(named: "static_null")) cell.imgitem3.layer.borderWidth = 1 cell.imgitem3.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor cell.imgitem4.sd_setImage(with: URL(string: tstats[indexPath.row - static_cell_rows_count].stats.item4imagelink), placeholderImage: UIImage(named: "static_null")) cell.imgitem4.layer.borderWidth = 1 cell.imgitem4.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor cell.imgitem5.sd_setImage(with: URL(string: tstats[indexPath.row - static_cell_rows_count].stats.item5imagelink), placeholderImage: UIImage(named: "static_null")) cell.imgitem5.layer.borderWidth = 1 cell.imgitem5.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor cell.imgtrinket.sd_setImage(with: URL(string: tstats[indexPath.row - static_cell_rows_count].stats.item6imagelink), placeholderImage: UIImage(named: "static_null")) cell.imgtrinket.layer.borderWidth = 1 cell.imgtrinket.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor let spell1 = rt.listaSpeel(id: tstats[indexPath.row - static_cell_rows_count].spell1Id) cell.imgtlt0.sd_setImage(with: URL(string: "\(spell1.imagelink)"), placeholderImage: UIImage(named: "static_null")) cell.imgtlt0.layer.borderWidth = 1 cell.imgtlt0.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor let spell2 = rt.listaSpeel(id: tstats[indexPath.row - static_cell_rows_count].spell2Id) cell.imgtlt1.sd_setImage(with: URL(string: "\(spell2.imagelink)"), placeholderImage: UIImage(named: "static_null")) cell.imgtlt1.layer.borderWidth = 1 cell.imgtlt1.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor let masterys = tstats[indexPath.row - static_cell_rows_count].masterys let masteryf = masterys.filter{ if ($0.masteryId == 6161 || $0.masteryId == 6162 || $0.masteryId == 6164 || $0.masteryId == 6363 || $0.masteryId == 6362 || $0.masteryId == 6361 || $0.masteryId == 6263 || $0.masteryId == 6262 || $0.masteryId == 6261 ) { return true } else { return false } } if masteryf.count > 0 { let mastery = rt.listaMastery(id: masteryf[0].masteryId) cell.imgtltmast.sd_setImage(with: URL(string: "\(mastery.imagelink)"), placeholderImage: UIImage(named: "static_null")) cell.imgtltmast.layer.borderWidth = 1 cell.imgtltmast.layer.borderColor = UIColor(hex: rootclass.colors.BORDA_OFUSCADA.rawValue).cgColor } else { cell.imgtltmast.isHidden = true } } } return cell } default: let cell = Bundle.main.loadNibNamed("infoTVCC", owner: self, options: nil)?.first as! infoTVCC cell.selectionStyle = UITableViewCellSelectionStyle.none return cell } } override func numberOfSections(in tableView: UITableView) -> Int { return sections.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 14 case 1: return 14 default: return 0 } } override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if section == 0 { view.backgroundColor = UIColor(hex: rootclass.colors.TEXTO_VITORIA.rawValue) } else { view.backgroundColor = UIColor(hex: rootclass.colors.TEXTO_DERROTA.rawValue) } } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let cell = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: "headerTVH") let cheader = cell as! headerTVH if section == 0 { cheader.header.text = sections[section] cheader.contentView.backgroundColor = UIColor(hex: rootclass.colors.TEXTO_VITORIA.rawValue) cheader.header.backgroundColor = UIColor(hex: rootclass.colors.TEXTO_VITORIA.rawValue) cheader.contentView.backgroundColor = UIColor(hex: rootclass.colors.TEXTO_VITORIA.rawValue) cell?.backgroundView?.backgroundColor = UIColor(hex: rootclass.colors.TEXTO_VITORIA.rawValue) cell?.backgroundColor = UIColor(hex: rootclass.colors.TEXTO_VITORIA.rawValue) } else { cheader.header.text = sections[section] cheader.contentView.backgroundColor = UIColor(hex: rootclass.colors.TEXTO_DERROTA.rawValue) cheader.header.backgroundColor = UIColor(hex: rootclass.colors.TEXTO_DERROTA.rawValue) cheader.contentView.backgroundColor = UIColor(hex: rootclass.colors.TEXTO_DERROTA.rawValue) cell?.backgroundView?.backgroundColor = UIColor(hex: rootclass.colors.TEXTO_DERROTA.rawValue) cell?.backgroundColor = UIColor(hex: rootclass.colors.TEXTO_DERROTA.rawValue) } return cheader } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch indexPath.section { case 0: switch indexPath.row { case (0...7): return 44 case 8: return 55 default: return 95 } case 1: switch indexPath.row { case (0...7): return 44 case 8: return 55 default: return 95 } default: return 0 } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "." } func initView(){ let attnav = [ NSAttributedStringKey.foregroundColor: UIColor(hex:rootclass.colors.TEXTO_TOP_BAR.rawValue), NSAttributedStringKey.font: UIFont(name: "Friz Quadrata TT", size: 17)! ] let button = UIButton.init(type: .custom) button.setImage(UIImage(named:"static_button_back"), for: UIControlState.normal) button.addTarget(self, action:#selector(spopViewController), for: UIControlEvents.touchUpInside) button.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30) let barButton = UIBarButtonItem.init(customView: button) self.navigationItem.leftBarButtonItem = barButton let nib = UINib(nibName: "headerTVH", bundle: nil) tableView.register(nib, forHeaderFooterViewReuseIdentifier: "headerTVH") self.navigationController?.navigationBar.barTintColor = UIColor(hex: rootclass.colors.FUNDO.rawValue) self.navigationController?.navigationBar.titleTextAttributes = attnav self.title = "Match Details" } func initAdMob() { Analytics.setScreenName(rootclass.screens.matchesdet, screenClass: String(describing: matchesdetTVC.self)) if rt.viewbanner { let adBannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait) adBannerView.adUnitID = rootadmob.admob.admob_banner adBannerView.delegate = self adBannerView.rootViewController = self adBannerView.load(GADRequest()) self.tableView.tableHeaderView = adBannerView } } @objc func spopViewController(){ self.navigationController?.popViewController(animated: true) } }
// // BreadcrumbStore.swift // SentrySwift // // Created by Josh Holtz on 3/29/16. // // import Foundation @objc public class BreadcrumbStore: NSObject { private var crumbs = [String: [Breadcrumb]]() private var _maxCrumbsForType = 20 public var maxCrumbsForType: Int { get { return _maxCrumbsForType } set { _maxCrumbsForType = max(0, newValue) } } public typealias StoreUpdated = (BreadcrumbStore) -> () public var storeUpdated: StoreUpdated? public func add(crumb: Breadcrumb) { var typedCrumbs = crumbs[crumb.type] ?? [] typedCrumbs.insert(crumb, atIndex: 0) if typedCrumbs.count > maxCrumbsForType { typedCrumbs = Array(typedCrumbs[0..<maxCrumbsForType]) } crumbs[crumb.type] = typedCrumbs storeUpdated?(self) } public func get(type: String) -> [Breadcrumb]? { return crumbs[type] } public func clear(type: String? = nil) { if let type = type { crumbs.removeValueForKey(type) } else { crumbs.removeAll() } storeUpdated?(self) } } extension BreadcrumbStore: EventSerializable { public typealias SerializedType = SerializedTypeArray public var serialized: SerializedType { return crumbs.values.flatMap{$0.map{$0.serialized}}.flatMap{$0} } }
struct BetaReviewInfo { }
// // LandingViewController.swift // UserInterface // // Created by Fernando Moya de Rivas on 01/09/2019. // Copyright © 2019 Fernando Moya de Rivas. All rights reserved. // import UIKit class LandingViewController: UIViewController, Bindable { @IBOutlet weak var goButton: UIButton! { didSet { goButton.layer.cornerRadius = goButton.bounds.width / 2 goButton.layer.borderWidth = 2 goButton.layer.borderColor = UIColor.white.cgColor goButton.layer.masksToBounds = true } } @IBAction func userDidTapGo(_ sender: UIButton) { viewModel.goDidTap(sender: sender) } var viewModel: LandingViewModel init(viewModel: LandingViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: Bundle(for: type(of: self))) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func bindViewModel() { } }
// // Step4ViewController.swift // Gulp // // Created by Max on 5/28/15. // Copyright (c) 2015 Laurax Studios. All rights reserved. // import UIKit var selectedDrink: String = "" var sizeSelection: Int = 0 class Step4ViewController: UIViewController { @IBOutlet weak var drinknamecontainer: UILabel! @IBOutlet weak var barButton1: UIButton! @IBOutlet weak var barButton2: UIButton! @IBOutlet weak var barButton3: UIButton! @IBOutlet weak var childrenSizeButton: UIButton! @IBOutlet weak var xlargeSizeButton: UIButton! @IBOutlet weak var smallSizeButton: UIButton! @IBOutlet weak var mediumSizeButton: UIButton! @IBOutlet weak var largeSizeButton: UIButton! var choice1: Int? var choice2: Int? var choice3: Int? var barButton1String: String? var barButton2String: String? var barButton3String: String? var finalDrinkArray: [AnyObject?] = [] var counter: Int = 0 let normalLibrary = NormalMenuLibrary().library override func viewDidLoad() { super.viewDidLoad() childrenSizeButton.layer.borderWidth = 2.0 xlargeSizeButton.layer.borderWidth = 2.0 smallSizeButton.layer.borderWidth = 2.0 mediumSizeButton.layer.borderWidth = 2.0 largeSizeButton.layer.borderWidth = 2.0 barButton1.setTitle(barButton1String!, forState: UIControlState.Normal) barButton2.setTitle(barButton2String!, forState: UIControlState.Normal) barButton3.setTitle(barButton3String!, forState: UIControlState.Normal) //Generate drink array for drink in normalLibrary { if let selection = drink["selector"] as? [Int] { for category in selection { if category == choice1! || category == choice2! || category == choice3! { ++counter } // if category } //for category } //if let if counter == 3 { finalDrinkArray.append(drink) } counter = 0 } //for drink drinknamecontainer.text = randomdrinkselector(finalDrinkArray) } func randomdrinkselector (drinkarray: [AnyObject?]) -> String { //Get random drink and print to slot //get size of finalDrinkArray //use size to generate random number //use random number to extract drink from finalDrinkArray let randomIndex = Int(arc4random_uniform(UInt32(drinkarray.count))) let finaldrink = drinkarray[randomIndex]!["name"]!! as? String return finaldrink! } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func showanother(sender: AnyObject) { drinknamecontainer.text = randomdrinkselector(finalDrinkArray) } @IBAction func showanotherswipe(sender: UISwipeGestureRecognizer) { drinknamecontainer.text = randomdrinkselector(finalDrinkArray) print("worked") } @IBAction func sizeSelectionNextScreen(sender: AnyObject) { performSegueWithIdentifier("fourFiveSegue", sender: sender) selectedDrink = drinknamecontainer.text! sizeSelection = sender.tag } @IBAction func unwindToStep4Segue (segue : UIStoryboardSegue) {} }
// // Movie.swift // MovieEnvoy // // Created by Jerry Edens on 11/14/18. // Copyright © 2018 Edens R&D. All rights reserved. // import Foundation final class MovieSummary: Decodable { let id: Int let adult: Bool? let backdropPath: String? let title: String? let overview: String? let posterPath: String? let releaseDate: String? let voteAverage: Double? let voteCount: Int? } extension MovieSummary: CustomDebugStringConvertible { var debugDescription: String { return """ Movie: id: \(id) title: \(title ?? "No Title") """ } }
// // QueueProblems.swift // QueuesHWProblems // // Created by C4Q on 11/1/16. // Copyright © 2016 C4Q . All rights reserved. // import Foundation //In all problems, the input queue should be in its original state after your function is done running. //Find the sum of a queue func sum(q: Queue<Int>) -> Int? { guard !q.isEmpty() else { return nil } let newQ = Queue<Int>() var sum = 0 while !q.isEmpty() { let tempNum = q.deQueue()! newQ.enQueue(newElement: tempNum) sum += tempNum } while !newQ.isEmpty() { q.enQueue(newElement: newQ.deQueue()!) } return sum } //Find the smallest element in a queue func smallest<T:Comparable>(q: Queue<T>) -> T? { guard !q.isEmpty() else { return nil } let newQ = Queue<T>() var smallest = q.peek()! while !q.isEmpty() { let tempElement = q.deQueue()! newQ.enQueue(newElement: tempElement) if tempElement < smallest { smallest = tempElement } } while !newQ.isEmpty() { q.enQueue(newElement: newQ.deQueue()!) } return smallest } //Find out whether or not a queue is in sorted order from smallest to biggest //True example: (Back) 9 - 6 - 2 - 1 (Front) //False example (Back) 4 - 19 - 134 200 (Front) func isSorted<T: Comparable>(q: Queue<T>) -> Bool? { guard !q.isEmpty() else { return nil } let newQ = Queue<T>() var sorted = true while !q.isEmpty() { let tempElement = q.deQueue()! newQ.enQueue(newElement: tempElement) if let nextElement = q.peek () { if tempElement > nextElement { sorted = false break } } } while !newQ.isEmpty() { q.enQueue(newElement: newQ.deQueue()!) } return sorted } //Return a reversed queue. func reverse<T>(q: Queue<T>) -> Queue<T> { guard !q.isEmpty() else { return Queue<T>() } let newQ = Queue<T>() let tempStack = Stack<T>() while !q.isEmpty() { let tempElement = q.deQueue()! newQ.enQueue(newElement: tempElement) tempStack.push(element: tempElement) } var reversedQueue = Queue<T>() while !tempStack.isEmpty() { reversedQueue.enQueue(newElement: tempStack.pop()!) q.enQueue(newElement: newQ.deQueue()!) } return reversedQueue } //Determine if two queues are equal. func areEqual<T: Equatable>(qOne: Queue<T>, qTwo: Queue<T>) -> Bool { if qOne === qTwo { return true } let q1 = Queue<T>() let q2 = Queue<T>() var isEqual = true while !qOne.isEmpty() || !qTwo.isEmpty() { if qOne.isEmpty() || qTwo.isEmpty() { isEqual = false break } let tempElement1 = qOne.deQueue()! let tempElement2 = qTwo.deQueue()! q1.enQueue(newElement: tempElement1) q2.enQueue(newElement: tempElement2) if tempElement1 != tempElement2 { isEqual = false break } } while !q1.isEmpty() || !q2.isEmpty() { if !q1.isEmpty() { qOne.enQueue(newElement: q1.deQueue()!) } if !q2.isEmpty() { qTwo.enQueue(newElement: q2.deQueue()!) } } return isEqual } //Bonus: Hot Potato //https://interactivepython.org/runestone/static/pythonds/BasicDS/SimulationHotPotato.html
// // SendMessageButton.swift // TinderLikeSwipeAnimation // // Created by krAyon on 24.12.18. // Copyright © 2018 DocDevs. All rights reserved. // import UIKit class SendMessageButton: UIButton { override func draw(_ rect: CGRect) { super.draw(rect) let gradientLayer = CAGradientLayer() let leftColor = #colorLiteral(red: 0.9215686275, green: 0.3019607843, blue: 0.2941176471, alpha: 1), rightColor = #colorLiteral(red: 0.1921568662, green: 0.007843137719, blue: 0.09019608051, alpha: 1) gradientLayer.colors = [leftColor.cgColor, rightColor.cgColor] gradientLayer.startPoint = CGPoint(x: 0, y: 0.5) gradientLayer.endPoint = CGPoint(x: 1, y: 0.5) layer.cornerRadius = rect.height / 2 clipsToBounds = true gradientLayer.frame = rect self.layer.insertSublayer(gradientLayer, at: 0) } }
// // IjomeCollectionViewCell.swift // IjomeMessage // // Created by Benny Pollak on 10/13/18. // Copyright © 2018 Alben Software. All rights reserved. // import UIKit import Messages class IjomeCollectionViewCell: UICollectionViewCell { @IBOutlet weak var image: UIImageView! @IBOutlet weak var captionLbl: UILabel! @IBOutlet weak var stickerView: MSStickerView! }
// // AddPhotoCell.swift // GardenCoceral // // Created by TongNa on 2018/4/14. // Copyright © 2018年 tongna. All rights reserved. // import UIKit import Reusable import ImagePicker import SKPhotoBrowser class AddPhotoCell: UITableViewCell, Reusable { var photo = UIImageView() var backImg: ((String)->())? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) _ = photo.then{ contentView.addSubview($0) $0.snp.makeConstraints({ (m) in m.top.equalTo(25) m.left.equalTo(60) m.right.equalTo(-60) m.height.equalTo(photo.snp.width).dividedBy(1.67) m.bottom.equalTo(-25) }) $0.contentMode = .scaleAspectFill $0.clipsToBounds = true let tap = UITapGestureRecognizer(target: self, action: #selector(uploadFile)) $0.addGestureRecognizer(tap) $0.isUserInteractionEnabled = true } setData() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension AddPhotoCell { func setData() { photo.image = #imageLiteral(resourceName: "member-upload") } @objc func uploadFile() { alertPicker() } func alertPicker() { var configuration = Configuration() configuration.cancelButtonTitle = "取消" configuration.doneButtonTitle = "完成" configuration.noImagesTitle = "貌似还没有图片哦!" configuration.recordLocation = false let imagePickerController = ImagePickerController(configuration: configuration) imagePickerController.delegate = self imagePickerController.imageLimit = 1 parentViewController?.present(imagePickerController, animated: true, completion: nil) } } extension AddPhotoCell: ImagePickerDelegate { func wrapperDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) { guard images.count != 0 else { return } let photos = images.map{ return SKPhoto.photoWithImage($0) } SKPhotoBrowserOptions.enableSingleTapDismiss = true let brower = SKPhotoBrowser(photos: photos, initialPageIndex: 0) imagePicker.present(brower, animated: true, completion: nil) } func doneButtonDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) { imagePicker.dismiss(animated: true, completion: nil) if let imgData = UIImageJPEGRepresentation(images[0], 0.1) { let fullPath = NSHomeDirectory() + "/Documents/\(Date().timeIntervalSince1970).jpg" let url = URL(fileURLWithPath: fullPath) do { try imgData.write(to: url, options: .atomic) Log(fullPath) if let backImg = self.backImg { backImg(fullPath) } } catch { Log(error) } } photo.image = images[0] } func cancelButtonDidPress(_ imagePicker: ImagePickerController) { imagePicker.dismiss(animated: true, completion: nil) } }
// // AcronymsMockService.swift // AcronymsTests // // Created by Douglas Poveda on 28/04/21. // import Foundation @testable import Acronyms final class AcronymsMockService: AcronymsService { var acronyms = [Acronym(sf: "usa", lfs: [Meaning(lf: "Us Son At", freq: 145, since: 1946, vars: nil)])] func getAcronyms(parameters: GetAcronymsParameters, completion: @escaping GetAcronymsHandler) { let match = self.acronyms.contains { acronym in acronym.sf == parameters.keyword.lowercased() } if match { completion(.success(acronyms)) } else { completion(.failure(.unexpectedError)) } } }
// // SecViewController.swift // LoverApp // // Created by sky on 2016/7/27. // Copyright © 2016年 sky. All rights reserved. // import UIKit class SecViewController: UIViewController { var name:String! var sign:String! var girlImage:String! var loverNumber:Int! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var signLabel: UILabel! @IBOutlet weak var imageforgirl: UIImageView! @IBAction func pressedEditButton(_ sender: AnyObject) { } func upload(noti:Notification){ let newname = noti.userInfo!["name"] as! String let newsign = noti.userInfo!["sign"] as! String self.name = newname //這二個name、sign屬性要建立,否則無法更新資料 self.sign = newsign self.nameLabel.text = newname self.signLabel.text = newsign //self.imageforgirl.image = UIImage(named: NewImage) } override func viewDidLoad() { super.viewDidLoad() if let newname = name{ nameLabel.text = newname //self.title = newname } if let newsign = sign{ signLabel.text = newsign } if let newImage = girlImage{ imageforgirl.image = UIImage(named: newImage)//少了這行,圖片不會出現。 } let NotiName = Notification.Name("update") NotificationCenter.default.addObserver(self, selector: #selector(upload(noti:)), name: NotiName, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) { let controller = segue.destination as! EditViewController controller.name = name controller.sign = sign controller.loverNumber = loverNumber //controller.girlImage = girlImage }//將值傳回下一頁文字框的連結 }
// // Group_Messages+CoreDataClass.swift // witOrbit // // Created by ZainAnjum on 24/02/2018. // Copyright © 2018 Gul Mehru. All rights reserved. // // import Foundation import CoreData @objc(Group_Messages) public class Group_Messages: NSManagedObject { }
// // AKActualTableViewController.swift // TortyMozyrApp // // Created by Саша Капчук on 3.04.21. // import UIKit class AKActualTableViewController: UITableViewController { // MARK: - variables private var images = [ UIImage(named: "bigFruitCakeImage"), UIImage(named: "cupcakeImage"), UIImage(named: "fruitCakeImage"), UIImage(named: "krasniyBarhatImage") ] private var titles = [ "На большой праздник", "Ко дню учителя", "Ко дню рождения", "Неизменная классика" ] private var descriptions = [ "Чтобы удивить всех и немного удивиться самому!", "Вкусный подарок для любимого преподавателя.", "Раз в году можно побаловать себя чем-то по-настоящему вкусным!", "То, что никогда не подводит." ] // MARK: - app life cycle override func viewDidLoad() { super.viewDidLoad() self.title = "Actual".localized self.view.backgroundColor = .white self.tableView.separatorStyle = .none self.tableView.showsVerticalScrollIndicator = false self.tableView.register(AKActualCell.self, forCellReuseIdentifier: AKActualCell.reuseIdentifier) } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.images.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: AKActualCell.reuseIdentifier, for: indexPath) if let cell = cell as? AKActualCell { cell.setCellData(image: self.images[indexPath.row] ?? #imageLiteral(resourceName: "blackberryCakeImage"), imageName: self.titles[indexPath.row], imageDescription: self.descriptions[indexPath.row]) cell.showPage = { [weak self] in self?.navigationController?.pushViewController(AKSorryPageViewController(), animated: true) } } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.navigationController?.pushViewController(AKSorryPageViewController(), animated: true) } }
// // FabricaRepositorios.swift // hubAPS // // Created by Ian Manor on 9/27/16. // Copyright © 2016 Hilton Pintor Bezerra Leite. All rights reserved. // import Foundation protocol FabricaRepositoriosAbstrata { func criarRepositorioContas() -> IRepositorioContas func criarRepositorioItens() -> IRepositorioItens func criarRepositorioTrocas() -> IRepositorioTrocas }
// // SearchRouter.swift // Uala // // Created by Miguel Angel Olmedo Perez on 02/03/21. // import Foundation import UIKit final class SearchRouter: RouterProtocol { internal weak var viewController: UIViewController? required init(viewController: UIViewController) { self.viewController = viewController } func pushToDetail(with id: String) { let context = Context() let dataSource = DetailViewModelDataSource(context: context, id: id) push(viewController: DetailBuilder.build(with: dataSource)) } }
// // responseViewController.swift // Roshambo // // Created by Shakil Kanji on 2015-07-29. // Copyright (c) 2015 Shakil Kanji. All rights reserved. // import UIKit class responseViewController: UIViewController { var comValue: Int? var humanValue: Int? @IBOutlet weak var resultStatement: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { if humanValue == comValue { self.resultStatement.text = "It's a tie!" } else if (humanValue == 3 && comValue == 1) { self.resultStatement.text = "Rock crushed scissors. Com Wins!" } else if (humanValue > comValue) { self.resultStatement.text = "Human Wins!" } else { self.resultStatement.text = "Com Wins!" } } @IBAction func dismiss(sender: UIButton) { self.dismissViewControllerAnimated(true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // AppDelegate.swift // MyLoqta // // Created by Ashish Chauhan on 03/07/18. // Copyright © 2018 AppVenturez. All rights reserved. // /* 201, 199 191 222 */ import UIKit import FBSDKCoreKit import Firebase import GoogleSignIn import AWSCore import SwiftyUserDefaults import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { //http://www.myloqta.com/resetPassword/69/Xh9CVhpgNRmKooUr7gkristI5XL7l2gd var window: UIWindow? class var delegate: AppDelegate { return UIApplication.shared.delegate as! AppDelegate } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. GIDSignIn.sharedInstance().clientID = "896283309594-j2chiu194sr7eoptcph6a11sf07akbng.apps.googleusercontent.com" FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) self.registerForPushNotifications(application: application) self.checkUserStatus() //self.showHome() // self.checkUserStatus() self.initializeS3() if let option = launchOptions, let url = option[UIApplicationLaunchOptionsKey.url] as? URL { self.handleDeepLinking(url: url) } return true } func initializeS3() { let poolId = "us-east-1:b1f250f2-66a7-4d07-96e9-01817149a439" let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: poolId) let configuration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: credentialsProvider) AWSServiceManager.default().defaultServiceConfiguration = configuration TAS3Manager.sharedInst.createS3Folder() } @available(iOS 9.0, *) func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool { if url.absoluteString.hasSubString("myloqta") { return self.application(application, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: [:]) } return GIDSignIn.sharedInstance().handle(url, sourceApplication:options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: [:]) } //- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { //<a href="myloqta://seller/14">Click here to switch to app OR on page load</a> //<a href="myloqta://product/20">Click here to switch to app OR on page loadp</a> if url.absoluteString.hasSubString("myloqta") { self.handleDeepLinking(url: url) return true } return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation) } //http://www.myloqta.com/resetPassword/69/Xh9CVhpgNRmKooUr7gkristI5XL7l2gd //http://www.myloqta.com/SellerDeeplink/product/id //http://appinventive.com:8194/deeplinkForget?token=Xh9CVhpgNRmKooUr7gkristI5XL7l2gd&userId=69 func handleDeepLinking(url: URL) { let urlStr = url.absoluteString let array = urlStr.components(separatedBy: "/") let arrayCount = array.count if arrayCount >= 3 { let resetPass = array[(arrayCount - 3)] if resetPass == "resetPassword" { let idValue = array[(arrayCount - 2)] let token = array[(arrayCount - 1)] self.deepLinkingResetPassword(userId: idValue, token: token) return } } if arrayCount >= 2 { let idValue = array[(arrayCount - 1)] let pushType = array[(arrayCount - 2)] self.deepLinking(idValue: idValue, isSeller: (pushType == "seller")) } } func deepLinking(idValue: String, isSeller: Bool) { if let topVC = Helper.topMostViewController(rootViewController: Helper.rootViewController()) { if isSeller { if let sellerProfileVC = DIConfigurator.sharedInst().getSellerProfileVC(), let storeId = Int(idValue) { //sellerProfileVC.isSelfProfile = false sellerProfileVC.sellerId = storeId //sellerProfileVC.delegate = self topVC.navigationController?.pushViewController(sellerProfileVC, animated: false) } } else { if let detailVC = DIConfigurator.sharedInst().getBuyerProducDetail(), let itemId = Int(idValue) { detailVC.productId = itemId topVC.navigationController?.pushViewController(detailVC, animated: false) } } } } func deepLinkingResetPassword(userId: String, token: String) { if UserSession.sharedSession.isLoggedIn() { return } if let topVC = Helper.topMostViewController(rootViewController: Helper.rootViewController()), let updatePassVC = DIConfigurator.sharedInst().getUpdatePasswordVC() { updatePassVC.userId = userId updatePassVC.token = token topVC.navigationController?.pushViewController(updatePassVC, animated: false) } } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { UIApplication.shared.applicationIconBadgeNumber = 0 // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } } //MARK: - Push Notification Methods extension AppDelegate: UNUserNotificationCenterDelegate { //MARK: - Push Notification func registerForPushNotifications(application: UIApplication) { if #available(iOS 10.0, *) { UNUserNotificationCenter.current().delegate = self UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert], completionHandler: { (granted, error) in DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } }) } else{ //If user is not on iOS 10 use the old methods we've been using let notificationSettings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil) application.registerUserNotificationSettings(notificationSettings) } } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let token = deviceToken.reduce("", {$0 + String(format: "%02X", $1)}) print(token) Defaults[.deviceToken] = token } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("i am not available in simulator \(error)") } // Banner Tapped - App Active func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo print("User info -----\(userInfo)") guard let dictData = userInfo["data"] as? [String : AnyObject], let pushType = userInfo["pushType"] as? String else { return; } self.navigateToDetail(pushType: pushType, dictData: dictData) } // This method will be called when app receives push notifications in foreground @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void){ print("received notification\(notification.request.content)") completionHandler([.alert,.sound,.badge]) } }
// // Memoizations.swift // AlgorithmSwift // // Created by Liangzan Chen on 1/30/18. // Copyright © 2018 clz. All rights reserved. // import UIKit func memoizedFib(_ n: Int, _ mem: inout [Int : Int]) -> Int { if let fib = mem[n] { return fib } if n <= 2 { return 1 } else { let fib = memoizedFib(n-1, &mem) + memoizedFib(n-2, &mem) mem[n] = fib return fib } }
// Note that for the test to be effective, each of these enums must only have // its Equatable or Hashable conformance referenced /once/ in the primary file. enum FromOtherFile : String { case A = "a" } enum AlsoFromOtherFile : Int { case A = 0 } enum YetAnotherFromOtherFile: Float { case A = 0.0 }
// // StringRotation.swift // AlgorithmSwift // // Created by Liangzan Chen on 7/10/18. // Copyright © 2018 clz. All rights reserved. // import Foundation func isRotated(_ str1: String, _ str2: String) -> Bool { guard str1.count == str2.count else { return false } let doubleStr1 = str1 + str1 if doubleStr1.contains(str2) { return true } else { return false } }
// // SignUp8ViewController.swift // MagotakuApp // // Created by 宮本一成 on 2020/02/28. // Copyright © 2020 ISSEY MIYAMOTO. All rights reserved. // import UIKit import Foundation import Firebase import FirebaseAuth import FirebaseCore import FirebaseFirestore var seniorProfile = SeniorUserCollection.shared.createSeniorUser() //プロフィール画像が渡ってくる var seniorImage: UIImage? class SignUp8ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { // Firestore へのアクセスに使う let db = Firestore.firestore() // Storage へのアクセスに使う let storage = Storage.storage() let user = Auth.auth().currentUser @IBOutlet weak var tableView: UITableView! @IBOutlet weak var viewForBtn: UIView! @IBOutlet weak var registerBtn: UIButton! // @IBOutlet weak var aNameLabel: UILabel! // @IBOutlet weak var userImage: UIImageView! let titleLabels:[String] = ["アプリ利用者の名前", "あなたの名前", "あなたの生年月日", "あなたの性別", "あなたの電話番号", "あなたの趣味", "あなたの郵便番号","あなたの住所"] let imageLists:[String] = ["person.fill", "person.fill", "calendar.circle.fill", "person.crop.rectangle.fill", "phone.fill", "bookmark", "house.fill", "list.number"] let profileInfo: [String] = [seniorProfile.aName, seniorProfile.sName, seniorProfile.bornDate, seniorProfile.sex, seniorProfile.phoneNumber, seniorProfile.CharaHob, seniorProfile.addressNum, seniorProfile.address] override func viewDidLoad() { super.viewDidLoad() //profileのidに seniorProfile.uid = user!.uid //navigationBarのタイトル設定 self.title = "登録情報確認" tableView.delegate = self tableView.dataSource = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() //tableViewのframe tableView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: self.view.bounds.height - 96) //登録用のviewとbtnのframeを設定する viewForBtn.frame = CGRect(x: 0, y: self.view.bounds.height - 72, width: UIScreen.main.bounds.width, height: 96) registerBtn.frame = CGRect(x: 32, y: 12, width: UIScreen.main.bounds.width - 64, height: 48) registerBtn.layer.cornerRadius = 24 } func numberOfSections(in tableView: UITableView) -> Int { return titleLabels.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.row { case 0: let cell = UITableViewCell(style: .value1, reuseIdentifier: "cell") cell.textLabel?.text = titleLabels[indexPath.section] cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 16) cell.imageView?.image = UIImage(systemName: imageLists[indexPath.section]) //セル選択時にハイライトさせない cell.selectionStyle = .none return cell default: let cell1 = UITableViewCell(style: .value1, reuseIdentifier: "cell1") cell1.textLabel?.text = profileInfo[indexPath.section] // //セルの右端にタッチ利用可能の補助イメージ // let touchImage = UIImageView() // touchImage.image = UIImage(systemName: "chevron.right") // touchImage.frame = CGRect(x: UIScreen.main.bounds.width - 32, y: (cell1.bounds.height / 5) * 2 , width: 8, height: cell1.bounds.height / 5) // cell1.contentView.addSubview(touchImage) return cell1 } } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 32 } //headerViewを設置 func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { switch section { case 0: let view = UIView() view.backgroundColor = UIColor(red: 225/255, green: 225/255, blue: 225/255, alpha: 1) view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 240) let imageView = UIImageView() if let seniorImage = seniorImage{ imageView.image = seniorImage } imageView.backgroundColor = UIColor(red: 99/255, green: 101/255, blue: 105/255, alpha: 1) imageView.frame = CGRect(x: (UIScreen.main.bounds.width / 8) * 3, y: (240 - UIScreen.main.bounds.width / 4) / 2, width: UIScreen.main.bounds.width / 4, height: UIScreen.main.bounds.width / 4) imageView.layer.cornerRadius = UIScreen.main.bounds.width / 8 // //タップイベントがブロックされないようにする // imageView.isUserInteractionEnabled = true view.addSubview(imageView) // let button = UIButton(type: .system) // button.frame = CGRect(x: UIScreen.main.bounds.width / 4, y: (UIScreen.main.bounds.width / 4) + (248 - UIScreen.main.bounds.width / 4) / 2, width: UIScreen.main.bounds.width / 2, height: 12) // button.setTitle("プロフィール写真を変更", for: .normal) // button.titleLabel?.font = UIFont.systemFont(ofSize: 12) // button.titleLabel?.textAlignment = .center // button.addTarget(self, action: #selector(tapBtn), for: .touchUpInside) // view.addSubview(button) return view default: return nil } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { switch section { case 0: return 240 default: return 0 } } //登録処理 @IBAction func tapToRegister(_ sender: Any) { //firebaseに値を保存 //画像を保存 → profileのimageNmaeに値わたし if seniorImage != nil{ SeniorUserCollection.shared.saveImage(image: seniorImage) { (imageName) in guard let imageName = imageName else{ return } seniorProfile.imageName = imageName SeniorUserCollection.shared.addTask(seniorProfile) } } //遷移先に飛ばす guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene, let sceneDelegate = windowScene.delegate as? SceneDelegate else{ return } let vc = MainTabBarController() sceneDelegate.window?.rootViewController = vc } }
// // MainTabController.swift // OnTheMap // // Created by Lawrence Tan on 3/1/16. // Copyright © 2016 Lawrence Tan. All rights reserved. // import UIKit class MainTabController: UITabBarController { }
// // CIOAutocompleteClickTracker.swift // Constructor.io // // Copyright © Constructor.io. All rights reserved. // http://constructor.io/ // import Foundation /** Struct encapsulating the parameters that must/can be set in order to track a click on an autocomplete result. `sectionName` is an optional parameter. - If specified, it will report the autocomplete click as a *select* type and should be used for all types of item clicks, which simply tracks a user selection on an autocomplete item. - Otherwise, it will report the autocomplete click as a *search* type, typically used when the clicked item is a search suggestion for tracking what users search (in addition to the *select* type). */ public struct CIOAutocompleteClickTracker { public let searchTerm: String public let clickedItemName: String public let sectionName: String? public init(searchTerm: String, clickedItemName: String, sectionName: String? = nil) { self.searchTerm = searchTerm self.clickedItemName = clickedItemName self.sectionName = sectionName } }
// Copyright © 2019 Poikile Creations. All rights reserved. import SwiftUI struct HourLines : View { @State var color = Color.white @State var dates: [Date]? = nil @State var thickness = CGFloat(2.0) var body: some View { GeometryReader { geometry in Path { path in self.dates?.forEach() { date in let width = min(geometry.size.width, geometry.size.height) let center = CGPoint(x: width / 2.0, y: width / 2.0) path.move(to: center) let edgePoint = CGPoint(x: center.x + CGFloat(cos(date.hour24RotationAngle.radians)) * width / 2.0, y: center.y + CGFloat(sin(date.hour24RotationAngle.radians)) * width / 2.0) path.addLine(to: edgePoint) } } .stroke(self.color, lineWidth: self.thickness) } } } struct HourLines_Previews : PreviewProvider { static var previews: some View { ZStack { HourLines(color: .green, dates: Tempus().sunEvents?.daylightHours, thickness: 2.0) HourLines(color: .red, dates: Tempus().sunEvents?.nighttimeHours, thickness: 2.0) } } }
// // Case3.swift // ArtOfStateObserving // // Created by Nestor Hernandez on 12/03/22. // import SwiftUI struct InnerItem { var title: String var color: Color var id: Int mutating func updateTitle(_ title: String){ self.title = title } } class ViewModel: ObservableObject { @Published var item1: InnerItem var item2: InnerItem var item3: InnerItem init(item1:InnerItem, item2:InnerItem, item3: InnerItem) { self.item1 = item1 self.item2 = item2 self.item3 = item3 } } struct Case3: View { @ObservedObject var vm:ViewModel = ViewModel(item1: InnerItem(title: "one", color: Color.red, id: 1), item2: InnerItem(title: "two", color: Color.green, id:2), item3: InnerItem(title: "three", color: Color.blue, id:3)) var body: some View { VStack(){ Text("Item List") .padding() HStack{ Text("\(vm.item1.title)") Rectangle().fill(vm.item1.color) Text("\(vm.item1.id)") } HStack{ Text("\(vm.item2.title)") Rectangle().fill(vm.item2.color) Text("\(vm.item2.id)") } HStack{ Text("\(vm.item3.title)") Rectangle().fill(vm.item3.color) Text("\(vm.item3.id)") } }.onAppear{ DispatchQueue.main.asyncAfter(deadline: .now() + 2) { self.vm.item1.color = Color.orange //self.vm.item2.color = Color.orange } } } } struct Case3_Previews: PreviewProvider { static var previews: some View { Case3() } }
// // File.swift // Milestone1 // // Created by Johnson Taylor on 31/3/21. // import Foundation import SwiftUI extension String { func load() -> UIImage { do { // convert string to URL guard let url = URL(string: self) else{ //return empty image if URL is invalid return UIImage() } let data: Data = try Data(contentsOf: url) return UIImage(data: data) ?? UIImage() } catch { } return UIImage() } } struct ContentView: View { // instating all Entries from ListView @ObservedObject var entries: ViewModel var body: some View { NavigationView { MasterView(entries: entries) .navigationBarTitle(Text("Favorite Foods")) .navigationBarItems(leading: EditButton(), trailing: Button(action: { withAnimation { entries.addElement() } }) { Image(systemName: "plus") }) } } } struct MasterView: View { @Environment(\.editMode) var editMode @ObservedObject var entries: ViewModel var body: some View { List { ForEach(entries.model, id: \.description) { entry in NavigationLink( destination: DetailView(entry: entry), label: { HStack{ Image(uiImage: entry.image.load()) .resizable() .frame (width:75, height:50) .scaledToFit() VStack(alignment: .leading){ Text(entry.title) .padding(.horizontal, 10) .padding(.vertical, 10) .font(.system(size: 20)) Text(entry.description) .multilineTextAlignment(.leading) .padding(.horizontal, 10) .padding(.vertical, 10) .font(.footnote) .lineSpacing(0.5) } } }) }.onMove(perform: move) .onDelete { entries.remove(at: $0) } } } func move(from source: IndexSet,to destination: Int) { entries.model.move(fromOffsets: source, toOffset: destination) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView(entries:ViewModel()) } }