blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
6
116
path
stringlengths
5
872
src_encoding
stringclasses
7 values
length_bytes
int64
10
4.68M
score
float64
2.52
5.63
int_score
int64
3
5
detected_licenses
listlengths
0
47
license_type
stringclasses
2 values
text
stringlengths
7
4.81M
download_success
bool
1 class
27c7818eafdf667568ed61350f767079277c72e3
Swift
sarveshsingh88/Mivi_sample
/Mivi/Mivi/Home/ViewController/ProductsViewC.swift
UTF-8
2,269
2.625
3
[]
no_license
// // ProductsViewC.swift // Mivi // // Created by Talentedge on 17/08/18. // Copyright © 2018 Sample. All rights reserved. // import UIKit class ProductsViewC: UIViewController { @IBOutlet weak var tableView: UITableView! var products = [Product]() override func viewDidLoad() { super.viewDidLoad() self.title = "Product" self.navigationController?.isNavigationBarHidden = false if let servicesArr = DataParser.productsModels() { self.products.append(contentsOf: servicesArr) // TableView Setup self.tableView.registerMultiple(nibs: [ProductTVCell.className]) self.tableView.estimatedRowHeight = 100 self.tableView.rowHeight = UITableViewAutomaticDimension self.tableView.reloadData() } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ProductsViewC: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return products.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return self.cellForIdentifier(ProductTVCell.className, indexPath: indexPath, tableView) } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) } } extension ProductsViewC { func cellForIdentifier(_ identifier: String, indexPath: IndexPath, _ tableView: UITableView) -> UITableViewCell { switch identifier { case ProductTVCell.className: if let cell = tableView.dequeueReusableCell(withIdentifier: ProductTVCell.className, for: indexPath) as? ProductTVCell { let data = products[indexPath.row] cell.configureWith(product: data) return cell } return UITableViewCell() default: return UITableViewCell() } } }
true
39130388707ea1116ec1399351e3a74111f3d220
Swift
suwagboe/SkinT-App
/ActualSkinTeaApp/main controllers/LoginViewController.swift
UTF-8
3,528
2.765625
3
[]
no_license
// // ViewController.swift // ActualSkinTeaApp // // Created by Pursuit on 12/29/19. // Copyright © 2019 Pursuit. All rights reserved. // import UIKit // The readMe should be done. class LoginViewController: UIViewController { // MARK: outlets and variables @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var signInButton: UIButton! override func viewDidLoad() { super.viewDidLoad() handleTextField() self.emailTextField.delegate = self self.passwordTextField.delegate = self // the code to set the emailtextfield emailTextField.backgroundColor = UIColor.clear emailTextField.tintColor = UIColor.white emailTextField.textColor = UIColor.systemBlue // emailTextField.attributedPlaceholder = NSAttributedString(string: emailTextField.placeholder!, attributes: [NSForegroundColorAttributeName: UIColor(white: 1.0, alpha: 0.6)]) // need to double check what this does let bottomLayerEmail = CALayer() bottomLayerEmail.frame = CGRect(x: 0, y: 29, width: 1000, height: 0.6) emailTextField.layer.addSublayer(bottomLayerEmail) passwordTextField.backgroundColor = UIColor.clear passwordTextField .tintColor = UIColor.white passwordTextField.textColor = UIColor.systemBlue // let attributeString = passwordTextField.placeholder! //passwordTextField.attributedPlaceholder = NSAttributedString(string: passwordTextField.placeholder!, attributes: [NSForegroundColorAttributesName: UIColor(white: 1.0, alpha: 0.6)]) let bottomLayerPassword = CALayer() bottomLayerPassword.frame = CGRect(x: 0, y: 29, width: 1000, height: 0.6) bottomLayerPassword.backgroundColor = UIColor(red: 20/255, green: 50/255, blue: 25/255, alpha: 1).cgColor //passwordTextField.layer.addSublayer(bottomLayerPassword) } func handleTextField() { emailTextField.addTarget(self, action: #selector(LoginViewController.textFieldDidChange), for: UIControl.Event.editingChanged) passwordTextField.addTarget(self, action: #selector(LoginViewController.textFieldDidChange), for: UIControl.Event.editingChanged) } @objc func textFieldDidChange() { guard let emailtext = emailTextField.text, !emailtext.isEmpty, let passwordText = passwordTextField.text else { signInButton.setTitleColor(UIColor.lightText, for: UIControl.State.normal) signInButton.isEnabled = false return } // if the information has text in it then the sign in button will work signInButton.setTitleColor(UIColor.green, for: UIControl.State.normal) signInButton.isEnabled = true } // MARK: action make results @IBAction func signupButton(_ sender: UIButton) { // prepare(for: <#T##UIStoryboardSegue#>, sender: <#T##Any?#>) } } extension LoginViewController: UITextFieldDelegate{ // text func textFieldShouldReturn(_ textField: UITextField) -> Bool { // dismiss the keyboard emailTextField.resignFirstResponder() passwordTextField.resignFirstResponder() // need to get code that will store the information user enters return true } }
true
475d489b91193da64c6a36a89bbf703b9ae95ba2
Swift
Kovaline/Swift-Piscine
/day09/day09/AddArticleViewController.swift
UTF-8
4,727
2.546875
3
[]
no_license
// // AddArticleViewController.swift // day09 // // Created by Ihor KOVALENKO on 10/11/19. // Copyright © 2019 Ihor KOVALENKO. All rights reserved. // import UIKit import ikovalen2019 import AVFoundation class AddArticleViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { let pickerController = UIImagePickerController() let articleMan = ArticleManager(); var oldarticle: Article? @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var title1: UITextField! @IBOutlet weak var contentView: UITextView! @IBAction func saveButton(_ sender: Any) { if (oldarticle == nil) { print ("imhere") let article = articleMan.newArticle(); if title1.text != "" { article.title = title1.text } if contentView.text != "" { article.content = contentView.text } if imageView.image != nil { if let imageData = UIImageJPEGRepresentation(imageView.image!, 1){ article.image = imageData as NSData? } } article.creation_date = NSDate() article.mod_date = NSDate(); } else { oldarticle?.mod_date = NSDate() oldarticle?.title = title1.text oldarticle?.content = contentView.text if imageView.image != nil { if let imageData = UIImageJPEGRepresentation(imageView.image!, 1){ oldarticle?.image = imageData as NSData? } } } articleMan.save() self.navigationController?.popViewController(animated: true) } @IBAction func takePhoto(_ sender: Any) { AVCaptureDevice.requestAccess(for: AVMediaType.video) { response in if response { if(UIImagePickerController.isSourceTypeAvailable(.camera)) { self.pickerController.sourceType = .camera self.present(self.pickerController, animated: true, completion: nil) } else { let alert = UIAlertController(title: "Alert", message: "No Camera available", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } else { let alert = UIAlertController(title: "Alert", message: "No Camera available", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } @IBAction func selectPhoto(_ sender: Any) { if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)) { pickerController.sourceType = .photoLibrary present(pickerController, animated: true, completion: nil) } else { let alert = UIAlertController(title: "Alert", message: "No Library available", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { imageView.image = pickedImage } dismiss(animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() pickerController.delegate = self; if (oldarticle != nil) { title1.text = oldarticle?.title contentView.text = oldarticle?.content if let image = oldarticle?.image { imageView.image = UIImage(data: image as Data) } } // 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. } */ }
true
3627fc2365cb3a3bbf3312d20075d3873ef37ca4
Swift
jordainfg/OneMenu3.0
/One Menu/OneMenuAppClip/FirebaseService.swift
UTF-8
2,057
2.75
3
[ "MIT" ]
permissive
// // FirebaseService.swift // One Menu // // Created by Jordain Gijsbertha on 21/08/2020. // import Foundation import Firebase import FirebaseCore //import FirebaseMessaging class FirebaseService : NSObject { static let shared = FirebaseService() func start() {} func configure(){ FirebaseApp.configure() Auth.auth().signInAnonymously() { (authResult, error) in // ... guard let user = authResult?.user else { return } user.getIDTokenForcingRefresh(true) { idToken, error in if let error = error { // Handle error print("Error getting token for request: \(error.localizedDescription)") return; } UserDefaults.standard.setValue(idToken, forKey: "token") // Send token to your backend via HTTPS // ... } } } func refreshToken(completionHandler: @escaping (Result<Response, CoreError>) -> Void){ Auth.auth().signInAnonymously() { (authResult, error) in // ... guard let user = authResult?.user else { completionHandler(.failure(CoreError.errorDescription(error: "Error getting token for request"))) return } user.getIDTokenForcingRefresh(true) { idToken, error in if let error = error { // Handle error completionHandler(.failure(CoreError.errorDescription(error: "Error getting token for request"))) print("Error getting token for request: \(error.localizedDescription)") return; } print("Succesful token refresh") UserDefaults.standard.setValue(idToken, forKey: "token") completionHandler(.success(Response.tokenRefreshed)) } } } }
true
ef125eb5e0d02a2873a985adcf8f80cffbff032b
Swift
issaCucumber/TrafficCameraSnap
/TrafficCameraSnap/Model/Common.swift
UTF-8
666
3.03125
3
[]
no_license
// // Common.swift // TrafficCameraSnap // // Created by Christina Lui on 28/3/21. // import MapKit struct Location: Decodable { let latitude: Double let longitude: Double var coordinates: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } } struct ImageMetadata: Decodable { let height: Int let width: Int let md5: String } enum APIStatus { case healthy case sick } struct APIInfo: Decodable { let status: String var readableStatus: APIStatus { if status == "healthy" { return .healthy } return .sick } }
true
e3c7e6254ad2ee98d2cbb7cc587b274d96350987
Swift
ismetanin/vk-hack-art-of-coding
/sevcabel/Reuse/DrawerTransition/DrawerCustomTransitionDelegate.swift
UTF-8
1,354
2.5625
3
[]
no_license
// // DrawerCustomTransitionDelegate.swift // sevcabel // // Created by Ivan Smetanin on 11/11/2018. // Copyright © 2018 Ivan Smetanin. All rights reserved. // import UIKit final class DrawerCustomTransitionDelegate: NSObject, UIViewControllerTransitioningDelegate { // MARK: - Constants private let interactiveTransition = UIPercentDrivenInteractiveTransition() // MARK: - Properties var shouldDoInteractive = false // MARK: - Internal helpers func update(with progress: Float) { interactiveTransition.update(CGFloat(progress)) } func finish() { interactiveTransition.finish() } func cancel() { interactiveTransition.cancel() } // MARK: - UIViewControllerTransitioningDelegate func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return DrawerPresentTransition() } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return DrawerDismissTransition() } func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return shouldDoInteractive ? interactiveTransition : nil } }
true
69ebf48d9ef335f877f89f01a472943d8c7dc701
Swift
kindnesswall/iOSApp
/app/Models/Country.swift
UTF-8
356
2.71875
3
[]
no_license
// // Country.swift // app // // Created by Amir Hossein on 2/27/20. // Copyright © 2020 Hamed.Gh. All rights reserved. // import Foundation class Country: Codable { var id:Int? var name:String var phoneCode: String? var localization: String? var sortIndex:Int? var isFarsi: Bool { return localization == "fa" } }
true
ca7242eda49325fd009a5c8faef637b830d6b587
Swift
AdrianBinDC/SwifterSwift
/Sources/Extensions/Foundation/Deprecated/FoundationDeprecated.swift
UTF-8
1,662
3.390625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // FoundationDeprecated.swift // SwifterSwift // // Created by Guy Kogus on 04/10/2018. // Copyright © 2018 SwifterSwift // #if canImport(Foundation) import Foundation extension Date { /// SwifterSwift: Random date between two dates. /// /// Date.random() /// Date.random(from: Date()) /// Date.random(upTo: Date()) /// Date.random(from: Date(), upTo: Date()) /// /// - Parameters: /// - fromDate: minimum date (default is Date.distantPast) /// - toDate: maximum date (default is Date.distantFuture) /// - Returns: random date between two dates. @available(*, deprecated: 4.7.0, message: "Use random(in:) or random(in:using:) instead") public static func random(from fromDate: Date = Date.distantPast, upTo toDate: Date = Date.distantFuture) -> Date { guard fromDate != toDate else { return fromDate } let diff = llabs(Int64(toDate.timeIntervalSinceReferenceDate - fromDate.timeIntervalSinceReferenceDate)) var randomValue: Int64 = Int64.random(in: Int64.min...Int64.max) randomValue = llabs(randomValue%diff) let startReferenceDate = toDate > fromDate ? fromDate : toDate return startReferenceDate.addingTimeInterval(TimeInterval(randomValue)) } /// SwifterSwift: Time zone used currently by system. /// /// Date().timeZone -> Europe/Istanbul (current) /// @available(*, deprecated: 4.7.0, message: "`Date` objects are timezone-agnostic. Please use Calendar.current.timeZone instead.") public var timeZone: TimeZone { return Calendar.current.timeZone } } #endif
true
683fd73529807d1c8429f8308e955db5ac831990
Swift
ProjectWoong/Woong_iOS
/Woong-iOS/Models/CartData.swift
UTF-8
699
2.640625
3
[]
no_license
// // CartData.swift // Woong-iOS // // Created by Leeseungsoo on 2018. 7. 12.. // Copyright © 2018년 Leess. All rights reserved. // import Foundation struct CartData: Codable { let message: String let data: [Cart] } struct Cart: Codable { let marketID, itemID: Int let carttitle, fileKey, packging: String let itemPrice: Int let itemUnit: String let delivery: Int enum CodingKeys: String, CodingKey { case marketID = "market_id" case itemID = "item_id" case carttitle case fileKey = "file_key" case packging case itemPrice = "item_price" case itemUnit = "item_unit" case delivery } }
true
f38ad8cc2610aeeb5056beaad3f3c353f2f77f3e
Swift
eyupgoymen/FamilyTracking
/FamilyTracking/UI/CustomUI/TextField/TextFieldStyle.swift
UTF-8
878
2.921875
3
[ "MIT" ]
permissive
// // TextFieldStyle.swift // FamilyTracking // // Created by Eyup Kazım Göymen on 4.09.2019. // Copyright © 2019 Eyup Kazım Göymen. All rights reserved. // import UIKit enum TextFieldStyle { case none case popup(_ placeHolder: String) private var style: Style<TextFieldProp> { switch self { case .popup(let placeHolder): return .with( .backgroundColor(UIColor.black.withAlphaComponent(0.1)), .cornerRadius(8), .align(.left), .placeHolder(placeHolder), .font(Fonts.System_Placeholder), .leftPadding(4), .autoCapitalization(.none) ) default: return Style() } } func install(to label: UITextField) { style.install(to: label) } }
true
8fb27f7b1cbd7a938df6f711cc971d83b7f75e52
Swift
wimix-dev/AlgorithmsCollection
/Sources/AlgorithmsCollection/ObjectPool/KeyedObjectPool.swift
UTF-8
1,022
3.0625
3
[ "MIT" ]
permissive
// // File.swift // // // Created by Vitali Kurlovich on 7.07.21. // import Foundation public final class KeyedObjectPool<T: AnyObject, Key: Hashable> { private var objectPool = [Key: T]() public let createObject: (Key) -> T public let maxSize: Int public init(maxSize: Int = 0, createObject: @escaping (Key) -> T) { self.maxSize = maxSize self.createObject = createObject if maxSize > 0 { objectPool.reserveCapacity(maxSize) } } public func pull(key: Key) -> T { if let object = objectPool.removeValue(forKey: key) { return object } if let key = objectPool.first?.key, let object = objectPool.removeValue(forKey: key) { return object } return createObject(key) } public func push(_ object: T, for key: Key) { guard maxSize == 0 || objectPool.count < maxSize || objectPool[key] != nil else { return } objectPool[key] = object } }
true
5f7a3a73af07f911f52ea553ce9ad14908aca1c6
Swift
bernardonunes97/WWDC_2020_Scholarship
/MemoryGame.playground/Contents.swift
UTF-8
535
2.59375
3
[]
no_license
//: A UIKit based Playground for presenting user interface import UIKit import PlaygroundSupport // Present the view controller in the Live View window PlaygroundPage.current.needsIndefiniteExecution = true let window = UIWindow() window.frame.size = CGSize(width: 768, height: 576) let initialViewController = InitialViewController() initialViewController.preferredContentSize = CGSize(width: 768, height: 576) window.rootViewController = initialViewController window.makeKeyAndVisible() PlaygroundPage.current.liveView = window
true
eac48d29d0e7d5a661d1bc9f762b97e61b9ee54e
Swift
lfryer/Ashland-Nyanza-Project
/Ashland-Nyanza Project/BookListTableViewController.swift
UTF-8
10,613
2.53125
3
[]
no_license
// // BookListViewController.swift // Ashland-Nyanza Project // // Created by Lorraine Fryer on 10/14/15. // Copyright © 2015 Lorraine Fryer. All rights reserved. // import UIKit class BookListViewController: UITableViewController { @IBAction func back(sender: UIButton) { dismissViewControllerAnimated(true, completion: nil) } var bookList = [BookListItem]() override func viewDidLoad() { super.viewDidLoad() loadBookList() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } func loadBookList() { let photo1 = UIImage(named: "flashpoints.jpg")! let book1 = BookListItem(text: "Flashpoints in Environmental Policymaking", photo: photo1, url: "http://amzn.com/0791433307") let photo2 = UIImage(named: "better.jpg")! let book2 = BookListItem(text: "Better: The Everyday Art of Sustainable Living", photo: photo2, url: "http://amzn.com/086571794X") let photo3 = UIImage(named: "bodytoxic.jpg")! let book3 = BookListItem(text: "Body Toxic: An Environmental Memoir", photo: photo3, url: "http://amzn.com/1582431167") let photo4 = UIImage(named: "moralground.jpg")! let book4 = BookListItem(text: "Moral Ground: Ethical Action for a Planet in Peril", photo: photo4, url: "http://amzn.com/1595340858") let photo5 = UIImage(named: "1001ways.jpg")! let book5 = BookListItem(text: "1001 Ways to Save the Earth", photo: photo5, url: "http://amzn.com/081185986X") let photo6 = UIImage(named: "ecochick.jpg")! let book6 = BookListItem(text: "The Eco Chick Guide to Life: How to Be Fabulously Green", photo: photo6, url: "http://amzn.com/0312378947") let photo7 = UIImage(named: "betterworldshopping.jpg")! let book7 = BookListItem(text: "The Better World Shopping Guide #5: Every Dollar Makes a Difference", photo: photo7, url: "http://amzn.com/0865717907") let photo8 = UIImage(named: "toxicwastesites.jpg")! let book8 = BookListItem(text: "Toxic Waste Sites: An Encyclopedia of Endangered America", photo: photo8, url: "http://amzn.com/0874369347") let photo9 = UIImage(named: "theepa.jpg")! let book9 = BookListItem(text: "EPA (Government Agencies)", photo: photo9, url: "http://amzn.com/158810981X") let photo10 = UIImage(named: "ecosinner.jpg")! let book10 = BookListItem(text: "Confessions of an Eco-Sinner: Tracking Down the Sources of My Stuff", photo: photo10, url: "http://amzn.com/0807085952") let photo11 = UIImage(named: "nottypicalbook.jpg")! let book11 = BookListItem(text: "Not Your Typical Book About the Environment", photo: photo11, url: "http://amzn.com/189734984X") let photo12 = UIImage(named: "toxicdebts.jpg")! let book12 = BookListItem(text: "Toxic Debts and the Superfund Dilemma", photo: photo12, url: "http://amzn.com/0807844357") let photo13 = UIImage(named: "commonchemicals.jpg")! let book13 = BookListItem(text: "Common Chemicals Found at Superfund Sites", photo: photo13, url: "http://amzn.com/1249499585") let photo14 = UIImage(named: "conundrum.jpg")! let book14 = BookListItem(text: "The Conundrum", photo: photo14, url: "http://amzn.com/1594485615") let photo15 = UIImage(named: "environmentalgeology.jpg")! let book15 = BookListItem(text: "Environmental Geology (8th Edition)", photo: photo15, url: "http://amzn.com/0130224669") let photo16 = UIImage(named: "whereamiwearing.jpg")! let book16 = BookListItem(text: "Where am I Wearing: A Global Tour to the Countries, Factories, and People That Make Our Clothes", photo: photo16, url: "http://amzn.com/1118277554") let photo17 = UIImage(named: "pollution.jpg")! let book17 = BookListItem(text: "Pollution (Current Controversies)", photo: photo17, url: "http://amzn.com/0737756357") let photo18 = UIImage(named: "environmentalpendulum.jpg")! let book18 = BookListItem(text: "The Environmental Pendulum: A Quest for the Truth about Toxic Chemicals, Human Health, and Environmental Protection", photo: photo18, url: "http://amzn.com/0520220471") let photo19 = UIImage(named: "nucleartoxicwaste.jpg")! let book19 = BookListItem(text: "Nuclear and Toxic Waste (At Issue Series)", photo: photo19, url: "http://amzn.com/0737746823") let photo20 = UIImage(named: "cleaningupthemess.jpg")! let book20 = BookListItem(text: "Cleaning Up the Mess: Implementation Strategies in Superfund", photo: photo20, url: "http://amzn.com/0815714130") let photo21 = UIImage(named: "invisiblenature.jpg")! let book21 = BookListItem(text: "Invisible Nature: Healing the Destructive Divide Between People and the Environment", photo: photo21, url: "http://amzn.com/B00BH0VPII") let photo22 = UIImage(named: "unequalprotection.jpg")! let book22 = BookListItem(text: "Unequal Protection: Environmental Justice and Communities of Color", photo: photo22, url: "http://amzn.com/0871563800") let photo23 = UIImage(named: "overdressed.jpg")! let book23 = BookListItem(text: "Overdressed: The Shockingly High Cost of Cheap Fashion", photo: photo23, url: "http://amzn.com/1591846544") let photo24 = UIImage(named: "toxiccommunities.jpg")! let book24 = BookListItem(text: "Toxic Communities: Environmental Racism, Industrial Pollution, and Residential Mobility", photo: photo24, url: "http://amzn.com/1479861782") let photo25 = UIImage(named: "somethingnew.jpg")! let book25 = BookListItem(text: "Something New Under the Sun: An Environmental History of the World in the 20th Century (Global Century Series)", photo: photo25, url: "http://amzn.com/0140295097") let photo26 = UIImage(named: "zerowastehome.jpg")! let book26 = BookListItem(text: "Zero Waste Home: The Ultimate Guide to Simplifying Your Life by Reducing Your Waste", photo: photo26, url: "http://amzn.com/1451697686") let photo27 = UIImage(named: "wearnoevil.jpg")! let book27 = BookListItem(text: "Wear No Evil: How to Change the World with Your Wardrobe", photo: photo27, url: "http://amzn.com/0762451270") let photo28 = UIImage(named: "merchants.jpg")! let book28 = BookListItem(text: "Merchants of Doubt: How a Handful of Scientists Obscured the Truth on Issues from Tobacco Smoke to Global Warming", photo: photo28, url: "http://amzn.com/1608193942") let photo29 = UIImage(named: "enforcement.jpg")! let book29 = BookListItem(text: "Enforcement at the EPA: High Stakes and Hard Choices, Revised Edition", photo: photo29, url: "http://amzn.com/0292754418") bookList += [book1, book2, book3, book4, book5, book6, book7, book8, book9, book10, book11, book12, book13, book14, book15, book16, book17, book18, book19, book20, book21, book22, book23, book24, book25, book26, book27, book28, book29] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return bookList.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "BookListItemTableViewCell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! BookListTableViewCell let book = bookList[indexPath.row] cell.bookLabel.text = book.text cell.bookCover.image = book.photo return cell } override func tableView(tableview: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let book = bookList[indexPath.row] let siteUrl = book.url UIApplication.sharedApplication().openURL(NSURL(string: siteUrl)!) } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
true
fa0570ff17b355bf993c89ca1dc19359a7a18565
Swift
Gagnant/Socket
/Socket/Extensions+Thread.swift
UTF-8
825
2.8125
3
[ "MIT" ]
permissive
// // Extensions+Thread.swift // Socket // // Created by Andrew Visotskyy on 1/30/17. // Copyright © 2017 Andrew Visotskyy. All rights reserved. // import Foundation @objc private class Context: NSObject { private let block: () -> Void fileprivate init(with block: @escaping () -> Swift.Void) { self.block = block } @objc fileprivate func invoke() { self.block() } } extension Thread { @available(iOS 2.0, *) internal convenience init(with block: @escaping () -> Swift.Void) { let context = Context(with: block) self.init(target: context, selector: #selector(Context.invoke), object: nil) } @available(iOS 2.0, *) internal func perform(_ block: @escaping () -> Swift.Void) { let context = Context(with: block) context.perform(#selector(Context.invoke), on: self, with: nil, waitUntilDone: false) } }
true
7403437c804456e9cd04c10aa469b1e5952cb353
Swift
sanarroya/mail-app
/MailApp/Common/Extensions/ErrorNotificationProtocol.swift
UTF-8
1,204
2.8125
3
[]
no_license
// // ErrorNotificationProtocol.swift // MailApp // // Created by Santiago Avila Arroyave on 2/24/19. // Copyright © 2019 Santiago Avila Arroyave. All rights reserved. // import UIKit import SwiftEntryKit protocol NotificationProtocol { func showError(withMessage message: String, imageName: String?) } extension NotificationProtocol where Self: UIViewController { func showError(withMessage message: String, imageName: String? = nil) { let title = EKProperty.LabelContent(text: "Error.Title".localized(context: self), style: .init(font: .boldSystemFont(ofSize: 16), color: .white)) let description = EKProperty.LabelContent(text: message, style: .init(font: .systemFont(ofSize: 14), color: .white)) var image: EKProperty.ImageContent? if let imageName = imageName { image = .init(image: UIImage(named: imageName)!, size: CGSize(width: 35, height: 35)) } let simpleMessage = EKSimpleMessage(image: image, title: title, description: description) let notificationMessage = EKNotificationMessage(simpleMessage: simpleMessage) let contentView = EKNotificationMessageView(with: notificationMessage) SwiftEntryKit.display(entry: contentView, using: Notification.attributes) } }
true
18c2e08e1bc4f81d2861da7994ab8e67ad7ca4c1
Swift
Z-Natalya/rs.ios.stage-task6
/Swift_Task6/ios.stage-task/Exercises/Exercise-1/CoronaClass.swift
UTF-8
1,240
3.515625
4
[]
no_license
import Foundation class CoronaClass { var seats = [Int]() var n: Int init(n: Int) { if n > 500 { self.n = 500} else if n < 1 { self.n = 1 } else { self.n = n } } func seat() -> Int { var numberOfTable = 0 let lastNumber = n - 1 if seats.isEmpty { seats.append(0) } else { var temp = 0 switch seats.count { case _ where seats.last != lastNumber : if (lastNumber - seats.last!) > temp { numberOfTable = lastNumber seats.append(lastNumber) } default: for i in 0 ..< seats.count-1 { if ((seats[i+1] - seats[i]) / 2) > temp { temp = (seats[i+1] - seats[i]) / 2 numberOfTable = (seats[i] + temp) } } seats.append(numberOfTable) seats = seats.sorted() } } return numberOfTable } func leave(_ p: Int) { if let index = seats.firstIndex(of: p ) { seats.remove(at: index) } } }
true
109be77635af038402dbf8879f047637c4004101
Swift
malashM/TestTaskPecode
/NewsClient/NewsClient/Extensions/UIKit/UIViewController/UIViewController+Alert.swift
UTF-8
407
2.734375
3
[]
no_license
// // AlertManager.swift // NewsClient // // Created by Admin on 16.09.21. // import UIKit extension UIViewController { func showAlert(_ message: String) { let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert) let action = UIAlertAction(title: "Continue", style: .cancel) alert.addAction(action) present(alert, animated: true) } }
true
08b2969be3ebaf711e4b08cd68db7ed137e8d5e8
Swift
alexrsn/iOS-Hackeru
/MyFirstPlayground.playground/Contents.swift
UTF-8
433
3.046875
3
[]
no_license
//Hello import Cocoa; var x:String; x = "hello"; let s1:String = "Hello"; //s1 = "World"; this is an error because constants cannot be changed. var s2:String = "Hello World"; s2 = "Hallo Welt"; s2 = "Hola Mundo"; s2 = "Shalom Olam"; //String, Int, Float, Double, Bool let s: String = "Hi"; let i: Int = -25; let f: Float = 3.14; let d: Double = 99.99; let b: Bool = true;
true
4f603575fd8919b85d997dca3ce5ce3fdc716ea2
Swift
KeyTalk/ios-client
/KeyTalk/Connection/ServerDefines.swift
UTF-8
2,761
2.828125
3
[]
no_license
// // ServerDefines.swift // KeyTalk // // Created by Paurush on 5/17/18. // Copyright © 2018 Paurush. All rights reserved. // import Foundation import UIKit public enum URLs: Int { case hello case handshake case authReq case authentication case certificate } public enum AuthResult: String { case ok = "OK" case delayed = "DELAY" case locked = "LOCKED" case expired = "EXPIRED" case challenge = "CHALLENGE" } //https://192.168.129.122 var serverUrl = "" var dataCert = Data() let rcdpProtocol = "/rcdp/2.2.0" let HELLO_URL = "/hello" let HANDSHAKE_URL = "/handshake" let AUTH_REQUIREMENTS_URL = "/auth-requirements" let AUTHENTICATION_URL = "/authentication" let CERTIFICATE_URL = "/cert?format=P12&include-chain=True&out-of-band=True"//PEM&include-chain=True" let HTTP_METHOD_POST = "POST" let DELAY = "DELAY" let LOCKED = "LOCKED" let EXPIRED = "EXPIRED" class Server { class func getUrl(type: URLs) -> URL { var urlStr = "" switch type { case .hello: urlStr = serverUrl + rcdpProtocol + HELLO_URL break case .handshake: urlStr = serverUrl + rcdpProtocol + HANDSHAKE_URL + "?caller-utc=\(getISO8601DateFormat())" break case .authReq: urlStr = serverUrl + rcdpProtocol + AUTH_REQUIREMENTS_URL+"?service=\(serviceName)" break case .authentication: urlStr = serverUrl + rcdpProtocol + AUTHENTICATION_URL + authentication() break case .certificate: urlStr = serverUrl + rcdpProtocol + CERTIFICATE_URL break default: print("Encounter unidentified url type") } return URL.init(string: urlStr)! } class func authentication() -> String { let encodedHwsig = Utilities.sha256(securityString: HWSIGCalc.calcHwSignature()) let hwsig = "CS-" + encodedHwsig let tempStr = "?service=\(serviceName)&caller-hw-description=\(UIDevice.current.modelName() + "," + UIDevice.current.name)&USERID=\(username)&PASSWD=\(password)&HWSIG=\(hwsig.uppercased())" let urlStr = tempStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! return urlStr } class private func getISO8601DateFormat() -> String { let dateFormatter = DateFormatter() let timeZone = TimeZone.init(identifier: "GMT") dateFormatter.timeZone = timeZone dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSS'Z'" let iso8601String = dateFormatter.string(from: Date()) print("FormatISO8601String::\(iso8601String)") return iso8601String.replacingOccurrences(of: ":", with: "%3A") } }
true
d288ea5a6f5b424f63a4e0a7943024e6b6737013
Swift
gwair1989/Test-Lottie
/Test Lottie/OrderWallHeader+Intructions.swift
UTF-8
2,811
2.546875
3
[]
no_license
// // OrderWallHeader+Intructions.swift // Test Lottie // // Created by Aleksandr Khalupa on 30.08.2021. // import Foundation import UIKit protocol LearnMoreDelegate: AnyObject { func didLearnMorePressed() } extension OrderWallHeaderVC { class Instructions: UIView { weak var delegate: LearnMoreDelegate? private let titleLabel = UILabel(.color(UIColor.black), .font(.sfPro(.display, 32, .bold)), .numberOfLines(0), .huggPrio(.required, .vertical), .compResiPrio(.defaultLow, .horizontal), .lineBreakMode(.byWordWrapping), .text("")) private let imageView = UIImageView(.contentMode(.scaleAspectFit), .image("reorder_hero_image")) private let learnMoreButton = UIButton(.font(.sfPro(.text, 14, .regular)),.titleColor(.link, .normal),.backgroundColor(UIColor.clear),.localized("order_orderwall_banner_button", .normal)) override init(frame: CGRect) { super.init(frame: frame) addSubView() addConstrains() learnMoreButton.addTarget(self, action: #selector(learnMorePressed), for: .touchUpInside) learnMoreButton.setTitle("title of button", for: .normal) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func learnMorePressed() { delegate?.didLearnMorePressed() } func addSubView() { addSubview(imageView) addSubview(titleLabel) addSubview(learnMoreButton) } func addConstrains() { imageView.translatesAutoresizingMaskIntoConstraints = false titleLabel.translatesAutoresizingMaskIntoConstraints = false learnMoreButton.translatesAutoresizingMaskIntoConstraints = false imageView.handleInsets([.top(0), .trailing(0), .width(140), .height(140)], superView: self, priority: .required) titleLabel.handleInsets([.top(24), .leading(24), .constraint(titleLabel.trailingAnchor.constraint(equalTo: imageView.leadingAnchor))], superView: self, priority: .required) learnMoreButton.setContentCompressionResistancePriority(.required, for: .vertical) learnMoreButton.handleInsets([ .constraint(learnMoreButton.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 0)), .leading(24), .bottom(-28), .height(36), ], superView: self, priority: .required) } } }
true
d7fe231149273ec917548078b57f2eeb7e9dc58d
Swift
Gagan5278/ParallaxEffect
/ParallaxEffect_Complete/ParallaxEffect/Controller/InterpolationParallaxEffect/InterpolationViewController.swift
UTF-8
4,028
3.078125
3
[]
no_license
// // InterpolationViewController.swift // ParallaxEffect // // Created by Vishal Mishra, Gagan on 14/10/15. // Copyright (c) 2015 Vishal Mishra, Gagan. All rights reserved. // import UIKit let cellIdentifierInterpolation = "CellIdentifierInterpolation" class InterpolationViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { //TableView object for showing images on cell @IBOutlet weak var customTableView: UITableView! //Arry to hold images with name var arrayOfContents : [String] = Array () //Dictionary to detect which cell has motion effect applied var dictionaryOfAddedMotionEffect = Dictionary<String, String>() //MARK:- View Life Cycle override func viewDidLoad() { super.viewDidLoad() self.title = "Motiion Effect" //run loop & Add images name from image assets to array for var i=1 ; i<=12 ; i++ { self.arrayOfContents.append("img\(i)") } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //MARK:- Add motion effect on table cell func interPolationMotionEffectAtCell (MyCell cell : CustomTableViewCell , image : UIImage) { var min = -image.size.height var max = image.size.height max = max - cell.frame.size.height min = min + cell.frame.size.height if max > 0 && min != 0 { let verticalEffect = InterpollationMotionEffect(keyPath: "center.y", type: .TiltAlongVerticalAxis, minimumRelativeValue: min, maximumRelativeValue: max) cell.celImageView.addMotionEffect(verticalEffect) } min = -image.size.width max = image.size.width max = max - cell.frame.size.width min = min + cell.frame.size.width if max > 0 && min != 0 { let horizontalEffect = InterpollationMotionEffect(keyPath: "center.x", type: .TiltAlongHorizontalAxis, minimumRelativeValue: min, maximumRelativeValue: max) cell.celImageView.addMotionEffect(horizontalEffect) } } // MARK:- TableView Delegate & Datasource func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.arrayOfContents.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifierInterpolation, forIndexPath: indexPath) as! CustomTableViewCell let imgName = self.arrayOfContents[indexPath.row] as String cell.celImageView?.image = UIImage(named:imgName) cell.clipsToBounds=true cell.titleLabel?.text = imgName return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) cell?.selected = false } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { let cCell = cell as! CustomTableViewCell let imgName = self.arrayOfContents[indexPath.row] as String let cellIndex = ("\(indexPath.row)") if let arrayOfEffects = cCell.celImageView?.motionEffects { self.dictionaryOfAddedMotionEffect[cellIndex] = nil for motionEffects in arrayOfEffects { cCell.celImageView .removeMotionEffect(motionEffects ) } } if self.dictionaryOfAddedMotionEffect[cellIndex] == nil { interPolationMotionEffectAtCell(MyCell: cCell, image: UIImage(named:imgName)!) self.dictionaryOfAddedMotionEffect[cellIndex] = cellIndex } } }
true
7bcf07369c97edfc3a83e705988f7da24246390d
Swift
river2202/DescriptiveCoordinator
/DescriptiveCoordinator/DateSelectViewController.swift
UTF-8
778
2.9375
3
[]
no_license
import UIKit class DateSelectViewController: UIViewController { enum Action { case back case selectDate(Date) } var actionHandler: ActionHandler<Action>? static func instanciate(date: Date, actionHandler: ActionHandler<Action>? = nil) -> DateSelectViewController { let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DateSelectViewController") as! DateSelectViewController vc.actionHandler = actionHandler vc.date = date return vc } var date: Date! override func viewDidLoad() { super.viewDidLoad() } @IBAction func dateSelected(_ sender: Any) { actionHandler?(.selectDate(Date())) } @IBAction func onBackTapped(_ sender: Any) { actionHandler?(.back) } }
true
a52e34a88e677150849d19bc29d6f7b6129a2392
Swift
gragerdsouza/vettrivaanoli
/Vettri Vaanoli/AppDelegate.swift
UTF-8
4,869
2.6875
3
[]
no_license
// // AppDelegate.swift // Vettri Vaanoli // // Created by Grager D'souza on 27/06/2020. // Copyright © 2020 Grager D'souza. All rights reserved. // import UIKit import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. //splash screen delay fro few seconds Thread.sleep(forTimeInterval: 3.0) //Call function registerForPushNotifications to register for push notification registerForPushNotifications() // set the delegate in didFinishLaunchingWithOptions UNUserNotificationCenter.current().delegate = self return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } // Register for Push Notifications func registerForPushNotifications() { UNUserNotificationCenter.current() // 1 .requestAuthorization(options: [.alert, .sound, .badge]) { // 2 [weak self] granted, error in print("Permission granted: \(granted)") // 3 guard granted else { return } self?.getNotificationSettings() } } func getNotificationSettings() { UNUserNotificationCenter.current().getNotificationSettings { settings in print("Notification settings: \(settings)") guard settings.authorizationStatus == .authorized else { return } DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } } //get device token here func application( _ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data ) { let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) } let token = tokenParts.joined() print("Device Token: \(token)") //send tokens to backend server } // func application(_ application: UIApplication, // didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { // let tokenParts = deviceToken.map { data -> String in // return String(format: "%02.2hhx", data) // } // // let token = tokenParts.joined() // print("Device Token: \(token)") // } func application( _ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Failed to register: \(error)") } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { //Your code to handle events //print(notification.request.content.userInfo) print("Handle push from foreground") // custom code to handle push while app is in the foreground print("\(notification.request.content.userInfo)") completionHandler([.alert, .badge, .sound]) } //get Notification Here below ios 10 func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) { // Print notification payload data print("Push notification received: \(data)") } @available(iOS 10.0, *) private func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) { //Handle the notification completionHandler( [UNNotificationPresentationOptions.alert, UNNotificationPresentationOptions.sound, UNNotificationPresentationOptions.badge]) } }
true
5b07b02d643392d2f4327c1c00de8360bd7a9434
Swift
gordonseto/Eightam
/eightam/Post.swift
UTF-8
4,046
2.625
3
[]
no_license
// // Post.swift // eightam // // Created by Gordon Seto on 2016-08-24. // Copyright © 2016 gordonseto. All rights reserved. // import Foundation import FirebaseDatabase class Post { private var _key: String! private var _authorUid: String! private var _threadKey: String! private var _text: String! private var _time: NSTimeInterval! private var _points: Int! private var _upVotes: [String: Bool]! private var _downVotes: [String: Bool]! var key: String! { return _key } var authorUid: String! { return _authorUid } var threadKey: String! { return _threadKey } var text: String! { return _text } var time: NSTimeInterval! { return _time } var points: Int! { return _upVotes.count - _downVotes.count } var upVotes: [String: Bool]! { get {return _upVotes} set { _upVotes = newValue} } var downVotes: [String: Bool]! { get {return _downVotes} set {_downVotes = newValue} } var numVoters: Int! { return _upVotes.count + _downVotes.count } var notificationMilestone: Int = 0 var firebase: FIRDatabaseReference! init(key: String) { _key = key } init(uid: String, threadKey: String, text: String){ _authorUid = uid _threadKey = threadKey _text = text _time = NSDate().timeIntervalSince1970 upVotes = [:] downVotes = [:] } init(key: String, uid: String, threadKey: String, text: String, upVotes: [String:Bool], downVotes: [String:Bool], time: NSTimeInterval){ _key = key _authorUid = uid _threadKey = threadKey _text = text _upVotes = upVotes _downVotes = downVotes _time = time notificationMilestone = numVoters } func findUserVoteStatus(uid: String) -> VoteStatus { guard let upVotes = _upVotes else { return VoteStatus.NoVote } guard let downVotes = _downVotes else { return VoteStatus.NoVote } if upVotes[uid] != nil { return VoteStatus.UpVote } else if downVotes[uid] != nil { return VoteStatus.DownVote } else { return VoteStatus.NoVote } } func post(threadId: String, completion: (Post) -> ()) { guard let authorUid = _authorUid else { return } guard let threadKey = _threadKey else { return } guard let text = text else { return } guard let time = _time else { return } let post = ["authorUid": authorUid, "threadKey": threadKey, "text": text, "time": time] firebase = FIRDatabase.database().reference() _key = firebase.child("threads").child(threadId).child("replies").childByAutoId().key firebase.child("replies").child(_key).setValue(post) firebase.child("replyInfos").child(authorUid).child(_key).setValue(time) firebase.child("threads").child(threadId).child("replies").child(_key).setValue(true) completion(self) } func downloadPost(completion: (Post) ->()){ guard let key = _key else { return } firebase = FIRDatabase.database().reference() firebase.child("replies").child(_key).observeSingleEventOfType(.Value, withBlock: {snapshot in self._authorUid = snapshot.value!["authorUid"] as? String ?? "" self._threadKey = snapshot.value!["threadKey"] as? String ?? "" self._text = snapshot.value!["text"] as? String ?? "" self._time = snapshot.value!["time"] as? NSTimeInterval ?? NSDate().timeIntervalSince1970 self._upVotes = snapshot.value!["upVotes"] as? [String: Bool] ?? [:] self._downVotes = snapshot.value!["downVotes"] as? [String: Bool] ?? [:] print("downloaded \(self.text)") completion(self) }) } }
true
e24aff32c056e0438127121f358eb9be0761164e
Swift
aminfaruq/gameCatalogue-ios
/Game Catalogue/GameNetwork/DAO/DetailGame/DAODetailGameMetacriticPlatforms.swift
UTF-8
2,370
3.09375
3
[]
no_license
// // DAODetailGameMetacriticPlatforms.swift // // Created by Amin faruq on 10/07/20 // Copyright (c) . All rights reserved. // import Foundation import SwiftyJSON public final class DAODetailGameMetacriticPlatforms: NSCoding { // MARK: Declaration for string constants to be used to decode and also serialize. private struct SerializationKeys { static let metascore = "metascore" static let platform = "platform" static let url = "url" } // MARK: Properties public var metascore: Int? public var platform: DAODetailGamePlatform? public var url: String? // MARK: SwiftyJSON Initializers /// Initiates the instance based on the object. /// /// - parameter object: The object of either Dictionary or Array kind that was passed. /// - returns: An initialized instance of the class. public convenience init(object: Any) { self.init(json: JSON(object)) } /// Initiates the instance based on the JSON that was passed. /// /// - parameter json: JSON object from SwiftyJSON. public required init(json: JSON) { metascore = json[SerializationKeys.metascore].int platform = DAODetailGamePlatform(json: json[SerializationKeys.platform]) url = json[SerializationKeys.url].string } /// Generates description of the object in the form of a NSDictionary. /// /// - returns: A Key value pair containing all valid values in the object. public func dictionaryRepresentation() -> [String: Any] { var dictionary: [String: Any] = [:] if let value = metascore { dictionary[SerializationKeys.metascore] = value } if let value = platform { dictionary[SerializationKeys.platform] = value.dictionaryRepresentation() } if let value = url { dictionary[SerializationKeys.url] = value } return dictionary } // MARK: NSCoding Protocol required public init(coder aDecoder: NSCoder) { self.metascore = aDecoder.decodeObject(forKey: SerializationKeys.metascore) as? Int self.platform = aDecoder.decodeObject(forKey: SerializationKeys.platform) as? DAODetailGamePlatform self.url = aDecoder.decodeObject(forKey: SerializationKeys.url) as? String } public func encode(with aCoder: NSCoder) { aCoder.encode(metascore, forKey: SerializationKeys.metascore) aCoder.encode(platform, forKey: SerializationKeys.platform) aCoder.encode(url, forKey: SerializationKeys.url) } }
true
83fa82deff2599a0810a575223c6e5a957c9e010
Swift
a120256/TalkingApp
/Contents.swift
UTF-8
380
2.515625
3
[]
no_license
//speak import AVFoundation let speech = AVSpeechUtterance(string: "這是第一個用程式碼寫出來的ios app,雖然不是作業,不過既然都做了,就想要擺上來~開心!!!") speech.voice = AVSpeechSynthesisVoice(language: "zh-TW") speech.pitchMultiplier = 1.3 speech.rate = 0.2 let talk = AVSpeechSynthesizer() talk.speak(speech)//講話的method
true
1a4176721458b065f5deefeb720bb20941de2f90
Swift
EyadZaid/MinesweeperGame-IOS
/Minesweeper/CollectionViewCell.swift
UTF-8
1,472
2.84375
3
[]
no_license
// // CollectionViewCell.swift // Minesweeper // // Created by Eyad on 4/1/19. // Copyright © 2019 Afeka. All rights reserved. // import UIKit class CollectionViewCell: UICollectionViewCell { @IBOutlet weak var imageViewCell: UIImageView! @IBOutlet weak var labelCell: UILabel! func updateItemInCollectionView(item: ItemInCollectionView) -> Void { let itemState = item.GetItemCurrentState() let itemNumber = item.GetItemCurrentValue() if(itemState == ItemInCollectionView.itemState.MINES){ imageViewCell.image = #imageLiteral(resourceName: "mine_image") labelCell.text = "" labelCell.textAlignment = .center; } else if(itemState == ItemInCollectionView.itemState.FLAG){ imageViewCell.image = #imageLiteral(resourceName: "flag_image") labelCell.text = "" labelCell.textAlignment = .center; } else if(itemState == ItemInCollectionView.itemState.NUMBER && itemNumber > 0){ labelCell.text = "\(itemNumber)" labelCell.textAlignment = .center; labelCell.textColor = (ItemInCollectionView.itemColor.NUMBER).color() } else{ labelCell.text = "" labelCell.textAlignment = .center; labelCell.textColor = (ItemInCollectionView.itemColor.SPACE).color() } } }
true
af72969d8cb11488607691cc2b9b7fb9ca4cf25c
Swift
seymotom/AC3.2
/lessons/structs-and-classes/exercises/structsClassesExercises/structsClassesExercises/President.swift
UTF-8
366
2.90625
3
[]
no_license
// // President.swift // structsClassesExercises // // Created by Tom Seymour on 06/09/2016. // Copyright © 2016 Tom Seymour. All rights reserved. // import Foundation class President: Person { var yearEnteredOffice = 0 var yearLeftOffice = 0 func inOffice(year: Int) -> Bool { return year >= yearEnteredOffice && year <= yearLeftOffice } }
true
511db844ba71f898f2f67b18b8d20fd487be1966
Swift
Choi-MinKyu/CodeSamples
/RXImageDown/RXImageDown/ViewController.swift
UTF-8
1,945
2.625
3
[]
no_license
// // ViewController.swift // RXImageDown // // Created by CHOI MIN KYU on 04/03/2019. // Copyright © 2019 RX Samples. All rights reserved. // import UIKit import RxSwift import RxCocoa import Alamofire final class ViewController: UIViewController { @IBOutlet weak var urlTextField: UITextField! @IBOutlet weak var goButton: UIButton! @IBOutlet weak var imageView: UIImageView! let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. bind() } } extension ViewController { func bind() { goButton.rx.tap.withLatestFrom(self.urlTextField.rx.text.orEmpty) .map { text -> URL in return try text.asURL() } .filter { (url: URL) -> Bool in let imageExtension = ["jpg", "jpeg", "gif", "png"] return imageExtension.contains(url.pathExtension) }.flatMap { (url: URL) -> Observable<String> in return Observable<String>.create({ anyObserver -> Disposable in let destination: DownloadRequest.DownloadFileDestination = { _, _ in let directoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let file = directoryURL.appendingPathComponent(url.relativeString, isDirectory: false) return (file, [.createIntermediateDirectories, .removePreviousFile]) } let download = Alamofire.download(url, to: destination) .response { (response: DefaultDownloadResponse) in if let data = response.destinationURL { anyObserver.onNext(data.path) anyObserver.onCompleted() } else { anyObserver.onError(RxError.unknown) } } return Disposables.create { download.cancel() } }) }.map { (data: String) -> UIImage in guard let image = UIImage(contentsOfFile: data) else { throw RxError.noElements } return image }.bind(to: imageView.rx.image) .disposed(by: disposeBag) } }
true
dd7e4c246ad439b4d97445bf2c8f2804f925cedd
Swift
EdouardPlantevin/Reciplease
/RecipleaseTests/RecipeServiceNetworkCallTestCase.swift
UTF-8
5,578
2.578125
3
[]
no_license
// // RecipeAlamofire.swift // RecipleaseTests // // Created by Edouard PLANTEVIN on 10/03/2020. // Copyright © 2020 Edouard PLANTEVIN. All rights reserved. // import Foundation import XCTest import Alamofire @testable import Reciplease class RecipeServiceTests: XCTestCase { // MARK: - Properties var ingredientsList: [String]! // MARK: - Tests Life Cycle override func setUp() { super.setUp() ingredientsList = ["Lemon", "Chicken"] } // MARK: - Tests func testGetRecipesShouldPostFailedCallback() { let fakeResponse = FakeResponse(response: nil, data: nil, error: FakeResponseData.networkError) let recipeSessionFake = RecipeSessionFake(fakeResponse: fakeResponse) let recipeService = RecipeService(recipeSession: recipeSessionFake) let expectation = XCTestExpectation(description: "Wait for queue change.") recipeService.getRecipe { (success) in XCTAssertFalse(success) expectation.fulfill() } wait(for: [expectation], timeout: 0.01) } func testGetRecipesShouldPostFailedCallbackIfNoData() { let fakeResponse = FakeResponse(response: nil, data: FakeResponseData.incorrectData, error: nil) let recipeSessionFake = RecipeSessionFake(fakeResponse: fakeResponse) let recipeService = RecipeService(recipeSession: recipeSessionFake) let expectation = XCTestExpectation(description: "Wait for queue change.") recipeService.getRecipe { (success) in XCTAssertFalse(success) expectation.fulfill() } wait(for: [expectation], timeout: 0.01) } func testGetRecipesShouldPostFailedCallbackIfIncorrectResponse() { let fakeResponse = FakeResponse(response: FakeResponseData.responseKO, data: FakeResponseData.correctData, error: nil) let recipeSessionFake = RecipeSessionFake(fakeResponse: fakeResponse) let recipeService = RecipeService(recipeSession: recipeSessionFake) let expectation = XCTestExpectation(description: "Wait for queue change.") recipeService.getRecipe { (success) in XCTAssertFalse(success) expectation.fulfill() } wait(for: [expectation], timeout: 0.01) } func testGetRecipesShouldPostFailedCallbackIfResponseCorrectAndDataNil() { let fakeResponse = FakeResponse(response: FakeResponseData.responseOK, data: nil, error: nil) let recipeSessionFake = RecipeSessionFake(fakeResponse: fakeResponse) let recipeService = RecipeService(recipeSession: recipeSessionFake) let expectation = XCTestExpectation(description: "Wait for queue change.") recipeService.getRecipe { (success) in XCTAssertFalse(success) expectation.fulfill() } wait(for: [expectation], timeout: 0.01) } func testGetRecipesShouldPostFailedCallbackIfIncorrectData() { let fakeResponse = FakeResponse(response: FakeResponseData.responseOK, data: FakeResponseData.incorrectData, error: nil) let recipeSessionFake = RecipeSessionFake(fakeResponse: fakeResponse) let recipeService = RecipeService(recipeSession: recipeSessionFake) let expectation = XCTestExpectation(description: "Wait for queue change.") recipeService.getRecipe { (success) in XCTAssertFalse(success) expectation.fulfill() } wait(for: [expectation], timeout: 0.01) } func testGetRecipeShouldPostSuccessCallbackIfNoErrorAndCorrectData() { let fakeResponse = FakeResponse(response: FakeResponseData.responseOK, data: FakeResponseData.correctData, error: nil) let recipeSessionFake = RecipeSessionFake(fakeResponse: fakeResponse) let recipeService = RecipeService(recipeSession: recipeSessionFake) let expectation = XCTestExpectation(description: "Wait for queue change.") recipeService.getRecipe { (success) in XCTAssertTrue(success) let name = recipeService.recipes?[0].name let image = recipeService.recipes?[0].image XCTAssertEqual(name, "Chicken Vesuvio") XCTAssertEqual(image, "https://www.edamam.com/web-img/e42/e42f9119813e890af34c259785ae1cfb.jpg") expectation.fulfill() } wait(for: [expectation], timeout: 0.01) } func testGetRecipeShouldPostSuccessCallbackIfNoErrorAndCorrectDataAndCorrectItem() { let fakeResponse = FakeResponse(response: FakeResponseData.responseOK, data: FakeResponseData.correctData, error: nil) let recipeSessionFake = RecipeSessionFake(fakeResponse: fakeResponse) let recipeService = RecipeService(recipeSession: recipeSessionFake) let ingredient = ItemDataModel(context: AppDelegate.viewContext) ingredient.name = "Chicken" try? AppDelegate.viewContext.save() let expectation = XCTestExpectation(description: "Wait for queue change.") recipeService.getRecipe { (success) in XCTAssertTrue(success) let name = recipeService.recipes?[0].name let image = recipeService.recipes?[0].image XCTAssertEqual(name, "Chicken Vesuvio") XCTAssertEqual(image, "https://www.edamam.com/web-img/e42/e42f9119813e890af34c259785ae1cfb.jpg") ItemDataModel.deleteAll() expectation.fulfill() } wait(for: [expectation], timeout: 0.01) } }
true
f2984ba92284b8c7d375a65393c161e7acc66bf0
Swift
hisaac/HIGColors
/HIGColorsTests/HIGColorsTests.swift
UTF-8
2,659
2.71875
3
[ "MIT" ]
permissive
// Created by Isaac Halvorson on 8/20/18 import HIGColors import XCTest // If on iOS, tvOS, or watchOS, import UIKit and set the `Color` typealias to UIColor #if canImport(UIKit) public typealias Color = UIColor // If on macOS, import UIKit and set the `Color` typealias to NSColor #elseif canImport(AppKit) public typealias Color = NSColor #endif class HIGColorTests: XCTestCase { let higRed = Color(red: 255, green: 59, blue: 48) let higOrange = Color(red: 255, green: 149, blue: 0) let higYellow = Color(red: 255, green: 204, blue: 0) let higGreen = Color(red: 76, green: 217, blue: 100) let higTealBlue = Color(red: 90, green: 200, blue: 250) let higBlue = Color(red: 0, green: 122, blue: 255) let higPurple = Color(red: 88, green: 86, blue: 214) let higPink = Color(red: 255, green: 45, blue: 85) func testColorValues() { XCTAssert(HIGColors.red.rawValue == higRed) XCTAssert(HIGColors.orange.rawValue == higOrange) XCTAssert(HIGColors.yellow.rawValue == higYellow) XCTAssert(HIGColors.green.rawValue == higGreen) XCTAssert(HIGColors.tealBlue.rawValue == higTealBlue) XCTAssert(HIGColors.blue.rawValue == higBlue) XCTAssert(HIGColors.purple.rawValue == higPurple) XCTAssert(HIGColors.pink.rawValue == higPink) } func testColorInitialization() { XCTAssert(HIGColors(rawValue: higRed) == HIGColors.red) XCTAssert(HIGColors(rawValue: higOrange) == HIGColors.orange) XCTAssert(HIGColors(rawValue: higYellow) == HIGColors.yellow) XCTAssert(HIGColors(rawValue: higGreen) == HIGColors.green) XCTAssert(HIGColors(rawValue: higTealBlue) == HIGColors.tealBlue) XCTAssert(HIGColors(rawValue: higBlue) == HIGColors.blue) XCTAssert(HIGColors(rawValue: higPurple) == HIGColors.purple) XCTAssert(HIGColors(rawValue: higPink) == HIGColors.pink) XCTAssertNil(HIGColors(rawValue: Color.clear)) } func testUIColorExtension() { XCTAssert(Color.higRed == higRed) XCTAssert(Color.higOrange == higOrange) XCTAssert(Color.higYellow == higYellow) XCTAssert(Color.higGreen == higGreen) XCTAssert(Color.higTealBlue == higTealBlue) XCTAssert(Color.higBlue == higBlue) XCTAssert(Color.higPurple == higPurple) XCTAssert(Color.higPink == higPink) } func testCGColorExtension() { XCTAssert(CGColor.higRed == higRed.cgColor) XCTAssert(CGColor.higOrange == higOrange.cgColor) XCTAssert(CGColor.higYellow == higYellow.cgColor) XCTAssert(CGColor.higGreen == higGreen.cgColor) XCTAssert(CGColor.higTealBlue == higTealBlue.cgColor) XCTAssert(CGColor.higBlue == higBlue.cgColor) XCTAssert(CGColor.higPurple == higPurple.cgColor) XCTAssert(CGColor.higPink == higPink.cgColor) } }
true
f9d6f6c0391f515441b4835709af526c136a5ed5
Swift
bosstone80123/Means-Testing
/Means Testing/ViewController.swift
UTF-8
3,573
2.59375
3
[]
no_license
// // ViewController.swift // Means Testing // // Created by Jon Slaughter on 12/25/15. // Copyright © 2015 Jon Slaughter. All rights reserved. // import UIKit class ViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate { @IBOutlet var StatePicker: UIPickerView! = UIPickerView() @IBOutlet var StateTextBox: UITextField! = UITextField() @IBOutlet var MaritalStatusPicker: UIPickerView! = UIPickerView() @IBOutlet var MaritalStatusTextBox: UITextField! = UITextField() @IBOutlet var HouseholdSizeTextBox: UITextField! @IBOutlet var HouseHoldSize: UIStepper! @IBAction func HouseholdSizeStepper(sender: UIStepper) { HouseholdSizeTextBox.text = Int(sender.value).description } var StatePickerData = ["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware", "District of Columbia","Florida","Georgia","Guam","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky", "Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska", "Nevada","New Hampshire","New Jersey","New Mexico","New York","North Carolina","North Dakota","Northern Mariana Islands", "Ohio","Oklahoma","Oregon","Pennsylvania","Puerto Rico","Rhode Island","South Carolina","South Dakota","Tennessee", "Texas","Utah","Vermont","Virginia","Virgin Islands","Washington","West Virginia","Wisconsin","Wyoming"] var MaritalStatusData = ["Individual","Individual Married","Joint"] override func viewDidLoad() { super.viewDidLoad() StatePicker.hidden=true StatePicker.delegate = self MaritalStatusPicker.hidden=true MaritalStatusPicker.delegate=self HouseholdSizeTextBox.text = Int(HouseHoldSize.value).description // Do any additional setup after loading the view, typically from a nib. } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if pickerView == StatePicker{ return StatePickerData.count } else if pickerView == MaritalStatusPicker{ return MaritalStatusData.count } return 1 } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if pickerView == StatePicker{ return StatePickerData[row] } else if pickerView == MaritalStatusPicker{ return MaritalStatusData[row] } return "" } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if pickerView == StatePicker{ StateTextBox.text = StatePickerData[row] StatePicker.hidden = true } else if pickerView == MaritalStatusPicker{ MaritalStatusTextBox.text = MaritalStatusData[row] MaritalStatusPicker.hidden = true } } func textFieldShouldBeginEditing(textField: UITextField) -> Bool{ if textField.tag == 1{ StatePicker.hidden = false } else if textField.tag == 3{ MaritalStatusPicker.hidden = false } return false } // I'm not sure what this is for generated code. override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
true
9df7ae322b515dd6970e3ca000632bf5dae2b0c7
Swift
bluewhiteio/Presentations
/GameplayKit/Sample Code/Minmax/Sol/PredicatesSetup.swift
UTF-8
2,383
2.90625
3
[]
no_license
// // PredicatesSetup.swift // Sol // // Created by Sash Zats on 10/4/15. // Copyright © 2015 Comyar Zaheri. All rights reserved. // import Foundation private let best = 50 private let good = 25 private let notBad = -25 private let worst = -50 class PredicatesSetup: NSObject { static let sharedInstance = PredicatesSetup() let engine = SuggestionEngine.sharedInstance func setupPredicates() { // Finish demo engine.register(FinishDemo.self) { states in if states.count >= 25 { return best } return nil } // Preferences engine.register(Preferences.self) { states in if Array(states[0..<states.count-1]).containsType(Preferences.self) { return nil } return states.count > 5 ? good : nil } // Change temperature engine.register(SwitchUnits.self){ states in if Array(states[0..<states.count-1]).containsType(SwitchUnits.self) { return nil } switch states.count { case 0...5: return best default: return good } } // Add a city engine.register(AddCity.self){ states in switch states.filter({ $0 is AddCity }).count { case 0: return best case 1...3: return good + 1 default: return nil } } // Delete a city engine.register(DeleteCity.self){ states in if Array(states[0..<states.count-1]).containsType(DeleteCity.self) { return nil } if states.filter({ $0 is AddCity }).count > 2 && states.last is DeleteCity { return best } return nil } // Switch city engine.register(SwitchCity.self){ states in if Array(states[0..<states.count-1]).containsType(SwitchCity.self) { return nil } // we have at least 2 cities to show if states.filter({ $0 is AddCity }).count - states.filter({ $0 is DeleteCity }).count > 2 { return good + 1 } return nil } } }
true
c89e29f678564fb699839b37e0e02c5a19936bc4
Swift
Jamiek94/Motoren-iOS
/Motoren/UploadImageController.swift
UTF-8
2,445
2.578125
3
[]
no_license
// // UploadImageController.swift // Motoren // // Created by Jamie Knoef on 29/10/2017. // Copyright © 2017 Jamie Knoef. All rights reserved. // import UIKit import FirebaseAuth class UploadImageController: UIViewController, UITextFieldDelegate { public var selectedImage : UIImage! public var uploadedImage : Image? public var uploadService : IUploadService! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var descriptionView: UITextView! @IBOutlet weak var titleTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() hideKeyboardWhenTappedAround() imageView.image = selectedImage descriptionView.createBorder() titleTextField.delegate = self } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return true; } @IBAction func onImageUpload(_ sender: UIBarButtonItem) { let progressHUD = ProgressHUD.init(text : "Uploaden...") progressHUD.show() view.addSubview(progressHUD) uploadService.upload(author : Author.init(user: Auth.auth().currentUser!), title : titleTextField.text, description: descriptionView.text, image: imageView.image) { (image, validationResult, error) in progressHUD.hide() progressHUD.removeFromSuperview() self.uploadedImage = image guard error == nil else { self.showAlert(title : "Foutmelding", message : "Kon de afbeelding niet uploaden. Heb je nog wel internet?") return } guard error == nil && validationResult.isValid else { self.showAlert(title: "Validatie fout", message: validationResult.errorMessages.joined(separator: "\n * ")) return } if error == nil && validationResult.isValid { //navigationController!.setViewControllers(controllerStack, animated: true) self.performSegue(withIdentifier: "ImageDetail", sender: nil) } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let imageDetailController = segue.destination as! ImageDetailController imageDetailController.imageToDisplay = uploadedImage! } }
true
af952759b6695d0d072a572a3825089ef5383266
Swift
Little-Captain/Protocol-Oriented-Programming-with-Swift
/04/TestProject-01/TestProject-01/main.swift
UTF-8
452
2.625
3
[]
no_license
// // main.swift // TestProject-01 // // Created by Liu-Mac on 3/15/18. // Copyright © 2018 Liu-Mac. All rights reserved. // import Foundation testPerson() var intQ2 = GenericQueue<Int>() intQ2.addItem(2) intQ2.addItem(4) if let i = intQ2.getItem() { print(i) } intQ2.addItem(6) var displayDelegate = MyDisplayNameDelegate() var person = Person1(displayNameDelegate: displayDelegate) person.firstName = "Jon" person.lastName = "Hoffman"
true
c77ea154d8555f2318adedd258960ac21769462b
Swift
iamdiegolucero/Ascension
/Ascension/Ascension/Hero.swift
UTF-8
561
2.515625
3
[ "MIT" ]
permissive
// // Hero.swift // Ascension // // Created by Diego Lucero on 7/18/17. // Copyright © 2017 Make School. All rights reserved. // import SpriteKit class Hero: SKSpriteNode { /* You are required to implement this for your subclass to work */ override init(texture: SKTexture?, color: UIColor, size: CGSize) { super.init(texture: texture, color: color, size: size) } /* You are required to implement this for your subclass to work */ required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
true
9b36204c7492e25f32da8e87452de46ddbc32607
Swift
marolsi/Pantri
/Pantri/AddItemVC.swift
UTF-8
5,506
2.5625
3
[]
no_license
// // AddItemVC.swift // Pantri // // Created by Mariah Olson on 3/6/17. // Copyright © 2017 Mariah Olson. All rights reserved. // import UIKit class AddItemVC: UIViewController, UITextFieldDelegate { @IBOutlet weak var nameField: UITextField! @IBOutlet weak var priorityControl: UISegmentedControl! @IBOutlet weak var categoryPicker: UIPickerView! @IBOutlet weak var notesField: UITextField! @IBOutlet weak var currentStockControl: UISegmentedControl! @IBOutlet weak var keepStockedSwitch: UISwitch! @IBOutlet weak var addButton: UIButton! @IBOutlet weak var priorityHeight: NSLayoutConstraint! var inNav = false // PROBABLY WONT USE var picker : CategoryPicker! var itemToEdit : Item? override func viewDidLoad() { super.viewDidLoad() // set text field delegates self.notesField.delegate = self self.nameField.delegate = self // create back button on nav bar if let topItem = self.navigationController?.navigationBar.topItem { topItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil) } // put data in picker picker = CategoryPicker() categoryPicker.delegate = picker categoryPicker.dataSource = picker // set state of add button & hide priority setting nameField.addTarget(self, action: #selector(editingChanged(_:)), for: .editingChanged) // check if there is data to load if itemToEdit != nil { loadItemData() nameField.isEnabled = false } else { // if there is not an old item, wait to enable save addButton.isEnabled = false } // check if we came from grocery list if (!inNav){ keepStockedSwitch.setOn(true, animated: false) } } @IBAction func setKeepSlider(_ sender: Any) { if (keepStockedSwitch.isOn) { priorityHeight.constant = 28 priorityControl.isHidden = false } else { priorityHeight.constant = 0 priorityControl.isHidden = true } } // maintain save button state func editingChanged(_ textField: UITextField) { // if a space is first char, consider empty if nameField.text?.characters.count == 1 { if nameField.text?.characters.first == " " { nameField.text = "" return } } // check to see if text field stops being empty guard let field = nameField.text, !field.isEmpty else { addButton.isEnabled = false return } addButton.isEnabled = true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return false } @IBAction func addButtonPressed(_ sender: Any) { var item: Item! let brandNewItem = (itemToEdit == nil) // check if we are editing old or creating new if brandNewItem { item = Item(context: context) } else { item = itemToEdit! } // set fields if let name = nameField.text { item.name = name } let categoryName = picker.categories[categoryPicker.selectedRow(inComponent: 0)] item.category = Category.categoryWithName(name: categoryName, context: context) if let notes = notesField.text { item.notes = notes } item.priority = Int16(priorityControl.selectedSegmentIndex) item.amountLeft = Int16(currentStockControl.selectedSegmentIndex) item.mustKeepOnHand = keepStockedSwitch.isOn if(!brandNewItem){ cloud.updateItemInCloud(item: item, keysToChange: nil) } else { cloud.createItemInCloud(item: item) } self.dismiss(animated: true, completion: nil) } @IBAction func deletePressed(_ sender: UIBarButtonItem) { // delete item currently being edited if itemToEdit != nil { cloud.deleteItemInCloud(item: itemToEdit!) context.delete(itemToEdit!) ad.saveContext() } self.dismiss(animated: true, completion: nil) } @IBAction func backPressed(_ sender: UIBarButtonItem) { self.dismiss(animated: true, completion: nil) } // Load data into fields if editing old item func loadItemData() { if let item = itemToEdit { // load each field with preset data nameField.text = item.name // category picker may cause errors if let category = item.category?.name { var index = 0 repeat { let t = picker.categories[index] if t == category { categoryPicker.selectRow(index, inComponent: 0, animated: false) break } index += 1 } while (index < picker.categories.count) } priorityControl.selectedSegmentIndex = Int(item.priority) currentStockControl.selectedSegmentIndex = Int(item.amountLeft) notesField.text = item.notes } } }
true
30c50345df865262b8babfb69fcd68ecb1298e16
Swift
Yard-Smart/YardRemote-DEPRECATED
/YardRemote Manager /YardRemote Xcode/YardRemote Manager/YardRemote Manager/Data/Job.swift
UTF-8
626
2.859375
3
[]
no_license
// // Job.swift // YardRemote Manager // // Created by Felipe Galindo on 12/19/20. // import Foundation struct Job: Identifiable, Hashable, Equatable{ let id: String let name: String let CreatorID: String let EmployeesIDs: [String] let address: String let startLatitude: String let startLongitude: String let startTime: String let endLatitude: String let endLongitude: String let endTime: String func hash(into hasher: inout Hasher) { hasher.combine(id) } static func ==(lhs: Job, rhs: Job) -> Bool { return lhs.name == rhs.name && lhs.id == rhs.id } }
true
3e63f109b2012ed5dbf01919da4d602abc7000fc
Swift
egortka/RabbleWabble
/RabbleWabble/Caretakers/QuestionGroupCaretaker.swift
UTF-8
1,254
2.65625
3
[]
no_license
// // QuestionGroupCaretaker.swift // RabbleWabble // // Created by Egor Tkachenko on 20/11/2019. // Copyright © 2019 ET. All rights reserved. // import Foundation public final class QuestionGroupCaretaker { // MARK: - Properties private let fileName = "QuestionGroupData" public var questionGroups: [QuestionGroup] = [] public var selectedQuestionGroup: QuestionGroup! // MARK: - Object Lifecycle public init() { loadQuestionGroups() } public func loadQuestionGroups() { if let questionGroups = try? DiskCaretacker.retrieve([QuestionGroup].self, from: fileName) { self.questionGroups = questionGroups } else { let bundle = Bundle.main let url = bundle.url(forResource: fileName, withExtension:".json")! self.questionGroups = try! DiskCaretacker.retrieve([QuestionGroup].self, from: url) try! saveQuestionGroups() } } public func saveQuestionGroups() throws { try DiskCaretacker.save(questionGroups, to: fileName) } }
true
2996f0d317aa73b76570a7c3ffdf045aa03870e6
Swift
Milvan/Swiftlearning
/ItunesAPI/ItunesAPI/TableViewController.swift
UTF-8
3,904
2.90625
3
[]
no_license
// // TableViewController.swift // ItunesAPI // // Created by Marcus Larson on 11/10/16. // Copyright © 2016 IVaE. All rights reserved. // import UIKit class TableViewController: UITableViewController{ @IBOutlet var appsTableView : UITableView! var tableData : [NSDictionary] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. searchItunesFor(searchTerm: "one direction") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func searchItunesFor(searchTerm: String){ // Itunes wants multiple terms separated by +, so replace " " with "+" let itunesSearchTerm = searchTerm.replacingOccurrences(of: " ", with: "+") // Now escape anything else that isn't URL-friendly let escapedSearchTerm = itunesSearchTerm.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed ) let urlPath = "http://itunes.apple.com/search?term=\(escapedSearchTerm!)&media=software" let url = URL(string: urlPath) let request = URLRequest(url: url!) let session = URLSession.shared let task = session.dataTask(with: request) {data, response, error in if(error != nil) { // If there is an error in the web request, print it to the console print(error!.localizedDescription) } do{ let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary if let results: NSArray = jsonResult!["results"] as? NSArray { DispatchQueue.main.async(execute: { self.tableData = results as! [NSDictionary] self.appsTableView.reloadData() }) } } catch let err as NSError{ // If there is an error parsing JSON, print it to the console print("JSON Error \(err.localizedDescription)") } } // The task is just an object with all these properties set // In order to actually make the web request, we need to "resume" task.resume() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.tableData.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "MyTestCell") let rowData: NSDictionary = self.tableData[indexPath.row] // Grab the artworkUrl60 key to get an image URL for the app's thumbnail let urlString = rowData["artworkUrl60"] as? String // Create an NSURL instance from the String URL we get from the API let imgURL = NSURL(string: urlString!) // Get the formatted price string for display in the subtitle let formattedPrice = rowData["formattedPrice"] as? String // Download an NSData representation of the image at the URL let imgData = NSData(contentsOf: imgURL as! URL) // Get the track name let trackName = rowData["trackName"] as? String // Get the formatted price string for display in the subtitle cell.detailTextLabel?.text = formattedPrice // Update the imageView cell to use the downloaded image data cell.imageView?.image = UIImage(data: imgData as! Data) // Update the textLabel text to use the trackName from the API cell.textLabel?.text = trackName return cell } }
true
fd696433eb80abb7cbbde363118dc73fedc206f2
Swift
AlexSumak/TwitterWeek2
/TwitterDemo/TweetCell.swift
UTF-8
5,116
2.6875
3
[ "Apache-2.0" ]
permissive
// // TweetCell.swift // TwitterDemo // // Created by Alex Sumak on 2/26/17. // Copyright © 2017 Alex Sumak. All rights reserved. // import UIKit protocol TweetCellDelegate: class { func userTappedProfilePicture(tappedCell: TweetCell, withUserData data: User) func userTappedText(tappedCell: TweetCell, withUserData data: Tweet) func userTappedReply(tappedCell: TweetCell, withUserData data: User) } class TweetCell: UITableViewCell { var retweetCount: Int = 0 var favoritesCount: Int = 0 var retweetMe: Int = 1 var favoriteMe: Int = 1 weak var delegate: TweetCellDelegate? @IBOutlet weak var profilePicImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var handleLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var likeLabel: UILabel! @IBOutlet weak var repostLabel: UILabel! @IBOutlet weak var tweetTextLabel: UILabel! //@IBOutlet weak var profileImageView: UIImageView! var tweet: Tweet!{ didSet{ //set the url using the new user property inside the Tweet class we just created if let profileURL = self.tweet.user.profileUrl{ self.profilePicImageView.setImageWith(profileURL) } //set the name using the new user property inside the Tweet class we just created if let name = self.tweet.user.name{ self.nameLabel.text = name } //update the rest of the UI self.likeLabel.text = tweet.favoriteCount.description self.repostLabel.text = tweet.retweetCount.description self.timeLabel.text = timeAgoSince(tweet.timestamp!) self.tweetTextLabel.text = tweet.text } } func timeAgoSince(_ date: Date) -> String { let calendar = Calendar.current let now = Date() let unitFlags: NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfYear, .month, .year] let components = (calendar as NSCalendar).components(unitFlags, from: date, to: now, options: []) if let year = components.year, year >= 2 { return "\(year) years ago" } if let year = components.year, year >= 1 { return "Last year" } if let month = components.month, month >= 2 { return "\(month) months ago" } if let month = components.month, month >= 1 { return "Last month" } if let week = components.weekOfYear, week >= 2 { return "\(week) weeks ago" } if let week = components.weekOfYear, week >= 1 { return "Last week" } if let day = components.day, day >= 2 { return "\(day) days ago" } if let day = components.day, day >= 1 { return "Yesterday" } if let hour = components.hour, hour >= 2 { return "\(hour) hours ago" } if let hour = components.hour, hour >= 1 { return "An hour ago" } if let minute = components.minute, minute >= 2 { return "\(minute) minutes ago" } if let minute = components.minute, minute >= 1 { return "A minute ago" } if let second = components.second, second >= 3 { return "\(second) seconds ago" } return "Just now" } 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 } @IBAction func userTappedProfilePicture(_ sender: Any) { delegate?.userTappedProfilePicture(tappedCell: self, withUserData: (self.tweet?.user)!) } @IBAction func userTappedText(_ sender: Any) { delegate?.userTappedText(tappedCell: self, withUserData: (self.tweet)!) } @IBAction func userTappedReply(_ sender: Any) { delegate?.userTappedReply(tappedCell: self, withUserData: (self.tweet?.user)!) } @IBAction func onRetweet(_ sender: Any) { favoritesCount = tweet.favoriteCount favoritesCount = favoritesCount + 1 likeLabel.text = String (self.favoritesCount) retweetMe = retweetMe + 1 if (retweetMe % 2 != 0){ favoritesCount = favoritesCount - 1 likeLabel.text = String (self.favoritesCount) } } @IBAction func onLike(_ sender: Any) { retweetCount = tweet.retweetCount retweetCount = retweetCount + 1 repostLabel.text = String (self.retweetCount) favoriteMe = favoriteMe + 1 if (favoriteMe % 2 != 0){ retweetCount = retweetCount - 1 repostLabel.text = String (self.retweetCount) } } }
true
dd4d38728ad270ab0246a08bb95ed50c006d043a
Swift
kingslay/core-image-video
/MyPlayground.playground/Contents.swift
UTF-8
1,782
2.953125
3
[]
no_license
//: Playground - noun: a place where people can play import XCPlayground import UIKit let view = UIView() view.frame = CGRectMake(0, 0, 400, 400) view.backgroundColor = UIColor.redColor() let view2 = UIView() view2.frame = CGRectMake(100, 100, 100, 100) view2.backgroundColor = UIColor.whiteColor() view.addSubview(view2) print("view2.frame:\(view2.frame)") let view3 = UIView() view3.frame = CGRectMake(50, 50, 50, 50) view3.backgroundColor = UIColor.yellowColor() view2.addSubview(view3) view3.layer.frame //view3.transform = CGAffineTransformMakeScale(1,2) print("view3.frame:\(view3.frame)") let view4 = UIView() view4.frame = CGRectMake(0, 25, 50, 50) view4.backgroundColor = UIColor.brownColor() view2.addSubview(view4) print("view4.frame:\(view4.frame)") print("view4.frame:\(view4.convertRect(view4.bounds, toView: view))") //view.bounds = CGRectMake(-10, -10, 200, 200) view2.bounds = CGRectMake(0, 0, 190, 190) XCPlaygroundPage.currentPage.liveView = view XCPlaygroundPage.currentPage.needsIndefiniteExecution = true let url = NSURL(string: "http://httpbin.org/image/png")! let task = NSURLSession.sharedSession().dataTaskWithURL(url) { data, _, _ in let image = UIImage(data: data!) XCPlaygroundPage.currentPage.finishExecution() } task.resume() let marray1 = NSMutableArray() marray1.addObject(NSMutableString(string: "1")) marray1.addObject(NSMutableString(string: "2")) marray1.addObject(NSMutableString(string: "3")) marray1.addObject(NSMutableString(string: "4")) let marray2 = marray1.mutableCopy() let array1 = marray1.copy() as! NSArray let array2 = marray1.mutableCopy() as! NSArray marray1[0].appendString("append") marray1.addObject(NSMutableString(string: "5")) marray1 marray2 array1 array2 let arr2 = [10 ... 14] + [1 ... 24] arr2
true
5089b6222932e213307f15ca0874fb4391cb0828
Swift
renshuki/stts
/stts/Services/AppleDeveloper.swift
UTF-8
411
2.59375
3
[ "MIT" ]
permissive
// // AppleDeveloper.swift // stts // import Foundation class AppleDeveloper: Apple { override var name: String { return "Apple Developer" } override var url: URL { return URL(string: "https://developer.apple.com/system-status/")! } override var dataURL: URL { return URL(string: "https://www.apple.com/support/systemstatus/data/developer/system_status_en_US.js")! } }
true
5dbe3aadc91f506dcb06185610fb182d2a8591be
Swift
Wertuoz/PrnkTest
/PrnkTest/View/PrnkViewController.swift
UTF-8
4,435
2.9375
3
[]
no_license
// // ViewController.swift // PrnkTest // // Created by Anton Trofimenko on 31/03/2019. // Copyright © 2019 Anton Trofimenko. All rights reserved. // import UIKit /// Available controlls types enum ViewType: String { case text = "hz" case pic = "picture" case selector = "selector" } /// Protocol to communicate with views protocol PrnkViewWithData { func updateData(data: NamedData) init(withFrame: CGRect) } /// Class to catch touch events from subviews of containerview class PassthroughView: UIView { override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { let view = super.hitTest(point, with: event) return view == self ? nil : view } override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { return true } } class PrnkViewController: UIViewController { @IBOutlet weak var showNextBtn: UIButton! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var containerView: UIView! private let presenter = PrnkViewPresenter(service: PrnkViewService()) private var dataToDisplay: ViewListData? private var currentViewIndex: Int = 0 override func viewDidLoad() { super.viewDidLoad() presenter.attachView(self) activityIndicator.hidesWhenStopped = true presenter.fetchData() } // MARK: Presenter's callbacks to call private func updateView() { guard let data = dataToDisplay else { return } containerView.removeAllSubView() presenter.getCurrentViewData(index: currentViewIndex, data: data) } private func updateViewWithData(data: NamedData) { guard let viewWithData = getViewByType(viewType: data.name) else { return } containerView.isUserInteractionEnabled = true view.isUserInteractionEnabled = true containerView.addView(viewWithData as! UIView) viewWithData.updateData(data: data) } /// MARK: Helpers @IBAction func onNextViewClick(_ sender: Any) { currentViewIndex += 1 updateView() guard let data = dataToDisplay else { return } if currentViewIndex >= data.viewSequence.count - 1 { currentViewIndex = -1 } } /// Fabric method instatiates views by control name private func getViewByType(viewType: String) -> PrnkViewWithData? { switch viewType { case ViewType.text.rawValue: let tempView = PrnkTextView(withFrame: view.frame) tempView.delegate = self return tempView case ViewType.pic.rawValue: let tempView = PrnkPictureView(withFrame: view.frame) tempView.delegate = self return tempView case ViewType.selector.rawValue: let tempView = PrnkSelectorView(withFrame: view.frame) tempView.delegate = self return tempView default: return nil } } } // Extension to communicate with presenter extension PrnkViewController: PrnkControlsView { func setCurrentViewData(data: NamedData?) { guard let currentData = data else { return } updateViewWithData(data: currentData) } func startLoading() { activityIndicator.startAnimating() showNextBtn.isEnabled = false } func finishLoading() { activityIndicator.stopAnimating() showNextBtn.isEnabled = true } func setViewData(viewListData: ViewListData) { self.dataToDisplay = viewListData updateView() } func setEmptyData() { print("data is empty") } func setErrorFetchData(error: Error) { print(error.localizedDescription) } } /// MARK: Extensions to react on views actions extension PrnkViewController: PrnkPictureViewDelegate { func pictureViewTapped(text: String, url: String) { print("Tapped PictureView with text: \(text) and url: \(url)") } } extension PrnkViewController: PrnkSelectorViewdelegate { func radioButtonSelected(id: Int, text: String) { print("Tapped SelectorView with id: \(id) and text: \(text)") } } extension PrnkViewController: PrnkTextViewDelegate { func textViewTapped(text: String) { print("Tapped TextView with text: \(text)") } }
true
e250f3e34a06bdac286844e2abe5cf7e507ffadf
Swift
tdolotkazin/FitCook
/FitCook/Controllers/Meals/RecipePageVC.swift
UTF-8
2,626
2.609375
3
[]
no_license
import UIKit class RecipePageVC: UIViewController { var recipeItems: [RecipeItem]! var selectedItemIndex: Int! var coreData: CoreDataHelper? private var pageController: UIPageViewController? private var currentIndex = 0 override func viewDidLoad() { super.viewDidLoad() pageController = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil) pageController?.dataSource = self pageController?.delegate = self pageController?.view.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height) addChild(pageController!) view.addSubview(pageController!.view) let storyBoard = UIStoryboard(name: "Main", bundle: .main) let initialVC = storyBoard.instantiateViewController(identifier: "RecipeItemVC") as! RecipeItemVC initialVC.recipeItem = recipeItems[selectedItemIndex] initialVC.coreData = coreData pageController?.setViewControllers([initialVC], direction: .forward, animated: true, completion: nil) pageController?.didMove(toParent: self) } } extension RecipePageVC: UIPageViewControllerDelegate, UIPageViewControllerDataSource { func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let currentVC = viewController as? RecipeItemVC else { return nil } var index = recipeItems.firstIndex(of: currentVC.recipeItem)! if index == 0 { index = recipeItems.count - 1 } else { index -= 1 } let storyBoard = UIStoryboard(name: "Main", bundle: .main) let beforeVC = storyBoard.instantiateViewController(identifier: "RecipeItemVC") as! RecipeItemVC beforeVC.recipeItem = recipeItems[index] beforeVC.coreData = coreData return beforeVC } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let currentVC = viewController as? RecipeItemVC else { return nil } var index = recipeItems.firstIndex(of: currentVC.recipeItem)! if index == recipeItems.count - 1 { index = 0 } else { index += 1 } let storyBoard = UIStoryboard(name: "Main", bundle: .main) let afterVC = storyBoard.instantiateViewController(identifier: "RecipeItemVC") as! RecipeItemVC afterVC.recipeItem = recipeItems[index] afterVC.coreData = coreData return afterVC } func presentationCount(for pageViewController: UIPageViewController) -> Int { return recipeItems!.count } func presentationIndex(for pageViewController: UIPageViewController) -> Int { return currentIndex } }
true
148aeb3a45013ab3a1720d623f0cc281685be993
Swift
Dipesh117/ShineGlass
/ShineGlass/Project Manager/Service Manager/AuthenticationManager.swift
UTF-8
13,495
2.59375
3
[]
no_license
// // AuthenticationManager.swift // ShineGlass // // Created by Lucifer on 19/10/20. // Copyright © 2020 Tecocraft. All rights reserved. // import Foundation import PromiseKit import SwiftyJSON import AlamofireSwiftyJSON func header() -> [String : String] { return [ "Accept":"application/json", "Content-Type":"application/json", ] } func authHeader() -> [String : String] { return [ "Accept":"application/json", "Content-Type":"application/json", "token": authToken ] } struct AuthenticationManager { // Register User func registerUserApi(param: [String: String]) -> Promise<LoginResponse> { let url = sAPIUrl + sRegister let decoder = JSONDecoder() decoder.keyDecodingStrategy = .useDefaultKeys let jsonData1 = try? JSONSerialization.data(withJSONObject: param, options: []) let jsonString = String(data: jsonData1!, encoding: .utf8) let jsonData = jsonString?.data(using: .utf8, allowLossyConversion: false)! var request = URLRequest(url: URL(string: url)!) request.httpMethod = HTTPMethod.post.rawValue request.timeoutInterval = 40 request.httpBody = jsonData request.allHTTPHeaderFields = header() return Promise() { resolver in Alamofire.request(request) .validate(statusCode: 200..<400) .validate(contentType: ["application/json"]) .responseSwiftyJSON{ (response) in switch(response.result) { case .success(_): if let responseData = response.data { do { let loginResponse = try decoder.decode(LoginResponse.self, from: responseData) resolver.fulfill(loginResponse) } catch (let errorN) { resolver.reject(errorN) } } else { let error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey :"An error has occured." as Any]) resolver.reject(error) } case .failure(let error): if let responseData = response.data { do { let loginResponse = try decoder.decode(LoginResponse.self, from: responseData) if loginResponse.message != nil { let errorMsg = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: loginResponse.message as Any]) resolver.reject(errorMsg) } resolver.reject(error) } catch { resolver.reject(error) } } resolver.reject(error) } } } } // Login User func loginUserApi(param: [String: String]) -> Promise<LoginResponse> { let url = sAPIUrl + sLogin let decoder = JSONDecoder() decoder.keyDecodingStrategy = .useDefaultKeys let jsonData1 = try? JSONSerialization.data(withJSONObject: param, options: []) let jsonString = String(data: jsonData1!, encoding: .utf8) let jsonData = jsonString?.data(using: .utf8, allowLossyConversion: false)! var request = URLRequest(url: URL(string: url)!) request.httpMethod = HTTPMethod.post.rawValue request.timeoutInterval = 40 request.httpBody = jsonData request.allHTTPHeaderFields = header() return Promise() { resolver in Alamofire.request(request) .validate(statusCode: 200..<400) .validate(contentType: ["application/json"]) .responseSwiftyJSON{ (response) in switch(response.result) { case .success(_): if let responseData = response.data { do { let loginResponse = try decoder.decode(LoginResponse.self, from: responseData) resolver.fulfill(loginResponse) } catch (let errorN) { resolver.reject(errorN) } } else { let error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey :"An error has occured." as Any]) resolver.reject(error) } case .failure(let error): if let responseData = response.data { do { let loginResponse = try decoder.decode(LoginResponse.self, from: responseData) if loginResponse.message != nil { let errorMsg = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: loginResponse.message as Any]) resolver.reject(errorMsg) } resolver.reject(error) } catch { resolver.reject(error) } } resolver.reject(error) } } } } // Login with OTP func loginWithOTPUserApi(param: [String: String]) -> Promise<LoginResponse> { let url = sAPIUrl + sNumberLogin let decoder = JSONDecoder() decoder.keyDecodingStrategy = .useDefaultKeys let jsonData1 = try? JSONSerialization.data(withJSONObject: param, options: []) let jsonString = String(data: jsonData1!, encoding: .utf8) let jsonData = jsonString?.data(using: .utf8, allowLossyConversion: false)! var request = URLRequest(url: URL(string: url)!) request.httpMethod = HTTPMethod.post.rawValue request.timeoutInterval = 40 request.httpBody = jsonData request.allHTTPHeaderFields = header() return Promise() { resolver in Alamofire.request(request) .validate(statusCode: 200..<400) .validate(contentType: ["application/json"]) .responseSwiftyJSON{ (response) in switch(response.result) { case .success(_): if let responseData = response.data { do { let loginResponse = try decoder.decode(LoginResponse.self, from: responseData) resolver.fulfill(loginResponse) } catch (let errorN) { resolver.reject(errorN) } } else { let error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey :"An error has occured." as Any]) resolver.reject(error) } case .failure(let error): if let responseData = response.data { do { let loginResponse = try decoder.decode(LoginResponse.self, from: responseData) if loginResponse.message != nil { let errorMsg = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: loginResponse.message as Any]) resolver.reject(errorMsg) } resolver.reject(error) } catch { resolver.reject(error) } } resolver.reject(error) } } } } func requestApiCall(param: [String: String]) -> Promise<[MyRequestResponse]> { let url = sAPIUrl + sQuotation let decoder = JSONDecoder() decoder.keyDecodingStrategy = .useDefaultKeys var request = URLRequest(url: URL(string: url)!) request.httpMethod = HTTPMethod.get.rawValue request.timeoutInterval = 40 request.allHTTPHeaderFields = authHeader() return Promise() { resolver in Alamofire.request(request) .validate(statusCode: 200..<400) .validate(contentType: ["application/json"]) .responseSwiftyJSON{ (response) in switch(response.result) { case .success(_): if let responseData = response.data { do { let request = try decoder.decode([MyRequestResponse].self, from: responseData) resolver.fulfill(request) } catch (let errorN) { resolver.reject(errorN) } } else { let error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey :"An error has occured." as Any]) resolver.reject(error) } case .failure(let error): if let responseData = response.data { do { let loginResponse = try decoder.decode(LoginResponse.self, from: responseData) if loginResponse.message != nil { let errorMsg = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: loginResponse.message as Any]) resolver.reject(errorMsg) } resolver.reject(error) } catch { resolver.reject(error) } } resolver.reject(error) } } } } }
true
7001b49ec6c0d28ef3fbbc34b33047654a94a6d9
Swift
prempratapsingh/GitExplore
/GitExplore/Services/DataServices/RepositorySearchService.swift
UTF-8
1,846
2.953125
3
[]
no_license
// // RepositorySearchService.swift // GitExplore // // Created by Prem Pratap Singh on 25/12/20. // import Foundation /// Typealias for search API response handler typealias SearchRepositoriesResponseHandler = ([RepositorySearchResult]?, GEError?) -> Void /// Protocol for the search service protocol SearchService: DataService { var isSearchInProgress: Bool { get } func searchRepositories(for keyword: String, responseHandler: @escaping SearchRepositoriesResponseHandler) } /// Search repository service class class RepositorySearchService: SearchService { // MARK: Public properties var isSearchInProgress: Bool { return self.searchTask != nil } // MARK: Private properties private var searchTask: URLSessionDataTask? // MARK: Public methods func searchRepositories(for keyword: String, responseHandler: @escaping SearchRepositoriesResponseHandler) { // Cancel existing search task, if any if let task = self.searchTask, task.state == .running { task.cancel() self.searchTask = nil } self.search(for: keyword) { searchResult, error in self.searchTask = nil responseHandler(searchResult, error) } } // MARK: Private methods private func search(for keyword: String, responseHandler: @escaping SearchRepositoriesResponseHandler) { let url = self.getServiceUrl(for: RestAPIServer.github, endpoint: RestAPIEndpoint.search) let parameters: [String: Any] = [ "q": keyword, "per_page": 20 ] let networkRequest = NetworkRequest(url: url, method: NetworkMethod.get, parameters: parameters) self.searchTask = getData(request: networkRequest, responseHandler: responseHandler) } }
true
8290ad30212cd0a56ff1d1b4dc09ced5cde003b8
Swift
TiffanyObi/IntroToUnitTestingLab
/Controllers!!!/TriviaDataViewController.swift
UTF-8
2,041
2.75
3
[]
no_license
// // TriviaDataViewController.swift // IntroToUnitTestingLab // // Created by Tiffany Obi on 12/4/19. // Copyright © 2019 Tiffany Obi. All rights reserved. // import UIKit class TriviaDataViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var welcomeLabel: UILabel! var allTrivia = [Trivia]() func loadData() { guard let fileURL = Bundle.main.url(forResource: "triviaData", withExtension: "json") else { fatalError("could not locate file") } do{ let data = try Data(contentsOf: fileURL) let trivias = try JSONDecoder().decode(AllTriviaData.self, from: data) allTrivia = trivias.results } catch { fatalError("could not decode data: \(error)") } welcomeLabel.textColor = .purple } override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self loadData() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let triviaQuestion = segue.destination as? TriviaDetailViewController, let indexPath = tableView.indexPathForSelectedRow else { fatalError("return ") } triviaQuestion.trivia = allTrivia[indexPath.row] } } extension TriviaDataViewController : UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { allTrivia.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let triviaCell = tableView.dequeueReusableCell(withIdentifier: "triviaCell", for: indexPath) let trivia = allTrivia[indexPath.row] triviaCell.textLabel?.text = trivia.category.removingPercentEncoding return triviaCell } }
true
155dd6fad31fd510bb56333d0a668361dc78bc37
Swift
vitolibrarius/ContentaTools
/Tests/ContentaToolsTests/FileCacheTests.swift
UTF-8
3,149
2.921875
3
[ "BSD-2-Clause" ]
permissive
// // DiskCacheTests.swift // CacheKit // // Created by Katsuma Tanaka on 2015/03/13. // Copyright (c) 2015 Katsuma Tanaka. All rights reserved. // import Foundation import XCTest @testable import ContentaTools class FileCacheTests: XCTestCase { static var allTests = [ ("testInitialization", testInitialization), ("testAccessors", testAccessors), ("testSubscription", testSubscription), ("testCount", testCount), ("testCountLimit", testCountLimit), ("testCaching", testCaching), ("testCachingWithCountLimit", testCachingWithCountLimit), ] private var cache: FileCache<String>! override func setUp() { super.setUp() do { cache = try FileCache<String>() } catch { XCTFail() } } override func tearDown() { cache.removeAllObjects() super.tearDown() } func testInitialization() { XCTAssertEqual(cache.count, UInt(0)) XCTAssertEqual(cache.countLimit, UInt(0)) } func testAccessors() { cache.setObject(object: "vito", forKey: "name") let object = cache.objectForKey(key: "name") XCTAssertEqual(object ?? "", "vito") } func testSubscription() { cache["person"] = "Vito Librarius" let object = cache["person"] XCTAssertEqual(object ?? "", "Vito Librarius") } func testCount() { cache["person"] = "Vito Librarius" cache["name"] = "vito" XCTAssertEqual(cache.count, UInt(2)) cache.removeValue(forKey: "name") XCTAssertEqual(cache.count, UInt(1)) cache.removeValue(forKey: "person") XCTAssertEqual(cache.count, UInt(0)) cache.removeValue(forKey: "person") XCTAssertEqual(cache.count, UInt(0)) } func testCountLimit() { cache.countLimit = 2 cache["0"] = "0" cache["1"] = "1" cache["2"] = "2" XCTAssertEqual(cache.count, UInt(2)) XCTAssertFalse(cache.hasObjectForKey(key: "0")) XCTAssertTrue(cache.hasObjectForKey(key: "1")) XCTAssertTrue(cache.hasObjectForKey(key: "2")) } func testCaching() { for number in 0..<100 { cache["key\(number)"] = "value\(number)" } XCTAssertEqual(cache.count, UInt(100)) for number in 0..<100 { if let object = cache.objectForKey(key: "key\(number)") { XCTAssertEqual("value\(number)", object) } else { XCTFail() } } } func testCachingWithCountLimit() { cache.countLimit = 20 for number in 0..<100 { cache["key\(number)"] = "value\(number)" } XCTAssertEqual(cache.count, UInt(20)) for number in 80..<100 { if let object = cache.objectForKey(key: "key\(number)") { XCTAssertEqual("value\(number)", object) } else { XCTFail() } } } }
true
41ea528d383158e111aae129389a5dcb5afa0769
Swift
IM-MC/TWO
/TWO/ViewControllers/NavViewController.swift
UTF-8
1,101
2.53125
3
[]
no_license
// // NavViewController.swift // TWO // // Created by Matthew Chung on 2020-04-27. // Copyright © 2020 Matthew Chung. All rights reserved. // import UIKit import Firebase class NavViewController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() if isLoggedIn() { let email = UserDefaults.standard.string(forKey: kUserEmail) ?? "" let password = UserDefaults.standard.string(forKey: kUserPassword) ?? "" Auth.auth().signIn(withEmail: email, password: password) { (res, err) in if err != nil { print(err ?? "Error signing in") } else { self.perform(#selector(self.showHomeController), with: nil, afterDelay: 0.01) } } } } fileprivate func isLoggedIn() -> Bool { return UserDefaults.standard.bool(forKey: kIsLoggedIn) } @objc func showHomeController() { let homeController = FastViewController() self.pushViewController(homeController, animated: true) } }
true
487b8a78a7ab98a3d9a70a5e40e121e83069e35d
Swift
BunnySai500/RealEstateApp-VIPER-Architecture-
/RealEstateApp/Booking/ViperScene/View/VentureOptionHeader.swift
UTF-8
1,213
2.609375
3
[]
no_license
import Foundation import UIKit @IBDesignable class VentureOptionHeader: UIView, ConfigurableHeader { static let reuseId = "VentureOptionHeaderreuseId" @IBOutlet weak var nameLbl: UILabel! @IBOutlet weak var selectionLbl: UILabel! override init(frame: CGRect) { super.init(frame: frame) configureView() } func configureHeader(withVm vm: VenturHeaderViewModel) { self.nameLbl.text = vm.name self.selectionLbl.text = vm.optionName } required init?(coder: NSCoder) { super.init(coder: coder) configureView() } private func configureView() { isUserInteractionEnabled = true guard let vie = self.loadNib(nibName: "VentureOptionHeader") else{return} vie.frame = self.bounds vie.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.addSubview(vie) } } extension UIView { func loadNib(nibName: String) -> UIView? { let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: nibName, bundle: bundle) return nib.instantiate(withOwner: self, options: nil).first as? UIView } } protocol ConfigurableHeader { func configureHeader(withVm vm: VenturHeaderViewModel) }
true
dd0c6b5ec1e15649ea1112da245b819e3d3d78f4
Swift
mengia/PostcardSwift
/PostcardSwift/ViewController.swift
UTF-8
1,733
2.515625
3
[]
no_license
// // ViewController.swift // PostcardSwift // // Created by Mengistayehu Mamo on 9/6/15. // Copyright (c) 2015 Mengistayehu Mamo. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var messageLabel:UILabel! @IBOutlet weak var enterEnterName:UITextField! @IBOutlet weak var enterEnterMessage:UITextField! @IBOutlet weak var mailSend: UIButton! @IBOutlet weak var nameTextLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func sendMailButtonPressed(sender:UIButton){ // second commit to check the repo nameTextLabel.hidden=false nameTextLabel.text=enterEnterName.text nameTextLabel.textColor=UIColor.blueColor() nameTextLabel.numberOfLines=0 messageLabel.hidden=false messageLabel.text=enterEnterMessage.text messageLabel.textColor=UIColor.redColor(); messageLabel.numberOfLines=0 enterEnterMessage.resignFirstResponder() enterEnterName.resignFirstResponder() if(enterEnterMessage.text=="" || enterEnterName.text==""){ messageLabel.text="please fill all the fields" nameTextLabel.text="" } else { mailSend.setTitle("Message Sent", forState: UIControlState.Normal) } enterEnterName.text="" enterEnterMessage.text="" } }
true
51c033ac01cbc1776b577fc90de4b75789517cd3
Swift
bassaer/micro_blog_for_ios
/micro_blog/MicropostDetailViewController.swift
UTF-8
892
2.578125
3
[]
no_license
// // MicropostDetailViewController.swift // micro_blog // // Created by Nakayama on 2016/05/15. // Copyright © 2016年 Nakayama. All rights reserved. // import UIKit class MicropostDetailViewController: UIViewController { var micropost: Micropost? @IBOutlet weak var titleTextLabel: UILabel! @IBOutlet weak var bodyTextLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() if let micropost = self.micropost { titleTextLabel.text = micropost.title bodyTextLabel.text = micropost.body titleTextLabel.layer.borderColor = UIColor.blueColor().CGColor bodyTextLabel.layer.borderColor = UIColor.blueColor().CGColor titleTextLabel.layer.borderWidth = 1.0 bodyTextLabel.layer.borderWidth = 1.0 } } }
true
e1b8698cd6b6385df537bb8bf81b01c83f087fde
Swift
rajlfc/ForPractice
/SubArrayWithGivenSUm.playground/Contents.swift
UTF-8
409
3.078125
3
[]
no_license
import UIKit var greeting = "Hello, playground" var numbers = [1,2,3,7,5] var S = 12 var currrentSum = numbers[0] var start = 0 for i in 1...numbers.count { while currrentSum < S && start < i-1 { currrentSum = currrentSum-numbers[start] start += 1 } if i < numbers.count { currrentSum = currrentSum + numbers[i] } } /// Have to complete the above code
true
bd0ae51beae53fe59bcbcc9a4d15558bd854a8b1
Swift
songhailiang/Loading
/Loading/Loading.swift
UTF-8
3,985
2.90625
3
[ "MIT" ]
permissive
// // Loading.swift // Loading // // Created by songhailiang on 2018/5/9. // Copyright © 2018 songhailiang. All rights reserved. // import UIKit /** configuration options for Loading */ public struct LoadingConfig { /// both width & height, default is 40.0 public var width: CGFloat = 40.0 /// corner radius, default is 5.0 public var radius: CGFloat = 5.0 /// if value > 0, Loading will force to hide if more than this interval, default is 30 public var maxUnlockTime: TimeInterval = 30 /// indicator view style, default is .white public var style: UIActivityIndicatorViewStyle = .white /// indicator color, default is UIColor.white public var color: UIColor = UIColor.white /// background color for indicator container view public var backgroundColor: UIColor = UIColor.black.withAlphaComponent(0.5) } /** A top most indicator view. */ public class Loading { private static let shared = Loading() private var config = LoadingConfig() private let loadingController: LoadingController private let loadingWindow: UIWindow private var timer: Timer? init() { loadingController = LoadingController() loadingWindow = UIWindow(frame: UIScreen.main.bounds) loadingWindow.windowLevel = UIWindowLevelAlert + 1 loadingWindow.rootViewController = loadingController } /// update configuration /// /// - Parameter config: new configuration data public static func config(_ config: LoadingConfig) { shared.config = config shared.loadingController.config = config } /// show Loading public static func show() { shared.loadingWindow.makeKeyAndVisible() shared.startUnlockTimer() } /// hide Loading public static func hide() { shared.loadingWindow.isHidden = true shared.stopUnlockTimer() } private func startUnlockTimer() { if config.maxUnlockTime <= 0 { return } if timer != nil { stopUnlockTimer() } timer = Timer.after(config.maxUnlockTime, mode: .commonModes, { Loading.hide() }) } private func stopUnlockTimer() { timer?.invalidate() timer = nil } } fileprivate class LoadingController: UIViewController { private var loadingView: LoadingView! fileprivate var config = LoadingConfig() { didSet { if isViewLoaded && view != nil { updateLoadingView() } } } override func viewDidLoad() { super.viewDidLoad() loadingView = LoadingView(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) view.addSubview(loadingView) updateLoadingView() } override func viewDidLayoutSubviews() { loadingView.center = self.view.center } private func updateLoadingView() { loadingView.bounds.size = CGSize(width: config.width, height: config.width) loadingView.layer.cornerRadius = config.radius loadingView.backgroundColor = config.backgroundColor loadingView.indicator.activityIndicatorViewStyle = config.style loadingView.indicator.color = config.color } } fileprivate class LoadingView: UIView { fileprivate var indicator: UIActivityIndicatorView = { return UIActivityIndicatorView(activityIndicatorStyle: .white) }() override init(frame: CGRect) { super.init(frame: frame) self.addSubview(indicator) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { indicator.center = CGPoint(x: self.bounds.width / 2, y: self.bounds.height / 2) } override func willMove(toSuperview newSuperview: UIView?) { if newSuperview != nil { indicator.startAnimating() } else { indicator.stopAnimating() } } }
true
f9285fb503fed1201858062359e8d56cc696e18b
Swift
Tehreer/Tehreer-Cocoa
/Source/Layout/TruncationPlace.swift
UTF-8
903
2.515625
3
[ "Apache-2.0" ]
permissive
// // Copyright (C) 2020 Muhammad Tayyab Akram // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation /// Specifies the text truncation place. public enum TruncationPlace: Int { /// Text is truncated at the start of the line. case start = 0 /// Text is truncated at the middle of the line. case middle = 1 /// Text is truncated at the end of the line. case end = 2 }
true
076b4611c766f59d8a9bfe7c12e76b677dc13739
Swift
LCernei/Piscine-Swift
/Piscine Swift/d01/ex03/Card.swift
UTF-8
589
3.90625
4
[]
no_license
import Foundation class Card: NSObject { var color: Color var value: Value init (color: Color, value: Value) { self.color = color self.value = value } override var description: String { get { let string = "(\(self.value), \(self.color))" return string } } static func ==(card1: Card, card2: Card) -> Bool { if ((card1.color == card2.color) && (card1.value == card2.value)) { return true } return false } override func isEqual(_ object: Any?) -> Bool { if object is Card { if object as! Card == self { return true } } return false } }
true
864ca73ec366aa2184009b0825c813f19781df96
Swift
codepath-jjc/LevelUpApp
/LevelUp/LevelUp/LevelUpClient.swift
UTF-8
7,574
2.671875
3
[]
no_license
// // LevelUpClient.swift // LevelUp // // Created by jason on 11/10/16. // Copyright © 2016 jasonify. All rights reserved. // import UIKit import Parse class LevelUpClient: NSObject { static let sharedInstance = LevelUpClient() static var morphLevel = 0 static var poops = 0 static var cachedQuests: [Quest]? { didSet { guard cachedQuests != nil else {return} for cachedQuest in cachedQuests! { LevelUpClient.sharedInstance.fetchIcon(quest: cachedQuest, success: { (image: UIImage) -> () in cachedQuest.image = image }, failure: { (error: Error) -> () in // }) } } } static var cachedMilestones: [Milestone]? static var __points = 1 func fetchIcon(quest: Quest, success: @escaping (UIImage) -> (), failure: @escaping (Error)->() ) { if let loadedIcon = quest.image { success(loadedIcon) } else { // XXX: if this is not defined, it should go to an else but that doesnt work in swift?.. if let userImageFile = quest.imageFile { userImageFile.getDataInBackground(block: { (imageData:Data?, error:Error?) in if error == nil { if let imageData = imageData { let image = UIImage(data:imageData) quest.image = image success((image)!) } } else { failure((error)!) } }) } if quest.imageFile == nil { var imageIndex = 0 if quest.imageFallback == nil { } else { imageIndex = quest.imageFallback! } if let image = Quest.images[imageIndex] { success(image) } } } } func user() -> PFUser?{ let currentUser = PFUser.current() if let currentUser = currentUser { currentUser.setValue(0, forKey: "points") currentUser.saveInBackground() return currentUser // Do stuff with the user } return nil } func getPoints() -> Int { return LevelUpClient.__points // try? LevelUpClient.sharedInstance.user()!.fetch() // return LevelUpClient.sharedInstance.user()!["points"] as! Int } func addPoints(points: Int){ LevelUpClient.__points += points // LevelUpClient.sharedInstance.user()!.incrementKey("points", byAmount: points as NSNumber) // LevelUpClient.sharedInstance.user()!.saveInBackground() } // This is a mutating function - the input Quest and Milestone WILL be updated func sync(quest: inout Quest, success: @escaping () -> (), failure: @escaping (Error?) -> ()) { if let questPfObject = quest.pfObject { // Update the PFObject on the quest and save in background questPfObject.setDictionary(quest.dictionary) questPfObject.saveInBackground(block: { (successStatus: Bool, error: Error?) -> Void in if successStatus { success() } else { failure(error) } }) } else { // Create - since it must not exist on Parse let questPFObject = PFObject(className: Quest.className) questPFObject.setDictionary(quest.dictionary) // XXX: this is not ideal since we will not get the progress indicator // TODO(Jason): Implement save progressively // Save questPFObject.saveInBackground { (successStatus: Bool, error: Error?) -> Void in if successStatus { success() } else { failure(error) } } quest.pfObject = questPFObject } } // This is a mutating function - the input Quest and Milestone WILL be updated func sync(milestone: inout Milestone, success: @escaping () -> (), failure: @escaping (Error?) -> ()) { if let milestonePfObject = milestone.pfObject { // Update milestonePfObject.setDictionary(milestone.dictionary ) milestonePfObject.saveInBackground(block: { (successStatus: Bool, error: Error?) -> Void in if successStatus { success() } else { failure(error) } }) } else { // Create - since it must not exist on Parse let milestonePFObject = PFObject(className: Milestone.className) milestonePFObject.setDictionary(milestone.dictionary) // Save milestonePFObject.saveInBackground { (successStatus: Bool, error: Error?) -> Void in if (successStatus) { success() } else { failure(error) } } milestone.pfObject = milestonePFObject } } // Refresh local object from Parse func fetch(quest: inout Quest) { try? quest.pfObject?.fetch() } func fetch(milestone: inout Milestone) { try? milestone.pfObject?.fetch() } func quests(success: @escaping ([Quest]) -> (), failure: @escaping (Error?) -> ()) { let query = PFQuery(className: Quest.className) query.whereKey("user", equalTo: LevelUpClient.sharedInstance.user()!) query.findObjectsInBackground(block: { (pfObjects: [PFObject]?, error: Error?) -> () in if let pfObjects = pfObjects { var quests = [Quest]() for pfObject in pfObjects { quests.append(Quest(pfObject: pfObject)) } LevelUpClient.cachedQuests = quests success(quests) } else { failure(error) } }) } func milestones(success: @escaping ([Milestone]) -> (), failure: @escaping (Error?) -> ()) { let query = PFQuery(className: Milestone.className) query.whereKey("user", equalTo: LevelUpClient.sharedInstance.user()!) query.findObjectsInBackground(block: { (pfObjects: [PFObject]?, error: Error?) -> () in if let pfObjects = pfObjects { var milestones = [Milestone]() for pfObject in pfObjects { let milestone = Milestone(pfObject: pfObject) if let id = milestone.questId { milestone.quest = LevelUpClient.cachedQuests?.find(questId: id) } milestones.append(milestone) } LevelUpClient.cachedMilestones = milestones success(milestones) } else { failure(error) } }) } }
true
5a436de1237bd1e620d2267d97cb5569fdca26ad
Swift
rbarbera/excelsior
/CharacterDetailKit/Source/Presentation/CharacterDetailNavigator.swift
UTF-8
858
2.6875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // CharacterDetailNavigator.swift // CharacterDetailKit // // Created by Rafael Bartolome on 22/03/2020. // Copyright © 2020 Rafael Bartolome. All rights reserved. // import Foundation import NavigatorKit import CommonUIKit class InternalCharacterDetailNavigator { // Dependencies private let mainNavigator: Navigator private let detailScreen: CharacterDetailScreen init(mainNavigator: Navigator, detailScreen: CharacterDetailScreen) { self.mainNavigator = mainNavigator self.detailScreen = detailScreen } } extension InternalCharacterDetailNavigator: CharacterDetailNavigator { func navigateToCharacterDetail(withIdentifier characterId: Int) { let screenParams = [CharacterDetailScreen.Params.characterId: characterId] mainNavigator.handle(navigation: .push(detailScreen, screenParams)) } }
true
d07058a8a1d545d0127267a7eef1439f8e6d8a33
Swift
macbellingrath/Parakeet
/TappyTimer/Session.swift
UTF-8
881
3.265625
3
[]
no_license
// // Session.swift // TappyTimer // // Created by Mac Bellingrath on 1/8/16. // Copyright © 2016 Mac Bellingrath. All rights reserved. // import Foundation struct Segment { enum Type: String { case Work, Rest } var interval: NSTimeInterval var type: Type var completed: Bool } struct Session { var intervals: [Segment] var totalTime: NSTimeInterval { return intervals.reduce(0.0) { $0 + $1.interval } } init(rest: NSTimeInterval, work: NSTimeInterval, number: Int) { self.intervals = [] let w = Segment(interval: work, type: .Work, completed: false) let r = Segment(interval: rest, type: .Rest, completed: false ) for _ in 1...number { if rest > 0.0 { self.intervals.append(r) } self.intervals.append(w) } } }
true
3fed627914eaff1c698583b11198f24c5828cd5e
Swift
minhazur-piash/ColorPopEffect
/kgs-assignment/TaskController.swift
UTF-8
1,537
2.828125
3
[]
no_license
// // TaskController.swift // kgs-assignment // // Created by Minhazur Rahman on 4/29/17. // Copyright © 2017 MinhazHome. All rights reserved. // import UIKit protocol TaskControllerDelegate { func showAlert(title: String, message: String) func showLoader() func hideLoader(completion: (() -> Swift.Void)?) } class TaskController: NSObject { private var taskControllerDelegate: TaskControllerDelegate init(taskControllerDelegate: TaskControllerDelegate) { self.taskControllerDelegate = taskControllerDelegate } func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) { DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { completion() } } func saveImageToPhotoLibrary(image: UIImage) { DispatchQueue.global(qos: .background).async { self.taskControllerDelegate.showLoader() UIImageWriteToSavedPhotosAlbum(image, self, #selector(TaskController.imageSaved(_:didFinishSavingWithError:contextInfo:)), nil) } } @objc func imageSaved(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) { var message = "Color popped image has been saved to your photos." var title = "Saved!" if let error = error { title = "Error!" message = error.localizedDescription } taskControllerDelegate.showAlert(title: title, message: message) } }
true
cbfd9101d4e0cc50553225edfcc039eff3709183
Swift
genmaiokome/SlideShowApp
/slideshowApp/PictureViewController.swift
UTF-8
943
2.578125
3
[]
no_license
// // PictureViewController.swift // slideshowApp // // Created by 渡辺涼介 on 2020/10/05. // Copyright © 2020 ryosuke.watanabe. All rights reserved. // import UIKit class PictureViewController: UIViewController { @IBOutlet weak var ImageView: UIImageView! var ImageNo = 0 let Picture = ["ベース", "キーボード", "ドラム", "ギター"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. ImageView.image = UIImage(named: Picture[ImageNo]) } /* // 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. } */ }
true
3767a3c9795742278fa10ae14ff947ba4e375b19
Swift
cjnevin/MessagesPOC
/MessagesPOC/List/Model/DataSource.swift
UTF-8
2,924
2.640625
3
[ "MIT" ]
permissive
import UIKit import Dwifft @objc class DataSource: NSObject, UICollectionViewDataSource { private var diffCalculator: CollectionViewDiffCalculator<String, Item>? private var sectionedValues: SectionedValues<String, Item> { let tuples = sections.map { ($0.title, $0.items) } return SectionedValues(tuples) } private var cellFactories: [CellFactory] = [] private var headerFactories: [HeaderFactory] = [] private weak var collection: UICollectionView? var sections: [Section] = [] { didSet { self.diffCalculator?.sectionedValues = sectionedValues } } func bind(_ collection: UICollectionView, with cellFactories: [CellFactory], and headerFactories: [HeaderFactory]) { diffCalculator = CollectionViewDiffCalculator(collectionView: collection, initialSectionedValues: sectionedValues) self.collection = collection self.cellFactories = cellFactories self.headerFactories = headerFactories collection.dataSource = self headerFactories.forEach { $0.register(in: collection) } cellFactories.forEach { $0.register(in: collection) } } func numberOfSections(in collectionView: UICollectionView) -> Int { return diffCalculator?.numberOfSections() ?? 0 } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionHeader { guard let title = diffCalculator?.value(forSection: indexPath.section), let header = headerFactories.first(evaluating: { $0.header(for: title, at: indexPath) }) else { return UICollectionReusableView() } return header } else { return UICollectionReusableView() } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return diffCalculator?.numberOfObjects(inSection: section) ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let model = diffCalculator?.value(atIndexPath: indexPath).model, let cell = cellFactories.first(evaluating: { $0.cell(for: model, at: indexPath) }) else { return UICollectionViewCell() } return cell } } fileprivate extension Sequence { func first<T>(evaluating f: @escaping (Element) -> (T?)) -> T? { for element in self { if let result = f(element) { return result } } return nil } }
true
48f05f9045847a7ef2eacef9555ab3e334ea253c
Swift
lucidvision/scheduler-swift
/scheduler-swift/DataService.swift
UTF-8
823
2.546875
3
[]
no_license
// // DataService.swift // scheduler-swift // // Created by Brian Park on 2016-08-05. // Copyright © 2016 Casting Workbook. All rights reserved. // import Foundation import Alamofire typealias Completion = (data: AnyObject) -> Void class DataService { static let ds = DataService() func postSession(username: String, password: String, completed: Completion) { let parameters = [ "username": username, "password": password, "remember_password": "no", "doAction": "mobileactorupload" ] Alamofire.request(.POST, URL_LOGIN, parameters: parameters).responseJSON { (response) in completed(data: response.response!) } } func getUser(loginResponse: String, completed: Completion) { } }
true
b97086a001b39af1b0973e66ed871e144274188b
Swift
Kosalos/HanoiRobot
/HanoiRobot/ViewController.swift
UTF-8
806
2.640625
3
[]
no_license
import UIKit import QuartzCore import SceneKit var scenePtr:SCNScene! var hanoi:Hanoi! var timer = Timer() class ViewController: UIViewController { @IBOutlet var sView: SCNView! override func viewDidLoad() { super.viewDidLoad() sView.backgroundColor = UIColor.black sView.autoenablesDefaultLighting = true sView.allowsCameraControl = true sView.scene = SCNScene() scenePtr = sView.scene hanoi = Hanoi(SCNVector3(-0.1,0.1,0)) timer = Timer.scheduledTimer(timeInterval: 1.0/60.0, target:self, selector: #selector(ViewController.timerHandler), userInfo: nil, repeats:true) } @objc func timerHandler() { hanoi.update() } override var prefersStatusBarHidden : Bool { return true } }
true
6f1028eda1b0388ee4d32e9eb670b89112b9b159
Swift
IanLuo/nebula-note
/Iceberg/Core/AttachmentModel/AttachmentDocument.swift
UTF-8
3,382
2.53125
3
[]
no_license
// // AttachmentDocument.swift // Business // // Created by ian luo on 2019/3/22. // Copyright © 2019 wod. All rights reserved. // import Foundation import UIKit public class AttachmentDocument: UIDocument { public static let fileExtension = "ica" public static let jsonFile = "info.json" public var fileToSave: URL? public var attachment: Attachment? public override func contents(forType typeName: String) throws -> Any { guard let attachment = self.attachment else { return "".data(using: .utf8)! } guard let fileToSave = self.fileToSave else { return "".data(using: .utf8)! } let wrapper = FileWrapper(directoryWithFileWrappers: [:]) let encoder = JSONEncoder() encoder.dateEncodingStrategy = .secondsSince1970 do { // change the url of content in to be the one inside attchment wrapper let json = try encoder.encode(attachment) let jsonWrapper = FileWrapper(regularFileWithContents: json) jsonWrapper.preferredFilename = AttachmentDocument.jsonFile wrapper.addFileWrapper(jsonWrapper) } catch { log.error(error) throw error } let dataWrapper = FileWrapper(regularFileWithContents: try Data(contentsOf: fileToSave)) // use the outter file url, and write to wrapper directory dataWrapper.preferredFilename = attachment.fileName wrapper.addFileWrapper(dataWrapper) return wrapper } public override func load(fromContents contents: Any, ofType typeName: String?) throws { if let wrapper = contents as? FileWrapper { if let jsonData = wrapper.fileWrappers?[AttachmentDocument.jsonFile]?.regularFileContents { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .secondsSince1970 let keyOnPath = self.fileURL.deletingPathExtension().lastPathComponent self.attachment = try decoder.decode(Attachment.self, from: jsonData) if self.attachment?.key != keyOnPath { self.attachment?.key = keyOnPath } } } } public class func createAttachment(url: URL) -> Attachment? { let jsonURL = url.appendingPathComponent(AttachmentDocument.jsonFile) do { var dd: Data? jsonURL.read(completion: { d in dd = d }) guard let data = dd else { return nil } let decoder = JSONDecoder() decoder.dateDecodingStrategy = .secondsSince1970 let keyOnPath = url.deletingPathExtension().lastPathComponent var attachment = try decoder.decode(Attachment.self, from: data) if attachment.key != keyOnPath { attachment.key = keyOnPath } return attachment } catch { log.error(error) return nil } } public override func handleError(_ error: Error, userInteractionPermitted: Bool) { super.handleError(error, userInteractionPermitted: userInteractionPermitted) log.error(error) } }
true
05d4b6884abaa81dbdc513be62d9a8e6dd357b1e
Swift
whatdakell/KellyLinehanAdvancedMAD
/soap help/soap help/Uiti.swift
UTF-8
1,821
2.765625
3
[]
no_license
// // Uiti.swift // soap help // // Created by Kelly Linehan on 4/17/16. // Copyright © 2016 Kelly Linehan. All rights reserved. // import Foundation let ISO_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss" let ISO_DATE_FORMAT = "yyyy-MM-dd" class Uiti: NSObject{ class func concate(orig: String!, notNilString: String) -> String { return orig == nil ? notNilString : "\(orig)\(notNilString)" } //REDOO! class func convertDateToISO(date: NSDate) -> String { // Convert NSDate to string var df = NSDateFormatter() df.dateFormat = ISO_DATE_TIME_FORMAT df.timeZone = NSTimeZone(name: "GMT") return df.stringFromDate(date) } /*! Convert a date string in the ISO format (yyyy-MM-ddTHH:mm:ss) to the system date object @param string a date string in the ISO formate */ class func convertISOToDate(string: String) -> NSDate { // Convert string to NSDate var df = NSDateFormatter() df.dateFormat = ISO_DATE_TIME_FORMAT df.timeZone = NSTimeZone(name: "GMT") return df.dateFromString(string)! } class func dateToString(date: NSDate, format: String) -> String { // Convert NSDate to string var df = NSDateFormatter() df.dateFormat = format df.timeZone = NSTimeZone(name: "GMT") return df.stringFromDate(date) } /*! Convert a date string in the given formate to a system date @param string a date string in the ISO formate @param formate date string format */ class func stringToDate(string: String, format: String) -> NSDate { // Convert NSDate to string var df = NSDateFormatter() df.dateFormat = format df.timeZone = NSTimeZone(name: "GMT") return df.dateFromString(string)! } }
true
974ebca26189a9a4a9ca03794122ae180dff7c32
Swift
bernhard-eiling/CPTR
/explosure/CompoundImage.swift
UTF-8
535
2.578125
3
[]
no_license
// // CompoundImage.swift // CPTR // // Created by Bernhard on 28.02.16. // Copyright © 2016 bernhardeiling. All rights reserved. // import UIKit import CoreGraphics class CompoundImage { var completed: Bool { return imageCounter >= 2 && image != nil } var image: CGImage? { didSet { imageCounter += 1 } } var imageOrientation: UIImageOrientation? var jpegUrl: URL? private var imageCounter: UInt init() { self.imageCounter = 0 } }
true
1fa234bc8aa61cd4375bb187be0014d48a8e147b
Swift
thiagolioy/ModularArch
/BeerCatalog/Coordinators/BeerCatalogCoordinator.swift
UTF-8
1,201
2.828125
3
[]
no_license
// // BeerCatalogCoordinator.swift // BeersApp // // Created by Thiago Lioy on 18/03/18. // Copyright © 2018 Thiago Lioy. All rights reserved. // import UIKit import UIFramework import ModelsFramework public protocol BeerCatalogCoordinatorDelegate: class { func proceedToNext() } public final class BeerCatalogCoordinator: Coordinator { private let presenter: UINavigationController private var catalogController: BeerCatalogController? private weak var delegate: BeerCatalogCoordinatorDelegate? public init(presenter: UINavigationController, delegate: BeerCatalogCoordinatorDelegate) { self.presenter = presenter self.delegate = delegate } public func start() { let builder = BeerCatalogPresenterBuilder(delegate: self) let controller = BeerCatalogController(builder: builder) presenter.pushViewController(controller, animated: true) catalogController = controller } } extension BeerCatalogCoordinator: BeerCatalogPresenterDelegate { func didClickMe() { delegate?.proceedToNext() } func didSelect(beer: Beer) { print("didSelect beer \(beer.name) from the coordinator") } }
true
65af2584ecaebe7808ad8d017e1a9583c9d179fa
Swift
dmaulikr/PlayersGame
/New Final Project/Menu Delegation Ver 2/Menu Delegation/MenuViewController.swift
UTF-8
3,999
2.765625
3
[]
no_license
// // MenuViewController.swift // Menu Delegation // // Created by Dave Scherler on 3/18/15. // Copyright (c) 2015 DaveScherler. All rights reserved. // import UIKit protocol PassingQuote { func showSelectedQuote(ArrayLocation: Int, listOrigin: String) } class MenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var delegate: PassingQuote? var favListSelected: Bool? var allQuotesData = ["Local All One","Local All Two","Local All Three"] var favQuotesData = ["Local Fav One","Local Fav Two", "Local Fav Three"] @IBOutlet weak var filterStatus: UISegmentedControl! @IBOutlet weak var table: UITableView! @IBAction func filterQuotes(sender: UISegmentedControl) { switch filterStatus.selectedSegmentIndex { case 0: filter("allQuotes") self.table.reloadData() self.favListSelected = false case 1: filter("favQuotes") self.table.reloadData() self.favListSelected = true default: filter("allQuotes") self.table.reloadData() self.favListSelected = false } } // The re_filter function is called by the MainViewController // This function ensures that the quotes pushed by the MainViewController actually display func re_filter() { filter("allQuotes") self.table.reloadData() println("MenuViewVC: re_filter() called. The number of quotes in allQuotes is now: \(allQuotesData.count)\n") } var dataForCells: [String] = [] override func viewDidLoad() { super.viewDidLoad() println("MenuViewVC: The dataForCells value before calling filter is: \(dataForCells)") filter("allQuotes") self.table.reloadData() } func filter(filter: String) { if filter == "favQuotes" { self.dataForCells = self.favQuotesData println("MenuViewVC: filter() called for favQuotes. Number of favQuotes is \(self.favQuotesData.count)") } else { self.dataForCells = self.allQuotesData println("MenuViewVC: filter() called for allQuotes. Number of allQuotes is \(self.allQuotesData.count)") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataForCells.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // var cell = tableView.dequeueReusableCellWithIdentifier("quoteCell", forIndexPath: indexPath) as UITableViewCell var cell = tableView.dequeueReusableCellWithIdentifier("quoteCell") as UITableViewCell! if cell == nil { cell = UITableViewCell(style: .Default, reuseIdentifier: "quoteCell") } cell.textLabel?.textColor = UIColor.whiteColor() cell.backgroundColor = UIColor.clearColor() cell.textLabel?.text = dataForCells[indexPath.row] return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 40 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // let cell = self.tableView.cellForRowAtIndexPath(indexPath) as? LocationTableViewCell println("MenuViewVC: The selected row is \(indexPath.row)") var stringToPass: String? if self.favListSelected == true { stringToPass = "Favorites" } else { stringToPass = "All" } self.delegate?.showSelectedQuote(indexPath.row, listOrigin: stringToPass!) } } //}
true
71b2cc4df0fa974d9d17ae9fe80fcf41ce7fcdc4
Swift
ggndpsingh/LoanCalculator
/Shared/ContentView.swift
UTF-8
6,230
2.609375
3
[]
no_license
// // ContentView.swift // Shared // // Created by Gagandeep Singh on 2/2/21. // import SwiftUI struct ContentView: View { @Environment(\.presentationMode) private var presentationMode @ObservedObject var loan: HomeLoan @State private var showExtraRepaymentInput: Bool = false var body: some View { NavigationView { ScrollView { VStack { VStack(alignment: .leading, spacing: 24) { VStack(alignment: .leading, spacing: 4) { Group { Text("Borrowing") .font(.system(size: 13, weight: .regular)) + Text(" \(loan.loanAmount.currencyString)") .font(.system(size: 14, weight: .bold)) + Text(" over") .font(.system(size: 13, weight: .regular)) + Text(" \(loan.duration) years") .font(.system(size: 14, weight: .bold)) } Group { Text("at") .font(.system(size: 13, weight: .regular)) + Text(" \(loan.interestType.description)") .font(.system(size: 14, weight: .bold)) } .frame(maxWidth: .infinity, alignment: .leading) } VStack(alignment: .leading, spacing: 8) { Text("Repayment Frequency") .font(.system(size: 14, weight: .medium)) Picker(selection: $loan.repaymentFrequency, label: Text("Loan Type")) { ForEach(RepaymentFrequency.allCases) { frequency in Text(String(frequency.label)).tag(frequency) } } .pickerStyle(SegmentedPickerStyle()) } VStack(alignment: .leading) { Text("Extra Repayment") .font(.system(size: 14, weight: .medium)) TextField("0.0", value: $loan.extraRepayment, formatter: NumberFormatter.currencyInput) .textFieldStyle(RoundedBorderTextFieldStyle()) } .frame(maxWidth: .infinity, alignment: .leading) HStack(spacing: 24) { VStack(alignment: .leading, spacing: 4) { Text("Total loan repayments") .font(.system(size: 13, weight: .regular)) .foregroundColor(.secondary) Text(" \(loan.totalRepayments.currencyString)") .font(.system(size: 14, weight: .bold)) } .frame(minWidth: 150, alignment: .leading) VStack(alignment: .leading, spacing: 4) { Text("Total interest charged") .font(.system(size: 13, weight: .regular)) .foregroundColor(.secondary) Text(" \(loan.totalInterest.currencyString)") .font(.system(size: 14, weight: .bold)) } .frame(minWidth: 150, alignment: .leading) Spacer() } HStack(spacing: 24) { if let fixedPayment = loan.fixedPeriodRepayment { VStack(alignment: .leading, spacing: 4) { Text("Fixed Period Repayment") .font(.system(size: 13, weight: .regular)) .foregroundColor(.secondary) Text(" \(fixedPayment.currencyString)") .font(.system(size: 14, weight: .bold)) } .frame(minWidth: 150, alignment: .leading) } VStack(alignment: .leading, spacing: 4) { Text("Standard Repayment") .font(.system(size: 13, weight: .regular)) .foregroundColor(.secondary) Text(" \(loan.standardRepayment.currencyString)") .font(.system(size: 14, weight: .bold)) } .frame(minWidth: 150, alignment: .leading) Spacer() } } .padding() LineChart( loanAmount: loan.loanAmount, normalPayments: loan.normalRepaymentsTable.map{$0.closing}, extraPayments: loan.extraRepaymentsTable.map{$0.closing}) .frame(height: 200) .padding() AmortizationView(groups: loan.table, repayment: loan.interestType) } } .navigationTitle("Loan Details") .navigationBarItems(trailing: Button("Done") { presentationMode.wrappedValue.dismiss() } ) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView(loan: .init(loanAmount: 650000, duration: 30, repayment: .fixedPeriod(.init(duration: 4, fixedRate: 1.99, variableRate: 3.85)))) // ContentView(loan: .init(loanAmount: 650000, duration: 30, repayment: .standard(1.99))) } }
true
550f5a4f46f130ae7b90b66d9842b47e2af5f3e8
Swift
kipropkorir/Payoneer
/Payoneer/Extensions/NSString+Localization.swift
UTF-8
852
2.96875
3
[]
no_license
// // NSString+Localization.swift // Payoneer // // Created by Collins Korir on 22/05/2021. // import Foundation extension String { public var localized: String { return NSLocalizedString(self, comment: "") } public func localized(parameter: Int) -> String { let formatString = localized let resultString = String.localizedStringWithFormat(formatString, parameter) return resultString } public func localized(parameter: String) -> String { let formatString = localized let resultString = String.localizedStringWithFormat(formatString, parameter) return resultString } func capitalizingFirstLetter() -> String { return prefix(1).capitalized + dropFirst() } mutating func capitalizeFirstLetter() { self = self.capitalizingFirstLetter() } }
true
653c1e979a129061233ed78d57efffef1aea459b
Swift
s3714217/GoCar
/UserApp/GoCar/Control/BookingController/VerificationController.swift
UTF-8
4,229
2.640625
3
[]
no_license
// // VerificationController.swift // GoCar // // Created by Thien Nguyen on 27/3/21. // import UIKit import Firebase import FirebaseAuth class VerificationController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { var currentUser = User() let imagePicker = UIImagePickerController() @IBOutlet weak var nameLbl: UILabel! @IBOutlet var statusImg: UIImageView! @IBOutlet var statusImgDone: UIImageView! @IBOutlet weak var area_code: UITextField! @IBOutlet weak var number: UITextField! @IBOutlet weak var confirmBtn: UIButton! @IBOutlet weak var emailLbl: UITextField! private var blurEffect : UIBlurEffect = .init() private var blurEffectView : UIVisualEffectView = .init() @IBOutlet var popUp: UIView! @IBOutlet weak var errorNoti: UILabel! var photo: UIImage! var photoUploaded = 0 override func viewDidLoad() { super.viewDidLoad() statusImg.isHidden = false statusImgDone.isHidden = true nameLbl.text = currentUser.fullName emailLbl.text = Auth.auth().currentUser?.email confirmBtn.layer.cornerRadius = 12 } @IBAction func takePhoto(_ sender: Any) { imagePicker.sourceType = .camera imagePicker.allowsEditing = true imagePicker.delegate = self present(imagePicker, animated: true) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { picker.dismiss(animated: true) self.errorNoti.text = "" guard let image = info[.editedImage] as? UIImage else { print("No image found") photoUploaded = -1 return } if photoUploaded == 0 { self.statusImg.isHidden = true self.statusImgDone.isHidden = false self.photo = image photoUploaded = 1 } else{ errorNoti.text = "No image taken" } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return false } @IBAction func verifying(_ sender: Any) { if self.area_code.text!.count != 3 || self.number.text!.count > 11 || self.number.text!.count < 5{ self.errorNoti.text = "Invalid phone number" return } if !isValidEmail(email: self.emailLbl.text!){ self.errorNoti.text = "Invalid email" return } if self.photoUploaded < 1 { self.errorNoti.text = "Please upload your licence" return } self.currentUser.email = String(self.emailLbl.text!) self.currentUser.phone_number = String(self.area_code.text!) + String(self.number.text!) self.currentUser.userID = String(Auth.auth().currentUser!.uid) DBService().submitVerificationForm(user: self.currentUser, image: self.photo) showNotification() } private func isValidEmail(email: String) -> Bool{ let emailSynx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailPred = NSPredicate(format:"SELF MATCHES %@", emailSynx) return emailPred.evaluate(with: email) } private func showNotification(){ blurEffect = UIBlurEffect(style: .dark) blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = self.view.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] blurEffectView.backgroundColor = .clear self.view.addSubview(blurEffectView) self.view.addSubview(self.popUp) self.popUp.isHidden = false self.popUp.center = self.view.center self.popUp.layer.cornerRadius = 30 } /* // 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. } */ }
true
39c14c2d0b6c8d8c3c34f95fb61bd003595fe4dc
Swift
prince1809/MovieDB-ios
/MovieDB/ViewComponents/PlaceholderViews/Empty/EmptyPlaceholderView.swift
UTF-8
1,973
3.046875
3
[]
no_license
// // EmptyPlaceholderView.swift // MovieDB // // Created by Prince Kumar on 2019/09/18. // Copyright © 2019 Prince Kumar. All rights reserved. // import UIKit class EmptyPlaceholderView: UIView, NibLoadable { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var messageLabel: UILabel! private var animationDuration = 0.3 var isPresented: Bool = false var messageText: String? { didSet { guard let messageText = messageText else { return } messageLabel.text = messageText } } // MARK: - Lifecycle override func awakeFromNib() { super.awakeFromNib() setupUI() } private func setupUI() { imageView.image = #imageLiteral(resourceName: "EmptyPlaceholder") messageLabel.textColor = ColorPalette.lightBlueColor } private func show(animated: Bool = true, completion: ((Bool) -> Swift.Void)? = nil) { self.superview?.bringSubviewToFront(self) if animated { UIView.animate(withDuration: self.animationDuration, animations: { self.alpha = 1 }, completion: completion) } else { self.alpha = 1 completion?(true) } } } // MARK: - EMptyDisplayable extension EmptyPlaceholderView { static func show<T: EmptyPlaceholderView>( fromViewController viewController: UIViewController, animated: Bool = true, completion: ((Bool) -> Swift.Void)? = nil) -> T { guard let subview = loadFromNib() as? T else { fatalError("The subview is exptected to be of type \(T.self)") } viewController.view.addSubview(subview) // Configure constraints if needed subview.alpha = 0 subview.isPresented = true subview.superview?.sendSubviewToBack(subview) subview.show(animated: animated) { _ in } return subview } }
true
9f134116e788ceedbf64e516e12eecde53106dcc
Swift
geyoga/HPParallaxHeader
/HPParallaxHeader/Classes/HPParallaxHeader.swift
UTF-8
9,744
2.921875
3
[ "MIT" ]
permissive
// // HPParallaxHeader.swift // HPParallaxHeader // // Created by Hien Pham on 06/03/2021. // import Foundation import UIKit public enum HPParallaxHeaderMode { /** The option to scale the content to fill the size of the header. Some portion of the content may be clipped to fill the header’s bounds. */ case fill /** The option to scale the content to fill the size of the header and aligned at the top in the header's bounds. */ case topFill /** The option to center the content aligned at the top in the header's bounds. */ case top /** The option to center the content in the header’s bounds, keeping the proportions the same. */ case center /** The option to center the content aligned at the bottom in the header’s bounds. */ case bottom } public protocol HPParallaxHeaderDelegate: AnyObject { /** Tells the header view that the parallax header did scroll. The view typically implements this method to obtain the change in progress from parallaxHeaderView. @param parallaxHeader The parallax header that scrolls. */ func parallaxHeaderDidScroll(_ parallaxHeader: HPParallaxHeader) } open class HPParallaxHeader: NSObject { /** The content view on top of the UIScrollView's content. */ public var contentView: UIView { if let contentView = _contentView { return contentView } let contentView = HPParallaxView() contentView.parent = self contentView.clipsToBounds = true contentView.translatesAutoresizingMaskIntoConstraints = false heightConstraint = contentView.heightAnchor.constraint(equalToConstant: 0) _contentView = contentView return contentView } private var _contentView: UIView? /** Delegate instance that adopt the MXScrollViewDelegate. */ public weak var delegate: HPParallaxHeaderDelegate? /** The header's view. */ @IBOutlet public var view: UIView? { get { return _view } set { if (newValue != _view) { _view?.removeFromSuperview() _view = newValue updateConstraints() contentView.layoutIfNeeded() height = contentView.frame.size.height; heightConstraint?.constant = height heightConstraint?.isActive = true } } } private var _view: UIView? /** The header's default height. 0 by default. */ @IBInspectable public var height: CGFloat = 0 { didSet { if (height != oldValue) { //Adjust content inset adjustScrollViewTopInset((scrollView?.contentInset.top ?? 0) - oldValue + height) heightConstraint?.constant = height heightConstraint?.isActive = true layoutContentView() } } } /** The header's minimum height while scrolling up. 0 by default. */ @IBInspectable @objc public dynamic var minimumHeight: CGFloat = 0 { didSet { layoutContentView() } } /** The parallax header behavior mode. */ public var mode: HPParallaxHeaderMode = .fill { didSet { if (mode != oldValue) { updateConstraints() } } } /** The parallax header progress value. */ public private(set) var progress: CGFloat = 0 { didSet { if (oldValue != progress) { delegate?.parallaxHeaderDidScroll(self) } } } /** Loads a `view` from the nib file in the specified bundle. @param name The name of the nib file, without any leading path information. @param bundleOrNil The bundle in which to search for the nib file. If you specify nil, this method looks for the nib file in the main bundle. @param optionsOrNil A dictionary containing the options to use when opening the nib file. For a list of available keys for this dictionary, see NSBundle UIKit Additions. */ public func load(nibName name: String, bundle bundleOrNil: Bundle?, options: [UINib.OptionsKey: Any]) { let nib = UINib(nibName: name, bundle: bundleOrNil) nib.instantiate(withOwner: self, options: options) } weak var scrollView: UIScrollView? { didSet { if oldValue != scrollView { isObserving = true } } } private var positionConstraint: NSLayoutConstraint? private var heightConstraint: NSLayoutConstraint? private var isObserving: Bool = false // MARK: - Constraints func updateConstraints() { guard let view = view else { return } contentView.removeFromSuperview() scrollView?.addSubview(contentView) view.removeFromSuperview() contentView.addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false switch self.mode { case .fill: setFillModeConstraints() case .topFill: setTopFillModeConstraints() case .top: setTopModeConstraints() case .bottom: setBottomModeConstraints() case .center: setCenterModeConstraints() } setContentViewConstraints() } func setCenterModeConstraints() { view?.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true view?.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true view?.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true view?.heightAnchor.constraint(equalTo: contentView.heightAnchor).isActive = true } func setFillModeConstraints() { view?.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true view?.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true view?.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true view?.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true } func setTopFillModeConstraints() { view?.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true view?.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true view?.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true view?.heightAnchor.constraint(equalTo: contentView.heightAnchor).isActive = true let constraint = view?.bottomAnchor.constraint(equalTo: contentView.bottomAnchor) constraint?.priority = .defaultHigh constraint?.isActive = true } func setTopModeConstraints() { view?.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true view?.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true view?.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true view?.heightAnchor.constraint(equalToConstant: height).isActive = true } func setBottomModeConstraints() { view?.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true view?.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true view?.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true view?.heightAnchor.constraint(equalToConstant: height).isActive = true } func setContentViewConstraints() { guard let scrollView = scrollView else { return } contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true positionConstraint = contentView.topAnchor.constraint(equalTo: scrollView.topAnchor) positionConstraint?.isActive = true } // MARK: - Private Methods private func layoutContentView() { let minimumHeightReal = min(minimumHeight, height); let relativeYOffset = (scrollView?.contentOffset.y ?? 0) + (scrollView?.contentInset.top ?? 0) - height let relativeHeight = -relativeYOffset; positionConstraint?.constant = relativeYOffset heightConstraint?.constant = max(relativeHeight, minimumHeightReal) contentView.layoutSubviews() let div = height - minimumHeightReal progress = (contentView.frame.size.height - minimumHeightReal) / (div != 0 ? div : height) } private func adjustScrollViewTopInset(_ top: CGFloat) { var inset = scrollView?.contentInset ?? .zero //Adjust content offset var offset = scrollView?.contentOffset ?? .zero offset.y += inset.top - top scrollView?.contentOffset = offset //Adjust content inset inset.top = top scrollView?.contentInset = inset } // MARK: - KVO override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if context == &HPParallaxView.KVOContext { if keyPath == #keyPath(UIScrollView.contentOffset) { layoutContentView() } } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } }
true
97823ee35f623fa60c91b21a335689e5eefb70e2
Swift
ealesid/gbUIApplication
/gbUIApplication/Cells/FriendCollectionViewCell.swift
UTF-8
1,673
3.140625
3
[]
no_license
import UIKit protocol TapImageDelegate: class { func tapImage() func tapImageEnd() } class FriendCollectionViewCell: UICollectionViewCell { @IBOutlet weak var labelFriendName: UILabel! @IBOutlet weak var viewFriendPhoto: UIView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var imageViewLike: UIImageView! var likeImages: [UIImage] = [] func setFriend(_ friend: Friend) { imageView.image = friend.image imageView.setRounded() self.viewFriendPhoto.setShadow() self.viewFriendPhoto.addSubview(imageView) self.labelFriendName.text = friend.name self.imageViewLike.image = friend.isLiked ? UIImage(named: "heart-23") : UIImage(named: "heart-0") } } extension FriendCollectionViewCell { func createImagesArray(total: Int, prefix: String) -> [UIImage] { var imagesArray: [UIImage] = [] for count in 0..<total { imagesArray.append(UIImage(named: "\(prefix)-\(count)")!) } return imagesArray } func animate(imageview: UIImageView, images: [UIImage]) { imageview.animationImages = images imageview.animationDuration = 1.0 imageview.animationRepeatCount = 1 imageview.startAnimating() } } extension FriendCollectionViewCell: TapImageDelegate { func tapImage() { viewFriendPhoto.transform = CGAffineTransform(scaleX: 0.98, y: 0.98) self.animate(imageview: imageViewLike, images: createImagesArray(total: 23, prefix: "heart")) } func tapImageEnd() { viewFriendPhoto.transform = CGAffineTransform.identity } }
true
d623f04c303de25dffd938e887af3311d87a2dea
Swift
ihusnainalii/my-swift-journey
/SwiftUI-Instafilter/Instafilter/Instafilter/Reusables/Views/UIImagePickerWrapper/UIImagePickerWrapper.swift
UTF-8
1,362
2.71875
3
[ "MIT" ]
permissive
// // UIImagePickerWrapper.swift // Instafilter // // Created by CypherPoet on 11/29/19. // ✌️ // import SwiftUI struct UIImagePickerWrapper { typealias UIViewControllerType = UIImagePickerController @Environment(\.presentationMode) var presentationMode let onSelect: ((UIImage) -> Void) } // MARK: - UIViewControllerRepresentable extension UIImagePickerWrapper: UIViewControllerRepresentable { func makeCoordinator() -> UIImagePickerWrapper.Coordinator { Self.Coordinator(onSelect: self.imageSelected(_:)) } func makeUIViewController( context: UIViewControllerRepresentableContext<UIImagePickerWrapper> ) -> UIImagePickerController { let picker = UIImagePickerController() picker.delegate = context.coordinator return picker } func updateUIViewController( _ imagePickerController: UIImagePickerController, context: UIViewControllerRepresentableContext<UIImagePickerWrapper> ) { } } private extension UIImagePickerWrapper { func imageSelected(_ image: UIImage) { onSelect(image) presentationMode.wrappedValue.dismiss() } } // MARK: - Preview //struct UIImagePickerWrapper_Previews: PreviewProvider { // // static var previews: some View { // UIImagePickerWrapper() // } //}
true
cf98d95f8e9f6c4ea72caad8fd7e1192d5cb2338
Swift
dchssk/TableViewCapture
/TableViewCapture/TableViewAndOtherViewController.swift
UTF-8
2,339
2.75
3
[]
no_license
// // TableViewAndOtherViewController.swift // TableViewCapture // // Created by dchSsk on 2019/01/22. // Copyright © 2019 dchssk. All rights reserved. // import UIKit class TableViewAndOtherViewController: UIViewController, ImageProtocol { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var imageHolderView: UIView! /** TableViewとImageViewのキャプチャを生成する ・TableViewより上の部分は、self.viewからのキャプチャとする ・そのキャプチャに被せるようにtableViewのキャプチャを載せる */ func createViewImage() -> UIImage? { // キャプチャサイズ計算 let captureSize = CGSize(width: self.view.frame.size.width, height: self.imageHolderView.frame.size.height + tableView.contentSize.height) print("captureSize = \(captureSize)") // context生成 UIGraphicsBeginImageContextWithOptions(captureSize, false, 0.0) // tableViewのframe退避 let previousFrame = tableView.frame // UINavigationController調整 var topAdjust: CGFloat = 0 if let _ = self.navigationController { // 最上部に描画するViewからy座標の位置分調整する // もしくは、NavigationControllerの高さとステータスバーの高さを調整としても良い topAdjust = self.imageHolderView.frame.origin.y } if let context = UIGraphicsGetCurrentContext(){ // NavigationControllerが描画域に入らないように調整して描画 context.translateBy(x: 0, y: -topAdjust) self.view.layer.render(in: context) context.translateBy(x: 0, y: topAdjust) // tableViewの描画にむけ、contextをimageView分だけ移動 context.translateBy(x: 0, y: self.imageHolderView.frame.size.height) // tableviewのframeを、コンテンツサイズに一時的に変更 tableView.frame = CGRect(x:tableView.frame.origin.x, y:tableView.frame.origin.y, width:tableView.contentSize.width, height:tableView.contentSize.height) // tableViewのレイヤを描画 tableView.layer.render(in: context) } // tableViewのframe復帰 tableView.frame = previousFrame // image生成 let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext(); return image } override func viewDidLoad() { super.viewDidLoad() } }
true
af07816663cbafd9c72e05a7ae088a121cc8a67c
Swift
polgass/SwiftPlayground
/SwiftProgrammingLanguage/BasicOperators.playground/section-1.swift
UTF-8
2,643
4.375
4
[]
no_license
// Basic Operators // Assignment Operator let b = 10 var a = 5 a = b let (x, y) = (1, 2) //if x = y {} // error // Arithmetic Operators 1 + 2 5 - 3 2 * 3 10.0 / 2.5 "hello, " + "world" // Remainder Operator // a = (b × some multiplier) + remainder 9 % 4 -9 % 4 9 % -4 // Floating-Point Remainder Calculations 8 % 2.5 9 % 3.03 // Increment and Decrement Operators var i = 0 ++i i++ i-- --i var q = 0 let r = ++q let s = q++ // Unary Minus Operator let three = 3 let minusThree = -three let plusThree = -minusThree // Unary Plus Operator let minusSix = -6 let alsoMinusSix = +minusSix // Compound Assignment Operators var e = 1 e += 2 // Comparison Operators 1 == 1 // true, because 1 is equal to 1 2 != 1 // true, because 2 is not equal to 1 2 > 1 // true, because 2 is greater than 1 1 < 2 // true, because 1 is less than 2 1 >= 1 // true, because 1 is greater than or equal to 1 2 <= 1 // false, because 2 is not less than or equal to 1 let name = "world" if name == "world" { println("hello, world") } else { println("I'm sorry \(name), but I don't recognize you") } // Ternary Conditional Operator let contentHeight = 40 let hasHeader = true let rowHeight = contentHeight + (hasHeader ? 50 : 20) // Nil Coalescing Operator // (a ?? b) let defaultColorName = "red" var userDefinedColorName: String? var colorNameToUse = userDefinedColorName ?? defaultColorName userDefinedColorName = "green" colorNameToUse = userDefinedColorName ?? defaultColorName // Range Operators // Closed Range Operator for index in 1...5 { println("\(index) times 5 is \(index * 5)") } // Half-Open Range Operator let names = ["Anna", "Alex", "Brian", "Jack"] let count = names.count for i in 0..<count { println("Person \(i + 1) is called \(names[i])") } // Logical Operators // Logical NOT Operator let allowedEntry = false if !allowedEntry { println("ACCESS DENIED") } // Logical AND Operator let enteredDoorCode = true let passedRetinaScan = false if enteredDoorCode && passedRetinaScan { println("Welcome!") } else { println("ACCESS DENIED") } // Logical OR Operator let hasDoorKey = false let knowsOverridePassword = true if hasDoorKey || knowsOverridePassword { println("Welcome!") } else { println("ACCESS DENIED") } // Combining Logical Operators if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword { println("Welcome!") } else { println("ACCESS DENIED") } // Explicit Parentheses if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword { println("Welcome!") } else { println("ACCESS DENIED") }
true
88eda8e0fec89d2035787cf84f32df948591cce1
Swift
olliekav/turbo-ios
/Source/Path Configuration/PathConfigurationDecoder.swift
UTF-8
894
2.90625
3
[ "MIT" ]
permissive
import Foundation /// Internal struct for simplifying decoding /// since the public PathConfiguration can have multiple sources /// that update async struct PathConfigurationDecoder: Equatable { let settings: [String: AnyHashable] let rules: [PathRule] init(settings: [String: AnyHashable] = [:], rules: [PathRule] = []) { self.settings = settings self.rules = rules } } extension PathConfigurationDecoder { init(json: [String: Any]) throws { // rules must be present, settings are optional guard let rulesArray = json["rules"] as? [[String: AnyHashable]] else { throw JSONDecodingError.invalidJSON } let rules = try rulesArray.compactMap(PathRule.init) let settings = (json["settings"] as? [String: AnyHashable]) ?? [:] self.init(settings: settings, rules: rules) } }
true
a5139bc1a43a8c6b63897ac420c279db37ed23bd
Swift
damianogiusti/version-bumper
/VersionBumper/FileEditor/BaseRegexFileWriter.swift
UTF-8
1,633
2.9375
3
[ "Apache-2.0" ]
permissive
// // BaseRegexFileWriter.swift // VersionBumper // // Created by Damiano Giusti on 25/03/2020. // Copyright © 2020 Damiano Giusti. All rights reserved. // import Foundation class BaseRegexFileWriter: FileWriter { let versionNameRegex: NSRegularExpression let versionNumberRegex: NSRegularExpression let url: URL let contents: String init( url: URL, contents: String, versionNameRegex: NSRegularExpression, versionNumberRegex: NSRegularExpression ) { self.url = url self.contents = contents self.versionNameRegex = versionNameRegex self.versionNumberRegex = versionNumberRegex } func write( replacingOldVersion name: String, with newName: String, oldCode code: Int, with newCode: Int ) { if let nameMatch = versionNameRegex.matches(in: contents).first?.capture(at: 0, in: contents), let numberMatch = versionNumberRegex.matches(in: contents).first?.capture(at: 0, in: contents) { let newNameMatch = nameMatch.replacingOccurrences( of: name, with: newName ) let newNumberMatch = numberMatch.replacingOccurrences( of: String(code), with: String(newCode) ) try! contents .replacingOccurrences(of: nameMatch, with: newNameMatch) .replacingOccurrences(of: numberMatch, with: newNumberMatch) .write(to: url, atomically: true, encoding: .utf8) } else { fatalError("Cannot update version in file \(url)") } } }
true
9f38d197623856427d9cf96bf957e1ba37e1e5c9
Swift
pcjbird/10000ui
/10000ui-swift/UI/Complex/CalendarViewSample/CalendarView/CalendarDayCollectionReusableHeaderView.swift
UTF-8
1,337
2.8125
3
[ "MIT" ]
permissive
// // BSCalendarDayCollectionReusableView.swift // 10000ui-swift // // Created by 张亚东 on 16/4/27. // Copyright © 2016年 blurryssky. All rights reserved. // import UIKit enum CalendarViewSeparatorStyle { case relativeMargin(margin: CGFloat) case none } class CalendarDayCollectionReusableHeaderView: UICollectionReusableView { var separatorStyle: CalendarViewSeparatorStyle = .relativeMargin(margin: 5) { didSet { layoutIfNeeded() } } lazy var lineLayer: CAShapeLayer = { let lineLayer = CAShapeLayer() lineLayer.lineWidth = 1/UIScreen.main.scale return lineLayer }() override init(frame: CGRect) { super.init(frame: frame) layer.addSublayer(lineLayer) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let path = UIBezierPath() switch separatorStyle { case .relativeMargin(let margin): path.move(to: CGPoint(x: margin, y: bs.height/2)) path.addLine(to: CGPoint(x: bs.width - margin * 2, y: bs.height/2)) case .none: break } lineLayer.path = path.cgPath; } }
true
214d1efda27f30fc05e8bfff0ad7e4e065643d2b
Swift
axcs/FlickerFinder
/FlickerFinder/FlickerFinder/Uitls/ExString.swift
UTF-8
588
3.0625
3
[]
no_license
// // ExString.swift // FlickerFinder // // Created by BBVAMobile on 27/01/2021. // Copyright © 2021 Alexandre Carvalho. All rights reserved. // import Foundation protocol SearchTextSpaceRemover{} extension String: SearchTextSpaceRemover { public var isNotEmpty: Bool { return !isEmpty } } extension SearchTextSpaceRemover where Self == String { //MARK: - Removing space from String var removeSpace: String { if self.isNotEmpty { return self.components(separatedBy: .whitespaces).joined() }else{ return "" } } }
true
e3ee0f6b650e9461fd31462c732068e796ac7550
Swift
hbksilver/background-image-sellector
/Ex1/Ex1/ViewController.swift
UTF-8
1,614
2.796875
3
[]
no_license
// // ViewController.swift // Ex1 // // Created by hassan Baraka on 4/24/21. // import UIKit class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource{ let ArrayOfColors = ["Green", "Blue", "Yellow"] let colors = [UIColor.green, UIColor.blue, UIColor.yellow] func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return ArrayOfColors.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { let row = ArrayOfColors[row] return row } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { self.view.backgroundColor = colors[row] } @IBOutlet weak var image3: UIImageView! @IBOutlet weak var myPicker: UIPickerView! override func viewDidLoad() { super.viewDidLoad() self.myPicker.delegate = self self.myPicker.dataSource = self } @IBAction func Bottun1(_ sender: Any) { // if image3.isHidden == true { //image3.isHidden = false //} else { image3.isHidden = true // } } @IBAction func Button2(_ sender: Any) { // if image3.isHidden == true { image3.isHidden = false // } else { // image3.isHidden = true // } } }
true
e0e671dae7d35115a43d143635855d8fccd7b6fe
Swift
iOSDevLog/raywenderlich
/code/1747. Living Style Guides 1-Living-Style-Guides/1-Living-Style-Guides/Demo1/starter/Spacetime/Spacetime/Extensions/UIFont+Spacetime.swift
UTF-8
774
2.8125
3
[ "MIT" ]
permissive
// // UIFont+Spacetime.swift // Spacetime // // Created by Ellen Shapiro on 1/7/18. // Copyright © 2018 RayWenderlich.com. All rights reserved. // import UIKit /** Good resource for fonts and their font names available on iOS: http://iosfonts.com/ */ extension UIFont { public static func spc_standard(size: CGFloat) -> UIFont { return UIFont(name: "Futura-Medium", size: size)! } public static func spc_consensed(size: CGFloat) -> UIFont { return UIFont(name: "Futura-CondensedMedium", size: size)! } public static func spc_bold(size: CGFloat) -> UIFont { return UIFont(name: "Futura-Bold", size: size)! } public static func spc_condensedBold(size: CGFloat) -> UIFont { return UIFont(name: "Futura-CondensedExtraBold", size: size)! } }
true
04f9b56a710bd20f124f95745ac89f21d7f47b3f
Swift
TilakGondi/FrostNotes
/FrostNotes/Views/NotesViewController.swift
UTF-8
4,279
2.84375
3
[]
no_license
// // NotesViewController.swift // FrostNotes // // Created by Tilakkumar Gondi on 06/02/20. // Copyright © 2020 Tilakkumar Gondi. All rights reserved. // // PENDING FEATURE IMPLEMENTATIONS: // 1: Search notes by title, The search predicate is created in the DB handler, and the method to fetch the results from the db based on the search term is available in the NotesViewModel class. // 2: Filtering by dates is also partially implemented, as the calculation of time logic is not yet implemented when performing the fetch from db. // 3: Autolayout support for all the screen sizes and orientations is not completely implemented. import UIKit class NotesViewController: UIViewController { @IBOutlet weak var notesTable: UITableView! let addBtn = UIButton(type: .custom) var selectedNote:Note? //Datasource for the table in this viewController let dataSrc = NotesListDataSource() //ViewModel for the this viewController lazy var viewModel: NotesViewModel = { let viewModel = NotesViewModel(dataSource: dataSrc) return viewModel }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.navigationController?.isToolbarHidden = false // Fetch the notes from the db on loading the app. self.viewModel.loadNotesListFromDB() self.notesTable.dataSource = self.dataSrc self.notesTable.delegate = self //To add the observer/notifier on the datasource values to trigger the notes table view reload when the notes are fetched from the DB. self.dataSrc.data.addAndNotify(obsrv: self) { [weak self] in self?.notesTable.reloadData() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier { case "NoteDetails": let detailVC:DetailsViewController = segue.destination as! DetailsViewController // set the selected note to the note object in details view controller detailVC.note = self.selectedNote break default: print("default segue in NotesViewController") } } } extension NotesViewController{ func setUpNavigationControllerUI() { let label = UILabel() label.textColor = UIColor.black label.text = "Notes" label.font = .boldSystemFont(ofSize: 18) self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: label) addBtn.frame = CGRect(x: (self.view.frame.size.width/2)-50, y: self.view.frame.size.height-130, width: 100, height: 100) addBtn.setImage(UIImage(named: "add_note"), for: .normal) self.view.bringSubviewToFront(addBtn) addBtn.addTarget(self, action: #selector(addNewnote), for: .touchUpInside) //Iam using this depricated way of adding the floating button as i have used this earlier in my previously worked projects. Due to time constraints at my end, did not find the recommended way to implement this (I believe this could be achieved by other ways). if let window = UIApplication.shared.keyWindow { window.addSubview(addBtn) } } //Action on taping the floating add new note button. @objc func addNewnote() { self.performSegue(withIdentifier: "AddNote", sender: self) } override func viewWillAppear(_ animated: Bool) { //Refresh the list with any new additions to the db. self.viewModel.loadNotesListFromDB() //to put back the floating button and the left alligned title in the navigation bar view setUpNavigationControllerUI() super.viewWillAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) //To remove the floating add button. addBtn.removeFromSuperview() } } extension NotesViewController:UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //To get the note object on taping the note and navigating to details page self.selectedNote = self.dataSrc.data.value[indexPath.row] self.performSegue(withIdentifier: "NoteDetails", sender: self) } }
true
07ea03af413cb865aeb83029dbb66d4579a54ead
Swift
fs/FSHelper
/Source/FSExtensions/FSE+UIImage.swift
UTF-8
2,991
2.578125
3
[ "MIT" ]
permissive
// // FSE+UIImage.swift // Swift-Base // // Created by Kruperfone on 23.09.15. // Copyright © 2015 Flatstack. All rights reserved. // import UIKit public extension UIImage { convenience public init(fs_color color: UIColor) { let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0) UIGraphicsBeginImageContext(rect.size) let context: CGContext = UIGraphicsGetCurrentContext()! context.setFillColor(color.cgColor) context.fill(rect) UIGraphicsEndImageContext() let image = context.makeImage()! self.init(cgImage: image) } public func fs_aspectFillImageWithSize(_ size: CGSize) -> UIImage{ UIGraphicsBeginImageContextWithOptions(size, false, 0) let scale = max(size.width / self.size.width, size.height / self.size.height) let newSize = CGSize(width: ceil(self.size.width * scale), height: ceil(self.size.height * scale)) let frame = CGRect(x: ceil((size.width - newSize.width) / 2.0), y: ceil((size.height - newSize.height) / 2.0), width: newSize.width, height: newSize.height) self.draw(in: frame) let image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } public func fs_aspectFitImageWithSize(_ size: CGSize) -> UIImage { let scale = min(size.width / self.size.width, size.height / self.size.height) let targetSize = CGSize(width: ceil(self.size.width * scale), height: ceil(self.size.height * scale)) return self.fs_aspectFillImageWithSize(targetSize) } public final func fs_scaled(toSize size: CGSize) -> UIImage? { UIGraphicsBeginImageContextWithOptions(size, false, 0.0) self.draw(in: CGRect(x: 0.0, y: 0.0, size: size)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage } public final func fs_scaled(toWidth width: CGFloat) -> UIImage? { let scaleFactor = width / self.size.width let scaledSize: CGSize = CGSize(width: self.size.width * scaleFactor, height: self.size.height * scaleFactor) UIGraphicsBeginImageContext(scaledSize) self.draw(in: CGRect(x: 0.0, y: 0.0, size: scaledSize)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage } public var fs_base64: String { let imageData = self.pngData()! let base64String = imageData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) return base64String } }
true
ee7081405231ca379ff441a0739ed198ba6487ab
Swift
Zarif-Karim/Mobile-Application-Development
/iOS/Tute12/Tute12/gView.swift
UTF-8
1,883
2.96875
3
[]
no_license
// // gView.swift // Tute12 // // Created by Muhsana Chowdhury on 20/1/21. // import UIKit import CoreGraphics class gView: UIView { var currentShapeType: Int = 0 init(frame: CGRect, shape: Int) { super.init(frame: frame) self.currentShapeType = shape // shapeType was passed by ViewController File } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code //draw X let contextX = UIGraphicsGetCurrentContext() contextX?.setLineWidth(2.0) contextX?.setStrokeColor(UIColor.blue.cgColor) contextX?.move(to: CGPoint(x:100, y: 100)) contextX?.addLine(to: CGPoint(x: 200, y: 200)) contextX?.move(to: CGPoint(x:200, y: 100)) contextX?.addLine(to: CGPoint(x: 100, y: 200)) contextX?.strokePath() //draw rectangle let contextY = UIGraphicsGetCurrentContext() contextY?.setStrokeColor(UIColor.red.cgColor) contextY?.setLineWidth(2.0) let rectangle = CGRect(x: 100, y: 100, width: 100, height: 100) contextY?.addRect(rectangle) contextY?.strokePath() //draw circle let contextZ = UIGraphicsGetCurrentContext() contextZ?.setStrokeColor(UIColor.green.cgColor) contextZ?.setLineWidth(2.0) let circle = CGRect(x: 78, y: 78, width: 142, height: 148) contextZ?.addEllipse(in: circle) contextZ?.strokePath() } }
true
f4ccc8e8f118809b266f6b8a34175ab86c3af686
Swift
Jesus0414/PDM_Practica10
/PDM_Practica10-main/modelosJesus/modelosJesus/DetallesRestaurantController.swift
UTF-8
610
2.65625
3
[]
no_license
// // DetallesRestaurantController.swift // modelosJesus // // Created by Alumno on 10/6/21. // Copyright © 2021 Alumno. All rights reserved. // import Foundation import UIKit class DetallesRestaurantController : UIViewController{ var restaurant : Restaurant = Restaurant(nombre: "", direccion: "", horario: "") @IBOutlet weak var lblHorario: UILabel! @IBOutlet weak var lblDirreccion: UILabel! override func viewDidLoad() { self.title = restaurant.nombre lblDirreccion.text = restaurant.direccion lblHorario.text = restaurant.horario } }
true
bd9f3e8f8704906044f7be14f039912ab1ccd285
Swift
bbbbpage/LocalizationKit_iOS
/Sources/Core/LocalizationKit.swift
UTF-8
27,464
2.921875
3
[ "MIT" ]
permissive
// // Language.swift // Pods // // Created by Will Powell on 03/11/2016. // // import Foundation import SocketIO public enum LanguageDirection:String{ case rtl = "rtl" case ltr = "ltr" case unknown = "unknown" } public class Language:NSObject,NSCoding { public var localizedName:String = ""; public var key:String = ""; // language code eg. en, zh-Hans public var localizedNames:[String:Any]? // localized language names public var direction = LanguageDirection.unknown public var isPrimary:Bool = false init (localizedName:String, key:String, localizedNames:[String:Any]?, direction:LanguageDirection?){ self.key = key; self.localizedName = localizedName self.localizedNames = localizedNames self.direction = direction ?? .unknown } required convenience public init?(coder decoder: NSCoder) { if let localizedNameTemp = decoder.decodeObject(forKey: "localizedName") as? String, let keyTemp = decoder.decodeObject(forKey: "key") as? String { let localizedNamesTemp = decoder.decodeObject(forKey: "localizedNames") as? [String:String] var direction = LanguageDirection.ltr if let directionString = decoder.decodeObject(forKey: "direction") as? String, let newDirection = LanguageDirection.init(rawValue: directionString) { direction = newDirection } self.init(localizedName: localizedNameTemp, key: keyTemp, localizedNames: localizedNamesTemp, direction:direction) }else{ self.init(localizedName: "English", key: "en", localizedNames: nil, direction:LanguageDirection.ltr) } } public func encode(with aCoder: NSCoder) { aCoder.encode(self.localizedName, forKey: "localizedName") aCoder.encode(self.key, forKey: "key") aCoder.encode(self.direction.rawValue, forKey: "direction") if let localizationNames = self.localizedNames { aCoder.encode(localizationNames, forKey: "localizedNames") } } public func name(forLangageCode languageCode:String)->String?{ return localizedNames?[languageCode] as? String } public var localName:String?{ get{ return name(forLangageCode: key) } } } public class Localization { /** Remote server address */ public static var server:String = "https://www.localizationkit.com"; /** If the keys are empty show the localization key eg. en.Home.Title to highlight the missing keys */ public static var ifEmptyShowKey = false /** If the device language doesnt match any available and there are no primary languages take the first language in the list */ public static var alwaysSelectLanguageIfAvailable = true /** core socket */ static var socket:SocketIOClient? static var manager:SocketManager? /** App Key */ private static var appKey:String? /** Loaded language string */ private static var loadedLanguageTranslations:[AnyHashable:String]? /** Notification event fired when language is initially loaded of localization text is changed */ public static var ALL_CHANGE = Notification.Name(rawValue: "LOCALIZATION_CHANGED") public static var INLINE_EDIT_CHANGED = Notification.Name(rawValue: "LOCALIZATION_INLINE_EDIT") private static let storageLocation:String = "SELECTED_LANGUAGE" private static var _liveEnabled:Bool = false; /** Allow the inline editor screens using long press on the string field */ public static var allowInlineEdit = false { didSet{ if oldValue != allowInlineEdit { NotificationCenter.default.post(name: Localization.INLINE_EDIT_CHANGED, object: nil) } } } /** The build language is the initial language for the current language keys */ public static var buildLanguageCode = "en" /** Trim localizationkey */ public static func parse(str:String)->String{ let newString = str.replacingOccurrences(of: " ", with: "", options: .literal, range: nil) let character = CharacterSet(charactersIn:"0123456789.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").inverted return newString.trimmingCharacters(in: character); } /** Current language code */ public static var languageCode:String? { get{ return language?.key } } private static var _language:Language? { didSet{ saveSelectedLanguageCode() } } /** Selected current language */ public static var language:Language? { get{ return _language } } /** Get language iso-639-1 code for selected language */ public static var language639Code:String? { get { if let langCode = languageCode { if langCode.contains("-") { let languageParts = langCode.components(separatedBy: "-") return languageParts[0] }else{ return languageCode } } return nil } } /** save the current selected language */ private static func saveSelectedLanguageCode(){ if let language = _language, let appKey = self.appKey { let encodedData = NSKeyedArchiver.archivedData(withRootObject: language) let standard = UserDefaults.standard; standard.set(encodedData, forKey: "\(appKey)_\(storageLocation)"); standard.synchronize() } } /** Load current language */ private static func loadSelectedLanguageCode(_ completion: @escaping (_ language:Language?) -> Swift.Void)->Swift.Void{ let standard = UserDefaults.standard; if let appKey = self.appKey, let val = standard.data(forKey: "\(appKey)_\(storageLocation)") { if let storedLanguage = NSKeyedUnarchiver.unarchiveObject(with: val) as? Language { return completion(storedLanguage) } } let defs = UserDefaults.standard guard let languages:NSArray = (defs.object(forKey: "AppleLanguages") as? NSArray), let current:String = languages.object(at: 0) as? String else{ return } languageFromAvailableLanguages(languagecode: current, completion: completion) } private static func languageFromAvailableLanguages(languagecode:String, completion: @escaping (_ language:Language?) -> Swift.Void){ let current = languagecode availableLanguages { (languages) in if let language = findLanguage(languages: languages, languageKey: current) { return completion(language) } if current.contains("-") { let currentComponents = current.components(separatedBy: "-") let reducedCurrentComponents = currentComponents[0..<(currentComponents.count-1)] let newCurrent = reducedCurrentComponents.joined(separator: "-") if let language = findLanguage(languages: languages, languageKey: newCurrent) { return completion(language) } if newCurrent.contains("-") { let finalCurrentComponents = newCurrent.components(separatedBy: "-") let finalReducedCurrentComponents = finalCurrentComponents[0..<(finalCurrentComponents.count-1)] let finalNewCurrent = finalReducedCurrentComponents.joined(separator: "-") if let language = findLanguage(languages: languages, languageKey: finalNewCurrent) { return completion(language) } } } // Select primary language let primaryLanguage = languages.first(where: { (language) -> Bool in return language.isPrimary }) guard let primaryLang = primaryLanguage else { // Fall back to first available language if self.alwaysSelectLanguageIfAvailable { guard let fallbackLanguage = languages.first else { return completion(nil) } return completion(fallbackLanguage) } return completion(nil) } return completion(primaryLang) } } /** Find a language by code within language array */ private static func findLanguage(languages:[Language], languageKey:String)->Language? { let foundLanguage = languages.filter({ (language) -> Bool in return language.key == languageKey }) if foundLanguage.count == 1 { return foundLanguage[0] } return nil } /** If live updates are enabled */ public static var liveEnabled:Bool { get { return _liveEnabled; } set (newValue){ if(_liveEnabled != newValue){ _liveEnabled = newValue if(newValue){ startSocket(); }else{ // end socket if let socket = self.socket { socket.disconnect() } } } } } public static func stop(){ appKey = nil liveEnabled = false socket = nil manager = nil allowInlineEdit = false loadedLanguageTranslations = nil NotificationCenter.default.removeObserver(self, name: UserDefaults.didChangeNotification, object: nil) } /** Start Localization Service - Parameter appKey: API key - Parameter live: should enable dynamic update */ public static func start(appKey:String, live:Bool){ guard self.appKey != appKey else{ print("App Key already set") return } stop() liveEnabled = false loadedLanguageTranslations = nil self.appKey = appKey initialLanguage(); liveEnabled = live; } /** Start Localization Service - Parameter appKey: API key - Parameter useSettings: Use the settings bundle */ public static func start(appKey:String, useSettings:Bool){ guard self.appKey != appKey else{ print("App key already set") return } stop() self.appKey = appKey if useSettings { NotificationCenter.default.addObserver(self, selector: #selector(Localization.defaultsChanged), name: UserDefaults.didChangeNotification, object: nil) defaultsChanged() } initialLanguage(); } /** Start Localization Service - Parameter appKey: API key */ public static func start(appKey:String){ self.appKey = appKey initialLanguage(); } @objc public static func defaultsChanged(){ let userDefaults = UserDefaults.standard let val = userDefaults.bool(forKey: "live_localization"); if val == true, liveEnabled == false, let language = self.language { self.loadLanguage(language); } liveEnabled = val; allowInlineEdit = userDefaults.bool(forKey: "live_localization_inline"); } /** Save localization to local storage - parameter code: language 2 character code - parameter translation: translations associated with the language */ public static func saveLanguageToDisk(code:String, translation:[AnyHashable:String]){ guard let appKey = self.appKey else { return } let standard = UserDefaults.standard; standard.set(translation, forKey: "\(appKey)_\(code)"); standard.synchronize() } /** Load localization from local storage - Parameter code: language 2 character code */ public static func loadLanguageFromDisk(code:String){ guard let appKey = self.appKey else { return } let standard = UserDefaults.standard guard let data = standard.object(forKey: "\(appKey)_\(code)") as? [AnyHashable : String] else { return } loadedLanguageTranslations = data; NotificationCenter.default.post(name: Localization.ALL_CHANGE, object: self) } /** Request localization - Parameter code: language 2 character code */ private static func loadLanguage(_ language:Language){ loadLanguage(language: language) { return; } } /** Request localization - Parameter code: language 2 character code */ private static func loadLanguage(language:Language, _ completion: @escaping () -> Swift.Void){ guard let appKey = self.appKey else { return } loadLanguageFromDisk(code: language.key); let config = URLSessionConfiguration.default let session = URLSession(configuration: config) let urlString = Localization.server+"/v2/api/app/\(appKey)/language/\(language.key)" guard let url = URL(string: urlString as String)else{ return } session.dataTask(with: url) { (data, response, error) in guard let data = data, error == nil else { // TODO handle failed language load return } if (response as? HTTPURLResponse) != nil { do { let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary guard let jsonData = json?["data"] as? [AnyHashable:String] else{ return; } loadedLanguageTranslations = jsonData; if let translations = self.loadedLanguageTranslations { saveLanguageToDisk(code: language.key, translation: translations); } self.joinLanguageRoom() NotificationCenter.default.post(name: Localization.ALL_CHANGE, object: self) completion(); } catch { print("error serializing JSON: \(error)") } } }.resume() } /** Request Available Languages */ public static func availableLanguages(_ completion: @escaping ([Language]) -> Swift.Void){ let language = self.languageCode ?? "en" loadAvailableLanguages (languageCode: language) { (languages) in completion(languages) } } /** Request Available Languages */ public static func availableLanguages(languageCode:String,_ completion: @escaping ([Language]) -> Swift.Void){ loadAvailableLanguages (languageCode: languageCode) { (languages) in completion(languages) } } /** Load available languages from server */ private static func loadAvailableLanguages(languageCode:String, _ completion: @escaping ([Language]) -> Swift.Void){ guard let appKey = self.appKey else{ return } let config = URLSessionConfiguration.default let session = URLSession(configuration: config) let urlString = Localization.server+"/v2/api/app/\(appKey)/languages/" guard let url = URL(string: urlString as String) else{ return } session.dataTask(with: url) { (data, response, error) in if (response as? HTTPURLResponse) != nil { do { guard let data = data else{ //todo add error case return } let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? NSDictionary guard let languages = json?["languages"] as? [[String:AnyHashable]] else{ return; } let languagesOutput = languages.compactMap({ (language) -> Language? in guard let languageKey = language["key"] as? String else { return nil } var languageNameLocalized = languageKey var languageNames = [String:Any]() if let languageName = language["name"] as? [String:Any] { languageNames = languageName if let langCode = languageName[languageCode] as? String { languageNameLocalized = langCode } } var direction = LanguageDirection.ltr if let directionString = language["direction"] as? String, let newDirection = LanguageDirection.init(rawValue: directionString) { direction = newDirection } let lang = Language(localizedName: languageNameLocalized, key: languageKey, localizedNames:languageNames, direction:direction) if let isPrimary = language["primary"] as? Bool { lang.isPrimary = isPrimary } return lang }) completion(languagesOutput) } catch { print("error serializing JSON: \(error)") } } }.resume() } /** Load initial language */ private static func initialLanguage(){ guard let appKey = self.appKey, let url = URL(string: "\(server)/v2/app/#/app/\(appKey)") else { return } print("LocalizationKit:", url) loadSelectedLanguageCode { (language) in guard let lang = language else { print("No language available") return } setLanguage(lang) } } /** Reset to device's natural language */ public static func resetToDeviceLanguage(_ completion: ((_ language:Language?)->Void)? = nil){ let defs = UserDefaults.standard guard let languages:NSArray = (defs.object(forKey: "AppleLanguages") as? NSArray), let current:String = languages.object(at: 0) as? String else{ return } languageFromAvailableLanguages(languagecode: current) { (language) in guard let lang = language else { return } setLanguage(lang, { if let comp = completion { comp(language) } }) } } /** Get the Notification.Name for a Localization Key for a Highlight event - Parameter localizationKey: localization key for element */ public static func highlightEvent(localizationKey:String) -> Notification.Name{ return Notification.Name(rawValue: "LOC_HIGHLIGHT_\(localizationKey)") } /** Get the Notification.Name for a Localization Key for a Text/Localization event - Parameter localizationKey: localization key for element */ public static func localizationEvent(localizationKey:String) -> Notification.Name{ return Notification.Name(rawValue: "LOC_TEXT_\(localizationKey)") } /** Start socket server */ private static func startSocket(){ guard let url = URL(string: server) else { print("Start Socket URL Incorrect") return } let manager = SocketManager(socketURL: url, config: [.log(false), .compress, .path("/v2/socket.io")]) self.manager = manager let socket = manager.defaultSocket socket.on("connect") { data, ack in self.joinLanguageRoom() if let appKey = self.appKey { let appRoom = "\(appKey)_app" sendMessage(type: "join", data: ["room":appRoom]) } NotificationCenter.default.post(name: ALL_CHANGE, object: self) } socket.on("languages") {data,ack in //let dictionary = data[0] as! [AnyHashable : Any] } socket.on("highlight"){ data,ack in if let dictionary = data[0] as? [AnyHashable : Any] { guard let meta = dictionary["meta"] as? String else { return; } NotificationCenter.default.post(name: self.highlightEvent(localizationKey: meta), object: self) } } socket.on("text") { data,ack in if let dictionary = data[0] as? [AnyHashable : Any] { guard let meta = dictionary["meta"] as? String else { return; } if let value = dictionary["value"] as? String { self.loadedLanguageTranslations?[meta] = value NotificationCenter.default.post(name: self.localizationEvent(localizationKey: meta), object: self) } } } socket.connect() self.socket = socket } private static var hasJoinedLanguageRoom:Bool = false private static func joinRoom(name:String){ self.sendMessage(type: "join", data: ["room":name]) } /** Subscribe to current language updates */ private static func joinLanguageRoom(){ guard liveEnabled == true else { return } guard let appKey = self.appKey, let langCode = self.language?.key else{ return } hasJoinedLanguageRoom = true let languageRoom = "\(appKey)_\(langCode)" joinRoom(name:languageRoom) } private static func leaveRoom(name:String){ self.sendMessage(type: "leave", data: ["room":name]) } /** Subscribe to current language updates */ private static func leaveLanguageRoom(){ if let appKey = self.appKey, let languageCode = self.languageCode { let languageRoom = "\(appKey)_\(languageCode)" leaveRoom(name:languageRoom) } } /** Send Message - Parameter type: type string - Parameter data: data object */ private static func sendMessage(type:String, data:SocketData...){ if socket?.status == .connected { socket?.emit(type, with: data) } } /** Set Language Code - Parameter language: language 2 character code */ public static func setLanguage(_ language:String){ let languageCode = language self.languageFromAvailableLanguages(languagecode: languageCode) { (language) in if let lang = language { self.setLanguage(lang) } } } /** Set Language Code with completion call back - Parameter language: language 2 character code - Parameter completion: function called when language has been loaded */ public static func setLanguage(_ language:String, _ completion: @escaping () -> Swift.Void){ let languageCode = language self.languageFromAvailableLanguages(languagecode: languageCode) { (language) in if let lang = language { self.setLanguage(lang, completion) } } } /** Set Language Code with language object - Parameter language: language object */ public static func setLanguage(_ language:Language){ setLanguage(language) { return; } } /** Set Language Code with language object - Parameter languageNew: language object - Parameter completion: completion block */ public static func setLanguage(_ languageNew:Language, _ completion: @escaping () -> Swift.Void){ if language?.key != languageNew.key { leaveLanguageRoom(); _language = languageNew loadLanguage(language: languageNew, { completion(); }) }else{ completion(); } } /** Set new language key - Parameter key: the new key object that is created - Parameter value: the starting text used - Parameter language: the language the value text is for. If left blank uses the default */ public static func set(_ key:String,value:String, language:String? = nil){ guard let appKey = self.appKey, let languageCode = Localization.languageCode else { print("You havent specified an app key") return } var data = ["appuuid":appKey, "key":key, "value":value, "language": languageCode] if language != nil { data["language"] = language } if liveEnabled && socket?.status == .connected { loadedLanguageTranslations?[key] = value sendMessage(type: "translation:save", data: data) NotificationCenter.default.post(name: self.localizationEvent(localizationKey: key), object: self) } } /** Get translation for text - Parameter key: the unique translation text identifier - Parameter alternate: the default text for this key */ public static func get(_ key:String, alternate:String) -> String{ guard let appKey = self.appKey else { print("Cannot get without appkey") return alternate } let m = self.loadedLanguageTranslations var keyString = "NA-\(key)" if let languageCode = self.languageCode { keyString = "\(languageCode)-\(key)" } if m == nil { if alternate.count == 0 && ifEmptyShowKey == true { return keyString } return alternate } guard let localisation = loadedLanguageTranslations?[key] else { if liveEnabled && languageCode != nil && socket?.status == .connected { self.loadedLanguageTranslations?[key] = alternate if alternate != key && alternate != keyString { self.sendMessage(type: "key:add", data: ["appuuid":appKey, "key":key, "language":buildLanguageCode, "raw":alternate]) }else{ self.sendMessage(type: "key:add", data: ["appuuid":appKey, "key":key, "language":buildLanguageCode]) } } if alternate.count == 0 && ifEmptyShowKey == true { return keyString } return alternate; } if localisation.count == 0 && ifEmptyShowKey == true { return keyString } return localisation } }
true
eabc93e713c9c5aa475300088b9254695de6ddfb
Swift
XiaowenMa/iOS_Development
/XiaowenMa-Lab4/XiaowenMa-Lab4/SignupViewController.swift
UTF-8
3,966
2.765625
3
[]
no_license
// // SignupViewController.swift // XiaowenMa-Lab4 // // Created by 马晓雯 on 7/13/20. // Copyright © 2020 Xiaowen Ma. All rights reserved. // import UIKit import FirebaseAuth //Reference for firebase sign up and log in:https://www.youtube.com/watch?v=1HN7usMROt8 class SignupViewController: UIViewController { @IBOutlet weak var username: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var signInButton: UIButton! @IBOutlet weak var errorMessage: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. errorMessage.alpha=0 navigationItem.title="Join Us" signInButton.layer.cornerRadius=15; signInButton.layer.backgroundColor=UIColor.systemGray6.cgColor } func validateFileds()->String?{ //check if name and password are properly filled if(username.text?.trimmingCharacters(in: .whitespacesAndNewlines)==""||password.text?.trimmingCharacters(in: .whitespacesAndNewlines)==""){ return "Please Fill in Both Fields!" } else{ let emailValidation=NSPredicate(format: "SELF MATCHES %@","^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,}$") if(emailValidation.evaluate(with: username.text?.trimmingCharacters(in: .whitespacesAndNewlines))==false){ return "Invalid email address format." } } return nil } @IBAction func signInClicked(_ sender: Any) { //validate let error=validateFileds() if error != nil{ let InputAlert = UIAlertController(title: "Input Fileds Not Valid", message: "Error: \(error!)", preferredStyle: .alert) InputAlert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil)) self.present(InputAlert, animated: true, completion: nil) //errorMessage.text = error! //errorMessage.alpha=1 } else{ //clean up email and pwd let email = username.text!.trimmingCharacters(in: .whitespacesAndNewlines) let pwd = password.text!.trimmingCharacters(in: .whitespacesAndNewlines) //create a user errorMessage.text="Signing up..." errorMessage.textColor = .black errorMessage.alpha=1 Auth.auth().createUser(withEmail: email, password: pwd){(result,err) in if err != nil{ let SignUpAlert = UIAlertController(title: "Sign Up Failed", message: "Error: \(String(describing: err!.localizedDescription))", preferredStyle: .alert) SignUpAlert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil)) self.present(SignUpAlert, animated: true, completion: nil) //self.errorMessage.text = "Error in Creating User" //self.errorMessage.alpha=1 self.errorMessage.text="" } else{ //go to home scree self.goToHomeScreen() } } } } func goToHomeScreen(){ let homeTabVarViewController=storyboard?.instantiateViewController(identifier: "Home") as! myTabController homeTabVarViewController.user=username.text!.trimmingCharacters(in: .whitespacesAndNewlines) view.window?.rootViewController=homeTabVarViewController view.window?.makeKeyAndVisible() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
true
40307f56d357599918ef7931643c124a12defce4
Swift
xiyuyanhen/XiyuyanhenTools
/XYYHTools/XYYHTools/Code/Base/XYKits/Extension/UIImage+Extension.swift
UTF-8
7,950
2.890625
3
[]
no_license
// // UIImage+Extension.swift // EStudy // // Created by 细雨湮痕 on 2018/12/21. // Copyright © 2018 xiyuyanhen. All rights reserved. // import Foundation extension UIImage { static let NetworkDefaultImageName : String = "Public_Image_Default" static let NetworkDefaultImage : UIImage? = UIImage(named: UIImage.NetworkDefaultImageName) } extension UIImage { func xyCaculateHeight(_ width: CGFloat) -> CGFloat { return CaculateHeightBySize(width: width, referenceSize: self.size) } } extension UIImage { /** * @description 从图片缓存库中清除指定的图片 * * @param urlOrNil 图片路径 * */ static func ClearImageCacheBy(URL urlOrNil: String?) { guard let urlStr = urlOrNil, let url = URL(string: urlStr) else { return } self.ClearImageCacheBy(URL: url) } /** * @description 从图片缓存库中清除指定的图片 * * @param urlOrNil 图片路径 * */ static func ClearImageCacheBy(URL urlOrNil: URL?) { guard let url = urlOrNil else { return } let fetcher = NetworkFetcher<UIImage>(URL: url) Shared.imageCache.remove(key: fetcher.key) } /** * @description 将指定的图片添加到图片缓存库 * * @param key 图片索引 * */ @discardableResult static func SetImageCacheBy(key keyOrNil: String?, image imageOrNil: UIImage?) -> Bool { guard let key = keyOrNil, let image = imageOrNil else { return false } Shared.imageCache.set(value: image, key: key) return true } } extension UIImage{ convenience init?(xyImgName imgNameOrNil: String?) { guard let imgName = imgNameOrNil else { return nil } self.init(named: imgName) } convenience init?(imgPath imgPathOrNil: String?) { guard let imgPath = imgPathOrNil else { return nil } let url = URL(fileURLWithPath: imgPath) guard let imgData = try? Data(contentsOf: url, options: Data.ReadingOptions.dataReadingMapped) else { return nil } self.init(data: imgData) } /** * @description 生成矩形图片 * * @param color 背景颜色 * * @param size 矩形大小 * * @return 矩形图片 */ class func ImageWithColor(_ color:UIColor, size: CGSize = CGSize(width: 1.0, height: 1.0)) -> UIImage? { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContext(rect.size) var imageOrNil: UIImage? = nil if let context = UIGraphicsGetCurrentContext() { context.setFillColor(color.cgColor) context.fill(rect) if let image = UIGraphicsGetImageFromCurrentImageContext() { imageOrNil = image } } UIGraphicsEndImageContext() return imageOrNil } /** * @description 生成圆形图片 * * @param diameter 直径 * * @param color 背景颜色 * * @return 圆形图片 */ class func ImageCircleWith(_ diameter: CGFloat, color:UIColor) -> UIImage? { let rect = CGRect(x: 0, y: 0, width: diameter, height: diameter) /// 半径 let radius: CGFloat = diameter/2.0 UIGraphicsBeginImageContext(rect.size) var imageOrNil: UIImage? = nil if let context = UIGraphicsGetCurrentContext() { context.addArc(center: CGPoint(x: radius, y: radius), radius: radius, startAngle: 0, endAngle: CGFloat.pi*2.0, clockwise: true) context.setFillColor(color.cgColor) context.fillPath() if let image = UIGraphicsGetImageFromCurrentImageContext() { imageOrNil = image } } UIGraphicsEndImageContext() return imageOrNil } func imageResize(size : CGSize) -> UIImage { let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions( size, false, scale) self.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) let newImg = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImg! } func grayImage() -> UIImage { let imageRef:CGImage = self.cgImage! let width:Int = imageRef.width let height:Int = imageRef.height let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceGray() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue) let context:CGContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)! let rect:CGRect = CGRect.init(x: 0, y: 0, width: width, height: height) context.draw(imageRef, in: rect) let outPutImage:CGImage = context.makeImage()! let newImage:UIImage = UIImage.init(cgImage: outPutImage, scale: self.scale, orientation: self.imageOrientation) return newImage } } // MARK: - Image From String extension UIImage { static func CreateBy(view: UIView, size: CGSize) -> UIImage? { //UIGraphicsBeginImageContextWithOptions(区域大小, 是否是非透明的, 屏幕密度); UIGraphicsBeginImageContextWithOptions(size, true, UIScreen.main.scale) guard let imageContext = UIGraphicsGetCurrentContext() else { return nil } view.layer.render(in: imageContext) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } static func CreateBy(attText attTextOrNil: NSAttributedString?, size: CGSize) -> UIImage? { guard let attText = attTextOrNil else { return nil } let label = BaseLabel.newAutoLayout() label.setBackgroundColor(customColor: .xe5e5e5) .setAttributedText(attText) // 添加一个像素以解决生成的图片底部有一条黑线 var newSize = size newSize.height += 1.0 label.frame = CGRect(origin: CGPoint.zero, size: newSize) label.layoutIfNeeded() return self.CreateBy(view: label, size: size) } static func CreateBy(attText attTextOrNil: NSAttributedString?, preferceWidth: CGFloat) -> UIImage? { guard let attText = attTextOrNil else { return nil } let label = BaseLabel.newAutoLayout() label.setBackgroundColor(customColor: .xe5e5e5) .setAttributedText(attText) let size = label.sizeThatFits(CGSize(width: preferceWidth, height: 0)) label.frame = CGRect(origin: CGPoint.zero, size: size) label.layoutIfNeeded() return self.CreateBy(view: label, size: size) } /// 加载中... static var LoadingAttText : NSAttributedString { var loadingAttTextModel = NSMutableAttributedString.AttributesModel(text: "加载中...", fontSize: 18, textColor: XYColor.CustomColor.x666666) loadingAttTextModel.addAttFont(font: XYFont.BoldFont(size: 18)) loadingAttTextModel.addAttParagraphStyle(alignment: .center, lineSpacing: 8, firstLineIndent: nil) return loadingAttTextModel.attributedString() } }
true
e62f2e5cec1ab153a232ec8ab1399a9802a9cb86
Swift
ronnievoss/Code-Test-Ronnie-Voss
/Code Test Ronnie Voss/EditableCell.swift
UTF-8
1,414
2.71875
3
[]
no_license
// // EditableCell.swift // Code Test Ronnie Voss // // Created by Ronnie Voss on 10/11/17. // Copyright © 2017 Ronnie Voss. All rights reserved. // import Foundation import UIKit final class EditableCell: UITableViewCell { @IBOutlet weak var textField: UITextField! @IBOutlet weak var label: UILabel! @IBOutlet weak var textFieldLabel: UILabel! @IBOutlet weak var addressLabel: UITextField! @IBOutlet weak var address1: UITextField! @IBOutlet weak var address2: UITextField! @IBOutlet weak var city: UITextField! @IBOutlet weak var state: UITextField! @IBOutlet weak var zipcode: UITextField! @IBOutlet weak var phoneLabel: UITextField! @IBOutlet weak var phoneNumber: UITextField! @IBOutlet weak var emailLabel: UITextField! @IBOutlet weak var emailAddress: UITextField! enum Field: Int { case firstName = 1 case lastName = 2 case birthdate = 3 case addressLabel = 4 case address1 = 5 case address2 = 6 case city = 7 case state = 8 case zipcode = 9 case phoneLabel = 10 case phoneNumber = 11 case emailLabel = 12 case emailAddress = 13 } var isEditable: Bool = false { didSet { textField?.isEnabled = isEditable textField?.borderStyle = isEditable ? .roundedRect : .none } } }
true
6d258bcd063e269bfdd8bfeb2df7883de5957dbd
Swift
matiasgualino/OpenHABSwift
/GLAD/SetpointUITableViewCell.swift
UTF-8
3,228
2.625
3
[]
no_license
// // SetpointUITableViewCell.swift // GLAD // // Created by Matias Gualino on 3/4/15. // Copyright (c) 2015 Glad. All rights reserved. // import Foundation import UIKit class SetpointUITableViewCell : GenericUITableViewCell { var widgetSegmentedControl : UISegmentedControl! @IBOutlet weak private var label : UILabel! required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.widgetSegmentedControl = self.viewWithTag(300) as? UISegmentedControl self.selectionStyle = UITableViewCellSelectionStyle.None self.separatorInset = UIEdgeInsetsZero } override func displayWidget() { self.label.text = self.widget.labelText() self.label.textColor = UIColor.whiteColor() var widgetValue : String? if self.widget.item.state == "Uninitialized" { widgetValue = "N/A" } else { widgetValue = String(format:"%.01f", self.widget.item.stateAsFloat()) } self.widgetSegmentedControl.setTitle(widgetValue, forSegmentAtIndex: 1) self.widgetSegmentedControl.addTarget(self, action: "pickOne:", forControlEvents: UIControlEvents.ValueChanged) self.detailTextLabel?.font = UIFont(name: "HelveticaNeue", size: 14.0) self.label.font = UIFont(name: "HelveticaNeue", size: 15.0) } func pickOne(sender: AnyObject) { var segmentedControl = sender as? UISegmentedControl println(String(format:"Setpoint pressed %d", segmentedControl!.selectedSegmentIndex)) if segmentedControl?.selectedSegmentIndex == 1 { self.widgetSegmentedControl.selectedSegmentIndex = -1 } else if segmentedControl?.selectedSegmentIndex == 0 { if self.widget.item.state == "Uninitialized" { self.widget.sendCommand(self.widget.minValue) } else { if self.widget.minValue != nil { if self.widget.item.stateAsFloat() - (self.widget.step as NSString).floatValue >= (self.widget.minValue as NSString).floatValue { self.widget.sendCommand(String(format:"%.01f", self.widget.item.stateAsFloat() - (self.widget.step as NSString).floatValue)) } } else { self.widget.sendCommand(String(format:"%.01f", self.widget.item.stateAsFloat() - (self.widget.step as NSString).floatValue)) } } } else if segmentedControl?.selectedSegmentIndex == 2 { if self.widget.item.state == "Uninitialized" { self.widget.sendCommand(self.widget.minValue) } else { if self.widget.maxValue != nil { if self.widget.item.stateAsFloat() + (self.widget.step as NSString).floatValue <= (self.widget.maxValue as NSString).floatValue { self.widget.sendCommand(String(format:"%.01f", self.widget.item.stateAsFloat() + (self.widget.step as NSString).floatValue)) } } else { self.widget.sendCommand(String(format:"%.01f", self.widget.item.stateAsFloat() + (self.widget.step as NSString).floatValue)) } } } } }
true
c7f08207256bdcd8c7e5fe64056e99516f4f3360
Swift
grisvladko/COVIDStatisticsGov
/COVIDStatisticsGov/delegates/MainTableViewDelegate/MainTableViewDelegate.swift
UTF-8
1,258
2.53125
3
[]
no_license
// // MainTableViewDelegate.swift // COVIDStatisticsGov // // Created by hyperactive on 17/11/2020. // Copyright © 2020 hyperactive. All rights reserved. // import UIKit class MainTableViewDelegate: NSObject, UITableViewDelegate, UITableViewDataSource { var data: Any! var views: [UIView] init(_ views : [UIView]) { self.views = views } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "mainCell", for: indexPath) as! MainTableViewCell cell.clean() cell.setup(views[indexPath.row]) cell.backgroundColor = .clear return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { var height: CGFloat = 0 switch indexPath.row { case 0: height = views[0].bounds.height case 1: height = views[1].bounds.height case 2: height = views[2].bounds.height default: break } return height } }
true
75493dd3e282691f5652010f7523d14e680e6e4f
Swift
kevintooley/library_app
/MyLibrary/Views/BookDetail.swift
UTF-8
2,443
3.15625
3
[]
no_license
// // BookDetail.swift // MyLibrary // // Created by Kevin Tooley on 8/5/21. // import SwiftUI struct BookDetail: View { @EnvironmentObject var model:BookModel var book: Book @State var starType = "" @State var rating = 1 // init() { // starType = book.isFavourite ? "star.fill" : "star" // } var body: some View { VStack { Spacer() NavigationLink( destination: BookContent(book: book), label: { VStack { Text("Read Now!") .font(.largeTitle) .foregroundColor(Color.black) Image("cover\(book.id)") .resizable() .scaledToFit() } }) Button(action: { model.updateFavorite(bookIndex: book.id) starType = book.isFavourite ? "star.fill" : "star" }, label: { VStack { Text("Mark for Later") .font(.headline) .foregroundColor(Color.black) Image(systemName: starType) .resizable() .foregroundColor(.yellow) .frame(width: 30, height: 30) } }).padding() .onAppear(perform: { starType = book.isFavourite ? "star.fill" : "star" }) Text("Rate \(book.title)") Picker("", selection: $rating) { /*@START_MENU_TOKEN@*/Text("1").tag(1)/*@END_MENU_TOKEN@*/ /*@START_MENU_TOKEN@*/Text("2").tag(2)/*@END_MENU_TOKEN@*/ Text("3").tag(3) Text("4").tag(4) Text("5").tag(5) }.pickerStyle(SegmentedPickerStyle()) .padding() .onChange(of: rating, perform: { value in model.updateRating(bookIndex: book.id, newRating: rating) }) Spacer() } .onAppear { rating = book.rating } .navigationBarTitle(book.title) } } struct BookDetail_Previews: PreviewProvider { static var previews: some View { BookDetail(book: Book()) .environmentObject(BookModel()) } }
true
ecbe4babb1dfff2b5717cbca3296812ed791790b
Swift
ty0x2333/TyBattleCity
/TyBattleCity/Tank.swift
UTF-8
8,131
2.90625
3
[ "MIT" ]
permissive
// // Tank.swift // TyBattleCity // // Created by luckytianyiyan on 2017/8/3. // Copyright © 2017年 luckytianyiyan. All rights reserved. // import SceneKit enum Direction: Int { case up case right case down case left var offset: CGPoint { return offset(unit: CGPoint(x: 0.5, y: 0.5)) } func offset(unit: CGPoint) -> CGPoint { switch self { case .up: return CGPoint(x: 0, y: -unit.y) case .right: return CGPoint(x: unit.x, y: 0) case .down: return CGPoint(x: 0, y: unit.y) case .left: return CGPoint(x: -unit.x, y: 0) } } static func direction(from src: CGPoint, to dst: CGPoint) -> Direction? { if dst.x > src.x { return .right } else if dst.x < src.x { return .left } else if dst.y > src.y { return .down } else if dst.y < src.y { return .up } return nil } } class Bullet: SCNNode { var body: SCNNode weak var owner: SCNNode? init(owner: SCNNode? = nil, scale: Float = 1) { let scene = SCNScene(named: "Assets.scnassets/tank.scn")! body = scene.rootNode.childNode(withName: "bullet", recursively: true)! super.init() self.owner = owner body.position = SCNVector3() addChildNode(body) let physicsBody = SCNPhysicsBody(type: .dynamic, shape: SCNPhysicsShape(geometry: SCNSphere(radius: CGFloat(0.05 * scale)), options: nil)) physicsBody.mass = 0 physicsBody.categoryBitMask = CollisionMask.bullet.rawValue physicsBody.collisionBitMask = CollisionMask.bullet.rawValue | CollisionMask.obstacles.rawValue | CollisionMask.tank.rawValue physicsBody.contactTestBitMask = CollisionMask.bullet.rawValue | CollisionMask.obstacles.rawValue | CollisionMask.tank.rawValue self.physicsBody = physicsBody } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class Tank: SCNNode { enum State: Int { case normal case moving case correcting } var body: SCNNode var launchingPoint: SCNNode var firingRange: CGFloat = Config.tankFiringRange var bulletSpeed: CGFloat = Config.bulletSpeed var firingRate: TimeInterval = Config.FiringRate.tank var movingSpeed: Float = 2.5 var nearNextPosition: float2 { let mapPosition = float2(x: position.x, y: position.z) let remainderX = mapPosition.x.truncatingRemainder(dividingBy: 0.5) let remainderY = mapPosition.y.truncatingRemainder(dividingBy: 0.5) let floorX = floor(mapPosition.x / 0.5) * 0.5 let floorY = floor(mapPosition.y / 0.5) * 0.5 var dstX: Float = position.x var dstY: Float = position.z switch direction { case .up: dstY = floorY break case .down: dstY = abs(remainderY) > 0 ? floorY + 0.5 : position.z break case .left: dstX = floorX break case .right: dstX = abs(remainderX) > 0 ? floorX + 0.5 : position.x break } return float2(x: dstX, y: dstY) } var nearPosition: float2 { let mapPosition = float2(x: position.x, y: position.z) let floorX = floor(mapPosition.x / 0.5) * 0.5 let floorY = floor(mapPosition.y / 0.5) * 0.5 var dstX: Float = floorX var dstY: Float = floorY switch direction { case .down: let remainderY = mapPosition.y.truncatingRemainder(dividingBy: 0.5) dstY = abs(remainderY) > 0 ? floorY + 0.5 : position.z break case .right: let remainderX = mapPosition.x.truncatingRemainder(dividingBy: 0.5) dstX = abs(remainderX) > 0 ? floorX + 0.5 : position.x break default: break } return float2(x: dstX, y: dstY) } var direction: Direction = .down { didSet { switch direction { case .right: eulerAngles.y = Float.pi / 2 case .left: eulerAngles.y = -Float.pi / 2 case .up: eulerAngles.y = -Float.pi case .down: eulerAngles.y = 0 } } } var state: Tank.State = .normal private var dstLocation: CGPoint? var nextLocation: CGPoint { let offset = direction.offset let location = dstLocation ?? CGPoint(x: CGFloat(position.x), y: CGFloat(position.z)) return CGPoint(x: location.x + offset.x, y: location.y + offset.y) } override init() { let scene = SCNScene(named: "Assets.scnassets/tank.scn")! body = scene.rootNode.childNode(withName: "tank", recursively: true)! launchingPoint = scene.rootNode.childNode(withName: "launching_point", recursively: true)! super.init() body.position = SCNVector3() addChildNode(body) updatePhysicsBody(scale: 1.0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updatePhysicsBody(scale: CGFloat) { let physicsBody = SCNPhysicsBody(type: .dynamic, shape: SCNPhysicsShape(geometry: SCNBox(width: 1 * scale, height: 1 * scale, length: 1 * scale, chamferRadius: 0), options: nil)) physicsBody.mass = 0 physicsBody.categoryBitMask = CollisionMask.tank.rawValue physicsBody.collisionBitMask = CollisionMask.bullet.rawValue physicsBody.contactTestBitMask = CollisionMask.bullet.rawValue self.physicsBody = physicsBody } func trun(to direction: Direction) { guard self.direction != direction else { return } self.direction = direction print("trun to \(direction)") } func fire(completion: ((_ bullet: Bullet) -> Void)?) -> Bullet? { guard let parent = parent else { return nil } let bullet = Bullet(owner: self, scale: GameController.shared.mapScale) let offset = direction.offset bullet.position = convertPosition(launchingPoint.position, to: parent) parent.addChildNode(bullet) let distanceX = offset.x * firingRange let distanceY = offset.y * firingRange let distance = sqrt(distanceX * distanceX + distanceY * distanceY) bullet.runAction(SCNAction.moveBy(x: distanceX, y: 0, z: distanceY, duration: TimeInterval(distance / bulletSpeed))) { completion?(bullet) } return bullet } } class Player: Tank { var firingObstacleTimer: Timer? override init() { super.init() firingRate = Config.FiringRate.player } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func fire(completion: ((Bullet) -> Void)?) -> Bullet? { guard firingObstacleTimer == nil else { return nil } firingObstacleTimer = Timer.scheduledTimer(withTimeInterval: firingRate, repeats: false, block: {[weak self] _ in self?.firingObstacleTimer = nil }) return super.fire(completion: completion) } } class Enemy: Tank { var firingTimer: Timer? override init() { super.init() firingRate = Config.FiringRate.enemy } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func autoFiring(begin: ((Bullet) -> Void)?, completion: ((Bullet) -> Void)?) { firingTimer?.invalidate() firingTimer = Timer.scheduledTimer(withTimeInterval: firingRate, repeats: true, block: { _ in if let bullet = self.fire(completion: completion) { begin?(bullet) } }) } func stopFiring() { firingTimer?.invalidate() firingTimer = nil } }
true
0ab2f64cbb15c0fbae294fdebbf634d21bb84161
Swift
noxt/Groshy
/Sources/Models/Hastag.swift
UTF-8
251
2.5625
3
[ "MIT" ]
permissive
// // Created by Dmitry Ivanenko on 05/08/2019. // Copyright © 2019 Groshy. All rights reserved. // import Foundation struct Hashtag: Codable, Equatable, Identifiable { typealias RawIdentifier = UUID let id: ID let title: String }
true
9dd0aefca9068c9eced20172c98304211c2a91a9
Swift
mixalich7b/uproar-mac-client
/uproar-mac-client/Extension/Array.swift
UTF-8
682
3
3
[]
no_license
// // Array.swift // uproar-mac-client // // Created by Тупицин Константин on 09.04.17. // Copyright © 2017 mixalich7b. All rights reserved. // import Foundation extension Array { /// Returns the first element that satisfies the given /// predicate and remove it from the array. mutating func pullFirst() -> Element? { return pullFirst(where: { _ in true }) } mutating func pullFirst(where predicate: (Element) throws -> Bool) rethrows -> Element? { if let idx = try self.index(where: predicate) { let value = self[idx] self.remove(at: idx) return value } return nil } }
true
56fba7a1c33e0ccd9307c2b9d9f945c28f71d009
Swift
kobmeier/gaff-game
/GreatAmericanFamilyFunGame/Game.swift
UTF-8
3,259
3.25
3
[]
no_license
// // Game.swift // GreatAmericanFamilyFunGame // // Created by Kerry S Dobmeier on 11/26/16. // Copyright © 2016 Kerry. All rights reserved. // import Foundation class Game { var settings = Settings() var team1 = Team() var team2 = Team() var numberOfPlayers = 0 var words = [String]() var rounds = [Round]() private var currentRoundIndex = 0 func setRounds() { let describeRound = Round(type: .describe, words: words, team1: team1, team2: team2) let actRound = Round(type: .act, words: words, team1: team1, team2: team2) let oneWordRound = Round(type: .oneword, words: words, team1: team1, team2: team2) rounds = [describeRound, actRound, oneWordRound] } func getCurrentRound() -> Round? { let currentRound = rounds[currentRoundIndex] if currentRound.bowl.unseenWords.count == 0 { self.currentRoundIndex += 1 if (currentRoundIndex > rounds.count - 1) { return nil } let newRound = rounds[currentRoundIndex] newRound.currentTeamIndex = currentRound.currentTeamIndex return newRound } return currentRound } } class Settings { var turnTime = 60 var wordsPerPlayer = 5 } class Team { var name = String() var score = 0 } enum RoundType: String { case describe = "Describe" case act = "Act" case oneword = "One Word" } class Round { var type = RoundType.describe let bowl: Bowl let team1: Team let team2: Team let teams: [Team] fileprivate var currentTeamIndex: Int var currentWord: String? init(type: RoundType, words: [String], team1: Team, team2: Team) { self.type = type self.bowl = Bowl(words: words) self.team1 = team1 self.team2 = team2 self.currentTeamIndex = 0 self.teams = [team1, team2] } func startTurn() { currentWord = bowl.drawWord() } func endTurn() { self.switchTeam() } func wordSolved() { guard let current = currentWord else { print("Word should not be solved without a current word!") return } teams[currentTeamIndex].score += 1 bowl.removeWord(word: current) currentWord = bowl.drawWord() } func wordSkipped() { teams[currentTeamIndex].score -= 1 currentWord = bowl.drawWord() } func getCurrentTeam() -> Team { return teams[currentTeamIndex] } func switchTeam() { currentTeamIndex = (currentTeamIndex + 1) % teams.count } } class Bowl { var unseenWords = [String]() var seenWords = [String]() init(words: [String]) { unseenWords = words } func drawWord() -> String? { if unseenWords.count > 0 { let index = Int(arc4random_uniform(UInt32(unseenWords.count))) return unseenWords[index] } else { return nil } } func removeWord(word: String) { if let index = unseenWords.index(of: word) { unseenWords.remove(at: index) seenWords.append(word) } } }
true