text stringlengths 8 1.32M |
|---|
//
// SolarSystemScene.swift
// OnlineTutor
//
// Created by Rojan Bajracharya on 5/25/20.
// Copyright © 2020 Rojan Bajracharya. All rights reserved.
//
import Foundation
import ARKit
class SolarSystemScene {
static let shareInstance = SolarSystemScene()
func displaySolarSystem(radiusValue: Double, imageName: String) -> SCNNode {
let sphere = SCNSphere(radius: CGFloat(radiusValue))
let material = SCNMaterial()
var imageLocation = "art.scnassets/" + imageName + ".jpg"
material.diffuse.contents = UIImage.init(named: imageLocation)
sphere.materials = [material]
let node = SCNNode()
node.position = SCNVector3(0.1, 0.1, -20.9)
node.geometry = sphere
return node
}
func displaySolarSystem(imageName: String) -> SCNNode {
let sphere = SCNSphere(radius: 1)
let material = SCNMaterial()
var imageLocation = "art.scnassets/" + imageName + ".jpg"
material.diffuse.contents = UIImage.init(named: imageLocation)
sphere.materials = [material]
let node = SCNNode()
node.position = SCNVector3(0.1, -0.5, -4.9)
node.geometry = sphere
return node
}
func displayPlanetDescription(valueToDisplay: String) -> SCNNode {
let textGeometry = SCNText(string: valueToDisplay, extrusionDepth: 1.0)
textGeometry.firstMaterial?.diffuse.contents = UIColor.black
let textNode = SCNNode(geometry: textGeometry)
textNode.scale = SCNVector3(x: 0.01, y: 0.01, z: 0.01)
textNode.position = SCNVector3(x: 0.9, y: -0.5, z: -3.5)
return textNode
}
}
|
//
// QuietScroller.swift
// InoJournal
//
// Created by Luis Orozco on 3/24/17.
// Copyright © 2017 Luis Orozco. All rights reserved.
//
import Cocoa
class QuietScroller: NSScroller {
override func draw(_ dirtyRect: NSRect) {
NSColor(red:0, green:0, blue: 0, alpha:0.2).set()
super.draw(dirtyRect)
}
}
|
//
// RestAPIRequest.swift
// Jarvis
//
// Created by Jianguo Wu on 2018/10/25.
// Copyright © 2018年 wujianguo. All rights reserved.
//
import Foundation
enum RestAPIError: Error {
case serverError(Int, String)
case networkError(Int, String)
case defaultError
}
protocol RestAPIResponseProtocol: Decodable {
var msg: String { get }
var code: Int { get }
var error: Error? { get }
}
struct RestAPIResponse<T: Decodable> : RestAPIResponseProtocol {
let msg: String
let code: Int
let data: T?
var error: Error? {
if code != 0 {
return RestAPIError.serverError(code, msg)
}
return nil
}
}
struct RestAPIRequest {
static func url(endpoint: String) -> URL {
if endpoint.hasPrefix("http://") || endpoint.hasPrefix("https://") {
return URL(string: endpoint)!
}
return URL(string: "https://yousir.leanapp.cn/")!.appendingPathComponent(endpoint)
}
let request: URLRequest
// init(get endpoint: String, query: [String: Any]) {
//
// }
init(post endpoint: String, query: [String: Any] = [:], body: Data) {
var components = URLComponents(string: RestAPIRequest.url(endpoint: endpoint).absoluteString)!
var queryItems = [URLQueryItem]()
for (k, v) in query {
queryItems.append(URLQueryItem(name: k, value: "\(v)"))
}
components.queryItems = queryItems
var req = URLRequest(url: components.url!)
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.httpBody = body
request = req
}
@discardableResult
func response<T: Decodable>(success: ((T)->Void)?, failure: ((Error)->Void)?) -> URLSessionDataTask {
return responseData(success: { (data) in
do {
let ret = try JSONDecoder().decode(RestAPIResponse<T>.self, from: data)
DispatchQueue.main.async {
if let error = ret.error {
debugPrint(error)
failure?(error)
} else if ret.data != nil {
success?(ret.data!)
} else {
failure?(RestAPIError.defaultError)
}
}
} catch {
DispatchQueue.main.async {
debugPrint(error)
failure?(error)
}
}
}, failure: failure)
}
func responseData(success: ((Data)->Void)?, failure: ((Error)->Void)?) -> URLSessionDataTask {
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
DispatchQueue.main.async {
failure?(error)
}
} else if let data = data {
success?(data)
} else {
DispatchQueue.main.async {
failure?(RestAPIError.defaultError)
}
}
}
task.resume()
return task
}
}
|
//
// StackOverflowClientTests.swift
// SOTopTwentyKitTests
//
// Created by Trevor Doodes on 15/02/2020.
// Copyright © 2020 IronworksMediaLimited. All rights reserved.
//
@testable import SOTopTwentyKit
import XCTest
class StackOverFlowClientTests: XCTestCase {
var baseURL: URL!
var session: MockURLSession!
var sut: StackOverflowClient!
var getUsersURL: URL {
return URL(string: "users?pagesize=20&order=desc&sort=reputation&site=stackoverflow", relativeTo: baseURL)!
}
override func setUp() {
super.setUp()
baseURL = URL(string: "https://example.com/api/v1")!
session = MockURLSession()
sut = StackOverflowClient(baseURL: baseURL, session: session, responseQueue: nil)
}
override func tearDown() {
baseURL = nil
session = nil
sut = nil
super.tearDown()
}
func whenGetUsers(data: Data? = nil,
statusCode: Int = 200,
error: Error? = nil) -> (calledCompletion: Bool, items: Items?, error: Error?){
let response = HTTPURLResponse(url: getUsersURL,
statusCode: statusCode,
httpVersion: nil,
headerFields: nil)!
var calledCompletion = false
var receivedItems: Items? = nil
var receivedError: Error? = nil
let mockTask = sut.getUsers() { items, error in
calledCompletion = true
receivedItems = items
receivedError = error
} as! MockURLSessionDataTask
mockTask.completionHandler(data, response, error)
return (calledCompletion, receivedItems, receivedError)
}
func verifyGetUsersDispatchedToMain(data: Data? = nil,
statusCode: Int = 200,
error: Error? = nil,
line: UInt = #line) {
session.givenDispatchQueue()
sut = StackOverflowClient(baseURL: baseURL, session: session, responseQueue: .main)
let expectation = self.expectation(description: "Completion wasn't called")
var thread: Thread!
let mockTask = sut.getUsers() { items, error in
thread = Thread.current
expectation.fulfill()
} as! MockURLSessionDataTask
let response = HTTPURLResponse(url: getUsersURL,
statusCode: statusCode,
httpVersion: nil,
headerFields: nil)!
mockTask.completionHandler(data, response, error)
waitForExpectations(timeout: 0.2) { _ in
XCTAssertTrue(thread.isMainThread, line: line)
}
}
func testConformsToStackOverflowSevice() {
XCTAssertTrue((sut as AnyObject) is StackOverflowService)
}
func testStackOverflowServiceDeclaresGetDogs() {
let service = sut as StackOverflowService
_ = service.getUsers() { _, _ in }
}
func testSharedSetsBaseURL() {
let baseURL = URL(string: "https://api.stackexchange.com/2.2/")!
XCTAssertEqual(StackOverflowClient.shared.baseURL, baseURL)
}
func testSharedSetsSession() {
let session = URLSession.shared
XCTAssertEqual(StackOverflowClient.shared.session, session)
}
func testShared_setsResponseQueue() {
let responseQueue = DispatchQueue.main
XCTAssertEqual(StackOverflowClient.shared.responseQueue, responseQueue)
}
func testInitSetsBaseURL() {
XCTAssertEqual(sut.baseURL, baseURL)
}
func testInitSetsSession() {
XCTAssertEqual(sut.session, session)
}
func testInitSetsResponseQueue() {
let responseQueue = DispatchQueue.main
sut = StackOverflowClient(baseURL: baseURL, session: session, responseQueue: responseQueue)
XCTAssertEqual(sut.responseQueue, responseQueue)
}
func testGetUsersCallsExpectedURL() {
let mockTask = sut.getUsers() {_, _ in } as! MockURLSessionDataTask
XCTAssertEqual(mockTask.url, getUsersURL)
}
func testGetusersCalls_resumeOnTask() {
let mockTask = sut.getUsers() { _, _ in } as! MockURLSessionDataTask
XCTAssertTrue(mockTask.calledResume)
}
func testGetUsersGivesResponseStatusCode500CallsCompletion() {
let result = whenGetUsers(statusCode: 500)
XCTAssertTrue(result.calledCompletion)
XCTAssertNil(result.items)
XCTAssertNil(result.error)
}
func testGetUsersGivenErrorCallsCompletionWithError() throws {
let expectedError = NSError(domain: "com.SOTopTwentyKitTests", code: 99)
let result = whenGetUsers(error: expectedError)
XCTAssertTrue(result.calledCompletion)
XCTAssertNil(result.items)
let actualError = try XCTUnwrap(result.error as NSError?)
XCTAssertEqual(actualError, expectedError)
}
func testGetUsersGivenValidJSONCallsCompletionWithDogs() throws {
let data = try Data.fromJSON(fileName: "Items")
let decoder = JSONDecoder()
let items = try decoder.decode(Items.self, from: data)
let result = whenGetUsers(data: data)
XCTAssertTrue(result.calledCompletion)
XCTAssertEqual(result.items, items)
XCTAssertNil(result.error)
}
func testGetUsersGivenInvalidJSONCallsCompletionWithError() throws {
let data = try Data.fromJSON(fileName: "GetUsersMissingValuesResponse")
var expectedError: NSError!
let decoder = JSONDecoder()
do {
_ = try decoder.decode(Items.self, from: data)
} catch {
expectedError = error as NSError
}
let result = whenGetUsers(data: data)
XCTAssertTrue(result.calledCompletion)
let actualError = try XCTUnwrap(result.error as NSError?)
XCTAssertEqual(actualError.domain, expectedError.domain)
XCTAssertEqual(actualError.code, expectedError.code)
}
func testGetUsersGivenHTTPStatusErrorDispatchToResponseQueue() {
verifyGetUsersDispatchedToMain(statusCode: 500)
}
func testGetUsersGivenErrorDispatchesToResponseQueue() {
let error = NSError(domain: "com.SOTopTwentyKitTests", code: 99)
verifyGetUsersDispatchedToMain(error: error)
}
func testGetUsersGivenGoodResponseDispatchesToResponseQueue() throws {
let data = try Data.fromJSON(fileName: "Items")
verifyGetUsersDispatchedToMain(data: data)
}
func testGetUsersGivenInvalidResponseDispatchsToResponseQueue() throws {
let data = try Data.fromJSON(fileName: "GetUsersMissingValuesResponse")
verifyGetUsersDispatchedToMain(data: data)
}
}
|
//
// ModalMegaChildViewController.swift
// Wallet One
//
// Created by Vitaliy Kuzmenko on 28/02/2017.
// Copyright © 2017 Wallet One. All rights reserved.
//
import UIKit
open class ModalMegaChildViewController: UIViewController {
@IBOutlet open var cancelButton: UIBarButtonItem!
open weak var modalMegaViewController: ModalMegaViewController!
open var preferredContentHeight: CGFloat {
return 100
}
open let topSpace: CGFloat = 130
open let maxHeight = UIScreen.main.bounds.height - 64
override open func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
deinit {
print("deinit ModalMegaChildViewController")
NotificationCenter.default.removeObserver(self)
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
set(height: preferredContentHeight, animated: animated)
}
@IBAction open func cancel() {
modalMegaViewController._dismiss(animated: true)
}
open func setNeedsHeightUpdate(complete: (() -> Void)? = nil) {
DispatchQueue.main.async {
self.set(height: self.preferredContentHeight, animated: true, complete: complete)
}
}
func set(height: CGFloat, animated: Bool, complete: (() -> Void)? = nil) {
let space: CGFloat
if #available(iOS 11.0, *) {
space = view.safeAreaInsets.bottom
} else {
space = bottomLayoutGuide.length
}
modalMegaViewController?.heightConstraint.constant = min(height + space, maxHeight)
if animated {
UIView.animate(withDuration: 0.3, animations: {
self.modalMegaViewController?.view.layoutIfNeeded()
}) { f in
complete?()
}
}
}
override open func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? ModalMegaChildViewController {
vc.modalMegaViewController = self.modalMegaViewController
}
}
override open func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
modalMegaViewController._dismiss(animated: flag, completion: completion)
}
override open func present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil) {
modalMegaViewController.present(viewControllerToPresent, animated: flag, completion: completion)
}
func viewWillDismiss(animated: Bool) {
}
// MARK: - Keyboard
@objc func keyboardWillShow(notification: Notification) {
guard let nInfo = notification.userInfo as? [String: Any], let value = nInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
keyboardWillShow(frame: value.cgRectValue)
}
@objc func keyboardWillHide(notification: Notification) {
guard let nInfo = notification.userInfo as? [String: Any], let value = nInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
keyboardWillHide(frame: value.cgRectValue)
}
func keyboardWillShow(frame: CGRect) {
let bottom = frame.height - modalMegaViewController.cornerRadius
let sum = bottom + modalMegaViewController.heightConstraint.constant
if sum > maxHeight {
let newHeight = maxHeight - frame.height
set(height: newHeight, animated: false)
}
modalMegaViewController.holderViewBottomConstraint.constant = -bottom
modalMegaViewController.view.layoutIfNeeded()
}
func keyboardWillHide(frame: CGRect) {
modalMegaViewController.holderViewBottomConstraint.constant = modalMegaViewController.cornerRadius
set(height: preferredContentHeight, animated: false)
modalMegaViewController.view.layoutIfNeeded()
}
}
|
//
// Manager.swift
// Alamofire
//
// Created by Alan Jeferson on 09/05/2018.
//
import Foundation
public protocol Manager: Fetcher, Creator, Updater {
}
|
//
// RestaurantTests.swift
// JustEatTestTests
//
// Created by Eugene Pankratov on 25.05.2018.
// Copyright © 2018 Home. All rights reserved.
//
import XCTest
@testable import JustEatTest
class RestaurantTests: XCTestCase {
var validJson: [String: Any] = [:]
var invalidJson: [String: Any] = [:]
override func setUp() {
super.setUp()
if let path = Bundle(for: type(of: self)).path(forResource: "valid-value", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
if let jsonResult = jsonResult as? [String: Any] {
validJson = jsonResult
}
} catch {
// handle error
}
}
if let path = Bundle(for: type(of: self)).path(forResource: "invalid-value", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
if let jsonResult = jsonResult as? [String: Any] {
invalidJson = jsonResult
}
} catch {
// handle error
}
}
}
override func tearDown() {
super.tearDown()
}
func testValidJsonInitialization() {
let restaurant = Restaurant(validJson)
XCTAssert(restaurant.restaurantId == "13620", "Restaurant ID must be parsed correctly as string")
XCTAssert(restaurant.name == "Pizza Plus Pizza", "Restaurant name must be parsed correctly")
XCTAssert(restaurant.address == "2 High Street", "Address must be parsed correctly")
XCTAssert(restaurant.postcode == "SE25 6EP", "Postcode must be parsed correctly")
XCTAssert(restaurant.city == "South Norwood", "must be parsed correctly")
XCTAssert(restaurant.cuisineTypes[0].name == "Pizza", "Cuisine name must be parsed correctly")
XCTAssert(restaurant.cuisineTypes[1].name == "Chicken", "Cuisine name must be parsed correctly")
XCTAssert(restaurant.url == "https://www.just-eat.co.uk/restaurants-pizzapluspizzase25", "URL must be parsed correctly")
XCTAssert(restaurant.logoUrl == "http://d30v2pzvrfyzpo.cloudfront.net/uk/images/restaurants/13620.gif", "Logo URL must be parsed correctly")
guard let date = restaurant.openingTime else {
XCTFail("Date must be present")
return
}
XCTAssert(String(describing: date) == "2018-05-23 10:30:00 +0000", "Date must be parsed correctly \(String(describing: restaurant.openingTime?.description)) <> \(String(describing: date))")
}
func testInvalidJsonInitialization() {
let restaurant = Restaurant(invalidJson)
XCTAssert(restaurant.restaurantId == "0", "Restaurant ID must be parsed correctly as string")
XCTAssert(restaurant.name == "", "Restaurant name must be parsed correctly")
XCTAssert(restaurant.address == nil, "Address must be parsed correctly")
XCTAssert(restaurant.postcode == nil, "Postcode must be parsed correctly")
XCTAssert(restaurant.city == nil, "must be parsed correctly")
XCTAssert(restaurant.cuisineTypes.count == 0, "Cuisine name must be parsed correctly")
}
}
|
//
// JsonUtil.swift
// iOSTraining
//
// Created by Shota Fuchikami on 2021/05/29.
//
import Foundation
struct JsonUtil {
/// Jsonエンコード
/// - Parameter param: リクエストパラメータ
/// - Returns: エンコードしたJson文字列
static func jsonEncode(param: Parameter) -> String? {
do {
let encodedData = try JSONEncoder().encode(param)
return String(data: encodedData, encoding: .utf8)
} catch {
Logging.log(message: "Error: \(error)")
return nil
}
}
/// Jsonデコード
/// - Parameter jsonString: Json文字列
/// - Returns: WeatherData
static func jsonDecode(jsonString: String) -> Result.WeatherData? {
do {
guard let data = jsonString.data(using: .utf8) else { return nil }
let decodedData = try JSONDecoder().decode(Result.WeatherData.self, from: data)
return decodedData
} catch {
Logging.log(message: "Error: \(error)")
return nil
}
}
}
|
//
// Copyright © 2021 Tasuku Tozawa. All rights reserved.
//
import Domain
struct ClipPreviewPageViewCacheState: Equatable {
var clipId: Clip.Identity
var itemId: ClipItem.Identity?
}
|
public class PriorityQueue<T: Equatable> {
private var heap = Array<(Int, T)>()
public init() {}
public func push(priority: Int, item: T) {
heap.append((priority, item))
if heap.count == 1 {
return
}
var current = heap.count - 1
while current > 0 {
let parent = (current - 1) >> 1
if heap[parent].0 <= heap[current].0 {
break
}
(heap[parent], heap[current]) = (heap[current], heap[parent])
current = parent
}
}
public func pop() -> (Int, T) {
(heap[0], heap[heap.count - 1]) = (heap[heap.count - 1], heap[0])
let pop = heap.removeLast()
heapify(0)
return pop
}
public func updatePriority(priority: Int, item: T) {
let index = heap.indexOf { $0.1 == item }
heap.removeAtIndex(index!)
push(priority, item: item)
}
public func contains(item: T) -> Bool {
return heap.contains { $0.1 == item }
}
func heapify(index: Int) {
let left = index * 2 + 1
let right = index * 2 + 2
var smallest = index
if left < heap.count && heap[left].0 < heap[smallest].0 {
smallest = left
}
if right < heap.count && heap[right].0 < heap[smallest].0 {
smallest = right
}
if smallest != index {
(heap[index], heap[smallest]) = (heap[smallest], heap[index])
heapify(smallest)
}
}
public var count: Int {
get {
return heap.count
}
}
public var isEmpty: Bool {
if count == 0 {
return true
}
return false
}
} |
//
// HomeViewController.swift
// BeeHive
//
// Created by HyperDesign-Gehad on 8/2/18.
// Copyright © 2018 HyperDesign-Gehad. All rights reserved.
//
import UIKit
import GoogleMaps
import AlamofireImage
import Alamofire
import MOLH
import SideMenu
class HomeViewController: UIViewController,CLLocationManagerDelegate,GMSMapViewDelegate{
// MARK: - Outlets
@IBOutlet weak var mapView: GMSMapView!
@IBOutlet weak var showUsersButton: UIButton!
@IBOutlet weak var noUsersLabel: UILabel!
@IBOutlet weak var usersTableView: UITableView!
@IBOutlet weak var segmentedView: UISegmentedControl!
@IBOutlet weak var notificationButton: UIBarButtonItem!
// MARK: - Vars
var nearUsersArray = [UserLocation]()
var nearPlacesArray = [Place]()
let locationManager = CLLocationManager()
var timer = Timer()
var longitude = Double()
var latitude = Double()
let date = Date()
// MARK: - ViewLifeCycle
override func viewDidLoad() {
super.viewDidLoad()
setTableDelegateAndDataSource()
configureLocationManagerAndMapView()
setStyle()
}
override func viewDidAppear(_ animated: Bool) {
self.checkStatus()
updateView()
updateNotificationsNumber()
}
override func viewDidDisappear(_ animated: Bool) {
timer.invalidate()
}
// MARK: - Actions
@IBAction func sideMenuTapped(_ sender: Any) {
performSegue(withIdentifier: "sideMenuSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "sideMenuSegue"{
if let destination = segue.destination as? UISideMenuNavigationController{
if MOLHLanguage.currentAppleLanguage() == "en"{
destination.leftSide = true
}
}
}
}
@IBAction func NotificationButtonTapped(_ sender: Any) {
openOtherController(fromStoryboard: "Notification", withIdentifier: "NotificationID") {(controller) in
self.pushViewController(controller: controller)
}
}
@IBAction func messageButtonInNavTapped(_ sender: Any) {
let isActive = self.checkUserActivation()
if isActive{
openOtherController(fromStoryboard: "Messages", withIdentifier: "usersInMessagesID") {(controller) in
self.pushViewController(controller: controller)
}
}
}
@IBAction func searchButtonInNavTapped(_ sender: Any) {
openOtherController(fromStoryboard: "Search", withIdentifier: "SearchID") {(controller) in
self.pushViewController(controller: controller)
}
}
@IBAction func segmentedViewSegmentChanged(_ sender: Any) {
handleReceivedDataFromApi(users: nearUsersArray, places: nearPlacesArray)
}
// MARK: - HelpingMethods
func setStyle(){
self.navigationController?.navigationBar.addShadowAndCornerRadiusToViewWith(shadowHeight: 5, shadowOpacity: 0.25, shadowRadius: 10, cornerRadius: 0)
usersTableView.addShadowAndCornerRadiusToViewWith(shadowHeight: 5, shadowOpacity: 0.28, cornerRadius: 0)
mapView.addShadowAndCornerRadiusToViewWith(shadowHeight: 3, shadowOpacity: 0.28, cornerRadius: 0)
mapView.layer.masksToBounds = false
segmentedView.selectedSegmentIndex = 0
}
func configureLocationManagerAndMapView() {
mapView.delegate = self
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 50
locationManager.startUpdatingLocation()
locationManager.requestAlwaysAuthorization()
}
func updateNotificationsNumber(){
ApiRequests.apisInstance.getNotSeenNotificationsCount { (count, message) in
if let notficationCount = count{
UserDefaults.standard.setNotificationBadge(value: notficationCount)
}else{
self.showAlert(title: "", message: message, closure: nil)
}
}
}
func getNearUsers(latitude : Double , longitude : Double , status : String){
ApiRequests.apisInstance.getNearUsersLocation(latitude: "\(latitude)", longitude: "\(longitude)", status: status) { (usersLocation,places, msg) in
if let locations = usersLocation , let places = places{
self.handleReceivedDataFromApi(users: locations, places: places)
}else{
self.showAlert(title: "", message: msg, closure: nil)
}
if status == "0"{
self.showUsersButton.isEnabled = true
self.showUsersButton.backgroundColor = #colorLiteral(red: 0.937254902, green: 0.6666666667, blue: 0.1333333333, alpha: 1)
}
self.segmentedView.setTitle(NSLocalizedString("Users", comment: "") + " " + "(\(self.nearUsersArray.count))" , forSegmentAt: 0)
self.segmentedView.setTitle(NSLocalizedString("Places", comment: "") + " " + "(\(self.nearPlacesArray.count))" , forSegmentAt: 1)
}
}
func addUsersMarkersInMap(users: [UserLocation]){
for userLocation in users{
if let user = userLocation.user, let lat = userLocation.latitude , let long = userLocation.longitude, let latDouble = Double(lat) , let longDouble = Double(long) , let photo = user.photo{
if user.photo != ""{
self.addMarkerInLocation(latitude: latDouble, longitude: longDouble, imageUrl: photo)
}else{
self.addMarkerInLocation(latitude: latDouble, longitude: longDouble, imageUrl: "person")
}
}
}
}
func addPlacesMarkersInMap(places : [Place]) {
for place in places{
if let lat = place.latitute , let long = place.longitute, let latDouble = Double(lat) , let longDouble = Double(long) , let photo = place.logo{
if place.logo != ""{
self.addMarkerInLocation(latitude: latDouble, longitude: longDouble, imageUrl: photo)
}else{
self.addMarkerInLocation(latitude: latDouble, longitude: longDouble, imageUrl: "Group 357")
}
}
}
}
func handleReceivedDataFromApi(users: [UserLocation],places : [Place]){
self.nearUsersArray.removeAll()
self.nearPlacesArray.removeAll()
if users.count != 0 && places.count != 0{
self.noUsersLabel.isHidden = true
self.addUsersMarkersInMap(users: users)
self.addPlacesMarkersInMap(places: places)
}
else if users.count != 0 && places.count == 0{
if self.segmentedView.selectedSegmentIndex == 0{
self.noUsersLabel.isHidden = true
self.addUsersMarkersInMap(users: users)
}else{
self.noUsersLabel.isHidden = false
}
}
else if users.count == 0 && places.count != 0{
if self.segmentedView.selectedSegmentIndex == 0{
self.noUsersLabel.isHidden = false
}else{
self.noUsersLabel.isHidden = true
self.addPlacesMarkersInMap(places: places)
}
}
else{
self.noUsersLabel.isHidden = false
}
self.nearPlacesArray += places
self.nearUsersArray += users
self.usersTableView.reloadData()
}
func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {
getNearUsers(latitude: position.target.latitude, longitude: position.target.longitude , status: "0")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.mapView.clear()
if let location = locations.last{
let camera = GMSCameraPosition.camera(withLatitude: (location.coordinate.latitude), longitude: (location.coordinate.longitude), zoom: 10.0)
self.mapView?.animate(to: camera)
// let latitude = 30.001681597516885
// let longitude = 31.170505546496543
// let camera = GMSCameraPosition.camera(withLatitude: latitude, longitude: longitude, zoom: 17.0)
// self.mapView?.animate(to: camera)
// let coordinates = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
// let marker = GMSMarker(position: coordinates)
// self.latitude = latitude
// self.longitude = longitude
self.longitude = (location.coordinate.longitude)
self.latitude = (location.coordinate.latitude)
UserDefaults.standard.setUserLatitude(value: self.latitude)
UserDefaults.standard.setUserLongitude(value: self.longitude)
let marker = GMSMarker(position: location.coordinate)
marker.map = self.mapView
marker.icon = #imageLiteral(resourceName: "ic_person_pin_circle_24px")
getNearUsers(latitude: self.latitude, longitude: self.longitude, status: "1")
}
}
func addCurrentUserLocation(){
self.mapView.clear()
let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
let marker = GMSMarker(position: coordinates)
marker.map = self.mapView
marker.icon = #imageLiteral(resourceName: "ic_person_pin_circle_24px")
}
func addMarkerInLocation(latitude : Double , longitude : Double , imageUrl : String){
let coordinates = CLLocationCoordinate2DMake(latitude, longitude)
let marker = GMSMarker(position: coordinates)
marker.map = self.mapView
let markerView = UIImageView(image: #imageLiteral(resourceName: "Location"))
markerView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([markerView.heightAnchor.constraint(equalToConstant: 32),markerView.widthAnchor.constraint(equalToConstant: 31)])
if imageUrl == "person"{
markerView.image = #imageLiteral(resourceName: "person")
}else if imageUrl == "Group 357"{
markerView.image = #imageLiteral(resourceName: "Group 357")
}else{
if let url = URL(string: (imageUrl)){
markerView.af_setImage(withURL: url)
}
}
markerView.addShadowAndCornerRadiusToViewWith(shadowWidth: 0, shadowHeight: 0, shadowOpacity: 0, shadowRadius: 0, cornerRadius: 16)
markerView.clipsToBounds = true
marker.iconView = markerView
// self.mapView.animate(toZoom: 15.0)
}
func updateView() {
// Start timer
timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(self.setTimeLeft), userInfo: nil, repeats: true)
}
@objc func setTimeLeft() {
// Only keep counting if timeEnd is bigger than timeNow
addCurrentUserLocation()
getNearUsers(latitude: latitude, longitude: longitude, status: "1")
}
}
|
//
// MealActionCellModel.swift
// BodyMetrics
//
// Created by Ken Yu on 12/8/15.
// Copyright © 2015 Ken Yu. All rights reserved.
//
import Foundation
import UIKit
public class MealActionKeys {
public static let kAddMealItem = "MEAL_ITEM_ADD"
public static let kRemoveMealItem = "MEAL_ITEM_REMOVE"
public static let kCompleteMeal = "MEAL_COMPLETE"
public static let kUncompleteMeal = "MEAL_UNCOMPLETE"
}
public class MealActionCellModel {
let actionKey: String
let actionTitle: String
public init(_ actionKey: String, actionTitle: String) {
self.actionKey = actionKey
self.actionTitle = actionTitle
}
} |
//
// ParentLoginViewController.swift
// FoodTracker
//
// Created by SWUCOMPUTER on 2017. 11. 17..
// Copyright © 2017년 Apple Inc. All rights reserved.
//
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import GoogleSignIn
import FirebaseMessaging
class ParentLoginViewController: UIViewController, UITextFieldDelegate,GIDSignInUIDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
//displayLabel.text = textField.text
return true
}
@IBOutlet var idTextField: UITextField!
@IBOutlet var pwTextField: UITextField!
@IBOutlet var signInButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
// if Auth.auth().currentUser != nil{
// self.presentLoggedInScreen()
// }
GIDSignIn.sharedInstance().uiDelegate = self //델리게이트
//키값이 맞으면 자동로그인
if UserDefaults.standard.bool(forKey: "USERLOGGEDIN") == true{
//user is already logged in just navigate him to home screen
self.presentLoggedInScreen()
}
}
@IBAction func loginTapped(_ sender: UIButton) {
if let email = idTextField.text, let password = pwTextField.text{
Auth.auth().signIn(withEmail: email, password: password, completion: { (user, error) in
if let firebaseError = error{
print(firebaseError.localizedDescription)
return
}
//각자 아이디별로 토큰이 만들어어진다.
let uid = Auth.auth().currentUser?.uid
let token = InstanceID.instanceID().token()
// let fcmToken=Messaging.messaging().fcmToken
Database.database().reference().child("Parent Users").child(uid!).updateChildValues(["pushToken":token!]) // 내 데이터베이스 계정에 넣어준다. setvalue 는 기존 데이터 다 날라감 update를 해서 덮어씌워줘야 한다.
// print("Firebase registration token: \(fcmToken)")
print("FCM token: \(token ?? "")")
print("success!")
//자동 로그인하기위해 아이디비번이 맞다면 키값 저장
UserDefaults.standard.set(true, forKey: "USERLOGGEDIN")
self.presentLoggedInScreen()
})
}
}
func presentLoggedInScreen(){
let storyboard:UIStoryboard = UIStoryboard(name:"Main", bundle: nil)
let loggedInVC:ParentViewController = storyboard.instantiateViewController(withIdentifier: "ParentViewController") as! ParentViewController
//self.present(loggedInVC, animated: true, completion: nil)
self.navigationController!.pushViewController(loggedInVC, animated: true)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
idTextField.resignFirstResponder()
pwTextField.resignFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func SignInButton(_ sender: Any) {
GIDSignIn.sharedInstance().signIn() //회원가입 신청
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
//
// AccountManager+Extras.swift
// Server
//
// Created by Christopher G Prince on 7/12/20.
//
import Foundation
import Credentials
import ServerAccount
import ServerDropboxAccount
import ServerGoogleAccount
import ServerMicrosoftAccount
import ServerAppleSignInAccount
import ServerFacebookAccount
import CredentialsGoogle
import CredentialsFacebook
import CredentialsDropbox
import CredentialsMicrosoft
import CredentialsAppleSignIn
// import CredentialsSolid
import LoggerAPI
extension AccountManager {
func setupAccounts(credentials: Credentials) -> [ServerRoute] {
var resultRoutes = [ServerRoute]()
if Configuration.server.allowedSignInTypes.Google == true {
let googleCredentials = CredentialsGoogleToken(tokenTimeToLive: Configuration.server.signInTokenTimeToLive)
credentials.register(plugin: googleCredentials)
addAccountType(GoogleCreds.self)
}
if Configuration.server.allowedSignInTypes.Facebook == true {
let facebookCredentials = CredentialsFacebookToken(tokenTimeToLive: Configuration.server.signInTokenTimeToLive)
credentials.register(plugin: facebookCredentials)
addAccountType(FacebookCreds.self)
}
if Configuration.server.allowedSignInTypes.Dropbox == true {
let dropboxCredentials = CredentialsDropboxToken(tokenTimeToLive: Configuration.server.signInTokenTimeToLive)
credentials.register(plugin: dropboxCredentials)
addAccountType(DropboxCreds.self)
}
if Configuration.server.allowedSignInTypes.Microsoft == true {
let microsoftCredentials = CredentialsMicrosoftToken(tokenTimeToLive: Configuration.server.signInTokenTimeToLive)
credentials.register(plugin: microsoftCredentials)
addAccountType(MicrosoftCreds.self)
}
if Configuration.server.allowedSignInTypes.AppleSignIn == true {
if let clientId = Configuration.server.appleSignIn?.clientId {
let controller = AppleServerToServerNotifications(clientId: clientId)
let appleServerToServerRoute:ServerRoute = (NotificationRequest.endpoint, controller.process)
let appleCredentials = CredentialsAppleSignInToken(clientId: clientId, tokenTimeToLive: Configuration.server.signInTokenTimeToLive)
credentials.register(plugin: appleCredentials)
addAccountType(AppleSignInCreds.self)
resultRoutes += [appleServerToServerRoute]
}
else {
Log.warning("No Configuration.server.appleSignIn.clientId; cannot register CredentialsAppleSignInToken")
}
}
// if Configuration.server.allowedSignInTypes.Solid == true {
// let solidCredentials = CredentialsSolid(tokenTimeToLive: Configuration.server.signInTokenTimeToLive)
// credentials.register(plugin: solidCredentials)
// // addAccountType(AppleSignInCreds.self)
// }
// 8/8/17; There needs to be at least one sign-in type configured for the server to do anything. And at least one of these needs to allow owning users. If there can be no owning users, how do you create anything to share? https://github.com/crspybits/SyncServerII/issues/9
if numberAccountTypes == 0 {
Startup.halt("There are no sign-in types configured!")
return []
}
if numberOfOwningAccountTypes == 0 {
Startup.halt("There are no owning sign-in types configured!")
return []
}
return resultRoutes
}
}
|
//
// HomeView.swift
// TicTacToe
//
// Created by Yuan Chang on 6/27/21.
//
import SwiftUI
struct HomeView: View {
@ObservedObject var viewModel: TicTakToeGame
var body: some View {
ZStack {
NavigationView {
VStack (spacing: 10){
Text("TicTacToe")
.font(.largeTitle)
Spacer()
ZStack {
homeButtonsView(viewModel: viewModel)
}
Spacer()
}
}
LaunchScreenAnimation()
}
}
}
struct homeAnimationView: View {
var content: String
var offset: CGFloat
@State var move: Bool = false
var body: some View {
Image(systemName: content)
.font(.largeTitle)
.foregroundColor(.orange)
.opacity(/*@START_MENU_TOKEN@*/0.8/*@END_MENU_TOKEN@*/)
.offset(y:offset)
.rotationEffect(move ? .degrees(0) : .degrees(-360))
.animation(animation)
.onAppear {
move.toggle()
}
}
var animation: Animation {
Animation.linear(duration: 5)
.repeatForever(autoreverses: false)
}
}
struct homeButtonsView: View {
var viewModel: TicTakToeGame
var body: some View {
VStack {
NavigationLink(
destination: GameView(viewModel:viewModel),
label: {
Text("Play")
.foregroundColor(.white)
.font(.headline)
.frame(height: 60)
.frame(maxWidth: 200)
.background(Color.blue)
.cornerRadius(3.0)
})
.padding()
NavigationLink(
destination: /*@START_MENU_TOKEN@*/Text("Destination")/*@END_MENU_TOKEN@*/,
label: {
Text("Game Info")
.foregroundColor(.white)
.font(.headline)
.frame(height: 60)
.frame(maxWidth: 200)
.background(Color.blue)
.cornerRadius(3.0)
})
.padding()
}
}
}
struct HomeView_Previews: PreviewProvider {
static var previews: some View {
let game = TicTakToeGame()
HomeView(viewModel: game)
}
}
|
//
// BranchProvider.swift
// Brizeo
//
// Created by Roman Bayik on 2/12/17.
// Copyright © 2017 Kogi Mobile. All rights reserved.
//
import UIKit
import Branch
import SwiftyUserDefaults
extension DefaultsKeys {
static let sharedUserId = DefaultsKey<String?>("sharedUserId")
static let launchCount = DefaultsKey<Int>("launchCount")
static let userIdToPresent = DefaultsKey<String?>("userIdToPresent")
static let momentIdToPresent = DefaultsKey<String?>("momentIdToPresent")
}
let sharedValuesAreUpdated = "sharedValuesAreUpdated"
//TODO: check invited by link
class BranchProvider: NSObject {
// MARK: - Types
enum Feature: String {
case invite = "invite"
}
enum Channel: String {
case SMS = "SMS"
case facebook = "FacebookInvite"
case social = "social"
case mail = "mail"
}
enum MetadataKeys: String {
case referrerId = "referrer_id"
case userId = "user_id"
case momentId = "moment_id"
case invitedByUserId = "invitedBy_user_id"
case invitedByUserName = "invitedBy_user_name"
case clickedOnLink = "+clicked_branch_link"
case isFirstSession = "+is_first_session"
}
enum BuiltInKeys: String {
case referralBucket = "successful_referral"
case installationBucket = "installation_bucket"
case installAfterInvitation = "InstallAfterInvitation"
}
// MARK: - Class methods
class func logout() {
Branch.getInstance().logout()
}
class func inviteByParams(otherParams: [MetadataKeys: String]?) -> [MetadataKeys: String] {
var params = [
MetadataKeys.invitedByUserId: UserProvider.shared.currentUser!.objectId,
MetadataKeys.invitedByUserName: UserProvider.shared.currentUser!.shortName
]
if let otherParams = otherParams {
for (key, value) in otherParams {
params[key] = value
}
}
return params
}
class func userIdToPresent() -> String? {
return Defaults[.userIdToPresent]
}
class func momentIdToPresent() -> String? {
return Defaults[.momentIdToPresent]
}
//TODO: use this method
class func clearPresentData() {
Defaults[.userIdToPresent] = nil
Defaults[.momentIdToPresent] = nil
}
class func generateInviteURL(forMomentId momentId: String, imageURL: String? = nil, andCallback completionHandler: @escaping (String?) -> Void) {
let params = self.inviteByParams(otherParams: [.momentId: momentId])
generateInviteURL(forParams: params, imageURL: imageURL, andCallback: completionHandler)
}
class func generateInviteURL(forUserId userId: String, imageURL: String? = nil, andCallback completionHandler: @escaping (String?) -> Void) {
let params = self.inviteByParams(otherParams: [.userId: userId])
generateInviteURL(forParams: params, imageURL: imageURL, andCallback: completionHandler)
}
class func generateShareURL(callback completionHandler: @escaping (String?) -> Void) {
let branchUniversalObject: BranchUniversalObject = BranchUniversalObject()
branchUniversalObject.title = LocalizableString.Brizeo.localizedString
branchUniversalObject.contentDescription = LocalizableString.InviteFriends.localizedString
for (key, value) in self.inviteByParams(otherParams: nil) {
branchUniversalObject.addMetadataKey(key.rawValue, value: value)
}
let linkProperties: BranchLinkProperties = BranchLinkProperties()
linkProperties.feature = Feature.invite.rawValue
linkProperties.channel = Channel.social.rawValue
branchUniversalObject.getShortUrl(with: linkProperties, andCallback: { (url, error) -> Void in
completionHandler(url)
})
}
class func setupBranch(with launchOptions: [AnyHashable: Any]?) {
let branch: Branch = Branch.currentInstance
//TODO: remove before release
//#if PRODUCTION
//#else
//branch.setDebug()
//#endif
branch.initSession(launchOptions: launchOptions) { (params, error) in
guard error == nil else {
print("Branch error: \(error?.localizedDescription)")
return
}
if FirstEntranceProvider.shared.isFirstEntrancePassed == false {
return
}
// check params for userId or momentId
print("Setup Branch data: \(params?.description)")
if let userIdToPresent = params?[MetadataKeys.userId.rawValue] as? String {
print("user should present user id = \(userIdToPresent)")
Defaults[.userIdToPresent] = userIdToPresent
} else {
Defaults[.userIdToPresent] = nil
}
if let momentIdToPresent = params?[MetadataKeys.momentId.rawValue] as? String {
print("user should present moment id = \(momentIdToPresent)")
Defaults[.momentIdToPresent] = momentIdToPresent
} else {
Defaults[.momentIdToPresent] = nil
}
Helper.sendNotification(with: sharedValuesAreUpdated, object: nil, dict: nil)
}
}
class func loadReward(handler: @escaping (Int?, Error?) -> Void) {
Branch.currentInstance.loadRewards { (changed, error) -> Void in
let bucket = BuiltInKeys.installationBucket.rawValue
let credits = Branch.currentInstance.getCreditsForBucket(bucket)
guard error != nil else {
handler(nil, error)
return
}
handler(credits, nil)
}
}
class func checkUserReward() {
loadReward { (invitedCount, error) in
guard invitedCount != nil else {
// print("Error: Branch invited person count is nil")
return
}
guard invitedCount! > 0 && (invitedCount! % Configurations.RewardInfo.minInvitedUsers == 0) else {
print("Info: user has invited only \(invitedCount) persons")
return
}
InfoProvider.notifyAdminAboutDownloads(count: invitedCount!, completion: nil)
}
}
class func operateCurrentUserLogin() {
guard let currentUser = UserProvider.shared.currentUser else {
return
}
if !Branch.currentInstance.isUserIdentified() {
Branch.currentInstance.setIdentity("\(currentUser.objectId)-\(currentUser.displayName)") { (params, error) in
guard error == nil else {
print("Error in Branch login: \(error!.localizedDescription)")
return
}
BranchProvider.checkUserReward()
}
}
}
class func operateFirstEntrance(with user: User) {
// identify current user
Branch.currentInstance.setIdentity("\(user.objectId)-\(user.displayName)")
// check referring params
let installParams = Branch.currentInstance.getFirstReferringParams()
let clickedOnLink = Bool((installParams?[MetadataKeys.clickedOnLink.rawValue] as? NSNumber) ?? 0)
let isFirstSession = Bool((installParams?[MetadataKeys.isFirstSession.rawValue] as? NSNumber) ?? 0)
if clickedOnLink && isFirstSession {
Branch.currentInstance.userCompletedAction(BuiltInKeys.installAfterInvitation.rawValue, withState: [String: String]())
// operate who has invited the current user
if let invitedByUserId = installParams?[MetadataKeys.invitedByUserId.rawValue] as? String, let invitedByUserName = installParams?[MetadataKeys.invitedByUserName.rawValue] as? String {
print("User was invited by \(invitedByUserId) - \(invitedByUserName)")
user.invitedByUserId = invitedByUserId
user.invitedByUserName = invitedByUserName
UserProvider.updateUser(user: user, completion: nil)
}
}
}
// MARK: - Private methods
class private func generateInviteURL(forParams params: [MetadataKeys: String], imageURL: String?, andCallback completionHandler: @escaping (String?) -> Void) {
let branchUniversalObject = BranchUniversalObject()
branchUniversalObject.title = LocalizableString.Brizeo.localizedString
branchUniversalObject.contentDescription = LocalizableString.BrizeoInvite.localizedString
branchUniversalObject.imageUrl = imageURL ?? Configurations.Invite.previewURL
for (key, value) in params {
branchUniversalObject.addMetadataKey(key.rawValue, value: value)
}
let linkProperties = BranchLinkProperties()
linkProperties.feature = Feature.invite.rawValue
linkProperties.channel = Channel.SMS.rawValue
branchUniversalObject.getShortUrl(with: linkProperties, andCallback: { (url, error) -> Void in
if let error = error {
print("BranchManager: \(error.localizedDescription)")
}
completionHandler(url)
})
}
}
|
import XCTest
class BottleTest: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func test_1() {
var expected = "99 bottles of beer on the wall, " +
"99 bottles of beer.\n" +
"Take one down and pass it around, " +
"98 bottles of beer on the wall.\n"
XCTAssertEqual(expected, Bottle().getVerse(99))
expected = "3 bottles of beer on the wall, " +
"3 bottles of beer.\n" +
"Take one down and pass it around, " +
"2 bottles of beer on the wall.\n"
XCTAssertEqual(expected, Bottle.getVerse(3))
expected = "2 bottles of beer on the wall, " +
"2 bottles of beer.\n" +
"Take one down and pass it around, " +
"1 bottle of beer on the wall.\n"
XCTAssertEqual(expected, Bottle.getVerse(2))
expected = "1 bottle of beer on the wall, " +
"1 bottle of beer.\n" +
"Take it down and pass it around, " +
"no more bottles of beer on the wall.\n"
XCTAssertEqual(expected, Bottle.getVerse(1))
expected = "No more bottles of beer on the wall, " +
"no more bottles of beer.\n" +
"Go to the store and buy some more, " +
"99 bottles of beer on the wall.\n"
XCTAssertEqual(expected, Bottle.getVerse(0))
expected = "99 bottles of beer on the wall, " +
"99 bottles of beer.\n" +
"Take one down and pass it around, " +
"98 bottles of beer on the wall.\n" +
"\n" +
"98 bottles of beer on the wall, " +
"98 bottles of beer.\n" +
"Take one down and pass it around, " +
"97 bottles of beer on the wall.\n"
XCTAssertEqual(expected, Bottle.getVerses(99, 98))
expected = "2 bottles of beer on the wall, " +
"2 bottles of beer.\n" +
"Take one down and pass it around, " +
"1 bottle of beer on the wall.\n" +
"\n" +
"1 bottle of beer on the wall, " +
"1 bottle of beer.\n" +
"Take it down and pass it around, " +
"no more bottles of beer on the wall.\n" +
"\n" +
"No more bottles of beer on the wall, " +
"no more bottles of beer.\n" +
"Go to the store and buy some more, " +
"99 bottles of beer on the wall.\n"
XCTAssertEqual(expected, Bottle.getVerses(2, 0))
}
} |
public struct BlockSequence<SequenceInput, SequenceOutput>: Block, ExpressibleByArrayLiteral {
var blocks: [AnyBlock]
public init(arrayLiteral elements: AnyBlock...) {
self.blocks = elements
}
public init(_ elements: [AnyBlock] = []) {
self.blocks = elements
}
public mutating func append<B: Block>(_ block: B) {
blocks.append(block.eraseToAnyBlock())
}
public func run(_ input: SequenceInput, _ completion: @escaping (BlockResult<SequenceOutput>) -> Void) {
guard blocks.count > 0 else { return completion(.failed(BlockError.emptyBlockSequence)) }
run(at: 0, input, completion)
}
private func run(at index: Int, _ nextInput: Any, _ completion: @escaping (BlockResult<SequenceOutput>) -> Void) {
if let block = blocks.value(at: index) {
block.run(nextInput) { result in
switch result {
case .done(let nextInput):
run(at: index + 1, nextInput, completion)
case .break(let output):
if let output = output as? SequenceOutput {
completion(.done(output))
} else {
completion(.failed(BlockError.unmatchedOutputTypes))
}
case .failed(let error):
completion(.failed(error))
}
}
} else if let output = nextInput as? SequenceOutput {
completion(.done(output))
} else {
completion(.failed(BlockError.unmatchedOutputTypes))
}
}
}
public protocol BlockState: ExpressibleByNilLiteral {}
public struct StateBlockSequence<State: BlockState, SequenceInput, SequenceOutput>: StateBlock, ExpressibleByArrayLiteral {
public private(set) var _state: AssuredValue<State>
var blocks: [TypeErasedBlock]
public init(arrayLiteral elements: AnyStateBlock...) {
self._state = .init()
self.blocks = elements
}
public init(_ state: State, _ elements: [AnyStateBlock] = []) {
self._state = .init(state)
self.blocks = elements
}
init(arrayLiteral elements: TypeErasedBlock...) {
self._state = .init()
self.blocks = elements
}
init(_ state: State, _ elements: [TypeErasedBlock] = []) {
self._state = .init(state)
self.blocks = elements
}
public mutating func append<B: StateBlock>(_ block: B) {
blocks.append(block.eraseToAnyStateBlock())
}
public func run(_ input: SequenceInput, _ completion: @escaping (BlockResult<SequenceOutput>) -> Void) {
guard blocks.count > 0 else { return completion(.failed(BlockError.emptyBlockSequence)) }
blocks.compactMap { $0 as? AnyStateBlock }.forEach { $0._state.wrappedValue = _state.wrappedValue }
run(at: 0, input, completion)
}
private func run(at index: Int, _ nextInput: Any, _ completion: @escaping (BlockResult<SequenceOutput>) -> Void) {
if let block = blocks.value(at: index).flatMap({ $0 as? AnyStateBlock }) {
block.run(nextInput) { result in
switch result {
case .done(let nextInput):
run(at: index + 1, nextInput, completion)
case .break(let output):
if let output = output as? SequenceOutput {
completion(.done(output))
} else {
completion(.failed(BlockError.unmatchedOutputTypes))
}
case .failed(let error):
completion(.failed(error))
}
}
} else if let block = blocks.value(at: index).flatMap({ $0 as? AnyBlock }) {
block.run(nextInput) { result in
switch result {
case .done(let nextInput):
run(at: index + 1, nextInput, completion)
case .break(let output):
if let output = output as? SequenceOutput {
completion(.done(output))
} else {
completion(.failed(BlockError.unmatchedOutputTypes))
}
case .failed(let error):
completion(.failed(error))
}
}
} else if let output = nextInput as? SequenceOutput {
completion(.done(output))
} else {
completion(.failed(BlockError.unmatchedOutputTypes))
}
}
}
|
import Foundation
import SwaggerKit
enum SpecObjectSchemaSeeds {
// MARK: - Type Properties
static let implicitlyAnyYAML = "{}"
static let anyYAML = "additionalProperties: true"
static let any = SpecObjectSchema(additionalProperties: SpecComponent(value: .any))
static let stringToStringYAML = """
additionalProperties:
\(SpecSchemaSeeds.stringYAML.yamlIndented(level: 1))
maxProperties: 12
minProperties: 3
"""
static let stringToString = SpecObjectSchema(
additionalProperties: SpecComponent(value: SpecSchemaSeeds.string),
minPropertyCount: 3,
maxPropertyCount: 12
)
static let imageSizeYAML = """
additionalProperties: false
properties:
width:
\(SpecSchemaSeeds.integerYAML.yamlIndented(level: 2))
height:
\(SpecSchemaSeeds.integerYAML.yamlIndented(level: 2))
required:
- width
- height
"""
static let imageSize = SpecObjectSchema(
properties: [
"width": SpecComponent(value: SpecSchemaSeeds.integer),
"height": SpecComponent(value: SpecSchemaSeeds.integer)
],
requiredProperties: ["width", "height"]
)
static let imageYAML = """
additionalProperties: false
properties:
size:
\(SpecSchemaSeeds.imageSizeYAML.yamlIndented(level: 2))
required:
- size
"""
static let image = SpecObjectSchema(
properties: ["size": SpecComponent(value: SpecSchemaSeeds.imageSize)],
requiredProperties: ["size"]
)
static let videoYAML = """
additionalProperties: false
properties:
duration:
\(SpecSchemaSeeds.videoDurationYAML.yamlIndented(level: 2))
required:
- duration
"""
static let video = SpecObjectSchema(
properties: ["duration": SpecComponent(value: SpecSchemaSeeds.videoDuration)],
requiredProperties: ["duration"]
)
static let mediaYAML = """
additionalProperties: false
properties:
mediaType:
\(SpecSchemaSeeds.mediaTypeYAML.yamlIndented(level: 2))
url:
\(SpecSchemaSeeds.stringYAML.yamlIndented(level: 2))
required:
- mediaType
- url
discriminator:
\(SpecSchemaDiscriminatorSeeds.mediaTypeYAML.yamlIndented(level: 1))
"""
static let media = SpecObjectSchema(
properties: [
"mediaType": SpecComponent(value: SpecSchemaSeeds.mediaType),
"url": SpecComponent(value: SpecSchemaSeeds.string)
],
requiredProperties: ["mediaType", "url"],
discriminator: SpecSchemaDiscriminatorSeeds.mediaType
)
}
|
//
// ItermView.swift
// Rhythm
//
// Created by 陈宝 on 2020/1/3.
// Copyright © 2020 chenbao. All rights reserved.
//
import CoreData
//import nav
import SwiftUI
struct ItermView: View {
let objectId: NSManagedObjectID
let contentView: ContentView
// 计算属性可以及时的显示变更
private var entity: Iterm {
self.contentView.moc.object(with: self.objectId) as! Iterm
}
var body: some View {
VStack {
self.header
self.conment
}
.contextMenu { self.menu }
.listRowBackground(self.entity.isWorking ? Color.green : Color.clear) // 这一行放在 .contextMenu 下面就会起作用, 放到上面就不行, 不知道为啥?
}
@Environment(\.colorScheme) var colorscheme: ColorScheme
}
extension ItermView {
// MARK: - some Views
var headerFont: Font {
#if os(iOS)
return Font.title
#else
return Font.body
#endif
}
var header: some View {
HStack(alignment: .center) {
self.heart
Text("\(self.entity.title ?? "")")
.foregroundColor(self.colorscheme == .dark ? Color.white : Color.black)
Spacer()
self.startAndPause
}
.frame(maxWidth: .infinity, alignment: .center)
.font(self.headerFont)
}
var conment: some View {
Group {
if self.entity.conment != nil {
HStack {
Text("\(self.entity.conment ?? "")")
.font(.body)
.foregroundColor(.gray)
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
var doings: some View {
ForEach(self.entity.doing?.array as! [Doing], id: \Doing.start) { (d: Doing) in
VStack {
Text(d.start?.description ?? "none")
d.end?.description ?? "end none"
}
}
}
var heart: some View {
Image(systemName: self.entity.isDoone ? "heart.fill" : "heart")
.foregroundColor(self.entity.isDoone ? .red : .blue)
.onTapGesture {
self.entity.isDoone.toggle()
if self.entity.isDoone {
self.entity.doneDate = Date()
} else {
self.entity.doneDate = nil
}
do {
try Iterm.shared.save()
} catch {
whenDebugCatching(err: error) {
fatalError()
}
}
}
}
var startAndPause: some View {
Group {
if !self.entity.isDoone {
Image(systemName: self.entity.isWorking ? "pause.fill" : "play.fill")
.onTapGesture {
self.entity.doingToggle(context: self.contentView.moc)
}
} else {
self.entity.总耗时.formated
.foregroundColor(.gray)
}
}
}
}
extension ItermView {
// MARK: - context Menu
var menu: some View {
Group {
Button("删除") {
Iterm.shared.delete(self.entity)
do {
try Iterm.shared.save()
} catch {
whenDebugCatching(err: error) {
fatalError()
}
}
}
}
}
}
struct adfadsfadsf: View {
@State private var selection: Int? = nil
var body: some View {
List {
ForEach(0...199, id: \Int.self) { i in
Text(i.description)
.background(
NavigationLink(destination: Text(i.description),
// tag: i,
// selection: self.$selection,
label: { EmptyView() })
)
}
}
}
}
// func 有(paramater: Int) { print(paramater) }
//
// func 没有(_ paramater: Int) { print(paramater) }
//
// func 调用() {
// 没有(1)
// 有(paramater: 1)
// }
func whenDebugCatching(message: String = "", err: Error, f: () -> ()) {
#if DEBUG
print("\n🔰🔰🔰🔰🔰 ERROR 🔰🔰🔰🔰🔰:\n message: \(message)\n \(err)\n")
f()
fatalError()
#endif
}
|
//
// HikeTrail.swift
// hikeVA
//
// Created by Felipe Samuel Rodriguez on 12/11/16.
// Copyright © 2016 Technigraphic. All rights reserved.
//
import Foundation
import Foundation
class HikeTrail {
var HikeLocation:String = ""
var HId:String = ""
var HikeName:String = ""
var HikeImageURL:String = ""
var HikeLength:String = ""
var HikeTime:String = ""
var HikeElevation:String = ""
var HikeDifficulty:String = ""
var HikeStreams:String = ""
var HikeViews:String = ""
var HikeSolitude:String = ""
var HikeGoogleMaps:String = ""
var UURL:String = ""
init(location:String, hid:String, name:String, imageurl:String, length:String, time:String, elevation:String, difficulty:String, streams:String, views:String, solitude:String, map:String, uurl:String) {
self.HId = hid
self.HikeLocation = location
self.HikeName = name
self.HikeImageURL = imageurl
self.HikeLength = length
self.HikeTime = time
self.HikeElevation = elevation
self.HikeDifficulty = difficulty
self.HikeStreams = streams
self.HikeViews = views
self.HikeSolitude = solitude
self.HikeGoogleMaps = map
self.UURL = uurl
}
}
|
//
// Coordinator.swift
// Crepatura
//
// Created by Yaroslav Pasternak on 14/04/2019.
// Copyright © 2019 Thorax. All rights reserved.
//
import UIKit
protocol Coordinator: AnyObject {
var childCoordinators: [Coordinator] { get set }
var navigationController: UINavigationController { get set }
func start()
}
|
/*
public protocol IteratorProtocol {
associatedtype Element
public mutating func next() -> Self.Element?
}
*/
/*
public protocol Sequence {
associatedtype Iterator : IteratorProtocol
func makeIterator() -> Self.Iterator
}
*/
let array = [1, 2, 3, 4]
var iterator = array.makeIterator()
while let element = iterator.next() {
print(element)
}
|
//
// SpeakerProfileVC.swift
// Elshams
//
// Created by mac on 12/5/18.
// Copyright © 2018 mac. All rights reserved.
//
import UIKit
import SafariServices
import MessageUI
//import AlamofireImage
import Alamofire
import SwiftyJSON
class SpeakerProfileVC: UIViewController {
var singleItem:Speakers?
var speakerSessionsList = Array<SpeakerSeasions>()
var sessionCounterIndex : Int = 0
var sessionFirstConstatContraint : CGFloat?
@IBOutlet weak var nextBackSessionsContainer: UIView!
@IBOutlet weak var nextBtnSession: UIButton!
@IBOutlet weak var backBtnSession: UIButton!
@IBOutlet weak var nextImgSession: UIImageView!
@IBOutlet weak var backImgSession: UIImageView!
@IBOutlet weak var informatonViewContainer: UIView!
@IBOutlet weak var aboutTopConstraints: NSLayoutConstraint!
@IBOutlet weak var aboutViewContainer: UIView!
@IBOutlet weak var sessionViewContainer: UIView!
@IBOutlet weak var sessionTopConstraints: NSLayoutConstraint!
@IBOutlet weak var speakerName: UILabel!
@IBOutlet weak var speakerEmail: UILabel!
@IBOutlet weak var aboutSpeaker: UITextView!
// @IBOutlet weak var speakerSecSName: UILabel!
@IBOutlet weak var speakerFSLocation: UILabel!
@IBOutlet weak var connectColor: UIView!
// @IBOutlet weak var speakerSecSTime: UILabel!
// @IBOutlet weak var speakerSecSLocation: UILabel!
@IBOutlet weak var speakerFSTime: UILabel!
@IBOutlet weak var speakerFSName: UILabel!
// @IBOutlet weak var speakerFacebook: UILabel!
@IBOutlet weak var speakerWebsite: UILabel!
@IBOutlet weak var speakerPhone: UILabel!
@IBOutlet weak var activeNow: UILabel!
@IBOutlet weak var speakerJobTitle: UILabel!
@IBOutlet weak var speakerProfileImg: UIImageView!
var phoneNumber:String?
var email:String?
var faceBookLinkEdinNow:String?
override func viewDidLoad() {
super.viewDidLoad()
speakerProfileImg.layer.cornerRadius = speakerProfileImg.frame.width / 2
speakerProfileImg.clipsToBounds = true
connectColor.layer.cornerRadius = connectColor.frame.width / 2
connectColor.clipsToBounds = true
speakerName.text = singleItem?.name
speakerJobTitle.text = singleItem?.jobTitle
speakerPhone.isHidden = true
sessionFirstConstatContraint = sessionTopConstraints.constant
if singleItem?.speakerImageUrl != nil {
Helper.loadImagesKingFisher(imgUrl: (singleItem?.speakerImageUrl)!, ImgView: speakerProfileImg)
}
phoneNumber = singleItem?.contectInforamtion!["phone"] as! String
email = singleItem?.contectInforamtion!["Email"] as! String
faceBookLinkEdinNow = singleItem?.contectInforamtion!["linkedin"] as! String
speakerPhone.text = phoneNumber
if faceBookLinkEdinNow == nil || faceBookLinkEdinNow == ""{
// speakerFacebook.text = "Na"
}else {
// speakerFacebook.text = faceBookLinkEdinNow
}
speakerEmail.text = email
speakerWebsite.text = faceBookLinkEdinNow
if singleItem?.about == nil || singleItem?.about == "" || singleItem?.about == "About"{
noAboutMethod()
} else {
aboutViewContainer.isHidden = false
aboutSpeaker.text = singleItem?.about
}
sessionViewContainer.isHidden = true
connectColor.isHidden = true
connectColor.backgroundColor = UIColor.green
activeNow.isHidden = true
let tapCall = UITapGestureRecognizer(target: self, action: #selector(SpeakerProfileVC.tapCallFunc))
speakerPhone.isUserInteractionEnabled = true
speakerPhone.addGestureRecognizer(tapCall)
let tapLink = UITapGestureRecognizer(target: self, action: #selector(SpeakerProfileVC.tapOpenLinkFunc))
speakerWebsite.isUserInteractionEnabled = true
speakerWebsite.addGestureRecognizer(tapLink)
let tapMail = UITapGestureRecognizer(target: self, action: #selector(SpeakerProfileVC.tapMailFunc))
speakerEmail.isUserInteractionEnabled = true
speakerEmail.addGestureRecognizer(tapMail)
}
override func viewWillAppear(_ animated: Bool) {
UIApplication.shared.isStatusBarHidden = false
loadAllSpeakerData()
}
func loadAllSpeakerData() {
Service.getService(url: "\(URLs.getSpeakerDetail)/\((singleItem?.speaker_id)!)") {
(response) in
print(response)
let json = JSON(response)
let result = json
if !(result.isEmpty){
let speaker_ID = result["ID"].string
let speaker_Name = result["name"].string
let speaker_JobTitle = result["jobTitle"].string
let speaker_CompanyName = result["companyName"].string
let speaker_ImageUrl = result["imageUrl"].string
let speaker_About = result["about"].string
let speaker_ContectInforamtion = result["ContectInforamtion"].dictionaryObject
let speaker_Email = result["ContectInforamtion"]["Email"].string
let speaker_Linkedin = result["ContectInforamtion"]["linkedin"].string
let speaker_Phone = result["ContectInforamtion"]["phone"].string
let contect = ["Email": "","linkedin": "","phone": ""]
let speaker_Sessions = result["Seassions"]
var iDNotNull = true
var index = 0
while iDNotNull {
let session_ID = speaker_Sessions[index]["ID"].string
if session_ID == nil || session_ID?.trimmed == "" || session_ID == "null" || session_ID == "nil" {
iDNotNull = false
break
}
let session_Title = speaker_Sessions[index]["Title"].string
let session_Location = speaker_Sessions[index]["Location"].string
let session_Time = speaker_Sessions[index]["Time"].string
self.speakerSessionsList.append(SpeakerSeasions(Session_id: session_ID ?? "", Session_Title: session_Title ?? "", Session_Location: session_Location ?? "", Session_Time: session_Time ?? ""))
index = index + 1
}
self.speakerPhone.text = speaker_Phone
self.speakerEmail.text = speaker_Email
self.speakerWebsite.text = speaker_Linkedin
if speaker_About == nil || speaker_About == "" {
//self.noAboutMethod()
print("no about")
} else {
self.showAboutMethod()
self.aboutSpeaker.text = speaker_About?.htmlToString
}
if !(self.speakerSessionsList.isEmpty) {
// for ind in 0..<self.speakerSessionsList.count{
//if ind == 0 {
self.sessionViewContainer.isHidden = false
if self.speakerSessionsList.count == 1{
self.nextBackSessionsContainer.isHidden = true
}
else if self.speakerSessionsList.count == 2{
self.nextBackSessionsContainer.isHidden = false
self.backBtnSession.isHidden = true
self.backImgSession.isHidden = true
}
else {
self.nextBackSessionsContainer.isHidden = false
self.backBtnSession.isHidden = true
self.backImgSession.isHidden = true
}
self.speakerFSName.text = self.speakerSessionsList[0].session_Title
self.speakerFSTime.text = self.speakerSessionsList[0].session_Time
self.speakerFSLocation.text = self.speakerSessionsList[0].session_Location
} else {
// session view hidden
self.noSessionsMethod()
}
}
else {
let alert = UIAlertController(title: "No Data", message: "No Data found till now", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
@objc func tapFacebookLinkFunc(sender:UIGestureRecognizer) {
if let openURL = URL(string: "twitter://"){
let canOpen = UIApplication.shared.canOpenURL(openURL)
print("\(canOpen)")
}
// let apppName = "Facebook"
//let apppName = "fb://feed"
let apppName = "fb"
let appScheme = "\(apppName)://profile"
let appSchemeUrl = URL(string: appScheme)
if UIApplication.shared.canOpenURL(appSchemeUrl! as URL) {
UIApplication.shared.open(appSchemeUrl!, options: [:], completionHandler: nil)
}
else {
let alert = UIAlertController(title: "\(apppName) Error...", message: "the app named \(apppName) not found,please install it fia app store.", preferredStyle: .alert )
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
@objc func tapMailFunc(sender:UIGestureRecognizer) {
guard MFMailComposeViewController.canSendMail()
else {
return
}
let compser = MFMailComposeViewController()
compser.mailComposeDelegate = self
compser.setToRecipients([(email)!])
compser.setSubject("Event User Want to connect")
compser.setMessageBody("", isHTML: false)
present(compser, animated: true, completion: nil)
}
@objc func tapCallFunc(sender:UIGestureRecognizer) {
if phoneNumber != nil {
PhoneCall.makeCall(PhoneNumber: (phoneNumber)!)
guard let numberString = phoneNumber,let url = URL(string: "telprompt://\(numberString)")
else {
return
}
UIApplication.shared.open(url)
}
}
@IBAction func backSessionMethod(_ sender: Any) {
if sessionCounterIndex > 0 {
print(sessionCounterIndex)
sessionCounterIndex = sessionCounterIndex - 1
nextBtnSession.isHidden = false
nextImgSession.isHidden = false
if sessionCounterIndex == 0 {
backImgSession.isHidden = true
backBtnSession.isHidden = true
}
} else if sessionCounterIndex == 0 {
backImgSession.isHidden = true
backBtnSession.isHidden = true
nextBtnSession.isHidden = false
nextImgSession.isHidden = false
}
if !(speakerSessionsList.isEmpty) { // != nil
speakerFSName.text = speakerSessionsList[sessionCounterIndex].session_Title
speakerFSTime.text = speakerSessionsList[sessionCounterIndex].session_Time
speakerFSLocation.text = speakerSessionsList[sessionCounterIndex].session_Location
}
}
@IBAction func nextSessionMethod(_ sender: Any) {
if sessionCounterIndex < speakerSessionsList.count - 1 {
print(sessionCounterIndex)
sessionCounterIndex = sessionCounterIndex + 1
backImgSession.isHidden = false
backBtnSession.isHidden = false
if sessionCounterIndex == speakerSessionsList.count - 1 {
nextBtnSession.isHidden = true
nextImgSession.isHidden = true
}
} else if sessionCounterIndex == speakerSessionsList.count - 1 {
backImgSession.isHidden = false
backBtnSession.isHidden = false
nextBtnSession.isHidden = true
nextImgSession.isHidden = true
}
if !(speakerSessionsList.isEmpty) { // != nil
speakerFSName.text = speakerSessionsList[sessionCounterIndex].session_Title
speakerFSTime.text = speakerSessionsList[sessionCounterIndex].session_Time
speakerFSLocation.text = speakerSessionsList[sessionCounterIndex].session_Location
}
}
//MARK:- Shw/HideContainers
func noAboutMethod() {
aboutViewContainer.isHidden = true
sessionTopConstraints.constant = -(aboutViewContainer.frame.height) + (sessionTopConstraints.constant)
}
func showAboutMethod() {
aboutViewContainer.isHidden = false
sessionTopConstraints.constant = sessionFirstConstatContraint!
}
func noSessionsMethod() {
sessionViewContainer.isHidden = true
}
@objc func tapOpenLinkFunc(sender:UIGestureRecognizer) {
guard let url = URL(string: (speakerWebsite.text)!)
else {
return
}
let safariVC = SFSafariViewController(url: url)
present(safariVC, animated: true, completion: nil)
}
}
extension SpeakerProfileVC : MFMailComposeViewControllerDelegate {
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
if let _ = error {
//show error alert
controller.dismiss(animated: true, completion: nil)
}
switch result {
case .cancelled:
print("cancelled")
case .failed:
print("failed")
case .saved:
print("saved")
case .sent:
print("sent")
}
controller.dismiss(animated: true, completion: nil)
}
}
|
//
// FetchChannelAction.swift
// Mitter
//
// Created by Rahul Chowdhury on 30/11/18.
// Copyright © 2018 Chronosphere Technologies Pvt. Ltd. All rights reserved.
//
import Foundation
import RxSwift
class FetchChannelsAction: UniParamAction {
private let channelRepository: ChannelRepository
init(channelRepository: ChannelRepository) {
self.channelRepository = channelRepository
}
func execute(t: [String]) -> PrimitiveSequence<SingleTrait, [Channel]> {
return channelRepository.fetchChannels(channelIds: t)
}
}
|
//
// favorites.swift
// Remote
//
// Created by oleg on 3/5/19.
// Copyright © 2019 DePaul University. All rights reserved.
//
import UIKit
class favorites: UIViewController {
var data = Data()
@IBOutlet weak var button_number: UISegmentedControl!
@IBOutlet weak var label: UITextField!
@IBOutlet weak var channel: UILabel!
@IBOutlet weak var cursor: UISegmentedControl!
var x : Int = 0
override func viewDidLoad() {
super.viewDidLoad()
x = Int(channel.text!)!
}
@IBAction func inc_dec(_ sender: UISegmentedControl) {
if (sender.selectedSegmentIndex == 0){
x = x - 1
} else {
x = x + 1
}
channel.text = String(x)
sender.selectedSegmentIndex = -1
}
@IBAction func save(_ sender: UIButton) {
// pop up to ask are you sure then save new fav channel
if let x = label.text, let y = channel.text{
// checking label containing digits
let decimalCharacters = CharacterSet.decimalDigits
let decimalRange = x.rangeOfCharacter(from: decimalCharacters)
if (x.count < 5 && x.count > 0) && (y.count < 3 && y.count > 0 && y != "00") && decimalRange == nil{
data.setFavTag(x: Int(channel.text!)!)
data.setFavIndex(x: button_number.selectedSegmentIndex)
data.setFavLabel(x: label.text!)
self.x = 0
// popup about saving
let title = "Are you sure you would like to proceed?"
let message = "You wanted to save channel \(self.channel.text!) as \(self.label.text!)"
let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "Go Back", style: .destructive) { action in
let cancelController = UIAlertController(title: "No Problem", message: "Everything is saved", preferredStyle: .alert)
let okayAction = UIAlertAction(title: "Okay", style: .default, handler: nil)
cancelController.addAction(okayAction)
self.present(cancelController, animated: true, completion: nil)
}
let confirmAction = UIAlertAction(title: "Confirm", style: .default) { action in
let okayController = UIAlertController(title: "Okay", message: "The channel \(self.channel.text!) is saved as \( self.label.text!) in your favorites", preferredStyle: .alert)
let okayAction = UIAlertAction(title: "Okay", style: .default, handler: nil)
okayController.addAction(okayAction)
self.present(okayController, animated: true, completion: nil)
self.label.text = ""
self.channel.text = ""
self.x = 0
}
alertController.addAction(cancelAction)
alertController.addAction(confirmAction)
present(alertController, animated: true, completion: nil)
} else {
// return popup
let alertController = UIAlertController(title: "Illegal Inputs", message: "The Channel should be between 0-99 and its label should be 1-4 letters long. Please try again", preferredStyle: .alert)
let okayAction = UIAlertAction(title: "Okay", style: .default, handler: nil)
alertController.addAction(okayAction)
self.present(alertController, animated: true, completion: nil)
self.label.text = ""
self.channel.text = ""
self.x = 0
}
}
}
@IBAction func cancel(_ sender: UIButton) {
// pop up to ask are you sure
let title = "Are you sure you would like to cancel?"
let message = "You wanted to save channel \(String(describing: self.channel.text)) as \(String(describing: self.label.text))"
let alertController = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "Go Back", style: .destructive) { action in
let cancelController = UIAlertController(title: "No Problem", message: "Everything is saved", preferredStyle: .alert)
let okayAction = UIAlertAction(title: "Okay", style: .default, handler: nil)
cancelController.addAction(okayAction)
self.present(cancelController, animated: true, completion: nil)
}
let confirmAction = UIAlertAction(title: "Confirm", style: .default) { action in
let okayController = UIAlertController(title: "Okay", message: "Try again", preferredStyle: .alert)
let okayAction = UIAlertAction(title: "Okay", style: .default, handler: nil)
okayController.addAction(okayAction)
self.present(okayController, animated: true, completion: nil)
self.label.text = ""
self.channel.text = ""
}
alertController.addAction(cancelAction)
alertController.addAction(confirmAction)
present(alertController, animated: true, completion: nil)
}
}
|
//
// TwitterClient.swift
// Twitter
//
// Created by Liang Rui on 10/26/16.
// Copyright © 2016 Etcetera. All rights reserved.
//
import BDBOAuth1Manager
import UIKit
let twitterConsumerKey = "03KzAjYeVI68G9kZKXHIoXvSh"
let twitterConsumerSecret = "csKH6yuZnuSBX6dCcIN6SVPjzUIIya9kHg1ToXspGT9HuXn9SG"
let twitterBaseURL = URL(string: "https://api.twitter.com")
class TwitterClient: BDBOAuth1SessionManager {
class var sharedInstance: TwitterClient {
struct Static {
static let instance = TwitterClient(baseURL: twitterBaseURL, consumerKey: twitterConsumerKey, consumerSecret: twitterConsumerSecret)
}
return Static.instance!
}
var loginSuccess: (() -> ())?
var loginFailure: ((NSError) -> ())?
func logout() {
User.currentUser = nil
deauthorize()
let notificationName = NSNotification.Name("UserDidLogout")
NotificationCenter.default.post(name: notificationName, object: nil)
}
func login(success: @escaping () -> (), failure: @escaping (NSError) -> () ) {
loginSuccess = success
loginFailure = failure
TwitterClient.sharedInstance.requestSerializer.removeAccessToken()
TwitterClient.sharedInstance.fetchRequestToken(withPath: "oauth/request_token", method: "GET", callbackURL: URL(string: "mstwitterdemo://oauth"), scope: nil, success:
{ (requestToken:BDBOAuth1Credential?) -> Void in
if (requestToken != nil) {
let myToken = requestToken!
let authURL = URL(string:"https://api.twitter.com/oauth/authorize?oauth_token=\(myToken.token!)")
UIApplication.shared.open(authURL!, options: [:], completionHandler: {
(completed: Bool) -> Void in
if (completed) {
print ("Login Authorization Completed")
} else {
print ("Login Authorization Not Completed")
}
})
}
},
failure: { (myError: Error?) -> Void in
self.loginFailure?(myError as! NSError)
print ("Login Authorization: Failed to get request token \(myError?.localizedDescription)")
})
}
func handleOpenUrl(url: URL) {
let requestToken = BDBOAuth1Credential(queryString: url.query)
let client = TwitterClient.sharedInstance
client.fetchAccessToken(withPath: "oauth/access_token", method: "POST", requestToken: requestToken, success: { (accessToken : BDBOAuth1Credential?) in
print("handleOpenUrl: Got access token.")
client.requestSerializer.saveAccessToken(accessToken)
self.currentAccount(success: { (user: User) in
print("Current account success")
User.currentUser = user
self.loginSuccess?()
}, failure: { (error: NSError) in
print("Current account failure")
self.loginFailure?(error)
})
},
failure: { (error : Error?) in
print("handleOpenUrl: Failed to receive access token");
self.loginFailure?(error as! NSError)
})
}
func currentAccount(success: @escaping (User) -> (), failure: @escaping (NSError) -> ()) {
TwitterClient.sharedInstance.get("1.1/account/verify_credentials.json", parameters: nil, progress: nil,success: { (operation, response) in
let userDictionary = response as! NSDictionary
let user = User(dictionary: userDictionary)
print ("The user dict is \(response)")
/*
print ("User's name is \(user.name)\n")
print ("User's screen name is \(user.screenName)\n")
print ("User's profile pic url is \(user.profileUrl)")
print ("User's description is \(user.tagLine)\n")
*/
success(user)
},
failure: { (response, error) in
print ("currentAccount: Error gettting user.")
failure(error as NSError)
})
}
func postTweet(params: NSDictionary?, completion: @escaping (NSError?) -> () ){
TwitterClient.sharedInstance.post("1.1/statuses/update.json", parameters: params, progress: nil, success: { (error, response) in
print ("postTweet: Posted tweet!")
completion(nil)
}) { (session, error) in
print ("postTweet: Error tweeting \(error.localizedDescription)")
completion(nil)
}
}
func favorite(id: Int, params: NSDictionary?, completion: @escaping (Error?) -> () ){
post("1.1/favorites/create.json?id=\(id)", parameters: params, progress: nil, success:
{ (operation, response) -> Void in
print("favorite: completed")
completion(nil)
}, failure:
{ (operation, error) -> Void in
print("favorite: error")
completion(error)
}
)}
func retweet(id: Int, params: NSDictionary?, completion: @escaping (Error?) -> () ) {
post("1.1/statuses/retweet/\(id).json", parameters: params, progress:
{ (progress) in
print ("reteet: Progress")
}, success:
{ (session, response) in
print ("retweet: Successful")
completion(nil)
}) { (session, error) in
print ("retweet: Error \(error.localizedDescription)")
completion(error)
}
}
func userTimeline(id: Int, success: @escaping ([Tweet]) -> (), failure: @escaping (NSError) -> ()) {
let params = NSMutableDictionary()
params["user_id"] = id
get("1.1/statuses/user_timeline.json", parameters: params, progress: nil, success: { (operation, response) in
let tweetDictionaries = response as! [NSDictionary]
let tweets = Tweet.tweetsWithArray(dictionaries: tweetDictionaries)
/*for tweet in tweets {
print("\(tweet.text!)\n")
}*/
success(tweets)
},
failure: { (response, error) in
print ("userTimeline: Error getting home timeline. \(error.localizedDescription)")
failure(error as NSError)
})
}
func homeTimeline(success: @escaping ([Tweet]) -> (), failure: @escaping (NSError) -> ()) {
get("1.1/statuses/home_timeline.json", parameters: nil, progress: nil, success: { (operation, response) in
let tweetDictionaries = response as! [NSDictionary]
let tweets = Tweet.tweetsWithArray(dictionaries: tweetDictionaries)
for tweet in tweets {
print("\(tweet.text!)\n")
}
success(tweets)
},
failure: { (response, error) in
print ("Error getting home timeline.")
failure(error as NSError)
})
}
func mentionsTimeline(success: @escaping ([Tweet]) -> (), failure: @escaping (NSError) -> ()) {
get("1.1/statuses/mentions_timeline.json", parameters: nil, progress: nil, success: { (operation, response) in
let tweetDictionaries = response as! [NSDictionary]
let tweets = Tweet.tweetsWithArray(dictionaries: tweetDictionaries)
for tweet in tweets {
print("\(tweet.text!)\n")
}
success(tweets)
},
failure: { (response, error) in
print ("Error getting home timeline.")
failure(error as NSError)
})
}
}
|
import SwiftUI
import Arweave
struct WalletsView: View {
@State private var showingAlert = false
@State private var showingFilePicker = false
@ObservedObject var model: WalletPersistence
var body: some View {
NavigationView {
listView
.navigationTitle("Wallets")
.toolbar {
Button(action: {
showingFilePicker.toggle()
}) {
Image(systemName: "doc.fill.badge.plus")
.font(.title2)
}
.accessibilityLabel("Import wallet")
.foregroundStyle(.orange, .tint)
}
}
.sheet(isPresented: $showingFilePicker) {
DocumentPicker() { data in
do {
let wallet = try Wallet(jwkFileData: data)
try model.add(wallet)
} catch {
showingAlert = true
}
}
}
.alert("Unable to create wallet for the specified keyfile.",
isPresented: $showingAlert) {
Button("OK", role: .cancel) { }
}
}
@ViewBuilder
var listView: some View {
if model.wallets.isEmpty {
placeholder
} else {
walletList
}
}
var placeholder: some View {
Text("Import a wallet to get started.").italic()
}
var walletList: some View {
List {
ForEach(model.wallets, id: \.self) { wallet in
Text(wallet.id)
}
.onDelete(perform: delete)
}
}
func delete(at offsets: IndexSet) {
for index in offsets {
let wallet = model.wallets[index]
try? model.remove(wallet)
}
}
}
struct WalletsView_Previews: PreviewProvider {
static var previews: some View {
WalletsView(model: WalletPersistence())
}
}
|
// @copyright German Autolabs Assignment
import UIKit
class WeatherViewController: UIViewController, WeatherViewInput {
var output: WeatherViewOutput!
@IBOutlet weak var recordButton: UIButton!
@IBOutlet weak var weatherView: WeatherView!
@IBOutlet weak var hudView: UIView!
// MARK: - Actions
@IBAction func onRecordBtn(_ sender: UIButton) {
output.didTapOnRecord()
}
// MARK: - WeatherViewInput
func updateRecordButton(title: String) {
recordButton.setTitle(title, for: .normal)
}
func display(weather: WeatherViewModel) {
weatherView.display(model: weather)
}
func displayHUD() {
hudView.isHidden = false
}
func hideHUD() {
hudView.isHidden = true
}
func display(message: String) {
let alert = UIAlertController(title: nil,
message: message,
preferredStyle: .alert)
let okAction = UIAlertAction(title: NSLocalizedString("Dismiss", comment: ""),
style: .default) { _ in
alert.dismiss(animated: true, completion: nil)
}
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
}
|
//
// GameScene.swift
// Game Remake
//
// Created by Hai on 8/29/16.
// Copyright (c) 2016 Hai. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
// Node
var plane:SKSpriteNode!
var bullets : [SKSpriteNode] = []
var enemy:SKSpriteNode!
var enemys : [SKSpriteNode] = []
var enemyBullets : [SKSpriteNode] = []
// Counter
var bullteIntervalCount = 0
var enemyIntervalCount = 0
// Time
var lastUpdateTime : NSTimeInterval = -1
override func didMoveToView(view: SKView) {
addBackground()
addPlane()
addEnemys()
}
func addBackground() {
// 1
let background = SKSpriteNode(imageNamed: "background.png")
//2
background.anchorPoint = CGPointZero
background.position = CGPointZero
//3
addChild(background)
}
func addPlane() {
//1
plane = SKSpriteNode(imageNamed: "plane2.png")
//2
//plane.anchorPoint = CGPointMake(0.5, 0.5)
plane.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height/2)
// 3
let shot = SKAction.runBlock {
self.addBullets()
}
let periodShot = SKAction.sequence([shot, SKAction.waitForDuration(0.3)])
let shotForever = SKAction.repeatActionForever(periodShot)
//3
plane.runAction(shotForever)
addChild(plane)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
//print ("touchesMoved")
//print ("touches count : \(touches.count)")
//prin (touches.first)
if let touch = touches.first{
let currentTouch = touch.locationInNode(self)
let previousTouch = touch.previousLocationInNode(self)
plane.position.x = max(plane.position.x, plane.size.width/2)
plane.position.x = min(plane.position.x, self.frame.size.width - plane.size.width/2)
plane.position.y = max(plane.position.y, plane.size.height/2)
plane.position.y = min(plane.position.y, self.frame.size.height - plane.size.height/2)
// 2 Caculate movement vector and move plane by this vector
plane.position = plane.position.add(currentTouch.subtract(previousTouch))
}
}
override func update(currentTime: CFTimeInterval) {
print("currentTime : \(currentTime)")
for (bulletIndex, bullet) in bullets.enumerate() {
if bullet.position.y > self.frame.maxY{
bullet.removeFromParent()
bullets.removeAtIndex(bulletIndex)
}
for (enemyIndex, enemy) in enemys.enumerate() {
// 1
let bulletFrame = bullet.frame
let enemyFrame = enemy.frame
// 2 check
if CGRectIntersectsRect(bulletFrame, enemyFrame) {
// 3 remove
bullet.removeFromParent()
enemy.removeFromParent()
// 4
bullets.removeAtIndex(bulletIndex)
enemys.removeAtIndex(enemyIndex)
}
}
}
}
func addBullets() {
// 1
let bullet = SKSpriteNode(imageNamed: "bullet.png")
// 2 Set bullet position
bullet.position.y = plane.frame.maxY + bullet.frame.maxY * 1.2
bullet.position.x = plane.position.x
//bullet.position.y = plane.position.y
// 3
self.addChild(bullet)
//4
let fly = SKAction.moveByX(0, y: 20, duration: 0.1)
bullet.runAction(SKAction.repeatActionForever(fly))
bullets.append(bullet)
}
func addEnemys() {
//let addEnemy = SKAction.runBlock {
// 1 Add enemy
self.enemy = SKSpriteNode(imageNamed: "enemy_plane_white_1.png")
// 2 Set enemy position
let PlaneX = UInt32(CGRectGetMaxX(self.frame))
let randomX = CGFloat(arc4random_uniform(PlaneX))
self.enemy.position.x = randomX
self.enemy.position.y = self.frame.size.height
// 3 move Enemy
let moveEnemy = SKAction.moveByX(0, y: -10, duration: 0.2)
self.enemy.runAction(SKAction.repeatActionForever(moveEnemy))
// 4 Shot
self.enemys.append(self.enemy)
let enemyShot = SKAction.runBlock{
self.addEnemyBullet()
}
let enemyShotPeriod = SKAction.sequence([enemyShot, SKAction.waitForDuration(1)])
self.enemy.runAction(SKAction.repeatActionForever(enemyShotPeriod))
// 5
self.addChild(self.enemy)
//}
//let enemyPeriod = SKAction.sequence([addEnemy, SKAction.waitForDuration(3)])
//self.runAction(SKAction.repeatActionForever(enemyPeriod))
}
func addEnemyBullet(){
// 1
let enemyBullet = SKSpriteNode(imageNamed: "bullet_enemy.png")
// 2
enemyBullet.position.y = enemy.frame.minY - enemyBullet.frame.maxY
enemyBullet.position.x = enemy.position.x
// 3
self.addChild(enemyBullet)
// 4
if enemyBullet.position != self.plane.position {
let moveto = SKAction.runBlock {
let fly = SKAction.moveTo(self.plane.position, duration: NSTimeInterval (self.plane.position.distance(enemyBullet.position)/100))
enemyBullet.runAction(SKAction.repeatActionForever(fly))
self.enemyBullets.append(enemyBullet)
}
let moveToPeriod = SKAction.sequence([moveto, SKAction.waitForDuration(0.1)])
enemyBullet.runAction(SKAction.repeatActionForever(moveToPeriod))
}
else {
}
}
}
|
//
// boomBox.swift
// Kana
//
// Created by Chris Phillips on 11/12/15.
// Copyright © 2015 Mad Men of Super Science, LLC. All rights reserved.
//
|
//
// SceneDelegate+SpotifyCallback.swift
// TrackFinder
//
// Created by Niels Hoogendoorn on 18/06/2020.
// Copyright © 2020 Nihoo. All rights reserved.
//
import Foundation
extension SceneDelegate {
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
guard let url = URLContexts.first?.url else { return }
let parameters = rootViewController.appRemote.authorizationParameters(from: url)
let code = parameters?["code"]
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let authService = appDelegate?.container.resolve(AuthenticationServiceProtocol.self)
authService?.getAccessToken(code: code, completion: { [weak self] result in
guard let `self` = self else { return }
switch result {
case .failure:
self.rootViewController.showError(true)
log.error("Failed to receive access token")
case .success:
self.rootViewController.showError(false)
self.loadSearchViewControllerIfNotPresented()
}
})
}
}
|
//
// CTFPAMRaw+SBBDataArchiveBuilder.swift
// Impulse
//
// Created by James Kizer on 2/26/17.
// Copyright © 2017 James Kizer. All rights reserved.
//
import Foundation
import sdlrkx
import BridgeSDK
extension CTFPAMRaw {
//its up to this convertable to manage the schema id and schema revision
override public var schemaIdentifier: String {
return "pam"
}
override public var schemaVersion: Int {
return 2
}
override public var data: [String: Any] {
return self.pamChoice
}
}
|
//
// StockTests.swift
// StockQuoteTests
//
// Created by Ernest Fan on 2019-11-13.
// Copyright © 2019 ErnestFan. All rights reserved.
//
import XCTest
@testable import StockQuote
class StockTests: XCTestCase {
var symbol : String!
var attributes : [String: Any]!
var stock : Stock!
override func setUp() {
super.setUp()
symbol = "MSFT"
attributes = [
"01. symbol": "MSFT",
"02. open": "146.7400",
"03. high": "147.4625",
"04. low": "146.2800",
"05. price": "146.7300",
"06. volume": "8991011",
"07. latest trading day": "2019-11-13",
"08. previous close": "147.0700",
"09. change": "-0.3800",
"10. change percent": "-0.2584%"
]
stock = Stock(symbol: symbol, attributes: attributes)
}
override func tearDown() {
super.tearDown()
symbol = nil
attributes = nil
stock = nil
}
func testStockAttributes() {
// Test Stock model with normal attributes
XCTAssertEqual(stock.symbol, symbol)
XCTAssertEqual(stock.open, 146.7400)
XCTAssertEqual(stock.high, 147.4625)
XCTAssertEqual(stock.low, 146.2800)
XCTAssertEqual(stock.price, 146.7300)
XCTAssertEqual(stock.volume, 8991011)
XCTAssertEqual(stock.latestTradingDate, "2019-11-13")
XCTAssertEqual(stock.previousClose, 147.0700)
XCTAssertEqual(stock.change, -0.3800)
XCTAssertEqual(stock.changePercentage, -0.2584)
}
func testStockEmptyAttributes() {
// Test Stock model with empty attributes (eg. request returns nothing)
attributes = [:]
stock = Stock(symbol: symbol, attributes: attributes)
XCTAssertEqual(stock.symbol, symbol)
XCTAssertEqual(stock.open, 0.0)
XCTAssertEqual(stock.high, 0.0)
XCTAssertEqual(stock.low, 0.0)
XCTAssertEqual(stock.price, 0.0)
XCTAssertEqual(stock.volume, 0)
XCTAssertEqual(stock.latestTradingDate, "")
XCTAssertEqual(stock.previousClose, 0.0)
XCTAssertEqual(stock.change, 0.0)
XCTAssertEqual(stock.changePercentage, 0.0)
XCTAssertEqual(stock.displayTextForPrice(), "-")
XCTAssertEqual(stock.displayTextForPriceChange(), "-")
}
func testStockDisplayInfoWithNegativePriceChange() {
// Normal Stock, negative price change
XCTAssertEqual(stock.displayTextForPrice(), "146.73")
XCTAssertEqual(stock.displayTextForPriceChange(), "-0.38")
}
func testStockDisplayInfoWithPositivePriceChange() {
// Normal Stock, positive price change
attributes["09. change"] = "+0.3800"
stock = Stock(symbol: symbol, attributes: attributes)
XCTAssertEqual(stock.displayTextForPrice(), "146.73")
XCTAssertEqual(stock.displayTextForPriceChange(), "+0.38")
}
}
|
//
// Main.swift
// eve-home-alarm-manager
//
// Created by Kevin Wei on 2019-12-11.
// Copyright © 2019 Kevin Wei. All rights reserved.
//
import UIKit
import HomeKit
import FirebaseDatabase
class Main: UITableViewController {
var ref : DatabaseReference! = Database.database().reference()
//Register list of devices
var deviceList = [HMService]()
var home: HMHome? {
didSet {
home?.delegate = DeviceStore.shared
loadAccessories()
}
}
func loadAccessories() {
deviceList = []
guard let home = home else { return }
for accessory in home.accessories {
accessory.delegate = DeviceStore.shared
print(accessory)
for service in accessory.services.filter({ $0.isPrimaryService }) {
print(service)
deviceList.append(service)
// Ask for notifications from any characteristics that support them.
for characteristic in service.characteristics.filter({
$0.properties.contains(HMCharacteristicPropertySupportsEventNotification)
}) {
characteristic.enableNotification(true) { _ in }
}
}
}
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
DeviceStore.shared.deviceManager.delegate = self
DeviceStore.shared.addHomeDelegate(self)
DeviceStore.shared.addAccessoryDelegate(self)
loadAccessories()
}
/// Deregisters this view controller as various kinds of delegate.
deinit {
DeviceStore.shared.deviceManager.delegate = nil
DeviceStore.shared.removeHomeDelegate(self)
DeviceStore.shared.removeAccessoryDelegate(self)
}
/*
// 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.
}
*/
@IBAction func addDevices(_ sender: Any) {
// Consistent user experience for HomeKit apps
// replaces HMAccessoryBrowser
home?.addAndSetupAccessories(completionHandler: { error in
if let error = error {
print(error)
} else {
// Make no assumption about changes; just reload everything.
self.loadAccessories()
}
})
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return deviceList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DeviceCell", for: indexPath) as! DeviceCell
let device = deviceList[indexPath.row]
// print("DEVICE", device)
cell.sensorLabel.text = device.name
cell.idLabel.text = device.uniqueIdentifier.uuidString
cell.stateLabel.text = "Updating..."
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.ref.child("alarms").child("alrmidhere").setValue(["Description": "Front Door 2", "ID": "alarm", "approve": true])
}
}
|
//
// LogoView.swift
// Ani_MoblieDeveloper_iOS
//
// Created by ani david on 10/05/21.
//
import SwiftUI
struct LogoView: View {
var body: some View {
ZStack{
Image("Vector-2")
.resizable()
.scaledToFill()
.frame(width: 13.02, height: 12.1)
.padding(.top,47.0)
.padding(.bottom,74)
.padding(.trailing,111.0)
Image("Vector")
.resizable()
.scaledToFill()
.frame(width: 13.02, height: 11.78)
.padding(.top,66.0)
.padding(.bottom,65.0)
.padding(.trailing,139.0)
Image("Vector-3")
.resizable()
.scaledToFill()
.frame(width: 21.02, height: 14.78)
.padding(.top,73.0)
.padding(.bottom,75)
.padding(.trailing,119.0)
Image("Vector-1")
.resizable()
.scaledToFill()
.frame(width: 14.09, height: 14.78)
.padding(.top,51.0)
.padding(.bottom,75)
.padding(.trailing,132.0)
Image("T_teamio")
.resizable()
.scaledToFill()
.frame(width: 13.04, height: 10)
.padding(.top,65)
.padding(.bottom,75)
.padding(.trailing,74.0)
Image("e_teamio")
.resizable()
.scaledToFill()
.frame(width: 18.7, height: 15.0)
.padding(.top,68.0)
.padding(.bottom,75)
.padding(.trailing,39.0)
Image("a_teamio")
.resizable()
.scaledToFill()
.frame(width: 18.0, height: 15.0)
.padding(.top,68.0)
.padding(.bottom,75)
.padding(.trailing,0.0)
Image("m_teamio")
.resizable()
.scaledToFill()
.frame(width: 22.0, height: 16.0)
.padding(.top,68.0)
.padding(.bottom,75.0)
.padding(.leading, 46.0)
Image("i_teamio")
.resizable()
.scaledToFill()
.frame(width: 6.0, height: 9.0)
.padding(.top,62.0)
.padding(.bottom,75.0)
.padding(.leading, 79.0)
Image("O_teamio")
.resizable()
.scaledToFill()
.frame(width: 18.0, height: 15.0)
.padding(.top,69.0)
.padding(.bottom,75.0)
.padding(.leading, 105.0)
}
}
}
struct LogoView_Previews: PreviewProvider {
static var previews: some View {
LogoView()
}
}
|
//
// MainView.swift
// ProgrammaticUI
//
// Created by Matthew Ramos on 1/28/20.
// Copyright © 2020 Matthew Ramos. All rights reserved.
//
import UIKit
class MainView: UIView {
let defaultMessage = "No default color set, please go to settings"
//create a label
public lazy var messageLabel: UILabel = {
let label = UILabel()
label.backgroundColor = .systemYellow
label.textAlignment = .center
label.text = defaultMessage
label.font = UIFont.systemFont(ofSize: 17, weight: .semibold)
return label
}() // --- Creates a closure and calls simultaneously
//create a button
public lazy var resetButton: UIButton = {
let button = UIButton()
button.backgroundColor = .systemYellow
button.setTitle("Reset", for: .normal)
button.setTitleColor(.systemBlue, for: .normal)
return button
}()
//if this view is initialized programmatically, gets called
override init(frame: CGRect) {
super.init(frame: UIScreen.main.bounds)
commonInit()
}
//if this view gets initialized from storyboard, this initializer gets called
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
setupMessageLabelConstraints()
setupResetButtonConstraints()
}
private func setupMessageLabelConstraints() {
addSubview(messageLabel)
//set constraints for the messageLabel
messageLabel.translatesAutoresizingMaskIntoConstraints = false // required to use autolayout
NSLayoutConstraint.activate([
messageLabel.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: 20),
messageLabel.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor, constant: 20),
messageLabel.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor, constant: 20)
//set top anchor 20 points from safe area top
//set padding at the leading and trailing edges of the MainView
])
}
private func setupResetButtonConstraints() {
addSubview(resetButton)
resetButton.translatesAutoresizingMaskIntoConstraints = false
//set constraints
NSLayoutConstraint.activate([
resetButton.centerXAnchor.constraint(equalTo: centerXAnchor),
resetButton.topAnchor.constraint(equalTo: messageLabel.bottomAnchor, constant: 40)
])
}
}
|
//
// FirstViewController.swift
// BreakiPoint
//
// Created by Alireza Maleklou on 8/20/19.
// Copyright © 2019 Alireza Maleklou. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
|
import UIKit
extension UIStoryboard {
class var main: UIStoryboard {
UIStoryboard(name: Constants.Storyboards.main, bundle: nil)
}
class var onboarding: UIStoryboard {
UIStoryboard(name: Constants.Storyboards.onboarding, bundle: nil)
}
}
|
//
// HomeCollectionViewCell.swift
// CP103D_Topic0308
//
// Created by min-chia on 2019/3/27.
// Copyright © 2019 min-chia. All rights reserved.
//
import UIKit
class HomeCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var homecellImageview: UIImageView!
@IBOutlet weak var homecellLabel: UILabel!
}
|
//
// Heap.swift
// Heap
//
// Created by Yuri Gorokhov on 11/13/14.
// Copyright (c) 2014 Yuri Gorokhov. All rights reserved.
//
import Foundation
private extension Int {
func Parent() -> Int {
return Int(floor(Double(self) / 2.0))
}
func LeftChild() -> Int {
return 2*self
}
func RightChild() -> Int {
return 2*self + 1
}
}
public class MinHeap<T: Comparable> {
//--- Variables ---
private var _dataArray: [T] = []
//--- Properties ---
public var isEmpty: Bool {
get {
return _dataArray.isEmpty
}
}
//--- Init ---
init(fromArray array: [T]) {
for elem in array {
Insert(elem)
}
}
convenience init() {
self.init(fromArray: [T]())
}
//--- Methods ---
public func Insert(item: T) {
_dataArray.append(item)
HeapUp(_dataArray.count - 1)
}
public func Peek() -> T? {
if _dataArray.isEmpty {
return nil
}
return _dataArray[0];
}
public func Size() -> Int {
return _dataArray.count
}
public func ExtractMin() -> T? {
if _dataArray.isEmpty {
return nil
}
let min = _dataArray[0]
_dataArray[0] = _dataArray[_dataArray.count - 1]
_dataArray.removeAtIndex(_dataArray.count - 1)
HeapDown(0)
return min
}
private func HeapUp(i: Int) {
let parent = i.Parent()
if _dataArray[i] < _dataArray[parent] {
Swap(i, with: parent)
HeapUp(parent)
}
}
private func HeapDown(i: Int) {
var left = i.LeftChild()
var right = i.RightChild()
if right < _dataArray.count {
// both left and right child exist
if _dataArray[i] > min(_dataArray[left], _dataArray[right]) {
if _dataArray[left] < _dataArray[right] {
Swap(i, with: left)
HeapDown(left)
} else {
Swap(i, with: right)
HeapDown(right)
}
}
} else if left < _dataArray.count && _dataArray[i] > _dataArray[left] {
// only left child exists
Swap(i, with: left)
HeapDown(left)
}
}
private func Swap(i: Int, with j: Int) {
let tmp = _dataArray[i]
_dataArray[i] = _dataArray[j]
_dataArray[j] = tmp;
}
} |
//
// LargeImageViewController.swift
// Top Free Apps
//
// Created by mohammad shatarah on 4/8/19.
// Copyright © 2019 mohammad shatarah. All rights reserved.
//
import UIKit
class LargeImageViewController: UIViewController {
var imageURL: String?
@IBOutlet weak var appImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
if (imageURL != nil) {
appImageView.downloadImage(from: URL(string: imageURL!)!)
} }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// MiniPlayerView.swift
// SpotifyClone
//
// Created by JAYANTA GOGOI on 1/16/20.
// Copyright © 2020 JAYANTA GOGOI. All rights reserved.
//
import UIKit
class MiniTrackTitleCell: CollectionBaseCell{
override func setupView() {
title.font = UIFont.systemFont(ofSize: 11)
title.textColor = .white
title.textAlignment = .center
addSubview(title)
addConstraintWithFormat(formate: "H:|[v0]|", views: title)
addConstraintWithFormat(formate: "V:|[v0]|", views: title)
}
}
class MiniPlayer: UIView {
var didMakeFavorite: (()->())?
var didTapOnPlayPause: ((Bool)->())?
var didTapOnTrack:(()->())?
var isPlaying = false
let identifier = "miniplayerTrackCell"
let btnMakeFav: UIButton = {
let btn = UIButton()
btn.setBackgroundImage(#imageLiteral(resourceName: "fav_icon"), for: .normal)
return btn
}()
let btnPlayPause: UIButton = {
let btn = UIButton()
btn.setBackgroundImage(#imageLiteral(resourceName: "play_white_outline"), for: .normal)
btn.setBackgroundImage(#imageLiteral(resourceName: "paus_white_outline"), for: .selected)
return btn
}()
let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let collView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collView.backgroundColor = .clear
collView.showsHorizontalScrollIndicator = false
collView.isPagingEnabled = true
return collView
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
setupCollectionView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
func setupView(){
self.backgroundColor = UIColor.rgba(r: 40, g: 40, b: 40, a: 1)
addSubview(btnMakeFav)
addSubview(collectionView)
addSubview(btnPlayPause)
addConstraintWithFormat(formate: "V:[v0(32)]", views: btnMakeFav)
addConstraintWithFormat(formate: "V:[v0(32)]", views: btnPlayPause)
addConstraintWithFormat(formate: "V:|[v0]|", views: collectionView)
addConstraintWithFormat(formate: "H:|-10-[v0(32)]-10-[v1]-10-[v2(32)]-10-|", views: btnMakeFav, collectionView, btnPlayPause)
addConstraint(NSLayoutConstraint(item: btnMakeFav, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: btnPlayPause, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
btnMakeFav.addTarget(self, action: #selector(onTapMakeFav(_:)), for: .touchUpInside)
btnPlayPause.addTarget(self, action: #selector(onTapPlayPause(_:)), for: .touchUpInside)
}
private func setupCollectionView(){
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(MiniTrackTitleCell.self, forCellWithReuseIdentifier: identifier)
}
}
//MARK: - OnTap Actions
extension MiniPlayer {
@objc func onTapMakeFav(_ sender: UIButton){
sender.onTapAnimation()
self.didMakeFavorite?()
}
@objc func onTapPlayPause(_ sender: UIButton){
sender.onTapAnimation()
self.isPlaying.toggle()
sender.setBackgroundImage( self.isPlaying ? #imageLiteral(resourceName: "paus_white_outline") : #imageLiteral(resourceName: "play_white_outline") , for: .normal)
self.didTapOnPlayPause?(self.isPlaying)
}
}
//MARK: - Collection View Functionality
extension MiniPlayer: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! MiniTrackTitleCell
cell.title.text = "Track Title wil display here \(indexPath.row)"
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// check for negetive value to get rid from negetive layout constraint size issue
return CGSize(width: collectionView.frame.size.width > 0 ? collectionView.frame.size.width : 0 , height: collectionView.frame.size.height > 0 ? collectionView.frame.size.height : 0)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.didTapOnTrack?()
}
}
|
//
// Article.swift
// Positive News App
//
// Created by Harsh Khajuria on 10/05/19.
// Copyright © 2019 horcrux2301. All rights reserved.
//
import Foundation
import UIKit
class Article{
var downvotes:String!
var upvotes:String!
var headline:String!
var img:String!
var id:String!
init(downvotes:String!, upvotes:String!, headline: String!, img: String!, id:String!){
self.downvotes = downvotes
self.upvotes = upvotes
self.headline = headline
self.img = img
self.id = id
}
}
|
//
// Extension.swift
// CavistaApp
//
// Created by Apple on 08/09/20.
// Copyright © 2020 NayanV. All rights reserved.
//
|
import Kitura
/**
Forwards all requests to a specific domain if one is configured.
This middleware also enforces HTTPS when running in the cloud.
*/
struct ForwardingMiddleware: RouterMiddleware {
/// The domain to forward to.
let domain: String?
func handle(request: RouterRequest, response: RouterResponse, next: @escaping () -> Void) throws {
// Do not forward the /health endpoint as this will cause it to fail.
guard !request.originalURL.contains("/health") else {
return next()
}
if let domain = domain, request.hostname != domain {
try response.redirect("https://\(domain)/")
} else if let proto = request.headers["X-Forwarded-Proto"], proto == "http" {
// IBM Cloud terminates SSL at the proxy level.
// This means we have to check the `X-Forwarded-Proto` header, not the URL, to find out if the original request used HTTP.
try response.redirect(request.originalURL.replacingOccurrences(of: "http://", with: "https://"))
} else {
next()
}
}
}
|
//
// PreGameViewController.swift
// DuckRacer
//
// Created by Gerardo Gallegos on 10/12/17.
// Copyright © 2017 Gerardo Gallegos. All rights reserved.
//
import UIKit
import SwiftySound
import Firebase
class PreGameViewController: UIViewController {
var diff: Int!
var isTwoPlayer: Bool!
var scoreLimit: Int = 10
@IBOutlet weak var sliderOutlet: UISlider!
@IBOutlet weak var lapCounter: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
print("PreGame Page: .\(isTwoPlayer), .\(diff)")
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backButton(_ sender: Any) {
if isTwoPlayer{
self.performSegue(withIdentifier: "backToFirst", sender: nil)
}else {
self.performSegue(withIdentifier: "backToDiff", sender: nil)
}
}
@IBAction func scoreSlider(_ sender: Any) {
let currentValue = Int(sliderOutlet.value)
scoreLimit = currentValue
lapCounter.text = "\(scoreLimit) Laps"
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toGameSegue"{
if let destination = segue.destination as? ViewController {
destination.isTwoPlayer = self.isTwoPlayer
destination.scoreLimit = self.scoreLimit
destination.diff = self.diff
}
}else if segue.identifier == "backToDiff"{
if let destination = segue.destination as? DifficultyViewController {
destination.isTwoPlayer = self.isTwoPlayer
print("backtodiff")
}
}
}
}
|
//
// TableViewCell.swift
// WorksManagementApp
//
// Created by 大原一倫 on 2018/12/25.
// Copyright © 2018 oharakazumasa. All rights reserved.
//
import UIKit
class TableViewCell: UITableViewCell {
@IBOutlet var subjectLabel: UILabel!
@IBOutlet var homeWorkLabel: 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
}
}
|
//
// ProtocolGallerySlideshowItemViewDelegate.swift
// f26
//
// Created by David on 05/09/2017.
// Copyright © 2017 com.smartfoundation. All rights reserved.
//
/// Defines a delegate for a GallerySlideshowItemView class
public protocol ProtocolGallerySlideshowItemViewDelegate {
// MARK: - Methods
func checkIsConnected() -> Bool
}
|
//
// JsonCodable.swift
// GitHubber
//
// Created by user on 11/5/18.
// Copyright © 2018 Shalom Friss. All rights reserved.
//
import Foundation
/// Mappable
protocol JsonCodable: Codable {
init?(jsonString: String)
func jsonEncoded() -> String?
}
extension JsonCodable {
/// initialize from a json string
///
/// - Parameter jsonString:String
init?(jsonString: String) {
guard let data = jsonString.data(using: .utf8) else {
return nil
}
do {
self = try JSONDecoder().decode(Self.self, from: data)
} catch {
return nil
}
}
/// return encoded json string
///
/// - Returns: string?
func jsonEncoded() -> String? {
let encoder = JSONEncoder()
do {
let jsonData = try encoder.encode(self)
let jsonString = String(data: jsonData, encoding: .utf8)!
return jsonString
} catch {
return nil
}
}
}
|
//
// GettingUsersLocationRootView.swift
// MVVM_Uber
//
// Created by Nestor Hernandez on 29/07/22.
//
import Foundation
import UIKit
class GettingUsersLocationRootView: NiblessView{
let viewModel: GettingUsersLocationViewModel
let appLogoImageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "roo_logo"))
imageView.backgroundColor = AppColor.background
return imageView
}()
let gettingLocationLabel: UILabel = {
let locationLabel = UILabel()
locationLabel.font = .boldSystemFont(ofSize: 24)
locationLabel.text = "Finding your Location..."
locationLabel.textColor = .white
return locationLabel
}()
init(frame: CGRect = .zero,
viewModel: GettingUsersLocationViewModel){
self.viewModel = viewModel
super.init(frame: frame)
self.viewModel.getCurrentLocation()
}
override func didMoveToWindow() {
super.didMoveToWindow()
self.backgroundColor = AppColor.background
self.buildHierarchy()
self.activateConstraints()
}
private func buildHierarchy(){
addSubview(appLogoImageView)
addSubview(gettingLocationLabel)
}
private func activateConstraints(){
self.activateConstraintsAppLogo()
self.activateConstraintsLocationLabel()
}
private func activateConstraintsAppLogo() {
self.appLogoImageView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.appLogoImageView.centerXAnchor.constraint(equalTo: centerXAnchor),
self.appLogoImageView.centerYAnchor.constraint(equalTo: centerYAnchor)
])
}
private func activateConstraintsLocationLabel() {
self.gettingLocationLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.gettingLocationLabel.topAnchor.constraint(equalTo: self.appLogoImageView.bottomAnchor, constant: 30),
self.gettingLocationLabel.centerXAnchor.constraint(equalTo: centerXAnchor)
])
}
}
|
//
// AppDelegate.swift
// modana_mobile_Muhammad
//
// Created by Muhammad Reynaldi on 12/03/20.
// Copyright © 2020 -. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
setNavigationBar()
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
}
private func setNavigationBar() {
let navBarAppearance = UINavigationBarAppearance()
navBarAppearance.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
navBarAppearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
navBarAppearance.backgroundColor = UIColor(displayP3Red: 45/255, green: 128/255, blue: 236/255, alpha: 1.0)
UINavigationBar.appearance(whenContainedInInstancesOf: [UINavigationController.self]).standardAppearance = navBarAppearance
UINavigationBar.appearance(whenContainedInInstancesOf: [UINavigationController.self]).scrollEdgeAppearance = navBarAppearance
}
}
|
//
// DateRangeTests.swift
// TaskMan
//
// Created by Luiz Fernando Silva on 07/12/16.
// Copyright © 2016 Luiz Fernando Silva. All rights reserved.
//
import XCTest
class DateRangeTests: XCTestCase {
func testIntersects() {
// Intersecting inside
do {
let dateRange1 = DateRange(startDate: Date(timeIntervalSince1970: 0), endDate: Date(timeIntervalSince1970: 10))
let dateRange2 = DateRange(startDate: Date(timeIntervalSince1970: 2), endDate: Date(timeIntervalSince1970: 8))
XCTAssert(dateRange1.intersects(with: dateRange2))
}
// Intersecting at the edges
do {
let dateRange1 = DateRange(startDate: Date(timeIntervalSince1970: 0), endDate: Date(timeIntervalSince1970: 10))
let dateRange2 = DateRange(startDate: Date(timeIntervalSince1970: 10), endDate: Date(timeIntervalSince1970: 20))
XCTAssert(dateRange1.intersects(with: dateRange2))
}
// Non-intersecting
do {
let dateRange1 = DateRange(startDate: Date(timeIntervalSince1970: 0), endDate: Date(timeIntervalSince1970: 10))
let dateRange2 = DateRange(startDate: Date(timeIntervalSince1970: 11), endDate: Date(timeIntervalSince1970: 20))
XCTAssertFalse(dateRange1.intersects(with: dateRange2))
}
}
func testIntersection() {
// Intersecting inside
do {
let dateRange1 = DateRange(startDate: Date(timeIntervalSince1970: 0), endDate: Date(timeIntervalSince1970: 10))
let dateRange2 = DateRange(startDate: Date(timeIntervalSince1970: 2), endDate: Date(timeIntervalSince1970: 8))
XCTAssertEqual(dateRange1.intersection(with: dateRange2), dateRange2)
}
// Intersecting outside
do {
let dateRange1 = DateRange(startDate: Date(timeIntervalSince1970: 0), endDate: Date(timeIntervalSince1970: 10))
let dateRange2 = DateRange(startDate: Date(timeIntervalSince1970: 9), endDate: Date(timeIntervalSince1970: 20))
let expected = DateRange(startDate: Date(timeIntervalSince1970: 9), endDate: Date(timeIntervalSince1970: 10))
XCTAssertEqual(dateRange1.intersection(with: dateRange2), expected)
}
// Intersecting at edges
do {
let dateRange1 = DateRange(startDate: Date(timeIntervalSince1970: 0), endDate: Date(timeIntervalSince1970: 10))
let dateRange2 = DateRange(startDate: Date(timeIntervalSince1970: 10), endDate: Date(timeIntervalSince1970: 20))
XCTAssertNil(dateRange1.intersection(with: dateRange2))
}
// Non-intersecting
do {
let dateRange1 = DateRange(startDate: Date(timeIntervalSince1970: 0), endDate: Date(timeIntervalSince1970: 10))
let dateRange2 = DateRange(startDate: Date(timeIntervalSince1970: 20), endDate: Date(timeIntervalSince1970: 30))
XCTAssertNil(dateRange1.intersection(with: dateRange2))
}
}
func testUnion() {
// Union inside
do {
let dateRange1 = DateRange(startDate: Date(timeIntervalSince1970: 0), endDate: Date(timeIntervalSince1970: 10))
let dateRange2 = DateRange(startDate: Date(timeIntervalSince1970: 2), endDate: Date(timeIntervalSince1970: 8))
XCTAssertEqual(dateRange1.union(with: dateRange2), dateRange1)
}
// Union intersecting
do {
let dateRange1 = DateRange(startDate: Date(timeIntervalSince1970: 0), endDate: Date(timeIntervalSince1970: 10))
let dateRange2 = DateRange(startDate: Date(timeIntervalSince1970: 8), endDate: Date(timeIntervalSince1970: 20))
let expected = DateRange(startDate: Date(timeIntervalSince1970: 0), endDate: Date(timeIntervalSince1970: 20))
XCTAssertEqual(dateRange1.union(with: dateRange2), expected)
}
// Union outside
do {
let dateRange1 = DateRange(startDate: Date(timeIntervalSince1970: 0), endDate: Date(timeIntervalSince1970: 10))
let dateRange2 = DateRange(startDate: Date(timeIntervalSince1970: 20), endDate: Date(timeIntervalSince1970: 30))
let expected = DateRange(startDate: Date(timeIntervalSince1970: 0), endDate: Date(timeIntervalSince1970: 30))
XCTAssertEqual(dateRange1.union(with: dateRange2), expected)
}
}
}
|
//
// Protocols.swift
// fl_music_ios
//
// Created by fengli on 2019/1/17.
// Copyright © 2019 fengli. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
protocol FLViewModelType {
func transform(input: InputType?) -> OutputType?
}
protocol FLViewType {
func provideInput() -> InputType?
}
protocol InputType {
}
protocol OutputType {
}
|
//: Playground - noun: a place where people can play
import UIKit
class Vehicle {
var currentSpeed = 0.0
var description: String {
return "traveling at \(currentSpeed) miles per hour"
}
func makeNoise() {
// do nothing - an arbitrary vehicle doesn't necessarily make a noise
}
}
class Bicycle: Vehicle {
var hasBasket = false
}
class Tandem: Bicycle {
var currentNumberOfPassengers = 0
}
/// Overriding
/**
A subclass can provide its own custom implementation of an instance method, type method, instance property, type property, or subscript that it would otherwise inherit from a superclass. This is known as overriding.
An overridden method named someMethod() can call the superclass version of someMethod() by calling super.someMethod() within the overriding method implementation.
An overridden property called someProperty can access the superclass version of someProperty as super.someProperty within the overriding getter or setter implementation.
An overridden subscript for someIndex can access the superclass version of the same subscript as super[someIndex] from within the overriding subscript implementation.
*/
/// If you provide a setter as part of a property override, you must also provide a getter for that override. If you don’t want to modify the inherited property’s value within the overriding getter, you can simply pass through the inherited value by returning super.someProperty from the getter, where someProperty is the name of the property you are overriding.
class Train: Vehicle {
override func makeNoise() {
print("Choo Choo")
}
}
class Car: Vehicle {
var gear = 1
override var description: String {
return super.description + " in gear \(gear)"
}
}
class AutomaticCar: Car {
override var currentSpeed: Double {
didSet {
gear = Int(currentSpeed / 10.0) + 1
}
}
}
/**
You can prevent a method, property, or subscript from being overridden by marking it as final. Do this by writing the final modifier before the method, property, or subscript’s introducer keyword
*/ |
//
// FetchOperation.swift
//
//
// Created by Alsey Coleman Miller on 8/16/23.
//
import Foundation
public enum FetchOperation <T: Entity> {
case fetch(T.Type, T.ID)
case create(T.Type)
case edit(T.Type, T.ID)
case delete(T.Type, T.ID)
}
|
//
// Link.swift
// Helios
//
// Created by Lars Stegman on 02-01-17.
// Copyright © 2017 Stegman. All rights reserved.
//
import Foundation
public struct Link/*: Thing, Created, Votable */{
public let id: String
public static let kind = Kind.link
// MARK: - Content data
public let title: String
public let contentUrl: URL
public let permalink: String
public let domain: URL
public var selftext: String
public let createdUtc: Date
public let subreddit: String
public let subredditId: String
public let preview: Preview
public var isEdited: Edited
public let isSelf: Bool
public let isOver18: Bool
public let isSpoiler: Bool
public var linkFlair: Flair?
public let author: String?
public let authorFlair: Flair?
// MARK: - Community interaction data
public var score: Int
public var upvotes: Int
public var downvotes: Int
public var numberOfComments: Int
public var distinguished: Distinguishment?
public var isStickied: Bool
public var isLocked: Bool
// MARK: - User interaction data
public var isHidden: Bool
public var isRead: Bool
public var liked: Vote
public var isSaved: Bool
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingsKeys.self)
id = try container.decode(String.self, forKey: .id)
title = try container.decode(String.self, forKey: .title)
contentUrl = try container.decode(URL.self, forKey: .contentUrl)
permalink = try container.decode(String.self, forKey: .permalink)
domain = try container.decode(URL.self, forKey: .domain)
selftext = try container.decode(String.self, forKey: .selftext)
createdUtc = Date(timeIntervalSince1970: try container.decode(TimeInterval.self, forKey: .createdUtc))
subreddit = try container.decode(String.self, forKey: .subreddit)
subredditId = try container.decode(String.self, forKey: .subredditId)
preview = try container.decode(Preview.self, forKey: .preview)
isEdited = try container.decode(Edited.self, forKey: .isEdited)
isSelf = try container.decode(Bool.self, forKey: .isSelf)
isOver18 = try container.decode(Bool.self, forKey: .isOver18)
isSpoiler = try container.decode(Bool.self, forKey: .isSpoiler)
linkFlair = try LinkFlair(from: decoder)
author = try container.decode(String.self, forKey: .author)
authorFlair = try AuthorFlair(from: decoder)
score = try container.decode(Int.self, forKey: .score)
upvotes = try container.decode(Int.self, forKey: .upvotes)
downvotes = try container.decode(Int.self, forKey: .downvotes)
numberOfComments = try container.decode(Int.self, forKey: .numberOfComments)
distinguished = try container.decode(Distinguishment.self, forKey: .distinguishment)
isStickied = try container.decode(Bool.self, forKey: .isStickied)
isLocked = try container.decode(Bool.self, forKey: .isLocked)
isHidden = try container.decode(Bool.self, forKey: .isHidden)
isRead = try container.decode(Bool.self, forKey: .isRead)
liked = try container.decode(Vote.self, forKey: .liked)
isSaved = try container.decode(Bool.self, forKey: .isSaved)
}
private enum CodingsKeys: String, CodingKey {
case id
case title
case contentUrl = "url"
case domain
case score
case upvotes = "ups"
case downvotes = "downs"
case author
case isRead = "clicked"
case isHidden = "hidden"
case isSelf = "is_self"
case liked = "likes"
case isLocked = "locked"
case isEdited = "edited"
case numberOfComments = "num_comments"
case isOver18 = "over_18"
case isSpoiler = "spoiler"
case permalink
case isSaved = "saved"
case selftext
case subreddit
case subredditId = "subreddit_id"
case preview
case isStickied = "stickied"
case createdUtc = "created_utc"
case distinguishment = "distinguished"
}
}
|
import UIKit
import UIExtension
protocol ConvertOrderTableViewControllerCoordinator: AnyObject {
func viewController(_ viewController: ConvertOrderTableViewController, didSelect order: String)
}
final class ConvertOrderTableViewController: UITableViewController {
weak var coordinator: ConvertOrderTableViewControllerCoordinator?
}
extension ConvertOrderTableViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
coordinator?.viewController(self, didSelect: "\(indexPath.row)")
}
}
extension ConvertOrderTableViewController: IBInstantiatable {}
import SwiftUI
extension ConvertOrderTableViewController: UIViewControllerRepresentable {}
struct ConvertOrderTableViewController_Previews: PreviewProvider {
static var previews: some View {
ConvertOrderTableViewController.instantiate()
}
}
|
//
// ViewController.swift
// PromiseKit_Study
//
// Created by 伯驹 黄 on 2017/5/18.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import UIKit
import Alamofire
import PromiseKit
// https://blog.dianqk.org/2016/08/22/rxswift-vs-promisekit/
// http://promisekit.org/docs/
// https://www.raywenderlich.com/145683/getting-started-promises-promisekit
// http://swift.gg/2017/05/04/common-patterns-with-promises/
// http://swift.gg/2017/03/27/promises-in-swift/
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
threeRequest().ensure {
print("完成啦")
}.catch {
print($0)
}
// firstly {
// loginPromise()
// }.then { dict in
// print(dict)
// }.then {
// print("then")
// }.always {
// print("aaaa")
// }
sessionTest()
}
func request(with parameters: [String: Any]) -> Promise<NSDictionary> {
return Promise { seal in
Alamofire.request("https://httpbin.org/get", method: .get, parameters: parameters).validate().responseJSON() { (response) in
switch response.result {
case .success(let dict):
seal.fulfill(dict as! NSDictionary)
case .failure(let error):
seal.reject(error)
}
}
}
}
func threeRequest() -> Promise<()> {
return firstly {
request(with: ["test1": "first"])
}.then { (v) -> Promise<NSDictionary> in
print("🍀", v)
return self.request(with: ["test2": "second"])
}.then { (v) -> Promise<NSDictionary> in
print("🍀🍀", v)
return self.request(with: ["test3": "third"])
}.done { (v) in
print("🍀🍀🍀", v)
}
}
func afterTest() {
after(seconds: 1.5).done {
}
}
func raceTest() {
firstly {
race(loginPromise(), loginPromise())
}.done {
print($0)
}.catch {
print($0)
}
}
func whenTest() {
firstly {
when(fulfilled: sessionPromise(), loginPromise())
}.done { result1, result2 in
print(result1, result2)
}.catch {
print($0)
}
}
let url = URL(string: "http://www.tngou.net/api/area/province")!
func AlamofireWithPromise() {
firstly {
Alamofire.request(url, method: .get, parameters: ["type": "all"]).responseJSON()
}.done { result1 in
print(result1)
}.catch {
print($0)
}
}
func loginPromise() -> Promise<NSDictionary> {
return Promise { seal in
Alamofire.request("https://httpbin.org/get", method: .get, parameters: ["foo": "bar"]).validate().responseJSON() { (response) in
switch response.result {
case .success(let dict):
seal.fulfill(dict as! NSDictionary)
case .failure(let error):
seal.reject(error)
}
}
}
}
func sessionTest() {
firstly {
sessionPromise()
}.then(on: .global()) { data -> Promise<[String: Any]> in
print("global queue", Thread.current)
return Promise<[String: Any]> { seal in
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
seal.fulfill(json as! [String : Any])
} catch {
seal.reject(error)
}
}
}.ensure {
print("1111", Thread.current)
}.done { json in
print(json, Thread.current)
}.ensure {
}.catch {
print($0)
}
}
func sessionPromise() -> Promise<Data> {
return URLSession.shared.promise(URL(string: "https://httpbin.org/get?foo=bar")!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension URLSession {
func promise(_ url: URL) -> Promise<Data> {
return Promise<Data> { seal in
dataTask(with: url) { (data, _, error) in
if let data = data {
seal.fulfill(data)
} else if let error = error {
seal.reject(error)
}
}.resume()
}
}
}
|
import UIKit
class TaskTableViewCell: UITableViewCell, UITextFieldDelegate {
//MARK: Properties
var task: MainTask! {
didSet {
self.titleTextEdit.text = task.title
if task.title.count != 0 {
self.titleTextEdit.isEnabled = false
}
self.deadlineLabel.text = task.isDone()
? NSLocalizedString("Done", comment: "").uppercased()
: task.deadline?.getDueString()
self.reloadCheckBoxContent()
self.contentView.backgroundColor = Utils.getTaskCellColor(priority: self.task.cellHeight)
self.adjustTitleFont()
self.seperator.frame = getSeperatorFrame()
self.updateCellExtension()
}
}
var cellExtension: TaskTableViewCellContent?
var seperator: UIView!
//MARK: Outlets
@IBOutlet weak var titleTextEdit: UITextField!
@IBOutlet weak var checkButton: UIButton!
@IBOutlet weak var deadlineLabel: UILabel!
@IBOutlet weak var extensionButton: UIButton!
static let PADDING_X: CGFloat = 5
static let PADDING_Y: CGFloat = 5
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.titleTextEdit.delegate = self
self.setupCheckButton()
self.setupBackgroundView()
self.addSeperator()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func check(_ sender: UIButton) {
if task.isDone() {
task.setUndone()
} else {
task.setDone()
}
TaskArchive.saveTask(task: task)
reloadCheckBoxContent()
self.deadlineLabel.text = task.isDone()
? NSLocalizedString("Done", comment: "").uppercased()
: task.deadline?.getDueString() ?? ""
guard let tableView = getTableView(),
let viewController = tableView.delegate as? TaskTableViewController else {
return
}
viewController.updateCategoryCellContent()
viewController.updateTaskOrdering()
viewController.updateTaskCategoryProgressbar()
viewController.tableView.reloadData() // update whole content in order to apply new order
}
@IBAction func didPressExtensionButton(_ sender: UIButton) {
guard let tableView = getTableView(),
let viewController = tableView.delegate as? TaskTableViewController,
let index = getIndexInTableView() else {
fatalError("Could not retrieve tableView as superview of tableViewCell!")
}
let decisionMenu = OverlayDecisionView(presenter: viewController.navigationController!, cancelPosition: .center)
decisionMenu.addOption(title: NSLocalizedString("Checklist", comment: "")) {
let newTask = TaskCheckList(task: self.task)
TaskManager.shared.addTask(task: newTask)
tableView.reloadRows(at: [index], with: .automatic)
guard let newCell = tableView.cellForRow(at: index) as? TaskTableViewCell,
let checkList = newCell.cellExtension as? CheckListView else {
return
}
checkList.addSubTask(checkList.addButton)
}
decisionMenu.addOption(title: NSLocalizedString("FollowUp", comment: "")) {
let newTask = TaskConsecutiveList(task: self.task)
TaskManager.shared.addTask(task: newTask)
tableView.reloadRows(at: [index], with: .automatic)
guard let newCell = tableView.cellForRow(at: index) as? TaskTableViewCell,
let consecutiveList = newCell.cellExtension as? ConsecutiveListView else {
return
}
consecutiveList.createFollowUpTask(consecutiveList.forwardButton)
}
decisionMenu.show()
}
//MARK: TextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
// Add overlay view on whole screen, so that user can also end editing by tapping outside the keyboard
let view = UIView(frame: UIScreen.main.bounds)
let stopTitleEditingTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(stopEditingTitle(_:)))
view.addGestureRecognizer(stopTitleEditingTapGestureRecognizer)
window?.addSubview(view)
}
@objc private func stopEditingTitle(_ sender: UITapGestureRecognizer) {
titleTextEdit.resignFirstResponder()
}
func textFieldDidEndEditing(_ textField: UITextField) {
window?.subviews.last?.removeFromSuperview()
guard let newTitle = textField.text, newTitle.count > 0 else {
guard let tableView = getTableView(),
let viewController = tableView.delegate as? TaskTableViewController else {
fatalError("Could not retrieve tableView as superview of tableViewCell!")
}
viewController.currList!.deleteTask(id: task.id)
viewController.updateTaskOrdering()
viewController.updateCurrListProgressBar()
tableView.reloadData()
return
}
task.title = newTitle
TaskArchive.saveTask(task: task)
// Disable textfield once the title was inserted to make for a bigger surface for tap gesture
// Title can be changed in the Task Settings afterwards
textField.isEnabled = false
}
func updateAppearance(newHeight: CGFloat) {
let scaledHeight = Utils.getTaskCellHeight(priority: newHeight)
self.task.cellHeight = scaledHeight
self.contentView.backgroundColor = Utils.getTaskCellColor(priority: scaledHeight)
}
func adjustTitleFont() {
guard task != nil else {
return
}
let fontSize = Utils.getTaskCellTextSize(priority: task.cellHeight)
self.titleTextEdit.font = self.titleTextEdit.font!.withSize(fontSize)
self.deadlineLabel.font = self.deadlineLabel.font.withSize(min(fontSize - 5, 20))
let fontColor = Utils.getTaskCellFontColor(priority: task.cellHeight)
self.titleTextEdit.textColor = fontColor
self.deadlineLabel.textColor = fontColor
self.extensionButton.setTitleColor(fontColor, for: .normal)
self.titleTextEdit.sizeToFit()
}
func startPinchMode() {
self.titleTextEdit.isHidden = true
self.deadlineLabel.isHidden = true
self.seperator.isHidden = true
self.cellExtension?.isHidden = true
}
func endPinchMode() {
self.titleTextEdit.isHidden = false
self.deadlineLabel.isHidden = false
self.adjustTitleFont()
self.seperator.frame = getSeperatorFrame()
self.seperator.isHidden = false
self.cellExtension?.isHidden = false
self.updateCellExtension()
}
func updateCellExtension() {
// Remove prior task extensions (e.g. checklists)
for subview in self.subviews {
if subview is CheckListView || subview is ConsecutiveListView {
subview.removeFromSuperview()
}
}
let extensionFrame = CGRect(x: self.titleTextEdit.frame.minX,
y: self.contentView.bounds.maxY - task.getTaskExtensionHeight() - (TaskTableViewController.extensionBottomPadding),
width: self.contentView.bounds.maxX - 30 - self.titleTextEdit.frame.minX,
height: task.getTaskExtensionHeight())
if let cellExtension = task.createTaskExtensionView(frame: extensionFrame) {
self.addSubview(cellExtension)
self.extensionButton.isHidden = true
self.cellExtension = cellExtension
cellExtension.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: -0.5 * TaskTableViewController.extensionBottomPadding)
} else {
self.extensionButton.isHidden = false
}
}
func getTableView() -> UITableView? {
let tableView: UITableView?
if #available(iOS 11.0, *) {
tableView = superview as? UITableView
} else {
// In iOS 10, superview is scrollview
tableView = superview?.superview as? UITableView
}
return tableView
}
//MARK: Private Methods
private func getIndexInTableView() -> IndexPath? {
guard let tableView = getTableView() else {
fatalError("Error: Failed to retrieve tableview while returning index of cell!")
}
return tableView.indexPath(for: self)
}
private func setupCheckButton() {
checkButton.layer.cornerRadius = 5
checkButton.layer.borderColor = UIColor.black.cgColor
checkButton.layer.borderWidth = 1.0
}
private func setupBackgroundView() {
self.contentView.layer.cornerRadius = 20
self.contentView.layer.masksToBounds = false
self.contentView.layer.shadowColor = Theme.taskCellShadowColor
self.contentView.layer.shadowRadius = 3.0
self.contentView.layer.shadowOffset = CGSize(width: 0, height: 2)
self.contentView.layer.shadowOpacity = 1.0
self.contentView.translatesAutoresizingMaskIntoConstraints = false
self.contentView.topAnchor.constraint(equalTo: self.topAnchor, constant: TaskTableViewCell.PADDING_Y).isActive = true
self.contentView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -1 * TaskTableViewCell.PADDING_Y).isActive = true
self.contentView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: TaskTableViewCell.PADDING_X).isActive = true
self.contentView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -1 * TaskTableViewCell.PADDING_X).isActive = true
}
private func reloadCheckBoxContent() {
if task.isDone() {
checkButton.setTitle("✔️", for: .normal)
} else {
checkButton.setTitle(nil, for: .normal)
}
}
private func getSeperatorFrame() -> CGRect {
return CGRect(x: self.titleTextEdit.frame.minX,
y: self.titleTextEdit.frame.maxY + 5,
width: self.contentView.frame.width - self.titleTextEdit.frame.minX - 80,
height: 1)
}
private func addSeperator() {
let rect = getSeperatorFrame()
let view = UIView(frame: rect)
view.backgroundColor = Theme.taskCellSeperatorColor
self.addSubview(view)
self.seperator = view
}
}
|
//
// ViewController.swift
// MemeMe
//
// Created by Nicholas Park on 5/3/16.
// Copyright © 2016 Nicholas Park. All rights reserved.
//
import UIKit
@objc protocol MemeProtocol{
func keyboardWillShow(sender: NSNotification)
func keybaordWillHide(sender: NSNotification)
func shareMeme()
func cancelMeme()
}
class MemeEditorViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
struct Constants{
static let TopText = "TOP"
static let BottomText = "BOTTOM"
static let Title = "New Meme"
}
let memeTextAttributes = [
NSStrokeColorAttributeName : UIColor.blackColor(),
NSForegroundColorAttributeName : UIColor.whiteColor(),
NSFontAttributeName : UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!,
NSStrokeWidthAttributeName : -1.0
]
var currentMeme:Meme?
@IBOutlet var imagePickerView: UIImageView!
@IBOutlet var galleryButton: UIBarButtonItem!
@IBOutlet var cameraButton: UIBarButtonItem!
@IBOutlet var toolBar: UIToolbar!
@IBOutlet var bottomTextField: UITextField!
@IBOutlet var titleTextField: UITextField!
@IBOutlet var navigationBar: UINavigationBar!
var navItem: UINavigationItem?
override func viewDidLoad() {
super.viewDidLoad()
cameraButton.enabled = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
setup()
//SET THE NAVBAR ITEMS
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: #selector(MemeProtocol.shareMeme))
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: #selector(MemeProtocol.cancelMeme))
navigationItem.leftBarButtonItem?.enabled = false
navigationBar.items = [navigationItem]
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
subscribeToKeyboardNotifications()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
unsubscribeToKeyboardNotifications()
}
@IBAction func getImageButtonClicked(sender: UIBarButtonItem) {
if sender.tag == 0{
pickAnImage(UIImagePickerControllerSourceType.Camera)
}else{
pickAnImage(UIImagePickerControllerSourceType.PhotoLibrary)
}
}
/*
** Redundant Methods
- Keeping these to remind myself what not to do later
@IBAction func pickAnImageFromAlbum(sender: AnyObject){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
presentViewController(imagePicker, animated: true, completion: nil)
}
@IBAction func pickAnImageFromCamera(sender: AnyObject){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
presentViewController(imagePicker, animated: true, completion: nil)
}
*/
func pickAnImage(sourceType: UIImagePickerControllerSourceType){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = sourceType
presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
dismissViewControllerAnimated(true, completion: nil)
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage{
imagePickerView.image = image
imagePickerView.contentMode = UIViewContentMode.ScaleAspectFit
self.navigationItem.leftBarButtonItem?.enabled = true
}
}
/*
KEYBOARD shtuff
*/
func keyboardWillShow(sender: NSNotification){
if bottomTextField.isFirstResponder() {
self.view.frame.origin.y -= getKeyboardHeight(sender)
}
}
func keybaordWillHide(sender: NSNotification){
if bottomTextField.isFirstResponder(){
self.view.frame.origin.y += getKeyboardHeight(sender)
}
}
func getKeyboardHeight(notification: NSNotification) -> CGFloat {
let userInfo = notification.userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue // of CGRect
return keyboardSize.CGRectValue().height
}
// MARK: TextField Delegate Methods
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func textFieldDidBeginEditing(textField: UITextField) {
textField.text = ""
}
// MARK: Notification Methods
//Add an observer for the keyboard both on attachment and detachment
func subscribeToKeyboardNotifications(){
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MemeProtocol.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MemeProtocol.keybaordWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
}
func unsubscribeToKeyboardNotifications(){
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
/*
Stylistic Setup Arguments
*/
func setup(){
titleTextField.text = Constants.TopText
titleTextField.defaultTextAttributes = memeTextAttributes
bottomTextField.defaultTextAttributes = memeTextAttributes
bottomTextField.text = Constants.BottomText
titleTextField.delegate = self
bottomTextField.delegate = self
titleTextField.textAlignment = NSTextAlignment.Center
bottomTextField.textAlignment = NSTextAlignment.Center
}
/*
MEME Methods
*/
func shareMeme(){
let generatedImage = generateMemedImage()
let objectsToShare = [generatedImage]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
activityVC.completionWithItemsHandler = { activity, success, items, error in
if success{
let meme = Meme(topText: self.titleTextField!.text!, image: self.imagePickerView!.image, bottomText: self.bottomTextField!.text!, memedImage: generatedImage)
(UIApplication.sharedApplication().delegate as! AppDelegate).memes.append(meme)
}
}
presentViewController(activityVC, animated: true, completion: nil)
}
func generateMemedImage() -> UIImage{
//HIDE the navigation bar first
navigationBar.hidden = true
toolBar.hidden = true
//Save Shtuff
UIGraphicsBeginImageContext(self.view.frame.size)
view.drawViewHierarchyInRect(self.view.frame,
afterScreenUpdates: true)
let memedImage : UIImage =
UIGraphicsGetImageFromCurrentImageContext()
memedImage.drawAtPoint(CGPointMake(0, 50))
UIGraphicsEndImageContext()
//Show the Navigation Bar again
navigationBar.hidden = false
toolBar.hidden = false
return memedImage
}
func cancelMeme(){
/*
imagePickerView.image = nil
titleTextField.text = Constants.TopText
bottomTextField.text = Constants.BottomText
if titleTextField.isFirstResponder() {
titleTextField.resignFirstResponder()
}else if bottomTextField.isFirstResponder(){
bottomTextField.resignFirstResponder()
}
self.navigationItem.leftBarButtonItem?.enabled = false
*/
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
}
}
|
//
// RequestViewModel.swift
// StayRequest
//
// Created by Thongchai Subsaidee on 12/7/2564 BE.
//
import SwiftUI
class RequestViewModel: ObservableObject {
@Published var requests = requestData
}
|
//
// LastSearch+CoreDataProperties.swift
// FaceRecognition
//
// Created by Ali Hadi on 1/27/16.
// Copyright © 2016 Ali Hadi. All rights reserved.
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
import Foundation
import CoreData
extension LastSearch {
@NSManaged var id: NSNumber?
@NSManaged var arrayPersonne: NSSet?
}
|
//
// HomeController.swift
// sideMenu
//
// Created by Javier Porras jr on 10/18/19.
// Copyright © 2019 Javier Porras jr. All rights reserved.
//
import UIKit
class HomeController: UIViewController {
//MARK: Properties
var delegate: HomeControllerDelegate?
//MARK: Init
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
configureNavigationBar()
}
//MARK: Handlers
@objc func handleMenuToggle(){
//print("Toggle menu...")
delegate?.handleMenuToggle(for: nil)
}
func configureNavigationBar(){
navigationController?.navigationBar.barTintColor = .darkGray
navigationController?.navigationBar.barStyle = .black
navigationItem.title = "Slide Menu"
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "menu")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(handleMenuToggle))
}
}
|
//
// ResultsTableViewController.swift
// testYourself
//
// Created by Marin on 11/02/2018.
// Copyright © 2018 Arthur BRICQ. All rights reserved.
//
import UIKit
/*
let tmp1 = OneScore(name: "Arthur", gender: "Male", nameOfQuizz: "FF", scores: [0, 0, 0, 0, 0, 0])
let tmp2 = OneScore(name: "Marin", gender: "Male", nameOfQuizz: "Fjkf", scores: [40, 0, 40, 0, 40, 0])
let tmp3 = OneScore(name: "Elsa", gender: "Female", nameOfQuizz: "efe", scores: [0, 0, 40, 0, 40, 0])
var items : [OneScore] = [tmp1, tmp2, tmp3]
*/
class ResultsTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return allScores.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "resultCell", for: indexPath) as! ResultTableViewCell
cell.nameLabel.text = allScores[indexPath.section].name.capitalized
cell.genderLabel.text = allScores[indexPath.section].gender.capitalized
cell.quizNameLabel.text = allScores[indexPath.section].nameOfQuizz.capitalized
cell.bestCategoryLabel.text = findTheGreatestCategory(atIndex: indexPath.section).capitalized
return cell
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 30
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView()
footerView.backgroundColor = UIColor.clear
return footerView
}
func findTheGreatestCategory(atIndex: Int) -> String { /*
On appelle cette fonction pour retourner le string du paramètre qui possède la score le plus élevé pour une partie, afin de l'afficher sur l'écran des résultats.
Le paramètre d'entré représente l'index du quizz parmis tout ceux sauvegardé.
*/
var toReturn: String = ""
// 1) trouver la valeur maximale et son index
let currentScore = allScores[atIndex].scores
print("\n\(currentScore)")
var maxIndex: Int = 0
var maxValue: CGFloat = currentScore[0]
for i in 1..<6 {
if currentScore[i] > maxValue {
maxValue = currentScore[i]
maxIndex = i
}
}
// 2) trouver le quizz en question grâce à son titre, et extraire le nom de la propriété maximale.
let nameOfQuizz = allScores[atIndex].nameOfQuizz
for tmpQuizz in allQuizz {
if tmpQuizz.title == nameOfQuizz {
toReturn = tmpQuizz.properties[maxIndex]
}
}
return toReturn
}
// when a cell is pressed
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let previousResultVC = self.parent as! PreviousResultViewController
previousResultVC.showPopover(scoreToShow: allScores[indexPath.section])
}
}
|
//
// User.swift
// punchin
//
// Created by Carla Miettinen on 29/04/16.
// Copyright © 2016 Arto Heino. All rights reserved.
//
import Foundation
class User {
var lastname: String
var studentId: String
init?(lastname: String, studentId: String) {
self.lastname = lastname
self.studentId = studentId
if lastname.isEmpty || studentId.isEmpty{
return nil
}
}
} |
//
// Int+Extension.swift
// JC Movies
//
// Created by Mohammed Shakeer on 06/08/18.
// Copyright © 2018 Just Movies. All rights reserved.
import UIKit
extension Int {
func commaSeparated() -> String {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.decimal
return numberFormatter.string(from: NSNumber(value: self))!
}
}
|
//
// FilterBottomSheetVC.swift
// Qvafy
//
// Created by ios-deepak b on 05/08/20.
// Copyright © 2020 IOS-Aradhana-cat. All rights reserved.
//
//import UIKit
//
//class FilterBottomSheetVC: UIViewController {
//
//}
import UIKit
//MARK: step 1 Add Protocol here
protocol FilterBottomSheetVCDelegate: class {
func sendDataToFirstViewController(arrId:[Int], arrName:[String])
}
class FilterBottomSheetVC: UIViewController {
// MARK:- Outlets
@IBOutlet weak var tblBottom: UITableView!
@IBOutlet weak var lblHeader: UILabel!
@IBOutlet weak var tblHeight: NSLayoutConstraint!
@IBOutlet weak var vwtbl: UIView!
@IBOutlet weak var viewSearch: UIView!
@IBOutlet weak var txtSearch: UITextField!
@IBOutlet weak var btnDone: UIButton!
@IBOutlet weak var vwDone: UIView!
@IBOutlet weak var vwImgDone: UIView!
//MARK: step 2 Create a delegate property here, don't forget to make it weak!
var delegate: FilterBottomSheetVCDelegate? = nil
var strSearchText = ""
// MARK:- Varibles
var arrCategory:[FilterModel] = []
var arrBusiness:[FilterModel] = []
var arrBottom:[FilterModel] = []
var arrBottomAll:[FilterModel] = []
var SelectedArrBottom:[Int] = []
// var arrID:[Int] = []
var arrName:[String] = []
var strHeader = ""
var selectAll: Bool = false
var arrLanguage:[String] = []
// MARK:- LifeCycle
override func viewDidLoad() {
super.viewDidLoad()
self.vwDone.setButtonView(vwOuter : self.vwDone , vwImage : self.vwImgDone, btn: self.btnDone )
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//localisation -
self.txtSearch.placeholder = "Search_Country".localize
self.btnDone.setTitle("Done".localize, for: .normal)
if self.strHeader == "Bussiness Type".localize {
//self.SelectedArrBottom = objAppShareData.arrSelectedBusinessId
// deepak new
if !objAppShareData.arrSelectedBusinessId.isEmpty {
self.SelectedArrBottom = objAppShareData.arrSelectedBusinessId
}// deepak new
} else if self.strHeader == "Select_Language".localize {
// objAppShareData.arrSelectedLanguageId = [2]
// objAppShareData.arrSelectedLanguageName = ["Spanish"]
let selectedlanguage = UserDefaults.standard.string(forKey: "Selectdlanguage")
print(selectedlanguage ?? "")
if selectedlanguage == "es"{
LocalizationSystem.sharedInstance.setLanguage(languageCode: "es")
objAppShareData.arrSelectedLanguageId = [2]
objAppShareData.arrSelectedLanguageName = ["Spanish"]
}else{
LocalizationSystem.sharedInstance.setLanguage(languageCode: "en")
objAppShareData.arrSelectedLanguageId = [1]
objAppShareData.arrSelectedLanguageName = ["English"]
}
////////////////////
self.SelectedArrBottom = objAppShareData.arrSelectedLanguageId
self.arrName = objAppShareData.arrSelectedLanguageName
print(self.SelectedArrBottom.count)
print(self.arrName.count)
}else {
// self.SelectedArrBottom = objAppShareData.arrSelectedCategoryId
// deepak new
if !objAppShareData.arrSelectedCategoryId.isEmpty {
self.SelectedArrBottom = objAppShareData.arrSelectedCategoryId
} // deepak new
}
self.viewSearch.isHidden = true
self.lblHeader.text = self.strHeader
self.vwtbl.roundCorners(corners: [.topLeft, .topRight], radius: 15.0)
self.tblBottom.reloadData()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
override func viewWillLayoutSubviews() {
super.updateViewConstraints()
if strSearchText.count == 0{
if self.arrBottom.count > 14{
let bounds = UIScreen.main.bounds.size.height
self.tblHeight.constant = bounds - 150
self.tblBottom.isScrollEnabled = true
}else{
self.tblHeight.constant = self.tblBottom.contentSize.height + 10
self.tblBottom.isScrollEnabled = false
}
}
}
// MARK:- Buttons Action
@IBAction func btnDoneAction(_ sender: UIButton) {
self.view.endEditing(true)
if self.strHeader == "Bussiness Type".localize{
if self.selectAll == false && self.SelectedArrBottom.count == 0 {
objAlert.showAlert(message: "Please_select_atleast_one_type".localize, title: kAlert.localize , controller: self)
return
}else{
}
}else{
if self.selectAll == false && self.SelectedArrBottom.count == 0 {
objAlert.showAlert(message:"Please_select_atleast_one_type".localize , title: kAlert.localize , controller: self)
return
}else{
}
}
self.delegate?.sendDataToFirstViewController(arrId:self.SelectedArrBottom, arrName:self.arrName )
self.dismiss(animated: false, completion: nil)
}
@IBAction func btnBackAction(_ sender: UIButton)
{
self.view.endEditing(true)
self.dismiss(animated: false, completion: nil)
//self.navigationController?.popViewController(animated: false)
}
}
// MARK:- TableView Delegate and DataSource
extension FilterBottomSheetVC : UITableViewDelegate ,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.arrBottom.count
//print("self.arrBottom count is \(self.arrBottom.count)")
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "BasicInfoCell")as! BasicInfoCell
let obj = self.arrBottom[indexPath.row]
cell.btnCheck.tag = indexPath.row
cell.btnCheck.addTarget(self,action:#selector(buttonClicked(sender:)), for: .touchUpInside)
if self.strHeader == "Bussiness Type".localize{
cell.lblTitle.text = obj.strName.capitalizingFirstLetter()
if self.selectAll{
cell.imgCheck.image = #imageLiteral(resourceName: "active_check_box_ico")
}else if SelectedArrBottom.contains(Int(obj.strBusinessTypeID) ?? 0){
cell.imgCheck.image = #imageLiteral(resourceName: "active_check_box_ico")
}else{
cell.imgCheck.image = #imageLiteral(resourceName: "deselect_ico")
}
} else if self.strHeader == "Select_Language".localize{
cell.lblTitle.text = obj.strName.capitalizingFirstLetter()
if SelectedArrBottom.contains(Int(obj.strBusinessTypeID) ?? 0){
cell.imgCheck.image = #imageLiteral(resourceName: "active_check_box_ico")
}else{
cell.imgCheck.image = #imageLiteral(resourceName: "inactive_tick_ico")
}
}else {
cell.lblTitle.text = obj.strCategoryName.capitalizingFirstLetter()
if self.selectAll{
cell.imgCheck.image = #imageLiteral(resourceName: "active_check_box_ico")
}else if SelectedArrBottom.contains(Int(obj.strCategoryID) ?? 0){
cell.imgCheck.image = #imageLiteral(resourceName: "active_check_box_ico")
}else{
cell.imgCheck.image = #imageLiteral(resourceName: "inactive_tick_ico")
}
}
if self.arrBottom.count - 1 == indexPath.row {
cell.vwShadow.backgroundColor = UIColor.clear
}else{
cell.vwShadow.backgroundColor = #colorLiteral(red: 0.9333333333, green: 0.9333333333, blue: 0.9333333333, alpha: 1)
}
return cell
}
func tableView(_ tableView: UITableView,
heightForRowAt indexPath: IndexPath) -> CGFloat{
return 60 // 44
}
@objc func buttonClicked(sender:UIButton) {
if self.arrBottom.count > 0 {
let obj = self.arrBottom[sender.tag]
if self.strHeader == "Bussiness Type".localize{
if let index = SelectedArrBottom.firstIndex(of: Int(obj.strBusinessTypeID)!) {
SelectedArrBottom.remove(at: index)
/// self.arrName.remove(at: index)
}else{
if !SelectedArrBottom.contains(Int(obj.strBusinessTypeID)!){
SelectedArrBottom.append(Int(obj.strBusinessTypeID)!)
}
if !self.arrName.contains(obj.strName){
/// self.arrName.append(obj.strName)
}
}
}else if self.strHeader == "Select_Language".localize{
if let index = SelectedArrBottom.firstIndex(of: Int(obj.strBusinessTypeID)!) {
// SelectedArrBottom.remove(at: index)
// self.arrName.remove(at: index)
}else{
self.arrName.removeAll()
self.SelectedArrBottom.removeAll()
if !SelectedArrBottom.contains(Int(obj.strBusinessTypeID)!){
SelectedArrBottom.append(Int(obj.strBusinessTypeID)!)
}
if !self.arrName.contains(obj.strName){
self.arrName.append(obj.strName)
}
}
}else{
if let index = SelectedArrBottom.firstIndex(of: Int(obj.strCategoryID)!) {
SelectedArrBottom.remove(at: index)
/// self.arrName.remove(at: index)
}else{
if !SelectedArrBottom.contains(Int(obj.strCategoryID)!){
SelectedArrBottom.append(Int(obj.strCategoryID)!)
}
if !self.arrName.contains(obj.strCategoryName){
/// self.arrName.append(obj.strCategoryName)
}
}
}
print(" self.SelectedArrBottom \(self.SelectedArrBottom)")
print(" self.arrName \(self.arrName)")
self.tblBottom.reloadData()
}
}
}
|
//
// User.swift
// Spoint
//
// Created by kalyan on 11/11/17.
// Copyright © 2017 Personal. All rights reserved.
//
import UIKit
import Firebase
class FollowUser: NSObject {
var userInfo: User
var locationStatus:Bool
var timelineStatus:Bool
var notificationStatus:Bool
var messageStatus:Bool
var requestStatus:Int
init(userinfo: User, locationstatus: Bool, timelinestatus: Bool, notificationstatus: Bool,requeststatus:Int,messageStatus:Bool) {
self.userInfo = userinfo
self.notificationStatus = notificationstatus
self.locationStatus = locationstatus
self.timelineStatus = timelinestatus
self.requestStatus = requeststatus
self.messageStatus = messageStatus
}
static func ==(lhs: FollowUser, rhs: FollowUser) -> Bool {
return lhs.locationStatus == rhs.locationStatus && lhs.timelineStatus == rhs.timelineStatus && lhs.notificationStatus == rhs.notificationStatus && lhs.requestStatus == rhs.requestStatus && lhs.userInfo == rhs.userInfo
}
}
class NotificationsInfo: NSObject {
var userInfo: User
var message:String
var notificationType:String
var sendername: String
var key:String?
var timeStamp:Int64
var createdBy:String
var unread:Bool
var id:String
init(userinfo: User, message: String, notificationtype: String, sender:String, key:String?, timestamp:Int64, createdby:String, unreadStatus:Bool, id:String) {
self.userInfo = userinfo
self.message = message
self.notificationType = notificationtype
self.sendername = sender
self.key = key
self.timeStamp = timestamp
self.createdBy = createdby
self.unread = unreadStatus
self.id = id
}
}
struct UserPermissions {
let notification:Bool
let location:Bool
let message:Bool
let timeline:Bool
init(notification:Bool,location:Bool,message:Bool,timeline:Bool) {
self.notification = notification
self.location = location
self.message = message
self.timeline = timeline
}
}
class RecentChatMessages: NSObject {
var userInfo: User
var message:String
var timeStamp:Int64
var unread:Bool
var unreadCount:Int
init(userinfo:User,message:String,timestamp:Int64, unread:Bool, unreadCount:Int) {
self.userInfo = userinfo
self.message = message
self.timeStamp = timestamp
self.unread = unread
self.unreadCount = unreadCount
}
}
func ==(lhs: User, rhs: User) -> Bool {
return lhs.id == rhs.id
}
class User: NSObject {
//MARK: Properties
let name: String
let email: String
let id: String
var profilePic: URL
let fullname:String
let gender:String
let age: String
let latitude: Double
let longitude : Double
let city :String
let token:String
var locationState:Bool
let deviceType:Int
let phone:String
var permission: UserPermissions?
var accountTypePrivate:Bool
var dob:String
var unreadMessages:Int
var unreadNotifications:Int
//MARK: Methods
class func registerUser(withFullName: String,username:String,gender: String,age:String, email: String, profilePic: UIImage, completion: @escaping (Bool) -> Swift.Void) {
let storageRef = Storage.storage().reference().child("usersProfilePics").child((Auth.auth().currentUser?.uid)!)
let imageData = UIImageJPEGRepresentation(profilePic, 0.1)
storageRef.putData(imageData!, metadata: nil, completion: { (metadata, err) in
if err == nil {
let path = metadata?.downloadURL()?.absoluteString
let values = ["name": withFullName, "email": email, "profilePicLink": path!]
Database.database().reference().child("users").child((Auth.auth().currentUser?.uid)!).child("credentials").updateChildValues(values, withCompletionBlock: { (errr, _) in
if errr == nil {
UserDefaults.standard.set(values, forKey: "userInformation")
completion(true)
}
})
}else{
completion(false)
}
})
}
class func logOutUser(completion: @escaping (Bool) -> Swift.Void) {
do {
try Auth.auth().signOut()
UserDefaults.standard.removeObject(forKey: "userInformation")
completion(true)
} catch _ {
completion(false)
}
}
//MARK: Inits
init(name: String, email: String, id: String, profilePic: URL,fullname:String,age:String,gender:String,latitude:Double,longitude:Double,city:String, token:String,locationState:Bool,devicetype:Int,phoneNo:String, permission:UserPermissions?, accountPrivate:Bool = true,dob:String, unreadmessage:Int, unreadnotification:Int) {
self.name = name
self.email = email
self.id = id
self.profilePic = profilePic
self.age = age
self.gender = gender
self.fullname = fullname
self.latitude = latitude
self.longitude = longitude
self.city = city
self.token = token
self.locationState = locationState
self.deviceType = devicetype
self.permission = permission
self.phone = phoneNo
self.accountTypePrivate = accountPrivate
self.dob = dob
self.unreadMessages = unreadmessage
self.unreadNotifications = unreadnotification
}
}
|
/**
* CNAME file generator plugin for Publish
* Copyright (c) Manny Guerrero 2020
* MIT license, see LICENSE file for details
*/
import Files
import Plot
import Publish
import XCTest
@testable import CNAMEPublishPlugin
// MARK: - TestWebsite
private struct TestWebsite: Website {
enum SectionID: String, WebsiteSectionID {
case test
}
struct ItemMetadata: WebsiteItemMetadata {
}
var url = URL(string: "http://httpbin.org")!
var name = "test"
var description = ""
var language: Language = .english
var imagePath: Path? = nil
}
// MARK: - CNAMEPublishPluginTests
final class CNAMEPublishPluginTests: XCTestCase {
// MARK: - Properties
private static var testDirPath: Path {
let sourceFileURL = URL(fileURLWithPath: #file)
return Path(sourceFileURL.deletingLastPathComponent().path)
}
static var allTests = [
("testGeneratedCNAME", testGenerateCNAME),
("testGenerateCNAME_WhenDomainNameIsEmpty", testGenerateCNAME_WhenDomainNameIsEmpty),
("testGenerateCNAME_WhenListOfDomainNamesAreEmpty", testGenerateCNAME_WhenListOfDomainNamesAreEmpty),
("testAddCNAME", testAddCNAME),
("testAddCNAME_WhenFileIsEmpty", testAddCNAME_WhenFileIsEmpty)
]
private var outputFolder: Folder? {
try? Folder(path: Self.testDirPath.appendingComponent("Output").absoluteString)
}
private var resourcesFolder: Folder? {
try? Folder(path: Self.testDirPath.absoluteString).createSubfolder(named: "Resources")
}
private var outputFile: File? {
try? outputFolder?.file(named: "CNAME")
}
// MARK: - Lifecycle
override func setUp() {
super.setUp()
try? outputFolder?.delete()
try? resourcesFolder?.delete()
}
override func tearDown() {
super.tearDown()
try? outputFolder?.delete()
try? resourcesFolder?.delete()
try? Folder(path: Self.testDirPath.appendingComponent(".publish").absoluteString).delete()
}
// MARK: - Test(s)
func testGenerateCNAME() throws {
try TestWebsite().publish(at: Self.testDirPath, using: [
.installPlugin(.generateCNAME(with: "test.io", "www.test.io"))
])
let cnameOutput = try outputFile?.readAsString()
XCTAssertEqual(cnameOutput, """
test.io
www.test.io
""")
}
func testGenerateCNAME_WhenDomainNameIsEmpty() {
XCTAssertThrowsError(
try TestWebsite().publish(
at: Self.testDirPath,
using: [.installPlugin(.generateCNAME(with: ""))]
)
) { error in
let errorDescription = (error as? PublishingError)?.errorDescription ?? ""
XCTAssertTrue(errorDescription.contains(CNAMEGenerationError.containsEmptyString.localizedDescription))
}
}
func testGenerateCNAME_WhenListOfDomainNamesAreEmpty() {
XCTAssertThrowsError(
try TestWebsite().publish(
at: Self.testDirPath,
using: [.installPlugin(.generateCNAME(with: []))]
)
) { error in
let errorDescription = (error as? PublishingError)?.errorDescription ?? ""
XCTAssertTrue(errorDescription.contains(CNAMEGenerationError.listEmpty.localizedDescription))
}
}
func testAddCNAME() throws {
try resourcesFolder?
.createFile(named: "CNAME")
.write(["test.io", "www.test.io"].joined(separator: "\n"))
try TestWebsite().publish(at: Self.testDirPath, using: [
.installPlugin(.addCNAME())
])
let cnameOutput = try outputFile?.readAsString()
XCTAssertEqual(cnameOutput, """
test.io
www.test.io
""")
}
func testAddCNAME_WhenFileIsEmpty() throws {
try resourcesFolder?.createFile(named: "CNAME")
XCTAssertThrowsError(
try TestWebsite().publish(
at: Self.testDirPath,
using: [.installPlugin(.addCNAME())]
)
) { error in
let errorDescription = (error as? PublishingError)?.errorDescription ?? ""
XCTAssertTrue(errorDescription.contains(CNAMEGenerationError.listEmpty.localizedDescription))
}
}
}
|
import SwiftUI
struct TreatmentProStages: View {
@ObservedObject var viewModel : TreatmentDetailsModel
@State var novaEtapa = false
@State private var selectedStage: StepDetailsModel?
var body: some View {
VStack{
ScrollView {
VStack (alignment: .center, spacing: 15) {
Text("Crie o seu tratamento do jeito que quiser, adicione etapas, tarefas, frequência e tempo.")
.font(.footnote)
.frame(width: 339, alignment: .center)
.padding(.top, 15)
ZStack {
RoundedRectangle(cornerRadius: 10.0).fill(LinearGradient(gradient: Gradient(colors: [Color(.systemBlue), Color(.systemIndigo)]), startPoint: .leading, endPoint: .trailing)).opacity(0.1)
.frame(height: 46, alignment: .center)
.foregroundColor(Color("card-color"))
Text("\(Image(systemName: "plus")) Nova Etapa")
.font(.footnote).foregroundColor(.blue)
.sheet(isPresented: $novaEtapa) {
ModalNewStep(viewModel : StepDetailsModel(title: "Nova Etapa", stepByStep: "", activityTime: false, frequency: false),completeStep: completeStep)
}
.onTapGesture {
novaEtapa = true
}
}
ForEach(viewModel.stepList) { stepItem in
Button(action: {
selectedStage = stepItem
}){
Text(stepItem.title)
.foregroundColor(.white)
}.buttonStyle(StageCard())
.background(CardsGradientStyle())
.cornerRadius(10)
}.sheet(item: $selectedStage) { step in
ModalNewStep(viewModel: step, completeStep: completeStep)
}
}
.padding(.horizontal)
}
Spacer()
NavigationLink(destination: AtributesOfTheTreatment(tratamento: viewModel, name: viewModel.treatmentName, description: viewModel.description) ){
ZStack {
RoundedRectangle(cornerRadius: 10.0) .fill(LinearGradient(gradient: Gradient(colors: [Color(.systemBlue), Color(.systemIndigo)]), startPoint: .leading, endPoint: .trailing))
.frame(width: 150, height: 45, alignment: .center)
Text("Seguinte").foregroundColor(.white)
.font(.footnote)
}.padding()
}
}.navigationTitle(viewModel.treatmentName)
.navigationBarTitleDisplayMode(.inline)
// MARK: --TODO: adicionar botoes de add e editar quando prontos
.navigationBarItems(leading: EmptyView(), trailing: HStack {
Image(systemName: "eye")
NavigationLink(destination: PacientsOfTheTreatment(tratamento: viewModel)){
Image(systemName: "person.badge.plus")
}.buttonStyle(PlainButtonStyle())
})
}
func completeStep(id: UUID, title: String, stepByStep: String, activityTime : Bool, frequency : Bool, image : UIImage? = nil) {
if let model = viewModel.stepList.first(where: { step in
step.id == id
}){
viewModel.objectWillChange.send()
model.title = title
model.stepByStep = stepByStep
model.activityTime = activityTime
model.frequency = frequency
model.image = image
} else {
let step : StepDetailsModel = StepDetailsModel(title:title, stepByStep:stepByStep, activityTime:activityTime, frequency:frequency, image: image)
viewModel.stepList.append(step)
}
}
}
struct TreatmentProStages_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
TreatmentProStages(viewModel: .init())
}
}
}
|
//
// ViewController.swift
// NotesApp
//
// Created by Hermish Mehta on 1/8/18.
// Copyright © 2018 Hermish Mehta. All rights reserved.
//
import UIKit
protocol NoteUpdateDelegate: class {
func updateNote(note: Note, at index: Int)
}
class DetailViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
weak var delegate: NoteUpdateDelegate?
var note: Note?
var noteIndex: Int?
func configureView() {
if let unwrappedNote = note {
textView.text = unwrappedNote.content
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
note?.content = textView.text
if let note = note, let index = noteIndex {
delegate?.updateNote(note: note, at: index)
}
}
}
|
//
// APIManager.swift
// Twitter
//
// Created by Dan on 1/3/19.
// Copyright © 2019 Dan. All rights reserved.
//
import UIKit
import BDBOAuth1Manager
class TwitterAPICaller: BDBOAuth1SessionManager {
static let client = TwitterAPICaller(baseURL: URL(string: "https://api.twitter.com"), consumerKey: "uFTmFW66AAMEUwx3rZlZDMSCf", consumerSecret: "LtlxIoQpBvHcqjpSMIA9Gs2E9wCJbr7xkx9EpSdBYoNedaZUgh")
var loginSuccess: (() -> ())?
var loginFailure: ((Error) -> ())?
func handleOpenUrl(url: URL){
let requestToken = BDBOAuth1Credential(queryString: url.query)
TwitterAPICaller.client?.fetchAccessToken(withPath: "oauth/access_token", method: "POST", requestToken: requestToken, success: { (accessToken: BDBOAuth1Credential!) in
self.loginSuccess?()
}, failure: { (error: Error!) in
self.loginFailure?(error)
})
}
func login(url: String, success: @escaping () -> (), failure: @escaping (Error) -> ()){
loginSuccess = success
loginFailure = failure
TwitterAPICaller.client?.deauthorize()
TwitterAPICaller.client?.fetchRequestToken(withPath: url, method: "GET", callbackURL: URL(string: "alamoTwitter://oauth"), scope: nil, success: { (requestToken: BDBOAuth1Credential!) -> Void in
let url = URL(string: "https://api.twitter.com/oauth/authorize?oauth_token=\(requestToken.token!)")!
UIApplication.shared.open(url)
}, failure: { (error: Error!) -> Void in
print("Error: \(error.localizedDescription)")
self.loginFailure?(error)
})
}
func logout (){
deauthorize()
}
func getDictionaryRequest(url: String, parameters: [String:Any], success: @escaping (NSDictionary) -> (), failure: @escaping (Error) -> ()){
TwitterAPICaller.client?.get(url, parameters: parameters, progress: nil, success: { (task: URLSessionDataTask, response: Any?) in
success(response as! NSDictionary)
}, failure: { (task: URLSessionDataTask?, error: Error) in
failure(error)
})
}
func getDictionariesRequest(url: String, parameters: [String:Any], success: @escaping ([NSDictionary]) -> (), failure: @escaping (Error) -> ()){
TwitterAPICaller.client?.get(url, parameters: parameters, progress: nil, success: { (task: URLSessionDataTask, response: Any?) in
success(response as! [NSDictionary])
}, failure: { (task: URLSessionDataTask?, error: Error) in
failure(error)
})
}
func postRequest(url: String, parameters: [Any], success: @escaping () -> (), failure: @escaping (Error) -> ()){
TwitterAPICaller.client?.post(url, parameters: parameters, progress: nil, success: { (task: URLSessionDataTask, response: Any?) in
success()
}, failure: { (task: URLSessionDataTask?, error: Error) in
failure(error)
})
}
func fetchUserTimeline(for viewController: UIViewController, count: Int, _ completion: @escaping ([Post]) -> Void) {
var posts = [Post]()
let timelineURL = "https://api.twitter.com/1.1/statuses/home_timeline.json"
self.getDictionariesRequest(url: timelineURL, parameters: ["count": count], success: { (postDictionaries) in
guard let postDictionaries = postDictionaries as? [[String: Any]] else {
AlertControllerHelper.presentAlert(for: viewController, withTitle: "Error", withMessage: "Error parsing post data")
return
}
for postDictionary in postDictionaries {
guard let post = Post(postDictionary: postDictionary) else {
AlertControllerHelper.presentAlert(for: viewController, withTitle: "Error", withMessage: "Error parsing post data")
return
}
posts.append(post)
}
let dispatchGroup = DispatchGroup()
for post in posts {
dispatchGroup.enter()
_ = post.posterImage
dispatchGroup.leave()
}
dispatchGroup.notify(queue: .main, execute: {
completion(posts)
})
}, failure: { (error) in
AlertControllerHelper.presentAlert(for: viewController, withTitle: "Error", withMessage: error.localizedDescription)
})
}
func postTweet(withText tweetString: String, completion: @escaping (_ success: Bool, _ errorString: String?) -> ()) {
let url = "https://api.twitter.com/1.1/statuses/update.json"
self.post(url, parameters: ["status": tweetString], progress: nil, success: { (session, response) in
completion(true, nil)
}) { (session, error) in
completion(false, error.localizedDescription)
}
}
func setTweetFavourite(withID id: String, postState isFavourited: Bool, success: @escaping (_ success: Bool, _ errorString: String?) -> ()) {
let url = isFavourited ? "https://api.twitter.com/1.1/favorites/destroy.json" : "https://api.twitter.com/1.1/favorites/create.json"
self.post(url, parameters: ["id": id], progress: nil, success: { (task, response) in
success(true, nil)
}) { (task, error) in
success(false, error.localizedDescription)
}
}
func setRetweeted(withID id: String, postState isRetweeted: Bool, success: @escaping (_ success: Bool, _ errorString: String?) -> ()) {
let url = isRetweeted ? "https://api.twitter.com/1.1/statuses/unretweet/\(id).json" : "https://api.twitter.com/1.1/statuses/retweet/\(id).json"
self.post(url, parameters: ["id": id], progress: nil, success: { (task, response) in
success(true, nil)
}) { (task, error) in
success(false, error.localizedDescription)
}
}
}
|
import Foundation
class DevicesViewModel: ObservableObject {
@Published var devices = [Device]()
func append(_ device: Device) {
if !devices.contains(where: { d in
d.id == device.id
}) {
devices.append(device)
}
}
}
|
//
// toDoListTableViewCell.swift
// beltExam2
//
// Created by Ricardo Rojas on 11/19/17.
// Copyright © 2017 Ricardo Rojas. All rights reserved.
//
import UIKit
import CoreData
class toDoListTableViewCell: UITableViewCell {
@IBAction func doneButtonPressed(_ sender: UIButton) {
}
@IBOutlet weak var toDoItemLabel: UILabel!
@IBOutlet weak var doneButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
//: Playground - noun: a place where people can play
import Cocoa
var str = "Hello, playground"
print("The maximum Int value is \(Int.max).")
print("The minimum Int value is \(Int.min).")
print("The maximum 32-bit Int value is \(Int32.max).")
print("The minimum 32-bit Int value is \(Int32.min).")
print("The maximum UInt value is \(UInt.max)")
print("The minimum UInt value is \(UInt.min)")
let numberOfPages: Int = 10
// Declares the type explicitly1
let numberOfChapters = 3
//also the type of int, but inferred by the compiler
let numberOfPeople: UInt = 40
let volumeAdjustment: Int32 = -1000
print(10 + 20)
print(30 - 5)
print(5 * 6)
print(10 + 2 * 5)
//20, because 2 * 5 is evaluated first
print(30 - 5 - 5)
//20, because 30 - 5 is evaluated first
print ((10 + 2) * 5)
//60, because (10 + 2) is now evaluated first
print(30 - (5 - 5));
//30, because (5-5) is now evaluated first integer division
print(11 / 3) //Prints 3
print(11 % 3) //Prints 2
print(-11 % 3)//Prints -2
var x = 10
x+=10
print("x has had 10 added to it and is now \(x)")
let y: Int8 = 120
let z = y &+ 10
print("120 &+ 10 is \(z)")
let d1 = 1.1 //Implicitly Double
let d2: Double = 1.1
let f1: Float = 100.3
print(10.0 + 11.4)
print(11.0/3.0)
if d1 == d2 {
print("d1 and d2 are the same!")
}
print("d1 + .01 is \(d1 + 0.1)")
if d1 + 0.1 == 1.2 { print("d1 + 0.1 is equal to 1.2")
}
|
//
// SettingsVC.swift
// CureadviserApp
//
// Created by Bekground on 30/03/17.
// Copyright © 2017 BekGround-2. All rights reserved.
//
import UIKit
class SettingsVC: UIViewController {
@IBOutlet var mainView: UIView!
@IBOutlet var scrView: UIScrollView!
@IBOutlet var cameraBtn: UIButton!
override func viewWillAppear(_ animated: Bool) {
cameraBtn.layer.cornerRadius = 25
cameraBtn.layer.shadowColor = UIColor.darkGray.cgColor
cameraBtn.layer.shadowOffset = CGSize(width: 0, height: 1.0)
cameraBtn.layer.shadowOpacity = 0.5
cameraBtn.layer.shadowRadius = 2.0
mainView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 667)
scrView.addSubview(mainView)
scrView.contentSize = CGSize(width: screenWidth, height: 700)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(DismissKeyBoard))
self.view.addGestureRecognizer(tapGesture)
}
func DismissKeyBoard()
{
view.endEditing(true)
}
@IBAction func MenuAction(_ sender: Any) {
self.menuContainerViewController!.toggleLeftSideMenuCompletion({})
}
@IBAction func SubmitSettingAction(_ sender: Any) {
self.navigationController?.pushViewController(Dashboard(nibName: "Dashboard", bundle: nil), animated: true)
}
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.
}
*/
}
|
//
// MainViewController.swift
// Pin
//
// Created by Ken on 6/19/14.
// Copyright (c) 2014 Bacana. All rights reserved.
//
import UIKit
import AudioToolbox
class MainViewController: UITableViewController {
var friendList: [PinFriend] = PinFriendUtil().getFriends()
var friends = Dictionary<String, PinFriend>()
var addTextBox: SHSPhoneTextField!
var newUserPhone: NSString?
var addressBook: AddressBookManager = AddressBookManager()
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var silentRefreshTimer: NSTimer = NSTimer()
// MARK: - UITableViewController Methods -
override func viewDidLoad() {
super.viewDidLoad()
initiateConnection()
addObservers()
addressBook.checkAddressBookAccess()
PinFriendUtil().syncFriends(friendList)
friendListToDict()
addRefreshControl()
makeFooter()
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.backgroundColor = UIColor.clearColor()
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
makeFooter()
}
}
// MARK: - UITableViewCell Subclass and UITableViewDataSource -
extension MainViewController {
func setupAddTextBox(tag: Int) {
var textBoxFrame = CGRectMake(0, 0, view.frame.size.width, cellImageSize.height)
addTextBox = SHSPhoneTextField(frame: textBoxFrame)
if NSLocale.currentLocale().localeIdentifier == "en_US" {
addTextBox.formatter.setDefaultOutputPattern("+# (###) ###-####")
} else {
addTextBox.formatter.setDefaultOutputPattern("+## (##) ####-####")
}
addTextBox.font = defaultFont
addTextBox.textColor = UIColor.whiteColor()
addTextBox.textAlignment = NSTextAlignment.Center
addTextBox.contentVerticalAlignment = UIControlContentVerticalAlignment.Center
addTextBox.backgroundColor = UIColor.clearColor()
addTextBox.keyboardType = UIKeyboardType.PhonePad
addTextBox.placeholder = "Enter a phone number".lowercaseString
addTextBox.adjustsFontSizeToFitWidth = true
addTextBox.delegate = self
addTextBox.tag = tag
}
class UITableViewCellFix: UITableViewCell {
override func layoutSubviews() {
super.layoutSubviews()
var imageFrame = imageView?.frame
imageFrame?.origin = CGPointZero
imageFrame?.size = cellImageSize
imageFrame?.size.width += 12
imageView?.frame = imageFrame!
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCellFix(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
var currentFriend = friendList[indexPath.row] as PinFriend
var uniqueColor = ((currentFriend.number as NSString!).substringWithRange(NSMakeRange(1, 9)) as NSString).integerValue
var tapped: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tappedOnMap:")
if (currentFriend.number != nil) {
var who: NSString! = (currentFriend.name != nil) ? currentFriend.name as NSString! : currentFriend.number as NSString!
if (currentFriend.city != nil) {
cell = UITableViewCellFix(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
DefaultCellStyle.subtitle().stylize(cell)
cell.textLabel?.text = currentFriend.city
cell.detailTextLabel?.text = "from \(who.lowercaseString)"
} else {
cell.textLabel?.text = who.lowercaseString
}
cell.imageView?.image = currentFriend.map
cell.imageView?.contentMode = UIViewContentMode.ScaleToFill
cell.imageView?.tag = indexPath.row
cell.imageView?.userInteractionEnabled = true
cell.imageView?.addGestureRecognizer(tapped)
} else {
setupAddTextBox(indexPath.row)
cell.addSubview(addTextBox)
}
cell.backgroundColor = cellColors[uniqueColor % cellColors.count]
tapped.numberOfTapsRequired = 1
DefaultCellStyle().stylize(cell)
cell.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: cell.bounds.size.width*2)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
var friendTapped: PinFriend = friendList[indexPath.row] as PinFriend
appDelegate.getLocation(friendTapped.number)
updateFriend(friendTapped, mentionSent: true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return cellImageSize.height
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return friendList.count
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
friendList.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
PinFriendUtil().syncFriends(friendList)
friendListToDict()
}
}
// MARK: - Private View Methods -
extension MainViewController {
func addFriend(friend: PinFriend) {
var firstRow: NSIndexPath = NSIndexPath(forRow: 0, inSection: 0)
friendList.insert(friend, atIndex: 0)
tableView.insertRowsAtIndexPaths([firstRow], withRowAnimation: UITableViewRowAnimation.Top)
silentRefresh()
}
func updateFriend(friend: PinFriend, mentionSent: Bool) {
var currentFriend: PinFriend = PinFriendUtil().getFriendWithNumber(addressBook.contactList, number: friend.number!)
var firstRow: NSIndexPath = NSIndexPath(forRow: 0, inSection: 0)
var rowToHandle: NSIndexPath = firstRow
var rowsToRemove: [NSIndexPath] = []
var foundAtIndex: Int = 0
var foundYet: Bool = false
func indexPathRow(index: Int) -> NSIndexPath {
return NSIndexPath(forRow: index, inSection: 0)
}
currentFriend.updateLocation(friend.location)
for (index, myFriend: PinFriend) in enumerate(friendList) {
let frnd: PinFriend = myFriend as PinFriend
if frnd.number == currentFriend.number && foundYet {
friendList.removeAtIndex(index)
rowsToRemove.append(indexPathRow(index))
continue
}
if frnd.number == currentFriend.number {
friendList[index] = currentFriend
rowToHandle = indexPathRow(index)
foundYet = true
foundAtIndex = index
}
}
if mentionSent {
var currentCell = tableView.cellForRowAtIndexPath(rowToHandle)
currentCell?.textLabel?.text = "Sent".lowercaseString
if (currentCell?.detailTextLabel != nil) {
var who: NSString! = (currentFriend.name != nil) ? currentFriend.name as NSString! : currentFriend.number as NSString!
currentCell?.detailTextLabel?.text = "to \(who.lowercaseString)"
}
} else {
tableView.reloadRowsAtIndexPaths([rowToHandle], withRowAnimation: UITableViewRowAnimation.Automatic)
}
tableView.moveRowAtIndexPath(rowToHandle, toIndexPath: firstRow)
tableView.deleteRowsAtIndexPaths(rowsToRemove, withRowAnimation: UITableViewRowAnimation.Top)
friendList.removeAtIndex(foundAtIndex)
friendList.insert(currentFriend, atIndex: 0)
silentRefresh()
}
func refreshTable() {
UIView.transitionWithView(tableView, duration: 0.5, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: {
self.tableView.reloadData()
}, completion: nil)
}
func addRefreshControl() {
var refresher = UIRefreshControl()
refresher.addTarget(self, action: "refreshContacts", forControlEvents: UIControlEvents.ValueChanged)
refreshControl = refresher
}
func showPushAlert(from: PinFriend) {
if UIApplication.sharedApplication().applicationState != UIApplicationState.Background { return }
var pushAlert: UILocalNotification = UILocalNotification()
var now: NSDate = NSDate()
if appDelegate.ios8() {
pushAlert.category = "DEFAULT_CATEGORY"
}
pushAlert.alertBody = "from \(from.name!.uppercaseString)"
pushAlert.fireDate = now.dateByAddingTimeInterval(0)
pushAlert.userInfo = from.location?.asDictionary() as NSDictionary!
UIApplication.sharedApplication().scheduleLocalNotification(pushAlert)
UIApplication.sharedApplication().applicationIconBadgeNumber += 1
}
// MARK: Tour
func silentRefresh() {
silentRefreshTimer.invalidate()
UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler { () -> Void in }
silentRefreshTimer = NSTimer.scheduledTimerWithTimeInterval(0.6, target: self, selector: "refreshTable", userInfo: nil, repeats: false)
NSRunLoop.currentRunLoop().addTimer(silentRefreshTimer, forMode: NSRunLoopCommonModes)
}
func showTourRefresh() {
var tooltip = CMPopTipView(message: TourGuide.tip.refresh)
DefaultTooltipStyle().stylize(tooltip)
tooltip.presentPointingAtView(refreshControl, inView: self.view, animated: true)
TourGuide().setSeen(TGTip.refresh)
}
func showTourSend() {
var tooltip = CMPopTipView(message: TourGuide.tip.send)
DefaultTooltipStyle().stylize(tooltip)
displayTooltipOnFirstCell(tooltip)
TourGuide().setSeen(TGTip.send)
}
func showTourPin() {
var tooltip = CMPopTipView(message: TourGuide.tip.pin)
DefaultTooltipStyle().stylize(tooltip)
displayTooltipOnFirstCell(tooltip)
TourGuide().setSeen(TGTip.pin)
}
func showTourContacts() {
var tooltip = CMPopTipView(message: TourGuide.tip.contacts)
DefaultTooltipStyle().stylize(tooltip)
tooltip.presentPointingAtView(refreshControl, inView: self.view, animated: true)
TourGuide().setSeen(TGTip.contacts)
}
func displayTooltipOnFirstCell(tooltip: CMPopTipView) {
var firstIndex = NSIndexPath(forRow: 0, inSection: 0)
var firstCell = self.tableView.cellForRowAtIndexPath(firstIndex)
tooltip.presentPointingAtView(firstCell, inView: self.view, animated: true)
}
// MARK: Footer
func makeFooter() {
var logoAndVersionView = UIView(frame: CGRectMake(0, 0, self.view.frame.width, 130))
logoAndVersionView.backgroundColor = DefaultFooterStyle().backgroundColor
self.createAndAddLogo(logoAndVersionView)
self.createAndAddTagline(logoAndVersionView)
self.createAndAddVersion(logoAndVersionView)
self.tableView.tableFooterView = logoAndVersionView
}
func createAndAddLogo(view: UIView) {
var imageLogo = UIImage(named: "logo-pin-100.png")
var imageLogoView = UIImageView(image: imageLogo)
imageLogoView.frame = CGRectMake(0, 0, 50, 50)
imageLogoView.center = CGPointMake(self.view.frame.width/2, 40)
view.addSubview(imageLogoView)
}
func createAndAddTagline(view: UIView) {
var labelTagline = UILabel(frame: CGRectMake(0, 60, self.view.frame.width, 30))
labelTagline.text = "Made in Brazil"
DefaultFooterStyle.tagline().stylize(labelTagline)
view.addSubview(labelTagline)
}
func createAndAddVersion(view: UIView) {
var labelVersion = UILabel(frame: CGRectMake(0, 77, self.view.frame.width, 30))
var versionNumber = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as NSString
labelVersion.text = "Version \(versionNumber)"
DefaultFooterStyle.version().stylize(labelVersion)
view.addSubview(labelVersion)
}
}
// MARK: - Private Methods -
extension MainViewController {
func initiateConnection() {
appDelegate.socketManager.connect(appDelegate.sendingFrom)
}
func connected() {
requestContacts()
}
func refreshContacts() {
appDelegate.socketManager.disconnectSocket()
addressBook.checkAddressBookAccess()
}
func tappedOnMap(recognizer: UIGestureRecognizer!) {
var cellImageViewTapped: UIImageView = recognizer.view as UIImageView
var friendTapped: PinFriend = friendList[cellImageViewTapped.tag] as PinFriend
MapUtil().launchMapApp(friendTapped.location)
}
func pressedViewMapAction(notification: NSNotification) {
var location: Location = Location(dictionary: notification.userInfo!)
MapUtil().launchMapApp(location)
}
func gotNewPin(notification: NSNotification) {
var pinResponse: NSDictionary = notification.userInfo!
var fromNumber: NSString = pinResponse["from_cellphone_number"] as NSString
var fromLocation: Location = Location(dictionary: pinResponse["location"] as NSDictionary)
var fromFriend: PinFriend = PinFriend(friendNumber: fromNumber, friendLocation: fromLocation)
if !TourGuide().seenPinTip {
var delayedTip = NSTimer.scheduledTimerWithTimeInterval(TourGuide().tipDelay, target: self, selector: "showTourPin", userInfo: nil, repeats: false)
NSRunLoop.currentRunLoop().addTimer(delayedTip, forMode: NSRunLoopCommonModes)
}
if friendList.exists(fromFriend) {
updateFriend(fromFriend, mentionSent: false)
} else {
addFriend(fromFriend)
}
AudioServicesPlaySystemSound(1007)
PinFriendUtil().syncFriends(friendList)
friendListToDict()
if (friends[fromFriend.number!] != nil) {
fromFriend = friends[fromFriend.number!] as PinFriend!
}
showPushAlert(fromFriend)
}
func requestContacts() {
appDelegate.socketManager.requestContactList(addressBook.getMobileNumbersArray())
}
func friendListToDict() {
for friend: PinFriend in friendList {
friends[friend.number!] = friend
}
}
func gotContacts(notification: NSNotification) {
var pinResponse: NSArray = notification.userInfo!["numbers"] as NSArray
refreshControl?.endRefreshing()
if pinResponse.count == 0 {
refreshTable()
if !TourGuide().seenContactsTip {
var delayedTipContacts = NSTimer.scheduledTimerWithTimeInterval(TourGuide().tipDelay, target: self, selector: "showTourContacts", userInfo: nil, repeats: false)
NSRunLoop.currentRunLoop().addTimer(delayedTipContacts, forMode: NSRunLoopCommonModes)
var delayedTipRefresh = NSTimer.scheduledTimerWithTimeInterval(TourGuide().tipDelay, target: self, selector: "showTourRefresh", userInfo: nil, repeats: false)
NSRunLoop.currentRunLoop().addTimer(delayedTipRefresh, forMode: NSRunLoopCommonModes)
}
return
}
var newFriendList = PinFriendUtil().numberArrayToFriendList(self.addressBook.contactList, numbersArray: pinResponse)
var updatedFriendList = PinFriendUtil().mergeFriendList(friendList, rightList: newFriendList)
friendList = updatedFriendList
PinFriendUtil().syncFriends(friendList)
friendListToDict()
silentRefresh()
if !TourGuide().seenSendTip {
var delayedTip = NSTimer.scheduledTimerWithTimeInterval(TourGuide().tipDelay, target: self, selector: "showTourSend", userInfo: nil, repeats: false)
NSRunLoop.currentRunLoop().addTimer(delayedTip, forMode: NSRunLoopCommonModes)
}
if !TourGuide().seenRefreshTip {
var delayedTip = NSTimer.scheduledTimerWithTimeInterval(TourGuide().tipDelay, target: self, selector: "showTourRefresh", userInfo: nil, repeats: false)
NSRunLoop.currentRunLoop().addTimer(delayedTip, forMode: NSRunLoopCommonModes)
}
}
func addObservers() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "initiateConnection", name: "disconnected", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "connected", name: "connected", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "gotNewPin:", name: "gotNewPin", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "gotContacts:", name: "gotContacts", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "pressedViewMapAction:", name: "pressedViewMapAction", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "backupFriends", name: "backupFriends", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "silentRefresh", name: "silentRefresh", object: nil)
}
func backupFriends() {
PinFriendUtil().syncFriends(friendList)
}
}
// MARK: - UITextFieldDelegate -
extension MainViewController: UITextFieldDelegate {
func textFieldDidEndEditing(textField: UITextField!) {
if textField == addTextBox {
newUserPhone = addTextBox?.phoneNumber()
friendList[0].number = newUserPhone
updateFriend(friendList[0], mentionSent: false)
}
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
textField.resignFirstResponder()
return false
}
}
|
//
// SentenceJSON.swift
// Dibilingo-iOS
//
// Created by Vlad Vrublevsky on 15.12.2020.
//
import Foundation
struct SentenceJSON: Codable {
let sentence: String
init (_ sentence: String) {
self.sentence = sentence
}
}
struct sentencesAll: Codable {
let animals: [String]
let weather: [String]
let transport: [String]
}
|
//
// AppDelegate.swift
// Figueres2018
//
// Created by Javier Jara on 12/6/16.
// Copyright © 2016 Data Center Consultores. All rights reserved.
//
import UIKit
import CoreData
import Fabric
import TwitterKit
import UserNotifications
import SwiftyJSON
import Alamofire
import KeychainAccess
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let dateFormatter = DateFormatter()
let clientSecret = "3674277790370273599"
let clientId = "3MVG9jfQT7vUue.HqM6QpUVnyetAT0hnMDeHFwJyRLEUdv90PB0P31sRrLQu_dSkdLJsC4skCo5VDx2MBnnup"
let username = "entebbe@incompany.cr.WSapp"
let password = "Laluchasinfin2017"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Fabric.with([Twitter.self])
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
}
UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
startAlamofireOauth()
// let keychain = Keychain(service: "com.datacenter.figueres2018")
// if let token = keychain["access_token"] {
// print("There is a token already installed in keychain and is: \(token)")
// fetchuser(userId: "110400781", access_token: token)
//
// } else {
// startAlamofireOauth()
// }
return true
}
// Support for background fetch
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let api = TwitterAPI()
let twitterW = TwitterWorker(twitterAPIStore: api)
twitterW.fetchLatestTweets { (tweets)->Void in
if tweets.count > 0 {
completionHandler(.newData)
for tweet in tweets {
print(tweet.text)
let content = UNMutableNotificationContent()
content.title = "New Tweet From Figueres"
content.subtitle = tweet.tweetID
content.body = tweet.text
UserDefaults.standard.set(tweet.tweetID, forKey: K.UserDefautls.lastTweetID)
// Deliver the notification in five seconds.
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5,
repeats: false)
// Schedule the notification.
let request = UNNotificationRequest(identifier: "FiveSecond", content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request, withCompletionHandler:nil)
}
} else {
completionHandler(.noData)
}
}
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(_ app: UIApplication,
open url: URL,
options: [UIApplicationOpenURLOptionsKey: Any] = [:]) -> Bool {
// you should probably first check if this is the callback being opened
if url.scheme == "salesforce" {
// if your oauth2 instance lives somewhere else, adapt accordingly
// oauth2.handleRedirectURL(url)
return true
}
return false
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.appcoda.CoreDataDemo" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "CoreDataDemo", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("CoreDataDemo.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
// MARK: - CSV Parser Methods
func parseCSV (_ contentsOfURL: URL, encoding: String.Encoding) -> [(id:String, codelec:String, sexo: String, fechacaduc:String,junta: String, nombre:String, apellido1:String, apellido2:String)]? {
// Load the CSV file and parse it
let delimiter = ","
var items:[(id:String, codelec:String, sexo: String, fechacaduc:String, junta: String, nombre:String, apellido1:String, apellido2:String)]?
do {
let content = try String(contentsOf: contentsOfURL, encoding: encoding)
//print(content)
items = []
let lines:[String] = content.components(separatedBy: CharacterSet.newlines) as [String]
for line in lines {
var values:[String] = []
if line != "" {
// For a line with double quotes
// we use NSScanner to perform the parsing
if line.range(of: "\"") != nil {
var textToScan:String = line
var value:NSString?
var textScanner:Scanner = Scanner(string: textToScan)
while textScanner.string != "" {
if (textScanner.string as NSString).substring(to: 1) == "\"" {
textScanner.scanLocation += 1
textScanner.scanUpTo("\"", into: &value)
textScanner.scanLocation += 1
} else {
textScanner.scanUpTo(delimiter, into: &value)
}
// Store the value into the values array
values.append(value as! String)
// Retrieve the unscanned remainder of the string
if textScanner.scanLocation < textScanner.string.characters.count {
textToScan = (textScanner.string as NSString).substring(from: textScanner.scanLocation + 1)
} else {
textToScan = ""
}
textScanner = Scanner(string: textToScan)
}
// For a line without double quotes, we can simply separate the string
// by using the delimiter (e.g. comma)
} else {
values = line.components(separatedBy: delimiter)
}
// Put the values into the tuple and add it to the items array
//let item = (name: values[0], detail: values[1], price: values[2])
// [(id:String, codelec:NSNumber, sexo: NSNumber, junta: NSNumber, fechacaduc:NSDate, nombre:String, apellido1:String, apellido2:String)]?
let item = (id:values[0], codelec:values[1], sexo:values[2], fechacaduc:values[3], junta:values[4], nombre:values[5], apellido1:values[6], apellido2:values[7])
items?.append(item)
}
}
} catch {
print(error)
}
return items
}
func preloadData () {
// Retrieve data from the source file
if let contentsOfURL = Bundle.main.url(forResource: "padron", withExtension: "csv") {
// Remove all the menu items before preloading
removeData()//NSMacOSRomanStringEncoding
if let people = parseCSV(contentsOfURL, encoding: String.Encoding.macOSRoman){
let managedObjectContext = self.managedObjectContext
for personP in people {
let personObj = NSEntityDescription.insertNewObject(forEntityName: "Person", into: managedObjectContext) as! Person
personObj.id = Int32(personP.id)!
personObj.codelec = Int32(personP.codelec)!
personObj.sexo = Int32(personP.sexo)!
personObj.junta = Int32(personP.junta)!
if let dateString = dateFormatter.date(from: personP.fechacaduc) {
personObj.fechacaduc = dateString as Date?
}
personObj.nombre = personP.nombre.trimmingCharacters(in:CharacterSet.whitespacesAndNewlines)
personObj.apellido1 = personP.apellido1.trimmingCharacters(in:CharacterSet.whitespacesAndNewlines)
personObj.apellido2 = personP.apellido2.trimmingCharacters(in:CharacterSet.whitespacesAndNewlines)
do {
try managedObjectContext.save()
} catch _ {
print ("There was an error saving the data base")
}
}
}
}
}
func removeData () {
// Remove the existing items
let managedObjectContext = self.managedObjectContext
//let fetchRequest = NSFetchRequest("Person")
//let fetchRequest: NSFetchRequest<NSFetchRequestResult> = Person.fetchRequest()
let request:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Person")
do {
let menuItems = try managedObjectContext.fetch(request) as! [Person]
for menuItem in menuItems {
managedObjectContext.delete(menuItem)
}
} catch _ {
print ("There was an error DELETING the data base")
}
}
// MARK - OAuth
func startAlamofireOauth() {
let parameters: Parameters = [
"grant_type": "password",
"client_id" : clientId,
"client_secret" : clientSecret,
"username": username,
"password": password,
"redirect_uri": "https://cs52.salesforce.com/services/oauth2/token"
]
let headers: HTTPHeaders = [
"content-type" : "application/x-www-form-urlencoded; charset=utf-8"
]
//https://login.salesforce.com/services/oauth2/token
//https://cs52.salesforce.com/services/oauth2/token
Alamofire.request("https://cs52.salesforce.com/services/oauth2/token", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).authenticate(user: username, password: password).responseJSON { response in
switch response.result {
case .success(let data):
let json = JSON(data)
guard json["error"].string == nil else {
print("Error returned by server: \(json["error"])")
let keychain = Keychain(service: "com.datacenter.figueres2018")
_ = try! keychain.remove("access_token")
return
}
let issued_at = json["issued_at"]
let access_token = json["access_token"].stringValue
print("Access token: \(access_token), issued at: \(issued_at)")
let keychain = Keychain(service: "com.datacenter.figueres2018")
keychain["access_token"] = access_token
case .failure(let error):
print(error)
}
}
}
func fetchuser(userId:String, access_token:String) {
let sessionManager = SessionManager()
sessionManager.adapter = AccessTokenAdapter(accessToken:access_token)
let headers: HTTPHeaders = [
"Authorization" : "Bearer \(access_token)",
"content-type" : "application/x-www-form-urlencoded; charset=utf-8"
]
Alamofire.request("https://cs59.salesforce.com/services/apexrest/Contacts/\(userId)", method: .get , encoding: URLEncoding.httpBody, headers: headers).responseJSON { response in
switch response.result {
case .success(let data):
let json = JSON(data)
guard json["error"].string == nil else {
print("Error returned by server: \(json["error"])")
return
}
print (json)
case .failure(let error):
print(error)
}
}
}
}
|
//
// UITextField+Extension.swift
// CryptocurrencyNews
//
// Created by Kristijan Delivuk on 31/10/2017.
// Copyright © 2017 Kristijan Delivuk. All rights reserved.
//
import UIKit
extension UITextField {
func setBottomBorder(borderColor: UIColor) {
borderStyle = UITextBorderStyle.none
backgroundColor = UIColor.clear
let height = 1.0
let bottomView = UIView()
bottomView.backgroundColor = borderColor
bottomView.frame = CGRect(x: 0, y: Double(self.frame.height) - height, width: Double(self.frame.width), height: height)
addSubview(bottomView)
}
}
|
//
// JobSheetTableViewCell.swift
// Schematic Capture
//
// Created by Gi Pyo Kim on 2/17/20.
// Copyright © 2020 GIPGIP Studio. All rights reserved.
//
import UIKit
class JobSheetTableViewCell: UITableViewCell {
@IBOutlet weak var jobSheetNameLabel: UILabel!
@IBOutlet weak var numOfComponentsLabel: UILabel!
// @IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var statusButton: UIButton!
@IBAction func statusToggleTapped(_ sender: Any) {
statusButton.isSelected.toggle()
if statusButton.isSelected {
jobSheet?.status = "complete"
}
if !statusButton.isSelected {
jobSheet?.status = "incomplete"
}
CoreDataStack.shared.save(context: context)
}
var context = CoreDataStack.shared.mainContext
var jobSheet: JobSheet? {
didSet{
updateViews()
}
}
private func updateViews() {
guard let jobSheet = jobSheet else { return }
jobSheetNameLabel.text = jobSheet.name
numOfComponentsLabel.text = jobSheet.components != nil ? "\(jobSheet.components!.count) Components" : "0 Components"
if jobSheet.status == "complete" {
statusButton.isSelected = true
}
if jobSheet.status == "incomplete" {
statusButton.isSelected = false
}
}
}
|
//
// Chapter5PairwiseSwap.swift
// CtCI
//
// Created by Jordan Doczy on 2/28/21.
//
import Foundation
class Chapter5PairwiseSwap {
typealias Test = (input: UInt32, output: UInt32)
// brute force
// step through each bit flip bit and bit + 1
/*
swap even and odd places
In: 1101
Out: 1110
-----------
In: 10110101
Out: 01111010
Out: 01111010
In: 10110101
Odd: 01010101
Intersect: 00010101
Shift < 1: 00101010
In: 10110101
Even: 10101010
Intersect: 10100000
Shift > 1: 01010000
Even Vals: 01010000
Odd Vals: 00101010
Even + Odd:01111010
How do we create a mask of alternating values?
*/
static func pairwiseSwap(_ input: UInt32) -> UInt32 {
let even: UInt32 = 0xAAAAAAAA
let odd: UInt32 = 0x55555555
let evenValues = (input & even) >> 1
let oddValues = (input & odd) << 1
return evenValues | oddValues
}
static func runTest(_ test: Test) -> Bool {
let output = pairwiseSwap(test.input)
print(test, output)
return test.output == output
}
static func runTests() -> Bool {
var tests: [Test] = []
tests.append((input: 0b10110101, output: 0b01111010))
tests.append((input: 0b1101, output: 0b1110))
tests.append((input: 0b1, output: 0b10))
for test in tests {
if runTest(test) == false {
return false
}
}
return true
}
}
|
//
// JSON.swift
// WeatherApp
//
// Created by Ashley Cameron on 02/11/2015.
// Copyright © 2015 Ashley Cameron. All rights reserved.
//
import Foundation
public typealias JSONDictionary = [String: AnyObject]
public typealias JSONArray = [AnyObject] |
//
// variables.swift
// testYourself
//
// Created by Marin on 04/02/2018.
// Copyright © 2018 Arthur BRICQ. All rights reserved.
//
import Foundation
import UIKit
// variables utilisées pour les segues slide sur la premiere page
var counterToPerformSegueOnlyOnce = true
var initialDiff = CGFloat()
var boleanTestTMP = true
var xPos : CGFloat = 0
var whichViewIsChanging = 0
var isItTheFirstTimeTheViewAppear = true
var labelWidth : CGFloat = 150
var isInSegueFromMenuToBricqBros = false
|
//
// MusicPlayer.swift
// 开闭原则
//
// Created by mxc235 on 2018/4/4.
// Copyright © 2018年 FY. All rights reserved.
//
import Cocoa
enum MusicType: Int {
case Classical = 0
case Popular
case Rock
}
class MusicPlayer: NSObject {
class func playMusic(musicType:MusicType) -> () {
switch musicType {
case .Classical:
ClassicalMusic.init().playMusic()
case .Popular:
PopularMusic.init().playMusic()
default:
break
}
}
}
|
struct RoomChannelResponse: Codable {
let account: String
let roommate: Array<String>?
let type: SocketType
let content: String?
init?(data: Any?) {
guard let result = JsonUtil.deserialize(data: data, type: RoomChannelResponse.self) else {
return nil
}
self = result
}
}
|
//
// YiFu_checkoutVC.swift
// CalculateAgent
//
// Created by Dongze Li on 4/6/18.
// Copyright © 2018 Dongze Li. All rights reserved.
//
import UIKit
import TextFieldEffects
import NVActivityIndicatorView
class YiFu_checkoutVC: UIViewController, UITextFieldDelegate {
// things for show page
var showPage: Bool = false
var editable: Bool = true
var showRecord: CheckoutRecord?
var records: [DeliveryRecord]?
var totalNum: [Int] = [0,0,0,0,0,0,0,0,0,0,0]
var activeTextField: UITextField?
var zone2Label: UILabel!
var zone3Label: UILabel!
var zone4Label: UILabel!
var zone5Label: UILabel!
var zone6Label: UILabel!
var zone7Label: UILabel!
var zone8Label: UILabel!
var zone1Label: UILabel!
var zone9Label: UILabel!
var zone10Label: UILabel!
var zone11Label: UILabel!
// all the fields
var zone2Field: UILabel!
var zone3Field: UILabel!
var zone4Field: UILabel!
var zone5Field: UILabel!
var zone6Field: UILabel!
var zone7Field: UILabel!
var zone8Field: UILabel!
var zone1Field: UILabel!
var zone9Field: UILabel!
var zone10Field: UILabel!
var zone11Field: UILabel!
var zone2Num: AkiraTextField!
var zone3Num: AkiraTextField!
var zone4Num: AkiraTextField!
var zone5Num: AkiraTextField!
var zone6Num: AkiraTextField!
var zone7Num: AkiraTextField!
var zone8Num: AkiraTextField!
var zone1Num: AkiraTextField!
var zone9Num: AkiraTextField!
var zone10Num: AkiraTextField!
var zone11Num: AkiraTextField!
var zone2Cash: AkiraTextField!
var zone3Cash: AkiraTextField!
var zone4Cash: AkiraTextField!
var zone5Cash: AkiraTextField!
var zone6Cash: AkiraTextField!
var zone7Cash: AkiraTextField!
var zone8Cash: AkiraTextField!
var zone1Cash: AkiraTextField!
var zone9Cash: AkiraTextField!
var zone10Cash: AkiraTextField!
var zone11Cash: AkiraTextField!
var animation: NVActivityIndicatorView!
var button: UIButton!
var initY = 70
let offset = 45
let smallOffset = 25
let gap = 300
let boxHeight = 53
override func viewDidLoad() {
super.viewDidLoad()
if (showPage) {
editable = false
} else {
editable = true
}
animation = NVActivityIndicatorView(frame: CGRect(x: view.frame.midX-50,
y: view.frame.midY-50,
width: 100,
height: 100),
type: .circleStrokeSpin, color: themeGreen,
padding: 10)
self.view.addSubview(animation)
NotificationCenter.default.addObserver(self, selector: #selector(YiFu_checkoutVC.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(YiFu_checkoutVC.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
// tap to hide keyboard
let hideTap = UITapGestureRecognizer(target: self, action: #selector(YiFu_checkoutVC.hideKeyboardTap(recognizer:)))
hideTap.numberOfTapsRequired = 1
self.view.isUserInteractionEnabled = true
self.view.addGestureRecognizer(hideTap)
zone2Label = UILabel(frame: CGRect(x: 10, y: initY, width: 50, height: boxHeight))
zone2Label.adjustsFontSizeToFitWidth = true
zone2Field = UILabel(frame: CGRect(x: 70, y: initY, width: 50, height: boxHeight))
zone2Label.adjustsFontSizeToFitWidth = true
zone2Num = AkiraTextField(frame: CGRect(x: 130, y: initY-5, width: 80, height: boxHeight))
zone2Num.delegate = self
zone2Cash = AkiraTextField(frame: CGRect(x: 220, y: initY-5, width: 150, height: boxHeight))
zone2Cash.delegate = self
zone2Label.text = "二病区"
zone2Field.text = "20套"
UIController.textFieldStyle_Akira(textField: zone2Num, str: "结账套数", editable:editable)
UIController.textFieldStyle_Akira(textField: zone2Cash, str: "结账金额(¥)", editable:editable)
self.view.addSubview(zone2Label)
self.view.addSubview(zone2Field)
self.view.addSubview(zone2Num)
self.view.addSubview(zone2Cash)
initY += offset
// zone3
zone3Label = UILabel(frame: CGRect(x: 10, y: initY, width: 50, height: boxHeight))
zone3Label.adjustsFontSizeToFitWidth = true
zone3Field = UILabel(frame: CGRect(x: 70, y: initY, width: 50, height: boxHeight))
zone3Label.adjustsFontSizeToFitWidth = true
zone3Num = AkiraTextField(frame: CGRect(x: 130, y: initY-5, width: 80, height: boxHeight))
zone3Cash = AkiraTextField(frame: CGRect(x: 220, y: initY-5, width: 150, height: boxHeight))
zone3Label.text = "二病区"
zone3Field.text = "20套"
zone3Num.delegate = self
zone3Cash.delegate = self
UIController.textFieldStyle_Akira(textField: zone3Num, str: "", editable:editable)
UIController.textFieldStyle_Akira(textField: zone3Cash, str: "", editable:editable)
self.view.addSubview(zone3Label)
self.view.addSubview(zone3Field)
self.view.addSubview(zone3Num)
self.view.addSubview(zone3Cash)
initY += offset
// zone 4
zone4Label = UILabel(frame: CGRect(x: 10, y: initY, width: 50, height: boxHeight))
zone4Label.adjustsFontSizeToFitWidth = true
zone4Field = UILabel(frame: CGRect(x: 70, y: initY, width: 50, height: boxHeight))
zone4Label.adjustsFontSizeToFitWidth = true
zone4Num = AkiraTextField(frame: CGRect(x: 130, y: initY-5, width: 80, height: boxHeight))
zone4Cash = AkiraTextField(frame: CGRect(x: 220, y: initY-5, width: 150, height: boxHeight))
zone4Label.text = "二病区"
zone4Field.text = "20套"
zone4Num.delegate = self
zone4Cash.delegate = self
UIController.textFieldStyle_Akira(textField: zone4Num, str: "", editable:editable)
UIController.textFieldStyle_Akira(textField: zone4Cash, str: "", editable:editable)
self.view.addSubview(zone4Label)
self.view.addSubview(zone4Field)
self.view.addSubview(zone4Num)
self.view.addSubview(zone4Cash)
initY += offset
// zone 5
zone5Label = UILabel(frame: CGRect(x: 10, y: initY, width: 50, height: boxHeight))
zone5Label.adjustsFontSizeToFitWidth = true
zone5Field = UILabel(frame: CGRect(x: 70, y: initY, width: 50, height: boxHeight))
zone5Label.adjustsFontSizeToFitWidth = true
zone5Num = AkiraTextField(frame: CGRect(x: 130, y: initY-5, width: 80, height: boxHeight))
zone5Cash = AkiraTextField(frame: CGRect(x: 220, y: initY-5, width: 150, height: boxHeight))
zone5Label.text = "二病区"
zone5Field.text = "20套"
zone5Num.delegate = self
zone5Cash.delegate = self
UIController.textFieldStyle_Akira(textField: zone5Num, str: "", editable:editable)
UIController.textFieldStyle_Akira(textField: zone5Cash, str: "", editable:editable)
self.view.addSubview(zone5Label)
self.view.addSubview(zone5Field)
self.view.addSubview(zone5Num)
self.view.addSubview(zone5Cash)
initY += offset
// zone 6
zone6Label = UILabel(frame: CGRect(x: 10, y: initY, width: 50, height: boxHeight))
zone6Label.adjustsFontSizeToFitWidth = true
zone6Field = UILabel(frame: CGRect(x: 70, y: initY, width: 50, height: boxHeight))
zone6Label.adjustsFontSizeToFitWidth = true
zone6Num = AkiraTextField(frame: CGRect(x: 130, y: initY-5, width: 80, height: boxHeight))
zone6Cash = AkiraTextField(frame: CGRect(x: 220, y: initY-5, width: 150, height: boxHeight))
zone6Label.text = "二病区"
zone6Field.text = "20套"
zone6Num.delegate = self
zone6Cash.delegate = self
UIController.textFieldStyle_Akira(textField: zone6Num, str: "", editable:editable)
UIController.textFieldStyle_Akira(textField: zone6Cash, str: "", editable:editable)
self.view.addSubview(zone6Label)
self.view.addSubview(zone6Field)
self.view.addSubview(zone6Num)
self.view.addSubview(zone6Cash)
initY += offset
// zone 7
zone7Label = UILabel(frame: CGRect(x: 10, y: initY, width: 50, height: boxHeight))
zone7Label.adjustsFontSizeToFitWidth = true
zone7Field = UILabel(frame: CGRect(x: 70, y: initY, width: 50, height: boxHeight))
zone7Label.adjustsFontSizeToFitWidth = true
zone7Num = AkiraTextField(frame: CGRect(x: 130, y: initY-5, width: 80, height: boxHeight))
zone7Cash = AkiraTextField(frame: CGRect(x: 220, y: initY-5, width: 150, height: boxHeight))
zone7Label.text = "二病区"
zone7Field.text = "20套"
zone7Num.delegate = self
zone7Cash.delegate = self
UIController.textFieldStyle_Akira(textField: zone7Num, str: "", editable:editable)
UIController.textFieldStyle_Akira(textField: zone7Cash, str: "", editable:editable)
self.view.addSubview(zone7Label)
self.view.addSubview(zone7Field)
self.view.addSubview(zone7Num)
self.view.addSubview(zone7Cash)
initY += offset
// zone 8
zone8Label = UILabel(frame: CGRect(x: 10, y: initY, width: 50, height: boxHeight))
zone8Label.adjustsFontSizeToFitWidth = true
zone8Field = UILabel(frame: CGRect(x: 70, y: initY, width: 50, height: boxHeight))
zone8Label.adjustsFontSizeToFitWidth = true
zone8Num = AkiraTextField(frame: CGRect(x: 130, y: initY-5, width: 80, height: boxHeight))
zone8Cash = AkiraTextField(frame: CGRect(x: 220, y: initY-5, width: 150, height: boxHeight))
zone8Label.text = "二病区"
zone8Field.text = "20套"
zone8Num.delegate = self
zone8Cash.delegate = self
UIController.textFieldStyle_Akira(textField: zone8Num, str: "", editable:editable)
UIController.textFieldStyle_Akira(textField: zone8Cash, str: "", editable:editable)
self.view.addSubview(zone8Label)
self.view.addSubview(zone8Field)
self.view.addSubview(zone8Num)
self.view.addSubview(zone8Cash)
initY += offset
// zone 1
zone1Label = UILabel(frame: CGRect(x: 10, y: initY, width: 50, height: boxHeight))
zone1Label.adjustsFontSizeToFitWidth = true
zone1Field = UILabel(frame: CGRect(x: 70, y: initY, width: 50, height: boxHeight))
zone1Label.adjustsFontSizeToFitWidth = true
zone1Num = AkiraTextField(frame: CGRect(x: 130, y: initY-5, width: 80, height: boxHeight))
zone1Cash = AkiraTextField(frame: CGRect(x: 220, y: initY-5, width: 150, height: boxHeight))
zone1Label.text = "二病区"
zone1Field.text = "20套"
zone1Num.delegate = self
zone1Cash.delegate = self
UIController.textFieldStyle_Akira(textField: zone1Num, str: "", editable:editable)
UIController.textFieldStyle_Akira(textField: zone1Cash, str: "", editable:editable)
self.view.addSubview(zone1Label)
self.view.addSubview(zone1Field)
self.view.addSubview(zone1Num)
self.view.addSubview(zone1Cash)
initY += offset
// zone 9
zone9Label = UILabel(frame: CGRect(x: 10, y: initY, width: 50, height: boxHeight))
zone9Label.adjustsFontSizeToFitWidth = true
zone9Field = UILabel(frame: CGRect(x: 70, y: initY, width: 50, height: boxHeight))
zone9Label.adjustsFontSizeToFitWidth = true
zone9Num = AkiraTextField(frame: CGRect(x: 130, y: initY-5, width: 80, height: boxHeight))
zone9Cash = AkiraTextField(frame: CGRect(x: 220, y: initY-5, width: 150, height: boxHeight))
zone9Label.text = "二病区"
zone9Field.text = "20套"
zone9Num.delegate = self
zone9Cash.delegate = self
UIController.textFieldStyle_Akira(textField: zone9Num, str: "", editable:editable)
UIController.textFieldStyle_Akira(textField: zone9Cash, str: "", editable:editable)
self.view.addSubview(zone9Label)
self.view.addSubview(zone9Field)
self.view.addSubview(zone9Num)
self.view.addSubview(zone9Cash)
initY += offset
// zone 10
zone10Label = UILabel(frame: CGRect(x: 10, y: initY, width: 50, height: boxHeight))
zone10Label.adjustsFontSizeToFitWidth = true
zone10Field = UILabel(frame: CGRect(x: 70, y: initY, width: 50, height: boxHeight))
zone10Label.adjustsFontSizeToFitWidth = true
zone10Num = AkiraTextField(frame: CGRect(x: 130, y: initY-5, width: 80, height: boxHeight))
zone10Cash = AkiraTextField(frame: CGRect(x: 220, y: initY-5, width: 150, height: boxHeight))
zone10Num.delegate = self
zone10Cash.delegate = self
UIController.textFieldStyle_Akira(textField: zone10Num, str: "", editable:editable)
UIController.textFieldStyle_Akira(textField: zone10Cash, str: "", editable:editable)
self.view.addSubview(zone10Label)
self.view.addSubview(zone10Field)
self.view.addSubview(zone10Num)
self.view.addSubview(zone10Cash)
initY += offset
// zone 11
zone11Label = UILabel(frame: CGRect(x: 10, y: initY, width: 50, height: boxHeight))
zone11Label.adjustsFontSizeToFitWidth = true
zone11Field = UILabel(frame: CGRect(x: 70, y: initY, width: 50, height: boxHeight))
zone11Label.adjustsFontSizeToFitWidth = true
zone11Num = AkiraTextField(frame: CGRect(x: 130, y: initY-5, width: 80, height: boxHeight))
zone11Cash = AkiraTextField(frame: CGRect(x: 220, y: initY-5, width: 150, height: boxHeight))
zone11Label.text = "二病区"
zone11Field.text = "20套"
zone11Num.delegate = self
zone11Cash.delegate = self
UIController.textFieldStyle_Akira(textField: zone11Num, str: "", editable:editable)
UIController.textFieldStyle_Akira(textField: zone11Cash, str: "", editable:editable)
self.view.addSubview(zone11Label)
self.view.addSubview(zone11Field)
self.view.addSubview(zone11Num)
self.view.addSubview(zone11Cash)
button = UIButton(frame: CGRect(x: 20, y: 600, width: 330, height: 50))
button.addTarget(self, action: #selector(YiFu_checkoutVC.on_click(_:)), for: .touchUpInside)
UIController.buttonStyle(button: button, str: "确定")
// load the real page
if (showPage) {
showPageDetails()
} else {
DeliveryRecordsOps.getPeriodRecords(hospital: "医附院",
period: "month"){
records in
self.records = records
self.showDetails(records: self.records!)
}
self.view.addSubview(button)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// assign numbers to the labels
func showDetails(records: [DeliveryRecord]) -> Void{
zone1Label.text = "一病区"
zone2Label.text = "二病区"
zone3Label.text = "三病区"
zone4Label.text = "四病区"
zone5Label.text = "五病区"
zone6Label.text = "六病区"
zone7Label.text = "七病区"
zone8Label.text = "八病区"
zone9Label.text = "九病区"
zone10Label.text = "十病区"
zone11Label.text = "十一病区"
totalNum = [0,0,0,0,0,0,0,0,0,0,0]
for record in records {
for item in record.list {
switch item.key {
case "一病区": totalNum[0] += item.value; break
case "二病区": totalNum[1] += item.value; break
case "三病区": totalNum[2] += item.value; break
case "四病区": totalNum[3] += item.value; break
case "五病区": totalNum[4] += item.value; break
case "六病区": totalNum[5] += item.value; break
case "七病区": totalNum[6] += item.value; break
case "八病区": totalNum[7] += item.value; break
case "九病区": totalNum[8] += item.value; break
case "十病区": totalNum[9] += item.value; break
case "十一病区": totalNum[10] += item.value; break
default: break
}
}
}
zone1Field.text = "\(totalNum[0])套"
zone2Field.text = "\(totalNum[1])套"
zone3Field.text = "\(totalNum[2])套"
zone4Field.text = "\(totalNum[3])套"
zone5Field.text = "\(totalNum[4])套"
zone6Field.text = "\(totalNum[5])套"
zone7Field.text = "\(totalNum[6])套"
zone8Field.text = "\(totalNum[7])套"
zone9Field.text = "\(totalNum[8])套"
zone10Field.text = "\(totalNum[9])套"
zone11Field.text = "\(totalNum[10])套"
}
func showPageDetails () {
zone1Label.text = "一病区"
zone2Label.text = "二病区"
zone3Label.text = "三病区"
zone4Label.text = "四病区"
zone5Label.text = "五病区"
zone6Label.text = "六病区"
zone7Label.text = "七病区"
zone8Label.text = "八病区"
zone9Label.text = "九病区"
zone10Label.text = "十病区"
zone11Label.text = "十一病区"
if let checkoutRecord = showRecord {
for item in checkoutRecord.totalDeliveryNums {
switch item.key {
case "一病区": zone1Field.text = "\(item.value)套"; break
case "二病区": zone2Field.text = "\(item.value)套"; break
case "三病区": zone3Field.text = "\(item.value)套"; break
case "四病区": zone4Field.text = "\(item.value)套"; break
case "五病区": zone5Field.text = "\(item.value)套"; break
case "六病区": zone6Field.text = "\(item.value)套"; break
case "七病区": zone7Field.text = "\(item.value)套"; break
case "八病区": zone8Field.text = "\(item.value)套"; break
case "九病区": zone9Field.text = "\(item.value)套"; break
case "十病区": zone10Field.text = "\(item.value)套"; break
case "十一病区": zone11Field.text = "\(item.value)套"; break
default: break
}
}
for item in checkoutRecord.totalCheckoutNums {
switch item.key {
case "一病区": zone1Num.text = "\(item.value)"; break
case "二病区": zone2Num.text = "\(item.value)"; break
case "三病区": zone3Num.text = "\(item.value)"; break
case "四病区": zone4Num.text = "\(item.value)"; break
case "五病区": zone5Num.text = "\(item.value)"; break
case "六病区": zone6Num.text = "\(item.value)"; break
case "七病区": zone7Num.text = "\(item.value)"; break
case "八病区": zone8Num.text = "\(item.value)"; break
case "九病区": zone9Num.text = "\(item.value)"; break
case "十病区": zone10Num.text = "\(item.value)"; break
case "十一病区": zone11Num.text = "\(item.value)"; break
default: break
}
}
for item in checkoutRecord.totalCheckoutCash {
switch item.key {
case "一病区": zone1Cash.text = "¥\(item.value)"; break
case "二病区": zone2Cash.text = "¥\(item.value)"; break
case "三病区": zone3Cash.text = "¥\(item.value)"; break
case "四病区": zone4Cash.text = "¥\(item.value)"; break
case "五病区": zone5Cash.text = "¥\(item.value)"; break
case "六病区": zone6Cash.text = "¥\(item.value)"; break
case "七病区": zone7Cash.text = "¥\(item.value)"; break
case "八病区": zone8Cash.text = "¥\(item.value)"; break
case "九病区": zone9Cash.text = "¥\(item.value)"; break
case "十病区": zone10Cash.text = "¥\(item.value)"; break
case "十一病区": zone11Cash.text = "¥\(item.value)"; break
default: break
}
}
}
}
@objc func keyboardWillShow(notification: NSNotification) {
if let activeTextField = self.activeTextField {
let diff = self.view.frame.height - activeTextField.frame.maxY
print(self.view.frame.height)
print(activeTextField.frame.maxY)
if diff <= 291 {
self.view.frame.origin.y -= 233
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if self.view.frame.origin.y < 0{
self.view.frame.origin.y += 233
}
}
@objc func hideKeyboardTap(recognizer : UITapGestureRecognizer) {
self.view.endEditing(true)
}
func textFieldDidBeginEditing(_ textField: UITextField){
activeTextField = textField
}
func textFieldDidEndEditing(_ textField: UITextField){
activeTextField = nil
}
@objc func on_click(_ sender: Any) {
if (zone1Num.text!.isEmpty || zone1Cash.text!.isEmpty ||
zone2Num.text!.isEmpty || zone2Cash.text!.isEmpty ||
zone3Num.text!.isEmpty || zone3Cash.text!.isEmpty ||
zone4Num.text!.isEmpty || zone4Cash.text!.isEmpty ||
zone5Num.text!.isEmpty || zone5Cash.text!.isEmpty ||
zone6Num.text!.isEmpty || zone6Cash.text!.isEmpty ||
zone7Num.text!.isEmpty || zone7Cash.text!.isEmpty ||
zone8Num.text!.isEmpty || zone8Cash.text!.isEmpty ||
zone9Num.text!.isEmpty || zone9Cash.text!.isEmpty ||
zone10Num.text!.isEmpty || zone10Cash.text!.isEmpty ||
zone11Num.text!.isEmpty || zone11Cash.text!.isEmpty) {
let alert = UIAlertController(title: "错误",
message: "请填写所有结款数目及结款金额", preferredStyle: UIAlertControllerStyle.alert)
let ok = UIAlertAction(title: "好的", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
return
}
let list1: [String:Int] = [zone1Label.text!:totalNum[0],
zone2Label.text!:totalNum[1],
zone3Label.text!:totalNum[2],
zone4Label.text!:totalNum[3],
zone5Label.text!:totalNum[4],
zone6Label.text!:totalNum[5],
zone7Label.text!:totalNum[6],
zone8Label.text!:totalNum[7],
zone9Label.text!:totalNum[8],
zone10Label.text!:totalNum[9],
zone11Label.text!:totalNum[10]]
let list2: [String:Int] = [zone1Label.text!:Int(zone1Num.text!)!,
zone2Label.text!:Int(zone2Num.text!)!,
zone3Label.text!:Int(zone3Num.text!)!,
zone4Label.text!:Int(zone4Num.text!)!,
zone5Label.text!:Int(zone5Num.text!)!,
zone6Label.text!:Int(zone6Num.text!)!,
zone7Label.text!:Int(zone7Num.text!)!,
zone8Label.text!:Int(zone8Num.text!)!,
zone9Label.text!:Int(zone9Num.text!)!,
zone10Label.text!:Int(zone10Num.text!)!,
zone11Label.text!:Int(zone11Num.text!)!]
let list3: [String:Int] = [zone1Label.text!:Int(zone1Cash.text!)!,
zone2Label.text!:Int(zone2Cash.text!)!,
zone3Label.text!:Int(zone3Cash.text!)!,
zone4Label.text!:Int(zone4Cash.text!)!,
zone5Label.text!:Int(zone5Cash.text!)!,
zone6Label.text!:Int(zone6Cash.text!)!,
zone7Label.text!:Int(zone7Cash.text!)!,
zone8Label.text!:Int(zone8Cash.text!)!,
zone9Label.text!:Int(zone9Cash.text!)!,
zone10Label.text!:Int(zone10Cash.text!)!,
zone11Label.text!:Int(zone11Cash.text!)!]
let date = Date()
let calendar = Calendar.current
let year = calendar.component(.year, from: date)
let month = calendar.component(.month, from: date)
let day = calendar.component(.day, from: date)
let formattedDate:String = "\(year) / \(month) / \(day)"
let hospital:String = "医附院"
let checkoutRecord = CheckoutRecord(date: formattedDate, hospital: hospital, totalDeliveryNums: list1, totalCheckoutNums: list2, totalCheckoutCash: list3)
self.animation.startAnimating()
UIApplication.shared.beginIgnoringInteractionEvents()
DeliveryRecordsOps.uploadCheckout(checkoutRecord: checkoutRecord) {
status in
self.animation.stopAnimating()
UIApplication.shared.endIgnoringInteractionEvents()
if (status) {
let alert = UIAlertController(title: "上传成功✅",
message: "已上传所有数据和金额", preferredStyle: UIAlertControllerStyle.alert)
let ok = UIAlertAction(title: "好的", style: UIAlertActionStyle.cancel, handler: {
action in
self.navigationController?.popToRootViewController(animated: false)
})
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
} else {
let alert = UIAlertController(title: "错误❌",
message: "数据传输失败,请稍后重试", preferredStyle: UIAlertControllerStyle.alert)
let ok = UIAlertAction(title: "好的", style: UIAlertActionStyle.cancel, handler: {
action in
self.navigationController?.popToRootViewController(animated: false)
})
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
}
}
}
}
|
//
// Category.swift
// SoTube
//
// Created by VDAB Cursist on 23/05/17.
// Copyright © 2017 NV Met Talent. All rights reserved.
//
struct Category {
let name: String
let id: String
let coverUrl: String
let url: String
var playlists: [Playlist]?
init(named name: String,withId id: String, withCoverUrl coverUrl: String, withUrl url: String) {
self.name = name
self.id = id
self.url = url
self.coverUrl = coverUrl
}
}
|
//
// AddTeamViewController.swift
// TheBestKCProgrammingContest
//
// Created by Nick Pierce on 3/12/19.
// Copyright © 2019 SmartShopperTeam. All rights reserved.
//
import UIKit
class NewTeamViewController: UIViewController {
// property to refer to the selected School and parent VC
var selectedSchool: School!
var presented: TeamsTableViewController!
// enumerates outlets
@IBOutlet weak var name: UITextField!
@IBOutlet weak var student0: UITextField!
@IBOutlet weak var student1: UITextField!
@IBOutlet weak var student2: UITextField!
// array containing students
var studentArray: [UITextField?] = [] // initialized value, will be overriden in viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
studentArray = [student0,student1,student2]
// Do any additional setup after loading the view.
}
// dismisses all UITextField data and returns to modally presented
@IBAction func cancel(_ sender: Any){
// invokes dismiss and clears UITextFields
self.dismiss(animated: true) {
for textField in self.studentArray{
textField?.text = ""
}
}
}
// appends new team to school and dismisses to Presented modally
@IBAction func done(_ sender: Any?){
// informs user of background process and bars subsuquent user interaction
self.presented.activityIndicator.startAnimating()
UIApplication.shared.beginIgnoringInteractionEvents()
// creates local references to be used in background thread
let name = self.name.text!
let students: [String] = studentArray.map({return $0!.text! != "" ? $0!.text! : "student not entered"})
// invokes dismiss and appends new team instance to that school
self.dismiss(animated: true){
DispatchQueue.global(qos: .userInteractive).async{
Schools.shared.addTeam(forSchool: self.selectedSchool, withTeam: Team(name: name, students: students))
}
}
}
/*
// 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.
}
*/
}
|
import Shared
import XCTest
public extension XCUIElement {
var centerCoordinate: XCUICoordinate {
coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5))
}
func forceTap() {
centerCoordinate.tap()
}
func scrollTo(element: XCUIElement) {
if frame.minY > element.frame.minY {
scrollUpTo(element: element)
} else {
scrollDownTo(element: element)
}
}
func scrollDownTo(element: XCUIElement) {
while frame.contains(element.frame) == false {
centerCoordinate.press(forDuration: 0.05, thenDragTo: centerCoordinate.withOffset(CGVector(dx: 0, dy: -element.frame.height / 2)))
}
}
func scrollUpTo(element: XCUIElement) {
while frame.contains(element.frame) == false {
centerCoordinate.press(forDuration: 0.05, thenDragTo: centerCoordinate.withOffset(CGVector(dx: 0, dy: element.frame.height / 2)))
}
}
}
|
// swiftlint:disable all
import Amplify
import Foundation
public struct Answer: Model {
public let id: String
public var content: String?
public var prayerID: String
public init(id: String = UUID().uuidString,
content: String? = nil,
prayerID: String) {
self.id = id
self.content = content
self.prayerID = prayerID
}
} |
//
// MainViewModel.swift
// CountriesTask
//
// Created by Amr Mohamed on 4/12/20.
// Copyright © 2020 amr. All rights reserved.
//
import Foundation
class MainViewModel: NSObject {
var countries: [Country] = []
private var dataBaseController:DatabaseController
init(dataBaseController:DatabaseController){
self.dataBaseController = dataBaseController
}
func save(countryName:Country) {
dataBaseController.save(countryname: countryName)
}
func getSavedCountries() {
countries.append(contentsOf: dataBaseController.getSaved())
}
func deleteCountries(countryName:Country) {
dataBaseController.delete(countryname: countryName)
}
func rowCount() -> Int{
return countries.count
}
}
|
//
// SearchResultItem.swift
// ios-mvp-pattern-example
//
// Created by Ivan Podibka on 17/08/2018.
// Copyright © 2018 Ivan Podibka. All rights reserved.
//
import Foundation
class SearchResultItem: TableViewCellItem {
var id: Int?
var posterPath: String?
var title: String?
var overview: String?
var cellIdentifier: String {
return SearchResultTableViewCell.cellIdentifier
}
init(_ data: Movie) {
id = data.id
posterPath = data.posterPath
title = data.title
overview = data.overview
}
}
|
//
// LabelItem.swift
// collection-view-tutorial-2
//
// Created by Victor, Yuri on 5/7/19.
// Copyright © 2019 Victor, Yuri. All rights reserved.
//
import Cocoa
class LabelItem: NSCollectionViewItem {
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
}
|
//
// Created by Иван Лизогуб on 19.11.2020.
//
import UIKit
import FlagPhoneNumber
import FirebaseAuth
class PhoneNumberRegistrationView: AutoLayoutView {
var GetButtonTappedOnce : Bool = false
var codeIsRight : Bool = false
private var defaultNumber = "2 22 22 22 22"
var phoneNumber : String?
var verificationID: String!
private let textFieldHeight: CGFloat = 50.0
private let numberSectionStack = UIStackView()
var listController: FPNCountryListViewController = FPNCountryListViewController(style: .grouped)
let numberFPNTextField = FPNTextField()
let verificationCodeTextField = AnimatedTextField()
private let yourNumberLabel = UILabel()
var isTapped : Bool = false
let yourCodeLabel = AnimatedLabel()
let numberWasRegisteredLabel = WarningLabel()
let verificationWasFailed = WarningLabel()
let nextButton = UIButton()
let getCodeButton = UIButton()
var onTapNextButton: ((String?) -> Void)?
var onTapGetButton: ((String?) -> Void)?
init() {
super.init(frame: .zero)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
backgroundColor = .systemGray6
nextButton.setTitle("Далее", for: .normal)
nextButton.backgroundColor = .black
nextButton.setTitleColor(.white, for: .normal)
nextButton.layer.cornerRadius = 20.0
nextButton.clipsToBounds = false
nextButton.addTarget(self, action: #selector(onTapNext), for: .touchUpInside)
self.addSubview(nextButton)
self.getCodeButton.setTitle("Отправить код", for: .normal)
self.getCodeButton.alpha = 0.5
self.getCodeButton.isEnabled = true
self.getCodeButton.backgroundColor = .black
self.getCodeButton.setTitleColor(.white, for: .normal)
self.getCodeButton.layer.cornerRadius = 20.0
self.getCodeButton.clipsToBounds = false
getCodeButton.addTarget(self, action: #selector(onTapGet), for: .touchUpInside)
self.addSubview(getCodeButton)
numberSectionStack.axis = .vertical
numberSectionStack.alignment = .fill
numberSectionStack.distribution = .fill
self.yourNumberLabel.text = "Какой ваш номер телефона?"
self.yourNumberLabel.textColor = .black
self.yourNumberLabel.font = .boldSystemFont(ofSize: 20)
self.yourCodeLabel.text = "Введите код из СМС-сообщения"
self.numberFPNTextField.keyboardType = .numberPad
self.numberFPNTextField.borderStyle = .roundedRect
self.numberFPNTextField.displayMode = .list
self.numberFPNTextField.text = defaultNumber
self.verificationCodeTextField.keyboardType = .numberPad
self.verificationCodeTextField.borderStyle = .roundedRect
self.verificationCodeTextField.isHidden = true
listController.setup(repository: numberFPNTextField.countryRepository)
listController.didSelect = {[weak self] country in
self?.numberFPNTextField.setFlag(countryCode: country.code)
}
self.numberWasRegisteredLabel.text = "Этот номер уже используется."
self.verificationWasFailed.text = "Ошибка верефикации."
self.numberSectionStack.addArrangedSubview(yourNumberLabel)
self.numberSectionStack.addArrangedSubview(numberFPNTextField)
self.numberSectionStack.addArrangedSubview(numberWasRegisteredLabel)
self.numberSectionStack.addArrangedSubview(yourCodeLabel)
self.numberSectionStack.addArrangedSubview(verificationCodeTextField)
self.numberSectionStack.addArrangedSubview(verificationWasFailed)
self.addSubview(numberSectionStack)
self.nextButton.setTitle("Далее", for: .normal)
self.nextButton.backgroundColor = .black
self.nextButton.setTitleColor(.white, for: .normal)
self.nextButton.layer.cornerRadius = 20.0
self.nextButton.alpha = 0
self.nextButton.isEnabled = false
self.nextButton.clipsToBounds = false
nextButton.addTarget(self, action: #selector(onTapNext), for: .touchUpInside)
addSubview(nextButton)
}
override func setupConstraints() {
super.setupConstraints()
let margins = layoutMarginsGuide
NSLayoutConstraint.activate([
numberFPNTextField.heightAnchor.constraint(equalToConstant: textFieldHeight),
verificationCodeTextField.heightAnchor.constraint(equalToConstant: textFieldHeight),
numberSectionStack.topAnchor.constraint(equalTo: margins.topAnchor, constant: 20.0),
numberSectionStack.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: 0.0),
numberSectionStack.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant: 0.0),
getCodeButton.topAnchor.constraint(
equalTo: self.numberSectionStack.bottomAnchor,
constant: 20.0),
getCodeButton.centerXAnchor.constraint(equalTo: self.numberSectionStack.centerXAnchor),
getCodeButton.heightAnchor.constraint(equalToConstant: 50),
getCodeButton.widthAnchor.constraint(equalToConstant: 200.0),
nextButton.topAnchor.constraint(
equalTo: self.getCodeButton.bottomAnchor,
constant: 20.0
),
nextButton.heightAnchor.constraint(equalToConstant: 50),
nextButton.widthAnchor.constraint(equalToConstant: 150.0),
nextButton.centerXAnchor.constraint(equalTo: numberSectionStack.centerXAnchor)
])
}
@objc private func onTapNext() {
let phoneNumber = numberFPNTextField.getFormattedPhoneNumber(format: .International)
onTapNextButton?(phoneNumber)
}
@objc private func onTapGet() {
let phoneNumber = self.numberFPNTextField.getFormattedPhoneNumber(format: .International)
self.onTapGetButton?(phoneNumber)
}
}
|
// MIT License
//
// Copyright (c) 2019 Lorenzo Villani
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
public extension String {
/// Calculates the Levenshtein distance to another string. The semantic is the same as
/// `distanceTo' but the result is returned as a normalized value between 0.0 and 1.0.
///
/// - parameter other: The string we are calculating the distance to.
/// - parameter minLikeness: The minimum acceptable likeness, in a range between 0.0 and 1.0.
/// Values outside the range are interpreted as 0.0.
public func likenessTo(_ other: String, minLikeness: Float = 0.0) -> Float {
let countSelf = self.count
let countOther = other.count
let countMax = Float(max(countSelf, countOther))
let distance: Int
if minLikeness <= 0.0 || minLikeness > 1.0 {
// Fast path
distance = self.distanceTo(other)
} else {
distance = self.distanceTo(other, maxDistance: Int(countMax * (1.0 - minLikeness)))
}
return 1.0 - Float(distance) / countMax
}
/// Calculates the Levenshtein distance to another string.
///
/// - parameter other: The string we are calculating the distance to.
/// - parameter maxDistance: The maximum acceptable distance. Zero means no limit.
///
/// - returns: The edit distance between strings. If ``maxDistance`` is not zero the returned
/// value is eventually clamped to the value of ``maxDistance``.
public func distanceTo(_ other: String, maxDistance: Int = 0) -> Int {
// Minor optimization, let's avoid calling count() too many times.
let countSelf = self.count
let countOther = other.count
// If either string is of length zero, the distance is the length of the other string.
if countSelf == 0 {
return countOther
} else if countOther == 0 {
return countSelf
}
// The starting distance is the difference in length between the two strings.
var distance = abs(countSelf - countOther)
// Stop early if we already reached the maximum acceptable distance.
if maxDistance > 0 && distance >= maxDistance {
return distance
}
// Save the starting position so that we can increment it later without using advance()
// which is O(N) for Strings.
var posSelf = self.startIndex
var posOther = other.startIndex
// Iterate only over the character set common to both substrings, since all subsequent
// characters are automatically different and count as edit distance.
for _ in 0...min(countSelf, countOther) - 1 {
if self[posSelf] != other[posOther] {
distance += 1
}
// Early termination in case we reach the maximum acceptable distance.
if maxDistance > 0 && distance >= maxDistance {
return distance
}
// Advance to the next character.
posSelf = self.index(after: posSelf)
posOther = other.index(after: posOther)
}
return distance
}
}
|
//
// HOTPCodeView.swift
// Oak
//
// Created by Alex Catchpole on 07/02/2021.
//
import Foundation
import SwiftUI
import Resolver
struct HOTPCodeView: View {
@StateObject var viewModel: HOTPCodeViewModel = Resolver.resolve()
let hasCopied: Bool
let account: Account
init(hasCopied: Bool, account: Account) {
self.hasCopied = hasCopied
self.account = account
}
var body: some View {
HStack {
Text(hasCopied ? "Copied" : viewModel.code)
.font(Font.system(.subheadline, design: .monospaced).monospacedDigit())
.transition(.opacity)
.id(viewModel.code)
.foregroundColor(.primary)
Button {
viewModel.generateCode(increment: true)
} label: {
Text("Next").font(.system(.caption)).padding(6)
}
.disabled(hasCopied)
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke(Color.accentColor, lineWidth: 1)
)
}
.onAppear {
viewModel.setAccount(account: account)
viewModel.generateCode(increment: false)
}
}
}
|
//
// SourceCollectionController
// DemoChartOSX
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// Copyright © 2017 thierry Hentic.
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
import Cocoa
class SourceCollectionController: NSViewController {
@IBOutlet weak var collectionView: NSCollectionView!
var mainWindowController: MainWindowController?
fileprivate var imageInfos = [ImageInfo]()
fileprivate(set) var numberOfSections = 1
var singleSectionMode = false
fileprivate struct SectionAttributes {
var sectionOffset: Int // the index of the first image of this section in the imageFiles array
var sectionLength: Int // number of images in the section
var sectionName : String
}
// sectionLengthArray - An array of picked integers.
fileprivate var sectionLengthArray = [Int]()
fileprivate var sectionsAttributesArray = [SectionAttributes]()
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
configureCollectionView()
}
func registerPlotItem( imageInfo : [ImageInfo])
{
if imageInfos.count > 0 { // When not initial folder
imageInfos.removeAll()
}
imageInfos = imageInfo
setupData()
}
fileprivate func configureCollectionView() {
let flowLayout = NSCollectionViewFlowLayout()
flowLayout.itemSize = NSSize(width: 140.0, height: 120.0)
flowLayout.sectionInset = EdgeInsets(top: 30.0, left: 20.0, bottom: 30.0, right: 20.0)
flowLayout.minimumInteritemSpacing = 5.0
flowLayout.minimumLineSpacing = 5.0
flowLayout.sectionHeadersPinToVisibleBounds = true
collectionView.collectionViewLayout = flowLayout
view.wantsLayer = true
collectionView.layer?.backgroundColor = NSColor.black.cgColor
}
func setupData()
{
if sectionsAttributesArray.count > 0 { // If not first time, clean old sectionsAttributesArray
sectionsAttributesArray.removeAll()
}
numberOfSections = 1
if singleSectionMode {
setupDataForSingleSectionMode()
} else {
setupDataForMultiSectionMode()
}
}
fileprivate func setupDataForSingleSectionMode() {
let sectionAttributes = SectionAttributes(sectionOffset: 0, sectionLength: imageInfos.count, sectionName: "")
sectionsAttributesArray.append(sectionAttributes) // sets up attributes for first section
}
fileprivate func setupDataForMultiSectionMode() {
let arrayFromDic = Array(imageInfos.map{ $0.type.label })
var counts: [String: Int] = [:]
for item in arrayFromDic {
counts[item] = (counts[item] ?? 0) + 1
}
let countsSorted = counts.sorted(by: { $0.0 < $1.0 })
sectionLengthArray.removeAll()
for countSorted in countsSorted
{
sectionLengthArray.append(countSorted.value)
}
let haveOneSection = singleSectionMode || sectionLengthArray.count < 2 || imageInfos.count <= sectionLengthArray[0]
var realSectionLength = haveOneSection ? imageInfos.count : sectionLengthArray[0]
var sectionAttributes = SectionAttributes(sectionOffset: 0, sectionLength: realSectionLength, sectionName: imageInfos[0].type.label)
sectionsAttributesArray.append(sectionAttributes) // sets up attributes for first section
guard !haveOneSection else {return}
var offset: Int
var nextOffset: Int
let maxNumberOfSections = sectionLengthArray.count
for i in 1..<maxNumberOfSections {
numberOfSections += 1
offset = sectionsAttributesArray[i-1].sectionOffset + sectionsAttributesArray[i-1].sectionLength
nextOffset = offset + sectionLengthArray[i]
if imageInfos.count <= nextOffset {
realSectionLength = imageInfos.count - offset
nextOffset = -1 // signal this is last section for this collection
} else {
realSectionLength = sectionLengthArray[i]
}
let sectionName = imageInfos[offset].type.label
sectionAttributes = SectionAttributes(sectionOffset: offset, sectionLength: realSectionLength, sectionName: sectionName)
sectionsAttributesArray.append(sectionAttributes)
if nextOffset < 0 {
break
}
}
}
func numberOfItemsInSection(_ section: Int) -> Int {
return sectionsAttributesArray[section].sectionLength
}
func imageFileForIndexPath(_ indexPath: IndexPath) -> ImageInfo {
let imageIndexInImageFiles = sectionsAttributesArray[indexPath.section].sectionOffset + indexPath.item
let imageInfo = imageInfos[imageIndexInImageFiles]
return imageInfo
}
@IBAction func showHideSections(_ sender: NSButton) {
let show = sender.state
singleSectionMode = (show == NSOffState)
setupData()
collectionView.reloadData()
}
}
extension SourceCollectionController : NSCollectionViewDelegate
{
func collectionView (_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>)
{
guard let indexPath = indexPaths.first else {
return
}
// 3
guard let item = collectionView.item(at: indexPath) else {
return
}
(item as! CollectionViewItem).setHighlight(selected: true)
print(item)
let nameController = (item as! CollectionViewItem).imageInfo?.nameController
let array = Array(indexPaths)
print("Allows multiple selection:", collectionView.allowsMultipleSelection)
print("Number of selected items:", collectionView.selectionIndexPaths.count)
print(indexPaths)
print(array[0])
print("")
mainWindowController?.changeView(name: nameController!)
}
func highlightItems( selected: Bool, atIndexPaths: Set<IndexPath>) {
for indexPath in atIndexPaths {
guard let item = collectionView.item(at: indexPath as IndexPath) else {continue}
(item as! CollectionViewItem).setHighlight(selected: selected)
}
}
}
extension SourceCollectionController : NSCollectionViewDataSource {
func numberOfSections(in collectionView: NSCollectionView) -> Int {
return numberOfSections
}
func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
print ("numberOfItemsInSection : ", numberOfItemsInSection(section))
return numberOfItemsInSection(section)
}
func collectionView(_ itemForRepresentedObjectAtcollectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let item = collectionView.makeItem(withIdentifier: "CollectionViewItem", for: indexPath)
guard let collectionViewItem = item as? CollectionViewItem else {return item}
let imageInfo = imageFileForIndexPath(indexPath)
collectionViewItem.imageInfo = imageInfo
return item
}
func collectionView(_ collectionView: NSCollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> NSView {
let view = collectionView.makeSupplementaryView(ofKind: NSCollectionElementKindSectionHeader, withIdentifier: "HeaderView", for: indexPath) as! HeaderView
view.sectionTitle.stringValue = "\(sectionsAttributesArray[indexPath.section].sectionName)"
let nbOfItemsInSection = self.numberOfItemsInSection(indexPath.section)
view.imageCount.stringValue = "\(nbOfItemsInSection) chart(s)"
return view
}
}
extension SourceCollectionController : NSCollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> NSSize {
return singleSectionMode ? NSZeroSize : NSSize(width: 1000, height: 40)
}
}
|
//
// GenericItemStub.swift
// SailingThroughHistory
//
// Created by henry on 13/4/19.
// Copyright © 2019 Sailing Through History Team. All rights reserved.
//
import Foundation
class GenericItemStub: GenericItem {
let name: String
var itemParameter: ItemParameter
var weight: Int {
return itemParameter.unitWeight * quantity
}
var quantity: Int
var isAvailableAtPort = true
var doesItemDecay = true
var buyValue = 100
var sellValue = 100
init(name: String, itemParameter: ItemParameter, quantity: Int) {
self.name = name
self.itemParameter = itemParameter
self.quantity = quantity
}
func setItemParameter(_ itemParameter: ItemParameter) {
}
func combine(with item: inout GenericItem) -> Bool {
return true
}
func remove(amount: Int) -> Int {
guard quantity >= amount else {
let deficit = amount - quantity
quantity = 0
return deficit
}
quantity -= amount
return 0
}
func setQuantity(quantity: Int) {
self.quantity = quantity
}
func getBuyValue(at port: Port) -> Int? {
return buyValue
}
func sell(at port: Port) -> Int? {
return sellValue
}
func copy() -> GenericItemStub {
let newCopy = GenericItemStub(name: name, itemParameter: itemParameter, quantity: quantity)
newCopy.itemParameter = itemParameter
newCopy.isAvailableAtPort = isAvailableAtPort
newCopy.doesItemDecay = doesItemDecay
newCopy.buyValue = buyValue
newCopy.sellValue = sellValue
return newCopy
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.