text stringlengths 8 1.32M |
|---|
//
// ParserError.swift
// EasyGitHubSearch
//
// Created by Yevhen Triukhan on 11.10.2020.
// Copyright © 2020 Yevhen Triukhan. All rights reserved.
//
import Foundation
enum ParserError: Error {
case missingData
case invalidData
}
extension ParserError: LocalizedError {
public var errorDescription: String? {
switch self {
case .missingData:
return NSLocalizedString("Could not find data object.", comment: "missingData")
case .invalidData:
return NSLocalizedString("Could not parse data object.", comment: "invalidData")
}
}
}
|
//
// WordService.swift
// Englib
//
// Created by Barış Uyar on 3.11.2019.
// Copyright © 2019 Barış Uyar. All rights reserved.
//
import Foundation
class WebService {
func getWords(completion: @escaping ([Word]?) -> ()){
guard let url = URL(string: "https://temporal-pisces.glitch.me/word") else {
completion(nil)
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else {
DispatchQueue.main.async {
completion(nil)
}
return
}
let words = try? JSONDecoder().decode([Word].self, from: data)
DispatchQueue.main.async {
completion(words)
}
}.resume()
}
func save(_ word: Word, completion: @escaping (AddedModel?) -> ()) {
guard let url = URL(string: "https://temporal-pisces.glitch.me/word") else {
fatalError("Invalid URL")
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try? JSONEncoder().encode(word)
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
DispatchQueue.main.async {
completion(nil)
}
return
}
let response = try? JSONDecoder().decode(AddedModel.self, from: data)
DispatchQueue.main.async {
completion(response)
}
}.resume()
}
}
|
//
// PatterInjectBuilder.swift
// Patter
//
// Created by Maksim Ivanov on 12/04/2019.
// Copyright © 2019 Maksim Ivanov. All rights reserved.
//
import Foundation
import Swinject
import UIKit
final class PatterInjectBuiler: PatterBuilder, RegistrableVIPERModuleComponents {
func buildPatterModule(patterId: String) -> UIViewController? {
let container = Container.sharedContainer
let realmPatterEntityService = container.resolve(RealmPatterEntityService.self, argument: patterId)!
let patterViewController = container.resolve(PatterView.self) as! PatterViewController
let pressenter = patterViewController.presenter as! PatterDefaultPresenter
let interactor = pressenter.interactor as! PatterDefaultInteractor
interactor.realmPatterEntityService = realmPatterEntityService
return patterViewController
}
static func registerVIPERComponents(in container: Container) {
registerView(container: container)
registerInteractor(container: container)
registerPresenter(container: container)
registerRouter(container: container)
}
private static func registerView(container: Container) {
let viewDescription = container.register(PatterView.self) { _ in
let controller =
UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "showPatter")
return controller as! PatterViewController
}
viewDescription.initCompleted { (resolver, view) in
let view = view as! PatterViewController
view.presenter = resolver.resolve(PatterPresenter.self)!
}
}
private static func registerInteractor(container: Container) {
let interactorDescription = container.register(PatterInteractor.self) { (resolver) in
PatterDefaultInteractor(audioRecordingService: resolver.resolve(AudioRecordingService.self)!,
audioPlayerService: resolver.resolve(AudioPlayerService.self)!,
vibrationService: resolver.resolve(VibrationService.self)!)
}
interactorDescription.initCompleted { (resolver, interactor) in
let presenter = resolver.resolve(PatterPresenter.self)!
let interactor = interactor as! PatterDefaultInteractor
interactor.presenter = presenter
}
}
private static func registerPresenter(container: Container) {
let presenterDescription = container.register(PatterPresenter.self) { _ in
PatterDefaultPresenter()
}
presenterDescription.initCompleted { (resolver, presenter) in
let presenter = presenter as! PatterDefaultPresenter
presenter.view = resolver.resolve(PatterView.self)!
presenter.interactor = resolver.resolve(PatterInteractor.self)!
presenter.router = resolver.resolve(PatterRouter.self)!
}
}
private static func registerRouter(container: Container) {
let routerDescription = container.register(PatterRouter.self) { (_) in
PatterDefaultRouter()
}
routerDescription.initCompleted { (resolver, router) in
let router = router as! PatterDefaultRouter
router.viewController = resolver.resolve(PatterView.self)! as? UIViewController
router.presenter = resolver.resolve(PatterPresenter.self)!
}
}
}
|
//
// HueRotation_Photos.swift
// 100Views
//
// Created by Mark Moeykens on 9/2/19.
// Copyright © 2019 Mark Moeykens. All rights reserved.
//
import SwiftUI
struct HueRotation_Photos: View {
var body: some View {
VStack(spacing: 5) {
Text("Hue Rotation").font(.largeTitle)
Text("With Photos").font(.title).foregroundColor(.gray)
Text("Applying hue rotation on a photo will rotate all colors.")
.frame(maxWidth: .infinity)
.font(.title).padding()
.background(Color.red)
.layoutPriority(1)
.foregroundColor(.white)
VStack(spacing: 5) {
Image("rainbow").resizable()
.scaledToFit()
.frame(height: 150)
.overlay(Text("0°"))
Image("rainbow").resizable()
.scaledToFit()
.frame(height: 150)
.hueRotation(Angle.degrees(90))
.overlay(Text("90°"))
Image("rainbow").resizable()
.scaledToFit()
.frame(height: 150)
.hueRotation(Angle.degrees(180))
.overlay(Text("180°"))
Image("rainbow").resizable()
.scaledToFit()
.frame(height: 150)
.hueRotation(Angle.degrees(270))
.overlay(Text("270°"))
}
.font(.title)
.foregroundColor(.white)
Text("Photo by Daniele Pelusi")
.font(.caption)
}.edgesIgnoringSafeArea(.bottom)
}
}
struct HueRotation_Photos_Previews: PreviewProvider {
static var previews: some View {
HueRotation_Photos()
}
}
|
//
// ReadListModel.swift
// OneCopy
//
// Created by Mac on 16/10/13.
// Copyright © 2016年 DJY. All rights reserved.
//
import UIKit
class ReadListFrameModel: BaseModel {
var titleLblFrame : CGRect?
var writerLblFrame : CGRect?
var contentViewFrame : CGRect?
var typeLblFrame : CGRect?
var lineFrame : CGRect?
}
class ReadModel: BaseModel {
var frameModel : ReadListFrameModel?
var title : NSString?
var writer : NSString?
var content : NSString?
var type : NSString?
}
class ReadListModel: BaseModel {
let topMargin : CGFloat = 15
let insidePadding : CGFloat = 10
let outsidePadding : CGFloat = 10
let contentPadding : CGFloat = 10
let bottomMargin : CGFloat = 15
let titleFont : CGFloat = 17.5
let contentFont : CGFloat = 13
let typeFont : CGFloat = 10
let lineSpace : CGFloat = 10
var listCardFrame : CGRect?
//保存了每一页的文章
var readList : [ReadModel]?
//每一页的每一个文章在列表中的frame,调用calLayout后
var readListFrames : [ReadListFrameModel]?
func calLayout() -> Void {
self.readListFrames = Array.init()
let typeW : CGFloat = 40
let cardW : CGFloat = APPWINDOWWIDTH - outsidePadding * 2
let titleW : CGFloat = cardW - insidePadding * 2 - typeW
var totolHeight : CGFloat = 0
for model : ReadModel in self.readList! {
let frameModel : ReadListFrameModel = ReadListFrameModel.init()
//类型lbl
frameModel.typeLblFrame = CGRect.init(x: cardW - outsidePadding - typeW, y: topMargin + totolHeight , width: typeW, height: 20)
//算title的size ,宽是确定的
let titleSize = Tools.getTextRectSize(text: model.title!, font: UIFont.systemFont(ofSize: titleFont), size: CGSize.init(width: titleW, height:CGFloat(MAXFLOAT)))
frameModel.titleLblFrame = CGRect.init(x: insidePadding, y: topMargin + totolHeight, width: cardW - insidePadding * 2 - (frameModel.typeLblFrame?.width)! - insidePadding, height:titleSize.height)
//作者
frameModel.writerLblFrame = CGRect.init(x: insidePadding, y: (frameModel.titleLblFrame?.maxY)! + contentPadding , width: 250, height: UIFont.systemFont(ofSize: contentFont).lineHeight)
//内容
//原文本size
let contentOriTextRect = Tools.getTextRectSize(text: model.content!, font: UIFont.systemFont(ofSize: contentFont), size: CGSize.init(width: cardW - insidePadding * 2, height:CGFloat(MAXFLOAT)))
//算高度
//1.算大概有多少行
let rowNum : CGFloat = contentOriTextRect.height / (UIFont.systemFont(ofSize: contentFont).lineHeight)
//2.原高度 + 总行间距 + 误差
let contentHeight = contentOriTextRect.height + (rowNum - 1) * lineSpace + 10.0
frameModel.contentViewFrame = CGRect.init(x:0, y: (frameModel.writerLblFrame?.maxY)! + contentPadding , width: cardW, height: contentHeight)
frameModel.lineFrame = CGRect.init(x: insidePadding, y: (frameModel.contentViewFrame?.maxY)! + bottomMargin , width: cardW - insidePadding * 2, height: 1)
self.readListFrames?.append(frameModel)
totolHeight = (frameModel.lineFrame?.maxY)!
}
self.listCardFrame = CGRect.init(x: outsidePadding, y: outsidePadding, width: APPWINDOWWIDTH - outsidePadding * 2, height: totolHeight)
}
}
|
//
// ViewController.swift
// Static表格
//
// Created by bingoogol on 14/8/26.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
// 在静态表格中,可以等同于UIViewController使用,在静态表格中,程序员几乎不需要考虑键盘的问题
@IBOutlet weak var nickName: UITextField!
@IBOutlet var password: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.backgroundColor = UIColor(patternImage:UIImage(named: "bg.jpg"))
}
@IBAction func saveUserData(sender: UIButton) {
println("保存用户信息")
}
} |
/////
//// Preferences.swift
/// Copyright © 2020 Dmitriy Borovikov. All rights reserved.
//
import Foundation
struct Preferences {
@UserPreference("PlayListBookmark")
static var playListBookmark: Data?
}
|
//
// HomeController.swift
// PalmTree
//
// Created by SprintSols on 13/5/20.
// Copyright © 2020 apple. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
import Firebase
import FirebaseMessaging
import UserNotifications
import FirebaseCore
import FirebaseInstanceID
import IQKeyboardManagerSwift
import CoreLocation
var signoutFlag = false
class HomeController: UIViewController, UITableViewDelegate, UITableViewDataSource, NVActivityIndicatorViewable, AddDetailDelegate, CategoryDetailDelegate, UISearchBarDelegate, MessagingDelegate,UNUserNotificationCenterDelegate , UIGestureRecognizerDelegate, CLLocationManagerDelegate {
//MARK:- Outlets
@IBOutlet weak var tableView: UITableView! {
didSet {
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
tableView.showsVerticalScrollIndicator = false
tableView.separatorStyle = .none
tableView.register(UINib(nibName: "SearchSectionCell", bundle: nil), forCellReuseIdentifier: "SearchSectionCell")
tableView.addSubview(refreshControl)
}
}
@IBOutlet weak var btnHome: UIButton!
@IBOutlet weak var btnPalmtree: UIButton!
@IBOutlet weak var btnPost: UIButton!
@IBOutlet weak var btnWishlist: UIButton!
@IBOutlet weak var btnMessages: UIButton!
@IBOutlet weak var btnSearch: UIButton!
//MARK:- Properties
let keyboardManager = IQKeyboardManager.sharedManager()
lazy var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action:
#selector(refreshTableView),
for: UIControlEvents.valueChanged)
if let mainColor = defaults.string(forKey: "mainColor") {
refreshControl.tintColor = Constants.hexStringToUIColor(hex: mainColor)
}
return refreshControl
}()
var defaults = UserDefaults.standard
var latestAdsArray = [AdsJSON]()
var locationManager = CLLocationManager()
lazy var geocoder = CLGeocoder()
var fromVC = ""
//MARK:- View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
userDetail?.displayName = defaults.string(forKey: "displayName") ?? ""
userDetail?.id = defaults.integer(forKey: "id")
userDetail?.phone = defaults.string(forKey: "phone") ?? ""
userDetail?.profileImg = defaults.string(forKey: "profileImg") ?? ""
userDetail?.userEmail = defaults.string(forKey: "userEmail") ?? ""
homeVC = self
if (CLLocationManager.locationServicesEnabled())
{
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
self.navigationController?.isNavigationBarHidden = true
self.hideKeyboard()
self.googleAnalytics(controllerName: "Home Controller")
// self.sendFCMToken()
self.subscribeToTopicMessage()
self.showLoader()
self.homeData()
}
override func viewDidAppear(_ animated: Bool) {
if languageCode == "ar"
{
changeMenuButtons()
}
tableView.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
currentVc = self
if fromVC == "PostAd" || fromVC == "Favourites" || signoutFlag
{
fromVC = ""
signoutFlag = false
self.homeData()
}
adDetailObj = AdDetailObject()
tableView.reloadData()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
@objc func refreshTableView() {
self.homeData()
tableView.reloadData()
self.refreshControl.endRefreshing()
}
//MARK:- Cutom Functions
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let currentLoc = locations.last{
userDetail?.currentLocation = currentLoc
userDetail?.lat = currentLoc.coordinate.latitude
userDetail?.lng = currentLoc.coordinate.longitude
defaults.set(userDetail?.lat, forKey: "latitude")
defaults.set(userDetail?.lng, forKey: "longitude")
print("Latitude: \(currentLoc.coordinate.latitude)")
print("Longitude: \(currentLoc.coordinate.longitude)")
geocoder.reverseGeocodeLocation(currentLoc) { (placemarks, error) in
self.processResponse(withPlacemarks: placemarks, error: error)
}
}
}
private func processResponse(withPlacemarks placemarks: [CLPlacemark]?, error: Error?) {
// Update View
if let error = error
{
print("Unable to Reverse Geocode Location (\(error))")
}
else
{
if let placemarks = placemarks, let placemark = placemarks.first
{
userDetail?.currentAddress = placemark.compactAddress ?? ""
userDetail?.locationName = placemark.locationName ?? ""
userDetail?.country = placemark.currentCountry ?? ""
defaults.set(userDetail?.currentAddress, forKey: "address")
defaults.set(userDetail?.locationName, forKey: "locName")
defaults.set(userDetail?.country, forKey: "country")
self.showLoader()
self.homeData()
tableView.reloadData()
locationManager.stopUpdatingLocation()
}
}
}
func changeMenuButtons()
{
btnHome.setImage(UIImage(named: "home_active_" + languageCode), for: .normal)
btnPalmtree.setImage(UIImage(named: "mypalmtree_" + languageCode), for: .normal)
btnPost.setImage(UIImage(named: "post_" + languageCode), for: .normal)
btnWishlist.setImage(UIImage(named: "wishlist_" + languageCode), for: .normal)
btnMessages.setImage(UIImage(named: "messages_" + languageCode), for: .normal)
}
func subscribeToTopicMessage() {
if defaults.bool(forKey: "isLogin") {
Messaging.messaging().shouldEstablishDirectChannel = true
Messaging.messaging().subscribe(toTopic: "global")
}
}
func showLoader(){
self.startAnimating(Constants.activitySize.size, message: Constants.loaderMessages.loadingMessage.rawValue,messageFont: UIFont.systemFont(ofSize: 14), type: NVActivityIndicatorType.ballClipRotatePulse)
}
//MARK:- go to add detail controller
func goToAddDetail(ad_id: Int) {
let AdDetailVC = self.storyboard?.instantiateViewController(withIdentifier: "AdDetailVC") as! AdDetailVC
self.navigationController?.pushViewController(AdDetailVC, animated: true)
}
//MARK:- go to add detail controller
func goToAddDetailVC(detail: AdsJSON) {
let adDetailVC = self.storyboard?.instantiateViewController(withIdentifier: "AdDetailVC") as! AdDetailVC
adDetailVC.adDetailDataObj = detail
self.navigationController?.pushViewController(adDetailVC, animated: true)
}
//MARK:- Add to favourites
func addToFavourites(ad_id: Int, favFlag: Bool)
{
if defaults.bool(forKey: "isLogin") == false
{
let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
let navController = UINavigationController(rootViewController: loginVC)
self.present(navController, animated:true, completion: nil)
}
else
{
if !favFlag
{
let parameter: [String: Any] = ["ad_id": ad_id, "user_id": userDetail?.id ?? 0]
self.makeAddFavourite(param: parameter as NSDictionary)
}
else
{
self.showToast(message: NSLocalizedString(String(format: "fav_already_%@",languageCode), comment: ""))
}
}
}
//MARK:- go to category detail
func goToCategoryDetail() {
let categoryVC = self.storyboard?.instantiateViewController(withIdentifier: "CategoryVC") as! CategoryVC
self.navigationController?.pushViewController(categoryVC, animated: true)
}
//MARK:- go to ad list
func goToAdFilterListVC(cat_id: Int, catName: String) {
let adFilterListVC = self.storyboard?.instantiateViewController(withIdentifier: "AdFilterListVC") as! AdFilterListVC
adFilterListVC.categoryID = cat_id
adFilterListVC.catName = catName
self.navigationController?.pushViewController(adFilterListVC, animated: true)
}
@objc func actionHome() {
appDelegate.moveToHome()
}
//MARK:- Search Bar Delegates
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
//self.searchBarNavigation.endEditing(true)
searchBar.endEditing(true)
self.view.endEditing(true)
}
//MARK:- Table View Delegate Methods
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let section = indexPath.section
if section == 0
{
let cell: CategoriesTableCell = tableView.dequeueReusableCell(withIdentifier: "CategoriesTableCell", for: indexPath) as! CategoriesTableCell
cell.numberOfColums = 3
cell.categoryArray = categoryArray
cell.delegate = self
cell.collectionView.reloadData()
return cell
}
else if section == 1
{
let cell: AddsTableCell = tableView.dequeueReusableCell(withIdentifier: "AddsTableCell", for: indexPath) as! AddsTableCell
cell.locationBtnAction = { () in
let locationVC = self.storyboard?.instantiateViewController(withIdentifier: "LocationVC") as! LocationVC
self.navigationController?.pushViewController(locationVC, animated: true)
}
if userDetail?.locationName != ""
{
cell.locBtn.setTitle(userDetail?.locationName, for: .normal)
}
cell.dataArray = latestAdsArray
cell.delegate = self
cell.reloadData()
return cell
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
let section = indexPath.section
var totalHeight : CGFloat = 0
var height: CGFloat = 0
if section == 0
{
let itemHeight = CollectionViewSettings.getItemWidth(boundWidth: tableView.bounds.size.width)
let totalRow = ceil(CGFloat(categoryArray.count) / CollectionViewSettings.column)
let totalTopBottomOffSet = CollectionViewSettings.offset + CollectionViewSettings.offset
let totalSpacing = CGFloat(totalRow - 1) * CollectionViewSettings.minLineSpacing
totalHeight = ((itemHeight * CGFloat(totalRow)) + totalTopBottomOffSet + totalSpacing)
height = totalHeight
}
else if section == 1
{
let itemHeight = CollectionViewSettings.getAdItemWidth(boundWidth: tableView.bounds.size.width)
let totalRow = ceil(CGFloat(latestAdsArray.count) / 2)
let totalTopBottomOffSet = CollectionViewSettings.offset + CollectionViewSettings.offset
let totalSpacing = CGFloat(totalRow - 1) * CollectionViewSettings.minLineSpacing
totalHeight = ((itemHeight * CGFloat(totalRow)) + totalTopBottomOffSet + totalSpacing)
height = totalHeight + 350
}
return height
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
{
if tableView.isDragging {
cell.transform = CGAffineTransform.init(scaleX: 0.5, y: 0.5)
UIView.animate(withDuration: 0.3, animations: {
cell.transform = CGAffineTransform.identity
})
}
}
//MARK:- IBActions
@IBAction func searchBtnAction(_ button: UIButton)
{
let searchVC = self.storyboard?.instantiateViewController(withIdentifier: "SearchVC") as! SearchVC
self.navigationController?.pushViewController(searchVC, animated: false)
}
@IBAction func menuBtnAction(_ button: UIButton)
{
if button.tag == 1002
{
let myAdsVC = self.storyboard?.instantiateViewController(withIdentifier: "MyAdsController") as! MyAdsController
self.navigationController?.pushViewController(myAdsVC, animated: false)
}
else if button.tag == 1003
{
if defaults.bool(forKey: "isLogin") == false
{
let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
let navController = UINavigationController(rootViewController: loginVC)
self.present(navController, animated:true, completion: nil)
}
else
{
adDetailObj = AdDetailObject()
let adPostVC = self.storyboard?.instantiateViewController(withIdentifier: "AdPostVC") as! AdPostVC
let navController = UINavigationController(rootViewController: adPostVC)
navController.navigationBar.isHidden = true
navController.modalPresentationStyle = .fullScreen
self.present(navController, animated:true, completion: nil)
}
}
else if button.tag == 1004
{
if defaults.bool(forKey: "isLogin") == false
{
let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
let navController = UINavigationController(rootViewController: loginVC)
self.present(navController, animated:true, completion: nil)
}
else
{
let favouritesVC = self.storyboard?.instantiateViewController(withIdentifier: "FavouritesVC") as! FavouritesVC
self.navigationController?.pushViewController(favouritesVC, animated: false)
}
}
else if button.tag == 1005
{
if defaults.bool(forKey: "isLogin") == false
{
let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
let navController = UINavigationController(rootViewController: loginVC)
self.present(navController, animated:true, completion: nil)
}
else
{
let messagesVC = self.storyboard?.instantiateViewController(withIdentifier: "MessagesController") as! MessagesController
self.navigationController?.pushViewController(messagesVC, animated: false)
}
}
}
//MARK:- API Call
func homeData()
{
categoryArray.removeAll()
latestAdsArray.removeAll()
let savedLat = defaults.double(forKey: "latitude")
let savedLng = defaults.double(forKey: "longitude")
if savedLat > 0 && userDetail?.lat == latitude
{
userDetail?.lat = savedLat
}
if savedLng > 0 && userDetail?.lng == longitude
{
userDetail?.lng = savedLng
}
let parameter: [String: Any] = ["user_id" : self.defaults.integer(forKey: "userID"), "latitude": userDetail?.lat ?? latitude, "longitude" : userDetail?.lng ?? longitude]
print(parameter)
AddsHandler.homeData(parameter: parameter as NSDictionary, success: { (successResponse) in
self.stopAnimating()
if successResponse.success {
categoryArray = successResponse.categories
self.latestAdsArray = successResponse.adsData
if successResponse.userActivation == "1"
{
print("active.......")
userDetail?.id = self.defaults.integer(forKey: "userID")
userDetail?.displayName = self.defaults.string(forKey: "displayName")
userDetail?.userEmail = self.defaults.string(forKey: "userEmail")
userDetail?.joining = self.defaults.string(forKey: "joining")
userDetail?.profileImg = self.defaults.string(forKey: "url")
if userDetail?.userEmail != nil
{
self.createFirebaseUser(email: (userDetail?.userEmail)!)
}
}
else
{
print("inactive.......")
userDetail = UserObject()
adDetailObj = AdDetailObject()
self.defaults.set("",forKey: "userID")
self.defaults.set("",forKey: "displayName")
self.defaults.set("",forKey: "userEmail")
self.defaults.set("",forKey: "joining")
self.defaults.set("", forKey: "url")
signoutFlag = true
self.defaults.set(false, forKey: "isLogin")
self.defaults.set(false, forKey: "isGuest")
self.defaults.set(false, forKey: "isSocial")
FacebookAuthentication.signOut()
GoogleAuthenctication.signOut()
try! Auth.auth().signOut()
}
self.tableView.reloadData()
} else {
let alert = Constants.showBasicAlert(message: successResponse.message)
self.presentVC(alert)
}
}) { (error) in
self.stopAnimating()
let alert = Constants.showBasicAlert(message: NSLocalizedString(String(format: "something_%@", languageCode), comment: ""))
self.presentVC(alert)
}
}
func createFirebaseUser(email: String)
{
Auth.auth().createUser(withEmail: email, password: "Sprint1234!") { (user, error) in
if error == nil {
let databaseRef = Database.database().reference()
// var data = NSData()
// data = UIImageJPEGRepresentation(UIImage(named: ""), 0.8)! as NSData
// let storageRef = Storage.storage().reference()
// let filePath = "\(Auth.auth().currentUser!.uid)/\("imgUserProfile")"
// let metaData = StorageMetadata()
// metaData.contentType = "image/jpg"
// storageRef.child(filePath).putData(data as Data, metadata: metaData){(metaData,error) in
// if let error = error {
// print(error.localizedDescription)
// return
// }
// }
self.sendChatToken(chatToken: user?.user.uid ?? "")
print("User registered for chat")
databaseRef.child("users").child((user?.user.uid)!).setValue(["username": ["Firstname": userDetail?.displayName, "Lastname": ""]])
}
else
{
Auth.auth().signIn(withEmail: userDetail?.userEmail ?? "", password: "Sprint1234!") { (user, error) in
if error == nil {
print("User loggedin for chat......")
}
else
{
print("zain2")
print("User not loggedin for chat.....")
}
}
}
}
}
func sendChatToken(chatToken: String) {
if chatToken != ""
{
let param: [String: Any] = ["fc_token": chatToken, "user_id": userDetail?.id ?? 0]
print(param)
AddsHandler.sendFirebaseChatToken(parameter: param as NSDictionary, success: { (successResponse) in
print(successResponse)
}) { (error) in
self.stopAnimating()
// let alert = Constants.showBasicAlert(message: NSLocalizedString(String(format: "something_%@", languageCode), comment: ""))
// self.presentVC(alert)
}
}
}
@objc func nokri_showNavController1(){
let scrollPoint = CGPoint(x: 0, y: 0)
self.tableView.setContentOffset(scrollPoint, animated: true)
}
@objc func showAd(){
currentVc = self
}
@objc func showAd2(){
currentVc = self
}
//MARK:- Send fcm token to server
func sendFCMToken() {
var fcmToken = ""
if let token = defaults.value(forKey: "fcmToken") as? String {
fcmToken = token
} else {
fcmToken = appDelegate.deviceFcmToken
}
let param: [String: Any] = ["firebase_id": fcmToken]
print(param)
AddsHandler.sendFirebaseToken(parameter: param as NSDictionary, success: { (successResponse) in
self.stopAnimating()
print(successResponse)
}) { (error) in
self.stopAnimating()
// let alert = Constants.showBasicAlert(message: NSLocalizedString(String(format: "something_%@", languageCode), comment: ""))
// self.presentVC(alert)
}
}
//MARK:- Make Add Favourites
func makeAddFavourite(param: NSDictionary) {
self.showLoader()
AddsHandler.makeAddFavourite(parameter: param, success: { (successResponse) in
self.stopAnimating()
if successResponse.success {
var currentIndex = 0
for var post in self.latestAdsArray
{
if post.id == (param.value(forKey: "ad_id") as! Int)
{
post.isFavorite = true
self.latestAdsArray[currentIndex] = post
break
}
currentIndex += 1
}
self.tableView.reloadData()
}
else {
let alert = Constants.showBasicAlert(message: NSLocalizedString(String(format: "add_fav_%@", languageCode), comment: ""))
self.presentVC(alert)
}
}) { (error) in
self.stopAnimating()
let alert = Constants.showBasicAlert(message: NSLocalizedString(String(format: "something_%@", languageCode), comment: ""))
self.presentVC(alert)
}
}
}
extension CLPlacemark {
var compactAddress: String? {
if let name = subLocality {
var result = name
if let country = locality {
result += ", \(country)"
}
return result
}
else
{
return "UAE"
}
}
var currentCountry: String?
{
if let country = locality
{
return country
}
return nil
}
var locationName: String?
{
if let area = subLocality
{
return area
}
else if let area = locality
{
return area
}
else
{
return administrativeArea
}
}
}
class DynamicHeightCollectionView: UICollectionView
{
override func layoutSubviews()
{
super.layoutSubviews()
if bounds.size != intrinsicContentSize {
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize
{
return collectionViewLayout.collectionViewContentSize
}
}
|
//STRINGS
//a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable.
import UIKit
var str: String = "Hello, playground"
var xValue: Int = 50;
var firstName = "Jack";
var lastName = "Bauer";
var age: Int = 50;
var fullName = firstName + " " + lastName;
var fullName2 = "\(firstName) \(lastName) is \(age)" //String interpolation
fullName.append(" III");
var bookTitle = "heart of darkness";
bookTitle = bookTitle.capitalized;
bookTitle = bookTitle.lowercased();
//Curse words
var sentence = "What the f**k? You b***h";
if(sentence.contains("f**k") || sentence.contains("b***h"))
{
sentence.replacingOccurrences(of: "f**k", with: "fish");
sentence.replacingOccurrences(of: "b***h", with: "borito");
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
|
//
// ZoneTextWidget.swift
// Seriously
//
// Created by Jonathan Sand on 10/27/16.
// Copyright © 2016 Jonathan Sand. All rights reserved.
//
import Foundation
#if os(OSX)
import Cocoa
#elseif os(iOS)
import UIKit
#endif
enum ZTextType: Int {
case prefix
case name
case suffix
}
class ZoneTextWidget: ZTextField, ZTextFieldDelegate, ZToolTipper, ZGeneric {
override var debugName : String { return widgetZone?.zoneName ?? kUnknown }
var widgetZone : Zone? { return widget?.widgetZone }
var controller : ZMapController? { return widget?.controller }
weak var widget : ZoneWidget?
var type = ZTextType.name
var drawnSize = CGSize.zero
var isHovering = false
open func validateMenuItem(_ menuItem: ZMenuItem) -> Bool { return true }
var selectionRange: NSRange {
var range = gTextEditor.selectedRange
if range.length < 1 {
range.length = 1
if range.location > 0 {
range.location -= 1
}
}
return range
}
func updateTextColor() {
if gDragging.isDragged(widgetZone) {
textColor = gActiveColor
} else if gIsEssayMode, widgetZone?.isInBigMap ?? true {
textColor = kClearColor
} else if let tColor = widgetZone?.textColor,
let wColor = widgetZone?.lighterColor?.invertedBlackAndWhite,
let isLinear = widget?.isLinearMode {
let plain = !gDrawCirclesAroundIdeas
textColor = (isLinear || plain) ? tColor : wColor
}
}
func controllerSetup(with mapView: ZMapView?) {
delegate = self
isBordered = false
textAlignment = .left
backgroundColor = kClearColor
zlayer.backgroundColor = kClearColor.cgColor
font = widget?.controller?.font ?? gSmallFont
#if os(iOS)
autocapitalizationType = .none
#else
isEditable = widgetZone?.userCanWrite ?? false
#endif
}
override func menu(for event: ZEvent) -> ZMenu? {
let contextualMenu = controller?.ideaContextualMenu
contextualMenu?.textWidget = self
return contextualMenu
}
func updateText(isEditing: Bool = false) {
gTextEditor.updateText(inZone: widgetZone, isEditing: isEditing)
}
func updateChildrenViewDrawnSizesOfAllAncestors() {
widgetZone?.traverseAncestors { ancestor in
if let widget = ancestor.widget {
widget.updateLinesViewDrawnSize()
widget.updateWidgetDrawnSize()
return .eContinue
}
return .eStop
}
}
func updateFrameSize() {
setFrameSize(drawnSize)
}
func updateGUI() {
updateChildrenViewDrawnSizesOfAllAncestors()
controller?.layoutForCurrentScrollOffset()
}
func setText(_ iText: String?) {
text = iText
updateSize()
}
func updateSize() {
if let f = font,
let size = text?.sizeWithFont(f) {
let hide = widgetZone?.isFavoritesHere ?? false
let width = hide ? .zero : size.width + 6.0
let height = size.height + (controller?.dotHalfWidth ?? .zero * 0.8)
drawnSize = CGSize(width: width, height: height)
}
}
func offset(for selectedRange: NSRange, _ atStart: Bool) -> CGFloat? {
if let name = widgetZone?.unwrappedName,
let f = font {
let offset = name.offset(using: f, for: selectedRange, atStart: atStart)
var rect = name.rectWithFont(f)
rect = convert(rect, to: nil)
return rect.minX + offset
}
return nil
}
override func mouseDown(with event: ZEvent) {
if !gRefusesFirstResponder, window == gMainWindow { // ignore mouse down during startup
gTemporarilySetMouseDownLocation(event.locationInWindow.x)
gTemporarilySetMouseZone(widgetZone)
if !becomeFirstResponder() {
super.mouseDown(with: event)
}
}
}
@discardableResult override func becomeFirstResponder() -> Bool {
printDebug(.dEdit, " TRY " + (widgetZone?.unwrappedName ?? kEmpty))
if !isFirstResponder,
let zone = widgetZone,
zone.canEditNow, // detect if mouse down inside widget OR key pressed
super.becomeFirstResponder() { // becomeFirstResponder is called first so delegate methods will be called
if gIsSearching {
gExitSearchMode()
} else if gIsEssayMode {
gControllers.swapMapAndEssay()
} else {
gSetEditIdeaMode()
}
gSelecting.ungrabAll(retaining: [zone])
printDebug(.dEdit, " RESPOND " + zone.unwrappedName)
gTextEditor.edit(zone, setOffset: gTextOffset)
return true
}
return false
}
func selectCharacter(in range: NSRange) {
#if os(OSX)
if let e = currentEditor() {
e.selectedRange = range
}
#endif
}
func alterCase(up: Bool) {
if var t = text {
t = up ? t.uppercased() : t.lowercased()
gTextEditor.assign(t, to: widgetZone)
updateGUI()
}
}
func swapWithParent() {
if let zone = widgetZone,
let saved = text {
let range = gTextEditor.selectedRange
zone.swapWithParent {
gRelayoutMaps(for: zone) {
zone.zoneName = saved
zone.editAndSelect(range: range)
}
}
}
}
func extractTitleOrSelectedText(requiresAllOrTitleSelected: Bool = false) -> String? {
var extract = extractedTitle
if let original = text, gIsEditIdeaMode {
let range = gTextEditor.selectedRange
extract = original.substring(with: range)
if range.length < original.length {
if !requiresAllOrTitleSelected {
setText(original.stringBySmartReplacing(range, with: kEmpty))
gSelecting.ungrabAll()
} else if range.location != 0 && !original.isLineTitle(enclosing: range) {
extract = nil
}
}
}
return extract
}
var extractedTitle: String? {
var extract = text
if let original = text {
let substrings = original.components(separatedBy: kHalfLineOfDashes)
if substrings.count > 1 {
extract = substrings[1].spacesStripped
}
}
return extract
}
override func draw(_ iDirtyRect: CGRect) {
updateTextColor()
super.draw(iDirtyRect)
if !isFirstResponder,
gIsMapOrEditIdeaMode,
let zone = widgetZone,
!zone.isGrabbed,
zone.isTraveller {
// /////////////////////////////////////////////////////
// draw line underneath text indicating it can travel //
// /////////////////////////////////////////////////////
let deltaX = min(3.0, iDirtyRect.width / 2.0)
let inset = CGFloat(0.5)
var rect = iDirtyRect.insetBy(dx: deltaX, dy: inset)
rect.size.height = .zero
rect .origin.y = iDirtyRect.maxY - 1.0
let path = ZBezierPath(rect: rect)
path .lineWidth = 0.4
zone.color?.setStroke()
path.stroke()
}
}
}
|
//
// LogTableViewController.swift
// CountApp
//
// Created by Daiki Uchiyama on 2020/09/20.
// Copyright © 2020 Daiki Uchiyama. All rights reserved.
//
import UIKit
import RealmSwift
class LogTableViewController: UITableViewController {
let MV = MainViewController()
var items: Results<TableItem>!
/* -- 基本背景色 -- */
let backGroundColor = UIColor(red: 245/255, green: 245/255, blue: 245/255, alpha: 1)
override func viewDidLoad() {
super.viewDidLoad()
let realm = try! Realm()
self.items = realm.objects(TableItem.self)
print(items.count)
//背景色設定
self.view.backgroundColor = backGroundColor
}
override func viewWillAppear(_ animated: Bool) {
tableView.reloadData()
}
// 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 {
return self.items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
var date = cell.viewWithTag(1) as! UILabel
var progress = cell.viewWithTag(2) as! UILabel
var target = cell.viewWithTag(3) as! UILabel
let tableItem: TableItem = self.items[indexPath.row]
date.text = tableItem.date
progress.text = tableItem.progress
target.text = tableItem.target
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return view.frame.size.height / 8
}
// override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
//
// // 先にデータを削除しないと、エラーが発生します。
// self.tableData.remove(at: indexPath.row)
// tableView.deleteRows(at: [indexPath], with: .automatic)
// }
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// 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: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let realm = try! Realm()
self.items = realm.objects(TableItem.self)
try! realm.write {
realm.delete(items[indexPath.row])
}
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// EVARecieveEtherVC.swift
// EVA Wallet
//
// Created by Charlie Morris on 9/16/16.
// Copyright © 2016 Flailing Whale. All rights reserved.
//
import UIKit
class EVARecieveEtherVC: UIViewController {
// =========
// LIFECYCLE
// =========
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var prefersStatusBarHidden: Bool {
get {
return true
}
}
// =======
// ACTIONS
// =======
@IBAction func downButtonTapped(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}
|
//
// KeyboardKeyCollectionViewCell.swift
// DemoKeyboard
//
// Created by admin on 05/03/21.
//
import UIKit
class KeyboardKeyCollectionViewCell: UICollectionViewCell {
@IBOutlet var imgDisplay: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
|
import Foundation
/*
MAKING A PLAN
A common problem solving model is known as input-process-output.
1. What are the possible inputs I can expect to receive?
2. How should each type of input be processed?
3. What should the output be in each case?
It can be helpful to organize this into a table. Here's an example:
http://russellgordon.ca/rsgc/2016-17/ics3u/IPO-example.jpg
*/
/*
IMPLEMENT THE PLAN
A good way to orgaize your code is to separate your code into the three sections - input, process, output – as much as possible.
The start of a solution is implemented below. Consider all the possible inputs. Can you finish the solution?
*/
/*
INPUT
Be sure that your implementation of this section discards all the possible bad inputs the user could provide.
*/
var inputToProcess : String = ""
// Loop until valid input is received
while inputToProcess == "" {
// Show the prompt
print("Ask the question here? ", terminator: "")
// Get the user's input
var input : String?
input = readLine()
// Use optional binding to see if the string can be unwrapped (to see if it is not nil)
if let notNilInput = input {
// You probably need to add additional checks to be sure the
// input received is valid
// Add checks as needed...
// Save the input given, as we are certain it's what we are looking for now
inputToProcess = notNilInput
}
}
/*
PROCESS
Here is where you implement the logic that solves the problem at hand.
(e.g.: in past exercises, verify that a number is prime, for example).
Of course, what goes here in your code varies, depending on the problem you are solving.
*/
// Add 'process' code below....
print("replace with process logic")
/*
OUTPUT
Here is where you report the results of the 'process' section above.
*/
// Add 'output' code below... replace what is here as needed.
print("The input given was: \(inputToProcess)")
|
//
// File.swift
//
//
// Created by Michal Ziobro on 09/07/2020.
//
import Foundation
public enum Authorization {
case noAuth
case bearerToken(token : String)
case queryParams(_ params: [String:Any])
}
public protocol IRouter: Requestable, MultipartUploading, Encoder {
static var baseURL: String { get }
var path: String { get }
var isFullPath: Bool { get }
var method: HTTPMethod { get }
var headerParams: [String: String] { get }
var authorization: Authorization { get }
var queryParams: [String:Any] { get }
var bodyParams: [String: Any] { get }
var bodyEncoding: EncodingType { get }
var files: [FileUploadInfo]? { get }
}
|
//
// GZFlingCarryingView.swift
// GZFlingViewDemo
//
// Created by Grady Zhuo on 12/11/14.
// Copyright (c) 2014 Grady Zhuo. All rights reserved.
//
import UIKit
public enum GZFlingCarryingViewTemplateType{
case Xib(UINib)
case Class(GZFlingCarryingView.Type)
}
public class GZFlingCarryingViewTemplate:NSObject {
public internal(set) var type:GZFlingCarryingViewTemplateType
public init(cls: GZFlingCarryingView.Type){
self.type = .Class(cls)
}
public init(nibName: String, inBundle bundle:NSBundle!){
self.type = .Xib(UINib(nibName: nibName, bundle: bundle))
}
public init(xib: UINib){
self.type = .Xib(xib)
}
internal func instantiate() -> GZFlingCarryingView? {
if case let .Class(cls) = self.type {
let carryingView = cls.init()
return carryingView
}
if case let .Xib(xib) = self.type {
let views = xib.instantiateWithOwner(nil, options: nil)
if let carryingView = views.first as? GZFlingCarryingView {
return carryingView
}else{
return nil
}
}
return nil
}
}
public class GZFlingCarryingView: UIView {
public var flingIndex:Int = 0
public var flingView:GZFlingView!
@IBOutlet public var customView:UIView! = UIView(){
willSet{
if (newValue != customView) {
self.customView?.removeFromSuperview()
}
}
didSet{
if oldValue != customView {
self.addSubview(customView!)
}
}
}
public convenience init(customView:UIView!) {
self.init(frame: .zero)
self.customView = customView
self.addSubview(customView)
self.initialize()
}
func initialize(){
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.mainScreen().scale
}
public func prepareForReuse(){
}
deinit{
// GZDebugLog("GZFlingCarryingView is deinit")
}
override public func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSetAllowsAntialiasing(context, true)
CGContextSetShouldAntialias(context, true)
}
}
|
//
// NavigationViews.swift
// Basics
//
// Created by Venkatnarayansetty, Badarinath on 11/2/19.
// Copyright © 2019 Badarinath Venkatnarayansetty. All rights reserved.
//
import Foundation
import SwiftUI
//Key Notes : Navigation view should be present inside VStack.
struct DetailView: View {
// environment variable to access presentationMode property ( useful for dismissing the view )
@Environment(\.presentationMode) var presentationMode
var body: some View {
VStack {
Text("Detail View")
}
.navigationBarBackButtonHidden(true) // hide the system button
.navigationBarItems(leading: Button(action: {
self.presentationMode.wrappedValue.dismiss()
}){
HStack{
Image(systemName: "arrow.left.circle")
Text("Go Back")
}
})
}
}
struct NavigationViews: View {
@State private var isHidden = false
var body: some View {
NavigationView {
ZStack {
Color.white.edgesIgnoringSafeArea(.bottom)
VStack {
NavigationLink("Go To Detail", destination: DetailView())
Toggle("Hide Navigation Bar" , isOn: $isHidden).padding()
}
.navigationBarTitle(Text("Navigation"))
.navigationBarItems(
leading:
Button(action: {}) {
Text("Actions").font(.body).accentColor(Color.pink)
},
trailing: Button(action : {}) {
Image(systemName: "bell.fill").accentColor(Color.pink)
})
.navigationBarHidden(isHidden)
}
}
}
}
|
//
// FoursquareDataManger.swift
// Demo
//
// Created by Henrik Rostgaard on 07/02/16.
// Copyright © 2016 35b.dk. All rights reserved.
//
import Foundation
import CoreLocation
class FoursquareDataManager : FoursquareDataMangerProtocol {
private let CLIENT_ID = "X0EB2PODK042RBHCFVULKL0QEAY1IPBYLIYZJGNUYWREIRJU"
private let CLIENT_SECRET = "<Insert Secret here>"
func loadFoursquareData(searchString: String, location: (Double, Double), completion: ([FoursquareDataModel], resultOk: Bool) -> Void) -> Void {
let session = NSURLSession.sharedSession()
let urlString = "https://api.foursquare.com/v2/venues/search?ll=\(location.0),\(location.1)&client_id=\(CLIENT_ID)&client_secret=\(CLIENT_SECRET)&v=20160207&query=\(searchString)&limit=50"
guard let url = NSURL(string: urlString) else {
completion([], resultOk: false)
return
}
session.dataTaskWithURL(url, completionHandler: {
(data, response, error) in
guard error == nil, let urlContent = data else {
completion([], resultOk: false)
return
}
self.parseJson(urlContent, completionHandler: completion)
}).resume()
}
private func parseJson(data: NSData, completionHandler: ([FoursquareDataModel], resultOk: Bool) -> Void) {
var json: [String: AnyObject]!
do {
json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as? [String: AnyObject]
} catch {
completionHandler([], resultOk: false)
}
guard let response = json["response"] as? [String: AnyObject],
let venues = response["venues"] as? [AnyObject] else {
completionHandler([], resultOk: false)
return
}
//Loop all venues at create FoursquareDataModel's (Using flatmap to remove any nil's (Venues not conform with expected json)
let result = venues.map {
(venue: AnyObject) -> FoursquareDataModel? in
guard let name = venue["name"] as? String,
let location = venue["location"] as? [String: AnyObject],
let distance = location["distance"] as? Int,
let address = location["formattedAddress"] as? [String] else {
return nil //This venue is not in expected format return nil (Will be removed later)
}
return FoursquareDataModel(name: name, address: address, distance: distance)
}.flatMap {$0}.sort({ $0.distance < $1.distance })
completionHandler(result, resultOk: true)
}
}
//Example of data from Foursquare..
/*
{
"meta": {
"code": 200,
"requestId": "56b723ea498ee943fb0994de"
},
"response": {
"venues": [{
"id": "4d64f6f94e1ea1cd848f4ab9",
"name": "SMC Biler Køge",
"contact": {
"phone": "+4556652001",
"formattedPhone": "+45 56 65 20 01"
},
"location": {
"address": "Tangmosevej 110",
"lat": 55.47548058238196,
"lng": 12.185584176356347,
"distance": 12173,
"postalCode": "4600",
"cc": "DK",
"city": "Køge",
"state": "Zealand",
"country": "Denmark",
"formattedAddress": ["Tangmosevej 110", "4600 Køge", "Denmark"]
},
"categories": [{
"id": "4bf58dd8d48988d124951735",
"name": "Automotive Shop",
"pluralName": "Automotive Shops",
"shortName": "Automotive",
"icon": {
"prefix": "https:\/\/ss3.4sqi.net\/img\/categories_v2\/shops\/automotive_",
"suffix": ".png"
},
"primary": true
}],
"verified": false,
"stats": {
"checkinsCount": 47,
"usersCount": 21,
"tipCount": 0
},
"allowMenuUrlEdit": true,
"specials": {
"count": 0,
"items": []
},
"hereNow": {
"count": 0,
"summary": "Nobody here",
"groups": []
},
"referralId": "v-1454842858",
"venueChains": []
}
*/ |
//
// GZEProfileViewModelReadOnly.swift
// Gooze
//
// Created by Yussel on 3/5/18.
// Copyright © 2018 Gooze. All rights reserved.
//
import UIKit
import ReactiveSwift
import ReactiveCocoa
import Result
import SwiftOverlays
import Gloss
class GZEProfileViewModelReadOnly: NSObject, GZEProfileViewModel {
// MARK - GZEProfileViewModel protocol
var mode = GZEProfileMode.contact {
didSet {
log.debug("mode set: \(self.mode)")
setMode()
}
}
let dateRequest: MutableProperty<GZEDateRequest?>
var acceptRequestAction: Action<Void, GZEDateRequest, GZEError>!
var bottomButtonAction: CocoaAction<GZEButton>?
let loading = MutableProperty<Bool>(false)
let error = MutableProperty<String?>(nil)
let actionButtonIsHidden = MutableProperty<Bool>(false)
let actionButtonTitle = MutableProperty<String>("")
weak var controller: UIViewController?
let (didLoad, didLoadObs) = Signal<Void, NoError>.pipe()
func startObservers() {
self.appearObs.send(value: ())
self.observeRequests()
self.observeSocketEvents()
self.dateRequest.producer
.take(until: self.disappearSignal)
.on(disposed: {log.debug("dateRequest observer disposed")})
.startWithValues{[weak self] dateRequest in
log.debug("dateRequest didSet: \(String(describing: dateRequest))")
guard let this = self else {return}
if let dateRequest = dateRequest {
GZEDatesService.shared.activeRequest = MutableProperty(dateRequest)
} else {
GZEDatesService.shared.activeRequest = nil
}
this.setMode()
}
}
func stopObservers() {
self.disappearObs.send(value: ())
self.stopObservingSocketEvents()
self.stopObservingRequests()
if let activeRequest = GZEDatesService.shared.activeRequest {
activeRequest.signal
.take(until: self.appearSignal)
.observeValues {[weak self] dateRequest in
log.debug("dateRequest didSet: \(String(describing: dateRequest))")
guard let this = self else {return}
this.dateRequest.value = dateRequest
}
}
}
// End GZEProfileViewModel protocol
let user: GZEUser
let contactButtonTitle = "vm.profile.contactTitle".localized().uppercased()
let acceptRequestButtonTitle = "vm.profile.acceptRequestTitle".localized().uppercased()
let acceptedRequestButtonTitle = "vm.profile.acceptedRequestButtonTitle".localized().uppercased()
let rejectedRequestButtonTitle = "vm.profile.rejectedRequestButtonTitle".localized().uppercased()
let sentRequestButtonTitle = "vm.profile.sentRequestButtonTitle".localized().uppercased()
let endedRequestButtonTitle = "vm.profile.endedRequestButtonTitle".localized().uppercased()
let addPayPalAccountRequest = "vm.profile.addPayPalAccountRequest".localized()
let addPayPalAccountAnswerAdd = "vm.profile.addPayPalAccountAnswerAdd".localized()
let addPayPalAccountAnswerLater = "vm.profile.addPayPalAccountAnswerLater".localized()
let addPaymentMethodRequest = "vm.profile.addPaymentMethodRequest".localized()
let addPaymentMethodAnswerAdd = "vm.profile.addPaymentMethodAnswerAdd".localized()
let addPaymentMethodAnswerLater = "vm.profile.addPaymentMethodAnswerLater".localized()
let completeProfileRequest = "vm.profile.completeProfileRequest".localized()
let completeProfileRequestYes = "vm.profile.completeProfileRequestYes".localized()
let completeProfileRequestNo = "vm.profile.completeProfileRequestNo".localized()
let isContactButtonEnabled = MutableProperty<Bool>(false)
var messagesObserver: Disposable?
var requestsObserver: Disposable?
var socketEventsObserver: Disposable?
var (disappearSignal, disappearObs) = Signal<Void, NoError>.pipe()
var (appearSignal, appearObs) = Signal<Void, NoError>.pipe()
var chatViewModel: GZEChatViewModel? {
log.debug("chatViewModel called")
guard let daRequestProperty = GZEDatesService.shared.activeRequest else {
log.error("Unable to open the chat, found nil active date request")
error.value = "service.chat.invalidChatId".localized()
return nil
}
guard let chat = self.dateRequest.value?.chat else {
log.error("Unable to open the chat, found nil chat on date request")
error.value = "service.chat.invalidChatId".localized()
return nil
}
var chatMode: GZEChatViewMode
if self.mode == .request {
chatMode = .gooze
} else {
chatMode = .client
}
return GZEChatViewModelDates(chat: chat, dateRequest: daRequestProperty, mode: chatMode, username: self.user.username)
}
var registerPayPalViewModel: GZERegisterPayPalViewModel {
return GZERegisterPayPalViewModel()
}
var paymentsViewModel: GZEPaymentMethodsViewModel {
return GZEPaymentMethodsViewModelAdded()
}
// MARK - init
init(user: GZEUser, dateRequest: MutableProperty<GZEDateRequest?>) {
self.user = user
self.dateRequest = dateRequest
super.init()
log.debug("\(self) init")
self.getUpdatedRequest(dateRequest.value?.id)
let acceptRequestAction = self.createAcceptRequestAction()
acceptRequestAction.events.observeValues {[weak self] in
self?.onAcceptRequestAction($0)
}
self.bottomButtonAction = CocoaAction(acceptRequestAction) { [weak self] _ in
self?.loading.value = true
}
}
private func createAcceptRequestAction() -> Action<Void, GZEDateRequest, GZEError> {
return Action(enabledIf: isContactButtonEnabled) {[weak self] in
guard let this = self else {
log.error("self disposed before used");
return SignalProducer(error: .repository(error: .UnexpectedError))
}
if this.mode == .request {
if let dateRequest = this.dateRequest.value {
switch dateRequest.status {
case .sent,
.received:
return GZEDatesService.shared.acceptDateRequest(withId: this.dateRequest.value?.id)
case .accepted, .onDate:
this.openChat()
return SignalProducer.empty
case .rejected, .ended:
return SignalProducer.empty
}
} else {
return SignalProducer.empty
}
} else {
if let dateRequest = this.dateRequest.value {
switch dateRequest.status {
case .sent,
.received,
.rejected,
.ended:
break
case .accepted, .onDate:
this.openChat()
}
} else {
return GZEDatesService.shared.requestDate(to: this.user.id)
}
return SignalProducer.empty
}
}
}
private func onAcceptRequestAction(_ event: Event<GZEDateRequest, GZEError>) {
log.debug("event received: \(event)")
self.loading.value = false
switch event {
case .value(let dateRequest):
GZEDatesService.shared.upsert(dateRequest: dateRequest)
self.dateRequest.value = dateRequest
switch self.mode {
case .request:
self.openChat()
case .contact:
self.error.value = "service.dates.requestSuccessfullySent".localized()
}
case .failed(let error):
onError(error)
default: break
}
}
private func onError(_ error: GZEError) {
switch error {
case .datesSocket(let datesError):
if datesError == .payPalAccountRequired {
GZEAlertService.shared.showConfirmDialog(
title: error.localizedDescription,
message: addPayPalAccountRequest,
buttonTitles: [addPayPalAccountAnswerAdd],
cancelButtonTitle: addPayPalAccountAnswerLater,
actionHandler: {[weak self] (_, _, _) in
log.debug("Add pressed")
self?.openRegisterPayPalView()
},
cancelHandler: { _ in
log.debug("Cancel pressed")
}
)
return
}
if datesError == .paymentMethodRequired {
GZEAlertService.shared.showConfirmDialog(
title: error.localizedDescription,
message: addPaymentMethodRequest,
buttonTitles: [addPaymentMethodAnswerAdd],
cancelButtonTitle: addPaymentMethodAnswerLater,
actionHandler: {[weak self] (_, _, _) in
log.debug("Add pressed")
self?.openAddPaymentMethodsView()
},
cancelHandler: { _ in
log.debug("Cancel pressed")
}
)
return
}
case .repository(let repoErr):
switch repoErr {
case .GZEApiError(let apiErr):
if apiErr.code == GZEApiError.Code.userIncompleteProfile.rawValue {
var missingProperties: [String] = []
if let detailsJson = apiErr.details?.json {
missingProperties = ("missingProperties" <~~ detailsJson) ?? []
}
GZEAlertService.shared.showConfirmDialog(
title: "validation.profile.incomplete".localized(),
message: "\(missingProperties.map{GZEUser.Validation(rawValue: $0)?.fieldName ?? $0}.joined(separator: ", ")).\n\n\(completeProfileRequest)",
buttonTitles: [completeProfileRequestYes],
cancelButtonTitle: completeProfileRequestNo,
actionHandler: {[weak self] (_, _, _) in
log.debug("Yes pressed")
guard let this = self else {return}
this.openMyProfileView()
},
cancelHandler: { _ in
log.debug("No pressed")
}
)
return
}
default: break
}
default:
break
}
self.error.value = error.localizedDescription
}
private func setMode() {
setActionButtonTitle()
setActionButtonState()
}
private func setActionButtonTitle() {
log.debug("set action button title called")
if mode == .request {
if let dateRequest = self.dateRequest.value {
switch dateRequest.status {
case .sent,
.received:
self.actionButtonTitle.value = self.acceptRequestButtonTitle
case .accepted, .onDate:
self.actionButtonTitle.value = self.acceptedRequestButtonTitle
case .rejected:
self.actionButtonTitle.value = self.rejectedRequestButtonTitle
case .ended:
self.actionButtonTitle.value = self.endedRequestButtonTitle
}
} else {
self.actionButtonTitle.value = ""
}
} else {
if let dateRequest = dateRequest.value {
switch dateRequest.status {
case .sent,
.received:
self.actionButtonTitle.value = self.sentRequestButtonTitle
case .accepted, .onDate:
self.actionButtonTitle.value = self.acceptedRequestButtonTitle
case .rejected:
self.actionButtonTitle.value = self.rejectedRequestButtonTitle
case .ended:
self.actionButtonTitle.value = self.endedRequestButtonTitle
}
} else {
self.actionButtonTitle.value = self.contactButtonTitle
}
}
}
private func setActionButtonState() {
log.debug("set action button state called")
if mode == .request {
if let dateRequest = self.dateRequest.value {
switch dateRequest.status {
case .sent,
.received,
.accepted,
.onDate:
isContactButtonEnabled.value = true
case .rejected, .ended:
isContactButtonEnabled.value = false
}
} else {
isContactButtonEnabled.value = false
}
} else {
if let dateRequest = self.dateRequest.value {
switch dateRequest.status {
case .sent,
.received,
.rejected,
.ended:
isContactButtonEnabled.value = false
case .accepted, .onDate:
isContactButtonEnabled.value = true
}
} else {
isContactButtonEnabled.value = true
}
}
}
private func openChat() {
log.debug("open chat called")
guard
let controller = self.controller as? GZEProfilePageViewController,
let chatViewModel = self.chatViewModel
else {
log.error("Unable to open chat view GZEProfilePageViewController is not set")
return
}
controller.performSegue(withIdentifier: controller.segueToChat, sender: chatViewModel)
}
private func openRegisterPayPalView() {
log.debug("openRegisterPayPalView called")
guard
let controller = self.controller as? GZEProfilePageViewController
else {
log.error("Unable to payment view GZEProfilePageViewController is not set")
return
}
controller.performSegue(withIdentifier: controller.segueToRegisterPayPal, sender: self.registerPayPalViewModel)
}
private func openAddPaymentMethodsView() {
log.debug("openAddPaymentMethodsView called")
guard
let controller = self.controller as? GZEProfilePageViewController
else {
log.error("Unable to payment view GZEProfilePageViewController is not set")
return
}
controller.performSegue(withIdentifier: controller.segueToPayments, sender: self.paymentsViewModel)
}
private func openMyProfileView() {
log.debug("openMyProfileView called")
guard
let navController = self.controller?.navigationController,
let myProfileController = self.controller?.storyboard?.instantiateViewController(withIdentifier: "GZEProfilePageViewController") as? GZEProfilePageViewController
else {
log.error("Unable to open my profile view, failed to instantiate GZEProfilePageViewController")
return
}
guard let user = GZEAuthService.shared.authUser else {
log.error("Unable to open my profile view, Auth user not found")
return
}
myProfileController.profileVm = GZEProfileUserInfoViewModelMe(user)
myProfileController.ratingsVm = GZERatingsViewModelMe(user)
myProfileController.galleryVm = GZEGalleryViewModelMe(user)
navController.pushViewController(myProfileController, animated: true)
}
private func observeRequests() {
self.stopObservingRequests()
self.requestsObserver = (
Signal.merge([
GZEDatesService.shared.lastReceivedRequest.signal,
GZEDatesService.shared.lastSentRequest.signal
])
.skipNil()
.filter{[weak self] in
guard let this = self else { return false }
log.debug("filter called: \(String(describing: $0)) \(String(describing: this.dateRequest))")
return $0 == this.dateRequest.value
}
.observeValues {[weak self] updatedDateRequest in
log.debug("updatedDateRequest: \(String(describing: updatedDateRequest))")
self?.dateRequest.value = updatedDateRequest
}
)
}
private func stopObservingRequests() {
self.requestsObserver?.dispose()
self.requestsObserver = nil
}
private func observeSocketEvents() {
stopObservingSocketEvents()
self.socketEventsObserver = GZEDatesService.shared.dateSocket?
.socketEventsEmitter
.signal
.skipNil()
.filter { $0 == .authenticated }
.observeValues {[weak self] _ in
guard let this = self else {
log.error("self was disposed")
return
}
this.getUpdatedRequest(this.dateRequest.value?.id)
}
}
private func stopObservingSocketEvents() {
log.debug("stop observing SocketEvents")
self.socketEventsObserver?.dispose()
self.socketEventsObserver = nil
}
private func getUpdatedRequest(_ dateRequestId: String?) {
if let dateRequestId = dateRequestId {
let blocker = SwiftOverlays.showBlockingWaitOverlay()
GZEDatesService.shared.find(byId: dateRequestId)
.start{[weak self] event in
log.debug("find request event received: \(event)")
blocker.removeFromSuperview()
guard let this = self else {return}
switch event {
case .value(let dateRequest):
this.dateRequest.value = dateRequest
case .failed(let error):
log.error(error.localizedDescription)
default: break
}
}
}
}
// MARK: - Deinitializers
deinit {
GZEDatesService.shared.activeRequest = nil
log.debug("\(self) disposed")
}
}
|
//
// ETCPaymentDebugInformationController.swift
// Dash
//
// Created by Yuji Nakayama on 2020/01/13.
// Copyright © 2020 Yuji Nakayama. All rights reserved.
//
import UIKit
class ETCPaymentDebugInformationViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
var payment: ETCPaymentProtocol?
override func viewDidLoad() {
if let payment = payment {
textView.text = String(reflecting: payment)
} else {
textView.text = ""
}
}
}
|
import Foundation
import FigmaExportCore
final public class XcodeIconsExporter: XcodeImagesExporterBase {
public func export(icons: [ImagePack], append: Bool) throws -> [FileContents] {
// Generate metadata (Assets.xcassets/Icons/Contents.json)
let contentsFile = XcodeEmptyContents().makeFileContents(to: output.assetsFolderURL)
// Generate assets
let assetsFolderURL = output.assetsFolderURL
let preservesVectorRepresentation = output.preservesVectorRepresentation
let imageAssetsFiles = try icons.flatMap { imagePack -> [FileContents] in
let preservesVector = preservesVectorRepresentation?.first(where: { $0 == imagePack.name }) != nil
return try imagePack.makeFileContents(to: assetsFolderURL, preservesVector: preservesVector)
}
// Generate extensions
let imageNames = icons.map { $0.name }
let extensionFiles = try generateExtensions(names: imageNames, append: append)
return [contentsFile] + imageAssetsFiles + extensionFiles
}
}
|
//
// second.swift
// work2
//
// Created by tsui erh li on 2020/10/2.
//
import SwiftUI
struct secondView: View {
var body: some View {
Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
}
}
struct second_Previews: PreviewProvider {
static var previews: some View {
secondView()
}
}
|
//
// BidPage.swift
// Yelnur
//
// Created by Дастан Сабет on 28.03.2018.
// Copyright © 2018 Дастан Сабет. All rights reserved.
//
import UIKit
import Alamofire
class BidPage: UIViewController {
enum reuseIdentifiers: String {
case payment = "textFieldCell"
case transport = "transportCell"
case price = "priceCell"
case service = "serviceCell"
case shipping = "shippingCell"
case textview = "textViewCell"
}
lazy var tableView: UITableView = {
let tableview = UITableView(frame: .zero, style: .grouped)
tableview.delegate = self
tableview.dataSource = self
tableview.backgroundColor = UIColor(hex: "232323")
tableview.separatorStyle = .none
tableview.register(PriceAmountCell.self, forCellReuseIdentifier: reuseIdentifiers.price.rawValue)
tableview.register(DarkTextFieldCell.self, forCellReuseIdentifier: reuseIdentifiers.payment.rawValue)
tableview.register(DarkTextFieldCell.self, forCellReuseIdentifier: reuseIdentifiers.transport.rawValue)
tableview.register(DarkTextFieldCell.self, forCellReuseIdentifier: reuseIdentifiers.service.rawValue)
tableview.register(DarkTextFieldCell.self, forCellReuseIdentifier: reuseIdentifiers.shipping.rawValue)
tableview.register(TextViewCell.self, forCellReuseIdentifier: reuseIdentifiers.textview.rawValue)
return tableview
}()
let messageView = Message.view.showMB()
var offer: Offer?
var order: Order?
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
offer = Offer(comment: "", transport_id: -1, transport_name: "", transport_number: "", price: -1, currency: Strings.amountTengeSymbol, payment_type: -1, payment_name: "", other_service: -1, other_service_name: "", shipping_type: -1, shipping_name: "")
navigationItem.title = Strings.suggestPrice
let rightBarButtonItem = UIBarButtonItem(title: Strings.done, style: .plain, target: self, action: #selector(handleBid))
navigationItem.rightBarButtonItem = rightBarButtonItem
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.isTranslucent = false
navigationController?.addShadow()
}
@objc func handleBid() {
if offer?.price == -1 {
Alert.alert(message: Strings.writePrice, controller: self)
}else if offer?.transport_id == -1 {
Alert.alert(message: "\(Strings.choose) \(Strings.transportLowerCase)", controller: self)
}else if offer?.payment_type == -1 {
Alert.alert(message: "\(Strings.choose) \(Strings.writePaymentType)", controller: self)
}else if offer?.other_service == -1 {
Alert.alert(message: "\(Strings.choose) \(Strings.otherService)", controller: self)
}else if offer?.shipping_type == -1 {
Alert.alert(message: "\(Strings.choose) \(Strings.shippingOnOff)", controller: self)
}else if offer?.comment.count == 0 {
Alert.alert(message: Strings.writeComment, controller: self)
}else {
let parameters: Parameters = [
"transport_id" : "\(offer!.transport_id)",
"price" : "\(offer!.price)",
"payment_type" : "\(offer!.payment_type)",
"other_service" : "\(offer!.other_service)",
"shipping_type" : "\(offer!.shipping_type)",
"currency" : "\(offer!.currency)",
"comment" : "\(offer!.comment)",
]
print("PRAMS: ", parameters)
messageView.show(animated: true)
API.shared.fetch(with: Router.Courier.Offer.create(endPoint: "\(order!.id)/offer/", params: parameters), onSuccess: { (response) in
switch response {
case .raw(_):
let alert = UIAlertController(title: Strings.successfullySent, message: nil, preferredStyle: .alert)
let ok = UIAlertAction(title: Strings.ok, style: .default, handler: { (_) in
if let controller = self.navigationController?.viewControllers.first as? CourierOrdersPage {
if let subController = controller.client_controllers.first as? OrderCourierPage {
subController.getOrders()
}
}
self.navigationController?.popToRootViewController(animated: true)
self.messageView.hide(animated: true)
})
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
}
}) { (error) in
Alert.alert(message: error.message, controller: self)
self.messageView.hide(animated: true)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension BidPage: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let priceCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifiers.price.rawValue, for: indexPath) as! PriceAmountCell
priceCell.dark = true
priceCell.delegate = self
if offer?.price == -1 {
priceCell.price.text = nil
}else {
priceCell.price.text = "\(offer!.price)"
}
priceCell._amount.text = offer?.currency
return priceCell
}else if indexPath.row == 1 {
let transportCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifiers.transport.rawValue, for: indexPath) as! DarkTextFieldCell
transportCell.placeHolder = Strings.transport
transportCell.accessoryType = .disclosureIndicator
transportCell.textField.isUserInteractionEnabled = false
transportCell.textField.text = offer?.transport_name
transportCell.delegate = self
transportCell.indexPath = indexPath
return transportCell
}else if indexPath.row == 2 {
let priceCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifiers.payment.rawValue, for: indexPath) as! DarkTextFieldCell
priceCell.placeHolder = Strings.paymentType
priceCell.accessoryType = .disclosureIndicator
priceCell.textField.isUserInteractionEnabled = false
priceCell.textField.text = offer?.payment_name
priceCell.indexPath = indexPath
priceCell.delegate = self
return priceCell
}else if indexPath.row == 3 {
let serviceCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifiers.service.rawValue, for: indexPath) as! DarkTextFieldCell
serviceCell.placeHolder = Strings.otherService
serviceCell.accessoryType = .disclosureIndicator
serviceCell.textField.isUserInteractionEnabled = false
serviceCell.textField.text = offer?.other_service_name
serviceCell.indexPath = indexPath
serviceCell.delegate = self
return serviceCell
}else if indexPath.row == 4 {
let shippingCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifiers.shipping.rawValue, for: indexPath) as! DarkTextFieldCell
shippingCell.placeHolder = Strings.shippingOnOff
shippingCell.accessoryType = .disclosureIndicator
shippingCell.textField.isUserInteractionEnabled = false
shippingCell.textField.text = offer?.shipping_name
shippingCell.indexPath = indexPath
shippingCell.delegate = self
return shippingCell
}else {
let commentCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifiers.textview.rawValue, for: indexPath) as! TextViewCell
commentCell.placeHolder = Strings.comment
commentCell.backgroundColor = UIColor(hex: "333333")
commentCell.tintColor = UIColor.white
commentCell.textView.backgroundColor = UIColor(hex: "333333")
commentCell.textView.textColor = UIColor.white.withAlphaComponent(0.9)
commentCell.textView.keyboardAppearance = .dark
commentCell.textView.text = offer?.comment
commentCell.indexPath = indexPath
commentCell.delegate = self
return commentCell
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "\(Strings.applicationWillStay) \(order!.shipping_date.dayAndMonth)."
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 1 {
let transportController = TransportPage()
transportController.bid = false
navigationController?.pushViewController(transportController, animated: true)
}else if indexPath.row == 2 {
let serviceController = InfoPage()
serviceController.paymentBid = true
serviceController.dark = true
serviceController.navigationItem.title = Strings.paymentType
navigationController?.pushViewController(serviceController, animated: true)
}else if indexPath.row == 3 {
let serviceController = InfoPage()
serviceController.other = true
serviceController.dark = true
serviceController.navigationItem.title = Strings.otherService
navigationController?.pushViewController(serviceController, animated: true)
}else if indexPath.row == 4 {
let shippingController = InfoPage()
shippingController.dark = true
shippingController.shippingBid = true
shippingController.navigationItem.title = Strings.shippingOnOff
navigationController?.pushViewController(shippingController, animated: true)
}
}
}
extension BidPage: TextFieldHandler, TextViewHandler, PriceAmountHandler {
func priceDidChanged(price: String) {
if let _price = Int(price) {
offer?.price = _price
}else {
offer?.price = -1
}
}
func amoundDidChange(amount: String) {
offer?.currency = amount
}
func textViewDidChange(forRow indexPath: IndexPath, text: String) {
if indexPath.row == 5 {
offer?.comment = text
}
}
func textFieldDidChange(forRow indexPath: IndexPath, text: String, _ textField: UITextField) {
if indexPath.row == 0 {
if let price = Int(text) {
offer?.price = price
}
}
}
}
|
//
// BasicTemplate.swift
// Basics
//
// Created by Venkatnarayansetty, Badarinath on 11/1/19.
// Copyright © 2019 Badarinath Venkatnarayansetty. All rights reserved.
//
import Foundation
import SwiftUI
//Key Notes : 1. Color.white is a View
// 2. Text wont be wrapped if layoutPriority is set to (1) : default : 0
struct BasicTemplate: View {
var body: some View {
VStack(spacing: 20) {
Text("Images")
.font(.largeTitle) // because it sets the font again , local gets priority over global i.e, largetitle is applied to "Images" and .title is applied to remaining two components
Text("Using SF Symbols")
.foregroundColor(Color.gray)
Text("You will see I use icons or symbols to add clarity to what i'm demonstrating.These come from Apple's new symbol font library which you can browse using an app called 'SF Symbol'")
.frame(maxWidth: .infinity) // Extend until you can't go anymore
.padding()
.foregroundColor(Color.white)
.background(Color.blue)
.layoutPriority(3)
Image(systemName: "hand.thumbsup.fill")
.font(.largeTitle)
Image("SF Symbols")
Image("yosemite")
.resizable()
.frame(width: 320, height: 50, alignment: .leading)
.opacity(0.7) // make image 70% solid
.background(Color.red.opacity(0.3)) // Layer behind image
.background(Color.yellow.opacity(0.3)) // Layer behind red
.background(Color.blue.opacity(0.3)) // Layer behind yellow
.overlay(Text("Yosemite")) //Layer on top of image
Text("This text has a rounded rectangle behind it")
.foregroundColor(Color.white)
.padding()
.background(RoundedRectangle(cornerRadius: 10)
.foregroundColor(Color.blue))
.padding()
.layoutPriority(2)
Text("But some times i'll use color and coner radius:")
.font(.caption)
Text("This text has a color with corner radius")
.foregroundColor(Color.white)
.padding()
.background(Color.blue)
.cornerRadius(20)
.padding()
.layoutPriority(2)
}.font(.title)
}
}
|
//
// CollectionDemoViewModel.swift
// CompositionalLayout
//
// Created by Nestor Hernandez on 09/07/22.
//
import Foundation
import Combine
class CollectionDemoViewModel: ObservableObject {
}
|
//
// SearchResultCell.swift
// City-Search
//
// Created by Mathew Thomas on 02/02/2021.
//
import UIKit
class SearchResultCell: UITableViewCell {
@IBOutlet weak var cityNameLabel: UILabel!
@IBOutlet weak var countryCodeLabel: UILabel!
@IBOutlet weak var latLongLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
|
//
// ViewController.swift
// Blet Exam
//
// Created by Peisure on 1/25/18.
// Copyright © 2018 Ben. All rights reserved.
//
import UIKit
import CoreData
class ShowTableViewController: UITableViewController, AddViewDelegate, cellDelegate{
let manageDatabase = (UIApplication.shared.delegate as!
AppDelegate).persistentContainer.viewContext
var com = [Todolist]()
var incom = [Todolist]()
//**************** Display table **********************************
var sectionTitle = ["Incomplete","Complete"]
override func numberOfSections(in tableView: UITableView) -> Int {
return sectionTitle.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionTitle[section]
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0{
return incom.count
}
else{
return com.count
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0{
let cell = tableView.dequeueReusableCell(withIdentifier: "ICell") as! ICell
cell.displayTitle.text = incom[indexPath.row].title
let formatter = DateFormatter()
formatter.timeStyle = .short
let myTime = incom[indexPath.row].beginDate
cell.displayTime.text = formatter.string(from: myTime!)
cell.delegate = self
cell.editButton.tag = indexPath.row
return cell
}
else{
let cell = tableView.dequeueReusableCell(withIdentifier: "CCell") as! CCell
cell.displayTitle.text = com[indexPath.row].title
let formatter = DateFormatter()
formatter.timeStyle = .short
let myTime = com[indexPath.row].beginDate
cell.displayTime.text = formatter.string(from: myTime!)
return cell
}
}
//***************** add, edit data *********************************
func addItem(_ controller: AddItemViewController, with toDoTitle: String, _ content: String, and beginTime: Date, by sender: UIButton, at indexPath: NSIndexPath?) {
if sender.tag == 0 {
self.navigationController?.popViewController(animated: true)
dismiss(animated: true, completion: nil)
}
else{
if let ip = indexPath{
let item = incom[ip.row]
item.title = toDoTitle
item.content = content
item.beginDate = beginTime
item.finish = false
}
else{
let item = NSEntityDescription.insertNewObject(forEntityName: "Todolist", into: manageDatabase) as! Todolist
item.title = toDoTitle
item.content = content
item.beginDate = beginTime
item.finish = false
incom.append(item)
}
do{
try manageDatabase.save()
}
catch{
print("\(error)")
}
self.navigationController?.popViewController(animated: true)
dismiss(animated: true, completion: nil)
fetchAllItems()
tableView.reloadData()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "addItem"{
let target = segue.destination as! AddItemViewController
target.delegate = self
}
else if segue.identifier == "edit"{
let target = segue.destination as! AddItemViewController
target.delegate = self
if let button = (sender as? UIButton){
target.item = incom[button.tag]
if let superview = button.superview {
if let cell = superview.superview as? ICell {
let indexPath = tableView.indexPath(for: cell)! as NSIndexPath
target.indexPath=indexPath
}
}
}
}
}
//******************** TableView Stuff ********************************
override func viewDidLoad() {
super.viewDidLoad()
fetchAllItems()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//********************* Database stuff **********************************
func fetchAllItems(){
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Todolist")
request.predicate = NSPredicate(format: "finish == %@", NSNumber(value: true))
do{
let result = try manageDatabase.fetch(request)
com = result as! [Todolist]
}
catch{
print("\(error)")
}
request.predicate = NSPredicate(format: "finish == %@", NSNumber(value: false))
do{
let result = try manageDatabase.fetch(request)
incom = result as! [Todolist]
}
catch{
print("\(error)")
}
}
//********************** Row selected stuff ***********************************
func editRow(_ sender: ICell) {
print("here")
// let indexPath = tableView.indexPath(for: sender)! as NSIndexPath
// performSegue(withIdentifier: "edit", sender: indexPath)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var item:Todolist?
if indexPath.section == 0{
item = incom[indexPath.row]
}
else{
item = com[indexPath.row]
}
if item?.finish == false{
item?.finish = true
}
else{
item?.finish = false
}
do{
try manageDatabase.save()
}
catch{
print("\(error)")
}
fetchAllItems()
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
var item:Todolist?
if indexPath.section == 0{
item = incom[indexPath.row]
}
else{
item = com[indexPath.row]
}
manageDatabase.delete(item!)
do{
try manageDatabase.save()
}
catch{
print("\(error)")
}
fetchAllItems()
tableView.reloadData()
}
}
class CCell:UITableViewCell{
@IBOutlet weak var displayTitle: UILabel!
@IBOutlet weak var displayTime: UILabel!
}
class ICell:UITableViewCell{
@IBOutlet weak var displayTime: UILabel!
@IBOutlet weak var displayTitle: UILabel!
@IBOutlet weak var editButton: UIButton!
weak var delegate:cellDelegate?
@IBAction func editButtonPressed(_ sender: UIButton) {
delegate?.editRow(self)
}
}
protocol cellDelegate:class {
func editRow(_ sender:ICell)
}
|
//
// Networking.swift
// AboutCanada
//
// Created by Vivek Goswami on 2/5/21.
// Copyright © 2021 Vivek Goswami. All rights reserved.
//
import UIKit
import SVProgressHUD
/**
BASE URL of app with selection Production and Development
- parameter nil: nil.
- returns: stringURL
- warning:
# Notes: #
1. If you want to change environment from AppDelegate when deploy
# Example #
```
AppManager.shared.appStatus = .development
```
*/
var baseURL: String {
if AppManager.shared.appStatus == .production {
return API.productionURL // Live
}
return API.developmentURL // Development
}
struct App {
struct BaseURL {
static let url = baseURL
}
}
|
//
// ViewController.swift
// ViewControllerLifeCycle1
//
// Created by Nagarajan on 8/27/14.
// Copyright (c) 2014 Nagarajan. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder);
print("%s", #function);
print("Unarchive data from nib or storyboard\n\n")
}
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: Bundle!)
{
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
print("%s", #function);
}
override func awakeFromNib()
{
super.awakeFromNib()
print("%s", #function);
print("Prepares the receiver for service after it has been loaded from an Interface Builder archive, or nib file\n\n")
}
override func loadView()
{
super.loadView()
print("%s", #function);
print("You should never call this method directly. The view controller callls this method when its view property is requested but is currently nil. This method loads or creates a view and asigns in to the view property\n\n")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
print("%s", #function);
print("This method is called after the view controller has loaded its view hierarchy into memory\n\n")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
print("%s", #function);
}
}
|
import Foundation
/// Witness for the `Moore<E, V>` data type. To be used in simulated Higher Kinded Types.
public final class ForMoore {}
/// Partial application of the Moore type constructor, omitting the last parameter.
public final class MoorePartial<E>: Kind<ForMoore, E> {}
/// Higher Kinded Type alias to improve readability of `Kind<MoorePartial<E>, V>`.
public typealias MooreOf<E, V> = Kind<MoorePartial<E>, V>
/// Moore represents Moore machines that hold values of type `V` and handle inputs of type `E`.
public final class Moore<E, V>: MooreOf<E, V> {
/// Value hold in this Moore machine.
public let view: V
/// Function to handle inputs to the Moore machine.
public let handle: (E) -> Moore<E, V>
/// Safe downcast.
///
/// - Parameter value: Value in the higher-kind form.
/// - Returns: Value cast to Moore.
public static func fix(_ value: MooreOf<E, V>) -> Moore<E, V> {
value as! Moore<E, V>
}
/// Creates a Moore machine from a hidden initial state and a function that provides the next value and handling function.
///
/// - Parameters:
/// - state: Initial state.
/// - next: Function to determine the next value and handling function.
/// - Returns: A Moore machine described from the input values.
public static func unfold<S>(
_ state: S,
_ next: @escaping (S) -> (V, (E) -> S)) -> Moore<E, V> {
let (a, transition) = next(state)
return Moore(view: a) { input in
unfold(transition(input), next)
}
}
/// Creates a Moore machine from an initial state, a rendering function and an update function.
///
/// - Parameters:
/// - initialState: Initial state.
/// - render: Rendering function.
/// - update: Update function.
/// - Returns: A Moore machine described from the input functions.
public static func from<S>(
initialState: S,
render: @escaping (S) -> V,
update: @escaping (S, E) -> S) -> Moore<E, V> {
unfold(initialState) { state in
(render(state), { input in update(state, input) })
}
}
/// Creates a Moore machine from an initial state, a rendering function and an update function.
///
/// - Parameters:
/// - initialState: Initial state.
/// - render: Rendering function.
/// - update: Update function.
/// - Returns: A Moore machine described from the input functions.
public static func from<S>(
initialState: S,
render: @escaping (S) -> V,
update: @escaping (E) -> State<S, S>) -> Moore<E, V> {
from(initialState: initialState, render: render, update: { s, e in update(e).run(s).0 })
}
/// Initializes a Moore machine.
///
/// - Parameters:
/// - view: Value wrapped in the machine.
/// - handle: Function to handle inputs to the machine.
public init(view: V, handle: @escaping (E) -> Moore<E, V>) {
self.view = view
self.handle = handle
}
/// Transforms the inputs this machine is able to handle.
///
/// - Parameter f: Transforming funtion.
/// - Returns: A Moore machine that works on the new type of inputs.
public func contramapInput<EE>(_ f: @escaping (EE) -> E) -> Moore<EE, V> {
Moore<EE, V>(view: self.view, handle: f >>> { x in self.handle(x).contramapInput(f) })
}
}
public extension Moore where E == V, E: Monoid {
/// Creates a Moore machine that logs the inputs it receives.
static var log: Moore<E, E> {
func h(_ m: E) -> Moore<E, E> {
Moore(view: m) { a in h(m.combine(a)) }
}
return h(.empty())
}
}
/// Safe downcast.
///
/// - Parameter value: Value in higher-kind form.
/// - Returns: Value cast to Moore.
public postfix func ^<E, V>(_ value: MooreOf<E, V>) -> Moore<E, V> {
Moore.fix(value)
}
// MARK: Instance of Functor for Moore
extension MoorePartial: Functor {
public static func map<A, B>(
_ fa: MooreOf<E, A>,
_ f: @escaping (A) -> B) -> MooreOf<E, B> {
Moore<E, B>(view: f(fa^.view),
handle: { update in fa^.handle(update).map(f)^ })
}
}
// MARK: Instance of Comonad for Moore
extension MoorePartial: Comonad {
public static func coflatMap<A, B>(
_ fa: MooreOf<E, A>,
_ f: @escaping (MooreOf<E, A>) -> B) -> MooreOf<E, B> {
Moore<E, B>(view: f(fa^),
handle: { update in fa^.handle(update).coflatMap(f)^ })
}
public static func extract<A>(_ fa: MooreOf<E, A>) -> A {
fa^.view
}
}
|
//
// AlertControllerManager.swift
//
import UIKit
import StoreKit
class AlertControllerManager: NSObject {
//MARK:-Alert Controller
func alertForCustomMessage(_ errorTitle: String ,errorMessage: String, handler: @escaping (UIAlertAction!)->Void) -> UIAlertController {
let alert = UIAlertController(title: errorTitle, message: errorMessage, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: handler))
return alert
}
func alertForServerError(_ errorTitle: String ,errorMessage: String) -> UIAlertController {
let alert = UIAlertController(title: errorTitle , message: errorMessage, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
return alert
}
func alertForEmptyTextField (_ fieldWithError: String) -> UIAlertController {
let alert = UIAlertController(title: fieldWithError, message:" ", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
return alert
}
func alertForMaxCharacters(_ fieldWithError: String) -> UIAlertController {
let alert = UIAlertController(title: fieldWithError, message:"Text is too long (maximum is 64 characters)", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
return alert
}
func alertForLessThanMinCharacters(_ fieldWithError: String) -> UIAlertController {
let alert = UIAlertController(title: fieldWithError, message:"Text is too short (minimum is 6 characters)", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
return alert
}
func alertForFailInInternetConnection () -> UIAlertController {
let alert = UIAlertController(title: "Internet'connection needed", message:"To use this App please connect to Internet", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
return alert
}
func alertForNotEmailString () -> UIAlertController {
let alert = UIAlertController(title: "Invalid email", message:"Please enter your email in the format someone@example.com", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
return alert
}
func alertForSuccesfulSentEmail (_ handler: ((UIAlertAction?)->Void)?) -> UIAlertController {
let alert = UIAlertController(title: "Email Sent", message:
"The email with the recorvery instructions has been sent", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default,handler: handler))
return alert
}
func alertForSuccesfulCreatedAccount (_ handler: ((UIAlertAction?)->Void)?) -> UIAlertController {
let alert = UIAlertController(title: "Account Created", message:
"Your account has been created successfully", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default,handler: handler))
return alert
}
func alertForSuccesfulSavedChanges (_ handler: ((UIAlertAction?)->Void)?) -> UIAlertController {
let alert = UIAlertController(title: "Profile Updated", message:
"Your information has been updated successfully", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default,handler: handler))
return alert
}
}
|
//
// ClassMateViewController.swift
// CoreDataDemo
//
// Created by Terry on 16/5/12.
// Copyright © 2016年 Terry. All rights reserved.
//
import UIKit
import CoreData
class ClassMateViewController: UITableViewController,UINavigationControllerDelegate {
var classMates = [ClassMate]()
var classMate: ClassMate!
override func viewDidLoad() {
super.viewDidLoad()
print(NSBundle.mainBundle().resourcePath)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func fetchClassMates() {
let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context = delegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "ClassMate")
do{
let fetchedObject = try context.executeFetchRequest(fetchRequest) as! [ClassMate]
classMates = fetchedObject
self.tableView.reloadData()
}
catch{
print(error)
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
fetchClassMates()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return classMates.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! ClassMateTableViewCell
cell.name.text = classMates[indexPath.row].name
cell.desc.text = classMates[indexPath.row].desc
cell.price.text = "¥\(classMates[indexPath.row].price!)"
let imageStr = classMates[indexPath.row].images
if (imageStr != nil) {
cell.images.image = UIImage.init(named: imageStr!)
}else{
cell.images.image = UIImage.init(named: "no")
}
let grade = "\(classMates[indexPath.row].grade!)"
switch grade {
case "0":
cell.star.image = UIImage(named: "0")
case "1":
cell.star.image = UIImage(named: "1")
case "2":
cell.star.image = UIImage(named: "2")
case "3":
cell.star.image = UIImage(named: "3")
case "4":
cell.star.image = UIImage(named: "4")
default:
cell.star.image = UIImage(named: "5")
}
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return UITableViewCellEditingStyle.Delete
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
deleteClassMate(indexPath.row)
classMates.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
classMate = classMates[indexPath.row]
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showInfo" {
let indexPath = tableView.indexPathForSelectedRow
var nextPage = segue.destinationViewController as! ViewController
nextPage.classMate = classMates[(indexPath?.row)!]
}
}
func deleteClassMate(rowIndex: Int) {
let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context = delegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "ClassMate")
do {
let fetchObject = try context.executeFetchRequest(fetchRequest) as! [ClassMate]
classMates = fetchObject
context.deleteObject(classMates[rowIndex])
try context.save()
}
catch {
print("error")
}
}
}
|
//
// Date+Additions.swift
// WFAPPCore
//
// Created by Dario Carlomagno on 03/08/2019.
//
import Foundation
extension Date {
var iso8601FullDate: Date? {
let dateFormatter = ISO8601DateFormatter([.withFullDate])
return dateFormatter.date(from: self.iso8601)
}
}
|
//
// Test.swift
// Reciplease
//
// Created by Raphaël Payet on 18/06/2021.
//
import Foundation
import Alamofire
// MARK: - From Kévin
enum NetworkRequestError: Error {
case statusCode(Int)
case serializationError(Error?)
}
protocol NetworkRequest {
func get<DataType: Codable>(_ url: URL, with: [String: Any], completion: @escaping (DataType?, Error?) -> Void)
}
class AlamofireNetworkRequest: NetworkRequest {
func get<DataType: Codable>(_ url: URL, with: [String: Any], completion: @escaping (DataType?, Error?) -> Void) {
// Do whatever needed with Alamofire
}
}
struct FakeNetworkRequest: NetworkRequest {
var data: Data?
var response: HTTPURLResponse?
var error: Error?
func get<DataType: Codable>(_ url: URL, with: [String: Any], completion: @escaping (DataType?, Error?) -> Void) {
guard let response = response, response.statusCode == 200 else {
return completion(nil, NetworkRequestError.statusCode(self.response?.statusCode ?? -1))
}
guard let data = data else {
return completion(nil, error)
}
do {
completion(try JSONDecoder().decode(DataType.self, from: data), nil)
} catch {
completion(nil, NetworkRequestError.serializationError(error))
}
}
}
// MARK: - New
class FakeAFSession: Session {
// override func request(_ convertible: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> DataRequest {
// <#code#>
// }
}
|
//
// FAQPageDropCell.swift
// CoAssets-Agent
//
// Created by Macintosh HD on 12/24/15.
// Copyright © 2015 Nikmesoft Ltd. All rights reserved.
//
import UIKit
import Foundation
class FAQPageDropCell: UITableViewCell {
@IBOutlet weak private var contentTextView: BaseTextView!
override func awakeFromNib() {
super.awakeFromNib()
self.selectionStyle = UITableViewCellSelectionStyle.None
loadData()
}
}
//MARK: Private
extension FAQPageDropCell {
func loadData() {
guard let htmlFinal = ResourcesHelper.readHTMLFile("FAQResource") else {
return
}
do {
let str = try NSAttributedString(data: htmlFinal.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
contentTextView.attributedText = str
} catch {
print(error)
}
}
}
|
//
// SearchPresenter.swift
// IOS Task-Softxpert
//
// Created by Abeer Meckawi on 29/07/2021.
//
import Foundation
class SearchPresenter: SearchRecipePresenterProtocol{
weak var view: SearchRecipeViewProtocol?
private let interactor : SearchRecipeInteractorInputProtocol
private let router: SearchRecipeRouterProtocol
private let searchHisroryDef = UserDefaults.standard
private var hits = [Hits]()
var recentHistory = [String]()
var query = [String]()
var health = ""
var numberOfRows: Int {
return hits.count
}
init(view: SearchRecipeViewProtocol, interactor: SearchRecipeInteractorInputProtocol, router: SearchRecipeRouterProtocol) {
self.view = view
self.interactor = interactor
self.router = router
}
func viewDidLoad() {
view?.showLoadingIndicator()
interactor.getRecipes(query: query,health: health)
}
func configure(cell: SearchRecipeCellView, indexPath: IndexPath) {
let hit = hits[indexPath.row]
let viewModel = SearchViewModel(hit: hit)
cell.configure(viewModel: viewModel)
}
func addSearchHistory(input: String) {
if recentHistory.count < 10 {
recentHistory.append(input)
}else if recentHistory.contains(input){
recentHistory = getSearchHistory()
}else{
recentHistory.removeFirst()
recentHistory.insert(input, at: recentHistory.count)
}
searchHisroryDef.set(recentHistory, forKey: "SearchHistorry")
}
func getSearchHistory() -> [String]{
let savedHistory = searchHisroryDef.object(forKey: "SearchHistorry") as? [String] ?? [String]()
recentHistory = savedHistory
return recentHistory
}
func showRecipeDetails(indexPath :IndexPath) {
guard let view = view else { return }
let hit = hits[indexPath.row]
router.presentRecipeDetail(from: view, for: hit)
}
}
extension SearchPresenter :SearchRecipeInteractorOutputProtocol{
func searchFetchedSuccessfully(hits: [Hits]) {
if hits.count == 0{
view?.createAlert(message:"Not Data Avaliable For This Recipe")
}else{
view?.hideLoadingIndicator()
self.hits = hits
view?.reloadData()
}
}
func searchFetchingFailed(withError error: Error) {
view?.hideLoadingIndicator()
view?.createAlert(message:"Try Agin Failed to Fetch Data")
}
}
|
//
// StandardUserPresenceTypeNames.swift
// Mitter
//
// Created by Rahul Chowdhury on 22/11/18.
// Copyright © 2018 Chronosphere Technologies Pvt. Ltd. All rights reserved.
//
import Foundation
public enum StandardUserPresenceTypeNames {
public static let Online: String = "mitter.up.Online"
public static let Sleeping: String = "mitter.up.Sleeping"
public static let Away: String = "mitter.up.Away"
public static let Missing: String = "mitter.up.Missing"
public static let Offline: String = "mitter.up.Offline"
}
|
var s = "你好啊。こんにちは。" // 10 Chars
print("---- characters ----")
let ctc = s.characters.count
print(ctc)
print("---- utf8 ----")
let ctu8 = s.utf8.count
print(ctu8)
print("---- utf16 ----")
let ctu16 = s.utf16.count
print(ctu16)
print("---- unicodeScalars----")
let ctus = s.unicodeScalars.count
print(ctus)
|
//
// networkServiceViewController.swift
// SJIalmofire
//
// Created by adriansalim on 21/04/20.
// Copyright © 2020 adriansalim. All rights reserved.
//
import UIKit
import Alamofire
import SystemConfiguration
public typealias HTTPHeaders = [String: String]
public enum HTTPMethod: String {
case options = "OPTIONS"
case get = "GET"
case head = "HEAD"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
case trace = "TRACE"
case connect = "CONNECT"
}
/*
200 = Success get response from server
400 = Bad request
500 = Internal server error
501 = No data from server
503 = No connection
*/
public func apiResult(url: String, param: [String : Any]?, method: Alamofire.HTTPMethod, callback: @escaping (_ result: Bool, _ response: Any?, _ statusCode: String?) -> Void) {
if(Reachability.getNetworkType() == "No Connection"){
callback(false, "Please check your connection", "503")
}
else{
let currentHeaders = [
"Content-Type" : "application/x-www-form-urlencoded",
] as HTTPHeaders
Alamofire.request(URL(string: url)!, method: method, parameters: param, encoding: URLEncoding.default, headers: currentHeaders)
.responseJSON{ response in
if(response.response == nil){
callback(false, nil, "501")
}
else{
let statusCode = response.response?.statusCode
switch statusCode!{
case 200:
callback(true, response.data, "200")
case 400:
print("Bad Request")
callback(false, nil, "400")
break
default:
callback(false, nil, "500")
break
}
}
}
}
}
public func getIpAddress(callback: @escaping (_ ip: String?) -> Void) {
Alamofire.request("https://api.ipify.org").responseString { (response) in
if(response.value! != ""){
callback(response.value!)
}
else{
callback("")
}
}
}
|
//
// Login.swift
// Bank
//
// Created by Junior Obici on 13/01/20.
// Copyright © 2020 Junior Obici. All rights reserved.
//
import Foundation
struct LoginResponse: Codable {
let user: User
enum CodingKeys: String, CodingKey {
case user = "userAccount"
}
}
struct User: Codable {
let userId: Int
let userName: String
let userAccount: String
let userAgency: String
let userBalance: Double
enum CodingKeys: String, CodingKey {
case userId
case userName = "name"
case userAccount = "bankAccount"
case userAgency = "agency"
case userBalance = "balance"
}
}
|
//
// LinkView.swift
// RyujumeApp
//
// Created by baby1234 on 31/07/2019.
// Copyright © 2019 baby1234. All rights reserved.
//
import UIKit
class LinkView: UIView {
let linkLbl = UILabel()
let deleteBtn = UIButton()
func configureView(addStackView: UIStackView, defaultFontSize: Int, linkInfo: String){
self.backgroundColor = UIColor.white
self.translatesAutoresizingMaskIntoConstraints = false
linkLbl.text = linkInfo
linkLbl.font = UIFont.appMidiumFontWith(size: CGFloat(defaultFontSize - 3))
linkLbl.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(linkLbl)
deleteBtn.setTitle("삭제", for: .normal)
deleteBtn.titleLabel?.font = UIFont.appExtraLightFontWith(size: CGFloat(defaultFontSize + 3))
deleteBtn.setTitleColor(UIColor.blue, for: .normal)
deleteBtn.tag = 0
deleteBtn.translatesAutoresizingMaskIntoConstraints = false
deleteBtn.addTarget(self, action: #selector(tapedDeleteBtn), for: .touchUpInside)
self.addSubview(deleteBtn)
self.widthAnchor.constraint(equalToConstant: addStackView.frame.width).isActive = true
linkLbl.topAnchor.constraint(equalTo: self.topAnchor, constant: 5).isActive = true
linkLbl.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
linkLbl.widthAnchor.constraint(greaterThanOrEqualToConstant: 20).isActive = true
linkLbl.heightAnchor.constraint(greaterThanOrEqualToConstant: 40).isActive = true
deleteBtn.topAnchor.constraint(equalTo: self.topAnchor, constant: 2).isActive = true
deleteBtn.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -10).isActive = true
deleteBtn.widthAnchor.constraint(equalToConstant: 20).isActive = true
deleteBtn.heightAnchor.constraint(equalTo: deleteBtn.widthAnchor).isActive = true
linkLbl.trailingAnchor.constraint(lessThanOrEqualTo: self.trailingAnchor).isActive = true
self.bottomAnchor.constraint(equalTo: linkLbl.bottomAnchor).isActive = true
}
}
|
//
// LikeViewController.swift
// Whoop
//
// Created by Li Jiatan on 4/16/15.
// Copyright (c) 2015 Li Jiatan. All rights reserved.
//
import UIKit
class LikeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
let identifier = "likeViewCell"
var stopLoading: Bool = true
var _db = NSMutableArray()
var uid = String()
var page: Int = 1
@IBOutlet weak var likeTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.uid = FileUtility.getUserId()
_db.removeAllObjects()
let nib = UINib(nibName:"LikeViewCell", bundle: nil)
self.likeTableView.registerNib(nib, forCellReuseIdentifier: identifier)
//load_Data()
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
self.navigationItem.title = "Likes".localized()
_db.removeAllObjects()
self.page = 1
load_Data()
}
func load_Data(){
let url = FileUtility.getUrlDomain() + "msg/getMsgByUId?uid=\(self.uid)&pageNum=\(self.page)"
//var url = "http://104.131.91.181:8080/whoops/msg/getMsgByUId?uid=97&pageNum=1"
YRHttpRequest.requestWithURL(url,completionHandler:{ data in
if data as! NSObject == NSNull()
{
UIView.showAlertView("Alert".localized(), message: "Loading Failed".localized())
return
}
let arr = data["data"] as! NSArray
if (arr.count == 0){
self.stopLoading = true
}else{
self.stopLoading = false
}
for data : AnyObject in arr
{
var isExist:Bool = false
for item in self._db
{
let oldId = data["id"] as! Int
let newId = item["id"] as! Int
if oldId == newId
{
isExist = true
}
}
if isExist == false {
self._db.addObject(data)
}
}
self.likeTableView.reloadData()
// self.refreshView!.stopLoading()
//self.page++
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self._db.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as? LikeViewCell
var cell : LikeViewCell? = tableView.dequeueReusableCellWithIdentifier(identifier) as? LikeViewCell
if cell == nil{
cell = LikeViewCell(style: .Default, reuseIdentifier: identifier)
}
let index = indexPath.row
cell!.data = _db[index] as! NSDictionary
cell!.setupSubviews()
if (indexPath.row == self._db.count-1) && (self.stopLoading == false){
self.page++
load_Data()
}
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let index = indexPath.row
let data = self._db[index] as! NSDictionary
let commentsVC = YRCommentsViewController(nibName :nil, bundle: nil)
commentsVC.jokeId = data.stringAttributeForKey("postId")
commentsVC.hidesBottomBarWhenPushed = true
likeTableView.deselectRowAtIndexPath(indexPath, animated: true)
self.navigationController?.pushViewController(commentsVC, animated: true)
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
let index = indexPath.row
let data = self._db[index] as! NSDictionary
return LikeViewCell.cellHeightByData(data)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// StoryboardSegue.swift
// NewProject
//
// Created by yauheni prakapenka on 01.03.2020.
// Copyright © 2020 yauheni prakapenka. All rights reserved.
//
enum StoryboardSegue: String {
case alertVC = "AlertVC"
case userInfo = "UserInfo"
}
|
//
// ViewController.swift
// DKMapKit
//
// Created by DKJone on 04/25/2019.
// Copyright (c) 2019 DKJone. All rights reserved.
//
import BaiduMapAPI_Cloud
import DKMapKit
import UIKit
import BaiduMapAPI_Utils
import BaiduMapAPI_Map
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let mang = BMKClusterManager()
let mapview = BMKMapView(frame: self.view.bounds)
view.addSubview(mapview)
let ap = BMKMapPointForCoordinate(CLLocationCoordinate2D.init(latitude: 100, longitude: 112))
DKJone().draw()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// Data+AES.swift
// WavesWallet-iOS
//
// Created by Prokofev Ruslan on 23/09/2018.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import WavesSDKCrypto
import Foundation
import CryptoSwift
fileprivate enum Constants {
static let iterations: Int = 5000
static let keyLength: Int = 32
}
public extension Data {
func aesEncrypt(withKey key: String) -> Data? {
let iv: Array<UInt8> = AES.randomIV(AES.blockSize)
let keyBytes = try! PKCS5.PBKDF2(password: key.bytes,
salt: iv,
iterations: Constants.iterations,
keyLength: Constants.keyLength,
variant: .sha256).calculate()
do {
let aes = try AES(key: keyBytes, blockMode: CBC(iv: iv))
let encrypt = try aes.encrypt(self.bytes)
var combine = [UInt8]()
combine.append(contentsOf: iv)
combine.append(contentsOf: encrypt)
return Base58Encoder.encode(combine).data(using: .utf8)
} catch _ {
return nil
}
}
func aesDecrypt(withKey key: String) -> Data? {
guard let stringFromData = String(data: self, encoding: .utf8) else { return nil }
let dataBase58 = Base58Encoder.decode(stringFromData)
let iv: Array<UInt8> = Array(dataBase58[0..<AES.blockSize])
let keyBytes = try! PKCS5.PBKDF2(password: key.bytes,
salt: iv,
iterations: 5000,
keyLength: 32,
variant: .sha256).calculate()
do {
let aes = try AES(key: keyBytes, blockMode: CBC(iv: iv))
let dataBytes = dataBase58[AES.blockSize..<dataBase58.count]
let decrypt = try aes.decrypt(dataBytes)
return Data(bytes: decrypt)
} catch let error {
print(error)
}
return nil
}
}
public extension String {
func aesEncrypt(withKey key: String) -> String? {
guard let data = self.data(using: .utf8) else { return nil }
guard let encrypt = data.aesEncrypt(withKey: key) else { return nil }
return String(data: encrypt, encoding: .utf8)
}
func aesDecrypt(withKey key: String) -> String? {
guard let data = self.data(using: .utf8) else { return nil }
guard let decrypt = data.aesDecrypt(withKey: key) else { return nil }
return String(data: decrypt, encoding: .utf8)
}
}
|
//
// PropertyNames.swift
// YumaApp
//
// Created by Yuma Usa on 2018-04-15.
// Copyright © 2018 Yuma Usa. All rights reserved.
//
import Foundation
protocol PropertyNames
{
func propertyNames() -> [String]
}
extension PropertyNames
{
func propertyNames() -> [String]
{
return Mirror(reflecting: self).children.compactMap { $0.label }
}
}
|
//
// RecordingViewController.swift
// MotionBasedSecurityKey
//
// Created by Jordan Harrod on 5/3/17.
// Copyright © 2017 Jordan Harrod. All rights reserved.
//
import UIKit
import Foundation
// JH: Unchanged from the original Xcode specifications
// JH: Created in order to utilize the RecordingViewController in other areas of the application, this ViewController is transient.
class RecordingViewController: UIViewController {
@IBOutlet weak var spinning: UIActivityIndicatorView!
var password: Gyroscope!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
spinning = UIActivityIndicatorView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationViewController = segue.destination as? SavedViewController {
destinationViewController.password = self.password
}
}
@IBAction func moveToNext(_ sender: UIButton) {
let thirdViewController = SavedViewController()
self.navigationController?.pushViewController(thirdViewController, animated: true)
thirdViewController.viewDidLoad()
}
}
|
//
// SongDetailViewModal.swift
// MVVM
//
// Created by Himanshu Chimanji on 19/09/21.
//
import Foundation
class SongDetailViewModal: NSObject {
static let instance = SongDetailViewModal()
var songDetail : SongsStruct?
}
|
//
// CompassServiceProtocol.swift
// smartWeather
//
// Created by Maderbacher Florian on 06/11/15.
// Copyright © 2015 FH Joanneum. All rights reserved.
//
import Foundation
protocol CompassServiceProtocol {
func registerCompass(compassChanged: CompassState -> Void)
func filterLocations(compassState: CompassState, position: Geoposition, locations: [Location]) -> [Location]
} |
//
// ViewController.swift
// CoreDataSwiftSample
//
// Created by SunilMaurya on 31/03/18.
// Copyright © 2018 SunilMaurya. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let userDict:[String : Any] = ["name":"Sunil", "email":"skm17081990@gmail.com", "userid":1, "address":"India"]
let workDict:[String : Any] = ["workDate":NSDate(), "workName": "CoreData Learning"]
CoreDataManager.sharedInstance.save(tableName: "User", dictionaryValues: userDict, arrayValues: [workDict])
if let allUsers = CoreDataManager.sharedInstance.getAllObjects(tableName: "User") as? [User] {
print(allUsers[0].name ?? "")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// MyWishListViewC.swift
// Paysfer
//
// Created by VISHAL VERMA on 23/06/20.
// Copyright © 2020 VISHAL VERMA. All rights reserved.
//
import UIKit
import PKHUD
class MyWishListViewC: UIViewController {
@IBOutlet weak var collectionViewFeatured: UICollectionView!
@IBOutlet weak var lblHiddenTxt: UILabel!
@IBOutlet weak var imgHidden: UIImageView!
@IBOutlet weak var lblCart: UILabel!
var productData = [FeatureModel]()
let service = ServerHandler()
override func viewDidLoad() {
super.viewDidLoad()
registerNibFiles()
Helper.cornerCircle(lblCart)
}
override func viewWillAppear(_ animated: Bool) {
self.tabBarController?.tabBar.isHidden = false
homeProductData()
carttData()
}
override func viewDidAppear(_ animated: Bool) {
carttData()
}
@IBAction func cartDetailsScreen(_ sender: UIButton) {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "CartDetailViewController") as! CartDetailViewController
self.tabBarController?.tabBar.isHidden = true
self.navigationController?.pushViewController(nextViewController, animated: true)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
private func registerNibFiles(){
self.collectionViewFeatured.register(UINib.init(nibName: "FeaturedCollectionVCell", bundle: nil), forCellWithReuseIdentifier: FeaturedCollectionVCell.reuseId)
}
func carttData(){
let userData = Helper.setUserDetailsInUsermodel(details: UserDefaults.standard.getUserDetails())
HUD.show(.labeledProgress(title: "", subtitle: "Getting products for you..."))
service.getResponseFromServer(parametrs: "home_product.php?home_product=home_product&&user_id=\( userData.user_id ?? "")") { (results) in
let status = results["status"] as? String ?? ""
if status == "1"{
HUD.hide()
let count = results["wish_count"] as? String ?? ""
if let cartCount = results["cart_count"] as? String {
if cartCount != ""{
self.lblCart.isHidden = false
self.lblCart.text = cartCount
}else{
self.lblCart.isHidden = true
}
}
if let tabItems = self.tabBarController?.tabBar.items {
// In this case we want to modify the badge number of the third tab:
let tabItem = tabItems[1]
if count != ""{
tabItem.badgeValue = count
}
else{
tabItem.badgeValue = nil
}
}
}else{
Helper.showSnackBar(with: results["message"] as? String ?? "")
// let alertController = UIAlertController(title: "Failure", message: results["message"] as? String ?? "", preferredStyle: .alert)
//
// let cancelAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.cancel) {
// UIAlertAction in
// }
// alertController.addAction(cancelAction)
}
}
}
func homeProductData(){
productData.removeAll()
collectionViewFeatured.isHidden = false
let userData = Helper.setUserDetailsInUsermodel(details: UserDefaults.standard.getUserDetails())
HUD.show(.labeledProgress(title: "", subtitle: "Getting products for you..."))
service.getResponseFromServer(parametrs: "wishlist_details.php?user_id=\( userData.user_id ?? "")") { (results) in
let status = results["status"] as? String ?? ""
if status == "1"{
HUD.hide()
self.imgHidden.isHidden = true
self.lblHiddenTxt.isHidden = true
if let feature = results["data"] as? [[String:Any]]{
for item in feature{
print(item)
self.productData.append(FeatureModel(item))
}
DispatchQueue.main.async {
self.collectionViewFeatured.reloadData()
}
}
}else{
HUD.hide()
DispatchQueue.main.async {
if self.productData.count == 0{
self.imgHidden.isHidden = false
self.lblHiddenTxt.isHidden = false
self.collectionViewFeatured.isHidden = true
}
else{
self.imgHidden.isHidden = true
self.lblHiddenTxt.isHidden = true
self.collectionViewFeatured.isHidden = false
}
self.collectionViewFeatured.reloadData()
}
// let alertController = UIAlertController(title: "Failure", message: results["message"] as? String ?? "", preferredStyle: .alert)
//
// let cancelAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.cancel) {
// UIAlertAction in
// }
// alertController.addAction(cancelAction)
}
}
}
}
extension MyWishListViewC:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return productData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FeaturedCollectionVCell", for: indexPath) as! FeaturedCollectionVCell
cell.vwBackground.layer.shadowColor = UIColor.black.cgColor
cell.vwBackground.layer.shadowOffset = CGSize(width: 0.0, height: 5.0)
cell.vwBackground.layer.shadowRadius = 5
cell.vwBackground.layer.shadowOpacity = 0.3
cell.vwBackground.layer.cornerRadius = 8
//r
cell.vwBottomBg.roundedView()
cell.imgBackground.roundedimgView()
let newArriv = productData[indexPath.row]
cell.lblProductName.text = newArriv.pro_title
if let discount = newArriv.pro_discount{
if discount == "0" {
if let price = newArriv.pro_regular_price{
cell.lblFinalPrice.text = "$ \(price)"
}
cell.lblSelingPrice.isHidden = true
cell.lblLine.isHidden = true
cell.lblDiscount.isHidden = true
}
else{
if let price = newArriv.pro_sale_price{
cell.lblFinalPrice.text = "$ \(price)"
}
cell.lblSelingPrice.isHidden = false
cell.lblLine.isHidden = false
cell.lblDiscount.isHidden = false
cell.lblDiscount.text = "\(discount)% OFF"
if let price = newArriv.pro_regular_price{
cell.lblSelingPrice.text = "$ \(price)"
}
}
}
// if let variablePro = newArriv.variable_pro{
// if variablePro == "0"{
// //addtoCartfeatureData
// cell.btnAddToCart.tag = indexPath.item
// cell.btnAddToCart.addTarget(self, action: #selector(self.addtoCartNewArrival(_:)), for: .touchUpInside)
// }else{
//
// }
// }
cell.btnAddToCart.tag = indexPath.item
cell.btnAddToCart.addTarget(self, action: #selector(self.detailScreenNewArrival(_:)), for: .touchUpInside)
cell.btnHeart.tag = indexPath.item
cell.btnHeart.addTarget(self, action: #selector(self.appcetAction(_:)), for: .touchUpInside)
if let img = newArriv.pro_image{
cell.imgBackground.sd_setImage(with: URL(string: img ), placeholderImage: UIImage(named: ""))
}
cell.imgHeart.image = #imageLiteral(resourceName: "heart (3)")
return cell
}
@objc func addtoCartNewArrival(_ sender: UIButton) {
HUD.show(.labeledProgress(title: "", subtitle: "Adding product your cart..."))
let userData = Helper.setUserDetailsInUsermodel(details: UserDefaults.standard.getUserDetails())
let params : [String:Any] = ["user_id":"\(userData.user_id ?? "")",
"product_id":"\(productData[sender.tag].pro_id ?? "")",
"variation_id":"0",
"qty":"1"]
service.getResponseFromServerByPostMethod(parametrs: params, url: "add_to_cart.php?") { (results) in
let status = results["status"] as? String ?? ""
if status == "1"{
HUD.hide()
Helper.showSnackBar(with: results["message"] as? String ?? "")
DispatchQueue.main.async {
self.carttData()
// self.homeProductData()
}
}else{
HUD.hide()
Helper.showSnackBar(with: results["message"] as? String ?? "")
}
}
}
@objc func detailScreenNewArrival(_ sender: UIButton) {
if let variablePro = productData[sender.tag].variable_pro{
if variablePro == "0"{
HUD.show(.labeledProgress(title: "", subtitle: "Adding product your cart..."))
let userData = Helper.setUserDetailsInUsermodel(details: UserDefaults.standard.getUserDetails())
let params : [String:Any] = ["user_id":"\(userData.user_id ?? "")",
"product_id":"\(productData[sender.tag].pro_id ?? "")",
"variation_id":"0",
"qty":"1"]
service.getResponseFromServerByPostMethod(parametrs: params, url: "add_to_cart.php?") { (results) in
let status = results["status"] as? String ?? ""
if status == "1"{
HUD.hide()
Helper.showSnackBar(with: results["message"] as? String ?? "")
DispatchQueue.main.async {
self.carttData()
// self.homeProductData()
}
}else{
HUD.hide()
Helper.showSnackBar(with: results["message"] as? String ?? "")
}
}
}else{
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "ProductDetailViewC") as! ProductDetailViewC
guard let p_Id = productData[sender.tag].pro_id else{ return }
nextViewController.p_id = p_Id
self.tabBarController?.tabBar.isHidden = true
self.navigationController?.pushViewController(nextViewController, animated: true)
}
}
}
@objc func appcetAction(_ sender: UIButton) {
print(sender.tag)
HUD.show(.labeledProgress(title: "", subtitle: "Getting products for you..."))
let userData = Helper.setUserDetailsInUsermodel(details: UserDefaults.standard.getUserDetails())
let params : [String:Any] = ["user_id":"\(userData.user_id ?? "")",
"product_id":"\(productData[sender.tag].pro_id ?? "")"]
service.getResponseFromServerByPostMethod(parametrs: params, url: "remove_wishlist.php?") { (results) in
let status = results["status"] as? String ?? ""
if status == "1"{
HUD.hide()
Helper.showSnackBar(with: results["message"] as? String ?? "")
let count = results["wish_count"] as? String ?? ""
DispatchQueue.main.async {
if let tabItems = self.tabBarController?.tabBar.items {
// In this case we want to modify the badge number of the third tab:
let tabItem = tabItems[1]
tabItem.badgeValue = count
self.homeProductData()
self.carttData()
}
}
}else{
HUD.hide()
Helper.showSnackBar(with: results["message"] as? String ?? "")
}
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionViewFeatured.frame.size.width/2 - 10, height:320)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == collectionViewFeatured {
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "ProductDetailViewC") as! ProductDetailViewC
guard let p_Id = productData[indexPath.row].pro_id else{ return }
nextViewController.p_id = p_Id
self.tabBarController?.tabBar.isHidden = true
self.navigationController?.pushViewController(nextViewController, animated: true)
}
}
}
|
//
// ShapeOverlayView.swift
// Construction
//
// Created by Macmini on 11/3/17.
// Copyright © 2017 LekshmySankar. All rights reserved.
//
import UIKit
protocol ShapeOverLayDelegate {
func needsFirstResponder(needsFirstResponder: Bool)
func drawCancelled()
func shapeCreated(_ shape: Shape)
func shapeDeleted(_ shape: Shape)
func focused()
}
@IBDesignable class ShapeOverlayView: UIView {
var sheet: Sheet!
var zoomeScale: CGFloat = 1.0
var selectedType: ShapeType = .NONE {
didSet {
if self.delegate != nil {
self.delegate.needsFirstResponder(needsFirstResponder: selectedType != .NONE)
}
}
}
var selectedColor: UIColor = Colors.darkColor
var isDrawing: Bool = false
var delegate: ShapeOverLayDelegate!
private var _selectedShape: Shape?
var selectedShape: Shape? {
get {
return _selectedShape
}
set {
if let old = _selectedShape {
old.selected = false
self.hideDelete()
}
if let newShape = newValue {
newShape.selected = true
self.showDelete(on: newShape)
}
if self.delegate != nil {
self.delegate.needsFirstResponder(needsFirstResponder: newValue != nil)
}
_selectedShape = newValue
}
}
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
func hideDelete() {
let menu = UIMenuController.shared
menu.setMenuVisible(false, animated: true)
}
func showDelete(on shape: Shape) {
let menu = UIMenuController.shared
menu.menuItems = [UIMenuItem(title: "Delete", action: #selector(ShapeOverlayView.deleteShape))]
menu.setTargetRect(shape.boundRect, in: self)
menu.setMenuVisible(true, animated: true)
becomeFirstResponder()
}
@objc func deleteShape() {
if let shape = self.selectedShape {
if let index = self.sheet.shapes.index(where: { (shapeInShapes) -> Bool in
if shape.fbshape == shapeInShapes.fbshape {
return true
}
return false
}) {
self.sheet.shapes.remove(at: index)
}
if let delegate = self.delegate {
delegate.shapeDeleted(shape)
}
DispatchQueue.main.async {
self.selectedShape = nil
self.redraw()
}
}
}
func initialize() {
self.contentMode = .scaleToFill
if sheet == nil {
sheet = Sheet()
}
self.selectedShape = nil
self.isUserInteractionEnabled = true
self.isMultipleTouchEnabled = true
becomeFirstResponder()
}
override func draw(_ rect: CGRect) {
guard let shapes = self.sheet.shapes else {
return
}
if let context = UIGraphicsGetCurrentContext() {
for shape in shapes {
_ = shape.drawAt(context: context, zoomScale: zoomeScale)
}
if let current = selectedShape {
_ = current.drawAt(context: context, zoomScale: zoomeScale)
}
}
}
func redraw() {
setNeedsDisplay()
}
func shapeAtPoint(point: CGPoint) -> Shape? {
for i in (0..<sheet.shapes.count).reversed(){
if sheet.shapes[i].boundRect.contains(point) {
return sheet.shapes[i]
}
}
return nil
}
func createShape(shape: Shape) {
sheet.shapes.append(shape)
if let delegate = self.delegate {
delegate.shapeCreated(shape)
}
// self.selectedType = .NONE
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if touches.count > 1 {
return
}
if let delegate = self.delegate {
delegate.focused()
}
if let touch = touches.first {
let point = touch.location(in: self)
if isDrawing == false {
//select shape at point
if let shape = self.selectedShape {
let index = shape.isUpdatablePoint(point: point)
if index != -1 {
shape.updatingPointIndex = index
return
}
}
if let shape = shapeAtPoint(point: point) {
self.selectedShape = shape
}
else {
if let shape = ShapeFactory.shared.create(type: selectedType, color: selectedColor) {
isDrawing = true
_ = shape.addPoint(point: point)
self.selectedShape = shape
}
else {
self.selectedShape = nil
}
}
}
else {
if let shape = self.selectedShape{
if shape.type == .POLYGON {
if shape.addPoint(point: point) == false {
self.createShape(shape: shape)
shape.updateFBShape()
shape.isClosed = true
self.selectedShape = nil
isDrawing = false
}
}
}
}
redraw()
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if touches.count > 1 {
return
}
if let touch = touches.first {
let point = touch.location(in: self)
if isDrawing {
guard let shape = selectedShape else {
return
}
guard shape.type != .POLYGON else {
return
}
if shape.points.count > 0 {
var points = [CGPoint]()
let start = shape.points[0]
points.append(start)
points.append(CGPoint(x: start.x, y: point.y))
points.append(point)
points.append(CGPoint(x: point.x, y: start.y))
shape.points = points
}
}
else {
let prevPoint = touch.previousLocation(in: self)
if let shape = selectedShape {
if shape.updatingPointIndex != -1 {
shape.update(at: shape.updatingPointIndex, with: point)
}
else {
if shape.boundRect.contains(point) {
shape.move(dp: CGPoint(x: point.x - prevPoint.x, y: point.y - prevPoint.y))
}
}
}
}
}
redraw()
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if touches.count > 1 {
return
}
guard let shape = self.selectedShape else {
return
}
guard shape.type != .POLYGON else {
if !isDrawing {
if shape.updatingPointIndex != -1 {
shape.updatingPointIndex = -1;
}
}
return
}
if isDrawing {
if shape.points.count >= 2 {
self.createShape(shape: shape)
}
else {
if let delegate = self.delegate {
delegate.drawCancelled()
}
self.selectedShape = nil
}
isDrawing = false
}
else {
if shape.updatingPointIndex != -1 {
shape.updatingPointIndex = -1;
}
}
shape.updateFBShape()
redraw()
}
}
extension ShapeOverlayView {
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(ShapeOverlayView.deleteShape) {
return true
}
return false
}
override var canBecomeFirstResponder: Bool {
return true
}
}
|
print("Hello world")
/*:
# Swift
* Строгая статическая типизация
* Типовыводимость
* Мультипарадигменность:
* OOP;
* POP;
* FP;
* Imperative;
* Declarative
* OpenSource
* Version 5.1
* [Swift.org](https://swift.org)/[swiftbook.ru](https://swiftbook.ru/content/languageguide)
*/
|
//
// LeftThirdCalculation.swift
// Rectangle
//
// Created by Ryan Hanson on 7/26/19.
// Copyright © 2019 Ryan Hanson. All rights reserved.
//
import Foundation
class FirstThirdCalculation: WindowCalculation {
private var centerThirdCalculation: CenterThirdCalculation?
private var lastThirdCalculation: LastThirdCalculation?
init(repeatable: Bool = true) {
if repeatable && Defaults.subsequentExecutionMode.value != .none {
centerThirdCalculation = CenterThirdCalculation()
lastThirdCalculation = LastThirdCalculation(repeatable: false)
}
}
override func calculateRect(_ window: Window, lastAction: RectangleAction?, visibleFrameOfScreen: CGRect, action: WindowAction) -> RectResult {
guard Defaults.subsequentExecutionMode.value != .none,
let last = lastAction, let lastSubAction = last.subAction else {
return firstThirdRect(window, lastAction: lastAction, visibleFrameOfScreen: visibleFrameOfScreen, action: action)
}
var calculation: WindowCalculation?
if last.action == .firstThird {
switch lastSubAction {
case .topThird, .leftThird:
calculation = centerThirdCalculation
case .centerHorizontalThird, .centerVerticalThird:
calculation = lastThirdCalculation
default:
break
}
} else if last.action == .lastThird {
switch lastSubAction {
case .topThird, .leftThird:
calculation = centerThirdCalculation
default:
break
}
}
if let calculation = calculation {
return calculation.calculateRect(window, lastAction: lastAction, visibleFrameOfScreen: visibleFrameOfScreen, action: action)
}
return firstThirdRect(window, lastAction: lastAction, visibleFrameOfScreen: visibleFrameOfScreen, action: action)
}
func firstThirdRect(_ window: Window, lastAction: RectangleAction?, visibleFrameOfScreen: CGRect, action: WindowAction) -> RectResult {
return isLandscape(visibleFrameOfScreen)
? RectResult(leftThird(visibleFrameOfScreen), subAction: .leftThird)
: RectResult(topThird(visibleFrameOfScreen), subAction: .topThird)
}
private func leftThird(_ visibleFrameOfScreen: CGRect) -> CGRect {
var oneThirdRect = visibleFrameOfScreen
oneThirdRect.size.width = floor(visibleFrameOfScreen.width / 3.0)
return oneThirdRect
}
private func topThird(_ visibleFrameOfScreen: CGRect) -> CGRect {
var oneThirdRect = visibleFrameOfScreen
oneThirdRect.size.height = floor(visibleFrameOfScreen.height / 3.0)
oneThirdRect.origin.y = visibleFrameOfScreen.origin.y + visibleFrameOfScreen.height - oneThirdRect.height
return oneThirdRect
}
}
|
//
// EaseMobMessageManager.swift
// SpecialTraining
//
// Created by 尹涛 on 2018/11/20.
// Copyright © 2018 youpeixun. All rights reserved.
//
import Foundation
class EaseMobMessageManager: NSObject {
override init() {
super.init()
}
// 注册环信回调回调
func emRegisterDelegate() {
EMClient.shared().chatManager.add(self, delegateQueue: nil)
EMClient.shared().contactManager.add(self, delegateQueue: nil)
}
}
extension EaseMobMessageManager: EMChatManagerDelegate {
func conversationListDidUpdate(_ aConversationList: [Any]!) {
PrintLog("会话列表发生变化: \(aConversationList)")
NotificationCenter.default.post(name: NotificationName.EaseMob.ConversationListChange, object: nil)
}
func messagesDidReceive(_ aMessages: [Any]!) {
PrintLog("收到消息:\(aMessages)")
NotificationCenter.default.post(name: NotificationName.EaseMob.ReceivedNewMessage, object: aMessages)
}
}
extension EaseMobMessageManager: EMContactManagerDelegate {
func friendRequestDidReceive(fromUser aUsername: String!, message aMessage: String!) {
AddFriendsModel.inster(with: aUsername) {
NotificationCenter.default.post(name: NotificationName.EaseMob.addFriend, object: aUsername)
}
// NoticesCenter.alert(message: "收到 \(aUsername ?? "") 的好友申请", cancleTitle: "拒绝", okTitle: "同意", callBackCancle: {
//
// }) {
// if let error = EMClient.shared()?.contactManager.acceptInvitation(forUsername: aUsername) {
// PrintLog("同意 \(aUsername) 的好友申请 失败!")
// }else {
// PrintLog("已同意 \(aUsername) 的好友申请!")
// }
// }
}
func friendRequestDidApprove(byUser aUsername: String!) {
// NoticesCenter.alert(message: "\(aUsername) 已接受我的好友邀请")
PrintLog("\(aUsername ?? "") 已接受我的好友邀请")
}
func friendshipDidRemove(byUser aUsername: String!) {
// NoticesCenter.alert(message: "\(aUsername) 已解除与我的好友关系")
PrintLog("\(aUsername ?? "") 已解除与我的好友关系")
}
}
|
//
// TabBarController.swift
// Eventful
//
// Created by Amy Chin Siu Huang on 5/9/20.
// Copyright © 2020 Amy Chin Siu Huang. All rights reserved.
//
import UIKit
class TabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
self.tabBar.isTranslucent = false
let tabBarAppearance = UITabBar.appearance()
tabBarAppearance.tintColor = UIColor(red: 0.2784, green: 0.6392, blue: 1, alpha: 1.0)
let fontAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)]
UITabBarItem.appearance().setTitleTextAttributes(fontAttributes, for: .normal)
let eventVC = UINavigationController(rootViewController: EventsViewController())
eventVC.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "eventtabicon"), selectedImage: UIImage(named: "eventtabicon"))
eventVC.tabBarItem.imageInsets = UIEdgeInsets.init(top: 5,left: 0,bottom: -5,right: 0)
let userVC = UINavigationController(rootViewController: UserProfileViewController())
userVC.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "profiletabicon"), selectedImage: UIImage(named: "profiletabicon"))
userVC.tabBarItem.imageInsets = UIEdgeInsets.init(top: 5,left: 0,bottom: -5,right: 0)
let tabBars = [eventVC, userVC]
viewControllers = tabBars
}
}
|
//
// NewRecipeBookNameCell.swift
// RecipeManager
//
// Created by Anton Stamme on 09.04.20.
// Copyright © 2020 Anton Stamme. All rights reserved.
//
import Foundation
import UIKit
class NewRecipeBookNameCell: BaseTableViewCell {
var _target: NewRecipeBookViewController!
lazy var textField: UITextField = {
let tf = UITextField()
tf.translatesAutoresizingMaskIntoConstraints = false
tf.borderStyle = .none
tf.font = UIFont.systemFont(ofSize: 18, weight: .medium)
tf.placeholder = "Name..."
tf.clearButtonMode = .always
tf.delegate = self
return tf
}()
func setUpViews() {
selectionStyle = .none
contentView.addSubview(textField)
textField.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
textField.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16).isActive = true
textField.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -16).isActive = true
textField.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
}
func fillData() {
textField.text = _target.recipeBookName
}
override func prepareForReuse() {
textField.text = ""
}
}
extension NewRecipeBookNameCell: UITextFieldDelegate {
func textFieldDidChangeSelection(_ textField: UITextField) {
_target.recipeBookName = textField.text ?? ""
}
}
|
//
// Card.swift
// Game of Set
//
// Created by Dawid Nadolski on 11/12/2019.
// Copyright © 2019 Dawid Nadolski. All rights reserved.
//
import Foundation
struct Card {
}
|
enum TimetableServiceError: Error {
case invalidLocalFile
case unknown
}
|
//
// SKColor.swift
// TopiPizza
//
// Created by Thomas Dekker on 19-05-16.
// Copyright © 2016 Topicus. All rights reserved.
//
import SpriteKit
extension SKColor {
// MARK: - Properties
static var positiveColor : SKColor {
return SKColor(red: 126, green: 211, blue: 33)
}
static var negativeColor : SKColor {
return SKColor(red: 208, green: 2, blue: 27)
}
// MARK: - Construction
convenience init(red: Int, green: Int, blue: Int) {
self.init(
deviceRed: CGFloat(red)/256,
green: CGFloat(green)/256,
blue: CGFloat(blue)/256,
alpha: 1
)
}
// MARK: - Functions
func setFill(context: CGContext) {
if let fill = colorUsingColorSpace(NSColorSpace.deviceRGBColorSpace()) {
CGContextSetRGBFillColor(
context,
fill.redComponent,
fill.greenComponent,
fill.blueComponent,
fill.alphaComponent
)
}
}
static func randomPastel() -> SKColor {
return random(base: SKColor.whiteColor())
}
static func random(base base: SKColor) -> SKColor {
var red = CGFloat(Int.random(256)) / 256
var green = CGFloat(Int.random(256)) / 256
var blue = CGFloat(Int.random(256)) / 256
if let base = base.colorUsingColorSpace(NSColorSpace.deviceRGBColorSpace()) {
red = (red + base.redComponent) / 2
green = (green + base.greenComponent) / 2
blue = (blue + base.blueComponent) / 2
}
return SKColor(deviceRed: red, green: green, blue: blue, alpha: 1)
}
}
|
//
// ProfileFreindViewController.swift
// coachApp
//
// Created by ESPRIT on 21/04/2018.
// Copyright © 2018 ESPRIT. All rights reserved.
//
import UIKit
import Alamofire
import AlamofireImage
class ProfileFreindViewController: UIViewController {
@IBOutlet weak var imageprofile: UIImageView!
@IBOutlet weak var follow: UILabel!
@IBOutlet weak var myfreinds: UILabel!
@IBOutlet weak var following: UILabel!
@IBOutlet weak var btnfollow: UIButton!
@IBOutlet weak var descrption: UILabel!
@IBOutlet weak var fullname: UILabel!
@IBOutlet weak var imagecover: UIImageView!
var email = UserDefaults.standard.string(forKey: "emailfreind")!
let getUserAbonne = "http://172.19.20.20/coachAppService/web/app_dev.php/getallfollow/"
let followingURL = "http://172.19.20.20/coachAppService/web/app_dev.php/following/"
let getUserConnectedURL = "http://172.19.20.20/coachAppService/web/app_dev.php/getUserConnected/"
var mylistfollwing = [AnyObject]()
var mylistfollow = [AnyObject]()
var userFreinds = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
fullname.text = email
self.imageprofile.layer.cornerRadius = self.imageprofile.frame.size.width / 2
self.imageprofile.clipsToBounds = true
// Do any additional setup after loading the view.
getUserConnected() { (reviews) in
let firstname = reviews.firstName
let lastname = reviews.lastName
self.fullname.text = firstname! + " " + lastname!
let downloadURL = NSURL(string: "http://172.19.20.20/coachAppService/web/uploads/images/" + reviews.image!)
//emissionImg?.af_setImage(withURL: downloadURL! as URL)
self.imageprofile.af_setImage(withURL: downloadURL! as URL)
self.imagecover.af_setImage(withURL: downloadURL! as URL)
}
getNumberFollow() { (reviews) in
self.follow.text = String(reviews)
self.myfreinds.text = String(reviews)
}
getNumberFollowIng() { (reviews) in
self.following.text = String(reviews)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func followAction(_ sender: Any) {
if(btnfollow.titleLabel?.text=="UnFollow"){
btnfollow.backgroundColor = UIColor.blue
btnfollow.setTitleColor(UIColor.white, for: .normal)
btnfollow.setTitle("Follow", for: .normal)
}
else{
btnfollow.backgroundColor = UIColor.white
btnfollow.setTitleColor(UIColor.blue, for: .normal)
btnfollow.setTitle("UnFollow", for: .normal)
}
DispatchQueue.main.async {
let parameters = [
"emailMe": UserDefaults.standard.string(forKey: "email")!,
"emailYou": self.email,
]
Alamofire.request(self.followingURL, method: .post, parameters: parameters).responseJSON { response in
switch response.result {
case .success:
let res = response.result.value as! NSDictionary
print(res)
//res.object(forKey: "nbFollowedYou")
print(res.object(forKey: "nbFollowedYou") as! Int)
let nbfollowing = res.object(forKey: "nbFollowedYou") as! Int
self.following.text = String(nbfollowing)
case .failure(let error):
print(error)
}
}
}
}
func getUserConnected(completion: @escaping (User) -> Void) {
print(email)
print("aaaaa")
let parameters = [
"email": email,
]
Alamofire.request(getUserConnectedURL, method: .post, parameters: parameters).responseJSON { response in
switch response.result {
case .success:
let dict = response.result.value as? Dictionary<String,AnyObject>
let res = dict!["user"] as! NSDictionary
print(res)
//example if there is an id
let domain: Domain = Domain(id: 0, name: "")
let firstname = res.object(forKey: "first_name")!
let id = res.object(forKey: "id")!
let phonenumber = res.object(forKey: "phone_num")!
let lastName = res.object(forKey: "last_name")!
let image = res.object(forKey: "image")!
let email = res.object(forKey: "email")!
let user: User = User(id: 0, firstName: "", lastName: "", email: "", password: "", birthday: "", gender: "", image: "", nbfollow: 0, nbfollowed: 0, phoneNumber: 0, typeUser: "", domain: domain)
user.firstName = firstname as? String
user.id = id as? Int
user.phoneNumber = phonenumber as? Int
user.lastName = lastName as? String
user.image = image as? String
user.email = email as? String
completion(user)
case .failure(let error):
print(error)
}
}
}
func loadlist () {
let parameters = [
"email": UserDefaults.standard.string(forKey: "email")!,
]
Alamofire.request(getUserAbonne, method: .post, parameters: parameters).responseJSON { response in
switch response.result {
case .success:
let result = response.result
if let dict = result.value as? Dictionary<String,AnyObject> {
if let inerDict = dict["mylistfollow"] {
print(inerDict)
self.mylistfollwing = inerDict as! [AnyObject]
}
}
case .failure(let error):
print(error)
}
}
}
func getNumberFollowIng(completion: @escaping (Int) -> Void) {
let parameters = [
"email": email
]
Alamofire.request(getUserAbonne, method: .post, parameters: parameters).responseJSON { response in
switch response.result {
case .success:
let result = response.result
if let dict = result.value as? Dictionary<String,AnyObject> {
if let inerDict = dict["mylistfollwing"] {
print(inerDict)
self.mylistfollwing = inerDict as! [AnyObject]
completion(self.mylistfollwing.count)
}
}
case .failure(let error):
print(error)
}
}
}
func getNumberFollow(completion: @escaping (Int) -> Void) {
let parameters = [
"email": email,
]
Alamofire.request(getUserAbonne, method: .post, parameters: parameters).responseJSON { response in
switch response.result {
case .success:
let result = response.result
if let dict = result.value as? Dictionary<String,AnyObject> {
if let inerDict = dict["mylistfollow"] {
print(inerDict)
self.mylistfollow = inerDict as! [AnyObject]
completion(self.mylistfollow.count)
}
}
case .failure(let error):
print(error)
}
}
}
@IBAction func backAct(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func emchibrasomk(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func messageAct(_ sender: Any) {
performSegue(withIdentifier: "profileToMessage", sender: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// ViewController.swift
// example
//
// Created by GG on 10/12/2020.
//
import UIKit
import SocketManager
class ViewController: UIViewController {
@IBOutlet weak var socketState: UILabel!
var socketManager: SocketManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// socketManager = SocketManager(root: URL(string: "wss://echo.websocket.org")!,
socketManager = SocketManager(root: URL(string: "ws://localhost:8080")!,
clientIdentifier: UUID(),
delegate: self,
handledTypes: [LoginResponseMessage.self])
}
@IBAction func connect(_ sender: Any) {
socketManager.connect()
}
@IBAction func sendMessage(_ sender: Any) {
// socketManager.send(TestSocketMessage(data: ["test" : "My Test"])) {
//
// }
}
}
private struct TokenMessage: Codable {
let token: String
let state: Int
}
class LoginMessage: ATAWriteSocketMessage {
private static let routeToCheck = "Login"
override var checkMethod: SocketRoute { LoginMessage.routeToCheck }
enum CodingKeys: String, CodingKey {
case token = "params"
}
required init(from decoder: Decoder) throws {
fatalError()
}
init() {
super.init(route: LoginMessage.routeToCheck)
}
init(routeToCheck: SocketRoute) {
super.init(route: routeToCheck)
}
override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(TokenMessage(token: "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MzM2ODk5OTYsImlhdCI6MTYzMzY4Mjc5NiwidXNlclV1aWQiOiJmNTY1Yzg5ZS01N2UxLTEwM2ItOTEwZS01OTA4N2Q3ZjkwZmMiLCJ1c2VySWQiOjI5Mn0.Qpm-KY2izkVcq_csz-aXF6TD6jnrWiLcxihYHWgGqJKw2Amk_ANIeFCzsMAjv0_kyIcULSAS9700Smj1yjUVOq79kBNRAQ_ZFO9Z836CLKBs9zTih5nyZs3gYIeMetSkR_uQJkoKJWxpbet8yY1LlO609kqskA7mXoxk9eUZh5ajQebfTkLFHG3uGbhW46ulH8smbr7-jva1Kb7LQlhmOMCr8-vZrV1Alws_CGAi_8OxqA_kS9VLkTOsrHM4BuVkqPNymVit1fBTHGZs1n9dS_XJeSA5Pg8emrrHnab10FuqEvSDpUFhyRsubZbqZg7-OE38poCaDyC8sf4UmtBslA", state: 0), forKey: .token)
try super.encode(to: encoder)
}
}
class LoginResponseMessage: ATAReadSocketMessage<LoginMessage> {
static let routeToCheck = "LoginResponse"
override var checkMethod: SocketRoute { LoginResponseMessage.routeToCheck }
enum CodingKeys: String, CodingKey {
case token = "params"
}
required init(from decoder: Decoder) throws {
do {
let container = try decoder.container(keyedBy: CodingKeys.self)
//mandatory
guard try container.decodeIfPresent(TokenMessage.self, forKey: .token) != nil else {
throw EncodingError.invalidValue("Token", EncodingError.Context.init(codingPath: [CodingKeys.token], debugDescription: "Token is missing"))
}
try super.init(from: decoder)
} catch (let error) {
throw error
}
}
}
extension ViewController: SocketManagerDelegate {
func route(_ route: SocketRoute, failedWith error: SocketErrorMessage, message: ATAErrorSocketMessage) {
print("\(route) failedWith \(error) from \(message)")
}
func socketDidConnect(_ socketManager: SocketManager) {
socketState.text = "Connecté"
socketState.textColor = .green
socketManager.send(LoginMessage())
}
func socketDidDisconnect(_ socketManager: SocketManager, reason: String, code: UInt16) {
socketState.text = "Déconnecté \(reason)"
socketState.textColor = .magenta
}
func didReceiveMessage(_ socketManager: SocketManager, message: SocketBaseMessage) {
print(message)
}
func didReceiveError(_ error: Error?) {
socketState.text = "ERROR \(error?.localizedDescription ?? "")"
socketState.textColor = .red
}
}
|
//
// deviceModel.swift
//
//
// Created by Michael Kane on 8/19/16.
//
//
import UIKit
import Foundation
class DeviceModel: NSObject {
static let sharedInstance = DeviceModel()
func deviceDictionary() -> NSDictionary {
let deviceDictionary = [
"x86_64" : "Simulator", //Simulator
"iPhone1,1" : "iPhone 1G", //iPhone
"iPhone1,2" : "iPhone 3G",
"iPhone2,1" : "iPhone 3GS",
"iPhone3,1" : "iPhone 4",
"iPhone3,2" : "iPhone 4",
"iPhone3,3" : "iPhone 4",
"iPhone4,1" : "iPhone 4S",
"iPhone5,1" : "iPhone 5",
"iPhone5,2" : "iPhone 5",
"iPhone5,3" : "iPhone 5C",
"iPhone5,4" : "iPhone 5C",
"iPhone6,1" : "iPhone 5S",
"iPhone6,2" : "iPhone 5S",
"iPhone7,2" : "iPhone 6",
"iPhone7,1" : "iPhone 6 Plus",
"iPhone8,1" : "iPhone 6s",
"iPhone8,2" : "iPhone 6s Plus",
"iPhone8,4" : "iPhone SE",
"iPad1,1" : "iPad 1", //iPads
"iPad2,1" : "iPad 2",
"iPad2,2" : "iPad 2 Cellular",
"iPad2,3" : "iPad Cellular",
"iPad2,4" : "iPad 2",
"iPad3,1" : "iPad 3",
"iPad3,2" : "iPad 3 Cellular",
"iPad3,3" : "iPad 3 Cellular",
"iPad3,4" : "iPad 4",
"iPad3,5" : "iPad 4 Cellular",
"iPad3,6" : "iPad 4 Cellular",
"iPad4,1" : "iPad Air",
"iPad4,2" : "iPad Air Cellular",
"iPad4,3" : "iPad Air Cellular",
"iPad2,5" : "iPad Mini",
"iPad2,6" : "iPad Mini Cellular",
"iPad2,7" : "iPad Mini Cellular",
"iPad4,4" : "iPad Mini Retina",
"iPad4,5" : "iPad Mini Retina Cellular",
"iPad4,6" : "iPad Mini Retina Cellular",
"iPad4,7" : "iPad Mini 3",
"iPad4,8" : "iPad Mini 3 Cellular",
"iPad4,9" : "iPad Mini 3 Cellular",
"iPad5,1" : "iPad Air 4",
"iPad5,2" : "iPad Air 4 Cellular",
"iPad5,3" : "iPad Air 2",
"iPad5,4" : "iPad Air 2 Cellular",
"iPad6,3" : "iPad Pro 9.7",
"iPad6,4" : "iPad Pro 9.7",
"iPad6,7" : "iPad Pro 12.9",
"iPad6,8" : "iPad Pro 12.9"]
return deviceDictionary as NSDictionary
}
}
|
//
// UIFont+StarterKit.swift
// StarterKit
//
// Created by Emilio Pavia on 20/01/2020.
// Copyright © 2020 Emilio Pavia. All rights reserved.
//
import UIKit
public extension UIFont {
func withTraits(_ traits: UIFontDescriptor.SymbolicTraits) -> UIFont {
let descriptor = fontDescriptor.withSymbolicTraits(traits)
return UIFont(descriptor: descriptor!, size: 0) //size 0 means keep the size as it is
}
func bold() -> UIFont {
return withTraits(.traitBold)
}
func italic() -> UIFont {
return withTraits(.traitItalic)
}
@available(iOS 13.0, *)
func withDesign(_ design: UIFontDescriptor.SystemDesign) -> UIFont {
let descriptor = fontDescriptor.withDesign(design)
return UIFont(descriptor: descriptor!, size: 0) //size 0 means keep the size as it is
}
@available(iOS 13.0, *)
func rounded() -> UIFont {
return withDesign(.rounded)
}
}
|
//
// PickerCell.swift
// TrendTestTask
//
// Created by Nikolay on 14/04/2019.
// Copyright © 2019 Nikolay. All rights reserved.
//
import UIKit
class PickerCell: UITableViewCell {
@IBOutlet weak var amountLabel: UILabel!
@IBOutlet weak var checkMarkImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
}
}
|
//
// JetBlackService.swift
// SwiftySensorsTrainers
//
// https://github.com/kinetic-fit/sensors-swift-trainers
//
// Copyright © 2017 Kinetic. All rights reserved.
//
import CoreBluetooth
import SwiftySensors
import Signals
/// :nodoc:
open class JetBlackService: Service, ServiceProtocol {
public static var uuid: String { return "C4630001-003F-4CEC-8994-E489B04D857E" }
public static var characteristicTypes: Dictionary<String, Characteristic.Type> = [
SlowChange.uuid: SlowChange.self,
FastChange.uuid: FastChange.self
]
public var slowChange: SlowChange? { return characteristic(SlowChange.uuid) }
public var fastChange: FastChange? { return characteristic(FastChange.uuid) }
open class SlowChange: Characteristic {
public static var uuid: String { return "C4632B01-003F-4CEC-8994-E489B04D857E" }
public static let writeType = CBCharacteristicWriteType.withResponse
public var data: JetBlackSerializer.SlowChangeData?
required public init(service: Service, cbc: CBCharacteristic) {
super.init(service: service, cbc: cbc)
cbCharacteristic.notify(true)
}
override open func valueUpdated() {
if let value = cbCharacteristic.value {
data = JetBlackSerializer.readSlowChange(value)
}
super.valueUpdated()
}
}
open class FastChange: Characteristic {
public static var uuid: String { return "C4632B02-003F-4CEC-8994-E489B04D857E" }
public static let writeType = CBCharacteristicWriteType.withResponse
public var data: JetBlackSerializer.FastChangeData?
required public init(service: Service, cbc: CBCharacteristic) {
super.init(service: service, cbc: cbc)
cbCharacteristic.notify(true)
}
override open func valueUpdated() {
if let value = cbCharacteristic.value {
data = JetBlackSerializer.readFastChange(value)
}
super.valueUpdated()
}
}
@discardableResult open func setTargetPower(_ watts: UInt16) -> [UInt8] {
let bytes = JetBlackSerializer.setTargetPower(watts)
slowChange?.cbCharacteristic.write(Data(bytes), writeType: SlowChange.writeType)
return bytes
}
@discardableResult open func setRiderWeight(_ weight: UInt16) -> [UInt8] {
let bytes = JetBlackSerializer.setRiderWeight(weight)
slowChange?.cbCharacteristic.write(Data(bytes), writeType: SlowChange.writeType)
return bytes
}
@discardableResult open func setSimulationParameters(rollingResistance: Float, windResistance: Float, grade: Float, windSpeed: Float, draftingFactor: Float) -> [UInt8] {
let bytes = JetBlackSerializer.setSimulationParameters(rollingResistance: rollingResistance,
windResistance: windResistance,
grade: grade,
windSpeed: windSpeed,
draftingFactor: draftingFactor)
fastChange?.cbCharacteristic.write(Data(bytes), writeType: FastChange.writeType)
return bytes
}
}
|
//
// extTests.swift
// SimpleDomainModelTests
//
// Created by YuanShaochen on 2017/10/19.
// Copyright © 2017年 Ted Neward. All rights reserved.
//
import XCTest
import SimpleDomainModel
class extTests: XCTestCase {
func testDescription() {
let test1 = Money(amount: 1, currency:"USD")
let test2 = Money(amount: 2, currency:"GBP")
let test3 = Money(amount: 40, currency:"EUR")
let test4 = Money(amount: 100, currency:"CAN")
XCTAssert(test1.description == "USD1.0")
XCTAssert(test2.description == "GBP2.0")
XCTAssert(test3.description == "EUR40.0")
XCTAssert(test4.description == "CAN100.0")
}
func testJobPerson() {
let job = Job(title: "developer", type: Job.JobType.Hourly(25))
XCTAssert(job.description == "Job:developer, Income:25000")
let su = Person(firstName: "Su", lastName: "Wang", age: 28)
su.job = Job(title: "developer", type: Job.JobType.Hourly(25))
su.spouse = Person(firstName: "Shaochen", lastName: "Yuan", age: 28)
XCTAssert(su.job != nil)
XCTAssert(su.spouse != nil)
XCTAssert(su.description == "[Su Wang, job: developer, spouse: Shaochen Yuan]")
let annie = Person(firstName: "Anne", lastName: "Wong", age: 22)
//annie.spouse = Person(firstName: "Haochen", lastName: "Su", age: 29)
XCTAssert(annie.description == "[Anne Wong, job: Jobless, spouse: Single]")
}
func testExtension() {
let test1 = Money(amount: 20, currency: "USD")
let test2 = Money(amount: 50, currency: "GBP")
let ext1 = 20.USD
let ext2 = 50.GBP
XCTAssert(test1.amount == ext1.amount && test1.currency == ext1.currency)
XCTAssert(test2.amount == ext2.amount && test2.currency == ext2.currency)
}
func testMath() {
let money1 = Money(amount: 4, currency: "USD")
let money2 = Money(amount: 6, currency: "USD")
let money3 = Money(amount: 1, currency: "USD")
XCTAssert(money1.add(money2).amount == 10 && money2.add(money3).amount == 7)
XCTAssert(money1.currency == money2.currency && money2.currency == money3.currency && money1.currency == money3.currency)
let moneySub1 = Money(amount: 10, currency: "USD")
let moneySub2 = Money(amount: 30, currency: "USD")
let moneySub3 = Money(amount: 10, currency: "USD")
XCTAssert(moneySub1.subtract(moneySub2).amount == 20 && moneySub2.subtract(moneySub3).amount == -20)
XCTAssert(moneySub1.currency == moneySub2.currency && moneySub2.currency == moneySub3.currency && moneySub1.currency == moneySub3.currency)
}
}
|
//
// LoginController.swift
// tennislike
//
// Created by Maik Nestler on 05.12.20.
//
import UIKit
import JGProgressHUD
protocol AuthenticationDelegate: class {
func authenticationComplete()
}
class LoginController: UIViewController {
//MARK: - Properties
private var viewModel = LoginViewModel()
weak var delegate: AuthenticationDelegate?
private let logoImageView: UIImageView = {
let iv = UIImageView()
iv.contentMode = .scaleAspectFit
iv.clipsToBounds = true
iv.image = #imageLiteral(resourceName: "person_1")
return iv
}()
private lazy var emailContainerView: UIView = {
let view = UIView().inputContainerView(image: SFSymbols.mail!, textField: emailTextField)
view.heightAnchor.constraint(equalToConstant: 50).isActive = true
return view
}()
private lazy var passwordContainerView: UIView = {
let view = UIView().inputContainerView(image: SFSymbols.password!, textField: passwordTextField)
view.heightAnchor.constraint(equalToConstant: 50).isActive = true
return view
}()
private let emailTextField: UITextField = {
return UITextField().textField(withPlaceholder: "E-Mail", isSecureTextEntry: false, keyboardType: .emailAddress)
}()
private let passwordTextField: UITextField = {
return UITextField().textField(withPlaceholder: "Passwort", isSecureTextEntry: true, keyboardType: .default)
}()
private let loginButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Log In", for: .normal)
button.tintColor = .brandingColor
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
button.backgroundColor = .clear
button.layer.cornerRadius = 10
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.lightGray.cgColor
button.addTarget(self, action: #selector(handleLogin), for: .touchUpInside)
return button
}()
let dontHaveAccountButton: UIButton = {
let button = UIButton(type: .system)
let attributedTitle = NSMutableAttributedString(string: "Du hast noch keinen Account? ", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor.white])
attributedTitle.append(NSAttributedString(string: "Melde dich an", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16), NSAttributedString.Key.foregroundColor: UIColor.black]))
button.addTarget(self, action: #selector(handleShowSignUp), for: .touchUpInside)
button.setAttributedTitle(attributedTitle, for: .normal)
return button
}()
//MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configureGradientLayer()
dismissKeyboardTapGesture()
configureNavigationBarHide()
configureUI()
configureTextFieldObservers()
}
//MARK: - Selectors
@objc func handleLogin() {
guard let email = emailTextField.text else { return }
guard let password = passwordTextField.text else { return }
let hud = JGProgressHUD(style: .dark)
// hud.textLabel.text = "Logging In"
hud.show(in: view)
AuthService.logUserIn(withEmail: email, password: password) { (result, error) in
if let error = error {
print("DEBUG: Error logging user in \(error.localizedDescription)")
hud.dismiss()
return
}
hud.dismiss()
self.delegate?.authenticationComplete()
}
}
@objc func handleShowSignUp() {
let signUpVC = SignUpController()
signUpVC.delegate = delegate
navigationController?.pushViewController(signUpVC, animated: true)
}
@objc func textDidChange(sender: UITextField) {
if sender == emailTextField {
viewModel.email = sender.text
} else {
viewModel.password = sender.text
}
checkFormStatus()
}
//MARK: - Helper Function
func configureUI() {
view.backgroundColor = .brandingColor
view.addSubview(logoImageView)
logoImageView.centerXView(inView: view, topAnchor: view.safeAreaLayoutGuide.topAnchor, paddingTop: 0)
view.addSubview(loginButton)
loginButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
let stackView = UIStackView(arrangedSubviews: [emailContainerView, passwordContainerView, loginButton])
stackView.axis = .vertical
stackView.distribution = .fillEqually
stackView.spacing = 24
view.addSubview(stackView)
stackView.anchor(top: logoImageView.bottomAnchor, left: view.leftAnchor, right: view.rightAnchor, paddingTop: 40, paddingLeft: 16, paddingRight: 16)
view.addSubview(dontHaveAccountButton)
dontHaveAccountButton.centerX(inView: view)
dontHaveAccountButton.anchor(bottom: view.safeAreaLayoutGuide.bottomAnchor, height: 32)
}
func checkFormStatus() {
if viewModel.formIsValid {
loginButton.isEnabled = true
loginButton.backgroundColor = .white
} else {
loginButton.isEnabled = false
loginButton.backgroundColor = .clear
}
}
func configureTextFieldObservers() {
emailTextField.addTarget(self, action: #selector(textDidChange), for: .editingChanged)
passwordTextField.addTarget(self, action: #selector(textDidChange), for: .editingChanged)
}
}
|
// GreetingRouter.swift
import UIKit
/// Greeting Router
protocol GreetingRouter { }
/// Greeting Wireframe
///
/// `Wireframe`プロトコルです。
///
/// `AppGreetingView`に関する画面遷移を担当し、`View`の参照を保持し、`Presenter`オブジェクトを生成し`View`に設定します。
protocol GreetingWireframe: GreetingRouter {
var View: GreetingViewController? { get set }
func presentGreetingView(from wireframe: AppWireframe, completion: (() -> Void)?)
func closeGreetingView(from presenter: GreetingPresenterInterface)
}
/// Greeting Wireframe Impl
///
/// `GreetingWireframe`プロトコルを実装します。
///
/// `Wireframe`は `UIKit`をimportできるので、UIWindow, UIViewControllerなどを扱うことができます。
struct GreetingWireframeImpl: GreetingWireframe {
let GreetingStoryboard = "Greeting"
var View: GreetingViewController?
func presentGreetingView(from wireframe: AppWireframe, completion: (() -> Void)?) {
let sb = UIStoryboard(name: GreetingStoryboard, bundle: nil)
guard let nc = sb.instantiateInitialViewController() as? UINavigationController,
let greetingView = nc.viewControllers[0] as? GreetingViewController else {
return
}
Router.App.Greeting.View = greetingView
greetingView.presenter = GreetingPresenterImpl(greetingView)
wireframe.View?.present(nc, animated: true, completion: completion)
}
func closeGreetingView(from presenter: GreetingPresenterInterface) {
if presenter.shouldClose {
Router.App.closeGreetingView(completion: {
presenter.didClose()
})
}
}
}
|
//
// MovieTableViewCell.swift
// TEST
//
// Created by Deniz Tutuncu on 2/15/19.
// Copyright © 2019 Deniz Tutuncu. All rights reserved.
//
import UIKit
class MovieTableViewCell: UITableViewCell {
@IBOutlet weak var titleLable: UILabel!
@IBOutlet weak var overviewLabel: UILabel!
@IBOutlet weak var ratingLabel: UILabel!
@IBOutlet weak var movieImageView: UIImageView!
var movies: DSTMovie?{
didSet{
updateViews()
}
}
var movieImage: UIImage? {
didSet{
updateViews()
}
}
func updateViews() {
guard let movies = movies else {return}
titleLable.text = movies.title
ratingLabel.text = movies.overview
overviewLabel.text = " Rating: \(movies.rating) / 100"
movieImageView.image = movieImage
}
}
|
//
// EditRecipeController.swift
// RecipeMadness
//
// Created by Ramisetty,Tejesh Kumar on 4/14/15.
// Copyright (c) 2015 Tejesh Kumar Ramisetty. All rights reserved.
//
import UIKit
import QuartzCore
//Added textfielddelegate by CG on Apr16
class EditRecipeController: UIViewController, UITableViewDelegate, UITableViewDataSource,UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate
{
@IBOutlet weak var txtName: UITextField!
@IBOutlet weak var txtUnits: UITextField!
@IBOutlet weak var txtQty: UITextField!
@IBOutlet weak var txtServes: UITextField!
@IBOutlet weak var tableViewIngredientsToSave: UITableView!
@IBOutlet weak var recipeImage: UIImageView!
@IBOutlet weak var txtRecipeProcedure: UITextView!
var matchingUnits: [String] = []
let picker = UIImagePickerController()
var ingredientsInRecipe: [TempIngredient] = []
var distinctIngredients: [Ingredient] = []
var matchingIngredients: [Ingredient] = []
var recipe: Recipe!
var appy = (UIApplication.sharedApplication().delegate as! AppDelegate)
@IBOutlet weak var lblIngredientBar: UILabel!
@IBOutlet weak var lblIngredientListBar: UILabel!
override func viewDidLoad()
{
super.viewDidLoad()
tableViewIngredientsToSave.rowHeight = CGFloat(25)
recipeImage.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "imageTapped:"))
txtRecipeProcedure.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "recipeTapped:"))
distinctIngredients = DBmanager.getDistinctIngredients()
picker.delegate = self
self.view.backgroundColor = appy.viewBackground
tableViewIngredientsToSave.layer.masksToBounds = true
tableViewIngredientsToSave.layer.cornerRadius = 8
tableViewIngredientsToSave.backgroundColor = appy.tableViewBackground
txtRecipeProcedure.backgroundColor = appy.tableViewBackground
txtRecipeProcedure.layer.masksToBounds = true
txtRecipeProcedure.layer.cornerRadius = 8
txtRecipeProcedure.backgroundColor = appy.labelViewBackground
lblIngredientBar.layer.masksToBounds = true
lblIngredientBar.layer.cornerRadius = 8
lblIngredientBar.backgroundColor = appy.labelViewBackground
lblIngredientListBar.layer.masksToBounds = true
lblIngredientListBar.layer.cornerRadius = 8
lblIngredientListBar.backgroundColor = appy.labelViewBackground
recipeImage.layer.masksToBounds = true
recipeImage.layer.cornerRadius = 8
txtRecipeProcedure.setContentOffset(CGPointZero, animated: true)
}
override func viewWillAppear(animated: Bool)
{
appy.showProcessIndicator()
self.title = recipe.name
recipeImage.image = recipe.image as? UIImage
txtRecipeProcedure.text = recipe.procedure
txtRecipeProcedure.setContentOffset(CGPointZero, animated: true)
txtServes.text = recipe.numServes.description
txtServes.textAlignment = .Right
tableViewIngredientsToSave.reloadData()
appy.hideProcessIndicator()
}
func imageTapped(sender: UIImageView)
{
picker.allowsEditing = false
picker.sourceType = .PhotoLibrary
presentViewController(picker, animated: true, completion: nil)
}
func recipeTapped(sender: UITextField)
{
performSegueWithIdentifier("EditRecipe", sender: nil)
}
@IBAction func textChanged(sender: AnyObject)
{
//Modified by CG on Apr16
if(sender as! UITextField == txtName)
{
searchAutocompleteEntriesWithSubstring(txtName.text!)
}
else if(sender as! UITextField == txtUnits)
{
getMatchingUnits(txtUnits.text!)
print(txtName.text)
}
//End CG
}
@IBAction func checkServesValue(sender: AnyObject)
{
if(txtServes.text!.utf16Count > 3)
{
txtServes.deleteBackward()
}
}
//For getting image from Lib
func tapImage(gesture: UIGestureRecognizer)
{
picker.allowsEditing = false
picker.sourceType = .PhotoLibrary
presentViewController(picker, animated: true, completion: nil)
}
@IBAction func AddIngredient(sender: AnyObject)
{
appy.showProcessIndicator()
if(txtName.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).isEmpty)
{
let alertView = UIAlertView(title: "Error", message: "Ingredient name cannot be empty!", delegate: self, cancelButtonTitle: "Dismiss")
alertView.show()
}
else if(txtQty.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).isEmpty)
{
let alertView = UIAlertView(title: "Error", message: "Quantity cannot be empty!", delegate: self, cancelButtonTitle: "Dismiss")
alertView.show()
}
else if(txtUnits.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).isEmpty)
{
let alertView = UIAlertView(title: "Error", message: "Units cannot be empty!", delegate: self, cancelButtonTitle: "Dismiss")
alertView.show()
}
else
{
//Register the ingredient to Db, if it is new one.
let newIngredient = DBmanager.AddIfDistinctIngredient(txtName.text, units: txtUnits.text!)
//Share the ingredient with parent
recipe.addIngredient(newIngredient, quantity: (txtQty.text as NSString).doubleValue)
ClearTextBoxes(self)
tableViewIngredientsToSave.reloadData()
}
appy.hideProcessIndicator()
}
//For clearing text boxes
@IBAction func ClearTextBoxes(sender: AnyObject)
{
txtName.text = ""
txtQty.text = ""
txtUnits.text = ""
self.view.endEditing(true)
}
@IBAction func saveRecipe(sender: AnyObject)
{
appy.showProcessIndicator()
if(txtServes.text!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).isEmpty)
{
let alertView = UIAlertView(title: "Error", message: "Number of serves cannot be empty!", delegate: self, cancelButtonTitle: "Dismiss")
alertView.show()
}
else if recipe.save()
{
let alertView = UIAlertView(title: "success", message: "Updated recipe saved to the book!", delegate: self, cancelButtonTitle: "OK")
alertView.show()
self.navigationController?.popViewControllerAnimated(true)
}
else
{
let alertView = UIAlertView(title: "Fail", message: "Unable to update recipe to the book!", delegate: self, cancelButtonTitle: "OK")
alertView.show()
}
appy.hideProcessIndicator()
}
//After image has been bicked
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
appy.showProcessIndicator()
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
recipe.image = chosenImage
dismissViewControllerAnimated(true, completion: nil)
appy.hideProcessIndicator()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
if(tableView == tableViewIngredientsToSave)
{
return recipe.getIngredients().count
}
else if(autocompleteTableView != nil && tableView == autocompleteTableView)
{
return matchingIngredients.count
}
else
{
return matchingUnits.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
appy.showProcessIndicator()
if(tableView == tableViewIngredientsToSave)
{
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! IngedientViewCell
let ingredient = recipe.getIngredients()[indexPath.row]
cell.setup(indexPath.row+1, name: ingredient.name, units: ingredient.units, qty: ingredient.quantity)
//Added by CG on Apr18
cell.textLabel?.adjustsFontSizeToFitWidth = true
cell.textLabel?.minimumScaleFactor = 0.1
cell.textLabel?.font = UIFont.systemFontOfSize(12.0)
cell.layer.masksToBounds = true
cell.layer.cornerRadius = 8
cell.backgroundColor = appy.cellViewBackground
appy.hideProcessIndicator()
return cell
}
else if(autocompleteTableView != nil && tableView == autocompleteTableView)
{
let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle,
reuseIdentifier: "cell")
let index = indexPath.row as Int
let ingredient = matchingIngredients[indexPath.row]
cell.textLabel?.text = ingredient.name
cell.textLabel?.font = UIFont(name: "Arial", size: 12)
cell.detailTextLabel?.text = ingredient.units
cell.detailTextLabel?.font = UIFont(name: "Arial", size: 10)
cell.layer.masksToBounds = true
cell.layer.cornerRadius = 8
cell.backgroundColor = appy.autoCellViewBackground
cell.hidden = false
appy.hideProcessIndicator()
return cell
}
else
{
let cell = UITableViewCell(style: UITableViewCellStyle.Subtitle,
reuseIdentifier: "cell")
let index = indexPath.row as Int
cell.textLabel?.text = matchingUnits[indexPath.row]
cell.textLabel?.font = UIFont(name: "Arial", size: 12)
cell.layer.masksToBounds = true
cell.layer.cornerRadius = 8
cell.backgroundColor = appy.autoCellViewBackground
cell.hidden = false
appy.hideProcessIndicator()
return cell
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if(segue.identifier == "EditRecipe")
{
(segue.destinationViewController as! AddRecipeIngredientController).parent = self
}
}
//For Autocompletion
var autocompleteTableView: UITableView!
var autocompleteUnits: UITableView!
//For Autocompletion
func setAutocompleteTableView(forTextField: UITextField)
{
if(forTextField == txtName)
{
autocompleteTableView = UITableView(frame: CGRectMake(forTextField.frame.origin.x,forTextField.frame.origin.y + forTextField.frame.height,forTextField.frame.width, 200), style: UITableViewStyle.Plain)
autocompleteTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "AutoCompleteRowIdentifier")
view.addSubview(autocompleteTableView)
autocompleteTableView.layer.masksToBounds = true
autocompleteTableView.layer.cornerRadius = 8
autocompleteTableView.backgroundColor = appy.autoTableBackground
autocompleteTableView.delegate = self
autocompleteTableView.dataSource = self
autocompleteTableView.scrollEnabled = true
autocompleteTableView.hidden = true
autocompleteTableView.rowHeight = 25
}
else if(forTextField == txtUnits)
{
autocompleteUnits = UITableView(frame: CGRectMake(forTextField.frame.origin.x,forTextField.frame.origin.y + forTextField.frame.height,forTextField.frame.width, 100), style: UITableViewStyle.Plain)
autocompleteUnits.registerClass(UITableViewCell.self, forCellReuseIdentifier: "AutoCompleteRowIdentifier")
view.addSubview(autocompleteUnits)
autocompleteUnits.layer.masksToBounds = true
autocompleteUnits.layer.cornerRadius = 8
autocompleteUnits.backgroundColor = appy.autoTableBackground
autocompleteUnits.delegate = self
autocompleteUnits.dataSource = self
autocompleteUnits.scrollEnabled = true
autocompleteUnits.hidden = true
autocompleteUnits.rowHeight = 20
}
}
//For Autocompletion
func textFieldDidBeginEditing(textField: UITextField)
{
//Modified by CG on Apr16
if(textField == txtName)
{
setAutocompleteTableView(forTextField: textField)
}
else if(textField == txtUnits)
{
setAutocompleteTableView(forTextField: textField)
}
//End CG
//Added by CG on Apr21
if(textField == txtQty || textField == txtServes || textField == txtUnits || textField == txtName)
{
if(textField != txtServes)
{
self.view.frame.origin.y -= 90
}
if(textField != txtUnits && textField != txtName)
{
textField.textAlignment = .Right
}
}
//End CG
}
//For Autocompletion
func textFieldShouldEndEditing(textField: UITextField) -> Bool
{
//Modified by CG on Apr16
if(textField == txtName)
{
autocompleteTableView.removeFromSuperview()
}
else if(textField == txtUnits)
{
autocompleteUnits.removeFromSuperview()
}
//End CG
//Added by CG on Apr21
if(textField == txtQty || textField == txtServes || textField == txtUnits || textField == txtName)
{
if(textField != txtServes)
{
self.view.frame.origin.y += 90
}
if(textField != txtUnits && textField != txtName)
{
textField.textAlignment = .Center
}
} //End CG
return true
}
//For Autocompletion
func searchAutocompleteEntriesWithSubstring(substring: String)
{
matchingIngredients = [Ingredient]()
for ing in distinctIngredients
{
if ing.name.uppercaseString.hasPrefix(substring.uppercaseString)
{
matchingIngredients.append(ing)
}
}
if(matchingIngredients.count > 0)
{
autocompleteTableView.hidden = false
autocompleteTableView.reloadData()
}
else
{
autocompleteTableView.hidden = true
}
}
func getMatchingUnits(substring: String)
{
matchingUnits = [String]()
for unit in appy.units
{
if unit.uppercaseString.hasPrefix(substring.uppercaseString)
{
matchingUnits.append(unit)
}
}
if(matchingUnits.count > 0)
{
autocompleteUnits.hidden = false
autocompleteUnits.reloadData()
}
else
{
autocompleteUnits.hidden = true
}
}
//For Autocompletion
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
if(autocompleteTableView != nil && tableView == autocompleteTableView)
{
let selectedCell : UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
txtName.text = matchingIngredients[indexPath.row].name
txtUnits.text = matchingIngredients[indexPath.row].units
txtQty.becomeFirstResponder()
autocompleteTableView.hidden = true
}
else if(autocompleteUnits != nil && tableView == autocompleteUnits)
{
txtUnits.text = matchingUnits[indexPath.row]
autocompleteUnits.hidden = true
}
}
//for deleting ingredient
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
{
if(tableView == tableViewIngredientsToSave)
{
if (editingStyle == UITableViewCellEditingStyle.Delete)
{
DBmanager.deleteRecipeIngredient(recipe.getIngredients()[indexPath.row])
tableViewIngredientsToSave.reloadData()
}
}
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool
{
if(autocompleteTableView != nil && tableView == autocompleteTableView)
{
return false
}
return true
}
//Added by CG on Apr16
func touchesBegan(touches: NSSet, withEvent event: UIEvent)
{
self.view.endEditing(true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool
{
self.view.endEditing(true)
return true
}
@IBAction func ingredientNameChanged(sender: AnyObject)
{
Utility.acceptOnlyCharacter(sender as! UITextField)
}
@IBAction func unitsChanged(sender: AnyObject)
{
Utility.acceptOnlyCharacter(sender as! UITextField)
}
//End CG
}
|
//
// QColor.swift
// TodoList
//
// Created by Christian Oberdörfer on 20.03.19.
// Copyright © 2019 Christian Oberdörfer. All rights reserved.
//
import UIKit
public enum QColor: String {
case lightWhite = "lightwhite"
case white = "white"
case lightRed = "lightred"
case red = "red"
case lightOrange = "lightorange"
case orange = "orange"
case lightYellow = "lightyellow"
case yellow = "yellow"
case lightGreen = "lightgreen"
case green = "green"
case lightBlue = "lightblue"
case blue = "blue"
case lightPurple = "lightpurple"
case purple = "purple"
public var color: UIColor {
switch self {
case .lightWhite:
return UIColor(red: 0.95, green: 0.95, blue: 0.96, alpha: 1.00)
case .white:
return UIColor(red: 0.89, green: 0.86, blue: 0.78, alpha: 1.00)
case .lightRed:
return UIColor(red: 0.73, green: 0.27, blue: 0.24, alpha: 1.00)
case .red:
return UIColor(red: 0.61, green: 0.22, blue: 0.18, alpha: 1.00)
case .lightOrange:
return UIColor(red: 0.89, green: 0.60, blue: 0.25, alpha: 1.00)
case .orange:
return UIColor(red: 0.82, green: 0.42, blue: 0.26, alpha: 1.00)
case .lightYellow:
return UIColor(red: 0.92, green: 0.81, blue: 0.33, alpha: 1.00)
case .yellow:
return UIColor(red: 0.92, green: 0.69, blue: 0.25, alpha: 1.00)
case .lightGreen:
return UIColor(red: 0.45, green: 0.69, blue: 0.61, alpha: 1.00)
case .green:
return UIColor(red: 0.34, green: 0.48, blue: 0.42, alpha: 1.00)
case .lightBlue:
return UIColor(red: 0.49, green: 0.64, blue: 0.81, alpha: 1.00)
case .blue:
return UIColor(red: 0.16, green: 0.31, blue: 0.58, alpha: 1.00)
case .lightPurple:
return UIColor(red: 0.62, green: 0.52, blue: 0.85, alpha: 1.00)
case .purple:
return UIColor(red: 0.40, green: 0.30, blue: 0.62, alpha: 1.00)
}
}
}
|
//
// RestTimeTVC.swift
// Skrot
//
// Created by Jonni on 2015-01-22.
// Copyright (c) 2015 Jonni. All rights reserved.
//
import UIKit
import CoreData
protocol RestTimeProtocol : class {
func restTimeDidCancel()
func restTimeDidSave()
}
class RestTimeTVC: UITableViewController {
var delegate:RestTimeProtocol? = nil
// MARK: - Core Data
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var selectedExercise: Exercise?
var selectedDay: Day?
var selectedString = String()
var anyTouch = UITapGestureRecognizer()
@IBOutlet var restTimeField: UITextField!
@IBOutlet var restTimeSegment: UISegmentedControl!
var tempRestTime:Double = 0.0
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.translucent = false
anyTouch = UITapGestureRecognizer(target: self, action: "tableTap")
tableView.addGestureRecognizer(anyTouch)
anyTouch.enabled = false
loadCancelBtn()
setFields()
}
override func viewDidAppear(animated: Bool) {
restTimeField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableTap(){
self.view.endEditing(true)
anyTouch.enabled = false
}
// MARK: - Checks On Load
func loadCancelBtn() {
let cancelBtn = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: "cancelBtnPressed:")
self.navigationItem.leftBarButtonItem = cancelBtn
}
func setFields(){
let restTime = selectedExercise!.restTime.doubleValue
restTimeField.text = String(format:"%.01f", restTime) + LocalizationStrings._MIN
restTimeField.attributedPlaceholder = NSAttributedString(string:restTimeField.text!, attributes:[NSForegroundColorAttributeName: UIColor.darkGrayColor()])
tempRestTime = restTime
switch selectedExercise!.restTime.doubleValue{
case 1.0:
restTimeSegment.selectedSegmentIndex = 0
case 2.0:
restTimeSegment.selectedSegmentIndex = 1
case 3.0:
restTimeSegment.selectedSegmentIndex = 2
case 4.0:
restTimeSegment.selectedSegmentIndex = 3
case 5.0:
restTimeSegment.selectedSegmentIndex = 4
default:
break
}
}
// MARK: - Actions
@IBAction func restTimeSegmentPressed(sender: UISegmentedControl) {
}
func cancelBtnPressed(sender: UIBarButtonItem) {
if let navController = self.navigationController {
navController.popViewControllerAnimated(true)
}
if (delegate != nil){
delegate?.restTimeDidCancel()
}
}
@IBAction func saveBtnPressed(sender: AnyObject) {
if restTimeField.isFirstResponder() {
restTimeField.resignFirstResponder()
}
anyTouch.enabled = false
save()
}
// MARK: - Text Field Delegates
func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.view.endEditing(true)
anyTouch.enabled = false
//println("Done Button On Keypad Pressed!")
return false
}
@IBAction func textFieldReturn(sender: UITextField) {
//println("Do somthing cool after jumping between textfields!")
stringByReplacing()
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
textField.clearsOnBeginEditing = true
restTimeField.attributedPlaceholder = NSAttributedString(string:textField.text!, attributes:[NSForegroundColorAttributeName: UIColor.darkGrayColor()])
anyTouch.enabled = true
return true
}
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
//println("textFieldShouldEndEditing!")
if textField.text!.isEmpty{
textField.text = textField.placeholder
}
textField.resignFirstResponder()
return true
}
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
let newLength = (textField.text!).characters.count + (string!).characters.count - range.length
return newLength > 3 ? false : true
}
func stringByReplacing(){
let stringByReplacingWeight = restTimeField.text!.stringByReplacingOccurrencesOfString(",", withString: ".")
let strWeight: NSString = stringByReplacingWeight as NSString
let doubleWeight: Double = strWeight.doubleValue
restTimeField.text = String(format:"%.01f", doubleWeight) + LocalizationStrings._MIN
tempRestTime = doubleWeight
}
// MARK: - Save
func save(){
let stringByReplacingWeight = restTimeField.text!.stringByReplacingOccurrencesOfString(",", withString: ".")
let strWeight: NSString = stringByReplacingWeight as NSString
let doubleWeight: Double = strWeight.doubleValue
tempRestTime = doubleWeight
selectedExercise?.restTime = tempRestTime
switch restTimeSegment.selectedSegmentIndex{
case 0:
selectedExercise?.restTime = 1.0
case 1:
selectedExercise?.restTime = 2.0
case 2:
selectedExercise?.restTime = 3.0
case 3:
selectedExercise?.restTime = 4.0
case 4:
selectedExercise?.restTime = 5.0
default:
break
}
//SAVE
if (delegate != nil){
delegate?.restTimeDidSave()
}
if let navController = self.navigationController {
navController.popViewControllerAnimated(true)
}
}
}
|
//
// ToDoItemRepo.swift
// ToDoList
//
// Created by njliu on 1/3/15.
// Copyright (c) 2015 Naijia Liu. All rights reserved.
//
import Foundation
import CoreData
class _ProductRepo : NSObject {
private let entityName = "Product"
lazy var context : NSManagedObjectContext = {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
return appDelegate.managedObjectContext!
}()
func create() -> Product {
return NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: context) as Product
}
func deleteObject(item: Product) {
//context.deleteObject(item)
}
func saveChanges() {
var error: NSError?
if !context.save(&error) {
NSLog("Could not save \(error), \(error?.userInfo)")
}
}
func getAll() -> [Product] {
var error: NSError?
let fetchedResults = context.executeFetchRequest(NSFetchRequest(entityName: entityName), error: &error) as [Product]?
if let results = fetchedResults {
return results
} else {
NSLog("Could not fetch \(error), \(error!.userInfo)")
return []
}
}
} |
//
// String+ext.swift
// MarvelCharacters
//
// Created by Osamu Chiba on 9/26/21.
// Copyright © 2021 Opix. All rights reserved.
//
import Foundation
import CryptoKit
extension String {
// Reference:
// https://stackoverflow.com/questions/32163848/how-can-i-convert-a-string-to-an-md5-hash-in-ios-using-swift/32166735
var md5Hash: String {
return Insecure.MD5.hash(data: self.data(using: .utf8)!).map { String(format: "%02hhx", $0) }.joined()
}
}
|
//
// IDModelObject.swift
// RESS
//
// Created by Luiz Fernando Silva on 17/02/16.
// Copyright © 2016 Luiz Fernando Silva. All rights reserved.
//
import Cocoa
import SwiftyJSON
/// Protocol to be implemented by model objects identifiable by a unique ID
protocol IDModelObject: Hashable {
associatedtype IdentifierType = Int
/// Gets a unique identifier for this model object
var id: IdentifierType { get }
}
/// Default implementation of Hashable for an IDModelObject which has a Hashable key type - returns the hash of the object's ID
extension IDModelObject where IdentifierType: Hashable {
var hashValue: Int {
return id.hashValue
}
}
/// Protocol to be implemented by model objects that conform to a simple { id, name } model structure.
/// This model type is also sortable by name by default.
protocol NamedIDModelObject: IDModelObject, Comparable {
/// Gest the display name of this model
var name: String { get }
init(id: IdentifierType, name: String)
}
/// Comparable extension that is used to sort for interface display
func <<T: NamedIDModelObject>(lhs: T, rhs: T) -> Bool {
return lhs.name < rhs.name
}
// Extension for quick initialization of simple named model objects by providing a JSON with ID and Name, where the ID is an integer
extension ModelObject where Self: NamedIDModelObject, Self.IdentifierType == Int {
init(json: JSON) throws {
try self.init(id: json["id"].tryInt(), name: json["name"].tryString())
}
func serialize() -> JSON {
return ["id": id, "name": name]
}
}
// Extension for quick initialization of simple named model objects by providing a JSON with ID and Name, where the ID is a string
extension ModelObject where Self: NamedIDModelObject, Self.IdentifierType == String {
init(json: JSON) throws {
try self.init(id: json["id"].tryString(), name: json["name"].tryString())
}
func serialize() -> JSON {
return ["id": id, "name": name]
}
}
// Extension that speeds up comparisions of model objects by first checking if their IDs match
// before making a full value-wise comparision
extension ModelObject where Self: IDModelObject, Self.IdentifierType: Equatable {
func equalsTo(_ other: Self) -> Bool {
return self.id == other.id && self.serialize() == other.serialize()
}
}
// Extension that speeds up comparisions of model objects by checking ID and name directly.
// No further comparision is made, as NamedIDModelObjects are assumed to contain only an id and name field.
extension ModelObject where Self: NamedIDModelObject, Self.IdentifierType: Equatable {
func equalsTo(_ other: Self) -> Bool {
return self.id == other.id && self.name == other.name
}
}
|
//
// FirstCell.swift
// NewListForEye
//
// Created by 任前辈 on 16/8/30.
// Copyright © 2016年 任前辈. All rights reserved.
//
import UIKit
typealias ClickEvent = (ItemModel)->()
class FirstCell: UITableViewCell,Reusable {
var model : ItemModel! {
didSet {
nameLabel.text = model.title + model.subTitle
let image = model.feed ?? model.image ?? ""
imageV.yy_setImageWithURL(NSURL(string:image), placeholder: nil, options:.Progressive, progress: nil, transform: nil, completion: nil)
//
}
}
var callBack : ClickEvent?
override func awakeFromNib() {
//
contentView.userInteractionEnabled = false
imageV.contentMode = .ScaleAspectFill
}
@IBAction func play(sender: AnyObject) {
print("播放")
callBack?(model)
}
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var imageV: UIImageView!
}
|
//
// Channel.swift
// Add to Are.na
//
// Created by Charles Broskoski on 1/31/18.
// Copyright © 2018 When It Changed, Inc. All rights reserved.
//
import UIKit
final class Channel {
var id: Int!
var title: String!
var visibility: String!
}
|
//
// FunctionTableViewCell.swift
// WSwiftApp
//
// Created by LHWen on 2018/8/21.
// Copyright © 2018年 LHWen. All rights reserved.
//
import UIKit
class FunctionTableViewCell: UITableViewCell {
var iconImgView: UIImageView?
var titleLbl: UILabel?
var rightImgView: UIImageView?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.contentView.backgroundColor = .white
p_setup()
}
private func p_setup() {
p_setupIconImageViewLayout()
p_setupTitleLableLayout()
p_setupRightImageViewLayout()
}
private func p_setupIconImageViewLayout() {
if iconImgView == nil {
iconImgView = CreateViewFactory.p_setImagVIewScaleAspectFit("mine_password")
self.contentView.addSubview(iconImgView!)
iconImgView?.snp.makeConstraints({ (make) -> Void in
make.centerY.equalTo(self.contentView.snp.centerY)
make.left.equalTo(13.0)
})
}
}
private func p_setupTitleLableLayout() {
if titleLbl == nil {
titleLbl = CreateViewFactory.p_setLableWhiteBGAndOneLinesLeft("修改密码", 15.0, ColorUtility.colorWithHexString(toConvert: "#333333", a: 1.0))
self.contentView.addSubview(titleLbl!)
titleLbl?.snp.makeConstraints({ (make) -> Void in
make.centerY.equalTo(self.contentView.snp.centerY)
make.left.equalTo(iconImgView!.snp.right).offset(13.0)
})
}
}
private func p_setupRightImageViewLayout() {
if rightImgView == nil {
rightImgView = CreateViewFactory.p_setImagVIewScaleAspectFit("My_client_r")
self.contentView.addSubview(rightImgView!)
rightImgView?.snp.makeConstraints({ (make) -> Void in
make.centerY.equalTo(self.contentView.snp.centerY)
make.right.equalTo(-13.0)
})
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
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
}
}
|
//
// NetworkingViewController.swift
// Pruebas
//
// Created by Julio Banda on 05/05/18.
// Copyright © 2018 Julio Banda. All rights reserved.
//
import UIKit
import UILoadControl
class NetworkingViewController: UIViewController {
@IBOutlet weak var connectButton: UIButton!
@IBOutlet weak var contactsTableView: UITableView!
var control: UILoadControl?
var selectedIndexPath = IndexPath(row: -1, section: 0)
var contacts = [User]()
var currentPageIndex = 0
let pageSize = 10
var noMorePages = false
var loadingPage = false
override func viewDidLoad() {
super.viewDidLoad()
control = UILoadControl(target: self, action: #selector(loadNextPage))
contactsTableView.loadControl = control
control?.heightLimit = 80
loadNextPage()
}
@objc func loadNextPage() {
if (control?.isTracking)! {
print("Tracking")
}
if noMorePages || loadingPage {
self.loadingPage = false
self.control?.endLoading()
return
}
loadingPage = true
UIApplication.shared.isNetworkActivityIndicatorVisible = true
ContactsManager().downloadUsers(page: currentPageIndex) { (success, users) in
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.loadingPage = false
self.control?.endLoading()
self.contacts.append(contentsOf: users.results)
self.contactsTableView.reloadData()
self.currentPageIndex += 1
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "DetailSegue" {
let detail = segue.destination as! ContactDetailViewController
detail.contact = sender as! User
}
}
}
extension NetworkingViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == contacts.count - 1 && contacts.count <= 15{
loadNextPage()
}
if contacts.count == 30 {
noMorePages = true
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedIndexPath = indexPath
let cell = tableView.cellForRow(at: selectedIndexPath)
cell!.textLabel?.numberOfLines = 0
contactsTableView.reloadData()
let contact = contacts[indexPath.row]
performSegue(withIdentifier: "DetailSegue", sender: contact)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == selectedIndexPath.row {
return UITableViewAutomaticDimension
}
return contactsTableView.rowHeight
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollView.loadControl?.update()
}
}
extension NetworkingViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.contacts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "contact", for: indexPath)
let contact = self.contacts[indexPath.row]
cell.textLabel?.text = "\(contact.email) - Number \(indexPath.row)"
return cell
}
}
|
//
// LoginTextField.swift
// OnTheMap
//
// Created by omoon on 2016/08/17.
// Copyright © 2016年 lamolabo. All rights reserved.
//
import UIKit
class LoginTextField: UITextField {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.borderStyle = .RoundedRect
self.textColor = UIColor.grayColor()
}
} |
//
// NotesMain.swift
// MC3
//
// Created by Aghawidya Adipatria on 30/07/20.
// Copyright © 2020 Aghawidya Adipatria. All rights reserved.
//
import SwiftUI
struct NotesMain: View {
@EnvironmentObject var moduleInfo : ModuleInfo
@ObservedObject var dataCenter = DataCenter()
@State private var notesName: String = ""
@State private var notesDescription: String = ""
@State private var notesID: Int?
@State private var notesEditing: Bool = false
@State private var editMode: EditMode = .add
var body: some View {
VStack(spacing: 0) {
ModuleSegmentHeader(
title: "Notes",
action: {
self.editMode = .add
self.notesName = ""
self.notesDescription = ""
self.notesEditing = true},
isEditable: !self.notesEditing)
if notesEditing {
NotesEdit(
notesName: $notesName,
notesDescription: $notesDescription,
editMode: .add,
actionCancel: {
self.editMode = .add
self.notesEditing = false
},
actionNext: {
let index = self.moduleInfo.mainNoteIndex
if self.editMode == .add {
self.moduleInfo.currentModule.content.notes.append(
MainNotes(name: self.notesName,
desc: self.notesDescription))
} else if self.editMode == .edit {
self.moduleInfo.currentModule.content.notes[index].name = self.notesName
self.moduleInfo.currentModule.content.notes[index].desc = self.notesDescription
}
self.dataCenter.saveModule(module: self.moduleInfo.currentModule)
self.notesEditing = false
})
} else {
ScrollView(.vertical, showsIndicators: false) {
ZStack {
Rectangle()
.fill(Color.white)
.cornerRadius(10)
.frame(height: CGFloat((self.moduleInfo.currentModule.content.notes.count) * 134 + 30))
VStack(spacing: 0) {
Rectangle()
.fill(Color.separator)
.frame(width: UIScreen.main.bounds.width, height: 1)
ForEach(0..<moduleInfo.currentModule.content.notes.count, id: \.self) { (index) in
NavigationLink(
destination: NotesDetail(
notesEditing: self.$notesEditing),
tag: index,
selection: self.noteBinding(index)
) {
self.getContentCard(index)
}.buttonStyle(PlainButtonStyle())
}
}.padding(.vertical, 20)
}
}
}
Spacer()
}
.onAppear(perform: {
if self.moduleInfo.currentModule.content.notes.count < 1 {
self.notesEditing = true
}
})
}
func noteBinding(_ index: Int) -> Binding<Int?> {
let binding = Binding<Int?>(get: {
self.notesID
}, set: {
self.moduleInfo.mainNoteIndex = index
self.notesID = $0
})
return binding
}
func getContentCard(_ index: Int) -> ContentCard {
let note = self.moduleInfo.currentModule.content.notes[index]
return ContentCard(
title: note.name,
description: note.desc,
actionDelete: {
self.moduleInfo.currentModule.content.notes.remove(at: index)
self.dataCenter.saveModule(module: self.moduleInfo.currentModule)
if self.moduleInfo.currentModule.content.notes.count < 1 {
self.notesEditing = true
}
},
actionEdit: {
self.moduleInfo.mainNoteIndex = index
self.notesName = note.name
self.notesDescription = note.desc
self.editMode = .edit
self.notesEditing = true
}
)
}
}
struct Notes_Previews: PreviewProvider {
static var previews: some View {
NotesMain()
}
}
|
//
// PriceRange.swift
// UberEATS
//
// Created by Sean Zhang on 11/30/17.
// Copyright © 2017 Sean Zhang. All rights reserved.
//
import UIKit
class FilterViewCell1: UICollectionViewCell {
let sortOptions: [String] = ["Recommended", "Most popular", "Rating", "Delivery time"];
let sortImages:[String] = ["filter_recommended", "filter_popular", "filter_rating", "filter_delivery"];
var delegate: FilterSelectDelegate?
lazy var tableView: UITableView = {
let tableView = UITableView(frame: .zero)
tableView.translatesAutoresizingMaskIntoConstraints = false
return tableView
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupTableView()
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setupTableView(){
tableView.delegate = self
tableView.dataSource = self
tableView.register(FilterTableCell.self, forCellReuseIdentifier: "FilterTableCell")
tableView.separatorColor = UIColor.white
tableView.isScrollEnabled = false
}
fileprivate func setupViews(){
addSubview(tableView)
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: topAnchor),
tableView.leftAnchor.constraint(equalTo: leftAnchor, constant: 0),
tableView.rightAnchor.constraint(equalTo: rightAnchor),
tableView.heightAnchor.constraint(equalToConstant: frame.height)
])
}
}
extension FilterViewCell1: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FilterTableCell", for: indexPath) as! FilterTableCell
cell.tl.text = sortOptions[indexPath.row]
cell.iv.image = UIImage(imageLiteralResourceName: sortImages[indexPath.row])
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 40
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
delegate?.selected(section: 0, row: indexPath.row)
}
}
protocol FilterSelectDelegate {
func selected(section: Int, row: Int) -> Void
}
class FilterTableCell: UITableViewCell {
var iv: UIImageView = {
let iv = UIImageView()
iv.contentMode = .scaleAspectFit
iv.translatesAutoresizingMaskIntoConstraints = false
return iv
}()
var tl: UILabel = {
let label = UILabel()
label.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupView() {
addSubview(iv)
NSLayoutConstraint.activate([
iv.centerYAnchor.constraint(equalTo: centerYAnchor),
iv.leftAnchor.constraint(equalTo: leftAnchor, constant: 10),
iv.widthAnchor.constraint(equalToConstant: 24),
iv.heightAnchor.constraint(equalToConstant: 24)
])
addSubview(tl)
NSLayoutConstraint.activate([
tl.centerYAnchor.constraint(equalTo: centerYAnchor),
tl.leftAnchor.constraint(equalTo: iv.rightAnchor, constant: 10),
tl.rightAnchor.constraint(equalTo: rightAnchor, constant: -10),
tl.heightAnchor.constraint(equalToConstant: 24)
])
}
}
|
//
// ProfileView.swift
// TinderClone
//
// Created by JD on 20/08/20.
//
import SwiftUI
struct ProfileView: View {
var body: some View {
VStack(spacing: 20) {
Image("img_jd")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 120, height: 120)
.cornerRadius(60)
.shadow(radius: 5)
VStack(spacing: 5) {
Text("JD")
.font(.system(size: 30))
.fontWeight(.heavy)
Text("iOS Engineer")
Text("Bengaluru, India")
}
ZStack {
HStack(spacing: 50) {
VStack(spacing: 8) {
Image(systemName: "gearshape.fill")
.font(.system(size: 35, weight: .heavy))
.foregroundColor(.gray)
.frame(width: 70, height: 70)
.modifier(ButtonBG())
.cornerRadius(35)
.modifier(ThemeShadow())
Text("Settings")
}
Spacer()
VStack(spacing: 8) {
Image(systemName: "pencil")
.font(.system(size: 35, weight: .heavy))
.foregroundColor(.gray)
.frame(width: 70, height: 70)
.modifier(ButtonBG())
.cornerRadius(35)
.modifier(ThemeShadow())
Text("Edit Info")
}
}.padding(.horizontal, 35)
VStack(spacing: 8) {
Image(systemName: "camera.fill")
.font(.system(size: 40, weight: .heavy))
.foregroundColor(.white)
.frame(width: 90, height: 90)
.background(Color.electricPink)
.cornerRadius(45)
.modifier(ThemeShadow())
Text("Media")
}.offset(y: 40)
}
.offset(y: -20)
VStack {
ProfileCarouselInfo()
Button(action: {}) {
Text("UPGRADE")
.font(.title2)
.bold()
.foregroundColor(.electricPink)
.frame(width: 230, height: 60)
.modifier(ButtonBG())
.cornerRadius(30)
}
.modifier(ThemeShadow())
}
.padding(.top, 60)
}
.padding(.vertical, 30)
}
}
struct ProfileView_Previews: PreviewProvider {
static var previews: some View {
ProfileView()
.preferredColorScheme(.dark)
}
}
struct ProfileCarouselInfo: View {
@State private var selectedTab = 0
@State var currentDate = Date()
let timer = Timer.publish(every: 4, on: .main, in: .common).autoconnect()
let info = CarouselInfo.info
var body: some View {
TabView(selection: $selectedTab) {
ForEach(0..<info.count) { i in
VStack(spacing: 12) {
HStack(spacing: 16) {
Image(systemName: info[i].image)
.font(.system(size: 20))
.foregroundColor(info[i].color)
Text(info[i].title)
.font(.title2)
.bold()
}
Text(info[i].info)
.fontWeight(.light)
Spacer()
}
.tag(i)
}
}
.frame(width: UIScreen.main.bounds.width, height: 100)
.tabViewStyle(PageTabViewStyle())
.onReceive(timer) { input in
withAnimation(.easeInOut(duration: 1)) {
self.selectedTab += 1
if selectedTab == info.count {
selectedTab = 0
}
}
}
}
}
struct CarouselInfo {
let id: Int
let title: String
let info: String
let image: String
let color: Color
static let info = [
CarouselInfo(id: 0,
title: "Get Tinder Gold",
info: "See who likes you & more!",
image: "flame.fill",
color: .gold),
CarouselInfo(id: 1,
title: "Get matches faster",
info: "Boost your profile once a month!",
image: "bolt.fill",
color: .purple),
CarouselInfo(id: 2,
title: "Stand out with Super Likes",
info: "You're 3 times more likely to geta match!",
image: "star.fill",
color: .blue),
CarouselInfo(id: 3,
title: "Swipe around the world",
info: "Passport to anywhere with Tinder Plus!",
image: "location.fill",
color: .blue),
CarouselInfo(id: 4,
title: "Control your profile",
info: "Limit what others see with Tinder Plus.",
image: "key.fill",
color: .orange),
CarouselInfo(id: 5,
title: "I meant to swipe right.",
info: "Get unlimited Rewinds with Tinder Plus!",
image: "gobackward",
color: .gold),
CarouselInfo(id: 6,
title: "Increase your chances",
info: "Get unlimited likes with Tinder Plus!",
image: "heart.fill",
color: Color(UIColor(red: 60/255, green: 229/255, blue: 184/255, alpha: 1)))
]
}
|
//
// Date+Additions.swift
// News
//
// Created by Viacheslav Goroshniuk on 9/23/19.
// Copyright © 2019 Viacheslav Goroshniuk. All rights reserved.
//
import Foundation
import SwiftDate
extension DateFormatter {
struct News {
static let publishedDate: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
let currentTimeZoneOffset = TimeZone.current.secondsFromGMT()
formatter.timeZone = TimeZone(secondsFromGMT: currentTimeZoneOffset)
return formatter
}()
}
}
|
//
// MenuTableViewCell.swift
// MyNews
//
// Created by Yaroslava HLIBOCHKO on 8/2/19.
// Copyright © 2019 Yaroslava HLIBOCHKO. All rights reserved.
//
import UIKit
class MenuTableViewCell: UITableViewCell {
let iconView: UIImageView = {
let icon = UIImageView()
icon.clipsToBounds = true
return icon
}()
let descriptionLabel: UILabel = {
let description = UILabel()
description.textColor = .gray
description.font = UIFont.systemFont(ofSize: 16)
return description
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(iconView)
iconView.translatesAutoresizingMaskIntoConstraints = false
iconView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
iconView.leftAnchor.constraint(equalTo: leftAnchor, constant: 10).isActive = true
iconView.heightAnchor.constraint(equalToConstant: 25).isActive = true
iconView.widthAnchor.constraint(equalToConstant: 25).isActive = true
addSubview(descriptionLabel)
descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
descriptionLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
descriptionLabel.leftAnchor.constraint(equalTo: iconView.rightAnchor, constant: 10).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
//
// ConditionCode.swift
// HeWeatherIO
//
// Created by iMac on 2018/5/25.
// Copyright © 2018年 iMac. All rights reserved.
//
import Foundation
enum ConditionCode: Int {
case sunny = 100
case cloudy = 101
case fewCloudy = 102
case partlyCloudy = 103
case overcast = 104
case windy = 200
case calm = 201
case lightBreeze = 202
case moderate = 203
case freshBreeze = 204
case strongBreeze = 205
case highWind = 206
case gale = 207
case strongGale = 208
case storm = 209
case violentStorm = 210
case hurricane = 211
case tornado = 212
case tropicalStorm = 213
case showerRain = 300
case heavyShowerRain = 301
case thunderShower = 302
case heavyThunderStorm = 303
case hail = 304
case lightRain = 305
case moderateRain = 306
case heavyRain = 307
case extremeRain = 308
case drizzleRain = 309
case stormRain = 310
case heavyStormRain = 311
case severeStormRain = 312
case freezingRain = 313
case lightSnow = 400
case moderateSnow = 401
case heavySnow = 402
case snowstorm = 403
case sleet = 404
case rainAndSnow = 405
case showerSnow = 406
case snowFlurry = 407
case mist = 500
case foggy = 501
case haze = 502
case sand = 503
case dust = 504
case duststorm = 507
case sandstorm = 508
case hot = 900
case cold = 901
case unknown = 999
}
|
//
// AppDelegate.swift
// RealmTasks
//
// Created by Hossam Ghareeb on 10/12/15.
// Copyright © 2015 Hossam Ghareeb. All rights reserved.
//
import UIKit
import UserNotifications
import Firebase
import FirebaseMessaging
import RealmSwift
import FBSDKCoreKit
import FBSDKLoginKit
import WalinnsAPI_Swift
import SafariServices
import CleverTapSDK
import Appsee
let uiRealm = try! Realm()
fileprivate let viewActionIdentifier = "VIEW_IDENTIFIER"
fileprivate let newsCategoryIdentifier = "NEWS_CATEGORY"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate ,UIGestureRecognizerDelegate {
var window: UIWindow?
let gcmMessageIDKey = "847728109840"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// CleverTap.autoIntegrate()
Appsee.start()
FirebaseApp.configure()
Messaging.messaging().delegate = self
if #available(iOS 10.0, *) {
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
CleverTap.sharedInstance()?.handleNotification(withData: userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
Messaging.messaging().appDidReceiveMessage(userInfo)
// CleverTap.sharedInstance()?.handleNotification(withData: userInfo)
print("user info \(userInfo)")
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
// [END receive_message]
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the FCM registration token.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")
Messaging.messaging().apnsToken = deviceToken;
// With swizzling disabled you must set the APNs token here.
// Messaging.messaging().apnsToken = deviceToken
}
}
// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// With swizzling disabled you must let Messaging know about the message, for Analytics
// Messaging.messaging().appDidReceiveMessage(userInfo)
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
// Change this to your preferred presentation option
completionHandler([])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
let aps = userInfo["aps"] as! [String: AnyObject]
if let newsItem = NewsItem.makeNewsItem(aps) {
(window?.rootViewController as? UITabBarController)?.selectedIndex = 1
if response.actionIdentifier == viewActionIdentifier,
let url = URL(string: newsItem.link) {
let safari = SFSafariViewController(url: url)
window?.rootViewController?.present(safari, animated: true, completion: nil)
}
}
completionHandler()
}
}
extension AppDelegate : MessagingDelegate {
// [START refresh_token]
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
WalinnsApi.sendPushToken(push_token: fcmToken)
// TODO: If necessary send token to application server.
// Note: This callback is fired at each app startup and whenever a new token is generated.
}
// [END refresh_token]
// [START ios_10_data_message]
// Receive data messages on iOS 10+ directly from FCM (bypassing APNs) when the app is in the foreground.
// To enable direct data messages, you can set Messaging.messaging().shouldEstablishDirectChannel to true.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let tapGesture = UITapGestureRecognizer(target: self, action: nil)
tapGesture.delegate = self
window?.addGestureRecognizer(tapGesture)
return true
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
// User tapped on screen, do whatever you want to do here.
print("Touch gesture ", touch)
return true
}
}
|
//: Playground - noun: a place where people can play
import UIKit
///Sorted 方法
let names = ["Chris","Alex","Ewa","Barry","Daniella"]
func backward(_ s1: String, _ s2: String) -> Bool {
return s1 > s2
}
var snNames = names.sorted()
var reversedNames = names.sorted(isOrderedBefore: backward)
///闭包表达式语法
//{ (parameters) -> (return type) in
// statements
//}
///尾随闭包
func someFunction(closure:() -> Void){
print("www")
}
someFunction(closure: {
}) |
//
// main.swift
// Calc Array Points
//
// Created by studentuser on 10/11/17.
// Copyright © 2017 Nestor Qin. All rights reserved.
//
import Foundation
func add(num_1: Int?, num_2: Int?) -> Double {
if (num_1 == nil || num_2 == nil) {
print("Error")
return -1
} else {
return Double(num_1!) + Double(num_2!)
}
}
func subtract(num_1: Int?, num_2: Int?) -> Double {
if (num_1 == nil || num_2 == nil) {
print("Error")
return -1
} else {
return Double(num_1!) - Double(num_2!)
}
}
func multiply(num_1: Int?, num_2: Int?) -> Double {
if (num_1 == nil || num_2 == nil) {
print("Error")
return -1
} else {
return Double(num_1!) * Double(num_2!)
}
}
func divide(num_1: Int?, num_2: Int?) -> Double {
if (num_1 == nil || num_2 == nil) {
print("Error")
return -1
} else {
return Double(num_1!) / Double(num_2!)
}
}
func calculate(operation:(Int?, Int?) -> Double, num_1: Int?, num_2: Int?) -> Double {
if (num_1 == nil || num_2 == nil) {
print("Error")
return -1.0
} else {
return Double(operation(num_1, num_2))
}
}
func add(nums: [Int?]?) -> Double {
if (nums == nil) {
print("Error")
return -1.0
} else {
var result = 0.0
for num in nums! {
if (num == nil) {
print("Error")
return -1.0
} else {
result += Double(num!)
}
}
return result
}
}
func multiply(nums: [Int?]?) -> Double {
if (nums == nil) {
print("Error")
return -1.0
} else {
var result = 0.0
for num in nums! {
if (num == nil) {
print("Error")
return -1.0
} else {
result *= Double(num!)
}
}
return result
}
}
func count(nums: [Int?]?) -> Double {
if (nums == nil) {
print("Error")
return -1.0
} else {
var count = 0.0
for num in nums! {
if (num == nil) {
print("Error")
return -1.0
} else {
count += 1.0
}
}
return count
}
}
func avg(nums: [Int?]?) -> Double {
if (nums == nil) {
print("Error")
return -1.0
} else {
var sum = 0.0
for num in nums! {
if (num == nil) {
print("Error")
return -1.0
} else {
sum += Double(num!)
}
}
return Double(sum) / Double(nums!.count)
}
}
func calcPoints(operation:([Int?]?) -> Double, nums: [Int?]?) -> Double {
if (nums == nil) {
print("Error")
return -1.0
} else {
return operation(nums)
}
}
func addPoints(point_1 p1:(x:Int, y:Int), point_2 p2:(x:Int, y:Int)) -> (x:Int, y:Int) {
let xSum:Int = p1.x + p2.x
let ySum:Int = p1.y + p2.y
return (xSum, ySum)
}
func addPoints(point_1 p1:(x:Double, y:Double), point_2 p2:(x:Double, y:Double)) -> (x:Double, y:Double) {
let xSum:Double = p1.x + p2.x
let ySum:Double = p1.y + p2.y
return (xSum, ySum)
}
func subtractPoints(point_1 p1:(x:Int, y:Int), point_2 p2:(x:Int, y:Int)) -> (x:Int, y:Int) {
let xSum:Int = p1.x - p2.x
let ySum:Int = p1.y - p2.y
return (xSum, ySum)
}
func subtractPoints(point_1 p1:(x:Double, y:Double), point_2 p2:(x:Double, y:Double)) -> (x:Double, y:Double) {
let xSum:Double = p1.x - p2.x
let ySum:Double = p1.y - p2.y
return (xSum, ySum)
}
func addPoints(point_1 p1:[String: Int], point_2 p2:[String: Int]) -> [String: Int]{
if (p1["x"] != nil && p1["y"] != nil &&
p2["x"] != nil && p2["y"] != nil) {
let xSum: Int = p1["x"]! + p2["x"]!
let ySum: Int = p1["y"]! + p2["y"]!
return ["x": xSum, "y": ySum]
} else {
print("Error")
return ["Error": -1]
}
}
func subtractPoints(point_1 p1:[String: Int], point_2 p2:[String: Int]) -> [String: Int]{
if (p1["x"] != nil && p1["y"] != nil &&
p2["x"] != nil && p2["y"] != nil) {
let xSum: Int = p1["x"]! - p2["x"]!
let ySum: Int = p1["y"]! - p2["y"]!
return ["x": xSum, "y": ySum]
} else {
print("Error")
return ["Error": -1]
}
}
|
//
// CoreDataUtilities.swift
// CameraDemo_fhu
//
// Created by Hufang on 2019/6/24.
// Copyright © 2019 Fhu. All rights reserved.
//
import Foundation
import UIKit
import CoreData
class CoreDataHelper {
public class func saveImageToDB(image: UIImage, imageName: String, shootDate: String) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
print(#function + " failed to get appDelegate.")
return
}
let context = appDelegate.persistentContainer.viewContext
//Insert data into Entity
let entity = NSEntityDescription.insertNewObject(forEntityName: "Photo", into: context)
// Save values getting from database
entity.setValue(imageName, forKey: "title")
entity.setValue(shootDate, forKey: "shootDate")
entity.setValue(image.pngData(), forKey: "image")
do{
try context.save()
print("Image saved successfully.")
}
catch{
print("Failed in saving the image.")
}
}
public class func retrieveImageFromDB() -> [NSManagedObject?] {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
print(#function + " failed to get appDelegate.")
return []
}
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Photo")
request.returnsObjectsAsFaults = false;
do {
let results = try context.fetch(request)
if results.count > 0 {
guard let result = results as? [NSManagedObject] else {
print(#function + " failed to get results when retrieve from database.")
return []
}
return result
}
}
catch {
print(#function + " Error occurred when retrieve from database.")
}
return []
}
}
|
//
// BlockCell.swift
// BlockPulse
//
// Created by 洪鑫 on 2018/12/11.
// Copyright © 2018 Xin Hong. All rights reserved.
//
import UIKit
enum BlockCellStyle {
case block
case tempTransactions
}
class BlockCell: UICollectionViewCell {
@IBOutlet weak var indexLabel: UILabel!
@IBOutlet weak var blockView: UIView!
@IBOutlet weak var connector: UIView!
@IBOutlet weak var contentLabel: UILabel!
var style: BlockCellStyle = .block {
didSet {
update()
}
}
// MARK: - Life cycle
override func awakeFromNib() {
super.awakeFromNib()
setupUI()
}
// MARK: - Helpers
fileprivate func setupUI() {
blockView.layer.masksToBounds = true
blockView.layer.cornerRadius = 3
blockView.layer.borderWidth = 1.5
}
fileprivate func update() {
switch style {
case .block:
connector.isHidden = false
blockView.backgroundColor = .clear
blockView.layer.borderColor = UIColor.black.cgColor
case .tempTransactions:
connector.isHidden = true
blockView.backgroundColor = .white
blockView.layer.borderColor = UIColor.clear.cgColor
}
}
}
|
//
// Section.swift
// Stock
//
// Created by Abigail Ng on 10/23/19.
// Copyright © 2019 Abigail Ng. All rights reserved.
//
import Foundation
class Section: Equatable {
var name: String
var items: [Item]
var description: String
init(name: String, description: String) {
self.name = name
self.items = []
self.description = description
}
init() {
self.name = "Unititled section"
self.items = []
self.description = ""
}
func addItem(item: Item) {
self.items.append(item)
}
static func ==(lhs:Section, rhs:Section) -> Bool {
return lhs.name == rhs.name
}
}
|
//
// FriendCell.swift
// SocialApp
//
// Created by Иван Казанцев on 28.03.2021.
//
import UIKit
import Kingfisher
class FriendCell: UITableViewCell {
public let avatar = UserAvatarImageView()
public let name = UILabel()
private let backShadow = UserAvatarShadowView()
private let height: CGFloat = 90
private let insetBackShadow: CGFloat = 10
private let insetLabel: CGFloat = 15
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = .clear
self.selectionStyle = .none
setupSubviews()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupSubviews()
}
private func setupSubviews() {
addSubview(backShadow)
backShadow.addSubview(avatar)
addSubview(name)
}
override func layoutSubviews() {
super.layoutSubviews()
setupBackShadow()
setupAvatar()
setupName()
}
private func setupBackShadow() {
let size = CGSize (width: height, height: height)
let origin = CGPoint (x: (insetBackShadow), y: (bounds.height - height)/2)
backShadow.frame = CGRect (origin: origin, size: size)
}
private func setupAvatar() {
avatar.frame = backShadow.bounds
avatar.contentMode = .scaleAspectFit
}
private func setupName() {
let size = getLabelSize(text: name.text ?? "", font: name.font)
let origin = CGPoint(x: (backShadow.bounds.width + insetBackShadow + insetLabel), y: (bounds.height - size.height)/2)
name.frame = CGRect(origin: origin, size: size)
}
private func getLabelSize(text: String, font: UIFont) -> CGSize {
let maxWidth = contentView.bounds.width - backShadow.bounds.width - insetBackShadow - (insetLabel*2)
let textblock = CGSize(width: maxWidth, height: .greatestFiniteMagnitude)
let rect = text.boundingRect(with: textblock, options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font : font], context: nil)
let width = rect.width.rounded(.up)
let height = rect.height.rounded(.up)
return CGSize(width: width, height: height)
}
public func configureGroup(with group: Group?) {
guard let group = group else {return}
name.text = group.name
avatar.kf.setImage(with: URL(string: group.avatar))
}
public func configureUser(with user: User?){
guard let user = user else {return}
name.text = user.firstName + " " + user.lastName
avatar.kf.setImage(with: URL(string: user.avatar))
}
}
|
//
// PreviewViewController.swift
// photoSweetMom
//
// Created by kantapong on 19/1/2563 BE.
// Copyright © 2563 kantapong. All rights reserved.
//
import UIKit
class PreviewViewController: UIViewController {
var image: UIImage!
let previewImage: UIImageView = {
let image = UIImageView()
//image.image = UIImage(named: "")
image.contentMode = .scaleAspectFill
image.layer.masksToBounds = true
return image
}()
lazy var popUpWindow: PopUpWindow = {
let view = PopUpWindow()
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 8
view.delegate = self
return view
}()
let visualEffectView: UIVisualEffectView = {
let blurEffect = UIBlurEffect(style: .dark)
let view = UIVisualEffectView(effect: blurEffect)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
previewImage.image = image
view.addSubview(previewImage)
view.addSubview(visualEffectView)
previewImage.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
visualEffectView.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
view.addSubview(popUpWindow)
popUpWindow.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -40).isActive = true
popUpWindow.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
popUpWindow.heightAnchor.constraint(equalToConstant: view.frame.width - 64).isActive = true
popUpWindow.widthAnchor.constraint(equalToConstant: view.frame.width - 64).isActive = true
popUpWindow.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
popUpWindow.alpha = 0
UIView.animate(withDuration: 0.5) {
self.visualEffectView.alpha = 1
self.popUpWindow.alpha = 1
self.popUpWindow.transform = CGAffineTransform.identity
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
extension PreviewViewController: PopUpDelegate {
func handleDismissal() {
UIView.animate(withDuration: 0.5, animations: {
self.visualEffectView.alpha = 0
self.popUpWindow.alpha = 0
self.popUpWindow.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
}) { (_) in
self.popUpWindow.removeFromSuperview()
print("Did remove pop up window..")
}
}
}
|
//
// LoginViewController.swift
// SimplySiamApplication
//
// Created by student on 1/31/18.
// Copyright © 2018 student. All rights reserved.
//
import UIKit
import Firebase
import GoogleSignIn
class LoginViewController: UIViewController,UITextFieldDelegate,GIDSignInUIDelegate {
@IBOutlet weak var username: UITextField!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var loginImage: UIImageView!
@IBAction func ForgotPassword(_ sender: Any) {
print("forgot password")
let alert = UIAlertController(title: "Simply Siam Password Recovery", message: "Mail will be sent to \(self.username.text!) with steps to recover password?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { action in
if databaseManager.resetPassword(username: self.username.text!){
let alertController = UIAlertController(title: "Simply Siam", message:
"Reset password mail sent successfully..!!!", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
self.present(alertController, animated: true, completion: nil)
}else{
let alertController = UIAlertController(title: "Simply Siam", message:
"Reset password mail sent successfully..!!!", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}))
alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
@IBAction func LoginUserBtn(_ sender: Any) {
var status:Bool = databaseManager.loginUser(username: username.text!, password: password.text!)
if status == true && isUserLoggedIn == true{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let menuItemTabbarVC = storyboard.instantiateViewController(withIdentifier: "menuItemTabbarVC") as! UITabBarController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = menuItemTabbarVC
} else {
let alertController = UIAlertController(title: "Simply Siam", message:
"User Login Failed..!!!", preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}
@IBAction func ContinueAsGuest(_ sender: Any) {
print("guest")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let menuItemTabbarVC = storyboard.instantiateViewController(withIdentifier: "menuItemTabbarVC") as! UITabBarController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = menuItemTabbarVC
}
override func viewDidLoad() {
super.viewDidLoad()
self.username.delegate = self
self.password.delegate = self
setupGoogleButtons()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
fileprivate func setupGoogleButtons() {
//add google sign in button
let googleButton = GIDSignInButton()
googleButton.frame = CGRect(x: 16, y: 500, width: view.frame.width - 32, height: 50)
view.addSubview(googleButton)
GIDSignIn.sharedInstance().uiDelegate = self
}
@objc func handleCustomGoogleSign() {
GIDSignIn.sharedInstance().signIn()
}
/*
// 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.
}
*/
}
|
//
// Grid.swift
// Lecture06
//
// Created by Van Simmons on 7/16/18.
// Copyright © 2018 ComputeCycles, LLC. All rights reserved.
//
import Foundation
let EngineNoticationName = Notification.Name(rawValue: "EngineUpdate")
public typealias Position = (row: Int, col: Int)
public typealias PositionSequence = [Position]
// Implement the wrap around rules
public func normalize(position: Position, to modulus: Position) -> Position {
let modRows = modulus.row, modCols = modulus.col
return Position(
row: ((position.row % modRows) + modRows) % modRows,
col: ((position.col % modCols) + modCols) % modCols
)
}
// Provide a sequence of all positions in a range
public func positionSequence (from: Position, to: Position) -> PositionSequence {
return (from.row ..< to.row)
.map { row in zip( [Int](repeating: row, count: to.col - from.col), from.col ..< to.col ) }
.flatMap { $0 }
}
public enum CellState: String, CustomStringConvertible {
public var description: String {
switch self {
default:
return self.rawValue
}
}
case alive = "alive"
case empty = "empty"
case born = "born"
case died = "died"
public var isAlive: Bool {
switch self {
case .alive, .born: return true
default: return false
}
}
}
public struct Cell {
var position = Position(row:0, col:0)
var state = CellState.empty
}
public struct Grid {
private var _cells: [[Cell]]
fileprivate var modulus: Position { return Position(_cells.count, _cells[0].count) }
// Get and Set cell states by position
public subscript (pos: Position) -> CellState {
get { let pos = normalize(position: pos, to: modulus); return _cells[pos.row][pos.col].state }
set { let pos = normalize(position: pos, to: modulus); _cells[pos.row][pos.col].state = newValue }
}
// Allow access to the sequence of positions
public let positions: PositionSequence
// Initialize _cells and positions
public init(_ rows: Int, _ cols: Int, cellInitializer: (Position) -> CellState = { (_) in .empty } ) {
_cells = [[Cell]]( repeatElement( [Cell](repeatElement(Cell(), count: cols)), count: rows) )
positions = positionSequence(from: Position(0,0), to: Position(rows, cols))
positions.forEach { _cells[$0.row][$0.col].position = $0; self[$0] = cellInitializer($0) }
}
private static let offsets: [Position] = [
(row: -1, col: -1), (row: -1, col: 0), (row: -1, col: 1),
(row: 0, col: -1), (row: 0, col: 1),
(row: 1, col: -1), (row: 1, col: 0), (row: 1, col: 1)
]
private func neighbors(of position: Position) -> [CellState] {
return Grid.offsets.map {
let neighbor = normalize(position: Position(
row: (position.row + $0.row),
col: (position.col + $0.col)
), to: modulus)
return self[neighbor]
}
}
private func nextState(of position: Position) -> CellState {
switch neighbors(of: position).filter({ $0.isAlive }).count {
case 2 where self[position].isAlive,
3: return self[position].isAlive ? .alive : .born
default: return self[position].isAlive ? .died : .empty
}
}
// Generate the next state of the grid
public func next() -> Grid {
var nextGrid = Grid(modulus.row, modulus.col)
positions.forEach { nextGrid[$0] = self.nextState(of: $0) }
return nextGrid
}
}
public extension Grid {
public var description: String {
return positions
.map { (self[$0].isAlive ? "*" : " ") + ($0.1 == self.modulus.col - 1 ? "\n" : "") }
.joined()
}
public var living: [Position] { return positions.filter { return self[$0].isAlive } }
public var dead : [Position] { return positions.filter { return !self[$0].isAlive } }
public var alive : [Position] { return positions.filter { return self[$0] == .alive } }
public var born : [Position] { return positions.filter { return self[$0] == .born } }
public var died : [Position] { return positions.filter { return self[$0] == .died } }
public var empty : [Position] { return positions.filter { return self[$0] == .empty } }
}
extension Grid: Sequence {
public struct SimpleGridIterator: IteratorProtocol {
private var grid: Grid
public init(grid: Grid) {
self.grid = grid
}
public mutating func next() -> Grid? {
grid = grid.next()
return grid
}
}
public struct HistoricGridIterator: IteratorProtocol {
private class GridHistory: Equatable {
let positions: [Position]
let previous: GridHistory?
static func == (lhs: GridHistory, rhs: GridHistory) -> Bool {
return lhs.positions.elementsEqual(rhs.positions, by: ==)
}
init(_ positions: [Position], _ previous: GridHistory? = nil) {
self.positions = positions
self.previous = previous
}
var hasCycle: Bool {
var prev = previous
while prev != nil {
if self == prev { return true }
prev = prev!.previous
}
return false
}
}
private var grid: Grid
private var history: GridHistory!
init(grid: Grid) {
self.grid = grid
self.history = GridHistory(grid.living)
}
public mutating func next() -> Grid? {
if history.hasCycle { return nil }
let newGrid = grid.next()
history = GridHistory(newGrid.living, history)
grid = newGrid
return grid
}
}
public func makeIterator() -> HistoricGridIterator {
return HistoricGridIterator(grid: self)
}
}
func gliderInitializer(row: Int, col: Int) -> CellState {
switch (row, col) {
case (0, 1), (1, 2), (2, 0), (2, 1), (2, 2): return .alive
default: return .empty
}
}
typealias UpdateClosure = (Engine) -> Void
protocol EngineDelegate {
func engine(didUpdate: Engine) -> Void
}
class Engine {
static var sharedInstance: Engine = Engine()
var size: Int = 10
var grid: Grid = Grid(10,10)
private var timer: Timer?
var updateClosure: UpdateClosure = { _ in }
var delegate: EngineDelegate?
var interval: Double = 0 {
didSet {
timer?.invalidate()
timer = nil
if interval > 0 {
timer = Timer.scheduledTimer(
withTimeInterval: interval,
repeats: true
) { (t: Timer) -> Void in
self.grid = self.grid.next()
self.updateClosure(self)
// self.delegate?.engine(didUpdate: self)
// let nc = NotificationCenter.default
// let info = ["engine": self]
// nc.post(name: EngineNoticationName, object: nil, userInfo:info)
}
}
}
}
}
|
//
// RecommendAdModel.swift
// Inke
//
// Created by huangjinbiao on 2017/10/23.
// Copyright © 2017年 DevHuangjb. All rights reserved.
//
import UIKit
import SwiftyJSON
import IGListKit
class RecommendAdModel: NSObject {
var style: Int = 0
var ticker: [JSON]?
init(json: JSON) {
style = json["cover"]["style"].intValue
ticker = json["data"]["ticker"].arrayValue
}
}
extension RecommendAdModel: ListDiffable {
func diffIdentifier() -> NSObjectProtocol {
return self
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
return self === object ? true : self.isEqual(object)
}
}
|
//
// Strings.swift
// iOS-FolderStructure
//
// Created by Tharindu Perera on 2/22/19.
// Copyright © 2019 Tharindu Perera. All rights reserved.
//
import Foundation
struct Strings {
struct Alerts {
static let waiting = "Please wait.."
static let defaultFailedMessage = "Failed. Please try again"
}
struct Messages {
struct Success {
static let common = "Success."
static let dataDownload = "Data fetching succeed."
}
struct Error {
static let common = "Something went wrong!"
}
}
}
|
//
// Gryphon
// Created by rinov on 9/17/16.
// Copyright © 2016 rinov. All rights reserved.
//
import Foundation
public final class Task<Response,Error> {
// Success handler type.
public typealias Fulfill = Response -> Void
// Failure handler type.
public typealias Reject = Error -> Void
// Cancel handler type.
public typealias Cancel = Void -> Void
// Initializer must declare both fullfill and reject cases.
public typealias Initializer = (_: Fulfill, _: Reject) -> Void
// The default value of maximum retry count.
private let maximumRetryCount: Int = 10
// The default value of maximum interval time(ms).
private let maximumIntervalTime: Double = 10000.0
// Fullfil handler.
private var fulfill: Fulfill?
// Reject handler.
private var reject: Reject?
// Cancel handler.
private var cancel: Cancel?
// Initializer handler.
private var initializer: Initializer?
// Retry count
private lazy var retry: Int = 0
// Interval time of request
private lazy var interval: Double = 0.0
// In case of succeed, It is able to process the result of response.
public func success(response handler: Fulfill) -> Self {
fulfill = handler
return self
}
// In case of failure, It will be able to process the error by reason.
public func failure(error handler: Reject) -> Self {
reject = handler
return self
}
// If the request was rejected by your `validate`, It will be able to perform to your cancel at last.
public func cancel(canceler handler: Cancel) -> Self {
cancel = handler
return self
}
// The maximum number of retry.
public func retry(max times: Int) -> Self {
retry = times
return self
}
// The time of interval for API request.
public func interval(milliseconds ms: Double) -> Self {
interval = ms
return self
}
// Initializing by closure of `initializar`.
public init(initClosuer: Initializer ) {
initializer = initClosuer
executeRequest()
}
// MARK: Private Methods
private func executeRequest() {
initializer?({ response in
self.fulfill?(response)
}){ error in
self.reject?(error)
self.doRetry()
}
}
// If `retry` count is one or more.
private func doRetry() {
if retry > maximumRetryCount {
fatalError("The retry count is too many.\nPlease check the retry count again.")
}
if retry > 0 {
retry -= 1
if interval > maximumIntervalTime {
fatalError("The interval time is too much.\nPlease check the interval time again.")
}
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64( interval / 1000.0 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
self.executeRequest()
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.