text
stringlengths
8
1.32M
import Foundation import Combine import MatrixClient import NetworkDispatcher final class RoomsViewModel: ObservableObject { private let client = MatrixClient(baseURL: URL(string:"https://matrix.org")!, dispatcher: DefaultDispatcher()) var objectWillChange = PassthroughSubject<RoomsViewModel, Never>() private(set) var rooms = [Room]() { didSet { DispatchQueue.main.async { self.objectWillChange.send(self) } } } init() { getRooms() } func getRooms() { let _ = client.publicRooms().print().sink(receiveCompletion: {_ in }, receiveValue: {print($0)}) } }
// // DashboardContainerViewController.swift // Clique // // Created by Chris Shadek on 4/24/16. // Copyright © 2016 BuckMe. All rights reserved. // class DashboardContainerViewController: UIViewController { @IBOutlet weak var segmentedFilter: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() self.segmentedFilter.tintColor = UIColor.whiteColor() self.navigationController?.navigationBar.backgroundColor = UIColor.blueColor() } }
// // InputItemTableViewController.swift // Closet-Cat // // Created by GirlsWhoCode on 8/5/16. // Copyright © 2016 GirlsWhoCode. All rights reserved. // import UIKit class InputItemTableViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIPickerViewDataSource,UIPickerViewDelegate { @IBOutlet var imageView:UIImageView! @IBOutlet weak var categoryPicker: UIPickerView! override func viewDidLoad() { super.viewDidLoad() categoryPicker.dataSource = self categoryPicker.delegate = self // 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() //lighter pink view.backgroundColor = UIColor(red: 255.0/255.0, green: 251.0/255.0, blue: 251.0/255.0, alpha: 1.0) tableView.backgroundColor = UIColor(red: 255.0/255.0, green: 251.0/255.0, blue: 251.0/255.0, alpha: 1.0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row == 0 { let alertController = UIAlertController(title: "Choose Method", message: "", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Take Photo", style: UIAlertActionStyle.Default) { (action: UIAlertAction) in self.takePic()}) alertController.addAction(UIAlertAction(title: "Choose From Library", style: UIAlertActionStyle.Default) { (action: UIAlertAction) in self.choosePic()}) self.presentViewController(alertController, animated: true, completion: nil) } tableView.deselectRowAtIndexPath(indexPath, animated: true) } func choosePic() { if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.allowsEditing = false imagePicker.sourceType = .PhotoLibrary self.presentViewController(imagePicker, animated: true, completion:nil) } } func takePic() { if UIImagePickerController.isSourceTypeAvailable(.Camera) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.allowsEditing = false imagePicker.sourceType = .Camera self.presentViewController(imagePicker, animated: true, completion:nil) } } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.clipsToBounds = true let leadingConstraint = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: imageView.superview, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0) leadingConstraint.active = true let trailingConstraint = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: imageView.superview, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0) trailingConstraint.active = true let topConstraint = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: imageView.superview, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0) topConstraint.active = true let bottomConstraint = NSLayoutConstraint(item: imageView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: imageView.superview, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0) bottomConstraint.active = true dismissViewControllerAnimated(true, completion: nil) } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { cell.backgroundColor = UIColor.clearColor() } // override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: // NSIndexPath) -> UITableViewCell { // let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) // // cell.backgroundColor = UIColor.clearColor() // // return cell // } // MARK: - Table view data source /* override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } */ /* override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } */ /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ //MARK: - Delegates and data sources //MARK: Data Sources func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return clothingCategories.count } //MARK: Delegates func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return clothingCategories[row] } //func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { // myLabel.text = pickerData[row] func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView { let pickerLabel = UILabel() let titleData = clothingCategories[row] let myTitle = NSAttributedString(string: titleData, attributes: [NSFontAttributeName:UIFont(name: "Raleway-Regular", size: 18.0)!,NSForegroundColorAttributeName:UIColor.blackColor()]) pickerLabel.attributedText = myTitle pickerLabel.textAlignment = .Center return pickerLabel } }
// // Student+CoreDataClass.swift // InternshipManagement // // Created by Nguyen Truong Dai Vi on 6/26/17. // Copyright © 2017 Nguyen Truong Dai Vi. All rights reserved. // import Foundation import CoreData public class Student: NSManagedObject { }
// // YNOrderFormAddressCell.swift // 2015-08-06 // // Created by 农盟 on 15/9/17. // Copyright (c) 2015年 农盟. All rights reserved. //地址cell import UIKit class YNOrderFormAddressCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.selectionStyle = UITableViewCellSelectionStyle.none setupInterface() setupLayout() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupLayout() { //topImageView Layout().addTopConstraint(topImageView, toView: self.contentView, multiplier: 1, constant: 0) Layout().addLeftConstraint(topImageView, toView: self.contentView, multiplier: 1, constant: 0) Layout().addRightConstraint(topImageView, toView: self.contentView, multiplier: 1, constant: 0) Layout().addHeightConstraint(topImageView, toView: nil, multiplier: 0, constant: 2) //userNameLabel Layout().addLeftConstraint(userNameLabel, toView: self.contentView, multiplier: 1, constant: 12) Layout().addTopToBottomConstraint(userNameLabel, toView: topImageView, multiplier: 1, constant: 8) Layout().addWidthConstraint(userNameLabel, toView: nil, multiplier: 0, constant: 50) Layout().addHeightConstraint(userNameLabel, toView: nil, multiplier: 0, constant: 20) //userGenderLabel Layout().addLeftToRightConstraint(userGenderLabel, toView: userNameLabel, multiplier: 1, constant: 0) Layout().addTopBottomConstraints(userGenderLabel, toView: userNameLabel, multiplier: 1, constant: 0) Layout().addWidthConstraint(userGenderLabel, toView: nil, multiplier: 0, constant: 40) //userPhoneNumberLabel Layout().addTopBottomConstraints(userPhoneNumberLabel, toView: userNameLabel, multiplier: 1, constant: 0) Layout().addLeftToRightConstraint(userPhoneNumberLabel, toView: userGenderLabel, multiplier: 1, constant: 30) Layout().addRightConstraint(userPhoneNumberLabel, toView: self.contentView, multiplier: 1, constant: 0) //indicatorImageView Layout().addRightConstraint(indicatorImageView, toView: self.contentView, multiplier: 1, constant: -20) Layout().addWidthConstraint(indicatorImageView, toView: nil, multiplier: 0, constant: 7) Layout().addHeightConstraint(indicatorImageView, toView: nil, multiplier: 0, constant: 12) Layout().addCenterYConstraint(indicatorImageView, toView: self.contentView, multiplier: 1, constant: 0) //userAddressLabel Layout().addLeftConstraint(userAddressLabel, toView: userNameLabel, multiplier: 1, constant: 0) Layout().addRightToLeftConstraint(userAddressLabel, toView: indicatorImageView, multiplier: 1, constant: -12) Layout().addTopToBottomConstraint(userAddressLabel, toView: userNameLabel, multiplier: 1, constant: 0) Layout().addBottomConstraint(userAddressLabel, toView: self.contentView, multiplier: 1, constant: -8) //bottomImageView Layout().addBottomConstraint(bottomImageView, toView: self.contentView, multiplier: 1, constant: 0) Layout().addLeftConstraint(bottomImageView, toView: self.contentView, multiplier: 1, constant: 0) Layout().addRightConstraint(bottomImageView, toView: self.contentView, multiplier: 1, constant: 0) Layout().addHeightConstraint(bottomImageView, toView: nil, multiplier: 0, constant: 2) } func setupInterface() { self.contentView.addSubview(userNameLabel) self.contentView.addSubview(userGenderLabel) self.contentView.addSubview(userPhoneNumberLabel) self.contentView.addSubview(userAddressLabel) self.contentView.addSubview(topImageView) self.contentView.addSubview(bottomImageView) self.contentView.addSubview(indicatorImageView) } fileprivate lazy var userNameLabel: UILabel = { var tempLabel = UILabel() tempLabel.font = UIFont.systemFont(ofSize: 14) tempLabel.textColor = UIColor.black tempLabel.translatesAutoresizingMaskIntoConstraints = false tempLabel.text = "程亚男" return tempLabel }() fileprivate lazy var userGenderLabel: UILabel = { var tempLabel = UILabel() tempLabel.font = UIFont.systemFont(ofSize: 14) tempLabel.textColor = UIColor.black tempLabel.translatesAutoresizingMaskIntoConstraints = false tempLabel.text = "女士" return tempLabel }() fileprivate lazy var userPhoneNumberLabel: UILabel = { var tempLabel = UILabel() tempLabel.font = UIFont.systemFont(ofSize: 14) tempLabel.textColor = UIColor.black tempLabel.translatesAutoresizingMaskIntoConstraints = false tempLabel.text = "18790295312" return tempLabel }() fileprivate lazy var userAddressLabel: UILabel = { var tempLabel = UILabel() tempLabel.font = UIFont.systemFont(ofSize: 14) tempLabel.textColor = UIColor.black tempLabel.translatesAutoresizingMaskIntoConstraints = false tempLabel.text = "古德佳苑7号楼2单元35室" tempLabel.numberOfLines = 2 return tempLabel }() fileprivate lazy var topImageView: UIImageView = { var tempView = UIImageView() tempView.backgroundColor = UIColor(patternImage: UIImage(named: "address_line_bg")!) tempView.translatesAutoresizingMaskIntoConstraints = false return tempView }() fileprivate lazy var bottomImageView: UIImageView = { var tempView = UIImageView() tempView.backgroundColor = UIColor(patternImage: UIImage(named: "address_line_bg")!) tempView.translatesAutoresizingMaskIntoConstraints = false return tempView }() fileprivate lazy var indicatorImageView: UIImageView = { var tempView = UIImageView(image: UIImage(named: "icon_cell_rightArrow")!) tempView.contentMode = UIViewContentMode.scaleAspectFit tempView.translatesAutoresizingMaskIntoConstraints = false return tempView }() }
//: [Previous](@previous) import Foundation enum MLSTeam { case montreal case toronto case newYork case columbus case losAngeles case seattle } let theTeam = MLSTeam.montreal switch theTeam { case .montreal: print("Montreal Impact") case .toronto: print("Toronto FC") case .newYork: print("Newyork Redbulls") case .columbus: print("Columbus Crew") case .losAngeles: print("LA Galaxy") case .seattle: print("Seattle Sounders") } enum Dimension { case us(Double, Double) case metric(Double, Double) } func convert(dimension: Dimension) -> Dimension { switch dimension { case let .us(length, width): return .metric(length * 0.304, width * 0.304) case let .metric(length, width): return .us(length * 3.280, width * 3.280) } } let convertedDimension = convert(dimension: Dimension.metric(5.0, 4.0)) print(convertedDimension) //func convert(dimension: Dimension) -> Dimension { // switch dimension { // case let .us(length, width): // return .metric(length * 0.304, width * 0.304) // default: // return .us(0.0, 0.0) // } //} //: [Next](@next)
// // BaseFormCell.swift // EAO // // Created by Amir Shayegh on 2018-01-08. // Copyright © 2018 FreshWorks. All rights reserved. // import Foundation import UIKit class BaseFormCell: UITableViewCell { func styleContainer(view: CALayer) { roundContainer(view: view) view.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5).cgColor view.shadowOffset = CGSize(width: 0, height: 2) view.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5).cgColor view.shadowOpacity = 1 view.shadowRadius = 4 } func roundContainer(view: CALayer) { view.cornerRadius = 8 } }
// Hacker Rank min max problem var arr = [8,7,2,1,5] var sum: Int = 0 for i in 0...4 { // arr[i] = Int(readLine()!)! sum += arr[i] } var min: Int = arr[0] var max: Int = arr[0] for i in 1...4 { if arr[i] > max { max = arr[i] } else if arr[i] < min { min = arr[i] } } print("\(sum - max) \(sum - min)")
// // StoreManager.swift // 3Dlook // // Created by Тимур Кошевой on 27.08.2020. // Copyright © 2020 homeAssignment. All rights reserved. // import Foundation protocol StoreManagerProtocol: AnyObject { func getTimers() -> TimersModel? func saveTimers(_ timers: TimersModel?) } class StoreManager: StoreManagerProtocol { private let timersKey = "timers" public func saveTimers(_ timers: TimersModel?) { guard let timers = timers else { return } let defaults = UserDefaults.standard defaults.set(try? PropertyListEncoder().encode(timers), forKey: timersKey) } public func getTimers() -> TimersModel? { let defaults = UserDefaults.standard if let timers = defaults.object(forKey: timersKey) as? Data { let timers = try? PropertyListDecoder().decode(TimersModel.self, from: timers) return timers } else { return nil } } }
// // Request.swift // AllPeople // // Created by zzh_iPhone on 16/4/25. // Copyright © 2016年 zzh_iPhone. All rights reserved. // import Foundation import Kingfisher import Alamofire class request { init(){ } class func defaultInstance() -> request { struct statics { static let instance = request() } return statics.instance } func GetRequest(url:String)-> Request { return Alamofire.request(.GET, url) } func PostRequest(url:String)-> Request { return Alamofire.request(.POST, url) } }
// // StockAPIClient.swift // PeopleAndAppleStockPrices // // Created by Oniel Rosario on 12/12/18. // Copyright © 2018 Pursuit. All rights reserved. // import UIKit final class StockAPI { static func getStockImage(url: String) -> UIImage? { guard let imageURL = URL.init(string: url) else { return nil} guard let data = try? Data.init(contentsOf: imageURL) else {return nil} let image = UIImage.init(data: data) return image } }
// ContentView.swift // MyVIAlarm // // Created by Joel Schow import SwiftUI import CoreData import AVFoundation enum page { case mainPage case alarmPage } enum editAlarmState { case editHour case editMinute case editAMPM case confirm case off } struct ContentView: View { @StateObject var delegate = NotificationDelegate() @Environment(\.managedObjectContext) var moc @FetchRequest(entity: Alarm.entity(), sortDescriptors: []) var alarms : FetchedResults<Alarm> @State private var myAlarm : Alarm? @State private var currentPage : page = .mainPage @State private var currentEditAlarmState : editAlarmState = .off @State private var backgroundColor = CGColor(red: 84/225, green: 131/225, blue: 151/225, alpha: 1) @State private var darkBackground = CGColor(red: 22/225, green: 22/225, blue: 24/225, alpha: 1) @State private var lightBackground = CGColor(red: 129/225, green: 129/225, blue: 129/225, alpha: 1) @State private var darkText = CGColor(red: 0/225, green: 0/225, blue: 0/225, alpha: 1) @State private var editHourValue : Int? @State private var editMinuteValue : Int? @State private var editAMPMValue : Int? //1 for AM, 2 for PM @State private var syn = AVSpeechSynthesizer() var body: some View { ZStack{ Color(.white) .onAppear(perform: { print("MyVIAlarm has started") UNUserNotificationCenter.current().delegate = delegate getAppData() getPermissions() correctCurrentAlarmDate() dictateInitialInstructions() }) .gesture( DragGesture(minimumDistance: 3.0, coordinateSpace: .local) .onChanged{ value in } .onEnded { value in if currentPage == .mainPage { if value.translation.width < -(UIScreen.screenWidth / 2) && value.translation.height > -50 && value.translation.height < 50 { print("left swipe") print("Entering alarmPage") handleStartAlarmEditing() } else if value.translation.height < 0 && value.translation.width < 100 && value.translation.width > -100 { print("up swipe") handleAlarmToggle() dictateAlarmToggleStatus() } else if value.translation.height > 0 && value.translation.width < 100 && value.translation.width > -100 { print("down swipe") createDemoAlarm() } else { print("non-conclusive swipe") } } else { if value.translation.width > (UIScreen.screenWidth / 2) && value.translation.height > -50 && value.translation.height < 50 { print("right swipe") print("Entering mainPage") currentPage = .mainPage dictateCancelEnteringMainPage() } else if value.translation.height < 0 && value.translation.width < 100 && value.translation.width > -100 { print("up swipe") if currentEditAlarmState == .editHour { if editHourValue! >= 12 { editHourValue! = 1 } else { editHourValue! += 1 } dictateEditHourUpdate() } else if currentEditAlarmState == .editMinute { if editMinuteValue! >= 45 { editMinuteValue! = 00 } else { editMinuteValue! += 15 } dictateEditMinuteUpdate() } else if currentEditAlarmState == .editAMPM { editAMPMValue = 1 dictateEditAMPMUpdate() } } else if value.translation.height > 0 && value.translation.width < 100 && value.translation.width > -100 { print("down swipe") if currentEditAlarmState == .editHour { if editHourValue! <= 1 { editHourValue! = 12 } else { editHourValue! -= 1 } dictateEditHourUpdate() } else if currentEditAlarmState == .editMinute { if editMinuteValue! <= 00 { editMinuteValue! = 45 } else { editMinuteValue! -= 15 } dictateEditMinuteUpdate() } else if currentEditAlarmState == .editAMPM { editAMPMValue = 2 dictateEditAMPMUpdate() } } else { print("non-conclusive swipe") } } } ) .onTapGesture(count: 2, perform: { print("double tap") if currentPage == .mainPage { dictateTimeAndAlarmDetails() } else { switch currentEditAlarmState { case .editHour: print("confirmed in edit alarm state for edit hour with value \(editHourValue!)") currentEditAlarmState = .editMinute dictateEditMinuteInstructions() case .editMinute: print("confirmed double tap in edit alarm state for edit minute with value \(editMinuteValue!)") currentEditAlarmState = .editAMPM dictateEditAMPMInstructions() case .editAMPM: print("confirmed double tap in edit alarm state for edit AMPM with value \(editAMPMValue!)") currentEditAlarmState = .confirm dictateEditAlarmConfirmInstructions() case .confirm: print("FINAL ALARM CONFIRMED") saveAlarmValues() dictateEditAlarmConfirmUpdate() turnAlarmOn() currentPage = .mainPage currentEditAlarmState = .off default: print("double tap in edit alarm state for default") } } }) .onTapGesture(count: 1, perform: { print("single tap") if currentPage == .mainPage { dictateMainPageInstructions() } else { switch currentEditAlarmState { case .editHour: dictateEditHourInstructionsTap() case .editMinute: dictateEditMinuteInstructionsTap() case .editAMPM: dictateEditAMPMInstructionsTap() case .confirm: dictateEditConfirmInstructionsTap() default: print("deault entered in single tap gesture") } } }) VStack { Text("MyVIAlarm") .font(.system(size: 20, weight: .semibold, design: .rounded)) Text("Joel Schow") .font(.system(size: 16, weight: .light, design: .rounded)) } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(Color(#colorLiteral(red: 0.8135031795, green: 0.8715417949, blue: 0.9930160315, alpha: 1))) .edgesIgnoringSafeArea(.all) .allowsHitTesting(false) } } //Helper Functions func getAppData(){ print("Begin getting app data") if alarms.count == 0 { print("Making new alarm data") let newAlarm = Alarm(context: self.moc) let date = Date() let newDateComponents = DateComponents( calendar: Calendar.current, timeZone: TimeZone.current, era: Calendar.current.component(.era, from: date), year: Calendar.current.component(.year, from: date), month: Calendar.current.component(.month, from: date), day: Calendar.current.component(.day, from: date), hour: 00, minute: 00, second: 00, nanosecond: 00, weekday: Calendar.current.component(.weekday, from: date), weekdayOrdinal: Calendar.current.component(.weekdayOrdinal, from: date), quarter: Calendar.current.component(.quarter, from: date), weekOfMonth: Calendar.current.component(.weekOfMonth, from: date), weekOfYear: Calendar.current.component(.weekOfYear, from: date), yearForWeekOfYear: Calendar.current.component(.yearForWeekOfYear, from: date)) let newAlarmTime = Calendar.current.date(from: newDateComponents) ?? Date() let newAlarmStatus = false print("alarm description: \(getDateText(date: newAlarmTime))") newAlarm.time = newAlarmTime newAlarm.status = newAlarmStatus try? self.moc.save() } print("Loading existing alarm data") myAlarm = alarms[0] getEditValues() } func getEditValues(){ let tempHourValue = Calendar.current.component(.hour, from: myAlarm?.time ?? Date()) if tempHourValue >= 12 { editAMPMValue = 2 if tempHourValue == 12 { editHourValue = 12 } else { editHourValue = tempHourValue - 12 } } else { editAMPMValue = 1 if tempHourValue == 00 { editHourValue = 12 } else { editHourValue = tempHourValue } } editMinuteValue = Calendar.current.component(.minute, from: myAlarm?.time ?? Date()) } func handleStartAlarmEditing(){ currentPage = .alarmPage currentEditAlarmState = .editHour getEditValues() dictateEditHourInstructions() } func handleAlarmToggle(){ if myAlarm!.status == true { turnAlarmOff() } else { turnAlarmOn() } } func turnAlarmOn(){ correctCurrentAlarmDate() myAlarm!.status = true try? self.moc.save() deleteAlarmNotification() createAlarmNotification() } func turnAlarmOff(){ myAlarm!.status = false try? self.moc.save() deleteAlarmNotification() } func saveAlarmValues(){ print("Alarm values before save are \(getDateText(date: myAlarm!.time!))") print("Saving Alarm values of Hour : \(editHourValue!), Minute : \(editMinuteValue!), AMPM : \(editAMPMValue!)") myAlarm!.time = Date() myAlarm!.time = Calendar.current.date(bySetting: .hour, value: convertToMillitaryTime(hourValue: editHourValue!, AmPm: editAMPMValue!), of: myAlarm!.time!) myAlarm!.time = Calendar.current.date(bySetting: .minute, value: editMinuteValue!, of: myAlarm!.time!) try? self.moc.save() print("Alarm values after save are \(getDateText(date: myAlarm!.time!))") } func convertToMillitaryTime(hourValue : Int, AmPm : Int) -> Int{ if hourValue == 12 { if AmPm == 1{ return 00 } else { return 12 } } return AmPm == 1 ? hourValue : hourValue + 12 } func createAlarmNotification(){ let content = UNMutableNotificationContent() content.title = "Alarm Going Off!" content.subtitle = "Alarm Set For \(getDateText(date: myAlarm?.time ?? Date()))" content.sound = UNNotificationSound.default let trigger = UNCalendarNotificationTrigger(dateMatching: Calendar.current.dateComponents([.hour,.minute,.second,], from: myAlarm!.time!), repeats: true) let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) } func createDemoAlarm(){ let content = UNMutableNotificationContent() content.title = "Alarm Going Off!" content.subtitle = "Alarm Set For \(getDateText(date: myAlarm?.time ?? Date()))" content.sound = UNNotificationSound.default let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) } func deleteAlarmNotification(){ UNUserNotificationCenter.current().removeAllDeliveredNotifications() UNUserNotificationCenter.current().removeAllPendingNotificationRequests() } func correctCurrentAlarmDate(){ print("Begin correcting current alarm date, current date is \(getDateText(date: myAlarm!.time!))") let alarmDay = Calendar.current.component(.day, from: (myAlarm?.time!)!) let currentDay = Calendar.current.component(.day, from: Date()) if myAlarm!.time! < Date() || ((alarmDay != currentDay) && (alarmDay != currentDay + 1)){ print("**ALARM TIME BEFORE CURRENT DATE**") myAlarm!.time = Calendar.current.date(bySetting: .year, value: Calendar.current.component(.year, from: Date()), of: myAlarm!.time!) myAlarm!.time = Calendar.current.date(bySetting: .month, value: Calendar.current.component(.month, from: Date()), of: myAlarm!.time!) myAlarm!.time = Calendar.current.date(bySetting: .day, value: Calendar.current.component(.day, from: Date()), of: myAlarm!.time!) if myAlarm!.time! < Date(){ print("******INCREMENTING DATE*********") myAlarm!.time = Calendar.current.date(byAdding: .day, value: 1, to: myAlarm!.time!) } try? self.moc.save() } print("Done correcting current alarm date, now the date is \(getDateText(date: myAlarm!.time!))") } func getPermissions(){ UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in if success { print("Permissions accepted") } else if let error = error { print(error.localizedDescription) } } } func getDateText(date : Date = Date())->String{ let time = date let timeFormatter = DateFormatter() timeFormatter.dateFormat = "MMMM dd yyyy, hh:mm a" let stringDate = timeFormatter.string(from: time) return stringDate } func getTimeText(date : Date = Date(), _ noAM : Bool = false)->String{ let time = date let timeFormatter = DateFormatter() if noAM == false { timeFormatter.dateFormat = "hh:mm a" } else { timeFormatter.dateFormat = "hh:mm" } let timeDate = timeFormatter.string(from: time) return timeDate } func getEditingDate()->Date{ var date = Date() date = Calendar.current.date(bySetting: .hour, value: editHourValue!, of: date)! date = Calendar.current.date(bySetting: .minute, value: editMinuteValue!, of: date)! return date } //Dictating Fuctions func dictateString(_ s : String, _ delay : Double = 0){ syn.stopSpeaking(at: .immediate) let toSpeak = AVSpeechUtterance(string: s) toSpeak.voice = AVSpeechSynthesisVoice(language: "en-GB") toSpeak.preUtteranceDelay = delay syn.speak(toSpeak) } func dictateInitialInstructions(){ dictateString("My VR alarm, tap the screen with one finger to hear instructions.") } func dictateMainPageInstructions(){ dictateString("Instructions. Double tap the screen with one finger for time and alarm details. Swipe up with one finger to toggle alarm on or off. Full screen swipe left to edit alarm settings. Tap the screen with one finger to hear instructions again.") } func dictateTimeAndAlarmDetails(){ print("Begin dictating alarm details") correctCurrentAlarmDate() print("Current date and time is \(getDateText()). Alarm status is : ", myAlarm?.status ?? false, ", Alarm time is : ", getDateText(date: myAlarm?.time ?? Date())) dictateString("Current date and time is \(getDateText()). Alarm is \(myAlarm!.status ? "On" : "Off"), set for \(getTimeText(date: myAlarm!.time!))") } func dictateAlarmToggleStatus(){ print("Begin dictating alarm toggle status") correctCurrentAlarmDate() print("Alarm status is : ", myAlarm?.status ?? false) dictateString("Alarm is now \(myAlarm!.status ? " On and set for \(getTimeText(date: myAlarm!.time!))" : "Off")") } func dictateEditHourInstructions(){ print("Begin dictating edit hour instructions") dictateString("Editing alarm. Edit hour, \(editHourValue!) O'clock, adjustable. Swipe up or down with one finger to adjust the value, double tap to confirm.") } func dictateEditHourInstructionsTap(){ dictateString("Edit hour, \(editHourValue!) O'clock, adjustable. Swipe up or down with one finger to adjust the value, double tap to confirm. Full screen swipe right to cancel editing.") } func dictateEditHourUpdate(){ print("Begin dictating edit hour update") dictateString("\(editHourValue!) O'clock") } func dictateEditMinuteInstructions(){ print("Begin dictating edit minute instructions") dictateString("\(editHourValue!) O'clock confirmed. Edit minute, \(getTimeText(date: getEditingDate(), true)), adjustable. Swipe up or down with one finger to adjust the value by 15 minutes, double tap to confirm.") } func dictateEditMinuteInstructionsTap(){ dictateString("Edit minute, \(getTimeText(date: getEditingDate(), true)), adjustable. Swipe up or down with one finger to adjust the value by 15 minutes, double tap to confirm. Full screen swipe right to cancel editing.") } func dictateEditMinuteUpdate(){ print("Begin dictating edit minute update") dictateString("\(getTimeText(date: getEditingDate(), true))") } func dictateEditAMPMInstructions(){ print("Begin dictating edit AMPM instructions") dictateString("\(getTimeText(date: getEditingDate(), true)) confirmed. Choose AM or PM. Swipe up to select AM, or swipe down to select PM.") } func dictateEditAMPMInstructionsTap(){ dictateString("Choose AM or PM. Swipe up to select AM, or swipe down to select PM. Double tap to confirm. Full screen swipe right to cancel editing.") } func dictateEditAMPMUpdate(){ print("Begin dictating edit AMPM update") dictateString("\(editAMPMValue == 1 ? "AM" : "PM") selected. Double tap to confirm.") } func dictateEditAlarmConfirmInstructions(){ print("Begin Final Confirmation") dictateString("\(editAMPMValue == 1 ? "AM" : "PM") confirmed. Alarm set for \(getTimeText(date: getEditingDate(), true)) \(editAMPMValue == 1 ? "AM" : "PM"). Double tap to confirm. Or full screen swipe right to cancel editing.") } func dictateEditConfirmInstructionsTap(){ dictateString("Alarm set for \(getTimeText(date: getEditingDate(), true)) \(editAMPMValue == 1 ? "AM" : "PM"). Double tap to confirm. Or full screen swipe right to cancel editing.") } func dictateEditAlarmConfirmUpdate(){ print("Final Confirmation Selected") dictateString("Alarm for \(getTimeText(date: myAlarm!.time!, false)) confirmed and turned on. Returning to main page.") } func dictateCancelEnteringMainPage(){ print("Canceling and entering main page") dictateString("Edit canceled, returning to main page.") } } class NotificationDelegate : NSObject, ObservableObject, UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.badge, .banner, .sound]) } } extension UIScreen{ static let screenWidth = UIScreen.main.bounds.size.width static let screenHeight = UIScreen.main.bounds.size.height static let screenSize = UIScreen.main.bounds.size }
// // UIColor+Extensions.swift // FriendTab // // Created by Dylan Elliott on 11/7/18. // Copyright © 2018 Dylan Elliott. All rights reserved. // import UIKit extension UIColor { enum Moocher { static let yellow = UIColor(hex: "#FFCC00")! // yellow static let green = UIColor(hex: "#4CD964")! // green static let red = UIColor(hex: "#FF3B30")! // red } }
import Foundation class CreateAwardRepository: CreateAwardRepositoryProtocol { let database: ManagedObjectProviding init(provider: CreateAwardRepositoryDependencyProviding) { database = provider.provideDatabase() } func createAward(action: String, value: Int64) throws { let awardModel: AwardModel = try database.newManagedObject("AwardModel") awardModel.uuid = UUID() awardModel.action = action awardModel.value = value let contest: Contest? = try database.fetchAll("Contest").first contest?.awardModels?.insert(awardModel) try? database.saveChanges() } }
// // Product.swift // DakkenApp // // Created by Sayed Abdo on 10/20/18. // Copyright © 2018 sayedAbdo. All rights reserved. // import Foundation class Product{ var id : Int var category : Int var trader_id : Int var title : String var price : Double var desc : String var image : String var qty : Int var productnum : String var size : String var color : String var suspensed : Int var created_at : String init(id : Int , category : Int ,trader_id : Int ,title : String ,price : Double ,desc : String , image : String , qty : Int ,productnum : String ,size : String ,color : String , suspensed : Int , created_at : String ){ self.id = id self.category = category self.trader_id = trader_id self.title = title self.price = price self.desc = desc self.image = image self.qty = qty self.productnum = productnum self.size = size self.color = color self.suspensed = suspensed self.created_at = created_at } }
// 资源管理器 // CTResourceManager.swift // KidForIPad // // Created by guominglong on 2017/1/1. // Copyright © 2017年 KidForMac. All rights reserved. // import Foundation class CTResourceManager: NSObject { var resourceMap:[String:CTResource]; static var instance:CTResourceManager{ get{ struct CTResourceManagerStr{ static let _ins:CTResourceManager = CTResourceManager(); } return CTResourceManagerStr._ins } } override init() { resourceMap = [String:CTResource](); super.init(); } /** 创建资源 resourceName 资源名称 res 资源 isLocked 是否强引用 默认为不强引用 */ func addResourceByName(_ resourceName:String,res:Any,isLocked:Bool = false){ let r = CTResource(); r.resName = resourceName; r.res = res; r.isLocked = isLocked; resourceMap[resourceName] = r; } /** 根据资源名称,返回资源 resourceName 资源名称 */ func getResourceByName(_ resourceName:String)->CTResource?{ if resourceMap.keys.contains(resourceName){ return resourceMap[resourceName]; }else{ return nil; } } /** 根据资源名称,删除资源 */ func deleteResourceByName(_ resourceName:String){ if resourceMap.keys.contains(resourceName){ let ir = resourceMap.removeValue(forKey: resourceName)! as CTResource; ir.res = nil; } } /** 删除所有资源 */ func deleteAllResource(){ let arr = resourceMap.keys; for str in arr{ resourceMap[str]?.res = nil; } resourceMap.removeAll(); } /** 删除所有没加锁的资源 */ func deleteUnLockImg(){ let arr = resourceMap.keys; for str in arr{ if let ir = resourceMap[str]{ if ir.isLocked == false{ resourceMap[str]?.res = nil; resourceMap.removeValue(forKey: str); } } } } } /** 通用资源类型 */ class CTResource: NSObject { private var _isLocked:Bool = false; /** 资源的锁定状态 */ var isLocked:Bool{ get{ return _isLocked; } set{ _isLocked = newValue; if _isLocked == false{ //如果这个值被设置为false,则从资源管理器中删除self CTResourceManager.instance.deleteResourceByName(self.resName); } } } /** 资源 */ var res:Any?; /** 资源名称 */ var resName:String = ""; }
// // GMSPolygon.swift // // Created by Raul on 4/21/15. // Copyright (c) 2015 rauluranga. All rights reserved. // import Darwin class GMSCirclePolygon: GMSPolygon { init(radius:Int, position:CLLocationCoordinate2D, detail:Int) { super.init() self.path = drawCirclePath(position, radius: radius, detail: detail) } convenience init (radius:Int, position:CLLocationCoordinate2D) { self.init(radius: radius, position: position, detail: 8) } private func drawCirclePath(point:CLLocationCoordinate2D, radius:Int, detail:Int) -> GMSMutablePath { let R = 6371009.0; // earh radius in meters let pi = M_PI; let Lat = (point.latitude * pi) / 180; let Lng = (point.longitude * pi) / 180; let d = Double(radius) / R; let path = GMSMutablePath() for(var i = 0; i <= 360; i += detail) { var brng = Double(i) * pi / 180.0; var pLat = asin(sin(Lat)*cos(d) + cos(Lat)*sin(d)*cos(brng)); var pLng = ((Lng + atan2(sin(brng)*sin(d)*cos(Lat), cos(d)-sin(Lat)*sin(pLat))) * 180) / pi; pLat = (pLat * 180.0)/pi; path.addCoordinate(CLLocationCoordinate2DMake(pLat, pLng)) } return path } }
// // UseCasesFactory.instance.analyticManagerswift // WavesWallet-iOS // // Created by Pavel Gubin on 3/22/19. // Copyright © 2019 Waves Platform. All rights reserved. // import Foundation import DomainLayer import Amplitude_iOS import FirebaseAnalytics import AppsFlyerLib import WavesSDKCrypto private struct Constants { static let AUUIDKey: String = "AUUID" } public final class AnalyticManager: AnalyticManagerProtocol { private var auuid: String? = nil public func setAUUID(_ AUUID: String) { self.auuid = AUUID } public func trackEvent(_ event: AnalyticManagerEvent) { var params = event.params if let auuid = auuid { params[Constants.AUUIDKey] = auuid } Amplitude.instance().logEvent(event.name, withEventProperties: params) Analytics.logEvent(event.name.replacingOccurrences(of: " ", with: "_"), parameters: params) AppsFlyerTracker.shared()?.trackEvent(event.name, withValues: params) } }
// // Items.swift // To do list app // // Created by Arturs Vitins on 18/02/2018. // Copyright © 2018 Arturs Vitins. All rights reserved. // import Foundation import RealmSwift class Items: Object { @objc dynamic var title: String = "" @objc dynamic var done: Bool = false @objc dynamic var dateCreated: Date? var parentCategory = LinkingObjects(fromType: Category.self, property: "item") }
print("What is the input string? ", separator: "", terminator: "") let input = readLine()! print("\(input) has \(input.characters.count) characters.")
// // CurrentLocationWeatherViewModel.swift // Weather App v2.0 // // Created by Ilya Senchukov on 17.03.2021. // import SwiftUI import Combine import CoreLocation class CurrentLocationWeatherViewModel: NSObject, ObservableObject { @Published var localWeather: WeatherModel? private var currentLocation: CLLocation? { didSet { fetchWeather() } } private let locationManager = CLLocationManager() private let weatherService: WeatherService private var cancellable = Set<AnyCancellable>() init(weatherService: WeatherService = WeatherManager()) { self.weatherService = weatherService super.init() setupLocation() fetchWeather() } } private extension CurrentLocationWeatherViewModel { func fetchWeather() { if let location = currentLocation { weatherService.loadCurrentWeather(coords: location.coordinate) .receive(on: RunLoop.main) .sink { status in switch status { case .failure(let error): print(error) case .finished: break } } receiveValue: { city in self.localWeather = city } .store(in: &cancellable) } } func setupLocation() { if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyKilometer locationManager.requestWhenInUseAuthorization() locationManager.requestLocation() } } } extension CurrentLocationWeatherViewModel: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.first { self.currentLocation = location } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Failed to find user's location: \(error.localizedDescription)") } }
/* Copyright Airship and Contributors */ import XCTest @testable import AirshipPreferenceCenter import AirshipCore class PreferenceCenterTest: XCTestCase { private var dataStore: PreferenceDataStore! private var privacyManager: PrivacyManager! private var preferenceCenter: PreferenceCenter! private var remoteDataProvider: MockRemoteDataProvider! override func setUp() { self.remoteDataProvider = MockRemoteDataProvider() self.dataStore = PreferenceDataStore(appKey: UUID().uuidString) self.privacyManager = PrivacyManager(dataStore: self.dataStore, defaultEnabledFeatures: .all) self.preferenceCenter = PreferenceCenter(dataStore: self.dataStore, privacyManager: self.privacyManager, remoteDataProvider: self.remoteDataProvider) } func testConfig() throws { let payloadData = """ { "preference_forms":[ { "created":"2017-10-10T12:13:14.023", "last_updated":"2017-10-10T12:13:14.023", "form_id":"031de218-9fff-44d4-b348-de4b724bb924", "form":{ "id":"form-1", "sections":[] } }, { "created":"2018-10-10T12:13:14.023", "last_updated":"2018-10-10T12:13:14.023", "form_id":"031de218-9fff-44d4-b348-de4b724bb931", "form":{ "id":"form-2", "sections":[] } } ] } """ let remoteData = createPayload(payloadData) let form1Expectation = XCTestExpectation(description: "form-1") self.preferenceCenter.config(preferenceCenterID: "form-1") { config in XCTAssertNotNil(config) XCTAssertEqual("form-1", config?.identifier) form1Expectation.fulfill() } let form2Expectation = XCTestExpectation(description: "form-2") self.preferenceCenter.config(preferenceCenterID: "form-2") { config in XCTAssertNotNil(config) XCTAssertEqual("form-2", config?.identifier) form2Expectation.fulfill() } let missingFormExpectation = XCTestExpectation(description: "missing") self.preferenceCenter.config(preferenceCenterID: "missing") { config in XCTAssertNil(config) missingFormExpectation.fulfill() } self.remoteDataProvider.dispatchPayload(remoteData) self.wait(for: [form1Expectation, form2Expectation, missingFormExpectation], timeout: 5) } func testJSONConfig() throws { let payloadData = """ { "preference_forms":[ { "created":"2017-10-10T12:13:14.023", "last_updated":"2017-10-10T12:13:14.023", "form_id":"031de218-9fff-44d4-b348-de4b724bb924", "form":{ "id":"form-1" } }, { "created":"2018-10-10T12:13:14.023", "last_updated":"2018-10-10T12:13:14.023", "form_id":"031de218-9fff-44d4-b348-de4b724bb931", "form":{ "id":"form-2" } } ] } """ let remoteData = createPayload(payloadData) var expectedConfig: [String : Any] = [:] expectedConfig.updateValue("form-1", forKey: "id") let form1Expectation = XCTestExpectation(description: "form-1") self.preferenceCenter.jsonConfig(preferenceCenterID: "form-1") { config in XCTAssertNotNil(config) XCTAssertTrue(NSDictionary(dictionary: config).isEqual(to: expectedConfig)) form1Expectation.fulfill() } var expectedConfig2: [String : Any] = [:] expectedConfig2.updateValue("form-2", forKey: "id") let form2Expectation = XCTestExpectation(description: "form-2") self.preferenceCenter.jsonConfig(preferenceCenterID: "form-2") { config in XCTAssertNotNil(config) XCTAssertTrue(NSDictionary(dictionary: config).isEqual(to: expectedConfig2)) form2Expectation.fulfill() } self.remoteDataProvider.dispatchPayload(remoteData) self.wait(for: [form1Expectation, form2Expectation], timeout: 5) } func testOpenDelegate() { let delegate = MockPreferenceCenterOpenDelegate() self.preferenceCenter.openDelegate = delegate self.preferenceCenter.open("some-form") XCTAssertEqual("some-form", delegate.lastOpenId) } func testDeepLink() { let delegate = MockPreferenceCenterOpenDelegate() self.preferenceCenter.openDelegate = delegate let valid = URL(string: "uairship://preferences/some-id")! XCTAssertTrue(self.preferenceCenter.deepLink(valid)) XCTAssertEqual("some-id", delegate.lastOpenId) let trailingSlash = URL(string: "uairship://preferences/some-other-id/")! XCTAssertTrue(self.preferenceCenter.deepLink(trailingSlash)) XCTAssertEqual("some-other-id", delegate.lastOpenId) } func testDeepLinkInvalid() { let delegate = MockPreferenceCenterOpenDelegate() self.preferenceCenter.openDelegate = delegate let wrongScheme = URL(string: "whatever://preferences/some-id")! XCTAssertFalse(self.preferenceCenter.deepLink(wrongScheme)) let wrongHost = URL(string: "uairship://message_center/some-id")! XCTAssertFalse(self.preferenceCenter.deepLink(wrongHost)) let tooManyArgs = URL(string: "uairship://preferences/some-other-id/what")! XCTAssertFalse(self.preferenceCenter.deepLink(tooManyArgs)) } private func createPayload(_ json: String) -> RemoteDataPayload { let data = try! JSONSerialization.jsonObject(with: json.data(using: .utf8)!, options: []) as! [AnyHashable : Any] return RemoteDataPayload(type: "preference_forms", timestamp: Date(), data: data, metadata: [:]) } }
// // DiscoverViewController.swift // Hookah // // Created by Bogdan Kostyuchenko on 13/03/2018. // Copyright © 2018 Bogdan Kostyuchenko. All rights reserved. // import UIKit class DiscoverViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var displayCollection: DiscoverDisplayCollection! override func viewDidLoad() { super.viewDidLoad() navigationController?.makeTransparentNavigationBar(false) displayCollection = DiscoverDisplayCollection() displayCollection.delegate = self tableView.registerNibs(from: displayCollection) } } extension DiscoverViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return displayCollection.numberOfSections } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return displayCollection.numberOfRows(in: section) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let model = displayCollection.model(for: indexPath) let cell = tableView.dequeueReusableCell(for: indexPath, with: model) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) displayCollection.didSelect(indexPath: indexPath) } }
import XCTest import PasswordTests var tests = [XCTestCaseEntry]() tests += PasswordTests.allTests() XCTMain(tests)
// // Keyboard Adjustments.swift // MemeMe // // Created by TJ on 11/28/18. // Copyright © 2018 TJ. All rights reserved. // import UIKit extension ImageViewController { // MARK: Subscribe/Unsubscribe to Keyboard Notifications override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) subscribeToKeyboardWillShowNotifications() subscribeToKeyboardWillHideNotifications() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) unsubscribeFromKeyboardWillShowNotifications() unsubscribeFromKeyboardWillHideShowNotifications() } func subscribeToKeyboardWillShowNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) } func unsubscribeFromKeyboardWillShowNotifications() { NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) } // MARK: How to shift the view's frame UP when the keyboardWillShow notification is received @objc func keyboardWillShow(_ notification:Notification) { view.frame.origin.y -= getKeyboardHeight(notification) } func getKeyboardHeight(_ notification:Notification) -> CGFloat { let userInfo = notification.userInfo let keyboardSize = userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue // of CGRect let keyboardHeight = keyboardSize.cgRectValue.height return keyboardHeight } // MARK: func subscribeToKeyboardWillHideNotifications () { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) } func unsubscribeFromKeyboardWillHideShowNotifications() { NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) } // MARK: How to shift the view's frame DOWN when the keyboardWillHide notification is received @objc func keyboardWillHide(_ notification: Notification) { view.frame.origin.y += getKeyboardHeight(notification) } }
// // FullScreenPagingCollectionViewCell.swift // PagingTableView // // Created by Brent Raines on 9/7/16. // Copyright © 2016 Brent Raines. All rights reserved. // import UIKit class FullScreenPagingCollectionViewCell: UICollectionViewCell { var image: UIImage? { didSet { imageView.image = image } } private let imageView = UIImageView() private func cellOffset() -> CGFloat { let collectionView = self.superview as? FullScreenPagingCollectionView let flowLayout = collectionView?.collectionViewLayout as? FullScreenPagingCollectionViewFlowLayout return flowLayout?.cellOffset ?? 0 } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override func prepareForReuse() { super.prepareForReuse() image = nil } func setup() { clipsToBounds = false contentMode = .redraw addSubview(imageView) imageView.contentMode = .scaleAspectFill imageView.translatesAutoresizingMaskIntoConstraints = false imageView.topAnchor.constraint(equalTo: topAnchor).isActive = true imageView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true imageView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true imageView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true imageView.backgroundColor = UIColor.white } override func draw(_ rect: CGRect) { let maskPath = UIBezierPath() maskPath.move(to: CGPoint(x: rect.origin.x, y: rect.origin.y)) maskPath.addLine(to: CGPoint(x: rect.origin.x + rect.size.width, y: rect.origin.y + cellOffset())) maskPath.addLine(to: CGPoint(x: rect.origin.x + rect.size.width, y: rect.origin.y + rect.size.height)) maskPath.addLine(to: CGPoint(x: rect.origin.x, y: rect.origin.y + rect.size.height - cellOffset())) maskPath.close() let maskLayer = CAShapeLayer() maskLayer.path = maskPath.cgPath layer.mask = maskLayer } }
// // ContinentTableViewRoute.swift // CaptainDemo // // Created by Vincent Esche on 5/28/18. // Copyright © 2018 Vincent Esche. All rights reserved. // import UIKit import Captain enum ContinentTableViewRoute { enum CountryOrId { case id(Int64) case object(Country) } case country(country: CountryOrId) enum Error: Swift.Error { case invalid } } extension ContinentTableViewRoute: AnyNavigationRoute { var tail: AnyNavigationRoute? { return nil } } extension ContinentTableViewRoute: NavigationRoute { typealias Navigator = ContinentTableViewNavigator }
// // TweetCell.swift // Twitter // // Created by Rohit Jhangiani on 5/21/15. // Copyright (c) 2015 5TECH. All rights reserved. // import UIKit @objc protocol TweetCellDelegate { optional func tweetCell(tweetCell: TweetCell, didChangeFavoriteStatus status: Bool) optional func tweetCell(tweetCell: TweetCell, didChangeRetweetStatus status: Bool) optional func tweetCell(tweetCell: TweetCell, didTapReplyTweetId tweetId: String, fromUser: String) } class TweetCell: UITableViewCell { // outlets @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var handleLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var tweetTextLabel: UILabel! @IBOutlet weak var replyButton: UIButton! @IBOutlet weak var retweetButton: UIButton! @IBOutlet weak var retweetLabel: UILabel! @IBOutlet weak var favoriteButton: UIButton! @IBOutlet weak var favoriteLabel: UILabel! // variables var tweet: Tweet? // delegates weak var delegate: TweetCellDelegate? override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = UITableViewCellSelectionStyle.None nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width handleLabel.preferredMaxLayoutWidth = handleLabel.frame.size.width tweetTextLabel.preferredMaxLayoutWidth = tweetTextLabel.frame.size.width retweetLabel.preferredMaxLayoutWidth = retweetLabel.frame.size.width favoriteLabel.preferredMaxLayoutWidth = favoriteLabel.frame.size.width } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } override func layoutSubviews() { super.layoutSubviews() nameLabel.preferredMaxLayoutWidth = nameLabel.frame.size.width handleLabel.preferredMaxLayoutWidth = handleLabel.frame.size.width tweetTextLabel.preferredMaxLayoutWidth = tweetTextLabel.frame.size.width retweetLabel.preferredMaxLayoutWidth = retweetLabel.frame.size.width favoriteLabel.preferredMaxLayoutWidth = favoriteLabel.frame.size.width } @IBAction func onReply(sender: AnyObject) { self.delegate?.tweetCell!(self, didTapReplyTweetId: self.tweet!.id!, fromUser: self.tweet!.user!.screenname!) } @IBAction func onRetweet(sender: AnyObject) { if !tweet!.isRetweeted! { retweetButton.setImage(UIImage(named: "retweetOn"), forState: UIControlState.Normal) var params: NSDictionary = ["id": tweet!.id!] TwitterClient.sharedInstance.retweet(tweet!.id!, completion: { (tweet, error) -> () in if tweet != nil { self.retweetLabel.text = "\(++self.tweet!.numRetweets!)" self.delegate?.tweetCell!(self, didChangeRetweetStatus: true) return } }) } else if tweet!.isRetweeted! { retweetButton.setImage(UIImage(named: "retweet"), forState: UIControlState.Normal) var params: NSDictionary = ["id": tweet!.id!] TwitterClient.sharedInstance.unretweet(tweet!.id!, completion: { (retweet, error) -> () in if retweet != nil { self.retweetLabel.text = "\(--self.tweet!.numRetweets!)" self.delegate?.tweetCell!(self, didChangeRetweetStatus: false) return } }) } } @IBAction func onFavorite(sender: AnyObject) { if !tweet!.isFavorited! { favoriteButton.setImage(UIImage(named: "favoriteOn"), forState: UIControlState.Normal) TwitterClient.sharedInstance.favorite(tweet!.id!, completion: { (tweet, error) -> () in if tweet != nil { self.favoriteLabel.text = "\(++self.tweet!.numFavorites!)" self.delegate?.tweetCell!(self, didChangeFavoriteStatus: true) } }) } else { favoriteButton.setImage(UIImage(named: "favorite"), forState: UIControlState.Normal) var params: NSDictionary = ["id": tweet!.id!] TwitterClient.sharedInstance.unfavorite(tweet!.id!, completion: { (tweet, error) -> () in if tweet != nil { self.favoriteLabel.text = "\(--self.tweet!.numFavorites!)" self.delegate?.tweetCell!(self, didChangeFavoriteStatus: false) } }) } } }
import UIKit public class WaterStateView: UIView, StateView { enum ActionType: String { case error case empty case loading } internal var type: ActionType = .empty public var titleView: UIView? public var title: String? public var descriptionInfo: String? public var buttonTitle: String? public var configureView: ((WaterStateView) -> Void)? public var appearance = StateViewAppearance() public weak var delegate: WaterStatesDelegate? // Stack view constraints private var stackLeadingConstraint: NSLayoutConstraint! private var stackTrailingConstraint: NSLayoutConstraint! private var stackBottomConstraint: NSLayoutConstraint! var contentStackView: UIStackView! private lazy var builder = WaterStatesViewBuilder(appearance: appearance) public func configure(with title: String?, description: String?) { showContentStackView() if let titleView = titleView { contentStackView.addArrangedSubview(titleView) } if let title = title ?? self.title { contentStackView.addArrangedSubview(builder.makeTitleLabel(with: title)) } if let descriptionInfo = description ?? descriptionInfo { contentStackView.addArrangedSubview(builder.makeDescriptionLabel(with: descriptionInfo)) } if let buttonTitle = buttonTitle { let button = builder.actionButton(title: buttonTitle) button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside) contentStackView.addArrangedSubview(button) } backgroundColor = appearance.backgroundColor } // MARK: Actions @objc func buttonTapped(_: UIButton) { switch type { case .empty: delegate?.emptyActionTapped(with: .default) case .error: delegate?.errorActionTapped(with: .default) default: return } } // MARK: Private Methods private func showContentStackView() { guard contentStackView == nil else { contentStackView.arrangedSubviews.forEach { $0.removeFromSuperview() } return } contentStackView = builder.mainStackView(spacing: 38) contentStackView.translatesAutoresizingMaskIntoConstraints = false addSubview(contentStackView) stackLeadingConstraint = contentStackView.leadingAnchor.constraint(equalTo: leadingAnchor) stackLeadingConstraint.isActive = true stackTrailingConstraint = contentStackView.trailingAnchor.constraint(equalTo: trailingAnchor) stackTrailingConstraint.isActive = true stackBottomConstraint = contentStackView.centerYAnchor.constraint(equalTo: centerYAnchor) stackBottomConstraint.isActive = true } func copyView() -> Self { let stateView = WaterStateView() stateView.titleView = titleView?.copyView() stateView.title = title stateView.descriptionInfo = descriptionInfo stateView.buttonTitle = buttonTitle stateView.appearance = appearance stateView.configureView = configureView stateView.configureView?(stateView) return stateView as! Self } } private extension UIView { func copyView<T: UIView>() -> T { return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self)) as! T } }
// // ViewController.swift // DecodingJSONMultipleDates // // Created by Suresh Shiga on 28/11/19. // Copyright © 2019 Test. All rights reserved. //https://blog.usejournal.com/decoding-a-json-having-multiple-date-formats-in-swift-9ad22c443448 import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // 1 setupJSON() //2 //setupJSON2() } //1 private func setupJSON(){ let formatter = DateFormatter() formatter.dateFormat = "hh:mm a" let decodable = JSONDecoder() decodable.dateDecodingStrategy = .formatted(formatter) do { let sunPosition = try decodable.decode(SunPosition.self, from: data) print(sunPosition.sunrise) print(sunPosition.sunset) } catch { print(error) } } // 2 private func setupJSON2(){ do { guard let data3 = data2 else { fatalError("data not found")} let sunPosition = try JSONDecoder().decode(SunPosition2.self, from: data3) print(sunPosition.sunrise.value) print(sunPosition.sunset.value) print(sunPosition.day.value) } catch { print(error) } } } //MARK:- MODEL // 1 struct SunPosition: Codable { let location: String let sunrise: Date let sunset: Date } // 2 struct SunPosition2: Codable { let location: String let sunrise: CustomDate<HoursAndMinutes> let sunset: CustomDate<HoursAndMinutes> let day: CustomDate<Days> } // Protocal for dateformatter protocol HasDateFormatter { static var dateFormatter: DateFormatter {get} } // CustomDate Struct for getting date value struct CustomDate<E:HasDateFormatter>: Codable { let value: Date init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let text = try container.decode(String.self) guard let date = E.dateFormatter.date(from: text) else { throw CustomDateError.general} self.value = date } enum CustomDateError: Error { case general } } // Get the hours and minutes struct HoursAndMinutes: HasDateFormatter { static var dateFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "hh:mm a" return formatter } } //Get the Days struct Days: HasDateFormatter { static var dateFormatter: DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "dd-MMM-yyyy" return formatter } } //MARK:- DATA //1 let data = """ { "location": "India", "sunrise": "4:48 AM", "sunset": "8:26 PM" } """ .data(using: .utf8)! // 2 let data2 = """ { "location": "India", "sunrise": "03:00 AM", "sunset": "09: 00 PM", "day": "12-SEP-2019" } """ .data(using: .utf8)
// // CreatePostViewController.swift // uSell // // Created by Adam Johnson on 8/10/15. // // import UIKit import Parse import Reachability protocol CreatePostViewControllerDelegate { func updateTableView(controller: CreatePostViewController, object: PFObject) } class CreatePostViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate { var delegate: CreatePostViewControllerDelegate? var create = true var initialObject : PFObject! var image : PFFile? @IBOutlet weak var scanBarcodeButton: UIButton! @IBOutlet weak var departmentPickerView: UIPickerView! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var postButton: UIButton! @IBOutlet weak var titleTextField: UITextField! @IBOutlet weak var editionTextField: UITextField! @IBOutlet weak var authorTextField: UITextField! @IBOutlet weak var costTextField: UITextField! let pickerData = GlobalConstants.Departments.departments var pickerSelection: String! override func viewDidLoad() { super.viewDidLoad() self.handleColors() self.titleTextField.delegate = self self.editionTextField.delegate = self self.costTextField.delegate = self self.authorTextField.delegate = self self.pickerSelection = pickerData[0] handleEditing() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func postButtonTouch(sender: AnyObject) { if self.create { self.doCreate() } else { self.doEdit() } } @IBAction func cancelButtonTouch(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } func textFieldShouldReturn(textField: UITextField) -> Bool { self.view.endEditing(true) return false } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return self.pickerData.count } func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { let attString = NSAttributedString(string: pickerData[row], attributes: [NSForegroundColorAttributeName :GlobalConstants.Colors.pickerViewTextColor]) return attString } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { pickerSelection = pickerData[row] } @IBAction func scanBarcodeButtonTouch(sender: AnyObject) { self.performSegueWithIdentifier("createPostToBarcodeScannerSegue", sender: self) } func readInJSON(controller: UIViewController, title: String, author: String, imageLink: String) { if title == "" || author == "" || imageLink == "" { GlobalConstants.AlertMessage.displayAlertMessage("There was an issue finding some or all of this book's information", view: self) } dispatch_async(dispatch_get_main_queue()) { self.titleTextField.text = title self.authorTextField.text = author } if let url = NSURL(string: imageLink) { if let data = NSData(contentsOfURL: url){ self.image = PFFile(data: data) } } } private func handleColors() { self.view.backgroundColor = GlobalConstants.Colors.backgroundColor self.cancelButton.setTitleColor(GlobalConstants.Colors.buttonTextColor, forState: UIControlState.Normal) self.cancelButton.backgroundColor = GlobalConstants.Colors.buttonBackgroundColor self.cancelButton.layer.cornerRadius = 5 self.cancelButton.layer.borderWidth = 1 self.cancelButton.layer.borderColor = GlobalConstants.Colors.buttonBackgroundColor.CGColor self.postButton.setTitleColor(GlobalConstants.Colors.buttonTextColor, forState: UIControlState.Normal) self.postButton.backgroundColor = GlobalConstants.Colors.buttonBackgroundColor self.postButton.layer.cornerRadius = 5 self.postButton.layer.borderWidth = 1 self.postButton.layer.borderColor = GlobalConstants.Colors.buttonBackgroundColor.CGColor //self.scanBarcodeButton.setTitleColor(GlobalConstants.Colors.buttonTextColor, forState: UIControlState.Normal) //self.scanBarcodeButton.backgroundColor = GlobalConstants.Colors.buttonBackgroundColor //self.scanBarcodeButton.layer.cornerRadius = 5 //self.scanBarcodeButton.layer.borderWidth = 1 //self.scanBarcodeButton.layer.borderColor = GlobalConstants.Colors.buttonBackgroundColor.CGColor self.titleTextField.backgroundColor = GlobalConstants.Colors.textFieldBackgroundColor self.titleTextField.textColor = GlobalConstants.Colors.textFieldTextColor self.editionTextField.backgroundColor = GlobalConstants.Colors.textFieldBackgroundColor self.editionTextField.textColor = GlobalConstants.Colors.textFieldTextColor self.costTextField.backgroundColor = GlobalConstants.Colors.textFieldBackgroundColor self.costTextField.textColor = GlobalConstants.Colors.textFieldTextColor self.authorTextField.backgroundColor = GlobalConstants.Colors.textFieldBackgroundColor self.authorTextField.textColor = GlobalConstants.Colors.textFieldTextColor } private func handleEditing() { if !self.create { self.postButton.setTitle("Save", forState: .Normal) self.titleTextField.text = self.initialObject["postTitle"] as? String self.editionTextField.text = self.initialObject["postEdition"] as? String self.costTextField.text = self.initialObject["postCost"] as? String self.authorTextField.text = self.initialObject["postAuthor"] as? String self.departmentPickerView.selectRow(pickerData.indexOf((self.initialObject["postDepartment"] as? String)!)!, inComponent: 0, animated: false) self.image = self.initialObject["image"] as? PFFile } } private func doEdit() { let title = self.titleTextField.text let author = self.authorTextField.text let cost = self.costTextField.text let edition = self.editionTextField.text if (Int(cost!)) == nil || (Int(edition!)) == nil { GlobalConstants.AlertMessage.displayAlertMessage("Your cost and or edition input is not in the correct form. Make sure they're whole numbers and submit again.", view: self) } else { if (cost != "" && title != "" && author != "") { let reachability = Reachability.reachabilityForInternetConnection() if (reachability.isReachable()) { PFQuery(className: "post").getObjectInBackgroundWithId(self.initialObject.objectId!, block: { (object, error) -> Void in if (error == nil) { object!["postTitle"] = title object!["postEdition"] = edition object!["postDepartment"] = self.pickerSelection object!["postCost"] = cost object!["postAuthor"] = author if self.image == nil { object!["image"] = NSNull() } else { object!["image"] = self.image } object!.saveInBackgroundWithBlock { (success, error) -> Void in if (success == true) { if (error == nil) { self.dismissViewControllerAnimated(true, completion: nil) } } else { GlobalConstants.AlertMessage.displayAlertMessage("error updating object", view: self) } } } }) } else { GlobalConstants.AlertMessage.displayAlertMessage("You aren't connected to the internet, please check your connection and try again.", view: self) } } } } private func doCreate() { let postTitle = titleTextField.text let postEdition = editionTextField.text let postCost = costTextField.text let postAuthor = authorTextField.text if (Int(postCost!) == nil) || (Int(postEdition!) == nil) { GlobalConstants.AlertMessage.displayAlertMessage("Your cost and or edition input is not in the correct form. Make sure they're whole numbers and submit again.", view: self) } else { if (postTitle != "" && postCost != "" && postAuthor != "") { let reachability = Reachability.reachabilityForInternetConnection() if (reachability.isReachable()) { let newPost = PFObject(className: "post") newPost.setObject(postTitle!, forKey: "postTitle") newPost.setObject(self.pickerSelection, forKey: "postDepartment") newPost.setObject(postEdition!, forKey: "postEdition") newPost.setObject(postCost!, forKey: "postCost") newPost.setObject(postAuthor!, forKey: "postAuthor") newPost.setObject(PFUser.currentUser()!, forKey: "poster") if self.image == nil { newPost.setObject(NSNull(), forKey: "image") } else { newPost.setObject(self.image!, forKey: "image") } newPost.saveInBackgroundWithBlock({ (success: Bool, error: NSError? ) -> Void in if (error == nil) { self.delegate!.updateTableView(self, object: newPost) self.dismissViewControllerAnimated(true, completion: nil) } else { //put an alert in here } }) } else { GlobalConstants.AlertMessage.displayAlertMessage("You aren't connected to the internet, please check your connection and try again.", view: self) } } else { GlobalConstants.AlertMessage.displayAlertMessage("You are missing some necessary fields", view: self) } } } }
// // RepresentationSearchModel.swift // Cargo Transportation // // Created by Alex Bezkopylnyi on 29.11.2020. // import Foundation // Poka hz zachem struct RepresentationSearchModel: BaseModelProtocol { var status: Bool var message: String var data: [RepresentationSearchDataModel] } struct RepresentationSearchDataModel: Codable { var id, name: String var distance, longitude, latitude, longitudeCorrect: Double var latitudeCorrect: Double var cityName: String var address: String var isWarehouse: Bool var phone, workingTime: String enum CodingKeys: String, CodingKey { case id, name, distance, longitude, latitude, longitudeCorrect, latitudeCorrect, cityName, address case isWarehouse = "IsWarehouse" case phone case workingTime = "working_time" } }
// // InputTodoViewModel.swift // NGenTodo // // Created by yamada.ryo on 2020/07/19. // Copyright © 2020 yamada.ryo. All rights reserved. // import SwiftUI class InputTodoViewModel: ObservableObject { @Published var title: String @Published var point: String @Published var isUseDeadline: Bool @Published var deadlineDate: Date @Published var mode: Mode enum Mode { case add(maxOrder: Int) case edit var navigationTitle: String { switch self { case .add: return "Add Todo" case .edit: return "Edit Todo" } } } private let maxOrder: Int? private var todo: TodoData? var hasError: Bool { return title.isEmpty } init(todo: TodoData) { self.mode = .edit self.todo = todo self.title = todo.title self.point = todo.point.description self.isUseDeadline = todo.deadlineDate != nil self.deadlineDate = todo.deadlineDate ?? Date() self.maxOrder = nil } init(maxOrder: Int) { self.mode = .add(maxOrder: maxOrder) self.todo = nil self.title = "" self.point = "" self.isUseDeadline = false self.deadlineDate = Date() self.maxOrder = maxOrder } func onAppear() { } func save() { if todo == nil { todo = CoreDataService.new() } guard let todo = todo else { return } todo.title = title todo.point = Int(point) ?? 0 todo.deadlineDate = isUseDeadline == false ? nil : deadlineDate if case .add(let maxOrder) = mode { todo.id = UUID() todo.createDate = Date() todo.order = maxOrder + 1 CoreDataService.insert(todo) } CoreDataService.save() } func cancel() { CoreDataService.rollback() } }
import Quick import Nimble import Clappr class ContainerFactoryTests: QuickSpec { override func spec() { let optionsWithValidSource = [kSourceUrl : "http://test.com"] let optionsWithInvalidSource = [kSourceUrl : "invalid"] var factory: ContainerFactory! var loader: Loader! beforeEach() { loader = Loader() loader.addExternalPlugins([StubPlayback.self]) } context("Container creation") { it("Should create a container with valid playback for a valid source") { factory = ContainerFactory(loader: loader, options: optionsWithValidSource) expect(factory.createContainer().playback.pluginName) == "AVPlayback" } it("Should create a container with invalid playback for url that cannot be played") { factory = ContainerFactory(loader: loader, options: optionsWithInvalidSource) expect(factory.createContainer().playback.pluginName) == "NoOp" } it("Should add container plugins from loader") { loader.addExternalPlugins([FakeContainerPlugin.self, AnotherFakeContainerPlugin.self]) factory = ContainerFactory(loader: loader, options: optionsWithValidSource) let container = factory.createContainer() expect(container.hasPlugin(FakeContainerPlugin)).to(beTrue()) expect(container.hasPlugin(AnotherFakeContainerPlugin)).to(beTrue()) } it("Should add a container context to all plugins") { factory = ContainerFactory(loader: loader, options: optionsWithValidSource) let container = factory.createContainer() expect(container.plugins).toNot(beEmpty()) for plugin in container.plugins { expect(plugin.container) == container } } } } class StubPlayback: Playback { override class func canPlay(options: Options) -> Bool { return options[kSourceUrl] as! String != "invalid" } override var pluginName: String { return "AVPlayback" } } class FakeContainerPlugin: UIContainerPlugin { override var pluginName: String { return "FakeContainerPlugin" } } class AnotherFakeContainerPlugin: UIContainerPlugin { override var pluginName: String { return "AnotherFakeContainerPlugin" } } }
// // customSideViewCell.swift // GoApp // // Created by X on 12/9/16. // Copyright © 2016 Brenda Kaing. All rights reserved. // import Foundation import UIKit class customSideViewCell: UITableViewCell { @IBOutlet weak var categoryLabel: UILabel! @IBOutlet weak var `switch`: UISwitch! private var _model: String = "" public internal (set) var model: String { get { return self._model } set { self._model = newValue self.categoryLabel.text = self._model } } //******************* MARK: Switch control weak var delegate: SwitchDelegate? @IBAction func switchSwitched(_ sender: Any) { let category = self._model delegate?.switchChanged(controller: self, selectedCategory: category) } }
// // AssetDetailModel.swift // MMWallet // // Created by Dmitry Muravev on 20.07.2018. // Copyright © 2018 micromoney. All rights reserved. // import RealmSwift import ObjectMapper class AssetDetailModel: Object, Mappable { @objc dynamic var id = 0 @objc dynamic var name = "" @objc dynamic var currency = "" @objc dynamic var balanceString = "" @objc dynamic var balance = 0.0 @objc dynamic var address = "" @objc dynamic var createdAt: Date? = nil @objc dynamic var updatedAt: Date? = nil @objc dynamic var rate: RateModel? @objc dynamic var typeString = "" //token cryptocurrency @objc dynamic var symbol = "" var transactionList = List<TransactionModel>() var owner = List<TokenOwnerModel>() override class func primaryKey() -> String? { return "id" } required convenience init?(map: Map) { self.init() } func mapping(map: Map) { id <- map["id"] name <- map["name"] address <- map["address"] currency <- map["currency"] balance <- map["balance"] balanceString <- map["balance"] createdAt <- (map["createdAt"], DateIntTransform()) updatedAt <- (map["updatedAt"], DateIntTransform()) rate <- map["rate"] rate?.id = "asset:\(id)" typeString <- map["type"] symbol <- map["symbol"] if let owners: [String: Any] = map.JSON["owner"] as? [String: Any] { for address in owners.keys { let tokenOwnerModel = TokenOwnerModel() tokenOwnerModel.address = address if let ownerBalance: Double = owners[address] as? Double{ tokenOwnerModel.balance = ownerBalance } tokenOwnerModel.id = "\(id):\(address)" owner.append(tokenOwnerModel) } } transactionList <- (map["transactionList"], ListTransform<TransactionModel>()) } }
//: Playground - noun: a place where people can play import UIKit var str = " { logo = cnews; name = "C News"; stream = ""; }, { logo = bfmtv; name = "BFM TV"; stream = ""; }"
// // ResultViewController.swift // BMI // // Created by Hanoudi on 6/26/20. // Copyright © 2020 Hanan. All rights reserved. // import Foundation import UIKit class ResultViewController: UIViewController { // MARK:- Variables // Variables the result view need to display // Passed on from calcule view controller and set there. var bmiValue: String? var advice: String? var color: UIColor? // MARK:- Outlets. @IBOutlet weak var bmiLabel: UILabel! @IBOutlet weak var adviceLabel: UILabel! // MARK:- Functions. @IBAction func recalculatePressed(_ sender: UIButton) { dismiss(animated: true, completion: nil) } // MARK:- View's life cycle override func viewDidLoad() { super.viewDidLoad() bmiLabel.text = bmiValue adviceLabel.text = advice adviceLabel.textColor = color } }
// // CommentCell.swift // ZoomGiaoThong // // Created by Thanh Phạm on 1/31/18. // Copyright © 2018 3T Asia. All rights reserved. // import UIKit class CommentCell: UITableViewCell { @IBOutlet weak var imageAvatar: UIImageView! @IBOutlet weak var labelComment: UILabel! @IBOutlet weak var labelUpdated: UILabel! @IBOutlet weak var labelUserName: UILabel! }
// // ChainableAnimator.swift // JHChainableAnimations // // Created by Jeff Hurray on 1/17/17. // Copyright © 2017 jhurray. All rights reserved. // import Foundation import UIKit internal extension Float { var toCG: CGFloat { return CGFloat(self) } } public final class ChainableAnimator { fileprivate let animator: JHChainableAnimator! public init(view: UIView) { animator = JHChainableAnimator(view: view) } public var completion: () -> Void { get { return animator.completionBlock } set (newCompletion) { animator.completionBlock = newCompletion } } public var isAnimating: Bool { return animator.isAnimating } public var isPaused: Bool { return animator.isPaused } public var view: UIView { return animator.view } public func pause() { animator.pause() } public func resume() { animator.resume() } public func stop() { animator.stop() } } public extension ChainableAnimator { public func make(frame: CGRect) -> Self { animator.makeFrame()(frame) return self; } public func make(bounds: CGRect) -> Self { animator.makeBounds()(bounds) return self } public func make(width: Float, height: Float) -> Self { animator.makeSize()(width.toCG, height.toCG) return self } public func makeOrigin(x: Float, y: Float) -> Self { animator.makeOrigin()(x.toCG, y.toCG) return self } public func makeCenter(x: Float, y: Float) -> Self { animator.makeCenter()(x.toCG, y.toCG) return self } public func make(x: Float) -> Self { animator.makeX()(x.toCG) return self } public func make(y: Float) -> Self { animator.makeY()(y.toCG) return self } public func make(width: Float) -> Self { animator.makeWidth()(width.toCG) return self } public func make(height: Float) -> Self { animator.makeHeight()(height.toCG) return self } public func make(alpha: Float) -> Self { animator.makeOpacity()(alpha.toCG) return self } public func make(backgroundColor color: UIColor) -> Self { animator.makeBackground()(color) return self } public func make(borderColor color: UIColor) -> Self { animator.makeBorderColor()(color) return self } public func make(borderWidth width: Float) -> Self { animator.makeBorderWidth()(width.toCG) return self } public func make(cornerRadius: Float) -> Self { animator.makeCornerRadius()(cornerRadius.toCG) return self } public func make(scale: Float) -> Self { animator.makeScale()(scale.toCG) return self } public func make(scaleY: Float) -> Self { animator.makeScaleY()(scaleY.toCG) return self } public func make(scaleX: Float) -> Self { animator.makeScaleX()(scaleX.toCG) return self } public func makeAnchor(x: Float, y: Float) -> Self { animator.makeAnchor()(x.toCG, y.toCG) return self } public func move(x: Float) -> Self { animator.moveX()(x.toCG) return self } public func move(y: Float) -> Self { animator.moveY()(y.toCG) return self } public func move(x: Float, y: Float) -> Self { animator.moveXY()(x.toCG, y.toCG) return self } public func move(width: Float) -> Self { animator.moveWidth()(width.toCG) return self } public func move(height: Float) -> Self { animator.moveHeight()(height.toCG) return self } public func movePolar(radius: Float, angle: Float) -> Self { animator.movePolar()(radius.toCG, angle.toCG) return self } public var transformIdentity: ChainableAnimator { animator.transformIdentity() return self } public func rotate(angle: Float) -> Self { animator.rotate()(angle.toCG) return self } public func rotateX(angle: Float) -> Self { animator.rotateX()(angle.toCG) return self } public func rotateY(angle: Float) -> Self { animator.rotateY()(angle.toCG) return self } public func rotateZ(angle: Float) -> Self { animator.rotateZ()(angle.toCG) return self } public func transform(x: Float) -> Self { animator.transformX()(x.toCG) return self } public func transform(y: Float) -> Self { animator.transformY()(y.toCG) return self } public func transform(x: Float, y: Float) -> Self { animator.transformXY()(x.toCG, y.toCG) return self } public func transform(scale: Float) -> Self { animator.transformScale()(scale.toCG) return self } public func transform(scaleX: Float) -> Self { animator.transformScaleX()(scaleX.toCG) return self } public func transform(scaleY: Float) -> Self { animator.transformScaleY()(scaleY.toCG) return self } public func move(onPath path: UIBezierPath, rotate: Bool = false, isReversed: Bool = false) -> Self { if rotate { if isReversed { animator.moveAndReverseRotateOnPath()(path) } else { animator.moveAndRotateOnPath()(path) } } else { animator.moveOnPath()(path) } return self } public enum AnchorPosition { case normal case center case topLeft case topRight case bottomLeft case bottomRight case top case bottom case left case right } public func anchor(_ position: AnchorPosition) -> ChainableAnimator { switch position { case .normal: animator.anchorDefault() case .center: animator.anchorCenter() case .topLeft: animator.anchorTopLeft() case .topRight: animator.anchorTopRight() case .bottomLeft: animator.anchorBottomLeft() case .bottomRight: animator.anchorBottomRight() case .top: animator.anchorTop() case .bottom: animator.anchorBottom() case .left: animator.anchorLeft() case .right: animator.anchorRight() } return self } public func delay(t: TimeInterval) -> Self { animator.delay()(t) return self } public func wait(t: TimeInterval) -> Self { animator.wait()(t) return self } public var easeIn: ChainableAnimator { animator.easeIn() return self } public var easeOut: ChainableAnimator { animator.easeOut() return self } public var easeInOut: ChainableAnimator { animator.easeInOut() return self } public var easeBack: ChainableAnimator { animator.easeBack() return self } public var spring: ChainableAnimator { animator.spring() return self } public var bounce: ChainableAnimator { animator.bounce() return self } public var easeInQuad: ChainableAnimator { animator.easeInQuad() return self } public var easeOutQuad: ChainableAnimator { animator.easeOutQuad() return self } public var easeInOutQuad: ChainableAnimator { animator.easeInOutQuad() return self } public var easeInCubic: ChainableAnimator { animator.easeInCubic() return self } public var easeOutCubic: ChainableAnimator { animator.easeOutCubic() return self } public var easeInOutCubic: ChainableAnimator { animator.easeInOutCubic() return self } public var easeInQuart: ChainableAnimator { animator.easeInQuart() return self } public var easeOutQuart: ChainableAnimator { animator.easeOutQuart() return self } public var easeInOutQuart: ChainableAnimator { animator.easeInOutQuart() return self } public var easeInQuint: ChainableAnimator { animator.easeInQuint() return self } public var easeOutQuint: ChainableAnimator { animator.easeOutQuint() return self } public var easeInOutQuint: ChainableAnimator { animator.easeInOutQuint() return self } public var easeInSine: ChainableAnimator { animator.easeInSine() return self } public var easeOutSine: ChainableAnimator { animator.easeOutSine() return self } public var easeInOutSine: ChainableAnimator { animator.easeInOutSine() return self } public var easeInExpo: ChainableAnimator { animator.easeInExpo() return self } public var easeOutExpo: ChainableAnimator { animator.easeOutExpo() return self } public var easeInOutExpo: ChainableAnimator { animator.easeInOutExpo() return self } public var easeInCirc: ChainableAnimator { animator.easeInCirc() return self } public var easeOutCirc: ChainableAnimator { animator.easeOutCirc() return self } public var easeInOutCirc: ChainableAnimator { animator.easeInOutCirc() return self } public var easeInElastic: ChainableAnimator { animator.easeInElastic() return self } public var easeOutElastic: ChainableAnimator { animator.easeOutElastic() return self } public var easeInOutElastic: ChainableAnimator { animator.easeInOutElastic() return self } public var easeInBack: ChainableAnimator { animator.easeInBack() return self } public var easeOutBack: ChainableAnimator { animator.easeOutBack() return self } public var easeInOutBack: ChainableAnimator { animator.easeInOutBack() return self } public var easeInBounce: ChainableAnimator { animator.easeInBounce() return self } public var easeOutBounce: ChainableAnimator { animator.easeOutBounce() return self } public var easeInOutBounce: ChainableAnimator { animator.easeInOutBounce() return self } public func customAnimationFunction(function: @escaping (Double, Double, Double, Double) -> (Double)) -> Self { animator.customAnimationFunction()(function) return self } public func preAnimationBlock(block: @escaping () -> ()) -> Self { animator.preAnimationBlock()(block) return self } public func postAnimationBlock(block: @escaping () -> ()) -> Self { animator.postAnimationBlock()(block) return self } public func `repeat`(t: TimeInterval, count: Int) -> Self { animator.`repeat`()(t, count) return self } public func thenAfter(t: TimeInterval) -> Self { animator.thenAfter()(t) return self } public func animate(t: TimeInterval) { animator.animate()(t) } public func animateWithRepeat(t: TimeInterval, count: Int) { animator.animateWithRepeat()(t, count) } public func animate(t: TimeInterval, completion: @escaping () -> ()) { animator.animateWithCompletion()(t, completion) } }
// // Event.swift // Calendar v1 // // Created by Inal Gotov on 2016-07-14. // Copyright © 2016 William Lyon Mackenize CI. All rights reserved. // import Foundation class Event: Hashable { var title:String var description:String var startDate:Date? var endDate:Date? var location:String fileprivate var dateCreator:DateComponents = DateComponents() var hashValue: Int { get { if title == "" && description == "" && startDate == nil && endDate == nil && location == "" { return -1 } else { return (title + description + (startDate?.description)! + (endDate?.description)! + location).hashValue } } } init (calendar:Calendar) { self.title = "" self.description = "" self.startDate = nil self.endDate = nil self.location = "" self.dateCreator.calendar = calendar self.dateCreator.timeZone = TimeZone(abbreviation: "EST") } func setTitle (_ newTitle:NSString) { self.title = newTitle as String } func setDescription (_ newDescription:NSString) { self.description = newDescription as String } func setStartDate (_ newDate:NSString) { if newDate.hasPrefix(":"){ // Example :20130410T230000Z dateCreator.year = Int (newDate.substring(with: NSMakeRange(1, 4)))! dateCreator.month = Int (newDate.substring(with: NSMakeRange(5, 2)))! dateCreator.day = Int (newDate.substring(with: NSMakeRange(7, 2)))! dateCreator.hour = Int (newDate.substring(with: NSMakeRange(10, 2)))! - 4 // Minus 4 because it returns time in a different timezone (No clue as to why) dateCreator.minute = Int (newDate.substring(with: NSMakeRange(12, 2)))! dateCreator.second = Int (newDate.substring(with: NSMakeRange(14, 2)))! startDate = dateCreator.date! } else if newDate.hasPrefix(";TZID") { // Example ;TZID=America/Toronto:20120928T100000 let firstLocation = newDate.range(of: "=").location + 1 dateCreator.timeZone = TimeZone(identifier: newDate.substring(with: NSMakeRange(firstLocation, newDate.range(of: ":").location - firstLocation))) dateCreator.year = Int (newDate.substring(with: NSMakeRange(22, 4)))! dateCreator.month = Int (newDate.substring(with: NSMakeRange(26, 2)))! dateCreator.day = Int (newDate.substring(with: NSMakeRange(28, 2)))! dateCreator.hour = Int (newDate.substring(with: NSMakeRange(31, 2)))! - 4 dateCreator.minute = Int (newDate.substring(with: NSMakeRange(33, 2)))! dateCreator.second = Int (newDate.substring(with: NSMakeRange(35, 2)))! startDate = dateCreator.date! } else if newDate.hasPrefix(";") { // Example ;VALUE=DATE:20170609 dateCreator.year = Int (newDate.substring(with: NSMakeRange(12, 4)))! dateCreator.month = Int (newDate.substring(with: NSMakeRange(16, 2)))! dateCreator.day = Int (newDate.substring(with: NSMakeRange(18, 2)))! dateCreator.hour = 00 - 4 dateCreator.minute = 00 dateCreator.second = 00 startDate = dateCreator.date! } else if newDate == "" { dateCreator.year = 1970 dateCreator.month = 01 dateCreator.day = 01 dateCreator.hour = 00 dateCreator.minute = 00 dateCreator.second = 00 startDate = dateCreator.date! } else { fatalError("Failed to prase \(newDate)") } } func setEndDate (_ newDate:NSString) { if newDate.hasPrefix(":"){ // Example :20130410T230000Z dateCreator.year = Int (newDate.substring(with: NSMakeRange(1, 4)))! dateCreator.month = Int (newDate.substring(with: NSMakeRange(5, 2)))! dateCreator.day = Int (newDate.substring(with: NSMakeRange(7, 2)))! dateCreator.hour = Int (newDate.substring(with: NSMakeRange(10, 2)))! - 4 // Minus 4 because it returns time in a different timezone (No clue as to why) dateCreator.minute = Int (newDate.substring(with: NSMakeRange(12, 2)))! dateCreator.second = Int (newDate.substring(with: NSMakeRange(14, 2)))! endDate = dateCreator.date! } else if newDate.hasPrefix(";TZID") { // Example ;TZID=America/Toronto:20120928T100000 let firstLocation = newDate.range(of: "=").location + 1 dateCreator.timeZone = TimeZone(identifier: newDate.substring(with: NSMakeRange(firstLocation, newDate.range(of: ":").location - firstLocation))) dateCreator.year = Int (newDate.substring(with: NSMakeRange(22, 4)))! dateCreator.month = Int (newDate.substring(with: NSMakeRange(26, 2)))! dateCreator.day = Int (newDate.substring(with: NSMakeRange(28, 2)))! dateCreator.hour = Int (newDate.substring(with: NSMakeRange(31, 2)))! - 4 dateCreator.minute = Int (newDate.substring(with: NSMakeRange(33, 2)))! dateCreator.second = Int (newDate.substring(with: NSMakeRange(35, 2)))! endDate = dateCreator.date! } else if newDate.hasPrefix(";") { // Example ;VALUE=DATE:20170609 dateCreator.year = Int (newDate.substring(with: NSMakeRange(12, 4)))! dateCreator.month = Int (newDate.substring(with: NSMakeRange(16, 2)))! dateCreator.day = Int (newDate.substring(with: NSMakeRange(18, 2)))! dateCreator.hour = 00 - 4 dateCreator.minute = 00 dateCreator.second = 00 endDate = dateCreator.date! } else if newDate == "" { dateCreator.year = 1970 dateCreator.month = 01 dateCreator.day = 01 dateCreator.hour = 00 dateCreator.minute = 00 dateCreator.second = 00 endDate = dateCreator.date! } else { fatalError("Failed to prase \(newDate)") } } func setLocation (_ newLocation:NSString) { self.location = newLocation as String } } func == (lhs: Event, rhs: Event) -> Bool { if (lhs.hashValue == rhs.hashValue) { return true } else if (lhs.title == rhs.title) && (lhs.description == rhs.description) && (lhs.startDate == rhs.startDate) && (lhs.endDate == rhs.endDate) && (lhs.location == rhs.location) { return true } return false }
// // VenueCategory.swift // Task-iOSDeveloper // // Created by Tuan Le on 9/29/20. // struct VenueCategory: Codable { let popularTags: [PopularTag] let id: Int let feelingLuckyData: [FeelingLuckyData] let gradientColorStart: String let image: String let gradientColorEnd: String let feelingLuckyTitle: String let feelingLucky: Int let categoryAny: String let smokingArea: SmokeArea let name: String enum CodingKeys: String, CodingKey { case popularTags, id, feelingLuckyData, image, categoryAny, smokingArea, name case gradientColorStart = "gradient_color_start" case gradientColorEnd = "gradient_color_end" case feelingLuckyTitle = "feeling_lucky_title" case feelingLucky = "feeling_lucky" } } struct FeelingLuckyData: Codable { let anyTitle: String let id: Int let tagGroup: TagGroup let order: Int let categoryId: Int let title: String enum CodingKeys: String, CodingKey { case id, tagGroup, order, title case anyTitle = "any_title" case categoryId = "category_id" } }
// // Sword.swift // SwiftGame // // Created by Cindy Perat on 19/09/2018. // Copyright © 2018 Cindy Perat. All rights reserved. // class Sword: Weapon { init() { super.init(name: .sword, type: .attack, removalLifePoints: swordRemovalLifePoints, addingLifePoints: swordAddingLifePoints) } }
// swift-tools-version:4.2 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let commonTestDependencies: [Target.Dependency] = ["Quick", "Nimble"] let package = Package( name: "rosswift", products: [ .library( name: "Ros", targets: ["Ros"] ), .library( name: "MessageGeneratorKit", targets: ["MessageGeneratorKit"] ), ], dependencies: [ .package(url: "https://github.com/quick/quick.git", from: "1.3.3"), .package(url: "https://github.com/quick/nimble.git", from: "7.3.3"), .package(url: "https://github.com/apple/swift-package-manager.git", from: "0.3.0"), ], targets: [ .target( name: "Ros", dependencies: [] ), .testTarget( name: "RosTests", dependencies: ["Ros"] + commonTestDependencies ), .target( name: "MessageGeneratorKit", dependencies: [] ), .target( name: "MessageGenerator", dependencies: ["MessageGeneratorKit", "Utility"] ), .testTarget( name: "MessageGeneratorKitTests", dependencies: ["MessageGeneratorKit"] + commonTestDependencies ), ] )
// @copyright German Autolabs Assignment import XCTest import CoreLocation @testable import WeatherApp final class WeatherInteractorTests: XCTestCase { var interactor: WeatherInteractor! var output: MockWeatherInteractorOutput! var speechRecognition: MockSpeechRecognition! var parser: MockTranscriptionParser! var weatherService: MockWeatherService! var locationService: MockLocationService! override func setUp() { super.setUp() speechRecognition = MockSpeechRecognition() parser = MockTranscriptionParser() weatherService = MockWeatherService() locationService = MockLocationService() interactor = WeatherInteractor(speechRecognizer: speechRecognition, parser: parser, weatherService: weatherService, locationService: locationService) output = MockWeatherInteractorOutput() interactor.output = output } override func tearDown() { interactor = nil output = nil speechRecognition = nil parser = nil weatherService = nil locationService = nil super.tearDown() } func testStartRecognition() { // when interactor.startRecognition() // then XCTAssertEqual(output.invocations[0], .didStartRecognition) XCTAssertEqual(speechRecognition.invocations[0], .recordAndRecognize) } func testStopRecognition() { // when interactor.stopRecognition() // then XCTAssertEqual(speechRecognition.invocations[0], .stop) } func testReceivedSpeechRecognitionResultSuccess() { // given let transcription = "test transcription" // when interactor.received(.success(transcription)) // then XCTAssertEqual(output.invocations[0], .didFinishRecognition) XCTAssertEqual(parser.invocations[0], .parseTranscription(transcription)) } func testReceivedSpeechRecognitionResultDenied() { // when interactor.received(.denied) // then XCTAssertEqual(output.invocations[0], .didFinishRecognition) XCTAssertEqual(output.invocations[1], .didReceiveRecognitionResult(.failure(.denied))) } func testReceivedSpeechRecognitionResultUnavailable() { // when interactor.received(.unavailable) // then XCTAssertEqual(output.invocations[0], .didFinishRecognition) XCTAssertEqual(output.invocations[1], .didReceiveRecognitionResult(.failure(.unavailable))) } func testUnrecognizedCommand() { // given parser.mockResult = nil // when interactor.received(.success("test")) // then XCTAssertEqual(output.invocations[0], .didFinishRecognition) XCTAssertEqual(output.invocations[1], .didReceiveRecognitionResult(.failure(.unrecognizedCommand))) } func testReceiveWeatherLocationDenied() { // given parser.mockResult = .weather(city: nil, date: nil) locationService.mockResult = .denied // when interactor.received(.success("test")) // then XCTAssertEqual(output.invocations[0], .didFinishRecognition) XCTAssertEqual(output.invocations[1], .didReceiveRecognitionResult(.weatherCommand(city: nil, date: nil))) XCTAssertEqual(output.invocations[2], .didStartWeatherFetching) XCTAssertEqual(output.invocations[3], .didFinishWeatherFetching) XCTAssertEqual(output.invocations[4], .didReceiveWeatherResult(.failure(.locationDenied))) } func testReceiveWeatherServiceError() { // given let error = NSError(domain: "test", code: 1, userInfo: nil) parser.mockResult = .weather(city: nil, date: nil) locationService.mockResult = .success(CLLocation(latitude: 10, longitude: 10)) let apiError = WeatherServiceError.api(error) weatherService.mockResult = .failure(apiError) // when interactor.received(.success("test")) // then XCTAssertEqual(output.invocations[0], .didFinishRecognition) XCTAssertEqual(output.invocations[1], .didReceiveRecognitionResult(.weatherCommand(city: nil, date: nil))) XCTAssertEqual(output.invocations[2], .didStartWeatherFetching) XCTAssertEqual(output.invocations[3], .didFinishWeatherFetching) XCTAssertEqual(output.invocations[4], .didReceiveWeatherResult(.failure(.unknown(apiError)))) } func testReceiveWeatherServiceSuccess() throws { // given let entity = try generateEntity()! parser.mockResult = .weather(city: nil, date: nil) locationService.mockResult = .success(CLLocation(latitude: 10, longitude: 10)) weatherService.mockResult = .success(entity) // when interactor.received(.success("test")) // then XCTAssertEqual(output.invocations[0], .didFinishRecognition) XCTAssertEqual(output.invocations[1], .didReceiveRecognitionResult(.weatherCommand(city: nil, date: nil))) XCTAssertEqual(output.invocations[2], .didStartWeatherFetching) XCTAssertEqual(output.invocations[3], .didFinishWeatherFetching) if case let .didReceiveWeatherResult(.success(model)) = output.invocations[4] { XCTAssertEqual(model.name, entity.name) XCTAssertEqual(model.description, entity.conditions?.first?.description) XCTAssertEqual(model.temperature, entity.temperature) XCTAssertEqual(model.conditionURL, entity.conditions?.first?.iconURL()) } else { XCTFail() } } }
// // URLSession+Request.swift // HeWeatherIO // // Created by iMac on 2018/5/28. // Copyright © 2018年 iMac. All rights reserved. // import Foundation extension URLSession { func request<T: Codable>(request: URLRequest, queue: DispatchQueue? = nil, completionHandler: @escaping (Result<T>) -> Void) { let task = self.dataTask(with: request) { (data, response, error) in var result: Result<T> = .failure(HeWeatherError.unknownError(nil)) defer { (queue ?? DispatchQueue.main).async { completionHandler(result) } } if let error = error { result = .failure(HeWeatherError.unknownError(error)) return } guard let _ = response else { result = .failure(HeWeatherError.noResponseError) return } guard let data = data else { result = .failure(HeWeatherError.noDataError) return } let decoder = JSONDecoder() if let value = try? decoder.decode(T.self, from: data) { result = .success(value) } else { result = .failure(HeWeatherError.decodeError) } } task.resume() } }
// // ValidHelper.swift // CoAssetsApps // // Created by Tony Tuong on 3/10/16. // Copyright © 2016 TruongVO07. All rights reserved. // import UIKit class ValidHelper: NSObject { static func isValidEmail(emailText: String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) let result = emailTest.evaluateWithObject(emailText) return result } static func isValidatePhoneNumber(value: String) -> Bool { let PHONE_REGEX = "\\+?[0-9]{1,13}" let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX) let result = phoneTest.evaluateWithObject(value) return result } static func stringIsDecimalNumber(stringValue: String) -> Bool { let scan = NSScanner(string: stringValue) scan.charactersToBeSkipped = NSCharacterSet(charactersInString: "1234567890.").invertedSet if scan.scanDouble(nil) { return scan.atEnd } else { return false } } }
// // Course.swift // AluDash // // Created by Rafael Escaleira on 04/07/21. // import Foundation struct Course: Codable { static let url: String = "https://www.alura.com.br/api/curso-" var slug: String? var nome: String? var metadescription: String? var quantidade_avaliacoes: Int? var carga_horaria: Int? var quantidade_atividades: Int? var data_criacao: String? var data_atualizacao: String? var publico_alvo: String? var ementa: [Grade]? struct Grade: Codable { var capitulo: String? var secoes: [String]? } }
import Flutter import UIKit public class SwiftPoseDetectionPlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "pose_detection_plugin", binaryMessenger: registrar.messenger()) let instance = SwiftPoseDetectionPlugin() registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { guard call.method == "processFrame" else { result(FlutterMethodNotImplemented) return } processFrame(arguments: call.arguments) { response in DispatchQueue.main.async { result(response) } } } func processFrame(arguments: Any?, result: @escaping (String?) -> Void){ DispatchQueue.global(qos: .background).async { guard let args = arguments as? Dictionary<String, Any> else { result(nil) return } let isAccurate = args["isAccurate"] as! Bool if (PoseDetectionHelper.instance.isAccurate != isAccurate) { PoseDetectionHelper.instance.setup(accurate: isAccurate) } guard let uiimage = ImageHelper.getImage(args: args) else { result(nil) return } let positions = PoseDetectionHelper.instance.processVisionImage(uiimage: uiimage) result(positions) } } }
// // CLLocationCoordinate2dExtension.swift // GameSetPlayTests // // Created by Zack Falgout on 7/31/18. // Copyright © 2018 Zack Falgout. All rights reserved. // import Foundation import MapKit extension CLLocationCoordinate2D: Codable { public enum CodingKeys: String, CodingKey { case latitude case longitude } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(latitude, forKey: .latitude) try container.encode(longitude, forKey: .longitude) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.init() latitude = try values.decode(Double.self, forKey: .latitude) longitude = try values.decode(Double.self, forKey: .longitude) } } extension CLLocationCoordinate2D: Equatable { static public func ==(lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool { return lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude } }
// // TextFiledCollectionViewCell.swift // EmojiArt // // Created by Svitlana Dzyuban on 29/8/18. // Copyright © 2018 Lana Dzyuban. All rights reserved. // import UIKit class TextFiledCollectionViewCell: UICollectionViewCell, UITextFieldDelegate { @IBOutlet weak var textField: UITextField! { didSet { textField.delegate = self } } var resignationHandler: (() -> Void)? func textFieldDidEndEditing(_ textField: UITextField) { resignationHandler?() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
// // CustomerInfoTableViewCell.swift // YuQinClient // // Created by ksn_cn on 16/3/18. // Copyright © 2016年 YuQin. All rights reserved. // import UIKit class CustomerInfoTableViewCell: UITableViewCell { @IBOutlet weak var label1: 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 } }
// // Favorite.swift // inChurchMovies // // Created by Victor Vieira Veiga on 21/01/21. // import Foundation import RealmSwift class Favorite : Object { //model of favorite data object using Realm. @objc dynamic var idMovie: Int = 0 @objc dynamic var title: String? @objc dynamic var overview : String? @objc dynamic var date : String? @objc dynamic var posterDropImage : String? //get movies favorited from Realm database func getFavorite() -> Results<Favorite>{ let realm = try! Realm() var favorite : Results<Favorite>? favorite = realm.objects(Favorite.self) return favorite! } }
// // PostCell.swift // page de recherche // // Created by yenbou on 04/02/2020. // Copyright © 2020 yenbou. All rights reserved. // import SwiftUI struct PostCell: View { let imageName: String let postName: String var body: some View { ZStack { Image(imageName) .renderingMode(.original) .resizable() .frame(width: UIScreen.main.bounds.width, height: 276) .opacity(0.5) .background(Color.black) Text(postName) .foregroundColor(.white) .fontWeight(.bold) .font(.largeTitle) .opacity(1) } } } struct PostCell_Previews: PreviewProvider { static var previews: some View { PostCell(imageName: "Salade", postName: "SALADE") } }
// // main.swift // 单一职责原则 // // Created by mxc235 on 2018/4/5. // Copyright © 2018年 FY. All rights reserved. // import Foundation print("Hello, World!")
// // NumberTableViewCell.swift // DeclarativeTableView // // Created by Robin Charlton on 06/07/2021. // import UIKit class NumberTableViewCell: UITableViewCell, Reusable, TypeDepending, ViewHeightProviding { static var viewHeight: CGFloat = 40 func setDependency(_ dependency: Int) { contentView.backgroundColor = .systemYellow textLabel?.text = "The number is \(dependency)" textLabel?.adjustsFontSizeToFitWidth = true } }
// // SearchResultElement.swift // AppDynamicsClientApp // // Created by Bojan Savic on 5/11/19. // Copyright © 2019 Bojan Savic. All rights reserved. // import Foundation import Alamofire class SearchResult { var _title: String! var _imageUrl: String! var _description: String! var _date: String! init() { } init(title: String, description: String, date: String, imageUrl: String) { self._title = title self._description = description self._date = date self._imageUrl = imageUrl } var title: String { if _title == nil { _title = "" } return _title } var imageUrl: String { if _imageUrl == nil { _imageUrl = "" } return _imageUrl } var description: String { if _description == nil { _description = "" } return _description } var date: String { if _date == nil { _date = "" } let dateFormatter = DateFormatter() dateFormatter.dateStyle = .full dateFormatter.timeStyle = .none let currentDate = dateFormatter.string(from: Date()) _date = "Today, \(currentDate)" return _date } }
// // TDUserTabeleViewCell.swift // TestData // // Created by Krzysztof Biskupski on 11.12.2017. // Copyright © 2017 pl.naosoft. All rights reserved. // import UIKit import AlamofireImage class TDUserTableViewCell : UITableViewCell { @IBOutlet var title : UILabel? @IBOutlet var fullName : UILabel? @IBOutlet var email : UILabel? @IBOutlet var actionButton : UIButton? @IBOutlet var photo : UIImageView? var finishSelectionAction:((TDUser) -> Void)? var currentUserData:TDUser? func propagerDataOnView(userData : TDUser, isFavouriteMode:Bool) { self.title?.text = userData.name?.title self.fullName?.text = (userData.name?.first)! + " " + (userData.name?.last)! self.email?.text = userData.email currentUserData = userData loadImageHelper(photo, sourceUrl: (userData.picture?.medium)!, placeholder: nil) if isFavouriteMode { actionButton?.setTitle("Delete", for: UIControlState.normal) } else { actionButton?.setTitle("Favourite", for: UIControlState.normal) } } @IBAction func favouriteAction() { if self.finishSelectionAction != nil { self.finishSelectionAction!(self.currentUserData!) } } func loadImageHelper(_ targetImage:UIImageView?, sourceUrl:String, placeholder:UIView?) { targetImage?.af_setImage(withURL:URL(string: sourceUrl)!, placeholderImage:UIImage(), filter:nil, imageTransition:.crossDissolve(0.2)) } }
// // NPLinkedInParser.swift // LinkedINLogin // // Created by NOUMAN PERVEZ on 16/01/18. // Copyright © 2018 NOUMAN PERVEZ. All rights reserved. // import UIKit import LinkedinSwift import Alamofire import AlamofireObjectMapper import ObjectMapper protocol NPLinkedInParserDelegate: class { func linkedInParsingCompleted(_ obj: NPLinkedInParser) -> Void } class NPLinkedInParser: NSObject { public var emailID : String! public var LName : String! public var FName : String! public var linkedInID : String! public var location : NSDictionary! public var pictureUrls : NSDictionary! public var positions : NSDictionary! public var error : Error! public weak var delegate : NPLinkedInParserDelegate? override init() { super.init() self.getLinkedData() return } func getLinkedData() -> Void { let linkedinHelper = LinkedinSwiftHelper(configuration: LinkedinSwiftConfiguration(clientId:"YOUR CLIENT ID", clientSecret: "YOUR CLIENT SECRET KEY", state: "YOUR ADMIN KEY", permissions: ["r_basicprofile", "r_emailaddress"], redirectUrl: "YOUR REDIRECT URL")) linkedinHelper.authorizeSuccess({ (token) in print(token) //This token is useful for fetching profile info from LinkedIn server linkedinHelper.requestURL("https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address,picture-url,picture-urls::(original),positions,date-of-birth,phone-numbers,location)?format=json", requestType: LinkedinSwiftRequestGet, success: { (response) -> Void in self.parseLinkedInResponse(response) //parse this response which is in the JSON format }) {(error) -> Void in self.error = error print(error.localizedDescription) //handle the error self.delegate?.linkedInParsingCompleted(self) } }, error: { (error) in self.error = error print(error.localizedDescription) //show respective error self.delegate?.linkedInParsingCompleted(self) }) } func parseLinkedInResponse(_ response: LSResponse) -> Void { if let email = response.jsonObject["emailAddress"] { self.emailID = email as! String } else{ self.emailID = "" } if let name = response.jsonObject["id"]{ self.linkedInID = name as! String } else{ self.linkedInID = "" } if let fName = response.jsonObject["firstName"]{ self.FName = fName as! String } else{ self.FName = "" } if let lName = response.jsonObject["lastName"]{ self.LName = lName as! String } else{ self.LName = "" } if let location = response.jsonObject["location"]{ self.location = location as! NSDictionary } else{ self.location = [:] } if let picture = response.jsonObject["pictureUrls"]{ self.pictureUrls = picture as! NSDictionary } else{ self.pictureUrls = [:] } if let positions = response.jsonObject["positions"]{ self.positions = positions as! NSDictionary } else{ self.positions = [:] } self.error = nil //calls delegate and sends backs to Viewcontroller self.delegate?.linkedInParsingCompleted(self) } }
public typealias JSONArray = [[String : AnyObject]] public typealias JSONDictionary = [String : AnyObject] public typealias Action = () -> Void
// // MainTabBarController.swift // LoLMessenger // // Created by Young Rok Kim on 2015. 10. 20.. // Copyright © 2015년 rokoroku. All rights reserved. // import UIKit import STPopup class MainTabBarController : UITabBarController { var contentViewFrame : CGRect? var isAdActivated: Bool = false override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.delegate = self NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateLocale", name: LCLLanguageChangeNotification, object: nil) if let roster = XMPPService.sharedInstance.roster() { updateRosterBadge(roster) } if let chat = XMPPService.sharedInstance.chat() { updateChatBadge(chat) } AppDelegate.addDelegate(self) Async.main(after: 2) { self.activateBannerAd() } updateLocale() } deinit { AppDelegate.removeDelegate(self) } func updateLocale() { if let items = self.tabBar.items { items[0].title = Localized("Friends") items[1].title = Localized("Chat") items[2].title = Localized("Setting") } } override func viewWillAppear(animated: Bool) { // Called when the view is about to made visible. XMPPService.sharedInstance.roster()?.addDelegate(self) XMPPService.sharedInstance.chat()?.addDelegate(self) if let presentedViewController = self.selectedViewController { self.tabBarController(self, didSelectViewController: presentedViewController) } else { self.navigationItem.title = Localized("Friends") } } override func viewDidAppear(animated: Bool) { if let presentedViewController = self.selectedViewController { self.tabBarController(self, didSelectViewController: presentedViewController) } Async.main(after: 1) { self.startAdRequest() } } override func viewDidDisappear(animated: Bool) { if !(UIApplication.topViewController() is STPopupContainerViewController) { XMPPService.sharedInstance.chat()?.removeDelegate(self) XMPPService.sharedInstance.roster()?.removeDelegate(self) NSNotificationCenter.defaultCenter().removeObserver(self, name: LCLLanguageChangeNotification, object: nil) stopAdRequest() } } func updateRosterBadge(rosterService: RosterService) { if let viewControllers = viewControllers { for viewController in viewControllers { if viewController.restorationIdentifier == "RosterTableViewController" { let value = rosterService.getNumOfSubscriptionRequests() viewController.tabBarItem?.badgeValue = value > 0 ? String(value) : nil return } } } } func updateChatBadge(chatService: ChatService) { if let viewControllers = viewControllers { for viewController in viewControllers { if viewController.restorationIdentifier == "RecentChatViewController" { let value = chatService.getNumOfUnreadMessages() viewController.tabBarItem?.badgeValue = value > 0 ? String(value) : nil return } } } } } extension MainTabBarController : AdMixerViewDelegate, BackgroundDelegate { func activateBannerAd() { if view.viewWithTag(11) == nil { let bounds = UIScreen.mainScreen().bounds let bannerView = AdMixerView(frame: CGRectMake(0.0, bounds.size.height, bounds.width, 50.0)) bannerView.backgroundColor = UIColor.init(patternImage: UIImage(named: "default_banner_bg")!) bannerView.tag = 11 bannerView.clipsToBounds = true self.view.addSubview(bannerView) startAdRequest() } } func startAdRequest() { if let banner = view.viewWithTag(11) as? AdMixerView where !isAdActivated && isVisible() { isAdActivated = true let adInfo = AdMixerInfo() adInfo.axKey = "3l188e4t" adInfo.rtbVerticalAlign = AdMixerRTBVAlignCenter adInfo.rtbBannerHeight = AdMixerRTBBannerHeightFixed banner.delegate = self banner.startWithAdInfo(adInfo, baseViewController: self) } } func stopAdRequest(layout: Bool = false) { if let banner = view.viewWithTag(11) as? AdMixerView where isAdActivated { banner.stop() isAdActivated = false if layout { layoutBanner(false) } } } @objc func onSucceededToReceiveAd(adView: AdMixerView!) { #if DEBUG print("receive AD from \(adView.currentAdapterName())") #endif layoutBanner() } @objc func onFailedToReceiveAd(adView: AdMixerView!, error: AXError!) { #if DEBUG print("fail to receive \(adView.currentAdapterName()), \(error)") #endif layoutBanner(false) } internal func didEnterBackground(sender: UIApplication) { stopAdRequest(true) } internal func didBecomeActive(sender: UIApplication) { Async.main(after: 1) { self.startAdRequest() } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.view.bringSubviewToFront(self.tabBar) } override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator) Async.main(after:0.1) { self.layoutBanner() } } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) Async.main(after:0.1) { self.layoutBanner() } } private func layoutBanner(var show: Bool = true) { if let banner = view.viewWithTag(11) as? AdMixerView { let adapter: String? = banner.currentAdapterName() if selectedViewController is MoreViewController { show = false } else if adapter == nil || adapter == "ax_default" { show = false } let bounds = UIScreen.mainScreen().bounds let bannerSize = banner.sizeThatFits(bounds.size) var bannerFrame = banner.frame bannerFrame.width = bounds.width bannerFrame.height = bannerSize.height //let bannerItem = banner.subviews.first where !bannerItem.subviews.isEmpty && if isAdActivated && show { bannerFrame.origin.y = self.tabBar.frame.y - bannerSize.height } else { bannerFrame.origin.y = bounds.size.height } self.view.bringSubviewToFront(self.tabBar) UIView.animateWithDuration(0.25, animations: { banner.frame = bannerFrame }, completion: { _ in self.selectedViewController?.viewWillLayoutSubviews() }) } } func getAdView() -> UIView? { if let banner = view.viewWithTag(11) as? AdMixerView { let adapter: String? = banner.currentAdapterName() return (adapter != nil && adapter != "ax_default") ? banner.subviews.first : nil } return nil } } extension MainTabBarController : UITabBarControllerDelegate { func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) { if let navigationItem: UINavigationItem = viewController.navigationItem { self.navigationItem.title = navigationItem.title self.navigationItem.setLeftBarButtonItems(navigationItem.leftBarButtonItems, animated: false) self.navigationItem.setRightBarButtonItems(navigationItem.rightBarButtonItems, animated: false) } self.layoutBanner() } } extension MainTabBarController : ChatDelegate, RosterDelegate { func didReceiveFriendSubscription(sender: RosterService, from: LeagueRoster) { if selectedViewController?.isKindOfClass(RosterTableViewController) == false { updateRosterBadge(sender) } } func didReceiveNewMessage(sender: ChatService, from: LeagueChat, message: LeagueMessage.RawData) { if selectedViewController?.isKindOfClass(RecentChatViewController) == false { updateChatBadge(sender) } } }
// // PlanDisplayHelper.swift // KayakFirst Ergometer E2 // // Created by Balazs Vidumanszki on 2018. 01. 19.. // Copyright © 2018. Balazs Vidumanszki. All rights reserved. // import Foundation class PlanDisplayHelper { //MARK: properties private let telemetry: Telemetry private var plan: Plan? private var planElements: [PlanElement]? private var planElementsOriginal: [PlanElement]? private var duration: Double = 0 private var distance: Double = 0 private var planElementPosition: Int = 0 private var localeValue: Double = 0 private var showPosition: Int = -1 private var planElementColor = Colors.colorAccent private var value: Double = 0 private var valueAccent: Double = 0 private var totalProgress: Double = 0 private var actualProgress: Double = 0 private var isDone = false //MARK: init private static var instance: PlanDisplayHelper? class func getInstance(telemetry: Telemetry) -> PlanDisplayHelper { if PlanDisplayHelper.instance == nil { PlanDisplayHelper.instance = PlanDisplayHelper(telemetry: telemetry) } return PlanDisplayHelper.instance! } private init(telemetry: Telemetry) { self.telemetry = telemetry } public func setPlane(plan: Plan?) { self.plan = plan if plan != nil && plan!.planElements != nil { planElements = plan!.planElements!.map { $0 } planElementsOriginal = plan!.planElements!.map { $0 } setData(duration: 0, distance: 0) } } //MARK: functions func setData(duration: Double, distance: Double) { if let plan = plan { self.duration = duration self.distance = distance if let planElements = plan.planElements { totalProgress = getTotalPercent() if totalProgress >= 0 { isDone = false setPlanElementPosition() actualProgress = getCurrentPercent() } else { isDone = true planElementPosition = planElements.count resetProgress() } setValues() setToTelemetry() } } } func reset() { duration = 0 distance = 0 planElementPosition = 0 localeValue = 0 showPosition = -1 planElementColor = Colors.colorAccent value = 0 valueAccent = 0 totalProgress = 0 actualProgress = 0 isDone = false if plan != nil { resetProgress() } } private func setToTelemetry() { telemetry.planTelemetryObject = getPlanTelemetryObject() } private func getTotalPercent() -> Double { if getCurrentTotalValue() > plan!.length { return -1 } else { let percent: Double = getCurrentTotalValue() / plan!.length return (Double(100) * (Double(1) - percent)) } } private func setPlanElementPosition() { let localPlanElementPos = planElementPosition var sum: Double = 0 for i in 0..<plan!.planElements!.count { sum += plan!.planElements![i].value if sum >= getCurrentTotalValue() { planElementPosition = i if localPlanElementPos != i { resetProgress() } break } } } private func getCurrentPercent() -> Double { var percent: Double = 1 if let currentPlanElement = getCurrentPlanElement() { var sum: Double = 0 for i in 0..<planElementPosition { sum += plan!.planElements![i].value } let diff = getCurrentTotalValue() - sum percent = diff / currentPlanElement.value } return (1 - percent) } private func getCurrentTotalValue() -> Double { var valueToCheck = duration if plan!.type == PlanType.distance { valueToCheck = distance } return valueToCheck } private func getCurrentPlanElement() -> PlanElement? { if plan != nil && plan!.planElements != nil && planElementPosition < plan!.planElements!.count { return plan!.planElements![planElementPosition] } return nil } private func resetProgress() { localeValue = distance if plan!.type == PlanType.distance { localeValue = duration } value = 0 valueAccent = 0 actualProgress = 0 setProgressBarPlanElementColor() showPlanElementByPosition() } private func setProgressBarPlanElementColor() { planElementColor = Colors.colorAccent if let planElement = getCurrentPlanElement() { planElementColor = getPlanElementColor(planElement: planElement) } } private func setValues() { value = 0 valueAccent = 0 if let planElement = getCurrentPlanElement() { value = actualProgress * planElement.value valueAccent = distance - localeValue if plan!.type == PlanType.distance { valueAccent = duration - localeValue } } } private func showPlanElementByPosition() { if planElements != nil && showPosition != planElementPosition { var newElements = [PlanElement]() for i in planElementPosition..<planElementsOriginal!.count { newElements.append(planElementsOriginal![i]) } planElements = newElements } self.showPosition = planElementPosition } private func getPlanTelemetryObject() -> PlanTelemetryObject { return PlanTelemetryObject( planElementColor: planElementColor, planElementList: planElements, value: value, valueAccent: valueAccent, totalProgress: totalProgress, actualProgress: 100 * actualProgress, isDone: isDone) } }
// VCDetallesMomento.swift // ProyectoRecuerdos import UIKit import MediaPlayer import AVFoundation class VCDetallesMomento: UIViewController, AVAudioPlayerDelegate { // Declaracion de elementos de interfaz @IBOutlet weak var lbNombre: UILabel! @IBOutlet weak var imagenFoto: UIImageView! @IBOutlet weak var lbFecha: UILabel! @IBOutlet weak var tfDescripcion: UITextView! // Declaracion de variables var anterior : TableViewControllerMomentos! // Apuntador a Tabla de Momentos var momentoDicc : NSDictionary! // Informacion del momento var indexPath : IndexPath! // Declaracion de elementos para musica var songURL: URL? = nil var audioPlayer: AVAudioPlayer! var reproduciendo = false // Configuracion de los elementos de interfaz del boton de musica @IBOutlet weak var nombreCancion: UILabel! @IBOutlet weak var nombreArtista: UILabel! @IBOutlet weak var btMusica: UIButton! @IBOutlet weak var viewBTMusica: UIView! override func viewDidLoad() { super.viewDidLoad() // Configuracion de Navigation Bar title = "Detalles" self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil) // Muestra la informacion del momento lbNombre.text = (momentoDicc.value(forKey: "nombre") as! String) let fechaSeleccionada = momentoDicc.value(forKey: "fecha") as! Date let calendario = Calendar(identifier: .gregorian) let formateador = DateFormatter() formateador.dateFormat = "MMMM" let dia = calendario.component(.day, from: fechaSeleccionada) let mes = "\(formateador.string(from: fechaSeleccionada))" let año = calendario.component(.year, from: fechaSeleccionada) lbFecha.text = "\(dia) de \(mes) de \(año)" tfDescripcion.text = momentoDicc.value(forKey: "descripcion") as! String imagenFoto.image = UIImage(data: momentoDicc.value(forKey: "foto") as! Data, scale:1.0) // Si no existe musica oculta el boton de musica let urlCancion = momentoDicc.value(forKey: "musica") as! String if urlCancion != "" { let nombreCancionS = momentoDicc.value(forKey: "cancion") as? String let nombreArtistaS = momentoDicc.value(forKey: "artista") as? String nombreArtista.isHidden = false nombreArtista.isHidden = false btMusica.isHidden = false viewBTMusica.isHidden = false nombreArtista.text = nombreArtistaS nombreCancion.text = nombreCancionS } else { nombreArtista.isHidden = true nombreArtista.isHidden = true btMusica.isHidden = true viewBTMusica.isHidden = true } } override func viewWillDisappear(_ animated: Bool) { if let player = audioPlayer { btMusica.setImage(#imageLiteral(resourceName: "iconPlay"), for: .normal) player.stop() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func unwindEnviar(unwindSegue : UIStoryboardSegue) { } func recargaVista() { viewDidLoad(); } // Funcion que reproduce una cancion @IBAction func reproducirMusica(_ sender: UIButton) { let cancionURL = momentoDicc.value(forKey: "musica") as! String if cancionURL != "" { songURL = URL(string: cancionURL) audioPlayer = try? AVAudioPlayer(contentsOf: songURL!) // Detecta cuando termina de reproducirse una cancion audioPlayer.numberOfLoops = 0 audioPlayer.delegate = self if audioPlayer != nil { audioPlayer.prepareToPlay() } else { print("Song not found") } reproduciendo = !reproduciendo if let player = audioPlayer { if reproduciendo { player.play() btMusica.setImage(#imageLiteral(resourceName: "iconPause"), for: .normal) } else { btMusica.setImage(#imageLiteral(resourceName: "iconPlay"), for: .normal) player.stop() } } } } // Se llama cuando termina una cancion func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { reproduciendo = !reproduciendo if let player = audioPlayer { btMusica.setImage(#imageLiteral(resourceName: "iconPlay"), for: .normal) player.stop() } } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let viewModificar = segue.destination as! ViewControllerAgregarMomento viewModificar.nombrePantalla = "Modificar Momento" viewModificar.momentoDicc = momentoDicc viewModificar.anterior = anterior viewModificar.indexPath = indexPath } // MARK: - Funciones de bloqueo de Orientación override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return UIInterfaceOrientationMask.landscape } override var shouldAutorotate: Bool { return false } }
// // RootImageViewLabelCollectionViewCell.swift // TeadsSampleApp // // Created by Thibaud Saint-Etienne on 16/10/2020. // Copyright © 2020 Teads. All rights reserved. // import UIKit class RootImageViewLabelCollectionViewCell: UICollectionViewCell { @IBOutlet var imageView: UIImageView! @IBOutlet var label: UILabel! override func awakeFromNib() { super.awakeFromNib() layer.cornerRadius = 12 layer.borderWidth = 1 layer.borderColor = UIColor.teadsGray.cgColor label.textColor = .teadsGray } override var isHighlighted: Bool { didSet { UIView.animate(withDuration: 0.1) { if self.isHighlighted { self.alpha = 0.5 } else { self.alpha = 1 } } } } }
// // ViewsFactory.swift // github-usersbook // // Created by Lukasz Gajewski on 06/08/2019. // Copyright © 2019 Lukasz. All rights reserved. // import Foundation import UIKit public class ViewsFactory { public static func view(forBackground backgroundColor: UIColor, forAutoresizingMaskIntoConstraints translatesAutoresizingMaskIntoConstraints: Bool) -> UIView { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = translatesAutoresizingMaskIntoConstraints view.backgroundColor = backgroundColor view.layer.masksToBounds = false view.layer.shadowColor = UIColor.black.cgColor view.layer.shadowOpacity = 0.1 view.layer.shadowOffset = CGSize(width: 8, height: 8) view.layer.shadowRadius = 15 view.layer.borderColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1) view.layer.borderWidth = 0.3 view.layer.cornerRadius = 15 view.clipsToBounds = false view.isUserInteractionEnabled = false return view } public static func label(text: String, color: UIColor, numberOfLines: Int, fontSize: CGFloat) -> UILabel { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = text label.textAlignment = .left label.textColor = color label.numberOfLines = numberOfLines label.font = UIFont(name: "HelveticaNeue-Light", size: fontSize) return label } public static func imageView(image: UIImage? = nil, forAutoresizingMaskIntoConstraints translatesAutoresizingMaskIntoConstraints: Bool) -> UIImageView { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = translatesAutoresizingMaskIntoConstraints imageView.contentMode = .scaleAspectFit imageView.clipsToBounds = true return imageView } }
// // DashBoardViewController.swift // NV_ORG // // Created by Netventure on 28/03/20. // Copyright © 2020 netventure. All rights reserved. // import UIKit class DashBoardViewController: UIViewController { @IBOutlet weak var dashBoardTableView: UITableView! @IBOutlet weak var profileImageButton: UIButton! var dashModel : DashBoardResponseModel? = nil var dashViewModel : DashBoardViewModel? internal var delegate : DashBoardViewModelDelegateProtocol! var updateCellContentsTimer : Timer! var updateAdvertisementTimer : Timer! var newsListcount = 0 var advertisementListCount = 0 var swipeLeft : UISwipeGestureRecognizer! override func viewDidLoad() { super.viewDidLoad() setUI() } @IBAction func profileButtonTapped(_ sender: Any) { dashViewModel!.moveToMenuPage(viewController: self, model: self.dashModel) } @objc func backButton(){ dashViewModel!.skipButtontapped(view: self) } } //MARK:- userDefined Functions extension DashBoardViewController : DashBoardViewModelViewControllerDelegateProtocol{ func setUI(){ updateCellContentsTimer = Timer.scheduledTimer(timeInterval: 7,target: self,selector: #selector(self.updateCells),userInfo: nil, repeats: true) updateAdvertisementTimer = Timer.scheduledTimer(timeInterval: 10,target: self,selector: #selector(self.updateAdvertisementCells),userInfo: nil, repeats: true) dashViewModel = DashBoardViewModel() let _tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(backButton)) self.view.addGestureRecognizer(_tap) profileImageButton.setCornerRadius(radius: self.profileImageButton.frame.height / 2, bg_Color: .clear) dashViewModel?.delegate = self callApi() } func callApi(){ Webservice.shared.dsashBoardRequest { (model, erroe) in debugPrint(model) if model != nil { self.dashModel = model self.dashViewModel!.setDashBoardCell(model: (self.dashModel?.data)!) self.dashBoardFeedAPI() } } } @objc func updateCells(){ if let _ = dashBoardTableView{ if self.dashBoardTableView.numberOfRows(inSection: 0) != 0{ newsListcount = (newsListcount == (self.dashViewModel?.dashBoardFeedModel?.data?.news_list!.count)! ? 0 : newsListcount) self.dashBoardTableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .left) } } } @objc func updateAdvertisementCells(){ if let _ = dashBoardTableView{ if self.dashBoardTableView.numberOfRows(inSection: 0) != 0{ advertisementListCount = (advertisementListCount == (self.dashViewModel?.dashBoardFeedModel?.data?.advertisement_list!.count)! ? 0 : advertisementListCount) self.dashBoardTableView.reloadRows(at: [IndexPath(row: 6, section: 0)], with: .left) } //advertisementListCount } } func dashBoardFeedAPI(){ Webservice.shared.dashBoardFeed(body: self.dashViewModel!.request!.updateDic) { (model, message) in if model != nil{ self.dashViewModel?.dashBoardFeedModel = model DispatchQueue.main.async { self.dashBoardTableView.reloadData() } } } } } extension DashBoardViewController:UITableViewDelegate,UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return self.dashViewModel!.numberofSections } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (self.dashViewModel?.numberOfRowsInSection(section))! } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = DashBoardTableViewCell() switch self.dashViewModel?.mainCell[indexPath.row] { case "DashBoardTableViewCell0": cell = tableView.dequeueReusableCell(withIdentifier: "DashBoardTableViewCell0", for: indexPath) as! DashBoardTableViewCell if !(self.dashViewModel?.dashBoardFeedModel?.data?.news_list!.isEmpty)!{ if (self.dashViewModel?.dashBoardFeedModel?.data?.news_list!.count)! - 1 == newsListcount{ newsListcount = 0 }else{ newsListcount += 1 } cell.newsTitleLabel.text = (self.dashViewModel?.dashBoardFeedModel?.data?.news_list![newsListcount].news_name)! cell.newsDescriptionLabel.text = (self.dashViewModel?.dashBoardFeedModel?.data?.news_list![newsListcount].news_brief)! cell.newsImageView.sd_setImage(with: URL(string: (self.dashViewModel?.dashBoardFeedModel?.data?.news_list![newsListcount].news_url)!), placeholderImage: UIImage(named: "event.png"), options: .continueInBackground, completed: nil) swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.ImageViewSwipedLeft(sender:))) swipeLeft.delegate = self cell.newsImageView?.addGestureRecognizer(swipeLeft) // return cell } case "DashBoardTableViewCell1": cell = tableView.dequeueReusableCell(withIdentifier: "DashBoardTableViewCell1", for: indexPath) as! DashBoardTableViewCell cell.eventsCollectionView.dataSource = self cell.eventsCollectionView.delegate = self cell.eventsCollectionView.tag = 1 cell.eventsCollectionView.layoutIfNeeded() cell.eventsCollectionView.reloadData() // return cell case "DashBoardTableViewCell2": cell = tableView.dequeueReusableCell(withIdentifier: "DashBoardTableViewCell2", for: indexPath) as! DashBoardTableViewCell cell.meetingsCollectionView.dataSource = self cell.meetingsCollectionView.delegate = self cell.meetingsCollectionView.tag = 2 cell.meetingsCollectionView.layoutIfNeeded() cell.meetingsCollectionView.reloadData() case "DashBoardTableViewCell3": cell = tableView.dequeueReusableCell(withIdentifier: "DashBoardTableViewCell3", for: indexPath) as! DashBoardTableViewCell cell.WishesCollectionView.dataSource = self cell.WishesCollectionView.delegate = self cell.WishesCollectionView.tag = 3 cell.WishesCollectionView.layoutIfNeeded() cell.WishesCollectionView.reloadData() case "DashBoardTableViewCell4": cell = tableView.dequeueReusableCell(withIdentifier: "DashBoardTableViewCell4", for: indexPath) as! DashBoardTableViewCell if !(self.dashViewModel?.dashBoardFeedModel?.data?.job_vacancy_list!.isEmpty)!{ cell.jobTitle.text = (self.dashViewModel?.dashBoardFeedModel?.data?.job_vacancy_list![0].job_vacancy_name)! cell.jobExperienceLabel.text = (self.dashViewModel?.dashBoardFeedModel?.data?.job_vacancy_list![0].job_vacancy_occasion)! cell.jobSalaryLabel.text = (self.dashViewModel?.dashBoardFeedModel?.data?.job_vacancy_list![0].job_vacancy_occasion)! } case "DashBoardTableViewCell5": cell = tableView.dequeueReusableCell(withIdentifier: "DashBoardTableViewCell5", for: indexPath) as! DashBoardTableViewCell cell.galleryCollectionView.dataSource = self cell.galleryCollectionView.delegate = self cell.galleryCollectionView.tag = 5 cell.galleryCollectionView.layoutIfNeeded() cell.galleryCollectionView.reloadData() case "DashBoardTableViewCell6": cell = tableView.dequeueReusableCell(withIdentifier: "DashBoardTableViewCell6", for: indexPath) as! DashBoardTableViewCell if !(self.dashViewModel?.dashBoardFeedModel?.data?.advertisement_list!.isEmpty)!{ if (self.dashViewModel?.dashBoardFeedModel?.data?.advertisement_list!.count)! - 1 == advertisementListCount{ advertisementListCount = 0 }else{ advertisementListCount += 1 } cell.advertisementImageView.sd_setImage(with: URL(string: (self.dashViewModel?.dashBoardFeedModel?.data?.advertisement_list![advertisementListCount].advertisement_image_url)!), placeholderImage: UIImage(named: "events.png"), options: .continueInBackground, completed: nil) } default: return UITableViewCell() } return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let heightForRow : CGFloat! switch indexPath.row { case 0: heightForRow = !(self.dashViewModel?.dashBoardFeedModel?.data?.news_list!.isEmpty)! ? 200 : 0 case 1: heightForRow = !(self.dashViewModel?.dashBoardFeedModel?.data?.event_list!.isEmpty)! ? 300 : 0 case 2: heightForRow = !(self.dashViewModel?.dashBoardFeedModel?.data?.meetings_list!.isEmpty)! ? 150 : 0 case 3: heightForRow = !(self.dashViewModel?.dashBoardFeedModel?.data?.celebration_list!.isEmpty)! ? 150 : 0 case 4: heightForRow = !(self.dashViewModel?.dashBoardFeedModel?.data?.job_vacancy_list!.isEmpty)! ? 130 : 0 case 5: heightForRow = !(self.dashViewModel?.dashBoardFeedModel?.data?.gallery_list!.isEmpty)! ? 170 : 0 case 6: heightForRow = !(self.dashViewModel?.dashBoardFeedModel?.data?.advertisement_list!.isEmpty)! ? 150 : 0 default: heightForRow = UITableView.automaticDimension } return heightForRow } } extension DashBoardViewController: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView.tag == 5{ return (self.dashViewModel?.dashBoardFeedModel?.data?.gallery_list?.count)! }else if collectionView.tag == 1{ return (self.dashViewModel?.dashBoardFeedModel?.data?.event_list?.count)! }else if collectionView.tag == 2{ return (self.dashViewModel?.dashBoardFeedModel?.data?.meetings_list?.count)! }else{ return (self.dashViewModel?.dashBoardFeedModel?.data?.celebration_list?.count)! } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { var cell = DashBoardCollectionViewCell() switch collectionView.tag{ case 0,4,6: break case 1: cell = collectionView.dequeueReusableCell(withReuseIdentifier:"DashBoardCollectionViewCell" , for: indexPath) as! DashBoardCollectionViewCell if !(self.dashViewModel?.dashBoardFeedModel?.data?.event_list!.isEmpty)!{ cell.eventNameLabel.text = (self.dashViewModel?.dashBoardFeedModel?.data?.event_list![indexPath.row].event_name)! cell.eventOrganiserLabel.text = (self.dashViewModel?.dashBoardFeedModel?.data?.event_list![indexPath.row].event_brief)! cell.eventDateLabel.text = (self.dashViewModel?.dashBoardFeedModel?.data?.event_list![indexPath.row].event_date)! cell.eventsImageView.sd_setImage(with: URL(string: (self.dashViewModel?.dashBoardFeedModel?.data?.event_list![indexPath.row].event_url)!), placeholderImage: UIImage(named: "events.png"), options: .continueInBackground, completed: nil) return cell }else{ return cell } case 2: cell = collectionView.dequeueReusableCell(withReuseIdentifier:"DashBoardCollectionViewCell" , for: indexPath) as! DashBoardCollectionViewCell if !(self.dashViewModel?.dashBoardFeedModel?.data?.meetings_list!.isEmpty)!{ cell.meetingNameLabel.text = (self.dashViewModel?.dashBoardFeedModel?.data?.meetings_list![indexPath.row].meeting_name)! cell.meetingDateLabel.text = (self.dashViewModel?.dashBoardFeedModel?.data?.meetings_list![indexPath.row].meeting_date)! cell.meetingTimeLabel.text = (self.dashViewModel?.dashBoardFeedModel?.data?.meetings_list![indexPath.row].meeting_city)! return cell }else{ return cell } case 3: cell = collectionView.dequeueReusableCell(withReuseIdentifier:"DashBoardCollectionViewCell" , for: indexPath) as! DashBoardCollectionViewCell if !(self.dashViewModel?.dashBoardFeedModel?.data?.celebration_list!.isEmpty)!{ cell.wishesNameLabel.text = (self.dashViewModel?.dashBoardFeedModel?.data?.celebration_list![indexPath.row].celebration_name)! cell.wishesTitleLabel.text = (self.dashViewModel?.dashBoardFeedModel?.data?.celebration_list![indexPath.row].celebration_occasion)! cell.wishesImageView.sd_setImage(with: URL(string: (self.dashViewModel?.dashBoardFeedModel?.data?.celebration_list![indexPath.row].celebration_name)!), placeholderImage: UIImage(named: "profile.png"), options: .continueInBackground, completed: nil) return cell }else{ return cell } case 5: cell = collectionView.dequeueReusableCell(withReuseIdentifier:"DashBoardCollectionViewCell" , for: indexPath) as! DashBoardCollectionViewCell if !(self.dashViewModel?.dashBoardFeedModel?.data?.gallery_list!.isEmpty)!{ cell.galleryImageView.sd_setImage(with: URL(string: (self.dashViewModel?.dashBoardFeedModel?.data?.gallery_list![indexPath.row].gallery_URL)!), placeholderImage: UIImage(named: "events.png"), options: .continueInBackground, completed: nil) return cell }else{ return cell } default : return cell } return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let width = self.dashBoardTableView.frame.size.width if collectionView.tag == 2{ return CGSize(width: width - 30, height: 150) } if collectionView.tag == 3{ return CGSize(width: (self.dashViewModel?.dashBoardFeedModel?.data?.celebration_list!.count)! == 1 ? width - 30 : width - 50, height: 120) } if collectionView.tag == 5{ return CGSize(width: (self.dashViewModel?.dashBoardFeedModel?.data?.gallery_list!.count)! == 1 ? width - 30 : width - 50, height: 150) } else{ return CGSize(width: width - 30, height: (collectionView.tag == 0 ? 240 : 300)) } } } extension DashBoardViewController : UIGestureRecognizerDelegate{ @objc func ImageViewSwipedLeft(sender: UISwipeGestureRecognizer) { if sender.direction == .left{ newsListcount += 1 updateCells() } print("labelSwipedLeft called") } }
// // Factory.swift // LemonadeStand // // Created by David Vences Vaquero on 3/5/15. // Copyright (c) 2015 David. All rights reserved. // import Foundation class Factory { class func weather() -> Int { var maxCustomers = 10 var customerMultiplier:Double = 1 var weatherRandomiser = Int(arc4random_uniform(UInt32(3))) switch weatherRandomiser{ case 0: customerMultiplier = 1.4 case 1: customerMultiplier = 0.6 case 2: customerMultiplier = 1 default: println("error") } maxCustomers = Int((Double(maxCustomers) * customerMultiplier)) println("customerMultiplier = \(customerMultiplier)") return maxCustomers } class func customerArrayCreator() -> [Customer] { var customers:[Customer] = [] var numberOfCustomers = Factory.weather() var customer:Customer? for var customerNumber = 0; customerNumber < numberOfCustomers; customerNumber++ { var customer = Factory.customerCreator() customers.append(customer) println("\(customerNumber) created") } println("\(customers.count) elementos en el array") println("\(numberOfCustomers) tendrían que venir debido al tiempo") return customers } class func customerCreator() -> Customer { var randomNumber = Double(Int(arc4random_uniform(UInt32(11)))) / 10 var customer: Customer? if randomNumber < 0.4 { customer = Customer(tasteRange: 1, tasteRangeString: "acid") println("al cliente le gusta \(customer?.tasteRangeString)") } else if randomNumber > 0.6 { customer = Customer(tasteRange: 3, tasteRangeString: "diluted") println("al cliente le gusta \(customer?.tasteRangeString)") } else { customer = Customer(tasteRange: 2, tasteRangeString: "medium") println("al cliente le gusta \(customer?.tasteRangeString)") } println("he creado un cliente que\(customer?.tasteRangeString), número de gusto \(customer?.tasteRange)") return customer! } }
// // User.swift // Jock // // Created by HD on 15/3/13. // Copyright (c) 2015年 Haidy. All rights reserved. // import UIKit class User { var created_at: Int64? var last_device: String! var role = "" var last_visited_at: Int64? var state = "" var login = "" var id = "" var icon: String! var email: String! func saveValue(config: BaseConfig) { config.saveValue(created_at!, key: "created_at") config.saveValue(last_device, key: "last_device") config.saveValue(role, key: "role") config.saveValue(last_visited_at!, key: "last_visited_at") config.saveValue(state, key: "state") config.saveValue(login, key: "login") config.saveValue(id, key: "id") config.saveValue(icon, key: "icon") config.saveValue(email, key: "email") } ///解析数据 class func analyse(json: JSON) -> User! { var user = User() user.created_at = json["created_at"].int64Value user.last_device = json["last_device"].string user.role = json["role"].string! user.last_visited_at = json["last_visited_at"].int64Value user.state = json["state"].string! user.login = json["login"].string! user.id = json["id"].string! user.icon = json["icon"].string user.email = json["email"].string return user } }
// // MessageHUDProtocol.swift // PaiBaoTang // // Created by ZJaDe on 2017/7/6. // Copyright © 2017年 Z_JaDe. All rights reserved. // #if canImport(MBProgressHUD) import Foundation extension UIViewController: MessageHUDProtocol {} public protocol MessageHUDProtocol: AssociatedObjectProtocol { func showMessage(_ message: String) -> HUD func resetMessage(_ message: String) -> HUD func hideMessage(_ message: String) func showSuccess(_ text: String) func showSuccess(_ text: String, delay: TimeInterval) func showError(_ text: String) func showError(_ text: String, delay: TimeInterval) } private var hudKey: UInt8 = 0 private var messageArrKey: UInt8 = 0 extension MessageHUDProtocol { private var hud: HUD { associatedObject(&hudKey, createIfNeed: HUD()) } private var messageArr: [String] { get {return associatedObject(&messageArrKey, createIfNeed: [])} set {setAssociatedObject(&messageArrKey, newValue)} } } extension MessageHUDProtocol where Self: UIViewController { fileprivate func show() { DispatchQueue.main.async { self.hud._hud.label.numberOfLines = 0 self.hud.text = self.messageArr.last ?? "" self.hud.show(to: self.view) } } fileprivate func hide() { DispatchQueue.main.async { self.hud.hide() } } fileprivate func update() { if self.messageArr.isNotEmpty { self.show() } else { self.hide() } } } public extension MessageHUDProtocol where Self: UIViewController { @discardableResult func showMessage(_ message: String) -> HUD { self.messageArr.append(message) self.show() return self.hud } @discardableResult func resetMessage(_ message: String) -> HUD { self.messageArr = [message] self.show() return self.hud } func hideMessage(_ message: String = "") { if let index = self.messageArr.firstIndex(of: message) { self.messageArr.remove(at: index) } else { _ = self.messageArr.popLast() } self.update() } func showSuccess(_ text: String) { HUD.showSuccess(text, to: self.view) } func showSuccess(_ text: String, delay: TimeInterval) { HUD.showSuccess(text, delay: delay, to: self.view) } func showError(_ text: String) { HUD.showError(text, to: self.view) } func showError(_ text: String, delay: TimeInterval) { HUD.showError(text, delay: delay, to: self.view) } } #endif
// // ProfileViewController.swift // AutoLayout // // Created by mac on 02.10.2021. // import UIKit class ProfileViewController: UIViewController, UIScrollViewDelegate { private lazy var headView = ProfilePreviewView() private let mainStackView = UIStackView() private let scrollView = UIScrollView() private let settingButton: UIButton = { let button = UIButton(type: .system) button.translatesAutoresizingMaskIntoConstraints = false button.setTitleColor(.white, for: .normal) button.setTitle("Settings", for: .normal) button.layer.borderColor = UIColor.lightGray.cgColor button.layer.borderWidth = 1.0 button.layer.cornerRadius = 37.5 button.backgroundColor = .blue return button }() override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.backgroundColor = .systemGray4 setupScrollView() setupMainStackView() setupCallButton() } private func setupHeadView() { mainStackView.addArrangedSubview(headView) headView.translatesAutoresizingMaskIntoConstraints = false headView.heightAnchor.constraint(equalToConstant: 300).isActive = true } private func setupMainStackView() { mainStackView.axis = .vertical mainStackView.distribution = .equalSpacing mainStackView.translatesAutoresizingMaskIntoConstraints = false mainStackView.backgroundColor = .systemBackground scrollView.addSubview(mainStackView) let contentLayoutGuide = scrollView.contentLayoutGuide NSLayoutConstraint.activate([ mainStackView.widthAnchor.constraint(equalTo: view.widthAnchor), mainStackView.leadingAnchor.constraint(equalTo: contentLayoutGuide.leadingAnchor), mainStackView.trailingAnchor.constraint(equalTo: contentLayoutGuide.trailingAnchor), mainStackView.topAnchor.constraint(equalTo: contentLayoutGuide.topAnchor), mainStackView.bottomAnchor.constraint(equalTo: contentLayoutGuide.bottomAnchor) ]) setupHeadView() setupButtons() } private func setupScrollView() { scrollView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scrollView) let frameLayoutGuide = scrollView.frameLayoutGuide NSLayoutConstraint.activate([ frameLayoutGuide.leadingAnchor.constraint(equalTo: view.leadingAnchor), frameLayoutGuide.trailingAnchor.constraint(equalTo: view.trailingAnchor), frameLayoutGuide.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), frameLayoutGuide.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) ]) } } extension ProfileViewController { private func createButton(text: String, color: UIColor = .blue) -> UIButton { let button = UIButton(type: .system) button.translatesAutoresizingMaskIntoConstraints = false button.heightAnchor.constraint(equalToConstant: 55).isActive = true button.setTitle(text, for: .normal) button.setTitleColor(color, for: .normal) button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 35, bottom: 0, right: 0) button.contentHorizontalAlignment = .left button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside) return button } func setupButtons() { let buttonTitles = [ "Share Profile", "Favorites Messages", "Saved Messages", "Bookmarks", "History", "Notifications", "Find Friends", "Security", "Help", "Logout"] let buttonStack = UIStackView() buttonStack.translatesAutoresizingMaskIntoConstraints = false buttonStack.alignment = .fill buttonStack.axis = .vertical buttonStack.distribution = .equalSpacing buttonTitles.forEach { (buttonTitle) in buttonStack.addArrangedSubview(createButton(text: buttonTitle)) } mainStackView.addArrangedSubview(buttonStack) NSLayoutConstraint.activate([ buttonStack.widthAnchor.constraint(equalTo: mainStackView.widthAnchor), buttonStack.centerXAnchor.constraint(equalTo: mainStackView.centerXAnchor) ]) } @objc private func buttonPressed(_ sender: UIButton) { let buttonTitle = sender.titleLabel?.text ?? "" let message = "\(buttonTitle) button has been pressed" let alert = UIAlertController( title: "Button Pressed", message: message, preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default) alert.addAction(action) present(alert, animated: true, completion: nil) } private func setupCallButton() { scrollView.addSubview(settingButton) NSLayoutConstraint.activate([ settingButton.widthAnchor.constraint(equalToConstant: 75), settingButton.heightAnchor.constraint(equalToConstant: 75), settingButton.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor, constant: -20), settingButton.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor, constant: -50), ]) } }
// // ProtocolShowViewController.swift // szenzormodalitasok // // Created by Tóth Zoltán on 2021. 05. 09.. // Copyright © 2021. Tóth Zoltán. All rights reserved. // // Imports import UIKit import WebKit // ProtocolShowViewController class ProtocolShowViewController : UIViewController { // Variables struct Args { var url: String } var pdfArgs = Args(url: "") // IBOutlets @IBOutlet weak var pdfWebKit: WKWebView! // viewDidLoad func override func viewDidLoad() { super.viewDidLoad() guard let url = URL(string: pdfArgs.url) else { return } pdfWebKit.load(URLRequest(url: url)) } }
// // LoginPresenter.swift // ios_viper // // Created by KHURSHIDBEK on 2019/11/08. // Copyright © 2019 UHanaro. All rights reserved. // import Foundation protocol LoginPresenterProtocol: LoginRequestProtocol { // To Interactor func apiLogin(email:String, password: String) // To Routing func naviagteHomeScreen() } class LoginPresenter: LoginPresenterProtocol{ var ineractor: LoginInteractorProtocol! var routing: LoginRoutingProtocol! func apiLogin(email: String, password: String) { ineractor.apiLogin(email: email, password: password) } func naviagteHomeScreen() { routing.naviagteHomeScreen() } }
// // CharacterDetailViewController.swift // RickAndMortyInfo // // Created by Richmond Ko on 11/04/2018. // Copyright © 2018 Richmond Ko. All rights reserved. // import UIKit class CharacterDetailViewController: UIViewController { // MARK: - Stored var character: Character? // MARK: - Stored (IBOutlet) @IBOutlet var characterAvatarImageView: UIImageView! @IBOutlet var nameLabel: UILabel! @IBOutlet var idAndCreatedLabel: UILabel! @IBOutlet var statusLabel: UILabel! @IBOutlet var speciesLabel: UILabel! @IBOutlet var genderLabel: UILabel! @IBOutlet var originLabel: UILabel! @IBOutlet var lastLocationLabel: UILabel! @IBOutlet var episodeListLabel: UILabel! // MARK: - App View Life Cycle override func viewDidLoad() { super.viewDidLoad() setCharacterData() configureAvatarImageView() } // MARK: - Instance private func configureAvatarImageView() { characterAvatarImageView.layer.cornerRadius = characterAvatarImageView.frame.size.width / 2 characterAvatarImageView.layer.masksToBounds = true } private func setCharacterData() { guard let character = character else { return } if let url = URL(string: character.image) { characterAvatarImageView.kf.setImage(with: url, placeholder: nil, options: [.transition(.fade(0.2))], progressBlock: nil, completionHandler: nil) } else { characterAvatarImageView.image = nil } nameLabel.text = character.name idAndCreatedLabel.text = "id: \(character.id) - created at \(character.created)" statusLabel.text = character.status speciesLabel.text = character.species genderLabel.text = character.gender originLabel.text = character.origin.name lastLocationLabel.text = character.location.name episodeListLabel.text = "\(character.episode.debugDescription)" } }
// Playground - noun: a place where people can play import UIKit func permutations(s: [Int]) -> [[Int]] { var path = [Int]() var result = [[Int]]() helper(s.sorted(<), &path, &result) return result } func helper(s: [Int], inout path: [Int], inout result: [[Int]]) { if s.count == 0 { result.append(path) } else { for i in 0..<s.count { if i>0 && s[i] == s[i-1] { continue } let e = s[i] path.append(e) var newS = [Int](s) newS.removeAtIndex(i) helper(newS, &path, &result) path.removeLast() } } } permutations([1,1,2]) /*: Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example, [1,1,2] have the following unique permutations: [1,1,2], [1,2,1], and [2,1,1]. */
// // STTodoListViewController.swift // Sample ToDo // // Created by Arasuvel Theerthapathy on 19/12/16. // Copyright © 2016 Arasuvel Theerthapathy. All rights reserved. // import UIKit import Firebase import Foundation import FirebaseDatabase class Item { var ref: DatabaseReference? var title: String? init (snapshot: DataSnapshot) { ref = snapshot.ref let data = snapshot.value as! Dictionary<String, String> title = data["title"]! as String } } class STTodoListViewController: UIViewController { var user: User! var items = [Item]() var ref: DatabaseReference! private var databaseHandle: DatabaseHandle! @IBOutlet weak var tableView: UITableView! func startObservingDatabase () { databaseHandle = ref.child("users/\(self.user.uid)/items").observe(.value, with: { (snapshot) in var newItems = [Item]() for itemSnapShot in snapshot.children { let item = Item(snapshot: itemSnapShot as! DataSnapshot) newItems.append(item) } self.items = newItems self.tableView.reloadData() }) } deinit { ref.child("users/\(self.user.uid)/items").removeObserver(withHandle: databaseHandle) } /* // 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. } */ } extension STTodoListViewController { override func viewDidLoad() { super.viewDidLoad() user = Auth.auth().currentUser ref = Database.database().reference() startObservingDatabase() if tableView != nil { tableView.tableFooterView = UIView() } } } extension STTodoListViewController { @IBAction func didTapSignOut(_ sender: UIBarButtonItem) { do { try Auth.auth().signOut() kAppDelegate.loginAsRootViewController() } catch let error { assertionFailure("Error signing out: \(error)") } } @IBAction func didTapAddItem(_ sender: UIBarButtonItem) { let prompt = UIAlertController(title: "To Do App", message: "To Do Item", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default) { (action) in let userInput = prompt.textFields![0].text if (userInput!.isEmpty) { return } self.ref.child("users").child(self.user.uid).child("items").childByAutoId().child("title").setValue(userInput) } prompt.addTextField(configurationHandler: nil) prompt.addAction(okAction) present(prompt, animated: true, completion: nil); } } // MARK: - Table view data source extension STTodoListViewController: UITableViewDelegate { } extension STTodoListViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TODOCell", for: indexPath) let item = items[indexPath.row] cell.textLabel?.text = item.title return cell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let item = items[indexPath.row] item.ref?.removeValue() } } } extension STTodoListViewController: DZNEmptyDataSetSource { func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? { let message = "Nothing to display" let attributedString: NSMutableAttributedString = NSMutableAttributedString(string:message, attributes:convertToOptionalNSAttributedStringKeyDictionary([convertFromNSAttributedStringKey(NSAttributedString.Key.font): UIFont.systemFont(ofSize: 20.0)])) return attributedString } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)}) } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String { return input.rawValue }
// // ChallengeTableViewController.swift // Gamin // // Created by yiling on 7/17/16. // Copyright © 2016 yiling. All rights reserved. // import UIKit import Firebase //MARK: Properties class ChallengeTableViewController: UITableViewController { var ref: FIRDatabaseReference! var challenges: [FIRDataSnapshot]! = [] private var _refHandle: FIRDatabaseHandle! override func viewDidLoad() { super.viewDidLoad() // self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "ChallengeTableViewCell") configureDatabase() // loadSampleChallenges() } // MARK: Firebase deinit { self.ref.child("challenges").removeObserverWithHandle(_refHandle) } func configureDatabase() { ref = FIRDatabase.database().reference() print(self.ref.child("challenges").URL) // Listen for new messages in the Firebase database _refHandle = self.ref.child("challenges").observeEventType(.ChildAdded, withBlock: { (snapshot) -> Void in self.challenges.append(snapshot) print("add") self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: self.challenges.count-1, inSection: 0)], withRowAnimation: .Automatic)//? }) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return challenges.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {//???? //Fetches the appropriate challenge for the data source layout //let challenge = challenges[indexPath.row] let cellIdentifier = "ChallengeTableViewCell" // Unpack message from Firebase DataSnapshot let challengeSnapshot: FIRDataSnapshot! = self.challenges[indexPath.row] let challenge = challengeSnapshot.value as! Dictionary<String, String> let name = challenge["name"] as String! let text = challenge["text"] as String! print(name) print(text) let cell: ChallengeTableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ChallengeTableViewCell cell.titleLabel?.text = name + ": " + text //cell!.imageView?.image = UIImage(named: "ic_account_circle") // let text = challenge[Constants.MessageFields.text] as String! //let image1 = UIImage(named: "Challenge1")! //cell.challengeImageView.image = image1 return cell } func loadSampleChallenges() { let image1 = UIImage(named: "Challenge1")! let challenge1 = Challenge(title: "Art Challenge", image: image1, detail: "Go to Nice and find the most beautiful place in Nice")! let image2 = UIImage(named: "Challenge2")! let challenge2 = Challenge(title: "Paul Challenge", image: image2, detail: "Find out the secret ingredients in beignet :)")! //challenges += [challenge1, challenge2] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // Constants.swift // Not Hotdog // // Created by Randy Hsu on 2019-02-02. // Copyright © 2019 DeveloperRandy. All rights reserved. // import Foundation import UIKit struct Constants { struct Green { static let Red:CGFloat = 0.18 static let Green:CGFloat = 0.80 static let Blue:CGFloat = 0.44 static let Alpha:CGFloat = 1.0 } struct Red { static let Red:CGFloat = 0.91 static let Green:CGFloat = 0.30 static let Blue:CGFloat = 0.24 static let Alpha:CGFloat = 1.0 } }
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" let lineBreaks = """ This string starts with a line break. It also ends with a line break. """ // INITIALIZING an EMPTY STRING // WORKING with CHARACTERS let catCharacters: [Character] = ["C", "A", "T", "!", "🐱"] let catstring = String(catCharacters) print(catstring) // UNICODE let eAcute: Character = "\u{E9}" let compinedEAcute: Character = "\u{65}\u{301}" let preAcute: Character = "\u{65}" let deAcute: Character = "\u{301}" let unusualMenagerie = "Koala 🐨, Snail 🐌, Penguin 🐧, Dromedary 🐪" print("unusualMenagerie has \(unusualMenagerie.count) characters") let menagerie = "🐌" print("unusualMenagerie has \(menagerie.count) characters") let greeting = "Guten Tag!" greeting[greeting.startIndex] greeting[greeting.index(after: greeting.startIndex)] let helloGreeting = "Hello, world!" let index = helloGreeting.first let romeoAndJuliet = [ "Act 1 Scene 1: Verona, A public place", "Act 1 Scene 2: Capulet's mansion", "Act 1 Scene 3: A room in Capulet's mansion", "Act 1 Scene 4: A street outside Capulet's mansion", "Act 1 Scene 5: The Great Hall in Capulet's mansion", "Act 2 Scene 1: Outside Capulet's mansion", "Act 2 Scene 2: Capulet's orchard", "Act 2 Scene 3: Outside Friar Lawrence's cell", "Act 2 Scene 4: A street in Verona", "Act 2 Scene 5: Capulet's mansion", "Act 2 Scene 6: Friar Lawrence's cell" ] var act1SceneCount = 0 for scene in romeoAndJuliet { if scene.hasPrefix("Act 1") { act1SceneCount += 1 } } print("There are \(act1SceneCount) scene in Act1") var mansionCount = 0 var cellCount = 0 for scene in romeoAndJuliet { if scene.hasSuffix("Capulet's mansion") { mansionCount += 1 } else if scene.hasSuffix("Friar Lawrence's cell") { cellCount += 1 } } print("\(mansionCount) mansion scenes; \(cellCount) cell scenes") let dogString = "Dog‼🐶" for codeUnit in dogString.utf8 { print("\(codeUnit)", terminator: "-") } print("") for scalar in dogString.unicodeScalars { print("\(scalar) ") }
// // ViewController.swift // iOSProject // // Created by Sinchon on 2021/04/21. // import UIKit class ViewController: UIViewController { @IBOutlet weak var label: UILabel! var timer:Timer! = nil //뷰 컨트롤러가 FirstResponder가 될 수 있도록 해주는 프로퍼티 재정의 override var canBecomeFirstResponder: Bool{ get{ return true } } override func viewDidLoad() { super.viewDidLoad() //뷰 컨트롤러가 FirstResponder가 되도록 설정 self.becomeFirstResponder() //바로 시작하는 타이머 생성 timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: {(timer) -> Void in //현재 날짜 및 시간 let date = Date() //날짜 및 시간을 문자열로 만들어주는 클래스의 객체 생성 let formatter = DateFormatter() //문자열 서식 설정 formatter.dateFormat = "yyyy-MM-dd ccc hh:mm:ss" let msg = formatter.string(from: date) //클로저에서는 클래스에 만든 프로퍼티를 직접 사용이 안 됨 //객체를 통해서 접근해야 함 self.label.text = msg }) //회전 label.transform = CGAffineTransform(rotationAngle: CGFloat.pi / 2.0) //선 모양 변경 label.layer.borderWidth = 3.0 label.layer.borderColor = UIColor.magenta.cgColor } //흔들기가 시작되면 호출되는 메서드 override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { NSLog("흔들기 시작") } }
// // LoginService.swift // // Created by Chuck Krutsinger on 2/4/19. // Copyright © 2019 Countermind, LLC. All rights reserved. // import Foundation import RxSwift enum LoginError: Error { case invalidCredentials } enum LoginResult { case success(user: User, jwt: JWT) case failure(error: LoginError) } typealias JWT = String //just for demo typealias Username = String typealias Password = String func mockLoginValidatorService(username: String, password: String) -> Observable<LoginResult> { return Single<LoginResult>.create { observer in //dispatch to simulate web service DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { //pause as if going to web //simulates invalid username by using "bogus" as username guard username != "bogus" else { observer(.success(LoginResult.failure(error: LoginError.invalidCredentials))) return } //simulates login failure by using "bogus" as password guard password != "bogus" else { observer(.success(LoginResult.failure(error: LoginError.invalidCredentials))) return } //accept any username/password combo that gets past the guard statements observer(.success(LoginResult.success(user: User(username: username), jwt: "SOMEJWTSTRINGWOULDGOHERE"))) } return Disposables.create() }.asObservable() }
import Foundation import CoreLocation public typealias SearchQuery = String public struct GooglePlacesNearbyQuerySearchParams { var latitude : CLLocationDegrees var longitude : CLLocationDegrees var keywords : SearchQuery public init(_ keywords:SearchQuery, latitude:CLLocationDegrees, longitude: CLLocationDegrees) { self.keywords = keywords self.latitude = latitude self.longitude = longitude } public init(_ keywords:SearchQuery, location: CLLocationCoordinate2D) { self.init(keywords, latitude:location.latitude, longitude:location.longitude) } }
import UIKit var str = "Hello, playground" func eagleRect(width: Int, height: Int){ if width <= 0 || height <= 0 { print("Cannot print a rectangle with zero dimension") } else { let eagle = "🦅" var row = "" for _ in 0..<width{ row = row + eagle } for _ in 0..<height{ print(row) } } } eagleRect(width: 3, height: 4)
// // NewProject // Copyright (c) Yuichi Nakayasu. All rights reserved. // import UIKit protocol DatePickerDayCellDelegate: class { func datePickerDayCell(_ cell: DatePickerDayCell, date: Date) } class DatePickerDayCell: CalendarViewDayCell { enum State { case `default` case today case selected } weak var delegate: DatePickerDayCellDelegate! @IBOutlet private weak var dayLabel: UILabel! @IBOutlet private weak var dayButton: UIButton! override var date: Date! { didSet { setupDayButton() if !month.isSameMonth(date) { visibleDayButton(false) return } visibleDayButton(true) dayLabel.text = date.day.string } } var state: State = .default { didSet { UIView.setAnimationsEnabled(false) if state == .default { dayLabel.backgroundColor = .clear dayLabel.textColor = #colorLiteral(red: 0.2078431373, green: 0.2196078431, blue: 0.2470588235, alpha: 1) } if state == .today { dayLabel.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1) dayLabel.textColor = #colorLiteral(red: 0.2078431373, green: 0.2196078431, blue: 0.2470588235, alpha: 1) } if state == .selected { dayLabel.backgroundColor = #colorLiteral(red: 0, green: 0.6352941176, blue: 0.6235294118, alpha: 1) dayLabel.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) } dayLabel.layoutIfNeeded() dayButton.layoutIfNeeded() UIView.setAnimationsEnabled(true) } } @IBAction private func didTapDayButton() { delegate.datePickerDayCell(self, date: date) } private func setupDayButton() { dayLabel.corner = dayLabel.frame.width / 2 dayButton.corner = dayButton.frame.width / 2 } private func visibleDayButton(_ visble: Bool) { dayLabel.isHidden = !visble dayButton.isHidden = !visble } }
// // TalkTableViewCell.swift // PyConJP2016 // // Created by Yutaro Muta on 2016/03/07. // Copyright © 2016 PyCon JP. All rights reserved. // import UIKit class TalkTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var placeLabel: UILabel! @IBOutlet weak var placeView: UIView! @IBOutlet weak var speakerLabel: UILabel! static let estimatedRowHeight: CGFloat = 134 override func prepareForReuse() { titleLabel.text = nil timeLabel.text = nil placeLabel.text = nil speakerLabel.text = nil placeView.backgroundColor = UIColor.darkGray } func fill(talkObject: TalkObject) { titleLabel.text = talkObject.title timeLabel.text = talkObject.periodTime placeLabel.text = talkObject.place speakerLabel.text = talkObject.speakers if let room = talkObject.room { placeView.backgroundColor = room.color } } }
// // CloudKitTestViewController.swift // Teachify // // Created by Marcel Hagmann on 13.04.18. // Copyright © 2018 Christian Pfeiffer. All rights reserved. // import UIKit import CloudKit class CloudKitTestViewController: UIViewController { @IBOutlet weak var sharingQRImageView: UIImageView! @IBOutlet weak var linkToShareTextField: UITextField! var classCtrl: TKClassController! var teacherCtrl: TKTeacherController! var subjectCtrl: TKSubjectController! var documentCtrl: TKDocumentController! var exerciseCtrl: TKExerciseController! var sharingCtrl: TKShareController! var settingsCtrl = TKSettingsController() // var solutionsCtrl: TKSolutionController! var userCtrl: TKUserProfileController! override func viewDidLoad() { super.viewDidLoad() linkToShareTextField.addTarget(self, action: #selector(linkInputDidChange), for: .editingChanged) } @IBAction func setUpForStudent(_ sender: UIButton) { let rank = TKRank.student initCtrl(withRank: rank) } @IBAction func setUpForTeacher(_ sender: UIButton) { let rank = TKRank.teacher initCtrl(withRank: rank) } func initCtrl(withRank rank: TKRank) { classCtrl = TKClassController() classCtrl.initialize(withRank: rank) { (succeed) in print("Class init --> \(String(describing: succeed))") } teacherCtrl = TKTeacherController() teacherCtrl.initialize(withRank: rank) { (succeed) in print("Teacher init --> \(String(describing: succeed))") } subjectCtrl = TKSubjectController() subjectCtrl.initialize(withRank: rank) { (succeed) in print("Subject init --> \(String(describing: succeed))") } documentCtrl = TKDocumentController() documentCtrl.initialize(withRank: rank) { (succeed) in print("Document init --> \(String(describing: succeed))") } exerciseCtrl = TKExerciseController() exerciseCtrl.initialize(withRank: rank) { (succeed) in print("Exercise init --> \(String(describing: succeed))") } // solutionsCtrl = TKSolutionController() // solutionsCtrl.initialize(withRank: rank) { (succeed) in // print("Solution init --> \(succeed)") // } userCtrl = TKUserProfileController() sharingCtrl = TKShareController(view: self.view) } // MARK: - IBActions @IBAction func shareSubjectAction(_ sender: UIButton) { let subjectNameToShare = "mhTEST_subject" shareASubject(subjectName: subjectNameToShare) } @IBAction func stopSharing(_ sender: UIButton) { let subjectNameToShare = "SubjectName17_123" self.subjectCtrl.fetchSubject { (allSubjects, error) in for subject in allSubjects { if subject.name == subjectNameToShare { let test = TKShareController(view: self.view) test.createCloudSharingController(forSubject: subject, withShareOption: .removeParticipant, completion: { (removeCtrl, error) in if let removeCtrl = removeCtrl { self.present(removeCtrl, animated: true) } }) } } } } @IBAction func fetchAllDocuments(_ sender: UIButton) { self.documentCtrl.fetchDocuments { (fetchedDocuments, error) in print("Number of Shared Documents: \(fetchedDocuments.count)") for document in fetchedDocuments { print("Shared Document Name: \(document.name)") } } } @IBAction func fetchAllSubjects(_ sender: UIButton) { self.subjectCtrl.fetchSubject { (fetchedSubjects, error) in print("Number of Shared Subjects: \(fetchedSubjects.count)") for subject in fetchedSubjects { print("Shared Subject Name: \(subject.name)") } } } @IBAction func fetchAllExercises(_ sender: UIButton) { self.exerciseCtrl.fetchExercises { (fetchedExercises, error) in print("Number of Shared Exercises: \(fetchedExercises.count)") for exercise in fetchedExercises { print("Shared Exercise Name: \(exercise.name)") } } } @IBAction func createNewDummyContent(_ sender: UIButton) { let alert = UIAlertController(title: "Create", message: "Hier wird automatisch ein Class, Subject, Document und Exercise Objekt erstellt und in die Cloud geladen.", preferredStyle: .alert) alert.addTextField(configurationHandler: nil) alert.addAction(UIAlertAction(title: "Abbrechen", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Create", style: .default, handler: { (_) in let text = alert.textFields![0].text! self.create(className: "\(text)_class", subjectName: "\(text)_subject", documentName: "\(text)_document", exerciseName: "\(text)_exercise") })) present(alert, animated: true) } @objc func linkInputDidChange() { if let inputString = linkToShareTextField.text { let qrCode = createQRCode(string: inputString) sharingQRImageView.image = qrCode } } // MARK: - Hilfsmethoden func createQRCode(string: String) -> UIImage? { let data = string.data(using: .ascii, allowLossyConversion: false) let filter = CIFilter(name: "CIQRCodeGenerator") filter?.setValue(data, forKey: "inputMessage") if let ciImage = filter?.outputImage { let highResolutionCIImageQR = ciImage.transformed(by: CGAffineTransform(scaleX: 20, y: 20)) return UIImage(ciImage: highResolutionCIImageQR) } return nil } // MARK: - Hilfsmethoden zum schnelleren testen der CloudController func create(className: String, subjectName: String, documentName: String, exerciseName: String) { let tkClass = TKClass(name: className) let tkSubject = TKSubject(name: subjectName, color: TKColor.red) let tkDocument = TKDocument(name: documentName, deadline: nil) let tkExercise = TKExercise(name: exerciseName, deadline: nil, type: .mathpiano, data: "Daaaata") self.classCtrl.create(tkClass: tkClass) { (createdClass, error) in print("Class Error: \(String(describing: error))") guard let createdClass = createdClass else { return } self.subjectCtrl.add(subject: tkSubject, toTKClass: createdClass, completion: { (createdSubject, error) in print("Subject Error: \(String(describing: error))") guard let createdSubject = createdSubject else { return } self.documentCtrl.add(document: tkDocument, toSubject: createdSubject, completion: { (createdDocument, error) in print("Document Error: \(String(describing: error))") guard let createdDocument = createdDocument else { return } self.exerciseCtrl.create(exercise: tkExercise, toDocument: createdDocument, completion: { (createdExercise, error) in print("Exercise Error: \(String(describing: error))") }) }) }) } } func createExercise() { let className = "17a" let subjectName = "Subject17" let documentName = "Document17" let exercise = TKExercise(name: "Aufgabe17", deadline: nil, type: .mathpiano, data: "Hello das ist die Dataaaaaa!") classCtrl.fetchClasses { (fetchedClasses, error) in for fetchedClass in fetchedClasses { if fetchedClass.name == className { self.subjectCtrl.fetchSubject(forClass: fetchedClass, withFetchSortOptions: [], completion: { (fetchedSubjects, error) in for subject in fetchedSubjects { if subject.name == subjectName { self.documentCtrl.fetchDocuments(forSubject: subject, completion: { (fetchedDocuments, error) in for document in fetchedDocuments { if document.name == documentName { self.exerciseCtrl.create(exercise: exercise, toDocument: document, completion: { (createdExercise, error) in print("error: \(error) -- \(String(describing: createdExercise?.name))") }) } } }) } } }) } } } } func shareASubject(subjectName: String) { self.subjectCtrl.fetchSubject { (fetchedSubjects, error) in print("subject error: \(String(describing: error)) -- count: \(fetchedSubjects.count)") for subject in fetchedSubjects { print("sss \(subject.name)") if subject.name == subjectName { self.sharingCtrl.createCloudSharingController(forSubject: subject, withShareOption: TKShareOption.addParticipant, completion: { (sharingViewCtrl, error) in print("Sharing Errors: \(String(describing: error))") if let sharingViewCtrl = sharingViewCtrl { self.present(sharingViewCtrl, animated: true) } }) } } } } @IBAction func solutionTestAction(_ sender: UIButton) { // exerciseCtrl.fetchExercises { (allExercises, error) in // for exercise in allExercises { // print(exercise.name) // } // } print("START") self.exerciseCtrl.fetchExercises { (allExercises, error) in for exercise in allExercises { print(exercise.name) } } print("ENDE") } // func fetchAllSolutions() { // solutionsCtrl.fetchSolutions { (allSolutions, error) in // for solution in allSolutions { // print(solution.userSolution) // } // } // } // // func deleteAllSolutions() { // solutionsCtrl.fetchSolutions { (allSolutions, error) in // for solution in allSolutions { // self.solutionsCtrl.delete(solution: solution, completion: { (error) in // print("solution-delete-error: \(error)") // }) // } // } // } // // func updateSoltution() { // solutionsCtrl.fetchSolutions { (allSolutions, error) in // for var solution in allSolutions { // solution.userSolution = "Muhahahahahahahaha :)))))))" // self.solutionsCtrl.update(solution: solution, completion: { (updatedSolution, error) in // print("error: \(error)") // }) // } // } // } // // func addSolution() { // CKContainer.default().fetchUserRecordID { (userRecordID, error) in // if let userRecordID = userRecordID { // let userID = userRecordID.recordName // let solution = TKSolution(userSolution: "This is my solution :)", status: .correct, owner: userID) // let test2 = TKSolution2(status: .correct, userSolution: "This is my solution :)))))", ownerID: userID) // // self.exerciseCtrl.fetchExercises(completion: { (allExercises, error) in // for var exercise in allExercises { // if exercise.name == "mhTEST_exercise" { // // // exercise.solutions = [test2] // // self.exerciseCtrl.update(exercise: exercise, completion: { (newExercise, error) in // print("---- > error: \(error) - \(newExercise)") // }) // // } // } // }) // // } else { // print("Solution upload error - id fetching failed: \(error)") // } // } // } @IBAction func userProfileAction(_ sender: UIButton) { // userCtrl.fetchUserProfile { (user, error) in // guard var user = user else { return } // user.firstname = "Vorname" // user.lastname = "Nachname" // user.image = UIImage(named: "Inder") // // self.userCtrl.update(user: user, completion: { (updatedUser, error) in // print("----> \(updatedUser)") // }) // // } userCtrl.fetchUserProfile { (user, error) in guard let user = user else { return } DispatchQueue.main.async { self.sharingQRImageView.image = user.image print("image: \(String(describing: user.image))") } } } }
// // MemesCollectionViewCell.swift // MemeMe // // Created by admin on 11/22/15. // Copyright © 2015 admin. All rights reserved. // import Foundation import UIKit class MemesCollectionViewCell: UICollectionViewCell { }
// // SOTManager.swift // SOTManager // // Created by Sven Svensson on 27/08/2021. // import Foundation class SOTManager: ObservableObject{ @Published var parents: [Parent] = [Parent]()// Parent.data init(){} init(parents: [Parent]){ self.parents = parents } func remove(at index:Int){ parents.remove(at: index) } func remove(atOffsets: IndexSet){ parents.remove(atOffsets: atOffsets) } func remove(_ parent: Parent){ guard let _pIndex = parents.firstIndex(where: {$0.id == parent.id}) else { print("SOTManager, remove - Parent Not found!") return } parents.remove(at: _pIndex) } func remove(atOffsets: IndexSet, toChildrenOf parent: Parent ){ guard let _pIndex = parents.firstIndex(where: {$0.id == parent.id}) else { print("SOTManager, remove - Parent Not found!") return } parents[_pIndex].children.remove(atOffsets: atOffsets) } func remove(_ child: Child){ guard let _pIndex = parents.firstIndex(where: {$0.children.contains(child) }), let _cIndex = parents[_pIndex].children.firstIndex(where: { $0.id == child.id }) else { print("SOTManager, remove - Parent Not found!") return } parents[_pIndex].children.remove(at: _cIndex) } func remove(atOffsets: IndexSet, toToysOf child: Child ){ guard let _pIndex = parents.firstIndex(where: {$0.children.contains(child) }), let _cIndex = parents[_pIndex].children.firstIndex(where: { $0.id == child.id }) else { print("SOTManager, remove - Parent Not found!") return } parents[_pIndex].children[_cIndex].toys.remove(atOffsets: atOffsets) } func remove(_ toy: Toy){ guard let _pIndex = parents.firstIndex(where: {$0.children.first (where: { $0.toys.contains(toy) }) != nil }), let _cIndex = parents[_pIndex].children.firstIndex(where: { $0.toys.contains(toy) }), let _tIndex = parents[_pIndex].children[_cIndex].toys.firstIndex(where: { $0.id == toy.id }) else { print("SOTManager, remove - Parent Not found!") return } parents[_pIndex].children[_cIndex].toys.remove(at: _tIndex) } func append(_ data: Parent.Data){ let newParent = Parent( id: UUID(), name: data.name, children: data.children) parents.append(newParent) } func append(_ data: Child.Data, toChildrenOf parent: Parent){ guard let _pIndex = parents.firstIndex(where: {$0.id == parent.id}) else { print("SOTManager, append - Parent Not found!") return } let newChild = Child( id: UUID(), name: data.name, toys: data.toys) parents[_pIndex].children.append(newChild) } func append(_ data: Toy.Data, toToysOf child: Child){ guard let _pIndex = parents.firstIndex(where: {$0.children.contains(where: { $0.id == child.id }) }), let _cIndex = parents[_pIndex].children.firstIndex(where: { $0.id == child.id }) else { print("SOTManager, append - Parent Not found!") return } let newToy = Toy( id: UUID(), name: data.name) parents[_pIndex].children[_cIndex].toys.append(newToy) } func update(_ parent: Parent, from data: Parent.Data){ for pIndex in 0..<parents.count { if parents[pIndex].id == parent.id { parents[pIndex].update(from: data) break } } } func update(_ child: Child, from data: Child.Data){ outerloop: for pIndex in 0..<parents.count { for cIndex in 0..<parents[pIndex].children.count { if parents[pIndex].children[cIndex].id == child.id { parents[pIndex].children[cIndex].update(from: data) break outerloop } } } } func update(_ toy: Toy, from data: Toy.Data){ // find parent containing child containing toy outerloop: for pIndex in 0..<parents.count { for cIndex in 0..<parents[pIndex].children.count { for tIndex in 0..<parents[pIndex].children[cIndex].toys.count { if parents[pIndex].children[cIndex].toys[tIndex].id == toy.id { parents[pIndex].children[cIndex].toys[tIndex].update(from: data) break outerloop } } } } } static var emptyState: SOTManager { let manager = SOTManager() manager.parents = [] return manager } static var fullState: SOTManager { let manager = SOTManager() manager.parents = Parent.data return manager } }
// // Utilities.swift // Focus // // Created by William Wu on 10/15/19. // Copyright © 2019 Project Pinnacles. All rights reserved. // import Foundation class Utilities { static func generatePasswd() -> String { var rtn = ""; for _ in 1...6 { rtn += String(Int.random(in: 0..<10)); } return rtn; } public var totalSec = 0; public var sessionSec = 0; public var isTimer = false; func writeToConfig() { let defaults = UserDefaults.standard; let curr = defaults.integer(forKey: "focusedSec") + totalSec; defaults.set(curr, forKey: "focusedSec"); sessionSec += totalSec; totalSec = 0; } }
// // WorkType.swift // GV24 // // Created by Macbook Solution on 6/28/17. // Copyright © 2017 admin. All rights reserved. // import Foundation import SwiftyJSON class WorkType: AppModel { var id: String? var image: String? var name: String? var workDescription : String? var title : String? var weight : Int? var price : NSNumber? var tools : Bool? = false var suggests : [Suggest] = [Suggest]() override init() { super.init() } override init(json: JSON) { super.init(json: json) self.id = json["_id"].string self.image = json["image"].string self.name = json["name"].string self.workDescription = json["description"].string self.title = json["title"].string self.price = json["price"].number self.weight = json["weight"].int self.tools = json["tools"].bool let suggetsJson = json["suggest"].arrayValue for suggestData in (suggetsJson as [JSON]) { self.suggests.append(Suggest(json: suggestData)) } } } class Suggest : AppModel{ var id : String? var name : String? override init() { super.init() } override init(json: JSON) { super.init(json: json) self.id = json["_id"].string self.name = json["name"].string } }
// // AddConversacionController.swift // Citious_IOs // // Created by Manuel Citious on 1/4/15. // Copyright (c) 2015 Citious Team. All rights reserved. // import UIKit import MobileCoreServices import AVFoundation var vieneDeListadoMensajes = false var hacerFoto = false class AddConversacionController: UIViewController, UITableViewDataSource, UITableViewDelegate { //Variables var userKey:String! var userName:String! var conversacionNueva:Bool! var mensajeAlert = "" var tituloAlert = "" var conversationKey = "" var listaMensajes = [MessageModel]() var listaMensajesPaginada = [MessageModel]() var indicePaginado = 0 var moverUltimaFila = true var keyboardFrame: CGRect = CGRect.null var keyboardIsShowing: Bool = false var mostrarMensajesAnteriores:Bool = false let llamarInfoCellId = "llamarInfoCell" let cargarMensajesAnterioresId = "CargarMensajesAnteriores" let pdfEncuenstaCellId = "pdfEncuesta" let mensajePdf = "Abrir Pdf" let mensajeEncuesta = "Realizar encuesta" let mensajeRealizdaEncuesta = "Encuesta realizada" var fechaCreacion = "" var desLoguear = false var listaMessagesKeyFallidos = [String]() let fname = Utils.obtenerFname() let lname = Utils.obtenerLname() let imagenDetailSegue = "imagenDetailSegue" let videoSegue = "videoSegue" let pdfSegue = "pdfSegue" let showUsersChat = "showUsersChat" var indiceSeleccionado = 0 var codError = "" var myTimer = NSTimer.init() //MARK: - Outlets @IBOutlet weak var escribirMensajeOutlet: UITextField! @IBOutlet weak var miTabla: UITableView! @IBOutlet weak var vistaContenedoraTeclado: UIView! @IBOutlet weak var spinner: UIActivityIndicatorView! @IBOutlet weak var bottomConstratitVistaTeclado: NSLayoutConstraint! //MARK: - Actions @IBAction func takePhoto(sender: AnyObject) { self.view.endEditing(true) hacerFoto = true //Creamos el picker para la foto let photoPicker = UIImagePickerController() //Nos declaramos delegado photoPicker.delegate = self let alert = UIAlertController(title: "Elija una opción", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) //Añadimos un boton para sacar una foto con la camara alert.addAction(UIAlertAction(title: "Hacer foto", style: .Default, handler: { action -> Void in if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){ photoPicker.sourceType = UIImagePickerControllerSourceType.Camera //Lo mostramos dispatch_async(dispatch_get_main_queue()) { self.presentViewController(photoPicker, animated: true, completion: { () -> Void in }) } } })) //Añdimos un boton para coger una foto de la galeria alert.addAction(UIAlertAction(title: "Album", style: .Default, handler: { action -> Void in if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)){ photoPicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary photoPicker.mediaTypes = UIImagePickerController.availableMediaTypesForSourceType(UIImagePickerControllerSourceType.Camera)! //Lo mostramos dispatch_async(dispatch_get_main_queue()) { self.presentViewController(photoPicker, animated: true, completion: { () -> Void in }) } } })) ////Añdimos un boton para coger una foto de la galeria alert.addAction(UIAlertAction(title: "Video", style: .Default, handler: { action -> Void in if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){ photoPicker.sourceType = UIImagePickerControllerSourceType.Camera photoPicker.mediaTypes = [kUTTypeMovie as String] photoPicker.allowsEditing = false //photoPicker.videoMaximumDuration = 10.0 //Lo mostramos dispatch_async(dispatch_get_main_queue()) { self.presentViewController(photoPicker, animated: true, completion: { () -> Void in }) } } })) //Añdimos un boton para cancelar las opciones alert.addAction(UIAlertAction(title: "Cancelar", style: .Cancel, handler: { action -> Void in })) //mostramos el alert dispatch_async(dispatch_get_main_queue()) { self.presentViewController(alert, animated: true) { () -> Void in } } } //MARK: - LifeCycle override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if(!conversacionNueva){ myTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "recuperarListadoMensajesTimer", userInfo: nil, repeats: true) } vistaContenedoraTeclado.layer.borderWidth = 0.5 vistaContenedoraTeclado.layer.borderColor = UIColor(red:0/255.0, green:0/255.0, blue:0/255.0, alpha: 0.3).CGColor //Nos damos de alta para responder a la notificacion enviada por push modificarUI() startObservingKeyBoard() //Nos aseguramos de activar el spinner por si volvemos de mas info spinner.hidden = false spinner.startAnimating() rellenarListaMensajes() if(!conversacionNueva && !hacerFoto){ recuperarListadoMensajes() }else if(hacerFoto){ hacerFoto = false } addTap() NSNotificationCenter.defaultCenter().addObserver(self, selector: "recargarPantalla", name:notificationChat, object: nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.tabBarController?.tabBar.hidden = false listaMensajes.removeAll(keepCapacity: false) listaMensajesPaginada.removeAll(keepCapacity: false) mostrarMensajesAnteriores = false moverUltimaFila = true miTabla.reloadData() //Nos damos de baja de la notificacion indicePaginado = 0 stopObservingKeyBoard() dissmisKeyboard() bottomConstratitVistaTeclado.constant = 0 vieneDeListadoMensajes = true //Nos damos de baja de la notificacion NSNotificationCenter.defaultCenter().removeObserver(self, name: notificationChat, object: nil) myTimer.invalidate() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if(listaMensajes.isEmpty && !conversacionNueva){ spinner.startAnimating() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - Utils func resetearBadgeIconoApp(){ let numeroMensajesSinLeer = Conversation.numeroMensajesSinLeer() if(numeroMensajesSinLeer > 0){ UIApplication.sharedApplication().applicationIconBadgeNumber = numeroMensajesSinLeer }else{ UIApplication.sharedApplication().applicationIconBadgeNumber = 0 } } func addTap(){ let tapRec = UITapGestureRecognizer() tapRec.addTarget(self, action: "tappedTabla") miTabla.addGestureRecognizer(tapRec) } func tappedTabla(){ self.view.endEditing(true) } func rellenarListaMensajes(){ //Recogemos los datos en segundo plano para no bloquear la interfaz //dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.listaMensajes = Messsage.devolverListMessages(self.conversationKey) if(!self.listaMensajes.isEmpty){ self.conversacionNueva = false Conversation.cambiarFlagNewMessageUserConversation(self.conversationKey,nuevo: false) self.resetearBadgeIconoApp() if(self.listaMensajes.count > 20){ let botonMasMensajes = ["message_key": "a","converstation_key": "a", "sender": "a", "created": "a", "content": "a", "type": "botonMensajeAnterior", "enviado":"true", "fname": "a", "lname": "a"] let fakeDictMasMensajeBoton = MessageModel(aDict: botonMasMensajes) self.listaMensajesPaginada = Array(self.listaMensajes[(0)..<20])//Copiamos los 20 primeros elementos de la lista self.listaMensajesPaginada.append(fakeDictMasMensajeBoton) }else{ self.listaMensajesPaginada = self.listaMensajes } } //Cuando acabamos todo lo demas volvemos al hilo principal para actualizar la UI dispatch_async(dispatch_get_main_queue()) { self.miTabla.reloadData() self.spinner.stopAnimating() } //}) }) } func recargarPantalla(){//Recargamos la pantalla cuando nos llegue una notificacion listaMensajes.removeAll(keepCapacity: false) listaMensajesPaginada.removeAll(keepCapacity: false) mostrarMensajesAnteriores = false moverUltimaFila = true Conversation.cambiarFlagNewMessageUserConversation(conversationKey,nuevo: true) resetearBadgeIconoApp() dispatch_async(dispatch_get_main_queue(), { () -> Void in self.rellenarListaMensajes() }) } //Funcion que va aumentando la lista de mensajes de 20 en 20 siempre que sea posible func mostrarMasMensajes(){ indicePaginado += 1 if(listaMensajes.count > (indicePaginado * 20)){ listaMensajesPaginada.removeAll(keepCapacity: false)//Vaciamos la lista para añadir los elementos paginados let indiceFinal = (indicePaginado + 1) * 20 if( indiceFinal < listaMensajes.count){ //Comprobamos si se pueden mostrar los 20 siguientes mensajes enteros listaMensajesPaginada = Array(listaMensajes[0..<indiceFinal]) //Si el indice es menor que el tamaño entero se el ultimo elemento sera el de indiceFinal let botonMasMensajes = ["message_key": "a","converstation_key": "a", "sender": "a", "created": "a", "content": "a", "type": "botonMensajeAnterior" ,"enviado":"true", "fname": "a", "lname": "a"] let fakeDictMasMensajeBoton = MessageModel(aDict: botonMasMensajes) //Si el indice final es menor que el numero de elementos significa que hay mas mensajes por lo tanto mostramos el boton de mensajes Anteriores listaMensajesPaginada.append(fakeDictMasMensajeBoton) }else{ listaMensajesPaginada = Array(listaMensajes[0..<listaMensajes.count]) } miTabla.reloadData() } } //Funcion para redondear los botones y demas formatos de la UI func modificarUI(){ self.title = userName //Ocultamos el tabBar self.tabBarController?.tabBar.hidden = true } //Funcion para visualizar la ultima fila de la tabla func establecerUltimaFilaTabla(){ let lastSection = miTabla.numberOfSections - 1 let lastRow = miTabla.numberOfRowsInSection(lastSection) - 1 let ip = NSIndexPath(forRow: lastRow, inSection: lastSection) miTabla.scrollToRowAtIndexPath(ip, atScrollPosition: UITableViewScrollPosition.Bottom, animated: false) } func mostrarAlerta(){ //Nos aseguramos que esta en el hilo principal o rompera dispatch_async(dispatch_get_main_queue(), { () -> Void in self.view.endEditing(true) let alert = UIAlertController(title: self.tituloAlert, message: self.mensajeAlert, preferredStyle: UIAlertControllerStyle.Alert) alert.view.tintColor = UIColor(red: 193/255, green: 24/255, blue: 20/255, alpha: 1) //Añadimos un bonton al alert y lo que queramos que haga en la clausur if(self.desLoguear){ self.desLoguear = false myTimerLeftMenu.invalidate() alert.addAction(UIAlertAction(title: "ACEPTAR", style: .Default, handler: { (action) -> Void in LogOut.desLoguearBorrarDatos() self.presentingViewController!.dismissViewControllerAnimated(true, completion: nil) })) }else{ //Añadimos un bonton al alert y lo que queramos que haga en la clausur alert.addAction(UIAlertAction(title: "ACEPTAR", style: .Default, handler: { (action) -> Void in if(self.codError == "list_messages_empty"){ self.navigationController?.popToRootViewControllerAnimated(true) } })) } //mostramos el alert self.presentViewController(alert, animated: true) { () -> Void in self.tituloAlert = "" self.mensajeAlert = "" } }) } //Funcion para reenviar el mensaje cuando fallo y pulsamos el boton func reenviarMensaje(sender:UIButton){ var upMessage = false var posicion = 0 let alert = UIAlertController(title: "Elija una opción", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) alert.addAction(UIAlertAction(title: "Reenviar mensajes fallidos", style: .Default, handler: { action -> Void in let listaMensajesFallidos = Messsage.devolverMensajesFallidos(self.conversationKey) for mensajeFallido in listaMensajesFallidos{ Messsage.cambiarEstadoEnviadoMensaje(mensajeFallido.conversationKey, messageKey: mensajeFallido.messageKey, enviado: "true") let fechaActualizada = Fechas.fechaActualToString() Messsage.actualizarFechaMensaje(self.conversationKey, messageKey: mensajeFallido.messageKey, fecha: fechaActualizada) self.rellenarListaMensajes() var content = "" if(mensajeFallido.type == "jpeg_base64" || mensajeFallido.type == "mp4_base64"){ content = mensajeFallido.content.stringByReplacingOccurrencesOfString("+", withString: "%2B", options: [], range: nil) } else{ content = mensajeFallido.content } for (var i=0 ; i < self.listaMessagesKeyFallidos.count; i++){ if (mensajeFallido.messageKey == self.listaMessagesKeyFallidos[i]){ upMessage = true posicion = i i = self.listaMessagesKeyFallidos.count } } if(upMessage){ self.updateMessage(mensajeFallido.messageKey, content: mensajeFallido.content, tipo: mensajeFallido.type) self.listaMessagesKeyFallidos.removeAtIndex(posicion ) }else{ let sessionKey = Utils.getSessionKey() let params = "action=add_message&session_key=\(sessionKey)&conversation_key=\(self.conversationKey)&type=premessage&app_version=\(appVersion)&app=\(app)" self.addMessage(params, messageKey: mensajeFallido.messageKey, contenido: content, tipo: mensajeFallido.type) } } })) alert.addAction(UIAlertAction(title: "Borrar mensajes fallidos", style: .Default, handler: { action -> Void in Messsage.borrarMensajesFallidosConversacion(self.conversationKey) //Recuperamos el ultimo mensaje que tenemos tras el borrado para actualizar el ultimo de la conversacion let ultimoMensaje = Messsage.devolverUltimoMensajeConversacion(self.conversationKey) Conversation.updateLastMesssageConversation(ultimoMensaje.conversationKey , ultimoMensaje: ultimoMensaje.content, fechaCreacion: ultimoMensaje.created) self.rellenarListaMensajes() })) //Añdimos un boton para cancelar las opciones alert.addAction(UIAlertAction(title: "Cancelar", style: .Cancel, handler: { action -> Void in //No hacemos nada........Solo cancelamos el alert })) //mostramos el alert self.presentViewController(alert, animated: true) { () -> Void in } } //Funcion que se ejecuta cuando pulsamos sobre las imagenes de las celdas func tapImage(sender: UITapGestureRecognizer){ indiceSeleccionado = (sender.view?.tag)! let listaMensajesOrdenadas = Array(listaMensajesPaginada.reverse()) if(listaMensajesOrdenadas[indiceSeleccionado].type == "jpeg_base64"){ performSegueWithIdentifier(imagenDetailSegue, sender: self) }else if(listaMensajesOrdenadas[indiceSeleccionado].type == "mp4_base64"){ performSegueWithIdentifier(videoSegue, sender: self) }else{ performSegueWithIdentifier(pdfSegue, sender: self) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == imagenDetailSegue){ let listaMensajesOrdenadas = Array(listaMensajesPaginada.reverse()) let imagenMostrar = decodificarImagen(listaMensajesOrdenadas[indiceSeleccionado].content) let imagenDetailVC = segue.destinationViewController as! ImageDetailController imagenDetailVC.imagenMostrada = imagenMostrar }else if(segue.identifier == videoSegue){ let listaMensajesOrdenadas = Array(listaMensajesPaginada.reverse()) let mostrarVideoVC = segue.destinationViewController as! VideoViewController mostrarVideoVC.dataVideo = Utils.decodificarVideo(listaMensajesOrdenadas[indiceSeleccionado].content) mostrarVideoVC.messageKey = listaMensajesOrdenadas[indiceSeleccionado].messageKey }else if(segue.identifier == pdfSegue){ var listaMensajesOrdenadas = Array(listaMensajesPaginada.reverse()) let urlPdf = Utils.returnUrlWS("pdf") + listaMensajesOrdenadas[indiceSeleccionado].messageKey + ".pdf" let detailPdf = segue.destinationViewController as! visorPdfController detailPdf.urlString = urlPdf detailPdf.titulo = listaMensajesOrdenadas[indiceSeleccionado].content } } //Funcion que se ejecuta cuando pulsamos sobre los botones de realizar encuesta o abrir pdf func tapCell(sender: UITapGestureRecognizer){ let row = sender.view?.tag if let indice = row{ indiceSeleccionado = indice performSegueWithIdentifier(pdfSegue, sender: self) } } func addNuevaConversacion(lastMessage:String){ if let user = User.obtenerUser(userKey){ let imageData = UIImagePNGRepresentation((user.avatar)!) var avatar = "" if let avatarImage = imageData?.base64EncodedStringWithOptions([]){ avatar = avatarImage } let hora = NSString(string: Conversation.devolverHoraUltimaConversacion()).doubleValue if(NSString(string: fechaCreacion).doubleValue < hora){ fechaCreacion = "\(hora + 3)" } let auxUserDict = ["user_key":userKey, "avatar": avatar,"connection-status": user.connectionStatus] let userNameArray = user.userName.componentsSeparatedByString(" ") let userFname:String = userNameArray[0] var lnameUser = "" for(var i = 1; i < userNameArray.count; i++){ lnameUser += userNameArray[i] + " " } let conversacionDict = ["conversation_key": conversationKey, "user_fname": userFname, "user_lname": lnameUser,"user": auxUserDict, "flag_new_message_user": "0", "last_message": lastMessage, "last_update": fechaCreacion] _=Conversation(aDict: conversacionDict, aLastUpdate: fechaCreacion, existe: false) } } //Funcion para devolver la encuesta enviada formateada func devolverEncuestaEnviadaFormateada(pregunta:String, respuesta:String, puntuacion:String) -> NSMutableAttributedString{ let style = "<style>body { font-family: HelveticaNeue; font-size:14px } b{font-size:10px}</style>" //String para formatear la font family en todas las politicas var mezcla = "" if(respuesta.isEmpty && puntuacion.isEmpty){ let tituloEncuesta = "<b>Encuesta enviada:</b><br>" mezcla = style + tituloEncuesta + pregunta }else{ let tituloEncuesta = "<b>Encuesta enviada:</b><br>" let tituloRespuesta = "<b>Respuesta recibida (\(puntuacion)/5):</b><br>" mezcla = style + tituloEncuesta + pregunta + "<br><br>" + tituloRespuesta + respuesta } return try! NSMutableAttributedString( data: mezcla.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) } //MARK: - ComunicacionServidor func recuperarListadoMensajes(){ let sessionKey = Utils.getSessionKey() let lastUpdate = Conversation.obtenerLastUpdate(conversationKey) let params = "action=list_messages&session_key=\(sessionKey)&conversation_key=\(conversationKey)&last_update=\(lastUpdate)&offset=\(0)&limit=\(1000)&app_version=\(appVersion)&app=\(app)" let urlServidor = Utils.returnUrlWS("conversations") let request = NSMutableURLRequest(URL: NSURL(string: urlServidor)!) let session = NSURLSession.sharedSession() request.HTTPMethod = "POST" request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding) let recuperarListadoMensajesTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in guard data != nil else { print("no data found: \(error)") return } do { if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: [NSJSONReadingOptions.MutableContainers]) as? NSDictionary { if let resultCode = json.objectForKey("result") as? Int{ if(resultCode == 1){ dispatch_async(dispatch_get_main_queue(), { () -> Void in if let dataResultado = json.objectForKey("data") as? NSDictionary{//4 if let lastUp = dataResultado.objectForKey("last_update") as? String{//5 Conversation.modificarLastUpdate(self.conversationKey, aLastUpdate: lastUp) }//5 if let needToUpdate = dataResultado.objectForKey("need_to_update") as? Bool{//6 if (needToUpdate){//7 Messsage.borrarMensajesConConverstaionKey(self.conversationKey) if let messagesArray = dataResultado.objectForKey("messages") as? [NSDictionary]{//8 //Llamamos por cada elemento del array de empresas al constructor for dict in messagesArray{//9 _ = Messsage(aDict: dict, aConversationKey: self.conversationKey) }//9 }//8 dispatch_async(dispatch_get_main_queue(), { () -> Void in self.rellenarListaMensajes() }) }//7 }//6 }//4 }) }//3 else{ if let codigoError = json.objectForKey("error_code") as? String{ self.codError = codigoError self.desLoguear = LogOut.comprobarDesloguear(codigoError) (self.tituloAlert,self.mensajeAlert) = Utils.returnTitleAndMessageAlert(codigoError) dispatch_async(dispatch_get_main_queue(), { () -> Void in self.mostrarAlerta() }) } } } } } catch{ (self.tituloAlert,self.mensajeAlert) = Utils.returnTitleAndMessageAlert("error") dispatch_async(dispatch_get_main_queue(), { () -> Void in self.mostrarAlerta() }) } } recuperarListadoMensajesTask.resume() } func crearConversacion(){ let sessionKey = Utils.getSessionKey() let params = "action=open_conversation&session_key=\(sessionKey)&user_key=\(userKey)&app_version=\(appVersion)&app=\(app)" let urlServidor = Utils.returnUrlWS("conversations") let request = NSMutableURLRequest(URL: NSURL(string: urlServidor)!) let session = NSURLSession.sharedSession() request.HTTPMethod = "POST" request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding) let semaphore = dispatch_semaphore_create(0) let openConversationTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in guard data != nil else { print("no data found: \(error)") return } do { if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: [NSJSONReadingOptions.MutableContainers]) as? NSDictionary { if let resultCode = json.objectForKey("result") as? Int{ if(resultCode == 1){ if let dataResultado = json.objectForKey("data") as? NSDictionary{ if let claveConversacion = dataResultado.objectForKey("conversation_key") as? String{ self.conversationKey = claveConversacion self.conversacionNueva = false self.myTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "recuperarListadoMensajesTimer", userInfo: nil, repeats: true) if let lastUpdate = dataResultado.objectForKey("conversations_last_update") as? String{ Utils.saveConversationsLastUpdate(lastUpdate) } } } }else{ if let codigoError = json.objectForKey("error_code") as? String{ self.desLoguear = LogOut.comprobarDesloguear(codigoError) (self.tituloAlert,self.mensajeAlert) = Utils.returnTitleAndMessageAlert(codigoError) dispatch_async(dispatch_get_main_queue(), { () -> Void in self.mostrarAlerta() }) } } } } } catch{ (self.tituloAlert,self.mensajeAlert) = Utils.returnTitleAndMessageAlert("error") dispatch_async(dispatch_get_main_queue(), { () -> Void in self.mostrarAlerta() }) } dispatch_semaphore_signal(semaphore) } openConversationTask.resume() dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) } func addMessage(params:String, messageKey:String, contenido:String, tipo:String){ let urlServidor = Utils.returnUrlWS("conversations") let request = NSMutableURLRequest(URL: NSURL(string: urlServidor)!) let session = NSURLSession.sharedSession() request.HTTPMethod = "POST" request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding) let addMensajeTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in guard data != nil else { print("no data found: \(error)") return } do { if(error != nil){ if(error!.code == -1005){ self.addMessage(params, messageKey: messageKey, contenido: contenido, tipo: tipo) } }else{ if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: [NSJSONReadingOptions.MutableContainers]) as? NSDictionary { if let resultCode = json.objectForKey("result") as? Int{ if(resultCode == 1){ //Se ha insertado el mensaje correctamente y por lo tanto guardamos el lastUpdate if let dataResultado = json.objectForKey("data") as? NSDictionary{ dispatch_async(dispatch_get_main_queue(), { () -> Void in if let lastUpd = dataResultado.objectForKey("last_update") as?String{ var hora = NSString(string: Messsage.devolverHoraUltimoMensaje(self.conversationKey)).doubleValue if(NSString(string: lastUpd).doubleValue < hora){ hora = hora + 3 } Messsage.actualizarFechaMensaje(self.conversationKey, messageKey: messageKey, fecha: "\(hora)") } if let messageKeyServidor = dataResultado.objectForKey("message_key") as?String { Messsage.updateMessageKeyTemporal(self.conversationKey, messageKey: messageKey, messageKeyServidor: messageKeyServidor) self.updateMessage(messageKeyServidor, content: contenido,tipo: tipo) } }) } }else{ dispatch_async(dispatch_get_main_queue(), { () -> Void in Messsage.cambiarEstadoEnviadoMensaje(self.conversationKey, messageKey: messageKey, enviado: "false") let anUltimoMensajeEnviado = Messsage.devolverUltimoMensajeEnviadoOk(self.conversationKey) if let ultimoMensajeEnviado = anUltimoMensajeEnviado{ Conversation.updateLastMesssageConversation(ultimoMensajeEnviado.conversationKey, ultimoMensaje: ultimoMensajeEnviado.content, fechaCreacion: ultimoMensajeEnviado.created) } dispatch_async(dispatch_get_main_queue(), { () -> Void in self.rellenarListaMensajes() }) if let codigoError = json.objectForKey("error_code") as? String{ self.desLoguear = LogOut.comprobarDesloguear(codigoError) (self.tituloAlert,self.mensajeAlert) = Utils.returnTitleAndMessageAlert(codigoError) dispatch_async(dispatch_get_main_queue(), { () -> Void in self.mostrarAlerta() }) } }) } } } } } catch{ (self.tituloAlert,self.mensajeAlert) = Utils.returnTitleAndMessageAlert("error") dispatch_async(dispatch_get_main_queue(), { () -> Void in self.mostrarAlerta() }) } } addMensajeTask.resume() } func updateMessage(messageKey:String, content:String, tipo:String){ let sessionKey = Utils.getSessionKey() let params = "action=update_message&session_key=\(sessionKey)&conversation_key=\(conversationKey)&message_key=\(messageKey)&content=\(content)&type=\(tipo)&app=\(app)" let urlServidor = Utils.returnUrlWS("conversations") let request = NSMutableURLRequest(URL: NSURL(string: urlServidor)!) let session = NSURLSession.sharedSession() request.HTTPMethod = "POST" request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding) let udpateMensajeTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in guard data != nil else { print("no data found: \(error)") return } do { if(error != nil){ if(error!.code == -1005){ self.updateMessage(messageKey, content: content,tipo: tipo) } }else{ if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: [NSJSONReadingOptions.MutableContainers]) as? NSDictionary { if let resultCode = json.objectForKey("result") as? Int{ if(resultCode == 1){ //LogOutCorrecto }else{ dispatch_async(dispatch_get_main_queue(), { () -> Void in self.listaMessagesKeyFallidos.append(messageKey) Messsage.cambiarEstadoEnviadoMensaje(self.conversationKey, messageKey: messageKey, enviado: "false") let anUltimoMensajeEnviado = Messsage.devolverUltimoMensajeEnviadoOk(self.conversationKey) if let ultimoMensajeEnviado = anUltimoMensajeEnviado{ Conversation.updateLastMesssageConversation(ultimoMensajeEnviado.conversationKey, ultimoMensaje: ultimoMensajeEnviado.content, fechaCreacion: ultimoMensajeEnviado.created) } dispatch_async(dispatch_get_main_queue(), { () -> Void in self.rellenarListaMensajes() }) if let codigoError = json.objectForKey("error_code") as? String{ self.desLoguear = LogOut.comprobarDesloguear(codigoError) (self.tituloAlert,self.mensajeAlert) = Utils.returnTitleAndMessageAlert(codigoError) dispatch_async(dispatch_get_main_queue(), { () -> Void in self.mostrarAlerta() }) } }) } } } } } catch{ (self.tituloAlert,self.mensajeAlert) = Utils.returnTitleAndMessageAlert("error") dispatch_async(dispatch_get_main_queue(), { () -> Void in self.mostrarAlerta() }) } } udpateMensajeTask.resume() } //MARK: - Teclado func dissmisKeyboard(){ self.view.endEditing(true) } func startObservingKeyBoard(){ //Funcion para darnos de alta como observador en las notificaciones de teclado let nc:NSNotificationCenter = NSNotificationCenter.defaultCenter() nc.addObserver(self, selector: "notifyThatKeyboardWillAppear:", name: UIKeyboardWillShowNotification, object: nil) nc.addObserver(self, selector: "notifyThatKeyboardWillDisappear:", name: UIKeyboardWillHideNotification, object: nil) } //Funcion para darnos de alta como observador en las notificaciones de teclado func stopObservingKeyBoard(){ let nc:NSNotificationCenter = NSNotificationCenter.defaultCenter() nc.removeObserver(self) } //Funcion que se ejecuta cuando aparece el teclado func notifyThatKeyboardWillAppear(notification:NSNotification){ keyboardIsShowing = true if let info = notification.userInfo { self.moverUltimaFila = true self.mostrarMensajesAnteriores = false self.miTabla.reloadData() keyboardFrame = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() bottomConstratitVistaTeclado.constant = keyboardFrame.size.height UIView.animateWithDuration(0.25, animations: { self.view.layoutIfNeeded() }) } } //Funcion que se ejecuta cuando desaparece el teclado func notifyThatKeyboardWillDisappear(notification:NSNotification){ keyboardIsShowing = false bottomConstratitVistaTeclado.constant = 0 UIView.animateWithDuration(0.25, animations: { () -> Void in self.view.layoutIfNeeded() }) } //Funcion que evita que el teclado solape la vista de un determinado control func arrangeViewOffsetFromKeyboard() { let theApp: UIApplication = UIApplication.sharedApplication() let windowView: UIView? = theApp.delegate!.window! let textFieldLowerPoint: CGPoint = CGPointMake(vistaContenedoraTeclado.frame.origin.x, vistaContenedoraTeclado!.frame.origin.y + vistaContenedoraTeclado!.frame.size.height) let convertedTextFieldLowerPoint: CGPoint = self.view.convertPoint(textFieldLowerPoint, toView: windowView) let targetTextFieldLowerPoint: CGPoint = CGPointMake(vistaContenedoraTeclado!.frame.origin.x, keyboardFrame.origin.y) let targetPointOffset: CGFloat = targetTextFieldLowerPoint.y - convertedTextFieldLowerPoint.y let adjustedViewFrameCenter: CGPoint = CGPointMake(self.view.center.x, self.view.center.y + targetPointOffset) UIView.animateWithDuration(0.25, animations: { self.view.center = adjustedViewFrameCenter }) } //Funcion que devuelve al estado origian la vista func returnViewToInitialFrame() { let initialViewRect: CGRect = CGRectMake(0.0, 0.0, self.view.frame.size.width, self.view.frame.size.height) if (!CGRectEqualToRect(initialViewRect, self.view.frame)) { UIView.animateWithDuration(0.2, animations: { self.view.frame = initialViewRect }); } } //Funcion para decodificar una imagen a partir de un String func decodificarImagen (dataImage:String) -> UIImage{ if let decodedData = NSData(base64EncodedString: dataImage, options:NSDataBase64DecodingOptions.IgnoreUnknownCharacters){ if(decodedData.length > 0){ return UIImage(data: decodedData)! } else{ return UIImage(named: "NoImage")! } } else{ return UIImage(named: "NoImage")! } } //MARK: - Table internal func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return listaMensajesPaginada.count } internal func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let listaMensajesOrdenadas = Array(listaMensajesPaginada.reverse()) if(listaMensajesOrdenadas[indexPath.row].sender != "brand"){ if(listaMensajesOrdenadas[indexPath.row].type == "jpeg_base64"){ let cell = tableView.dequeueReusableCellWithIdentifier("FotoBrand") as! CeldaImagenMensajes cell.imagen.image = listaMensajesOrdenadas[indexPath.row ].miniImagen cell.hora.text = Fechas.devolverTiempo(listaMensajesOrdenadas[indexPath.row ].created) ////////////////////Añadimos el tap a la imagen//////////////////// cell.imagen.userInteractionEnabled = true cell.imagen.tag = indexPath.row let tapRec = UITapGestureRecognizer() tapRec.addTarget(self, action: "tapImage:") cell.imagen.addGestureRecognizer(tapRec) ////////////////////////////////////////////////////////////////// //Ocultamos el boton play cell.playImage.hidden = true return cell }else if(listaMensajesOrdenadas[indexPath.row].type == "mp4_base64"){ let cell = tableView.dequeueReusableCellWithIdentifier("FotoBrand") as! CeldaImagenMensajes cell.imagen.image = listaMensajesOrdenadas[indexPath.row ].miniImagen cell.imagen.contentMode = UIViewContentMode.Redraw cell.hora.text = Fechas.devolverTiempo(listaMensajesOrdenadas[indexPath.row ].created) ////////////////////Añadimos el tap a la imagen//////////////////// cell.playImage.userInteractionEnabled = true cell.playImage.tag = indexPath.row cell.imagen.userInteractionEnabled = true cell.imagen.tag = indexPath.row let tapRec = UITapGestureRecognizer() tapRec.addTarget(self, action: "tapImage:") cell.imagen.addGestureRecognizer(tapRec) cell.playImage.addGestureRecognizer(tapRec) ////////////////////////////////////////////////////////////////// return cell }else if(listaMensajesOrdenadas[indexPath.row].type == "poll_response"){ let cell = tableView.dequeueReusableCellWithIdentifier("MensajeBrand") as! CeldaTextoMensaje let preguntaRespuesta = listaMensajesOrdenadas[indexPath.row].content let contenidoArray = preguntaRespuesta.componentsSeparatedByString("::") let preguntaEncuesta = contenidoArray[0] let puntuacionEncuesta = contenidoArray[1] let respuestaEncuesta = contenidoArray[2] cell.hora.text = Fechas.devolverTiempo(listaMensajesOrdenadas[indexPath.row].created) cell.mensaje.attributedText = devolverEncuestaEnviadaFormateada(preguntaEncuesta,respuesta: respuestaEncuesta, puntuacion: puntuacionEncuesta) return cell }else if(listaMensajesOrdenadas[indexPath.row].type == "botonMensajeAnterior"){ let cell = tableView.dequeueReusableCellWithIdentifier(cargarMensajesAnterioresId) as! CeldaCargarMensajesAnteriores //Añadimos una accion a cada boton(llamar/Info) cell.btnCargarMensajesAnteriores.addTarget(self, action: "mostrarMasMensajes", forControlEvents: UIControlEvents.TouchUpInside) return cell }else{ let cell = tableView.dequeueReusableCellWithIdentifier("MensajeBrand") as! CeldaTextoMensaje let mensajeString = NSMutableAttributedString(string: listaMensajesOrdenadas[indexPath.row].content) mensajeString.addAttribute(NSFontAttributeName, value: UIFont(name: "Helvetica Neue", size: 14.0)!, range: NSMakeRange(0, mensajeString.length)) cell.mensaje.attributedText = mensajeString cell.hora.text = Fechas.devolverTiempo(listaMensajesOrdenadas[indexPath.row ].created) cell.botonReenviarMensaje.hidden = true return cell } }else{ if(listaMensajesOrdenadas[indexPath.row].type == "jpeg_base64"){ let cell = tableView.dequeueReusableCellWithIdentifier("FotoUsuario") as! CeldaImagenMensajes cell.imagen.image = listaMensajesOrdenadas[indexPath.row ].miniImagen cell.imagen.contentMode = UIViewContentMode.Redraw cell.hora.text = Fechas.devolverTiempo(listaMensajesOrdenadas[indexPath.row ].created) cell.senderBrandName.text = listaMensajesOrdenadas[indexPath.row].fname + " " + listaMensajesOrdenadas[indexPath.row].lname if(listaMensajesOrdenadas[indexPath.row].enviado == "true"){ cell.traillingContraitNombre.constant = 10 cell.traillingConstraitImagen.constant = 8 cell.traillingConstraitHora.constant = 10 cell.botonReenviarMensaje.hidden = true }else{ cell.traillingConstraitImagen.constant = 36 cell.traillingConstraitHora.constant = 38 cell.traillingContraitNombre.constant = 38 cell.botonReenviarMensaje.hidden = false } cell.botonReenviarMensaje.tag = indexPath.row cell.botonReenviarMensaje.addTarget(self, action: "reenviarMensaje:", forControlEvents: UIControlEvents.TouchUpInside) ////////////////////Añadimos el tap a la imagen//////////////////// cell.imagen.userInteractionEnabled = true cell.imagen.tag = indexPath.row let tapRec = UITapGestureRecognizer() tapRec.addTarget(self, action: "tapImage:") cell.imagen.addGestureRecognizer(tapRec) ////////////////////////////////////////////////////////////////// cell.playImage.hidden = true return cell }else if(listaMensajesOrdenadas[indexPath.row].type == "document_pdf"){ let cell = tableView.dequeueReusableCellWithIdentifier(pdfEncuenstaCellId) as! CeldaPdfEncuesta cell.imagen.image = UIImage(named: "pdf") cell.mensaje.text = listaMensajesOrdenadas[indexPath.row].content cell.accion.text = mensajePdf cell.hora.text = Fechas.devolverTiempo(listaMensajesOrdenadas[indexPath.row].created) cell.senderBrandName.text = listaMensajesOrdenadas[indexPath.row].fname + " " + listaMensajesOrdenadas[indexPath.row].lname ////////////////////Añadimos el tap a la celda//////////////////// cell.tag = indexPath.row let tapRec = UITapGestureRecognizer() tapRec.addTarget(self, action: "tapCell:") cell.addGestureRecognizer(tapRec) ////////////////////////////////////////////////////////////////// return cell }else if(listaMensajesOrdenadas[indexPath.row].type == "poll" || listaMensajesOrdenadas[indexPath.row].type == "poll_closed"){ let cell = tableView.dequeueReusableCellWithIdentifier("MensajeUsuario") as! CeldaTextoMensaje cell.senderBrandName.text = listaMensajesOrdenadas[indexPath.row].fname + " " + listaMensajesOrdenadas[indexPath.row].lname cell.hora.text = Fechas.devolverTiempo(listaMensajesOrdenadas[indexPath.row].created) cell.mensaje.attributedText = devolverEncuestaEnviadaFormateada(listaMensajesOrdenadas[indexPath.row].content,respuesta: "", puntuacion: "") //Como vendra desde el manager ocultamos los botones para reenviar cell.traillingContraitNombre.constant = 16 cell.traillingConstrait.constant = 8 cell.botonReenviarMensaje.hidden = true //////////////////////////////////// return cell }else if(listaMensajesOrdenadas[indexPath.row].type == "premessage"){ let cell = tableView.dequeueReusableCellWithIdentifier("FotoUsuario") as! CeldaImagenMensajes cell.imagen.image = listaMensajesOrdenadas[indexPath.row ].miniImagen cell.imagen.contentMode = UIViewContentMode.Redraw cell.hora.text = Fechas.devolverTiempo(listaMensajesOrdenadas[indexPath.row ].created) cell.traillingConstraitImagen.constant = 8 cell.traillingConstraitHora.constant = 10 cell.botonReenviarMensaje.hidden = true let activityIndicator = Utils.crearActivityLoading(160, heigth: 160) activityIndicator.startAnimating() cell.imagen.addSubview(activityIndicator) return cell }else if(listaMensajesOrdenadas[indexPath.row].type == "mp4_base64"){ let cell = tableView.dequeueReusableCellWithIdentifier("FotoUsuario") as! CeldaImagenMensajes cell.imagen.image = listaMensajesOrdenadas[indexPath.row ].miniImagen cell.imagen.contentMode = UIViewContentMode.Redraw cell.hora.text = Fechas.devolverTiempo(listaMensajesOrdenadas[indexPath.row ].created) cell.senderBrandName.text = listaMensajesOrdenadas[indexPath.row].fname + " " + listaMensajesOrdenadas[indexPath.row].lname if(listaMensajesOrdenadas[indexPath.row].enviado == "true"){ cell.traillingContraitNombre.constant = 10 cell.traillingConstraitImagen.constant = 8 cell.traillingConstraitHora.constant = 10 cell.botonReenviarMensaje.hidden = true }else{ cell.traillingConstraitImagen.constant = 36 cell.traillingConstraitHora.constant = 38 cell.traillingContraitNombre.constant = 38 cell.botonReenviarMensaje.hidden = false } cell.botonReenviarMensaje.tag = indexPath.row cell.botonReenviarMensaje.addTarget(self, action: "reenviarMensaje:", forControlEvents: UIControlEvents.TouchUpInside) ////////////////////Añadimos el tap a la imagen//////////////////// cell.playImage.userInteractionEnabled = true cell.playImage.tag = indexPath.row cell.imagen.userInteractionEnabled = true cell.imagen.tag = indexPath.row let tapRec = UITapGestureRecognizer() tapRec.addTarget(self, action: "tapImage:") cell.imagen.addGestureRecognizer(tapRec) cell.playImage.addGestureRecognizer(tapRec) ////////////////////////////////////////////////////////////////// return cell }else{ let cell = tableView.dequeueReusableCellWithIdentifier("MensajeUsuario") as! CeldaTextoMensaje let mensajeString = NSMutableAttributedString(string: listaMensajesOrdenadas[indexPath.row].content) mensajeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blackColor(), range: NSMakeRange(0, mensajeString.length)) mensajeString.addAttribute(NSFontAttributeName, value: UIFont(name: "Helvetica Neue", size: 14.0)!, range: NSMakeRange(0, mensajeString.length)) cell.mensaje.attributedText = mensajeString cell.hora.text = Fechas.devolverTiempo(listaMensajesOrdenadas[indexPath.row ].created) cell.senderBrandName.text = listaMensajesOrdenadas[indexPath.row].fname + " " + listaMensajesOrdenadas[indexPath.row].lname if(listaMensajesOrdenadas[indexPath.row].enviado == "true"){ cell.traillingContraitNombre.constant = 16 cell.traillingConstrait.constant = 8 cell.botonReenviarMensaje.hidden = true }else{ cell.traillingContraitNombre.constant = 44 cell.traillingConstrait.constant = 36 cell.botonReenviarMensaje.hidden = false } cell.botonReenviarMensaje.tag = indexPath.row cell.botonReenviarMensaje.addTarget(self, action: "reenviarMensaje:", forControlEvents: UIControlEvents.TouchUpInside) return cell } } } //Funcion para discernir cuando es una imagen y establecer un tamaño fijo o cuando no y ponerlo dinámico func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { //Usamos este metodo para ver si el indexPath es igual a la ultima celda if(indexPath.isEqual(tableView.indexPathsForVisibleRows?.last)){ if(moverUltimaFila || !mostrarMensajesAnteriores){ establecerUltimaFilaTabla() } } } func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { moverUltimaFila = false mostrarMensajesAnteriores = true } //MARK: - recuperarListadoMensajesTimer func recuperarListadoMensajesTimer(){ recuperarListadoMensajes() } } //MARK: - UITextFieldDelegate extension AddConversacionController: UITextFieldDelegate{ func textFieldShouldReturn(textField: UITextField) -> Bool { guardarMensajeYenviar() return true } func guardarMensajeYenviar(){ let tipo = "text" //guardamos el valor del mensaje que hemos introducido y lo ponemos a blanco var textoMensaje = escribirMensajeOutlet.text! escribirMensajeOutlet.text = "" //Si el tamaño del texto es mayor que 0 quiere decir que hemos introducido algo if(Utils.quitarEspacios(textoMensaje).characters.count > 0){ fechaCreacion = Fechas.fechaActualToString() //si venimos de la pantalla de ListBrand, Favoritos o Busqueda es una conversacion nueva con lo cual tenemos que crear la conversacion if(conversacionNueva == true){ crearConversacion() addNuevaConversacion(textoMensaje) }else{ let hora = NSString(string: Messsage.devolverHoraUltimoMensaje(self.conversationKey)).doubleValue if(NSString(string: fechaCreacion).doubleValue < hora){ fechaCreacion = "\(hora + 3)" } } let messageKey = Messsage.obtenerMessageKeyTemporal() //Añadimos un mensaje nuevo al modelo let mensajeTextoDict = ["message_key": messageKey, "converstation_key": conversationKey, "sender": "brand", "created": fechaCreacion, "content": textoMensaje, "type": tipo, "enviado": "true", "fname": fname, "lname": lname] let mensaje = MessageModel(aDict: mensajeTextoDict) _ = Messsage(model: mensaje) listaMensajes.removeAll(keepCapacity: false) listaMensajes = Messsage.devolverListMessages(conversationKey) if(listaMensajes.count > 20){ let botonMasMensajes = ["message_key": "a", "converstation_key": "a", "sender": "a", "created": "a", "content": "a", "type": "botonMensajeAnterior","enviado":"true", "fname": "a", "lname": "a"] let fakeDictMasMensajeBoton = MessageModel(aDict: botonMasMensajes) listaMensajesPaginada = Array(listaMensajes[(0)..<20]) listaMensajesPaginada.append(fakeDictMasMensajeBoton) indicePaginado = 0 }else{ listaMensajesPaginada = listaMensajes } moverUltimaFila = true miTabla.reloadData() Conversation.updateLastMesssageConversation(conversationKey, ultimoMensaje: textoMensaje, fechaCreacion: fechaCreacion) textoMensaje = Utils.removerEspaciosBlanco(textoMensaje)//Cambiamos los espacios en blanco por + let sessionKey = Utils.getSessionKey() let params = "action=add_message&session_key=\(sessionKey)&conversation_key=\(conversationKey)&type=premessage&app_version=\(appVersion)&app=\(app)" addMessage(params, messageKey: messageKey, contenido: textoMensaje, tipo: tipo) } } } //MARK: - extension AddConversacionController: UINavigationControllerDelegate, UIImagePickerControllerDelegate { //Funcion para formatear la foto a enviar func formatearFoto(imagenOriginal:UIImage){ var reducir : Bool var tamaño:CGSize? var imagenReescalada: UIImage? listaMensajes.removeAll(keepCapacity: false) (reducir , tamaño) = ResizeImage().devolverTamaño(imagenOriginal) if(!reducir){ imagenReescalada = ResizeImage().RedimensionarImagen(imagenOriginal) }else{ imagenReescalada = ResizeImage().RedimensionarImagenContamaño(imagenOriginal, targetSize: tamaño!) } fechaCreacion = Fechas.fechaActualToString() if(conversacionNueva == true){ crearConversacion() addNuevaConversacion("[::image]") }else{ let hora = NSString(string: Messsage.devolverHoraUltimoMensaje(self.conversationKey)).doubleValue if(NSString(string: fechaCreacion).doubleValue < hora){ fechaCreacion = "\(hora + 3)" } } let tipo = "jpeg_base64" let contenido = codificarImagen(imagenReescalada!) enviarFotoVideo(tipo, contenido: contenido, ultimoMensaje: "📷") } //Funcion para formatear el video a enviar func formatearVideo(dataVideo:NSData, urlString:String){ fechaCreacion = Fechas.fechaActualToString() if(conversacionNueva == true){ crearConversacion() addNuevaConversacion("[::video]") }else{ let hora = NSString(string: Messsage.devolverHoraUltimoMensaje(self.conversationKey)).doubleValue if(NSString(string: fechaCreacion).doubleValue < hora){ fechaCreacion = "\(hora + 3)" } } let tipo = "mp4_base64" let contenido = codificarVideo(dataVideo) enviarFotoVideo(tipo, contenido: contenido, ultimoMensaje: "📹") } //Funcion para enviar tanto si es foto como video func enviarFotoVideo(tipo:String, contenido:String, ultimoMensaje:String){ let messageKey = Messsage.obtenerMessageKeyTemporal() let mensajeTextoDict = ["message_key": messageKey, "converstation_key": conversationKey, "sender": "brand", "created": fechaCreacion, "content": contenido, "type": tipo, "enviado":"true", "fname": fname, "lname": lname] let mensaje = MessageModel(aDict: mensajeTextoDict) _ = Messsage(model: mensaje) listaMensajes.removeAll(keepCapacity: false) listaMensajes = Messsage.devolverListMessages(conversationKey) if(listaMensajes.count > 20){ let botonMasMensajes = ["message_key": "a", "converstation_key": "a", "sender": "a", "created": "a", "content": "a", "type": "botonMensajeAnterior", "enviado":"true", "fname": "a", "lname": "a"] let fakeDictMasMensajeBoton = MessageModel(aDict: botonMasMensajes) listaMensajesPaginada = Array(listaMensajes[(0)..<20]) listaMensajesPaginada.append(fakeDictMasMensajeBoton) indicePaginado = 0 }else{ listaMensajesPaginada = listaMensajes } miTabla.reloadData() Conversation.updateLastMesssageConversation(conversationKey, ultimoMensaje: ultimoMensaje, fechaCreacion: fechaCreacion) let content = contenido.stringByReplacingOccurrencesOfString("+", withString: "%2B", options: [], range: nil) let sessionKey = Utils.getSessionKey() let params = "action=add_message&session_key=\(sessionKey)&conversation_key=\(conversationKey)&type=premessage&app_version=\(appVersion)&app=\(app)" addMessage(params, messageKey: messageKey, contenido: content, tipo: tipo) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] self.dismissViewControllerAnimated(true, completion: { () -> Void in }) //Comprobamos si es una imagen o un video if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { //Es una imagen formatearFoto(pickedImage) }else{//Es un video if let urlVideo = info[UIImagePickerControllerMediaURL] as? NSURL{ convertToMp4(urlVideo) } } } func imagePickerControllerDidCancel(picker: UIImagePickerController) { self.dismissViewControllerAnimated(true, completion: { () -> Void in }) } // Funcion que codifica la imagen func codificarImagen(dataImage:UIImage) -> String{ let imageData = UIImagePNGRepresentation(dataImage) return imageData!.base64EncodedStringWithOptions([]) } //Funcion que codifica el video func codificarVideo(dataVideo:NSData) -> String{ return dataVideo.base64EncodedStringWithOptions([]) } //Funcion para convertir de .mov a .mp4 func convertToMp4(urlMov:NSURL){ let doubleNSString = NSString(string: Fechas.fechaActualToString()) let timestampAsDouble = Int(doubleNSString.doubleValue * 1000) let idVideo = "\(timestampAsDouble)" let video = AVURLAsset(URL: urlMov, options: nil) let exportSession = AVAssetExportSession(asset: video, presetName: AVAssetExportPresetMediumQuality) let myDocumentPath = applicationDocumentsDirectory().stringByAppendingPathComponent(idVideo + ".mp4") let url = NSURL(fileURLWithPath: myDocumentPath) exportSession!.outputURL = url exportSession!.outputFileType = AVFileTypeMPEG4; exportSession!.shouldOptimizeForNetworkUse = true; exportSession!.exportAsynchronouslyWithCompletionHandler ({ if(exportSession!.status == AVAssetExportSessionStatus.Completed){ if let videoData = NSData(contentsOfURL: url){ self.formatearVideo(videoData, urlString: "\(url)") } }else{ //Fallo la exportacion y no hacemos nada } }) } func applicationDocumentsDirectory() -> NSString {//En esta funcion obtenemos la ruta temporal donde guardar nuestro archivo return NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString } }
// // ViewController.swift // HR // // Created by lipeng on 2018/11/29. // Copyright © 2018 lipeng. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // 继承 let tom = Tom() tom.show() // 重写 方法 let superClass = SupperClass() superClass.show() let subClass = SubClass() subClass.show() // 重写属性 let rectangle = Rectangle() rectangle.radius = 25.0 rectangle.print = 3 print("Radius\(rectangle.area)") } func typeTranslate() { let sa = [ Chemistry(physics: "固体物理", equations: "赫兹"), Maths(physic: "流体动力学", formulae: "千兆赫") ] let samplechem = Chemistry(physics: "固体物理", equations: "赫兹") print("实例物理学是\(samplechem.physics)") print("实例方程式:\(samplechem.equations)") let sampleMatchs = Maths(physic: "流体动力学", formulae: "千兆赫") print("实例物理学是:\(sampleMatchs.physics)") print("实例公式是:\(sampleMatchs.formulae)") // 检查类型 // 类型转换用于检测实例类型是否属于特定的实例类型。 // 你可以将它用在类和子类的层次结构上,检查特定类实例的类型并且转换这个类实例的类型成为这个层次结构中的其他类型。 // 类型检查使用 is 关键字。 // 操作符 is 来检查一个实例是否属于特定子类型。若实例属于那个子类型,类型检查操作符返回 true,否则返回 false。 var chemCount = 0; var mathsCount = 0; for item in sa { if item is Chemistry { chemCount += 1 } else if item is Maths { mathsCount += 1 } } // 向下转型 // 向下转型,用类型转换操作符(as? 或 as!) // 当你不确定向下转型可以成功时,用类型转换的条件形式(as?)。条件形式的类型转换总是返回一个可选值(optional value),并且若下转是不可能的,可选值将是 nil。 // 只有你可以确定向下转型一定会成功时,才使用强制形式(as!)。当你试图向下转型为一个不正确的类型时,强制形式的类型转换会触发一个运行时错误。 for item in sa { if let show = item as? Chemistry { print("化学主题是:'\(show.physics)',\(show.equations)"); } else if let example = item as? Maths { print("数学主题是:'\(example.physics)',\(example.formulae)") } } // Any和AnyObject的类型转换 // Swift为不确定类型提供了两种特殊类型别名: // AnyObject可以代表任何class类型的实例。 // Any可以表示任何类型,包括方法类型(function types)。 // 注意: // 只有当你明确的需要它的行为和功能时才使用Any和AnyObject。在你的代码里使用你期望的明确的类型总是更好的。 // Any 实例 var exampleAny = [Any]() exampleAny.append(12) exampleAny.append(3.14159) exampleAny.append("Any 实例") exampleAny.append(Chemistry(physics: "固体物理", equations:"兆赫")) for item in exampleAny { switch item { case let someInt as Int: print("整数值为\(someInt)") case let someDouble as Double where someDouble > 0 : print("PI为\(someDouble)") case let someString as String: print("\(someString)") case let phy as Chemistry : print("print 主题为\(phy.physics)") default: print("none") } } // AnyObject 实例 // AnyObject 可以代表任何class类型的实例 let saprint : [AnyObject] = [ Chemistry(physics: "固体物理", equations: "赫兹"), Maths(physic: "流体动力学", formulae: "千兆赫"), Chemistry(physics: "热物理学", equations: "分贝"), Maths(physic: "天体物理学", formulae: "兆赫"), Maths(physic: "微分方程", formulae: "余弦级数") ] for item in saprint { if let show = item as? Chemistry { print("化学主题是:'\(show.physics)',\(show.equations)") } else if let example = item as? Maths { print("数学主题是:'\(example.physics)',\(example.formulae)") } } } // 扩展 func showExtension() { // 计算型属性 // 扩展可以向已有类型添加计算型实例属性和计算型类型属性。 let addition = 3.add print("加法运算后的值:\(addition)") let subtraction = 120.sub print("减法运算后的值:\(subtraction)") let multiplication = 39.mul print("乘法运算后的值:\(multiplication)") let division = 55.div print("除法运算后的值: \(division)") let mix = 30.add + 34.sub print("混合运算结果:\(mix)") // 构造器 // 扩展可以向已有类型添加新的构造器。 // 这可以让你扩展其它类型,将你自己的定制类型作为构造器参数,或者提供该类型的原始实现中没有包含的额外初始化选项。 // 扩展可以向类中添加新的便利构造器 init(),但是它们不能向类中添加新的指定构造器或析构函数 deinit() 。 let a = sum(num1: 100, num2: 200) let b = diff(no1: 200, no2: 100) let getMult = mult(x: a, y: b) print("getMult sum\(getMult.a.num1, getMult.a.num2)") print("getMult diff\(getMult.b.no1, getMult.b.no2)") // 扩展可以向已有类型添加新的实例方法和类型方法。 // 4.topics({ // print("扩展模块内") // }) // // 3.topics({ // print("内型转换模块内") // }) // 可变实例方法 // 通过扩展添加的实例方法也可以修改该实例本身。 // 结构体和枚举类型中修改self或其属性的方法必须将该实例方法标注为mutating,正如来自原始实现的修改方法一样。 var Trial1 = 3.3 Trial1.square() print("圆的面积为: \(Trial1)") var Trial2 = 5.8 Trial2.square() print("圆的面积为: \(Trial2)") var Trial3 = 120.3 Trial3.square() print("圆的面积为: \(Trial3)") //下标 //扩展可以向一个已有类型添加新下标。 // print(12[0]) // print(7869[1]) // print(786543[2]) // 嵌套类型 // 扩展可以向已有的类、结构体和枚举添加新的嵌套类型: result(numb:[0, 1, 2, 3, 4, 7]) } // APNS func apnsPush() { // let push = ServerPush(); } }
// // DayFive2021.swift // AdventOfCode // // Created by Shawn Veader on 12/5/21. // import Foundation struct DayFive2021: AdventDay { var year = 2021 var dayNumber = 5 var dayTitle = "Hydrothermal Venture" var stars = 2 func parse(_ input: String?) -> [Line] { (input ?? "").split(separator: "\n").map(String.init).compactMap { Line.parse($0) } } func partOne(input: String?) -> Any { let floor = OceanFloor(lines: parse(input)) return floor.overlapPoints().count } func partTwo(input: String?) -> Any { let floor = OceanFloor(lines: parse(input), ignoreDiagonals: false) return floor.overlapPoints().count } }
// // StatementResponse.swift // Bank App // // Created by Chrystian (Pessoal) on 02/01/2019. // Copyright © 2019 Salgado's Productions. All rights reserved. // import Foundation struct StatementResponse: Decodable { let statementList: [Statement]? let error: BankError? enum CodingKeys: String, CodingKey { case statementList case error } } extension StatementResponse { init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) statementList = try values.decodeIfPresent([Statement].self, forKey: .statementList) error = try values.decodeIfPresent(BankError.self, forKey: .error) } }
// // NewQuestionView.swift // Vote // // Created by Tiziano Coroneo on 01/01/2018. // Copyright © 2018 Tiziano Coroneo. All rights reserved. // import UIKit class NewQuestionView: UIView, ToggleStateAnimatable { @IBOutlet private weak var questionView: QuestionView! @IBOutlet private weak var addAnswerView: UIView! @IBOutlet private weak var answersContainer: UIStackView! @IBOutlet private weak var optionsHeaderView: UIView! @IBOutlet private weak var optionsContainer: UIStackView! @IBOutlet private weak var optionsStackPositionConstraint: NSLayoutConstraint! var duration: TimeInterval { return 0.4 } var totalDistance: CGFloat { return targetPosition - initialPosition } var state: ToggleState = .off var runningAnimators: [UIViewPropertyAnimator] = [] var progressWhenInterrupted: [UIViewPropertyAnimator : CGFloat] = [:] private var initialPosition: CGFloat { return (optionsHeaderView?.frame.height ?? 60) + 10 } private var targetPosition: CGFloat { return (optionsContainer?.frame.height ?? 60) + 10 } var initialAnimatedProperties: (() -> ()) { return { [weak self, initialPosition] in self?.optionsStackPositionConstraint?.constant = initialPosition self?.layoutIfNeeded() } } var targetAnimatedProperties: (() -> ()) { return { [weak self, targetPosition] in self?.optionsStackPositionConstraint?.constant = targetPosition self?.layoutIfNeeded() } } // override func layoutSubviews() { // super.layoutSubviews() // state == .on // ? targetAnimatedProperties() // : initialAnimatedProperties() // } var processAnimationProgress: (CGFloat) -> (CGFloat) { return { [totalDistance] x in return x / (totalDistance) } } override func awakeFromNib() { super.awakeFromNib() setupGestures() } private func setupGestures() { let tapRecognizer = UITapGestureRecognizer.init( target: self, action: #selector(handleTap(_:))) optionsHeaderView?.addGestureRecognizer(tapRecognizer) let panGestureRecognizer = UIPanGestureRecognizer.init( target: self, action: #selector(handlePan(_:))) optionsHeaderView?.addGestureRecognizer(panGestureRecognizer) } @objc func handleTap(_ recognizer: UITapGestureRecognizer) { animateOrReverseRunningTransition( destinationState: !state, duration: duration) } @objc func handlePan(_ recognizer: UIPanGestureRecognizer) { switch recognizer.state { case .began: startInteractiveTransition( destinationState: !state, duration: duration) case .changed: let translation = recognizer.translation(in: self) updateInteractiveTransition( distanceTraveled: translation.y) case .cancelled, .failed: continueInteractiveTransition(cancel: true) case .ended: let isCancelled = isGestureCancelled(recognizer) continueInteractiveTransition(cancel: isCancelled) default: break } } private func isGestureCancelled(_ recognizer: UIPanGestureRecognizer) -> Bool { let isCancelled: Bool let velocityY = recognizer.velocity(in: self).y if velocityY != 0 { let isPanningOn = velocityY < 0 isCancelled = (state == .on && !isPanningOn) || (state == .off && isPanningOn) } else { isCancelled = false } return isCancelled } }
class Star_bulletin : Codable{ var sb_no : String? var sb_title : String? var store_code : String? var member_id : String? var sb_score : String? var sb_content: String? var sb_image : String? var sb_c_date : String? var sb_u_date : String? var sb_d_date : String? var member_image : String? }
// MakeNewFlashcardViewController.swift import UIKit class MakeNewFlashcardViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate, UITextViewDelegate { //makes variables for the stuff var numberForPicker = 0 var flashcardMade = Flashcard(title: "", text1: "", text2: "", colour: .yellow, type: .note) var pickerArray: [String] = ["Note", "Question", "Definition"] var flashcardColour: Colour = .yellow //makes outlets for the stuff @IBOutlet weak var titleTextField: UITextField! @IBOutlet weak var text1TextView: UITextView! @IBOutlet weak var text2TextView: UITextView! @IBOutlet weak var colourButton: UIButton! @IBOutlet weak var picker: UIPickerView! @IBOutlet weak var labelOne: UILabel! @IBOutlet weak var labelTwo: UILabel! //defines the amount of components and rows in the picker, adds text to it, and does the appropriate actions func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return pickerArray[row] } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerArray.count } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if row == 0 { text2TextView.isHidden = true labelOne.text = "Enter Note:" labelTwo.isHidden = true } else if row == 1 { text2TextView.isHidden = false labelOne.isHidden = false labelTwo.isHidden = false labelOne.text = "Enter Question:" labelTwo.text = "Enter Answer:" } else { text2TextView.isHidden = false labelOne.isHidden = false labelTwo.isHidden = false labelOne.text = "Enter Word:" labelTwo.text = "Enter Definition:" } numberForPicker = row } //makes a flashcard based on all of the information chosen by the user override func prepare(for segue: UIStoryboardSegue, sender: Any?) { flashcardMade = Flashcard(title: titleTextField.text!, text1: text1TextView.text!, text2: text2TextView.text!, colour: flashcardColour, type: flashcardMade.beAType(notePicked: pickerArray[numberForPicker])) } //makes the keyobard disapear with return and clicking outside as well as makes the view scroll down when the keyboard is pulled up to keep visibility override func viewDidLoad() { super.viewDidLoad() self.titleTextField.delegate = self self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:)))) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) } @objc func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { if self.view.frame.origin.y == 0 { self.view.frame.origin.y -= keyboardSize.height } } } @objc func keyboardWillHide(notification: NSNotification) { if self.view.frame.origin.y != 0 { self.view.frame.origin.y = 0 } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { titleTextField.resignFirstResponder() return true } func textViewShouldReturn(_ textView: UITextView) -> Bool { text1TextView.resignFirstResponder() return true } func textViewShouldReturn2(_ textView: UITextView) -> Bool { text2TextView.resignFirstResponder() return true } //hides the elements that do not appear if the flashcard is a note override func viewWillAppear(_ animated: Bool) { text2TextView.isHidden = true labelTwo.isHidden = true } //assigns the flashcard a color when the color button is pressed @IBAction func colourButtonPressed(_ sender: Any) { if colourButton.backgroundColor == #colorLiteral(red: 0.9995340705, green: 0.988355577, blue: 0.4726552367, alpha: 1) { colourButton.backgroundColor = #colorLiteral(red: 1, green: 0.5781051517, blue: 0, alpha: 1) flashcardColour = .orange } else if colourButton.backgroundColor == #colorLiteral(red: 1, green: 0.5781051517, blue: 0, alpha: 1) { colourButton.backgroundColor = #colorLiteral(red: 1, green: 0.5409764051, blue: 0.8473142982, alpha: 1) flashcardColour = .pink } else if colourButton.backgroundColor == #colorLiteral(red: 1, green: 0.5409764051, blue: 0.8473142982, alpha: 1) { colourButton.backgroundColor = #colorLiteral(red: 1, green: 0.4127538204, blue: 0.350384295, alpha: 1) flashcardColour = .red } else if colourButton.backgroundColor == #colorLiteral(red: 1, green: 0.4127538204, blue: 0.350384295, alpha: 1) { colourButton.backgroundColor = #colorLiteral(red: 0.3912315071, green: 0.7174404263, blue: 0.8626636863, alpha: 1) flashcardColour = .blue } else if colourButton.backgroundColor == #colorLiteral(red: 0.3912315071, green: 0.7174404263, blue: 0.8626636863, alpha: 1) { colourButton.backgroundColor = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1) flashcardColour = .green } else if colourButton.backgroundColor == #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1) { colourButton.backgroundColor = #colorLiteral(red: 0.9995340705, green: 0.988355577, blue: 0.4726552367, alpha: 1) flashcardColour = .yellow } } }
// // DatabaseManager.swift // News // // Created by Bilal Durnagöl on 2.11.2020. // import Foundation class DatabaseManager { static let shared = DatabaseManager() let localhost: String = "host" //MARK:- Account funcs // User login function public func login(email: String, password: String, completion: @escaping (Result<User, Error>) -> ()) { let params = [ "email": email, "password": password ] let data = try? JSONSerialization.data(withJSONObject: params, options: .init()) guard let url = URL(string: "\(localhost)/login") else {return} var urlRequest = URLRequest(url: url) urlRequest.httpBody = data urlRequest.httpMethod = "POST" urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") URLSession.shared.dataTask(with: urlRequest, completionHandler: { [self]data, response, error in guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { let message = try? JSONDecoder().decode(DatabaseMessage.self, from: data!) guard let error = message?.message else {return} completion(.failure(DatabaseManagerError.failedToLogin(error: error))) return } getUserInfo(email: email, completion: {result in switch result { case .failure(_): completion(.failure(DatabaseManagerError.failedToGetUserInfo)) case .success(let user): completion(.success(user)) } }) }).resume() } //Get user info public func getUserInfo(email: String, completion: @escaping (Result<User, Error>) -> ()) { guard let url = URL(string: "\(localhost)/user_info/\(email)") else {return} URLSession.shared.dataTask(with: url, completionHandler: {data, response, error in guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { completion(.failure(DatabaseManagerError.failedToGetUserInfo)) return } guard let userInfo = try? JSONDecoder().decode(User.self, from: data!) else {return} completion(.success(userInfo)) }).resume() } //Create user func public func createNewUser(user: User, completion: @escaping (Result<User, Error>) -> ()) { let params = [ "user_name": user.user_name, "user_email": user.user_email, "user_password": user.user_password, "user_location": user.user_location ] let data = try? JSONSerialization.data(withJSONObject: params, options: .init()) guard let url = URL(string: "\(localhost)/register") else {return} var urlRequest = URLRequest(url: url) urlRequest.httpBody = data urlRequest.httpMethod = "POST" urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") URLSession.shared.dataTask(with: urlRequest, completionHandler: {data, response, _ in guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { let message = try? JSONDecoder().decode(DatabaseMessage.self, from: data!) guard let error = message?.message else {return} completion(.failure(DatabaseManagerError.failedToCreateNewUser(error: error))) return } let user = try? JSONDecoder().decode(User.self, from: data!) completion(.success(user!)) }).resume() } //MARK:- Topic Funcs //add topics public func addTopic(email: String, chooseTopicsArray: [String], completion: @escaping (Result<String,Error>) -> ()) { var params = [ "topics": [] ] for topic in chooseTopicsArray { let topicArray = ["topic_name": topic] var topicsArray = params ["topics"] topicsArray!.append(topicArray) params["topics"] = topicsArray } print(params) let data = try? JSONSerialization.data(withJSONObject: params, options: .init()) guard let url = URL(string: "\(localhost)/add_topics/\(email)") else {return} var urlRequest = URLRequest(url: url) urlRequest.httpBody = data urlRequest.httpMethod = "POST" urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") URLSession.shared.dataTask(with: urlRequest, completionHandler: {data, response, _ in guard let urlResponse = response as? HTTPURLResponse, urlResponse.statusCode == 200 else { completion(.failure(DatabaseManagerError.failedToAddTopic)) return } let message = try? JSONDecoder().decode(DatabaseMessage.self, from: data!) guard let safeMessage = message?.message else {return} completion(.success(safeMessage)) }).resume() } //MARK:- Articles Funcs //Get all articles public func getArticles(url: String, completion: @escaping (Result<[Article]?, Error>) -> ()) { guard let url = URL(string: url) else {return} URLSession.shared.dataTask(with: url, completionHandler: {data, response, error in guard let data = data, error == nil else { completion(.failure(DatabaseManagerError.failedToFetchArticles)) return } let articles = try? JSONDecoder().decode(ArticleList.self, from: data) completion(.success(articles?.articles)) }).resume() } //Get featured articles public func getFeaturedArticle(url: String, completion: @escaping (Result<[Article]?, Error>) -> ()) { guard let url = URL(string: url) else {return} URLSession.shared.dataTask(with: url, completionHandler: {data, response, error in guard let data = data, error == nil else { completion(.failure(DatabaseManagerError.failedToFetchFeaturedArticles)) return } let articles = try? JSONDecoder().decode(ArticleList.self, from: data) completion(.success(articles?.articles)) }).resume() } //MARK:- Setting Funcs //Edit profile public func editProfile(userID: Int, userName: String, userEmail: String, userPassword: String, completion: @escaping (Bool)->()) { let params = [ "name": userName, "email": userEmail, "password": userPassword ] let data = try? JSONSerialization.data(withJSONObject: params, options: .init()) guard let url = URL(string: "\(localhost)/user_info_update/\(userID)") else {return} var urlRequest = URLRequest(url: url) urlRequest.httpBody = data urlRequest.httpMethod = "PUT" urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") URLSession.shared.dataTask(with: urlRequest, completionHandler: {_, response, _ in guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { completion(false) return } completion(true) }).resume() } //Update topics public func updateTopics(topics: [String], userID: Int, completion: @escaping (Bool) -> ()) { var params = [ "topics": [] ] as [String: Any] for topic in topics { let topicArray: [String: Any] = ["topic_name" : topic] var topicsArray = params["topics"] as? [[String: Any]] ?? [[String: Any]]() topicsArray.append(topicArray) params["topics"] = topicsArray } let data = try? JSONSerialization.data(withJSONObject: params, options: .init()) guard let url = URL(string: "\(localhost)/update_topic/\(userID)") else {return} var urlRequest = URLRequest(url: url) urlRequest.httpBody = data urlRequest.httpMethod = "POST" urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") URLSession.shared.dataTask(with: urlRequest, completionHandler: {data, response, _ in guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { completion(false) return } completion(true) }).resume() } //Update Location public func updateLocation(user: User?, completion: @escaping (Bool) -> ()) { guard let location = user?.user_location, let id = user?.user_id else {return} let params = [ "location": location ] let data = try? JSONSerialization.data(withJSONObject: params, options: .init()) guard let url = URL(string: "\(localhost)/update_location/\(id)") else {return} var urlRequest = URLRequest(url: url) urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type") urlRequest.httpBody = data urlRequest.httpMethod = "PUT" URLSession.shared.dataTask(with: urlRequest, completionHandler: {data, response, error in guard let urlResponse = response as? HTTPURLResponse, urlResponse.statusCode == 200 else { completion(false) return } completion(true) }).resume() } } //MARK:- Database Errors extension DatabaseManager { enum DatabaseManagerError: Error { case failedToLogin(error: String) case failedToGetUserInfo case failedToCreateNewUser(error: String) case failedToAddTopic case failedToFetchArticles case failedToFetchFeaturedArticles } } extension DatabaseManager.DatabaseManagerError: LocalizedError { public var errorDescription: String? { switch self { case .failedToLogin(error: let error): return NSLocalizedString("\(error)", comment: "Error") case .failedToGetUserInfo: return NSLocalizedString("Failed to get user info.", comment: "Error") case .failedToCreateNewUser(error: let error): return NSLocalizedString("\(error)", comment: "Error") case .failedToAddTopic: return NSLocalizedString("Failed add user's choose topics.", comment: "Error") case .failedToFetchArticles: return NSLocalizedString("Failed to get news.", comment: "Error") case .failedToFetchFeaturedArticles: return NSLocalizedString("Failed to get featured news.", comment: "Error") } } }
// // Linear_ColorLocations.swift // 100Views // // Created by Mark Moeykens on 8/24/19. // Copyright © 2019 Mark Moeykens. All rights reserved. // import SwiftUI struct Linear_ColorLocations: View { var body: some View { let gradientColors = Gradient(stops: [ .init(color: .red, location: 0), .init(color: .orange, location: 0.75), .init(color: .yellow, location: 1)]) let linearGradient = LinearGradient(gradient: gradientColors, startPoint: .top, endPoint: .bottom) return VStack(spacing: 20) { Text("Linear Gradient").font(.largeTitle) Text("Color Location").foregroundColor(.gray) Text("By default, colors in a gradient are evenly spaced. But you can customize the color 'stops' or locations when you setup the Gradient object.") .frame(maxWidth: .infinity).padding() .background(Color.pink).foregroundColor(.black) .layoutPriority(1) HStack { VStack { Text("0") Spacer() Text("0.75") .padding(.bottom, 50) Text("1") } Rectangle() .fill(linearGradient) } .frame(height: 300) .padding() }.font(.title) } } struct Linear_ColorLocations_Previews: PreviewProvider { static var previews: some View { Linear_ColorLocations() } }
// // BigLabelButton.swift // QuickDial // // Created by mikewang on 2017/9/19. // Copyright © 2017年 mike. All rights reserved. // import UIKit class BigLabelButton: UIButton { let bigLabel = UILabel() var colorArray:[UIColor]? var colorPressArray:[UIColor]? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) bigLabel.text = "Long Press" // 文字顏色 bigLabel.textColor = UIColor.white // 文字陰影 bigLabel.shadowColor = UIColor.black addSubview(bigLabel) colorArray = [ UIColor(red: 0.91, green: 0.26, blue: 0.12, alpha: 1), UIColor(red: 0.98, green: 0.66, blue: 0.023, alpha: 1), UIColor(red: 0.01, green: 0.63, blue: 0.51, alpha: 1), UIColor(red: 0.04, green: 0.67, blue: 0.86, alpha: 1), UIColor(red: 0.01, green: 0.5, blue: 0.81, alpha: 1) ] colorPressArray = [ UIColor(red: 0.79, green: 0.15, blue: 0, alpha: 1), UIColor(red: 0.86, green: 0.54, blue: 0, alpha: 1), UIColor(red: 0, green: 0.51, blue: 0.4, alpha: 1), UIColor(red: 0, green: 0.55, blue: 0.74, alpha: 1), UIColor(red: 0, green: 0.38, blue: 0.7, alpha: 1) ] if colorArray != nil { backgroundColor = colorArray![tag] } } override var isHighlighted: Bool { didSet { guard colorArray != nil && colorPressArray != nil else { return } switch isHighlighted { case true: backgroundColor = colorPressArray![tag] bigLabel.textColor = UIColor.gray case false: backgroundColor = colorArray![tag] bigLabel.textColor = UIColor.white } } } }
// // Item.swift // FoodZilla // // Created by David Murillo on 6/16/20. // Copyright © 2020 MuriTech. All rights reserved. // import UIKit struct Item { var image:UIImage var name:String var price:Double }