text
stringlengths
8
1.32M
// // Suit.swift // Poker Simulator // // Created by Edward Huang on 10/15/17. // Copyright © 2017 Eddie Huang. All rights reserved. // import Foundation enum Suit: Int { case clubs = 0, diamonds, hearts, spades }
// // UIViewController+Extensions.swift // StarWarsMovies // // Created by José Naves Moura Neto on 27/05/19. // Copyright © 2019 José Naves Moura Neto. All rights reserved. // import UIKit extension UIViewController { func showAlertMessage(message: String) { DispatchQueue.main.async { let alertController = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertController.Style.alert) let alertAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil) alertController.addAction(alertAction) self.present(alertController, animated: true, completion: nil) } } func showSpinner(onView : UIView) { let spinnerView = UIView.init(frame: onView.bounds) spinnerView.backgroundColor = UIColor.init(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.5) let ai = UIActivityIndicatorView.init(style: .whiteLarge) ai.startAnimating() ai.center = spinnerView.center DispatchQueue.main.async { spinnerView.addSubview(ai) onView.addSubview(spinnerView) } vSpinner = spinnerView } func removeSpinner() { DispatchQueue.main.async { vSpinner?.removeFromSuperview() vSpinner = nil } } }
// // ViewController.swift // Positive News App // // Created by Harsh Khajuria on 10/05/19. // Copyright © 2019 horcrux2301. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var mainImage: UIImageView! @objc func switchScreen(){ let uid = UserDefaults.standard.object(forKey: "uid") if uid != nil{ DispatchQueue.main.async { self.performSegue(withIdentifier: "showCollection", sender: self) } } else { DispatchQueue.main.async { self.performSegue(withIdentifier: "showLogin", sender: self) } } } override func viewDidLoad() { super.viewDidLoad() let image = UIImage(named: "mainBackground1") mainImage.image = image print("loaded") // UserDefaults.standard.removeObject(forKey: "uid") _ = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(switchScreen), userInfo: nil, repeats: false) // Do any additional setup after loading the view. } // override func viewDidAppear(_ animated: Bool) { // print("appeared") // // } }
import UIKit import XCTest class Bug { enum State { case open case closed } let state: State let timestamp: Date let comment: String init(state: State, timestamp: Date, comment: String) { // To be implemented //initialize class constant variable self.state = state self.timestamp = timestamp self.comment = comment } init(jsonString: String) throws { // To be implemented //extract json into dictionary let json = jsonString.data(using: .utf8) let dictionary = try JSONSerialization.jsonObject(with: json!, options: []) as? [String : AnyObject] let stateString = (dictionary?["state"] as? String)! if stateString == "open" { self.state = State.open } else { self.state = State.closed } self.timestamp = Date(timeIntervalSince1970: TimeInterval((dictionary?["timestamp"])! as! NSNumber)) self.comment = dictionary?["comment"] as! String } } enum TimeRange { case pastDay case pastWeek case pastMonth } class Application { var bugs: [Bug] init(bugs: [Bug]) { self.bugs = bugs } func findBugs(state: Bug.State?, timeRange: TimeRange) -> [Bug]{ var packOfBugs = [Bug]() //array of bugs let date = Date() let pastDay = date.addingTimeInterval(-1*(60*60*24)) //estimate date in pastday let pastWeek = date.addingTimeInterval(-1*(60*60*24*7)) //estimate date in pastweek let pastMonth = date.addingTimeInterval(-1*(60*60*24*30)) //estimate date in pastmonth for findBug in bugs{ if findBug.state == state{ //check state opened or closed if findBug.timestamp <= pastDay {packOfBugs.append(findBug)} if findBug.timestamp <= pastWeek {packOfBugs.append(findBug)} if findBug.timestamp <= pastMonth {packOfBugs.append(findBug)} } } return packOfBugs } } class UnitTests : XCTestCase { lazy var bugs: [Bug] = { var date26HoursAgo = Date() date26HoursAgo.addTimeInterval(-1 * (26 * 60 * 60)) var date2WeeksAgo = Date() date2WeeksAgo.addTimeInterval(-1 * (14 * 24 * 60 * 60)) let bug1 = Bug(state: .open, timestamp: Date(), comment: "Bug 1") let bug2 = Bug(state: .open, timestamp: date26HoursAgo, comment: "Bug 2") let bug3 = Bug(state: .closed, timestamp: date2WeeksAgo, comment: "Bug 2") return [bug1, bug2, bug3] }() lazy var application: Application = { let application = Application(bugs: self.bugs) return application }() func testFindOpenBugsInThePastDay() { let bugs = application.findBugs(state: .open, timeRange: .pastDay) XCTAssertTrue(bugs.count == 1, "Invalid number of bugs") XCTAssertEqual(bugs[0].comment, "Bug 1", "Invalid bug order") } func testFindClosedBugsInThePastMonth() { let bugs = application.findBugs(state: .closed, timeRange: .pastMonth) XCTAssertTrue(bugs.count == 1, "Invalid number of bugs") } func testFindClosedBugsInThePastWeek() { let bugs = application.findBugs(state: .closed, timeRange: .pastWeek) XCTAssertTrue(bugs.count == 0, "Invalid number of bugs") } func testInitializeBugWithJSON() { do { let json = "{\"state\": \"open\",\"timestamp\": 1493393946,\"comment\": \"Bug via JSON\"}" let bug = try Bug(jsonString: json) XCTAssertEqual(bug.comment, "Bug via JSON") XCTAssertEqual(bug.state, .open) XCTAssertEqual(bug.timestamp, Date(timeIntervalSince1970: 1493393946)) } catch { print(error) } } } class PlaygroundTestObserver : NSObject, XCTestObservation { @objc func testCase(_ testCase: XCTestCase, didFailWithDescription description: String, inFile filePath: String?, atLine lineNumber: UInt) { print("Test failed on line \(lineNumber): \(String(describing: testCase.name)), \(description)") } } let observer = PlaygroundTestObserver() let center = XCTestObservationCenter.shared() center.addTestObserver(observer) TestRunner().runTests(testClass: UnitTests.self)
// // RWQuoteTableViewCell.swift // DogmaDebate // // Created by Rondale Williams on 5/26/16. // Copyright © 2016 RondaleWilliams. All rights reserved. // import UIKit class RWQuoteTableViewCell: UITableViewCell { @IBOutlet weak var quoteLabel: UILabel! }
// // MyRoomDetailViewController.swift // test1 // // Created by 김환석 on 2020/11/17. // Copyright © 2020 김환석. All rights reserved. // import UIKit import Alamofire class MyRoomDetailViewController: UIViewController, UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate { @IBOutlet var collectionView: UICollectionView! @IBOutlet var pageControlMyMeetingImage: UIPageControl! @IBOutlet var lblTitle: UILabel! @IBOutlet var lblLocation1: UILabel! @IBOutlet var lblLocation2: UILabel! @IBOutlet var lblAge: UILabel! @IBOutlet var lblTotal: UILabel! @IBOutlet var lbldate: UILabel! @IBOutlet var lblTag: UILabel! var images:[String] = [] var boardIdx:Int? var gradientLayer: CAGradientLayer! override func viewDidLoad() { super.viewDidLoad() self.pageControlMyMeetingImage.currentPage = 0 // Do any additional setup after loading the view. //backGround Color let backGroundColor = MyBackGroundColor() self.gradientLayer = CAGradientLayer() self.gradientLayer.frame = self.view.bounds self.gradientLayer.startPoint = CGPoint(x: 0, y: 0) self.gradientLayer.endPoint = CGPoint(x: 1, y: 1) self.gradientLayer.colors = [UIColor(red: backGroundColor.startColorRed, green: backGroundColor.startColorGreen, blue: backGroundColor.startColorBlue , alpha: 1).cgColor, UIColor(red: backGroundColor.endColorRed , green: backGroundColor.endColorGreen, blue: backGroundColor.endColorBlue, alpha: 1).cgColor] self.view.layer.insertSublayer(self.gradientLayer, at: 0) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) let url = Config.baseURL + "/api/boards/\(self.boardIdx!)/\(Config.userIdx!)" AF.request(url, method: .get, encoding: URLEncoding.default, headers: ["Content-Type":"application/json"]).validate(statusCode: 200 ..< 300) .responseJSON(){ response in switch response.result{ case .success(let json): do { let data = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) let jsonParsing = try JSONDecoder().decode(DetailBoardParsing.self, from: data) self.lblTitle.text = jsonParsing.title self.lblLocation1.text = jsonParsing.location1 self.lblLocation2.text = jsonParsing.location2 self.lblAge.text = "\(jsonParsing.age) 세" self.lblTotal.text = jsonParsing.numType self.lbldate.text = jsonParsing.date self.lblTag.text = "#" + jsonParsing.tag1 + "#" + jsonParsing.tag2 + "#" + jsonParsing.tag3 //cell image info save self.images.append(jsonParsing.img1) self.images.append(jsonParsing.img2) self.images.append(jsonParsing.img3) self.collectionView.reloadData() self.pageControlMyMeetingImage.numberOfPages = self.images.count }catch let jsonError{ print("Error seriallizing json:",jsonError) } case .failure(let error): print("error: \(String(describing: error))") } } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width) pageControlMyMeetingImage.currentPage = Int(pageNumber) } //셀의 갯수 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.images.count } //셀 커스텀 수행 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyRoomDetailCustomCell", for: indexPath) as! MyRoomDetailCustomCell let url = URL(string: self.images[indexPath.row]) do{ let data = try Data(contentsOf: url!) cell.imgMyMeetingImage.image = UIImage(data: data) } catch{ cell.imgMyMeetingImage.image = nil } //cell 테두리 cell.layer.borderColor = UIColor.gray.cgColor cell.layer.borderWidth = 0 cell.layer.cornerRadius = 10 return cell } //행당 1개씩 셀 출력을 위해서 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let width1 = collectionView.frame.size.width let height = collectionView.frame.size.height return CGSize(width: width1, height: height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } @IBAction func btnBack(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } @IBAction func btnRoomRemove(_ sender: UIButton) { let alert = UIAlertController(title: "확인", message: "방을 삭제 하시겠습니까?", preferredStyle: .alert) let actionRemove = UIAlertAction(title: "삭제", style: .destructive, handler: { action in let url = Config.baseURL + "/api/boards" + "/\(self.boardIdx!)" AF.request(url, method: .delete, encoding: URLEncoding.default, headers: ["Content-Type":"application/json"]).validate(statusCode: 200 ..< 300).responseJSON(){response in switch response.result{ case .success(let json): do{ let data = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) let jsonParsing = try JSONDecoder().decode(CodeAndMsg.self, from: data) if(jsonParsing.code == 200){ let alertSuccess = UIAlertController(title: "알림", message: "삭제를 완료하였습니다", preferredStyle: .alert) let actionOK = UIAlertAction(title: "확인", style: .default, handler: {action in self.dismiss(animated: true, completion: nil) }) alertSuccess.addAction(actionOK) self.present(alertSuccess, animated: true, completion: nil) } }catch let jsonError{ print("Error seriallizing json:",jsonError) } case .failure(let error): print("error: \(String(describing: error))") } } }) let actionCancle = UIAlertAction(title: "아니요", style: .cancel, handler: nil) alert.addAction(actionRemove) alert.addAction(actionCancle) self.present(alert, animated: true, completion: nil) } func myAlert(_ title: String, message: String){ let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let action = UIAlertAction(title: "확인", style: UIAlertAction.Style.default, handler: nil) alert.addAction(action) self.present(alert, animated: true, completion: nil) } /* // 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. } */ } class MyRoomDetailCustomCell:UICollectionViewCell{ @IBOutlet var imgMyMeetingImage: UIImageView! }
import UIKit var greeting = "Hello, playground" var LastName:String = "Alhammad" print(LastName)
// // TransactionCardOrderCell.swift // WavesWallet-iOS // // Created by rprokofev on 29/03/2019. // Copyright © 2019 Waves Platform. All rights reserved. // import Foundation import UIKit import Extensions final class TransactionCardOrderCell: UITableViewCell, Reusable { struct Model { let amount: BalanceLabel.Model let price: BalanceLabel.Model let total: BalanceLabel.Model } @IBOutlet private var amountTitleLabel: UILabel! @IBOutlet private var amountBalanceLabel: BalanceLabel! @IBOutlet private var priceTitleLabel: UILabel! @IBOutlet private var priceBalanceLabel: BalanceLabel! @IBOutlet private var totalTitleLabel: UILabel! @IBOutlet private var totalBalanceLabel: BalanceLabel! override func awakeFromNib() { super.awakeFromNib() } override func layoutSubviews() { super.layoutSubviews() separatorInset = .init(top: 0, left: bounds.width, bottom: 0, right: 0) } } // MARK: ViewConfiguration extension TransactionCardOrderCell: ViewConfiguration { func update(with model: TransactionCardOrderCell.Model) { amountTitleLabel.text = Localizable.Waves.Transactioncard.Title.amount amountBalanceLabel.update(with: model.amount) priceTitleLabel.text = Localizable.Waves.Transactioncard.Title.price priceBalanceLabel.update(with: model.price) totalTitleLabel.text = Localizable.Waves.Transactioncard.Title.total totalBalanceLabel.update(with: model.total) } }
// // LocalFileAirport.swift // Zeus // // Created by Lahari Ganti on 8/3/19. // Copyright © 2019 Lahari Ganti. All rights reserved. // import Foundation import SuggestionRow struct LocalFileAirport: Codable { let iata: String? let name: String? } extension LocalFileAirport: SuggestionValue { var suggestionString: String { if let name = name { return "\(name)" } return "" } init?(string stringValue: String) { return nil } }
// RUN: %target-swift-frontend -O -primary-file %s -disable-availability-checking -emit-ir | %FileCheck %s // CHECK: define{{( dllexport)?}}{{( protected)?}} i32 @main{{.*}} { // CHECK: store ptr %{{[0-9]+}}, ptr @"$s13rdar1140137091xQrvp" actor Actor {} let x: some Actor = Actor()
// // DataSource.swift // LightPlanPhilips // // Created by Mark Aptroot on 10-11-16. // Copyright © 2016 The App Academy. All rights reserved. // import UIKit class DataSource: NSObject { static let sharedInstance = DataSource() private override init() {} var myHome: Home = Home() func createData() { // create some bulbs and add to home (unassigned bulbs) myHome.unassignedBulbs.append(Bulb(name: "E27", image: UIImage(named: "E27")!)) myHome.unassignedBulbs.append(Bulb(name: "E27", image: UIImage(named: "E27")!)) myHome.unassignedBulbs.append(Bulb(name: "E27", image: UIImage(named: "E27")!)) myHome.unassignedBulbs.append(Bulb(name: "GO", image: UIImage(named: "GO")!)) myHome.unassignedBulbs.append(Bulb(name: "Lightstrip", image: UIImage(named: "Lightstrip")!)) myHome.unassignedBulbs.append(Bulb(name: "GU10", image: UIImage(named: "GU10")!)) myHome.unassignedBulbs.append(Bulb(name: "GU10", image: UIImage(named: "GU10")!)) myHome.unassignedBulbs.append(Bulb(name: "BR30", image: UIImage(named: "BR30")!)) myHome.unassignedBulbs.append(Bulb(name: "BR30", image: UIImage(named: "BR30")!)) } func getGroupAreas() -> [ChooseItem]{ var items:[ChooseItem] = [] items.append(ChooseItem(name: "Bathroom", image: UIImage(named: "Bathroom")!)) items.append(ChooseItem(name: "Bedroom", image: UIImage(named: "Bedroom")!)) items.append(ChooseItem(name: "Dining", image: UIImage(named: "Dining")!)) items.append(ChooseItem(name: "Kicthen", image: UIImage(named: "Kitchen")!)) items.append(ChooseItem(name: "Living", image: UIImage(named: "Living")!)) items.append(ChooseItem(name: "Toilet", image: UIImage(named: "Toilet")!)) return items } func getGroupTypes() -> [ChooseItem]{ var items:[ChooseItem] = [] items.append(ChooseItem(name: "Ceiling", image: UIImage(named: "Ceiling")!)) items.append(ChooseItem(name: "Floor", image: UIImage(named: "Floor")!)) items.append(ChooseItem(name: "Pendant", image: UIImage(named: "Pendant")!)) items.append(ChooseItem(name: "Rec spot", image: UIImage(named: "Rec spot")!)) items.append(ChooseItem(name: "Spot", image: UIImage(named: "Spot")!)) items.append(ChooseItem(name: "Table", image: UIImage(named: "Table")!)) return items } func getGroup(groupId: String) -> Group? { var foundgroup: Group? for room in myHome.rooms { for group in room.groups { if group.id == groupId { foundgroup = group } } } return foundgroup } func getBulb(bulbId: String) -> Bulb? { for bulb in getBulbsInHome() { if bulb.id == bulbId { return bulb } } for room in myHome.rooms { for assignedBulb in room.assignedBulbs { if assignedBulb.id == bulbId { return assignedBulb } for group in room.groups { for assignedBulb in group.assignedBulbs { if assignedBulb.id == bulbId { return assignedBulb } } } } } return nil } // add bulb to room and reove from home func moveBulbFromHomeToRoom(bulbId: String, roomId: String) { var bulbCounter = 0 for bulb in myHome.unassignedBulbs { if bulb.id == bulbId { myHome.unassignedBulbs.remove(at: bulbCounter) for room in myHome.rooms { if room.id == roomId { bulb.positionX = 0 bulb.positionY = 0 room.assignedBulbs.append(bulb) } } } bulbCounter += 1 } } // move bulb from room and move to house func moveBulbFromRoomToHome(bulbId: String, roomId: String) { var bulbcounter:Int = 0 // find room in home for room in myHome.rooms { if room.id == roomId { // find bulb in room for assignedBulb in room.assignedBulbs { if assignedBulb.id == bulbId { // remove bulb from room room.assignedBulbs.remove(at: bulbcounter) // add bulb to home myHome.unassignedBulbs.append(assignedBulb) } } bulbcounter += 1 } } } // move bulb from group and move to room func moveBulbFromGroupToRoom(bulbId: String, groupId: String) { var bulbCounter: Int = 0 // find group in home for room in myHome.rooms { for group in room.groups { if group.id == groupId { // find bulb in group for assignedBulb in group.assignedBulbs { if assignedBulb.id == bulbId { // remove bulb from group group.assignedBulbs.remove(at: bulbCounter) // add bulb to room room.assignedBulbs.append(assignedBulb) } bulbCounter += 1 } } } } } func moveBulbFromRoomToGroup(bulbId: String, groupId: String) { var bulbCounter: Int // find group in home for room in myHome.rooms { for group in room.groups { if group.id == groupId { bulbCounter = 0 for assignedBulb in room.assignedBulbs { if assignedBulb.id == bulbId { // remove bulb from room room.assignedBulbs.remove(at: bulbCounter ) // add bulb to group group.assignedBulbs.append(assignedBulb) } bulbCounter += 1 } } } } } // create group and add to room func addGroupToRoom(roomId: String, group: Group) { // find room in home for room in myHome.rooms { if room.id == roomId { room.groups.append(group) } } } // remove group,if bulbs are still in group, they will be moved to room func removeGroup(groupId: String){ var groupCounter: Int for room in myHome.rooms { // reset groupcounter groupCounter = 0 for group in room.groups { if group.id == groupId { // check if bulbs are in group and move to room for assignedBulb in group.assignedBulbs { room.assignedBulbs.append(assignedBulb) } // remove room room.groups.remove(at: groupCounter) } groupCounter += 1 } } } // get rooms in home func getRooms() -> [Room] { var rooms: [Room] = [] // find all rooms in home for room in myHome.rooms { rooms.append(room) } return rooms } // get room func getRoom(roomId: String) -> Room? { var foundRoom: Room? // find all rooms in home for room in myHome.rooms { if room.id == roomId { foundRoom = room } } return foundRoom } // get groups in room func getGroupsInRoom(roomId: String) -> [Group] { var groups: [Group] = [] // find room in house for room in myHome.rooms { if room.id == roomId { for group in room.groups { groups.append(group) } } } return groups } // get bulbs in room func getBulbsInRoom(roomId: String) -> [Bulb] { // find room in house for room in myHome.rooms { if room.id == roomId { return room.assignedBulbs } } return [] } // get bulbs in group func getBulbsInGroup(groupId: String) -> [Bulb] { var bulbs: [Bulb] = [] // check all rooms in house for group for room in myHome.rooms{ for group in room.groups { if group.id == groupId { for assignedBulb in group.assignedBulbs { bulbs.append(assignedBulb) } } } } return bulbs } // get unassigned bulbs in home func getBulbsInHome() -> [Bulb] { return myHome.unassignedBulbs } }
// // EditGroupViewController.swift // Spoint // // Created by kalyan on 27/02/18. // Copyright © 2018 Personal. All rights reserved. // import UIKit struct GroupFriends { let userInfo:User var selected:Bool init(userinfo:User, selected:Bool) { self.userInfo = userinfo self.selected = selected } } class EditGroupViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tableview:UITableView! var groupFriends = [GroupFriends]() var idsArray: [String]! var groupsView:GroupsViewController! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. tableview.register(FriendsTableViewCell.self) self.tableview.allowsMultipleSelection = true for userid in idsArray { FireBaseContants.firebaseConstant.getUser(userid) { (user) in DispatchQueue.main.async() { if user.id != FireBaseContants.firebaseConstant.CURRENT_USER_ID { self.groupFriends.append(GroupFriends(userinfo: user, selected: true)) self.tableview.reloadData() } } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func backButtonAction(){ self.navigationController?.popViewController(animated: true) } @IBAction func doneButtonAction(){ groupsView.editGroup(list: groupFriends) self.navigationController?.popViewController(animated: true) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if groupFriends.count == 0{ self.showEmptyMessage(message: "No data available", tableview: tableView) return 0 }else{ tableview.backgroundView = nil return groupFriends.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "FriendsTableViewCell") as! FriendsTableViewCell cell.titleLabel?.text = self.groupFriends[indexPath.item].userInfo.name.capitalized cell.imageview?.kf.setImage(with: self.groupFriends[indexPath.item].userInfo.profilePic) self.groupFriends[indexPath.item].selected = cell.checkmarkButton.isSelected ? true : false if cell.checkmarkButton.isSelected { cell.checkmarkButton.isSelected = true }else{ cell.checkmarkButton.isSelected = false } cell.accessoryType = cell.isSelected ? .checkmark : .none cell.selectionStyle = .none return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedCell = tableView.cellForRow(at: indexPath)! as! FriendsTableViewCell selectedCell.checkmarkButton.isSelected = true self.groupFriends[indexPath.item].selected = true } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { let deselectedCell = tableView.cellForRow(at: indexPath)! as! FriendsTableViewCell deselectedCell.checkmarkButton.isSelected = false self.groupFriends[indexPath.item].selected = false } /* // 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. } */ }
// // DataObj.swift // FixedPosition // // Created by 飞翔 on 2020/6/4. // Copyright © 2020 飞翔. All rights reserved. // import UIKit class DataObj: NSObject { var name:String? var sex:String? var age:String? static func loadData() -> [DataObj] { let dataAry = [["name":"Jack","sex":"male","age":"18"], ["name":"Peter","sex":"male","age":"19"], ["name":"Monkey","sex":"male","age":"20"], ["name":"Tom","sex":"male","age":"21"], ["name":"Tom","sex":"male","age":"22"], ["name":"Lisy","sex":"female","age":"23"], ["name":"Rose","sex":"female","age":"24"], ["name":"Jim","sex":"male","age":"25"], ["name":"Lilei","sex":"male","age":"26"], ["name":"WuTao","sex":"male","age":"27"], ["name":"Jack","sex":"male","age":"18"], ["name":"Peter","sex":"male","age":"19"], ["name":"Monkey","sex":"male","age":"20"], ["name":"Tom","sex":"male","age":"21"], ["name":"Tom","sex":"male","age":"22"], ["name":"Lisy","sex":"female","age":"23"], ["name":"Rose","sex":"female","age":"24"], ["name":"Jim","sex":"male","age":"25"], ["name":"Lilei","sex":"male","age":"26"], ["name":"WuTao","sex":"male","age":"27"], ["name":"Jack","sex":"male","age":"18"], ["name":"Peter","sex":"male","age":"19"], ["name":"Monkey","sex":"male","age":"20"], ["name":"Tom","sex":"male","age":"21"], ["name":"Tom","sex":"male","age":"22"], ["name":"Lisy","sex":"female","age":"23"], ["name":"Rose","sex":"female","age":"24"], ["name":"Jim","sex":"male","age":"25"], ["name":"Lilei","sex":"male","age":"26"], ["name":"WuTao","sex":"male","age":"27"] ] var sourceAry = [DataObj]() for dict:Dictionary in dataAry { let model = DataObj() model.name = dict["name"]! model.age = dict["age"]! model.sex = dict["sex"]; sourceAry.append(model) } return sourceAry } }
// // SpacedLabel.swift // App Store // // Created by Chidi Emeh on 2/2/18. // Copyright © 2018 Chidi Emeh. All rights reserved. // import UIKit @IBDesignable class SpacedLabel: UILabel { @IBInspectable var spacing: CGFloat = 4.0 override func awakeFromNib() { let attributedString = NSMutableAttributedString(string: self.text!) attributedString.addAttribute(NSAttributedStringKey.kern, value: spacing, range: NSMakeRange(0, attributedString.length)) self.attributedText = attributedString } }
// // TutorialViewController.swift // Bluffer // // Created by Mariya on 2/25/16. // Copyright © 2016 Blake Hudelson. All rights reserved. // import UIKit class TutorialViewController: UIViewController { @IBOutlet weak var pageControl: UIPageControl! @IBOutlet var scrollView: UIScrollView! @IBAction func onSkip3(sender: AnyObject) { } @IBAction func onSkip2(sender: AnyObject) { } @IBAction func onStartGame(sender: AnyObject) { //NOTE BUG HERE // When a game is finisheed and user taps "Exit" // Will exit to the Tutorial screen if that was loaded prior to the game // Instead of the main screen performSegueWithIdentifier("StartGame", sender: self) } override func viewDidLoad() { super.viewDidLoad() print("Tutorial View Controller Loaded") print("scrollView width: ", scrollView.bounds.width) print("scrollView height: ", scrollView.bounds.height) //contentWidth is 3x scrollView bounds because we have 3 horizontal tutorial screens let contentWidth = scrollView.bounds.width * 3 let contentHeight = scrollView.bounds.height scrollView.contentSize = CGSizeMake(contentWidth, contentHeight) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // AnswerButton.swift // quiz // // Created by Brian Xu on 4/7/2018. // Copyright © 2018 Fake Name. All rights reserved. // import UIKit class AnswerButton: UIButton { required init(coder aDecoder: NSCoder) { fatalError("you dead") } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor(red: 0.13, green: 0.64, blue: 0.62, alpha: 1.0) } override func layoutSubviews() { super.layoutSubviews() self.layer.cornerRadius = self.frame.size.height/2 } }
// // Merge.swift // Rx // // Created by Krunoslav Zaher on 3/28/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation // sequential class MergeSinkIter<S: ObservableConvertibleType, O: ObserverType where O.E == S.E> : ObserverType , LockOwnerType , SynchronizedOnType { typealias E = O.E typealias DisposeKey = Bag<Disposable>.KeyType typealias Parent = MergeSink<S, O> private let _parent: Parent private let _disposeKey: DisposeKey var _lock: NSRecursiveLock { return _parent._lock } init(parent: Parent, disposeKey: DisposeKey) { _parent = parent _disposeKey = disposeKey } func on(event: Event<E>) { synchronizedOn(event) } func _synchronized_on(event: Event<E>) { switch event { case .Next: _parent.forwardOn(event) case .Error: _parent.forwardOn(event) _parent.dispose() case .Completed: _parent._group.removeDisposable(_disposeKey) if _parent._stopped && _parent._group.count == 1 { _parent.forwardOn(.Completed) _parent.dispose() } } } } class MergeSink<S: ObservableConvertibleType, O: ObserverType where O.E == S.E> : Sink<O> , ObserverType , LockOwnerType , SynchronizedOnType { typealias E = S typealias Parent = Merge<S> private let _parent: Parent let _lock = NSRecursiveLock() // state private var _stopped = false private let _group = CompositeDisposable() private let _sourceSubscription = SingleAssignmentDisposable() init(parent: Parent, observer: O) { _parent = parent super.init(observer: observer) } func run() -> Disposable { _group.addDisposable(_sourceSubscription) let disposable = _parent._sources.subscribe(self) _sourceSubscription.disposable = disposable return _group } func on(event: Event<E>) { if case .Next(let value) = event { let innerSubscription = SingleAssignmentDisposable() let maybeKey = _group.addDisposable(innerSubscription) if let key = maybeKey { let observer = MergeSinkIter(parent: self, disposeKey: key) let disposable = value.asObservable().subscribe(observer) innerSubscription.disposable = disposable } return } synchronizedOn(event) } func _synchronized_on(event: Event<E>) { switch event { case .Next: rxFatalError("Next should have been handled") case .Error(let error): forwardOn(.Error(error)) dispose() case .Completed: _stopped = true if _group.count == 1 { forwardOn(.Completed) dispose() } else { _sourceSubscription.dispose() } } } } // concurrent class MergeConcurrentSinkIter<S: ObservableConvertibleType, O: ObserverType where S.E == O.E> : ObserverType , LockOwnerType , SynchronizedOnType { typealias E = O.E typealias DisposeKey = Bag<Disposable>.KeyType typealias Parent = MergeConcurrentSink<S, O> private let _parent: Parent private let _disposeKey: DisposeKey var _lock: NSRecursiveLock { return _parent._lock } init(parent: Parent, disposeKey: DisposeKey) { _parent = parent _disposeKey = disposeKey } func on(event: Event<E>) { synchronizedOn(event) } func _synchronized_on(event: Event<E>) { switch event { case .Next: _parent.forwardOn(event) case .Error: _parent.forwardOn(event) _parent.dispose() case .Completed: _parent._group.removeDisposable(_disposeKey) let queue = _parent._queue if queue.value.count > 0 { let s = queue.value.dequeue() _parent.subscribe(s, group: _parent._group) } else { _parent._activeCount = _parent._activeCount - 1 if _parent._stopped && _parent._activeCount == 0 { _parent.forwardOn(.Completed) _parent.dispose() } } } } } class MergeConcurrentSink<S: ObservableConvertibleType, O: ObserverType where S.E == O.E> : Sink<O> , ObserverType , LockOwnerType , SynchronizedOnType { typealias E = S typealias Parent = Merge<S> typealias QueueType = Queue<S> private let _parent: Parent let _lock = NSRecursiveLock() // state private var _stopped = false private var _activeCount = 0 private var _queue = RxMutableBox(QueueType(capacity: 2)) private let _sourceSubscription = SingleAssignmentDisposable() private let _group = CompositeDisposable() init(parent: Parent, observer: O) { _parent = parent _group.addDisposable(_sourceSubscription) super.init(observer: observer) } func run() -> Disposable { _group.addDisposable(_sourceSubscription) let disposable = _parent._sources.subscribe(self) _sourceSubscription.disposable = disposable return _group } func subscribe(innerSource: E, group: CompositeDisposable) { let subscription = SingleAssignmentDisposable() let key = group.addDisposable(subscription) if let key = key { let observer = MergeConcurrentSinkIter(parent: self, disposeKey: key) let disposable = innerSource.asObservable().subscribe(observer) subscription.disposable = disposable } } func on(event: Event<E>) { synchronizedOn(event) } func _synchronized_on(event: Event<E>) { switch event { case .Next(let value): let subscribe: Bool if _activeCount < _parent._maxConcurrent { _activeCount += 1 subscribe = true } else { _queue.value.enqueue(value) subscribe = false } if subscribe { self.subscribe(value, group: _group) } case .Error(let error): forwardOn(.Error(error)) dispose() case .Completed: if _activeCount == 0 { forwardOn(.Completed) dispose() } else { _sourceSubscription.dispose() } _stopped = true } } } class Merge<S: ObservableConvertibleType> : Producer<S.E> { private let _sources: Observable<S> private let _maxConcurrent: Int init(sources: Observable<S>, maxConcurrent: Int) { _sources = sources _maxConcurrent = maxConcurrent } override func run<O: ObserverType where O.E == S.E>(observer: O) -> Disposable { if _maxConcurrent > 0 { let sink = MergeConcurrentSink(parent: self, observer: observer) sink.disposable = sink.run() return sink } else { let sink = MergeSink(parent: self, observer: observer) sink.disposable = sink.run() return sink } } }
// // LastOnboardingCVC.swift // Whale-iOS // // Created by 황지은 on 2021/06/11. // import UIKit class LastOnboardingCVC: UICollectionViewCell { @IBOutlet var firstLabel: UILabel! @IBOutlet var secondLabel: UILabel! @IBOutlet var whaleImageView: UIImageView! override func awakeFromNib() { customLabels() } //MARK: - 라벨 AttributeFont 설정 func customLabels() { /// set firstBigLabel fonts let firstAttributedString = NSMutableAttributedString(string: firstLabel.text!, attributes: [ .font: UIFont.AppleSDGothicB(size: 23), .foregroundColor: UIColor.brown_2, .kern: -1.15 ]) firstAttributedString.addAttribute(.font, value: UIFont.AppleSDGothicR(size: 23), range: (firstLabel.text! as NSString).range(of: "와 함께")) firstAttributedString.addAttribute(.foregroundColor, value: UIColor.brown_2, range: (firstLabel.text! as NSString).range(of: "와 함께")) firstLabel.attributedText = firstAttributedString firstLabel.sizeToFit() /// set secondBigLabel fonts let secondAttributedString = NSMutableAttributedString(string: secondLabel.text!, attributes: [ .font: UIFont.AppleSDGothicB(size: 23), .foregroundColor: UIColor.brown_2, .kern: -1.15 ]) secondAttributedString.addAttribute(.font, value: UIFont.AppleSDGothicR(size: 23), range: (secondLabel.text! as NSString).range(of: "매일")) secondAttributedString.addAttribute(.foregroundColor, value: UIColor.brown_2, range: (secondLabel.text! as NSString).range(of: "매일")) secondLabel.attributedText = secondAttributedString secondLabel.sizeToFit() } func makeAnimation() { whaleImageView.frame = CGRect(x: 0, y: 83, width: self.whaleImageView.frame.width, height: self.whaleImageView.frame.height) UIView.animate(withDuration: 1, delay: 0, options: [.repeat, .autoreverse] , animations: { self.whaleImageView.frame = CGRect(x: 10, y: 83, width: self.whaleImageView.frame.width, height: self.whaleImageView.frame.height) }) } }
// // MemeDetailViewController.swift // MemeMe1.0 // // Created by Jonathan Miranda on 5/6/20. // Copyright © 2020 Jonathan Miranda. All rights reserved. // import UIKit class MemeDetailViewController: UIViewController { var image: UIImage? @IBOutlet weak var imageDetail: UIImageView! override func viewDidLoad() { super.viewDidLoad() if let img = image { imageDetail.image = img } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tabBarController?.tabBar.isHidden = true } }
// // NumbersLightListNumbersLightListviewcontrollerSpecs.swift // NumbersLight // // Created by Guillaume on 27/01/2020. // Copyright © 2020 gsabatie. All rights reserved. // import XCTest import Quick import Nimble import SwiftyMocky @testable import NumbersLight final class JapaneseNumeralListViewControllerSpecs: QuickSpec { var viewController: JapaneseNumeralTableViewController! var presenter: JapaneseNumeralListViewEventResponderProtocolMock! override func spec() { } } extension JapaneseNumeralTableViewController { static func forTest(presenterMock: inout JapaneseNumeralListViewEventResponderProtocol) -> JapaneseNumeralTableViewController { let viewController = JapaneseNumeralTableViewController() viewController.output = presenterMock return viewController } } fileprivate extension JapaneseNumeralListViewEventResponderProtocolMock { }
// // AllWinesView.swift // wineApp // // Created by stephanie on 7/9/20. // Copyright © 2020 stephanie. All rights reserved. // import SwiftUI struct AllWinesView: View { let blueViolet = Color(red: 90/255, green:7/255, blue: 173/255) let darkPurple = Color(red: 67/255, green:64/255, blue: 83/255) struct HeaderStyle: ViewModifier { func body(content: Content) -> some View { return content .foregroundColor(Color.white) .modifier(Shadow()) .font(Font.custom("Trebuchet MS", size: 35)) } } struct LinkStyle: ViewModifier { func body(content: Content) -> some View { return content .foregroundColor(Color.white) .modifier(Shadow()) .font(Font.custom("Trebuchet MS", size: 35)) } } struct Shadow: ViewModifier { func body(content: Content) -> some View { return content .shadow(color: Color.black, radius: 5, x: 2, y: 2) } } var body: some View { ZStack { Color(red: 67/255, green:64/255, blue: 83/255) .edgesIgnoringSafeArea(.all) VStack { Spacer() Text("Wines I've Tried...").modifier(HeaderStyle()) Spacer() } } } } struct AllWinesView_Previews: PreviewProvider { static var previews: some View { AllWinesView() } }
// // ThemeManager.swift // Pigeon-project // // Created by Roman Mizin on 8/2/17. // Copyright © 2017 Roman Mizin. All rights reserved. // import UIKit let SelectedThemeKey = "SelectedTheme" extension NSNotification.Name { static let themeUpdated = NSNotification.Name(Bundle.main.bundleIdentifier! + ".themeUpdated") } struct ThemeManager { static func applyTheme(theme: Theme) { userDefaults.updateObject(for: userDefaults.selectedTheme, with: theme.rawValue) UITabBar.appearance().barStyle = theme.barStyle UINavigationBar.appearance().isTranslucent = false UINavigationBar.appearance().barStyle = theme.barStyle UINavigationBar.appearance().barTintColor = theme.barBackgroundColor UITabBar.appearance().barTintColor = theme.barBackgroundColor NotificationCenter.default.post(name: .themeUpdated, object: nil) } static func currentTheme() -> Theme { if let storedTheme = userDefaults.currentIntObjectState(for: userDefaults.selectedTheme) { return Theme(rawValue: storedTheme)! } else { return .Default } } } enum Theme: Int { case Default, Dark var generalBackgroundColor: UIColor { switch self { case .Default: return .white case .Dark: return UIColor(hexString: "#141820") } } var backbuttonColor: UIColor { switch self { case .Default: return UIColor(hexString: "#3E434D") case .Dark: return .white } } var ConnectedBottomView: UIColor { switch self { case .Default: return UIColor(hexString: "#F2F2F2") case .Dark: return UIColor(hexString: "#262B35") } } var LocationViewColor: UIColor { switch self { case .Default: return UIColor.lightGray case .Dark: return UIColor.white } } var NavigationBarBackgroundColor: UIColor { switch self { case .Default: return UIColor.white case .Dark: return UIColor(hexString: "#262B35") } } var CountryTableviewBackgroundColor: UIColor { switch self { case .Default: return .white case .Dark: return UIColor(hexString: "#141820") } } var CountryListSelectedTextBackgroundColor: UIColor { switch self { case .Default: return UIColor(hexString: "#3D434E") case .Dark: return UIColor(hexString: "#FFFFFF") } } var CountryListTextBackgroundColor: UIColor { switch self { case .Default: return UIColor(hexString: "#677080") case .Dark: return UIColor(hexString: "#AEB4BE") } } var CountryTableviewCellbackgroundColor: UIColor { switch self { case .Default: return UIColor(hexString: "#22CC77").withAlphaComponent(0.10) case .Dark: return UIColor(hexString: "##E9EFF0").withAlphaComponent(0.10) } } var barBackgroundColor: UIColor { switch self { case .Default: return .white case .Dark: return .black } } var SepratedViewColor: UIColor { switch self { case .Default: return UIColor(hexString: "#000000").withAlphaComponent(0.10) case .Dark: return UIColor(hexString: "#FFFFFF").withAlphaComponent(0.10) } } var generalTitleColor: UIColor { switch self { case .Default: return UIColor.black case .Dark: return UIColor.white } } var generalSubtitleColor: UIColor { switch self { case .Default: return UIColor(red:0.67, green:0.67, blue:0.67, alpha:1.0) case .Dark: return UIColor(red:0.67, green:0.67, blue:0.67, alpha:1.0) } } var ConnectedTextColor: UIColor { switch self { case .Default: return UIColor(hexString: "#22CC77") case .Dark: return UIColor(hexString: "#DFE1E5") } } var DisConnectedTextColor: UIColor { switch self { case .Default: return UIColor(hexString: "#FF0033") case .Dark: return UIColor(hexString: "#DFE1E5") } } //location & under switch text var locationAndOtherTextColor: UIColor { switch self { case .Default: return UIColor(hexString: "#AEB4BE") case .Dark: return UIColor(hexString: "#AEB4BE") } } var TitleColor: UIColor { switch self { case .Default: return UIColor(hexString: "#3D434E") case .Dark: return UIColor(hexString: "#FFFFFF") } } var DetailTextColor: UIColor { switch self { case .Default: return UIColor(hexString: "#677080") case .Dark: return UIColor(hexString: "#AEB4BE") } } var DisconnectSwitchColor: UIColor { switch self { case .Default: return UIColor(hexString: "#C1C1C1") case .Dark: return UIColor(hexString: "#363B45") } } var ConnectSwitchColor: UIColor { switch self { case .Default: return UIColor(hexString: "#22CC77") case .Dark: return UIColor(hexString: "#22CC77") } } var settingimg: UIImage{ switch self { case .Default: return UIImage(named: "Settingimg")! case .Dark: return UIImage(named: "SettingimgDark")! } } var statusimg: UIImage{ switch self { case .Default: return UIImage(named: "Statusimg")! case .Dark: return UIImage(named: "StatusimgDark")! } } var shareimg: UIImage{ switch self { case .Default: return UIImage(named: "Shareimg")! case .Dark: return UIImage(named: "ShareimgDark")! } } var themeimg: UIImage{ switch self { case .Default: return UIImage(named: "Themeimg")! case .Dark: return UIImage(named: "ThemeimgDark")! } } var countrypinmainimg: UIImage{ switch self { case .Default: return UIImage(named: "LocationpinimgMain")! case .Dark: return UIImage(named: "LocationpinimgMainDark")! } } var countrypinsettingimg: UIImage{ switch self { case .Default: return UIImage(named: "LocationPinSetting")! case .Dark: return UIImage(named: "LocationPinSettingDark")! } } var reviewsettingimg: UIImage{ switch self { case .Default: return UIImage(named: "Feedbackimg")! case .Dark: return UIImage(named: "FeedbackimgDark")! } } var dropmenumainimg: UIImage{ switch self { case .Default: return UIImage(named: "DropmenuMainimg")! case .Dark: return UIImage(named: "DropmenuMainimgDark")! } } var dropmenusettingimg: UIImage{ switch self { case .Default: return UIImage(named: "DropmenuimgSetting")! case .Dark: return UIImage(named: "DropmenuimgSettingDark")! } } var cellSelectionColor: UIColor { switch self { case .Default: return UIColor(red:0.95, green:0.95, blue:0.95, alpha:1.0) //F1F1F1 case .Dark: return UIColor(red:0.10, green:0.10, blue:0.10, alpha:1.0) //191919 } } var inputTextViewColor: UIColor { switch self { case .Default: return UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0) case .Dark: return UIColor(red: 0.11, green: 0.11, blue: 0.11, alpha: 1.0) } } var controlButtonsColor: UIColor { switch self { case .Default: return UIColor(red:0.94, green:0.94, blue:0.96, alpha:1.0) case .Dark: return UIColor(red: 0.11, green: 0.11, blue: 0.11, alpha: 1.0) } } var searchBarColor: UIColor { switch self { case .Default: return UIColor(red: 0.99, green: 0.99, blue: 0.99, alpha: 0.5) case .Dark: return UIColor(red: 0.11, green: 0.11, blue: 0.11, alpha: 0.8) } } var mediaPickerControllerBackgroundColor: UIColor { switch self { case .Default: return UIColor(red: 209.0/255.0, green: 213.0/255.0, blue: 218.0/255.0, alpha: 1.0) case .Dark: return UIColor(red: 0.10, green: 0.10, blue: 0.10, alpha: 1.0) } } var splashImage: UIImage { switch self { case .Default: return UIImage(named: "whiteSplash")! case .Dark: return UIImage(named: "blackSplash")! } } var mainimage: UIImage{ switch self { case .Default: return UIImage(named: "backimgdark")! case .Dark: return UIImage(named: "backimglight")! } } var typingIndicatorURL: URL? { switch self { case .Default: return Bundle.main.url(forResource: "typingIndicator", withExtension: "gif") case .Dark: return Bundle.main.url(forResource: "typingindicatorDark", withExtension: "gif") } } var enterPhoneNumberBackground: UIImage { switch self { case .Default: return UIImage(named: "LightAuthCountryButtonNormal")! case .Dark: return UIImage(named: "DarkAuthCountryButtonNormal")! } } var enterPhoneNumberBackgroundSelected: UIImage { switch self { case .Default: return UIImage(named:"LightAuthCountryButtonHighlighted")! case .Dark: return UIImage(named:"DarkAuthCountryButtonHighlighted")! } } var personalStorageImage: UIImage { switch self { case .Default: return UIImage(named: "PersonalStorage")! case .Dark: return UIImage(named: "PersonalStorage")! } } var incomingBubble: UIImage { switch self { case .Default: return UIImage(named: "DarkPigeonBubbleIncomingFull")!.resizableImage(withCapInsets: UIEdgeInsets(top: 14, left: 22, bottom: 17, right: 20))//UIImage(named: "PigeonBubbleIncomingFull")!.resizableImage(withCapInsets: UIEdgeInsetsMake(14, 22, 17, 20)) case .Dark: return UIImage(named: "DarkPigeonBubbleIncomingFull")!.resizableImage(withCapInsets: UIEdgeInsets(top: 14, left: 22, bottom: 17, right: 20)) } } var outgoingBubble: UIImage { switch self { case .Default: return UIImage(named: "PigeonBubbleOutgoingFull")!.resizableImage(withCapInsets: UIEdgeInsets(top: 14, left: 14, bottom: 17, right: 28)) case .Dark: //DarkPigeonBubbleOutgoingFull return UIImage(named: "PigeonBubbleOutgoingFull")!.resizableImage(withCapInsets: UIEdgeInsets(top: 14, left: 14, bottom: 17, right: 28)) } } var keyboardAppearance: UIKeyboardAppearance { switch self { case .Default: return .default case .Dark: return .dark } } var barStyle: UIBarStyle { switch self { case .Default: return .default case .Dark: return .black } } var statusBarStyle: UIStatusBarStyle { switch self { case .Default: return .default case .Dark: return .lightContent } } var scrollBarStyle: UIScrollView.IndicatorStyle { switch self { case .Default: return .default case .Dark: return .white } } var backgroundColor: UIColor { switch self { case .Default: return UIColor.white case .Dark: return UIColor.black } } var secondaryColor: UIColor { switch self { case .Default: return UIColor(red: 242.0/255.0, green: 101.0/255.0, blue: 34.0/255.0, alpha: 1.0) case .Dark: return UIColor(red: 34.0/255.0, green: 128.0/255.0, blue: 66.0/255.0, alpha: 1.0) } } } struct FalconPalette { static let defaultBlue = UIColor(red:0.00, green:0.50, blue:1.00, alpha: 1.0) static let dismissRed = UIColor(red:1.00, green:0.23, blue:0.19, alpha:1.0) static let appStoreGrey = UIColor(red:0.94, green:0.94, blue:0.96, alpha:1.0) }
// // CoreData.swift // florafinder // // Created by Andrew Tokeley on 6/01/16. // Copyright © 2016 Andrew Tokeley . All rights reserved. // import Foundation import CoreData enum CoreDataControllerError: ErrorType { case DataModelNotFound case InsufficientFunds(coinsNeeded: Int) case OutOfStock } /** Provides access to Core Data functionality */ class CoreDataController: NSObject { private var _coordinator: NSPersistentStoreCoordinator? private var _managedObjectContext: NSManagedObjectContext? //MARK: - Initialisers /** Creates a new CoreDataController instance - Parameters: - storeName: the name of the store - dataModelName: the name of the data model - Returns: not applicable - Throws: `CoreDataControllerError.DataModelNotFound` if data model file not found */ init(dataModelName:NSString, storeName: NSString) throws { self.dataModelName = dataModelName self.storeName = storeName; super.init() // check validity of controller // the compiled data model must exist otherwise we're screwed guard (NSBundle.mainBundle().URLForResource(dataModelName as String, withExtension: "momd") != nil) else { throw CoreDataControllerError.DataModelNotFound } } //MARK: - Properties /** Read-only property that returns the URL to the application's Documents directory. This is where the database store will be saved */ var applicationDocumentsDirectory: NSURL { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] } /** Returns or sets the name given to the data model. This name should match the name of your *.xcdatamodeld file. */ var dataModelName: NSString /** Returns or sets the name given to the data store. */ var storeName: NSString = "" /** Read-only property that returns the full path to the database store */ var storeURL: NSURL { return self.applicationDocumentsDirectory.URLByAppendingPathComponent("\(self.storeName).sqlite") } /** Set to true to force self.persistentStoreCoordinator to return a new coordinator */ var needsUpdateManagedObjectContext: Bool = true /** Returns the managed object context for the application. */ var managedObjectContext: NSManagedObjectContext { if (needsUpdateManagedObjectContext) { _managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType) _managedObjectContext!.persistentStoreCoordinator = self.persistentStoreCoordinator needsUpdateManagedObjectContext = false } // We can assume that needsUpdateManagdObjectContext is initialised to true so that at this point _managedObjectContext is never nil return _managedObjectContext! } /** Returns the `ManagedObjectModel` associated with the specified dataModel. */ lazy var managedObjectModel: NSManagedObjectModel = { let modelURL = NSBundle.mainBundle().URLForResource(self.dataModelName as String, withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() /** Set to true to force self.persistentStoreCoordinator to return a new coordinator */ var needsUpdateStoreCoordinator:Bool = true /** The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ var persistentStoreCoordinator:NSPersistentStoreCoordinator? { if (needsUpdateStoreCoordinator) { // Create the coordinator and store _coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let failureReason = "There was an error creating or loading the application's saved data." do { try _coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: self.storeURL, options: nil) needsUpdateStoreCoordinator = false } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } } return _coordinator } //MARK: - Functions /** Rolls back unsaved changes made on the `managedObjectContext` */ func rollback() { self.managedObjectContext.rollback() } /** Save unsaved changes made on the `managedObjectContext` - Throws: propogates any exceptions thrown by managedObjectContext.save() */ func save() throws { // propogates the error up the chain try self.managedObjectContext.save() } func resetDatastore() throws -> Bool { var success: Bool = false self.managedObjectContext.lock() self.managedObjectContext.reset() if let store = self.persistentStoreCoordinator?.persistentStores.last { do { try self.persistentStoreCoordinator?.removePersistentStore(store) needsUpdateStoreCoordinator = true needsUpdateManagedObjectContext = true try NSFileManager.defaultManager().removeItemAtPath(storeURL.path!) // Now recreate the store - necessary? self.managedObjectContext.unlock() success = true } catch { // TODO: Log success = false } } return success } // Remove the Persistant Data Store, removing all data, and recreated // - (BOOL)resetDatastore // { // [_managedObjectContext lock]; // [_managedObjectContext reset]; // NSPersistentStore *store = [[_persistentStoreCoordinator persistentStores] lastObject]; // BOOL resetOk = NO; // // if (store) // { // NSURL *storeUrl = store.URL; // NSError *error; // // if ([_persistentStoreCoordinator removePersistentStore:store error:&error]) // { // _persistentStoreCoordinator = nil; // _managedObjectContext = nil; // // if (![[NSFileManager defaultManager] removeItemAtPath:storeUrl.path error:&error]) // { // NSLog(@"\nresetDatastore. Error removing file of persistent store: %@", // [error localizedDescription]); // resetOk = NO; // } // else // { // //now recreate persistent store // [[self managedObjectContext] unlock]; // resetOk = YES; // } // } // else // { // NSLog(@"\nresetDatastore. Error removing persistent store: %@", // [error localizedDescription]); // resetOk = NO; // } // return resetOk; // } // else // { // NSLog(@"\nresetDatastore. Could not find the persistent store"); // return resetOk; // } }
// // WindowController.swift // ParcelTracker // // Created by Максим Данилов on 16/12/2018. // Copyright © 2018 Maxim Danilov. All rights reserved. // import Cocoa class WindowController: NSWindowController { @IBOutlet weak var updateProgressIndicator: NSProgressIndicator! @IBOutlet weak var deleteButton: NSButton! override func windowDidLoad() { super.windowDidLoad() // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file. } }
// // MainController.swift // FBMIF50 // // Created by BeInMedia on 3/22/20. // Copyright © 2020 MIF50. All rights reserved. // import UIKit import SwiftUI import LBTATools class MainController: LBTAListHeaderController<PostCell,String,StoryHeader> { // outlite nav bar let fbLogo: UIImageView = { let img = UIImageView(image: UIImage(named: "fb_logo"), contentMode: .scaleAspectFit) img.withWidth(120) return img }() let searchBtn: UIButton = { let btn = UIButton(image: UIImage(named: "search")!, tintColor: .black) btn.withWidth(34).withHeight(34) btn.clipsToBounds = true btn.layer.cornerRadius = 17 btn.backgroundColor = UIColor.init(white: 0.9, alpha: 1) return btn }() let messengerBtn: UIButton = { let btn = UIButton(image: UIImage(named: "messenger")!, tintColor: .black) btn.withWidth(34).withHeight(34) btn.clipsToBounds = true btn.layer.cornerRadius = 17 btn.backgroundColor = UIColor.init(white: 0.9, alpha: 1) return btn }() override func viewDidLoad() { super.viewDidLoad() initCollectionView() setupNavBar() } private func initCollectionView(){ collectionView.backgroundColor = .init(white: 0.9, alpha: 1) self.items = ["hello", "wolrd","1","2"] } fileprivate func setupNavBar() { let coverWhiteView = UIView(backgroundColor: .white) view.addSubview(coverWhiteView) coverWhiteView.anchor(top: view.topAnchor, leading: view.leadingAnchor, bottom: nil, trailing: view.trailingAnchor) let topSafeArea = UIApplication.shared.windows.filter{$0.isKeyWindow}.first?.safeAreaInsets.top ?? 0 coverWhiteView.withHeight(topSafeArea) navigationController?.navigationBar.barTintColor = .white navigationController?.navigationBar.shadowImage = UIImage() navigationController?.navigationBar.tintColor = .white let lessWidth: CGFloat = 34 + 34 + 120 + 16 + 24 let width = view.frame.width - lessWidth let navView = UIView() navView.frame = .init(x: 0, y: 0, width: width, height: 50) navView.hstack(fbLogo,UIView(backgroundColor: .clear).withWidth(width),searchBtn,messengerBtn,spacing: 8) .padBottom(8) navigationItem.titleView = navView } override func scrollViewDidScroll(_ scrollView: UIScrollView) { let safeAreaTop = UIApplication.shared.windows.filter{$0.isKeyWindow}.first?.safeAreaInsets.top ?? 0 let magicalSafeAreaTop: CGFloat = safeAreaTop + (navigationController?.navigationBar.frame.height ?? 0) let offset = scrollView.contentOffset.y + magicalSafeAreaTop let alpha: CGFloat = 1 - (scrollView.contentOffset.y + magicalSafeAreaTop) / magicalSafeAreaTop [fbLogo,searchBtn,messengerBtn].forEach { $0.alpha = alpha } navigationController?.navigationBar.transform = .init(translationX: 0, y: min(0,-offset)) print("y = \(scrollView.contentOffset.y) alph = \(alpha)") } } //MARK:- Collection View Delegate Flow Layout extension MainController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return .init(width: 0, height: 230 + 130 + 12) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return .init(width: view.frame.width, height: 400) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return .init(top: 12, left: 0, bottom: 0, right: 0) } } // to preview desing form SwiftUI struct MainPreview: PreviewProvider{ static var previews: some View { ContainerView().edgesIgnoringSafeArea(.all) } struct ContainerView: UIViewControllerRepresentable { func makeUIViewController(context: UIViewControllerRepresentableContext<MainPreview.ContainerView>) -> UIViewController { return UINavigationController(rootViewController: MainController()) } func updateUIViewController(_ uiViewController: MainPreview.ContainerView.UIViewControllerType, context: UIViewControllerRepresentableContext<MainPreview.ContainerView>) { } } }
// // GZEUsersList.swift // Gooze // // Created by Yussel on 3/26/18. // Copyright © 2018 Gooze. All rights reserved. // import UIKit class GZEUsersList: UIView { // MARK: - public vars var onDismiss: (() -> ())? var users: [GZEUserConvertible] { set(users) { self.usersListCollectionView.users = users self.usersListCollectionView.reloadData() } get { return self.usersListCollectionView.users } } var onUserTap: ((UITapGestureRecognizer, GZEUserBalloon) -> ())? { set(onUserTap) { self.usersListCollectionView.onUserTap = onUserTap } get { return self.usersListCollectionView.onUserTap } } let actionButton = GZEButton() // MARK: - private vars private let usersListCollectionView = GZEUsersListCollectionView() private let dismissView = DismissView() private let usersListBackground = UIView() // MARK: - init required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) log.debug("\(self) init") initialize() } override init(frame: CGRect) { super.init(frame: frame) log.debug("\(self) init") initialize() } convenience init() { self.init(frame: CGRect.zero) } // MARK: - Public methods func show() { UIView.animate(withDuration: 0.5) {[weak self] in self?.alpha = 1 } } @objc func dismiss() { UIView.animate(withDuration: 0.5) {[weak self] in self?.alpha = 0 } self.onDismiss?() } func updateItems(at index: [Int]) { self.usersListCollectionView.reloadItems(at: index.map{IndexPath(item: $0, section: 0)}) } // MARK: - Private methods private func initialize() { self.alpha = 0 self.usersListBackground.layer.cornerRadius = 15 self.usersListBackground.layer.masksToBounds = true self.usersListBackground.backgroundColor = UIColor(white: 1/3, alpha: 0.7) self.actionButton.setGrayFormat() self.dismissView.label.font = GZEConstants.Font.mainSuperBig self.dismissView.label.textColor = .white self.dismissView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismiss))) self.addSubview(self.usersListBackground) self.addSubview(self.usersListCollectionView) self.addSubview(self.actionButton) self.addSubview(self.dismissView) // Constraints self.translatesAutoresizingMaskIntoConstraints = false self.usersListBackground.translatesAutoresizingMaskIntoConstraints = false // Background view self.topAnchor.constraint(equalTo: self.usersListBackground.topAnchor).isActive = true self.bottomAnchor.constraint(equalTo: self.usersListBackground.bottomAnchor).isActive = true self.trailingAnchor.constraint(equalTo: self.usersListBackground.trailingAnchor).isActive = true self.leadingAnchor.constraint(equalTo: self.usersListBackground.leadingAnchor).isActive = true // Users list collection self.topAnchor.constraint(equalTo: self.usersListCollectionView.topAnchor, constant: -30).isActive = true self.bottomAnchor.constraint(equalTo: self.usersListCollectionView.bottomAnchor, constant: 55).isActive = true self.trailingAnchor.constraint(equalTo: self.usersListCollectionView.trailingAnchor, constant: 10).isActive = true self.leadingAnchor.constraint(equalTo: self.usersListCollectionView.leadingAnchor, constant: -10).isActive = true // Action button self.bottomAnchor.constraint(equalTo: self.actionButton.bottomAnchor, constant: 10).isActive = true self.centerXAnchor.constraint(equalTo: self.actionButton.centerXAnchor).isActive = true // Dismiss view self.trailingAnchor.constraint(equalTo: self.dismissView.trailingAnchor).isActive = true self.topAnchor.constraint(equalTo: self.dismissView.topAnchor).isActive = true self.dismissView.widthAnchor.constraint(equalToConstant: 60).isActive = true self.dismissView.heightAnchor.constraint(equalToConstant: 60).isActive = true } // MARK: - Deinitializers deinit { log.debug("\(self) disposed") } }
// // LinkedList.swift // Data Structures // // Created by Gabriel Revells on 5/21/19. // Copyright © 2019 Gabriel Revells. All rights reserved. // import UIKit /// A singly linked list. /// - Complexity: O(n) storage class LinkedList<V>: ListProtocol { public private(set) var size: Int = 0 private var first: Node<V> private var last: Node<V> init() { // Create sentinal node first = Node<V>() last = first } /// Append a new value to the end of the list. /// /// - Parameter value: The value to append to the list /// - Complexity: O(1) time func append(_ value: V) { let newNode = Node<V>(value) last.next = newNode last = newNode size += 1 } /// Insert a value at a given index of the list. /// /// If the index is beyond the current size of the list, the value will be /// appended to the end of the list. If the index is negative, the value /// will be inserted at the beginning of the list. /// /// - Parameters: /// - value: The value to insert /// - index: The index to insert at /// - Complexity: O(n) time func insert(_ value: V, at index: Int) { let previousNode = (try? getNode(at: index).previous) ?? (index < 0 ? first : last) let newNode = Node<V>(value) newNode.next = previousNode.next previousNode.next = newNode size += 1 } /// Get a value at a specific index in the list. /// /// Returns nil if the index is out of bounds of the list. /// /// - Parameter index: The position index to grab from. /// - Returns: The value at that index, or nil if the index is out of bounds /// - Complexity: O(1) time func get(at index: Int) -> V? { // Techincally node.value is optional, because the sentry node doesn't // have a value. However, realistically this won't happen because we // don't get the sentry node from getNode. return try? getNode(at: index).current.value } /// Remove the value at a given index. /// /// Remove the value at a given index from the list, and return the value. /// /// - Parameter index: The index of the value to remove. /// - Returns: The value at the index, or nil if the index is out of bounds. /// - Complexity: O(n) time func remove(at index: Int) -> V? { guard let nodes = try? getNode(at: index) else { return nil } let previousNode = nodes.previous let nodeToRemove = nodes.current previousNode.next = nodeToRemove.next size -= 1 return nodeToRemove.value } /// Get the node at a current index. /// /// This gets the node at a specific index, and the previous node. The /// current node is the node at the given index, and is gurenteed to be an /// actual node. The previous node is gurenteed to exist, but may be the /// sentry node at the beginning of the list. /// /// - Parameter index: The index of the node to get. /// - Returns: /// - previous: The node before the given index /// - current: The node at the given index /// - Throws: Throws an index out of bounds error if the index is outside /// of the current list. /// - Complexity: O(n) time private func getNode(at index: Int) throws -> (previous: Node<V>, current: Node<V>) { guard index >= 0 else { throw ListError.IndexOutOfBoundsError } // Our first node is a sentry node, so skip that var previousNode = first guard var currentNode = first.next else { throw ListError.IndexOutOfBoundsError } var count = 0 while count < index { guard let nextNode = currentNode.next else { throw ListError.IndexOutOfBoundsError } previousNode = currentNode currentNode = nextNode count += 1 } return (previous: previousNode, current: currentNode) } }
import UIKit import MetalKit class UltrasoundContainerView: UIView { var metalView: MTKView? private var metalViewXConstraint: NSLayoutConstraint? private var metalViewYConstraint: NSLayoutConstraint? private var metalViewWidthConstraint: NSLayoutConstraint? private var metalViewHeightConstraint: NSLayoutConstraint? private var depthRulerView: UIView? private var widthRulerView: UIView? var _hatchMarkSpacingXDirection: Double = 0 var hatchMarkSpacingXDirection: Double { get { return _hatchMarkSpacingXDirection } set { _hatchMarkSpacingXDirection = newValue self.showWidthRuler = _showWidthRuler } } var _hatchMarkSpacingZDirection: Double = 0 var hatchMarkSpacingZDirection: Double { get { return _hatchMarkSpacingZDirection } set { _hatchMarkSpacingZDirection = newValue self.showDepthRuler = _showDepthRuler } } var metalViewSize: CGSize { get { guard let metalView = self.metalView else { return CGSize.zero } return metalView.bounds.size } set(size) { guard let metalView = self.metalView else { print("Metal view is not ready.") return } var metalRect = CGRect.zero metalRect.size = size metalView.bounds = metalRect metalView.drawableSize = size if let widthConstraint = self.metalViewWidthConstraint, let heightConstraint = self.metalViewHeightConstraint { widthConstraint.constant = CGFloat(size.width) heightConstraint.constant = CGFloat(size.height) } } } private var _showDepthRuler = true var showDepthRuler: Bool { get { return _showDepthRuler } set { _showDepthRuler = newValue self.depthRulerView?.removeFromSuperview() if newValue { self.depthRulerView = self.depthRuler() } else { self.depthRulerView = nil } self.invalidateIntrinsicContentSize() } } private var _showWidthRuler = true var showWidthRuler: Bool { get { return _showWidthRuler } set { _showWidthRuler = newValue self.widthRulerView?.removeFromSuperview() if newValue { self.widthRulerView = self.widthRuler() } else { self.widthRulerView = nil } self.invalidateIntrinsicContentSize() } } override var intrinsicContentSize: CGSize { get { let metalViewSize = self.metalViewSize var depthRulerSize = CGSize.zero var widthRulerSize = CGSize.zero if let depthRuler = self.depthRulerView, let widthRuler = self.widthRulerView { depthRulerSize = depthRuler.bounds.size widthRulerSize = widthRuler.bounds.size } let width = metalViewSize.width + depthRulerSize.width let height = metalViewSize.height + widthRulerSize.height return CGSize(width: width, height: height) } } required init?(coder aDecoder: NSCoder) { fatalError("Unimplemented") } required init() { super.init(frame: CGRect.zero) translatesAutoresizingMaskIntoConstraints = false let metalView = MTKView(frame: CGRect.zero) metalView.translatesAutoresizingMaskIntoConstraints = false metalView.device = MTLCreateSystemDefaultDevice() metalView.depthStencilPixelFormat = .invalid metalView.colorPixelFormat = .bgra8Unorm metalView.clearColor = MTLClearColorMake(0, 0, 0, 1) metalView.preferredFramesPerSecond = 120 self.addSubview(metalView) self.metalView = metalView let metalViewXConstraint = NSLayoutConstraint(item: metalView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1.0, constant: 0.0) metalViewXConstraint.isActive = true self.metalViewXConstraint = metalViewXConstraint let metalViewYConstraint = NSLayoutConstraint(item: metalView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0) metalViewYConstraint.isActive = true self.metalViewYConstraint = metalViewYConstraint let metalViewWidthConstraint = NSLayoutConstraint(item: metalView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 0.0) metalViewWidthConstraint.isActive = true self.metalViewWidthConstraint = metalViewWidthConstraint let metalViewHeightConstraint = NSLayoutConstraint(item: metalView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 0.0) metalViewHeightConstraint.isActive = true self.metalViewHeightConstraint = metalViewHeightConstraint } func widthRuler() -> UIView? { guard self.hatchMarkSpacingXDirection > 0 else { return nil } let halfWidth = (Double(self.metalViewSize.width) * self.hatchMarkSpacingXDirection) / 2.0 let ruler = Ruler(withStart: -halfWidth, stop: halfWidth, orientation: .Horizontal, spacing: hatchMarkSpacingXDirection) guard let rulerLayer = ruler.drawRuler() else { return nil } let size = ruler.size() let startHatchMarkPosition = CGFloat(ruler.startPosition) let frame = CGRect(origin: CGPoint.zero, size: size) let rulerView = UIView(frame: frame) rulerView.backgroundColor = UIColor.white rulerView.translatesAutoresizingMaskIntoConstraints = false rulerView.layer.addSublayer(rulerLayer) self.addSubview(rulerView) guard let metalView = self.metalView else { return nil } self.metalViewXConstraint?.constant = startHatchMarkPosition self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[rulerView]", options: [], metrics: nil, views: ["metalView": metalView, "rulerView": rulerView])) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[metalView][rulerView]", options: [], metrics: nil, views: ["metalView": metalView, "rulerView": rulerView])) rulerView.addConstraint(NSLayoutConstraint(item: rulerView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: size.width)) rulerView.addConstraint(NSLayoutConstraint(item: rulerView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: size.height)) return rulerView } func depthRuler() -> UIView? { guard self.hatchMarkSpacingZDirection > 0 else { return nil } let depth = Double(self.metalViewSize.height) * self.hatchMarkSpacingZDirection let ruler = Ruler(withStart: 0, stop: depth, orientation: .Vertical, spacing: hatchMarkSpacingZDirection) guard let rulerLayer = ruler.drawRuler() else { return nil } let size = ruler.size() let startHatchMarkPosition = CGFloat(ruler.startPosition) let frame = CGRect(origin: CGPoint.zero, size: size) let rulerView = UIView(frame: frame) rulerView.backgroundColor = UIColor.white rulerView.translatesAutoresizingMaskIntoConstraints = false rulerView.layer.addSublayer(rulerLayer) self.addSubview(rulerView) guard let metalView = self.metalView else { return nil } self.metalViewYConstraint?.constant = startHatchMarkPosition self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[metalView][rulerView]", options: [], metrics: nil, views: ["metalView": metalView, "rulerView": rulerView])) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[rulerView]", options: [], metrics: nil, views: ["metalView": metalView, "rulerView": rulerView])) rulerView.addConstraint(NSLayoutConstraint(item: rulerView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: size.width)) rulerView.addConstraint(NSLayoutConstraint(item: rulerView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: size.height)) return rulerView } }
// // EditProfileController.swift // layout // // Created by Rama Agastya on 14/09/20. // Copyright © 2020 Rama Agastya. All rights reserved. // import UIKit class EditProfileController: UIViewController { @IBOutlet weak var IVEditProfile: UIImageView! @IBOutlet weak var ETName: UITextField! @IBOutlet weak var ETEmail: UITextField! @IBOutlet weak var ETNumber: UITextField! @IBOutlet weak var ETAddress: UITextField! @IBAction func btnSubmit(_ sender: Any) { self.updateProfile(updateEmail: (ETEmail.text ?? ""), updateName: (ETName.text ?? ""), updatePhone: (ETNumber.text ?? ""), updateAddress: (ETAddress.text ?? "")){ self.dialogMessage() } } var dataUser:UserSingle! override func viewDidLoad() { super.viewDidLoad() getData { self.ETName.text? = self.dataUser!.user.name self.ETNumber.text? = self.dataUser!.user.phone self.ETEmail.text? = self.dataUser!.user.email self.ETAddress.text? = self.dataUser!.user.address if let imageURL = URL(string: self.dataUser!.user.photo_image_url) { DispatchQueue.global().async { let data = try? Data(contentsOf: imageURL) if let data = data { let image = UIImage(data: data) DispatchQueue.main.async { self.IVEditProfile.image = image } } } } } } func dialogMessage() { let dialogMessage = UIAlertController(title: "Hi " + dataUser!.user.name, message: "Successfully Update Profile", preferredStyle: .alert) let submit = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in self.navigationController?.popViewController(animated: true) }) dialogMessage.addAction(submit) self.present(dialogMessage, animated: true, completion: nil) } func updateProfile(updateEmail:String, updateName:String, updatePhone:String, updateAddress:String, completed: @escaping () -> ()) { let url = GlobalVariable.urlUpdateProfile var components = URLComponents(string: url)! components.queryItems = [ URLQueryItem(name: "email", value: updateEmail), URLQueryItem(name: "name", value: updateName), URLQueryItem(name: "phone", value: updatePhone), URLQueryItem(name: "address", value: updateAddress) ] components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B") var request = URLRequest(url:components.url!) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue(UserDefaults.standard.string(forKey: "Token")!, forHTTPHeaderField: "Authorization") URLSession.shared.dataTask(with: request) { (data, response, error) in if error == nil { DispatchQueue.main.async { completed() } } }.resume() } func getData(completed: @escaping () -> ()){ let url = GlobalVariable.urlGetAccount let components = URLComponents(string: url)! var request = URLRequest(url:components.url!) request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue(UserDefaults.standard.string(forKey: "Token")!, forHTTPHeaderField: "Authorization") URLSession.shared.dataTask(with: request) { (data, response, error) in if error == nil { do { self.dataUser = try JSONDecoder().decode(UserSingle.self, from: data!) DispatchQueue.main.async { completed() } } catch { print("JSON Error") } } }.resume() } }
import Foundation public protocol JSONDecoder { func decode<T>(_ type: T.Type, from data: Data) throws -> T where T: Decodable } extension Foundation.JSONDecoder: JSONDecoder {}
// // Waypoint.swift // Prototype // // Created by Oleg Gnashuk on 1/26/16. // Copyright © 2016 Oleg Gnashuk. All rights reserved. // import MapKit class Waypoint: NSObject, MKAnnotation { var latitude: Double! var longitude: Double! var title: String! var subtitle: String! var imageURL: String! // init(latitude: Double, longitude: Double, title: String, subtitle: String) { // self.latitude = latitude // self.longitude = longitude // self.title = title // self.subtitle = subtitle // } var coordinate: CLLocationCoordinate2D { get { return CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } set { latitude = newValue.latitude longitude = newValue.longitude } } }
// // FavoriteBeerInteractor.swift // Bebida-Fractal // // Created by Fernanda de Lima on 15/12/2017. // Copyright © 2017 Empresinha. All rights reserved. // import Foundation class FavoriteBeerInteractor: FavoriteBeerInteractorInputProtocol{ weak var presenter: FavoriteBeerInteractorOutputProtocol? var localDatamanager: FavoriteBeerLocalDataManagerInputProtocol? func retrieveFavoriteBeer() { do { if let favoriteBeers = try localDatamanager?.retrieveFavoriteBeer() { var favoriteList: [FavoriteBeer] = [] for f in favoriteBeers{ let favor = FavoriteBeer() favor.tagLine = f.tagLine favor.title = f.title favor.content = f.content favor.imageUrl = f.imageUrl favoriteList.append(favor) } if favoriteList.isEmpty { presenter?.didRetrieveBeers([]) }else{ presenter?.didRetrieveBeers(favoriteList) } } } catch { presenter?.didRetrieveBeers([]) } } func updateFavoriteBeer() { do { if let favoriteBeers = try localDatamanager?.retrieveFavoriteBeer() { var favoriteList: [FavoriteBeer] = [] for f in favoriteBeers{ let favor = FavoriteBeer() favor.tagLine = f.tagLine favor.title = f.title favor.content = f.content favor.imageUrl = f.imageUrl favoriteList.append(favor) } if favoriteList.isEmpty { presenter?.updateFavoriteBeers([]) }else{ presenter?.updateFavoriteBeers(favoriteList) } } } catch { presenter?.updateFavoriteBeers([]) } } } extension FavoriteBeerInteractor: FavoriteBeerLocalDataManagerOutputProtocol { func updateFavoriteBeers(_ favorites: [FavoriteBeer]) { presenter?.updateFavoriteBeers(favorites) } func onBeersRetrieved(_ favorites: [FavoriteBeer]) { presenter?.didRetrieveBeers(favorites) } func onError() { presenter?.onError() } }
// // BootViewController.swift // finalProject // // Created by Juncheng Xu on 2/27/17. // Copyright © 2017 Juncheng Xu. All rights reserved. // import UIKit import CoreData class BootViewController: UIViewController { @IBOutlet weak var tf_username: UITextField! @IBOutlet weak var tf_password: UITextField! let coreData = BaseCoreData() override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { if(haveUser()){ UserConfig.User = coreData.findCoreData(entityName: "Userinfo", predicate: nil) self.performSegue(withIdentifier: "login", sender: self) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func click_addUser(_ sender: Any) { if tf_username.text == nil && (tf_username.text?.isEmpty)!{ Alert.show("username is empty", view: self) return } if tf_password.text == nil && (tf_password.text?.isEmpty)!{ Alert.show("password is empty", view: self) return } let username = tf_username.text! let password = tf_password.text! let codition = "username == %@" let predicate = NSPredicate(format: codition,username) if (coreData.findCoreData(entityName: "Userinfo", predicate: predicate) != nil){ Alert.show("User already exists", view: self) return } let context = coreData.getContext() let entity = NSEntityDescription.entity(forEntityName: "Userinfo", in: context) let Userinfo = NSManagedObject(entity: entity!, insertInto: context) Userinfo.setValue(username, forKey: "username") Userinfo.setValue(password, forKey: "password") do{ try context.save() // Alert.show("success", view: self) UserConfig.User = Userinfo self.performSegue(withIdentifier: "showMainPage", sender: self) }catch{ Alert.show("error", view: self) } } func haveUser()->Bool{ if let object = coreData.findAllCoreDate(entityName: "Userinfo", predicate:nil ){ if object.count>0{ return true } return false } return false } }
// // XYProfileCell.swift // XYReadBook // // Created by tsaievan on 2017/9/4. // Copyright © 2017年 tsaievan. All rights reserved. // import UIKit class XYProfileCell: XYBasicCell { var accView: UIView? var accViewName: String? { didSet { guard let cls = NSClassFromString(model?.accessViewName ?? "") as? UIView.Type else { return } accView = cls.init() if let accView = accView { (accView as? UIImageView)?.image = (#imageLiteral(resourceName: "enter")) addSubview(accView) accView.snp.makeConstraints{ (make) in make.centerY.equalTo(self) make.right.equalTo(self).offset(-16) } } } } }
// // CircleView.swift // ChuaBTAutoLayout // // Created by Taof on 11/23/19. // Copyright © 2019 Taof. All rights reserved. // import UIKit @IBDesignable class CircleView: UIView { @IBInspectable var radius: CGFloat = 0.0 @IBInspectable var fillColor: UIColor = .red override func draw(_ rect: CGRect) { let path = UIBezierPath(roundedRect: rect, cornerRadius: radius) fillColor.setFill() path.fill() let shapeLayer = CAShapeLayer() shapeLayer.path = path.cgPath self.layer.addSublayer(shapeLayer) self.layer.mask = shapeLayer } }
// // LandmarkDetail.swift // Landmarks_2021 // // Created by USER on 2021/05/09. // import SwiftUI struct LandmarkDetail: View { var landmark: Landmark var body: some View { VStack { MapView(coordinates: landmark.coordinates) .ignoresSafeArea(edges: .top) .frame(height: 250) CircleImage(landmark: landmark) .offset(y: -130) .padding(.bottom, -130) VStack(alignment: .leading) { Text(landmark.name) .font(.title) HStack { Text(landmark.park) .font(.subheadline) Spacer() Text(landmark.state) .font(.subheadline) } .font(.subheadline) .foregroundColor(.secondary) Divider() Text("About \(landmark.name)") .font(.title2) Text(landmark.description) } .padding() Spacer() } } } struct LandmarkDetail_Previews: PreviewProvider { static var previews: some View { LandmarkDetail(landmark: Landmark( name: "Turtle Rock", category: "Rivers", city: "Twentynine Palms", state: "California", id: 1001, isFeatured: true, isFavorite: true, park: "Joshua Tree National Park", description: "description ...", imageName: "turtlerock", coordinates: Landmark.Coordinate( latitude: 34.011286, longitude: -116.166868) ) ) .previewDevice("iPhone 12") } }
// // TestInfoTests.swift // TestInfoTests // // Created by Thiago Santos on 02/10/2018. // Copyright © 2018 Thiago Santos. All rights reserved. // import XCTest @testable import TestInfo class TestInfoTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testEmptyItems() { let home = Homewireframe().make()?.topViewController as! HomeViewController XCTAssertTrue(home.items.count == 0 , "Error não esta vazio") } func testPresenterIsNull(){ let home = Homewireframe().make()?.topViewController as! HomeViewController XCTAssertTrue(home.presenter != nil , "Error seu presenter esta nulo") } func testCheckApi(){ let data = loadJson(filename: "capa") XCTAssertTrue(data != nil, "Error não esta vazio") XCTAssertTrue(data?.count == 14, "Error api não contem esse numero exatos") } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
// // TimeIntervalExtension.swift // PaypayCurrencyConverter // // Created by Chung Han Hsin on 2021/3/8. // import Foundation extension TimeInterval { func isExceed(refreshedSeconds: Double = 30 * 60) -> Bool { let date = Date(timeIntervalSince1970: self) var passedTimeInterval = date.timeIntervalSinceNow passedTimeInterval = TimeInterval(-Int(passedTimeInterval)) if passedTimeInterval > refreshedSeconds || passedTimeInterval == refreshedSeconds { return true } return false } }
// // Settings.swift // Oak // // Created by Alex Catchpole on 31/01/2021. // import SwiftUI import Resolver enum SettingsKey: String { case failedToDeleteZone = "failedToDeleteZone" case iCloudEnabled = "iCloudEnabled" case requireAuthOnStart = "requireAuthOnStart" case biometricsEnabled = "biometricsEnabled" case isSetup = "isSetup" } protocol Settings { func bool(key: SettingsKey) -> Bool func set(key: SettingsKey, value: Any) } class RealSettings: Settings { func bool(key: SettingsKey) -> Bool { return UserDefaults.standard.bool(forKey: key.rawValue) } func set(key: SettingsKey, value: Any) { UserDefaults.standard.set(value, forKey: key.rawValue) } } extension Resolver { static func RegisterSettingsUtil() { register { RealSettings() as Settings }.scope(.shared) } }
// // CustomInputAccessoryView.swift // ChatApp // // Created by L on 2021/9/18. // import UIKit protocol CustomInputAccessoryViewDelegate: AnyObject { func inputView(_ inputView: CustomInputAccessoryView, send message: String) } class CustomInputAccessoryView: UIView { // MARK: - Properties weak var delegate: CustomInputAccessoryViewDelegate? private let messageInputTextView: UITextView = { let textView = UITextView() textView.font = UIFont.systemFont(ofSize: 16) textView.isScrollEnabled = false return textView }() private lazy var sendButton: UIButton = { let button = UIButton(type: .system) button.setTitle("Send", for: .normal) button.setTitleColor(.systemBlue, for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16) button.addTarget(self, action: #selector(sendMessage), for: .touchUpInside) return button }() private let placeholderLabel: UILabel = { let label = UILabel() label.text = "Enter Message" label.font = UIFont.systemFont(ofSize: 16) label.textColor = .lightGray return label }() // MARK: - Lifecycle override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .white //自動調整高度 autoresizingMask = .flexibleHeight layer.shadowOpacity = 0.3 layer.shadowRadius = 10 layer.shadowOffset = .init(width: 0, height: -8) layer.shadowColor = UIColor.lightGray.cgColor addSubview(sendButton) sendButton.snp.makeConstraints { make in make.top.equalToSuperview().offset(4) make.right.equalToSuperview().offset(-10) make.size.equalTo(50) } addSubview(messageInputTextView) messageInputTextView.snp.makeConstraints { make in make.top.equalToSuperview().offset(10) make.left.equalToSuperview().offset(5) make.right.equalTo(sendButton.snp.left).offset(-5) make.bottom.equalTo(safeAreaLayoutGuide).offset(-10) } addSubview(placeholderLabel) placeholderLabel.snp.makeConstraints { make in make.left.equalTo(messageInputTextView).offset(5) make.centerY.equalTo(messageInputTextView) } NotificationCenter.default.addObserver(self, selector: #selector(textInputChange), name: UITextView.textDidChangeNotification, object: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var intrinsicContentSize: CGSize { return .zero } // MARK: - Selectors @objc func textInputChange() { placeholderLabel.isHidden = !messageInputTextView.text.isEmpty } @objc func sendMessage() { guard let message = messageInputTextView.text else { return } delegate?.inputView(self, send: message) } // MARK: - Helpers func clearMessageText() { messageInputTextView.text = nil placeholderLabel.isHidden = false } }
// // NSFirebase.swift // Pictlonis // // Created by Manuel Teissier on 05/10/2020. // import UIKit import Firebase class SIFirebase { let firebaseCallback = "firebaseCallback" let cleanCanvasCallback = "cleanCanvasCallback" let newColorCallback = "newColorCallback" static let sharedInstance = SIFirebase() var firebaseHandler = DatabaseHandle() private init() { firebaseHandler = ref.observe(.childAdded, with: { (snapshot:DataSnapshot!) -> Void in NotificationCenter.default.post(name: NSNotification.Name(rawValue: self.firebaseCallback), object: nil, userInfo: ["send": snapshot as Any]) }) } let pathsInLine = NSMutableSet() let ref = Database.database().reference() func testUnit(text: String) { ref.setValue(text) } func resetValues() { ref.setValue("") } func addPath(path: FBPath) -> String { let FBKey = ref.childByAutoId() pathsInLine.add(FBKey) // print("SENDING ===> \(path)") FBKey.setValue(path.serialize()) { (error, ref: DatabaseReference!) -> Void in if let error = error { print("Error encountered while saving path in Firebase \(error.localizedDescription)") } else { self.pathsInLine.remove(FBKey) } } return FBKey.key! } }
// // EPBarButtonItem.swift // EPNavController // // Created by Paige Sun on 2019-07-07. // Copyright © 2019 Paige Sun. All rights reserved. // import Foundation public enum EPNavBarCenter { case title(_ text: String) case image(_ image: UIImage, height: CGFloat) } public struct EPBarButtonItem { let title: String let didTapButton: (() -> Void)? public init(title: String, didTapButton: (() -> Void)?) { self.title = title self.didTapButton = didTapButton } }
// // ConfiramcionPizzaController.swift // PizzaWatch // // Created by Jesús de Villar on 23/4/16. // Copyright © 2016 JdeVillar. All rights reserved. // import WatchKit import Foundation class ConfiramcionPizzaController: WKInterfaceController { @IBOutlet var tamano: WKInterfaceLabel! @IBOutlet var masa: WKInterfaceLabel! @IBOutlet var queso: WKInterfaceLabel! @IBOutlet var ingredientes: WKInterfaceLabel! @IBAction func NavegaAInicio() { pushControllerWithName("inicio", context:nil) } @IBAction func Canfirmacion() { pushControllerWithName("alHorno", context:nil) } override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) let c = context as! Valor var tipoQueso = "" if c.tipoQueso == "Sin Queso" { tipoQueso = c.tipoQueso } else { tipoQueso = "con Queso \(c.tipoQueso)" } self.tamano.setText("Pizza \(c.tamanoPizza)") self.masa.setText("con masa \(c.tipoMasa)") self.queso.setText(tipoQueso) var ingreConcatenados: String = "" for i in 0...c.ingredientesSeleccionados.count - 1 { if i > 0 { if ((i == c.ingredientesSeleccionados.count - 1) && (c.ingredientesSeleccionados.count > 1)){ ingreConcatenados = ingreConcatenados + " y " } else { ingreConcatenados = ingreConcatenados + ", " } } ingreConcatenados = ingreConcatenados + " \(c.ingredientesSeleccionados[i])" } self.ingredientes.setText(ingreConcatenados) } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } }
// // ViewsVC.swift // Surface // // Created by Appinventiv Mac on 10/04/18. // Copyright © 2018 Appinventiv. All rights reserved. // import UIKit class ViewsVC: UIViewController { @IBOutlet weak var headerViews: UIView! @IBOutlet weak var viewsCountLabel: UILabel! @IBOutlet weak var viewsTabelView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.registerCells() self.setUpViews() } func registerCells(){ viewsTabelView.register(UINib(nibName: "TagPeopleTVC", bundle: nil), forCellReuseIdentifier: "TagPeopleTVC") viewsTabelView.delegate = self viewsTabelView.dataSource = self } func setUpViews(){ self.headerViews.layer.cornerRadius = 12 self.headerViews.clipsToBounds = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func popVCButton(_ sender: UIButton) { let _ = self.navigationController?.popViewController(animated: true) } } extension ViewsVC:UITableViewDataSource,UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = viewsTabelView.dequeueReusableCell(withIdentifier: "TagPeopleTVC", for: indexPath) as? TagPeopleTVC else { return UITableViewCell()} cell.userNameLabel.text = "sri_arpit" cell.nameLabel.text = "Arpit Srivastava" cell.profileImageView.image = UIImage(named: "1") cell.selectImageView.isHidden = true return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 90 } }
// // RequestViewController.swift // ParseStarterProject-Swift // // Created by Loaner on 11/30/15. // Copyright © 2015 Parse. All rights reserved. // import UIKit import Parse import MapKit class RequestViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet var map: MKMapView! @IBAction func pickUpRider(sender: AnyObject) { //perform a query in the when the button is tapped. Find the requestUsername var query = PFQuery(className:"riderRequest") //can unwrap both the current user and the username because it has already been checked at this point query.whereKey("username", equalTo: requestUsername) query.findObjectsInBackgroundWithBlock {(objects: [PFObject]?, error: NSError?) -> Void in if error == nil { // The find succeeded // Do something with the found objects. did not need to cast objects as a PFObject since it already is a PFObject if let objects = objects { for object in objects { //this will create a driverResponded in parse object["driverResponded"] = PFUser.currentUser()!.username! //then save the object in parse. Needs the do/try/catch do { try object.save() } catch {} //added in since the example did not save the driver's username in driverResponded. The difference here is instead of just saving the object, it's querying for the objectId then saving that into parse var query = PFQuery(className: "riderRequest") //query to get the current user's id query.getObjectInBackgroundWithId(object.objectId!, block: { (object: PFObject?, error) -> Void in //check for errors if error != nil { print(error) } else if let object = object { //if there are no errors, save the cuser's username in driverResponded //if this still does not save the username in parse, check the ACL and make sure it has "Public Read Write" object["driverResponded"] = PFUser.currentUser()!.username! object.saveInBackground() let requestCLLocation = CLLocation(latitude: self.requestLocation.latitude, longitude: self.requestLocation.longitude) //the CLGeocoder should return an array of placemarks of CLPlaceMarks type CLGeocoder().reverseGeocodeLocation(requestCLLocation, completionHandler: { (placemarks, error) -> Void in if error != nil { print(error!) } else { if placemarks!.count > 0 { //take the first placemarks from the array (placemark) let pm = placemarks![0] as! CLPlacemark //convert a CLPlacemark to a MKPlacemark let mkPm = MKPlacemark(placemark: pm) //from stackOF. Need to get your current address using PlaceMark. Need to convert from CLLocation2D to a placemark var mapItem = MKMapItem(placemark: mkPm) mapItem.name = self.requestUsername //You could also choose: MKLaunchOptionsDirectionsModeWalking var launchOptions = [MKLaunchOptionsDirectionsModeKey : MKLaunchOptionsDirectionsModeDriving] mapItem.openInMapsWithLaunchOptions(launchOptions) } else { print("Problem with the data received from geocoder") } } }) } }) } } else { // Log details of the failure print(error) } } } } //store the location. This is the same type as the DriverViewController's location var. Make sure to initialize the variables with a default value or it runs into an initializer error var requestLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(0, 0) var requestUsername: String = "" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. print(requestUsername) print(requestLocation) let region = MKCoordinateRegion(center: requestLocation, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) //then updates the mapview self.map.setRegion(region, animated: true) //before adding the new annotation, remove all annotations from the map self.map.removeAnnotations(map.annotations) //creates a MKPointAnnotation object manager var objectAnnotation = MKPointAnnotation() //displays the pinLocation objectAnnotation.coordinate = requestLocation objectAnnotation.title = requestUsername //this adds the annotation to the mapview and the map view object in storyboard self.map.addAnnotation(objectAnnotation) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // CGPath+FastIntersections.swift // CGPathIntersection // // Created by Mohsen Alijanpour on 28/11/2018. // Copyright © 2018 Cal Stephens. All rights reserved. // import CoreGraphics public class CachedDiffablePath { public var pathImage: CGPathImage public init(from path: CGPath) { pathImage = CGPathImage(from: path) } public func intersects(path: CachedDiffablePath) -> Bool { return !self.pathImage.intersectionPoints(with: path.pathImage).isEmpty } public func intersectionPoints(with path: CachedDiffablePath) -> [CGPoint] { return self.pathImage.intersectionPoints(with: path.pathImage) } }
// // LoginController.swift // NLBKlik // // Created by WF | Gorjan Shukov on 10/3/16. // Copyright © 2016 WF | Gorjan Shukov. All rights reserved. // import UIKit import SnapKit class LoginController: BaseViewController, LoginView { private var presenter: LoginPresenter private var scrollView: UIScrollView! private var contentView: UIView! private var activeField: UITextField? private var logoImageView: UIImageView! private var usernameTextField: UITextField! private var passwordTextField: UITextField! private var loginButton: UIButton! private var rememberMeLabel: UILabel! private var rememberMeSwitch: UISwitch! private var autoLoginLabel: UILabel! private var autoLoginSwitch: UISwitch! private var animationView: AnimationView! init(presenter: LoginPresenter) { self.presenter = presenter super.init() registerForKeyboardNotifications() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { deregisterFromKeyboardNotifications() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) presenter.attachView(self) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) presenter.detachView(self) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() scrollView.contentSize = CGSizeMake(UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.width) } override func setupViews() { super.setupViews() view.backgroundColor = UIColor.whiteColor() scrollView = UIScrollView() scrollView.scrollEnabled = false scrollView.delaysContentTouches = false scrollView.canCancelContentTouches = false contentView = UIView() contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))) logoImageView = UIImageView(image: UIImage(named: "NLBLogo")) logoImageView.contentMode = UIViewContentMode.ScaleAspectFit usernameTextField = UITextField() usernameTextField.tag = 0 usernameTextField.font = UIFont.systemFontOfSize(20) usernameTextField.autocapitalizationType = UITextAutocapitalizationType.None usernameTextField.returnKeyType = UIReturnKeyType.Next usernameTextField.placeholder = "Username" usernameTextField.leftView = UIImageView(image: UIImage(named: "User")) usernameTextField.leftViewMode = UITextFieldViewMode.Always usernameTextField.addBorder(edges: .Bottom, colour: UIColor.grayColor().colorWithAlphaComponent(0.7)) usernameTextField.autocorrectionType = .No usernameTextField.autocapitalizationType = .None usernameTextField.delegate = self passwordTextField = UITextField() passwordTextField.tag = 1 passwordTextField.font = UIFont.systemFontOfSize(20) passwordTextField.returnKeyType = UIReturnKeyType.Go passwordTextField.placeholder = "Password" passwordTextField.secureTextEntry = true passwordTextField.leftView = UIImageView(image: UIImage(named: "Lock")) passwordTextField.leftViewMode = UITextFieldViewMode.Always passwordTextField.delegate = self loginButton = UIButton() loginButton.setTitle("Log In", forState: .Normal) loginButton.layer.cornerRadius = 5 loginButton.backgroundColor = UIColor.customPurple() loginButton.addTarget(self, action: #selector(loginButtonTapped), forControlEvents: .TouchUpInside) rememberMeSwitch = UISwitch() rememberMeSwitch.transform = CGAffineTransformMakeScale(0.75, 0.75) rememberMeSwitch.onTintColor = UIColor.customPurple() rememberMeSwitch.on = true rememberMeSwitch.addTarget(self, action: #selector(rememberMeSwitchChangedValue(_:)), forControlEvents: .ValueChanged) rememberMeLabel = UILabel() rememberMeLabel.font = rememberMeLabel.font.fontWithSize(14) rememberMeLabel.text = "Remember Me" rememberMeLabel.textColor = UIColor.blackColor().colorWithAlphaComponent(0.6) autoLoginSwitch = UISwitch() autoLoginSwitch.transform = CGAffineTransformMakeScale(0.75, 0.75) autoLoginSwitch.onTintColor = UIColor.customPurple() autoLoginLabel = UILabel() autoLoginLabel.font = rememberMeLabel.font.fontWithSize(14) autoLoginLabel.text = "Auto Login" autoLoginLabel.textColor = UIColor.blackColor().colorWithAlphaComponent(0.6) animationView = AnimationView(frame: UIScreen.mainScreen().bounds) contentView.addSubview(logoImageView) contentView.addSubview(usernameTextField) contentView.addSubview(passwordTextField) contentView.addSubview(loginButton) contentView.addSubview(rememberMeSwitch) contentView.addSubview(rememberMeLabel) contentView.addSubview(autoLoginSwitch) contentView.addSubview(autoLoginLabel) scrollView.addSubview(contentView) view.addSubview(scrollView) view.addSubview(animationView) } override func setupConstraints() { super.setupConstraints() let horizontalMargin = UIScreen.mainScreen().bounds.width / 8 let topMargin = UIScreen.mainScreen().bounds.height / 7 let imageHeight = (531 / (993 / (4 * horizontalMargin))) scrollView.snp_makeConstraints { (make) in make.edges.equalTo(self.view) } contentView.snp_makeConstraints { (make) in make.edges.equalTo(scrollView) make.width.equalTo(scrollView.snp_width) make.height.equalTo(scrollView.snp_height) } logoImageView.snp_makeConstraints { (make) in make.top.equalTo(self.contentView.snp_top).offset(topMargin) make.left.equalTo(self.contentView.snp_left).offset(2 * horizontalMargin) make.right.equalTo(self.contentView.snp_right).offset(2 * (-horizontalMargin)) make.height.equalTo(imageHeight) } usernameTextField.snp_makeConstraints { (make) in make.top.equalTo(logoImageView.snp_bottom).offset(topMargin) make.left.equalTo(self.contentView.snp_left).offset(horizontalMargin) make.right.equalTo(self.contentView.snp_right).offset(-horizontalMargin) make.height.equalTo(40) } passwordTextField.snp_makeConstraints { (make) in make.top.equalTo(usernameTextField.snp_bottom) make.left.equalTo(usernameTextField.snp_left) make.right.equalTo(usernameTextField.snp_right) make.height.equalTo(40) } loginButton.snp_makeConstraints { (make) in make.top.equalTo(passwordTextField.snp_bottom).offset(20) make.left.equalTo(usernameTextField.snp_left) make.right.equalTo(usernameTextField.snp_right) make.height.equalTo(40) } rememberMeSwitch.snp_makeConstraints { (make) in make.top.equalTo(loginButton.snp_bottom).offset(10) make.right.equalTo(logoImageView.snp_right) } rememberMeLabel.snp_makeConstraints { (make) in make.top.equalTo(rememberMeSwitch.snp_top).offset(6) make.right.equalTo(rememberMeSwitch.snp_left) } autoLoginSwitch.snp_makeConstraints { (make) in make.top.equalTo(rememberMeSwitch.snp_bottom).offset(5) make.right.equalTo(rememberMeSwitch.snp_right) } autoLoginLabel.snp_makeConstraints { (make) in make.top.equalTo(autoLoginSwitch.snp_top).offset(6) make.right.equalTo(autoLoginSwitch.snp_left) } // let test = NetworkManager.sharedInstance.tempTest() // view.addSubview(test) // test.snp_makeConstraints { (make) in // make.left.right.bottom.equalTo(self.view) // make.top.equalTo(loginButton.snp_bottom) // } } func rememberMeSwitchChangedValue(sender: UISwitch) { if (sender.on) { autoLoginSwitch.enabled = true } else { autoLoginSwitch.enabled = false } } func dismissKeyboard() { usernameTextField.resignFirstResponder() passwordTextField.resignFirstResponder() } func loginButtonTapped() { var userData = [String: AnyObject]() userData[UserDataKeys.username] = usernameTextField.text userData[UserDataKeys.password] = passwordTextField.text userData[UserDataKeys.rememberMe] = rememberMeSwitch.on userData[UserDataKeys.autoLogin] = (rememberMeSwitch.on == true) ? autoLoginSwitch.on : false presenter.login(userData) } func setContent(user: User) { usernameTextField.text = user.username passwordTextField.text = user.password rememberMeSwitch.on = true autoLoginSwitch.on = user.autoLogin if (autoLoginSwitch.on) { loginButtonTapped() } } func animate(shouldAnimate animate: Bool) { if (animate) { dismissKeyboard() } animationView.animate(animate) } func showNextScreen() { presentViewController(MainAssembly.sharedInstance.getMainController(), animated: true, completion: nil) } func showLoginError() { presentViewController(AlertFactory.loginError(), animated: true, completion: nil) } func showConnectionError() { let iOSVerzion = NSProcessInfo().operatingSystemVersion.majorVersion if (iOSVerzion <= 9) { presentViewController(AlertFactory.connectionError(), animated: true, completion: nil) } else { AlertFactory.connectionErrorIOS10() } } } extension LoginController: UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField) -> Bool { if (textField.tag == 0) { passwordTextField.becomeFirstResponder() } else { textField.resignFirstResponder() loginButtonTapped() } return true } func textFieldDidBeginEditing(textField: UITextField) { activeField = textField } func textFieldDidEndEditing(textField: UITextField) { activeField = nil } func registerForKeyboardNotifications() { // Adding notifies on keyboard appearing NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginController.keyboardWasShown(_:)), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginController.keyboardWillBeHidden(_:)), name: UIKeyboardWillHideNotification, object: nil) } func deregisterFromKeyboardNotifications() { // Removing notifies on keyboard appearing NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } func keyboardWasShown(notification: NSNotification) { // Need to calculate keyboard exact size due to Apple suggestions self.scrollView.scrollEnabled = true let info: NSDictionary = notification.userInfo! let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0) self.scrollView.contentInset = contentInsets self.scrollView.scrollIndicatorInsets = contentInsets var aRect: CGRect = self.view.frame aRect.size.height -= keyboardSize!.height if let activeFieldPresent = activeField { if (!CGRectContainsPoint(aRect, activeFieldPresent.frame.origin)) { self.scrollView.scrollRectToVisible(activeFieldPresent.frame, animated: true) } } } func keyboardWillBeHidden(notification: NSNotification) { // Once keyboard disappears, restore original positions let info: NSDictionary = notification.userInfo! let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0) self.scrollView.contentInset = contentInsets self.scrollView.scrollIndicatorInsets = contentInsets self.view.endEditing(true) self.scrollView.scrollEnabled = false } }
// // ViewController.swift // iNote // // Created by Arthur Ataide on 2020-06-05. // Copyright © 2020 Arthur Ataide and Jose Marmolejos. All rights reserved. // import UIKit import CLTypingLabel class WelcomeViewController: UIViewController { @IBOutlet weak var titleLabel: CLTypingLabel! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.isNavigationBarHidden = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.isNavigationBarHidden = false } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. titleLabel.text = "iNotes" titleLabel.charInterval = 0.5 } }
// // MovieViewController.swift // OneMovie // // Created by Ahmet Celikbas on 20/06/2017. // Copyright © 2017 Ahmet Celikbas. All rights reserved. // import UIKit import TMDBSwift import JHSpinner class MovieViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var movieId = Int() var TableArray = [CastingMakup]() @IBOutlet weak var MovieTitle: UILabel! @IBOutlet var CastingTableView: UITableView! @IBOutlet var MovieGenre: UILabel! @IBOutlet var MovieDateAndLikes: UILabel! @IBOutlet var MovieImage: UIImageView! @IBOutlet var MovieOverview: UITextView! @IBOutlet var MovieTrailer: UIWebView! override func viewDidLoad() { super.viewDidLoad() self.MovieTitle.text = "" self.MovieGenre.text = "" self.MovieDateAndLikes.text = "" self.MovieOverview.text = "" self.MovieTrailer.allowsInlineMediaPlayback = true self.MovieTrailer.scrollView.isScrollEnabled = false self.MovieTrailer.scrollView.bounces = false self.loadTmdbData() self.CastingTableView.delegate = self self.CastingTableView.dataSource = self // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func closeModal(_ sender: UIButton) { print("close modal") self.dismiss(animated: true) {} } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { print(TableArray.count) return TableArray.count } // Set cell content for each rows of TableArray func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "castingCell", for: indexPath) as! CastingTableViewCell cell.CastingActorLabel.text = TableArray[indexPath.row].name cell.CastingRoleLabel.text = TableArray[indexPath.row].character cell.CastingImageView.downloadImage(from: TableArray[indexPath.row].profile_path) return cell } func loadTmdbData() { let spinner = JHSpinnerView.showOnView(view, spinnerColor:UIColor.red, overlay:.circular, overlayColor:UIColor.black.withAlphaComponent(0.9)) self.view.addSubview(spinner) MovieMDB.movie(Config.apiKey, movieID: self.movieId, language: Config.language){ apiReturn, movie in if let movie = movie{ self.MovieTitle.text = movie.title ?? "Titre du film non trouvé" // Get 3 first genre var genreCount = 0 for genre in movie.genres { if(genreCount < 3) { self.MovieGenre.text = self.MovieGenre.text! + genre.name! + " " genreCount += 1 } } let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" let date = dateFormatter.date(from: movie.release_date!) dateFormatter.dateFormat = "dd MMM yyyy" self.MovieDateAndLikes.text = dateFormatter.string(from: date!) + " - noté " + String(format:"%.1f", movie.vote_average!) if((movie.backdrop_path) != nil) { self.MovieImage.downloadImage(from: Config.url_backdrop_path + movie.backdrop_path!) } self.MovieOverview.text = movie.overview ?? "" MovieMDB.videos(Config.apiKey, movieID: self.movieId, language: Config.language){ apiReturn, videos in if let videos = videos{ for video in videos { if(video.site == "YouTube") { self.MovieTrailer.loadHTMLString("<iframe width=\"\(self.MovieTrailer.frame.width - 10)\" height=\"\(self.MovieTrailer.frame.height - 10)\" src=\"\(Config.url_youtube_embed + video.key)\" frameborder=\"0\" allowfullscreen></iframe>", baseURL: nil) break } } } } MovieMDB.credits(Config.apiKey, movieID: self.movieId){ apiReturn, credits in if let credits = credits{ var castCount = 0 for cast in credits.cast{ if(castCount <= 6){ // Construct a movie object with the current casting data let castingObject = CastingMakup( name: cast.name ?? "Acteur", character: cast.character ?? "Rôle", profile_path: cast.profile_path ?? "no_profile" ) // Add casting to the tableArray self.TableArray.append(castingObject) castCount += 1 } self.CastingTableView.reloadData() } } } } } spinner.dismiss() } /* // 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. } */ }
// // TMRequestSectionController.swift // consumer // // Created by Gregory Sapienza on 2/13/17. // Copyright © 2017 Human Ventures Co. All rights reserved. // import UIKit import IGListKit protocol TMRequestSectionControllerProtocol { /// Cell has been tapped within TMRequestSectionController section. /// /// - Parameter request: Request representing cell tapped. func cellTapped(request: TMRequest) } class TMRequestSectionController: IGListSectionController { //MARK: - Public iVars /// Request to display in cell. var request: TMRequest? /// Delegate representing TMRequestSectionControllerProtocol. var delegate: TMRequestSectionControllerProtocol? } // MARK: - IGListSectionType extension TMRequestSectionController: IGListSectionType { func numberOfItems() -> Int { return 1 } func sizeForItem(at index: Int) -> CGSize { var cellW: CGFloat = 172.0 var cellH: CGFloat = 220.0 if DeviceType.IS_IPHONE_5 || DeviceType.IS_IPHONE_4_OR_LESS { cellW = 145.0 cellH = 200.0 } else if DeviceType.IS_IPHONE_6P { cellW = 192.0 cellH = 215.0 } let size = CGSize(width: cellW, height: cellH) return size } func cellForItem(at index: Int) -> UICollectionViewCell { guard let cell = collectionContext?.dequeueReusableCell(of: TMRequestCollectionViewCell.self, for: self, at: index) as? TMRequestCollectionViewCell else { fatalError("Cell is incorrect type.") } guard let request = self.request else { fatalError("No request found for cell.") } cell.request = request return cell } func didSelectItem(at index: Int) { guard let request = self.request else { fatalError("No request found for cell.") } delegate?.cellTapped(request: request) } func didUpdate(to object: Any) { request = object as? TMRequest } }
// // EditAlarmTableViewController.swift // AlarmRise // // Created by Tiffany Cai on 5/18/20. // Copyright © 2020 Tiffany Cai. All rights reserved. // import UIKit class EditAlarmTableViewController: UITableViewController { @IBOutlet var editAlarmTableView: UITableView! @IBOutlet weak var datePickerAlarmTime: UIDatePicker! @IBOutlet weak var txtFieldAlarmName: UITextField! @IBOutlet weak var switchSnooze: UISwitch! @IBOutlet weak var labelSnoozeTime: UILabel! @IBOutlet weak var stepperSnoozeTime: UIStepper! @IBOutlet weak var buttonSave: UIBarButtonItem! @IBOutlet weak var buttonCancel: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() } @IBAction func buttonSavePressed(_ sender: Any) { let newAlarm = AlarmEntity(context: DB.context) newAlarm.alarmEnabled = true newAlarm.alarmName = txtFieldAlarmName.text newAlarm.alarmTime = datePickerAlarmTime.date //newItem.snoozeEnabled = //newItem.snoozeTime = stepperSnoozeTime. DB.saveData() //tableAlarms.reloadData() /* AlarmListTableViewController().scheduleNotification(alarmName: txtFieldAlarmName.text, alarmTime: datePickerAlarmTime.date)*/ dismiss(animated: true, completion: nil) } @IBAction func buttonCancelPressed(_ sender: Any) { dismiss(animated: true, completion: nil) } @IBAction func stepperSnoozePressed(_ sender: UIStepper) { let newValue = sender.value self.labelSnoozeTime.text = "\(Int(newValue)) minutes" } }
// // UIImageView+Extension.swift // MovieEnvoy // // Created by Jerry Edens on 4/29/19. // Copyright © 2019 Edens R&D. All rights reserved. // import UIKit import Kingfisher extension UIImageView { struct Constants { static let ShadowViewTag = 0xDEADBEEF } func download(url: String?, showIndicator: Bool = true, placeholder: UIImage? = nil, downsample: Bool = true) { guard let urlString = url, let url = URL(string: urlString) else { image = placeholder return } let imageOptions: KingfisherOptionsInfo = [ .scaleFactor(UIScreen.main.scale), .transition(.fade(0.2)), .cacheOriginalImage ] var kf = self.kf kf.indicatorType = showIndicator ? .activity : .none kf.setImage(with: url, placeholder: placeholder, options: imageOptions) } func cancelDownload() { self.kf.cancelDownloadTask() } func addBlurTransition() { // Add blur effect let blurEffect = UIBlurEffect(style: .regular) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = self.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.addSubview(blurEffectView) // Remove blur effect UIView.animate(withDuration: 0.25, animations: { blurEffectView.alpha = 0 }, completion: { _ in blurEffectView.removeFromSuperview() }) } func addOverlay() { let overlay = UIView() overlay.backgroundColor = .black overlay.alpha = 0.3 self.addSubview(overlay) overlay.translatesAutoresizingMaskIntoConstraints = false overlay.topAnchor.constraint(equalTo: self.topAnchor).isActive = true overlay.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true overlay.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true overlay.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true } func addShadowToImageView(with radius: CGFloat = 5.0, for offsetSize: CGSize = CGSize(width: 0.0, height: 2.0), shadowOpacity: CGFloat = 0.1) { guard let superview = self.superview, superview.viewWithTag(Constants.ShadowViewTag) == nil else { return } let outerView = UIView(frame: self.bounds) outerView.tag = Constants.ShadowViewTag superview.insertSubview(outerView, belowSubview: self) outerView.translatesAutoresizingMaskIntoConstraints = false outerView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true outerView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true outerView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true outerView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true outerView.backgroundColor = .clear outerView.clipsToBounds = false outerView.layer.allowsGroupOpacity = false outerView.layer.cornerRadius = self.layer.cornerRadius outerView.layer.shadowColor = UIColor.black.cgColor outerView.layer.shadowOpacity = Float(shadowOpacity) outerView.layer.shadowRadius = radius outerView.layer.shadowOffset = offsetSize outerView.layer.shadowPath = UIBezierPath(roundedRect: outerView.bounds, cornerRadius: self.layer.cornerRadius).cgPath } func circularize() { layer.cornerRadius = frame.width / 2 layer.masksToBounds = true } func curveBottom(curvedPercent: CGFloat) { guard curvedPercent <= 1 && curvedPercent > 0 else { return } let width = self.bounds.size.width let height = self.bounds.size.height let arrowPath = UIBezierPath() arrowPath.move(to: CGPoint(x: 0, y: 0)) arrowPath.addLine(to: CGPoint(x: width, y: 0)) arrowPath.addLine(to: CGPoint(x: width, y: height - (height * curvedPercent))) arrowPath.addQuadCurve(to: CGPoint(x: 0, y: height - (height * curvedPercent)), controlPoint: CGPoint(x: width / 2, y: height)) arrowPath.addLine(to: CGPoint(x: 0, y: 0)) arrowPath.close() let shapeLayer = CAShapeLayer(layer: layer) shapeLayer.path = arrowPath.cgPath shapeLayer.frame = bounds shapeLayer.masksToBounds = true layer.mask = shapeLayer } }
// // UploadLogs.swift // KayakFirst Ergometer E2 // // Created by Balazs Vidumanszki on 2018. 02. 01.. // Copyright © 2018. Balazs Vidumanszki. All rights reserved. // import Foundation import Alamofire import SwiftyJSON class UploadLogs: ServerService<Bool> { //MARK: properties private let message: String //MARK: init init(message: String) { self.message = message } //MARK: functions override func handleServiceCommunication(alamofireRequest: DataRequest) -> Bool? { return true } override func initUrlTag() -> String { return "uploadLog" } override func initMethod() -> HTTPMethod { return .post } override func initParameters() -> Parameters? { let systemInfos = SystemInfoDbLoader.sharedInstance.loadData(predicate: nil) let logObjest = LogObjectDbLoader.sharedInstance.loadData(predicate: nil) let feedbackDto = FeedbackDto(message: message, systemInfos: systemInfos, logs: logObjest) return feedbackDto.getParameters() } override func initEncoding() -> ParameterEncoding { return JSONEncoding.default } override func getManagerType() -> BaseManagerType { return LogManagerType.send_feedback } }
// // UIViewController+Extension.swift // MJExtension // // Created by chenminjie on 2020/11/7. // import UIKit import RTRootNavigationController import MBProgressHUD extension UIViewController { public enum MJHUDStyle { case light case dark } } extension TypeWrapperProtocol where WrappedType: UIViewController { public static var window: UIWindow? { get { var window: UIWindow? = nil if #available(iOS 13, *) { window = UIApplication.shared.windows.filter{ $0.isKeyWindow }.first } else { window = UIApplication.shared.keyWindow } return window } } /// pop 到指定类型的控制器, return true表示pop成功 @discardableResult public func popTo(controller: AnyClass) -> Bool { guard let vcs = wrappedValue.navigationController?.viewControllers else { return false } var find: UIViewController? for vc in vcs.reversed() { if vc.isMember(of: controller) { find = vc break } } if let tfind = find { wrappedValue.navigationController?.popToViewController(tfind, animated: true) return true } else { return false } } // MARK: 导航栏是否隐藏 public func prefersNavigationBar(hidden: Bool) { if let navigation = wrappedValue.navigationController { navigation.isNavigationBarHidden = hidden } } /// 移除指定的Controller类型的controller /// /// - Parameter controllerTypes: 类数组 public func remove(controllerTypes: [AnyClass]) { guard let vcs = wrappedValue.navigationController?.viewControllers else { return } let res = vcs.filter { (vc) -> Bool in var find = false for type in controllerTypes { if vc.isMember(of: type) { find = true break } } return !find } if res.count < vcs.count { wrappedValue.navigationController?.viewControllers = res } } public func setRightNaviItem(image: UIImage?, target: Any?, selector: Selector) { guard let image = image else { return } let button = UIButton() button.addTarget(self, action: selector, for: .touchUpInside) button.frame = CGRect(x: 0, y: 0, width: 44, height: 44) button.setImage(image, for: .normal) if image.size.width < 44 { button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 44 - image.size.width, bottom: 0, right: 0) } wrappedValue.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button) } @discardableResult public func setRightNaviItem(title: String?, color: UIColor = UIColor.blue, target: Any?, selector: Selector) -> UIButton? { guard let title = title else { return nil } var button = UIButton() button.addTarget(self, action: selector, for: .touchUpInside) button.setTitle(title, for: .normal) button.setTitleColor(color, for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .semibold) button.sizeToFit() button.ext.height = 44 wrappedValue.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button) return button } /// 获取当前控制器 public static func currentViewController() -> UIViewController? { if let vc = UIApplication.shared.keyWindow?.rootViewController { return Self.findBestViewController(vc: vc) } return nil } private static func findBestViewController(vc: UIViewController) -> UIViewController { if vc.presentedViewController != nil { return Self.findBestViewController(vc: vc.presentedViewController!) } else if let svc = vc as? UISplitViewController { if svc.viewControllers.count > 0 { return Self.findBestViewController(vc: svc.viewControllers.last!) } else { return vc } } else if let nvc = vc as? UINavigationController { if nvc.viewControllers.count > 0 { return Self.findBestViewController(vc: nvc.topViewController!) } else { return vc } } else if let tvc = vc as? UITabBarController { if (tvc.viewControllers?.count)! > 0 { return Self.findBestViewController(vc: tvc.selectedViewController!) } else { return vc } } else { if let rtvc = vc as? RTContainerController { return Self.findBestViewController(vc: rtvc.contentViewController!) } return vc } } } /// hud extension TypeWrapperProtocol where WrappedType: UIView { /// 隐藏hud public func hideHUD() { MBProgressHUD.hide(for: wrappedValue, animated: true) } /// 显示文本hud public func showMessage(_ text: String? = nil, style: UIViewController.MJHUDStyle = .dark, completion: (() -> Void)? = nil) { wrappedValue.ext.hideHUD() let hud = MBProgressHUD.showAdded(to: wrappedValue, animated: true) hud.mode = .text if style == .dark { hud.bezelView.style = .solidColor hud.bezelView.backgroundColor = UIColor.init(red: 30.0/255, green: 29.0/255, blue: 29.9/255, alpha: 1) } hud.label.font = UIFont.systemFont(ofSize: 14, weight: .medium) hud.label.textColor = UIColor.white hud.label.text = text hud.removeFromSuperViewOnHide = true hud.hide(animated: true, afterDelay: 0.9) hud.completionBlock = { if let _completion = completion { _completion() } } } /// 显示加载 public func showLoading(_ text: String? = nil, style: UIViewController.MJHUDStyle = .dark) { wrappedValue.ext.hideHUD() let hud = MBProgressHUD.showAdded(to: wrappedValue, animated: true) hud.mode = .indeterminate if style == .dark { hud.bezelView.style = .solidColor hud.bezelView.backgroundColor = UIColor.init(red: 30.0/255, green: 29.0/255, blue: 29.9/255, alpha: 1) } hud.label.font = UIFont.systemFont(ofSize: 14, weight: .medium) hud.label.textColor = UIColor.white hud.label.text = text hud.removeFromSuperViewOnHide = true } }
// // DriverAnnotation.swift // UberX // // Created by pop on 7/1/20. // Copyright © 2020 pop. All rights reserved. // import UIKit import MapKit class DriverAnnotation:NSObject,MKAnnotation{ dynamic var coordinate:CLLocationCoordinate2D var key:String init(coordinate:CLLocationCoordinate2D,withKey key:String){ self.coordinate = coordinate self.key = key super.init() } func update(annotaionPostion annotation:DriverAnnotation,withcoordinate coordinate2:CLLocationCoordinate2D){ var location = self.coordinate location.latitude = coordinate2.latitude location.longitude = coordinate2.longitude UIView.animate(withDuration: 0.2) { self.coordinate = location } } }
import SwiftGRPC import XCTest @testable import XpringKit final class DefaultXpringClientTest: XCTestCase { // Codes which are failures returned from the ledger. private static let transactionStatusFailureCodes = [ "tefFAILURE", "tecCLAIM", "telBAD_PUBLIC_KEY", "temBAD_FEE", "terRETRY" ] // MARK: - Balance func testGetBalanceWithSuccess() { // GIVEN a Xpring client which will successfully return a balance from a mocked network call. let xpringClient = DefaultXpringClient(networkClient: FakeNetworkClient.successfulFakeNetworkClient) // WHEN the balance is requested. guard let balance = try? xpringClient.getBalance(for: .testAddress) else { XCTFail("Exception should not be thrown when trying to get a balance") return } // THEN the balance is correct. XCTAssertEqual(balance, .testBalance) } func testGetBalanceWithClassicAddress() { // GIVEN a classic address. guard let classicAddressComponents = Utils.decode(xAddress: .testAddress) else { XCTFail("Failed to decode X-Address.") return } let xpringClient = DefaultXpringClient(networkClient: FakeNetworkClient.successfulFakeNetworkClient) // WHEN the balance is requested THEN an error is thrown. XCTAssertThrowsError( try xpringClient.getBalance(for: classicAddressComponents.classicAddress), "Exception not thrown" ) { error in guard case .invalidInputs = error as? XRPLedgerError else { XCTFail("Error thrown was not invalid inputs error") return } } } func testGetBalanceWithFailure() { // GIVEN a Xpring client which will throw an error when a balance is requested. let networkClient = FakeNetworkClient( accountInfoResult: .failure(XpringKitTestError.mockFailure), feeResult: .success(.testGetFeeResponse), submitTransactionResult: .success(.testSubmitTransactionResponse), transactionStatusResult: .success(.testGetTransactionResponse), transactionHistoryResult: .success(.testTransactionHistoryResponse) ) let xpringClient = DefaultXpringClient(networkClient: networkClient) // WHEN the balance is requested THEN the error is thrown. XCTAssertThrowsError(try xpringClient.getBalance(for: .testAddress), "Exception not thrown") { error in guard let _ = error as? XpringKitTestError else { XCTFail("Error thrown was not mocked error") return } } } // MARK: - Send func testSendWithSuccess() { // GIVEN a Xpring client which will successfully return a balance from a mocked network call. let xpringClient = DefaultXpringClient(networkClient: FakeNetworkClient.successfulFakeNetworkClient) // WHEN XRP is sent. guard let transactionHash = try? xpringClient.send( .testSendAmount, to: .testAddress, from: .testWallet) else { XCTFail("Exception should not be thrown when trying to send XRP") return } // THEN the engine result code is as expected. XCTAssertEqual(transactionHash, TransactionHash.testTransactionHash) } func testSendWithClassicAddress() { // GIVEN a classic address. guard let classicAddressComponents = Utils.decode(xAddress: .testAddress) else { XCTFail("Failed to decode X - Address.") return } let xpringClient = DefaultXpringClient(networkClient: FakeNetworkClient.successfulFakeNetworkClient) // WHEN XRP is sent to a classic address THEN an error is thrown. XCTAssertThrowsError(try xpringClient.send( .testSendAmount, to: classicAddressComponents.classicAddress, from: .testWallet )) } func testSendWithInvalidAddress() { // GIVEN a Xpring client and an invalid destination address. let xpringClient = DefaultXpringClient(networkClient: FakeNetworkClient.successfulFakeNetworkClient) let destinationAddress = "xrp" // WHEN XRP is sent to an invalid address THEN an error is thrown. XCTAssertThrowsError(try xpringClient.send( .testSendAmount, to: destinationAddress, from: .testWallet )) } func testSendWithAccountInfoFailure() { // GIVEN a Xpring client which will fail to return account info. let networkClient = FakeNetworkClient( accountInfoResult: .failure(XpringKitTestError.mockFailure), feeResult: .success(.testGetFeeResponse), submitTransactionResult: .success(.testSubmitTransactionResponse), transactionStatusResult: .success(.testGetTransactionResponse), transactionHistoryResult: .success(.testTransactionHistoryResponse) ) let xpringClient = DefaultXpringClient(networkClient: networkClient) // WHEN a send is attempted then an error is thrown. XCTAssertThrowsError(try xpringClient.send( .testSendAmount, to: .testAddress, from: .testWallet )) } func testSendWithFeeFailure() { // GIVEN a Xpring client which will fail to return a fee. let networkClient = FakeNetworkClient( accountInfoResult: .success(.testGetAccountInfoResponse), feeResult: .failure(XpringKitTestError.mockFailure), submitTransactionResult: .success(.testSubmitTransactionResponse), transactionStatusResult: .success(.testGetTransactionResponse), transactionHistoryResult: .success(.testTransactionHistoryResponse) ) let xpringClient = DefaultXpringClient(networkClient: networkClient) // WHEN a send is attempted then an error is thrown. XCTAssertThrowsError(try xpringClient.send( .testSendAmount, to: .testAddress, from: .testWallet )) } func testSendWithSubmitFailure() { // GIVEN a Xpring client which will fail to submit a transaction. let networkClient = FakeNetworkClient( accountInfoResult: .success(.testGetAccountInfoResponse), feeResult: .success(.testGetFeeResponse), submitTransactionResult: .failure(XpringKitTestError.mockFailure), transactionStatusResult: .success(.testGetTransactionResponse), transactionHistoryResult: .success(.testTransactionHistoryResponse) ) let xpringClient = DefaultXpringClient(networkClient: networkClient) // WHEN a send is attempted then an error is thrown. XCTAssertThrowsError(try xpringClient.send( .testSendAmount, to: .testAddress, from: .testWallet )) } // MARK: - Transaction Status func testGetTransactionStatusWithUnvalidatedTransactionAndFailureCode() { // Iterate over different types of transaction status codes which represent failures. for transactionStatusCodeFailure in DefaultXpringClientTest.transactionStatusFailureCodes { // GIVEN a XpringClient which returns an unvalidated transaction and a failed transaction status code. let transactionStatusResponse = makeGetTransactionResponse( validated: false, resultCode: transactionStatusCodeFailure ) let networkClient = FakeNetworkClient( accountInfoResult: .success(.testGetAccountInfoResponse), feeResult: .success(.testGetFeeResponse), submitTransactionResult: .success(.testSubmitTransactionResponse), transactionStatusResult: .success(transactionStatusResponse), transactionHistoryResult: .success(.testTransactionHistoryResponse) ) let xpringClient = DefaultXpringClient(networkClient: networkClient) // WHEN the transaction status is retrieved. let transactionStatus = try? xpringClient.getTransactionStatus(for: .testTransactionHash) // THEN the transaction status is pending. XCTAssertEqual(transactionStatus, .pending) } } func testGetTransactionStatusWithUnvalidatedTransactionAndSuccessCode() { // GIVEN a XpringClient which returns an unvalidated transaction and a succeeded transaction status code. let transactionStatusResponse = makeGetTransactionResponse( validated: false, resultCode: .testTransactionStatusCodeSuccess ) let networkClient = FakeNetworkClient( accountInfoResult: .success(.testGetAccountInfoResponse), feeResult: .success(.testGetFeeResponse), submitTransactionResult: .success(.testSubmitTransactionResponse), transactionStatusResult: .success(transactionStatusResponse), transactionHistoryResult: .success(.testTransactionHistoryResponse) ) let xpringClient = DefaultXpringClient(networkClient: networkClient) // WHEN the transaction status is retrieved. let transactionStatus = try? xpringClient.getTransactionStatus(for: .testTransactionHash) // THEN the transaction status is pending. XCTAssertEqual(transactionStatus, .pending) } func testGetTransactionStatusWithValidatedTransactionAndFailureCode() { // Iterate over different types of transaction status codes which represent failures. for transactionStatusCodeFailure in DefaultXpringClientTest.transactionStatusFailureCodes { // GIVEN a XpringClient which returns an unvalidated transaction and a failed transaction status code. let transactionStatusResponse = makeGetTransactionResponse( validated: true, resultCode: transactionStatusCodeFailure ) let networkClient = FakeNetworkClient( accountInfoResult: .success(.testGetAccountInfoResponse), feeResult: .success(.testGetFeeResponse), submitTransactionResult: .success(.testSubmitTransactionResponse), transactionStatusResult: .success(transactionStatusResponse), transactionHistoryResult: .success(.testTransactionHistoryResponse) ) let xpringClient = DefaultXpringClient(networkClient: networkClient) // WHEN the transaction status is retrieved. let transactionStatus = try? xpringClient.getTransactionStatus(for: .testTransactionHash) // THEN the transaction status is failed. XCTAssertEqual(transactionStatus, .failed) } } func testGetTransactionStatusWithValidatedTransactionAndSuccessCode() { // GIVEN a XpringClient which returns a validated transaction and a succeeded transaction status code. let transactionStatusResponse = makeGetTransactionResponse( validated: true, resultCode: .testTransactionStatusCodeSuccess ) let networkClient = FakeNetworkClient( accountInfoResult: .success(.testGetAccountInfoResponse), feeResult: .success(.testGetFeeResponse), submitTransactionResult: .success(.testSubmitTransactionResponse), transactionStatusResult: .success(transactionStatusResponse), transactionHistoryResult: .success(.testTransactionHistoryResponse) ) let xpringClient = DefaultXpringClient(networkClient: networkClient) // WHEN the transaction status is retrieved. let transactionStatus = try? xpringClient.getTransactionStatus(for: .testTransactionHash) // THEN the transaction status is succeeded. XCTAssertEqual(transactionStatus, .succeeded) } func testGetTransactionStatusWithServerFailure() { // GIVEN a XpringClient which fails to return a transaction status. let networkClient = FakeNetworkClient( accountInfoResult: .success(.testGetAccountInfoResponse), feeResult: .success(.testGetFeeResponse), submitTransactionResult: .success(.testSubmitTransactionResponse), transactionStatusResult: .failure(XpringKitTestError.mockFailure), transactionHistoryResult: .success(.testTransactionHistoryResponse) ) let xpringClient = DefaultXpringClient(networkClient: networkClient) // WHEN the transaction status is retrieved THEN an error is thrown. XCTAssertThrowsError(try xpringClient.getTransactionStatus(for: .testTransactionHash)) } func testTransactionStatusWithUnsupportedTransactionType() { // GIVEN a XpringClient which will return a non-payment type transaction. let getTransactionResponse = Org_Xrpl_Rpc_V1_GetTransactionResponse.with { $0.transaction = Org_Xrpl_Rpc_V1_Transaction() } let networkClient = FakeNetworkClient( accountInfoResult: .success(.testGetAccountInfoResponse), feeResult: .success(.testGetFeeResponse), submitTransactionResult: .success(.testSubmitTransactionResponse), transactionStatusResult: .success(getTransactionResponse), transactionHistoryResult: .success(.testTransactionHistoryResponse) ) let xpringClient = DefaultXpringClient(networkClient: networkClient) // WHEN the transaction status is retrieved. let transactionStatus = try? xpringClient.getTransactionStatus(for: .testTransactionHash) // THEN the status is UNKNOWN. XCTAssertEqual(transactionStatus, .unknown) } func testTransactionStatusWithPartialPayment() { // GIVEN a XpringClient which will return a partial payment type transaction. let getTransactionResponse = Org_Xrpl_Rpc_V1_GetTransactionResponse.with { $0.transaction = Org_Xrpl_Rpc_V1_Transaction.with { $0.payment = Org_Xrpl_Rpc_V1_Payment() $0.flags = Org_Xrpl_Rpc_V1_Flags.with { $0.value = RippledFlags.tfPartialPayment.rawValue } } } let networkClient = FakeNetworkClient( accountInfoResult: .success(.testGetAccountInfoResponse), feeResult: .success(.testGetFeeResponse), submitTransactionResult: .success(.testSubmitTransactionResponse), transactionStatusResult: .success(getTransactionResponse), transactionHistoryResult: .success(.testTransactionHistoryResponse) ) let xpringClient = DefaultXpringClient(networkClient: networkClient) // WHEN the transaction status is retrieved. let transactionStatus = try? xpringClient.getTransactionStatus(for: .testTransactionHash) // THEN the status is UNKNOWN. XCTAssertEqual(transactionStatus, .unknown) } // MARK: - Account Existence func testAccountExistsWithSuccess() { // GIVEN a XpringClient which will successfully return a balance from a mocked network call. let xpringClient = DefaultXpringClient(networkClient: FakeNetworkClient.successfulFakeNetworkClient) // WHEN the existence of the account is checked. guard let exists = try? xpringClient.accountExists(for: .testAddress) else { XCTFail("Exception should not be thrown when checking existence of valid account") return } // THEN the balance is correct. XCTAssertTrue(exists) } func testAccountExistsWithClassicAddress() { // GIVEN a classic address. guard let classicAddressComponents = Utils.decode(xAddress: .testAddress) else { XCTFail("Failed to decode X-Address.") return } let xpringClient = DefaultXpringClient(networkClient: FakeNetworkClient.successfulFakeNetworkClient) // WHEN the account's existence is checked THEN an error is thrown. XCTAssertThrowsError( try xpringClient.accountExists(for: classicAddressComponents.classicAddress), "Exception not thrown" ) { error in guard case .invalidInputs = error as? XRPLedgerError else { XCTFail("Error thrown was not invalid inputs error") return } } } func testAccountExistsWithNotFoundFailure() { // GIVEN a XpringClient which will throw an RPCError w/ StatusCode notFound when a balance is requested. let networkClient = FakeNetworkClient( accountInfoResult: .failure(RPCError.callError(CallResult(success: false, statusCode: StatusCode.notFound, statusMessage: "Mocked RPCError w/ notFound StatusCode", resultData: nil, initialMetadata: nil, trailingMetadata: nil))), feeResult: .success(.testGetFeeResponse), submitTransactionResult: .success(.testSubmitTransactionResponse), transactionStatusResult: .success(.testGetTransactionResponse), transactionHistoryResult: .success(.testTransactionHistoryResponse) ) let xpringClient = DefaultXpringClient(networkClient: networkClient) // WHEN the existence of the account is checked guard let exists = try? xpringClient.accountExists(for: .testAddress) else { XCTFail("Exception should not be thrown when checking existence of non-existent account") return } // THEN false is returned. XCTAssertFalse(exists) } func testAccountExistsWithUnknownFailure() { // GIVEN a XpringClient which will throw an RPCError w/ StatusCode unknown when a balance is requested. let networkClient = FakeNetworkClient( accountInfoResult: .failure(RPCError.callError(CallResult(success: false, statusCode: StatusCode.unknown, statusMessage: "Mocked RPCError w/ unknown StatusCode", resultData: nil, initialMetadata: nil, trailingMetadata: nil))), feeResult: .success(.testGetFeeResponse), submitTransactionResult: .success(.testSubmitTransactionResponse), transactionStatusResult: .success(.testGetTransactionResponse), transactionHistoryResult: .success(.testTransactionHistoryResponse) ) let xpringClient = DefaultXpringClient(networkClient: networkClient) // WHEN the account's existence is checked THEN the error is re-thrown. XCTAssertThrowsError( try xpringClient.accountExists(for: .testAddress), "Exception not thrown" ) { error in guard case .callError = error as? RPCError else { XCTFail("Error thrown was not RPCError.callError") return } } } // MARK: - TransactionHistory func testTransactionHistoryWithSuccess() { // GIVEN a Xpring client which will successfully return a transactionHistory mocked network call. let xpringClient = DefaultXpringClient(networkClient: FakeNetworkClient.successfulFakeNetworkClient) // WHEN the transactionHistory is requested. guard let transactions = try? xpringClient.getTransactionHistory(for: .testAddress) else { XCTFail("Exception should not be thrown when trying to get a balance") return } // THEN the balance is correct. XCTAssertEqual(transactions, .testTransactions) } func testGetTransactionHistoryWithClassicAddress() { // GIVEN a classic address. guard let classicAddressComponents = Utils.decode(xAddress: .testAddress) else { XCTFail("Failed to decode X-Address.") return } let xpringClient = DefaultXpringClient(networkClient: FakeNetworkClient.successfulFakeNetworkClient) // WHEN the transaction history is requested THEN an error is thrown. XCTAssertThrowsError( try xpringClient.getTransactionHistory(for: classicAddressComponents.classicAddress), "Exception not thrown" ) { error in guard case .invalidInputs = error as? XRPLedgerError else { XCTFail("Error thrown was not invalid inputs error") return } } } func testGetTransactionHistoryWithFailure() { // GIVEN a Xpring client which will throw an error when a balance is requested. let networkClient = FakeNetworkClient( accountInfoResult: .success(.testGetAccountInfoResponse), feeResult: .success(.testGetFeeResponse), submitTransactionResult: .success(.testSubmitTransactionResponse), transactionStatusResult: .success(.testGetTransactionResponse), transactionHistoryResult: .failure(XpringKitTestError.mockFailure) ) let xpringClient = DefaultXpringClient(networkClient: networkClient) // WHEN the transaction history is requested THEN an error is thrown. XCTAssertThrowsError(try xpringClient.getTransactionHistory(for: .testAddress), "Exception not thrown") { error in guard let _ = error as? XpringKitTestError else { XCTFail("Error thrown was not mocked error") return } } } // MARK: - Helpers private func makeGetTransactionResponse( validated: Bool, resultCode: String ) -> Org_Xrpl_Rpc_V1_GetTransactionResponse { return Org_Xrpl_Rpc_V1_GetTransactionResponse.with { $0.validated = validated $0.meta = Org_Xrpl_Rpc_V1_Meta.with { $0.transactionResult = Org_Xrpl_Rpc_V1_TransactionResult.with { $0.result = resultCode } } $0.transaction = Org_Xrpl_Rpc_V1_Transaction.with { $0.payment = Org_Xrpl_Rpc_V1_Payment() } } } }
// ViewDelegate.swift import Foundation /// ViewDelegate /// /// このプロトコルは`VIPER`で定義された`View`のライフサイクルを委譲します。 /// /// このプロトコルは `Presenter`に実装継承されます。また、`Behavior`の参照を保持します。 /// /// このプロトコルを適用する場合は、`ViewDelegate`を継承したプロトコルを用意する必要があります。 /// View Delegate protocol ViewDelegate { // Managing the View func loadView() func viewDidLoad() // Responding to View Events func viewWillAppear(_ animated: Bool) func viewDidAppear(_ animated: Bool) func viewWillDisappear(_ animated: Bool) func viewDidDisappear(_ animated: Bool) // Configuring the View's Layout Behavior func viewWillLayoutSubviews() func viewDidLayoutSubviews() func updateViewConstraints() }
// // ViewController.swift // Maps // // Created by Jide Opeola on 2/2/15. // Copyright (c) 2015 Jide Opeola. All rights reserved. // // Homework // - make the map view show your current location (not as an annotation, but as the blue dot) // - make the "annotation view" show using "title" on an annotation (make the title be the name of the venue) // - make the mapview zoom to the annotations (maybe look for a way to make a region based on the annotations) // - change the pin color import UIKit import MapKit import CoreLocation var onceToken: dispatch_once_t = 0 class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate { var lManager = CLLocationManager() var mapView = MKMapView() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. mapView.delegate = self mapView.frame = view.frame mapView.showsUserLocation = true view.addSubview(mapView) lManager.requestWhenInUseAuthorization() lManager.delegate = self lManager.desiredAccuracy = kCLLocationAccuracyBest lManager.distanceFilter = kCLDistanceFilterNone lManager.pausesLocationUpdatesAutomatically = true lManager.distanceFilter = 1000 lManager.startUpdatingLocation() } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { dispatch_once(&onceToken) { () -> Void in // println(locations.last) if let location = locations.last as? CLLocation { // self.mapView.centerCoordinate = location.coordinate // span 0.1 is in degrees let span = MKCoordinateSpanMake(0.1, 0.1) let region = MKCoordinateRegion(center: location.coordinate, span: span) self.mapView.setRegion(region, animated: true) let venues = FourSquareRequest.requestVenuesWithLocation(location) self.createAnnotationsWithVenues(venues) self.userLocation() // request to foursquare for venues with location // println(venues) } } lManager.stopUpdatingLocation() } func createAnnotationsWithVenues(venues: [AnyObject]) { for venue in venues as! [[String:AnyObject]] { let locationInfo = venue["location"] as! [String:AnyObject] let venueName = venue["name"] as! String let lat = locationInfo["lat"] as! CLLocationDegrees let lng = locationInfo["lng"] as! CLLocationDegrees // CLLocationCoordinate2D c2D = CLLocationCoordinate2DMake(CLLocationDegrees latitude, CLLocationDegrees longitude); let locValue:CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat, lng) let span = MKCoordinateSpanMake(0.01, 0.01) let region = MKCoordinateRegion(center: locValue, span: span) let coordinate = CLLocationCoordinate2DMake(lat, lng) self.mapView.setRegion(region, animated: true) let annotation = MKPointAnnotation() annotation.coordinate = coordinate // annotation.setCoordinate(coordinate) annotation.title = venueName mapView.addAnnotation(annotation) } } func userLocation() { // let userL = MKUserLocation. as CLLocationDegrees var centre = mapView.centerCoordinate as CLLocationCoordinate2D let locValue:CLLocationCoordinate2D = lManager.location.coordinate let annotation = MKPointAnnotation() annotation.coordinate = locValue // annotation.setCoordinate(locValue) // myPinView.pinColor = MKPinAnnotationColor.Purple; // annotation. let myPin = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "MyIdentifier") myPin?.pinColor = .Green // return myPin mapView.addAnnotation(annotation) // println("locations = \(locValue.latitude) \(locValue.longitude)") // MKUserLocation. } func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { if annotation is MKUserLocation { //return nil so map view draws "blue dot" for standard user location return nil } let reuseId = "pin" var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView if pinView == nil { pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId) pinView!.canShowCallout = true pinView!.animatesDrop = true pinView!.pinColor = .Purple } else { pinView!.annotation = annotation } return pinView } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // MyLocation.swift // SimpleLoginLogoutAPI // // Created by Lainel John Dela Cruz on 10/10/2018. // Copyright © 2018 Lainel John Dela Cruz. All rights reserved. // import Foundation import CoreLocation class MyLocation:QueryData{ public var ID:String; public var longitude:Double; public var latitude:Double; public let locationManager=CLLocationManager(); override init(){ self.ID=""; self.longitude=0; self.latitude=0; super.init(); } convenience init(id:String, long:Double, lat:Double){ self.init(); self.ID=id; self.longitude=long; self.latitude=lat; } convenience init(coordinate:CLLocationCoordinate2D){ self.init(); self.MLinit(coordinate: coordinate) } func LMInit(delegate:CLLocationManagerDelegate, accuracy:CLLocationAccuracy){ self.locationManager.delegate=delegate; self.locationManager.desiredAccuracy=accuracy; } func MLinit(coordinate:CLLocationCoordinate2D){ self.longitude=coordinate.longitude; self.latitude=coordinate.latitude; print("Coordinates"); print(self.latitude," ",self.longitude); } }
// // LineChartData.swift // KayakFirst Ergometer E2 // // Created by Balazs Vidumanszki on 2017. 02. 18.. // Copyright © 2017. Balazs Vidumanszki. All rights reserved. // import Charts class AppLineChartData { //MARK: properties private var lineChart: LineChartView internal let sumChartTraining: SumChartTraining private var lineDataSets: [LineChartDataSet]? private var label: CalculateEnum? private var hasLeftData = false private var hasRightData = false fileprivate var leftYDateFormatHelper = DateFormatHelper() //MARK: init init(lineChart: LineChartView, sumChartTraining: SumChartTraining) { self.lineChart = lineChart self.sumChartTraining = sumChartTraining initChartDesign() } //MARK: abstract functions func createEntries(trainingList: [ChartTraining]) -> [ChartDataEntry] { fatalError("Must be implemented") } func xAxisFormatter() -> IAxisValueFormatter { fatalError("Must be implemented") } //MARK: createData func createTrainingListByLabel(diagramLabels: [DiagramLabel]) { hasLeftData = false hasRightData = false lineDataSets = [LineChartDataSet]() for l in diagramLabels { if l.isActive { addData(trainingList: getChartTrainingListByLabel(label: l.getLabel()), diagramLabel: l) } else { label = nil } } refreshChart() } private func initChartDesign() { formatXAxis(); formatYAxis(); lineChart.chartDescription = nil lineChart.legend.enabled = false lineChart.noDataText = getString("chart_training_no_value_selected") lineChart.noDataTextColor = Colors.colorAccent lineChart.doubleTapToZoomEnabled = false } private func addData(trainingList: [ChartTraining], diagramLabel: DiagramLabel) { lineDataSets?.append(createLineDataSet(entries: createEntries(trainingList: trainingList), diagramLabel: diagramLabel)) } private func refreshChart() { var dataSets = [LineChartDataSet]() for lineDataSet in lineDataSets! { dataSets.append(lineDataSet) } var lineData: LineChartData? if dataSets.count == 0 { lineData = nil } else { lineData = LineChartData(dataSets: dataSets) } let lowestVisibleX = lineChart.lowestVisibleX lineChart.data = lineData lineChart.moveViewToX(lowestVisibleX) } private func createLineDataSet(entries: [ChartDataEntry]?, diagramLabel: DiagramLabel) -> LineChartDataSet { let lineDataSet = LineChartDataSet(values: entries, label: diagramLabel.getLabel().rawValue) lineDataSet.colors = [CalculateEnum.getColor(calculate: diagramLabel.getLabel())] lineDataSet.drawCirclesEnabled = false lineDataSet.valueTextColor = UIColor.clear lineDataSet.lineWidth = chartLineWidth lineDataSet.highlightEnabled = false if diagramLabel.getLabel() == CalculateEnum.T_200 || diagramLabel.getLabel() == CalculateEnum.T_500 || diagramLabel.getLabel() == CalculateEnum.T_1000 { lineDataSet.axisDependency = .left hasLeftData = true } else { lineDataSet.axisDependency = .right hasRightData = true } setYAxisEnabled() return lineDataSet } private func formatXAxis() { let axis = lineChart.xAxis axis.labelPosition = .bottom axis.valueFormatter = xAxisFormatter() axis.drawGridLinesEnabled = false axis.axisLineColor = Colors.colorWhite axis.axisLineWidth = chartLineWidth axis.labelTextColor = Colors.colorWhite } private func formatYAxis() { let leftAxis = lineChart.leftAxis let rightAxis = lineChart.rightAxis leftYDateFormatHelper.format = TimeEnum.timeFormatTwo leftAxis.valueFormatter = LeftYAxisFormatter(lineChartData: self) rightAxis.valueFormatter = RightYAxisFormatter() leftAxis.gridColor = Colors.colorInactive rightAxis.gridColor = Colors.colorInactive leftAxis.axisLineColor = Colors.colorWhite rightAxis.axisLineColor = Colors.colorWhite leftAxis.axisLineWidth = chartLineWidth rightAxis.axisLineWidth = chartLineWidth leftAxis.labelTextColor = Colors.colorWhite rightAxis.labelTextColor = Colors.colorWhite } private func setYAxisEnabled() { lineChart.leftAxis.enabled = hasLeftData lineChart.rightAxis.enabled = hasRightData } func getChartTrainingListByLabel(label: CalculateEnum) -> [ChartTraining] { switch label { case CalculateEnum.T_200: return sumChartTraining.t200Charts case CalculateEnum.T_500: return sumChartTraining.t500Charts case CalculateEnum.T_1000: return sumChartTraining.t1000Charts case CalculateEnum.STROKES: return sumChartTraining.strokesCharts case CalculateEnum.F: return sumChartTraining.forceCharts case CalculateEnum.V: return sumChartTraining.speedCharts default: fatalError("There is no createTrainingList for this : \(label)") } } } class LeftYAxisFormatter: NSObject, IAxisValueFormatter { private var lineChartData: AppLineChartData init(lineChartData: AppLineChartData) { self.lineChartData = lineChartData } func stringForValue(_ value: Double, axis: AxisBase?) -> String { return lineChartData.leftYDateFormatHelper.getTime(millisec: value)! } } class RightYAxisFormatter: NSObject, IAxisValueFormatter { func stringForValue(_ value: Double, axis: AxisBase?) -> String { return String(format: "%.0f", value) } }
// // DBManagement.swift // 2Q2R // // Created by Sam Claus on 8/24/16. // Copyright © 2016 Tera Insights, LLC. All rights reserved. // TODO: setCounter should also update the datetime on the key // import Foundation var database: FMDatabase! = nil func initializeDatabase() { let dbFileURL = try! FileManager.default.url(for: .libraryDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("keys.sqlite") guard let db = FMDatabase(path: dbFileURL.path) else { print("Failed to access database file!") return } guard db.open() else { print("Failed to open database!") return } do { try db.executeUpdate("CREATE TABLE IF NOT EXISTS keys(keyID TEXT PRIMARY KEY NOT NULL, appID TEXT NOT NULL, counter TEXT NOT NULL, userID TEXT NOT NULL, used DATETIME NOT NULL)", values: nil) try db.executeUpdate("CREATE TABLE IF NOT EXISTS servers(appID TEXT PRIMARY KEY NOT NULL, appName TEXT NOT NULL, appURL TEXT NOT NULL)", values: nil) database = db } catch let error { print("Could not create tables in database, error: \(error)") } } func insertNewKey(_ keyID: String, appID: String, userID: String) { do { try database.executeUpdate("INSERT INTO keys VALUES ('\(keyID)', '\(appID)', '0', '\(userID)', '\(Date())');", values: nil) refreshTableData() } catch let error { print(error) } } func deleteKey(withID keyID: String) { do { try database.executeUpdate("DELETE FROM keys WHERE keyID = '\(keyID)'", values: nil) refreshTableData() } catch let error { print(error) } } func insertNewServer(_ appID: String, appName: String, appURL: String) { do { try database.executeUpdate("INSERT INTO servers VALUES ('\(appID)', '\(appName)', '\(appURL)')", values: nil) } catch let error { print(error) } } func userIsAlreadyRegistered(_ userID: String, forServer appID: String) -> Bool { do { let query = try database.executeQuery("SELECT userID, appID FROM keys WHERE userID = '\(userID)' AND appID = '\(appID)'", values: nil) return query.next() } catch let error { print(error) return false } } func getUserID(forKey keyID: String) -> String? { do { let query = try database.executeQuery("SELECT userID FROM keys WHERE keyID = '\(keyID)'", values: nil) guard query.next() else { return nil } return query.string(forColumn: "userID") } catch let error { print(error) return nil } } func getInfo(forServer appID: String) -> (appName: String, appURL: String)? { do { let query = try database.executeQuery("SELECT appName, appURL FROM servers WHERE appID = '\(appID)'", values: nil) if query.next() { return (query.string(forColumn: "appName"), query.string(forColumn: "appURL")) } } catch let error { print(error) } return nil } func getRecentKeys() -> [[String:AnyObject]] { var result: [[String:AnyObject]] = [] do { let query = try database.executeQuery("SELECT keyID, userID, appName, appURL, used, counter FROM keys, servers WHERE keys.appID = servers.appID ORDER BY used DESC LIMIT 5", values: nil) while query.next() { result.append([ "keyID": query.string(forColumn: "keyID") as AnyObject, "userID": query.string(forColumn: "userID") as AnyObject, "appName": query.string(forColumn: "appName") as AnyObject, "appURL": query.string(forColumn: "appURL") as AnyObject, "used": query.date(forColumn: "used") as AnyObject, "counter": Int(query.int(forColumn: "counter")) as AnyObject ]) } } catch let error { print(error) } return result } func getAllKeys() -> [[String:AnyObject]] { var result: [[String:AnyObject]] = [] do { let query = try database.executeQuery("SELECT keyID, userID, appName, appURL, used, counter FROM keys, servers WHERE keys.appID = servers.appID ORDER BY appName, userID DESC", values: nil) while query.next() { result.append([ "keyID": query.string(forColumn: "keyID") as AnyObject, "userID": query.string(forColumn: "userID") as AnyObject, "appName": query.string(forColumn: "appName") as AnyObject, "appURL": query.string(forColumn: "appURL") as AnyObject, "used": query.date(forColumn: "used") as AnyObject, "counter": Int(query.int(forColumn: "counter")) as AnyObject ]) } } catch let error { print(error) } return result } func getCounter(forKey keyID: String) -> Int? { do { let query = try database.executeQuery("SELECT counter FROM keys WHERE keyID = '\(keyID)'", values: nil) if query.next() { return Int(query.int(forColumn: "counter")) } } catch let error { print(error) } return nil } func setCounter(forKey keyID: String, to counter: Int) { do { try database.executeUpdate("UPDATE keys SET counter = '\(counter)', used = '\(Date())' WHERE keyID = '\(keyID)'", values: nil) } catch let error { print(error) } }
import Foundation import CocoaLumberjack internal extension Jack { struct Scope { static let fallback = Scope("InvalidScope")! // swiftlint:disable:next nesting enum Kind { case normal case file } let string: String let kind: Kind static func isValid(scopeString: String) -> Bool { let components = scopeString.split(separator: ".", omittingEmptySubsequences: false) // Must have at least one component. guard !components.isEmpty else { return false } // Must NOT contain empty string `""` components. guard components.firstIndex(of: "") == nil else { return false } return true } init?(_ string: String, kind: Kind = .normal) { guard Scope.isValid(scopeString: string) else { return nil } self.string = string self.kind = kind } var superScopeStrings: [String] { let first = string.components(separatedBy: ".") return sequence(first: first) { let next = $0.dropLast() return next.isEmpty ? nil : Array(next) } .map { $0.joined(separator: ".") } } } }
// Tự học Swift 4.0 - xuanvinhtd import Foundation import UIKit extension String { static func className(_ aClass: AnyClass) -> String { return NSStringFromClass(aClass).components(separatedBy: ".").last! } func substring(_ from: Int) -> String { return self.substring(from: self.characters.index(self.startIndex, offsetBy: from)) } var length: Int { return self.characters.count } var htmlDecoded: String { guard let encodedData = self.data(using: .utf8) else { return self } let attributedOptions: [String : Any] = [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue] do { let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil) return attributedString.string } catch { print("Error: \(error)") return self } } }
// // ViewController.swift // ARKitDemo // // Created by Lebron on 09/09/2017. // Copyright © 2017 HackNCraft. All rights reserved. // import UIKit import SceneKit import ARKit class ViewController: UIViewController, ARSCNViewDelegate { // MARK: - Properties @IBOutlet var sceneView: ARSCNView! @IBOutlet weak var addButton: UIButton! @IBOutlet weak var confirmButton: UIButton! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var settingsButton: UIButton! @IBOutlet weak var messageLabel: UILabel! @IBOutlet var collectionViewTopConstraint: NSLayoutConstraint! @IBOutlet var collectionViewBottomCloseButtonConstraint: NSLayoutConstraint! @IBOutlet var collectionViewHeightConstraint: NSLayoutConstraint! @IBOutlet var collectionViewBottomMessageLabelConstraint: NSLayoutConstraint! @IBOutlet var closeButtonBottomConstraint: NSLayoutConstraint! @IBOutlet weak var addButtonBottomConstraint: NSLayoutConstraint! @IBOutlet weak var settingsButtonTrailingConstraint: NSLayoutConstraint! @IBOutlet var cancelAndConfirmButtonBottomConstraints: [NSLayoutConstraint]! var messageManager: MessageManager! var currentHelperNode: PlacementHelperNode? var currentHelperNodeAngle: Float = 0 var currentHelperNodePosition = float3(0, 0, 0) var selectedObjectIndex: Int = 0 lazy var virtualObjectManager = VirtualObjectManager() lazy var placementHelperNodeManager = PlacementHelperNodeManager() var objectManager: ObjectManager { return (currentHelperNode == nil) ? virtualObjectManager : placementHelperNodeManager } // MARK: - View life cycle override func viewDidLoad() { super.viewDidLoad() sceneView.delegate = self sceneView.debugOptions = [ARSCNDebugOptions.showFeaturePoints] messageManager = MessageManager(messageLabel: messageLabel) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) hideCollectionViewAndCloseButton(animated: false) animateAddButton(hide: true, animated: false) animateCancelAndConfirmButtons(hide: true, animated: false) animateSettingsButton(hide: true, animated: false) let configuration = ARWorldTrackingConfiguration() configuration.planeDetection = .horizontal sceneView.session.run(configuration) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) sceneView.session.pause() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Private Methods func hideCollectionViewAndCloseButton(animated: Bool) { let duration = animated ? 0.25 : 0 UIView.animate(withDuration: duration, animations: { self.collectionViewTopConstraint.isActive = false self.collectionViewBottomCloseButtonConstraint.isActive = false self.closeButtonBottomConstraint.constant = -60 self.view.layoutIfNeeded() }) } func animateAddButton(hide: Bool, animated: Bool) { let duration = animated ? 0.25 : 0 let constant: CGFloat = hide ? -60 : 20 UIView.animate(withDuration: duration, animations: { self.addButtonBottomConstraint.constant = constant self.view.layoutIfNeeded() }) } func addButtonIsHidden() -> Bool { return addButtonBottomConstraint.constant == -60 } func animateSettingsButton(hide: Bool, animated: Bool) { let duration = animated ? 0.25 : 0 let constant: CGFloat = hide ? -60 : 20 UIView.animate(withDuration: duration, animations: { self.settingsButtonTrailingConstraint.constant = constant self.view.layoutIfNeeded() }) } func animateCancelAndConfirmButtons(hide: Bool, animated: Bool) { let duration = animated ? 0.25 : 0 let constant: CGFloat = hide ? -60 : 20 UIView.animate(withDuration: duration, animations: { self.cancelAndConfirmButtonBottomConstraints.forEach({ constraint in constraint.constant = constant }) self.view.layoutIfNeeded() }) } private func showCollectionViewAndCloseButton() { collectionViewHeightConstraint.isActive = false collectionViewBottomMessageLabelConstraint.isActive = false UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.4, options: [.curveEaseInOut], animations: { self.collectionViewTopConstraint.isActive = true self.collectionViewBottomCloseButtonConstraint.isActive = true self.closeButtonBottomConstraint.constant = 20 self.view.layoutIfNeeded() }, completion: { _ in UIView.animate(withDuration: 0.25, animations: { self.closeButtonBottomConstraint.constant = 20 self.view.layoutIfNeeded() }) }) } func addVirtualOjbect(at index: Int) { guard let cameraTransform = sceneView.session.currentFrame?.camera.transform else { return } let definition = VirtualObjectManager.availableObjectDefinitions[index] let object = VirtualObject(definition: definition) guard let virtualObjectManager = objectManager as? VirtualObjectManager else { return } virtualObjectManager.loadVirtualObject(object, to: currentHelperNodePosition, cameraTransform: cameraTransform) object.eulerAngles.y = currentHelperNodeAngle if object.parent == nil { DispatchQueue.global().async { self.sceneView.scene.rootNode.addChildNode(object) } } } func addPlacementHelperNode(at index: Int) { let helperNode = PlacementHelperNode() helperNode.simdPosition = worldPositionFromScreenCenter() DispatchQueue.global().async { self.sceneView.scene.rootNode.addChildNode(helperNode) } currentHelperNode = helperNode } func worldPositionFromScreenCenter() -> float3 { let screenCenter = CGPoint(x: sceneView.bounds.midX, y: sceneView.bounds.midY) let (worldPosition, _, _) = objectManager.worldPosition(from: screenCenter, in: sceneView, objectPosition: float3(0)) return worldPosition ?? float3(0) } // MARK: - Actions @IBAction func addButtonTapped() { animateAddButton(hide: true, animated: true) showCollectionViewAndCloseButton() } @IBAction func closeButtonTapped() { animateAddButton(hide: false, animated: true) hideCollectionViewAndCloseButton(animated: true) } @IBAction func cancelButtonTapped() { animateAddButton(hide: false, animated: true) animateCancelAndConfirmButtons(hide: true, animated: true) currentHelperNode?.removeFromParentNode() currentHelperNode = nil } @IBAction func confirmButtonTapped() { animateCancelAndConfirmButtons(hide: true, animated: true) animateAddButton(hide: false, animated: true) if let helperNode = currentHelperNode { currentHelperNodeAngle = helperNode.eulerAngles.y currentHelperNodePosition = helperNode.simdPosition } currentHelperNode?.removeFromParentNode() currentHelperNode = nil addVirtualOjbect(at: selectedObjectIndex) } // MARK: - ARSCNViewDelegate func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) { DispatchQueue.main.async { if self.addButtonIsHidden() { self.animateAddButton(hide: false, animated: true) self.messageManager.showMessage("FIND A SURFACE TO PLACE AN OBJECT") } } } // MARK: - ARSessionObserver func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) { messageManager.showTrackingQualityInfo(for: camera.trackingState) } func session(_ session: ARSession, didFailWithError error: Error) { // Present an error message to the user } func sessionWasInterrupted(_ session: ARSession) { // Inform the user that the session has been interrupted, for example, by presenting an overlay } func sessionInterruptionEnded(_ session: ARSession) { // Reset tracking and/or remove existing anchors if consistent tracking is required } // MARK: - Gesture Recognizers override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { objectManager.reactToTouchesBegan(touches, with: event, in: self.sceneView) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { objectManager.reactToTouchesMoved(touches, with: event) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { objectManager.reactToTouchesEnded(touches, with: event) } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { objectManager.reactToTouchesCancelled(touches, with: event) } }
// // LibraryViewController.swift // e-news-paper // // Created by SimpuMind on 4/6/17. // Copyright © 2017 SimpuMind. All rights reserved. // import UIKit import Firebase class LibraryViewController: UIViewController { var set = [NewsPaper]() fileprivate let itemsPerRow: CGFloat = 2 fileprivate let sectionInsets = UIEdgeInsets(top: 0, left: 5.0, bottom: 0, right: 5.0) fileprivate var storageRef = Storage.storage().reference() @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() collectionView.delegate = self collectionView.dataSource = self self.navigationItem.title = Localization("libraryText") //self.automaticallyAdjustsScrollViewInsets = false // navigationController?.navigationBar.isTranslucent = true // navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) // navigationController?.navigationBar.shadowImage = UIImage() let id = UserDefaults.standard.getUserKey() AppFirRef.subscriberRef.child(id).child("susbscriptions").observe(.childAdded, with: { (snapshot) in print(snapshot.key) AppFirRef.newspaperRef.child(snapshot.key).observeSingleEvent(of: .value, with: { (snapshot) in if snapshot.value is NSNull { AppFirRef.subscriberRef.child(id).child("susbscriptions").child(snapshot.key).removeValue() return } guard let value = snapshot.value as? [String : Any] else { return } print(value) let newspaper = NewsPaper(value: value, vendorKey: snapshot.key) self.set.append(newspaper) DispatchQueue.main.async { self.collectionView.reloadData() } }) }) } } extension LibraryViewController: UICollectionViewDelegate, UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LibraryCell", for: indexPath) as! LibraryCell let s = set[indexPath.item] cell.set = s if let path = s.logo{ if let url = URL(string: path) { self.storageRef = Storage.storage().reference(withPath: url.path) cell.vendorImage.sd_setImage(with: self.storageRef, placeholderImage: #imageLiteral(resourceName: "default")) } } return cell } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return set.count } } extension LibraryViewController : UICollectionViewDelegateFlowLayout { //1 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { //2 let paddingSpace = sectionInsets.left * (itemsPerRow + 1) let availableWidth = collectionView.frame.width - paddingSpace let widthPerItem = availableWidth / itemsPerRow return CGSize(width: widthPerItem, height: widthPerItem) } //3 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return sectionInsets } // 4 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return sectionInsets.left } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let vendor = set[indexPath.item] self.performSegue(withIdentifier: "showNews", sender: vendor) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if segue.identifier == "showNews"{ if let vendor = sender as? NewsPaper{ let newsListVc = segue.destination as! NewsListVC let backItem = UIBarButtonItem() backItem.title = "" navigationController?.navigationBar.barTintColor = .white navigationController?.navigationBar.tintColor = .black self.navigationItem.backBarButtonItem = backItem newsListVc.vendor = vendor newsListVc.hidesBottomBarWhenPushed = true } } } }
// // EventTimerCellViewModel.swift // TimerX // // Created by 이광용 on 02/05/2019. // Copyright © 2019 GwangYongLee. All rights reserved. // import Foundation import RxCocoa import Domain final class EventTimeCellViewModel { let title: Driver<String> let description: Driver<String> init(title: String, description: Driver<String>) { self.title = Driver.just(title) self.description = description } } //let timeEventTimeInterval = timeEvent.rx.observe(TimeInterval.self, "seconds").unwrap() //let countingEventInterval = countingEvent.rx.observe(TimeInterval.self, "interval").unwrap()
import Bow import SwiftCheck public class SemiringLaws<A: Semiring & Equatable & Arbitrary> { public static func check() { MonoidLaws<A>.check() commutativityForCombining() associativityForMultiplying() leftIdentityForMultiplying() rightIdentityForMultiplying() leftDistribution() rightDistribution() leftAnnihilation() rightAnnihilation() } private static func commutativityForCombining() { property("Commutativity for combining") <~ forAll { (a: A) in A.zero().combine(a) == a.combine(.zero()) } } private static func associativityForMultiplying() { property("Ascociativity for multiplying") <~ forAll { (a: A, b: A, c: A) in a.multiply(b).multiply(c) == a.multiply(b.multiply(c)) } } private static func leftIdentityForMultiplying() { property("Left identity for multiplying") <~ forAll { (a: A) in A.one().multiply(a) == a } } private static func rightIdentityForMultiplying() { property("Right identity for multiplying") <~ forAll { (a: A) in a.multiply(.one()) == a } } private static func leftDistribution() { property("Left distribution") <~ forAll { (a: A, b: A, c: A) in a.multiply(b.combine(c)) == (a.multiply(b)).combine(a.multiply(c)) } } private static func rightDistribution() { property("Right distribution") <~ forAll { (a: A, b: A, c: A) in a.combine(b).multiply(c) == a.multiply(c).combine(b.multiply(c)) } } private static func leftAnnihilation() { property("Left Annihilation") <~ forAll { (a: A) in A.zero().multiply(a) == .zero() } } private static func rightAnnihilation() { property("Right Annihilation") <~ forAll { (a: A) in a.multiply(.zero()) == .zero() } } }
// // MeditationTableViewCell.swift // PrototypeApp // // Created by Surjeet on 30/03/21. // import UIKit import SDWebImage class MeditationTableViewCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var descLabel: UILabel! @IBOutlet weak var medImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setData(_ medication: Meditation) { titleLabel.text = medication.title descLabel.text = medication.teacherName if let image = medication.imageUrl, let imageURL = URL(string: image), imageURL.host != nil { medImageView.backgroundColor = .clear medImageView.sd_setImage(with: imageURL, placeholderImage: nil, options: SDWebImageOptions.progressiveLoad, context: nil) } else { medImageView.image = nil medImageView.backgroundColor = UIColor.black.withAlphaComponent(0.5) } } }
import Basic import Foundation /// Xcode project scheme. class Scheme: JSONMappable, Equatable { /// Scheme name. let name: String /// True if the scheme is shared. let shared: Bool /// Scheme build action. let buildAction: BuildAction? /// Scheme test action. let testAction: TestAction? /// Scheme run action. let runAction: RunAction? /// Initializes the scheme with its properties. /// /// - Parameters: /// - name: scheme name. /// - shared: whether the scheme is shared or not. /// - buildAction: build action. /// - testAction: test action. /// - runAction: run action. init(name: String, shared: Bool = false, buildAction: BuildAction? = nil, testAction: TestAction? = nil, runAction: RunAction? = nil) { self.name = name self.shared = shared self.buildAction = buildAction self.testAction = testAction self.runAction = runAction } /// Initializes the scheme with its JSON representation. /// /// - Parameter json: JSON representation. /// - Throws: an error if it cannot be parsed. required init(json: JSON) throws { name = try json.get("name") shared = try json.get("shared") buildAction = try? json.get("build_action") testAction = try? json.get("test_action") runAction = try? json.get("run_action") } /// Compares two schemes. /// /// - Parameters: /// - lhs: first scheme to be compared. /// - rhs: second scheme to be compared. /// - Returns: true if the two schemes are the same. static func == (lhs: Scheme, rhs: Scheme) -> Bool { return lhs.name == rhs.name && lhs.shared == rhs.shared && lhs.buildAction == rhs.buildAction && lhs.testAction == rhs.testAction && lhs.runAction == rhs.runAction } } /// Scheme action arguments. class Arguments: JSONMappable, Equatable { /// Environment variables. let environment: [String: String] /// Launch arguments. The key represents the argument, and the value whether the argument is enabled or not. let launch: [String: Bool] /// Initializes the arguments with its properties. /// /// - Parameters: /// - environment: environment variables. /// - launch: launch arguments. init(environment: [String: String] = [:], launch: [String: Bool] = [:]) { self.environment = environment self.launch = launch } /// Initializes Arguments with its JSON representation. /// /// - Parameter json: JSON representation. /// - Throws: an error if the arguments cannot be parsed. required init(json: JSON) throws { environment = try json.get("environment") launch = try json.get("launch") } /// Compares two Argument instances. /// /// - Parameters: /// - lhs: first instance to be compared. /// - rhs: second instance to be compared. /// - Returns: true if the two arguments are the same. static func == (lhs: Arguments, rhs: Arguments) -> Bool { return lhs.environment == rhs.environment && lhs.launch == rhs.launch } } /// Scheme build action. class BuildAction: JSONMappable, Equatable { /// Build action targets. let targets: [String] /// Initializes the build action with its properties. /// /// - Parameter targets: targets to be built. init(targets: [String] = []) { self.targets = targets } /// Initializes BuildAction with its JSON representation. /// /// - Parameter json: JSON representation. /// - Throws: an error if the action cannot be parsed. required init(json: JSON) throws { targets = try json.get("targets") } /// Compares two build action instances. /// /// - Parameters: /// - lhs: first instance to be compared. /// - rhs: second instance to be compared. /// - Returns: true if the two instances are the same. static func == (lhs: BuildAction, rhs: BuildAction) -> Bool { return lhs.targets == rhs.targets } } /// Test action. class TestAction: JSONMappable, Equatable { /// Targets that are tested. let targets: [String] /// Arguments. let arguments: Arguments? /// Build configuration. let config: BuildConfiguration /// True if the test coverage data should be gathered. let coverage: Bool /// Initializes the test action with its attributes. /// /// - Parameters: /// - targets: targets to be tested. /// - arguments: launch arguments. /// - config: build configuration. /// - coverage: whether the test coverage should be gathered. init(targets: [String] = [], arguments: Arguments? = nil, config: BuildConfiguration = .debug, coverage: Bool = false) { self.targets = targets self.arguments = arguments self.config = config self.coverage = coverage } /// Initializes the test action with its JSON representation. /// /// - Parameter json: JSON representation. /// - Throws: an error if the action cannot be parsed. required init(json: JSON) throws { targets = try json.get("targets") arguments = try? json.get("arguments") let configString: String = try json.get("config") config = BuildConfiguration(rawValue: configString)! coverage = try json.get("coverage") } /// Compares two test actions. /// /// - Parameters: /// - lhs: first test action to be compared. /// - rhs: second test action to be compared. /// - Returns: true if the two actions are the same. static func == (lhs: TestAction, rhs: TestAction) -> Bool { return lhs.targets == rhs.targets && lhs.arguments == rhs.arguments && lhs.config == rhs.config && lhs.coverage == rhs.coverage } } /// Run action class RunAction: JSONMappable, Equatable { /// Build configuration to be run. let config: BuildConfiguration /// Name of the executable. let executable: String? /// Run action arguments. let arguments: Arguments? /// Initializes the run action with its attributes. /// /// - Parameters: /// - config: build configuration. /// - executable: executable. /// - arguments: launch arguments. init(config: BuildConfiguration, executable: String? = nil, arguments: Arguments? = nil) { self.config = config self.executable = executable self.arguments = arguments } /// Initializes the run action with its JSON representation. /// /// - Parameter json: JSON representation. /// - Throws: throws an error if it cannot be parsed. required init(json: JSON) throws { let configString: String = try json.get("config") config = BuildConfiguration(rawValue: configString)! executable = try? json.get("executable") arguments = try? json.get("arguments") } static func == (lhs: RunAction, rhs: RunAction) -> Bool { return lhs.config == rhs.config && lhs.executable == rhs.executable && lhs.arguments == rhs.arguments } }
// // ConceptTests.swift // ElementsOfProgrammingTests // import XCTest import EOP class Concept { // MARK: Chapter 1 static func regular<T: Regular>(x: T) { // Default constructor (not really invoked until an object is initialized in Swift) var y: T // Equality XCTAssert(x == x) // Assignment y = x XCTAssert(y == x) // Copy constructor let xCopy = x XCTAssert(xCopy == x) // Default total ordering XCTAssert(!less(x: x, y: x)) // Underlying type XCTAssert(type(of: x) == T.self) // Destructor } static func totallyOrdered<T: Regular>(x0: T, x1: T) { // Precondition: x0 < x1 XCTAssert(x0 != x1) XCTAssert(!(x0 == x1)) // Natural total ordering XCTAssert(!(x0 < x0)) XCTAssert(x0 < x1) XCTAssert(x1 > x0) XCTAssert(x0 <= x1) XCTAssert(x1 >= x0) XCTAssert(!(x1 < x0)) XCTAssert(!(x0 > x1)) XCTAssert(!(x1 <= x0)) XCTAssert(!(x0 >= x1)) } // MARK: Chapter 2 static func transformation<DomainF: Distance>(f: Transformation<DomainF>, x: DomainF) { typealias CodomainF = DomainF typealias X = DomainF typealias Y = CodomainF // X == Y var y = x XCTAssert(x == y) y = f(y) var n = N(1) } static func unaryPredicate<DomainP: Regular>(p: UnaryPredicate<DomainP>, x: DomainP) { typealias X = DomainP var x0: X, x1: X if p(x) { x0 = x } else { x1 = x } } // MARK: Chapter 3 static func binaryOperation<DomainOp: Regular>(op: BinaryOperation<DomainOp>, x: DomainOp) { typealias CodomainOp = DomainOp typealias X = DomainOp typealias Y = CodomainOp var y = x XCTAssert(x == y) y = op(x, x) } static func integer(n: Int) { typealias I = Int let k = I(11) Concept.regular(x: n) var m: I m = n + k m = n + k m = m - k m = m * k m = m / k m = m % k m = I(0) // ensure m < k Concept.totallyOrdered(x0: m, x1: k) m = n.successor() m = n.predecessor() m = m.twice() m = m.halfNonnegative() m = m.binaryScaleDownNonnegative(k: I(1)) m = m.binaryScaleUpNonnegative(k: I(1)) let bp = m.isPositive() let bn = m.isNegative() XCTAssert(!(bp && bn)) let bz = m.isZero() XCTAssert((bz && !(bn || bp)) || (!bz && (bn || bp))) let b1 = m.isOne() XCTAssert(!(bz && b1)) XCTAssert(!b1 || bp) let be = m.isEven() let bo = m.isOdd() XCTAssert(be != bo) } // MARK: Chapter 4 static func relation<DomainR: Regular>(r: Relation<DomainR>, x: DomainR) { typealias X = DomainR let y: X, z: X if r(x,x) { y = x } else { z = x } } // MARK: Chapter 5 static func orderedAdditiveSemigroup<T: OrderedAdditiveSemigroup>(x: T, y: T, z: T) { // Precondition: x < y Concept.regular(x: x) // + : T x T -> T let a = (x + y) + z let b = x + (y + z) XCTAssert(a == b) XCTAssert(x + y == y + x) Concept.totallyOrdered(x0: x, x1: y) XCTAssert(x + z < y + z) } static func orderedAdditiveMonoid<T: OrderedAdditiveMonoid>(x: T, y: T, z: T) { Concept.orderedAdditiveSemigroup(x: x, y: y, z: z) // 0 in T XCTAssert(x + T.additiveIdentity == x) } static func orderedAdditiveGroup<T: OrderedAdditiveGroup>(x: T, y: T, z: T) { // Precondition: x < y Concept.orderedAdditiveMonoid(x: x, y: y, z: z) // - : T -> T XCTAssert(x + (-x) == T.additiveIdentity) } static func cancellableMonoid<T: CancellableMonoid>(x: T, y: T, z: T) { // Precondition: x < y Concept.orderedAdditiveMonoid(x: x, y: y, z: z) // - : T x T -> T if x <= y { let z = y - x // defined XCTAssert(z + x == y) } } static func archimedeanMonoid<T: ArchimedeanMonoid>(x: T, y: T, z: T, n: QuotientType) { // Precondition: x < y Concept.cancellableMonoid(x: x, y: y, z: z) typealias N = QuotientType Concept.integer(n: n) // slow_remainder terminates for all positive arguments } static func archimedeanGroup<T: ArchimedeanGroup>(x: T, y: T, z: T, n: QuotientType) { // Precondition: x < y Concept.archimedeanMonoid(x: x, y: y, z: z, n: n) let tmp = x - y XCTAssert(tmp < T.additiveIdentity) XCTAssert(-tmp == y - x) } }
// // ChatListConstants.swift // sendit-ios // // Created by Andy on 18/7/20. // Copyright © 2020 Aditya Pokharel. All rights reserved. // extension ChatListView { enum Constants { static let errorMessageFetch = "CHAT Error decoding current user." static let navigationTitle = "Your Chats" } }
// //JS调用原生方法类 import Foundation typealias JSCallback = (String, Bool)->Void class JsApiTestSwift: NSObject { var value = 10 var feedbankHandler : JSCallback? var valueTimer: Timer? // MARK: - 同步调用H5的onMessage方法 @objc func jimuLogin( _ arg:Any) -> Dictionary<String, Any> { print(arg) let dic: Dictionary = ["result" : "i love u", "errorCode" : 0] as [String : Any] //NotificationCenter.default.post(name: Notification.Name(rawValue: "onMessage"), object: nil) return dic } // MARK: - 异步调用H5的onMessage方法 @objc func showException( _ arg:Any) -> Dictionary<String, Any> { print(arg) let dic: Dictionary = ["name" : "liudashen", "age" : 20] as [String : Any] //NotificationCenter.default.post(name: Notification.Name(rawValue: "onMessage"), object: nil) return dic } // MARK: - 测试同步方法 //MUST use "_" to ignore the first argument name explicitly。 @objc func testSyn( _ arg:String) -> String { print("js调用了原生的testSyn方法") return String(format:"%@[Swift sync call:%@]", arg, "test") } // MARK: - 测试异步有回调 @objc func testAsyn( _ arg:String, handler: JSCallback) { print("js调用了原生的testAsyn方法") handler(String(format:"%@[Swift async call:%@]", arg, "test"), true) } // MARK: - 带有dic参数的 @objc func testNoArgSyn( _ args:Dictionary<String, Any>) -> String{ print("js调用了原生的testNoArgSyn方法") return String("带有dic参数的的方法") } // MARK: - 持续返回进度 @objc func callProgress( _ args:Dictionary<String, Any> , handler: @escaping JSCallback ){ print("js调用了原生的callProgress方法") feedbankHandler = handler valueTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(feedbackValue), userInfo: nil, repeats: true) } //返回进度value @objc func feedbackValue() { if let handler = feedbankHandler { if value > 0{ handler(String(value), false)//上传中 value -= 1 }else { handler(String(value), true)//上传完成 } } } }
import Foundation import Cocoa import OpenGL enum QueueEntry { case Point(CGPoint, Brush) case Finish case Destroy } class GLDrawingKernel : NSThread, DrawingKernel { let imageSize : CGSize var queue : [QueueEntry] = [] var queueLock : NSLock = NSLock() var openGLContext : NSOpenGLContext! var program : GLuint = GLuint() var vertexArray : GLuint = GLuint() var scaleUniform : GLint = GLint() var offsetUniform : GLint = GLint() var colorUniform : GLint = GLint() var hardnessUniform : GLint = GLint() //delegation pattern here instead? var updateFunc : ((image : NSImage) -> Void)? var finishFunc : (() -> Void)? var conditionLock : NSConditionLock var buffer : UnsafeMutablePointer<UInt8>? var bufferSize : Int = 0; init(size : CGSize) { self.imageSize = size conditionLock = NSConditionLock(condition: ThreadState.Waiting.rawValue) super.init() self.start() } deinit { buffer?.destroy(bufferSize) } func startDraw(update : (image : NSImage) -> Void) { updateFunc = update } func addPoint(point : CGPoint, brush : Brush) { queueLock.lock() queue.append(.Point(point, brush)) queueLock.unlock() runWork() } func stopDraw(finish : () -> Void) { finishFunc = finish queueLock.lock() queue.append(.Finish) queueLock.unlock() runWork() } func doneDrawing() -> Bool { queueLock.lock() let left = queue.count queueLock.unlock() return left == 0 } func destroy() { queueLock.lock() queue.append(.Destroy) queueLock.unlock() runWork() } // Must only be called on the GLDrawingThread func tearDownOpenGL() { openGLContext.clearDrawable() } func createShaderProgram() { // Compile shaders and create glsl program let vertexShader : GLuint = glCreateShader(GLenum(GL_VERTEX_SHADER)) let vertPath = NSBundle.mainBundle().pathForResource("GLDrawingKernelVsh", ofType: "vsh")! let vertSource = NSString(contentsOfFile: vertPath, encoding: NSUTF8StringEncoding, error: nil)! glShaderSource(vertexShader, 1, [vertSource.UTF8String], [GLint(Int32(vertSource.length))]) glCompileShader(vertexShader) let fragPath = NSBundle.mainBundle().pathForResource("GLDrawingKernelFsh", ofType: "fsh")! let fragmentShader : GLuint = glCreateShader(GLenum(GL_FRAGMENT_SHADER)) let fragSource = NSString(contentsOfFile: fragPath, encoding: NSUTF8StringEncoding, error: nil)! glShaderSource(fragmentShader, 1, [fragSource.UTF8String], [GLint(Int32(fragSource.length))]) glCompileShader(fragmentShader) program = glCreateProgram() glAttachShader(program, vertexShader) glAttachShader(program, fragmentShader) glLinkProgram(program) } func setupOffscreenRendering() { let glPFAttributes:[NSOpenGLPixelFormatAttribute] = [ UInt32(NSOpenGLPFAAccelerated), UInt32(NSOpenGLPFADoubleBuffer), UInt32(NSOpenGLPFAMultisample), UInt32(NSOpenGLPFASampleBuffers), UInt32(1), UInt32(NSOpenGLPFASamples), UInt32(4), UInt32(NSOpenGLPFAMinimumPolicy), UInt32(0) ] let pixelFormat = NSOpenGLPixelFormat(attributes: glPFAttributes) openGLContext = NSOpenGLContext(format: pixelFormat, shareContext: nil) openGLContext.makeCurrentContext() openGLContext.update() let height = UInt(imageSize.height) let width = UInt(imageSize.width) // Framebuffer for offscreen rendering and copying pixels var frameBuffer : GLuint = 0 glGenFramebuffersEXT(1, &frameBuffer) glBindFramebufferEXT(GLenum(GL_FRAMEBUFFER_EXT), frameBuffer) var texture : GLuint = 0 glGenTextures(1, &texture) glBindTexture(GLenum(GL_TEXTURE_2D), texture) glTexImage2D(GLenum(GL_TEXTURE_2D), GLint(0), GLint(GL_RGBA8), GLsizei(width), GLsizei(height), GLint(0), GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), UnsafePointer.null()) glFramebufferTexture2DEXT(GLenum(GL_FRAMEBUFFER_EXT), GLenum(GL_COLOR_ATTACHMENT0_EXT), GLenum(GL_TEXTURE_2D), texture, GLint(0)) var renderbuffer : GLuint = 0 glGenRenderbuffersEXT(1, &renderbuffer) glBindRenderbufferEXT(GLenum(GL_RENDERBUFFER_EXT), renderbuffer) glRenderbufferStorageEXT(GLenum(GL_RENDERBUFFER_EXT), GLenum(GL_RGBA8), GLsizei(width), GLsizei(height)) glFramebufferRenderbufferEXT(GLenum(GL_FRAMEBUFFER_EXT), GLenum(GL_COLOR_ATTACHMENT0_EXT), GLenum(GL_RENDERBUFFER_EXT), renderbuffer) let status = glCheckFramebufferStatusEXT(GLenum(GL_FRAMEBUFFER_EXT)) if Int32(status) != GL_FRAMEBUFFER_COMPLETE_EXT { log.error("Could not setup framebuffer") } } func setupUniforms() { // Get uniforms scaleUniform = glGetUniformLocation(program, ("scale" as NSString).UTF8String) if scaleUniform < 0 { log.error("Error in getting scale uniform") } offsetUniform = glGetUniformLocation(program, ("offset" as NSString).UTF8String) if offsetUniform < 0 { log.error("Error in getting offset uniform") } colorUniform = glGetUniformLocation(program, ("color" as NSString).UTF8String) if colorUniform < 0 { log.error("Error in getting color uniform") } hardnessUniform = glGetUniformLocation(program, ("hardness" as NSString).UTF8String) if hardnessUniform < 0 { log.error("Error in getting color uniform") } } func setupVerticies() { // Set up verticies glGenVertexArrays(1, &vertexArray) glBindVertexArray(vertexArray) var vertexBuffer : GLuint = GLuint() glGenBuffers(1, &vertexBuffer) glBindBuffer(GLenum(GL_ARRAY_BUFFER), vertexBuffer) // Verticies for a size 2 square centered at the origin let vertexData : [GLfloat] = [ -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0 ] glBufferData(GLenum(GL_ARRAY_BUFFER), vertexData.count * sizeof(GLfloat.self), vertexData, GLenum(GL_DYNAMIC_DRAW)) let triangleVertexPosition = glGetAttribLocation(program, ("vertex_position" as NSString).UTF8String) if triangleVertexPosition < 0 { log.error("Failed to get vertex_pos attribute location") } let posIndex = GLuint(triangleVertexPosition) glEnableVertexAttribArray(posIndex) glVertexAttribPointer(posIndex, 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 0, UnsafePointer.null()) glBindBuffer(GLenum(GL_ARRAY_BUFFER), 0) } // Must only be called on the GLDrawingThread func setupOpenGL() { setupOffscreenRendering() // Set up view and clear let height = UInt(imageSize.height) let width = UInt(imageSize.width) glViewport(0, 0, GLsizei(width), GLsizei(height)) glClearColor(0.0, 0.0, 0.0, 0.0) glClear(GLenum(GL_COLOR_BUFFER_BIT)) createShaderProgram() setupUniforms() setupVerticies() // Transparency support. glEnable(GLenum(GL_BLEND)) glBlendEquationSeparate(GLenum(GL_FUNC_ADD), GLenum(GL_MAX)) } // Must only be called on the GLDrawingThread func getImageFromBuffer() -> NSImage { let height : UInt = UInt(imageSize.height) let width : UInt = UInt(imageSize.width) if buffer == nil { bufferSize = Int(4 * height * width) buffer = UnsafeMutablePointer<UInt8>.alloc(bufferSize) } glReadPixels(0, 0, GLsizei(width), GLsizei(height), GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), buffer!) let representation = NSBitmapImageRep(bitmapDataPlanes: &buffer!, pixelsWide: Int(width), pixelsHigh: Int(height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bitmapFormat:NSBitmapFormat.NSAlphaNonpremultipliedBitmapFormat, bytesPerRow: 4 * Int(width), bitsPerPixel: 32) var image = NSImage(size: imageSize) if let rep = representation { image.addRepresentation(rep) } else { log.error("No image rep from GL") } return image } // Must only be called on the GLDrawingThread func updateDraw(point : CGPoint, brush : Brush) { openGLContext.makeCurrentContext() glUseProgram(program) glBindVertexArray(vertexArray) glUniform2f(scaleUniform, GLfloat(brush.size/imageSize.width), GLfloat(brush.size/imageSize.height)) let offsetX = (point.x / imageSize.width) * 2 - 1.0 let offsetY = 1.0 - (point.y / imageSize.height) * 2 glUniform2f(offsetUniform, GLfloat(offsetX), GLfloat(offsetY)) let color = brush.color glUniform3f(colorUniform, GLfloat(color.redComponent), GLfloat(color.greenComponent), GLfloat(color.blueComponent)) glUniform1f(hardnessUniform, GLfloat(brush.hardness)) glDrawArrays(GLenum(GL_TRIANGLES), 0, 6) glUseProgram(0) glBindVertexArray(0) } private func runWork() { conditionLock.lock() conditionLock.unlockWithCondition(ThreadState.WorkTodo.rawValue) } override func main() { setupOpenGL() var lastPoint : CGPoint? = nil while true { conditionLock.lockWhenCondition(ThreadState.WorkTodo.rawValue) conditionLock.unlockWithCondition(ThreadState.Waiting.rawValue) queueLock.lock() var count = queue.count queueLock.unlock() while count > 0 { queueLock.lock() let queueEntry = queue[0] queueLock.unlock() switch queueEntry { case .Point(let currentPoint, let brush): if let lp = lastPoint { let numInterpolate = 20 // Linearly interpolate and draw <numInterpolate> sprites inbetween points // Relative to the image copy this is very fast. // TODO: Consider varying number of sprites depending on distance for i in 0..<numInterpolate { let t = CGFloat(i) / CGFloat(numInterpolate) let x = t*lp.x + (1.0 - t) * currentPoint.x let y = t*lp.y + (1.0 - t) * currentPoint.y updateDraw(CGPoint(x: x, y: y), brush: brush) } } lastPoint = currentPoint let image = getImageFromBuffer() if let update = updateFunc { update(image: image) } case .Finish: glClearColor(0.0, 0.0, 0.0, 0.0) glClear(GLenum(GL_COLOR_BUFFER_BIT)) if finishFunc != nil { finishFunc!() lastPoint = nil finishFunc = nil updateFunc = nil } case .Destroy: tearDownOpenGL() queueLock.lock() queue.removeAtIndex(0) queueLock.unlock() return } // Important, remove at end to prevent a race condition queueLock.lock() queue.removeAtIndex(0) count = queue.count queueLock.unlock() } } } }
// // Disclaimer.swift // proj4 // // Created by Joseph Ham on 5/6/21. // Copyright © 2021 Sam Spohn. All rights reserved. // import SwiftUI struct Disclaimer: View { var body: some View { VStack{ Text("[Legal Disclaimer Here]\n\n©2021 The Smart Apples and Alcor, \nAll Rights Reserved.") .font(.title2) .multilineTextAlignment(.center) } } } struct Disclaimer_Previews: PreviewProvider { static var previews: some View { Disclaimer() } }
// // SourceListRow.swift // Feedit // // Created by Tyler D Lawrence on 8/10/20. // import SwiftUI import SwipeCell import UIKit import Intents import FeedKit struct RSSRow: View { @ObservedObject var imageLoader: ImageLoader @ObservedObject var rss: RSS init(rss: RSS) { self.rss = rss self.imageLoader = ImageLoader(path: rss.image) } private func iconImageView(_ image: UIImage) -> some View { Image(uiImage: image) .resizable() .cornerRadius(0) .animation(.easeInOut) .border(Color.white, width: 1) } private var pureTextView: some View { VStack(spacing: 0.0) { Text(rss.title) .font(.body) .multilineTextAlignment(.leading) .lineLimit(1) //.contextMenu { //EditButton() //Spacer() //Text("Article List") //Text("Details") //Text("Unsubscribe") } // below are options to have parsed feed description and last updated time //Text(rss.desc) //.font(.subheadline) //.lineLimit(1) //Text(rss.createTimeStr) //.font(.footnote) //.foregroundColor(.gray) } var body: some View { HStack() { VStack(alignment: .center) { HStack { if self.imageLoader.image != nil { iconImageView(self.imageLoader.image!) .font(.body) .frame(width: 20.0, height: 20.0,alignment: .center) //.layoutPriority(10) pureTextView } else { Image(systemName:"dot.squareshape") .font(.body) //"dock.rectangle" .foregroundColor(Color.gray) .frame(width: 20, height: 20, alignment: .center) //.cornerRadius(2) .animation(.easeInOut) .imageScale(.large) pureTextView } } // Text(rss.createTimeStr) // .font(.footnote) // .foregroundColor(.gray) } } .padding(.top, 10) .padding(.bottom, 10) //.frame(maxWidth: .infinity, alignment: .leading) //.background(Color(red: 32/255, green: 32/255, blue: 32/255)) } } struct RSSRow_Previews: PreviewProvider { static var previews: some View { ContentView() .preferredColorScheme(.dark) .previewDevice("iPhone 11") } }
// // ViewController.swift // WKWebViewTest // // Created by Johannes H on 11.08.2016. // Copyright © 2016 Johannes Harestad. All rights reserved. // import UIKit import WebKit class ViewController: UIViewController, WKScriptMessageHandler { var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() let contentController = WKUserContentController() contentController.addScriptMessageHandler(self, name: "callbackHandler") let wkConfig = WKWebViewConfiguration() wkConfig.userContentController = contentController webView = WKWebView(frame: view.bounds, configuration: wkConfig) view.addSubview(webView) /* if you want to use local files, this is how you do can do it if let webAppPath = NSBundle.mainBundle().resourcePath?.stringByAppendingString(webDir) { let webAppURL = NSURL(fileURLWithPath: webAppPath, isDirectory: true) // Locate the index.html file if let indexPath = NSBundle.mainBundle().resourcePath?.stringByAppendingString("\(webDir)/index.html") { let indexURL = NSURL(fileURLWithPath: indexPath) webView.loadFileURL(indexURL, allowingReadAccessToURL: webAppURL) } }*/ /* USE A SERVER/LOCALHOST `npm start` inside AngularApp */ let localhostURL = NSURL(string: "http://localhost:8000")! let localhostRequest = NSURLRequest(URL: localhostURL) webView.loadRequest(localhostRequest) } func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if message.name == "callbackHandler" { guard let data = message.body as? [String: AnyObject] else { return } guard let somethingUnique = data["unique"] else { return } guard let message = data["message"] else { return } let randomTime = Double(arc4random_uniform(2) + 3) // between 2 and 5 seconds waiting time print("Received data from JavaScript, doing some async work that will take \(randomTime) seconds") let dispatchDelay = dispatch_time(DISPATCH_TIME_NOW, Int64(randomTime * Double(NSEC_PER_SEC))) dispatch_after(dispatchDelay, dispatch_get_main_queue()) { [unowned self] in print("Will return to JavaScript with some data") let evaluate = "callMeFromSwift({'unique': \(somethingUnique), 'message': '\(message)'})" self.webView.evaluateJavaScript(evaluate, completionHandler: nil) } } } }
// // ZQKTVHTTPCacheModel.swift // ZQOpenTools // // Created by Darren on 2020/6/22. // Copyright © 2020 Darren. All rights reserved. // import UIKit class ZQKTVHTTPCacheModel: NSObject { var title:String? var url:String? convenience init(title:String?, url:String?) { self.init() self.title = title self.url = url } }
// // ViewController.swift // srgtuszy // // Created by admin on 9/9/21. // import UIKit import SafariServices final class GitHubSearchVC: UIViewController { private let tableView = UITableView() private let searchController = UISearchController(searchResultsController: nil) private let queryService = GitHubQueryService() private var repositoryResults: Repository? private var timer: Timer? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Search" navigationController?.navigationBar.prefersLargeTitles = true setupTableView() setupSearchBar() } private func setupSearchBar() { definesPresentationContext = true navigationItem.searchController = self.searchController navigationItem.hidesSearchBarWhenScrolling = true searchController.searchBar.delegate = self let textFieldInsideSearchBar = searchController.searchBar.value(forKey: "searchField") as? UITextField textFieldInsideSearchBar?.placeholder = "Search keywords or qualifiers" } private func setupTableView() { let cellIdentifier = String(describing: RepositoryTableViewCell.self) view.addSubview(tableView) tableView.dataSource = self tableView.delegate = self tableView.register(UINib(nibName: cellIdentifier, bundle: nil), forCellReuseIdentifier: cellIdentifier) tableView.rowHeight = UITableView.automaticDimension tableView.translatesAutoresizingMaskIntoConstraints = false tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true tableView.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor).isActive = true tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true tableView.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor).isActive = true } private func loadRepositoriesData(search q: String) { queryService.getSearchResults(search: q) { (results) in switch results { case .success(let repositories): print(repositories.items) self.repositoryResults = repositories DispatchQueue.main.async { self.tableView.reloadData() } case .failure(let error): print(error.localizedDescription) } } } } extension GitHubSearchVC: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return repositoryResults?.items.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: RepositoryTableViewCell.self)) as! RepositoryTableViewCell cell.setRepositoryItem(repositoryResults?.items[indexPath.row]) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let repository = repositoryResults?.items[indexPath.row], let repositoryURL = repository.htmlUrl else { return } let safariVC = SFSafariViewController(url: repositoryURL) self.present(safariVC, animated: true, completion: nil) } } extension GitHubSearchVC: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { timer?.invalidate() timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: false, block: { (_) in self.loadRepositoriesData(search: searchText) }) } }
// // ItemDetailViewController.swift // PartyPlanner // // Created by Molly Soja on 10/21/19. // Copyright © 2019 Molly Soja. All rights reserved. // import UIKit class ItemDetailViewController: UIViewController { @IBOutlet weak var partyItemField: UITextField! @IBOutlet weak var personResponsibleField: UITextField! @IBOutlet weak var saveBarButton: UIBarButtonItem! var partyListItem: PartyListItem! override func viewDidLoad() { super.viewDidLoad() if partyListItem == nil { partyListItem = PartyListItem(partyItem: "", personResponsible: "") } partyItemField.text = partyListItem.partyItem personResponsibleField.text = partyListItem.personResponsible // Do any additional setup after loading the view. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { partyListItem.partyItem = partyItemField.text! partyListItem.personResponsible = personResponsibleField.text! } @IBAction func saveBarButtonPressed(_ sender: UIBarButtonItem) { } @IBAction func cancelBarButtonPressed(_ sender: UIBarButtonItem) { let isPresentingInAddMode = presentingViewController is UINavigationController if isPresentingInAddMode { dismiss(animated: true, completion: nil) } else { navigationController!.popViewController(animated: true) } } }
// // ProfileMainStore.swift // GitWorld // // Created by jiaxin on 2019/7/5. // Copyright © 2019 jiaxin. All rights reserved. // import SwiftUI import Combine struct UserInfo { let login: String let nick: String let followersCount: Int let followingCount: Int } class ProfileMainStore: BindableObject { var client = apolloClient var userInfo = UserInfo(login: "账号名", nick: "昵称", followersCount: 0, followingCount: 0) { didSet { didChange.send(self) } } var didChange = PassthroughSubject<ProfileMainStore, Never>() func fetch() { client.fetch(query: UserInfoQuery(), cachePolicy: .fetchIgnoringCacheData, queue: DispatchQueue.main) { (result, error) in if let viewer = result?.data?.viewer { let userInfo = UserInfo(login: viewer.login, nick: viewer.name ?? "默认昵称", followersCount: viewer.followers.totalCount, followingCount: viewer.following.totalCount) self.userInfo = userInfo } } } }
// // Tela2 Login.swift // WorkFit // // Created by IFCE on 16/02/17. // Copyright © 2017 Work Fit Team. All rights reserved. //259bf3 import UIKit import Firebase import FirebaseAuth class Tela2_Login: UIViewController,UITextFieldDelegate { @IBOutlet weak var bLoginFacebook: UIButtonBorder! @IBOutlet var txtEmail: TxtFieldImg! @IBOutlet var txtPassword: TxtFieldImg! @IBOutlet weak var bLogin: UIButtonRounded! @IBOutlet weak var bottomConstraint: NSLayoutConstraint! var originConstraintConstant : CGFloat = 0.0; let databaseRef = FIRDatabase.database().reference() override func viewDidLoad() { super.viewDidLoad() txtEmail.delegate = self txtPassword.delegate = self self.navigationController?.isNavigationBarHidden = false txtEmail.becomeFirstResponder() //bLogin.backgroundColor = UIColor.init(red: 0x00/255, green: 0x9f/255, blue: 0xf9/255, alpha: 1.0) txtPassword.editConfig(image: "Password Filled_20.png", position: true) txtEmail.editConfig(image: "Message Filled_20.png", position: true) registerKeyboardListeners() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) originConstraintConstant = bottomConstraint.constant } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) deregisterKeyboardListeners() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == self.txtEmail { self.txtPassword.becomeFirstResponder() } if textField == self.txtPassword { self.txtEmail.becomeFirstResponder() } return true } func registerKeyboardListeners() { NotificationCenter.default.addObserver(self, selector: #selector(Tela2_Login.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(Tela2_Login.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func deregisterKeyboardListeners(){ NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) } func keyboardWillShow(notification: Notification) { let userInfo = notification.userInfo let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue bottomConstraint.constant = keyboardSize.cgRectValue.height + 11 } func keyboardWillHide(notification: Notification) { bottomConstraint.constant = originConstraintConstant } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } @IBAction func bLogin(_ sender: UIButtonRounded) { if (txtEmail.text == "") || (txtPassword.text == "") { let alert = UIAlertController(title: "Atenção", message: "Insira todos os campos!", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } else { if ((txtEmail.text == "marllons") && (txtPassword.text == "marllons")) || ((txtEmail.text == "ivan") && (txtPassword.text == "ivan")) || ((txtEmail.text == "daniel") && (txtPassword.text == "daniel")) { self.performSegue(withIdentifier: "goToAdm", sender: self) return } if let email = txtEmail.text , let pass = txtPassword.text { FIRAuth.auth()?.signIn(withEmail: email, password: pass, completion: {(user, error) in if user != nil { if let user = FIRAuth.auth()?.currentUser { self.databaseRef.child("Clients").child(user.uid).child("levelAcess").observe(.value, with: { (snapshot) in let level = snapshot.value as? String UserDefaults.standard.set(level, forKey: "levelAcess") UserDefaults.standard.synchronize() if level == "1" { self.setupProfileUser() } else { self.setupProfileAdm() } }) } } else { let alert = UIAlertController(title: "Login Incorreto", message: "Usuário inexistente. Verifique se o email e senha estão corretos!", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } }) } } } @IBAction func bLoginFB(_ sender: UIButtonBorder) { appDelegate.handleLogout() } // MARK: - functions login func setupProfileUser(){ if FIRAuth.auth()?.currentUser?.uid == nil{ appDelegate.handleLogout() } else { let uid = FIRAuth.auth()?.currentUser?.uid // imgView.layer.cornerRadius = imgView.frame.size.width/2 // imgView.clipsToBounds = true //carregar foto de perfil aqui databaseRef.child("Clients").child(uid!).observe(.value, with: { (snapshot) in if let dict = snapshot.value as? [String: AnyObject]{ userCoach = (dict["coach"] as? String)! userCoachID = (dict["idCoach"] as? String)! userName = (dict["name"] as? String)! userAltura = (dict["altura"] as? String)! userBF = (dict["bf"] as? String)! userDietID = (dict["dietID"] as? String)! userDietKcal = (dict["dietKcal"] as? String)! userEmail = (dict["email"] as? String)! userUID = uid! userObj = (dict["goal"] as? String)! userCoachID = (dict["idCoach"] as? String)! userLevel = (dict["levelAcess"] as? String)! userPeso = (dict["peso"] as? String)! userPic = (dict["pic"] as? String)! userTMB = (dict["tmb"] as? String)! userTrainID = (dict["trainID"] as? String)! //userCoachPic = (dict["name"] as? String)! } }) self.appDelegate.handleLogin() } } func setupProfileAdm(){ if FIRAuth.auth()?.currentUser?.uid == nil{ appDelegate.handleLogout() } else { let uid = FIRAuth.auth()?.currentUser?.uid // imgView.layer.cornerRadius = imgView.frame.size.width/2 // imgView.clipsToBounds = true //carregar foto de perfil aqui databaseRef.child("Clients").child(uid!).observe(.value, with: { (snapshot) in if let dict = snapshot.value as? [String: AnyObject]{ userName = (dict["name"] as? String)! userEmail = (dict["email"] as? String)! userUID = uid! userCoachID = (dict["idCoach"] as? String)! userLevel = (dict["levelAcess"] as? String)! userPic = (dict["pic"] as? String)! //userCoachPic = (dict["name"] as? String)! } }) self.appDelegate.handleLogin() } } @IBAction func forgotPass(_ sender: Any) { if (txtEmail.text == ""){ let alert = UIAlertController(title: "Error", message: "Insert the email first!!", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } else { FIRAuth.auth()?.sendPasswordReset(withEmail: txtEmail.text!) { error in if let error = error { let alert = UIAlertController(title: "Error", message: "An error has ocurred", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } else { let alert = UIAlertController(title: "Atention!", message: "Email for recover has been sent", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } } } }
// // TextFileCell.swift // FileAnalyzer // // Created by Carlos Gonzalez on 24/4/21. // import UIKit class TextFileCell: UITableViewCell { static let TAG = String(describing: TextFileCell.self) @IBOutlet weak var tv_file_name: UILabel! override func awakeFromNib() { super.awakeFromNib() } public func setCell(_ file: FileObject) { tv_file_name.text = "\(file.getName())\(file.getFileType())" } public func selectRow() { self.accessoryType = .checkmark } public func deselectRow() { self.accessoryType = .none } }
// // TweetRowView.swift // TweetSearchApp // // Created by Mitsuaki Ihara on 2020/12/02. // import SwiftUI struct TweetRowView: View { var tweet: Tweet var body: some View { HStack { URLImageView(viewModel: .init(url: tweet.user.profileImageUrl)) .frame(width: 56, height: 56) .clipShape(Circle()) Text(tweet.text).padding(10) Spacer() Text(tweet.user.name) } .padding(30) } }
// // PTMainTabCollectionHeaderView.swift // wwg // // Created by dewey on 2018. 7. 13.. // Copyright © 2018년 dewey. All rights reserved. // import UIKit import GoogleMobileAds import MapKit class PTMainTabCollectionHeaderView: UICollectionReusableView { static var reuseIdentifier: String { return NSStringFromClass(self) } var bannerView: GADBannerView! override func awakeFromNib() { super.awakeFromNib() let adSize = GADAdSizeFromCGSize(self.frameSize()) self.bannerView = GADBannerView(adSize: adSize) // self.bannerView.adUnitID = "ca-app-pub-3918803652819009/7146182843" self.bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716" // For Test /* * Set ad targetting */ let request = GADRequest() let extras = GADExtras() extras.additionalParameters = ["max_ad_content_rating": "T"] request.register(extras) if let currentLocation = CLLocationManager().location { request.setLocationWithLatitude(CGFloat(currentLocation.coordinate.latitude), longitude: CGFloat(currentLocation.coordinate.longitude), accuracy: CGFloat(currentLocation.horizontalAccuracy)) } bannerView.load(request) bannerView.delegate = self /* * Add */ self.addSubview(self.bannerView) self.bannerView.translatesAutoresizingMaskIntoConstraints = false self.bannerView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true self.bannerView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true self.bannerView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true self.bannerView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true } } extension PTMainTabCollectionHeaderView: GADBannerViewDelegate { /// Tells the delegate an ad request loaded an ad. func adViewDidReceiveAd(_ bannerView: GADBannerView) { print("adViewDidReceiveAd") } /// Tells the delegate an ad request failed. func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError) { print("adView:didFailToReceiveAdWithError: \(error.localizedDescription)") } /// Tells the delegate that a full-screen view will be presented in response /// to the user clicking on an ad. func adViewWillPresentScreen(_ bannerView: GADBannerView) { print("adViewWillPresentScreen") } /// Tells the delegate that the full-screen view will be dismissed. func adViewWillDismissScreen(_ bannerView: GADBannerView) { print("adViewWillDismissScreen") } /// Tells the delegate that the full-screen view has been dismissed. func adViewDidDismissScreen(_ bannerView: GADBannerView) { print("adViewDidDismissScreen") } /// Tells the delegate that a user click will open another app (such as /// the App Store), backgrounding the current app. func adViewWillLeaveApplication(_ bannerView: GADBannerView) { print("adViewWillLeaveApplication") } }
/* Copyright Airship and Contributors */ import Foundation import CoreData /** * Pending chat message data. */ @objc(UAPendingChatMessageData) class PendingChatMessageData : NSManagedObject, PendingChatMessageDataProtocol { /** * The message ID. */ @NSManaged dynamic var requestID: String /** * The message text. */ @NSManaged dynamic var text: String? /** * The message URL */ @NSManaged dynamic var attachment: URL? /** * The message created date. */ @NSManaged dynamic var createdOn: Date /** * The message source. */ @NSManaged dynamic var direction: UInt }
// // UiButtonExtension.swift // caffinho-iOS // // Created by Jose Ricardo de Oliveira on 6/20/16. // Copyright © 2016 venturus. All rights reserved. // import Foundation @IBDesignable extension UIButton { @IBInspectable var borderColor: UIColor? { set { layer.borderColor = newValue?.CGColor } get { if let color = layer.borderColor { return UIColor(CGColor:color) } else { return nil } } } }
// // TabBarButtonView.swift // SimpleGoceryList // // Created by Payton Sides on 6/15/21. // import SwiftUI struct TabBarButtonView: View { //MARK: - Properties @Binding var current : String var image : String var animation : Namespace.ID //MARK: - Body var body: some View { Button(action: { withAnimation{current = image} }) { VStack(spacing: 5){ Image(systemName: image) .font(.title2) .foregroundColor(current == image ? .mint : Color.black.opacity(0.3)) // default Frame to avoid resizing... .frame(height: 35) ZStack{ Rectangle() .fill(Color.clear) .frame(height: 4) // matched geometry effect slide animation... if current == image{ Rectangle() .fill(Color.orange.opacity(0.6)) .frame(height: 4) .matchedGeometryEffect(id: "Tab", in: animation) } } } } } }
// This source file is part of the https://github.com/ColdGrub1384/Pisth open source project // // Copyright (c) 2017 - 2019 Adrian Labbé // Licensed under Apache License v2.0 // // See https://raw.githubusercontent.com/ColdGrub1384/Pisth/master/LICENSE for license information #if os(iOS) import UIKit #endif #if os(macOS) import Cocoa #endif /// Default theme for the terminal. Uses system appearance. open class DefaultTheme: TerminalTheme { #if os(iOS) open override var keyboardAppearance: UIKeyboardAppearance { if #available(iOS 13.0, *) { if UITraitCollection.current.userInterfaceStyle == .dark { return .dark } else { return .default } } else { return .default } } open override var toolbarStyle: UIBarStyle { return .default } #endif open override var selectionColor: Color? { #if os(macOS) return Color.selectedControlColor #else if #available(iOS 11.0, *) { return UIColor(named: "Purple") ?? Color.systemPurple } else { return Color.systemPurple } #endif } open override var backgroundColor: Color? { #if os(macOS) if #available(OSX 10.14, *) { if NSAppearance.current.name == .darkAqua || NSAppearance.current.name == .accessibilityHighContrastDarkAqua { return Color(red: 30/255, green: 30/255, blue: 30/255, alpha: 1) } else { return .white } } else { return .white } #else if #available(iOS 13.0, *) { return Color { (traitCollection) -> UIColor in if traitCollection.userInterfaceStyle == .dark { return .black } else { return .white } } } else { return Color.white } #endif } open override var foregroundColor: Color? { #if os(macOS) if #available(OSX 10.14, *) { if NSAppearance.current.name == .darkAqua || NSAppearance.current.name == .accessibilityHighContrastDarkAqua { return .white } else { return .black } } else { return .black } #else if #available(iOS 13.0, *) { return Color.label } else { return Color.black } #endif } open override var cursorColor: Color? { return foregroundColor } }
// // FansViewController.swift // IAmPet // // Created by 长浩 张 on 2017/10/3. // Copyright © 2017年 changhaozhang. All rights reserved. // import Foundation class FansViewController: SBaseViewController { var tableView: UITableView?; override func viewDidLoad() { super.viewDidLoad(); setNavTitle("关注者") initView(); } /** init view - returns: Void */ private func initView() { self.automaticallyAdjustsScrollViewInsets = false; addTableView(); } /** add tableview */ private func addTableView() { let frame = CGRect(x: 0, y: 64, width: ScreenWidth, height: ScreenHeight - 64); tableView = UITableView(frame: frame, style:.plain); tableView?.delegate = self; tableView?.dataSource = self; tableView?.tableFooterView = UIView(frame: CGRect.zero); view.addSubview(tableView!); } } //MARK: - UITableViewDataSource extension FansViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1; } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: FansCell.identifier) as? FansCell; if (nil == cell) { cell = FansCell.loadNib(); } cell?.imgHead = UIImage(named: "icon_icon.jpg"); cell?.nickName = "不吃鱼的喵"; cell?.introduce = "本喵是个素食主义喵"; weak var weakCell = cell; cell?.changeConcerned = { (isConcerned: Bool) -> Void in if (isConcerned) { weakCell?.isConcerned = false; } else { weakCell?.isConcerned = true; } }; if (0 == indexPath.row % 2) { cell?.isConcerned = true; } else { cell?.isConcerned = false; } return cell!; } } //MARK: - UITableViewDelegate extension FansViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return FansCell.cellHeight; } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let controller = PersonHomeViewController(); controller.hidesBottomBarWhenPushed = true; controller.personName = "不吃鱼的喵"; self.navigationController?.pushViewController(controller, animated: true); } }
// // CoinTableViewCell.swift // CryptoWalletTest // // Created by Матвей Анисович on 6/11/21. // import UIKit class CoinTableViewCell: UITableViewCell { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var symbolLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var holdingsLabel: UILabel! @IBOutlet weak var holdingsUsdLabel: UILabel! @IBOutlet weak var coinPriceLabel: UILabel! @IBOutlet weak var profitLabel: UILabel! }
// // AdvancedExampleViewController.swift // GradientLoadingBar_Example // // Created by Felix Mau on 29.08.18. // Copyright © 2018 CocoaPods. All rights reserved. // import UIKit import GradientLoadingBar class AdvancedExampleViewController: UIViewController { // MARK: - Outlets @IBOutlet var customSuperviewButton: BlueBorderedButton! @IBOutlet var customColorsButton: BlueBorderedButton! // MARK: - Private properties private var buttonGradientLoadingBar: GradientLoadingBar? private var customColorsGradientLoadingBar: GradientLoadingBar? // MARK: - Public methods override func viewDidLoad() { super.viewDidLoad() buttonGradientLoadingBar = GradientLoadingBar(height: 3.0, onView: customSuperviewButton) // Source: https://color.adobe.com/Pink-Flamingo-color-theme-10343714/ let gradientColorList = [ #colorLiteral(red: 0.9490196078, green: 0.3215686275, blue: 0.431372549, alpha: 1), #colorLiteral(red: 0.9450980392, green: 0.4784313725, blue: 0.5921568627, alpha: 1), #colorLiteral(red: 0.9529411765, green: 0.737254902, blue: 0.7843137255, alpha: 1), #colorLiteral(red: 0.4274509804, green: 0.8666666667, blue: 0.9490196078, alpha: 1), #colorLiteral(red: 0.7568627451, green: 0.9411764706, blue: 0.9568627451, alpha: 1) ] customColorsGradientLoadingBar = BottomGradientLoadingBar(height: 3.0, gradientColorList: gradientColorList, onView: customColorsButton) } @IBAction func customSuperviewButtonTouchUpInside(_: Any) { buttonGradientLoadingBar?.toggle() } @IBAction func customGradientColorsButtonTouchUpInside(_: Any) { customColorsGradientLoadingBar?.toggle() } } // MARK: - UIBarPositioningDelegate // Notice: Delegate is setted-up via storyboard. extension AdvancedExampleViewController: UINavigationBarDelegate { func position(for _: UIBarPositioning) -> UIBarPosition { return .topAttached } }
// // ViewController.swift // PiaSysTechBitesGraphConsumer01 // // Created by Paolo Pialorsi on 16/12/21. // import UIKit import MSAL class ViewController: UIViewController { let kClientID = "4441676f-d34b-4640-9185-c1268a211441" let kRedirectUri = "msauth.PaoloPia.PiaSysTechBitesGraphConsumer01://auth" let kAuthority = "https://login.microsoftonline.com/6c94075a-da0a-4c6a-8411-badf652e8b53" let kGraphEndpoint = "https://graph.microsoft.com/" let kScopes: [String] = ["user.read", "calendars.read"] var accessToken = String() var applicationContext : MSALPublicClientApplication? var webViewParameters : MSALWebviewParameters? var currentAccount: MSALAccount? var loggingText: UITextView! var signOutButton: UIButton! var callGraphButton: UIButton! var usernameLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() initUI() do { try self.initMSAL() } catch let error { self.updateLogging(text: "Unable to create Application Context \(error)") } self.loadCurrentAccount() self.platformViewDidLoadSetup() } func initMSAL() throws { guard let authorityURL = URL(string: kAuthority) else { self.updateLogging(text: "Unable to create authority URL") return } let authority = try MSALAADAuthority(url: authorityURL) let msalConfiguration = MSALPublicClientApplicationConfig(clientId: kClientID, redirectUri: nil, authority: authority) self.applicationContext = try MSALPublicClientApplication(configuration: msalConfiguration) self.initWebViewParams() } func initWebViewParams() { self.webViewParameters = MSALWebviewParameters(authPresentationViewController: self) } func getGraphEndpoint() -> String { return kGraphEndpoint.hasSuffix("/") ? (kGraphEndpoint + "v1.0/me/events") : (kGraphEndpoint + "/v1.0/me/events"); } @objc func callGraphAPI(_ sender: AnyObject) { self.loadCurrentAccount { (account) in guard let currentAccount = account else { // We check to see if we have a current logged in account. // If we don't, then we need to sign someone in. self.acquireTokenInteractively() return } self.acquireTokenSilently(currentAccount) } } typealias AccountCompletion = (MSALAccount?) -> Void func loadCurrentAccount(completion: AccountCompletion? = nil) { guard let applicationContext = self.applicationContext else { return } let msalParameters = MSALParameters() msalParameters.completionBlockQueue = DispatchQueue.main applicationContext.getCurrentAccount(with: msalParameters, completionBlock: { (currentAccount, previousAccount, error) in if let error = error { self.updateLogging(text: "Couldn't query current account with error: \(error)") return } if let currentAccount = currentAccount { self.updateLogging(text: "Found a signed in account \(String(describing: currentAccount.username)). Updating data for that account...") self.updateCurrentAccount(account: currentAccount) if let completion = completion { completion(self.currentAccount) } return } self.updateLogging(text: "Account signed out. Updating UX") self.accessToken = "" self.updateCurrentAccount(account: nil) if let completion = completion { completion(nil) } }) } func acquireTokenInteractively() { guard let applicationContext = self.applicationContext else { return } guard let webViewParameters = self.webViewParameters else { return } let parameters = MSALInteractiveTokenParameters(scopes: kScopes, webviewParameters: webViewParameters) parameters.promptType = .selectAccount applicationContext.acquireToken(with: parameters) { (result, error) in if let error = error { self.updateLogging(text: "Could not acquire token: \(error)") return } guard let result = result else { self.updateLogging(text: "Could not acquire token: No result returned") return } self.accessToken = result.accessToken self.updateLogging(text: "Access token is \(self.accessToken)") self.updateCurrentAccount(account: result.account) self.getEventsWithAccessToken() } } func acquireTokenSilently(_ account : MSALAccount!) { guard let applicationContext = self.applicationContext else { return } let parameters = MSALSilentTokenParameters(scopes: kScopes, account: account) applicationContext.acquireTokenSilent(with: parameters) { (result, error) in if let error = error { let nsError = error as NSError if (nsError.domain == MSALErrorDomain) { if (nsError.code == MSALError.interactionRequired.rawValue) { DispatchQueue.main.async { self.acquireTokenInteractively() } return } } self.updateLogging(text: "Could not acquire token silently: \(error)") return } guard let result = result else { self.updateLogging(text: "Could not acquire token: No result returned") return } self.accessToken = result.accessToken self.updateLogging(text: "Refreshed Access token is \(self.accessToken)") self.updateSignOutButton(enabled: true) self.getEventsWithAccessToken() } } func getEventsWithAccessToken() { let graphURI = getGraphEndpoint() let url = URL(string: graphURI) var request = URLRequest(url: url!) request.setValue("Bearer \(self.accessToken)", forHTTPHeaderField: "Authorization") URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { self.updateLogging(text: "Couldn't get graph result: \(error)") return } guard let jsonEvents = data else { self.updateLogging(text: "Couldn't read the result from the API call") return } do { let decoder = JSONDecoder() let events = try decoder.decode(EventsResponse.self, from: jsonEvents) self.updateLogging(text: "Retrieved \(events.value.capacity) events from Graph!") } catch { self.updateLogging(text: "Couldn't deserialize result JSON") return } }.resume() } @objc func signOut(_ sender: AnyObject) { guard let applicationContext = self.applicationContext else { return } guard let account = self.currentAccount else { return } do { /** Removes all tokens from the cache for this application for the provided account - account: The account to remove from the cache */ let signoutParameters = MSALSignoutParameters(webviewParameters: self.webViewParameters!) signoutParameters.signoutFromBrowser = false // set this to true if you also want to signout from browser or webview applicationContext.signout(with: account, signoutParameters: signoutParameters, completionBlock: {(success, error) in if let error = error { self.updateLogging(text: "Couldn't sign out account with error: \(error)") return } self.updateLogging(text: "Sign out completed successfully") self.accessToken = "" self.updateCurrentAccount(account: nil) }) } } func initUI() { usernameLabel = UILabel() usernameLabel.translatesAutoresizingMaskIntoConstraints = false usernameLabel.text = "" usernameLabel.textColor = .darkGray usernameLabel.textAlignment = .right self.view.addSubview(usernameLabel) usernameLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 50.0).isActive = true usernameLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -10.0).isActive = true usernameLabel.widthAnchor.constraint(equalToConstant: 300.0).isActive = true usernameLabel.heightAnchor.constraint(equalToConstant: 50.0).isActive = true // Add call Graph button callGraphButton = UIButton() callGraphButton.translatesAutoresizingMaskIntoConstraints = false callGraphButton.setTitle("Call Microsoft Graph API", for: .normal) callGraphButton.setTitleColor(.blue, for: .normal) callGraphButton.addTarget(self, action: #selector(callGraphAPI(_:)), for: .touchUpInside) self.view.addSubview(callGraphButton) callGraphButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true callGraphButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 120.0).isActive = true callGraphButton.widthAnchor.constraint(equalToConstant: 300.0).isActive = true callGraphButton.heightAnchor.constraint(equalToConstant: 50.0).isActive = true // Add sign out button signOutButton = UIButton() signOutButton.translatesAutoresizingMaskIntoConstraints = false signOutButton.setTitle("Sign Out", for: .normal) signOutButton.setTitleColor(.blue, for: .normal) signOutButton.setTitleColor(.gray, for: .disabled) signOutButton.addTarget(self, action: #selector(signOut(_:)), for: .touchUpInside) self.view.addSubview(signOutButton) signOutButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true signOutButton.topAnchor.constraint(equalTo: callGraphButton.bottomAnchor, constant: 10.0).isActive = true signOutButton.widthAnchor.constraint(equalToConstant: 150.0).isActive = true signOutButton.heightAnchor.constraint(equalToConstant: 50.0).isActive = true let deviceModeButton = UIButton() deviceModeButton.translatesAutoresizingMaskIntoConstraints = false deviceModeButton.setTitle("Get device info", for: .normal); deviceModeButton.setTitleColor(.blue, for: .normal); deviceModeButton.addTarget(self, action: #selector(getDeviceMode(_:)), for: .touchUpInside) self.view.addSubview(deviceModeButton) deviceModeButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true deviceModeButton.topAnchor.constraint(equalTo: signOutButton.bottomAnchor, constant: 10.0).isActive = true deviceModeButton.widthAnchor.constraint(equalToConstant: 150.0).isActive = true deviceModeButton.heightAnchor.constraint(equalToConstant: 50.0).isActive = true // Add logging textfield loggingText = UITextView() loggingText.isUserInteractionEnabled = false loggingText.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(loggingText) loggingText.topAnchor.constraint(equalTo: deviceModeButton.bottomAnchor, constant: 10.0).isActive = true loggingText.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 10.0).isActive = true loggingText.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -10.0).isActive = true loggingText.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: 10.0).isActive = true } func platformViewDidLoadSetup() { NotificationCenter.default.addObserver(self, selector: #selector(appCameToForeGround(notification:)), name: UIApplication.willEnterForegroundNotification, object: nil) } @objc func appCameToForeGround(notification: Notification) { self.loadCurrentAccount() } func updateLogging(text : String) { if Thread.isMainThread { self.loggingText.text = text } else { DispatchQueue.main.async { self.loggingText.text = text } } } func updateSignOutButton(enabled : Bool) { if Thread.isMainThread { self.signOutButton.isEnabled = enabled } else { DispatchQueue.main.async { self.signOutButton.isEnabled = enabled } } } func updateAccountLabel() { guard let currentAccount = self.currentAccount else { self.usernameLabel.text = "Signed out" return } self.usernameLabel.text = currentAccount.username } func updateCurrentAccount(account: MSALAccount?) { self.currentAccount = account self.updateAccountLabel() self.updateSignOutButton(enabled: account != nil) } @objc func getDeviceMode(_ sender: AnyObject) { if #available(iOS 13.0, *) { self.applicationContext?.getDeviceInformation(with: nil, completionBlock: { (deviceInformation, error) in guard let deviceInfo = deviceInformation else { self.updateLogging(text: "Device info not returned. Error: \(String(describing: error))") return } let isSharedDevice = deviceInfo.deviceMode == .shared let modeString = isSharedDevice ? "shared" : "private" self.updateLogging(text: "Received device info. Device is in the \(modeString) mode.") }) } else { self.updateLogging(text: "Running on older iOS. GetDeviceInformation API is unavailable.") } } }
// // Identifiers.swift // AV TEST AID // // Created by Timileyin Ogunsola on 13/07/2021. // Copyright © 2021 TopTier labs. All rights reserved. // import Foundation struct StringIDs { struct SegueIdentfiers {} struct StoryBoardIdentifiers { static let MAIN = "Main" static let DASHBOARD = "DashBoardStorryBoard" } struct PersistenceIdentifiers { static let PROFESSIONS = "professions" static let PROFESSION = "profession" static let SHUFFLE_PRACTICE_QUESTION = "shuffle_practice_question" static let SHUFFLE_STUDY_QUESTION = "shuffle_study_question" static let SHOW_ONLY_CORRECT_QUESTION = "show_only_correct_question" } struct ProfessionIdentifiers { static let PILOT = "Pilot" static let AIR_TRAFFIC_CONTROLLER = "Air traffic controller" static let ENGINEER = "Engineer" static let FLIGHT_ATTENDANT = "Flight attendant" } }
//// //// ViewController.swift //// test //// //// Created by kishirinichiro on 2018/07/11. //// Copyright © 2018年 kishirinichiro. All rights reserved. //// import UIKit import FacebookLogin //Firebase モジュールを UIApplicationDelegate サブクラスにインポートします。 import Firebase import FirebaseDatabase import FBSDKCoreKit import FBSDKLoginKit import SVProgressHUD import FirebaseAuth // class ViewController: UIViewController, LoginButtonDelegate { //Firebase で認証する //FBSDKLoginButton オブジェクトを初期化するときに、ログイン イベントとログアウト イベントを受信するようにデリゲートを設定します。次に例を示します。 //アプリにFacebook公式のログインボタンを実装 var loginButton = FBSDKLoginButton() var ref:DatabaseReference! public func loginButtonDidLogOut(_ loginButton: LoginButton) { } //Called when the button was used to login and the process finished. //デリゲートで didCompleteWithResult:error: を実装します。 public func loginButtonDidCompleteLogin(_ loginButton: LoginButton, result: LoginResult) { let loginManager = LoginManager() switch result { case .failed(let error): print("Error \(error)") break case .success(let grantedPermissions, let declinedPermissions, let accessToken): loginFireBase() break default: break } } // override func viewDidAppear(_ animated: Bool) { // if (FBSDKAccessToken.current() != nil) { // print("User Already Logged In") // //既にログインしていた場合の処理(メイン画面へ遷移)を書く // self.performSegue(withIdentifier: "MyPageView", sender: self) // } else { // print("User not Logged In") // let loginButton = LoginButton(readPermissions: [ .email, .publicProfile, .userGender ]) // loginButton.center = self.view.center // loginButton.delegate = self // self.view.addSubview(loginButton) // ref = Database.database().reference() // } // } //View が初めて呼び出される時に1回だけ呼ばれます。アプリ起動後に初めて当Viewが表示された場合に1度だけ呼ばれます。 override func viewDidLoad() { super.viewDidLoad() //追加の読み取りアクセス許可をリクエストするには、FBSDKLoginButtonオブジェクトのreadPermissionsプロパティを設定します。 let loginButton = LoginButton(readPermissions: [ .email, .publicProfile, .userGender ]) loginButton.center = self.view.center loginButton.delegate = self self.view.addSubview(loginButton) ref = Database.database().reference() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /** Login to Firebase after FB Login is successful */ func loginFireBase() { //ユーザがログインに成功したらログインしたユーザのアクセストークンを取得してFirebase認証情報と交換します。 let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString) //待機中のくるくるしてるやつ。 SVProgressHUD.show() //最後に、Firebase 認証情報を使用して Firebase での認証を行います。 Auth.auth().signInAndRetrieveData(with: credential) { (user, error) in if error != nil { // ここでエラーが発生 return }else if FBSDKAccessToken.current() != nil{ SVProgressHUD.dismiss() self.performSegue(withIdentifier: "MyPageView", sender: self) self.postUser() } } } func postUser(){ guard let user = Auth.auth().currentUser else{ assert(true, "post user with nil") return } let facebookId = FBSDKAccessToken.current().userID let userRef = ref.child("Users") userRef .queryOrdered(byChild: "facebookId") .queryEqual(toValue: facebookId) .observeSingleEvent(of: DataEventType.value) { (snapshot) in if snapshot.exists() { print("Exist user") }else{ //FBSDKAccessTokenにはuserIDが含まれています。これを使用して利用者を特定できます。 let postUser = ["facebookId": FBSDKAccessToken.current().userID, "name": user.displayName] let postUserRef = userRef.childByAutoId() postUserRef.setValue(postUser) } } } } //import UIKit //import Firebase //import FirebaseAuth //import FacebookLogin //import TwitterKit //import FBSDKCoreKit //import FBSDKLoginKit //import Reachability // //// 【このビューでの処理】 //// ・通信状態のチェック //// ・Facebookログイン処理 //// ・ログイン時は、処理をスキップ //// ・プライバシーポリシー/利用規約のリンク表示 // //class ViewController: UIViewController,UITextViewDelegate { // // let reachability = Reachability()! // // // @IBOutlet weak var textView: UITextView! // // // // override func viewDidLoad() { // super.viewDidLoad() // // //通信状態のチェック // reachabilityCheck() // // // //Facebookログインボタンのサイズ、装飾、位置設定 // // let myLoginButton = UIButton(type: .custom) // myLoginButton.backgroundColor = UIColor(red: 0.23, green: 0.35, blue: 0.60, alpha: 1.0) // // myLoginButton.frame = CGRect(x:0, y:0, width:231, height:40); // myLoginButton.layer.cornerRadius = 15 // myLoginButton.clipsToBounds = true // myLoginButton.center = CGPoint(x:view.frame.size.width/2,y:view.frame.size.height-120) // myLoginButton.setTitle("規約に同意してログイン", for: []) // myLoginButton.titleLabel?.font = UIFont(name:"ヒラギノ丸ゴ ProN W4",size: 16) // myLoginButton.setImage(UIImage(named:"FacebookIcon_Circle_White_Large.png"),for: []) // // クリック時のアクション // myLoginButton.addTarget(self, action: #selector(self.loginButtonDidCompleteLogin), for: .touchUpInside) // // // サブビューとして追加 // view.addSubview(myLoginButton) // // //ハイパーリンク // // let baseString = "※ご利用開始時に、本サービスの利用規約とプライバシーポリシーをご確認ください" // let attributedString = NSMutableAttributedString(string: baseString) // // attributedString.addAttribute(.link, // value: "http://katyofugestu.sakura.ne.jp/Hokkori_LP/Terms_Of_Use.html", // range: NSString(string: baseString).range(of: "利用規約")) // // attributedString.addAttribute(.link, // value: "http://katyofugestu.sakura.ne.jp/Hokkori_LP/Privacy_Policy.html", // range: NSString(string: baseString).range(of: "プライバシーポリシー")) // // textView.attributedText = attributedString // textView.textColor = UIColor.gray // textView.delegate = self // // } // // override func didReceiveMemoryWarning() { // super.didReceiveMemoryWarning() // // Dispose of any resources that can be recreated. // } // // public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { // // UIApplication.shared.open(URL) // return false // } // // func reachabilityCheck(){ // // //通信状態のチェック // reachability.whenReachable = { reachability in // if reachability.connection == .wifi { // print("Reachable via WiFi") // } else { // print("Reachable via Cellular") // } // } // reachability.whenUnreachable = { _ in // print("Not reachable") // // UIAlertController // let alertController: UIAlertController = // UIAlertController(title: "通信できません", // message: "通信状況のよい場所で再度お試しください。", // preferredStyle: .alert) // // UIAlertControllerの起動 // self.present(alertController, animated: true, completion: nil) // // //「キャンセルボタン」のアラートアクションを作成する。 // let alertAction = UIAlertAction( // title: "確認", // style: UIAlertActionStyle.cancel, // handler: nil // ) // // //アラートアクションを追加する。 // alertController.addAction(alertAction) // // } // do { // try reachability.startNotifier() // } catch { // print("Unable to start notifier") // } // // // } // // @objc func loginButtonDidCompleteLogin() { // let loginManager = LoginManager() // // loginManager.logIn(readPermissions:[.publicProfile, .email, .userFriends, .userGender], viewController: self){LoginResult in // switch LoginResult { // case .failed(let error): // // エラー処理 // print(error) // case .cancelled:print("User cancelled login.") // case .success( _, _,let token): // let credential = FacebookAuthProvider.credential(withAccessToken: token.authenticationToken) // // Firebaseにcredentialを渡してlogin // Auth.auth().signInAndRetrieveData(with: credential) { (fireUser, fireError) in // if let error = fireError { // // エラー処理 // print(error) // return // } // // //ログイン時の処理をここに書く。 // self.performSegue(withIdentifier: "LoginSuccess", sender: nil) // // } // // } // } // } // // override func viewDidAppear(_ animated: Bool) { // super.viewDidAppear(animated) // // if Auth.auth().currentUser != nil { // let autoLoginView = self.storyboard?.instantiateViewController(withIdentifier: "TabBarController") // self.present(autoLoginView!, animated: true, completion: nil) // print("\(Auth.auth().currentUser!)←ユーザーID") // } // } // // // // //}
// // ViewController+CallKit.swift // VideoCallKitQuickStart // // Copyright © 2016-2019 Twilio, Inc. All rights reserved. // import UIKit import TwilioVideo import CallKit import AVFoundation extension ViewController : CXProviderDelegate { func providerDidReset(_ provider: CXProvider) { logMessage(messageText: "providerDidReset:") // AudioDevice is enabled by default self.audioDevice.isEnabled = false room?.disconnect() } func providerDidBegin(_ provider: CXProvider) { logMessage(messageText: "providerDidBegin") } func provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) { logMessage(messageText: "provider:didActivateAudioSession:") self.audioDevice.isEnabled = true } func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) { logMessage(messageText: "provider:didDeactivateAudioSession:") audioDevice.isEnabled = false } func provider(_ provider: CXProvider, timedOutPerforming action: CXAction) { logMessage(messageText: "provider:timedOutPerformingAction:") } func provider(_ provider: CXProvider, perform action: CXStartCallAction) { logMessage(messageText: "provider:performStartCallAction:") callKitProvider.reportOutgoingCall(with: action.callUUID, startedConnectingAt: nil) performRoomConnect(uuid: action.callUUID, roomName: action.handle.value) { (success) in if (success) { provider.reportOutgoingCall(with: action.callUUID, connectedAt: Date()) action.fulfill() } else { action.fail() } } } func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) { logMessage(messageText: "provider:performAnswerCallAction:") performRoomConnect(uuid: action.callUUID, roomName: self.roomTextField.text) { (success) in if (success) { action.fulfill(withDateConnected: Date()) } else { action.fail() } } } func provider(_ provider: CXProvider, perform action: CXEndCallAction) { NSLog("provider:performEndCallAction:") room?.disconnect() action.fulfill() } func provider(_ provider: CXProvider, perform action: CXSetMutedCallAction) { NSLog("provier:performSetMutedCallAction:") muteAudio(isMuted: action.isMuted) action.fulfill() } func provider(_ provider: CXProvider, perform action: CXSetHeldCallAction) { NSLog("provier:performSetHeldCallAction:") let cxObserver = callKitCallController.callObserver let calls = cxObserver.calls guard let call = calls.first(where:{$0.uuid == action.callUUID}) else { action.fail() return } if call.isOnHold { holdCall(onHold: false) } else { holdCall(onHold: true) } action.fulfill() } } // MARK:- Call Kit Actions extension ViewController { func performStartCallAction(uuid: UUID, roomName: String?) { let callHandle = CXHandle(type: .generic, value: roomName ?? "") let startCallAction = CXStartCallAction(call: uuid, handle: callHandle) startCallAction.isVideo = true let transaction = CXTransaction(action: startCallAction) callKitCallController.request(transaction) { error in if let error = error { NSLog("StartCallAction transaction request failed: \(error.localizedDescription)") return } NSLog("StartCallAction transaction request successful") } } func reportIncomingCall(uuid: UUID, roomName: String?, completion: ((NSError?) -> Void)? = nil) { let callHandle = CXHandle(type: .generic, value: roomName ?? "") let callUpdate = CXCallUpdate() callUpdate.remoteHandle = callHandle callUpdate.supportsDTMF = false callUpdate.supportsHolding = true callUpdate.supportsGrouping = false callUpdate.supportsUngrouping = false callUpdate.hasVideo = true callKitProvider.reportNewIncomingCall(with: uuid, update: callUpdate) { error in if error == nil { NSLog("Incoming call successfully reported.") } else { NSLog("Failed to report incoming call successfully: \(String(describing: error?.localizedDescription)).") } completion?(error as NSError?) } } func performEndCallAction(uuid: UUID) { let endCallAction = CXEndCallAction(call: uuid) let transaction = CXTransaction(action: endCallAction) callKitCallController.request(transaction) { error in if let error = error { NSLog("EndCallAction transaction request failed: \(error.localizedDescription).") return } NSLog("EndCallAction transaction request successful") } } func performRoomConnect(uuid: UUID, roomName: String? , completionHandler: @escaping (Bool) -> Swift.Void) { // Configure access token either from server or manually. // If the default wasn't changed, try fetching from server. if (accessToken == "TWILIO_ACCESS_TOKEN") { do { accessToken = try TokenUtils.fetchToken(url: tokenUrl) } catch { let message = "Failed to fetch access token" logMessage(messageText: message) return } } // Prepare local media which we will share with Room Participants. self.prepareLocalMedia() // Preparing the connect options with the access token that we fetched (or hardcoded). let connectOptions = ConnectOptions(token: accessToken) { (builder) in // Use the local media that we prepared earlier. builder.audioTracks = self.localAudioTrack != nil ? [self.localAudioTrack!] : [LocalAudioTrack]() builder.videoTracks = self.localVideoTrack != nil ? [self.localVideoTrack!] : [LocalVideoTrack]() // Use the preferred audio codec if let preferredAudioCodec = Settings.shared.audioCodec { builder.preferredAudioCodecs = [preferredAudioCodec] } // Use the preferred video codec if let preferredVideoCodec = Settings.shared.videoCodec { builder.preferredVideoCodecs = [preferredVideoCodec] } // Use the preferred encoding parameters if let encodingParameters = Settings.shared.getEncodingParameters() { builder.encodingParameters = encodingParameters } // Use the preferred signaling region if let signalingRegion = Settings.shared.signalingRegion { builder.region = signalingRegion } // The name of the Room where the Client will attempt to connect to. Please note that if you pass an empty // Room `name`, the Client will create one for you. You can get the name or sid from any connected Room. builder.roomName = roomName // The CallKit UUID to assoicate with this Room. builder.uuid = uuid } // Connect to the Room using the options we provided. room = TwilioVideoSDK.connect(options: connectOptions, delegate: self) logMessage(messageText: "Attempting to connect to room \(String(describing: roomName))") self.showRoomUI(inRoom: true) self.callKitCompletionHandler = completionHandler } }
// // ViewController.swift // WeatherApplication // // Created by Nuthan Raju Pesala on 22/06/21. // import UIKit class ViewController: UIViewController { private let table: UITableView = { let tv = UITableView() tv.register(WeatherTableViewCell.createNib(), forCellReuseIdentifier: WeatherTableViewCell.identifier) tv.tableFooterView = UIView() return tv }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. navigationController?.navigationBar.prefersLargeTitles = true navigationController?.navigationBar.tintColor = UIColor(red: 50/255, green: 158/255, blue: 190/255, alpha: 1) title = "Weather Forecast" self.view.addSubview(table) table.dataSource = self table.delegate = self view.backgroundColor = UIColor(red: 50/255, green: 158/255, blue: 190/255, alpha: 1) table.backgroundColor = UIColor(red: 50/255, green: 158/255, blue: 190/255, alpha: 1) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.table.frame = view.bounds } } extension ViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 0 } return 10 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: WeatherTableViewCell.identifier, for: indexPath) as! WeatherTableViewCell cell.backgroundColor = UIColor(red: 50/255, green: 158/255, blue: 190/255, alpha: 1) return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { switch section { case 0: let header = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 200)) let countryNameLabel = UILabel(frame: CGRect(x: 0, y: 30, width: view.frame.width, height: 30)) let summaryLabel = UILabel(frame: CGRect(x: 0, y: 65, width: view.frame.width, height: 20)) let tempLabel = UILabel(frame: CGRect(x: 0, y: 90, width: view.frame.width, height: 50)) header.addSubview(countryNameLabel) header.addSubview(summaryLabel) header.addSubview(tempLabel) countryNameLabel.textAlignment = .center summaryLabel.textAlignment = .center tempLabel.textAlignment = .center countryNameLabel.font = UIFont.systemFont(ofSize: 20, weight: .semibold) summaryLabel.font = UIFont.systemFont(ofSize: 16, weight: .medium) tempLabel.font = UIFont.systemFont(ofSize: 26, weight: .semibold) countryNameLabel.text = "Kakinada,Andhra Pradesh" summaryLabel.text = "Mostly,Cloudy" tempLabel.text = "18°C" return header case 1: let layout = UICollectionViewFlowLayout() let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) layout.scrollDirection = .horizontal collectionView.frame = CGRect(x: 15, y: 0, width: view.frame.width, height: 150) collectionView.backgroundColor = UIColor(red: 50/255, green: 158/255, blue: 190/255, alpha: 1) collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell") collectionView.register(WeatherCollectionViewCell.self, forCellWithReuseIdentifier: WeatherCollectionViewCell.identifier) layout.sectionInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) collectionView.dataSource = self collectionView.delegate = self return collectionView default: return UIView() } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 200 } return 180 } } extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: WeatherCollectionViewCell.identifier, for: indexPath) as! WeatherCollectionViewCell cell.backgroundColor = .lightGray cell.layer.cornerRadius = 4 return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: (collectionView.frame.width / 4 ) - 2, height: (collectionView.frame.width / 4) - 4) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 2 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 4 } }
// // Moment.swift // Weibo // // Created by 牟滔 on 2021/2/4. // Copyright © 2021 牟滔. All rights reserved. // import SwiftUI struct User :Codable{ let avatar:String let username:String let nick:String }
// // PromiseTableFeed.swift // SmartLock // // Created by Sam Davies on 21/11/2015. // Copyright © 2015 Sam Davies. All rights reserved. // import UIKit class PromiseTableFeed: UIViewController, UITableViewDataSource, UITableViewDelegate { //grid and scrollview referneces @IBOutlet var table : UITableView! override func viewDidLoad() { //DownloadBlocks(downloadURL) super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.table.dataSource = self self.table.delegate = self self.automaticallyAdjustsScrollViewInsets = false } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.getGridObjects() } func getGridObjects(){ } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return UITableViewCell() } func reloadCells(){ dispatch_async(dispatch_get_main_queue(), { self.table!.reloadData() }) } }
// // FileManager.swift // App // // Created by yenz0redd on 16.12.2019. // import Foundation /// For configuration from file final class FileManager { static let shared = FileManager() private init() { } var configDict: [String: String]? { return self.parseConfigFile() } private let configPath: String? = { return Bundle.main.path(forResource: "config", ofType: "txt") }() private func getFileContent() -> [String]? { guard let path = self.configPath else { return nil } do { let data = try String(contentsOfFile: path, encoding: .utf8) let lines = data.components(separatedBy: .newlines) return lines } catch { return [] } } private func parseConfigFile() -> [String: String]? { guard let lines = self.getFileContent() else { return nil } var result: [String: String] = [:] for line in lines { let keyValue = line.components(separatedBy: "~") result[keyValue[0]] = keyValue[1] } return result } }
// // XRPLResponse.swift // BigInt // // Created by Mitch Lang on 2/3/20. // import Foundation import AnyCodable //public struct XRPWebSocketResponse<T:Codable>: Codable { // public var id: String // public var status: String // public var type: String // public var result: T //} public struct XRPWebSocketResponse: Codable{ public let id: String public let status: String public let type: String private let _result: AnyCodable public var result: [String:AnyObject] { return _result.value as! [String:AnyObject] } enum CodingKeys: String, CodingKey { case id case status case type case _result = "result" } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) id = try values.decode(String.self, forKey: .id) status = try values.decode(String.self, forKey: .status) type = try values.decode(String.self, forKey: .type) _result = try values.decode(AnyCodable.self, forKey: ._result) } } public struct XRPJsonRpcResponse<T> { public var result: T }