text
stringlengths
8
1.32M
import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { return [ testCase(CircuitKitTests.allTests), testCase(UnitsTests.allTests), testCase(ComplexTests.allTests), testCase(CircuitTests.allTests), testCase(MatrixTests.allTests) ] } #endif
// // MainBigCircle.swift // Connect2U // // Created by Cory Green on 11/28/14. // Copyright (c) 2014 com.Cory. All rights reserved. // import UIKit class MainBigCircle: NSObject { let theMainView:UIView! var radiusOfTheMainCircle:Double? var locationOfCircle:CGPoint? let circle:CAShapeLayer = CAShapeLayer() let palette:ColorPalettes = ColorPalettes() override init() { super.init() } // override init(mainView:UIView, radiusOfCircle:Double, location:CGPoint) { super.init() theMainView = mainView radiusOfTheMainCircle = radiusOfCircle locationOfCircle = location self.createCircle() } func scaleDownCircle(){ var radiusOfCircle = 50.0 circle.path = UIBezierPath(roundedRect: CGRectMake(locationOfCircle!.x - CGFloat(radiusOfTheMainCircle!), locationOfCircle!.y - CGFloat(radiusOfTheMainCircle!), CGFloat(3.0 * radiusOfTheMainCircle!), CGFloat(3.0 * radiusOfTheMainCircle!)), cornerRadius: CGFloat(radiusOfTheMainCircle!)).CGPath // the fill color // circle.fillColor = palette.darkGreenColor.CGColor self.theMainView.layer.addSublayer(circle) } func createCircle(){ circle.path = UIBezierPath(roundedRect: CGRectMake(locationOfCircle!.x - CGFloat(radiusOfTheMainCircle!), locationOfCircle!.y - CGFloat(radiusOfTheMainCircle!), CGFloat(3.0 * radiusOfTheMainCircle!), CGFloat(3.0 * radiusOfTheMainCircle!)), cornerRadius: CGFloat(radiusOfTheMainCircle!)).CGPath // the fill color // circle.fillColor = palette.darkGreenColor.CGColor self.theMainView.layer.addSublayer(circle) } }
@testable import App import Vapor import XCTest import FluentPostgreSQL final class AppTests: XCTestCase { func testNothing() throws { } static let allTests = [ ("testNothing", testNothing) ] }
// // ViewController.swift // SwiftLocale // // Created by Key Hui on 06/23/2018. // Copyright (c) 2018 Key Hui. All rights reserved. // import UIKit import SwiftLocale class ViewController: UIViewController { @IBOutlet var loader: UIActivityIndicatorView! @IBOutlet var textView: UITextView! let kServerPath = "http://localhost/JsonSample/" // let kServerPath = "http://localhost/JsonSampleNew/" let kRootFile = "version.json" override func viewDidLoad() { super.viewDidLoad() textView.text = "" RemoteLocaleManager.shared.initConfig( cacheName: "SwiftLocaleDemo", serverPath: kServerPath, rootFile: kRootFile) // RemoteLocaleManager.shared.clear() startLoading() RemoteLocaleManager.shared.run { response, error in // print("response = \(response?.description ?? "nil")") DispatchQueue.main.async { if let response = response { self.textView.text = response.description + "\n" self.textView.text.append(RemoteLocaleManager.shared.getLocaleModel().toString()) let appNameEN = RemoteLocaleManager.shared.getString(locale: "en", key: "app_name") let appNameTC = RemoteLocaleManager.shared.getString(locale: "tc", key: "app_name") let appNameSC = RemoteLocaleManager.shared.getString(locale: "sc", key: "app_name") self.textView.text.append("\nappNameEN = \(appNameEN)\n") self.textView.text.append("\nappNameTC = \(appNameTC)\n") self.textView.text.append("\nappNameSC = \(appNameSC)\n") } else { self.textView.text = error?.localizedDescription } self.stopLoading() } } } private func startLoading() { DispatchQueue.main.async { self.textView.isHidden = true self.loader.isHidden = false self.loader.startAnimating() } } private func stopLoading() { DispatchQueue.main.async { self.textView.isHidden = false self.loader.isHidden = true self.loader.stopAnimating() } } }
// // ViewController.swift // moodify // // Created by Dilraj Devgun on 10/16/16. // Copyright © 2016 Dilraj Devgun. All rights reserved. // import UIKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { var firstLoad:Bool = true; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(_ animated: Bool) { if (self.firstLoad) { let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil) let nextViewController = storyBoard.instantiateViewController(withIdentifier: "login") as! LoginViewController self.present(nextViewController, animated:true, completion:{() in self.firstLoad = false}) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func uploadButtonPressed(_ sender: AnyObject) { let picker = UIImagePickerController() picker.delegate = self if sender.tag == 1{ picker.sourceType = UIImagePickerControllerSourceType.camera } else if sender.tag == 2 { picker.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum } self.present(picker, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { self.dismiss(animated: true, completion: {() let storyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let uvc: UploadViewController = storyboard.instantiateViewController(withIdentifier: "UploadViewController") as! UploadViewController if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { uvc.imageToPresent = selectedImage self.navigationController?.pushViewController(uvc, animated: true) } }) } }
// // YourPostsViewController.swift // MakeChoice // // Created by 吴梦宇 on 7/12/15. // Copyright (c) 2015 ___mengyu wu___. All rights reserved. // import UIKit import ConvenienceKit import Social import MBProgressHUD class YourPostsViewController: UIViewController,TimelineComponentTarget { @IBOutlet weak var tableView: UITableView! var timelineComponent:TimelineComponent<Post, YourPostsViewController>! let defaultRange = 0...4 let additionalRangeSize = 5 var postId:String?="" var selectedPost:Post? /** This method should load the items within the specified range and call the `completionBlock`, with the items as argument, upon completion. */ func loadInRange(range: Range<Int>, completionBlock: ([Post]?) -> Void){ UICustomSettingHelper.MBProgressHUDLoading(self.view) ParseHelper.timelineRequestforCurrentUserOwn(range){ (result: [AnyObject]?, error: NSError?) -> Void in MBProgressHUD.hideAllHUDsForView(self.view, animated: true) if error != nil{ UICustomSettingHelper.sweetAlertNetworkError() } let posts = result as? [Post] ?? [] completionBlock(posts) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.tableView.dataSource=self self.tableView.delegate=self timelineComponent = TimelineComponent(target: self) timelineComponent.refresh(self) // // tableView.estimatedRowHeight=100 // tableView.rowHeight=UITableViewAutomaticDimension NSNotificationCenter.defaultCenter().addObserver(self, selector: "userPostReceived", name: "UserPost", object: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // TODO: bug, it will crash if tapped before you resfresh // timelineComponent.refresh(self) // tableView.reloadData() //listening for the user post // NSNotificationCenter.defaultCenter().addObserver(self, selector: "userPostReceived", name: "UserPost", object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func userPostReceived(){ println("your posts userPostReceived") timelineComponent.refresh(self) } /* // 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. } */ override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier=="postToDetailSegue") { let postDetailViewController = segue.destinationViewController as! PostDetailViewController postDetailViewController.post=self.selectedPost }else if(segue.identifier=="addressBookSegue") { let addressBookViewController = segue.destinationViewController as! AddressBookViewController addressBookViewController.post=sender as? Post } } } // MARK: dataSouce extension YourPostsViewController: UITableViewDataSource{ func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return 1 } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return timelineComponent.content.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell=tableView.dequeueReusableCellWithIdentifier("YourPostsCell", forIndexPath: indexPath) as! YourPostsTableViewCell let post=timelineComponent.content[indexPath.section] // download, only downloaded with needed post.downloadImage() //get post statistic post.getPostStatistic() cell.post=post cell.title.text=post.title ?? "" cell.title.sizeToFit() //cell.title.lineBreakMode = .ByWordWrapping //setting img radious DesignHelper.setImageCornerRadius(cell.img1) DesignHelper.setImageCornerRadius(cell.img2) //set segue delegate cell.delegate=self return cell } } // MARK: delegate extension YourPostsViewController:UITableViewDelegate{ func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.selectedPost=timelineComponent.content[indexPath.section] self.performSegueWithIdentifier("postToDetailSegue", sender: self) //2 } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { timelineComponent.calledCellForRowAtIndexPath(indexPath) } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if (editingStyle == .Delete) { SweetAlert().showAlert("Are you sure?", subTitle: "Your post will be permanently deleted!", style: AlertStyle.Warning, buttonTitle:"Cancel", buttonColor:UIColor.colorFromRGB(0xD0D0D0) , otherButtonTitle: "Yes, delete it!", otherButtonColor: UIColor.colorFromRGB(0xDD6B55)) { (isOtherButton) -> Void in if isOtherButton == true { print("Cancel Button Pressed", appendNewline: false) tableView.editing=false; } else { let post=self.timelineComponent.content[indexPath.section] let postId=post.objectId ?? "" //UICustomSettingHelper.MBProgressHUDSimple(self.view) ParseHelper.deletePostWithPostId(postId){ (success:Bool, error: NSError?) -> Void in // MBProgressHUD.hideAllHUDsForView(self.view, animated: true) if error != nil{ UICustomSettingHelper.sweetAlertNetworkError() } if success { // refresh self.timelineComponent.refresh(self) NSNotificationCenter.defaultCenter().postNotificationName("DeletePost", object: nil) SweetAlert().showAlert("Deleted!", subTitle: "Your post has been deleted!", style: AlertStyle.Success) } } } } } } } // MARK: YourPostsTableViewCellSegueDelegate extension YourPostsViewController:YourPostsTableViewCellDelegate{ func cell(cell: YourPostsTableViewCell, didSelectAddressBookSegue post: Post){ self.performSegueWithIdentifier("addressBookSegue", sender: post) } func cell(cell: YourPostsTableViewCell, didSelectShareToFacebook post: Post){ UICustomSettingHelper.MBProgressHUDProcessingImages(self.view) var shareToFacebook=SLComposeViewController(forServiceType: SLServiceTypeFacebook) var questions=post.title ?? "" //Add attachment as NSData, post.downloadImageSynchronous() var image1=post.image1.value var image2=post.image2.value var finalImage:UIImage? var finalImageData:NSData? if let image1=image1, image2=image2 { //merge images finalImage=DesignHelper.mergeTwoImages(image1, image2: image2) finalImageData=UIImagePNGRepresentation(finalImage) } shareToFacebook.addImage(finalImage) shareToFacebook.setInitialText("Please help me vote on: \(questions) ") MBProgressHUD.hideAllHUDsForView(self.view, animated: true) self.presentViewController(shareToFacebook,animated:true, completion:nil) } func presentViewController(alertController: UIAlertController) { self.presentViewController(alertController, animated: true, completion: nil) } }
// // SymptomCheckDetailView.swift // CovidAlert // // Created by Matthew Garlington on 12/21/20. // import SwiftUI struct SymptomCheckDetailView: View { @State var isMarked:Bool = false @State var isMarked1:Bool = false @State var isMarked2:Bool = false @State var isMarked3:Bool = false @State var isMarked4:Bool = false @State var isMarked5:Bool = false @State var isMarked6:Bool = false @State var isMarked7:Bool = false @State var isMarked8:Bool = false @State var isMarked9:Bool = false @State var isMarkedBar:Bool = false var body: some View { ScrollView { VStack(spacing: 30) { Text("What Symptoms do you Currently have? (Check all that Apply) :") .bold() .font(.title2) ZStack(alignment: .leading) { Spacer() .frame(width: 375, height: 100) .background(Color(.init(white: 0.95, alpha: 1))) .cornerRadius(30) .shadow(radius: 10) HStack { Text("Fever or chills") .foregroundColor(.black) .font(.headline) .fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/) .padding(.horizontal) Spacer() Button(action:{ self.isMarked.toggle() }) { Image(systemName: self.isMarked ? "checkmark.circle.fill" : "checkmark.circle") .renderingMode(.original) .font(.title) }.padding() } } ZStack(alignment: .leading) { Spacer() .frame(width: 375, height: 100) .background(Color(.init(white: 0.95, alpha: 1))) .cornerRadius(30) .shadow(radius: 10) HStack { Text("Cough") .foregroundColor(.black) .font(.headline) .fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/) .padding(.horizontal) Spacer() Button(action:{ self.isMarked1.toggle() }) { Image(systemName: self.isMarked1 ? "checkmark.circle.fill" : "checkmark.circle") .renderingMode(.original) .font(.title) }.padding() } } ZStack(alignment: .leading) { Spacer() .frame(width: 375, height: 100) .background(Color(.init(white: 0.95, alpha: 1))) .cornerRadius(30) .shadow(radius: 10) HStack { Text("Shortness of breath or difficulty breathing") .foregroundColor(.black) .font(.headline) .fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/) .padding(.horizontal) Spacer() Button(action:{ self.isMarked2.toggle() }) { Image(systemName: self.isMarked2 ? "checkmark.circle.fill" : "checkmark.circle") .renderingMode(.original) .font(.title) }.padding() } } ZStack(alignment: .leading) { Spacer() .frame(width: 375, height: 100) .background(Color(.init(white: 0.95, alpha: 1))) .cornerRadius(30) .shadow(radius: 10) HStack { Text("Fatigue") .foregroundColor(.black) .font(.headline) .fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/) .padding(.horizontal) Spacer() Button(action:{ self.isMarked3.toggle() }) { Image(systemName: self.isMarked3 ? "checkmark.circle.fill" : "checkmark.circle") .renderingMode(.original) .font(.title) }.padding() } } ZStack(alignment: .leading) { Spacer() .frame(width: 375, height: 100) .background(Color(.init(white: 0.95, alpha: 1))) .cornerRadius(30) .shadow(radius: 10) HStack { Text("Muscle or body aches") .foregroundColor(.black) .font(.headline) .fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/) .padding(.horizontal) Spacer() Button(action:{ self.isMarked4.toggle() }) { Image(systemName: self.isMarked4 ? "checkmark.circle.fill" : "checkmark.circle") .renderingMode(.original) .font(.title) }.padding() } } ZStack(alignment: .leading) { Spacer() .frame(width: 375, height: 100) .background(Color(.init(white: 0.95, alpha: 1))) .cornerRadius(30) .shadow(radius: 10) HStack { Text("Headache") .foregroundColor(.black) .font(.headline) .fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/) .padding(.horizontal) Spacer() Button(action:{ self.isMarked5.toggle() }) { Image(systemName: self.isMarked5 ? "checkmark.circle.fill" : "checkmark.circle") .renderingMode(.original) .font(.title) }.padding() } } ZStack(alignment: .leading) { Spacer() .frame(width: 375, height: 100) .background(Color(.init(white: 0.95, alpha: 1))) .cornerRadius(30) .shadow(radius: 10) HStack { Text("New loss of Taste or Smell") .foregroundColor(.black) .font(.headline) .fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/) .padding(.horizontal) Spacer() Button(action:{ self.isMarked6.toggle() }) { Image(systemName: self.isMarked6 ? "checkmark.circle.fill" : "checkmark.circle") .renderingMode(.original) .font(.title) }.padding() } } ZStack(alignment: .leading) { Spacer() .frame(width: 375, height: 100) .background(Color(.init(white: 0.95, alpha: 1))) .cornerRadius(30) .shadow(radius: 10) HStack { Text("Sore Throat") .foregroundColor(.black) .font(.headline) .fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/) .padding(.horizontal) Spacer() Button(action:{ self.isMarked7.toggle() }) { Image(systemName: self.isMarked7 ? "checkmark.circle.fill" : "checkmark.circle") .renderingMode(.original) .font(.title) }.padding() } } ZStack(alignment: .leading) { Spacer() .frame(width: 375, height: 100) .background(Color(.init(white: 0.95, alpha: 1))) .cornerRadius(30) .shadow(radius: 10) HStack { Text("Nausea or Vomiting") .foregroundColor(.black) .font(.headline) .fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/) .padding(.horizontal) Spacer() Button(action:{ self.isMarked8.toggle() }) { Image(systemName: self.isMarked8 ? "checkmark.circle.fill" : "checkmark.circle") .renderingMode(.original) .font(.title) }.padding() } } }.padding(.horizontal) VStack { NavigationLink( destination: QuestionarreLineOfWorkView(), label: { ZStack{ Spacer() .frame(width: 400, height: 75) .background(Color.blue) .cornerRadius(30) .shadow(radius: 10) Text("Next") .foregroundColor(.white) .bold() .font(.title2) } }) }.padding(.top, 75) } } } struct SymptomCheckDetailView_Previews: PreviewProvider { static var previews: some View { SymptomCheckDetailView() } }
// // ViewController.swift // Radios Argentina // // Created by Marcos Ocon on 19/05/2020. // Copyright © 2020 Marcos Ocon. All rights reserved. // import UIKit class StationsViewController: UIViewController { @IBAction func onListenButtonPress(_ sender: UIButton) { self.performSegue(withIdentifier: "GoToPlayerScreen", sender: self) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "GoToPlayerScreen" { let playerVC = segue.destination as! PlayerViewController playerVC.stationName = "Testing Bananas" } } }
// // GZEDatesService.swift // Gooze // // Created by Yussel on 3/27/18. // Copyright © 2018 Gooze. All rights reserved. // import Foundation import Gloss import SocketIO import ReactiveSwift import Alamofire import enum Result.NoError class GZEDatesService: NSObject { static let shared = GZEDatesService() let dateRequestRepository: GZEDateRequestRepositoryProtocol = GZEDateRequestApiRepository() let userRepository: GZEUserRepositoryProtocol = GZEUserApiRepository() let bgSessionManager: SessionManager let lastReceivedRequest = MutableProperty<GZEDateRequest?>(nil) let receivedRequests = MutableProperty<[GZEDateRequest]>([]) let lastSentRequest = MutableProperty<GZEDateRequest?>(nil) let sentRequests = MutableProperty<[GZEDateRequest]>([]) var activeRequest: MutableProperty<GZEDateRequest>? let userLastLocation = MutableProperty<GZEUser?>(nil) var sendLocationDisposable: Disposable? var socketEventsDisposable: Disposable? var dateSocket: DatesSocket? { return GZESocketManager.shared[DatesSocket.namespace] as? DatesSocket } override init() { let configuration = URLSessionConfiguration.background(withIdentifier: "net.gooze.app.background") self.bgSessionManager = Alamofire.SessionManager(configuration: configuration) super.init() receivedRequests.signal.observeValues { log.debug("receivedRequests changed: \(String(describing: $0.toJSONArray()))") } sentRequests.signal.observeValues { log.debug("sentRequests changed: \(String(describing: $0.toJSONArray()))") } } func findUnrespondedRequests() -> SignalProducer<[GZEDateRequest], GZEError> { return self.dateRequestRepository.findUnresponded() } func find(byId id: String) -> SignalProducer<GZEDateRequest, GZEError> { guard let dateSocket = self.dateSocket else { log.error("Date socket not found") return SignalProducer(error: .datesSocket(error: DatesSocketError.unexpected)) } log.debug("finding date request... [id=\(id)]") return SignalProducer { sink, disposable in disposable.add { log.debug("find request signal disposed") } dateSocket.emitWithAck(.findRequestById, id).timingOut(after: GZESocket.ackTimeout) {[weak self] data in if let data = data[0] as? String, data == SocketAckStatus.noAck.rawValue { log.error("No ack received from server") sink.send(error: .datesSocket(error: .noAck)) return } if let errorJson = data[0] as? JSON, let error = GZEApiError(json: errorJson) { log.error("\(String(describing: error.toJSON()))") sink.send(error: .datesSocket(error: .unexpected)) } else if let dateRequestJson = data[1] as? JSON, let dateRequest = GZEDateRequest(json: dateRequestJson) { self?.upsert(dateRequest: dateRequest) sink.send(value: dateRequest) } else { log.error("Unable to parse data to expected objects") sink.send(error: .datesSocket(error: .unexpected)) } } } } func requestDate(to recipientId: String) -> SignalProducer<GZEDateRequest, GZEError> { guard let dateSocket = self.dateSocket else { log.error("Date socket not found") return SignalProducer(error: .datesSocket(error: .unexpected)) } log.debug("sending date request...") return SignalProducer { sink, disposable in dateSocket.emitWithAck(.dateRequestSent, recipientId).timingOut(after: GZESocket.ackTimeout) {[weak self] data in log.debug("ack data: \(data)") disposable.add { log.debug("acceptDateRequest signal disposed") } if let data = data[0] as? String, data == SocketAckStatus.noAck.rawValue { log.error("No ack received from server") sink.send(error: .datesSocket(error: .noAck)) return } if let errorJson = data[0] as? JSON, let error = GZEApiError(json: errorJson) { self?.handleError(error, sink) } else if let dateRequestJson = data[1] as? JSON, let dateRequest = GZEDateRequest(json: dateRequestJson) { log.debug("Date request successfully sent") self?.sentRequests.value.upsert(dateRequest){$0 == dateRequest} self?.lastSentRequest.value = dateRequest sink.send(value: dateRequest) sink.sendCompleted() } else { log.error("Unable to parse data to expected objects") sink.send(error: .datesSocket(error: .unexpected)) } } } } func acceptDateRequest(withId requestId: String?) -> SignalProducer<GZEDateRequest, GZEError> { guard let dateSocket = self.dateSocket else { log.error("Date socket not found") return SignalProducer(error: .datesSocket(error: .unexpected)) } guard let requestId = requestId else { log.error("Request id is required to accept a request") return SignalProducer(error: .datesSocket(error: .unexpected)) } return SignalProducer { sink, disposable in log.debug("emitting accept request...") dateSocket.emitWithAck(.acceptRequest, requestId).timingOut(after: GZESocket.ackTimeout) {[weak self] data in log.debug("ack data: \(data)") disposable.add { log.debug("acceptDateRequest signal disposed") } if let data = data[0] as? String, data == SocketAckStatus.noAck.rawValue { log.error("No ack received from server") sink.send(error: .datesSocket(error: .noAck)) return } if let errorJson = data[0] as? JSON, let error = GZEApiError(json: errorJson) { self?.handleError(error, sink) } else if let dateRequestJson = data[1] as? JSON, let dateRequest = GZEDateRequest(json: dateRequestJson) { log.debug("Date request successfully accepted") GZEDatesService.shared.receivedRequests.value.upsert(dateRequest) {$0 == dateRequest} GZEDatesService.shared.lastReceivedRequest.value = dateRequest sink.send(value: dateRequest) sink.sendCompleted() } else { log.error("Unable to parse data to expected objects") sink.send(error: .datesSocket(error: .unexpected)) } } } } func createCharge( dateRequest: GZEDateRequest, amount: Decimal, clientTaxAmount: Decimal, goozeTaxAmount: Decimal, paymentMethodToken: String? = nil, paymentMethodNonce: String? = nil, senderId: String, username: String, chat: GZEChat, mode: GZEChatViewMode ) -> SignalProducer<(GZEDateRequest, GZEUser), GZEError> { return dateRequestRepository.createCharge( dateRequest: dateRequest, amount: amount, clientTaxAmount: clientTaxAmount, goozeTaxAmount: goozeTaxAmount, paymentMethodToken: paymentMethodToken, paymentMethodNonce: paymentMethodNonce, senderId: senderId, username: username, chat: chat, mode: mode ) } func createCharge(requestId: String, senderId: String, username: String, chat: GZEChat, mode: GZEChatViewMode) -> SignalProducer<GZEDateRequest, GZEError> { guard let dateSocket = self.dateSocket else { log.error("Date socket not found") return SignalProducer(error: .datesSocket(error: .unexpected)) } guard let chatJson = chat.toJSON() else { log.error("Failed to parse GZEChat to JSON") return SignalProducer(error: .datesSocket(error: .unexpected)) } guard let messageJson = GZEChatMessage(text: "service.dates.dateCreated", senderId: senderId, chatId: chat.id, type: .info).toJSON() else { log.error("Failed to parse GZEChatMessage to JSON") return SignalProducer(error: .datesSocket(error: .unexpected)) } return SignalProducer { sink, disposable in log.debug("emitting create date event...") dateSocket.emitWithAck(.createCharge, requestId, messageJson, username, chatJson, mode.rawValue).timingOut(after: GZESocket.ackTimeout) {data in log.debug("ack data: \(data)") disposable.add { log.debug("acceptDateRequest signal disposed") } if let data = data[0] as? String, data == SocketAckStatus.noAck.rawValue { log.error("No ack received from server") sink.send(error: .datesSocket(error: .noAck)) return } if let errorJson = data[0] as? JSON, let error = GZEApiError(json: errorJson) { log.error("\(String(describing: error.toJSON()))") sink.send(error: .datesSocket(error: .unexpected)) } else if let dateRequestJson = data[1] as? JSON, let dateRequest = GZEDateRequest(json: dateRequestJson), let userJson = data[2] as? JSON, let user = GZEUser(json: userJson) { if user.id == GZEAuthService.shared.authUser?.id { GZEAuthService.shared.authUser = user } else { log.error("Missmatch user received") } log.debug("Date successfully created") GZEDatesService.shared.upsert(dateRequest: dateRequest) GZEDatesService.shared.sendLocationUpdate(to: dateRequest.recipient.id, dateRequest: dateRequest) sink.send(value: dateRequest) sink.sendCompleted() } else { log.error("Unable to parse data to expected objects") sink.send(error: .datesSocket(error: .unexpected)) } } } } func startDate(_ dateRequest: GZEDateRequest) -> SignalProducer<GZEDateRequest, GZEError> { return self.dateRequestRepository.startDate(dateRequest) .map{ let (dateRequest, user) = $0 if user.id == GZEAuthService.shared.authUser?.id { GZEAuthService.shared.authUser = user } else { log.error("Missmatch user received") } return dateRequest } } func endDate(_ dateRequest: GZEDateRequest) -> SignalProducer<GZEDateRequest, GZEError> { return self.dateRequestRepository.endDate(dateRequest) .map{ let (dateRequest, user) = $0 if user.id == GZEAuthService.shared.authUser?.id { GZEAuthService.shared.authUser = user } else { log.error("Missmatch user received") } return dateRequest } } func cancelDate(_ dateRequest: GZEDateRequest) -> SignalProducer<GZEDateRequest, GZEError> { return self.dateRequestRepository.cancelDate(dateRequest) .map{ let (dateRequest, user) = $0 if user.id == GZEAuthService.shared.authUser?.id { GZEAuthService.shared.authUser = user } else { log.error("Missmatch user received") } return dateRequest } } func sendLocationUpdate(to recipientId: String, dateRequest: GZEDateRequest) { guard let authUser = GZEAuthService.shared.authUser else {return} let user = GZEUser( id: authUser.id, username: authUser.username, email: authUser.email ) sendLocationDisposable?.dispose() GZELocationService.shared.startUpdatingLocation(background: true) sendLocationDisposable = GZELocationService.shared.lastLocation.producer.skipNil().throttle(1.0, on: QueueScheduler.main) .flatMap(.latest){[weak self] location -> SignalProducer<Bool, GZEError> in user.currentLocation = GZEUser.GeoPoint(CLCoord: location.coordinate) guard let this = self else {return SignalProducer.empty} let isArriving = location.distance(from: dateRequest.location.toCLLocation()) < 100 if UIApplication.shared.applicationState == .background { return this.sendLocationUpdateInBackground(to: recipientId, user: user, isArriving: isArriving, dateRequestId: dateRequest.id).throttle(10.0, on: QueueScheduler.main).flatMapError{ error in log.error(error.localizedDescription) return SignalProducer.empty } } else { return this.sendLocationUpdateInForeground(to: recipientId, user: user, isArriving: isArriving, dateRequestId: dateRequest.id).flatMapError{ error in log.error(error.localizedDescription) return SignalProducer.empty } } } .take(during: self.reactive.lifetime) .start { event in log.debug("send location event received: \(event)") } } func stopSendingLocationUpdates() { GZELocationService.shared.stopUpdatingLocation() self.sendLocationDisposable?.dispose() } func sendLocationUpdateInForeground(to recipientId: String, user: GZEUser, isArriving: Bool, dateRequestId: String) -> SignalProducer<Bool, GZEError> { log.debug("sendLocationUpdateInForeground") guard let dateSocket = self.dateSocket else { log.error("Date socket not found") return SignalProducer(error: .datesSocket(error: .unexpected)) } guard let userJson = user.toJSON() else { log.error("Failed to parse GZEUser to JSON") return SignalProducer(error: .datesSocket(error: .unexpected)) } return SignalProducer { sink, disposable in log.debug("emitting updateLocation...") dateSocket.emitWithAck(.updateLocation, recipientId, userJson, isArriving, dateRequestId).timingOut(after: GZESocket.ackTimeout) {data in log.debug("ack data: \(data)") disposable.add { log.debug("sendLocationUpdateInForeground signal disposed") } if let data = data[0] as? String, data == SocketAckStatus.noAck.rawValue { log.error("No ack received from server") sink.send(error: .datesSocket(error: .noAck)) return } if let errorJson = data[0] as? JSON, let error = GZEApiError(json: errorJson) { log.error("\(String(describing: error.toJSON()))") sink.send(error: .datesSocket(error: .unexpected)) } else { log.debug("Location successfully updated") sink.sendCompleted() } } } } func sendLocationUpdateInBackground(to recipientId: String, user: GZEUser, isArriving: Bool, dateRequestId: String) -> SignalProducer<Bool, GZEError> { log.debug("sendLocationUpdateInBackground") guard let userJson = user.toJSON() else { log.error("Failed to parse GZEUser to JSON") return SignalProducer(error: .datesSocket(error: .unexpected)) } return SignalProducer {[weak self] sink, disposable in disposable.add { log.debug("sendLocationUpdateInBackground signal disposed") } guard let this = self else { log.error("self was disposed") sink.send(error: .datesSocket(error: .unexpected)) return } let params: [String: Any] = ["location": [ "recipientId": recipientId, "user": userJson, "isArriving": isArriving, "dateRequestId": dateRequestId ]] this.bgSessionManager.request(GZEUserRouter.sendLocationUpdate(parameters: params)) .responseJSON(completionHandler: GZEApi.createResponseHandler(sink: sink, createInstance: { (json: JSON) in return true })) } } func upsert(dateRequest: GZEDateRequest) { guard let authUser = GZEAuthService.shared.authUser else { log.error("auth user not found") return } if dateRequest.sender.id == authUser.id { self.sentRequests.value.upsert(dateRequest){$0 == dateRequest} self.lastSentRequest.value = dateRequest } else if dateRequest.recipient.id == authUser.id { self.receivedRequests.value.upsert(dateRequest) {$0 == dateRequest} self.lastReceivedRequest.value = dateRequest } } func listenSocketEvents() { self.socketEventsDisposable?.dispose() self.socketEventsDisposable = self.dateSocket?.socketEventsEmitter .signal .skipNil() .filter{$0 == .authenticated} .flatMap(.latest) { _ -> SignalProducer<GZEUser, NoError> in return GZEAuthService.shared.loadAuthUser() .flatMapError{ error in log.error(error) GZEDatesService.shared.stopSendingLocationUpdates() return SignalProducer.empty } } .flatMap(.latest) { user -> SignalProducer<(GZEUser.Mode, GZEDateRequest?), NoError> in guard let mode = user.mode, user.status == .onDate else { GZEDatesService.shared.stopSendingLocationUpdates() return SignalProducer.empty } let findBy: String if mode == .gooze { findBy = "recipientId" } else { findBy = "senderId" } return GZEDatesService.shared.dateRequestRepository.findActiveDate(by: findBy) .map{(mode, $0.first)} .flatMapError{ error in log.error(error) GZEDatesService.shared.stopSendingLocationUpdates() return SignalProducer.empty } } .observeValues { (mode, dateRequest) in guard let dateRequest = dateRequest, let date = dateRequest.date, date.status == .route || date.status == .starting && (mode == .gooze && !date.recipientStarted || mode == .client && !date.senderStarted) else { GZEDatesService.shared.stopSendingLocationUpdates() return } if mode == .gooze { GZEDatesService.shared.sendLocationUpdate(to: dateRequest.sender.id, dateRequest: dateRequest) } else { GZEDatesService.shared.sendLocationUpdate(to: dateRequest.recipient.id, dateRequest: dateRequest) } } } func handleError(_ error: GZEApiError, _ sink: Observer<GZEDateRequest, GZEError>) { guard let errorCode = error.code else { log.error("\(String(describing: error.toJSON()))") sink.send(error: .datesSocket(error: .unexpected)) return } if let datesError = DatesSocketError(rawValue: errorCode) { log.debug("Error: \(datesError)") sink.send(error: .datesSocket(error: datesError)) return } if errorCode == GZEApiError.Code.userIncompleteProfile.rawValue { log.error("\(String(describing: error.toJSON()))") sink.send(error: .repository(error: .GZEApiError(error: error))) return } log.error("\(String(describing: error.toJSON()))") sink.send(error: .datesSocket(error: .unexpected)) return } func cleanup() { self.socketEventsDisposable?.dispose() self.stopSendingLocationUpdates() self.sentRequests.value = [] self.receivedRequests.value = [] } // MARK: deinit deinit { log.debug("\(self) disposed") } }
// // ThirdPageViewController.swift // macro-tracker // // Created by Felix on 2020-03-09. // Copyright © 2020 Felix. All rights reserved. // import UIKit protocol ThirdPageViewControllerDelegate: AnyObject { } class ThirdPageViewController: UIViewController { weak var delegate: ThirdPageViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .orange } }
// // YelpTableViewCell.swift // Yelp // // Created by Gabriel Santos on 2/13/15. // Copyright (c) 2015 Gabriel Santos. All rights reserved. // import UIKit class YelpTableViewCell: UITableViewCell { @IBOutlet weak var mainPicture: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var ratingImage: UIImageView! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var genreLabel: UILabel! @IBOutlet weak var reviewLabel: UILabel! @IBOutlet weak var distanceLabel: UILabel! func setData(data: NSDictionary, index: Int) { // println(data) if let image_url = data["image_url"] as? String { let url = NSURL(string: image_url) mainPicture.setImageWithURL(url) } if let name = data["name"] as? String { titleLabel.text = "\(index). \(name)" } if let rating_img_url = data["rating_img_url"] as? String { let url = NSURL(string: rating_img_url) ratingImage.setImageWithURL(url) } if let location = data["location"] as? NSDictionary { if let display_address = location["display_address"] as? NSArray { addressLabel.text = "\(display_address[0]), \(display_address[1])" } if let coordinate = location["coordinate"] as? NSDictionary { if let latitude = coordinate["latitude"] as? Float { if let longitude = coordinate["longitude"] as? Float { // println("coord: \(latitude),\(longitude)") let geoLoc = GeoCoordinate(latitude: latitude, longitude: longitude) let code_path_boot_camp_geo_location = GeoCoordinate(latitude: 37.770706, longitude: -122.403511) let dist = code_path_boot_camp_geo_location.DistanceInMiles(geoLoc) distanceLabel.text = String(format: "%.1f mi", dist) } } } } if let categories = data["categories"] as? NSArray { var str = "" for (var i = 0; i < categories.count; i++) { if let categ = categories[i] as? NSArray { if let s = categ[0] as? String { str += s if i < categories.count - 1 { str += ", " } } } } genreLabel.text = str } if let reviews = data["review_count"] as? Int { reviewLabel.text = "\(reviews) reviews" } } 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 } }
// UIAlertControllerExtensions.swift - Copyright 2020 SwifterSwift #if canImport(UIKit) && !os(watchOS) import UIKit #if canImport(AudioToolbox) import AudioToolbox #endif // MARK: - Methods public extension UIAlertController { /// SwifterSwift: Present alert view controller in the current view controller. /// /// - Parameters: /// - animated: set true to animate presentation of alert controller (default is true). /// - vibrate: set true to vibrate the device while presenting the alert (default is false). /// - completion: an optional completion handler to be called after presenting alert controller (default is nil). @available(iOSApplicationExtension, unavailable) @available(visionOS, unavailable) func show(animated: Bool = true, vibrate: Bool = false, completion: (() -> Void)? = nil) { #if targetEnvironment(macCatalyst) let window = UIApplication.shared.windows.last #else let window = UIApplication.shared.keyWindow #endif window?.rootViewController?.present(self, animated: animated, completion: completion) if vibrate { #if canImport(AudioToolbox) AudioServicesPlayAlertSound(kSystemSoundID_Vibrate) #endif } } /// SwifterSwift: Add an action to Alert. /// /// - Parameters: /// - title: action title. /// - style: action style (default is UIAlertActionStyle.default). /// - isEnabled: isEnabled status for action (default is true). /// - handler: optional action handler to be called when button is tapped (default is nil). /// - Returns: action created by this method. @discardableResult func addAction( title: String, style: UIAlertAction.Style = .default, isEnabled: Bool = true, handler: ((UIAlertAction) -> Void)? = nil) -> UIAlertAction { let action = UIAlertAction(title: title, style: style, handler: handler) action.isEnabled = isEnabled addAction(action) return action } /// SwifterSwift: Add a text field to Alert. /// /// - Parameters: /// - text: text field text (default is nil). /// - placeholder: text field placeholder text (default is nil). /// - editingChangedTarget: an optional target for text field's editingChanged. /// - editingChangedSelector: an optional selector for text field's editingChanged. func addTextField( text: String? = nil, placeholder: String? = nil, editingChangedTarget: Any?, editingChangedSelector: Selector?) { addTextField { textField in textField.text = text textField.placeholder = placeholder if let target = editingChangedTarget, let selector = editingChangedSelector { textField.addTarget(target, action: selector, for: .editingChanged) } } } } // MARK: - Initializers public extension UIAlertController { /// SwifterSwift: Create new alert view controller with default OK action. /// /// - Parameters: /// - title: alert controller's title. /// - message: alert controller's message (default is nil). /// - defaultActionButtonTitle: default action button title (default is "OK"). /// - tintColor: alert controller's tint color (default is nil). convenience init( title: String, message: String? = nil, defaultActionButtonTitle: String = "OK", tintColor: UIColor? = nil) { self.init(title: title, message: message, preferredStyle: .alert) let defaultAction = UIAlertAction(title: defaultActionButtonTitle, style: .default, handler: nil) addAction(defaultAction) if let color = tintColor { view.tintColor = color } } /// SwifterSwift: Create new error alert view controller from Error with default OK action. /// /// - Parameters: /// - title: alert controller's title (default is "Error"). /// - error: error to set alert controller's message to it's localizedDescription. /// - defaultActionButtonTitle: default action button title (default is "OK"). /// - preferredStyle: type of alert to display (default is .alert). /// - tintColor: alert controller's tint color (default is nil). convenience init( title: String = "Error", error: Error, defaultActionButtonTitle: String = "OK", preferredStyle: UIAlertController.Style = .alert, tintColor: UIColor? = nil) { self.init(title: title, message: error.localizedDescription, preferredStyle: preferredStyle) let defaultAction = UIAlertAction(title: defaultActionButtonTitle, style: .default, handler: nil) addAction(defaultAction) if let color = tintColor { view.tintColor = color } } } #endif
// // ViewController.swift // FamilyFeud // // Created by GC Student on 10/8/15. // Copyright © 2015 GC Student. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var userInputField: UITextField! var topics = Topics() let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "Default") override func viewDidLoad() { super.viewDidLoad() cell.hidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return topics.bathroomItems.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "Default") cell.textLabel?.text = topics.bathroomItems[indexPath.row] return cell } @IBAction func guessButtonPressed(sender: AnyObject) { for word in topics.bathroomItems { print(word) if userInputField.text! == word { cell.hidden = false } else { print("Nope") } } } }
// // APIKeysIntegrationTests.swift // // // Created by Vladislav Fitc on 22/04/2020. // import Foundation import XCTest @testable import AlgoliaSearchClient class APIKeysIntegrationTests: IntegrationTestCase { override var indexNameSuffix: String? { return "apiKeys" } var keyToDelete: APIKey? override var retryableTests: [() throws -> Void] { [apiKeys] } override var allowFailure: Bool { true } func apiKeys() throws { let parameters = APIKeyParameters(ACLs: [.search]) .set(\.description, to: "A description") .set(\.indices, to: ["index"]) .set(\.maxHitsPerQuery, to: 1000) .set(\.maxQueriesPerIPPerHour, to: 1000) .set(\.query, to: Query().set(\.typoTolerance, to: .strict)) .set(\.referers, to: ["referer"]) .set(\.validity, to: 600) let addedKey = try client.addAPIKey(with: parameters) keyToDelete = addedKey.key var keyResponseContainer: APIKeyResponse? = nil func checkKey(exists expectExists: Bool, attempts: Int = 100) throws { // There is no way to be notified about the succesful operation with the API key // That's why the operation performed multiple times until the expected key state achieved for _ in 0...attempts { if !expectExists { keyResponseContainer = nil } do { keyResponseContainer = try client.getAPIKey(addedKey.key) if expectExists { break } else { continue } } catch let error { if case TransportError.httpError(let httpError) = error, httpError.statusCode == 404 { if expectExists { continue } else { break } } else { throw error } } } } try checkKey(exists: true) guard let addedKeyResponse = keyResponseContainer else { XCTFail("Key fetch failed") return } keyResponseContainer = nil XCTAssertEqual(addedKeyResponse.key, addedKey.key) XCTAssertEqual(addedKeyResponse.ACLs, [.search]) XCTAssertEqual(addedKeyResponse.description, parameters.description) XCTAssertEqual(addedKeyResponse.indices, parameters.indices) XCTAssertEqual(addedKeyResponse.maxHitsPerQuery, parameters.maxHitsPerQuery) XCTAssertEqual(addedKeyResponse.maxQueriesPerIPPerHour, parameters.maxQueriesPerIPPerHour) XCTAssertEqual(addedKeyResponse.query, "typoTolerance=strict") XCTAssertEqual(addedKeyResponse.referers, ["referer"]) XCTAssertLessThan(addedKeyResponse.validity, 600) XCTAssertGreaterThan(addedKeyResponse.validity, 500) let keysList = try client.listAPIKeys().keys XCTAssert(keysList.contains(where: { $0.key == addedKey.key })) try client.updateAPIKey(addedKey.key, with: APIKeyParameters(ACLs: []).set(\.maxHitsPerQuery, to: 42)) for _ in 0...100 { keyResponseContainer = try client.getAPIKey(addedKey.key) if keyResponseContainer?.maxHitsPerQuery == 42 { break } } guard let updatedKeyResponse = keyResponseContainer else { XCTFail("Key update failed") return } keyResponseContainer = nil XCTAssertEqual(updatedKeyResponse.maxHitsPerQuery, 42) try client.deleteAPIKey(addedKey.key) try checkKey(exists: false) XCTAssertNil(keyResponseContainer) try client.restoreAPIKey(addedKey.key) try checkKey(exists: true) guard let restoredKeyResponse = keyResponseContainer else { XCTFail("Key restoration failed") return } keyResponseContainer = nil XCTAssertEqual(restoredKeyResponse.key, addedKey.key) } override func tearDownWithError() throws { try super.tearDownWithError() if let keyToDelete = keyToDelete { try client.deleteAPIKey(keyToDelete) } } }
// // ViewController.swift // myFaultReporter // // Created by Henry McC on 2017/03/30. // Copyright © 2017 HiddenPlatform. All rights reserved. // import UIKit import MapKit import FirebaseDatabase class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var crosshair: UIImageView! @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var imgHolder: UIImageView! @IBOutlet weak var borderImg: UIImageView! @IBOutlet weak var typePckr: UIPickerView! var pickerDataOne = [""] let locationManager = CLLocationManager() var mapHasCentredOnce = false var geoFire: GeoFire! var geoFireRef: FIRDatabaseReference! override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self typePckr.delegate = self typePckr.dataSource = self //this will keep track of the user populatePickers() getSegmentIndex() mapView.userTrackingMode = MKUserTrackingMode.follow //crosshair.alpha = 0 geoFireRef = FIRDatabase.database().reference() geoFire = GeoFire(firebaseRef: geoFireRef) } override func viewDidAppear(_ animated: Bool) { locationAuthStatus() } //////////////Authorization func locationAuthStatus() { if CLLocationManager.authorizationStatus() == .authorizedWhenInUse{ mapView.showsUserLocation = true }else{ locationManager.requestWhenInUseAuthorization() } } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == CLAuthorizationStatus.authorizedWhenInUse { mapView.showsUserLocation = true } } func centerMapOnLocation(location: CLLocation){ let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 150, 150) mapView.setRegion(coordinateRegion, animated: true) } //One time use so first load of map and centred location. func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) { if let loc = userLocation.location { if !mapHasCentredOnce { centerMapOnLocation(location: loc) showSightingsOnMap(location: loc) crosshair.center = CGPoint(x: imgHolder.frame.width/2, y: imgHolder.frame.height/2 + borderImg.frame.height + 35) // activityIndicator.center = CGPointMake(view.width/2, view.height/2) mapHasCentredOnce = true } } } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { var annotationView: MKAnnotationView? let annoIdentifier = "Pokemon" if annotation.isKind(of: MKUserLocation.self){ annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "User") annotationView?.image = UIImage(named: "person") }else if let deqAnno = mapView.dequeueReusableAnnotationView(withIdentifier: annoIdentifier) { annotationView = deqAnno annotationView?.annotation = annotation }else { let av = MKAnnotationView(annotation: annotation, reuseIdentifier: annoIdentifier) av.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) annotationView = av } if let annotationView = annotationView, let anno = annotation as? PokeAnnotation { annotationView.canShowCallout = true annotationView.image = UIImage(named: "\(anno.pokemonNumber)") let btn = UIButton() btn.frame = CGRect(x: 0, y: 0, width: 30, height: 30) //image size btn.setImage(UIImage(named: "map"), for: .normal) annotationView.rightCalloutAccessoryView = btn } return annotationView } func createSighting(forLocation location: CLLocation, withPokemon pokeId: Int){ geoFire.setLocation(location, forKey: "\(pokeId)") } func showSightingsOnMap(location: CLLocation){ let circleQuery = geoFire!.query(at: location, withRadius: 2.5) _ = circleQuery?.observe(GFEventType.keyEntered, with: { (key, location) in if let key = key, let location = location { let anno = PokeAnnotation(coordinate: location.coordinate, pokemonNumber: Int(key)!) self.mapView.addAnnotation(anno) } }) } func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) { crosshair.alpha = CGFloat(0.25) let loc = CLLocation(latitude: mapView.centerCoordinate.latitude, longitude: mapView.centerCoordinate.longitude) showSightingsOnMap(location: loc) } func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) { crosshair.alpha = 0 var center = mapView.centerCoordinate } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if let anno = view.annotation as? PokeAnnotation { let place = MKPlacemark(coordinate: anno.coordinate) let destination = MKMapItem(placemark: place) destination.name = "Reported Fault" ////CHANGE THIS TO WHATEVER IS SAVED IN Firebase let regionDistance: CLLocationDistance = 1000 let regionSpan = MKCoordinateRegionMakeWithDistance(anno.coordinate, regionDistance, regionDistance) let option = [MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center),MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving] as [String: Any] MKMapItem.openMaps(with: [destination], launchOptions: option) } } //Set up the picker delegate and datasource func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerDataOne.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return pickerDataOne[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { //call the function that will manage the selection } func populatePickers(){ } func getSegmentIndex(){ switch segmentedControl.selectedSegmentIndex { case 0: pickerDataOne = ["Theft","Vandalism","Graffiti"] typePckr.selectRow(0, inComponent: 0, animated: true) typePckr.reloadAllComponents() case 1: pickerDataOne = ["Pothole","Traffic Lights","Burst Pipe"] typePckr.selectRow(0, inComponent: 0, animated: true) typePckr.reloadAllComponents() default: break; } } @IBOutlet weak var segmentedControl: UISegmentedControl! @IBAction func indexChanged(_ sender: UISegmentedControl) { getSegmentIndex() } @IBAction func submitCurrentLocation(_ sender: Any) { let location = CLLocation(latitude: mapView.centerCoordinate.latitude, longitude: mapView.centerCoordinate.longitude) let rand = arc4random_uniform(20) + 1 createSighting(forLocation: location, withPokemon: Int(rand)) showSightingsOnMap(location: location) } }
// // Weather.swift // SailingThroughHistory // // Created by Jason Chong on 14/3/19. // Copyright © 2019 Sailing Through History Team. All rights reserved. // import UIKit class Weather: Volatile { var windVelocity: Float = 0 let strengths: [Float] = Default.Weather.strengths /// Update the oldVelocity with influence of weather. override func applyVelocityModifier(to oldVelocity: Float, with modifier: Float) -> Float { if isActive { return oldVelocity + windVelocity } else { return oldVelocity } } /// Update wind velocity based on current month strength. override func update(currentMonth: Int) { windVelocity = strengths[currentMonth / 4] isActive = windVelocity != 0 } }
// // TableTieTests.swift // TableTieTests // // Created by Vladimir Kofman on 25/04/2017. // Copyright © 2017 Vladimir Kofman. All rights reserved. // import XCTest @testable import TableTie extension String: Row { public func configure(cell: UITableViewCell) { cell.textLabel?.text = self } } class TableTieTests: XCTestCase { var adapter: Adapter! var tableView: UITableView! override func setUp() { super.setUp() adapter = Adapter() tableView = UITableView(frame: CGRect.zero) tableView.dataSource = adapter tableView.delegate = adapter } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } //MARK: - func testEmptyAdapterInit() { XCTAssertEqual(adapter.numberOfSections(in: tableView), 0) } func testAdapterInitRows() { let arr = ["a", "b", "c"] adapter = Adapter(arr) tableView = UITableView(frame: CGRect.zero) tableView.dataSource = adapter tableView.delegate = adapter XCTAssertEqual(adapter.numberOfSections(in: tableView), 1) XCTAssertEqual(adapter.tableView(tableView, numberOfRowsInSection: 0), arr.count) } func testAdapterInitSections() { let sections = [Section("A", ["a", "b"])] adapter = Adapter(sections) tableView = UITableView(frame: CGRect.zero) tableView.dataSource = adapter tableView.delegate = adapter XCTAssertEqual(adapter.numberOfSections(in: tableView), 1) XCTAssertEqual(adapter.tableView(tableView, numberOfRowsInSection: 0), sections[0].rows.count) } func testAdapterSetRows() { let arr = ["a", "b", "c"] adapter.set(arr) XCTAssertEqual(adapter.numberOfSections(in: tableView), 1) XCTAssertEqual(adapter.tableView(tableView, numberOfRowsInSection: 0), arr.count) } func testCellForRow() { let arr = ["d", "e", "f", "g"] adapter.set(arr) let testRowIndex = arr.count / 2 let cell = adapter.tableView(tableView, cellForRowAt: IndexPath(row: testRowIndex, section: 0)) XCTAssertEqual(cell.textLabel?.text, arr[testRowIndex]) adapter.set([] as! [AnyRow]) XCTAssertEqual(adapter.numberOfSections(in: tableView), 1) } func testAdapterSetSections() { let sections = [Section("A", ["a", "b"]), Section("B", ["d", "e", "f"])] adapter.set(sections) XCTAssertEqual(adapter.numberOfSections(in: tableView), sections.count) for (i, section) in sections.enumerated() { XCTAssertEqual(adapter.tableView(tableView, numberOfRowsInSection: i), sections[i].rows.count) XCTAssertEqual(adapter.tableView(tableView, titleForHeaderInSection: i), sections[i].header) XCTAssertNil(adapter.tableView(tableView, titleForFooterInSection: i)) let testRowIndex = section.rows.count / 2 let cell = adapter.tableView(tableView, cellForRowAt: IndexPath(row: testRowIndex, section: i)) XCTAssertEqual(cell.textLabel?.text, section.rows[testRowIndex] as? String) } } func testSelectableRow() { var callMeCalled = false func callMe() { callMeCalled = true } adapter.set([SelectableRow("a", callMe())]) XCTAssertFalse(callMeCalled) adapter.tableView(tableView, didSelectRowAt: IndexPath(row: 0, section: 0)) XCTAssertTrue(callMeCalled) } func testDefaultRowHeight() { adapter.set(["a"]) XCTAssertEqual(adapter.tableView(tableView, heightForRowAt: IndexPath(row: 0, section: 0)), UITableViewAutomaticDimension) } }
// // CustomButton.swift // SwiftTraningProject // // Created by 吉祥具 on 2017/6/7. // Copyright © 2017年 吉祥具. All rights reserved. // import Foundation class CustomButton { //寬高基數為40和30 class func makeCustomBtn(button:UIButton , content:String , fontSizeSet:CGFloat , widthGet:NSLayoutConstraint, heightGet:NSLayoutConstraint ) ->UIButton{ button.layer.masksToBounds=true button.backgroundColor = UIColor.init(red: 0.52, green: 0.78, blue: 1, alpha: 0.8) button.tintColor = UIColor.white button.titleLabel?.font = UIFont.init(name: fontNameSet, size: fontSizeSet) button.setTitle(content, for: .normal) button.layer.cornerRadius = widthGet.constant/8 widthGet.constant = widthGet.constant + fontSizeSet*5 heightGet.constant = heightGet.constant + fontSizeSet return button } class func makeCustomRatingBtn(button:UIButton , content:String , fontSizeSet:CGFloat) ->UIButton{ button.layer.masksToBounds=true button.backgroundColor = UIColor.black button.layer.cornerRadius = button.frame.size.width/8 button.layer.borderColor = UIColor.white.cgColor button.layer.borderWidth = 1 button.tintColor = UIColor.white button.titleLabel?.font = UIFont.init(name: fontNameSet, size: fontSizeSet) button.setTitle(content, for: .normal) return button } class func makeViewContainerCustomButton(button:UIButton , content:String , fontSizeSet:CGFloat) -> UIButton{ button.backgroundColor = UIColor.clear button.tintColor = UIColor.white button.titleLabel?.font = UIFont.init(name: fontNameSet, size: fontSizeSet) button.setTitle(content, for: .normal) return button } }
// // NoticeModel.swift // 卖货神器 // // Created by CYT on 2017/5/5. // Copyright © 2017年 CYT. All rights reserved. // import UIKit class NoticeModel: NSObject { }
// // PDFActivity.swift // SaneScanner // // Created by Stanislas Chevallier on 06/02/2019. // Copyright © 2019 Syan. All rights reserved. // #if !targetEnvironment(macCatalyst) import UIKit import SYKit class PDFActivity: UIActivity { // MARK: Properties weak var presentingViewController: UIViewController? private weak var hud: HUDAlertController? // MARK: Original activity properties private var items: [URL] = [] private weak var sourceView: UIView? private weak var barButtonItem: UIBarButtonItem? private var sourceRect = CGRect.zero private var permittedArrowDirections = UIPopoverArrowDirection.any // MARK: Methods func configure(using originalActivityViewController: UIActivityViewController) { guard let popoverController = originalActivityViewController.popoverPresentationController else { return } barButtonItem = popoverController.barButtonItem sourceView = popoverController.sourceView sourceRect = popoverController.sourceRect permittedArrowDirections = popoverController.permittedArrowDirections } // MARK: UIActivity override var activityType: UIActivity.ActivityType? { let id = Bundle.main.bundleIdentifier!.appending(".pdfActivity") return UIActivity.ActivityType(id) } override var activityTitle: String? { return "SHARE AS PDF".localized } override var activityImage: UIImage? { return .icon(.pdf) } override class var activityCategory: UIActivity.Category { return .action } override func canPerform(withActivityItems activityItems: [Any]) -> Bool { let readableCount = activityItems .compactMap { $0 as? URL } .filter { ["png", "heic", "jpg"].contains($0.pathExtension.lowercased()) } .count return activityItems.count == readableCount } override func prepare(withActivityItems activityItems: [Any]) { super.prepare(withActivityItems: activityItems) self.items = activityItems .compactMap { $0 as? URL } .sorted { $0.lastPathComponent > $1.lastPathComponent } if #available(iOS 13.0, *) { // apparently after doing that on iOS 12 perform never gets called (something most be dealloced somewhere...) obtainPresentingViewController { self.hud = HUDAlertController.show(in: $0, animated: false) } } } private func obtainPresentingViewController(_ completion: @escaping (UIViewController) -> ()) { guard let presentingViewController = presentingViewController else { return } if let vc = presentingViewController.presentedViewController { vc.dismiss(animated: true, completion: { completion(presentingViewController) }) } else { completion(presentingViewController) } } override func perform() { super.perform() let tempURL = GalleryManager.shared.tempPdfFileUrl() do { try PDFGenerator.generatePDF(destination: tempURL, images: self.items, pageSize: Preferences.shared.pdfSize) } catch { obtainPresentingViewController { UIAlertController.show(for: error, in: $0) } activityDidFinish(false) return } let vc = UIActivityViewController(activityItems: [tempURL], applicationActivities: nil) vc.popoverPresentationController?.barButtonItem = barButtonItem vc.popoverPresentationController?.sourceView = sourceView vc.popoverPresentationController?.sourceRect = sourceRect vc.popoverPresentationController?.permittedArrowDirections = permittedArrowDirections vc.completionWithItemsHandler = { activityType, completed, returnedItems, error in // is called when the interaction with the PDF is done. It's either been copied, imported, // displayed, shared or printed, but we can dispose of it GalleryManager.shared.deleteTempPDF() self.activityDidFinish(completed) } obtainPresentingViewController { $0.present(vc, animated: true, completion: nil) } } } #endif
// // DataExtensions.swift // Mitter // // Created by Rahul Chowdhury on 29/11/18. // Copyright © 2018 Chronosphere Technologies Pvt. Ltd. All rights reserved. // import Foundation extension Array { func flattenWithCommas() -> String { let reducedArray = self.reduce("", { reduced, element in "\(reduced),\(element)" }) if reducedArray.isEmpty { return "" } else { let index = reducedArray.index(reducedArray.startIndex, offsetBy: 1) return String(reducedArray[index...]) } } }
import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var myTableView: UITableView! var list: [String] = ["1", "2", "3"] override func viewDidLoad() { super.viewDidLoad() // init myTableView = UITableView() myTableView.delegate = self myTableView.dataSource = self view.addSubview(myTableView) myTableView.register(CSTableCell.classForCoder(), forCellReuseIdentifier: "cell") // layout myTableView.translatesAutoresizingMaskIntoConstraints = false myTableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true myTableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true myTableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true myTableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return list.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! CSTableCell cell.lbl.text = list[indexPath.row] cell.btn.setTitle(list[indexPath.row], for: .normal) cell.btn.backgroundColor = .green return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return view.frame.height / 10 } } class CSTableCell: UITableViewCell { public var lbl : UILabel! public var btn: UIButton! override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setup() contentView.addSubview(lbl) contentView.addSubview(btn) lbl.translatesAutoresizingMaskIntoConstraints = false btn.translatesAutoresizingMaskIntoConstraints = false lbl.leftAnchor.constraint(equalTo: safeAreaLayoutGuide.leftAnchor, constant: 10).isActive = true btn.rightAnchor.constraint(equalTo: safeAreaLayoutGuide.rightAnchor, constant: -10).isActive = true } required init?(coder: NSCoder) { super.init(coder: coder) setup() } private func setup() { lbl = UILabel() lbl.textColor = .black lbl.font = UIFont.boldSystemFont(ofSize: 16) lbl.textAlignment = .left btn = UIButton() btn.setTitleColor(.black, for: .normal) } }
/* * Version for iOS © 2015–2021 YANDEX * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at https://yandex.com/legal/mobileads_sdk_agreement/ */ import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { let gdprManager = GDPRUserConsentManager(userDefaults: UserDefaults.standard) gdprManager.initializeUserDefaults() let navigationController = window?.rootViewController as? UINavigationController let viewController = navigationController?.topViewController as? ViewController viewController?.gdprManager = gdprManager return true } }
// // Shape+Color.swift // Lato // // Created by juandahurt on 30/01/21. // import Foundation import SwiftUI extension Shape { static func chooseShapeColor(for color: Shape.Color) -> SwiftUI.Color { switch color { case .red: return SwiftUI.Color("Red") case .yellow: return SwiftUI.Color("Yellow") case .black: return SwiftUI.Color("Black") case .blue: return SwiftUI.Color("Blue") case .green: return SwiftUI.Color("Green") } } }
// // ViewController.swift // StickyHeaderDemo // // Created by 默司 on 2017/7/20. // Copyright © 2017年 默司. All rights reserved. // import UIKit class ViewController: StickyHeaderViewController { lazy var topView: UIView = { let view = UIView(frame: .zero) view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1) return view }() lazy var headerView: UIView = { let view = UIView(frame: .zero) view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1) return view }() lazy var pager: UIPageViewController = { let vc = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal) return vc }() lazy var pages: [NumbersTableViewController] = { return [NumbersTableViewController(count: 5), NumbersTableViewController(count: 100)] }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.addChildViewController(pager) self.pager.didMove(toParentViewController: self) self.pager.delegate = self self.pager.dataSource = self self.pager.setViewControllers([pages[0]], direction: .forward, animated: false) self.scrollView = pages[0].tableView self.setupLayout() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func setupLayout() { self.view.addSubview(pager.view) self.view.addSubview(topView) self.view.addSubview(headerView) self.pager.view.translatesAutoresizingMaskIntoConstraints = false self.topView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true self.topView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true self.topView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true self.headerOffsetConstrant = self.topView.heightAnchor.constraint(equalToConstant: headerMaxOffset) self.headerOffsetConstrant?.isActive = true self.headerView.topAnchor.constraint(equalTo: topView.bottomAnchor).isActive = true self.headerView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true self.headerView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true self.headerView.heightAnchor.constraint(equalToConstant: 50).isActive = true self.pager.view.topAnchor.constraint(equalTo: self.headerView.bottomAnchor).isActive = true self.pager.view.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true self.pager.view.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true self.pager.view.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor).isActive = true } } extension ViewController: UIPageViewControllerDelegate, UIPageViewControllerDataSource { func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { if viewController == pages.first { return nil } return pages.first } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { if viewController == pages.first { return pages[1] } return nil } func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { guard let vc = pendingViewControllers.first as? NumbersTableViewController else { return } self.scrollView = vc.tableView } }
//STRUCTS struct Coord{ var X:Int=0; var Y:Int=0; } var A = Coord(X: 20, Y: 40); var B = Coord(); print(A.X + A.Y) A.X = 5; A.Y = 4; B.X = 1; B.Y = 2; A=B; //CLASSES class Coordi{ var X: Int var Y: Int init() { X = 9; Y = 9; } } var C = Coordi() var D = Coordi() if(D===C) { print("Same Referrence") } else { print ("Not Same Referrence")} //PROPERTIES struct point { var x: Int var y : Int var Sum:point{ get{ return point(x+y,x+y) } set(newxy){ x = newxy.x y = newxy.y } willSet { } } init(_ a:Int,_ b:Int) { x=a; y=b; } } var temp = point(2,1) print(temp.Sum) temp.Sum = point(5,5) print(temp.Sum) //LAZY VARIABLES struct LazyVar { var a: Int { willSet { print("Setting \(newValue)") } didSet { print("Set new value : \(oldValue)") } } init() { print("Lazy Variable created!") a = 10; } } struct LazyEx { lazy var LazyVariable = LazyVar() init() { print("Lazy example created") } } //DOES NOT CREATE LAZY VARIABLE var ab:LazyEx = LazyEx() //LAZY VARIABLE CREATED HERE ab.LazyVariable.a = 5 //MUTATING FUNCTIONS struct X{ var a:Int static var b: Int = 6 init(_ i:Int) { a = i; } init() { a=0 } //NEED TO WRITE MUTATING IF WE'RE MODIFYING ANY VALUES mutating func ModifyA(x: Int) -> () { a = x } func PrintA() -> () { print(a) } static func Modifyb(i: Int) -> () //No need to use Mutating to modify static values { b = i } static func PrintB() -> () { print(b) } } var Z: X = X(7) Z.PrintA() Z.ModifyA(x: (90)) Z.PrintA() X.Modifyb(i: 5) X.PrintB()
// // WFEditViewController.swift // niinfor // // Created by 王孝飞 on 2018/8/22. // Copyright © 2018年 孝飞. All rights reserved. // import UIKit import TZImagePickerController class WFEditImageViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() setUPUI() } fileprivate let buttomView : UIView = { let bv = UIView.init() bv.backgroundColor = UIColor.white return bv }() fileprivate let photoAbumBtn : UIButton = { let button = UIButton.init() button.setTitle("相册", for: .normal) button.setTitleColor(#colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1), for: .normal) button.addTarget(self, action: #selector(albumBtnclick), for: .touchUpInside) return button }() fileprivate let transformBtn : UIButton = { //#imageLiteral(resourceName: "旋转") let button = UIButton.init() button.setImage(#imageLiteral(resourceName: "旋转"), for: .normal) button.addTarget(self, action: #selector(rotationBtnclick), for: .touchUpInside) return button }() fileprivate let editBtn : UIButton = { let button = UIButton.init() button.setImage(#imageLiteral(resourceName: "裁剪-1"), for: .normal) button.addTarget(self, action: #selector(cropBtnclick), for: .touchUpInside) return button }() fileprivate let deleteBtn : UIButton = { let button = UIButton.init() button.setTitle("删除", for: .normal) button.setTitleColor(#colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1), for: .normal) button.addTarget(self, action: #selector(deleteBtnclick), for: .touchUpInside) return button }() let contentImageV : UIImageView = { let imageV = UIImageView.init() imageV.contentMode = .scaleAspectFit imageV.isHidden = true return imageV }() let cropView = PECropView.init(frame: CGRect.zero) var btnright = UIButton.init() var blockCompliction : ((UIImage?)->Void)? var image : UIImage?{ didSet{ contentImageV.image = image cropView.image = image contentImageV.sizeToFit() } } } extension WFEditImageViewController{ @objc func rightBtnclick(){ dismiss(animated: true) { guard let complict = self.blockCompliction else { return } if self.cropView.cropRectView.isHidden == false { self.cropBtnclick() } complict(self.image) } } @objc func leftBtnclick(){ dismiss(animated: true, completion: nil) } @objc func albumBtnclick(){ rechooseImage() } @objc func rotationBtnclick(){ contentImageV.image = contentImageV.image?.rotate(.right) image = contentImageV.image } @objc func cropBtnclick(){ if cropView.cropRectView.isHidden == false { image = cropView.croppedImage } cropView.cropRectView.isHidden = !cropView.cropRectView.isHidden cropView.isUserInteractionEnabled = !cropView.isUserInteractionEnabled } @objc func deleteBtnclick(){ dismiss(animated: true) { guard let complict = self.blockCompliction else { return } complict(nil) } } } /// MARK : 选择相册 extension WFEditImageViewController : TZImagePickerControllerDelegate{ fileprivate func rechooseImage() { let vc = TZImagePickerController(maxImagesCount: 1 , delegate: self ) vc?.didFinishPickingPhotosHandle = {[weak self](_ phots : [UIImage]?, _ array : [Any]?, isSecled :Bool)in if phots?.count == 0{return} self?.image = phots?[0] } present(vc!, animated: true, completion: nil) } } extension WFEditImageViewController{ fileprivate func setUPUI() { view.backgroundColor = #colorLiteral(red: 0.9529411765, green: 0.9529411765, blue: 0.9529411765, alpha: 1) title = "图片编辑" addSubView() setConstront() setNavigationBtn() cropView.cropRectView.isHidden = true cropView.isUserInteractionEnabled = false } fileprivate func setNavigationBtn() { btnright = UIButton.cz_textButton("完成", fontSize: 15, normalColor: #colorLiteral(red: 0.2470588235, green: 0.6117647059, blue: 0.7019607843, alpha: 1), highlightedColor: UIColor.white) btnright.setTitleColor(#colorLiteral(red: 0.2470588235, green: 0.6117647059, blue: 0.7019607843, alpha: 1), for: .normal) btnright.addTarget(self, action: #selector(rightBtnclick), for: .touchUpInside) self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: btnright) let btnleft = UIButton.cz_textButton("取消", fontSize: 15, normalColor: #colorLiteral(red: 0.2, green: 0.2, blue: 0.2, alpha: 1), highlightedColor: UIColor.white) btnleft?.addTarget(self, action: #selector(leftBtnclick), for: .touchUpInside) navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btnleft!) } fileprivate func addSubView() { view.addSubview(contentImageV) view.addSubview(cropView) view.addSubview(buttomView) buttomView.addSubview(photoAbumBtn) buttomView.addSubview(transformBtn) buttomView.addSubview(editBtn) buttomView.addSubview(deleteBtn) } fileprivate func setConstront(){ buttomView.snp.makeConstraints { (maker) in maker.bottom.left.right.equalToSuperview() maker.height.equalTo(50) } photoAbumBtn.snp.makeConstraints { (maker) in maker.top.height.equalToSuperview() maker.width.equalToSuperview().multipliedBy(1.0/4.0) maker.left.equalToSuperview() } transformBtn.snp.makeConstraints { (maker) in maker.top.height.equalToSuperview() maker.width.equalToSuperview().multipliedBy(1.0/4.0) maker.left.equalToSuperview().offset( CGFloat(1) * Screen_width / 4.0) } editBtn.snp.makeConstraints { (maker) in maker.top.height.equalToSuperview() maker.width.equalToSuperview().multipliedBy(1.0/4.0) maker.left.equalToSuperview().offset( CGFloat(2) * Screen_width / 4.0) } deleteBtn.snp.makeConstraints { (maker) in maker.top.equalToSuperview() maker.width.equalToSuperview().multipliedBy(1.0/4.0) maker.height.equalTo(44) maker.left.equalToSuperview().offset( CGFloat(3) * Screen_width / 4.0) } contentImageV.snp.makeConstraints { (maker) in maker.right.left.width.equalToSuperview() maker.top.equalToSuperview().offset(100) maker.bottom.equalToSuperview().offset(-100) } // let size = contentImageV.image?.size cropView.snp.makeConstraints { (maker) in maker.left.width.equalToSuperview() maker.top.equalTo(navigation_height) maker.height.equalToSuperview().offset(-navigation_height - 50) // maker.size.equalTo(size!) // maker.center.equalTo(contentImageV) } } }
// // ViewController.swift // lab4-1-5 // // Created by taizhou on 2019/8/1. // Copyright © 2019 taizhou. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func nextPage(_ sender: Any) { } func presentVC(){ let storyBoard = UIStoryboard.init(name: "Main", bundle: nil) let VC = storyBoard.instantiateViewController(identifier: "SecViewController") as! SecViewController present(VC, animated: true, completion: nil) } func pushVC(){ let storyBoard = UIStoryboard.init(name: "Main", bundle: nil) let VC = storyBoard.instantiateViewController(identifier: "SecViewController") as! SecViewController navigationController?.pushViewController(VC, animated: true) } }
//: Playground - noun: a place where people can play import UIKit //ClassWork var str = "Hello, playground" // Bubble Sort func bubbleSort(_ array: [Int]) -> [Int] { var arr = array let size: Int = arr.count for _ in 1 ..< size{ for j in 0 ..< size - 1{ if arr[j] > arr[j + 1]{ swap( &arr[j], &arr[j+1]) } } } print(arr) return arr } var arr = [2,3,5,7,10,-1] bubbleSort(arr) // OOП // Наследование class Vehicle { var curSpeed = 0.0 var description: String { return "движется на скорости \(curSpeed) миль в час" } func go(){ } //Полиморфизм func makeNoise() { } } class Bicycle: Vehicle { var hasBasket = false //Полиморфизм override func makeNoise() { print("Звук велосипеда") } } class MotorByke: Vehicle{ //Полиморфизм override func makeNoise() { print("РРРРРРРРРРРР") } override func go(){ //инкапсулированный метод startEngine() //and more } // инкапсуляция private func startEngine(){ ///// } } //Полиморфизм MotorByke().makeNoise(); Bicycle().makeNoise(); //MyStack struct MyStack<Element> { fileprivate var array: [Element] = [] mutating func push(_ element: Element) { array.append(element) } mutating func pop() -> Element? { return array.popLast() } func peek() -> Element? { return array.last } } var stack = MyStack<Int>() stack.push(5) print(stack.pop()!)
// // Conversation.swift // SlideDM // // Created by Eric LaBouve on 2/28/19. // Copyright © 2019 Eric LaBouve. All rights reserved. // import Foundation import Firebase class Conversation: NSObject, Codable { // fromUserRef and toUserRef are required to create a conversation var fromUserRef: DocumentReference var toUserRef: DocumentReference // fromUserID and toUserID are required to check if a user is initiating a new conversation var fromUserID: String var toUserID: String // Reference to the conversation document in Firestore var ref: DocumentReference? init(fromUser: SDMUser, toUser: SDMUser) { self.fromUserRef = fromUser.ref! self.toUserRef = toUser.ref! self.fromUserID = fromUser.phoneID self.toUserID = toUser.phoneID } static func == (lhs: Conversation, rhs: Conversation) -> Bool { guard let ref1 = lhs.ref, let ref2 = rhs.ref else { return false } return ref1 == ref2 } // Those who implement UserLocationListener should call this and pass self // in order to receive updates when a new message is sent. func addConversationListener(listener: ConversationListener) { // Listen only to new messages that are sent ref?.collection("messages") .whereField("timestampDate", isGreaterThan: Timestamp(date: Date(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970 - 1)))) .addSnapshotListener { querySnapshot, error in guard let snapshot = querySnapshot else { print("Error fetching snapshots: \(error!)"); return } snapshot.documentChanges.forEach { diff in if (diff.type == .added) { let message = TextMessage(values: diff.document.data()) listener.conversationChanged(conversation: self, textMessage: message) } /* if (diff.type == .modified) { print("Modified city: \(diff.document.data())") } if (diff.type == .removed) { print("Removed city: \(diff.document.data())") } */ } } } } // Conform to this protocol to receive updates when messages are sent to a conversation protocol ConversationListener { func conversationChanged(conversation: Conversation, textMessage: TextMessage) }
// // ApiVehicle.swift // OnestapSDK // // Created by Munir Wanis on 30/08/17. // Copyright © 2017 Stone Payments. All rights reserved. // import Foundation struct ApiVehicle: InitializableWithData, InitializableWithJson { var key: String = "" var licensePlate: String var licensePlateCity: String? = nil var licensePlateState: String? = nil var licensePlateCountry: String? = nil init(data: Data?) throws { guard let data = data, let jsonObject = try? JSONSerialization.jsonObject(with: data), let json = jsonObject as? JSON else { throw NSError.createParseError() } try self.init(json: json) } init(json: JSON) throws { guard let key = json["key"] as? String, let licensePlate = json["licensePlate"] as? String else { throw NSError.createParseError() } self.key = key self.licensePlate = licensePlate self.licensePlateCity = json["licensePlateCity"] as? String self.licensePlateState = json["licensePlateState"] as? String self.licensePlateCountry = json["licensePlateCountry"] as? String } } extension ApiVehicle { var vehicle: Vehicle { var vehicle = Vehicle(licensePlate: self.licensePlate) vehicle.key = self.key vehicle.licensePlateCountry = self.licensePlateCountry vehicle.licensePlateCity = self.licensePlateCity vehicle.licensePlateState = self.licensePlateState return vehicle } }
// // DeleteMeasurerRequestParameters.swift // EFI // // Created by LUIS ENRIQUE MEDINA GALVAN on 01/08/18. // Copyright © 2018 LUIS ENRIQUE MEDINA GALVAN. All rights reserved. // import Foundation struct DeleteMeasurerRequestParameters:Codable { var ClaveLocalizacion:String? var UserId:String? = "fe040b94-82bf-4e09-b171-ec6e050810a4" //"b3f5b6d3-d53b-4c27-8ad8-4841f7b39aaf" var NS:String? }
// // SocketParser.swift // Unfiltr // // Created by Md Tauseef on 1/2/21. // import Foundation class JSONParser { static func convert<T: Decodable>(data: Any) throws -> T { let jsonData = try JSONSerialization.data(withJSONObject: data) let decoder = JSONDecoder() return try decoder.decode(T.self, from: jsonData) } static func convert<T: Decodable>(dataArr: [Any]) throws -> [T] { return try dataArr.map{ (dict) -> T in let jsonData = try JSONSerialization.data(withJSONObject: dict) let decoder = JSONDecoder() return try decoder.decode(T.self, from: jsonData) } } }
// // ScanButton.swift // EpilepsyMonitor // // Created by chapnickc on 8/11/16. // Copyright © 2016 Chad. All rights reserved. // import UIKit class ScanButton: UIButton { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // add a layer to the button layer.borderWidth = 1.5 //layer.borderColor = UIColor.redColor().CGColor } func buttonColorScheme(isScanning: Bool) { let title = isScanning ? "Stop Scanning" : "Scan" setTitle(title, forState: UIControlState.Normal) let titleColor = isScanning ? UIColor.redColor() : UIColor.whiteColor() setTitleColor(titleColor, forState: .Normal) backgroundColor = isScanning ? UIColor.clearColor() : UIColor.blueColor() layer.borderColor = isScanning ? UIColor.redColor().CGColor : UIColor.blueColor().CGColor } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ }
// // MoviesTableViewController.swift // MovieSearch // // Created by Jordan Bryant on 9/25/20. // Copyright © 2020 Jordan Bryant. All rights reserved. // import UIKit class MoviesTableViewController: UITableViewController { //MARK: - Outlets @IBOutlet weak var movieSearchBar: UISearchBar! //MARK: - Properties var movies: [Movie] = [] //MARK: - Lifecycle Methods override func viewDidLoad() { super.viewDidLoad() movieSearchBar.delegate = self tableView.tableFooterView = UIView() } //MARK: - TableView Delegate Functions override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return movies.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "movieCellId") as? MovieTableViewCell else { return UITableViewCell(frame: .zero) } let movie = movies[indexPath.row] cell.movie = movie return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 175 } //MARK: - Segue Prep override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "toDetailVC" { guard let detailVC = segue.destination as? MovieDetailViewController else { return } guard let selectedIndex = tableView.indexPathForSelectedRow else { return } guard let selectedCell = tableView.cellForRow(at: selectedIndex) as? MovieTableViewCell else { return } let movie = movies[selectedIndex.row] detailVC.movie = movie detailVC.movieImage = selectedCell.posterImageView.image ?? UIImage(named: "noPosterImage") } } } //MARK: - Search Bar Delegate extension MoviesTableViewController: UISearchBarDelegate { func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { guard let searchText = searchBar.text, !searchText.isEmpty else { return } MovieController.searchMovies(searchText: searchText) { (result) in switch result { case .success(let movies): self.movies = movies self.tableView.reloadData() searchBar.text = "" self.view.endEditing(true) case .failure(let error): print(error.localizedDescription) } } } }
// // SwiftyCache.swift // SwiftyCache // // Created by lihao on 16/5/21. // Copyright © 2016年 Egg Swift. All rights reserved. // import Foundation public class SwiftyCache { public static let prefix: String = { let appName = NSBundle.mainBundle().infoDictionary?[String(kCFBundleExecutableKey)] as? String ?? "Application" let prefix = "com." + appName + "." return prefix }() }
// // HomeViewController.swift // Ravinsu M.H.S - COBSCComp171P-001 // // Created by Sahan Ravindu on 5/18/19. // Copyright © 2019 Sahan Ravindu. All rights reserved. // import UIKit import Firebase import FirebaseAuth import Alamofire import Kingfisher class HomeViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var studentTable: UITableView! var studentData: [Student] = [] var userData: [User] = [] var ref: DatabaseReference! override func viewDidLoad() { super.viewDidLoad() //Load user data to user model // self.getViewUserData() //Initialized data refferencess ref = Database.database().reference() self.registerCell() self.getStudentList() self.studentTable.tableFooterView = UIView() studentTable.delegate = self studentTable.dataSource = self // Do any additional setup after loading the view. } //call Registration func registerCell() { self.studentTable.register(UINib(nibName: "tableTableViewCell", bundle: nil), forCellReuseIdentifier: "tableTableViewCell") // self.tableView.register(singerViewCell.self, forCellReuseIdentifier: "singerViewCell") } //End of cell registration //Load student List func getStudentList() { //self.showActivity() self.ref.child("NIBMConnect/Students").observeSingleEvent(of: .value, with: { (snapshot) in // Get user value let value = snapshot.value as? NSDictionary //let singersList = value! print(snapshot.children) var newstudent: [Student] = [] if snapshot.childrenCount > 0 { for student in snapshot.children.allObjects as! [DataSnapshot] { //getting values let studentObject = student.value as? [String: AnyObject] let student = Student(fName: studentObject!["fName"] as! String, lName: studentObject!["lName"] as! String, phoneNumber: studentObject!["phone"] as! Int, fbUrl: studentObject!["fbUrl"] as! String, city: studentObject!["city"] as! String, profUrl: studentObject!["imgUrl"] as! String) newstudent.append(student) } } self.studentData = newstudent print(self.studentData[0].fName) self.studentTable.reloadData() //self.hideActivity() // ... }) { (error) in print(error.localizedDescription) } } //End Of loading student List func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.studentData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "studentCell", for: indexPath ) as! tableTableViewCell let url = URL( string: self.studentData[indexPath.row].profUrl) cell.profileImg.kf.setImage(with: url) cell.studentName.text = self.studentData[indexPath.row].fName + " " + self.studentData[indexPath.row].lName cell.city.text = self.studentData[indexPath.row].city cell.phoneNumber = self.studentData[indexPath.row].phoneNumber cell.fbProfile = self.studentData[indexPath.row].fbUrl return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showstudent" { let selectedIndex = sender as! Int let selectedStudent = self.studentData[selectedIndex] let destinationVC = segue.destination as! showFriendsViewController destinationVC.studentInfo = selectedStudent } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.performSegue(withIdentifier: "showstudent", sender: indexPath.row) tableView.deselectRow(at: indexPath, animated: true) } //Log out btn @IBAction func logOut(_ sender: Any) { let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() } catch let signOutError as NSError { print ("Error signing out: %@", signOutError) let alert = UIAlertController(title: "Login Error", message: signOutError.localizedDescription, preferredStyle:.alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } self.navigationController?.dismiss(animated: true) } //End of log out btn /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
// // cellCompletedJobSeeker.swift // WorkingBeez // // Created by Brainstorm on 3/12/17. // Copyright © 2017 Brainstorm. All rights reserved. // import UIKit class cellCompletedJobSeeker: UITableViewCell { @IBOutlet weak var lblPaid: UILabel! @IBOutlet weak var lblJobTitle: UILabel! @IBOutlet weak var lblHiredTillDate: UILabel! @IBOutlet weak var lblCompanyName: UILabel! @IBOutlet weak var viewRating: HCSStarRatingView! @IBOutlet weak var btnAddress: UIButton! @IBOutlet weak var imgCompanyPhoto: cImageView! @IBOutlet weak var lblHourlyRate: UILabel! @IBOutlet weak var lblTotalPayment: UILabel! @IBOutlet weak var lblRosterDate: UILabel! @IBOutlet weak var lblRosterTime: UILabel! @IBOutlet weak var lblRosterBreak: UILabel! @IBOutlet weak var lblRosterBreakPaid: UILabel! @IBOutlet weak var viewDays: UIView! @IBOutlet weak var lblRosterRepeat: UILabel! @IBOutlet weak var btnMon: cButton! @IBOutlet weak var btnTue: cButton! @IBOutlet weak var btnWed: cButton! @IBOutlet weak var btnThu: cButton! @IBOutlet weak var btnFri: cButton! @IBOutlet weak var btnSat: cButton! @IBOutlet weak var btnSun: cButton! @IBOutlet weak var btnHelp: UIButton! @IBOutlet weak var lblJobStatus: UILabel! @IBOutlet weak var btnfeedback: UIButton! @IBOutlet weak var lblJobId: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
// // ViewController.swift // SeeFood // // Created by Justyn Henman on 24/07/2020. // Copyright © 2020 Justyn Henman. All rights reserved. // import UIKit import CoreML import Vision import AVFoundation import LTMorphingLabel class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, AVCapturePhotoCaptureDelegate{ @IBOutlet weak var previewView: UIView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var thinkLabel: LTMorphingLabel! @IBOutlet weak var oobeLabel: UILabel! @IBOutlet weak var oobeArrow: UIImageView! @IBOutlet weak var scanButton: ButtonStyle! @IBOutlet weak var cameraButton: ButtonStyle! @IBOutlet weak var cameraButtonWidthConstaint: NSLayoutConstraint! @IBOutlet weak var buttonStackView: UIStackView! var captureSession: AVCaptureSession! var stillImageOutput: AVCapturePhotoOutput! var videoPreviewLayer: AVCaptureVideoPreviewLayer! var isScanning: Bool = false var isShowingPhoto: Bool = false //MARK: - ViewDidLoad override func viewDidLoad() { super.viewDidLoad() thinkLabel.morphingEffect = .evaporate scanButton.topGradient = "StartTop" scanButton.bottomGradient = "StartBottom" scanButton.setTitleColor(UIColor.black, for: .normal) cameraButton.topGradient = "CamTop" cameraButton.bottomGradient = "CamBottom" cameraButton.setContentHuggingPriority(UILayoutPriority.required, for: .horizontal) previewView.layer.cornerRadius = 10 imageView.layer.cornerRadius = 10 } //MARK: - ViewDidAppear //Setup override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) captureSession = AVCaptureSession() captureSession.sessionPreset = .hd1280x720 //creates capturesession with photo preset let videoDevice = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: .back).devices.first do{ let cameraInput = try AVCaptureDeviceInput(device: videoDevice!) stillImageOutput = AVCapturePhotoOutput() let canAddIO = captureSession.canAddInput(cameraInput) && captureSession.canAddOutput(stillImageOutput) if canAddIO{ captureSession.addInput(cameraInput) captureSession.addOutput(stillImageOutput) setupLivePreview() } }catch{ print(error.localizedDescription) } } //MARK: - Live Preview Setup func setupLivePreview(){ videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) videoPreviewLayer.videoGravity = .resizeAspectFill videoPreviewLayer.connection?.videoOrientation = .portrait videoPreviewLayer.cornerRadius = 10 previewView.layer.addSublayer(videoPreviewLayer) DispatchQueue.global(qos: .userInitiated).async { self.captureSession.startRunning() DispatchQueue.main.async { self.videoPreviewLayer.frame = self.previewView.bounds } } } //MARK: - Set UIImage to Cam Output func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) { guard let imageData = photo.fileDataRepresentation() else { return } let image = UIImage(data: imageData) if scanButton.isHidden{ imageView.image = image } detect(image: CIImage(cgImage: image!.cgImage!)) } func photoOutput(_ output: AVCapturePhotoOutput, willCapturePhotoFor resolvedSettings: AVCaptureResolvedPhotoSettings) { // dispose system shutter sound AudioServicesDisposeSystemSoundID(1108) } //MARK: - Image scanning function func detect(image: CIImage){ guard let model = try? VNCoreMLModel(for: Inceptionv3(configuration: MLModelConfiguration()).model) else { fatalError("Broken coreml") } let request = VNCoreMLRequest(model: model) { (request, error) in guard let results = request.results as? [VNClassificationObservation] else{ fatalError("vnrequest error") } if let result = results.first{ if Int(result.confidence * 100) > 1 { self.thinkLabel.text = "I think this is \(result.identifier)" } } } let handler = VNImageRequestHandler(ciImage: image) do{ try handler.perform([request]) }catch{ print("Error handler") } //jank ass real time tracking if cameraButton.isHidden == true{ DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { let settings = AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.hevc]) self.stillImageOutput.capturePhoto(with: settings, delegate: self) } } } //MARK: - ViewWillDisappear //remove capturesession when view disappears override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) //kills capture session in background self.captureSession.stopRunning() } //MARK: - Camera Button Pressed @IBAction func cameraButtonTapped(_ sender: UIButton) { UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5) { [self] in hideOOBE() if isShowingPhoto{ isShowingPhoto = false thinkLabel.text = "Scanning..." //code for button ui scanButton.alpha = 1 cameraButton.topGradient = "CamTop" cameraButton.bottomGradient = "CamBottom" cameraButton.setTitle(nil, for: .normal) cameraButton.setImage(UIImage(systemName: "camera.fill"), for: .normal) scanButton.setNeedsDisplay() thinkLabel.alpha = 0 //code for action videoPreviewLayer.isHidden = false imageView.image = nil }else{ isShowingPhoto = true cameraButtonWidthConstaint = nil //scanning button hidden //code for button ui scanButton.alpha = 0 cameraButton.topGradient = "DoneTop" cameraButton.bottomGradient = "DoneBottom" cameraButton.setTitle("Done", for: .normal) cameraButton.setImage(nil, for: .normal) scanButton.setNeedsDisplay() //code for action videoPreviewLayer.isHidden = true let settings = AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.hevc]) stillImageOutput.capturePhoto(with: settings, delegate: self) thinkLabel.alpha = 1 } scanButton.isHidden.toggle() //buttonStackView.layoutIfNeeded() } } //MARK: - Scan Button Pressed @IBAction func scanButtonTapped(_ sender: Any) { UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5) { [self] in hideOOBE() if isScanning{ isScanning = false //camera button shown cameraButton.alpha = 1 scanButton.topGradient = "StartTop" scanButton.bottomGradient = "StartBottom" scanButton.setTitle("Start Scanning", for: .normal) scanButton.setTitleColor(UIColor.black, for: .normal) scanButton.setNeedsDisplay() thinkLabel.alpha = 0 }else{ isScanning = true //camera button hidden cameraButton.alpha = 0 scanButton.topGradient = "StopTop" scanButton.bottomGradient = "StopBottom" scanButton.setTitleColor(UIColor.white, for: .normal) scanButton.setTitle("Stop Scanning", for: .normal) scanButton.setNeedsDisplay() thinkLabel.alpha = 1 let settings = AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.hevc]) stillImageOutput.capturePhoto(with: settings, delegate: self) } cameraButton.isHidden.toggle() buttonStackView.layoutIfNeeded() } } //MARK: - Hide info text func hideOOBE(){ oobeLabel.alpha = 0 oobeArrow.alpha = 0 } }
// // InitialModelTests.swift // InitialModelTests // // Created by Steven Curtis on 03/06/2020. // Copyright © 2020 Steven Curtis. All rights reserved. // import XCTest @testable import MVVMCDependencyInjection class InitialModelTests: XCTestCase { var initialViewModel: InitialViewModel? override func setUpWithError() throws { let factory = FactoryMock() let coordinator = ProjectCoordinator(factory: factory) initialViewModel = InitialViewModel(coordinator: coordinator, networkManager: HTTPManagerMock()) } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testViewModel() { let expectation = XCTestExpectation(description: #function) initialViewModel?.fetchData(completion: {result in switch result { case .failure: XCTFail() case .success(let data): expectation.fulfill() XCTAssertEqual(data[0].dataString, "The Test Data") } }) wait(for: [expectation], timeout: 3.0) } }
// // SocialPost.swift // grubber // // Created by JABE on 11/16/15. // Copyright © 2015 JABELabs. All rights reserved. // public class SocialPost{ var photo : UIImage? var caption: String? var refId: String var objectType: String // TODO: Add refId and objectType here so that these info can be saved after posting. init(refId: String, objectType: String, photo: UIImage?, caption: String?){ self.refId = refId self.objectType = objectType self.photo = photo self.caption = caption } // convenience init(){ // self.init photo: UIImage?.None, caption: String?.None) // } // // convenience init(photo: UIImage){ // self.init(photo: photo, caption: String?.None) // } // // convenience init(caption: String){ // self.init(photo: UIImage?.None, caption: caption) // } }
// // ViewController.swift // SwiftSampleBezier // // Created by Alina Hambaryan on 4/8/16. // Copyright © 2016 Alina Hambaryan. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var bottomView: UIView! @IBOutlet weak var topView: UIView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() maskView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func maskView() { let shapeTopLayer = CAShapeLayer() var frame = self.topView.bounds frame.size.height = frame.height*2 let path = UIBezierPath(roundedRect:self.topView.bounds, cornerRadius:0) path.appendPath(UIBezierPath(ovalInRect: frame)) shapeTopLayer.path = path.CGPath shapeTopLayer.fillRule = kCAFillRuleEvenOdd self.topView.layer.mask = shapeTopLayer let shapeBottomLayer = CAShapeLayer() var bottomFrame = self.bottomView.bounds bottomFrame.origin.y -= bottomFrame.height bottomFrame.size.height = bottomFrame.height*2 let bottomPath = UIBezierPath(roundedRect:self.bottomView.bounds, cornerRadius:0) bottomPath.appendPath(UIBezierPath(ovalInRect: bottomFrame)) shapeBottomLayer.path = bottomPath.CGPath shapeBottomLayer.fillRule = kCAFillRuleEvenOdd self.bottomView.layer.mask = shapeBottomLayer } }
// // SearchViewResponse.swift // Musinic // // Created by Student on 5/2/19. // Copyright © 2019 Student. All rights reserved. // import Foundation class searchViewResponse : Codable { var tracks : searchViewTrack? }
// // Food.swift // project // // Created by Ajay Raj on 23/03/2016. // Copyright © 2016 Ajay Raj. All rights reserved. // import Foundation import CoreData class Foods: Reminders{ @NSManaged var name: String }
// // ApiService.swift // Joeppie // // Created by Shahin Mirza on 26/11/2019. // Copyright © 2019 Bever-Apps. All rights reserved. // import Foundation import Alamofire import SwiftKeychainWrapper class ApiService { private static let baseURL = "https://api.stider.space" //(POST)/login static func logUserIn(withIdentiefier identifier: String, andPassword password: String) -> (DataRequest) { var parameters : [String:String] = [:] parameters["identifier"] = identifier parameters["password"] = password return Alamofire.request(baseURL + "/auth/local", method: .post, parameters: parameters, encoding: Alamofire.JSONEncoding.default, headers: nil) } //(POST)/register static func createUser(withUsername username : String, email : String, andPassword password : String) -> (DataRequest) { var parameters : [String:String] = [:] parameters["username"] = username parameters["email"] = email parameters["password"] = password var headers : [String : String] = [:] if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } return Alamofire.request(baseURL + "/auth/local/register", method: .post, parameters: parameters, encoding: Alamofire.JSONEncoding.default, headers: headers) } //Ercan:(delete)/dose static func deleteBaxter(baxter:Baxter) -> (DataRequest) { var headers : [String : String] = [:] if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } return Alamofire.request(baseURL + "/baxters/"+String(baxter.id), method: .delete,headers: headers) } static func getAllBaxtersPatient(patientId:Int) -> (DataRequest){ var headers : [String : String] = [:] var parameters : [String:String] = [:] if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } parameters["patient.id"] = "\(patientId)" return Alamofire.request(baseURL + "/baxters?_sort=day_of_week:ASC", method: .get, parameters: parameters,headers: headers) } static func updateOnBoarding(userId:String)-> (DataRequest) { var headers : [String : String] = [:] var parameters : [String : Any] = [:] parameters["confirmed"] = true if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } return Alamofire.request(baseURL + "/users/" + userId, method: .put, parameters: parameters,headers: headers) } //(GET)/baxters static func getBaxterClient(dayOfWeek: String, patientId: Int) -> (DataRequest) { var headers : [String : String] = [:] var parameters : [String : Any] = [:] if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" parameters["patient"] = "\(patientId)" parameters["day_of_week"] = "\(dayOfWeek)" } return Alamofire.request(baseURL + "/baxters?&_sort=intake_time:ASC", method: .get, parameters: parameters,headers: headers) } //(GET)/medicines static func getMedicines() -> (DataRequest) { var headers : [String : String] = [:] if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } return Alamofire.request(baseURL + "/medicines", method: .get, headers: headers) } //(update)/dose static func updateDose(id:String, lastTaken:String) -> (DataRequest) { var headers : [String : String] = [:] var parameters : [String:String] = [:] parameters["last_taken"] = lastTaken if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } return Alamofire.request(baseURL + "/doses/"+id, method: .put, parameters: parameters,headers: headers) } //Ercan:(delete)/dose static func deleteDose(id:String) -> (DataRequest) { var headers : [String : String] = [:] if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } return Alamofire.request(baseURL + "/doses/\(id)", method: .delete, headers: headers) } //(put)/intake static func setIntake(dose:NestedDose, patient:Patient, timeNow:String, state:String) -> (DataRequest) { var headers : [String : String] = [:] var parameters : [String:String] = [:] parameters["medicine"] = String(dose.medicine) parameters["patient"] = String(patient.id) parameters["time_taken_in"] = timeNow parameters["state"] = state if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } return Alamofire.request(baseURL + "/intakes", method: .post, parameters: parameters,headers: headers) } static func getIntakesCount(takenTime:DoseTakenTime) -> (DataRequest) { var headers : [String : String] = [:] var parameters : [String:String] = [:] if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } let stringTakenId = String(takenTime.rawValue) parameters["state"] = "\(stringTakenId)" return Alamofire.request(baseURL + "/intakes/count", method: .get, parameters: parameters,headers: headers) } static func getIntakesCountAll(greaterthandate:String, lowerthandate:String, patientId:Int) -> (DataRequest) { var headers : [String : String] = [:] var parameters : [String:String] = [:] if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } parameters["time_taken_in_gte"] = "\(greaterthandate)" parameters["time_taken_in_lte"] = "\(lowerthandate)" parameters["patient.id"] = "\(patientId)" return Alamofire.request(baseURL + "/intakes", method: .get, parameters: parameters,headers: headers) } //(GET)/patients static func getPatients(forCoachId coachId : Int) -> (DataRequest) { var headers : [String : String] = [:] if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } return Alamofire.request(baseURL + "/patients?coach_id=\(coachId)", method: .get, parameters: nil /*parameters*/, encoding: Alamofire.JSONEncoding.default, headers: headers) } //(POST)/patients static func createPatient(user: Int, first_name: String, insertion: String?, last_name: String, date_of_birth: String, coach_id: Int) -> (DataRequest) { var parameters : [String:Any] = [:] parameters["user"] = user parameters["first_name"] = first_name parameters["insertion"] = insertion ?? "" parameters["last_name"] = last_name parameters["date_of_birth"] = date_of_birth parameters["coach_id"] = coach_id var headers : [String : String] = [:] if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } return Alamofire.request(baseURL + "/patients", method: .post, parameters: parameters, encoding: Alamofire.JSONEncoding.default, headers: headers) } //(PUT)/users static func updateUser(userId: Int, username: String, email : String, password : String? = nil) -> (DataRequest) { var parameters : [String:String] = [:] parameters["username"] = username parameters["email"] = email if password != nil { parameters["password"] = password }else{ print("Pass is Null") } var headers : [String : String] = [:] if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } return Alamofire.request(baseURL + "/users/\(userId)", method: .put, parameters: parameters, encoding: Alamofire.JSONEncoding.default, headers: headers) } //(PUT)/patients static func updatePatient(patinetId: Int, first_name: String, insertion: String?, last_name: String, date_of_birth: String) -> (DataRequest) { var parameters : [String: String] = [:] parameters["first_name"] = first_name parameters["insertion"] = insertion ?? "" parameters["last_name"] = last_name parameters["date_of_birth"] = date_of_birth var headers : [String : String] = [:] if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } return Alamofire.request(baseURL + "/patients/\(patinetId)", method: .put, parameters: parameters, encoding: Alamofire.JSONEncoding.default, headers: headers) } //(GET)/patients static func getPatient(withUserId userId : Int) -> (DataRequest) { var headers : [String : String] = [:] if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } return Alamofire.request(baseURL + "/patients?user=\(userId)", method: .get, parameters: nil, encoding: Alamofire.JSONEncoding.default, headers: headers) } //(GET)/coaches static func getCoach(withUserId userId : Int) -> (DataRequest) { var headers : [String : String] = [:] if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } return Alamofire.request(baseURL + "/coaches?user=\(userId)", method: .get, parameters: nil, encoding: Alamofire.JSONEncoding.default, headers: headers) } //(GET)/medicines static func getAllMedicines() -> (DataRequest) { var headers : [String : String] = [:] if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } return Alamofire.request(baseURL + "/medicines", method: .get, parameters: nil, encoding: Alamofire.JSONEncoding.default, headers: headers) } //(GET)/Dose/{id} static func getOneDose(doseId: Int) -> (DataRequest) { var headers : [String : String] = [:] if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } return Alamofire.request(baseURL + "/doses/\(doseId)", method: .get, parameters: nil, encoding: Alamofire.JSONEncoding.default, headers: headers) } //(DELETE)/Dose/{id} static func deleteOneDose(doseId: Int) -> (DataRequest) { var headers : [String : String] = [:] if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } return Alamofire.request(baseURL + "/doses/\(doseId)", method: .delete, encoding: Alamofire.JSONEncoding.default, headers: headers) } //(POST)/baxter static func createNewBaxter(patientId: Int, intakeTime: String, doses: [Int], dayOfWeek: String) -> (DataRequest) { var headers : [String : String] = [:] var parameters : [String: Any] = [:] parameters["patient"] = patientId parameters["intake_time"] = intakeTime parameters["doses"] = doses parameters["day_of_week"] = dayOfWeek if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } return Alamofire.request(baseURL + "/baxters", method: .post, parameters: parameters, encoding: Alamofire.JSONEncoding.default, headers: headers) } //(POST)/doses static func createNewDose(amount: Int, medicineId: Int) -> (DataRequest) { var headers : [String : String] = [:] var parameters : [String: Any] = [:] parameters["amount"] = amount parameters["medicine"] = medicineId parameters["last_taken"] = "2010-01-01 12:00:00" if let token = KeychainWrapper.standard.string(forKey: Constants.tokenIdentifier) { headers["Authorization"] = "Bearer \(token)" } return Alamofire.request(baseURL + "/doses", method: .post, parameters: parameters, encoding: Alamofire.JSONEncoding.default, headers: headers) .responseJSON { response in print("UPDATE Patient:\(response.result.value)")} } }
// // SKSpriteNodeExtension.swift // MC7-Camp // // Created by Paula Leite on 09/07/20. // Copyright © 2020 Paula Leite. All rights reserved. // import Foundation import SpriteKit extension SKNode { func addGlow(radius: Float = 100) -> SKEffectNode { let view = SKView() let effectNode = SKEffectNode() let texture = view.texture(from: self) effectNode.shouldRasterize = true effectNode.blendMode = .add effectNode.filter = CIFilter(name: "CIGaussianBlur",parameters: ["inputRadius":radius]) addChild(effectNode) effectNode.addChild(SKSpriteNode(texture: texture)) return effectNode } func removeGlow(node: SKEffectNode) { removeChildren(in: [node]) } }
// // MessageDetails.swift // Tooli // // Created by Aadil Keshwani on 17/02/17. // Copyright © 2017 impero. All rights reserved. // import UIKit import Kingfisher import JSQMessagesViewController import NVActivityIndicatorView import Alamofire import ObjectMapper class MessageDetails: JSQMessagesViewController,NVActivityIndicatorViewable { var messages:[JSQMessage] = [] var currentBuddy : BuddyM = BuddyM() var userDetails = UIView() @IBOutlet var headerView : UIView? var lblName : UILabel? var page = 1 var isFirstTime : Bool = true var isFull : Bool = false var isCallWebService : Bool = true override func viewDidLoad() { super.viewDidLoad() self.startAnimating() chatHistory() NotificationCenter.default.addObserver(self, selector: #selector(chatMessage), name: NSNotification.Name(rawValue: Constants.Notifications.CHATHISTORYRETRIVED), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(chatMessageRecived), name: NSNotification.Name(rawValue: Constants.Notifications.MESSAGERECEIVED), object: nil) self.navigationController!.interactivePopGestureRecognizer!.isEnabled = true; let hView = UIView(frame: CGRect(x: 0, y: 0, width: Constants.ScreenSize.SCREEN_WIDTH, height: 60)) let backButton = UIButton(frame: CGRect(x: 8, y: 20, width: 40, height: 40)) backButton.setImage(UIImage(named: "ic_Backarrow"), for: UIControlState.normal) backButton.addTarget(self, action: #selector(actionBack(sender:)), for: UIControlEvents.touchUpInside) self.lblName = UILabel(frame: CGRect(x: 48, y: 23, width: Constants.ScreenSize.SCREEN_WIDTH-80, height: 30)) lblName?.text = self.currentBuddy.Name lblName?.textAlignment = NSTextAlignment.center lblName?.font = UIFont(name: "Oxygen-Bold", size: 18) lblName?.textColor = UIColor.white let navButton : UIButton = UIButton(frame: CGRect(x:80,y:0,width : Constants.ScreenSize.SCREEN_WIDTH - 160,height: 60)) navButton.addTarget(self, action: #selector(navigateTofriend), for: UIControlEvents.touchUpInside) hView.addSubview(lblName!) hView.addSubview(backButton) hView.addSubview(navButton) hView.backgroundColor = Constants.THEME.BGCOLOR hView.backgroundColor = UIColor.init(colorLiteralRed: 235.0/255.0, green: 38.0/255.0, blue: 40.0/255.0, alpha: 1) self.view.addSubview(hView) self.collectionView!.collectionViewLayout.springinessEnabled = false self.view.backgroundColor = Constants.THEME.BGCOLOR self.topContentAdditionalInset = 60 //self.view.bringSubview(toFront: self.headerView!) self.collectionView.backgroundColor = Constants.THEME.BGCOLOR self.inputToolbar!.contentView!.leftBarButtonItem!.isHidden = true self.inputToolbar!.contentView!.backgroundColor = Constants.THEME.BGCOLOR self.inputToolbar.contentView.rightBarButtonItem.imageView?.contentMode = UIViewContentMode.scaleAspectFit self.inputToolbar.contentView.rightBarButtonItem.setImage(UIImage(named: "ic_send"), for: UIControlState.normal) self.inputToolbar.contentView.rightBarButtonItem.setTitle("", for: UIControlState.normal) self.inputToolbar.contentView.leftBarButtonItemWidth = CGFloat(0.0) // Do any additional setup after loading the view. self.view.backgroundColor = UIColor.init(colorLiteralRed: 241.0/255.0, green: 242.0/255.0, blue: 243.0/255.0, alpha: 1) self.collectionView.collectionViewLayout.incomingAvatarViewSize = CGSize(width: 0.1, height: 0.1) self.senderId = "true" self.collectionView.collectionViewLayout.outgoingAvatarViewSize = CGSize(width: 0.1, height: 0.1) } override func viewWillAppear(_ animated: Bool) { self.sideMenuController()?.sideMenu?.allowLeftSwipe = false self.sideMenuController()?.sideMenu?.allowPanGesture = false self.sideMenuController()?.sideMenu?.allowRightSwipe = false //logintoXMPP() AppDelegate.sharedInstance().isChatActive = true AppDelegate.sharedInstance().cureentChatUserId = currentBuddy.ChatUserID self.finishReceivingMessage(animated: true) guard let tracker = GAI.sharedInstance().defaultTracker else { return } tracker.set(kGAIScreenName, value: "Message Details Screen.") guard let builder = GAIDictionaryBuilder.createScreenView() else { return } tracker.send(builder.build() as [NSObject : AnyObject]) } func chatMessage() { if(AppDelegate.sharedInstance().MsgListOfBuddy.Result.count == 0) { isFull = true } AppDelegate.sharedInstance().MsgListOfBuddy.Result = AppDelegate.sharedInstance().MsgListOfBuddy.Result.sorted { $0.ChatMessageID > $1.ChatMessageID } for temp in AppDelegate.sharedInstance().MsgListOfBuddy.Result { let msg:JSQMessage = JSQMessage(senderId: "\(temp.IsSendByMe)", senderDisplayName: temp.Name , date: Date(timeIntervalSince1970: temp.TotalMiliSecond), text: temp.MessageText) if(!self.isCallWebService) { self.messages.append(msg) } else { self.messages.insert(msg, at: 0) } } AppDelegate.sharedInstance().MsgListOfBuddy.Result = [] self.stopAnimating() self.isCallWebService = false self.collectionView.reloadData() if(self.page == 1) { self.finishReceivingMessage(animated: true) self.scrollToBottom(animated: true) } self.page = page + 1 } func chatMessageRecived() { for temp in AppDelegate.sharedInstance().MsgListOfBuddy.Result { let msg:JSQMessage = JSQMessage(senderId: "\(temp.IsSendByMe)", senderDisplayName: temp.Name, date: Date(timeIntervalSince1970: temp.TotalMiliSecond), text: temp.MessageText) self.messages.append(msg) } AppDelegate.sharedInstance().MsgListOfBuddy.Result = [] self.collectionView.reloadData() self.finishReceivingMessage(animated: true) self.scrollToBottom(animated: true) } func navigateTofriend (sender : UIButton) { if(currentBuddy.Role == 1) { let companyVC = self.storyboard?.instantiateViewController(withIdentifier: "OtherContractorProfile") as! OtherContractorProfile companyVC.userId = "\(currentBuddy.ChatUserID)" self.navigationController?.pushViewController(companyVC, animated: true) } else { let companyVC = self.storyboard?.instantiateViewController(withIdentifier: "CompanyView") as! CompanyView companyVC.userId = "\(currentBuddy.ChatUserID)" self.navigationController?.pushViewController(companyVC, animated: true) } } func actionBack(sender : UIButton) { self.navigationController?.popViewController(animated: true) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewWillDisappear(_ animated: Bool) { do { try AppDelegate.sharedInstance().simpleHub.invoke("GetBuddyList", arguments: []) } catch { print(error) } userDetails.removeFromSuperview() AppDelegate.sharedInstance().isChatActive = false AppDelegate.sharedInstance().cureentChatUserId = currentBuddy.ChatUserID } var isComposing = false var timer: Timer? override func textViewDidChange(_ textView: UITextView) { super.textViewDidChange(textView) if textView.text.characters.count == 0 { if isComposing { hideTypingIndicator() } } else { timer?.invalidate() if !isComposing { self.isComposing = true } else { } } } func hideTypingIndicator() { } override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) { if (text == "") { return; } if(!Reachability.isConnectedToNetwork()) { self.view.makeToast("Please Check Network Connection..", duration: 3, position: .center) return } let para:NSMutableDictionary = NSMutableDictionary() para.setValue(currentBuddy.ChatUserID, forKey: "ReceiverID") para.setValue(text, forKey: "MessageText") do { try AppDelegate.sharedInstance().simpleHub.invoke("SendMessage", arguments: [para]) } catch { } self.inputToolbar.contentView.textView.text = "" self.collectionView.reloadData() self.scrollToBottom(animated: true) } // Mark: JSQMessages CollectionView DataSource override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! { let message: JSQMessage = self.messages[indexPath.item] return message } override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource! { let message: JSQMessage = self.messages[indexPath.item] let bubbleFactory = JSQMessagesBubbleImageFactory() let outgoingBubbleImageData = bubbleFactory?.outgoingMessagesBubbleImage(with: UIColor(colorLiteralRed: 254.0/255.0, green: 210.0/255.0, blue: 209.0/255.0, alpha: 0.7)) let incomingBubbleImageData = bubbleFactory?.incomingMessagesBubbleImage(with: UIColor(colorLiteralRed: 89.0/255.0, green: 87.0/255.0, blue: 88.0/255.0, alpha: 0.1)) if message.senderId == self.senderId { return outgoingBubbleImageData } return incomingBubbleImageData } override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! { var senderAvatar : JSQMessagesAvatarImage = JSQMessagesAvatarImage(placeholder: UIImage()) senderAvatar = JSQMessagesAvatarImageFactory.avatarImage(withUserInitials: "SR", backgroundColor: UIColor(white: 0.85, alpha: 1.0), textColor: UIColor(white: 0.60, alpha: 1.0), font: UIFont(name: "Helvetica Neue", size: 14.0), diameter: 30) return senderAvatar } override func collectionView(_ collectionView: JSQMessagesCollectionView!, attributedTextForMessageBubbleTopLabelAt indexPath: IndexPath!) -> NSAttributedString! { return nil; } override func collectionView(_ collectionView: JSQMessagesCollectionView!, attributedTextForCellTopLabelAt indexPath: IndexPath!) -> NSAttributedString! { // let message: JSQMessage = self.messages[indexPath.item] // if message.senderId == self.senderId // { // return nil // } // // if indexPath.item - 1 > 0 // { // let previousMessage: JSQMessage = self.messages[indexPath.item - 1] // if previousMessage.senderId == message.senderId // { // return nil // } // } return nil } override func collectionView(_ collectionView: JSQMessagesCollectionView!, attributedTextForCellBottomLabelAt indexPath: IndexPath!) -> NSAttributedString! { return nil } // Mark: UICollectionView DataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.messages.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: JSQMessagesCollectionViewCell = super.collectionView(collectionView, cellForItemAt: indexPath) as! JSQMessagesCollectionViewCell let msg: JSQMessage = self.messages[indexPath.item] if !msg.isMediaMessage { if msg.senderId == self.senderId { cell.textView!.textColor = UIColor.black cell.textView!.linkTextAttributes = [NSForegroundColorAttributeName:UIColor.red, NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue] } else { cell.textView!.textColor = UIColor.black cell.textView!.linkTextAttributes = [NSForegroundColorAttributeName:UIColor.red, NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue] } } return cell } override func collectionView(_ collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForCellTopLabelAt indexPath: IndexPath!) -> CGFloat { return 0.0 } override func collectionView(_ collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForMessageBubbleTopLabelAt indexPath: IndexPath!) -> CGFloat { let currentMessage: JSQMessage = self.messages[indexPath.item] if currentMessage.senderId == self.senderId { return 0.0 } if indexPath.item - 1 > 0 { let previousMessage: JSQMessage = self.messages[indexPath.item - 1] if previousMessage.senderId == currentMessage.senderId { return 0.0 } } return kJSQMessagesCollectionViewCellLabelHeightDefault } override func collectionView(_ collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForCellBottomLabelAt indexPath: IndexPath!) -> CGFloat { return 0.0 } @IBAction func actionBack() { self.navigationController?.popViewController(animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func scrollViewDidScroll(_ scrollView: UIScrollView) { if !self.isCallWebService { if(!isFull) { if(scrollView.contentOffset.y <= -50) { chatHistory() } } } } func chatHistory() { self.isCallWebService = true let para:NSMutableDictionary = NSMutableDictionary() para.setValue(currentBuddy.ChatUserID, forKey: "ReceiverID") para.setValue(page, forKey: "PageIndex") do { try AppDelegate.sharedInstance().simpleHub.invoke("GetConversation", arguments: [para]) } catch { print(error) } } }
// // NSLayoutConstraint+AutoLayout.swift // AutoLayout // // Created by Stanislav Novacek on 02/10/2019. // import Foundation import UIKit extension NSLayoutConstraint { /// Sets given priority. /// - Parameter priority: priority public func priority(_ priority: UILayoutPriority) -> NSLayoutConstraint { self.priority = priority return self } /// Activated this constraint. @discardableResult public func activate() -> Self { isActive = true return self } /// Deactivate this constraint. @discardableResult public func deactivate() -> Self { isActive = false return self } }
// // DetailVC.swift // FinalProject // // Created by Nikita Tribhuvan on 4/20/18. // Copyright © 2018 Nikita Tribhuvan. All rights reserved. // import UIKit import CoreLocation class DetailVC: UITableViewController { var locationManager: CLLocationManager? var restaurant: Restaurant! let restaurantList = Restaurants() override func viewDidLoad() { super.viewDidLoad() locationManager = CLLocationManager() if CLLocationManager.locationServicesEnabled(){ locationManager!.requestWhenInUseAuthorization() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 5 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 0{ return 300.0 } else{ return 75.0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { tableView.backgroundColor = UIColor(red: 0.8196, green: 0.1255, blue: 0.0824, alpha: 1.0) switch indexPath.section { case 0: let cell = tableView.dequeueReusableCell(withIdentifier: "detail") as! DetailedTableViewCell! // cell!.restuaurantImage.image = restaurant.image cell!.name.text = restaurant.name cell!.address.text = restaurant.address cell!.cuisine.text = restaurant.cuisine cell!.rating.text = restaurant.rating cell!.cost.text = "Avg cost for two: $\(restaurant.cost)" return cell! case 1: let cell = tableView.dequeueReusableCell(withIdentifier: "sub") cell!.textLabel?.text = "Menu" cell!.detailTextLabel?.text = restaurant.menu return cell! case 2: let cell = tableView.dequeueReusableCell(withIdentifier: "sub") cell!.textLabel?.text = "Visit website" cell!.detailTextLabel?.text = restaurant.url return cell! case 3: let cell = tableView.dequeueReusableCell(withIdentifier: "favourite") cell!.textLabel?.text = "Get Directions" return cell! case 4: let cell = tableView.dequeueReusableCell(withIdentifier: "favourite") return cell! default: break } return UITableViewCell() } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.section { case 1: let url = URL(string: restaurant.menu) UIApplication.shared.open(url!, options: [:], completionHandler: nil) case 2: let url = URL(string: restaurant.url) UIApplication.shared.open(url!, options: [:], completionHandler: nil) case 3: let coordinate = locationManager?.location?.coordinate //make sure location manager has updated before trying to use let url = String(format: "http://maps.apple.com/maps?saddr=%f,%f&daddr=%f,%f", (coordinate?.latitude)!,(coordinate?.longitude)!,(restaurant.coordinate.latitude),(restaurant.coordinate.longitude)) UIApplication.shared.open(URL(string: url)!, options: [:], completionHandler: nil) case 4: let alertController = UIAlertController(title: "Favourites", message: "\(restaurant.name) added to favourites", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default) {(action) in } alertController.addAction(okAction) present(alertController, animated: true) { var array = UserDefaults.standard.array(forKey: "favorites") as? [String] if array != nil { if !array!.contains(self.restaurant.name) { array!.append(self.restaurant.name) } } else { array = [] array!.append(self.restaurant.name) } UserDefaults.standard.set(array, forKey:"favorites") } // restaurantList.restaurantList.append(self.restaurant) // let navVC = tabBarController!.viewControllers![1] as! UINavigationController // let tableVC = navVC.viewControllers[0] as! FavouriteVC // tableVC.restaurantList.restaurantList.append(restaurant) default: break } } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // Mention.swift // SZMentionsSwift // // Created by Steven Zweier on 1/11/16. // Copyright © 2016 Steven Zweier. All rights reserved. // import UIKit public struct Mention: Equatable { /** @brief The location of the mention within the attributed string of the UITextView */ public internal(set) var range: NSRange /** @brief Contains a reference to the object sent to the addMention: method */ public private(set) var object: CreateMention public static func == (lhs: Mention, rhs: Mention) -> Bool { return lhs.range == rhs.range && lhs.object.mentionName == rhs.object.mentionName } }
// // Size.swift // HseTimetable // // Created by Pavel on 20.04.2020. // Copyright © 2020 Hse. All rights reserved. // import UIKit import Foundation enum Size { case common case double case small case large var indent: CGFloat { switch self { case .common: return 5.0 case .double: return Size.common.indent * 2 case .small: return 2.5 case .large: return 20.0 } } var cornerRadius: CGFloat { switch self { case .common: return 15.0 case .double: return Size.double.cornerRadius * 2 case .small: return 5.0 case .large: return 40.0 } } var font: CGFloat { switch self { case .common: return 15.0 case .double: return Size.common.font * 2 case .small: return 12.0 case .large: return 25.0 } } }
// // CoronaLegendViewControllerFactory.swift // CoronaGotUs // // Created by Karim Alweheshy on 11/25/20. // import UIKit struct CoronaLegendViewControllerFactory { func makeViewController() -> CoronaLegendViewController { let storyboard = UIStoryboard(name: "CoronaLegend", bundle: nil) let viewController = storyboard.instantiateInitialViewController { coder -> CoronaLegendViewController? in CoronaLegendViewController(coder: coder) } return viewController! } }
// // DIResolver+Details.swift // Recruitment-iOS // // Created by Oleksandr Bambuliak on 18/03/2020. // Copyright © 2020 Oleksandr Bambuliak. All rights reserved. // import UIKit // MARK: - Details protocol DetailsProtocol { func presentDetailsViewController(model: ItemData) -> UIViewController } extension DIResolver: DetailsProtocol { func presentDetailsViewController(model: ItemData) -> UIViewController { let viewController = DetailsViewController() let interactor = DetailsInteractor(networkController: self.networkController) let wireFrame = DetailsWireFrame(resolver: self) let presenter = DetailsPresenter(model: model, view: viewController, wireFrame: wireFrame, interactor: interactor) viewController.presenter = presenter return viewController } }
// // Created by Wojciech Chojnacki on 03/06/2021. // import Foundation public struct PageProperiesUpdateRequest { public enum Key: Hashable, Equatable { case name(Page.PropertyName) case id(PageProperty.Identifier) } public let properties: [Key: WritePageProperty] public init(properties: [Key: WritePageProperty]) { self.properties = properties } } extension PageProperiesUpdateRequest: Encodable { enum CodingKeys: String, CodingKey { case properties } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) // default encoder wasn't happy with out properties type and was converting it to an array. let entries: [(String, WritePageProperty)] = self.properties.map { entry in let key: String switch entry.0 { case .name(let value): key = value case .id(let value): key = value.rawValue } return (key, entry.1) } let properties = Dictionary(uniqueKeysWithValues: entries) try container.encode(properties, forKey: .properties) } } extension PageProperiesUpdateRequest.Key: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() switch self { case .name(let value): try container.encode(value) case .id(let value): try container.encode(value) } } }
// // UITableView+Extension.swift // Githuber // // Created by Meng Li on 2020/9/9. // Copyright © 2020 Meng Li. All rights reserved. // extension UITableView { func hideFooterView() { tableFooterView = UIView(frame: .zero) tableFooterView?.backgroundColor = .clear } }
// // ColorPadsTests.swift // ColorPadsTests // // Created by Reza Shirazian on 4/6/20. // Copyright © 2020 Reza Shirazian. All rights reserved. // import XCTest import WorkflowTesting @testable import ColorPads class ColorPadsTests: XCTestCase { func test_colorPadPanelWorkflow_colorChange() throws { ColorPadPanelWorkflow.Action .tester(withState: ColorPadPanelWorkflow.State()) .send(action: .colorChanged(.red)) { output in switch output { case .colorChanged(let color): XCTAssertEqual(color, .red) default: XCTFail() } } } func test_colorPadRootWorkflow_colorChange() { ColorPadRootWorkflow.Action .tester(withState: ColorPadRootWorkflow.State(color: .blue)) .assertState {state in XCTAssertEqual(state.color, .blue) }.send(action: .colorChanged(.red)) .assertState {state in XCTAssertEqual(state.color, .red) } } }
// // Created by Scott Moon on 2019-05-01. // Copyright (c) 2019 Scott Moon. All rights reserved. // import Foundation public protocol Endpoint { var baseURL: String { get } var path: String { get } var httpMethod: HTTPMethod { get } var headers: [String: String]? { get } var queryParameters: [String: String]? { get } var bodyParameters: [String: Any]? { get } } extension Endpoint { public var headers: [String: String]? { return nil } public var bodyParameters: [String: Any]? { return nil } }
// // 2018-Day3.swift // AOC2018 // // Created by Philipp Wallrich on 16.12.18. // /*: ## Day 3 Part 1 The whole piece of fabric they're working on is a very large square - at least `1000` inches on each side. Each Elf has made a claim about which area of fabric would be ideal for Santa's suit. All claims have an ID and consist of a single rectangle with edges parallel to the edges of the fabric. Each claim's rectangle is defined as follows: The number of inches between the left edge of the fabric and the left edge of the rectangle. The number of inches between the top edge of the fabric and the top edge of the rectangle. The width of the rectangle in inches. The height of the rectangle in inches. A claim like `#123 @ 3,2: 5x4` means that claim ID `123` specifies a rectangle `3` inches from the left edge, `2` inches from the top edge, `5` inches wide, and `4` inches tall. Visually, it claims the square inches of fabric represented by `#` (and ignores the square inches of fabric represented by `.`) in the diagram below: ``` ........... ........... ...#####... ...#####... ...#####... ...#####... ........... ........... ........... ``` The problem is that many of the claims overlap, causing two or more claims to cover part of the same areas. For example, consider the following claims: ``` #1 @ 1,3: 4x4 #2 @ 3,1: 4x4 #3 @ 5,5: 2x2 ``` Visually, these claim the following areas: ``` ........ ...2222. ...2222. .11XX22. .11XX22. .111133. .111133. ........ ``` The four square inches marked with X are claimed by both `1` and `2`. (Claim `3`, while adjacent to the others, does not overlap either of them.) If the Elves all proceed with their own plans, none of them will have enough fabric. How many square inches of fabric are within two or more claims? */ /*: ## Day 3 Part 2 Amidst the chaos, you notice that exactly one claim doesn't overlap by even a single square inch of fabric with any other claim. If you can somehow draw attention to it, maybe the Elves will be able to make Santa's suit after all! For example, in the claims above, only claim 3 is intact after all claims are made. What is the ID of the only claim that doesn't overlap? The current solution isn't really quick yet, so smth else should be used. Maybe creating a Matrix upfront and checking with the matrix if the regions overlap */ import Foundation open class Day3: Day { public init() { super.init(file: #file) } public init(with input: String) { super.init(input: input) } override public func part1() -> String { var matrix = Array(repeating: Array(repeating: 0, count: 1000), count: 1000) let res = input.split(separator: "\n") .reduce(0) { res, str in var newRes = res let rect = Rect(from: String(str))! for x in rect.x..<(rect.x + rect.width) { for y in rect.y..<(rect.y + rect.height) { matrix[x][y] += 1 if matrix[x][y] == 2 { // if the value is 2 after increasing // there was allready 1 item at that slot before // therfore increasing counter. 3rd, 4th.. occurences won't increment newRes += 1 } } } return newRes } return "\(res)" } override public func part2() -> String { let values = getRects(from: input) for (idx, rect) in values.enumerated() { var overlaps = false for i in 0..<values.count { if i == idx { continue } if rect.overlaps(with: values[i]) { overlaps = true break } } if !overlaps { return "\(rect.id)" } } return "" } func getRects(from data: String) -> [Rect] { return data .split(separator: "\n") .map { Rect(from: String($0))! } } }
// // BBBackbeamRequest.swift // backbeam // // Created by James Tang on 28/7/14. // Copyright (c) 2014 James Tang. All rights reserved. // import Foundation class BBBackbeamRequest: NSObject { var key : String? var method : String? var nonce : String? var path : String? var time : String? var secret : String? var project : String? var env : String? var optionals = Dictionary<String, AnyObject>() func signature () -> String { return canonical().digest(HMACAlgorithm.SHA1, key: secret!) } func canonical () -> String { var keys : [AnyObject] = self.canonicalArray() var params = Dictionary<String, AnyObject>() for (key, value) in self.dictionaryWithValuesForKeys(keys) { params.updateValue(value, forKey: key as String) } for (key, value) in self.optionals { params.updateValue(value, forKey: key) } var array = sorted(params.keys, <) var mapped = array.map { "\($0)=\(params[$0]!)" } return join("&", mapped); } func canonicalArray () -> [String] { return ["key", "method", "nonce", "path", "time"] } func query() -> String { var keys : [AnyObject] = ["key", "nonce", "time"] var params = Dictionary<String, AnyObject>() for (key, value) in self.dictionaryWithValuesForKeys(keys) { params.updateValue(value, forKey: key as String) } for (key, value) in self.optionals { params.updateValue(value, forKey: key) } var array = sorted(params.keys, <) var mapped = array.map { "\($0)=\(params[$0]!)" } return join("&", mapped); } func send(completion:((NSData!, NSURLResponse!, NSError!) -> Void)!) -> Void { let base = "http://api-\(env!)-\(project!).backbeamapps.com" let component = NSURLComponents(string: base) component.path = path! component.query = query() + "&signature=\(signature())" let url = component.URL let task = NSURLSession.sharedSession().dataTaskWithURL(url , completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in completion(data, response, error) }) task.resume() } }
// Chapter 3, Exercise 3-23 // Implement an algorithm to reverse a linked list. Now do it without recursion. class ListNode { let value: Int var next: ListNode? init(value: Int) { self.value = value } } var headNode: ListNode? var currentNode: ListNode? // Populate for i in 0...10 { if let previousNode = currentNode { let node = ListNode(value: i) previousNode.next = node currentNode = node } else { headNode = ListNode(value: i) currentNode = headNode } } // Reverse currentNode = headNode var reversedHeadNode: ListNode? while currentNode != nil { let nextNode = currentNode!.next currentNode!.next = reversedHeadNode reversedHeadNode = currentNode currentNode = nextNode } // Print reversed list currentNode = reversedHeadNode while currentNode != nil { print("Current node \(currentNode!.value)") currentNode = currentNode!.next }
// // EnsureFinancialDataZone.swift // Jupiter // // Created by adulphan youngmod on 21/8/18. // Copyright © 2018 goldbac. All rights reserved. // import Foundation import Foundation import CloudKit extension OperationCloudKit { func ensureZoneForFinancialData() { let operation = CKFetchRecordZonesOperation.fetchAllRecordZonesOperation() operation.fetchRecordZonesCompletionBlock = { (recordZones, error) in if error != nil { print(error!) ; return } let zoneID = CloudKit.financialDataZoneID let isContained = recordZones?.contains(where: { (dictionary) -> Bool in dictionary.value.zoneID == zoneID }) ?? false if isContained { print("FinancialData: zone already created") } else { self.createZoneForFinancialData() } } CloudKit.privateDatabase.add(operation) } private func createZoneForFinancialData() { let zoneID = CloudKit.financialDataZoneID let zone = CKRecordZone(zoneID: zoneID) let operation = CKModifyRecordZonesOperation(recordZonesToSave: [zone], recordZoneIDsToDelete: nil) operation.modifyRecordZonesCompletionBlock = { (zones, zoneIDs, error) in if error != nil { print(error!) ; return } print(zones!) print("FinancialData: successfully created") } CloudKit.privateDatabase.add(operation) } func deleteAllZone() { let zoneID = CloudKit.financialDataZoneID let operation = CKModifyRecordZonesOperation(recordZonesToSave: nil, recordZoneIDsToDelete: [zoneID]) operation.modifyRecordZonesCompletionBlock = { (zones, zoneIDs, error) in if error != nil { print(error!) ; return } for id in zoneIDs! { print(id.zoneName," is deleted") } } CloudKit.privateDatabase.add(operation) } }
// // Request.swift // InvestimentApp // // Created by Israel on 10/12/19. // Copyright © 2019 israel3D. All rights reserved. // import Foundation struct Request { var investedAmount: Double var index: String = "CDI" var rate: Int var isTaxFree: Bool = false var maturityDate: String var params: [String: Any] { return [ "investedAmount": investedAmount, "index": index, "rate": rate, "isTaxFree": isTaxFree, "maturityDate": maturityDate ] } }
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ import UIKit class MessageCell: UITableViewCell { static let MaxMessageWidth: CGFloat = UIScreen.main.bounds.width * 0.8 var message: String? { didSet { messageLabel.text = message updateSelfWidth(message: message!) } } var author: String? { didSet { authorLabel.text = author } } var authorColor: Int? { didSet { authorLabel.textColor = UIColor.chatColors[authorColor ?? 0] } } var date: String? { didSet { dateLabel.text = date } } var maxConstraint: CGFloat! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var widthConstraint: NSLayoutConstraint! @IBOutlet weak var shadowView: UIView! { didSet { shadowView.layer.shadowColor = UIColor.black.cgColor shadowView.layer.shadowOffset = CGSize(width: 0, height: 1); shadowView.layer.shadowRadius = 5; shadowView.layer.shadowOpacity = 0.1; shadowView.layer.masksToBounds = false } } @IBOutlet weak var messageView: UIView! { didSet { messageView.layer.cornerRadius = 10 messageView.clipsToBounds = true } } override func awakeFromNib() { super.awakeFromNib() maxConstraint = MessageCell.MaxMessageWidth messageLabel.font = UIFont.systemFont(ofSize: MessageCell.defaultFontSize()) backgroundColor = .clear selectionStyle = .none } func updateSelfWidth(message: String) { let textLabel = UILabel() textLabel.text = message textLabel.sizeToFit() let constant = min(textLabel.frame.width, maxConstraint) self.widthConstraint.constant = max(constant + 16, 116) } static func defaultFontSize() -> CGFloat { return 17 } }
import Foundation import RxSwift import RxRelay import RxCocoa class SendFeeCautionViewModel { private let disposeBag = DisposeBag() private let service: FeeRateService private let cautionRelay = BehaviorRelay<TitledCaution?>(value: nil) var caution: TitledCaution? { didSet { if oldValue != caution { cautionRelay.accept(caution) } } } init(service: FeeRateService) { self.service = service subscribe(disposeBag, service.statusObservable) { [weak self] _ in self?.sync() } sync() } private func sync() { guard service.feeRateAvailble else { caution = TitledCaution(title: "send.fee_settings.fee_error.title".localized, text: "send.fee_settings.fee_rate_unavailable".localized, type: .error) return } if case let .completed(feeRate) = service.status, service.recommendedFeeRate > feeRate { if service.minimumFeeRate <= feeRate { caution = TitledCaution(title: "send.fee_settings.stuck_warning.title".localized, text: "send.fee_settings.stuck_warning".localized, type: .warning) } else { caution = TitledCaution(title: "send.fee_settings.fee_error.title".localized, text: "send.fee_settings.too_low".localized, type: .error) } } else { caution = nil } } } extension SendFeeCautionViewModel: ITitledCautionViewModel { var cautionDriver: Driver<TitledCaution?> { cautionRelay.asDriver() } }
// // ContactsViewController.swift // Dota // // Created by Pisit Lolak on 19/7/2561 BE. // Copyright © 2561 Pisit Lolak. All rights reserved. // import UIKit import ContactsUI class ContactsViewController: UIViewController, CNContactPickerDelegate { @IBOutlet weak var phoneNumberLabel: UILabel! @IBAction func selectNumber(_ sender: Any) { let picker = CNContactPickerViewController() picker.delegate = self picker.displayedPropertyKeys = [CNContactPhoneNumbersKey] present(picker,animated: true,completion: nil) } func contactPicker(_ picker: CNContactPickerViewController, didSelect contactProperty: CNContactProperty) { let phoneNumber = contactProperty.value as? CNPhoneNumber phoneNumberLabel.text = phoneNumber?.stringValue } }
// // SpellViewController.swift // QrCode App // // Created by Liloudini Aziz on 29/10/2017. // Copyright © 2017 Liloudini Aziz. All rights reserved. // import UIKit import AVFoundation import Alamofire class SpellViewController: UIViewController { @IBOutlet weak var txvCode: UITextView! @IBOutlet weak var btnList: UIButton! @IBOutlet weak var btnSave: UIButton! var lecteur = AVSpeechUtterance() var synth = AVSpeechSynthesizer() var textGet:String = "" let save = UserDefaults.standard override func viewDidLoad() { super.viewDidLoad() let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))) tap.cancelsTouchesInView = false self.view.addGestureRecognizer(tap) // Do any additional setup after loading the view. btnList.layer.cornerRadius = btnList.frame.height / 2 btnSave.layer.cornerRadius = btnList.frame.height / 2 txvCode.layer.borderWidth = CGFloat(2.0) //txvCode.layer.borderColor = UIColor.blue.cgColor txvCode.text = textGet.couper(longFin: 2) // self.lecteur = AVSpeechUtterance(string: txvCode.text) spell() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func actionSave(_ sender: UIButton) { if synth.isSpeaking { synth.stopSpeaking(at: .immediate) } let alert = UIAlertController(title: "Confirmation", message: "Enregistrer ce code qr ?", preferredStyle: .alert) let okAction = UIAlertAction(title: "ok", style: .default, handler: {(void) in let id = (Int)(UserDefaults.standard.value(forKey: "id") as! String)! //enregistrement du code self.save(id: id, texte: self.textGet) }) let cancelAction = UIAlertAction(title: "cancel", style: .cancel, handler: nil) alert.addAction(okAction) alert.addAction(cancelAction) self.present(alert, animated: true, completion: nil) } func save (id:Int,texte:String){ let parameter:Parameters = ["id_user":id,"instruction":texte] Alamofire.request("http://pridux.net/mobile/save_scan.php", method: .post,parameters:parameter).validate(){request, response, data in return .success }.responseJSON() { response in let rep = response.result.value as? Bool debugPrint(" Resultat \(rep!) ") if rep! { let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "liste") as! ListCodeViewController self.present(viewController, animated: true, completion: nil) }else{ let alert = UIAlertController(title: "Erreur", message: "Erreur lors de l'enregistrement", preferredStyle: .alert) let okAction = UIAlertAction(title: "Ok", style: .destructive, handler: nil) alert.addAction(okAction) self.present(alert, animated: true, completion: nil) } } } @IBAction func actionReplay(_ sender: UIButton) { spell() } func spell() { if synth.isSpeaking { synth.stopSpeaking(at: .immediate) } lecteur = AVSpeechUtterance(string: txvCode.text) lecteur.voice = AVSpeechSynthesisVoice(language: Provider.getLangue(lg: textGet.couper(longDeb: 2))) lecteur.rate = 0.4 synth.speak(lecteur) } @IBAction func actionMenu(_ sender: UIBarButtonItem) { let alert = UIAlertController(title: "Menu", message: "", preferredStyle: .actionSheet) let okAction = UIAlertAction(title: "Liste des codes qr", style: .default, handler: {(action) -> Void in }) let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: {(action) -> Void in }) alert.addAction(okAction) alert.addAction(cancelAction) self.present(alert, animated: true, completion: nil) } override func viewWillDisappear(_ animated: Bool) { synth.stopSpeaking(at: .immediate) } /* // 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. } */ @IBAction func actionDisconnet(_ sender: Any) { let alert = UIAlertController(title: "Information", message: "Voulez vous vous deconnecter ?", preferredStyle: .alert) let okAction = UIAlertAction(title: "ok", style: .default, handler: {(void) in let viewCOntroller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "welcome") self.present(viewCOntroller, animated: true, completion: nil) UserDefaults.standard.removeObject(forKey: "id") }) let cancelAction = UIAlertAction(title: "cancel", style: .cancel, handler: nil) alert.addAction(okAction) alert.addAction(cancelAction) self.present(alert, animated: true, completion: nil) } }
// // FlightAttendantViewController.swift // Flykeart App // // Created by Federico Brandt on 4/27/19. // Copyright © 2019 Federico Brandt. All rights reserved. // import UIKit class FlightAttendantViewController: UIViewController { var seats = [String]() @IBOutlet weak var orderTable: UITableView! @IBOutlet weak var WaterAmount: UILabel! @IBOutlet weak var CokeAmount: UILabel! @IBOutlet weak var PeanutsAmount: UILabel! @IBOutlet weak var PretzelsAmount: UILabel! var waterAmount = 0 var cokeAmount = 0 var peanutsAmount = 0 var pretzelsAmount = 0 var orderList : [Order] = [] override func viewDidLoad() { super.viewDidLoad() orderTable.dataSource = self orderTable.delegate = self super.view.addSubview(orderTable) loadTotal() loadNewOrders() orderTable.dataSource = self orderTable.delegate = self } @IBAction func goBackClicked(_ sender: Any) { self.dismiss(animated: true, completion: nil) } private func loadNewOrders() { FirebaseClient.getNewOrders(completion: {(result) in guard let newOrder = result else {return} self.orderList.append(newOrder) self.orderTable.reloadData() }) } func loadTotal(){ waterAmount = 0 cokeAmount = 0 peanutsAmount = 0 pretzelsAmount = 0 if orderList.count != 0{ for order in self.orderList{ if order.drinkChoice == "Water"{ waterAmount += 1 } if order.drinkChoice == "Coke"{ cokeAmount += 1 } if order.snackChoice == "Peanuts"{ peanutsAmount += 1 } if order.snackChoice == "Pretzels"{ pretzelsAmount += 1 } } } WaterAmount.text = String(waterAmount) CokeAmount.text = String(cokeAmount) PretzelsAmount.text = String(pretzelsAmount) PeanutsAmount.text = String(peanutsAmount) } } extension FlightAttendantViewController: UITableViewDelegate,UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return orderList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = orderTable.dequeueReusableCell(withIdentifier: "OrderCell")! as! OrderCellTableViewCell if let btnServe = cell.contentView.viewWithTag(101) as? UIButton{ btnServe.addTarget(self, action: #selector(deleteRow(_ :)), for: .touchUpInside) } let info = orderList[indexPath.row] cell.setUpCell(withInfo : info) return cell } @objc func deleteRow(_ sender: UIButton){ let point = sender.convert(CGPoint.zero, to: orderTable) guard let indexPath = orderTable.indexPathForRow(at: point) else{ return } // Delete from firebase FirebaseClient.uploadServed(seat: orderList[indexPath.item].seat, name: orderList[indexPath.item].name, snack: orderList[indexPath.item].snackChoice, drink: orderList[indexPath.item].drinkChoice) FirebaseClient.deleteOrder(seatNumber: orderList[indexPath.row].getSeat()) orderList.remove(at: indexPath.row) orderTable.deleteRows(at: [indexPath], with: .left) loadTotal() } }
// // SecretConstants.swift // Travel Companion // // Created by Stefan Jaindl on 01.08.18. // Copyright © 2018 Stefan Jaindl. All rights reserved. // import Foundation class SecretConstants { static let apiKeyGoogleMaps = "placeholder" static let apiKeyGooglePlaces = "placeholder" static let apiKeyFlickr = "placeholder" static let apiKeyRomeToRio = "placeholder" static let userNameGeoNames = "placeholder" static let restCountriesApiKey = "placeholder" static let countryApiApiKey = "placeholder" }
// // TextTableViewCell.swift // SuperHeroes // // Created by Òscar Muntal on 23/01/2018. // Copyright © 2018 Muntalapps. All rights reserved. // import UIKit class TextTableViewCell: UITableViewCell { @IBOutlet weak var descriptionLabel: UILabel! func configure(superHero: SuperHero) { descriptionLabel.text = superHero.description != "" ? superHero.description : "(No description)" } }
// // ViewController.swift // Quick Share // // Created by Abhishek Thakur on 12/05/19. // Copyright © 2019 Abhishek Thakur. All rights reserved. // import UIKit import Photos class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var assetCollection: PHAssetCollection? var photos: PHFetchResult<PHAsset>? @IBOutlet weak var tableView: UITableView! let reuseIdentifier = "tableViewCell" var dummyObject = ["hi","there","iam","Abhushe"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let collection = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: nil) if(collection.firstObject != nil) { self.assetCollection = collection.firstObject! as PHAssetCollection let option = PHFetchOptions() option.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue) option.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: false)] self.photos = PHAsset.fetchAssets(in: assetCollection!, options: option) } else{ print("Nothing found") } tableView.dataSource = self tableView.delegate = self } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let id = segue.identifier{ if(id == "ShowFullImageSegue"){ let newVc = segue.destination as! ShowImageViewController var indexpath = self.tableView.indexPath(for: sender as! UITableViewCell) if let asset = self.photos?[(indexpath!.row)]{ newVc.asset = asset } } } } // Defineing each table or poppulated func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: myTableViewCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! myTableViewCell if let asset = self.photos?[indexPath.row]{ PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width: 320, height: 240), contentMode: .aspectFill, options: nil, resultHandler:{ (result, info) in if let image = result { cell.myImageview?.image = image } }) } cell.myImageview.image = UIImage(named: "polaroid") return cell } // Handling each table view func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dummyObject.count } }
// // ViewController.swift // Challenge // // Created by Camilo Castro on 06-09-20. // Copyright © 2020 SoSafe. All rights reserved. // import UIKit import MapKit import Shared import API class ViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var map: MKMapView! var debounce:Timer? var lastQuery:String = "" // Mark - Lifecycle override func viewDidLoad() { super.viewDidLoad() self.showCurrentLocationIn(map: self.map) self.map.delegate = self self.showNearbyPointsOfInterestIn(map: self.map, keyword: self.lastQuery) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.setNavigationBarHidden(false, animated: animated) } // Mark - Map Delegate func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { let identifier = annotation.title! ?? "" var view: MKMarkerAnnotationView if let dequeuedView = mapView.dequeueReusableAnnotationView( withIdentifier: identifier) as? MKMarkerAnnotationView { dequeuedView.annotation = annotation view = dequeuedView return view } view = MKMarkerAnnotationView( annotation: annotation, reuseIdentifier: identifier) view.canShowCallout = true view.calloutOffset = CGPoint(x: -5, y: 5) let infoButton = UIButton(type: .detailDisclosure) infoButton.tag = GooglePlacePointAnnotationCallouts.info.rawValue view.rightCalloutAccessoryView = infoButton let addFavsButton = UIButton(type:.contactAdd) addFavsButton.tag = GooglePlacePointAnnotationCallouts.favs.rawValue view.leftCalloutAccessoryView = addFavsButton return view } func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) { // https://stackoverflow.com/a/53802335 debounce?.invalidate() debounce = Timer.scheduledTimer(withTimeInterval: 1.5, repeats: false, block: {_ in Shared.log.trace("Changed Map Region \(mapView.region.center)") self.showNearbyPointsOfInterestIn(map: mapView, keyword: self.lastQuery) }) } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { guard view.annotation is GooglePlacePointAnnotation else { return } if(control.tag == GooglePlacePointAnnotationCallouts.info.rawValue) { Shared.log.info("Presenting Info Detail") self.performSegue(withIdentifier: "favsSegue", sender: self) return; } Shared.log.info("Adding Location to Favourites") self.saveLocationToFavourites(annotation: view.annotation as! GooglePlacePointAnnotation) } // Mark - UIActions @IBAction func searchButtonClicked(_ sender: UIButton) { self.showMapPlaceKeywordSearchAlert({query in self.lastQuery = query self.showNearbyPointsOfInterestIn(map: self.map, keyword: self.lastQuery) }) } }
// // ViewController.swift // SlideUpBar // // Created by Beka Demuradze on 2/27/20. // Copyright © 2020 Beka Demuradze. All rights reserved. // import UIKit import Lottie class ViewController: UIViewController { var value: CGFloat = 0 let arrowAnimation = AnimationView(name: "arrow2") let topView: UIView = { let topView = UIView() topView.backgroundColor = .white return topView }() let bottomControlls = BottomControls() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white view.addSubview(bottomControlls) bottomControlls.anchor(top: nil, leading: view.leadingAnchor, bottom: view.bottomAnchor, trailing: view.trailingAnchor, padding: .init(top: 0, left: 15, bottom: 10, right: 15)) view.addSubview(topView) topView.fillSuperview() view.bringSubviewToFront(topView) topView.layer.shadowColor = UIColor.black.cgColor topView.layer.shadowOpacity = 1 topView.layer.shadowOffset = .init(width: 0, height: -10) topView.layer.shadowRadius = 20 topView.addSubview(arrowAnimation) arrowAnimation.center = view.center arrowAnimation.anchor(top: nil, leading: view.leadingAnchor, bottom: view.bottomAnchor, trailing: view.trailingAnchor, padding: .init(top: 0, left: 185, bottom: 35, right: 185)) let panGesture = UIPanGestureRecognizer(target: self, action: #selector(draging)) topView.addGestureRecognizer(panGesture) } @objc func draging(gesture: UIPanGestureRecognizer) { switch gesture.state { case .changed: if value == 0 { slidingUp(gesture) } else { slidingDown(gesture) } case.ended: finishSliding(gesture) default: () } } func slidingUp(_ gesture: UIPanGestureRecognizer) { let translation = gesture.translation(in: nil) let move: CGFloat = translation.y if move > 0 { self.topView.transform = CGAffineTransform(translationX: 0, y: max(move - move, -120)) } else { self.topView.transform = CGAffineTransform(translationX: 0, y: max(move, -120)) } } func slidingDown(_ gesture: UIPanGestureRecognizer){ let translation = gesture.translation(in: nil) let move: CGFloat = translation.y self.topView.transform = CGAffineTransform(translationX: 0, y: -120) if move > 0 { self.topView.transform = CGAffineTransform(translationX: 0, y: min(0, -120 + move)) } } func finishSliding(_ gesture: UIPanGestureRecognizer) { let translation = gesture.translation(in: nil) let move: CGFloat = translation.y if move < -50 { UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: { self.topView.transform = CGAffineTransform(translationX: 0, y: -120) }) value = 1 arrowAnimation.play(toFrame: 20) } else { UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseInOut, animations: { self.topView.transform = CGAffineTransform(translationX: 0, y: 0) }) arrowAnimation.play(fromFrame: 20, toFrame: 68) value = 0 } } }
// // ImageProcessor-Swift.swift // Pixel // // Created by tu on 2019/6/28. // Copyright © 2019 iSpeech. All rights reserved. // import Foundation class ImageProcessor1 { class func processImage(image: UIImage) { guard let cgImage = image.cgImage else { return } let width = Int(image.size.width) let height = Int(image.size.height) let bytesPerRow = width * 4 let imageData = UnsafeMutablePointer<UInt32>.allocate(capacity: width * height) let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo: UInt32 = CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue guard let imageContext = CGContext(data: imageData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else { return } imageContext.draw(cgImage, in: CGRect(origin: .zero, size: image.size)) print("---------data from Swift version----------") for i in 0..<width * height { print(imageData[i]) } } }
// // ViewController.swift // Shake Your Moody // // Created by Robin PAUQUET on 07/06/2016. // Copyright © 2016 Robin PAUQUET. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var hair: UISwitch! @IBOutlet weak var skin: UISwitch! @IBOutlet weak var sex: UISwitch! @IBOutlet weak var imgMoi: UIImageView! @IBOutlet weak var btnClair: UIButton! @IBOutlet weak var btnCheveuxFonce: UIButton! @IBOutlet weak var btnSkinClair: UIButton! @IBOutlet weak var btnSkinFonce: UIButton! @IBOutlet weak var btnSexMale: UIButton! @IBOutlet weak var btnSexFemale: UIButton! let bold:UIFont = UIFont.boldSystemFontOfSize(15.0) let nobold:UIFont = UIFont.systemFontOfSize(15.0) override func viewDidLoad() { super.viewDidLoad() ProductsManager.sharedInstance.setProducts(Parser(adresse: "http://163.172.27.134/api/products").getProducts()) ProductsManager.sharedInstance.setHair(NSUserDefaults.standardUserDefaults().boolForKey("hair_b"), dark: NSUserDefaults.standardUserDefaults().boolForKey("hair_d")) ProductsManager.sharedInstance.setSkin(NSUserDefaults.standardUserDefaults().boolForKey("skin_b"), dark: NSUserDefaults.standardUserDefaults().boolForKey("skin_d")) ProductsManager.sharedInstance.setSex(NSUserDefaults.standardUserDefaults().boolForKey("sex_m"), female: NSUserDefaults.standardUserDefaults().boolForKey("sex_f")) sex.on = NSUserDefaults.standardUserDefaults().boolForKey("sex") hair.on = NSUserDefaults.standardUserDefaults().boolForKey("hair") skin.on = NSUserDefaults.standardUserDefaults().boolForKey("skin") if (NSUserDefaults.standardUserDefaults().boolForKey("hair_b")) { btnClair.titleLabel!.font = bold btnCheveuxFonce.titleLabel!.font = nobold } else { btnClair.titleLabel!.font = nobold btnCheveuxFonce.titleLabel!.font = bold } if (NSUserDefaults.standardUserDefaults().boolForKey("skin_b")) { btnSkinClair.titleLabel!.font = bold btnSkinFonce.titleLabel!.font = nobold } else { btnSkinClair.titleLabel!.font = nobold btnSkinFonce.titleLabel!.font = bold } if (NSUserDefaults.standardUserDefaults().boolForKey("sex_m")) { btnSexMale.titleLabel!.font = bold btnSexFemale.titleLabel!.font = nobold } else { btnSexMale.titleLabel!.font = nobold btnSexFemale.titleLabel!.font = bold } updateImage() //var products:[Product] = jsonToData(getJSON("http://163.172.27.134/api/products")) //test // Do any additional setup after loading the view, typically from a nib. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { Next() } func Next() { ProductsManager.sharedInstance.setMe(hair.on, skin: skin.on, sex: sex.on) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func click(sender: AnyObject) { switch sender as! UIButton { case btnClair: ProductsManager.sharedInstance.setHair(true, dark: false) btnClair.titleLabel!.font = bold btnCheveuxFonce.titleLabel!.font = nobold NSUserDefaults.standardUserDefaults().setObject(true, forKey: "hair_b") NSUserDefaults.standardUserDefaults().setObject(false, forKey: "hair_d") case btnCheveuxFonce: ProductsManager.sharedInstance.setHair(false, dark: true) btnClair.titleLabel!.font = nobold btnCheveuxFonce.titleLabel!.font = bold NSUserDefaults.standardUserDefaults().setObject(false, forKey: "hair_b") NSUserDefaults.standardUserDefaults().setObject(true, forKey: "hair_d") case btnSkinClair: ProductsManager.sharedInstance.setSkin(true, dark: false) btnSkinClair.titleLabel!.font = bold btnSkinFonce.titleLabel!.font = nobold NSUserDefaults.standardUserDefaults().setObject(true, forKey: "skin_b") NSUserDefaults.standardUserDefaults().setObject(false, forKey: "skin_d") case btnSkinFonce: ProductsManager.sharedInstance.setSkin(false, dark: true) btnSkinClair.titleLabel!.font = nobold btnSkinFonce.titleLabel!.font = bold NSUserDefaults.standardUserDefaults().setObject(false, forKey: "skin_b") NSUserDefaults.standardUserDefaults().setObject(true, forKey: "skin_d") case btnSexMale: ProductsManager.sharedInstance.setSex(true, female: false) btnSexMale.titleLabel!.font = bold btnSexFemale.titleLabel!.font = nobold NSUserDefaults.standardUserDefaults().setObject(true, forKey: "sex_m") NSUserDefaults.standardUserDefaults().setObject(false, forKey: "sex_f") case btnSexFemale: ProductsManager.sharedInstance.setSex(false, female: true) btnSexMale.titleLabel!.font = nobold btnSexFemale.titleLabel!.font = bold NSUserDefaults.standardUserDefaults().setObject(false, forKey: "sex_m") NSUserDefaults.standardUserDefaults().setObject(true, forKey: "sex_f") default: break } updateImage() } @IBAction func changedValue(sender: AnyObject) { switch sender as! UISwitch { case sex: NSUserDefaults.standardUserDefaults().setObject(sex.on, forKey: "sex") break; case hair: NSUserDefaults.standardUserDefaults().setObject(hair.on, forKey: "hair") break; case skin: NSUserDefaults.standardUserDefaults().setObject(skin.on, forKey: "skin") break; default: break; } } func updateImage() { imgMoi.image = UIImage(named: ProductsManager.sharedInstance.getMe()) } }
// SCNVector3Extensions.swift - Copyright 2020 SwifterSwift #if os(OSX) /// SwifterSwift: CGFloat. public typealias SceneKitFloat = CGFloat #else /// SwifterSwift: Float. public typealias SceneKitFloat = Float #endif #if canImport(SceneKit) import SceneKit // MARK: - Methods public extension SCNVector3 { /// SwifterSwift: Returns the absolute values of the vector's components. /// /// SCNVector3(2, -3, -6).abs -> SCNVector3(2, 3, 6) /// var absolute: SCNVector3 { return SCNVector3(abs(x), abs(y), abs(z)) } /// SwifterSwift: Returns the length of the vector. /// /// SCNVector3(2, 3, 6).length -> 7 /// var length: SceneKitFloat { return sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2)) } /// SwifterSwift: Returns the unit or normalized vector where `length = 1`. /// /// SCNVector3(2, 3, 6).normalized -> SCNVector3(2/7, 3/7, 6/7) /// var normalized: SCNVector3 { let length = sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2)) return SCNVector3(x / length, y / length, z / length) } } // MARK: - Operators public extension SCNVector3 { /// SwifterSwift: Add two SCNVector3s. /// /// SCNVector3(10, 10, 10) + SCNVector3(10, 20, -30) -> SCNVector3(20, 30, -20) /// /// - Parameters: /// - lhs: SCNVector3 to add to. /// - rhs: SCNVector3 to add. /// - Returns: result of addition of the two given SCNVector3s. static func + (lhs: SCNVector3, rhs: SCNVector3) -> SCNVector3 { return SCNVector3(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z) } /// SwifterSwift: Add a SCNVector3 to self. /// /// SCNVector3(10, 10, 10) += SCNVector3(10, 20, -30) -> SCNVector3(20, 30, -20) /// /// - Parameters: /// - lhs: `self`. /// - rhs: SCNVector3 to add. static func += (lhs: inout SCNVector3, rhs: SCNVector3) { lhs.x += rhs.x lhs.y += rhs.y lhs.z += rhs.z } /// SwifterSwift: Subtract two SCNVector3s. /// /// SCNVector3(10, 10, 10) - SCNVector3(10, 20, -30) -> SCNVector3(0, -10, 40) /// /// - Parameters: /// - lhs: SCNVector3 to subtract from. /// - rhs: SCNVector3 to subtract. /// - Returns: result of subtract of the two given SCNVector3s. static func - (lhs: SCNVector3, rhs: SCNVector3) -> SCNVector3 { return SCNVector3(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z) } /// SwifterSwift: Subtract a SCNVector3 from self. /// /// SCNVector3(10, 10, 10) -= SCNVector3(10, 20, -30) -> SCNVector3(0, -10, 40) /// /// - Parameters: /// - lhs: `self`. /// - rhs: SCNVector3 to subtract. static func -= (lhs: inout SCNVector3, rhs: SCNVector3) { lhs.x -= rhs.x lhs.y -= rhs.y lhs.z -= rhs.z } /// SwifterSwift: Multiply a SCNVector3 with a scalar /// /// SCNVector3(10, 20, -30) * 3 -> SCNVector3(30, 60, -90) /// /// - Parameters: /// - vector: SCNVector3 to multiply. /// - scalar: scalar value. /// - Returns: result of multiplication of the given SCNVector3 with the scalar. static func * (vector: SCNVector3, scalar: SceneKitFloat) -> SCNVector3 { return SCNVector3(vector.x * scalar, vector.y * scalar, vector.z * scalar) } /// SwifterSwift: Multiply self with a scalar /// /// SCNVector3(10, 20, -30) *= 3 -> SCNVector3(30, 60, -90) /// /// - Parameters: /// - vector: `self`. /// - scalar: scalar value. /// - Returns: result of multiplication of the given CGPoint with the scalar. static func *= (vector: inout SCNVector3, scalar: SceneKitFloat) { vector.x *= scalar vector.y *= scalar vector.z *= scalar } /// SwifterSwift: Multiply a scalar with a SCNVector3. /// /// 3 * SCNVector3(10, 20, -30) -> SCNVector3(30, 60, -90) /// /// - Parameters: /// - scalar: scalar value. /// - vector: SCNVector3 to multiply. /// - Returns: result of multiplication of the given CGPoint with the scalar. static func * (scalar: SceneKitFloat, vector: SCNVector3) -> SCNVector3 { return SCNVector3(vector.x * scalar, vector.y * scalar, vector.z * scalar) } /// SwifterSwift: Divide a SCNVector3 with a scalar. /// /// SCNVector3(10, 20, -30) / 3 -> SCNVector3(3/10, 0.15, -30) /// /// - Parameters: /// - vector: SCNVector3 to divide. /// - scalar: scalar value. /// - Returns: result of division of the given SCNVector3 with the scalar. static func / (vector: SCNVector3, scalar: SceneKitFloat) -> SCNVector3 { return SCNVector3(vector.x / scalar, vector.y / scalar, vector.z / scalar) } /// SwifterSwift: Divide self with a scalar. /// /// SCNVector3(10, 20, -30) /= 3 -> SCNVector3(3/10, 0.15, -30) /// /// - Parameters: /// - vector: `self`. /// - scalar: scalar value. /// - Returns: result of division of the given CGPoint with the scalar. static func /= (vector: inout SCNVector3, scalar: SceneKitFloat) { vector = SCNVector3(vector.x / scalar, vector.y / scalar, vector.z / scalar) } } #endif
// // ViewImageSnapshot.swift // ListableUI-Unit-Tests // // Created by Kyle Van Essen on 11/26/19. // import UIKit public struct ViewImageSnapshot<ViewType:UIView> : SnapshotOutputFormat { // MARK: SnapshotOutputFormat public typealias RenderingFormat = ViewType public static func snapshotData(with renderingFormat : ViewType) throws -> Data { return renderingFormat.toImage.pngData()! } public static var outputInfo : SnapshotOutputInfo { return SnapshotOutputInfo( directoryName: "Images", fileExtension: "snapshot.png" ) } public static func validate(render newView : ViewType, existingData: Data) throws { let existing = try ViewImageSnapshot.image(with: existingData) let new = newView.toImage guard existing.size == new.size else { throw Error.differentSizes } guard UIImage.compareImages(lhs: existing, rhs: new) else { throw Error.notMatching } } private static func image(with data : Data) throws -> UIImage { guard data.isEmpty == false else { throw Error.zeroSizeData } guard let image = UIImage(data: data) else { throw Error.couldNotLoadReferenceImage } return image } public enum Error : Swift.Error { case differentSizes case notMatching case zeroSizeData case couldNotLoadReferenceImage } } extension UIView { var toImage : UIImage { UIGraphicsBeginImageContext(self.bounds.size) self.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } } /// Image diffing copied from Point Free (https://github.com/pointfreeco/swift-snapshot-testing/blob/master/Sources/SnapshotTesting/Snapshotting/UIImage.swift) /// with some changes. Notably, we base the extension UIImage { static func compareImages(lhs : UIImage, rhs : UIImage) -> Bool { return lhs.pngData() == rhs.pngData() } private func compare(_ old: UIImage, _ new: UIImage, precision: Float) -> Bool { guard let oldCgImage = old.cgImage else { return false } guard let newCgImage = new.cgImage else { return false } guard oldCgImage.width != 0 else { return false } guard newCgImage.width != 0 else { return false } guard oldCgImage.width == newCgImage.width else { return false } guard oldCgImage.height != 0 else { return false } guard newCgImage.height != 0 else { return false } guard oldCgImage.height == newCgImage.height else { return false } // Values between images may differ due to padding to multiple of 64 bytes per row, // because of that a freshly taken view snapshot may differ from one stored as PNG. // At this point we're sure that size of both images is the same, so we can go with minimal `bytesPerRow` value // and use it to create contexts. let minBytesPerRow = min(oldCgImage.bytesPerRow, newCgImage.bytesPerRow) let byteCount = minBytesPerRow * oldCgImage.height var oldBytes = [UInt8](repeating: 0, count: byteCount) guard let oldContext = context(for: oldCgImage, bytesPerRow: minBytesPerRow, data: &oldBytes) else { return false } guard let oldData = oldContext.data else { return false } if let newContext = context(for: newCgImage, bytesPerRow: minBytesPerRow), let newData = newContext.data { if memcmp(oldData, newData, byteCount) == 0 { return true } } let newer = UIImage(data: new.pngData()!)! guard let newerCgImage = newer.cgImage else { return false } var newerBytes = [UInt8](repeating: 0, count: byteCount) guard let newerContext = context(for: newerCgImage, bytesPerRow: minBytesPerRow, data: &newerBytes) else { return false } guard let newerData = newerContext.data else { return false } if memcmp(oldData, newerData, byteCount) == 0 { return true } if precision >= 1 { return false } var differentPixelCount = 0 let threshold = 1 - precision for byte in 0..<byteCount { if oldBytes[byte] != newerBytes[byte] { differentPixelCount += 1 } if Float(differentPixelCount) / Float(byteCount) > threshold { return false} } return true } private func context(for cgImage: CGImage, bytesPerRow: Int, data: UnsafeMutableRawPointer? = nil) -> CGContext? { guard let space = cgImage.colorSpace, let context = CGContext( data: data, width: cgImage.width, height: cgImage.height, bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: bytesPerRow, space: space, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue ) else { return nil } context.draw(cgImage, in: CGRect(x: 0, y: 0, width: cgImage.width, height: cgImage.height)) return context } }
// // ViewController.swift // Dicee // // Created by Tim Goens on 8/8/19. // Copyright © 2019 Tim Goens. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var diceImageView1: UIImageView! @IBOutlet weak var diceImageView2: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func rollButtonPressed(_ sender: UIButton) { } }
// // GameScene2.swift // BountySpinImage // // Created by justin fluidity on 6/29/17. // Copyright © 2017 justin fluidity. All rights reserved. // import SpriteKit // MARK: - Setup: class GameScene2: SKScene { var textures = [SKTexture]() let sprite = SKSpriteNode() let label = SKLabelNode() let spinSpeed = TimeInterval(0.25) var didClicklabel = false override func didMove(to view: SKView) { anchorPoint = CGPoint(x: 0.5, y: 0.5) // load label button: label.text = "auto-spin sculpture" label.position.y = (frame.maxY - label.frame.height) - x15 addChild(label) // load textures: for i in 0...6 { textures.append(SKTexture(imageNamed: "img_\(i)")) } // load sprite: sprite.texture = textures.first! sprite.size = textures.first!.size() addChild(sprite) } } // MARK: - Image manipulation extension GameScene2 { func imageUp() { let index = textures.index(of: sprite.texture!) if index == textures.count - 1 { sprite.texture = textures[0] } else { sprite.texture = textures[index! + 1] } } func imageDown() { let index = textures.index(of: sprite.texture!) if index == 0 { sprite.texture = textures[textures.count - 1] } else { sprite.texture = textures[index! - 1] } } func changeImage(_ isUp: Bool, _ amountOfTime: CGFloat) { let wait = SKAction.wait(forDuration: TimeInterval(amountOfTime)) if isUp { run(wait) { self.imageUp() } } else { run(wait) { self.imageDown() } } } } // MARK: - Touches: extension GameScene2 { enum Direction { case left, right } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { sprite.removeAllActions() if nodes(at: touches.first!.location(in: self)).contains(label) { didClicklabel = true sprite.run(.repeatForever(.animate(with: textures, timePerFrame: spinSpeed))) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { didClicklabel = false } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if didClickLabel { return } let touch = touches.first! let dx: Direction let (thisLoc, prevLoc) = (touch.location(in: self), touch.previousLocation(in: self)) guard thisLoc.x != prevLoc.x else { return } if (thisLoc.x > prevLoc.x) { dx = .right } else { dx = .left } if dx == .right { imageDown() } else { imageUp() } } }
import Bow /// Protocol for automatic derivation of Prism optics. public protocol AutoPrism: AutoOptics {} public extension AutoPrism { /// Generates a prism for an enum case with no associated values. /// /// - Parameter case: Case where the Prism must focus. /// - Returns: A Prism focusing on the provided case. static func prism(for case: Self) -> Prism<Self, ()> { return Prism<Self, ()>(getOrModify: { whole in (String(describing: whole) == String(describing: `case`)) ? Either.right(()) : Either.left(whole) }, reverseGet: { _ in `case` }) } /// Generates a prism for an enum case with associated values. /// /// - Parameter constructor: Constructor for the case with associated values. /// - Returns: A Prism focusing on the provided case. static func prism<A>(for constructor: @escaping (A) -> Self) -> Prism<Self, A> { func isSameCase(_ lhs: Self, _ rhs: Self) -> Bool { guard let lhsChild = Mirror(reflecting: lhs).children.first, let rhsChild = Mirror(reflecting: rhs).children.first else { return false } let lhsLabeledChild = Mirror(reflecting: lhsChild.value).children.first let rhsLabeledChild = Mirror(reflecting: rhsChild.value).children.first return lhsChild.label == rhsChild.label && lhsLabeledChild?.label == rhsLabeledChild?.label } func extractValues(autoPrism: Self) -> A? { let mirror = Mirror(reflecting: autoPrism) guard let child = mirror.children.first else { return nil } if let value = child.value as? A { return value } else { let labeledValueMirror = Mirror(reflecting: child.value) return labeledValueMirror.children.first?.value as? A } } func autoDerivation(autoPrism: Self) -> Either<Self, A> { guard let values = extractValues(autoPrism: autoPrism) else { return .left(autoPrism) } guard isSameCase(constructor(values), autoPrism) else { return .left(autoPrism) } return .right(values) } return Prism<Self, A>(getOrModify: autoDerivation, reverseGet: constructor) } }
// // CheckInViewModelTests.swift // MeventsUnitTests // // Created by Isnard Silva on 06/01/21. // import XCTest @testable import Mevents final class CheckInViewModelTests: XCTestCase { // MARK: - Properties var sut: CheckInViewModel! // MARK: - Setup Methods override func setUp() { super.setUp() } override func tearDown() { sut = nil super.tearDown() } // MARK: Test Methods func testEmptyEmailError() { // Given sut = CheckInViewModel() // When XCTAssertThrowsError(try sut.setUserEmail("")) { error in // Then XCTAssertEqual(error as? CheckInError, .emptyEmail) } } func testEmptyUserNameError() { // Given sut = CheckInViewModel() // When XCTAssertThrowsError(try sut.setUserName("")) { error in // Then XCTAssertEqual(error as? CheckInError, .emptyUserName) } } func testEmptyEventId() throws { // Given let promise = expectation(description: "Call to save an Check In") sut = CheckInViewModel() try sut.setUserName("User") try sut.setUserEmail("user@mail.com") // When sut.checkIn(completionHandler: { error in // Then XCTAssertEqual(error as? CheckInError, .emptyEventId) promise.fulfill() }) wait(for: [promise], timeout: 5) } }
// // AppointmentDetailTextFieldDelegate.swift // Appointment // // Created by Jeffrey Moran on 11/4/20. // Copyright © 2020 Jeff Moran. All rights reserved. // import UIKit protocol AppointmentDetailTextFieldDelegate: AnyObject { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool }
// // greenLabel.swift // TicTacToe // // Created by Christian Hurtado on 11/6/19. // Copyright © 2019 Pursuit. All rights reserved. // import Foundation
// // UIViewAnimationViewController.swift // swift2.0玩转UIKit基础篇 // // Created by goupigao on 16/8/25. // Copyright © 2016年 goupigao. All rights reserved. // import UIKit class UIViewAnimationViewController: UIViewController { //MARK: 全局变量和常量 @IBOutlet weak var contentView: UIView! var mFirstView: UIView! var mFirstViewFrame = CGRect(x: 8, y: 8, width: 150, height: 30) var mFirstViewBgColor = UIColor.purpleColor() var mFirstSubView: UIView! var mFirstSubViewFrame = CGRect(x: 5, y: 5, width: 20, height: 20) var replaceView:UIView! var mSecondView: UIView! var mSecondViewFrame = CGRect(x: 8, y: 48, width: 150, height: 10) var mThirdView: UIView! var mThirdViewFrame = CGRect(x: 8, y: 58, width: 150, height: 10) var mFourthView: UIView! var mFourthViewFrame = CGRect(x: 8, y: 68, width: 150, height: 10) override func viewDidLoad() { super.viewDidLoad() self.title = "演示UIViewAnimation" mFirstView = UIView(frame: mFirstViewFrame) mFirstView.backgroundColor = mFirstViewBgColor mFirstSubView = UIView(frame: mFirstSubViewFrame) mFirstSubView.backgroundColor = UIColor.whiteColor() mFirstView.addSubview(mFirstSubView) contentView.addSubview(mFirstView) replaceView = UIView(frame: mFirstViewFrame) replaceView.backgroundColor = UIColor.cyanColor() mSecondView = UIView(frame: mSecondViewFrame) mSecondView.backgroundColor = UIColor.redColor() contentView.addSubview(mSecondView) mThirdView = UIView(frame: mThirdViewFrame) mThirdView.backgroundColor = UIColor.greenColor() contentView.addSubview(mThirdView) mFourthView = UIView(frame: mFourthViewFrame) mFourthView.backgroundColor = UIColor.blueColor() contentView.addSubview(mFourthView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK:动画操作视图属性的三个方法: //1.beginCommit方法(iOS4.1及以下) @IBAction func startBtnClick1(sender: AnyObject) { UIView.beginAnimations("testAnimate", context: nil) UIView.setAnimationDuration(1) UIView.setAnimationRepeatAutoreverses(true) UIView.setAnimationRepeatCount(10) UIView.setAnimationDelegate(self) UIView.setAnimationDidStopSelector(#selector(animationDidStop(_:finished:))) mFirstView.backgroundColor = UIColor.magentaColor() UIView.commitAnimations() } override func animationDidStop(anim: CAAnimation, finished flag: Bool) { print("动画播放完成") } //2.Block方法:可以在一个动画中操作多个View,当操作开始执行的时候,会开启新的线程,避免阻塞主线程 @IBAction func startBtnClick2(sender: AnyObject) { UIView.animateWithDuration(1, delay: 0, options: [.CurveEaseInOut ,.Repeat], animations: { self.mFirstView.frame.origin.x += 60 }) { (true) in print("动画播放完成") } //UIViewAnimationOptions分3类: //1.动画控制相关:如LayoutSubviews(子控件一起动画),AllowUserInteraction(动画时允许用户交互)等 //2.时间曲线相关:如CurveEaseInOut等 //3.转场效果相关:如TransitionFlipFromLeft(从左翻转)等 } //3.Nest方法(嵌套Block):子Block会默认继承父Block的duration、curve等属性 @IBAction func startBtnClick3(sender: AnyObject) { UIView.animateWithDuration(1, delay: 0, options: [.CurveEaseInOut], animations: { self.mFirstView.frame.origin.x += 60 UIView.animateWithDuration(5, delay: 0, options: [.CurveLinear], animations: { self.mSecondView.frame.origin.x += 60 }, completion: nil)//未重写属性,5秒及CurveLinear的设置均不会生效 UIView.animateWithDuration(1, delay: 0, options: [.OverrideInheritedCurve,.CurveLinear], animations: { self.mThirdView.frame.origin.x += 60 }, completion: nil)//重写Curve属性 UIView.animateWithDuration(5, delay: 0, options: [.OverrideInheritedDuration,.OverrideInheritedCurve,.CurveLinear], animations: { self.mFourthView.frame.origin.x += 60 }, completion: nil)//重写Duration和Curve属性 }, completion: nil) } //MARK:视图转场动画(过渡动画) //操作subView @IBAction func startBtnClick4(sender: AnyObject) { UIView.transitionWithView(mFirstView, duration: 2, options: [.TransitionCurlUp,.AllowAnimatedContent], animations: { self.mFirstSubView.frame.origin.x += 120 }, completion: nil) //转场动画TransitionCurlUp表示向上翻页 //如果不设置AllowAnimatedContent,那么animations中的动画将在转场动画完成之后的瞬间完成重绘,显得特别突兀 } //替换View @IBAction func startBtnClick5(sender: AnyObject) { UIView.transitionFromView(mFirstView, toView: replaceView, duration: 2, options: .TransitionCrossDissolve, completion: nil) } //MARK:回退动画 @IBAction func fallbackBtnClick1(sender: AnyObject) { mFirstView.backgroundColor = mFirstViewBgColor//恢复初始的背景色 mFirstView.frame = mFirstViewFrame//恢复初始的frame mFirstSubView.frame = mFirstSubViewFrame mSecondView.frame = mSecondViewFrame mThirdView.frame = mThirdViewFrame mFourthView.frame = mFourthViewFrame mFirstView.layer.removeAllAnimations()//移除所有动画 mSecondView.layer.removeAllAnimations() mThirdView.layer.removeAllAnimations() mFourthView.layer.removeAllAnimations() UIView.transitionFromView(replaceView, toView:mFirstView , duration: 0, options: .TransitionNone, completion: nil)//替换回原始的View } }
// nef:begin:header /* layout: docs title: Overview */ // nef:end /*: # Effects {:.beginner} beginner The `BowEffects` module provides a foundation to work with side effects in a functional manner. In order to use it, you only need to import it: */ import BowEffects /*: This module includes multiple facilities to work with side effects: - **Type classes**: abstractions to suspend side effects and execute them asynchronous and concurrently. - **IO**: a powerful data type to encapsulate side effects and work with them in a functional manner. - **Utilities**: data types to work with resources and shared state functionally. ## Type classes Type classes in the Effects module abstract over the suspension of effects and their asynchronous and concurrent execution. The module contains the following type classes: | Type class | Description | | ---------------- | ------------------------------------------------------- | | MonadDefer | Enables delaying the evaluation of a computation | | Async | Enables running asynchronous computations that may fail | | Bracket | Provides safe resource acquisition, usage and release | | Effect | Enables suspension of side effects | | Concurrent | Enables concurrent execution of asynchronous operations | | ConcurrentEffect | Enables cancelation of effects running concurrently | | UnsafeRun | Enables unsafe execution of side effects | ## IO The IO data type is the core data type to provide suspension of side-effects. Its API lets us do powerful transformations and composition, and eventually evaluate them concurrently and asynchronously. IO also provides error handling capabilities. It lets us specify explicitly the type of errors that may happen in its underlying encapsulated side-effects and the type of values it produces. There are several variants of IO depending on the needs of our program: | Variant | Description | | -------------- | ----------- | | IO&lt;E, A&gt; | An encapsulated side effect producing values of type `A` and errors of type `E` | | UIO&lt;A&gt; | An encapsulated side effect producing values of type `A` that will never fail | | Task&lt;A&gt; | An encapsulated side effect producing values of type `A` and no explicit error type (using `Error`) | Besides, if we want to model side effects depending on a context of type `D`, we can use the `EnvIO<D, E, A>` type, or any of its variants: | Variant | Description | | -------------------- | ----------- | | EnvIO&lt;D, E, A&gt; | A side effect depending on context `D` that produces values of type `A` and errors of type `E` | | URIO&lt;D, A&gt; | A side effect depending on context `D` that produces values of type `A` and will never fail | | RIO&lt;D, A&gt; | A side effect depending on context `D` that produces values of type `A` and no explicit error type (using `Error`) | ## Utilities Besides the IO data types, the Effects module provides some utilities: | Data type | Description | | --------- | ----------- | | Atomic&lt;A&gt; | An atomically modifiable reference to a value | | Ref&lt;F, A&gt; | An asynchronous, concurrent mutable reference providing safe functional access and modification of its content | | Resource&lt;F, A&gt; | A resource that provides safe allocation, usage and release | */
// // ChangeAuthUserController.swift // MsdGateLock // // Created by ox o on 2017/6/30. // Copyright © 2017年 xiaoxiao. All rights reserved. // import UIKit class ChangeAuthUserController: UITableViewController { @IBOutlet weak var setVailTip: UILabel! @IBOutlet weak var starTip: UILabel! @IBOutlet weak var endTip: UILabel! @IBOutlet weak var isLongSwitch: UISwitch! @IBOutlet weak var starTimeLabel: UILabel! @IBOutlet weak var endTimeLabel: UILabel! var oneSectionCount : Int = 1 override func viewDidLoad() { super.viewDidLoad() self.title = "设置时效" setupUI() } } extension ChangeAuthUserController{ func setupUI(){ navigationItem.rightBarButtonItem = UIBarButtonItem(title: "确认", style: .plain, target: self, action: #selector(ChangeAuthUserController.affirmClick)) setVailTip.textColor = UIColor.textBlackColor isLongSwitch.onTintColor = UIColor.textBlueColor starTip.textColor = UIColor.textBlackColor endTip.textColor = UIColor.textBlackColor starTimeLabel.textColor = UIColor.textGrayColor endTimeLabel.textColor = UIColor.textGrayColor isLongSwitch.addTarget(self, action: #selector(AddAuthorizaMemberController.seletedTimeClick(perpSwitch:)), for: .valueChanged) } } extension ChangeAuthUserController{ @objc func affirmClick(){ QPCLog("确认") navigationController?.popViewController(animated: true) } func seletedTimeClick(perpSwitch : UISwitch){ if perpSwitch.isOn { oneSectionCount = 1 self.tableView .reloadData() }else{ oneSectionCount = 3 self.tableView.reloadData() } } func seletedTimeClick(str : String){ let datepicker = WSDatePickerView.init(dateStyle: DateStyleShowYearMonthDayHourMinute) { [weak self](selectDate) in guard let weakSelf = self else {return} let dateStr = selectDate?.string_from(formatter: "yyyy-MM-dd HH:mm") QPCLog("选择的日期:\(String(describing: dateStr))") if str == "开始时间" { weakSelf.starTimeLabel.text = dateStr }else if str == "结束时间"{ weakSelf.endTimeLabel.text = dateStr } } datepicker?.dateLabelColor = UIColor.textBlueColor datepicker?.datePickerColor = UIColor.textBlackColor datepicker?.doneButtonColor = UIColor.textBlueColor datepicker?.show() // // // self.datePick.sucessReturnB = { returnValue in // // debugPrint("我要消失了哈哈哈哈哈哈\(returnValue)") // if str == "开始时间" { // weakSelf!.starTimeLabel.text = returnValue // }else if str == "结束时间"{ // weakSelf!.endTimeLabel.text = returnValue // } // weakSelf!.datePick.removeFromSuperview() // // } // //需要初始化数据 // datePick.initData() // datePick.frame = CGRect(x: 0, y: kScreenHeight - 314, width: kScreenWidth, height: 250) // self.view.addSubview(datePick) } } extension ChangeAuthUserController{ override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 28 } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.001 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let timeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 28)) timeLabel.font = UIFont.systemFont(ofSize: 12.0) timeLabel.textAlignment = .natural timeLabel.text = " 转换权限前,请为该成员设置开门权限有效期" timeLabel.textColor = UIColor.textGrayColor return timeLabel } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return oneSectionCount } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == 1 { seletedTimeClick(str: "开始时间") }else if indexPath.row == 2 { seletedTimeClick(str: "结束时间") } } }
// // DishModel.swift // UBIEAT // // Created by UBIELIFE on 2016-08-28. // Copyright © 2016 UBIELIFE Inc. All rights reserved. // /* 该类用来表示一道菜, 包含的变量应该有 @params 1. 菜名 2. 单价 3. 是否是主菜 (否则为配菜) 4. 是否有配菜 (配菜是没有配菜的) 5. 配菜列表 */ class DishModel: NSObject , NSCoding { var DishID: Int var dishName: String! var pricePerUnit: Double! var accessoryDishList: [AccessoryDish]! var accessoryIDList: [Int]! // indicate the index of the group, which this dish belong to, in the group table var groupIndex: Int = 0 var count:Int = 0{ didSet{ print("kf") } } // 已经选择好的 配菜 id var selectedAcceStr: String = "" // 该菜属于哪一类 var sortID: Int! // 已经选择的配菜 var selectedAccessories:[Int] = [Int]() init(copyFrom dish: DishModel) { self.DishID = dish.DishID self.accessoryDishList = dish.accessoryDishList self.accessoryIDList = dish.accessoryIDList self.dishName = dish.dishName self.sortID = dish.sortID self.pricePerUnit = dish.pricePerUnit } init(data: Dictionary<String , AnyObject>) { self.DishID = (data["foodid"] as! NSNumber).integerValue self.accessoryDishList = [AccessoryDish]() self.dishName = data["name"] as! String self.sortID = (data["foodtype"] as! NSNumber).integerValue self.pricePerUnit = data["price"] as! Double let accessoryStr = data["accessory"] as! String self.accessoryIDList = [Int]() if accessoryStr == ""{ // 没有配菜 } else{ let list = accessoryStr.componentsSeparatedByString(",") for index in list { self.accessoryIDList.append(Int(index)!) } } } func hasAccessoryOrNot() -> Bool{ if self.accessoryDishList.count == 0 { return false } return true } // 获取 对于已选择配菜的描述 func getAccessoryDescription()-> String{ let splits = self.selectedAcceStr.componentsSeparatedByString(",") var size = [String]() var addons = [String]() for element in splits { let id = Int(element) for access in self.accessoryDishList { if access.ID == id && access.addOnType == 0{ size.append(access.name) break } else if access.ID == id && access.addOnType == 1{ addons.append(access.name) break } } } return size.joinWithSeparator(",") + "," + addons.joinWithSeparator(",") } // MARK NSCoding methods func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.sortID, forKey: "sortID") aCoder.encodeObject(self.DishID, forKey: "DishID") aCoder.encodeObject(self.dishName, forKey: "dishName") aCoder.encodeObject(self.count, forKey: "count") aCoder.encodeObject(self.pricePerUnit, forKey: "pricePerUnit") aCoder.encodeObject(self.accessoryDishList, forKey: "accessoryDishList") aCoder.encodeObject(self.accessoryIDList, forKey: "accessoryIDList") aCoder.encodeObject(self.selectedAccessories, forKey: "selectedAccessories") aCoder.encodeObject(self.selectedAcceStr, forKey: "selectedAcceStr") } required init?(coder aDecoder: NSCoder) { self.DishID = (aDecoder.decodeObjectForKey("DishID") as! NSNumber).integerValue self.sortID = (aDecoder.decodeObjectForKey("sortID") as! NSNumber).integerValue self.count = (aDecoder.decodeObjectForKey("count") as! NSNumber).integerValue self.dishName = aDecoder.decodeObjectForKey("dishName") as! String self.pricePerUnit = aDecoder.decodeObjectForKey("pricePerUnit") as! Double self.accessoryDishList = aDecoder.decodeObjectForKey("accessoryDishList") as! [AccessoryDish] self.accessoryIDList = aDecoder.decodeObjectForKey("accessoryIDList") as! [Int] self.selectedAccessories = aDecoder.decodeObjectForKey("selectedAccessories") as! [Int] self.selectedAcceStr = aDecoder.decodeObjectForKey("selectedAcceStr") as! String } }
// // Resistor6Controller.swift // ResistorCodeCalculator // // Created by Five Admin on 6/21/19. // Copyright © 2019 Five Admin. All rights reserved. // import UIKit class Resistor6Controller: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UITabBarControllerDelegate { @IBOutlet weak var collectionViewColors6: UICollectionView! @IBOutlet weak var labelType6: UILabel! @IBOutlet weak var labelCalculation6: UILabel! @IBOutlet weak var imageView6: UIImageView! @IBAction func saveToFavs6(_ sender: Any) { UIView.animate(withDuration: 0.25, delay: 0.0, animations: { self.buttonSave6.transform = CGAffineTransform(scaleX: 0.85, y: 0.85) }) { _ in } UIView.animate(withDuration: 0.5, delay: 0.25, animations: { self.buttonSave6.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) }) { _ in } let value: String = labelCalculation6.text! let color1: UIColor = colorBand61.backgroundColor! let color2: UIColor = colorBand62.backgroundColor! let color3: UIColor = colorBand63.backgroundColor! let color4: UIColor = colorBand64.backgroundColor! let color5: UIColor = colorBand65.backgroundColor! let color6: UIColor = colorBand66.backgroundColor! CDManager().createData(value: value, color1: color1, color2: color2, color3: color3, color4: color4, color5: color5, color6: color6) } @IBOutlet weak var buttonSave6: UIButton! @IBOutlet weak var colorBand61: UIView! @IBOutlet weak var colorBand62: UIView! @IBOutlet weak var colorBand63: UIView! @IBOutlet weak var colorBand64: UIView! @IBOutlet weak var colorBand65: UIView! @IBOutlet weak var colorBand66: UIView! var items: Array<Double> = [] var digitBand: Array<Double> = [] var multiplierBand: Array<Double> = [] var toleranceBand: Array<Double> = [] var tempCoefBand: Array<Double> = [] var colors: Array<UIColor> = [] var currentSelection: Array<Double> = [0,0,0,0,0,0] var colorBandViews: Array<UIView> = [] var selectedTab: Int = 0 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.items.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "uiCollectionViewCell", for: indexPath as IndexPath) as! uiCollectionViewCell let dividedBySix = indexPath.row / 6 if items[indexPath.row] == -1 { cell.backgroundColor = Color.WHITE.color cell.labelColorCell.text="" cell.alpha = 0.0 } else{ cell.backgroundColor = colors[Int(indexPath.row / 6)] cell.labelColorCell.text = String(items[indexPath.row]) cell.labelColorCell.textColor = Color.BLACK.color if (dividedBySix == 0 || dividedBySix == 10){ cell.labelColorCell.textColor = Color.WHITE.color } } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let selectedFeature: Int = indexPath.row % 6 currentSelection[selectedFeature] = Double(items[indexPath.row]) let selectedBandView: UIView = colorBandViews[selectedFeature] selectedBandView.backgroundColor = colors[Int(indexPath.row / 6)] var value: Double = currentSelection[0]*100+currentSelection[1]*10+currentSelection[2] if selectedTab == 2{ //ako ima samo 4 trake value = currentSelection[0]*10+currentSelection[1] } value = (value*currentSelection[3]) let tolerance: Double = currentSelection[4] let tempCoef: Double = currentSelection[5] //print("You selected cell #\(indexPath.item)!") let display:String = String(format:"%.2f",value) + "Ω ± " + String(tolerance) + "%\n" + String(tempCoef) + "ppm" self.labelCalculation6.text = display //self.collectionViewColors6.reloadData() } func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) { let tabBarIndex = tabBarController.selectedIndex selectedTab = tabBarIndex print(tabBarIndex) //self.collectionViewColors6.reloadData() } func setupCollection(){ digitBand = [0,1,2,3,4,5,6,7,8,9, -1, -1] multiplierBand = [ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, -1, -1, 0.01, 0.1] toleranceBand = [-1, 1, 2, -1, -1, 0.5, 0.25, 0.1, 0.05, -1, 10, 5] tempCoefBand = [ -1, 100, 50, 15, 25, -1, -1, -1, -1, -1, -1, -1] colors = [Color.BLACK.color, Color.BROWN.color , Color.RED.color, Color.ORANGE.color, Color.YELLOW.color , Color.GREEN.color, Color.BLUE.color, Color.PURPLE.color, Color.GREY.color, Color.WHITE.color, Color.SILVER.color, Color.GOLD.color] let listOfBands = [digitBand, digitBand, digitBand, multiplierBand, toleranceBand, tempCoefBand] colorBandViews = [colorBand61, colorBand62, colorBand63, colorBand64, colorBand65, colorBand66] for i in 0...11{ for j in 0...5{ let elem: Double = (listOfBands[j])[i] items.append(elem) } } } override func viewDidLoad() { super.viewDidLoad() let columnLayout = FlowLayoutCollection( cellsPerRow: 6, minimumInteritemSpacing: 5, minimumLineSpacing: 5, sectionInset: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) ) self.collectionViewColors6?.collectionViewLayout = columnLayout setupCollection() self.collectionViewColors6.register(UINib(nibName: "uiCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "uiCollectionViewCell") self.tabBarController?.delegate = self self.collectionViewColors6.delegate = self self.collectionViewColors6.dataSource = self } }
// // FoundService.swift // Pawie // // Created by Yu Ming Lin on 8/30/21. // import Firebase import UIKit struct FoundCredentials { let species: String let petName: String let breed: String let area: String let description: String let phone: String let email: String let ownerName: String let petImage: UIImage let time: Timestamp } struct FoundService { static func uploadFounds(withCredentials credentials: FoundCredentials, completion: @escaping(Error?)-> Void) { ImageUploader.uploadImage(image: credentials.petImage) { imageURL in let data: [String: Any] = ["petName" : credentials.petName, "breed": credentials.breed, "area": credentials.area, "ownername": credentials.ownerName, "petImageURL": imageURL, "description": credentials.description, "phone": credentials.phone, "email": credentials.email, "time": credentials.time, "species": credentials.species, ] COLLECTION_FOUND.addDocument(data: data, completion: completion) } } static func fetchFounds(completion: @escaping([Found]) -> Void) { COLLECTION_FOUND.order(by: "time", descending: true).getDocuments { (snapshot, error) in guard let snapshot = snapshot else {return} let founds = snapshot.documents.map({Found(dictionary: $0.data())}) completion(founds) } } }
// // TriviaProvider.swift // TrueFalseStarter // // Created by nikko444 on 2017-11-25. // Copyright © 2017 Treehouse. All rights reserved. // import GameKit class TriviaProvider { let trivia: [TriviaModel?] = [ TriviaModel(question: "This was the only US President to serve more than two consecutive terms.", answer: "Franklin D. Roosevelt", option1: "George Washington", option2: "Woodrow Wilson"), TriviaModel(question: "Which of the following countries has the most residents?", answer: "Nigeria", option1: "Russia", option2: "Iran", option3: "Vietnam"), TriviaModel(question: "In what year was the United Nations founded?", answer: "1945", option1: "1918", option2: "1919", option3: "1954"), TriviaModel(question: "The Titanic departed from the United Kingdom, where was it supposed to arrive?", answer: "New York City", option1: "Washington D.C.", option2: "Boston", option3: "Paris"), TriviaModel(question: "Which nation produces the most oil?", answer: "Canada", option1: "Iran", option2: "Iraq", option3: "Brazil"), TriviaModel(question: "Which country has most recently won consecutive World Cups in Soccer?", answer: "Brazil", option1: "Italy", option2: "Argetina", option3: "Spain"), TriviaModel(question: "Which of the following rivers is longest?", answer: "Mississippi", option1: "Yangtze", option2: "Congo", option3: "Mekong"), TriviaModel(question: "Which city is the oldest?", answer: "Mexico City", option1: "Cape Town", option2: "San Juan", option3: "Sydney"), TriviaModel(question: "Which country was the first to allow women to vote in national elections?", answer: "Poland", option1: "United States", option2: "Sweden", option3: "Senegal"), TriviaModel(question: "Which of these countries won the most medals in the 2012 Summer Games?", answer: "Great Britian", option1: "France", option2: "Germany", option3: "Japan") ] var usedQuestions: [Int] = [] func randomQuestion () -> Int { if trivia.count == usedQuestions.count { usedQuestions = [] } var indexOfSelectedQuestion: Int var reGenerate: Bool repeat { reGenerate = false indexOfSelectedQuestion = GKRandomSource.sharedRandom().nextInt(upperBound: trivia.count) for check in usedQuestions { if check == indexOfSelectedQuestion { reGenerate = true } } } while reGenerate usedQuestions.append(indexOfSelectedQuestion) return indexOfSelectedQuestion } func provide () -> TriviaModel? { guard let unwrappedTrivia = trivia[randomQuestion()] else { return nil } return unwrappedTrivia } }
// // Register+CoreDataClass.swift // Reminder // // Created by RAHUL GOEL on 10/01/21. // // import Foundation import CoreData @objc(Register) public class Register: NSManagedObject { }
// // MoviesTableViewCellViewModel.swift // TMDBSearch-RestAPI // // Created by Jervy Umandap on 6/24/21. // import Foundation class MovieViewModel { private var popularMovies = [Movie]() func fetchPopularMoviesData(completion: @escaping() -> ()) { APICaller.shared.getPopularMovies(completion: { [weak self] result in switch result { case .success(let data): self?.popularMovies = data.movies completion() case .failure(let error): print("Error proccessing json: - \(error)") } }) } func numberOfRowsInSection(section: Int) -> Int { if popularMovies.count != 0 { return popularMovies.count } return 0 } func cellForRowAt(indexPath: IndexPath) -> Movie { return popularMovies[indexPath.row] } }
// // Seed.swift // Auction // // Created by Raymond Law on 1/25/18. // Copyright © 2018 Clean Swift LLC. All rights reserved. // import Foundation struct Seed { static let users: [[String: Any]] = [ [ "id": "user_alex", "name": "Alex", "email": "alex@gmail.com", "soldItems": [ ["id": "sold_item_apples", "name": "Apples", "quantity": 11, "price": 11.00], ["id": "sold_item_apricots", "name": "Apricots", "quantity": 12, "price": 12.00] ], "boughtItems": [ ["id": "bought_item_asparagus", "name": "Asparagus", "quantity": 111, "price": 111.00], ["id": "bought_item_avocados", "name": "Avocados", "quantity": 112, "price": 112.00] ] ], [ "id": "user_bob", "name": "Bob", "email": "bob@gmail.com", "soldItems": [ ["id": "sold_item_bananas", "name": "Bananas", "quantity": 21, "price": 21.00], ["id": "sold_item_blueberries", "name": "Blueberries", "quantity": 22, "price": 22.00] ], "boughtItems": [] ], [ "id": "user_chloe", "name": "Chloe", "email": "chloe@gmail.com", "soldItems": [], "boughtItems": [ ["id": "bought_item_cherries", "name": "Cherries", "quantity": 311, "price": 311.00], ["id": "bought_item_cantaloupe", "name": "Cantaloupe", "quantity": 312, "price": 312.00] ] ], [ "id": "user_david", "name": "David", "email": "david@gmail.com", "soldItems": [], "boughtItems": [] ] ] }
// // DetailViewController.swift // UploadApp // // Created by Yocelin Garcia Romero on 04/04/21. // import UIKit import Firebase import CoreServices import FirebaseUI protocol CanReceive { func passDataBack(imageRef: StorageReference, currentImage: Int) } class DetailViewController: UIViewController { var imageRef: StorageReference var currentImage: Int let placeholerImage = UIImage(named: "placeholder") let storage = Storage.storage() required init?(coder aDecoder: NSCoder) { let storageRef = storage.reference() self.imageRef = storageRef.child("images/profile/userProfile.png") self.currentImage = 0 super.init(coder: aDecoder) } @IBOutlet weak var detailImage: UIImageView! @IBOutlet weak var imageName: UILabel! @IBOutlet weak var imageDatetime: UILabel! @IBOutlet weak var imageSize: UILabel! @IBOutlet weak var likeCount: UILabel! @IBOutlet weak var likeButton: UIButton! @IBOutlet weak var deleteButton: UIButton! var delegate:CanReceive? override func viewDidLoad() { super.viewDidLoad() setImageValues() // Do any additional setup after loading the view. } func setImageValues(){ let forestRef = imageRef forestRef.getMetadata { metadata, error in if let error = error { print("An error had happended: \(error)") } else { self.detailImage.sd_setImage(with: self.imageRef, placeholderImage: self.placeholerImage) self.imageName.text = "Nombre: \(metadata?.name ?? "")" self.imageDatetime.text = "Fecha: \(metadata?.timeCreated ?? Date())" self.imageSize.text = "Size: \(metadata?.size ?? 0)" } } } @IBAction func likeOrDislike(_ sender: Any) { } @IBAction func deleteImage(_ sender: Any) { imageRef.delete { error in if let error = error { print("An error had happended: \(error)") } else { print("Sucess") } } delegate?.passDataBack(imageRef: imageRef, currentImage: currentImage) dismiss(animated: true, completion: nil) self.navigationController?.popViewController(animated: true) } }
// // FeedItem.swift // NewsTest // // Created by Dmitry Kanivets on 25.06.18. // Copyright © 2018 Dmitry Kanivets. All rights reserved. // import Foundation struct Source { var id: String var name: String var descriptionText: String var url: String var category: String var language: String var country: String } struct Article { var author: String? var title: String var descriptionText: String? var url: String var urlToImage: String? var publishedAt: String var content: String }
// // VCHTimer.swift // SwiftDemo002 // // Created by chenhui on 17/4/2. // Copyright © 2017年 vhuichen. All rights reserved. // import UIKit class VCHTimer: NSObject { var count: Double var timer: Timer init(count: Double, timer: Timer) { self.count = count self.timer = timer } override init() { count = 0 timer = Timer() } }
// MyViewController.swift - Copyright 2022 SwifterSwift #if canImport(UIKit) && !os(watchOS) import UIKit class MyViewController: UIViewController { @IBOutlet var testLabel: UILabel! } #endif
// // VideoFormat.swift // SkyTV // // Copyright © 2018 Mark Bourke. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE // import Foundation struct VideoFormat: Decodable { /// The quality of the video. let quality: Quality /// The id of the video. let id: String /// The channel which is providing the video. let provider: String /// The date on which the video stops being available on-demand. let expiryDate: Date /// The URL to download the video. let downloadUrl: URL /// The video's age rating let certification: String /// The size of the video, in bytes. let size: Int enum CodingKeys: String, CodingKey { case quality = "videotype" case id = "programmeid" case expiryDate = "availendtime" case certification = "r" case downloadUrl = "downloadlink" case size case provider = "providername" } }
// // CustomLayoutCollectionViewCell.swift // pokedex3 // // Created by Richard Rodriguez on 5/4/17. // // import UIKit class CustomLayoutCollectionViewCell: UICollectionViewCell { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) layer.cornerRadius = 5.0 } }
// // ViewController.swift // LSystem01 // // Created by Jeff Holtzkener on 4/4/16. // Copyright © 2016 Jeff Holtzkener. All rights reserved. // import UIKit class ViewController: UIViewController { var arrayOfNode = [Node]() var maxAngle = CGFloat(M_PI) var minAng = CGFloat(0) var rootNode: Node? var nodeViews = [ViewForNode]() var knobs = [Knob]() var nodeTypes:Int { return listofNodeClasses.count } var nodeCount = 0 var listofNodeClasses: [Node.Type] { return Array(Constants.allNodeClasses[0..<Settings.sharedInstance.numOfActiveNodes]) } var settingsButton: UIButton? override func viewDidLoad() { super.viewDidLoad() settingsButton = UIButton() settingsButton?.setImage(UIImage(named: "cogwheel"), forState: .Normal) settingsButton?.addTarget(self, action: #selector(pressedSettings(_:)), forControlEvents: .TouchUpInside) Settings.sharedInstance.setWithNumberedPreset(Int(arc4random_uniform(UInt32(5)))) } override func viewWillAppear(animated: Bool) { navigationController?.navigationBarHidden = true setUp() } override func viewWillLayoutSubviews() { setUp() } override func prefersStatusBarHidden() -> Bool { return true } func setUp() { createAndAssignNodeViews() makeInitialNode() makeKnobs() nodeCount = 0 for gen in 0..<50{ print("generation \(gen)") if arrayOfNode.count == 0 { break } if nodeCount < Settings.sharedInstance.maxNumberOfNodes && arrayOfNode[0].segmentLength > 0.5 { regenerate() } } view.gestureRecognizers?.removeAll() let pinch = UIPinchGestureRecognizer(target: self, action: #selector(pinched(_:))) view.addGestureRecognizer(pinch) let pan = UIPanGestureRecognizer(target: self, action: #selector(ViewController.panned(_:))) view.addGestureRecognizer(pan) placeSettingsButton() } func pinched(gesture: UIPinchGestureRecognizer) { // change magnification by changing original segment length let scale: CGFloat = gesture.scale; rootNode?.segmentLength *= scale for view in nodeViews { view.clearPaths() } rootNode?.recursiveChangeLength() for view in nodeViews { view.setNeedsDisplay() } gesture.scale = 1 } func panned(gesture: UIPanGestureRecognizer) { let trans = gesture.translationInView(view) for view in nodeViews { view.clearPaths() } rootNode?.rootLocation!.x += trans.x rootNode?.rootLocation!.y += trans.y rootNode?.recursiveReposition() for view in nodeViews { view.setNeedsDisplay() } gesture.setTranslation(CGPoint.zero, inView: view) } func makeInitialNode() { arrayOfNode = [Node]() let rootLocation = CGPoint(x: view.bounds.width / 2, y: view.bounds.height / 2) print("MAKE INITIAL \(Settings.sharedInstance.startingNode)") let rootInit = Settings.initDict[Settings.sharedInstance.startingNode]! rootNode = rootInit(segmentLength: getInitialSegmentLength(), parent: nil, rootLocation: rootLocation) print(rootNode) if let rootNode = rootNode { arrayOfNode.append(rootNode) print("size \(arrayOfNode.count)") } else { print("couldn't unwrap rootNode") } } func getInitialSegmentLength() -> CGFloat { // use value from settings modified by screen size let initial = Settings.sharedInstance.initialLengthRatio let smallScreenDimension = view.bounds.width < view.bounds.height ? view.bounds.width : view.bounds.height print(smallScreenDimension) return initial * (smallScreenDimension / 180) } func regenerate() { var newArrayOfNodes = [Node]() for (i,_) in arrayOfNode.enumerate() { let spawn = arrayOfNode[i].spawn() for newNode in spawn { newArrayOfNodes.append(newNode) nodeCount += 1 } if nodeCount > Settings.sharedInstance.maxNumberOfNodes + 1000 { break } } arrayOfNode = newArrayOfNodes print("end: arrayOfNode size: \(arrayOfNode.count)") } func createAndAssignNodeViews() { if nodeViews.count > 0 { for nodeView in nodeViews { nodeView.removeFromSuperview() } } nodeViews = [ViewForNode]() for i in 0..<nodeTypes { let nodeView = ViewForNode(frame: view.bounds) nodeViews.append(nodeView) nodeView.backgroundColor = UIColor.clearColor() view.addSubview(nodeView) nodeView.fillColor = Constants.nodeColors[i].colorWithAlphaComponent(0.4) listofNodeClasses[i].view = nodeView } } func makeKnobs() { var maxKnob = CGFloat(130) > view.bounds.width / 5 ? view.bounds.width / 5 : CGFloat(130) let minKnob: CGFloat = 65 if maxKnob > view.bounds.height / 4 { maxKnob = view.bounds.height / 4 } print("maxKnob: \(maxKnob)") var width = view.bounds.width / CGFloat(2 * nodeTypes - 1 ) var buffer:CGFloat = 0 var spacerWidth = width if width > maxKnob { width = maxKnob spacerWidth = maxKnob buffer = (view.bounds.width - maxKnob * CGFloat((2 * nodeTypes - 1))) / 2 } else if width < minKnob { width = minKnob buffer = 5 spacerWidth = (view.bounds.width - CGFloat(nodeTypes) * width - buffer * 2) / CGFloat(nodeTypes - 1) } if knobs.count > 0 { for knob in knobs { knob.removeFromSuperview() } knobs = [Knob]() } var offset: CGFloat = buffer for i in 0..<(2 * nodeTypes - 1) { if i % 2 == 0 { let π = Float(M_PI) let rect = CGRect(x: offset, y: view.bounds.height - (width + 10), width: width, height: width) let knob = Knob(frame: rect) offset += width knob.continuous = true knob.minimumValue = -2 * π knob.pointerLength = 10.0 knob.maximumValue = 0 knob.lineWidth = 5.0 knob.tintColor = Constants.nodeColors[i/2].colorWithAlphaComponent(0.4) knob.addTarget(self, action: #selector(ViewController.knobPositionChanged(_:)), forControlEvents: .ValueChanged) knobs.append(knob) view.addSubview(knob) } else { offset += spacerWidth } } view.setNeedsDisplay() } func knobPositionChanged(sender: Knob) { listofNodeClasses[knobs.indexOf(sender)!].angle = CGFloat(sender.value) for view in nodeViews { view.clearPaths() } rootNode?.recursiveReposition() for view in nodeViews { view.setNeedsDisplay() } } func placeSettingsButton() { let size: CGFloat = 44 let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.height let rect = CGRect(x: view.bounds.width - size - 5, y: statusBarHeight + 5, width: size, height: size) settingsButton?.removeFromSuperview() settingsButton?.frame = rect nodeViews.last?.addSubview(settingsButton!) } func pressedSettings(sender: AnyObject?) { print("pressed") performSegueWithIdentifier("toSettings", sender: self) } }
// // ViewController.swift // testPanelBottom // // Created by asdfgh1 on 09/02/16. // Copyright © 2016 rshev. All rights reserved. // import UIKit class ViewController: UIViewController { var panelModel = SomeModel() // for demo purposes, should be given from outside @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var panelView: UIView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var summaryLabel: UILabel! @IBOutlet weak var longTextLabel: UILabel! @IBOutlet weak var panelViewTopConstraint: NSLayoutConstraint! lazy var panGestureRecognizer: UIPanGestureRecognizer = { let gr = UIPanGestureRecognizer(target: self, action: "panGesture:") self.panelView.addGestureRecognizer(gr) return gr }() override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() collectionView.collectionViewLayout.invalidateLayout() // to refresh cell size on device rotation let currentPage = collectionView.contentOffset.x / collectionView.bounds.width NSOperationQueue.mainQueue().addOperationWithBlock { self.collectionView.setContentOffset(CGPoint(x: currentPage * self.collectionView.bounds.width, y: 0), animated: false) } } override func viewDidLoad() { super.viewDidLoad() _ = panGestureRecognizer // lazily init originalPanelPosition = panelViewTopConstraint.constant originalPanelAlpha = panelView.alpha } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.nameLabel.text = panelModel.getName() self.summaryLabel.text = panelModel.getTextSummary() self.longTextLabel.text = panelModel.getTextLong() } var originalPanelAlpha: CGFloat = 0 var originalPanelPosition: CGFloat = 0 var lastPoint: CGPoint = CGPointZero func setViewAlphas(centerRatio centerRatio: CGFloat) { panelView.alpha = originalPanelAlpha + (centerRatio * (1.0 - originalPanelAlpha)) let howFarFromCenterRatio = 0.5 - centerRatio summaryLabel.alpha = howFarFromCenterRatio * 2 longTextLabel.alpha = -howFarFromCenterRatio * 2 } func panGesture(gestureRecognizer: UIPanGestureRecognizer) { let point = gestureRecognizer.locationInView(self.view) let screenHeight = collectionView.bounds.height let centerRatio = (-panelViewTopConstraint.constant + originalPanelPosition) / (screenHeight + originalPanelPosition) switch gestureRecognizer.state { case .Changed: let yDelta = point.y - lastPoint.y var newConstant = panelViewTopConstraint.constant + yDelta newConstant = newConstant > originalPanelPosition ? originalPanelPosition : newConstant newConstant = newConstant < -screenHeight ? -screenHeight : newConstant panelViewTopConstraint.constant = newConstant setViewAlphas(centerRatio: centerRatio) case .Ended: self.panelViewTopConstraint.constant = centerRatio < 0.5 ? self.originalPanelPosition : -screenHeight UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: [.CurveEaseInOut], animations: { self.view.layoutIfNeeded() self.setViewAlphas(centerRatio: centerRatio < 0.5 ? 0.0 : 1.0) }, completion: nil) default: break } lastPoint = point } } extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return panelModel.getImages().count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("image", forIndexPath: indexPath) as! ImageCollectionViewCell if let img = panelModel.getImages()[indexPath.item] { cell.imageView.image = img } return cell } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return collectionView.bounds.size } }