text stringlengths 8 1.32M |
|---|
//
// GoodNewsUIConfiguration.swift
// GoodNews
//
// Created by Muhammad Osama Naeem on 3/15/20.
// Copyright © 2020 Muhammad Osama Naeem. All rights reserved.
//
import UIKit
struct GNUIConfiguration {
static let mainForegroundColor = UIColor(red:0.92, green:0.25, blue:0.20, alpha:1.00)//UIColor(red:0.16, green:0.76, blue:0.69, alpha:1.0)
static let secondaryForegroundColor = UIColor(red:0.16, green:0.62, blue:0.76, alpha:1.0)
static let selectedColor = UIColor(red:0.90, green:0.38, blue:0.56, alpha:1.0)
static let textColor = UIColor(red:1.00, green:0.18, blue:0.33, alpha:1.00)
}
|
//
// CommentView.swift
// WhatDidILike
//
// Created by Christopher G Prince on 9/3/17.
// Copyright © 2017 Spastic Muffin, LLC. All rights reserved.
//
import UIKit
import SMCoreLib
class CommentView: UIView, XibBasics {
typealias ViewType = CommentView
@IBOutlet weak var bottom: NSLayoutConstraint!
@IBOutlet weak var commentImagesContainer: UIView!
@IBOutlet weak var ratingContainer: UIView!
@IBOutlet weak var comment: TextView!
private let rating = RatingView.create()!
private let images = ImagesView.create()!
@IBOutlet weak var removeButton: UIButton!
@IBOutlet weak var separator: UIView!
var removeComment:(()->())?
override func awakeFromNib() {
super.awakeFromNib()
Layout.format(textBox: comment)
comment.autocapitalizationType = .sentences
rating.frameWidth = ratingContainer.frameWidth
ratingContainer.addSubview(rating)
images.frameWidth = commentImagesContainer.frameWidth
commentImagesContainer.addSubview(images)
images.lowerLeftLabel.text = "Comment pictures"
Layout.format(comment: self)
removeButton.tintColor = .trash
}
func setup(withComment comment: Comment, andParentVC vc: UIViewController) {
self.comment.text = comment.comment
rating.setup(withRating: comment.rating!)
images.setup(withParentVC:vc, andImagesObj: comment)
removeButton.isHidden = Parameters.commentStyle == .single
// Assumes images are positioned at the bottom of the CommentView.
if Parameters.commentStyle == .single {
// This removes extra area needed for the removeButton and also makes the corner rounding look better.
frameHeight -= bottom.constant
bottom.constant = 0
}
}
@IBAction func removeCommentAction(_ sender: Any) {
removeComment?()
}
deinit {
Log.msg("deinit")
}
}
|
//
// GameType.swift
// AahToZzz
//
// Created by David Fierstein on 1/24/17.
// Copyright © 2017 David Fierstein. All rights reserved.
//
import Foundation
@objc enum GameType: Int {
case twoLetterWords = 0
case threeLetterWords = 1
case jqxz = 2
case sevenLetterWords = 3
case eightLetterWords = 4
case nineLetterWords = 5
}
// TODO: link this enum/struct to Game managed object
// move dictionaryName property from GameData to Game
// TODO:-- make this a struct, so can have stored properties
//TODO:-- make the enum map to integer for persisting in core data
//TODO:-- add other properties for each type
// lengthOfWords
// deviceOrientation
// which dictionary(s) to use (So dictionary property should be an array of Strings, corresponding to the file name for the dictionary)
// unique rules for the game, such as mix of letters to use
// Question: if you create a struct that goes with the game, does it need to be created just once? each time game is loaded??
|
//
// StudentProfileViewController.swift
// MagotakuApp
//
// Created by 宮本一成 on 2020/03/15.
// Copyright © 2020 ISSEY MIYAMOTO. All rights reserved.
//
import UIKit
import Firebase
import FirebaseAuth
class StudentProfileViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
let cellText = ["プロフィール", "過去の業務と報酬", "レビュー", "設定", "ログアウト"]
let detailText = ["プロフィールを閲覧・編集できます", "過去の業務と報酬について閲覧できます", "レビューの閲覧・投稿できます", "各種設定を行えます", "ログアウトできます"]
let cellicon = ["person", "dollarsign.circle", "square.and.pencil", "gear", "lock"]
//プロフィール写真用のUIImageView
let profileImage = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "マイアカウント"
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundColor = UIColor(red: 225/255, green: 225/255, blue: 225/255, alpha: 1)
navigationController?.navigationBar.titleTextAttributes = [
// 文字の色
.foregroundColor: UIColor.white
]
if let navigationBar = self.navigationController?.navigationBar {
let gradient = CAGradientLayer()
var bounds = navigationBar.bounds
bounds.size.height += self.additionalSafeAreaInsets.top
gradient.frame = bounds
gradient.colors = [UIColor(red: 41/255, green: 162/255, blue: 226/255, alpha: 1).cgColor, UIColor(red: 65/255, green: 132/255, blue: 190/255, alpha: 1).cgColor]
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 1, y: 0)
if let image = getImageFrom(gradientLayer: gradient) {
navigationBar.setBackgroundImage(image, for: UIBarMetrics.default)
}
}
}
func getImageFrom(gradientLayer:CAGradientLayer) -> UIImage? {
var gradientImage:UIImage?
UIGraphicsBeginImageContext(gradientLayer.frame.size)
if let context = UIGraphicsGetCurrentContext() {
gradientLayer.render(in: context)
gradientImage = UIGraphicsGetImageFromCurrentImageContext()?.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .stretch)
}
UIGraphicsEndImageContext()
return gradientImage
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellText.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//デフォルトのtableViewCellを使用
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") ?? UITableViewCell(style: .subtitle, reuseIdentifier: "cell")
//内容
cell.textLabel!.text = cellText[indexPath.row]
//左端のイメージアイコン設置
cell.imageView!.image = UIImage(systemName: cellicon[indexPath.row])
//内容詳細
cell.detailTextLabel!.text = detailText[indexPath.row]
cell.detailTextLabel!.tintColor = UIColor.darkGray
//セルの右端にタッチ利用可能の補助イメージ
let touchImage = UIImageView()
touchImage.image = UIImage(systemName: "chevron.right")
touchImage.frame = CGRect(x: UIScreen.main.bounds.width - 32, y: 26, width: 8, height: 12)
cell.contentView.addSubview(touchImage)
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//プロフィール写真用のUIImageView
// let profileImage = UIImageView()
//もし学生側に情報としてimageNameが入っていたらそれを取得して表示させる
if let imageName: String? = studentProfile.imageName,
let ref = StudentUserCollection.shared.getImageRef(imageName: imageName!){
profileImage.sd_setImage(with: ref)
}else{
profileImage.image = UIImage(systemName: "person.fill")
}
profileImage.frame = CGRect(x: (UIScreen.main.bounds.width - 60) / 2, y: 32, width: 60, height: 60)
profileImage.layer.cornerRadius = 30.0
//サービス利用者氏名を表示
let nameLabel = UILabel()
nameLabel.frame = CGRect(x: 32, y: 108, width: UIScreen.main.bounds.width - 64, height: 22)
nameLabel.textAlignment = .center
nameLabel.font = UIFont.boldSystemFont(ofSize: 16)
nameLabel.text = "\(studentProfile.name) さん"
//上記2個をセットするUIViewを定義
let headerView = UIView()
headerView.backgroundColor = UIColor(red: 225/255, green: 225/255, blue: 225/255, alpha: 1)
headerView.addSubview(profileImage)
headerView.addSubview(nameLabel)
return headerView
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.row {
case 0:
//プロフィールを押した際の挙動
let vc = EditProfileViewController()
vc.imageView.image = profileImage.image
let backButtonItem = UIBarButtonItem(title: "戻る", style: .plain, target: nil, action: nil)
navigationItem.backBarButtonItem = backButtonItem
navigationController?.pushViewController(vc, animated: true)
case 1:
return
case 2:
return
case 3:
return
default:
do {
try Auth.auth().signOut()
// 強制的に現在の表示している vc を変更する
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateInitialViewController()
let sceneDelegate = view.window?.windowScene?.delegate as! SceneDelegate
sceneDelegate.window?.rootViewController = vc
} catch {
print("error:",error.localizedDescription)
}
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 160
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 64
}
}
|
//
// ViewModelProtocol.swift
// MVVMFramework
//
// Created by lisilong on 2018/12/5.
// Copyright © 2018 lisilong. All rights reserved.
//
// OneTableViewCell
protocol OneTableViewCellViewModelProtocol: ViewModelProtocol {
var title: String { get }
var price: String { get }
var status: Int { get }
}
// TwoTableViewCell
protocol TwoTableViewCellViewModelProtocol: ViewModelProtocol {
var title: String { get }
var content: String { get }
}
// ThreeTableViewCell
protocol ThreeTableViewCellViewModelProtocol: ViewModelProtocol {
var id: String { get }
var title: String { get }
var image: String { get }
}
|
//
// LeftSidePanelViewController.swift
// Hitcher
//
// Created by Kelvin Fok on 11/2/18.
// Copyright © 2018 Kelvin Fok. All rights reserved.
//
import UIKit
import Firebase
class PanelViewController: UIViewController {
var currentUser: User?
let appDelegate = AppDelegate.getAppDelegate()
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var accountTypeLabel: UILabel!
@IBOutlet weak var profileImageView: RoundImageView!
@IBOutlet weak var pickUpModeLabel: UILabel!
@IBOutlet weak var pickUpModeSwitch: UISwitch!
@IBOutlet weak var signUpLoginButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupInitialViews()
observePassengersAndDrivers()
}
func setupInitialViews() {
pickUpModeSwitch.isOn = false
pickUpModeSwitch.isHidden = true
pickUpModeLabel.isHidden = true
if let currentUser = Auth.auth().currentUser {
self.currentUser = currentUser
displayUserIsLoginViews()
} else {
displayUserIsLogoutViews()
}
}
func displayUserIsLogoutViews() {
emailLabel.text = ""
accountTypeLabel.text = ""
profileImageView.isHidden = true
signUpLoginButton.setTitle("Sign Up / Login", for: .normal)
}
func displayUserIsLoginViews() {
emailLabel.text = Auth.auth().currentUser?.email
accountTypeLabel.text = ""
profileImageView.isHidden = false
signUpLoginButton.setTitle("Logout", for: .normal)
}
func observePassengersAndDrivers() {
DataService.instance.REF_DRIVERS.observeSingleEvent(of: .value) { (snapshot) in
if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
for snapshot in snapshots {
if snapshot.key == Auth.auth().currentUser?.uid {
print("is driver")
Session.instance.userType = .DRIVER
self.accountTypeLabel.text = "Driver"
self.pickUpModeSwitch.isHidden = false
let switchStatus = snapshot.childSnapshot(forPath: PathManager.Path.isPickUpModeEnabled.rawValue).value as! Bool
self.pickUpModeSwitch.isOn = switchStatus
self.pickUpModeLabel.isHidden = false
}
}
}
}
DataService.instance.REF_USERS.observeSingleEvent(of: .value) { (snapshot) in
if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
for snapshot in snapshots {
if snapshot.key == Auth.auth().currentUser?.uid {
Session.instance.userType = .PASSENGER
print("is passenger")
self.accountTypeLabel.text = "Passenger"
}
}
}
}
}
@IBAction func handleSignUpLoginButton(_ sender: Any) {
if Auth.auth().currentUser == nil {
let loginViewController = UIStoryboard.getMainStoryboard().instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
self.present(loginViewController, animated: true, completion: nil)
} else {
do {
try Auth.auth().signOut()
displayUserIsLogoutViews()
} catch (let error ) {
print("Sign out error: \(error.localizedDescription)")
}
}
}
@IBAction func handlePickUpModeSwitch(_ sender: Any) {
if pickUpModeSwitch.isOn {
pickUpModeLabel.text = "Pickup Mode Enabled"
appDelegate.containerViewController.toggleLeftPanel()
let dictionary = [PathManager.Path.isPickUpModeEnabled.rawValue : true]
DataService.instance.REF_DRIVERS.child(self.currentUser!.uid).updateChildValues(dictionary)
} else {
pickUpModeLabel.text = "Pickup Mode Disabled"
appDelegate.containerViewController.toggleLeftPanel()
let dictionary = [PathManager.Path.isPickUpModeEnabled.rawValue : false]
DataService.instance.REF_DRIVERS.child(self.currentUser!.uid).updateChildValues(dictionary)
}
}
}
|
//
// MasterSingleton.swift
// London Mosque
//
// Created by Yunus Amer on 2020-12-15.
//
import Foundation
import AVFoundation
import UIKit
let sharedMasterSingleton = MasterSingleton()
class MasterSingleton {
let preferences = UserDefaults.standard
var player: AVAudioPlayer?
let notifications = Notifications()
var todaysDate = Date()
var volumeChoice = 0
var vibrateChoice = 0
var customTimerOn = false
var customTimerLength = 5
var athanChoice = 0
var prayerNotifierOn = [true, true, true, true, true,
true, true, true, true, true,
true, true, true, true, true]
let color_darkBlue = UIColor.init(red: 43/255, green: 69/255, blue: 126/255, alpha: 1)
let color_lightBlue = UIColor.init(red: 204/255, green: 214/255, blue: 232/255, alpha: 1)
let color_darkOrange = UIColor.init(red: 243/255, green: 177/255, blue: 46/255, alpha: 1)
let color_lightOrange = UIColor.init(red: 245/255, green: 238/255, blue: 223/255, alpha: 1)
func getColor(color: String) -> UIColor{
if (color == "darkBlue"){
return color_darkBlue
} else if (color == "lightBlue"){
return color_lightBlue
} else if (color == "darkOrange"){
return color_darkOrange
} else if (color == "lightOrange"){
return color_lightOrange
}
return UIColor.red
}
let prayerAccessor = PrayerAccessor()
var prayerVals = [String]()
// Initialization
init() {
volumeChoice = getUserDefault(key: "volumeChoice") as? Int ?? 0
vibrateChoice = getUserDefault(key: "vibrateChoice") as? Int ?? 0
customTimerOn = getUserDefault(key: "customTimerOn") as? Bool ?? false
customTimerLength = getUserDefault(key: "customTimerLength") as? Int ?? 5
athanChoice = getUserDefault(key: "athanChoice") as? Int ?? 0
for x in 0...14{
let key = "prayerNotifier"+String(x)
prayerNotifierOn[x] = getUserDefault(key: key) as? Bool ?? true
}
prayerVals = prayerAccessor.getNextPrayer(date: Date())
nextPrayerName = prayerVals[0]
nextPrayerCall = prayerVals[1]
}
func scheduleNotifications(){
notifications.scheduleNotifications()
}
func getUserDefault(key: String) -> AnyObject{
return preferences.object(forKey: key) as AnyObject
}
func setUserDefault(key: String, val: Bool){
preferences.set(val, forKey: key)
}
func setUserDefault(key: String, val: Int){
preferences.set(val, forKey: key)
}
func getPrayerAccessor() -> PrayerAccessor{
return prayerAccessor
}
func getTodaysDate() -> Date{
return todaysDate
}
func getVolumeChoice() -> Int{
return volumeChoice
}
func getVibrateChoice() -> Int{
return vibrateChoice
}
func isCustomTimerOn() -> Bool{
return customTimerOn
}
func getCustomTimerLength() -> Int{
return customTimerLength
}
func getAthanChoice() -> Int{
return athanChoice
}
func isPrayerNotifierIsOn(tag: Int) -> Bool{
return prayerNotifierOn[tag-1]
}
func setVolumeChoice(val: Int){
volumeChoice = val
setUserDefault(key: "volumeChoice", val: val)
}
func setVibrateChoice(val: Int){
vibrateChoice = val
setUserDefault(key: "vibrateChoice", val: val)
vibrate()
}
func setCustomTimerOn(val: Bool){
customTimerOn = val
setUserDefault(key: "customTimerOn", val: val)
scheduleNotifications()
}
func setCustomTimerLength(val: Int){
customTimerLength = val
setUserDefault(key: "customTimerLength", val: val)
scheduleNotifications()
}
func setAthanChoice(val: Int){
athanChoice = val
setUserDefault(key: "athanChoice", val: val)
}
func setPrayerNotifierIsOn(val: Bool, tag: Int){
prayerNotifierOn[tag-1] = val
let key = "prayerNotifier"+String(tag-1)
setUserDefault(key: key, val: val)
}
var nextPrayerName = ""
var nextPrayerCall = ""
func setNextPrayerName(name: String){
nextPrayerName = name
}
func setNextPrayerCall(call: String){
nextPrayerCall = call
}
func notifyPrayer(){
var tag: Int
switch(nextPrayerName){
case "Fajr":
tag = 1
break
case "Dhuhr":
tag = 4
break
case "Asr":
tag = 7
break
case "Maghrib":
tag = 10
break
case "Isha":
tag = 13
break
default:
tag = -9
break
}
if(nextPrayerCall == "Athan"){
if(isPrayerNotifierIsOn(tag: tag)){
vibrate()
}
tag += 1
if(isPrayerNotifierIsOn(tag: tag)){
playSound()
}
} else if(nextPrayerCall == "Iqama"){
tag += 2
if(isPrayerNotifierIsOn(tag: tag)){
vibrate()
}
}
}
var vibrateCounter = 0
var vibeTimer = Timer()
func vibrate(){
vibrateCounter = vibrateChoice-1
AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate), nil)
vibeTimer = Timer.scheduledTimer(timeInterval: 0.65, target: self, selector: #selector(vibrateTimer), userInfo: nil, repeats: true)
}
@objc func vibrateTimer(){
if (vibrateCounter < 0){
vibeTimer.invalidate()
} else { AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate), nil)
}
vibrateCounter -= 1
}
func playSound() {
let soundName = "athan_" + String(athanChoice)
guard let url = Bundle.main.url(forResource: soundName, withExtension: "mp3") else { return }
do {
if #available(iOS 10.0, *) {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: .mixWithOthers)
} else {
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
}
try AVAudioSession.sharedInstance().setActive(true)
/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
func stopSound(){
player?.stop()
}
}
|
//
// AddLocationViewController.swift
// OnTheMap
//
// Created by Sushma Adiga on 27/06/21.
//
import Foundation
import UIKit
import MapKit
class AddLocationViewController: UIViewController, MKMapViewDelegate {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var placemark: CLPlacemark?
var mapString: String?
var mediaURL: String?
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var finishAddLocation: UIButton!
var firstName: String = ""
var lastName: String = ""
var segueIdentifier: String = ""
override func viewDidLoad() {
super.viewDidLoad()
mapView.delegate = self
self.drawMap()
self.getPublicUserInformation()
}
@IBAction func finishAddLocation(_ sender: Any) {
self.createStudentLocation()
navigationController?.popToRootViewController(animated: true)
}
func createStudentLocation() {
OTMClient.createStudentLocation(firstName: firstName, lastName: lastName, mapString: appDelegate.mapString ?? "", mediaURL: appDelegate.mediaURL ?? "", latitude: (appDelegate.placemark?.location!.coordinate.latitude)!, longitude: (appDelegate.placemark?.location!.coordinate.longitude)!, completion: self.handleCreateStudentLocation(success:error:))
}
func handleCreateStudentLocation(success: Bool, error: Error?) {
if (success) {
view.window?.rootViewController?.dismiss(animated: true, completion: nil)
}
else {
showFailure(failureType: "Can not create Student Location", message: error?.localizedDescription ?? "")
}
}
func getPublicUserInformation() {
OTMClient.getPublicUserData(completion: self.handleGetPublicUserData(response:error:))
}
func handleGetPublicUserData(response: User?, error: Error?) {
if (response != nil) {
firstName = response!.firstName
lastName = response!.lastName
}
else {
showFailure(failureType: "Unable to get Public User Data", message: error?.localizedDescription ?? "")
}
}
func drawMap() {
var annotations = [MKPointAnnotation]()
let annotation = MKPointAnnotation()
if( appDelegate.placemark?.location?.coordinate != nil) {
annotation.coordinate = (appDelegate.placemark?.location?.coordinate)!
}
annotation.title = appDelegate.mapString
annotations.append(annotation)
self.mapView.addAnnotations(annotations)
self.mapView.setRegion(MKCoordinateRegion(center:annotation.coordinate, latitudinalMeters: 0.01, longitudinalMeters: 0.01), animated:true)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let reuseId = "pin"
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
pinView!.canShowCallout = true
pinView!.pinTintColor = .red
pinView!.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
else {
pinView!.annotation = annotation
}
return pinView
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if control == view.rightCalloutAccessoryView {
let app = UIApplication.shared
if let toOpen = view.annotation?.subtitle! {
app.open(URL(string: toOpen)!)
}}
}
}
|
//
// AutoLaunchHelper.swift
// Statbar
//
// Copyright © 2017 bsdelf. All rights reserved.
// Copyright © 2016 郭佳哲. All rights reserved.
//
import Foundation
import ServiceManagement
open class AutoLaunchHelper {
static func isLoginStartEnabled() -> Bool {
return UserDefaults.standard.string(forKey: "appLoginStart") == "true"
}
static func toggleLoginStart() {
let identifier = "com.bsdelf.StatbarHelper" // Bundle.main.bundleIdentifier!
let toggled = !isLoginStartEnabled()
let ok = SMLoginItemSetEnabled(identifier as CFString, toggled)
if (ok) {
UserDefaults.standard.set(String(toggled), forKey: "appLoginStart")
} else {
print("Failed to toggle login start", identifier, toggled);
}
}
}
|
//
// CollectionHolderTableViewCell.swift
// Dikke Ploaten
//
// Created by Victor Vanhove on 04/04/2019.
// Copyright © 2019 bazookas. All rights reserved.
//
import UIKit
class CollectionHolderTableViewCell: UITableViewCell {
@IBOutlet weak var collectionCollectionView: UICollectionView!
var albums: [Album] = []
func updateAlbums(albums: [Album]) {
self.albums = []
self.albums = albums
collectionCollectionView.reloadData()
}
}
extension CollectionHolderTableViewCell: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if albums.isEmpty {
return 0
}
return albums.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "albumCell", for: indexPath) as! AlbumCollectionViewCell
if !albums.isEmpty {
cell.updateUI(forAlbum: albums[indexPath.item])
}
return cell
}
}
extension CollectionHolderTableViewCell: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let itemsPerRow: CGFloat = 4
let hardCodedPadding: CGFloat = 5
let itemWidth = (collectionView.bounds.width / itemsPerRow) - hardCodedPadding
return CGSize(width: itemWidth, height: itemWidth)
}
}
|
import Alamofire
@discardableResult
public func checkStatus(
completionHandler: @escaping (DataResponse<Bool>) -> Void)
-> DataRequest
{
return request("https://kyfw.12306.cn/otn/login/checkUser", method: .post)
.validateJSON()
.response(completionHandler: { (response) in
})
.responseSwiftyJSON(completionHandler: { (response) in
if let flag = response.result.value?["data"]["flag"].bool {
completionHandler(response.replacingSuccess(value: flag))
} else {
completionHandler(response.replacingFailure(type: Bool.self))
}
})
}
@discardableResult
public func prepareForSignIn(
completionHandler: @escaping (DataResponse<Any>) -> Void)
-> DataRequest
{
return request("https://kyfw.12306.cn/otn/login/init", method: .get)
.responseString(completionHandler: { (response) in
guard let scriptURL = response.result.value?.substring(with: "(?<=<script src=\").+?(?=\" type=\"text/javascript\" xml:space=\"preserve\">)") else {
completionHandler(response.replacingFailure(type: Any.self))
return
}
request("https://kyfw.12306.cn\(scriptURL)", method: .get).responseData(completionHandler: { (response) in
completionHandler(response.replacingSuccess(value: 1))
})
})
}
@discardableResult
public func retrieveSignInCaptchaImage(
completionHandler: @escaping (DataResponse<UIImage>) -> Void)
-> DataRequest
{
let random = Double(arc4random()) / Double(RAND_MAX)
let URLString = NSString(format: "https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=login&rand=sjrand&%.18f", random) as String
return request(URLString, method: .get).responseImage(completionHandler: completionHandler)
}
@discardableResult
public func checkSignInCaptcha(
captcha: String,
completionHandler: @escaping (DataResponse<Bool>) -> Void)
-> DataRequest
{
let parameters = [
"randCode": captcha,
"rand": "sjrand"
]
return request("https://kyfw.12306.cn/otn/passcodeNew/checkRandCodeAnsyn", method: .post, parameters: parameters).validateJSON().responseSwiftyJSON(completionHandler: { (response) in
if let result = response.result.value?["data"]["result"].string {
completionHandler(response.replacingSuccess(value: result == "1"))
} else {
completionHandler(response.replacingFailure(type: Bool.self))
}
})
}
@discardableResult
public func signIn(
signInForm: SignInForm,
completionHandler: @escaping (DataResponse<Bool>) -> Void)
-> DataRequest
{
var parameters = [
"loginUserDTO.user_name": signInForm.username ?? "",
"userDTO.password": signInForm.password ?? "",
"randCode": signInForm.captcha ?? ""
]
if let extraParameters = signInForm.extraParameters {
parameters.merge(extraParameters)
}
return request("https://kyfw.12306.cn/otn/login/loginAysnSuggest", method: .post, parameters: parameters)
.validateJSON()
.responseSwiftyJSON(completionHandler: { (response) in
completionHandler(response.replacingSuccess(value: true))
})
}
|
//
// TappableViewSelectableContainerComponent.swift
// TSupportLibrary
//
// Created by Matteo Corradin on 16/05/18.
// Copyright © 2018 Matteo Corradin. All rights reserved.
//
import Foundation
import UIKit
open class TappableViewSelectableContainerComponent: TappableViewContainerComponent {
private var _selected: Int?
public var selectedCallback : ((_ selected: Int) -> Void)?
public var selected: Int? {
get {
return _selected
}
set {
if let newValue = newValue{
if self.tappableViews.count > 0 && newValue <= self.tappableViews.count{
newViewSelectedAction(old: _selected, new: newValue)
}
}
}
}
//on override, please make sure to call super unless you know what you are doing!
open func newViewSelectedAction(old: Int?, new: Int){
_selected = new
if let callback = selectedCallback{
callback(new)
}
}
override open func addTappableView(_ view: TappableViewComponent) {
super.addTappableView(view)
if self.tappableViews.count > 0 && selected == nil {
selected = 0
}
}
}
|
//
// QuizDataRepository.swift
// QuizApp
//
// Created by Marin on 24.05.2021..
//
class QuizDataRepository: QuizRepositoryProtocol {
private let networkDataSource: QuizNetworkSourceProtocol
private let coreDataSource: QuizCoreDataSourceProtocol
init(networkService: NetworkServiceProtocol) {
self.coreDataSource = QuizCoreDataSource()
self.networkDataSource = QuizNetworkDataSource(networkService: networkService, quizCoreDataSource: coreDataSource)
}
func fetchData(filter: FilterSettings) -> [Quiz] {
var quizzes: [Quiz] = []
// if network is connected, fetch quizzes from network (and save in core data)
if(NetworkMonitor.shared.isConnected){
networkDataSource.fetchQuizzesFromNetwork()
}
quizzes = coreDataSource.fetchQuizzesFromCoreData(filter: filter)
return quizzes
}
func fetchRemoteData() {
networkDataSource.fetchQuizzesFromNetwork()
}
func fetchLocalData(filter: FilterSettings) -> [Quiz] {
return coreDataSource.fetchQuizzesFromCoreData(filter: filter)
}
func deleteLocalData(withId id: Int) {
coreDataSource.deleteQuiz(withId: id)
}
}
|
//
// BetTableView.swift
// BetMate
//
// Created by sebastian on 08/11/2019.
// Copyright © 2019 sebastian. All rights reserved.
//
import UIKit
struct cellData{
var oppened = Bool()
var title = String()
var sectionData = [String]()
}
var tableViewData = [cellData]()
class BetTableView: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableViewData = [cellData(oppened: false, title: "randers vs agf", sectionData: ["over 10 gule kort"]),
cellData(oppened: false, title: "liverpool vs manchester united", sectionData: ["begge hold score"]),
cellData(oppened: false, title: "fc barcelona vs real madrid", sectionData: ["mere end 3,5 hjørnespark i første halvleg"]),
cellData(oppened: false, title: "dortmund vs bayern munchen", sectionData: ["der bliver dømt straffe spark"])]
}
override func numberOfSections(in tableView: UITableView) -> Int {
tableViewData.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableViewData[section].oppened == true{
return tableViewData[section].sectionData.count+1
}
else {
return 1
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let dataIndex = indexPath.row-1
if indexPath.row == 0{
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else {return UITableViewCell()}
cell.textLabel?.text = tableViewData[indexPath.section].title
return cell
}
else{
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") else {return UITableViewCell()}
cell.textLabel?.text = tableViewData[indexPath.section].sectionData[dataIndex]
return cell
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if tableViewData[indexPath.section].oppened == true{
tableViewData[indexPath.section].oppened = false
let sections = IndexSet.init(integer: indexPath.section)
tableView.reloadSections(sections, with: .none)
}
else{
tableViewData[indexPath.section].oppened = true
let sections = IndexSet.init(integer: indexPath.section)
tableView.reloadSections(sections, with: .none)
}
}
}
|
//
// MapView.swift
// MeetupRemainder
//
// Created by Vegesna, Vijay V EX1 on 9/18/20.
// Copyright © 2020 Vegesna, Vijay V. All rights reserved.
//
import SwiftUI
import MapKit
struct MapView: UIViewRepresentable {
@Binding var centerCoordinate: CLLocationCoordinate2D
var currentLocation: CLLocationCoordinate2D?
var withAnnotation: MKPointAnnotation?
class Coordinator: NSObject, MKMapViewDelegate {
var parent: MapView
init(_ parent: MapView) {
self.parent = parent
}
func mapViewDidChangeVisibleRegion(_ mapView: MKMapView) {
if !mapView.showsUserLocation {
parent.centerCoordinate = mapView.centerCoordinate
}
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView()
mapView.delegate = context.coordinator
mapView.showsUserLocation = false
return mapView
}
func updateUIView(_ uiView: MKMapView, context: Context) {
if let currentLocation = self.currentLocation {
if let annotation = self.withAnnotation {
uiView.removeAnnotation(annotation)
}
uiView.showsUserLocation = true
let region = MKCoordinateRegion(center: currentLocation, latitudinalMeters: 800, longitudinalMeters: 800)
uiView.setRegion(region, animated: true)
} else if let annotation = self.withAnnotation {
uiView.removeAnnotations(uiView.annotations)
uiView.addAnnotation(annotation)
}
}
}
|
// SignedIntegerExtensionsTests.swift - Copyright 2020 SwifterSwift
@testable import SwifterSwift
import XCTest
final class SignedIntegerExtensionsTests: XCTestCase {
func testAbs() {
XCTAssertEqual((-9).abs, 9)
}
func testIsPositive() {
XCTAssert(1.isPositive)
XCTAssertFalse(0.isPositive)
XCTAssertFalse((-1).isPositive)
}
func testIsNegative() {
XCTAssert((-1).isNegative)
XCTAssertFalse(0.isNegative)
XCTAssertFalse(1.isNegative)
}
func testIsEven() {
XCTAssert(2.isEven)
XCTAssertFalse(3.isEven)
}
func testIsOdd() {
XCTAssert(3.isOdd)
XCTAssertFalse(2.isOdd)
}
func testTimeString() {
XCTAssertEqual((-1).timeString, "0 sec")
XCTAssertEqual(45.timeString, "45 sec")
XCTAssertEqual(120.timeString, "2 min")
XCTAssertEqual(3600.timeString, "1h")
XCTAssertEqual(3660.timeString, "1h 1m")
}
func testGcd() {
XCTAssertEqual(8.gcd(of: 20), 4)
}
func testLcm() {
XCTAssertEqual(4.lcm(of: 3), 12)
}
func testString() {
XCTAssertEqual(2.string, "2")
}
}
|
//
// Note+CoreDataClass.swift
// All Planned
//
// Created by Lam Nguyen on 1/31/21.
//
//
import Foundation
import CoreData
@objc(Note)
public class Note: NSManagedObject {
}
|
//
// ViewController.swift
// Control de Ingreso2
//
// Created by Esteban Choque Villalobos on 9/14/20.
// Copyright © 2020 Esteban Choque Villalobos. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var usuarioField: UITextField!
@IBOutlet weak var passField: UITextField!
@IBOutlet var _login_button: UIButton!
var whosLogin : String!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let button = UIButton.init(type: .roundedRect)
button.frame = CGRect(x:100.0, y:400.0, width:200.0, height:50.0)
button.setTitle("INGRESAR", for: .normal)
button.addTarget(self, action: #selector(buttonClicked(_ :)), for: .touchUpInside)
self.view.addSubview(button)
let myColor : UIColor = UIColor.black
usuarioField.layer.borderColor = myColor.cgColor
usuarioField.layer.borderWidth = 1.0
passField.layer.borderColor = myColor.cgColor
passField.layer.borderWidth = 1.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private var credentials: String {
//return "\(ingresoVisitantes):\(albosalpz01codex)"
return "ingresoVisitantes:albosalpz01codex" }
private var basicAuthHeader: String
{
return "Basic \(credentials)"
}
func makePostCall(user : String, pass : String) {
/*let user : String
let pass : String
user = usuarioField.text!
pass = passField.text!*/
let todosEndpoint: String = "http://190.129.90.115:8083/ingresoVisitantes/oauth/token"
let loginString = String(format: "%@:%@", "ingresoVisitantes", "albosalpz01codex")
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()
guard let todosURL = URL(string: todosEndpoint) else {
print("Error: cannot create URL")
return
}
var todosUrlRequest = URLRequest(url: todosURL)
todosUrlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
todosUrlRequest.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
todosUrlRequest.setValue("PostmanRunTime/7.26.3", forHTTPHeaderField: "User-Agent")
todosUrlRequest.httpMethod = "POST"
let data : Data = "username=\(user)&password=\(pass)&grant_type=password".data(using: .utf8)!
todosUrlRequest.httpBody = data
let session = URLSession.shared
let task = session.dataTask(with: todosUrlRequest) {
(data, response, error) in
guard error == nil else {
print("error calling POST on /todos/1")
print(error!)
return
}
guard let responseData = data else {
print("Error: did not receive data")
return
}
do {
guard let receivedTodo = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any] else {
print("Could not get JSON from responseData as dictionary")
return
}
print("The access_token is: " + receivedTodo.description)
guard let todoID = receivedTodo["access_token"] as? String else {
print("Could not get todoID as int from JSON")
return
}
DispatchQueue.main.async {
self.performSegue(withIdentifier:"homeSegue",sender:self);
}
print("The message is: \(todoID)")
} catch {
print("error parsing response from POST on /todos")
return
}
}
task.resume()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let nextViewController = segue.destination as! HomeController
nextViewController.whosLogin = usuarioField.text!
}
@objc func buttonClicked(_ : UIButton)
{
let user : String
let pass : String
user = usuarioField.text!
pass = passField.text!
if(!user.isEmpty && !pass.isEmpty)
{
//makePostCall(user:user, pass:pass)
self.performSegue(withIdentifier: "homeSegue", sender: nil)
}
else
{
print("Todos los campos son necesarios")
}
//makePostCall()
}
}
|
//
// SetStockViewedResponse.swift
// carWash
//
// Created by Juliett Kuroyan on 14.01.2020.
// Copyright © 2020 VooDooLab. All rights reserved.
//
struct SetStockViewedResponse: Codable {
var status: String
}
|
//
// Github.swift
// Sample
//
// Created by PranayBansal on 08/04/19.
// Copyright © 2019 PranayBansal. All rights reserved.
//
import Foundation
struct GithubApi : Codable {
let avatar_url : String
let login :String
}
|
//
// Day2ViewController.swift
// DailyiOSAnimations
//
// Created by Jinsei Shima on 2018/07/06.
// Copyright © 2018 Jinsei Shima. All rights reserved.
//
import Foundation
import UIKit
class Day2ViewController: UIViewController {
let targetView = UIView()
let slider = UISlider()
let button = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
targetView.frame = CGRect(origin: .zero, size: CGSize(width: 100, height: 100))
targetView.center = CGPoint(x: view.center.x, y: 150)
targetView.backgroundColor = UIColor.lightGray
view.addSubview(targetView)
slider.frame = CGRect(origin: .zero, size: CGSize(width: 200, height: 40))
slider.center = CGPoint(x: view.center.x, y: view.center.y + 200)
slider.addTarget(self, action: #selector(self.changeValue(_:)), for: .valueChanged)
slider.minimumValue = 0
slider.maximumValue = 1
view.addSubview(slider)
button.frame = CGRect(x: 0, y: 0, width: 80, height: 60)
button.center = CGPoint(x: view.center.x, y: view.center.y + 250)
button.setTitle("Resume", for: .normal)
button.setTitleColor(.darkGray, for: .normal)
button.addTarget(self, action: #selector(self.tapButton(_:)), for: .touchUpInside)
view.addSubview(button)
let animation = CABasicAnimation(keyPath: "position")
animation.fromValue = targetView.center
animation.toValue = CGPoint(x: targetView.center.x, y: targetView.center.y + 200)
// animation.repeatCount = 0
// animation.autoreverses = true
let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
scaleAnimation.fromValue = 1.0
scaleAnimation.toValue = 2.0
let animations = CAAnimationGroup()
animations.duration = 1.0
animations.animations = [animation, scaleAnimation]
animations.fillMode = kCAFillModeForwards
animations.delegate = self
targetView.layer.removeAllAnimations()
targetView.layer.add(animations, forKey: nil)
targetView.layer.speed = 0.0
}
@objc func changeValue(_ sender: UISlider) {
setProgressLayer(layer: targetView.layer, progress: sender.value)
}
@objc func tapButton(_ sender: UIColor) {
print("tap button")
let timeOffset = targetView.layer.timeOffset
targetView.layer.speed = 1.0
targetView.layer.timeOffset = 0.0
targetView.layer.beginTime = 0.0
targetView.layer.beginTime = targetView.layer.convertTime(CACurrentMediaTime(), from: nil) - timeOffset
}
func setProgressLayer(layer: CALayer, progress: Float) {
layer.timeOffset = Double(progress)
layer.beginTime = layer.convertTime(CACurrentMediaTime(), from: nil)
}
}
extension Day2ViewController : CAAnimationDelegate {
func animationDidStart(_ anim: CAAnimation) {
print("animationDidStart", anim)
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
print("animationDidStop", anim)
}
}
|
import SwiftUI
import WaterRowerData_BLE
struct DeviceDetailsView: View {
@ObservedObject var viewModel: DeviceDetailsViewModel
var body: some View {
List {
connectionRow()
if viewModel.connectionStatus == .connected {
Group {
dataRow(title: "Stroke rate") { rowerData in rowerData?.strokeRate }
dataRow(title: "Stroke count") { rowerData in rowerData?.strokeCount }
dataRow(title: "Average stroke rate") { rowerData in rowerData?.averageStrokeRate }
dataRow(title: "Total distance") { rowerData in rowerData?.totalDistanceMeters }
dataRow(title: "Instantaneous pace") { rowerData in rowerData?.instantaneousPaceSeconds }
dataRow(title: "Average pace") { rowerData in rowerData?.averagePaceSeconds }
dataRow(title: "Instantaneous power") { rowerData in rowerData?.instantaneousPowerWatts }
dataRow(title: "Average power") { rowerData in rowerData?.averagePowerWatts }
dataRow(title: "Resistance level") { rowerData in rowerData?.resistanceLevel }
dataRow(title: "Total energy") { rowerData in rowerData?.totalEnergyKiloCalories }
}
Group {
dataRow(title: "Energy per hour") { rowerData in rowerData?.energyPerHourKiloCalories }
dataRow(title: "Energy per minute") { rowerData in rowerData?.energyPerMinuteKiloCalories }
dataRow(title: "Heart rate") { rowerData in rowerData?.heartRate }
dataRow(title: "Metabolic equivalent") { rowerData in rowerData?.metabolicEquivalent }
dataRow(title: "Elapsed time") { rowerData in rowerData?.elapsedTimeSeconds }
dataRow(title: "Remaining time") { rowerData in rowerData?.remainingTimeSeconds }
}
}
}.navigationBarTitle(viewModel.deviceName)
.onAppear { self.viewModel.viewDidAppear() }
.onDisappear { self.viewModel.viewDidDisappear() }
}
private func connectionRow() -> some View {
HStack {
connectionStatusText()
Spacer()
connectionButton().buttonStyle(BorderlessButtonStyle())
}
}
private func connectionStatusText() -> Text {
return Text(viewModel.connectionStatus.rawValue)
}
private func connectionButton() -> some View {
switch viewModel.connectionStatus {
case .disconnected, .connecting, .failed:
return AnyView(connectButton(connectionStatus: viewModel.connectionStatus))
case .connected:
return AnyView(disconnectButton())
}
}
private func connectButton(connectionStatus: ConnectionStatus) -> some View {
return Button(action: {
self.viewModel.connect()
}) {
Text("Connect")
}.disabled(connectionStatus != .disconnected)
}
private func disconnectButton() -> some View {
return Button(action: {
self.viewModel.disconnect()
}) {
Text("Disconnect")
}.disabled(false)
}
private func dataRow(
title: String,
value: (RowerData?) -> Any?
) -> some View {
return HStack {
Text(title)
Spacer()
valueText(value: value(viewModel.rowerData))
}
}
private func valueText(value: Any?) -> Text {
if let value = value {
return Text(String(describing: value))
} else {
return Text("-")
}
}
}
struct DeviceDetailsView_Previews: PreviewProvider {
static var previews: some View {
DeviceDetailsView(
viewModel: DeviceDetailsViewModel(
Device(id: UUID(), name: "My device")
)
)
}
}
|
//
// acceptedCellPoster.swift
// WorkingBeez
//
// Created by Brainstorm on 2/24/17.
// Copyright © 2017 Brainstorm. All rights reserved.
//
import UIKit
class acceptedCellPoster: UITableViewCell {
@IBOutlet weak var lblSeekerName: UILabel!
@IBOutlet weak var lblJobCompleted: UILabel!
@IBOutlet weak var viewSeekerRating: HCSStarRatingView!
@IBOutlet weak var imgSeekerPhoto: cImageView!
@IBOutlet weak var lblSeekerStatus: cLable!
@IBOutlet weak var btnSeekerKm: UIButton!
@IBOutlet weak var btnSeekerHaveVehicle: UIButton!
@IBOutlet weak var btnSeekerTotalJobs: UIButton!
@IBOutlet weak var btnSeekerTotalPayment: UIButton!
@IBOutlet weak var btnChat: UIButton!
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
}
}
|
//
// MoveDetailView.swift
// PocketDex
//
// Created by Thomas Tenzin on 6/14/20.
// Copyright © 2020 Thomas Tenzin. All rights reserved.
//
import SwiftUI
import CodableCSV
struct MoveDetailView: View {
@EnvironmentObject var selectedVersion: UserVersion
@Environment(\.managedObjectContext) var moc
@FetchRequest(entity: FavPkmn.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \FavPkmn.pkmnID, ascending: true)]) var allFavPkmn: FetchedResults<FavPkmn>
var pokemonList: [Pokemon]
var pokemonFormsList: [Pokemon_Forms]
var pokemonTypeList: [PokemonType]
var moveList: [Move]
var moveEffectList: [MoveEffectProse]
var typeList: [Type]
var abilityList: [Ability]
var abilityProseList: [AbilityProse]
var pokemonAbilitiesList: [PokemonAbilities]
var itemList: [Item]
let move: Move
var versionFilter: Int = 18
var pokemonMoveList: [PokemonMove] {
return Bundle.main.decodeCSV(move.pkmnMovesName + "_\(String(format:"%02d", selectedVersion.versionOrder+1))" + ".csv")
}
var filteredPokemonMoveList_byVer: [PokemonMove] {
return pokemonMoveList.filter{$0.version_group_id == self.selectedVersion.versionOrder+1}
}
var filteredPokemonMoveList: [PokemonMove] {
return filteredPokemonMoveList_byVer.filter{$0.pokemon_id < 808}
}
var body: some View {
GeometryReader { geo in
ScrollView(.vertical) {
VStack {
HStack{
// Move Type
HStack{
Text("Type")
.font(.headline)
ZStack {
Text("\(self.typeList[self.move.type_id-1].wrappedName)")
}
.frame(width: 56, height: 28)
.background(typeColor(type: self.typeList[self.move.type_id-1].wrappedName))
.cornerRadius(6)
.font(.caption)
}
.padding()
.frame(width: geo.size.width/2)
.fixedSize(horizontal: false, vertical: true)
.background(Color(UIColor.secondarySystemBackground))
.cornerRadius(12)
// Move Category
HStack{
Text("Category")
.font(.headline)
.fixedSize(horizontal: true, vertical: false)
Text("\(self.move.damage_class)")
.frame(width: 56, height: 28)
.background(self.categoryColor(category: self.move.damage_class))
.cornerRadius(6)
.font(.caption)
}
.padding()
.frame(width: geo.size.width/2)
.fixedSize(horizontal: false, vertical: true)
.background(Color(UIColor.secondarySystemBackground))
.cornerRadius(12)
}
.padding(.top)
VStack(alignment: .leading) {
HStack{
Text("Move Details")
.font(.system(.title2, design: .rounded))
.bold()
Spacer()
}
Divider()
HStack{
Text("Power:")
.font(.headline)
Text("\(self.move.wrappedPower)")
}
HStack{
Text("Accuracy:")
.font(.headline)
Text("\(self.move.wrappedAccuracy)")
}
HStack{
Text("PP:")
.font(.headline)
Text("\(self.move.wrappedPP)")
}
}
.padding()
.frame(width: geo.size.width)
.fixedSize(horizontal: false, vertical: true)
.background(Color(UIColor.secondarySystemBackground))
.cornerRadius(12)
// Move Battle Effect
VStack(alignment: .leading) {
HStack{
Text("Battle Effect")
.font(.system(.title2, design: .rounded))
.bold()
Spacer()
}
Text(self.moveEffectFromId(moveEffectID: self.move.effect_id, effectChance: self.move.effect_chance, moveEffectList: moveEffectList))
.lineLimit(40)
}
.padding()
.frame(width: geo.size.width)
.fixedSize(horizontal: false, vertical: true)
.background(Color(UIColor.secondarySystemBackground))
.cornerRadius(12)
// Pokemon that can learn the move
VStack{
Text("Pokemon than can learn the move: ")
.font(.caption)
ForEach(self.filteredPokemonMoveList, id: \.id) { pokemonMove in
NavigationLink(destination: DetailView(pokemonFormsList: pokemonFormsList,
pokemonTypeList: pokemonTypeList,
typeList: typeList,
pokemonList: pokemonList,
moveList: moveList,
moveEffectList: moveEffectList,
abilityList: abilityList,
abilityProseList: abilityProseList,
pokemonAbilitiesList: pokemonAbilitiesList,
itemList: itemList,
pkmn: self.pokemonList[pokemonMove.pokemon_id-1])) {
pokemonRow(PKMN: self.pokemonList[pokemonMove.pokemon_id-1], pokemonMove: pokemonMove)
.padding()
.frame(width: geo.size.width, height: 48)
.background(Color(UIColor.secondarySystemBackground))
.cornerRadius(12)
.hoverEffect(.highlight)
}
}
}
}
}
.navigationBarTitle("\(self.move.wrappedName)", displayMode: .inline)
.navigationBarItems(trailing:
Menu {
if allFavPkmn.contains{$0.pkmnID == move.id && $0.type==2} {
Button(action: {
// let newFavPkmn = FavPkmn(context: self.moc)
// newFavPkmn.id = UUID()
// newFavPkmn.pkmnID = Int16(pkmn.id)
// try? self.moc.save()
print("already saved")
}) {
Text("Added to favorites")
Image(systemName: "star.fill")
}
} else {
Button(action: {
let newFavPkmn = FavPkmn(context: self.moc)
newFavPkmn.id = UUID()
newFavPkmn.pkmnID = Int16(move.id)
newFavPkmn.type = 2 // Type 2 = Move
try? self.moc.save()
// print("saved, \(newTeam.name ?? "failed")")
}) {
Text("Add to favorites")
Image(systemName: "star")
}
}
} label: {
Image(systemName: "ellipsis.circle")
.imageScale(.large)
}
)
}
.padding(.horizontal)
}
func moveEffectFromId(moveEffectID: Int, effectChance: Int?, moveEffectList: [MoveEffectProse]) -> String {
var uncleanMoveEffect = ""
if let i = moveEffectList.firstIndex(where: {$0.move_effect_id == moveEffectID }) {
uncleanMoveEffect = moveEffectList[i].short_effect?.replacingOccurrences(of: "$effect_chance", with: "\(effectChance ?? 0)") ?? "No Effect"
return removeMechanic(input: uncleanMoveEffect)
}
return "No Effect"
}
func categoryColor(category: String) -> Color {
if category == "Physical" {
return Color.red
} else if category == "Special" {
return Color.blue
} else if category == "Status" {
return Color.gray
} else {
return Color.white
}
}
}
struct pokemonRow: View {
let PKMN: Pokemon
let pokemonMove: PokemonMove
var typeList: [Type] = Bundle.main.decode("types.json")
var pokemonTypeList: [PokemonType] = Bundle.main.decode("pokemon_types.json")
@EnvironmentObject var selectedTheme: UserTheme
let moveMethod: [String] = ["Level-up", "Egg Move", "Move Tutor", "TM/HM", "Stadium Surfing Pikachu", "Light Ball Egg Move", "Colosseum Purification", "XD-Shadow", "XD-Prufication", "Form Change"]
var body: some View {
HStack{
if selectedTheme.showSprites {
Image("\(PKMN.imgName)")
.renderingMode(Image.TemplateRenderingMode?.init(Image.TemplateRenderingMode.original))
}
VStack(alignment: .leading) {
Text("\(PKMN.id) - \(PKMN.wrappedName)")
.font(.headline)
Text("\(moveMethod[pokemonMove.pokemon_move_method_id-1])")
.font(.caption)
}
Spacer()
ForEach(self.getTypes(typeList: self.pokemonTypeList, pkmnID: PKMN.id), id: \.self) { type1 in
ZStack {
Text("\(self.typeList[type1.type_id - 1].wrappedName)")
.foregroundColor(Color(UIColor.label))
}
.frame(width: 56, height: 28)
.background(typeColor(type: self.typeList[type1.type_id - 1].wrappedName ))
.cornerRadius(6)
.font(.caption)
}
}
}
func getTypes(typeList: [PokemonType], pkmnID: Int) -> [PokemonType] {
var resultTypes = [PokemonType]()
if let i = typeList.firstIndex(where: {$0.pokemon_id == pkmnID }) {
resultTypes.append(typeList[i])
if typeList[i+1].pokemon_id == pkmnID {
resultTypes.append(typeList[i+1])
}
}
return resultTypes
}
}
|
//
// DetailViewModel.swift
// MovieStatusCode
//
// Created by Kingsley Enoka on 10/28/20.
//
import Foundation
class DetailViewModel {
static let shared = DetailViewModel()
private var result: Results? = nil
private var imageData: Data? = nil
func getImage(completionHandler: @escaping (Data?)->() ) {
guard let urlString = result?.image_url,
let url = URL(string: urlString) else { return }
APIHandler.shared.getData(url: url) { (data, _, _) in
completionHandler(data)
}
}
func setResult(result: Results) {
self.result = result
}
func getResult() -> Results? {
return result
}
private init() {}
}
|
//
// ViewControllerTwo.swift
// StickyHeader
//
// Created by Yannick Heinrich on 26.08.16.
// Copyright © 2016 yageek. All rights reserved.
//
import UIKit
class ViewControllerTwo: UITableViewController {
let headerView: UIView = {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 100))
view.backgroundColor = UIColor.blue
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.stickyHeader.view = self.headerView
self.tableView.stickyHeader.height = 200
self.tableView.stickyHeader.minimumHeight = 100
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1000
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier:"Cell", for: indexPath)
return cell
}
}
|
//
// DetailViewController.swift
// College Profile Builder 1
//
// Created by jcysewski on 1/21/16.
// Copyright © 2016 jcysewski. All rights reserved.
//
import UIKit
import SafariServices
class DetailViewController: UIViewController, SFSafariViewControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
@IBOutlet weak var myImageView: UIImageView!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var locationTextField: UITextField!
@IBOutlet weak var numberOfPeopleTextField: UITextField!
@IBOutlet weak var urlTextField: UITextField!
let myImagePicker = UIImagePickerController()
var myPhotos: [UIImage] = [] // empty arrays of UIImages
var counter = 0
var college : CollegeClass!
override func viewDidLoad()
{
super.viewDidLoad()
nameTextField.text! = college.name
locationTextField.text! = college.location
numberOfPeopleTextField.text! = String(college.numberOfStudents)
myImageView.image = college.picture
urlTextField.text! = college.webpage
myImagePicker.delegate = self
myImagePicker.allowsEditing = true
}
@IBAction func saveButtonTapped(sender: AnyObject)
{
college.name = nameTextField.text!
college.location = locationTextField.text!
college.numberOfStudents = Int(numberOfPeopleTextField.text!)!
college.webpage = urlTextField.text!
}
@IBAction func webpageButtonTapped(sender: AnyObject)
{
let myURL = NSURL(string: "\(college.webpage)")
let svc = SFSafariViewController(URL: myURL!)
svc.delegate = self
presentViewController(svc, animated: true, completion: nil)
}
func safariViewControllerDidFinish(controller: SFSafariViewController)
{
controller.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func changePhotoButtonTapped(sender: AnyObject)
{
print("tapped")
let mySheet = UIAlertController(title: "add from...", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
mySheet.addAction(UIAlertAction(title: "Photo Library", style: .Default, handler:
{ (libraryAction) -> Void in
self.myImagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(self.myImagePicker, animated: true, completion: nil)
}))
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
{
mySheet.addAction(UIAlertAction(title: "Camera", style: .Default, handler:
{ (cameraAction) -> Void in
self.myImagePicker.sourceType = UIImagePickerControllerSourceType.Camera
self.presentViewController(self.myImagePicker, animated: true, completion: nil)
}))
}
presentViewController(mySheet, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
{
myImagePicker.dismissViewControllerAnimated(true)
{ () -> Void in
self.myImageView.image = (info[UIImagePickerControllerEditedImage] as! UIImage)
}
}
}
|
//
// JKHyperLabel.swift
// ADGAP
//
// Created by Jitendra Kumar on 18/06/20.
// Copyright © 2020 Jitendra Kumar. All rights reserved.
//
import UIKit
extension UIView {
private struct OnClickHolder {
static var _closure:(_ gesture: UITapGestureRecognizer)->() = {_ in }
}
private var onClickClosure: (_ gesture: UITapGestureRecognizer) -> () {
get { return OnClickHolder._closure }
set { OnClickHolder._closure = newValue }
}
func onClick(target: Any, _ selector: Selector) {
isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: target, action: selector)
addGestureRecognizer(tap)
}
func onClick(closure: @escaping (_ gesture: UITapGestureRecognizer)->()) {
self.onClickClosure = closure
isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(onClickAction))
addGestureRecognizer(tap)
}
@objc private func onClickAction(_ gesture: UITapGestureRecognizer) {
onClickClosure(gesture)
}
}
extension NSMutableAttributedString {
func removeAttributes() {
let range = NSMakeRange(0, self.length)
self.removeAttributes(range: range)
}
func removeAttributes(range: NSRange) {
self.enumerateAttributes(in: range, options: []) { (attributes, range, _) in
for attribute in attributes {
self.removeAttribute(attribute.key, range: range)
}
}
}
}
extension UILabel{
func setLinkFor(_ subStrings:String...,linkAttributed:[NSAttributedString.Key:Any]? = nil,completion:@escaping(UILabel, String)->Void){
let font = UIFont.systemFont(ofSize: self.font!.pointSize+2, weight: .semibold)
let underlineColor:UIColor = self.textColor
if let attributedText = self.attributedText {
let attributedString = NSMutableAttributedString(attributedString: attributedText)
for string in subStrings {
let linkRange = (attributedText.string as NSString).range(of: string)
let linkAttributedDict:[NSAttributedString.Key:Any] = linkAttributed == nil ? [.underlineColor: underlineColor,.underlineStyle:NSUnderlineStyle.single.rawValue,.strokeColor: self.textColor!,.font:font] : linkAttributed!
attributedString.addAttributes(linkAttributedDict, range: linkRange)
}
self.attributedText = attributedString
}else if let text = self.text{
let fullRange = NSMakeRange(0, text.count)
let attributedString = NSMutableAttributedString(string: text)
let textAttributed:[NSAttributedString.Key:Any] = [.font: self.font!,.foregroundColor: self.textColor!]
attributedString.addAttributes(textAttributed, range: fullRange)
for string in subStrings {
let linkRange = (text as NSString).range(of: string)
let linkAttributedDict:[NSAttributedString.Key:Any] = linkAttributed == nil ? [.underlineColor: underlineColor,.underlineStyle:NSUnderlineStyle.single.rawValue,.strokeColor: self.textColor!,.font: font] : linkAttributed!
attributedString.addAttributes(linkAttributedDict, range: linkRange)
}
self.attributedText = attributedString
}
self.onClick {gesture in
guard let text = self.text else { return }
for string in subStrings {
let rRange = (text as NSString).range(of: string)
if gesture.didTapAttributedTextInLabel(label: self, inRange: rRange) {
completion(self,string)
}
}
}
}
}
extension UITapGestureRecognizer {
func didTapAttributedTextInLabel(label: UILabel, inRange targetRange: NSRange) -> Bool {
// Create instances of NSLayoutManager, NSTextContainer and NSTextStorage
let layoutManager = NSLayoutManager()
let textContainer = NSTextContainer(size: CGSize.zero)
let textStorage = NSTextStorage(attributedString: label.attributedText!)
// Configure layoutManager and textStorage
layoutManager.addTextContainer(textContainer)
textStorage.addLayoutManager(layoutManager)
// Configure textContainer
textContainer.lineFragmentPadding = 0.0
textContainer.lineBreakMode = label.lineBreakMode
textContainer.maximumNumberOfLines = label.numberOfLines
let labelSize = label.bounds.size
textContainer.size = labelSize
// Find the tapped character location and compare it to the specified range
let locationOfTouchInLabel = self.location(in: label)
let textBoundingBox = layoutManager.usedRect(for: textContainer)
let textContainerOffset = CGPoint(x: (labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x,
y: (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y);
let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x,
y: locationOfTouchInLabel.y - textContainerOffset.y);
var indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
indexOfCharacter = indexOfCharacter + 4
return NSLocationInRange(indexOfCharacter, targetRange)
}
}
|
//
// PhotoRepresentation.swift
// Schematic Capture
//
// Created by Gi Pyo Kim on 2/13/20.
// Copyright © 2020 GIPGIP Studio. All rights reserved.
//
import Foundation
struct PhotoRepresentation: Codable {
var name: String
var imageData: Data
private enum CodingKeys: String, CodingKey {
case name
case imageData
}
}
|
//
// TripEntityDataMapper.swift
// EmpireMobileApp
//
// Created by Rodrigo Nunes on 10/12/19.
// Copyright © 2019 Rodrigo Nunes Gil. All rights reserved.
//
import Foundation
struct TripEntityDataMapper {
static func transform(entity: TripEntity) -> Trip {
let pilot = PilotEntityDataMapper.transform(entity: entity.pilot)
let distance = DistanceEntityDataMapper.transform(entity: entity.distance)
let pickUp = LocationEntityDataMapper.transform(entity: entity.pickUp)
let dropOff = LocationEntityDataMapper.transform(entity: entity.dropOff)
return Trip(id: entity.id,
pilot: pilot,
distance: distance,
duration: entity.duration,
pickUp: pickUp,
dropOff: dropOff)
}
}
|
//
// LaunchViewController.swift
// FGiP
//
// Created by Peter Chen on 2016-04-23.
// Copyright © 2016 CoreDevo. All rights reserved.
//
import UIKit
class LaunchViewController: UIViewController, LoginViewDelegate {
@IBOutlet weak var iconView: UIView!
@IBOutlet weak var vesselButton: UIButton!
@IBOutlet weak var fisherButton: UIButton!
private var loginView: LoginView!
private var username: String?
override func viewDidLoad() {
super.viewDidLoad()
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
self.view.addGestureRecognizer(tapRecognizer)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.iconView.hidden = true
self.vesselButton.hidden = true
self.fisherButton.hidden = true
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.iconView.popOut {
self.vesselButton.popOut({
self.fisherButton.popOut()
})
}
}
@IBAction func vesselButtonPressed(sender: AnyObject) {
self.performSegueWithIdentifier("ToVesselVC", sender: sender)
}
@IBAction func fisherButtonPressed(sender: AnyObject) {
self.loginView = LoginView()
self.loginView.delegate = self
self.loginView.translatesAutoresizingMaskIntoConstraints = false
var mConstraints: [NSLayoutConstraint] = []
mConstraints.append(NSLayoutConstraint(item: self.loginView, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1.0, constant: 0.0))
mConstraints.append(NSLayoutConstraint(item: self.loginView, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
mConstraints.append(NSLayoutConstraint(item: self.loginView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 250))
mConstraints.append(NSLayoutConstraint(item: self.loginView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 350))
self.loginView.hidden = true
self.loginView.layer.cornerRadius = 15
self.loginView.layer.masksToBounds = true
self.view.addSubview(loginView)
self.view.addConstraints(mConstraints)
self.fisherButton.enabled = false
self.loginView.popOut()
}
@objc private func dismissKeyboard() {
self.loginView?.usernameTextField.resignFirstResponder()
}
func loginViewDidCancelLogin() {
UIView.animateWithDuration(0.3, animations: {
self.loginView.alpha = 0
}) { (finished) in
self.loginView.removeFromSuperview()
self.loginView = nil
self.fisherButton.enabled = true
}
}
func loginViewDidFinishLoginWithUserID(id: String) {
NSLog("Login: \(id)")
self.username = id
self.performSegueWithIdentifier("ToFisherVC", sender: self)
UIView.animateWithDuration(0.3, animations: {
self.loginView.alpha = 0
}) { (finished) in
self.loginView.removeFromSuperview()
self.loginView = nil
self.fisherButton.enabled = true
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
switch identifier {
case "ToFisherVC":
if let destVC = segue.destinationViewController as? FisherViewController {
destVC.username = self.username
}
default:
()
}
}
}
} |
//
// TreeDCoordinate.swift
// aoc2020
//
// Created by Shawn Veader on 12/17/20.
//
import Foundation
struct TreeDCoordinate: PowerSourceCoordinate, Equatable, Hashable {
let x: Int
let y: Int
let z: Int
var neighboringCoordinates: [TreeDCoordinate] {
(x-1...x+1).flatMap { nx -> [TreeDCoordinate] in
(y-1...y+1).flatMap { ny -> [TreeDCoordinate] in
(z-1...z+1).compactMap { nz -> TreeDCoordinate? in
let neighbor = TreeDCoordinate(x: nx, y: ny, z: nz)
guard neighbor != self else { return nil } // don't include ourselves
return neighbor
}
}
}
}
}
extension TreeDCoordinate: CustomDebugStringConvertible {
var debugDescription: String {
"(x: \(x), y: \(y), z: \(z))"
}
}
|
//
// StudyPactOnboardingViewController.swift
// berkeley-mobile
//
// Created by Eashan Mathur on 10/17/20.
// Copyright © 2020 ASUC OCTO. All rights reserved.
//
import UIKit
class StudyPactOnboardingViewController: UIViewController {
let numberLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.widthAnchor.constraint(equalToConstant: 30).isActive = true
label.heightAnchor.constraint(equalToConstant: 30).isActive = true
label.textColor = .white
label.font = Font.medium(18)
label.textAlignment = .center
label.clipsToBounds = true
return label
}()
let stepLabel: UILabel = {
let label = UILabel()
label.font = Font.bold(30)
label.adjustsFontSizeToFitWidth = true
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
let screenshotBlobView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
let screenshotImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
let blobImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
let descriptionLabel: UILabel = {
let descriptionLabel = UILabel()
descriptionLabel.numberOfLines = 4
descriptionLabel.adjustsFontSizeToFitWidth = true
descriptionLabel.textColor = .gray
descriptionLabel.textAlignment = .center
descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
return descriptionLabel
}()
let bottomButton: UIButton = {
let button = UIButton()
button.titleLabel?.font = Font.medium(15)
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
button.widthAnchor.constraint(equalToConstant: 110).isActive = true
button.heightAnchor.constraint(equalToConstant: 37).isActive = true
return button
}()
override func viewDidLayoutSubviews() {
bottomButton.layer.cornerRadius = bottomButton.frame.height / 2
numberLabel.layer.cornerRadius = numberLabel.frame.height / 2
}
@objc func buttonTapped(_: UIButton) {
if getStarted {
if let tabBarController = UIApplication.shared.windows.first!.rootViewController as? TabBarController {
tabBarController.selectProfileTab()
}
self.dismiss(animated: true, completion: nil)
} else {
pageViewController.moveToNextPage()
}
}
var getStarted = false
var pageViewController: PageViewController
init(stepText: String, themeColor: UIColor, stepNumber: Int, screenshotImage: UIImage, blobImage: UIImage,
descriptionText: String, pageViewController: PageViewController, boldedStrings: [String] = [],
getStarted: Bool = false) {
numberLabel.backgroundColor = themeColor
numberLabel.text = String(stepNumber)
stepLabel.text = stepText
screenshotImageView.image = screenshotImage
blobImageView.image = blobImage
descriptionLabel.attributedText = NSAttributedString.boldedText(withString: descriptionText, boldStrings: boldedStrings, font: Font.regular(18), boldFont: Font.bold(18))
bottomButton.backgroundColor = themeColor
self.getStarted = getStarted
self.pageViewController = pageViewController
super.init(nibName: nil, bundle: nil)
if getStarted {
bottomButton.setTitle("Let's go!", for: .normal)
} else {
bottomButton.setTitle("Next", for: .normal)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setupCard()
}
func setupCard(){
let stack = UIStackView()
stack.axis = .vertical
stack.distribution = .equalSpacing
stack.alignment = .center
stack.spacing = view.frame.height * 0.03
stack.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stack)
let numberTitleStack = UIStackView()
numberTitleStack.axis = .horizontal
numberTitleStack.distribution = .equalCentering
numberTitleStack.alignment = .center
numberTitleStack.spacing = 25
numberTitleStack.addArrangedSubview(numberLabel)
numberTitleStack.addArrangedSubview(stepLabel)
stack.addArrangedSubview(screenshotBlobView)
stack.addArrangedSubview(numberTitleStack)
stack.addArrangedSubview(descriptionLabel)
stack.addArrangedSubview(bottomButton)
stack.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
stack.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 40).isActive = true
stack.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -40).isActive = true
screenshotBlobView.addSubview(blobImageView)
screenshotBlobView.addSubview(screenshotImageView)
screenshotBlobView.widthAnchor.constraint(equalTo: stack.widthAnchor).isActive = true
screenshotBlobView.heightAnchor.constraint(equalTo: screenshotImageView.heightAnchor).isActive = true
screenshotImageView.contentMode = .scaleAspectFit
screenshotImageView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.35).isActive = true
screenshotImageView.centerXAnchor.constraint(equalTo: screenshotBlobView.centerXAnchor).isActive = true
blobImageView.contentMode = .scaleAspectFit
blobImageView.centerXAnchor.constraint(equalTo: screenshotBlobView.centerXAnchor).isActive = true
blobImageView.centerYAnchor.constraint(equalTo: screenshotBlobView.centerYAnchor).isActive = true
blobImageView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -25).isActive = true
}
}
extension NSAttributedString {
static func boldedText(withString string: String, boldStrings: [String], font: UIFont, boldFont: UIFont) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: string,
attributes: [NSAttributedString.Key.font: font])
let boldFontAttribute: [NSAttributedString.Key: Any] = [NSAttributedString.Key.font: boldFont]
for boldString in boldStrings {
let range = (string as NSString).range(of: boldString)
attributedString.addAttributes(boldFontAttribute, range: range)
}
return attributedString
}
}
|
//
// ViewController.swift
// CategoryAverage
//
// Created by Suraj Pathak on 26/6/17.
// Copyright © 2017 Suraj Pathak. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var averageLabel: UILabel!
var spinner: UIActivityIndicatorView!
let categoryType: String = Config.categoryType
var processedItems: [Product]! {
didSet {
tableView.reloadData()
let validProducts = processedItems.filter { $0.category == self.categoryType }
statusLabel.text = "Found " + "\(validProducts.count)" + " items out of \(processedItems.count)"
if validProducts.count > 0 {
averageLabel.text = String(format: "%.2f", Product.averageCubicWeight(validProducts))
} else {
averageLabel.text = "--"
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
spinner.hidesWhenStopped = true
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: spinner)
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Reload", style: .plain, target: self, action: #selector(reload))
categoryLabel.text = "Category: " + categoryType
reload()
}
func reload() {
processedItems = []
let firstPage = Config.firstPage
readProducts(categoryName: self.categoryType, page: firstPage)
}
func readProducts(categoryName: String, page: String) {
self.title = "Processing page \(page) "
spinner.startAnimating()
ProductRequest(pageUrl: page)?.fetch({ [weak self] page in
if let products = page?.products {
self?.processedItems.append(contentsOf: products)
}
if let next = page?.nextUrl {
self?.readProducts(categoryName: categoryName, page: next)
} else {
self?.title = "Kogan!"
self?.spinner.stopAnimating()
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Processed Items"
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return processedItems.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 64
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell!
let cellIdentifier = "TableViewCell"
if let validCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) {
cell = validCell
} else {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellIdentifier)
}
let product = processedItems[indexPath.row]
cell.textLabel?.text = product.title
cell.textLabel?.numberOfLines = 0
cell.detailTextLabel?.text = String(format: "%@ (%.2f)", product.category, product.cubicWeight)
cell.textLabel?.textColor = product.category == self.categoryType ? .red : .black
return cell
}
}
|
//
// ReportViewModel.swift
// SafeNomad_iOS
//
// Created by Yessen Yermukhanbet on 5/23/21.
//
import Foundation
import Alamofire
protocol ReportViewModelDelegate {
func success()
}
class ReportViewModel: NSObject{
var delegate: ReportViewModelDelegate?
let headers: HTTPHeaders = [
"Content-Type": "application/json; utf-8"
]
public func submitReport(with report: ReportRequest){
let param: [String: Any] = [
"userId": report.userId,
"message": report.message,
"longitude": report.longitude,
"latitude": report.latitude
]
AF.request("https://safe-nomad.herokuapp.com/complain", method: .post,parameters: param, encoding: JSONEncoding.default, headers: headers).validate(statusCode: 200 ..< 500).responseJSON { AFdata in
do {
let data = AFdata.value as? [String: Any]
debugPrint(data as Any)
self.delegate!.success()
}
}
}
}
|
//
// Asset.swift
// WavesWallet-iOS
//
// Created by mefilt on 09.07.2018.
// Copyright © 2018 Waves Platform. All rights reserved.
//
import Foundation
import RealmSwift
final class Asset: Object {
@objc dynamic var id: String = ""
@objc dynamic var wavesId: String?
@objc dynamic var gatewayId: String?
@objc dynamic var displayName: String = ""
@objc dynamic var precision: Int = 0
@objc dynamic var descriptionAsset: String = ""
@objc dynamic var height: Int64 = 0
@objc dynamic var timestamp: Date = Date()
@objc dynamic var sender: String = ""
@objc dynamic var quantity: Int64 = 0
@objc dynamic var ticker: String?
@objc dynamic var modified: Date = Date()
@objc dynamic var isReusable: Bool = false
@objc dynamic var isSpam: Bool = false
@objc dynamic var isFiat: Bool = false
@objc dynamic var isGeneral: Bool = false
@objc dynamic var isMyWavesToken: Bool = false
@objc dynamic var isWavesToken: Bool = false
@objc dynamic var isGateway: Bool = false
@objc dynamic var isWaves: Bool = false
@objc dynamic var addressRegEx: String = ""
@objc dynamic var iconLogoUrl: String?
@objc dynamic var hasScript: Bool = false
@objc dynamic var minSponsoredFee: Int64 = 0
@objc dynamic var gatewayType: String?
override class func primaryKey() -> String? {
return "id"
}
var icon: String {
return gatewayId ?? displayName
}
}
|
//
// CFWelcomeView.swift
// 花菜微博
//
// Created by 花菜ChrisCai on 2016/12/19.
// Copyright © 2016年 花菜ChrisCai. All rights reserved.
//
import UIKit
import SnapKit
import SDWebImage
class CFWelcomeView: UIView {
fileprivate lazy var iconView = UIImageView(image: UIImage(named: "avatar_default_big"))
fileprivate lazy var label: UILabel = UILabel(text: "欢迎回来", fontSize: 16)
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.red
setupOwerViews()
setupLayoutConstraint()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - UI界面相关
extension CFWelcomeView {
/// 添加子控件
fileprivate func setupOwerViews() {
// 背景图片
let backImageView = UIImageView(image: UIImage(named: "ad_background"))
backImageView.frame = UIScreen.main.bounds
addSubview(backImageView)
// 头像
addSubview(iconView)
// 文字
addSubview(label)
label.alpha = 0
// 设置图片
guard let urlString = CFNetworker.shared.userAccount.avatar_large,
let url = URL(string: urlString) else {
return
}
iconView.sd_setImage(with: url, placeholderImage: UIImage(named: "avatar_default_big"))
// 设置圆角半径
iconView.cornerRadius = 85 * 0.5
}
}
/// 添加约束
extension CFWelcomeView {
fileprivate func setupLayoutConstraint() {
iconView.snp.makeConstraints { (make) in
make.bottom.equalToSuperview().offset(-200)
make.centerX.equalToSuperview()
make.width.height.equalTo(85)
}
label.snp.makeConstraints { (make) in
make.top.equalTo(iconView.snp.bottom).offset(10)
make.centerX.equalToSuperview()
}
}
}
// MARK: - 动画相关
extension CFWelcomeView {
// 视图添加到window上,标识视图已经显示
override func didMoveToWindow() {
super.didMoveToWindow()
// 强制更新约束
self.layoutIfNeeded()
// 更新头像的底部约束
iconView.snp.updateConstraints { (make) in
make.bottom.equalToSuperview().offset(-(UIScreen.main.bounds.height - 200))
}
// 执行动画
UIView.animate(withDuration: 2, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: .curveEaseIn, animations: {
// 更新约束
self.layoutIfNeeded()
}) { (_) in
// 透明度动画
UIView.animate(withDuration: 1, animations: {
self.label.alpha = 1
}, completion: { (_) in
// 动画完成后移除欢迎页
self.removeFromSuperview()
})
}
}
}
|
//
// Framework.swift
// FrameworkTools
//
// Created by James Bean on 4/19/16.
// Copyright © 2016 James Bean. All rights reserved.
//
import Foundation
import SwiftShell
import ScriptingTools
public final class Framework {
// AKA $(PROJECT_DIR)
private var projectDirectory: Path!
// Name of the Framework
private let name: String
// Create a Framework from scratch
public init(
name: String,
git shouldPrepareGit: Bool = true,
carthage shouldPrepareCarthage: Bool = true,
travis shouldPrepareTravis: Bool = true
)
{
self.name = name
createFileStructure()
if shouldPrepareGit { prepareGit() }
if shouldPrepareCarthage { prepareCarthage() }
if shouldPrepareTravis { prepareTravis() }
configureProject()
}
/*
// Create a Framework from an extant file
public init(projectDirectory: Path) throws {
changeDirectory(to: projectDirectory)
}
*/
private func prepareGit() {
changeDirectory(to: projectDirectory)
run("git", "init")
}
private func prepareCarthage() {
changeDirectory(to: projectDirectory)
touch(newFileAt: "Cartfile")
}
private func prepareTravis() {
let travisPath = ".travis.yml"
changeDirectory(to: projectDirectory)
touch(newFileAt: travisPath)
append(line: "language: objective-c", toFileAt: travisPath)
append(line: "osx_image: xcode7.3", toFileAt: travisPath)
append(line: "xcode_project: \(name).xcodeproj", toFileAt: travisPath)
append(line: "xcode_scheme: \(name)Mac", toFileAt: travisPath)
append(line: "xcode_sdk: macosx", toFileAt: travisPath)
append(line: "before_script:", toFileAt: travisPath)
append(line: " - carthage bootstrap", toFileAt: travisPath)
}
private func configureProject() {
print("Configuring project for \(name)")
createProject()
createInfoPropertyLists()
configurePBXGroups()
configureTargets()
configureHeader()
configureSchemes()
configureBuildConfigurationSettings()
addCopyBuildPhaseForTestTargets()
}
private func createFileStructure() {
print("Creating file structure for \(name) at: \(currentDirectory)")
makeDirectory(at: name)
changeDirectory(to: name)
projectDirectory = currentDirectory
createDirectoriesForTargets()
}
private func createDirectoriesForTargets() {
[name, "\(name)Tests"].forEach { makeDirectory(at: $0) }
}
private func createProject() {
run(rubyFileAt: newFrameworkPath, function: "create_project", parameters: name)
}
private func createInfoPropertyLists() {
// TODO: ensure info plists exist
copy(fileAt: primaryTargetInfoPropertyList, to: "\(name)/Info.plist")
copy(fileAt: testsTargetInfoPropertyList, to: "\(name)Tests/Info.plist")
}
private func configurePBXGroups() {
run(rubyFileAt: newFrameworkPath, function: "configure_PBXGroups", parameters: name)
}
private func configureTargets() {
run(rubyFileAt: newFrameworkPath, function: "configure_targets", parameters: name)
}
private func configureHeader() {
createHeader()
run(rubyFileAt: newFrameworkPath, function: "configure_header", parameters: name)
}
private func createHeader() {
touch(newFileAt: "\(name)/\(name).h")
}
private func addCopyBuildPhaseForTestTargets() {
run(rubyFileAt: newFrameworkPath,
function: "add_copy_files_build_phase_for_test_targets",
parameters: name
)
}
private func configureSchemes() {
run(rubyFileAt: newFrameworkPath, function: "configure_schemes", parameters: name)
}
private func configureBuildConfigurationSettings() {
run(rubyFileAt: newFrameworkPath,
function: "configure_build_configuration_settings",
parameters: name
)
}
} |
//
// HomeViewController + UITableView.swift
// BeeHive
//
// Created by HyperDesign-Gehad on 1/29/19.
// Copyright © 2019 HyperDesign-Gehad. All rights reserved.
//
import UIKit
extension HomeViewController : UITableViewDelegate,UITableViewDataSource{
func setTableDelegateAndDataSource(){
usersTableView.delegate = self
usersTableView.dataSource = self
usersTableView.register(UINib(nibName: "UserTableViewCell", bundle: nil), forCellReuseIdentifier: "userCell")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if segmentedView.selectedSegmentIndex == 0 {
return nearUsersArray.count
}else{
return nearPlacesArray.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath) as! UserTableViewCell
if segmentedView.selectedSegmentIndex == 0 {
cell.config(user: nearUsersArray[indexPath.row].user!)
}else{
cell.config(place: nearPlacesArray[indexPath.row])
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let isActive = self.checkUserActivation()
if isActive{
if segmentedView.selectedSegmentIndex == 0{
guard let id = nearUsersArray[indexPath.row].user?.id else {return}
self.openOtherController(fromStoryboard: "OtherUserProfile", withIdentifier: "otherUserProfileID", completion: {(controller) in
if let controller = controller as? OtherUserProfileViewController{
controller.anotherUserId = id
}
})
}else{
let selectedPlaceID = nearPlacesArray[indexPath.row].id
self.openOtherController(fromStoryboard: "Place", withIdentifier: "PlaceID", completion: {(controller) in
if let controller = controller as? PlaceViewController{
controller.placeID = selectedPlaceID
}
})
}
}
}
}
|
//
// CustomDatePicker.swift
// Animal House
//
// Created by Roy Geagea on 8/10/19.
// Copyright © 2019 Roy Geagea. All rights reserved.
//
import SwiftUI
struct CustomDatePicker: View {
var dateFormatter: DateFormatter {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter
}
@Binding var birthDate: Date
var body: some View {
VStack {
DatePicker(selection: $birthDate, displayedComponents: .date) {
Text("")
}
}
}
}
//#if DEBUG
//struct CustomDatePicker_Previews: PreviewProvider {
//
// static var previews: some View {
// CustomDatePicker(birthDate: $date)
// }
//}
//#endif
|
import UIKit
class SectionHeaderViewCell: UITableViewCell {
static let cellIdentifier = "SectionHeaderViewCell"
@IBOutlet weak var titleLabel: UILabel!
func configureWithTitle(title: String) {
self.titleLabel.text = title.uppercased()
}
}
|
struct ExportCompliance {
}
|
import SemanticVersion
import XCTest
import XCTestExtensions
@testable import Bundles
final class BundlesTests: XCTestCase {
/// Bundle to use for resource loading tests
var bundle: Bundle { Bundle(url: testURL(named: "Test", withExtension: "bundle"))! }
func testStringResource() {
XCTAssertEqual(bundle.stringResource(named: "Test"), "String contents.")
}
func testDataResource() {
if UserDefaults.standard.bool(forKey: "rewriteTestData") {
let url = bundle.bundleURL.appendingPathComponent("Test.data")
try! "String contents.".data(using: .utf8)!.write(to: url)
} else {
let data = bundle.dataResource(named: "Test")
let string = String(data: data, encoding: .utf8)
XCTAssertEqual(string, "String contents.")
}
}
func testJSONResource() {
let json: [String] = bundle.jsonResource(named: "Test")
XCTAssertEqual(json, ["item 1", "item 2"])
}
func testDecodableResource() {
struct Test: Decodable {
let name: String
let description: String
}
let data = bundle.decodeResource(Test.self, named: "Decodable")
XCTAssertEqual(data.name, "Test")
XCTAssertEqual(data.description, "Some test data")
}
func testInfoFromBundle() {
let info = BundleInfo(for: bundle)
XCTAssertEqual(info.name, "Name")
XCTAssertEqual(info.id, "Identifier")
XCTAssertEqual(info.build, 1234)
XCTAssertEqual(info.version, SemanticVersion("1.2.3"))
XCTAssertEqual(info.commit, "Commit")
XCTAssertEqual(info.executable, "Executable")
XCTAssertEqual(info.copyright, "Copyright")
}
func testInfoFromConstructor() {
let info = BundleInfo(name: "Name", id: "Identifier", executable: "Executable", build: 1234, version: "1.2.3", commit: "Commit", copyright: "Copyright")
XCTAssertEqual(info.name, "Name")
XCTAssertEqual(info.id, "Identifier")
XCTAssertEqual(info.build, 1234)
XCTAssertEqual(info.version, SemanticVersion("1.2.3"))
XCTAssertEqual(info.commit, "Commit")
XCTAssertEqual(info.executable, "Executable")
XCTAssertEqual(info.copyright, "Copyright")
}
}
|
//
// GQiuBaiViewModel.swift
// Girls
//
// Created by 张如泉 on 16/3/29.
// Copyright © 2016年 quange. All rights reserved.
//
import ReactiveViewModel
import ReactiveCocoa
class GQiuBaiViewModel: RVMViewModel {
var qiubaiModels :NSMutableArray?
override init() {
super.init()
self.qiubaiModels = []
}
func fetchQiuBaiData(_ more: Bool)->RACSignal{
let page = !more ? 1 : ((self.qiubaiModels!.count - self.qiubaiModels!.count%40 )/40+(self.qiubaiModels!.count%40 == 0 ? 1 : 2))
//let gifDuration = more ? 1 : 0
return GAPIManager.sharedInstance.fetchQiuBaiHot(page).map({ (result) -> AnyObject! in
if !more {
self.qiubaiModels?.removeAllObjects()
}
self.qiubaiModels?.addObjectsFromArray(result as! [AnyObject])
return result
})
}
func numOfItems()->Int{
return (qiubaiModels?.count)!
}
func contentOfRow(_ row:Int)->String{
let model = qiubaiModels![row] as! GQiuBaiModel
return model.content!
}
func typeOfRow(_ row:Int)->String
{
let model = qiubaiModels![row] as! GQiuBaiModel
return model.format!
}
func imageUrlOfRow(_ row:Int)->String
{
let model = qiubaiModels![row] as! GQiuBaiModel
if model.format == "image"
{
let imageId = model.modelId!.stringValue as NSString
let prefiximageId = imageId.substring(to: imageId.length - 4)
//imagURL = "http://pic.qiushibaike.com/system/pictures/\(prefiximageId)/\(imageId)/small/\(model.image)"
let image = model.image! as NSString
let url = "http://pic.qiushibaike.com/system/pictures/\(prefiximageId)/\(imageId)/medium/\(image)"
return url
} else if model.format == "video"
{
return model.pic_url!
}
return ""
}
func imageHeightOfRow(_ row:Int)->CGFloat
{
let model = qiubaiModels![row] as! GQiuBaiModel
if model.format == "image"
{
let size = model.imageSize! as NSDictionary
let sizeInfo = size["m"] as! NSArray
let hw = (sizeInfo.object(at: 1) as AnyObject).floatValue/(sizeInfo.object(at: 0) as AnyObject).floatValue
let h = (UIScreen.main.bounds.width - 16.0) * CGFloat(hw)
return h
} else if model.format == "video"
{
let h = UIScreen.main.bounds.width - 16.0
return h
}
return 0
}
func userIcon(_ row:Int)->String
{
let model = qiubaiModels![row] as! GQiuBaiModel
if model.user == nil
{
return ""
}
let userInfor = model.user! as NSDictionary
let icon = userInfor["icon"] as! NSString
let idNumber = userInfor["id"] as? NSNumber
let userId = idNumber!.stringValue as NSString
let prefixUserId = userId.substring(to: userId.length - 4)
let userImageURL = "http://pic.qiushibaike.com/system/avtnew/\(prefixUserId)/\(userId)/medium/\(icon)"
return userImageURL
}
func userNickName(_ row:Int)->String
{
let model = qiubaiModels![row] as! GQiuBaiModel
let userInfor = model.user! as NSDictionary
return userInfor["login"] as! String
}
}
|
//
// EightViewController.swift
// FYSliderView
//
// Created by 武飞跃 on 16/10/21.
// Copyright © 2016年 武飞跃. All rights reserved.
//
import UIKit
class EightViewController: Base2VC,FYSliderViewCustomizable {
var sliderView:FYSliderView!
override func viewDidLoad() {
super.viewDidLoad()
//获取网络数据
getData { (data) in
let dic = try! NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
let dataSource = dic["data"] as! [[String:String]]
self.sliderView.imageObjectGroup = dataSource.map({ dic in
return FYImageObject(url: nil, title: dic["banner_title"])
})
}
//初始化轮播图
sliderView = FYSliderView(frame: CGRect(x: 0, y: 64, width: view.bounds.size.width, height: 40),option:self)
view.addSubview(sliderView)
}
//MARK: - FYSliderView配置信息
var scrollDirection: UICollectionViewScrollDirection{
return .Vertical
}
var titleStyle: FYTitleStyle{
return [.textColor(UIColor.blackColor()),.labelHeight(40)]
}
var controlType: FYPageControlType{
return .none
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// NoteStruct.swift
// Swingle
//
// Created by 藤井陽介 on 2016/09/01.
// Copyright © 2016年 touyou. All rights reserved.
//
import Foundation
import Himotoki
// MARK: - Notes
public struct Notes {
public var notes: [Note]?
}
extension Notes: Decodable {
public static func decode(_ e: Extractor) throws -> Notes {
return try Notes(
notes: e <||? "notes"
)
}
}
// MARK: - Note
public struct Note {
public var index: Int
public var start: UInt64
public var duration: UInt64
public var pitch: Double
public var number: Int
}
extension Note: Decodable {
public static func decode(_ e: Extractor) throws -> Note {
return try Note(
index: e <| "index",
start: e <| "start",
duration: e <| "duration",
pitch: e <| "pitch",
number: e <| "number"
)
}
}
|
//
// Item.swift
// RealmTodoListApp
//
// Created by shin seunghyun on 2020/02/20.
// Copyright © 2020 shin seunghyun. All rights reserved.
//
import RealmSwift
class Item: Object {
@objc dynamic var title: String = ""
@objc dynamic var done: Bool = false
@objc dynamic var dateCreated: Date?
var parentCategory: LinkingObjects = LinkingObjects(fromType: Category.self, property: "items")
}
|
//
// TaskList.swift
// TaskMan
//
// Created by Luiz Fernando Silva on 05/12/16.
// Copyright © 2016 Luiz Fernando Silva. All rights reserved.
//
import Cocoa
import SwiftyJSON
/// Describes a collection of tasks.
/// Used mostly to store tasks and associated segments to a persistency interface.
struct TaskList {
/// List of tasks
var tasks: [Task] = []
/// List of task segments registered for the tasks above
var taskSegments: [TaskSegment] = []
init(tasks: [Task] = [], taskSegments: [TaskSegment] = []) {
self.tasks = tasks
self.taskSegments = taskSegments
}
}
// MARK: Json
extension TaskList: JsonInitializable, JsonSerializable {
init(json: JSON) throws {
try tasks = json[JsonKey.tasks].tryParseModels()
try taskSegments = json[JsonKey.taskSegments].tryParseModels()
}
func serialize() -> JSON {
var dict: [JsonKey: Any] = [:]
dict[.tasks] = tasks.jsonSerialize().map { $0.object }
dict[.taskSegments] = taskSegments.jsonSerialize().map { $0.object }
return dict.mapToJSON()
}
}
extension TaskList {
/// Inner enum containing the JSON key names for the model
enum JsonKey: String, JSONSubscriptType {
case tasks
case taskSegments = "task_segments"
var jsonKey: JSONKey {
return JSONKey.key(self.rawValue)
}
}
}
|
//
// ServiceLifecycle.swift
// Schuylkill-App
//
// Created by Sam Hicks on 3/13/21.
//
import Foundation
protocol ServiceLifecycle {
var state: ServiceState? { get set }
func start()
func pause()
func restart()
func terminate()
}
|
//
// MainMovieVC.swift
// MovieTest
//
// Created by Rydus on 18/04/2019.
// Copyright © 2019 Rydus. All rights reserved.
//
import UIKit
import AVKit
import AVFoundation
import XCDYouTubeKit
class MainMovieVC: BaseVC, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: MySearchBar!
var jsonArray : [MainMovieModel] = []
var isLandscape:Bool = false
var width = CGFloat()
var height = CGFloat()
// VC Lifecycle
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated);
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear), name: UIResponder.keyboardWillHideNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear), name: UIResponder.keyboardWillShowNotification, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
width = UI.getScreenSize().width
height = UI.getScreenSize().height
if(isNetAvailable) { // normal
WSRequest();
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
width = size.width
height = size.height
if !UIDevice.current.orientation.isPortrait {
Common.Log(str: "Landscape")
isLandscape = true
} else {
Common.Log(str: "Portrait")
isLandscape = false
}
}
// MARK: Keyboard Notifications Selectors
@objc func keyboardWillAppear(_ notification: Notification) {
//Do something here
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
searchBar.frame = CGRect(x: 0, y: UI.getScreenSize().height - (keyboardHeight + searchBar.frame.size.height), width: width, height: searchBar.frame.size.height)
}
}
@objc func keyboardWillDisappear(_ notification: Notification) {
//Do something here
searchBar.frame = CGRect(x: 0, y: UI.getScreenSize().height - searchBar.frame.size.height, width: width, height: searchBar.frame.size.height)
}
// MARK: WS
func WSRequest() {
HttpMgr.shared.get(uri: Server.API_MOVIE_DB_URL) { (json) in
let results = json["results"]
if results.count > 0 {
self.jsonArray.removeAll()
for arr in results.arrayValue {
self.jsonArray.append(MainMovieModel(json: arr))
}
DispatchQueue.main.async {
self.searchBar.isHidden = false
self.tableView.reloadData()
}
}
else {
DispatchQueue.main.async {
Common.Log(str: "No Result Found")
self.searchBar.isHidden = true
self.showAlert(msg: "Sorry, movie result not found")
}
}
};
}
// MARK: TableView Delegates
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.jsonArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:MainMovieCell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! MainMovieCell
//Common.Log(str: self.jsonArray[indexPath.row].poster_path)
cell.avator.kf.setImage(with: URL(string:String(format:"%@%@",Server.API_POSTER_IMAGE_URL, self.jsonArray[indexPath.row].poster_path)), options: [
.transition(.fade(1)),
.cacheOriginalImage
])
let title = self.jsonArray[indexPath.row].title
cell.title.tag = self.jsonArray[indexPath.row].id
cell.title.text = title
cell.title.addTapGestureRecognizer {
Common.Log(str: String(format:"title tapped at index = %i",cell.title.tag))
if(self.isNetAvailable) {
DispatchQueue.main.async {
if let vc = self.storyboard!.instantiateViewController(withIdentifier: "DetailMovieVC") as? DetailMovieVC {
vc.movie_id = cell.title.tag
vc.width = self.width
vc.height = self.height
self.navigationController!.pushViewController(vc, animated: true)
}
}
}
}
cell.backgroundColor = .clear
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
UIView.animate(withDuration: 0.5) {
cell.transform = CGAffineTransform.identity
}
}
/*func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
Common.Log(str: "You tapped cell number \(indexPath.row).")
let vc = storyboard!.instantiateViewController(withIdentifier: "DetailMovieVC") as! DetailMovieVC
vc.dicDetails = self.jsonArray[indexPath.row] as! NSDictionary
self.navigationController!.pushViewController(vc, animated: true)
}*/
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
let cell:MainMovieCell = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! MainMovieCell
return cell.frame.size.height
// Tried to control view height in every devices
/*var h = CGFloat(getScreenSize().height*20/100)
switch(UIDevice.current.userInterfaceIdiom) {
case .phone:
if(isLandscape) {
h = CGFloat(getScreenSize().width*20/100)
}
else {
h = CGFloat(getScreenSize().height*18/100)
}
break;
case .pad:
if(isLandscape) {
h = CGFloat(getScreenSize().width*25/100)
}
else {
h = CGFloat(getScreenSize().height*22/100)
}
break;
case .unspecified:
break;
case .tv:
break;
case .carPlay:
break;
}
return h*/
}
// MARK: Searchbar delegates
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
Common.Log(str: searchBar.text!)
searchBar.resignFirstResponder()
if let keywords = searchBar.text {
if keywords.count > 0 {
// high order function e.g sort, map, filter, reduce here i 've used filter to bring start with result from title
let searchResults = MainMovieParser.getTitleMovie(keyword: keywords, model: self.jsonArray)
if searchResults.count > 0 {
self.jsonArray = searchResults
Common.Log(str: self.jsonArray.description)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
else {
self.showAlert(msg: "Sorry, your search record not found")
}
}
else {
// normal to get all data from coredb
WSRequest();
}
}
}
}
|
//
// CertificateViewController.swift
// FruitSchool
//
// Created by Presto on 29/09/2018.
// Copyright © 2018 YAPP. All rights reserved.
//
import UIKit
import SVProgressHUD
class CertificateViewController: UIViewController {
private lazy var dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "ko_KR")
dateFormatter.dateFormat = "yyyy.MM.dd"
return dateFormatter
}()
private var nickname: String {
return nicknameTextField.text ?? ""
}
@IBOutlet private weak var backgroundView: UIView! {
didSet {
backgroundView.layer.cornerRadius = 13
}
}
@IBOutlet private weak var nicknameTextField: UITextField!
@IBOutlet private weak var dateLabel: UILabel! {
didSet {
dateLabel.text = dateFormatter.string(from: Date())
}
}
@IBOutlet private weak var startButton: UIButton! {
didSet {
startButton.addTarget(self, action: #selector(touchUpStartButton(_:)), for: .touchUpInside)
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if deviceModel == .iPad {
NSLayoutConstraint.activate([
backgroundView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
backgroundView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
backgroundView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.63),
backgroundView.widthAnchor.constraint(equalTo: backgroundView.heightAnchor, multiplier: 270 / 422)
])
} else {
NSLayoutConstraint.activate([
backgroundView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
backgroundView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
backgroundView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.63),
backgroundView.heightAnchor.constraint(equalTo: backgroundView.widthAnchor, multiplier: 422 / 270)
])
}
view.layoutIfNeeded()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
nicknameTextField.becomeFirstResponder()
}
@objc private func touchUpStartButton(_ sender: UIButton) {
if nickname.isEmpty {
UIAlertController
.alert(title: "", message: "닉네임을 입력하세요.")
.action(title: "확인")
.present(to: self)
return
}
guard let next = UIViewController.instantiate(storyboard: "Book", identifier: "BookNavigationController") else { return }
SVProgressHUD.show()
API.requestFruitList { response, _, error in
if let error = error {
DispatchQueue.main.async {
UIAlertController.presentErrorAlert(to: next, error: error.localizedDescription)
}
return
}
guard let response = response else { return }
for data in response.data {
ChapterRecord.add(id: data.id, title: data.title, english: data.english, grade: data.grade)
}
DispatchQueue.main.async {
SVProgressHUD.dismiss()
UserRecord.add(nickname: self.nickname)
let splitViewController = UISplitViewController()
let master = UIViewController.instantiate(storyboard: "Book", identifier: "BookNavigationController") ?? UIViewController()
let detail = UIViewController.instantiate(storyboard: "Book", identifier: DummyDetailNavigationController.classNameToString) ?? UIViewController()
splitViewController.viewControllers = [master, detail]
splitViewController.modalTransitionStyle = .crossDissolve
self.present(splitViewController, animated: true, completion: nil)
}
}
}
}
extension CertificateViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
|
//
// LocationService.swift
// WeatherApp
//
// Created by Konada on 11/11/16.
// Copyright © 2016 Konada. All rights reserved.
//
import Foundation
import CoreLocation
protocol LocationServiceDelegate {
func tracingLocation(_ currentLocation: CLLocation)
func tracingLocationDidFailWithError(_ error: NSError)
}
class LocationService: NSObject, CLLocationManagerDelegate {
static let sharedInstance: LocationService = {
let instance = LocationService()
return instance
}()
var locationManager: CLLocationManager?
var currentLocation: CLLocation?
var delegate: LocationServiceDelegate?
override init() {
super.init()
self.locationManager = CLLocationManager()
guard let locationManager = self.locationManager else {
return
}
if CLLocationManager.authorizationStatus() == .notDetermined {
locationManager.requestWhenInUseAuthorization()
}
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.distanceFilter = 200
locationManager.delegate = self
}
func startUpdatingLocation() {
print("Starting Location Updates")
self.locationManager?.startUpdatingLocation()
}
func stopUpdatingLocation() {
print("Stop Location Updates")
self.locationManager?.stopUpdatingLocation()
}
// CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else {
return
}
// singleton for get last(current) location
currentLocation = location
// use for real time update location
updateLocation(location)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
// do on error
updateLocationDidFailWithError(error as NSError)
}
func formattedLat() -> String{
return String.localizedStringWithFormat("%.2f", (locationManager!.location?.coordinate.latitude)!)
}
func formattedLon() -> String{
return String.localizedStringWithFormat("%.2f",(locationManager!.location?.coordinate.longitude)!)
}
// Private function
fileprivate func updateLocation(_ currentLocation: CLLocation){
guard let delegate = self.delegate else {
return
}
delegate.tracingLocation(currentLocation)
}
fileprivate func updateLocationDidFailWithError(_ error: NSError) {
guard let delegate = self.delegate else {
return
}
delegate.tracingLocationDidFailWithError(error)
}
}
|
//
// NYC_HS_SATTests.swift
// NYC HS SATTests
//
// Created by C4Q on 3/9/18.
// Copyright © 2018 basedOnTy. All rights reserved.
//
import XCTest
@testable import NYC_HS_SAT
class NYC_HS_SATTests: XCTestCase {
var sessionUnderTest: URLSession!
override func setUp() {
super.setUp()
sessionUnderTest = URLSession(configuration: URLSessionConfiguration.default)
}
override func tearDown() {
sessionUnderTest = nil
super.tearDown()
}
func testCallToNYCOpenDataSATScore() { // SAT API
let token = "9ubKuJcvrZbHBNOSLWvi1a7Ux"
let url = URL(string: "https://data.cityofnewyork.us/resource/734v-jeq5.json?&$$app_token=\(token)")
let promise = expectation(description: "Status code: 200")
let dataTask = sessionUnderTest.dataTask(with: url!) { data, response, error in
if let error = error {
XCTFail("Error: \(error.localizedDescription)")
return
} else if let statusCode = (response as? HTTPURLResponse)?.statusCode {
if statusCode == 200 {
promise.fulfill()
} else {
XCTFail("Status code: \(statusCode)")
}
}
}
dataTask.resume()
waitForExpectations(timeout: 10) { (error) in
XCTAssertNil(error, "Test timed out")
}
}
func testCallToNYCOpenDataAllHighSchools() { // Highschool API
let token = "9ubKuJcvrZbHBNOSLWvi1a7Ux"
let url = URL(string: "https://data.cityofnewyork.us/resource/97mf-9njv.json?&$$app_token=\(token)")
let promise = expectation(description: "Status code: 200")
let dataTask = sessionUnderTest.dataTask(with: url!) { data, response, error in
if let error = error {
XCTFail("Error: \(error.localizedDescription)")
return
} else if let statusCode = (response as? HTTPURLResponse)?.statusCode {
if statusCode == 200 {
promise.fulfill()
} else {
XCTFail("Status code: \(statusCode)")
}
}
}
dataTask.resume()
waitForExpectations(timeout: 10) { (error) in
XCTAssertNil(error, "Test timed out")
}
}
}
|
//
// SendTableViewCell.swift
// SOSVietnam
//
// Created by Ecko Huynh on 25/04/2020.
// Copyright © 2020 admin. All rights reserved.
//
import UIKit
class SendTableViewCell: UITableViewCell {
var callback: ((_ value: Void)->())?
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
}
@IBAction func sendClick(_ sender: Any) {
callback?(())
}
}
|
//
// SMFavoritesCell.swift
// Silly Monks
//
// Created by CX_One on 7/29/16.
// Copyright © 2016 Sarath. All rights reserved.
//
import UIKit
class SMFavoritesCell: UITableViewCell {
@IBOutlet weak var favouritesImageview: UIImageView!
@IBOutlet weak var favouritesTitleLabel: UILabel!
@IBOutlet weak var favouritesDetailTextView: UITextView!
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
}
}
|
//
// GameURLs.swift
// Hero Game Bot
//
// Created by Ilya Sysoi on 3/2/19.
// Copyright © 2019 Ilya Sysoi. All rights reserved.
//
import Foundation
enum GameURLsEnum {
static let base = URL(string: "http://g.meni.mobi/")!
static let login = URL(string: "http://g.meni.mobi/login")!
static let assignments = URL(string: "http://g.meni.mobi/game/assignments")!
static let game = URL(string: "http://g.meni.mobi/game")!
static let campaign = URL(string: "http://g.meni.mobi/game/campaign")!
static let battle = URL(string: "http://g.meni.mobi/game/battle/mercenary/new")!
}
|
//
// ProfileTableViewController.swift
// plizdoo
//
// Created by Matthieu Tournesac on 22/03/2015.
// Copyright (c) 2015 MatthieuTnsc. All rights reserved.
//
import UIKit
import MaterialKit
class ProfileTableViewController: UITableViewController {
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var infoLabel: UILabel!
@IBOutlet weak var receivedLabel: UILabel!
@IBOutlet weak var receivedAppIconSwitch: UISwitch!
@IBOutlet weak var sentLabel: UILabel!
@IBOutlet weak var sentAppIconSwitch: UISwitch!
@IBOutlet weak var syncFacebookButton: MKButton!
@IBOutlet weak var eulaLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.title = NSLocalizedString("PROFILE.TITLE", comment: "")
receivedLabel.text = NSLocalizedString("PROFILE.LABEL_RECEIVED", comment: "")
sentLabel.text = NSLocalizedString("PROFILE.LABEL_SENT", comment: "")
syncFacebookButton.setTitle(NSLocalizedString("PROFILE.BUTTON_SYNC", comment: ""), forState: UIControlState.Normal)
eulaLabel.text = NSLocalizedString("PROFILE.LABEL_EULA", comment: "")
receivedAppIconSwitch.addTarget(self, action: Selector("receivedAppIconSwitchStateChanged:"), forControlEvents: UIControlEvents.ValueChanged)
sentAppIconSwitch.addTarget(self, action: Selector("sentAppIconSwitchStateChanged:"), forControlEvents: UIControlEvents.ValueChanged)
if NSUserDefaults.standardUserDefaults().boolForKey("received_badge_app_icon") == true {
self.receivedAppIconSwitch.setOn(true, animated: false)
} else {
self.receivedAppIconSwitch.setOn(false, animated: false)
}
if NSUserDefaults.standardUserDefaults().boolForKey("sent_badge_app_icon") {
sentAppIconSwitch.setOn(true, animated: true)
} else {
self.sentAppIconSwitch.setOn(false, animated: true)
}
nameLabel.text = String(PFUser.currentUser()!["first_name"] as! String) + " " + String(PFUser.currentUser()!["last_name"] as! String)
self.profileImageView.layer.cornerRadius = 10.0
self.profileImageView.clipsToBounds = true
// Check our image cache for the existing key. This is just a dictionary of UIImages
var facebook_id = PFUser.currentUser()!["facebook_id"] as! String
var profile_pic:UIImage? = imageCache[facebook_id]
if profile_pic == nil {
// If the image does not exist, we need to download it
Brain().convertUrlToImage(facebook_id, completion: { (success, error) -> Void in
if success == true {
dispatch_async(dispatch_get_main_queue(), {
self.profileImageView.image = imageCache[facebook_id]
})
} else {
println(error)
}
})
} else {
dispatch_async(dispatch_get_main_queue(), {
self.profileImageView.image = imageCache[facebook_id]
})
}
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var sectionName:String = ""
switch (section)
{
case 0:
sectionName = NSLocalizedString("PROFILE.SECTION_NAME", comment: "")
break
case 1:
sectionName = NSLocalizedString("PROFILE.SECTION_BADGE", comment: "")
break
case 2:
sectionName = NSLocalizedString("PROFILE.SECTION_FB", comment: "")
break
case 3:
sectionName = NSLocalizedString("PROFILE.SECTION_INFO", comment: "")
break
default:
break
}
return sectionName;
}
func receivedAppIconSwitchStateChanged(switchState: UISwitch) {
if switchState.on {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "received_badge_app_icon")
} else {
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "received_badge_app_icon")
}
NSNotificationCenter.defaultCenter().postNotificationName(updateReceivedBadgeNotificationKey, object: self)
}
func sentAppIconSwitchStateChanged(switchState: UISwitch) {
if switchState.on {
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "sent_badge_app_icon")
} else {
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "sent_badge_app_icon")
}
NSNotificationCenter.defaultCenter().postNotificationName(updateSentBadgeNotificationKey, object: self)
}
@IBAction func logout(sender: AnyObject) {
PFObject.unpinAllObjectsInBackgroundWithName("ToMe")
NSUserDefaults.standardUserDefaults().removeObjectForKey("lastUpdateToMe")
PFObject.unpinAllObjectsInBackgroundWithName("FromMe")
NSUserDefaults.standardUserDefaults().removeObjectForKey("lastUpdateFromMe")
PFObject.unpinAllObjectsInBackgroundWithName("Friends")
NSUserDefaults.standardUserDefaults().removeObjectForKey("lastUpdateFriends")
PFObject.unpinAllObjectsInBackgroundWithName("Friend")
// Update app badge
var badgeValue:NSInteger = UIApplication.sharedApplication().applicationIconBadgeNumber
badgeValue = 0
var currentInstallation:PFInstallation = PFInstallation.currentInstallation()
currentInstallation.badge = badgeValue
currentInstallation.saveEventually()
PFUser.logOut()
// Show the login screen
let loginViewController = self.storyboard?.instantiateViewControllerWithIdentifier("LoginViewController") as! UIViewController
self.presentViewController(loginViewController, animated: true, completion: nil)
}
@IBAction func syncFacebookFriends(sender: AnyObject) {
KVNProgress.show()
Brain().syncFacebookFriends { (success, error) -> Void in
if success == true {
KVNProgress.showSuccess()
} else {
KVNProgress.showErrorWithStatus(error)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// Layout.swift
// NiceLayout
//
// Created by Adam Shin on 3/2/20.
// Copyright © 2020 Adam Shin. All rights reserved.
//
import UIKit
// MARK: - Superview Target
public enum LayoutSuperviewTarget {
case `super`
case margins
case readableContent
@available(iOS 11.0, *) case safeArea
}
// MARK: - Relation Operators
public struct LayoutRelationProxy { }
public typealias LayoutRelationOperator =
(LayoutRelationProxy, LayoutRelationProxy)
-> NSLayoutConstraint.Relation
public func == (a: LayoutRelationProxy, b: LayoutRelationProxy)
-> NSLayoutConstraint.Relation {
return .equal
}
public func <= (a: LayoutRelationProxy, b: LayoutRelationProxy)
-> NSLayoutConstraint.Relation {
return .lessThanOrEqual
}
public func >= (a: LayoutRelationProxy, b: LayoutRelationProxy)
-> NSLayoutConstraint.Relation {
return .greaterThanOrEqual
}
|
//
// ConditionViewModel.swift
// BondStudy
//
// Created by DaichiSaito on 2017/02/02.
// Copyright © 2017年 DaichiSaito. All rights reserved.
//
import Foundation
import Bond
import Alamofire
import SwiftyJSON
class ConditionViewModel: NSObject {
var conditions = MutableObservableArray<Condition>([Condition]())
// let nails = MutableObservableArray<Nail>()
// func request2() {
// // 本来はこれはuserDefaultからとってくる
// let value: [String: Any] = [
// "tops": [
// "colors":["1","2","3"],
// "brands":["ナイキ","アディダス","プーマ"]
// ],
// "pants": [
// "colors":["1","2","3"],
// "brands":["ナイキ","アディダス","プーマ"]
// ],
// "outer": [
// "colors":["1","2","3"],
// "brands":["ナイキ","アディダス","プーマ"]
// ],
// "shose": [
// "colors":["1","2","3"],
// "brands":["ナイキ","アディダス","プーマ"]
// ],
// "hat": [
// "colors":["1","2","3"],
// "brands":["ナイキ","アディダス","プーマ"]
// ],
// "neck": [
// "colors":["1","2","3"],
// "brands":["ナイキ","アディダス","プーマ"]
// ]
// ]
// let json = JSON(value)
// print(json)
// for (_, subJson) in json {
// let condition = Condition(json: subJson)
// self.conditions.append(condition)
// }
//
// }
func getCondition() {
let condition = UserDefaults.standard.object(forKey: "CONDITION")
// let condition = UserDefaults.standard.object(forKey: "CONDITION2")
if let condition = condition {
let json = JSON(condition)
for (key, subJson) in json {
// print(key)// item,tagとか
if key == "item" {
// itemの場合はネストされているのでさらにfor文で回す
for (key, subsubJson) in subJson {
if key == "season" {
// seasonの場合は
continue
}
// print(key)
let condition = Condition(json: subsubJson, key: key)
self.conditions.append(condition)
}
}
}
// viewModel.conditions = condition
} else {
print("なんもないよー")
}
}
}
|
//
// NSDate-Extension.swift
// TV_Show
//
// Created by 郑娇鸿 on 17/3/4.
// Copyright © 2017年 郑娇鸿. All rights reserved.
//
import Foundation
|
//
// Copyright © 2020 Tasuku Tozawa. All rights reserved.
//
import Nimble
import Quick
import Domain
@testable import Persistence
class TemporaryImageStorageSpec: QuickSpec {
static let testDirectory = FileManager.default.temporaryDirectory
.appendingPathComponent("TemporaryImageStorageSpec", isDirectory: true)
static let testDirectory2 = FileManager.default.temporaryDirectory
.appendingPathComponent("TemporaryImageStorageSpec2", isDirectory: true)
static let config = TemporaryImageStorage.Configuration(targetUrl: TemporaryImageStorageSpec.testDirectory)
override func spec() {
var storage: TemporaryImageStorage!
let sampleImage = UIImage(named: "SampleImageBlack", in: Bundle(for: Self.self), with: nil)!
let sampleClipId = UUID(uuidString: "E621E1F8-C36C-495A-93FC-0C247A3E6111")!
let expectedClipDirectoryUrl = Self.testDirectory
.appendingPathComponent("E621E1F8-C36C-495A-93FC-0C247A3E6111", isDirectory: true)
beforeSuite {
if FileManager.default.fileExists(atPath: Self.testDirectory.path) {
try! FileManager.default.removeItem(at: Self.testDirectory)
}
if FileManager.default.fileExists(atPath: Self.testDirectory2.path) {
try! FileManager.default.removeItem(at: Self.testDirectory2)
try! FileManager.default.createDirectory(at: Self.testDirectory2, withIntermediateDirectories: true, attributes: nil)
} else {
try! FileManager.default.createDirectory(at: Self.testDirectory2, withIntermediateDirectories: true, attributes: nil)
}
}
afterSuite {
try! FileManager.default.removeItem(at: Self.testDirectory)
try! FileManager.default.removeItem(at: Self.testDirectory2)
}
describe("init") {
beforeEach {
storage = try! TemporaryImageStorage(configuration: Self.config, fileManager: FileManager.default)
}
it("画像保存用のディレクトリが作成されている") {
expect(FileManager.default.fileExists(atPath: Self.testDirectory.path)).to(beTrue())
}
}
describe("imageFileExists(named:inClipHaving:)") {
context("画像が存在する") {
beforeEach {
storage = try! TemporaryImageStorage(configuration: Self.config, fileManager: FileManager.default)
try! storage.save(sampleImage.pngData()!, asName: "hogehoge.png", inClipHaving: sampleClipId)
}
afterEach {
try! FileManager.default.removeItem(at: expectedClipDirectoryUrl)
}
it("trueが返る") {
expect(storage.imageFileExists(named: "hogehoge.png", inClipHaving: sampleClipId)).to(beTrue())
}
}
context("存在しない画像を読み込む") {
beforeEach {
storage = try! TemporaryImageStorage(configuration: Self.config, fileManager: FileManager.default)
}
it("falseが返る") {
expect(storage.imageFileExists(named: "hogehoge.png", inClipHaving: sampleClipId)).to(beFalse())
}
}
}
describe("save(_:asName:inClipHaving:)") {
context("新しいクリップに画像を保存する") {
beforeEach {
storage = try! TemporaryImageStorage(configuration: Self.config, fileManager: FileManager.default)
try! storage.save(sampleImage.pngData()!, asName: "hogehoge.png", inClipHaving: sampleClipId)
}
afterEach {
try! FileManager.default.removeItem(at: expectedClipDirectoryUrl)
}
it("クリップ用のディレクトリが作成されている") {
expect(FileManager.default.fileExists(atPath: expectedClipDirectoryUrl.path)).to(beTrue())
}
it("画像が保存されている") {
let imagePath = expectedClipDirectoryUrl
.appendingPathComponent("hogehoge.png", isDirectory: false)
.path
expect(FileManager.default.fileExists(atPath: imagePath)).to(beTrue())
}
}
context("既存のクリップに画像を保存する") {
beforeEach {
storage = try! TemporaryImageStorage(configuration: Self.config, fileManager: FileManager.default)
try! storage.save(sampleImage.pngData()!, asName: "hogehoge.png", inClipHaving: sampleClipId)
try! storage.save(sampleImage.pngData()!, asName: "fugafuga.png", inClipHaving: sampleClipId)
}
afterEach {
try! FileManager.default.removeItem(at: expectedClipDirectoryUrl)
}
it("クリップ用のディレクトリが作成されている") {
expect(FileManager.default.fileExists(atPath: expectedClipDirectoryUrl.path)).to(beTrue())
}
it("画像が保存されている") {
let firstImagePath = expectedClipDirectoryUrl
.appendingPathComponent("hogehoge.png", isDirectory: false)
.path
let secondImagePath = expectedClipDirectoryUrl
.appendingPathComponent("hogehoge.png", isDirectory: false)
.path
expect(FileManager.default.fileExists(atPath: firstImagePath)).to(beTrue())
expect(FileManager.default.fileExists(atPath: secondImagePath)).to(beTrue())
}
}
context("重複して画像を保存する") {
beforeEach {
storage = try! TemporaryImageStorage(configuration: Self.config, fileManager: FileManager.default)
try! storage.save(sampleImage.pngData()!, asName: "hogehoge.png", inClipHaving: sampleClipId)
try! storage.save(sampleImage.pngData()!, asName: "hogehoge.png", inClipHaving: sampleClipId)
}
afterEach {
try! FileManager.default.removeItem(at: expectedClipDirectoryUrl)
}
it("クリップ用のディレクトリが作成されている") {
expect(FileManager.default.fileExists(atPath: expectedClipDirectoryUrl.path)).to(beTrue())
}
it("画像が保存されている") {
let imagePath = expectedClipDirectoryUrl
.appendingPathComponent("hogehoge.png", isDirectory: false)
.path
expect(FileManager.default.fileExists(atPath: imagePath)).to(beTrue())
}
}
}
describe("delete(fileName:inClipHaving:)") {
context("クリップに複数存在するうちの1つの画像を削除する") {
beforeEach {
storage = try! TemporaryImageStorage(configuration: Self.config, fileManager: FileManager.default)
try! storage.save(sampleImage.pngData()!, asName: "hogehoge.png", inClipHaving: sampleClipId)
try! storage.save(sampleImage.pngData()!, asName: "fugafuga.png", inClipHaving: sampleClipId)
try! storage.delete(fileName: "hogehoge.png", inClipHaving: sampleClipId)
}
afterEach {
try! FileManager.default.removeItem(at: expectedClipDirectoryUrl)
}
it("クリップ用のディレクトリが削除されていない") {
expect(FileManager.default.fileExists(atPath: expectedClipDirectoryUrl.path)).to(beTrue())
}
it("指定した画像が削除されている") {
let firstImagePath = expectedClipDirectoryUrl
.appendingPathComponent("hogehoge.png", isDirectory: false)
.path
let secondImagePath = expectedClipDirectoryUrl
.appendingPathComponent("fugafuga.png", isDirectory: false)
.path
expect(FileManager.default.fileExists(atPath: firstImagePath)).to(beFalse())
expect(FileManager.default.fileExists(atPath: secondImagePath)).to(beTrue())
}
}
context("クリップの最後の1枚の画像を削除する") {
beforeEach {
storage = try! TemporaryImageStorage(configuration: Self.config, fileManager: FileManager.default)
try! storage.save(sampleImage.pngData()!, asName: "hogehoge.png", inClipHaving: sampleClipId)
try! storage.delete(fileName: "hogehoge.png", inClipHaving: sampleClipId)
}
it("クリップ用のディレクトリが削除されている") {
expect(FileManager.default.fileExists(atPath: expectedClipDirectoryUrl.path)).to(beFalse())
}
}
context("存在しない画像を削除する") {
beforeEach {
storage = try! TemporaryImageStorage(configuration: Self.config, fileManager: FileManager.default)
}
it("何も起きない") {
expect({
try storage.delete(fileName: "hogehoge.png", inClipHaving: sampleClipId)
}).notTo(throwError())
}
}
}
describe("deleteAll()") {
// TODO:
}
describe("readImage(named:inClipHaving:)") {
var data: Data!
context("存在する画像を読み込む") {
beforeEach {
storage = try! TemporaryImageStorage(configuration: Self.config, fileManager: FileManager.default)
try! storage.save(sampleImage.pngData()!, asName: "hogehoge.png", inClipHaving: sampleClipId)
data = try! storage.readImage(named: "hogehoge.png", inClipHaving: sampleClipId)
}
afterEach {
try! FileManager.default.removeItem(at: expectedClipDirectoryUrl)
}
it("画像データが読み込める") {
expect(data).notTo(beNil())
expect(data).to(equal(sampleImage.pngData()!))
}
}
context("存在しない画像を読み込む") {
beforeEach {
storage = try! TemporaryImageStorage(configuration: Self.config, fileManager: FileManager.default)
data = try! storage.readImage(named: "hogehoge.png", inClipHaving: sampleClipId)
}
it("nilが返る") {
expect(data).to(beNil())
}
}
}
}
}
|
//
// Portfolio+CoreDataClass.swift
// InvestingForAll
//
// Created by Christopher Lee on 4/15/20.
// Copyright © 2020 Christopher Lee. All rights reserved.
//
//
import Foundation
import CoreData
@objc(Portfolio)
public class Portfolio: NSManagedObject {
}
|
import UIKit
let testString = "haaacatt"
let range = NSRange(location: 0, length: testString.count)
let regex = try! NSRegularExpression(pattern: "[a-z][0-9]at")
print(regex.firstMatch(in: testString, options: [], range: range))
|
//
// Constants.swift
// Reached
//
// Created by John Wu on 2016-07-26.
// Copyright © 2016 ReachedTechnologies. All rights reserved.
//
import Foundation
import AWSCore
//facebook id of the user
var facebookId: String?
//user's information
var user = User()
//user's currently selected crowdlist
var crowdList = CrowdList()
//todays current events with information relevant to specific user
var events: Array<Event>? = Array<Event>()
//rewards corresponding to the user
var rewards: Array<Reward>? = Array<Reward>()
//list of reward id's corresponding to the user
var rewardList = RewardList()
//user's current news feed
var newsFeed = NewsFeed()
//all of the user's friends
var friends: Array<User>? = Array<User>()
//list of the user's friends facebook id's
var friendsList = FriendsList()
//dynamodb object mapper for accessing database
var dynamoDBObjectMapper = AWSDynamoDBObjectMapper.defaultDynamoDBObjectMapper()
//dynamodb query expression for making queries
var queryExpression = AWSDynamoDBScanExpression()
|
//
// ZBreadcrumbsController.swift
// Seriously
//
// Created by Jonathan Sand on 2/14/20.
// Copyright © 2020 Jonathan Sand. All rights reserved.
//
import Foundation
#if os(OSX)
import Cocoa
#elseif os(iOS)
import UIKit
#endif
var gBreadcrumbsController: ZBreadcrumbsController? { return gControllers.controllerForID(.idCrumbs) as? ZBreadcrumbsController }
class ZBreadcrumbsController: ZGenericController {
@IBOutlet var crumbsView : ZBreadcrumbsView?
override var controllerID : ZControllerID { return .idCrumbs }
override func handleSignal(_ iSignalObject: Any?, kind: ZSignalKind) {
crumbsView?.setupAndRedraw()
}
}
|
//
// OLDataSource.swift
// OpenLibrary
//
// Created by Bob Wakefield on 4/28/16.
// Copyright © 2016 Bob Wakefield. All rights reserved.
//
import Foundation
protocol OLDataSource {
func numberOfSections() -> Int
func numberOfRowsInSection( _ section: Int ) -> Int
// func objectAtIndexPath( indexPath: NSIndexPath ) -> OLManagedObject?
@discardableResult func displayToCell( _ cell: OLTableViewCell, indexPath: IndexPath ) -> OLManagedObject?
func updateUI() -> Void
func clearQuery() -> Void
}
|
import UIKit
let sync = SyncUpdate(periodic: 7)
class SyncUpdate {
private var lastSync: TimeInterval = 0
private var timer: Timer!
private var paused: Int = 1 // first start() will decrement
private var filterType: DateFilterKind
private var range: SQLiteRowRange? // written in reloadRangeFromDB()
/// `tsEarliest ?? 0`
private var tsMin: Timestamp { tsEarliest ?? 0 }
/// `(tsLatest + 1) ?? 0`
private var tsMax: Timestamp { (tsLatest ?? -1) + 1 }
/// Returns invalid range `(-1,-1)` if collection contains no rows
var rows: SQLiteRowRange { get { range ?? (-1,-1) } }
private(set) var tsEarliest: Timestamp? // as set per user, not actual earliest
private(set) var tsLatest: Timestamp? // as set per user, not actual latest
fileprivate init(periodic interval: TimeInterval) {
(filterType, tsEarliest, tsLatest) = Prefs.DateFilter.restrictions()
reloadRangeFromDB()
NotifyDateFilterChanged.observe(call: #selector(didChangeDateFilter), on: self)
timer = Timer.repeating(interval, call: #selector(periodicUpdate), on: self)
syncNow() // because timer will only fire after interval
}
/// Callback fired every `7` seconds.
@objc private func periodicUpdate() { if paused == 0 { syncNow() } }
/// Callback fired when user changes `DateFilter` on root tableView controller
@objc private func didChangeDateFilter() {
self.pause()
let filter = Prefs.DateFilter.restrictions()
filterType = filter.type
DispatchQueue.global().async {
// Not necessary, but improve execution order (delete then insert).
if self.tsMin <= (filter.earliest ?? 0) {
self.set(newEarliest: filter.earliest)
self.set(newLatest: filter.latest)
} else {
self.set(newLatest: filter.latest)
self.set(newEarliest: filter.earliest)
}
self.continue()
}
}
/// - Warning: Always call from a background thread!
func needsReloadDB(domain: String? = nil) {
assert(!Thread.isMainThread)
reloadRangeFromDB()
if let dom = domain {
notifyObservers { $0.syncUpdate(self, partialRemove: dom) }
} else {
notifyObservers { $0.syncUpdate(self, reset: rows) }
}
}
// MARK: - Sync Now
/// This will immediately resume timer updates, ignoring previous `pause()` requests.
func start() { paused = 0 }
/// All calls must be balanced with `continue()` calls.
/// Can be nested within other `pause-continue` pairs.
/// - Warning: An execution branch that results in unbalanced pairs will completely disable updates!
func pause() { paused += 1 }
/// Must be balanced with a `pause()` call. A `continue()` without a `pause()` is a `nop`.
/// - Note: Internally the sync timer keeps running. The `pause` will simply ignore execution during that time.
func `continue`() { if paused > 0 { paused -= 1 } }
/// Persist logs from cache and notify all observers. (`NotifySyncInsert`)
/// Determine rows of outdated entries that should be removed and notify observers as well. (`NotifySyncRemove`)
/// - Note: This method is rate limited. Sync will be performed at most once per second.
/// - Note: This method returns immediatelly. Syncing is done in a background thread.
/// - Parameter block: **Always** called on a background thread!
func syncNow(whenDone block: (() -> Void)? = nil) {
let now = Date().timeIntervalSince1970
guard (now - lastSync) > 1 else { // rate limiting
if let b = block { DispatchQueue.global().async { b() } }
return
}
lastSync = now
self.pause() // reduce concurrent load
DispatchQueue.global().async {
self.internalSync()
block?()
self.continue()
}
}
/// Called by `syncNow()`. Split to a separate func to reduce `self.` cluttering
private func internalSync() {
assert(!Thread.isMainThread)
// Always persist logs ...
if let newest = AppDB?.dnsLogsPersist() { // move cache -> heap
if filterType == .ABRange {
// ... even if we filter a few later
if let r = rows(tsMin, tsMax, scope: newest) {
notify(insert: r, .Latest)
}
} else {
notify(insert: newest, .Latest)
}
}
if filterType == .LastXMin {
set(newEarliest: Timestamp.past(minutes: Prefs.DateFilter.LastXMin))
}
// TODO: periodic hard delete old logs (will reset rowids!)
}
// MARK: - Internal
private func rows(_ ts1: Timestamp, _ ts2: Timestamp, scope: SQLiteRowRange = (0,0)) -> SQLiteRowRange? {
AppDB?.dnsLogsRowRange(between: ts1, and: ts2, within: scope)
}
private func reloadRangeFromDB() {
// `nil` is not SQLiteRowRange(0,0) aka. full collection.
// `nil` means invalid range. e.g. ts restriction too high or empty db.
range = rows(tsMin, tsMax)
}
/// Update internal `tsEarliest`, then post `NotifySyncInsert` or `NotifySyncRemove` notification with row ids.
/// - Warning: Always call from a background thread!
private func set(newEarliest: Timestamp?) {
func from(_ t: Timestamp?) -> Timestamp { t ?? 0 }
func to(_ t: Timestamp) -> Timestamp { tsLatest == nil ? t : min(t, tsMax) }
if let (old, new) = tsEarliest <-/ newEarliest {
if old != nil, (new == nil || new! < old!) {
if let r = rows(from(new), to(old!), scope: (0, range?.start ?? 0)) {
notify(insert: r, .Earliest)
}
} else if range != nil {
if let r = rows(from(old), to(new!), scope: range!) {
notify(remove: r, .Earliest)
}
}
}
}
/// Update internal `tsLatest`, then post `NotifySyncInsert` or `NotifySyncRemove` notification with row ids.
/// - Warning: Always call from a background thread!
private func set(newLatest: Timestamp?) {
func from(_ t: Timestamp) -> Timestamp { max(t + 1, tsMin) }
func to(_ t: Timestamp?) -> Timestamp { t == nil ? 0 : t! + 1 }
// +1: include upper end because `dnsLogsRowRange` selects `ts < X`
if let (old, new) = tsLatest <-/ newLatest {
if old != nil, (new == nil || old! < new!) {
if let r = rows(from(old!), to(new), scope: (range?.end ?? 0, 0)) {
notify(insert: r, .Latest)
}
} else if range != nil {
if let r = rows(from(new!), to(old), scope: range!) {
notify(remove: r, .Latest)
}
}
}
}
/// - Warning: Always call from a background thread!
private func notify(insert r: SQLiteRowRange, _ end: SyncUpdateEnd) {
if range == nil { range = r }
else {
switch end {
case .Earliest: range!.start = r.start
case .Latest: range!.end = r.end
}
}
notifyObservers { $0.syncUpdate(self, insert: r, affects: end) }
}
/// - Warning: `range` must not be `nil`!
/// - Warning: Always call from a background thread!
private func notify(remove r: SQLiteRowRange, _ end: SyncUpdateEnd) {
switch end {
case .Earliest: range!.start = r.end + 1
case .Latest: range!.end = r.start - 1
}
if range!.start > range!.end { range = nil }
notifyObservers { $0.syncUpdate(self, remove: r, affects: end) }
}
// MARK: - Observer List
private var observers: [WeakObserver] = []
/// Add `delegate` to observer list and immediatelly call `syncUpdate(reset:)` (on background thread).
func addObserver(_ delegate: SyncUpdateDelegate) {
observers.removeAll { $0.target == nil }
observers.append(.init(target: delegate))
DispatchQueue.global().async {
delegate.syncUpdate(self, reset: self.rows)
}
}
/// - Warning: Always call from a background thread!
private func notifyObservers(_ block: (SyncUpdateDelegate) -> Void) {
assert(!Thread.isMainThread)
self.pause()
for o in observers where o.target != nil { block(o.target!) }
self.continue()
}
}
/// Wrapper class for `SyncUpdateDelegate` that supports weak references
private struct WeakObserver {
weak var target: SyncUpdateDelegate?
weak var pullToRefresh: UIRefreshControl?
}
enum SyncUpdateEnd { case Earliest, Latest }
protocol SyncUpdateDelegate : AnyObject {
/// `SyncUpdate` has unpredictable changes. Reload your `dataSource`.
/// - Warning: This function will **always** be called from a background thread.
func syncUpdate(_ sender: SyncUpdate, reset rows: SQLiteRowRange)
/// `SyncUpdate` added new `rows` to database. Sync changes to your `dataSource`.
/// - Warning: This function will **always** be called from a background thread.
func syncUpdate(_ sender: SyncUpdate, insert rows: SQLiteRowRange, affects: SyncUpdateEnd)
/// `SyncUpdate` outdated some `rows` in database. Sync changes to your `dataSource`.
/// - Warning: This function will **always** be called from a background thread.
func syncUpdate(_ sender: SyncUpdate, remove rows: SQLiteRowRange, affects: SyncUpdateEnd)
/// Background process did delete some entries in database that match `affectedDomain`.
/// Update or remove entries from your `dataSource`.
/// - Warning: This function will **always** be called from a background thread.
func syncUpdate(_ sender: SyncUpdate, partialRemove affectedDomain: String)
}
// MARK: - Pull-To-Refresh
@available(iOS 10.0, *)
extension SyncUpdate {
/// Add Pull-To-Refresh control to `tableViewController`. On action notify `observer.syncUpdate(reset:)`
/// - Warning: Must be called after `addObserver()` such that `observer` exists in list of observers.
func allowPullToRefresh(onTVC tableViewController: UITableViewController?, forObserver: SyncUpdateDelegate) {
guard let i = observers.firstIndex(where: { $0.target === forObserver }) else {
assertionFailure("You must add the observer before enabling Pull-To-Refresh!")
return
}
// remove previous
observers[i].pullToRefresh?.removeTarget(self, action: #selector(pullToRefresh), for: .valueChanged)
observers[i].pullToRefresh = nil
if let tvc = tableViewController {
let rc = UIRefreshControl()
rc.addTarget(self, action: #selector(pullToRefresh), for: .valueChanged)
tvc.tableView.refreshControl = rc
observers[i].pullToRefresh = rc
}
}
/// Pull-To-Refresh callback method. Find observer with corresponding `RefreshControl` and notify `syncUpdate(reset:)`
@objc private func pullToRefresh(sender: UIRefreshControl) {
guard let x = observers.first(where: { $0.pullToRefresh === sender }) else {
assertionFailure("Should never happen. RefreshControl removed from table view while keeping it active somewhere else.")
return
}
syncNow {
x.target?.syncUpdate(self, reset: self.rows)
DispatchQueue.main.sync {
sender.endRefreshing()
}
}
}
}
|
//
// parkingZoomCell.swift
// testPokemon
//
// Created by Justin Huang on 2018/1/22.
// Copyright © 2018年 findata. All rights reserved.
//
import UIKit
class parkingZoomCell: UITableViewCell {
@IBOutlet weak var parkingZoomCollectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
parkingZoomCollectionView.delegate = self
parkingZoomCollectionView.dataSource = self
parkingZoomCollectionView.clipsToBounds = false
parkingZoomCollectionView.register(UINib.init(nibName: "parkingStatusCell", bundle: nil), forCellWithReuseIdentifier: "parkingStatusCell")
parkingZoomCollectionView.register(UINib.init(nibName: "ParkingFeatureItemCell", bundle: nil), forCellWithReuseIdentifier: "ParkingFeatureItemCell")
if let flowLayout = parkingZoomCollectionView.collectionViewLayout as? UICollectionViewFlowLayout{
flowLayout.estimatedItemSize = CGSize(width: 100.0, height: 100.0)
}
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
extension parkingZoomCell:UICollectionViewDelegate,UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
switch indexPath.row {
case 0 :
let parkingStatusCell = collectionView.dequeueReusableCell(withReuseIdentifier: "parkingStatusCell", for: indexPath)
return parkingStatusCell
// let parkingStatusCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ParkingFeatureItemCell", for: indexPath)
// return parkingStatusCell
// case 1:
// let parkingSupportCell = collectionView.dequeueReusableCell(withReuseIdentifier: "parkingSupportCell", for: indexPath)
// return parkingSupportCell
// let parkingStatusCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ParkingFeatureItemCell", for: indexPath)
// return parkingStatusCell
default:
let parkingStatusCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ParkingFeatureItemCell", for: indexPath)
return parkingStatusCell
}
}
}
|
//
// TripsTableViewCell.swift
// My Personal Planner
//
// Created by Shahin Farzane on 2019-04-09.
// Copyright © 2019 ShahinFarzane. All rights reserved.
//
import UIKit
class TripsTableViewCell: UITableViewCell {
@IBOutlet weak var cardView: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var tripImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
cardView.addShadowAndRoundCorners()
titleLabel.font = UIFont(name: Theme.mainFontName,size: 32)
cardView.backgroundColor = Theme.accent
tripImage.layer.cornerRadius = cardView.layer.cornerRadius
}
func setup(tripModel: TripModel){
titleLabel.text = tripModel.title
if let tripImg = tripModel.image {
tripImage.alpha = 0.3
tripImage.image = tripImg
UIView.animate(withDuration: 1){
self.tripImage.alpha = 1
}
}
}
}
|
//
// Forecast.swift
// WeatherByCity
//
// Created by Erick Tran on 10/10/17.
// Copyright © 2017 Erick Tran. All rights reserved.
//
import UIKit
import Alamofire
class Forecast {
//Declare Variable
var _date: String!
var _weatherType: String!
var _temp: String!
var _iconCondition: String!
var _windSpeed: String!
var date: String {
if _date == nil {
_date = ""
}
return _date
}
var weatherType: String {
if _weatherType == nil {
_weatherType = ""
}
return _weatherType
}
var windSpeed: String {
if _windSpeed == nil {
_windSpeed = ""
}
return _windSpeed
}
var temp: String {
if _temp == nil {
_temp = ""
}
return _temp
}
var iconCondition: String {
if _iconCondition == nil {
_iconCondition = ""
}
return _iconCondition
}
//Initiate Forecast object
init(weatherDictionary: Dictionary<String, Any>) {
//get temperature vavue
if let temp = weatherDictionary["main"] as? Dictionary<String, Any> {
if let min = temp["temp"] as? Double {
let kelvinToFarenheitTemp = (min * (9/5) - 459.67)
let kelvinToFarenheit = Double(round(10 * kelvinToFarenheitTemp/10))
self._temp = "\(kelvinToFarenheit)"
}
}
//get wind speed value
if let wind = weatherDictionary["wind"] as? Dictionary<String, Any> {
if let tempSpeed = wind["speed"] as? Double {
let speed = tempSpeed/0.44704
self._windSpeed = "\(Double(round(10 * speed/10))) mi/hr "
}
}
//get condition value
if let weatherType = weatherDictionary["weather"] as? [Dictionary<String, Any>] {
if let main = weatherType[0]["description"] as? String {
self._weatherType = main.capitalized
}
if let tempIcon = weatherType[0]["icon"] as? String {
self._iconCondition = tempIcon
}
}
//get date and time
if let date = weatherDictionary["dt"] as? Double {
let unixConnvertedDate = Date(timeIntervalSince1970: date)
let dayTimePeriodFormatter = DateFormatter()
dayTimePeriodFormatter.dateFormat = "EEE hh:mm a"
let dateString = dayTimePeriodFormatter.string(from: unixConnvertedDate)
self._date = dateString
}
}
}
|
//
// TrapRepresentation.swift
// Ruins
//
// Created by Theodore Abshire on 7/13/16.
// Copyright © 2016 Theodore Abshire. All rights reserved.
//
import UIKit
class TrapRepresentation:Representation
{
let trap:Trap
let x:Int
let y:Int
init(trap:Trap, x:Int, y:Int, superview:UIView, atCameraPoint:CGPoint, map:Map)
{
self.trap = trap
self.x = x
self.y = y
let view = UIView(frame: CGRectMake(0, 0, tileSize, tileSize))
view.backgroundColor = UIColor.orangeColor()
super.init(view: view, superview: superview)
updatePosition(atCameraPoint, map: map)
updateVisibility(atCameraPoint, map: map)
}
override func updatePosition(toCameraPoint:CGPoint, map:Map)
{
view.center = CGPoint(x: (0.5 + CGFloat(x)) * tileSize - toCameraPoint.x, y: (0.5 + CGFloat(y)) * tileSize - toCameraPoint.y)
self.view.alpha = map.tileAt(x: x, y: y).visible ? 1 : 0
}
override func updateVisibility(atCameraPoint:CGPoint, map:Map)
{
self.view.hidden = !map.tileAt(x: x, y: y).visible
}
override var dead:Bool
{
return trap.dead
}
} |
//
// Colors+Text.swift
// bm-persona
//
// Created by Kevin Hu on 3/15/20.
// Copyright © 2020 RJ Pimentel. All rights reserved.
//
import Foundation
import UIKit
extension Color {
static var primaryText: UIColor {
return UIColor.init { (trait) -> UIColor in
return trait.userInterfaceStyle == .dark ?
UIColor(red: 250/255, green: 250/255, blue: 250/255, alpha: 1.0) :
UIColor(red: 35/255, green: 35/255, blue: 35/255, alpha: 1.0)
}
}
static var blackText: UIColor {
return UIColor.init { (trait) -> UIColor in
return trait.userInterfaceStyle == .dark ?
UIColor(red: 250/255, green: 250/255, blue: 250/255, alpha: 1.0) :
UIColor(red: 44/255, green: 44/255, blue: 45/255, alpha: 1.0)
}
}
static var blueText: UIColor {
return UIColor(red: 48.0 / 255.0, green: 80.0 / 255.0, blue: 149.0 / 255.0, alpha: 1.0)
}
static var lightGrayText: UIColor {
return UIColor.init { (trait) -> UIColor in
return trait.userInterfaceStyle == .dark ?
UIColor(displayP3Red: 170/255, green: 170/255, blue: 170/255, alpha: 1.0) :
UIColor(red: 98.0 / 255.0, green: 97.0 / 255.0, blue: 98.0 / 255.0, alpha: 1.0)
}
}
static var lightLightGrayText: UIColor {
return UIColor(red: 200.0 / 255.0, green: 200.0 / 255.0, blue: 200.0 / 255.0, alpha: 1.0)
}
static var darkGrayText: UIColor {
return UIColor(red: 138.0 / 255.0, green: 135.0 / 255.0, blue: 138.0 / 255.0, alpha: 1.0)
}
static var secondaryText: UIColor {
return UIColor.init { (trait) -> UIColor in
return trait.userInterfaceStyle == .dark ?
UIColor(displayP3Red: 170/255, green: 170/255, blue: 170/255, alpha: 1.0) :
UIColor(displayP3Red: 105/255, green: 105/255, blue: 105/255, alpha: 1.0)
}
}
}
|
import UIKit
class ParameterSceneDataBuilder {
struct CellID {
static let BasicCell = "TitleValueCell"
}
struct Icon {
static let Parameter = "iconParameter"
}
static func constructSceneData(parameterList: PCList<PCParameter>) -> NameValueSceneData {
let parameters = parameterList.list
return NameValueSceneData(
section: [
NameValueSceneDataSection(
title: "Parameters",
item: parameters.map {
self.constructSceneDataItem(parameter: $0)
}
)
]
)
}
static func constructSceneDataItem(parameter: PCParameter) -> NameValueSceneDataItem {
return NameValueSceneDataItem(
refID: parameter.id,
cellID: CellID.BasicCell,
title: parameter.name,
detail: parameter.value,
segue: nil,
icon: UIImage(named: Icon.Parameter)
)
}
}
|
public protocol ScrollableIndexProtocol: AnyObject {
var moveForward: () -> Void { get }
var moveBackward: () -> Void { get }
}
class ScrollableIndexBindings: ScrollableIndexProtocol {
let moveForward: () -> Void
let moveBackward: () -> Void
init(_ moveForward: @escaping () -> Void,
_ moveBackward: @escaping () -> Void) {
self.moveForward = moveForward
self.moveBackward = moveBackward
}
}
|
//
// ListViewReorder.swift
// TelerikUIExamplesInSwift
//
// Copyright (c) 2015 Telerik. All rights reserved.
//
import UIKit
class ListViewReorder: TKExamplesExampleViewController, TKListViewDelegate {
let listView = TKListView()
let dataSource = TKDataSource()
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.addOption("Reorder with handle", action:reorderWithHandleSelected)
self.addOption("Reorder with long press", action:reorderWithLongPressSelected)
self.addOption("Disable reorder mode", action:disableReorderSelected)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.dataSource.loadDataFromJSONResource("PhotosWithNames", ofType: "json", rootItemKeyPath: "names")
if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad {
self.listView.frame = self.view.bounds
}
else {
self.listView.frame = self.view.bounds
}
self.listView.autoresizingMask = UIViewAutoresizing(rawValue: UIViewAutoresizing.FlexibleWidth.rawValue | UIViewAutoresizing.FlexibleHeight.rawValue)
// >> listview-delegate-set-swift
self.listView.delegate = self
// << listview-delegate-set-swift
// >> listview-datasource-reorder-swift
self.listView.dataSource = self.dataSource
self.dataSource.allowItemsReorder = true
// << listview-datasource-reorder-swift
// >> listview-reorder-swift
self.listView.allowsCellReorder = true
// << listview-reorder-swift
self.view.addSubview(self.listView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func reorderWithHandleSelected() {
self.listView.allowsCellReorder = true
self.listView.reorderMode = TKListViewReorderMode.WithHandle
}
func reorderWithLongPressSelected() {
self.listView.allowsCellReorder = true
self.listView.reorderMode = TKListViewReorderMode.WithLongPress
}
func disableReorderSelected() {
self.listView.allowsCellReorder = false
}
// MARK: - TKListViewDelegate
func listView(listView: TKListView, willReorderItemAtIndexPath indexPath: NSIndexPath) {
let cell = listView.cellForItemAtIndexPath(indexPath)
cell!.backgroundView?.backgroundColor = UIColor.yellowColor()
}
// >> listview-did-reorder-swift
func listView(listView: TKListView, didReorderItemFromIndexPath originalIndexPath: NSIndexPath, toIndexPath targetIndexPath: NSIndexPath) {
let cell = listView.cellForItemAtIndexPath(originalIndexPath)
cell!.backgroundView?.backgroundColor = UIColor.whiteColor()
self.dataSource .listView(listView, didReorderItemFromIndexPath: originalIndexPath, toIndexPath: targetIndexPath)
}
// << listview-did-reorder-swift
}
|
//
// ACLoginVc.swift
// ACAlamofireDemos
//
// Created by Air_chen on 2016/11/17.
// Copyright © 2016年 Air_chen. All rights reserved.
//
import UIKit
import Alamofire
class ACLoginVc: UIViewController {
@IBOutlet weak var userNameField: UITextField!
@IBOutlet weak var keyField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func loginAction(_ sender: Any) {
let param: Parameters = [
"username":self.userNameField.text! as String,
"pwd":self.keyField.text! as String
]
Alamofire.request("http://120.25.226.186:32812/login", method:.post, parameters:param, encoding:URLEncoding.default).validate(statusCode:200..<300).responseJSON{ (response) in
let result = String(data: response.data!, encoding: .utf8)
print("Result:\(result)")
if (result?.contains("success"))!{
print("Login success!")
let alertVc = UIAlertController(title: "Success!", message: "Success Login!", preferredStyle: UIAlertControllerStyle.alert)
let alertAction = UIAlertAction(title: "OK!", style: UIAlertActionStyle.default, handler: nil)
alertVc.addAction(alertAction)
self.present(alertVc, animated: true, completion: nil)
}
}
}
func authorMethod() {
let user = "user"
let password = "password"
Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)")
.authenticate(user: user, password: password)
.responseJSON { response in
debugPrint(response)
}
}
}
|
//
// QuestionSession.swift
// AV TEST AID
//
// Created by Timileyin Ogunsola on 15/07/2021.
// Copyright © 2021 TopTier labs. All rights reserved.
//
import Foundation
import RealmSwift
class QuestionSession: Object{
@objc dynamic var id = UUID().uuidString
dynamic var questionSessions = List<QuestionSessionItem>()
dynamic var optionSelectedList = List<OptionsSelected>()
@objc dynamic var currentQuestionIndex = 0
@objc dynamic var totalQuestions = 10
@objc dynamic var sessionFinished = false
@objc dynamic var questionInReviewSession = false
convenience init(questions : [Question], questionsAmount : Int = 10) {
self.init()
self.totalQuestions = questionsAmount
questions.forEach { (question) in
questionSessions.append(QuestionSessionItem(questionId: question.id, question: question))
}
}
convenience init(currentQuestionIndex: Int = 0, id: String, questionSessions: List<QuestionSessionItem>, questionsAmount : Int = 10, sessionFinished: Bool = false, questionInReviewSession: Bool = false) {
self.init()
self.id = id
self.currentQuestionIndex = currentQuestionIndex
self.questionSessions = questionSessions
self.totalQuestions = questionsAmount
self.sessionFinished = sessionFinished
self.questionInReviewSession = questionInReviewSession
}
convenience init (currentQuestionIndex: Int = 0, id: String){
self.init()
self.id = id
self.currentQuestionIndex = currentQuestionIndex
}
required init() {
}
override static func primaryKey() -> String? {
return "id"
}
static func onSessionEnded( _ realm: Realm){
let questionSessionResult = realm.objects(QuestionSession.self).first
if let questionSession = questionSessionResult{
try! realm.write{
questionSession.sessionFinished = true
}
}
}
static func insertQuestionSession(questionSession: QuestionSession, realm: Realm){
try! realm.write{
realm.add(questionSession, update: .modified)
}
}
static func onOptionSelected(forQuestionId questionId : String, option:Option, _ realm: Realm){
let questionSession = realm.objects(QuestionSession.self).first
var optionSelect : OptionsSelected? = nil
for option in questionSession!.optionSelectedList {
if option.id == questionId {
optionSelect = option
}
}
if let optionSelected = optionSelect {
try! realm.write{
optionSelected.optionId = option.id ?? ""
optionSelected.isCorrect = option.isCorrect
}
} else {
let optionsSelected = OptionsSelected(id: questionId, optionId: option.id ?? "", isCorrect: option.isCorrect)
try! realm.write{
let item = realm.create(OptionsSelected.self, value: optionsSelected, update: .modified)
questionSession?.optionSelectedList.append(item)
}
}
}
@discardableResult
static func getQuestionSession(_ realm: Realm) -> QuestionSession? {
let questionSession = realm.objects(QuestionSession.self).first
guard let questionSessions = questionSession else {return nil}
return questionSessions
}
@discardableResult
static func getCurrentQuestionForSessionOnNext(_ realm: Realm) -> (QuestionSessionItem?, Int)? {
if let questionSession = realm.objects(QuestionSession.self).first {
guard questionSession.currentQuestionIndex < questionSession.totalQuestions else {
return nil
}
print("on next button \(questionSession.questionSessions)")
let newIndex = questionSession.currentQuestionIndex + 1
let sessionItem = questionSession.questionSessions[newIndex]
try! realm.write{
questionSession.currentQuestionIndex = newIndex
}
return (sessionItem, newIndex)
}
return nil
}
@discardableResult
static func getCurrentQuestionAndStateForSession(_ realm: Realm) -> (QuestionSessionItem?, Int, Int, [OptionsSelected])? {
if let questionSession = realm.objects(QuestionSession.self).first {
let sessionItem = questionSession.questionSessions[questionSession.currentQuestionIndex]
var tempOptionsSelected : [OptionsSelected] = []
questionSession.optionSelectedList.forEach{ option in
tempOptionsSelected.append(option)
}
return (sessionItem, questionSession.currentQuestionIndex, questionSession.totalQuestions, tempOptionsSelected)
}
return nil
}
@discardableResult
static func getCurrentQuestionForSessionOnPrev(_ realm: Realm) -> (QuestionSessionItem?, Int)? {
if let questionSession = realm.objects(QuestionSession.self).first {
guard questionSession.currentQuestionIndex > 0 else {
return nil
}
let newIndex = questionSession.currentQuestionIndex - 1
let sessionItem = questionSession.questionSessions[newIndex]
try! realm.write{
questionSession.currentQuestionIndex = newIndex
}
return (sessionItem, newIndex)
}
return nil
}
@discardableResult
static func getSessionStats(_ realm: Realm) -> (Int, Int)? {
var totalCorrect = 0
if let questionSession = realm.objects(QuestionSession.self).first {
for sessionItem in questionSession.optionSelectedList {
if sessionItem.isCorrect {
totalCorrect = totalCorrect + 1
}
}
return (totalCorrect, questionSession.totalQuestions)
}
return nil
}
static func resetSession(_ realm: Realm) {
if let questionSession = realm.objects(QuestionSession.self).first {
try! realm.write{
questionSession.optionSelectedList = List<OptionsSelected>()
}
}
}
}
|
//
// YTLaunchModel.swift
// YTRxSwiftNewsDemo
//
// Created by tangyin on 09/03/2018.
// Copyright © 2018 ytang. All rights reserved.
//
import UIKit
import ObjectMapper
struct YTLaunchModel:Mappable {
var creatives:[YTLaunchModelImg]?
init?(map:Map) {
}
mutating func mapping(map: Map) {
creatives <- map["creatives"]
}
}
struct YTLaunchModelImg:Mappable {
var url: String = ""
init?(map:Map) {
}
mutating func mapping(map: Map) {
url <- map["url"]
}
}
|
//
// SegueThings.swift
// IGExplorer
//
// Created by bill donner on 1/19/16.
// Copyright © 2016 Bill Donner. All rights reserved.
//
import UIKit
protocol SegueThing {
func prepareInjectedData(segue:UIStoryboardSegue,igp:OU)
}
extension SegueThing {
func prepareInjectedData(segue:UIStoryboardSegue,igp:OU){
// Pass the selected object to the new view controller.
//print (">Injecting segue data \(segue.identifier) for \(igp.targetID))")
//assert(igp.pd.ouUserInfo != nil,"No user info for \(igp.targetID)")
if let fbvc = segue.destinationViewController as? BoosterFollowersViewController {
fbvc.igp = igp
}
if let fbvc = segue.destinationViewController as? SecretAdmirersViewController {
fbvc.igp = igp
}
if let fbvc = segue.destinationViewController as? UnrequitedFollowersViewController {
fbvc.igp = igp
}
if let fbvc = segue.destinationViewController as? GhostFollowersViewController {
fbvc.igp = igp
}
if let fbvc = segue.destinationViewController as? TopPostsSaysFollowersViewController {
fbvc.igp = igp
}
if let fbvc = segue.destinationViewController as? SpeechlessLikersViewController {
fbvc.igp = igp
}
if let fbvc = segue.destinationViewController as? HeartlessCommentersViewController {
fbvc.igp = igp
}
if let fbvc = segue.destinationViewController as? TopPostsByCommentsViewController {
fbvc.igp = igp
}
if let fbvc = segue.destinationViewController as? TopCommentersViewController {
fbvc.igp = igp
}
if let fbvc = segue.destinationViewController as? TopLikersViewController {
fbvc.igp = igp
}
if let fbvc = segue.destinationViewController as? TopFollowersViewController {
fbvc.igp = igp
}
if let fbvc = segue.destinationViewController as? BattleViewController {
fbvc.igp = igp
}
if let fbvc = segue.destinationViewController as? FollowingTableViewController {
fbvc.igp = igp
}
if let fbvc = segue.destinationViewController as? TopPostsByLikesViewController {
fbvc.igp = igp
}
if let fbvc = segue.destinationViewController as? TopPostsByCommentsViewController {
fbvc.igp = igp
}
if let dvc = segue.destinationViewController as? PrimaryMenuViewController {
dvc.igp = igp
}
if let dvc = segue.destinationViewController as? PeopleReportsMenuViewController {
dvc.igp = igp
}
if let dvc = segue.destinationViewController as? SpecialFollowersReportsMenuViewController {
dvc.igp = igp
}
if let dvc = segue.destinationViewController as? BTPM7x24Controller {
dvc.igp = igp
}
if let dvc = segue.destinationViewController as? WIPM7x24Controller {
dvc.igp = igp
}
if let dvc = segue.destinationViewController as? CalcFailController {
dvc.igp = igp
}
if let mvc = segue.destinationViewController as? MainScreenViewController {
mvc.igp = igp
}
}
} |
//
// HomeScreenViewController.swift
// Coptic Companion
//
// Created by Mike on 2016-02-13.
// Copyright (c) 2016 Mike Zaki. All rights reserved.
//
import UIKit
import RealmSwift
import Alamofire
import SwiftyJSON
class HomeScreenViewController : BaseViewController {
//Things to add, Realm, menu
//add new views at base
@IBOutlet weak var navigationView: BorderView!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var homeButton: MultiLanguageButton!
@IBOutlet weak var profileButton: UIButton!
@IBOutlet weak var chatButton: UIButton!
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet weak var diagnoseQueryView: UIView!
@IBOutlet weak var profileTableView: UITableView!
@IBOutlet weak var diagnoseMenuConstraint: NSLayoutConstraint!
@IBOutlet weak var profileTableViewConstraint: NSLayoutConstraint!
@IBOutlet weak var userSymptoms: UITextField!
var containerViewController: HomeScreenContainerViewController!
let realm = try!Realm()
var notificationToken: NotificationToken?
var mainMenuShown = false {
didSet{
if !oldValue {
showMenu()
}else {
hideMenu()
}
}
}
var profileMenuShown = false {
didSet{
if !oldValue {
showPMenu()
}else {
hidePMenu()
}
}
}
var mainMenuCollectionView:UICollectionView!
var mainMenuBottomConstraint:NSLayoutConstraint!
var mainMenuHeightConstraint:NSLayoutConstraint!
var mainMenuWidthConstraint:NSLayoutConstraint!
var profileMenuCollectionView:UICollectionView!
var profileMenuBottomConstraint:NSLayoutConstraint!
var profileMenuHeightConstraint:NSLayoutConstraint!
var profileMenuWidthConstraint:NSLayoutConstraint!
var mainMenuDataSource: MenuDataSource!
var profileMenuDataSource: ProfileMenuDataSource!
//var copticEvent = try! Realm().objects(events).sorted("position", ascending: true)
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//synFirebaseVariables
notificationToken = realm.addNotificationBlock { [weak self] note, realm in
if let strongSelf = self {
strongSelf.updateMenu()
strongSelf.updateSettings()
}
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
realm.removeNotification(notificationToken!)
}
//MARK: - Setup
func setupUI() {
//temporarily
self.backgroundImageView.hidden = true
setupNav()
setupMainMenu()
setupProfile()
}
func setupNav() {
self.navigationView.layer.zPosition += 1
self.navigationView.addBorder(edges: [.Top], colour: UIColor.lightGrayColor())
self.profileButton.layer.cornerRadius = self.profileButton.frame.size.width / 2
self.profileButton.clipsToBounds = true
self.chatButton.layer.cornerRadius = self.chatButton.frame.size.width / 2
self.chatButton.clipsToBounds = true
}
func setupMainMenu(){
mainMenuDataSource = MenuDataSource()
//pass the data source the info from the realm
mainMenuDataSource.didSelectMenuItem = { [weak self] index in
if let strongSelf = self {
strongSelf.mainMenuShown = false
strongSelf.showMenuItemAtIndex(index)
}
}
let flowLayout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
flowLayout.itemSize = CGSizeMake(300, 100)
flowLayout.scrollDirection = UICollectionViewScrollDirection.Vertical
mainMenuCollectionView = UICollectionView(frame: view.frame, collectionViewLayout: flowLayout)
mainMenuCollectionView.backgroundColor = UIColor.blackColor()
mainMenuCollectionView.alpha = 0.5
mainMenuCollectionView.translatesAutoresizingMaskIntoConstraints = false
mainMenuCollectionView.registerNib(UINib(nibName: "MenuCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "menuCollectionViewCell")
mainMenuCollectionView.dataSource = self.mainMenuDataSource
mainMenuCollectionView.delegate = self.mainMenuDataSource
view.addSubview(mainMenuCollectionView)
let horizontalConstraint = NSLayoutConstraint(item: mainMenuCollectionView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
mainMenuBottomConstraint = NSLayoutConstraint(item: mainMenuCollectionView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
mainMenuWidthConstraint = NSLayoutConstraint(item: mainMenuCollectionView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0)
mainMenuHeightConstraint = NSLayoutConstraint(item: mainMenuCollectionView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 400)
view.addConstraint(horizontalConstraint)
view.addConstraint(mainMenuHeightConstraint)
view.addConstraint(mainMenuWidthConstraint)
view.addConstraint(mainMenuBottomConstraint)
}
func setupProfile() {
self.profileTableView.dataSource = ProfileMenuDataSource()
self.profileTableView.delegate = ProfileMenuDataSource()
}
//MARK: - Update
func updateMenu() {
self.mainMenuCollectionView.reloadData()
}
func updateSettings() {
//update change anything here
// self.profileMenuCollectionView.reloadData()
}
//MARK: - Menu
func showMenu(){
self.mainMenuCollectionView.hidden = true
self.diagnoseQueryView.hidden = false
mainMenuBottomConstraint.constant = -(self.navigationView.frame.height+mainMenuCollectionView.frame.height)
diagnoseMenuConstraint.constant = -(self.navigationView.frame.height+diagnoseQueryView.frame.height)
let animations = {
self.view.layoutIfNeeded()
//maybe overlay here
}
UIView.animateWithDuration(0.5, animations: animations)
}
func hideMenu(){
mainMenuBottomConstraint.constant = 0
diagnoseMenuConstraint.constant = 0
//containerView.hidden = false
let animations = {
self.view.layoutIfNeeded()
//maybe overlay
}
UIView.animateWithDuration(0.5, animations: animations) { [weak self] result in
self?.mainMenuCollectionView.hidden = true
self?.diagnoseQueryView.hidden = true
}
}
//MARK: - Profile
func showPMenu(){
self.profileTableView.hidden = false
profileTableViewConstraint.constant = -(self.navigationView.frame.height+profileTableView.frame.height)
let animations = {
self.view.layoutIfNeeded()
}
UIView.animateWithDuration(0.5, animations: animations)
}
func hidePMenu(){
profileTableViewConstraint.constant = 0
let animations = {
self.view.layoutIfNeeded()
}
UIView.animateWithDuration(0.5, animations: animations) { [weak self] result in
self?.profileTableView.hidden = true
}
}
//MARK: - ContainerViews
func showMenuItemAtIndex (index:Int) {
self.containerViewController.showMenuItemAtIndex(index){
self.containerViewController.navigationController?.popToRootViewControllerAnimated(false)
}
}
func showPMenuItemAtIndex (index:Int) {
self.containerViewController.showPMenuItemAtIndex(index){
self.containerViewController.navigationController?.popToRootViewControllerAnimated(false)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showMainMenu" {
let newController = segue.destinationViewController as! UINavigationController
self.containerViewController = newController.topViewController as! HomeScreenContainerViewController
}
}
//onOverlayTapped
//onSettingsTapped
//onQuickMenuPressed
@IBAction func onMenuButtonPressed(sender: MultiLanguageButton) {
if self.profileMenuShown {
profileMenuShown = false
}
self.mainMenuShown = !mainMenuShown
}
@IBAction func onProfileButtonPressed(sender: UIButton) {
if self.mainMenuShown {
mainMenuShown = false
}
self.profileMenuShown = !profileMenuShown
}
@IBAction func onChatButtonPressed(sender: UIButton) {
self.containerViewController.showSmooch{
self.containerViewController.navigationController?.popToRootViewControllerAnimated(false)
}
}
@IBAction func onDiagnoseButtonPressed(sender: UIButton) {
if userSymptoms.text != ""
{
let wordsArray = []
let textString = userSymptoms.text
DiagnosisManager().evaluateQuerry(DiagnosisManager().populateDiagnosticQuery(textString!, intoArray: wordsArray as! [String]))
let smoochViewController = SmoochViewController()
let userId = SKTUser.currentUser().smoochId
print(userId)
Smooch.showConversationFromViewController(smoochViewController)
mainMenuShown = !mainMenuShown
}else{
//alert
}
}
}
|
//
// CompareController.swift
// SyllaSync
//
// Created by Joel Wasserman on 8/3/15.
// Copyright (c) 2015 IVET. All rights reserved.
//
import UIKit
class NotificationsController: UIViewController {
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var scrollView: UIScrollView!
var childVC:NotificationSettingsVC?
override func viewDidLoad() {
super.viewDidLoad()
//scroll view
childVC = storyboard?.instantiateViewControllerWithIdentifier("NotificationSettingsVC") as? NotificationSettingsVC
childVC!.view.frame = CGRectMake(0, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height)
childVC!.view.translatesAutoresizingMaskIntoConstraints = true
scrollView.addSubview(childVC!.view)
scrollView.contentSize = CGSizeMake(self.scrollView.frame.width, self.scrollView.frame.height)
addChildViewController(childVC!)
childVC!.didMoveToParentViewController(self as NotificationsController)
//end scroll view
let fontSize = self.descriptionLabel.font.pointSize
descriptionLabel.font = UIFont(name: "BoosterNextFY-Medium", size: fontSize)
titleLabel.font = UIFont(name: "BoosterNextFY-Medium", size: fontSize)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func dismiss(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
|
//
// TessC.swift
// Pods
//
// Created by Luiz Fernando Silva on 01/03/17.
//
//
import libtess2
public enum WindingRule: Int, CustomStringConvertible, CaseIterable {
case evenOdd
case nonZero
case positive
case negative
case absGeqTwo
public var description: String {
switch(self) {
case .evenOdd:
return "evenOdd"
case .nonZero:
return "nonZero"
case .positive:
return "positive"
case .negative:
return "negative"
case .absGeqTwo:
return "absGeqTwo"
}
}
}
public enum ElementType: Int {
case polygons
case connectedPolygons
case boundaryContours
}
public enum ContourOrientation {
case original
case clockwise
case counterClockwise
}
/// Wraps the low-level C libtess2 library in a nice interface for Swift
open class TessC {
/// Memory pooler - simple struct that is used as `userData` by the `TESSalloc`
/// methods.
/// Nil, if not using memory pooling.
var memoryPool: UnsafeMutablePointer<MemPool>?
/// Pointer to raw memory buffer used for memory pool - nil, if not using
/// memory pooling.
var poolBuffer: UnsafeMutablePointer<UInt8>?
/// Allocator - nil, if not using memory pooling.
var ma: TESSalloc?
/// TESStesselator* tess
var _tess: UnsafeMutablePointer<Tesselator>
/// The pointer to the Tesselator struct that represents the underlying
/// libtess2 tesselator.
///
/// This pointer wraps the dynamically allocated underlying pointer, and is
/// automatically deallocated on deinit, so you don't need to (nor should!)
/// manually deallocate it, or keep it alive externally longer than the life
/// time of a `TessC` instance.
///
/// If you want to manually manage a libtess2's tesselator lifetime, use
/// `Tesselator.create(allocator:)` and `Tesselator.destroy(_:Tesselator)`
/// instead.
public var tess: UnsafePointer<Tesselator> {
return UnsafePointer(_tess)
}
/// Whether to allow the output tesselated polygons to contain 0-area polys
/// within.
/// Defaults to false.
public var noEmptyPolygons: Bool {
get {
return tessGetNoEmptyPolygons(_tess)
}
set {
tessSetNoEmptyPolygons(_tess, newValue)
}
}
/// List of vertices tesselated.
///
/// Is nil, until a tesselation (CVector3-variant) is performed.
public var vertices: [CVector3]?
/// Raw list of vertices tesselated.
///
/// Is nil, until a tesselation (any variant) is performed.
public var verticesRaw: [TESSreal]?
/// List of elements tesselated.
///
/// Is nil, until a tesselation is performed.
public var elements: [Int]?
/// Number of vertices present.
///
/// Is 0, until a tesselation is performed.
public var vertexCount: Int = 0
/// Number of elements present.
///
/// Is 0, until a tesselation is performed.
public var elementCount: Int = 0
/// Tries to init this tesselator
/// Optionally specifies whether to use memory pooling, and the memory size
/// of the pool.
/// This can be usefull for cases of constrained memory usage, and reduces
/// overhead of repeated malloc/free calls
public init?(usePooling: Bool = true, poolSize: Int = 1024 * 1024 * 10) {
if usePooling {
poolBuffer = malloc(poolSize).assumingMemoryBound(to: UInt8.self)
let bufferPtr = UnsafeMutableBufferPointer(start: poolBuffer, count: poolSize)
memoryPool = .allocate(capacity: 1)
memoryPool?.pointee = MemPool(buffer: bufferPtr, size: 0)
ma = TESSalloc(memalloc: poolAlloc,
memrealloc: nil,
memfree: poolFree,
userData: memoryPool, meshEdgeBucketSize: 0,
meshVertexBucketSize: 0, meshFaceBucketSize: 0,
dictNodeBucketSize: 0, regionBucketSize: 0,
extraVertices: 256)
guard let tess = Tesselator.create(allocator: &ma!) else {
// Free memory
free(poolBuffer!)
// Tesselator failed to initialize
print("Failed to initialize tesselator")
return nil
}
self._tess = tess
} else {
guard let tess = Tesselator.create(allocator: nil) else {
// Tesselator failed to initialize
print("Failed to initialize tesselator")
return nil
}
self._tess = tess
}
}
deinit {
// Free tesselator
_tess.pointee.destroy()
if let mem = poolBuffer {
free(mem)
}
if let memoryPool = memoryPool {
memoryPool.deallocate()
}
}
/// A raw access to libtess2's tessAddContour, providing the contour from
/// a specified array, containing raw indexes.
///
/// Stride of contour that is passed down is:
///
/// MemoryLayout<TESSreal>.size * vertexSize
///
/// (`vertexSize` is 3 for `.vertex3`, 2 for `.vertex2`).
///
/// - Parameters:
/// - vertices: Raw vertices to add
/// - vertexSize: Size of vertices. This will change the size of the stride
/// when adding the contour, as well.
open func addContourRaw(_ vertices: [TESSreal], vertexSize: VertexSize) {
if(vertices.count % vertexSize.rawValue != 0) {
print("Warning: Vertices array provided has wrong count! Expected multiple of \(vertexSize.rawValue), received \(vertices.count).")
}
_tess.pointee.addContour(size: Int32(vertexSize.rawValue),
pointer: vertices,
stride: CInt(MemoryLayout<TESSreal>.size * vertexSize.rawValue),
count: CInt(vertices.count / vertexSize.rawValue))
}
/// Adds a new contour using a specified set of 3D points.
///
/// - Parameters:
/// - vertices: Vertices to add to the tesselator buffer.
/// - forceOrientation: Whether to force orientation of contour in some way.
/// Defaults to `.original`, which adds contour as-is with no modifications
/// to orientation.
open func addContour(_ vertices: [CVector3], _ forceOrientation: ContourOrientation = .original) {
var vertices = vertices
// Re-orientation
if (forceOrientation != .original) {
let area = signedArea(vertices)
if (forceOrientation == .clockwise && area < 0.0) || (forceOrientation == .counterClockwise && area > 0.0) {
vertices = vertices.reversed()
}
}
_tess.pointee.addContour(size: 3, pointer: vertices, stride: CInt(MemoryLayout<CVector3>.size), count: CInt(vertices.count))
}
/// Tesselates a given series of points, and returns the final vector
/// representation and its indices.
/// Can throw errors, in case tesselation failed.
///
/// This variant of `tesselate` returns the raw set of vertices on `vertices`.
/// `vertices` will always be `% vertexSize` count of elements.
///
/// - Parameters:
/// - windingRule: Winding rule for tesselation.
/// - elementType: Type of elements contained in the contours buffer.
/// - polySize: Defines maximum vertices per polygons if output is polygons.
/// - vertexSize: Defines the vertex size to fetch with the output. Specifying
/// .vertex2 on inputs that have 3 coordinates will zero 'z' values of all
/// coordinates.
@discardableResult
open func tessellateRaw(windingRule: WindingRule, elementType: ElementType, polySize: Int, vertexSize: VertexSize = .vertex3) throws -> (vertices: [TESSreal], indices: [Int]) {
if(_tess.pointee.tesselate(windingRule: Int32(windingRule.rawValue), elementType: Int32(elementType.rawValue), polySize: Int32(polySize), vertexSize: Int32(vertexSize.rawValue), normal: nil) == 0) {
throw TessError.tesselationFailed
}
// Fetch tesselation out
tessGetElements(_tess)
let verts = _tess.pointee.vertices!
let elems = _tess.pointee.elements!
let nverts = Int(_tess.pointee.vertexCount)
let nelems = Int(_tess.pointee.elementCount)
let stride: Int = vertexSize.rawValue
var output: [TESSreal] = Array(repeating: 0, count: nverts * stride)
output.withUnsafeMutableBufferPointer { body -> Void in
body.baseAddress?.assign(from: verts, count: nverts * stride)
}
var indicesOut: [Int] = []
for i in 0..<nelems {
let p = elems.advanced(by: i * polySize)
for j in 0..<polySize where p[j] != ~TESSindex() {
indicesOut.append(Int(p[j]))
}
}
verticesRaw = output
vertexCount = nverts
elementCount = nelems
elements = indicesOut
return (output, indicesOut)
}
/// Tesselates a given series of points, and returns the final vector
/// representation and its indices.
/// Can throw errors, in case tesselation failed.
///
/// This variant of `tesselate` automatically compacts vertices into an array
/// of CVector3 values before returning.
///
/// - Parameters:
/// - windingRule: Winding rule for tesselation.
/// - elementType: Type of elements contained in the contours buffer.
/// - polySize: Defines maximum vertices per polygons if output is polygons.
/// - vertexSize: Defines the vertex size to fetch with the output. Specifying
/// .vertex2 on inputs that have 3 coordinates will zero 'z' values of all
/// coordinates.
@discardableResult
open func tessellate(windingRule: WindingRule, elementType: ElementType, polySize: Int, vertexSize: VertexSize = .vertex3) throws -> (vertices: [CVector3], indices: [Int]) {
let (verts, i) = try tessellateRaw(windingRule: windingRule, elementType: elementType, polySize: polySize, vertexSize: vertexSize)
var output: [CVector3] = []
output.reserveCapacity(vertexCount)
let stride: Int = vertexSize.rawValue
for i in 0..<vertexCount {
let x = verts[i * stride]
let y = verts[i * stride + 1]
let z = vertexSize == .vertex3 ? verts[i * stride + 2] : 0
output.append(CVector3(x: x, y: y, z: z))
}
vertices = output
return (output, i)
}
private func signedArea(_ vertices: [CVector3]) -> TESSreal {
var area: TESSreal = 0.0
for i in 0..<vertices.count {
let v0 = vertices[i]
let v1 = vertices[(i + 1) % vertices.count]
area += v0.x * v1.y
area -= v0.y * v1.x
}
return 0.5 * area
}
public enum TessError: Error {
/// Error when a tessTesselate() call fails.
case tesselationFailed
/// Error thrown by TessC.tesselate static method when TessC initialization
/// failed.
case tessCInitFailed
}
/// Used to specify vertex sizing to underlying tesselator.
///
/// - vertex2: Vertices have 2 coordinates.
/// - vertex3: Vertices have 3 coordinates.
public enum VertexSize: Int {
case vertex2 = 2
case vertex3 = 3
}
}
// MARK: - Helper static members
public extension TessC {
/// Tesselates a set of 2d coordinates.
///
/// - Parameter vertices: Set of vertices to tesselate.
/// - Returns: Pair of vertices/indices outputted by tesselation
static func tesselate2d(polygon: [Vector2Representable]) throws -> (vertices: [CVector3], indices: [Int]) {
guard let tess = TessC() else {
throw TessError.tessCInitFailed
}
let polySize = 3
let contour = polygon.map {
CVector3(x: $0.x, y: $0.y, z: 0.0)
}
tess.addContour(contour)
try tess.tessellate(windingRule: .evenOdd, elementType: .polygons, polySize: polySize)
let result: [CVector3] = tess.vertices!
var indices: [Int] = []
for i in 0..<tess.elementCount
{
for j in 0..<polySize
{
let index = tess.elements![i * polySize + j]
if (index == -1) {
continue
}
indices.append(index)
}
}
return (result, indices)
}
/// Tesselates a set of 3d coordinates.
///
/// Note that the third coordinate is ignored during tesselation, as the
/// library supports only 2D polygonal tesselations.
///
/// - Parameter vertices: Set of vertices to tesselate.
/// - Returns: Pair of vertices/indices outputted by tesselation
static func tesselate3d(polygon: [Vector3Representable]) throws -> (vertices: [CVector3], indices: [Int]) {
guard let tess = TessC() else {
throw TessError.tessCInitFailed
}
let polySize = 3
let contour = polygon.map {
CVector3(x: $0.x, y: $0.y, z: $0.z)
}
tess.addContour(contour)
try tess.tessellate(windingRule: .evenOdd, elementType: .polygons, polySize: polySize)
var indices: [Int] = []
for i in 0..<tess.elementCount
{
for j in 0..<polySize
{
let index = tess.elements![i * polySize + j]
if (index == -1) {
continue
}
indices.append(index)
}
}
return (tess.vertices!, indices)
}
}
|
//
// NewsSubject.swift
// FudanNews
//
// Created by ChenxiStudio on 17/2/15.
// Copyright © 2017年 Fudan University. All rights reserved.
//
import UIKit
import AlamofireImage
import MJRefresh
class NewsSubject: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableview: UITableView!
@IBOutlet weak var headImage: UIImageView!
@IBOutlet weak var subjectInc: UITextView!
var dataArray: [News] = []
var cacheArray: [News] = []
var localSubject: News!
var total: Int = 0
override func viewDidAppear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = false
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableview!.delegate = self
self.tableview!.dataSource = self
self.tableview!.separatorStyle = .none
self.tableview!.register(UINib(nibName: "NewsNormal", bundle: nil), forCellReuseIdentifier: "NewsNormal")
self.tableview!.register(UINib(nibName: "NewsGallery", bundle: nil), forCellReuseIdentifier: "NewsGallery")
let header = MJRefreshGifHeader(refreshingTarget: self,refreshingAction:#selector(self.headerRefresh))
tableview.mj_header = header
tableview.mj_header = MJRefreshNormalHeader(refreshingTarget: self,refreshingAction:#selector(self.headerRefresh))
tableview.mj_footer = MJRefreshBackFooter(refreshingTarget: self, refreshingAction: #selector(self.footerRefresh))
tableview.estimatedRowHeight = 44.0
tableview.rowHeight = UITableViewAutomaticDimension
}
func headerRefresh() {
total = 0
update()
}
func footerRefresh() {
NetworkManager.getNewsList(forSubjectID: localSubject.id, startedFrom: total, withLimit: 15) { news in
if news != nil {
for e in news! {
self.cacheArray.append(e)
self.total = e.id
}
self.dataArray = self.cacheArray
DispatchQueue.main.async {
self.tableview.mj_footer.endRefreshing()
self.tableview.reloadData()
}
}
}
}
func update() {
self.title = localSubject.shortTitle
cacheArray.removeAll()
NetworkManager.getSubjectDetail(forSubjectID: localSubject.id) { tuple in
if tuple != nil{
self.headImage.af_setImage(withURL: tuple!.logo, placeholderImage: #imageLiteral(resourceName: "default_news_img"))
self.headImage.contentMode = .scaleAspectFit
self.subjectInc.text = tuple!.abstract
}
}
NetworkManager.getNewsList(forSubjectID: localSubject.id, startedFrom: total, withLimit: 10) { news in
if news != nil {
for e in news! {
self.cacheArray.append(e)
self.total = e.id
}
self.dataArray = self.cacheArray
DispatchQueue.main.async {
self.tableview.mj_header.endRefreshing()
self.tableview.reloadData()
}
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch dataArray[indexPath.row].newsType {
case .successor_gallery:
let cell = (self.tableview!).dequeueReusableCell(withIdentifier: "NewsGallery") as! NewsGallery
cell.localNews = dataArray[indexPath.row]
cell.type.text = ""
cell.update()
return cell
case .successor_normal:
let cell = (self.tableview!).dequeueReusableCell(withIdentifier: "NewsNormal") as! NewsNormal
cell.localNews = dataArray[indexPath.row]
cell.type.text = ""
cell.update()
return cell
default:
let cell = (self.tableview!).dequeueReusableCell(withIdentifier: "NewsNormal") as! NewsNormal
cell.localNews = dataArray[indexPath.row]
cell.type.text = ""
cell.update()
return cell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "ShowSubjectNewsDetail", sender: dataArray[indexPath.row])
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowSubjectNewsDetail" {
let controller = segue.destination as! NewsDetailViewController
controller.localNews = sender as! News
}
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
}
|
//
// APIManager.swift
// EmployeeManagement
//
// Created by Md, Afsarunnisa on 10/04/19.
// Copyright © 2019 Md, Afsarunnisa. All rights reserved.
//
import Foundation
import Alamofire
class APIManager : ApiClient {
// MARK: - Protocol Properties
static let shared = APIManager(baseURL:"")
private var baseURL: String = ""
private let sessionManager = Alamofire.SessionManager()
typealias JSONTaskCompletionHandler = (Decodable?, APIError?) -> Void
required init(baseURL: String) {
self.baseURL = baseURL
}
private func decodingTask<T: Decodable>(with requestModel: APIRequestModel, decodingType: T.Type, completionHandler completion: @escaping JSONTaskCompletionHandler) -> DataRequest {
let method = HTTPMethod(rawValue: requestModel.method.rawValue)!
var encoding: ParameterEncoding
if requestModel.paramsEncoding == .urlEncoded {
encoding = URLEncoding.default
} else {
encoding = JSONEncoding.default
}
// let task = sessionManager.request(request as! URLRequestConvertible)
let task = sessionManager.request(requestModel.url,
method: method,
parameters: requestModel.params,
encoding: encoding,
headers: requestModel.headers)
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json;charset=utf-8"])
.responseData { response in
switch response.result {
case .success(let data):
do {
let genericModel = try JSONDecoder().decode(decodingType, from: data)
completion(genericModel, nil)
} catch {
completion(nil, .jsonConversionFailure)
}
case .failure(let error):
completion(nil, .responseUnsuccessful)
}
}
return task
}
func MakeAsyncCall<T: Decodable>(with requestModel: APIRequestModel, decode: @escaping (Decodable) -> T?, completion: @escaping (Result<T, APIError>) -> Void) {
// let request = apiRequest(requestModel: requestModel)
let task = decodingTask(with: requestModel, decodingType: T.self) { (json , error) in
//MARK: change to main queue
DispatchQueue.main.async {
guard let json = json else {
if let error = error {
completion(Result.failure(error))
} else {
completion(Result.failure(.invalidData))
}
return
}
if let value = decode(json) {
completion(.success(value))
} else {
completion(.failure(.jsonParsingFailure))
}
}
}
task.resume()
}
func apiRequest(requestModel : APIRequestModel) -> DataRequest {
// Insert your common headers here, for example, authorization token or accept.
// all common headers and tokens we can add here
let method = HTTPMethod(rawValue: requestModel.method.rawValue)!
// var request1: NSURLRequest = NSURLRequest(requestModel.url, method: method, parameters: requestModel.params, encoding: requestModel.paramsEncoding as! ParameterEncoding, headers: requestModel.headers)
var encoding: ParameterEncoding
if requestModel.paramsEncoding == .urlEncoded {
encoding = URLEncoding.default
} else {
encoding = JSONEncoding.default
}
return request(requestModel.url, method: method, parameters: requestModel.params, encoding: encoding, headers: requestModel.headers);
}
// func apiRequest<T>(endpoint: String,method : HTTPMethod, parameters: T? = nil) -> Request {
// // Insert your common headers here, for example, authorization token or accept.
//
// var commonHeaders = ["Accept" : "application/json"]
//
//// let allHeaders = commonHeaders + headers
//// if let headers = headers {
//// commonHeaders = commonHeaders + headers
//// }
//
// return request(endpoint, method: method, parameters: parameters, encoding: URLEncoding.default, headers: commonHeaders);
// }
}
|
//
// PhotosViewController.swift
// Nasa App
//
// Created by Lucas Daniel on 25/02/19.
// Copyright © 2019 Lucas Daniel. All rights reserved.
//
import UIKit
import CoreData
class FavoritesPhotoCollectionCell: UICollectionViewCell {
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var photoDate: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
}
class SectionHeader: UICollectionReusableView {
@IBOutlet weak var sectionHeaderlabel: UILabel!
}
class PhotosViewController: UIViewController {
var sondaCuriosity: Sonda?
var sondaOpportunity: Sonda?
var sondaSpirit: Sonda?
var photos: [Photo]?
var photosCuriosity: [Photo]?
var photosOpportunity: [Photo]?
var photosSpirit: [Photo]?
var fetchedResultsController: NSFetchedResultsController<Photo>!
var selectedIndexes = [IndexPath]()
var insertedIndexPaths: [IndexPath]!
var deletedIndexPaths: [IndexPath]!
var updatedIndexPaths: [IndexPath]!
var stack = CoreDataStack.shared
let handleSonda = HandleSonda()
let handlePhoto = HandlePhoto()
@IBOutlet weak var favoritesPhotosCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
if let sondas = loadAllSondas() {
setupSondas(sonda: sondas)
}
setupPhotos()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let sondas = loadAllSondas() {
setupSondas(sonda: sondas)
setupPhotos()
}
}
func showAlert(indexPath: IndexPath) {
let alertController = UIAlertController(title: "Deletar", message: "Deseja realmente deletar essa foto?", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default) {
UIAlertAction in
self.deletePhoto(indexPath: indexPath)
DispatchQueue.main.async {
self.setupPhotos()
self.favoritesPhotosCollectionView.reloadData()
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
}
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
private func setupFetchedResultControllerWith(_ sonda: Sonda) {
let fr = NSFetchRequest<Photo>(entityName: Photo.name)
fr.sortDescriptors = []
fr.predicate = NSPredicate(format: "sonda == %@", argumentArray: [sonda])
fetchedResultsController = NSFetchedResultsController(fetchRequest: fr, managedObjectContext: stack.viewContext, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultsController.delegate = self
var error: NSError?
do {
try fetchedResultsController.performFetch()
} catch let errorTemp as NSError {
error = errorTemp
}
if let error = error {
print("\(#function) Error performing initial fetch: \(error)")
}
}
}
//Sonda
extension PhotosViewController {
func setupSondas(sonda: [Sonda]) {
sondaCuriosity = sonda[0]
sondaOpportunity = sonda[2]
sondaSpirit = sonda[4]
}
func loadAllSondas() -> [Sonda]? {
var sondas: [Sonda]?
do {
try sondas = handleSonda.fetchAllSondas(entityName: Sonda.name, viewContext: stack.viewContext)
} catch {
showInfo(withTitle: "Error", withMessage: "Error while fetching Pin locations: \(error)")
}
return sondas
}
}
extension PhotosViewController {
func setupPhotos() {
self.photosCuriosity = nil
self.photosCuriosity = nil
self.photosSpirit = nil
self.photosCuriosity = self.loadPhotos(using: self.sondaCuriosity!)
self.photosOpportunity = self.loadPhotos(using: self.sondaOpportunity!)
self.photosSpirit = self.loadPhotos(using: self.sondaSpirit!)
self.favoritesPhotosCollectionView.reloadData()
}
func loadPhotos(using sonda: Sonda) -> [Photo]? {
let predicate = NSPredicate(format: "sonda == %@", argumentArray: [sonda])
var photos: [Photo]?
do {
try photos = handlePhoto.fetchPhotos(predicate, entityName: Photo.name, sorting: nil, viewContext: stack.viewContext)
} catch {
showInfo(withTitle: "Error", withMessage: "Error while loading Photos from disk: \(error)")
}
return photos
}
func deletePhoto(indexPath: IndexPath) {
if indexPath.section == 0 {
self.setupFetchedResultControllerWith(sondaCuriosity!)
} else if indexPath.section == 1 {
self.setupFetchedResultControllerWith(sondaOpportunity!)
} else if indexPath.section == 2 {
self.setupFetchedResultControllerWith(sondaSpirit!)
}
let tempIndexPath: IndexPath = IndexPath(row: indexPath.row, section: 0)
let photoToDelete = self.fetchedResultsController.object(at: tempIndexPath)
self.stack.viewContext.delete(photoToDelete)
if indexPath.section == 0 {
self.setupFetchedResultControllerWith(sondaCuriosity!)
} else if indexPath.section == 1 {
self.setupFetchedResultControllerWith(sondaOpportunity!)
} else if indexPath.section == 2 {
self.setupFetchedResultControllerWith(sondaSpirit!)
}
do {
try stack.viewContext.save()
} catch {
showInfo(withTitle: "Error", withMessage: "Error while save context: \(error)")
}
}
}
extension PhotosViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: Screen.screenWidth*44/100, height: Screen.screenWidth*44/100)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
if !(photosCuriosity?.isEmpty)! {
return (photosCuriosity?.count)!
}
} else if section == 1 {
if !(photosOpportunity?.isEmpty)! {
return (photosOpportunity?.count)!
}
} else if section == 2 {
if !(photosSpirit?.isEmpty)! {
return (photosSpirit?.count)!
}
}
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let section = indexPath.section
var cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! FavoritesPhotoCollectionCell
var imageUrlString: String = ""
cell.photoImageView.tag = indexPath.item
if section == 0 {
imageUrlString = (photosCuriosity?[indexPath.item].img_src)!
if let date = dateToString(dateToConvert: (photosCuriosity?[indexPath.item].earth_date)!, actualFormat: "yyyy-MM-dd", newFormat: "dd/MM/yyyy") {
cell.photoDate.text = date
}
} else if section == 1 {
imageUrlString = (photosOpportunity?[indexPath.item].img_src)!
if let date = dateToString(dateToConvert: (photosOpportunity?[indexPath.item].earth_date)!, actualFormat: "yyyy-MM-dd", newFormat: "dd/MM/yyyy") {
cell.photoDate.text = date
}
} else if section == 2 {
imageUrlString = (photosSpirit?[indexPath.item].img_src)!
if let date = dateToString(dateToConvert: (photosSpirit?[indexPath.item].earth_date)!, actualFormat: "yyyy-MM-dd", newFormat: "dd/MM/yyyy") {
cell.photoDate.text = date
}
}
let imageUrl: URL = URL(string: imageUrlString)!
let url = URL(string: imageUrlString)
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
DispatchQueue.main.async {
cell.photoImageView.image = UIImage(data: data!)
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
showAlert(indexPath: indexPath)
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if let sectionHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "SectionHeader", for: indexPath) as? SectionHeader{
let title = ["Curiosity", "Opportunity", "Spirit"]
sectionHeader.sectionHeaderlabel.text = title[indexPath.section]
return sectionHeader
}
return UICollectionReusableView()
}
}
extension PhotosViewController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
insertedIndexPaths = [IndexPath]()
deletedIndexPaths = [IndexPath]()
updatedIndexPaths = [IndexPath]()
}
func controller(
_ controller: NSFetchedResultsController<NSFetchRequestResult>,
didChange anObject: Any,
at indexPath: IndexPath?,
for type: NSFetchedResultsChangeType,
newIndexPath: IndexPath?) {
switch (type) {
case .insert:
insertedIndexPaths.append(newIndexPath!)
break
case .delete:
deletedIndexPaths.append(indexPath!)
break
case .update:
updatedIndexPaths.append(indexPath!)
break
case .move:
print("Move an item. We don't expect to see this in this app.")
break
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
favoritesPhotosCollectionView.performBatchUpdates({() -> Void in
for indexPath in self.insertedIndexPaths {
self.favoritesPhotosCollectionView.insertItems(at: [indexPath])
}
for indexPath in self.deletedIndexPaths {
self.favoritesPhotosCollectionView.deleteItems(at: [indexPath])
}
for indexPath in self.updatedIndexPaths {
self.favoritesPhotosCollectionView.reloadItems(at: [indexPath])
}
}, completion: nil)
}
}
|
//
// APIHomeworkClose.swift
// homework
//
// Created by Liu, Naitian on 9/25/16.
// Copyright © 2016 naitianliu. All rights reserved.
//
import Foundation
class APIHomeworkClose {
let url = APIURL.homeworkClose
let role = UserDefaultsHelper().getRole()!
let homeworkModelHelper = HomeworkModelHelper()
let homeworkKeys = GlobalKeys.HomeworkKeys.self
var vc: HomeworkDetailViewController!
init(vc: HomeworkDetailViewController) {
self.vc = vc
}
func run(homeworkUUID: String) {
let data: [String: AnyObject] = [
self.homeworkKeys.homeworkUUID: homeworkUUID,
"role": role
]
let hudHelper = ProgressHUDHelper(view: self.vc.view)
hudHelper.show()
CallAPIHelper(url: url, data: data).POST({ (responseData) in
// success
let success = responseData["success"].boolValue
if success {
self.homeworkModelHelper.close(homeworkUUID)
self.vc.navigationController?.popViewControllerAnimated(true)
if let didCloseHomework = self.vc.didCloseHomeworkBlock {
didCloseHomework()
}
}
hudHelper.hide()
}) { (error) in
// error
hudHelper.hide()
}
}
} |
//
// NetworkRequest+Extension.swift
// EKNetworking
//
// Created by Nikita Tatarnikov on 19.06.2023
// Copyright © 2023 TAXCOM. All rights reserved.
//
import Foundation
public extension EKNetworkRequest {
var needToCache: Bool {
get { return false }
set {}
}
var array: [[String: Any]]? {
get { return nil }
set {}
}
}
|
//
// SettingsMenuScene.swift
// Reaveen
//
// Created by Matic Vrenko on 03/02/16.
// Copyright © 2016 Matic Teršek. All rights reserved.
//
import UIKit
import SpriteKit
class SettingsMenuScene: SKScene {
override func didMove(to view: SKView) {
let label = SKLabelNode(fontNamed: "Chalkduster")
label.text = "Settings"
label.fontSize = 40
label.fontColor = SKColor.black
label.position = CGPoint(x: size.width/2, y: size.height*0.3)
addChild(label)
let backButton: UIButton = UIButton(defaultButtonImage: "buttonTextureDefault", activeButtonImage: "buttonTextureActive", buttonAction: goToMainMenu)
backButton.position = CGPoint(x: 7*self.frame.width / 8, y: self.frame.height / 1.5)
addChild(backButton)
/*
let defaults = NSUserDefaults.standardUserDefaults()
if(defaults.boolForKey("Sound")){
let checkbox = childNodeWithName("soundCheckbox") as! SKSpriteNode
checkbox.texture = SKTexture(imageNamed: "checkboxChecked")
}else{
let checkbox = childNodeWithName("soundCheckbox") as! SKSpriteNode
checkbox.texture = SKTexture(imageNamed: "checkboxUnchecked")
}*/
}
func goToMainMenu () {
let endScene = MainMenuScene(fileNamed: "MainMenuScene")! //Replace here with the target scene
endScene.scaleMode = .aspectFill
self.view?.presentScene(endScene, transition: SKTransition.push(with: .down, duration: 0.35)) // Performs the transition of scene if the button was touch
}
/*
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches{
let positionInScene = touch.locationInNode(self)
let touchedNode = self.nodeAtPoint(positionInScene)
if let name = touchedNode.name
{
if name == "soundCheckbox"
{
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setBool(!defaults.boolForKey("Sound"), forKey: "Sound")
if(defaults.boolForKey("Sound")){
let checkbox = childNodeWithName("soundCheckbox") as! SKSpriteNode
checkbox.texture = SKTexture(imageNamed: "checkboxChecked")
}else{
let checkbox = childNodeWithName("soundCheckbox") as! SKSpriteNode
checkbox.texture = SKTexture(imageNamed: "checkboxUnchecked")
}
}
}
}
}*/
}
|
// Created by Niklas Bülow on 28.03.17.
// Copyright © 2017 Niklas Bülow. All rights reserved.
import Foundation
import SpriteKit
import CoreGraphics
public extension GameScene {
func gsMainGame() {
self.levelGenerator = LevelGenerator()
self.physicsWorld.contactDelegate = self
self.scaleMode = .resizeFill
self.currentGameState = .menu
scoreSystem!.score = 0
self.backgroundColor = .clear
//initialize startPlanet where the rocket stands on at launch
let startPlanetPosition = CGPoint(x: size.width / 2, y: -((size.width / 2) * 3 / 8))
let startPlanet = Universe.createPlanet(position: startPlanetPosition, circleOfRadius: size.width, type: .earthlike(50), gravitySize: 0, withPhysics: false, settings: settings!)
//initialize rocket as player
let rocket = Rocket()
rocket.position = CGPoint(x: size.width / 2, y: startPlanet.position.y + startPlanet.frame.height / 2 + 60)
let flightPath = gsFlightPath()
//initialize startLabel to start the game on tap
let startTitle = gsLabel(initText: "LAUNCH", name: "menu.launchbutton")
startTitle.position = CGPoint(x: size.width / 2, y: startTitle.frame.height - 10)
let startPic = gsTitle()
startPic.position = CGPoint(x: size.width / 2, y: 750)
let spButton = gsIcon(image: "settings")
spButton.position = CGPoint(x: 360, y: 900)
//add all previously initialized nodes to the scene
addChilds([startPlanet, startTitle, rocket, flightPath, startPic, spButton])
}
func gsSettings() {
self.backgroundColor = .darkGray
self.currentGameState = .settings
let settingsLabel = gsLabel(initText: "Settings", name: "settingsLabel")
settingsLabel.position = CGPoint(x: size.width / 2, y: 800)
let closeButton = gsIcon(image: "close")
closeButton.position = CGPoint(x: 360, y: 900)
let showGravityNodes = gsLabel(initText: "show Gravity:", name: "showGravity", size: 20)
showGravityNodes.position = CGPoint(x: size.width / 3, y: 700)
let showGravityNodesButton = gsIcon(image: "close")
if settings!.showGravity {
showGravityNodesButton.texture = SKTexture(imageNamed: "checked")
} else {
showGravityNodesButton.texture = SKTexture(imageNamed: "unchecked")
}
showGravityNodesButton.name = "showGravityButton"
showGravityNodesButton.size = CGSize(width: 30, height: 30)
showGravityNodesButton.position = CGPoint(x: size.width / 2 + 50 , y: 708)
addChilds([settingsLabel, closeButton, showGravityNodes, showGravityNodesButton])
}
func gsPause() {
guard let rocket = childNode(withName: "rocket") else {
//print("[FAILURE] Did not find rocket!")
return
}
pausedVelocity = rocket.physicsBody!.velocity
rocket.physicsBody!.isResting = true
rocket.physicsBody!.fieldBitMask = 2
for i in children {
i.isPaused = true
}
currentGameState = .pause
guard let pauseButton = childNode(withName: "pause") as? SKSpriteNode else {
//print("[FAILURE] Did not find pauseButton!")
return
}
pauseButton.texture = SKTexture(imageNamed: "close")
let pausedLabel = gsLabel(initText: "PAUSED", name: "pausedLabel", size: 100)
pausedLabel.position = CGPoint(x: camera!.position.x , y: camera!.position.y + 500)
let restartButton = gsLabel(initText: "restart", name: "restart", size: 70, color: .red)
restartButton.position = CGPoint(x: camera!.position.x, y: camera!.position.y - 500)
addChilds([pausedLabel, restartButton])
}
func gsDePause() {
guard let pauseButton = childNode(withName: "pause") as? SKSpriteNode else {
//print("[FAILURE] Did not find pauseButton!")
return
}
pauseButton.texture = SKTexture(imageNamed: "pause")
guard let rocket = childNode(withName: "rocket") as? Rocket else {
//print("[FAILURE] Did not find rocket!")
return
}
rocket.physicsBody!.isResting = false
rocket.physicsBody!.fieldBitMask = 1
rocket.physicsBody!.velocity = pausedVelocity!
guard let restartButton = childNode(withName: "restart") else {
//print("[FAILURE] Did not find rocket!")
return
}
guard let pausedLabel = childNode(withName: "pausedLabel") else {
//print("[FAILURE] Did not find rocket!")
return
}
self.removeChildren(in: [restartButton, pausedLabel])
currentGameState = .play
}
func gsGameOver() {
removeAllChildren()
self.backgroundColor = .darkGray
let gameOverLabel = gsLabel(initText: "GAMEOVER", name: "gameOver", size: 100)
gameOverLabel.position = CGPoint(x: camera!.position.x , y: camera!.position.y + 500)
let bestScore = "Best Score: \(self.scoreSystem!.bestScore)"
let bestScoreLabel = gsLabel(initText: bestScore, name: "bestScore", size: 70, color: .red)
bestScoreLabel.position = CGPoint(x: camera!.position.x, y: camera!.position.y + 100)
let currentScore = "Current Score: \(self.scoreSystem!.score)"
let currentScoreLabel = gsLabel(initText: currentScore, name: "currentScore")
currentScoreLabel.position = CGPoint(x: camera!.position.x, y: camera!.position.y)
let restartButton = gsLabel(initText: "restart", name: "restart", size: 70, color: .red)
restartButton.position = CGPoint(x: camera!.position.x, y: camera!.position.y - 500)
addChilds([gameOverLabel, bestScoreLabel, currentScoreLabel, restartButton])
}
}
|
//
// UIImageExtension.swift
// TestSwiftCycleImageTools
//
// Created by Mazy on 2017/4/20.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
extension UIImage {
func scaleRoundImage(size: CGSize, radius: CGFloat = 0) -> UIImage {
let newImage: UIImage?
let imageSize = self.size
let width = imageSize.width
let height = imageSize.height
let targetWidth = size.width
let targetHeight = size.height
var scaleFactor: CGFloat = 0.0
var scaledWidth = targetWidth
var scaledHeight = targetHeight
var thumbnailPoint = CGPoint(x: 0, y: 0)
if(__CGSizeEqualToSize(imageSize, size) == false){
let widthFactor = targetWidth / width
let heightFactor = targetHeight / height
if(widthFactor > heightFactor){
scaleFactor = widthFactor
}
else{
scaleFactor = heightFactor
}
scaledWidth = width * scaleFactor
scaledHeight = height * scaleFactor
if(widthFactor > heightFactor){
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
}else if(widthFactor < heightFactor){
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}
UIGraphicsBeginImageContextWithOptions(size, false, 0.0);
var thumbnailRect = CGRect.zero
thumbnailRect.origin = thumbnailPoint
thumbnailRect.size.width = scaledWidth
thumbnailRect.size.height = scaledHeight
if radius != 0 {
UIColor.red.setFill()
let path = UIBezierPath(roundedRect: CGRect(origin: CGPoint.zero, size: size), cornerRadius: radius)
path.addClip()
}
self.draw(in: thumbnailRect)
newImage = UIGraphicsGetImageFromCurrentImageContext()
if(newImage == nil){
print("scale image fail")
}
UIGraphicsEndImageContext()
guard let image = newImage else {
return UIImage()
}
return image
}
}
|
//
// ProgramsViewModel.swift
// Random1
//
// Created by Joan Domingo on 29.06.17.
//
//
import Foundation
import RxSwift
protocol ProgramsViewModelType: class {
var programs: Observable<[Program]> { get }
}
class ProgramsViewModel: ProgramsViewModelType {
let programs: Observable<[Program]>
private let programsInteractor: ProgramsInteractor
init(programsInteractor: ProgramsInteractor = ProgramsInteractor()) {
self.programsInteractor = programsInteractor
self.programs = self.programsInteractor.loadPrograms()
.observeOn(MainScheduler.instance)
}
}
|
//
// File.swift
//
//
// Created by Mason Phillips on 6/13/20.
//
import Foundation
import RxSwift
struct SearchKeywordEndpoint: APIRequest {
typealias Response = PagedSearchKeywordModel
var endpoint: String { "/search/keyword" }
var parameters: Dictionary<String, String> {
return [
"query": query,
"page": "\(page)"
]
}
let query: String
let page: Int
}
public extension API {
func searchKeyword(_ query: String, page: Int = 1) -> Single<PagedSearchKeywordModel> {
return _fetch(SearchKeywordEndpoint(query: query, page: page))
}
}
|
//
// FeedCell.swift
// AlTayer
//
// Created by Anton Vizgin on 10/17/18.
// Copyright © 2018 Al Tayer. All rights reserved.
//
import UIKit
final class FeedCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
func setup(_ feedModel: FeedModel) {
imageView.loadImage(withUrl: (Constants.Network.imagesBaseURL + (feedModel.media.first?.src ?? "")))
titleLabel.text = feedModel.designerCategoryName
descriptionLabel.text = feedModel.name
priceLabel.text = "USD \(feedModel.minPrice)"
}
}
|
//
// ActivityDao.swift
// Findout
//
// Created by Ramzy Kermad on 19/12/2019.
// Copyright © 2019 Ramzy Kermad. All rights reserved.
//
import Foundation
struct ActivityDao {
// Represente le type d'activité voulue
// Elle comprend 0, 1 ou plusieurs catégories d'activités
var name: String
var activityID: String
var categoryListID: String
init?(jsonResponse: [String: Any]){
self.name = ""
self.activityID = ""
self.categoryListID = ""
guard let name = jsonResponse["name"] as? String,
let activityId = jsonResponse["activity_id"] as? String,
let catListId = jsonResponse["category_list_id"] as? String else{
return
}
}
init(activityName: String, activityId: String, catListId: String){
self.name = activityName
self.activityID = activityId
self.categoryListID = catListId
}
}
|
import Opaque
import Foundation
let jsonDecoder = JSONDecoder()
let jsonEncoder = JSONEncoder()
struct RegistrationPayload: Codable {
let encryptedPrivateKey: Opaque.EncryptedPrivateKey
let publicKey: Opaque.PublicKey
}
let salt: Opaque.Salt = try .random()
var verificationNonce = Opaque.VerificationNonce()
let registrationPayload: RegistrationPayload
do {
print("Paste encrypted password (1):")
let encryptedPassword = try Opaque.EncryptedPassword(
base64Encoded: readLine()!)
let encryptedSaltedPassword = try encryptedPassword.salted(with: salt).base64EncodedString()
print("Encrypted salted password:\n\(encryptedSaltedPassword)")
print("Paste registration payload:")
do {
let data = readLine()!.data(using: .utf8)!
registrationPayload = try jsonDecoder.decode(RegistrationPayload.self, from: data)
}
}
// Authenticate
do {
print("Paste encrypted password (2):")
let encryptedPassword = try Opaque.EncryptedPassword(base64Encoded: readLine()!)
struct VerificationRequest: Codable {
let encryptedPrivateKey: Opaque.EncryptedPrivateKey
let verificationNonce: Opaque.VerificationNonce
let encryptedSaltedPassword: Opaque.EncryptedSaltedPassword
}
let currentVerificationNonce = verificationNonce
try verificationNonce.increment()
// At this point, we should save the incremented verification nonce to ensure it is never reused.
let verificationRequest = VerificationRequest(
encryptedPrivateKey: registrationPayload.encryptedPrivateKey,
verificationNonce: currentVerificationNonce,
encryptedSaltedPassword: try encryptedPassword.salted(with: salt)
)
let encodedVerificationRequest = String(data: try jsonEncoder.encode(verificationRequest), encoding: .utf8)!
print("Verification request:\n\(encodedVerificationRequest)")
print("Paste verification:")
let verification = try! Opaque.Verification(base64Encoded: readLine()!)
try verification.validate(registrationPayload.publicKey, currentVerificationNonce)
print("Verification is valid!")
}
|
//
// Item.swift
// Expo1900
//
// Created by 이영우 on 2021/04/06.
//
import Foundation
/// JSON 파일 items에 해당되는 타입
/// - name : String 타입으로 item의 이름, nil 값에 해당할 경우 비어 있는 문자열 반환
/// - imageName : String 타입으로 item 이미지 이름, nil 값에 해당할 경우 비어 있는 문자열 반환
/// - shortDesc : String 타입으로 item 요약 설명, nil 값에 해당할 경우 비어 있는 문자열 반환
/// - description : String 타입으로 item 설명, nil 값에 해당할 경우 비어 있는 문자열 반환
struct Item: Decodable {
let name: String
let imageName: String
let shortDesc: String
let description: String
private enum CodingKeys: String, CodingKey {
case name
case imageName = "image_name"
case shortDesc = "short_desc"
case description = "desc"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = (try? container.decode(String.self, forKey: .name)) ?? .blank
self.imageName = (try? container.decode(String.self, forKey: .imageName)) ?? .blank
self.shortDesc = (try? container.decode(String.self, forKey: .shortDesc)) ?? .blank
self.description = (try? container.decode(String.self, forKey: .description)) ?? .blank
}
}
|
//
// PostPictureViewController.swift
// sns
//
// Created by REO HARADA on 2017/10/29.
// Copyright © 2017年 reo harada. All rights reserved.
//
import UIKit
/********** レッスン3-4 UIImagePickerControllerと相談する準備 **********/
// UIImagePickerControllerと相談する準備その1
// UIImagePickerControllerDelegate:UIImagePickerControllerと相談する宣言
// UINavigationControllerDelegate:UIImagePickerControllerは、UINavigationControllerの子どもであり、UINavigationControllerとの相談宣言も必要
class PostPictureViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
/********** レッスン3-4 UIImagePickerControllerと相談する準備 **********/
@IBOutlet weak var selectedImageView: UIImageView!
@IBOutlet weak var notificationLabel: UILabel!
/********** レッスン3-3 iPhoneに保存してある写真を取得、カメラを起動してくれる部品を用意 **********/
var imgPC = UIImagePickerController()
/********** レッスン3-3 iPhoneに保存してある写真を取得、カメラを起動してくれる部品を用意 **********/
/********** レッスン4-4 objectIdを保存しておく部品を用意 **********/
var objectId = ""
/********** レッスン4-4 objectIdを保存しておく部品を用意 **********/
override func viewDidLoad() {
super.viewDidLoad()
/********** レッスン3-4 UIImagePickerControllerと相談する準備 **********/
// UIImagePickerControllerと相談する準備その2
self.imgPC.delegate = self
/********** レッスン3-4 UIImagePickerControllerと相談する準備 **********/
/********** レッスン3-7 選んだ写真を編集したいとき **********/
// 編集モードに変更
self.imgPC.allowsEditing = true
/********** レッスン3-7 選んだ写真を編集したいとき **********/
}
@IBAction func tapSelectFromPicture(_ sender: Any) {
/********** レッスン3-5 写真から選ぶ画面を起動する **********/
// もし、PhotoLibraryが読み込み可能であれば
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
// UIImagePickerControllerにどこから写真を選ぶか指定する(PhotoLibraryから)
self.imgPC.sourceType = .photoLibrary
// UIImagePickerControllerを表示する
self.present(imgPC, animated: true, completion: nil)
}
/********** レッスン3-5 写真から選ぶ画面を起動する **********/
}
@IBAction func tapSelectFromCamera(_ sender: Any) {
/********** レッスン3-x カメラをを起動する **********/
// もし、カメラが読み込み可能であれば
if UIImagePickerController.isSourceTypeAvailable(.camera) {
// UIImagePickerControllerにどこから写真を選ぶか指定する(カメラから)
self.imgPC.sourceType = .camera
// UIImagePickerControllerを表示する
self.present(imgPC, animated: true, completion: nil)
}
/********** レッスン3-x カメラをを起動する **********/
}
@IBAction func tapPostCompleteButton(_ sender: Any) {
if self.selectedImageView.image == nil {
self.notificationLabel.isHidden = false
return
}
/********** レッスン4-1 選んだ写真を保存する **********/
// // 選んだ画像(UIImage)をデータに変更(Data)
let data = UIImagePNGRepresentation(self.selectedImageView.image!)
// // ファイルを保存してくれる人(NCMBFile)を呼んでくる
// // ファイル名と保存するデータを渡す
// /********** レッスン4-6 ファイル名にobjectIdを利用する **********/
let file = NCMBFile.file(withName: "\(objectId).png", data: data) as? NCMBFile
// /********** レッスン4-6 ファイル名にobjectIdを利用する **********/
// // ファイルを保存してもらう
file?.saveInBackground({ (error) in
// // ファイル保存が終わったらどうするぅ?
// /********** レッスン4-2 保存が終わったあとの処理 **********/
// // もし、エラーでなかったら
if error == nil {
// // 最初の画面に戻る
self.navigationController?.popToRootViewController(animated: true)
}
// /********** レッスン4-2 保存が終わったあとの処理 **********/
})
/********** レッスン4-1 選んだ写真を保存する **********/
}
/********** レッスン3-6 UIImagePickerControllerとの相談 **********/
// UIImagePickerControllerとの相談↓
// 写真を選択した後どうするぅ?
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
/********** レッスン3-7 選んだ写真を編集したいとき **********/
// 編集した画像を取得
let img = info[UIImagePickerControllerEditedImage] as! UIImage
/********** レッスン3-7 選んだ写真を編集したいとき **********/
// 選んだ画像をselectedImageViewに表示する
self.selectedImageView.image = img
// UIImagePickerControllerの画面を閉じる
self.imgPC.dismiss(animated: true, completion: nil)
}
/********** レッスン3-6 写真を選択したらどうするぅ? **********/
}
|
//
// GradientView.swift
// JPGradient
//
// Created by 周健平 on 2020/9/17.
// Copyright © 2020 周健平. All rights reserved.
//
import UIKit
public class GradientView: UIView {
// MARK: - 重写的父类函数
public override class var layerClass: AnyClass {
CAGradientLayer.self
}
// MARK: - 构造函数
public override init(frame: CGRect) {
super.init(frame: frame)
}
public convenience init(frame: CGRect = .zero,
startPoint: CGPoint = .zero,
endPoint: CGPoint = .zero,
locations: [NSNumber]? = nil,
colors: [UIColor]? = nil) {
self.init(frame: frame)
self.startPoint(startPoint)
.endPoint(endPoint)
.locations(locations)
.colors(colors)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - JPGradient
extension GradientView: JPGradient {
public var gLayer: CAGradientLayer { layer as! CAGradientLayer }
}
|
//
// NoteDetailViewController.swift
// Manawadu M.S-Cobsccomp171p008
//
// Created by Sandeepa Manawadu on 2019/05/23.
// Copyright © 2019 Sandeepa Manawadu. All rights reserved.
//
import UIKit
class NoteDetailViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
// to capture user input text
var text: String = ""
// create a property of master VC reference
var masterView: NotesViewController!
override func viewDidLoad() {
super.viewDidLoad()
textView.text = text
// set small title for Note
self.navigationItem.largeTitleDisplayMode = .never
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// to automatically display the phone keypad
textView.becomeFirstResponder()
}
// setting text from master ViewController
func setText(t: String) {
// modify the text
text = t
if isViewLoaded {
//update the textview
textView.text = t
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
masterView.newRowText = textView.text
// to hold the keypad
textView.resignFirstResponder()
}
}
|
//
// ToDo.swift
// MAPD714_Assignment2
//
// Created by Sherlyn Lobo on 2018-12-07.
// Copyright © 2018 Sherlyn Lobo. All rights reserved.
//
// File Name : ToDoTableViewController.swift
// Author Name : Sherlyn Lobo
// Student ID : 301013071
// App Description : ToDo List App
import UIKit
class ToDo
{
var name = ""
var important = false
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.