text
stringlengths
8
1.32M
// // EntryController.swift // Journal // // Created by Parker Donat on 5/3/16. // Copyright © 2016 Falcone Development. All rights reserved. // import Foundation class EntryController { static func createEntry(title: String, text: String, completion: (success: Bool) -> Void) { let entry = Entry(title: title, text: text) FirebaseController.base.childByAppendingPath("users").childByAppendingPath(UserController.currentUser!.identifier).childByAppendingPath("entries").childByAutoId().setValue(entry.dictValue) { (error, _) in if let error = error { print(error.localizedDescription) completion(success: false) } else { completion(success: true) } } } static func deleteEntry(entry: Entry, completion: (success: Bool) -> Void) { if let identifier = entry.identifier { FirebaseController.base.childByAppendingPath("users").childByAppendingPath(UserController.currentUser!.identifier).childByAppendingPath("entries").childByAppendingPath(identifier).removeValueWithCompletionBlock({ (error, _) in if let error = error { print(error.localizedDescription) completion(success: false) } else { completion(success: true) } }) } } static func fetchAllEntriesForUser(user: User, completion: (entries: [Entry]) -> Void) { FirebaseController.dataEndpoint("users/\(user.identifier)/entries") { (data) in guard let entryDicts = data as? [String : [String : AnyObject]] else { completion(entries: []) return } let entries = entryDicts.map({Entry(dictionary: $0.1, identifier: $0.0)!}) completion(entries: entries) } } static func updateEntry(entry: Entry, completion: (success: Bool) -> Void) { if let identifier = entry.identifier { FirebaseController.base.childByAppendingPath("users").childByAppendingPath(UserController.currentUser!.identifier).childByAppendingPath("entries").childByAppendingPath(identifier).setValue(entry.dictValue, withCompletionBlock: { (error, _) in if let error = error { print(error.localizedDescription) completion(success: false) } else { completion(success: true) } }) } else { print(entry.identifier) } } }
// // HomeViewController.swift // Maddar // // Created by Admin on 5/23/18. // Copyright © 2018 Admin. All rights reserved. // import UIKit import GoogleMaps class LocationManager : NSObject,CLLocationManagerDelegate{ private var locationMgr:CLLocationManager! private var delegate:LocationManagerProtocol? private var locationReturn : ((CLLocation?)->Void)? private var isFirstTime:Bool = true static internal func sharedInstance (withDelagate delagate:LocationManagerProtocol) ->(LocationManager) { struct Singleton { static let instance = LocationManager(); } Singleton.instance.delegate=delagate return Singleton.instance } private override init(){ super.init() locationMgr = CLLocationManager() locationMgr.delegate=self } // mark: When change authorization func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if(isFirstTime){ isFirstTime=false return } switch status { case .notDetermined,.restricted, .denied: delegate?.goToSettings() case .authorizedAlways,.authorizedWhenInUse: locationMgr.startUpdatingLocation() } } // mark: When location update func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location:CLLocation = locations.first{ locationReturn?(location) } locationMgr.stopUpdatingLocation() } // mark: Call to update location private func enableLocationServices() { switch CLLocationManager.authorizationStatus() { case .notDetermined,.restricted, .denied: locationMgr.requestAlwaysAuthorization() case .authorizedAlways,.authorizedWhenInUse: locationMgr.startUpdatingLocation() } } func getCurrentLocation(toMethod method:@escaping (CLLocation?)->Void)->(Void) { locationReturn=method self.enableLocationServices() } func getAddress(ofLocationCoordinates location:CLLocation,onSuccess:@escaping (String)->Void) -> Void { let geocoder = CLGeocoder() geocoder.reverseGeocodeLocation(location) { (placemarksArray, error) in if let placemarksArray = placemarksArray{ if (placemarksArray.count) > 0 { let placemark = placemarksArray.first var address:String="" if let street = placemark!.thoroughfare {address += street } if let number = placemark!.subThoroughfare {address += ", \(number)"} if let subLocality = placemark!.subLocality {address += ", \(subLocality)"} if let locality = placemark!.locality {address += ", \(locality)"} onSuccess(address != "" ? address : "Picked location") } }} } }
// // main.swift // lastobot // // Created by milkavian on 5/4/20. // Copyright © 2020 milonmusk. All rights reserved. // import Foundation let bot = Bot() bot.run() RunLoop.current.run() extension Array { func chunked(into size: Int) -> [[Element]] { return stride(from: 0, to: count, by: size).map { Array(self[$0 ..< Swift.min($0 + size, count)]) } } }
// // UserProfile.swift // Domain // // Created by Tyler Zhao on 11/21/18. // Copyright © 2018 Tyler Zhao. All rights reserved. // import Foundation public struct UserProfile: Codable { public let uid: String public let username: String public let name: String public let followers: [User] public let following: [User] public let bio: String public let profileImage: CollectionImage }
// // ExtensionUIView.swift // HISmartPhone // // Created by MACOS on 12/20/17. // Copyright © 2017 MACOS. All rights reserved. // import UIKit class Constant { static let baseURL = "http://api1.centurylogistics.com.vn/api/" static let autoID = "NULL" static let dayLoadChart: Int = 20 }
// // CreateAccountViewModel.swift // LucrezCeva // // Created by Suciu Radu on 14/12/2018. // Copyright © 2018 LucrezCeva. All rights reserved. // import UIKit class CreateAccountViewModel { let createAccountSuccess = DynamicValue<Bool>(false) weak var flowDelegate: LoginFlowDelegate? func createAccount(fullName: String, email: String, password: String, confirmPassword: String) { ApiClient.shared.register(fullName, email, password, confirmPassword) { (success) in if success { self.createAccountSuccess.value = true } else { self.createAccountSuccess.value = false } } } func completeAccountTapped(fullName: String, email: String, password: String, image: UIImage) { flowDelegate?.completeAccountTapped(name: fullName, email: email, password: password, image: image) } }
// // CreatePlaceWithImage.swift // YuluDemo // // Created by Admin on 11/4/19. // Copyright © 2019 Admin. All rights reserved. // import Foundation protocol CreatePlaceAPIResource: ImageUploadAPIResource { var latitude:String { get } var longtitude:String { get } var description:String { get } } extension CreatePlaceAPIResource { var parameters: [String: String] { return [ "title": titleName, "latitude": latitude, "longitude": longtitude, "description": description ] } var urlRequest: URLRequest { var urlrequest = URLRequest(url: self.url) let media = Media(withImage: imageFile, fileName: "test.jpg")! let boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW" let body = createDataBody(withParameters: parameters, media: [media], boundary: boundary) urlrequest.allHTTPHeaderFields = headers urlrequest.httpBody = body urlrequest.httpMethod = methodType return urlrequest } }
// // Friend.swift // Friend // // Created by Martin Rist on 23/08/2021. // import Foundation struct Friend: Codable, Identifiable { let id: UUID let name: String }
// // DetailsInteractor.swift // CleanSwiftTest // // Created by Dave on 5/19/21. // Copyright (c) 2021 ___ORGANIZATIONNAME___. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit import CoreData protocol DetailsBusinessLogic { func fetchData() func deleteItem() } protocol DetailsDataStore { //var name: String { get set } } class DetailsInteractor: DetailsBusinessLogic, DetailsDataStore { var presenter: DetailsPresentationLogic? var worker: DetailsWorker? var dbWorker: CoreDataManagerProtocol? var index: Int? var allData: [Places] = [] // MARK: Do something func fetchData() { guard let data = dbWorker?.fetchData(), let index = index, let title = data[index].titile, let detail = data[index].detail, let url = data[index].url else {return} allData = data worker?.downloadImage(from: URL(string: url)!) {[weak self] result in switch result { case .success(let data): let sendingData = DetailsModel.Item.Response(title: title, details: detail, image: data) self?.presenter?.sendData(item: sendingData) default: print("Error") } } } func deleteItem() { let deleteData = CoreDataManager.shared.deleteItem(item: allData[index!]) if deleteData { presenter?.itemDeleted() } } }
// // UserExperience.swift // 6.1-cta // // Created by Levi Davis on 12/2/19. // Copyright © 2019 Levi Davis. All rights reserved. // import Foundation enum UserExperience: String { case event case art }
// // main.swift // tcc // // Created by Cayke Prudente on 06/12/16. // Copyright © 2016 Cayke Prudente. All rights reserved. // import Foundation let debug = false if debug { let id = 1 Server(id: id, ip: "127.0.0.1", port: 5000 + id, verbose: 2).waitForConnection(); } else { let arguments = CommandLine.arguments if arguments.count < 4 { print ("Numero de argumentos inválidos") } else { let ip = arguments[1] let id = Int(arguments[2]) let verbose = Int(arguments[3]) Server(id: id!, ip: ip, port: 5000+id!, verbose: verbose!).waitForConnection(); } }
// // Photo.swift // UnsplashClient // // Created by Ness Bautista on 07/07/20. // Copyright © 2020 Ness Bautista. All rights reserved. // import UIKit struct UnsplashQueryResponse:Decodable { var total:Int var total_pages:Int var results:[Photo] } struct Photo: Decodable { var id:String var alt_description:String? var width:Int var height:Int var color:String var created_at:String var likes:Int var liked_by_user:Bool var description:String? var urls:[String:String] var links:[String:String] var user:User } enum PhotoRecordState { case new case downloaded case failed } struct PhotoVM: URLImageProvider { var id:String var description:String var thumbURL:URL? var thumbImg:UIImage = UIImage(named:"Placeholder")! var state:PhotoRecordState = .new var userLike:Bool var userName:String var user:UserVM var downloadURL: URL? { return self.thumbURL } var outputImage: UIImage?{ get{ return self.thumbImg } set{ self.thumbImg = newValue ?? UIImage(named:"Placeholder")! } } init(photo:Photo){ self.id = photo.id self.description = photo.description ?? photo.alt_description ?? "" if let thumbUrl = photo.urls["thumb"], let url = URL(string: thumbUrl){ self.thumbURL = url } self.userName = photo.user.name self.user = UserVM(user: photo.user) self.userLike = photo.liked_by_user } } protocol URLImageProvider { var downloadURL:URL? {get} var outputImage:UIImage? {get set} var state:PhotoRecordState {get set} }
// // ApiService.swift // MarvelHeroes // // Created by RafaelAlmeida on 10/07/19. // Copyright © 2019 RafaelAlmeida. All rights reserved. // import Foundation class ApiService: NSObject { static let shared = ApiService() func fetchAllHeroes(completion: @escaping (ApiResponse?, Error?) -> ()) { guard let url = APIUtils().getUrl() else { return } URLSession.shared.dataTask(with: url) { (data, resp, err) in if let err = err { completion(nil, err) print("Failed to fetch heroes: ", err) return } guard let data = data else { return } do { let heroes = try JSONDecoder().decode(ApiResponse.self, from: data) DispatchQueue.main.async { print(heroes) completion(heroes, nil) } } catch let jsonErr { print("Failed to decode: ", jsonErr) } }.resume() } func downloadImage(url: String, completion: @escaping (Data?, Error?) -> ()) { guard let imageUrl = URL(string: url) else { return } let downloadTask = URLSession.shared.downloadTask(with: imageUrl) { localURL, resp, err in if let err = err { completion(nil, err) print("Failed to get image: ", err) return } if let localURL = localURL { if let image = try? Data(contentsOf: localURL) { completion(image, nil) } } } downloadTask.resume() } }
// // AlertSettingsInfo.swift // TelerikUIExamplesInSwift // // Copyright (c) 2015 Telerik. All rights reserved. // import Foundation class AlertSettingsInfo: NSObject { var title = "Alert" var message = "Hello world" var allowParallax = false var backgroundStyle = TKAlertBackgroundStyle.Dim var actionsLayout = TKAlertActionsLayout.Horizontal var dismissMode = TKAlertDismissMode.None var dismissDirection = TKAlertSwipeDismissDirection.Horizontal var animationDuration: CGFloat = 0.3 var backgroundDim: CGFloat = 0.3 }
// // AddOrEditTimeEntryVC.swift // MyTime // // Created by Anibal Ferreira on 23/04/2017. // Copyright © 2017 Anibal Ferreira. All rights reserved. // import UIKit import Foundation import SwiftyPickerPopover class AddOrEditTimeEntryVC: UITableViewController, AddOrEditTimeEntryPresenterDelegate { public var presenter: AddOrEditTimeEntryPresenterProtocol! public var wantsToEdit = false @IBOutlet private weak var timeEntryDateLabel: UILabel! @IBOutlet private var timeEntryProjectLabel: UILabel! @IBOutlet private weak var timeEntryActivityLabel: UILabel! @IBOutlet private weak var timeEntryHoursTextField: UITextField! @IBOutlet private weak var timeEntryDetailsTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() self.tableView.delegate = self self.tableView.dataSource = self self.presenter.delegate = self } override func viewWillAppear(_ animated: Bool) { refreshData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let theCell = self.tableView.cellForRow(at: indexPath) switch indexPath.row { case 0: showDatePicker(sender: theCell) case 1: showProjectPicker(sender: theCell) case 2: showActivityPicker(sender: theCell) default: return } } func showDatePicker(sender: UITableViewCell?) { guard let theSender = sender else { return } DatePickerPopover(title: "Date") .setDateMode(.date) .setSelectedDate(self.presenter.timeEntry.date) .setDoneAction({ selectedDate in self.presenter.timeEntry.date = selectedDate.1 self.timeEntryDateLabel.text = Calendar.myCustomDateString(from: self.presenter.timeEntry.date) print("selectedDate \(selectedDate.1)") }) .setCancelAction({ _ in print("cancel") }) .appear(originView: theSender, baseViewController: self) } func showProjectPicker(sender: UITableViewCell?) { if let mySender = sender { StringPickerPopover(title: "Projects", choices: [ProjectName.blueSea.rawValue, ProjectName.energy.rawValue, ProjectName.keepCalm.rawValue, ProjectName.risingSun.rawValue]) .setSelectedRow(0) .setDoneAction({ (_, selectedRow, selectedString) in self.presenter.timeEntry.project = selectedString self.timeEntryProjectLabel.text = selectedString print("done row \(selectedRow) \(selectedString)") }) .setCancelAction({ _ in print("cancel") }) .appear(originView: mySender, baseViewController: self) } } func showActivityPicker(sender: UITableViewCell?) { if let mySender = sender { StringPickerPopover(title: "Activities", choices: [ProjectActivity.analysis.rawValue, ProjectActivity.architecture.rawValue, ProjectActivity.uidesign.rawValue]) .setSelectedRow(0) .setDoneAction({ (_, selectedRow, selectedString) in self.presenter.timeEntry.activity = selectedString self.tableView.reloadData() self.timeEntryActivityLabel.text = selectedString print("done row \(selectedRow) \(selectedString)") }) .setCancelAction({ _ in print("cancel") }) .appear(originView: mySender, baseViewController: self) } } func refreshData() { // Ternary here is to fix an Apple optimization that removes views from the hierarchy of the tableviewcell // when contents are empty self.timeEntryDateLabel.text = Calendar.myCustomDateString(from: self.presenter.timeEntry.date) self.timeEntryProjectLabel.text = self.presenter.timeEntry.project.isEmpty == true ? " " : self.presenter.timeEntry.project self.timeEntryActivityLabel.text = self.presenter.timeEntry.activity.isEmpty ? " " : self.presenter.timeEntry.activity self.timeEntryHoursTextField.text = String(self.presenter.timeEntry.hours) self.timeEntryDetailsTextView.text = self.presenter.timeEntry.details } public func didAddTimeEntry() { navigationController?.popViewController(animated: true) } public func didUpdateTimeEntry() { navigationController?.popViewController(animated: true) } @IBAction func saveTimeEntryButtonTapped(_ sender: UIBarButtonItem) { if let myHoursString = self.timeEntryHoursTextField.text, let hours = Int(myHoursString) { self.presenter.timeEntry.hours = hours } else { self.timeEntryHoursTextField.text = String(self.presenter.timeEntry.hours) } self.presenter.timeEntry.details = self.timeEntryDetailsTextView.text if self.presenter.timeEntry.project.isEmpty || self.presenter.timeEntry.activity.isEmpty || self.presenter.timeEntry.hours == 0 { let alert = UIAlertController(title: "Warning", message: "Please add more info", preferredStyle: UIAlertControllerStyle.alert) let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) alert.addAction(cancelAction) self.present(alert, animated: true) } else { if wantsToEdit { self.presenter.updateCurrentTimeEntry() } else { self.presenter.addCurrentTimeEntry() } } } }
// // MapViewController.swift // WorldTrotter // // Created by 김예진 on 2017. 10. 25.. // Copyright © 2017년 Kim,Yejin. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { var mapView : MKMapView! // let currentLocationButton = UIButton() // let locationManager = CLLocationManager() override func loadView() { mapView = MKMapView() // Create a map view view = mapView let segmentedControl = UISegmentedControl(items : ["Standard","Hybrid","Satellite"]) segmentedControl.backgroundColor = UIColor.white.withAlphaComponent(0.5) segmentedControl.selectedSegmentIndex = 0 segmentedControl.addTarget(self, action: #selector(mapTypeChanged(segControl:)), for: .valueChanged) segmentedControl.translatesAutoresizingMaskIntoConstraints = false view.addSubview(segmentedControl) //let topConstraint = segmentedControl.topAnchor.constraint(equalTo: view.topAnchor) let topConstraint = segmentedControl.topAnchor.constraint(equalTo:topLayoutGuide.bottomAnchor, constant: 8) //let leadingConstraint = segmentedControl.leadingAnchor.constraint(equalTo: view.leadingAnchor) //let trailingConstraint = segmentedControl.trailingAnchor.constraint(equalTo: view.trailingAnchor) let margins = view.layoutMarginsGuide let leadingConstraint = segmentedControl.leadingAnchor.constraint(equalTo: margins.leadingAnchor) let trailingConstraint = segmentedControl.trailingAnchor.constraint(equalTo: margins.trailingAnchor) topConstraint.isActive = true leadingConstraint.isActive = true trailingConstraint.isActive = true } func mapTypeChanged(segControl: UISegmentedControl) { switch segControl.selectedSegmentIndex { case 0 : mapView.mapType = .standard case 1 : mapView.mapType = .hybrid case 2 : mapView.mapType = .satellite default : break } } override func viewDidLoad() { super.viewDidLoad() // print("MapViewController loaded its view.") // userLocation() } // MARK : Appear the location of user. -> Added 'Privacy - Location When In Use Usage Description' at Info.plist /* func userLocation() { currentLocationButton.setTitle("current Location", for : .normal) currentLocationButton.setTitleColor(UIColor.blue, for: .normal) currentLocationButton.backgroundColor = UIColor.white.withAlphaComponent(0.5) currentLocationButton.translatesAutoresizingMaskIntoConstraints = false currentLocationButton.addTarget(self, action: #selector(currentLocation(sender:)), for: .touchUpInside) view.addSubview(currentLocationButton) let bottomConstraint = currentLocationButton.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor, constant : -8) let margins = view.layoutMarginsGuide let leadingConstraint = currentLocationButton.leadingAnchor.constraint(equalTo: margins.leadingAnchor) let trailingConstraint = currentLocationButton.trailingAnchor.constraint(equalTo: margins.trailingAnchor) bottomConstraint.isActive = true leadingConstraint.isActive = true trailingConstraint.isActive = true } func currentLocation(sender: AnyObject) { print("click") mapView.delegate = self locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() mapView.showsUserLocation = true } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations.last let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude) let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1)) mapView.setRegion(region, animated: true) locationManager.stopUpdatingLocation() } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Error - " + error.localizedDescription, terminator: "") } */ override func viewWillAppear(_ animated: Bool) { // print("viewWillAppear") } }
// // ViewController.swift // MacQQ // // Created by sycf_ios on 2017/4/19. // Copyright © 2017年 shibiao. All rights reserved. // import Cocoa class LoginViewController: NSViewController { @IBOutlet weak var accountField: NSTextField! @IBOutlet weak var passwordField: NSTextField! @IBOutlet weak var iconImg: SBImageView! var subWindow: NSWindow? override func viewDidLoad() { super.viewDidLoad() view.window?.isRestorable = false view.window?.center() } override func viewDidAppear() { if accountField.stringValue.isEmpty { accountField.becomeFirstResponder() }else{ passwordField.becomeFirstResponder() } } @IBAction func login(_ sender: Any) { if !accountField.stringValue.isEmpty && !passwordField.stringValue.isEmpty{ let mainWindowController = NSStoryboard.init(name: "MainUI", bundle: nil).instantiateInitialController() as! MainUIWindowController mainWindowController.window?.makeKeyAndOrderFront(nil) view.window?.close() } } @IBAction func showOrHideSubWindow(_ sender: Any) { let btn = sender as! NSButton if btn.image == #imageLiteral(resourceName: "loginDown") { subWindow = NSWindow(contentRect: NSMakeRect((self.view.window?.frame.origin.x)!, (self.view.window?.frame.origin.y)! - 75, (self.view.window?.frame.size.width)!, 75), styleMask: .titled, backing: .nonretained, defer: true) let setupViewController = NSStoryboard.init(name: "Main", bundle: nil).instantiateController(withIdentifier: "login") as! LoginSetupViewController subWindow?.contentViewController = setupViewController view.window?.addChildWindow(subWindow!, ordered: .below) }else{ view.window?.removeChildWindow(subWindow!) subWindow?.setFrame(NSZeroRect, display: false) } btn.image = btn.image == #imageLiteral(resourceName: "loginDown") ? #imageLiteral(resourceName: "loginUp") :#imageLiteral(resourceName: "loginDown") } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } }
// // NewsTopicController.swift // News App // // This file setsup the view that will display // the news topic names on the table view cell. // // Created by Naveen Gaur on 8/1/19. // Copyright © 2019 Naveen Gaur. All rights reserved. // import UIKit import Moya public var globalIndex = 0 class NewsTopicController: UIViewController { @IBOutlet weak var navigationBar: UINavigationBar! @IBOutlet weak var tableView: UITableView! private var newsTopics = [String]() var tapGesture = UITapGestureRecognizer() private var indexCount: Int = 0 // This control the index for the views inside the table view cells. override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setupNavBar() setupNewsTopicArray() getParticularNews(newsTopic: "premier league") configureTableView() view.isUserInteractionEnabled = true tableView.isUserInteractionEnabled = true } /// This function is used to configure some properties of the table view. private func configureTableView() { tableView.separatorStyle = .none tableView.allowsSelection = false } /// This function is used to set the title for the navigation bar. private func setupNavBar() { navigationBar.dropShadow(scale: true) navigationBar.topItem?.title = "News Topic" } // MARK: - Here are the News Topic names. /// Fills the array with the hardcoded news topic. private func setupNewsTopicArray() { newsTopics = ["Fashion","NBA","NFL","Soccer","Music","Premier League","Politics","Technology","Apple","Microsoft"] } // MARK: - This function is used to connect to the api and get the data from it. /// This function is used to get data from the api about a particular news topic that a user /// might select. /// /// - Parameter newsTopic: Takes a string as a parameter that indicates what news topic the /// user might be intrested in. func getParticularNews(newsTopic: String) { let newsService = MoyaProvider<specificNewsService>() newsService.request(.getNews(query: newsTopic), completion: { (result) in switch result { case .success(let response): if response.statusCode == 200 { // Parse JSON Response let json = try! JSONDecoder().decode(News.self, from: response.data) } case .failure(let error): print(error) } }) } /// This Function is triggered when the user taps on a cell that displayed the news topic to them. /// /// - Parameter _ges: Takes in a UIGestureRecognizer as a param. @objc func handleTap(gestureRecognizer: UIGestureRecognizer) { if (gestureRecognizer.view as? UILabel) != nil { } } } // MARK: - Setup for table view here. extension NewsTopicController : UITableViewDelegate,UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // We make the count half because we have two views that will display the // topic name on each cell. return newsTopics.count/2 } // MARK:- The Tap gesture is configured here. /// This function is used to setup the table view cells. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? NewsTopicsCell else { fatalError("Could not dequeue cell with identifier: cell") } cell.setupSelectionViews() cell.setSelectionViewNames(topicName1: newsTopics[indexCount], topicName2: newsTopics[indexCount+1]) indexCount+=2 // Increment the index count after each cell has been setup. // Setup the tap gesture here. tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(handleTap(gestureRecognizer:))) cell.addGestureRecognizer(_ges: tapGesture) return cell } // MARK: - Add animations on the table view cells. func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let animationTransform = CATransform3DTranslate(CATransform3DIdentity, 0, 50, 0) cell.layer.transform = animationTransform cell.alpha = 0 UIView.animate(withDuration: 0.75) { cell.layer.transform = CATransform3DIdentity cell.alpha = 1.0 } } }
// // UIView+.swift // // Created by Ken Yu on 10/3/15. // Copyright © 2015 Ken Yu. All rights reserved. // import Foundation import UIKit extension UIImage { /** Setter and getter for size of the view's frame */ public func imageWithColor(color: UIColor, size: CGSize) -> UIImage { let rect = CGRectMake(0, 0, size.width, size.height) UIGraphicsBeginImageContextWithOptions(size, false, 0) color.setFill() UIRectFill(rect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } // public func imageWithGradient(size: CGSize) -> UIImage { // var currentContext = UIGraphicsGetCurrentContext() // // // 2 // CGContextSaveGState(currentContext); // // // 3 // var colorSpace = CGColorSpaceCreateDeviceRGB() // // // 4 // var startColor = UIColor.redColor(); // var startColorComponents = CGColorGetComponents(startColor.CGColor) // var endColor = UIColor.blueColor(); // var endColorComponents = CGColorGetComponents(endColor.CGColor) // // // 5 // var colorComponents // = [startColorComponents[0], startColorComponents[1], startColorComponents[2], startColorComponents[3], endColorComponents[0], endColorComponents[1], endColorComponents[2], endColorComponents[3]] // // // 6 // var locations:[CGFloat] = [0.0, 1.0] // // // 7 // var gradient = CGGradientCreateWithColorComponents(colorSpace,&colorComponents,&locations,2) // // var startPoint = CGPointMake(0, size.height) // var endPoint = CGPointMake(size.width, size.height) // // // 8 // CGContextDrawLinearGradient(currentContext,gradient,startPoint,endPoint, CGGradientDrawingOptions.DrawsBeforeStartLocation) // // // 9 // CGContextRestoreGState(currentContext); // // return // } }
// // PostTableViewCell.swift // iOS App // // Created by Flannery Jefferson on 2018-03-24. // Copyright © 2018 Flannery Jefferson. All rights reserved. // import UIKit class PostTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var coverPhotoView: UIImageView! @IBOutlet weak var bodyLabel: UILabel! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
// // ViewController.swift // SimpleAutoLayoutExample // // Created by Bao Lei on 4/10/16. // Copyright © 2016 Bao Lei. All rights reserved. // import SimpleAutoLayout class ViewController: UIViewController { let flag = UIView() let red = Helper.viewWithColor(UIColor.red) let white = Helper.viewWithColor(UIColor.white) let blue = Helper.viewWithColor(UIColor.blue) let bearCanvas = Helper.viewWithColor(UIColor.white) let bearHead = Helper.viewWithColor(UIColor.brown) let leftEar = Helper.viewWithColor(UIColor.brown) let rightEar = Helper.viewWithColor(UIColor.brown) let leftEye = Helper.viewWithColor(UIColor.black) let rightEye = Helper.viewWithColor(UIColor.black) let nose = Helper.viewWithColor(UIColor.black) let line = Helper.viewWithColor(UIColor.lightGray) let label1 = Helper.label("Simple") let label2 = Helper.label("Auto") let label3 = Helper.label("Layout") let label4 = Helper.label("🐼") override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(white: 0.95, alpha: 1) layoutFlag() layoutBear() } fileprivate func layoutFlag() { SimpleAutoLayout(on: self.view) .place(flag, from: [.left: 20, .right: 20, .top: 40], size: [.aspectRatio: 2], safeAreaEdges: [.top]) .place(blue, alignToLast: [.left: 1, .top: 1, .bottom: 1]) .addConstraint(blue, a1: .width, item2: flag, a2: .width, multiplier: 1/3) .goRight(white, alignToLast: [.top: 0, .bottom: 0, .width: 0]) .goRight(red, alignToLast: [.top: 0, .bottom: 0, .width: 0]) } fileprivate func layoutBear() { let bearEarRadius: CGFloat = 40 let bearEyeRadius: CGFloat = 15 let bearNoseRadius: CGFloat = 30 let bearHeadRadius: CGFloat = 100 let noseEyeHorizontalDistance: CGFloat = 20 Helper.makeCircleWithRadius(bearHeadRadius, forView: bearHead) Helper.makeCircleWithRadius(bearEarRadius, forView: leftEar) Helper.makeCircleWithRadius(bearEarRadius, forView: rightEar) Helper.makeCircleWithRadius(bearEyeRadius, forView: leftEye) Helper.makeCircleWithRadius(bearEyeRadius, forView: rightEye) Helper.makeCircleWithRadius(bearNoseRadius, forView: nose) Helper.addBorder(UIColor.white, width: 5, forView: leftEye) Helper.addBorder(UIColor.white, width: 5, forView: rightEye) label4.textAlignment = .right SimpleAutoLayout(on: self.view) .from(flag) .goDown(bearCanvas, distance: 20, size: [.aspectRatio: 1], alignToLast: [.width: 0, .centerX: 0]) SimpleAutoLayout(on: bearCanvas) .place(bearHead, from: [.centerX: 0, .centerY: 0], size: [.w: bearHeadRadius*2, .aspectRatio: 1]) .place(leftEar, size: [.w: bearEarRadius*2, .aspectRatio: 1], alignToLast: [.left: 0, .top: -20]) .from(bearHead) .place(rightEar, size: [.w: bearEarRadius*2, .aspectRatio: 1], alignToLast: [.right: 0, .top: -20]) .from(bearHead) .place(nose, size: [.w: bearNoseRadius*2, .aspectRatio: 1], alignToLast: [.centerX: 0, .centerY: 30]) .goLeft(leftEye, distance: noseEyeHorizontalDistance - bearNoseRadius, size: [.w: bearEyeRadius*2, .aspectRatio: 1], alignToLast: [.centerY: -60]) .goRight(rightEye, distance: noseEyeHorizontalDistance*2, alignToLast: [.centerY: 0, .width: 0, .height: 0]) .from(bearHead) .goDown(line, distance: 20, size: [.h: 1]) .place(line, from: [.left: 10, .right: 10]) .goDown(label1, distance: 5, alignToLast: [.left: 0]) .goRight(label2, distance: 5, alignToLast: [.centerY: 0]) .goRight(label3, distance: 5, alignToLast: [.centerY: 0]) .place(label4, from: [.right: 10], alignToLast: [.centerY: 0]) } }
// // TMDateFormatter.swift // TheMovieTest // // Created by Roman Rybachenko on 28.09.2020. // Copyright © 2020 Roman Rybachenko. All rights reserved. // import Foundation class TMDateFormatter { static let shared = TMDateFormatter() private let dateFormatter = DateFormatter() enum DateFormat: String { case server = "yyyy.MM.dd" // 2010-10-22 } func date(from string: String?, format: DateFormat) -> Date? { guard let dateStr = string else { return nil } dateFormatter.dateFormat = format.rawValue return dateFormatter.date(from: dateStr) } func string(from date: Date?, format: DateFormat) -> String? { guard let date = date else { return nil } dateFormatter.dateFormat = format.rawValue return dateFormatter.string(from: date) } }
// // WKTestingViewController.swift // WebViewTesting // // Created by TechFun on 6/5/19. // Copyright © 2019 TechFun. All rights reserved. // import UIKit import WebKit class WKTestingViewController: UIViewController { @IBOutlet weak var TopView: UIView! @IBOutlet weak var BottomView: UIView! @IBOutlet weak var showTextField: UITextField! @IBOutlet weak var searchBtn: UIButton! @IBOutlet weak var backBtn: UIButton! @IBOutlet weak var nextBtn: UIButton! @IBOutlet weak var webView: WKWebView! @IBOutlet var backUIView: UIView! public var myActivityIndicatior = UIActivityIndicatorView() override func viewDidLoad() { super.viewDidLoad() myActivityIndicatior.center = self.view.center myActivityIndicatior.style = .gray view.addSubview(myActivityIndicatior) // self.webView.addObserver(self, forKeyPath: #keyPath(WKWebView.isLoading), options: .new, context: nil) } @IBAction func searchAction(_ sender: Any) { if let urlString = showTextField.text{ let url = NSURL(string: urlString) let request = NSURLRequest(url: url! as URL) if urlString.starts(with: "http://") || urlString.starts(with: "https://"){ webView.load(request as URLRequest) }else if urlString.contains("www"){ webView.load(request as URLRequest) } else{ searchOnGoogle(text: urlString) } } } func searchOnGoogle(text: String) { let textComponent = text.components(separatedBy: " ") let searchString = textComponent.joined(separator: "+") let url = URL(string: "https://www.google.com/search?q=" + searchString) let urlRequest = URLRequest(url: url!) webView.load(urlRequest) self.hideView() self.view.addSubview(backUIView) self.backUIView.isHidden = false self.setupLayout() } func hideView(){ TopView.isHidden = true BottomView.isHidden = true } // @IBAction func backAction(_ sender: Any) { // // let viewController = UIStoryboard(name: "WKTesting", bundle: nil).instantiateViewController(withIdentifier: "BackID") // self.present(viewController, animated: true, completion: nil) // // } func setupLayout(){ webView.translatesAutoresizingMaskIntoConstraints = false webView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true } @IBAction func backBtnAction(_ sender: Any) { let backController = UIStoryboard(name: "QNA", bundle: nil).instantiateViewController(withIdentifier: "QNAID") self.present(backController, animated: true, completion: nil) } override var prefersStatusBarHidden: Bool{ return true } }
// // Post.swift // Reddit Client // // Created by Женя on 24.05.2021. // import Foundation import UIKit struct Post { var id: String var name: String var title: String var author: String var url: String var thumbnail: String var postHint: String? var comments: Int var createdUTC: TimeInterval var image: UIImage? } // MARK: - Decodable extension Post: Decodable { enum CodingKeys: String, CodingKey { case id case name case title case author case url case thumbnail case post_hint case num_comments case created_utc case data } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) let dataContainer = try values.nestedContainer(keyedBy: CodingKeys.self, forKey: .data) id = try dataContainer.decode(String.self, forKey: .id) name = try dataContainer.decode(String.self, forKey: .name) title = try dataContainer.decode(String.self, forKey: .title) author = try dataContainer.decode(String.self, forKey: .author) url = try dataContainer.decode(String.self, forKey: .url) thumbnail = try dataContainer.decode(String.self, forKey: .thumbnail) postHint = try dataContainer.decodeIfPresent(String.self, forKey: .post_hint) comments = try dataContainer.decode(Int.self, forKey: .num_comments) createdUTC = try dataContainer.decode(TimeInterval.self, forKey: .created_utc) if let thumbnailURL = URL(string: thumbnail), let data = try? Data(contentsOf: thumbnailURL) { image = UIImage(data: data) } } } //MARK: - CoreData extension Post { // This init needed to read posts stored locally init(from postData: PostData) { id = postData.id ?? "" name = postData.name ?? "" title = postData.title ?? "" author = postData.author ?? "" url = postData.url ?? "" thumbnail = postData.thumbnail ?? "" postHint = postData.postHint comments = Int(postData.comments) createdUTC = postData.createdUTC if let data = postData.image { image = UIImage(data: data) } } }
import XCTest import SyntaxParserTests var tests = [XCTestCaseEntry]() tests += SyntaxParserTests.allTests() XCTMain(tests)
// // SocketComm.swift // Homee // // Created by Realank-Mac on 15/4/5. // Copyright (c) 2015年 Realank-Mac. All rights reserved. // import UIKit protocol receiveSocketMsgDelegate{ func receivedBufferFromSocket(count:Int, data: String) } struct IPAndPort { static var hostIP = "182.92.183.168" static var port = 6001 } class SocketComm: NSObject { var receiverDelegater : receiveSocketMsgDelegate? let queue = dispatch_queue_create("SocketComm",DISPATCH_QUEUE_CONCURRENT) func communicate(dataToSend data: String){ dispatch_async(queue){ self.communicateAsync(dataToSend: data) } } func communicateAsync(dataToSend : String? = nil){ var socket : ActiveSocketIPv4? = ActiveSocket<sockaddr_in>() println("Got socket: \(socket)") if socket == nil { return } socket?.onRead { (ActiveSocket, Int) -> Void in let (count, block, errno) = ActiveSocket.read() if count < 0 && errno == EWOULDBLOCK { return } if count < 1 { println("EOF, or great error handling \(errno).") socket?.close() return } var dataReceived = String.fromCString(block)! dataReceived = dataReceived.trim() // println("Socket Answer is: \(count) bytes: \(dataReceived)") //usleep(3000000) self.receiverDelegater?.receivedBufferFromSocket(dataReceived.length(), data: dataReceived) socket?.close() } socket?.onClose { fd in println("Closing \(fd) ..."); } // connect println("Connect \(IPAndPort.hostIP):\(IPAndPort.port) ...") let ok = socket?.connect(sockaddr_in(address:IPAndPort.hostIP, port:IPAndPort.port)) { println("connected \(socket)") socket?.isNonBlocking = true if let sk = socket{ sk.write( dataToSend ?? "WTHR:CHEK:WEEK:0000" ) } } if (ok == nil) { println("connect failed \(socket)") socket?.close() socket = nil } } }
/* Copyright 2018 by Multy.io * Licensed under Multy.io license. * * See LICENSE for details */ import UIKit class ViewController: UIViewController { @IBOutlet weak var libraryVersionLabel: UILabel! @IBOutlet weak var testsResultsLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() let testResults = run_tests(1, UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: 1)) testsResultsLabel.text = testResults == 0 ? "Ok" : "Not Ok" let version = UnsafeMutablePointer<UnsafePointer<Int8>?>.allocate(capacity: 1) defer { version.deallocate(capacity: 1) } let error = make_version_string(version) if error != nil { let errrString = returnErrorString(opaquePointer: error!, mask: "make_version_string") libraryVersionLabel.text = errrString } else { let versionString = String(cString: version.pointee!) libraryVersionLabel.text = versionString } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func returnErrorString(opaquePointer: OpaquePointer, mask: String) -> String { let pointer = UnsafeMutablePointer<MultyError>(opaquePointer) let errorString = String(cString: pointer.pointee.message) print("\(mask): \(errorString))") defer { pointer.deallocate(capacity: 1) } return errorString } }
import UIKit import AVFoundation class SounViewController: UIViewController { //outlets @IBOutlet weak var recordButton: UIButton! @IBOutlet weak var nameTextFile: UITextField! @IBOutlet weak var playButton: UIButton! @IBOutlet weak var addButton: UIButton! var audioRecorder : AVAudioRecorder? var audioPlayer : AVAudioPlayer? var audioURL : URL? override func viewDidLoad() { super.viewDidLoad() setupRecorder() playButton.isEnabled = false addButton.isEnabled = false // Do any additional setup after loading the view. } func setupRecorder(){ do{ //creando una sesion de audio let session = AVAudioSession.sharedInstance() try session.setCategory(AVAudioSessionCategoryPlayAndRecord) try session.overrideOutputAudioPort(.speaker) try session.setActive(true) //Creando una direccion para el archivo de audio let basePath : String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! let pathComponents = [basePath,"audio.m4a"] audioURL = NSURL.fileURL(withPathComponents: pathComponents)! print("**************************") print(audioURL) print("**************************") //crear opciones para el grabador de audio var settings : [String:AnyObject] = [:] settings[AVFormatIDKey] = Int(kAudioFormatMPEG4AAC) as AnyObject? settings[AVSampleRateKey] = 44100.0 as AnyObject? settings[AVNumberOfChannelsKey] = 2 as AnyObject? //Crear el objeto de grabaciones de audio audioRecorder = try AVAudioRecorder(url: audioURL!, settings: settings) audioRecorder!.prepareToRecord() }catch let error as NSError{ print(error) } } @IBAction func recordTapped(_ sender: Any) { if audioRecorder!.isRecording{ //Detener la grabacion audioRecorder?.stop() //Cambiar el texto del boton grabar recordButton.setTitle("Record", for: .normal) playButton.isEnabled = true addButton.isEnabled = true } else{ //empezar a grabar audioRecorder?.record() //Cambiar el titulo del boton a detener recordButton.setTitle("Stop", for: .normal) } } @IBAction func playTapped(_ sender: Any) { do { try audioPlayer = AVAudioPlayer(contentsOf: audioURL!) audioPlayer!.play() } catch{} } @IBAction func addTapped(_ sender: Any) { let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext let sound = Sound(context:context) sound.name = nameTextFile.text sound.audio = NSData(contentsOf: audioURL!) as Data? (UIApplication.shared.delegate as! AppDelegate).saveContext() navigationController!.popViewController(animated: true) } }
// // AbschnitteSectionTVC.swift // ELRDRG // // Created by Jonas Wehner on 20.11.20. // Copyright © 2020 Jonas Wehner. All rights reserved. // import UIKit protocol AbschnitteSectionTVCDelegate { func addSection(section : BaseSection) } class AbschnitteSectionTVC: UITableViewCell { override func awakeFromNib() { super.awakeFromNib() // Initialization code } @IBOutlet weak var Name: UILabel! public var section : BaseSection? public var delegate : AbschnitteSectionTVCDelegate? @IBAction func addSection(_ sender: Any) { if let sec = self.section { self.delegate?.addSection(section: sec) } } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
import UIKit import RxSwift import RxCocoa /* Driver UI layer reactive code with specific characteristics: 1. can't error out 2. observe occurs on main scheduler 3. share(replay: 1, scope: .whileConnected) https://github.com/ReactiveX/RxSwift/blob/master/Documentation/Traits.md#driver */ let publishSubjectForDriver = PublishSubject<String>() let driver = publishSubjectForDriver .flatMap { value -> Single<String> in if value == "error" { return Single<String>.error(RxError.argumentOutOfRange) } return Single<String>.just(value) } .asDriver(onErrorDriveWith: Driver<String>.empty()) driver.drive( onNext: { value in print("drive1 value: \(value)") }, onCompleted: { print("drive1 completed") }, onDisposed: { print("drive1 disposed") } ) publishSubjectForDriver.onNext("value0") publishSubjectForDriver.onNext("value1") driver.drive( onNext: { value in print("drive2 value: \(value)") }, onCompleted: { print("drive2 completed") }, onDisposed: { print("drive2 disposed") } ) publishSubjectForDriver.onNext("value2") publishSubjectForDriver.onNext("error") publishSubjectForDriver.onNext("value3") /* Signal UI layer reactive code with specific characteristics: 1. can't error out 2. observe occurs on main scheduler 3. share(scope: .whileConnected) https://github.com/ReactiveX/RxSwift/blob/master/Documentation/Traits.md#signal */ let publishSubjectForSignal = PublishSubject<String>() let signal = publishSubjectForSignal .flatMap { value -> Single<String> in if value == "error" { return Single<String>.error(RxError.argumentOutOfRange) } return Single<String>.just(value) } .asSignal(onErrorJustReturn: "<err>") signal.emit( onNext: { value in print("signal1 value: \(value)") }, onCompleted: { print("signal1 completed") }, onDisposed: { print("signal1 disposed") } ) publishSubjectForSignal.onNext("value0") publishSubjectForSignal.onNext("value1") signal.emit( onNext: { value in print("signal2 value: \(value)") }, onCompleted: { print("signal2 completed") }, onDisposed: { print("signal2 disposed") } ) publishSubjectForSignal.onNext("value2") publishSubjectForSignal.onNext("error") publishSubjectForSignal.onNext("value3")
// // StartGame.swift // TikiTacToe // // Created by Pro on 27.01.2021. // import GameplayKit import SpriteKit class GameStarting: GKState { var scene: GameScene? var winLabel: SKNode! var restartNode: SKNode! var board: SKNode! init(scene: GameScene) { self.scene = scene super.init() } override func isValidNextState(_ stateClass: AnyClass) -> Bool { return stateClass == GamePlaying.self } override func update(deltaTime seconds: TimeInterval) { restartGame() scene?.turnsAIthinkOf(lvl: scene?.level ?? 1) self.stateMachine?.enter(GamePlaying.self) } func restartGame() { let topLeft: BoardCell = BoardCell(value: .none, node: "//*top_left") let middleLeft: BoardCell = BoardCell(value: .none, node: "//*middle_left") let bottomLeft: BoardCell = BoardCell(value: .none, node: "//*bottom_left") let topMiddle: BoardCell = BoardCell(value: .none, node: "//*top_middle") let center: BoardCell = BoardCell(value: .none, node: "//*center") let bottomMiddle: BoardCell = BoardCell(value: .none, node: "//*bottom_middle") let topRight: BoardCell = BoardCell(value: .none, node: "//*top_right") let middleRight: BoardCell = BoardCell(value: .none, node: "//*middle_right") let bottomRight: BoardCell = BoardCell(value: .none, node: "//*bottom_right") board = self.scene?.childNode(withName: "//Grid") as? SKSpriteNode winLabel = self.scene?.childNode(withName: "winLabel") winLabel.isHidden = true restartNode = self.scene?.childNode(withName: Consts.restart) restartNode.isHidden = true restartNode.alpha = 0.0 let board = [topLeft, topMiddle, topRight, middleLeft, center, middleRight, bottomLeft, bottomMiddle, bottomRight] let currentPlayer = scene?.humanOrAI() ?? .human self.scene?.gameBoard = Grid(gameboard: board, currentPlayer: currentPlayer) self.scene?.enumerateChildNodes(withName: "//grid*") { (node, stop) in if let node = node as? SKSpriteNode { node.removeAllChildren() } } } }
// // GMPresentationAnimator.swift // mab // // Created by Shuo Wang on 4/6/20. // Copyright © 2020 Shuo Wang. All rights reserved. // import UIKit /// Modal animation controller class GMPresentationAnimator: NSObject { private var isPresentation: Bool private var position: GMPresentationPosition private var alertSize: CGSize private var customY: CGFloat init(isPresentation: Bool, manager: GMPresentationManager) { self.isPresentation = isPresentation self.position = manager.position self.alertSize = manager.size self.customY = manager.customY super.init() } } extension GMPresentationAnimator: UIViewControllerAnimatedTransitioning { // set transition duration func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.32 } // set animation func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let key = isPresentation ? UITransitionContextViewControllerKey.to : UITransitionContextViewControllerKey.from guard let controller = transitionContext.viewController(forKey: key) else { return } if isPresentation { transitionContext.containerView.addSubview(controller.view) } let presentedFrame = transitionContext.finalFrame(for: controller) var dismissedFrame = presentedFrame switch position { case .top, .customY: dismissedFrame.origin.y = -alertSize.height case .center, .bottom: dismissedFrame.origin.y = transitionContext.containerView.frame.size.height } let initialFrame = isPresentation ? dismissedFrame : presentedFrame let finalFrame = isPresentation ? presentedFrame : dismissedFrame let animationDuration = transitionDuration(using: transitionContext) controller.view.frame = initialFrame UIView.animate(withDuration: animationDuration, animations: { controller.view.frame = finalFrame }) { (finished) in transitionContext.completeTransition(finished) } } }
/* The MIT License (MIT) Copyright (c) 2016 Bertrand Marlier 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 Foundation import Logger let log = Logger(withName: "Brokers") func nilIfZero<T: ExpressibleByIntegerLiteral & Equatable>(_ value: T) -> T? { return value == 0 ? nil : value } func nilIfZero<T: ExpressibleByIntegerLiteral & Equatable>(_ value: T?) -> T? { return value == 0 ? nil : value } public struct Timestamp { public typealias RawValue = UInt64 public let nanoSeconds: RawValue // Number of nanoseconds since January 1st, 1970 00:00 GMT public var rawValue: RawValue { return nanoSeconds } public init(rawValue: RawValue) { nanoSeconds = rawValue } public init(nanoSeconds value: RawValue) { nanoSeconds = value } public init(microSeconds value: UInt64) { self.init(nanoSeconds: value * 1_000) } public init(seconds value: UInt32) { self.init(nanoSeconds: UInt64(value) * 1_000_000_000) } public init(date: Date) { self.init(nanoSeconds: UInt64(date.timeIntervalSince1970 * 1_000_000_000)) } /** Expected format (RFC3339): "YYYY-MM-DDTHH:MM:SS+ZZ:zz" */ public init?(rfc3339: String) { let RFC3339DateFormatter = DateFormatter() RFC3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" guard let date = RFC3339DateFormatter.date(from: rfc3339) else { return nil } self.init(date: date) } public var date: Date { return Date(timeIntervalSince1970: Double(nanoSeconds)/Double(TimestampInterval.Second)) } /** eg: "yyyy-MM-dd'T'HH:mm:ssZZZZZ" */ public func format(_ format: String) -> String { let formatter = DateFormatter() formatter.dateFormat = format return formatter.string(from: date) } public static var now: Timestamp { return Timestamp(date: Date()) } public var seconds: UInt32 { return UInt32(nanoSeconds / 1_000_000_000) } public var microSeconds: UInt64 { return nanoSeconds / 1_000 } } extension Timestamp: Comparable { } extension Timestamp: Hashable { public var hashValue: Int { return nanoSeconds.hashValue } } /*extension Timestamp: CustomStringConvertible { public var description: String { return nanoSeconds.description } }*/ public struct TimestampInterval { static public let Zero = TimestampInterval(seconds: 0) static public let Second: Int64 = 1_000_000_000 static public let Hour: Int64 = 3600 * 1_000_000_000 static public let Day: Int64 = 24 * 3600 * 1_000_000_000 public let nanoSeconds: Int64 public init(nanoSeconds value: Int64) { nanoSeconds = value } public init(microSeconds value: Int64) { self.init(nanoSeconds: value * 1_000) } public init(milliSeconds value: Int64) { self.init(nanoSeconds: value * 1_000_000) } public init(seconds value: Int32) { self.init(nanoSeconds: Int64(value) * 1_000_000_000) } public var seconds: Int32 { return Int32(nanoSeconds / 1_000_000_000) } public var milliSeconds: Int64 { return nanoSeconds / 1_000_000 } public var microSeconds: Int64 { return nanoSeconds / 1_000 } /** eg: "%02d:%02d:%02d" */ public func format(_ formatString: String = "%02d:%02d:%02d") -> String { var remainingSeconds = nanoSeconds/1_000_000_000 let hours = remainingSeconds / 3600 remainingSeconds -= hours * 3600 let minutes = remainingSeconds / 60 remainingSeconds -= minutes * 60 return String(format: formatString, hours, minutes, remainingSeconds) } } extension TimestampInterval: CustomStringConvertible { public var description: String { var remainingSeconds = nanoSeconds/1_000_000_000 var result = "" let hours = remainingSeconds / 3600 if hours != 0 { remainingSeconds -= hours * 3600 result += "\(hours)h" } let minutes = remainingSeconds/60 if minutes != 0 { remainingSeconds -= minutes * 60 result += "\(minutes)m" } if remainingSeconds != 0 || (minutes == 0 && hours == 0) { result += "\(remainingSeconds)s" } return result } } public func ==(lhs: TimestampInterval, rhs: TimestampInterval) -> Bool { return lhs.nanoSeconds == rhs.nanoSeconds } public func <(lhs: TimestampInterval, rhs: TimestampInterval) -> Bool { return lhs.nanoSeconds < rhs.nanoSeconds } public func >(lhs: TimestampInterval, rhs: TimestampInterval) -> Bool { return lhs.nanoSeconds > rhs.nanoSeconds } public func <=(lhs: TimestampInterval, rhs: TimestampInterval) -> Bool { return lhs.nanoSeconds <= rhs.nanoSeconds } public func >=(lhs: TimestampInterval, rhs: TimestampInterval) -> Bool { return lhs.nanoSeconds >= rhs.nanoSeconds } public func -(lhs: Timestamp, rhs: Timestamp) -> TimestampInterval { return TimestampInterval(nanoSeconds: Int64(lhs.nanoSeconds) - Int64(rhs.nanoSeconds)) } public func -(lhs: Timestamp, rhs: TimestampInterval) -> Timestamp { return Timestamp(nanoSeconds: UInt64(Int64(lhs.nanoSeconds) - rhs.nanoSeconds)) } public func +(lhs: Timestamp, rhs: TimestampInterval) -> Timestamp { return Timestamp(nanoSeconds: UInt64(Int64(lhs.nanoSeconds) + rhs.nanoSeconds)) } public func +(lhs: TimestampInterval, rhs: TimestampInterval) -> TimestampInterval { return TimestampInterval(nanoSeconds: lhs.nanoSeconds + rhs.nanoSeconds) } public func -(lhs: TimestampInterval, rhs: TimestampInterval) -> TimestampInterval { return TimestampInterval(nanoSeconds: lhs.nanoSeconds - rhs.nanoSeconds) } public func <(lhs: Timestamp, rhs: Timestamp) -> Bool { return lhs.nanoSeconds < rhs.nanoSeconds } public func ==(lhs: Timestamp, rhs: Timestamp) -> Bool { return lhs.nanoSeconds == rhs.nanoSeconds } public typealias Amount = Double public typealias Price = Double extension Price: Priceable { public var price: Price { return self } } public protocol Priceable { var price: Price { get } } public protocol Tradeable: Priceable { var bid: Price { get } var ask: Price { get } } public protocol Dated { var time: Timestamp { get } } public func <(lhs: Dated, rhs: Dated) -> Bool { return lhs.time < rhs.time } public protocol Tickable: Tradeable, Dated { } extension Tickable { func translateBid(_ bid: Price) -> Tickable { return Tick(time: time, bid: bid, ask: bid + spread) } func translateAsk(_ ask: Price) -> Tickable { return Tick(time: time, bid: ask - spread, ask: ask) } public func entryPrice(toSide side: Side) -> Price { switch side { case .buy: return ask case .sell: return bid } } public func exitPrice(fromSide side: Side) -> Price { switch side { case .buy: return bid case .sell: return ask } } public func touches(stopLoss price: Price, atSide side: Side) -> Bool { switch side { case .sell: return ask >= price case .buy: return bid <= price } } public func touches(takeProfit price: Price, atSide side: Side) -> Bool { switch side { case .sell: return ask <= price case .buy: return bid >= price } } } extension Tradeable { public var spread: Price { return ask - bid } public var mean: Price { return (ask + bid)/2 } public var price: Price { return mean } } public struct BidAsk: Tradeable { public let bid: Price public let ask: Price public init(bid: Price, ask: Price) { self.bid = bid self.ask = ask } } public struct Tick: Tickable { public let time: Timestamp public let bid: Price public let ask: Price public init(time: Timestamp, bid: Price, ask: Price) { self.time = time self.bid = bid self.ask = ask } public var inverse: Tick { return Tick(time: time, bid: 1/ask, ask: 1/bid) } } public enum Currency: String { case AUD case CAD case CHF case CNH case CNY case CZK case DKK case EUR case GBP case HKD case HUF case INR case JPY case MXN case NOK case NZD case PLN case SAR case SEK case SGD case THB case TRY case TWD case USD case XAG case XAU case XCU case XPD case XPT case ZAR } /*public protocol Candle { typealias PriceType //typealias VolumeType var time: Timestamp { get } var open: PriceType { get } var high: PriceType { get } var low: PriceType { get } var close: PriceType { get } //var volume: VolumeType { get } }*/ open class Candle<PriceType:Priceable> : Priceable { open let time: Timestamp open let open: PriceType open let high: PriceType open let low: PriceType open let close: PriceType public init(time: Timestamp, open: PriceType, high: PriceType, low: PriceType, close: PriceType) { self.time = time self.open = open self.high = high self.low = low self.close = close } open var price: Price { return close.price } } open class CandleBidAsk: Candle<BidAsk>, Tickable { open var bid: Price { return close.bid } open var ask: Price { return close.ask } public override init(time: Timestamp, open: BidAsk, high: BidAsk, low: BidAsk, close: BidAsk) { super.init(time: time, open: open, high: high, low: low, close: close) } var naturalTickSequence: [Tickable] { var result: [Tickable] = [] result.append(Tick(time: time, bid: open.bid, ask: open.ask)) if close.mean > open.mean { result.append(Tick(time: time, bid: low.bid, ask: low.ask)) result.append(Tick(time: time, bid: high.bid, ask: high.ask)) } else if close.mean < open.mean { result.append(Tick(time: time, bid: high.bid, ask: high.ask)) result.append(Tick(time: time, bid: low.bid, ask: low.ask)) } else { log.warning("%f: arbitrary tick order: high then low") result.append(Tick(time: time, bid: high.bid, ask: high.ask)) result.append(Tick(time: time, bid: low.bid, ask: low.ask)) } result.append(Tick(time: time, bid: close.bid, ask: close.ask)) return result } } public protocol CandleBidAskListener { func onNewCandle(_ candle: CandleBidAsk) } public enum Granularity: String { case S5 case S10 case S30 case M1 case M2 case M3 case M4 case M5 case M10 case M15 case M30 case H1 case H2 case H3 case H4 case H6 case H8 case H12 case D case W case M }
// // UserCollectionViewCell.swift // att-hack // // Created by Cameron Moreau on 8/20/16. // Copyright © 2016 Kolten. All rights reserved. // import UIKit class UserCollectionViewCell: UICollectionViewCell { @IBOutlet weak var userImage: UIImageView! @IBOutlet weak var userName: UILabel! func animate(delay: NSTimeInterval) { let OG = userImage.frame.size userImage.frame = CGRectMake(OG.width / 2, OG.height / 2, 0, 0) UIView.animateWithDuration(0.25, delay: delay, usingSpringWithDamping: 0.4, initialSpringVelocity: 3, options: .CurveEaseIn, animations: { self.userImage.frame = CGRectMake(0, 0, OG.width, OG.height) }, completion: nil) } }
// // AddCoffeeViewController.swift // CoffeeNerd // // Created by Baptiste Leguey on 13/11/2017. // Copyright © 2017 Baptiste Leguey. All rights reserved. // import UIKit class AddCoffeeViewController: UIViewController, ClassNameable { var brewingMethodList: [BrewingMethod] = BrewingMethod.allValues var selectedCoffeeRecord: CoffeeRecord! @IBOutlet var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() collectionView.allowsMultipleSelection = true } override func viewWillAppear(_ animated: Bool) { self.navigationController?.setNavigationBarHidden(false, animated: false) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: IBActions @IBAction func cancelTapped(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBAction func doneTapped(_ sender: Any) { var hasOneMethodChosen = false for cell in collectionView.visibleCells { if cell.isSelected { hasOneMethodChosen = true } } if (hasOneMethodChosen) { CoffeeDatabase.shared.insertCoffee(withRecord: selectedCoffeeRecord) self.dismiss(animated: true, completion: nil) } else { print("you must choose a method") } } } extension AddCoffeeViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let brewingMethodRecord = BrewingMethodRecord(brewingMethod: brewingMethodList[indexPath.row], grinderSetting: nil, groundWeight: nil, waterWeight: nil, brewingTime: nil, notes: nil) selectedCoffeeRecord.add(brewingMethodRecord) } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { let brewingMethodRecord = BrewingMethodRecord(brewingMethod: brewingMethodList[indexPath.row], grinderSetting: nil, groundWeight: nil, waterWeight: nil, brewingTime: nil, notes: nil) selectedCoffeeRecord.remove(brewingMethodRecord) } } extension AddCoffeeViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return brewingMethodList.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: BrewingMethodCollectionViewCell.cellName, for: indexPath) as? BrewingMethodCollectionViewCell else { return UICollectionViewCell() } cell.configureCell(withBrewingMethod: brewingMethodList[indexPath.row]) return cell } }
// // Recipe+Comparable.swift // UserInterface // // Created by Fernando Moya de Rivas on 01/09/2019. // Copyright © 2019 Fernando Moya de Rivas. All rights reserved. // import Foundation import Domain extension Recipe: Comparable { public static func < (lhs: Recipe, rhs: Recipe) -> Bool { return lhs.title < rhs.title } public static func == (lhs: Recipe, rhs: Recipe) -> Bool { return lhs.title == rhs.title && lhs.imageUrl == rhs.imageUrl } }
// // This source file is part of the Apodini open source project // // SPDX-FileCopyrightText: 2019-2021 Paul Schmiedmayer and the Apodini project authors (see CONTRIBUTORS.md) <paul.schmiedmayer@tum.de> // // SPDX-License-Identifier: MIT // import Foundation import ApodiniContext public extension TypeInformation { /// A simplified enum of the `typeInformation` enum RootType: String, CustomStringConvertible, Codable { case scalar case repeated case dictionary case optional case `enum` case object case reference public var description: String { rawValue.upperFirst } } /// The root type of this `typeInformation` var rootType: RootType { switch self { case .scalar: return .scalar case .repeated: return .repeated case .dictionary: return .dictionary case .optional: return .optional case .enum: return .enum case .object: return .object case .reference: return .reference } } /// Indicates whether the root type is a scalar (primitive type) var isScalar: Bool { rootType == .scalar } /// Indicates whether the root type is a repeated type var isRepeated: Bool { rootType == .repeated } /// Indicates whether the root type is a dictionary var isDictionary: Bool { rootType == .dictionary } /// Indicates whether the root type is an optional var isOptional: Bool { rootType == .optional } /// Indicates whether the root type is an enum var isEnum: Bool { rootType == .enum } /// Indicates whether the root type is an object var isObject: Bool { rootType == .object } /// Indicates whether the root type is an enum or an object var isEnumOrObject: Bool { isEnum || isObject } /// Indicates whether the root type is a reference var isReference: Bool { rootType == .reference } /// If the root type is enum, returns `self`, otherwise the nested types are searched recursively var enumType: TypeInformation? { switch self { case let .repeated(element): return element.enumType case let .dictionary(_, value): return value.enumType case let .optional(wrappedValue): return wrappedValue.unwrapped.enumType case .enum: return self default: return nil } } /// If the root type is an object, returns `self`, otherwise the nested types are searched recursively var objectType: TypeInformation? { switch self { case let .repeated(element): return element.objectType case let .dictionary(_, value): return value.objectType case let .optional(wrappedValue): return wrappedValue.objectType case .object: return self default: return nil } } /// Returns the referenceKey of an nested reference var referenceKey: ReferenceKey? { if case let .reference(key) = reference { return key } return nil } /// Returns the nested reference if any. References can be stored inside repeated types, dictionaries, optionals, or at top level var reference: TypeInformation? { switch self { case let .repeated(element): return element.reference case let .dictionary(_, value): return value.reference case let .optional(wrappedValue): return wrappedValue.reference case .reference: return self default: return nil } } /// Indicates whether the nested or top level element is an object var elementIsObject: Bool { objectType != nil } /// Indicates whether the nested or top level element is an enum var elementIsEnum: Bool { enumType != nil } /// Indicates whether the nested or top level element is an enum or an object var isReferencable: Bool { elementIsObject || elementIsEnum } /// The typeName of this `typeInformation` /// results in fatal error if requested for a `.reference` var typeName: TypeName { switch self { case let .scalar(primitiveType): return primitiveType.typeName case let .repeated(element): return element.unwrapped.typeName case let .dictionary(_, value): return value.unwrapped.typeName case let .optional(wrappedValue): return wrappedValue.unwrapped.typeName case let .enum(name, _, _, _): return name case let .object(name, _, _): return name case .reference: fatalError("Cannot unwrap `TypeName` for the reference type \(self). Please dereference the type beforehand.") } } /// String representation of the type in a `Swift` compliant way, e.g. `User`, `User?`, `[String: User]` or `[User]` /// This computed property results in a fatalError if called for a `.reference`. var typeString: String { switch self { case let .scalar(primitiveType): return primitiveType.description case let .repeated(element): return "[\(element.typeString)]" case let .dictionary(key, value): return "[\(key.description): \(value.typeString)]" case let .optional(wrappedValue): return wrappedValue.typeString + "?" case .enum, .object, .reference: return typeName.buildName() } } /// Nested type string of this type information /// This computed property results in a fatalError if called for a `.reference`. var nestedTypeString: String { switch self { case .scalar, .enum, .object: return typeString case let .repeated(element): return element.nestedTypeString case let .dictionary(_, value): return value.nestedTypeString case let .optional(wrappedValue): return wrappedValue.unwrapped.nestedTypeString case let .reference(referenceKey): return referenceKey.rawValue } } /// Indicate whether `self` has the same root type with other `typeInformation` /// - Note: This method was replaced with ``comparingRootType(with:)` to more clearly communicate /// what this method actually does. @available(*, deprecated, renamed: "comparingRootType(with:)") func sameType(with typeInformation: TypeInformation) -> Bool { rootType == typeInformation.rootType } /// Indicate whether `self` has the same root type with other `typeInformation` func comparingRootType(with typeInformation: TypeInformation) -> Bool { rootType == typeInformation.rootType } /// Recursively unwraps the value of optional type if `self` is `.optional` var unwrapped: TypeInformation { if case let .optional(wrapped) = self { return wrapped.unwrapped } return self } /// Returns the dictionary key if `self` is `.dictionary` var dictionaryKey: PrimitiveType? { if case let .dictionary(key, _) = self { return key } return nil } /// Returns the dictionary value type if `self` is `.dictionary` var dictionaryValue: TypeInformation? { if case let .dictionary(_, value) = self { return value } return nil } /// Returns object properties if `self` is `.object`, otherwise an empty array var objectProperties: [TypeProperty] { switch self { case let .object(_, properties, _): return properties default: return objectType?.objectProperties ?? [] } } /// Returns enum cases if `self` is `.enum`, otherwise an empty array var enumCases: [EnumCase] { if case let .enum(_, _, cases, _) = self { return cases } return [] } /// Return rawValueType type if `self` is enum and enum has a raw value type. var rawValueType: TypeInformation? { if case let .enum(_, rawValueType, _, _) = self { return rawValueType } return nil } /// Wraps a type descriptor as an optional type. If already an optional, returns self var asOptional: TypeInformation { isOptional ? self : .optional(wrappedValue: self) } /// Retrieves the `Context` where parsed Metadata is stored of a ``TypeInformation`` instance. /// Returns nil for cases of ``TypeInformation`` which don't expose Metadata declaration blocks. var context: Context? { switch self { case let .object(_, _, context): return context case let .enum(_, _, _, context): return context default: return nil } } /// Recursively returns all types included in this `typeInformation`, e.g. primitive types, enums, objects /// and nested elements in repeated types, dictionaries and optionals func allTypes() -> [TypeInformation] { var allTypes: Set<TypeInformation> = [self] switch self { case let .repeated(element): allTypes += element.allTypes() case let .dictionary(key, value): allTypes += .scalar(key) + value.allTypes() case let .optional(wrappedValue): allTypes += wrappedValue.allTypes() case let .object(_, properties, _): allTypes += properties.flatMap { $0.type.allTypes() } default: break } return Array(allTypes) } /// Returns whether the typeInformation is contained in `allTypes()` of self func contains(_ typeInformation: TypeInformation?) -> Bool { guard let typeInformation = typeInformation else { return false } return allTypes().contains(typeInformation) } /// Returns whether the `self` is contained in `allTypes()` of `typeInformation` func isContained(in typeInformation: TypeInformation) -> Bool { typeInformation.contains(self) } /// Filters `allTypes()` by a boolean property of `TypeInformation` func filter(_ keyPath: KeyPath<TypeInformation, Bool>) -> [TypeInformation] { allTypes().filter { $0[keyPath: keyPath] } } /// Returns a version of self as a reference func asReference() -> TypeInformation { switch self { case .scalar: return self case let .repeated(element): return .repeated(element: element.asReference()) case let .dictionary(key, value): return .dictionary(key: key, value: value.asReference()) case let .optional(wrappedValue): return .optional(wrappedValue: wrappedValue.asReference()) case .enum, .object: return .reference(.init(typeName.buildName(componentSeparator: ".", genericsStart: "<", genericsSeparator: ",", genericsDelimiter: ">"))) case .reference: return self } } /// Returns the property with name `named` func property(_ named: String) -> TypeProperty? { objectProperties.first { $0.name == named } } /// If a object, types of object properties are changed to references func referencedProperties() -> TypeInformation { switch self { case .scalar, .enum: return self case let .repeated(element): return .repeated(element: element.referencedProperties()) case let .dictionary(key, value): return .dictionary(key: key, value: value.referencedProperties()) case let .optional(wrappedValue): return .optional(wrappedValue: wrappedValue.referencedProperties()) case let .object(typeName, properties, context): return .object( name: typeName, properties: properties.map { $0.referencedType() }, context: context ) case .reference: return self } } /// Returns all distinct scalars in `allTypes()` func scalars() -> [TypeInformation] { filter(\.isScalar) } /// Returns all distinct repeated types in `allTypes()` func repeatedTypes() -> [TypeInformation] { filter(\.isRepeated) } /// Returns all distinct dictionaries in `allTypes()` func dictionaries() -> [TypeInformation] { filter(\.isDictionary) } /// Returns all distinct optionals in `allTypes()` func optionals() -> [TypeInformation] { filter(\.isOptional) } /// Returns all distinct enums in `allTypes()` func enums() -> [TypeInformation] { filter(\.isEnum) } /// Returns all distinct objects in `allTypes()` func objectTypes() -> [TypeInformation] { filter(\.isObject) } /// Returns a reference with the given string key static func reference(_ key: String) -> TypeInformation { .reference(.init(key)) } }
// // ContentView.swift // Impfalarm // // Created by Jannik Feuerhahn on 04.06.21. // import SwiftUI struct ContentView: View { @ObservedObject var logic:Logic var body: some View { ZStack { NavigationView { ScrollViewReader { proxy in Form { if let error = logic.error { Section(header:Text("Fehler")) { HStack { Text(error) Spacer() Image(systemName: "xmark.octagon") .foregroundColor(.red) } } } if logic.deniedPushAuth { Section(header: Text("Berechtigung")) { HStack { Text("Sie haben der App die Berechtigung verweigert Pushnachrichten zu empfangen.") Spacer() Image(systemName: "exclamationmark.triangle") .foregroundColor(.yellow) } Button(action: { logic.openPushSettings() }, label: { Text("Einstellung öffnen") }) } } if logic.saved { Section(header: Text("Status")) { HStack { Text("Deine Daten wurden gespeichert. Du wirst benachrichtigt, sobald ein Impftermin frei ist.") Spacer() Image(systemName: "checkmark.icloud") .foregroundColor(.green) } } } Section(header: Text("Nutzerdaten")) { HStack { Text("Postleitzahl") Spacer() TextField("12345", text: $logic.zip) .keyboardType(.numberPad) .textFieldStyle(DefaultTextFieldStyle()) .multilineTextAlignment(.trailing) .foregroundColor(logic.saved ? Color(UIColor(named: "DisabledColor")!) : .primary) } Toggle("Alter über 60", isOn: $logic.ageOver60) .toggleStyle(SwitchToggleStyle(tint: Color(UIColor.systemBlue))) }.id(1) .disabled(logic.saved) Section(header: Text("Benachrichtigungen")) { Picker(selection: $logic.priorityIndex, label: Text("Frequenz")) { ForEach(0 ..< logic.priorityOptions.count) { Text(logic.priorityOptions[$0]) } } } .disabled(logic.saved) Section(header: Text("Impfstoffe")) { Toggle("AstraZeneca", isOn: $logic.allowAstra) .toggleStyle(SwitchToggleStyle(tint: Color(UIColor.systemBlue))) Toggle("BioNTech", isOn: $logic.allowBiontech) .toggleStyle(SwitchToggleStyle(tint: Color(UIColor.systemBlue))) Toggle("Johnson & Johnson", isOn: $logic.allowJohnson) .toggleStyle(SwitchToggleStyle(tint: Color(UIColor.systemBlue))) Toggle("Moderna", isOn: $logic.allowModerna) .toggleStyle(SwitchToggleStyle(tint: Color(UIColor.systemBlue))) } .disabled(logic.saved) Section { if !logic.saved { Button(action: { logic.subscribe() //Scroll to top proxy.scrollTo(1) UIApplication.shared.endEditing() }) { Text("Benachrichtigung aktivieren") }.disabled(logic.deniedPushAuth) } else { Button(action: { withAnimation { logic.unsubscribe() UIApplication.shared.endEditing() } }, label: { Text("Benachrichtigung deaktivieren") .foregroundColor(.red) }) } } } .navigationBarTitle("Impfalarm") } }.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in logic.checkForPushAuthorization() }.onAppear() { logic.checkForPushAuthorization() } if logic.loading { Rectangle() .foregroundColor(.init(white: 0, opacity: 0.2)) .ignoresSafeArea() ProgressView("Lädt...") } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView(logic: Logic()) } } }
// // BeaeModel.swift // FangZhiHuRiBao // // Created by chenming on 16/11/20. // Copyright © 2016年 chenxiaoming. All rights reserved. // import UIKit class BeaeModel: NSObject { init(dict: [String: AnyObject]) { super.init() setValuesForKeys(dict) } //防止对象属性和kvo时的dict的key 不匹配而崩溃 override func setValue(_ value: Any?, forUndefinedKey key: String) { } }
import Foundation import XcodeProj import XCTest class BuildPhaseTests: XCTestCase { func test_sources_hasTheCorrectRawValue() { XCTAssertEqual(BuildPhase.sources.rawValue, "Sources") } func test_frameworks_hasTheCorrectRawValue() { XCTAssertEqual(BuildPhase.frameworks.rawValue, "Frameworks") } func test_resources_hasTheCorrectRawValue() { XCTAssertEqual(BuildPhase.resources.rawValue, "Resources") } func test_copyFiles_hasTheCorrectRawValue() { XCTAssertEqual(BuildPhase.copyFiles.rawValue, "CopyFiles") } func test_runStript_hasTheCorrectRawValue() { XCTAssertEqual(BuildPhase.runScript.rawValue, "Run Script") } func test_headers_hasTheCorrectRawValue() { XCTAssertEqual(BuildPhase.headers.rawValue, "Headers") } func test_carbonResources_hasTheCorrectRawValue() { XCTAssertEqual(BuildPhase.carbonResources.rawValue, "Rez") } func test_sources_hasTheCorrectBuildPhase() { XCTAssertEqual(BuildPhase.sources, PBXSourcesBuildPhase().buildPhase) } func test_frameworks_hasTheCorrectBuildPhase() { XCTAssertEqual(BuildPhase.frameworks, PBXFrameworksBuildPhase().buildPhase) } func test_resources_hasTheCorrectBuildPhase() { XCTAssertEqual(BuildPhase.resources, PBXResourcesBuildPhase().buildPhase) } func test_copyFiles_hasTheCorrectBuildPhase() { XCTAssertEqual(BuildPhase.copyFiles, PBXCopyFilesBuildPhase().buildPhase) } func test_runStript_hasTheCorrectBuildPhase() { XCTAssertEqual(BuildPhase.runScript, PBXShellScriptBuildPhase().buildPhase) } func test_headers_hasTheCorrectBuildPhase() { XCTAssertEqual(BuildPhase.headers, PBXHeadersBuildPhase().buildPhase) } func test_carbonResources_hasTheCorrectBuildPhase() { XCTAssertEqual(BuildPhase.carbonResources, PBXRezBuildPhase().buildPhase) } }
// // NetworkManager.swift // HackerNews // // Created by David Mobley on 11/5/20. // import Foundation class NetworkManager: ObservableObject { @Published var posts = [Hit]() func fetchData() { // see: https://hn.algolia.com/api if let url = URL(string: "http://hn.algolia.com/api/v1/search?tags=front_page") { let session = URLSession(configuration: .default) let task = session.dataTask(with: url) { (data, response, error) in if (error != nil) { print("fetchData: ERROR: \(error!.localizedDescription)") //delegate?.didFailWithError(error: error!) return } if let safeData = data { do { let hackerNewsResults = try JSONDecoder().decode(HackerNewsModel.self, from: safeData) DispatchQueue.main.async { self.posts = hackerNewsResults.hits } } catch { print("fetchData: ERROR: \(error.localizedDescription)") } } else { print("ERROR: no data to parse") } } task.resume() } else { print("ERROR: url is empty") } } }
// ResRest.swift // SweetDeal import Foundation struct Rest: Decodable { let image_url: String? let name: String? let phone: String? let display_phone: String? let price: String? let rating: Float? let review_count: Int? let id: String? let dealIDs : [String]? let categories: [Title]? let coordinates: Coordinate? let hours: [Hour]? let location: Location? enum CodingKeys : String, CodingKey { case image_url case name case phone case display_phone case price case rating case review_count case categories case coordinates case hours case location case id case dealIDs } } struct Title: Decodable { let title: String? enum CodingKeys : String, CodingKey { case title } } struct Coordinate: Decodable { let latitude: Float? let longitude: Float? enum CodingKeys : String, CodingKey { case latitude case longitude } } struct Hour: Decodable { let day: Int? let start: String? let end: String? enum CodingKeys : String, CodingKey { case day case start case end } } struct Location: Decodable { let address1: String? let address2: String? let address3: String? let city: String? let state: String? let zipcode: String? let display_address: [String]? enum CodingKeys : String, CodingKey { case address1 case address2 case address3 case city case state case zipcode = "zip_code" case display_address } }
// // HomeController.swift // Jenin Residences // // Created by Ahmed Khalaf on 2/5/17. // Copyright © 2017 pxlshpr. All rights reserved. // import UIKit class HomeController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() } }
// // GoogleClient.swift // Travel Companion // // Created by Stefan Jaindl on 14.08.18. // Copyright © 2018 Stefan Jaindl. All rights reserved. // import CoreLocation import Foundation import RxSwift import shared // TODO: Can we move it to shared? class GoogleClient { static let sharedInstance = GoogleClient() private init() {} func autocomplete(input: String, token: String) -> Observable<[PlacesPredictions]> { if input.count < AutocompleteConfig.autocompletionMinChars { let filterStrings: [PlacesPredictions] = [] return Observable.from(optional: filterStrings) } let sharedClient = TCInjector.shared.googleClient let queryItems = sharedClient.buildAutoCompleteRequestParams(input: input, token: token) let urlComponents = GoogleConstants.UrlComponents() let url = WebClient.sharedInstance.createUrlWithKotlinQueryItems( forScheme: urlComponents.urlProtocol, forHost: urlComponents.domain, forMethod: urlComponents.pathAutocomplete, withQueryItems: queryItems ) let request = WebClient.sharedInstance.buildRequest(withUrl: url, withHttpMethod: WebConstants.ParameterKeys.httpGet) return WebClient.sharedInstance.taskForRxDataPlacesPredictionsWebRequest(with: request) { (data) in do { let decoder = JSONDecoder() let result = try decoder.decode(PlacesAutoCompleteResponse.self, from: data!) var filterStrings: [PlacesPredictions] = [] for prediction in (result.predictions) { filterStrings.append(prediction/* .description */) } return filterStrings } catch { print("Error: \(error)") return [] } } } func placeDetail(placeId: String, token: String) -> Observable<PlacesDetailsResponse?> { let sharedClient = TCInjector.shared.googleClient let queryItems = sharedClient.buildPlaceDetailRequestParams(placeId: placeId, token: token) let urlComponents = GoogleConstants.UrlComponents() let url = WebClient.sharedInstance.createUrlWithKotlinQueryItems( forScheme: urlComponents.urlProtocol, forHost: urlComponents.domain, forMethod: urlComponents.pathPlaceDetail, withQueryItems: queryItems ) let request = WebClient.sharedInstance.buildRequest(withUrl: url, withHttpMethod: WebConstants.ParameterKeys.httpGet) return WebClient.sharedInstance.taskForRxDataPlaceDetailsWebRequest(with: request) { (data) in do { let decoder = JSONDecoder() let result = try decoder.decode(PlacesDetailsResponse.self, from: data!) return result } catch { print("Error: \(error)") return nil } } } }
// // Item+Mapper.swift // GitXplore // // Created by Augusto Cesar do Nascimento dos Reis on 15/12/20. // import Foundation extension Item { func toItemDetail() -> ItemDetail { return ItemDetail( name: name, updatedAt: updatedAt?.dayMonthYearHourMinute, ownerLogin: owner?.login, language: language, avatarUrl: owner?.avatarUrl, createdAt: createdAt?.dayMonthYearHourMinute, licenseName: license?.name, forks: forks?.string, score: score?.string, watchers: watchers?.string, size: size?.string, url: url, pushedAt: pushedAt?.dayMonthYearHourMinute) } }
// // UartLogManager.swift // Calibration // // Created by Antonio García on 24/10/2016. // Copyright © 2016 Adafruit. All rights reserved. // import Foundation class UartLogManager { private static var kIsEnabled = false enum LogType { case info case uartTx case uartRx var description: String { switch self { case .info: return "" case .uartTx: return "sent" case .uartRx: return "received" } } } struct LogItem { var type = LogType.info var data: Data } static var logItems = [LogItem]() static func log(data: Data, type: LogType) { if UartLogManager.kIsEnabled { let item = LogItem(type: type, data: data) UartLogManager.logItems.append(item) } } static func log(message: String, type: LogType = .info) { if UartLogManager.kIsEnabled { if let data = message.data(using: .utf8) { let item = LogItem(type: type, data: data) UartLogManager.logItems.append(item) } } } static func clearLog() { UartLogManager.logItems.removeAll() } }
import Foundation /** https:adventofcode.com/2019/day/8 */ private struct Layer { let width: Int let content: [Int] init(with input: String, width: Int) { content = input.compactMap { $0.wholeNumberValue } self.width = width } init(with content: [Int], width: Int) { self.content = content self.width = width } var formattedOutput: String { var output = String(content.flatMap { String($0) }) for index in 0..<content.count / width { let index = String.Index(utf16Offset: index * (width + 1), in: output) output.insert("\n", at: index) } return output.replacingOccurrences(of: "0", with: "◾️") .replacingOccurrences(of: "1", with: "⬜️") .replacingOccurrences(of: "2", with: "🧊") } } enum Day08 { static let width = 25 static let height = 6 static var numberOfPixels: Int { width * height } static func solve() { let input = Input.get("08-Input.txt") print("Result Day 8 - Part One: \(parseImageDataForPart1(input: input))") print("Result Day 8 - Part Two: \(printImageDataForPart2(input: input))") } private static func parseImageDataForPart1(input: String) -> String { let layers = parseImageData(input) let layerWithFewestZeroDigits = layers.min { $0.content.filter { $0 == 0 }.count < $1.content.filter { $0 == 0 }.count }! let numberOfOneDigit = layerWithFewestZeroDigits.content.filter { $0 == 1 }.count let numberOfTwoDigit = layerWithFewestZeroDigits.content.filter { $0 == 2 }.count let result = numberOfOneDigit * numberOfTwoDigit assert(result == 1463) return String(result) } private static func printImageDataForPart2(input: String) -> String { let layers = parseImageData(input) var newContent: [Int] = [] for pixelIndex in 0..<numberOfPixels { let pixels = layers.map { $0.content[pixelIndex] } let outputPixel = pixels.first { $0 != 2 } ?? 2 newContent.append(outputPixel) } let result = Layer(with: newContent, width: width).formattedOutput let expectedResult = """ ◾️⬜️⬜️◾️◾️⬜️◾️◾️⬜️◾️◾️⬜️⬜️◾️◾️⬜️◾️◾️⬜️◾️⬜️◾️◾️⬜️◾️ ⬜️◾️◾️⬜️◾️⬜️◾️⬜️◾️◾️⬜️◾️◾️⬜️◾️⬜️◾️⬜️◾️◾️⬜️◾️◾️⬜️◾️ ⬜️◾️◾️◾️◾️⬜️⬜️◾️◾️◾️⬜️◾️◾️◾️◾️⬜️⬜️◾️◾️◾️⬜️⬜️⬜️⬜️◾️ ⬜️◾️⬜️⬜️◾️⬜️◾️⬜️◾️◾️⬜️◾️◾️◾️◾️⬜️◾️⬜️◾️◾️⬜️◾️◾️⬜️◾️ ⬜️◾️◾️⬜️◾️⬜️◾️⬜️◾️◾️⬜️◾️◾️⬜️◾️⬜️◾️⬜️◾️◾️⬜️◾️◾️⬜️◾️ ◾️⬜️⬜️⬜️◾️⬜️◾️◾️⬜️◾️◾️⬜️⬜️◾️◾️⬜️◾️◾️⬜️◾️⬜️◾️◾️⬜️◾️ """ assert(result == expectedResult) return result } } extension Day08 { private static func parseImageData(_ input: String) -> [Layer] { var input = input let lowerBound = String.Index(utf16Offset: 0, in: input) let upperBound = String.Index(utf16Offset: numberOfPixels, in: input) var formattedInput: [String] = [] for _ in 0..<input.count / numberOfPixels { let line = String(input[lowerBound..<upperBound]) formattedInput.append(line) input = String(input.dropFirst(numberOfPixels)) } return formattedInput.map { Layer(with: $0, width: width) } } }
// // RouterScreen.swift // Lesson__6_7_8_HW // // Created by admin on 06.11.2020. // import UIKit class RouterScreen :UIViewController { public static func switchToAddUserScreen(_ caller: UIViewController){ if let controller = getController(name: "scr5",storybordName: "Second") { controller.modalPresentationStyle = .fullScreen callViewC(caller,callee: controller) } } public static func switchToLoginScreen2(_ caller: UIViewController){ if let controller = getController(name: "scr4",storybordName: "Second") { controller.modalPresentationStyle = .fullScreen callViewC(caller,callee: controller) } } public static func switchToRegisterScreen2(_ caller: UIViewController){ if let controller = getController(name: "scr6",storybordName: "Second") { controller.modalPresentationStyle = .fullScreen callViewC(caller,callee: controller) } } public static func switchToLoginScreen(_ caller: UIViewController){ if let controller = getController(name: "scr3") { controller.modalPresentationStyle = .fullScreen callViewC(caller,callee: controller) } } public static func switchToRegisterScreen(_ caller: UIViewController){ if let controller = getController(name: "scr2") { controller.modalPresentationStyle = .fullScreen callViewC(caller,callee: controller) } } public static func switchToAppScreen(_ caller: UIViewController, mainLabelText: String){ if let controller = getController(name: "scr1") { (controller as? AppViewController)?.mainLableText = mainLabelText controller.modalPresentationStyle = .fullScreen callViewC(caller,callee: controller) } } private static func callViewC(_ caller: UIViewController,callee : UIViewController){ caller.present(callee, animated: true, completion: nil) } private static func getController(name : String , storybordName : String = "Main") -> UIViewController?{ let storyboard = UIStoryboard(name: storybordName, bundle:.main) // let registerScreen: UIViewController? if let registerScreen : UIViewController? = storyboard.instantiateViewController(identifier: name) { return registerScreen } return nil } }
// // TableViewController.swift // MemeMe2 // // Created by Jim Nording on 23/12/15. // Copyright © 2015 Jim Nording. All rights reserved. // import Foundation import UIKit class TableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! // Access to memes array in AppDelegate.swift let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate // View Lifecycle override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) tableView.reloadData() } override func viewDidLoad() { super.viewDidLoad() } // Table View Methods // Get number of rows from memes Array func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return appDelegate.memes.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("MemeTableCell")! as UITableViewCell let meme = appDelegate.memes[indexPath.row] cell.imageView?.image = meme.memedImage cell.textLabel?.text = meme.topText return cell } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let meme = appDelegate.memes[indexPath.row] let detailedController = storyboard?.instantiateViewControllerWithIdentifier("DetailedVC") as! DetailedViewController detailedController.meme = meme navigationController?.pushViewController(detailedController, animated: true) } // Enable Delete button when swiping func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if (editingStyle == UITableViewCellEditingStyle.Delete) { // Deletes meme from memes Array in AppDelegate appDelegate.memes.removeAtIndex(indexPath.row) // Removes cell from tableView tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } }
// // ContentView.swift // 00657025_hw3 // // Created by User23 on 2020/4/28. // Copyright © 2020 User23. All rights reserved. // import SwiftUI struct ContentView: View { @State private var showSecondPage = false @State private var isProfile = false @State private var gender = "Boy" let gend = ["Boy", "Girl"] @State private var name = "" @State private var birthday = Date() @State private var mood = 0 @State private var red: Double = 0 @State private var green: Double = 0 @State private var blue: Double = 0 @State private var showAlert = false var body: some View { VStack { if isProfile { Image(gender) .resizable() .scaledToFill() .frame(width: 200, height: 200) .clipped() } else { Image("person") .resizable() .scaledToFill() .frame(width: 200, height: 200) .clipped() } Form { Toggle("Do you want to show picture?", isOn: $isProfile) if isProfile { VStack(alignment: .leading) { Picker("Gender", selection: $gender) { ForEach(gend, id: \.self) { (gende) in Text(gende) } } .pickerStyle(SegmentedPickerStyle()) } } TextField("What's your Name?", text: $name) DatePicker("When is your birthday?", selection: $birthday, in: ...Date(), displayedComponents: .date) Stepper(value: $mood, in: -10...10) { if mood < -3 { Text("Mood: Upset") } else if mood > 3 { Text("Mood: Elated") } else { Text("Mood: Normal") } } chooseColor(red: $red, green: $green, blue: $blue) } Text("Your color") .font(.headline) .frame(width: 200, height: 100) .background(Color(red: red, green: green, blue: blue, opacity: 0.3)) Spacer() Button(action: {self.showSecondPage = true}) { Text("OK!") .font(.headline) .padding() .foregroundColor(.purple) .frame(width: 80, height: 50) .overlay(RoundedRectangle(cornerRadius: 20).stroke(Color.purple, lineWidth: 5)) } .sheet(isPresented: self.$showSecondPage) { SecondPage(showSecondPage: self.$showSecondPage, isProfile: self.$isProfile, gender: self.$gender, name: self.$name, birthday: self.$birthday, mood: self.$mood, red: self.$red, green: self.$green, blue: self.$blue) } } .background(Image("back1") .resizable() .scaledToFill() .opacity(0.7) .edgesIgnoringSafeArea(.all)) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } struct chooseColor: View { @Binding var red: Double @Binding var green: Double @Binding var blue: Double var body: some View { VStack { HStack { Text("Red") .foregroundColor(Color.red) Slider(value: $red, in: 0...1) .accentColor(.red) } HStack { Text("Green") .foregroundColor(Color.green) Slider(value: $green, in: 0...1) .accentColor(.green) } HStack { Text("Blue") .foregroundColor(Color.blue) Slider(value: $blue, in: 0...1) .accentColor(.blue) } } } }
// // Assets.swift // SwiftUI-Clean-Template // // Created by Julien Delferiere on 21/03/2021. // import SwiftUI enum Assets: String { case myAsset }
// // ViewController.swift // ASA // // Created by Infosys on 1/16/19. // Copyright © 2019 Infosys. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { let tableView = UITableView() let cells = ["Card Details" : [["type":"LabelNumber","title":"Card Number","value":"1234 5451 5624 2451","placeholder":"4215 4512 5484 2521"],["type":"LabelNumber","title":"CVV","value":"","placeholder":"458"],["type":"Picker","title":"Expiry","value":"","placeholder":"Mon/yyyy"],["type":"LabelString","title":"Name","value":"","placeholder":"Smith"]], "Address": [["type":"LabelString","title":"First Name","value":"","placeholder":"Johny"],["type":"LabelString","title":"Last Name","value":"","placeholder":"Bravo"],["type":"LabelPhoneNumber","title":"Phone Number","value1":"+91","value2":"8792362045","placeholder1":"+91","placeholder2":"99051436245"]]] var keys : Array<String>? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.addSubview(tableView) setupTableViewConstraints() registerTableViewCells() keys = Array(cells.keys) tableView.dataSource = self tableView.delegate = self } func setupTableViewConstraints(){ tableView.translatesAutoresizingMaskIntoConstraints = false tableView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true tableView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true tableView.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true tableView.heightAnchor.constraint(equalTo: self.view.heightAnchor).isActive = true } func registerTableViewCells(){ tableView.register(LabelNumberTableViewCell.self, forCellReuseIdentifier: "LabelNumber") tableView.register(LabelStringTableViewCell.self, forCellReuseIdentifier: "LabelString") tableView.register(PickerTableViewCell.self, forCellReuseIdentifier: "Picker") tableView.register(LabelPhoneNumberTableViewCell.self, forCellReuseIdentifier: "LabelPhoneNumber") } func numberOfSections(in tableView: UITableView) -> Int { return cells.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let key = keys![section] guard let count = cells[key]?.count else { return 0 } return count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let key = keys![indexPath.section] let type = cells[key]![indexPath.row]["type"] if let cell = tableView.dequeueReusableCell(withIdentifier: type!) as? ConfigureCellProtocol{ cell.configureCell(data: cells[key]![indexPath.row]) return cell as! UITableViewCell } return UITableViewCell() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return keys?[section] } } protocol ConfigureCellProtocol { func configureCell(data: [String:String]) }
// // QuizModel.swift // QuizCWC // // Created by Vitaliy Kurbatov on 02/02/2018. // Copyright © 2018 Vitaliy Kurbatov. All rights reserved. // import Foundation protocol QuizProtocol { func questionsRetrieved(questions:[Question]) } class QuizModel { var delegate:QuizProtocol? func getQuestions() { getRemoteJsonFile() } func getLocalJsonFile() { let path = Bundle.main.path(forResource: "QuestionData", ofType: ".json") guard path != nil else { print("No JSON File") return } let url = URL(fileURLWithPath: path!) do { let data = try Data(contentsOf: url) let decoder = JSONDecoder() let array = try decoder.decode([Question].self, from: data) delegate?.questionsRetrieved(questions: array) } catch { print("can't create data object from file") } } func getRemoteJsonFile() { // get a url obj fram a string let stringURL = "https://codewithchris.com/code/QuestionData.json" let url = URL(string: stringURL) guard url != nil else { print("error. couldnt get a URL Obj") return } let session = URLSession.shared // get a Datatask object let dataTask = session.dataTask(with: url!) { (data, response, error) in if error == nil && data != nil { let decoder = JSONDecoder() do { let array = try decoder.decode([Question].self, from: data!) DispatchQueue.main.async { self.delegate?.questionsRetrieved(questions: array) } } catch { print("Cant parse json") } } } dataTask.resume() } }
// // Instantiatable.swift // Item Lister // // Created by Cemil Kocaman on 19.01.2020. // Copyright © 2020 Cemil Kocaman Software. All rights reserved. // import UIKit protocol Instantiatable { static func instantiate() -> Self } extension Instantiatable where Self: StoryboardLoadable { /// Instantiates view controller whose identifier is its class name static func instantiate() -> Self { let storyboard = UIStoryboard(name: storyboardName.rawValue, bundle: nil) let identifier = String(describing: self) guard let viewController = storyboard.instantiateViewController(identifier: identifier) as? Self else { fatalError("Instantiation from storyboard failed!") } return viewController } }
// // Item.swift // example // // Created by Denis G. Kim on 24.07.2018. // Copyright © 2018 Denis G. Kim. All rights reserved. // import Foundation class Item: Codable { var name: String init(name: String) { self.name = name } }
// // BullEyeGameViewController.swift // Pruebas // // Created by Julio Banda on 12/2/18. // Copyright © 2018 Julio Banda. All rights reserved. // import UIKit class BullEyeGameViewController: UIViewController { @IBOutlet weak var slider: UISlider! @IBOutlet weak var scoreLabel: UILabel! @IBOutlet weak var targetLabel: UILabel! @IBOutlet weak var roundLabel: UILabel! var orientation = UIInterfaceOrientation.landscapeLeft.rawValue lazy var currentValue: Int = { return Int(slider.value.rounded()) }() var targetValue: Int = 0 { willSet { targetLabel.text = String(describing: newValue) } } var score: Int = 0 { willSet { scoreLabel.text = String(describing: newValue) } } var round: Int = 0 { willSet { roundLabel.text = String(describing: newValue) } } //MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.barStyle = .blackTranslucent customizeSlider() UIDevice.current.setValue(orientation, forKey: "orientation") startNewGame() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.navigationBar.barStyle = .default } @IBAction func sliderMoves (_ slider: UISlider) { print("The value of the slider is: \(slider.value)") let roundedValue: Float = slider.value.rounded() currentValue = Int(roundedValue) } @IBAction func showAlert(_ sender: UIButton) { let difference: Int = abs(targetValue - currentValue) var points: Int = 100 - difference let title: String if difference == 0 { title = "Perfect!" points += 100 } else if difference < 5 { title = "You almost had it!" if difference == 1 { points += 50 } } else if difference < 10 { title = "Pretty good!" } else { title = "Not even close" } let message: String = "You scored: \(points) points." let alert: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let action: UIAlertAction = UIAlertAction(title: "Ok", style: .default) { (_) in self.score += points self.startNewRound() } alert.addAction(action) present(alert, animated: true) } @IBAction func startOver(_ sender: UIButton) { startNewGame() } func startNewRound(){ round += 1 targetValue = makeNewTargetValue() currentValue = 50 slider.value = 50.0 } func makeNewTargetValue() -> Int { return Int.random(in: 0...100) } func startNewGame(){ self.score = 0 self.round = 0 self.startNewRound() } //MARK: - Customization func customizeSlider() { let thumbImageNormal: UIImage = #imageLiteral(resourceName: "SliderThumb-Normal") let thumbImageHightlighted: UIImage = #imageLiteral(resourceName: "SliderThumb-Highlighted") let insets: UIEdgeInsets = UIEdgeInsets(top: 0, left: 14, bottom: 0, right: 14) let trackLeftImage: UIImage = #imageLiteral(resourceName: "SliderTrackLeft") let trackLeftResizable = trackLeftImage.resizableImage(withCapInsets: insets) let trackRightImage: UIImage = #imageLiteral(resourceName: "SmallButton") let trackRightResizable = trackRightImage.resizableImage(withCapInsets: insets) slider.setThumbImage(thumbImageNormal, for: .normal) slider.setThumbImage(thumbImageHightlighted, for: .highlighted) slider.setMinimumTrackImage(trackLeftResizable, for: .normal) slider.setMaximumTrackImage(trackRightResizable, for: .normal) } //MARK: - View Orientation override var shouldAutorotate: Bool { return false } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { return .landscapeRight } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .landscape } }
// // VacationController.swift // TheHoneymoonPlanner // // Created by Jerry haaser on 2/7/20. // Copyright © 2020 Jonalynn Masters. All rights reserved. // import Foundation import UIKit import CoreData class VacationController { static let shared = VacationController() func createVacation(with cost: Double?, date_start: Date?, date_end: Date?, imageURL: URL?, latitude: Double?, longitude: Double?, location: String?, title: String, wishlist: [Wishlist]? = [], activities: [Activity]? = [], context: NSManagedObjectContext) { Vacation(cost: cost, date_start: date_start, date_end: date_end, imageURL: imageURL, latitude: latitude, longitude: longitude, location: location, title: title, context: context) saveToPersistentStore() } func update(_ vacation: Vacation, with cost: Double?, date_start: Date?, date_end: Date?, imageURL: URL?, latitude: Double?, longitude: Double?, location: String?, title: String, wishlist: [Wishlist]? = [], activities: [Activity]? = [], context: NSManagedObjectContext) { vacation.date_start = date_start vacation.date_end = date_end vacation.imageURL = imageURL vacation.title = title vacation.location = location if let cost = cost, let latitude = latitude, let longitude = longitude, let wishlist = wishlist, let activities = activities { vacation.cost = cost vacation.latitude = latitude vacation.longitude = longitude vacation.wishlist = NSOrderedSet(array: wishlist) vacation.activities = NSOrderedSet(array: activities) saveToPersistentStore() } } func delete(_ vacation: Vacation) { let moc = NSManagedObjectContext.context moc.delete(vacation) saveToPersistentStore() } func loadVacationFromPersistentStore() -> [Vacation] { let fetchRequest: NSFetchRequest<Vacation> = Vacation.fetchRequest() let moc = NSManagedObjectContext.context do { let wishlist = try moc.fetch(fetchRequest) return wishlist } catch { NSLog("Error fetching vacation: \(error)") return [] } } func saveToPersistentStore() { let moc = NSManagedObjectContext.context do { try moc.save() } catch { NSLog("Error saving from vacaton controller: \(error)") moc.reset() } } }
// // OnCreateUserListener.swift // FirebaseCRUDExample // // Created by Luis Sergio da Silva Junior on 06/02/17. // Copyright © 2017 Luis Sergio. All rights reserved. // import Foundation public protocol OnCreateUserProtocol{ func getNewUser() -> User func createNewUser() }
// // MovieCollectionViewCell.swift // MovieDBJobAssignment // // Created by Zin Min on 15/01/2020. // Copyright © 2020 Zin Min. All rights reserved. // import UIKit class MovieCollectionViewCell: UICollectionViewCell { @IBOutlet weak var movieImage: UIImageView! @IBOutlet weak var movieName: UILabel! override func awakeFromNib() { super.awakeFromNib() movieImage.layer.cornerRadius = 10 movieImage.layer.masksToBounds = true } }
// // OutfitViewController.swift // Looksie // // Created by Alex Fu on 5/15/15. // Copyright (c) 2015 Alex Fu. All rights reserved. // import UIKit class OutfitViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = self collectionView.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 8 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ItemCell", forIndexPath: indexPath) as! ItemCell let index = indexPath.item % 4 + 1 cell.photoView.image = UIImage(named: "Outfit Shot \(index)") return cell } }
// // QuestionsStorage.swift // Who Wants to Be a Millionaire? // // Created by Микаэл Мартиросян on 21.03.2021. // import Foundation class QuestionsStorage { static let shared = QuestionsStorage() private(set) var questions: [QuestionsStruct] = [QuestionsStruct(question: "При каком императоре было отменено крепостное право в России?", answers: ["Александр III", "Петр I", "Николай I", "Александр II"], correctAnswer: "Александр II"), QuestionsStruct(question: "Какая страна не граничит с Россией?", answers: ["Северная Корея", "Польша", "Германия", "США"], correctAnswer: "Германия"), QuestionsStruct(question: "Какого цвета волк?", answers: ["Серого", "Голубого", "Зеленого", "Желтого"], correctAnswer: "Серого"), QuestionsStruct(question: "Как умер Пушкин?", answers: ["От простуды", "В дуэли", "От отравления", "От смеха"], correctAnswer: "В дуэли"), QuestionsStruct(question: "Как называется спутник Земли?", answers: ["Астероид", "Солнце", "Нептун", "Луна"], correctAnswer: "Луна") ] private init() {} func addQuestion(question: [QuestionsStruct]) { self.questions.append(contentsOf: question) } }
// // ProductDetailsViewModel.swift // B&W // // Created by Dalia on 19/09/2020. // Copyright © 2020 Artemis Simple Solutions Ltd. All rights reserved. // import Foundation protocol ProductDetailsViewModelInput { func updateImage() } protocol ProductDetailsViewModelOutput { var name: String { get } var image: Observable<Data?> { get } var description: String { get } var price: String { get } } protocol ProductDetailsViewModel: ProductDetailsViewModelInput, ProductDetailsViewModelOutput { } final class DefaultProductDetailsViewModel: ProductDetailsViewModel { private let imagePath: String? private let imagesRepository: ImagesRepository private var imageLoadTask: Cancellable? { willSet { imageLoadTask?.cancel() } } let name: String let image: Observable<Data?> = Observable(nil) let description: String let price: String init(product: Product, imagesRepository: ImagesRepository) { self.name = product.name ?? "" self.description = product.description ?? "" self.imagePath = product.imagePath self.price = product.price ?? "" self.imagesRepository = imagesRepository } } extension DefaultProductDetailsViewModel { func updateImage() { guard let imagePath = imagePath else { return } imageLoadTask = imagesRepository.fetchImage(with: imagePath) { result in guard self.imagePath == imagePath else { return } switch result { case .success(let data): self.image.value = data case .failure: break } self.imageLoadTask = nil } } }
// // VAction.swift // TG // // Created by Andrii Narinian on 8/7/17. // Copyright © 2017 ROLIQUE. All rights reserved. // import Foundation import SwiftyJSON extension FActionModel { convenience init(json: JSON) { let action = ActionType.create(with: json) ?? .Unknown self.init(action: action) } } class ActionModel: VModel { var name: String? var url: String? var actionId: String? var timeStamp: String? var payload: [String: Any]? var playerName: String? var playerId: String? var gold: Int? var lifetimeGold: Int? var remainingGold: Int? var level: Int? var price: Int? var damage: Int? var expAmount: Int? var deltDamage: Int? var isHero: Int? var targetIsHero: Int? var sharedWithCount: Int? var position: [Double]? var targetPosition: [Double]? var swaps: [Swap]? var actorIdentifier: String? var actor: Actor? { guard let id = actorIdentifier else { return nil } return Actor(id: id, type: .actor) } var targetActorIdentifier: String? var targetActor: Actor? { guard let id = targetActorIdentifier else { return nil } return Actor(id: id, type: .actor) } var skinIdentifier: String? var skin: Skin? { guard let id = skinIdentifier else { return nil } return Skin(id: id, type: .skin) } var sideString: String? var side: Side? { return Side(string: sideString) } var targetSideString: String? var targetSide: Side? { return Side(string: targetSideString) } var abilityString: String? var ability: Ability? { guard let id = abilityString else { return nil } return Ability(id: id, type: .ability) } required init(json: JSON, included: [VModel]? = nil) { super.init(json: json, included: included) decode(json) } override var encoded: [String : Any?] { let dict: [String: Any?] = [ "type": type, "id": id, "url": url, "name": name, "actionId": actionId, "timeStamp": timeStamp, "payload": payload, "playerName": playerName, "playerId": playerId, "gold": gold, "lifetimeGold": lifetimeGold, "remainingGold": remainingGold, "level": level, "price": price, "damage": damage, "expAmount": expAmount, "deltDamage": deltDamage, "isHero": isHero, "targetIsHero": targetIsHero, "sharedWithCount": sharedWithCount, "swaps": swaps?.map { $0.encoded }, "position": position, "targetPosition": targetPosition, "actor": actor?.encoded, "targetActor": targetActor?.encoded, "skin": skin?.encoded, "side": side?.identifier, "targetSide": targetSide?.identifier, "ability": ability?.encoded ] return dict } private func decode(_ json: JSON) { id = json["id"].string type = "Action" name = json["name"].string url = json["url"].string actionId = json["type"].string timeStamp = json["time"].string payload = json["payload"].dictionaryObject playerId = json["payload"]["Player"].string swaps = json["payload"].arrayValue.map { Swap(json: $0) } gold = json["payload"]["Gold"].int lifetimeGold = json["payload"]["url"].int remainingGold = json["payload"]["url"].int level = json["payload"]["url"].int price = json["payload"]["url"].int damage = json["payload"]["url"].int expAmount = json["payload"]["url"].int deltDamage = json["payload"]["url"].int isHero = json["payload"]["url"].int targetIsHero = json["payload"]["url"].int sharedWithCount = json["payload"]["url"].int position = json["payload"]["url"].arrayObject as? [Double] targetPosition = json["payload"]["url"].arrayObject as? [Double] actorIdentifier = json["payload"]["url"].string targetActorIdentifier = json["payload"]["Hero"].string skinIdentifier = json["payload"]["url"].string sideString = json["payload"]["url"].string targetSideString = json["payload"]["url"].string abilityString = json["payload"]["url"].string } } extension ActionType { static func create(with json: JSON) -> ActionType? { guard let id = json["type"].string else { return nil } let time = json["time"].stringValue.dateFromISO8601 ?? .now switch id { case "HeroSwap": let jsonArray = json["payload"].arrayValue let swaps = jsonArray.map { Swap(json: $0) } return ActionType.HeroSwap(time: time, swaps: swaps) case "GoldFromGoldMine": let actor = Actor(id: json["payload"]["Actor"].stringValue, type: .actor) let side = Side(string: json["payload"]["Team"].string) let amount = json["payload"]["Amount"].intValue return ActionType.GoldFromGoldMine(time: time, side: side, actor: actor, amount: amount) case "GoldFromTowerKill": let actor = Actor(id: json["payload"]["Actor"].stringValue, type: .actor) let side = Side(string: json["payload"]["Team"].string) let amount = json["payload"]["Amount"].intValue return ActionType.GoldFromTowerKill(time: time, side: side, actor: actor, amount: amount) case "GoldFromKrakenKill": let actor = Actor(id: json["payload"]["Actor"].stringValue, type: .actor) let side = Side(string: json["payload"]["Team"].string) let amount = json["payload"]["Amount"].intValue return ActionType.GoldFromKrakenKill(time: time, side: side, actor: actor, amount: amount) case "DealDamage": let actor = Actor(id: json["payload"]["Actor"].stringValue, type: .actor) let target = Actor(id: json["payload"]["Target"].stringValue, type: .actor) let side = Side(string: json["payload"]["Team"].string) let source = json["payload"]["Source"].stringValue let damage = json["payload"]["Damage"].intValue let delt = json["payload"]["Delt"].intValue let isHero = json["payload"]["IsHero"].intValue == 1 let targetIsHero = json["payload"]["TargetIsHero"].intValue == 1 return ActionType.DealDamage(time: time, side: side, actor: actor, target: target, source: source, damage: damage, delt: delt, isHero: isHero, targetIsHero: targetIsHero) case "NPCkillNPC": let actor = Actor(id: json["payload"]["Actor"].stringValue, type: .actor) let killed = Actor(id: json["payload"]["Killed"].stringValue, type: .actor) let side = Side(string: json["payload"]["Team"].string) let gold = Int(json["payload"]["Gold"].stringValue) ?? 0 let killedTeam = json["payload"]["KilledTeam"].stringValue let isHero = json["payload"]["IsHero"].intValue == 1 let targetIsHero = json["payload"]["TargetIsHero"].intValue == 1 let position = Position(json: json["payload"]["Position"]) return ActionType.NPCkillNPC(time: time, side: side, actor: actor, killed: killed, killedTeam: killedTeam, gold: gold, isHero: isHero, targetIsHero: targetIsHero, position: position) case "KillActor": let actor = Actor(id: json["payload"]["Actor"].stringValue, type: .actor) let killed = Actor(id: json["payload"]["Killed"].stringValue, type: .actor) let side = Side(string: json["payload"]["Team"].string) let gold = Int(json["payload"]["Gold"].stringValue) ?? 0 let killedTeam = json["payload"]["KilledTeam"].stringValue let isHero = json["payload"]["IsHero"].intValue == 1 let targetIsHero = json["payload"]["TargetIsHero"].intValue == 1 let position = Position(json: json["payload"]["Position"]) return ActionType.KillActor(time: time, side: side, actor: actor, killed: killed, killedTeam: killedTeam, gold: gold, isHero: isHero, targetIsHero: targetIsHero, position: position) case "Executed": let actor = Actor(id: json["payload"]["Actor"].stringValue, type: .actor) let killed = Actor(id: json["payload"]["Killed"].stringValue, type: .actor) let side = Side(string: json["payload"]["Team"].string) let gold = Int(json["payload"]["Gold"].stringValue) ?? 0 let killedTeam = json["payload"]["KilledTeam"].stringValue let isHero = json["payload"]["IsHero"].intValue == 1 let targetIsHero = json["payload"]["TargetIsHero"].intValue == 1 let position = Position(json: json["payload"]["Position"]) return ActionType.Executed(time: time, side: side, actor: actor, killed: killed, killedTeam: killedTeam, gold: gold, isHero: isHero, targetIsHero: targetIsHero, position: position) case "EarnXP": let actor = Actor(id: json["payload"]["Actor"].stringValue, type: .actor) let source = Actor(id: json["payload"]["Source"].stringValue, type: .actor) let side = Side(string: json["payload"]["Team"].string) let amount = json["payload"]["Amount"].intValue let sharedWith = json["payload"]["Shared With"].intValue return ActionType.EarnXP(time: time, side: side, actor: actor, source: source, amount: amount, sharedWith: sharedWith) case "LearnAbility": let actor = Actor(id: json["payload"]["Actor"].stringValue, type: .actor) let ability = Ability(id: json["payload"]["Ability"].stringValue, type: .ability) let side = Side(string: json["payload"]["Team"].string) let level = json["payload"]["Level"].intValue return ActionType.LearnAbility(time: time, side: side, actor: actor, ability: ability, level: level) case "UseAbility": let actor = Actor(id: json["payload"]["Actor"].stringValue, type: .actor) let targetActor = Actor(id: json["payload"]["TargetActor"].stringValue, type: .actor) let ability = Ability(id: json["payload"]["Ability"].stringValue, type: .ability) let side = Side(string: json["payload"]["Team"].string) let position = Position(json: json["payload"]["Position"]) let targetPosition = Position(json: json["payload"]["TargetPosition"]) return ActionType.UseAbility(time: time, side: side, actor: actor, ability: ability, position: position, targetActor: targetActor, targetPosition: targetPosition) case "UseItemAbility": let actor = Actor(id: json["payload"]["Actor"].stringValue, type: .actor) let targetActor = Actor(id: json["payload"]["TargetActor"].stringValue, type: .actor) let ability = Ability(id: json["payload"]["Ability"].stringValue, type: .ability) let side = Side(string: json["payload"]["Team"].string) let position = Position(json: json["payload"]["Position"]) let targetPosition = Position(json: json["payload"]["TargetPosition"]) return ActionType.UseItemAbility(time: time, side: side, actor: actor, ability: ability, position: position, targetActor: targetActor, targetPosition: targetPosition) case "BuyItem": let actor = Actor(id: json["payload"]["Actor"].stringValue, type: .actor) let item = Item(id: json["payload"]["Item"].stringValue, type: .item) let side = Side(string: json["payload"]["Team"].string) let price = json["payload"]["Cost"].intValue let remainingGold = json["payload"]["RemainingGold"].intValue let position = Position(json: json["payload"]["Position"]) return ActionType.BuyItem(time: time, side: side, actor: actor, item: item, price: price, remainingGold: remainingGold, position: position) case "SellItem": let actor = Actor(id: json["payload"]["Actor"].stringValue, type: .actor) let item = Item(id: json["payload"]["Item"].stringValue, type: .item) let side = Side(string: json["payload"]["Team"].string) let price = json["payload"]["Cost"].intValue return ActionType.SellItem(time: time, side: side, actor: actor, item: item, price: price) case "LevelUp": let actor = Actor(id: json["payload"]["Actor"].stringValue, type: .actor) let level = json["payload"]["Level"].intValue let gold = json["payload"]["LifetimeGold"].intValue let side = Side(string: json["payload"]["Team"].string) return ActionType.LevelUp(time: time, side: side, actor: actor, level: level, gold: gold) case "PlayerFirstSpawn": let side = Side(string: json["payload"]["Team"].string) return ActionType.PlayerFirstSpawn(time: time, side: side) case "HeroBan": let actor = Actor(id: json["payload"]["Hero"].stringValue, type: .actor) let side = Side(string: json["payload"]["Team"].string) return ActionType.HeroBan(time: time, actor: actor, side: side) case "HeroSelect": let actor = Actor(id: json["payload"]["Hero"].stringValue, type: .actor) let playerId = json["payload"]["Player"].stringValue let playerName = json["payload"]["Handle"].stringValue let side = Side(string: json["payload"]["Team"].string) return ActionType.HeroSelect(time: time, actor: actor, side: side, playerId: playerId, playerName: playerName) case "HeroSkinSelect": let actor = Actor(id: json["payload"]["Hero"].stringValue, type: .actor) let skin = Skin(id: json["payload"]["Skin"].stringValue, type: .skin) return ActionType.HeroSkinSelect(time: time, actor: actor, skin: skin) default: print("found unhandled action: \(id)") return nil } } }
// // Note.swift // ForestNotes // // Created by Eleven Fifty on 5/31/15. // Copyright (c) 2015 Forest Gafford. All rights reserved. // import UIKit class Note: NSObject, NSCoding { var title = "" var text = "" var date = NSDate() // no value is actually assigned so therefor there is no issue here with it. var dateString : String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MM/dd/yyyy" return dateFormatter.stringFromDate(date) } override init() { super.init() } init(title: String, text: String) { self.title = title self.text = text } required init(coder aDecoder: NSCoder) { self.title = aDecoder.decodeObjectForKey("title") as! String self.text = aDecoder.decodeObjectForKey("text") as! String self.date = aDecoder.decodeObjectForKey("date") as! NSDate } func encodeWithCoder(aCoder : NSCoder){ aCoder.encodeObject(title, forKey: "title") aCoder.encodeObject(text, forKey: "text") aCoder.encodeObject(date, forKey: "date") } }
// // ConnectionManager+DownloadTask.swift // TestAlamofire // // Created by CN320 on 5/2/17. // Copyright © 2017 CN320. All rights reserved. // import Foundation import Alamofire extension ConnectionManager { class func downloadFile(urlString : String? ,fileName: String?, downloadFilePath:String?, completion: @escaping (_ result: Any?, _ error : Error?) -> Void) { guard self.validateURL(urlString: urlString) else { completion(nil, NSError(domain: "Invalid url String", code: 0, userInfo: nil)) return } let _ = self.getDownloadTask(urlString : urlString! , fileName: fileName, downloadFilePath:downloadFilePath, methodType : .get, parameters:nil, headerInfo:nil, shouldStartImmediately : true, progress: nil){ (data, er) in completion(data,er) } } class func getDownloadTask(urlString : String , fileName: String?, downloadFilePath:String?, methodType : HTTPMethod?, parameters:Dictionary<String,Any>?, headerInfo:HTTPHeaders?, shouldStartImmediately : Bool, progress: ((_ downloadProgress : Progress?)->Void)? , completion: @escaping (_ result: Any?, _ error : Error?) -> Void) ->DownloadRequest? { let destination = ConnectionManager.getDestination(urlString : urlString, fileName : fileName, downloadFilePath :downloadFilePath) var downloadRequest : DownloadRequest? let mType:HTTPMethod = methodType ?? .get downloadRequest = Alamofire.download( urlString, method: mType, parameters: parameters, encoding: JSONEncoding.default, headers: nil, to: destination) .downloadProgress(closure: { (progress) in // Progress Completion block DispatchQueue.main.async { print (progress.totalUnitCount) print (progress.completedUnitCount) } }).response(completionHandler: { (DefaultDownloadResponse) in completion(DefaultDownloadResponse.destinationURL,DefaultDownloadResponse.error) }) if(shouldStartImmediately) { downloadRequest?.resume() } return downloadRequest } class func getDestination(urlString : String , fileName: String?, downloadFilePath:String?) -> DownloadRequest.DownloadFileDestination { let destination: DownloadRequest.DownloadFileDestination = { _, _ in let pathComponent : String var downloadPath : URL? if(fileName == nil || fileName?.getFullyTrimmedStringLength() == 0) { let date = NSDate() let filePathExtension = (urlString as NSString).pathExtension var timeIntervalString = String(format:"%f", date.timeIntervalSince1970) timeIntervalString = timeIntervalString.replacingOccurrences(of: ".", with: "") pathComponent = "File_Downloaded_T" + timeIntervalString + "." + filePathExtension } else { pathComponent = fileName! } if(downloadFilePath == nil || downloadFilePath?.getFullyTrimmedStringLength() == 0) { downloadPath = CustomFileManager.downloadDataFolderPath() } else { downloadPath = CustomFileManager.downloadDataFolderPath(subDir: downloadFilePath!) } let filePathURL = downloadPath?.appendingPathComponent(pathComponent) return (filePathURL!, [.removePreviousFile, .createIntermediateDirectories]) } return destination } }
// // EnigmaRotorView.swift // iEnigma // // Created by Leo Mehlig on 4/18/15. // Copyright (c) 2015 Leonard Mehlig. All rights reserved. // import UIKit @IBDesignable class EnigmaRotorLayer: CALayer { var crogs: Int = 23 { didSet { self.setNeedsDisplay() } } var lineWidth: CGFloat = 3 { didSet { self.setNeedsDisplay() } } var margin: CGFloat = 3 { didSet { self.setNeedsDisplay() } } var strokeColor: UIColor = Constants.Design.Colors.Text { didSet { self.setNeedsDisplay() } } var fillColor: UIColor = Constants.Design.Colors.Foreground { didSet { self.setNeedsDisplay() } } override func drawInContext(ctx: CGContext!) { let points = gearWheelPointsForRect(bounds) if !points.inner.isEmpty && !points.outter.isEmpty { UIGraphicsPushContext(ctx) let path = UIBezierPath() path.moveToPoint(points.inner.first!) var isOutter = false for (idx, innerPoint) in enumerate(points.inner) { if idx >= points.outter.count { break } let outterPoint = points.outter[idx] if isOutter { path.addLineToPoint(outterPoint) path.addLineToPoint(innerPoint) isOutter = false } else { path.addLineToPoint(innerPoint) path.addLineToPoint(outterPoint) isOutter = true } } path.closePath() path.lineWidth = lineWidth strokeColor.setStroke() fillColor.setFill() path.stroke() path.fill() UIGraphicsPopContext() } super.drawInContext(ctx) } var radius: (CGFloat, CGFloat) { let outterRadius: CGFloat = min(bounds.height / 2, bounds.width / 2) - borderWidth - margin let innerRadius: CGFloat = outterRadius - outterRadius / 10 return (outterRadius, innerRadius) } private func tanDeg(x: CGFloat) -> CGFloat { return tan(x / CGFloat(180 / M_PI)) } private func calcPoints(mA: CGFloat, mB: CGFloat, a: CGPoint, b: CGPoint) -> (CGPoint, CGPoint) { let x = (mB * b.x - mA * a.x + a.y - b.y) / (mB - mA) let x1 = 2 * a.x - x let y = -(mA * x1 - mA * a.x - a.y) let p1 = CGPoint(x: x, y: y) let p2 = CGPoint(x: x1, y: y) return (p1, p2) } private func gearWheelPointsForRect(rect: CGRect) -> (inner: [CGPoint], outter: [CGPoint]){ let viewCenter = CGPoint(x: rect.midX, y: rect.midY) let points: Int if crogs < 10 { points = 10 } else if crogs % 2 == 1 { points = crogs + 1 } else { points = crogs } let (outterRadius, innerRadius) = radius let innerA = CGPoint(x: viewCenter.x, y: viewCenter.y - innerRadius) let outterA = CGPoint(x: viewCenter.x, y: viewCenter.y - outterRadius) let angle = 360 / CGFloat(points) var innerPoints = [innerA] var outterPoints = [outterA] for i in 1...points/2 { let n = angle * CGFloat(i) if n >= 180 { innerPoints.append(CGPoint(x: viewCenter.x, y: viewCenter.y + innerRadius)) outterPoints.append(CGPoint(x: viewCenter.x, y: viewCenter.y + outterRadius)) } else { let angleA = tanDeg(-90 + ((180 - n) / 2)) let angleB = tanDeg(90 - n) let p = calcPoints(angleA, mB: angleB, a: innerA, b: viewCenter) innerPoints.insert(p.0, atIndex: 0) innerPoints.append(p.1) let largeP = calcPoints(angleA, mB: angleB, a: outterA, b: viewCenter) outterPoints.insert(largeP.0, atIndex: 0) outterPoints.append(largeP.1) } } return (innerPoints, outterPoints) } }
// // Date+Extension.swift // ObjcTools // // Created by douhuo on 2021/2/18. // Copyright © 2021 wangergang. All rights reserved. // import UIKit extension Date { /// 获取当前 秒级 时间戳 - 10位 var currentTimeStamp : Int { let timeInterval: TimeInterval = self.timeIntervalSince1970 let timeStamp = Int(timeInterval) return timeStamp } /// 获取当前 毫秒级 时间戳 - 13位 var currentMilliStamp : String { let timeInterval: TimeInterval = self.timeIntervalSince1970 let millisecond = CLongLong(round(timeInterval*1000)) return "\(millisecond)" } }
// // DetailViewController.swift // ExchangeRates // // Created by Andrey Novikov on 9/7/20. // Copyright © 2020 Andrey Novikov. All rights reserved. // import UIKit import Combine class DetailViewController: UIViewController { // MARK: - Public properties var presenter: DetailPresenterProtocol? // MARK: - Private properties private var selectedRate: Rate? private var rates: [Rate]? private var timeIntervalRates: [Rate]? private var collectionView: UICollectionView! private var dataSource: UICollectionViewDiffableDataSource<DetailSectionType, Rate>! enum DetailSectionType: Int, CaseIterable { case detailCell case dayCell } // MARK: - Live cycle override func viewDidLoad() { super.viewDidLoad() presenter?.getRate() presenter?.getRates() presenter?.getRequestsTimeInterval(withRateInterval: RateInterval()) setupNavigationController() setupCollectionView() setupDataSource() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupNavigationController() } // MARK: - Private methods private func reloadData() { var snapshot = NSDiffableDataSourceSnapshot<DetailSectionType, Rate>.init() snapshot.appendSections(DetailSectionType.allCases) snapshot.appendItems(rates ?? [], toSection: .detailCell) snapshot.appendItems(timeIntervalRates ?? [], toSection: .dayCell) dataSource.apply(snapshot) } } // MARK: - Setup extension DetailViewController { private func setupNavigationController() { navigationController?.navigationBar.topItem?.title = "" navigationItem.title = selectedRate?.name } private func setupCollectionView() { collectionView = UICollectionView(frame: view.frame, collectionViewLayout: UICollectionViewFlowLayout()) collectionView.autoresizingMask = [.flexibleWidth, .flexibleWidth] collectionView.backgroundColor = .backgroundBlack collectionView.collectionViewLayout = setupCompositionalLayout() collectionView.delegate = self collectionView.register(DetailRateCell.self, forCellWithReuseIdentifier: DetailRateCell.reuseId) collectionView.register(DayCell.self, forCellWithReuseIdentifier: DayCell.reuseId) collectionView.register(GraphFooterView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: GraphFooterView.reuseId) view.addSubview(collectionView) } private func setupCompositionalLayout() -> UICollectionViewLayout { let layout = UICollectionViewCompositionalLayout { (section, enviroment) -> NSCollectionLayoutSection? in guard let section = DetailSectionType(rawValue: section) else { return nil } switch section { case .detailCell: return self.setupDetailSection() case .dayCell: return self.setupDaySection() } } return layout } private func setupDetailSection() -> NSCollectionLayoutSection { let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1)) let item = NSCollectionLayoutItem(layoutSize: itemSize) item.contentInsets.leading = 10 let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1 / 1.2), heightDimension: .absolute(80)) let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item]) group.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 10) let section = NSCollectionLayoutSection(group: group) section.orthogonalScrollingBehavior = .groupPaging section.interGroupSpacing = 10 section.contentInsets.top = 10 section.contentInsets.bottom = 16 return section } private func setupDaySection() -> NSCollectionLayoutSection { let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1 / 6), heightDimension: .fractionalHeight(1)) let item = NSCollectionLayoutItem(layoutSize: itemSize) item.contentInsets.leading = 16 let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(50)) let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item]) let section = NSCollectionLayoutSection(group: group) let footerView = setupBoundarySupplementaryItemForDetailSection() section.boundarySupplementaryItems = [footerView] section.orthogonalScrollingBehavior = .continuous section.contentInsets.bottom = 10 return section } private func setupBoundarySupplementaryItemForDetailSection() -> NSCollectionLayoutBoundarySupplementaryItem { let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalWidth(1)) let item = NSCollectionLayoutBoundarySupplementaryItem(layoutSize: itemSize, elementKind: UICollectionView.elementKindSectionFooter, alignment: .bottom) return item } private func setupDataSource() { dataSource = UICollectionViewDiffableDataSource<DetailSectionType, Rate>.init(collectionView: collectionView, cellProvider: { (collectionView, indexPath, rate) -> UICollectionViewCell? in guard let section = DetailSectionType(rawValue: indexPath.section) else { return nil } switch section { case .detailCell: return collectionView.dequeuCell(withValue: rate, forIndexPath: indexPath, ofType: DetailRateCell.self) case .dayCell: return collectionView.dequeuCell(withValue: rate, forIndexPath: indexPath, ofType: DayCell.self) } }) dataSource.supplementaryViewProvider = { (collectionView, kind, indexPath) -> UICollectionReusableView? in let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: GraphFooterView.reuseId, for: indexPath) as? GraphFooterView footerView?.configure(withRate: self.selectedRate) return footerView } reloadData() } } // MARK: - UICollectionViewDelegate extension DetailViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let section = DetailSectionType(rawValue: indexPath.section) else { return } guard let rate = dataSource.itemIdentifier(for: indexPath) else { return } guard let rates = rates else { return } switch section { case .detailCell: presenter?.didSelectRate(rates: rates, selectedRate: rate) case .dayCell: print(indexPath) } } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let section = DetailSectionType(rawValue: indexPath.section) else { return } switch section { case .detailCell: break case .dayCell: let dayCell = collectionView.cellForItem(at: indexPath) as? DayCell if indexPath.item == 0 { dayCell?.isSelected = true } } } } // MARK: - DetailViewProtocol extension DetailViewController: DetailViewProtocol { func setRate(_ rate: Rate) { self.selectedRate = rate } func setRates(_ rates: [Rate]) { self.rates = rates } func setRequestsTimeInterval(_ rates: [Rate]) { self.timeIntervalRates = rates } }
// // File.swift // // // Created by Guerson on 2020-07-21. // import Foundation enum IndexesType { case indexes case deletions }
// // AppDelegate.swift // CKCCApp // // Created by Bun Leap on 11/12/18. // Copyright © 2018 Cambodia-Korea Cooperation Center. All rights reserved. // import UIKit import Firebase import FBSDKCoreKit import GoogleMaps @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) GMSServices.provideAPIKey("AIzaSyBQgfKfLnagAH8RMh5KtgLIckt5fcNg7bs") return true } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { let handled: Bool = FBSDKApplicationDelegate.sharedInstance().application(app, open: url, options: options) return handled } }
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @testable import SKCore import Basic import Utility import XCTest import POSIX final class ToolchainRegistryTests: XCTestCase { func testDefaultBasic() { let tr = ToolchainRegistry() XCTAssertNil(tr.default) tr.registerToolchain(Toolchain(identifier: "a", displayName: "a", path: nil)) XCTAssertEqual(tr.default?.identifier, "a") tr.registerToolchain(Toolchain(identifier: "b", displayName: "b", path: nil), isDefault: true) XCTAssertEqual(tr.default?.identifier, "b") tr.setDefaultToolchain(identifier: "a") XCTAssertEqual(tr.default?.identifier, "a") tr.setDefaultToolchain(identifier: nil) XCTAssertNil(tr.default) } func testDefaultDarwin() { let prevPlatform = Platform.currentPlatform defer { Platform.currentPlatform = prevPlatform } Platform.currentPlatform = .darwin let tr = ToolchainRegistry() XCTAssertNil(tr.default) tr.registerToolchain(Toolchain(identifier: "a", displayName: "a", path: nil)) XCTAssertEqual(tr.default?.identifier, "a") tr.registerToolchain(Toolchain(identifier: ToolchainRegistry.darwinDefaultToolchainID, displayName: "a", path: nil)) XCTAssertEqual(tr.default?.identifier, "a") tr.setDefaultToolchain(identifier: nil) tr.updateDefaultToolchainIfNeeded() XCTAssertEqual(tr.default?.identifier, ToolchainRegistry.darwinDefaultToolchainID) } func testUnknownPlatform() { let prevPlatform = Platform.currentPlatform defer { Platform.currentPlatform = prevPlatform } Platform.currentPlatform = nil let fs = InMemoryFileSystem() let makeToolchain = { (binPath: AbsolutePath) in let libPath = binPath.parentDirectory.appending(component: "lib") try! fs.createDirectory(libPath, recursive: true) try! fs.writeFileContents(libPath.appending(components: "libsourcekitdInProc.so") , bytes: "") } let binPath = AbsolutePath("/foo/bar/my_toolchain/bin") makeToolchain(binPath) guard let t = Toolchain(identifier: "a", displayName: "b", searchForTools: binPath, fileSystem: fs) else { XCTFail("could not find any tools") return } XCTAssertNotNil(t.sourcekitd) } func testSearchDarwin() { // FIXME: requires PropertyListEncoder #if os(macOS) let prevPlatform = Platform.currentPlatform defer { Platform.currentPlatform = prevPlatform } Platform.currentPlatform = .darwin let fs = InMemoryFileSystem() let tr = ToolchainRegistry(fileSystem: fs) let xcodeDeveloper = tr.currentXcodeDeveloperPath! let toolchains = xcodeDeveloper.appending(components: "Toolchains") let makeToolchain = { (id: String, opensource: Bool, path: AbsolutePath) in let skpath: AbsolutePath = path.appending(components: "usr", "lib", "sourcekitd.framework") try! fs.createDirectory(skpath, recursive: true) try! fs.writeFileContents(skpath.appending(component: "sourcekitd"), bytes: "") let infoPlistPath = path.appending(component: opensource ? "Info.plist" : "ToolchainInfo.plist") let infoPlist = try! PropertyListEncoder().encode(XCToolchainPlist(identifier: id, displayName: "name-\(id)")) try! fs.writeFileContents(infoPlistPath, body: { stream in stream.write(infoPlist) }) } makeToolchain(ToolchainRegistry.darwinDefaultToolchainID, false, toolchains.appending(component: "XcodeDefault.xctoolchain")) XCTAssertNil(tr.default) XCTAssert(tr.toolchains.isEmpty) tr.scanForToolchains() XCTAssertEqual(tr.default?.identifier, ToolchainRegistry.darwinDefaultToolchainID) XCTAssertEqual(tr.default?.path, toolchains.appending(component: "XcodeDefault.xctoolchain")) XCTAssertNotNil(tr.default?.sourcekitd) XCTAssertEqual(tr.toolchains.count, 1) let defaultToolchain = tr.default! XCTAssert(tr.toolchains.first?.value === defaultToolchain) tr.scanForToolchains() XCTAssertEqual(tr.toolchains.count, 1) XCTAssert(tr.default === defaultToolchain) makeToolchain("com.apple.fake.A", false, toolchains.appending(component: "A.xctoolchain")) makeToolchain("com.apple.fake.B", false, toolchains.appending(component: "B.xctoolchain")) tr.scanForToolchains() XCTAssertEqual(tr.toolchains.count, 3) makeToolchain("com.apple.fake.C", false, toolchains.appending(component: "C.wrong_extension")) makeToolchain("com.apple.fake.D", false, toolchains.appending(component: "D_no_extension")) tr.scanForToolchains() XCTAssertEqual(tr.toolchains.count, 3) makeToolchain("com.apple.fake.A", false, toolchains.appending(component: "E.xctoolchain")) tr.scanForToolchains() XCTAssertEqual(tr.toolchains.count, 3) makeToolchain("org.fake.global.A", true, AbsolutePath("/Library/Developer/Toolchains/A.xctoolchain")) makeToolchain("org.fake.global.B", true, AbsolutePath(expandingTilde: "~/Library/Developer/Toolchains/B.xctoolchain")) tr.scanForToolchains() XCTAssertEqual(tr.toolchains.count, 5) #endif } func testSearchPATH() { let fs = InMemoryFileSystem() let tr = ToolchainRegistry(fileSystem: fs) let makeToolchain = { (binPath: AbsolutePath) in let libPath = binPath.parentDirectory.appending(component: "lib") try! fs.createDirectory(binPath, recursive: true) try! fs.createDirectory(libPath.appending(component: "sourcekitd.framework"), recursive: true) try! fs.writeFileContents(libPath.appending(components: "sourcekitd.framework", "sourcekitd") , bytes: "") } let binPath = AbsolutePath("/foo/bar/my_toolchain/bin") makeToolchain(binPath) XCTAssertNil(tr.default) XCTAssert(tr.toolchains.isEmpty) try! setenv("SOURCEKIT_PATH", value: "/bogus:\(binPath.asString):/bogus2") defer { try! setenv("SOURCEKIT_PATH", value: "") } tr.scanForToolchains() guard case (_, let tc)? = tr.toolchains.first(where: { _, value in value.path == binPath }) else { XCTFail("couldn't find expected toolchain") return } XCTAssertEqual(tr.default?.identifier, tc.identifier) XCTAssertEqual(tc.identifier, binPath.asString) XCTAssertNil(tc.clang) XCTAssertNil(tc.clangd) XCTAssertNil(tc.swiftc) XCTAssertNotNil(tc.sourcekitd) XCTAssertNil(tc.libIndexStore) } func testSearchExplicitEnv() { let fs = InMemoryFileSystem() let tr = ToolchainRegistry(fileSystem: fs) let makeToolchain = { (binPath: AbsolutePath) in let libPath = binPath.parentDirectory.appending(component: "lib") try! fs.createDirectory(binPath, recursive: true) try! fs.createDirectory(libPath.appending(component: "sourcekitd.framework"), recursive: true) try! fs.writeFileContents(libPath.appending(components: "sourcekitd.framework", "sourcekitd") , bytes: "") } let binPath = AbsolutePath("/foo/bar/my_toolchain/bin") makeToolchain(binPath) XCTAssertNil(tr.default) XCTAssert(tr.toolchains.isEmpty) try! setenv("SOURCEKIT_TOOLCHAIN_PATH", value: binPath.parentDirectory.asString) defer { try! setenv("SOURCEKIT_TOOLCHAIN_PATH", value: "") } tr.scanForToolchains() guard case (_, let tc)? = tr.toolchains.first(where: { _, value in value.path == binPath.parentDirectory }) else { XCTFail("couldn't find expected toolchain") return } XCTAssertEqual(tr.default?.identifier, tc.identifier) XCTAssertEqual(tc.identifier, binPath.parentDirectory.asString) XCTAssertNil(tc.clang) XCTAssertNil(tc.clangd) XCTAssertNil(tc.swiftc) XCTAssertNotNil(tc.sourcekitd) XCTAssertNil(tc.libIndexStore) } func testFromDirectory() { // This test uses the real file system because the in-memory system doesn't support marking files executable. let fs = localFileSystem let tempDir = try! TemporaryDirectory(removeTreeOnDeinit: true) let path = tempDir.path.appending(components: "A.xctoolchain", "usr") try! fs.createDirectory(path.appending(component: "bin"), recursive: true) try! fs.createDirectory(path.appending(components: "lib", "sourcekitd.framework"), recursive: true) try! fs.writeFileContents(path.appending(components: "bin", "clang") , bytes: "") try! fs.writeFileContents(path.appending(components: "bin", "clangd") , bytes: "") try! fs.writeFileContents(path.appending(components: "bin", "swiftc") , bytes: "") try! fs.writeFileContents(path.appending(components: "bin", "other") , bytes: "") try! fs.writeFileContents(path.appending(components: "lib", "sourcekitd.framework", "sourcekitd") , bytes: "") let t1 = Toolchain(identifier: "a", displayName: "b", xctoolchainPath: path.parentDirectory, fileSystem: fs) XCTAssertNotNil(t1.sourcekitd) XCTAssertNil(t1.clang) XCTAssertNil(t1.clangd) XCTAssertNil(t1.swiftc) func chmodRX(_ path: AbsolutePath) { XCTAssertEqual(chmod(path.asString, S_IRUSR | S_IXUSR), 0) } chmodRX(path.appending(components: "bin", "clang")) chmodRX(path.appending(components: "bin", "clangd")) chmodRX(path.appending(components: "bin", "swiftc")) chmodRX(path.appending(components: "bin", "other")) let t2 = Toolchain(identifier: "a", displayName: "b", xctoolchainPath: path.parentDirectory, fileSystem: fs) XCTAssertNotNil(t2.sourcekitd) XCTAssertNotNil(t2.clang) XCTAssertNotNil(t2.clangd) XCTAssertNotNil(t2.swiftc) } func testDylibNames() { let fs = InMemoryFileSystem() let ext = Platform.currentPlatform?.dynamicLibraryExtension ?? "so" let makeToolchain = { (binPath: AbsolutePath) in let libPath = binPath.parentDirectory.appending(component: "lib") try! fs.createDirectory(libPath, recursive: true) try! fs.writeFileContents(libPath.appending(component: "libsourcekitdInProc.\(ext)") , bytes: "") try! fs.writeFileContents(libPath.appending(component: "libIndexStore.\(ext)") , bytes: "") } let binPath = AbsolutePath("/foo/bar/my_toolchain/bin") makeToolchain(binPath) guard let t = Toolchain(identifier: "a", displayName: "b", searchForTools: binPath, fileSystem: fs) else { XCTFail("could not find any tools") return } XCTAssertNotNil(t.sourcekitd) XCTAssertNotNil(t.libIndexStore) } func testSubDirs() { let fs = InMemoryFileSystem() let makeToolchain = { (binPath: AbsolutePath) in let libPath = binPath.parentDirectory.appending(component: "lib") try! fs.createDirectory(libPath.appending(component: "sourcekitd.framework"), recursive: true) try! fs.writeFileContents(libPath.appending(components: "sourcekitd.framework", "sourcekitd") , bytes: "") } makeToolchain(AbsolutePath("/t1/bin")) makeToolchain(AbsolutePath("/t2/usr/bin")) XCTAssertNotNil(Toolchain(identifier: "a", displayName: "b", searchForTools: AbsolutePath("/t1"), fileSystem: fs)) XCTAssertNotNil(Toolchain(identifier: "a", displayName: "b", searchForTools: AbsolutePath("/t1/bin"), fileSystem: fs)) XCTAssertNotNil(Toolchain(identifier: "a", displayName: "b", searchForTools: AbsolutePath("/t2"), fileSystem: fs)) XCTAssertNil(Toolchain(identifier: "a", displayName: "b", searchForTools: AbsolutePath("/t3"), fileSystem: fs)) try! fs.createDirectory(AbsolutePath("/t3/bin"), recursive: true) try! fs.createDirectory(AbsolutePath("/t3/lib/sourcekitd.framework"), recursive: true) XCTAssertNil(Toolchain(identifier: "a", displayName: "b", searchForTools: AbsolutePath("/t3"), fileSystem: fs)) makeToolchain(AbsolutePath("/t3/bin")) XCTAssertNotNil(Toolchain(identifier: "a", displayName: "b", searchForTools: AbsolutePath("/t3"), fileSystem: fs)) } static var allTests = [ ("testDefaultBasic", testDefaultBasic), ("testDefaultDarwin", testDefaultDarwin), ("testUnknownPlatform", testUnknownPlatform), ("testSearchDarwin", testSearchDarwin), ("testSearchPATH", testSearchPATH), ("testFromDirectory", testFromDirectory), ] }
// // YGListCell.swift // CardSJD // // Created by X on 16/9/12. // Copyright © 2016年 QS. All rights reserved. // import UIKit class YGListCell: UITableViewCell { @IBOutlet var img: UIImageView! @IBOutlet var name: UILabel! @IBOutlet var tel: UILabel! var model:YuangongModel? { didSet { name.text = model?.truename tel.text = model?.mobile } } override func layoutSubviews() { super.layoutSubviews() self.setHighlighted(false, animated: false) } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
// // AppDelegate.swift // ForceUpdate // // Created by Active Mac05 on 11/02/16. // Copyright © 2016 techactive. All rights reserved. // import UIKit import SwiftyJSON @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { isNewUpdateAvailable() // Override point for customization after application launch. return true } func isNewUpdateAvailable(){ let url = iTunesURLFromString() let request = NSMutableURLRequest(URL: url) let session = NSURLSession.sharedSession() session.sendSynchronousRequest(request) { data, response, error in guard data != nil else { return } // print(String(data: data!, encoding: NSUTF8StringEncoding)) let json = JSON(data: data!) let version = json["results"][0]["version"].stringValue print("the current appstore version is \(version)") let currentBuildVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String print("the current debugging version is \(currentBuildVersion)") if self.isAppStoreVersionNewer(currentBuildVersion, currentAppStoreVersion: version) { dispatch_async(dispatch_get_main_queue(), { () -> Void in if self.window?.rootViewController?.presentedViewController is UIAlertController { self.window?.rootViewController?.presentedViewController?.dismissViewControllerAnimated(false, completion: nil) } let alertController = UIAlertController(title: "", message: "A newer version \(version) \nis Available", preferredStyle: .Alert) alertController.addAction(self.updateAlertAction()) self.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil) }) } } } func updateAlertAction() -> UIAlertAction { let action = UIAlertAction(title: "Update", style: .Default) { (alert: UIAlertAction) -> Void in let iTunesString = "https://itunes.apple.com/app/id\(1068737983)" let iTunesURL = NSURL(string: iTunesString) UIApplication.sharedApplication().openURL(iTunesURL!) return } return action } func iTunesURLFromString() -> NSURL { let appID = 1068737983 var countryCode: String? var storeURLString = "https://itunes.apple.com/lookup?id=\(appID)" countryCode = "in" if let countryCode = countryCode { storeURLString += "&country=\(countryCode)" } print("[Siren] iTunes Lookup URL: \(storeURLString)") return NSURL(string: storeURLString)! } func isAppStoreVersionNewer(currentInstalledVersion : String?, currentAppStoreVersion : String?) -> Bool { var newVersionExists = false print("currentInstalledVersion = \(currentInstalledVersion) and currentAppStoreVersion = \(currentAppStoreVersion)") if let currentInstalledVersion = currentInstalledVersion, currentAppStoreVersion = currentAppStoreVersion { if (currentInstalledVersion.compare(currentAppStoreVersion, options: .NumericSearch) == NSComparisonResult.OrderedAscending) { newVersionExists = true } } return newVersionExists } func applicationWillResignActive(application: UIApplication) { if self.window?.rootViewController?.presentedViewController is UIAlertController { self.window?.rootViewController?.presentedViewController?.dismissViewControllerAnimated(false, completion: nil) } // 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 throttle down OpenGL ES frame rates. 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) { isNewUpdateAvailable() // Called as part of the transition from the background to the inactive 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:. } }
// // GraphView.swift // Calculator // // Created by Stephan Thordal Larsen on 08/07/15. // Copyright (c) 2015 Stephan Thordal. All rights reserved. // import UIKit protocol GraphDataSource { func yForX(xValue: CGFloat) -> CGFloat? } @IBDesignable class GraphView: UIView { var dataSource: GraphDataSource? private let axesDrawer = AxesDrawer() var origin: CGPoint? = nil { didSet{ setNeedsDisplay() } } @IBInspectable var scale: CGFloat = 1 { didSet { setNeedsDisplay() } } @IBInspectable var axesColor: UIColor = UIColor.blackColor() { didSet { setNeedsDisplay() } } override func drawRect(rect: CGRect) { if origin == nil { origin = CGPoint(x: (rect.midX), y: (rect.midY )) } lastDataPoint = nil axesDrawer.color = axesColor axesDrawer.contentScaleFactor = contentScaleFactor axesDrawer.drawAxesInRect(rect, origin: origin!, pointsPerUnit: scale) let xVals = calculateXVals(origin!, rectWidth: rect.width) print(xVals.count) drawGraph(xVals, rect: rect) } private func calculateXVals(origin: CGPoint, rectWidth: CGFloat) -> [CGFloat] { var xVals = [CGFloat]() for(var i : CGFloat = 0; i < rectWidth; i++) { //var newXVal = i*scaling //*someotherconstanct <------AA, more datapoints! let newXVal = (i - origin.x) * 1/scale xVals.append(newXVal) } return xVals } private func drawGraph(xValues: [CGFloat], rect: CGRect) { var remainingXValues = xValues if remainingXValues.count <= 0 { return } let xVal = remainingXValues.removeLast() if let yVal = dataSource?.yForX(xVal) { let scaledYVal = yVal * scale let scaledXVal = xVal * scale drawDataPoint(xValue: scaledXVal, yValue: scaledYVal, origin: origin!, rect: rect) } drawGraph(remainingXValues, rect: rect) } var lastDataPoint: CGPoint? = nil private func drawDataPoint(#xValue: CGFloat, yValue: CGFloat, origin: CGPoint, rect: CGRect) { //TODO: Draw point in graph //Make up for origin location here! var dataPoint = origin dataPoint.x += xValue dataPoint.y -= yValue if lastDataPoint != nil { let path = UIBezierPath() path.moveToPoint(lastDataPoint!) path.addLineToPoint(dataPoint) path.stroke() } lastDataPoint = dataPoint } func scale(gesture: UIPinchGestureRecognizer) { if gesture.state == .Changed { scale *= gesture.scale gesture.scale = 1 } } func pan(gesture: UIPanGestureRecognizer) { switch gesture.state { case .Ended: fallthrough case .Changed: let translation = gesture.translationInView(self) origin!.y += translation.y origin!.x += translation.x gesture.setTranslation(CGPointZero, inView: self) setNeedsDisplay() default: break } } func tap(gesture: UITapGestureRecognizer) { if gesture.state == .Ended { let tapPoint = gesture.locationInView(self) origin = tapPoint } } }
// // Constants.swift // GithubFollowers // // Created by matt_spb on 21.05.2020. // Copyright © 2020 matt_spb_dev. All rights reserved. // import Foundation enum SFSymbols { static let location = "mappin.and.ellipse" }
// // KeyboardKeyPopupTypeController.swift // KeyboardKit // // Created by Valentin Shergin on 1/18/16. // Copyright © 2016 AnchorFree. All rights reserved. // import UIKit internal final class KeyboardKeyPopupTypeController: KeyboardKeyListenerProtocol { let popupShowEvents: UIControlEvents = [.TouchDown, .TouchDragInside, .TouchDragEnter] let popupHideEvents: UIControlEvents = [.TouchDragExit, .TouchCancel] let popupDelayedHideEvents: UIControlEvents = [.TouchUpInside, .TouchUpOutside, .TouchDragOutside] internal init() { } internal func keyViewDidSendEvents(controlEvents: UIControlEvents, keyView: KeyboardKeyView, key: KeyboardKey, keyboardMode: KeyboardMode) { let appearance = keyView.appearance if key.alternateKeys != nil { if popupShowEvents.contains(controlEvents) { self.setTimeout(keyView.hashValue) { KeyboardSoundService.sharedInstance.playAlternateInputSound() keyView.keyMode.popupMode = .AlternateKeys keyView.updateIfNeeded() } } } if popupHideEvents.contains(controlEvents) || popupDelayedHideEvents.contains(controlEvents) { self.clearTimeout() } if appearance.shouldShowPreviewPopup && keyView.keyMode.popupMode == .None && popupShowEvents.contains(controlEvents) { self.showPopupForKeyView(keyView) return } if keyView.keyMode.popupMode != .None && popupHideEvents.contains(controlEvents) { self.hidePopupForKeyView(keyView) return } if keyView.keyMode.popupMode != .None && popupDelayedHideEvents.contains(controlEvents) { let delay = 0.05 let when = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * NSTimeInterval(NSEC_PER_SEC))) dispatch_after(when, dispatch_get_main_queue()) { [weak self] in self?.hidePopupForKeyView(keyView) } return } } private func showPopupForKeyView(keyView: KeyboardKeyView) { keyView.keyMode.popupMode = .Preview keyView.updateIfNeeded() } private func hidePopupForKeyView(keyView: KeyboardKeyView) { keyView.keyMode.popupMode = .None keyView.updateIfNeeded() } private var timeoutToken: Int? func setTimeout(token: Int?, callback: () -> ()) { guard token != self.timeoutToken else { return } self.clearTimeout() self.timeoutToken = token let timeoutToken = token let delay = 0.7 let when = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * NSTimeInterval(NSEC_PER_SEC))) dispatch_after(when, dispatch_get_main_queue()) { [weak weakSelf = self] in guard let strongSelf = weakSelf else { return } guard strongSelf.timeoutToken == timeoutToken else { return } callback() } } func clearTimeout() { self.timeoutToken = nil } } extension UIControlEvents { internal static let LongPress = UIControlEvents(rawValue: 0x01000000) internal static let VeryLongPress = UIControlEvents(rawValue: 0x02000000) } extension KeyboardKeyListenerProtocol { internal func handleLongPresses(controlEvents: UIControlEvents, keyView: KeyboardKeyView, key: KeyboardKey, keyboardMode: KeyboardMode) { } }
// // ByteRangeDataAssetLoader.swift // GoogleMusicClientMacOS // // Created by Anton Efimenko on 23/06/2019. // Copyright © 2019 Anton Efimenko. All rights reserved. // import Foundation import AVFoundation import RxSwift import RxGoogleMusic private extension Observable where Element == (SessionDataEvent, URLSessionDataTask) { func ignoreElementsWithExtractedErrors() -> Completable { return Completable.create { observer in let errorOrComplete = { (error: Error?) in if let e = error { observer(.error(e)) } else { observer(.completed) } } let subscription = self.subscribe(onNext: { result in switch result.0 { case let .didCompleteWithError(_, task, error) where task == result.1: errorOrComplete(error) case .didBecomeInvalidWithError(_, let error): errorOrComplete(error) default: break } }) return Disposables.create { subscription.dispose() } } } } final class ByteRangeDataAssetLoader: NSObject { enum AssetType: String { case aac = "public.aac-audio" } private let createRequest: (ClosedRange<Int>) -> Single<URLRequest> private let assetType: AssetType private let sessionDelegate = NSURLSessionDataEventsObserver() private let session: URLSession private let errorsSubject: PublishSubject<Error> private var bag = DisposeBag() init(type: AssetType, errors: PublishSubject<Error>, createRequest: @escaping (ClosedRange<Int>) -> Single<URLRequest>) { self.assetType = type self.errorsSubject = errors self.createRequest = createRequest session = URLSession(configuration: .default, delegate: sessionDelegate, delegateQueue: nil) } deinit { print("ByteRangeDataAssetLoader deinit") session.invalidateAndCancel() } } extension ByteRangeDataAssetLoader: AVAssetResourceLoaderDelegate { func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool { return handleLoadingRequest(loadingRequest) } func resourceLoader(_ resourceLoader: AVAssetResourceLoader, didCancel loadingRequest: AVAssetResourceLoadingRequest) { bag = DisposeBag() } } private extension ByteRangeDataAssetLoader { func handleLoadingRequest(_ loadingRequest: AVAssetResourceLoadingRequest) -> Bool { let request: Completable? = { if let info = loadingRequest.contentInformationRequest { return handleInformationRequest(info) } else if let data = loadingRequest.dataRequest { return handleDataRequest(data) } else { return nil } }() request? .do(onError: { [weak self] in loadingRequest.finishLoading(with: $0); self?.errorsSubject.onNext($0) }) .do(onCompleted: { loadingRequest.finishLoading() }) .subscribe() .disposed(by: bag) return request != nil } func handleInformationRequest(_ informationRequest: AVAssetResourceLoadingContentInformationRequest) -> Completable { informationRequest.contentType = assetType.rawValue informationRequest.isByteRangeAccessSupported = true return createRequest(0...1) .map(session.dataTask) .asObservable() .flatMap(resume) .do(onNext: { result in guard case let .didReceiveResponse(_, task, response, completion) = result.0, task == result.1 else { return } informationRequest.contentLength = contentLengthFromRange(for: response as! HTTPURLResponse) ?? 2 completion(.allow) }) .ignoreElementsWithExtractedErrors() } func handleDataRequest(_ dataRequest: AVAssetResourceLoadingDataRequest) -> Completable { let lower = Int(dataRequest.requestedOffset) let upper = lower + dataRequest.requestedLength - 1 let range = (lower...upper) return createRequest(range) .map(session.dataTask) .asObservable() .flatMap(resume) .do(onNext: { result in switch result.0 { case let .didReceiveResponse(_, task, _, completion) where task == result.1: completion(.allow) case let .didReceiveData(_, task, data) where task == result.1: dataRequest.respond(with: data) default: break } }) .ignoreElementsWithExtractedErrors() } func resume(task: URLSessionDataTask) -> Observable<(SessionDataEvent, URLSessionDataTask)> { task.resume() return sessionDelegate.sessionEvents.map { ($0, task) } } } private func contentLengthFromRange(for response: HTTPURLResponse) -> Int64? { guard let header = response.allHeaderFields["Content-Range"] as? String else { return nil } return Int64(header.split(separator: "/").last ?? "") }
//: Playground - noun: a place where people can play import UIKit struct mathOperands{ let units: String var Operations : (Double, Double)->Double = { (firstValue, secondValue) in return firstValue * secondValue } init?(units: String){ if units.isEmpty{return nil} self.units = units } }
// // NSCalendar+NWCalendarView.swift // NWCalendarDemo // // Created by Nicholas Wargnier on 12/1/15. // Copyright © 2015 Nick Wargnier. All rights reserved. // import Foundation import UIKit extension NSCalendar { class func usLocaleCurrentCalendar() -> NSCalendar { let us = NSLocale(localeIdentifier: "en_US") let calendar = NSCalendar.currentCalendar() calendar.locale = us return calendar } }
// // EditorViewController.swift // Bonsai // // Created by Viktor Strate Kløvedal on 20/05/2020. // Copyright © 2020 viktorstrate. All rights reserved. // import Cocoa class EditorViewController: NSSplitViewController { var projectController: ProjectViewController { get { return self.splitViewItems[0].viewController as! ProjectViewController } } var panelController: PanelLayoutController { get { return self.splitViewItems[1].viewController as! PanelLayoutController } } var codeDocumentWindow: CodeDocumentWindow! override func viewDidLoad() { super.viewDidLoad() // Do view setup here. splitViewItems[0].isCollapsed = true } func documentSetup() { panelController.editorSetup(editorController: self) projectController.editorSetup(editorController: self) codeDocumentWindow = self.view.window?.windowController as? CodeDocumentWindow } func openProject(directory: URL) { projectController.projectDirectory = directory splitViewItems[0].isCollapsed = false } }
// // CourierRegisterPage2.swift // Vozon // // Created by Дастан Сабет on 21.05.2018. // Copyright © 2018 Дастан Сабет. All rights reserved. // import UIKit class CourierRegisterPage2: UIViewController { private let reuseIdentifier: String = "segment" private let reuseIdentifierExperience: String = "experience" lazy var tableView: UITableView = { let tableView = UITableView(frame: .zero, style: .grouped) tableView.register(RegisterCell.self, forCellReuseIdentifier: reuseIdentifierExperience) tableView.register(SegmentCell.self, forCellReuseIdentifier: reuseIdentifier) tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = .none return tableView }() var courier: User! var code: String = "" var avatar: UIImage! let messageView = Message.view.showMB() var edit: Bool = false override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.tintColor = UIColor(hex: "222222") let right = UIBarButtonItem(title: Strings.done, style: .plain, target: self, action: #selector(done)) navigationItem.rightBarButtonItem = right navigationItem.title = Strings.registration view.addSubview(tableView) view.addSubview(messageView) tableView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } if !edit { courier.courier_type = 1 } } @objc func done() { if courier.experience == nil { Alert.alert(message: Strings.writeExperience, controller: self) }else { if edit { let params = [ "name" : "\(courier.name)", "city_id" : "\(courier.city.id)", "type" : "\(courier.type)", "experience" : "\(courier.experience!)", "courier_type" : "\(courier.courier_type!)", "about" : "\(courier.about!)", ] print("Params: ", params) self.messageView.show(animated: true) API.shared.registerCourier(avatar: avatar!, parameters: params, method: .patch, url: "courier/couriers", onSuccess: { (response) in switch response { case .raw(let data): _ = User(withoutToken: data) UINavigationBar.courier() Alert.alertBack(message: Strings.profileSuccessfullyChanged, controller: self) } }) { (error) in self.messageView.hide(animated: true) Alert.alert(message: error.message, controller: self) } }else { let params = [ "phone" : "\(code)\(courier.phone)", "name" : "\(courier.name)", "city" : "\(courier.city.id)", "type" : "\(courier.type)", "experience" : "\(courier.experience!)", "courier_type" : "\(courier.courier_type!)", "about" : "\(courier.about!)", ] print("Params: ", params) self.messageView.show(animated: true) API.shared.registerCourier(avatar: avatar!, parameters: params, method: .post, onSuccess: { (response) in switch response { case .raw(_): let destination = LoginPage() destination.fromRegister = true destination.phone = "\(self.code)\(self.courier.phone)" self.messageView.hide(animated: true) DispatchQueue.main.async { Alert.alertNext(message: Strings.registrationSuccessfull, controller: self, to: UINavigationController(rootViewController: destination)) } } }) { (error) in self.messageView.hide(animated: true) Alert.alert(message: error.message, controller: self) } } } } } extension CourierRegisterPage2: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! SegmentCell cell.delegate = self if edit { if let type = courier.courier_type { print("TYPE COURIER: ", type) cell.segmentedContol.selectedSegmentIndex = type - 1 } } return cell }else { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierExperience, for: indexPath) as! RegisterCell cell.indexPath = indexPath cell.accessoryType = .none cell.icon.image = #imageLiteral(resourceName: "register_experience") cell.title = Strings.experience cell.field.keyboardType = .numberPad cell.delegate = self if edit { if let experience = courier.experience { cell.field.text = "\(experience)" } } return cell } } } extension CourierRegisterPage2: RegisterTextFieldHandler, SegmentStateControl { func didChangeText(indexPath: IndexPath, text: String) { if let experience = Int(text) { courier.experience = experience } } func segmentDidChange(_ index: Int) { courier.courier_type = index + 1 print("INDEX: ", index) print(index + 1) } }
// // File.swift // OcrExample // import Foundation
// // EventsList.swift // FNFA // // Created by Robin Minervini on 24/12/2017. // Copyright © 2017 Robin Minervini. All rights reserved. // import Foundation // Structure du JSON struct EventList : Decodable { let id: Int let name: String var excerpt: String var categoryId: Int var category: String var placeIds: Array<Int> var place: Array<String> var startingDate: String var startingDateDayNumber: String } struct CategoryList : Decodable { let id: Int let name: String } struct PlaceList : Decodable { let id: Int let name: String }
// // MoreCalendarCell.swift // EasyMeals // // Created by Alex Grimes on 5/9/20. // Copyright © 2020 Alex Grimes. All rights reserved. // import UIKit protocol MoreCalendarCellProtocol { func pushMoreDatesView() } class MoreCalendarCell: UICollectionViewCell { var delegate: MoreCalendarCellProtocol? = nil @IBOutlet weak var moreLabel: UILabel! override func prepareForReuse() { super.prepareForReuse() } override func awakeFromNib() { super.awakeFromNib() // Initialization code } @objc func pushMore() { delegate?.pushMoreDatesView() } }
// // LoginViewController.swift // Z2LChatApp // // Created by Othman Mashaab on 05/04/2017. // Copyright © 2017 Othman Mashaab. All rights reserved. // import UIKit import GoogleSignIn import FirebaseAuth class LoginViewController: UIViewController, GIDSignInUIDelegate, GIDSignInDelegate { override func viewDidLoad() { super.viewDidLoad() anonymousButton.layer.borderWidth = 1.0 anonymousButton.layer.borderColor = UIColor.white.cgColor GIDSignIn.sharedInstance().clientID = "131014422343-ch26vfap00jh2d7brj2ab2uot9dbs6ns.apps.googleusercontent.com" GIDSignIn.sharedInstance().uiDelegate = self GIDSignIn.sharedInstance().delegate = self } @IBOutlet weak var anonymousButton: UIButton! @IBAction func loginAnoumously(_ sender: Any) { print("Login anonymosuly did tapped") Helper.helper.loginAnonymously() } @IBAction func googleLoginTapped(_ sender: Any) { print("Login google") GIDSignIn.sharedInstance().signIn() } @IBOutlet weak var googleLoginDidTapped: UIButton! func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) { print(user.authentication) Helper.helper.loginWithGoogle(user.authentication) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) print(FIRAuth.auth()?.currentUser) FIRAuth.auth()?.addStateDidChangeListener({ (auth: FIRAuth, user: FIRUser?) in if user != nil { print(user) Helper.helper.switchToNavigationViewController() }else{ print("Unauthorized") } }) } }
// // NewsViewController.swift // Jarvis // // Created by apple on 2017. 8. 2.. // Copyright © 2017년 apple. All rights reserved. // import UIKit import FirebaseAuth import Firebase class NewsViewController: UIViewController { //파싱 이후 실제 뉴스 뷰 @IBOutlet weak var webView: UIWebView! @objc var address : String? @objc var newsTitle : String? @objc var ref : DatabaseReference? @IBAction func Favorite(_ sender: UIBarButtonItem) { // 즐겨찾기 let dic = ["title" : "\(newsTitle!)", "URL" : "\(address!)"] ref?.child("User").child((Auth.auth().currentUser?.uid)!).child("BookMarks").childByAutoId().setValue(dic) // 해당 url 저장 } override func viewDidLoad() { super.viewDidLoad() ref = Database.database().reference() //connect UINavigationBar.appearance().tintColor = UIColor.black if let url = URL(string: address!) { let request = URLRequest(url: url) print(request) webView.loadRequest(request) } } 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. } */ }
// // ColorStruct.swift // Colors // // Created by Ryan Glascock on 4/4/19. // Copyright © 2019 Ryan Glascock. All rights reserved. // import UIKit struct Color { let name: String let uiColor: UIColor }
// // Host.swift // NetworkingWrapper // // Created by Jaime Laino on 1/7/17. // Copyright © 2017 Jaime Laino. All rights reserved. // public protocol Host { associatedtype Environment : Hashable var headers: [String : String]? { get } var parameters: [String : String]? { get } var environment : Environment { get } var listRequest : [Environment : URLRequestConvertible] { get } func baseURL() -> String! } extension Host { public func baseURL() -> String! { return request().url } private func request() -> URLRequest! { guard let request = listRequest[environment] else { assert(true, "add request for environment: \(environment)") return nil } return request.urlRequest } }
import Foundation struct CharacterFieldsConstants { static let status: String = "Status" static let species: String = "Species" static let type: String = "Type" static let gender: String = "Gender" static let origin: String = "Origin location" static let location: String = "Last known location" }
// // Model12+Extension.swift // NewSwift // // Created by gail on 2019/4/24. // Copyright © 2019 NewSwift. All rights reserved. // import Foundation import RxSwift import Moya import ObjectMapper extension Observable { /// 将字典转为model public func mapObject<T: Mappable>(type: T.Type) -> Observable<T> { return self.map { response in guard let dict = response as? [String: Any] else { throw self.parseError(response: response) } guard let model = Mapper<T>().map(JSON: dict) else { throw self.parseError(response: response) } return model } } /// 将字典数组转为model数组 public func mapArray<T: Mappable>(type: T.Type) -> Observable<[T]> { return self.map { response in guard let array = response as? [[String: Any]] else { throw self.parseError(response: response) } return Mapper<T>().mapArray(JSONArray: array) } } /// 抛出解析的错误 private func parseError(response: Any) -> MoyaError { if let _response = response as? Response { return MoyaError.statusCode(_response) } // 解析失败时,作为服务器响应错误处理 let data = try? JSONSerialization.data(withJSONObject: response, options: []) let _response = Response(statusCode: 555, data: data ?? Data()) return MoyaError.statusCode(_response) } }
// // ViewController.swift // hw2.7 // // Created by yauheni prakapenka on 19.02.2020. // Copyright © 2020 yauheni prakapenka. All rights reserved. // import UIKit class PersonViewController: UIViewController { // MARK: - IBOutlets @IBOutlet var tableView: UITableView! // MARK: - Private properties var persons = Person.getContactList() // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // В storyboard переход от ячейки в другой VC. Делегат не нужно указывать. if let indexpath = tableView.indexPathForSelectedRow { let detailVC = segue.destination as! DetailViewController detailVC.person = persons[indexpath.row] } } } // MARK: - Table View Data Source extension PersonViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { persons.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let person = persons[indexPath.row] cell.textLabel?.text = person.fullName return cell } }
// // ClimbStairs.swift // LeetCode-Solutions // // Created by Vishal Patel on 18/9/17. // Copyright © 2017 Vishal Patel. All rights reserved. // import Foundation struct ClimbStairs { static func numOfWays(n : Int ) -> Int { var dp = [Int](repeating:0, count:n + 4) dp[0] = 1 dp[1] = 1 dp[2] = 2 if n < 3 { return dp[n] } for i in 3...n { dp[i] = dp[i-1] + dp[i-2] } return dp[n] } }
// // NodesViewController.swift // BlockPulse // // Created by 洪鑫 on 2018/12/9. // Copyright © 2018 Xin Hong. All rights reserved. // import UIKit class NodesViewController: UITableViewController { // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() setupUI() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(false, animated: false) } // MARK: - Helpers fileprivate func setupUI() { navigationItem.title = "在线节点" tableView.separatorInset.left = 15 tableView.registerNibForCell(NodeCell.self) NotificationCenter.default.addObserver(self, selector: #selector(onlineNodesUpdated(_:)), name: NSNotification.Name(.onlineNodesUpdated), object: nil) } fileprivate func showTransferAlert(with node: Node) { let alert = UIAlertController(title: "转账给 \(node.name ?? "")", message: node.address, preferredStyle: .alert) alert.addTextField { (textField) in textField.placeholder = "输入转账金额" textField.keyboardType = .decimalPad NotificationCenter.default.addObserver(self, selector: #selector(self.transferAlertTextDidChange(_:)), name: UITextField.textDidChangeNotification, object: textField) } let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (_) in NotificationCenter.default.removeObserver(self, name: UITextField.textDidChangeNotification, object: nil) } let transferAction = UIAlertAction(title: "转账", style: .default) { (_) in NotificationCenter.default.removeObserver(self, name: UITextField.textDidChangeNotification, object: nil) if let text = alert.textFields?.first?.text, let amount = Double(text) { self.transfer(to: node, amount: amount) } } alert.addAction(cancelAction) alert.addAction(transferAction) transferAction.isEnabled = false present(alert, animated: true, completion: nil) } fileprivate func showBalanceNotEnoughAlert() { let alert = UIAlertController(title: "余额不足!", message: "当前余额:\(BlockchainServer.shared.balance) BTC", preferredStyle: .alert) let okAction = UIAlertAction(title: "确定", style: .cancel, handler: nil) alert.addAction(okAction) present(alert, animated: true, completion: nil) } fileprivate func transfer(to recipient: Node, amount: Double) { guard BlockchainServer.shared.balance >= amount else { showBalanceNotEnoughAlert() return } let data: [String: Any] = ["sender": BlockchainServer.shared.currentNode?.address ?? "", "recipient": recipient.address ?? "", "amount": amount, "timestamp": Date().timeIntervalSince1970] let message = Message() message.type = .newTransaction message.sender = BlockchainServer.shared.currentNode message.data = data message.timestamp = Date().timeIntervalSince1970 UdpSocketManager.shared.broadcast(message) } } extension NodesViewController { // MARK: - Actions @objc func transferAlertTextDidChange(_ notification: Notification) { guard let alert = presentedViewController as? UIAlertController, let transferAction = alert.actions.last, let text = alert.textFields?.first?.text else { return } transferAction.isEnabled = !text.isEmpty } @objc func onlineNodesUpdated(_ notification: Notification) { tableView.reloadData() } } extension NodesViewController { // MARK: - Table view data source and delegate override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return BlockchainServer.shared.onlineNodes.count } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 55 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return nil } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return nil } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(NodeCell.self) let node = BlockchainServer.shared.onlineNodes[indexPath.row] if node == BlockchainServer.shared.currentNode { cell.accessoryType = .none cell.isUserInteractionEnabled = false cell.nameLabel.text = (node.name ?? "") + "(当前节点)" } else { cell.accessoryType = .disclosureIndicator cell.isUserInteractionEnabled = true cell.nameLabel.text = node.name } cell.addressLabel.text = node.address return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let node = BlockchainServer.shared.onlineNodes[indexPath.row] guard node != BlockchainServer.shared.currentNode else { return } showTransferAlert(with: node) } }
// // JourneyTableViewCell.swift // JourneyTracker // // Created by Aidan Haley on 14/11/2019. // Copyright © 2019 Aidan Haley. All rights reserved. // import UIKit class JourneyTableViewCell: UITableViewCell { //Outlets @IBOutlet var startTimeLabel: UILabel! @IBOutlet var endTimeLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! //Vars static let reuseIdentifier = "JourneyCell" // MARK: - Initialization override func awakeFromNib() { super.awakeFromNib() } }
// // BaseController.swift // homeCheif // // Created by mohamed abdo on 3/25/18. // Copyright © 2018 Atiaf. All rights reserved. // import UIKit class BaseController: UIViewController, PresentingViewProtocol, POPUPView, Alertable { var hiddenNav: Bool = false var pushTranstion: Bool = true var popTranstion: Bool = false var publicFont: UIFont? var centerImageNavigation: UIImageView? { didSet { if centerImageNavigation != nil { let size: CGSize = CGSize(width: centerImageNavigation!.frame.width, height: centerImageNavigation!.frame.height) let marginX: CGFloat = (self.navigationController!.navigationBar.frame.size.width / 2) - (size.width / 2) centerImageNavigation?.frame = CGRect(x: marginX, y: 0, width: size.width, height: size.height) self.navigationController?.navigationBar.addSubview(centerImageNavigation!) } } } @IBOutlet weak var menuBtnButton: UIButton! @IBOutlet weak var menuBtn: UIBarButtonItem! @IBOutlet weak var titleBar: UIBarButtonItem! @IBAction func backBtn(_ sender: Any) { self.navigationController?.popViewController(animated: true) } @IBAction func search(_ sender: Any) { let vc = controller(SearchController.self) push(vc) } @IBAction func chat(_ sender: Any) { } //var baseViewModel:SettingViewModel? //public static var config:Config? public static var configLoaded = false public static var configRunning = false //public static var setting:SettingData? override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.removeSubviews() self.navigationItem.setHidesBackButton(true, animated: false) self.setupBase() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if self.hiddenNav { // Show the Navigation Bar self.navigationController?.setNavigationBarHidden(true, animated: false ) self.navigationController?.navigationBar.shadowImage = UIImage() } else { self.navigationController?.setNavigationBarHidden(false, animated: false) } self.navigationController?.navigationBar.removeSubviews() initLang() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) //baseViewModel = nil if self.hiddenNav { // Show the Navigation Bar self.navigationController?.setNavigationBarHidden(true, animated: false) self.navigationController?.navigationBar.shadowImage = UIImage() } else { self.navigationController?.setNavigationBarHidden(false, animated: false) } } func bind() { } } extension BaseController: BaseViewControllerProtocol { func setupBase() { //init menu if menuBtn != nil { MenuHelper.instance.setUpMenuButton(delegate: self, menuBtn: menuBtn) } if menuBtnButton != nil { MenuHelper.instance.setUpMenuButton(delegate: self, menuBtn: menuBtnButton) } if !BaseController.configLoaded { //baseViewModel = SettingViewModel() //baseViewModel?.fetchSetting() bindSetting() } //reset paginator ApiManager.instance.resetPaginate() //binding } func bindSetting() { // let closure:(Config)->() = { // BaseController.config = $0 // BaseController.configRunning = false // BaseController.configLoaded = true // } // baseViewModel?.setting.bind(closure) // } } extension BaseController: UIPopoverPresentationControllerDelegate { func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return .none } }
import GameplayKit import UIKit enum CoinColor: Int { case none = 0 case orange case cyan } class Player: NSObject, GKGameModelPlayer { var chip: CoinColor var color: UIColor var name: String var playerId: Int static var allPlayers = [Player(chip: .orange), Player(chip: .cyan)] var opponent: Player { if chip == .orange { return Player.allPlayers[1] } else { return Player.allPlayers[0] } } init(chip: CoinColor) { self.chip = chip self.playerId = chip.rawValue if chip == .orange { color = .orange name = "Orange" } else { color = .cyan name = "Cyan" } super.init() } }
// // Segment.swift // iSphinx // // Created by Saiful I. Wicaksana on 20/12/17. // Copyright © 2017 icaksama. All rights reserved. // import Foundation open class Segment { fileprivate var pointer: OpaquePointer! fileprivate var aScore: CInt = 0 fileprivate var lScore: CInt = 0 fileprivate var lBack: CInt = 0 fileprivate var startFrame: CInt = 0 fileprivate var endFrame: CInt = 0 fileprivate var prob: CInt = 0 internal init() {} internal init(pointer: OpaquePointer) { self.pointer = pointer self.prob = ps_seg_prob(pointer, &aScore, &lScore, &lBack) ps_seg_frames(pointer, &startFrame, &endFrame) } internal func getPointer() -> OpaquePointer { return pointer } /** Delete segment from memory. */ open func delete() { ps_seg_free(pointer) } /** Get word from segment. */ open func getWord() -> String { return String.init(cString: ps_seg_word(pointer)) } /** Get AScore from segment. */ open func getAScore() -> Int { return Int(aScore) } /** Get LScore from segment. */ open func getLScore() -> Int { return Int(lScore) } /** Get LBack from segment. */ open func getLBack() -> Int { return Int(lBack) } /** Get Start Frame from segment. */ open func getStartFrame() -> Int { return Int(startFrame) } /** Get End Frame from segment. */ open func getEndFrame() -> Int { return Int(endFrame) } /** Get Prob from segment. */ open func getProb() -> Int { return Int(prob) } }
// // ProfileHeader.swift // FacebookMockup // // Created by Omri Shapira on 14/04/2020. // Copyright © 2020 Omri Shapira. All rights reserved. // import SwiftUI struct ProfileHeader: View { var body: some View { Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/) } } struct ProfileHeader_Previews: PreviewProvider { static var previews: some View { ProfileHeader() } }
// // LoopMailContactsViewController.swift // break // // Created by Saagar Jha on 11/14/16. // Copyright © 2016 Saagar Jha. All rights reserved. // import UIKit class LoopMailContactsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating { static let cellIdentifier = "contact" var loopMailContactsDelegate: LoopMailContactsDelegate? var schoolLoop: SchoolLoop! var contacts = [SchoolLoopContact]() var selectedContacts = [SchoolLoopContact]() @IBOutlet weak var contactsTableView: UITableView! let searchController = UISearchController(searchResultsController: nil) override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. addSearchBar(from: searchController, to: contactsTableView) if #available(iOS 11.0, *) { navigationItem.hidesSearchBarWhenScrolling = false } NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: .UIKeyboardWillHide, object: nil) navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(done)) schoolLoop = SchoolLoop.sharedInstance } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Wait for the search controller to finish its setup DispatchQueue.main.async { [unowned self] in self.searchController.searchBar.becomeFirstResponder() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc func done(_ sender: Any?) { loopMailContactsDelegate?.selected(contacts: selectedContacts) navigationController?.popViewController(animated: true) } func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return selectedContacts.count case 1: return contacts.count default: return 0 } } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "Selected" case 1: return "Search Results" default: return "" } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: LoopMailContactsViewController.cellIdentifier, for: indexPath) let contact: SchoolLoopContact switch indexPath.section { case 0: contact = selectedContacts[indexPath.row] cell.accessoryType = .checkmark case 1: contact = contacts[indexPath.row] cell.accessoryType = .none default: return cell } cell.textLabel?.text = contact.name cell.detailTextLabel?.text = "\(contact.role)\(contact.desc)" return cell } func updateSearchResults(for searchController: UISearchController) { let filter = searchController.searchBar.text?.lowercased() ?? "" if filter != "" { schoolLoop.getLoopMailContacts(withQuery: filter) { contacts, error in guard error == .noError else { return } DispatchQueue.main.async { [unowned self] in self.contacts = contacts.filter { !self.selectedContacts.contains($0) } self.contactsTableView.reloadData() } } } else { contacts.removeAll() DispatchQueue.main.async { [unowned self] in self.contactsTableView.reloadData() } } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.section { case 0: contacts.append(selectedContacts.remove(at: indexPath.row)) case 1: selectedContacts.append(contacts.remove(at: indexPath.row)) default: return } tableView.deselectRow(at: indexPath, animated: true) contactsTableView.reloadData() } @objc func keyboardWillChange(notification: NSNotification) { guard let userInfo = notification.userInfo, let animationDuration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue, let keyboardEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } let convertedKeyboardEndFrame = contactsTableView.convert(keyboardEndFrame, from: contactsTableView.window) let rawAnimationCurve = (userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.uintValue ?? 0 let animationCurve = UIViewAnimationOptions(rawValue: rawAnimationCurve) contactsTableView.contentInset = UIEdgeInsets(top: contactsTableView.contentInset.top, left: contactsTableView.contentInset.left, bottom: max(contactsTableView.bounds.maxY - convertedKeyboardEndFrame.minY, tabBarController?.tabBar.frame.height ?? 0), right: contactsTableView.contentInset.right) contactsTableView.scrollIndicatorInsets = UIEdgeInsets(top: contactsTableView.scrollIndicatorInsets.top, left: contactsTableView.scrollIndicatorInsets.left, bottom: max(contactsTableView.bounds.maxY - convertedKeyboardEndFrame.minY, tabBarController?.tabBar.frame.height ?? 0), right: contactsTableView.scrollIndicatorInsets.right) contactsTableView.flashScrollIndicators() UIView.animate(withDuration: animationDuration, delay: 0, options: [UIViewAnimationOptions.beginFromCurrentState, animationCurve], animations: { [unowned self] in self.contactsTableView.layoutIfNeeded() }) } /* // 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. } */ }
// // ViewController.swift // myfbswift // // Created by YangBo on 03/03/16. // Copyright © 2016 Symbio. All rights reserved. // import UIKit import Alamofire import CoreLocation class ViewController: UIViewController, FBSDKLoginButtonDelegate, CLLocationManagerDelegate { let locationManager = CLLocationManager() override func viewDidLoad() { FBSDKAccessToken.setCurrentAccessToken(nil) super.viewDidLoad() locationManager.delegate = self locationManager.requestAlwaysAuthorization() let identifier = "F7826DA6-4FA2-4E98-8024-BC5B71E0893E" let proximityUUID = NSUUID.init(UUIDString: "F7826DA6-4FA2-4E98-8024-BC5B71E0893E"); let beaconRegion = CLBeaconRegion.init(proximityUUID: proximityUUID!, identifier: identifier) locationManager.startMonitoringForRegion(beaconRegion) locationManager.startRangingBeaconsInRegion(beaconRegion) if (FBSDKAccessToken.currentAccessToken() != nil) { self.userData() // User is already logged in, do work such as go to next view controller. } else { let loginView : FBSDKLoginButton = FBSDKLoginButton() self.view.addSubview(loginView) loginView.center = self.view.center loginView.readPermissions = ["public_profile", "email", "user_friends"] loginView.delegate = self } // Do any additional setup after loading the view, typically from a nib. } func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) { for beacon in beacons { print(beacon) } } func locationManager(manager: CLLocationManager, monitoringDidFailForRegion region: CLRegion?, withError error: NSError) { print("Failed monitoring region: \(error.description)") } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print("Location manager failed: \(error.description)") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) { print("User Logged In") if ((error) != nil){ // Process error } else if result.isCancelled { // Handle cancellations } else { self.userData() // If you ask for multiple permissions at once, you // should check if specific permissions missing if result.grantedPermissions.contains("email") { // Do work } } } func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) { print("User Logged Out") } @IBAction func monitorBeacon(sender: UIButton) { print("xx") } func userData(){ let params = ["fields": "email, picture, first_name, last_name, id"] let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: params) graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in if ((error) != nil) { // Process error print("Error: \(error)") } else { print("fetched user: \(result)") let firstName : NSString = result.valueForKey("first_name") as! NSString let lastName : NSString = result.valueForKey("last_name") as! NSString let facebookId : NSString = result.valueForKey("id") as! NSString let email : NSString = result.valueForKey("email") as! NSString let url = NSURL(string: "http://localhost:8080/rest/v1/account/facebook-signup"); let request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let values = ["firstName":firstName, "lastName":lastName, "facebookId":facebookId, "email":email] request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(values, options: []) Alamofire.request(request) .responseJSON { response in print(response.request) // original URL request print(response.response) // URL response print(response.data) // server data print(response.result) // result of response serialization if let JSON = response.result.value { print("JSON: \(JSON)") } } } }) } }