text
stringlengths 8
1.32M
|
|---|
//
// ProgramLibraryViewController.swift
// UPK-GE01
//
// Created by zhongzhong.cao on 2019/7/15.
// Copyright © 2019 umehealltd. All rights reserved.
//
import UIKit
class ProgramLibraryViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {
var therapy = [["Relieve"], ["Strengthen"], ["Relax"]]
var therapy_decribe = ["Programs designed to help relieve your muscle and joint pain and stiffness", "Programs designed to help strenghten and restore your muscles and promote movement", "Programs designed to massage and relax your muscles"]
var session_image = ["pic1", "pic1", "pic1"]
override func viewDidLoad() {
super.viewDidLoad()
// title = "Program Library"
self.navigationItem.title = "RelieforMe"
let item = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)
self.navigationItem.backBarButtonItem = item
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
if ((self.navigationController?.viewControllers.count)!) > 1{
self.tabBarController?.tabBar.isHidden = true
}
else{
self.tabBarController?.tabBar.isHidden = false
}
}
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 1
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 10
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 10
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 85
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell_programlibrary", for: indexPath) as! ProgramLibraryUITableViewCell
cell.SessionName.text = therapy[indexPath.section][indexPath.row]
cell.SessionImage.image = UIImage(named:session_image[indexPath.section])
cell.SessionImage.layer.cornerRadius = cell.SessionImage.frame.size.height/2
cell.SessionImage.clipsToBounds = true
cell.SessionDetial.text = therapy_decribe[indexPath.section]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0 && indexPath.row == 0 {
let vc = PLViewController()
vc.index = 0
self.navigationController?.pushViewController(vc, animated: true)
}
else if indexPath.section == 1 && indexPath.row == 0 {
let vc = PLViewController()
vc.index = 1
self.navigationController?.pushViewController(vc, animated: true)
}
else if indexPath.section == 2 && indexPath.row == 0 {
let vc = PLViewController()
vc.index = 2
self.navigationController?.pushViewController(vc, animated: true)
}
}
// override func addChild(_ childController: UIViewController) {
//}
}
|
import UIKit
@testable import CountriesQL
final class AppRouterMock: AppRouterProtocol {
var viewController: UIViewController?
var isAnimated: Bool?
var onNavigateBack: NavigationBackClosure?
func push(_ viewController: UIViewController, isAnimated: Bool, onNavigateBack: NavigationBackClosure?) {
self.viewController = viewController
self.isAnimated = isAnimated
self.onNavigateBack = onNavigateBack
}
}
|
//
// PushModel.swift
// OmnipotentSkip
//
// Created by sks on 17/3/31.
// Copyright © 2017年 besttone. All rights reserved.
//
import UIKit
class PushModel: NSObject {
var warmOneModel : WarmOneDataModel = WarmOneDataModel()
var warmTwoModel : WarmTwoDataModel = WarmTwoDataModel()
var deadOneModel : DeadOneDataModel = DeadOneDataModel()
var deadTwoModel : DeadTwoDataModel = DeadTwoDataModel()
override init() {
super.init()
}
}
|
import Foundation
import UIKit
extension UIViewController {
func presentAlertWith(title: String, message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default)
alertController.addAction(okAction)
present(alertController, animated: true)
}
func dimScreenWithActivitySpinner() {
// Add dimmed view
let dimmedView = UIView(frame: view.window?.frame ?? view.frame) // TODO: Crashing with nil window?
dimmedView.tag = 1
dimmedView.backgroundColor = UIColor.black.withAlphaComponent(0.3)
view.window?.addSubview(dimmedView)
// Add activity indicator
let spinnerView = UIActivityIndicatorView.init(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
spinnerView.tag = 1
spinnerView.center = CGPoint(x: view.center.x, y: view.center.y - navigationController!.navigationBar.frame.height)
view.window?.addSubview(spinnerView)
spinnerView.startAnimating()
}
func undimScreenAndRemoveActivitySpinner() {
if let window = view.window {
for view in window.subviews {
if view.tag == 1 {
view.removeFromSuperview()
}
}
}
}
}
|
//
// CollectionNormalCell.swift
// MyDYZB
//
// Created by 王武 on 2020/11/10.
//
import UIKit
class CollectionNormalCell: CollectionBaseCell {
// MARK:- 设置属性
@IBOutlet weak var roomnameLabel: UILabel!
// MARK:- 定义模型属性
override var anchor: AnchorModel? {
didSet {
// 1. 将属性传递给父类
super.anchor = anchor
// 2. 设置房间名称
roomnameLabel.text = anchor?.room_name
}
}
}
|
//
// TitleView.swift
// DesignCode
//
// Created by Alex Ochigov on 8/12/20.
// Copyright © 2020 Alex Ochigov. All rights reserved.
//
import SwiftUI
struct TitleView: View {
var body: some View {
VStack {
HStack {
Text("Certificates")
.font(.largeTitle)
.fontWeight(.bold)
Spacer()
}
.padding()
Image("Background1")
Spacer()
}
}
}
|
//
// CollectionViewController.swift
// GenericCollectionViewCell
//
// Created by Diogo Tridapalli on 1/31/16.
// Copyright © 2016 Diogo Tridapalli. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class CollectionViewController: UICollectionViewController {
override func viewDidLoad()
{
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
if let collectionView = self.collectionView {
collectionView.backgroundColor = UIColor.whiteColor()
// Register cell classes
collectionView.registerClass(CollectionViewCell<UILabel, String>.self, forCellWithReuseIdentifier: reuseIdentifier)
}
}
// MARK: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
{
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return 5
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)
if let cell = cell as? CollectionViewCell<UILabel, String> {
let max = collectionView.numberOfItemsInSection(indexPath.section)
cell.model = "Cell \(indexPath.row+1)/\(max)"
}
return cell
}
// MARK: UICollectionViewDelegateFlowLayout
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
let width = collectionView.bounds.size.width
let height = CGRectGetHeight(self.view.bounds)
let contentInset = collectionView.contentInset
let size = CGSizeMake(width - contentInset.right - contentInset.left,
height);
return size;
}
}
extension UILabel: HasModel {
var model: String {
get {
return text ?? ""
}
set(newModel) {
text = newModel
textAlignment = .Center
}
}
}
|
//
// Room+CoreDataProperties.swift
// bib Stundenplan
//
// Created by Erik Schaumlöffel / PBS2H17A on 5/17/19.
// Copyright © 2019 Erik Schaumlöffel / PBS2H17A. All rights reserved.
//
//
import Foundation
import CoreData
extension Room {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Room> {
return NSFetchRequest<Room>(entityName: "Room")
}
@NSManaged public var name: String?
@NSManaged public var number: String?
@NSManaged public var events: NSSet?
}
// MARK: Generated accessors for events
extension Room {
@objc(addEventsObject:)
@NSManaged public func addToEvents(_ value: Event)
@objc(removeEventsObject:)
@NSManaged public func removeFromEvents(_ value: Event)
@objc(addEvents:)
@NSManaged public func addToEvents(_ values: NSSet)
@objc(removeEvents:)
@NSManaged public func removeFromEvents(_ values: NSSet)
}
|
//
// AnimationBuilder.swift
// Slaminate
//
// Created by Kristian Trenskow on 08/02/16.
// Copyright © 2016 Trenskow.io. All rights reserved.
//
import Foundation
@objcMembers
class AnimationBuilder: AnimationGroup {
static var allAnimations = [AnimationGroup]()
static var builders = [AnimationBuilder]()
fileprivate static func updateSwizzle() {
NSObject.swizzled = builders.some({ $0.buildState == .collecting })
}
static var top: AnimationBuilder! {
return builders.last
}
enum AnimationBuilderState {
case waiting
case collecting
case resetting
case building
case done
}
var buildState = AnimationBuilderState.building {
didSet {
AnimationBuilder.updateSwizzle()
}
}
var propertyInfos = [PropertyInfo]()
var constraintInfos = [PropertyInfo]()
var constraintPresenceInfos = [ConstraintPresenceInfo]()
let animation: () -> Void
var applyDuration: TimeInterval
var applyCurve: Curve
init(duration: TimeInterval, curve: Curve, animation: @escaping () -> Void) {
self.animation = animation
self.applyCurve = curve
self.applyDuration = duration
super.init(animations: [])
}
override var duration: TimeInterval {
get { return applyDuration }
set {
applyDuration = newValue
animations.forEach({ $0.duration = newValue })
}
}
override func setPosition(_ position: TimeInterval, apply: Bool) {
if position > 0.0 {
build()
}
super.setPosition(position, apply: apply)
}
func setObjectFromValue(_ object: NSObject, key: String, value: NSObject?) -> Bool {
guard buildState == .collecting else {
return false
}
let idx = propertyInfos.indexOf(object, key: key)
propertyInfos[idx].fromValue ??= value
return true
}
func setObjectToValue(_ object: NSObject, key: String, value: NSObject?) -> Bool {
guard buildState == .collecting else {
return false
}
propertyInfos[propertyInfos.indexOf(object, key: key)].toValue = value
return true
}
func setObjectFromToValue(_ object: NSObject, key: String, fromValue: NSObject?, toValue: NSObject?) -> Bool {
guard buildState == .collecting else {
return false
}
let idx = propertyInfos.indexOf(object, key: key)
propertyInfos[idx].fromValue ??= fromValue
propertyInfos[idx].toValue = toValue
return true
}
func setConstraintValue(_ object: NSLayoutConstraint, key: String, fromValue: NSObject, toValue: NSObject) {
guard buildState == .collecting else { return }
let index = constraintInfos.indexOf(object, key: key)
constraintInfos[index].fromValue ??= fromValue
constraintInfos[index].toValue = toValue
if key == "constant" {
_ = setObjectFromToValue(object, key: key, fromValue: fromValue, toValue: toValue)
}
}
func addConstraintPresence(_ view: UIView, constraint: NSLayoutConstraint, added: Bool) {
guard buildState == .collecting else { return }
constraintPresenceInfos.append(ConstraintPresenceInfo(
view: view,
constraint: constraint,
added: added)
)
}
func collectAnimations() {
guard buildState == .collecting else {
fatalError("Finalizing without collecting.")
}
constraintInfos.applyToValues()
constraintPresenceInfos.applyPresent(true)
var views: [(UIView, UIView?)] = constraintInfos.map({ (
($0.object as! NSLayoutConstraint).firstItem as! UIView,
($0.object as! NSLayoutConstraint).secondItem as? UIView
) })
views.append(contentsOf: constraintPresenceInfos.map({ (
($0.constraint.firstItem as! UIView),
($0.constraint.secondItem as? UIView)
) }))
if let first = views.first {
var common = views.reduce(first.1 != nil ? first.0.commonAncestor(first.1!)! : first.0, { (c, views) -> UIView in
var first = c.commonAncestor(views.0)
if let _ = views.1 {
first = first?.commonAncestor(views.1!)
}
return first!
})
if let superview = common.superview , superview as? UIWindow == nil {
common = superview
}
common.updateConstraints()
common.layoutSubviews()
buildState = .resetting
constraintInfos.applyFromValues()
constraintPresenceInfos.applyPresent(false)
common.updateConstraints()
common.layoutSubviews()
}
buildState = .resetting
// Apply from value to all but constraints constants.
propertyInfos.filter({
$0.key != "constant" && !($0.object is NSLayoutConstraint)
}).applyFromValues()
buildState = .building
for propertyInfo in propertyInfos {
guard let object = propertyInfo.object, let toValue = propertyInfo.toValue else { continue }
let animation = object.pick(
animationForKey: propertyInfo.key,
fromValue: nil,
toValue: toValue,
duration: duration,
curve: applyCurve)
if let animation = animation {
add(animation)
} else {
propertyInfo.applyToValue()
}
}
buildState = .done
}
func build() {
guard buildState == .building else { return }
AnimationBuilder.builders.append(self)
buildState = .collecting
let enabled = UIView.areAnimationsEnabled
UIView.setAnimationsEnabled(false)
animation()
collectAnimations()
UIView.setAnimationsEnabled(enabled)
AnimationBuilder.builders.removeLast()
}
override func commit() {
build()
super.commit()
}
override func complete(_ finished: Bool) {
constraintInfos.applyToValues()
constraintPresenceInfos.applyPresent(true)
super.complete(finished)
}
}
|
//
// RepScheme.swift
// five3one
//
// Created by Cody Dillon on 10/18/18.
// Copyright © 2018 Be More Innovations. All rights reserved.
//
import Foundation
class RepScheme {
var sets: Int = 0
var reps: Int = 0
init(sets: Int, reps: Int) {
self.sets = sets
self.reps = reps
}
}
|
//
// ContentView.swift
// HelloCast
//
// Created by Johnson Osei Yeboah on 28/01/2021.
//
import SwiftUI
import CoreData
struct ContentView: View {
var body: some View {
TabView{
ExploreView().tabItem {
Image("compass")
Text("Explore")
}
LibraryView().tabItem {
Image("compass")
Text("Library")
}
ProfileView().tabItem {
Image("compass")
Text("Profile")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
import SwiftUI
class MemoryGameViewModel: ObservableObject {
private let game: MemoryGame<String>
@Published var cardViewModels: [CardViewModel]
init(game: MemoryGame<String>) {
self.game = game
self.cardViewModels = game.cards.map { CardViewModel(card: $0) }
}
func cardViewModelTapped(_ viewModel: CardViewModel) {
game.cardTapped(id: viewModel.id)
cardViewModels = game.cards.map { CardViewModel(card: $0) }
}
}
class CardViewModel: Identifiable {
var id: UUID
var isFaceUp: Bool
var content: String
init(card: MemoryGame<String>.Card) {
self.id = card.id
self.isFaceUp = card.isFaceUp
self.content = card.content
}
}
|
//
// collectionViewProtocol.swift
// Hepsiburada_iOS_Code_Case
//
// Created by Ege Seçkin on 31.10.2021.
//
import UIKit
extension ResultViewController: UICollectionViewDelegate,UICollectionViewDataSource{
//if input inside searchbar changes (dynamically) it comes here
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchApi()
}
// MARK: Number Of Items
//How many items should be displayed
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
self.actIN.stopAnimating()
if(dataresult.count > 0 ){
if(dataresult.count < cellNumber){
return dataresult.count
}
else{
return cellNumber
}
}
return 0
}
// MARK: Pagination
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
//Increments the number of cells on the page when it comes to end of page
if indexPath.row == cellNumber-1 {
self.actIN.startAnimating()
cellNumber = cellNumber + 20
collectionView.reloadData()
}
}
}
|
//
// SecondCollectionViewController.swift
// GiphySearchApp
//
// Created by Dmitry Kyrskiy on 21.12.16.
// Copyright © 2016 Dmitry Kyrskiy. All rights reserved.
//
import UIKit
import FLAnimatedImage
import SDWebImage
class SecondCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let apiClient = ApiClient()
var gifs: [Gif] = []
var searchText: String = ""
override func viewDidLoad() {
self.title = searchText
apiClient.searchGifs(searchText: searchText) { (gifs, error) in
if let gifs = gifs {
self.gifs = gifs
self.collectionView?.reloadData()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return gifs.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "searchCell", for: indexPath) as! SecondCollectionViewCell
cell.flImageView.sd_setImage(with: URL(string: self.gifs[indexPath.row].url))
if (!gifs[indexPath.row].trended.isEmpty || !gifs[indexPath.row].username.isEmpty) {
cell.infoView.isHidden = false
cell.trandedView.isHidden = gifs[indexPath.row].trended.isEmpty
cell.usernameLabel.text = gifs[indexPath.row].username ?? ""
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.frame.width / 3 - 1
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 1.0
}
}
|
//
// AddGroupMemberViewController.swift
// strolling-of-time-ios
//
// Created by 강수진 on 2019/08/20.
// Copyright © 2019 wiw. All rights reserved.
//
import UIKit
class AddGroupMemberViewController: UIViewController, NibLoadable {
typealias SelectedMember = (member: String, image: String, index: Int)
@IBOutlet weak var collectionViewHeight: NSLayoutConstraint!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var invitationButton: UIButton!
var delegate: SendDataDelegate?
private var searchTxtField: UITextField = {
let txtField = UITextField()
txtField.placeholder = "닉네임 또는 메일로 검색해보세요"
txtField.font = UIFont.systemFont(ofSize: 18.0)
return txtField
}()
var tableViewSampleMember: [SelectedMember] = [] {
didSet {
self.tableView.reloadData()
}
}
var collectionViewSampleMember: [SelectedMember] = []
var sampleMember :[SelectedMember] = [("최고운", "background", 1), ("김민철", "background", 2), ("진성곤", "background", 3), ("박다예", "background", 4), ("강수진", "background", 5), ("조우현", "background", 6)]
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if isMovingFromParent {
delegate?.sendData(data: self.collectionViewSampleMember)
}
}
func collectionViewDataDidChanged() {
collectionViewHeight.constant = collectionViewSampleMember.isEmpty ? 0 : 150
self.invitationButton.setValidButton(isActive: !collectionViewSampleMember.isEmpty)
let buttonTitle = collectionViewSampleMember.isEmpty ? "멤버를 초대해주세요" : "\(collectionViewSampleMember.count)명에게 초대장 보내기"
self.invitationButton.setTitle(buttonTitle, for: .normal)
self.collectionView?.reloadData()
}
override func viewDidLayoutSubviews() {
collectionViewDataDidChanged()
}
override func viewDidLoad() {
super.viewDidLoad()
setNavigationbar()
setupCollectionView()
setupTableView()
setupTextfield()
setupInvitationButton()
hideKeyboarOnTap_()
}
func setNavigationbar() {
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()
navigationItem.titleView = searchTxtField
}
func setupCollectionView() {
collectionView.dataSource = self
collectionView.delegate = self
collectionViewHeight.constant = 0
}
func setupTableView() {
tableView.delegate = self
tableView.dataSource = self
self.tableView.isUserInteractionEnabled = true
self.tableView.allowsSelection = true
}
func setupTextfield() {
searchTxtField.delegate = self
searchTxtField.addTarget(self, action: #selector(searchBarEditingChanged(_:)), for: .editingChanged)
}
func setupInvitationButton() {
invitationButton.addTarget(self, action: #selector(inviteMember), for: .touchUpInside)
self.invitationButton.backgroundColor = .gray
self.invitationButton.setTitle("0명에게 초대장 보내기", for: .normal)
}
@objc func inviteMember() {
self.navigationController?.popViewController(animated: true)
}
}
//TableView
extension AddGroupMemberViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableViewSampleMember.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.cell(for: AddGroupMemberTableViewCell.self)
cell.configure(data: tableViewSampleMember[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard collectionViewSampleMember.count < 10 else {
self.simpleAlert(title: "오류", message: "10명 이상을 추가할 수 없습니다")
return
}
let selectedMemeber = tableViewSampleMember[indexPath.row]
if !collectionViewSampleMember.map({(_, _, idx) -> Int in
return idx
}).contains(selectedMemeber.index) {
self.collectionViewSampleMember.append(selectedMemeber)
self.collectionViewDataDidChanged()
}
}
}
//CollectionView
extension AddGroupMemberViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collectionViewSampleMember.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.cell(type: AddGroupMemberCollectionViewCell.self, for: indexPath)
cell.configure(row: indexPath.row, data: collectionViewSampleMember[indexPath.row])
cell.setCallback {[weak self] (row: Int) in
guard let `self` = self else {
return
}
self.collectionViewSampleMember.remove(at: indexPath.row)
self.collectionViewDataDidChanged()
}
return cell
}
}
//textField
extension AddGroupMemberViewController: UITextFieldDelegate, AlertUsable {
@objc func searchBarEditingChanged(_ searchBar: UISearchBar) {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.searchMember(_:)), object: searchBar)
perform(#selector(self.searchMember(_:)), with: searchBar, afterDelay: 0.5)
}
@objc func searchMember(_ searchBar: UISearchBar) {
//실시간 통신?
guard let searchText = searchBar.text else {
return
}
self.tableViewSampleMember = self.sampleMember.filter { (arg) -> Bool in
let (member, _, _) = arg
return member.contains(searchText)
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField.text == "" {
simpleAlert(title: "오류", message: "검색어를 입력해주세요")
return false
}
if let myString = textField.text {
let emptySpacesCount = myString.components(separatedBy: " ").count-1
if emptySpacesCount == myString.count {
simpleAlert(title: "오류", message: "검색어를 입력하세요")
return false
}
}
if let searchString = textField.text {
print("enter")
}
return true
}
}
//키보드
extension AddGroupMemberViewController {
private func hideKeyboarOnTap_() {
let tap = UITapGestureRecognizer(target: self, action: #selector(hideKeyboardAction))
tap.cancelsTouchesInView = false
self.view.addGestureRecognizer(tap)
}
@objc private func hideKeyboardAction(view: UIView) {
self.searchTxtField.endEditing(true)
}
}
|
//
// UIColor+AppColors.swift
// MyShopping
//
// Created by Sami Rämö on 11/05/2017.
// Copyright © 2017 Sami Ramo. All rights reserved.
//
import UIKit
struct AppColors {
struct Theme1 {
let cellColor = UIColor(red: 255/255, green: 211/255, blue: 144/255, alpha: 1.0)
let cellSelectColor = UIColor(red: 95/255, green: 204/255, blue: 193/255, alpha: 1.0)
let lightBackgroundColor = UIColor(red: 245/255, green: 240/255, blue: 219/255, alpha: 1.0)
let darkestColor = UIColor(red: 153/255, green: 143/255, blue: 100/255, alpha: 1.0)
let lightUIColor = UIColor(red: 208/255, green: 247/255, blue: 255/255, alpha: 1.0)
let strikeColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
}
struct Theme2 {
let cellColor = UIColor(red: 255/255, green: 211/255, blue: 144/255, alpha: 1.0)
let cellSelectColor = UIColor(red: 95/255, green: 204/255, blue: 193/255, alpha: 1.0)
let lightBackgroundColor = UIColor(red: 245/255, green: 240/255, blue: 219/255, alpha: 1.0)
let darkestColor = UIColor(red: 112/255, green: 105/255, blue: 73/255, alpha: 1.0)
let lightUIColor = UIColor(red: 208/255, green: 247/255, blue: 255/255, alpha: 1.0)
let strikeColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
}
}
|
//
// DetailsCellDataSource.swift
// NTGTags
//
// Created by Mena Gamal on 2/16/20.
// Copyright © 2020 Mena Gamal. All rights reserved.
//
import Foundation
import UIKit
class DetailsCellDataSource: NSObject, UICollectionViewDataSource, UICollectionViewDelegate ,UICollectionViewDelegateFlowLayout {
var items = [Items]()
var collection:UICollectionView!
var img:String!
override init() {
super.init()
}
init(collection:UICollectionView,items:[Items],img:String) {
super.init()
self.img = img
self.collection = collection
self.items = items
self.collection.register(UINib(nibName: "DetailsCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "DetailsCollectionViewCell")
self.collection.dataSource = self
self.collection.delegate = self
self.collection.reloadData()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DetailsCollectionViewCell",for: indexPath) as! DetailsCollectionViewCell
let item = items[indexPath.row]
cell.setDetails(title: item.name!, imgUrl: self.img!, completation: { img in
let imageData = img.pngData()
let imageToBaseStr = imageData!.base64EncodedString(options: .lineLength76Characters)
self.items[indexPath.row].characterImageBaseString = imageToBaseStr
})
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAt indexPath: IndexPath) -> CGSize {
let padding: CGFloat = 1
let collectionViewSize = collectionView.frame.size.width/3 - padding
return CGSize(width: collectionViewSize, height: collectionView.frame.size.height - padding)
}
}
|
//
// FlickrCollectionViewController.swift
// RandomFlickrImagesAppleTV
//
// Created by Rahath cherukuri on 3/6/16.
// Copyright © 2016 Rahath cherukuri. All rights reserved.
//
import UIKit
class FlickrCollectionViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var flickrCollectionViewOne: UICollectionView!
@IBOutlet weak var flickrCollectionViewTwo: UICollectionView!
var methodArguments = [
"method": METHOD_NAME,
"api_key": API_KEY,
"safe_search": SAFE_SEARCH,
"extras": EXTRAS,
"format": DATA_FORMAT,
"nojsoncallback": NO_JSON_CALLBACK
]
override func viewDidLoad() {
setFirstCollectionView()
setSecondCollectionView()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
func setFirstCollectionView() {
let searchText = "Yosemite National Park, California"
print("Random Text: ", searchText)
methodArguments["text"] = searchText
FlickrClient.sharedInstance().getImageFromFlickrBySearch(methodArguments) {(success, photos, errorString) in
if success {
FlickrClient.sharedInstance().savePhotoData(photos!, index: 0)
dispatch_async(dispatch_get_main_queue(), {
self.flickrCollectionViewOne.reloadData()
})
} else {
print("Error: ", errorString)
}
}
}
func setSecondCollectionView() {
let searchText = "NewYork, NY"
print("Random Text: ", searchText)
methodArguments["text"] = searchText
FlickrClient.sharedInstance().getImageFromFlickrBySearch(methodArguments) {(success, photos, errorString) in
if success {
FlickrClient.sharedInstance().savePhotoData(photos!,index: 1)
dispatch_async(dispatch_get_main_queue(), {
self.flickrCollectionViewTwo.reloadData()
})
} else {
print("Error: ", errorString)
}
}
}
// UICollectionViewDataSource methods
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let tag = collectionView.tag
if tag == 0 {
return Data.DataCollectionViewOne.count
} else {
return Data.DataCollectionViewTwo.count
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let tag = collectionView.tag
if tag == 0 {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("FlickrCollectionViewCellOne", forIndexPath: indexPath) as! FlickrCollectionViewCell
if Data.DataCollectionViewOne.count > 0 {
let photo = Data.DataCollectionViewOne[indexPath.row]
let imageUrlString = photo.url
let imageURL = NSURL(string: imageUrlString)
if let imageData = NSData(contentsOfURL: imageURL!) {
dispatch_async(dispatch_get_main_queue(), {
cell.imageViewOne.image = UIImage(data: imageData)
})
}
return cell
} else {
return cell
}
} else {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("FlickrCollectionViewCellTwo", forIndexPath: indexPath) as! FlickrCollectionViewCell
if Data.DataCollectionViewTwo.count > 0 {
let photo = Data.DataCollectionViewTwo[indexPath.row]
let imageUrlString = photo.url
let imageURL = NSURL(string: imageUrlString)
if let imageData = NSData(contentsOfURL: imageURL!) {
dispatch_async(dispatch_get_main_queue(), {
cell.imageViewTwo.image = UIImage(data: imageData)
})
}
return cell
} else {
return cell
}
}
}
// Mark: UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
}
func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
cell.alpha = 0.0
UIView.animateWithDuration(1.0) { () -> Void in
cell.alpha = 1.0
}
}
// Mark: Helper methods.
func getRandomPhotoIndex()-> String {
let cityStates = ["Hyderabad, India", "Norfolk, VA", "Syracuse, NY", "Banglore, India", "Chennai, India", "Rochester, NY", "NewYork, NY"]
let randomPhotoIndex = Int(arc4random_uniform(UInt32(cityStates.count)))
return cityStates[randomPhotoIndex]
}
}
|
import Foundation
import Capacitor
import ADAL
@available(iOS 13.0, *)
public class ADAuthentication {
var kClientID: String;
var kGraphURI: String;
var kAuthority: String;
var kRedirectUri = URL(string: "")
var applicationContext : ADAuthenticationContext?
let call: CAPPluginCall
var detectedAlready = false
public init(call: CAPPluginCall, KClientID: String,kGraphURI: String,kAuthority: String,kRedirectUri: String) {
self.call = call
self.kClientID = KClientID
self.kGraphURI = kGraphURI
self.kAuthority = kAuthority
CAPLog.print("kClientID fn: \(kClientID)");
CAPLog.print("kRedirectUri fn: \(kRedirectUri)");
self.kRedirectUri = URL(string: kRedirectUri)
CAPLog.print("kRedirectUri: \(self.kRedirectUri)");
self.applicationContext = ADAuthenticationContext(authority: kAuthority, error: nil)
self.applicationContext?.credentialsType = AD_CREDENTIALS_AUTO
}
public func initADAL() {
// fail out if call is already used up
guard let applicationContext = self.applicationContext else { return }
guard let kRedirectUri = kRedirectUri else { return }
applicationContext.acquireToken(withResource: kGraphURI, clientId: kClientID, redirectUri: kRedirectUri){ (result) in
if (result.status != AD_SUCCEEDED) {
if let error = result.error {
if error.domain == ADAuthenticationErrorDomain,
error.code == ADErrorCode.ERROR_UNEXPECTED.rawValue {
CAPLog.print("Unexpected internal error occured: \(error.description)")
self.call.reject("Unexpected internal error occured: \(error.description)")
return
} else {
CAPLog.print(error.description)
self.call.reject(error.description)
return
}
}
self.call.reject("ApplicationContext AcquireToken Reject")
return
} else {
CAPLog.print("Access token is \(String(describing: result.accessToken))")
self.call.success(["accessToken": result.accessToken])
}
}
}
public func acquireTokenSilently() {
guard let applicationContext = self.applicationContext else { return }
guard let kRedirectUri = kRedirectUri else { return }
applicationContext.acquireTokenSilent(withResource: kGraphURI, clientId: kClientID, redirectUri: kRedirectUri) { (result) in
if (result.status != AD_SUCCEEDED) {
if let error = result.error {
if error.domain == ADAuthenticationErrorDomain,
error.code == ADErrorCode.ERROR_SERVER_USER_INPUT_NEEDED.rawValue {
DispatchQueue.main.async {
self.initADAL()
}
} else {
CAPLog.print("Could not acquire token silently: \(error.description)")
self.call.reject("Could not acquire token silently: \(error.description)")
}
}
} else {
CAPLog.print("Refreshed Access token is \(String(describing: result.accessToken))")
self.call.success(["accessToken": result.accessToken])
}
}
}
public func currentAccount() {
guard let cachedTokens = ADKeychainTokenCache.defaultKeychain().allItems(nil) else {
CAPLog.print("Didn't find a default cache. This is very unusual.")
self.call.reject("Didn't find a default cache. This is very unusual.")
return
}
if !(cachedTokens.isEmpty) {
for (_, cachedToken) in cachedTokens.enumerated() {
if cachedToken.accessToken != nil {
self.call.success(["cachedToken": cachedToken])
}
}
}
}
public func signOut() {
/**
Removes all tokens from the cache for this application for the current account in use
- account: The account user ID to remove from the cache
*/
guard let account = currentAccount()?.userInformation?.userId else {
CAPLog.print("Didn't find a logged in account in the cache.")
self.call.reject("Didn't find a logged in account in the cache.")
return
}
ADKeychainTokenCache.defaultKeychain().removeAll(forUserId: account, clientId: kClientID, error: nil)
self.call.success(["success": true])
}
}
|
//
// APIIProBonus.swift
//
// Created by Александра on 28.04.2021.
//
import Foundation
public class APIIProBonus: ObservableObject {
@Published var token: String?
@Published var clientBonusInfo: ClientBonusInfo?
public var clientTotalBonus: Double?
public var clientBonusBirned: Double?
public var birnData: String?
public var clientID: String
public var deviceID: String
public struct AppError: Identifiable {
public let id = UUID().uuidString
let errorString: String
}
public init(clientID: String, deviceID: String) {
self.clientID = clientID
self.deviceID = deviceID
getToken(clientID: self.clientID, deviceID: self.deviceID)
}
public func getToken(clientID: String, deviceID: String) {
let apiService = APIGetToken.shared
apiService.getJSON(urlString: "https://mp1.iprobonus.com/api/v3/clients/accesstoken/",
idClient: clientID,
paramValue: deviceID)
{ (result: Result<Token,APIGetToken.APIError>) in
switch result {
case .success(let tokenFromService):
DispatchQueue.main.async {
self.token = tokenFromService.accessToken
DispatchQueue.global().async {
self.getBonusInfo()
}
}
case .failure(let apiError):
switch apiError {
case .error(let errorString):
print(errorString)
}
}
}
}
public func getBonusInfo() {
let apiService = APIGetClientInfo.shared
if token != nil {
apiService.getJSON(urlString: "https://mp1.iprobonus.com/api/v3/ibonus/generalinfo/\(token!)") { (result: Result<ClientBonusInfo,APIGetClientInfo.APIError>) in
switch result {
case .success(let bonusInfo):
DispatchQueue.main.async {
self.clientBonusInfo = bonusInfo
self.clientTotalBonus = bonusInfo.data.currentQuantity
self.clientBonusBirned = bonusInfo.data.forBurningQuantity
let isoDate = bonusInfo.data.dateBurning
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "ru_RU")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let date = dateFormatter.date(from:isoDate)!
let calendar = Calendar.current
let day = calendar.component(.day, from: date)
let month = calendar.component(.month, from: date)
let dateBurn = String(day) + "." + String(month)
self.birnData = dateBurn
}
case .failure(let apiError):
switch apiError {
case .error(let errorString):
print(errorString)
}
}
}
} else {
print("The token did not come from the server")
}
}
}
|
//
// FriendsPhotoViewController.swift
// VkGb
//
// Created by VitaliyFilippov on 05.04.2018.
// Copyright © 2018 VitaliyFilippov. All rights reserved.
import UIKit
import RealmSwift
private let reuseIdentifier = "Cell"
class FriendsPhotoViewController: UICollectionViewController {
var notificationToken: NotificationToken? = nil
var id: Int!
private var photosList: Results<VKPhotos>?
override func viewDidLoad() {
super.viewDidLoad()
prepareRealm()
loadPhotos()
}
deinit {
notificationToken?.invalidate()
}
func prepareRealm() {
let realm = try! Realm()
photosList = realm.objects(VKPhotos.self)
// Observe Results Notifications
notificationToken = photosList?.observe { [weak self] (changes: RealmCollectionChange) in
guard let collectionView = self?.collectionView else { return }
collectionView.reloadData()
}
}
// // Uncomment the following line to preserve selection between presentations
// // self.clearsSelectionOnViewWillAppear = false
//
// // Register cell classes
// self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
//
// // Do any additional setup after loading the view.
// }
//
// override func didReceiveMemoryWarning() {
// super.didReceiveMemoryWarning()
// // Dispose of any resources that can be recreated.
// }
//
// /*
// // MARK: - Navigation
//
// // In a storyboard-based application, you will often want to do a little preparation before navigation
// override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// // Get the new view controller using [segue destinationViewController].
// // Pass the selected object to the new view controller.
// }
// */
//
// // MARK: UICollectionViewDataSource
//
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
//
//
func loadPhotos() {
let friendsPhotoService = FriendsPhotoService()
friendsPhotoService.loadPhotos(ownerID: id)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photosList!.count
}
//
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FriendsPhoto", for: indexPath) as! FriendsPhotoViewCell
// let id = photosList![indexPath.row]
// let friend = photosList[indexPath.row]
// cell.friendsName.text = friend.first_name + " " + friend.last_name
let photo: String = photosList![indexPath.row].photo_75
do {
try cell.photoView.image = UIImage(data: Data(contentsOf: URL(string:photo)!))!
} catch {
print(error)
}
return cell
}
//
// // MARK: UICollectionViewDelegate
//
// /*
// // Uncomment this method to specify if the specified item should be highlighted during tracking
// override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
// return true
// }
// */
//
// /*
// // Uncomment this method to specify if the specified item should be selected
// override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
// return true
// }
// */
//
// /*
// // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
// override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
// return false
// }
//
// override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
// return false
// }
//
// override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
//
// }
// */
//
}
|
//
// PlayVideoVC.swift
// VideoRecorder
//
// Created by YourtionGuo on 17/11/2016.
// Copyright © 2016 Yourtion. All rights reserved.
//
import UIKit
import AVFoundation
class PlayVideoVC: UIViewController {
open var videoUrl:URL!
var player: AVPlayer? = nil
var playerLayer: AVPlayerLayer? = nil
var playerItem: AVPlayerItem? = nil
var playing = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
guard (videoUrl) != nil else {
return
}
let movieAsset = AVURLAsset(url: videoUrl)
self.playerItem = AVPlayerItem(asset: movieAsset)
self.player = AVPlayer(playerItem: self.playerItem)
self.playerLayer = AVPlayerLayer(player: self.player)
self.playerLayer?.frame = self.view.bounds
self.playerLayer?.videoGravity = AVLayerVideoGravityResizeAspect
self.view.layer.addSublayer(self.playerLayer!)
let playTap = UITapGestureRecognizer(target: self, action: #selector(playOrPause))
self.view.addGestureRecognizer(playTap)
let returnTap = UILongPressGestureRecognizer(target: self, action: #selector(goBack))
self.view.addGestureRecognizer(returnTap)
self.player?.play()
}
func goBack() {
self.dismiss(animated: true, completion: nil)
}
func playOrPause() {
if self.playing {
self.player?.pause()
self.playing = false
} else {
self.player?.play()
self.playing = true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// PostListResponse.swift
// Assignment
//
// Created by Rajmani Kushwaha on 21/02/20.
// Copyright © 2020 Rajmani Kushwaha. All rights reserved.
//
import Foundation
struct PostListResponse: Decodable {
internal let postList: [Post]?
internal let page: Int
internal enum CodingKeys: String, CodingKey {
case postList = "hits"
case page
}
}
struct Post: Decodable {
internal let title: String
internal let url: String?
internal let author: String
internal let points: Int
internal let storyText: String?
internal let storyTitle: String?
internal let storyUrl: String?
internal let createdAt: String
internal var isSelected: Bool? = false
}
|
//
// Lemonade.swift
// LemonadeStand
//
// Created by Christian Romeyke on 22/11/14.
// Copyright (c) 2014 Christian Romeyke. All rights reserved.
//
import Foundation
class Lemonade {
let price = 1
var numLemons, numIceCubes: Int
var flavor: Flavor
init(numLemons:Int, numIceCubes:Int) {
self.numLemons = numLemons
self.numIceCubes = numIceCubes
switch numLemons {
case let(x) where x > numIceCubes:
flavor = Flavor.Acidic
case let(x) where x < numIceCubes:
flavor = Flavor.Diluted
default:
flavor = Flavor.Neutral
}
}
}
|
//
// CameraViewController.swift
// Experiences
//
// Created by Benjamin Hakes on 2/22/19.
// Copyright © 2019 Benjamin Hakes. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
class CameraViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Get authorization
authorization()
// Get user Location
self.geotag = locationHelper.fetchUsersLocation()
// Set up the capture session
let camera = bestCamera()
guard let cameraInput = try? AVCaptureDeviceInput(device: camera) else {
fatalError("Can't create an input from the camera. Do something better than this (crashing).")
}
guard captureSession.canAddInput(cameraInput) else {
fatalError("This session can't handle this kind of input.")
}
captureSession.addInput(cameraInput)
guard captureSession.canAddOutput(fileOutput) else {
fatalError("Cannot record to file")
}
captureSession.addOutput(fileOutput)
if captureSession.canSetSessionPreset(.hd1920x1080) {
captureSession.sessionPreset = .hd1920x1080
} else {
captureSession.sessionPreset = .high
}
captureSession.commitConfiguration()
cameraView.session = captureSession
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
captureSession.startRunning()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
captureSession.stopRunning()
}
// MARK: - AVCaptureFileOutputRecordingDelegate
// starting recording will take a fraction of a second,
// we can't assume that it will start and stop recording
// right away, it may have to finish writing data out to file
// if we were to access the file being written to to quickly,
// it may result in a corrupted file
func fileOutput(_ output: AVCaptureFileOutput, didStartRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) {
DispatchQueue.main.async {
self.updateViews()
}
}
func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
saveVideo(with: outputFileURL)
videoURL = outputFileURL
DispatchQueue.main.async {
self.updateViews()
}
}
// MARK: - Private Methods
private func updateViews(){
let isRecording = fileOutput.isRecording
recordButton.setTitle(isRecording ? "Stop" : "Record", for: .normal)
}
private func bestCamera() -> AVCaptureDevice {
if let device = AVCaptureDevice.default(.builtInDualCamera, for: .video, position: .back) {
return device
}
if let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) {
return device
}
fatalError("Showhow were on a device that doesn't have a camera")
}
func defaultCamera() -> AVCaptureDevice? {
if let device = AVCaptureDevice.default(.builtInDualCamera,
for: AVMediaType.video,
position: .back) {
return device
} else if let device = AVCaptureDevice.default(.builtInWideAngleCamera,
for: AVMediaType.video,
position: .back) {
return device
} else {
return nil
}
}
private func newRecordingURL() -> URL {
let fm = FileManager.default
let documents = try! fm.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let f = ISO8601DateFormatter()
f.formatOptions = [.withInternetDateTime]
let name = f.string(from: Date())
return documents.appendingPathComponent(name).appendingPathExtension("mov")
}
private func saveVideo(with url: URL) {
PHPhotoLibrary.requestAuthorization { status in
guard status == .authorized else { return }
PHPhotoLibrary.shared().performChanges({
PHAssetCreationRequest.creationRequestForAssetFromVideo(atFileURL: url)
}, completionHandler: { (success, error) in
if let error = error {
NSLog("error saving photo: \(error)")
} else {
NSLog("saving photo succeeded")
}
})
}
}
private func authorization() {
let authorizationStatus = AVCaptureDevice.authorizationStatus(for: .video)
switch authorizationStatus {
case .notDetermined:
// we have not asked the user yet for authorization
AVCaptureDevice.requestAccess(for: .video) { granted in
if granted == false {
fatalError("Please don't do this in an actual app")
}
print("Permission Authorized")
}
case .restricted:
// parental controls on the device prevent access to the cameras
fatalError("Please have beter scenario handling than this")
case .denied:
// we asked for permission, but they said no
fatalError("Please have beter scenario handling than this")
case .authorized:
// we asked for permission, and they said yes
print("Permission Authorized")
}
}
// MARK: - IBActions
@IBAction func toggleRecording(_ sender: Any) {
if fileOutput.isRecording {
fileOutput.stopRecording()
} else {
let url = newRecordingURL()
fileOutput.startRecording(to: url, recordingDelegate: self)
}
}
@IBAction func saveButtonClicked(_ sender: Any) {
guard let title = titleString,
let audioURL = audioURL,
let videoURL = videoURL,
let imageURL = imageURL else {fatalError("not enough information to create a new experience")}
experienceController.createExperience(with: title, audioURL: audioURL, videoURL: videoURL, imageURL: imageURL, geotag: geotag)
self.dismiss(animated: true) {
self.navigationController?.popViewController(animated: true)
}
}
// AVPlayer - playback
// this is playback but not visualization
// AVPlayerLayer - like subclass of CameraPreviewLayer
// set the
// AVKit - provides a whole entire view controller
// you can standard playback UI
// simply by initializing one and setting a player property on it
//
// MARK: - Properties
@IBOutlet weak var cameraView: CameraPreviewView!
private let captureSession = AVCaptureSession()
var locationHelper = LocationHelper()
var experienceController = ExperienceController()
private let fileOutput = AVCaptureMovieFileOutput()
@IBOutlet weak var recordButton: UIButton!
var imageURL: URL?
var titleString: String?
var audioURL: URL?
var videoURL: URL?
var geotag: CLLocationCoordinate2D?
}
|
//
// AppVariables.swift
// AR_Camera
//
// Created by Justin Lee on 3/26/20.
// Copyright © 2020 com.lee. All rights reserved.
//
import Foundation
import UIKit
var screenWidth:CGFloat = CGFloat();
var screenHeight:CGFloat = CGFloat();
var cameraButtonDimension:CGFloat = CGFloat();
var cameraButtonMinY: CGFloat = CGFloat();
public func instantiateVariables() {
cameraButtonDimension = screenWidth*0.2
cameraButtonMinY = screenHeight*0.9 - cameraButtonDimension
}
|
import RxSwift
import RxCocoa
/**
The QuizListViewModel is a canonical representation of the QuizListView. That is, the QuizListViewModel provides a set of interfaces, each of which represents a UI component in the QuizListView.
*/
public class QuizListViewModel {
/// :nodoc:
private let disposeBag = DisposeBag()
/// :nodoc:
var courseID: Int?
/// Represents a value that changes over time.
let items: BehaviorRelay<[QuizSectionModel]>
/// :nodoc:
let success: PublishSubject<Void>
/// :nodoc:
let failure: PublishSubject<NetworkError>
/// :nodoc:
let loadPageTrigger: PublishSubject<Void>
/**
Constructor of viewmodel. Initializes all attributes, subscriptions, observables etc.
- Postcondition:
ViewModel object will be initialized. Subscriptions, triggers and subjects will be created.
*/
init() {
items = BehaviorRelay(value: [])
failure = PublishSubject()
success = PublishSubject()
loadPageTrigger = PublishSubject()
loadPageTrigger.asObservable()
.flatMap { [unowned self] (_) -> Observable<[QuizSectionModel]> in
var endpoint: QuizEndpoint = .owner
if let id = self.courseID {
endpoint = QuizEndpoint.course(id: id)
}
return self.fetch(endpoint)
}.bind(to: items)
.disposed(by: disposeBag)
}
/// :nodoc:
convenience init(courseID: Int) {
self.init()
self.courseID = courseID
}
/**
Fires an HTTP GET API request to the given endpoint. Response will be converted to observable of needed object.
- Parameters:
- endpoint: An `EndpointType` instance.
- Precondition: `endpoint` must be non-nil.
- Postcondition:
API request will be send and after getting response, it will be returned. If an error occupied, error event will be fired.
- Returns: Observable<[QuizSectionModel]>
*/
public func fetch(_ endpoint: QuizEndpoint) -> Observable<[QuizSectionModel]> {
return Observable.create({ [weak self] (observer) -> Disposable in
guard let strongSelf = self else { return Disposables.create() }
NetworkManager.shared.request(endpoint, [Quiz].self)
.subscribe(onNext: { (result) in
switch result {
case .success(let object):
var sectionModel: [QuizSectionModel] = []
object.forEach({ (quiz) in
sectionModel.append(.quiz(item: quiz))
})
observer.onNext(sectionModel)
case .failure(let error):
strongSelf.failure.onNext(error)
}
}).disposed(by: strongSelf.disposeBag)
return Disposables.create()
})
}
/**
Fires a API request. If the given quiz will found in the system it will be validated. If validation is ok then quiz will be deleted.
- Parameters:
- quiz: Quiz instance.
- Precondition: `quiz` must be non-nil.
- Precondition: `quiz` must not be started or must be finished.
- Precondition: `quiz` must be created by logged user.
- Invariant: `quiz` reference will not change during the execution of this method.
- Postcondition:
If the given quiz will found in the system it will be validated. If validation is ok then logged user will append to the quiz and feedback event will be fired. Otherwise, error event will fired.
*/
public func delete(_ quiz: Quiz) {
let endpoint = QuizEndpoint.delete(quizID: quiz.id)
NetworkManager.shared.requestJSON(endpoint, .apiMessage)
.subscribe(onNext: { [weak self] (result) in
switch result {
case .success:
self?.success.onNext(())
case .failure(let error):
self?.failure.onNext(error)
}
}).disposed(by: disposeBag)
}
/**
Fires a API request. If the given quiz id will found in the system it will be validated. If validation is ok then logged user will append to the quiz.
- Parameters:
- id: Identifier of the quiz.
- Precondition: `id` must be non-nil.
- Precondition: `id` must be greater than 0.
- Precondition: `quiz` must not be started.
- Precondition: `quiz` must not be private.
- Precondition: `quiz` must not be created by logged user.
- Precondition: logged user must not be instructor.
- Precondition: logged user must not be in the list of participants of `quiz`.
- Invariant: `quiz` reference will change during the execution of this method.
- Postcondition:
If the given quiz id will found in the system it will be validated. If validation is ok then logged user will append to the quiz and feedback event will be fired. Otherwise, error event will fired.
*/
public func append(_ id: Int) {
let endpoint = QuizEndpoint.append(quizID: id)
NetworkManager.shared.requestJSON(endpoint, .apiMessage)
.subscribe(onNext: { [weak self] (result) in
switch result {
case .success:
self?.success.onNext(())
case .failure(let error):
self?.failure.onNext(error)
}
}).disposed(by: disposeBag)
}
}
|
//
// ZXAddRemindViewController.swift
// YDHYK
//
// Created by 120v on 2017/11/22.
// Copyright © 2017年 screson. All rights reserved.
//
import UIKit
class ZXAddRemindViewController: ZXUIViewController {
struct TextTag {
static let drugName = 5311
static let dosage = 5312
static let remark = 5313
static let cycle = 5314
}
//
@IBOutlet weak var drugNameText: UITextField!
@IBOutlet weak var dosageText: UITextField!
@IBOutlet weak var descText: UITextField!
@IBOutlet weak var historyBtn: UIButton!
@IBOutlet weak var unitBtn: ZXBButton!
//
@IBOutlet weak var drugCycleText: UITextField!
@IBOutlet weak var drugCycleBtn: UIButton!
//
@IBOutlet weak var drugTimeView: ZXSettingTimeView!
/* 用药时间*/
var drugDateStr: String = ""
/* 用药单位*/
var unitStr: String = ""
/* 用药周期的键*/
var cycleKey: String = ""
class func loadStoryBoard() -> ZXAddRemindViewController {
return UIStoryboard.init(name: "DrugRemind", bundle: nil).instantiateViewController(withIdentifier: "ZXAddRemind") as! ZXAddRemindViewController
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "添加提醒"
self.view.backgroundColor = UIColor.white
//nav
self.zx_addNavBarButtonItems(textNames: ["保存"], font: nil, color: nil, at: .right)
//Http
self.requestForHistoryOrder()
self.requestForDrugUnits()
self.requestForDrugCycle()
//
self.setUI()
//获取时间设置
self.getDate()
}
func setUI() {
self.drugNameText.delegate = self
self.dosageText.delegate = self
self.descText.delegate = self
self.drugCycleText.delegate = self
self.drugNameText.textColor = UIColor.zx_textColorTitle
self.dosageText.textColor = UIColor.zx_textColorTitle
self.descText.textColor = UIColor.zx_textColorTitle
self.drugCycleText.textColor = UIColor.zx_textColorTitle
}
//MARK: - NAV/保存
override func zx_rightBarButtonAction(index: Int) {
self.resignFirstRespond()
self.requestForSave()
}
//MARK: - 获取时间设置
func getDate() {
self.drugTimeView.completion = {drugDateArr in
var arr: Array<String> = Array.init()
for model in drugDateArr {
arr.append(model.drugTime)
}
self.drugDateStr = arr.joined(separator: ",")
}
}
//MARK: - 历史记录
@IBAction func historyBtnAction(_ sender: UIButton) {
self.resignFirstRespond()
let hisVC: ZXHistoryOrderController = ZXHistoryOrderController()
hisVC.delegate = self
hisVC.hidesBottomBarWhenPushed = true
hisVC.histOrderArray = self.hisOrderArr
self.navigationController?.pushViewController(hisVC, animated: true)
}
//Mark: - 单位
@IBAction func unitBtnAction(_ sender: UIButton) {
self.resignFirstRespond()
if self.drugUnitsArr.count > 0 {
let arr: NSMutableArray = NSMutableArray.init(capacity: 5)
for model in self.drugUnitsArr {
arr.add(model.value)
}
let drugUnitsView: ZXPopView = ZXPopView.loadNib()
drugUnitsView.delegate = self
drugUnitsView.flag = ZXPopView.PopViewFlag.DrugUnits
ZXRootController.appWindow()?.addSubview(drugUnitsView)
drugUnitsView.loadData(NSMutableArray.init(array: arr),"选择用药单位","")
}else{
ZXHUD.showFailure(in: self.view, text: "暂无数据", delay: ZX.HUDDelay)
}
}
//MARK: - 用药周期
@IBAction func drugCycleBtnAction(_ sender: UIButton) {
self.resignFirstRespond()
if self.drugUnitsArr.count > 0 {
let arr: NSMutableArray = NSMutableArray.init(capacity: 5)
for model in self.drugCycleArr {
arr.add(model.value)
}
let drugCycleView: ZXPopView = ZXPopView.loadNib()
drugCycleView.delegate = self
drugCycleView.flag = ZXPopView.PopViewFlag.DrugCycle
ZXRootController.appWindow()?.addSubview(drugCycleView)
drugCycleView.loadData(NSMutableArray.init(array: arr),"选择用药周期","")
}else{
ZXHUD.showFailure(in: self.view, text: "暂无数据", delay: ZX.HUDDelay)
}
}
//MARK: - 注销TextField响应
func resignFirstRespond() {
self.view.endEditing(true)
self.drugNameText.resignFirstResponder()
self.dosageText.resignFirstResponder()
self.descText.resignFirstResponder()
self.drugCycleText.resignFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Lazy
/** 历史订单*/
lazy var hisOrderArr: Array<ZXHistoryOrderModel> = {
let arr: Array<ZXHistoryOrderModel> = Array.init()
return arr
}()
/** 用药单位*/
lazy var drugUnitsArr: Array<ZXCommonModel> = {
let arr: Array<ZXCommonModel> = Array.init()
return arr
}()
/** 用药提醒周期*/
lazy var drugCycleArr: Array<ZXCommonModel> = {
let arr: Array<ZXCommonModel> = Array.init()
return arr
}()
}
//MARK: - UITextFieldDelegate
extension ZXAddRemindViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if (textField.textInputMode?.primaryLanguage!.isEqual("emoji")) == true || ((textField.textInputMode?.primaryLanguage) == nil){
return false
}
switch textField.tag {
case TextTag.drugName:
if range.location + string.count > 16 {
ZXHUD.showFailure(in: self.view, text: "药品名称不能大于16个字符", delay: ZX.HUDDelay)
return false
}
case TextTag.dosage:
if range.location + string.count > 8 {
ZXHUD.showFailure(in: self.view, text: "药品名称不能大于8个字符", delay: ZX.HUDDelay)
return false
}
case TextTag.remark:
if range.location + string.count > 16 {
ZXHUD.showFailure(in: self.view, text: "药品名称不能大于16个字符", delay: ZX.HUDDelay)
return false
}
default:
break
}
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
//MARK: - ZXHistoryOrderControllerDelegate
extension ZXAddRemindViewController: ZXHistoryOrderControllerDelegate {
func didHistoryOrderCell(_ model: ZXHistoryOrderDetailModel) {
self.drugNameText.text = model.drugName
}
}
extension ZXAddRemindViewController: ZXPopViewDelegate {
func didSelectedPopViewCell(_ str: String, _ flag: Int) {
switch flag {
case ZXPopView.PopViewFlag.DrugUnits:
self.unitBtn.setTitle(str, for: .normal)
self.unitStr = str
case ZXPopView.PopViewFlag.DrugCycle:
self.drugCycleText.text = str
for model in self.drugCycleArr {
if model.value == str {
self.cycleKey = model.key
}
}
default:
break
}
}
}
//MARK: - HTTP
extension ZXAddRemindViewController {
//MARK: - 用药提醒历史订单药品列表
func requestForHistoryOrder() {
ZXAddRemindControl.requestForGetHistoryDrugOrder { (succ, code, hisArr) in
if succ,hisArr?.count != 0 {
self.hisOrderArr = hisArr!
self.historyBtn.isHidden = false
}else{
self.historyBtn.isHidden = true
/* 测试数据
for i in 0..<5 {
let model = ZXHistoryOrderModel()
model.drugstoreName = "name+\(arc4random_uniform(UInt32(i*5)))"
model.orderDateStr = "2017-10-22 18:30:00"
var arr:Array<Any> = []
for _ in 0..<3 {
let subMod = ZXHistoryOrderDetailModel()
subMod.drugName = "药名+\(arc4random_uniform(UInt32(i*5)))"
arr.append(subMod)
}
model.orderDetailList = arr
self.hisOrderArr.append(model)
}
*/
}
}
}
//MARK: - 药品单位
func requestForDrugUnits() {
ZXAddRemindControl.requestForGetDrugUnits("10", completion: { (succ, Code, dictList) in
if succ,dictList?.count != 0 {
self.drugUnitsArr = dictList!
}
})
}
//MARK: - 用药周期
func requestForDrugCycle() {
ZXAddRemindControl.requestForGetDrugUnits("8", completion: { (succ, Code, dictList) in
if succ,dictList?.count != 0 {
self.drugCycleArr = dictList!
}
})
}
//MARK: - 保存
func requestForSave() {
var dict: Dictionary<String,Any> = Dictionary()
if self.drugNameText.text?.isEmpty == false {
dict["drugName"] = self.drugNameText.text
}else{
ZXHUD.showFailure(in: self.view, text: "药品名不能为空", delay: ZX.HUDDelay)
return
}
if self.dosageText.text?.isEmpty == false {
dict["dosage"] = self.dosageText.text
}else{
ZXHUD.showFailure(in: self.view, text: "每次用量不能为空", delay: ZX.HUDDelay)
return
}
if self.unitBtn.titleLabel?.text?.isEmpty == false {
dict["unitValue"] = self.unitBtn.titleLabel?.text
}else{
ZXHUD.showFailure(in: self.view, text: "用药单位不能为空", delay: ZX.HUDDelay)
return
}
if self.descText.text?.isEmpty == false {
dict["notes"] = self.descText.text
}
if self.drugCycleText.text?.isEmpty == false,self.cycleKey.isEmpty == false {
dict["cycleValue"] = self.drugCycleText.text
dict["cycleKey"] = self.cycleKey
}else{
ZXHUD.showFailure(in: self.view, text: "用药周期不能为空", delay: ZX.HUDDelay)
return
}
if self.drugDateStr.isEmpty == false {
dict["remindTimes"] = self.drugDateStr
}else{
ZXHUD.showFailure(in: self.view, text: "用药时间不能为空", delay: ZX.HUDDelay)
return
}
ZXHUD.showLoading(in: self.view, text: ZX_LOADING_TEXT, delay: nil)
ZXAddRemindControl.requestForAddDrugRemind(dict) { (succ, code, errMsg) in
ZXHUD.hide(for: self.view, animated: true)
if succ {
if code == ZXAPI_SUCCESS {
ZXHUD.showSuccess(in: self.view, text: "设置成功", delay: ZX.HUDDelay)
//
self.navigationController?.popViewController(animated: true)
}else{
ZXHUD.showFailure(in: self.view, text: errMsg!, delay: ZX.HUDDelay)
}
}else{
ZXHUD.showFailure(in: self.view, text: errMsg!, delay: ZX.HUDDelay)
}
}
}
}
|
//
// data.swift
// 00557117
//
// Created by User19 on 2019/10/9.
// Copyright © 2019 557021. All rights reserved.
//
import SwiftUI
struct data: View {
var body: some View {
Text(/*@START_MENU_TOKEN@*/"Hello World!"/*@END_MENU_TOKEN@*/)
}
}
struct data_Previews: PreviewProvider {
static var previews: some View {
data()
}
}
|
//
// AboutUs.swift
// Tonsorial LIC
//
// Created by Jose Delaguarda on 6/18/19.
// Copyright © 2019 DLGTECH. All rights reserved.
//
import UIKit
class AboutUs : UIViewController {
override func viewDidLoad(){
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
//
// AllJobsModelController.swift
// NYC_JOBS_DATA_FINAL
//
// Created by Jonathan Cravotta on 5/28/18.
// Copyright © 2018 Jonathan Cravotta. All rights reserved.
//
import Foundation
import ReactiveSwift
class AllJobsModelController {
var data: [Job] = []
var state: MutableProperty<State<[Job]>>
init() {
state = MutableProperty(.initial)
}
func refreshData(withSearchTerm term: String? = nil) {
var urlString = "https://data.cityofnewyork.us/resource/swhp-yxa4.json"
if let term = term {
urlString = urlString + "?$q=\(term)".addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!
}
let url = URL(string: urlString)!
state.value = .updating
NetworkClient.get(with: url) { [weak self] (response) in
guard let `self` = self else { return }
switch response {
case .success(let data):
do {
let decodedData = try JSONDecoder().decode([Job].self, from: data)
self.data = decodedData
self.state.value = .didUpdate(decodedData)
} catch let error {
print(error.localizedDescription)
self.state.value = .didFailToUpdate
}
case .error:
self.state.value = .didFailToUpdate
}
}
}
}
|
//
// TestAppDelegate.swift
// TodoListTests
//
// Created by Christian Oberdörfer on 18.03.19.
// Copyright © 2019 Christian Oberdörfer. All rights reserved.
//
import UIKit
/// Minimum app delegate for faster testing
class TestAppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow? = UIWindow(frame: UIScreen.main.bounds)
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.backgroundColor = UIColor.white
self.window?.rootViewController = UIViewController()
self.window?.makeKeyAndVisible()
return true
}
}
|
//
// GeofenceTracker.swift
// GeofenceCaseStudy
//
// Created by Atul Gawali on 20/07/21.
//
import Foundation
/// The Geofence Tracker Delegate is used to pass the event to controller.
///
protocol GeofenceTrackerDelegate: AnyObject {
/// The updated region called when region update
///
/// - Parameter region: The list of the region we need to display
///
func updatedRegion(region: [GeofenceRegion])
}
class GeofenceTracker {
// MARK: - Properties
static let shared = GeofenceTracker()
/// The delegate used to trigger event
weak var delegate: GeofenceTrackerDelegate?
/// The region list store in memory.
fileprivate var regionList: [GeofenceRegion]
/// The geofence event tracker deal with the location.
fileprivate let geofenceTracker = LocationEventManager()
// Initialization
private init() {
regionList = [
GeofenceRegion(id: "001", isEntered: false, latitude: 40.6892, longitude: 74.0445, name: "Statue of Liberty", radius: 50),
GeofenceRegion(id: "002", isEntered: false, latitude: 51.5014, longitude: 0.1419, name: "Buckingham Palace", radius: 50),
GeofenceRegion(id: "003", isEntered: false, latitude: 47.5576, longitude: 10.7498, name: "Neuschwanstein Castle", radius: 50),
GeofenceRegion(id: "004", isEntered: false, latitude: 19.0176147, longitude: 72.8561644, name: "Mumbai India", radius: 50),
]
geofenceTracker.initializeLocationManager()
geofenceTracker.delegate = self
for item in regionList {
geofenceTracker.addCircularRegion(id: item.id, lat: item.latitude, lng: item.longitude, radius: item.radius)
}
}
/// Get region list public function
///
/// - returns: The list of geofence array.
func getRegionList() -> [GeofenceRegion] {
return regionList
}
/// The update Geofence in the memory
///
/// - Parameters:
/// - id: The geofence id
/// - isEntered: The bool value need to updated in model
///
fileprivate func updateGeofence(id: String, isEntered: Bool) {
regionList = regionList.map { item in
var region = item
if region.id == id {
region.isEntered = isEntered
EventLogger.shared.printLog(message: region.debugDescription, event: .i)
}
return region
}
}
}
extension GeofenceTracker: LocationManagerDelegate {
/// The updated region called when region update
///
/// - Parameters:
/// - region: The list of the region we need to display
/// - isEntered: The bool value need to updated in model
///
func didUpdateRegion(id: String, isEntered: Bool) {
self.updateGeofence(id: id, isEntered: isEntered)
delegate?.updatedRegion(region: self.regionList)
EventLogger.shared.printLog(message: "did Update Region", event: .i)
}
}
|
//
// AccessTokenParser.swift
// Slidecoin
//
// Created by Oleg Samoylov on 19.12.2019.
// Copyright © 2019 Oleg Samoylov. All rights reserved.
//
import Foundation
import Toolkit
final class AccessTokenParser: ParserProtocol {
func parse(data: Data) -> String? {
do {
let jsonDecorder = JSONDecoder()
jsonDecorder.dateDecodingStrategy = .iso8601
jsonDecorder.keyDecodingStrategy = .convertFromSnakeCase
let response = try jsonDecorder.decode(TokenRefresh.self, from: data)
return response.accessToken
} catch {
print(error)
return nil
}
}
}
|
//
// AssetModuleBuild.swift
// WavesWallet-iOS
//
// Created by mefilt on 06.08.2018.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import UIKit
import Extensions
struct AssetDetailModuleBuilder: ModuleBuilderOutput {
struct Input: AssetDetailModuleInput {
var assets: [AssetDetailTypes.DTO.Asset.Info]
var currentAsset: AssetDetailTypes.DTO.Asset.Info
}
var output: AssetDetailModuleOutput
func build(input: AssetDetailModuleBuilder.Input) -> UIViewController {
let presenter = AssetDetailPresenter(input: input)
let vc = StoryboardScene.Asset.assetViewController.instantiate()
presenter.interactor = AssetDetailInteractor()
presenter.moduleOutput = output
vc.presenter = presenter
return vc
}
}
|
//
// BinaryNode.swift
// BinaryNode
//
// Created by Valeriano Della Longa on 2021/01/27.
// Copyright © 2021 Valeriano Della Longa
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
/// A protocol defining functionalites for a 2-node data structure with reference semantics.
/// That is a 2-node is a node with a key/value pair as element and two children nodes,
/// one at its left and one at its right.
/// Thus recursively defining a binary tree.
///
/// - ToDo: conformance to CustomStringConvertible and CustomDebugStringConvertible
public protocol BinaryNode: AnyObject, Sequence where Element == (key: Key, value: Value) {
associatedtype Key
associatedtype Value
/// The key for this node
var key: Key { get }
/// The value stored in this node
var value: Value { get }
/// The number of elements for this node.
var count: Int { get }
/// The child node to the left of this node.
var left: Self? { get }
/// The child node to the right of this node.
var right: Self? { get }
}
// MARK: - Default implementations
extension BinaryNode {
public var count: Int {
1 + (left?.count ?? 0) + (right?.count ?? 0)
}
}
// MARK: - Sequence default implementation
extension BinaryNode {
/// The key-value pair for this node.
public var element: Element { (key: key, value: value) }
public var underestimatedCount: Int {
1 + (left != nil ? 1 : 0) + (right != nil ? 1 : 0)
}
public func makeIterator() -> AnyIterator<Element> {
withExtendedLifetime(self, {
var stack = [WrappedNode<Self>]()
var wrappedNode: WrappedNode<Self>? = WrappedNode(node: $0)
return AnyIterator {
while let n = wrappedNode {
stack.append(n)
wrappedNode = n.wrappedLeft
}
guard
let current = stack.popLast()
else { return nil }
defer { wrappedNode = current.wrappedRight }
return current.node.element
}
})
}
public func forEach(_ body: (Element) throws -> Void) rethrows {
try inOrderTraverse { try body($0.element) }
}
public func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element] {
var result = [Element]()
try inOrderTraverse {
if try isIncluded($0.element) {
result.append($0.element)
}
}
return result
}
public func map<T>(_ transform: (Element) throws -> T) rethrows -> [T] {
var result = [T]()
try inOrderTraverse {
let newValue = try transform($0.element)
result.append(newValue)
}
return result
}
public func compactMap<ElementOfResult>(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] {
var result = [ElementOfResult]()
try inOrderTraverse {
try transform($0.element)
.map { result.append($0) }
}
return result
}
@available(swift, deprecated: 4.1, renamed: "compactMap(_:)", message: "Please use compactMap(_:) for the case where closure returns an optional value")
public func flatMap<ElementOfResult>(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] {
try compactMap(transform)
}
public func flatMap<SegmentOfResult>(_ transform: (Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult : Sequence {
var result = [SegmentOfResult.Element]()
try inOrderTraverse {
let segment = try transform($0.element)
result.append(contentsOf: segment)
}
return result
}
public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Element) throws -> ()) rethrows -> Result {
var result = initialResult
try inOrderTraverse {
try updateAccumulatingResult(&result, $0.element)
}
return result
}
public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result {
try reduce(into: initialResult) {
$0 = try nextPartialResult($0, $1)
}
}
public func first(where predicate: (Element) throws -> Bool) rethrows -> Element? {
if let lF = try left?.first(where: predicate) { return lF }
if try predicate((key, value)) { return element }
return try right?.first(where: predicate)
}
public func contains(where predicate: (Element) throws -> Bool) rethrows -> Bool {
guard
try (left?.contains(where: predicate) ?? false) == false
else { return true }
guard
try predicate(element) == false
else { return true }
return try (right?.contains(where: predicate) ?? false)
}
public func allSatisfy(_ predicate: (Element) throws -> Bool) rethrows -> Bool {
guard
try (left?.allSatisfy(predicate) ?? true)
else { return false }
guard
try predicate(element)
else { return false }
return try (right?.allSatisfy(predicate) ?? true)
}
public func reversed() -> [Element] {
var result = [(Key, Value)]()
reverseInOrderTraverse { result.append($0.element) }
return result
}
}
// MARK: - Tree and binary search tree operations
// MARK: - Tree traversal operations
extension BinaryNode {
/// Traverse the binary tree rooted at this node in-order executing the given `body` closure
/// on each node during the traversal operation.
///
/// - Parameter _: a closure to execute on every node during the traversal.
/// - Complexity: O(`n`) where `n` is the count of nodes in the tree rooted at this
/// node.
public func inOrderTraverse(_ body: (Self) throws -> Void) rethrows {
try left?.inOrderTraverse(body)
try body(self)
try right?.inOrderTraverse(body)
}
/// Traverse the binary tree rooted at this node in reverse-in-order executing the given
/// `body` closure on each node during the traversal operation.
///
/// - Parameter _: a closure to execute on every node during the traversal.
/// - Complexity: O(`n`) where `n` is the count of nodes in the tree rooted at this
/// node.
public func reverseInOrderTraverse(_ body: (Self) throws -> Void) rethrows {
try right?.reverseInOrderTraverse(body)
try body(self)
try left?.reverseInOrderTraverse(body)
}
/// Traverse the binary tree rooted at this node in pre-order executing the given `body`
/// closure on each node during the traversal operation.
///
/// - Parameter _: a closure to execute on every node during the traversal.
/// - Complexity: O(`n`) where `n` is the count of nodes in the tree rooted at this
/// node.
public func preOrderTraverse(_ body: (Self) throws -> Void) rethrows {
try body(self)
try self.left?.preOrderTraverse(body)
try self.right?.preOrderTraverse(body)
}
/// Traverse the binary tree rooted at this node in post-order executing the given `body`
/// closure on each node during the traversal operation.
///
/// - Parameter _: a closure to execute on every node during the traversal.
/// - Complexity: O(`n`) where `n` is the count of nodes in the tree rooted at this
/// node.
public func postOrderTraverse(_ body: (Self) throws -> Void) rethrows {
try left?.postOrderTraverse(body)
try right?.postOrderTraverse(body)
try body(self)
}
/// Traverse the binary tree rooted at this node in level-order executing the given `body`
/// closure on each node during the traversal operation.
///
/// - Parameter _: a closure to execute on every node during the traversal.
/// - Complexity: Amortized O(`n`) where `n` is the count of nodes in the tree
/// rooted at this node.
public func levelOrderTraverse(_ body: (Self) throws -> Void) rethrows {
try withExtendedLifetime(self, {
var currentLevel = _Queue<WrappedNode<Self>>()
currentLevel.enqueue(WrappedNode(node: $0))
try _levelOrder(currentLevel: ¤tLevel, body: body)
})
}
fileprivate func _levelOrder(currentLevel: inout _Queue<WrappedNode<Self>>, body: (Self) throws -> Void) rethrows {
var nextLevel = _Queue<WrappedNode<Self>>()
while let wrappedNode = currentLevel.dequeue() {
try body(wrappedNode.node)
if wrappedNode.wrappedLeft != nil { nextLevel.enqueue(wrappedNode.wrappedLeft!) }
if wrappedNode.wrappedRight != nil { nextLevel.enqueue(wrappedNode.wrappedRight!) }
}
guard !nextLevel.isEmpty else { return }
try _levelOrder(currentLevel: &nextLevel, body: body)
}
}
// MARK: - paths
extension BinaryNode {
/// The nodes to traverse in the tree rooted at this node to get to a leaf.
public typealias Path = [WrappedNode<Self>]
/// Every path to leaf nodes in the tree rooted at this node.
///
/// Every node in a path is wrapped as an `unowned(unsafe)` instance,
/// not to strongly reference it and increase its reference count: therefore a path
/// is not reliable to be stored.
/// Attempting to access a node in a path when the original node was already
/// deallocated results in unexpected beahvior and potential run-time errors.
/// Additionally when a node is changed, the path in which was previously stored
/// might as well not be valid anymore.
/// - Complexity: O(*n²*) where *n* is the lenght of the tree
/// rooted at this node.
public var paths: [Path] {
withExtendedLifetime(self, {
buildPaths(WrappedNode(node: $0), current: [])
})
}
fileprivate func buildPaths(_ wrappedNode: WrappedNode<Self>, current: Path) -> [Path] {
var paths = [Path]()
let updated = current + [wrappedNode]
if wrappedNode.wrappedLeft == nil && wrappedNode.wrappedRight == nil {
paths.append(updated)
} else {
if wrappedNode.wrappedLeft != nil {
paths += buildPaths(wrappedNode.wrappedLeft!, current: updated)
}
if wrappedNode.wrappedRight != nil {
paths += buildPaths(wrappedNode.wrappedRight!, current: updated)
}
}
return paths
}
}
// MARK: - Binary Search Tree utilities
extension BinaryNode where Key: Comparable {
/// A boolean value, `true` when the tree rooted at this node is a Binary Search Tree.
///
/// A Binary Search Tree holds the invariant recursively so that the left children has a smaller
/// `key` than the node and the right children has a greater `key` than the node.
public var isBinarySearchTree: Bool {
if left != nil {
guard
left!.key < key,
left!.isBinarySearchTree
else { return false }
}
if right != nil {
guard
right!.key > key,
right!.isBinarySearchTree
else { return false }
}
return true
}
/// Lookup and returns the node with the given `key` in the tree rooted at this node, by
/// adopting a binary search on it.
///
/// - Parameter needle: The `key` to lookup for.
/// - Returns: The node in the tree with the given `key`, or `nil` if such a node
/// couldn't be found.
/// - Complexity: O(log *n*) where *n* is the count of nodes in the tree rooted at
/// this node.
/// - Note: If the tree rooted at this node is not a Binary Search Tree, then this method
/// won't behave as expected.
public func binarySearch(_ needle: Key) -> Self? {
if needle < key { return left?.binarySearch(needle) }
if needle > key { return right?.binarySearch(needle) }
if needle == key { return self }
return nil
}
}
// MARK: - Sequential Search
extension BinaryNode where Key: Equatable {
/// Lookup for the node with the given `key` in the tree rooted at this node.
///
/// - Parameter needle: The `key` to lookup for.
/// - Returns: The node in the tree with the given `key`, or `nil` if such a node
/// couldn't be found.
/// - Complexity: O(*n*) where *n* is the count of nodes in the tree rooted at this
/// node.
/// - Note: This search algorithm uses a pre-order tree traversal algorithm.
/// Hence checking for queried key on currently traversed node,
/// then recursively on its left and right nodes.
public func sequentialSearch(_ needle: Key) -> Self? {
if needle == key { return self }
return left?.sequentialSearch(needle) ?? right?.sequentialSearch(needle)
}
}
// MARK: - WrappedNode
/// Wraps an `unowned(unsafe)` instance of `BinaryNode` used
/// to weakly reference node instances without incrementing their reference count.
public struct WrappedNode<Node: BinaryNode> {
/// The wrapped node instance.
public unowned(unsafe) let node: Node
/// The `left` node of the wrapped node as `WrappedNode`; `nil` when the wrapped node's `left == nil` .
public var wrappedLeft: WrappedNode? {
guard node.left != nil else { return nil }
return WrappedNode(node: node.left!)
}
/// The `right` node of the wrapped node as `WrappedNode`; `nil` when the wrapped node's `right == nil` .
public var wrappedRight: WrappedNode? {
guard node.right != nil else { return nil }
return WrappedNode(node: node.right!)
}
/// Returns a new instance initialized to wrap the given node
///
/// - Returns: A new instance wrapping the given node.
public init(node: Node) {
self.node = node
}
}
// MARK: - Queue used internally for level order tree traversal
fileprivate struct _Queue<Element>: Sequence {
private var enqueued: [Element] = []
private var dequeued: [Element] = []
var count: Int { enqueued.count + dequeued.count }
var underestimatedCount: Int { dequeued.count }
var isEmpty: Bool { enqueued.isEmpty && dequeued.isEmpty }
mutating func enqueue(_ newElement: Element) {
enqueued.append(newElement)
}
mutating func dequeue() -> Element? {
if dequeued.isEmpty && !enqueued.isEmpty {
dequeued = enqueued.reversed()
enqueued.removeAll()
}
return dequeued.popLast()
}
mutating func next() -> Element? { dequeue() }
func makeIterator() -> AnyIterator<Element> {
var elements = self
return AnyIterator { elements.next() }
}
}
|
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
final class URLSessionHTTPClientAdapter: HTTPClient {
private let urlSession: URLSession
init(urlSession: URLSession) {
self.urlSession = urlSession
}
func get(url: URL, headers: [String: String]) async throws -> HTTPResponse {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "GET"
for header in headers {
urlRequest.addValue(header.value, forHTTPHeaderField: header.key)
}
let data: Data
let response: URLResponse
do {
(data, response) = try await perform(urlRequest)
} catch let error {
throw error
}
guard let httpURLResponse = response as? HTTPURLResponse else {
return HTTPResponse(statusCode: -1, data: nil)
}
let statusCode = httpURLResponse.statusCode
return HTTPResponse(statusCode: statusCode, data: data)
}
}
extension URLSessionHTTPClientAdapter {
#if canImport(FoundationNetworking)
private func perform(_ urlRequest: URLRequest) async throws -> (Data, URLResponse) {
return try await withCheckedThrowingContinuation { continuation in
urlSession.dataTask(with: urlRequest) { data, response, error in
if let error {
continuation.resume(throwing: error)
return
}
guard let data, let response else {
continuation.resume(throwing: NSError(domain: "uk.co.adam-young.TMDb", code: -1))
return
}
continuation.resume(returning: (data, response))
}
.resume()
}
}
#else
private func perform(_ urlRequest: URLRequest) async throws -> (Data, URLResponse) {
try await urlSession.data(for: urlRequest)
}
#endif
}
|
//
// DatabaseBusyError.swift
// RepoDB
//
// Created by Groot on 13.09.2020.
// Copyright © 2020 K. All rights reserved.
//
import Foundation
struct DatabaseBusyError: RepoDatabaseError {
var code: Int { return 5 }
var message: String { return ErrorLocalizer.error_code_5.localize() }
}
|
import Foundation
import Alamofire
import RxSwift
typealias Parameters = [String: Any]?
typealias DeezerObject = [String: Any]
typealias DeezerResponse = (response: Any, serverError: String?)
/**
The API protocol contains all the properties and methods to implement a network client
*/
protocol API {
var baseUrl: String { get set }
func requestPlaylists(for user: String, parameters: Parameters) -> Single<DeezerResponse>
func requestTracks(for playlist: String, parameters: Parameters) -> Single<DeezerResponse>
}
/**
Implementation of API protocol for Deezer client
Documentation can be found at: https://developers.deezer.com/api/
*/
class DeezerApi: API {
/// Base url to access Deezer RESTAPI
var baseUrl: String
/// Custom init for Deezer Client
///
/// - Parameter url: String base url
init(with url: String) {
self.baseUrl = url
}
/// This method request all the playlist a user has on his account
///
/// - Parameters:
/// - user: String userId to fetch
/// - parameters: Parameters? used to implement different request such as post/deelete/patch
/// - Returns: Single<DeezerResponse> Observable that returns a tuple (data, internal error) on success
func requestPlaylists(for user: String, parameters: Parameters) -> Single<DeezerResponse> {
return Single<DeezerResponse>.create { observer in
// Create Request
let request = Alamofire.request("\(self.baseUrl)/user/\(user)/playlists", method: .get, parameters: nil, encoding: URLEncoding(boolEncoding: .numeric), headers: nil)
// trigger request
request.validate().responseJSON { response in
// check for successful connexion
switch response.result{
case .success:
guard let data = response.value as? DeezerObject else {
return }
// check if deezer server produces an error
if data["error"] != nil {
// send back response with error message
let response: DeezerResponse = (data,self.parseDeezerError(data: data))
observer(.success(response))
}
observer(.success((data,nil)))
// Return an error if no connection to the server
case .failure(let error):
observer(.error(error))
}
}
return Disposables.create {
request.cancel()
}
}
}
/// This method request all the tracks for a particular playlist
///
/// - Parameters:
/// - user: String Playlist id url fetched from resquestPlaylit()
/// - parameters: Parameters? used to implement different request such as post/deelete/patch
/// - Returns: Single<DeezerResponse> Observable that returns a tuple (data, internal error) on success
func requestTracks(for playlist: String, parameters: Parameters) -> Single<DeezerResponse> {
return Single<DeezerResponse>.create { observer in
// create request
let request = Alamofire.request(playlist, method: .get, parameters: nil, encoding: URLEncoding(boolEncoding: .numeric), headers: nil)
// trigger request
request.validate().responseJSON { response in
// properties to temp store the results to return
var objects = [DeezerObject]()
// check for successful connexion
switch response.result{
case .success:
guard let data = response.value as? [String: Any] else { return }
// check if deezer server produces an error
if data["error"] != nil {
// send back response with error message
let response: DeezerResponse = (data,self.parseDeezerError(data: data))
observer(.success(response))
}
if let json = data ["data"] as? [DeezerObject] {
objects = json
// attention array d object
observer(.success((objects,nil)))
}
case .failure(let error):
observer(.error(error))
}
}
return Disposables.create {
request.cancel()
}
}
}
/// Converts internal Server Errors to a error message string
///
/// - Parameter data: [String: Any] server response
/// - Returns: String Error message
func parseDeezerError(data: [String: Any]) -> String {
// property to temp store the result to return
var errorMessage: String!
// check the server data
if let serverResponse = data["error"] as? [String: Any] {
if let code = serverResponse["code"] as? Int {
// convert to error message string
errorMessage = DeezerErrors.checkErrorCode(code).localizedDescription
}
}
return errorMessage
}
}
|
///Users/berylxzhang/Documents/Dooro Learinng/Dooro Learinng/ViewController.swift
// ViewController.swift
// Dooro Learinng
//
// Created by Beryl Zhang on 6/18/21.
//
import UIKit
import MBProgressHUD
import Loaf
import Combine
import Firebase
import FirebaseAuth
import FBSDKLoginKit
import FBSDKCoreKit
import FBSDKShareKit
import GoogleSignIn
import SDWebImage
// Swift
//
// Add this to the header of your file, e.g. in ViewController.swift
// Add this to the body
class ViewController: UIViewController{
var googleSignIn = GIDSignIn.sharedInstance()
var userID: String?
@IBOutlet weak var Photo: UIImageView!
private let authManager = AuthManager()
private var subscriber: AnyCancellable?
@IBOutlet weak var facebookButton: UIButton!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var googleButton: UIButton!
// @IBOutlet weak var facebookButton: UIButton!
// @IBOutlet weak var facebook: UIButton!
@IBOutlet weak var signupButton: UIButton!
@IBOutlet weak var forgetpasswordButton: UIButton!
@IBOutlet weak var errorLabel: UILabel!
private let loginButton = FBLoginButton(frame: .zero, permissions: [.publicProfile])
private var errorMessage: String? {
didSet {
showErrorMessageIfNeeded(text: errorMessage)
}
}
var iconClick = false
let imageicon = UIImageView()
let facebookimageicon = UIImageView()
let googleimageicon = UIImageView()
//
@objc func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
imageicon.image = UIImage(systemName: "eye.slash")
let contentView = UIView()
contentView.addSubview(imageicon)
contentView.frame = CGRect(x: 0, y: 0, width: UIImage(systemName: "eye.slash")!.size.width, height: UIImage(systemName: "eye.slash")!.size.height)
imageicon.frame = CGRect(x: -10, y: 0, width: UIImage(systemName: "eye.slash")!.size.width, height: UIImage(systemName: "eye.slash")!.size.height)
passwordTextField.rightView = contentView
passwordTextField.rightViewMode = .always
facebookimageicon.image = UIImage(named: "facebook_logo.png")
let size = facebookimageicon.image?.size
let buttonheight = facebookButton.frame.height
let buttonwidth = facebookButton.frame.width
let imageWidth = facebookButton.imageView!.frame.width
facebookButton.imageEdgeInsets = UIEdgeInsets(top:4, left:4,bottom: 4, right: 4+buttonwidth-buttonheight)
facebookButton.setImage(facebookimageicon.image, for: .normal)
googleimageicon.image = UIImage(named: "google_logo.png")
googleButton.imageEdgeInsets = UIEdgeInsets(top:4, left:4,bottom: 4, right: 4+buttonwidth-buttonheight)
googleButton.setImage(googleimageicon.image, for: .normal)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
imageicon.isUserInteractionEnabled = true
imageicon.addGestureRecognizer(tapGestureRecognizer)
// loginButton.frame = CGRect(x: facebookLogin.frame.origin.x, y:facebookLogin.frame.origin.y + (passwordTextField.frame.origin.y - emailTextField.frame.origin.y - passwordTextField.frame.height) , width: facebookLogin.frame.width, height: facebookLogin.frame.height)
loginButton.permissions = ["public_profile", "email"]
loginButton.delegate = self
loginButton.isHidden = true
view.addSubview(loginButton)
// googleLoginButton.setImage(UIImage(named: "google_logo.png"), for: UIControl.State.Normal)
GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
GIDSignIn.sharedInstance().delegate = self
GIDSignIn.sharedInstance()?.presentingViewController = self
FacebookLogin()
GIDSignIn.sharedInstance()?.restorePreviousSignIn()
if(GIDSignIn.sharedInstance()?.currentUser != nil)
{
// print("logged in")
}
else
{
//not loggedIn
// print("nobody")
}
print(self.userID)
}
// Swift
@IBAction func tapGoogleLogin(_ sender: Any) {
GIDSignIn.sharedInstance().signIn()
}
@IBAction func tapFacebookLogin(_ sender: Any) {
loginButton.sendActions(for: .touchUpInside)
}
@IBAction func taplogin(_ sender: Any) {
view.endEditing(true)
guard let email = emailTextField.text,
!email.isEmpty,
let password = passwordTextField.text,
!password.isEmpty else {
showErrorMessageIfNeeded(text: "Invalid form")
return }
MBProgressHUD.showAdded(to: view, animated: true)
authManager.loginUser(withEmail: email, password: password) { [weak self] (result) in
guard let this = self else { return }
MBProgressHUD.hide(for: this.view, animated: true)
switch result {
case .success:
if let loginUser = Auth.auth().currentUser{
print("Current firebase user is")
print(loginUser)
self!.userID = loginUser.uid
print(loginUser.uid)
print(self!.userID!)
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "ChooseModeViewController") as! ChooseModeViewController
nextViewController.modalPresentationStyle = .fullScreen
nextViewController.userID = self?.userID
print( nextViewController.userID!)
self!.present(nextViewController, animated:true, completion:nil)}
case .failure(let error):
this.showErrorMessageIfNeeded(text: error.localizedDescription)
}
}
}
var userName: String?
var userPhoto: String?
var facebookToken: String?
var googleuserName: String?
var googleuserPhoto: String?
@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer){
let tappedImage = tapGestureRecognizer.view as! UIImageView
if iconClick{
iconClick = false
tappedImage.image = UIImage(systemName: "eye.slash")
passwordTextField.isSecureTextEntry = true
}
else{
iconClick = true
tappedImage.image = UIImage(systemName: "eye")
passwordTextField.isSecureTextEntry = false
}
}
@IBOutlet weak var login: UIButton!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
emailTextField.becomeFirstResponder()
}
private func observeTextFields() {
subscriber = NotificationCenter.default.publisher(for: UITextField.textDidChangeNotification).sink { [unowned self] (notification) in
guard let _ = (notification.object as? UITextField) else { return }
showErrorMessageIfNeeded(text: nil)
}
}
private func showErrorMessageIfNeeded(text: String?) {
errorLabel.isHidden = text == nil
errorLabel.text = text
}
func FacebookLogin() {
if let token = AccessToken.current,
!token.isExpired {
let token = token.tokenString
let request = FBSDKShareKit.GraphRequest(graphPath: "me",
parameters: ["fields":"email,name,picture,first_name"],
tokenString: token,
version: nil,
httpMethod: .get)
request.start(completionHandler: { connection, result,error in
print("\(result)")
let dict = result as! [String: AnyObject]
let profileDic = dict as NSDictionary
let first_name = profileDic.object(forKey: "first_name") as! String
let temURL1 = profileDic.object(forKey: "picture") as! NSDictionary
let temTRL2 = temURL1.object(forKey: "data") as! NSDictionary
let profileURL = temTRL2.object(forKey: "url") as! String
print(first_name)
print(profileURL)
self.userName = first_name
self.userPhoto = profileURL
self.facebookToken = token
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
print(token)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "facebookView") as! facebookViewController
nextViewController.userName = self.userName
nextViewController.userPhoto = self.userPhoto
nextViewController.facebookToken = self.facebookToken
nextViewController.modalPresentationStyle = .fullScreen
self.present(nextViewController, animated:false, completion:nil)
})
firebaseFacebooklogin(accessToken: token)
}
// loginButton.frame = CGRect(x: 0, y:0 , width: 5, height: 10)
}
func firebaseFacebooklogin(accessToken: String){
let credential = FacebookAuthProvider.credential(withAccessToken: accessToken )
Auth.auth().signIn(with: credential, completion: { ( authResult, error) in
if let error = error{
print("Firebase login Error")
print(error)
return
}
//User has signed
print("Firebase Login Done")
print(authResult)
if let user = Auth.auth().currentUser{
print("Current firebase user is")
print(user)
self.userID = user.uid
print(user.uid)
print(self.userID!)
// let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
//
// let signUpViewController = storyBoard.instantiateViewController(withIdentifier: "signUpViewController") as! signUpViewController
// signUpViewController.userID = self.userID!
//
// print(signUpViewController.userID! )
//
// let RecoveryViewController = storyBoard.instantiateViewController(withIdentifier: "RecoveryViewController") as! RecoveryViewController
// RecoveryViewController.userID = self.userID!
//
// let facebookViewController = storyBoard.instantiateViewController(withIdentifier: "facebookView") as! facebookViewController
// facebookViewController.userID = self.userID!
//
// let googleViewController = storyBoard.instantiateViewController(withIdentifier: "googleViewController") as! googleViewController
// googleViewController.userID = self.userID!
//
// let ChooseModeViewController = storyBoard.instantiateViewController(withIdentifier: "ChooseModeViewController") as! ChooseModeViewController
// ChooseModeViewController.userID = self.userID!
//
// print(ChooseModeViewController.userID! )
//
// let hangmanGameController = storyBoard.instantiateViewController(withIdentifier: "hangmanGameController") as! hangmanGameController
// hangmanGameController.userID = self.userID!
//
//
// let FlaskCardViewController = storyBoard.instantiateViewController(withIdentifier: "FlashCardView") as! FlaskCardViewController
// FlaskCardViewController.userID = self.userID!
//
// let winViewController = storyBoard.instantiateViewController(withIdentifier: "winViewController") as! winViewController
// winViewController.userID = self.userID!
//
// let looseViewController = storyBoard.instantiateViewController(withIdentifier: "looseViewController") as! looseViewController
// looseViewController.userID = self.userID!
//
// let AddWordViewController = storyBoard.instantiateViewController(withIdentifier: "AddWordViewController") as! AddWordViewController
// AddWordViewController.userID = self.userID!
//
// let explanViewController = storyBoard.instantiateViewController(withIdentifier: "explanViewController") as! explanViewController
// explanViewController.userID = self.userID!
//
// let hangmanAddViewController = storyBoard.instantiateViewController(withIdentifier: "hangmanAddViewController") as! hangmanAddViewController
// hangmanAddViewController.userID = self.userID!
}
})
}
}
extension ViewController: LoginButtonDelegate{
func loginButtonDidLogOut(_ loginButton: FBLoginButton) {
print("Logout")
}
func loginButton(_ loginButton: FBLoginButton, didCompleteWith result: LoginManagerLoginResult?, error: Error?) {
let token = result?.token?.tokenString
FacebookLogin()
}
}
//
extension ViewController: GIDSignInDelegate {func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let error = error{
print("\(error.localizedDescription)")
}else{
let userIdToken = user.authentication.idToken ?? ""
print("Google ID Token: \(userIdToken)")
let userFirstName = user.profile.givenName ?? ""
print("Google User First Name: \(userFirstName)")
let userLastName = user.profile.familyName ?? ""
print("Google User Last Name: \(userLastName)")
let userEmail = user.profile.email ?? ""
print("Google User Email: \(userEmail)")
let googleProfilePicURL = user.profile.imageURL(withDimension: 150)?.absoluteString ?? ""
print("Google Profile Avatar URL: \(googleProfilePicURL)")
self.googleuserName = userFirstName
self.googleuserPhoto = googleProfilePicURL
guard let authentication = user.authentication else { return }
let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
accessToken: authentication.accessToken)
Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in
if let error = error{
print("Firebase sign in error")
print(error)
return
} else{
print("User is signed in with firebase")
}
if let googleUser = Auth.auth().currentUser{
print("Current firebase user is")
print(googleUser)
self.userID = googleUser.uid
print(googleUser.uid)
print(self.userID!)
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "googleViewController") as! googleViewController
nextViewController.userName = self.googleuserName
nextViewController.userPhoto = self.googleuserPhoto
nextViewController.userID = self.userID
print( nextViewController.userID!)
nextViewController.modalPresentationStyle = .fullScreen
self.present(nextViewController, animated:true, completion:nil)
}
}
}
}
}
|
//
// ViewController.swift
// TmpTestCGAffine
//
// Created by 김종권 on 2020/05/01.
// Copyright © 2020 mustang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var btn: UIButton!
var vc: ViewController2!
var width: CGFloat!
var isOpen: Bool!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .yellow
isOpen = false
btn = UIButton()
btn.setTitle("slide btn", for: .normal)
btn.backgroundColor = .black
btn.frame = CGRect(x: 50, y: 30, width: 100, height: 30)
view.addSubview(btn)
vc = ViewController2()
vc.view.backgroundColor = .blue
width = view.frame.width
let height = view.frame.height
vc.view.frame = CGRect(x: -width, y: 0, width: width, height: height)
view.addSubview(vc.view)
btn.addTarget(self, action: #selector(toggle(_:)), for: .touchUpInside)
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
view.addGestureRecognizer(panGesture)
}
@objc func handlePan(gesture : UIPanGestureRecognizer){
let translation = gesture.translation(in: view)
print(translation) // translation은 드래그 이동거리를 의미(0에서 시작)
let slideWidth:CGFloat = 50
if gesture.state == .changed {
var x = translation.x
if isOpen {
x += slideWidth
}
x = min(slideWidth , x)
x = max(0 , x)
vc.view.transform = CGAffineTransform(translationX: x, y: 0)
view.transform = CGAffineTransform(translationX: x, y: 0)
} else if gesture.state == .ended {
if isOpen {
if abs(translation.x) > slideWidth / 2 {
isOpen = false // 사이드바가 현재 닫혀 있으니, 열으라는 조건
}
toggle()
} else {
if translation.x < slideWidth / 2 {
isOpen = true // 사이드바가 현재 열려 있으니, 닫으라는 조건
}
toggle()
}
}
}
@objc func toggle(_ sender: Any) {
self.toggle()
}
func toggle() {
if isOpen == false {
isOpen = true
view.transform = CGAffineTransform(translationX: 50, y: 0)
vc.view.transform = CGAffineTransform(translationX: 50, y: 0)
} else {
isOpen = false
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
self.view.transform = .identity
self.vc.view.transform = .identity
}, completion: nil)
}
}
}
|
//
// CourseTableViewController.swift
// Binder
//
// Created by Christina Depena on 4/15/18.
// Copyright © 2018 The University of Texas at Austin. All rights reserved.
//
import UIKit
class CourseTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return loadCourseTableView().count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let person = DataStore.shared.getIndexOfUserLoggedIn()
let cell = tableView.dequeueReusableCell(withIdentifier: "courseCell", for: indexPath)
let myCourseList = loadCourseTableView()
// Configure the cell...
let course = myCourseList[indexPath.row]
cell.textLabel?.text = course.courseName
let grade = calculateCourseGrade(course: myCourseList[indexPath.row], person: person)
cell.detailTextLabel?.text = String(grade)
return cell
}
func loadCourseTableView() -> [Courses] {
// Initialize return array
var returnArray:[Courses] = []
// Obtain the user first
let currentUser = DataStore.shared.getIndexOfUserLoggedIn()
// Initialize two booleans
var areThereCourses:Bool = true
var firstTimeUser:Bool = false
// Check to see if there are any courses at all
let courseCount = DataStore.shared.countOfCourses()
if courseCount == 0 {
areThereCourses = false
return returnArray
}
// Check to see if the user is enrolled in any courses
let peopleInCoursesCount = DataStore.shared.countOfPeopleInCourses()
var userCourseIDs:[Int] = []
for i in 0...(peopleInCoursesCount - 1){
let peopleInCoursesObject = DataStore.shared.getPeopleInCourses(index: i)
if peopleInCoursesObject.personID == currentUser {
userCourseIDs.append(peopleInCoursesObject.courseID)
}
}
if userCourseIDs.count == 0 {
firstTimeUser = true
return returnArray
}
// Now populate userCourse Names list which is the returnArray
if firstTimeUser == false && areThereCourses == true {
for i in 0...(userCourseIDs.count - 1){
for j in (0...courseCount - 1){
let course = DataStore.shared.getCourse(index: j)
if userCourseIDs[i] == course.courseID{
returnArray.append(course)
}
}
}
}
return returnArray
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
func retrieveAssignments(course:Courses, person:Int) -> [Assignments] {
var returnArray: [Assignments] = []
// Handle the case the case for a newly enrolled user in a class/the very first user
// Get a count of total assignments
let assignmentCount = DataStore.shared.countOfAssignments()
if assignmentCount == 0 {
return returnArray
}
// Loop through to try and add assignments that match the course and the user
for i in (0...assignmentCount - 1){
let assignment = DataStore.shared.getAssignment(index: i)
if assignment.courseID == course.courseID && assignment.personID == person{
returnArray.append(assignment)
}
}
return returnArray
}
func calculateCourseGrade(course: Courses, person:Int) -> Float {
// Count the number of categories in a course
let catCount = DataStore.shared.countOfCourseCategoryBreakdowns()
// Handle the case that this is the first user and they did not add any categories
if catCount == 0{
return 0
}
let peopleInCoursesCount = DataStore.shared.countOfPeopleInCourses()
var peopleInCoursesIDList:[Int] = []
var courseCats:[CourseCategoryBreakdown] = []
// Obtain the appropriate pks
for i in (0...peopleInCoursesCount - 1){
let peopleInCoursesObject = DataStore.shared.getPeopleInCourses(index: i)
if course.courseID == peopleInCoursesObject.courseID && person == peopleInCoursesObject.personID{
peopleInCoursesIDList.append(peopleInCoursesObject.pk)
}
}
// See if there are any matching current categories
for i in (0...peopleInCoursesIDList.count - 1){
for j in (0...catCount - 1){
let currentCat = DataStore.shared.getCourseCategoryBreakdown(index: j)
if peopleInCoursesIDList[i] == currentCat.peopleInCoursesID{
courseCats.append(currentCat)
}
}
}
// Handle the case that the user has not added categories for the course yet
if courseCats.count == 0 {
return 0
}
// Pull the assignments for that user/that course
let yourAssignments = retrieveAssignments(course: course, person: person)
// Handle the case that the user has not added assignments for the course
if yourAssignments.count == 0{
return 0
}
// Otherwise begin grade calculation
var finalGrade: Float = 0
var percentageDenom: Float = 0
for i in (0...courseCats.count - 1){
var assignmentGradeByType:Float = 0
var countOfAssignmentsByType:Float = 0
percentageDenom += Float(courseCats[i].percentOfFinalGradeOfCategory)
for j in (0...yourAssignments.count - 1){
if courseCats[i].category == yourAssignments[j].assignmentType{
countOfAssignmentsByType += 1
assignmentGradeByType += Float(yourAssignments[j].assignmentGrade)
}
}
if countOfAssignmentsByType == 0 {
percentageDenom -= Float(courseCats[i].percentOfFinalGradeOfCategory)
}
if percentageDenom == 0 {
continue
} else {
assignmentGradeByType = Float(assignmentGradeByType/countOfAssignmentsByType)
finalGrade += Float(assignmentGradeByType) * (courseCats[i].percentOfFinalGradeOfCategory/100)
}
}
finalGrade = finalGrade/percentageDenom * (100)
return finalGrade
}
// 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.
// Reload the courselist and pass the course to the Assignment Table VC
let myCourseList = loadCourseTableView()
if let destinationVC = segue.destination as? AssignmentTableViewController,
let selectedIndexPath = tableView.indexPathForSelectedRow {
destinationVC.selectedCourse = myCourseList[selectedIndexPath.row]
print(destinationVC.selectedCourse!.courseAbbreviation)
}
}
}
|
//
// TrackViewModel.swift
// Saturdays
//
// Created by Said Ozcan on 13/06/2017.
// Copyright © 2017 Said Ozcan. All rights reserved.
//
import UIKit
class TrackViewModel : NSObject, ViewModelProtocol {
// MARK : Properties
let trackName : String
let artistName : String
let albumArtUrl : URL
let albumArtSize: CGSize?
let deeplinkURL : URL
// MARK : Lifecycle
init(with track:Track) {
self.trackName = track.name
self.artistName = track.artist
self.albumArtUrl = track.albumArt.url
self.albumArtSize = track.albumArt.size
self.deeplinkURL = track.externalURL
super.init()
}
}
|
//
// Venue.swift
// FourCubed
//
// Created by Pritesh Nadiadhara on 2/8/19.
// Copyright © 2019 Pritesh Nadiadhara. All rights reserved.
//
import Foundation
import CoreLocation
struct VenueData: Codable {
let response: Venues
}
struct Venues: Codable {
let venues: [Venue]
}
struct Venue: Codable {
let id: String
let name: String
let location : LocationData?
var categories : [CatagoryData]
// let delivery : DeliveryInfo?
}
struct LocationData : Codable {
let address : String?
let crossStreet : String?
let lat : Double
let lng : Double
let distance : Int
let postalCode : String?
let city : String
let state : String
let country : String
let formattedAddress : [String]
let venuePage : [VenueId]?
public var coordinate: CLLocationCoordinate2D {
return CLLocationCoordinate2DMake(lat, lng)
}
}
struct CatagoryData : Codable {
let name : String
}
struct VenueId : Codable {
let id : String
}
struct DeliveryInfo : Codable {
let url : String // this links to a food menue
let provider : ProviderInfo
}
struct ProviderInfo : Codable {
let name: String
let icon : IconInfo
}
struct IconInfo : Codable {
let prefix : String
let sizes : [Int]
let name : String
}
|
//
// ContactViewController.swift
// LyonsDen
//
// The ContactViewContrller will be used for controlling the contact screen.
//
// Created by Inal Gotov on 2016-06-30.
// Copyright © 2016 William Lyon Mackenize CI. All rights reserved.
//
import UIKit
import FirebaseDatabase
import MessageUI
import Contacts
class ContactViewController: UIViewController, MFMailComposeViewControllerDelegate {
static var displayToast = false
@IBOutlet weak var menuButton: UIBarButtonItem!
@IBOutlet var navBar: UINavigationItem!
var toast:ToastView!
@IBOutlet var buttons: [UIButton]!
override func viewDidLoad() {
super.viewDidLoad()
// Make sidemenu swipeable
if self.revealViewController() != nil {
menuButton.target = self.revealViewController()
menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
let titles = ["Propose\nAnnoun-\ncement", "Contact a\nTeacher", "Secret\nComing\nSoon!", "Emergency\nHotline"]
for h in 0..<buttons.count {
buttons[h].setTitle(titles[h], for: .normal)
buttons[h].titleLabel?.numberOfLines = 0
buttons[h].titleLabel?.lineBreakMode = NSLineBreakMode.byCharWrapping
buttons[h].titleLabel?.textAlignment = NSTextAlignment.center
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if ContactViewController.displayToast {
toast = ToastView(inView: self.view, withText: "Proposal Submitted!")
self.view.addSubview(toast)
ContactViewController.displayToast = false
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let toastView = toast {
toastView.initiate()
}
}
@IBAction func displayTeacherList(_ sender: UIButton) {
PeopleList.listRef = FIRDatabase.database().reference(withPath: "users").child("teachers")
PeopleList.title = "Teachers"
performSegue(withIdentifier: "TeacherListSegue", sender: self)
}
// This is required for a successful unwind to this View Controller
// It just needs to be present, so don't mind it at all
@IBAction func myUnwindAction (_ unwindSegue: UIStoryboardSegue) {
}
// This is called whenever people get too curious
@IBAction func curiosityWon(_ sender: UIButton) {
let anim = CAKeyframeAnimation( keyPath:"transform" )
anim.values = [NSValue(caTransform3D:CATransform3DMakeTranslation(-5, 0, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(5, 0, 0))]
anim.autoreverses = true
anim.repeatCount = 2
anim.duration = 7/100
for view in self.view.subviews {
view.layer.add(anim, forKey: nil)
}
}
@IBAction func hotlineSelected(_ sender: AnyObject) {
let title = "Emergency Hotline"
let subTitle = "Who would you like to talk to?"
let options = UIAlertController(title: title, message: subTitle, preferredStyle: .actionSheet)
// MARK: VISUAL COSTUMIZATIONS
options.setValue(NSAttributedString(string: title, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 17), NSForegroundColorAttributeName : colorAccent]), forKey: "attributedTitle")
options.setValue(NSAttributedString(string: subTitle, attributes: [NSFontAttributeName : UIFont.systemFont(ofSize: 14), NSForegroundColorAttributeName : colorAccent]), forKey: "attributedMessage")
options.view.tintColor = colorAccent
options.addAction(UIAlertAction(title: "Student Emergency Hotline", style: .default, handler: { action in
self.phoneCall(URL(string: "telprompt://1-800-668-6868")!) // kids help phone
}))
options.addAction(UIAlertAction(title: "Emergency Contact", style: .default, handler: { action in
// for now
self.phoneCall(URL(string: "telprompt://647-300-9301")!) // rachels
})) // set emergency contact from contacts in phone. save to NSDefaults. figure out how
options.addAction(UIAlertAction(title: "WLMCI", style: .default, handler: { action in
self.phoneCall(URL(string: "telprompt://416-395-3330")!) // school's phone
}))
options.addAction(UIAlertAction(title: "911", style: .default, handler: { action in
self.phoneCall(URL(string: "telprompt://911")!) // obvious
}))
options.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(options, animated: true, completion: nil)
}
@IBAction func reportBug(_ sender: UIButton) {
// if MFMailComposeViewController.canSendMail() { // We shall send mail
let composeVC = MFMailComposeViewController()
let mVC = MFMailComposeViewController(navigationBarClass: nil, toolbarClass: nil)
// composeVC.mailComposeDelegate = self
// Configure fields
// composeVC.setToRecipients(["TheLyonsKeeper@gmail.com"])
// composeVC.setSubject("Hey Keeper, I found a bug!")
// composeVC.setMessageBody("Before the bug occured I did this:", isHTML: false)
// Present VC modally
self.present(mVC, animated: true, completion: nil)
// } else { // We shan't send mail
// print ("Mail services not available on this device")
// // Present a LyonsAlert notifying the user that he cannot send mail on this device
// let alert = LyonsAlert(withTitle: "Mail Services Unavailable!", subtitle: "Unfortunately there are no mail services enabled on this device. Please enable mail service and try again.", style: .alert)
// alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil))
// alert.showIn(self)
// }
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
var toastMessage = "Report "
if result == MFMailComposeResult.sent {
toastMessage += "Sent!"
} else if result == MFMailComposeResult.failed {
toastMessage += "Failed to Send!"
} else if result == MFMailComposeResult.cancelled {
toastMessage += "Cancelled"
}
if let mailError = error {
print ("Bug Reporting Error!")
print (mailError.localizedDescription)
}
let toast = ToastView(inView: self.view, withText: toastMessage)
self.view.addSubview(toast)
// Dismiss the mail VC
controller.dismiss(animated: true) {
toast.initiate()
}
}
fileprivate func phoneCall (_ phoneNumber: URL) {
if UIApplication.shared.canOpenURL(phoneNumber) {
UIApplication.shared.openURL(phoneNumber)
}
}
}
|
//
// AddLabelsViewController.swift
// Fugu
//
// Created by Divyansh Bhardwaj on 16/03/18.
// Copyright © 2018 Socomo Technologies Private Limited. All rights reserved.
//
import UIKit
protocol AddLabelProtocol: class {
func addLabelAction(tagsArray: [TagDetail])
func cancelAction()
}
class AddLabelsViewController: UIViewController {
@IBOutlet weak var searchBarHeightConstraints: NSLayoutConstraint!
@IBOutlet weak var labelsTableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var addLabelsButton: UIButton!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var plusButton: UIBarButtonItem!
@IBOutlet weak var backItem: UIBarButtonItem!
weak var delegate: AddLabelProtocol?
var channelId: Int?
var titleSearchBar = UISearchBar()
var lastActiveStatus = [TagDetail]()
var alterTags: [TagDetail] = []
var filteredTags = [TagDetail]()
var allTags = [TagDetail]()
override func viewDidLoad() {
super.viewDidLoad()
self.setUpAddLablesScreen()
if #available(iOS 13.0, *) {
self.overrideUserInterfaceStyle = .light
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
fuguDelay(0.0) {
self.navigationController?.setNavigationBarHidden(false, animated: false)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.searchBar.resignFirstResponder()
self.titleSearchBar.resignFirstResponder()
self.navigationController?.isNavigationBarHidden = true
}
// MARK: Add labels action
@IBAction func addLabelsAction(_ sender: UIButton) {
self.searchBar.resignFirstResponder()
updateChannelTags { (success) in
guard success else {
return
}
self.delegate?.addLabelAction(tagsArray: self.lastActiveStatus)
self.navigationController?.popViewController(animated: true)
}
}
// MARK: Create labels action
@IBAction func createLabelsAction(_ sender: UIBarButtonItem) {
self.searchBar.resignFirstResponder()
pushToCreateLabel()
}
// MARK: Cancel button
@IBAction func cancelsAction(_ sender: UIButton) {
self.searchBar.resignFirstResponder()
self.delegate?.addLabelAction(tagsArray: self.lastActiveStatus)
self.navigationController?.popViewController(animated: true)
}
// MARK: Cancel button
@IBAction func backAction(_ sender: UIButton) {
self.searchBar.resignFirstResponder()
self.delegate?.addLabelAction(tagsArray: self.lastActiveStatus)
self.navigationController?.popViewController(animated: true)
}
//Class methods
class func get(channelId: Int, existingTags: [TagDetail]) -> AddLabelsViewController {
let storyboard = UIStoryboard(name: "AgentSdk", bundle: FuguFlowManager.bundle)
let vc = storyboard.instantiateViewController(withIdentifier: "AddLabelsViewController") as! AddLabelsViewController
vc.channelId = channelId
vc.lastActiveStatus = existingTags
return vc
}
func setTheme() {
view.backgroundColor = HippoConfig.shared.theme.backgroundColor
}
}
extension AddLabelsViewController {
func pushToCreateLabel() {
let vc = CreateLabelViewController.get()
vc.delegate = self
self.navigationController?.pushViewController(vc, animated: true)
}
func setUpAddLablesScreen() {
registerCell()
DispatchQueue.main.async {
self.getAllTags(sortList: true)
}
setupNavigationBar()
self.setUpSearchBar()
addLabelsButton.backgroundColor = HippoConfig.shared.theme.themeColor
addLabelsButton.setTitleColor(HippoConfig.shared.theme.backgroundColor, for: .normal)
setTheme()
}
func registerCell() {
labelsTableView.register(UINib(nibName: "CustomerTagsTableViewCell", bundle: FuguFlowManager.bundle), forCellReuseIdentifier: "CustomerTagsTableViewCell")
}
func setupNavigationBar() {
backItem.tintColor = HippoConfig.shared.theme.headerTextColor
plusButton.tintColor = HippoConfig.shared.theme.headerTextColor
self.setNavBar(with: "Add Labels")
}
func setUpSearchBar() {
searchBar.sizeToFit()
searchBar.placeholder = "Search Label"
searchBar.barTintColor = UIColor.white
searchBar.returnKeyType = .done
searchBar.delegate = self
searchBar.tintColor = UIColor.white
searchBar.backgroundColor = UIColor.white
searchBar.backgroundImage = UIImage()
titleSearchBar.sizeToFit()
titleSearchBar.placeholder = "Search Label"
titleSearchBar.barTintColor = UIColor.white
titleSearchBar.returnKeyType = .done
titleSearchBar.delegate = self
titleSearchBar.frame = searchBar.frame
}
func getAllTags(sortList: Bool = false) {
if CacheManager.getStoredTagDetail().isEmpty{
ChatInfoManager.sharedInstance.getAllTags(showLoader: false, sortList: sortList, exsitingTagsArray: self.lastActiveStatus) { (result) in
guard let tags = result else {
return
}
self.filteredTags = tags
self.allTags = self.filteredTags
CacheManager.storeTags(tags: tags.clone())
Business.shared.tags = tags.clone()
self.labelsTableView.reloadData()
}
}else{
let tagsArray = TagDetail.parseTagDetailWithSelected(data: CacheManager.getStoredTagDetail().clone().getJsonToStore(), sortList: false, existingTagsArray: self.lastActiveStatus)
self.filteredTags = tagsArray
self.allTags = self.filteredTags
self.labelsTableView.reloadData()
}
}
func filterTagsForStore() {
for each in alterTags {
let index = lastActiveStatus.firstIndex { (t) -> Bool in
return t.tagId == each.tagId
}
if let parsedIndex = index, !each.isSelected {
lastActiveStatus.remove(at: parsedIndex)
} else if each.isSelected {
lastActiveStatus.append(each)
}
}
}
}
extension AddLabelsViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
self.filterLabels(searchString: searchText.lowercased())
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
return true
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
}
func filterLabels(searchString: String) {
if searchString.isEmpty {
filteredTags = allTags
self.labelsTableView.reloadData()
return
}
let tempArr = allTags.filter { (c) -> Bool in
let tagName = (c.tagName ?? "").lowercased()
return tagName.contains(searchString)
}
filteredTags = tempArr
self.labelsTableView.reloadData()
}
}
extension AddLabelsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.filteredTags.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "CustomerTagsTableViewCell", for: indexPath) as? CustomerTagsTableViewCell else {
return UITableViewCell()
}
return cell.configureCustomerCell(resetProperties: false, tagsDetail: self.filteredTags[indexPath.row])
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let tag = filteredTags[indexPath.row]
handleSelectionOf(tag: tag)
tag.isSelected = !tag.isSelected
self.labelsTableView.reloadRows(at: [indexPath], with: .none)
}
func handleSelectionOf(tag: TagDetail) {
let lastAlertedTagIndex = alterTags.firstIndex { (t) -> Bool in
return t.tagId == tag.tagId
}
if let parsedIndex = lastAlertedTagIndex {
alterTags.remove(at: parsedIndex)
} else {
alterTags.append(tag)
}
}
}
extension AddLabelsViewController: CreateLabelDelegate {
func createnewLabel(tagDetail: TagDetail, use: Bool) {
self.allTags.append(tagDetail)
CacheManager.storeTags(tags: allTags)
Business.shared.tags = allTags.clone()
self.filterLabels(searchString: searchBar?.text ?? "")
if use {
handleSelectionOf(tag: tagDetail)
tagDetail.isSelected = true
}
self.labelsTableView.reloadData()
}
}
extension AddLabelsViewController {
func useNewCreatedLabel(tagDetail: TagDetail, appendToExisting: Bool = true, updateSortedData: Bool) {
guard let status = tagDetail.status, let channelId = channelId, let tag_id = tagDetail.tagId else {
return
}
let param = ["tag_id": tag_id,
"status": status,
"channel_id": channelId]
if appendToExisting {
self.lastActiveStatus.append(tagDetail)
}
ChatInfoManager.sharedInstance.useCreatedTag(showLoader: false, param: param) {[weak self] (result) in
guard result != nil, self != nil else {
return
}
if updateSortedData {
self?.getAllTags()
}
}
}
func updateChannelTags(completion: @escaping ((_ success: Bool) -> ())) {
guard let channelId = channelId else {
completion(false)
return
}
guard !alterTags.isEmpty else {
completion(true)
return
}
let request = ChatInfoManager.UpdateChannelTagRequest(tags: alterTags, channelId: channelId, enableLoader: true)
ChatInfoManager.sharedInstance.updateChannelTags(request: request) {[weak self] (success) in
self?.filterTagsForStore()
completion(success)
}
}
}
extension UIViewController{
func setNavBar(with title: String){
let value: [NSAttributedString.Key : Any] = [NSAttributedString.Key.foregroundColor: HippoConfig.shared.theme.headerTextColor,
NSAttributedString.Key.font: HippoConfig.shared.theme.headerTextFont ?? UIFont()]
navigationItem.title = title
navigationItem.hidesBackButton = true
navigationController?.view.backgroundColor = .white
navigationController?.navigationBar.barStyle = .default
navigationController?.navigationBar.isTranslucent = false
navigationController?.navigationBar.titleTextAttributes = value
if #available(iOS 15, *) {
let appearance = UINavigationBarAppearance()
appearance.configureWithOpaqueBackground()
appearance.backgroundColor = .white
appearance.titleTextAttributes = value
appearance.shadowImage = UIColor.black.withAlphaComponent(0.3).as1ptImage()
navigationController?.navigationBar.standardAppearance = appearance
navigationController?.navigationBar.scrollEdgeAppearance = appearance
}
}
}
extension UIColor {
/// Converts this `UIColor` instance to a 1x1 `UIImage` instance and returns it.
///
/// - Returns: `self` as a 1x1 `UIImage`.
func as1ptImage() -> UIImage {
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
setFill()
UIGraphicsGetCurrentContext()?.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
UIGraphicsEndImageContext()
return image
}
}
|
//
// CalculatorTests.swift
// CalculatorTests
//
// Created by Mikhail Ladutska
import XCTest
@testable import Calculator
class CalculatorTests: XCTestCase {
func testFactorial() {
let sut = ViewController()
let value = 5
let factorialValue = sut.factorial(value)
XCTAssertEqual(factorialValue, 120)
}
func testSqrt() {
let sut = ViewController()
let value: Float = 100
let sqrtValue = sut.findSqrt(number: value)
XCTAssertEqual(sqrtValue, 10)
}
}
|
//
// recipe.swift
// restaurantlist
//
// Created by Grazietta Hof on 2017-04-02.
// Copyright © 2017 Grazietta Hof. All rights reserved.
//
import UIKit
class recipe: NSObject {
var Name: String = ""
var ID: Double = 0
var Count: Double = 0
var accuracy: Double = 0
init(Name: String, ID: Double,Count: Double, accuracy: Double ){
self.Name = Name
self.ID = ID
self.Count = Count
self.accuracy = accuracy
}
override init() {
self.Name = ""
self.ID = 0
self.Count = 0
self.accuracy = 0
}
}
|
//
// AlamofireRouterProtocol.swift
// ios_mvvm
//
// Created by prongbang on 28/7/2561 BE.
// Copyright © 2561 prongbang. All rights reserved.
//
import Alamofire
public protocol AlamofireRouterProtocol: URLRequestConvertible {
var baseURLString: String { get }
var path: String { get }
var method: Alamofire.HTTPMethod { get }
var headers: [String: String]? { get }
var parameters: [String: Any]? { get }
var rawBody: NSData { get }
}
|
//
// LeagueVC.swift
// Swoosh
//
// Created by Zubieta on 10/3/20.
// Copyright © 2020 zubie7a. All rights reserved.
//
import UIKit
class LeagueVC: UIViewController {
@IBOutlet weak var nextButton: BorderButton!
@IBOutlet weak var mensButton: BorderButton!
@IBOutlet weak var womensButton: BorderButton!
@IBOutlet weak var coedsButton: BorderButton!
// Implicitly unwrapped optional. We don't want this code
// to even run unless there's a player.
var player : Player!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationController?.setNavigationBarHidden(true, animated: false)
// Disable the button by default, can't press unless
// some of the previous options is selected.
nextButton.isEnabled = false
// Initialize the struct.
player = Player()
}
override var prefersStatusBarHidden: Bool {
return true
}
func setDesiredLeague(_ league : String) {
player.desiredLeague = league
nextButton.isEnabled = true
// So we can highlight with a different color the last
// selected button and also "greenlighting" next button.
switch league {
case "mens":
mensButton.layer.borderColor = UIColor.red.cgColor
womensButton.layer.borderColor = UIColor.white.cgColor
coedsButton.layer.borderColor = UIColor.white.cgColor
nextButton.layer.borderColor = UIColor.green.cgColor
case "womens":
mensButton.layer.borderColor = UIColor.white.cgColor
womensButton.layer.borderColor = UIColor.red.cgColor
coedsButton.layer.borderColor = UIColor.white.cgColor
nextButton.layer.borderColor = UIColor.green.cgColor
case "coeds":
mensButton.layer.borderColor = UIColor.white.cgColor
womensButton.layer.borderColor = UIColor.white.cgColor
coedsButton.layer.borderColor = UIColor.red.cgColor
nextButton.layer.borderColor = UIColor.green.cgColor
default:
nextButton.isEnabled = false
}
}
@IBAction func onMensTapped(_ sender: Any) {
setDesiredLeague("mens")
}
@IBAction func onWomensTapped(_ sender: Any) {
setDesiredLeague("womens")
}
@IBAction func onCoedsTapped(_ sender: Any) {
setDesiredLeague("coeds")
}
@IBAction func onNextTapped(_ sender: Any) {
// Programatical segues are good when you want to have
// logic for what to transition next, which interface
// builder doesn't allow to do programatically. In fact
// many companies also dislike interface builder because
// it's not possible to debug because it has no break
// points, so they'd rather do everything in code.
performSegue(withIdentifier: "skillVCSegue", sender: self)
// A segue has to be created in IB, but only from VC to
// VC, not from Button to VC, which means that anything
// in the first VC can trigger it as long as it happens
// from the code.
}
// This function was linked by dragging the "Back" button on the
// second storyboard to the "Exit" icon of that ViewController,
// then this function (which had to be defined previously) will
// appear to be linked!
@IBAction func unwindFromSkillVC(unwindSegue: UIStoryboardSegue) {
// The function name doesn't matter, the parameter name also,
// the only thing that matters is the type (UIStoryboardSegue)
// and it will automatically know it has to go back to the
// view of this controller.
}
// Whenever moving data around view controllers, ALWAYS put it in
// a struct or a class, never pass around multiple variables between
// view controllers. Send it like a package!
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// It will try and run this statement. If it fails, the
// if statement will fail. The failure can happen in "as?"
// `destination` is a generic ViewController, but we can
// "downcast" it to the children type and see if it works.
if let skillVC = segue.destination as? SkillVC {
skillVC.player = player
}
// `prepare(for segue` will always always ALWAYS A L W A Y S
// be called before `viewDidLoad` on the destination VC so that
// all the necessary data will be there when the segue happens.
}
}
|
//
// UCollectionViewSectionBackgroundLayout.swift
// Cartoon
//
// Created by apple on 2018/11/2.
// Copyright © 2018年 hzbojin. All rights reserved.
//
/*给UICollectionView里的Section分别设置不同的背景颜色:
(1)继承UICollectionReusableView来自定义一个装饰视图(Decoration视图),用来作为各个分组的背景视图
(2)继承UICollectionViewLayoutAttributes来自定义一个新的布局属性,里面添加一个backgroundColor属性,用来表示Section的背景颜色
(3)继承UICollectionViewFlowLayout来自定义一个新布局,在这里计算及返回各个分组背景视图的布局属性(位置、尺寸、颜色等)
(4)新增一个协议方法,使得section背景色可以在外面通过数据源来设置
*/
import UIKit
private let SectionBackground = "UCollectionReusableView"
//增加自己的协议方法,使其可以像cell那样根据数据源来设置section背景色
protocol UCollectionViewSectionBackgroundLayoutDelegateLayout: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
backgroundColorForSectionAt section: Int) -> UIColor
}
//协议扩展:通过扩展提供方法的实现,这样就无需在每个遵循协议的类型中重复同样的实现,会自动获得这个扩展所增加的方法实现
extension UCollectionViewSectionBackgroundLayoutDelegateLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
backgroundColorForSectionAt section: Int) -> UIColor {
return collectionView.backgroundColor ?? UIColor.clear
}
}
//定义一个UICollectionViewLayoutAttributes子类作为section背景的布局属性
private class UCollectionViewLayoutAttributes: UICollectionViewLayoutAttributes {
//默认背景色
var backgroundColor = UIColor.white
//由于layout attributes对象可能会被collection view复制,所以layout attributes对象应该遵循NSCoping协议,并实现copyWithZone:方法,否则我们获取的自定义属性会一直是空值
override func copy(with zone: NSZone? = nil) -> Any {
let copy = super.copy(with: zone) as! UCollectionViewLayoutAttributes
copy.backgroundColor = self.backgroundColor
return copy
}
//如果UICollectionViewLayoutAttributes的属性值没有改变,collection view不会应用layout attributes,这些layout attributes的是否改变由isEqual:的返回值来决定,所以必须实现isEqual:方法来比较自定义属性
override func isEqual(_ object: Any?) -> Bool {
guard let rhs = object as? UCollectionViewLayoutAttributes else { return false }
if !self.backgroundColor.isEqual(rhs.backgroundColor) {
return false
}
return super.isEqual(object)
}
}
//继承UICollectionReusableView来自定义一个装饰视图,用于作为section背景
private class UCollectionReusableView: UICollectionReusableView {
//通过apply方法让自定义属性生效
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
super.apply(layoutAttributes)
guard let attr = layoutAttributes as? UCollectionViewLayoutAttributes else { return }
self.backgroundColor = attr.backgroundColor
}
}
//自定义布局
class UCollectionViewSectionBackgroundLayout: UICollectionViewFlowLayout {
//保存所有自定义的section背景的布局属性
private var decorationViewAttrs: [UICollectionViewLayoutAttributes] = []
override init() {
super.init()
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
setup()
}
private func setup() {
//注册自定义用来作为Section背景的装饰视图DecorationView
self.register(UCollectionReusableView.classForCoder(), forDecorationViewOfKind: SectionBackground)
}
override func prepare() {
super.prepare()
//若当前没有分区则返回
guard let numberOfSections = self.collectionView?.numberOfSections else { return }
//若未实现代理则返回
guard let delegate = self.collectionView?.delegate as? UCollectionViewSectionBackgroundLayoutDelegateLayout else { return }
//先删除原来的section背景的布局属性
self.decorationViewAttrs.removeAll()
//分别计算每个section背景的布局属性
for section in 0..<numberOfSections {
let indexPath = IndexPath(item: 0, section: section)
//获取该section下第一个和最后一个item的布局属性
guard let numberOfItems = self.collectionView?.numberOfItems(inSection: section),
numberOfItems > 0,
let firstItemAttr = self.layoutAttributesForItem(at: indexPath),
let lastItemAttr = self.layoutAttributesForItem(at: IndexPath(item: numberOfItems - 1, section: section))
else {
continue
}
//获取该section的内边距
var sectionInset = self.sectionInset //UICollectionViewFlowLayout设置
if let delegateInset = delegate.collectionView?(self.collectionView!, layout: self, insetForSectionAt: section) { //代理设置
sectionInset = delegateInset
}
//获取组头组尾的布局
let headLayout = layoutAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, at: indexPath)
let footLayout = layoutAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, at: indexPath)
//计算该section实际的位置
var sectionFrame = firstItemAttr.frame.union(lastItemAttr.frame)
sectionFrame.origin.x = sectionInset.left
sectionFrame.origin.y -= sectionInset.top
//计算该section实际的尺寸
if self.scrollDirection == .horizontal {
sectionFrame.origin.y -= headLayout?.frame.height ?? 0
sectionFrame.size.width += sectionInset.left + sectionInset.right
sectionFrame.size.height = (collectionView?.frame.height ?? 0) + (headLayout?.frame.height ?? 0) + (footLayout?.frame.height ?? 0)
} else {
sectionFrame.origin.y -= headLayout?.frame.height ?? 0
sectionFrame.size.width = collectionView?.frame.width ?? 0
sectionFrame.size.height = sectionFrame.size.height + sectionInset.top + sectionInset.bottom + (headLayout?.frame.height ?? 0) + (footLayout?.frame.height ?? 0)
}
//根据上面的结果计算section背景的布局属性
let attr = UCollectionViewLayoutAttributes(forDecorationViewOfKind: SectionBackground, with: IndexPath(item: 0, section: section))
attr.frame = sectionFrame
attr.zIndex = -1
//通过代理方法获取该section背景使用的颜色
attr.backgroundColor = delegate.collectionView(self.collectionView!, layout: self, backgroundColorForSectionAt: section)
self.decorationViewAttrs.append(attr)
}
}
//返回rect范围内的所有元素的布局属性
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attrs = super.layoutAttributesForElements(in: rect)
attrs?.append(contentsOf: decorationViewAttrs.filter {
return rect.intersects($0.frame)
})
return attrs
}
//返回对应于indexPath的位置的Decoration视图的布局属性
override func layoutAttributesForDecorationView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
//如果是自定义的Decoration视图,则返回它的布局属性
if elementKind == SectionBackground {
return self.decorationViewAttrs[indexPath.section]
}
return super.layoutAttributesForDecorationView(ofKind: elementKind, at: indexPath)
}
}
|
//
// LessonsRouter.swift
// HseTimetable
//
// Created by Pavel on 21.04.2020.
// Copyright © 2020 Hse. All rights reserved.
//
import RxSwift
import RxCocoa
import Foundation
final class LessonsRouter: LessonsRouterProtocol, LessonsRouterInputsProtocol, Routerable {
private(set) weak var view: Viewable!
var inputs: LessonsRouterInputsProtocol { return self }
/// Inputs
let presentLessonEvent = PublishSubject<(Lesson, EventSegueType)>()
let pushAuthTrigger = PublishSubject<Void>()
private let disposeBag = DisposeBag()
required init(view: Viewable) {
self.view = view
/// Inputs setup
self.presentLessonEvent.asObserver()
.observeOn(MainScheduler.asyncInstance)
.subscribe(onNext: { [unowned self] lesson, segue in
switch segue {
case .lessonsToCalendar(let type):
let calendarConfigurator: CalendarConfiguratorProtocol = CalendarConfigurator()
if type == .present { calendarConfigurator.configureWithPresent(from: self.view, lesson: lesson) }
else if type == .push { calendarConfigurator.configureWithPush(from: self.view, lesson: lesson) }
case .lessonsToReminder(let type):
let reminderConfigurator: ReminderConfiguratorProtocol = ReminderConfigurator()
if type == .present { reminderConfigurator.configureWithPresent(from: self.view, lesson: lesson) }
else if type == .push { reminderConfigurator.configureWithPush(from: self.view, lesson: lesson) }
}
})
.disposed(by: self.disposeBag)
self.pushAuthTrigger.asObserver()
.observeOn(MainScheduler.asyncInstance)
.subscribe(onNext: { _ in
let authConfigurator: AuthConfiguratorProtocol = AuthConfigurator()
authConfigurator.configureWithMove()
})
.disposed(by: self.disposeBag)
}
}
|
//
// NHImageView.swift
// Registradores-Arisp
//
// Created by Nathan Hegedus on 24/06/15.
// Copyright (c) 2015 Nathan Hegedus. All rights reserved.
//
import UIKit
class NHButton: UIButton {
@IBInspectable var streachSize: Int = 0 {
didSet {
let backgroundImage = self.currentBackgroundImage?.stretchableImageWithLeftCapWidth(streachSize, topCapHeight: streachSize)
self.setBackgroundImage(backgroundImage, forState: .Normal)
self.setBackgroundImage(backgroundImage, forState: .Highlighted)
self.setBackgroundImage(backgroundImage, forState: .Disabled)
self.setBackgroundImage(backgroundImage, forState: .Selected)
}
}
@IBInspectable var cornerRadius: CGFloat = 0.0 {
didSet {
self.layer.cornerRadius = cornerRadius
}
}
@IBInspectable var borderColor: UIColor = UIColor.clearColor() {
didSet {
self.layer.borderColor = borderColor.CGColor
}
}
@IBInspectable var borderWidth: CGFloat = 0.0 {
didSet {
self.layer.borderWidth = borderWidth
}
}
@IBInspectable var layerBackgroundColor: UIColor = UIColor.clearColor() {
didSet {
self.layer.backgroundColor = layerBackgroundColor.CGColor
}
}
}
|
//
// HasName.swift
// bm-persona
//
// Created by Shawn Huang on 9/5/20.
// Copyright © 2020 RJ Pimentel. All rights reserved.
//
import Foundation
protocol HasName {
var name: String { get }
}
|
import SpriteKit
class GameObjectNode: SKNode{
func collisionWithPlayer(player:SKNode) -> Bool {
return false
}
func checkNodeRemoval(playerY: CGFloat) {
if playerY > self.position.y + 300 {
self.removeFromParent()
}
}
}
|
//
// DataStore.swift
// ViewController. Single Responsibility Principle.
//
// Created by Алексей Пархоменко on 22/05/2019.
// Copyright © 2019 Алексей Пархоменко. All rights reserved.
//
import UIKit
class DataStore {
func saveNameInCache(name: String) {
print("Ваше имя сохранено: \(name)")
}
func getNameFromCache() -> String {
return "some name"
}
}
|
//
// UIImageExtension.swift
// Add Contact
//
// Created by Hoang Tung Lam on 3/8/21.
//
import Foundation
import UIKit
extension UIImage {
func crop(withPath: UIBezierPath) -> UIImage {
let r: CGRect = withPath.cgPath.boundingBox
UIGraphicsBeginImageContextWithOptions(r.size, false, self.scale)
if let context = UIGraphicsGetCurrentContext() {
let rect = CGRect(origin: .zero, size: size)
// context.setFillColor(andColor.cgColor)
context.fill(rect)
context.translateBy(x: -r.origin.x, y: -r.origin.y)
context.addPath(withPath.cgPath)
context.clip()
}
draw(in: CGRect(origin: .zero, size: size))
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
return UIImage()
}
UIGraphicsEndImageContext()
return image
}
func cropImage(rect: CGRect) -> UIImage {
let r: CGRect = rect
UIGraphicsBeginImageContextWithOptions(r.size, false, self.scale)
if let context = UIGraphicsGetCurrentContext() {
let rect = CGRect(origin: .zero, size: size)
// context.setFillColor(andColor.cgColor)
context.fill(rect)
context.translateBy(x: -r.origin.x, y: -r.origin.y)
// context.addPath(withPath.cgPath)
context.clip()
}
draw(in: CGRect(origin: .zero, size: size))
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
return UIImage()
}
UIGraphicsEndImageContext()
return image
}
func flattenImage(topLeft: CGPoint, topRight: CGPoint, bottomLeft: CGPoint, bottomRight: CGPoint) -> CIImage {
let docImage = self.ciImage ?? CIImage()
let rect = CGRect(origin: CGPoint.zero, size: self.size)
let perspectiveCorrection = CIFilter(name: "CIPerspectiveCorrection")!
perspectiveCorrection.setValue(CIVector(cgPoint: self.cartesianForPoint(point: topLeft, extent: rect)), forKey: "inputTopLeft")
perspectiveCorrection.setValue(CIVector(cgPoint: self.cartesianForPoint(point: topRight, extent: rect)), forKey: "inputTopRight")
perspectiveCorrection.setValue(CIVector(cgPoint: self.cartesianForPoint(point: bottomLeft, extent: rect)), forKey: "inputBottomLeft")
perspectiveCorrection.setValue(CIVector(cgPoint: self.cartesianForPoint(point: bottomRight, extent: rect)), forKey: "inputBottomRight")
perspectiveCorrection.setValue(docImage, forKey: kCIInputImageKey)
return perspectiveCorrection.outputImage!
}
func cartesianForPoint(point:CGPoint,extent:CGRect) -> CGPoint {
return CGPoint(x: point.x,y: extent.height - point.y)
}
}
extension UIImage {
func rotate(radians: CGFloat) -> UIImage {
let rotatedSize = CGRect(origin: .zero, size: size)
.applying(CGAffineTransform(rotationAngle: CGFloat(radians)))
.integral.size
UIGraphicsBeginImageContext(rotatedSize)
if let context = UIGraphicsGetCurrentContext() {
let origin = CGPoint(x: rotatedSize.width / 2.0,
y: rotatedSize.height / 2.0)
context.translateBy(x: origin.x, y: origin.y)
context.rotate(by: radians)
draw(in: CGRect(x: -origin.y, y: -origin.x,
width: size.width, height: size.height))
let rotatedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return rotatedImage ?? self
}
return self
}
}
|
//
// CRMPropertyTableViewController.swift
// SweepBright
//
// Created by Kaio Henrique on 4/14/16.
// Copyright © 2016 madewithlove. All rights reserved.
//
import UIKit
import RealmSwift
class CRMPropertyTableViewController: UITableViewController {
var queue: NSOperationQueue!
let CRMContactCellReuseIdentifier = "contactCell"
var contacts: Results<CRMContact>!
var token: NotificationToken?
var cellNib: UINib! {
return UINib(nibName: "CRMPropertyCell", bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 64.0
self.tableView.rowHeight = UITableViewAutomaticDimension
self.queue = NSOperationQueue()
let realm = try! Realm()
self.contacts = realm.getAllContacts()
self.token = self.contacts.addNotificationBlock({ (_: RealmCollectionChange) in
self.tableView.reloadData()
})
self.tableView.registerNib(self.cellNib, forCellReuseIdentifier: CRMContactCellReuseIdentifier)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(showContactDetails), name: CRMNewContactAddedNotification, object: nil)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.tableView.reloadData()
}
deinit {
self.token?.stop()
}
@IBAction func refresh(sender: UIRefreshControl) {
AlertFactory.loadingTopBarMessage("Updating list of contacts")
self.updateContactsList({
dispatch_async(dispatch_get_main_queue(), {
sender.endRefreshing()
AlertFactory.dismissTopBarMessage()
})
})
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if var destinationView = segue.destinationViewController as? CRMContactDependent, let contact = sender as? CRMContact {
destinationView.contact = contact
}
super.prepareForSegue(segue, sender: sender)
}
func showContactDetails(notification: NSNotification) {
let realm = try! Realm()
if let contactId = notification.object as? String, let contact = realm.objectForPrimaryKey(CRMContact.self, key: contactId) {
self.performSegueWithIdentifier("contactDetail", sender: contact)
}
}
}
//MARK: Contacts Service
extension CRMPropertyTableViewController: CRMContactService {
}
//MARK: DataSource
extension CRMPropertyTableViewController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.contacts.count
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
(cell as! CRMContactCell).contact = self.contacts[indexPath.row]
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(CRMContactCellReuseIdentifier, forIndexPath: indexPath) as! CRMContactCell
return cell
}
}
//MARK: Delegate
extension CRMPropertyTableViewController {
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let contact: CRMContact? = self.contacts[indexPath.row] {
self.performSegueWithIdentifier("contactDetail", sender: contact)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
}
|
//
// ProfileViewController.swift
// BradleyUTour
//
// Created by Jacob Wilson on 4/27/17.
// Copyright © 2017 Bradley University. All rights reserved.
//
import UIKit
import RealmSwift
class ProfileViewController: UIViewController {
@IBOutlet var editButton:UIButton!
@IBOutlet var firstNameField: UITextField!
@IBOutlet var lastNameField: UITextField!
@IBOutlet var emailField: UITextField!
@IBOutlet var scrollView:UIScrollView!
var activeField:UITextField?
override func viewDidLoad() {
super.viewDidLoad()
addBorder(editButton, cornerRadius: 15)
addBorder(firstNameField)
addBorder(lastNameField)
addBorder(emailField)
addColorPlaceholderText(firstNameField)
addColorPlaceholderText(lastNameField)
addColorPlaceholderText(emailField)
registerKeyboard()
hideKeyboardWhenTapped()
let realm = try! Realm()
let users = realm.objects(User.self)
if users.count > 0 {
let user = users[0]
firstNameField.text = user.firstName
lastNameField.text = user.lastName
emailField.text = user.email
}
// Do any additional setup after loading the view.
}
func saveUser() {
let realm = try! Realm()
let users = realm.objects(User.self)
let user = updateUser(firstName: firstNameField, lastName: lastNameField, email: emailField)
if let user = user {
try! realm.write {
users[0].firstName = user.firstName
users[0].lastName = user.lastName
users[0].email = user.email
}
}
}
@IBAction func editPressed(_ sender: UIButton) {
saveUser()
self.navigationController?.popViewController(animated: true)
}
override func viewWillDisappear(_ animated: Bool) {
saveUser()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: UITextFieldDismissing stuff
override func keyboardWasShown(notification: NSNotification){
//Need to calculate keyboard exact size due to Apple suggestions
scrollView.isScrollEnabled = true
var info = notification.userInfo!
let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
var aRect : CGRect = self.view.frame
aRect.size.height -= keyboardSize!.height
if let activeField = activeField {
if (!aRect.contains(activeField.frame.origin)){
self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
}
}
}
override func keyboardWillBeHidden(notification: NSNotification){
//Once keyboard disappears, restore original positions
var info = notification.userInfo!
let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
view.endEditing(true)
scrollView.isScrollEnabled = false
}
func textFieldDidBeginEditing(_ textField: UITextField){
activeField = textField
}
func textFieldDidEndEditing(_ textField: UITextField){
activeField = nil
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// GeneralTool.swift
// AppDemoBySwift
//
// Created by admin on 16/3/31.
// Copyright © 2016年 admin. All rights reserved.
//
import UIKit
class GeneralTool: NSObject {
class func setLaunchViewController() ->(Bool){
//获取当前版本
let APPBundleVersion : AnyObject? = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"]
print("APPBundleVersion == \(APPBundleVersion)")
//判断APP是否有版本记录
if let version = userDefaults.objectForKey(defaultSet.CurrentDVVersionKey) {
var oldVersion :String?
var currentVersion :String?
oldVersion = version as? String
//旧版本记录跟当前版本对比
if let version = APPBundleVersion {currentVersion = version as? String}
if let o = oldVersion,let c = currentVersion {
//不相同就显示引导页
if o != c{
userDefaults.setObject(APPBundleVersion,forKey: defaultSet.CurrentDVVersionKey)
let version = userDefaults.objectForKey(defaultSet.CurrentDVVersionKey)
print("旧版本号为\(o),当前版本号为\(c),两者版本不一致,更新记录的version版本号为\(version)")
return true
}else {
print("旧版本号为\(o),当前版本号为\(c),两者版本一致,无需更新版本号")
return false
}
}else {
return false
}
}else {
var appBundleVersion : String?
if let version = APPBundleVersion {appBundleVersion = version as? String}
if let p = appBundleVersion {
//没有版本记录就记录并且显示引导页
userDefaults.setObject(p,forKey: defaultSet.CurrentDVVersionKey)
userDefaults.synchronize()
let version = userDefaults.objectForKey(defaultSet.CurrentDVVersionKey)
if let ver = version as? String {print("没有记录的版本号,当前版本号\(ver)将被记录,")}
}
return true
}
}
}
|
//
// ApplicationError.swift
// Schuylkill-App
//
// Created by Sam Hicks on 2/28/21.
//
import Amplify
import Foundation
import SwiftyBeaver
typealias ApplicationError = AmplifyError
extension ApplicationError {
}
|
import Foundation
struct Beat : Equatable {
let time : Double
let key : Character
//func within(k: Character, t: Double, d: Double) ??
func within(t: Double, d: Double) -> Bool{
return(((t-d)..<(t+d)).contains(time))
}
}
struct Level{
private let l : [Beat]
init(filename f: String) throws{
let p = Bundle.main.path(forResource: f, ofType: nil)
// TODO: depending on file size this could be very costly!
guard let a = try? String(contentsOfFile: p!, encoding: .utf8).split(separator: "\n") else{
throw NSError(domain: "Error opening Level file", code: 23)
}
var k : [Beat] = []
for t in a {
let x = t.split(separator: " ")
k.append(Beat(time: Double(x[0])!, key: Character(String(x[1]))))
}
l = k
}
func getBeat(time t: Double) -> Beat?{
return l.first(where: {$0.time == t})
}
func getBeatRange(range r: ClosedRange<Double>) -> [Beat]{
return l.filter{r.contains($0.time)}
}
}
class Game{
enum diff{case easy, medium, hard}
let d : diff
let l : Level
let beatFadeTimeMax : Double
var score = 0
var gameTime : Double
var curBeats : [(b: Beat, p: Double)] = []
init(filename f: String, difficulty d: diff) throws{
self.d = d
switch (d){
case .easy:
beatFadeTimeMax = 1.0
case .medium:
beatFadeTimeMax = 0.75
case .hard:
beatFadeTimeMax = 0.5
}
gameTime = 0.0
l = try! Level(filename: f)
if let b = l.getBeat(time: 0.0){
curBeats.append((b, 0.0))
}
}
func update(delta: Double){
// ISSUE: beats are not being added in at the correct time... i.e. if you use a 0.15 second delay the second beat doesn't get added in until 0.15 (when it should be 0.1)
// Not sure how big of an issue this is: when would it be important? where would your beat time ever be bigger than your game time?
for i in (0 ..< curBeats.count).reversed() {
if (curBeats[i].p <= beatFadeTimeMax) {
curBeats[i].p += delta
} else {
curBeats.remove(at: i)
}
}
for b in l.getBeatRange(range: (gameTime)...(gameTime+delta)){
if (!curBeats.contains{$0.b == b}){
curBeats.append((b, 0.0))
}
}
gameTime += delta
}
}
|
//: [Previous](@previous)
import Foundation
import Combine
enum APIError: Error {
case negativeValue
}
let array = [1,2,4,5,7,3,2,5,-1,9,23,12,75,23,34,65,76]
array.publisher
// .setFailureType(to: APIError.self)
// .tryFilter {
// guard $0 >= 0 else { throw APIError.negativeValue }
// return true
// }
// .replaceError(with: 1000)
.map { "\($0)" }
.delay(for: 1, scheduler: DispatchQueue.main)
.sink(receiveCompletion: { (error) in print("Error: \(error)") },
receiveValue: { print("Value: \($0)") }
)
//: [Next](@next)
|
//: Playground - noun: a place where people can play
import UIKit
// Logical NOT operator - unary prefix operator
let allowedEntry = false
// Same as saying: if allowedEntry != true (more characters)
if !allowedEntry {
print("You can't get in!")
}
let enteredDoorCode = true
let passedRetinaScan = false
let iAmSKE = false
// When using the '&&' both statements have to be true
if enteredDoorCode && passedRetinaScan || iAmSKE {
print("Welcome Grasshopper!")
} else {
print("Access denied bro...or sis!")
}
let hasDoorKey = true
let knowsOverridePassword = false
// When using the '||' operator, you just need one to be true
if hasDoorKey || knowsOverridePassword {
print("Welcome, come on in!")
} else {
print("You are still stuck outside!")
}
|
//
// Data.swift
// BasicTableView
//
// Created by Ryo Makabe on 2016-08-04.
// Copyright © 2016 ryomakabe. All rights reserved.
//
import UIKit
class Data {
var name: String!
init(name: String) {
self.name = name
}
}
|
//
// RealmCity.swift
// WeatherApp
//
// Created by Nikita Egoshin on 20.10.2020.
//
import Foundation
import RealmSwift
final class RealmCity: Object {
@objc dynamic var id: String = ""
@objc dynamic var cityName: String = ""
override class func primaryKey() -> String? {
return "cityName"
}
}
extension RealmCity {
convenience init(city: City) {
self.init()
self.id = city.id
self.cityName = city.cityName
}
func toCity() -> City {
City(id: id, cityName: cityName)
}
}
|
//
// PunchPopUpViewController.swift
// Contech
//
// Created by Lauren Shultz on 7/16/18.
// Copyright © 2018 Lauren Shultz. All rights reserved.
//
import UIKit
class PunchPopUpViewController: UIViewController {
var project: Project!
var punch: Punch!
var onViewerClosed: (() -> ())?
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var tradeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.black.withAlphaComponent(0.8)
titleLabel.text = punch.title
descriptionLabel.text = punch.note
tradeLabel.text = punch.trade.title
}
@IBAction func close(_ sender: Any) {
onViewerClosed!()
self.view.removeFromSuperview()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// String.swift
// swift.sintax
//
// Created by 鳥嶋晃次 on 2019/09/24.
// Copyright © 2019 鳥嶋晃次. All rights reserved.
//
import UIKit
/***********String (文字列)**********
ストリングのつくりかた
ストリングの連結
ストリング変換
*/
// ストリングリテラル "" 囲む
let message = "ハロー"
var bird:String
bird = "アイウエオ"
// 複数のストリングリテラル """ ~ """
let yotei = """
1日目 サイクリング
二日目 釣り
"""
print(yotei)
//1日目 サイクリング
//二日目 釣り
print("=====================")
let hello = String("hallo") + String(2000 + 20)
print(hello)
//hallo2020
print("=====================")
// 空のストリング
let emptyString = String()
var str = "hallo"
str = "" // からにする
// isEmpty を使うと 空白かどうか調べられる
func hello(_ who:String) {
if who.isEmpty {
return // who がからの場合途中で中断
}
let msg = "hello!" + who + "さん"
print(msg)
}
hello ("") // からなので表示されない
hello ("tanaka")
print("=====================")
// 同じ文字の繰り返し String(repeating: , count: )
let stars = String(repeating:"*", count: 10) // "" で囲めば 記号や絵文字もStringとして扱える
print(stars)
print("=====================")
// 特殊文字 色々ある
let swift = "swiftとは\n\"アマツバメ\"です"
print(swift)
//swiftとは
//"アマツバメ"です
print("=====================")
//文字数 を数える
let str1 = "アイウエオ12345ABcde(^^)!"
let num = str1.count
print(num) // 20
print("=====================")
// ストリングに変数や式を含める
let entries = 24
let staff = 3
let str2 = "参加者\(entries)名"
let str3 = "スタッフを含めると\(entries + staff)名です"
print(str2) // 参加者24名
print(str3) // スタッフを含めると27名です
print("=====================")
// ストリングの連結
let miyoji = "田中"
let namae = "太郎"
let renketu = miyoji + namae + "さん"
print(miyoji + namae)//田中太郎
print(renketu) //田中太郎さん
print("=====================")
let week = ["月","火","水","木","金","土","日"]
var oneWeek = "" // 初期化
for day in week {
oneWeek += day // day に一文字ずつ取り出して oneWeek に連結
}
print(oneWeek) //月火水木金土日
print("=====================")
// ストリングの変換
// string を Int に変換
let kakaku:String = "240"
let kosu: String = "2"
let kingaku = Int(kakaku)! * Int(kosu)! // オプショナルバリュー !
print(kingaku)// 480
// string を Double に変換
let r = "20"
let pi = "3.14"
let menseki = Double(r)! * Double(r)! * Double(pi)!
print("半径\(r)の面積は\(menseki)です") // 半径20の面積は1256.0です
print("=====================")
// 数値をストリング変換
let nakami = 135.5
let packege = 12.0
let str4 = "内容量:" + String(nakami) + "g"
let str5 = "総重量:" + (nakami + packege).description + "g"
print(str4) //内容量:135.5g
print(str5) //総重量:147.5g
print("=====================")
/* ストリングの比較と検索
比較演算子を使う
==
文字の大きさの比較
<,>,<=,>=
*/
let num1 = "Swift入門"
let num2 = "SWIFT入門"
let num3 = "Swift" + "入門"
if num1 == num2 {
print("num1とnum2は同じです")
} else {
print("num1とnum2は同じではありません")
}
if num1 == num3 {
print("num1とnum3は同じです")
} else {
print("num1とnum3は同じではありません")
}
/*
num1とnum2は同じではありません 大文字と小文字を区別している
num1とnum3は同じです
*/
// 大きさの比較
let a = "iPad"
let b = "iPhone"
if a > b {
print("\(a)の方が\(b)より大きい")
} else if a < b {
print("\(b)の方が\(a)より大きい")
} else {
print("\(a)と\(b)は同じ")
}
// iPhoneの方がiPadより大きい
/*
文字の大きさを比較している A < a < あ < ア の順
上記の場合は iP は同じ
a と h を比較している
結果 iPhoneの方がiPadより大きい と出る
*/
/* 大文字と小文字を区別せずに比較
英文字を比較する場合
大文字と小文字を区別せずに比較ときは 全てを揃えて比較
小文字にするには lowercased()
大文字にするには uppercased()
*/
let name1 = "apple"
let name2 = "Apple"
if name1.lowercased() == name2.lowercased() {
print("\(name1)と\(name2)は同じ")
} else {
print("\(name1)と\(name2)は違う")
}
// appleとAppleは同じ *lowercased() を使っているから
print("=====================")
// 前方一致 後方一致 hasPrefix() hasSufuffix()
let itemList = ["カツ丼","カツカレー","親子丼","天丼", ]
var menu1 = [String]()
var menu2 = [String]()
for item in itemList {
if item.hasPrefix("カツ") {
menu1.append(item) // 追加
}
if item.hasSuffix("丼") {
menu2.append(item) // 追加
}
}
print(menu1)
print(menu2)
//["カツ丼", "カツカレー"] カツ で分けている
//["カツ丼", "親子丼", "天丼"] 丼 で 分けている
print("=====================")
//ストリングにふまれているか contains()
let moji1 = "私は黒猫"
let moji2 = "黒猫"
if moji1.contains(moji2) { // containsで確認している
print("[\(moji2)]は含まれる")
} else {
print("[\(moji2)]は含まれない")
}
print("=====================")
//見つかった範囲の後ろを取り出す range() upperBound
let str6 = "東京都千代田区神南1-2-3"
let result6 = str6.range(of: "東京都")
if let theRange1 = result6 { // result6 に値があるとき theRange1に値が入る
let afterStr = str6[theRange1.upperBound...] // ... がないと一文字しかでない
print(afterStr)
} else {
print(str6)
}
//千代田区神南1-2-3
print("=====================")
/* 見つかった範囲を削除 removeSubrange()
substringとは違う
元のストリングを書き換えるので let ではく var
*/
var str7 = "東京都千代田区神南1-2-3"
let result7 = str7.range(of: "千代田区神南1-2-3") // 削除する範囲を求める
if let theRange2 = result7 { // result7 に値があるとき theRange2 に値が入る
str7.removeSubrange(theRange2) //****
}
print(str7)
// 東京都
|
/*
See LICENSE folder for this sample’s licensing information.
Abstract:
Platform representable accessibility examples
*/
import Foundation
import SwiftUI
public struct RepresentableExample: View {
public var body: some View {
VStack(alignment: .leading) {
Text("Element with representable view")
// You can use SwiftUI's Accessibility API to customize to accessibility of
// AppKit or UIKit represented elements
RepresentableView()
.frame(width: 128, height: 48)
.accessibilityLabel(Text("representable view accessibility label"))
.accessibilityValue(Text("representable view accessibility value"))
LargeSpacer()
Text("Element with representable view controller")
RepresentableViewController()
.frame(width: 128, height: 48)
.accessibilityLabel(Text("representable view controller accessibility label"))
.accessibilityValue(Text("representable view controller accessibility value"))
}
}
public init() {}
}
|
import AEXML
import Foundation
import PathKit
extension XCScheme {
public final class ProfileAction: SerialAction {
// MARK: - Static
private static let defaultBuildConfiguration = "Release"
// MARK: - Attributes
public var runnable: Runnable?
public var buildableProductRunnable: BuildableProductRunnable? {
// For backwards compatibility - can be removed in the next major version
runnable as? BuildableProductRunnable
}
public var buildConfiguration: String
public var shouldUseLaunchSchemeArgsEnv: Bool
public var savedToolIdentifier: String
public var ignoresPersistentStateOnLaunch: Bool
public var customWorkingDirectory: String?
public var useCustomWorkingDirectory: Bool
public var debugDocumentVersioning: Bool
public var askForAppToLaunch: Bool?
public var commandlineArguments: CommandLineArguments?
public var environmentVariables: [EnvironmentVariable]?
public var macroExpansion: BuildableReference?
public var enableTestabilityWhenProfilingTests: Bool
public var launchAutomaticallySubstyle: String?
// MARK: - Init
public init(runnable: Runnable?,
buildConfiguration: String,
preActions: [ExecutionAction] = [],
postActions: [ExecutionAction] = [],
macroExpansion: BuildableReference? = nil,
shouldUseLaunchSchemeArgsEnv: Bool = true,
savedToolIdentifier: String = "",
ignoresPersistentStateOnLaunch: Bool = false,
customWorkingDirectory: String? = nil,
useCustomWorkingDirectory: Bool = false,
debugDocumentVersioning: Bool = true,
askForAppToLaunch: Bool? = nil,
commandlineArguments: CommandLineArguments? = nil,
environmentVariables: [EnvironmentVariable]? = nil,
enableTestabilityWhenProfilingTests: Bool = true,
launchAutomaticallySubstyle: String? = nil) {
self.runnable = runnable
self.buildConfiguration = buildConfiguration
self.macroExpansion = macroExpansion
self.shouldUseLaunchSchemeArgsEnv = shouldUseLaunchSchemeArgsEnv
self.savedToolIdentifier = savedToolIdentifier
self.customWorkingDirectory = customWorkingDirectory
self.useCustomWorkingDirectory = useCustomWorkingDirectory
self.debugDocumentVersioning = debugDocumentVersioning
self.askForAppToLaunch = askForAppToLaunch
self.commandlineArguments = commandlineArguments
self.environmentVariables = environmentVariables
self.ignoresPersistentStateOnLaunch = ignoresPersistentStateOnLaunch
self.enableTestabilityWhenProfilingTests = enableTestabilityWhenProfilingTests
self.launchAutomaticallySubstyle = launchAutomaticallySubstyle
super.init(preActions, postActions)
}
public convenience init(
buildableProductRunnable: Runnable?,
buildConfiguration: String,
preActions: [ExecutionAction] = [],
postActions: [ExecutionAction] = [],
macroExpansion: BuildableReference? = nil,
shouldUseLaunchSchemeArgsEnv: Bool = true,
savedToolIdentifier: String = "",
ignoresPersistentStateOnLaunch: Bool = false,
customWorkingDirectory: String? = nil,
useCustomWorkingDirectory: Bool = false,
debugDocumentVersioning: Bool = true,
askForAppToLaunch: Bool? = nil,
commandlineArguments: CommandLineArguments? = nil,
environmentVariables: [EnvironmentVariable]? = nil,
enableTestabilityWhenProfilingTests: Bool = true,
launchAutomaticallySubstyle: String? = nil)
{
self.init(
runnable: buildableProductRunnable,
buildConfiguration: buildConfiguration,
preActions: preActions,
postActions: postActions,
macroExpansion: macroExpansion,
shouldUseLaunchSchemeArgsEnv: shouldUseLaunchSchemeArgsEnv,
savedToolIdentifier: savedToolIdentifier,
ignoresPersistentStateOnLaunch: ignoresPersistentStateOnLaunch,
customWorkingDirectory: customWorkingDirectory,
useCustomWorkingDirectory: useCustomWorkingDirectory,
debugDocumentVersioning: debugDocumentVersioning,
askForAppToLaunch: askForAppToLaunch,
commandlineArguments: commandlineArguments,
environmentVariables: environmentVariables,
enableTestabilityWhenProfilingTests: enableTestabilityWhenProfilingTests,
launchAutomaticallySubstyle: launchAutomaticallySubstyle)
}
override init(element: AEXMLElement) throws {
buildConfiguration = element.attributes["buildConfiguration"] ?? ProfileAction.defaultBuildConfiguration
shouldUseLaunchSchemeArgsEnv = element.attributes["shouldUseLaunchSchemeArgsEnv"].map { $0 == "YES" } ?? true
savedToolIdentifier = element.attributes["savedToolIdentifier"] ?? ""
useCustomWorkingDirectory = element.attributes["useCustomWorkingDirectory"] == "YES"
debugDocumentVersioning = element.attributes["debugDocumentVersioning"].map { $0 == "YES" } ?? true
askForAppToLaunch = element.attributes["askForAppToLaunch"].map { $0 == "YES" || $0 == "Yes" }
ignoresPersistentStateOnLaunch = element.attributes["ignoresPersistentStateOnLaunch"].map { $0 == "YES" } ?? false
// Runnable
let buildableProductRunnableElement = element["BuildableProductRunnable"]
let remoteRunnableElement = element["RemoteRunnable"]
if buildableProductRunnableElement.error == nil {
runnable = try BuildableProductRunnable(element: buildableProductRunnableElement)
} else if remoteRunnableElement.error == nil {
runnable = try RemoteRunnable(element: remoteRunnableElement)
}
let buildableReferenceElement = element["MacroExpansion"]["BuildableReference"]
if buildableReferenceElement.error == nil {
macroExpansion = try BuildableReference(element: buildableReferenceElement)
}
let commandlineOptions = element["CommandLineArguments"]
if commandlineOptions.error == nil {
commandlineArguments = try CommandLineArguments(element: commandlineOptions)
}
let environmentVariables = element["EnvironmentVariables"]
if environmentVariables.error == nil {
self.environmentVariables = try EnvironmentVariable.parseVariables(from: environmentVariables)
}
enableTestabilityWhenProfilingTests = element.attributes["enableTestabilityWhenProfilingTests"].map { $0 != "No" } ?? true
launchAutomaticallySubstyle = element.attributes["launchAutomaticallySubstyle"]
if let elementCustomWorkingDirectory: String = element.attributes["customWorkingDirectory"] {
customWorkingDirectory = elementCustomWorkingDirectory
}
try super.init(element: element)
}
// MARK: - XML
func xmlElement() -> AEXMLElement {
let element = AEXMLElement(name: "ProfileAction",
value: nil,
attributes: [
"buildConfiguration": buildConfiguration,
"shouldUseLaunchSchemeArgsEnv": shouldUseLaunchSchemeArgsEnv.xmlString,
"savedToolIdentifier": savedToolIdentifier,
"useCustomWorkingDirectory": useCustomWorkingDirectory.xmlString,
"debugDocumentVersioning": debugDocumentVersioning.xmlString,
])
super.writeXML(parent: element)
if let runnable = runnable {
element.addChild(runnable.xmlElement())
}
if let askForAppToLaunch = askForAppToLaunch {
element.attributes["askForAppToLaunch"] = askForAppToLaunch.xmlString
}
if ignoresPersistentStateOnLaunch {
element.attributes["ignoresPersistentStateOnLaunch"] = ignoresPersistentStateOnLaunch.xmlString
}
if !enableTestabilityWhenProfilingTests {
element.attributes["enableTestabilityWhenProfilingTests"] = "No"
}
if let commandlineArguments = commandlineArguments {
element.addChild(commandlineArguments.xmlElement())
}
if let environmentVariables = environmentVariables {
element.addChild(EnvironmentVariable.xmlElement(from: environmentVariables))
}
if let launchAutomaticallySubstyle = launchAutomaticallySubstyle {
element.attributes["launchAutomaticallySubstyle"] = launchAutomaticallySubstyle
}
if let customWorkingDirectory = customWorkingDirectory {
element.attributes["customWorkingDirectory"] = customWorkingDirectory
}
if let macroExpansion = macroExpansion {
let macro = element.addChild(name: "MacroExpansion")
macro.addChild(macroExpansion.xmlElement())
}
return element
}
// MARK: - Equatable
override func isEqual(to: Any?) -> Bool {
guard let rhs = to as? ProfileAction else { return false }
return super.isEqual(to: to) &&
runnable == rhs.runnable &&
buildConfiguration == rhs.buildConfiguration &&
shouldUseLaunchSchemeArgsEnv == rhs.shouldUseLaunchSchemeArgsEnv &&
savedToolIdentifier == rhs.savedToolIdentifier &&
ignoresPersistentStateOnLaunch == rhs.ignoresPersistentStateOnLaunch &&
customWorkingDirectory == rhs.customWorkingDirectory &&
useCustomWorkingDirectory == rhs.useCustomWorkingDirectory &&
debugDocumentVersioning == rhs.debugDocumentVersioning &&
askForAppToLaunch == rhs.askForAppToLaunch &&
commandlineArguments == rhs.commandlineArguments &&
environmentVariables == rhs.environmentVariables &&
macroExpansion == rhs.macroExpansion &&
enableTestabilityWhenProfilingTests == rhs.enableTestabilityWhenProfilingTests &&
launchAutomaticallySubstyle == rhs.launchAutomaticallySubstyle
}
}
}
|
//
// MapView.swift
// IsisCalendar
//
// Created by Jorge Sanmartin on 10/09/15.
// Copyright (c) 2015 isis. All rights reserved.
//
import MapKit
class MapView: BaseView {
var mapView: MKMapView!
override func setupConstraints(){
self.mapView.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0))
}
override func changeConstraints(){
}
override func initialize() {
createSubViews()
addSubviews()
addStyles()
}
func createSubViews(){
self.mapView = MKMapView.newAutoLayoutView()
}
func addSubviews(){
self.addSubview(self.mapView)
}
func addStyles(){
}
}
|
//
// BaseValues.swift
// Currency Converter
//
// Created by Pedro Fonseca on 30/08/20.
// Copyright © 2020 Pedro Bernils. All rights reserved.
//
import UIKit
class BaseValues: NSObject {
static func getBaseURL() -> String {
return Bundle.main.object(forInfoDictionaryKey: "baseURL") as! String
}
static func getToken() -> String {
return Bundle.main.object(forInfoDictionaryKey: "token") as! String
}
}
|
//
// STBindPhoneViewController.swift
// SpecialTraining
//
// Created by 尹涛 on 2018/12/13.
// Copyright © 2018 youpeixun. All rights reserved.
//
import UIKit
class STBindPhoneViewController: BaseViewController {
@IBOutlet weak var phoneOutlet: UITextField!
@IBOutlet weak var codeOutlet: UITextField!
@IBOutlet weak var okOutlet: UIButton!
@IBOutlet weak var authorOutlet: UIButton!
private var viewModel: BindPhoneViewModel!
private let timer = CountdownTimer.init()
override func setupUI() {
navigationItem.title = "绑定手机号"
}
override func rxBind() {
timer.showText.asDriver().skip(1)
.drive(onNext: { [unowned self] (second) in
if second == 0 {
self.authorOutlet.isUserInteractionEnabled = true
self.authorOutlet.setTitle("获取验证码", for: .normal)
} else {
self.authorOutlet.isUserInteractionEnabled = false
self.authorOutlet.setTitle("\(second)s", for: .normal)
}
}).disposed(by: disposeBag)
let nextDriver = okOutlet.rx.tap.asDriver()
.do(onNext: { [unowned self] in self.view.endEditing(true) })
let codeDriver = authorOutlet.rx.tap.asDriver()
.do(onNext: { [unowned self] _ in
self.view.endEditing(true)
})
viewModel = BindPhoneViewModel.init(input: (phoneOutlet.rx.text.orEmpty.asDriver(),
code: codeOutlet.rx.text.orEmpty.asDriver()),
tap: (sendAuth: codeDriver,
next: nextDriver))
viewModel.sendCodeSubject.subscribe(onNext: { [unowned self] (success) in
success == true ? self.timer.timerStar() : self.timer.timerPause()
}).disposed(by: disposeBag)
viewModel.popSubject.subscribe(onNext: { [weak self] _ in
self?.navigationController?.dismiss(animated: true, completion: nil)
})
.disposed(by: disposeBag)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let frame = CGRect.init(x: 0, y: 0, width: okOutlet.width, height: okOutlet.height)
okOutlet.layer.insertSublayer(STHelper.themeColorLayer(frame: frame), at: 0)
}
}
|
//
// RecordCell.swift
// SPHTechApp
//
// Created by Hoang Nguyen on 6/5/20.
// Copyright © 2020 Hoang Nguyen. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class RecordCell: UITableViewCell {
@IBOutlet weak var yearLabel: UILabel!
@IBOutlet weak var volumeLabel: UILabel!
@IBOutlet weak var infoButton: UIButton!
// MARK: ViewModel
var viewModel: RecordCellModelType! {
didSet {
configureUI()
}
}
private var disposeBag = DisposeBag()
// MARK: Overrides
override func prepareForReuse() {
super.prepareForReuse()
disposeBag = DisposeBag()
}
private func configureUI() {
yearLabel.text = viewModel.outputs.year
volumeLabel.text = viewModel.outputs.volume
infoButton.isHidden = !viewModel.outputs.isDecrease
infoButton.rx.tap.bind(to: viewModel.inputs.infoTapAction).disposed(by: disposeBag)
}
}
|
import UIKit
import UIExtension
import Trade
import OtherTabs
class RootPresenter: TabPresenter {
let tab1: HomePresenter
let tab2: MarketsPresenter
let tab3: TradeNavigationPresener
let tab4: FuturesPresenter
let tab5: WalletsPresenter
init() {
tab1 = .instantiate()
tab2 = .instantiate()
tab3 = TradeNavigationPresener()
tab4 = .instantiate()
tab5 = .instantiate()
super.init(nibName: nil, bundle: nil)
tab1.coordinator = self
viewControllers = [tab1, tab2, tab3, tab4, tab5]
}
required init?(coder: NSCoder) {
return nil
}
}
extension RootPresenter: HomePresenterCoordinator {
func presenterGoToConvert(_ presenter: HomePresenter) {
selectedViewController = tab3
tab3.showConvert()
}
}
|
//
// AppDelegate.swift
// TipCalculator
//
// Created by Abhay on 9/13/15.
// Copyright © 2015 Abhay. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let size : CGSize = UIScreen.mainScreen().bounds.size;
var storyBoard : UIStoryboard;
var initialVC : UIViewController;
if (size.height == 480) {
storyBoard = UIStoryboard(name:"Main4S", bundle:nil);
} else {
storyBoard = UIStoryboard(name:"Main", bundle:nil);
}
initialVC = storyBoard.instantiateInitialViewController()!;
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window?.rootViewController = initialVC;
self.window?.makeKeyAndVisible();
return true
}
}
|
//
// RainRange.swift
// RedCatWeather
//
// Created by Markus Pfeifer on 14.05.21.
//
enum RainRange : Character {
case sunny = "☀️"
case clouds = "⛅️"
case maybeRain = "🌦"
case rain = "🌧"
case stayAtHome = "⛈"
init(rainProbability: Double) {
switch Int(100 * rainProbability) {
case 0...10:
self = .sunny
case 10...40:
self = .clouds
case 40...60:
self = .maybeRain
case 60...85:
self = .rain
default:
self = .stayAtHome
}
}
}
extension HourForecast {
var rainRange : RainRange {
RainRange(rainProbability: rainProbability)
}
}
extension DayForecast {
var rainRange : RainRange {
RainRange(rainProbability: average.rainProbability)
}
}
extension WeekForecast {
var rainRange : RainRange {
RainRange(rainProbability: DayForecast(day: "?",
hourly: daily.map(\.average)).average.rainProbability)
}
}
extension ResolvedForecast {
var rainRange : RainRange {
switch self {
case .hour(let hour):
return hour.rainRange
case .day(let day):
return day.rainRange
case .week(let week):
return week.rainRange
}
}
}
|
import UIKit
class ItemTableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var favoriteButtonContainer: UIView!
@IBOutlet weak var favoriteButton: UIButton!
var item: Item? {
didSet {
guard let item = item else { return }
nameLabel.text = item.name
descriptionLabel.text = item.description
refreshFavoriteButton()
}
}
override func awakeFromNib() {
super.awakeFromNib()
backgroundColor = Color.medium
nameLabel.textColor = Color.text
descriptionLabel.textColor = Color.text
favoriteButtonContainer.backgroundColor = Color.dark
let bgColorView = UIView()
bgColorView.backgroundColor = Color.light
selectedBackgroundView = bgColorView
}
@IBAction func didTapFavoriteButton(_ sender: Any) {
guard let item = item else { return }
ItemManager.sharedInstance.toggleFavorite(item: item)
refreshFavoriteButton()
NotificationCenter.default.post(name: Notification.Name(rawValue: itemFavoritesDidUpdateNotificationKey), object: self)
}
fileprivate func refreshFavoriteButton() {
guard let item = item else { return }
if ItemManager.sharedInstance.isFavorited(item: item) {
favoriteButton.setImage(UIImage(named: "heart_filled"), for: UIControlState())
} else {
favoriteButton.setImage(UIImage(named: "heart_unfilled"), for: UIControlState())
}
}
}
|
//
// ChartsTableViewCell.swift
// KPCharts
//
// Created by Michael Merani on 6/26/17.
//
//
import UIKit
class ChartsTableViewCell: UITableViewCell {
@IBOutlet weak var txtFieldYards: UITextField!
@IBOutlet weak var txtFieldHangtime: UITextField!
@IBOutlet weak var txtFieldKickYards: UITextField!
@IBOutlet weak var makeOrMiss: UISegmentedControl!
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
}
}
|
//
// ContentView.swift
// SwiftUI-PopToRootExample
//
// Created by Chuck Hartman on 5/20/20.
// Copyright © 2020 ForeTheGreen. All rights reserved.
//
import SwiftUI
struct ContentView: View {
@State private var isActive : Bool = false
var body: some View {
NavigationView {
VStack {
Text("Root")
NavigationLink(destination: ContentView2(), isActive: self.$isActive )
{ Text("Push") }
.isDetailLink(false)
}
.navigationBarTitle("Root")
}
.navigationViewStyle(StackNavigationViewStyle())
.environment(\.rootPresentationMode, self.$isActive)
}
}
struct ContentView2: View {
@State private var isActive : Bool = false
@Environment(\.presentationMode) private var presentationMode: Binding<PresentationMode>
@Environment(\.rootPresentationMode) private var rootPresentationMode: Binding<RootPresentationMode>
var body: some View {
VStack {
Text("Two")
NavigationLink(destination: ContentView3(), isActive: self.$isActive)
{ Text("Push") }
.isDetailLink(false)
Button (action: { self.presentationMode.wrappedValue.dismiss() } )
{ Text("Pop") }
Button (action: { self.rootPresentationMode.wrappedValue.dismiss() } )
{ Text("Pop to root") }
}
.navigationBarTitle("Two")
}
}
struct ContentView3: View {
@State private var isActive : Bool = false
@Environment(\.presentationMode) private var presentationMode: Binding<PresentationMode>
@Environment(\.rootPresentationMode) private var rootPresentationMode: Binding<RootPresentationMode>
var body: some View {
VStack {
Text("Three")
NavigationLink(destination: ContentView4(), isActive: self.$isActive)
{ Text("Push") }
.isDetailLink(false)
Button (action: { self.presentationMode.wrappedValue.dismiss() } )
{ Text("Pop") }
Button (action: { self.rootPresentationMode.wrappedValue.dismiss() } )
{ Text("Pop to root") }
}
.navigationBarTitle("Three")
}
}
struct ContentView4: View {
@Environment(\.presentationMode) private var presentationMode: Binding<PresentationMode>
@Environment(\.rootPresentationMode) private var rootPresentationMode: Binding<RootPresentationMode>
var body: some View {
VStack {
Text("Four")
Button (action: { self.presentationMode.wrappedValue.dismiss() } )
{ Text("Pop") }
Button (action: { self.rootPresentationMode.wrappedValue.dismiss() } )
{ Text("Pop to root") }
}
.navigationBarTitle("Four")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
import UIKit
import ContactsUI
class FriendsViewController: UITableViewController {
var friendsList = Friend.defaultContacts()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.titleView = UIImageView(image: UIImage(named: "RWConnectTitle")!)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.tintColor = .white
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if
segue.identifier == "EditFriendSegue",
// 1
let cell = sender as? FriendCell,
let indexPath = tableView.indexPath(for: cell),
let editViewController = segue.destination as? EditFriendTableViewController {
let friend = friendsList[indexPath.row]
// 2
let store = CNContactStore()
// 3
let predicate = CNContact.predicateForContacts(matchingEmailAddress: friend.workEmail)
// 4
let keys = [CNContactPhoneNumbersKey as CNKeyDescriptor]
// 5
if
let contacts = try? store.unifiedContacts(matching: predicate, keysToFetch: keys),
let contact = contacts.first,
let contactPhone = contact.phoneNumbers.first {
// 6
friend.storedContact = contact.mutableCopy() as? CNMutableContact
friend.phoneNumberField = contactPhone
friend.identifier = contact.identifier
}
editViewController.friend = friend
}
}
@IBAction private func addFriends(sender: UIBarButtonItem) {
// 1
let contactPicker = CNContactPickerViewController()
contactPicker.delegate = self
// 2
contactPicker.predicateForEnablingContact = NSPredicate(format: "emailAddresses.@count > 0")
present(contactPicker, animated: true)
}
}
//MARK: - UITableViewDataSource
extension FriendsViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return friendsList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FriendCell", for: indexPath)
if let cell = cell as? FriendCell {
let friend = friendsList[indexPath.row]
cell.friend = friend
}
return cell
}
}
//MARK: - UITableViewDelegate
extension FriendsViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
// 1
let friend = friendsList[indexPath.row]
let contact = friend.contactValue
// 2
let contactViewController = CNContactViewController(forUnknownContact: contact)
contactViewController.hidesBottomBarWhenPushed = true
contactViewController.allowsEditing = false
contactViewController.allowsActions = false
// 3
navigationController?.navigationBar.tintColor = .appBlue
navigationController?.pushViewController(contactViewController, animated: true)
}
}
//MARK: - CNContactPickerDelegate
extension FriendsViewController: CNContactPickerDelegate {
func contactPicker(_ picker: CNContactPickerViewController,
didSelect contacts: [CNContact]) {
let newFriends = contacts.compactMap { Friend(contact: $0) }
for friend in newFriends {
if !friendsList.contains(friend) {
friendsList.append(friend)
}
}
tableView.reloadData()
}
}
|
import Foundation
@testable import SmartyStreets
class MockLogger: SmartyLogger {
var log = NSMutableArray()
override func log(message: String) {
self.log.add(message)
}
}
|
// Mission day 16 - Part 1 with the for loop - Longest String
func longestString(_ arr: [String]) -> String {
let strLength = arr[0].count
var longestStr = arr[0]
for str in arr {
if str.count > strLength {
longestStr = str
}
}
return longestStr
}
let arr1 = ["hello", "Joe", "Card"]
let theLongestString1 = longestString(arr1)
print(theLongestString1)
let arr2 = ["hello", "Joe", "Card", "Silent"]
let theLongestString2 = longestString(arr2)
print(theLongestString2)
|
//
// ActivityManager.swift
// Calm Cloud
//
// Created by Kate Duncan-Welke on 4/9/20.
// Copyright © 2020 Kate Duncan-Welke. All rights reserved.
//
import Foundation
struct ActivityManager {
static var loaded: [ActivityId] = []
static var completion: [Int : Bool] = [:]
static var searchResults: [Activity] = []
static let activities = [
Activity(title: "Draw", category: .creative, id: 10),
Activity(title: "Try breathing exercises", category: .mindfulness, id: 26),
Activity(title: "Listen to music", category: .creative, id: 27),
Activity(title: "Do yoga", category: .physical, id: 49),
Activity(title: "Clean a room", category: .home, id: 21),
Activity(title: "Garden", category: .nature, id: 2),
Activity(title: "Take photos outside", category: .nature, id: 35),
Activity(title: "Play an instrument", category: .creative, id: 12),
Activity(title: "Do a coloring page", category: .creative, id: 17),
Activity(title: "Play with a pet", category: .interaction, id: 4),
Activity(title: "Do laundry", category: .home, id: 8),
Activity(title: "Sit outside and listen", category: .mindfulness, id: 5),
Activity(title: "Meditate", category: .mindfulness, id: 25),
Activity(title: "Dance to music", category: .physical, id: 23),
Activity(title: "Bake cookies", category: .creative, id: 32),
Activity(title: "Open windows for air", category: .nature, id: 33),
Activity(title: "Vacuum", category: .home, id: 19),
Activity(title: "Phone or text someone", category: .interaction, id: 41),
Activity(title: "Play a relaxing game", category: .interaction, id: 37),
Activity(title: "Go for a run", category: .physical, id: 22),
Activity(title: "Game with friends", category: .interaction, id: 42),
Activity(title: "Talk with friends or family", category: .interaction, id: 13),
Activity(title: "Do some dusting", category: .home, id: 39),
Activity(title: "Perform an act of kindness", category: .kindness, id: 47),
Activity(title: "Make origami", category: .creative, id: 34),
Activity(title: "Listen to ambient noise", category: .mindfulness, id: 28),
Activity(title: "Write a letter", category: .interaction, id: 44),
Activity(title: "Floss and brush teeth", category: .selfCare, id: 7),
Activity(title: "Take a walk", category: .physical, id: 0),
Activity(title: "Have a spa day", category: .selfCare, id: 48),
Activity(title: "Write down your thoughts", category: .mindfulness, id: 36),
Activity(title: "Hike on a nature trail", category: .nature, id: 50),
Activity(title: "Write a thank you note", category: .kindness, id: 51),
Activity(title: "Make a calm jar", category: .creative, id: 30),
Activity(title: "Assemble a to-do list", category: .mindfulness, id: 24),
Activity(title: "Take a shower", category: .selfCare, id: 15),
Activity(title: "Journal", category: .mindfulness, id: 9),
Activity(title: "Water plants", category: .nature, id: 16),
Activity(title: "Offer to help someone", category: .kindness, id: 3),
Activity(title: "Plant an herb garden", category: .home, id: 40),
Activity(title: "Take a nap", category: .selfCare, id: 18),
Activity(title: "Change your sheets", category: .home, id: 1),
Activity(title: "Read a book", category: .creative, id: 14),
Activity(title: "Take a bubble bath", category: .selfCare, id: 29),
Activity(title: "Make a gift for someone", category: .kindness, id: 43),
Activity(title: "Make a box of donations", category: .kindness, id: 20),
Activity(title: "Trim your nails", category: .selfCare, id: 6),
Activity(title: "Check on a friend", category: .kindness, id: 45),
Activity(title: "Stretch your muscles", category: .physical, id: 38),
Activity(title: "Swing on a porch swing", category: .physical, id: 31),
Activity(title: "Sing", category: .creative, id: 11),
Activity(title: "Chat with friends online", category: .interaction, id: 52),
Activity(title: "Bird watch", category: .nature, id: 46),
Activity(title: "Write down your favorite things", category: .mindfulness, id: 53),
Activity(title: "Call a friend", category: .interaction, id: 54),
Activity(title: "Watch funny videos", category: .selfCare, id: 55),
Activity(title: "Organize part of a room", category: .home, id: 56),
Activity(title: "Make a wish list", category: .selfCare, id: 57),
Activity(title: "Do yard work", category: .physical, id: 58),
Activity(title: "Start a craft project", category: .creative, id: 59),
Activity(title: "Give someone a compliment", category: .kindness, id: 60),
Activity(title: "Pull weeds", category: .nature, id: 61),
Activity(title: "Lift weights", category: .physical, id: 62),
Activity(title: "Close your eyes and listen", category: .mindfulness, id: 63),
Activity(title: "Pumice your hands or feet", category: .selfCare, id: 64),
Activity(title: "Visit a park", category: .nature, id: 65),
Activity(title: "Write a short story", category: .creative, id: 66),
Activity(title: "Watch a favorite show or movie", category: .selfCare, id: 67),
Activity(title: "Volunteer", category: .kindness, id: 68),
Activity(title: "Decorate for a holiday or season", category: .home, id: 69),
Activity(title: "Walk with a friend", category: .interaction, id: 70),
Activity(title: "Research hobbies to try", category: .mindfulness, id: 71),
Activity(title: "Sit under a tree", category: .nature, id: 72),
Activity(title: "Ride a bike", category: .physical, id: 73),
Activity(title: "Wash the dishes", category: .home, id: 74),
Activity(title: "Cook for someone", category: .kindness, id: 75)
]
}
struct Activity {
let title: String
let category: Type
let id: Int
}
enum Type: String {
case creative = "Creative"
case home = "Around the home"
case interaction = "Interaction"
case kindness = "Act of kindness"
case mindfulness = "Mindfulness"
case nature = "Nature"
case physical = "Physical"
case selfCare = "Self Care"
}
|
//
// UIBezierPath+Extensions.swift
// Inkable
//
// Created by Adam Wulf on 5/1/21.
//
#if canImport(UIKit)
import UIKit
extension UIBezierPath {
/// Returns a new path that is the same as the current path, but stroked with the current line width, line cap style, line join style, and miter limit
/// - Returns: A new path that is the same as the current path, but stroked
public func strokedPath() -> UIBezierPath {
return UIBezierPath(cgPath: cgPath.copy(strokingWithWidth: lineWidth,
lineCap: lineCapStyle,
lineJoin: lineJoinStyle,
miterLimit: miterLimit))
}
}
#endif
|
//
// ViewController.swift
// Metabolism
//
// Created by Bilgihan Köse on 22.08.2020.
// Copyright © 2020 Bilgihan Kose. All rights reserved.
//
import UIKit
class CalculateViewController: UIViewController {
var calculatorBrain = CalculatorBrain()
@IBOutlet weak var heightLabel: UILabel!
@IBOutlet weak var weightLabel: UILabel!
@IBOutlet weak var heightSlider: UISlider!
@IBOutlet weak var weightSlider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
calculatorBrain.getBMIValue()
}
@IBAction func calculateButton(_ sender: Any) {
let height = heightSlider.value
let weight = weightSlider.value
calculatorBrain.calculateBMI(height, weight)
self.performSegue(withIdentifier: "goToResult", sender: self) //birden fazla ekranla calistigimizda hangi ekrani acacagini gostermemiz icin id vermemiz gerekir.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToResult" {
let destinationVC = segue.destination as! ResultViewController //downcast etmezsek veriyi tasiyamayiz, cunku hangi VC oldugunu bilmiyor.
destinationVC.bmiValue = calculatorBrain.getBMIValue() //burada artik ResultViewController'in property ve methodlarina ulasabiliyoruz, bu VC'den digerine veri tasiyabiliriz.
destinationVC.advice = calculatorBrain.getAdvice()
destinationVC.color = calculatorBrain.getColor()
}
}
@IBAction func heightSliderValue(_ sender: UISlider) {
let heightSliderValue = String(format: "%.2f", sender.value)
heightLabel.text = "\(heightSliderValue) M"
}
@IBAction func weightSliderValue(_ sender: UISlider) {
let weightSliderValue = String(format: "%.0f", sender.value)
weightLabel.text = "\(weightSliderValue) Kg"
}
}
|
//
// WeatherViewController.swift
// weather
//
// Created by Lauriane Haydari on 12/02/2020.
// Copyright © 2020 Lauriane Haydari. All rights reserved.
//
import UIKit
class WeekViewController: UIViewController {
// MARK: - Outlet
@IBOutlet private weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet private weak var tableView: UITableView!
@IBOutlet private weak var tempLabel: UILabel!
@IBOutlet private weak var nowLabel: UILabel!
@IBOutlet private weak var iconImageView: UIImageView!
// MARK: - Properties
var viewModel: WeekViewModel!
private var source = WeekDataSource()
// MARK: - View life cycle
override func viewDidLoad() {
super.viewDidLoad()
navigationBarCustom()
tableView.delegate = source
tableView.dataSource = source
bind(to: viewModel)
bind(to: source)
viewModel.viewDidLoad()
}
// MARK: - Private Functions
private func bind(to viewModel: WeekViewModel) {
viewModel.visibleItems = { [weak self] items in
DispatchQueue.main.async {
self?.source.update(with: items)
self?.tableView.reloadData()
}
}
viewModel.isLoading = { [weak self] loadingState in
DispatchQueue.main.async {
guard let self = self else { return }
switch loadingState {
case true:
self.tableView.isHidden = true
self.activityIndicator.isHidden = false
self.activityIndicator.startAnimating()
case false:
self.tableView.isHidden = false
self.activityIndicator.stopAnimating()
self.activityIndicator.isHidden = true
}
}
}
viewModel.tempText = { [weak self] text in
DispatchQueue.main.async {
self?.tempLabel.text = text
}
}
viewModel.iconText = { [weak self] text in
DispatchQueue.main.async {
self?.iconImageView.image = UIImage(named: text)
}
}
viewModel.nowText = { [weak self] text in
self?.nowLabel.text = text
}
}
private func bind(to source: WeekDataSource) {
source.selectedWeatherDay = viewModel.didSelectWeatherDay
}
// MARK: - Private Files
func navigationBarCustom() {
guard let bar = navigationController?.navigationBar else { return }
bar.setBackgroundImage(UIImage(), for: .default)
bar.shadowImage = UIImage()
bar.tintColor = .white
bar.clipsToBounds = false
bar.shadowImage = UIColor(red: 215/255, green: 215/255, blue: 215/255, alpha: 1.0).image(CGSize(width: self.view.frame.width, height: 1))
viewModel.navBarTitle = { text in
self.navigationItem.title = text
}
let textAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white,
NSAttributedString.Key.font: UIFont(name: "kailasa", size: 20)]
navigationController?.navigationBar.titleTextAttributes = textAttributes as [NSAttributedString.Key: Any]
}
}
|
import Foundation
/**
View model for **edit-activity-datetime.stencil**.
*/
struct EditActivityDateTimeViewModel: Codable {
let base: BaseViewModel
let id: Int
struct DateViewModel: Codable {
let day: Int
let month: Int
let year: Int
let hour: Int
let minute: Int
init(_ components: DateComponents) {
day = components.day!
month = components.month!
year = components.year!
hour = components.hour!
minute = components.minute!
}
}
let date: DateViewModel
init(base: BaseViewModel, activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
self.base = base
self.id = id
let components = Settings.calendar.dateComponents(in: Settings.timeZone, from: activity.date)
self.date = DateViewModel(components)
}
}
|
//
// AppDelegate.swift
// Apple-Camera-App
//
// Created by Chrishon Wyllie on 3/27/17.
// Copyright © 2017 Chrishon Wyllie. All rights reserved.
//
import UIKit
import Photos
public var phassetImageArray = [PHAsset]()
public var lastImageFromPhotoLibrary: UIImage?
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
navigate_To_Programmatically_Created_CameraController()
return true
}
func navigate_To_Programmatically_Created_CameraController() {
// Load the images before navigating to the controller
attempt_To_Retrieve_Photos_From_Library()
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
let cameraController = CameraController()
window?.rootViewController = cameraController
}
// The reason this functuon takes in a UICollectionView parameter is because we must reload the UICollectionView
// after the images have been loaded
func attempt_To_Retrieve_Photos_From_Library() {
// whenever you download and open a new app, you are often prompted allow the
// app to access your camera, contacts, etc.
// In this case, we want to determine whether we already have access to the user's photos gallery
let status: PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
if status == .authorized {
// User has pressed "Allow" when asked for access to their camera roll
self.loadCameraImages()
} else if status == .notDetermined {
// Access has not been determined.
PHPhotoLibrary.requestAuthorization({(_ status: PHAuthorizationStatus) -> Void in
if status == .authorized {
// Access has been granted.
self.loadCameraImages()
} else {
/*Access has been denied.*/
}
})
}
}
func loadCameraImages() {
let requestOptions = PHImageRequestOptions()
// May slow down loading of images
// Other options: .fastFormat | .opportunistic
requestOptions.deliveryMode = .highQualityFormat
let fetchOptions = PHFetchOptions()
// This is for if you want the most recent image taken to be at the top of the UICollectionView
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
// Returns all PHAssets (images, videos) from the options you specified
let fetchAllResults: PHFetchResult = PHAsset.fetchAssets(with: fetchOptions)
if fetchAllResults.count > 0 {
for i in 0..<fetchAllResults.count {
phassetImageArray.append(fetchAllResults.object(at: i) )
}
}
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
//
// ViewController.swift
// X-O
//
// Created by Sarah Almarii on 9/27/20.
// Copyright © 2020 fajer. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var b1: UIButton!
@IBOutlet weak var b2: UIButton!
@IBOutlet weak var b3: UIButton!
@IBOutlet weak var b4: UIButton!
@IBOutlet weak var b5: UIButton!
@IBOutlet weak var b6: UIButton!
@IBOutlet weak var b7: UIButton!
@IBOutlet weak var b8: UIButton!
@IBOutlet weak var b9: UIButton!
@IBOutlet weak var TurnLabel: UILabel!
@IBOutlet weak var XcounterLabel: UILabel!
@IBOutlet weak var OcounterLabel: UILabel!
var count = 0
var Ocounter = 0
var Xcounter = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
var buttons:[UIButton] = []
@IBAction func Click(_ sender: UIButton) {
if count % 2 == 0
{
sender.setTitle("X", for: .normal)
TurnLabel.text = "O's Turn"
}else{
sender.setTitle("O", for: .normal)
TurnLabel.text = "X's Turn"
}
checkWinner(winner: "O")
checkWinner(winner: "X")
sender.isUserInteractionEnabled = false
count += 1
}
func restartGame(){
let buttons:[UIButton] = [b1,b2,b3,b4,b5,b6,b7,b8,b9]
for button in buttons{
print(button)
button.setTitle("", for: .normal)
button.titleLabel?.text = ""
button.isUserInteractionEnabled = true
}
count = 0
TurnLabel.text = "X's-Turn"
}
func checkWinner(winner : String)
{
if (b1.titleLabel?.text == winner && b2.titleLabel?.text == winner && b3.titleLabel?.text == winner) ||
(b4.titleLabel?.text == winner && b5.titleLabel?.text == winner && b6.titleLabel?.text == winner) ||
(b7.titleLabel?.text == winner && b8.titleLabel?.text == winner && b9.titleLabel?.text == winner) ||
(b1.titleLabel?.text == winner && b4.titleLabel?.text == winner && b7.titleLabel?.text == winner) ||
(b2.titleLabel?.text == winner && b5.titleLabel?.text == winner && b8.titleLabel?.text == winner) ||
(b3.titleLabel?.text == winner && b6.titleLabel?.text == winner && b9.titleLabel?.text == winner) ||
(b1.titleLabel?.text == winner && b5.titleLabel?.text == winner && b9.titleLabel?.text == winner) ||
(b3.titleLabel?.text == winner && b5.titleLabel?.text == winner && b7.titleLabel?.text == winner)
{
if winner == "O"
{
Ocounter += 1
OcounterLabel.text = String(Ocounter)
}
else if winner == "X"
{
Xcounter += 1
XcounterLabel.text = String(Xcounter)
}
let alerController = UIAlertController(title: "\(winner)فاز ", message: " قم بضغط الزر لإعادة اللعب ", preferredStyle: .alert)
let restartAction = UIAlertAction(title: "reset", style: .cancel){
(alert) in self.restartGame()
}
alerController.addAction(restartAction)
present(alerController, animated: true, completion: nil)
}
}
@IBAction func Reset(_ sender: UIButton) {
restartGame()
}
}
|
//
// iOS_Aura
//
// Copyright © 2016 Ayla Networks. All rights reserved.
//
import Foundation
import iOS_AylaSDK
class DeviceDetailProvider: NSObject, AylaDeviceDetailProvider {
let deviceType_gateway = "Gateway"
let oemModel_ledevb = "ledevb"
let oemModel_generic = "generic"
let ledevb_managedProperties = ["Blue_LED", "Green_LED", "Blue_button","Red_Led"]
let genericGateway_managedProperties = ["join_enable", "join_status", "cmd", "log"]
func monitoredPropertyNames(for device: AylaDevice) -> [Any]? {
if device.oemModel == oemModel_ledevb {
return ledevb_managedProperties as [AnyObject]?
}
else if device.oemModel == oemModel_generic && device.deviceType == deviceType_gateway {
return genericGateway_managedProperties as [AnyObject]?
}
else if let propertyNames = device.properties?.keys {
return Array(propertyNames) as [AnyObject]?;
}
return nil;
}
}
|
//
// ViewController.swift
// VenueSearch
//
// Created by Conny Yang on 7/01/2017.
// Copyright © 2017 Conny Yang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let baseURL = "https://api.foursquare.com/v2/"
let path = "venues/search?ll=40.7,-74&client_id=EV3LGPWPNGBQ2MRFABCW0AEIAWYNMKHQ0EPS3RDTINSRMAD2&client_secret=XANXUPKQXL2KRSPP5I241IYXXUJUU0QVOMGJMQJ2M14OVT0X&v=20160827"
let urlString = "\(baseURL)\(path)"
let url = URL(string: urlString)!
let urlRequest = URLRequest(url: url)
let networkProcessing = NetworkProcessing(request: urlRequest)
networkProcessing.downloadJSON { (json, response, error) in
print("**********2************")
print(json)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
import UIKit
/*******
You don't need to do anything in this class.
You can use this class for verify ServiceStatusDelegate handling
*******/
class ViewController: UIViewController {
fileprivate let handler = ServiceStatusHandler()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.handler.delegate = self
self.handler.start()
}
}
extension ViewController:ServiceStatusDelegate {
func endSuccess() {
print("endSuccess")
}
func endFailure() {
print("endFailure")
}
func showVersionForceUpdateAlert(message: String) {
print("showVersionForceUpdateAlert \(message)")
}
func showVersionSuggestUpdateAlert(message: String) {
print("showVersionSuggestUpdateAlert \(message)")
}
}
|
//
// ProductTests.swift
// GBShop
//
// Created by Константин Кузнецов on 01.07.2021.
//
import XCTest
@testable import GBShop
class ProductTests: XCTestCase {
var requestFactory: RequestFactory?
var productsFactory: ProductRequestFactory?
override func setUpWithError() throws {
requestFactory = RequestFactory()
productsFactory = requestFactory?.makeProductRequaetFactory()
}
override func tearDownWithError() throws {
requestFactory = nil
productsFactory = nil
}
func testProduct() throws {
let expectation = XCTestExpectation(description: "getProduct")
productsFactory?.getProduct(id: 123, oauthToken: "token", completionHandler: { (response) in
switch response.result{
case .success(let product):
XCTAssertEqual(product.name, "Ноутбук")
expectation.fulfill()
case .failure(let error):
XCTFail(error.localizedDescription)
}
})
wait(for: [expectation], timeout: 5)
}
func testProducts() throws {
let expectation = XCTestExpectation(description: "getProducts")
productsFactory?.getProducts(oauthToken: "token", nextPageToken: "", prevPageToken: "", limit: 10, offset: 0, completionHandler: { (response) in
switch response.result{
case .success(let products):
XCTAssertNotNil(products)
expectation.fulfill()
case .failure(let error):
XCTFail(error.localizedDescription)
}
})
wait(for: [expectation], timeout: 5)
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
|
//
// LoginMainVC.swift
// MyTestApp
//
// Created by Joe Kletz on 11/11/2020.
//
import UIKit
class LoginMainVC: UIViewController {
let mainImageView : MainImagesView = {
let v = MainImagesView(frame: CGRect.zero)
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
let loginButton : GradientButton = {
let v = GradientButton()
// v.setTitle("Login", for: .normal)
v.title = "Login"
v.colors = [#colorLiteral(red: 0.0862745098, green: 1, blue: 0.7960784314, alpha: 1).cgColor,#colorLiteral(red: 0.07397184521, green: 0.4660721421, blue: 0.9371407628, alpha: 1).cgColor]
v.setTitleColor(.white, for: .normal)
v.backgroundColor = .systemTeal
v.addTarget(self, action: #selector(tappedLogin), for: .touchUpInside)
v.titleLabel?.font = UIFont(name: Globals.semiboldWeight, size: 25)
v.translatesAutoresizingMaskIntoConstraints = false
v.contentEdgeInsets = UIEdgeInsets(top: 15, left: 0, bottom: 15, right: 0)
v.layer.cornerRadius = 10
return v
}()
let signupButton : GradientButton = {
let v = GradientButton()
// v.setTitle("Signup", for: .normal)
v.title = "Sign Up"
v.colors = [#colorLiteral(red: 0.01327205449, green: 0.7977505326, blue: 0.9842525125, alpha: 1).cgColor,#colorLiteral(red: 0.2245837152, green: 0.006199446972, blue: 0.7438004613, alpha: 1).cgColor]
v.setTitleColor(.white, for: .normal)
v.addTarget(self, action: #selector(tappedSignup), for: .touchUpInside)
v.backgroundColor = #colorLiteral(red: 0.4705882353, green: 0.2352941176, blue: 1, alpha: 1)
v.titleLabel?.font = UIFont(name: Globals.semiboldWeight, size: 25)
v.translatesAutoresizingMaskIntoConstraints = false
v.contentEdgeInsets = UIEdgeInsets(top: 15, left: 0, bottom: 15, right: 0)
v.layer.cornerRadius = 10
return v
}()
let buttonsStack : UIStackView = {
let v = UIStackView()
v.axis = .vertical
v.spacing = 10
v.distribution = .fillEqually
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
let starsTopImageView : UIImageView = {
let v = UIImageView(image: UIImage(named: "StarsTop"))
v.translatesAutoresizingMaskIntoConstraints = false
return v
}()
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
}
func setupViews() {
view.addSubview(starsTopImageView)
view.addSubview(buttonsStack)
buttonsStack.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20).isActive = true
buttonsStack.leftAnchor.constraint(equalTo: view.layoutMarginsGuide.leftAnchor).isActive = true
buttonsStack.rightAnchor.constraint(equalTo: view.layoutMarginsGuide.rightAnchor).isActive = true
buttonsStack.heightAnchor.constraint(equalToConstant: 110).isActive = true
buttonsStack.addArrangedSubview(loginButton)
buttonsStack.addArrangedSubview(signupButton)
starsTopImageView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
starsTopImageView.heightAnchor.constraint(equalTo: starsTopImageView.widthAnchor).isActive = true
starsTopImageView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
starsTopImageView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
view.addSubview(mainImageView)
mainImageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
mainImageView.bottomAnchor.constraint(equalTo: buttonsStack.topAnchor).isActive = true
mainImageView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
mainImageView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
}
override func viewDidLayoutSubviews() {
let gradientLayer = CAGradientLayer()
let colors = [#colorLiteral(red: 0.6147674918, green: 0.943643868, blue: 0.9678253531, alpha: 1).cgColor,#colorLiteral(red: 0.3294117647, green: 0.6588235294, blue: 1, alpha: 1).cgColor]
gradientLayer.colors = colors
gradientLayer.frame = view.bounds
view.layer.insertSublayer(gradientLayer, at: 0)
//EMITTER
let l = CAEmitterLayer()
l.frame = view.bounds
l.birthRate = 2
l.emitterShape = .line
l.emitterSize = CGSize(width: 250, height: 2)
l.emitterPosition = CGPoint(x: view.bounds.width/2, y: 140)
let cell = CAEmitterCell()
cell.contentsScale = UIScreen.main.scale
cell.birthRate = 4
cell.lifetime = 15
cell.velocity = 30
// cell.emissionLongitude = CGFloat.pi
cell.emissionRange = .pi
cell.alphaSpeed = -0.3
cell.alphaRange = 0.5
cell.contents = UIImage(named: "Star")?.cgImage
l.emitterCells = [cell]
view.layer.insertSublayer(l, at: 2)
}
override func loadView() {
let v = UIView()
v.backgroundColor = #colorLiteral(red: 0.3294117647, green: 0.6588235294, blue: 1, alpha: 1)
self.view = v
}
@objc
func tappedLogin(){
let vc = LoginVC()
self.present(vc, animated: true)
}
@objc
func tappedSignup(){
let vc = EmailSignupVC()
// vc.modalPresentationStyle = .fullScreen
present(vc, animated: true)
}
}
internal class MainImagesView: UIImageView {
let bookImage : UIImageView = {
let v = UIImageView(image: UIImage(named: "OpenBook"))
v.translatesAutoresizingMaskIntoConstraints = false
v.contentMode = .scaleAspectFit
return v
}()
let logoImage : UIImageView = {
let v = UIImageView(image: UIImage(named: "CircleLogo"))
v.translatesAutoresizingMaskIntoConstraints = false
v.contentMode = .scaleAspectFit
return v
}()
let beeLady : UIImageView = {
let v = UIImageView(image: UIImage(named: "BeeLady"))
v.translatesAutoresizingMaskIntoConstraints = false
v.contentMode = .scaleAspectFit
return v
}()
let witchGirl : UIImageView = {
let v = UIImageView(image: UIImage(named: "WitchGirl"))
v.translatesAutoresizingMaskIntoConstraints = false
v.contentMode = .scaleAspectFit
return v
}()
let superBoy : UIImageView = {
let v = UIImageView(image: UIImage(named: "SuperBoy"))
v.translatesAutoresizingMaskIntoConstraints = false
v.contentMode = .scaleAspectFit
return v
}()
let mummy : UIImageView = {
let v = UIImageView(image: UIImage(named: "Mummy"))
v.translatesAutoresizingMaskIntoConstraints = false
v.contentMode = .scaleAspectFit
return v
}()
let superDad : UIImageView = {
let v = UIImageView(image: UIImage(named: "SuperDad"))
v.translatesAutoresizingMaskIntoConstraints = false
v.contentMode = .scaleAspectFit
return v
}()
let skeleton : UIImageView = {
let v = UIImageView(image: UIImage(named: "Skeleton"))
v.translatesAutoresizingMaskIntoConstraints = false
v.contentMode = .scaleAspectFit
return v
}()
let dad : UIImageView = {
let v = UIImageView(image: UIImage(named: "Dad"))
v.translatesAutoresizingMaskIntoConstraints = false
v.contentMode = .scaleAspectFit
return v
}()
let mum : UIImageView = {
let v = UIImageView(image: UIImage(named: "Mum"))
v.translatesAutoresizingMaskIntoConstraints = false
v.contentMode = .scaleAspectFit
return v
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
override func layoutSubviews() {
let l = CAEmitterLayer()
l.anchorPoint = CGPoint(x: 0.5, y: 1)
l.frame = bounds
l.emitterShape = .point
l.setAffineTransform(CGAffineTransform(rotationAngle: -.pi/2))
l.emitterPosition = CGPoint(x: center.x - 20, y: bounds.height)
l.setAffineTransform(CGAffineTransform(translationX: 0, y: -80).rotated(by: -.pi/2))
l.emitterMode = .points
let cell = CAEmitterCell()
cell.contentsScale = UIScreen.main.scale
cell.birthRate = 6
cell.lifetime = 11
cell.velocity = 25
cell.alphaSpeed = -0.15
cell.alphaRange = 0.5
cell.contents = UIImage(named: "Dot")?.cgImage
cell.emissionRange = .pi/2.4
cell.color = #colorLiteral(red: 0.08600000292, green: 1, blue: 0.7960000038, alpha: 1).cgColor
let cellStar = CAEmitterCell()
cellStar.contentsScale = UIScreen.main.scale
cellStar.birthRate = 7
cellStar.lifetime = 12
cellStar.velocity = 30
cellStar.alphaSpeed = -0.15
cellStar.alphaRange = 0.5
cellStar.contents = UIImage(named: "Star")?.cgImage
cellStar.emissionRange = .pi/2
l.emitterCells = [cell, cellStar]
layer.insertSublayer(l, at: 0)
}
func setupViews() {
addSubview(bookImage)
addSubview(logoImage)
addSubview(mum)
addSubview(dad)
addSubview(beeLady)
addSubview(superDad)
addSubview(witchGirl)
addSubview(superBoy)
addSubview(mummy)
addSubview(skeleton)
let offset = UIScreen.main.bounds.width/4
bookImage.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
bookImage.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
bookImage.heightAnchor.constraint(equalToConstant: 150).isActive = true
logoImage.topAnchor.constraint(equalTo: topAnchor).isActive = true
logoImage.leftAnchor.constraint(equalTo: layoutMarginsGuide.leftAnchor).isActive = true
logoImage.rightAnchor.constraint(equalTo: layoutMarginsGuide.rightAnchor).isActive = true
logoImage.heightAnchor.constraint(equalToConstant: 200).isActive = true
dad.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -110).isActive = true
dad.centerXAnchor.constraint(equalTo: centerXAnchor, constant: -offset - 30).isActive = true
dad.widthAnchor.constraint(equalToConstant: 125).isActive = true
dad.heightAnchor.constraint(equalToConstant: 125).isActive = true
mum.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -90).isActive = true
mum.centerXAnchor.constraint(equalTo: centerXAnchor, constant: offset + 35).isActive = true
mum.widthAnchor.constraint(equalToConstant: 150).isActive = true
mum.heightAnchor.constraint(equalToConstant: 150).isActive = true
beeLady.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -50).isActive = true
beeLady.centerXAnchor.constraint(equalTo: centerXAnchor, constant: -offset - 30).isActive = true
beeLady.widthAnchor.constraint(equalToConstant: 130).isActive = true
beeLady.heightAnchor.constraint(equalToConstant: 130).isActive = true
superDad.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -50).isActive = true
superDad.centerXAnchor.constraint(equalTo: centerXAnchor, constant: offset + 45).isActive = true
superDad.widthAnchor.constraint(equalToConstant: 105).isActive = true
superDad.heightAnchor.constraint(equalToConstant: 105).isActive = true
skeleton.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -140).isActive = true
skeleton.centerXAnchor.constraint(equalTo: centerXAnchor,constant: 15).isActive = true
skeleton.widthAnchor.constraint(equalToConstant: 110).isActive = true
skeleton.heightAnchor.constraint(equalToConstant: 110).isActive = true
witchGirl.centerYAnchor.constraint(equalTo: centerYAnchor, constant: -30).isActive = true
witchGirl.centerXAnchor.constraint(equalTo: centerXAnchor, constant: -offset - 30).isActive = true
witchGirl.widthAnchor.constraint(equalToConstant: 100).isActive = true
witchGirl.heightAnchor.constraint(equalToConstant: 100).isActive = true
superBoy.centerYAnchor.constraint(equalTo: centerYAnchor, constant: -100).isActive = true
superBoy.centerXAnchor.constraint(equalTo: centerXAnchor, constant: 40).isActive = true
superBoy.widthAnchor.constraint(equalToConstant: 150).isActive = true
superBoy.heightAnchor.constraint(equalToConstant: 150).isActive = true
mummy.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
mummy.centerXAnchor.constraint(equalTo: centerXAnchor, constant: offset).isActive = true
mummy.widthAnchor.constraint(equalToConstant: 120).isActive = true
mummy.heightAnchor.constraint(equalToConstant: 120).isActive = true
UIView.animate(withDuration: 3, delay: 0, options: [.autoreverse, .repeat, .curveLinear]) {
self.mummy.transform = CGAffineTransform(rotationAngle: 50)
self.mummy.transform = CGAffineTransform(translationX: 30, y: 0)
}
UIView.animate(withDuration: 4, delay: 0, options: [.autoreverse, .repeat]) {
self.witchGirl.transform = CGAffineTransform(translationX: 30, y: 32)
}
UIView.animate(withDuration: 3.5, delay: 0, options: [.autoreverse, .repeat]) {
self.superBoy.transform = CGAffineTransform(translationX: 0, y: 30)
self.superBoy.transform = CGAffineTransform(rotationAngle: .pi/11)
}
UIView.animate(withDuration: 2, delay: 0, options: [.autoreverse, .repeat]) {
self.skeleton.transform = CGAffineTransform(translationX: 0, y: 15)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
internal class GradientButton : UIButton{
var title : String?
var colors : [Any]?
override func layoutSubviews() {
layer.masksToBounds = true
let gradientLayer = CAGradientLayer()
gradientLayer.colors = colors
gradientLayer.frame = layer.bounds
layer.insertSublayer(gradientLayer, at: 0)
let text = CATextLayer()
text.font = UIFont(name: Globals.semiboldWeight, size: 20)
text.frame = bounds
text.string = title
text.alignmentMode = .center
text.fontSize = 25
text.anchorPoint = CGPoint(x: 0.5,y: 0.3)
// text.foregroundColor = UIColor.white.cgColor
layer.insertSublayer(text, at: 1)
}
}
|
// ___FILEHEADER___
import UIKit
protocol ___VARIABLE_sceneName___DisplayLogic: AnyObject {
// func displaySomething(viewModel: ___VARIABLE_sceneName___.Something.ViewModel)
}
class ___FILEBASENAMEASIDENTIFIER___: UICollectionViewController {
var interactor: ___VARIABLE_sceneName___BusinessLogic?
var router: (___VARIABLE_sceneName___RoutingLogic & ___VARIABLE_sceneName___DataPassing)?
// MARK: Lifecycle
init(collectionViewLayout: UICollectionViewLayout) {
super.init(collectionViewLayout: collectionViewLayout)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
}
}
// MARK: - Display logic
extension ___VARIABLE_sceneName___CollectionViewController: ___VARIABLE_sceneName___DisplayLogic {
//func displaySomething(viewModel: ___VARIABLE_sceneName___.Something.ViewModel) {
//}
}
|
//
// InfoViewController.swift
// PageChange
//
// Created by Yung on 2018/10/8.
//
import UIKit
class InfoViewController: UIViewController {
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func infoBackBtn(_ sender: UIButton) {
//呼叫 dismiss 方法退回去主頁
//self.dismiss(animated: true, completion: nil)
self.navigationController?.popViewController(animated: true)
}
}
|
//
// InterfaceController.swift
// breadwallet WatchKit Extension
//
// Created by ajv on 10/5/16.
// Copyright © 2016 breadwallet LLC. All rights reserved.
//
import WatchKit
import Foundation
class BalanceInterfaceController: WKInterfaceController {
@IBOutlet var bitsBalance: WKInterfaceLabel!
@IBOutlet var localBalance: WKInterfaceLabel!
@IBOutlet var noWallet: WKInterfaceLabel!
@IBOutlet var loadingIndicator: WKInterfaceImage!
override func awake(withContext context: Any?) {
super.awake(withContext: context)
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
NotificationCenter.default.addObserver(self, selector: #selector(BalanceInterfaceController.update(notification:)), name: .ApplicationDataDidUpdateNotification, object: nil)
update()
}
@objc func update(notification: NSNotification) {
update()
}
private func update() {
if let data = WatchDataManager.shared.data {
loadingIndicator.setHidden(true)
if data.hasWallet {
bitsBalance.setText(data.balance)
localBalance.setText(data.localBalance)
noWallet.setText("")
} else {
noWallet.setText(S.Watch.noWalletWarning)
bitsBalance.setText("")
localBalance.setText("")
}
} else {
bitsBalance.setText("")
localBalance.setText("")
noWallet.setText("")
}
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
|
//
// CompletedTasksCoordinator.swift
// WorkAndAnalyse
//
// Created by Ruslan Khanov on 25.05.2021.
//
import UIKit
class CompletedTasksCoordinator: BaseCoordinator {
// MARK: - Vars & Lets
private let router: RouterProtocol
private let coordinatorFactory: CoordinatorFactoryProtocol
private let viewControllerFactory: ViewControllerFactory
// MARK: - Coordinator
override func start() {
showCompletedTasksViewController()
}
// MARK: - Init
init(router: RouterProtocol, coordinatorFactory: CoordinatorFactoryProtocol, viewControllerFactory: ViewControllerFactory) {
self.router = router
self.coordinatorFactory = coordinatorFactory
self.viewControllerFactory = viewControllerFactory
}
// MARK: - Private methods
private func showCompletedTasksViewController() {
let viewController = viewControllerFactory.instantiateTaskListViewController()
viewController.tabBarItem = UITabBarItem(title: nil, image: UIImage(systemName: "checkmark.circle"), tag: 2)
viewController.navigationItem.title = "Completed"
let viewModel = TaskListViewModel(taskService: TaskServiceImplementation.shared, taskTypes: [.history])
viewModel.delegate = viewController
viewModel.noDataText = "You haven't completed any task :("
viewController.viewModel = viewModel
router.setRootModule(viewController)
}
}
|
import Foundation
class WatchService {
private let accountFactory: AccountFactory
private(set) var name: String?
init(accountFactory: AccountFactory) {
self.accountFactory = accountFactory
}
}
extension WatchService {
var defaultAccountName: String {
accountFactory.nextWatchAccountName
}
var resolvedName: String {
let trimmedName = (name ?? defaultAccountName).trimmingCharacters(in: .whitespacesAndNewlines)
return trimmedName
}
func set(name: String) {
if name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
self.name = nil
} else {
self.name = name
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.