text stringlengths 8 1.32M |
|---|
//
// main.swift
// 34
//
// Created by cyzone on 2020/12/1.
//
import Foundation
/// 34.给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
//如果数组中不存在目标值 target,返回 [-1, -1]。
//进阶:
//你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗?
//示例 1:
//输入:nums = [5,7,7,8,8,10], target = 8
//输出:[3,4]
//第一眼,暴力 第二眼:有序,logn --二分
func searchRange(_ nums: [Int], _ target: Int) -> [Int] {
var left = 0
let n = nums.count
var right = n - 1
while left <= right {
let mid = left + ((right - left) >> 1)
if nums[mid] == target {
//相等 可能左边和右边有
left = mid
right = mid
while left > 0, nums[left - 1] == nums[left]{
//左边和目标相等就左移,直到不相等为止
left = left - 1
}
while right < n - 1, nums[right] == nums[right + 1] {
//右边和目标相等就右移,直到不相等为止
right = right + 1
}
//查找到结果
return [left,right]
} else if nums[mid] > target {
//中间大于目标 那么目标肯定在左边的区间范围,改变右
right = mid - 1
} else {
//中间小于目标 那么目标肯定在右边的区间范围,改变左
left = mid + 1
}
}
return [-1,-1]
}
print(searchRange([5,7,7,8,8,10], 8))
print(searchRange([5,7,7,8,8,10], 6))
print(searchRange([], 1))
|
//
// AcronymsNetworkService.swift
// Acronyms
//
// Created by Douglas Poveda on 28/04/21.
//
import Foundation
class AcronymsNetworkService: AcronymsService {
func getAcronyms(parameters: GetAcronymsParameters,
completion: @escaping GetAcronymsHandler) {
do {
let request =
try NetworkRouter.getAcronyms(parameters: parameters)
.asURLRequest()
let service = NetworkService(with: request)
service.getAcronyms { result in
completion(result)
}
} catch {
completion(.failure(.unexpectedError))
}
}
}
|
//
// main.swift
// calc
//
// Created by Lahiru Ranasinghe on 5/4/19.
// Copyright © 2019 UTS. All rights reserved.
//
import Foundation
var args = ProcessInfo.processInfo.arguments
args.removeFirst() // remove the name of the program
func main(_ args : [String]){
var checker = InputChecker(expression: args)
do {
//validate input
//if there is any error, Error will be thrown
let isValid = try checker.isValidExpression()
if(isValid){
//calculate expression
var calculate = Calculator(expression: args)
let result = try calculate.calculateExpression()
print(result)
exit(0)
}
}catch CalcErrors.divisionByZero {
print("Cannot Devide by Zero")
exit(1)
}catch CalcErrors.invalidExpression {
print("Invalid expression. Expected input of the form number operation number .. 2 + 3")
exit(1)
}catch CalcErrors.invalidNumber(let number) {
print("Invalid number input found: \(number)")
exit(1)
}catch CalcErrors.invalidOperator(let character) {
print("Invalid operator input found: \(character)")
exit(1)
} catch {
print("Error \(error)")
exit(1)
}
}
main(args)
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Sequence {
/// Implementation for min(count:areInIncreasingOrder:)
@inlinable
internal func _minImplementation(
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
var iterator = makeIterator()
var result: [Element] = []
result.reserveCapacity(count)
while result.count < count, let e = iterator.next() {
result.append(e)
}
try result.sort(by: areInIncreasingOrder)
while let e = iterator.next() {
// To be part of `result`, `e` must be strictly less than `result.last`.
guard try areInIncreasingOrder(e, result.last!) else { continue }
let insertionIndex =
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
assert(insertionIndex != result.endIndex)
result.removeLast()
result.insert(e, at: insertionIndex)
}
return result
}
/// Implementation for max(count:areInIncreasingOrder:)
@inlinable
internal func _maxImplementation(
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
var iterator = makeIterator()
var result: [Element] = []
result.reserveCapacity(count)
while result.count < count, let e = iterator.next() {
result.append(e)
}
try result.sort(by: areInIncreasingOrder)
while let e = iterator.next() {
// To be part of `result`, `e` must be greater/equal to `result.first`.
guard try !areInIncreasingOrder(e, result.first!) else { continue }
let insertionIndex =
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
assert(insertionIndex > 0)
// Inserting `e` and then removing the first element (or vice versa)
// would perform a double shift, so we manually shift down the elements
// before dropping `e` in.
var i = 1
while i < insertionIndex {
result[i - 1] = result[i]
i += 1
}
result[insertionIndex - 1] = e
}
return result
}
/// Returns the smallest elements of this sequence, as sorted by the given
/// predicate.
///
/// This example partially sorts an array of integers to retrieve its three
/// smallest values:
///
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
/// let smallestThree = numbers.min(count: 3, sortedBy: <)
/// // [1, 2, 3]
///
/// If you need to sort a sequence but only need to access its smallest
/// elements, using this method can give you a performance boost over sorting
/// the entire sequence. The order of equal elements is guaranteed to be
/// preserved.
///
/// - Parameters:
/// - count: The number of elements to return. If `count` is greater than
/// the number of elements in this sequence, all of the sequence's
/// elements are returned.
/// - areInIncreasingOrder: A predicate that returns `true` if its
/// first argument should be ordered before its second argument;
/// otherwise, `false`.
/// - Returns: An array of the smallest `count` elements of this sequence,
/// sorted according to `areInIncreasingOrder`.
///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// sequence and *k* is `count`.
@inlinable
public func min(
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
precondition(count >= 0, """
Cannot find a minimum with a negative count of elements!
"""
)
// Do nothing if we're prefixing nothing.
guard count > 0 else {
return []
}
return try _minImplementation(count: count, sortedBy: areInIncreasingOrder)
}
/// Returns the largets elements of this sequence, as sorted by the given
/// predicate.
///
/// This example partially sorts an array of integers to retrieve its three
/// largest values:
///
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
/// let smallestThree = numbers.max(count: 3, sortedBy: <)
/// // [7, 8, 9]
///
/// If you need to sort a sequence but only need to access its largest
/// elements, using this method can give you a performance boost over sorting
/// the entire sequence. The order of equal elements is guaranteed to be
/// preserved.
///
/// - Parameters:
/// - count: The number of elements to return. If `count` is greater than
/// the number of elements in this sequence, all of the sequence's
/// elements are returned.
/// - areInIncreasingOrder: A predicate that returns `true` if its
/// first argument should be ordered before its second argument;
/// otherwise, `false`.
/// - Returns: An array of the largest `count` elements of this sequence,
/// sorted according to `areInIncreasingOrder`.
///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// sequence and *k* is `count`.
@inlinable
public func max(
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
precondition(count >= 0, """
Cannot find a maximum with a negative count of elements!
"""
)
// Do nothing if we're suffixing nothing.
guard count > 0 else {
return []
}
return try _maxImplementation(count: count, sortedBy: areInIncreasingOrder)
}
}
extension Sequence where Element: Comparable {
/// Returns the smallest elements of this sequence.
///
/// This example partially sorts an array of integers to retrieve its three
/// smallest values:
///
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
/// let smallestThree = numbers.min(count: 3)
/// // [1, 2, 3]
///
/// If you need to sort a sequence but only need to access its smallest
/// elements, using this method can give you a performance boost over sorting
/// the entire sequence. The order of equal elements is guaranteed to be
/// preserved.
///
/// - Parameter count: The number of elements to return. If `count` is greater
/// than the number of elements in this sequence, all of the sequence's
/// elements are returned.
/// - Returns: An array of the smallest `count` elements of this sequence.
///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// sequence and *k* is `count`.
@inlinable
public func min(count: Int) -> [Element] {
return min(count: count, sortedBy: <)
}
/// Returns the largest elements of this sequence.
///
/// This example partially sorts an array of integers to retrieve its three
/// largest values:
///
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
/// let smallestThree = numbers.max(count: 3)
/// // [7, 8, 9]
///
/// If you need to sort a sequence but only need to access its largest
/// elements, using this method can give you a performance boost over sorting
/// the entire sequence. The order of equal elements is guaranteed to be
/// preserved.
///
/// - Parameter count: The number of elements to return. If `count` is greater
/// than the number of elements in this sequence, all of the sequence's
/// elements are returned.
/// - Returns: An array of the largest `count` elements of this sequence.
///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// sequence and *k* is `count`.
@inlinable
public func max(count: Int) -> [Element] {
return max(count: count, sortedBy: <)
}
}
extension Collection {
/// Returns the smallest elements of this collection, as sorted by the given
/// predicate.
///
/// This example partially sorts an array of integers to retrieve its three
/// smallest values:
///
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
/// let smallestThree = numbers.min(count: 3, sortedBy: <)
/// // [1, 2, 3]
///
/// If you need to sort a collection but only need to access its smallest
/// elements, using this method can give you a performance boost over sorting
/// the entire collection. The order of equal elements is guaranteed to be
/// preserved.
///
/// - Parameters:
/// - count: The number of elements to return. If `count` is greater than
/// the number of elements in this collection, all of the collection's
/// elements are returned.
/// - areInIncreasingOrder: A predicate that returns `true` if its
/// first argument should be ordered before its second argument;
/// otherwise, `false`.
/// - Returns: An array of the smallest `count` elements of this collection,
/// sorted according to `areInIncreasingOrder`.
///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// collection and *k* is `count`.
@inlinable
public func min(
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
precondition(count >= 0, """
Cannot find a minimum with a negative count of elements!
"""
)
// Do nothing if we're prefixing nothing.
guard count > 0 else {
return []
}
// Make sure we are within bounds.
let prefixCount = Swift.min(count, self.count)
// If we're attempting to prefix more than 10% of the collection, it's
// faster to sort everything.
guard prefixCount < (self.count / 10) else {
return Array(try sorted(by: areInIncreasingOrder).prefix(prefixCount))
}
return try _minImplementation(count: count, sortedBy: areInIncreasingOrder)
}
/// Returns the largets elements of this collection, as sorted by the given
/// predicate.
///
/// This example partially sorts an array of integers to retrieve its three
/// largest values:
///
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
/// let smallestThree = numbers.max(count: 3, sortedBy: <)
/// // [7, 8, 9]
///
/// If you need to sort a collection but only need to access its largest
/// elements, using this method can give you a performance boost over sorting
/// the entire collection. The order of equal elements is guaranteed to be
/// preserved.
///
/// - Parameters:
/// - count: The number of elements to return. If `count` is greater than
/// the number of elements in this collection, all of the collection's
/// elements are returned.
/// - areInIncreasingOrder: A predicate that returns `true` if its
/// first argument should be ordered before its second argument;
/// otherwise, `false`.
/// - Returns: An array of the largest `count` elements of this collection,
/// sorted according to `areInIncreasingOrder`.
///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// collection and *k* is `count`.
@inlinable
public func max(
count: Int,
sortedBy areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> [Element] {
precondition(count >= 0, """
Cannot find a maximum with a negative count of elements!
"""
)
// Do nothing if we're suffixing nothing.
guard count > 0 else {
return []
}
// Make sure we are within bounds.
let suffixCount = Swift.min(count, self.count)
// If we're attempting to prefix more than 10% of the collection, it's
// faster to sort everything.
guard suffixCount < (self.count / 10) else {
return Array(try sorted(by: areInIncreasingOrder).suffix(suffixCount))
}
return try _maxImplementation(count: count, sortedBy: areInIncreasingOrder)
}
}
extension Collection where Element: Comparable {
/// Returns the smallest elements of this collection.
///
/// This example partially sorts an array of integers to retrieve its three
/// smallest values:
///
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
/// let smallestThree = numbers.min(count: 3)
/// // [1, 2, 3]
///
/// If you need to sort a collection but only need to access its smallest
/// elements, using this method can give you a performance boost over sorting
/// the entire collection. The order of equal elements is guaranteed to be
/// preserved.
///
/// - Parameter count: The number of elements to return. If `count` is greater
/// than the number of elements in this collection, all of the collection's
/// elements are returned.
/// - Returns: An array of the smallest `count` elements of this collection.
///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// collection and *k* is `count`.
@inlinable
public func min(count: Int) -> [Element] {
return min(count: count, sortedBy: <)
}
/// Returns the largest elements of this collection.
///
/// This example partially sorts an array of integers to retrieve its three
/// largest values:
///
/// let numbers = [7, 1, 6, 2, 8, 3, 9]
/// let smallestThree = numbers.max(count: 3)
/// // [7, 8, 9]
///
/// If you need to sort a collection but only need to access its largest
/// elements, using this method can give you a performance boost over sorting
/// the entire collection. The order of equal elements is guaranteed to be
/// preserved.
///
/// - Parameter count: The number of elements to return. If `count` is greater
/// than the number of elements in this collection, all of the collection's
/// elements are returned.
/// - Returns: An array of the largest `count` elements of this collection.
///
/// - Complexity: O(*k* log *k* + *nk*), where *n* is the length of the
/// collection and *k* is `count`.
@inlinable
public func max(count: Int) -> [Element] {
return max(count: count, sortedBy: <)
}
}
|
//
// BaseAPIResponse.swift
// VechicleTracker
//
// Created by vineeth on 6/13/18.
// Copyright © 2018 vineeth. All rights reserved.
//
import UIKit
class BaseAPIResponse: BaseMappableModel {
var status: Bool?
var message: String?
override func mapping(map: Map) {
super.mapping(map: map)
self.status <- map["status"]
self.message <- map["message"]
}
func getAPIError() -> BaseAPIError {
var error: BaseAPIError
if status != nil {
if status == true {
error = APIErrorTypeNone()
error.message = message
return error
}
error = APIErrorTypeResponse()
error.message = "Error in response."
if message != nil {
error.message = message
}
return error
}
error = APIErrorTypeResponse()
error.message = BaseAPIError.getMessageForErrorType(apiError: error)
return error
}
}
|
//
// ShareInfoPatientAlert.swift
// HISmartPhone
//
// Created by Huỳnh Công Thái on 1/19/18.
// Copyright © 2018 MACOS. All rights reserved.
//
import UIKit
class ShareInfoPatientAlert: BaseAlertViewController {
// MARK: Define variable
var patientBeShared: PatientBeShared? {
willSet {
guard let value = newValue else {
return
}
self.shareInfoPatientAlertView.setValue(patientBeShared: value)
}
}
// MARK: Define controls
private let shareInfoPatientAlertView = ShareInfoPatientAlertView()
// MARK: Setup UI
override func setupView() {
self.setupAlertView()
}
private func setupAlertView() {
self.view.addSubview(self.shareInfoPatientAlertView)
self.shareInfoPatientAlertView.snp.makeConstraints { (make) in
make.centerY.equalToSuperview()
make.left.equalToSuperview().offset(Dimension.shared.largeHorizontalMargin_32)
make.right.equalToSuperview().offset(-Dimension.shared.largeHorizontalMargin_32)
make.height.lessThanOrEqualToSuperview()
}
self.shareInfoPatientAlertView.delegate = self
}
override func dismissAlert() {
self.dismiss(animated: true) {
BeSharedManager.share.isShow = false
}
}
}
// MARK: Extension
extension ShareInfoPatientAlert: ShareInfoPatientAlertViewDelegate {
func handleCloseAlert() {
self.dismissAlert()
}
}
|
//
// URLSession+DataTask.swift
// GIPHYTags
//
// Created by David S Reich on 9/12/19.
// Copyright © 2020 Stellar Software Pty Ltd. All rights reserved.
//
import Foundation
extension URLSession {
class func urlSessionDataTask(urlString: String,
mimeType: String,
not200Handler: HTTPURLResponseNot200? = nil,
completion: @escaping (DataResult) -> Void) -> URLSessionDataTask? {
guard let url = URL(string: urlString) else {
print("Cannot make URL")
completion(.failure(.badURL))
return nil
}
//using an URLRequest object is not necessary in this usage
let dataTask = URLSession.shared.dataTask(with: url) { data, response, error in
HTTPURLResponse.validateData(data: data,
response: response,
error: error,
mimeType: mimeType,
not200Handler: not200Handler,
completion: completion)
}
dataTask.resume()
return dataTask
}
}
|
//
// UIImage+Size.swift
// Fakestagram
//
// Created by Jeremy Robinson on 11/1/18.
// Copyright © 2018 Jeremy Robinson. All rights reserved.
//
import UIKit
extension UIImage {
var aspectHeight: CGFloat {
let heightRatio = size.height / 736
let widthRatio = size.width / 414
let aspectRatio = fmax(heightRatio,widthRatio)
return size.height / aspectRatio
}
}
|
import XCTest
import Nimble
import Quick
@testable import JacKit
class JackLoggingSpec: QuickSpec { override func spec() {
let jack = Jack().set(level: .verbose)
// MARK: Scope
it("error") {
jack.error("error message", format: .short)
}
it("warn") {
jack.warn("warn message", format: .bare)
}
it("info") {
jack.info("info message", format: .compact)
}
it("debug") {
jack.debug("debug message", format: .noLocation)
}
it("verbose") {
jack.verbose("verbose message", format: .noScope)
}
it("assert") {
#if DEBUG
expect {
jack.assert(true, "message")
}.notTo(throwAssertion())
expect {
jack.assert(false, "message")
}.to(throwAssertion())
#else
expect {
jack.assert(true, "message")
}.toNot(throwAssertion())
expect {
jack.assert(false, "message")
}.toNot(throwAssertion())
#endif
}
it("failure") {
#if DEBUG
expect {
jack.failure("message")
}.to(throwAssertion())
#else
expect {
jack.failure("message")
}.toNot(throwAssertion())
#endif
}
} }
|
//
// Observer.swift
//
// Copyright © 2017-2022 Doug Russell. All rights reserved.
//
import Asynchrone
import Cocoa
public protocol Observer {
associatedtype ObserverElement: Element
typealias ObserverAsyncSequence = SharedAsyncSequence<AsyncStream<ObserverNotification<ObserverElement>>>
func start() async throws
func stop() async throws
// Hopefully we can eventually make the return type here
// some AsyncSequence where Element == ObserverNotification<ObserverElement>>
func stream(
element: ObserverElement,
notification: NSAccessibility.Notification
) async throws -> ObserverAsyncSequence
}
|
//
// Copyright © 2021 Tasuku Tozawa. All rights reserved.
//
public extension DarwinNotification.Name {
static let shareExtensionDidCompleteRequest = DarwinNotification.Name("net.tasuwo.TBoxCore.shareExtensionDidCompleteRequest")
}
|
//
// AppDelegate.swift
// WordBuzzer
//
// Created by Yotam Ohayon on 27/01/2018.
// Copyright © 2018 Yotam Ohayon. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private let dependencyInjector = DependencyInjector()
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
setupWindow()
return true
}
}
private extension AppDelegate {
func setupWindow() {
let window = UIWindow(frame: UIScreen.main.bounds)
window.makeKeyAndVisible()
self.window = window
let storyboard = self.dependencyInjector.storyboard
window.rootViewController = storyboard.instantiateInitialViewController()
}
}
|
//
// FlashCardDatabaseManager.swift
// Jouzu
//
// Created by Johann Diedrick on 4/2/15.
// Copyright (c) 2015 Johann Diedrick. All rights reserved.
//
import Foundation
let sharedInstance = FlashCardDatabaseManager()
class FlashCardDatabaseManager{
var database : FMDatabase? = nil
class var instance : FlashCardDatabaseManager{
let path = NSBundle.mainBundle().pathForResource("japanese", ofType:"sqlite")
println("path: \(path)")
sharedInstance.database = FMDatabase(path: path)
return sharedInstance
}
func addCallAndResponse()->Bool{
if !sharedInstance.database!.open(){
println("unable to open database")
return false
}else{
println("opened database")
let sql_stmt = "CREATE TABLE IF NOT EXISTS japanese (ID INTEGER PRIMARY KEY AUTOINCREMENT, call TEXT, response TEXT)"
if !sharedInstance.database!.executeStatements(sql_stmt) {
println("Error: \(sharedInstance.database!.lastErrorMessage())")
return false
}else{
sharedInstance.database!.close()
return true
}
}
}
func getCallAndResponse()->FMResultSet?{
var rs : FMResultSet
if !sharedInstance.database!.open(){
println("unable to open database")
return nil
}else{
if let rs = sharedInstance.database!.executeQuery("select call, response from japanese", withArgumentsInArray: nil) {
println(rs)
return rs
} else {
println("select failed: \(sharedInstance.database!.lastErrorMessage())")
return nil
}
}
}
} |
//
// BillFormUITests.swift
// Jenin ResidencesUITests
//
// Created by Ahmed Khalaf on 19/4/17.
// Copyright © 2017 pxlshpr. All rights reserved.
//
import XCTest
class BillFormUITests: XCTestCase, UITestable {
// let app = XCUIApplication()
override func setUp() {
super.setUp()
continueAfterFailure = false
app.launch()
}
override func tearDown() {
super.tearDown()
}
func testInputValidForm() {
app.buttons[UI.Welcome.login].tap()
app.cells[UI.Login.bypassLoginButton.accessibilityLabel].tap()
app.buttons[UI.Bills.new].tap()
fillForm(forTestCase: .Valid)
app.switches[UI.Bill.showDetailsSwitch.rawValue].tap()
dismissKeyboard()
assertFormValues(forTestCase: .Valid)
app.buttons[UI.Bill.saveButton.rawValue].tap()
//assert we're back on the list
//assert number of cells is what is expected
}
func _testEditBill() {
app.buttons[UI.Welcome.login].tap()
app.cells[UI.Login.bypassLoginButton.accessibilityLabel].tap()
refreshCells()
//#37
app.cells["13421"].tap()
sleep(10)
}
//MARK: - Helpers
private func assertFormValues(forTestCase testCase: TestCase) {
let cells: [UI.Bill] = [.unit, .previousDate, .currentDate]
for cell in cells {
assertCell(cell, forTestCase: testCase)
}
let textFields: [UI.Bill] = [.days, .previousReading, .currentReading, .consumption, .rate, .bandA, .bandB, .bandC, .fixedCharge, .surcharge, .otherCharges, .total]
for textField in textFields {
assertTextField(textField, forTestCase: testCase)
}
//#38
}
}
|
//
// ActivityCell.swift
// It Happened
//
// Created by Drew Lanning on 9/1/17.
// Copyright © 2017 Drew Lanning. All rights reserved.
//
import UIKit
import CoreData
import AVFoundation
class ActivityCell: UITableViewCell, AudioPlayer {
var audioPlayer: AVAudioPlayer?
@IBOutlet weak var activityTitleLbl: UILabel!
@IBOutlet weak var lastIncidentLbl: UILabel!
@IBOutlet weak var todayTotalLbl: UILabel!
@IBOutlet weak var todayTotalTimes: UILabel!
@IBOutlet weak var newIncidentBtn: IncrementButton!
@IBOutlet weak var animationView: UIView!
var addNewInstance: (() -> ())?
var swipe: UISwipeGestureRecognizer?
let generator = UINotificationFeedbackGenerator()
func styleViews() {
activityTitleLbl.textColor = Settings().colorTheme[.accent2]
lastIncidentLbl.textColor = Settings().colorTheme[.accent1]
todayTotalLbl.textColor = Settings().colorTheme[.accent2]
todayTotalTimes.textColor = Settings().colorTheme[.accent2]
self.backgroundColor = Settings().colorTheme[.background]
newIncidentBtn.tintColor = Settings().colorTheme[.accent1]
}
func configureCell(with activity: Activity) {
activityTitleLbl.text = activity.name
lastIncidentLbl.text = activity.lastInstance?.getColloquialDateAndTime()
setIncrementCounter(to: activity.getInstanceCount(forDate: Date()))
addNewInstance = { [weak self] in
activity.addNewInstance(withContext: DataManager().context)
self?.playSound(called: Sound.numberRise)
}
self.selectionStyle = .none
}
func setIncrementCounter(to count: Int) {
self.todayTotalLbl.text = "\(count)"
}
@IBAction func activityHappened(sender: IncrementButton) {
UIView.animate(withDuration: 0.0, delay: 0, options: .transitionCrossDissolve, animations: {
self.newIncidentBtn.setCheckImage()
self.generator.notificationOccurred(.success)
}, completion: { finished in
UIView.animate(withDuration: 0.4, delay: 0.2, animations: {
self.newIncidentBtn.alpha = 0.0
}, completion: { (finished) in
self.newIncidentBtn.setDefaultImage()
self.newIncidentBtn.alpha = 1.0
if let addNew = self.addNewInstance {
addNew()
DataManager().save()
}
})
})
}
override func willTransition(to state: UITableViewCellStateMask) {
if state == .showingDeleteConfirmationMask {
newIncidentBtn.isUserInteractionEnabled = false
} else {
newIncidentBtn.isUserInteractionEnabled = true
}
}
override func awakeFromNib() {
super.awakeFromNib()
styleViews()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func prepareForReuse() {
super.prepareForReuse()
styleViews()
}
// MARK: UIGesture methods
override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return true
}
}
|
//
// ContributorsListViewController.swift
// MyLeaderboard
//
// Created by Joseph Roque on 2019-08-23.
// Copyright © 2019 Joseph Roque. All rights reserved.
//
import UIKit
import FunctionalTableData
import myLeaderboardApi
class ContributorsListViewController: FTDViewController {
private static let contributors: [PlayerListItem] = [
PlayerListItem(
id: GraphID(rawValue: "0"),
displayName: "Joseph Roque",
username: "autoreleasefool",
avatar: "https://github.com/autoreleasefool.png"
),
PlayerListItem(
id: GraphID(rawValue: "1"),
displayName: "Mori Ahmadi",
username: "mori-ahk",
avatar: "https://github.com/mori-ahk.png"
),
]
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Contributors"
self.navigationItem.leftBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .done,
target: self,
action: #selector(finish)
)
let rows: [CellConfigType] = ContributorsListViewController.contributors.map { contributor in
return PlayerListItemCell(
key: "Contributor-\(contributor.id)",
style: CellStyle(highlight: true, accessoryType: .disclosureIndicator),
actions: CellActions(selectionAction: { [weak self] _ in
self?.openURL(URL(string: "https://github.com/\(contributor.username)"))
return .deselected
}),
state: PlayerListItemState(
displayName: contributor.displayName,
username: contributor.username,
avatar: contributor.qualifiedAvatar
),
cellUpdater: PlayerListItemState.updateView
)
}
let section = TableSection(key: "Contributors", rows: rows)
tableData.renderAndDiff([section])
}
private func openURL(_ url: URL?) {
guard let url = url, UIApplication.shared.canOpenURL(url) else { return }
UIApplication.shared.open(url)
}
@objc private func finish() {
dismiss(animated: true)
}
}
|
//
// ViewController.swift
// MultipleLayerArcMenu
//
// Copyright © 2018 personal. All rights reserved.
//
import UIKit
let MENU_OPTION_TITLE_KEY = "titleLabel"
let MENU_OPTION_IMAGE_KEY = "imageName"
class ViewController: UIViewController {
var _circularMenuVC : MultipleLayerArcMenu?
var arrayOfMenuButtons = [[[String : String]]]()
@IBOutlet weak var optionButton: UIButton!
override func viewDidLoad()
{
super.viewDidLoad()
arrayOfMenuButtons = [[[MENU_OPTION_TITLE_KEY : "A1"],[MENU_OPTION_TITLE_KEY : "B1"],[MENU_OPTION_TITLE_KEY : "C1"]],[[MENU_OPTION_TITLE_KEY : "A2"],[MENU_OPTION_TITLE_KEY : "B2"],[MENU_OPTION_TITLE_KEY : "C2"],[MENU_OPTION_TITLE_KEY : "D2"]],[[MENU_OPTION_TITLE_KEY : "A3"],[MENU_OPTION_TITLE_KEY : "B3"],[MENU_OPTION_TITLE_KEY : "C3"],[MENU_OPTION_TITLE_KEY : "D3"],[MENU_OPTION_TITLE_KEY : "D3"]]]
optionButton.layer.cornerRadius = optionButton.frame.size.width/2
optionButton.backgroundColor = UIColor.init(red: 255/255.0, green: 112/255.0, blue: 92/255.0, alpha: 1.0)
optionButton.tintColor = UIColor.white
optionButton.setTitle("Menu", for: .normal)
optionButton.setTitleColor(UIColor.white , for: .normal)
self.view.bringSubview(toFront: optionButton)
}
@IBAction func optionButtonTapped(_ sender: UIButton) {
self._circularMenuVC = MultipleLayerArcMenu.init(listOfButtonDetails: arrayOfMenuButtons, viewController: self, centerButtonFrame: self.optionButton.frame, circularButton: self.optionButton, startAngle: 95, totalAngle: 95, radius: -80)
self._circularMenuVC?._delegateSemiCircularMenu = self
self._circularMenuVC?.showMenuOption()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController : SemiCircularMenuDelegate
{
func SemiCircularMenuClickedButtonAtIndex(buttonIndex: Int, buttonOutlet: UIButton)
{
print("title text in button = \(buttonOutlet.titleLabel?.text ?? "") is tapped")
}
}
|
//
// SerieCharacterTableViewCell.swift
// URLSession
//
// Created by lpiem on 13/03/2020.
// Copyright © 2020 lpiem. All rights reserved.
//
import UIKit
class SerieCharacterTableViewCell: UITableViewCell {
private static let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .short
return formatter
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
}
required init?(coder: NSCoder) {
fatalError("init(coder: ) has not been implemented")
}
func configure(title: String, date: Date, imageURL: URL) {
textLabel?.text = title
detailTextLabel?.text = SerieCharacterTableViewCell.dateFormatter.string(from: date)
imageView?.image(from: imageURL)
}
}
|
/* =======================
- Jiffy -
made by Pawan Litt ©2016
==========================*/
import Foundation
import UIKit
import CloudKit
// CHANGE THE RED STRING BELOW ACCORDINGLY TO THE NAME YOU'LL GIVE TO YOUR OWN VERISON OF THIS APP
var APP_NAME = "Jiffy"
var categoriesArray = [
"Jobs",
"Real Estate",
"Services",
"Electronics",
"Vehicles",
"Shopping",
"Community",
"Pets",
"Free stuff"
// You can add more Categories here....
]
// IMPORTANT: Change the red string below with the path where you've stored the sendReply.php file (in this case we've stored it into a directory in our website called "Jiffy")
var PATH_TO_PHP_FILE = "http://www.jiffyClassifieds.com/jiffy/"
// IMPORTANT: You must replace the red email address below with the one you'll dedicate to Report emails from Users, in order to also agree with EULA Terms (Required by Apple)
let MY_REPORT_EMAIL_ADDRESS = "pawan.litt27@gmail.com"
// IMPORTANT: Replace the red string below with your own AdMob INTERSTITIAL's Unit ID
var ADMOB_UNIT_ID = "ca-app-pub-3011193616117520/4110419697"
// HUD View
let hudView = UIView(frame: CGRectMake(0, 0, 80, 80))
let indicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 80, 80))
extension UIViewController {
func showHUD() {
hudView.center = CGPointMake(view.frame.size.width/2, view.frame.size.height/2)
hudView.backgroundColor = UIColor(red: 250.0/255.0, green: 110.0/255.0, blue: 82.0/255.0, alpha: 1.0)
hudView.alpha = 0.9
hudView.layer.cornerRadius = hudView.bounds.size.width/2
indicatorView.center = CGPointMake(hudView.frame.size.width/2, hudView.frame.size.height/2)
indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.White
hudView.addSubview(indicatorView)
indicatorView.startAnimating()
view.addSubview(hudView)
}
func hideHUD() {
hudView.removeFromSuperview()
}
func simpleAlert(mess:String) {
UIAlertView(title: APP_NAME, message: mess, delegate: nil, cancelButtonTitle: "OK").show()
}
}
let publicDatabase = CKContainer.defaultContainer().publicCloudDatabase
let def = NSUserDefaults.standardUserDefaults()
var currentUsername = def.stringForKey("currentUsername")
var CurrentUser = CKRecord(recordType: USER_CLASS_NAME)
var reloadUser = Bool()
/* USER CLASS */
var USER_CLASS_NAME = "USERS_"
var USER_ID = "objectId"
var USER_USERNAME = "username"
var USER_PASSWORD = "password"
var USER_FULLNAME = "fullName"
var USER_PHONE = "phone"
var USER_EMAIL = "email"
var USER_WEBSITE = "website"
var USER_AVATAR = "avatar"
/* CLASSIFIEDS CLASS */
var CLASSIF_CLASS_NAME = "Classifieds"
var CLASSIF_ID = "objectId"
var CLASSIF_USER_POINTER = "userPointer" // User Pointer
var CLASSIF_TITLE = "title"
var CLASSIF_TITLE_LOWERCASE = "titleLowercase"
var CLASSIF_CATEGORY = "category"
var CLASSIF_ADDRESS = "address" // GeoPoint
var CLASSIF_ADDRESS_STRING = "addressString"
var CLASSIF_PRICE = "price"
var CLASSIF_DESCRIPTION = "description"
var CLASSIF_IMAGE1 = "image1" // File
var CLASSIF_IMAGE2 = "image2" // File
var CLASSIF_IMAGE3 = "image3" // File
var CLASSIF_CREATION_DATE = "creationDate"
var CLASSIF_MODIFICATION_DATE = "modificationDate"
/* FAVORITES CLASS */
var FAV_CLASS_NAME = "Favorites"
var FAV_USER_POINTER = "userPointer"
var FAV_AD_POINTER = "adPointer"
|
import Foundation
import SwaggerKit
enum SpecOAuthAuthorizationCodeFlowSeeds {
// MARK: - Type Properties
static let noScopesYAML = """
authorizationUrl: https://example.com/oauth/authorize
tokenUrl: https://example.com/oauth/token
scopes: {}
"""
static let noScopes = SpecOAuthAuthorizationCodeFlow(
authorizationURL: URL(string: "https://example.com/oauth/authorize")!,
tokenURL: URL(string: "https://example.com/oauth/token")!,
scopes: [:]
)
static let readWriteAppsYAML = """
authorizationUrl: https://example.com/oauth/authorize
tokenUrl: https://example.com/oauth/token
refreshUrl: https://example.com/oauth/token
scopes:
apps:read: Read app information
apps:write: Modify app information
x-private: true
"""
static let readWriteApps = SpecOAuthAuthorizationCodeFlow(
authorizationURL: URL(string: "https://example.com/oauth/authorize")!,
tokenURL: URL(string: "https://example.com/oauth/token")!,
refreshURL: URL(string: "https://example.com/oauth/token")!,
scopes: [
"apps:read": "Read app information",
"apps:write": "Modify app information"
],
extensions: ["private": true]
)
}
|
//
// SCSHomeNavController.swift
// leShou365
//
// Created by 张鹏 on 15/8/17.
// Copyright © 2015年 SmallCobblerStudio. All rights reserved.
//
import UIKit
class SCSHomeNavController: SCSBaseNavController {
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.barTintColor = UIColor.whiteColor()
//设置标题颜色
let navigationTitleAttribute : NSDictionary = NSDictionary(object: UIColor.costomGreen(),forKey: NSForegroundColorAttributeName)
navigationBar.titleTextAttributes = navigationTitleAttribute as? [String : AnyObject]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//https://www.hackingwithswift.com/books/ios-swiftui/creating-a-custom-component-with-binding
//@Bindingについて
//
//struct ContentView: View {
// @State private var rememberMe = false
//
// var body: some View {
// VStack {
// PushButton(title: "Remember Me", isOn: $rememberMe)
// Text(rememberMe ? "On" : "Off")
// }
// }
//}
//
//struct PushButton: View {
// let title: String
//// @State var isOn: Bool
// //@StateだとPushButton内部でしか値の変更が有効でない
// @Binding var isOn: Bool
// //@Bindingを使うとContentViewにも飛んでいく
//
// var onColors = [Color.red, Color.yellow]
// var offColors = [Color(white: 0.6), Color(white: 0.4)]
//
// var body: some View {
// Button(title) {
// self.isOn.toggle()
// }
// .padding()
// .background(LinearGradient(gradient: Gradient(colors: isOn ? onColors : offColors), startPoint: .top, endPoint: .bottom))
// .foregroundColor(.white)
// .clipShape(Capsule())
// .shadow(radius: isOn ? 0 : 5)
// }
//}
//https://www.hackingwithswift.com/books/ios-swiftui/using-size-classes-with-anyview-type-erasure
//AnyViewについて(どこでも使うとパフォーマンスが悪くなる)
//struct ContentView: View {
// @Environment(\.horizontalSizeClass) var sizeClass
//
// var body: some View {
// if sizeClass == .compact {
//// AnyView, which is what’s called a type erased wrapper.
//// Externally AnyView doesn’t expose what it contains – Swift sees our condition as returning either an AnyView or an AnyView, so it’s considered the same type.
// return AnyView(VStack {
// Text("Active size class:")
// Text("COMPACT")
// }
// .font(.largeTitle))
// } else {
// return AnyView(HStack {
// Text("Active size class:")
// Text("REGULAR")
// }
// .font(.largeTitle))
// }
// }
//}
//https://www.hackingwithswift.com/books/ios-swiftui/how-to-combine-core-data-and-swiftui
//Core Dataについて
//@Environment(\.managedObjectContext) var moc
//
//@FetchRequest(entity: Student.entity(), sortDescriptors: []) var students: FetchedResults<Student>
////a fetch request for our “Student” entity, applies no sorting, and places it into a property called students that has the the type FetchedResults<Student>.
//
//
// var body: some View {
// VStack {
// List {
// ForEach(students, id: \.id) { student in
// Text(student.name ?? "Unknown")
// }
// }
//
// Button("Add") {
// let firstNames = ["Ginny", "Harry", "Hermione", "Luna", "Ron"]
// let lastNames = ["Granger", "Lovegood", "Potter", "Weasley"]
//
// let chosenFirstName = firstNames.randomElement()!
// let chosenLastName = lastNames.randomElement()!
//
// let student = Student(context: self.moc)
// student.id = UUID()
// student.name = "\(chosenFirstName) \(chosenLastName)"
//
// try? self.moc.save()
// }
//
// }
// }
//}
//Cant Undestand
// https://www.hackingwithswift.com/books/ios-swiftui/adding-a-custom-star-rating-component
|
//
// AddView.swift
// GetupApp
//
// Created by 神村亮佑 on 2020/07/05.
// Copyright © 2020 神村亮佑. All rights reserved.
//
import SwiftUI
struct AddView: View {
let endTime = Calendar.current.date(byAdding: .hour,value: 24, to: Date())!
var timeFormatter: DateFormatter{
let formatter = DateFormatter()
formatter.timeStyle = .short
return formatter
}
@State private var gotobedTime = Date()
@State private var getupTime = Date()
var inputform: some View{
ZStack{
Color(#colorLiteral(red: 0.6229396462, green: 0.5232685804, blue: 0.9278500676, alpha: 1))
.edgesIgnoringSafeArea(.all)
VStack{
HStack {
VStack {
Text("Sleep Time")
.font(.callout)
.fontWeight(.bold)
Image("sleep")
.resizable()
.frame(width: 100, height: 100)
.foregroundColor(.white)
}.padding()
DatePicker("", selection: $gotobedTime,in: Date()...endTime, displayedComponents: .hourAndMinute)
.labelsHidden()
.frame(width: 150, height: 80, alignment: .center)
.clipped()
.padding(.vertical)
}.padding()
HStack {
VStack {
Text("Get up Time")
.font(.callout)
.fontWeight(.bold)
Image("rise")
.resizable()
.frame(width: 100, height: 100)
}.padding()
DatePicker("", selection: $getupTime, displayedComponents: .hourAndMinute)
.labelsHidden()
.frame(width: 150, height: 80, alignment: .center)
.clipped()
.padding(.vertical)
}
Button(action: {
print(self.getupTime)
}) {
Text("Input")
.font(.title)
.fontWeight(.light)
.padding()
.background(Color(#colorLiteral(red: 0.2940887213, green: 0.2941361666, blue: 0.2940783501, alpha: 1)))
.cornerRadius(30)
.foregroundColor(Color(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)))
.padding(10)
.overlay(
RoundedRectangle(cornerRadius: 20)
.stroke(Color(#colorLiteral(red: 0.2940887213, green: 0.2941361666, blue: 0.2940783501, alpha: 1)), lineWidth: 5)
)
}
}
}.cornerRadius(100)
}
var body: some View {
ZStack{
inputform
}
}
}
struct AddView_Previews: PreviewProvider {
static var previews: some View {
AddView().environment(\.locale, Locale(identifier: "ja_JP"))
}
}
|
//
// Item.swift
// SwiftUIBasicExample
//
// Created by Christian Quicano on 17/09/21.
//
import Foundation
struct Item: Identifiable {
let id: Int
let value: Int
}
|
//
// App Configurations.swift
// Rate Compare App
//
// Created by Jojo Destreza on 9/10/19.
// Copyright © 2019 Jojo Destreza. All rights reserved.
//
import UIKit
class AppConfig {
var url : String = "http://ratecompare.us-east-2.elasticbeanstalk.com" //"http://120.28.164.65/" // OA_RateCompareApi
}
|
import UIKit
import SVProgressHUD
import Cosmos
import Instructions
class DetailedHallController: UIViewController{
@IBOutlet weak var callView: UIView!
@IBOutlet weak var newRateView: UIView!
@IBOutlet weak var addressTextView: UITextView!
@IBOutlet weak var ratingStarsView: CosmosView!
@IBOutlet weak var favoriteImageView: UIImageView!
@IBOutlet weak var favoriteBackgroundView: UIView!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var collectionView1: UICollectionView!
@IBOutlet weak var infoTextView: UITextView!
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var offersTextView: UITextView!
@IBOutlet weak var ratesLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var locationView: UIView!
var detailedHall: Hall?
var favoriteDetailedHall: FavoriteHall?
var hallName: String?
var hallId: String?
var hallAddress: String?
var hallLocationLong: String?
var hallLocationLat: String?
var hallPhoneNumber: String?
var hallImages: [String] = []
let coachMarksController = CoachMarksController()
let coachMarksTitles: [String] = ["Add to favorite","Tap tp submit new rate","Show location on map","Call wedding hall directly"]
override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar()
setupComponents()
setupHallInfo()
SVProgressHUD.setupView()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if firstOpenDone() == false {
self.coachMarksController.start(in: .window(over: self))
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if firstOpenDone() == false {
finishCoachMark()
}
}
func setupComponents(){
collectionView1.delegate = self
collectionView1.dataSource = self
locationView.backgroundColor = UIColor.white
locationView.layer.cornerRadius = 15
locationView.layer.borderWidth = 1.5
locationView.layer.borderColor = UIColor.mainAppPink().cgColor
locationView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(viewOnMap)))
favoriteImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(addTofavoriteButtonAction)))
favoriteBackgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(addTofavoriteButtonAction)))
self.coachMarksController.dataSource = self
self.coachMarksController.overlay.color = UIColor.black.withAlphaComponent(0.6)
newRateView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(rateHalls)))
}
func setupHallInfo(){
if detailedHall != nil {
hallLocationLat = detailedHall?.hallLocationLat
hallLocationLong = detailedHall?.hallLocationLong
hallImages = (detailedHall?.hallImage)!
hallId = detailedHall?._id
hallPhoneNumber = detailedHall?.hallPhoneNumber
hallAddress = detailedHall?.hallAdress
hallName = detailedHall?.hallName
titleLabel.text = hallName
addressTextView.text = hallAddress
priceLabel.text = "\(Int(detailedHall?.hallPrice ?? 0)) EGP"
ratingStarsView.rating = Double(Int(detailedHall?.hallRate ?? 0))
ratesLabel.text = "(\(Int(detailedHall?.hallRatesCounter ?? 0))) Rating"
infoTextView.text = detailedHall?.hallDescription
offersTextView.text = detailedHall?.hallSpecialOffers
if detailedHall?.hallImage.count ?? 0 > 0 && detailedHall?.hallImage.isEmpty == false {
hallImages = (detailedHall?.hallImage)!
self.pageControl.numberOfPages = hallImages.count
self.pageControl.currentPage = 0
}
favoriteImageView.isHidden = false
favoriteBackgroundView.isHidden = false
}else if favoriteDetailedHall != nil {
hallLocationLat = favoriteDetailedHall?.hallId.hallLocationLat
hallLocationLong = favoriteDetailedHall?.hallId.hallLocationLong
hallImages = (favoriteDetailedHall?.hallId.hallImage)!
hallId = favoriteDetailedHall?.hallId._id
hallPhoneNumber = favoriteDetailedHall?.hallId.hallPhoneNumber
hallAddress = favoriteDetailedHall?.hallId.hallAdress
hallName = favoriteDetailedHall?.hallId.hallName
titleLabel.text = hallName
addressTextView.text = hallAddress
priceLabel.text = "\(Int(favoriteDetailedHall?.hallId.hallPrice ?? 0)) EGP"
ratingStarsView.rating = Double(Int(favoriteDetailedHall?.hallId.hallsAverageRating ?? 0))
ratesLabel.text = "(\((Int(favoriteDetailedHall?.hallId.hallsRatingCounter ?? 0)))) Rating"
infoTextView.text = favoriteDetailedHall?.hallId.hallDescription
offersTextView.text = favoriteDetailedHall?.hallId.hallSpecialOffers
if favoriteDetailedHall?.hallId.hallImage.count ?? 0 > 0 && favoriteDetailedHall?.hallId.hallImage.isEmpty == false {
hallImages = (favoriteDetailedHall?.hallId.hallImage)!
self.pageControl.numberOfPages = hallImages.count
self.pageControl.currentPage = 0
}
favoriteImageView.isHidden = true
favoriteBackgroundView.isHidden = true
}
}
@IBAction func CallButtonAction(_ sender: UIButton) {
guard let phoneNumber = hallPhoneNumber, hallPhoneNumber != nil else {
self.show1buttonAlert(title: "Oops", message: "Hall phone number is not available!", buttonTitle: "OK") {
}
return
}
let encodedPhoneNumber = phoneNumber.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let number = URL(string: "tel://" + "\(encodedPhoneNumber!)")
UIApplication.shared.open(number!)
}
@objc func viewOnMap(_ sender: UITapGestureRecognizer){
guard let Longitude = hallLocationLong, let Latitude = hallLocationLat, let Name = hallName, let Address = hallAddress else {
self.show1buttonAlert(title: "Oops", message: "Hall location is not available!", buttonTitle: "OK") {
}
return
}
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "MapViewController") as! MapViewController
controller.hallLat = (Latitude as NSString).floatValue
controller.hallLong = (Longitude as NSString).floatValue
controller.hallName = Name
controller.hallAddress = Address
navigationController?.pushViewController(controller, animated: true)
}
@objc func addTofavoriteButtonAction(){
if defaults.dictionary(forKey: "loggedInClient") != nil{
addToFavorite()
}else {
self.show2buttonAlert(title: "Add to favorites?", message: "You have to login or create account in order to save this hall in your favorites!", cancelButtonTitle: "Cancel", defaultButtonTitle: "Login") { (defualt) in
if defualt {
self.showLoginComponent()
}
}
}
}
func addToFavorite(){
guard let hallID = hallId else { return }
SVProgressHUD.show()
ApiManager.sharedInstance.addHallToFavorite(hallID: hallID) { (valid, msg, reRequest) in
self.dismissRingIndecator()
if reRequest {
self.addToFavorite()
}
else if valid {
self.favoriteImageView.image = UIImage(named: "HeartICONSelected777")
self.show1buttonAlert(title: "Done", message: "Hall saved to favorite successfullt", buttonTitle: "OK", callback: {
})
}else {
self.show1buttonAlert(title: "Error", message: msg, buttonTitle: "OK", callback: {
})
}
}
}
func showLoginComponent(){
let storyboard = UIStoryboard(name: "LoginBoard", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "signInScreen") as! SignInController
let homeController = UINavigationController(rootViewController: controller)
homeController.isNavigationBarHidden = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
self.present(homeController, animated: true, completion: nil)
}
}
@objc func rateHalls(){
if defaults.dictionary(forKey: "loggedInClient") == nil{
self.show2buttonAlert(title: "Rate this wedding hall?", message: "You have to login or create account in order to rate this hall!", cancelButtonTitle: "Cancel", defaultButtonTitle: "Login") { (defualt) in
if defualt {
self.showLoginComponent()
}
}
}else {
self.showRateAlert { (valid, rate) in
if valid {
self.rateHall(rate: rate)
}
}
}
}
func rateHall(rate: Int){
guard let hallID = self.hallId else {
self.show1buttonAlert(title: "Error", message: "Error happend, try again later", buttonTitle: "OK") {
}
return
}
SVProgressHUD.show()
ApiManager.sharedInstance.rateHall(hallID: hallID, rating: rate) { (valid, msg, reRequest) in
self.dismissRingIndecator()
if reRequest {
self.rateHall(rate: rate)
}
else if valid {
self.show1buttonAlert(title: "Done", message: "Hall rated successfullt", buttonTitle: "OK", callback: {
})
}else {
self.show1buttonAlert(title: "Error", message: msg, buttonTitle: "OK", callback: {
})
}
}
}
func setupNavigationBar(){
navigationController?.navigationBar.barStyle = .default
navigationController?.navigationBar.isTranslucent = false
navigationController?.navigationBar.prefersLargeTitles = false
navigationController?.navigationBar.barTintColor = UIColor(hexString: "#F6F6F6")
navigationController?.isNavigationBarHidden = false
let iconImage = UIImageView()
iconImage.image = UIImage(named: "logo2")
iconImage.contentMode = .scaleAspectFit
iconImage.backgroundColor = UIColor.clear
navigationItem.titleView = iconImage
let leftButton = UIButton(type: .custom)
leftButton.setImage(UIImage(named: "BackICON77777")?.withRenderingMode(.alwaysTemplate), for: .normal)
leftButton.tintColor = UIColor.mainAppPink()
leftButton.translatesAutoresizingMaskIntoConstraints = false
leftButton.widthAnchor.constraint(equalToConstant: 20).isActive = true
leftButton.heightAnchor.constraint(equalToConstant: 20).isActive = true
leftButton.addTarget(self, action: #selector(leftButtonAction), for: .touchUpInside)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftButton)
}
@objc func leftButtonAction(){
navigationController?.popViewController(animated: true)
}
}
|
//
// DatabaseObject.swift
// SlouchDBTests
//
// Created by Allen Ussher on 11/4/17.
// Copyright © 2017 Ussher Press. All rights reserved.
//
import Foundation
public typealias DatabaseObjectPropertiesDictionary = [String : String]
public struct DatabaseObject: Equatable {
public static let kUnassignedIdentifier = "unassigned"
public static let kDeltaIdentifier = "delta"
public static let kIdentifierPropertyKey = "_id"
public static let kDeletedPropertyKey = "_de"
public static let kCreationDatePropertyKey = "_cd"
public static let kLastModifiedDatePropertyKey = "_lm"
public var properties: DatabaseObjectPropertiesDictionary
public var identifier: String = kUnassignedIdentifier
public var creationDate: Date
public var lastModifiedDate: Date
public init(identifier: String? = nil,
creationDate: Date,
lastModifiedDate: Date,
properties: DatabaseObjectPropertiesDictionary = [:]) {
let ignoredPropertyKeys = [DatabaseObject.kIdentifierPropertyKey,
DatabaseObject.kCreationDatePropertyKey,
DatabaseObject.kLastModifiedDatePropertyKey]
if let identifier = identifier {
self.identifier = identifier
} else if let identifier = properties[DatabaseObject.kIdentifierPropertyKey] {
self.identifier = identifier
}
self.creationDate = creationDate
self.lastModifiedDate = lastModifiedDate
self.properties = properties.filter { ignoredPropertyKeys.contains($0.key) == false }
}
static public func ==(lhs: DatabaseObject, rhs: DatabaseObject) -> Bool {
return lhs.properties == rhs.properties
}
}
|
import Foundation
@objcMembers public class USAutocompleteResult: NSObject, Codable {
public var suggestions:[USAutocompleteSuggestion]?
public init(dictionary: NSDictionary) {
super.init()
if let suggestions = dictionary["suggestions"] {
self.suggestions = convertToSuggestionObjects(suggestions as! [[String:Any]])
} else {
self.suggestions = [USAutocompleteSuggestion]()
}
}
func convertToSuggestionObjects(_ object:[[String:Any]]) -> [USAutocompleteSuggestion] {
var mutable = [USAutocompleteSuggestion]()
for city in object {
mutable.append(USAutocompleteSuggestion(dictionary: city as NSDictionary))
}
return mutable
}
func getSuggestionAtIndex(index: Int) -> USAutocompleteSuggestion {
if let suggestions = self.suggestions {
return suggestions[index]
} else {
return USAutocompleteSuggestion(dictionary: NSDictionary())
}
}
}
|
//
// TMAddressTableViewCell.swift
// consumer
//
// Created by Vladislav Zagorodnyuk on 5/17/16.
// Copyright © 2016 Human Ventures Co. All rights reserved.
//
protocol TMAddressTableViewCellDelegate {
func editingSelectedForAddress(_ address: TMContactAddress?, cell: TMAddressTableViewCell)
}
class TMAddressTableViewCell: UITableViewCell {
// Address
var address: TMContactAddress? {
didSet {
// Safety check
guard let _address = address else {
return
}
// Title label
self.titleLabel.text = _address.label?.uppercased()
// Address label
let addressString = TMContactAddress.getAddressDetailsStringFromAddress(_address)
self.addressLabel.attributedText = NSMutableAttributedString.initWithString(addressString.uppercased(), lineSpacing: 7.0, aligntment: .left)
}
}
// Delegate
var delegate: TMAddressTableViewCellDelegate?
// Address Title Label
@IBOutlet var titleLabel: UILabel!
// Full Address Label
@IBOutlet var addressLabel: UILabel!
// Selection Button
@IBOutlet var selectionImageView: UIImageView!
// Editing Button
@IBOutlet var editingButton: UIButton!
// Selected cell
var selectedCell = false {
didSet {
if selectedCell {
self.selectionImageView.image = UIImage(named: "Address_selected")
self.editingButton.isHidden = false
}
else {
self.selectionImageView.image = UIImage(named: "Address_unselected")
self.editingButton.isHidden = true
}
}
}
// Editing button pressed
@IBAction func editAddressButtonPressed(_ sender: AnyObject) {
// Calling delegate method
self.delegate?.editingSelectedForAddress(self.address, cell: self)
}
}
|
//
// MealItemCell.swift
// EasyMeals
//
// Created by Alex Grimes on 8/13/18.
// Copyright © 2018 Alex Grimes. All rights reserved.
//
import UIKit
class MealItemCell: UITableViewCell {
@IBOutlet weak var foodLabel: 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
}
}
|
//
// ThrottlerSpy.swift
// MarvelTests
//
// Created by MACBOOK on 21/05/2021.
//
import Foundation
@testable import Marvel
final class ThrottlerSpy: Throttler {
var completion: (() -> Void)!
var callCount = 0
func throttle(_ block: @escaping () -> Void) {
callCount += 1
completion = block
}
}
|
//
// SettingTableViewController.swift
// Pomodoro
//
// Created by 蘇健豪1 on 2017/1/4.
// Copyright © 2017年 Oyster. All rights reserved.
//
import UIKit
class SettingTableViewController: UITableViewController {
var rowData : [[String]]!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "設定"
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
rowData = [["說明"],["版本", "回饋"]]
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return rowData.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rowData[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel!.text = rowData[indexPath.section][indexPath.row]
if indexPath.section == 0 && indexPath.row == 0 {
cell.accessoryType = .disclosureIndicator
}
else {
cell.accessoryType = .none
}
return cell
}
/*
// 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.
}
*/
}
|
//
// UICollectionView+SWFBuilder.swift
// TestSwift
//
// Created by wsy on 2018/1/10.
// Copyright © 2018年 wangshengyuan. All rights reserved.
//
import Foundation
import UIKit
func CollectionView(_ rect: CGRect) -> UICollectionView {
return UICollectionView.init(frame: rect, collectionViewLayout: UICollectionViewLayout())
}
func CollectionView(_ rect: CGRect, _ layout: UICollectionViewLayout) -> UICollectionView {
return UICollectionView.init(frame: rect, collectionViewLayout: layout)
}
extension UICollectionView
{
func collectionViewDelegate(_ delegate: UICollectionViewDelegate?) -> UICollectionView {
self.delegate = delegate
return self
}
func collectionViewDataSource(_ dataSource: UICollectionViewDataSource?) -> UICollectionView {
self.dataSource = dataSource
return self
}
func collectionViewRegisterCell(_ cellClass: AnyClass?, _ id: String) -> UICollectionView {
self.register(cellClass, forCellWithReuseIdentifier: id)
return self
}
func collectionViewRegisterHeaderView(_ cellClass: AnyClass?, _ id: String) -> UICollectionView {
self.register(cellClass, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: id)
return self
}
func collectionViewRegisterFooterView(_ cellClass: AnyClass?, _ id: String) -> UICollectionView {
self.register(cellClass, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: id)
return self
}
func collectionViewReuseableCell(_ id: String, _ indexPath: IndexPath) -> UICollectionViewCell {
return self.dequeueReusableCell(withReuseIdentifier: id, for: indexPath)
}
}
|
//
// ViewController.swift
// SQLIteExample
//
// Created by Scott Lee on 2016. 10. 4..
// Copyright © 2016년 Studio G.B.U. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var memo: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func saveMemo(_ sender: UIButton) {
}
@IBAction func loadMemo(_ sender: UIButton) {
}
}
|
//===--- PopFrontGeneric.swift --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
let reps = 1
let arrayCount = 1024
// This test case exposes rdar://17440222 which caused rdar://17974483 (popFront
// being really slow).
func _arrayReplace<B: _ArrayBufferProtocol, C: Collection
where C.Iterator.Element == B.Element, B.Index == Int
>(
_ target: inout B, _ subRange: Range<Int>, _ newValues: C
) {
_precondition(
subRange.lowerBound >= 0,
"Array replace: subRange start is negative")
_precondition(
subRange.upperBound <= target.endIndex,
"Array replace: subRange extends past the end")
let oldCount = target.count
let eraseCount = subRange.count
let insertCount = numericCast(newValues.count) as Int
let growth = insertCount - eraseCount
if target.requestUniqueMutableBackingBuffer(minimumCapacity: oldCount + growth) != nil {
target.replace(subRange: subRange, with: insertCount, elementsOf: newValues)
}
else {
_preconditionFailure("Should not get here?")
}
}
@inline(never)
public func run_PopFrontArrayGeneric(_ N: Int) {
let orig = Array(repeating: 1, count: arrayCount)
var a = [Int]()
for _ in 1...20*N {
for _ in 1...reps {
var result = 0
a.append(contentsOf: orig)
while a.count != 0 {
result += a[0]
_arrayReplace(&a._buffer, 0..<1, EmptyCollection())
}
CheckResults(result == arrayCount, "IncorrectResults in StringInterpolation: \(result) != \(arrayCount)")
}
}
}
|
//
// ViewController.swift
// HotCold
//
// Created by user131306 on 1/31/18.
// Copyright © 2018 Maryville App Development. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var manager = CLLocationManager()
var savedLocation: CLLocation!
var buttonOnOff = 0
@IBOutlet weak var saveCurrentLocation: UIButton!
@IBOutlet weak var findLastLocation: UIButton!
@IBOutlet weak var helpView: UIView!
@IBAction func saveCurrentLocation(_ sender: UIButton) {
savedLocation = manager.location
findLastLocation.isEnabled = true
findLastLocation.backgroundColor = UIColor(red: 251.0/255.0, green: 50.0/255.0, blue: 67.0/255.0, alpha: 1.0)
saveCurrentLocation.backgroundColor = UIColor(red: 69.0/255.0, green: 86.0/255.0, blue: 103.0/255.0, alpha: 1.0)
print(savedLocation)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "findLastLocation" {
let mapVC = segue.destination as! MapViewController
mapVC.savedLocation = savedLocation
}
}
@IBAction func findLastLocation(_ sender: UIButton) {
performSegue(withIdentifier: "findLastLocation", sender: self)
}
@IBAction func Help(_ sender: UIButton) {
buttonOnOff += 1
if buttonOnOff == 1 {
helpView.isHidden = false
}
else if buttonOnOff == 2 {
helpView.isHidden = true
buttonOnOff = 0
}
}
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.startUpdatingLocation()
manager.allowsBackgroundLocationUpdates = true
manager.requestAlwaysAuthorization()
manager.startUpdatingLocation()
findLastLocation.isEnabled = false
helpView.isHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
//
// Conversation.swift
// SecChat
//
// Created by Oscar Götting on 12/04/2017.
// Copyright © 2017 Oscar Götting. All rights reserved.
//
import Foundation
import JSQMessagesViewController
class Conversation {
init(conversationId: String, target: User, imageResource: String) {
self.conversationId = conversationId
self.targetUser = target
self.imageResource = imageResource
self.hasUnreadMessage = false
}
var conversationId : String!
var targetUser : User!
var imageResource : String!
var userName : String!
var isEmpty : Bool!
var lastMessageBody: String!
var messages = [Message]()
var hasUnreadMessage : Bool!
}
|
//
// GameView.swift
// AVAEGamingExample
//
// Translated by OOPer in cooperation with shlab.jp, on 2015/4/20.
//
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
GameView
*/
import SceneKit
import AVFoundation
@objc(GameView)
class GameView: SCNView {
var gameAudioEngine: AudioEngine!
var previousTouch: CGPoint = CGPoint()
override func awakeFromNib() {
super.awakeFromNib()
#if os(iOS) || os(tvOS)
self.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(panGesture)))
#endif
}
func degreesFromRad<F: BinaryFloatingPoint>(_ rad: F) -> F {
return (rad / .pi) * 180
}
func radFromDegrees<F: BinaryFloatingPoint>(_ degree: F) -> F {
return (degree/180) * .pi
}
private func updateEulerAnglesAndListener(fromDeltaX dx: CGFloat, deltaY dy: CGFloat) {
//estimate the position deltas as the angular change and convert it to radians for scene kit
let dYaw = self.radFromDegrees(SCNVectorFloat(dx))
let dPitch = self.radFromDegrees(SCNVectorFloat(dy))
//scale the feedback to make the transitions smooth and natural
let scalar: SCNVectorFloat = 0.1
self.pointOfView?.eulerAngles = SCNVector3Make(self.pointOfView!.eulerAngles.x+dPitch*scalar,
self.pointOfView!.eulerAngles.y+dYaw*scalar,
self.pointOfView!.eulerAngles.z)
let listener = self.scene!.rootNode.childNode(withName: "listenerLight", recursively: true)
listener?.eulerAngles = SCNVector3Make(self.pointOfView!.eulerAngles.x,
self.pointOfView!.eulerAngles.y,
self.pointOfView!.eulerAngles.z)
//convert the scene kit angular orientation (radians) to degrees for AVAudioEngine and match the orientation
self.gameAudioEngine
.updateListenerOrientation(AVAudioMake3DAngularOrientation(Float(self.degreesFromRad(-1*self.pointOfView!.eulerAngles.y)),
Float(self.degreesFromRad(-1*self.pointOfView!.eulerAngles.x)),
Float(self.degreesFromRad(self.pointOfView!.eulerAngles.z))))
}
#if os(iOS) || os(tvOS)
@objc private func panGesture(_ panRecognizer: UIPanGestureRecognizer) {
//capture the first touch
if panRecognizer.state == .began {
self.previousTouch = panRecognizer.location(in: self)
}
let currentTouch = panRecognizer.location(in: self)
//Calculate the change in position
let dX = currentTouch.x-self.previousTouch.x
let dY = currentTouch.y-self.self.previousTouch.y
self.previousTouch = currentTouch
self.updateEulerAnglesAndListener(fromDeltaX: dX, deltaY: dY)
}
#else
override func mouseDown(with theEvent: NSEvent) {
/* Called when a mouse click occurs */
super.mouseDown(with: theEvent)
}
override func mouseDragged(with theEvent: NSEvent) {
/* Called when a mouse dragged occurs */
super.mouseDragged(with: theEvent)
self.updateEulerAnglesAndListener(fromDeltaX: theEvent.deltaX, deltaY: theEvent.deltaY)
}
override func magnify(with event: NSEvent) {
//implement this method to zoom in and out
//super.magnify(with: event)
}
override func rotate(with event: NSEvent) {
//implement this to have to listener roll along the perpendicular axis to the screen plane
//super.rotate(with: event)
}
#endif //os(iOS) || os(TvOS)
}
|
//
// VolunteerPopUpViewController.swift
// LoginScreen
//
// Created by Ali Halawa on 1/19/20.
// Copyright © 2020 Macbook. All rights reserved.
//
import UIKit
class VolunteerPopUpViewController: UIViewController {
@IBOutlet weak var Davis: UILabel!
@IBOutlet weak var AlexSmith: UILabel!
@IBOutlet weak var helpyouwiththat: UILabel!
@IBOutlet weak var HelpingHandFound: UILabel!
@IBOutlet weak var Accept: UIButton!
@IBOutlet weak var Decline: UIButton!
@IBOutlet weak var Charity: UIImageView! {
didSet {
self.Charity.tappable = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
Davis.textColor = .black
AlexSmith.textColor = .black
helpyouwiththat.textColor = .black
HelpingHandFound.textColor = .black
Accept.layer.cornerRadius = 10
Accept.clipsToBounds = true
Decline.layer.cornerRadius = 10
Decline.clipsToBounds = true
// Do any additional setup after loading the view.
self.Charity.callback = {
// Some actions etc.
print("pressed image")
if let url = URL(string: "https://www.stjude.org/donate/pm.html?sc_dcm=254910857&sc_cid=kwp75473&source_code=IIQ190721002&ef_id=EAIaIQobChMIx7a8tb2Q5wIVah6tBh0C4g_eEAAYASAAEgLf1vD_BwE:G:s&s_kwcid=AL!4519!3!386681578030!e!!g!!st%20judes&gclid=EAIaIQobChMIx7a8tb2Q5wIVah6tBh0C4g_eEAAYASAAEgLf1vD_BwE") {
UIApplication.shared.open(url)
}
}
}
/*
// 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 AcceptPressed(_ sender: Any) {
self.presentingViewController?.presentingViewController?.dismiss(animated: true, completion: nil)
}
@IBAction func DeclinePressed(_ sender: Any) {
self.presentingViewController?.presentingViewController?.dismiss(animated: true, completion: nil)
}
}
public typealias SimpleClosure = (() -> ())
private var tappableKey : UInt8 = 0
private var actionKey : UInt8 = 1
extension UIImageView {
@objc var callback: SimpleClosure {
get {
return objc_getAssociatedObject(self, &actionKey) as! SimpleClosure
}
set {
objc_setAssociatedObject(self, &actionKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
var gesture: UITapGestureRecognizer {
get {
return UITapGestureRecognizer(target: self, action: #selector(tapped))
}
}
var tappable: Bool! {
get {
return objc_getAssociatedObject(self, &tappableKey) as? Bool
}
set(newValue) {
objc_setAssociatedObject(self, &tappableKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
self.addTapGesture()
}
}
fileprivate func addTapGesture() {
if (self.tappable) {
self.gesture.numberOfTapsRequired = 1
self.isUserInteractionEnabled = true
self.addGestureRecognizer(gesture)
}
}
@objc private func tapped() {
callback()
}
}
|
//
// MessageCenter.swift
// StulingTanks
//
// Created by Misha Lvovsky on 5/1/18.
// Copyright © 2018 Lvovsky, Michael. All rights reserved.
//
import Foundation
struct MessageCenter {
var messages: [String:String]
func getMessage(key: String) -> String? {
return messages[key]
}
mutating func sendMessage(key: String, message: String) {
messages[key] = message
return
}
init() {
messages = [String:String]()
}
}
|
//
// PostView.swift
// InstagramApp
//
// Created by Seo Kyohei on 2015/10/31.
// Copyright © 2015年 Kyohei Seo. All rights reserved.
//
import UIKit
class PostView: UIView {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var twitterButton: UIButton!
@IBOutlet weak var lineButton: UIButton!
@IBOutlet weak var postButton: UIButton!
override func layoutSubviews() {
super.layoutSubviews()
layoutTextView(textView)
layoutButton(twitterButton)
layoutButton(lineButton)
}
func layoutButton(button: UIButton) {
button.layer.borderWidth = 2
button.layer.borderColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1).CGColor
}
func layoutTextView(textView: UITextView) {
textView.layer.borderWidth = 3
textView.layer.borderColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1).CGColor
textView.layer.cornerRadius = 7
}
}
|
//
// OptionalSugars.swift
// Lazy
//
// Created by Yuhuan Jiang on 10/8/17.
//
// Swift 4 comiplier crashes on this code.
// See [SR-6090](https://bugs.swift.org/browse/SR-6090)
//extension Optional: Sequence {
// public func makeIterator() -> OptionalIterator<Wrapped> {
// return OptionalIterator(self)
// }
//
// public func get() -> Wrapped {
// return unsafelyUnwrapped
// }
//}
//
//public class OptionalIterator<T>: IteratorProtocol {
// let o: Optional<T>
//
// init(_ o: Optional<T>) {
// self.o = o
// }
//
// public func next() -> T? {
// return o == nil ? nil : o!
// }
//
// public typealias Element = T
//
//
//}
|
//
// ViewController.swift
// WeatherOne
//
// Created by Gavril Tonev on 2/9/16.
// Copyright © 2016 Gavril Tonev. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
{
let people = [
Person(name: "John", location: "Blago"),
Person(name: "Anna", location: "Sofia"),
Person(name: "Jack", location: "Plovdiv")
]
var selectedPersonIndex = 0
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return people.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell")!
cell.textLabel?.text = people[indexPath.row].name
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedPersonIndex = indexPath.row
performSegueWithIdentifier("gotoPerson", sender: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "gotoPerson" {
if let personVC = segue.destinationViewController as? PersonViewController {
personVC.person = people[selectedPersonIndex]
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBarHidden = true
}
}
|
//
// DDC.swift
// UISwipeGestureRecognizerTest
//
// Created by 周兵 on 16/7/28.
// Copyright © 2016年 RNT. All rights reserved.
//
import Foundation
class DDC : UIViewController {
func log(strToLog : String) {
NSLog("this is DDC Log %@", strToLog)
}
} |
//
// LandSearchBuyCollectionViewCell.swift
// LandSearch
//
// Created by Deeva Infotech LLP on 17/01/18.
// Copyright © 2018 Deeva Infotech LLP. All rights reserved.
//
import UIKit
class LandSearchBuyCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var LandTypeImage: UIImageView!
@IBOutlet weak var LandTypeLabel: UILabel!
}
|
//
// ViewController.swift
// ZoomSample
//
// Created by Yu Kadowaki on 2018/06/13.
// Copyright © 2018 gates1de. All rights reserved.
//
import UIKit
import MobileRTC
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func didTapJoinMeeting(_ sender: UIButton) {
// Using browser (Safari or WebView)
let meetingId: String = ProcessInfo.processInfo.environment["MeetingId"] ?? ""
// let url = URL(string: "zoomus://zoomus/join?confno=\(meetingId)")
// UIApplication.shared.open(url!)
// Using zoom SDK (MobileRTC)
let meetingService = MobileRTC.shared().getMeetingService()
let meetingParameter = [
kMeetingParam_Username : "test_user",
kMeetingParam_MeetingNumber : meetingId
]
let result = meetingService?.joinMeeting(with: meetingParameter)
print("Meeting result: \(result)")
}
}
|
//
// SettingsViewController.swift
// DoReMi
//
// Created by Conor Smith on 7/1/21.
//
import Appirater
import SafariServices
import UIKit
class SettingsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
private let tableView: UITableView = {
let table = UITableView(frame: .zero, style: .grouped)
table.register(
UITableViewCell.self,
forCellReuseIdentifier: "cell"
)
table.register(
SwitchTableViewCell.self,
forCellReuseIdentifier: SwitchTableViewCell.identifier
)
return table
}()
var sections = [SettingsSection]()
override func viewDidLoad() {
super.viewDidLoad()
sections = [
SettingsSection(
title: "Preferences",
options: [
SettingsOption(title: "Save Videos", handler: { })
]
),
SettingsSection(
title: "Enjoying the app?",
options: [
SettingsOption(title: "Rate App", handler: {
DispatchQueue.main.async {
Appirater.tryToShowPrompt()
//UIApplication.shared.open(URL(string: "")!, options: [:], completionHandler: nil)
}
}),
SettingsOption(title: "Share App", handler: { [weak self] in
DispatchQueue.main.async {
guard let url = URL(string: "my app to url direct download") else {
return
}
let vc = UIActivityViewController(
activityItems: [url],
applicationActivities: []
)
self?.present(vc, animated: true, completion: nil)
}
})
]
),
SettingsSection(
title: "Information",
options: [
SettingsOption(title: "Terms of Service", handler: { [weak self] in
DispatchQueue.main.async {
guard let url = URL(string: "") else {
return
}
let vc = SFSafariViewController(url: url)
self?.present(vc, animated: true)
}
}),
SettingsOption(title: "Privacy Policy", handler: { [weak self] in
DispatchQueue.main.async {
guard let url = URL(string: "") else {
return
}
let vc = SFSafariViewController(url: url)
self?.present(vc, animated: true)
}
})
]
)
]
title = "Settings"
view.backgroundColor = .systemBackground
view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
createFooter()
}
func createFooter() {
let footer = UIView(frame: CGRect(x: 0, y: 0, width: view.width, height: 100))
let button = UIButton(frame: CGRect(x: (view.width - 200)/2, y: 25, width: 200, height: 50))
button.setTitle("Sign Out", for: .normal)
button.setTitleColor(.systemRed, for: .normal)
button.addTarget(self, action: #selector(didTapSignOut), for: .touchUpInside)
footer.addSubview(button)
tableView.tableFooterView = footer
}
@objc func didTapSignOut() {
let actionSheet = UIAlertController(
title: "Sign Out",
message: "Would you like to sign out?",
preferredStyle: .actionSheet
)
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
actionSheet.addAction(UIAlertAction(title: "Sign Out", style: .destructive, handler: { _ in
DispatchQueue.main.async {
AuthManager.shared.signOut { [weak self] success in
if success{
UserDefaults.standard.setValue(nil, forKey: "username")
UserDefaults.standard.setValue(nil, forKey: "profile_picture_url")
self?.navigationController?.popToRootViewController(animated: true)
self?.tabBarController?.selectedIndex = 0
}
else {
let alert = UIAlertController(
title: "Whoops",
message: "Something went wrong when signing out. Please try again",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil))
self?.present(alert, animated: true)
}
}
}
}))
present(actionSheet, animated: true)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.frame = view.bounds
}
// TableView
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].options.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = sections[indexPath.section].options[indexPath.row]
//REDO: Make it a switch statment like in Discover controller
if model.title == "Save Videos" {
guard let cell = tableView.dequeueReusableCell(
withIdentifier: SwitchTableViewCell.identifier,
for: indexPath
) as? SwitchTableViewCell else {
return UITableViewCell()
}
cell.delegate = self
cell.configure(with: SwitchCellViewModel(title: model.title, isOn: UserDefaults.standard.bool(forKey: "save_video")))
return cell
}
let cell = tableView.dequeueReusableCell(
withIdentifier: "cell",
for: indexPath
)
cell.accessoryType = .disclosureIndicator
cell.textLabel?.text = model.title
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let model = sections[indexPath.section].options[indexPath.row]
model.handler()
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section].title
}
}
extension SettingsViewController: SwitchTableViewCellDelegate {
func switchTableViewCell(_ cell: SwitchTableViewCell, didUpdateSwitchTo isOn: Bool) {
UserDefaults.standard.setValue(isOn, forKey: "save_video")
}
}
|
//
// ImagePickerView.swift
// ChatViewController
//
// Created by Hoangtaiki on 6/11/18.
// Copyright © 2018 toprating. All rights reserved.
//
import UIKit
import Photos
open class ImagePickerView: UIView {
/// Image Picker Helper
open lazy var imagePickerHelper: ImagePickerHelperable = {
let imagePickerHelper = ImagePickerHelper()
imagePickerHelper.delegate = self
return imagePickerHelper
}()
public var collectionView: ImagePickerCollectionView!
public weak var pickerDelegate: ImagePickerResultDelegate?
/// Parent View Controller
weak var parentViewController: UIViewController? {
didSet {
imagePickerHelper.parentViewController = parentViewController
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
frame = bounds
setUI()
}
override init(frame: CGRect) {
super.init(frame: frame)
setUI()
}
open func openCamera() {
imagePickerHelper.accessCamera()
}
open func openLibrary() {
imagePickerHelper.accessLibrary()
}
private func setUI() {
backgroundColor = UIColor.black.withAlphaComponent(0.87)
collectionView = ImagePickerCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.pickerDelegate = self
addSubview(collectionView)
collectionView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
collectionView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
collectionView.topAnchor.constraint(equalTo: topAnchor).isActive = true
collectionView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
// Pass actions to collection view
collectionView.takePhoto = { [weak self] in
self?.openCamera()
}
collectionView.showCollection = { [weak self] in
self?.openLibrary()
}
}
}
extension ImagePickerView: ImagePickerResultDelegate {
public func didSelectImage(url: URL?) {
pickerDelegate?.didSelectImage?(url: url, imageData: nil)
}
public func didSelectVideo(url: URL?) {
pickerDelegate?.didSelectVideo?(url: url, imageData: nil)
}
public func didSelectDocumet(url: URL?, documentData: Data?) {
pickerDelegate?.didSelectDocumet?(url: url, documentData: documentData)
}
}
|
//
// MyNav.swift
// FlaskNav
//
// Created by hassan uriostegui on 9/15/18.
// Copyright © 2018 eonflux. All rights reserved.
//
import UIKit
enum Tabs:String {
case Home, Friends
}
enum Controllers:String {
case Feed, Settings
}
enum Modals:String {
case Login, Share
}
class MyFlaskNav: FlaskNav<Tabs, Controllers,Modals> {
override func defineRouting(){
defineNavRoot(){ ViewController() }
defineTabRoot(.Home){ AsyncViewController() }
defineTabRoot(.Friends){ AsyncViewController() }
define(controller: .Settings){ AsyncViewController()}
define(controller: .Feed){ AsyncViewController()}
define(modal: .Login){ AsyncViewController() }
define(modal: .Share){ AsyncViewController() }
}
}
|
/** Swift Addendum
* Issue #13 Architecture, June 2014
* By Jeff Gilbert and Conrad Stoll
* http://www.objc.io/issue-13/viper.html
*/
/**
* Last week at WWDC Apple introduced the Swift programming language as the
* future of Cocoa and Cocoa Touch development. It's too early to have formed
* complex opinions about the Swift language, but we do know that languages
* have a major influence on how we design and build software. We decided to
* rewrite our VIPER TODO example app using Swift
* (https://github.com/objcio/issue-13-viper-swift) to help us learn what this
* means for VIPER. So far, we like what we see. Here are a few features of
* Swift that we feel will improve the experience of building apps using VIPER.
*
* Structs
* =======
*
* In VIPER we use small, lightweight, model classes to pass data between
* layers, such as from the Presenter to the View. These PONSOs are usually
* intended to simply carry small amounts of data, and are usually not intended
* to be subclassed. Swift structs are a perfect fit for these situations.
* Here's an example of a struct used in the VIPER Swift example. Notice that
* this struct needs to be equatable, and so we have overloaded the == operator
* to compare two instances of its type:
*/
struct UpcomingDisplayItem : Equatable, Printable {
let title : String = ""
let dueDate : String = ""
var description : String { get {
return "\(title) -- \(dueDate)"
}}
init(title: String, dueDate: String) {
self.title = title
self.dueDate = dueDate
}
}
func == (leftSide: UpcomingDisplayItem, rightSide: UpcomingDisplayItem) -> Bool
{
var hasEqualSections = false
hasEqualSections = rightSide.title == leftSide.title
if hasEqualSections == false {
return false
}
hasEqualSections = rightSide.dueDate == leftSide.dueDate
return hasEqualSections
}
/** Type Safety
* ===========
*
* Perhaps the biggest difference between Objective-C and Swift is how the two
* deal with types. Objective-C is dynamically typed and Swift is very
* intentionally strict with how it implements type checking at compile time.
* For an architecture like VIPER, where an app is composed of multiple
* distinct layers, type safety can be a huge win for programmer efficiency and
* for architectural structure. The compiler is helping you make sure
* containers and objects are of the correct type when they are being passed
* between layer boundaries. This is a great place to use structs as shown
* above. If a struct is meant to live at the boundary between two layers, then
* you can guarantee that it will never be able to escape from between those
* layers thanks to type safety.
*/
/** Further Reading
* ===============
*
* VIPER TODO, article example app
* https://github.com/objcio/issue-13-viper
*
* VIPER SWIFT, article example app built using Swift
* https://github.com/objcio/issue-13-viper-swift
*
* Counter, another example app
* https://github.com/mutualmobile/Counter
*
* Mutual Mobile Introduction to VIPER
* http://mutualmobile.github.io/blog/2013/12/04/viper-introduction/
*
* Clean Architecture
* http://blog.8thlight.com/uncle-bob/2011/11/22/Clean-Architecture.html
*
* Lighter View Controllers
* http://www.objc.io/issue-1/lighter-view-controllers.html
*
* Testing View Controllers
* http://www.objc.io/issue-1/testing-view-controllers.html
*
* Bunnies
* http://inessential.com/2014/03/16/smaller_please
*/
|
//
// VetrinaCollectionCell.swift
// Myoozik
//
// Created by Alessandro Bolattino on 17/04/18.
// Copyright © 2018 Mussini SAS. All rights reserved.
//
import Foundation
import UIKit
import Hero
class VetrinaCollectionCell: UICollectionViewCell {
let artista = VetrinaCircularView(bordered: true)
var vetrina: Home.vetrinaband? {
didSet {
//titleLabel.text = viewModel?.title
//imageView.setImageURL(url: viewModel?.imageURL)
self.artista.vetrinaItem = vetrina
}
}
override init(frame: CGRect) {
super.init(frame: frame)
// ... and then the rest of the code
artista.addTo(view: self).setSize(width: 66, height: 66).setCenter(of: self)
artista.hero.id = "vetrina"
}
/*init(){
super.init(frame: CGRect(x: 0, y: 0, width: 70, height: 70))
}*/
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
}
}
|
//
// Home.swift
// switui_learn
//
// Created by laijihua on 2020/10/16.
//
import SwiftUI
struct Home: View {
var body: some View {
NavigationView(content: {
Text("Home")
.navigationTitle(Text("Home").foregroundColor(.red))
})
}
}
struct Home_Previews: PreviewProvider {
static var previews: some View {
Home()
}
}
|
//
// Store+Extensions.swift
// PlumTestTask
//
// Created by Adrian Śliwa on 22/06/2020.
// Copyright © 2020 sliwa.adrian. All rights reserved.
//
import ComposableArchitecture
extension Store where State: Equatable {
var view: ViewStore<State, Action> {
return ViewStore(self)
}
}
|
//
// UIView+Extension.swift
// Wipro Assignment
//
// Created by Dhiman Ranjit on 18/07/20.
// Copyright © 2020 Dhiman Ranjit. All rights reserved.
//
import UIKit
var imageCache = ImageCache()
typealias ImageDownloadCompletionHandler = (_ image: UIImage?) -> ()
extension UIView {
func anchorToTop(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil) {
anchorWithConstantsToTop(top, left: left, bottom: bottom, right: right, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0)
}
func anchorWithConstantsToTop(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0) {
_ = anchor(top, left: left, bottom: bottom, right: right, topConstant: topConstant, leftConstant: leftConstant, bottomConstant: bottomConstant, rightConstant: rightConstant)
}
func anchor(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] {
translatesAutoresizingMaskIntoConstraints = false
var anchors = [NSLayoutConstraint]()
if let top = top {
anchors.append(topAnchor.constraint(equalTo: top, constant: topConstant))
}
if let left = left {
anchors.append(leftAnchor.constraint(equalTo: left, constant: leftConstant))
}
if let bottom = bottom {
anchors.append(bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant))
}
if let right = right {
anchors.append(rightAnchor.constraint(equalTo: right, constant: -rightConstant))
}
if widthConstant > 0 {
anchors.append(widthAnchor.constraint(equalToConstant: widthConstant))
}
if heightConstant > 0 {
anchors.append(heightAnchor.constraint(equalToConstant: heightConstant))
}
anchors.forEach({$0.isActive = true})
return anchors
}
func rounded() {
self.layer.cornerRadius = self.frame.size.width/2
self.clipsToBounds = true
}
}
extension UIImageView {
func downloadImage(from urlString: String, completion: ImageDownloadCompletionHandler?) {
if let imageFromCache = imageCache["\(urlString)"] {
completion?(UIImage(data: imageFromCache))
return
}
guard let url = URL(string: urlString) else {
print("Wrong URL")
completion?(nil)
return
}
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if error != nil {
completion?(nil)
return
}
guard let data = data else { return }
DispatchQueue.main.async {
if let image = UIImage(data: data) {
imageCache["\(urlString)"] = image.pngData()
completion?(image)
} else {
completion?(nil)
}
}
}).resume()
}
}
extension CAPropertyAnimation {
enum Key: String {
var path: String {
return rawValue
}
case strokeStart = "strokeStart"
case strokeEnd = "strokeEnd"
case strokeColor = "strokeColor"
case rotationZ = "transform.rotation.z"
case scale = "transform.scale"
}
convenience init(key: Key) {
self.init(keyPath: key.path)
}
}
extension CGSize {
var min: CGFloat {
return CGFloat.minimum(width, height)
}
}
extension CGRect {
var center: CGPoint {
return CGPoint(x: midX, y: midY)
}
}
extension UIBezierPath {
convenience init(center: CGPoint, radius: CGFloat) {
self.init(arcCenter: center, radius: radius, startAngle: 0, endAngle: CGFloat(.pi * 2.0), clockwise: true)
}
}
|
//
// R.shadow.swift
// YumaApp
//
// Created by Yuma Usa on 2018-06-18.
// Copyright © 2018 Yuma Usa. All rights reserved.
//
import UIKit
extension R
{
struct shadow
{
static func darkGray3_downright1() -> NSShadow
{
let shadow = NSShadow()
shadow.shadowBlurRadius = 3
shadow.shadowOffset = CGSize(width: 1, height: 1)
shadow.shadowColor = UIColor.gray
return shadow
}
static func YumaRed5_downright1() -> NSShadow
{
let shadow = NSShadow()
shadow.shadowBlurRadius = 5
shadow.shadowOffset = CGSize(width: 1, height: 1)
shadow.shadowColor = R.color.YumaRed
return shadow
}
static func YumaDRed5_downright1() -> NSShadow
{
let shadow = NSShadow()
shadow.shadowBlurRadius = 5
shadow.shadowOffset = CGSize(width: 1, height: 1)
shadow.shadowColor = R.color.YumaDRed
return shadow
}
static func darkGray1_downright1() -> NSShadow
{
let shadow = NSShadow()
shadow.shadowBlurRadius = 1
shadow.shadowOffset = CGSize(width: 1, height: 1)
shadow.shadowColor = UIColor.darkGray
return shadow
}
static func darkGray5_downright1() -> NSShadow
{
let shadow = NSShadow()
shadow.shadowBlurRadius = 5
shadow.shadowOffset = CGSize(width: 1, height: 1)
shadow.shadowColor = UIColor.gray
return shadow
}
static func darkGray5_downright2() -> NSShadow
{
let shadow = NSShadow()
shadow.shadowBlurRadius = 10
shadow.shadowOffset = CGSize(width: 2, height: 2)
shadow.shadowColor = UIColor.gray
return shadow
}
}
}
|
//
// ForcetouchGestureRecognizer.swift
// JvbForceTouchDemo
//
// Created by Joost van Breukelen on 15-09-16.
// Copyright © 2016 J.J.A.P. van Breukelen. All rights reserved.
//
import UIKit
//we need this import because we want to override the methods that are declared in the UIGestureRecognizerSubclass class extension of UIGestureRecognizer
import UIKit.UIGestureRecognizerSubclass
@available(iOS 9.0, *)
class ForceGestureRecognizer: UIGestureRecognizer {
var forceValue: CGFloat = 0
var maxValue: CGFloat!
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesBegan(touches, with: event)
handleForceWithTouches(touches: touches)
state = .began
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesMoved(touches, with: event)
handleForceWithTouches(touches: touches)
state = .changed
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesEnded(touches, with: event)
handleForceWithTouches(touches: touches)
state = .ended
}
func handleForceWithTouches(touches: Set<UITouch>) {
//only do something is one touch is received
if touches.count != 1 {
state = .failed
return
}
//check if touch is valid, otherwise set state to failed and return
guard let touch = touches.first else {
state = .failed
return
}
//if everything is ok, set our variables.
forceValue = touch.force
maxValue = touch.maximumPossibleForce
}
//This is called when our state is set to .ended.
public override func reset() {
super.reset()
print("reset")
forceValue = 0.0
}
}
|
//
// UserHotSpots.swift
// RBC Money Coach
//
// Created by Applied Innovation on 2015-06-29.
// Copyright (c) 2015 Applied Innovation. All rights reserved.
//
import Foundation
class UserHotSpots {
var hotspots = [HotspotLocation]()
init(){
hotspots = [HotspotLocation(locationName: "Starbucks",
latitude: 43.641074,
longitude: -79.378069),
HotspotLocation(locationName: "Chipotle",
latitude: 43.638538,
longitude: -79.387697),
HotspotLocation(locationName: "Forever 21",
latitude: 43.653226,
longitude: -79.383184),
HotspotLocation(locationName: "Walmart",
latitude: 43.709483,
longitude: -79.473672),
HotspotLocation(locationName: "Eaton Centre",
latitude: 43.654872,
longitude: -79.380327)]
}
func returnUserHotSpots()->[HotspotLocation]{
return hotspots
}
} |
//
// LoginViewController.swift
// OAuth2
//
// Created by Maxim Spiridonov on 07/04/2019.
// Copyright © 2019 Maxim Spiridonov. All rights reserved.
//
import UIKit
import FBSDKLoginKit
import FirebaseAuth
import FirebaseDatabase
import GoogleSignIn
class LoginViewController: UIViewController {
var userProfile: UserProfile?
@IBOutlet weak var acivityIndicator: UIActivityIndicatorView!
lazy var customFBLoginButton: UIButton = {
let loginButton = UIButton()
loginButton.backgroundColor = UIColor(hexValue: "#3B5999", alpha: 1)
loginButton.setTitle("Login with Facebook", for: .normal)
loginButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
loginButton.setTitleColor(.white, for: .normal)
loginButton.frame = CGRect(x: 32, y: 320, width: view.frame.width - 64, height: 50)
loginButton.layer.cornerRadius = 4
loginButton.addTarget(self, action: #selector(handleCustomFBLogin), for: .touchUpInside)
return loginButton
}()
lazy var googleLoginButton: GIDSignInButton = {
let loginButton = GIDSignInButton()
loginButton.frame = CGRect(x: 32, y: 400, width: view.frame.width - 60, height: 50)
return loginButton
}()
lazy var signInWithEmail: UIButton = {
let loginButton = UIButton()
loginButton.frame = CGRect(x: 32, y: 480, width: view.frame.width - 60, height: 50)
loginButton.setTitle("Sign In with Email", for: .normal)
loginButton.addTarget(self, action: #selector(openSignInVC), for: .touchUpInside)
return loginButton
}()
override func viewDidLoad() {
super.viewDidLoad()
acivityIndicator.stopAnimating()
view.addVerticalGradientLayer(topColor: primaryColor, bottomColor: secondaryColor)
setupViews()
GIDSignIn.sharedInstance().delegate = self
GIDSignIn.sharedInstance().uiDelegate = self
}
override var preferredStatusBarStyle: UIStatusBarStyle {
get {
return .lightContent
}
}
private func setupViews() {
view.addSubview(customFBLoginButton)
view.addSubview(googleLoginButton)
view.addSubview(signInWithEmail)
}
@objc private func openSignInVC() {
performSegue(withIdentifier: "SignIn", sender: self)
}
}
extension LoginViewController: FBSDKLoginButtonDelegate {
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
if error != nil {
print(error)
return
}
guard FBSDKAccessToken.currentAccessTokenIsActive() else { return }
openMainViewController()
print("Successfully logged in with facebook...")
}
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
print("Did log out of facebook")
}
private func openMainViewController() {
dismiss(animated: true)
}
@objc private func handleCustomFBLogin() {
FBSDKLoginManager().logIn(withReadPermissions: ["email", "public_profile"], from: self) { (result, error) in
self.acivityIndicator.startAnimating()
if let error = error {
print(error.localizedDescription)
return
}
guard let result = result else { return }
if result.isCancelled { return }
else {
self.singIntoFirebase()
}
}
}
private func singIntoFirebase() {
let accessToken = FBSDKAccessToken.current()
guard let accessTokenString = accessToken?.tokenString else { return }
let credentials = FacebookAuthProvider.credential(withAccessToken: accessTokenString)
Auth.auth().signInAndRetrieveData(with: credentials) { (user, error) in
if let error = error {
print("Что то пошло не так !Упс при аунтентификации в Facebook: ", error)
return
}
print("Успешная аунтентификация в Facebook")
self.fetchFacebookFields()
}
}
private func fetchFacebookFields() {
/*
Вот наиболее распространенные поля public_user:
id
cover
name
first_name
last_name
age_range
link
gender
locale
picture
timezone
updated_time
verified
*/
FBSDKGraphRequest(graphPath: "me",
parameters: ["fields": "id, name, email, first_name, last_name, picture.type(large)"])?.start(completionHandler: { (_, result, error) in
if let error = error {
print(error)
return
}
guard let userData = result as? [String: Any] else { return }
self.userProfile = UserProfile(data: userData)
print("Публичные данные получены с Facebook")
self.saveIntoFirebase()
})
}
private func saveIntoFirebase() {
guard
let uid = Auth.auth().currentUser?.uid,
userProfile?.fetchUserData() != nil
else { return }
Database.database().reference().child("users").updateChildValues([uid: userProfile?.fetchUserData() as Any]) { (error, _) in
if let error = error {
print(error)
return
}
print("Данныe сохранены в Firebase")
self.acivityIndicator.stopAnimating()
self.openMainViewController()
}
}
}
// MARK: Google SDK
extension LoginViewController: GIDSignInDelegate, GIDSignInUIDelegate {
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let error = error {
print("Faild to log into Google: \(error)")
return
}
print("Successfully logged in Google")
var imageURL: String?
if user.profile.hasImage {
imageURL = user.profile.imageURL(withDimension: 100).absoluteString
}
self.userProfile = UserProfile(id: user?.userID,
name: user?.profile.name,
lastName: user?.profile.familyName,
firstName: user?.profile.givenName,
email: user?.profile.email,
picture: imageURL)
print("Публичные данные получены с Google")
guard let authentication = user.authentication else { return }
let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
accessToken: authentication.accessToken)
Auth.auth().signInAndRetrieveData(with: credential) { (user, error) in
if let error = error {
print("Something went wrong with our Google user: ", error)
return
}
print("Successfully logged into Firebase with Google")
self.saveIntoFirebase()
}
}
}
|
//
// UpdatePassword.swift
// KayakFirst Ergometer E2
//
// Created by Balazs Vidumanszki on 2017. 02. 04..
// Copyright © 2017. Balazs Vidumanszki. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
class UpdatePassword: ServerService<Bool> {
private let currentPassword: String
private let newPassword: String
init(currentPassword: String, newPassword: String) {
self.currentPassword = currentPassword
self.newPassword = newPassword
}
override func handleServiceCommunication(alamofireRequest: DataRequest) -> Bool? {
return true
}
override func initUrlTag() -> String {
return "users/password/update"
}
override func initMethod() -> HTTPMethod {
return .post
}
override func initParameters() -> Parameters? {
return [
"currentPassword": currentPassword,
"newPassword": newPassword
]
}
override func initEncoding() -> ParameterEncoding {
return JSONEncoding.default
}
override func getManagerType() -> BaseManagerType {
return UserManagerType.update_pw
}
}
|
//
// LoginViewController.swift
// selfigram
//
// Created by Nitin Panchal on 2017-09-26.
// Copyright © 2017 Sweta panchal. All rights reserved.
//
import UIKit
import Parse
import FBSDKLoginKit
//import FBSDKCoreKit
class LoginViewController: UIViewController, FBSDKLoginButtonDelegate{
@IBOutlet weak var EmailIdTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let loginButton = FBSDKLoginButton()
loginButton.frame = CGRect(x: 80, y: 450, width: 100, height: 28)
view.addSubview(loginButton)
loginButton.readPermissions = ["email","public_profile"]
loginButton.delegate = self
// if (FBSDKAccessToken.current() != nil)
// {
// view.willRemoveSubview(loginButton)
// let viewController:UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "FeedViewController")
// self.present(viewController, animated: true, completion: nil)
// }
}
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!){
if error != nil {
print(error)
return;
}
else {
print("Successfuly logged using Facebook");
// showEmailAddress()
if (FBSDKAccessToken.current() != nil)
{
//view.willRemoveSubview(loginButton)
self.nextViewController()
}
}
}
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!){
print("Did log out of Facebook")
}
// func showEmailAddress() {
// FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start(completionHandler: { (connection, result, err) in
//
// if err != nil {
// print("Failed to start graph request \(String(describing: err))")
// return;
// }
// print(result!)
//
// })
// }
@IBAction func loginButtonTapped(_ sender: Any) {
let uname = EmailIdTextField.text
let pwd = passwordTextField.text
if(uname!.isEmpty || pwd!.isEmpty){
displayMyAlertMessage(title: "Alert", userMsg: "All fields are required...!!!!")
return;
}
else
{
PFUser.logInWithUsername(inBackground: uname!, password: pwd!, block: { (user, error) -> Void in
if ((user) != nil) {
self.nextViewController()
}
else {
self.displayMyAlertMessage(title: "Error", userMsg: "Username and Password is wrong.... Please enter correct Username & Password...!!!")
}
})
}
}
func nextViewController() {
DispatchQueue.main.async(execute: { () -> Void in
let viewController:UITabBarController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "selfigramTabBar") as! UITabBarController
self.present(viewController, animated: true, completion: nil)
})
}
func displayMyAlertMessage(title: String, userMsg: String)
{
let MyAlert = UIAlertController(title: title, message:userMsg, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil);
MyAlert.addAction(okAction)
self.present(MyAlert, animated: true, completion: nil)
}
@IBAction func unwindToLogInScreen(segue:UIStoryboardSegue) {
}
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.
}
*/
}
|
//
// CardStruct.swift
// FallenCherryBlossom
//
// Created by 合田竜志 on 2017/12/15.
// Copyright © 2017年 Nivis. All rights reserved.
//
import Foundation
struct CardModel: Codable {
let megami_code: Int
let megami_name: String
let code: String
let name: String
let main_type: String
let sub_type: String
let range: String
let damage_aura: String
let damage_life: String
}
class Card {
var megamiName: String = ""
var cardName: String = ""
var mainType: String = ""
var subType: String = ""
var range: String = ""
var damageAura: String = ""
var damageLife: String = ""
var cardId: String = "" // 画像との紐付けに使うためのID
init(model: CardModel) {
megamiName = model.megami_name
cardName = model.name
mainType = model.main_type
subType = model.sub_type
range = model.range
damageAura = model.damage_aura
damageLife = model.damage_life
cardId = model.megami_code.description + model.code
}
}
|
//
// ApiSearchResponse.swift
// Rubicon
//
// Created by Pavle on 22.6.18..
// Copyright © 2018. Pavle. All rights reserved.
//
import Foundation
class Welcome: Codable {
let page: Int
let results: [Result]
let totalPages, totalResults: Int
enum CodingKeys: String, CodingKey {
case page, results
case totalPages = "total_pages"
case totalResults = "total_results"
}
init(page: Int, results: [Result], totalPages: Int, totalResults: Int) {
self.page = page
self.results = results
self.totalPages = totalPages
self.totalResults = totalResults
}
}
class Result: Codable {
let id: Int
let logoPath: JSONNull?
let name: String
enum CodingKeys: String, CodingKey {
case id
case logoPath = "logo_path"
case name
}
init(id: Int, logoPath: JSONNull?, name: String) {
self.id = id
self.logoPath = logoPath
self.name = name
}
}
// MARK: Encode/decode helpers
class JSONNull: Codable {
public init() {}
public required init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if !container.decodeNil() {
throw DecodingError.typeMismatch(JSONNull.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for JSONNull"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encodeNil()
}
}
|
//
// LoginView.swift
// Ursus Chat
//
// Created by Daniel Clelland on 24/06/20.
// Copyright © 2020 Protonome. All rights reserved.
//
import SwiftUI
import KeyboardObserving
import UrsusAirlock
struct LoginView: View {
@EnvironmentObject var store: AppStore
@State var url: String = ""
@State var code: String = ""
var isAuthenticating: Bool
var body: some View {
NavigationView {
Form {
Section(header: Text("URL"), footer: Text("The URL where your ship is hosted")) {
TextField("http://sampel-palnet.arvo.network", text: $url)
.textContentType(.URL)
.keyboardType(.URL)
.autocapitalization(.none)
}
Section(header: Text("Access Key"), footer: Text("Get key from Bridge, or +code in dojo")) {
SecureField("sampel-ticlyt-migfun-falmel", text: $code)
.textContentType(.password)
.keyboardType(.asciiCapable)
}
Section {
Button(action: startSession) {
Text("Continue")
}
Button(action: openBridge) {
Text("Open Bridge")
}
Button(action: openPurchaseID) {
Text("Purchase an Urbit ID")
}
}
}
.disabled(isAuthenticating)
.navigationBarTitle("Login")
.keyboardObserving()
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
enum LoginViewError: LocalizedError {
case invalidURL(String)
case invalidCode(String)
var errorDescription: String? {
switch self {
case .invalidURL(let url):
return "Invalid URL: \"\(url)\""
case .invalidCode:
return "Invalid access key"
}
}
}
extension LoginView {
private func startSession() {
guard let url = URL(string: url) else {
store.dispatch(AppErrorAction(error: LoginViewError.invalidURL(self.url)))
return
}
guard let code = try? Code(string: code) else {
store.dispatch(AppErrorAction(error: LoginViewError.invalidCode(self.code)))
return
}
store.dispatch(AppThunk.startSession(credentials: AirlockCredentials(url: url, code: code)))
}
private func openBridge() {
UIApplication.shared.open(.bridgeURL)
}
private func openPurchaseID() {
UIApplication.shared.open(.purchaseIDURL)
}
}
extension URL {
static let bridgeURL = URL(string: "https://bridge.urbit.org/")!
static let purchaseIDURL = URL(string: "https://urbit.org/using/install/#id")!
}
|
//
// DetailViewController.swift
// BlinkList!
//
// Created by omokagbo on 19/04/2021.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var authorLabel: UILabel!
var imageName = UIImage()
var titleLbl = ""
var authorLbl = ""
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = imageName
titleLabel.text = titleLbl
authorLabel.text = authorLbl
}
}
|
import json;
/*
print json_type("/home/wozniak/test.json", "main")
print json_list_length("/home/wozniak/test.json", "main")
print json_get("/home/wozniak/test.json", "main")
print json_dict_entries("/home/wozniak/test.json", "repository")
print json_get("/home/wozniak/test.json", "repository,url")
*/
trace(json_type(input("/home/wozniak/test.json"), "main"));
trace(json_list_length(input("/home/wozniak/test.json"), "main"));
trace(json_get(input("/home/wozniak/test.json"), "main"));
trace(json_dict_entries(input("/home/wozniak/test.json"), "repository"));
trace(json_get(input("/home/wozniak/test.json"), "repository,url"));
trace(json_get(input("/home/wozniak/test.json"), "x"));
|
//
// ContentView.swift
// TikTokTrainer
//
// Created by Natascha Kempfe on 2/21/21.
//
import Foundation
import SwiftUI
import StatefulTabView
enum MainTabs {
case tutorialTab,
cameraTab,
historyTab
}
struct ContentView: View {
@State private var selectedTab = 1
let rgbValue = 0x141414
let minDragThreshold: CGFloat = 50.0
let numTabs = 3
init() {
resetTabBarColor()
}
func resetTabBarColor() {
UITabBar.appearance().isTranslucent = false
}
func tabItem(iconName: String, text: String, color: Color) -> some View {
VStack {
Label(text, systemImage: iconName)
.foregroundColor(color)
}
}
var body: some View {
StatefulTabView(selectedIndex: $selectedTab) {
Tab(title: "Tutorial", systemImageName: "clock") {
TutorialView()
.highPriorityGesture(DragGesture().onEnded(viewDragged))
}
Tab(title: "Record", systemImageName: "video") {
CameraTabView()
.highPriorityGesture(DragGesture().onEnded(viewDragged))
}
Tab(title: "History", systemImageName: "questionmark") {
HistoryView()
.highPriorityGesture(DragGesture().onEnded(viewDragged))
}
}
.barTintColor(.red)
.unselectedItemTintColor(.gray)
.barAppearanceConfiguration(.transparent)
.barBackgroundColor(UIColor(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
))
}
private func viewDragged(_ val: DragGesture.Value) {
guard abs(val.translation.width) > minDragThreshold else { print("Width: \(val.translation.width)"); return }
if val.translation.width > 0 && self.selectedTab != 0 {
self.selectedTab -= 1
} else if val.translation.width < 0 && self.selectedTab < (numTabs-1) {
self.selectedTab += 1
} else {
print("Width: \(val.translation.width)")
print("Selected tab: \(self.selectedTab)")
}
}
}
|
//
// TestAPIResponseUSDRates.swift
// PaypayCurrencyConverterTests
//
// Created by Chung Han Hsin on 2021/3/8.
//
import XCTest
@testable import PaypayCurrencyConverter
class TestAPIResponseUSDRates: XCTestCase {
override func setUp() {}
override func tearDown() {}
func testAPIResponseUSDRates() {
guard
let filePath = Bundle(for: Swift.type(of: self)).path(forResource: "currencylayer|live", ofType: "json"),
let data = try? Data(contentsOf: URL(fileURLWithPath: filePath))
else {
XCTFail("file is not exist or something wrong.")
return
}
let decoder = JSONDecoder()
do {
let response = try decoder.decode(APIResponseUSDRates.self, from: data)
XCTAssertNotNil(response)
// test basic repsonse
XCTAssertEqual(response.success, true)
XCTAssertEqual(response.terms, "https://currencylayer.com/terms")
XCTAssertEqual(response.privacy, "https://currencylayer.com/privacy")
// test currencies
let rates = response.currenciesRate
// test three elements: { "USDAED": 3.673042, "USDAFN": 77.450404, "USDALL": 103.625041 }
guard let USDAED = rates["USDAED"] else {
XCTFail("USDAED should in currencies")
return
}
guard let USDAFN = rates["USDAFN"] else {
XCTFail("USDAFN should in currencies")
return
}
guard let USDALL = rates["USDALL"] else {
XCTFail("ALL should in currencies")
return
}
XCTAssertEqual(USDAED, 3.673042)
XCTAssertEqual(USDAFN, 77.450404)
XCTAssertEqual(USDALL, 103.625041)
// test currencies count
XCTAssertEqual(rates.count, 168)
} catch {
XCTFail(error.localizedDescription)
}
}
}
|
//
// Location.swift
// WeatherMan
//
// Created by Jesse Tayler on 8/8/19.
// Copyright © 2019 Jesse Tayler. All rights reserved.
//
import Combine
import SwiftUI
import CoreLocation
class Location: NSObject, CLLocationManagerDelegate, ObservableObject, Identifiable {
static let shared = Location()
@Published var cityStore: CityStore
@Published var locationAuthorizationStatus: CLAuthorizationStatus = .notDetermined
private let manager: CLLocationManager
var localCity = City()
var location: CLLocation?
init(manager: CLLocationManager = CLLocationManager()) {
self.manager = manager
self.cityStore = CityStore(isLargeView: true)
super.init()
}
func startUpdating() {
manager.desiredAccuracy = kCLLocationAccuracyHundredMeters
manager.distanceFilter = 100
manager.requestWhenInUseAuthorization()
manager.delegate = self
manager.requestLocation()
#if os(iOS)
manager.startUpdatingLocation()
#endif
}
func startReceivingSignificantLocationChanges() {
let authorizationStatus = CLLocationManager.authorizationStatus()
if authorizationStatus != .authorizedAlways && authorizationStatus != .authorizedWhenInUse {
print("not authorized")
return
}
#if os(OSX)
if CLLocationManager.significantLocationChangeMonitoringAvailable() {
print("significantLocationChangeMonitoring not available")
manager.startMonitoringSignificantLocationChanges()
}
manager.startUpdatingLocation()
#endif
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("locationManager location change \(locations)")
location = locations.last
if let location = location {
self.reverseGeo(location: location)
}
}
func reverseGeo(location: CLLocation) {
CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) in
if let error = error {
print("reverse geodcode fail: \(error.localizedDescription)")
} else if let placemark = placemarks?.first {
self.updateCity(toPlacemark: placemark)
}
})
}
func updateCity(toPlacemark: CLPlacemark) {
if let name = toPlacemark.locality {
if localCity.name != name {
if let location = toPlacemark.location {
localCity = City(name: name, longitude: location.coordinate.longitude, latitude: location.coordinate.latitude, isLocal: true)
print("located \(localCity.name)")
guard let city = cityStore.cities.first else {
cityStore.cities.append(localCity)
return
}
if city.isLocal {
cityStore.cities.remove(at: 0)
}
cityStore.cities.insert(localCity, at: 0)
print("city count \(cityStore.cities.count)")
#if os(OSX)
#elseif os(iOS)
#elseif os(tvOS)
Network.fetchWeather(for: localCity) { (weather) in }
#elseif os(watchOS)
Network.fetchWeather(for: localCity) { (weather) in }
#endif
}
}
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
locationAuthorizationStatus = status
if locationAuthorizationStatus == .authorizedWhenInUse {
#if os(OSX)
manager.startUpdatingLocation()
#elseif os(iOS)
manager.startUpdatingLocation()
#elseif os(tvOS)
// compiles for TV OS
#elseif os(watchOS)
manager.startUpdatingLocation()
#endif
}
}
}
|
//
// ItemDescriptionCell.swift
// MyLoqta
//
// Created by Ashish Chauhan on 13/08/18.
// Copyright © 2018 AppVenturez. All rights reserved.
//
import UIKit
class ItemDescriptionCell: BaseTableViewCell, NibLoadableView, ReusableView {
@IBOutlet weak var lblTitle: AVLabel!
@IBOutlet weak var lblValue: AVLabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configureCell(data: [String: Any]) {
if let title = data[Constant.keys.kTitle] as? String {
self.lblTitle.text = title
} else {
self.lblTitle.text = ""
}
if let value = data[Constant.keys.kValue] as? String {
self.lblValue.text = value
} else {
self.lblValue.text = ""
}
}
func configureAddressCell(order: Product, indexPath: IndexPath) {
if indexPath.row == 0 {
self.lblTitle.text = "Delivery".localize()
if let shipping = order.shipping {
self.lblValue.text = Helper.returnShippingTitle(shipping: shipping)
}
} else {
if let shiping = order.shipping {
if shiping == 3 {
self.lblTitle.text = "Item location".localize()
} else {
self.lblTitle.text = "Shipping address".localize()
}
} else {
self.lblTitle.text = "Shipping address".localize()
}
if let address = order.address {
self.lblValue.text = address.getDisplayAddress()
} else {
self.lblValue.text = ""
}
}
}
}
|
import Foundation
struct SearchResponse: Decodable {
let data: [Datum]
}
struct Datum: Decodable {
let slug: String
let japanese: [Japanese]
let senses: [Sense]
}
struct Japanese: Decodable {
let word: String?
let reading: String?
}
struct Sense: Decodable {
let english_definitions: [String]
let parts_of_speech: [String]
let links: [Link]
}
struct Link: Decodable {
let text: String
let url: String
}
|
//
// CollectionsampleViewController.swift
// projectHo
//
// Created by Admin on 11/9/19.
// Copyright © 2019 Admin. All rights reserved.
//
import UIKit
class CollectionsampleViewController: UIViewController {
var users = ["AAA", "BBB", "CCC", "BBB", "CCC", "BBB", "CCC", "BBB", "CCC", "BBB", "CCC", "BBB", "CCC", "BBB", "CCC", "BBB", "CCC", "BBB", "CCC"]
var imageurls=["eee","fff","qqq","fff","qqq","fff","qqq","fff","qqq","fff","qqq","fff","qqq","fff","qqq","fff","qqq","fff","qqq"]
var screenwidth = UIScreen.main.bounds.width
var screenheight = UIScreen.main.bounds.height
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func backview(_ sender: Any) {
navigationController?.popViewController(animated: true)
}
}
extension CollectionsampleViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return users.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let item = collectionView.dequeueReusableCell(withReuseIdentifier: "UserCollectionViewCell",for: indexPath) as! UserCollectionViewCell
let user = users[indexPath.item]
item.imgAdater.image = UIImage(named: imageurls[indexPath.item])
item.lbName.text = user
return item
}
}
extension CollectionsampleViewController: UICollectionViewDelegate{
@available(iOS 13.0, *)
func collectionview(_ collectionview: UICollectionView, didSelectRowAt indexPath: IndexPath) {
let user = users[indexPath.row]
print(user)
}
}
extension CollectionsampleViewController: UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexpath:IndexPath)->CGSize{
let width=(screenwidth-50)/3
let height=screenheight/8
return CGSize(width:width, height:height)
}
}
|
//
// LeftPaddedTextField.swift
// companion
//
// Created by Uchenna Aguocha on 10/1/18.
// Copyright © 2018 Yves Songolo. All rights reserved.
//
import UIKit
class LeftPaddedTextField: UITextField {
override func textRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + 10,
y: bounds.origin.y,
width: bounds.width,
height: bounds.height)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + 10,
y: bounds.origin.y,
width: bounds.width,
height: bounds.height)
}
}
|
/*
The MIT License (MIT)
Copyright (c) 2016 Bertrand Marlier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
*/
import Foundation
public class GenericOrder//: Order
{
open let id: String
open let type: OrderType
open let side: Side
open var units: UInt
open let instrument: Instrument
open var entry: Price
open var stopLoss: Price?
open var takeProfit: Price?
open var expiry: Timestamp
init(instrument: Instrument, info: OrderInfo)
{
self.id = info.orderId
self.type = info.type
self.side = info.side
self.units = info.units
self.instrument = instrument
self.entry = info.entry
self.stopLoss = info.stopLoss
self.takeProfit = info.takeProfit
self.expiry = info.expiry
}
//func applyParameters
/*open func modify(change parameters: [OrderParameter], completion: @escaping (RequestStatus) -> ())
{
for param in parameters
{
switch param
{
case .stopLoss(let price): self.stopLoss = price
case .takeProfit(let price): self.takeProfit = price
case .entry(let price): self.entry = price!
case .expiry(let time): self.expiry = time! // expiry is mandatory in working orders
}
}
}*/
open func cancel(_ completion: @escaping (RequestStatus) -> ())
{
let _ = (instrument.account as? GenericAccount)?.removeOrder(id)
}
}
extension Order
{
var genericInstrument: GenericInstrument { return instrument as! GenericInstrument }
func modify(atTime time: Timestamp, parameters: [OrderParameter])
{
let updatedOrder = OrderUpdate(orderId: id,
time: time,
parameters: parameters)
genericInstrument.notify(tradeEvent: .orderUpdated(info: updatedOrder))
}
func expire(atTime time: Timestamp)
{
let event = TradeEvent.orderClosed(info: OrderClosure(orderId: id, time: time, reason: .expiry))
let _ = genericInstrument.genericAccount.removeOrder(id)
genericInstrument.notify(tradeEvent: event)
}
}
|
//
// ContentView.swift
// temperature_calculator
//
// Created by Borja Saez de Guinoa Vilaplana on 11/5/21.
//
import SwiftUI
struct ContentView: View {
let tempUnits : [UnitTemperature] = [.celsius, .kelvin, .fahrenheit]
@State var originTemp: String = ""
@State private var selectedInputUnit: UnitTemperature = .celsius
@State private var selectedOutputUnit: UnitTemperature = .celsius
private var resultTemperature: String {
guard let value = Double(originTemp) else { return "Enter the temperature" }
let inputUnitAndValue = Measurement.init(value: value, unit: selectedInputUnit)
let output = inputUnitAndValue.converted(to: selectedOutputUnit)
let formattedValue = String(format: "Temperature: %.1f", output.value)
return "\(formattedValue)\(output.unit.symbol)"
}
var body: some View {
NavigationView{
Form{
Section(header: Text("Enter the temperature")) {
TextField("Temp", text: $originTemp)
.keyboardType(.decimalPad)
}
Section(header: Text("Input Unit")) {
Picker("Input unit", selection: $selectedInputUnit) {
ForEach(tempUnits, id: \.self, content: {
Text($0.symbol)
})
}
}
Section(header: Text("Output Unit")) {
Picker("Output unit", selection: $selectedOutputUnit) {
ForEach(tempUnits, id: \.self, content: {
Text($0.symbol)
})
}
}
Section(header: Text("Result")) {
Text(resultTemperature)
}
}
.navigationBarTitle("Temperature calculator")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
|
//
// RestaurantCellView.swift
// RandomEats
//
// Created by Juan Reyes on 7/26/21.
//
import SwiftUI
struct RestaurantCellView: View {
let imageURL: String
let name: String
let rating: Double
let price: String
var body: some View {
RoundedRectangle(cornerRadius: 25.0)
.fill(Color.clear)
.frame(height: 175)
.overlay(
HStack(spacing:0) {
RemoteImage(url: imageURL)
.aspectRatio(contentMode: .fill)
.frame(width: 150, height: 150)
.clipShape(RoundedRectangle(cornerRadius: 25.0))
.overlay(
RoundedRectangle(cornerRadius: 25)
.stroke(Color.black, lineWidth: 5)
)
VStack {
Text(name)
.bold()
.frame(width: 200, height: 75)
.overlay(
Rectangle()
.stroke(Color.black, lineWidth: 5)
)
HStack(spacing: 0) {
Text("\(rating)")
.frame(width: 100, height: 75)
.overlay(
Rectangle()
.stroke(Color.black, lineWidth: 5)
)
Text("\(price)")
.frame(width: 100, height: 75)
.overlay(
Rectangle()
.stroke(Color.black, lineWidth: 5)
)
}
}
.padding()
}
)
}
}
struct RestaurantCellView_Previews: PreviewProvider {
static var previews: some View {
RestaurantCellView(imageURL: "poop", name: "poop", rating: 2.0, price: "2")
}
}
|
//
// AddTwo.swift
// LinkedList-Leetcode
//
// Created by cyzone on 2020/10/13.
//
import Foundation
/// 445. 两数相加 II
/// - Parameters:
/// - 给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。你可以假设除了数字 0 之外,这两个数字都不会以零开头。
/// 如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
/// 输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
/// 输出:7 -> 8 -> 0 -> 7
func addTwoNumbers1(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
if l1 == nil { return l2 }
if l2 == nil { return l1 }
var stack1 = Stack<ListNode>()
var stack2 = Stack<ListNode>()
var current1 = l1
var current2 = l2
while current1 != nil {
stack1.push(current1!)
current1 = current1?.next
}
while current2 != nil {
stack2.push(current2!)
current2 = current2?.next
}
var head:ListNode? = nil
var flag = 0
while !stack1.isEmpty && !stack2.isEmpty{
let node1 = stack1.pop()
let node2 = stack2.pop()
let newValue = node1!.val + node2!.val + flag
flag = newValue >= 10 ? 1: 0
let newNode = ListNode(newValue % 10)
newNode.next = head
head = newNode
}
if !stack1.isEmpty {
while !stack1.isEmpty {
let node = stack1.pop()
let newValue = node!.val + flag
flag = newValue >= 10 ? 1: 0
node?.val = newValue % 10
node?.next = head
head = node
}
flag = 0
}
if !stack2.isEmpty {
while !stack2.isEmpty {
let node = stack2.pop()
let newValue = node!.val + flag
flag = newValue >= 10 ? 1: 0
node?.val = newValue % 10
node?.next = head
head = node
}
flag = 0
}
if flag > 0 {
let temp = ListNode(flag)
temp.next = head
head = temp
}
return head
}
//输入:(7 -> 1 -> 6) +
// (5 -> 9 -> 2),即617 + 295
//输出:2 -> 1 -> 9,即912
func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
if l1 == nil { return l2 }
if l2 == nil { return l1 }
var current1 = l1
var current2 = l2
var flag = 0
var prev:ListNode? = nil
var head:ListNode?
while current1 != nil && current2 != nil {
let newValue = current1!.val + current2!.val + flag
let node = ListNode(newValue % 10)
if prev == nil {
head = node
}
prev?.next = node
prev = node
flag = newValue >= 10 ? 1 : 0
current1 = current1?.next
current2 = current2?.next
}
if current1 != nil {
while current1 != nil{
let newValue = current1!.val + flag
let node = ListNode(newValue % 10)
prev?.next = node
prev = node
current1 = current1?.next
flag = newValue >= 10 ? 1 : 0
}
}
if current2 != nil {
while current2 != nil{
let newValue = current2!.val + flag
let node = ListNode(newValue % 10)
prev?.next = node
prev = node
current2 = current2?.next
flag = newValue >= 10 ? 1 : 0
}
}
if flag > 0 {
let node = ListNode(flag)
prev?.next = node
}
return head
}
//24. 两两交换链表中的节点
//给定 1->2->3->4, 你应该返回 2->1->4->3.
//1->2->3->4->5 2->1->4->3->5
func swapPairs(_ head: ListNode?) -> ListNode? {
let dumyHead = ListNode(0)
dumyHead.next = head
var prev:ListNode? = dumyHead
while prev?.next != nil && prev?.next?.next != nil {
let node1 = prev?.next
let node2 = node1?.next
let next = node2?.next
node2?.next = node1
node1?.next = next
prev?.next = node2
prev = node1
}
return dumyHead.next
// if (head == nil || head?.next == nil) {return head}
//
// var current = head?.next //当前节点
// var prev = head //当前节点的前一个
// let result = current //头节点
//
// while current != nil {
// let temp = current?.next
// current?.next = prev
//
// current = temp?.next //一次移动两步
// if current == nil {
// prev?.next = temp //奇数个数时,直接连接最后一个节点
// }else{
// prev?.next = current
// }
// prev = temp
// }
//
// return result
}
|
//
// IntervalRangeViewController.swift
// JWSRxSwiftBeginningSample
//
// Created by Clint on 21/11/2018.
// Copyright © 2018 clintjang. All rights reserved.
//
import UIKit
final class DeferredViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("===============================")
let deferred = Observable<String>.deferred {
// just("defer")의 실행을 늦춰보자!!
Observable<String>.just("defer").debug()
}
// 딜레이 시키고 싶은 시간을 정하자
let delayTime = 3.0
print("== \(delayTime) 초 뒤에 subscribe 를 실행 할 것이고")
print("== 그때!! Observable<String>.just(..).debug() 가 실행 될 것입니다.")
print("\n\n")
// 3초 뒤에 "Observable<String>.just("defer").debug()" 실행
DispatchQueue.main.asyncAfter(deadline: .now() + delayTime) { [weak self] in
if let strongSelf = self {
deferred.subscribe(onNext:{ print($0) })
.disposed(by: strongSelf.disposeBag)
}
}
print("===============================")
print("\n\n")
}
}
|
//
// PDFViewController.swift
// HackerBooks
//
// Created by Akixe on 14/7/16.
// Copyright © 2016 AOA. All rights reserved.
//
import UIKit
class PDFViewController: UIViewController {
@IBOutlet weak var webView: UIWebView!
var model : Book
init(model: Book) {
self.model = model
super.init(nibName:nil, bundle:nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
syncModelAndView()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func syncModelAndView () {
if let bookData = model.bookPDF {
webView.loadData(bookData, MIMEType: "application/pdf", textEncodingName: "", baseURL: model.bookURL)
}
}
}
|
//
// WeatherAPI.swift
// WeatherApp
//
// Created by Bartek Poskart on 29/05/2020.
// Copyright © 2020 Bartek Poskart. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
struct WeatherMain: Codable {
var temp: Double?
var pressure: Int?
var humidity: Int?
var temp_min: Double?
var temp_max: Double?
}
struct Wind: Codable {
var speed: Double?
var deg: Int?
}
struct Clouds: Codable {
var all: Int?
}
struct Sys: Codable {
var type: Int?
var id: Int?
var message: Double?
var country: String?
var sunrise: Int?
var sunset: Int?
}
struct Weather: Codable {
var id: Int?
var main: String?
var description: String?
var icon: String?
}
struct WeatherResponse: Codable {
var id: Int?
var name: String?
var cod: Int?
var coord: Coord?
var weather: [Weather]
var main: WeatherMain?
var visibility: Int?
var wind: Wind?
var clouds: Clouds?
var dt: Int?
var sys: Sys?
}
struct Coord: Codable {
var lon: Double
var lat: Double
}
class WeatherAPI: RequestService {
static let kPathUrl = "/weather"
class func weather(_ id: Int) -> Single<WeatherResponse> {
return requestJSON(WeatherAPI.kPathUrl + "?id=\(id)" + "&appid=\(Constants.kApiKey)", params: EmptyParams(), method: .get)
}
class func weatherForLocation(lat: Double, lon: Double) -> Single<WeatherResponse> {
return requestJSON(WeatherAPI.kPathUrl + "?lat=\(lat)" + "&lon=\(lon)" + "&appid=\(Constants.kApiKey)", params: EmptyParams(), method: .get)
}
}
|
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
var someValue = 0
let serialQueue = DispatchQueue(label: "mySerialQueue")
func incrementValue() {
serialQueue.async {
someValue = someValue + 1
}
}
for _ in 0...999 {
DispatchQueue.global().async {
incrementValue()
}
}
sleep(2)
print(someValue) // always prints 1000
|
//
// GlawTapBarController.swift
// TermProject
//
// Created by kpugame on 2021/05/21.
//
import UIKit
class GlawTapBarController: UITabBarController {
var leisureURL:String?
var areaURL:String?
var weatherUIL: String?
var sgguCd: String?
override func viewDidLoad() {
super.viewDidLoad()
loadData()
}
func loadData()
{
if let navController = self.customizableViewControllers![0] as? UINavigationController
{
if let leisureViewController = navController.topViewController as? LeisureTableViewController
{
leisureViewController.url = leisureURL
leisureViewController.sgguCd = sgguCd
}
}
if let navController = self.customizableViewControllers![1] as? UINavigationController
{
if let areaViewController = navController.topViewController as? AreaTableViewController
{
areaViewController.url = areaURL
areaViewController.sgguCd = sgguCd
}
}
if let navController = self.customizableViewControllers![2] as? UINavigationController
{
if let weatherViewController = navController.topViewController as? WeatherViewController
{
globalMeasurements = []
weatherViewController.url = weatherUIL
weatherViewController.sgguCd = sgguCd
weatherViewController.beginParsing()
weatherViewController.setGlobalData()
}
}
}
}
|
//
// NameViewModel.swift
// Croesus
//
// Created by Ian Wanyoike on 02/02/2020.
// Copyright © 2020 Pocket Pot. All rights reserved.
//
import RxSwift
import RxCocoa
class NameViewModel {
private var person: PersonType
let firstName: BehaviorRelay<String?>
let lastName: BehaviorRelay<String?>
let disposeBag = DisposeBag()
init(person: PersonType) {
self.person = person
self.firstName = BehaviorRelay(value: person.firstName)
self.lastName = BehaviorRelay(value: person.lastName)
Disposables.create([
self.firstName.bind { [weak self] in
self?.person.firstName = $0
},
self.lastName.bind { [weak self] in
self?.person.lastName = $0
}
]).disposed(by: self.disposeBag)
}
}
|
//
// UIViewAnimation.swift
// jqSwiftExtensionSDK
//
// Created by Jefferson Qin on 2018/7/25.
//
import Foundation
import UIKit
public class JQAnimationController {
private init() {}
public static func animation(withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.AnimationOptions, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) {
UIView.animate(withDuration: duration, delay: delay, options: options, animations: animations, completion: completion)
}
public static func animationWithEase(withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.AnimationOptions, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) {
UIView.animate(withDuration: duration, delay: delay, options: [.curveEaseInOut, options], animations: animations, completion: completion)
}
public static func animationWithString(withDuration duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat, options: UIView.AnimationOptions, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) {
UIView.animate(withDuration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity, options: options, animations: animations, completion: completion)
}
public static func transitionAddSubViewInSuperView(ofView view : UIView, inSuperView superView: UIView, withDuration duration: TimeInterval, options: UIView.AnimationOptions, completion: ((Bool) -> Void)?) {
UIView.transition(with: view, duration: duration, options: options, animations: {
superView.addSubview(view)
}, completion: completion)
}
public static func transitionRemoveSubViewFromSuperView(ofView view : UIView, fromSuperView superView: UIView, withDuration duration: TimeInterval, options: UIView.AnimationOptions, completion: ((Bool) -> Void)?) {
UIView.transition(with: superView, duration: duration, options: options, animations: {
view.removeFromSuperview()
}, completion: completion)
}
public static func transitionHideSubViewInSuperView(ofView view: UIView, inSuperView superView: UIView, withDuration duration: TimeInterval, options: UIView.AnimationOptions, completion: ((Bool) -> Void)?) {
UIView.transition(with: superView, duration: duration, options: options, animations: {
view.isHidden = true
}, completion: completion)
}
public static func transitionUnhideSubViewInSuperView(ofView view: UIView, inSuperView superView: UIView, withDuration duration: TimeInterval, options: UIView.AnimationOptions, completion: ((Bool) -> Void)?) {
UIView.transition(with: superView, duration: duration, options: options, animations: {
view.isHidden = false
}, completion: completion)
}
public static func transitionFromImageToImage(inImageView view: UIImageView, to image: UIImage, withDuration duration: TimeInterval, options: UIView.AnimationOptions, completion: ((Bool) -> Void)?) {
UIView.transition(with: view, duration: duration, options: options, animations: {
view.image = image
}, completion: completion)
}
public static func transitionFromViewToView(fromView view1: UIView, toView view2: UIView, withDuration duration: TimeInterval, options: UIView.AnimationOptions, completion: ((Bool) -> Void)?) {
UIView.transition(from: view1, to: view2, duration: duration, options: options, completion: completion)
}
public static func transitionForLabelTextByVerticalCubeTransition_animation(withLabel label: UILabel, ofBackgroundColor color: UIColor, toText text: String, vanishDirection direction: AnimationVerticalDirection, withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.AnimationOptions) {
label.backgroundColor = color
let auxLabel = UILabel(frame: label.frame)
auxLabel.backgroundColor = color
auxLabel.text = text
auxLabel.font = label.font
auxLabel.textAlignment = label.textAlignment
auxLabel.textColor = label.textColor
let auxLabelOffset = CGFloat(direction.rawValue) * label.frame.height / 2.0
auxLabel.transform = CGAffineTransform(translationX: 0.0, y: auxLabelOffset).scaledBy(x: 1.0, y: 0.1)
label.superview?.addSubview(auxLabel)
UIView.animate(withDuration: duration, delay: delay, options: [options], animations: {
auxLabel.transform = .identity
label.transform = CGAffineTransform(translationX: 0.0, y: -auxLabelOffset)
.scaledBy(x: 1.0, y: 0.1)
}, completion: { _ in
label.text = auxLabel.text
label.transform = .identity
auxLabel.removeFromSuperview()
})
}
public static func transitionForLabelTextByHorizontalCubeTransition_animation(withLabel label: UILabel, ofBackgroundColor color: UIColor, toText text: String, vanishDirection direction: AnimationHorizontalDirection, withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.AnimationOptions) {
label.backgroundColor = color
let auxLabel = UILabel(frame: label.frame)
auxLabel.backgroundColor = color
auxLabel.text = text
auxLabel.font = label.font
auxLabel.textAlignment = label.textAlignment
auxLabel.textColor = label.textColor
let auxLabelOffset = CGFloat(direction.rawValue) * label.frame.width / 2.0
auxLabel.transform = CGAffineTransform(translationX: auxLabelOffset, y: 0.0)
.scaledBy(x: 0.1, y: 1.0)
label.superview?.addSubview(auxLabel)
UIView.animate(withDuration: duration, delay: delay, options: [options], animations: {
auxLabel.transform = .identity
label.transform = CGAffineTransform(translationX: -auxLabelOffset, y: 0.0).scaledBy(x: 0.1, y: 1.0)
}, completion: { _ in
label.text = auxLabel.text
label.transform = .identity
auxLabel.removeFromSuperview()
})
}
public static func transitionForLabelTextByFade_animation(ofLabel label: UILabel, withText text: String, byXOffset xOffset: CGFloat, byYOffset yOffset: CGFloat, withHorizontalFanishDirection xDirection: AnimationHorizontalDirection, withVerticalFanishDirection yDirection: AnimationVerticalDirection, withFanishDuration fDuration : TimeInterval, withEnterDuration eDuration: TimeInterval, withEnterDelay eDelay: TimeInterval, withBeginDelay delay: TimeInterval) {
let auxLabel = UILabel(frame: label.frame)
auxLabel.text = text
auxLabel.font = label.font
auxLabel.textAlignment = label.textAlignment
auxLabel.textColor = label.textColor
auxLabel.backgroundColor = .clear
auxLabel.transform = CGAffineTransform(translationX: xOffset * CGFloat(xDirection.rawValue), y: yOffset * CGFloat(yDirection.rawValue))
auxLabel.alpha = 0
label.superview?.addSubview(auxLabel)
UIView.animate(withDuration: fDuration, delay: delay, options: .curveEaseIn, animations: {
label.transform = CGAffineTransform(translationX: xOffset * CGFloat(xDirection.rawValue), y: yOffset * CGFloat(yDirection.rawValue))
label.alpha = 0.0
}, completion: nil)
UIView.animate(withDuration: eDuration, delay: eDelay, options: .curveEaseIn, animations: {
auxLabel.transform = .identity
auxLabel.alpha = 1.0
}, completion: {_ in
auxLabel.removeFromSuperview()
label.text = text
label.alpha = 1.0
label.transform = .identity
})
}
public static func animationFrameWithKeys(withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.KeyframeAnimationOptions, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) {
UIView.animateKeyframes(withDuration: duration, delay: delay, options: options, animations: animations, completion: completion)
}
public static func addKeyFrameAnimation(withStartTimePercentage startTimePercentage: Double, withDurationPercentage durationPercentage: Double, animations: @escaping () -> Void) {
UIView.addKeyframe(withRelativeStartTime: startTimePercentage, relativeDuration: durationPercentage, animations: animations)
}
public static func addKeyFrame_ViewDisappear_ReduceAlpha(withView view: UIView, withStartTimePercentage startTimePercentage: Double, withDurationPercentage durationPercentage: Double) {
UIView.addKeyframe(withRelativeStartTime: startTimePercentage, relativeDuration: durationPercentage) {
view.alpha = 0
}
}
public static func addKeyFrame_ViewReAppear_IncreaseAlpha(withView view: UIView, withStartTimePercentage startTimePercentage: Double, withDurationPercentage durationPercentage: Double) {
UIView.addKeyframe(withRelativeStartTime: startTimePercentage, relativeDuration: durationPercentage) {
view.alpha = 1
}
}
public enum AnimationVerticalDirection: Int {
case up = 1
case down = -1
}
public enum AnimationHorizontalDirection: Int {
case left = 1
case right = -1
}
public enum RotationDirection: Int {
case clockDirection = 1
case antiClockDirection = -1
}
}
|
//
// ViewController.swift
// Set
//
// Created by Teo on 2/15/19.
// Copyright © 2019 Teo. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private lazy var game = Set()
private var usingButtonsIndices = [Int]()
@IBOutlet var cardButtons: [UIButton]!
@IBAction func touchCard(_ sender: UIButton) {
let buttonIndex = cardButtons.firstIndex(of: sender)!
if let cardIndex = usingButtonsIndices.firstIndex(of: buttonIndex){
if game.cards[cardIndex].isSelected == true{
game.cards[cardIndex].isSelected = false
cardButtons[buttonIndex].layer.borderWidth = 0
game.selectedCards = game.selectedCards.filter {$0 != game.cards[cardIndex] }
}
else{
game.cards[cardIndex].isSelected = true
cardButtons[buttonIndex].layer.borderWidth = 3.0
cardButtons[buttonIndex].layer.borderColor = UIColor.blue.cgColor
cardButtons[buttonIndex].layer.cornerRadius = 8.0
game.selectedCards += [game.cards[cardIndex]]
if game.selectedCards.count > 3{
let removedSelectionCard = game.selectedCards.remove(at: 0)
removedSelectionCard.isSelected = false
let removedSelectionCardIndex = game.cards.firstIndex(of: removedSelectionCard)!
cardButtons[usingButtonsIndices[removedSelectionCardIndex]].layer.borderWidth = 0
}
}
updateViewFromModel()
}
}
@IBAction func newGame(_ sender: UIButton) {
for button in cardButtons{
button.layer.borderWidth = 0
button.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
button.setTitle(" ", for: UIControl.State.normal)
button.layer.cornerRadius = 0
}
usingButtonsIndices = [Int]()
game = Set()
while usingButtonsIndices.count < 12 {
let randomIndex = cardButtons.count.arc4random
if !usingButtonsIndices.contains( randomIndex ){
cardButtons[randomIndex].backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
usingButtonsIndices += [randomIndex]
}
}
for i in 0...11{
let shape = game.cards[i].shape
var color: UIColor
var alpha: CGFloat
switch game.cards[i].strip{
case "a":
alpha = 0.15
case "b":
alpha = 0.5
default:
alpha = 1.0
}
switch game.cards[i].color{
case "Red":
color = UIColor(red: 222/255.0, green: 0/255.0, blue: 0/255.0, alpha: alpha)
case "Blue":
color = UIColor(red: 0/255.0, green: 0/255.0, blue: 222/255.0, alpha: alpha)
default:
color = UIColor(red: 76/255.0, green: 170/255.0, blue: 0/255.0, alpha: alpha)
}
cardButtons[usingButtonsIndices[i]].setTitle(shape, for: UIControl.State.normal)
cardButtons[usingButtonsIndices[i]].setTitleColor(color, for: UIControl.State.normal)
}
}
@IBAction func dealThreeCards(_ sender: UIButton) {
if (usingButtonsIndices.count > 0 && usingButtonsIndices.count < 23) {
game.dealThreeCards()
let currentNumberOfCards = usingButtonsIndices.count
while usingButtonsIndices.count < currentNumberOfCards + 3 {
let randomIndex = cardButtons.count.arc4random
if !usingButtonsIndices.contains( randomIndex ){
cardButtons[randomIndex].backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
usingButtonsIndices += [randomIndex]
}
}
for i in currentNumberOfCards-1...currentNumberOfCards+2 {
let shape = game.cards[i].shape
var color: UIColor
var alpha: CGFloat
switch game.cards[i].strip{
case "a":
alpha = 0.15
case "b":
alpha = 0.5
default:
alpha = 1.0
}
switch game.cards[i].color{
case "Red":
color = UIColor(red: 222/255.0, green: 0/255.0, blue: 0/255.0, alpha: alpha)
case "Blue":
color = UIColor(red: 0/255.0, green: 0/255.0, blue: 222/255.0, alpha: alpha)
default:
color = UIColor(red: 76/255.0, green: 170/255.0, blue: 0/255.0, alpha: alpha)
}
cardButtons[usingButtonsIndices[i]].setTitle(shape, for: UIControl.State.normal)
cardButtons[usingButtonsIndices[i]].setTitleColor(color, for: UIControl.State.normal)
}
}
}
@IBAction func cheat(_ sender: UIButton) {
var possible = [Card]()
let combinations = game.cards.combinations.filter {$0.count == 3}
for c in combinations{
if game.isMatched(threeCards: c){
possible = c
break
}
}
let indices = possible.map {game.cards.firstIndex(of: $0)}
for index in indices{
cardButtons[usingButtonsIndices[index!]].layer.borderWidth = 3.0
cardButtons[usingButtonsIndices[index!]].layer.borderColor = UIColor.blue.cgColor
cardButtons[usingButtonsIndices[index!]].layer.cornerRadius = 8.0
}
}
func updateViewFromModel() {
if game.isMatched(threeCards: game.selectedCards){
let indices = game.selectedCards.map {game.cards.firstIndex(of: $0)}
var cards = [Card]()
for index in indices{
cardButtons[usingButtonsIndices[index!]].layer.borderWidth = 0
cardButtons[usingButtonsIndices[index!]].setTitle(" ", for: UIControl.State.normal)
cardButtons[usingButtonsIndices[index!]].backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
cards += [game.cards[index!]]
}
//clean up usingButtonIndices
usingButtonsIndices = usingButtonsIndices.filter { !indices.contains(usingButtonsIndices.index(of: $0)!) }
for card in cards{
game.usedCards += [card]
game.cards = game.cards.filter {$0 != card}
}
game.selectedCards.removeAll()
}
}
}
|
//
// LoadingAnimation.swift
// stckchck
//
// Created by Pho on 14/09/2018.
// Copyright © 2018 stckchck. All rights reserved.
//
import Foundation
import UIKit
import Lottie
class LoadingAnimation: UIView {
private let loadingAnimation = LOTAnimationView(name: "LoadingAnimation")
private override init(frame: CGRect) {
super.init(frame: frame)
configureView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func draw(_ rect: CGRect) {
loadingAnimation.frame = self.bounds
}
fileprivate func configureView() {
self.frame = CGRect(x: UIScreen.main.bounds.midX - 90, y: (UIScreen.main.bounds.midY - 90) - 80, width: 180, height: 180)
self.backgroundColor = .clear
self.alpha = 0
loadingAnimation.contentMode = .scaleAspectFill
loadingAnimation.animationSpeed = 1.0
loadingAnimation.loopAnimation = true
addSubview(loadingAnimation)
}
func display() {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
DispatchQueue.main.async { [weak weakSelf = self] in
weakSelf?.loadingAnimation.play(fromFrame: 1, toFrame: 40, withCompletion: nil)
UIView.animate(withDuration: 0.2) { [unowned self] in
self.alpha = 1.0
}
}
}
func stop() {
DispatchQueue.main.async { [weak weakSelf = self] in
weakSelf?.loadingAnimation.stop()
weakSelf?.removeFromSuperview()
}
}
}
|
//
// Array+.swift
// TimerX
//
// Created by 이광용 on 05/05/2019.
// Copyright © 2019 GwangYongLee. All rights reserved.
//
import Foundation
extension Array where Element: Equatable {
mutating func insert(_ newElement: Element, after element: Element) {
insert(newElement,
at: (firstIndex { $0 == element } ?? endIndex) + 1)
}
}
|
//
// getMovieListDataFunction.swift
// boostcamp_3_iOS
//
// Created by 이호찬 on 14/12/2018.
// Copyright © 2018 leehochan. All rights reserved.
//
import UIKit
class MovieStaticMethods {
static func getMovieData(completion: @escaping (_ isSucceed: Bool) -> Void) {
// 전에 저장되있던 캐시 이미지 삭제
MovieListData.shared.cache?.removeAllObjects()
let orderType = MovieListData.shared.sortRule.rawValue
guard let url = URL(string: "http://connect-boxoffice.run.goorm.io/movies?order_type=\(orderType)") else { return }
let session: URLSession = URLSession(configuration: .default)
let dataTask: URLSessionDataTask = session.dataTask(with: url) { (data: Data?, response: URLResponse?, error: Error?) in
if let error = error {
completion(false)
print(error.localizedDescription)
return
}
guard let data = data else {
completion(false)
return
}
do {
let apiResponse: MovieListAPIResopnse = try JSONDecoder().decode(MovieListAPIResopnse.self, from: data)
MovieListData.shared.movieLists = apiResponse.movies
completion(true)
} catch {
completion(false)
}
}
dataTask.resume()
}
}
|
//
// TheatresViewController.swift
// ChatFlix
//
// Created by Zeeshan Khan on 29/4/18.
// Copyright © 2018 Zeeshan Khan. All rights reserved.
//
import UIKit
import MapKit
class TheatresViewController: UIViewController{
@IBOutlet weak var mapView: MKMapView!
var currentLocation: CLLocationCoordinate2D?
var currentTitle: String?
var theatres: [MKMapItem] = []
override func viewDidLoad() {
super.viewDidLoad()
addAnnotation(title: currentTitle!, coordinate: currentLocation!)
focusOn(coordinate: currentLocation!)
// Use helper function to pinpoint theatres
annotateTheatres()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func annotateTheatres() {
// Expand region
let regionRadius: CLLocationDistance = 15000
let coordinateRegion = MKCoordinateRegionMakeWithDistance(currentLocation!, regionRadius * 2.0, regionRadius * 2.0)
self.mapView.setRegion(coordinateRegion, animated: true)
// Make a request to find places of interest with "Movie"
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = "Movie Theatres"
request.region = mapView.region
// Start searching
let search = MKLocalSearch(request: request)
search.start(completionHandler: { (response, error) in
if error != nil {
self.displayErrorMessage(error!.localizedDescription)
} else if response!.mapItems.count == 0 {
self.displayErrorMessage("No Movies Theatres found in this area")
} else {
for item in response!.mapItems {
// Append to our list
self.theatres.append(item)
// Add item annotation
self.addAnnotation(title: item.name!, coordinate: item.placemark.coordinate)
}
}
})
}
func addAnnotation(title: String, lat: Double, long: Double) {
let annotation = MKPointAnnotation()
annotation.title = title
annotation.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
self.mapView.addAnnotation(annotation)
}
func addAnnotation(title: String, coordinate: CLLocationCoordinate2D) {
let annotation = MKPointAnnotation()
annotation.title = title
annotation.coordinate = coordinate
self.mapView.addAnnotation(annotation)
}
func focusOn(annotation: MKPointAnnotation) {
let regionRadius: CLLocationDistance = 1000
let coordinateRegion = MKCoordinateRegionMakeWithDistance(annotation.coordinate, regionRadius * 2.0, regionRadius * 2.0)
self.mapView.setRegion(coordinateRegion, animated: true)
self.mapView.selectAnnotation(annotation, animated: true)
}
func focusOn(coordinate: CLLocationCoordinate2D) {
let regionRadius: CLLocationDistance = 1000
let coordinateRegion = MKCoordinateRegionMakeWithDistance(coordinate, regionRadius * 2.0, regionRadius * 2.0)
self.mapView.setRegion(coordinateRegion, animated: true)
}
func displayErrorMessage(_ message: String) {
let alertController = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
// Created by Axel Ancona Esselmann on 8/10/18.
// Copyright © 2019 Axel Ancona Esselmann. All rights reserved.
//
import URN
public struct DeepLink<Root> where Root: StringRepresentable {
public let root: Root
public let queryDict: [String: Any]
public init?(url: URL) {
guard
let components = NSURLComponents(url: url, resolvingAgainstBaseURL: true),
let hostString = components.host,
let root = Root(rawValue: hostString)
else {
return nil
}
self.root = root
self.queryDict = url.toQueryItems()?.toDictionary() ?? [:]
}
}
|
//
// UIColor.swift
// P3UIKit
//
// Created by Oscar Swanros on 6/17/16.
// Copyright © 2016 Pacific3. All rights reserved.
//
#if os(iOS) || os(tvOS)
public typealias P3Color = UIColor
#else
public typealias P3Color = NSColor
#endif
public extension P3Color {
private static var _colorCache: [String:P3Color] = [:]
class func p3_fromHexColorConvertible<C: HexColorConvertible>(hexColorConvertible: C) -> P3Color {
return P3Color(p3_hex: hexColorConvertible.hexColor)
}
convenience init(p3_hex hex: String) {
if let c = P3Color._colorCache[hex] {
#if os(iOS) || os(tvOS)
self.init(cgColor: c.cgColor)
#else
self.init(calibratedRed: c.redComponent, green: c.greenComponent, blue: c.blueComponent, alpha: c.alphaComponent)
#endif
} else {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if hex.hasPrefix("#") {
let index = hex.index(after: hex.startIndex)
let hex = "\(hex[index...])"
let scanner = Scanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexInt64(&hexValue) {
switch hex.count {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
print("Invalid HEX string, number of characters after '#' should be either 3, 4, 6 or 8")
}
} else {
print("Scan HEX error")
}
} else {
print("Invalid HEX string, missing '#' as prefix")
}
#if os(iOS) || os(tvOS)
let color = P3Color(red: red, green: green, blue: blue, alpha: alpha)
P3Color._colorCache[hex] = color
self.init(cgColor: color.cgColor)
#else
let color = P3Color(
calibratedRed: red,
green: green,
blue: blue,
alpha: alpha
)
P3Color._colorCache[hex] = color
self.init(
calibratedRed: color.redComponent,
green: color.greenComponent,
blue: color.blueComponent,
alpha: color.alphaComponent
)
#endif
}
}
}
|
//
// SearchVC.swift
// SOYoutube
//
// Created by Hitesh on 11/7/16.
// Copyright © 2016 myCompany. All rights reserved.
//
import UIKit
class SearchVC: UIViewController {
@IBOutlet weak var tblSearchVideos: UITableView!
@IBOutlet weak var searchBarvideo: UISearchBar!
var arrSearch = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBOutlet weak var actionBack: UIButton!
//MARK: - UITableViewDelegate
// func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell? {
// let cell:VideoListCell = tableView.dequeueReusableCell(withIdentifier: "VideoListSearchCell", for: indexPath as IndexPath) as! VideoListCell
// cell.selectionStyle = UITableViewCell.SelectionStyle.none
//
// let videoDetails = arrSearch[indexPath.row]
//
//// cell.lblVideoName.text = videoDetails["videoTitle"] as? String
//// cell.lblSubTitle.text = videoDetails["videoSubTitle"] as? String
//
//// cell.imgVideoThumb.sd_setImageWithURL(NSURL(string: (videoDetails["imageUrl"] as? String)!))
// return cell
//
// }
// func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
//
// }
//
// func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
//
// }
// MARK: - Searchbar Delegate -
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
tblSearchVideos.reloadData()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
tblSearchVideos.reloadData()
searchBar.resignFirstResponder()
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if searchBar.text == "" {
self.arrSearch.removeAllObjects()
self.tblSearchVideos.reloadData()
return
}else if searchText.characters.count > 1 {
self.arrSearch.removeAllObjects()
self.searchYouttubeVideoData(searchText: searchText)
}else{
self.arrSearch.removeAllObjects()
self.tblSearchVideos.reloadData()
}
}
//MARK: Search Videos
func searchYouttubeVideoData(searchText:String) -> Void {
SOYoutubeAPI().getVideoWithTextSearch(searchText: searchText, nextPageToken: "", completion: { (videosArray, succses, nextpageToken) in
if(succses == true){
self.arrSearch.addObjects(from: videosArray)
if(self.arrSearch.count == 0){
self.tblSearchVideos.isHidden = true
}else{
self.tblSearchVideos.isHidden = false
}
}
self.tblSearchVideos.reloadData()
})
}
@IBAction func actionBack(sender: AnyObject) {
self.navigationController?.popViewController(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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension SearchVC: UITableViewDelegate, UITableViewDataSource {
//MARK: - UITableViewDelegate
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrSearch.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:VideoListCell = tableView.dequeueReusableCell(withIdentifier: "VideoListTopCell", for: indexPath as IndexPath) as! VideoListCell
cell.selectionStyle = UITableViewCell.SelectionStyle.none
// cell.lblVideoName.text = arrVideos[indexPath.row].snippet.channelTitle
// cell.lblSubTitle.text = arrVideos[indexPath.row].snippet.description
//
// let url = URL(string: arrVideos[indexPath.row].thumbnail.url)
// // imageView.kf.setImage(with: url)
// cell.imgVideoThumb.kf.setImage(with: url)
return cell
}
// func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return arrVideos.count
// }
// func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// let cell:VideoListCell = tableView.dequeueReusableCell(withIdentifier: "VideoListTopCell", for: indexPath as IndexPath) as! VideoListCell
// cell.selectionStyle = UITableViewCell.SelectionStyle.none
//
// // let videoDetails = arrVideos[indexPath.row]
//
// cell.lblVideoName.text = arrVideos[indexPath.row].snippet.channelTitle
// cell.lblSubTitle.text = arrVideos[indexPath.row].snippet.description
//
// let url = URL(string: arrVideos[indexPath.row].thumbnail.url)
// // imageView.kf.setImage(with: url)
// cell.imgVideoThumb.kf.setImage(with: url)
//
// // imgVideoThumb.sd_setImageWithURL(NSURL(string: (videoDetails["imageUrl"] as? String)!))
// return cell
// }
// func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
//
// }
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
// self.id = arrVideos[indexPath.row].id
performSegue(withIdentifier: "youtubeSegue", sender: self)
// self.navigationController?.pushViewController(dvc, animated: true)
}
// func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// }
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "youtubeSegue" {
// let dvc = segue.destination as! YoutubePlayViewController
// dvc.id = id
}
}
}
|
public protocol ListEmptySwitcher: class, PilesOrEmptyScreen {}
public class EmptySwitcher {
private weak var presenter: ListEmptySwitcher?
public init(_ presenter: ListEmptySwitcher) {
self.presenter = presenter
}
}
extension EmptySwitcher: PilesOrEmptyScreen {
public func presentPileList() {
presenter?.presentPileList()
}
public func presentEmpty() {
presenter?.presentEmpty()
}
}
|
//
// WalkthroughVC.swift
// D2020
//
// Created by Macbook on 2/26/20.
// Copyright © 2020 Abdallah Eslah. All rights reserved.
//
import UIKit
class WalkthroughVC: UIViewController {
//Mark: - Outlets
@IBOutlet var pageControl: UIPageControl!
@IBOutlet var nextButton:UIButton! {
didSet {
nextButton.layer.cornerRadius = 25.0
nextButton.layer.masksToBounds = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func loginButton(_ sender: Any) {
}
}
|
//
// AlertViewAnimations.swift
// TelerikUIExamplesInSwift
//
// Copyright (c) 2015 Telerik. All rights reserved.
//
import Foundation
class AlertAnimations: TKExamplesExampleViewController, TKListViewDelegate {
let alert = TKAlert()
let appearLabel = UILabel()
let hideLabel = UILabel()
let appearAnimationsList = TKListView()
let hideAnimationsList = TKListView()
let appearAnimations = TKDataSource(array: ["Scale in", "Fade in", "Slide from left", "Slide from top", "Slide from right", "Slide from bottom"])
let hideAnimations = TKDataSource(array: ["Scale out", "Fade out", "Slide to left", "Slide to top", "Slide to right", "Slide to bottom"])
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.addOption("Show Alert", action: show)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
alert.title = "Animations"
alert.style.backgroundStyle = TKAlertBackgroundStyle.Blur
alert.addActionWithTitle("Close") { (TKAlert, TKAlertAction) -> Bool in
return true
}
let block: TKDataSourceListViewSettings_InitCellWithItemBlock = { (listView: TKListView!, indexPath: NSIndexPath!, cell: TKListViewCell!, item: AnyObject!) -> Void in
cell.textLabel.font = UIFont.systemFontOfSize(12)
cell.textLabel.textAlignment = NSTextAlignment.Center
cell.textLabel.text = item as? String
}
self.appearAnimations.settings.listView.initCell(block)
self.hideAnimations.settings.listView.initCell(block)
self.view.addSubview(TKListView())
appearAnimationsList.frame = CGRectMake(0, 44, self.view.frame.size.width/2, self.view.frame.size.height)
appearAnimationsList.dataSource = self.appearAnimations
appearAnimationsList.delegate = self
appearAnimationsList.tag = 0
self.view.addSubview(appearAnimationsList)
appearAnimationsList.selectItemAtIndexPath(NSIndexPath(forItem:3, inSection: 0), animated: false, scrollPosition: UICollectionViewScrollPosition.None)
hideAnimationsList.frame = CGRectMake(self.view.frame.size.width/2 , 108, self.view.frame.size.width/2, self.view.frame.size.height + 20)
hideAnimationsList.dataSource = self.hideAnimations
hideAnimationsList.delegate = self
hideAnimationsList.tag = 1
self.view.addSubview(hideAnimationsList)
hideAnimationsList.selectItemAtIndexPath(NSIndexPath(forItem:5, inSection: 0), animated: false, scrollPosition: UICollectionViewScrollPosition.None)
appearLabel.frame = CGRectMake(0, 70, self.view.frame.size.width/2, 30)
appearLabel.text = "Show animation: "
appearLabel.backgroundColor = UIColor.whiteColor()
appearLabel.textColor = UIColor.blackColor()
appearLabel.font = UIFont.systemFontOfSize(12)
appearLabel.textAlignment = NSTextAlignment.Center
self.view.addSubview(appearLabel)
hideLabel.frame = CGRectMake(self.view.frame.size.width/2, 70 , self.view.frame.size.width/2, 30)
hideLabel.text = "Dismiss animation:"
hideLabel.backgroundColor = UIColor.whiteColor()
hideLabel.textColor = UIColor.blackColor()
hideLabel.font = UIFont.systemFontOfSize(12)
hideLabel.textAlignment = NSTextAlignment.Center
self.view.addSubview(hideLabel)
}
override func viewDidLayoutSubviews() {
var titleHeight:CGFloat = 60.0
if UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication().statusBarOrientation) {
titleHeight = 50.0
}
if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad {
titleHeight += 40;
}
let halfWidth:CGFloat = CGRectGetWidth(self.view.frame)/2.0
appearLabel.frame = CGRectMake(0.0, titleHeight + 10.0, halfWidth, 20.0)
hideLabel.frame = CGRectMake(halfWidth, titleHeight + 10.0, halfWidth, 20.0)
let height:CGFloat = CGRectGetHeight(self.view.frame) - titleHeight - 50.0
appearAnimationsList.frame = CGRectMake(0, titleHeight + 40, halfWidth, height)
hideAnimationsList.frame = CGRectMake(halfWidth, titleHeight + 40, halfWidth, height)
}
func show() {
let message = NSMutableString()
if let selected = appearAnimationsList.indexPathsForSelectedItems {
if (selected.count > 0) {
let indexPath:NSIndexPath = selected[0] as! NSIndexPath
message.appendString(String(format: "Alert did %@. \n", appearAnimations.items[indexPath.row] as! String))
}
}
if let selected = hideAnimationsList.indexPathsForSelectedItems {
if (selected.count > 0) {
let indexPath:NSIndexPath = selected[0] as! NSIndexPath
message.appendString(String(format: "It will %@ when closed. \n", appearAnimations.items[indexPath.row] as! String))
}
}
alert.message = message as String
alert.show(true)
}
//MARK: - TKListViewDelegate
func listView(listView: TKListView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if(listView.tag == 0) {
alert.style.showAnimation = TKAlertAnimation(rawValue: indexPath.row)!
} else {
alert.style.dismissAnimation = TKAlertAnimation(rawValue: indexPath.row)!
}
}
}
|
//
// PropertyWrappers.swift
// Template
//
// Created by Domagoj Kulundzic on 02/10/2019.
//
import Foundation
@propertyWrapper
public struct UserDefault<T> {
public let key: String
public let defaultValue: T
public init(_ key: String, defaultValue: T) {
self.key = key
self.defaultValue = defaultValue
}
public var wrappedValue: T {
get { return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue }
set { UserDefaults.standard.set(newValue, forKey: key) }
}
}
@propertyWrapper
public struct Atomic<T> {
private var value: T
private let lock = NSLock()
public init(wrappedValue value: T) {
self.value = value
}
public var wrappedValue: T {
get { return load() }
set { store(newValue: newValue) }
}
public func load() -> T {
lock.lock()
defer { lock.unlock() }
return value
}
public mutating func store(newValue: T) {
lock.lock()
defer { lock.unlock() }
value = newValue
}
}
|
//
// original.swift
// DollarWords
//
// Created by Michael Tackes on 2/18/15.
// Copyright (c) 2015 Michael Tackes. All rights reserved.
//
import Foundation
func simpleDispatch(words: [String]) {
var dollarWords = [String]()
var remainingWords = words.count
let countQueue = dispatch_queue_create("com.mtackes.dollarwords.counter", nil)
for word in words {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) {
if word.centValue() == 100 {
dispatch_sync(dispatch_get_main_queue()) {
dollarWords.append(word)
}
}
dispatch_async(countQueue) {
if --remainingWords == 0 {
printAllWithCount(dollarWords)
CFRunLoopStop(CFRunLoopGetMain())
}
}
}
}
CFRunLoopRun()
}
|
//
// IMUIWebImageDownloader.swift
// ImageDownload
//
// Created by oshumini on 2018/8/17.
// Copyright © 2018年 HXHG. All rights reserved.
//
import Foundation
public typealias downloadCompletionHandler = ((_ data:Data? , _ progressValue:Float, _ urlString: String,_ error: Error?) -> Void)
public class IMUIWebImageDownloader {
private var _imageData: NSMutableData = NSMutableData()
var callbacks = [downloadCompletionHandler]()
var task: URLSessionTask?
public func getRequestUrl() -> String {
return task?.originalRequest?.url?.absoluteString ?? ""
}
init(callback: @escaping downloadCompletionHandler) {
self.callbacks.append(callback)
}
public func addCallback(callback: @escaping downloadCompletionHandler) {
self.callbacks.append(callback)
}
public func appendData(with data: Data) {
self._imageData.append(data)
}
public func dispatchDownloader(_ session: URLSession, _ urlRequest: URLRequest) -> URLSessionTask? {
self.task = session.dataTask(with: urlRequest)
return self.task
}
public func completionHandler(with error: Error?) {
for callback in self.callbacks {
callback(self._imageData as Data, 1.0, (self.task?.currentRequest?.url?.absoluteString) ?? "" ,error)
}
}
}
|
//
// main.swift
// 20141105044严伟2
//
// Created by 20141105044y on 16/6/20.
// Copyright © 2016年 20141105044y. All rights reserved.
//
import Foundation
var i = 0
var sum = 0
while i < 101{
sum=sum+i
i++
}
print(sum) |
//
// LoginView.swift
// LadderPromise
//
// Created by Alexander Mason on 12/19/16.
// Copyright © 2016 Alexander Mason. All rights reserved.
//
import UIKit
import FirebaseDatabase
import FirebaseAuth
protocol LoginViewDelegate: class {
func presentAlertController()
func loginUser(email: String, password: String)
}
class LoginView: UIView {
weak var delegate: LoginViewDelegate?
let titleLoginImage = UIImageView()
let loginButton = UIButton()
let registerButton = UIButton()
let emailTextField = UITextField()
let passwordTextField = UITextField()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.secondaryTheme
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Button functions
func loginUserTapped() {
guard let email = emailTextField.text else { return }
guard let password = passwordTextField.text else { return }
delegate?.loginUser(email: email, password: password)
}
func registerButtonTapped() {
delegate?.presentAlertController()
}
}
extension LoginView {
// MARK: Setup LoginView subviews
func setupLoginView() {
setupTitleLoginLabel()
setupLoginButton()
setupRegisterButton()
setupEmailTextField()
setupPasswordTextField()
}
func setupTitleLoginLabel() {
self.addSubview(titleLoginImage)
titleLoginImage.backgroundColor = UIColor.clear
titleLoginImage.image = UIImage(named: "ladderImage")
titleLoginImage.translatesAutoresizingMaskIntoConstraints = false
titleLoginImage.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
titleLoginImage.topAnchor.constraint(equalTo: self.topAnchor, constant: self.bounds.height * 0.1).isActive = true
titleLoginImage.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.35).isActive = true
titleLoginImage.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.07).isActive = true
}
func setupLoginButton() {
self.addSubview(loginButton)
loginButton.backgroundColor = UIColor.mainTheme
loginButton.translatesAutoresizingMaskIntoConstraints = false
loginButton.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
loginButton.topAnchor.constraint(equalTo: self.centerYAnchor, constant: self.bounds.height * 0.05).isActive = true
loginButton.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.08).isActive = true
loginButton.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.4).isActive = true
loginButton.setToTheme()
loginButton.backgroundColor = UIColor.white
loginButton.setTitleColor(UIColor.black, for: .normal)
loginButton.setTitle("Login", for: .normal)
loginButton.addTarget(self, action: #selector(loginUserTapped), for: .touchUpInside)
}
func setupRegisterButton() {
self.addSubview(registerButton)
registerButton.backgroundColor = UIColor.mainTheme
registerButton.setTitle("Register", for: .normal)
registerButton.translatesAutoresizingMaskIntoConstraints = false
registerButton.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
registerButton.topAnchor.constraint(equalTo: self.loginButton.bottomAnchor, constant: self.bounds.height * 0.05).isActive = true
registerButton.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.08).isActive = true
registerButton.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.4).isActive = true
registerButton.setToTheme()
registerButton.backgroundColor = UIColor.white
registerButton.setTitleColor(UIColor.black, for: .normal)
registerButton.addTarget(self, action: #selector(registerButtonTapped), for: .touchUpInside)
}
func setupEmailTextField() {
self.addSubview(emailTextField)
emailTextField.translatesAutoresizingMaskIntoConstraints = false
emailTextField.setToTheme(string: "Enter your email")
emailTextField.backgroundColor = UIColor.white
emailTextField.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
emailTextField.topAnchor.constraint(equalTo: self.titleLoginImage.bottomAnchor, constant: self.bounds.height * 0.08).isActive = true
emailTextField.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.6).isActive = true
emailTextField.heightAnchor.constraint(equalToConstant: self.bounds.height * 0.07).isActive = true
}
func setupPasswordTextField() {
self.addSubview(passwordTextField)
passwordTextField.isSecureTextEntry = true
passwordTextField.translatesAutoresizingMaskIntoConstraints = false
passwordTextField.setToTheme(string: "Enter password")
passwordTextField.backgroundColor = UIColor.white
passwordTextField.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
passwordTextField.topAnchor.constraint(equalTo: self.emailTextField.bottomAnchor, constant: self.bounds.height * 0.03).isActive = true
passwordTextField.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.6).isActive = true
passwordTextField.heightAnchor.constraint(equalToConstant: self.bounds.height * 0.07).isActive = true
}
}
|
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
public class UnbufferedTokenStream: TokenStream {
internal var tokenSource: TokenSource
///
/// A moving window buffer of the data being scanned. While there's a marker,
/// we keep adding to buffer. Otherwise, _#consume consume()_ resets so
/// we start filling at index 0 again.
///
internal var tokens = [Token]()
///
/// The number of tokens currently in `self.tokens`.
///
/// This is not the buffer capacity, that's `self.tokens.count`.
///
internal var n = 0
///
/// `0...n-1` index into `self.tokens` of next token.
///
/// The `LT(1)` token is `tokens[p]`. If `p == n`, we are
/// out of buffered tokens.
///
internal var p = 0
///
/// Count up with _#mark mark()_ and down with
/// _#release release()_. When we `release()` the last mark,
/// `numMarkers` reaches 0 and we reset the buffer. Copy
/// `tokens[p]..tokens[n-1]` to `tokens[0]..tokens[(n-1)-p]`.
///
internal var numMarkers = 0
///
/// This is the `LT(-1)` token for the current position.
///
internal var lastToken: Token!
///
/// When `numMarkers > 0`, this is the `LT(-1)` token for the
/// first token in _#tokens_. Otherwise, this is `null`.
///
internal var lastTokenBufferStart: Token!
///
/// Absolute token index. It's the index of the token about to be read via
/// `LT(1)`. Goes from 0 to the number of tokens in the entire stream,
/// although the stream size is unknown before the end is reached.
///
/// This value is used to set the token indexes if the stream provides tokens
/// that implement _org.antlr.v4.runtime.WritableToken_.
///
internal var currentTokenIndex = 0
public init(_ tokenSource: TokenSource) throws {
self.tokenSource = tokenSource
try fill(1) // prime the pump
}
public func get(_ i: Int) throws -> Token {
// get absolute index
let bufferStartIndex = getBufferStartIndex()
if i < bufferStartIndex || i >= bufferStartIndex + n {
throw ANTLRError.indexOutOfBounds(msg: "get(\(i)) outside buffer: \(bufferStartIndex)..\(bufferStartIndex + n)")
}
return tokens[i - bufferStartIndex]
}
public func LT(_ i: Int) throws -> Token? {
if i == -1 {
return lastToken
}
try sync(i)
let index: Int = p + i - 1
if index < 0 {
throw ANTLRError.indexOutOfBounds(msg: "LT(\(i) gives negative index")
}
if index >= n {
//Token.EOF
assert(n > 0 && tokens[n - 1].getType() == CommonToken.EOF, "Expected: n>0&&tokens[n-1].getType()==Token.EOF")
return tokens[n - 1]
}
return tokens[index]
}
public func LA(_ i: Int) throws -> Int {
return try LT(i)!.getType()
}
public func getTokenSource() -> TokenSource {
return tokenSource
}
public func getText() -> String {
return ""
}
public func getText(_ ctx: RuleContext) throws -> String {
return try getText(ctx.getSourceInterval())
}
public func getText(_ start: Token?, _ stop: Token?) throws -> String {
return try getText(Interval.of(start!.getTokenIndex(), stop!.getTokenIndex()))
}
public func consume() throws {
//Token.EOF
if try LA(1) == CommonToken.EOF {
throw ANTLRError.illegalState(msg: "cannot consume EOF")
}
// buf always has at least tokens[p==0] in this method due to ctor
lastToken = tokens[p] // track last token for LT(-1)
// if we're at last token and no markers, opportunity to flush buffer
if p == n - 1 && numMarkers == 0 {
n = 0
p = -1 // p++ will leave this at 0
lastTokenBufferStart = lastToken
}
p += 1
currentTokenIndex += 1
try sync(1)
}
/// Make sure we have 'need' elements from current position _#p p_. Last valid
/// `p` index is `tokens.length-1`. `p+need-1` is the tokens index 'need' elements
/// ahead. If we need 1 element, `(p+1-1)==p` must be less than `tokens.length`.
///
internal func sync(_ want: Int) throws {
let need: Int = (p + want - 1) - n + 1 // how many more elements we need?
if need > 0 {
try fill(need)
}
}
///
/// Add `n` elements to the buffer. Returns the number of tokens
/// actually added to the buffer. If the return value is less than `n`,
/// then EOF was reached before `n` tokens could be added.
///
@discardableResult
internal func fill(_ n: Int) throws -> Int {
for i in 0..<n {
if self.n > 0 && tokens[self.n - 1].getType() == CommonToken.EOF {
return i
}
let t: Token = try tokenSource.nextToken()
add(t)
}
return n
}
internal func add(_ t: Token) {
if n >= tokens.count {
//TODO: array count buffer size
//tokens = Arrays.copyOf(tokens, tokens.length * 2);
}
if let wt = t as? WritableToken {
wt.setTokenIndex(getBufferStartIndex() + n)
}
tokens[n] = t
n += 1
}
///
/// Return a marker that we can release later.
///
/// The specific marker value used for this class allows for some level of
/// protection against misuse where `seek()` is called on a mark or
/// `release()` is called in the wrong order.
///
public func mark() -> Int {
if numMarkers == 0 {
lastTokenBufferStart = lastToken
}
let mark = -numMarkers - 1
numMarkers += 1
return mark
}
public func release(_ marker: Int) throws {
let expectedMark = -numMarkers
if marker != expectedMark {
throw ANTLRError.illegalState(msg: "release() called with an invalid marker.")
}
numMarkers -= 1
if numMarkers == 0 {
// can we release buffer?
if p > 0 {
// Copy tokens[p]..tokens[n-1] to tokens[0]..tokens[(n-1)-p], reset ptrs
// p is last valid token; move nothing if p==n as we have no valid char
tokens = Array(tokens[p ... n - 1])
n = n - p
p = 0
}
lastTokenBufferStart = lastToken
}
}
public func index() -> Int {
return currentTokenIndex
}
public func seek(_ index: Int) throws {
var index = index
// seek to absolute index
if index == currentTokenIndex {
return
}
if index > currentTokenIndex {
try sync(index - currentTokenIndex)
index = min(index, getBufferStartIndex() + n - 1)
}
let bufferStartIndex = getBufferStartIndex()
let i = index - bufferStartIndex
if i < 0 {
throw ANTLRError.illegalState(msg: "cannot seek to negative index \(index)")
}
else if i >= n {
throw ANTLRError.unsupportedOperation(msg: "seek to index outside buffer: \(index) not in \(bufferStartIndex)..<\(bufferStartIndex + n)")
}
p = i
currentTokenIndex = index
if p == 0 {
lastToken = lastTokenBufferStart
} else {
lastToken = tokens[p - 1]
}
}
public func size() -> Int {
fatalError("Unbuffered stream cannot know its size")
}
public func getSourceName() -> String {
return tokenSource.getSourceName()
}
public func getText(_ interval: Interval) throws -> String {
let bufferStartIndex = getBufferStartIndex()
let bufferStopIndex = bufferStartIndex + tokens.count - 1
let start = interval.a
let stop = interval.b
if start < bufferStartIndex || stop > bufferStopIndex {
throw ANTLRError.unsupportedOperation(msg: "interval \(interval) not in token buffer window: \(bufferStartIndex)...\(bufferStopIndex)")
}
let a = start - bufferStartIndex
let b = stop - bufferStartIndex
var buf = ""
for t in tokens[a...b] {
buf += t.getText()!
}
return buf
}
internal final func getBufferStartIndex() -> Int {
return currentTokenIndex - p
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.