text
stringlengths
8
1.32M
@testable import Vapor import XCTest final class URLEncodedFormParserTests: XCTestCase { func testBasic() throws { let data = "hello=world&foo=bar" let form = try URLEncodedFormParser().parse(data) XCTAssertEqual(form, ["hello": "world", "foo": "bar"]) } func testBasicWithAmpersand() throws { let data = "hello=world&foo=bar%26bar" let form = try URLEncodedFormParser().parse(data) XCTAssertEqual(form, ["hello": "world", "foo": "bar&bar"]) } func testDictionary() throws { let data = "greeting[en]=hello&greeting[es]=hola" let form = try URLEncodedFormParser().parse(data) XCTAssertEqual(form, ["greeting": ["es": "hola", "en": "hello"]]) } func testArray() throws { let data = "greetings[]=hello&greetings[]=hola" let form = try URLEncodedFormParser().parse(data) XCTAssertEqual(form, ["greetings": ["hello", "hola"]]) } func testOptions() throws { let data = "hello=&foo" let normal = try URLEncodedFormParser().parse(data) let noEmpty = try URLEncodedFormParser(omitEmptyValues: true).parse(data) let noFlags = try URLEncodedFormParser(omitFlags: true).parse(data) XCTAssertEqual(normal, ["hello": "", "foo": "true"]) XCTAssertEqual(noEmpty, ["foo": "true"]) XCTAssertEqual(noFlags, ["hello": ""]) } func testPercentDecoding() throws { let data = "aaa%5B%5D=%2Bbbb%20+ccc&d[]=1&d[]=2" let form = try URLEncodedFormParser().parse(data) XCTAssertEqual(form, ["aaa[]": "+bbb ccc", "d": ["1","2"]]) } func testNestedParsing() throws { // a[][b]=c&a[][b]=c // [a:[[b:c],[b:c]] let data = "a[b][c][d][hello]=world" let form = try URLEncodedFormParser().parse(data) XCTAssertEqual(form, ["a": ["b": ["c": ["d": ["hello": "world"]]]]]) } }
//: Playground - noun: a place where people can play import Foundation func vowelCount(string: String) { let maxNumber = value.maxValue([24,5,6,734,2,42,4,5,75]) print(maxNumber) word.popular("Dan is the man and Dan has the master plan") // print(words) } vowelCount(string: "this shits is hardlvu;abewbrau;tbuvb;v;bv;oboqborben") class MaxValue : NSObject { func maxValue(_ intergers: [Int]) -> Int { var biggest = 0 for interger in intergers { if biggest < interger { biggest = interger } } return biggest } } class Persons { var firstName: String var lastName: String var shoeSize: Int init(firstName: String, lastName: String, shoeSize: Int) { self.firstName = firstName self.lastName = lastName self.shoeSize = shoeSize } }
// // GZEChatMessageApiRepository.swift // Gooze // // Created by Yussel Paredes Perez on 6/26/18. // Copyright © 2018 Gooze. All rights reserved. // import Foundation import ReactiveSwift import Alamofire import Gloss class GZEChatMessageApiRepository: GZEChatMessageRepositoryProtocol { func setRead(chatId: String) -> SignalProducer<Int, GZEError> { guard let userId = GZEAuthService.shared.authUser?.id else { return SignalProducer(error: .repository(error: .AuthRequired)) } let filter: JSON = [ "where": [ "chatId": chatId, "senderId": ["neq": userId], "status": ["neq": GZEChatMessage.Status.read.rawValue] ] ] let data: JSON = [ "status": GZEChatMessage.Status.read.rawValue ] return update(filter: filter, data: data) } func count(filter: JSON) -> SignalProducer<Int, GZEError> { return SignalProducer {sink, disposable in Alamofire.request(GZEChatMessageRouter.count(filter: filter)) .responseJSON(completionHandler: GZEApi.createResponseHandler(sink: sink, createInstance: { (json: JSON) in return json["count"] as? Int })) } } func update(filter: JSON, data: JSON) -> SignalProducer<Int, GZEError> { return SignalProducer {sink, disposable in Alamofire.request(GZEChatMessageRouter.update(filter: filter, data: data)) .responseJSON(completionHandler: GZEApi.createResponseHandler(sink: sink, createInstance: { (json: JSON) in return json["count"] as? Int })) } } }
// // ArtworkComment.swift // f26Model // // Created by David on 25/10/2017. // Copyright © 2017 com.smartfoundation. All rights reserved. // import SFModel import SFCore import f26Core /// Encapsulates a ArtworkComment model item public class ArtworkComment: ModelItemBase { // MARK: - Initializers private override init() { super.init() } public override init(collection: ProtocolModelItemCollection, storageDateFormatter: DateFormatter) { super.init(collection: collection, storageDateFormatter: storageDateFormatter) } // MARK: - Public Methods let artworkidKey: String = "artworkid" /// Gets or sets the artworkID public var artworkID: Int { get { return Int(self.getProperty(key: artworkidKey)!)! } set(value) { self.setProperty(key: artworkidKey, value: String(value), setWhenInvalidYN: false) } } let datepostedKey: String = "dateposted" /// Gets or sets the datePosted public var datePosted: Date { get { let dateString = self.getProperty(key: datepostedKey)! return DateHelper.getDate(fromString: dateString, fromDateFormatter: self.storageDateFormatter!) } set(value) { self.setProperty(key: datepostedKey, value: self.getStorageDateString(fromDate: value), setWhenInvalidYN: false) } } let postedbynameKey: String = "postedbyname" /// Gets or sets the postedByName public var postedByName: String { get { return self.getProperty(key: postedbynameKey)! } set(value) { self.setProperty(key: postedbynameKey, value: value, setWhenInvalidYN: false) } } let postedbyemailKey: String = "postedbyemail" /// Gets or sets the postedByEmail public var postedByEmail: String { get { return self.getProperty(key: postedbyemailKey)! } set(value) { self.setProperty(key: postedbyemailKey, value: value, setWhenInvalidYN: false) } } let textKey: String = "text" /// Gets or sets the text public var text: String { get { return self.getProperty(key: textKey)! } set(value) { self.setProperty(key: textKey, value: value, setWhenInvalidYN: false) } } public func toWrapper() -> ArtworkCommentWrapper { let wrapper = ArtworkCommentWrapper() wrapper.id = Int.init(self.id)! wrapper.artworkID = self.artworkID wrapper.datePosted = self.datePosted wrapper.postedByName = self.postedByName wrapper.postedByEmail = self.postedByEmail wrapper.text = self.text return wrapper } // MARK: - Override Methods public override func initialiseDataNode() { // Setup the node data self.doSetProperty(key: idKey, value: "0") self.doSetProperty(key: artworkidKey, value: "0") self.doSetProperty(key: datepostedKey, value: "1/1/1900") self.doSetProperty(key: postedbynameKey, value: "") self.doSetProperty(key: postedbyemailKey, value: "") self.doSetProperty(key: textKey, value: "") } public override func initialiseDataItem() { // Setup foreign key dependency helpers } public override func initialisePropertyIndexes() { // Define the range of the properties using the enum values startEnumIndex = ModelProperties.artworkComment_id.rawValue endEnumIndex = ModelProperties.artworkComment_text.rawValue } public override func initialisePropertyKeys() { // Populate the dictionary of property keys keys[idKey] = ModelProperties.artworkComment_id.rawValue keys[artworkidKey] = ModelProperties.artworkComment_artworkID.rawValue keys[datepostedKey] = ModelProperties.artworkComment_datePosted.rawValue keys[postedbynameKey] = ModelProperties.artworkComment_postedByName.rawValue keys[postedbyemailKey] = ModelProperties.artworkComment_postedByEmail.rawValue keys[textKey] = ModelProperties.artworkComment_text.rawValue } public override var dataType: String { get { return "artworkComment" } } public override func clone(item: ProtocolModelItem) { // Validations should not be performed when cloning the item let doValidationsYN: Bool = self.doValidationsYN self.doValidationsYN = false // Copy all properties from the specified item if let item = item as? ArtworkComment { self.id = item.id self.artworkID = item.artworkID self.datePosted = item.datePosted self.postedByName = item.postedByName self.postedByEmail = item.postedByEmail self.text = item.text } self.doValidationsYN = doValidationsYN } public override func isValid(propertyEnum: Int, value: String) -> ValidationResultTypes { var result: ValidationResultTypes = ValidationResultTypes.passed // Perform validations for the specified property switch toProperty(propertyEnum: propertyEnum) { case .artworkComment_postedByName: result = self.isValidPostedByName(value: value) break case .artworkComment_text: result = self.isValidText(value: value) break default: break } return result } // MARK: - Private Methods fileprivate func toProperty(propertyEnum: Int) -> ModelProperties { return ModelProperties(rawValue: propertyEnum)! } // MARK: - Validations fileprivate func isValidPostedByName(value: String) -> ValidationResultTypes { var result: ValidationResultTypes = .passed result = self.checkMaxLength(value: value, maxLength: 50, propertyName: "PostedByName") return result } fileprivate func isValidText(value: String) -> ValidationResultTypes { var result: ValidationResultTypes = .passed result = self.checkMaxLength(value: value, maxLength: 250, propertyName: "Text") return result } }
// // Protocol.swift // clock // // Created by 陳冠諭 on 2020/10/9. // Copyright © 2020 KuanYu. All rights reserved. // import Foundation protocol PassAlarmArray { func passAlarmArray(data:[AlarmData]) } protocol SetRepeatDelegate { func setRepeat (days: [DataInfomation.DaysOfWeek]) } protocol LabelTextDelegate { func labelText(text: String) } protocol SetRingToneDelegate{ func setRingTone(index:Int) }
// // AuthError.swift // Start WebPower // // Created by Алик on 1/8/20. // Copyright © 2020 ALIK MOLDOVANU. All rights reserved. // import Foundation enum AuthError { case notFilled case invalidEmail case unknownError case serverError case responseError(String) case invalidLenght(Int, Int) } extension AuthError: LocalizedError { var errorDescription: String? { switch self { case .notFilled: return NSLocalizedString("Заполните все поля", comment: "") case .invalidEmail: return NSLocalizedString("Введите валидную почту", comment: "") case .unknownError: return NSLocalizedString("Неизвестная ошибка", comment: "") case .serverError: return NSLocalizedString("Ошибка сервера", comment: "") case .responseError(let error): return NSLocalizedString(error, comment: "") case .invalidLenght(let min, let max): return NSLocalizedString("Учитывайте диапазон: \(min)-\(max) символов", comment: "") } } }
// // Bool.swift // Airpin // // Created by Thomas Carey on 7/21/15. // Copyright © 2015 Thomas Carey. All rights reserved. // extension Bool { init(string: String) { assert(string == "yes" || string == "no", "Bool(string:) accepts \"yes\" or \"no\" arguments.") if string == "yes" { self = true } else { self = false } } }
// // CXCommentViewController.swift // Silly Monks // // Created by Sarath on 20/05/16. // Copyright © 2016 Sarath. All rights reserved. // import UIKit class CXCommentViewController: UIViewController { var writeBtn:UIButton! var ratingBtn:UIButton! var headerTitle:String! var orgID: String! var jobID : String! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.smBackgroundColor() self.customizeHeaderView() self.customizeMainView() // Do any additional setup after loading the view. } func customizeHeaderView() { self.navigationController?.navigationBar.translucent = false; self.navigationController?.navigationBar.barTintColor = UIColor.navBarColor() self.title = "Reviews" let lImage = UIImage(named: "left_aarow.png") as UIImage? let button = UIButton (type: UIButtonType.Custom) as UIButton button.frame = CGRectMake(0, 0, 40, 40) button.setImage(lImage, forState: .Normal) button.backgroundColor = UIColor.clearColor() button.addTarget(self, action: #selector(CXCommentViewController.backAction), forControlEvents: .TouchUpInside) let navSpacer: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.FixedSpace,target: nil, action: nil) navSpacer.width = -16; self.navigationItem.leftBarButtonItems = [navSpacer,UIBarButtonItem.init(customView: button)] let tLabel : UILabel = UILabel() tLabel.frame = CGRectMake(0, 0, 120, 40); tLabel.backgroundColor = UIColor.clearColor() tLabel.font = UIFont.init(name: "Roboto-Bold", size: 18) tLabel.text = headerTitle tLabel.textAlignment = NSTextAlignment.Center tLabel.textColor = UIColor.whiteColor() self.navigationItem.titleView = tLabel } func customizeMainView() { let height = UIScreen.mainScreen().bounds.size.height let vHeight = self.view.frame.size.height //print("Screen height \(height) and view frame \(vHeight)") let comentImageView = UIImageView.init(frame: CGRectMake((self.view.frame.size.width - 60)/2,(self.view.frame.size.height-65-60-50)/2 , 60, 60)) //comentImageView.backgroundColor = UIColor.redColor() //comentImageView.center = self.view.center comentImageView.image = UIImage(named: "write_coment.png") self.view.addSubview(comentImageView) let writeLbl = UILabel.init(frame: CGRectMake(20, comentImageView.frame.size.height+comentImageView.frame.origin.y, self.view.frame.size.width-40, 30)) writeLbl.text = "Be the first to write" writeLbl.textColor = UIColor.blackColor() writeLbl.font = UIFont(name: "Roboto-Regular", size: 15) writeLbl.textAlignment = NSTextAlignment.Center self.view.addSubview(writeLbl) let btnsView = UIView.init(frame: CGRectMake(0, self.view.frame.size.height-65-50, self.view.frame.size.width, 50)) btnsView.backgroundColor = UIColor.yellowColor() self.view.addSubview(btnsView) let writeColor = UIColor(red: 68.0/255.0, green: 68.0/255.0, blue: 68.0/255.0, alpha: 1.0) self.writeBtn = self.createButton(CGRectMake(0, 0, btnsView.frame.size.width/2, 50), title: "WRITE", tag: 1, bgColor: writeColor) self.writeBtn.addTarget(self, action: #selector(CXCommentViewController.writeCommentAction), forControlEvents: UIControlEvents.TouchUpInside) btnsView.addSubview(self.writeBtn) self.ratingBtn = self.createButton(CGRectMake(self.writeBtn.frame.size.width+self.writeBtn.frame.origin.x, 0, btnsView.frame.size.width/2, 50), title: "OVERALL RATING", tag: 2, bgColor: UIColor.navBarColor()) self.ratingBtn.addTarget(self, action: #selector(CXCommentViewController.overallRatingAction), forControlEvents: UIControlEvents.TouchUpInside) btnsView.addSubview(self.ratingBtn) } func writeCommentAction() { if NSUserDefaults.standardUserDefaults().valueForKey("USER_ID") != nil { let comRatView = CXCommentRatingViewController.init() comRatView.jobID = self.jobID self.navigationController?.pushViewController(comRatView, animated: true) } else { let signInView = CXSignInSignUpViewController.init() signInView.orgID = self.orgID self.navigationController?.pushViewController(signInView, animated: true) } } func overallRatingAction() { } func backAction() { self.navigationController?.popViewControllerAnimated(true) } func createButton(frame:CGRect,title: String,tag:Int, bgColor:UIColor) -> UIButton { let button: UIButton = UIButton() button.frame = frame button.setTitle(title, forState: .Normal) button.titleLabel?.font = UIFont.init(name:"Roboto-Bold", size: 15) button.titleLabel?.textAlignment = NSTextAlignment.Center button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) button.backgroundColor = bgColor return button } 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // RecoverPasswordViewController.swift // Guardianes Monarca // // Created by Juan David Torres on 10/10/19. // Copyright © 2019 Juan David Torres. All rights reserved. // import UIKit import FirebaseAuth class RecoverPasswordViewController: UIViewController { @IBOutlet weak var textFieldEmail: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } func isValidEmail(testStr: String) -> Bool { //let emailRegEx = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" let emailRegEx = "^\\w+([\\.\\+\\-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{2,4})+$" let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: testStr) } @IBAction func SendEmailButtonPressed(_ sender: Any) { validateFields() } func validateFields(){ if !isValidEmail(testStr: textFieldEmail.text!) { self.createAlert(view_controller: self, title: "Error", message: "Invalid Email Format") return } if textFieldEmail.text?.lowercased() == "" { self.createAlert(view_controller: self, title: "Error", message: "Ingresa un correo") return } Auth.auth().sendPasswordReset(withEmail: self.textFieldEmail.text!) { error in if error != nil { self.createAlert(view_controller: self, title: "Error", message: "Ocurrio un error, talvez tu correo no esta en el sistema") } else { self.createAlert(view_controller: self, title: "Exito", message: "Se ha enviado al correo \(String(describing: self.textFieldEmail.text!)) el proceso para recuperar su contraseña") } } } }
// // SecondViewController.swift // munchkin // // Created by Michael Rockway on 1/28/16. // Copyright © 2016 rockway. All rights reserved. // import UIKit class SecondViewController: UIViewController { // get user defaults from storage let defaults = NSUserDefaults.standardUserDefaults() // declare variables var dueDate: String = "" var dueDateFromPicker = NSDate() let formatter = NSDateFormatter() @IBOutlet weak var dueDateLabel: UILabel! @IBOutlet weak var setDateButton: UIButton! @IBOutlet weak var dueDateSelector: UIDatePicker! @IBOutlet weak var confirmDateButton: UIButton! @IBOutlet weak var enterDateLabel: UILabel! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var datePickerContainer: UIImageView! @IBOutlet weak var selectDateDescription: UILabel! @IBOutlet weak var dueDateBackgroundLabel: UIImageView! @IBOutlet weak var dueDateStatic: UILabel! override func viewDidLoad() { super.viewDidLoad() // hide date picker and confirm buttons dueDateSelector.hidden = true confirmDateButton.hidden = true setDateButton.hidden = false // if there is a saved date from a return user // set that date as the label text // otherwise hide the label if let savedDueDate = defaults.objectForKey("DueDate") { dueDateSelector.setDate(savedDueDate as! NSDate, animated: true) formatter.dateStyle = NSDateFormatterStyle.LongStyle dueDateLabel.text = "\(formatter.stringFromDate(savedDueDate as! NSDate))" } else { dueDateStatic.hidden = true } // call style function setStyleAttributes() // Do any additional setup after loading the view. } func setStyleAttributes() { // Set up shadow attributes let rgb: CGColorSpaceRef = CGColorSpaceCreateDeviceRGB()! let black: [CGFloat] = [0, 0, 0, 1] // border color for containers let borderColor = UIColor(red:154/255.0, green:154/255.0, blue:147/255.0, alpha: 1.0).CGColor // Styling for adding a date button setDateButton.layer.cornerRadius = 5 setDateButton.layer.borderColor = borderColor setDateButton.layer.borderWidth = 3 setDateButton.layer.shadowOffset = CGSizeMake(-2, 2) setDateButton.layer.shadowRadius = 5 setDateButton.layer.shadowColor = CGColorCreate(rgb, black) setDateButton.layer.shadowOpacity = 1 // Styling for confirming date button confirmDateButton.layer.cornerRadius = 5 confirmDateButton.layer.borderColor = borderColor confirmDateButton.layer.borderWidth = 3 confirmDateButton.layer.shadowOffset = CGSizeMake(-2, 2) confirmDateButton.layer.shadowRadius = 5 confirmDateButton.layer.shadowColor = CGColorCreate(rgb, black) confirmDateButton.layer.shadowOpacity = 1 // X button to go back to image screen cancelButton.layer.cornerRadius = 5 // style date picker container datePickerContainer.layer.borderWidth = 5 datePickerContainer.layer.borderColor = borderColor datePickerContainer.layer.cornerRadius = 10 datePickerContainer.layer.shadowRadius = 5 datePickerContainer.layer.shadowColor = CGColorCreate(rgb, black) datePickerContainer.layer.shadowOpacity = 1 datePickerContainer.layer.shadowOffset = CGSizeMake(-2,2) // style upper portion of date picker view dueDateBackgroundLabel.layer.borderWidth = 5 dueDateBackgroundLabel.layer.borderColor = borderColor dueDateBackgroundLabel.layer.cornerRadius = 10 dueDateBackgroundLabel.layer.shadowRadius = 5 dueDateBackgroundLabel.layer.shadowColor = CGColorCreate(rgb, black) dueDateBackgroundLabel.layer.shadowOpacity = 1 dueDateBackgroundLabel.layer.shadowOffset = CGSizeMake(-2,2) } // setup datepicker layout after selecting add date button @IBAction func setInitialDate() { dueDateSelector.hidden = false dueDateSelector.addTarget(self, action: Selector("datePickerChanged:"), forControlEvents: UIControlEvents.ValueChanged) dueDateLabel.hidden = false setDateButton.hidden = true confirmDateButton.hidden = false // get saved date from storage if it exists and set it as the default picker value if let savedDueDate = defaults.objectForKey("DueDate") { dueDateSelector.setDate(savedDueDate as! NSDate, animated: true) formatter.dateStyle = NSDateFormatterStyle.LongStyle dueDateLabel.text = "\(formatter.stringFromDate(savedDueDate as! NSDate))" } } // Set the due date func datePickerChanged(datePicker:UIDatePicker) { // give datepicker parameters to only include current date to 40 weeks from current date let fourtyWeeks = NSDate(timeInterval: (24192000), sinceDate: NSDate()) datePicker.minimumDate = NSDate() datePicker.maximumDate = fourtyWeeks // hide add date button setDateButton.hidden = true // format date to a readable format and convert into string formatter.dateStyle = NSDateFormatterStyle.LongStyle dueDateFromPicker = datePicker.date dueDate = formatter.stringFromDate(dueDateFromPicker) dueDateLabel.text = "\(dueDate)" } @IBAction func confirmDueDate() { // no date is selected show alert message otherwise save the due date and a boolean to show user has visited site into storage // schedule notifications // perform segue into image view if (dueDate == "") { let alert = UIAlertController(title: "Please enter the due date", message: "No never ending pregnancies allowed", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Try again", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } else { dueDateSelector.hidden = true confirmDateButton.hidden = true defaults.setObject(dueDateFromPicker, forKey: "DueDate") defaults.setBool(true, forKey: "returningUser") scheduleNofifications() } } func scheduleNofifications() { // Check to see if User has allowed Notifications let settings = UIApplication.sharedApplication().currentUserNotificationSettings() // Send message to user about not allowing notifications if settings!.types == .None { let ac = UIAlertController(title: "Enable notifications to find out when you new comparison is ready", message: "Either we don't have permission to schedule notifications, or we haven't asked yet.", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(ac, animated: true, completion: nil) return } // Clear any existing notifications before setting new ones UIApplication.sharedApplication().cancelAllLocalNotifications() // Set number of notifiations to schedule let weeksRemaining = Double(repeatNotifications()) // Build notification let notification = UILocalNotification() // Loop to create weekly notifications until the due date for var i:Double = 0; i <= weeksRemaining; i++ { notification.fireDate = NSDate(timeIntervalSinceNow: (604800 * i )) notification.alertBody = "Check out your new picture" notification.alertAction = "View image" notification.soundName = UILocalNotificationDefaultSoundName notification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1 UIApplication.sharedApplication().scheduleLocalNotification(notification) } } // finds how many weeks until due date and returns that number func repeatNotifications() -> Int { let weeks = dueDateFromPicker.timeIntervalSinceDate(NSDate())/604800 let weeksLeft = Int(ceil(weeks)) return weeksLeft } // change button text func adjustDueDate() { enterDateLabel.text = "Change the due date" setDateButton.setTitle("Edit Due Date", forState: .Normal) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // setup app to handle motion events override func canBecomeFirstResponder() -> Bool { return true } // On shake event the phone displays a helpful message override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) { if motion == .MotionShake { let ac = UIAlertController(title: "Careful", message: "Dont't shake the baby!", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "You have been warned", style: .Default, handler: nil)) presentViewController(ac, animated: true, completion: nil) return } } /* // 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. } */ }
// // SecondViewController.swift // Lesson07 // // Created by Rudd Taylor on 9/30/14. // Copyright (c) 2014 General Assembly. All rights reserved. // import UIKit class SecondViewController: UIViewController { @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() var name: String = "" var slider: Double = 0.0 var readSettings: NSDictionary? var settingsPath = NSBundle.mainBundle().pathForResource("Settings.bundle/Root", ofType: "plist") // println(settingsPath) // To read from data, use NSArray object if let path = settingsPath { // println("Unwrapped settingsPath") readSettings = NSDictionary(contentsOfFile: path) // Unwrap settings if let dict = readSettings { // println("Unwrapped readSettings") // Unwrap PreferenceSpecifiers if let preferenceSpecifiers: NSArray = dict["PreferenceSpecifiers"] as NSArray? { // println("Unwrapped preferenceSpecifiers") // Unwrap name if let unwrappedName = preferenceSpecifiers[1]["Title"] as String? { name = unwrappedName } else { println("Couldn't unwrap settings_name") } // Unwrap slider if let unwrappedSlider: Double = preferenceSpecifiers[2]["DefaultValue"] as Double? { slider = unwrappedSlider } else { println("Couldn't unwrap settings_slider") } } else { println("Couldn't unwrap preferenceSpecifiers") } } else { println("Could not unwrap readSettings") } } else { println("Could not unwrap settingsPath!") } // Set the text view self.textView.text = "Name: \(name)\nSlider: \(slider)" } }
// // Pianoset.swift // YourPad // // Created by Casey on 3/13/16. // Copyright © 2016 Casey. All rights reserved. // import Foundation import AVFoundation import AudioToolbox class Pianoset { var players: [AVAudioPlayer?] var bankName: String! let keyNames = ["c3", "c3Sharp", "d3", "d3Sharp", "e3", "f3", "f3Sharp", "g3", "g3Sharp", "a4", "a4Sharp", "b4", "c4"] init(bankName: String) { players = keyNames.map { note in let filename = (bankName + note) if let url = NSBundle.mainBundle().URLForResource(filename, withExtension: "wav") { return (try? AVAudioPlayer(contentsOfURL: url)) } else { return nil } } } func play(index: Int) { if !players.isEmpty && index >= 0 && index < players.count { players[index]?.play() } } }
// // MonthTabCell.swift // Maniau // // Created by Ryan Kanno on 6/23/21. // import UIKit class MonthTabCell: UITableViewCell { static let name: String = "MonthTabCell" @IBOutlet private weak var colorView: UIView! @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var descriptionLabel: UILabel! @IBOutlet private weak var startLabel: UILabel! @IBOutlet private weak var endLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() colorView.layer.cornerRadius = 4 colorView.backgroundColor = .systemTeal } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func configure(color: String, title: String, details: String, start: String, end: String) { colorView.backgroundColor = Animations.convertColorString(color) titleLabel.text = title descriptionLabel.text = details startLabel.text = start endLabel.text = end } }
// // PromotionsViewController.swift // HippoChat // // Created by Clicklabs on 12/23/19. // Copyright © 2019 CL-macmini-88. All rights reserved. // import UIKit protocol PromotionCellDelegate : class { //func getActionData(data:PromotionCellDataModel, viewController : UIViewController) func setData(data:PromotionCellDataModel) var cellIdentifier : String { get } var bundle : Bundle? { get } } typealias PromtionCutomCell = PromotionCellDelegate & UITableViewCell class PromotionsViewController: UIViewController { //MARK:- IBOutlets @IBOutlet weak var promotionsTableView: UITableView!{ didSet{ promotionsTableView.contentInset = UIEdgeInsets(top: 5, left: 0, bottom: 0, right: 0) } } @IBOutlet weak var navigationBackgroundView: UIView! @IBOutlet weak var loaderView: So_UIImageView! @IBOutlet var errorLabel: UILabel! @IBOutlet var viewError_Height: NSLayoutConstraint! @IBOutlet weak var errorContentView: UIView! @IBOutlet weak var navigationBar : NavigationBar! // @IBOutlet weak var top_Constraint : NSLayoutConstraint! //MARK:- Variables var data: [PromotionCellDataModel] = [] weak var customCell: PromtionCutomCell? var refreshControl = UIRefreshControl() // var count = 20 var isMoreData = false var channelIdsArr = [Int]() var informationView: InformationView? var selectedRow = -1 var states = [Bool]() var shouldUseCache : Bool = true var page = 1 var limit = 20 var shouldFetchData = true var previousPage = 0 var showMoreIndex : IndexPath? var isSendOpenened = false override func viewDidLoad() { super.viewDidLoad() FuguNetworkHandler.shared.fuguConnectionChangesStartNotifier() if shouldUseCache { self.data = fetchAllAnnouncementCache() for _ in data{ self.states.append(true) } noNotificationsFound() } self.setUpViewWithNav() setupRefreshController() promotionsTableView.backgroundColor = HippoConfig.shared.theme.promotionBackgroundColor promotionsTableView.register(UINib(nibName: "PromotionTableViewCell", bundle: FuguFlowManager.bundle), forCellReuseIdentifier: "PromotionTableViewCell") promotionsTableView.rowHeight = UITableView.automaticDimension promotionsTableView.estimatedRowHeight = 50 if let c = customCell { promotionsTableView.register(UINib(nibName: c.cellIdentifier, bundle: c.bundle), forCellReuseIdentifier: c.cellIdentifier) } if !(HippoConfig.shared.isOpenedFromPush ?? false){ self.callGetAnnouncementsApi() HippoNotification.removeAllAnnouncementNotification() }else{ refreshData(isOpenedFromPush: HippoConfig.shared.isOpenedFromPush ?? false) HippoConfig.shared.isOpenedFromPush = false } } internal func setupRefreshController() { // refreshControl.backgroundColor = .clear // refreshControl.tintColor = .themeColor promotionsTableView.refreshControl = refreshControl refreshControl.addTarget(self, action: #selector(reloadrefreshData(refreshCtrler:)), for: .valueChanged) } @objc func reloadrefreshData(refreshCtrler: UIRefreshControl) { isMoreData = false self.page = 1 if FuguNetworkHandler.shared.isNetworkConnected { self.getAnnouncements(endOffset:limit, startOffset: 0) }else{ self.refreshControl.endRefreshing() } } func refreshData(isOpenedFromPush: Bool){ getDataOrUpdateAnnouncement(HippoNotification.promotionPushDic.map{$0.value.channelID}, isforReadMore: false, isOpenedFromPush: isOpenedFromPush) HippoNotification.promotionPushDic.removeAll() } func getDataOrUpdateAnnouncement(_ channelIdArr : [Int], isforReadMore : Bool, indexRow : Int? = nil, isOpenedFromPush: Bool = false){ var params = [String : Any]() if currentUserType() == .customer{ params = ["app_secret_key" : HippoConfig.shared.appSecretKey, "channel_ids" : channelIdArr, "en_user_id" : currentEnUserId(), "offering" : HippoConfig.shared.offering, "device_type": Device_Type_iOS] as [String : Any] if let userIdenficationSecret = HippoConfig.shared.userDetail?.userIdenficationSecret{ if userIdenficationSecret.trimWhiteSpacesAndNewLine().isEmpty == false { params["user_identification_secret"] = userIdenficationSecret } } if isOpenedFromPush{ params["seen_status"] = 1 params["app_opened_through_push"] = 1 HippoConfig.shared.sessionStartTime = Date() } if var channelArr = params["channel_ids"] as? [Int], !channelArr.contains(HippoConfig.shared.tempChannelId ?? 0){ channelArr.append(HippoConfig.shared.tempChannelId ?? 0) params["channel_ids"] = channelArr } }else{ params = ["access_token" : HippoConfig.shared.agentDetail?.fuguToken ?? "", "channel_ids" : channelIdArr, "user_id" : currentUserId()] as [String : Any] if isOpenedFromPush{ params["seen_status"] = 1 params["app_opened_through_push"] = 1 HippoConfig.shared.sessionStartTime = Date() } if var channelArr = params["channel_ids"] as? [Int], !channelArr.contains(HippoConfig.shared.tempChannelId ?? 0){ channelArr.append(HippoConfig.shared.tempChannelId ?? 0) params["channel_ids"] = channelArr } } HippoConfig.shared.log.debug(("params sent in announcments ---------->>>>>>>>>>>>>", params), level: .info) HTTPClient.makeConcurrentConnectionWith(method: .POST, para: params, extendedUrl: FuguEndPoints.getAndUpdateAnnouncement.rawValue) { (response, error, _, statusCode) in if let response = response as? [String : Any], let data = response["data"] as? [[String : Any]]{ for value in data{ if let announcement = PromotionCellDataModel(dict: value){ for i in 0..<self.data.count{ if self.data[i].channelID == announcement.channelID{ self.data.remove(at: i) self.states.insert(false, at: 0) break } } self.data.insert(announcement, at: 0) self.states.insert(true, at: 0) } } let channelIdArr = self.data.map{String($0.channelID)} if let channelArr = UserDefaults.standard.value(forKey: DefaultName.announcementUnreadCount.rawValue) as? [String]{ let result = channelArr.filter { !channelIdArr.contains($0) } UserDefaults.standard.set(result, forKey: DefaultName.announcementUnreadCount.rawValue) HippoConfig.shared.announcementUnreadCount?(result.count) } self.noNotificationsFound() } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.isNavigationBarHidden = true self.promotionsTableView.isHidden = false self.checkNetworkConnection() self.setUpTabBar() self.setUpViewWithNav() //top_Constraint.constant = (self.navigationController?.navigationBar.frame.size.height ?? 0.0) + 20 self.view.layoutSubviews() } func callGetAnnouncementsApi(){ // self.startLoaderAnimation() self.page = 1 self.getAnnouncements(endOffset: limit, startOffset: 0) } override func viewWillLayoutSubviews() { self.setUpTabBar() } func setUpTabBar(){ // self.tabBarController?.hidesBottomBarWhenPushed = true // self.tabBarController?.tabBar.isHidden = false // self.tabBarController?.tabBar.layer.zPosition = 0 // self.tabBarController?.tabBar.items?[1].title = "Notifications" //hide //self.tabBarController?.hidesBottomBarWhenPushed = true self.tabBarController?.tabBar.isHidden = true //self.tabBarController?.tabBar.layer.zPosition = -1 } func setUpViewWithNav() { navigationBar.title = HippoConfig.shared.theme.promotionsAnnouncementsHeaderText navigationBar.leftButton.addTarget(self, action: #selector(backButtonClicked), for: .touchUpInside) navigationBar.rightButton.setTitle(HippoStrings.clearAll, for: .normal) navigationBar.rightButton.titleLabel?.font = UIFont.regular(ofSize: 14) navigationBar.rightButton.setTitleColor(UIColor(red: 95/255, green: 95/255, blue: 95/255, alpha: 1.0), for: .normal) navigationBar.rightButton.addTarget(self, action: #selector(deleteAllAnnouncementsButtonClicked), for: .touchUpInside) navigationBar.view.layer.shadowOffset = CGSize(width: 0.0, height: 0.5) navigationBar.view.layer.shadowRadius = 2.0 navigationBar.view.layer.shadowOpacity = 0.5 navigationBar.view.layer.masksToBounds = false navigationBar.view.layer.shadowPath = UIBezierPath(rect: CGRect(x: 0, y: navigationBar.bounds.maxY - navigationBar.layer.shadowRadius, width: navigationBar.bounds.width, height: navigationBar.layer.shadowRadius)).cgPath } @objc func backButtonClicked() { if let navigationController = UIApplication.shared.windows.first?.rootViewController as? UINavigationController{ if let tabBarController = navigationController.viewControllers[0] as? UITabBarController{ tabBarController.selectedIndex = 0 } } // if config.shouldPopVc { // self.navigationController?.popViewController(animated: true) // } else { _ = self.navigationController?.dismiss(animated: true, completion: nil) // } let json = PromotionCellDataModel.getJsonFromAnnouncementArr(self.data) self.savePromotionsInCache(json) } func startLoaderAnimation() { DispatchQueue.main.async { self.loaderView?.startRotationAnimation() } } func stopLoaderAnimation() { DispatchQueue.main.async { self.loaderView?.stopRotationAnimation() } } @objc func deleteAllAnnouncementsButtonClicked() { guard self.navigationItem.rightBarButtonItem?.tintColor != .clear else { return } UserDefaults.standard.set([], forKey: DefaultName.announcementUnreadCount.rawValue) HippoConfig.shared.announcementUnreadCount?(0) self.clearAnnouncements(indexPath: IndexPath(row: 0, section: 0), isDeleteAllStatus: 1) FuguDefaults.removeObject(forKey: DefaultName.appointmentData.rawValue) // }, failureButtonName: "NO", failureComplete: nil) } func getAnnouncements(endOffset:Int, startOffset:Int) { var params = [String : Any]() if currentUserType() == .customer{ params = ["end_offset":"\(endOffset)", "start_offset":"\(startOffset)", "en_user_id":HippoUserDetail.fuguEnUserID ?? "", "app_secret_key":HippoConfig.shared.appSecretKey, "offering" : HippoConfig.shared.offering, "device_type": Device_Type_iOS] if let userIdenficationSecret = HippoConfig.shared.userDetail?.userIdenficationSecret{ if userIdenficationSecret.trimWhiteSpacesAndNewLine().isEmpty == false { params["user_identification_secret"] = userIdenficationSecret } } }else{ params = ["end_offset":"\(endOffset)","start_offset":"\(startOffset)","user_id": "\(currentUserId())" ,"access_token":HippoConfig.shared.agentDetail?.fuguToken ?? ""] } HTTPClient.makeConcurrentConnectionWith(method: .POST, para: params, extendedUrl: AgentEndPoints.getAnnouncements.rawValue) { (response, error, _, statusCode) in // self.stopLoaderAnimation() if error == nil{ self.refreshControl.endRefreshing() let r = response as? NSDictionary if let arr = r?["data"] as? NSArray{ if arr.count == 0{ self.shouldFetchData = false } if startOffset == 0 && self.data.count > 0{ self.data.removeAll() self.states.removeAll() } for item in arr{ let i = item as! [String:Any] let dataNew = PromotionCellDataModel(dict:i) self.data.append(dataNew!) self.states.append(true) } if startOffset == 0{ self.savePromotionsInCache(arr as? [[String : Any]] ?? [[String : Any]]()) } let channelIdArr = self.data.map{String($0.channelID)} if let channelArr = UserDefaults.standard.value(forKey: DefaultName.announcementUnreadCount.rawValue) as? [String]{ let result = channelArr.filter { !channelIdArr.contains($0) } UserDefaults.standard.set(result, forKey: DefaultName.announcementUnreadCount.rawValue) HippoConfig.shared.announcementUnreadCount?(result.count) } } self.noNotificationsFound() //self.promotionsTableView.reloadData() } } } func noNotificationsFound(){ guard let _ = promotionsTableView else { return } if self.data.count <= 0{ // self.navigationItem.rightBarButtonItem?.tintColor = .clear if informationView == nil { informationView = InformationView.loadView(self.promotionsTableView.bounds) informationView?.informationLabel.text = HippoStrings.noNotificationFound } self.informationView?.isHidden = false self.promotionsTableView.addSubview(informationView!) }else{ for view in promotionsTableView?.subviews ?? [UIView](){ if view is InformationView{ view.removeFromSuperview() } } self.informationView?.isHidden = true // self.navigationItem.rightBarButtonItem?.tintColor = HippoConfig.shared.theme.logoutButtonTintColor ?? HippoConfig.shared.theme.headerTextColor } DispatchQueue.main.async { self.promotionsTableView.reloadData() } } func clearAnnouncements(indexPath: IndexPath, isDeleteAllStatus: Int){ var params = [String : Any]() if isDeleteAllStatus == 0{ //self.channelIdsArr.append(data[indexPath.row].channelID) //self.channelIdsArr[0] = data[indexPath.row].channelID self.channelIdsArr.insert(data[indexPath.row].channelID, at: 0) if currentUserType() == .customer{ params = ["app_secret_key":HippoConfig.shared.appSecretKey, "en_user_id":HippoUserDetail.fuguEnUserID ?? "", "channel_ids":self.channelIdsArr, "delete_all_announcements":isDeleteAllStatus] as [String : Any] }else{ params = ["access_token": HippoConfig.shared.agentDetail?.fuguToken ?? "", "user_id": "\(currentUserId())", "channel_ids":self.channelIdsArr, "delete_all_announcements":isDeleteAllStatus] as [String : Any] } }else{ if currentUserType() == .customer{ params = ["app_secret_key":HippoConfig.shared.appSecretKey,"en_user_id":HippoUserDetail.fuguEnUserID ?? "","delete_all_announcements":isDeleteAllStatus] as [String : Any] }else{ params = ["access_token": HippoConfig.shared.agentDetail?.fuguToken ?? "", "user_id": "\(currentUserId())", "delete_all_announcements":isDeleteAllStatus] as [String : Any] } } HTTPClient.makeConcurrentConnectionWith(method: .POST, para: params, extendedUrl: AgentEndPoints.clearAnnouncements.rawValue) { (response, error, _, statusCode) in self.channelIdsArr.removeAll() if error == nil { //let r = response as? NSDictionary if isDeleteAllStatus == 0{ self.promotionsTableView.beginUpdates() self.data.remove(at: indexPath.row) self.states.remove(at: indexPath.row) self.promotionsTableView.deleteRows(at: [indexPath], with: .fade) self.promotionsTableView.endUpdates() }else{ self.data.removeAll() self.states.removeAll() //self.promotionsTableView.reloadData() //DispatchQueue.main.async { // self.promotionsTableView.reloadData() //} } self.noNotificationsFound() } } } } extension PromotionsViewController: UITableViewDelegate,UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let c = customCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: c.cellIdentifier, for: indexPath) as? PromtionCutomCell else { return UITableView.defaultCell() } cell.selectionStyle = .none cell.backgroundColor = .clear // cell.promotionTitle.text = "This is a new tittle" // cell.descriptionLabel.text = "This is description of promotion in a new format" // cell.set(data: data[indexPath.row]) return cell } else { guard let cell = tableView.dequeueReusableCell(withIdentifier: "PromotionTableViewCell", for: indexPath) as? PromotionTableViewCell else { return UITableView.defaultCell() } cell.selectionStyle = .none cell.backgroundColor = .clear cell.previewImage = {[weak self]() in DispatchQueue.main.async { let showImageVC: ShowImageViewController = ShowImageViewController.getFor(imageUrlString: self?.data[indexPath.row].imageUrlString ?? "") //showImageVC.shouldHidetopHeader = true self?.modalPresentationStyle = .overCurrentContext self?.present(showImageVC, animated: true, completion: nil) } } cell.set(data: data[indexPath.row]) cell.showReadMoreLessButton.tag = indexPath.row cell.showReadMoreLessButton.addTarget(self, action: #selector(expandCellSize(_:)), for: .touchUpInside) //cell.descriptionLabel.numberOfLines = 2 let values = data[indexPath.row] let croppedDescription = values.description?.count ?? 0 > 150 ? String(values.description?.prefix(150) ?? "") : values.description ?? "" cell.promotionTitle.attributedText = NSAttributedString(string: values.title ?? "") cell.fullDescriptionLabel.attributedText = NSAttributedString(string: values.description ?? "") cell.descriptionLabel.attributedText = NSAttributedString(string: croppedDescription) cell.descriptionLabel.dataDetectorTypes = UIDataDetectorTypes.all cell.fullDescriptionLabel.dataDetectorTypes = UIDataDetectorTypes.all if (values.description?.count)! > 150{ cell.showReadMoreLessButton.isHidden = false cell.showReadMoreLessButtonHeightConstraint.constant = 30 }else{ cell.showReadMoreLessButton.isHidden = true cell.showReadMoreLessButtonHeightConstraint.constant = 0 } if indexPath.row < states.count, states[indexPath.row] == true{ cell.descriptionLabel.isHidden = false cell.fullDescriptionLabel.isHidden = true cell.showReadMoreLessButton.setTitle(HippoStrings.readMore, for: .normal) cell.showReadMoreLessButton.titleLabel?.font = UIFont.regular(ofSize: 14.0) cell.showReadMoreLessButton.setTitleColor(HippoConfig.shared.theme.themeColor, for: .normal) }else if indexPath.row < states.count, states[indexPath.row] == false{ cell.descriptionLabel.isHidden = true cell.fullDescriptionLabel.isHidden = false cell.showReadMoreLessButton.setTitle(HippoStrings.readLess, for: .normal) cell.showReadMoreLessButton.titleLabel?.font = UIFont.regular(ofSize: 14.0) cell.showReadMoreLessButton.setTitleColor(HippoConfig.shared.theme.themeColor, for: .normal) }else{} return cell } } @objc func expandCellSize(_ sender:UIButton) { let row = sender.tag //let values = data[row] let indexpath = IndexPath(row: row, section: 0) guard let _ = self.promotionsTableView.cellForRow(at: indexpath) as? PromotionTableViewCell else { return } if states[row] == true{ states[row] = false UIView.setAnimationsEnabled(false) self.promotionsTableView.beginUpdates() self.promotionsTableView.reloadRows(at: [indexpath], with: .none) self.promotionsTableView.layoutIfNeeded() self.promotionsTableView.endUpdates() UIView.setAnimationsEnabled(true) // self.promotionsTableView.setContentOffset(currentOffset, animated: false) self.promotionsTableView.scrollToRow(at: indexpath, at: .top, animated: false) }else if states[row] == false{ states[row] = true UIView.setAnimationsEnabled(false) self.promotionsTableView.beginUpdates() self.promotionsTableView.reloadRows(at: [indexpath], with: .none) self.promotionsTableView.layoutIfNeeded() self.promotionsTableView.endUpdates() UIView.setAnimationsEnabled(true) // self.promotionsTableView.setContentOffset(currentOffset, animated: false) self.promotionsTableView.scrollToRow(at: indexpath, at: .middle, animated: false) }else{} } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let promotionData = data[indexPath.row] let deepLink = promotionData.deepLink if deepLink == "3x67AU1"{ HippoConfig.shared.getDeepLinkData(promotionData.customAttributeData ?? [String : Any]()) } } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { return HippoStrings.clear } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if (editingStyle == .delete) { self.clearAnnouncements(indexPath: indexPath, isDeleteAllStatus: 0) // }, failureButtonName: "NO", failureComplete: nil) } } } extension PromotionsViewController{ //MARK:- Save Promotions data in cache func savePromotionsInCache(_ json: [[String: Any]]) { guard shouldUseCache else { return } FuguDefaults.set(value: json, forKey: DefaultName.appointmentData.rawValue) //FuguDefaults.set(value: self.conversationChatType, forKey: "conversationType") } func fetchAllAnnouncementCache() -> [PromotionCellDataModel] { guard let convCache = FuguDefaults.object(forKey: DefaultName.appointmentData.rawValue) as? [[String: Any]] else { return [] } let arrayOfConversation = PromotionCellDataModel.getAnnouncementsArrayFrom(json: convCache) return arrayOfConversation } } extension PromotionsViewController : UIScrollViewDelegate { func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { self.reloadProducts(scrollView) } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate { self.reloadProducts(scrollView) } } func reloadProducts(_ scrollView: UIScrollView) { if scrollView == promotionsTableView{ if scrollView.frame.size.height + scrollView.contentOffset.y >= scrollView.contentSize.height, shouldFetchData{ if page > previousPage{ self.previousPage = page self.page += 1 let previousOffset = data.count getAnnouncements(endOffset: limit, startOffset: previousOffset) }else{ return } } } } } extension PromotionsViewController{ @objc func appMovedToBackground() { checkNetworkConnection() } @objc func appMovedToForground() { checkNetworkConnection() } func checkNetworkConnection() { errorLabel.backgroundColor = UIColor.red if FuguNetworkHandler.shared.isNetworkConnected { viewError_Height.constant = 0 errorLabel.text = "" } else { viewError_Height.constant = 20 errorContentView.backgroundColor = .red errorLabel.text = HippoStrings.noNetworkConnection } } // MARK: - HELPER func updateErrorLabelView(isHiding: Bool) { if isHiding { if self.viewError_Height.constant == 20 { fuguDelay(3, completion: { // self.errorLabelTopConstraint.constant = -20 self.errorLabel.text = "" self.viewError_Height.constant = 0 self.view.layoutIfNeeded() self.errorLabel.backgroundColor = UIColor.red }) } return }else{ viewError_Height.constant = 20 self.view.layoutIfNeeded() } } }
import Foundation extension String { func toDate() -> Date? { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" return formatter.date(from: self) } }
// // CXCommentRatingViewController.swift // Silly Monks // // Created by NUNC on 5/23/16. // Copyright © 2016 Sarath. All rights reserved. // import UIKit class CXCommentRatingViewController: UIViewController,FloatRatingViewDelegate,UITextViewDelegate { var ratingLabel:UILabel! var floatRatingView: FloatRatingView! var commentsView:UITextView! var cScrollView:UIScrollView! var jobID : String! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.smBackgroundColor() self.customizeHeaderView() self.customizeMainView() // Do any additional setup after loading the view. } func customizeHeaderView() { self.navigationController?.navigationBar.isTranslucent = false; self.navigationController?.navigationBar.barTintColor = UIColor.navBarColor() let lImage = UIImage(named: "left_aarow.png") as UIImage? let button = UIButton (type: UIButtonType.custom) as UIButton button.frame = CGRect(x: 0, y: 0, width: 30, height: 30) button.setImage(lImage, for: UIControlState()) button.backgroundColor = UIColor.clear button.addTarget(self, action: #selector(CXCommentRatingViewController.backAction), for: .touchUpInside) let navSpacer: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.fixedSpace,target: nil, action: nil) navSpacer.width = -16; self.navigationItem.leftBarButtonItems = [navSpacer,UIBarButtonItem.init(customView: button)] let tLabel : UILabel = UILabel() tLabel.frame = CGRect(x: 0, y: 0, width: 120, height: 40); tLabel.backgroundColor = UIColor.clear tLabel.font = UIFont.init(name: "Roboto-Bold", size: 18) tLabel.text = "Comments" tLabel.textAlignment = NSTextAlignment.center tLabel.textColor = UIColor.white self.navigationItem.titleView = tLabel } func customizeMainView() { self.cScrollView = UIScrollView.init(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height-65)) self.view.addSubview(self.cScrollView) let labelText = UILabel.init(frame: CGRect(x: 5, y: 0, width: (self.cScrollView.frame.size.width/2)-10, height: 45)) labelText.text = "YOUR RATING" labelText.font = UIFont(name: "Roboto-Regular", size:15) labelText.textAlignment = NSTextAlignment.left self.cScrollView.addSubview(labelText) self.ratingLabel = UILabel.init(frame: CGRect(x: labelText.frame.size.width+labelText.frame.origin.x+5, y: 0, width: (self.cScrollView.frame.size.width/2)-10, height: 45)) self.ratingLabel.text = "0.0" self.ratingLabel.font = UIFont(name: "Roboto-Regular",size: 15) self.ratingLabel.textAlignment = NSTextAlignment.right self.cScrollView.addSubview(self.ratingLabel) let ratWidth = self.cScrollView.frame.size.width/2 self.floatRatingView = self.customizeRatingView(CGRect(x: (self.cScrollView.frame.size.width-ratWidth)/2, y: self.ratingLabel.frame.size.height+self.ratingLabel.frame.origin.y,width: ratWidth, height: 40)) self.floatRatingView.backgroundColor = UIColor.clear self.cScrollView.addSubview(self.floatRatingView) self.commentsView = UITextView.init(frame: CGRect(x: 5, y: self.floatRatingView.frame.size.height+self.floatRatingView.frame.origin.y, width: self.cScrollView.frame.size.width-10, height: 220)) self.commentsView.delegate = self self.commentsView.font = UIFont(name: "Roboto-Regular", size: 15) self.commentsView.text = "Wrire at least 50 characters" self.commentsView.layer.borderColor = UIColor.darkGray.cgColor self.commentsView.layer.borderWidth = 1 self.cScrollView.addSubview(self.commentsView) self.addAccessoryViewToField(self.commentsView) let submitBtn = UIButton.init(frame: CGRect(x: 10, y: self.commentsView.frame.size.height+self.commentsView.frame.origin.y+10, width: self.cScrollView.frame.size.width-20, height: 40)) submitBtn.setTitle("Submit", for: UIControlState()) submitBtn.backgroundColor = UIColor.darkGray submitBtn.setTitleColor(UIColor.white, for: UIControlState()) submitBtn.addTarget(self, action: #selector(CXCommentRatingViewController.submitAction), for: UIControlEvents.touchUpInside) self.cScrollView.addSubview(submitBtn) } func submitAction() { if self.commentsView.text != nil { if self.commentsView.text.characters.count < 50 { self.showAlertView("Please enter at least 50 characters.", status: 0) }else{ self.submitTheComments() } } } func showAlertView(_ message:String, status:Int) { let alert = UIAlertController(title: "Smart Movie Ticket", message: message, preferredStyle: UIAlertControllerStyle.alert) //alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default, handler: nil)) let okAction = UIAlertAction(title: "Okay", style: UIAlertActionStyle.default) { UIAlertAction in if status == 1 { //self.navigationController?.popViewControllerAnimated(true) } } alert.addAction(okAction) self.present(alert, animated: true, completion: nil) } func customizeRatingView(_ frame:CGRect) -> FloatRatingView { let ratView : FloatRatingView = FloatRatingView.init(frame: frame) ratView.emptyImage = UIImage(named: "star_unsel_108.png") ratView.fullImage = UIImage(named: "star_sel_108.png") // Optional params ratView.delegate = self ratView.contentMode = UIViewContentMode.scaleAspectFit ratView.maxRating = 5 ratView.minRating = 0 ratView.rating = 0 ratView.editable = true ratView.halfRatings = true ratView.floatRatings = false return ratView } func addAccessoryViewToField(_ mTextView:UITextView) { let numToolBar = UIToolbar.init(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50)) numToolBar.barStyle = UIBarStyle.blackTranslucent let clearBtn = UIBarButtonItem.init(title: "Clear", style: UIBarButtonItemStyle.bordered, target: self, action: #selector(CXCommentRatingViewController.clearNumPadAction)) let flexSpace = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action:nil) let doneBtn = UIBarButtonItem.init(title:"Done", style: UIBarButtonItemStyle.done, target: self, action: #selector(CXCommentRatingViewController.doneNumberPadAction)) numToolBar.items = [clearBtn,flexSpace,doneBtn] numToolBar.sizeToFit() mTextView.inputAccessoryView = numToolBar } func doneNumberPadAction() { self.view.endEditing(true) } //MARK: Submit the comment func commentSubiturl(_ userID:String, jobID:String,comment:String,rating:String,commentId:String) ->String{ //let escapedString = productType.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) let reqString = CXConstant.sharedInstance.PRODUCTION_BASE_URL + "/jobs/saveJobCommentJSON?userId="+userID+"&jobId="+jobID+"&comment="+comment+"&rating="+rating+"&disabled=false" //http://storeongo.com:8081/jobs/saveJobCommentJSON?/ userId=11&jobId=239&comment=excellent&rating=0.5&commentId=74 let encodedPublicUrl = reqString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! return encodedPublicUrl } func submitTheComments(){ /* return getHostUrl(mContext) + "/jobs/saveJobCommentJSON?"; / userId=11&jobId=239&comment=excellent&rating=0.5&commentId=74 / */ LoadingView.show("Submitting...", animated: true) guard let userId = UserDefaults.standard.value(forKey: "USER_ID") else { return } let number = CXConstant.resultString((userId as? AnyObject)!) SMSyncService.sharedInstance.startSyncProcessWithUrl(self.commentSubiturl(number, jobID: self.jobID, comment: self.commentsView.text.trimmingCharacters(in: CharacterSet.whitespaces), rating: self.ratingLabel.text!, commentId: "1")) { (responseDict) in // print(responseDict) DispatchQueue.main.async(execute: { () -> Void in LoadingView.hide() let alert = UIAlertController(title: "Smart Movie Ticket", message:"Submitted Successfully" , preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: { (alert) in let viewcontrollers = self.navigationController?.viewControllers for vc in viewcontrollers! { if vc.isKind(of: SMCategoryViewController.self) { self.navigationController?.popToViewController(vc, animated: true) break } } })) self.present(alert, animated: true, completion: nil) }) } } /* */ func clearNumPadAction() { self.view.endEditing(true) self.commentsView.text = nil } func backAction() { self.navigationController?.popViewController(animated: true) } func floatRatingView(_ ratingView: FloatRatingView, isUpdating rating:Float) { //ratingView.rating = 0 // let signInView = CXSignInSignUpViewController.init() // self.navigationController?.pushViewController(signInView, animated: true) } func floatRatingView(_ ratingView: FloatRatingView, didUpdate rating: Float) { //ratingView.rating = 0 self.ratingLabel.text = NSString(format: "%.1f", self.floatRatingView.rating) as String } func textViewDidBeginEditing(_ textView: UITextView) { if textView.text == "Wrire at least 50 characters" { textView.text = "" } let scrollPoint = CGPoint(x: 0, y: textView.frame.origin.y) self.cScrollView.setContentOffset(scrollPoint, animated: true) } func textViewDidEndEditing(_ textView: UITextView) { textView.text = textView.text.trimmingCharacters(in: CharacterSet.whitespaces) if textView.text == nil { textView.text = "Wrire at least 50 characters" } self.cScrollView.setContentOffset(CGPoint.zero, animated: true) } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { textView.contentOffset = CGPoint(x: 0.0, y: textView.contentSize.height) } return true } func textViewDidChange(_ textView: UITextView) { // let line : CGRect = textView.caretRectForPosition((textView.selectedTextRange?.start)!) // let overFlow: CGFloat = (line.origin.y + line.size.height) - ((textView.contentOffset.y + textView.bounds.size.height) - textView.contentInset.bottom - textView.contentInset.top) // if overFlow > 0 { // var offset = textView.contentOffset // offset.y += overFlow+7 // UIView.animateWithDuration(0.2, animations: { // textView.setContentOffset(offset, animated: true) // }) // } } 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // ExampleIIIViewController.swift // View Animations Demo // // Created by Joyce Echessa on 1/30/15. // Copyright (c) 2015 Appcoda. All rights reserved. // import UIKit class ExampleIIIViewController: UIViewController { var alertView: UIView! override func viewDidLoad() { super.viewDidLoad() createView() } func createView() { // create red view let alertWidth: CGFloat = view.bounds.width let alertHeight: CGFloat = view.bounds.height let alertViewFrame: CGRect = CGRectMake(0, 0, alertWidth, alertHeight) alertView = UIView(frame: alertViewFrame) alertView.backgroundColor = UIColor.init(colorLiteralRed: 204/255.0, green: 149/255.0, blue: 149/255.0, alpha: 0.9) // create imageview and add it to the view let imageView = UIImageView(frame: CGRectMake(0, 0, alertWidth, alertHeight / 2)) imageView.image = UIImage(named: "bike_traveler.png") alertView.addSubview(imageView) // creating a button and add listener when is tapped let button = UIButton(type: UIButtonType.System) as UIButton button.setTitle("Dismiss", forState: UIControlState.Normal) button.backgroundColor = UIColor.whiteColor() let buttonWidth: CGFloat = alertWidth / 2 let buttonHeight: CGFloat = 40 button.frame = CGRectMake(alertView.center.x - buttonWidth / 2, alertView.center.y - buttonHeight / 2, buttonWidth, buttonHeight) button.addTarget(self, action: #selector(ExampleIIIViewController.dismissAlert), forControlEvents: UIControlEvents.TouchUpInside) alertView.addSubview(button) view.addSubview(alertView) } func dismissAlert() { let bounds = alertView.bounds let smallFrame = CGRectInset(alertView.frame, alertView.frame.size.width / 4, alertView.frame.size.height / 4) let finalFrame = CGRectOffset(smallFrame, 0, bounds.size.height) let snapshot = alertView.snapshotViewAfterScreenUpdates(false) snapshot.frame = alertView.frame view.addSubview(snapshot) alertView.removeFromSuperview() UIView.animateKeyframesWithDuration(4, delay: 0, options: .CalculationModeCubic, animations: { UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.5, animations: { snapshot.frame = smallFrame }) UIView.addKeyframeWithRelativeStartTime(0.5, relativeDuration: 0.5, animations: { snapshot.frame = finalFrame }) }, completion: nil) } }
import Foundation protocol Requirement { func check(in data: Data) -> Bool }
// // LocationViewController.swift // LocationApp // // Created by Choi, Helen B on 7/12/19. // Copyright © 2019 Ford, Ryan M. All rights reserved. // import UIKit import CoreLocation class LocationViewController: UIViewController, CLLocationManagerDelegate { //declare variables var startLocation: CLLocation! //Optional handles nils; lat long course info class var locationManager: CLLocationManager = CLLocationManager() //start&stop delivery of events @IBOutlet weak var Latitude: UILabel! @IBOutlet weak var Longitude: UILabel! @IBOutlet weak var hAccuracy: UILabel! @IBOutlet weak var Altitude: UILabel! @IBOutlet weak var vAccuracy: UILabel! @IBOutlet weak var Distance: UILabel! @IBOutlet weak var btnDist: UIButton! override func viewDidLoad() { if #available(iOS 13.0, *) { overrideUserInterfaceStyle = .light } else { // Fallback on earlier versions } super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.Distance.text = String(0) //Location Manager Setup locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.delegate = self //establish view controller as delegate startLocation = nil locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() } //end view did load @IBAction func resetDistance(_ sender: Any) { //Sets distance label to zero startLocation = nil } //end reset Distance //didupdatelocations: (protocol stub) tells the delegate that new location data is available. func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let latestLocation: CLLocation = locations[locations.count - 1] Latitude.text = String(format: "%.4f", latestLocation.coordinate.latitude) Longitude.text = String(format: "%.4f", latestLocation.coordinate.longitude) hAccuracy.text = String(format: "%.1f", latestLocation.horizontalAccuracy) Altitude.text = String(format: "%.1f", latestLocation.altitude) vAccuracy.text = String(format: "%.1f", latestLocation.verticalAccuracy) if startLocation == nil { startLocation = latestLocation } let distanceBetween: CLLocationDistance = latestLocation.distance(from: startLocation) let distanceBetweenFormatted = String(format: "%.2f", distanceBetween) Distance.text = "\(distanceBetweenFormatted) m from last reset" } //end locationManager func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { } //end didFailWithError @IBAction func dismissLocation(_ sender: Any) { self.dismiss(animated: true, completion: nil) } } //end class
// // HouseholdSetupViewController.swift // Choreboard // // Created by Yeon Jun Kim on 4/29/21. // import Foundation import UIKit import RealmSwift class HouseholdSetupViewController: UIViewController { let userRealm: Realm let newHouseholdButton = UIButton(type: .custom) let joinHouseholdButton = UIButton(type: .custom) init(userRealm: Realm) { self.userRealm = userRealm super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = "Setup" view.backgroundColor = .systemBackground navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: nil, action: nil) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(signOutButtonDidClick)) let container = UIStackView() container.translatesAutoresizingMaskIntoConstraints = false container.axis = .vertical container.distribution = .fillProportionally container.spacing = 10.0 view.addSubview(container) NSLayoutConstraint.activate([ container.heightAnchor.constraint(equalToConstant: 100), container.widthAnchor.constraint(equalToConstant: 250), container.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor, constant: 0), container.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor, constant: -50) ]) newHouseholdButton.addTarget(self, action: #selector(newHouseholdButtonDidClick), for: .touchUpInside) newHouseholdButton.translatesAutoresizingMaskIntoConstraints = false newHouseholdButton.setAttributedTitle( NSAttributedString( string: "Start a New Household", attributes: [ NSAttributedString.Key.font: UIFont(name: "Lato-Regular", size: 18)!, NSAttributedString.Key.foregroundColor: UIColor.white ] ), for: .normal ) newHouseholdButton.titleEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) newHouseholdButton.layer.cornerRadius = 5 newHouseholdButton.backgroundColor = UIColor(hex: "#6EADE9") newHouseholdButton.layer.borderWidth = 1 newHouseholdButton.layer.borderColor = UIColor(hex: "#6EADE9")!.cgColor container.addArrangedSubview(newHouseholdButton) joinHouseholdButton.addTarget(self, action: #selector(joinHouseholdButtonDidClick), for: .touchUpInside) joinHouseholdButton.translatesAutoresizingMaskIntoConstraints = false joinHouseholdButton.setAttributedTitle( NSAttributedString( string: "Join a Household", attributes: [ NSAttributedString.Key.font: UIFont(name: "Lato-Regular", size: 18)!, NSAttributedString.Key.foregroundColor: UIColor.white ] ), for: .normal ) joinHouseholdButton.titleEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) joinHouseholdButton.layer.cornerRadius = 5 joinHouseholdButton.backgroundColor = UIColor(hex: "#6EADE9") joinHouseholdButton.layer.borderWidth = 1 joinHouseholdButton.layer.borderColor = UIColor(hex: "#6EADE9")!.cgColor container.addArrangedSubview(joinHouseholdButton) } @objc func signOutButtonDidClick() { let alertController = UIAlertController(title: "Are you sure you want to sign out?", message: "", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Sign Out", style: .destructive, handler: { _ -> Void in print("Signing out...") app.currentUser?.logOut { (_) in DispatchQueue.main.async { print("Logged out!") self.navigationController?.popToViewController((self.navigationController?.viewControllers[2])!, animated: true) } } })) alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alertController, animated: true, completion: nil) } @objc func newHouseholdButtonDidClick() { self.navigationController?.pushViewController(NewHouseholdSetupViewController(userRealm: self.userRealm), animated: true) } @objc func joinHouseholdButtonDidClick() { self.navigationController?.pushViewController(JoinHouseholdSetupViewController(userRealm: self.userRealm), animated: true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
// // CGPath+Test.swift // Scalar2D // // Created by Glenn Howes on 8/13/16. // Copyright © 2016 Generally Helpful Software. All rights reserved. // // The MIT License (MIT) // Copyright (c) 2016 Glenn R. Howes // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // import Foundation import CoreGraphics public extension CGPath { func asString() -> String { let result = NSMutableString() self.iterate { (element) in let points = element.points switch element.type { case .moveToPoint: let newPoint = points.pointee let xString = String(format: "%.02f", newPoint.x) let yString = String(format: "%.02f", newPoint.y) result.append("M (\(xString), \(yString))\n") case .addLineToPoint: let newPoint = points.pointee let xString = String(format: "%.02f", newPoint.x) let yString = String(format: "%.02f", newPoint.y) result.append("L (\(xString), \(yString))\n") case .closeSubpath: result.append("Z\n") case .addCurveToPoint: let controlPoint1 = points.pointee let controlPoint2 = points.advanced(by: 1).pointee let nextPoint = points.advanced(by: 2).pointee let controlPoint1XString = String(format: "%.02f", controlPoint1.x) let controlPoint1YString = String(format: "%.02f", controlPoint1.y) let controlPoint2XString = String(format: "%.02f", controlPoint2.x) let controlPoint2YString = String(format: "%.02f", controlPoint2.y) let xString = String(format: "%.02f", nextPoint.x) let yString = String(format: "%.02f", nextPoint.y) result.append("C (\(controlPoint1XString), \(controlPoint1YString), \(controlPoint2XString), \(controlPoint2YString), \(xString), \(yString))\n") case .addQuadCurveToPoint: let quadControlPoint = points.pointee let nextPoint = points.advanced(by: 1).pointee let quadControlPointXString = String(format: "%.02f", quadControlPoint.x) let quadControlPointYString = String(format: "%.02f", quadControlPoint.y) let xString = String(format: "%.02f", nextPoint.x) let yString = String(format: "%.02f", nextPoint.y) result.append("Q (\(quadControlPointXString), \(quadControlPointYString), \(xString), \(yString))\n") } } return result as String } }
// // TrailingCanvas.swift // TrailingTest // // Created by 唐泽宇 on 2019/3/28. // Copyright © 2019 唐泽宇. All rights reserved. // import UIKit extension UIView { var snapshot: UIImage? { UIGraphicsBeginImageContext(bounds.size) drawHierarchy(in: bounds, afterScreenUpdates: true) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } } class TrailingCanvas: UIView,UIDropInteractionDelegate { var UILabelLocation = [CGFloat]() /*override init (frame: GCRect){ super.init(frame:frame) setup() }*/ required init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) setup() } private func setup() { addInteraction(UIDropInteraction(delegate: self)) } func dropInteraction(_ interaction: UIDropInteraction, canHandle session: UIDropSession) -> Bool { return session.canLoadObjects(ofClass: NSAttributedString.self) } func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: UIDropSession) -> UIDropProposal { return UIDropProposal(operation: .copy) } func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) { session.loadObjects(ofClass: NSAttributedString.self){ providers in let dropPoint = session.location(in: self) for attributedString in providers as? [NSAttributedString] ?? []{ self.addLabel(with: attributedString, centeredAt: dropPoint) } } } private func addLabel (with attributedString:NSAttributedString, centeredAt point: CGPoint){ let label = UILabel() label.backgroundColor = .clear label.attributedText = attributedString label.sizeToFit() label.center = point addSubview(label) UILabelLocation.append(point.x) print(point.x) } var numberOfStoping = 0 var time = 0 var timer = Timer() var lineColor:UIColor! var lineWidth:CGFloat! var path:UIBezierPath! var startingPoint:CGPoint! var endingPointX:CGFloat! var touchPoint: CGPoint! var TrailUserInputX = [CGFloat]() var TrailUserInputY = [CGFloat]() lazy var UserMatchingLocation = [UILabelLocation[0]] var strokeCollection: StrokeCollection? { didSet { // If the strokes change, redraw the view's content. if oldValue !== strokeCollection { setNeedsDisplay() } } } // Initialization methods... override func layoutSubviews() { self.clipsToBounds = true self.isMultipleTouchEnabled = false lineColor = UIColor.red lineWidth = 2.0 } @objc func startTiming () { time += 1 } // Touch Handling methods override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { //start timing timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(TrailingCanvas.startTiming), userInfo: nil, repeats: true) // Create a new stroke and make it the active stroke. let newStroke = Stroke() let touch = touches.first strokeCollection?.activeStroke = newStroke startingPoint = touch?.preciseLocation(in: self) TrailUserInputX.append(startingPoint.x) TrailUserInputY.append(startingPoint.y) // The view does not support multitouch, so get the samples // for only the first touch in the event. if let coalesced = event?.coalescedTouches(for: touches.first!) { addSamples(for: coalesced) } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first touchPoint = touch?.preciseLocation(in: self) path = UIBezierPath() path.move(to: startingPoint) path.addLine(to: touchPoint) startingPoint = touchPoint TrailUserInputX.append(touchPoint.x) TrailUserInputY.append(touchPoint.y) drawShapeLayer() if let coalesced = event?.coalescedTouches(for: touches.first!) { addSamples(for: coalesced) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { //timer //timer.invalidate() // Accept the current stroke and add it to the stroke collection. if let coalesced = event?.coalescedTouches(for: touches.first!) { addSamples(for: coalesced) } // Accept the active stroke. strokeCollection?.acceptActiveStroke() endingPointX = TrailUserInputX.last if endingPointX != nil { UserMatchingLocation.append(endingPointX!) } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { // Clear the last stroke. strokeCollection?.activeStroke = nil } func drawShapeLayer(){ let shapeLayer = CAShapeLayer() shapeLayer.path = path.cgPath shapeLayer.strokeColor = lineColor.cgColor shapeLayer.lineWidth = lineWidth shapeLayer.fillColor = UIColor.clear.cgColor self.layer.addSublayer(shapeLayer) self.setNeedsDisplay() /*print("This is x-coordiante: \(TrailUserInputX)") print("This is y-coordinate: \(TrailUserInputY)")*/ } class Stroke { var samples = [StrokeSample]() func add(sample: StrokeSample) { samples.append(sample) } } struct StrokeSample { let location: CGPoint let coalescedSample: Bool init(point: CGPoint, coalesced : Bool = false) { location = point coalescedSample = coalesced } } func addSamples(for touches: [UITouch]) { if let stroke = strokeCollection?.activeStroke { // Add all of the touches to the active stroke. for touch in touches { if touch == touches.last { let sample = StrokeSample(point: touch.preciseLocation(in: self)) stroke.add(sample: sample) } else { // If the touch is not the last one in the array, // it was a coalesced touch. let sample = StrokeSample(point: touch.preciseLocation(in: self), coalesced: true) stroke.add(sample: sample) } } // Update the view. self.setNeedsDisplay() } } class StrokeCollection { var strokes = [Stroke]() var activeStroke: Stroke? = nil func acceptActiveStroke () { if let stroke = activeStroke { strokes.append(stroke) activeStroke = nil } } } func ClearCanvas () { path.removeAllPoints() //self.layer.sublayers = nil self.setNeedsDisplay() } }
// // MockGifService.swift // Hammer // // Created by Mike Sabo on 11/7/15. // Copyright © 2015 FlyingDinosaurs. All rights reserved. // import Foundation import SwiftyJSON class MockGifService : GifService { let gifResponse = Gifs(gifsJSON: JSON(data: TestingHelper.jsonFromFile("gifs"))) override func getGifsResponse() -> SignalProducer<Gifs, NSError> { return SignalProducer { observer, disposable in observer.sendNext(self.gifResponse) observer.sendCompleted() } } override func getGifsForTagSearchResponse(_ query: String) -> SignalProducer<Gifs, NSError> { return SignalProducer { observer, disposable in let singleGif = Gifs() singleGif.gifs = [self.gifResponse.gifs[0]] observer.sendNext(singleGif) observer.sendCompleted() } } override func retrieveImageDataFor(gif: Gif) -> SignalProducer<NSData?, NSError> { return SignalProducer { observer, disposable in print("in here") let singleGif = self.gifResponse.gifs[0] observer.sendNext(singleGif.thumbnailData) observer.sendCompleted() } } override func retrieveThumbnailImageFor(gif: Gif) -> SignalProducer<Gif, NSError> { return SignalProducer { observer, disposable in let singleGif = self.gifResponse.gifs[0] observer.sendNext(singleGif) observer.sendCompleted() } } }
// // OneSignalResult.swift // OneSignal // // Created by Anthony Castelli on 9/5/18. // import Foundation import Vapor public enum OneSignalError: Swift.Error { case `internal` case invalidURL case apiKeyNotSet case appIDNotSet case requestError(value: String) case decodingError } public enum OneSignalResult { case success case error(error: OneSignalError) case networkError(error: Error) }
// // BookDetailModel.swift // SendbirdAssignment_TaeHyeongKim // // Created by TaeHyeong Kim on 2021/02/15. // import Foundation struct BookDetailModel: Decodable { var error: String? var title: String? var subtitle: String? var authors: String? var publisher: String? var language: String? var isbn10: String? var isbn13: String? var pages: String? var year: String? var rating: String? var desc: String? var price: String? var image: String? var url: String? }
import Foundation class ReservaHistorial: NSObject, Codable { var id :Int? var locker_id :Int? var usuario_id :Int? var precio_total :Int? var tiempo_fin :String? var tiempo_inicio :String? var tiempo_retorno :String? var nombre_lugar :String? init(locker_id: Int, usuario_id:Int, precio_total:Int, tiempo_fin:String,tiempo_inicio:String,tiempo_retorno:String, nombre_lugar:String) { self.locker_id=locker_id self.usuario_id=usuario_id self.precio_total=precio_total self.tiempo_fin=tiempo_fin self.tiempo_inicio=tiempo_inicio self.tiempo_retorno=tiempo_retorno self.nombre_lugar=nombre_lugar } /*init(pId :String, pIdLocker :String, pIdUsuario :String, pLugarReserva :String, pPrecioTotal :Double, pTiempoFin :Int, pTiempoInicio :Int, pTiempoRetorno :Int) { id = pId idLocker = pIdLocker idUsuario = pIdUsuario lugarReserva = pLugarReserva precioTotal = pPrecioTotal tiempoFin = pTiempoFin tiempoInicio = pTiempoInicio tiempoRetorno = pTiempoRetorno }*/ }
// // UserPickerViewController.swift // NoteTaker // // Created by howard.lee on 11/15/15. // Copyright © 2015 howard.lee. All rights reserved. // import Foundation import UIKit class UserPickerViewController: UIViewController { let maximumUserNameLength = 16 @IBOutlet weak var tableView: UITableView! var allUsers: [User] { get { return appDelegate.allUsers } set { appDelegate.allUsers = newValue } } func showNameAlertWithTitle(title: String, message: String, handler: (String -> Void)) { let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) let okAction = UIAlertAction(title: "Confirm", style: .Default, handler: { (_) -> Void in let newName = alert.textFields![0].text! handler(newName) }) alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in textField.placeholder = "Enter name here" NSNotificationCenter.defaultCenter().addObserverForName(UITextFieldTextDidChangeNotification, object: textField, queue: NSOperationQueue.mainQueue(), usingBlock: { (notification) -> Void in // Restrict the name of the strength let text = textField.text! if text.characters.count > self.maximumUserNameLength { textField.text = text.substringToIndex(text.startIndex.advancedBy(self.maximumUserNameLength)) } // Set done button to enabled if text has been entered okAction.enabled = textField.text != "" }) }) alert.addAction(cancelAction) alert.addAction(okAction) self.presentViewController(alert, animated: true, completion: nil) } func createUserWithName(name: String) { let newUser = User(name: name, context: CoreDataStackManager.sharedInstance().managedObjectContext) CoreDataStackManager.sharedInstance().saveContext() allUsers.append(newUser) tableView.reloadData() } } extension UserPickerViewController: UITableViewDelegate, UITableViewDataSource { func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let row = indexPath.row if row < allUsers.count { // this is an actual user cell let cell = tableView.dequeueReusableCellWithIdentifier("user_cell") as! UserPickerTableViewCell cell.name = allUsers[row].name cell.count = allUsers[row].notes.count return cell } else { // this is the add user cell let cell = tableView.dequeueReusableCellWithIdentifier("add_user_cell")! return cell } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return allUsers.count + 1 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let row = indexPath.row if row < allUsers.count { // this is a user cell appDelegate.currentUser = allUsers[row] dismissViewControllerAnimated(true, completion: nil) } else { // this is the add user cell showNameAlertWithTitle("New User", message: "Enter the name of the user below", handler: { [unowned self] (name) -> Void in self.createUserWithName(name) }) } } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // all rows except the edit cell are editable return indexPath.row < allUsers.count } func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let deleteAction = UITableViewRowAction(style: .Destructive, title: "Delete") { [unowned self] (_, indexPath) -> Void in let row = indexPath.row let user = self.allUsers[row] CoreDataStackManager.sharedInstance().managedObjectContext.deleteObject(user) CoreDataStackManager.sharedInstance().saveContext() self.allUsers.removeAtIndex(row) self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Bottom) } let editAction = UITableViewRowAction(style: .Default, title: "Rename") { [unowned self] (_, indexPath) -> Void in self.showNameAlertWithTitle("Rename User", message: "Enter the user's new name below", handler: { (name) -> Void in self.allUsers[indexPath.row].name = name CoreDataStackManager.sharedInstance().saveContext() (tableView.cellForRowAtIndexPath(indexPath) as! UserPickerTableViewCell).name = name tableView.setEditing(false, animated: true) }) } editAction.backgroundColor = UIColor.blueColor() return [deleteAction, editAction] } }
import XCTest @testable import SmartyStreets class SmartyResponseTests: XCTestCase { override func setUp() { } override func tearDown() { } func testInit() { let payload = Data(count: 5) let response = SmartyResponse(statusCode:200, payload: payload) XCTAssertEqual(response.statusCode, 200) XCTAssertEqual(response.payload.count, 5) } }
// // getMotion.swift // MotionVisualize // // Created by 合田 和馬 on 2017/01/14. // Copyright © 2017年 Project. All rights reserved. // import UIKit import CoreMotion import Pulsator import SpriteKit import Starscream let kMaxRadius: CGFloat = 200 let kMaxDuration: TimeInterval = 10 class getMotion: UIViewController, WebSocketDelegate { @IBOutlet weak var sourceView: UIImageView! @IBOutlet weak var graphView: UIView! private var motionManager: CMMotionManager!//CMMotion使うためのやつ1 let pulsator = Pulsator() let socket = WebSocket(url: URL(string: "ws://motionvisualizer.herokuapp.com")!) override func viewDidLoad() { super.viewDidLoad() socket.delegate = self socket.connect() //波紋の描画 sourceView.layer.addSublayer(pulsator) pulsator.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1).cgColor pulsator.numPulse = 3 pulsator.radius = 120.0 //センサー情報の通知の開始 motionManager = CMMotionManager() motionManager.deviceMotionUpdateInterval = 0.2//加速度の取得間隔 motionManager.startDeviceMotionUpdates(to: OperationQueue.current!, withHandler: {deviceManager, error in let accel: CMAcceleration = deviceManager!.userAcceleration let text:String = "".appendingFormat("%.4f", accel.x) + "," + "".appendingFormat("%.4f", accel.y) self.socket.write(string: text) }) Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(getMotion.onTick(_:)), userInfo: nil, repeats: false) } func websocketDidConnect(socket: WebSocket) { print("websocket is connected") } func websocketDidDisconnect(socket: WebSocket, error: NSError?) { if let e = error { print("websocket is disconnected: \(e.localizedDescription)") } else { print("websocket disconnected") } } func websocketDidReceiveMessage(socket: WebSocket, text: String) { print("Received text: \(text)") } func websocketDidReceiveData(socket: WebSocket, data: Data) { print("Received data: \(data.count)") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } @IBAction func stop(_ sender: AnyObject) { pulsator.start() } //0.1秒間隔の定期処理 func onTick(_ timer: Timer){ pulsator.start() } @IBAction func back(_ sender: AnyObject) { self.dismiss(animated: true, completion: nil) } @IBAction func result(_ sender: AnyObject) { let targetView = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "result") targetView.modalTransitionStyle = UIModalTransitionStyle.crossDissolve self.present(targetView, animated: true, completion: nil) } }
import Foundation import ConsoleKit protocol StackableController: class { var parentController: StackableController? { get set } func start() func push(child controller: BaseController) func pop() } class BaseController: Identifiable, StackableController { // MARK: Initialization init(with context: AppContext) { self.context = context context.push() } // MARK: Deinitialization deinit { context.pop() } // MARK: Properties (Public) private(set) var id : UUID = UUID() let context : AppContext let console : Console = Terminal() weak var parentController: StackableController? { willSet { guard newValue == nil else { return } guard let parentController = self.parentController as? BaseController else { return } if let idx = parentController.childControllers.firstIndex(where: { $0.id == self.id }) { parentController.childControllers.remove(at: idx) } } } var childControllers: [BaseController] = [] func start() { /* no-op */ } func push(child controller: BaseController) { controller.parentController = self childControllers.append(controller) controller.start() } func pop() { self.parentController = nil } }
// // CollectionViewSupplementaryViewHeight.swift // AirCollection // // Created by Lysytsia Yurii on 15.07.2020. // Copyright © 2020 Developer Lysytsia. All rights reserved. // import struct CoreGraphics.CGFloat import class UIKit.UICollectionView /// Model for set collection view header or footer height public enum CollectionViewSupplementaryViewHeight { /// Collection view section header or footer height will be `CGSize.zero`. So collection view section header or footer won't be visible case none /// Dynamic collection view section header or footer height. Height will be calculated automatically and save to cache case flexible /// Fixed collection view section header or footer height case fixedHeight(CGFloat) }
// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | FileCheck %s // REQUIRES: objc_interop import Foundation class MyFunkyDictionary: NSDictionary { // CHECK-LABEL: sil hidden @_TZFC23super_objc_class_method17MyFunkyDictionary10initializefT_T_ // CHECK: super_method [volatile] %0 : $@thick MyFunkyDictionary.Type, #NSObject.initialize!1.foreign : (NSObject.Type) -> () -> () override class func initialize() { super.initialize() } }
// // contributionListCell.swift // mcwa // // Created by XingfuQiu on 15/10/21. // Copyright © 2015年 XingfuQiu. All rights reserved. // import UIKit class contributionListCell: UITableViewCell { @IBOutlet weak var lb_title: UILabel! @IBOutlet weak var lb_answerCount: UILabel! @IBOutlet weak var lb_accuracy: UILabel! @IBOutlet weak var lb_time: UILabel! @IBOutlet weak var iv_statusIcon: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) selectionStyle = .None // Configure the view for the selected state } func update(json: JSON) { // println(json) lb_title.text = json["title"].stringValue let dt = json["insertTime"].stringValue lb_time.text = dt //nopass(未通过) pass(通过) passing(审核中) let st = json["status"].stringValue switch st { case "pass": iv_statusIcon.image = UIImage(named: "cont_1") lb_answerCount.textColor = UIColor.whiteColor() lb_answerCount.text = json["allCount"].stringValue let rightCount = json["rightCount"].floatValue let allCount = json["allCount"].floatValue var accuracy: Float if allCount > 0 { accuracy = (rightCount / allCount) * 100 } else { accuracy = 0 } lb_accuracy.text = "正确率:\(Int(accuracy))%" lb_accuracy.hidden = false case "passing": iv_statusIcon.image = UIImage(named: "cont_2") lb_answerCount.textColor = UIColor(hexString: "#9090C6") lb_answerCount.text = "审核中" lb_accuracy.hidden = true case "nopass": iv_statusIcon.image = UIImage(named: "cont_3") lb_answerCount.textColor = UIColor(hexString: "#9090C6") lb_answerCount.text = "未通过" lb_accuracy.hidden = true default: break } } }
// // MediaDetailView.swift // App04-TMDB // // Created by David Cantú Delgado on 27/10/21. // import SwiftUI import Kingfisher struct MediaDetailView: View { @ObservedObject var mediaModel: MediaModel var media: Media var type: String var body: some View { GeometryReader { geo in VStack { Text(media.title) .font(.largeTitle) .fontWeight(.bold) Text(media.release_date) .font(.caption) ScrollView(.vertical, showsIndicators: false) { Text(media.overview) .font(.body) .multilineTextAlignment(.center) NavigationLink(destination: VideosListView(mediaModel: mediaModel, media: media, type: type)) { HStack { Image(systemName: "tv.and.mediabox") Text("Trailers") .font(.title2) } .foregroundColor(.white) .padding() .background(.blue) .cornerRadius(20) } KFImage(URL(string: "\(imageURL)\(media.poster)")) .resizable() .aspectRatio(contentMode: .fit) .frame(width: geo.size.width-20) } } .padding(.horizontal,10) .navigationBarTitle("Movie") } } } struct MediaDetailView_Previews: PreviewProvider { static var previews: some View { MediaDetailView(mediaModel: MediaModel(), media: Media.dummy, type: "movie") } }
// // StarSidebar.swift // StarSidebar // // Created by Linus Skucas on 8/20/21. // import CoreData import SwiftUI struct StarSidebar: View { @Environment(\.managedObjectContext) private var viewContext @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Star.creationDate, ascending: true)], animation: .default) private var stars: FetchedResults<Star> @State private var isShowingNewStarSheet = false var body: some View { List { ForEach(stars) { star in NavigationLink { StarDetailView(star: star) .toolbar { ToolbarItem { Button { if star.lookedAt { markStarAsUnread(star) } else { markStarAsRead(star) } } label: { Label("Mark as \(star.lookedAt ? "Unread" : "Read")", systemImage: star.lookedAt ? "xmark.seal" : "checkmark.seal") } .keyboardShortcut("u", modifiers: [.command, .shift]) } } } label: { StarSidebarCell(star: star) } .onDeleteCommand { deleteStar(star) } .contextMenu { Button("Delete") { deleteStar(star) } if star.lookedAt { Button("Mark as Unread") { markStarAsUnread(star) } } else { Button("Mark as Read") { markStarAsRead(star) } } } } .onDelete(perform: deleteStars) } .navigationTitle(Text("Stars")) .frame(minWidth: 280) .toolbar { Button { isShowingNewStarSheet.toggle() } label: { Label("New Star", systemImage: "plus") } } .sheet(isPresented: $isShowingNewStarSheet) { StarCreationSheet() } } private func deleteStars(offsets: IndexSet) { withAnimation { offsets.map { stars[$0] }.forEach(viewContext.delete) do { try viewContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nsError = error as NSError fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } } } private func deleteStar(_ star: Star) { withAnimation { viewContext.delete(star) try! viewContext.save() } } private func markStarAsRead(_ star: Star) { withAnimation { star.lookedAt = true star.dateLookedAt = Date() try! viewContext.save() } } private func markStarAsUnread(_ star: Star) { withAnimation { star.lookedAt = false star.dateLookedAt = nil try! viewContext.save() } } }
// // AlphabetCareInfoView.swift // KokaiByWGO // // Created by Waleerat Gottlieb on 2021-06-03. // import SwiftUI struct CardInfoView: View { @State var infoHeader: String @State var infoDetail: String var body: some View { HStack { Text(infoHeader) .foregroundColor(Color.black) .font(.title2) .fontWeight(.bold) Spacer() Text(infoDetail) .foregroundColor(Color.black) .font(.title2) } } } struct AlphabetCareInfoView_Previews: PreviewProvider { static var previews: some View { CardInfoView(infoHeader: "infoHeader", infoDetail: "infoDetail") .previewLayout(.fixed(width: 375, height: 60)) } }
// // ViewController.swift // horizontalScroller-tvOS // // Created by Robert Chen on 5/16/16. // Copyright © 2016 Robert Chen. All rights reserved. // import UIKit class ViewController: UITableViewController { } extension ViewController { override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("tableCell")! return cell } } extension ViewController { override func tableView(tableView: UITableView, canFocusRowAtIndexPath indexPath: NSIndexPath) -> Bool { return false } }
import UIKit // #-#-#-#-#-#-#-#-#-#-#-#-#-#-# // MARK: - UIImageView Extension // #-#-#-#-#-#-#-#-#-#-#-#-#-#-# extension UIImageView { func setImageFromURLInGuideCategoryList(url: URL) { // self.image = UIImage.init(named: "") // DispatchQueue.main.async { // self.af_setImage(withURL: url) // } let placeHolderImage = UIImage(named: "") self.sd_setImage(with: url, placeholderImage: placeHolderImage , options: kImageOptions, completed: { _, _, _, _ in }) } func setImageFromURLInCategoryList(url: URL) { // self.image = UIImage.init(named: "ic_ListViewPlaceHolder") // DispatchQueue.main.async { // self.af_setImage(withURL: url) // } let placeHolderImage = UIImage(named: "ic_ListViewPlaceHolder") self.sd_setImage(with: url, placeholderImage: placeHolderImage, options: kImageOptions, completed: { image, _, _, _ in if image == nil { // url.reamoveImageFromCache() self.image = UIImage.init(named: "ic_ListViewPlaceHolder") } }) } func setImageFromURLInCategoryDetails(url: URL) { // self.image = UIImage.init(named: "ic_ListDetailsPlaceHolder") // DispatchQueue.main.async { // self.af_setImage(withURL: url) // } let placeHolderImage = UIImage(named: "ic_ListDetailsPlaceHolder") self.sd_setImage(with: url, placeholderImage: placeHolderImage, options: kImageOptions, completed: { image, _, _, _ in if image == nil { // url.reamoveImageFromCache() self.image = UIImage.init(named: "ic_ListDetailsPlaceHolder") } }) } func setImageFromURLInCategoryListWithRenderingMode(url: URL) { // self.af_setImage(withURL: url) let placeHolderImage = UIImage(named: "") self.sd_setImage(with: url, placeholderImage: placeHolderImage, options: kImageOptions, completed: { _, _, _, _ in self.image = self.image?.withRenderingMode(.alwaysTemplate) self.tintColor = colorTabTint }) } func setImageDataFromURL(data: Data) { self.image = UIImage.init(data: data) } }
// // GameScene.swift // Jelly Jolly // // Created by Layal Alzaydi on 2020-01-02. // Copyright © 2020 Layal Alzaydi. All rights reserved. // import SpriteKit import GameplayKit var player = SKSpriteNode() var playercolor = UIColor.red var backgroundcolorCustom = UIColor(displayP3Red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) var playerSize = CGSize(width: 80, height: 80) var touchlocation = CGPoint() class GameScene: SKScene { private var label : SKLabelNode? private var spinnyNode : SKShapeNode? func spwanPlayer(){ player = SKSpriteNode(color: playercolor, size: playerSize) player.position = CGPoint(x: self.frame.midX, y: self.frame.midY + 200) self.addChild(player) } override func didMove(to view: SKView) { self.backgroundColor = backgroundcolorCustom spwanPlayer() } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches{ touchlocation = touch.location(in: self) player.position.x = touchlocation.x player.position.y = touchlocation.y } } override func update(_ currentTime: TimeInterval) { // Called before each frame is rendered } }
// // PacketTunnelProvider.swift // TunnelExtension // // Created by code8 on 16/11/27. // Copyright © 2016年 code8. All rights reserved. // import NetworkExtension import CocoaLumberjack import CocoaLumberjack import CocoaLumberjackSwift let ShadowVPNTunnelProviderErrorDomain = "ShadowVPNTunnelProviderErrorDomain" func synchronizd(lock: AnyObject, closure:()->()) { objc_sync_enter(lock) closure() objc_sync_exit(lock); } enum TunnelProviderErrorCode : Int { case TunnelProviderErrorCodeInvalidConfiguration = 0 case TunnelProviderErrorCodeDNSFailed = 1 } class PacketTunnelProvider: NEPacketTunnelProvider { var udpsession : NWUDPSession? = nil var sharedDefaults :UserDefaults? = nil var hostIPAddress : String? = nil var outgoinBuffer : NSMutableArray? = nil // var dispatchQueue : DispatchQueue? = nil var settings : SettingModel? = nil var dnsServer : DNSServer? = nil var systemServer : String? = nil let vpnCrypto : ShadowVPNCrypto = ShadowVPNCrypto() var lastPath : NWPath? = nil override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) { DDLog.removeAllLoggers() DDLog.add(DDTTYLogger.sharedInstance(),with : DDLogLevel.debug) DDLogDebug("statart tunnel ") // Add code here to start the process of connecting the tunnel. outgoinBuffer = NSMutableArray(capacity: 100) dispatchQueue = DispatchQueue(label :"TunnelProvider") NotificationCenter.default.addObserver(self, selector: #selector(PacketTunnelProvider.interfaceDidChange), name: NSNotification.Name(rawValue: NetworkInterfaceManagerInterfaceDidChange), object: nil) dispatchQueue?.async { let setting = SettingModel.settingsFromAppGroupContainer()! self.settings = setting do{ try self.settings?.validate() // self.addObserver(self, forKeyPath: "defaultPath", options: NSKeyValueObservingOptions(rawValue: 0), context: nil) self.vpnCrypto.setPassword(password: (self.settings?.password)!) self.startConnectionWithCompletionHandler(completionHandler: completionHandler) }catch{ let newError = NSError(domain: ShadowVPNTunnelProviderErrorDomain , code: TunnelProviderErrorCode.TunnelProviderErrorCodeInvalidConfiguration.rawValue, userInfo: [NSLocalizedDescriptionKey : "no config settings"]) completionHandler(newError) return } } } //route dns mtu func prepareTunnelNetworkSettings()-> NEPacketTunnelNetworkSettings { let nesettings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress:self.hostIPAddress!) nesettings.iPv4Settings = NEIPv4Settings(addresses: [(self.settings?.clientIP)!], subnetMasks:[(self.settings?.subnetMasks)!]) let routingMode = self.settings?.routingMode if routingMode == RoutingMode.RoutingModeChnroute{ self.setupChnroute(settings: nesettings.iPv4Settings!) }else if routingMode == RoutingMode.RoutingModeBestroutetb { self.setupBestroutetb(settings: nesettings.iPv4Settings!) }else{ nesettings.iPv4Settings?.includedRoutes = [] nesettings.iPv4Settings?.excludedRoutes = [] } var includedRoutes = nesettings.iPv4Settings?.includedRoutes ?? [NEIPv4Route]() var excludedRoutes = nesettings.iPv4Settings?.excludedRoutes ?? [NEIPv4Route]() includedRoutes.append(NEIPv4Route.default()) includedRoutes.append(NEIPv4Route(destinationAddress: (self.settings?.DNS)! ,subnetMask:"255.255.255.255")) excludedRoutes.append(NEIPv4Route(destinationAddress: (self.settings?.chinaDNS)! ,subnetMask:"255.255.255.255")) nesettings.iPv4Settings?.includedRoutes = includedRoutes nesettings.iPv4Settings?.excludedRoutes = excludedRoutes nesettings.dnsSettings = NEDNSSettings(servers: ["127.0.0.1"]) //nesettings.dnsSettings = NEDNSSettings(servers: ["223.5.5.5"]) nesettings.mtu = NSNumber(integerLiteral: (self.settings?.MTU)!) return nesettings } func startConnectionWithCompletionHandler(completionHandler: @escaping (NSError?) -> Void){ self.loadSystemDNSServer() let result = self.dnsResolveWithHost(host: (self.settings?.hostname)!) if result.count==0 { let error = NSError(domain: ShadowVPNTunnelProviderErrorDomain , code: TunnelProviderErrorCode.TunnelProviderErrorCodeInvalidConfiguration.rawValue, userInfo: [NSLocalizedDescriptionKey : "no Dns failed"]) completionHandler(error) return } self.hostIPAddress = result.firstObject as! String? let nesettings = self.prepareTunnelNetworkSettings() //建立隧道 self.setTunnelNetworkSettings(nesettings, completionHandler: { (error : Error?)->Void in if (error != nil) { completionHandler(error as NSError?) }else{ completionHandler(nil) self.dispatchQueue?.async { self.setupUDPSession() self.setupDNSSer() // NetworkInterfaceManager.sharedInstance().monitorInterfaceChange() self.readTun() } } }) } // //网络发生变化需要重新链接 func interfaceDidChange(){ dispatchQueue?.async { print("hello") self.reasserting = true self.releaseUDPSession() self.releaseDNSServer() self.setTunnelNetworkSettings(nil, completionHandler: { (error : Error?)->Void in if (error != nil) { self.cancelTunnelWithError(error) }else{ self.dispatchQueue?.async { self.startConnectionWithCompletionHandler(completionHandler: { (error : NSError?)->Void in if error != nil { self.cancelTunnelWithError(error) }else{ self.reasserting = false } }) } } }) } } //DNS服务 func setupDNSSer(){ dnsServer = DNSServer() dnsServer?.setupOutGoinConnectionWithTunnelProvider(provider: self, chinaDNS: (settings?.chinaDNS ?? systemServer)!, globalDNS: (settings?.DNS)!) dnsServer?.startServer() } //系统的DNS服务 func loadSystemDNSServer(){ // res_init() res_9_init() if _res.nscount>0 { let addr = _res.nsaddr_list.0.sin_addr systemServer = String(cString:inet_ntoa(addr)) }else{ systemServer = nil } } //建立与远程主机的UDP链接 func setupUDPSession(){ if udpsession != nil { return } let endpoint = NWHostEndpoint(hostname: hostIPAddress!, port: String(format: "%d",(settings?.port)!)) udpsession = self.createUDPSession(to: endpoint, from: nil) udpsession?.setReadHandler({ (datagrams : [Data], error : Error?)->Void in if(error != nil){ return }else{ self.processUDPIncomingDatagrams(datagrams: datagrams) } }, maxDatagrams: Int(INT32_MAX)) } //处理从远程主机发来的数据包,需要解密 func processUDPIncomingDatagrams(datagrams : [Data] ) { var result = [NSData]() var protocols = [NSNumber]() for (index,data) in datagrams.enumerated(){ let decryptedData = vpnCrypto.decryptData(data: NSData(data:data)) if decryptedData == nil { DDLogDebug("decrydata form incoming session failed!") return } result.append(decryptedData! as NSData) protocols.append(NSNumber(value: AF_INET)) } //写入隧道中 self.packetFlow.writePackets(result as [Data], withProtocols: protocols) } //读取隧道的数据 func readTun(){ self.packetFlow.readPackets { (packets : [Data], protocols :[NSNumber]) in var datas = [Any]() for (idx, data) in packets.enumerated() { if protocols[idx].int32Value != AF_INET{ return } let encrytedData = self.vpnCrypto.encryptData(data: NSData(data:data)) if encrytedData == nil{ return } datas.append(encrytedData as Any) } synchronizd(lock: self, closure: { (self.outgoinBuffer?.addObjects(from: datas ))! }) self.processOutgoingBuffer() //循环 self.readTun() } } //把上一步加密的数据发送到远程服务器里面 func processOutgoingBuffer(){ if udpsession == nil || udpsession?.state != NWUDPSessionState.ready { return } var datas :[Any]? = nil synchronizd(lock: self, closure:{ if outgoinBuffer?.count == 0 { return } datas = outgoinBuffer?.copy() as! [Any]? outgoinBuffer?.removeAllObjects() }) udpsession?.writeMultipleDatagrams(datas as! [Data], completionHandler: { (error : Error?)->Void in if error != nil { //处理失败的情况 synchronizd(lock: self, closure: { self.outgoinBuffer?.addObjects(from: datas! ) }) } }) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { // if (object as! NWUDPSession) == udpsession && keyPath == "state" { // // if udpsession?.state == NWUDPSessionState.failed || udpsession?.state == NWUDPSessionState.cancelled { // self.processOutgoingBuffer() // }else { // // } // //不够规范 // }else if (object as! PacketTunnelProvider) == self && keyPath == "defaultPath" { // if self.defaultPath?.status == NWPathStatus.satisfied && (self.defaultPath?.isEqual(to: self.lastPath!)==false) { // if self.lastPath != nil{ // self.lastPath = self.defaultPath // }else{ // //net work change // NetworkInterfaceManager.sharedInstance().updateInterfaceInfo() // } // } // // }else{ super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) // } } func releaseUDPSession(){ if udpsession != nil{ // udpsession?.removeObserver(self, forKeyPath: "state") udpsession = nil } } func releaseDNSServer(){ if dnsServer != nil{ dnsServer?.stopServer() dnsServer = nil } } //从系统解析host的地址 func dnsResolveWithHost(host : String)->NSArray{ let cfs = host as CFString let hostRef = CFHostCreateWithName(kCFAllocatorDefault, cfs) let result = CFHostStartInfoResolution(hostRef.takeUnretainedValue(),CFHostInfoType.addresses, nil) var darwinresult = DarwinBoolean(false) if result == true { let addresses = CFHostGetAddressing(hostRef.takeUnretainedValue() ,&darwinresult) let resultArray = NSMutableArray() for i in 0..<CFArrayGetCount(addresses?.takeUnretainedValue()){ let saData = CFArrayGetValueAtIndex(addresses?.takeUnretainedValue(), i) let manData : CFData = Unmanaged<CFData>.fromOpaque(saData!).takeUnretainedValue() let remoteAddr = CFDataGetBytePtr(manData) remoteAddr?.withMemoryRebound(to: sockaddr_in.self, capacity: 1){addr in let string = String(cString: inet_ntoa(addr.pointee.sin_addr)) resultArray.add(string) } } return resultArray as NSArray }else { return NSArray() } } func setupChnroute(settings : NEIPv4Settings){ var data :String? = nil do{ data = try NSString(contentsOfFile: Bundle.main.path(forResource: "chnroutes", ofType: "txt")!, encoding: String.Encoding.utf8.rawValue) as String }catch{ return } var routes = [NEIPv4Route]() data?.enumerateLines(invoking: { (line, stop) in let comps = line.components(separatedBy: " ") let route = NEIPv4Route(destinationAddress: comps[0], subnetMask: comps[1]) if routes.count <= 6000{ routes.append(route) } }) settings.excludedRoutes = routes settings.includedRoutes = routes } //best route func setupBestroutetb(settings : NEIPv4Settings){ var data :String? = nil do{ data = try NSString(contentsOfFile: Bundle.main.path(forResource: "bestroutetb", ofType: "txt")!, encoding: String.Encoding.utf8.rawValue) as String }catch{ return } var excludeRoutes = [NEIPv4Route]() var includeRoutes = [NEIPv4Route]() data?.enumerateLines(invoking: { (line, stop) in let comps = line.components(separatedBy: " ") let route = NEIPv4Route(destinationAddress: comps[0], subnetMask: comps[1]) //属于vpn网关 需要特殊处理,需要走隧道 if comps[2] == "vpn_gateway" { includeRoutes.append(route) }else{ excludeRoutes.append(route) } }) settings.excludedRoutes = excludeRoutes settings.includedRoutes = includeRoutes } override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) { //Add code here to start the process of stopping the tunnel. dispatchQueue?.async { self.releaseDNSServer() self.releaseUDPSession() completionHandler() } } override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)?) { guard let messageString = String(data: messageData, encoding: String.Encoding.utf8) else{ completionHandler?(nil) return } DDLogDebug(messageString) let responseData = "Hello app".data(using: String.Encoding.utf8) completionHandler?(responseData) } }
import Combine import Foundation import EvmKit import UniswapKit import RxSwift import RxRelay import MarketKit import HsExtensions class UniswapV3TradeService: ISwapSettingProvider { private static let timerFramePerSecond: Int = 30 private var disposeBag = DisposeBag() private var refreshTimerTask: AnyTask? private var refreshTimerCancellable: Cancellable? private var refreshTimerDisposeBag = DisposeBag() private var cancellables = Set<AnyCancellable>() private var tasks = Set<AnyTask>() private static let normalPriceImpact: Decimal = 1 private static let warningPriceImpact: Decimal = 5 private static let forbiddenPriceImpact: Decimal = 20 private let uniswapProvider: UniswapV3Provider let syncInterval: TimeInterval private var bestTrade: TradeDataV3? private(set) var tokenIn: MarketKit.Token? { didSet { if tokenIn != oldValue { tokenInRelay.accept(tokenIn) } } } private(set) var tokenOut: MarketKit.Token? { didSet { if tokenOut != oldValue { tokenOutRelay.accept(tokenOut) } } } private(set) var amountIn: Decimal = 0 { didSet { if amountIn != oldValue { amountInRelay.accept(amountIn) } } } private(set) var amountOut: Decimal = 0 { didSet { if amountOut != oldValue { amountOutRelay.accept(amountOut) } } } private(set) var tradeType: TradeType = .exactIn { didSet { if tradeType != oldValue { tradeTypeRelay.accept(tradeType) } } } private var tradeTypeRelay = PublishRelay<TradeType>() private var tokenInRelay = PublishRelay<MarketKit.Token?>() private var tokenOutRelay = PublishRelay<MarketKit.Token?>() private var amountInRelay = PublishRelay<Decimal>() private var amountOutRelay = PublishRelay<Decimal>() private let stateRelay = PublishRelay<State>() private(set) var state: State = .notReady(errors: []) { didSet { stateRelay.accept(state) } } private let countdownTimerRelay = PublishRelay<Float>() private let settingsRelay = PublishRelay<UniswapSettings>() var settings = UniswapSettings() { didSet { settingsRelay.accept(settings) _ = syncTradeData() } } init(uniswapProvider: UniswapV3Provider, state: SwapModule.DataSourceState, evmKit: EvmKit.Kit) { self.uniswapProvider = uniswapProvider syncInterval = evmKit.chain.syncInterval tokenIn = state.tokenFrom tokenOut = state.tokenTo if state.exactFrom { amountIn = state.amountFrom ?? 0 } else { amountOut = state.amountTo ?? 0 } evmKit.lastBlockHeightPublisher .sink { [weak self] blockNumber in self?.syncTradeData() } .store(in: &cancellables) syncTradeData() } private func syncTimer() { refreshTimerTask?.cancel() let tickerCount = Int(syncInterval) * Self.timerFramePerSecond refreshTimerTask = Task { [weak self] in for i in 0...tickerCount { try await Task.sleep(nanoseconds: 1_000_000_000 / UInt64(Self.timerFramePerSecond)) self?.countdownTimerRelay.accept(Float(i) / Float(tickerCount)) } self?.syncTradeData() }.erased() } @discardableResult private func syncTradeData() -> Bool { guard let tokenIn = tokenIn, let tokenOut = tokenOut else { state = .notReady(errors: []) return false } tasks = Set() syncTimer() state = .loading let amount = tradeType == .exactIn ? amountIn : amountOut guard amount > 0 else { state = .notReady(errors: []) return false } Task { [weak self, uniswapProvider, tradeType, settings] in do { let bestTrade = try await uniswapProvider.bestTrade(tokenIn: tokenIn, tokenOut: tokenOut, amount: amount, tradeType: tradeType, tradeOptions: settings.tradeOptions) self?.handle(tradeData: bestTrade) } catch { var convertedError = error if case UniswapKit.KitV3.TradeError.tradeNotFound = error { let wethAddressString = uniswapProvider.wethAddress.hex if case .native = tokenIn.type, case .eip20(let address) = tokenOut.type, address == wethAddressString { convertedError = UniswapModule.TradeError.wrapUnwrapNotAllowed } if case .native = tokenOut.type, case .eip20(let address) = tokenIn.type, address == wethAddressString { convertedError = UniswapModule.TradeError.wrapUnwrapNotAllowed } } self?.state = .notReady(errors: [convertedError]) } }.store(in: &tasks) return true } private func handle(tradeData: TradeDataV3) { bestTrade = tradeData switch tradeData.type { case .exactIn: amountOut = tradeData.amountOut ?? 0 case .exactOut: amountIn = tradeData.amountIn ?? 0 } let trade = Trade(tradeData: tradeData) state = .ready(trade: trade) } } protocol IUniswapTradeService { var stateObservable: Observable<UniswapTradeService.State> { get } } extension UniswapV3TradeService { var stateObservable: Observable<State> { stateRelay.asObservable() } var countdownTimerObservable: Observable<Float> { countdownTimerRelay.asObservable() } var tradeTypeObservable: Observable<TradeType> { tradeTypeRelay.asObservable() } var tokenInObservable: Observable<MarketKit.Token?> { tokenInRelay.asObservable() } var tokenOutObservable: Observable<MarketKit.Token?> { tokenOutRelay.asObservable() } var amountInObservable: Observable<Decimal> { amountInRelay.asObservable() } var amountOutObservable: Observable<Decimal> { amountOutRelay.asObservable() } var settingsObservable: Observable<UniswapSettings> { settingsRelay.asObservable() } func transactionData(tradeData: TradeDataV3) throws -> TransactionData { try uniswapProvider.transactionData(tradeData: tradeData, tradeOptions: settings.tradeOptions) } func set(tokenIn: MarketKit.Token?) { guard self.tokenIn != tokenIn else { return } self.tokenIn = tokenIn amountIn = 0 if tradeType == .exactIn { amountOut = 0 } if tokenOut == tokenIn { tokenOut = nil amountOut = 0 } bestTrade = nil syncTradeData() } func set(tokenOut: MarketKit.Token?) { guard self.tokenOut != tokenOut else { return } self.tokenOut = tokenOut amountOut = 0 if tradeType == .exactOut { amountIn = 0 } if tokenIn == tokenOut { tokenIn = nil amountIn = 0 } bestTrade = nil syncTradeData() } func set(amountIn: Decimal) { guard self.amountIn != amountIn else { return } tradeType = .exactIn self.amountIn = amountIn if !syncTradeData() { amountOut = 0 } } func set(amountOut: Decimal) { guard self.amountOut != amountOut else { return } tradeType = .exactOut self.amountOut = amountOut if !syncTradeData() { amountIn = 0 } } func switchCoins() { let swapToken = tokenOut tokenOut = tokenIn set(tokenIn: swapToken) } } extension UniswapV3TradeService { enum State { case loading case ready(trade: Trade) case notReady(errors: [Error]) } struct Trade { let tradeData: TradeDataV3 let impactLevel: UniswapTradeService.PriceImpactLevel? init(tradeData: TradeDataV3) { self.tradeData = tradeData impactLevel = tradeData.priceImpact.map { priceImpact in if priceImpact < UniswapV3TradeService.normalPriceImpact { return .negligible } if priceImpact < UniswapV3TradeService.warningPriceImpact { return .normal } if priceImpact < UniswapV3TradeService.forbiddenPriceImpact { return .warning } return .forbidden } } } }
// // InReadPageViewController.swift // TeadsSampleApp // // Created by Paul NICOLAS on 29/05/2023. // Copyright © 2023 Teads. All rights reserved. // import Foundation import TeadsSDK import UIKit class InReadPageViewController: UIPageViewController { var pid: String = PID.directLandscape var orderedViewControllers: [UIViewController] = [] var currentViewControlelr: UIViewController? // keep a strong reference to placement instance var placement: TeadsInReadAdPlacement? override func viewDidLoad() { super.viewDidLoad() dataSource = self loadPlacement() for index in 0 ..< 20 { if let viewController = storyboard?.instantiateViewController(withIdentifier: "page-view-controller") as? InReadDirectPageViewController { viewController.placement = placement viewController.articleLabelText = "ARTICLE \(index + 1) of 20" orderedViewControllers.append(viewController) } } currentViewControlelr = orderedViewControllers.first setViewControllers([currentViewControlelr!], direction: .forward, animated: true) } func loadPlacement() { let placementSettings = TeadsAdPlacementSettings { settings in settings.enableDebug() } placement = Teads.createInReadPlacement(pid: Int(pid) ?? 0, settings: placementSettings, delegate: self) } } extension InReadPageViewController: UIPageViewControllerDataSource { func pageViewController(_: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { if let currentIndex = orderedViewControllers.firstIndex(of: viewController), currentIndex > 0 { currentViewControlelr = orderedViewControllers[currentIndex - 1] return currentViewControlelr } return nil } func pageViewController(_: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { if let currentIndex = orderedViewControllers.firstIndex(of: viewController), currentIndex < orderedViewControllers.count - 1 { currentViewControlelr = orderedViewControllers[currentIndex + 1] return currentViewControlelr } return nil } } extension InReadPageViewController: TeadsInReadAdPlacementDelegate { func didReceiveAd(ad: TeadsInReadAd, adRatio: TeadsAdRatio) { guard let currentViewController = currentViewControlelr as? InReadDirectPageViewController else { return } ad.delegate = currentViewController currentViewController.resizeTeadsAd(adRatio: adRatio) currentViewController.teadsAdView.bind(ad) } func didUpdateRatio(ad _: TeadsInReadAd, adRatio: TeadsAdRatio) { guard let currentViewController = currentViewControlelr as? InReadDirectPageViewController else { return } currentViewController.resizeTeadsAd(adRatio: adRatio) } func didFailToReceiveAd(reason _: AdFailReason) { print(#function) } func adOpportunityTrackerView(trackerView _: TeadsAdOpportunityTrackerView) { print(#function) } }
import UIKit import CoreLocation class LocationViewController : UIViewController,CLLocationManagerDelegate, UITableViewDelegate, UITableViewDataSource { var lat : String = "" var lng : String = "" var mainRow : Array<nealStation> = [] @IBOutlet var underView: UIView! @IBOutlet var spinner: UIActivityIndicatorView! @IBOutlet var tableView: UITableView! @IBOutlet var refresh: UIButton! @IBAction func refreshBtn(sender: AnyObject) { self.lat = "" self.lng = "" self.locationManager.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBest self.locationManager.requestWhenInUseAuthorization() self.locationManager.startUpdatingLocation() //self.tableView.reloadData() } @IBAction func closeBtn(sender: AnyObject) { self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)//페이지 닫기 } let locationManager = CLLocationManager() override func viewDidLoad() { underView.bounds.size.height = settingFontSize(9) refresh.setFontSize(settingFontSize(0)) refresh.hidden = true for parent in self.navigationController!.navigationBar.subviews{ for childView in parent.subviews{ if(childView is UIImageView){ childView.removeFromSuperview() } } } //네비게이션바 색상변경 let navBarColor = navigationController!.navigationBar // navBarColor.translucent = false // navBarColor.barStyle = .Black navBarColor.barTintColor = UIColor(red: 230/255.0, green: 70/255.0, blue: 70/255.0, alpha: 0.0) navBarColor.tintColor = UIColor.whiteColor() navBarColor.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] self.lat = "" self.lng = "" self.locationManager.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBest self.locationManager.requestWhenInUseAuthorization() self.locationManager.startUpdatingLocation() self.spinner.startAnimating() } override func viewWillAppear(animated: Bool) { if(self.mainRow.count != 0){ self.tableView.reloadData() } } override func viewDidAppear(animated: Bool) { if(self.lng != "" && self.lat != ""){ self.mainRow = returnLocationRow() if(self.mainRow.count != 0){ self.tableView.reloadData() //self.refresh.hidden = false } }else{ let alert = UIAlertController(title: "오류", message: "현재 위치 정보를 가져오지 못하였습니다.", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "확인", style: .Cancel){(_) in self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)//페이지 닫기 } alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) } self.spinner.stopAnimating() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mainRow.count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return settingFontSize(9) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell; cell.textLabel?.text = "#\(indexPath.row+1) " + self.mainRow[indexPath.row].statnNm cell.detailTextLabel?.text = self.mainRow[indexPath.row].subwayNm cell.textLabel?.setFontSize(settingFontSize(0)) cell.detailTextLabel?.setFontSize(settingFontSize(0)) cell.detailTextLabel?.textColor = returnLineColor(SubwayId: self.mainRow[indexPath.row].subwayId) return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "moveToFinish") { let index = self.tableView.indexPathForCell(sender as! UITableViewCell) (segue.destinationViewController as? FinishSTViewController)?.startStation = self.mainRow[index!.row].statnNm } } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations.last //let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude) //let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1)) self.lat = String(location!.coordinate.latitude) self.lng = String(location!.coordinate.longitude) //print("r") self.locationManager.stopUpdatingLocation() } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { let alert = UIAlertController(title: "오류", message: "위치정보를 가져오지 못하였습니다.", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "확인", style: .Cancel){(_) in self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)//페이지 닫기 } alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) } func returnLocationRow() -> Array<nealStation>{ self.mainRow.removeAll() var nealTemp : Array<nealStation> = [] let wtm = getWTM()//wgs84 -> WTM convert let baseUrl = "http://swopenapi.seoul.go.kr/api/subway/\(KEY)/json/nearBy/0/50/\(wtm.0)/\(wtm.1)" let escapedText = baseUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) let apiURI = NSURL(string: escapedText!) let apidata : NSData? = NSData(contentsOfURL: apiURI!) do{ let apiDictionary = try NSJSONSerialization.JSONObjectWithData(apidata!, options: []) as! NSDictionary if(apiDictionary["stationList"] as? NSArray != nil){ let sub = apiDictionary["stationList"] as! NSArray //let sub2 = sub["row"] as! NSArray for row in sub{ nealTemp.append(nealStation( statnNm: row["statnNm"] as! String, subwayId: row["subwayId"] as! String, subwayNm: row["subwayNm"] as! String, ord: Int(row["ord"] as! String)! )) } nealTemp = nealTemp.sort({$0.ord < $1.ord}) }else{ let alert = UIAlertController(title: "오류", message: "목록을 가져오는데 실패하였습니다.(1)", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "확인", style: .Cancel, handler: nil) alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) } }catch{ let alert = UIAlertController(title: "오류", message: "목록을 가져오는데 실패하였습니다.(2)", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "확인", style: .Cancel, handler: nil) alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) } return nealTemp } func getWTM() -> (String, String){ var x : Double = 0 var y : Double = 0 let baseUrl = "http://apis.daum.net/maps/transcoord?apikey=874c220047db1145942dd82def9e2f8f&x=\(self.lng)&y=\(self.lat)&toCoord=WTM&fromCoord=WGS84&output=json" let escapedText = baseUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) let apiURI = NSURL(string: escapedText!) let apidata : NSData? = NSData(contentsOfURL: apiURI!) do{ let apiDictionary = try NSJSONSerialization.JSONObjectWithData(apidata!, options: []) as? NSDictionary if(apiDictionary != nil){ let sub = apiDictionary! x = sub["x"] as! Double y = sub["y"] as! Double }else{ let alert = UIAlertController(title: "오류", message: "좌표정보를 가져오는데 실패하였습니다.(1)", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "확인", style: .Cancel, handler: nil) alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) } }catch{ let alert = UIAlertController(title: "오류", message: "좌표정보를 가져오는데 실패하였습니다.(2)", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "확인", style: .Cancel, handler: nil) alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) } return (String(x), String(y)) } }
// // ZHelpLineView.swift // Seriously // // Created by Jonathan Sand on 4/7/19. // Copyright © 2019 Jonathan Sand. All rights reserved. // #if os(OSX) import AppKit #elseif os(iOS) import UIKit #endif class ZHelpLineView: ZView { override func draw(_ iDirtyRect: CGRect) { ZBezierPath.fillWithColor(kGridColor, in: iDirtyRect) } }
// // ViewController.swift // Prototyper // // Created by Stefan Kofler on 06/09/2016. // Copyright (c) 2016 Stefan Kofler. All rights reserved. // import UIKit import Prototyper class ViewController: PrototypeViewController { override func viewDidLoad() { super.viewDidLoad() self.loadPrototypeContainer("container") PrototypeController.sharedInstance.shouldShowFeedbackButton = true } }
// // main.swift // GolbexSwift // // Created by Nikolay Dolgopolov on 06/11/2018. // import Foundation protocol sdk { func productsList() -> [Product] func walletsList() -> [Wallet] func openOrders() -> [Order] func addOrder() func cancelOrder(id:String) func candles() -> [Candle] func lastCandles() -> [Candle] func productStat(product:String) -> ProductStat } public struct GolbexSDK{ var token = "" var api:Api public init(token:String){ self.token = token api = Api(token:token) } public func productsList() -> [Product] { let list = api.getProducts() return list } public func walletsList() -> (wallets:[Wallet], err:GolbexError?){ let result = api.getWallets() return result } // // func openOrders() -> [Order] { // // } // // func addOrder(order: Order) { // // } // // func cancelOrder(id: String) { // // } // // func candles() -> [Candle] { // // } // public func productStat(product: String) -> ProductStat { let stat = api.getProductStat(product: product) return stat } // public func addOrer(type:String, side:String, product:String, price:Double, size:Double) -> (order:Order, err:GolbexError?){ let result = api.addOrder(type:type, side:side, product:product, price:price, size:size) return result } }
// // SplashViewController.swift // Upcloud // // Created by Joseph on 3/1/19. // Copyright © 2019 Joseph. All rights reserved. // import UIKit import Gifu class SplashViewController: UIViewController { @IBOutlet weak var gif: GIFImageView! override func viewDidLoad() { super.viewDidLoad() self.gif?.animate(withGIFNamed: "splach", loopCount: 3) delayWithSeconds(3) { DispatchQueue.main.async { self.performSegue(withIdentifier: "home", sender: nil) } } } func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) { DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { completion() } } }
// // ViewController.swift // TestAlamofire // // Created by CN320 on 4/19/17. // Copyright © 2017 CN320. All rights reserved. // import UIKit class ViewController: UIViewController , UITableViewDelegate, UITableViewDataSource { var newsDataArray : NSMutableArray? var didUpdateConstraints : Bool! lazy var newsTableView : UITableView = { var newsTableView : UITableView = UITableView.init(frame: CGRect.zero, style: .plain) newsTableView.delegate = self newsTableView.dataSource = self newsTableView.backgroundColor = .clear newsTableView.bounces = false newsTableView.estimatedRowHeight = 44//UITableViewAutomaticDimension newsTableView.rowHeight = UITableViewAutomaticDimension newsTableView.translatesAutoresizingMaskIntoConstraints = false return newsTableView }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.view.translatesAutoresizingMaskIntoConstraints = false self.edgesForExtendedLayout = UIRectEdge.init(rawValue: 0) self.view.addSubview(self.newsTableView) self.didUpdateConstraints = false } class func letsTestTheFunc(str : String)->Bool { return false } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.fetchAndPopulateData() } override func updateViewConstraints() { super.updateViewConstraints() if !self.didUpdateConstraints { self.view.addConstraint(NSLayoutConstraint(item:newsTableView, attribute:NSLayoutAttribute.top, relatedBy:NSLayoutRelation.equal, toItem:self.view, attribute:NSLayoutAttribute.top, multiplier:1, constant:10)) self.view.addConstraint(NSLayoutConstraint(item:newsTableView, attribute:NSLayoutAttribute.bottom, relatedBy:NSLayoutRelation.equal, toItem:self.view, attribute:NSLayoutAttribute.bottom, multiplier:1, constant:-10)) self.view.addConstraint(NSLayoutConstraint(item:newsTableView, attribute:NSLayoutAttribute.leading, relatedBy:NSLayoutRelation.equal, toItem:self.view, attribute:NSLayoutAttribute.leading, multiplier:1, constant:20)) self.view.addConstraint(NSLayoutConstraint(item:newsTableView, attribute:NSLayoutAttribute.trailing, relatedBy:NSLayoutRelation.equal, toItem:self.view, attribute:NSLayoutAttribute.trailing, multiplier:1, constant:-20)) self.didUpdateConstraints = true } super.updateViewConstraints() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /*override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() let viewRect = self.view.frame let tableRect = viewRect.insetBy(dx:10,dy:100) if !self.newsTableView.frame.equalTo(tableRect) { self.newsTableView.frame = tableRect } }*/ func fetchAndPopulateData() -> Void { var dataArray : Array<NewsData>? = nil ConnectionManager.fetchNews { (result : Any?, error :Error?) in defer { DispatchQueue.main.async { self.reloadData(dataTableArray : dataArray) } } guard result != nil else { return } guard error == nil else { return } dataArray = NewsData.prepareNewsDataArray(rawDataArrray: result as? Array<Any>) as? Array<NewsData> } } func reloadData(dataTableArray : Array<NewsData>?)-> Void{ guard dataTableArray != nil else { return } guard dataTableArray?.count != 0 else{ return } if newsDataArray == nil || newsDataArray?.count == 0 { newsDataArray = NSMutableArray.init(array: dataTableArray!) } self.newsTableView.reloadData() } //MARK:- TABLEVIEW_DATASOURCE_METHODS func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return newsDataArray?.count ?? 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let tableCellString = "NewsTableViewCell" var tableViewCell : NewsTableViewCell? = tableView.dequeueReusableCell(withIdentifier: tableCellString) as? NewsTableViewCell if tableViewCell == nil { tableViewCell = NewsTableViewCell.init(style:.default, reuseIdentifier:tableCellString) } tableViewCell?.newsData = newsDataArray?.object(at: indexPath.row) as? NewsData tableViewCell?.updateUI() return tableViewCell! } }
// // SentencesView_Row.swift // ReaderTranslatorPlayer // // Created by Viktor Kushnerov on 16/12/19. // Copyright © 2019 Viktor Kushnerov. All rights reserved. // import SwiftUI import Combine struct SentencesView_Row: View { let sentence: LongmanSentence @Binding var showGTranlator: LongmanSentence? @Binding var showLongmanView: Bool @State var cancellableSpeakers: AnyCancellable? @ObservedObject var store = Store.shared var body: some View { HStack { Button(action: { cancellableSpeakers = Publishers .CombineLatest3( LongmanStore.shared.fetchInfo(text: sentence.text), CambridgeStore.shared.fetchInfo(text: sentence.text), CollinsStore.shared.fetchInfo(text: sentence.text)) .sink { hasLongmanSound, hasCambridgeSound, hasCollinsSound in if hasCambridgeSound { AudioStore.shared.play() } else if hasLongmanSound { AudioStore.shared.play() } else if hasCollinsSound { AudioStore.shared.play() } } }, label: { soundIco }) Button( action: { showGTranlator = sentence }, label: { Text(sentence.text).font(.headline) }) Spacer() Button(action: { showLongmanView = true }, label: { longmanIco }) }.padding(.leading, 10) } private var soundIco: some View { Image(systemName: "play.circle") .resizable() .aspectRatio(contentMode: .fit) .frame(height: 25) .padding(.trailing, 10) } private var longmanIco: some View { Image(systemName: "book.circle") .resizable() .aspectRatio(contentMode: .fit) .frame(height: 25) .padding(.trailing, 10) } } struct SentencesView_Row_Previews: PreviewProvider { @ObservedObject var store = Store.shared static var previews: some View { SentencesView_Row( sentence: LongmanSentence(text: "test", url: URL.empty), showGTranlator: .constant(nil), showLongmanView: .constant(false)) } }
import Foundation struct Stack<T> { var items = [T]() mutating func push(item: T) { items.append(item) } mutating func pop() -> T { return items.removeLast() } } // 为了能够在实例方法中修改属性值,可以在方法定义前添加关键字 mutating struct Point { var x = 0, y = 0 mutating func moveXBy(x:Int,yBy y:Int) { self.x += x self.y += y } } var p = Point(x: 5, y: 5) p.moveXBy(3, yBy: 3) //另外,在值类型的实例方法中,也可以直接修改self属性值。 enum TriStateSwitch { case Off, Low, High mutating func next() { switch self { case Off: self = Low case Low: self = High case High: self = Off } } } var ovenLight = TriStateSwitch.Low ovenLight.next() ovenLight.next() class Animal { func sayHi() { print("Hi bingoogol") } func sayClassName() { print("Animal") } } class Cat : Animal { var _name:String init(name:String) { self._name = name } override func sayClassName() { print("Cat") } func sayName() { print(self._name) } } func demo9() { let animal = Animal() animal.sayHi() animal.sayClassName() let cat = Cat(name: "加菲猫") cat.sayHi() cat.sayClassName() cat.sayName() } //(num:Int) -> Bool 闭包Closure参数类型 func hasClosureMath(arr:[Int],value:Int,cb:(num:Int,value:Int) -> Bool) ->Bool{ for item in arr { if cb(num:item,value:value) { return true } } return false } //闭包 func demo10() { let arr = [20,9,100,34,89,39] // 找是否arr中有比110大的数字 let v1 = hasClosureMath(arr,value: 110,cb: { (num:Int,value:Int) -> Bool in return num >= value //这里$0表示num $1表示value //return $0 >= $1 }) print("v1 is \(v1)") } struct QFTest { var x = 0; var y = 0; // 真正的构造函数 // 定义一个空的够着函数,构造函数是以init开头的,自动调用 init() { print("init invoked") } //定义带有两个参数的构造函数 init(x:Int,y:Int) { self.x = x self.y = y print("init(x:Int,y:Int) invoked") } // _ 这个可以让调用哪个的时候不用谢 x: y: init(_ x:Int,_ y:Int) { self.x = x self.y = y print("init(x:Int,y:Int) invoked") } func getCenter() -> Int { return (x + y)/2 } // 载调用的时候 xxx.addOffset(100,deltaY:100),不需要写deltaX mutating func addOffset(deltaX:Int,deltaY:Int) { // 结构体是一个拷贝的对象,默认是不能修改结构体内部的变量,加上mutating可以让函数修改结构体里面变量的值 self.x += deltaX self.y += deltaY } } func demo11() { let s1 = QFTest(x:100,y:200) print("x:\(s1.x) y:\(s1.y)") var s2 = QFTest() s2.x = 400 s2.y = 300 s2.addOffset(100,deltaY:100) print("x:\(s1.x) y:\(s1.y) center:\(s2.getCenter())") } // NSMutableArray练习 func demo12() { var arr = NSMutableArray(capacity: 4) arr.addObject(1) arr.addObject(2) arr.addObject(3) arr.addObject(4) arr.removeObjectAtIndex(1) arr.insertObject(5, atIndex: 2) arr.exchangeObjectAtIndex(0,withObjectAtIndex:2) } // 数组排序 func demo13() { let arrays:NSMutableArray=NSMutableArray() //增加数据 arrays.addObject("1") arrays.addObject("2") arrays.addObject("3") // arc4random_uniform(2) /* arrays.sortUsingComparator({ (s1:AnyObject!,s2:AnyObject!) -> NSComparisonResult in var str1=s1 as String var str2=s2 as String if str1>str2{ return NSComparisonResult.OrderedAscending }else{ return NSComparisonResult.OrderedDescending } }) */ /* arrays.sortUsingComparator({ s1, s2 in var str1=s1 as String var str2=s2 as String if str1 > str2 { return NSComparisonResult.OrderedAscending }else{ return NSComparisonResult.OrderedDescending } }) */ arrays.sortUsingComparator({ let str1=$0 as! String let str2=$1 as! String print("str1 = \(str1) str2 = \(str2)") if str1 > str2 { return NSComparisonResult.OrderedAscending }else{ return NSComparisonResult.OrderedDescending } }) print(arrays) let array:NSArray = [3,4,2,1] // 3,4,2,1 // 3,4,1,2 // 3,1,2,4 // 1,2,3,4 array.sortedArrayUsingComparator({p1, p2 in let pp1 = p1 as! Int let pp2 = p2 as! Int print("pp1 = \(pp1) pp2 = \(pp2)") if pp1 > pp2 { return NSComparisonResult.OrderedAscending }else{ return NSComparisonResult.OrderedDescending } }) print(array) } //////////////////////////////////////////////////////////////////////////////////////// func getLengthAndWidth(p0:(x:Double,y:Double),p1:(x:Double,y:Double)) -> (length:Double,width:Double) { return (abs(p0.y - p1.y),abs(p0.x - p1.x)) } //元组作为参数的函数 func demo14() { let p0:(x:Double,y:Double) = (0,0) let p1:(x:Double,y:Double) = (6,6) let w = getLengthAndWidth(p0,p1: p1).width let len = getLengthAndWidth(p0,p1: p1).length print("w=\(w) len=\(len)") } /* //////////////////////////////////////////////////////////////////////////////////////// //常量函数和变量函数,默认是常量函数let,参数前面加上var就变成变量函数 //即使这时候是变量函数,但实际上是值传递,只是函数内部可以修改可变参数的值,不可以修改常量参数的值 func params1(var a:Int,b:Int) { let t = a a = b // 错误写法,常量函数不能被修改 //b = t } //////////////////////////////////////////////////////////////////////////////////////// // 输入输出函数 func params2(inout a:Int,inout b:Int) { let t = a a = b b = t } func demo17() { var x = 10 var y = 19 params2(&x,&y) println("\(x),\(y)") } //////////////////////////////////////////////////////////////////////////////////////// //变参函数,必须放在最末尾 func add(a1:Int,array:Int...) -> Int { var sum = a1 for i in array { sum += i } return sum } func demo18() { println(add(1,2,3,4,5)) } //////////////////////////////////////////////////////////////////////////////////////// func type1(a:Int, b:Int) -> Int { return a+b } func type2(a:Int, b:Int) -> Int { return a-b } //函数作为参数 func typeTest(a:Int,b:Int,#op:(Int,Int) -> Int) -> Int { return op(a,b) } func testMax(a:Int,b:Int) -> Int { return a > b ? a : b } func testMin(a:Int,b:Int) -> Int { return a < b ? a : b } // 函数作为返回值 func chooseFunc(#getMax:Bool) -> (Int,Int) -> Int { return getMax ? testMax : testMin } // 函数类型 func demo19() { // (Int,Int) -> Int var callFunc:(Int,Int) -> Int = type2 println(callFunc(5,3)) println(typeTest(8,2,op:type1)) println(typeTest(8,2,type2)) var myFunc:(Int,Int) -> Int = chooseFunc(getMax:false) println(myFunc(50,100)) } //////////////////////////////////////////////////////////////////////////////////////// func fa(a:Int,b:Int) -> Int { return a + b } // 闭包无函数名,闭包有传入、传出,in间隔传入传出的语句块 // 没有函数名的语句块。相当于将函数的形参部分(a:Int,b:Int)和返回类型部分 -> Int写到花括号中,并用in隔开 var fb = {(a:Int,b:Int) -> Int in return a + b } // 第一个参数可以放函数,也可以放闭包 func ffb(f:(Int,Int) -> Int,x:Int,y:Int) { println(f(x,y)) } func demo20() { ffb(fa,5,10) ffb(fb,10,20) ffb({(a:Int,b:Int) -> Int in return a + b },30,40) //简化1:类型推断,去掉传入传出类型,简化闭包 ffb({a,b in return a + b },50,60) //简化2:单语句闭包,如果闭包语句体里只有return语句,return关键字可以不写 ffb({a,b in a + b },70,80) //简化3:参数名简化,位置替换参数,$0表示第一个参数,$1表示第二个参数 ffb({ $0 + $1 },90,100) } //////////////////////////////////////////////////////////////////////////////////////// //闭包练习1,交换两个数的值 func fswap(fs:(Int,Int) -> (Int,Int),x:Int,y:Int) { var t = fs(x,y) println("swapResult is \(t)") } func demo21() { var fcl1 = {(var a:Int,var b:Int) -> (Int,Int) in var t = a a = b b = t return (a,b) } fswap(fcl1,11,12) // 简化后的闭包 fswap({($1,$0)},13,14) } //////////////////////////////////////////////////////////////////////////////////////// //闭包练习2 filter,map,sort的使用 var fx = 1 func fil(y:Int) -> Bool { if fx == y { return true } else { return false } } func fmap(t : Int) -> Int { return t + 101 } func fsort(p1:Int,p2:Int) -> Bool { return p1 > p2 } func demo22() { var a:Array<Int> = [1,9,4,1,8,4,7,3,1,1] var aa = a.filter(fil) println(aa) var bb = a.filter({$0 == fx}) println(bb) var cc = a.map(fmap) println(cc) var dd = a.map({$0 + 11}) println(dd) //a.sort(fsort) println(a) //a.sort({$0 > $1}) println(a) /* protocol Comparable : Equatable { func <=(lhs: Self, rhs: Self) -> Bool func >=(lhs: Self, rhs: Self) -> Bool func >(lhs: Self, rhs: Self) -> Bool } */ // 应该不算闭包吧? a.sort(>) println(a) } //////////////////////////////////////////////////////////////////////////////////////// // TODO 谓词练习 func demo23() { var predicate:NSPredicate = NSPredicate(format: "self CONTAINS 'o'")! var text = "hello" println(predicate.evaluateWithObject(text)) } // 泛型 func swapValue<T>(inout a:T,inout b:T) { let temp = a a = b b = temp } class ClassA<T> { func getValue(value:T) { println(value) } } func demo24() { var a = 12 var b = 13 swapValue(&a, &b) println("a = \(a) b=\(b)") var s1 = "123" var s2 = "321" swapValue(&s1, &s2) println("s1 = \(s1) s2=\(s2)") } demo24() */
// // MeViewController.swift // MiaoShow // // Created by Mazy on 2017/4/7. // Copyright © 2017年 Mazy. All rights reserved. // import UIKit class MeViewController: XMBaseViewController { let tableView: UITableView = { return UITableView(frame: UIScreen.main.bounds, style: .grouped) }() var imageArray = [[String]]() var titleArray = [[String]]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. tableView.dataSource = self tableView.delegate = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") view.addSubview(tableView) titleArray = [["我的喵币","直播间管理","我的短视频"],["我的收益","游戏中心"],["设置"]] imageArray = [["my_coin","live_manager","shortVideo"],["income","game_center"],["setting"]] let headerView = Bundle.main.loadNibNamed("MeHeaderViwe", owner: nil, options: [:])?.last as? MeHeaderViwe headerView?.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: view.bounds.width, height: 200)) tableView.tableHeaderView = headerView tableView.contentInset = UIEdgeInsetsMake(-20, 0, 0, 0) tableView.sectionFooterHeight = 0 } override func viewWillAppear(_ animated: Bool) { navigationController?.setNavigationBarHidden(true, animated: false) } } extension MeViewController: UITableViewDataSource,UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return titleArray.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return titleArray[section].count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") cell?.accessoryType = .disclosureIndicator cell?.imageView?.image = UIImage(named: imageArray[indexPath.section][indexPath.row]) cell?.textLabel?.text = titleArray[indexPath.section][indexPath.row] return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } }
// // MapPinAnnotation.swift // Royals // // Created by Vinícius Couto on 31/08/21. // import MapKit class MapPinAnnotation: NSObject, MKAnnotation { // MARK: - Public attributes let id: UUID = .init() let unselectedColor: UIColor = Assets.Colors.lightGray.color let coordinate: CLLocationCoordinate2D let type: MapPinType let title: String? var isSelected: Bool = false { didSet { if isSelected { imageView.image = imageView.image?.imageWithColor(color: selectedColor) } else { imageView.image = imageView.image?.imageWithColor(color: unselectedColor) } imageView.layoutIfNeeded() } } // MARK: - Lazy variables lazy var imageView: UIImageView = { let asset = (self.type == .skateSpot) ? Assets.Images.skateSpotIcon : Assets.Images.skateStopperIcon return UIImageView(image: UIImage(asset: asset)!.imageWithColor(color: unselectedColor)) }() lazy var selectedColor: UIColor = { (type == .skateSpot) ? Assets.Colors.green.color : Assets.Colors.red.color }() // MARK: - Initialization init(title: String, coordinate: CLLocationCoordinate2D, type: MapPinType) { self.coordinate = coordinate self.title = title self.type = type } }
// // MovieListVIew.swift // Movie // // Created by Levin Ivan on 19/09/2019. // Copyright © 2019 Levin Ivan. All rights reserved. // import UIKit import TinyConstraints import Reusable class MoviesView: UIView { var movies: [MoviesModel.DisplayedMovie] = [] lazy var tableView: UITableView = { let tableView = UITableView() tableView.separatorStyle = .none tableView.estimatedRowHeight = 200 tableView.rowHeight = UITableView.automaticDimension tableView.register(cellType: MovieTableViewCell.self) return tableView }() init() { super.init(frame: .zero) setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { addSubview(tableView) tableView.edges(to: self) } }
// // UVCButton.swift // Learn IOS // 文字與邊緣有漸層效果的按鈕 // https://stackoverflow.com/questions/36836367/how-can-i-do-programmatically-gradient-border-color-uibutton-with-swift // Created by Kevin Le on 2021/8/11. // Copyright © 2021 Kevin Le. All rights reserved. // import UIKit class UVCButton: LeButton { var isOn: Bool = true { didSet { updateBorderLayer() } } var lineWidthRatio = 0.08 { didSet { borderMaskLayer.lineWidth = frame.size.width * lineWidthRatio } } override var isEnabled: Bool { didSet { updateBorderLayer() updateFontColor() } } private var label = UILabel() private var borderLayer: CAGradientLayer! private var borderMaskLayer = CAShapeLayer() private var componentsConstraints = [NSLayoutConstraint]() public override init(frame: CGRect) { super.init(frame: frame) initComponents() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** 更新字體大小與字體顏色 & 邊框的大小 */ override func updateLayout() { super.updateLayout() label.setFontSizeToFill() updateBorderLayer() updateFontColor() borderLayer.frame = bounds borderMaskLayer.lineWidth = frame.size.width * lineWidthRatio borderMaskLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).cgPath } } //MARK: Init extension UVCButton { private func initComponents() { initLabel() initBorderLayer() NSLayoutConstraint.activate(componentsConstraints) } /** 中間的漸層UVC Label */ private func initLabel() { addSubview(label) label.text = "UVC" label.textColor = UIColor(hexString: "#787878") label.textAlignment = .center label.font = .boldSystemFont(ofSize: label.font.pointSize) label.translatesAutoresizingMaskIntoConstraints = false componentsConstraints.append(label.centerXAnchor.constraint(equalTo: centerXAnchor)) componentsConstraints.append(label.centerYAnchor.constraint(equalTo: centerYAnchor)) componentsConstraints.append(label.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.6)) } /** 邊框的漸層 */ private func initBorderLayer() { borderLayer = getGradientLayer(bounds: .zero) layer.addSublayer(borderLayer) borderMaskLayer.strokeColor = UIColor.black.cgColor borderMaskLayer.fillColor = UIColor.clear.cgColor borderLayer.mask = borderMaskLayer } } //MARK: Update extension UVCButton { private func updateBorderLayer() { borderLayer.opacity = isOn && isEnabled ? 1 : 0 } private func updateFontColor() { if isEnabled { let gradient = getGradientLayer(bounds: label.bounds) label.textColor = gradientColor(bounds: label.bounds, gradientLayer: gradient) } else { label.textColor = UIColor(hexString: "#C8C8C8") } } } //MARK: Gradient extension UVCButton { /** 產生漸層的顏色 */ func gradientColor(bounds: CGRect, gradientLayer :CAGradientLayer) -> UIColor? { if bounds.size.width == 0 || bounds.size.height == 0 { return nil } UIGraphicsBeginImageContext(gradientLayer.bounds.size) gradientLayer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return UIColor(patternImage: image!) } /** 取得GradientLayer */ func getGradientLayer(bounds : CGRect) -> CAGradientLayer{ let gradient = CAGradientLayer() gradient.frame = bounds gradient.colors = [UIColor(hexString: "#A066FF8C").cgColor, UIColor(hexString: "#75ABFB8C").cgColor] gradient.startPoint = CGPoint(x: 0.0, y: 0.0) gradient.endPoint = CGPoint(x: 1.0, y: 1.0) return gradient } }
// // DB+Extension.swift // StoryReader // // Created by 020-YinTao on 2017/7/17. // Copyright © 2017年 020-YinTao. All rights reserved. // import Foundation import SQLite extension Connection { public var userVersion: Int32 { get { return Int32(try! scalar("PRAGMA user_version") as! Int64)} set { try! run("PRAGMA user_version = \(newValue)") } } }
// // PFLSwiftAlertView.swift // JiuDingPay // // Created by pfl on 15/9/29. // Copyright © 2015年 QianHai Electronic Pay. All rights reserved. // import UIKit import AudioToolbox let leadingX: CGFloat = 10 let trailingX: CGFloat = 10 let topYY: CGFloat = 40 let itemH: CGFloat = 30 let fontSize: CGFloat = 14 let btnH: CGFloat = 44 let alertViewWidth: CGFloat = 250 let deltaY: CGFloat = 5 let aCenter: CGPoint = CGPoint(x: UIScreen.main.bounds.midX, y: UIScreen.main.bounds.midY) enum AlertViewType { case PlainType,TextFieldType } @objc protocol PFLSwiftAlertViewDelegate { @objc optional func didClick(_ alertView: PFLSwiftAlertView, cancelButton:UIButton) @objc optional func didClick(_ alertView: PFLSwiftAlertView, confirmButton:UIButton) } typealias cancelClosure = ()->() typealias confirmClosure = ()->() typealias textFieldDidEndEditingClosure = (_ sting: String)->() typealias didSelectedIndexPathClosures = (String, NSInteger)->() class PFLSwiftAlertView: UIView, Animationable { var touchDismiss = false var didClickedCancelBtnClosure: cancelClosure? var didClickedConfirmBtnClosure: confirmClosure? var textFieldDidEndEditClosure: textFieldDidEndEditingClosure? var didSelectedIndexPathClosure: didSelectedIndexPathClosures? var passwordLength: Int = 6 var message: String? { didSet { self.messageLabel?.text = message } } var contentFont: CGFloat = 14 fileprivate var delegate: PFLSwiftAlertViewDelegate? fileprivate var cancelButtonTitle: String? var confirmButtonTitle: String? { didSet { if let btn = confirmBtn { btn.setTitle(confirmButtonTitle, for: UIControl.State.normal) } } } fileprivate var tableView: UITableView? var title: String? { didSet { self.titleLabel?.text = title } } /** 自定义alertView - parameter title: 标题 - parameter message: 信息 - parameter delegate: 代理 - parameter cancelButtonTitle: 取消按钮 - parameter otherButtonTitle: 确定按钮 - returns: alertView */ required init(title: String? = "提示", message: String?, delegate: AnyObject?, cancelButtonTitle: String?, otherButtonTitle: String?) { let rect: CGRect = CGRect(x: 0, y: 0, width: alertViewWidth, height: 100) super.init(frame:rect) self.title = title self.delegate = delegate as? PFLSwiftAlertViewDelegate self.message = message self.cancelButtonTitle = cancelButtonTitle self.confirmButtonTitle = otherButtonTitle self.frame = rect self.backgroundColor = UIColor.white self.layer.cornerRadius = 10.0 self.layer.masksToBounds = true NotificationCenter.default.addObserver(self, selector: #selector(PFLSwiftAlertView.keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(PFLSwiftAlertView.keyboardDidHide(_:)), name:UIResponder.keyboardDidHideNotification, object: nil) if let _ = title { self.contentView.addSubview(self.titleLabel!) } if let _ = message { self.contentView.addSubview(self.messageLabel!) } if let _ = cancelButtonTitle { self.contentView.addSubview(self.cancelBtn!) } if let _ = confirmButtonTitle { self.contentView.addSubview(self.confirmBtn!) } self.contentView.addSubview(self.topLine) if let _ = cancelButtonTitle, let _ = confirmButtonTitle { self.contentView.addSubview(self.midLine!) } self.adjustCenter() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } convenience init(withTableView tableView:UITableView) { self.init(title: "交易类别", message: nil, delegate: nil, cancelButtonTitle: nil, otherButtonTitle: "确定") self.tableView = tableView tableView.delegate = self tableView.dataSource = self tableView.tableFooterView = UIView() tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") self.contentView.addSubview(tableView) tableView.separatorStyle = UITableViewCell.SeparatorStyle.singleLine tableView.separatorInset = UIEdgeInsets.zero; self.frame = CGRect(x: 0, y: 0, width: alertViewWidth, height: 400) tableView.frame = CGRect(x: 0, y: 40, width: self.bounds.width, height: self.bounds.height) adjustCenter() } var inputTextFieldPlaceholder = "请输入支付密码" { didSet { self.inputTextField.placeholder = inputTextFieldPlaceholder } } var dataSource: [String]? { didSet { if let tableView = self.tableView { if let dataSource = self.dataSource { print(dataSource.count) self.topY = CGFloat(dataSource.count) * itemH > 400 ? 400:CGFloat(dataSource.count) * itemH + btnH + itemH tableView.frame.size.height = self.bounds.height - 40 adjustCenter() } } } } //MARK: itemsArr 与 hasTextField 不能同时设置 var itemsArr: NSArray? { didSet { guard self.alertViewType != .TextFieldType else {return}; if let arr = itemsArr { if arr.count > 0 { var y: CGFloat = 0; if let lab = self.messageLabel { y = lab.frame.maxY + topY / 4 } else { y = topY } for i in 0..<arr.count { let label = UILabel(frame: CGRect(x: leadingX, y: y + CGFloat(i) * itemH, width: self.bounds.width - 2*leadingX, height: itemH)) label.text = arr[i] as? String label.textAlignment = .left label.textColor = UIColor.brown label.font = UIFont.systemFont(ofSize: contentFont) label.numberOfLines = 0 label.lineBreakMode = NSLineBreakMode.byWordWrapping label.frame.size.height = self.getLabelHeight(label) self.contentView.addSubview(label) self.topY += itemH } self.adjustCenter() } } } } //MARK: itemsArr 与 hasTextField 不能同时设置 fileprivate var hasTextField: String? { didSet { if let _ = hasTextField { self.contentView.addSubview(self.inputTextField) IQKeyboardManager.shared().isEnabled = false } } } var alertViewType: AlertViewType = .PlainType { didSet { switch (alertViewType) { case .PlainType: break case .TextFieldType: guard let itemsArr = itemsArr , itemsArr.count > 0 else { self.contentView.addSubview(self.inputTextField) IQKeyboardManager.shared().isEnabled = false break } } } } var textFieldHeight: CGFloat = itemH { didSet { guard alertViewType == .TextFieldType else{return} inputTextField.frame.size.height = textFieldHeight; } } fileprivate var topY: CGFloat = 0 { didSet { topY = topY>40 ? topY : 40 self.frame.size.height = topY self.contentView.frame.size.height = topY self.center = aCenter print(self.contentView.frame) print(self.frame) } } @objc fileprivate func keyboardDidHide(_ notification: Notification) { UIView.animate(withDuration: 0.2, animations: { () -> Void in self.center = CGPoint(x: UIScreen.main.bounds.width/2, y: UIScreen.main.bounds.height/2) }) } @objc fileprivate func keyboardWillShow(_ notification: Notification) { let kbHeight:CGFloat = ((notification as NSNotification).userInfo![UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue.size.height let kbRect: CGRect = CGRect(x: 0, y: UIScreen.main.bounds.height - kbHeight, width: UIScreen.main.bounds.width, height: kbHeight) let point: CGPoint = CGPoint(x: self.bounds.minX, y: self.bounds.height/2 + UIScreen.main.bounds.height/2) if (kbRect.contains(point)) { let deltaY: CGFloat = point.y - kbRect.origin.y; self.frame.origin.y -= deltaY } } lazy fileprivate var contentView: UIView = { var contentView = UIView(frame: self.bounds) self.addSubview(contentView) return contentView }() lazy fileprivate var titleLabel: UILabel? = { if let title = self.title { var titleLabel: UILabel = UILabel(frame: CGRect(x: 20, y: leadingX, width: self.bounds.width-40, height: itemH)) titleLabel.text = self.title titleLabel.font = UIFont.systemFont(ofSize: fontSize) titleLabel.textAlignment = .center self.contentView.addSubview(titleLabel) self.topY = titleLabel.frame.maxY return titleLabel } else { return nil } }() var isCenter: Bool = true { didSet { titleLabel?.textAlignment = isCenter ? .center : .left } } lazy fileprivate var messageLabel: UILabel? = { if let message = self.message { var messageLabel: UILabel = UILabel(frame: CGRect(x: 0, y: self.titleLabel!.frame.maxY, width: self.bounds.width, height: itemH)) messageLabel.text = message messageLabel.font = UIFont.systemFont(ofSize: fontSize) messageLabel.numberOfLines = 0 messageLabel.lineBreakMode = NSLineBreakMode.byWordWrapping messageLabel.textAlignment = .center messageLabel.frame.size.height = self.getLabelHeight(messageLabel); self.contentView.addSubview(messageLabel) self.topY = messageLabel.frame.maxY return messageLabel } else { return nil } }() lazy fileprivate var cancelBtn: UIButton? = { if let cancelTitle = self.cancelButtonTitle { var btn: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: self.bounds.width * 0.5, height: btnH)) btn.center = CGPoint(x: self.bounds.midX, y: self.topY + btnH * 0.5) btn.addTarget(self, action: #selector(PFLSwiftAlertView.btnPressed(_:)), for: .touchUpInside) btn.tag = 1 btn.titleLabel?.font = UIFont.systemFont(ofSize: fontSize + 1) btn.setTitle(cancelTitle, for: UIControl.State.normal) btn.setTitleColor(UIColor.red, for: UIControl.State.normal) return btn } else { return nil } }() var cancelBtnColor: UIColor = UIColor.red { didSet { guard let cancelBtn = cancelBtn else {return} cancelBtn.setTitleColor(cancelBtnColor, for: UIControl.State.normal) } } var confirmBtnColor: UIColor = UIColor.red { didSet { guard let confirmBtn = confirmBtn else {return} confirmBtn.setTitleColor(confirmBtnColor, for: UIControl.State.normal) } } lazy fileprivate var confirmBtn: UIButton? = { if let confirmTitle = self.confirmButtonTitle { var btn: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: self.bounds.width * 0.5, height: btnH)) btn.center = CGPoint(x: self.bounds.midX, y: self.topY + btnH * 0.5) btn.addTarget(self, action: #selector(PFLSwiftAlertView.btnPressed(_:)), for: .touchUpInside) btn.tag = 2 btn.titleLabel?.font = UIFont.systemFont(ofSize: fontSize + 1) btn.setTitle(confirmTitle, for: UIControl.State.normal) btn.setTitleColor(UIColor.red, for: UIControl.State.normal) return btn } else { return nil } }() lazy fileprivate var dynamicAnimator: UIDynamicAnimator = { var dynamicAnimator: UIDynamicAnimator = UIDynamicAnimator(referenceView: self.bgWindow) return dynamicAnimator }() lazy fileprivate var bgWindow: UIWindow = { var bgWindow: UIWindow = UIWindow(frame: UIScreen.main.bounds) bgWindow.makeKeyAndVisible() return bgWindow }() lazy fileprivate var bgCoverView: UIView = { var bgCoverView: UIView = UIView(frame: UIScreen.main.bounds) bgCoverView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4) if self.touchDismiss { bgCoverView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissAlertView))) } return bgCoverView }() lazy fileprivate var topLine: UIView = { var y: CGFloat = (self.cancelBtn != nil) ? self.cancelBtn!.frame.minY : self.confirmBtn!.frame.minY var topLine: UIView = UIView(frame: CGRect(x: 0, y: y - 0.5, width: self.bounds.width, height: 1)) topLine.backgroundColor = UIColor.lightGray return topLine }() lazy fileprivate var midLine: UIView? = { if let _ = self.cancelButtonTitle, let _ = self.confirmButtonTitle { var midLine: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: btnH)) midLine.center = CGPoint(x: self.bounds.midX, y: self.confirmBtn!.frame.minY) midLine.backgroundColor = UIColor.lightGray return midLine } else { return nil } }() lazy var inputTextField: UITextField = { var y: CGFloat = topYY/4 if let msgL = self.messageLabel { y = msgL.frame.maxY + topYY/4 } else if let titleL = self.titleLabel { y = titleL.frame.maxY + topYY/4 } var inputTextField: UITextField = UITextField(frame: CGRect(x: leadingX, y: y, width: self.bounds.width-2*leadingX, height: itemH)) self.topY = inputTextField.frame.maxY + topYY/4 inputTextField.placeholder = self.inputTextFieldPlaceholder inputTextField.textAlignment = .center inputTextField.font = UIFont.systemFont(ofSize: fontSize-1) inputTextField.delegate = self inputTextField.layer.cornerRadius = 3 inputTextField.layer.borderWidth = 1 inputTextField.layer.borderColor = UIColor.gray.cgColor inputTextField.layer.masksToBounds = true self.adjustCenter() return inputTextField }() fileprivate func getLabelHeight(_ label: UILabel) -> CGFloat { var height: CGFloat = 0 guard let text = label.text else {return height} if (UIDevice.current.systemVersion as NSString).floatValue >= 7.0 { height = text.boundingRect(with: CGSize(width: label.frame.width, height: 1000), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font:label.font], context: nil).size.height } else { height = text.size(withAttributes: [NSAttributedString.Key.font:label.font]).height } return height } @objc fileprivate func btnPressed(_ btn: UIButton) { self.inputTextField.endEditing(true) switch (btn.tag) { case 1: if let cancelB = self.didClickedCancelBtnClosure { cancelB() } if let delegate = self.delegate { if (delegate as AnyObject).responds(to: #selector(PFLSwiftAlertViewDelegate.didClick(_:cancelButton:))) { delegate.didClick!(self, cancelButton: btn) } } case 2: if hasTextField != nil || alertViewType == .TextFieldType { if let txt = inputTextField.text , txt.utf8.count == 0 || txt.characters.count < passwordLength { animationForNoneString() return } } if let confirmB = self.didClickedConfirmBtnClosure { confirmB() } if let delegate = self.delegate { if (delegate as AnyObject).responds(to: #selector(PFLSwiftAlertViewDelegate.didClick(_:confirmButton:))) { delegate.didClick!(self, confirmButton: btn) } } default: break } self.dismissAlertView() } func animationForNoneString() { AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); let animationKeyPath = CAKeyframeAnimation(keyPath: "position.x") let centerX = self.bounds.midX * 0 animationKeyPath.values = [centerX-6,centerX-4,centerX-2,centerX,centerX+2,centerX+4,centerX+6] animationKeyPath.keyTimes = [NSNumber(value: 0.1 as Float),NSNumber(value: 0.2 as Float),NSNumber(value: 0.4 as Float),NSNumber(value: 0.6 as Float),NSNumber(value: 0.7 as Float),NSNumber(value: 0.8 as Float),NSNumber(value: 0.9 as Float),NSNumber(value: 1.0 as Float)] animationKeyPath.duration = 0.3 animationKeyPath.isAdditive = true self.inputTextField.layer .add(animationKeyPath, forKey: "shake") } fileprivate func adjustCenter() { if let _ = self.confirmButtonTitle { self.confirmBtn?.frame.size.width = self.bounds.width self.confirmBtn?.center.y = self.topY + btnH * 0.5 + deltaY self.confirmBtn?.center.x = self.bounds.width * 0.5 } if let _ = self.cancelButtonTitle { self.cancelBtn?.frame.size.width = self.bounds.width self.cancelBtn?.center.y = self.topY + btnH * 0.5 + deltaY self.cancelBtn?.center.x = self.bounds.width * 0.5 } if let _ = self.cancelButtonTitle, let _ = self.confirmButtonTitle { self.cancelBtn?.frame.size.width = self.bounds.width * 0.5 self.confirmBtn?.frame.size.width = self.bounds.width * 0.5 self.cancelBtn?.center.x = self.bounds.width * 0.25 self.confirmBtn?.center.x = self.bounds.width * 0.75 self.midLine!.center.y = self.cancelBtn!.center.y } if (self.cancelButtonTitle != nil) { self.topLine.center.y = self.cancelBtn!.frame.minY } else { self.topLine.center.y = self.confirmBtn!.frame.minY } self.topY += btnH + deltaY } func show() { self.bgWindow.addSubview(self.bgCoverView) self.bgWindow.addSubview(self) self.dynamicAnimator.addBehavior(self.addDropBehavior()) self.performAnimation() self.dynamicAnimator.removeAllBehaviors() NotificationCenter.default.addObserver(self, selector: #selector(dismissAlertView), name: UIApplication.willResignActiveNotification, object: nil) } @objc fileprivate func dismissAlertView() { self.dismissAnimation() self.dynamicAnimator.addBehavior(addBehavior()) let popTime = DispatchTime.now() + Double(Int64( Double(NSEC_PER_SEC) * 0.31)) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: popTime) { self.bgCoverView.removeFromSuperview() for vi in self.subviews { vi.removeFromSuperview() } self.removeFromSuperview() self.bgWindow.isHidden = true UIApplication.shared.windows.first?.makeKey() self.dynamicAnimator.removeAllBehaviors() } } deinit { IQKeyboardManager.shared().isEnabled = true NotificationCenter.default.removeObserver(self) print("deinit=============") } } extension PFLSwiftAlertView: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.endEditing(true) return true } func textFieldDidEndEditing(_ textField: UITextField) { if let isEndBlock = self.textFieldDidEndEditClosure, let txt = textField.text { isEndBlock(txt) } } } extension PFLSwiftAlertView: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let dataSource = self.dataSource { return dataSource.count } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")! cell.textLabel?.text = self.dataSource![indexPath.row] as String cell.textLabel?.textAlignment = .center cell.textLabel?.font = UIFont.systemFont(ofSize: contentFont) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let closure = self.didSelectedIndexPathClosure, let dataSource = dataSource { closure(dataSource[indexPath.row], indexPath.row) } self.dismissAlertView() } }
import Cocoa var str = "Hello, Switch" //1. Создать строку произвольного текста, минимум 200 символов. Используя цикл и оператор свитч посчитать количество гласных, согласных, цифр и символов. let string = "A string is a series of characters, such as \"Swift\", that forms a collection. Strings in Swift are Unicode correct and locale insensitive, and are designed to be efficient. The String type bridges with the Objective-C class NSString and offers interoperability with C functions that works with strings. 123 123 123" var vowels = 0 var consonant = 0 var symbols = 0 var digit = 0 for char in string.lowercased() { switch char { case "a", "e", "i", "o", "u" : vowels += 1 case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z" : consonant += 1 case "0"..."9" : digit += 1 default: symbols += 1 } } print("Vowels = \(vowels)\nConsonants = \(consonant)\nDigits = \(digit)\nSymbols = \(symbols)\n\n") //2. Создайте свитч который принимает возраст человека и выводит описание жизненного этапа var age = 9//Int() switch age { case 1...3: print("Baby") case 4...11: print("Kid") case 12...17: print("Teenager") default: print("Age not found") } //3. У вас есть имя отчество и фамилия студента (русские буквы). Имя начинается с А или О, то обращайтесь к студенту по имени, если же нет, то если у него отчество начинается на В или Д, то обращайтесь к нему по имени и отчеству, если же опять нет, то в случае если фамилия начинается с Е или З, то обращайтесь к нему только по фамилии. В противном случае обращайтесь к нему по полному имени. let firstName = "Galileo" let lastName = "Scaramouch" let patronymic = "Bismillah" var fullName = (firstName, lastName, patronymic) switch fullName { case (let name, _, _) where name.hasPrefix("A"): fallthrough case (let name, _, _) where name.hasPrefix("O"): print("Hi \(firstName)") case (_, _, let father) where father.hasPrefix("V"): fallthrough case (_, _, let father) where father.hasPrefix("D"): print("Hi \(firstName) \(lastName)") case (_, let lname, _) where lname.hasPrefix("E"): fallthrough case (_, let lname, _) where lname.hasPrefix("Z"): print("Hi \(firstName) \(patronymic)") default: print("Hi \(firstName) \(patronymic) \(lastName)") } //4. Представьте что вы играете в морской бои и у вас осталось некоторое количество кораблей на поле 10Х10 (можно буквы и цифры, а можно только цифры). Вы должны создать свитч, который примет тюпл с координатой и выдаст один из вариантов: мимо, ранил, убил. let ship1 = (x:7, y:5) switch ship1 { case (1...5, 5): print("\nHit") case (5, 5...10): print("\nHit") case (5, 5): print("\nKilled") default: print("\nMiss") } let ship2 = (x:3, y:5) switch ship2 { case (1...5, 5): print("\nHit") case (5, 5...10): print("\nHit") case (3, 3): print("\nKilled") default: print("\nMiss") }
func collectOrToggle () { if isOnGem { collectGem() } else if isOnClosedSwitch { toggleSwitch() } } for i in 0 ..< 5 { let row: Int = i % 2 == 0 ? 4 : i == 1 ? 2 : 1 for j in 0 ..< row { moveForward() collectOrToggle() } i == 0 || i == 1 ? turnLeft() : turnRight() }
// // GameButtonPanelView.swift // Asteroids // // Created by Gabriel Robinson on 4/12/19. // Copyright © 2019 CS4530. All rights reserved. // import UIKit class GameButtonPanelView: UIView { // Game control buttons var turnLeftButton = UIButton(type: UIButton.ButtonType.roundedRect) var turnRightButton = UIButton(type: UIButton.ButtonType.roundedRect) var accelerateButton = UIButton(type: UIButton.ButtonType.roundedRect) var fireButton = UIButton(type: UIButton.ButtonType.roundedRect) override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .clear turnLeftButton.setTitle("Left", for: UIControl.State.normal) turnLeftButton.backgroundColor = UIColor.white turnLeftButton.setTitleColor(UIColor.black, for: UIControl.State.normal) turnLeftButton.layer.cornerRadius = 5 turnLeftButton.layer.borderWidth = 1 turnLeftButton.layer.borderColor = UIColor.white.cgColor turnRightButton.setTitle("Right", for: UIControl.State.normal) turnRightButton.backgroundColor = UIColor.white turnRightButton.setTitleColor(UIColor.black, for: UIControl.State.normal) turnRightButton.layer.cornerRadius = 5 turnRightButton.layer.borderWidth = 1 turnRightButton.layer.borderColor = UIColor.white.cgColor accelerateButton.setTitle("Accelerate", for: UIControl.State.normal) accelerateButton.backgroundColor = UIColor.white accelerateButton.setTitleColor(UIColor.black, for: UIControl.State.normal) accelerateButton.layer.cornerRadius = 5 accelerateButton.layer.borderWidth = 1 accelerateButton.layer.borderColor = UIColor.white.cgColor fireButton.setTitle("Fire", for: UIControl.State.normal) fireButton.backgroundColor = UIColor.white fireButton.setTitleColor(UIColor.black, for: UIControl.State.normal) fireButton.layer.cornerRadius = 5 fireButton.layer.borderWidth = 1 fireButton.layer.borderColor = UIColor.white.cgColor // left button | acclerateion button | fire button | right button fireButton.frame = CGRect(x: 0, y: 0, width: self.frame.width * 0.25 - 2.5, height: 0.6 * self.frame.height) accelerateButton.frame = CGRect(x: fireButton.frame.maxX + 2.5, y: 0, width: self.frame.width * 0.25 - 2.5, height: 0.6 * self.frame.height) turnLeftButton.frame = CGRect(x: accelerateButton.frame.maxX + 2.5, y: 0, width: self.frame.width * 0.25 - 2.5, height: 0.6 * self.frame.height) turnRightButton.frame = CGRect(x: turnLeftButton.frame.maxX + 2.5, y: 0, width: self.frame.width * 0.25, height: 0.6 * self.frame.height) self.addSubview(turnLeftButton) self.addSubview(accelerateButton) self.addSubview(fireButton) self.addSubview(turnRightButton) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
struct Flavor { var name : String var rating : Double } struct Cone { let flavor : Flavor let size : Size let topping : String? func eat() { print("Mmm! I love \(flavor.name)") } } enum Size : Double { case small = 3.99 case medium = 4.99 case large = 5.99 case xl = 6.99 } struct Menu { let flavorSelection : [Flavor] let sizesAvailable : [Size] let toppingsSelection : [String] } class IceCreamShop { let menu : Menu var totalSales = 0.0 func listTopFlavors (flavorArray: [Flavor]) { var topFlavorArray = [String]() var message = "Our top flavors are" for flavor in flavorArray { if flavor.rating >= 4.0 { topFlavorArray.append(flavor.name) } } for flavor in topFlavorArray { if flavor == topFlavorArray.last { message += " and \(flavor)." } else { message += " \(flavor)," } } print(message) } func checkAvailability(cone: Cone) -> Bool { for flavor in menu.flavorSelection { if flavor.name == cone.flavor.name { return true } } return false } func orderCone(flavor: Flavor, size: Size, topping: String?) -> Cone? { let newCone = Cone(flavor: flavor, size: size, topping: topping) if checkAvailability(cone: newCone) == true { if let unwrappedTopping = newCone.topping { print("Your \(newCone.flavor.name) ice cream with \(unwrappedTopping) will be $\(newCone.size.rawValue)") } else { print("Your \(newCone.flavor.name) will be $\(newCone.size.rawValue)") } totalSales += newCone.size.rawValue } else if checkAvailability(cone: newCone) == false { print("Sorry we don't have \(newCone.flavor.name) ice cream.") } return newCone } func multipleOrders(cones: [Cone]) -> Double { var total = 0.0 for cone in cones { if checkAvailability(cone: cone) == true { total += cone.size.rawValue } } print("Your total will be \(total)") totalSales += total return total } init(menu : Menu) { self.menu = menu } } // Flavors Seperate let vanillaFlavor = Flavor.init(name: "Vanilla", rating: 1.5) let chocolateFlavor = Flavor.init(name: "Chocolate", rating: 4.5) let neopolitanFlavor = Flavor.init(name: "Neopolitan", rating: 3.5) let cookieDoughFlavor = Flavor(name: "Cookie Dough", rating: 4.8) let oreoCookieFlavor = Flavor(name: "Oreo Cookie", rating: 5) let rainbowSherbert = Flavor(name: "Rainbow Sherbert", rating: 5) // Array of Flavors var johnsFlavorArray = [vanillaFlavor, chocolateFlavor, neopolitanFlavor, cookieDoughFlavor, oreoCookieFlavor, rainbowSherbert] // Array of Toppings let toppingsArray = ["Chocolate Chips", "Sprinkles", "Cookie Dough"] // Cone Instances let newCone = Cone(flavor: vanillaFlavor, size: .small, topping: toppingsArray[0]) let newCone2 = Cone(flavor: chocolateFlavor, size: .large, topping: toppingsArray[1]) let newCone3 = Cone(flavor: neopolitanFlavor, size: .medium, topping: toppingsArray[2]) let newCone4 = Cone(flavor: cookieDoughFlavor, size: .large, topping: toppingsArray[0]) let newCone5 = Cone(flavor: oreoCookieFlavor, size: .medium, topping: toppingsArray[1]) let newCone6 = Cone(flavor: rainbowSherbert, size: .xl, topping: toppingsArray[2]) let johnsAvailableSizes = [Size.small, Size.medium, Size.large, Size.xl] // Orders let flavor1 = Flavor(name: "Chocolate", rating: 3.5) let size1 = Size.large let topping1 = "Chocolate chips" // Menu let johnsMenu = Menu(flavorSelection: johnsFlavorArray, sizesAvailable: johnsAvailableSizes, toppingsSelection: toppingsArray) // IceCreamShop Instance let johnsIceCreamShop = IceCreamShop(menu: johnsMenu) // Calling the listTopFlavors function in the IceCreamShop class johnsIceCreamShop.listTopFlavors(flavorArray: johnsMenu.flavorSelection) // Calling the eat function in the Cone struct newCone.eat() johnsIceCreamShop.orderCone(flavor: flavor1, size: size1, topping: topping1)?.eat() // Calling the orderCone function multiple times to make sure its adding the the total sales in the class johnsIceCreamShop.orderCone(flavor: flavor1, size: size1, topping: topping1) // If someone has a big order I'm Calling the multipleOrders function here //let bigOrder = [newCone, newCone4, newCone5, newCone6, newCone2, newCone3] //johnsIceCreamShop.multipleOrders(cones: bigOrder) // Johns Ice Cream Shop Total Sales print("🍦Johns Ice Cream Shop🍦 has $\(johnsIceCreamShop.totalSales) in total sales.")
// // BestsellersGenreModel.swift // NYTBestsellers // // Created by Jeffrey Almonte on 1/28/19. // Copyright © 2019 Pursuit. All rights reserved. // import Foundation struct Genre: Codable { let results: [BestsellerGenre] } struct BestsellerGenre: Codable { let listName: String private enum CodingKeys: String, CodingKey { case listName = "list_name" } }
// // LoginController.swift // GameOfChat // // Created by SEAN on 2017/9/22. // Copyright © 2017年 SEAN. All rights reserved. // import UIKit import Firebase class LoginController: UIViewController { var messageController: MessageController? let inputsContrainerView : UIView = { let view = UIView() view.backgroundColor = .white view.layer.cornerRadius = 5 view.layer.masksToBounds = true view.translatesAutoresizingMaskIntoConstraints = false return view }() lazy var loginRegisterButton: UIButton = { let button = UIButton(type: .system) button.backgroundColor = UIColor.darkGray button.setTitle("Register", for: UIControlState()) button.translatesAutoresizingMaskIntoConstraints = false button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16) button.setTitleColor(.white, for: UIControlState()) button.addTarget(self, action: #selector(handleLoginRegister), for: .touchUpInside) return button }() @objc func handleLoginRegister() { if loginRegisterSegmentedControl.selectedSegmentIndex == 0 { handleLogin() }else{ handleRegister() } } func handleLogin() { guard let email = emailTextField.text, let password = passwordTextField.text else { print("Form is not valid") return } Auth.auth().signIn(withEmail: email, password: password) { (user, error) in if error != nil { print(error ?? "error") return } //successfully logged in our user print("You're Logged in now") self.messageController?.fetchUserAndSetupNavBarTitle() self.dismiss(animated: true, completion: nil) } } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } let nameTextField: UITextField = { let tf = UITextField() tf.placeholder = "Name" tf.translatesAutoresizingMaskIntoConstraints = false return tf }() let nameSeperatorView: UIView = { let view = UIView() view.backgroundColor = UIColor(r: 220, g: 220, b: 220) view.translatesAutoresizingMaskIntoConstraints = false return view }() let emailTextField: UITextField = { let tf = UITextField() tf.placeholder = "email" tf.translatesAutoresizingMaskIntoConstraints = false return tf }() let emailSeperatorView: UIView = { let view = UIView() view.backgroundColor = UIColor(r: 220, g: 220, b: 220) view.translatesAutoresizingMaskIntoConstraints = false return view }() let passwordTextField: UITextField = { let tf = UITextField() tf.placeholder = "Password" tf.translatesAutoresizingMaskIntoConstraints = false tf.isSecureTextEntry = true return tf }() lazy var profileImageView: UIImageView = { let imageView = UIImageView() imageView.image = UIImage(named: "camera") imageView.contentMode = .scaleAspectFill imageView.translatesAutoresizingMaskIntoConstraints = false imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleSelectProfileImage))) imageView.isUserInteractionEnabled = true return imageView }() lazy var loginRegisterSegmentedControl: UISegmentedControl = { let sc = UISegmentedControl(items: ["Login", "Register"]) sc.translatesAutoresizingMaskIntoConstraints = false sc.tintColor = .white sc.selectedSegmentIndex = 1 sc.addTarget(self, action: #selector(handleLoginRegisterChange), for: .valueChanged) return sc }() @objc func handleLoginRegisterChange() { let title = loginRegisterSegmentedControl.titleForSegment(at: loginRegisterSegmentedControl.selectedSegmentIndex) loginRegisterButton.setTitle(title, for: UIControlState()) profileImageView.isHidden = loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? true : false inputsContainerViewHeight?.constant = loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 100 : 150 nameTextFieldHeight?.isActive = false nameTextFieldHeight = nameTextField.heightAnchor.constraint(equalTo: inputsContrainerView.heightAnchor, multiplier: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 0 : 1/3) nameTextFieldHeight?.isActive = true nameTextField.isHidden = loginRegisterSegmentedControl.selectedSegmentIndex == 0 emailTextFieldHeight?.isActive = false emailTextFieldHeight = emailTextField.heightAnchor.constraint(equalTo: inputsContrainerView.heightAnchor, multiplier: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 1/2 : 1/3) emailTextFieldHeight?.isActive = true passwordTextFieldHeight?.isActive = false passwordTextFieldHeight = passwordTextField.heightAnchor.constraint(equalTo: inputsContrainerView.heightAnchor, multiplier: loginRegisterSegmentedControl.selectedSegmentIndex == 0 ? 1/2 : 1/3) passwordTextFieldHeight?.isActive = true } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.gray view.addSubview(inputsContrainerView) view.addSubview(loginRegisterButton) view.addSubview(profileImageView) view.addSubview(loginRegisterSegmentedControl) setupLoginContainerView() setupLoginRegisterButton() setupProfileImageView() setupLoginRegisterSegmentedControl() } func setupLoginRegisterSegmentedControl() { loginRegisterSegmentedControl.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true loginRegisterSegmentedControl.bottomAnchor.constraint(equalTo: inputsContrainerView.topAnchor, constant: -12).isActive = true loginRegisterSegmentedControl.widthAnchor.constraint(equalTo: inputsContrainerView.widthAnchor, multiplier: 1).isActive = true loginRegisterSegmentedControl.heightAnchor.constraint(equalToConstant: 36).isActive = true } func setupProfileImageView() { profileImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true profileImageView.bottomAnchor.constraint(equalTo: loginRegisterSegmentedControl.topAnchor, constant: -12).isActive = true profileImageView.widthAnchor.constraint(equalToConstant: 150).isActive = true profileImageView.heightAnchor.constraint(equalToConstant: 150).isActive = true } var inputsContainerViewHeight: NSLayoutConstraint? var nameTextFieldHeight: NSLayoutConstraint? var emailTextFieldHeight: NSLayoutConstraint? var passwordTextFieldHeight: NSLayoutConstraint? func setupLoginContainerView() { inputsContrainerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true inputsContrainerView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true inputsContrainerView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -24).isActive = true inputsContainerViewHeight = inputsContrainerView.heightAnchor.constraint(equalToConstant: 150) inputsContainerViewHeight?.isActive = true inputsContrainerView.addSubview(nameTextField) inputsContrainerView.addSubview(nameSeperatorView) inputsContrainerView.addSubview(emailTextField) inputsContrainerView.addSubview(emailSeperatorView) inputsContrainerView.addSubview(passwordTextField) nameTextField.leftAnchor.constraint(equalTo: inputsContrainerView.leftAnchor, constant: 12).isActive = true nameTextField.topAnchor.constraint(equalTo: inputsContrainerView.topAnchor).isActive = true nameTextField.widthAnchor.constraint(equalTo: inputsContrainerView.widthAnchor, constant: -12).isActive = true nameTextFieldHeight = nameTextField.heightAnchor.constraint(equalTo: inputsContrainerView.heightAnchor, multiplier: 1/3) nameTextFieldHeight?.isActive = true nameSeperatorView.leftAnchor.constraint(equalTo: inputsContrainerView.leftAnchor).isActive = true nameSeperatorView.topAnchor.constraint(equalTo: nameTextField.bottomAnchor).isActive = true nameSeperatorView.widthAnchor.constraint(equalTo: inputsContrainerView.widthAnchor).isActive = true nameSeperatorView.heightAnchor.constraint(equalToConstant: 1).isActive = true emailTextField.leftAnchor.constraint(equalTo: inputsContrainerView.leftAnchor, constant: 12).isActive = true emailTextField.topAnchor.constraint(equalTo: nameTextField.bottomAnchor).isActive = true emailTextField.widthAnchor.constraint(equalTo: inputsContrainerView.widthAnchor, constant: -12).isActive = true emailTextFieldHeight = emailTextField.heightAnchor.constraint(equalTo: inputsContrainerView.heightAnchor, multiplier: 1/3) emailTextFieldHeight?.isActive = true emailSeperatorView.leftAnchor.constraint(equalTo: inputsContrainerView.leftAnchor).isActive = true emailSeperatorView.topAnchor.constraint(equalTo: emailTextField.bottomAnchor).isActive = true emailSeperatorView.widthAnchor.constraint(equalTo: inputsContrainerView.widthAnchor).isActive = true emailSeperatorView.heightAnchor.constraint(equalToConstant: 1).isActive = true passwordTextField.leftAnchor.constraint(equalTo: inputsContrainerView.leftAnchor, constant: 12).isActive = true passwordTextField.topAnchor.constraint(equalTo: emailTextField.bottomAnchor).isActive = true passwordTextField.widthAnchor.constraint(equalTo: inputsContrainerView.widthAnchor, constant: -12).isActive = true passwordTextFieldHeight = passwordTextField.heightAnchor.constraint(equalTo: inputsContrainerView.heightAnchor, multiplier: 1/3) passwordTextFieldHeight?.isActive = true } func setupLoginRegisterButton() { loginRegisterButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true loginRegisterButton.widthAnchor.constraint(equalTo: inputsContrainerView.widthAnchor).isActive = true loginRegisterButton.topAnchor.constraint(equalTo: inputsContrainerView.bottomAnchor, constant: 12).isActive = true loginRegisterButton.heightAnchor.constraint(equalToConstant: 50).isActive = true } }
// // Models.swift // TaylorSource // // Created by Daniel Thorpe on 08/03/2016. // // import Foundation import ValueCoding import YapDatabaseExtensions import YapDatabase @testable import TaylorSource struct EventSection: SectionType { typealias ItemType = Event let title: String let items: [Event] } extension EventSection: CustomStringConvertible { var description: String { return "\(title) (\(items.count) items)" } } extension EventSection: Equatable { } func == (lhs: EventSection, rhs: EventSection) -> Bool { return lhs.title == rhs.title && lhs.items == rhs.items } struct Event { enum Color { case Red, Blue, Green } let uuid: String let color: Color let date: NSDate init(uuid: String = NSUUID().UUIDString, color: Color, date: NSDate = NSDate()) { self.uuid = uuid self.color = color self.date = date } static func create(color color: Color = .Red) -> Event { return Event(color: color) } } extension Event.Color: CustomStringConvertible { var description: String { switch self { case .Red: return "Red" case .Blue: return "Blue" case .Green: return "Green" } } } extension Event.Color: Equatable { } func == (lhs: Event.Color, rhs: Event.Color) -> Bool { switch (lhs,rhs) { case (.Red, .Red), (.Blue, .Blue), (.Green, .Green): return true default: return false } } extension Event: Equatable { } func == (lhs: Event, rhs: Event) -> Bool { return (lhs.color == rhs.color) && (lhs.uuid == rhs.uuid) && (lhs.date == rhs.date) } extension Event.Color: ValueCoding { typealias Coder = EventColorCoder enum Kind: Int { case Red = 1, Blue, Green } var kind: Kind { switch self { case .Red: return Kind.Red case .Blue: return Kind.Blue case .Green: return Kind.Green } } } class EventColorCoder: NSObject, NSCoding, CodingType { let value: Event.Color required init(_ v: Event.Color) { value = v } required init?(coder aDecoder: NSCoder) { if let kind = Event.Color.Kind(rawValue: aDecoder.decodeIntegerForKey("kind")) { switch kind { case .Red: value = Event.Color.Red case .Blue: value = Event.Color.Blue case .Green: value = Event.Color.Green } } else { fatalError("Event.Color.Kind not correctly encoded.") } } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeInteger(value.kind.rawValue, forKey: "kind") } } extension Event: Identifiable { var identifier: String { return uuid } } extension Event: Persistable { static var collection: String { return "Events" } } extension Event: ValueCoding { typealias Coder = EventCoder } class EventCoder: NSObject, NSCoding, CodingType { let value: Event required init(_ v: Event) { value = v } required init?(coder aDecoder: NSCoder) { let color = Event.Color.decode(aDecoder.decodeObjectForKey("color")) let uuid = aDecoder.decodeObjectForKey("uuid") as? String let date = aDecoder.decodeObjectForKey("date") as? NSDate value = Event(uuid: uuid!, color: color!, date: date!) } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(value.color.encoded, forKey: "color") aCoder.encodeObject(value.uuid, forKey: "uuid") aCoder.encodeObject(value.date, forKey: "date") } } func createSomeEvents(numberOfDays: Int = 10) -> [Event] { let today = NSDate() let interval: NSTimeInterval = 86_400 return (0..<numberOfDays).map { index in let date = today.dateByAddingTimeInterval(-1.0 * Double(index) * interval) return Event(color: .Red, date: date) } } func events(byColor: Bool = false) -> YapDB.Fetch { let grouping: YapDB.View.Grouping = .ByObject({ (_, collection, key, object) -> String! in if collection == Event.collection { if !byColor { return collection } if let event = Event.decode(object) { return event.color.description } } return .None }) let sorting: YapDB.View.Sorting = .ByObject({ (_, group, collection1, key1, object1, collection2, key2, object2) -> NSComparisonResult in if let event1 = Event.decode(object1), let event2 = Event.decode(object2) { return event1.date.compare(event2.date) } return .OrderedSame }) let view = YapDB.View(name: Event.collection, grouping: grouping, sorting: sorting, collections: [Event.collection]) return .View(view) } func events(byColor: Bool = false, mappingBlock: YapDB.FetchConfiguration.MappingsConfigurationBlock? = .None) -> YapDB.FetchConfiguration { return YapDB.FetchConfiguration(fetch: events(byColor), block: mappingBlock) } func events(byColor: Bool = false, mappingBlock: YapDB.FetchConfiguration.MappingsConfigurationBlock? = .None) -> Configuration<Event> { return Configuration(fetch: events(byColor), itemMapper: Event.decode) } func eventsWithColor(color: Event.Color, byColor: Bool = false) -> YapDB.Fetch { let filtering: YapDB.Filter.Filtering = .ByObject({ (_, group, collection, key, object) -> Bool in if let event = Event.decode(object) { return event.color == color } return false }) let filter = YapDB.Filter(name: "\(color) Events", parent: events(byColor), filtering: filtering, collections: [Event.collection]) return .Filter(filter) } func eventsWithColor(color: Event.Color, byColor: Bool = false, mappingBlock: YapDB.FetchConfiguration.MappingsConfigurationBlock? = .None) -> YapDB.FetchConfiguration { return YapDB.FetchConfiguration(fetch: eventsWithColor(color, byColor: byColor), block: mappingBlock) } func eventsWithColor(color: Event.Color, byColor: Bool = false, mappingBlock: YapDB.FetchConfiguration.MappingsConfigurationBlock? = .None) -> Configuration<Event> { return Configuration(fetch: eventsWithColor(color, byColor: byColor), itemMapper: Event.decode) }
// // MediaType.swift // GeniusPlazaCodeChallegnge // // Created by Kadeem Palacios on 4/11/19. // Copyright © 2019 Kadeem Palacios. All rights reserved. // import Foundation class MediaType { static let appleMusic = "https://rss.itunes.apple.com/api/v1/us/apple-music/coming-soon/all/10/explicit.json" static let itunesMusic = "https://rss.itunes.apple.com/api/v1/us/itunes-music/hot-tracks/all/10/explicit.json" static let iOSApps = "https://rss.itunes.apple.com/api/v1/us/ios-apps/new-apps-we-love/all/10/explicit.json" static let macApps = "https://rss.itunes.apple.com/api/v1/us/macos-apps/top-free-mac-apps/all/10/explicit.json" static let audioBooks = "https://rss.itunes.apple.com/api/v1/us/audiobooks/top-audiobooks/all/10/explicit.json" static let books = "https://rss.itunes.apple.com/api/v1/us/books/top-free/all/10/explicit.json" static let tvShows = "https://rss.itunes.apple.com/api/v1/us/tv-shows/top-tv-episodes/all/10/explicit.json" static func allLinks() -> [String] { let links = [appleMusic, itunesMusic, iOSApps, macApps, audioBooks, books, tvShows] return links } } enum MediaEnum { case appleMusic case itunesMusic case iOSApps case macApps case audioBooks case books case tvShows }
// // VkRequestOperation.swift // SocialApp // // Created by Дима Давыдов on 13.01.2021. // import Foundation import Alamofire class VkRequestOperation: AsyncOperation { var request: RequestProtocol var result: AFDataResponse<Data>? private let version = "5.126" override var isAsynchronous: Bool { return true } init(request: RequestProtocol) { self.request = request super.init() } private func buildUrl(for method: VKMethod, params: Parameters?) -> URLComponents { var urlComponents = URLComponents() urlComponents.scheme = "https" urlComponents.host = "api.vk.com" urlComponents.path = "/method/\(method)" urlComponents.queryItems = [ URLQueryItem(name: "access_token", value: LoginService.shared.accessToken()), URLQueryItem(name: "v", value: version), ] if let params = params { for (k, v) in params { urlComponents.queryItems?.append(URLQueryItem(name: k, value: v as? String)) } } return urlComponents } override func main() { print("Enter main VkRequestOperation") guard let url = buildUrl(for: request.getMethod(), params: request.asParameters()).url else { return } Session.custom .request(url) .debugLog() .responseData { [weak self] (response) in print("done request") self?.result = response self?.state = .finished } } }
// // ViewController.swift // Pruebas // // Created by Julio Banda on 28/04/18. // Copyright © 2018 Julio Banda. All rights reserved. // import UIKit class ViewController: NoNavigationBarViewController, UIScrollViewDelegate { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var image: UIImageView! override func viewDidLoad() { super.viewDidLoad() updateZoomForSize(self.view.bounds.size) } func viewForZooming(in scrollView: UIScrollView) -> UIView? { return image } func updateZoomForSize(_ size: CGSize) { let widthScale = size.width / image.bounds.width let heightScale = size.height / image.bounds.height let scale = min(widthScale, heightScale) scrollView.minimumZoomScale = scale } }
// // AlertTitle.swift // HHTestTask // // Created by Maxim Tolstikov on 16/01/2019. // Copyright © 2019 Maxim Tolstikov. All rights reserved. // enum AlertTitle: String { case weather = "Текущая погода" case warning = "Внимание!" }
// // AssetSettingsInteractor.swift // WavesWallet-iOS // // Created by mefilt on 29/11/2018. // Copyright © 2018 Waves Platform. All rights reserved. // import Foundation import RxSwift import WavesSDKExtensions private enum Constants { static let sortLevelNotFound: Float = -1 } final class AssetsBalanceSettingsUseCase: AssetsBalanceSettingsUseCaseProtocol { private let assetsBalanceSettingsRepository: AssetsBalanceSettingsRepositoryProtocol private let environmentRepository: EnvironmentRepositoryProtocol private let authorizationInteractor: AuthorizationUseCaseProtocol init(assetsBalanceSettingsRepositoryLocal: AssetsBalanceSettingsRepositoryProtocol, environmentRepository: EnvironmentRepositoryProtocol, authorizationInteractor: AuthorizationUseCaseProtocol) { self.assetsBalanceSettingsRepository = assetsBalanceSettingsRepositoryLocal self.environmentRepository = environmentRepository self.authorizationInteractor = authorizationInteractor } func settings(by accountAddress: String, assets: [DomainLayer.DTO.Asset]) -> Observable<[DomainLayer.DTO.AssetBalanceSettings]> { return authorizationInteractor.authorizedWallet() .flatMap({ [weak self] (wallet) -> Observable<[DomainLayer.DTO.AssetBalanceSettings]> in guard let self = self else { return Observable.empty() } return self.environmentRepository.walletEnvironment() .flatMap({ [weak self] (environment) -> Observable<[DomainLayer.DTO.AssetBalanceSettings]> in guard let self = self else { return Observable.empty() } let ids = assets.map { $0.id } let settings = self.assetSettings(assets: assets, ids: ids, accountAddress: accountAddress, environment: environment) .flatMapLatest { [weak self] (settings) -> Observable<Bool> in guard let self = self else { return Observable.never() } return self .assetsBalanceSettingsRepository .saveSettings(by: accountAddress, settings: settings) } .flatMapLatest { [weak self] (settings) -> Observable<[DomainLayer.DTO.AssetBalanceSettings]> in guard let self = self else { return Observable.never() } return self .assetsBalanceSettingsRepository .listenerSettings(by: accountAddress, ids: ids) .map { $0.sorted(by: { $0.sortLevel < $1.sortLevel }) } } return settings }) }) } func setFavorite(by accountAddress: String, assetId: String, isFavorite: Bool) -> Observable<Bool> { return assetsBalanceSettingsRepository .settings(by: accountAddress) .flatMap { [weak self] (settings) -> Observable<Bool> in guard let self = self else { return Observable.never() } let sortedSettings = settings.sorted(by: { $0.sortLevel < $1.sortLevel }) guard var asset = settings.first(where: { $0.assetId == assetId }) else { return Observable.never() } if asset.isFavorite == isFavorite { return Observable.just(true) } var newSettings = sortedSettings.filter { $0.isFavorite && $0.assetId != assetId } let otherList = sortedSettings.filter { $0.isFavorite == false && $0.assetId != assetId } asset.isFavorite = isFavorite asset.isHidden = false newSettings.append(asset) newSettings.append(contentsOf: otherList) for index in 0..<newSettings.count { newSettings[index].sortLevel = Float(index) } return self.assetsBalanceSettingsRepository.saveSettings(by: accountAddress, settings: newSettings) } } func updateAssetsSettings(by accountAddress: String, settings: [DomainLayer.DTO.AssetBalanceSettings]) -> Observable<Bool> { return assetsBalanceSettingsRepository.saveSettings(by: accountAddress, settings: settings) } } private extension AssetsBalanceSettingsUseCase { //TODO: Refactor method func assetSettings(assets: [DomainLayer.DTO.Asset], ids: [String], accountAddress: String, environment: WalletEnvironment) -> Observable<[DomainLayer.DTO.AssetBalanceSettings]> { let spamIds = assets.reduce(into: [String: Bool](), {$0[$1.id] = $1.isSpam }) return assetsBalanceSettingsRepository.settings(by: accountAddress, ids: ids) .flatMapLatest({ [weak self] (mapSettings) -> Observable<[DomainLayer.DTO.AssetBalanceSettings]> in guard let self = self else { return Observable.empty() } let sortedSettings = mapSettings .reduce(into: [DomainLayer.DTO.AssetBalanceSettings](), { $0.append($1.value) }) .filter({ $0.sortLevel != Constants.sortLevelNotFound }) .sorted(by: { $0.sortLevel < $1.sortLevel }) let withoutSettingsAssets = assets.reduce(into: [DomainLayer.DTO.Asset](), { (result, asset) in if let settings = mapSettings[asset.id] { if settings.sortLevel == Constants.sortLevelNotFound { result.append(asset) } else if settings.isFavorite && spamIds[settings.assetId] == true { result.append(asset) } } else { result.append(asset) } }) let withoutSettingsAssetsSorted = self .sortAssets(assets: withoutSettingsAssets, enviroment: environment) .map { (asset) -> DomainLayer.DTO.AssetBalanceSettings in return DomainLayer.DTO.AssetBalanceSettings(assetId: asset.id, sortLevel: Constants.sortLevelNotFound, isHidden: false, isFavorite: asset.isInitialFavorite) } var settings = [DomainLayer.DTO.AssetBalanceSettings]() settings.append(contentsOf: sortedSettings) settings.append(contentsOf: withoutSettingsAssetsSorted) settings = settings .enumerated() .map { (element) -> DomainLayer.DTO.AssetBalanceSettings in let settings = element.element let level = Float(element.offset) let isFavorite = settings.isFavorite && spamIds[settings.assetId] == false return DomainLayer.DTO.AssetBalanceSettings(assetId: settings.assetId, sortLevel: level, isHidden: settings.isHidden, isFavorite: isFavorite) } return Observable.just(settings) }) } func sortAssets(assets: [DomainLayer.DTO.Asset], enviroment: WalletEnvironment) -> [DomainLayer.DTO.Asset] { let favoriteAssets = assets.filter { $0.isInitialFavorite }.sorted(by: { $0.isWaves && !$1.isWaves }) let secondsAssets = assets.filter { !$0.isInitialFavorite } let generalBalances = enviroment.generalAssets let sorted = secondsAssets.sorted { (assetFirst, assetSecond) -> Bool in let isGeneralFirst = assetFirst.isGeneral let isGeneralSecond = assetSecond.isGeneral if isGeneralFirst == true && isGeneralSecond == true { let indexOne = generalBalances .enumerated() .first(where: { $0.element.assetId == assetFirst.id }) .map { $0.offset } let indexTwo = generalBalances .enumerated() .first(where: { $0.element.assetId == assetSecond.id }) .map { $0.offset } if let indexOne = indexOne, let indexTwo = indexTwo { return indexOne < indexTwo } return false } if isGeneralFirst { return true } return false } return favoriteAssets + sorted } } private extension DomainLayer.DTO.Asset { var isInitialFavorite: Bool { return isWaves || (isMyWavesToken && !isSpam) } }
// // Database.swift // TodoList // // Created by Christian Oberdörfer on 18.03.19. // Copyright © 2019 Christian Oberdörfer. All rights reserved. // import CoreStore import Foundation import QLog /** Stores database information */ struct Database { static let modelName = App.name /// The CoreStore data stack of the application static let dataStack: DataStack = { let dataStack = DataStack(xcodeModelName: Database.modelName) do { try dataStack.addStorageAndWait(SQLiteStore(fileName: Database.modelName, configuration: "Default", localStorageOptions: . recreateStoreOnModelMismatch)) } catch let error { QLogError("Cannot set up database storage: \(error)") } return dataStack }() }
// // CastManager.swift // CastVideoTest // // Created by Ivan Obodovskyi on 4/10/19. // Copyright © 2019 Ivan Obodovskyi. All rights reserved. // import Foundation import GoogleCast class CastManager { private var sessionManager: GCKSessionManager! func initialise() { initialiseContext() createSessionManager() } //creates the GCKSessionManager private func createSessionManager() { sessionManager = GCKCastContext.sharedInstance().sessionManager } //initialises the GCKCastContext private func initialiseContext() { //application Id from the registered application let options = GCKCastOptions(discoveryCriteria: GCKDiscoveryCriteria.init(applicationID: "6118C72A")) GCKCastContext.setSharedInstanceWith(options) GCKCastContext.sharedInstance().useDefaultExpandedMediaControls = true } }
// // GameDetailViewController.swift // desafioZapVivaReal // // Created by Mac on 06/02/18. // Copyright © 2018 Mac. All rights reserved. // import UIKit import Kingfisher class GameDetailViewController: UIViewController { @IBOutlet weak var gameName: UILabel? @IBOutlet weak var gameImage: UIImageView? @IBOutlet weak var gameVisualization: UILabel? @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var gameView: UIView! var gameNameText: String? var gameImageView: UIImageView? var gameVisualizationText: String? var game: Game? init() { super.init(nibName: nil, bundle: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.gameView.isHidden = true self.activityIndicator.startAnimating() } override func viewDidLoad() { super.viewDidLoad() // var rightFavoriteBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.backgroundImage(UIImage(named: "notFavorite")), target: self, action: #selector(favoriteGame)) // navigationItem.setRightBarButton(rightFavoriteBarButtonItem, animated: true) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.gameName?.text = self.gameNameText let url = URL(string: (self.game?.gameImageList?.boxImages?.bannerLarge)!) self.gameImage?.kf.setImage(with: url!) self.gameVisualization?.text = "Número de visualizações: \(String(describing: self.gameVisualizationText!))" self.setNavigationTitle() self.view.layoutIfNeeded() self.view.updateConstraints() self.gameView.isHidden = false self.activityIndicator.stopAnimating() } func setNavigationTitle() { let navLabel = UILabel() navLabel.numberOfLines = 2 navLabel.textAlignment = .center let navTitle = NSMutableAttributedString(string: self.gameNameText!, attributes:[ NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont(name: "Roboto-Bold", size: 18)!]) navLabel.attributedText = navTitle self.navigationItem.titleView = navLabel } func setupVC(game: Game) { self.game = game self.gameNameText = game.gameName?.name! self.gameVisualizationText = String(game.visualizations!) self.view.layoutIfNeeded() self.view.updateConstraints() } func favoriteGame() { } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
//: [Previous](@previous) import Foundation /* Swift Memory Management Intro to Memory Management Problem: Deallocate and allocate object in ARC What is memory? 1. RAM: Fridge 2. DISK: Storage */ class Passport { var human: Human? var citizenship: String init(citizenship: String) { self.citizenship = citizenship print("\(citizenship) passport generated") } deinit { print("I, paper, am gone") } } class Human { weak var passport: Passport? let name: String init(name: String) { self.name = name print("\(name) generated") } deinit { print("I, \(name), gone") } } //: Automatic Reference Counting //: Create Instance var uchenna: Human? = Human(name: "Uchenna") var myPassport: Passport? = Passport(citizenship: "American") uchenna?.passport = myPassport myPassport?.human = uchenna uchenna = nil myPassport = nil /* Note: The Only Rule: if the reference count is zero/no relationship, the object gets purged out of memory */ //: [Next](@next)
// // TransactionsAPIMock.swift // TransactionsTests // // Created by Thiago Santiago on 1/20/19. // Copyright © 2019 Thiago Santiago. All rights reserved. // import Foundation import Alamofire @testable import Transactions class TransactionsWorkerMock: TransactionsWorker { var isFailure = false override func getTransactions(page: String, success: @escaping GetTransactionsSuccess, failure: @escaping Failure) { if self.isFailure { failure(TransactionsAPIError.unknownResponse) } else { let transactionList = TransactionList(transactions: self.createTransactionsList(), nextPage: "") success(transactionList) } } func createTransactionsList() -> [Transaction] { var transactions: [Transaction] = [] let testBundle = Bundle(for: type(of: self)) if let path = testBundle.path(forResource: "transactions", ofType: "json") { do { let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe) let decoder = JSONDecoder() transactions = try decoder.decode([Transaction].self, from: data) return transactions } catch { return transactions } } else { return transactions } } override func getUserInfo(success: @escaping TransactionsWorker.GetUserSuccess, failure: @escaping TransactionsWorker.Failure) { if isFailure { failure(TransactionsAPIError.unknownResponse) } else { let user = UserInfo(name: "Ernesto", surname: "Skipper", birthdate: "15/08/1970", nationality: "AUS") success(user) } } override func loadImage(success: @escaping TransactionsWorkerMock.GetUserImageSuccess, failure: @escaping TransactionsWorkerMock.Failure) { success(UIImage(named: "ic_wallet")!) } override func saveUser(image: UIImage, success: @escaping TransactionsWorkerMock.UserImageSavedSuccess, failure: @escaping TransactionsWorkerMock.Failure) { if isFailure { failure(TransactionsAPIError.unknownResponse) } else { success(true) } } }
// // XiTongSheZhiViewController.swift // Live-zzu // // Created by 如是我闻 on 2017/4/8. // Copyright © 2017年 如是我闻. All rights reserved. // import UIKit class XiTongSheZhiViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. addBackBtn() } //导航返回设置 func addBackBtn(){ let img=UIImage(named: "fragment_back.png") let leftBtn:UIBarButtonItem=UIBarButtonItem(image: img, style: UIBarButtonItemStyle.plain, target: self, action: #selector(XiTongSheZhiViewController.actionBack)) leftBtn.tintColor=UIColor.gray self.navigationItem.leftBarButtonItem=leftBtn; } //返回按钮事件 func actionBack(){ self.presentingViewController!.dismiss(animated: true, completion: nil) } }
// // CustomCell.swift // PopuMov // // Created by Shouri on 06/04/16. // Copyright © 2016 Shouri. All rights reserved. // import UIKit class CustomCell: UICollectionViewCell{ let imageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) imageView.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height) addSubview(imageView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // ViewController.swift // Landmark Book // // Created by İzzet Kara on 24.06.2019. // Copyright © 2019 Izzet Kara. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var landmarkNames = [String] () var landmarkImage = [UIImage] () var selectedLandmarkName = "" var selectedLanmarkImage = UIImage() func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return landmarkNames.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.text = landmarkNames[indexPath.row] return cell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { // Bir satırı kullanıcı kendi silmek isterse bu fonksiyonu kullanablirim.< if editingStyle == UITableViewCell.EditingStyle.delete { landmarkNames.remove(at: indexPath.row) landmarkImage.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } } // Kod: Bir yer seçildiğinde ne yapacağını yazıyoruz.Alttaki kod. didSelectRowAt func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedLandmarkName = landmarkNames[indexPath.row] selectedLanmarkImage = landmarkImage [indexPath.row] performSegue(withIdentifier: "toolImageViewController", sender: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "toolImageViewController" { let destinationViewController = segue.destination as! ImageViewController destinationViewController.landmarkName = selectedLandmarkName destinationViewController.landmarkImage = selectedLanmarkImage } } @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self landmarkNames.append("Istanbul") landmarkNames.append("Eskisehir") landmarkNames.append("Antalya") landmarkNames.append("Izmir") landmarkNames.append("Canakkale") landmarkImage.append(UIImage(named: "istanbul.jpg")!) landmarkImage.append(UIImage(named: "eskisehir.jpg")!) landmarkImage.append(UIImage(named: "antalya.jpg")!) landmarkImage.append(UIImage(named: "izmir.jpg")!) landmarkImage.append(UIImage(named: "canakkale.jpg")!) } }
// // NetworkManager.swift // Networking // // Created by liuxc on 2019/7/15. // Copyright © 2019 liuxc. All rights reserved. // import Foundation import Moya import RxSwift import RxCocoa import Alamofire public typealias NetworkErrorCallback = (NetworkError) -> Void class NetworkCancelWraper { var cancellable: Cancellable? init(_ cancellable: Cancellable) { self.cancellable = cancellable } func cancel() { cancellable?.cancel() } } public enum NetworkManager { case base(api: TargetType) public func bind<Handler: NetworkResponseHandler>(_ type: Handler.Type) -> NetworkResponseObserver<Handler> { switch self { case .base(let api): return NetworkResponseObserver<Handler>(api: api) } } public func bind<Handler: NetworkDataResponseHandler>(_ type: Handler.Type) -> NetworkDataObserver<Handler> { switch self { case .base(let api): return NetworkDataObserver<Handler>(api: api) } } public func bind<Handler: NetworkListDataResponseHandler>(_ type: Handler.Type) -> NetworkListDataObserver<Handler> { switch self { case .base(let api): return NetworkListDataObserver<Handler>(api: api) } } } public struct NetworkListDataObserver<Handler: NetworkListDataResponseHandler> { var api: TargetType public func single(progress: ProgressBlock? = nil, test: Bool = false) -> PrimitiveSequence<SingleTrait, [Handler.Response.ItemData]> { return createSingle(api: api, progress: progress, test: test) } func createSingle(api: TargetType, progress: ProgressBlock? = nil, test: Bool = false) -> PrimitiveSequence<SingleTrait, [Handler.Response.ItemData]> { let single = Single<[Handler.Response.ItemData]>.create { (single) -> Disposable in var responseHandle = Handler.init() let cancellableToken: NetworkCancelWraper = api.createRequest(networkManager: responseHandle.networkManager, plugins: responseHandle.plugins, progress: progress, success: { (resp) in do { let response = try responseHandle.makeResponse(resp.data) responseHandle.response = response if let error = responseHandle.makeCustomNetworkError() { single(.error(error)) } else { single(.success(response.listData)) } } catch let error as NetworkError { single(.error(error)) responseHandle.handleNetworkError(error) } catch {} }, error: { (error) in responseHandle.handleNetworkError(error) }, test: test) return Disposables.create { cancellableToken.cancel() } } return single } } public struct NetworkDataObserver<Handler: NetworkDataResponseHandler> { var api: TargetType public func single(progress: ProgressBlock? = nil, test: Bool = false) -> PrimitiveSequence<SingleTrait, Handler.Response.DataSource> { return createSingle(api: api, progress: progress, test: test) } func createSingle(api: TargetType, progress: ProgressBlock? = nil, test: Bool = false) -> PrimitiveSequence<SingleTrait, Handler.Response.DataSource> { let single = Single<Handler.Response.DataSource>.create { (single) -> Disposable in var responseHandle = Handler.init() let cancellableToken: NetworkCancelWraper = api.createRequest(networkManager: responseHandle.networkManager, plugins: responseHandle.plugins, progress: progress, success: { (resp) in do { let response = try responseHandle.makeResponse(resp.data) responseHandle.response = response if let error = responseHandle.makeCustomNetworkError() { single(.error(error)) } else { single(.success(response.data)) } } catch let error as NetworkError { single(.error(error)) responseHandle.handleNetworkError(error) } catch {} }, error: { (error) in single(.error(error)) responseHandle.handleNetworkError(error) }, test: test) return Disposables.create { cancellableToken.cancel() } } return single } } public struct NetworkResponseObserver<Handler: NetworkResponseHandler> { var api: TargetType public func single(progress: ProgressBlock? = nil, test: Bool = false) -> PrimitiveSequence<SingleTrait, Handler.Response> { return createSingle(api: api, progress: progress, test: test) } func createSingle(api: TargetType, progress: ProgressBlock? = nil, test: Bool = false) -> PrimitiveSequence<SingleTrait, Handler.Response> { let single = Single<Handler.Response>.create { (single) -> Disposable in var responseHandle = Handler.init() let cancellableToken: NetworkCancelWraper = api.createRequest(networkManager: responseHandle.networkManager, plugins: responseHandle.plugins, progress: progress, success: { (resp) in do { let response = try responseHandle.makeResponse(resp.data) responseHandle.response = response if let error = responseHandle.makeCustomNetworkError() { single(.error(error)) } else { single(.success(response)) } } catch let error as NetworkError { single(.error(error)) } catch {} }, error: { (error) in single(.error(error)) responseHandle.handleNetworkError(error) }, test: test) return Disposables.create { cancellableToken.cancel() } } return single } } extension TargetType { func createRequest(networkManager: Manager, plugins: [PluginType], progress: ProgressBlock? = nil, success: @escaping (Response) -> (), error: NetworkErrorCallback? = nil, test: Bool = false) -> NetworkCancelWraper { let provider: MoyaProvider<Self> = createProvider(networkManager: networkManager, plugins: plugins, test: test) let request = provider.request(self, callbackQueue: .global(), progress: progress) { (result) in switch result { case .failure(let e): error?(.default(error: e)) case .success(let d): do { let r = try d.filterSuccessfulStatusCodes() success(r) } catch let e as MoyaError { switch e { case .statusCode(let r): error?(.status(code: r.statusCode)) default: () } } catch {} } } return NetworkCancelWraper(request) } func createProvider(networkManager: Manager, plugins: [PluginType], test: Bool) -> MoyaProvider<Self> { let endpointClosure = { (target: TargetType) -> Endpoint in let url = target.baseURL.appendingPathComponent(target.path).absoluteString let endpoint = Endpoint(url: url, sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, task: target.task, httpHeaderFields: target.headers) return endpoint } if test { return MoyaProvider<Self>(endpointClosure: endpointClosure, stubClosure: { (target) -> StubBehavior in return StubBehavior.immediate }, manager: networkManager, plugins: plugins) } else { return MoyaProvider<Self>.init(endpointClosure: endpointClosure, manager: networkManager, plugins: plugins) } } }
// // LoginViewController.swift // FreeTime // // Created by Miki on 2015/10/04. // Copyright © 2015年 Miki. All rights reserved. // import UIKit import Parse import FBSDKCoreKit import ParseFacebookUtilsV4 class LoginViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func signInButtonTapped(sender: AnyObject) { PFFacebookUtils.logInInBackgroundWithReadPermissions(["public_profile","email"], block: { (user:PFUser?, error:NSError?) -> Void in if(error != nil) { //Display an alert message let myAlert = UIAlertController(title:"Alert", message:error?.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert); let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil) myAlert.addAction(okAction); self.presentViewController(myAlert, animated:true, completion:nil); return } print(user) print("Current user token=\(FBSDKAccessToken.currentAccessToken().tokenString)") print("Current user id \(FBSDKAccessToken.currentAccessToken().userID)") if (FBSDKAccessToken.currentAccessToken() != nil) { } }) } }
// // RealmService.swift // imgurTestApp // // Created by Admin on 01/10/2018. // Copyright © 2018 MacBook Pro. All rights reserved. // import Foundation import RealmSwift class RealmService { /// Метод сохраняет в БД объект изображения и массив комментариев /// - Parameter model : Image объект изображения /// - Parameter comments : [Comment] массив комментариев static func saveImage(model: Image, comments: [Comment]) { let realm = try! Realm() model.comment.append(objectsIn: comments) do { try realm.write { realm.add(model, update: true) //print("Image \(model.id) saved in DB, comments count - \(model.comment.count)") } } catch let error { print("\(#function) error saving model - \(error.localizedDescription)") } } ///Метод возвращает из БД массив объектов изображение static func getImages() -> (Results<Image>) { let realm = try! Realm() return realm.objects(Image.self).sorted(byKeyPath: "id").sorted(byKeyPath: "page", ascending: true) } ///метод очищает существующую БД static func deleteAll() { let realm = try! Realm() do { try realm.write { realm.deleteAll() print("DB cleared") } } catch let error { print("\(#function) error deleting model - \(error.localizedDescription)") } } }
import Foundation import SwiftDate extension SwiftUbx { public func timestamp() -> Int { return Int(Date().timeIntervalSince1970) } public func formatDate(_ timestamp: Double) -> String { let date = Date(timeIntervalSince1970: timestamp/1000) let formattedDate = date.string(format: .custom("yyyy-MM-dd HH:mm:ss")) return formattedDate } public func randomUserAgent() -> String { let userAgents = [ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.94 Safari/537.36", "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; fr) AppleWebKit/416.12 (KHTML, like Gecko) Safari/412.5", "Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20120819 Firefox/15.0 PaleMoon/15.0", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; GTB6; Acoo Browser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)", "Mozilla/5.0 (Windows; U; Windows NT 5.1; pt-BR) AppleWebKit/534.12 (KHTML, like Gecko) NavscapeNavigator/Pre-0.1 Safari/534.12", "Mozilla/5.0 (Windows; U; WinNT4.0; de-AT; rv:1.7.11) Gecko/20050728", ] let randomIndex = Int(arc4random_uniform(UInt32(userAgents.count))) return userAgents[randomIndex] } }
// // CollectionView.swift // TableView // // Created by Zeinab on 11/10/20. // Copyright © 2020 Zeinab. All rights reserved. // import UIKit class CollectionView: UIViewController, UICollectionViewDelegate { @IBOutlet weak var collectionView: UICollectionView! var photos: [Photos] = [] let refresh = UIRefreshControl() let itemsPerRow: CGFloat = 3 private let sectionInsets = UIEdgeInsets(top: 25.0, left: 10.0, bottom: 25.0, right: 10.0) override func viewDidLoad() { super.viewDidLoad() configureCollectionView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) getPhotos() } func configureCollectionView() { collectionView.delegate = self collectionView.dataSource = self collectionView.register(CollectionViewCell.nibCollection(), forCellWithReuseIdentifier: CollectionViewCell.collectionCell) collectionView.refreshControl = refresh refresh.addTarget(self, action: #selector(refreshPhotos), for:.valueChanged) } @objc func refreshPhotos (_ sender:Any) { getPhotos() } func getPhotos() { guard let url = URL(string:"https://jsonplaceholder.typicode.com/photos?albumId=1") else {return} let task = URLSession.shared.dataTask(with: url) { (data, response, error) in DispatchQueue.main.async { self.refresh.endRefreshing() } guard let jsonData = data , error == nil else { print("error!") return } do { let photos = try JSONDecoder().decode([Photos].self, from: jsonData) DispatchQueue.main.async { self.photos = photos self.collectionView.reloadData() } } catch { print("Error \(error.localizedDescription)") } } task.resume() } } extension CollectionView: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return photos.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCell.collectionCell, for: indexPath) as? CollectionViewCell { cell.configure(imageUrl: photos[indexPath.item].thumbnailUrl) return cell } else { return UICollectionViewCell() } } } extension CollectionView: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let paddingSpace = sectionInsets.left * (itemsPerRow + 1) let availableWidth = view.frame.width - paddingSpace let widthPerItem = availableWidth / itemsPerRow return CGSize(width: floor(widthPerItem), height: floor(widthPerItem)) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return sectionInsets } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return sectionInsets.left } }
import Simplex let x1 = Variable("x1") let x2 = Variable("x2") let x3 = Variable("x3") let x4 = Variable("x4") let x5 = Variable("x5") let x6 = Variable("x6")
// // QuestionSet.swift // cloudkit // // Created by Gibson Kong on 01/04/2017. // Copyright © 2017 Gibson Kong. All rights reserved. // import Foundation class quiz{ var id : Int! var question : String! var answer : [String]! var choice : [String]! init(id:Int,question:String,choice:[String],answer:[String]) { self.id = id self.question = question self.answer = answer self.choice = choice } func checkAns(){ return } func start(){ } } class ExamSet{ var setID : Int! var name : String! var quizList = [quiz]() var LicenseDir : String! var Filename : String! init(id : Int, name : String, LicenseDir : String, Filename : String) { self.setID = id self.name = name self.LicenseDir = LicenseDir self.Filename = Filename } func addQuiz(_ element:quiz){ quizList.append(element) } func selectQuiz(_ id:Int) -> quiz { return quizList[(id - 1)] } func demoQuizInit(){ for i in 1...20 { var asd:[String] = [] for j in 1...10 { asd.append("\(i * j * 2)") } let _quiz = quiz(id: i, question: "number \(i)", choice: asd, answer: ["0"] ) self.addQuiz(_quiz) } for _quiz in quizList { print("\(_quiz.choice) \(_quiz.answer) \(_quiz.question)") } } func shuffle(){ for _ in 0..<quizList.count{ var a = 0 var b = 0 while(a == b){ a = Int(arc4random_uniform(UInt32(quizList.count))) b = Int(arc4random_uniform(UInt32(quizList.count))) } swap(&quizList[a], &quizList[b]) } } func clone() -> ExamSet{ let temp = ExamSet(id: self.setID, name: self.name, LicenseDir: self.LicenseDir, Filename: self.Filename) for i in self.quizList{ temp.quizList.append(i) } return temp } } class LicenseType { var LicenseName:String! var ExamSet : [ExamSet] = [] init(_ LicenseName:String){ self.LicenseName = LicenseName } func addExamSet(_ Set:ExamSet) { self.ExamSet.append(Set) } } class LicenseGrade{ var Grade : String! var LicenseType : [LicenseType] = [] init(_ QuizGrade :String) { self.Grade = QuizGrade } func addLicenseType(_ Type:LicenseType){ LicenseType.append(Type) } } class professionType{ var ProfessionName : String! var LicenseGrade : [LicenseGrade] = [] init(Name : String) { self.ProfessionName = Name } func addLicenseGrade(_ LicenseGrade:LicenseGrade){ self.LicenseGrade.append(LicenseGrade) } }
// MARK: Flatten /// A closure that returns a future. public typealias LazyFuture<T> = () throws -> Future<T> extension Collection { /// Flattens an array of lazy futures into a future with an array of results. /// - note: each subsequent future will wait for the previous to complete before starting. public func syncFlatten<T>(on worker: Worker) -> Future<[T]> where Element == LazyFuture<T> { let promise = worker.eventLoop.newPromise([T].self) var elements: [T] = [] elements.reserveCapacity(self.count) var iterator = makeIterator() func handle(_ future: LazyFuture<T>) { do { try future().do { res in elements.append(res) if let next = iterator.next() { handle(next) } else { promise.succeed(result: elements) } }.catch { error in promise.fail(error: error) } } catch { promise.fail(error: error) } } if let first = iterator.next() { handle(first) } else { promise.succeed(result: elements) } return promise.futureResult } } extension Collection where Element == LazyFuture<Void> { /// Flattens an array of lazy void futures into a single void future. /// - note: each subsequent future will wait for the previous to complete before starting. public func syncFlatten(on worker: Worker) -> Future<Void> { let flatten: Future<[Void]> = self.syncFlatten(on: worker) return flatten.transform(to: ()) } } extension Collection where Element: FutureType { /// Flattens an array of futures into a future with an array of results. /// - note: the order of the results will match the order of the futures in the input array. public func flatten(on worker: Worker) -> Future<[Element.Expectation]> { let eventLoop = worker.eventLoop // Avoid unnecessary work guard count > 0 else { return eventLoop.newSucceededFuture(result: []) } let resultPromise: EventLoopPromise<[Element.Expectation]> = eventLoop.newPromise() var promiseFulfilled = false let expectedCount = self.count var fulfilledCount = 0 var results = Array<Element.Expectation?>(repeating: nil, count: expectedCount) for (index, future) in self.enumerated() { future.addAwaiter { result in let work: () -> Void = { guard !promiseFulfilled else { return } switch result { case .success(let result): results[index] = result fulfilledCount += 1 if fulfilledCount == expectedCount { promiseFulfilled = true // Forcibly unwrapping is okay here, because we know that each result has been filled. resultPromise.succeed(result: results.map { $0! }) } case .error(let error): promiseFulfilled = true resultPromise.fail(error: error) } } if future.eventLoop === eventLoop { work() } else { eventLoop.execute(work) } } } return resultPromise.futureResult } } extension Collection where Element == Future<Void> { /// Flattens an array of void futures into a single one. public func flatten(on worker: Worker) -> Future<Void> { let flatten: Future<[Void]> = self.flatten(on: worker) return flatten.map(to: Void.self) { _ in return } } }
/** * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import UIKit import Parse class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet var usernameLabel: UITextField! @IBOutlet var passwordLabel: UITextField! @IBOutlet var isRiderSwitch: UISwitch! var activityIndicator = UIActivityIndicatorView() var isSpinning = false func spinner(begin: Bool) { if isSpinning == false { activityIndicator = UIActivityIndicatorView(frame: CGRect(x:0 , y:0, width: 50, height: 50)) activityIndicator.center = self.view.center activityIndicator.hidesWhenStopped = true activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray self.view.addSubview(activityIndicator) if begin == true { activityIndicator.startAnimating() self.view.alpha = 0.5 self.isSpinning = true } else if begin == false { /////// CAN'T STOP ANIMATING IF NOT ALREADY ANIMATED///////////////////// // activityIndicator.stopAnimating() // self.view.alpha = 1 // self.isSpinning = false } } else if isSpinning == true { if begin == true { activityIndicator.startAnimating() self.view.alpha = 0.5 self.isSpinning = true } else if begin == false { activityIndicator.stopAnimating() self.view.alpha = 1 self.isSpinning = false } } } func segueToRider() { self.performSegue(withIdentifier: "toRiderPage", sender: self) } func segueToDriver() { self.performSegue(withIdentifier: "toDriverPage", sender: self) } @IBAction func loginButton(_ sender: AnyObject) { if usernameLabel.text != "" || passwordLabel.text != "" { if let passwordCheck = passwordLabel.text { if passwordCheck.characters.count > 5 { if let usernameCheck = usernameLabel.text { if usernameCheck.characters.count > 2 { let usernameQuery = PFUser.query() usernameQuery?.whereKey("username", equalTo: usernameCheck) self.spinner(begin: true) usernameQuery?.findObjectsInBackground(block: { (object, error) in //spin self.spinner(begin: false) if error != nil { //QUERY ERROR ALERT let errorString = (error as? NSError)?.userInfo["error"] as? NSString let alert = UIAlertView(title: "Error", message: "\(errorString!)", delegate: self, cancelButtonTitle: "OK") alert.show() } else if object!.count == 0 { //NO USER WITH SUCH NAME, ALERT AND CLEAR TEXT FIELD let alert = UIAlertView(title: "Error", message: "NO USER WITH SUCH NAME, PLEASE SIGN UP OR CHECK FORM FOR TYPOS", delegate: self, cancelButtonTitle: "OK") alert.show() self.usernameLabel.text = "" self.passwordLabel.text = "" self.isRiderSwitch.isOn = true } else { PFUser.logInWithUsername(inBackground: usernameCheck, password: passwordCheck, block: { (user, error) in self.spinner(begin: false) if error != nil { // LOGIN ERROR ALERT let errorString = (error as? NSError)?.userInfo["error"] as? NSString let alert = UIAlertView(title: "Error", message: "\(errorString!)", delegate: self, cancelButtonTitle: "OK") alert.show() } else { // IF USER IS RIDER, GO TO RIDER PAGE if user?.value(forKey: "IsARider") as? Bool == true { self.segueToRider() } else if user?.value(forKey: "IsARider") as? Bool == false { // ELSE IF USER IS DRIVER, GO TO DRIVER PAGE self.segueToDriver() } //SEGUE FOR LOGIN print(PFUser.current()) print("login success") } }) } }) } else { // USERNAME SHORTER THAN 3 CHARACTERS ALERT let alert = UIAlertView(title: "Error", message: "ERROR IN FORM, USERNAME MUST BE LONGER THAN TWO CHARACTERS", delegate: self, cancelButtonTitle: "OK") alert.show() self.usernameLabel.text = "" self.passwordLabel.text = "" self.isRiderSwitch.isOn = true } } } else { // PASSWORD SHORTER THAN 6 CHARACTERS ALERT let alert = UIAlertView(title: "Error", message: "ERROR IN FORM. PASSWORD MUST BE LONGER THAN 5 CHARACTERS", delegate: self, cancelButtonTitle: "OK") alert.show() self.passwordLabel.text = "" self.isRiderSwitch.isOn = true } } } else { //USERNAME OR PASSWORD FIELD EMPTY ALERT let alert = UIAlertView(title: "Error", message: "ERROR IN FORM, FILL IN BOTH USERNAME AND PASSWORD", delegate: self, cancelButtonTitle: "OK") alert.show() self.usernameLabel.text = "" self.passwordLabel.text = "" self.isRiderSwitch.isOn = true } } @IBAction func signupButton(_ sender: AnyObject) { if usernameLabel.text != "" || passwordLabel.text != "" { if let passwordCheck = passwordLabel.text { if passwordCheck.characters.count > 5 { if let usernameCheck = usernameLabel.text { if usernameCheck.characters.count > 2 { let usernameQuery = PFUser.query() usernameQuery?.whereKey("username", equalTo: usernameCheck) self.spinner(begin: true) usernameQuery?.findObjectsInBackground(block: { (object, error) in self.spinner(begin: false) if error != nil { //QUERY ERROR ALERT let errorString = (error as? NSError)?.userInfo["error"] as? NSString let alert = UIAlertView(title: "Error", message: "\(errorString!)", delegate: self, cancelButtonTitle: "OK") alert.show() } else if object!.count > 0 { // USERNAME TAKEN ALERT let alert = UIAlertView(title: "Error", message: "THAT USERNAME HAS ALREADY BEEN TAKEN", delegate: self, cancelButtonTitle: "OK") alert.show() self.usernameLabel.text = "" self.passwordLabel.text = "" self.isRiderSwitch.isOn = true } else if object!.count == 0 { //SIGN UP let newUser = PFUser() newUser.setValue(usernameCheck, forKey: "username") newUser.setValue(passwordCheck, forKey: "password") if self.isRiderSwitch.isOn == true { //rider sign up newUser.setValue(true, forKey: "IsARider") } else if self.isRiderSwitch.isOn == false{ //driver sign up newUser.setValue(false, forKey: "IsARider") } //SET ACL let acl = PFACL() acl.getPublicWriteAccess = true acl.getPublicReadAccess = true newUser.acl = acl self.spinner(begin: true) newUser.signUpInBackground(block: { (success, error) in self.spinner(begin: false) if error != nil { //USER SAVE ERROR ALERT let errorString = (error as? NSError)?.userInfo["error"] as? NSString let alert = UIAlertView(title: "Error", message: "\(errorString!)", delegate: self, cancelButtonTitle: "OK") alert.show() } else { // IF USER IS RIDER, GO TO RIDER PAGE if PFUser.current()?.value(forKey: "IsARider") as? Bool == true { self.segueToRider() } else if PFUser.current()?.value(forKey: "IsARider") as? Bool == false { // ELSE IF USER IS DRIVER, GO TO DRIVER PAGE self.segueToDriver() } print(newUser) print("success signing up") //SIGNED UP, SEGUE TO NEW WINDOW } }) } }) } else { // USERNAME SHORTER THAN 3 CHARACTERS ALERT let alert = UIAlertView(title: "Error", message: "ERROR IN FORM, USERNAME CAN'T BE SHORTER THAN THREE CHARACTERS", delegate: self, cancelButtonTitle: "OK") alert.show() self.usernameLabel.text = "" self.passwordLabel.text = "" self.isRiderSwitch.isOn = true } } } else { // PASSWORD SHORTER THAN 6 CHARACTERS ALERT let alert = UIAlertView(title: "Error", message: "ERROR IN FORM. PASSWORD CAN'T BE SHORTER THAN SIX CHARACTERS", delegate: self, cancelButtonTitle: "OK") alert.show() self.passwordLabel.text = "" self.isRiderSwitch.isOn = true } } } else { //USERNAME OR PASSWORD FIELD EMPTY ALERT let alert = UIAlertView(title: "Error", message: "ERROR IN FORM. BOTH FIELDS MUST BE FILLED", delegate: self, cancelButtonTitle: "OK") alert.show() self.usernameLabel.text = "" self.passwordLabel.text = "" self.isRiderSwitch.isOn = true } } 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. } override func viewDidAppear(_ animated: Bool) { if PFUser.current() != nil { // IF USER IS RIDER, GO TO RIDER PAGE if PFUser.current()?.value(forKey: "IsARider") as? Bool == true { segueToRider() } else if PFUser.current()?.value(forKey: "IsARider") as? Bool == false { // ELSE IF USER IS DRIVER, GO TO DRIVER PAGE segueToDriver() } } } /////////////////////////////////////////////////// // KEYBOARD DISMISS METHODS ///////////// override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
// // WeatherManager.swift // Calm Cloud // // Created by Kate Duncan-Welke on 10/9/20. // Copyright © 2020 Kate Duncan-Welke. All rights reserved. // import Foundation import UIKit struct WeatherManager { static var currentWeather: Weather = .clearWarm static let range = [1,2,3] static let snowDays = [1, 3, 5, 7, 10, 11, 13, 15, 17, 19, 20, 23, 25, 29, 30, 31] static func hasSnow(month: Int, day: Int) -> Bool { // snow possible november through march if month < 4 || month >= 11 { if snowDays.contains(day) { return true } else { return false } } else { // month does not fall into snow range return false } } static func getWeather(month: Int, day: Int) -> Weather { let isRaining = range.randomElement() print("month: \(month)") // snow possible november through march if month < 4 || month >= 11 { if hasSnow(month: month, day: day) { let isSnowing = Bool.random() if isSnowing { currentWeather = .snowing return .snowing } else { currentWeather = .snowOnGround return .snowOnGround } } else { currentWeather = .clearCool return .clearCool } } else if month > 3 && month < 9 { // possible rainy months in summer if isRaining == 3 { currentWeather = .rainingWarm return .rainingWarm } else { currentWeather = .clearWarm return .clearWarm } } else { // possible rainy months in fall, sept-oct if isRaining == 3 { currentWeather = .rainingCool return .rainingCool } else { currentWeather = .clearCool return .clearCool } } } static let rainImages = [#imageLiteral(resourceName: "rain1.png"),#imageLiteral(resourceName: "rain2.png")] static let snowImages = [#imageLiteral(resourceName: "snow1.png"),#imageLiteral(resourceName: "snow2.png"),#imageLiteral(resourceName: "snow3.png"),#imageLiteral(resourceName: "snow4.png"),#imageLiteral(resourceName: "snow5.png"),#imageLiteral(resourceName: "snow6.png")] } enum Weather { case clearWarm case clearCool case rainingWarm case rainingCool case snowing case snowOnGround } enum WeatherCondition { case rain case snow case nothing }
// // Color+Lerp.swift // LumoPostureV2.0 // // Created by Emil Selin on 4/8/18. // Copyright © 2018 com. All rights reserved. // import UIKit extension UIColor { static func lerp(colorA: UIColor, colorB: UIColor, colorC: UIColor, t: CGFloat) -> UIColor { let compA = t < 0.5 ? colorA.cgColor.components! : colorB.cgColor.components! let compB = t < 0.5 ? colorB.cgColor.components! : colorC.cgColor.components! return UIColor(red: compA[0] + (compB[0] - compA[0]) * (t*2 - 1), green: compA[1] + (compB[1] - compA[1]) * (t*2 - 1), blue: compA[2] + (compB[2] - compA[2]) * (t*2 - 1), alpha: 1.0) } }
// // SalmonRotationListView.swift // ikalendar2 // // Created by Tianwei Zhang on 3/26/21. // import SwiftUI // MARK: - SalmonRotationListView /// The view that displays a list of salmon rotations. struct SalmonRotationListView: View { @EnvironmentObject var ikaCatalog: IkaCatalog @EnvironmentObject var ikaTimer: IkaTimer var salmonRotations: [SalmonRotation] { let rawRotations = ikaCatalog.salmonRotations func filterCurrent<T: Rotation>(rotation: T) -> Bool { !rotation.isExpired(currentTime: ikaTimer.currentTime) } let results = rawRotations.filter(filterCurrent) return results } var body: some View { GeometryReader { geometry in Form { ForEach(Array(salmonRotations.enumerated()), id: \.offset) { index, rotation in SalmonRotationRow(rotation: rotation, index: index, width: geometry.size.width) } } .disabled(ikaCatalog.loadingStatus != .loaded) } } } // MARK: - SalmonRotationListView_Previews struct SalmonRotationListView_Previews: PreviewProvider { static var previews: some View { SalmonRotationListView() } }
// // CameraMenuViewController.swift // KidsChannel // // Created by sungju on 2017. 3. 28.. // Copyright © 2017년 sungju. All rights reserved. // import UIKit import SlideMenuControllerSwift enum RightMenu: Int { case close = 0 case cameraList case fourChennel case eightChennel case cameraListChennel case gellery } protocol RightMenuProtocol : class { func changeViewController(_ menu: RightMenu) } class CameraMenuViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var menus = ["", "카메라 뷰어", "4ch 카메라 뷰어", "8ch 카메라 뷰어", "리스트 카메라 뷰어", "갤러리 뷰어"] var mainViewController: UIViewController! var fourChViewController: UIViewController! var eightChViewController: UIViewController! var cameraListChViewController: UIViewController! var galleryViewController: UIViewController! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let storyboard = UIStoryboard(name: "Main", bundle: nil) let fourChViewController = storyboard.instantiateViewController(withIdentifier: "FourChannelCameraViewController") as! FourChannelCameraViewController self.fourChViewController = UINavigationController(rootViewController: fourChViewController) let eightChViewController = storyboard.instantiateViewController(withIdentifier: "EightChannelCameraViewController") as! EightChannelCameraViewController self.eightChViewController = UINavigationController(rootViewController: eightChViewController) let cameraListChViewController = storyboard.instantiateViewController(withIdentifier: "CameraListChannelViewController") as! CameraListChannelViewController self.cameraListChViewController = UINavigationController(rootViewController: cameraListChViewController) let galleryViewController = storyboard.instantiateViewController(withIdentifier: "GalleryViewController") as! GalleryViewController self.galleryViewController = UINavigationController(rootViewController: galleryViewController) self.tableView.registerCellNib(ButtonTableViewCell.self) self.tableView.tableFooterView = UIView(frame: CGRect.zero) } override func viewWillAppear(_ animated: Bool) { self.tableView.separatorColor = AppConfigure.sharedInstance.appSkin.tableSeparatorColor() self.tableView.backgroundColor = AppConfigure.sharedInstance.appSkin.userMenuViewBackgrounColor() self.tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension CameraMenuViewController : RightMenuProtocol { func changeViewController(_ menu: RightMenu) { switch menu { case .fourChennel: self.slideMenuController()?.changeMainViewController(self.fourChViewController, close: true) case .eightChennel: self.slideMenuController()?.changeMainViewController(self.eightChViewController, close: true) case .cameraListChennel: self.slideMenuController()?.changeMainViewController(self.cameraListChViewController, close: true) case .gellery: self.slideMenuController()?.changeMainViewController(self.galleryViewController, close: true) default: return } } } extension CameraMenuViewController : UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if let menu = RightMenu(rawValue: indexPath.row) { switch menu { case .close: return ButtonTableViewCell.height()+UIApplication.shared.statusBarFrame.height case .cameraList, .fourChennel, .eightChennel, .cameraListChennel, .gellery: return ButtonTableViewCell.height() } } return 0 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let menu = RightMenu(rawValue: indexPath.row) { self.changeViewController(menu) } } func scrollViewDidScroll(_ scrollView: UIScrollView) { if self.tableView == scrollView { } } } extension CameraMenuViewController : UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menus.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let menu = RightMenu(rawValue: indexPath.row) { let cell = self.tableView.dequeueReusableCell(withIdentifier: ButtonTableViewCell.identifier) as! ButtonTableViewCell cell.preservesSuperviewLayoutMargins = false cell.separatorInset = UIEdgeInsets.zero cell.layoutMargins = UIEdgeInsets.zero cell.backgroundColor = UIColor.clear cell.cellTextLabel.textColor = AppConfigure.sharedInstance.appSkin.cameraMenuFontColor() cell.cellImageView.tintColor = AppConfigure.sharedInstance.appSkin.iconsNormalTintColor() var data: ButtonTableViewCellData? switch menu { case .close: data = ButtonTableViewCellData(image: nil, text: menus[indexPath.row]) case .cameraList: data = ButtonTableViewCellData(image: AppConfigure.sharedInstance.appSkin.fourCameraChannelIcon(), text: menus[indexPath.row]) case .fourChennel, .eightChennel, .cameraListChennel: data = ButtonTableViewCellData(image: nil, text: menus[indexPath.row]) cell.backgroundColor = AppConfigure.sharedInstance.appSkin.otherChannelBackgroundColor() case .gellery: data = ButtonTableViewCellData(image: AppConfigure.sharedInstance.appSkin.galleryIcon(), text: menus[indexPath.row]) } cell.setData(data!) return cell } return UITableViewCell() } }
// // LoginRequest.swift // On the map // // Created by Bharani Nammi on 6/30/20. // Copyright © 2020 Bharani Nammi. All rights reserved. // import Foundation struct LoginRequest: Encodable { let udacity: UdacityUsernamePassword } struct UdacityUsernamePassword: Encodable { let username: String let password: String }
// // SettingsViewController.swift // Face-To-Name // // Created by John Bales on 4/28/17. // Copyright © 2017 John T Bales. All rights reserved. // import UIKit import AWSMobileHubHelper class SettingsViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: Login and Logout func handleLogout() { if (AWSIdentityManager.default().isLoggedIn) { AWSIdentityManager.default().logout(completionHandler: {(result: Any?, error: Error?) in self.navigationController!.popToRootViewController(animated: false) // self.setupRightBarButtonItem() self.presentSignInViewController() }) // print("Logout Successful: \(signInProvider.getDisplayName)"); } else { assert(false) } } //MARK: Actions @IBAction func signOut(_ sender: UIBarButtonItem) { handleLogout() } /* // 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. } */ }
import Foundation /// /// A model representing a pageable list of movies. /// public typealias MoviePageableList = PageableListResult<Movie>
// // CoinChange.swift // DynamicProgramming // // Created by ggl on 2020/8/23. // Copyright © 2020 ggl. All rights reserved. // 硬币找零问题 import Foundation /** * 硬币找零问题,我们在贪心算法那一节中讲过一次。我们今天来看一个新的硬币找零问题。 * 假设我们有几种不同币值的硬币 v1,v2,……,vn(单位是元), 如果我们要支付 w 元,求最少需要多少个硬币。 * 比如,我们有 3 种不同的硬币,1 元、3 元、5 元,我们要支付 9 元, * 最少需要 3 个硬币(3 个 3 元的硬币) */ /// 动态规划求解硬币找零问题 /// 钱币个数 + 金额作为状态 /// /// - Parameters: /// - coinItems: 不同硬币类别数组(例如:1元、3元、5元就传 [1,3,5]) /// - totalPay: 总共需要支付多少钱,例如9元 /// - Returns: 至少需要多个硬币 func coinChange(coinItems: [Int], totalPay: Int) -> Int { // 最大硬币个数,默认值为支付的金额 var maxCoinCount = totalPay if let minValue = coinItems.min() { // 硬币个数为需要支付的金额除以最小硬币数,向上取整 maxCoinCount = Int(ceil(Double(totalPay) / Double(minValue))) } // 状态数组,横轴存储支付的总金额(0~totalPay),纵轴存储硬币个数,范围为(0~maxCoinCount-1) var states = [[Bool]](repeating: [Bool](repeating: false, count: totalPay + 1), count: maxCoinCount) // 初始化硬币个数为1的数据(下标为0) for coin in coinItems { if coin > totalPay { continue } states[0][coin] = true } // 构建其他结点数值 for i in 1..<maxCoinCount { for j in 1...totalPay { // 判断已使用硬币数状态 if states[i-1][j] { // 遍历所有硬币,将状态设置为true for coin in coinItems { if j + coin <= totalPay { states[i][j+coin] = true } } } } } print("硬币状态数组=>") for i in 0..<maxCoinCount { for j in 0...totalPay { print(states[i][j] ? "1": "0", terminator: " ") } print("") } // 返回支付金额为totalPay,同时使用硬币最少的硬币个数 for i in 0..<maxCoinCount { if states[i][totalPay] { return i+1 } } return 0 } /// 最少硬币个数 private var minCoinCount = Int.max // 硬币状态映射,以钱币个数 + 金额作为Key private var coinStateMap = [String: Bool](minimumCapacity: 10) /// 回溯算法求解硬币找零问题 /// /// - Parameters: /// - coinItems: 硬币数组 /// - totalPay: 总共支付金额 /// - Returns: 最少硬币个数 func coinChangeRecursion(coinItems: [Int], totalPay: Int) -> Int { recurCoinChange(coinItems: coinItems, totalPay: totalPay, curPay: 0, coinCount: 0) return minCoinCount } /// 内部递归计算 /// /// - Parameters: /// - coinItems: 硬币数组 /// - totalPay: 总共支付金额 /// - curPay: 当前支付金额 /// - coinCount: 当前硬币个数 private func recurCoinChange(coinItems: [Int], totalPay: Int, curPay: Int, coinCount: Int) { // 支付金额超过,则返回 if curPay > totalPay { return } if curPay == totalPay { if coinCount < minCoinCount { minCoinCount = coinCount } return } /// 递归检查 for i in 0..<coinItems.count { recurCoinChange(coinItems: coinItems, totalPay: totalPay, curPay: curPay + coinItems[i], coinCount: coinCount + 1) } }
// // TeamMembersTableViewController.swift // Coordinate // // Created by James Wilkinson on 26/03/2016. // Copyright © 2016 James Wilkinson. All rights reserved. // import UIKit import Firebase class TeamInfoTableViewController: UITableViewController { var currentMember: Team.Member! var team: Team! private var data: [Team.Member] = [] override func viewDidLoad() { super.viewDidLoad() // 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() FIREBASE_ROOT_REF.childByAppendingPath("teams/\(team.id)/members").observeEventType(.ChildAdded) { (teamMemberSnap: FDataSnapshot!, previousKey: String!) in let username = teamMemberSnap.key FIREBASE_ROOT_REF.childByAppendingPath("users/\(username)/name").observeSingleEventOfType(.Value, withBlock: { (userSnap: FDataSnapshot!) in guard userSnap.exists() else { print("\(username) does not exist but is still a member of \(self.team.id)") return } guard let fullname = userSnap.value as? String else { print("\(username) does not have a full name??") return } let newMember = Team.Member(username: username) newMember.name = fullname if let prev = previousKey, index = self.data.indexOf({ $0.username == prev }) { self.data.insert(newMember, atIndex: index.advancedBy(1)) self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: index.advancedBy(1), inSection: 0)], withRowAnimation: .Automatic) } else { self.data.append(newMember) self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: self.data.count-1, inSection: 0)], withRowAnimation: .Automatic) } }) } FIREBASE_ROOT_REF.childByAppendingPath("teams/\(team.id)/members").observeEventType(.ChildRemoved) { (teamMemberSnap: FDataSnapshot!) in let username = teamMemberSnap.key if let index = self.data.indexOf({ $0.username == username }) { self.data.removeAtIndex(index) self.tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: .Automatic) } else { print("Member not found in tableview...") } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return self.data.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("memberCell", forIndexPath: indexPath) // Configure the cell... let member = self.data[indexPath.row] cell.textLabel!.text = member.name! + (member.username == self.currentMember.username ? " (You)" : "") cell.detailTextLabel!.text = member.username return cell } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let member = self.data[indexPath.row] if member.username == self.currentMember.username { UIAlertController.showAlertWithTitle("You cannot delete yourself from a team", message: nil, onViewController: self) return } let alert = UIAlertController(destructiveAlertWithTitle: "Are you sure?", message: "Are you sure you want to remove /\(member.username) from this team?", defaultTitle: "Yes", defaultHandler: { (_) in // Delete the row from the data source var dict = [String : AnyObject]() dict["teams/\(self.team.id)/members/\(member.username)"] = NSNull() dict["users/\(member.username)/teams/\(self.team.id)"] = NSNull() FIREBASE_ROOT_REF.updateChildValues(dict) }) self.navigationController!.presentViewController(alert, animated: true, completion: nil) } 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 func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String { return "Remove" } /* // 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. } */ }
// // LocationTableViewCell.swift // store-locations // // Created by Eric Drew on 2/16/16. // Copyright © 2016 Eric Drew. All rights reserved. // import UIKit class LocationTableViewCell: UITableViewCell { @IBOutlet weak var locationLbl: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func configureCell(location: String) { locationLbl.text = location } }
// // ViewController.swift // MVVMTutorial // // Created by mac on 2021/04/19. // import UIKit class ViewController: UIViewController { let tableView = UITableView() let models = [ Person(firstName: "Jang", lastName: "SeokJin", gender: "male", age: 30, height: 178.4), Person(firstName: "Kang", lastName: "SeonChan", gender: "male", age: 31, height: 177.7), Person(firstName: "Jeon", lastName: "JiHyeon", gender: "female", age: 22, height: 166.7), Person(firstName: "Son", lastName: "YeJin", gender: "female", age: 33, height: 158.2) ] override func viewDidLoad() { super.viewDidLoad() tableView.frame = view.bounds tableView.delegate = self tableView.dataSource = self tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: CustomTableViewCell.identifier) view.addSubview(tableView) } } //MARK: - UITableView extension ViewController:UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return models.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: CustomTableViewCell.identifier, for: indexPath) as! CustomTableViewCell let model = models[indexPath.row] cell.configure(with: Person(firstName: model.firstName, lastName: model.lastName, gender: model.gender, age: model.age, height: model.height)) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } }
// // ViewController.swift // FadeExtensionDemo // // Created by Gabrielle Miller-Messner on 6/26/15. // Copyright (c) 2015 Gabrielle Miller-Messner. All rights reserved. // import UIKit // MARK: - ViewController: UIViewController class ViewController: UIViewController { // MARK: Outlets @IBOutlet weak var imageView: UIImageView! @IBAction func alpha1(_ sender: Any) { imageView.alpha = 1 } @IBAction func alpha05(_ sender: Any) { imageView.alpha = 0.5 } @IBAction func alpha0(_ sender: UIButton) { imageView.alpha = 0 } @IBAction func anime1(_ sender: UIButton) { UIView.animate(withDuration: 1.0, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: { self.denme()}, completion: nil) } @IBAction func anime2(_ sender: Any) { UIView.animate(withDuration: 1.0, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: { self.imageView.alpha = 1}, completion: { (Bool) -> Void in if self.imageView.image == UIImage(named: "sunrise") { } self.sunRiseAndSet(AnyObject) self.anime2(Any) }) } func denme (){ self.imageView.alpha = 0 } // MARK: Actions @IBAction func sunRiseAndSet(_ sender: AnyObject) { if (self.imageView.image == UIImage(named: "sunrise")) { self.imageView.image = UIImage(named:"sunset")! } else { self.imageView.image = UIImage(named:"sunrise")! } } }
// // HTTPRequestRepresentable.swift // FlexibleNetworkLayer // // Created by Isa Aliev on 19.02.18. // Copyright © 2018 IA. All rights reserved. // import Foundation enum HTTPMethod: String { case GET case POST case PUT case DELETE } protocol HTTPRequestRepresentable { var path: String { get set } var httpMethod: HTTPMethod { get } var parameters: JSON? { get set } var headerFields: [String: String]? { get set } var bodyString: String? { get set } } extension HTTPRequestRepresentable { func urlRequest() -> URLRequest? { guard var urlComponents = URLComponents(string: self.path) else { return nil } if let parametersJSON = self.parameters { var queryItems = [URLQueryItem]() for (key, value) in parametersJSON { queryItems.append(URLQueryItem(name: key, value: value as? String)) } urlComponents.queryItems = queryItems } guard let url = urlComponents.url else { return nil } var urlRequest = URLRequest(url: url) urlRequest.httpMethod = self.httpMethod.rawValue urlRequest.allHTTPHeaderFields = headerFields if let body = bodyString { urlRequest.httpBody = body.data(using: .utf8) } return urlRequest } }
// RUN: %target-swift-frontend -emit-silgen %s -verify struct S {} class B {} class C: B {} class D: C {} class Opaque<T> { typealias ObnoxiousTuple = (T, (T.Type, (T) -> T)) func inAndOut(x: T) -> T { return x } func inAndOutGeneric<U>(x: T, y: U) -> U { return y } func inAndOutMetatypes(x: T.Type) -> T.Type { return x } func inAndOutFunctions(x: (T) -> T) -> (T) -> T { return x } func inAndOutTuples(x: ObnoxiousTuple) -> ObnoxiousTuple { return x } func variantOptionality(x: T) -> T? { return x } func variantOptionalityMetatypes(x: T.Type) -> T.Type? { return x } func variantOptionalityFunctions(x: (T) -> T) -> ((T) -> T)? { return x } func variantOptionalityTuples(x: ObnoxiousTuple) -> ObnoxiousTuple? { return x } } class StillOpaque<T>: Opaque<T> { override func variantOptionalityTuples(x: ObnoxiousTuple?) -> ObnoxiousTuple { return x! } } class ConcreteValue<X>: Opaque<S> { override func inAndOut(x: S) -> S { return x } override func inAndOutGeneric<Z>(x: S, y: Z) -> Z { return y } override func inAndOutMetatypes(x: S.Type) -> S.Type { return x } override func inAndOutFunctions(x: (S) -> S) -> (S) -> S { return x } override func inAndOutTuples(x: ObnoxiousTuple) -> ObnoxiousTuple { return x } override func variantOptionality(x: S?) -> S { return x! } override func variantOptionalityMetatypes(x: S.Type?) -> S.Type { return x! } override func variantOptionalityFunctions(x: ((S) -> S)?) -> (S) -> S { return x! } override func variantOptionalityTuples(x: ObnoxiousTuple?) -> ObnoxiousTuple { return x! } } class ConcreteClass<X>: Opaque<C> { override func inAndOut(x: C) -> C { return x } override func inAndOutMetatypes(x: C.Type) -> C.Type { return x } override func inAndOutFunctions(x: (C) -> C) -> (C) -> C { return x } override func inAndOutTuples(x: ObnoxiousTuple) -> ObnoxiousTuple { return x } override func variantOptionality(x: C?) -> C { return x! } override func variantOptionalityMetatypes(x: C.Type?) -> C.Type { return x! } override func variantOptionalityFunctions(x: ((C) -> C)?) -> (C) -> C { return x! } override func variantOptionalityTuples(x: ObnoxiousTuple?) -> ObnoxiousTuple { return x! } } class ConcreteClassVariance<X>: Opaque<C> { override func inAndOut(x: B) -> D { return x as! D } override func variantOptionality(x: B?) -> D { return x as! D } } class OpaqueTuple<U>: Opaque<(U, U)> { override func inAndOut(x: (U, U)) -> (U, U) { return x } override func variantOptionality(x: (U, U)?) -> (U, U) { return x! } } class ConcreteTuple<X>: Opaque<(S, S)> { override func inAndOut(x: (S, S)) -> (S, S) { return x } override func variantOptionality(x: (S, S)?) -> (S, S) { return x! } } class OpaqueFunction<U, V>: Opaque<(U) -> V> { override func inAndOut(x: (U) -> V) -> (U) -> V { return x } override func variantOptionality(x: ((U) -> V)?) -> (U) -> V { return x! } } class ConcreteFunction<X>: Opaque<(S) -> S> { override func inAndOut(x: (S) -> S) -> (S) -> S { return x } override func variantOptionality(x: ((S) -> S)?) -> (S) -> S { return x! } } class OpaqueMetatype<U>: Opaque<U.Type> { override func inAndOut(x: U.Type) -> U.Type { return x } override func variantOptionality(x: U.Type?) -> U.Type { return x! } } class ConcreteValueMetatype<X>: Opaque<S.Type> { override func inAndOut(x: S.Type) -> S.Type { return x } override func variantOptionality(x: S.Type?) -> S.Type { return x! } } class ConcreteClassMetatype<X>: Opaque<C.Type> { override func inAndOut(x: C.Type) -> C.Type { return x } override func variantOptionality(x: C.Type?) -> C.Type { return x! } } /* class ConcreteOptional<X>: Opaque<S?> { override func inAndOut(x: S?) -> S? { return x } override func variantOptionality(x: S??) -> S? { return x! } } */
// // Storyboards.swift // BoilerPlate // // Created by Raul Marques de Oliveira on 10/05/18. // Copyright © 2018 Raul Marques de Oliveira. All rights reserved. // import UIKit enum Storyboard: String { case Main func instantiateViewController<T: UIViewController>(WithIdentifier id: String) -> T { let instance = UIStoryboard.init(name: self.rawValue, bundle: Bundle.main) return instance.instantiateViewController(withIdentifier: id) as! T } }