text
stringlengths
8
1.32M
// // LoginViewController.swift // on the map // // Created by Xing Hui Lu on 2/10/16. // Copyright © 2016 Xing Hui Lu. All rights reserved. // import UIKit import FBSDKLoginKit class LoginViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var facebookLoginButton: UIButton! // MARK: - Viewcontroller Lifecycle override func viewDidLoad() { super.viewDidLoad() usernameTextField.delegate = self passwordTextField.delegate = self facebookLoginButton.addTarget(self, action: #selector(LoginViewController.loginWithFB), for: .touchUpInside) } // MARK: - Textfield Delegates func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } // MARK: - IBAction methods @IBAction func login(_ sender: UIButton) { view.endEditing(true) if usernameTextField.text == "" || passwordTextField.text == "" { showAlert("Login", message: "Please login with your Udacity credentials") } else { toggleUI() UdacityClient.sharedInstance().login(username: usernameTextField.text!, password: passwordTextField.text!, completionHandler: { (success, result, error) -> Void in // If successful, gather the public user data (REQUIRED FOR POSTING) if success { self.getUserPublicData() } else { self.showAlert("Login", message: error!.localizedDescription) self.toggleUI() return } }) } } // MARK: - Selectors func loginWithFB() { view.endEditing(true) toggleUI() (UIApplication.shared.delegate as! AppDelegate).loginManager = FBSDKLoginManager() let loginManager = (UIApplication.shared.delegate as! AppDelegate).loginManager loginManager?.logIn(withReadPermissions: ["public_profile"], from: self) { (result, error) -> Void in guard error == nil else { print("Process error, \(error?.localizedDescription)") self.toggleUI() return } if (result?.isCancelled)! { self.showAlert("Login", message: "Facebook authorization failed") self.toggleUI() } else { let tokenString = result?.token.tokenString ?? "" UdacityClient.sharedInstance().login(tokenString, completionHandler: { (success, result, error) -> Void in if success { self.getUserPublicData() } else { self.showAlert("Login", message: error!.localizedDescription) self.toggleUI() return } }) } } } // MARK: - Helper methods // No helper methods are suppose to be toggling, the only exception is this one! func getUserPublicData() { UdacityClient.sharedInstance().getUserPublicData({ (success, result, error) -> Void in if success { self.toggleUI() let tabBarController = self.storyboard?.instantiateViewController(withIdentifier: "MapAndTableView") as! UITabBarController self.present(tabBarController, animated: true, completion: nil) } else { self.toggleUI() self.showAlert("Login", message: error!.localizedDescription) return } }) } func toggleUI() { activityIndicator.isAnimating ? activityIndicator.stopAnimating(): activityIndicator.startAnimating() loginButton.isEnabled = !loginButton.isEnabled usernameTextField.isEnabled = !usernameTextField.isEnabled passwordTextField.isEnabled = !passwordTextField.isEnabled facebookLoginButton.isEnabled = !facebookLoginButton.isEnabled } func showAlert(_ title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) present(alert, animated: true, completion: nil) } }
// // DetailImageCell.swift // MyLoqta // // Created by Ashish Chauhan on 28/07/18. // Copyright © 2018 AppVenturez. All rights reserved. // import UIKit protocol DetailImageCellDelegate: class { func didTapLike() func imageDisplayed(indexPath: IndexPath) func didPerformActionOnTappingCart() } class DetailImageCell: BaseTableViewCell, NibLoadableView, ReusableView { //MARK: - IBOutlets @IBOutlet weak var headerView: AVView! @IBOutlet weak var pageControl: UIPageControl! @IBOutlet weak var collectionViewImage: UICollectionView! @IBOutlet weak var btnBack: UIButton! @IBOutlet weak var btnLike: UIButton! @IBOutlet weak var btnCart: UIButton! @IBOutlet weak var btnMoreOptions: UIButton! //MARK: - Variables weak var delegate: DetailImageCellDelegate? var arrayImage = [String]() //MARK: - LifeCycle Methods override func awakeFromNib() { super.awakeFromNib() self.setupHeaderView() self.setupCollectionView() self.pageControl.hidesForSinglePage = true self.pageControl.customPageControl(dotFillColor: .orange, dotBorderColor: .green, dotBorderWidth: 2) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } //MARK: - Private Methods private func setupHeaderView() { Threads.performTaskAfterDealy(0.05) { self.headerView.drawGradientWithRGB(startColor: UIColor.headerStartOrangeColor, endColor: UIColor.headerEndOrangeColor) } } private func setupCollectionView() { collectionViewImage.delegate = self collectionViewImage.dataSource = self collectionViewImage.register(DetailProductCollCell.self) } func configureCell(product: Product) { if let likeStatus = product.isLike { self.btnLike.isSelected = likeStatus } self.arrayImage.removeAll() if let array = product.imageUrl { self.arrayImage.append(contentsOf: array) self.collectionViewImage.reloadData() self.pageControl.numberOfPages = self.arrayImage.count } } // func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { // // Your code here // let visibleCell = self.collectionViewImage.visibleCells // if visibleCell.count > 0 { // let cell = visibleCell[0] // if let index = self.collectionViewImage.indexPath(for: cell) { // self.pageControl.currentPage = index.item // } // } // } //MARK:- IBAction Methods @IBAction func tapLikeProduct(_ sender: UIButton) { if let delegate = delegate { delegate.didTapLike() } } @IBAction func tapOpenCart(_ sender: UIButton) { if let delegate = delegate { delegate.didPerformActionOnTappingCart() } } } extension DetailImageCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { print((Constant.htRation * imageHeight)) return CGSize(width: Constant.screenWidth, height: (Constant.htRation * imageHeight)) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return arrayImage.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: DetailProductCollCell = collectionView.dequeueReusableCell(forIndexPath: indexPath) cell.imgViewImage.setImage(urlStr: self.arrayImage[indexPath.item], placeHolderImage: UIImage()) if let delegate = delegate { delegate.imageDisplayed(indexPath: indexPath) } return cell } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { self.pageControl.currentPage = indexPath.item } }
// // UINavigationController+Extensions.swift // Guard // // Created by Idan Moshe on 22/09/2020. // Copyright © 2020 Idan Moshe. All rights reserved. // import UIKit extension UINavigationController { /// SwifterSwift: Make navigation controller's navigation bar transparent. /// /// - Parameter tint: tint color (default is .white). func makeTransparent(withTint tint: UIColor? = nil) { navigationBar.setBackgroundImage(UIImage(), for: .default) navigationBar.shadowImage = UIImage() navigationBar.isTranslucent = true if let _ = tint { navigationBar.tintColor = tint! navigationBar.titleTextAttributes = [.foregroundColor: tint!] } } }
// // User.swift // RecipeApp // // Created by Vijayanand on 10/12/17. // Copyright © 2017 The Recipe App. All rights reserved. // import UIKit import Parse class User: PFUser { @NSManaged var screenName: String? @NSManaged var firstName: String? @NSManaged var lastName: String? private var name: String { get { return self.firstName! + " " + self.lastName! } } @NSManaged var stars: NSNumber? @NSManaged var following: [UInt64]? @NSManaged var followers: [UInt64]? @NSManaged var settings: UserSettings? @NSManaged var phone: String? @NSManaged var profileImage: PFFile? @NSManaged var preference: Int func custom_init(screenName: String?, firstName: String?, lastName: String?, phone: String?, shareMyCooking: Bool?, learnToCook: Bool?, enablePushNotifications: Bool?, favoriteCuisines: [String]?, stars: NSNumber?) { self.email = email self.screenName = screenName self.firstName = firstName self.lastName = lastName self.phone = phone self.stars = 0 self.followers = [UInt64]() self.following = [UInt64]() self.settings = UserSettings(shareMyCooking: shareMyCooking, learnToCook: learnToCook, enablePushNotifications: enablePushNotifications, favoriteCuisines: favoriteCuisines) self.stars = stars self.preference = -1 self.saveInBackground(block: { (success, error) in if (success) { // The object has been saved. print("User: " + self.username! + " saved with additional attributes") } else { // There was a problem, check error.description print("Unable to save User attributes for User: " + self.username!) print("error: " + (error?.localizedDescription)!) } }) } static func fetchUser(by objectId: String) -> User? { let query = PFUser.query() query?.whereKey("objectId", equalTo: objectId) do { let objects = try query?.findObjects() if let objects = objects { for object in objects { return object as? User } } return nil } catch { print("error retrieving user: " + objectId + ", \(error.localizedDescription)") return nil } } }
// // Created by Daniel Heredia on 2/27/18. // Copyright © 2018 Daniel Heredia. All rights reserved. // // Deck of Cards import Foundation // MARK: - General deck data structures enum Suit { case club case heart case spade case diamond } class CardDeck { private var cards: [Card] private var dealIndex: Int init(withCards cards: [Card]) { self.cards = cards self.dealIndex = 0 } func shuffle() { // Shuffle the cards } func dealCard() -> Card? { // Deal a card if there are remaining cards return nil } func dealHand(number: Int) -> [Card]? { // Returns an array of cards if there are enough remaining cards // to return the indicated number, otherwise returs nil return nil } var remainingCards: Int { return self.cards.count - self.dealIndex } } class Card { let suit: Suit let intrinsicValue: Int var available: Bool init(suit: Suit, value: Int) { self.suit = suit self.intrinsicValue = value self.available = true } var value:Int { // Returns a value according to the rules of the game return self.intrinsicValue } } class Hand { var cards: [Card] init() { self.cards = [Card]() } var score: Int { //Returns the score according to the present cards return 0 } func addCard(_ card: Card) { self.cards.append(card) } } // MARK: - Blackjack implementation class BlackjackCard: Card { override init(suit: Suit, value: Int) { super.init(suit: suit, value: value) } override var value: Int { if self.isAce { return 1 } else if self.isFaceCard { return 10 } else { return self.intrinsicValue } } var minValue: Int { if self.isAce { return 1 } else { return self.value } } var maxValue: Int { if self.isAce { return 11 } else { return self.value } } var isAce: Bool { return self.intrinsicValue == 1 } var isFaceCard: Bool { return self.intrinsicValue > 10 && self.intrinsicValue < 14 } } class BlackjackHand: Hand { var possibleScores: [Int] { // The implementations can return more than 1 score, // because an Ace has value of 1 and 11 simultaneusly return [Int]() } var isBusted: Bool { return self.score > 21 } var is21: Bool { return self.score == 21 } override var score: Int { let scores = self.possibleScores var maxUnder = Int.min var minAbove = Int.max for score in scores { if score <= 21 { if score > maxUnder { maxUnder = score } } else { if score < minAbove { minAbove = score } } } return maxUnder == Int.min ? minAbove : maxUnder } }
// // ViewController.swift // PhoneBookCoreData // // Created by Milad on 11/30/16. // Copyright © 2016 Milad . All rights reserved. // import UIKit import CoreData class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var managedObjectContext : NSManagedObjectContext! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var addContactBackGroundView: UIView! @IBOutlet weak var addContactInsertFieldsView: UIView! @IBOutlet weak var nameTextfield: UITextField! @IBOutlet weak var numberTextfield: UITextField! @IBOutlet weak var addContactErrorLabel: UILabel! var people : [NSManagedObject] = [NSManagedObject]() override func viewDidLoad() { super.viewDidLoad() let tap = UITapGestureRecognizer(target: self, action: #selector((ViewController.addContactBackgroundViewTapped(_:)))) self.addContactBackGroundView.addGestureRecognizer(tap) let appDelegate = UIApplication.shared.delegate as! AppDelegate self.managedObjectContext = appDelegate.persistentContainer.viewContext toggleAddContactMenu(off: true) let _ = retrievePhoneBook() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func retrievePhoneBook() -> [NSManagedObject] { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person") do { let results = try managedObjectContext.fetch(fetchRequest) self.people = results as! [NSManagedObject] for person in people { print(person.value(forKey: "name")) } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } return people } func saveNameAndNumber(name: String, number: String) -> Bool { let entity = NSEntityDescription.entity(forEntityName: "Person",in:managedObjectContext) let person = NSManagedObject(entity: entity!,insertInto: managedObjectContext) person.setValue(name, forKey: "name") person.setValue(number, forKey: "number") do { try self.managedObjectContext.save() people.append(person) return true } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") return false } } func toggleAddContactMenu(off: Bool) { self.addContactBackGroundView.isHidden = off self.nameTextfield.text = "" self.numberTextfield.text = "" } func addContactBackgroundViewTapped(_ gesture: UITapGestureRecognizer) { toggleAddContactMenu(off: true) } @IBAction func createContactButtonTapped(_ sender: AnyObject) { let name : String? = nameTextfield.text let number : String? = numberTextfield.text if ((name == nil) || (number == nil) || (number!.isEmpty) || (number!.isEmpty)) { self.addContactErrorLabel.text = "Input Error" return } let status = saveNameAndNumber(name: name!, number: number!) if status { toggleAddContactMenu(off: true) self.tableView.reloadData() } else { self.addContactErrorLabel.text = "Internal Error" } } @IBAction func addContactButtonTouched(_ sender: AnyObject) { toggleAddContactMenu(off: false) } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return people.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") cell?.textLabel?.text = people[indexPath.row].value(forKey: "name") as! String? cell?.detailTextLabel?.text = people[indexPath.row].value(forKey: "number") as! String? return cell! } }
// // NetRequest+Moya.swift // Net // // Created by Alex Rupérez on 24/4/17. // // import Moya import Alamofire extension NetRequest: TargetType { public var baseURL: URL { return url } public var path: String { return "" } public var method: Moya.Method { switch httpMethod { case .GET: return Alamofire.HTTPMethod.get case .POST: return Alamofire.HTTPMethod.post case .PUT: return Alamofire.HTTPMethod.put case .DELETE: return Alamofire.HTTPMethod.delete case .PATCH: return Alamofire.HTTPMethod.patch case .HEAD: return Alamofire.HTTPMethod.head case .TRACE: return Alamofire.HTTPMethod.trace case .OPTIONS: return Alamofire.HTTPMethod.options case .CONNECT: return Alamofire.HTTPMethod.connect default: return Alamofire.HTTPMethod.get } } public var parameters: [String: Any]? { do { return try NetTransformer.object(object: body) } catch { return nil } } public var parameterEncoding: Moya.ParameterEncoding { guard let parameterEncoding = contentType else { return Alamofire.URLEncoding.default } switch parameterEncoding { case .json: return Alamofire.JSONEncoding.default case .plist: return Alamofire.PropertyListEncoding.default default: return Alamofire.URLEncoding.default } } public var sampleData: Data { return body ?? Data() } public var task: Task { return Moya.Task.requestPlain } }
// // Post.swift // Instagram // // Created by saito-takumi on 2018/01/02. // Copyright © 2018年 saito-takumi. All rights reserved. // import UIKit import Parse public class Post: PFObject, PFSubclassing { //public API @NSManaged public var user: User @NSManaged public var postImageFile: PFFile @NSManaged public var postText: String @NSManaged public var numberOfLikes: Int @NSManaged public var likedUsrIDs: [String] override public init() { super.init() } init(user: User, postImage: UIImage, postText: String, numberOfLikes: Int) { super.init() self.postImageFile = createFileForm(image: postImage) self.user = user self.postText = postText self.numberOfLikes = numberOfLikes self.likedUsrIDs = [String]() } //PFSubclassing public static func parseClassName() -> String { return "Post" } // MARK: Method public func changeLike() { let currentUser = User.current()! if userDidLike(user: currentUser) { disLike() } else { like() } } private func like() { let currentUserID = User.current()?.objectId if !likedUsrIDs.contains(currentUserID!) { numberOfLikes += 1 likedUsrIDs.insert(currentUserID!, at: 0) saveInBackground() } } private func disLike() { let currentUserID = User.current()?.objectId if likedUsrIDs.contains(currentUserID!) { numberOfLikes -= 1 for (index, userID) in likedUsrIDs.enumerated() { if userID == currentUserID! { likedUsrIDs.remove(at: index) break } } saveInBackground() } } public func userDidLike(user :User) -> Bool { return likedUsrIDs.filter { (objectID) -> Bool in return user.objectId == objectID }.count > 0 } }
// // SATScores.swift // NYC HS SAT // // Created by C4Q on 3/9/18. // Copyright © 2018 basedOnTy. All rights reserved. // import Foundation struct SATScores: Codable { let dbn: String let num_of_sat_test_takers: String let sat_math_avg_score: String let sat_writing_avg_score: String let sat_critical_reading_avg_score: String let school_name: String }
// // FirebaseRoom.swift // SailingThroughHistory // // Created by Jason Chong on 27/3/19. // Copyright © 2019 Sailing Through History Team. All rights reserved. // import FirebaseFirestore /// A room stored on Firestore. class FirestoreRoom: Room { /// The name of the room let name: String /// Reference to Firestore private let firestore: Firestore init(named name: String) { self.name = name self.firestore = FirestoreConstants.firestore } /// Get Room objects from a QuerySnapshot /// /// - Parameters: /// - snapshot: The result of the query as a QuerySnapshot /// - error: The error from the query /// - Returns: The array of rooms stored in the snapshot. private static func processRooms(snapshot: QuerySnapshot?, error: Error?) -> [Room] { guard let roomDocuments = snapshot?.documents else { fatalError("Failed to read rooms") } return roomDocuments .map { FirestoreRoom(named: $0.documentID) } } func getConnection(completion callback: @escaping (RoomConnection?, Error?) -> Void) { FirebaseRoomConnection.getConnection(for: self, completion: callback) } /// Deletes a room on the network if necessary. /// i.e If all the devices in the room are not responsive or the room is empty. /// /// - Parameter name: The name of the room. static func deleteIfNecessary(named name: String) { let devicesCollectionReference = FirestoreConstants .roomCollection .document(name) .collection(FirestoreConstants.devicesCollectionName) let connection = FirebaseRoomConnection(forRoom: name) func deleteIfEmpty(_: Error?) { devicesCollectionReference.getDocuments(completion: { (snapshot, error) in guard let snapshot = snapshot else { print("Unable to load room players: \(String(describing: error?.localizedDescription))") return } if snapshot.documents.count <= 0 { FirebaseRoomConnection.deleteRoom(named: name) } }) } devicesCollectionReference.getDocuments { (snapshot, error) in guard let snapshot = snapshot else { print("Unable to load room players: \(String(describing: error?.localizedDescription))") return } for document in snapshot.documents { guard let lastHeartBeat = document.get(FirestoreConstants.lastHeartBeatKey) as? Double, Date().timeIntervalSince1970 - lastHeartBeat < 60 else { connection.removeDevice(withId: document.documentID) continue } } deleteIfEmpty(nil) } } }
// // wController.swift // Pagina // // Created by user on 2/8/18. // Copyright © 2018 dogbird. All rights reserved. // import UIKit import Firebase class StoryEditViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout{ @IBOutlet weak var navbarTitle: UINavigationItem! @IBOutlet weak var storyEditTextView: UITextView! @IBOutlet weak var inspirationCollectionView: UICollectionView! struct Inspiration { var type:String = ""; //"image", "map", "text" var id:String = ""; //Image var imageUrl:String = ""; var image: UIImage? = nil; //Map var long:Double = 0.0; var lat:Double = 0.0; //Text var text:String = ""; } var storageRef: StorageReference!; // Firebase Storage var ref:DatabaseReference!; //Firebase dbs var inspirations:[Inspiration] = []; var currentChapter:ChapterTableViewController.Chapter = ChapterTableViewController.Chapter(); // To save every so and so var saveTextTimer: Timer! var currentText = ""; var userid = "" //Class override func viewDidLoad() { super.viewDidLoad() if let user = Auth.auth().currentUser { userid = user.uid; } else { // No user is signed in. self.dismiss(animated: true, completion: nil); // What are you doing here? Get out! } ref = Database.database().reference(); storageRef = Storage.storage().reference(); fetchInspirations(); navbarTitle.title = currentChapter.title; storyEditTextView.text = currentChapter.content; currentText = storyEditTextView.text; saveTextTimer = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(saveText), userInfo: nil, repeats: true) //Recognize taps and hides keyboard let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard)) tap.cancelsTouchesInView = false storyEditTextView.addGestureRecognizer(tap) } override func viewWillDisappear(_ animated:Bool){ super.viewWillDisappear(true) saveTextTimer.invalidate(); saveText(); currentChapter.content = currentText; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Keyboard @objc func dismissKeyboard() { storyEditTextView.endEditing(true); // Hides Keyboard } //Save to dbs @objc func saveText(){ if storyEditTextView.text != currentText{ self.ref.child("users").child(userid).child("stories").child(currentChapter.storyid).child("chapters").child(currentChapter.id).updateChildValues(["text": self.storyEditTextView.text]); currentText = storyEditTextView.text; } } //Fetch from dbs func fetchInspirations(){ ref.child("users").child(userid).child("stories").child(currentChapter.storyid).child("chapters").child(currentChapter.id).child("inspirations").observe(DataEventType.value, with: { (snapshot) in self.inspirations.removeAll(keepingCapacity: false); for child in snapshot.children.allObjects as! [DataSnapshot]{ let value = child.value as? NSDictionary; var inspiration = Inspiration(); inspiration.type = value?["type"] as? String ?? ""; inspiration.id = child.key; if inspiration.type == "text"{ inspiration.text = value?["text"] as? String ?? ""; }else if inspiration.type == "map"{ inspiration.long = value?["long"] as? Double ?? 0.0; inspiration.lat = value?["lat"] as? Double ?? 0.0; }else if inspiration.type == "image"{ inspiration.imageUrl = value?["url"] as? String ?? ""; } self.inspirations.append(inspiration); } //fetch all images from storage for i in 0..<self.inspirations.count{ if self.inspirations[i].type == "image"{ let storagePath = self.inspirations[i].imageUrl; let imgRef = Storage.storage().reference(forURL: storagePath); var image:UIImage? imgRef.getData(maxSize: 15 * 1024 * 1024) { data, error in if let error = error { print(error) } else { image = UIImage(data: data!) ?? nil; self.inspirations[i].image = image; self.inspirationCollectionView.reloadData(); } } } } self.inspirationCollectionView.reloadData(); }) { (error) in print(error.localizedDescription) } } // Collection/Inspirations (Yes, we should have used a container view /similar for this) func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return inspirations.count + 1 // +1 for add } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.item >= inspirations.count{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "addInspirationCell", for: indexPath) as! AddInspirationCollectionViewCell return cell } if inspirations[indexPath.item].type == "image"{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageInspirationCell", for: indexPath) as! ImageInspirationCollectionViewCell if let image = inspirations[indexPath.item].image { cell.image.image = image; } return cell } if inspirations[indexPath.item].type == "text"{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "textInspirationCell", for: indexPath) as! TextInspirationCollectionViewCell cell.inspirationTextView.text = inspirations[indexPath.item].text; return cell } if inspirations[indexPath.item].type == "map"{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "mapInspirationCell", for: indexPath) as! MapInspirationCollectionViewCell; cell.setMap(long: inspirations[indexPath.item].long, lat: inspirations[indexPath.item].lat); return cell } let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ErrorInspirationCollectionViewCell cell.myLabel.text = "error" return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: ((collectionView.bounds.size.width/3) - 5), height: collectionView.bounds.size.height); } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return CGFloat(5); } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if indexPath.item >= inspirations.count { //??? } else if inspirations[indexPath.item].type == "image"{ performSegue(withIdentifier: "zoomImageSegue", sender: indexPath.item) } else if inspirations[indexPath.item].type == "text"{ performSegue(withIdentifier: "zoomTextSegue", sender: indexPath.item) } else if inspirations[indexPath.item].type == "map"{ performSegue(withIdentifier: "zoomMapSegue", sender: indexPath.item) } } //Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "addInspirationSegue" { if let inspiration = segue.destination as? AddInspirationViewController { inspiration.currentChapter = currentChapter; } }else if segue.identifier == "zoomTextSegue"{ if let zoom = segue.destination as? TextZoomViewController { if let i = sender as? Int { zoom.currentChapter = currentChapter; zoom.currentInspiration = inspirations[i]; } } }else if segue.identifier == "zoomMapSegue"{ if let zoom = segue.destination as? MapZoomViewController { if let i = sender as? Int { zoom.currentChapter = currentChapter; zoom.currentInspiration = inspirations[i]; } } }else if segue.identifier == "zoomImageSegue"{ if let zoom = segue.destination as? ImageZoomViewController { if let i = sender as? Int { zoom.currentChapter = currentChapter; zoom.currentInspiration = inspirations[i]; } } } } }
// // WFMeetingSearchController.swift // niinfor // // Created by 王孝飞 on 2017/8/23. // Copyright © 2017年 孝飞. All rights reserved. // import UIKit class WFMeetingSearchController: BaseViewController { } ///设置界面 extension WFMeetingSearchController{ override func setUpUI() { super.setUpUI() navItem.title = "会议查询" } }
// // HangmanKeyboard.swift // Hangman // // Created by Plexus on 03/12/2019. // Copyright © 2019 Plexus. All rights reserved. // import UIKit public protocol HangmangKeyboardDelegate: class { func keyDidTapped(key: String) } @IBDesignable public class HangmanKeyboard: UIView, ViewComponent { public var keyButtons = [UIButton]() // MARK: - Outlets @IBOutlet var qButton: UIButton! @IBOutlet var wButton: UIButton! @IBOutlet var eButton: UIButton! @IBOutlet var rButton: UIButton! @IBOutlet var tButton: UIButton! @IBOutlet var yButton: UIButton! @IBOutlet var uButton: UIButton! @IBOutlet var iButton: UIButton! @IBOutlet var oButton: UIButton! @IBOutlet var pButton: UIButton! @IBOutlet var aButton: UIButton! @IBOutlet var sButton: UIButton! @IBOutlet var dButton: UIButton! @IBOutlet var fButton: UIButton! @IBOutlet var gButton: UIButton! @IBOutlet var hButton: UIButton! @IBOutlet var jButton: UIButton! @IBOutlet var kButton: UIButton! @IBOutlet var lButton: UIButton! @IBOutlet var nnButton: UIButton! @IBOutlet var zButton: UIButton! @IBOutlet var xButton: UIButton! @IBOutlet var cButton: UIButton! @IBOutlet var vButton: UIButton! @IBOutlet var bButton: UIButton! @IBOutlet var nButton: UIButton! @IBOutlet var mButton: UIButton! // MARK: - Outlet Actions @IBAction func qButtonTouchUp(_ sender: UIButton) { guard let currentTitle = sender.currentTitle else { return } delegate?.keyDidTapped(key: currentTitle) } // MARK: - Class Properties public var delegate: HangmangKeyboardDelegate? // MARK: - UI Properties public var view: UIView! // MARK: - Initialization public override init(frame: CGRect) { super.init(frame: frame) xibSetup() setupButtons() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) xibSetup() setupButtons() } // MARK: - Public Functions /// Disable key and set color to gray. public func disableWord(_ word: String) { guard let button = keyButtons.first(where: { $0.currentTitle == word }) else { return } button.setTitleColor(.gray, for: .normal) button.isUserInteractionEnabled = false } /// Enable key and set color to black. public func enableWord(_ key: String) { guard let button = keyButtons.first(where: { $0.currentTitle == key }) else { return } button.setTitleColor(.black, for: .normal) button.isUserInteractionEnabled = true } /// Disable key and set color to red. public func setErrorKey(_ key: String) { guard let button = keyButtons.first(where: { $0.currentTitle == key }) else { return } button.setTitleColor(.red, for: .normal) button.isUserInteractionEnabled = false } public func reloadKeyBoard(){ keyButtons.forEach { (button) in if let buttonTitle = button.currentTitle{ self.enableWord(buttonTitle) } } } // MARK: - Setup Buttons public func setupButtons() { keyButtons = [qButton,wButton,eButton,rButton,tButton,yButton,uButton,iButton,oButton,pButton,aButton,sButton,dButton,fButton,gButton,hButton,jButton,kButton,lButton,nnButton,zButton,xButton,cButton,vButton,bButton,nButton,mButton] } // MARK: - Setup UI public func setupUI() { backgroundColor = .clear view.backgroundColor = .clear } public override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() xibSetup() view.prepareForInterfaceBuilder() } }
// // TMRequestInfoTextField.swift // consumer // // Created by Vladislav Zagorodnyuk on 4/21/16. // Copyright © 2016 Human Ventures Co. All rights reserved. // class TMRequestInfoTextField: UITextField { var textUnderline = UIView() var gradientLayer = CAGradientLayer() var yPos: CGPoint? var placeholderAttributes: [String: Any] = [ NSFontAttributeName: UIFont.MalloryBook(12.0), NSForegroundColorAttributeName: UIColor.TMColorWithRGBFloat(155.0, green: 155.0, blue: 155.0, alpha: 10), NSKernAttributeName: 1.0 ] var textAttributes: [String: Any] = [ NSFontAttributeName: UIFont.MalloryBook(12.0), NSForegroundColorAttributeName: UIColor.black, NSKernAttributeName: 1.0 ] override func awakeFromNib() { super.awakeFromNib() let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .center textAttributes[NSParagraphStyleAttributeName] = paragraphStyle self.attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: placeholderAttributes) self.addTarget(self, action: #selector(TMRequestInfoTextField.textDidChange(_:)), for: .editingChanged) } override func layoutSubviews() { super.layoutSubviews() self.layoutIfNeeded() if self.yPos == nil { self.yPos = self.superview!.convert(self.frame.origin, to: nil) } if !self.superview!.subviews.contains(textUnderline) { self.addUnderline() } else { if let _ = self.attributedPlaceholder { self.textUnderline.removeFromSuperview() self.addUnderline() } } } func addUnderline() { textUnderline.frame = CGRect(x: 0.0, y: yPos!.y + self.frame.height + 3.0, width: self.frame.size.width, height: 1.0) self.textUnderline.setFrameWidth(self.attributedPlaceholder!.widthWithConstrainedHeight(self.frameHeight()) + 150.0) self.textUnderline.centerX = self.center.x self.gradientLayer.removeFromSuperlayer() self.gradientLayer = textUnderline.addGradienBorder() self.superview?.addSubviewWithCheck(textUnderline) } func textDidChange(_ textField: UITextField) { self.typingAttributes = textAttributes let attributedString = textField.attributedText if textField.text!.length >= 15 { UIView.animate(withDuration: 0.1) { self.gradientLayer.removeFromSuperlayer() let frameNew = attributedString!.widthWithConstrainedHeight(self.frameHeight()) + 140.0 if frameNew < self.superview!.frame.width - 80.0 { self.textUnderline.setFrameWidth(frameNew) } self.gradientLayer = self.textUnderline.addGradienBorder() } self.textUnderline.centerX = self.center.x } else { self.resetUnderline() } } func resetUnderline() { textUnderline.frame = CGRect(x: 0.0, y: yPos!.y + self.frame.height + 3.0, width: self.frame.size.width, height: 1.0) let defaultString = "Brooklyn, NY".setCharSpacing(1.0) self.textUnderline.setFrameWidth(defaultString.widthWithConstrainedHeight(self.frameHeight()) + 150.0) self.textUnderline.centerX = self.center.x self.gradientLayer.removeFromSuperlayer() self.gradientLayer = textUnderline.addGradienBorder() } override func resignFirstResponder() -> Bool { let resigned = super.resignFirstResponder() self.layoutIfNeeded() return resigned } } extension TMRequestInfoTextField: UITextFieldDelegate { func textFieldDidEndEditing(_ textField: UITextField) { self.attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: placeholderAttributes) } }
// // GradientLayer.swift // CoffeeMeetsBagelTeam // // Created by Komran Ghahremani on 6/2/17. // Copyright © 2017 Komran Ghahremani. All rights reserved. // import UIKit // source: https://medium.com/ios-os-x-development/swift-3-easy-gradients-54ccc9284ce4 class GradientLayer: CAGradientLayer { var gradient: GradientType? { didSet { startPoint = gradient?.x ?? CGPoint.zero endPoint = gradient?.y ?? CGPoint.zero } } }
// // VotingCollectionView.swift // VotingSwipeView // // Created by Michael Green on 20/08/2019. // Copyright © 2019 Michael Green. All rights reserved. // import Foundation import UIKit class VotingCollectionView: UICollectionView { func setup() { let nib = UINib(nibName: "VotingCollectionViewCell", bundle: nil) self.register(nib, forCellWithReuseIdentifier: "VotingCollectionViewCell") self.delegate = self self.dataSource = self } } extension VotingCollectionView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "VotingCollectionViewCell", for: indexPath) as! VotingCollectionViewCell return cell } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if let cell = cell as? VotingCollectionViewCell { cell.setup() } } }
// // FetchChannelsForUserAction.swift // Mitter // // Created by Rahul Chowdhury on 30/11/18. // Copyright © 2018 Chronosphere Technologies Pvt. Ltd. All rights reserved. // import Foundation import RxSwift class FetchChannelsForUserAction: UniParamAction { private let channelRepository: ChannelRepository init(channelRepository: ChannelRepository) { self.channelRepository = channelRepository } func execute(t: String) -> PrimitiveSequence<SingleTrait, [ParticipatedChannel]> { return channelRepository.fetchChannelsForUser(userId: t) } }
// // CustomNavigationVC.swift // SwiftNewProject // // Created by gail on 2017/12/8. // Copyright © 2017年 XNX. All rights reserved. // import UIKit class CustomNavigationVC: UINavigationController { lazy var tipLabel : UILabel = UILabel() override func viewDidLoad() { super.viewDidLoad() navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor:UIColor.white,NSAttributedStringKey.font:UIFont.systemFont(ofSize: 18)] navigationBar.barTintColor = GlobalColor navigationBar.tintColor = UIColor.white CustomGestureRecognizer() } deinit { NotificationCenter.default.removeObserver(self) } override func pushViewController(_ viewController: UIViewController, animated: Bool) { if self.viewControllers.count > 0 { if !(viewController is MineViewController) { viewController.hidesBottomBarWhenPushed = true } viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(directionType:.left ,imageName: "btn_navBack", target: self, action: #selector(BackBtnClick)) } /// 水珠翻页效果 let animation = CATransition() animation.type = "rippleEffect" animation.subtype = "fromBottom" animation.duration = 1.0 animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) view.layer.add(animation, forKey: nil) super.pushViewController(viewController, animated: animated) } @objc func BackBtnClick() { if self.viewControllers.last is MineViewController { signOut() }else if self.viewControllers.last is InquireAboutCar{ for vc in self.viewControllers { if vc is homeViewController || vc is MineViewController { popToViewController(vc, animated: true) } } }else { popViewController(animated: true) } } override var preferredStatusBarStyle: UIStatusBarStyle{ return .lightContent } } // MARK: - 全屏手势 extension CustomNavigationVC { fileprivate func CustomGestureRecognizer() { let target = interactivePopGestureRecognizer?.delegate let pan : UIPanGestureRecognizer = UIPanGestureRecognizer(target: target!, action: Selector(("handleNavigationTransition:"))) pan.delegate = self as UIGestureRecognizerDelegate self.interactivePopGestureRecognizer?.isEnabled = false self.view.addGestureRecognizer(pan) } } // MARK: - 是否触发手势 extension CustomNavigationVC:UIGestureRecognizerDelegate{ func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if (viewControllers.last?.isKind(of: MineViewController.self))!{ return false } return viewControllers.count > 1 } } // MARK: - 退出登录提示 extension CustomNavigationVC { func signOut () { let alert = UIAlertController(title: "退出登录", message: "\n您确定要退出当前帐号?\n", preferredStyle: .alert) let okAction = UIAlertAction(title: "确定", style: .default) {[weak self] (action) in ZJKeyChain.delete("Login") UserDefaults.standard.removeObject(forKey: "StudentAlreadyRegistered") self?.popViewController(animated: true) } let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil) okAction.setValue(UIColor.darkGray, forKey: "_titleTextColor") cancelAction.setValue(UIColor.darkGray, forKey: "_titleTextColor") alert.addAction(okAction) alert.addAction(cancelAction) present(alert, animated: true, completion: nil) } }
// // Search.swift // Instagram_withStoryBoard // // Created by My iMac on 1/6/19. // Copyright © 2019 My iMac. All rights reserved. // import UIKit class Search: UIViewController { override func viewDidLoad() { super.viewDidLoad() } }
// // AddReviewRequestFactory.swift // GBShop // // Created by Зинде Иван on 3/4/21. // import Alamofire protocol AddReviewRequestFactory { func addReview(id: Int, text: String, completionHandler: @escaping (AFDataResponse<AddReviewResult>) -> Void) }
// // MeVC.swift // DevelopersBreakPoint // // Created by Sierra on 5/19/18. // Copyright © 2018 Nagiz. All rights reserved. // import UIKit import Firebase class MeVC: UIViewController , UIImagePickerControllerDelegate , UINavigationControllerDelegate{ override var preferredStatusBarStyle: UIStatusBarStyle{return .lightContent} @IBOutlet weak var ProfilePictureImage: UIImageView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var emailLbl: UILabel! var imagepicker:UIImagePickerController? override func viewDidLoad() { super.viewDidLoad() imagepicker = UIImagePickerController() imagepicker?.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) emailLbl.text = Auth.auth().currentUser?.email DataService.instance.loadImageFromFirebase(userUID: (Auth.auth().currentUser?.uid)!, imageholder: ProfilePictureImage) } //////////////////////////////////////////////////// func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { ProfilePictureImage.image = image } imagepicker?.dismiss(animated: true, completion: nil) uploadImageToFirebase() saveImageToFirebase(userImagePath: (Auth.auth().currentUser?.uid)!) } // save image as database in firebase func saveImageToFirebase(userImagePath:String){ DataService.instance.REF_USERS.child((Auth.auth().currentUser?.uid)!).updateChildValues(["userImagePath" : Auth.auth().currentUser?.uid]) } // sava image to storage func uploadImageToFirebase(){ guard let image = self.ProfilePictureImage.image else {return} guard let imageData = UIImageJPEGRepresentation(image, 1) else {return} let uploadImageRef = DataService.instance.imageReference.child("UsersImages").child((Auth.auth().currentUser?.uid)!) let uploadTask = uploadImageRef.putData(imageData, metadata: nil) { (metadata, error) in print("upload finished") } uploadTask.resume() } //////////////////////////////////////////////////// @IBAction func SignOutBtnWasPressed(_ sender: UIButton) { let popupController = UIAlertController(title: "logout?", message: "are you sure you want to logout?", preferredStyle: .actionSheet) let popupAction = UIAlertAction(title: "lougout?", style: .destructive) { (buttonTapped) in do{ try Auth.auth().signOut() let authVC = self.storyboard?.instantiateViewController(withIdentifier: "AuthVC") as! AuthVC self.present(authVC, animated: true, completion: nil) }catch{ print(error) } } popupController.addAction(popupAction) popupController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(popupController, animated: true, completion: nil) } @IBAction func imageBtnWasTapped(_ sender: UIButton) { present(imagepicker!, animated: true, completion: nil) } }
// // ViewController.swift // OnTheMap // // Created by Rahath cherukuri on 2/20/16. // Copyright © 2016 Rahath cherukuri. All rights reserved. // import UIKit class LoginViewController: UIViewController { @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var debugLabel: UILabel! @IBOutlet weak var logInButton: UIButton! // Handling Taps var tapRecognizer: UITapGestureRecognizer? = nil //Keyboard Notifications var keyboardAdjusted = false var lastKeyboardOffset: CGFloat = 0.0 // Handling View Methods override func viewDidLoad() { super.viewDidLoad() tapRecognizer = UITapGestureRecognizer(target: self, action: "handleSingleTap:") tapRecognizer?.numberOfTapsRequired = 1 } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) /* Add tap recognizer */ addKeyboardDismissRecognizer(); /* Subscribe to all keyboard events */ subscribeToKeyboardNotifications() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) /* Remove tap recognizer */ removeKeyboardDismissRecognizer() /* Unsubscribe to all keyboard events */ unsubscribeFromKeyboardNotifications() } // MARK: Actions @IBAction func loginButton(sender: AnyObject) { let username = usernameTextField!.text! let password = passwordTextField!.text! if usernameTextField!.text!.isEmpty { debugLabel.text = "Please enter your email." } else if passwordTextField!.text!.isEmpty { debugLabel.text = "Please enter your password." } else { logInButton.enabled = false logInButton.alpha = 0.5 UdacityClient.sharedInstance().getSessionID(username, password: password) { (success, sessionID, errorString) in if success { UdacityClient.sharedInstance().getUserData() {(success, errorString) in if success { dispatch_async(dispatch_get_main_queue(),{ self.completeLogin() self.logInButton.enabled = true self.logInButton.alpha = 1 }) } else { dispatch_async(dispatch_get_main_queue(),{ self.showAlertView(errorString!) self.logInButton.enabled = true self.logInButton.alpha = 1 }) } } } else { dispatch_async(dispatch_get_main_queue(),{ self.showAlertView(errorString!) self.logInButton.enabled = true self.logInButton.alpha = 1 }) } } } } @IBAction func signUpButton(sender: UIButton) { let app = UIApplication.sharedApplication() let toOpen = UdacityClient.Constants.AuthorizationURL app.openURL(NSURL(string:toOpen)!) } // Additional Methods func completeLogin() { usernameTextField!.text = "" passwordTextField!.text = "" debugLabel.text = "" openTabBarController(); } func openTabBarController() { let controller = storyboard!.instantiateViewControllerWithIdentifier("TabBarController") as! UITabBarController presentViewController(controller, animated: true, completion: nil) } // MARK: Show/Hide Keyboard func addKeyboardDismissRecognizer() { view.addGestureRecognizer(tapRecognizer!) } func removeKeyboardDismissRecognizer() { view.removeGestureRecognizer(tapRecognizer!) } func handleSingleTap(recognizer: UITapGestureRecognizer) { view.endEditing(true) } func showAlertView(message: String) { let alert = UIAlertController(title: "Login Failed", message: message, preferredStyle: UIAlertControllerStyle.Alert) let dismiss = UIAlertAction (title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil) alert.addAction(dismiss) presentViewController(alert, animated: true, completion: nil) } } // Mark: - Keyboard Methods extension LoginViewController { func subscribeToKeyboardNotifications() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } func unsubscribeFromKeyboardNotifications() { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) } func keyboardWillShow(notification: NSNotification) { if keyboardAdjusted == false { lastKeyboardOffset = getKeyboardHeight(notification) / 2 view.superview?.frame.origin.y -= lastKeyboardOffset keyboardAdjusted = true } } func keyboardWillHide(notification: NSNotification) { if keyboardAdjusted == true { view.superview?.frame.origin.y += lastKeyboardOffset keyboardAdjusted = false } } func getKeyboardHeight(notification: NSNotification) -> CGFloat { let userInfo = notification.userInfo let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue // of CGRect return keyboardSize.CGRectValue().height } }
import UIKit class MainTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() configureUIs() } private func configureUIs() { self.tabBar.isTranslucent = false let networkService: NetworkService = NetworkService(withBaseUrl: URL(string: "https://api.themoviedb.org/3/")!, andApiKey: "3afafd21270fe0414eb760a41f2620eb") let dependencyContainer = DependencyContainer(withStore: store, withNetworkService: networkService) let viewControllers = [ MoviesListViewController.instanceFromCode(with: MoviesListViewModel(with: dependencyContainer)), CheckedMoviesListViewController.instanceFromCode(with: CheckedMoviesListViewModel(with: dependencyContainer)) ] let controllers = viewControllers.enumerated().map { controller -> UINavigationController in let navigation = UINavigationController() navigation.navigationBar.isTranslucent = false navigation.setViewControllers([controller.element], animated: false) navigation.tabBarItem = UITabBarItem(title: String(controller.offset), image: nil, selectedImage: nil) return navigation } self.setViewControllers(controllers, animated: false) } }
// // Controller.swift // hello-api // // Created by Raghav Vashisht on 08/07/17. // // import Foundation import SwiftyJSON import LoggerAPI import CloudFoundryEnv import Configuration import Kitura #if os(Linux) import Glibc #else import Darwin #endif public class Controller { let router:Router let appEnv:ConfigurationManager var url:String { get {return appEnv.url} } var port: Int { get {return appEnv.port} } var vehicleArray:[Dictionary<String, Any>] = [ ["Make":"Nissan", "Model":"Murano", "Year":2017], ["Make":"Dodge", "Model":"Ram", "Year":2012], ["Make":"Nissan", "Model":"Rogue", "Year":2016] ] init() throws { appEnv = ConfigurationManager() router = Router() router.get("/", handler: getMain) router.get("/vehicles", handler: getAllVehicles) router.get("/vehicles/random", handler: getRandomVehicle) } func getMain(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) throws { Log.debug("GET - / router handler...") var json = JSON([:]) json["course"].stringValue = "Beginner API development with Swift,Kitura" json["myName"].stringValue = "Raghav Vashisht" json["company"].stringValue = "VashishtApps" try response.status(.OK).send(json: json).end() } func getAllVehicles(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) throws { let json = JSON(vehicleArray) try response.status(.OK).send(json: json).end() } func getRandomVehicle(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) throws { #if os(Linux) srandom(UInt32(Date().timeIntervalSince1970)) let index = random() % vehicleArray.count #else let index = Int(arc4random_uniform(UInt32(vehicleArray.count))) #endif let json = JSON(vehicleArray[index]) try response.status(.OK).send(json: json).end() } }
// // APIRouter.swift // AV // import UIKit import Alamofire import SwiftyUserDefaults public typealias JSONDictionary = [String: AnyObject] typealias APIParams = [String: AnyObject] struct APIRouter: URLRequestConvertible { var endpoint: APIEndpoint var detail: APIDetail init(endpoint: APIEndpoint) { self.endpoint = endpoint self.detail = APIDetail.init(endpoint: endpoint) } var baseUrl: String { return APIEnvironment.Base.rawValue } var method: Alamofire.HTTPMethod { return detail.method } var path: String { return detail.path } var parameters: APIParams { return detail.parameter } var encoding: ParameterEncoding? { return detail.encoding } var showAlert: Bool { return detail.showAlert } var showMessageOnSuccess: Bool { return detail.showMessageOnSuccess } var showLoader: Bool { return detail.showLoader } var supportOffline: Bool { return detail.supportOffline } var isBaseUrlNeedToAppend: Bool { return detail.isBaseUrlNeedToAppend } var isHeaderTokenRequired: Bool { return detail.isHeaderTokenRequired } var isUserIdInHeaderRequired: Bool { return detail.isUserIdInHeaderRequired } var fullResponse: Bool { return detail.fullResponse } var isAuthenticationRequired: Bool { switch endpoint { case .signup(_): return false default: return true } } /// Returns a URL request or throws if an `Error` was encountered. /// - throws: An `Error` if the underlying `URLRequest` is `nil`. /// - returns: A URL request. func asURLRequest() throws -> URLRequest { let url = URL(string: baseUrl) var urlRequest = URLRequest(url: isBaseUrlNeedToAppend ? (url?.appendingPathComponent(self.path))! : URL(string: self.path)!) urlRequest.httpMethod = method.rawValue urlRequest.timeoutInterval = 60 if let token = Defaults[.jwtToken], isHeaderTokenRequired { //urlRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") print("the token is --->",token) urlRequest.setValue(token, forHTTPHeaderField:KHeaderToken) } if isUserIdInHeaderRequired { let userId = UserSession.sharedSession.getUserId() urlRequest.setValue("\(userId)", forHTTPHeaderField:KUserId) } // application/x-www-form-urlencoded // "Content-Type" //urlRequest.setValue("gzip", forHTTPHeaderField: "Accept-Encoding") return try encoding!.encode(urlRequest, with: self.parameters) } }
// // FeedCollectionViewController.swift // instaClone // // Created by shiv on 9/4/19. // Copyright © 2019 none. All rights reserved. // import UIKit import Firebase private let reuseIdentifier = "Cell" class FeedViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, FeedCellDelegate { // MARK: Datasource var posts = [Post]() var viewSinglePost = false var post: Post? override func viewDidLoad() { super.viewDidLoad() collectionView.backgroundColor = .white // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Register cell classes self.collectionView!.register(FeedCell.self, forCellWithReuseIdentifier: reuseIdentifier) // refresh vc let refresh = UIRefreshControl() refresh.addTarget(self, action: #selector(handleRfresh), for: .valueChanged) collectionView.refreshControl = refresh // Do any additional setup after loading the view. configureLogoutButton() if !viewSinglePost { fetchPost() } } // MARK: UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let width = view.frame.width var height = width + 8 + 40 + 8 height += 111 return CGSize(width: width, height: height) } override func numberOfSections(in collectionView: UICollectionView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of items if viewSinglePost { return 1 } else { return posts.count } } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! FeedCell cell.delegate = self if viewSinglePost { if let post = self.post { cell.post = post } } else { cell.post = posts[indexPath.row ] } // Configure the cell return cell } //MARK: Functions // refresh @objc func handleRfresh() { posts.removeAll(keepingCapacity: false) fetchPost() collectionView?.reloadData() } // username func handleUsernameTapped(for cell: FeedCell) { guard let post = cell.post else { return } let userProfileVC = ProfileViewController(collectionViewLayout: UICollectionViewFlowLayout()) userProfileVC.user = post.user navigationController?.pushViewController(userProfileVC, animated: true) } // comments func handleCommentTapped(for cell: FeedCell) { print("comment") } // likes func handleLikeTapped(for cell: FeedCell) { guard let post = cell.post else { return } if post.didLike { post.adjustLikes(addLike: false, completion: { (likes) in cell.likeLabel.text = "\(likes) likes" cell.likeBtn.setImage(#imageLiteral(resourceName: "like_unselected"), for: .normal) }) } else { post.adjustLikes(addLike: true, completion: { ( likes ) in cell.likeBtn.setImage(#imageLiteral(resourceName: "like_selected"), for: .normal) cell.likeLabel.text = "\(likes) likes" }) } guard let like = post.likes else { return } cell.likeLabel.text = "\(like) likes" } // options func handleOptionTapped(for cell: FeedCell) { print("option") } // handle messages @objc func handleShowMessage() { print("tappp") } // handle log out *******CONFIGURENAVBAR******* func configureLogoutButton() { if !viewSinglePost { self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(handelLogout)) } self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "send2"), style: .plain, target: self, action: #selector(handleShowMessage)) self.navigationItem.title = "Feed" } @objc func handelLogout() { let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Log out", style: .destructive, handler: { (_) in do { try Auth.auth().signOut() let loginVC = LoginViewController() let navController = UINavigationController(rootViewController: loginVC) self.present(navController, animated: true, completion: nil) } catch { print("Login out unsucessful") } })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } // MARK: Fetch post func fetchPost() { guard let currentUid = Auth.auth().currentUser?.uid else { return } USER_FEED_REF.child(currentUid).observe(.childAdded) { (snapshot) in let postid = snapshot.key Database.fetchPost(with: postid, completion: { (post) in self.posts.append(post) self.posts.sort { (post1, post2) -> Bool in return post1.creationDate > post2.creationDate } // end refresh self.collectionView.refreshControl?.endRefreshing() self.collectionView?.reloadData() }) // end completion } // end db ref } // end fetch post } // end class
// // GroupRidesVC.swift // ResumeProject // // Created by john fletcher on 6/25/16. // Copyright © 2016 John Fletcher. All rights reserved. // import UIKit import Firebase import MapKit class GroupRidesVC: UITableViewController, CLLocationManagerDelegate { var requests = [rideDetails]() var locationManager:CLLocationManager! var driverVal: String! var driverGroupVal: String! var riderGroupVal: String! var Lat:CLLocationDegrees! var Long:CLLocationDegrees! var riderUser: String! var currentUsername: String! var riderInfo: String! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Group Rides" locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.allowsBackgroundLocationUpdates = true locationManager.startUpdatingLocation() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return self.requests.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) if self.requests.count >= 1 { let drove = "drove" let topple = "to" let userString = String(format:"%@ %@ %@ %@ %@ %@ %@", self.requests[(indexPath as NSIndexPath).row].driverUsername,drove, self.requests[(indexPath as NSIndexPath).row].username,topple, self.requests[(indexPath as NSIndexPath).row].destinationName,self.requests[(indexPath as NSIndexPath).row].acceptDate,self.requests[(indexPath as NSIndexPath).row].acceptTime) let characterNum1 = String(self.requests[(indexPath as NSIndexPath).row].driverUsername).characters.count let characterNum2 = String(self.requests[(indexPath as NSIndexPath).row].username).characters.count let myString:NSString = userString as NSString var myMutableString = NSMutableAttributedString() myMutableString = NSMutableAttributedString(string: myString as String, attributes: [NSFontAttributeName:UIFont(name:"ChalkboardSE-Bold", size: 11.0)!]) myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue, range: NSRange(location:0,length:characterNum1)) myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue, range: NSRange(location:(characterNum1+7),length:characterNum2)) cell.textLabel?.attributedText = myMutableString cell.textLabel?.adjustsFontSizeToFitWidth = true }else{ self.requests = [] self.tableView.reloadData() } return cell } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { self.userGroup() let user = FIRAuth.auth()?.currentUser?.uid let uref = FIRDatabase.database().reference().child("PickupNotification") uref.observe(.value, with: { (snapshot) in var exist = snapshot.exists() if exist { self.requests = [] if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] { for snap in snapshots { if let riderVal = (snap.value as? NSDictionary)?["Group"] as? String{ self.riderGroupVal = riderVal if let riderUsername = (snap.value as? NSDictionary)?["Username"] as? String{ self.riderUser = riderUsername if self.currentUsername != self.riderUser{ if self.riderGroupVal == self.driverGroupVal{ if (snap.value as? NSDictionary)?["driverAccepted"] as? String != nil { if let requestDictionary = snap.value as? Dictionary<String, AnyObject> { let request = rideDetails(uid: snap.key, dictionary:requestDictionary, tView: self.tableView) self.requests.insert(request, at: 0) self.tableView.reloadData() } }else{ self.tableView.reloadData() } } } } } } } }else{ self.requests = [] self.tableView.reloadData() self.showAlert("Error with Snapshot Request", message: "No Pickup Request to Retrieve Data") } }) } @IBAction func menuButton(_ sender: UIBarButtonItem) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let menuVC = storyboard.instantiateViewController(withIdentifier: "menuPageVC") self.present(menuVC, animated: true, completion: nil) } func userGroup() { let ref = FIRDatabase.database().reference() let userID = FIRAuth.auth()?.currentUser?.uid if FIRAuth.auth()?.currentUser != nil{ ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in let driGroup = (snapshot.value as? NSDictionary)?["Group"] as! String self.driverGroupVal = driGroup }) } } func userUsername() { let ref = FIRDatabase.database().reference() let userID = FIRAuth.auth()?.currentUser?.uid if FIRAuth.auth()?.currentUser != nil{ ref.child("PickupNotification").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in let username = (snapshot.value as? NSDictionary)?["Username"] as! String self.currentUsername = username }) } } func showAlert(_ title: String, message: String){ let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } /* let def = NSUserDefaults.standardUserDefaults() var key = "ridesArray" var array1: [NSString] = [NSString]() array1.append(self.riderInfo) //Save riderInfo to Array var defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(array1, forKey: key) defaults.synchronize() //read ridesArray if let ridesArray : AnyObject? = defaults.objectForKey(key){ var readArray : [NSString] = ridesArray! as! [NSString] print(readArray) } */
// // Element.swift // Formatter // // Created by John Ahrens on 10/21/17. // Copyright © 2017 John Ahrens. All rights reserved. // import Foundation class Element: Document { }
// // ParticipatedChannel.swift // Mitter // // Created by Rahul Chowdhury on 30/11/18. // Copyright © 2018 Chronosphere Technologies Pvt. Ltd. All rights reserved. // import Foundation import Mapper public struct ParticipatedChannel { public let participationStatus: ParticipationStatus public let channel: Channel } extension ParticipatedChannel: Mappable { public init(map: Mapper) throws { participationStatus = try map.from("participationStatus") channel = try map.from("channel") } }
import Foundation public struct AppSettings: Codable { public var serverPort: String public var mongoUrl: String public var parseApplicationId: String public var parseClientKey: String public static let `default`: AppSettings = { return .init( serverPort: "8080", mongoUrl: "mongodb://localhost/", parseApplicationId: "appId", parseClientKey: "clientKey") }() public static var current: AppSettings = .default public func merging(_ other: AppSettings) -> AppSettings { return AppSettings.fromDictionary( self.toDictionary().merging(other.toDictionary(), uniquingKeysWith: { $1 }) )! } public func merging(dictionary: [String: String]) -> AppSettings { let selfDict = self.toDictionary() let mergedDict = selfDict.merging(dictionary, uniquingKeysWith: { $1 }) return AppSettings.fromDictionary(mergedDict)! } public func merging(file: URL) -> AppSettings { guard let data = try? Data(contentsOf: file), let dictionary = try? JSONDecoder().decode([String: String].self, from: data) else { return self } return self.merging(dictionary: dictionary) } private func toDictionary() -> [String: String] { let encoder = JSONEncoder(), decoder = JSONDecoder() return (try? encoder.encode(self)) .flatMap { try? decoder.decode([String: String].self, from: $0) } ?? [:] } private static func fromDictionary(_ dictionary: [String: String]) -> AppSettings? { let encoder = JSONEncoder() return (try? encoder.encode(dictionary)) .flatMap { AppSettings.fromData($0) } } private static func fromData(_ data: Data) -> AppSettings? { let decoder = JSONDecoder() return try? decoder.decode(AppSettings.self, from: data) } }
// // ContentView.swift // cube // // Created by 4 on 8/11/20. // Copyright © 2020 XNO LLC. All rights reserved. // import SwiftUI import SceneKit struct ContentView: View { let cube = CubeView() var body: some View { ZStack { Rectangle().foregroundColor(.black) .frame(height: 2000) cube .frame(width: 300, height: 300) .onTapGesture(count: 2, perform: { self.cube.resetCube() }) } .statusBar(hidden: true) .gesture(DragGesture() .onEnded { drag in let h = drag.predictedEndTranslation.height let w = drag.predictedEndTranslation.width if abs(h)/abs(w) > 1 { self.cube.flipCube(up: h > 0) } else { self.cube.spinCube(right: w > 0) } }) } } struct CubeView : UIViewRepresentable { let scene = SCNScene() let help = SceneHelper() let name1 = "cube1" let name2 = "cube2" let camPos: CGFloat = 2.0 func makeUIView(context: Context) -> SCNView { scene.rootNode.addChildNode(help.makeCamera(pos: SCNVector3(camPos,camPos,camPos), rot: SCNVector3(-36,45,0))) scene.rootNode.addChildNode(help.makeAmbiLight()) scene.rootNode.addChildNode(help.makeBox(name: name1, pos: SCNVector3(0,0,0), size: 1.0, cmfr: 0.03, color: .white)) scene.rootNode.addChildNode(help.makeBox(name: name2, pos: SCNVector3(0,0,0), size: 0.999, cmfr: 0.0, color: .black)) scene.background.contents = UIColor.black return help.prepSCNView(scene: scene) } func updateUIView(_ scnView: SCNView, context: Context) { } public func spinCube(right: Bool) { let dir: Float = right ? 1.0 : -1.0 let node1 = scene.rootNode.childNode(withName: name1, recursively: false) let node2 = scene.rootNode.childNode(withName: name2, recursively: false) let rotateAction = SCNAction.rotate(by: help.dToR(90*dir), around: SCNVector3(0,1,0), duration: 0.35) rotateAction.timingMode = .easeInEaseOut node1?.runAction(rotateAction) node2?.runAction(rotateAction) } public func flipCube(up: Bool) { let dir: Float = up ? 1.0 : -1.0 let node1 = scene.rootNode.childNode(withName: name1, recursively: false) let node2 = scene.rootNode.childNode(withName: name2, recursively: false) let rotateAction = SCNAction.rotate(by: help.dToR(180*dir), around: SCNVector3(1,0,-1), duration: 0.5) rotateAction.timingMode = .easeInEaseOut node1?.runAction(rotateAction) node2?.runAction(rotateAction) } public func resetCube() { let node1 = scene.rootNode.childNode(withName: name1, recursively: false) let node2 = scene.rootNode.childNode(withName: name2, recursively: false) var rot = abs(node1?.rotation.w ?? 0) while rot > 0.5 { rot -= .pi/4 } if abs(rot) > 0.001 { let rotateAction = SCNAction.rotate(toAxisAngle: SCNVector4(0,0,0,0), duration: 0.3) rotateAction.timingMode = .easeInEaseOut node1?.runAction(rotateAction) node2?.runAction(rotateAction) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
// // PointAnnotations.swift // carWash // // Created by Juliett Kuroyan on 04.02.2020. // Copyright © 2020 VooDooLab. All rights reserved. // import MapKit private let ClusterID = "ClusterAnnotationView" // MARK: - PinAnnotationView @available(iOS 11.0, *) class PinAnnotationView: MKAnnotationView { var label: UILabel! static let ReuseID = "PinAnnotationView" // override var isSelected: Bool { // didSet { // if isSelected { // configureSelectedMode() // } else { // configureDeselectedMode() // } // } // } override var annotation: MKAnnotation? { willSet { clusteringIdentifier = ClusterID } } override init(annotation: MKAnnotation?, reuseIdentifier: String?) { super.init(annotation: annotation, reuseIdentifier: reuseIdentifier) displayPriority = .defaultHigh image = UIImage(named: MapViewConstants.pinImageName) label = UILabel() label.textColor = .white label.font = UIFont.systemFont(ofSize: 12, weight: .bold) label.tag = MapViewConstants.pinLabelTag subviews.forEach({ $0.removeFromSuperview() }) addSubview(label) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// - Tag: DisplayConfiguration @available(iOS 11.0, *) override func prepareForDisplay() { super.prepareForDisplay() if let customPointAnnotation = annotation as? CustomPointAnnotation { label.text = customPointAnnotation.text label.sizeToFit() let x = (frame.width - label.frame.width) / 2 let y = MapViewConstants.pinYOrigin label.frame.origin = CGPoint(x: x, y: y) } } } // MARK: - ClusterAnnotationView @available(iOS 11.0, *) class ClusterAnnotationView: MKAnnotationView { override init(annotation: MKAnnotation?, reuseIdentifier: String?) { super.init(annotation: annotation, reuseIdentifier: reuseIdentifier) collisionMode = .circle clusteringIdentifier = ClusterID centerOffset = CGPoint(x: 0, y: -10) // Offset center point to animate better with marker annotations displayPriority = .required } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// - Tag: CustomCluster override func prepareForDisplay() { super.prepareForDisplay() if let cluster = annotation as? MKClusterAnnotation { let totalCount = cluster.memberAnnotations.count image = UIImage(named: "clusterMapPin") let label = UILabel() label.textColor = .white label.text = "\(totalCount)" label.font = UIFont.systemFont(ofSize: 12, weight: .bold) label.tag = MapViewConstants.pinLabelTag label.sizeToFit() let x = (frame.width - label.frame.width) / 2 let y = (frame.height - label.frame.height) / 2 label.frame.origin = CGPoint(x: x, y: y) subviews.forEach({ $0.removeFromSuperview() }) addSubview(label) } } }
// // ImagesViewController.swift // ImageViewZoomDemo // // Created by Amsaraj Mariappan on 15/9/2562 BE. // Copyright © 2562 Amsaraj Mariyappan. All rights reserved. // import UIKit class ImagesViewController: UIViewController { var scrollView = UIScrollView() var attachedImages = [UIImage]() var views = [UIView]() var imageViews = [ImageViewZoom]() var currentIndex = Int() var saveImage : UIButton = { var button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.setImage(#imageLiteral(resourceName: "ic_download_white"), for: .normal) button.addTarget(self, action: #selector(saveImageButtonTapped), for: .touchUpInside) return button }() var cancel : UIButton = { var button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.setImage(#imageLiteral(resourceName: " ic_fill_cross_grey"), for: .normal) // button.frame = CGRect(x: 16, y: 16, width: 30, height: 30) button.addTarget(self, action: #selector(cancelButtonTapped), for: .touchUpInside) return button }() override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // (UIApplication.shared.delegate as! AppDelegate).restrictRotation = .all } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .black let viewHeight: CGFloat = self.view.bounds.size.height let viewWidth: CGFloat = self.view.bounds.size.width scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight)) scrollView.isPagingEnabled = true scrollView.delegate = self // let animals = ["tiger","horse","lion","horse","elephant"] var xPostion: CGFloat = 0 for image in attachedImages { let view = UIView(frame: CGRect(x: xPostion, y: 0, width: viewWidth, height: viewHeight)) let imageView = ImageViewZoom(frame: CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight)) imageView.setup() // imageView.imageScrollViewDelegate = self imageView.imageContentMode = .aspectFit imageView.initialOffset = .center imageView.display(image: image) // imageView.layer.borderColor = UIColor .red.cgColor // imageView.layer.borderWidth = 2 view.addSubview(imageView) scrollView.addSubview(view) xPostion += viewWidth views.append(view) imageViews.append(imageView) } scrollView.contentSize = CGSize(width: xPostion, height: viewHeight) view.addSubview(scrollView) // let cancel = UIButton() view.addSubview(cancel) cancel.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor, constant: 16).isActive = true cancel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16).isActive = true view.addSubview(saveImage) saveImage.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true saveImage.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -30).isActive = true scrollView.contentOffset = CGPoint(x: Int(self.view.bounds.size.width) * currentIndex, y: 0) } @objc private func cancelButtonTapped(sender: UIButton!) { self.dismiss(animated: true) { } } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { get { return .portrait } } @objc private func saveImageButtonTapped(sender: UIButton!) { UIImageWriteToSavedPhotosAlbum(attachedImages[currentIndex], self, #selector(savedImage), nil) } @objc func savedImage(_ im:UIImage, error:Error?, context:UnsafeMutableRawPointer?) { GlobalVariables.showAlert(title: MSG_TITLE_SAVE_IMAGE, message: MSG_IMAGE_SAVED, vc: self) } } extension ImagesViewController: UIScrollViewDelegate { func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { currentIndex = Int(scrollView.contentOffset.x) / Int(self.view.bounds.size.width) } } extension ImagesViewController: ImageViewZoomDelegate { func imageScrollViewDidChangeOrientation(imageViewZoom: ImageViewZoom) { print("Did change orientation") let viewHeight: CGFloat = self.view.bounds.size.height let viewWidth: CGFloat = self.view.bounds.size.width scrollView.frame = CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight) var xPostion: CGFloat = 0 for view in views { view.frame = CGRect(x: xPostion, y: 0, width: viewWidth, height: viewHeight) xPostion += viewWidth } for imageView in imageViews { imageView.frame = CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight) imageView.initialOffset = .center } scrollView.contentSize = CGSize(width: xPostion, height: viewHeight) } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { print("scrollViewDidEndZooming at scale \(scale)") } func scrollViewDidScroll(_ scrollView: UIScrollView) { print("scrollViewDidScroll at offset \(scrollView.contentOffset)") } }
// Swift Irregular Whitespace String Parser // Developed by Kyle O'Brien import Cocoa func split(str: String) -> [String] { var words:[String] = [] var previous = "" for char in str.characters { if char != " " { previous += String(char) } else if previous != "" { words.append(previous) previous = "" } } if str.characters.last != " " { words.append(previous) } return words } func test() { let originalString = "Of this, man will know nothing" let splitString = split(str: originalString) print(splitString) } test()
// // LevelTests.swift // colorspinModelTests // // Created by Anand Kumar on 7/22/18. // Copyright © 2018 Anand Kumar. All rights reserved. // import XCTest @testable import Colorspin class LevelTests: XCTestCase { private var fixedWheel: Wheel! override func setUp() { fixedWheel = try! Wheel(data: wheelData) } func testLevelEquatable() { let particle = Particle(at: CGPoint(x: 40, y: 100), radius: 20, color: .red, speed: 1.5) let level1 = Level(wheel: fixedWheel, particles: [particle], stars: fixedStars, cost: fixedCost, finalTick: 1) let level2 = Level(wheel: fixedWheel, particles: [], stars: fixedStars, cost: fixedCost, finalTick: 1) XCTAssertFalse(level1 == level2) XCTAssertTrue(level1 == level1) } func testLevelSetup() { let particle1 = Particle(at: CGPoint(x: 40, y: 100), radius: 20, color: .red, speed: 1.5) let particle2 = Particle(at: CGPoint(x: 40, y: 100), radius: 20, color: .green, speed: 1.5) let level = Level(wheel: fixedWheel, particles: [particle1, particle2], stars: fixedStars, cost: fixedCost, safetyBuffer: 0.3, tps: 4, finalTick: 1) XCTAssertEqual(level.particles.count, 2) XCTAssertEqual(level.wheel, fixedWheel) XCTAssertEqual(level.safetyBuffer, 0.3) XCTAssertEqual(level.tps, 4) XCTAssertEqual(level.stars.bronze, Star(scoreToReach: 1, type: .bronze)) XCTAssertEqual(level.cost, Cost(stars: 5, coins: 7)) XCTAssertEqual(level.finalTick, 1) } func testLevelFromJson() { let level = try? Level(data: levelData) XCTAssertNotNil(level) XCTAssertEqual(level?.particles.count, 4) XCTAssertEqual(level?.safetyBuffer, 0.2) XCTAssertEqual(level?.tps, 1) XCTAssertEqual(level?.stars.bronze, Star(scoreToReach: 1, type: .bronze)) XCTAssertEqual(level?.cost, Cost(stars: 5, coins: 10)) XCTAssertEqual(level?.finalTick, 200) } func testLevelMillisecondsPerTick() { var level = Level(wheel: fixedWheel, particles: [], stars: fixedStars, cost: fixedCost, tps: 4, finalTick: 1) XCTAssertEqual(level.millisecondsPerTick, 250.0) level = Level(wheel: fixedWheel, particles: [], stars: fixedStars, cost: fixedCost, tps: 1, finalTick: 1) XCTAssertEqual(level.millisecondsPerTick, 1000.0) } func testLevelTimeRemaining() { let level = Level(wheel: fixedWheel, particles: [], stars: fixedStars, cost: fixedCost, tps: 1, finalTick: 218) XCTAssertEqual(level.timeLeft(at: 0), "03:38") XCTAssertEqual(level.timeLeft(at: 38), "03:00") XCTAssertEqual(level.timeLeft(at: 158), "01:00") XCTAssertEqual(level.timeLeft(at: 215), "00:03") XCTAssertEqual(level.timeLeft(at: 218), "00:00") XCTAssertFalse(level.isTimeRunningOut(at: 0)) XCTAssertFalse(level.isTimeRunningOut(at: 38)) XCTAssertFalse(level.isTimeRunningOut(at: 158)) XCTAssertTrue(level.isTimeRunningOut(at: 215)) XCTAssertTrue(level.isTimeRunningOut(at: 218)) } }
// // ViewController.swift // camtest1 // // Created by matt on 1/8/17. // Copyright © 2017 BoulevardLabs. All rights reserved. // import UIKit import CameraManager import AVFoundation class ViewController: UIViewController { @IBOutlet weak var cameraView: UIView! let cameraManager = CameraManager() @IBOutlet weak var cameraButton: UIButton! override func viewDidLoad() { super.viewDidLoad() cameraManager.showAccessPermissionPopupAutomatically = true //let currentCameraState = cameraManager.currentCameraStatus() addCameraToView() } var player: AVAudioPlayer? func playSound() { let url = Bundle.main.url(forResource: "whistle", withExtension: "wav")! do { player = try AVAudioPlayer(contentsOf: url) guard let player = player else { return } player.prepareToPlay() player.play() } catch let error { print(error.localizedDescription) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.isHidden = true cameraManager.resumeCaptureSession() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) cameraManager.stopCaptureSession() } fileprivate func addCameraToView() { print(cameraManager.addPreviewLayerToView(self.cameraView)) } @IBAction func buttonDown(_ sender: Any) { print("button pressed") playSound() } @IBAction func buttonClick(_ sender: Any) { //stop sound player?.stop() cameraManager.capturePictureWithCompletion({ (image, error) -> Void in if let errorOccured = error { self.cameraManager.showErrorBlock("Error occurred", errorOccured.localizedDescription) } else { let vc: ImageViewController? = self.storyboard?.instantiateViewController(withIdentifier: "ImageVC") as? ImageViewController if let validVC: ImageViewController = vc { if let capturedImage = image { validVC.image = capturedImage self.navigationController?.pushViewController(validVC, animated: true) } } } }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // AppDelegate.swift // Fraktal // // Created by Dmitry Levsevich on 3/18/17. // Copyright © 2017 Home. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var root: Root = Root() var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. _ = root.present(presenters) return true } } extension AppDelegate: AnyPresentableSourceType { typealias Presenters = Root.RootPresentersContainer var presenters: Root.RootPresentersContainer { return Root.RootPresentersContainer(mainPresenter: self.mainPresenter, nonePresenter: self.nonePresenter) } var mainPresenter: Presenter<AnyPresentableType<MainPresentersContainer>> { return Presenter.UI { viewmodel in guard let window = self.window else { return nil } let main = UIStoryboard(name: "Main", bundle: nil) .instantiateViewController(withIdentifier: "MainScreen") as! MainViewController window.rootViewController = UINavigationController(rootViewController: main) window.makeKeyAndVisible() main.loadViewIfNeeded() return viewmodel <> main } } var nonePresenter: Presenter<()> { return Presenter.UI { viewmodel in return nil } } }
// // Stub+SyncDispatcher.swift // ReduxMe-Tests // // Created by Ilias Pavlidakis on 22/01/2020. // Copyright © 2020 Ilias Pavlidakis. All rights reserved. // import Foundation @testable import ReduxMe extension Stub { final class SyncDispatcher: DispatchQueing { func async(_ block: @escaping () -> Void) { block() } } }
// // Services+Release.swift // GitHubAPICommand // // Created by Wayne Hsiao on 2018/9/15. // import Foundation import ObjectMapper extension Services { public func release(request: GitHubAPIRequestFactory.Release, completionHandler: @escaping CompletionHandler) { guard let orginization = request.orginization.value, let repository = request.repository.value else { completionHandler(nil, nil, GitHubAPIError.ParameterError) return } do { let endpoint = try EndpointFactory.Release(host: host(request: request), orginization: orginization, repository: repository) guard let url = URL(string: endpoint.url) else { completionHandler(nil, nil, GitHubAPIError.ParameterError) return } let name = request.releaseName.value let body = request.releaseBody.value let tag = request.releaseTag.value let commitish = request.releaseCommitish.value let requestBody: [AnyHashable:Any] = ["tag_name" : tag, "target_commitish" : commitish, "name" : name, "body" : body] post(url: url, request: request, body: requestBody) { (data, response, error) in guard let data = data, let jsonDic = JSONParser(data: data).parsedDictionary else { completionHandler(nil,response, error) return } guard let accessToken = Mapper<GitHubRelease>().map(JSONObject: jsonDic) else { completionHandler(nil,response, error) return } completionHandler(accessToken, response, error) } } catch { print(error) } } }
// // GZEChatBubbleView.swift // Gooze // // Created by Yussel on 3/30/18. // Copyright © 2018 Gooze. All rights reserved. // import UIKit class GZEChatBubbleView: UIView { static let minSize: CGFloat = 57 static let font = GZEConstants.Font.main //static let labelPadding: CGFloat = 10 static let bubblePadding: CGFloat = 5 static let labelInsets = UIEdgeInsets(top: 10, left: 15, bottom: 10, right: 25) static let bubbleWidthProportion: CGFloat = 0.6 let bubbleImageView = UIImageView() let textLabel = UILabel() let fakeTextLabel = UILabel() var bubbleLeadingConstraint: NSLayoutConstraint! var bubbleTrailingConstraint: NSLayoutConstraint! var textLabelLeadingConstraint: NSLayoutConstraint! var textLabelTrailingConstraint: NSLayoutConstraint! var text: String? { didSet { self.textLabel.text = self.text self.fakeTextLabel.text = self.text } } enum Style { case sent case received } var style: Style = .sent { didSet { switch self.style { case .sent: self.changeImage(#imageLiteral(resourceName: "chat-bubble-sent")) self.bubbleImageView.tintColor = UIColor(white: 1, alpha: 0.8) self.textLabelTrailingConstraint.constant = GZEChatBubbleView.labelInsets.right self.textLabelLeadingConstraint.constant = -GZEChatBubbleView.labelInsets.left self.bubbleLeadingConstraint.isActive = false self.bubbleTrailingConstraint.isActive = true case .received: self.changeImage(#imageLiteral(resourceName: "chat-bubble-received")) self.bubbleImageView.tintColor = UIColor(white: 1, alpha: 0.6) self.textLabelTrailingConstraint.constant = GZEChatBubbleView.labelInsets.left self.textLabelLeadingConstraint.constant = -GZEChatBubbleView.labelInsets.right self.bubbleTrailingConstraint.isActive = false self.bubbleLeadingConstraint.isActive = true } } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } override init(frame: CGRect) { super.init(frame: frame) initialize() } init() { super.init(frame: CGRect.zero) initialize() } private func initialize() { self.backgroundColor = .clear self.textLabel.textColor = GZEConstants.Color.chatBubbleTextColor self.textLabel.numberOfLines = 0 self.textLabel.font = GZEChatBubbleView.font self.fakeTextLabel.numberOfLines = 0 self.fakeTextLabel.textColor = .clear self.fakeTextLabel.font = GZEChatBubbleView.font self.bubbleImageView.addSubview(self.fakeTextLabel) self.addSubview(self.bubbleImageView) self.addSubview(self.textLabel) // Constraints self.fakeTextLabel.translatesAutoresizingMaskIntoConstraints = false self.textLabel.translatesAutoresizingMaskIntoConstraints = false self.bubbleImageView.translatesAutoresizingMaskIntoConstraints = false self.bubbleImageView.topAnchor.constraint(equalTo: self.fakeTextLabel.topAnchor, constant: -GZEChatBubbleView.labelInsets.top).isActive = true self.bubbleImageView.bottomAnchor.constraint(equalTo: self.fakeTextLabel.bottomAnchor, constant: GZEChatBubbleView.labelInsets.bottom).isActive = true self.textLabelLeadingConstraint = self.bubbleImageView.leadingAnchor.constraint(equalTo: self.fakeTextLabel.leadingAnchor) self.textLabelTrailingConstraint = self.bubbleImageView.trailingAnchor.constraint(equalTo: self.fakeTextLabel.trailingAnchor) self.textLabelLeadingConstraint.isActive = true self.textLabelTrailingConstraint.isActive = true self.textLabel.topAnchor.constraint(equalTo: self.fakeTextLabel.topAnchor).isActive = true self.textLabel.bottomAnchor.constraint(equalTo: self.fakeTextLabel.bottomAnchor).isActive = true self.textLabel.leadingAnchor.constraint(equalTo: self.fakeTextLabel.leadingAnchor).isActive = true self.textLabel.trailingAnchor.constraint(equalTo: self.fakeTextLabel.trailingAnchor).isActive = true self.topAnchor.constraint(equalTo: self.bubbleImageView.topAnchor, constant: -GZEChatBubbleView.bubblePadding).isActive = true self.bottomAnchor.constraint(equalTo: self.bubbleImageView.bottomAnchor, constant: GZEChatBubbleView.bubblePadding).isActive = true self.bubbleImageView.widthAnchor.constraint(lessThanOrEqualTo: self.widthAnchor, multiplier: GZEChatBubbleView.bubbleWidthProportion).isActive = true self.bubbleLeadingConstraint = self.leadingAnchor.constraint(equalTo: self.bubbleImageView.leadingAnchor) self.bubbleTrailingConstraint = self.trailingAnchor.constraint(equalTo: self.bubbleImageView.trailingAnchor) } private func changeImage(_ image: UIImage) { self.bubbleImageView.image = image .resizableImage( withCapInsets: UIEdgeInsets(top: 15, left: 18, bottom: 15, right: 18), resizingMode: .stretch ) .withRenderingMode(.alwaysTemplate) } }
// // ChatManager.swift // 单一职责原则 // // Created by mxc235 on 2018/4/5. // Copyright © 2018年 FY. All rights reserved. // import Cocoa class ChatManager: NSObject { func loginChatServer() -> () { } func getFriendList() -> () { } func getGroupList() -> () { } func addFriend() -> () { } func joinGroup() -> () { } }
// // FranchiseMarketModel.swift // Airstrike // // Created by BoHuang on 6/23/17. // Copyright © 2017 Airstrike. All rights reserved. // import UIKit class FranchiseMarketModel: NSObject { var franchises: [Franchise]? var selectedFranchise: Franchise? func initialize() { /*guard let managerTeams = try? DAOTeam().getTeams(managerGuid: try DAOUser().getUser()?.id), let league = ServiceConnector.sharedInstance.getDisplayLeague(), let mTeams = managerTeams?.filter({ $0.leagueGuid == league.id }) else { return } teams = mTeams*/ franchises = [Franchise]() for _ in 1...5 { let frenchise = Franchise(id: "idxxxx", name: "Franchise", cost: 30, isNew: true, isForSale: false) franchises?.append(frenchise) } } } // MARK: TableView Information extension FranchiseMarketModel { func sections() -> Int { return 1 } func rows() -> Int { return franchises?.count ?? 0 } func reuseIdentifier() -> String { return "FranchiseMarketTableViewCell" } func franchiseName(for indexPath: IndexPath) -> String { return franchises?[indexPath.item].name ?? "" } func isFranchiseNew(for indexPath: IndexPath) -> Bool { return franchises?[indexPath.item].isNew ?? false } func isFranchiseForSale(for indexPath: IndexPath) -> Bool { return franchises?[indexPath.item].isForSale ?? false } func cellHeight() -> CGFloat { return 60 } func rowSelected(at indexPath: IndexPath) { self.selectedFranchise = franchises?[indexPath.item] } }
// // ConditionComparable.swift // SailingThroughHistory // // Created by Herald on 28/3/19. // Copyright © 2019 Sailing Through History Team. All rights reserved. // protocol ConditionComparable: ComparableOp { associatedtype SomeType where SomeType: Comparable } extension ConditionComparable { var operators: [GenericComparator] { return [ EqualOperator<SomeType>(), NotEqualOperator<SomeType>(), LessThanOperator<SomeType>(), GreaterThanOperator<SomeType>(), LessThanOrEqualOperator<SomeType>(), GreaterThanOrEqualOperator<SomeType>(), TrueOperator() ] } }
import AVFoundation import UIKit import Photos class StartViewController: UIViewController { @IBOutlet weak private var imageView: UIImageView! @IBOutlet weak private var makePhotoButton: UIButton! @IBOutlet weak private var galleryButton: UIButton! @IBOutlet weak private var saveButton: UIButton! private let pickerController = UIImagePickerController() var image : UIImage? var imagesArray = [UIImage]() enum ImageSource { case photoLibrary case camera } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() makeRadius() tappedImageView() pickerController.allowsEditing = true pickerController.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) imageView.image = image navigationController?.setNavigationBarHidden(true, animated: false) } // MARK: - Setup private func makeRadius() { makePhotoButton.layer.cornerRadius = ButtonConstants.startVCButtonRadius galleryButton.layer.cornerRadius = ButtonConstants.startVCButtonRadius saveButton.layer.cornerRadius = ButtonConstants.startVCButtonRadius } // MARK: - Actions @IBAction private func tappedSave(_ sender: Any) { guard let image = imageView.image else { showAlertWith(title: "Error", message: "Choose photo to save") return } if UIImagePickerController.isSourceTypeAvailable(.camera) { UIImageWriteToSavedPhotosAlbum(image, self, #selector(saveImage(_:didFinishSavingWithError:contextInfo:)), nil ) } else { showAlertWith(title: "Error", message: "picture exists") } } @IBAction private func tappedMakePhoto(_ sender: Any) { AVCaptureDevice.requestAccess(for: AVMediaType.video) { response in DispatchQueue.main.async { if response { guard UIImagePickerController.isSourceTypeAvailable(.camera) else { self.selectImageFrom(.photoLibrary) return } } else { self.alertCameraAccessDenied() } } } } @IBAction private func tappedShowGallery(_ sender: Any) { goToGalleryVC() } @objc private func saveImage(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) { if let error = error { showAlertWith(title: "Save error", message: error.localizedDescription) } else { showAlertWith(title: "Saved!", message: "Your image has been saved to your photos.") } } func tappedImageView() { let gesture = UITapGestureRecognizer() gesture.addTarget(self, action: #selector(goToDetailVC(_:))) imageView.addGestureRecognizer(gesture) imageView.isUserInteractionEnabled = true } @objc private func goToDetailVC(_ gesture: UIGestureRecognizer) { let storyboard = UIStoryboard(name: "DetailImage", bundle: nil) let viewController = storyboard.instantiateViewController(identifier: "DetailImageViewController") as DetailImageViewController viewController.modalPresentationStyle = .fullScreen if let image = image { viewController.image = image } navigationController?.pushViewController(viewController, animated: true) } // MARK: - Logic private func alertCameraAccessDenied() { let alert = UIAlertController(title: "ERROR", message: "Not allowed", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default)) self.present(alert, animated: true) } private func selectImageFrom(_ source: ImageSource) { switch source { case .camera: pickerController.sourceType = .camera case .photoLibrary: pickerController.sourceType = .photoLibrary } present(pickerController, animated: true, completion: nil) } private func showAlertWith(title: String, message: String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default)) present(alert, animated: true) } // MARK: - Navigation /* @IBAction private func unwindSegueToStartVC(_ unwindSegue: UIStoryboardSegue) { guard unwindSegue.identifier == "unwindSegue" else { return } guard let sourceVC = unwindSegue.source as? GalleryViewController else { return } imageView.image = sourceVC.image }*/ private func goToGalleryVC() { PHPhotoLibrary.requestAuthorization { (success) in DispatchQueue.main.async { if success == .authorized { self.performSegue(withIdentifier: "goToGalleryVC", sender: nil) } else if success == .denied { let alert = UIAlertController(title: "ERROR", message: "Not allowed", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default)) self.present(alert, animated: true) } } } } } // MARK: - Extentions extension StartViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [ UIImagePickerController.InfoKey: Any ]) { guard let selectedImage = info[.originalImage] as? UIImage else { return } imageView.image = selectedImage pickerController.dismiss(animated: true) } }
// // main.swift // area an volume // // Created by Sahab Alharbi on 06/03/1443 AH. // import Foundation let pi = 3.1415926 print("enter radius r ") let radiusR = Utils.readDouble() let area = pi * (pow(radiusR,2)) let volume = 4 * pi * (pow(radiusR,3)) / 3 print("area is:",area.rounded(), "and volume is:",volume.rounded())
import Foundation public class ToDoListAPI { public var date = DateAPI() public var httpRequest = HTTPRequestAPI() public var dataBase = DataBaseAPI() public var viewService = ViewAPI() }
// // Test.swift // TestFramework // // Created by Лада on 15/11/2019. // Copyright © 2019 Лада. All rights reserved. // import Foundation open class MyTest{ public init(){} public func myPrint() { print("I belive you have a nice day") } }
// // WodsPresenterTests.swift // WODmvpTests // // Created by Will Ellis on 10/10/17. // Copyright © 2017 Will Ellis Inc. All rights reserved. // import XCTest @testable import WODmvp class MockWodsView: WodsView { var calledRenderViewModel = false func render(_ viewModel: WodsViewModel) { calledRenderViewModel = true } } class MockWodsModelProvider: WodsModelProviderType { var subscriber: WodsModelSubscriber? var calledLoadModel = false func loadModel() { calledLoadModel = true } } class WodsPresenterTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func makeMockedWodsPresenter() -> (WodsPresenter, MockWodsView, MockWodsModelProvider) { let mockWodsView = MockWodsView() let mockWodsModelProvider = MockWodsModelProvider() let wodsPresenter = WodsPresenter(mockWodsModelProvider) return (wodsPresenter, mockWodsView, mockWodsModelProvider) } func testSetViewAlsoSetsWodsModelProviderSubscriber() { let (wodsPresenter, mockWodsView, mockWodsModelProvider) = makeMockedWodsPresenter() wodsPresenter.view = mockWodsView XCTAssertNotNil(mockWodsModelProvider.subscriber) XCTAssert(mockWodsModelProvider.subscriber! === wodsPresenter) wodsPresenter.view = nil XCTAssertNil(mockWodsModelProvider.subscriber) } func testUpdateWodsModel() { let (wodsPresenter, mockWodsView, mockWodsModelProvider) = makeMockedWodsPresenter() wodsPresenter.view = mockWodsView wodsPresenter.update(WodsModel()) XCTAssert(mockWodsView.calledRenderViewModel) XCTAssert(mockWodsModelProvider.calledLoadModel) } func testPresentWodDetails() { // TODO: WTE } }
// // PlayGame.swift // TikiTacToe // // Created by Pro on 27.01.2021. // import GameplayKit import SpriteKit class GamePlaying: GKState { var scene: GameScene? var isWaiting: Bool var winsArray = [Int]() init(scene: GameScene) { self.scene = scene isWaiting = false super.init() } override func isValidNextState(_ stateClass: AnyClass) -> Bool { return stateClass == GameEnding.self } override func didEnter(from previousState: GKState?) { isWaiting = false } override func update(deltaTime seconds: TimeInterval) { if !isWaiting { isWaiting = true updateGameState() } } func markLevelAsDone(gameResult: Int) { // to fill array with previous values winsArray = UserDefaults.standard.array(forKey: "winsArr") as? [Int] ?? [] let completed = UserDefaults.standard.integer(forKey: "completedLevel") + 1 print("completed \(completed)") UserDefaults.standard.setValue(completed, forKey: "completedLevel") // 0 - lose, 1 - win, 2 - draw if gameResult == 0 { winsArray.append(0) } else if gameResult == 1 { winsArray.append(1) } else { winsArray.append(2) } print(winsArray) // if level is restarted - delete last chest image from winsArray if UserDefaults.standard.integer(forKey: "restarted") == 1 { winsArray.removeLast() print("winsArr is \(winsArray)") UserDefaults.standard.setValue(0, forKey: "restarted") } UserDefaults.standard.setValue(winsArray, forKey: "winsArr") } func updateGameState() { let (state, winner) = self.scene!.gameBoard!.checkForWinner() if state == .winner { let winLabel = self.scene?.childNode(withName: "winLabel") winLabel?.isHidden = true let winPlayer = self.scene!.gameBoard!.isPlayer1(winner!) ? "1" : "2" if let winLabel = winLabel as? SKSpriteNode, let player1Score = self.scene?.childNode(withName: "//player1Score") as? SKLabelNode, let player2Score = self.scene?.childNode(withName: "//player2Score") as? SKLabelNode { if winPlayer == "1" { winLabel.texture = SKTexture(imageNamed: "winLabel") markLevelAsDone(gameResult: 1) } else if winPlayer == "2" { winLabel.texture = SKTexture(imageNamed: "loseLabel") markLevelAsDone(gameResult: 0) } winLabel.isHidden = false if winPlayer == "1" { player1Score.text = "\(Int(player1Score.text!)! + 1)" } else { player2Score.text = "\(Int(player2Score.text!)! + 1)" } // set scores if (Int(player1Score.text!))! > UserDefaults.standard.integer(forKey: "playerBestScore") { UserDefaults.standard.setValue(Int(player1Score.text!), forKey: "playerBestScore") } if (Int(player2Score.text!))! > UserDefaults.standard.integer(forKey: "machineBestScore") { UserDefaults.standard.setValue(Int(player2Score.text!), forKey: "machineBestScore") } self.stateMachine?.enter(GameEnding.self) isWaiting = false } } else if state == .draw { let winLabel = self.scene?.childNode(withName: "winLabel") winLabel?.isHidden = true if let winLabel = winLabel as? SKSpriteNode { winLabel.texture = SKTexture(imageNamed: "drawLabel") winLabel.isHidden = false } markLevelAsDone(gameResult: 2) self.stateMachine?.enter(GameEnding.self) isWaiting = false } else if self.scene!.gameBoard!.isPlayer2Turn() { let completion = colorActivePlayer(.ai, with: .yellow) self.scene?.isUserInteractionEnabled = false DispatchQueue.global(qos: .default).async { self.scene!.AI.gameModel = self.scene!.gameBoard! let turn = self.scene!.AI.bestMoveForActivePlayer() as? Step let aiTime = CFAbsoluteTimeGetCurrent() let delta = CFAbsoluteTimeGetCurrent() - aiTime let aiTimeMax: TimeInterval = 1.0 let delay = min(aiTimeMax - delta, aiTimeMax) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay) * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC)) { guard let cellNode: SKSpriteNode = self.scene?.childNode(withName: self.scene!.gameBoard!.getElemAtBoardLocation(turn!.cell).node) as? SKSpriteNode else { return } let imgSize = CGSize(width: Consts.cellSize + 40, height: Consts.cellSize + 40) let oo = SKSpriteNode(imageNamed: Consts.oCell) oo.size = imgSize cellNode.alpha = 0.0 cellNode.addChild(oo) let show = SKAction.fadeAlpha(to: 1.0, duration: 0.5) cellNode.run(show) self.scene!.gameBoard!.addPlayerValueAtBoardLocation(turn!.cell, value: .o) self.scene!.gameBoard!.togglePlayer() self.isWaiting = false self.scene?.isUserInteractionEnabled = true completion() } } } else { self.isWaiting = false self.scene?.isUserInteractionEnabled = true } } fileprivate func colorActivePlayer(_ player: CurrentPlayer, with color: UIColor) -> () -> ()? { let labelNodeName = player == .human ? "player1Label" : "player2Label" var font: UIColor? var label: SKLabelNode? if let playerNode = self.scene?.childNode(withName: labelNodeName) as? SKLabelNode { label = playerNode font = playerNode.fontColor playerNode.fontColor = color } let completion = { label?.fontColor = font } return completion } }
// // AppDelegate.swift // Dictionary // // Created by Мария on 20/03/2019. // Copyright © 2019 Мария. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? }
// // SceneNavigatorView.swift // InstaStories // // Created by Nika Shelia on 27.04.20. // Copyright © 2020 Nika Shelia. All rights reserved. // import Foundation import UIKit import YogaKit import RxSwift import RxCocoa class SceneNavigatorView: UIView { let viewModel: SceneNavigatorViewModel let bag = DisposeBag() var closeButton: UIButton! var brushButton: UIButton! var textFieldButton: UIButton! var stickersButton: UIButton! func createCloseButton() -> UIButton { closeButton = createHeaderButton(imageIdentifier: "close") closeButton.rx.tap.subscribe(onNext: { self.viewModel.closeButtonPress.accept(()) }).disposed(by: bag) return closeButton } func createDoneButton() -> UIButton { let doneButton = UIButton(type: .custom) doneButton.setTitle("DONE", for: .normal) doneButton.titleLabel?.font = .boldSystemFont(ofSize: 20) doneButton.configureLayout { (layout) in layout.isEnabled = true } return doneButton } func createHeaderButton(imageIdentifier: String) -> UIButton { let buttonImage = UIImage(named: imageIdentifier) as UIImage? let button = UIButton(type: .custom) button.isUserInteractionEnabled = true button.contentMode = .scaleAspectFill button.configureLayout { (layout) in layout.isEnabled = true layout.width = 40 layout.height = 40 } button.setImage(buttonImage, for: .normal) return button } init(viewModel: SceneNavigatorViewModel, frame: CGRect) { self.viewModel = viewModel super.init(frame: frame) self.configureLayout { layout in layout.isEnabled = true layout.position = .absolute layout.display = .flex layout.width = YGValue(UIScreen.main.bounds.size.width) layout.paddingHorizontal = 20 layout.flexDirection = .row layout.minHeight = 45 layout.alignItems = .center layout.justifyContent = .spaceBetween layout.top = YGValue(Constants.topSafeAreaHeight) } let drawingActionsView = UIView() drawingActionsView.configureLayout { layout in layout.isEnabled = true layout.alignItems = .center layout.flexDirection = .row layout.justifyContent = .center } self.addSubview(createCloseButton()) self.addSubview(drawingActionsView) brushButton = createHeaderButton(imageIdentifier: "brush") brushButton.rx.tap.subscribe(onNext: { self.viewModel.brushButtonPress.accept(()) }).disposed(by: bag) textFieldButton = createHeaderButton(imageIdentifier: "textField") textFieldButton.rx.tap.subscribe(onNext: { self.viewModel.textFieldButtonPress.accept(()) }).disposed(by: bag) stickersButton = createHeaderButton(imageIdentifier: "stickers") stickersButton.rx.tap.subscribe(onNext: { self.viewModel.stickersButtonPress.accept(()) }).disposed(by: bag) drawingActionsView.addSubview(stickersButton) drawingActionsView.addSubview(brushButton) drawingActionsView.addSubview(textFieldButton) self.yoga.applyLayout(preservingOrigin: true) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // TypeCell.swift // Cashbook // // Created by 王越 on 2019/1/16. // Copyright © 2019 王越. All rights reserved. // import UIKit class TypeCell: UITableViewCell { var data:TypeCellModel?{ didSet{ titleLabel.text = data?.title commentLabel.text = data?.comment titleLabel.backgroundColor = UIColor.ColorHex((data?.color!)!) } } lazy var titleLabel:UILabel = { let label = UILabel() label.textAlignment = .center label.font = UIFont.boldSystemFont(ofSize: 15) label.textColor = UIColor.white return label }() lazy var commentLabel:UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 10) return label }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.addSubview(titleLabel) self.addSubview(commentLabel) titleLabel.frame = CGRect(x: 15, y: 10, width: 40, height: 20) commentLabel.frame = CGRect(x: 15, y: self.titleLabel.frame.maxY + 10, width: self.frame.width - 15 - 40, height: 10) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } } extension UIColor{ class func ColorHex(_ color: String) -> UIColor? { if color.count <= 0 || color.count != 7 || color == "(null)" || color == "<null>" { return nil } var red: UInt32 = 0x0 var green: UInt32 = 0x0 var blue: UInt32 = 0x0 let redString = String(color[color.index(color.startIndex, offsetBy: 1)...color.index(color.startIndex, offsetBy: 2)]) let greenString = String(color[color.index(color.startIndex, offsetBy: 3)...color.index(color.startIndex, offsetBy: 4)]) let blueString = String(color[color.index(color.startIndex, offsetBy: 5)...color.index(color.startIndex, offsetBy: 6)]) Scanner(string: redString).scanHexInt32(&red) Scanner(string: greenString).scanHexInt32(&green) Scanner(string: blueString).scanHexInt32(&blue) let hexColor = UIColor.init(red: CGFloat(red)/255.0, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: 1) return hexColor } }
// // Mocks.swift // MovieMasterTests // // Created by Andre & Bianca on 02/02/20. // Copyright © 2020 Andre. All rights reserved. // import Foundation @testable import MovieMaster class Mocks { // var viewModel: MoviesViewModel? func getMovies() -> [Movie] { let movies: [Movie] = [ Movie( id: 330457, title: "Frozen II", popularity: 326.113, overview: "Elsa, Anna, Kristoff and Olaf head far into the forest to learn the truth about an ancient mystery of their kingdom.", voteCount: 654, voteAverage: 7.1, posterPath: "/qdfARIhgpgZOBh3vfNhWS4hmSo3.jpg", originalLanguage: "en", originalTitle: "Frozen II", genreIds: [16, 10402, 10751, 12], backdropPath: "/xJWPZIYOEFIjZpBL7SVBGnzRYXp.jpg", releaseDate: "2019-11-20" ) ] return movies } func getGenres() -> [Genre] { let genres: [Genre] = [ Genre(id: 16, name: "Animation"), Genre(id: 10751, name: "Family"), Genre(id: 10402, name: "Music"), Genre(id: 12, name: "Adventure") ] return genres } func getCasts() -> [Cast] { let casts: [Cast] = [ Cast(id: 40462, character: "Anna (voice)", creditId: "596a859992514136e7017277", name: "Kristen Bell", profilePath: "/9DoDVUkoXhT3O2R1RymPlOfUryl.jpg"), Cast(id: 19394, character: "Elsa (voice)", creditId: "596a858292514136e7017266", name: "Idina Menzel", profilePath: "/eGsyJmAZNV5tUU4RYy2DIRlFVpW.jpg") ] return casts } func getMovieDetail() -> MovieDetail { let movieDetail: MovieDetail = MovieDetail() movieDetail.runtime = 104 movieDetail.genres = getGenres() return movieDetail } }
// // HealthManager.swift // // // Created by Simran Preet S Narang on 18/10/14. // Copyright © 2015 SwiftStudio. All rights reserved. // import Foundation import HealthKit class HealthManager { let storage = HKHealthStore() static let TOTAL_STEPS_COUNT_AS_DOUBE:String = "totalStepsCountAsDouble" static let STEP_RECORD_ARRAY:String = "stepRecordArray" func authorizeHealthKit(completion: ((success: Bool, error: NSError!) -> Void)!) { let healthKitTypesToRead = Set(arrayLiteral: //Fututre enhancements //HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!, //HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)! ) let healthKitTypesToWrite = Set(arrayLiteral: //Fututre enhancements //HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!, //HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!, HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)! ) if(!HKHealthStore.isHealthDataAvailable()) { let error = NSError(domain: "com.CompleteStack", code: 2, userInfo: [NSLocalizedDescriptionKey:"HealthKit is not available in thie Device"]) if(completion != nil) { completion(success:false, error: error) } return ; } storage.requestAuthorizationToShareTypes(healthKitTypesToWrite, readTypes: healthKitTypesToRead) { (success, error) -> Void in if(completion != nil) { completion(success: success, error:error) } } } func recentSteps(completion: (Dictionary<String, AnyObject>, NSError?) -> () ) { var stepsMap: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>() // The type of data we are requesting (this is redundant and could probably be an enumeration let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) // Our search predicate which will fetch data from now until a day ago // (Note, 1.day comes from an extension // You'll want to change that to your own NSDate let date = NSDate() let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! let startDate = cal.startOfDayForDate(date) let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: NSDate(), options: .None) if(!HKHealthStore.isHealthDataAvailable()) { return ; } // The actual HealthKit Query which will fetch all of the steps and sub them up for us. let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: 0, sortDescriptors: nil) { query, results, error in var steps: Double = 0 if results?.count > 0 { var stepRecords:Array<Double> = Array<Double>(); for result in results as! [HKQuantitySample] { stepRecords.append(result.quantity.doubleValueForUnit(HKUnit.countUnit())) steps += result.quantity.doubleValueForUnit(HKUnit.countUnit()) } stepsMap[HealthManager.TOTAL_STEPS_COUNT_AS_DOUBE] = steps; stepsMap[HealthManager.STEP_RECORD_ARRAY] = stepRecords; } completion(stepsMap, error) } storage.executeQuery(query) } func saveSteps(numberOfStepsToSave:Int) { let hkUnit = HKUnit(fromString: "count") let steptype = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) let stepQuantity = HKQuantity(unit: hkUnit, doubleValue: Double(numberOfStepsToSave)) let stepSample = HKQuantitySample(type: steptype!, quantity: stepQuantity, startDate: NSDate(), endDate: NSDate()) storage.saveObject(stepSample, withCompletion: { success, error in if(error != nil) { print("Error Saving Data \(error)") } else { let logger = SyncLogger.sharedInstance logger.storeSyncLogs("FTOH", steps: numberOfStepsToSave) print("Data Saved") } }) } }
// // BuyCell.swift // firstDiploma // // Created by Евгений Войтин on 28.05.2021. // import UIKit class BuyCell: UITableViewCell { @IBOutlet weak var sizeLbl: UILabel! @IBOutlet weak var quantityLbl: UILabel! func initCell(size: String, quant: String){ self.sizeLbl.text = size self.quantityLbl.text = "Осталось: \(quant)" } }
//: [← Previous (SpriteKit Example)](@previous) let boardView = BoardView() import SwiftUI #if os(iOS) let controller = UIHostingController(rootView: boardView) #elseif os(macOS) let controller = NSHostingView(rootView: boardView) #endif import PlaygroundSupport PlaygroundSupport.PlaygroundPage.current.liveView = controller
// // File.swift // ivrit1 // // Created by Patrice Rapaport on 19/08/2018. // Copyright © 2018 Patrice Rapaport. All rights reserved. // import AppKit open class messageBox { var alert: NSAlert! public init (_ aMsg: String) { alert = NSAlert() alert.informativeText = "" alert.messageText = aMsg alert.addButton(withTitle: "Non") alert.addButton(withTitle: "Oui") } public func runModal() -> Bool { if alert.runModal() == NSApplication.ModalResponse.alertSecondButtonReturn { return true } else { return false } } }
// // CurrencyUtilTest.swift // MercadoPagoSDKTests // // Created by Juan sebastian Sanzone on 22/5/18. // Copyright © 2018 MercadoPago. All rights reserved. // import XCTest class CurrencyUtilTest: BaseTest { func test_whenThirdDecimalBelowFiveThenRoundDownWithOneDigit() { let amount: Double = 5.432 let roundedAmount: Double = CurrenciesUtil.getRoundedAmount(amount: amount) assert(roundedAmount .isEqual(to: 5.43)) } func test_whenThirdDecimalAboveFiveThenRoundUpWithOneDigit() { let amount: Double = 5.436 let roundedAmount: Double = CurrenciesUtil.getRoundedAmount(amount: amount) assert(roundedAmount .isEqual(to: 5.44)) } func test_whenThirdDecimalEqualsFiveThenRoundUpWithOneDigit() { let amount: Double = 5.435 let roundedAmount: Double = CurrenciesUtil.getRoundedAmount(amount: amount) assert(roundedAmount .isEqual(to: 5.44)) } func test_whenThirdDecimalBelowFiveThenRoundDownWithTwoDigits() { let amount: Double = 25.432 let roundedAmount: Double = CurrenciesUtil.getRoundedAmount(amount: amount) assert(roundedAmount .isEqual(to: 25.43)) } func test_whenThirdDecimalAboveFiveThenRoundUpWithTwoDigits() { let amount: Double = 25.436 let roundedAmount: Double = CurrenciesUtil.getRoundedAmount(amount: amount) assert(roundedAmount .isEqual(to: 25.44)) } func test_whenThirdDecimalEqualsFiveThenRoundUpWithTwoDigits() { let amount: Double = 25.435 let roundedAmount: Double = CurrenciesUtil.getRoundedAmount(amount: amount) assert(roundedAmount .isEqual(to: 25.44)) } func test_whenThirdDecimalBelowFiveThenRoundDownWithThreeDigits() { let amount: Double = 425.432 let roundedAmount: Double = CurrenciesUtil.getRoundedAmount(amount: amount) assert(roundedAmount .isEqual(to: 425.43)) } func test_whenThirdDecimalEqualsFiveThenRoundUpWithThreeDigits() { let amount: Double = 425.436 let roundedAmount: Double = CurrenciesUtil.getRoundedAmount(amount: amount) assert(roundedAmount .isEqual(to: 425.44)) } func test_whenTwoDecimalsThenDontRound() { let amount: Double = 5.43 let roundedAmount: Double = CurrenciesUtil.getRoundedAmount(amount: amount) assert(roundedAmount .isEqual(to: 5.43)) } func test_whenOneDecimalThenDontRound() { let amount: Double = 5.4 let roundedAmount: Double = CurrenciesUtil.getRoundedAmount(amount: amount) assert(roundedAmount .isEqual(to: 5.4)) } func test_whenThirdDecimalIsNineThenRoundUpWithThreeDigits() { let amount: Double = 425.099 let roundedAmount: Double = CurrenciesUtil.getRoundedAmount(amount: amount) assert(roundedAmount .isEqual(to: 425.10)) } func test_whenThirdDecimalIsFiveThenRoundUpWithThreeDigits() { let amount: Double = 425.005 let roundedAmount: Double = CurrenciesUtil.getRoundedAmount(amount: amount) assert(roundedAmount .isEqual(to: 425.01)) } }
// // Data.swift // YumaApp // // Created by Yuma Usa on 2018-07-02. // Copyright © 2018 Yuma Usa. All rights reserved. // import Foundation extension Data { var digestSHA1: Data { var bytes: [UInt8] = Array(repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH)) withUnsafeBytes { _ = CC_SHA1($0, CC_LONG(count), &bytes) } return Data(bytes: bytes) } var hexString: String { return map { String(format: "%02x", UInt8($0)) }.joined() } }
// // ZGImagePreviewPageControl.swift // Pods // // Created by zhaogang on 2017/7/13. // // import UIKit public class ZGImagePreviewPageControl: ZGImagePreviewBottomView { var pageControl:UIPageControl! public override func setItem(_ item:ZGImagePreviewBottomItemProtocol) { super.setItem(item) guard let bottomItem = self.item else { return } self.setTotal(bottomItem.total) let item2 = bottomItem as! ZGImagePreviewPageControlItem if let pageIndicatorTintColor = item2.pageIndicatorTintColor { self.pageControl.pageIndicatorTintColor = pageIndicatorTintColor } if let currentPageIndicatorTintColor = item2.currentPageIndicatorTintColor { self.pageControl.currentPageIndicatorTintColor = currentPageIndicatorTintColor } } public override init(frame: CGRect) { super.init(frame: frame) let pControl = UIPageControl(frame:CGRect.init(x: 0, y: 0, width: 150, height: 30)) self.addSubview(pControl) self.pageControl = pControl self.isUserInteractionEnabled = false } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func setCurrentIndex(_ index:Int, item:ZGImagePreviewItem) -> Void { self.pageControl.currentPage = index } public func setTotal(_ total:Int) -> Void { self.pageControl.numberOfPages = total var frame = self.pageControl.frame frame.size = self.pageControl.size(forNumberOfPages: total) frame.origin.x = (self.width - frame.size.width) / 2 frame.origin.y = (self.height - frame.size.height) / 2 self.pageControl.frame = frame } public override func layoutSubviews() { super.layoutSubviews() } }
// // Post.swift // iOS Concurrency // // Created by Andrei Chenchik on 9/12/21. // import Foundation // Source: https://jsonplaceholder.typicode.com/posts // Single User's Posts: https://jsonplaceholder.typicode.com/users/1/posts struct Post: Codable, Identifiable { let userId: Int let id: Int let title: String let body: String }
// // ViewController.swift // PikMap // // Created by John Leonardo on 8/29/16. // Copyright © 2016 John Leonardo. All rights reserved. // import UIKit import MapKit import FirebaseDatabase import FirebaseStorage import Firebase class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, MKMapViewDelegate, CLLocationManagerDelegate { @IBOutlet weak var topBanner: UIView! @IBOutlet weak var imagePickerImg: UIImageView! @IBOutlet weak var dropPikBtn: UIButton! @IBOutlet weak var pikPop: UIView! @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var textField: CustomTextField! var imageData: Any? let locationManager = CLLocationManager() var mapCentered = false var geoFire: GeoFire! var geoFireReference: FIRDatabaseReference! let imagePick = UIImagePickerController() var tempId: String? override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self imagePick.delegate = self //to dismiss the keyboard when we tap away from it let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard") view.addGestureRecognizer(tap) //auth user for uploading FIRAuth.auth()?.signInAnonymously(completion: { (user, error) in if error != nil { print("starterror \(error) enderror") return } else { print("logged in") let anon = user!.isAnonymous let uid = user!.uid } }) mapView.userTrackingMode = MKUserTrackingMode.follow geoFireReference = FIRDatabase.database().reference() geoFire = GeoFire(firebaseRef: geoFireReference) } override func viewDidAppear(_ animated: Bool) { locationAuthStatus() } //authorize us for using user location func locationAuthStatus() { if CLLocationManager.authorizationStatus() == .authorizedWhenInUse { mapView.showsUserLocation = true } else { locationManager.requestWhenInUseAuthorization() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // pointless boilerplate code } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == CLAuthorizationStatus.authorizedWhenInUse { mapView.showsUserLocation = true } } func centerMapOnLocation(location: CLLocation) { let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 2000, 2000) mapView.setRegion(coordinateRegion, animated: true) } func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) { if let loc = userLocation.location { if !mapCentered { centerMapOnLocation(location: loc) mapCentered = true } } } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let annoIdentifier = "Pikz" var annotationImg: MKAnnotationView? if annotation.isKind(of: MKUserLocation.self) { annotationImg = MKAnnotationView(annotation: annotation, reuseIdentifier: "User") annotationImg?.image = UIImage(named: "add_feeling_btn.png") } else if let deqAnno = mapView.dequeueReusableAnnotationView(withIdentifier: "Pikz") { annotationImg = deqAnno annotationImg?.annotation = annotation } else { let av = MKAnnotationView(annotation: annotation, reuseIdentifier: annoIdentifier) av.rightCalloutAccessoryView = UIButton(type: .custom) annotationImg = av } if let annotationImg = annotationImg, let anno = annotation as? PikAnnotation { //if annotation is NOT user, then make it have these properties annotationImg.canShowCallout = true annotationImg.image = UIImage(named: "annoimg2.png") let btn = UIButton() btn.frame = CGRect(x: 0, y: 0, width: 30, height: 30) btn.setImage(UIImage(named: "searchbutton.png"), for: .normal) annotationImg.rightCalloutAccessoryView = btn } return annotationImg } //passing the segue ID over to the next VC, so it knows which pic/caption to display override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "goToPik" { var svc = segue.destination as! PikController svc.segId = tempId } } //boilerplate imagepicker stuff func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let pickedImg = info[UIImagePickerControllerOriginalImage] as? UIImage { imagePickerImg.contentMode = .scaleAspectFit imagePickerImg.image = pickedImg } dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } //when region changes, show piks in radius func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) { let loc = CLLocation(latitude: mapView.centerCoordinate.latitude, longitude: mapView.centerCoordinate.longitude) showPiks(location: loc) } //GeoFire in action. this creates a database entry with the long/lat func dropPik(forLocation location:CLLocation, withImage imageId: String) { geoFire.setLocation(location, forKey: imageId) } //when callout is tapped, segue over to vc that has the pik/caption //set tempId to the iid from the annotation //this tells us which pic were actually viewing func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if let anno = view.annotation as? PikAnnotation { tempId = anno.iid self.performSegue(withIdentifier: "goToPik", sender: self) } } @IBAction func postPik(_ sender: AnyObject) { topBanner.isHidden = true pikPop.isHidden = false dropPikBtn.isHidden = true } @IBAction func closePikPop(_ sender: AnyObject) { topBanner.isHidden = false pikPop.isHidden = true dropPikBtn.isHidden = false imagePickerImg.image = UIImage(named: "photobtn.png") } @IBAction func imagePickerBtn(_ sender: AnyObject) { imagePick.allowsEditing = false imagePick.sourceType = .photoLibrary present(imagePick, animated: true, completion: nil) } @IBAction func uploadPik(_ sender: AnyObject) { //first, we're gonna check if it has an image selected, and caption isnt nil if imagePickerImg.image != UIImage(named: "photobtn.png") && textField.text != "" { if let uploadData = UIImageJPEGRepresentation(imagePickerImg.image!, 0.2) { //create a random UID for the image. helps SO much. let iid = NSUUID().uuidString.lowercased() //setting customMetadata to hold our caption in the photo var meta = FIRStorageMetadata() meta.customMetadata = ["caption" : self.textField.text!] //uploading photo to Firebase. It will name the photo the ID that it gen'd let imageRef = storageRef.child(iid) imageRef.put(uploadData, metadata: meta, completion: { (metadata, error) in if error != nil { print(error) return } else { let loc: CLLocation? /*** Okay, I know this is some really weird error handling, but basically were gonna try to get the current user location and for some reason if it fails, were just gonna get the map center and use that as the location. if lat isnt nil, then we know long wont be either, so that's what that's all about***/ let lat = self.locationManager.location?.coordinate.latitude let lon = self.locationManager.location?.coordinate.longitude if lat != nil { loc = CLLocation(latitude: lat!, longitude: lon!) } else { loc = CLLocation(latitude: self.mapView.centerCoordinate.latitude, longitude: self.mapView.centerCoordinate.longitude) } self.dropPik(forLocation: loc!, withImage: iid) print(metadata) } }) } //revert UI back to defaults when were done uploading, and close popup self.textField.text = "" imagePickerImg.image = UIImage(named: "photobtn.png") pikPop.isHidden = true topBanner.isHidden = false dropPikBtn.isHidden = false } else { //if user doesnt have text or pic let aC1 = UIAlertController(title: "Oops", message: "You need to have a picture and a caption! :(", preferredStyle: .alert) let okAction = UIAlertAction(title:"K", style: .cancel) { (action) in //idk... } aC1.addAction(okAction) self.present(aC1, animated: true, completion: nil) } } func dismissKeyboard() { view.endEditing(true) } //showing piks in the radius defined, and making a query using GeoFire func showPiks(location: CLLocation) { let circleQuery = geoFire!.query(at: location, withRadius: 2.5) _ = circleQuery?.observe(GFEventType.keyEntered, with: { (iid, location) in if let iid = iid, let location = location { let anno = PikAnnotation(coordinate: location.coordinate, iid: iid) self.mapView.addAnnotation(anno) } }) } }
// // Router.swift // Coordinator Example // // Created by yuriy.p on 17.12.2020. // import Foundation /// Маркер-протокол для реализации роутинга protocol Router {}
import Foundation import Bow /// A callback that receives an error or a value. public typealias Callback<E, A> = (Either<E, A>) -> Void /// An asynchronous operation that might fail. public typealias Proc<E, A> = (@escaping Callback<E, A>) -> Void /// An asynchronous operation that might fail. public typealias ProcF<F, E, A> = (@escaping Callback<E, A>) -> Kind<F, Void> /// Async models how a data type runs an asynchronous computation that may fail, described by the `Proc` signature. public protocol Async: MonadDefer { /// Suspends side effects in the provided registration function. The parameter function is injected with a side-effectful callback for signaling the result of an asynchronous process. /// /// - Parameter procf: Asynchronous operation. /// - Returns: A computation describing the asynchronous operation. static func asyncF<A>(_ procf: @escaping ProcF<Self, E, A>) -> Kind<Self, A> /// Switches the evaluation of a computation to a different `DispatchQueue`. /// /// - Parameters: /// - fa: A computation. /// - queue: A Dispatch Queue. /// - Returns: A computation that will run on the provided queue. static func continueOn<A>( _ fa: Kind<Self, A>, _ queue: DispatchQueue) -> Kind<Self, A> } public extension Async { /// Suspends side effects in the provided registration function. The parameter function is injected with a side-effectful callback for signaling the result of an asynchronous process. /// /// - Parameter proc: Asynchronous operation. /// - Returns: A computation describing the asynchronous operation. static func async<A>(_ proc: @escaping Proc<E, A>) -> Kind<Self, A> { asyncF { cb in later { proc(cb) } } } /// Provides a computation that evaluates the provided function on every run. /// /// - Parameter queue: Dispatch queue which the computation must be sent to. /// - Parameter f: Function returning a value. /// - Returns: A computation that defers the execution of the provided function. static func `defer`<A>( _ queue: DispatchQueue, _ f: @escaping () -> Kind<Self, A>) -> Kind<Self, A> { pure(()).continueOn(queue).flatMap(f) } /// Provides a computation that evaluates the provided function on every run. /// /// - Parameter queue: Dispatch queue which the computation must be sent to. /// - Parameter f: Function returning a value. /// - Returns: A computation that defers the execution of the provided function. static func later<A>( _ queue: DispatchQueue, _ f: @escaping () throws -> A) -> Kind<Self, A> { Self.defer(queue) { do { return pure(try f()) } catch let e as Self.E { return raiseError(e) } catch { fatalError("Unexpected error happened: \(error)") } } } /// Provides a computation that evaluates the provided function on every run. /// /// - Parameter queue: Dispatch queue which the computation must be sent to. /// - Parameter f: A function that provides a value or an error. /// - Returns: A computation that defers the execution of the provided value. static func delayOrRaise<A>( _ queue: DispatchQueue, _ f: @escaping () -> Either<E, A>) -> Kind<Self, A> { Self.defer(queue) { f().fold(raiseError, pure) } } /// Provides an asynchronous computation that never finishes. /// /// - Returns: An asynchronous computation that never finishes. static func never<A>() -> Kind<Self, A> { async { _ in } } } // MARK: Syntax for Async public extension Kind where F: Async { /// Suspends side effects in the provided registration function. The parameter function is injected with a side-effectful callback for signaling the result of an asynchronous process. /// /// - Parameter procf: Asynchronous operation. /// - Returns: A computation describing the asynchronous operation. static func asyncF(_ procf: @escaping ProcF<F, F.E, A>) -> Kind<F, A> { F.asyncF(procf) } /// Switches the evaluation of a computation to a different `DispatchQueue`. /// /// - Parameters: /// - queue: A Dispatch Queue. /// - Returns: A computation that will run on the provided queue. func continueOn(_ queue: DispatchQueue) -> Kind<F, A> { F.continueOn(self, queue) } /// Suspends side effects in the provided registration function. The parameter function is injected with a side-effectful callback for signaling the result of an asynchronous process. /// /// - Parameter proc: Asynchronous operation. /// - Returns: A computation describing the asynchronous operation. static func async(_ fa: @escaping Proc<F.E, A>) -> Kind<F, A> { F.async(fa) } /// Provides a computation that evaluates the provided function on every run. /// /// - Parameter queue: Dispatch queue which the computation must be sent to. /// - Parameter f: Function returning a value. /// - Returns: A computation that defers the execution of the provided function. static func `defer`( _ queue: DispatchQueue, _ f: @escaping () -> Kind<F, A>) -> Kind<F, A> { F.defer(queue, f) } /// Provides a computation that evaluates the provided function on every run. /// /// - Parameter queue: Dispatch queue which the computation must be sent to. /// - Parameter f: Function returning a value. /// - Returns: A computation that defers the execution of the provided function. static func later( _ queue: DispatchQueue, _ f: @escaping () throws -> A) -> Kind<F, A> { F.later(queue, f) } /// Provides a computation that evaluates the provided function on every run. /// /// - Parameter queue: Dispatch queue which the computation must be sent to. /// - Parameter f: A function that provides a value or an error. /// - Returns: A computation that defers the execution of the provided value. static func delayOrRaise<A>( _ queue: DispatchQueue, _ f: @escaping () -> Either<F.E, A>) -> Kind<F, A> { F.delayOrRaise(queue, f) } /// Provides an asynchronous computation that never finishes. /// /// - Returns: An asynchronous computation that never finishes. static func never() -> Kind<F, A> { F.never() } } // MARK: Async syntax for DispatchQueue public extension DispatchQueue { /// Provides an asynchronous computation that runs on this queue. /// /// - Returns: An asynchronous computation that runs on this queue. func shift<F: Async>() -> Kind<F, Void> { F.later(self) {} } }
import Foundation //1 Implement BFS for the Matrix Graph class GraphArr { var arrOfValues: [Int] = [] var arrOfLinks: [[Int]] = [] func addElem(value: Int) { arrOfValues.append(value) arrOfLinks.append(Array(repeatElement(0, count: arrOfValues.count-1))) arrOfLinks = arrOfLinks.map({ $0 + [0] }) } func addLink(fromIndex: Int, toIndex: Int, feedback: Bool) { arrOfLinks[toIndex][fromIndex] = 1 if feedback { arrOfLinks[fromIndex][toIndex] = 1 } } func BFS(key: Int) -> Bool { var visited = [Bool](repeatElement(false, count: arrOfValues.count)) var queue: [Int] = [] func isVisited(i: Int) -> Int? { if !visited[i] { return i } if !queue.isEmpty { return isVisited(i: queue.removeFirst()) } return nil } func BFS(key: Int, indexOfHead: Int) -> Bool { print("take head: \(arrOfValues[indexOfHead])") if key == arrOfValues[indexOfHead] { return true } for i in 0..<arrOfLinks[indexOfHead].count { if arrOfLinks[indexOfHead][i] == 1 { print("found childs: \(arrOfValues[i])") queue.append(i) visited[indexOfHead] = true } } for _ in 0..<queue.count { guard let index = isVisited(i: queue.removeFirst()) else { return false } return BFS(key: key, indexOfHead: index) } return false } return BFS(key: key, indexOfHead: 0) } func printGraph() { let newArr: [String] = arrOfValues.map{ String($0) } print( " " + newArr.joined(separator: " ")) for i in 0..<arrOfValues.count { let newArrLinks: [String] = arrOfLinks[i].map{ String($0) } let n = newArrLinks.joined(separator: " ") print("\(arrOfValues[i])| \(n)") } } } var obj = GraphArr() obj.addElem(value: 1) obj.addElem(value: 2) obj.addElem(value: 3) obj.addElem(value: 4) obj.addElem(value: 5) obj.addElem(value: 6) obj.addLink(fromIndex: 0, toIndex: 1, feedback: true) obj.addLink(fromIndex: 0, toIndex: 2, feedback: true) obj.addLink(fromIndex: 2, toIndex: 4, feedback: true) obj.addLink(fromIndex: 2, toIndex: 3, feedback: true) obj.addLink(fromIndex: 1, toIndex: 5, feedback: true) obj.addLink(fromIndex: 1, toIndex: 4, feedback: true)
// // StoryIoT.swift // StoryIoT // // Created by Oleksandr Yolkin on 6/4/19. // Copyright © 2019 Breffi. All rights reserved. // import Foundation import Alamofire import CoreLocation let timeoutInterval: TimeInterval = 120 // MARK: - SIOTFeedDirection public enum SIOTFeedDirection: String { case forward case backward } // MARK: - StoryIoT public class StoryIoT { private let authCredentials: SIOTAuthCredentials private let manager = Alamofire.Session.default public init(credentials: SIOTAuthCredentials) { self.authCredentials = credentials self.manager.session.configuration.timeoutIntervalForRequest = timeoutInterval } public init?(raw input: String) { let items = input.components(separatedBy: "=") guard items.count > 4 else { return nil } let endpoint = items[0] let hub = items[1] let key = items[2] let secret = items[3] var expirationTimeInterval: TimeInterval = 180 if items.count > 5 { if let timeInterval = TimeInterval(items[4]) { expirationTimeInterval = timeInterval } } self.authCredentials = SIOTAuthCredentials(endpoint: endpoint, hub: hub, key: key, secret: secret, expiration: expirationTimeInterval) self.manager.session.configuration.timeoutIntervalForRequest = timeoutInterval } // MARK: - Publish public func publish(message: SIOTMessageModel, success: @escaping (_ publishResponse: SIOTPublishResponse, _ dataResponse: DataResponse<Any, AFError>) -> Void, failure: @escaping (_ error: NSError, _ dataResponse: DataResponse<Any, AFError>?) -> Void) { switch message.body { case .json: self.internalPublishSmall(message: message, success: success, failure: failure) case .data: self.internalPublishLarge(message: message, success: success, failure: failure) } } // MARK: * Small @available(*, deprecated, renamed: "publish") public func publishSmall(message: SIOTMessageModel, success: @escaping (_ response: SIOTPublishResponse) -> Void, failure: @escaping (_ error: NSError) -> Void) { self.internalPublishSmall(message: message) { publishResponse, _ in success(publishResponse) } failure: { error, _ in failure(error) } } func internalPublishSmall(message: SIOTMessageModel, success: @escaping (_ response: SIOTPublishResponse, _ dataResponse: DataResponse<Any, AFError>) -> Void, failure: @escaping (_ error: NSError, _ dataResponse: DataResponse<Any, AFError>?) -> Void) { guard let url = publishRequestUrl() else { let err = SIOTError.make(description: "Can't get requestUrl", reason: nil) failure(err, nil) return } guard case let SIOTMessageModel.BodyModel.json(jsonBody) = message.body else { let err = SIOTError.make(description: "Wrong body type of SIOTMessageModel for publishSmall", reason: nil) failure(err, nil) return } let metadata = SIOTMetadataModel(message: message) var headers = HTTPHeaders(metadata.asDictionary()) headers["Content-Type"] = "application/json" var jsonData: Data do { jsonData = try JSONSerialization.data(withJSONObject: jsonBody, options: .prettyPrinted) } catch { let err = SIOTError.make(description: "Can't serialize body to jsonData", reason: error.localizedDescription) failure(err, nil) return } var request = URLRequest(url: url) request.httpMethod = HTTPMethod.post.rawValue request.allHTTPHeaderFields = headers.dictionary request.httpBody = jsonData AF.request(request).responseJSON { response in switch response.result { case .success: if let data = response.data { do { let jsonResponse = try JSONDecoder().decode(SIOTPublishResponse.self, from: data) success(jsonResponse, response) } catch let err { print(err.localizedDescription) let err = SIOTError.make(description: "Can't decode SIOTPublishResponse data", reason: nil) failure(err, response) } } else { let err = SIOTError.make(description: "SIOTPublishResponse data is nil", reason: nil) failure(err, nil) } case let .failure(error): print(error.localizedDescription) failure(error as NSError, response) } } } // MARK: * Large /// Большие данные. Этот тип сообщения позволяет загружать сообщения размер которых ограничивается только реализацией хранилища сообщений. Стандартное хранилище позволяет хранить сообщения размером до 2TB каждое. Публикация сообщений этого типа существенно отличается от публикации маленького сообщения. /// Публикация сообщения возможна только по протоколу HTTPS. Процесс выглядит следующим образом: /// Издатель публикует сообщение в конечную точку с пустым телом. Если авторизация и валидация сообщения прошла успешно, сервер присваивает сообщению уникальный идентификатор, извлекает метаданные из сообщения и создает пустой объект в хранилище сообщений. Это сообщение не будет видно в ленте. @available(*, deprecated, renamed: "publish") public func publishLarge(message: SIOTMessageModel, success: @escaping (_ response: SIOTPublishResponse) -> Void, failure: @escaping (_ error: NSError) -> Void) { self.internalPublishLarge(message: message) { publishResponse, _ in success(publishResponse) } failure: { error, _ in failure(error) } } func internalPublishLarge(message: SIOTMessageModel, success: @escaping (_ response: SIOTPublishResponse, _ dataResponse: DataResponse<Any, AFError>) -> Void, failure: @escaping (_ error: NSError, _ dataResponse: DataResponse<Any, AFError>?) -> Void) { guard let url = publishRequestUrl() else { let err = SIOTError.make(description: "Can't get requestUrl", reason: nil) failure(err, nil) return } guard case let SIOTMessageModel.BodyModel.data(bodyData) = message.body else { let error = SIOTError.make(description: "Wrong body type of SIOTMessageModel for publishLarge", reason: nil) failure(error, nil) return } let metadata = SIOTMetadataModel(message: message) var headers = HTTPHeaders(metadata.asDictionary()) headers["Content-Type"] = "application/json" var request = URLRequest(url: url) request.httpMethod = HTTPMethod.post.rawValue request.allHTTPHeaderFields = headers.dictionary AF.request(request).responseJSON { response in switch response.result { case .success: if let data = response.data { let utf8Text = String(data: data, encoding: .utf8) print("Data: \(String(describing: utf8Text))") do { let jsonResponse = try JSONDecoder().decode(SIOTPublishResponse.self, from: data) /// В ответе клиенту отдается сообщение, которое имеет поле Path. Это поле содержит URL по которому методом PUT необходимо выполнить загрузку. Перед загрузкой необходимо сделать хэш sha512 и закодировать байт массив в base64 (без замены символов “/” и “+”). Результат нужно упаковать в строку вида: /// “base64;sha512;{полученный хэш}”. /// Пример: /// “base64;sha512;mLnMEO1f1+ox0Aom+a+clb9T2V9bVxAlVDl4vtaIUY8nLPtHUc3RXHCEQMdaxIFOLMrpdqGkbjSdoVVLStTCZg==” /// При запросе необходимо добавить два заголовка один их которых - это получившийся хэш: /// x-ms-blob-type: BlockBlob /// x-ms-meta-hash: base64;sha512;BR0anYfPZHNYQofX2pojuATumdKOziOmW3Ad0j7FNiNgM1zuPUPu9s7rQRDMFLvSQddrdwbQtj9nonHlKk8ggg== /// Ссылка будет рабочей 24 часа, после чего нужно запросить новую ссылку, в случае неудачи и повторять этот процесс до успешной загрузки большого сообщения. if let messageId = jsonResponse.id, let path = jsonResponse.path, let url = URL(string: path) { self.uploadLargeData(bodyData, url: url) { uploadDataResponse in self.confirmLarge(messageId: messageId) { confirmPublishResponse, confirmDataResponse in success(confirmPublishResponse, confirmDataResponse) } failure: { confirmError, confirmDataResponse in failure(confirmError, confirmDataResponse) } } failure: { uploadError, uploadDataResponse in failure(uploadError, uploadDataResponse) } } else { let error = SIOTError.make(description: "response.path is nil or can't get url from path", reason: nil) failure(error, response) } } catch let err { print(err.localizedDescription) let err = SIOTError.make(description: "Can't decode SIOTPublishResponse data", reason: err.localizedDescription) failure(err, response) } } else { let err = SIOTError.make(description: "SIOTPublishResponse data is nil", reason: nil) failure(err, nil) } case let .failure(error): print(error.localizedDescription) failure(error as NSError, response) } } } private func uploadLargeData(_ data: Data, url: URL, success: @escaping (_ dataResponse: DataResponse<Any, AFError>) -> Void, failure: @escaping (_ error: NSError, _ dataResponse: DataResponse<Any, AFError>?) -> Void) { let hash = data.digest(.sha512).base64EncodedString() let hashResult = "base64;sha512;\(hash)" let headers = HTTPHeaders([ "x-ms-blob-type": "BlockBlob", "x-ms-meta-hash": hashResult, ]) var request = URLRequest(url: url) request.httpMethod = HTTPMethod.put.rawValue request.allHTTPHeaderFields = headers.dictionary request.httpBody = data AF.request(request).responseJSON { response in if let statusCode = response.response?.statusCode, statusCode == 201 { success(response) } else { if let error = response.error { failure(error as NSError, response) } else { let error = SIOTError.make(description: "Error while uploadLargeData", reason: nil) failure(error, response) } } } } private func confirmLarge(messageId: String, success: @escaping (_ publishResponse: SIOTPublishResponse, _ dataResponse: DataResponse<Any, AFError>) -> Void, failure: @escaping (_ error: NSError, _ dataResponse: DataResponse<Any, AFError>?) -> Void) { guard let url = getConfirmLargeUrl(messageId: messageId) else { let err = SIOTError.make(description: "Can't get requestUrl", reason: nil) failure(err, nil) return } manager.request(url, method: .put, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { response in switch response.result { case .success: if let data = response.data { let jsonDecoder = JSONDecoder() do { let jsonResponse = try jsonDecoder.decode(SIOTPublishResponse.self, from: data) success(jsonResponse, response) } catch let err { print(err.localizedDescription) let err = SIOTError.make(description: "Can't decode SIOTPublishResponse data", reason: err.localizedDescription) failure(err, response) } } else { let err = SIOTError.make(description: "SIOTPublishResponse data is nil", reason: nil) failure(err, response) } case let .failure(error): print(error.localizedDescription) failure(error as NSError, response) } } } // MARK: - Storage /// Хранилище сообщений позволяет получать сообщение по идентификатору и управлять его мета данными. /// public func getMessage(withMessgaeId messageId: String, success: @escaping (_ publishResponse: SIOTPublishResponse, _ dataResponse: DataResponse<Any, AFError>) -> Void, failure: @escaping (_ error: NSError, _ dataResponse: DataResponse<Any, AFError>?) -> Void) { guard let url = getStorageRequestUrl(withMessageId: messageId) else { let err = SIOTError.make(description: "Can't get requestUrl", reason: nil) failure(err, nil) return } self.manager.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { response in switch response.result { case .success: if let data = response.data { let jsonDecoder = JSONDecoder() do { let jsonResponse = try jsonDecoder.decode(SIOTPublishResponse.self, from: data) success(jsonResponse, response) } catch let err { print(err.localizedDescription) let err = SIOTError.make(description: "Can't decode SIOTPublishResponse data", reason: err.localizedDescription) failure(err, response) } } else { let err = SIOTError.make(description: "SIOTPublishResponse data is nil", reason: nil) failure(err, response) } case let .failure(error): print(error.localizedDescription) failure(error as NSError, response) } } } /// Метаданные можно изменять - задавать или удалять поля. Метод PUT позволяет задать значение. Если до этого такого значения не было то оно будет создано иначе значение заменяется новым. /// public func updateMeta(metaName: String, withNewValue newValue: String, inMessageWithId messageId: String, success: @escaping (_ publishResponse: SIOTPublishResponse, _ dataResponse: DataResponse<Any, AFError>) -> Void, failure: @escaping (_ error: NSError, _ dataResponse: DataResponse<Any, AFError>?) -> Void) { guard let url = updateStorageRequestUrl(withMessageId: messageId, metaName: metaName) else { let err = SIOTError.make(description: "Can't get requestUrl", reason: nil) failure(err, nil) return } let headers = HTTPHeaders([ "Content-Type": "application/json", ]) var request = URLRequest(url: url) request.httpMethod = HTTPMethod.put.rawValue request.allHTTPHeaderFields = headers.dictionary request.httpBody = newValue.data(using: .utf8) AF.request(request).responseJSON { response in switch response.result { case .success: if let data = response.data { let jsonDecoder = JSONDecoder() do { let jsonResponse = try jsonDecoder.decode(SIOTPublishResponse.self, from: data) success(jsonResponse, response) } catch let err { print(err.localizedDescription) let err = SIOTError.make(description: "Can't decode SIOTPublishResponse data", reason: err.localizedDescription) failure(err, response) } } else { let err = SIOTError.make(description: "SIOTPublishResponse data is nil", reason: nil) failure(err, response) } case let .failure(error): print(error.localizedDescription) failure(error as NSError, response) } } } /// Для того, чтобы удалить метаданные необходимо использовать метод DELETE и указать название поля которое надо удалить. Если поле существует то оно будет удалено иначе операция будет проигнорирована без возникновения ошибки. /// public func deleteMeta(metaName: String, inMessageWithId messageId: String, success: @escaping (_ publishResponse: SIOTPublishResponse, _ dataResponse: DataResponse<Any, AFError>) -> Void, failure: @escaping (_ error: NSError, _ dataResponse: DataResponse<Any, AFError>?) -> Void) { guard let url = deleteStorageRequestUrl(withMessageId: messageId, metaName: metaName) else { let err = SIOTError.make(description: "Can't get requestUrl", reason: nil) failure(err, nil) return } self.manager.request(url, method: .delete, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { response in switch response.result { case .success: if let data = response.data { let jsonDecoder = JSONDecoder() do { let jsonResponse = try jsonDecoder.decode(SIOTPublishResponse.self, from: data) success(jsonResponse, response) } catch let err { print(err.localizedDescription) let err = SIOTError.make(description: "Can't decode SIOTPublishResponse data", reason: err.localizedDescription) failure(err, response) } } else { let err = SIOTError.make(description: "SIOTPublishResponse data is nil", reason: nil) failure(err, response) } case let .failure(error): print(error.localizedDescription) failure(error as NSError, response) } } } // MARK: - Feed /// Лента сообщений предоставляет доступ к хранилищу сообщения представляя его в виде последовательного набора сообщений отсортированных по дате добавления сообщений в хранилище в порядке возрастания. В ленте отображаются только подтвержденные сообщения. /// В ленте сообщения расположены по порядку одно за другим в том порядке в котором они публикуются издателями. По этому, ленту можно обойти выбирая сообщения страницами в двух направлениях - от начала в конец и наоборот. /// Обход ленты сообщений осуществляется посредством токена продолжения. Вместе со страницей в заголовке ответа передается токен продолжение. Чтобы получить следующую страницу необходимо в следующий запрос передать токен продолженя и будет возвращена следующая страница. Таким образом, при первом запросе сервером устанавливается курсор и при каждом последующем запросе курсор смещается. Таким образом можно обойти все летнту сообщений в двух направления, указывая токен продолжения из предыдущего запроса и направление обхода ленты. /// Если токен не указан, то курсор устанавливается на первое сообщение в хранилище. После того, как будет произведена выборка первых записей в заголовке будет возвращен токен продолжения. Так начинается обход ленты. /// Токен продолжения можно сохранять и в любой момент продолжить получать новые сообщения для обработки. public func getFeed(token: String?, direction: SIOTFeedDirection, size: Int, success: @escaping (_ publishResponses: [SIOTPublishResponse], _ token: String?, _ dataResponse: DataResponse<Any, AFError>) -> Void, failure: @escaping (_ error: NSError, _ dataResponse: DataResponse<Any, AFError>?) -> Void) { guard let url = getFeedRequestUrl(token: token, direction: direction, size: size) else { let err = SIOTError.make(description: "Can't get requestUrl", reason: nil) failure(err, nil) return } self.manager.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { response in switch response.result { case .success: if let data = response.data { let token = response.response?.allHeaderFields["cursor-position"] as? String let jsonDecoder = JSONDecoder() do { let jsonResponse = try jsonDecoder.decode([SIOTPublishResponse].self, from: data) success(jsonResponse, token, response) } catch let err { print(err.localizedDescription) let err = SIOTError.make(description: "Can't decode SIOTPublishResponse data", reason: err.localizedDescription) failure(err, response) } } else { let err = SIOTError.make(description: "SIOTPublishResponse data is nil", reason: nil) failure(err, response) } case let .failure(error): print(error.localizedDescription) failure(error as NSError, response) } } } } // MARK: - URLs private extension StoryIoT { /// /// Каждый запрос к серверу имеет URL типа: /// {{endpoint}}/{{hub}}/feed/?key={{key}}&expiration={{expiration}}&signature={{signature}}. /// private func publishRequestUrl() -> URL? { guard let signatureInfo = self.generateSignatureInfo() else { return nil } let requestString = "\(authCredentials.endpoint)/\(authCredentials.hub)/publish/?key=\(authCredentials.key)&expiration=\(signatureInfo.expiration)&signature=\(signatureInfo.signature)" return URL(string: requestString) } private func getStorageRequestUrl(withMessageId messageId: String) -> URL? { guard let signatureInfo = self.generateSignatureInfo() else { return nil } let requestString = "\(authCredentials.endpoint)/\(authCredentials.hub)/storage/\(messageId)/?key=\(authCredentials.key)&expiration=\(signatureInfo.expiration)&signature=\(signatureInfo.signature)" return URL(string: requestString) } private func updateStorageRequestUrl(withMessageId messageId: String, metaName: String) -> URL? { guard let signatureInfo = self.generateSignatureInfo() else { return nil } let requestString = "\(authCredentials.endpoint)/\(authCredentials.hub)/storage/\(messageId)/meta/\(metaName)/?key=\(authCredentials.key)&expiration=\(signatureInfo.expiration)&signature=\(signatureInfo.signature)" return URL(string: requestString) } private func deleteStorageRequestUrl(withMessageId messageId: String, metaName: String) -> URL? { return updateStorageRequestUrl(withMessageId: messageId, metaName: metaName) } private func getFeedRequestUrl(token: String?, direction: SIOTFeedDirection, size: Int) -> URL? { guard let signatureInfo = self.generateSignatureInfo() else { return nil } var requestString = "\(authCredentials.endpoint)/\(authCredentials.hub)/feed/?key=\(authCredentials.key)&expiration=\(signatureInfo.expiration)&signature=\(signatureInfo.signature)&direction=\(direction.rawValue)&size=\(size)" if let token = token { requestString = requestString + "&token=\(token)" } return URL(string: requestString) } private func getConfirmLargeUrl(messageId: String) -> URL? { guard let signatureInfo = self.generateSignatureInfo() else { return nil } let requestString = "\(authCredentials.endpoint)/\(authCredentials.hub)/publish/\(messageId)/confirm/?key=\(authCredentials.key)&expiration=\(signatureInfo.expiration)&signature=\(signatureInfo.signature)" return URL(string: requestString) } // MARK: * Signature private func buildSignature(expiration: String) -> String? { let signBuilder = SIOTSignBuilder(privateKey: self.authCredentials.secret) signBuilder.add(key: "key", value: self.authCredentials.key) signBuilder.add(key: "expiration", value: expiration) return signBuilder.result() } private func generateSignatureInfo() -> (expiration: String, signature: String)? { let expirationString = ISO8601DateFormatter().string(from: Date(timeIntervalSinceNow: self.authCredentials.expirationTimeInterval)) guard let signature = self.buildSignature(expiration: expirationString) else { return nil } return (expiration: expirationString, signature: signature) } }
// // ViewController.swift // PitStop // // Created by Peter Huang on 26/10/2019. // import UIKit import Firebase //import PythonKit class PrePitstopViewController: UIViewController { @IBOutlet var heightConstraint: NSLayoutConstraint! @IBOutlet weak var BeginPitstop: UIButton! override func viewDidLoad() { super.viewDidLoad() BeginPitstop.layer.cornerRadius = 10 let pkA = PythonTesterA.init() pkA.loadSimpleFn() //pkA.numpyTest() //pkA.tester2() } @IBAction func beginPressed(_ sender: UIButton) { print("Executing python file!") //let file = Python.open("filename") } @IBAction func logOutPressed(_ sender: AnyObject) { do { try Auth.auth().signOut() navigationController?.popToRootViewController(animated: true) } catch { print("Error, there was a problem signing out") } } }
// // TasksVC.swift // Project // // Created by Peethambaram, Lavanya on 10/24/19. // Copyright © 2019 Peethambaram, Lavanya. All rights reserved. // import UIKit class TasksVC: UIViewController { @IBOutlet weak var segCtrlTasks: UISegmentedControl! @IBOutlet weak var lblTasks: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func segCtrlSelect(_ sender: Any) { switch segCtrlTasks.selectedSegmentIndex { case 0: lblTasks.text = "No overdues, tap '+' to add." case 1: lblTasks.text = "No important tasks assigned, tap '+' to add." case 2: lblTasks.text = "No projects added, tap '+' to add" case 3: lblTasks.text = "No files to be uploaded.. " default: break } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
// // MockAPI.swift // RijksMuseumTests // // Created by Alexander Vorobjov on 1/2/21. // import Alamofire @testable import RijksMuseum enum MockAPI { static let paramName = "paramName" static let paramValue = "paramValue" case test case overrideDefault } extension MockAPI: API { var path: String { return "/api/en/collection" } var parameters: Parameters { switch self { case .test: return [Self.paramName: Self.paramValue] case .overrideDefault: return [ Self.paramName: Self.paramValue, APITests.defaultName: APITests.defaultValue2, ] } } }
// // GeocodingData.swift // Tempest // // Created by Devan Allara on 5/2/18. // Copyright © 2018 Devan Allara. All rights reserved. // import Foundation import SwiftyJSON class GeocodingData { var latitude: Double var longitude: Double var name: String init(json: JSON) { print(json) self.latitude = json["results"]["geometry"]["location"]["lat"].doubleValue self.longitude = json["results"]["geometry"]["location"]["lng"].doubleValue self.name = json["results"]["address_components"][2]["long_name"].stringValue } }
// // VolunteerHospitalScreenerView.swift // CovidAlert // // Created by Matthew Garlington on 12/29/20. // import SwiftUI struct VolunteerHospitalScreenerView: View { @State var isDidWorkOrVolunteer : Bool = false @State var isDidNotWorkOrVolunteer : Bool = false @State private var didTap: Bool = false @State private var showContactHealthcare: Bool = false @State private var showContactWork: Bool = false @State private var showKeepPhysicalDistancing: Bool = false @ObservedObject var screenerStatus: ScreenerStatus var body: some View { VStack(spacing: 40) { VStack(alignment: .leading, spacing: 10) { Text("In the last 14 days, did you work or volunteer in a healthcare facility") .bold() .font(.title) Text("This includes a clinic, hospital, emergency room, other medical setting, or long-term care facility.") .font(.system(size: 20)) } .padding(.bottom) .padding() VStack(spacing: 40) { Button(action: { //Toggle of other checked items upon click if self.isDidNotWorkOrVolunteer == true { self.isDidNotWorkOrVolunteer.toggle() } else { } // Action to Display Check Mark when button is pressed if self.isDidNotWorkOrVolunteer == true { } else { self.isDidWorkOrVolunteer.toggle() } //Next Button Control if self.isDidWorkOrVolunteer == true { self.didTap = true} else { self.didTap = false } // Action Tells the Screener Status what is selected if self.isDidWorkOrVolunteer == true { self.screenerStatus.isDidWorkOrVolunteerSelected = true self.screenerStatus.isDidNotWorkOrVolunteerSelected = false } else { self.screenerStatus.isDidWorkOrVolunteerSelected = false } }, label: { ZStack { HStack(spacing: 75) { Text("I worked or volunteered in a healthcare facility in the last 14 days") .bold() .foregroundColor(.primary) .frame(width: 250) Image(systemName: self.isDidWorkOrVolunteer ? "checkmark.circle.fill" : "circle") .foregroundColor(Color.init(#colorLiteral(red: 0.3067349494, green: 0.3018456101, blue: 0.7518180013, alpha: 1))) .font(.system(size: 25)) } }.padding() }).buttonStyle(SimpleButtonStyle()) Button(action: { //Toggle of other checked items upon click if self.isDidWorkOrVolunteer == true { self.isDidWorkOrVolunteer.toggle() } else { } // Action to Display Check Mark when button is pressed if self.isDidWorkOrVolunteer == true { } else { self.isDidNotWorkOrVolunteer.toggle() } // Next Button Control... if self.isDidNotWorkOrVolunteer == true { self.didTap = true} else { self.didTap = false } // Action Tells the Screener Status what is selected if self.isDidNotWorkOrVolunteer == true { self.screenerStatus.isDidNotWorkOrVolunteerSelected = true self.screenerStatus.isDidWorkOrVolunteerSelected = false } else { self.screenerStatus.isDidNotWorkOrVolunteerSelected = false } }, label: { ZStack { HStack(spacing: 75) { Text("I did not work or volunteer in a healthcare facility in the last 14 days") .bold() .foregroundColor(.primary) .frame(width: 250) Image(systemName: self.isDidNotWorkOrVolunteer ? "checkmark.circle.fill" : "circle") .foregroundColor(Color.init(#colorLiteral(red: 0.3067349494, green: 0.3018456101, blue: 0.7518180013, alpha: 1))) .font(.system(size: 25)) } }.padding() }).buttonStyle(SimpleButtonStyle()) Spacer() // ZStack { // Spacer() // .frame(width: 375, height: 200, alignment: .center) // .background(Color(.init(white: 1, alpha: 1))) // .cornerRadius(15) // VStack { // // Text("Is Worked with Covid is \(self.screenerStatus.isDidWorkOrVolunteerSelected.description)") // .bold() // .foregroundColor(.primary) // .frame(width: 250) // Text("Is Did Not Worked with Covid is \(self.screenerStatus.isDidNotWorkOrVolunteerSelected.description)") // .bold() // .foregroundColor(.primary) // .frame(width: 300) // // } // // // }.padding() } VStack{ // These are the two views that will be the destination depending on which box is checked NavigationLink( destination: ContactHealthCareResultsView(screenerStatus: screenerStatus), isActive: $showContactHealthcare, label: { Text("") } ) NavigationLink( destination: ContactYourWorkResultsView(screenerStatus: screenerStatus) , isActive: $showContactWork, label: { Text("") } ) NavigationLink( destination: ContinuePhysicalDistancingResultsView(screenerStatus: screenerStatus), isActive: $showKeepPhysicalDistancing, label: { Text("") } ) //This is the nevigation button view at the button Button(action: { // If You did work at the hospital and had symptoms Then this will show the contact work page // show contact healthcare professional page if there are selected if self.screenerStatus.isDidWorkOrVolunteerSelected && self.screenerStatus.IsPositiveSelected == true { self.showContactWork = true } else if self.screenerStatus.isDidWorkOrVolunteerSelected && self.screenerStatus.isSomeImpactSelected || self.screenerStatus.isDidWorkOrVolunteerSelected && self.screenerStatus.isMajorImpactSelected == true { self.showContactWork = true } else if self.screenerStatus.isDidWorkOrVolunteerSelected && self.screenerStatus.isLiveInLongtermCareSelected || self.screenerStatus.isDidWorkOrVolunteerSelected && self.screenerStatus.isMightHaveBeenExposedToCovidSelected == true { self.showContactWork = true } else if self.screenerStatus.isDidWorkOrVolunteerSelected && self.screenerStatus.isLivedWithCovidPositivePersonSelected || self.screenerStatus.isDidWorkOrVolunteerSelected && self.screenerStatus.isCaredForCovidPositivePersonSelected == true { self.showContactWork = true } else { self.showContactWork = false } // show contact healthcare professional page if there are selected if self.screenerStatus.isDidNotWorkOrVolunteerSelected && self.screenerStatus.IsPositiveSelected == true { self.showContactHealthcare = true } else if self.screenerStatus.isDidNotWorkOrVolunteerSelected && self.screenerStatus.isSomeImpactSelected || self.screenerStatus.isDidNotWorkOrVolunteerSelected && self.screenerStatus.isMajorImpactSelected == true { self.showContactHealthcare = true } else if self.screenerStatus.isDidNotWorkOrVolunteerSelected && self.screenerStatus.isLiveInLongtermCareSelected || self.screenerStatus.isDidNotWorkOrVolunteerSelected && self.screenerStatus.isMightHaveBeenExposedToCovidSelected == true { self.showContactHealthcare = true } else if self.screenerStatus.isDidNotWorkOrVolunteerSelected && self.screenerStatus.isLivedWithCovidPositivePersonSelected || self.screenerStatus.isDidNotWorkOrVolunteerSelected && self.screenerStatus.isCaredForCovidPositivePersonSelected == true { self.showContactHealthcare = true } else { self.showContactHealthcare = false } // Show No test needed/ physical distancing screen if these are selected if self.screenerStatus.isDidNotWorkOrVolunteerSelected && self.screenerStatus.IsNegativeSelected == true { self.showKeepPhysicalDistancing = true } else if self.screenerStatus.isNonResultsSelected && self.screenerStatus.isNoneOfTheseSymptomsSelected || self.screenerStatus.isNonResultsSelected && self.screenerStatus.isNoneOfTheseSymptomsSelected == true { self.showKeepPhysicalDistancing = true } else if self.screenerStatus.isNoTestSelected && self.screenerStatus.isNoneOfTheseSymptomsSelected || self.screenerStatus.isNoTestSelected && self.screenerStatus.isLittleImpactSelected == true { self.showKeepPhysicalDistancing = true } else { self.showKeepPhysicalDistancing = false } }, label: { ZStack { Spacer() .frame(width: 375, height: 50, alignment: .center) .background(didTap ? Color.init(#colorLiteral(red: 0.3028137088, green: 0.2979239523, blue: 0.7478307486, alpha: 1)) : Color.gray) .cornerRadius(10) HStack { Text("Next") .foregroundColor(.white) } } }) }.padding() }.padding(.bottom) .padding(.top) .background(Color(.init(white: 0.95, alpha: 1))) } } struct VolunteerHospitalScreenerView_Previews: PreviewProvider { static var previews: some View { VolunteerHospitalScreenerView(screenerStatus: ScreenerStatus.init()) } }
/* * This file is part of Adblock Plus <https://adblockplus.org/>, * Copyright (C) 2006-present eyeo GmbH * * Adblock Plus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * Adblock Plus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. */ import Foundation public final class EventDispatcher: NSObject { weak var bridgeSwitchboard: BridgeSwitchboard? @objc public init(bridgeSwitchboard: BridgeSwitchboard?) { self.bridgeSwitchboard = bridgeSwitchboard } typealias CallbackTransform = (BridgeCallback) -> BridgeCallback? func dispatch(_ event: CallbackEventType, extension: BrowserExtension, json: Any, transform: CallbackTransform = EventDispatcher.identity) { let callbacks = `extension`.callbacks(for: .content, event: event) guard callbacks.count != 0 else { Log.error("Native event '\(event)' has no callbacks") return } dispatch(callbacks, json: json, transform: transform) } func dispatch(_ event: CallbackEventType, json: Any, transform: CallbackTransform = EventDispatcher.identity) { dispatch(callbacksFor(event), json: json, transform: transform) } func dispatch<R: JSParameter>(_ event: CallbackEventType, _ tabId: UInt, _ json: Any, _ completion: (([Result<R>]) -> Void)?) { let `extension` = bridgeSwitchboard?.virtualGlobalScopeExtension guard let callbacks = `extension`?.callbacksToContent(for: event, andTab: Int(tabId)), callbacks.count != 0 else { Log.error("Native event '\(event)' has no callbacks") completion?([]) return } if let completion = completion { dispatch(callbacks, json: json) { (results) in completion(results.map { (input) -> Result<R> in switch input { case .success(let output): if let result = R(json: output) { return .success(result) } else { return .failure(NSError(code: .eventResultDidNotMatch, message: "Event result did not match")) } case .failure(let error): return .failure(error) } }) } } else { dispatch(callbacks, json: json) } } func dispatch<R: JSParameter>(_ callback: BridgeCallback, _ json: Any, _ completion: ((Result<R>) -> Void)? = nil) { guard let injector = bridgeSwitchboard?.injector else { completion?(.failure(NSError(message: "Injector cannot be used"))) return } if let completion = completion { injector.call(callback, with: json) { input in switch input { case .success(let output): if let result = R(json: output) { return completion(.success(result)) } else { return completion(.failure(NSError(code: .eventResultDidNotMatch, message: "Event result did not match"))) } case .failure(let error): return completion(.failure(error)) } } } else { injector.call(callback, with: json, completion: nil) } } // MARK: - Objc @objc public func dispatch(_ event: CallbackEventType, extension: BrowserExtension, json: Any) { dispatch(event, json: json, transform: EventDispatcher.identity) } @objc public func dispatch(_ event: CallbackEventType, _ json: Any) { dispatch(event, json: json, transform: EventDispatcher.identity) } // MARK: - fileprivate fileprivate func dispatch(_ callbacks: [BridgeCallback], json: Any, transform: CallbackTransform = EventDispatcher.identity, completion: (([Result<Any?>]) -> Void)? = nil) { guard let injector = bridgeSwitchboard?.injector else { Log.error("Injector cannot be used") completion?([]) return } let listener: MultipleResultsListener<Any?>? if let completion = completion { listener = MultipleResultsListener(completion: completion) } else { listener = nil } for callback in callbacks { let completionListener = listener?.createCompletionListener() guard let finalCallback = transform(callback) else { completionListener?(.failure(NSError(message: "Callback has been discarded"))) continue } injector.call(finalCallback, with: json, completion: completionListener) } } fileprivate func callbacksFor(_ event: CallbackEventType) -> [BridgeCallback] { Log.debug("Native event '\(event)' \(String(describing: BridgeCallback.eventString(for: event)))") assert(Thread.isMainThread, "handleNativeEvent called from background thread") // emulate call from content script // both background and popup callbacks will be returned let delegate = bridgeSwitchboard?.webNavigationDelegate if let callbacks = delegate?.arrayOfExtensionUnspecificCallbacks(of: event) as? [BridgeCallback], callbacks.count > 0 { return callbacks } let `extension` = bridgeSwitchboard?.virtualGlobalScopeExtension if let callbacks = `extension`?.callbacksToContent(for: event, andTab: NSNotFound), callbacks.count > 0 { return callbacks } Log.debug("Native event '\(event)' has no callbacks") return [] } static func identity(_ callback: BridgeCallback) -> BridgeCallback? { return callback } }
// // BillsTableViewCell.swift // splitwork // // Created by Swathi Kommaghatta Chandrashekaraiah on 4/23/18. // Copyright © 2018 Vivek Badrinarayan. All rights reserved. // import UIKit class BillsTableViewCell: UITableViewCell { //MARK: Variables @IBOutlet weak var billNames: UILabel! @IBOutlet weak var oweLabel: UILabel! @IBOutlet weak var addedBy: UILabel! @IBOutlet weak var oweAmount: UILabel! @IBOutlet weak var group: 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 } }
// // AdOwnerInfoTableViewCell.swift // ListGridProject // // Created by Zuhaib Imtiaz on 2/24/21. // Copyright © 2021 Zuhaib Imtiaz. All rights reserved. // import UIKit class AdOwnerInfoTableViewCell: UITableViewCell { @IBOutlet weak var locationView:UIView! @IBOutlet weak var locationTitle:UILabel! @IBOutlet weak var phoneNoView:UIView! @IBOutlet weak var collectionView:UICollectionView! var phoneNos = [String]() override func awakeFromNib() { super.awakeFromNib() self.collectionView.delegate = self self.collectionView.dataSource = self self.collectionView.register(UINib(nibName: "PhoneNoCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "PhoneNoCollectionViewCell") } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func config(phoneNumbers:[String], sellerLocation:String){ self.phoneNos = phoneNumbers if sellerLocation != ""{ self.locationTitle.text = sellerLocation }else{ self.locationView.isHidden = true } } } extension AdOwnerInfoTableViewCell: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { self.phoneNos.count == 0 ? (self.phoneNoView.isHidden = true) : (self.phoneNoView.isHidden = false) return self.phoneNos.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhoneNoCollectionViewCell", for: indexPath) as? PhoneNoCollectionViewCell{ cell.phoneNoLabel.text = self.phoneNos[indexPath.row] return cell } return UICollectionViewCell.init() } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 150, height: 40) } }
// // ViewController.swift // COMP2601A3-100999500 // // Created by Avery Vine (100999500) and Alexei Tipenko (100995947) on 2017-03-11. // Copyright © 2017 Avery Vine and Alexei Tipenko. All rights reserved. // import UIKit class ViewController: UIViewController, Observer { @IBOutlet var tile0: UIButton? @IBOutlet var tile1: UIButton? @IBOutlet var tile2: UIButton? @IBOutlet var tile3: UIButton? @IBOutlet var tile4: UIButton? @IBOutlet var tile5: UIButton? @IBOutlet var tile6: UIButton? @IBOutlet var tile7: UIButton? @IBOutlet var tile8: UIButton? @IBOutlet var label: UILabel? @IBOutlet var button: UIButton? @IBOutlet var switchAI: UISwitch? var gameThread: DispatchQueue? var timer: DispatchSourceTimer? var game = Game() var xImage = UIImage(named: "x_button") var oImage = UIImage(named: "o_button") var emptyImage = UIImage(named: "empty_button") let strings = Strings() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. initUI() game.toggleActive() toggleClickListeners() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /*---------- - Description: observer function that updates the UI when a move is made - Input: the choice of move - Return: none ----------*/ func updateMove(choice: Int) { updateSquareUI(choice: choice, playerTurn: game.getPlayerTurn()) updateDisplayTextView(choice: choice) } /*---------- - Description: observer function that updates the UI when the game ends - Input: the winner of the game - Return: none ----------*/ func updateGameWinner(winner: Int) { DispatchQueue.main.async { self.gameOverUI(winner: winner) } } /*---------- - Description: runs when the Start/Running button is clicked - Input: none - Return: none ----------*/ @IBAction func startButtonOnClick() { if game.getActive() { timer?.cancel() timer = nil game.toggleActive() gameOverUI(winner: Game.EMPTY_VAL) if game.getPlayerTurn() == Game.X_VAL { toggleClickListeners() } } else { game = Game() self.game.attachObserver(observer: self) prepareUI() toggleClickListeners() gameLoop() } } /*---------- - Description: creates and starts the game loop for the computer - Input: none - Return: none ----------*/ func gameLoop() { gameThread = DispatchQueue(label: "gameThread", attributes: .concurrent) timer?.cancel() let computerMoveTask = DispatchWorkItem() { if !self.game.getActive() { self.timer?.cancel() self.timer = nil } let choice = self.game.randomSquare(switchAI: (self.switchAI?.isOn)!) DispatchQueue.main.sync { self.game.makeMove(choice: choice) } let gameWinner = self.game.gameWinner(currBoard: self.game.getBoard(), currPlayerTurn: self.game.getPlayerTurn()) if gameWinner == Game.EMPTY_VAL { self.game.switchPlayer() DispatchQueue.main.async { self.toggleClickListeners() } } else { self.game.toggleActive() DispatchQueue.main.async { self.timer?.cancel() self.timer = nil if self.game.getPlayerTurn() == Game.X_VAL { self.toggleClickListeners() } } } } timer = DispatchSource.makeTimerSource(queue: gameThread) timer?.scheduleRepeating(deadline: .now() + .seconds(2), interval: .seconds(2)) timer?.setEventHandler(handler: computerMoveTask) timer?.resume() } /*---------- - Description: updates the UI based off the player's move - Input: the position on the board, the current player - Return: none ----------*/ func updateSquareUI(choice: Int, playerTurn: Int) { var image: UIImage? if playerTurn == Game.X_VAL { image = xImage } else { image = oImage } switch choice { case 0: tile0?.setImage(image, for: UIControlState.normal) break case 1: tile1?.setImage(image, for: UIControlState.normal) break case 2: tile2?.setImage(image, for: UIControlState.normal) break case 3: tile3?.setImage(image, for: UIControlState.normal) break case 4: tile4?.setImage(image, for: UIControlState.normal) break case 5: tile5?.setImage(image, for: UIControlState.normal) break case 6: tile6?.setImage(image, for: UIControlState.normal) break case 7: tile7?.setImage(image, for: UIControlState.normal) break case 8: tile8?.setImage(image, for: UIControlState.normal) break default: print("Error setting button image") } } /*---------- - Description: updates the text view with the last move played - Input: the position of the move - Return: none ----------*/ func updateDisplayTextView(choice: Int) { if choice == 0 { label?.text = strings.square0 } else if choice == 1 { label?.text = strings.square1 } else if choice == 2 { label?.text = strings.square2 } else if choice == 3 { label?.text = strings.square3 } else if choice == 4 { label?.text = strings.square4 } else if choice == 5 { label?.text = strings.square5 } else if choice == 6 { label?.text = strings.square6 } else if choice == 7 { label?.text = strings.square7 } else if choice == 8 { label?.text = strings.square8 } } /*---------- - Description: sets the initial state for the UI when the program begins - Input: none - Return: none ----------*/ func initUI() { button?.setTitle(strings.startButton_gameInactive, for: UIControlState.normal) label?.text = strings.displayTextView_gameInactive wipeSquares() } /*---------- - Description: prepares the UI for a new game - Input: none - Return: none ----------*/ func prepareUI() { wipeSquares() button?.setTitle(strings.startButton_gameActive, for: UIControlState.normal) label?.text = strings.blank switchAI?.isEnabled = false } /*---------- - Description: sets every square on the board to empty - Input: none - Return: none ----------*/ func wipeSquares() { tile0?.setImage(emptyImage, for: UIControlState.normal) tile1?.setImage(emptyImage, for: UIControlState.normal) tile2?.setImage(emptyImage, for: UIControlState.normal) tile3?.setImage(emptyImage, for: UIControlState.normal) tile4?.setImage(emptyImage, for: UIControlState.normal) tile5?.setImage(emptyImage, for: UIControlState.normal) tile6?.setImage(emptyImage, for: UIControlState.normal) tile7?.setImage(emptyImage, for: UIControlState.normal) tile8?.setImage(emptyImage, for: UIControlState.normal) } /*---------- - Description: displays the "Game Over" UI to the user - Input: the winner of the game - Return: none ----------*/ func gameOverUI(winner: Int) { if winner == Game.X_VAL { label?.text = strings.x_winner } else if winner == Game.O_VAL { label?.text = strings.o_winner } else if winner == Game.TIE_VAL { label?.text = strings.tie_winner } else { label?.text = strings.no_winner } button?.setTitle(strings.startButton_gameInactive, for: UIControlState.normal) switchAI?.isEnabled = true } /*---------- - Description: toggles on and off the squares' click listeners - Input: none - Return: none ----------*/ func toggleClickListeners() { tile0?.isEnabled = !(tile0?.isEnabled)! tile1?.isEnabled = !(tile1?.isEnabled)! tile2?.isEnabled = !(tile2?.isEnabled)! tile3?.isEnabled = !(tile3?.isEnabled)! tile4?.isEnabled = !(tile4?.isEnabled)! tile5?.isEnabled = !(tile5?.isEnabled)! tile6?.isEnabled = !(tile6?.isEnabled)! tile7?.isEnabled = !(tile7?.isEnabled)! tile8?.isEnabled = !(tile8?.isEnabled)! } /*---------- - Description: runs when a square on the board is clicked - Input: the button that was pressed - Return: none ----------*/ @IBAction func squareClicked(sender: UIButton) { timer?.cancel() timer = nil let choice = sender.tag game.makeMove(choice: choice) let gameWinner = game.gameWinner(currBoard: game.getBoard(), currPlayerTurn: game.getPlayerTurn()) if gameWinner == Game.EMPTY_VAL { game.switchPlayer() gameLoop() } else { game.toggleActive() } toggleClickListeners() } }
// // SwitchTableViewCell.swift // Yelp // // Created by Randy Ting on 9/23/15. // Copyright © 2015 Randy Ting. All rights reserved. // import UIKit @objc protocol SwitchTableViewCellDelegate { optional func switchTableViewCell(switchTableViewCell: SwitchTableViewCell, switchValueChangedTo: Bool) } class SwitchTableViewCell: UITableViewCell { weak var delegate: AnyObject? @IBOutlet weak var selectSwitch: UISwitch! @IBOutlet weak var switchLabel: UILabel! @IBOutlet weak var switchHeightConstraint: NSLayoutConstraint! @IBOutlet weak var switchBottomToContentViewConstraint: NSLayoutConstraint! @IBOutlet weak var switchTopToContentViewConstraint: NSLayoutConstraint! @IBOutlet weak var seeAllLabel: UILabel! var shouldCollapse: Bool = true{ didSet { if shouldCollapse { collapse() } else { expand() } } } override func awakeFromNib() { super.awakeFromNib() selectSwitch.onTintColor = AppearanceHelper.colorFromHexString("#c41200") selectionStyle = UITableViewCellSelectionStyle.None layoutMargins = UIEdgeInsetsZero separatorInset = UIEdgeInsetsZero } func collapse() { switchTopToContentViewConstraint.constant = 0 switchBottomToContentViewConstraint.constant = 0 switchHeightConstraint.constant = 0 } func expand() { switchTopToContentViewConstraint.constant = 10 switchBottomToContentViewConstraint.constant = 10 switchHeightConstraint.constant = 31 } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } override func prepareForReuse() { self.textLabel!.text = "" self.switchLabel.text = "" } @IBAction func onSwitchValueChanged(sender: AnyObject) { delegate?.switchTableViewCell?(self, switchValueChangedTo: selectSwitch.on) } }
// // MyQuestions.swift // Elshams // // Created by mac on 12/6/18. // Copyright © 2018 mac. All rights reserved. // import UIKit import XLPagerTabStrip import Alamofire //import AlamofireImage import SwiftyJSON class MyQuestions: UIViewController , UITableViewDataSource ,UITableViewDelegate { var questionList = Array<QuestionsData>() @IBOutlet weak var activeLoader: UIActivityIndicatorView! @IBOutlet weak var noDataErrorContainer: UIView! @IBOutlet weak var questionTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() questionTableView.isHidden = true activeLoader.startAnimating() noDataErrorContainer.isHidden = true NotificationCenter.default.addObserver(self, selector: #selector(errorAlert), name: NSNotification.Name("ErrorConnections"), object: nil) loadMyQuestionData() } @objc func errorAlert(){ let alert = UIAlertController(title: "Error!", message: Service.errorConnection, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) questionTableView.isHidden = true activeLoader.isHidden = true } override func viewWillAppear(_ animated: Bool) { UIApplication.shared.isStatusBarHidden = false } func loadMyQuestionData() { if let apiToken = Helper.getApiToken() { Service.getServiceWithAuth(url: URLs.getQuestions) { // authorizre or not ? (response) in print(response) let json = JSON(response) let result = json["myQuestions"] print("All question \(result)") if !(result.isEmpty){ var iDNotNull = true var index = 0 while iDNotNull { let question_ID = result[index]["questionId"].string let question_head = result[index]["question"].string let question_answer = result[index]["answer"].string let question_TimeStamp = result[index]["questionTimeStamp"].string let question_speakerName = result[index]["speakerName"].string if question_ID == nil || question_ID?.trimmed == "" || question_ID == "null" || question_ID == "nil" { iDNotNull = false break } self.questionList.append(QuestionsData(Questions: question_head ?? "", Answer: question_answer ?? "", QuestionsID: question_ID ?? "", QuestionSpeaker: question_speakerName ?? "", QuestionTimeStamp: question_TimeStamp ?? "")) index = index + 1 self.noDataErrorContainer.isHidden = true self.questionTableView.reloadData() self.activeLoader.isHidden = true self.activeLoader.stopAnimating() self.questionTableView.isHidden = false } }else { self.noDataErrorContainer.isHidden = false let alert = UIAlertController(title: "No Data", message: "No Data found till now", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) self.activeLoader.isHidden = true } } }else { self.activeLoader.isHidden = true self.questionTableView.isHidden = true // print(error.localizedDescription) let alert = UIAlertController(title: "Error", message: "You must sign in to Show this Part", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) dismiss(animated: true, completion: nil) // and should dimiss } } //table view func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return questionList.count } /*func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 190.0 } */ func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "myquestioncell") as! MyQuestionsCell cell.setMyQuestionCell(QuestionList: questionList[indexPath.row]) return cell } } extension MyQuestions : IndicatorInfoProvider { func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo { return IndicatorInfo(title: "MyQuestions") } }
import UIKit class TVCConnectionAlerts: UITableViewController { @IBOutlet var showNotifications: UISwitch! @IBOutlet var cellSound: UITableViewCell! @IBOutlet var listsCustomA: UITableViewCell! @IBOutlet var listsCustomB: UITableViewCell! override func viewDidLoad() { super.viewDidLoad() cascadeEnableConnAlert(PrefsShared.ConnectionAlerts.Enabled) cellSound.detailTextLabel?.text = AlertSoundTitle(for: PrefsShared.ConnectionAlerts.Sound) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let (_, _, custA, custB) = DomainFilter.counts() listsCustomA.detailTextLabel?.text = "\(custA) Domains" listsCustomB.detailTextLabel?.text = "\(custB) Domains" } private func cascadeEnableConnAlert(_ flag: Bool) { showNotifications.isOn = flag // en/disable related controls } private func getListSelected(_ index: Int) -> Bool { switch index { case 0: return PrefsShared.ConnectionAlerts.Lists.Blocked case 1: return PrefsShared.ConnectionAlerts.Lists.CustomA case 2: return PrefsShared.ConnectionAlerts.Lists.CustomB case 3: return PrefsShared.ConnectionAlerts.Lists.Else default: preconditionFailure() } } private func setListSelected(_ index: Int, _ value: Bool) { switch index { case 0: PrefsShared.ConnectionAlerts.Lists.Blocked = value case 1: PrefsShared.ConnectionAlerts.Lists.CustomA = value case 2: PrefsShared.ConnectionAlerts.Lists.CustomB = value case 3: PrefsShared.ConnectionAlerts.Lists.Else = value default: preconditionFailure() } } // MARK: - Toggles @IBAction private func toggleShowNotifications(_ sender: UISwitch) { PrefsShared.ConnectionAlerts.Enabled = sender.isOn cascadeEnableConnAlert(sender.isOn) GlassVPN.send(.notificationSettingsChanged()) if sender.isOn { PushNotification.requestAuthorization { granted in if !granted { NotificationsDisabledAlert(presentIn: self) self.cascadeEnableConnAlert(false) } } } else { PushNotification.cancel(.AllConnectionAlertNotifications) } } // MARK: - Table View Delegate override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAt: indexPath) let checked: Bool switch indexPath.section { case 1: // mode selection checked = (indexPath.row == (PrefsShared.ConnectionAlerts.ExcludeMode ? 1 : 0)) case 2: // include & exclude lists checked = getListSelected(indexPath.row) default: return cell // process only checkmarked cells } cell.accessoryType = checked ? .checkmark : .none return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.section { case 1: // mode selection PrefsShared.ConnectionAlerts.ExcludeMode = indexPath.row == 1 tableView.reloadSections(.init(integer: 2), with: .none) case 2: // include & exclude lists let prev = tableView.cellForRow(at: indexPath)?.accessoryType == .checkmark setListSelected(indexPath.row, !prev) default: return // process only checkmarked cells } tableView.deselectRow(at: indexPath, animated: true) tableView.reloadSections(.init(integer: indexPath.section), with: .none) GlassVPN.send(.notificationSettingsChanged()) } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 2 { return PrefsShared.ConnectionAlerts.ExcludeMode ? "Exclude All" : "Include All" } return super.tableView(tableView, titleForHeaderInSection: section) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let dest = segue.destination as? TVCFilter { switch segue.identifier { case "segueFilterListCustomA": dest.navigationItem.title = "Custom List A" dest.currentFilter = .customA case "segueFilterListCustomB": dest.navigationItem.title = "Custom List B" dest.currentFilter = .customB default: break } } else if let tvc = segue.destination as? TVCChooseAlertTone { tvc.delegate = self } } } // MARK: - Sound Selection extension TVCConnectionAlerts: NotificationSoundChangedDelegate { func notificationSoundCurrent() -> String { PrefsShared.ConnectionAlerts.Sound } func notificationSoundChanged(filename: String, title: String) { cellSound.detailTextLabel?.text = title PrefsShared.ConnectionAlerts.Sound = filename GlassVPN.send(.notificationSettingsChanged()) } }
// // FirstTest.swift // provoq // // Created by parry on 4/15/16. // Copyright © 2016 provoq. All rights reserved. // import XCTest import ObjectMapper @testable import provoq class FirstTest: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testRankingEngine() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. let rating = newRating(2, k: 2, expectedScore: 10.0, win: true) print("rating = \(rating)") XCTAssert(rating <= -17.0) } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. let rating = newRating(2, k: 2, expectedScore: 10.0, win: true) print("rating = \(rating)") XCTAssert(rating <= -17.0) } } }
// // AllowListViewController.swift // JupJup_admin // // Created by 조주혁 on 2021/02/21. // import UIKit import Alamofire class AllowListViewController: UIViewController { var allowListModel: AllowListModel? @IBOutlet weak var allowListTableView: UITableView! { didSet { allowListTableView.delegate = self allowListTableView.dataSource = self allowListTableView.tableFooterView = UIView() } } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) allowListApiCall() } func allowListApiCall() { let URL = "http://15.165.97.179:8080/v2/admin/applyview" let token = KeychainManager.getToken() AF.request(URL, method: .get, headers: ["Authorization": token]).responseData { (data) in guard let data = data.data else { return } self.allowListModel = try? JSONDecoder().decode(AllowListModel.self, from: data) self.allowListTableView.reloadData() print(data) } } } extension AllowListViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return allowListModel?.list.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "AllowListTableViewCell", for: indexPath) as! AllowListTableViewCell let cellCount = (allowListModel?.list.count)! - 1 cell.allowListName.text = allowListModel?.list[cellCount - indexPath.row].equipment.name ?? "" cell.allowListContent.text = allowListModel?.list[cellCount - indexPath.row].equipment.content ?? "" cell.allowListCount.text = "수량: \(allowListModel?.list[cellCount - indexPath.row].amount ?? 0)개" let url = allowListModel?.list[cellCount - indexPath.row].equipment.img_equipment ?? "" let encodingURL = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! cell.allowListImage.kf.setImage(with: URL(string: encodingURL)) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 120 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cellCount = (allowListModel?.list.count)! - 1 allowListContentTitle = allowListModel?.list[cellCount - indexPath.row].equipment.name ?? "" allowListContentStudentNameData = allowListModel?.list[cellCount - indexPath.row].admin.name ?? "" allowListContentImageData = allowListModel?.list[cellCount - indexPath.row].equipment.img_equipment ?? "" allowListContentReasonData = allowListModel?.list[cellCount - indexPath.row].reason ?? "" allowListContentClassNumberData = allowListModel?.list[cellCount - indexPath.row].admin.classNumber ?? "" allowListContentStudentEmailData = allowListModel?.list[cellCount - indexPath.row].admin.email ?? "" allowListContentEquipmentIndexData = allowListModel?.list[cellCount - indexPath.row].eqa_Idx ?? 0 allowListContentEquipmentAmountData = allowListModel?.list[cellCount - indexPath.row].amount ?? 0 } }
// // SampleAssembly.swift // {{cookiecutter.app_name}} // // Copyright © 2020 {{cookiecutter.company_name}}. All rights reserved. // import Foundation import Swinject import SwinjectStoryboard class SampleAssembly: Assembly { func assemble(container: Container) { container.register(SampleUseCase.self) { (r, presenter: SamplePresenter) -> SampleUseCase in let usecase = SampleUseCase() usecase.gateway = r.resolve(SampleGateway.self, argument: usecase) usecase.presenter = presenter return usecase } container.register(SampleGateway.self) { (_, _: SampleUseCase) -> SampleGateway in let gateway = SampleGateway() return gateway } container.register(SamplePresenter.self) { (r, vc: SampleViewController) -> SamplePresenter in let presenter = SamplePresenter() presenter.view = vc presenter.useCase = r.resolve(SampleUseCase.self, argument: presenter) return presenter } container.storyboardInitCompleted(SampleViewController.self) { r, vc in vc.presenter = r.resolve(SamplePresenter.self, argument: vc) } } }
// // Symbol.swift // Transit // // Created by Matthew Nespor on 9/25/14. // // import Foundation public struct Symbol : Hashable { public let namespace: String? public let name: String public var hashValue: Int { get { return 19 * self.stringValue.hashValue } } public var stringValue: String { get { if var ns = namespace { return ns + "/" + name } else { return name } } } public init(symbol: String) { if let range = symbol.rangeOfCharacterFromSet(NSCharacterSet(charactersInString: "/")) { namespace = symbol.substringToIndex(range.startIndex) name = symbol.substringFromIndex(range.endIndex) } else { name = symbol } } } public func == (lhs: Symbol, rhs: Symbol) -> Bool { return lhs.stringValue == rhs.stringValue } public func != (lhs: Symbol, rhs: Symbol) -> Bool { return lhs.stringValue != rhs.stringValue }
// // Services+init.swift // Services+init // // Created by Admin on 01/09/2021. // import Foundation extension Services { public init() { self.init(networkService: URLSession.shared, keyValueService: UserDefaults.standard) } }
// // WriteViewController.swift // practice // // Created by SangDo on 2017. 7. 2.. // Copyright © 2017년 SangDo. All rights reserved. // import UIKit import Firebase class WriteViewController: UIViewController { @IBOutlet weak var titleText: UITextField! @IBOutlet weak var content: UITextView! var dbRef: FIRDatabaseReference! override func viewDidLoad() { super.viewDidLoad() dbRef = FIRDatabase.database().reference() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func clickOkButton(_ sender: Any) { if (titleText.text == "") || (content.text == "") { return } else { var count = "1" dbRef.child("list").observeSingleEvent(of: .value, with: { snapshot in if !snapshot.exists() { print("없음") } if let firebaseDic = snapshot.value as? [String: AnyObject] { print("********") count = String(firebaseDic.count + 1) } print("count \(count)") let writeDate = ["title": self.titleText.text!, "content": self.content.text!] self.dbRef.child("list/0\(count)").setValue(writeDate) }) let write = Write() write.setTitle(title: titleText.text!) write.setContent(content: content.text) write.setDate(date: Date().getCurrentDate()) writeList.list.append(write) self.dismiss(animated: true, completion: nil) } } @IBAction func clickCancelButton(_ sender: Any) { self.dismiss(animated: true, completion: nil) } }
// // OnboardPartThree.swift // Tipper // // Created by Ryan Romanchuk on 9/27/15. // Copyright © 2015 Ryan Romanchuk. All rights reserved. // import UIKit import PassKit import Stripe import ApplePayStubs class OnboardPartThree: GAITrackedViewController, UINavigationControllerDelegate, StandardViewController { var provider: AWSCognitoCredentialsProvider! var currentUser: CurrentUser! var managedObjectContext: NSManagedObjectContext? var market: Market! weak var onboardingDelegate: OnboardingViewController? weak var containerController: OnboardingViewController? lazy var paymentController : PaymentController = { PaymentController(withMarket: self.market) }() @IBOutlet weak var stripeButton: UIButton! @IBOutlet weak var applePayButton: UIButton! @IBOutlet weak var welcomeToTipperLabel: UILabel! @IBOutlet weak var tipAmountLabel: UILabel! @IBOutlet weak var fundAmountLabel: UILabel! @IBOutlet weak var btcConversionLabel: UILabel! @IBOutlet weak var ubtcExchangeLabel: UILabel! @IBOutlet weak var usdExchangeLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() updateBTCSpotPrice() updateMarketData() paymentController.walletDelegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func updateMarketData() { log.verbose("") if let fundAmount = Settings.sharedInstance.fundAmount, fundAmountUBTC = Settings.sharedInstance.fundAmountUBTC { btcConversionLabel.text = "(\(fundAmount) Bitcoin)" ubtcExchangeLabel.text = fundAmountUBTC } if let amount = market.amount { usdExchangeLabel.text = amount } } func updateBTCSpotPrice() { log.verbose("") market.update { () -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.updateMarketData() }) } } @IBAction func didTapPay(sender: UIButton) { log.verbose("") paymentController.pay() } func didTapButton(sender: UIButton) { log.verbose("") didTapPay(sender) } @IBAction func didTapSkip(sender: UIButton) { (parentViewController as! OnboardingPageControllerViewController).autoAdvance() } }
// // ContactsViewController.swift // ResQ // // Created by Chloe Yan on 11/16/19. // Copyright © 2019 Chloe Yan. All rights reserved. // import UIKit var userData = false class ContactsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var contactsListTableView: UITableView! func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return phoneNumberArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ let cell = UITableViewCell(style:UITableViewCell.CellStyle.default, reuseIdentifier: "cell") cell.textLabel?.text = phoneNumberArray[indexPath.row] return cell } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) contactsListTableView.reloadData() UserDefaults.standard.set(phoneNumberArray,forKey: "contacts") } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath){ if editingStyle == UITableViewCell.EditingStyle.delete{ if phoneNumberArray.count != 1{ phoneNumberArray.remove(at: indexPath.row) UserDefaults.standard.set(phoneNumberArray, forKey: "theEventT") } contactsListTableView.reloadData() } } open override func viewDidLoad() { super.viewDidLoad() userData = UserDefaults.standard.bool(forKey: "userData") if userData == true { phoneNumberArray = UserDefaults.standard.object(forKey: "contacts") as! [String] contactsListTableView.reloadData() } else { UserDefaults.standard.set(phoneNumberArray,forKey: "contacts") contactsListTableView.reloadData() } } }
// // ProfileRouter.swift // KarrotRouter // // Created by Geektree0101 on 2020/07/01. // Copyright © 2020 Geektree0101. All rights reserved. // import UIKit protocol ProfileRouteLogic: class { func pushCardViewController(feedID: Int) } protocol ProfileDataPassing: class { var dataStore: ProfileDataStore? { get set } } class ProfileRouter: ProfileDataPassing { weak var viewController: ProfileViewController? weak var dataStore: ProfileDataStore? } // MARK: - Route Logic extension ProfileRouter: ProfileRouteLogic { func pushCardViewController(feedID: Int) { guard let feedItem = dataStore?.feedItems .first(where: { $0.id == feedID }) else { return } let cardVC = CardViewController() cardVC.router.dataStore?.card = feedItem.card cardVC.router.dataStore?.user = feedItem.user if Bool.random() == true { self.viewController?.present( UINavigationController(rootViewController: cardVC), animated: true, completion: nil ) } else { self.viewController? .navigationController? .pushViewController(cardVC, animated: true) } } } // MARK: - DataDrain Logic extension ProfileRouter: DataDrainable { func drain(context: DataDrainContext) { switch context { case let ctx as CardUpdatedDrainContext: guard let items = self.dataStore?.feedItems, let index = items.firstIndex(where: { $0.card?.id == ctx.card.id }) else { return } self.dataStore?.feedItems[index].card = ctx.card self.viewController?.reload() default: break } } }
// // RewardVC.swift // Shopping_W // // Created by wanwu on 2017/6/2. // Copyright © 2017年 wanwu. All rights reserved. // import UIKit import MBProgressHUD class RewardModel: CustomTableViewCellItem { var fLevelpercentage = 0 //当前享受奖励比列 var fSumlevelintegral = 0//当前等级积分 var fLevelintegraltext = ""//当前等级 } class RewardVC: BaseViewController { @IBOutlet weak var gotBtn: UIButton! @IBOutlet weak var tableView: RefreshTableView! override func viewDidLoad() { super.viewDidLoad() self.title = "我的奖励" // cell 130 tableView.sectionHeaderHeight = 10 reqeustData() gotBtn.isEnabled = false gotBtn.layer.cornerRadius = CustomValue.btnCornerRadius } func reqeustData() { NetworkManager.requestTModel(params: ["method":"apigetlevelintegralsum"]).setSuccessAction { (bm: BaseModel<RewardModel>) in bm.whenSuccess { let data = bm.t!.build(cellClass: RewardTableViewCell.self).build(heightForRow: 100).build(isFromStoryBord: true) self.tableView.dataArray = [[data]] self.tableView.reloadData() self.gotBtn.isEnabled = true self.gotBtn.backgroundColor = CustomValue.common_red } bm.whenNoData { self.nomalLevel() } } } func nomalLevel() { let r = RewardModel().build(cellClass: RewardTableViewCell.self).build(heightForRow: 100).build(isFromStoryBord: true) r.fLevelintegraltext = "普通" self.tableView.dataArray = [[r]] self.tableView.reloadData() self.gotBtn.backgroundColor = UIColor.lightGray self.gotBtn.isEnabled = false } @IBAction func ac_get(_ sender: Any) { NetworkManager.requestTModel(params: ["method":"apiChangelevelintegral"]).setSuccessAction { (bm: BaseModel<CodeModel>) in bm.whenSuccess { MBProgressHUD.show(successText: "提取成功") self.nomalLevel() } } } }
// // SceneDelegate.swift // Trinity_Monsters // // Created by Alex Bro on 14.01.2021. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let winScene = (scene as? UIWindowScene) else { return } window = UIWindow(windowScene: winScene) let navigationController = UINavigationController() let assembly = AssemblyService() let router = RouterService(navigationController: navigationController, assembly: assembly) router.initialViewController() window?.rootViewController = navigationController window?.makeKeyAndVisible() } }
// // ListViewController.swift // FinFil // // Created by 张桀硕 on 2020/10/1. // Copyright © 2020年 jieshuo.zhang. All rights reserved. // import Foundation import UIKit class MovieInfoCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var overviewLabel: UILabel! } class ListViewController: UIViewController { @IBOutlet weak var tabelView: UITableView! var moviesInfo: [MovieInfo] = [] // MARK:- override func viewDidLoad() { super.viewDidLoad() prepareData() setupViews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { print( NSStringFromClass(self.classForCoder) + " deinit") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) refreshViews() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ListToDetails" { if let viewController = segue.destination as? ShowDetailsViewController { if sender != nil { viewController.movieDetail = sender as? MovieDetail } } } } } extension ListViewController { func prepareData() { print(moviesInfo) } func setupViews() { tabelView.delegate = self tabelView.dataSource = self } func refreshViews() {} } // MARK:- UITableViewDelegate, UITableViewDataSource extension ListViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return moviesInfo.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let row = indexPath.row // init the cell let cell = tableView.dequeueReusableCell(withIdentifier: "MovieInfoCell", for: indexPath) as! MovieInfoCell cell.contentView.backgroundColor = UIColor.clear // set datas let movie = moviesInfo[row] cell.titleLabel.text = movie.originalTitle cell.dateLabel.text = movie.releaseDate cell.overviewLabel.text = movie.overview return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let row = indexPath.row let movieID = moviesInfo[row].movieID tableView.deselectRow(at: indexPath, animated: true) NetworkAPI().get_details_request( controller: self, movieID: movieID, block: { movie in print(movie) if !movie.movieID.isEmpty { self.performSegue(withIdentifier: "ListToDetails", sender: movie) } else { Utils().okButtonAlertView( title: NSLocalizedString("Network_fails_tryAgain", comment: ""), controller: self, block: nil) } }) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } }
// // LoginService.swift // Kitsbee // // Created by VTS-ThangTV28 on 16/06/2021. // import UIKit class LoginService { }
// // ViewController.swift // Animations // // Created by PASHA on 07/08/18. // Copyright © 2018 Pasha. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var imag: UIImageView! var timer = Timer() var count = 1 var isAnimating = false override func viewDidLoad() { super.viewDidLoad() print("simple animating ......") print("1234567890") // Do any additional setup after loading the view, typically from a nib. } @IBAction func startTap(_ sender: UIButton) { if isAnimating { timer.invalidate() sender.setTitle("Start Animating......", for: []) isAnimating = false } else { timer = Timer.scheduledTimer(timeInterval: 001, target: self, selector: #selector(animatingAction), userInfo: nil, repeats: true) sender.setTitle("Stop Animating......", for: []) isAnimating = true } } @objc func animatingAction(){ self.imag.image = UIImage(named: "frame_\(count)_delay-0s.png") count += 1 if count == 11 { count = 0 } } @IBAction func fradeTap(_ sender: Any) { self.imag.alpha = 0 UIView.animate(withDuration: 01) { self.imag.alpha = 1 } } @IBAction func slideTap(_ sender: Any) { self.imag.center = CGPoint(x: self.imag.center.x-500, y: self.imag.center.y) UIView.animate(withDuration: 02) { self.imag.center = CGPoint(x: self.imag.center.x+500, y: self.imag.center.y) } } @IBAction func growTap(_ sender: Any) { self.imag.frame = CGRect(x: 0, y: 0, width: 0, height: 0) UIView.animate(withDuration: 01) { self.imag.frame = CGRect(x: 40, y: 105, width: 240, height: 240) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // ViewController.swift // Quizzler-iOS13 // import UIKit class ViewController: UIViewController { @IBOutlet var progressBar: UIProgressView! @IBOutlet var questionText: UILabel! let quizz = [ "Four + two is equal to six", "Five + five is equal to ten", "Ten minus 2 is equal to eight", ] @IBAction func trueButtonPressed(_ sender: UIButton) { } @IBAction func falseButtonPressed(_ sender: UIButton) { } override func viewDidLoad() { super.viewDidLoad() questionText.text = quizz.first! } }
// // CommentVC.swift // StudyMate // // Created by Vitaly Kuzenkov on 4/6/17. // Copyright © 2017 Vitaly Kuzenkov. All rights reserved. // import UIKit import Firebase import SwiftKeychainWrapper class CommentViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate { @IBOutlet var futureCommentLabel: TextFieldCustomView! @IBOutlet var tableView: UITableView! var postId: String = "empty" var numberOfCommentsInt: Int = 0 var commentId: String = "not provided" var testText: String = ":(" var userName: String = "N/A" var profileImageUrl: String! var comments = [Comment]() var currentCommentRef: FIRDatabaseReference! var numberOfComments: FIRDatabaseReference! override func viewDidLoad() { super.viewDidLoad() futureCommentLabel.delegate = self tableView.delegate = self tableView.dataSource = self if KeychainWrapper.standard.string(forKey: "PostId") != nil { self.postId = KeychainWrapper.standard.string(forKey: "PostId")! //print("Vitaly: PostID is in key chain \(self.postId)") } if KeychainWrapper.standard.string(forKey: "NumberOfComments") != nil { self.numberOfCommentsInt = Int(KeychainWrapper.standard.string(forKey: "NumberOfComments")!)! } findUser() startObservingChangesInComments() } func startObservingChangesInComments() { DataService.shared.REF_POST_CURRENT.child("commentsList").observe(.value, with: { (snapshot) in self.comments = [] if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] { for snap in snapshot { //print("SNAP in changes in comments : \(snap)") if let commentDict = snap.value as? Dictionary<String, AnyObject> { let key = snap.key let comment = Comment(commentId: key, commentData: commentDict) self.comments.append(comment) } } } self.comments.reverse() self.tableView.reloadData() }) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let comment = comments[indexPath.row] if let cell = tableView.dequeueReusableCell(withIdentifier: COMMENT_CELL) as? CommentCell { cell.configureCell(comment: comment) return cell } else { return PostCell() } } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return comments.count } @IBAction func backImageTapped(_ sender: Any) { self.performSegue(withIdentifier: "unwindToMain", sender: self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func sendButtonTapped(_ sender: Any) { guard let commentText = futureCommentLabel.text, commentText != "" else { futureCommentLabel.attributedPlaceholder = NSAttributedString(string: ERROR_COMMENT_TEXT_EMPTY, attributes: [NSForegroundColorAttributeName: UIColor.red]) return } self.postToFirebase() currentCommentRef.observeSingleEvent(of: .value, with: { (snapshot) in if let _ = snapshot.value as? NSNull { let comment: Dictionary<String, Any> = [ Constants.DatabaseColumn.userName.rawValue: self.userName as Any, COMMENT_TEXT: self.futureCommentLabel.text as Any ] self.currentCommentRef.setValue(comment) self.futureCommentLabel.text = "" } }) _ = self.textFieldShouldReturn(futureCommentLabel) futureCommentLabel.attributedPlaceholder = NSAttributedString(string: "Type your comment here...", attributes: [NSForegroundColorAttributeName: UIColor.gray]) } func findUser() { let ref = DataService.shared.REF_BASE let userID = FIRAuth.auth()?.currentUser?.uid _ = ref.child(Constants.DatabaseColumn.users.rawValue).child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in if let dictionary = snapshot.value as? [String: AnyObject] { self.userName = (dictionary[Constants.DatabaseColumn.userName.rawValue] as? String)! } }) } func postToFirebase() { let comment: Dictionary<String, Any> = [ Constants.DatabaseColumn.userName.rawValue: self.userName as Any, COMMENT_TEXT: self.futureCommentLabel.text as Any ] let firebaseComment = DataService.shared.REF_COMMENTS.childByAutoId() self.commentId = firebaseComment.key currentCommentRef = DataService.shared.REF_POST_CURRENT.child(Constants.Posts.commentList.rawValue).child(self.commentId) // get access to number of comments stored as Ints in the database numberOfComments = DataService.shared.REF_POST_CURRENT.child("comments") numberOfComments.setValue(self.numberOfCommentsInt + 1) //new comment was added, so increment the number of comments self.numberOfCommentsInt = self.numberOfCommentsInt + 1 KeychainWrapper.standard.set(self.numberOfCommentsInt, forKey: "NumberOfComments") firebaseComment.setValue(comment) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return false } // methods below resposible for moving text fields up, when the keyboard appears func textFieldDidBeginEditing(_ textField: UITextField) { animateViewMoving(up: true, moveValue: 250) } func textFieldDidEndEditing(_ textField: UITextField) { animateViewMoving(up: false, moveValue: 250) } func animateViewMoving (up:Bool, moveValue :CGFloat){ let movementDuration:TimeInterval = 0.3 let movement:CGFloat = ( up ? -moveValue : moveValue) UIView.beginAnimations( "animateView", context: nil) UIView.setAnimationBeginsFromCurrentState(true) UIView.setAnimationDuration(movementDuration ) self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement) UIView.commitAnimations() } }
import UIKit import Firebase import GoogleSignIn var currentUser: User? class GoogleSignInViewController: UIViewController, GIDSignInUIDelegate, GIDSignInDelegate { @IBOutlet weak var GIDSignInButton: GIDSignInButton! @IBOutlet weak var GIDSignOutButton: UIButton! let dele = AppDelegate() override func viewDidLoad() { super.viewDidLoad() GIDSignIn.sharedInstance().delegate = self GIDSignIn.sharedInstance().uiDelegate = self GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID print("user") } func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) { // ... if let error = error { print("error") return } guard let authentication = user.authentication else { return } let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken) // ... Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in if let error = error { //... return } self.checkIfUserIsLoggedIn() //cUser = Auth.auth().currentUser //self.SignIn.checkIfUserIsLoggedIn() print("User logged in") //currentUser = Auth.auth().currentUser // User is signed in // ... } } func checkIfUserIsLoggedIn(){ if let current = Auth.auth().currentUser{ //performSelector(#selector(dele.firebaseSignOut),withObjec : nil, afterDelay : 0) Database.database().reference().child("Users").child(current.uid).observeSingleEvent(of: .value, with:{Snapshot -> Void in if Snapshot.exists(){ print(Snapshot) var welcomemessage : String = "Welcome Back!" let objectUserName = Snapshot.childSnapshot(forPath: "Username").value as! String print(objectUserName) welcomemessage = "\(objectUserName) \(",")\(welcomemessage)" let alertController = UIAlertController(title: welcomemessage, message: "You've Already Signed In", preferredStyle: .alert) let defaultAction = UIAlertAction(title: "Safe To Home", style: .default){ action in self.performSegue(withIdentifier: "SkipProfile", sender: self) } alertController.addAction(defaultAction) self.present(alertController, animated: true, completion: nil) print("exists") } else{ var welcomemessage : String = "Welcome" let GoogleName: String = current.displayName as! String welcomemessage = "\(welcomemessage) \(GoogleName)" let alertController = UIAlertController(title: welcomemessage, message: "Please create your Profile.", preferredStyle: .alert) let CreateProfileAction = UIAlertAction(title: "Create Profile", style: .default){ action in self.performSegue(withIdentifier: "ToProfile", sender: self) } alertController.addAction(CreateProfileAction) self.present(alertController, animated: true, completion: nil) print("CreateProfile") } }) //if Auth.auth()?.currentUse?.uid == nil{ } } @IBAction func GIDSignOutAction(_ sender: Any) { let dele = AppDelegate() dele.firebaseSignOut() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
// // TeamPageDetailsVC.swift // Etbaroon // // Created by dev tl on 1/18/18. // Copyright © 2018 dev tl. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import Cosmos import AVKit class TeamPageDetailsVC: UIViewController , UINavigationControllerDelegate , UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout { @IBOutlet weak var videoView: UIView! @IBOutlet weak var banner: UIImageView! @IBOutlet weak var imagesView: UIView! @IBOutlet weak var infoView: UIView! let fileUrl = NSURL(fileURLWithPath: "sampleViveo.mp4") var SingelItemTeams : TeamInfo? var imgTeam = [Gallery]() var imgForTeam = [UIImage]() var teamRate = tRate() var resp = res() var direction : Bool! var activityInd : UIActivityIndicatorView = UIActivityIndicatorView() var found : Bool = true let avPlayerVC = AVPlayerViewController() var avPlayer : AVPlayer! var videoURl : NSURL! @IBOutlet weak var challengeBtn: UIButton! @IBOutlet weak var orderLbl: UILabel! @IBOutlet weak var pointsLbl: UILabel! @IBOutlet weak var scoreLbl: UILabel! @IBOutlet weak var noOfMatchesLbl: UILabel! @IBOutlet weak var defaultVideoImg: UIImageView! @IBOutlet weak var galleryImagesCV: UICollectionView! @IBOutlet weak var challengeOrJoinBtn: UIButton! @IBOutlet weak var lblTeamName: UILabel! @IBOutlet weak var imageDes: UIImageView! @IBOutlet weak var cosmosViewFull: CosmosView! lazy var refresherGallery: UIRefreshControl = { let refresherGallery = UIRefreshControl() refresherGallery.addTarget(self, action: #selector(handleRefershGetImages), for: .valueChanged) return refresherGallery }() override func viewWillAppear(_ animated: Bool) { //self.viewDidLoad() } override func viewDidLoad() { super.viewDidLoad() let group = DispatchGroup() group.enter() getTeamRecords() group.leave() if( helper.getUserId() == nil){ challengeBtn.isEnabled = false } self.navigationItem.title = "صفحة الفريق" self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor:UIColor.white] self.navigationItem.backBarButtonItem?.title = "back" self.navigationItem.backBarButtonItem?.tintColor = UIColor.white cosmosViewFull.didFinishTouchingCosmos = didFinishTouchingCosmos handleRefershGetImages() if(helper.getMyPlayerId() == helper.getCaptainId() && (helper.getMyTeamId()) != nil){ challengeOrJoinBtn.setTitle("اطلب التحدي", for: .normal) direction = true } else{ challengeOrJoinBtn.setTitle("اطلب الانضمام", for: .normal) direction = false } print(helper.getMyTeamId() ) print(SingelItemTeams?.TeamId ) if helper.getMyTeamId() == SingelItemTeams?.TeamId { challengeOrJoinBtn.isEnabled = false } lblTeamName.text = SingelItemTeams?.Name if (SingelItemTeams?.url != "غيرموجود"){ let url = URL(string: (SingelItemTeams?.url)!) if url != nil { if let data = try? Data(contentsOf: url!) { imageDes.image = UIImage(data: data) } } else { imageDes.image = UIImage(named: "default_team_photo") } } else{ imageDes.image = UIImage(named: "default_team_photo") } imageDes.layer.cornerRadius = imageDes.frame.height/2 imageDes.layer.borderWidth = 2 imageDes.layer.borderColor = UIColor.black.cgColor imageDes.clipsToBounds = true if(helper.getUserId() != nil){ SetCommentButton() } let TeamID = SingelItemTeams?.TeamId helper.saveOtherTeamId(OtherTeamId: TeamID!) getTeamRate() activityInd.center = self.view.center activityInd.hidesWhenStopped = true activityInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.whiteLarge view.addSubview(activityInd) //videoView if(SingelItemTeams?.TeamId != nil){ let videoS = URLs.URL_GET_TEAM_VIDEO+(SingelItemTeams?.TeamId)!+".mp4" self.videoURl = NSURL(string: videoS) print(videoURl) } loadVideo(){(isfound : Bool)in if isfound { DispatchQueue.main.async{ self.activityInd.stopAnimating() self.view.alpha = 1 self.view.isUserInteractionEnabled = true self.defaultVideoImg.isHidden = true self.avPlayer = AVPlayer(url: self.videoURl as URL) self.avPlayerVC.player = self.avPlayer self.videoView.addSubview(self.avPlayerVC.view) self.avPlayerVC.view.frame = self.videoView.bounds self.avPlayerVC.player?.play() } }else{ DispatchQueue.main.async{ self.defaultVideoImg.isHidden = false self.videoView.isHidden = true self.activityInd.stopAnimating() self.view.alpha = 1 self.view.isUserInteractionEnabled = true } } } //rundom banner let diceRoll = Int(arc4random_uniform(10)) let url = URLs.URL_Banner + "banner_" + String(diceRoll)+".jpg" Alamofire.request(url).response { response in if let data = response.data, let image = UIImage(data: data) { self.banner.image = image }else{ self.banner.image = UIImage(named: "banner_2") } } //getVideo(videoCode: DomainInfo.getDomainUrl()+"Resources/PlayerResources/PlayerResourcesVideo/174.mp4") } override func viewWillDisappear(_ animated: Bool) { self.avPlayerVC.player?.pause() } func SetCommentButton() { let btnRightMenu: UIButton = UIButton() btnRightMenu.setImage(UIImage(named: "comment_white"), for: UIControlState()) btnRightMenu.addTarget(self, action: #selector(self.navigate) , for: UIControlEvents.touchUpInside) let barButton = UIBarButtonItem(customView: btnRightMenu) self.navigationItem.rightBarButtonItem = barButton self.navigationItem.setRightBarButtonItems([barButton], animated: true) } @objc func navigate(){ let teamCommentsVC = storyboard?.instantiateViewController(withIdentifier: "GlobalTeamCommentsVC") as! TeamCommentsVC teamCommentsVC.teamId = SingelItemTeams?.TeamId navigationController?.pushViewController(teamCommentsVC, animated: true) } private func getTeamRate() { //self.refresher.endRefreshing() API_TeamRate.getTeamRate(fldAppTeamID: helper.getOtherTeamId()!){ (error: Error?,_ success: Bool ,tRating:tRate?)in if success { if let Team = tRating { self.teamRate = Team let num = Double(self.teamRate.fldAppTeamRating ) if ( num != nil) { self.cosmosViewFull.rating = num! } } else { self.cosmosViewFull.rating = Double(0.0) } } else { self.cosmosViewFull.rating = Double(0.0) } } } @objc private func handleRefershGetImages() { self.refresherGallery.endRefreshing() API_Gallery.getGalleryImagesForTeam(TeamId: SingelItemTeams!.TeamId ){(error: Error?, GalleryImages: [Gallery]? , success: Bool)in if success { if (GalleryImages != nil){ for index in 0..<GalleryImages!.count { let url = GalleryImages![index].imgUrl Alamofire.request(url!).response { response in if let data = response.data, let image = UIImage(data: data) { self.imgForTeam.append(image) self.galleryImagesCV.reloadData() } } } } } } } @objc private func getTeamRecords() { API_TeamDetails.getTeamOrder(fldAppTeamID: SingelItemTeams!.TeamId) { (error: Error?, teamOrder : String?)in if(teamOrder == nil){ self.orderLbl.text = "0" } else { print(teamOrder!) self.orderLbl.text = teamOrder! } } API_TeamDetails.getTeamScore(fldAppTeamID: SingelItemTeams!.TeamId) { (error: Error?, teamScore : String?)in if(teamScore == nil){ self.scoreLbl.text = "0" } else { print(teamScore!) self.scoreLbl.text = teamScore! } } API_TeamDetails.getTeamPoints(fldAppTeamID: SingelItemTeams!.TeamId) { (error: Error?, teamPoints : String?)in if(teamPoints == nil){ self.pointsLbl.text = "0" } else { print(teamPoints!) self.pointsLbl.text = teamPoints! } } API_TeamDetails.getTeamMatchesNumber(fldAppTeamID: SingelItemTeams!.TeamId) { (error: Error?, teamNoOfMathces : String?)in if(teamNoOfMathces == nil){ self.noOfMatchesLbl.text = "0" } else { print(teamNoOfMathces!) self.noOfMatchesLbl.text = teamNoOfMathces! } } } private func didFinishTouchingCosmos(_ rating: Double) { print(rating) if(helper.getUserId() != nil) { API_TeamRate.setTeamRate(fldAppUserID: helper.getUserId()!, fldAppTeamID: helper.getOtherTeamId()!, fldAppTeamRate: String(rating)) { (error: Error? , success: Bool, responce :res?) in if success { print("request succeeded") if let res = responce { self.resp = res self.setAlert(message: res.message) self.getTeamRate() } } } } else{ setAlert(message: "قم بالتسجيل اولا") } } @IBAction func showChallengeView(_ sender: UIButton) { if(helper.getMyPlayerId() != nil){ if(direction){ if((helper.getMyTeamId()) != nil){ let challengeTeamVc = storyboard?.instantiateViewController(withIdentifier: "ChallengeTeamVC") as! ChallengeTeamVC challengeTeamVc.teamNameDis = lblTeamName.text challengeTeamVc.teamImageDis = imageDes.image navigationController?.pushViewController(challengeTeamVc, animated: true) } else{ self.setAlert(message: "كون فريقك اولا") } } else{ //send join Team Request //let reqComment = "I am '"+helper.getUserName()!+"' request to join your team "+(SingelItemTeams?.Name)! var reqComment = "قام " reqComment.append("'"+helper.getUserName()!+"'") reqComment.append(" بتقديم طلب للانضمام لفريقك الحالي ") print(reqComment) API_JoinRequestToCaptain.SendJoinRequest(fldAppPlayerID: helper.getMyPlayerId()! ,fldAppCaptainID: (SingelItemTeams?.CaptainId)!, AppInvitationComment : reqComment){(_ error: Error?, message: String )in let msg = reqComment API_Firebase.sendSinglePushByPlayerId(title: "Join Team Request", message: msg, fldAppPlayerID: (self.SingelItemTeams?.CaptainId)!){( error: Error?, success: Bool )in if success { print("Notification sent successfully") } } if ( message == "Your Invitation Sent Successfully" ) { self.setAlert(message: "تم ارسال الطلب بنجاح") } else if ( message == "You Already Send Invitation" ) { self.setAlert(message: "تم ارسال الطلب مسبقا") } } } } else{ self.setAlert(message: "قم بالتسجيل اولا") } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let dis=segue.destination as? ChallengeTeamVC{ if let Team = sender as? TeamInfo { dis.teamToChallenge = Team } } } @IBAction func showTeamComments(_ sender: UIButton) { let teamCommentsVC = storyboard?.instantiateViewController(withIdentifier: "GlobalTeamCommentsVC") as! TeamCommentsVC teamCommentsVC.teamId = SingelItemTeams?.TeamId navigationController?.pushViewController(teamCommentsVC, animated: true) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imgForTeam.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell:TeamPhotoCVCell = collectionView.dequeueReusableCell(withReuseIdentifier: "TeamPhotoCVCell", for: indexPath) as! TeamPhotoCVCell cell.layer.cornerRadius=5.0 cell.layer.masksToBounds=false cell.layer.shadowColor=UIColor.black.withAlphaComponent(0.2).cgColor cell.layer.shadowOffset=CGSize(width: 0, height: 0) cell.layer.shadowOpacity=0.8 cell.imgPlayer.image = imgForTeam[indexPath.row] return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let imageView = UIImageView(image: imgForTeam[indexPath.row]) imageView.frame = self.view.frame imageView.contentMode = .center imageView.backgroundColor = UIColor.clear imageView.isUserInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(self.dismissFullscreenImage)) imageView.addGestureRecognizer(tap) self.view.addSubview(imageView) imageView.alpha = 1 imagesView.alpha = 0.5 infoView.alpha = 0.5 } func fileExistsAt(url : URL, completion: @escaping (Bool) -> Void) { let checkSession = Foundation.URLSession.shared var request = URLRequest(url: url) request.httpMethod = "HEAD" request.timeoutInterval = 1.0 // Adjust to your needs let task = checkSession.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if let httpResp: HTTPURLResponse = response as? HTTPURLResponse { completion(httpResp.statusCode == 200) } }) task.resume() } func loadVideo (completion: @escaping (_ error: Bool)->Void) { self.activityInd.startAnimating() self.view.alpha = 0.5 self.view.isUserInteractionEnabled = false fileExistsAt(url : videoURl as URL ){(success : Bool)in if success{ print("FILE AVAILABLE") self.found = true completion(self.found) } else { print("FILE NOT AVAILABLE") self.found = false completion(self.found) } } } @objc func dismissFullscreenImage(_ sender: UITapGestureRecognizer) { sender.view?.removeFromSuperview() self.view.alpha = 1 imagesView.alpha = 1 infoView.alpha = 1 } func setAlert(message : String) { let attributedString = NSAttributedString(string: " ", attributes: [ NSAttributedStringKey.font : UIFont.systemFont(ofSize: 15), //your font here NSAttributedStringKey.foregroundColor : UIColor.green ]) let alert = UIAlertController(title: "", message: "\(message)", preferredStyle: UIAlertControllerStyle.alert) let imageView = UIImageView(frame: CGRect(x: 10, y: 35, width: 30, height: 30)) imageView.image = UIImage(named: "ball_icon") alert.view.addSubview(imageView) alert.setValue(attributedString, forKey: "attributedTitle") alert.addAction(UIAlertAction(title: "موافق", style: UIAlertActionStyle.default, handler: nil)) present(alert, animated: true, completion: nil) } }
// // InterStaffListView.swift // AP5004 // // Created by Phạm Đức Mạnh on 3/18/19. // Copyright © 2019 Phạm Đức Mạnh. All rights reserved. // import Foundation protocol InnerStaffListView: BaseView { func onShowProgress() func onDismissProgress() func onGetStaffList(_ staffList: [Staff]) }
// // SelectUnitVC.swift // ELRDRG // // Created by Jonas Wehner on 09.09.18. // Copyright © 2018 Martin Mangold. All rights reserved. // import UIKit protocol unitSelectedProtocol { func didSelectUnit(unit : BaseUnit) func didSelectHospital(hospital : BaseHospital) func didselectUsedUnit(unit : Unit) } class SelectUnitVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UnitExtention, UISearchBarDelegate { func createdUnit(unit: BaseUnit) { self.delegate?.didSelectUnit(unit: unit) self.dismiss(animated: true, completion: nil) } let hospitalData = HospitalHandler() let unitData = UnitHandler() var units : [BaseUnit] = [] var usedUnits : [Unit] = [] var hospitals : [BaseHospital] = [] public var delegate : unitSelectedProtocol? public var type : availableTypes = .unitselector private var searchText : String = "" enum availableTypes { case unitselector case hospitalselector } @IBOutlet weak var searchBar: UISearchBar! func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { self.searchText = searchText table.reloadData() } func numberOfSections(in tableView: UITableView) -> Int { if type == .unitselector { return 2 } else { return 1 } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //do something // used hospitals separieren if(type == .unitselector) { if section == 0 { self.usedUnits = unitData.getUsedUnits() usedUnits = usedUnits.filter { if typeSelector.selectedSegmentIndex < 4 && $0.type == typeSelector.selectedSegmentIndex { if searchText.count > 0 { return $0.callsign!.uppercased().contains(searchText.uppercased()); } else { return true } } else if(typeSelector.selectedSegmentIndex == 4 && $0.type > 3) { if searchText.count > 0 { return $0.callsign!.uppercased().contains(searchText.uppercased()); } else { return true } } else { return false } } usedUnits.sort { ($0.callsign ?? "") < ($1.callsign ?? "") } return usedUnits.count } else { units = unitData.getUnusedBaseUnits() units = units.filter { if typeSelector.selectedSegmentIndex < 4 && $0.type == typeSelector.selectedSegmentIndex { return true } else if(typeSelector.selectedSegmentIndex == 4 && $0.type > 3) { return true } else { return false } } var newUnitList : [BaseUnit] = [] if searchText.count > 0 { for unit in self.units { if(unit.funkrufName!.uppercased().contains(searchText.uppercased())) { newUnitList.append(unit) } } units = newUnitList units.sort { ($0.funkrufName ?? "") < ($1.funkrufName ?? "") } } newUnitList = [] for unit in units{ var available = false for usedUnit in usedUnits { if usedUnit.callsign == unit.funkrufName { available = true } } if !available { newUnitList.append(unit) } } units = newUnitList units.sort { ($0.funkrufName ?? "") < ($1.funkrufName ?? "") } return units.count } } else if(type == .hospitalselector) { hospitals = hospitalData.getAllHospitals() var newHospitalList : [BaseHospital] = [] if searchText.count > 0 { for hospital in hospitals { let text : String = (hospital.city ?? "") + " " + (hospital.name ?? "") if(text.uppercased().contains(searchText.uppercased())) { newHospitalList.append(hospital) } } hospitals = newHospitalList } return hospitals.count } //einfang return 0 } @IBAction func AddCostum(_ sender: Any) { if(type == .unitselector) { let vc = self.storyboard?.instantiateViewController(withIdentifier: "CreateUnitVC") as! CreateUnitVC vc.delegate = self self.present(vc, animated: true, completion: nil) } else { handleHospitalAddAction() } } func handleHospitalAddAction() { let alertController = UIAlertController(title: "Klinik", message: "Stammdaten Krankenhaus erstellen", preferredStyle: .alert) alertController.addTextField { (textField : UITextField!) -> Void in textField.placeholder = "Krankenhaus" } alertController.addTextField {(textField : UITextField!) -> Void in textField.placeholder = "Stadt" } let saveAction = UIAlertAction(title: "Erstellen", style: .default, handler: { alert -> Void in let hospitalName = (alertController.textFields![0] as UITextField).text let hospitalCity = (alertController.textFields![1] as UITextField).text if((alertController.textFields![0] as UITextField).text != "" && (alertController.textFields![1] as UITextField).text != "") { let hospital = self.hospitalData.addBaseHospital(name: hospitalName!, city: hospitalCity!) self.delegate!.didSelectHospital(hospital: hospital) self.dismiss(animated: true, completion: nil) } }) let abortaction = UIAlertAction(title: "Abbrechen", style: .destructive, handler: nil) alertController.addAction(saveAction) alertController.addAction(abortaction) self.present(alertController, animated: true, completion: nil) } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if type == .unitselector { if section == 0 { return "Bereits im Einsatz" } else{ return "Stammdaten" } } return "" } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = table.dequeueReusableCell(withIdentifier: "selectUnitCell") as! UnitSelectCostumTableViewCell if(type == .unitselector) { if indexPath.section == 0 { let unit = usedUnits[indexPath.row] cell.Callsign.text = unit.callsign cell.crewCount.text = "" cell.pictureBox.image = BaseUnit.getImage(type: unit.type) cell.type.text = UnitHandler.BaseUnit_To_UnitTypeString(id: unit.type) var brightness = 0.92 if traitCollection.userInterfaceStyle == .dark { brightness = 0.32 } cell.backgroundColor = UIColor(hue: 0.2917, saturation: 0.35, brightness: CGFloat(brightness), alpha: 1.0) } else { let unit = units[indexPath.row] cell.Callsign.text = unit.funkrufName cell.crewCount.text = "" cell.pictureBox.image = UIImage(named: UnitHandler.BaseUnit_To_UnitTypeString(id: unit.type)) cell.type.text = UnitHandler.BaseUnit_To_UnitTypeString(id: unit.type) //cell.backgroundColor = UIColor.white } } else { let hospital = hospitals[indexPath.row] cell.Callsign.text = hospital.name cell.type.text = hospital.city cell.crewCount.text = String(Int((hospital.distance / 1000).rounded())) + " km" cell.pictureBox.image = UIImage(named: "hospital.png") //cell.backgroundColor = UIColor.clear } //do something return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 0 { if(type == .unitselector) { self.delegate!.didselectUsedUnit(unit: usedUnits[indexPath.row]) } else { self.delegate!.didSelectHospital(hospital: hospitals[indexPath.row]) } } else { if(type == .unitselector) { self.delegate!.didSelectUnit(unit: units[indexPath.row]) } else { self.delegate!.didSelectHospital(hospital: hospitals[indexPath.row]) } } self.dismiss(animated: true, completion: nil) } @IBOutlet weak var table: UITableView! @IBAction func abort_click(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBOutlet var typeSelector: UISegmentedControl! @IBAction func typeSelectorChanged(_ sender: Any) { searchBar(self.searchBar, textDidChange: self.searchBar.searchTextField.text ?? "") } override func viewDidLoad() { super.viewDidLoad() units = unitData.getAllBaseUnits() hospitals = hospitalData.getAllHospitals() if self.type == .unitselector { typeSelector.isHidden = false } else { typeSelector.isHidden = true } searchBar.delegate = self table.delegate = self table.dataSource = self searchBar(self.searchBar, textDidChange: self.searchBar.searchTextField.text ?? "") // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // ValueOrDecodingError.swift // Statham // // Created by Tom on 2016-07-18. // Copyright © 2016 Tom Lokhorst. All rights reserved. // import Foundation public enum ValueOrDecodingError<Wrapped> { case value(Wrapped) case error(DecodingError) public var value: Wrapped? { get { switch self { case .value(let value): return value case .error: return nil } } set { if let value = newValue { self = .value(value) } } } public var error: DecodingError? { switch self { case .value: return nil case .error(let error): return error } } } extension ValueOrDecodingError: Decodable where Wrapped: Decodable { public init(from decoder: Decoder) throws { do { let container = try decoder.singleValueContainer() let value = try container.decode(Wrapped.self) self = .value(value) } catch { if let error = error as? DecodingError { self = .error(error) } else { let context = DecodingError.Context(codingPath: [], debugDescription: "Unexpected non-DecodingError", underlyingError: error) self = .error(DecodingError.dataCorrupted(context)) } } } } extension ValueOrDecodingError: Encodable where Wrapped: Encodable { public func encode(to encoder: Encoder) throws { switch self { case .value(let value): var container = encoder.singleValueContainer() try container.encode(value) case .error: var container = encoder.singleValueContainer() try container.encodeNil() } } }
// // OrderTableViewCell.swift // NRTC // // Created by Wassay Khan on 03/10/2018. // Copyright © 2018 Netpace. All rights reserved. // import UIKit class OrderTableViewCell: UITableViewCell { @IBOutlet weak var orderView: UIView! @IBOutlet weak var lbQuantity: UILabel! @IBOutlet weak var imgProduct: UIImageView! @IBOutlet weak var lbTitle: UILabel! @IBOutlet weak var lbPrice: UILabel! @IBOutlet weak var lbUnitPrice: UILabel! var onAddTapped : (() -> Void)? = nil var onSubTapped : (() -> Void)? = nil override func awakeFromNib() { super.awakeFromNib() // Initialization code self.orderView.layer.cornerRadius = 10 self.orderView.clipsToBounds = true } @IBAction func btnAddAction(_ sender: Any) { if let onAddTapped = self.onAddTapped { onAddTapped() } //print(quantity) } @IBAction func btnSubtractAction(_ sender: Any) { if let onSubTapped = self.onSubTapped { onSubTapped() } } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }