text stringlengths 8 1.32M |
|---|
import Cocoa
let arr1 = ["a","b","c"]
let arr2 = [0,1,2]
var dict = [String : Int]()
for (char, num) in zip(arr1,arr2) {
dict[char] = num
}
print(dict)
|
//
// WeekDayCollectionViewCell.swift
// OutlookCalendar
//
// Created by Pnina Eliyahu on 1/15/18.
// Copyright © 2018 Pnina Eliyahu. All rights reserved.
//
import UIKit
// View for displaying a weekDay in the calendar header
class WeekDayView: UIView {
var title: UILabel! = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: UIFont.labelFontSize)
label.font = UIFont.systemFont(ofSize: 15.0)
label.textAlignment = .center
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
addSubview(title)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
title.frame = CGRect(origin: .zero, size: frame.size)
}
}
|
import XCTest
import Cuckoo
@testable import Showcase_iOS
class UserAuthenticationTests: XCTestCase {
// MARK: Mocked dependencies
var mockFirebaseAuthentication = MockFirebaseLoginAuthenticating()
var mockEmail: String?
// MARK: System under test
var serviceUnderTest: UserAuthentication!
// MARK: Lifecycle
override func setUp() {
super.setUp()
mockEmail = "test@gmail.com"
serviceUnderTest = UserAuthentication(mockFirebaseAuthentication)
}
override func tearDown() {
super.tearDown()
}
// MARK: Test(s)
func testThatSignInMethodCompletesWithAUserWhenAuthenticationIsSuccesfull() {
let mockUser = MockUser()
let fakeUserResult = MockAuthDataResultProtocol()
stub(fakeUserResult) { (mock) in
_ = when(mock.user.get.then({ _ in
return mockUser
}))
}
stub(mockFirebaseAuthentication) { (mock) in
let _ = when(mock.signIn(withEmail: anyString(), password: anyString(), completion: any()).then({ (email, password, completion) in
completion(fakeUserResult, nil)
}))
}
serviceUnderTest?.signIn(withEmail: mockEmail!, password: "") { (user, error) in
XCTAssertEqual(user?.user.uid, mockUser.uid )
}
verify(mockFirebaseAuthentication, times(1)).signIn(withEmail: anyString(), password: anyString(), completion: any())
}
func testThatSignInMethodCompletesWithAnErrorWhenAuthenticationIsUnSuccesfull() {
stub(mockFirebaseAuthentication) { (mock) in
let _ = when(mock.signIn(withEmail: anyString(), password: anyString(), completion: any()).then({ (email, password, completion) in
completion(nil ,AuthenticationError.notAuthenticated)
}))
}
serviceUnderTest?.signIn(withEmail: "", password: "") { (user, error) in
XCTAssertEqual(error as! AuthenticationError, AuthenticationError.notAuthenticated)
}
verify(mockFirebaseAuthentication, times(1)).signIn(withEmail: anyString(), password: anyString(), completion: any())
}
}
class MockUser: FirUserProtocol {
var uid: String = "user"
}
|
//
// ReadViewController.swift
// SaveToKeychain
//
// Created by Thuy Nguyen on 30/05/2021.
//
import UIKit
class ReadViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func clickRead(_ sender: Any) {
guard let appURL = URL(string: "ReadKeychainDemo://") else { return }
if UIApplication.shared.canOpenURL(appURL) {
UIApplication.shared.open(appURL, options: [:], completionHandler: nil)
}
}
}
|
//
// RoomTableViewCell.swift
// Guard
//
// Created by apple on 16/1/7.
// Copyright © 2016年 pz1943. All rights reserved.
//
import UIKit
class RoomTableViewCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
}
@IBOutlet weak var DoneFlagImageView: UIView!
@IBOutlet weak var roomTitle: UILabel!
var room: Room?
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// Utilities.swift
// BinaryTest
//
// Created by Jonathan Wight on 6/24/15.
//
// Copyright © 2016, Jonathan Wight
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Foundation
/**
* A wrapper around CFAbsoluteTime
*
* CFAbsoluteTime is just typealias for a Double. By wrapping it in a struct we're able to extend it.
*/
public struct Timestamp {
public let absoluteTime: CFAbsoluteTime
public init() {
absoluteTime = CFAbsoluteTimeGetCurrent()
}
public init(absoluteTime: CFAbsoluteTime) {
self.absoluteTime = absoluteTime
}
}
// MARK: -
extension Timestamp: Equatable {
}
public func == (lhs: Timestamp, rhs: Timestamp) -> Bool {
return lhs.absoluteTime == rhs.absoluteTime
}
// MARK: -
extension Timestamp: Comparable {
}
public func < (lhs: Timestamp, rhs: Timestamp) -> Bool {
return lhs.absoluteTime < rhs.absoluteTime
}
// MARK: -
extension Timestamp: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(absoluteTime.hashValue)
}
}
// MARK: -
extension Timestamp: CustomStringConvertible {
public var description: String {
return String(absoluteTime)
}
}
|
//
// This source file is part of the Apodini open source project
//
// SPDX-FileCopyrightText: 2019-2021 Paul Schmiedmayer and the Apodini project authors (see CONTRIBUTORS.md) <paul.schmiedmayer@tum.de>
//
// SPDX-License-Identifier: MIT
//
/// The `ContentMetadataNamespace` can be used to define an appropriate
/// Name for your `ContentMetadataDefinition` in a way that avoids Name collisions
/// on the global Scope.
///
/// Given the example of `DescriptionContentMetadata` you can define a Name like the following:
/// ```swift
/// extension ContentMetadataNamespace {
/// public typealias Description = DescriptionContentMetadata
/// }
/// ```
///
/// Refer to `TypedContentMetadataNamespace` if you need access to the generic `Content`
/// Type where the Metadata is used on.
public protocol ContentMetadataNamespace {}
|
//
// QRGeneratorViewController.swift
// mad2_practical6
//
// Created by Jm San Diego on 27/11/19.
// Copyright © 2019 Jm San Diego. All rights reserved.
//
import Foundation
import QRCoder
class QRGeneratorViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var urlTxtField: UITextField!
@IBOutlet weak var qrImage: UIImageView!
let generator = QRCodeGenerator(correctionLevel: .Q)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
urlTxtField.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
urlTxtField.resignFirstResponder()
let url = urlTxtField.text
qrImage.image = generator.createImage(value: url!, size: CGSize(width: 200,height: 200))
return true;
}
}
|
//
// UserLookupService.swift
// CharacterChat
//
// Created by 林 和弘 on 2016/07/16.
// Copyright © 2016年 Yahoo Japan Corporation. All rights reserved.
//
import Foundation
class UserLookupService {
enum Error: ErrorProtocol {
case general
}
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: OperationQueue.main)
func fetch(with keyword: String = "", page: Int = 0, complete: (result: Result<[User], Error>) -> Void) -> URLSessionTask {
let encodedUserName = keyword.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics)!
let task = session.dataTask(with: URL(string: "http://0.0.0.0:3000/search_users?query=\(encodedUserName)")!) { (data, response, error) in
guard let data = data else {
complete(result: Result(Error.general))
return
}
if let jsonObj = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers), let aryObj = jsonObj as? NSArray {
var friends = [User]()
for friendObj in aryObj {
if let dictObj = friendObj as? NSDictionary,
name = dictObj["name"] as? String,
identifier = dictObj["id"] as? Int,
profileUrl = dictObj["profile_url"] as? String {
friends.append(User(identifier: "\(identifier)", name: name, profileImage: URL(string: profileUrl)!))
}
}
complete(result: Result(friends))
} else {
complete(result: Result(Error.general))
}
}
task.resume()
return task
}
deinit {
}
}
|
//
// GardenInterface.swift
// CropBook
//
// Created by Jason Wu on 2018-07-02.
// Copyright © 2018 CMPT276-Group15. All rights reserved.
//
import UIKit
import Firebase
import CoreData
import MultiSelectSegmentedControl
class GardenCropList: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var menuButton: UIBarButtonItem!
@IBOutlet weak var addCropButton: UIButton!
var managedObjectContext : NSManagedObjectContext!
var myIndex=0
var gardenIndex = 0
var myGarden: MyGarden!
var cropList: [CropProfile?]?
var Online:Bool?
var isExtended: Int?
let ref=Database.database().reference()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.backgroundColor = UIColor(red: 248.0/255.0, green: 1, blue: 210/255, alpha:1)
self.view.bringSubview(toFront: self.addCropButton)
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if self.Online! {
// Ensure Menu Button is enabled
self.menuButton.tintColor = .black
self.menuButton.isEnabled = true
//remove all crop before loading from firebase
self.myGarden = SHARED_GARDEN_LIST[gardenIndex]
self.myGarden.cropProfile.removeAll()
//self.cropList?.removeAll()
//retrieve Crops from the Firebase
let gardenID = self.myGarden.gardenID
let GardenRef = ref.child("Gardens/\(gardenID!)/CropList")
GardenRef.observeSingleEvent(of: .value, with: {(snapshot) in
for child in snapshot.children.allObjects as![DataSnapshot]{
print(child)
let cropObject=child.value as? [String:AnyObject]
let cropname=cropObject?["CropName"]
let area=cropObject?["SurfaceArea"]
let cropinfo=lib.searchByName(cropName: cropname as! String)
let newCrop=CropProfile(cropInfo: cropinfo!, profName: cropname as! String)
newCrop.cropID=child.key
newCrop.surfaceArea = area as? Double
print(newCrop.surfaceArea)
print(child.key)
_ = self.myGarden.AddCrop(New: newCrop)
}
self.cropList = self.myGarden.cropProfile
self.tableView.reloadData()
})
}
else {
// Hide and Disable Menu Button
self.menuButton.tintColor = .clear
self.menuButton.isEnabled = false
// Load local garden
self.myGarden = MY_GARDEN
self.cropList = MY_GARDEN.cropProfile
}
//self.myGarden = GardenList[gardenIndex]
//self.cropList = GardenList[gardenIndex]?.cropProfile
self.isExtended = nil
self.tableView.reloadData()
self.title = myGarden?.gardenName;
print("Number of Crops = ", myGarden!.getSize())
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if (cropList?[indexPath.row]) != nil {
return 120
} else {
return 155
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let data = cropList {
return data.count
} else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cellData = cropList?[indexPath.row] {
// Make regular Crop Cell
let cell = tableView.dequeueReusableCell(withIdentifier: "cropCell", for:indexPath) as! CropTableViewCell
let name: String? = cellData.cropName
if indexPath.row % 2 == 0 {
cell.backgroundColor = UIColor(red: 202.0/255.0, green: 225/255, blue: 200/255, alpha:1)
} else {
cell.backgroundColor = UIColor(red: 244.0/255.0, green: 254/255, blue: 217/255, alpha:1)
}
cell.cropLabel?.text = name
cell.cropImage?.image = UIImage(named: (cellData.getImage()))
cell.deleteButton.addTarget(self, action: #selector(GardenCropList.deleteCrop), for: .touchUpInside)
cell.deleteButton.tag = indexPath.row
cell.detailsButton.addTarget(self, action: #selector(GardenCropList.openCropDetails), for: .touchUpInside)
cell.detailsButton.tag = indexPath.row
return cell
} else{
//Make Expanded cell
let expandedCell = tableView.dequeueReusableCell(withIdentifier: "ExpandedCropCell", for:indexPath) as! ExpandedCropCell
if let surface = cropList?[indexPath.row - 1]?.surfaceArea {
expandedCell.plotSize.text = String(surface)
} else {
expandedCell.plotSize.text = ""
expandedCell.plotSize.placeholder = "cm^2"
}
expandedCell.waterAmount.text = "0.0 mL"
if !self.Online!{
let indexSet = NSMutableIndexSet()
let array = cropList?[self.isExtended!]?.notif.scheduleDays
expandedCell.timeField.placeholder = MY_GARDEN.cropProfile[self.isExtended!]?.notif.getTimeString()
array?.forEach(indexSet.add)
expandedCell.selectDays.selectedSegmentIndexes = indexSet as IndexSet?
expandedCell.enableReminder.setOn((MY_GARDEN.cropProfile[self.isExtended!]?.notif.enabled)!, animated: true)
}
expandedCell.waterButton.addTarget(self, action: #selector(GardenCropList.updateWaterAmount), for: .touchUpInside)
expandedCell.enableReminder.addTarget(self, action: #selector(GardenCropList.updateScheduleEnabled), for: .valueChanged)
expandedCell.selectDays.addTarget(self, action: #selector(GardenCropList.updateScheduleWeekdays), for: .valueChanged)
expandedCell.timeField.addTarget(self, action: #selector(GardenCropList.updateScheduleTime), for: .editingDidEnd)
expandedCell.plotSize.addTarget(self, action: #selector(GardenCropList.updatePlotSize), for: .editingDidEnd)
return expandedCell
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
myIndex = indexPath.row
if (indexPath.row + 1 >= (cropList?.count)!){
expandCell(tableView: tableView, index: indexPath.row)
} else {
if (cropList?[indexPath.row + 1] != nil) {
expandCell(tableView: tableView, index: myIndex)
} else {
contractCell(tableView: tableView, index: myIndex)
}
}
}
@objc func openCropDetails(sender: UIButton){
self.myIndex = sender.tag
performSegue(withIdentifier: "CropProfileSegue", sender: self)
}
@objc func updateScheduleTime(sender: UITextField){
let timeString = sender.text!
// Scrapes textfield and converts time string into int values for hour and minute
for (index, char) in timeString.enumerated() {
if char == ":"{
var hourIndex = timeString.index(timeString.startIndex, offsetBy: index)
var hour = Int(timeString.prefix(upTo: hourIndex))!
hourIndex = timeString.index(timeString.startIndex, offsetBy: index + 1)
let minuteIndex = timeString.index(hourIndex, offsetBy: index + 2)
let minute = (timeString[hourIndex..<minuteIndex] as NSString).intValue
let AM_PM = timeString.index(timeString.endIndex, offsetBy: -2)
if timeString.suffix(from: AM_PM) == "PM" && hour != 12{
hour += 12
} else if timeString.suffix(from: AM_PM) == "AM" && hour == 12 {
hour += 12
}
MY_GARDEN.cropProfile[self.isExtended!]?.notif.setTimeString(time: timeString)
MY_GARDEN.cropProfile[self.isExtended!]?.notif.setTimeOfDay(Hour: hour, Minute: Int(minute))
let message = "Remember to water your " + (MY_GARDEN.cropProfile[self.isExtended!]?.GetCropName())! + "!"
MY_GARDEN.cropProfile[self.isExtended!]?.notif.scheduleEachWeekday(msg: message)
break
}
}
}
@objc func updatePlotSize(sender: UITextField){
if let newSize = sender.text {
if !self.Online!{
MY_GARDEN.cropProfile[self.isExtended!]?.setSurfaceArea(area: Double(newSize)!)
} else {
SHARED_GARDEN_LIST[self.gardenIndex]?.cropProfile[self.isExtended!]?.setSurfaceArea(area: Double(newSize)!)
}
}
}
@objc func updateScheduleEnabled(sender: UISwitch){
if !self.Online!{
MY_GARDEN.cropProfile[self.isExtended!]?.notif.enabled = sender.isOn
if !sender.isOn{
MY_GARDEN.cropProfile[self.isExtended!]?.notif.disableNotifications()
} else {
let message = "Remember to water your " + (MY_GARDEN.cropProfile[self.isExtended!]?.GetCropName())! + "!"
MY_GARDEN.cropProfile[self.isExtended!]?.notif.scheduleEachWeekday(msg: message)
}
}
}
// Water Button is Clicked
@objc func updateWaterAmount(sender: UIButton){
let midGrowth = cropList?[self.isExtended!]?.GetWateringVariable().getMid()
weather.UpdateWaterRequirements(coEfficient: midGrowth!)
let indexPath = IndexPath(row: self.isExtended! + 1, section: 0)
guard let cell = tableView.cellForRow(at: indexPath) as? ExpandedCropCell else {return}
if cell.plotSize.text != "" {
if let surfaceArea = cropList?[self.isExtended!]?.surfaceArea{
var waterAmnt = Double(weather.GetWaterRequirements())/10*surfaceArea
waterAmnt = Double( round(100*waterAmnt)/100)
cell.waterAmount.text = String(waterAmnt) + " mL"
} else {
print("No surface Area")
}
}
}
// Looks at multisegmented control in extended TableViewCell
// Sets the days of the week for notifications
@objc func updateScheduleWeekdays(sender: MultiSelectSegmentedControl){
let selectedIndices = Array(sender.selectedSegmentIndexes)
if !self.Online!{
MY_GARDEN.cropProfile[self.isExtended!]?.notif.setScheduleDays(days: selectedIndices)
let message = "Remember to water your " + (MY_GARDEN.cropProfile[self.isExtended!]?.GetCropName())! + "!"
MY_GARDEN.cropProfile[self.isExtended!]?.notif.scheduleEachWeekday(msg: message)
}
}
//Delete a selected crop from a garden
@objc func deleteCrop(sender: UIButton){
let passedIndex = sender.tag
let alert = UIAlertController(title: "Remove Crop from Garden?", message: myGarden.cropProfile[passedIndex]?.GetCropName(), preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.default, handler: { (action) in
alert.dismiss(animated:true, completion:nil)
if passedIndex == self.isExtended{
self.contractCell(tableView: self.tableView, index: passedIndex)
}
if self.Online!{
let cropid=self.myGarden.cropProfile[passedIndex]?.cropID
self.RemoveCropFromFB(cropid!)
//print(cropid)
}else{
let core = self.myGarden.cropProfile[passedIndex]?.coreData
self.removeFromCore(cropCore: core!)
}
self.cropList?.remove(at: passedIndex)
self.myGarden.cropProfile.remove(at: passedIndex)
self.tableView.reloadData()
}))
alert.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.default, handler: { (action) in
alert.dismiss(animated:true, completion:nil)
print("no delete")
}))
self.present(alert, animated:true, completion:nil)
self.tableView.reloadData()
}
func RemoveCropFromFB(_ id:String){
let gardenID=myGarden.gardenID
let CropRef=ref.child("Gardens/\(gardenID!)/CropList/\(id)")
CropRef.removeValue()
print("Removed!")
}
func removeFromCore(cropCore : NSManagedObject){
PersistenceService.context.delete(cropCore)
PersistenceService.saveContext()
print("Deleted")
}
/* Expand cell at given index */
private func expandCell(tableView: UITableView, index: Int) {
// Expand Cell -> add ExpansionCells
if (cropList?[index]) != nil {
// If a cell is currently expanded, close it before opening another
if let Extended = self.isExtended{
cropList?.remove(at: Extended + 1)
if (index > Extended){
// Selected cell is greater than currently expanded cell
tableView.deleteRows(at: [NSIndexPath(row: Extended+1, section: 0) as IndexPath], with: .top)
self.isExtended = index - 1
cropList?.insert(nil, at: index)
tableView.insertRows(at: [NSIndexPath(row: index, section: 0) as IndexPath] , with: .top)
} else if (index<Extended) {
// Selected cell is less than currently expanded cell
tableView.deleteRows(at: [NSIndexPath(row: Extended+1, section: 0) as IndexPath], with: .bottom)
self.isExtended = index
cropList?.insert(nil, at: index+1)
tableView.insertRows(at: [NSIndexPath(row: index+1, section: 0) as IndexPath] , with: .top)
}
} else {
// If no cell is currently expanded, just expand
cropList?.insert(nil, at: index + 1)
self.isExtended = index
tableView.insertRows(at: [NSIndexPath(row: index + 1, section: 0) as IndexPath] , with: .top)
}
}
}
/* Contract cell at given index */
private func contractCell(tableView: UITableView, index: Int) {
if (cropList?[index]) != nil {
cropList?.remove(at: index+1)
self.isExtended = nil
tableView.deleteRows(at: [NSIndexPath(row: index+1, section: 0) as IndexPath], with: .top)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Prepare next viewcontrollers for segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "CropProfileSegue"{
let receiverVC = segue.destination as! CropProfileViewController
if self.isExtended != nil {
if self.myIndex > self.isExtended! {
receiverVC.crop = myGarden.cropProfile[myIndex - 1]
receiverVC.myIndex = self.myIndex - 1
}
}
receiverVC.crop = myGarden.cropProfile[myIndex]
receiverVC.myIndex = self.myIndex
receiverVC.garden = myGarden
}else if segue.identifier == "createCrop"{
let receiverVC = segue.destination as! CropCreateVC
receiverVC.gardenIndex = gardenIndex
receiverVC.Online = self.Online
}
else if segue.identifier == "showMap"{
let receiverVC = segue.destination as!MapVC
receiverVC.gardenIndex=gardenIndex
receiverVC.garden=myGarden
}
else if segue.identifier == "showMember"{
let receiverVC = segue.destination as!MemberList
receiverVC.garden=myGarden
}
}
}
|
//
// AudioRecordable.swift
// AudioProcessorPackageDescription
//
// Created by Sam Meech-Ward on 2017-11-21.
//
import Foundation
/// Some sort of recorder
public protocol AudioRecordable {
/// Start Recording
func start(closure: (@escaping (_ successfully: Bool) -> ()))
/// Stop Recording
func stop(closure: (@escaping (_ successfully: Bool) -> ()))
/// The time, in seconds, since the beginning of the recording.
var currentTime: TimeInterval { get }
/// True if recording, false otherwise.
var isRecording: Bool { get }
}
public protocol AudioPowerTracker {
/**
The current average power, in decibels, for the sound being recorded. A return value of 0 dB indicates full scale, or maximum power; a return value of -160 dB indicates minimum power (that is, near silence).
- parameter: channelNumber: The number of the channel that you want the average power value for.
*/
func averageDecibelPower(forChannel channelNumber: Int) -> Float
}
public protocol AudioAmplitudeTracker {
/// Detected amplitude
var amplitude: Double? { get }
/// Detected amplitude
var rightAmplitude: Double? { get }
/// Detected amplitude
var leftAmplitude: Double? { get }
}
public protocol AudioFrequencyTracker {
/// Detected frequency
var frequency: Double? { get }
}
|
//
// ViewController.swift
// UnFlare
//
// Created by Floris Chabert on 9/3/16.
// Copyright © 2016 Floris Chabert. All rights reserved.
//
import UIKit
import Photos
class ViewCell : UICollectionViewCell {
var asset: PHAsset?
@IBOutlet weak var imageView: UIImageView!
}
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, ZoomTransitionProtocol {
var assets: PHFetchResult<PHAsset>?
var status: PHAuthorizationStatus?
var selectedIndexPath: IndexPath?
var animationController: ZoomTransition?
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.toolbar.isHidden = true
if let navigationController = self.navigationController {
animationController = ZoomTransition(navigationController: navigationController)
}
navigationController?.delegate = animationController
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
collectionView?.reloadData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
PHPhotoLibrary.requestAuthorization { status in
if self.status != status {
self.status = status
self.updateUI()
}
}
}
func updateUI() {
if status == .denied {
DispatchQueue.main.async {
self.performSegue(withIdentifier: "Denied", sender: self)
}
}
else {
DispatchQueue.global().async {
let options = PHFetchOptions()
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
self.assets = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: options)
DispatchQueue.main.async {
self.collectionView?.reloadData()
let lastItem = self.collectionView?.numberOfItems(inSection: 0)
let indexPath = IndexPath(item: lastItem!-1, section: 0)
self.collectionView?.scrollToItem(at: indexPath, at: .bottom, animated: false)
}
}
}
}
override func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool {
return false
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return assets?.count ?? 0
}
func collectionView(_ collection: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let photosPerRow = UIDevice.current.orientation.isLandscape ? 6 : 4
let size = Int(view.bounds.size.width)/photosPerRow
let remainer = Int(view.bounds.size.width) % photosPerRow
let width = indexPath.row % photosPerRow != photosPerRow-1 ? size-1 : size + remainer
return CGSize(width: width, height: size)
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ViewCell
let asset = assets!.object(at: indexPath.row)
cell.asset = asset
let options = PHImageRequestOptions()
options.resizeMode = .exact
options.isSynchronous = true
let retinaScale = UIScreen.main.scale;
let retinaSquare = CGSize(width: 100*retinaScale, height: 100*retinaScale)
let cropSideLength = min(asset.pixelWidth, asset.pixelHeight)
let x = asset.pixelWidth > asset.pixelHeight ? abs(asset.pixelWidth - asset.pixelHeight) / 2 : 0
let y = asset.pixelWidth > asset.pixelHeight ? 0 : abs(asset.pixelWidth - asset.pixelHeight) / 2
let square = CGRect(x: x, y: y, width: cropSideLength, height: cropSideLength)
let cropRect = square.applying(CGAffineTransform(scaleX: 1.0 / CGFloat(asset.pixelWidth), y: 1.0 / CGFloat(asset.pixelHeight)))
options.normalizedCropRect = cropRect
PHImageManager.default().requestImage(for: asset, targetSize: retinaSquare, contentMode: .aspectFit, options: options, resultHandler: {(result, info)->Void in
DispatchQueue.main.async {
cell.imageView.image = result
}
})
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedIndexPath = indexPath
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Photo" {
let cell = sender as! ViewCell
let imageViewController = segue.destination as! ImageViewController
imageViewController.asset = cell.asset
}
}
func viewForTransition() -> UIView {
collectionView?.layoutIfNeeded()
return (collectionView?.cellForItem(at: selectedIndexPath!) as! ViewCell).imageView
}
}
|
//
// MusicalGenre.swift
// Metronome
//
// Created by Jocelyn Griselle on 25/04/2020.
// Copyright © 2020 Jocelyn Griselle. All rights reserved.
//
import SwiftUI
import CoreLocation
import AVFoundation
//struct MusicalGenres {
// static let genres = [dancehall, hiphop, bosseSamba]
// static let dancehall = MusicalGenre(imageName: "wave", name: "Dancehall", song: "dancehall_hip", bpm: 98.0)
// static let hiphop = MusicalGenre(image: Image("wave"), name: "Hip-Hop", song: "acoustic_hiphop", bpm: 140.0)
// static let bosseSamba = MusicalGenre(image: Image("wave"), name: "Samba", song: "bossa_samba_acoustic", bpm: 80.0)
//}
struct MusicalGenre: Hashable, Codable, Identifiable {
var id : Int
var name : String
var bpm : Float
var minBpm : Float
var maxBpm : Float
var description : String
var descriptionTempo : String
var category: Category
fileprivate var imageName : String
fileprivate var loopName : String
var isFavorite: Bool
var isFeatured: Bool
enum Category: String, CaseIterable, Codable, Hashable {
case electro = "Electro"
case jazz = "Jazz"
case raggae = "Raggae"
case rock = "Rock"
case blues = "Blues"
case world = "World Music"
}
}
//fileprivate var loopName : String
// init(image: Image, name : String, song : String, bpm : Float) {
// self.id = UUID()
// self.image = image
// self.name = name
// self.song = song
// self.bpm = bpm
//
// if let url = Bundle.main.url(forResource: song, withExtension: "wav") {
// do {
// self.file = try AVAudioFile(forReading: url)
// }
// catch {
// print("CAN'T READ FILE")
// self.file = nil
// }
// } else {
// self.file = nil
// print("NOFILE")
// }
// }
//}
// var loop: AVAudioFile {
// //AVAudioFile
// ImageStore.shared.image(name: imageName)
// }
extension MusicalGenre {
var image: Image {
ImageStore.shared.image(name: imageName)
}
var cgImage: CGImage {
ImageStore.shared.cgImage(name: imageName)
}
}
extension MusicalGenre {
var loop: AVAudioFile {
//LoopStore.shared.loop(name: loopName)
guard
let url = Bundle.main.url(forResource: "\(loopName)", withExtension: "wav")//,subdirectory: "Resources")
else {
fatalError("Couldn't load loop \(name).wav from main bundle.")
}
do {
return try AVAudioFile(forReading: url)
}
catch {
fatalError("Couldn't convert loop \(name).wav from main bundle.")
}
}
}
|
//
// Breadth_Search.swift
// Algorithms
//
// Created by Loc Tran on 5/18/17.
// Copyright © 2017 LocTran. All rights reserved.
//
import Foundation
struct BFS_Step{
var act: String!
var point: String!
}
class BreadthFirstSearch{
var arrayAction: [BFS_Step]!
init() {
var adjacencyList = AdjacencyList<String>()
let s = adjacencyList.createVertex(data: "S")
let a = adjacencyList.createVertex(data: "A")
let b = adjacencyList.createVertex(data: "B")
let c = adjacencyList.createVertex(data: "C")
let d = adjacencyList.createVertex(data: "D")
let f = adjacencyList.createVertex(data: "F")
let g = adjacencyList.createVertex(data: "G")
let e = adjacencyList.createVertex(data: "E")
adjacencyList.add(.undirected, from: s, to: a)
adjacencyList.add(.undirected, from: a, to: b)
adjacencyList.add(.undirected, from: a, to: d)
adjacencyList.add(.undirected, from: a, to: c)
// adjacencyList.add(.undirected, from: b, to: d)
adjacencyList.add(.undirected, from: d, to: g)
adjacencyList.add(.undirected, from: d, to: f)
adjacencyList.add(.undirected, from: f, to: e)
// adjacencyList.breadthFirstSearch(from: s, to: e)
self.arrayAction = adjacencyList.breadthFirstSearch(from: s, to: e)
}
}
extension Graphable {
public mutating func breadthFirstSearch(from source: Vertex<Element>, to destination: Vertex<Element>)
-> [BFS_Step] {
var arrayAction = [BFS_Step]()
var queue = Queue<Vertex<Element>>()
queue.enqueue(source)
var visits : [Vertex<Element> : Visit<Element>] = [source: .source] // 1
while let visitedVertex = queue.dequeue() {
// var a = visitedVertex as! String
arrayAction.append(BFS_Step(act: "putOut", point: "\(visitedVertex)"))
// TODO: Replace this...
if visitedVertex == destination {
var vertex = destination // 1
var route : [Edge<Element>] = [] // 2
while let visit = visits[vertex],
case .edge(let edge) = visit { // 3
route = [edge] + route
vertex = edge.source // 4
}
// return route // 5
return arrayAction
}
let neighbourEdges = edges(from: visitedVertex) ?? []
for edge in neighbourEdges {
if visits[edge.destination] == nil { // 2
queue.enqueue(edge.destination)
arrayAction.append(BFS_Step(act: "destination", point: "\(edge.destination)"))
visits[edge.destination] = .edge(edge) // 3
}
}
}
return arrayAction
}
}
|
//
// Place.swift
// ProjetParking
//
// Created by on 31/01/2018.
// Copyright © 2018 com.iut-bm.univ. All rights reserved.
//
import Foundation
class Place {
var id: Int16
var adresse: String
var prixHoraire: Double
var surveiller: Int16
var souterrain: Int16
var dispo: Int16
var idUtilisateur: Int16
init(id: Int16, adresse: String, prixHoraire: Double, surveiller: Int16, souterrain: Int16, dispo: Int16, idUtilisateur: Int16) {
self.id = id
self.adresse = adresse
self.prixHoraire = prixHoraire
self.surveiller = surveiller
self.souterrain = souterrain
self.dispo = dispo
self.idUtilisateur = idUtilisateur
}
init() {
self.id = 0
self.adresse = ""
self.prixHoraire = 0
self.surveiller = 1
self.souterrain = 1
self.dispo = 1
self.idUtilisateur = 0
}
init?(json: [String: Any]) {
guard let id = json["id"] as? String,
let adresse = json["adresse"] as? String,
let prixHoraire = json["prix_horaire"] as? String,
let surveiller = json["is_surveille"] as? String,
let souterrain = json["is_souterrain"] as? String,
let dispo = json["is_dispo"] as? String,
let idUtilisateur = json["id_utilisateur"] as? String
else { return nil }
self.id = Int16(id)!
self.adresse = adresse
self.prixHoraire = Double(prixHoraire)!
self.surveiller = Int16(surveiller)!
self.souterrain = Int16(souterrain)!
self.dispo = Int16(dispo)!
self.idUtilisateur = Int16(idUtilisateur)!
}
}
|
//
// InvestMentHeaderVIew.swift
// CoAssets-Agent
//
// Created by Macintosh HD on 12/16/15.
// Copyright © 2015 Nikmesoft Ltd. All rights reserved.
//
import UIKit
class InvestmentHeaderVIew: BaseView {
override func viewDidLoad() {
super.viewDidLoad()
}
}
|
//
// ViewController.swift
// GUCustomizeViewsExamples
//
// Created by 默司 on 2016/8/26.
// Copyright © 2016年 默司. All rights reserved.
//
import UIKit
import GUCustomizeViews
class ViewController: UIViewController {
@IBOutlet weak var textField: GUTextFieldView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func show(sender: AnyObject) {
textField.setError("This is error")
}
@IBAction func hide(sender: AnyObject) {
textField.setError(nil)
}
}
|
//
// WeatherModeEnum.swift
// OpenWeatherMapKit
//
// Created by Anver Bogatov on 06/04/2018.
// Copyright © 2018 Anver Bogatov. All rights reserved.
//
import Foundation
/// Weather mode for which forecast must be retrieved.
///
/// - current: current weather data
/// - fiveDays: forecast for next 5 days
enum WeatherMode {
case current
case fiveDays
}
|
//
// File.swift
//
//
// Created by Zhu Shengqi on 2019/8/6.
//
#if os(iOS)
import Foundation
import UIKit
extension PageViewController {
public struct VerticalPagingLayouter: PageViewControllerContentLayouting {
public init() {}
public var shouldScrollViewAlwaysBounceHorizontal: Bool {
return false
}
public var shouldScrollViewAlwaysBounceVertical: Bool {
return true
}
public func calculateCanvasSize(containerSize: CGSize, pagesCount: Int) -> CGSize {
return CGSize(width: containerSize.width, height: containerSize.height * CGFloat(pagesCount))
}
public func calculateCurrentIndex(containerSize: CGSize, contentOffset: CGPoint) -> Int {
return Int((contentOffset.y / containerSize.height).rounded())
}
public func calculatePageFrame(at index: Int, containerSize: CGSize) -> CGRect {
return CGRect(x: 0, y: CGFloat(index) * containerSize.height, width: containerSize.width, height: containerSize.height)
}
public func calculatePreferredContentOffset(forDisplayingPageAt index: Int, containerSize: CGSize) -> CGPoint {
let pageFrame = self.calculatePageFrame(at: index, containerSize: containerSize)
return pageFrame.origin
}
}
}
#endif
|
//
// BubbleGameObject.swift
// GameEngine
//
// Created by Teo Ming Yi on 11/2/17.
// Copyright © 2017 nus.cs3217.a0146749n. All rights reserved.
//
import Foundation
import UIKit
class BubbleGameObject: BubbleModel, GameObject {
var physics: PhysicsComponent
var graphics: GraphicsComponent?
init(physics: PhysicsComponent, graphics: GraphicsComponent, type: BubbleType) {
self.physics = physics
self.graphics = graphics
super.init(type: type)
}
required init(coder: NSCoder) {
physics = CirclePhysicsComponent(radius: Constants.BUBBLE_RADIUS,
center: Constants.UPCOMING_BUBBLE_POSITION,
velocity: Constants.STATIONARY_VELOCITY,
direction: Constants.ZERO_VECTOR)
super.init(coder: coder)
}
func update(timeElapsed: TimeInterval) {
physics.update(timeElapsed: timeElapsed)
graphics?.update()
}
func loadInCannon(launchPoint: CGPoint) {
if let physicsCircle = physics as? CirclePhysicsComponent {
physicsCircle.center = launchPoint
}
if let bubbleView = graphics as? BubbleView {
bubbleView.center = launchPoint
}
}
}
|
//
// CharacterMoveView.swift
// SuperSmashBrosStats
//
// Created by Kamaal Farah on 18/06/2020.
// Copyright © 2020 Kamaal. All rights reserved.
//
import SwiftUI
struct CharacterMoveView: View {
@State private var expandMovesDetails = false
let move: CodableCharacterMoves
var body: some View {
Button(action: self.expandMoveAction) {
HStack {
VStack(alignment: .leading) {
Text(self.move.name)
.font(.body)
.foregroundColor(.accentColor)
if self.expandMovesDetails {
ForEach(self.move.unwrappedMoveStats.keys.sorted(), id: \.self) { key in
Text("\(key): \(self.move.unwrappedMoveStats[key] ?? "")")
.font(.body)
}
}
}
Spacer()
VStack {
Image(systemName: "chevron.right")
.imageScale(.medium)
.foregroundColor(.gray)
.rotationEffect(.degrees(self.chevronAngle))
.padding(.top, self.expandMovesDetails ? 16 : 0)
if self.expandMovesDetails {
Spacer()
}
}
}
}
}
private var chevronAngle: Double {
if self.expandMovesDetails { return 90 }
return 0
}
private func expandMoveAction() {
if self.expandMovesDetails {
withAnimation { self.expandMovesDetails = false }
} else {
withAnimation { self.expandMovesDetails = true }
}
}
}
//struct CharacterMoveView_Previews: PreviewProvider {
// static var previews: some View {
// CharacterMoveView()
// }
//}
|
//
// ViewController.swift
// Amusment Park Pass Generator: Part 2
//
// Created by Joe Sherratt on 24/07/2016.
// Copyright © 2016 jsherratt. All rights reserved.
//
import UIKit
class CreatePassViewController: UIViewController, UITextFieldDelegate {
//-----------------------
//MARK: Enum
//-----------------------
enum EntrantType {
case Guest
case Employee
case Manger
case Contractor
case Vendor
case None
}
//-----------------------
//MARK: Variables
//-----------------------
let kioskControl = KioskControl()
var guest: Entrant?
var entrantStackView: EntrantType = .None
var selectedEntrant: EntrantType = .None
var selectedEntrantSubtype: PassType = .None
var selectedContractProjectNumber: ProjectNumber?
var selectedVendorCompany: Company?
//-----------------------
//MARK: Outlets
//-----------------------
//Constraints
@IBOutlet weak var dateOfBirthStackViewConstraint: NSLayoutConstraint!
@IBOutlet weak var cityStackViewConstraint: NSLayoutConstraint!
@IBOutlet weak var companyStackViewConstraint: NSLayoutConstraint!
//Stackview
@IBOutlet weak var entrantSubTypeStackView: UIStackView!
//Text fields
@IBOutlet weak var dateOfBirthTextField: TextField!
@IBOutlet weak var ssnTextField: TextField!
@IBOutlet weak var projectNumberTextField: TextField!
@IBOutlet weak var dateOfVisitTextField: TextField!
@IBOutlet weak var firstNameTextField: TextField!
@IBOutlet weak var lastNameTextField: TextField!
@IBOutlet weak var companyTextField: TextField!
@IBOutlet weak var addressTextField: TextField!
@IBOutlet weak var cityTextField: TextField!
@IBOutlet weak var stateTextField: TextField!
@IBOutlet weak var zipCodeTextField: TextField!
//Array of all the text fields
@IBOutlet var textFieldArray: [TextField]!
//-----------------------
//MARK: Views
//-----------------------
override func viewDidLoad() {
super.viewDidLoad()
//Set the delegate for each text field
for textField in textFieldArray {
textField.delegate = self
}
//Add tap gesture recognizer to dismiss the keyboard when the user taps outside of the text field
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
view.addGestureRecognizer(tapGestureRecognizer)
//Add notification observers when the keyboard shows and hides
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
//Reset everything on return to the view. For example when the user presses create new pass in the pass view controller
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
guest = nil
selectedEntrant = .None
selectedEntrantSubtype = .None
selectedContractProjectNumber = nil
selectedVendorCompany = nil
resetTextFields()
removeButtonsFromStackView()
}
//-----------------------
//MARK: Button Actions
//-----------------------
//Generating the stackview of entrant subtypes from the selected entrant
@IBAction func selectEntrantToPopulateStackView(sender: UIButton) {
let buttonTitle = sender.currentTitle!
switch buttonTitle {
case "Guest":
resetTextFields()
selectedEntrant = .Guest
createEntrantSubTypeStackView(withEntant: .Guest)
case "Employee":
resetTextFields()
selectedEntrant = .Employee
createEntrantSubTypeStackView(withEntant: .Employee)
case "Manager":
resetTextFields()
selectedEntrant = .Manger
createEntrantSubTypeStackView(withEntant: .Manger)
case "Contractor":
resetTextFields()
selectedEntrant = .Contractor
createEntrantSubTypeStackView(withEntant: .Contractor)
case "Vendor":
resetTextFields()
selectedEntrant = .Vendor
createEntrantSubTypeStackView(withEntant: .Vendor)
default:
return
}
}
//Generate a pass from the selected entrant subtype
@IBAction func generatePass(sender: UIButton) {
switch selectedEntrantSubtype {
case .ChildGuestPass:
do {
let childGuest = try Guest(dateOfbirth: dateOfBirthTextField.text!, guestType: .FreeChild)
guest = childGuest
}catch Error.MissingDateOfBirth {
displayAlert("Error", message: "You must enter a date of birth")
}catch Error.ChildOlderThanFive {
displayAlert("Error", message: "Child is older than five. Please select adult guest")
}catch let error {
print(error)
}
case .AdultGuestPass:
createGuest(withGuestType: .Adult)
case .SeniorGuestPass:
do {
let seniorGuest = try Guest(firstName: firstNameTextField.text, lastName: lastNameTextField.text, dateOfbirth: dateOfBirthTextField.text, guestType: .Senior)
guest = seniorGuest
}catch Error.MissingDateOfBirth {
displayAlert("Error", message: "You must enter a date of birth")
}catch Error.MissingName {
displayAlert("Error", message: "You must enter a first and a last name")
}catch let error {
print(error)
}
case .VIPGuestPass:
createGuest(withGuestType: .VIP)
case .SeasonGuestPass:
do {
let seasonGuest = try Guest(firstName: firstNameTextField.text, lastName: lastNameTextField.text, streetAddress: addressTextField.text, city: cityTextField.text, state: stateTextField.text, zipCode: Int(zipCodeTextField.text!), dateOfbirth: dateOfBirthTextField.text, guestType: .SeasonPass)
guest = seasonGuest
}catch Error.MissingDateOfBirth {
displayAlert("Error", message: "You must enter a date of birth")
}catch Error.MissingName {
displayAlert("Error", message: "You must enter a first and a last name")
}catch Error.MissingAddress {
displayAlert("Error", message: "You must enter an address, city, state and zip code")
}catch let error {
print(error)
}
case .FoodServicePass:
createHourlyEmployeeGuest(withWorkType: .FoodServices)
case .RideServicePass:
createHourlyEmployeeGuest(withWorkType: .RideServices)
case .MaintenancePass:
createHourlyEmployeeGuest(withWorkType: .Maintenance)
case .SeniorManagerPass:
createManagerGuest(withManagerType: .SeniorManager)
case .GeneralManagerPass:
createManagerGuest(withManagerType: .GeneralManager)
case .ShiftManagerPass:
createManagerGuest(withManagerType: .ShiftManager)
case .ContractorPass:
if let projectNumber = selectedContractProjectNumber {
createContractEmployeeGuest(withProjectNumber: projectNumber)
}
case .VendorPass:
if let vendorCompany = selectedVendorCompany {
createVendorGuest(withCompany: vendorCompany)
}
//If no entrant subtype has been selected alert the user to select one
case .None:
displayAlert("Error", message: "You must select an entrant")
}
//Check if a guest exists. If so create a pass for the guest and segue to the pass view controller
if var entrant = guest {
let pass = kioskControl.createPass(forEntrant: entrant)
entrant.pass = pass
guest = entrant
performSegueWithIdentifier("ShowPass", sender: self)
}
}
//Populate text fields with data based on the selected entrant
@IBAction func populateData(sender: UIButton) {
switch selectedEntrant {
case .Guest:
switch selectedEntrantSubtype {
case .ChildGuestPass:
dateOfBirthTextField.text = "05/15/2014"
case .AdultGuestPass, .VIPGuestPass:
dateOfBirthTextField.text = "05/15/1995"
case .SeniorGuestPass:
dateOfBirthTextField.text = "05/15/1985"
firstNameTextField.text = "John"
lastNameTextField.text = "Appleseed"
case .SeasonGuestPass:
dateOfBirthTextField.text = "05/15/1995"
firstNameTextField.text = "John"
lastNameTextField.text = "Appleseed"
addressTextField.text = "1 Infinte Loop"
cityTextField.text = "Cupertino"
stateTextField.text = "CA"
zipCodeTextField.text = "95014"
default:
return
}
case .Employee, .Manger, .Contractor:
dateOfBirthTextField.text = "05/15/1995"
ssnTextField.text = "324-58-7532"
firstNameTextField.text = "John"
lastNameTextField.text = "Appleseed"
addressTextField.text = "1 Infinte Loop"
cityTextField.text = "Cupertino"
stateTextField.text = "CA"
zipCodeTextField.text = "95014"
case .Vendor:
dateOfBirthTextField.text = "05/15/1995"
dateOfVisitTextField.text = "08/10/2016"
firstNameTextField.text = "John"
lastNameTextField.text = "Appleseed"
case .None:
displayAlert("Error", message: "You must select an entrant")
}
}
//-----------------------
//MARK: Functions
//-----------------------
//Set the selected entrant subtype and activate the text fields required based on the selected entrant subtype.
func selectedEntrantSubType(sender: UIButton) {
resetTextFields()
dateOfBirthTextField.changeState = true
let buttonTitle = sender.currentTitle!
switch selectedEntrant {
case .Guest:
switch buttonTitle {
case "Child":
selectedEntrantSubtype = .ChildGuestPass
case "Adult":
selectedEntrantSubtype = .AdultGuestPass
case "Senior":
selectedEntrantSubtype = .SeniorGuestPass
activateTextFieldsForSeniorGuests()
case "VIP":
selectedEntrantSubtype = .VIPGuestPass
case "Season Pass":
selectedEntrantSubtype = .SeasonGuestPass
activateTextFieldsForSeasonPassGuests()
default:
return
}
case .Employee:
switch buttonTitle {
case "Food Services":
selectedEntrantSubtype = .FoodServicePass
activateTextFieldsForEmployeesAndManagers()
case "Ride Services":
selectedEntrantSubtype = .RideServicePass
activateTextFieldsForEmployeesAndManagers()
case "Maintenance":
selectedEntrantSubtype = .MaintenancePass
activateTextFieldsForEmployeesAndManagers()
default:
return
}
case .Manger:
switch buttonTitle {
case "Senior":
selectedEntrantSubtype = .SeniorManagerPass
activateTextFieldsForEmployeesAndManagers()
case "General":
selectedEntrantSubtype = .GeneralManagerPass
activateTextFieldsForEmployeesAndManagers()
case "Shift":
selectedEntrantSubtype = .ShiftManagerPass
activateTextFieldsForEmployeesAndManagers()
default:
return
}
case .Contractor:
selectedEntrantSubtype = .ContractorPass
activateTextFieldsForContractors()
switch buttonTitle {
case "1001":
selectedContractProjectNumber = .oneThousandOne
projectNumberTextField.text = "1001"
case "1002":
selectedContractProjectNumber = .oneThousandTwo
projectNumberTextField.text = "1002"
case "1003":
selectedContractProjectNumber = .oneThousandThree
projectNumberTextField.text = "1003"
case "2001":
selectedContractProjectNumber = .twoThousandOne
projectNumberTextField.text = "2001"
case "2002":
selectedContractProjectNumber = .twoThousandTwo
projectNumberTextField.text = "2002"
default:
return
}
case .Vendor:
selectedEntrantSubtype = .VendorPass
activateTextFieldsForVendors()
switch buttonTitle {
case "Acme":
selectedVendorCompany = .Acme
companyTextField.text = "Acme"
case "Orkin":
selectedVendorCompany = .Orkin
companyTextField.text = "Orkin"
case "Fedex":
selectedVendorCompany = .Fedex
companyTextField.text = "Fedex"
case "NW Electrical":
selectedVendorCompany = .NWElectrical
companyTextField.text = "NW Electrical"
default:
return
}
default:
return
}
}
func activateTextFieldsForSeasonPassGuests() {
firstNameTextField.changeState = true
lastNameTextField.changeState = true
addressTextField.changeState = true
cityTextField.changeState = true
stateTextField.changeState = true
zipCodeTextField.changeState = true
}
func activateTextFieldsForSeniorGuests() {
firstNameTextField.changeState = true
lastNameTextField.changeState = true
}
func activateTextFieldsForEmployeesAndManagers() {
ssnTextField.changeState = true
firstNameTextField.changeState = true
lastNameTextField.changeState = true
addressTextField.changeState = true
cityTextField.changeState = true
stateTextField.changeState = true
zipCodeTextField.changeState = true
}
func activateTextFieldsForContractors() {
ssnTextField.changeState = true
projectNumberTextField.changeState = true
projectNumberTextField.enabled = false
firstNameTextField.changeState = true
lastNameTextField.changeState = true
addressTextField.changeState = true
cityTextField.changeState = true
stateTextField.changeState = true
zipCodeTextField.changeState = true
}
func activateTextFieldsForVendors() {
dateOfVisitTextField.changeState = true
firstNameTextField.changeState = true
lastNameTextField.changeState = true
companyTextField.changeState = true
companyTextField.enabled = false
}
//------------------------------
//MARK: Create Guest Functions
//------------------------------
//Create a basic guest
func createGuest(withGuestType type: Guests) {
do {
let basicGuest = try Guest(dateOfbirth: dateOfBirthTextField.text!, guestType: type)
guest = basicGuest
}catch Error.MissingDateOfBirth {
displayAlert("Error", message: "You must enter a date of birth")
}catch let error {
print(error)
}
}
//Create an employee guest
func createHourlyEmployeeGuest(withWorkType workType: WorkType) {
do {
let hourlyEmployeeGuest = try HourlyEmployee(firstName: firstNameTextField.text, lastName: lastNameTextField.text, streetAddress: addressTextField.text, city: cityTextField.text, state: stateTextField.text, zipCode: Int(zipCodeTextField.text!), socialSecurityNumber: Int(ssnTextField.text!.stringByReplacingOccurrencesOfString("-", withString: "")), dateOfBirth: dateOfBirthTextField.text, workType: workType)
guest = hourlyEmployeeGuest
}catch Error.MissingDateOfBirth {
displayAlert("Error", message: "You must enter a date of birth")
}catch Error.MissingSocialSecurityNumber {
displayAlert("Error", message: "You must enter a social security number")
}catch Error.MissingName {
displayAlert("Error", message: "You must enter a first and a last name")
}catch Error.MissingAddress {
displayAlert("Error", message: "You must enter an address, city, state and zip code")
}catch let error {
print(error)
}
}
//Create a contract employee guest
func createContractEmployeeGuest(withProjectNumber projectNumber: ProjectNumber) {
do {
let contractEmployeeGuest = try ContractEmployee(firstName: firstNameTextField.text, lastName: lastNameTextField.text, streetAddress: addressTextField.text, city: cityTextField.text, state: stateTextField.text, zipCode: Int(zipCodeTextField.text!), socialSecurityNumber: Int(ssnTextField.text!.stringByReplacingOccurrencesOfString("-", withString: "")), dateOfBirth: dateOfBirthTextField.text, projectNumber: projectNumber)
guest = contractEmployeeGuest
}catch Error.MissingDateOfBirth {
displayAlert("Error", message: "You must enter a date of birth")
}catch Error.MissingSocialSecurityNumber {
displayAlert("Error", message: "You must enter a social security number")
}catch Error.MissingName {
displayAlert("Error", message: "You must enter a first and a last name")
}catch Error.MissingAddress {
displayAlert("Error", message: "You must enter an address, city, state and zip code")
}catch let error {
print(error)
}
}
//Create a manager guest
func createManagerGuest(withManagerType manager: Managers) {
do {
let managerGuest = try Manager(firstName: firstNameTextField.text, lastName: lastNameTextField.text, streetAddress: addressTextField.text, city: cityTextField.text, state: stateTextField.text, zipCode: Int(zipCodeTextField.text!), socialSecurityNumber: Int(ssnTextField.text!.stringByReplacingOccurrencesOfString("-", withString: "")), dateOfBirth: dateOfBirthTextField.text, managerType: manager)
guest = managerGuest
}catch Error.MissingDateOfBirth {
displayAlert("Error", message: "You must enter a date of birth")
}catch Error.MissingSocialSecurityNumber {
displayAlert("Error", message: "You must enter a social security number")
}catch Error.MissingName {
displayAlert("Error", message: "You must enter a first and a last name")
}catch Error.MissingAddress {
displayAlert("Error", message: "You must enter an address, city, state and zip code")
}catch let error {
print(error)
}
}
//Create a vendor guest
func createVendorGuest(withCompany company: Company) {
do {
let vendorGuest = try Vendor(firstName: firstNameTextField.text, lastName: lastNameTextField.text, company: company, dateOfBirth: dateOfBirthTextField.text, dateOfVisit: dateOfVisitTextField.text)
guest = vendorGuest
}catch Error.MissingDateOfBirth {
displayAlert("Error", message: "You must enter a date of birth")
}catch Error.MissingSocialSecurityNumber {
displayAlert("Error", message: "You must enter a social security number")
}catch Error.MissingName {
displayAlert("Error", message: "You must enter a first and a last name")
}catch Error.MissingAddress {
displayAlert("Error", message: "You must enter an address, city, state and zip code")
}catch let error {
print(error)
}
}
//---------------------------
//MARK: StackView Functions
//---------------------------
//Function that create a button. Used for the stack view
func createButton(withTitle title: String, tag: Int, selector: Selector) -> UIButton {
let button = UIButton(type: .System)
button.tag = tag
button.tintColor = UIColor.whiteColor()
button.titleLabel?.font = UIFont.systemFontOfSize(15, weight: UIFontWeightMedium)
button.setTitle(title, forState: .Normal)
button.addTarget(self, action: selector, forControlEvents: .TouchUpInside)
return button
}
//Creates and adds buttons to the entrant subtype stack view. When a new entrant is selected, the previous buttons are removed and new ones are created.
func createEntrantSubTypeStackView(withEntant entrant: EntrantType) {
switch entrant {
case .Guest:
removeButtonsFromStackView()
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "Child", tag: 0, selector: #selector(selectedEntrantSubType)))
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "Adult", tag: 1, selector: #selector(selectedEntrantSubType)))
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "Senior", tag: 2, selector: #selector(selectedEntrantSubType)))
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "VIP", tag: 3, selector: #selector(selectedEntrantSubType)))
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "Season Pass", tag: 4, selector: #selector(selectedEntrantSubType)))
case .Employee:
removeButtonsFromStackView()
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "Food Services", tag: 0, selector: #selector(selectedEntrantSubType)))
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "Ride Services", tag: 1, selector: #selector(selectedEntrantSubType)))
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "Maintenance", tag: 2, selector: #selector(selectedEntrantSubType)))
case .Manger:
removeButtonsFromStackView()
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "Senior", tag: 0, selector: #selector(selectedEntrantSubType)))
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "General", tag: 1, selector: #selector(selectedEntrantSubType)))
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "Shift", tag: 2, selector: #selector(selectedEntrantSubType)))
case .Contractor:
removeButtonsFromStackView()
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "1001", tag: 0, selector: #selector(selectedEntrantSubType)))
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "1002", tag: 1, selector: #selector(selectedEntrantSubType)))
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "1003", tag: 2, selector: #selector(selectedEntrantSubType)))
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "2001", tag: 2, selector: #selector(selectedEntrantSubType)))
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "2002", tag: 2, selector: #selector(selectedEntrantSubType)))
case .Vendor:
removeButtonsFromStackView()
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "Acme", tag: 0, selector: #selector(selectedEntrantSubType)))
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "Orkin", tag: 1, selector: #selector(selectedEntrantSubType)))
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "Fedex", tag: 2, selector: #selector(selectedEntrantSubType)))
entrantSubTypeStackView.addArrangedSubview(createButton(withTitle: "NW Electrical", tag: 2, selector: #selector(selectedEntrantSubType)))
case .None:
removeButtonsFromStackView()
}
}
//Function to remove current buttons from stack view
func removeButtonsFromStackView() {
for button in entrantSubTypeStackView.arrangedSubviews {
entrantSubTypeStackView.removeArrangedSubview(button)
button.removeFromSuperview()
}
}
//Function to reset all text fields
func resetTextFields() {
selectedContractProjectNumber = nil
selectedVendorCompany = nil
for textField in textFieldArray {
textField.changeState = false
textField.text = nil
}
}
//---------------------------
//MARK: Prepare For Segue
//---------------------------
//Assign the guest variable in the PassViewController to the guest variable in this viewController. Allows passing data between view controllers
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowPass" {
if let vc = segue.destinationViewController as? PassViewController {
vc.guest = guest
}
}
}
//---------------------------
//MARK: Text Field Delegate
//---------------------------
//Dismiss the keyboard
func dismissKeyboard() {
view.endEditing(true)
}
//As the user is active in the text field
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
//Only allow number input to text fields that require numbers only
if textField == dateOfBirthTextField || textField == ssnTextField || textField == projectNumberTextField || textField == dateOfVisitTextField || textField == zipCodeTextField {
let numberOnly = NSCharacterSet.init(charactersInString: "0123456789/-")
let stringFromTextField = NSCharacterSet.init(charactersInString: string)
let stringValid = numberOnly.isSupersetOfSet(stringFromTextField)
return stringValid
}
//Only allow character input in text fields that require characters only
if textField == firstNameTextField || textField == lastNameTextField || textField == companyTextField || textField == cityTextField || textField == stateTextField {
let charactersOnly = NSCharacterSet.init(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ")
let stringFromTextField = NSCharacterSet.init(charactersInString: string)
let stringValid = charactersOnly.isSupersetOfSet(stringFromTextField)
return stringValid
}
return true
}
//-----------------------
//MARK: Keyboard
//-----------------------
//Adjust constraints when keyboard shows
func keyboardWillShow(notification: NSNotification) {
UIView.animateWithDuration(2.0, animations: {
self.dateOfBirthStackViewConstraint.constant = 20
self.cityStackViewConstraint.constant = 20
self.companyStackViewConstraint.constant = 20
self.view.layoutIfNeeded()
})
}
//Adjust constraints when keyboard hides
func keyboardWillHide(notification: NSNotification) {
UIView.animateWithDuration(2.0, animations: {
self.dateOfBirthStackViewConstraint.constant = 50
self.cityStackViewConstraint.constant = 40
self.companyStackViewConstraint.constant = 40
self.view.layoutIfNeeded()
})
}
//Deinit both of the notification observers
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
//-----------------------
//MARK: Extra
//-----------------------
override func prefersStatusBarHidden() -> Bool {
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
//
// Resolver+ResolverRegistering.swift
// FoodicsAssesment
//
// Created by mohamed gamal on 12/17/20.
//
import Foundation
extension ContainerIdentifier {
public static var local = ContainerIdentifier(id: "Local")
public static var remote = ContainerIdentifier(id: "remote")
}
extension Resolver: ResolverRegistering {
public static func registerAllServices() {
registerNetworkLayerContainers()
registerCategoriesContainers()
registerProductsContainers()
registerCategoriesRepository()
registerProductsRepository()
}
static func registerCategoriesRepository() {
register { CategoriesRepository() as CategoriesRepositoryProtocol}.scope(Resolver.application)
register( name: .local,
factory: { LocalCategoriesDataSource() as CategoriesDataSource })
.scope(application)
register( name: .remote,
factory: { RemoteCategoriesDataSource() as CategoriesDataSource })
.scope(application)
}
static func registerProductsRepository() {
register { ProductsRepository() as ProductsRepositoryProtocol}.scope(Resolver.application)
register( name: .local,
factory: { LocalProductsDataSource() as ProductsDataSource })
.scope(application)
register( name: .remote,
factory: { RemoteProductsDataSource() as ProductsDataSource })
.scope(application)
}
}
|
import XCTest
import FrameworkBTests
var tests = [XCTestCaseEntry]()
tests += FrameworkBTests.allTests()
XCTMain(tests)
|
//
// ChatViewController.swift
// Bloom
//
// Created by Жарас on 25.04.17.
// Copyright © 2017 asamasa. All rights reserved.
//
import UIKit
import SwiftyJSON
import Starscream
class ChatViewController: UIViewController, WebSocketDelegate, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableOfDialogs: UITableView!
var isUser: Bool = true
var data: ChatData = ChatData()
var socket: WebSocket!
override func viewDidLoad() {
getDialogs()
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.getMessage(_:)), name: NSNotification.Name(rawValue: "ownMessage"), object: nil)
connectToServer()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getDialogs(){
APIManager.sharedInstance.chatGetAllDialogs(onSuccess: {(json) in
print(json)
if json.count != 0{
for dialog in json.array!{
if dialog["creator"]["id"].int! == 3{
self.isUser = true
}else if dialog["receiver"]["id"].int! == 3{
self.isUser = false
}
let _dialog = chatDialog(dialog["id"].int!,dialog["creator"]["id"].int!,dialog["receiver"]["id"].int!,dialog["created_at"].string!)
//Data for USER ------------------------------------
if self.isUser{
if let name = dialog["receiver"]["name"].string{ _dialog.partner_name = name }
if let surname = dialog["receiver"]["surname"].string{ _dialog.partner_surname = surname }
}else{
if let name = dialog["creator"]["name"].string{ _dialog.partner_name = name }
if let surname = dialog["creator"]["surname"].string{ _dialog.partner_surname = surname }
}
//---------------------------------------------
APIManager.sharedInstance.chatGetMessagesOfDialog(dialog_id: _dialog.id,onSuccess: { (json) in
if json.count != 0{
var arrayOfMessages: [chatMessage] = Array()
DispatchQueue.global().sync {
for message in json.array!{
let _message = chatMessage(message["id"].int!,message["dialog"]["id"].int!,message["type"].int!,message["context"].string!,message["sent_at"].string!,message["sender"]["id"].int!)
if let image = message["image"].string{
_message.image = "http://backend518.cloudapp.net:1010/media/"+image
}
arrayOfMessages.append(_message)
}
//arrayOfMessages.append(getMessage)
}
self.data.listOfMessages.append(arrayOfMessages)
}
DispatchQueue.global().sync {
var text = String()
if self.data.listOfMessages.last?.last?.type == 1{
text = (self.data.listOfMessages.last?.last?.image.components(separatedBy: "/").last!)!
}else{
text = (self.data.listOfMessages.last?.last?.context)!
}
let time = (self.data.listOfMessages.last?.last?.sended_at)!
self.data.setContentOfDialog(_dialog, text, time)
}
DispatchQueue.global().sync {
self.tableOfDialogs.reloadData()
}
})
}
}
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.listOfDialogs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableOfDialogs.dequeueReusableCell(withIdentifier: "cell") as! cellOfDialog
cell.nameOfPartner.text = String(data.listOfDialogs[indexPath.row].partner_name + " " + data.listOfDialogs[indexPath.row].partner_surname)
cell.lastMessage.text = data.listOfDialogs[indexPath.row].lastMessage
cell.setTimeOfLastSended(UTCtime: data.listOfDialogs[indexPath.row].lastTime)
return cell
}
@IBAction func goBackToDialog(segue:UIStoryboardSegue) {
}
func connectToServer(){
let baseURL = "ws://backend518.cloudapp.net:1010/api/stream/?token="
//let token = UserDefaults.standard.value(forKey: "token") as! String
let token = "7f64e4bae28a530c22c58997f0ca4c7ea721231f"
socket = WebSocket(url: URL(string: baseURL + token)!)
self.socket.delegate = self
self.socket.connect()
}
func websocketDidConnect(socket: WebSocket) {
print("websocket is connected")
}
func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
print("websocket is disconnected: \(String(describing: error?.localizedDescription))")
}
func websocketDidReceiveMessage(socket: WebSocket, text: String) {
print("Aaaaaaaaadaaaaaaaaaaaaa")
if let dataFromString = text.data(using: String.Encoding.utf8, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
let event = json["event"].string!
//let status = json["status"].string!
let dataFromJson = json["data"].dictionaryObject
if(event == "Message.Created") {
let messageData = (dataFromJson?["message"] as! Dictionary<String, Any>)
let dialog_id = messageData["dialog"] as! Int
data.listOfMessages[data.getIndex(dialog_id: dialog_id)].append(chatMessage(messageData["id"] as! Int,dialog_id,messageData["type"] as! Int,messageData["context"] as! String,messageData["sent_at"] as! String,messageData["sender"] as! Int))
if messageData["type"] as! Int == 1 {
data.listOfMessages[data.getIndex(dialog_id: dialog_id)].last?.image = (messageData["image"] as! String)
let name = (messageData["image"] as! String).components(separatedBy: "/").last
data.setContentOfDialog(data.getDialog(dialog_id: dialog_id),name!,messageData["sent_at"] as! String)
}else{
data.setContentOfDialog(data.getDialog(dialog_id: dialog_id),messageData["context"] as! String,messageData["sent_at"] as! String)
}
tableOfDialogs.reloadData()
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "messageCreated"), object: nil, userInfo: messageData)
}else if(event == "Connection.Pending"){
print("got some text: ","On First Connect",text)
}
}
}
func websocketDidReceiveData(socket: WebSocket, data: Data) {
print("got some data: \(data.count)")
}
func getMessage(_ notification: NSNotification) {
let message = notification.userInfo as! Dictionary<String, Any>
if let type = message["type"] as? Int {
let dialog_id = message["dialog"] as! Int
data.listOfMessages[data.getIndex(dialog_id: dialog_id)].append(chatMessage(message["id"] as! Int,dialog_id,type,message["context"] as! String,message["sent_at"] as! String,message["sender"] as! Int))
if type == 1 {
data.listOfMessages[data.getIndex(dialog_id: dialog_id)].last?.image = (message["image"] as! String)
let name = (message["image"] as! String).components(separatedBy: "/").last
data.setContentOfDialog(data.getDialog(dialog_id: dialog_id),name!,message["sent_at"] as! String)
}else{
data.setContentOfDialog(data.getDialog(dialog_id: dialog_id),message["context"] as! String,message["sent_at"] as! String)
}
tableOfDialogs.reloadData()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToChat"{
let navVc = segue.destination as! UINavigationController
let destination = navVc.viewControllers.first as! ChattingViewController
//let destination = navVc.viewControllers.first as! ChattingViewController
destination.msgs = data.getListOfDialogMessages(dialog_id: data.listOfDialogs[(self.tableOfDialogs.indexPathForSelectedRow?.row)!].id)
destination.dialog_ID = data.listOfDialogs[(self.tableOfDialogs.indexPathForSelectedRow?.row)!].id
destination.user_partner.name = String(data.listOfDialogs[(self.tableOfDialogs.indexPathForSelectedRow?.row)!].partner_name) + " " + String(data.listOfDialogs[(self.tableOfDialogs.indexPathForSelectedRow?.row)!].partner_surname)
destination.dialogProtocol = self
destination.selectedIndex = self.tableOfDialogs.indexPathForSelectedRow?.row
if isUser{
destination.user_me.id = String(data.listOfDialogs[(self.tableOfDialogs.indexPathForSelectedRow?.row)!].creator)
destination.user_partner.id = String(data.listOfDialogs[(self.tableOfDialogs.indexPathForSelectedRow?.row)!].partner)
}else{
destination.user_me.id = String(data.listOfDialogs[(self.tableOfDialogs.indexPathForSelectedRow?.row)!].partner)
destination.user_partner.id = String(data.listOfDialogs[(self.tableOfDialogs.indexPathForSelectedRow?.row)!].creator)
}
}
}
}
|
//
// NewFeaturesServiceApiProtocol.swift
// TrocoSimples
//
// Created by gustavo r meyer on 8/16/17.
// Copyright © 2017 gustavo r meyer. All rights reserved.
//
import UIKit
protocol NewFeaturesServiceApiProtocol {
func getNewFeatures(success _success: @escaping ([NewFeatures]) -> Void,
failure _failure: @escaping (NetworkError, Data?) -> Void)
}
|
//
// LogiinAndRegisterViewController.swift
// FireStoreEitangoApp
//
// Created by 下川勇輝 on 2020/10/11.
// Copyright © 2020 Yuki Shimokawa. All rights reserved.
//
import UIKit
import MaterialComponents.MaterialTextFields
import MaterialComponents.MaterialDialogs
import Firebase
import FirebaseFirestore
extension Notification.Name {
static let notification = Notification.Name("SettingsDoneLogin")
}
class LoginViewController: UIViewController,UITextFieldDelegate {
@IBOutlet weak var textFieldFloatingEmail: MDCTextField!
@IBOutlet weak var textFieldFloatingPW: MDCTextField!
var textControllerEmail: MDCTextInputControllerOutlined!
var textControllerPW: MDCTextInputControllerOutlined!
@IBOutlet weak var loginBtn: MDCRaisedButton!
let db = Firestore.firestore()
var refString = String()
override func viewDidLoad() {
super.viewDidLoad()
textFieldFloatingEmail.delegate = self
textFieldFloatingPW.delegate = self
loginBtn.layer.cornerRadius = 5
textFieldFloatingEmail.placeholder = "メールアドレス"
self.textControllerEmail = MDCTextInputControllerOutlined(textInput: textFieldFloatingEmail)
self.textControllerEmail.textInsets(UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16))
textFieldFloatingPW.placeholder = "パスワード"
self.textControllerPW = MDCTextInputControllerOutlined(textInput: textFieldFloatingPW)
textFieldFloatingEmail.textColor = .systemBlue
textFieldFloatingPW.textColor = .systemBlue
}
//ログイン画面が閉じるときに、元のviewへ「閉じるよ!」と伝える(プロフィールデータを更新のため)
override func viewWillDisappear(_ animated: Bool) {
NotificationCenter.default.post(name: .notification, object: nil)
}
@IBAction func login(_ sender: Any) {
Auth.auth().signIn(withEmail: textFieldFloatingEmail.text!, password: textFieldFloatingPW.text!) { (user, error) in
if error != nil{
print(error)
let alertController = MDCAlertController(title: "ログイン失敗", message: "メールアドレスかパスワードが違います")
let action = MDCAlertAction(title:"OK")
alertController.addAction(action)
self.present(alertController, animated:true)
}else{
// //練習
// //このユーザー専用のfirestore参照先(ドキュメントID)
// let profileRef = Firestore.firestore().collection("Profile").document()
// var refString = String()
// refString = profileRef.documentID
// UserDefaults.standard.setValue(refString, forKey: "refString")
// print("ログイン成功しただよ")
//FSからドキュメント全部とる。そのドキュメントの中で、現在のuidと一致するものを取ってくる。そしてそのdocの中のrefStringを取ってきてuserDefaultに保存。otherViewControllerに戻った時にきちんとプロフィールのデータがロードされる。
self.db.collection("Profile").getDocuments { (snapShot, error) in
if error != nil{
print(error.debugDescription)
}
//snapShotDocに、コレクション(Profile)の中にあるドキュメント全てが入っている
if let snapShotDoc = snapShot?.documents{
//snapShotDocの中身を一つ一つ見るためにdocへfor文で入れてる。
for doc in snapShotDoc{
//uidが一致したときだけ、そのドキュメントの中にあるrefStringを取ってきたい!(ユーザーとFireStore送信先を紐づけるため)
//docの中にあるdataを定数に入れてる。
let data = doc.data()
//空じゃないときだけ入れる
if let uid = data["uid"] as? String, let ref = data["refString"] as? String{
if uid == Auth.auth().currentUser!.uid{
//ドキュメントの中のデータ中のrefStringを取ってきて、変数に入れてる
self.refString = ref
print(self.refString)
//このユーザーのFireStore送信先を取ってこれたので保存する
UserDefaults.standard.setValue(self.refString, forKey: "refString")
}
}
}
}
}
//アラート
let alertController = MDCAlertController(title: "ログイン成功", message: "さあ、はじめましょう!")
let action = MDCAlertAction(title:"OK"){(alert) in
self.dismiss(animated: true, completion: nil)
}
alertController.addAction(action)
self.present(alertController, animated:true)
}
//非同期処理(通信重たい時などのためにUIの処理だけ並行してやってしまう)
DispatchQueue.main.async {
self.textFieldFloatingEmail.resignFirstResponder()
self.textFieldFloatingPW.resignFirstResponder()
}
}
}
@IBAction func close(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//タッチでキーボ閉じる
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
textFieldFloatingEmail.resignFirstResponder()
textFieldFloatingPW.resignFirstResponder()
}
//リターンでキーボ閉じる
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textFieldFloatingEmail.resignFirstResponder()
textFieldFloatingPW.resignFirstResponder()
return true
}
}
|
import Foundation
import Runtime
private var keyPaths = [Int : [String : PropertyInfo]]()
/**
# Key Path Listable
A type whose Key Paths can be used in GraphQL
*/
public protocol KeyPathListable { }
extension KeyPathListable {
subscript<T>(checkedMirrorDescendant key: String) -> T {
get {
return try! keyPaths[unsafeBitCast(Self.self, to: Int.self)]![key]!.get(from: self)
}
set {
try! keyPaths[unsafeBitCast(Self.self, to: Int.self)]![key]!.set(value: newValue, on: &self)
}
}
}
extension KeyPathListable {
static func resolve<T>() throws -> [String : KeyPath<Self, T>] {
let properties = try keyPaths.getOrPut(unsafeBitCast(Self.self, to: Int.self)) {
let keysAndValues = try typeInfo(of: Self.self, .properties).map { ($0.name, $0) }
return Dictionary(keysAndValues) { $1 }
}
// TODO: If T is Any or a protocol, we should allow other types as well
return properties
.filter { $0.value.type == T.self }
.mapValues { \Self.[checkedMirrorDescendant: $0.name] }
}
}
|
//
// TableController.swift
// RssBankNews
//
// Created by Nick Chekmazov on 02.12.2020.
//
import UIKit
final class TableNewsController: UIViewController {
//MARK: - Properties
let detailedNewsController = DetailedNewsController()
let networkManager = NetworkManager()
let tableCell = TableNewsCell()
var tableIndex: IndexPath?
var posts: [Post]?
var defaultUrl = "https://www.banki.ru/xml/news.rss"
lazy var tableViewNews: UITableView = {
let table = UITableView()
table.register(TableNewsCell.self, forCellReuseIdentifier: TableNewsCell.identifier)
table.delegate = self
table.dataSource = self
table.translatesAutoresizingMaskIntoConstraints = false
table.refreshControl = myRefreshControl
return table
}()
lazy var myRefreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refresh(sender:)), for: .valueChanged)
return refreshControl
}()
lazy var rightButton: UIBarButtonItem = {
let rightButton = UIBarButtonItem.init(barButtonSystemItem: .add, target: self, action: #selector(addURL))
return rightButton
}()
//MARK: - Delegate
weak var delegateNews: PassData?
override func viewDidLoad() {
super.viewDidLoad()
configure()
addSubViews()
addConstraints()
fetchData(newUrl: defaultUrl)
}
private func configure() {
delegateNews = detailedNewsController
view.backgroundColor = .white
navigationItem.title = "Bank News"
navigationItem.rightBarButtonItem = rightButton
}
private func addSubViews() {
view.addSubview(tableViewNews)
}
private func addConstraints() {
NSLayoutConstraint.activate([
tableViewNews.topAnchor.constraint(equalTo: view.topAnchor),
tableViewNews.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableViewNews.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableViewNews.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
}
func segueToDetailVC() {
navigationController?.pushViewController(detailedNewsController, animated: true)
}
func fetchData(newUrl: String) {
defaultUrl = newUrl
networkManager.parseNews(url: defaultUrl) { (posts) in
self.posts = posts
DispatchQueue.main.async {
self.tableViewNews.reloadSections(IndexSet(integer: 0), with: .left)
}
}
}
@objc private func refresh(sender: UIRefreshControl) {
fetchData(newUrl: defaultUrl)
tableViewNews.reloadData()
sender.endRefreshing()
}
@objc private func addURL() {
let alert = Alert()
let errorAlert = Alert()
alert.addUrl(vc: self, errorAlert: errorAlert)
}
}
|
import Foundation
import UIKit
class UpcomingDraftDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
let fetchUpcomingDraftDetailService = FetchUpcomingDraftDetailServices()
let fetchDraftResultDetailService = FetchDraftResultDetailService()
let fetchLiveMatchDetailService = FetchLiveMatchDetailService()
let fetchPlayerDetailsService = FetchPlayerDetailsService()
let userId: Int = UserDefaults.standard.integer(forKey: "UserId")
var upcomingDataTimer = Timer()
@IBOutlet weak var opponentsScroller: UIScrollView!
@IBOutlet weak var playersTableView: UITableView!
@IBOutlet weak var notActivePlayersView: UIView!
@IBOutlet weak var infoBtn: UIButton!
@IBOutlet weak var upcomingGraphDetailTitle: UILabel!
// Mark:- Player Details Object
@IBOutlet weak var playerDetailBg: UIView!
@IBOutlet weak var playerDetailMainView: UIView!
@IBOutlet weak var playerImage: UIImageView!
@IBOutlet weak var playerNameLbl: UILabel!
@IBOutlet weak var playerMatchDetailLbl: UILabel!
@IBOutlet weak var projectionLbl: UILabel!
@IBOutlet weak var averageLbl: UILabel!
@IBOutlet weak var playerDetailView: UIView!
@IBOutlet weak var firstTitle: UILabel!
@IBOutlet weak var secondTitle: UILabel!
@IBOutlet weak var thirdTitle: UILabel!
@IBOutlet weak var forthTitle: UILabel!
@IBOutlet weak var fifthTitle: UILabel!
@IBOutlet weak var sixthTitle: UILabel!
@IBOutlet weak var oponent1Lbl: UILabel!
@IBOutlet weak var oponent2Lbl: UILabel!
@IBOutlet weak var oponent3Lbl: UILabel!
@IBOutlet weak var oponent4Lbl: UILabel!
@IBOutlet weak var points1Lbl: UILabel!
@IBOutlet weak var points2Lbl: UILabel!
@IBOutlet weak var point3Lbl: UILabel!
@IBOutlet weak var points4Lbl: UILabel!
@IBOutlet weak var rebounds1Lbl: UILabel!
@IBOutlet weak var rebounds2Lbl: UILabel!
@IBOutlet weak var rebounds3Lbl: UILabel!
@IBOutlet weak var rebounds4Lbl: UILabel!
@IBOutlet weak var assists1Lbl: UILabel!
@IBOutlet weak var assists2Lbl: UILabel!
@IBOutlet weak var assists3Lbl: UILabel!
@IBOutlet weak var assists4Lbl: UILabel!
@IBOutlet weak var blockedShots1Lbl: UILabel!
@IBOutlet weak var blockedShots2Lbl: UILabel!
@IBOutlet weak var blockedShots3Lbl: UILabel!
@IBOutlet weak var blockedShots4Lbl: UILabel!
@IBOutlet weak var steals1Lbl: UILabel!
@IBOutlet weak var steals2Lbl: UILabel!
@IBOutlet weak var steals3Lbl: UILabel!
@IBOutlet weak var steals4Lbl: UILabel!
@IBOutlet weak var fantasyPoints1Lbl: UILabel!
@IBOutlet weak var fantasyPoints2Lbl: UILabel!
@IBOutlet weak var fantasyPoints3Lbl: UILabel!
@IBOutlet weak var fantasyPoints4Lbl: UILabel!
@IBOutlet weak var noteTxtView: UITextView!
var playerDetailsDataArray = NSArray()
var playerDetailsData = NSDictionary()
var swapPlayerScreen = SwapPlayerViewController()
var draftDetailPage = DraftDetailViewController()
var draftId:Int = 0
var playId:Int64 = 0
var sportsId:Int64 = 0
var isLive:Bool = false
var isResult:Bool = false
var isFromGame:Bool = false
// MARK: - UIViewLifeCycle
var draftDetailArray = NSArray ()
var draftplayerListArray = NSArray ()
var userUpcomingDraftDetailsDictionary = NSDictionary()
var selectedPlayerTeamList = NSMutableArray ()
var projectionList = NSMutableArray ()
var timer = Timer()
var isConnectionLost:Bool = false
var playerBtn = UIButton()
var selectedButtonTag: Int = 0
var userDraftResultsDetailDictionary = NSDictionary()
var liveMatchesDetailDictionary = NSDictionary()
override func viewDidLoad() {
super.viewDidLoad()
upcomingDataTimer.invalidate()
upcomingDataTimer = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(runTimedCode), userInfo: nil, repeats: true)
if Reachability.isConnectedToNetwork() == true {
if self.isLive{
self.upcomingGraphDetailTitle.text = "Live Details"
self.infoBtn.isHidden = true
self.fetchLiveMatchDetail(playId: playId)
}else if self.isResult{
self.upcomingGraphDetailTitle.text = "Result Details"
self.infoBtn.isHidden = true
self.fetchDraftResultDetail(playId: playId)
} else{
self.infoBtn.isHidden = false
fetchUpcomingDraftDetail(playId: playId, draftId: draftId)
}
} else {
let alertController = UIAlertController(title: "Warning", message:"Please check your internet connection.", preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {
(action : UIAlertAction!) -> Void in
})
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
timer.invalidate()
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.reachability), userInfo: nil, repeats: true)
self.clearImagesFromDirectory()
}
@objc func reachability() {
if Reachability.isConnectedToNetwork() == true {
if isConnectionLost{
timer.invalidate()
if self.isLive{
self.fetchLiveMatchDetail(playId: playId)
}else if self.isResult{
self.fetchDraftResultDetail(playId: playId)
} else{
fetchUpcomingDraftDetail(playId: playId, draftId: draftId)
}
isConnectionLost = false
}
} else {
isConnectionLost = true
print("Internet connection FAILED")
let alert = UIAlertController(title: "Warning", message:"Please check your internet connection.", preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: recheckReachability)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
}
}
func recheckReachability(action: UIAlertAction) {
self.reachability()
}
@objc func runTimedCode() {
if Reachability.isConnectedToNetwork() == true {
if self.isLive{
self.fetchLiveMatchDetail(playId: playId)
}else if self.isResult{
self.fetchDraftResultDetail(playId: playId)
} else{
fetchUpcomingDraftDetail(playId: playId, draftId: draftId)
}
} else {
let alertController = UIAlertController(title: "Warning", message:"Please check your internet connection.", preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {
(action : UIAlertAction!) -> Void in
})
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}
func addPlayerButtons() {
var xAxis: Int = 0
if self.draftDetailArray.count == 2{
xAxis = 110
}else if self.draftDetailArray.count == 3{
xAxis = 30
}else{
xAxis = 10
}
for i in 0..<self.draftDetailArray.count {
let playerDetail:NSDictionary = self.draftDetailArray[i] as! NSDictionary
let playerImageUrl: String = playerDetail.value(forKey: "ImagePath") as! String
let firstName = playerDetail.value(forKey: "UserName")
// let lastName: String = playerDetail.value(forKey: "LastName") as! String
// let winningPosition: Int64 = playerDetail.value(forKey: "WinningPosition") as! Int64
let playerName: String = firstName as! String
self.playerBtn = UIButton()
self.playerBtn.frame = CGRect(x: xAxis, y: 1, width: 65, height: 65)
self.playerBtn.backgroundColor = UIColor.clear
self.playerBtn.tag = i
self.playerBtn.sd_setImage(with: URL(string: playerImageUrl), for: .normal)
self.playerBtn.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
if i == self.selectedButtonTag{
self.playerBtn.layer.borderColor = UIColor(red: 133.0/255.0, green: 204.0/255.0, blue: 85.0/255.0, alpha: 1.0).cgColor
self.playerBtn.layer.borderWidth = 3
}else{
self.playerBtn.layer.borderColor = UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0).cgColor
self.playerBtn.layer.borderWidth = 1
}
self.playerBtn.layer.cornerRadius = playerBtn.frame.size.width/2
self.playerBtn.clipsToBounds = true;
let troffyImg = UIImageView(frame: CGRect(x:xAxis, y:Int(playerBtn.frame.origin.y + playerBtn.frame.width/2 + 15), width:25, height:25))
troffyImg.layer.cornerRadius = troffyImg.frame.width/2
troffyImg.layer.borderWidth = 1
troffyImg.clipsToBounds = true
troffyImg.tag = i + 300
troffyImg.image = #imageLiteral(resourceName: "First Troffy")
troffyImg.isHidden = true
let positionLbl = UILabel(frame: CGRect(x: xAxis + 60, y: Int(playerBtn.frame.height/2 - 10) , width: 50, height: 30))
positionLbl.textAlignment = .center
positionLbl.text = String(self.calculatePojections(buttonTag: i))
positionLbl.font = positionLbl.font.withSize(12)
positionLbl.numberOfLines = 2
positionLbl.tag = i + 200
let nameLbl = UILabel(frame: CGRect(x: playerBtn.frame.origin.x + 7, y: playerBtn.frame.size.height + 10, width: 65, height: 60))
nameLbl.textAlignment = .center
nameLbl.text = playerName
nameLbl.font = nameLbl.font.withSize(12)
nameLbl.numberOfLines = 5
nameLbl.sizeToFit()
self.opponentsScroller.addSubview(nameLbl)
self.opponentsScroller.addSubview(self.playerBtn)
if isLive || isResult{
if isResult{
self.opponentsScroller.addSubview(troffyImg)
}
self.opponentsScroller.addSubview(positionLbl)
}
if isLive || isResult{
xAxis = xAxis + 120
}else{
xAxis = xAxis + 100
}
self.opponentsScroller.contentSize = CGSize(width: xAxis + 150, height: Int(self.opponentsScroller.frame.size.height))
}
for subview in self.opponentsScroller.subviews{
let maxNumber = self.projectionList.value(forKeyPath: "@max.self") as? Double
print("\(maxNumber ?? 0)")
let index = self.projectionList.index(of: maxNumber ?? 0.0)
if subview.tag == index + 300 {
subview.isHidden = false
}
// Do what you want to do with the subview
print(subview)
}
}
func downloadUsersImages(imageUrl: String, imageName: String) {
URLSession.shared.dataTask(with: NSURL(string: imageUrl)! as URL, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error ?? "nil")
return
}
DispatchQueue.main.async(execute: { () -> Void in
// get the documents directory url
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// choose a name for your image
let fileName = imageName
// create the destination file url to save your image
let fileURL = documentsDirectory.appendingPathComponent(fileName)
// get your UIImage jpeg data representation and check if the destination file url already exists
let image = UIImage(data: data!)
if let data = UIImageJPEGRepresentation(image!, 1.0),
!FileManager.default.fileExists(atPath: fileURL.path) {
do {
// writes the image data to disk
try data.write(to: fileURL)
print("file saved")
} catch {
print("error saving file:", error)
}
}
})
}).resume()
}
func clearImagesFromDirectory() {
let fileManager = FileManager.default
let tempFolderPath = NSTemporaryDirectory()
do {
let filePaths = try fileManager.contentsOfDirectory(atPath: tempFolderPath)
for filePath in filePaths {
try fileManager.removeItem(atPath: tempFolderPath + filePath)
}
} catch {
print("Could not clear temp folder: \(error)")
}
}
func calculatePojections(buttonTag: Int) -> Double{
let playerDetail:NSDictionary = self.draftDetailArray[buttonTag] as! NSDictionary
let userId : Int = playerDetail.value(forKey: "UserId") as! Int
var total : Double = 0
for i in 0..<self.draftplayerListArray.count {
let playerTeamMember:NSDictionary = self.draftplayerListArray[i] as! NSDictionary
let playerTeamMemberUserId : Int = playerTeamMember.value(forKey: "UserId") as! Int
if userId == playerTeamMemberUserId {
if let projValue:Double = playerTeamMember.value(forKey: "Points") as? Double {
total = total + projValue
}
}
}
projectionList.add(total)
return total
}
func fetchUpcomingDraftDetail(playId: Int64, draftId: Int) {
//Show loading Indicator
let progressHUD = ProgressHUD(text: "Loading")
self.view.addSubview(progressHUD)
self.view.isUserInteractionEnabled = false
let userId: Int = UserDefaults.standard.integer(forKey: "UserId")
//Login Api
fetchUpcomingDraftDetailService.fetchUpcomingDraftDetailData(userId: userId, playId: playId) {(result, message, status )in
self.view.isUserInteractionEnabled = true
progressHUD.removeFromSuperview()
let upcomingDraftDetails = result as? FetchUpcomingDraftDetailServices
if let userUpcomingDraftDetailsDict = upcomingDraftDetails?.draftDetailData {
self.userUpcomingDraftDetailsDictionary = userUpcomingDraftDetailsDict
}else{
let alertController = UIAlertController(title: "Warning", message: "Something went wrong, please try again.", preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {
(action : UIAlertAction!) -> Void in
})
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
return
}
var result:String = ""
var message:String = ""
if let resultValue: String = self.userUpcomingDraftDetailsDictionary.value(forKey: "result") as? String {
result = resultValue
}else{
let alertController = UIAlertController(title: "Warning", message: "Something went wrong, please try again.", preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {
(action : UIAlertAction!) -> Void in
})
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
return
}
if let messageValue: String = self.userUpcomingDraftDetailsDictionary.value(forKey: "message") as? String{
message = messageValue
}
if result == "1"
{
self.draftDetailArray = (self.userUpcomingDraftDetailsDictionary.value(forKey: "data") as! NSArray)
self.draftplayerListArray = (self.userUpcomingDraftDetailsDictionary.value(forKey: "UserPlayers") as! NSArray)
for i in 0..<self.draftDetailArray.count {
let playerDetail:NSDictionary = self.draftDetailArray[i] as! NSDictionary
if let playerImageUrl = playerDetail.value(forKey: "ImagePath") ,
let firstName = playerDetail.value(forKey: "UserName") {
self.downloadUsersImages(imageUrl: playerImageUrl as! String, imageName: firstName as! String)
}
}
self.selectedButtonTag = 0
self.addPlayerButtons()
self.filterThePlayers(tagValue: 0)
}
else if result == "0"
{
let alertController = UIAlertController(title: "Warning", message: message, preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {
(action : UIAlertAction!) -> Void in
})
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
// MARK: - Fetch Draft Result Detail
func fetchDraftResultDetail(playId:Int64) {
//Show loading Indicator
let progressHUD = ProgressHUD(text: "Loading")
self.view.addSubview(progressHUD)
self.view.isUserInteractionEnabled = false
let userId: Int = UserDefaults.standard.integer(forKey: "UserId")
fetchDraftResultDetailService.fetchDraftResultDetailsData(userId: userId, playId: playId) {(result, message, status )in
self.view.isUserInteractionEnabled = true
progressHUD.removeFromSuperview()
let draftResultDetails = result as? FetchDraftResultDetailService
if let userDraftResultsDetailDict = draftResultDetails?.draftResultDetailData {
self.userDraftResultsDetailDictionary = userDraftResultsDetailDict
}else{
let alertController = UIAlertController(title: "Warning", message: "Something went wrong, please try again.", preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {
(action : UIAlertAction!) -> Void in
self.view.isUserInteractionEnabled = true
})
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
return
}
var result:String = ""
var message:String = ""
if let resultValue: String = self.userDraftResultsDetailDictionary.value(forKey: "result") as? String {
result = resultValue
}else{
let alertController = UIAlertController(title: "Warning", message: "Something went wrong, please try again.", preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {
(action : UIAlertAction!) -> Void in
})
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
return
}
if let messageValue: String = self.userDraftResultsDetailDictionary.value(forKey: "message") as? String{
message = messageValue
}
if result == "1"
{
self.draftDetailArray = (self.userDraftResultsDetailDictionary.value(forKey: "data") as! NSArray)
self.draftplayerListArray = (self.userDraftResultsDetailDictionary.value(forKey: "UserPlayers") as! NSArray)
self.selectedButtonTag = 0
self.addPlayerButtons()
self.filterThePlayers(tagValue: 0)
}
else if result == "0"
{
let alertController = UIAlertController(title: "Warning", message: message, preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {
(action : UIAlertAction!) -> Void in
})
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
// MARK: - Fetch Live Matches Detail
func fetchLiveMatchDetail(playId:Int64) {
//Show loading Indicator
let progressHUD = ProgressHUD(text: "Loading")
self.view.addSubview(progressHUD)
self.view.isUserInteractionEnabled = false
let userId: Int = UserDefaults.standard.integer(forKey: "UserId")
fetchLiveMatchDetailService.fetchLiveMatchesDetailsData(userId: userId, playId: playId) {(result, message, status )in
self.view.isUserInteractionEnabled = true
progressHUD.removeFromSuperview()
let liveMatchesDetails = result as? FetchLiveMatchDetailService
if let liveMatchesDetailDict = liveMatchesDetails?.draftLiveMatchesDetailData {
self.liveMatchesDetailDictionary = liveMatchesDetailDict
}else{
let alertController = UIAlertController(title: "Warning", message: "Something went wrong, please try again.", preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {
(action : UIAlertAction!) -> Void in
})
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
return
}
var result:String = ""
var message:String = ""
if let resultValue: String = self.liveMatchesDetailDictionary.value(forKey: "result") as? String {
result = resultValue
}else{
let alertController = UIAlertController(title: "Warning", message: "Something went wrong, please try again.", preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {
(action : UIAlertAction!) -> Void in
})
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
return
}
if let messageValue: String = self.liveMatchesDetailDictionary.value(forKey: "message") as? String{
message = messageValue
}
if result == "1"
{
self.draftDetailArray = (self.liveMatchesDetailDictionary.value(forKey: "data") as! NSArray)
self.draftplayerListArray = (self.liveMatchesDetailDictionary.value(forKey: "UserPlayers") as! NSArray)
for i in 0..<self.draftDetailArray.count {
let playerDetail:NSDictionary = self.draftDetailArray[i] as! NSDictionary
if let playerImageUrl: String = playerDetail.value(forKey: "ImagePath") as! String,
let firstName: String = playerDetail.value(forKey: "UserName") as! String{
self.downloadUsersImages(imageUrl: playerImageUrl, imageName: firstName)
}
}
self.selectedButtonTag = 0
self.addPlayerButtons()
self.filterThePlayers(tagValue: 0)
}
else if result == "0"
{
let alertController = UIAlertController(title: "Warning", message: message, preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {
(action : UIAlertAction!) -> Void in
})
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
@objc func buttonAction(sender: UIButton!) {
let tagValue: Int = sender.tag
self.selectedButtonTag = tagValue
self.addPlayerButtons()
self.filterThePlayers(tagValue: tagValue)
}
@objc func swapButtonAction(sender: UIButton!)
{
let tagValue: Int = sender.tag
let indexpath = IndexPath(row: tagValue, section: 0)
let playersDetail:NSDictionary = self.selectedPlayerTeamList[indexpath.row] as! NSDictionary
var playerNameValue: String = ""
var gameTimeValue: String = ""
var imageUrlValue: String = ""
var teamValue: String = ""
var opponentValue: String = ""
var positionValue: String = ""
var matchDetail = ""
var position = ""
var textColor:UIColor!
var playId = Int64()
var userDraftPlayerIdd = Int64()
if let playerName: String = playersDetail.value(forKey: "Name") as? String {
playerNameValue = playerName
}
if let gameTime: String = playersDetail.value(forKey: "GameDate") as? String {
gameTimeValue = gameTime
}
if let team: String = playersDetail.value(forKey: "Team") as? String {
teamValue = team
}
if let opponent: String = playersDetail.value(forKey: "Opponent") as? String {
opponentValue = opponent
}
if let imageUrl: String = playersDetail.value(forKey: "PhotoUrl") as? String {
imageUrlValue = imageUrl
}
if let playIdd:Int64 = playersDetail.value(forKey: "PlayId") as? Int64 {
playId = playIdd
}
if let position: String = playersDetail.value(forKey: "Position") as? String {
positionValue = position
}
if let UserDraftPlayerId:Int64 = playersDetail.value(forKey: "UserDraftPlayerId") as? Int64 {
userDraftPlayerIdd = UserDraftPlayerId
}
if gameTimeValue != ""{
let timeArray = gameTimeValue.components(separatedBy: ".")
let timeValue:String = timeArray[0]
let timeValueArray = timeValue.components(separatedBy: "T")
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier:"en_US_POSIX") as Locale?
dateFormatter.dateFormat = "HH:mm:ss"
// initially set the format based on your datepicker date / server String
let myString:String = timeValueArray[0]
let dateValueArray = myString.components(separatedBy: "-")
let strDate = "\(dateValueArray[1])/\(dateValueArray[2])"
let timeStr = dateFormatter.date(from: timeValueArray[1])
dateFormatter.dateFormat = "hh:mma"
let time = dateFormatter.string(from: timeStr!)
dateFormatter.dateFormat = "yyyy-MM-dd"
let todayDate = dateFormatter.date(from: timeValueArray[0])!
let weekDay = Calendar.current.component(.weekday, from: todayDate)
var day:String = ""
if weekDay == 1{
day = "Sun"
}
if weekDay == 2 {
day = "Mon"
}
if weekDay == 3 {
day = "Tus"
}
if weekDay == 4 {
day = "Wed"
}
if weekDay == 5 {
day = "Thur"
}
if weekDay == 6 {
day = "Fri"
}
if weekDay == 7 {
day = "Sat"
}
let teams:String = teamValue + " " + "vs" + " " + opponentValue
if positionValue == "QB"{
textColor = UIColor(red: 0.0/255.0, green: 141.0/255.0, blue: 234.0/255.0, alpha: 1.0)
position = positionValue
}else if positionValue == "RB"{
textColor = UIColor(red: 255.0/255.0, green: 76.0/255.0, blue: 26.0/255.0, alpha: 1.0)
position = positionValue
}else if positionValue == "WR" || positionValue == "TE" {
textColor = UIColor(red: 132.0/255.0, green: 204.0/255.0, blue: 85.0/255.0, alpha: 1.0)
position = positionValue
}else if positionValue == "C"{
textColor = UIColor(red: 0.0/255.0, green: 141.0/255.0, blue: 234.0/255.0, alpha: 1.0)
position = positionValue
}else if positionValue == "SF" || positionValue == "PF"{
textColor = UIColor(red: 132.0/255.0, green: 204.0/255.0, blue: 85.0/255.0, alpha: 1.0)
position = positionValue
}else if positionValue == "PG" || positionValue == "SG"{
textColor = UIColor(red: 255.0/255.0, green: 76.0/255.0, blue: 26.0/255.0, alpha: 1.0)
position = positionValue
}else if positionValue == "A"{
textColor = UIColor(red: 247.0/255.0, green: 85.0/255.0, blue: 40.0/255.0, alpha: 1.0)
position = positionValue
}else if positionValue == "D"{
textColor = UIColor(red: 0.0/255.0, green: 141.0/255.0, blue: 234.0/255.0, alpha: 1.0)
position = positionValue
}else if positionValue == "M"{
textColor = UIColor(red: 132.0/255.0, green: 204.0/255.0, blue: 85.0/255.0, alpha: 1.0)
position = positionValue
}
matchDetail = teams + " " + day + " " + strDate + " " + time
}
if let cell = self.playersTableView.cellForRow(at:indexpath) as? UpcomingDraftCell
{
let mainStoryBoard:UIStoryboard = UIStoryboard(name:"Home", bundle:nil)
// Create View Controllers
self.swapPlayerScreen = mainStoryBoard.instantiateViewController(withIdentifier: "swapPlayer") as! SwapPlayerViewController
self.swapPlayerScreen.position = position
self.swapPlayerScreen.textColor = textColor
self.swapPlayerScreen.gameTiming = matchDetail
self.swapPlayerScreen.name = playerNameValue
self.swapPlayerScreen.playId = playId
self.swapPlayerScreen.userDraftPlayerId = userDraftPlayerIdd
self.swapPlayerScreen.sportsId = self.sportsId
self.swapPlayerScreen.playerImg = (cell.playerImage?.image)!
self.present(self.swapPlayerScreen, animated: false, completion: nil)
}
}
func filterThePlayers(tagValue:Int) {
let playerDetail:NSDictionary = self.draftDetailArray[tagValue] as! NSDictionary
let userId : Int = playerDetail.value(forKey: "UserId") as! Int
selectedPlayerTeamList.removeAllObjects()
for i in 0..<self.draftplayerListArray.count {
let playerTeamMember:NSDictionary = self.draftplayerListArray[i] as! NSDictionary
let playerTeamMemberUserId : Int = playerTeamMember.value(forKey: "UserId") as! Int
if userId == playerTeamMemberUserId {
selectedPlayerTeamList.add(playerTeamMember)
}
}
self.playersTableView.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.runTimedCode()
playersTableView.reloadData()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
upcomingDataTimer.invalidate()
timer.invalidate()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
@IBAction func infoBtn(_ sender: Any) {
let mainStoryBoard:UIStoryboard = UIStoryboard(name:"Home", bundle:nil)
// Create View Controllers
self.draftDetailPage = mainStoryBoard.instantiateViewController(withIdentifier: "DraftDetails") as! DraftDetailViewController
self.draftDetailPage.draftId = draftId
self.draftDetailPage.isFromUpcoming = true
self.present(self.draftDetailPage, animated: false, completion: nil)
}
// tableview delegate
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
//make sure you use the relevant array sizes
if self.selectedPlayerTeamList.count == 0 {
self.notActivePlayersView.isHidden = false
self.view.bringSubview(toFront: self.notActivePlayersView)
}else{
self.notActivePlayersView.isHidden = true
self.view.sendSubview(toBack: self.notActivePlayersView)
}
return self.selectedPlayerTeamList.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 90
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let upcomingDraftCell = self.playersTableView.dequeueReusableCell(withIdentifier:"UpcomingDraft",for:indexPath) as! UpcomingDraftCell
let playersDetail:NSDictionary = self.selectedPlayerTeamList[indexPath.row] as! NSDictionary
var playerNameValue: String = ""
var gameTimeValue: String = ""
var gameRatingValue: String = ""
var imageUrlValue: String = ""
var teamValue: String = ""
var opponentValue: String = ""
var positionValue: String = ""
var homeTeamScoreValue: String = ""
var awayTeamScoreValue: String = ""
var statusValue: String = ""
var swapPlayer: Int64 = 0
var getUserId: Int64 = 0
if let playerName: String = playersDetail.value(forKey: "Name") as? String {
playerNameValue = playerName
}
if let gameTime: String = playersDetail.value(forKey: "GameDate") as? String {
gameTimeValue = gameTime
}
if isResult{
if let gameRating: Double = playersDetail.value(forKey: "Points") as? Double {
gameRatingValue = String(gameRating)
}
}
if isLive {
if let gameRating: Double = playersDetail.value(forKey: "Points") as? Double {
gameRatingValue = String(gameRating) + " " + "pts"
}
}else if isResult {
if let matchDetails: NSDictionary = playersDetail.value(forKey: "MatchDetails") as? NSDictionary {
if let gameRating: Double = matchDetails.value(forKey: "FantasyPointsFanDuel") as? Double {
gameRatingValue = String(gameRating) + " " + "pts"
}
}
if let matchDetails: NSDictionary = playersDetail.value(forKey: "SoccerPlayersGame") as? NSDictionary {
if let gameRating: Double = matchDetails.value(forKey: "FantasyPoints") as? Double {
gameRatingValue = String(gameRating) + " " + "pts"
}
}
}else{
if let matchDetails: NSDictionary = playersDetail.value(forKey: "MatchDetails") as? NSDictionary {
if let gameRating: Double = matchDetails.value(forKey: "FantasyPointsFanDuel") as? Double {
gameRatingValue = String(gameRating) + " " + "proj"
}
}
if let matchDetails: NSDictionary = playersDetail.value(forKey: "SoccerPlayersGame") as? NSDictionary {
if let gameRating: Double = matchDetails.value(forKey: "FantasyPoints") as? Double {
gameRatingValue = String(gameRating) + " " + "proj"
}
}
}
if let team: String = playersDetail.value(forKey: "Team") as? String {
teamValue = team
}
if let opponent: String = playersDetail.value(forKey: "Opponent") as? String {
opponentValue = opponent
}
if let imageUrl: String = playersDetail.value(forKey: "PhotoUrl") as? String {
imageUrlValue = imageUrl
}
if let position: String = playersDetail.value(forKey: "Position") as? String {
positionValue = position
}
if let homeTeamScore: Int64 = playersDetail.value(forKey: "HomeTeamScore") as? Int64 {
homeTeamScoreValue = String(homeTeamScore)
}
if let awayTeamScore: Int64 = playersDetail.value(forKey: "AwayTeamScore") as? Int64 {
awayTeamScoreValue = String(awayTeamScore)
}
if let status: String = playersDetail.value(forKey: "Status") as? String {
statusValue = status
}
if let swap = playersDetail.value(forKey: "SwapRequired") as? Int64 {
swapPlayer = swap
}
if let userId = playersDetail.value(forKey: "UserId") as? Int64 {
getUserId = userId
}
if isResult {
upcomingDraftCell.configureResultsCell(name: playerNameValue, homeTeamScore: homeTeamScoreValue, awayTeamScore: awayTeamScoreValue, rating: gameRatingValue, imageUrl: imageUrlValue, opponents: opponentValue, position: positionValue, status: statusValue)
}else{
upcomingDraftCell.btnSwapPlayer.tag = indexPath.row
upcomingDraftCell.btnSwapPlayer.addTarget(self, action: #selector(swapButtonAction), for: .touchUpInside)
upcomingDraftCell.configureCell(name: playerNameValue, time: gameTimeValue, rating: gameRatingValue, imageUrl: imageUrlValue, team: teamValue, opponents: opponentValue, position: positionValue, swapPlayer:swapPlayer, userId:getUserId)
}
return upcomingDraftCell as UpcomingDraftCell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
if isResult {
var draftPlayer = NSDictionary()
draftPlayer = self.selectedPlayerTeamList[indexPath.row] as! NSDictionary
var playerIdValue: Int64 = 0
if let playerId: Int64 = draftPlayer.value(forKey: "PlayerID") as? Int64 {
playerIdValue = playerId
}
if let playerRating: Double = draftPlayer.value(forKey: "FantasyPointsFanDuel") as? Double {
self.projectionLbl.text = String(playerRating)
}
if Reachability.isConnectedToNetwork() == true {
self.fetchPlayerDetails(playerId:playerIdValue ,sportsId: Int(self.sportsId))
} else {
let alertController = UIAlertController(title: "Warning", message:"Please check your internet connection.", preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {
(action : UIAlertAction!) -> Void in
})
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
func fetchPlayerDetails(playerId: Int64,sportsId: Int) {
//Show loading Indicator
let progressHUD = ProgressHUD(text: "Loading")
self.view.addSubview(progressHUD)
self.view.isUserInteractionEnabled = false
//Login Api
fetchPlayerDetailsService.fetchPlayerDetailsData(playId: playerId, sportsId: sportsId) {(result, message, status )in
self.view.isUserInteractionEnabled = true
let playerDetails = result as? FetchPlayerDetailsService
progressHUD.removeFromSuperview()
self.view.isUserInteractionEnabled = true
//
if let playerDetailsDataDict = playerDetails?.playerDetailsData {
self.playerDetailsData = playerDetailsDataDict
}else{
let alertController = UIAlertController(title: "Warning", message: "Something went wrong, please try again.", preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {
(action : UIAlertAction!) -> Void in
})
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
return
}
var result:String = ""
var message:String = ""
if let resultValue: String = self.playerDetailsData.value(forKey: "result") as? String {
result = resultValue
}else{
let alertController = UIAlertController(title: "Warning", message: "Something went wrong, please try again.", preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {
(action : UIAlertAction!) -> Void in
})
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
return
}
if let messageValue: String = self.playerDetailsData.value(forKey: "message") as? String{
message = messageValue
}
if result == "1"
{
self.playerDetailsDataArray = (self.playerDetailsData.value(forKey: "data") as! NSArray)
self.setplayerDetailsfieldValue(sportsId: sportsId)
self.playerDetailMainView.isHidden = false
self.playerDetailBg.isHidden = false
self.view.bringSubview(toFront: self.playerDetailBg)
self.view.bringSubview(toFront: self.playerDetailMainView)
}
else if result == "0"
{
let alertController = UIAlertController(title: "Warning", message: message, preferredStyle: UIAlertControllerStyle.alert)
let cancelAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {
(action : UIAlertAction!) -> Void in
})
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
@IBAction func backBtn(_ sender: Any) {
if isFromGame {
var homePage = HomeViewController()
let mainStoryBoard:UIStoryboard = UIStoryboard(name:"Home", bundle:nil)
// Create View Controllers
homePage = mainStoryBoard.instantiateViewController(withIdentifier: "Home") as! HomeViewController
homePage.sportsId = "0"
self.present(homePage, animated: true, completion: nil)
}else{
self.dismiss(animated: false, completion: nil)
}
}
func setplayerDetailsfieldValue(sportsId: Int){
var latestNewsDate: String = ""
playerImage?.layer.cornerRadius = playerImage.frame.size.width/2
playerImage?.layer.borderWidth = 1
playerImage?.layer.borderColor = UIColor(red: 147.0/255.0, green: 149.0/255.0, blue: 152.0/255.0, alpha: 0.4).cgColor
playerImage?.clipsToBounds = true;
playerDetailView?.layer.cornerRadius = 5.0
playerDetailView?.layer.borderWidth = 1
playerDetailView?.layer.borderColor = UIColor(red: 147.0/255.0, green: 149.0/255.0, blue: 152.0/255.0, alpha: 0.4).cgColor
playerDetailView?.clipsToBounds = true;
if sportsId == 1{
self.firstTitle.text = "Yds"
self.secondTitle.text = "TD"
self.thirdTitle.text = "INT"
self.forthTitle.text = "RuYd"
self.fifthTitle.text = "RuTd"
self.sixthTitle.text = "Total"
}else if sportsId == 3{
self.firstTitle.text = "SCR"
self.secondTitle.text = "GLS"
self.thirdTitle.text = "AST"
self.forthTitle.text = "FLD"
self.fifthTitle.text = "TKLW"
self.sixthTitle.text = "Total"
}
for i in 0..<self.playerDetailsDataArray.count {
let detail = self.playerDetailsDataArray[i] as! NSDictionary
if i == 0 {
self.playerNameLbl.text = (detail.value(forKey: "Name") as! String)
if let averageInt = detail.value(forKey: "FantasyPointsFanDuel") as? Double {
self.averageLbl.text = String(averageInt)
}
if let note = detail.value(forKey: "InjuryNotes") as? String {
self.noteTxtView.text = note
}else{
self.noteTxtView.text = "No news found!"
}
var positionValue : String = ""
var teamValue : String = ""
var opponentValue : String = ""
var timeValue : String = ""
if let playerImg = detail.value(forKey: "PhotoUrl") as? String {
self.playerImage.sd_setImage(with: URL(string: playerImg), placeholderImage:#imageLiteral(resourceName: "ProfilePlaceholder"))
}
if let position = detail.value(forKey: "Position") as? String {
positionValue = position
}
if let team = detail.value(forKey: "Team") as? String {
teamValue = team
}
if let opponent = detail.value(forKey: "Opponent") as? String {
opponentValue = opponent
}
if let time = detail.value(forKey:"GameDate") as? String {
let timeValueArray = time.components(separatedBy: "T")
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier:"en_US_POSIX") as Locale?
dateFormatter.dateFormat = "HH:mm:ss"
let time = dateFormatter.date(from: timeValueArray[1])
dateFormatter.dateFormat = "HH:mm a"
let timeStr = dateFormatter.string(from: time!)
dateFormatter.dateFormat = "yyy-mm-dd"
let date = dateFormatter.date(from: timeValueArray[0])!
dateFormatter.dateFormat = "eee"
let day = dateFormatter.string(from: date)
timeValue = " " + day + "," + " " + timeStr
}
let matchDetail : String = positionValue + " " + teamValue + " " + "vs" + opponentValue + timeValue
var myMutableString = NSMutableAttributedString()
myMutableString = NSMutableAttributedString(string: matchDetail as String, attributes: [NSAttributedStringKey.font:UIFont(name: "Georgia", size: 13.0)!])
var textColor:UIColor!
if positionValue == "QB"{
textColor = UIColor(red: 0.0/255.0, green: 141.0/255.0, blue: 234.0/255.0, alpha: 1.0)
}else if positionValue == "RB"{
textColor = UIColor(red: 255.0/255.0, green: 76.0/255.0, blue: 26.0/255.0, alpha: 1.0)
}else if positionValue == "WR" || positionValue == "TE" {
textColor = UIColor(red: 132.0/255.0, green: 204.0/255.0, blue: 85.0/255.0, alpha: 1.0)
}else if positionValue == "C"{
textColor = UIColor(red: 0.0/255.0, green: 141.0/255.0, blue: 234.0/255.0, alpha: 1.0)
}else if positionValue == "SF" || positionValue == "PF"{
textColor = UIColor(red: 132.0/255.0, green: 204.0/255.0, blue: 85.0/255.0, alpha: 1.0)
}else if positionValue == "PG" || positionValue == "SG"{
textColor = UIColor(red: 255.0/255.0, green: 76.0/255.0, blue: 26.0/255.0, alpha: 1.0)
}else if positionValue == "A"{
textColor = UIColor(red: 247.0/255.0, green: 85.0/255.0, blue: 40.0/255.0, alpha: 1.0)
}else if positionValue == "D"{
textColor = UIColor(red: 0.0/255.0, green: 141.0/255.0, blue: 234.0/255.0, alpha: 1.0)
}else if positionValue == "M"{
textColor = UIColor(red: 132.0/255.0, green: 204.0/255.0, blue: 85.0/255.0, alpha: 1.0)
}
myMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value:textColor, range: NSRange(location:0,length:positionValue.count))
myMutableString.addAttribute(NSAttributedStringKey.font, value: UIFont(name: "AmericanTypewriter-Bold", size: 13.0)!, range: NSRange(location:positionValue.count + 1,length:teamValue.count))
myMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.lightGray, range: NSRange(location:positionValue.count + teamValue.count + 2,length:timeValue.count))
myMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.lightGray, range: NSRange(location:matchDetail.count - timeValue.count,length:timeValue.count))
playerMatchDetailLbl.attributedText = myMutableString
}
if let playerGameDict = detail.value(forKey: "NBAPlayersGame"){
if detail["NBAPlayersGame"] is NSNull {
print("playerGameDict is Null")
}
else{
let playerGame = playerGameDict as! NSDictionary
if i == 0 {
if let pointsInt = playerGame.value(forKey: "Points") as? Double {
self.points1Lbl.text = String(pointsInt)
}
if let assistsInt = playerGame.value(forKey: "Assists") as? Double {
self.assists1Lbl.text = String(assistsInt)
}
if let blockedShotsInt = playerGame.value(forKey: "BlockedShots") as? Double {
self.blockedShots1Lbl.text = String(blockedShotsInt)
}
if let stealsInt = playerGame.value(forKey: "Steals") as? Double {
self.steals1Lbl.text = String(stealsInt)
}
if let fantasyPointsInt = playerGame.value(forKey: "FantasyPoints") as? Double {
self.fantasyPoints1Lbl.text = String(fantasyPointsInt)
}
if let reboundsInt = playerGame.value(forKey: "Rebounds") as? Double {
self.rebounds1Lbl.text = String(reboundsInt)
}
var opponentValue : String = ""
var dateValue : String = ""
var isProjectionValue : Bool = false
if let isProjection = detail.value(forKey: "IsProjection") as? Bool {
isProjectionValue = isProjection
}
if let opponent = playerGame.value(forKey: "Opponent") as? String {
opponentValue = opponent
}
if let gameDate = playerGame.value(forKey: "GameDate") as? String {
let timeValueArray = gameDate.components(separatedBy: "T")
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier:"en_US_POSIX") as Locale?
dateFormatter.dateFormat = "yyyy-mm-dd"
let date = dateFormatter.date(from: timeValueArray[0])!
dateFormatter.dateFormat = "mm/dd"
let dateStr = dateFormatter.string(from: date)
dateValue = dateStr
}
if isProjectionValue{
self.oponent1Lbl.text = "Projection"
self.oponent1Lbl.font = UIFont.boldSystemFont(ofSize: 11.0)
}else{
self.oponent1Lbl.text = dateValue + " " + "vs" + " " + opponentValue
}
}else if i == 1 {
if let pointsInt = playerGame.value(forKey: "Points") as? Double {
self.points2Lbl.text = String(pointsInt)
}
if let assistsInt = playerGame.value(forKey: "Assists") as? Double {
self.assists2Lbl.text = String(assistsInt)
}
if let blockedShotsInt = playerGame.value(forKey: "BlockedShots") as? Double {
self.blockedShots2Lbl.text = String(blockedShotsInt)
}
if let stealsInt = playerGame.value(forKey: "Steals") as? Double {
self.steals2Lbl.text = String(stealsInt)
}
if let fantasyPointsInt = playerGame.value(forKey: "FantasyPoints") as? Double {
self.fantasyPoints2Lbl.text = String(fantasyPointsInt)
}
if let reboundsInt = playerGame.value(forKey: "Rebounds") as? Double {
self.rebounds2Lbl.text = String(reboundsInt)
}
var opponentValue : String = ""
var dateValue : String = ""
var isProjectionValue : Bool = false
if let isProjection = detail.value(forKey: "IsProjection") as? Bool {
isProjectionValue = isProjection
}
if let opponent = playerGame.value(forKey: "Opponent") as? String {
opponentValue = opponent
}
if let gameDate = playerGame.value(forKey: "GameDate") as? String {
let timeValueArray = gameDate.components(separatedBy: "T")
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier:"en_US_POSIX") as Locale?
dateFormatter.dateFormat = "yyyy-mm-dd"
let date = dateFormatter.date(from: timeValueArray[0])!
dateFormatter.dateFormat = "mm/dd"
let dateStr = dateFormatter.string(from: date)
dateValue = dateStr
}
if isProjectionValue{
self.oponent2Lbl.text = "Projection"
self.oponent2Lbl.font = UIFont.boldSystemFont(ofSize: 11.0)
}else{
self.oponent2Lbl.text = dateValue + " " + "vs" + " " + opponentValue
}
}else if i == 2 {
if let pointsInt = playerGame.value(forKey: "Points") as? Double {
self.point3Lbl.text = String(pointsInt)
}
if let assistsInt = playerGame.value(forKey: "Assists") as? Double {
self.assists3Lbl.text = String(assistsInt)
}
if let blockedShotsInt = playerGame.value(forKey: "BlockedShots") as? Double {
self.blockedShots3Lbl.text = String(blockedShotsInt)
}
if let stealsInt = playerGame.value(forKey: "Steals") as? Double {
self.steals3Lbl.text = String(stealsInt)
}
if let fantasyPointsInt = playerGame.value(forKey: "FantasyPoints") as? Double {
self.fantasyPoints3Lbl.text = String(fantasyPointsInt)
}
if let reboundsInt = playerGame.value(forKey: "Rebounds") as? Double {
self.rebounds3Lbl.text = String(reboundsInt)
}
var opponentValue : String = ""
var dateValue : String = ""
var isProjectionValue : Bool = false
if let isProjection = detail.value(forKey: "IsProjection") as? Bool {
isProjectionValue = isProjection
}
if let opponent = playerGame.value(forKey: "Opponent") as? String {
opponentValue = opponent
}
if let gameDate = playerGame.value(forKey: "GameDate") as? String {
let timeValueArray = gameDate.components(separatedBy: "T")
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier:"en_US_POSIX") as Locale?
dateFormatter.dateFormat = "yyyy-mm-dd"
let date = dateFormatter.date(from: timeValueArray[0])!
dateFormatter.dateFormat = "mm/dd"
let dateStr = dateFormatter.string(from: date)
dateValue = dateStr
}
if isProjectionValue{
self.oponent3Lbl.text = "Projection"
self.oponent3Lbl.font = UIFont.boldSystemFont(ofSize: 11.0)
}else{
self.oponent3Lbl.text = dateValue + " " + "vs" + " " + opponentValue
}
}else if i == 3 {
if let pointsInt = playerGame.value(forKey: "Points") as? Double {
self.points4Lbl.text = String(pointsInt)
}
if let assistsInt = playerGame.value(forKey: "Assists") as? Double {
self.assists4Lbl.text = String(assistsInt)
}
if let blockedShotsInt = playerGame.value(forKey: "BlockedShots") as? Double {
self.blockedShots4Lbl.text = String(blockedShotsInt)
}
if let stealsInt = playerGame.value(forKey: "Steals") as? Double {
self.steals4Lbl.text = String(stealsInt)
}
if let fantasyPointsInt = playerGame.value(forKey: "FantasyPoints") as? Double {
self.fantasyPoints4Lbl.text = String(fantasyPointsInt)
}
if let reboundsInt = playerGame.value(forKey: "Rebounds") as? Double {
self.rebounds4Lbl.text = String(reboundsInt)
}
var opponentValue : String = ""
var dateValue : String = ""
var isProjectionValue : Bool = false
if let isProjection = detail.value(forKey: "IsProjection") as? Bool {
isProjectionValue = isProjection
}
if let opponent = playerGame.value(forKey: "Opponent") as? String {
opponentValue = opponent
}
if let gameDate = playerGame.value(forKey: "GameDate") as? String {
let timeValueArray = gameDate.components(separatedBy: "T")
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier:"en_US_POSIX") as Locale?
dateFormatter.dateFormat = "yyyy-mm-dd"
let date = dateFormatter.date(from: timeValueArray[0])!
dateFormatter.dateFormat = "mm/dd"
let dateStr = dateFormatter.string(from: date)
dateValue = dateStr
}
if isProjectionValue{
self.oponent4Lbl.text = "Projection"
self.oponent4Lbl.font = UIFont.boldSystemFont(ofSize: 11.0)
}else{
self.oponent4Lbl.text = dateValue + " " + "vs" + " " + opponentValue
}
}
}
}
if let playerGameDict = detail.value(forKey: "MatchDetails"){
if detail["MatchDetails"] is NSNull {
print("playerGameDict is Null")
}
else{
let playerGame = playerGameDict as! NSDictionary
if i == 0 {
if let pointsInt = playerGame.value(forKey: "PassingYards") as? Double {
self.points1Lbl.text = String(pointsInt)
}
if let assistsInt = playerGame.value(forKey: "Interceptions") as? Double {
self.assists1Lbl.text = String(assistsInt)
}
if let blockedShotsInt = playerGame.value(forKey: "RushingYards") as? Double {
self.blockedShots1Lbl.text = String(blockedShotsInt)
}
if let stealsInt = playerGame.value(forKey: "RushingTouchdowns") as? Double {
self.steals1Lbl.text = String(stealsInt)
}
if let fantasyPointsInt = playerGame.value(forKey: "FantasyPoints") as? Double {
self.fantasyPoints1Lbl.text = String(fantasyPointsInt)
}
if let reboundsInt = playerGame.value(forKey: "Touchdowns") as? Double {
self.rebounds1Lbl.text = String(reboundsInt)
}
var opponentValue : String = ""
var dateValue : String = ""
var isProjectionValue : Bool = false
if let isProjection = detail.value(forKey: "IsProjection") as? Bool {
isProjectionValue = isProjection
}
if let opponent = playerGame.value(forKey: "Opponent") as? String {
opponentValue = opponent
}
if let gameDate = playerGame.value(forKey: "GameDate") as? String {
let timeValueArray = gameDate.components(separatedBy: "T")
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier:"en_US_POSIX") as Locale?
dateFormatter.dateFormat = "yyyy-mm-dd"
let date = dateFormatter.date(from: timeValueArray[0])!
dateFormatter.dateFormat = "mm/dd"
let dateStr = dateFormatter.string(from: date)
dateValue = dateStr
}
if isProjectionValue{
self.oponent1Lbl.text = "Projection"
self.oponent1Lbl.font = UIFont.boldSystemFont(ofSize: 11.0)
}else{
self.oponent1Lbl.text = dateValue + " " + "vs" + " " + opponentValue
}
}else if i == 1 {
if let pointsInt = playerGame.value(forKey: "PassingYards") as? Double {
self.points2Lbl.text = String(pointsInt)
}
if let assistsInt = playerGame.value(forKey: "Interceptions") as? Double {
self.assists2Lbl.text = String(assistsInt)
}
if let blockedShotsInt = playerGame.value(forKey: "RushingYards") as? Double {
self.blockedShots2Lbl.text = String(blockedShotsInt)
}
if let stealsInt = playerGame.value(forKey: "RushingTouchdowns") as? Double {
self.steals2Lbl.text = String(stealsInt)
}
if let fantasyPointsInt = playerGame.value(forKey: "FantasyPoints") as? Double {
self.fantasyPoints2Lbl.text = String(fantasyPointsInt)
}
if let reboundsInt = playerGame.value(forKey: "Touchdowns") as? Double {
self.rebounds2Lbl.text = String(reboundsInt)
}
var opponentValue : String = ""
var dateValue : String = ""
var isProjectionValue : Bool = false
if let isProjection = detail.value(forKey: "IsProjection") as? Bool {
isProjectionValue = isProjection
}
if let opponent = playerGame.value(forKey: "Opponent") as? String {
opponentValue = opponent
}
if let gameDate = playerGame.value(forKey: "GameDate") as? String {
let timeValueArray = gameDate.components(separatedBy: "T")
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier:"en_US_POSIX") as Locale?
dateFormatter.dateFormat = "yyyy-mm-dd"
let date = dateFormatter.date(from: timeValueArray[0])!
dateFormatter.dateFormat = "mm/dd"
let dateStr = dateFormatter.string(from: date)
dateValue = dateStr
}
if isProjectionValue{
self.oponent2Lbl.text = "Projection"
self.oponent2Lbl.font = UIFont.boldSystemFont(ofSize: 11.0)
}else{
self.oponent2Lbl.text = dateValue + " " + "vs" + " " + opponentValue
}
}else if i == 2 {
if let pointsInt = playerGame.value(forKey: "PassingYards") as? Double {
self.point3Lbl.text = String(pointsInt)
}
if let assistsInt = playerGame.value(forKey: "Interceptions") as? Double {
self.assists3Lbl.text = String(assistsInt)
}
if let blockedShotsInt = playerGame.value(forKey: "RushingYards") as? Double {
self.blockedShots3Lbl.text = String(blockedShotsInt)
}
if let stealsInt = playerGame.value(forKey: "RushingTouchdowns") as? Double {
self.steals3Lbl.text = String(stealsInt)
}
if let fantasyPointsInt = playerGame.value(forKey: "FantasyPoints") as? Double {
self.fantasyPoints3Lbl.text = String(fantasyPointsInt)
}
if let reboundsInt = playerGame.value(forKey: "Touchdowns") as? Double {
self.rebounds3Lbl.text = String(reboundsInt)
}
var opponentValue : String = ""
var dateValue : String = ""
var isProjectionValue : Bool = false
if let isProjection = detail.value(forKey: "IsProjection") as? Bool {
isProjectionValue = isProjection
}
if let opponent = playerGame.value(forKey: "Opponent") as? String {
opponentValue = opponent
}
if let gameDate = playerGame.value(forKey: "GameDate") as? String {
let timeValueArray = gameDate.components(separatedBy: "T")
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier:"en_US_POSIX") as Locale?
dateFormatter.dateFormat = "yyyy-mm-dd"
let date = dateFormatter.date(from: timeValueArray[0])!
dateFormatter.dateFormat = "mm/dd"
let dateStr = dateFormatter.string(from: date)
dateValue = dateStr
}
if isProjectionValue{
self.oponent3Lbl.text = "Projection"
self.oponent3Lbl.font = UIFont.boldSystemFont(ofSize: 11.0)
}else{
self.oponent3Lbl.text = dateValue + " " + "vs" + " " + opponentValue
}
}else if i == 3 {
if let pointsInt = playerGame.value(forKey: "PassingYards") as? Double {
self.points4Lbl.text = String(pointsInt)
}
if let assistsInt = playerGame.value(forKey: "Interceptions") as? Double {
self.assists4Lbl.text = String(assistsInt)
}
if let blockedShotsInt = playerGame.value(forKey: "RushingYards") as? Double {
self.blockedShots4Lbl.text = String(blockedShotsInt)
}
if let stealsInt = playerGame.value(forKey: "RushingTouchdowns") as? Double {
self.steals4Lbl.text = String(stealsInt)
}
if let fantasyPointsInt = playerGame.value(forKey: "FantasyPoints") as? Double {
self.fantasyPoints4Lbl.text = String(fantasyPointsInt)
}
if let reboundsInt = playerGame.value(forKey: "Touchdowns") as? Double {
self.rebounds4Lbl.text = String(reboundsInt)
}
var opponentValue : String = ""
var dateValue : String = ""
var isProjectionValue : Bool = false
if let isProjection = detail.value(forKey: "IsProjection") as? Bool {
isProjectionValue = isProjection
}
if let opponent = playerGame.value(forKey: "Opponent") as? String {
opponentValue = opponent
}
if let gameDate = playerGame.value(forKey: "GameDate") as? String {
let timeValueArray = gameDate.components(separatedBy: "T")
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier:"en_US_POSIX") as Locale?
dateFormatter.dateFormat = "yyyy-mm-dd"
let date = dateFormatter.date(from: timeValueArray[0])!
dateFormatter.dateFormat = "mm/dd"
let dateStr = dateFormatter.string(from: date)
dateValue = dateStr
}
if isProjectionValue{
self.oponent4Lbl.text = "Projection"
self.oponent4Lbl.font = UIFont.boldSystemFont(ofSize: 11.0)
}else{
self.oponent4Lbl.text = dateValue + " " + "vs" + " " + opponentValue
}
}
}
}
if let playerGameDict = detail.value(forKey: "SoccerPlayersGame"){
if detail["SoccerPlayersGame"] is NSNull {
print("playerGameDict is Null")
}
else{
let playerGame = playerGameDict as! NSDictionary
if i == 0 {
if let pointsInt = playerGame.value(forKey: "Score") as? Double {
self.points1Lbl.text = String(pointsInt)
}
if let assistsInt = playerGame.value(forKey: "Assists") as? Double {
self.assists1Lbl.text = String(assistsInt)
}
if let blockedShotsInt = playerGame.value(forKey: "Fouled") as? Double {
self.blockedShots1Lbl.text = String(blockedShotsInt)
}
if let stealsInt = playerGame.value(forKey: "TacklesWon") as? Double {
self.steals1Lbl.text = String(stealsInt)
}
if let fantasyPointsInt = playerGame.value(forKey: "FantasyPoints") as? Double {
self.fantasyPoints1Lbl.text = String(fantasyPointsInt)
}
if let reboundsInt = playerGame.value(forKey: "Goals") as? Double {
self.rebounds1Lbl.text = String(reboundsInt)
}
var opponentValue : String = ""
var dateValue : String = ""
var isProjectionValue : Bool = false
if let isProjection = detail.value(forKey: "IsProjection") as? Bool {
isProjectionValue = isProjection
}
if let opponent = playerGame.value(forKey: "Opponent") as? String {
opponentValue = opponent
}
if let gameDate = playerGame.value(forKey: "GameDate") as? String {
let timeValueArray = gameDate.components(separatedBy: "T")
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier:"en_US_POSIX") as Locale?
dateFormatter.dateFormat = "yyyy-mm-dd"
let date = dateFormatter.date(from: timeValueArray[0])!
dateFormatter.dateFormat = "mm/dd"
let dateStr = dateFormatter.string(from: date)
dateValue = dateStr
}
if isProjectionValue{
self.oponent1Lbl.text = "Projection"
self.oponent1Lbl.font = UIFont.boldSystemFont(ofSize: 11.0)
}else{
self.oponent1Lbl.text = dateValue + " " + "vs" + " " + opponentValue
}
}else if i == 1 {
if let pointsInt = playerGame.value(forKey: "Score") as? Double {
self.points2Lbl.text = String(pointsInt)
}
if let assistsInt = playerGame.value(forKey: "Assists") as? Double {
self.assists2Lbl.text = String(assistsInt)
}
if let blockedShotsInt = playerGame.value(forKey: "Fouled") as? Double {
self.blockedShots2Lbl.text = String(blockedShotsInt)
}
if let stealsInt = playerGame.value(forKey: "TacklesWon") as? Double {
self.steals2Lbl.text = String(stealsInt)
}
if let fantasyPointsInt = playerGame.value(forKey: "FantasyPoints") as? Double {
self.fantasyPoints2Lbl.text = String(fantasyPointsInt)
}
if let reboundsInt = playerGame.value(forKey: "Goals") as? Double {
self.rebounds2Lbl.text = String(reboundsInt)
}
var opponentValue : String = ""
var dateValue : String = ""
var isProjectionValue : Bool = false
if let isProjection = detail.value(forKey: "IsProjection") as? Bool {
isProjectionValue = isProjection
}
if let opponent = playerGame.value(forKey: "Opponent") as? String {
opponentValue = opponent
}
if let gameDate = playerGame.value(forKey: "GameDate") as? String {
let timeValueArray = gameDate.components(separatedBy: "T")
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier:"en_US_POSIX") as Locale?
dateFormatter.dateFormat = "yyyy-mm-dd"
let date = dateFormatter.date(from: timeValueArray[0])!
dateFormatter.dateFormat = "mm/dd"
let dateStr = dateFormatter.string(from: date)
dateValue = dateStr
}
if isProjectionValue{
self.oponent2Lbl.text = "Projection"
self.oponent2Lbl.font = UIFont.boldSystemFont(ofSize: 11.0)
}else{
self.oponent2Lbl.text = dateValue + " " + "vs" + " " + opponentValue
}
}else if i == 2 {
if let pointsInt = playerGame.value(forKey: "Score") as? Double {
self.point3Lbl.text = String(pointsInt)
}
if let assistsInt = playerGame.value(forKey: "Assists") as? Double {
self.assists3Lbl.text = String(assistsInt)
}
if let blockedShotsInt = playerGame.value(forKey: "Fouled") as? Double {
self.blockedShots3Lbl.text = String(blockedShotsInt)
}
if let stealsInt = playerGame.value(forKey: "TacklesWon") as? Double {
self.steals3Lbl.text = String(stealsInt)
}
if let fantasyPointsInt = playerGame.value(forKey: "FantasyPoints") as? Double {
self.fantasyPoints3Lbl.text = String(fantasyPointsInt)
}
if let reboundsInt = playerGame.value(forKey: "Goals") as? Double {
self.rebounds3Lbl.text = String(reboundsInt)
}
var opponentValue : String = ""
var dateValue : String = ""
var isProjectionValue : Bool = false
if let isProjection = detail.value(forKey: "IsProjection") as? Bool {
isProjectionValue = isProjection
}
if let opponent = playerGame.value(forKey: "Opponent") as? String {
opponentValue = opponent
}
if let gameDate = playerGame.value(forKey: "GameDate") as? String {
let timeValueArray = gameDate.components(separatedBy: "T")
let dateFormatter = DateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier:"en_US_POSIX") as Locale?
dateFormatter.dateFormat = "yyyy-mm-dd"
let date = dateFormatter.date(from: timeValueArray[0])!
dateFormatter.dateFormat = "mm/dd"
let dateStr = dateFormatter.string(from: date)
dateValue = dateStr
}
if isProjectionValue{
self.oponent3Lbl.text = "Projection"
self.oponent3Lbl.font = UIFont.boldSystemFont(ofSize: 11.0)
}else{
self.oponent3Lbl.text = dateValue + " " + "vs" + " " + opponentValue
}
}
}
}
}
}
@IBAction func closeBtn(_ sender: Any) {
self.playerDetailMainView.isHidden = true
self.playerDetailBg.isHidden = true
self.view.sendSubview(toBack: self.playerDetailBg)
self.view.sendSubview(toBack: self.playerDetailMainView)
}
}
|
//
// AddCildCellCollectionViewCell.swift
// dasCriancas
//
// Created by Cassia Aparecida Barbosa on 25/07/19.
// Copyright © 2019 Cassia Aparecida Barbosa. All rights reserved.
//
import UIKit
import CoreData
class AddChildCell: UICollectionViewCell {
@IBOutlet var addChildPhoto: UIImageView!
@IBOutlet var addChildName: UITextField!
override func awakeFromNib() {
// deleteChild.imageView?.image = deleteChild.imageView?.image?.circleMask
addChildPhoto.layer.cornerRadius = 50
addChildPhoto.clipsToBounds = true
// base.layer.cornerRadius = 50
// base.clipsToBounds = true
// base.
}
}
|
../../../StellarKit/source/types/Ledger.swift |
//: [Previous](@previous)
class Solution {
func isSameTree(_ p: TreeNode?, _ q: TreeNode?) -> Bool {
var sameVal = false
if let pval = p?.val {
if let qval = q?.val {
if pval == qval {
sameVal = true
}
}
} else if q == nil {
sameVal = true
}
return sameVal && isSameTree(p?.left, q?.left) && isSameTree(p?.right, q?.right)
}
}
//: [Next](@next)
|
internal func getValidCount(range: Range<Int>, maxCount: Int) -> Int {
return max(min(range.endIndex, maxCount) - max(range.startIndex, 0), 0)
}
internal func clamp<T: Comparable>(x: T, lower: T, upper: T) -> T {
return min(max(x, lower), upper)
}
|
//
// Bytes.swift
// Orion
//
// Created by Eduard Shahnazaryan on 3/15/21.
//
import Foundation
public typealias GUID = String
/**
* Utilities for futzing with bytes and such.
*/
open class Bytes {
open class func generateRandomBytes(_ len: UInt) -> Data {
let len = Int(len)
var data = Data(count: len)
data.withUnsafeMutableBytes { (p: UnsafeMutableRawBufferPointer) in
guard let p = p.bindMemory(to: UInt8.self).baseAddress else {
fatalError("Random byte generation failed.")
}
if (SecRandomCopyBytes(kSecRandomDefault, len, p) != errSecSuccess) {
fatalError("Random byte generation failed.")
}
}
return data
}
open class func generateGUID() -> GUID {
// Turns the standard NSData encoding into the URL-safe variant that Sync expects.
return generateRandomBytes(9)
.base64EncodedString(options: [])
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "+", with: "-")
}
open class func decodeBase64(_ b64: String) -> Data? {
return Data(base64Encoded: b64, options: [])
}
/**
* Turn a string of base64 characters into an NSData *without decoding*.
* This is to allow HMAC to be computed of the raw base64 string.
*/
open class func dataFromBase64(_ b64: String) -> Data? {
return b64.data(using: .ascii, allowLossyConversion: false)
}
func fromHex(_ str: String) -> Data {
// TODO
return Data()
}
}
|
//
// Constants.swift
// Nine
//
// Created by Tian He on 3/12/16.
// Copyright © 2016 Tian He. All rights reserved.
//
import UIKit
struct Constants {
static let MaxMood = 100
static let MinMood = -100
static let MaxEnergy = 100
static let MinEnergy = -100
static let NormalizedScore = Float(100)
static let primaryColor = UIColor(red: 255.0/255.0, green: 158.0/255.0, blue: 75.0/255.0, alpha: 1.0)
static let primaryLightColor = UIColor(red: 255.0/255.0, green: 196/255.0, blue: 146/255.0, alpha: 1)
static let primaryDarkColor = UIColor(red: 255/255.0, green: 128/255.0, blue: 19/255.0, alpha: 1)
static let secondaryColor = UIColor(red: 67/255.0, green: 227/255.0, blue: 77/255.0, alpha: 1)
static let secondaryLightColor = UIColor(red: 139/255.0, green: 243/255.0, blue: 146/255.0, alpha: 1)
static let secondaryDarkColor = UIColor(red: 17/255.0, green: 225/255.0, blue: 31/255.0, alpha: 1)
static let tertiaryColor = UIColor(red: 78/255.0, green: 118/255.0, blue: 212/255.0, alpha: 1)
static let tertiaryLightColor = UIColor(red: 145/255.0, green: 173/255.0, blue: 236/255.0, alpha: 1)
static let tertiaryDarkColor = UIColor(red: 36/255.0, green: 88/255.0, blue: 209/255.0, alpha: 1)
static let colorScheme = [tertiaryLightColor, tertiaryColor, tertiaryDarkColor,
secondaryLightColor, secondaryColor, secondaryDarkColor,
primaryLightColor, primaryColor, primaryDarkColor
]
} |
//
// HomeSearchViewController.swift
// SwiftCaiYIQuan
//
// Created by 朴子hp on 2018/7/4.
// Copyright © 2018年 朴子hp. All rights reserved.
//
import UIKit
class HomeSearchViewController: ViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
setUpSearchView()
}
//MARK: 上方搜索内容视图
func setUpSearchView() -> Void {
//搜索背景视图
let searchView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenW, height: kNavH))
searchView.backgroundColor = kHexOfColor(hexString: "0xE6E6E6")
self.view.addSubview(searchView)
//搜索
let search = UISearchBar.init(frame: CGRect.init(x: 8, y: kNavH - 56, width: kScreenW - 70, height: 56))
search.searchBarStyle = .minimal
search.placeholder = "搜索昵称/手机号"
searchView.addSubview(search)
//取消按钮
let canceBtn = UIButton.init(title: "取消", titleColor: kHexOfColor(hexString: "0x333333"), font: 14.0)
canceBtn.frame = CGRect.init(x: kScreenW - 62, y: kNavH - 56, width: 50, height: 56)
canceBtn.addTarget(self, action: #selector(touchLeftBtn), for: .touchUpInside)
searchView.addSubview(canceBtn)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
//
// RPPoetryListController.swift
// RYPoetry
//
// Created by 王荣庆 on 2017/10/19.
// Copyright © 2017年 RyukieSama. All rights reserved.
//
import UIKit
class RPPoetryListController: RPBaseController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupUI()
loadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "segueToReadPoetryDetail" {
let vc = segue.destination as! RPReaderController
vc.poetry = poetries[selectedIndex]
}
}
// MARK: - UI
@IBOutlet var tvMain: UITableView!
private func setupUI() {
tvMain.register(UINib.init(nibName: "RPPoetryListCell", bundle: nil), forCellReuseIdentifier: "RPPoetryListCell")
}
// MARK: - data
private var poetries = [RPPoetryBaseModel]()
private var selectedIndex = 0
private func loadData() {
if (dic.count == 0) {//加载全部
RPPoetryHelper.sharedHelper.loadAllPoetry(callBack: { (poetryArr) in
self.poetries = poetryArr as! [RPPoetryBaseModel]
self.tvMain.reloadData()
})
return
}
//按卷号加载
let volume = dic["volume"] as! Int
if volume > 0 {
RPPoetryHelper.sharedHelper.loadPoetries(inVolume: volume) { (poetryArr) in
print(poetryArr.count)
self.poetries = poetryArr as! [RPPoetryBaseModel]
self.tvMain.reloadData()
}
return
}
//按作者加载
let author = dic["author"] as! String
if author.count > 0 {
RPPoetryHelper.sharedHelper.loadPoetries(ofAuthor: author) { (poetryArr) in
print(poetryArr.count)
self.poetries = poetryArr as! [RPPoetryBaseModel]
self.tvMain.reloadData()
}
return
}
}
}
extension RPPoetryListController : UITableViewDelegate,UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return poetries.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RPPoetryListCell", for: indexPath) as! RPPoetryListCell
cell.bindPoetryModel(poetry: poetries[indexPath.row])
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedIndex = indexPath.row
performSegue(withIdentifier: "segueToReadPoetryDetail", sender: nil)
}
}
|
//
// sdkPath.swift
// compile_ios
//
// Created by Adrian Labbe on 12/31/18.
// Copyright © 2018 Adrian Labbé. All rights reserved.
//
import Foundation
/// Returns the iOS sdk path.
var sdkPath: String = {
var sdkPath: String?
let sdkPipe = Pipe()
sdkPipe.fileHandleForReading.readabilityHandler = { handle in
if let str = String(data: handle.availableData, encoding: .utf8)?.replacingOccurrences(of: "\n", with: ""), FileManager.default.fileExists(atPath: str) {
sdkPath = str
}
}
let findSDK = RunExecutable(atPath: "/usr/bin/xcrun", withArguments: ["--sdk", "iphoneos", "--show-sdk-path"], standardOutput: sdkPipe)
guard findSDK == 0, sdkPath != nil else {
fputs("Cannot find SDK!\n", stderr)
exit(1)
}
return sdkPath!
}()
|
import UIKit
extension UIAlertController {
func showOnASubview() {
let alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow.rootViewController = UIViewController()
alertWindow.windowLevel = UIWindowLevelAlert + 1;
alertWindow.makeKeyAndVisible()
alertWindow.rootViewController?.present(self, animated: true, completion: nil)
}
}
|
//
// MainRouter.swift
// ComprasUSA
//
// Created by Alessandro on 14/08/19.
// Copyright © 2019 Alessandro. All rights reserved.
//
import Foundation
import UIKit
// MARK: CustomersRouter
class MainRouter: UINavigationController ,MainRouterProtocol{
// MARK: Properties
var window: UIWindow?
let myTabBarController = UITabBarController()
// MARK: Initializers
convenience init(window: UIWindow?) {
self.init()
self.window = window
}
func inicialView() {
let buyVC = BuyViewController()
buyVC.title = "Compra"
let settingsVC = SettingsViewController()
settingsVC.title = "Ajustes"
let taxesVC = TaxesViewController()
taxesVC.title = "Taxas"
buyVC.tabBarItem = UITabBarItem(title: "Compra", image: UIImage.init(named: "bag"), tag: 0)
settingsVC.tabBarItem = UITabBarItem(title: "Ajustes", image: UIImage.init(named: "settings"), tag: 1)
taxesVC.tabBarItem = UITabBarItem(title: "Taxas", image: UIImage.init(named: "taxes"), tag: 2)
let controllers = [buyVC, settingsVC, taxesVC]
myTabBarController.viewControllers = controllers
myTabBarController.viewControllers = controllers.map { UINavigationController(rootViewController: $0)}
window?.rootViewController = myTabBarController
window?.rootViewController?.navigationItem.title = "Teste"
}
}
|
//
// PlaceTests.swift
//
//
// Created by Vladislav Fitc on 12/04/2020.
//
import Foundation
import XCTest
@testable import AlgoliaSearchClient
class PlaceTests: XCTestCase {
func testDecoding() throws {
let place = try AssertDecode(jsonFilename: "Place.json", expected: Place.self)
XCTAssertEqual(place.country, "Denmark")
XCTAssertEqual(place.isCountry, false)
XCTAssertEqual(place.isHighway, false)
XCTAssertEqual(place.importance, 16)
XCTAssertEqual(place.tags, ["city", "country/dk", "place/city", "source/geonames"])
XCTAssertEqual(place.postcode, ["8000"])
XCTAssertEqual(place.county, ["Aarhus Municipality"])
XCTAssertEqual(place.population, 256018)
XCTAssertEqual(place.countryCode, .denmark)
XCTAssertEqual(place.isCity, true)
XCTAssertEqual(place.isPopular, true)
XCTAssertEqual(place.administrative, ["Region Midtjylland"])
XCTAssertEqual(place.adminLevel, 15)
XCTAssertEqual(place.isSuburb, false)
XCTAssertEqual(place.localeNames, ["Aarhus"])
}
func testDecodingMultiLanguage() throws {
// try let place = AssertDecode(jsonFilename: "MultiLanguagePlace.json", expected: Place.self)
}
}
|
//
// TitleButton.swift
// WeiBo
//
// Created by 覃鹏成 on 2017/6/9.
// Copyright © 2017年 qinpengcheng. All rights reserved.
//
import UIKit
class TitleButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setImage(UIImage(named : "down"), for: .normal)
setImage(UIImage(named : "down"), for: .selected)
setTitleColor(UIColor.white, for: .normal)
sizeToFit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel?.frame.origin.x = 0
imageView?.frame.origin.x = (titleLabel?.bounds.size.width)! + 5
}
}
|
//
// APIManager.swift
// Ready4sApplication
//
// Created by Maciej Hełmecki on 15.06.2017.
// Copyright © 2017 Maciej Hełmecki. All rights reserved.
//
import Foundation
import CoreLocation
final class APIManager: APIManagerType {
// MARK: Properties
static let shared: APIManagerType = APIManager()
fileprivate let urlBuilder: URLBuilderType
fileprivate let requestBuilder: RequestBuilderType
// MARK: Initializer
init(urlBuilder: URLBuilderType = URLBuilder(), requestBuilder: RequestBuilderType = RequestBuilder()) {
self.urlBuilder = urlBuilder
self.requestBuilder = requestBuilder
}
// MARK: API
func getPlaces(latitude: Double, longitude: Double, completion: @escaping (Result<[[String:Any]]>) -> ()) {
requestBuilder.GETRequest(withURL: urlBuilder.buildURL(latitude: latitude, longitude: longitude)) {
(result: Result<[[String:Any]]>) in
switch result {
case .error(error: let error):
DispatchQueue.main.async {
completion(Result.error(error: error))
}
case .success(result: let response):
DispatchQueue.main.async {
guard !response.isEmpty else { return }
completion(Result.success(result: response))
}
}
}
}
func getImage(image stringData: String, completion: @escaping (Result<Data>) -> ()) {
requestBuilder.GETImageData(withURL: urlBuilder.getImage(imageURL: stringData)) {
(result: Result<Data>) in
switch result {
case .error(error: let error):
DispatchQueue.main.async {
completion(Result.error(error: error))
}
case .success(result: let response):
DispatchQueue.main.async {
guard !response.isEmpty else { return }
completion(Result.success(result: response))
}
}
}
}
}
|
//
// SchoolClassStruct.swift
// MTHS
//
// Created by Patrick Coxall on 2016-08-06.
// Copyright © 2016 Patrick Coxall. All rights reserved.
//
//import Foundation
struct SchoolClass {
var semester : String!
var period : String!
var course : String!
var room : String!
var teacher : String!
var day : String! // for 7&8 students
}
|
//
// ContentView.swift
// CheckGo
//
// Created by Максим on 20.12.2020.
//
import SwiftUI
struct ContentView: View {
@State private var dishName = ""
@State private var dishCount = 0
@State private var dishPrice = ""
@State var personInGroup = 0
@State var tip = 0
let tipAmount = [0, 5, 10, 15, 20, 25]
//propetry wrapper is a solution to change values while program runs
//furthermore it allow us to store value in the place in SwiftUI
//that can be modified
//@state is for simple properties that will store only on one view
var totalPrice: Double {
//if no food declared = price insta 0
let dishConvertedPrice = Double(dishPrice) ?? 0
//because person count started from 0, nor a 1
let dishConvertedCount = Double(dishCount)
let totalPrice = (dishConvertedPrice * dishConvertedCount)
return totalPrice
}
var totalTip: Double {
let tipConverted = Double(tipAmount[tip])
let totalTip = totalPrice * tipConverted / 100
return totalTip
}
var pricePerPerson: Double {
let personConverted = Double(personInGroup + 1)
let pricePerPerson = (totalPrice + totalTip) / personConverted
return pricePerPerson
}
var body: some View {
NavigationView{
Form{
Section {
TextField("Select your dishes price:", text: $dishPrice).keyboardType(.decimalPad)
//$ sign before means that we will rewrite variable, not only read
Text("You price: \(dishPrice)")
//and here we need only to read variable
}
Section(header: Text("Dishes amount")) {
Button("Plus"){
self.dishCount+=1
}
Text("Currently dishes: \(dishCount)")
Button("Minus"){
if dishCount == 0{
}else{
self.dishCount-=1
}}}
Section(header: Text("How much person with you")) {
Picker("Choose number of person", selection: $personInGroup){
ForEach(1..<5){
Text("\($0) person")
}
}.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("How much tip want you pay"), footer: Text("Good choice")) {
Picker("Choose tip amount", selection: $tip){
ForEach(0..<tipAmount.count){
Text("\(self.tipAmount[$0])%")
}
}
.pickerStyle(SegmentedPickerStyle())
}
Text("Each person should pay \(pricePerPerson, specifier: "%.2f")$")
Section(header: Text("Your price:"), footer: Text("Thanks for using my app")) {
Text("Price of your purchase is: \(totalPrice, specifier: "%.2f")$")
HStack{
Text("Total tip for your dishes is: ")
if totalTip == 0{
Text("\(totalTip, specifier: "%.2f")$").foregroundColor(.red)
}else{
Text("\(totalTip, specifier: "%.2f")$")
}
}
}
}.navigationBarTitle("CheckGO", displayMode: .large)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
//
// ViewController.swift
// FunkyNotes
//
// Created by CARL SHOW on 9/21/21.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate
{
@IBOutlet weak var inp1: UITextField!
@IBOutlet weak var inp2: UITextField!
@IBOutlet weak var theButton: UIButton!
@IBOutlet weak var printField: UILabel!
@IBOutlet weak var swapper: UIButton!
var swappi = [false, false]
override func viewDidLoad() {
super.viewDidLoad()
theButton.layer.cornerRadius = 11
swapper.layer.cornerRadius = 11
inp1.delegate = self
inp2.delegate = self
}
@IBAction func buttonPress(_ sender: Any)
{
if let x = Double(inp1.text!)
{
if let y = Double(inp2.text!)
{
if swappi == [true, false]
{
printField.text = "Your perimeter is \(calcPerm(r: x, e: y)) units"
printField.backgroundColor = #colorLiteral(red: 0.7318757176, green: 0.8231084943, blue: 0.7646507621, alpha: 1)
// print("AAA")
}
else if swappi == [false, false]
{
printField.text = "Your area is \(calcRatio(r: x, e: y)) units^2"
printField.backgroundColor = #colorLiteral(red: 0.7318757176, green: 0.8231084943, blue: 0.7646507621, alpha: 1)
}
else
{
let o = calcRec(r: x, e: y)
printField.text = "Your area is \(o.area) and your perimeter is \(o.perimeter)"
printField.backgroundColor = #colorLiteral(red: 0.6980804205, green: 0.5548057556, blue: 0.6686703563, alpha: 0.928580682)
}
}
else
{
printField.text = "Your second input isn't valid, please re-enter your info."
printField.backgroundColor = #colorLiteral(red: 0.6686505079, green: 0.339101851, blue: 0.3927092552, alpha: 1)
}
}
else
{
printField.text = "Your first input isn't valid, please re-enter your info."
printField.backgroundColor = #colorLiteral(red: 0.6686505079, green: 0.339101851, blue: 0.3927092552, alpha: 1)
}
}
@IBAction func swapping(_ sender: Any)
{
if swappi == [false, true]
{
swappi = [false, false]
swapper.backgroundColor = #colorLiteral(red: 0.5166373253, green: 0.6924422383, blue: 0.5756877065, alpha: 1)
swapper.setTitle("( Area )", for: .normal)
theButton.setTitle("Calculate Area", for: .normal)
}
else if swappi == [false, false]
{
swappi = [true, false]
swapper.backgroundColor = #colorLiteral(red: 0.3024700284, green: 0.3434299827, blue: 0.6458516121, alpha: 1)
swapper.setTitle("( Perimeter )", for: .normal)
theButton.setTitle("Calculate Perimeter", for: .normal)
}
else
{
swappi = [false, true]
swapper.backgroundColor = #colorLiteral(red: 0.5725490451, green: 0, blue: 0.2313725501, alpha: 1)
swapper.setTitle("( Rect )", for: .normal)
theButton.setTitle("Calculate Rectangle", for: .normal)
}
}
func calcRatio(r: Double, e: Double) -> String
{
return String( r * e )
}
func calcPerm(r: Double, e: Double) -> String
{
return String( 2 * r + 2 * e )
}
func calcRec(r: Double, e: Double) -> (area: Double, perimeter: Double)
{
return (area: r * e, perimeter: 2 * r + 2 * e)
}
}
|
//
// TagListView.swift
// TagListViewDemo
//
// Created by Dongyuan Liu on 2015-05-09.
// Copyright (c) 2015 Ela. All rights reserved.
//
import UIKit
@objc protocol TagListViewDelegate {
@objc optional func tagPressed(_ title: String, tagView: TagView, sender: TagListView) -> Void
@objc optional func tagRemoveButtonPressed(_ title: String, tagView: TagView, sender: TagListView) -> Void
}
@IBDesignable
class TagListView: UIView {
var maxWidthPerecentage: CGFloat = 0.7
var buttonBorderWidth: CGFloat = 0
@IBInspectable dynamic var textColor: UIColor = UIColor.white {
didSet {
for tagView in tagViews {
tagView.textColor = textColor
}
}
}
@IBInspectable dynamic var selectedTextColor: UIColor = UIColor.white {
didSet {
for tagView in tagViews {
tagView.selectedTextColor = selectedTextColor
}
}
}
@IBInspectable dynamic var tagLineBreakMode: NSLineBreakMode = .byTruncatingTail {
didSet {
for tagView in tagViews {
tagView.titleLineBreakMode = tagLineBreakMode
}
}
}
@IBInspectable dynamic var tagBackgroundColor: UIColor = UIColor.gray {
didSet {
for tagView in tagViews {
tagView.tagBackgroundColor = tagBackgroundColor
}
}
}
@IBInspectable dynamic var tagHighlightedBackgroundColor: UIColor? {
didSet {
for tagView in tagViews {
tagView.highlightedBackgroundColor = tagHighlightedBackgroundColor
}
}
}
@IBInspectable dynamic var tagSelectedBackgroundColor: UIColor? {
didSet {
for tagView in tagViews {
tagView.selectedBackgroundColor = tagSelectedBackgroundColor
}
}
}
@IBInspectable dynamic var cornerRadiu: CGFloat = 0 {
didSet {
for tagView in tagViews {
tagView.cornerRadiu = cornerRadiu
}
}
}
@IBInspectable dynamic var borderWidt: CGFloat = 0 {
didSet {
for tagView in tagViews {
tagView.hippoBorderWidth = buttonBorderWidth
}
}
}
@IBInspectable dynamic var borderColo: UIColor? {
didSet {
for tagView in tagViews {
tagView.hippoBorderColor = hippoBorderColor
}
}
}
@IBInspectable dynamic var selectedBorderColor: UIColor? {
didSet {
for tagView in tagViews {
tagView.selectedBorderColor = selectedBorderColor
}
}
}
@IBInspectable dynamic var paddingY: CGFloat = 2 {
didSet {
for tagView in tagViews {
tagView.paddingY = paddingY
}
rearrangeViews()
}
}
@IBInspectable dynamic var paddingX: CGFloat = 5 {
didSet {
for tagView in tagViews {
tagView.paddingX = paddingX
}
rearrangeViews()
}
}
@IBInspectable dynamic var marginY: CGFloat = 5 {
didSet {
rearrangeViews()
}
}
@IBInspectable dynamic var marginX: CGFloat = 5 {
didSet {
rearrangeViews()
}
}
@objc public enum Alignment: Int {
case left
case center
case right
}
@IBInspectable var alignment: Alignment = .left {
didSet {
rearrangeViews()
}
}
@IBInspectable dynamic var shadowColor: UIColor = UIColor.white {
didSet {
rearrangeViews()
}
}
@IBInspectable dynamic var shadowRadius: CGFloat = 0 {
didSet {
rearrangeViews()
}
}
@IBInspectable dynamic var shadowOffset: CGSize = CGSize.zero {
didSet {
rearrangeViews()
}
}
@IBInspectable dynamic var shadowOpacity: Float = 0 {
didSet {
rearrangeViews()
}
}
@IBInspectable dynamic var enableRemoveButton: Bool = false {
didSet {
for tagView in tagViews {
tagView.enableRemoveButton = enableRemoveButton
}
rearrangeViews()
}
}
@IBInspectable dynamic var removeButtonIconSize: CGFloat = 12 {
didSet {
for tagView in tagViews {
tagView.removeButtonIconSize = removeButtonIconSize
}
rearrangeViews()
}
}
@IBInspectable dynamic var removeIconLineWidth: CGFloat = 1 {
didSet {
for tagView in tagViews {
tagView.removeIconLineWidth = removeIconLineWidth
}
rearrangeViews()
}
}
@IBInspectable dynamic var removeIconLineColor: UIColor = UIColor.white.withAlphaComponent(0.54) {
didSet {
for tagView in tagViews {
tagView.removeIconLineColor = removeIconLineColor
}
rearrangeViews()
}
}
@objc dynamic var textFont: UIFont = UIFont.regular(ofSize: 12) {
didSet {
for tagView in tagViews {
tagView.textFont = textFont
}
rearrangeViews()
}
}
@IBOutlet weak var delegate: TagListViewDelegate?
private(set) var tagViews: [TagView] = []
private(set) var tagBackgroundViews: [UIView] = []
private(set) var rowViews: [UIView] = []
private(set) var tagViewHeight: CGFloat = 0
private(set) var rows = 0 {
didSet {
invalidateIntrinsicContentSize()
}
}
// MARK: - Interface Builder
override public func prepareForInterfaceBuilder() {
// addTag("Welcome")
// addTag("to")
// addTag("TagListView").isSelected = true
}
// MARK: - Layout
override public func layoutSubviews() {
super.layoutSubviews()
rearrangeViews()
}
private func rearrangeViews() {
let views = tagViews as [UIView] + tagBackgroundViews + rowViews
for view in views {
view.removeFromSuperview()
}
rowViews.removeAll(keepingCapacity: true)
var currentRow = 0
var currentRowView: UIView!
var currentRowTagCount = 0
var currentRowWidth: CGFloat = 0
for (index, tagView) in tagViews.enumerated() {
tagView.frame.size = tagView.intrinsicContentSize
tagViewHeight = tagView.frame.height
if currentRowTagCount == 0 || currentRowWidth + tagView.frame.width > frame.width {
currentRow += 1
currentRowWidth = 0
currentRowTagCount = 0
currentRowView = UIView()
currentRowView.frame.origin.y = CGFloat(currentRow - 1) * (tagViewHeight + marginY)
rowViews.append(currentRowView)
addSubview(currentRowView)
tagView.frame.size.width = min(tagView.frame.size.width, frame.width)
}
let tagBackgroundView = tagBackgroundViews[index]
tagBackgroundView.frame.origin = CGPoint(x: currentRowWidth, y: 0)
tagBackgroundView.frame.size = tagView.bounds.size
tagBackgroundView.layer.shadowColor = shadowColor.cgColor
tagBackgroundView.layer.shadowPath = UIBezierPath(roundedRect: tagBackgroundView.bounds, cornerRadius: tagView.cornerRadiu).cgPath
tagBackgroundView.layer.shadowOffset = shadowOffset
tagBackgroundView.layer.shadowOpacity = shadowOpacity
tagBackgroundView.layer.shadowRadius = shadowRadius
tagBackgroundView.addSubview(tagView)
currentRowView.addSubview(tagBackgroundView)
currentRowTagCount += 1
currentRowWidth += tagView.frame.width + marginX
switch alignment {
case .left:
currentRowView.frame.origin.x = 0
case .center:
currentRowView.frame.origin.x = (frame.width - (currentRowWidth - marginX)) / 2
case .right:
currentRowView.frame.origin.x = frame.width - (currentRowWidth - marginX)
}
currentRowView.frame.size.width = currentRowWidth
currentRowView.frame.size.height = max(tagViewHeight, currentRowView.frame.height)
}
rows = currentRow
invalidateIntrinsicContentSize()
}
// MARK: - Manage tags
override public var intrinsicContentSize: CGSize {
var height = CGFloat(rows) * (tagViewHeight + marginY)
if rows > 0 {
height -= marginY
}
return CGSize(width: frame.width, height: height)
}
private func createNewTagView(_ object: TagViewCreation) -> TagView {
let tagView = TagView(title: object.name)
tagView.maxWidthPerecentage = maxWidthPerecentage
tagView.textColor = object.tagViewTextColor
tagView.detail = object
tagView.selectedTextColor = selectedTextColor
tagView.tagBackgroundColor = object.color
tagView.highlightedBackgroundColor = tagHighlightedBackgroundColor
tagView.selectedBackgroundColor = tagSelectedBackgroundColor
tagView.titleLineBreakMode = tagLineBreakMode
tagView.cornerRadiu = 10//cornerRadius
tagView.hippoBorderWidth = buttonBorderWidth//hippoBorderWidth
tagView.hippoBorderColor = borderColo
tagView.selectedBorderColor = selectedBorderColor
tagView.paddingX = paddingX
tagView.paddingY = paddingY
tagView.textFont = textFont
tagView.removeIconLineWidth = removeIconLineWidth
tagView.removeButtonIconSize = removeButtonIconSize
tagView.enableRemoveButton = enableRemoveButton
tagView.removeIconLineColor = removeIconLineColor
tagView.addTarget(self, action: #selector(tagPressed(_:)), for: .touchUpInside)
tagView.removeButton.addTarget(self, action: #selector(removeButtonPressed(_:)), for: .touchUpInside)
tagView.frame = CGRect(x: tagView.frame.origin.x, y: tagView.frame.origin.y, width: tagView.frame.width + 50, height: tagView.frame.height)
if object.circlularCorner {
tagView.cornerRadiu = tagView.intrinsicContentSize.height / 2
}
// On long press, deselect all tags except this one
tagView.onLongPress = { [unowned self] this in
for tag in self.tagViews {
tag.isSelected = (tag == this)
}
}
return tagView
}
private func createNewTagView(_ object: TagDetail) -> TagView {
let tagView = TagView(title: object.tagName ?? "")
tagView.textColor = UIColor.white
tagView.selectedTextColor = selectedTextColor
tagView.tagBackgroundColor = UIColor.hexStringToUIColor(hex: object.colorCode ?? "")
tagView.highlightedBackgroundColor = tagHighlightedBackgroundColor
tagView.selectedBackgroundColor = tagSelectedBackgroundColor
tagView.titleLineBreakMode = tagLineBreakMode
tagView.cornerRadiu = 6//cornerRadius
tagView.hippoBorderWidth = buttonBorderWidth//hippoBorderWidth
tagView.hippoBorderColor = hippoBorderColor
tagView.selectedBorderColor = selectedBorderColor
tagView.paddingX = paddingX
tagView.paddingY = paddingY
tagView.textFont = textFont
tagView.removeIconLineWidth = removeIconLineWidth
tagView.removeButtonIconSize = removeButtonIconSize
tagView.enableRemoveButton = enableRemoveButton
tagView.removeIconLineColor = removeIconLineColor
tagView.addTarget(self, action: #selector(tagPressed(_:)), for: .touchUpInside)
tagView.removeButton.addTarget(self, action: #selector(removeButtonPressed(_:)), for: .touchUpInside)
tagView.frame = CGRect(x: tagView.frame.origin.x, y: tagView.frame.origin.y, width: tagView.frame.width + 50, height: tagView.frame.height)
// On long press, deselect all tags except this one
tagView.onLongPress = { [unowned self] this in
for tag in self.tagViews {
tag.isSelected = (tag == this)
}
}
return tagView
}
func addTag(_ object: TagDetail) -> TagView {
return addTagView(createNewTagView(object))
}
func addTags(_ objects: [TagDetail]) -> [TagView] {
var tagViews: [TagView] = []
for object in objects {
tagViews.append(createNewTagView(object))
}
return addTagViews(tagViews)
}
func addTag(_ object: TagViewCreation) -> TagView {
return addTagView(createNewTagView(object))
}
@discardableResult
func addTags(_ objects: [TagViewCreation]) -> [TagView] {
var tagViews: [TagView] = []
for object in objects {
tagViews.append(createNewTagView(object))
}
return addTagViews(tagViews)
}
func addTagViews(_ tagViews: [TagView]) -> [TagView] {
for tagView in tagViews {
self.tagViews.append(tagView)
tagBackgroundViews.append(UIView(frame: tagView.bounds))
}
rearrangeViews()
return tagViews
}
func insertTag(_ object: TagDetail, at index: Int) -> TagView {
return insertTagView(createNewTagView(object), at: index)
}
func addTagView(_ tagView: TagView) -> TagView {
tagViews.append(tagView)
tagBackgroundViews.append(UIView(frame: tagView.bounds))
rearrangeViews()
return tagView
}
@discardableResult
func insertTagView(_ tagView: TagView, at index: Int) -> TagView {
tagViews.insert(tagView, at: index)
tagBackgroundViews.insert(UIView(frame: tagView.bounds), at: index)
rearrangeViews()
return tagView
}
func setTitle(_ title: String, at index: Int) {
tagViews[index].titleLabel?.text = title
}
func removeTag(_ title: String) {
// loop the array in reversed order to remove items during loop
for index in stride(from: (tagViews.count - 1), through: 0, by: -1) {
let tagView = tagViews[index]
if tagView.currentTitle == title {
removeTagView(tagView)
}
}
}
func removeTagView(_ tagView: TagView) {
tagView.removeFromSuperview()
if let index = tagViews.firstIndex(of: tagView) {
tagViews.remove(at: index)
tagBackgroundViews.remove(at: index)
}
rearrangeViews()
}
func removeAllTags() {
let views = tagViews as [UIView] + tagBackgroundViews
for view in views {
view.removeFromSuperview()
}
tagViews = []
tagBackgroundViews = []
rearrangeViews()
}
func selectedTags() -> [TagView] {
return tagViews.filter() { $0.isSelected == true }
}
// MARK: - Events
@objc func tagPressed(_ sender: TagView!) {
sender.onTap?(sender)
delegate?.tagPressed?(sender.currentTitle ?? "", tagView: sender, sender: self)
}
@objc func removeButtonPressed(_ closeButton: CloseButton!) {
if let tagView = closeButton.tagView {
delegate?.tagRemoveButtonPressed?(tagView.currentTitle ?? "", tagView: tagView, sender: self)
}
}
}
|
//
// GalleryImagesVC.swift
// SaneScanner
//
// Created by Stanislas Chevallier on 24/02/2019.
// Copyright © 2019 Syan. All rights reserved.
//
import UIKit
#if !targetEnvironment(macCatalyst)
class GalleryImagesVC: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
pagesVC.dataSource = self
pagesVC.delegate = self
pagesVC.willMove(toParent: self)
addChild(pagesVC)
view.addSubview(pagesVC.view)
pagesVC.view.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
pagesVC.didMove(toParent: self)
GalleryManager.shared.addDelegate(self)
openImage(at: initialIndex ?? 0, animated: false)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateNavBarContent()
updateToolbarContent()
updateDisplayMode(showNavBars: true, animated: false)
}
// MARK: Properties
var initialIndex: Int?
private var items = [GalleryItem]()
private(set) var currentIndex: Int? {
didSet {
updateNavBarContent()
updateToolbarContent()
}
}
override var prefersStatusBarHidden: Bool {
return navigationController?.isNavigationBarHidden ?? super.prefersStatusBarHidden
}
override var prefersHomeIndicatorAutoHidden: Bool {
return navigationController?.isNavigationBarHidden ?? super.prefersHomeIndicatorAutoHidden
}
// MARK: Views
private let pagesVC = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
// MARK: Actions
func openImage(at index: Int, animated: Bool) {
// don't ignore if index == currentIndex, because the image list may have changed (for instance when deleting
// the first image) and we still need to show the new page
guard let vc = imageViewController(at: index) else { return }
let isAfterCurrent = index >= (currentIndex ?? 0)
currentIndex = index
pagesVC.setViewControllers([vc], direction: isAfterCurrent ? .forward : .reverse, animated: animated, completion: nil)
}
@objc private func closeButtonTap() {
dismiss(animated: true, completion: nil)
}
@objc private func deleteCurrentImage(sender: UIBarButtonItem) {
guard let currentIndex = currentIndex else { return }
let item = items[currentIndex]
deleteGalleryItems([item], sender: sender)
}
@objc private func shareCurrentImage(sender: UIBarButtonItem) {
guard let currentIndex = currentIndex else { return }
let item = items[currentIndex]
UIActivityViewController.showForURLs([item.url], from: sender, presentingVC: self)
}
// MARK: Content
private func imageViewController(at index: Int) -> GalleryImageVC? {
guard index >= 0, index < items.count else { return nil }
let vc = GalleryImageVC(item: items[index], index: index)
vc.delegate = self
return vc
}
private func toggleDisplayMode(animated: Bool) {
let navBarsCurrentlyHidden = navigationController?.isNavigationBarHidden ?? false
updateDisplayMode(showNavBars: navBarsCurrentlyHidden, animated: animated)
}
private func updateDisplayMode(showNavBars: Bool, animated: Bool) {
if animated {
UIView.transition(with: view.window ?? view, duration: 0.3, options: .transitionCrossDissolve, animations: {
self.updateDisplayMode(showNavBars: showNavBars, animated: false)
}, completion: nil)
return
}
let canHideNavBars = navigationController?.isModal ?? false
let hideNavBars = !showNavBars && canHideNavBars
navigationController?.isNavigationBarHidden = hideNavBars
navigationController?.isToolbarHidden = hideNavBars
view.backgroundColor = hideNavBars ? .black : .background
setNeedsStatusBarAppearanceUpdate()
setNeedsUpdateOfHomeIndicatorAutoHidden()
}
private func updateNavBarContent() {
title = "GALLERY ITEM %d OF %d".localized((currentIndex ?? 0) + 1, items.count)
if navigationController?.isModal == true {
navigationItem.rightBarButtonItem = .close(target: self, action: #selector(self.closeButtonTap))
} else {
navigationItem.rightBarButtonItem = nil
}
}
private func updateToolbarContent() {
guard let currentIndex = currentIndex else {
toolbarItems = nil
return
}
let titleButton = UIBarButtonItem(
title: items[currentIndex].creationDateString(includingTime: true, allowRelative: true),
style: .plain, target: nil, action: nil
)
titleButton.tintColor = .normalText
toolbarItems = [
UIBarButtonItem.share(target: self, action: #selector(self.shareCurrentImage(sender:))),
UIBarButtonItem.flexibleSpace,
titleButton,
UIBarButtonItem.flexibleSpace,
UIBarButtonItem.delete(target: self, action: #selector(self.deleteCurrentImage(sender:))),
]
}
}
extension GalleryImagesVC : UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let currentVC = viewController as? GalleryImageVC else { return nil }
return imageViewController(at: currentVC.galleryIndex - 1)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let currentVC = viewController as? GalleryImageVC else { return nil }
return imageViewController(at: currentVC.galleryIndex + 1)
}
}
extension GalleryImagesVC : UIPageViewControllerDelegate {
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if completed {
currentIndex = (pageViewController.viewControllers?.first as? GalleryImageVC)?.galleryIndex
}
}
}
extension GalleryImagesVC : GalleryImageVCDelegate {
func galleryImageVC(singleTapped: GalleryImageVC) {
toggleDisplayMode(animated: true)
}
}
extension GalleryImagesVC : GalleryManagerDelegate {
func galleryManager(_ manager: GalleryManager, didUpdate items: [GalleryItem], newItems: [GalleryItem], removedItems: [GalleryItem]) {
let prevItems = self.items
self.items = items
guard let prevIndex = currentIndex, !prevItems.isEmpty, !items.isEmpty else { return }
let prevItem = prevItems[prevIndex]
if removedItems.contains(prevItem) {
// if deleting last: show the image before the one that we deleted
// else: reload the current index (visually this will look like going to the next one)
let newIndex = prevIndex >= items.count ? max(0, prevIndex - 1) : prevIndex
openImage(at: newIndex, animated: true)
return
}
guard let newIndex = items.firstIndex(of: prevItem) else { return }
openImage(at: newIndex, animated: false)
}
}
#endif
|
//
// RootViewControllerProtocol.swift
// PopUpCorn
//
// Created by Elias Paulino on 08/06/19.
// Copyright © 2019 Elias Paulino. All rights reserved.
//
import UIKit
@objc protocol RootViewControllerProtocol where Self: UIViewController {
func start(viewController: UIViewController)
func reloadableChildController() -> ReloadableChildProtocol?
}
|
//
// MenuTableViewCell.swift
// TravelApp
//
// Created by User on 7/26/21.
//
import UIKit
class MenuTableViewCell: UITableViewCell {
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var titleImage: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
self.selectionStyle = .none
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func setup(title: String, image: UIImage?) {
titleLabel.text = title
titleImage.image = image
}
}
|
import UIKit
//: ## Basics
//: ### Comparison
let moneyInPocket = 5.0
let beerPrice = 4.0
let chips = 1.0
let whiskyPrice = 6.5
if moneyInPocket >= beerPrice {
print("One beer please!")
}
if moneyInPocket < whiskyPrice {
print("Not enough for whisky")
}
if moneyInPocket == beerPrice + chips {
print("Some food and drink for me")
}
//: ### Logical operators
var boy = true
var married = false
var greatParty = true
if boy && !married {
print("let's go for a party")
}
married = true
if !married || greatParty {
print("No matter what I need to be there")
}
//: ### Ternary operator
//: #### as a shorthand
boy ? print("boy") : print("girl")
//: #### or as an expression
let originalAge = 20
boy = false
let age = originalAge + (boy ? 0 : -2)
|
//
// Copyright © 2020 Tasuku Tozawa. All rights reserved.
//
import Common
import Smoothie
public class ClipCommandService {
let clipStorage: ClipStorageProtocol
let referenceClipStorage: ReferenceClipStorageProtocol
let imageStorage: ImageStorageProtocol
let diskCache: DiskCaching
let logger: TBoxLoggable
let queue: DispatchQueue
private(set) var isTransporting: Bool = false
// MARK: - Lifecycle
public init(clipStorage: ClipStorageProtocol,
referenceClipStorage: ReferenceClipStorageProtocol,
imageStorage: ImageStorageProtocol,
diskCache: DiskCaching,
logger: TBoxLoggable,
queue: DispatchQueue)
{
self.clipStorage = clipStorage
self.referenceClipStorage = referenceClipStorage
self.imageStorage = imageStorage
self.diskCache = diskCache
self.logger = logger
self.queue = queue
}
}
extension ClipCommandService: ClipCommandServiceProtocol {
// MARK: - ClipCommandServiceProtocol
// MARK: Create
public func create(clip: ClipRecipe, withContainers containers: [ImageContainer], forced: Bool) -> Result<Clip.Identity, ClipStorageError> {
return self.queue.sync {
do {
let containsFilesFor = { (item: ClipItemRecipe) in
return containers.contains(where: { $0.id == item.imageId })
}
guard clip.items.allSatisfy({ item in containsFilesFor(item) }) else {
self.logger.write(ConsoleLog(level: .error, message: """
Clipに紐付けれた全Itemの画像データが揃っていない:
- expected: \(clip.items.map { $0.id.uuidString }.joined(separator: ","))
- got: \(containers.map { $0.id.uuidString }.joined(separator: ","))
"""))
return .failure(.invalidParameter)
}
try self.clipStorage.beginTransaction()
try self.imageStorage.beginTransaction()
let clipId: Clip.Identity
switch self.clipStorage.create(clip: clip) {
case let .success(clip):
clipId = clip.id
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
try? self.imageStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
クリップの保存に失敗: \(error.localizedDescription)
"""))
return .failure(error)
}
containers.forEach { container in
try? self.imageStorage.create(container.data, id: container.id)
}
try self.clipStorage.commitTransaction()
try self.imageStorage.commitTransaction()
return .success(clipId)
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
try? self.imageStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
クリップの保存に失敗: \(error.localizedDescription)
"""))
return .failure(.internalError)
}
}
}
public func create(tagWithName name: String) -> Result<Tag.Identity, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
try self.referenceClipStorage.beginTransaction()
let tag: Tag
switch self.clipStorage.create(tagWithName: name) {
case let .success(result):
tag = result
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
try? self.referenceClipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to create tag. (error=\(error.localizedDescription))
"""))
return .failure(error)
}
switch self.referenceClipStorage.create(tag: .init(id: tag.identity, name: tag.name, isHidden: tag.isHidden)) {
case .success:
break
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
try? self.referenceClipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to create tag. (error=\(error.localizedDescription))
"""))
return .failure(error)
}
try self.clipStorage.commitTransaction()
try self.referenceClipStorage.commitTransaction()
return .success(tag.id)
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
try? self.referenceClipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to create tag. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
public func create(albumWithTitle title: String) -> Result<Album.Identity, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
let result = self.clipStorage.create(albumWithTitle: title).map { $0.id }
try self.clipStorage.commitTransaction()
return result
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to create album. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
// MARK: Update
public func updateClips(having ids: [Clip.Identity], byHiding isHidden: Bool) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
let result = self.clipStorage.updateClips(having: ids, byHiding: isHidden).map { _ in () }
try self.clipStorage.commitTransaction()
return result
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to \(isHidden ? "hide" : "show") clips. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
public func updateClips(having clipIds: [Clip.Identity], byAddingTagsHaving tagIds: [Tag.Identity]) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
switch self.clipStorage.updateClips(having: clipIds, byAddingTagsHaving: tagIds) {
case .success:
break
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to update clips. (error=\(error.localizedDescription))
"""))
return .failure(error)
}
try self.clipStorage.commitTransaction()
return .success(())
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to update clips. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
public func updateClips(having clipIds: [Clip.Identity], byDeletingTagsHaving tagIds: [Tag.Identity]) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
switch self.clipStorage.updateClips(having: clipIds, byDeletingTagsHaving: tagIds) {
case .success:
break
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to update clips. (error=\(error.localizedDescription))
"""))
return .failure(error)
}
try self.clipStorage.commitTransaction()
return .success(())
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to update clips. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
public func updateClips(having clipIds: [Clip.Identity], byReplacingTagsHaving tagIds: [Tag.Identity]) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
switch self.clipStorage.updateClips(having: clipIds, byReplacingTagsHaving: tagIds) {
case .success:
break
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to update clips. (error=\(error.localizedDescription))
"""))
return .failure(error)
}
try self.clipStorage.commitTransaction()
return .success(())
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to update clips. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
public func updateClipItems(having ids: [ClipItem.Identity], byUpdatingSiteUrl siteUrl: URL?) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
let result = self.clipStorage.updateClipItems(having: ids, byUpdatingSiteUrl: siteUrl)
try self.clipStorage.commitTransaction()
return result
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to update album. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
public func updateClip(having id: Clip.Identity, byReorderingItemsHaving itemIds: [ClipItem.Identity]) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
let result = self.clipStorage.updateClip(having: id, byReorderingItemsHaving: itemIds)
try self.clipStorage.commitTransaction()
return result
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to update album. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
public func updateAlbum(having albumId: Album.Identity, byAddingClipsHaving clipIds: [Clip.Identity]) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
let result = self.clipStorage.updateAlbum(having: albumId, byAddingClipsHaving: clipIds).map { _ in () }
try self.clipStorage.commitTransaction()
return result
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to update album. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
public func updateAlbum(having albumId: Album.Identity, byDeletingClipsHaving clipIds: [Clip.Identity]) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
let result = self.clipStorage.updateAlbum(having: albumId, byDeletingClipsHaving: clipIds).map { _ in () }
try self.clipStorage.commitTransaction()
return result
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to update album. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
public func updateAlbum(having albumId: Album.Identity, byReorderingClipsHaving clipIds: [Clip.Identity]) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
let result = self.clipStorage.updateAlbum(having: albumId, byReorderingClipsHaving: clipIds).map { _ in () }
try self.clipStorage.commitTransaction()
return result
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to update album. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
public func updateAlbum(having albumId: Album.Identity, titleTo title: String) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
let result = self.clipStorage.updateAlbum(having: albumId, titleTo: title).map { _ in () }
try self.clipStorage.commitTransaction()
return result
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to update album. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
public func updateAlbum(having albumId: Album.Identity, byHiding isHidden: Bool) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
let result = self.clipStorage.updateAlbum(having: albumId, byHiding: isHidden).map { _ in () }
try self.clipStorage.commitTransaction()
return result
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to update album. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
public func updateAlbums(byReordering albumIds: [Album.Identity]) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
let result = self.clipStorage.updateAlbums(byReordering: albumIds).map { _ in () }
try self.clipStorage.commitTransaction()
return result
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to update album. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
public func updateTag(having id: Tag.Identity, nameTo name: String) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
try self.referenceClipStorage.beginTransaction()
switch self.clipStorage.updateTag(having: id, nameTo: name) {
case .success:
break
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
try? self.referenceClipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to update tag. (error=\(error.localizedDescription))
"""))
return .failure(error)
}
switch self.referenceClipStorage.updateTag(having: id, nameTo: name) {
case .success:
break
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
try? self.referenceClipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to update tag. (error=\(error.localizedDescription))
"""))
return .failure(error)
}
try self.clipStorage.commitTransaction()
try self.referenceClipStorage.commitTransaction()
return .success(())
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
try? self.referenceClipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to update tag. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
public func updateTag(having id: Tag.Identity, byHiding isHidden: Bool) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
let result = self.clipStorage.updateTag(having: id, byHiding: isHidden).map { _ in () }
try self.clipStorage.commitTransaction()
return result
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
try? self.referenceClipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to update tag. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
public func purgeClipItems(forClipHaving id: Domain.Clip.Identity) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
let albumIds: [Domain.Album.Identity]
switch self.clipStorage.readAlbumIds(containsClipsHaving: [id]) {
case let .success(ids):
albumIds = ids
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to purge clip. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
let originalTags: [Domain.Tag]
switch self.clipStorage.readTags(forClipHaving: id) {
case let .success(tags):
originalTags = tags
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to purge clip. (error=\(error.localizedDescription))
"""))
return .failure(error)
}
let originalClip: Domain.Clip
switch self.clipStorage.deleteClips(having: [id]) {
case let .success(clips) where clips.count == 1:
// swiftlint:disable:next force_unwrapping
originalClip = clips.first!
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to purge clip. (error=\(error.localizedDescription))
"""))
return .failure(error)
default:
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to purge clip.
"""))
return .failure(.internalError)
}
let newClips: [ClipRecipe] = originalClip.items.map { item in
let clipId = UUID()
let date = Date()
return ClipRecipe(id: clipId,
description: originalClip.description,
items: [
.init(id: UUID(),
url: item.url,
clipId: clipId,
clipIndex: 0,
imageId: item.imageId,
imageFileName: item.imageFileName,
imageUrl: item.imageUrl,
imageSize: item.imageSize,
imageDataSize: item.imageDataSize,
registeredDate: item.registeredDate,
updatedDate: date)
],
tagIds: originalTags.map { $0.id },
isHidden: originalClip.isHidden,
dataSize: item.imageDataSize,
registeredDate: date,
updatedDate: date)
}
for newClip in newClips {
switch self.clipStorage.create(clip: newClip) {
case .success:
break
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to purge clip. (error=\(error.localizedDescription))
"""))
return .failure(error)
}
}
for albumId in albumIds {
switch self.clipStorage.updateAlbum(having: albumId, byAddingClipsHaving: newClips.map({ $0.id })) {
case .success:
break
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to purge clip. (error=\(error.localizedDescription))
"""))
return .failure(error)
}
}
try self.clipStorage.commitTransaction()
return .success(())
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to purge clip. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
public func mergeClipItems(itemIds: [ClipItem.Identity], tagIds: [Tag.Identity], inClipsHaving clipIds: [Clip.Identity]) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
let albumIds: [Album.Identity]
switch self.clipStorage.readAlbumIds(containsClipsHaving: clipIds) {
case let .success(result):
albumIds = result
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
アルバムの読み取りに失敗. (error=\(error.localizedDescription))
"""))
return .failure(error)
}
let items: [ClipItem]
switch self.clipStorage.readClipItems(having: itemIds) {
case let .success(result):
items = result
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
ClipItemの読み取りに失敗. (error=\(error.localizedDescription))
"""))
return .failure(error)
}
switch self.clipStorage.deleteClips(having: clipIds) {
case .success:
break
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
クリップの削除に失敗 (error=\(error.localizedDescription))
"""))
return .failure(error)
}
let clipId = UUID()
let newItems = items.enumerated().map { index, item in
return ClipItemRecipe(id: UUID(),
url: item.url,
clipId: clipId,
clipIndex: index + 1,
imageId: item.imageId,
imageFileName: item.imageFileName,
imageUrl: item.imageUrl,
imageSize: item.imageSize,
imageDataSize: item.imageDataSize,
registeredDate: item.registeredDate,
updatedDate: Date())
}
let dataSize = newItems
.map { $0.imageDataSize }
.reduce(0, +)
let recipe = ClipRecipe(id: clipId,
description: nil,
items: newItems,
tagIds: tagIds,
isHidden: false,
dataSize: dataSize,
registeredDate: Date(),
updatedDate: Date())
switch self.clipStorage.create(clip: recipe) {
case .success:
break
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
新規クリップの作成に失敗. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
for albumId in albumIds {
switch self.clipStorage.updateAlbum(having: albumId, byAddingClipsHaving: [clipId]) {
case .success:
break
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
アルバムへの追加に失敗. (error=\(error.localizedDescription))
"""))
return .failure(error)
}
}
try self.clipStorage.commitTransaction()
return .success(())
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to merge clips. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
// MARK: Delete
public func deleteClips(having ids: [Clip.Identity]) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
try self.imageStorage.beginTransaction()
let clips: [Clip]
switch self.clipStorage.deleteClips(having: ids) {
case let .success(result):
clips = result
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
try? self.imageStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to delete clips. (error=\(error.localizedDescription))
"""))
return .failure(error)
}
let existsFiles = try clips
.flatMap { $0.items }
.allSatisfy { try self.imageStorage.exists(having: $0.imageId) }
if existsFiles {
clips
.flatMap { $0.items }
.forEach { try? self.imageStorage.delete(having: $0.imageId) }
} else {
self.logger.write(ConsoleLog(level: .error, message: """
No image files found for deleting clip. Ignored
"""))
}
try self.clipStorage.commitTransaction()
try self.imageStorage.commitTransaction()
return .success(())
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
try? self.imageStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to delete clips. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
public func deleteClipItem(_ item: ClipItem) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
try self.imageStorage.beginTransaction()
switch self.clipStorage.deleteClipItem(having: item.id) {
case .success:
break
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
try? self.imageStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to delete clip item. (error=\(error.localizedDescription))
"""))
return .failure(error)
}
guard try self.imageStorage.exists(having: item.imageId) else {
try? self.clipStorage.cancelTransactionIfNeeded()
try? self.imageStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to delete clip item. Image not found.
"""))
return .failure(.internalError)
}
try? self.imageStorage.delete(having: item.imageId)
self.diskCache.remove(forKey: "clip-collection-\(item.identity.uuidString)")
try self.clipStorage.commitTransaction()
try self.imageStorage.commitTransaction()
return .success(())
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
try? self.imageStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to delete clip item. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
public func deleteAlbum(having id: Album.Identity) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
let result = self.clipStorage.deleteAlbum(having: id).map { _ in () }
try self.clipStorage.commitTransaction()
return result
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to delete album. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
public func deleteTags(having ids: [Tag.Identity]) -> Result<Void, ClipStorageError> {
return self.queue.sync {
do {
try self.clipStorage.beginTransaction()
try self.referenceClipStorage.beginTransaction()
switch self.clipStorage.deleteTags(having: ids) {
case .success:
break
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
try? self.referenceClipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to delete tags. (error=\(error.localizedDescription))
"""))
return .failure(error)
}
switch self.referenceClipStorage.deleteTags(having: ids) {
case .success:
break
case let .failure(error):
try? self.clipStorage.cancelTransactionIfNeeded()
try? self.referenceClipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to delete tags. (error=\(error.localizedDescription))
"""))
return .failure(error)
}
try self.clipStorage.commitTransaction()
try self.referenceClipStorage.commitTransaction()
return .success(())
} catch {
try? self.clipStorage.cancelTransactionIfNeeded()
try? self.referenceClipStorage.cancelTransactionIfNeeded()
self.logger.write(ConsoleLog(level: .error, message: """
Failed to delete tags. (error=\(error.localizedDescription))
"""))
return .failure(.internalError)
}
}
}
}
|
import XCTest
import MemoryLeakTestKitTests
var tests = [XCTestCaseEntry]()
tests += MemoryLeakTestKitTests.allTests()
XCTMain(tests) |
//
// Photo+CoreDataClass.swift
// CoreDataTutorial
//
// Created by Vinay Ponnuri on 8/15/18.
// Copyright © 2018 James Rochabrun. All rights reserved.
//
//
import Foundation
import CoreData
public class Photo: NSManagedObject {
}
|
//
// CustomTableViewCell.swift
// PupCare
//
// Created by Uriel Battanoli on 9/5/16.
// Copyright © 2016 PupCare. All rights reserved.
//
import UIKit
class CustomTableViewCell: UITableViewCell {
@IBOutlet weak var firstLbl: UILabel!
@IBOutlet weak var secondLbl: UILabel!
@IBOutlet weak var thirdLbl: UILabel!
@IBOutlet weak var finisheBt: BTNAttributedStyle!
@IBOutlet weak var loaderBt: UIActivityIndicatorView!
@IBOutlet weak var markSelected: UIView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
if let markSelected = self.markSelected{
markSelected.layer.borderWidth = 0.5
markSelected.layer.borderColor = UIColor(red: 145, green: 145, blue: 145).cgColor
markSelected.backgroundColor = UIColor(red: 245, green: 245, blue: 245)
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func selectAddress() {
if let markSelected = self.markSelected{
markSelected.backgroundColor = UIColor(red: 115, green: 40, blue: 115)
}
}
func deselectAddress() {
if let markSelected = self.markSelected{
markSelected.backgroundColor = UIColor(red: 245, green: 245, blue: 245)
}
}
}
|
//
// Message.swift
// ChatApp
//
// Created by CebuSQA on 06/09/2018.
// Copyright © 2018 CebuSQA. All rights reserved.
//
import UIKit
struct Message{
var sender: String?
var text: String?
}
|
import Foundation;
var arr = [Int]()
var buffer = ""
var num = readLine()!
var count = num.characters.count
var c = 0
for i in num.characters{
c += 1
if i == " " {
arr.append(Int(buffer)!)
buffer = ""
}
else{
buffer += String(i)
}
}
if(c == count){
arr.append(Int(buffer)!)
}
var sum: Int = arr.reduce(0,{$0 + $1})
let min = arr.min()!
let max = arr.max()!
print("\(sum - max) \(sum - min)") |
//: [Previous](@previous)
import Combine
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
struct Breed: Equatable, Decodable {
let name: String
let subBreeds: [Breed]
}
struct BreedListAPIModel: Decodable {
let message: [String: [String]]
let status: String
}
func load() -> AnyPublisher<[Breed], Error> {
func convert(from model: BreedListAPIModel) -> [Breed] {
let messages = model.message
return messages.map { message in
Breed(name: message.key,
subBreeds: message.value
.map { Breed(name: $0, subBreeds: []) })
}
}
return URLSession.shared.dataTaskPublisher(for: URL(string: "https://dog.ceo/api/breeds/list/all")!)
.map(\.data)
.decode(type: BreedListAPIModel.self, decoder: JSONDecoder())
.map(convert(from:))
.eraseToAnyPublisher()
}
let subscription = load()
.sink(receiveCompletion: { finished in
print("receiveCompletion: \(finished)")
}, receiveValue: { value in
print("receiveValue: \(value)")
})
//: [Next](@next)
|
//
// PSTimer.swift
// PSTimer
//
// Created by Will on 2018/12/25.
// Copyright © 2018 Pacts. All rights reserved.
//
import UIKit
class PSTimer: NSObject {
/// - parameter timeInterval: The number of seconds between firings of the timer. If seconds is less than or equal to 0.0, this method chooses the nonnegative value of 0.1 milliseconds instead
/// - parameter repeats: If YES, the timer will repeatedly reschedule itself until invalidated. If NO, the timer will be invalidated after it fires.
/// - parameter block: The execution body of the timer; the timer itself is passed as the parameter to this block when executed to aid in avoiding cyclical references
static func scheduledTimer(withTimeInterval:TimeInterval, repeats:Bool, block:@escaping (DispatchSourceTimer) -> Void) -> DispatchSourceTimer {
/// Use the initial below if you wanna excute block on main queue
/// let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
let timer = DispatchSource.makeTimerSource()
timer.schedule(deadline: .now(),
repeating: withTimeInterval,
leeway: DispatchTimeInterval.milliseconds(100))
timer.setEventHandler {
block(timer)
if !repeats
{
timer.cancel()
}
}
return timer
}
}
|
//
// UseCaseFactoryTests.swift
// UserDisplayer
//
// Created by Jeremi Kaczmarczyk on 03/02/2017.
// Copyright © 2017 Jeremi Kaczmarczyk. All rights reserved.
//
import XCTest
@testable import UserDisplayer
class UseCaseFactoryTests: XCTestCase {
var useCaseFactory: UseCaseFactory!
var entityGateway: EntityGateway!
var closureWasInvoked = false
// MARK: - XCTestCase
override func setUp() {
super.setUp()
entityGateway = EntityGatewayMock()
useCaseFactory = UseCaseFactory(entityGateway: entityGateway)
closureWasInvoked = false
}
override func tearDown() {
useCaseFactory = nil
entityGateway = nil
closureWasInvoked = false
super.tearDown()
}
// MARK: - Tests
func testFactoryCreatesShowUserListUseCase() {
let useCase = useCaseFactory.create(useCase: .showUserList(completion: { _ in }))
XCTAssertNotNil(useCase as? ShowUserListUseCase)
}
func testShowUserListClosureInvoked() {
let useCase = useCaseFactory.create(useCase: .showUserList(completion: { _ in self.closureWasInvoked = true }))
useCase.execute()
XCTAssertTrue(closureWasInvoked)
}
func testFactoryCreatesShowPostListUseCase() {
let useCase = useCaseFactory.create(useCase: .showPostList(user: UserDisplayData.mock1, completion: { _ in }))
XCTAssertNotNil(useCase as? ShowPostListUseCase)
}
func testShowPostListClosureInvoked() {
let useCase = useCaseFactory.create(useCase: .showPostList(user: UserDisplayData.mock1, completion: { _ in
self.closureWasInvoked = true
}))
useCase.execute()
XCTAssertTrue(closureWasInvoked)
}
// MARK: - Mocks
class EntityGatewayMock: EntityGateway {
func getUsers(completion: @escaping (Result<[User], Error>) -> Void) {
completion(.success([]))
}
func getPosts(forUserId id: Int, completion: @escaping (Result<[Post], Error>) -> Void) {
completion(.success([]))
}
}
}
|
//
// ClientInfo.swift
// Yeah_SalesExpert
//
// Created by DavisChing on 16/5/16.
// Copyright © 2016年 DavisChing. All rights reserved.
//
import Foundation
class ClientInfo {
private var name : String = ""
private var company = ""
private var job = ""
private var mobile = ""
private var phone = ""
private var email = ""
private var checkList = [Check]()
private var id = 0
private var visit = 0
init(){
//do nothing
}
init(_name : String){
name = _name
id = DataReader.getNewClientId()
}
func getId() -> Int{
return id
}
func setId(newId : Int){
id = newId
}
func setName(_name : String){
name = _name
}
func getName() -> String {
return name
}
func setCompany(_company : String){
company = _company
}
func getCompany() -> String{
return company
}
func setJob(_job : String){
job = _job
}
func getJob() -> String{
return job
}
func setMobile(_mobile : String){
mobile = _mobile
}
func getMobile() -> String{
return mobile
}
func setPhone(_phone : String){
phone = _phone
}
func getPhone() -> String{
return phone
}
func setEmail(_email : String){
email = _email
}
func getEmail() -> String{
return email
}
func getCheckList() -> [Check] {
return checkList
}
func setCheckList(_list : [Check]) {
checkList = _list
}
func getCheckCount() -> Int {
return checkList.count
}
func appendList(check : Check){
checkList.append(check)
}
private var userId = -1
private var comId = -1
func getUserId() -> Int {
return userId
}
func setUserId(_id : Int) {
userId = _id
}
func getComId() -> Int {
return comId
}
func setComId(_id : Int) {
comId = _id
}
func setVisit(_count : Int) {
visit = _count
}
func getVisit() -> Int {
return visit
}
} |
//
// CountryList.swift
// TsumTestApp
//
// Created by Semen Matsepura on 14.04.2018.
// Copyright © 2018 Semen Matsepura. All rights reserved.
//
import Foundation
struct CountryList: Decodable, JSONCodable {
let name: String
let population: Int
}
struct CountryListData: Decodable, JSONCodable {
let countries: [CountryList]
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
var array: [CountryList] = []
while !container.isAtEnd {
array.append(try container.decode(CountryList.self))
}
countries = array
}
}
|
//
// HospitalViewCell.swift
// DemoCleanSwift
//
// Created by passakorn.siangsanan on 1/4/2564 BE.
//
import UIKit
class HospitalViewCell: UITableViewCell {
@IBOutlet weak var lblHospitalID: UILabel!
@IBOutlet weak var lblHospitalName: UILabel!
@IBOutlet weak var lblHospitalLocation: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func prepareCell(_ viewModel: DemoListModel.HospitalList.ViewModel.Hospital) {
selectionStyle = UITableViewCell.SelectionStyle.none
lblHospitalID.text = viewModel.id
lblHospitalName.text = viewModel.hospitalName
lblHospitalLocation.text = viewModel.HospitalLocation
}
}
|
//
// SetCell.swift
// Skrot
//
// Created by Jonni on 2014-12-07.
// Copyright (c) 2014 Jonni. All rights reserved.
//
import UIKit
protocol SetCellProtocol : class {
func weightPressedDelegate(cell:SetCell)
func repsBtnPressedDelegate(cell:SetCell)
func failBtnPressedDelegate(cell:SetCell)
func logBtnPressedDelegate(cell:SetCell)
func rowIsInEditMode(state:Bool)
}
class SetCell: UITableViewCell {
weak var delegate:SetCellProtocol? = nil
@IBOutlet var repsLabel: UILabel!
@IBOutlet var weightLabel: UILabel!
@IBOutlet var weightBtn: UIButton!
@IBOutlet var repsBtn: UIButton!
@IBOutlet var failBtn: UIButton!
var logBtn = UIButton()
let color:CheckColor = CheckColor()
var currentScreenSize:CGFloat = CGFloat()
var sWidth:CGFloat = CGFloat()
var sHeight:CGFloat = 70.0
var rowState = false
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let checkScreen:CheckScreen = CheckScreen()
currentScreenSize = checkScreen.checkScreenSizeWidthFloat()
sWidth = currentScreenSize
createRow()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func layoutSubviews() {
super.layoutSubviews()
}
func createRow(){
switch currentScreenSize {
case 320.0:
logBtn.frame = CGRectMake(sWidth - 86.0, (66.0/2) - (33.0/2), 63.0, 33.0)
case 375.0:
logBtn.frame = CGRectMake(sWidth - 86.0, (66.0/2) - (33.0/2), 63.0, 33.0)
case 414.0:
logBtn.frame = CGRectMake(sWidth - 94.0, (66.0/2) - (33.0/2), 63.0, 33.0)
default:
break
}
logBtn.setTitle(LocalizationStrings.LOG, forState: UIControlState.Normal)
logBtn.titleLabel?.font = UIFont(name: "HelveticaNeue-CondensedBold", size: 16)
let logBtnTapGesture = UITapGestureRecognizer(target: self, action: "logBtnPressed")
logBtn.addGestureRecognizer(logBtnTapGesture)
logBtn.backgroundColor = color.colorTintGreen()
logBtn.layer.cornerRadius = 3
logBtn.layer.borderWidth = 1.0
logBtn.layer.borderColor = color.colorTintGreen().CGColor
logBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
weightLabel.textColor = UIColor.whiteColor()
repsLabel.textColor = UIColor.whiteColor()
weightLabel.alpha = 1.0
repsLabel.alpha = 1.0
logBtn.alpha = 1.0
self.addSubview(logBtn)
}
func logBtnPressed(){
if (delegate != nil){
delegate?.logBtnPressedDelegate(self)
}
}
@IBAction func failBtnPressed(sender: UIButton){
if (delegate != nil){
delegate?.failBtnPressedDelegate(self)
}
}
// MARK: - Actions
@IBAction func weightBtnPressed(sender: UIButton) {
//println("weightBtnPressed")
if (delegate != nil){
delegate?.weightPressedDelegate(self)
}
}
@IBAction func repsBtnPressed(sender: UIButton) {
// println("repsBtnPressed")
if (delegate != nil){
delegate?.repsBtnPressedDelegate(self)
}
}
override func willTransitionToState(state: UITableViewCellStateMask) {
super.willTransitionToState(state)
if (state == UITableViewCellStateMask.DefaultMask) {
print("default1")
rowState = false
editMode()
} else if (state.intersect(UITableViewCellStateMask.ShowingEditControlMask) != [])
&& (state.intersect(UITableViewCellStateMask.ShowingDeleteConfirmationMask) != []) {
print("Edit Control + Delete Button")
} else if state.intersect(UITableViewCellStateMask.ShowingEditControlMask) != [] {
print("Edit Control Only")
rowState = true
editMode()
} else if state.intersect(UITableViewCellStateMask.ShowingDeleteConfirmationMask) != [] {
print("Swipe to Delete [Delete] button only")
rowState = true
editMode()
}
}
func editMode(){
if (delegate != nil){
delegate?.rowIsInEditMode(rowState)
}
}
}
|
import Foundation
extension String: Error { }
struct HttpResponse {
let data: Data
let statusCode: Int
}
struct HttpClient {
static func request(_ target: Arweave.Request) async throws -> HttpResponse {
var request = URLRequest(url: target.url)
request.httpMethod = target.method
request.httpBody = target.body
request.allHTTPHeaderFields = target.headers
let (data, response) = try await URLSession.shared.data(for: request)
let httpResponse = response as? HTTPURLResponse
let statusCode = httpResponse?.statusCode ?? 0
if case .transactionStatus = target.route {}
else if statusCode != 200 {
throw "Bad response code \(statusCode)"
}
return HttpResponse(data: data, statusCode: statusCode)
}
}
|
//
// SearchIntegrationTests.swift
//
//
// Created by Vladislav Fitc on 10.03.2020.
//
import Foundation
import XCTest
@testable import AlgoliaSearchClient
class SearchIntegrationTests: IntegrationTestCase {
override var retryableTests: [() throws -> Void] {
[search]
}
func search() throws {
let employeesData = try Data(filename: "Employees.json")
let employees = try JSONDecoder().decode([JSON].self, from: employeesData)
let settings = Settings().set(\.attributesForFaceting, to: [.searchable("company")])
try index.setSettings(settings).wait()
try index.saveObjects(employees, autoGeneratingObjectID: true).wait()
var results = try index.search(query: "algolia")
XCTAssertEqual(results.nbHits, 2)
XCTAssertEqual(results.hits.firstIndex { $0.objectID == "nicolas-dessaigne"}, 0)
XCTAssertEqual(results.hits.firstIndex { $0.objectID == "julien-lemoine"}, 1)
XCTAssertNil(results.hits.firstIndex { $0.objectID == ""})
var foundObject = try index.findObject(matching: { (_: JSON) in return false }, for: "", paginate: true, requestOptions: .none)
XCTAssertNil(foundObject)
foundObject = try index.findObject(matching: { (_: JSON) in return true }, for: "", paginate: true, requestOptions: .none)
XCTAssertEqual(foundObject?.page, 0)
XCTAssertEqual(foundObject?.position, 0)
foundObject = try index.findObject(matching: { (value: JSON) in value["company"] == "Apple" }, for: "algolia", paginate: true, requestOptions: .none)
XCTAssertNil(foundObject)
foundObject = try index.findObject(matching: { (value: JSON) in value["company"] == "Apple" }, for: Query.empty.set(\.hitsPerPage, to: 5), paginate: false, requestOptions: .none)
XCTAssertNil(foundObject)
foundObject = try index.findObject(matching: { (value: JSON) in value["company"] == "Apple" }, for: Query.empty.set(\.hitsPerPage, to: 5), paginate: true, requestOptions: .none)
XCTAssertEqual(foundObject?.page, 2)
XCTAssertEqual(foundObject?.position, 0)
results = try index.search(query: ("elon" as Query).set(\.clickAnalytics, to: true))
XCTAssertNotNil(results.queryID)
results = try index.search(query: ("elon" as Query).set(\.facets, to: ["*"]).set(\.filters, to: "company:tesla"))
XCTAssertEqual(results.nbHits, 1)
results = try index.search(query: ("elon" as Query).set(\.facets, to: ["*"]).set(\.filters, to: "(company:tesla OR company:spacex)"))
XCTAssertEqual(results.nbHits, 2)
let facetResults = try index.searchForFacetValues(of: "company", matching: "a")
XCTAssertEqual(Set(facetResults.facetHits.map(\.value)), ["Algolia", "Amazon", "Apple", "Arista Networks"])
}
}
|
//
// SampleTableViewController.swift
// TableViewControllerExample
//
// Created by Kristopher Kane on 6/29/15.
// Copyright (c) 2015 Kris Kane. All rights reserved.
//
import UIKit
class SampleTableViewController: UITableViewController {
let identifier = "Cell"
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: identifier)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// let rows: Int
//
// switch section {
// case 0:
// rows = 1
// case 1:
// rows = 2
// default:
// rows = 10
// }
return 2
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! UITableViewCell
if indexPath.row == 0 {
cell.textLabel?.text = "Arthur"
} else {
cell.textLabel?.text = "Thomas"
}
return cell
}
}
|
//
// AccountViewModel.swift
// Appetizer
//
// Created by Paco Cardenal on 17/04/2021.
//
import SwiftUI
final class AccountViewModel: ObservableObject {
@AppStorage("user") private var userData: Data?
@Published var user = User()
@Published var alertItem: AlertItem?
var isValidForm: Bool {
guard !user.firstName.isEmpty && !user.lastName.isEmpty && !user.email.isEmpty else {
alertItem = AlertContext.invalidForm
return false
}
guard user.email.isValidEmail else {
alertItem = AlertContext.invalidEmail
return false
}
return true
}
func saveChanges() {
guard isValidForm else { return }
do {
let data = try JSONEncoder().encode(user)
userData = data
alertItem = AlertContext.userSaveSuccess
} catch {
alertItem = AlertContext.invalidUserData
}
}
func retrieveUser() {
guard let userData = userData else { return }
do {
user = try JSONDecoder().decode(User.self, from: userData)
} catch {
alertItem = AlertContext.invalidUserData
}
}
}
|
// Code thanks to @nitesuit from https://github.com/nitesuit/Blog
import Plot
import Publish
extension Node where Context == HTML.BodyContext {
static func posts(for items: [Item<LascorbeCom>], on site: LascorbeCom, title: String) -> Node {
return .pageContent(
.div(
.class("posts"),
.h1(.class("content-subhead"), .text(title)),
.forEach(items) { item in
.postExcerpt(for: item, on: site)
}
)
)
}
}
|
//
// HttpMgr.swift
// MovieTest
//
// Created by Rydus on 18/04/2019.
// Copyright © 2019 Rydus. All rights reserved.
//
import UIKit
import Alamofire
import APESuperHUD
import SwiftyJSON
// MARK: Http Manager
// SingleTon Design Pattern to access globally from anywhere via shared instance without to create class instance.
final class HttpMgr {
static var shared = HttpMgr()
// MARK: Upload Data To The Web Server
func get(uri:String, completion: @escaping (_ result: JSON)->()) {
let serialQueue = DispatchQueue(label: "com.test.mySerialQueue")
serialQueue.sync {
DispatchQueue.main.async() {
// Add Hud
APESuperHUD.show(style: .loadingIndicator(type: .standard), title: nil, message: "Please wait...")
}
// Requesting to server...
Common.Log(str: uri)
Alamofire.request(uri, method: .get, parameters: nil, encoding: JSONEncoding.default)
.responseData { res in
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
APESuperHUD.dismissAll(animated: true)
})
do {
// Checking server response...
let json = try JSON(data: (res.data!))
Common.Log(str:json.description)
// call back response
completion(json as JSON);
}
catch {
DispatchQueue.main.async() {
let alertController = UIAlertController(title: "Alert", message: error.localizedDescription, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(OKAction)
}
}
}
}
}
// MARK: Exclude function from test. sample for uploading multipart data to the server
func postMultipart(uri:String, params: Dictionary<String, Any>,completion: @escaping (_ result: NSDictionary)->()) {
APESuperHUD.show(style: .loadingIndicator(type: .standard), title: nil, message: "Loading...")
Alamofire.upload(
multipartFormData: { multipartFormData in
// Static data for WS
multipartFormData.append( (UIDevice.current.identifierForVendor?.uuidString.data(using: .utf8)!)!, withName:"udid")
multipartFormData.append("test.munir".data(using: String.Encoding.utf8)!, withName:"device_token")
//multipartFormData.append(WS_KEY.data(using: String.Encoding.utf8)!, withName:"ws_key")
// Dynamic data for WS
for (key, value) in params {
if key.hasPrefix("image") {
if let imageData = (value as! UIImage).pngData() {
multipartFormData.append(imageData, withName: "file", fileName: "image.png", mimeType: "image/png")
}
else if let imageData = (value as! UIImage).jpegData(compressionQuality: 0.5) {
multipartFormData.append(imageData, withName: "file", fileName: "image.jpg", mimeType: "image/jpeg")
}
}
else {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}
},
to: uri,
encodingCompletion: { encodingResult in
debugPrint(uri)
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
APESuperHUD.dismissAll(animated: true)
})
if let jsonDict = response.result.value as? NSDictionary {
let error_type = jsonDict.value(forKey: "ERROR_CODE") as? Int
if(error_type==1) {
completion(jsonDict)
}
else {
let alertController = UIAlertController(title: "Alert", message: jsonDict.object(forKey: "REASON") as? String, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(OKAction)
}
}
else {
let alertController = UIAlertController(title: "Alert", message: "Internet Issue", preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(OKAction)
}
}
.uploadProgress { progress in // main queue by default
//self.img1Progress.alpha = 1.0
//self.img1Progress.progress = Float(progress.fractionCompleted)
print("Upload Progress: \(progress.fractionCompleted)")
}
return
case .failure(let encodingError):
debugPrint(encodingError)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
APESuperHUD.dismissAll(animated: true)
})
let alertController = UIAlertController(title: "Alert", message: "Internet Issue", preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(OKAction)
//progressBar.stopAnimating()
//progressBar.removeFromSuperview()
break;
}
})
}
// MARK: Download Image/Binary From Web Server
func getImage(uri: String, completion: @escaping (Data) -> ()) {
let serialQueue = DispatchQueue(label: "com.test.mySerialQueue")
serialQueue.sync {
/*Alamofire.request(uri).responseData { (response) in
if response.error != nil {
print(response.result)
// Show the downloaded image:
if let data = response.data {
completion(data)
}
}
}*/
let picUrl = URL(string: uri)!
// Creating a session object with the default configuration.
// You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
let session = URLSession(configuration: .default)
// Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.
let downloadPicTask = session.dataTask(with: picUrl) { (data, response, error) in
// The download has finished.
if let e = error {
Common.Log(str: "Error downloading picUrl: \(e)")
} else {
// No errors found.
// It would be weird if we didn't have a response, so check for that too.
if let res = response as? HTTPURLResponse {
Common.Log(str: "Downloaded picUrl with response code \(res.statusCode)")
if let imageData = data {
// Finally convert that Data into an image and do what you wish with it.
//let image = UIImage(data: imageData)
// Do something with your image.
completion(imageData)
} else {
Common.Log(str: "Couldn't get image: Image is nil")
}
} else {
Common.Log(str: "Couldn't get response code for some reason")
}
}
}
downloadPicTask.resume()
}
}
}
|
//
// Ext+UIView.swift
// Instagrid
//
// Created by Gilles David on 16/07/2021.
//
import UIKit
extension UIView {
var asImg: UIImage? {
let renderer = UIGraphicsImageRenderer(bounds: bounds)
return renderer.image { rendererContext in
layer.render(in: rendererContext.cgContext)
}
}
}
|
//
// ConfigureRSM.swift
//
//
// Created by Vũ Quý Đạt on 28/04/2021.
//
import Fluent
import FluentPostgresDriver
import Leaf
import Vapor
import MongoKitten
// configures your application
public func configureRSM(_ app: Application) throws {
// uncomment to serve files from /Public folder
app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
app.middleware.use(app.sessions.middleware)
// Serves files from `Public/` directory
// let fileMiddleware = FileMiddleware(
// publicDirectory: app.directory.publicDirectory
// )
// app.middleware.use(fileMiddleware)
// MARK: - Config http server."
app.http.server.configuration.hostname = "192.168.1.65"
app.http.server.configuration.port = 8080
app.routes.defaultMaxBodySize = "50mb"
// MARK: - Config DB.
let databaseName: String
let databasePort: Int
if (app.environment == .testing) {
databaseName = "vapor-test"
if let testPort = Environment.get("DATABASE_PORT") {
databasePort = Int(testPort) ?? 5433
} else {
databasePort = 5433
}
} else {
databaseName = "vapor_database"
databasePort = 5432
}
// default port for psql
// port: Environment.get("DATABASE_PORT").flatMap(Int.init(_:)) ?? PostgresConfiguration.ianaPortNumber,
app.databases.use(.postgres(
hostname: Environment.get("DATABASE_HOST") ?? "localhost",
port: databasePort,
username: Environment.get("DATABASE_USERNAME") ?? "vapor_username",
password: Environment.get("DATABASE_PASSWORD") ?? "vapor_password",
database: Environment.get("DATABASE_NAME") ?? databaseName
), as: .psql)
// MARK: - Connect MongoDB.
guard let connectionString = Environment.get("MONGODB") else {
fatalError("No MongoDB connection string is available in .env")
}
// connectionString should be MONGODB=mongodb://localhost:27017,localhost:27018,localhost:27019/social-messaging-server
try app.initializeMongoDB(connectionString: connectionString)
// MARK: - Table of DB.
app.migrations.add(CreateUserRSM())
app.migrations.add(CreateTokenRSM())
app.logger.logLevel = .debug
try app.autoMigrate().wait()
app.views.use(.leaf)
// app.leaf.tags["markdown"] = Markdown() //
// MARK: - Change the encoders and decoders.
// Global
// create a new JSON encoder that uses unix-timestamp dates
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .secondsSince1970
// override the global encoder used for the `.json` media type
ContentConfiguration.global.use(encoder: encoder, for: .json)
// register routes
try routesRSM(app)
// try createTestingUserRSMNoSQL(inDatabase: app.mongoDB)
}
/*
func createTestingUserRSMNoSQL(inDatabase database: MongoDatabase) throws {
let userCount = try database[UserRSMNoSQL.collection].count().wait()
if userCount > 0 {
// The testing users have already been created
return
}
let ray = UserRSMNoSQL(
_id: ObjectId(),
idOnRDBMS: UUID(uuidString: "kljshval2h34klj2h")!,
name: "vudat81299",
username: "vudat81299",
lastName: "vudat81299",
bio: "vudat81299",
privacy: .publicState,
profilePicture: "vudat81299",
personalData: PersonalData(
phoneNumber: "vudat81299",
email: "vudat81299",
dob: "vudat81299",
idDevice: "vudat81299",
block: []),
following: [],
box: []
)
let mainUser = UserRSMNoSQL(
_id: ObjectId(),
idOnRDBMS: UUID(uuidString: "trangsdfaksdflas")!,
name: "trang",
username: "trang",
lastName: "trang",
bio: "trang",
privacy: .publicState,
profilePicture: "trang",
personalData: PersonalData(
phoneNumber: "trang",
email: "trang",
dob: "trang",
idDevice: "trang",
block: []),
following: [],
box: []
)
let createdAdmin = database[UserRSMNoSQL.collection].insertEncoded(mainUser)
let createdUsers = database[UserRSMNoSQL.collection].insertManyEncoded([
ray
])
_ = try createdAdmin.and(createdUsers).wait()
}
*/
|
//
// GameState.swift
// ROCK_PAPER_SCISSOR
//
// Created by Macbook on 11/20/17.
// Copyright © 2017 Eric Witowski. All rights reserved.
//
import Foundation
import GameplayKit
enum GameState {
case start, win, lose, draw
}
|
//
// ViewController.swift
// Flashcards3
//
// Created by Salamata Bah on 2/27/21.
//
import UIKit
struct Flashcard{
var question: String
var answer: String
}
class ViewController: UIViewController {
@IBOutlet weak var answer_back: UILabel!
@IBOutlet weak var question_front: UILabel!
var flashcards = [Flashcard]()
var currentIndex = 0
@IBAction func didTapOnPrev(_ sender: Any) {
}
@IBAction func didTapOnNext(_ sender: Any) {
currentIndex = currentIndex + 1
updateLabels()
updateNextPrevButtons()
}
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var prevButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
updateFlashcard(question: "what month is this?", answer: "March")
}
@IBAction func didTapOnFlashCard(_ sender: Any) {
if(question_front.isHidden == false){
question_front.isHidden = true
}
else {
question_front.isHidden = false
}
}
@IBAction func didTapAnswer(_ sender: Any) {
answer_back.isHidden = true
}
func updateFlashcard(question: String, answer: String) {
let flashcard = Flashcard(question: question, answer: answer)
flashcards.append(flashcard)
print("Added new")
print("we now have \(flashcards.count) flashcards")
currentIndex = flashcards.count - 1
print("our curr index is \(currentIndex)")
updateNextPrevButtons()
updateLabels()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let navigationController = segue.destination as! UINavigationController
let createController = navigationController.topViewController as! CreationViewController
createController.flashcardsController = self
}
func updateNextPrevButtons(){
if currentIndex == 0 {
prevButton.isEnabled = false
}else {
prevButton.isEnabled = true
}
if currentIndex == flashcards.count - 1{
nextButton.isEnabled = false
} else{
nextButton.isEnabled = true
}
}
func updateLabels() {
let currentFlashcard = flashcards[currentIndex]
question_front.text = currentFlashcard.question
answer_back.text = currentFlashcard.answer
}
}
|
//
// AFReachabilityManagerMock.swift
//
//
// Created by Prabin Kumar Datta on 31/08/21.
//
import XCTest
import Alamofire
@testable import SimpleRIBNetworking
class AFReachabilityManagerMock: AFReachabilityManagerProtocol {
var shouldReturnReachable: Bool = false
var isReachable: Bool {
shouldReturnReachable
}
var didCallStartListening: Bool = false
var listener: NetworkReachabilityManager.Listener?
func startListening(onQueue queue: DispatchQueue,
onUpdatePerforming listener: @escaping NetworkReachabilityManager.Listener) -> Bool {
self.didCallStartListening = true
self.listener = listener
return true
}
func sendStatus(_ status: NetworkReachabilityManager.NetworkReachabilityStatus) {
self.listener?(status)
}
}
|
//
// ViewController.swift
// BatLogin
//
// Created by David de Tena on 04/03/2017.
// Copyright © 2017 David de Tena. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imgLogoBatman: UIImageView!
@IBOutlet weak var labelInstructions: UILabel!
var viewAnimator : UIViewPropertyAnimator!
private let unlockGesture = UIPanGestureRecognizer()
override func viewDidLoad() {
super.viewDidLoad()
// Set panGestureRecognizer to view
unlockGesture.addTarget(self, action: #selector(handle(pan:)))
self.view.addGestureRecognizer(unlockGesture)
// Set view animator and add animations manually
viewAnimator = UIViewPropertyAnimator(duration: 1.0, curve: .easeInOut, animations: nil)
viewAnimator.addAnimations {
// Hide label after animation finished, and make logo smaller
self.labelInstructions.layer.opacity = 0
self.imgLogoBatman.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
}
}
override var prefersStatusBarHidden: Bool{
return true
}
// MARK: - Utils
/// Handle our gesture recognizer. What to do while pulling down
///
/// - Parameter pan: the panGestureRecognizer
func handle(pan: UIPanGestureRecognizer){
let speed : CGFloat = 2.0
switch pan.state {
case .began:
// State active, but w/o motion
viewAnimator.pauseAnimation()
case .changed:
// Make the "pan" animation slower so we have time to view it
let translation = pan.translation(in: pan.view).y / speed
viewAnimator.fractionComplete = translation / 100
// Animation completed => trigger next animation
if viewAnimator.fractionComplete >= 0.99 {
buildAnimation()
}
default:
break
}
}
/// Build an animation for the logo to scale, as Twitter animation. When finished, we want the login screen to be displayed
func buildAnimation(){
let logoAnimator = UIViewPropertyAnimator(duration: 0.5, curve: .easeIn) {
self.imgLogoBatman.transform = CGAffineTransform(scaleX: 25.0, y: 25.0)
}
logoAnimator.startAnimation()
logoAnimator.addCompletion { (UIViewAnimatingPosition) in
self.beginApp()
}
}
/// Instanciate the loginVC
func beginApp(){
let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController")
self.present(loginVC!, animated: true, completion: nil)
}
}
|
//
// SortPostButtonStyle.swift
// Birdui
//
// Created by Franklin Byaruhanga on 09/07/2020.
// Copyright © 2020 Razeware. All rights reserved.
//
import SwiftUI
struct SortPostButtonStyle: ButtonStyle {
let diameter: CGFloat = 40
func makeBody(configuration: Self.Configuration) -> some View {
let trimColor: Color = configuration.isPressed ? .yellow : .white
return ZStack {
Circle()
.fill(GradientBack.linear)
VStack(spacing: 12) {
Image(systemName: "arrow.up.arrow.down")
.font(.system(size: 20))
.accessibility(label: Text("Sort Posts By Date"))
}.foregroundColor(trimColor)
}.frame(width: diameter, height: diameter)
.overlay(Circle()
.stroke(trimColor, lineWidth: 2)
.padding(4))
}
}
struct SortPostButtonLabView: View {
var labelContent: some View {
Text("Hello world!")
}
var body: some View {
VStack(spacing: 32) {
Button(action: {}) {
labelContent
}.buttonStyle(SortPostButtonStyle())
}.padding()
}
}
struct SortPostButton_Previews: PreviewProvider {
static var previews: some View {
Group {
SortPostButtonLabView()
.previewLayout(PreviewLayout.sizeThatFits)
.padding()
.background(Color(.systemBackground))
.environment(\.colorScheme, .dark)
.previewDisplayName("Button Dark Mode preview")
}
}
}
|
//
// UIImage+ConditionCode.swift
// HeWeatherIO
//
// Created by iMac on 2018/5/25.
// Copyright © 2018年 iMac. All rights reserved.
//
import Foundation
extension UIImage {
class func conditionImage(icon: ConditionCode, completionHandler: @escaping (UIImage?) -> Void) {
DispatchQueue.global(qos: .default).async {
var image: UIImage?
do {
let data = try Data(contentsOf: UIImage.localImagePath(icon: icon)!)
image = UIImage(data: data)
} catch {
do {
let data = try Data(contentsOf: UIImage.remoteImagePath(icon: icon)!)
image = UIImage(data: data)
let fileManager = FileManager.default
fileManager.createFile(atPath: UIImage.localImagePath(icon: icon),
contents: data,
attributes: nil)
} catch { }
}
image = image?.imageWithColor(color: UIColor.white)
DispatchQueue.main.async {
completionHandler(image)
}
}
}
private class func remoteImagePath(icon: ConditionCode) -> URL? {
return URL(string: "https://cdn.heweather.com/cond_icon/\(icon.rawValue).png")
}
private class func localImagePath(icon: ConditionCode) -> String {
let myPathes = NSSearchPathForDirectoriesInDomains(.documentDirectory,
.userDomainMask,
true)
let docPath = myPathes[0]
return NSString(string: docPath).appendingPathComponent("/conditionImage/\(icon.rawValue).png") as String
}
private class func localImagePath(icon: ConditionCode) -> URL? {
return URL(string: UIImage.localImagePath(icon: icon))
}
private func imageWithColor(color: UIColor) -> UIImage? {
guard let cgImage = self.cgImage else {
return nil
}
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
defer {
UIGraphicsEndImageContext()
}
let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: 0, y: self.size.height)
context?.scaleBy(x: 1.0, y: -1.0)
context?.setBlendMode(.normal)
let rect = CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height)
context?.clip(to: rect, mask: cgImage)
color.setFill()
context?.fill(rect)
return UIGraphicsGetImageFromCurrentImageContext()
}
}
|
//
// Chapter2Intersection.swift
// CtCI
//
// Created by Jordan Doczy on 2/18/21.
//
import Foundation
class Chapter2Intersection {
static func isIntersection(a: LinkedNode<Int>, b: LinkedNode<Int>) -> LinkedNode<Int>? {
var aNode: LinkedNode<Int>? = a
var bNode: LinkedNode<Int>? = b
var aEnd: LinkedNode<Int>?
var bEnd: LinkedNode<Int>?
var aLength = 0
var bLength = 0
while aNode != nil || bNode != nil { // find last nodes and lengths
if aNode != nil {
aEnd = aNode
aLength += 1
}
if bNode != nil {
bEnd = bNode
bLength += 1
}
aNode = aNode?.next
bNode = bNode?.next
}
guard aEnd === bEnd else { // tails must match
return nil
}
// reset to head
aNode = a
bNode = b
if aLength > bLength { // advance the greater of two lists by the difference
aNode = aNode!.getNode(at: aLength-bLength)
} else {
bNode = bNode!.getNode(at: bLength-aLength)
}
while aNode != nil && bNode != nil {
if aNode === bNode {
return aNode
}
aNode = aNode?.next
bNode = bNode?.next
}
return nil
}
// time = O(a*b), space = O(a+b)
static func isIntersectionBruteForce(a: LinkedNode<Int>, b: LinkedNode<Int>) -> LinkedNode<Int>? {
var aItems: [LinkedNode<Int>] = []
var bItems: [LinkedNode<Int>] = []
var aNode: LinkedNode<Int>? = a
while aNode != nil { // O(a)
aItems.append(aNode!)
aNode = aNode?.next
}
var bNode: LinkedNode<Int>? = b
while bNode != nil { // O(b)
bItems.append(bNode!)
bNode = bNode?.next
}
for aNode in aItems { // O(a*b)
for bNode in bItems {
if aNode === bNode {
return aNode
}
}
}
return nil
}
// time = O(a+b), space = O(a)
static func isIntersectionHash(a: LinkedNode<Int>, b: LinkedNode<Int>) -> LinkedNode<Int>? {
var aItems: [LinkedNode<Int>:Int] = [:]
var aNode: LinkedNode<Int>? = a
while aNode != nil {
aItems[aNode!] = 1
aNode = aNode?.next
}
var bNode: LinkedNode<Int>? = b
while bNode != nil {
if aItems[bNode!] != nil {
return bNode
}
bNode = bNode?.next
}
return nil
}
static func test() -> Bool {
let intersect = LinkedNode(data: -99)
intersect.next = LinkedNode(data: -100)
intersect.next!.next = LinkedNode(data: -101)
let a = LinkedNode(data: 0)
a.next = LinkedNode(data: 1)
a.next!.next = LinkedNode(data: 2)
a.next!.next!.next = intersect
print("a= \(a.getStringValue(useTime: false))")
let b = LinkedNode(data: 9)
b.next = LinkedNode(data: 10)
b.next!.next = LinkedNode(data: 11)
b.next!.next!.next = LinkedNode(data: 12)
b.next!.next!.next!.next = LinkedNode(data: 13)
b.next!.next!.next!.next!.next = intersect
print("b= \(b.getStringValue(useTime: false))")
return isIntersection(a: a, b: b) == intersect
}
}
|
/*-
* Copyright (c) 2020 Sygic
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
//
// FaceCaptureCoordinator.swift
// Covid
//
// Created by Boris Bielik on 03/04/2020.
// Copyright © 2020 Sygic. All rights reserved.
//
import Foundation
import UIKit
import DOT
final class FaceCaptureCoordinator {
enum FaceCaptureCoordinatorStep {
case initialised
case onboarding
case faceCapture
case faceVerification
case completion
}
weak var navigationController: UINavigationController?
let faceIdCapture = FaceIDCapture()
let faceIdValidator = FaceIDValidator()
let useCase: FaceIDUseCase
var onCoordinatorResolution: ((Result<Bool, Error>) -> Void)?
var onAlert: ((UIAlertController) -> Void)?
private(set) var step: FaceCaptureCoordinatorStep = .initialised
private var retryVerifyCount = 0
private var numberOfRetries = 5
private var coordinator: LivenessStepCoordinator?
deinit {
debugPrint("deallocated")
}
init(useCase: FaceIDUseCase) {
FaceID.initialize()
self.useCase = useCase
}
}
extension FaceCaptureCoordinator {
// MARK: Onboarding
func showOnboarding(in navigationController: UINavigationController) {
guard let viewController = UIStoryboard.controller(ofType: FaceCaptureOnboardingViewController.self) else { return }
viewController.onStart = { [weak self] in
if let controller = self?.startFaceCapture() {
navigationController.pushViewController(controller, animated: true)
}
}
self.navigationController = navigationController
navigationController.pushViewController(viewController, animated: true)
step = .onboarding
}
// MARK: Face Capture
func startFaceCapture() -> UIViewController {
let controller = faceIdCapture.createController { [weak self] (resolution) in
self?.processFaceCaptureResolution(resolution)
}
controller.title = useCase.title
step = .faceCapture
return controller
}
private func processFaceCaptureResolution(_ resolution: FaceIDCapture.FaceCaptureResolution) {
switch resolution {
case .sucess(let face):
switch useCase {
case .registerFace:
// store reference face
FaceIDStorage().saveReferenceFace(face)
completeFaceCapture(didSuccess: true)
case .verifyFace:
verifyFace(face)
case .borderCrossing:
verifyFace(face)
}
case .failedToCaptureFace:
debugPrint("failed to capture face")
case .failedToGiveCameraPermission:
debugPrint("failed to give camera permission")
}
}
private func verifyFace(_ face: FaceCaptureImage) {
let result = faceIdValidator.validateCapturedFaceToReferenceTemplate(face)
switch result {
case .success where useCase == .verifyFace:
debugPrint("verify: success")
startVerifying()
case .success where useCase == .borderCrossing:
completeFaceCapture(didSuccess: true)
case .failure(let error):
switch error {
case .failedToVerify, .underlyingError:
handleFailedVerification()
case .noCaptureTemplateDataFound,
.noReferenceFaceDataFound:
debugPrint("failed to verify: ", error.localizedDescription)
}
debugPrint("failed to verify")
default:
break
}
}
private func handleFailedVerification() {
if retryVerifyCount < numberOfRetries {
retryVerifyCount += 1
askToVerifyAgain { [weak self] _ in
self?.faceIdCapture.requestFaceCapture()
}
} else {
completeFaceCapture(didSuccess: false)
}
}
private func askToVerifyAgain(_ action: @escaping (UIAlertAction) -> Void) {
let alertController = UIAlertController(title: LocalizedString(forKey: "error.faceid.verification.failed.title"),
message: LocalizedString(forKey: "error.faceid.verification.failed.message"),
preferredStyle: .alert)
let retryAction = UIAlertAction(title: LocalizedString(forKey: "face_capture.confirmation.tryAgain"), style: .default) { uiAction in
action(uiAction)
}
let cancelAction = UIAlertAction(title: LocalizedString(forKey: "face_capture.confirmation.close"), style: .cancel) { [weak self] _ in
self?.completeFaceCapture(didSuccess: false)
}
alertController.addAction(retryAction)
alertController.addAction(cancelAction)
onAlert?(alertController)
}
}
// MARK: Completion
extension FaceCaptureCoordinator {
private func completeFaceCapture(didSuccess: Bool) {
step = .completion
switch useCase {
case .borderCrossing where didSuccess == true:
onCoordinatorResolution?(.success(true))
default:
FaceCaptureCompletedViewController.show(using: { [weak self] (viewController) in
guard let self = self else { return }
viewController.useCase = self.useCase
viewController.didSuccess = didSuccess
viewController.navigationItem.hidesBackButton = true
self.navigationController?.pushViewController(viewController, animated: true)
}, onCompletion: { [weak self] in
self?.onCoordinatorResolution?(.success(didSuccess))
})
}
}
}
// MARK: Verification
extension FaceCaptureCoordinator {
private func startVerifying() {
coordinator = LivenessStepCoordinator()
coordinator?.delegate = self
if let controller = coordinator?.createVerifyController(transitionType: .move) {
controller.title = useCase.verifyTitle
controller.navigationItem.hidesBackButton = true
navigationController?.pushViewController(controller, animated: false)
step = .faceVerification
}
}
}
extension FaceCaptureCoordinator: LivenessStepDelegate {
private func validateSegmentImages(_ segmentImages: [SegmentImage]) {
let result = faceIdValidator.validateSegmentImagesToReferenceTemplate(segmentImages)
switch result {
case .success:
debugPrint("verify: success")
completeFaceCapture(didSuccess: true)
case .failure:
debugPrint("verify: failure")
completeFaceCapture(didSuccess: false)
}
}
func liveness(_ step: LivenessStepCoordinator, didSucceed score: Float, capturedSegmentImages segmentImages: [SegmentImage]) {
debugPrint(#function)
validateSegmentImages(segmentImages)
step.stopVerifying()
}
func liveness(_ step: LivenessStepCoordinator, didFailed score: Float, capturedSegmentImages segmentImages: [SegmentImage]) {
debugPrint(#function)
livenessFailed(step)
step.stopVerifying()
}
func livenessdidFailedWithEyesNotDetected(_ step: LivenessStepCoordinator) {
debugPrint(#function)
livenessFailed(step)
step.stopVerifying()
}
func livenessFailed(_ step: LivenessStepCoordinator) {
switch useCase {
case .registerFace:
askToVerifyAgain { _ in
step.restartVerifying()
}
case .verifyFace:
guard retryVerifyCount < 1 else {
completeFaceCapture(didSuccess: false)
return
}
retryVerifyCount += 1
askToVerifyAgain { _ in
step.restartVerifying()
}
case .borderCrossing:
break
}
}
}
|
//
// LaunchViewController.swift
// Menu Delegation
//
// Created by Dave Scherler on 3/20/15.
// Copyright (c) 2015 DaveScherler. All rights reserved.
//
import UIKit
import pop
class LaunchViewController: UIViewController {
@IBOutlet weak var logoImage: UIImageView!
@IBOutlet weak var logoTopConstraint: NSLayoutConstraint!
var main: MainViewController?
override func viewDidLoad() {
UIView.animateWithDuration(1, animations: { () -> Void in
let scale = CGAffineTransformMakeScale(0.2, 0.25)
self.logoImage.transform = scale
}, completion: { (Bool) -> Void in
let slideUp = POPSpringAnimation(propertyNamed: kPOPLayoutConstraintConstant)
slideUp.toValue = -35
slideUp.springBounciness = 5
slideUp.springSpeed = 10
self.logoTopConstraint.pop_addAnimation(slideUp, forKey: "slideUp.move")
})
present()
}
func present() {
//self.view.backgroundColor = UIColor.clearColor()
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
self.main = self.storyboard?.instantiateViewControllerWithIdentifier("MainVC") as? MainViewController
// self.main?.view.setTranslatesAutoresizingMaskIntoConstraints(false)
// self.view.addSubview(self.main!.view)
self.presentViewController(main!, animated: false, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
import UIKit
class OTMTableViewController: UITableViewController {
@IBOutlet weak var logoutButton: UIBarButtonItem!
@IBOutlet weak var refreshButton: UIBarButtonItem!
@IBOutlet weak var addLocationButton: UIBarButtonItem!
var dataStore: OTMDataStore!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Map view controller calls this first, but just in case call it here if needed.
if dataStore.shouldCallForUdates {
getLocationDataWithUIEffectAndSpinner()
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataStore.studentLocations!.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.Identifier.TableViewCell, for: indexPath) as! OTMTableViewCell
let location = dataStore.studentLocations[indexPath.row]
cell.nameLabel?.text = "\(location.firstName) \(location.lastName)"
cell.mediaURLLabel?.text = location.mediaURL ?? ""
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let studentLocation = dataStore.studentLocations[indexPath.row]
if var urlString = studentLocation.mediaURL, let url = URL(string:urlString) {
if !urlString.starts(with: "http://") {
urlString = "http://" + urlString
}
UIApplication.shared.open(url, options: [:], completionHandler: { [unowned self] (success) in
if success {
self.tableView.deselectRow(at: indexPath, animated: true)
}
else {
// Could not open url
self.presentAlertWith(title: "Invalid link", message: "")
self.tableView.deselectRow(at: indexPath, animated: true)
}
})
}
else {
// No string or failed to create URL
self.presentAlertWith(title: "Invalid link", message: "")
self.tableView.deselectRow(at: indexPath, animated: true)
}
print(studentLocation.firstName)
print(studentLocation.lastName)
}
// MARK: - Bar Button methods
@IBAction func logoutBarButtonTapped(_ sender: UIBarButtonItem) {
print("Logout button tapped")
OTMClient.shared.deleteUdacitySession { [unowned self] (success, errorString) in
DispatchQueue.main.async {
if let errorString = errorString {
self.presentAlertWith(title: errorString, message: "")
}
else if success {
OTMClient.shared.logoutOfFacebook()
OTMClient.shared.removeSessionIDExpirationDateAndAccountKeyFromUserDefaults()
self.navigationController?.tabBarController?.navigationController?.popToRootViewController(animated: true)
}
else {
self.presentAlertWith(title: "Unknown error", message: "")
print("Should never be here. In logoutButton method of table view controller")
}
}
}
}
@IBAction func refreshBarButtonTapped(_ sender: UIBarButtonItem) {
getLocationDataWithUIEffectAndSpinner()
}
// MARK: - Data from network method
func getLocationDataWithUIEffectAndSpinner() {
deactivateUIForRefresh()
dimScreenWithActivitySpinner()
OTMClient.shared.getStudentLocationsInDateOrder { [unowned self] (success, locations, errorString) in
DispatchQueue.main.async {
if !success {
self.undimScreenAndRemoveActivitySpinner()
self.activateUI()
self.presentAlertWith(title: errorString ?? "Error occured", message: "")
}
else {
print("Just called for data. In table view controller with \(locations!.count) locations")
self.undimScreenAndRemoveActivitySpinner()
self.activateUI()
// Handle new data
self.dataStore.shouldCallForUdates = false
self.dataStore.studentLocations = locations
self.tableView.reloadData()
}
}
}
}
// MARK: - UI Methods
func deactivateUIForRefresh() {
logoutButton.isEnabled = false
refreshButton.isEnabled = false
addLocationButton.isEnabled = false
tabBarController?.tabBar.items?.first?.isEnabled = false
tabBarController?.tabBar.items?.last?.isEnabled = false
}
func activateUI() {
logoutButton.isEnabled = true
refreshButton.isEnabled = true
addLocationButton.isEnabled = true
tabBarController?.tabBar.items?.first?.isEnabled = true
tabBarController?.tabBar.items?.last?.isEnabled = true
}
}
|
//
// subbbalancecell.swift
// idashboard
//
// Created by Hasanul Isyraf on 29/04/2018.
// Copyright © 2018 Hasanul Isyraf. All rights reserved.
//
import UIKit
class subbbalancecell: UITableViewCell {
@IBOutlet weak var cabname: UILabel!
@IBOutlet weak var port: UILabel!
@IBOutlet weak var phase: UILabel!
@IBOutlet weak var region: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//
// calculatorController.swift
// PractiseTable
//
// Created by Ishan Mahajan on 02/09/16.
// Copyright © 2016 Ishan Mahajan. All rights reserved.
//
import Foundation
|
//
// ExposureAnalysis.swift
// GAEN_Explorer
//
// Created by Bill on 5/28/20.
// Copyright © 2020 Ninja Monkey Coders. All rights reserved.
//
import ExposureNotification
import Foundation
struct ExposureKey: Hashable, CustomStringConvertible {
var description: String {
day
}
let transmissionRiskLevel: ENRiskLevel
let duration: Int
var date: Date
var day: String {
dayFormatter.string(from: date)
}
init(info: CodableExposureInfo) {
self.date = info.date
self.duration = info.exposureInfoDuration
self.transmissionRiskLevel = info.transmissionRiskLevel
}
}
// 50 55 58 61 64 67 70 73
// 55 67 50 58 61 64 70 73
let multipassThresholds2 = [[58, 66],
[64, 68],
[56, 64],
[60, 68],
[52, 58],
[54, 62],
[50, 62],
[66, 70],
[68, 72]]
let multipassThresholds = [[58, 66, 70],
[64, 68, 72],
[56, 64, 70],
[60, 68, 76],
[52, 58, 72],
[54, 62, 74],
[50, 62],
[66, 70],
[68, 72]]
// 58 66 64 70 56 _64_ 60 68 52 _58_ 54 62
// 58 66 64 68 56 64 60 68 52 58 54 62 48 62
let lowerThresholdMeaningful = 58
let upperThresholdMeaningful = 64
let numberAnalysisPasses = multipassThresholds.count
let phoneAttenuationHandicapValues = [
"iPhone SE": 4,
"iPhone 11 Pro": 0,
"iPhone XS": 0,
"iPhone SE (2nd generation)": 2,
]
var phoneAttenuationHandicap: Int {
if true {
return 0
}
return phoneAttenuationHandicapValues[deviceModelName(), default: 0]
}
func getAttenuationDurationThresholds(pass: Int) -> [Int] {
multipassThresholds[pass - 1]
}
func uniqueSortedThresholds() -> [Int] {
Set(multipassThresholds.joined()).sorted()
}
|
//
// ViewController.swift
// JMODemo
//
// Created by christophe on 21/06/14.
// Copyright (c) 2014 cdebortoli. All rights reserved.
//
import UIKit
import JsonManagedObject
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// ------------------ Configuration ------------------
JMOConfig.jsonWithEnvelope = true
JMOConfig.dateFormat = "yyyy-MM-dd"
JMOConfig.managedObjectContext = databaseManagerSharedInstance.databaseCore.managedObjectContext
JMOConfig.temporaryNSManagedObjectInstance = true
// ------------------ Get Aircraft from JSON ------------------
let dict = dictionaryFromService("aircraftJsonWithEnvelope")
var aircraft:Aircraft? = jsonManagedObjectSharedInstance.analyzeJsonDictionary(dict, forClass:Aircraft.classForCoder()) as? Aircraft
println(aircraft)
// ------------------ Get multiple Aircrafts from JSON ------------------
let aircraftArray = arrayFromJson("aircraftsJsonWithEnvelope")
var aircrafts = jsonManagedObjectSharedInstance.analyzeJsonArray(aircraftArray, forClass: Aircraft.classForCoder()) as Aircraft[]
println(aircrafts)
// ------------------ Get JSON from Aircraft ------------------
let aircraftJsonRepresentation = aircraft?.getJmoJson()
println(aircraftJsonRepresentation)
// ------------------ Get Custom object from JSON ------------------
// let customObjectDict = dictionaryFromService("customObjectJson")
// var customObject:CustomObject? = jsonManagedObjectSharedInstance.analyzeJsonDictionary(customObjectDict, forClass: CustomObject.self) as? CustomObject
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func dictionaryFromService(service:String) -> Dictionary<String,AnyObject> {
let filepath = NSBundle.mainBundle().pathForResource(service, ofType: "json")
let filecontent = NSData.dataWithContentsOfFile(filepath, options: nil, error: nil)
let json = NSJSONSerialization.JSONObjectWithData(filecontent, options: NSJSONReadingOptions.MutableContainers, error: nil) as Dictionary<String, AnyObject>
return json
}
func arrayFromJson(service:String) -> AnyObject[] {
let filepath = NSBundle.mainBundle().pathForResource(service, ofType: "json")
let filecontent = NSData.dataWithContentsOfFile(filepath, options: nil, error: nil)
let json = NSJSONSerialization.JSONObjectWithData(filecontent, options: NSJSONReadingOptions.MutableContainers, error: nil) as AnyObject[]
return json
}
}
|
//
// ViewController.swift
// AppleMusicRPC
//
// Created by 정구현 on 2021/10/01.
//
import UIKit
class ViewController: UIViewController {
private let imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
return imageView
}()
private let button: UIButton = {
let button = UIButton()
button.backgroundColor = .white
button.setTitle("Connect To Server", for : .normal)
button.setTitleColor(.black, for : .normal)
return button
}()
private let ipinput: UITextField = {
let label = UITextField()
label.text = nil
label.attributedPlaceholder = NSAttributedString(string: " Input Server IP", attributes: [.foregroundColor: UIColor.systemGray])
label.backgroundColor = .white
label.textColor = .black
return label
}()
private let passphraseinput: UITextField = {
let label = UITextField()
label.text = nil
label.attributedPlaceholder = NSAttributedString(string: " Server Secret Passphrase", attributes: [.foregroundColor: UIColor.systemGray])
label.backgroundColor = .white
label.textColor = .black
return label
}()
private let labelofgithub: UILabel = {
let label = UILabel()
label.text = "https://github.com/justiceserv/AppleMusicDiscordRPC"
label.textColor = .white
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
view.backgroundColor = .black
view.addSubview(imageView)
imageView.frame = CGRect(x: view.center.x - 75, y:view.center.y - 250, width: 150, height: 150)
view.addSubview(button)
button.frame = CGRect(x: view.center.x - 100, y: view.center.y + 400, width: 200, height: 60)
getAppleMusicPhoto()
view.addSubview(ipinput)
view.addSubview(passphraseinput)
button.addTarget(self, action: #selector(TurnedOn), for: .touchUpInside)
view.addSubview(labelofgithub)
view.addGestureRecognizer(tap)
}
@objc func TurnedOn(){
button.setTitle("Connected To Server", for : .normal)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
button.frame = CGRect(
x: 30,
y: view.frame.size.height-250-view.safeAreaInsets.bottom,
width: view.frame.size.width-60,
height: 55
)
ipinput.frame = CGRect(
x:30,
y: view.frame.size.height-420-view.safeAreaInsets.bottom,
width: view.frame.size.width-60,
height: 50
)
passphraseinput.frame = CGRect(
x:30,
y: view.frame.size.height-350-view.safeAreaInsets.bottom,
width: view.frame.size.width-60,
height: 50
)
labelofgithub.frame = CGRect(
x: 5,
y: view.frame.size.height-30-view.safeAreaInsets.bottom,
width: view.frame.size.width-10,
height: 12
)
ipinput.borderStyle = .roundedRect
passphraseinput.borderStyle = .roundedRect
}
func getAppleMusicPhoto() {
let urlString = "https://i.ibb.co/bg3LvBP/2-2.png"
let url = URL(string: urlString)!
guard let data = try? Data(contentsOf: url) else { return }
imageView.image = UIImage(data: data)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
}
|
//
// AlertLoadingView.swift
// KidsChannel
//
// Created by sungju on 2017. 4. 11..
// Copyright © 2017년 sungju. All rights reserved.
//
import UIKit
class AlertLoadingView: UIView {
@IBOutlet weak var loadingView: UIView!
@IBOutlet weak var title: UILabel!
@IBOutlet weak var indicator: UIActivityIndicatorView!
override func awakeFromNib() {
self.loadingView.layoutIfNeeded()
self.loadingView.layer.cornerRadius = 10.0
self.loadingView.layer.borderWidth = 0.5
self.loadingView.layer.borderColor = UIColor.gray.cgColor
self.loadingView.clipsToBounds = true
}
}
|
//
// UIBarButtomItem+Extension.swift
// QiangShengPSI
//
// Created by 王孝飞 on 2017/8/10.
// Copyright © 2017年 孝飞. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
/// 创建 UIBarButtonItem
///
/// - parameter title: title
/// - parameter fontSize: fontSize,默认 16 号
/// - parameter target: target
/// - parameter action: action
/// - parameter isBack: 是否是返回按钮,如果是加上箭头
///
/// - returns: UIBarButtonItem
convenience init(imageString: String, fontSize: CGFloat = 16, target: AnyObject?, action: Selector, isBack: Bool = false ,fixSpace : CGFloat = 0,rightSpace : CGFloat = 0) {
let btn = UIButton.xf_imageBtn(imageString)
if isBack {
let imageName = "nav_icon_back"
btn.setImage(UIImage(named: imageName ), for: UIControlState(rawValue: 0))
btn.setImage(UIImage(named: imageName ), for: .highlighted)
btn.sizeToFit()
btn.frame = CGRect(x: 0, y: 0, width: 50, height: 44)
}
btn.frame = CGRect(x: 0, y: 0, width: 50, height: 44)
btn.imageEdgeInsets = UIEdgeInsetsMake(0, fixSpace, 0, rightSpace)
btn.addTarget(target, action: action, for: .touchUpInside)
// self.init 实例化 UIBarButtonItem
self.init(customView: btn)
}
}
|
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
import Metal
import Foundation
public class PaddleMobileUnitTest {
let device: MTLDevice
let queue: MTLCommandQueue
public init(inDevice: MTLDevice, inQueue: MTLCommandQueue) {
device = inDevice
queue = inQueue
}
private func indentPrintTensor(tensor: [Float32], dim: [Int], ix: [Int], indentLevel: Int) {
let indent = Array.init(repeating: " ", count: indentLevel).joined(separator: "")
var tx = ix
if dim.count == indentLevel + 1 {
var log: String = indent + "["
for i in 0..<dim[indentLevel] {
tx = ix
tx[indentLevel] = i
for x in 1..<dim.count {
for y in 0..<x {
tx[y] *= dim[x]
}
}
let c = tx.reduce(0) { $0 + $1 }
if i > 0 {
log += ", "
}
log += tensor[c].description
}
log += "]"
if (indentLevel > 0) && (ix[indentLevel - 1] < dim[indentLevel - 1] - 1) {
log += ","
}
print(log)
} else {
print(indent + "[")
for i in 0..<dim[indentLevel] {
tx[indentLevel] = i
indentPrintTensor(tensor: tensor, dim: dim, ix: tx, indentLevel: indentLevel + 1)
}
if (indentLevel > 0) && (ix[indentLevel - 1] < dim[indentLevel - 1] - 1) {
print(indent + "],")
} else {
print(indent + "]")
}
}
}
private func tensorPrint(tensor: [Float32], dim: [Int]) {
var detectPos = -1
var odim = 1
var ndim = dim
for i in 0..<dim.count {
if dim[i] == -1 {
if detectPos == -1 {
detectPos = i
} else {
detectPos = -2
}
} else if dim[i] <= 0 {
detectPos = -3
} else {
odim *= dim[i]
}
}
assert(detectPos >= -1)
if (detectPos == -1) {
assert(tensor.count == odim)
} else {
assert(tensor.count % odim == 0)
ndim[detectPos] = tensor.count / odim
}
indentPrintTensor(tensor: tensor, dim: ndim, ix: dim.map { $0 * 0 }, indentLevel: 0)
}
public func testConcat() {
// let buffer = queue.makeCommandBuffer() ?! "buffer is nil"
// var it: [[Float32]] = []
// for _ in 0..<7 {
// it.append((0..<12).map { Float32($0) })
// }
// let input = it.map { device.tensor2texture(value: $0, dim: [3, 4]) }
// let output = device.tensor2texture(value: [Float32](), dim: [3, 28])
//
// let param = ConcatTestParam.init(
// input: input,
// output: output,
// dims: [[3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4], [3, 4]],
// axis: 1,
// odim: [3, 28]
// )
// let concatKernel = ConcatKernel<Float32>.init(device: device, testParam: param)
// concatKernel.test(cmdBuffer: buffer, param: param)
// buffer.addCompletedHandler { (buffer) in
// for i in 0..<it.count {
// let _: Float32? = input[i].logDesc()
// self.tensorPrint(tensor: it[i], dim: [3, 4])
// }
// let _: Float32? = output.logDesc()
// let tx: [Float32] = self.device.texture2tensor(texture: output, dim: [3, 28])
// self.tensorPrint(tensor: tx, dim: [3, 28])
// }
//
// buffer.commit()
}
public func testReshape() {
// let buffer = queue.makeCommandBuffer() ?! "buffer is nil"
// let input: [Float32] = (0..<24).map { Float32($0) }
// let inTexture = device.tensor2texture(value: input, dim: [2, 3, 4])
// let outTexture = device.tensor2texture(value: [Float32](), dim: [4, 6])
// let mp = ReshapeMetalParam.init(
// idim: (1, 2, 3, 4),
// itrans: (0, 1, 2, 3),
// odim: (1, 1, 4, 6),
// otrans: (0, 1, 2, 3)
// )
// let param = ReshapeTestParam.init(
// inputTexture: inTexture,
// outputTexture: outTexture,
// param: mp
// )
// let reshapeKernel = ReshapeKernel<Float32>.init(device: device, testParam: param)
// reshapeKernel.test(commandBuffer: buffer, testParam: param)
// buffer.addCompletedHandler { (buffer) in
// let _: Float32? = inTexture.logDesc()
// let _: Float32? = outTexture.logDesc()
// self.tensorPrint(tensor: input, dim: [2, 3, 4])
// let tx: [Float32] = self.device.texture2tensor(texture: outTexture, dim: [4, 6])
// self.tensorPrint(tensor: tx, dim: [4, 6])
// }
// let input: [Float32] = (0..<24).map { Float32($0) }
// let inTexture = device.tensor2texture(value: input, dim: [2, 3, 4])
// let outTexture = device.tensor2texture(value: [Float32](), dim: [24])
// let mp = ReshapeMetalParam.init(
// idim: (1, 2, 3, 4),
// itrans: (0, 1, 2, 3),
// odim: (1, 1, 1, 24),
// otrans: (0, 1, 2, 3)
// )
// let param = ReshapeTestParam.init(
// inputTexture: inTexture,
// outputTexture: outTexture,
// param: mp
// )
// let reshapeKernel = ReshapeKernel<Float32>.init(device: device, testParam: param)
// reshapeKernel.test(commandBuffer: buffer, testParam: param)
// buffer.addCompletedHandler { (buffer) in
// let _: Float32? = inTexture.logDesc()
// let _: Float32? = outTexture.logDesc()
// self.tensorPrint(tensor: input, dim: [2, 3, 4])
// let tx: [Float32] = self.device.texture2tensor(texture: outTexture, dim: [24])
// self.tensorPrint(tensor: tx, dim: [24])
// }
//
//
// buffer.commit()
}
public func testTranspose() {
let buffer = queue.makeCommandBuffer() ?! "buffer is nil"
// var input: [Float32] = []
// for i in 0..<72 {
// input.append(Float32(i))
// }
//// let inputTexture = device.makeFloatTexture(value: input, textureWidth: 3, textureHeight: 2, arrayLength: 3)
// let inputTexture = device.tensor2texture(value: input, dim: [4, 3, 2, 3]);
// // group 1
// let outputTexture = device.tensor2texture(value: [Float32](), dim: [3, 3, 2, 4])
// let param = TransposeTestParam.init(inputTexture: inputTexture, outputTexture: outputTexture, iC: 3, oC: 4, axis: [3, 1, 2, 0])
//// let param = TransposeTestParam.init(inputTexture: inputTexture, outputTexture: outputTexture, iC: 4, oC: 2, axis: [3, 0, 2, 1])
//// // group 2
//// let outputTexture = device.makeFloatTexture(value: [Float32](), textureWidth: 3, textureHeight: 3, arrayLength: 6)
//// let param = TransposeTestParam.init(inputTexture: inputTexture, outputTexture: outputTexture, iC: 4, oC: 4, axis: [3, 0, 2, 1])
////
// let transposeKernel = TransposeKernel<Float32>.init(device: device, testParam: param)
//
// transposeKernel.test(commandBuffer: buffer, param: param)
//
// buffer.addCompletedHandler { (buffer) in
// let _: Float32? = inputTexture.logDesc(header: "input texture", stridable: false)
// let _: Float32? = outputTexture.logDesc(header: "output texture", stridable: false)
// self.tensorPrint(tensor: input, dim: [4, 3, 2, 3])
// let tx: [Float32] = self.device.texture2tensor(texture: outputTexture, dim: [3, 3, 2, 4])
// self.tensorPrint(tensor: tx, dim: [3, 3, 2, 4])
// }
//
// let input: [Float32] = (0..<24).map { Float32($0) }
// let inputTexture = device.tensor2texture(value: input, dim: [2, 3, 4])
// let outputTexture = device.tensor2texture(value: [Float](), dim: [3, 4, 2])
// let param = TransposeTestParam.init(inputTexture: inputTexture, outputTexture: outputTexture, iC: 4, oC: 2, axis: [0, 2, 3, 1])
// let transposeKernel = TransposeKernel<Float32>.init(device: device, testParam: param)
//
// transposeKernel.test(commandBuffer: buffer, param: param)
//
// buffer.addCompletedHandler { (buffer) in
// let _: Float32? = inputTexture.logDesc(header: "input texture", stridable: false)
// let _: Float32? = outputTexture.logDesc(header: "output texture", stridable: false)
// self.tensorPrint(tensor: input, dim: [2, 3, 4])
// let tx: [Float32] = self.device.texture2tensor(texture: outputTexture, dim: [3, 4, 2])
// self.tensorPrint(tensor: tx, dim: [3, 4, 2])
// }
//
buffer.commit()
}
public func testConvAddBnRelu() {
let buffer = queue.makeCommandBuffer() ?! " buffer is nil "
let input: [Float32] = [
1.0, 2.0, 3.0, 4.0,
1.0, 2.0, 3.0, 4.0,
1.0, 2.0, 3.0, 4.0,
1.0, 2.0, 3.0, 4.0,
1.0, 2.0, 3.0, 4.0,
1.0, 2.0, 3.0, 4.0,
1.0, 2.0, 3.0, 4.0,
1.0, 2.0, 3.0, 4.0,
1.0, 2.0, 3.0, 4.0,
]
let filter: [Float32] = [
//1.0
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
//2.0
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
//3.0
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
//4.0
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0,
]
let biase: [Float32] = [1.0, 1.0, 1.0, 100.0]
let newScalue: [Float32] = [1.0, 1.0, 1.0, 1.0]
let newBiase: [Float32] = [1.0, 1.0, 1.0, 1.0]
let inputeTexture = device.makeFloatTexture(value: input, textureWidth: 3, textureHeight: 3, arrayLength: 1)
//filter
let filterBuffer = device.makeBuffer(value: filter)
// biase
let biaseBuffer = device.makeBuffer(value: biase)
// new scale
let newScalueBuffer = device.makeBuffer(value: newScalue)
// new biase
let newBiaseBuffer = device.makeBuffer(value: newBiase)
//output
let outputTexture = device.makeFloatTexture(value: [Float32](), textureWidth: 2, textureHeight: 2, arrayLength: 1)
let filterSize: (width: Int, height: Int, channel: Int) = (3, 3, 4)
let paddings: (Int, Int) = (1, 1)
let stride: (Int, Int) = (2, 2)
let offsetX = filterSize.width/2 - paddings.0
let offsetY = filterSize.height/2 - paddings.1
let metalParam = MetalConvParam.init(offsetX: Int16(offsetX), offsetY: Int16(offsetY), offsetZ: 0, strideX: UInt16(stride.0), strideY: UInt16(stride.1), dilationX: UInt16(1), dilationY: UInt16(1))
let param = ConvAddBatchNormReluTestParam.init(inInputTexture: inputeTexture, inOutputTexture: outputTexture, inMetalParam: metalParam, inFilterBuffer: filterBuffer, inBiaseBuffer: biaseBuffer, inNewScaleBuffer: newScalueBuffer, inNewBiaseBuffer: newBiaseBuffer, inFilterSize: filterSize)
let initContext = InitContext.init()
initContext.metalLoadMode = .LoadMetalInDefaultLib
let convAddBnReluKernel = ConvAddBatchNormReluKernel<Float32>.init(device: device, testParam: param, initContext: initContext)
convAddBnReluKernel.test(commandBuffer: buffer, param: param)
buffer.addCompletedHandler { (buffer) in
let _: Float32? = inputeTexture.logDesc(header: "input texture", stridable: false)
let _: Float32? = outputTexture.logDesc(header: "output texture", stridable: false)
}
buffer.commit()
}
}
|
//
// ChatViewController.swift
// Firebase
//
// Created by erumaru on 10/30/19.
// Copyright © 2019 KBTU. All rights reserved.
//
import UIKit
class ChatViewController: UIViewController {
// MARK: - Constants
private struct Constants {
static let messagePlaceholder = "Введите сообщение"
}
// MARK: - Variables
var messages: [String] = []
// MARK: - Outlets
lazy var sendMessageButton: UIButton = {
let button = UIButton()
button.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .regular)
button.setTitleColor(.white, for: .normal)
button.setTitle("Отправить", for: .normal)
button.addTarget(self, action: #selector(sendMessage), for: .touchUpInside)
button.backgroundColor = .cyan
button.layer.cornerRadius = 10
return button
}()
lazy var tableView: UITableView = {
let view = UITableView()
view.tableFooterView = UIView()
view.rowHeight = UITableView.automaticDimension
view.estimatedRowHeight = 300
if #available(iOS 11.0, *) {
view.contentInsetAdjustmentBehavior = .never
} else {
// Fallback on earlier versions
}
view.delegate = self
view.dataSource = self
view.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
return view
}()
lazy var messageTextField: UITextField = {
let view = UITextField()
view.layer.cornerRadius = 10
view.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 16, height: 0))
view.leftViewMode = .always
view.backgroundColor = .lightGray
view.placeholder = Constants.messagePlaceholder
view.textContentType = .none
view.keyboardType = .default
view.returnKeyType = .done
return view
}()
// MARK: - Actions
@objc private func sendMessage() {
guard let text = messageTextField.text else { return }
ChatManager.shared.sendMessage(text)
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
ChatManager.shared.delegate = self
markup()
}
// MARK: - Markup
private func markup() {
view.backgroundColor = .white
[tableView, messageTextField, sendMessageButton].forEach { view.addSubview($0) }
tableView.snp.makeConstraints() {
$0.top.equalTo(view.snp.topMargin)
$0.left.right.equalToSuperview()
}
messageTextField.snp.makeConstraints() {
$0.bottom.equalTo(sendMessageButton.snp.top).offset(-8)
$0.left.equalToSuperview().offset(16)
$0.right.equalToSuperview().offset(-16)
$0.top.equalTo(tableView.snp.bottom).offset(8)
$0.height.equalTo(48)
}
sendMessageButton.snp.makeConstraints() {
$0.height.equalTo(48)
$0.left.equalToSuperview().offset(16)
$0.right.equalToSuperview().offset(-16)
$0.bottom.equalTo(view.snp.bottomMargin).offset(-16)
}
}
}
extension ChatViewController: ChatDelegate {
func updateChat(messages: [String]) {
self.messages = messages
self.tableView.reloadData()
}
}
extension ChatViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.numberOfLines = 0
cell.textLabel?.text = messages[indexPath.row]
return cell
}
}
|
//
// BenefitVC.swift
// Fid
//
// Created by CROCODILE on 10.03.2021.
//
import UIKit
import Freedom
import KeyboardLayoutGuide
import RealmSwift
import ProgressHUD
class BenefitVC: UIViewController {
@IBOutlet weak var cardImg: UIImageView!
@IBOutlet weak var cardNameLbl: UILabel!
@IBOutlet weak var view_numberLbl: UILabel!
@IBOutlet weak var likes_numberLbl: UILabel!
@IBOutlet weak var likesImg: UIImageView!
@IBOutlet weak var save_locallyBtn: UIButton!
@IBOutlet weak var uploadView: UIView!
@IBOutlet weak var saveView: UIView!
@IBOutlet weak var shopView: UIView!
@IBOutlet weak var chatView: UIView!
@IBOutlet weak var mapView: UIView!
@IBOutlet weak var shareView: UIView!
@IBOutlet weak var backImg: UIImageView!
@IBOutlet weak var descLbl: UILabel!
@IBOutlet weak var sendBtnImg: UIImageView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var bottomBar: UIView!
@IBOutlet weak var sendBtn: UIButton!
@IBOutlet weak var tagging: Tagging! {
didSet {
tagging.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tagging.accessibilityIdentifier = "Tagging"
tagging.textView.accessibilityIdentifier = "TaggingTextView"
tagging.borderWidth = 1.0
//tagging.cornerRadius = 5
tagging.textInset = UIEdgeInsets(top: 5, left: 0, bottom: 0, right: 0)
tagging.backgroundColor = UIColor.lightGray.withAlphaComponent(0.1)
tagging.defaultAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18)]
tagging.symbolAttributes = [NSAttributedString.Key.foregroundColor: UIColor.systemBlue]
tagging.taggedAttributes = [NSAttributedString.Key.foregroundColor: UIColor.systemBlue, NSAttributedString.Key.underlineStyle: NSNumber(value: 1)]
tagging.dataSource = self
tagging.symbol = "@"
switch traitCollection.userInterfaceStyle {
case .light, .unspecified:
// light mode detected
break
case .dark:
// dark mode detected
tagging.textView.textColor = .black
tagging.backgroundColor = .white
break
@unknown default:
break
}
}
}
let firebaseUpload = FirebaseUpload()
let firebaseDownload = FirebaseDownload()
@objc func handleSend() {
if tagging.textView.text.count != 0 {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "d MMM YYYY"
let dateStr = dateFormatter.string(from: Date())
let commentObject = ObjectComment()
commentObject.id = UUID().uuidString
commentObject.userId = AuthUser.userId()
commentObject.userName = Persons.fullname()
commentObject.comment = tagging.textView.text
commentObject.postId = self.benefit.benefit_id
commentObject.postTime = dateStr
commentObject.likes = []
commentObject.replies = []
self.comments.append(commentObject)
let indexPath = IndexPath(row: self.comments.count - 1, section: 0)
self.tableView.insertRows(at: [indexPath], with: .automatic)
self.tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
tagging.textView.text = nil
tagging.removeAllTaggedList()
firebaseUpload.UpdateComment(commentObject, postId: self.benefit.benefit_id) { response in
switch response {
case .failure: return
case .success:
print("Successfully commented")
}
}
self.tagging.textView.resignFirstResponder()
}
}
var comments: [ObjectComment] = [ObjectComment]()
var benefit: SearchQueryProduct!
var like_Num: Int = 0
private var person: Person!
private var initialTxt: String!
private var userImg: UIImage!
private var fullNameTxt: String!
var searchquery: String = ""
var searchcard: String = "I1I"
var searchcategory: String = "0"
var location_search: String = "0"
var userName: String = "Not Registered"
private var benefitRealm: Benefit?
private var likeBenefitRealm: LikeBenefit?
override func viewDidLoad() {
super.viewDidLoad()
initializeView()
configureView()
configureCommentView()
if let username = defaults.string(forKey: "userName") {
self.userName = username
}
}
//---------------------------------------------------------------------------------------------------------------------------------------------
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if (AuthUser.userId() == "") {
let alert = UIAlertController(title: "Login required", message: "You should login or register for benefit with the other users.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { void in
self.tabBarController?.selectedIndex = 0
}))
alert.addAction(UIAlertAction(title: "Register", style: .default, handler: { void in
let register = self.storyboard?.instantiateViewController(identifier: "RegisterVC") as! RegisterVC
self.navigationController?.popPushToVC(ofKind: RegisterVC.self, pushController: register)
}))
self.present(alert, animated: true, completion: nil)
}
FidHelper.shared.chatsFromBenefit = false
FidHelper.shared.benefit = nil
}
func initializeView() {
let back = UIImage(named: "back")
backImg.image = back?.withRenderingMode(.alwaysTemplate)
backImg.tintColor = UIColor(hexString: "#27bdb1")
self.uploadView.layer.borderWidth = 1.0
self.uploadView.layer.borderColor = UIColor.lightGray.cgColor
self.uploadView.layer.masksToBounds = true
self.saveView.layer.borderWidth = 1.0
self.saveView.layer.borderColor = UIColor.lightGray.cgColor
self.saveView.layer.masksToBounds = true
self.shopView.layer.borderWidth = 1.0
self.shopView.layer.borderColor = UIColor.lightGray.cgColor
self.shopView.layer.masksToBounds = true
self.chatView.layer.borderWidth = 1.0
self.chatView.layer.borderColor = UIColor.lightGray.cgColor
self.chatView.layer.masksToBounds = true
self.mapView.layer.borderWidth = 1.0
self.mapView.layer.borderColor = UIColor.lightGray.cgColor
self.mapView.layer.masksToBounds = true
self.shareView.layer.borderWidth = 1.0
self.shareView.layer.borderColor = UIColor.lightGray.cgColor
self.shareView.layer.masksToBounds = true
self.like_Num = Int(self.benefit.likes_number)!
// Benefit data from realm
benefitRealm = realm.object(ofType: Benefit.self, forPrimaryKey: self.benefit.benefit_id)
if benefitRealm != nil {
self.save_locallyBtn.isSelected = true
} else {
self.save_locallyBtn.isSelected = false
}
likeBenefitRealm = realm.object(ofType: LikeBenefit.self, forPrimaryKey: self.benefit.benefit_id)
if likeBenefitRealm != nil {
self.likesImg.image = UIImage(named: "icon_benefit_likes")
} else {
self.likesImg.image = UIImage(named: "icon_benefit_unlikes")
}
self.cardNameLbl.text = self.benefit.card_type
self.cardImg.sd_setImage(with: URL(string: self.benefit.card_image)!)
switch traitCollection.userInterfaceStyle {
case .light, .unspecified:
// light mode detected
break
case .dark:
// dark mode detected
let send = UIImage(named: "send_btn")
sendBtnImg.image = send?.withRenderingMode(.alwaysTemplate)
sendBtnImg.tintColor = UIColor(hexString: "#27bdb1")
break
@unknown default:
break
}
}
func configureView() {
self.descLbl.text = self.benefit.title
self.view_numberLbl.text = self.benefit.view_number
self.likes_numberLbl.text = self.benefit.likes_number
}
func configureCommentView() {
// bottomBar.bottomAnchor.constraint(equalTo: view.keyboardLayoutGuide.topAnchor).isActive = true
sendBtn.addTarget(self, action: #selector(handleSend), for: .touchUpInside)
self.tableView.keyboardDismissMode = .interactive
self.tableView.translatesAutoresizingMaskIntoConstraints = false
self.downloadComments()
}
// MARK: - IBActions
@IBAction func goback(_ sender: Any) {
self.navigationController?.popViewController(animated: true)
}
@IBAction func BenefitLikeAction(_ sender: Any) {
if likeBenefitRealm == nil {
self.like_Num = self.like_Num + 1
self.likes_numberLbl.text = "\(self.like_Num)"
self.likesImg.image = UIImage(named: "icon_benefit_likes")
self.sendLikeActionClick(operators: "increased")
self.saveLikeBenefit()
} else {
self.like_Num = self.like_Num - 1
self.likes_numberLbl.text = "\(self.like_Num)"
self.likesImg.image = UIImage(named: "icon_benefit_unlikes")
self.sendLikeActionClick(operators: "decreased")
let realm = try! Realm()
let deleteData = realm.object(ofType: LikeBenefit.self, forPrimaryKey: self.benefit.benefit_id)
try! realm.safeWrite {
realm.delete(deleteData!)
}
self.likeBenefitRealm = nil
print("deleted benefit from local")
}
}
@IBAction func gotoShare(_ sender: Any) {
self.shareAction()
}
@IBAction func gotoChat(_ sender: Any) {
// self.navigationController?.popToRootViewController(animated: true)
// NotificationCenter.default.post(name: NSNotification.Name("gotochat"), object: nil)
FidHelper.shared.chatsFromBenefit = true
FidHelper.shared.benefit = self.benefit
self.performSegue(withIdentifier: "chats_benefit", sender: self)
}
@IBAction func saveBenefitLocally(_ sender: Any) {
if benefitRealm == nil {
self.save_locallyBtn.isSelected = true
self.saveBenefit()
print("Saved benefit locally")
} else {
let realm = try! Realm()
let deleteData = realm.object(ofType: Benefit.self, forPrimaryKey: self.benefit.benefit_id)
try! realm.safeWrite {
realm.delete(deleteData!)
}
self.save_locallyBtn.isSelected = false
self.benefitRealm = nil
print("deleted benefit from local")
}
}
@IBAction func gotoMap(_ sender: Any) {
if self.benefit.locations.count != 0 {
self.performSegue(withIdentifier: "benefit_map", sender: self)
} else {
let alert = UIAlertController(title: "", message: "There is no any location data for this benefit", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
@IBAction func openShopUrl(_ sender: Any) {
UIApplication.shared.open(URL(string: self.benefit.search_url)!, options: [:], completionHandler: nil)
self.sendSearchUrl()
}
@IBAction func uploadAttachment(_ sender: Any) {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Open Camera", style: .default) { action in
ImagePicker.cameraPhoto(target: self, edit: true)
})
alert.addAction(UIAlertAction(title: "Photo Library", style: .default) { action in
ImagePicker.photoLibrary(target: self, edit: true)
})
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
present(alert, animated: true)
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func saveBenefit() {
let realm = try! Realm()
try! realm.safeWrite {
benefitRealm = Benefit()
benefitRealm?.benefit_id = self.benefit.benefit_id
benefitRealm?.title = self.benefit.title
benefitRealm?.card_type = self.benefit.card_type
benefitRealm?.search_url = self.benefit.search_url
benefitRealm?.search_category = self.benefit.search_category
benefitRealm?.card_image = self.benefit.card_image
benefitRealm?.view_number = self.benefit.view_number
benefitRealm?.likes_number = self.benefit.likes_number
let locationss = List<LocationRealm>()
for item in self.benefit.locations {
let loc = LocationRealm()
loc.lat = item.lat
loc.lon = item.lon
locationss.append(loc)
}
benefitRealm?.locations = locationss
realm.add(benefitRealm!, update: .modified)
}
}
func saveLikeBenefit() {
let realm = try! Realm()
try! realm.safeWrite {
likeBenefitRealm = LikeBenefit()
likeBenefitRealm?.benefit_id = self.benefit.benefit_id
likeBenefitRealm?.title = self.benefit.title
likeBenefitRealm?.card_type = self.benefit.card_type
likeBenefitRealm?.search_url = self.benefit.search_url
likeBenefitRealm?.search_category = self.benefit.search_category
likeBenefitRealm?.card_image = self.benefit.card_image
likeBenefitRealm?.view_number = self.benefit.view_number
likeBenefitRealm?.likes_number = self.benefit.likes_number
let locationss = List<LocationRealm>()
for item in self.benefit.locations {
let loc = LocationRealm()
loc.lat = item.lat
loc.lon = item.lon
locationss.append(loc)
}
likeBenefitRealm?.locations = locationss
realm.add(likeBenefitRealm!, update: .modified)
}
}
//---------------------------------------------------------------------------------------------------------------------------------------------
func uploadPicture(image: UIImage) {
if let data = image.jpegData(compressionQuality: 0.6) {
let pic_name = UUID().uuidString
self.showLoadingView()
MediaUpload.benefit(pic_name, data: data) { error in
if (error == nil) {
self.uploadAttachment_Img(pic_name: pic_name)
} else {
self.hideLoadingView()
ProgressHUD.showError("Picture upload error.")
}
}
}
}
func uploadAttachment_Img(pic_name: String) {
let param: [String: String] = ["username": self.userName, "benafit_id": self.benefit.benefit_id, "pic_name": pic_name]
APIHandler.AFPostRequest_SendSearchUrl(url: ServerURL.upload_click, param: param) { error in
self.hideLoadingView()
if let error = error {
print(error.localizedDescription)
ProgressHUD.showError(error.localizedDescription)
return
}
print("Success")
ProgressHUD.showSuccess()
}
}
func sendSearchUrl() {
let param: [String: String] = ["texturl": self.benefit.search_url, "textsearch": searchquery, "textcard": searchcard, "username": userName, "cardquery": self.benefit.card_type, "titlequery": self.benefit.title, "benafit_id": self.benefit.benefit_id]
print(param)
APIHandler.AFPostRequest_SendSearchUrl(url: ServerURL.sendSearchUrl, param: param) { error in
if let error = error {
print(error.localizedDescription)
return
}
print("Success")
}
}
func sendLikeActionClick(operators: String) {
let param : [String: String] = ["search_url": self.benefit.search_url, "benafit_id": self.benefit.benefit_id, "like_operator": operators, "username": userName, "card_displayname": self.benefit.card_type, "title_base": self.benefit.title]
print(param)
APIHandler.AFPostRequest_SendBenefitClick(url: ServerURL.like_insert, param: param) { error in
if let error = error {
print(error.localizedDescription)
return
}
print("Success")
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "benefit_map" {
let destination = segue.destination as! BenefitMapVC
destination.benefitList = self.benefit.locations
} else if segue.identifier == "chats_benefit" {
_ = segue.destination as! BenefitChatsView
}
}
// MARK: - Private methods
func shareAction() {
let title = self.benefit.title!
let url = URL(string: self.benefit.search_url)!
let end = "shared by FID app"
// Enable Debug Logs (disabled by default)
Freedom.debugEnabled = true
// Fetch activities for Safari and all third-party browsers supported by Freedom.
let activities = Freedom.browsers()
// Alternatively, one could select a specific browser (or browsers).
// let activities = Freedom.browsers([.chrome])
let activityViewController : UIActivityViewController = UIActivityViewController(
activityItems: [title, url, end], applicationActivities: activities)
activityViewController.isModalInPresentation = true
activityViewController.popoverPresentationController?.sourceView = self.view
// This lines is for the popover you need to show in iPad
// activityViewController.popoverPresentationController?.sourceView = (sender as! UIButton)
// This line remove the arrow of the popover to show in iPad
activityViewController.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.down
activityViewController.popoverPresentationController?.sourceRect = CGRect(x: 150, y: 150, width: 0, height: 0)
// Pre-configuring activity items
activityViewController.activityItemsConfiguration = [
UIActivity.ActivityType.message
] as? UIActivityItemsConfigurationReading
// Anything you want to exclude
activityViewController.excludedActivityTypes = [
UIActivity.ActivityType.postToWeibo,
UIActivity.ActivityType.print,
UIActivity.ActivityType.assignToContact,
UIActivity.ActivityType.saveToCameraRoll,
UIActivity.ActivityType.addToReadingList,
UIActivity.ActivityType.postToFlickr,
UIActivity.ActivityType.postToVimeo,
UIActivity.ActivityType.postToTencentWeibo,
UIActivity.ActivityType.postToFacebook
]
activityViewController.isModalInPresentation = true
self.present(activityViewController, animated: true, completion: nil)
}
func downloadComments() {
self.comments.removeAll()
// self.showLoadingView()
firebaseDownload.DownloadComments(postId: self.benefit.benefit_id) { comments, error in
// self.hideLoadingView()
if let error = error {
print(error.localizedDescription)
return
}
if let comments = comments {
let sortedComments = comments.sorted {
$0.timestamp < $1.timestamp
}
self.comments = sortedComments
self.tableView.reloadData()
self.tableView.scroll(to: .bottom, animated: true)
}
}
}
}
extension BenefitVC: UIActivityItemSource {
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return ""
}
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
return ""
}
func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivity.ActivityType?) -> String {
return "FID APP"
}
}
// MARK: - TaggingDataSource
extension BenefitVC: TaggingDataSource {
func tagging(_ tagging: Tagging, didChangedTaggedList taggedList: [TaggingModel]) {
}
}
extension BenefitVC : UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CommentTableCell", for: indexPath) as! CommentTableCell
let comment = self.comments[indexPath.row]
cell.configure(comment: comment)
cell.delegate = self
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
extension BenefitVC: UITextViewDelegate {
}
extension BenefitVC: CommentDelegate {
func handleMention(username: String) {
print("username is \(username)")
}
func handleHashTag(tagname: String) {
print("clicked hashtag")
}
func handleURL(url: URL) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
func replyComment(username: String) {
tagging.textView.text.append("@")
tagging.updateTaggedList(allText: tagging.textView.text, tagText: username)
tagging.textView.becomeFirstResponder()
}
}
// MARK: - UIImagePickerControllerDelegate
//-------------------------------------------------------------------------------------------------------------------------------------------------
extension BenefitVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//---------------------------------------------------------------------------------------------------------------------------------------------
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
if let image = info[.editedImage] as? UIImage {
uploadPicture(image: image)
}
picker.dismiss(animated: true)
}
}
|
//
// ViewModel.swift
// Examples
//
// Created by ALEXEY ABDULIN on 02.02.2021.
// Copyright © 2021 ALEXEY ABDULIN. All rights reserved.
//
import Foundation
import BaseMVVM
class ViewModel: SBServiceViewModel<SBDefaultServiceFactory>
{
override init( serviceFactory: SBDefaultServiceFactory, parent: SBViewModel? = nil )
{
super.init( serviceFactory: serviceFactory, parent: parent )
}
}
|
//
// CollectionViewCell.swift
// Virtual Tourist
//
// Created by Hanoudi on 5/18/20.
// Copyright © 2020 Hanan. All rights reserved.
//
// This is the controller reponsible for cells in the collection view
// It is responsible for downloading and retriving images from store
import Foundation
import UIKit
class CollectionViewCell: UICollectionViewCell {
// MARK:- Outlets
let delegate = UIApplication.shared.delegate as! AppDelegate
@IBOutlet weak var spinner: UIActivityIndicatorView!
@IBOutlet weak var imageView: UIImageView!
func loadImages(_ image: Image) {
if image.imageData != nil {
DispatchQueue.main.async {
self.imageView.image = UIImage(data: image.imageData! as Data)
self.spinner.stopAnimating()
}
} else {
download(image)
}
}
}
// ---------------------------------------------------------------------- //
// MARK:- CollectionViewCell's Extension
extension CollectionViewCell {
// MARK:- Methods
func download(_ image: Image) {
URLSession.shared.dataTask(with: URL(string: image.imageURL!)!) { (data, response, error) in
if error == nil {
DispatchQueue.main.async {
self.imageView.image = UIImage(data: data! as Data)
self.spinner.stopAnimating()
self.saveImageToDataController(image: image, imageData: data! as NSData)
}
}
}
.resume()
}
func saveImageToDataController(image: Image, imageData: NSData) {
do {
image.imageData = imageData
let dataController = delegate.dataController
try dataController.saveContext()
} catch {
print("Saving image failed.")
}
}
}
|
//
// RegistrationViewController.swift
// Shopping Tinder
//
// Created by Elad Golan on 15/09/2016.
// Copyright © 2016 AsaEl. All rights reserved.
//
import UIKit
import Foundation
class RegisterViewController: UIViewController,
UITextFieldDelegate{
@IBOutlet weak var userEmailTextField: UITextField!
@IBOutlet weak var friendEmailTextField: UITextField!
@IBOutlet weak var signupBackgroundImage: UIImageView!
@IBAction func actionTriggered(_ sender: AnyObject) {
let message = "Yours Email: "+userEmailTextField.text! +
"\n friend's Email: "+friendEmailTextField.text!
if (isValidEmail(testStr: userEmailTextField.text!) && isValidEmail(testStr: friendEmailTextField.text!)){
// let alert = UIAlertController(title: "Signup", message:message, preferredStyle: .alert)
// alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
// self.present(alert, animated: true){}
}
else{
let alert = UIAlertController(title: "Signup", message:"Email isn't valid", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
self.present(alert, animated: true){}
}
}
func isValidEmail(testStr:String) -> Bool {
// print("validate calendar: \(testStr)")
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: testStr)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool{
//hide the keyboard
textField.resignFirstResponder()
return true
}
private func textFieldDidEndEditing(_ textField1: UITextField,textField2: UITextField){
userEmailTextField.text = textField1.text
friendEmailTextField.text = textField2.text
}
// func md5(string: String) -> [UInt8] {
// var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0)
// if let data = string.data(usingEncoding: NSUTF8StringEncoding) {
// CC_MD5(data.bytes, CC_LONG(data.length), &digest)
// }
//
// return digest
// }
override func viewDidLoad() {
super.viewDidLoad()
userEmailTextField.delegate = self
friendEmailTextField.delegate = self
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let width = CGFloat(1.0)
let border = CALayer()
let border2 = CALayer()
border.borderColor = UIColor.gray.cgColor
border.frame = CGRect(x: 0, y: userEmailTextField.frame.size.height - width, width: userEmailTextField.frame.size.width, height: userEmailTextField.frame.size.height)
border.borderWidth = width
border2.borderColor = UIColor.gray.cgColor
border2.frame = CGRect(x: 0, y: friendEmailTextField.frame.size.height - width, width: friendEmailTextField.frame.size.width, height: friendEmailTextField.frame.size.height)
border2.borderWidth = width
userEmailTextField.layer.addSublayer(border)
userEmailTextField.layer.masksToBounds = true
friendEmailTextField.layer.addSublayer(border2)
friendEmailTextField.layer.masksToBounds = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
|
//
// MenuAddMoreCategoryVC.swift
// SnobbiMerchantSide
//
// Created by MAC on 05/10/17.
// Copyright © 2017 Orem. All rights reserved.
//
import UIKit
import FTIndicator
class MenuAddMoreCategoryVC: UIViewController {
//MARK- IBOutlet
@IBOutlet weak var txtFld_EnterItemCategory: UITextField!
@IBOutlet weak var txtFld_ItemName: UITextField!
@IBOutlet weak var txtFld_EnterPrice: UITextField!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var view_ItemandPrice: UIView!
@IBOutlet weak var view_ItemName: UIView!
@IBOutlet weak var view_itemPrice: UIView!
@IBOutlet weak var lbl_HeadingAddImage: UILabel!
@IBOutlet weak var lbl_HeadingPrice: UILabel!
@IBOutlet weak var lbl_HeadinItem: UILabel!
@IBOutlet weak var btn_SelectImage: UIButton!
//MARK- Constant and Variables
let kCellReusableIdentifier = "MenuAddItem"
var itemArray = [NSDictionary]()
var itemDict = NSDictionary()
var imageArray = [UIImage]()
var selectedImage:UIImage?
let wsManager = WebserviceManager()
var boolImageSelectd = false
var picker:UIImagePickerController?=UIImagePickerController()
//MARK- ViewLifeCycle
override func viewDidLoad() {
super.viewDidLoad()
txtFld_ItemName.delegate = self
txtFld_EnterPrice.delegate = self
txtFld_EnterItemCategory.delegate = self
self.addToolBar(textField : self.txtFld_EnterPrice)
}
func addToolBar(textField: UITextField){
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.tintColor = UIColor.black
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(donePressed))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
toolBar.items = [spaceButton, doneButton]
toolBar.sizeToFit()
textField.delegate = self
textField.inputAccessoryView = toolBar
}
func donePressed(){
view.endEditing(true)
}
func cancelPressed(){
view.endEditing(true) // or do something
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.navigationController?.setNavigationBarHidden(false, animated: animated);
self.title = "Add Items"
self.SetBackBarButtonCustom()
}
//MARK- Navigation Back Button
func SetBackBarButtonCustom()
{
//Back buttion
let btnLeftMenu: UIButton = UIButton()
btnLeftMenu.setImage(UIImage(named: "leftback"), for: UIControlState())
btnLeftMenu.addTarget(self, action: #selector(self.onClcikBack), for: UIControlEvents.touchUpInside)
btnLeftMenu.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
let barButton = UIBarButtonItem(customView: btnLeftMenu)
self.navigationItem.leftBarButtonItem = barButton
}
//Navigation back button action
func onClcikBack()
{
_ = self.navigationController?.popViewController(animated: true)
}
//MARK- IBAction
@IBAction func action_PickImage(_ sender: Any) {
showActionSheet()
}
@IBAction func action_Save(_ sender: Any) {
var price : String = ""
if (txtFld_EnterItemCategory.text?.isEmpty)!{
FTIndicator.showToastMessage("Please enter menu name")
return
}
if (txtFld_ItemName.text?.isEmpty)!{
FTIndicator.showToastMessage("Please enter item name")
return
}
if (txtFld_EnterPrice.text?.isEmpty)!{
FTIndicator.showToastMessage("Please enter item price")
return
}
if !((txtFld_EnterPrice.text?.isEmpty)!){
price = String(describing: Double(txtFld_EnterPrice.text!)!)
if price == "0.0"{
FTIndicator.showToastMessage("Please enter item price")
return
}
else {
txtFld_EnterPrice.text = price
}
}
if boolImageSelectd == false
{
FTIndicator.showToastMessage("Please select item image")
return
}
FTIndicator.showProgress(withMessage: "Requesting..")
self.wsManager.createMenu(menuname: txtFld_EnterItemCategory.text!, itemName: txtFld_ItemName.text!, itemPrice: txtFld_EnterPrice.text!, itemImage: selectedImage!, completionHandler:{ (success, message) -> Void in
DispatchQueue.main.async(execute: { () -> Void in
if success {
FTIndicator.dismissProgress()
FTIndicator.showToastMessage(message)
self.onClcikBack()
} else {
FTIndicator.dismissProgress()
FTIndicator.showToastMessage(message)
}
});
})
}
func notPrettyString(from object: Any) -> String? {
if let objectData = try? JSONSerialization.data(withJSONObject: object, options: JSONSerialization.WritingOptions(rawValue: 0)) {
let objectString = String(data: objectData, encoding: .utf8)
return objectString
}
return nil
}
@IBOutlet weak var btn_AddItem: UIButton!
@IBAction func addItemToTable(_ sender: UIButton){
if (txtFld_ItemName.text?.isEmpty)!{
FTIndicator.showToastMessage("Please enter item name")
return
}
else if (txtFld_EnterPrice.text?.isEmpty)!{
FTIndicator.showToastMessage("Please enter item price")
return
}
else if !boolImageSelectd{
FTIndicator.showToastMessage("Please select item image")
return
}
let selectedImage = btn_SelectImage.backgroundImage(for: .normal)
itemDict = ["name":txtFld_ItemName.text ?? "","price":txtFld_EnterPrice.text ?? "","image":"image\(imageArray.count-1).jpg"]
imageArray.append(selectedImage!)
itemArray.append(itemDict)
txtFld_ItemName.text = ""
txtFld_EnterPrice.text = ""
boolImageSelectd = false
btn_SelectImage.setBackgroundImage(UIImage(named:"placeholderImage"), for: .normal)
print(itemArray)
tableView.beginUpdates()
tableView.insertRows(at: [IndexPath(row: itemArray.count-1, section: 0)], with: .automatic)
tableView.endUpdates()
}
}
//MARK - Extension's
extension MenuAddMoreCategoryVC: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: kCellReusableIdentifier, for: indexPath) as? MenuAddItem ??
MenuAddItem(style: .default, reuseIdentifier: "kCellReusableIdentifier")
let dict = itemArray[indexPath.row] as NSDictionary
cell.lbl_ItemName.text = dict.object(forKey: "name") as? String
cell.lbl_ItemPrice.text = dict.object(forKey: "price") as? String
cell.thumbnailImageView.image = imageArray[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// DispatchQueue.main.async(){
//
// self.performSegue(withIdentifier: "segueAdditionalChargeVC", sender: self)
//
// }
// guard let menuContainerViewController = self.menuContainerViewController else {
// return
// }
//
// menuContainerViewController.selectContentViewController(menuContainerViewController.contentViewControllers[indexPath.row])
// menuContainerViewController.hideSideMenu()
}
}
|
//
// DemographicViewController.swift
// Jigsaw
//
// Created by Grant Larson on 10/27/19.
// Copyright © 2019 ECE564. All rights reserved.
//
import UIKit
import Firebase
class DemographicViewController: UIViewController,UITextFieldDelegate,UIPickerViewDelegate,UIPickerViewDataSource {
// lazy var datePicker: UIDatePicker = {
// let picker = UIDatePicker()
// picker.datePickerMode = .date
// picker.addTarget(self, action: #selector(datePickerChanged(_:)), for: .valueChanged)
// return picker
// }()
//
// lazy var dateFormatter: DateFormatter = {
// let formatter = DateFormatter()
// formatter.dateStyle = .medium
// formatter.timeStyle = .none
// return formatter
// }()
//
private var politicalPicker: UIPickerView?
private var genderPicker: UIPickerView?
private var agePicker: UIPickerView?
private var genderPickerOption = ["Male", "Female", "Non-binary", "Prefer not to say"]
private var politicalPickerOption = ["Democratic","Republican","others","Don't want to disclose"]
private var agePickerOption = ["18-25","25-35","35+","Don't want to disclose"]
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var genderTextField: UITextField!
// race
@IBOutlet weak var ageTextField: UITextField!
@IBOutlet weak var religionTextField: UITextField!
@IBOutlet weak var politicalTextField: UITextField!
@IBOutlet weak var deleteAccountButton: UIButton!
@IBOutlet weak var saveInfo: UIBarButtonItem!
@IBAction func storeDatabase(_ sender: Any) {
let currentuser : String? = Auth.auth().currentUser?.uid; Database.database().reference().child("users").child(currentuser!).child("religion").setValue(religionTextField.text ?? "Not chosen")
Database.database().reference().child("users").child(currentuser!).child("gender").setValue(genderTextField.text ?? "Not chosen")
Database.database().reference().child("users").child(currentuser!).child("political").setValue(politicalTextField.text ?? "Not chosen")
Database.database().reference().child("users").child(currentuser!).child("age").setValue(ageTextField.text ?? "Not chosen")
Database.database().reference().child("users").child(currentuser!).child("name").setValue(nameTextField.text ?? "Not chosen")
}
@IBAction func deleteAccount(_ sender: Any) {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let delete = UIAlertAction(title: "Delete", style: .destructive) { action in
guard let user = Auth.auth().currentUser else{
print("Not logged in?")
return
}
let uid = user.uid
user.delete { error in
if let error = error {
// An error happened.
print(error)
}
else {
let ref = Database.database().reference(fromURL: "https://jigsaw-25200.firebaseio.com/")
let usersRef = ref.child("users").child(uid)
usersRef.removeValue()
self.dismiss(animated: true, completion: {})
}
}
}
actionSheet.addAction(cancel)
actionSheet.addAction(delete)
present(actionSheet, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
setUpDeleteButton()
loadPicker()
setdelegate()
loadData()
// dismiss the keyboard
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))))
}
func loadData(){
let textfields = [nameTextField, genderTextField, ageTextField, religionTextField, politicalTextField]
let databaseStrings = ["name" ,"gender", "age", "religion", "political"]
let currentuser : String? = Auth.auth().currentUser?.uid;
for i in 0...databaseStrings.count-1 {
Database.database().reference().child("users").child(currentuser!).child(databaseStrings[i]).observeSingleEvent(of: .value, with: { (snapshot) in
let string_value = snapshot.value as? NSString
if (string_value != nil) {
textfields[i]!.text = String(string_value!)
}
}) { (error) in
print(error.localizedDescription)
}
}
}
func setUpDeleteButton() {
deleteAccountButton.setTitleColor(.red, for: .normal)
deleteAccountButton.setTitle("Delete Account", for: .normal)
deleteAccountButton.titleLabel?.alpha = 0.75
deleteAccountButton.layer.borderColor = UIColor.black.cgColor
//deleteAccountButton.layer.borderWidth = 1.0
deleteAccountButton.backgroundColor = UIColor(red: 246/255, green: 246/255, blue: 246/255, alpha:1)
deleteAccountButton.translatesAutoresizingMaskIntoConstraints = false
deleteAccountButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -40).isActive = true
deleteAccountButton.widthAnchor.constraint(equalTo: view.widthAnchor, constant: 0).isActive = true
deleteAccountButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
deleteAccountButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
}
//load the picker information
func loadPicker(){
// DOBTextField.inputView = datePicker
politicalPicker = UIPickerView()
politicalTextField.inputView = politicalPicker
genderPicker = UIPickerView()
genderTextField.inputView = genderPicker
agePicker = UIPickerView()
ageTextField.inputView = agePicker
}
//sets the delegate of the textfield as self
func setdelegate(){
nameTextField.delegate=self
politicalTextField.delegate = self
ageTextField.delegate = self
// DOBTextField.delegate = self
religionTextField.delegate = self
genderTextField.delegate=self
politicalPicker?.delegate=self
politicalPicker?.dataSource=self
genderPicker?.delegate=self
genderPicker?.dataSource=self
agePicker?.delegate=self
agePicker?.dataSource=self
}
// //MARK: date picker:
// @objc func datePickerChanged(_ sender: UIDatePicker) {
// DOBTextField.text = dateFormatter.string(from: sender.date)
// }
//
// override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// view.endEditing(true)
// }
//MARK: other picker
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
nameTextField.resignFirstResponder()
genderTextField.resignFirstResponder()
ageTextField.resignFirstResponder()
// DOBTextField.resignFirstResponder()
religionTextField.resignFirstResponder()
politicalTextField.resignFirstResponder()
return true
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch pickerView {
case politicalPicker:
return politicalPickerOption.count
case genderPicker:
return genderPickerOption.count
default:
return agePickerOption.count
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch pickerView {
case politicalPicker:
politicalTextField.text = politicalPickerOption[row]
case genderPicker:
genderTextField.text = genderPickerOption[row]
default://case agePicker:
ageTextField.text = agePickerOption[row]
}
self.politicalTextField.endEditing(false)
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch pickerView {
case politicalPicker:
return politicalPickerOption[row]
case genderPicker:
return genderPickerOption[row]
default:
return agePickerOption[row]
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
|
//
// AreaViewModel.swift
// inke
//
// Created by bb on 2017/8/13.
// Copyright © 2017年 bb. All rights reserved.
//
import UIKit
class AreaViewModel {
lazy var sexModelArray: [SexModel] = [SexModel]()
lazy var areaModelArray: [AreaModel] = [AreaModel]()
lazy var array: [[String: Any]] = [[String: Any]]()
}
extension AreaViewModel {
func loadData(finishedCallback: @escaping ()->()) {
let dGroup: DispatchGroup = DispatchGroup()
// MARK: 第一组
array = [["sex": "a", "isSelected": true], ["sex": "m", "isSelected": false], ["sex": "f", "isSelected": false]]
for dict in array {
sexModelArray.append(SexModel(dict: dict))
}
// MARK: 第二组
// http://116.211.167.106/api/live/classifyindex?interest=0&cv=IK4.0.90_Iphone
let locationUrlString = "http://116.211.167.106/api/live/classifyindex"
let locationParam = ["interest": "0", "cv": "IK4.0.90_Iphone"]
// 进入组
dGroup.enter()
NetworkTools.requestData(type: .GET, URLString: locationUrlString, parameters: locationParam) { (result) in
guard let resultDict = result as? [String: Any] else { return }
print(resultDict)
guard let dataArray = resultDict["location"] as? [[String : Any]] else {
print("location数据-请求失败")
// 离开组
dGroup.leave()
return
}
for dict in dataArray {
self.areaModelArray.append(AreaModel(dict: dict))
}
// 离开组
dGroup.leave()
}
dGroup.notify(queue: DispatchQueue.main) {
print("area-所有数据接收完成")
finishedCallback()
}
}
}
|
//
// Course+CoreDataProperties.swift
// ProyectoFinal - Organizador de Apuntes
//
// Created by Alumno on 4/10/18.
// Copyright © 2018 itesm. All rights reserved.
//
//
import Foundation
import CoreData
extension Course {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Course> {
return NSFetchRequest<Course>(entityName: "Course")
}
@NSManaged public var email: String?
@NSManaged public var name: String?
@NSManaged public var office: String?
@NSManaged public var professor: String?
@NSManaged public var tutoring: String?
@NSManaged public var hasNote: NSSet?
@NSManaged public var hasVideoLink: NSSet?
@NSManaged public var hasDocument: NSSet?
}
// MARK: Generated accessors for hasNote
extension Course {
@objc(addHasNoteObject:)
@NSManaged public func addToHasNote(_ value: Note)
@objc(removeHasNoteObject:)
@NSManaged public func removeFromHasNote(_ value: Note)
@objc(addHasNote:)
@NSManaged public func addToHasNote(_ values: NSSet)
@objc(removeHasNote:)
@NSManaged public func removeFromHasNote(_ values: NSSet)
}
// MARK: Generated accessors for hasVideoLink
extension Course {
@objc(addHasVideoLinkObject:)
@NSManaged public func addToHasVideoLink(_ value: VideoLink)
@objc(removeHasVideoLinkObject:)
@NSManaged public func removeFromHasVideoLink(_ value: VideoLink)
@objc(addHasVideoLink:)
@NSManaged public func addToHasVideoLink(_ values: NSSet)
@objc(removeHasVideoLink:)
@NSManaged public func removeFromHasVideoLink(_ values: NSSet)
}
// MARK: Generated accessors for hasDocument
extension Course {
@objc(addHasDocumentObject:)
@NSManaged public func addToHasDocument(_ value: Document)
@objc(removeHasDocumentObject:)
@NSManaged public func removeFromHasDocument(_ value: Document)
@objc(addHasDocument:)
@NSManaged public func addToHasDocument(_ values: NSSet)
@objc(removeHasDocument:)
@NSManaged public func removeFromHasDocument(_ values: NSSet)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.