hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
d747ad483c6d2badb0d2313a29cf0c301aae0af7
1,420
// // AppDelegate.swift // ios-templates // // Created by Mert Saraç on 7.04.2021. // import UIKit import Firebase @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. FirebaseApp.configure() return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
36.410256
179
0.733803
f9ee5c5186d9f614e5958339d3192c0198410604
3,228
/** 自动布局运行结果 loadView() (0.0, 0.0, 0.0, 0.0) viewDidLoad() (0.0, 0.0, 0.0, 0.0) viewWillAppear (0.0, 0.0, 0.0, 0.0) viewWillLayoutSubviews() (0.0, 0.0, 375.0, 667.0) viewDidLayoutSubviews() (0.0, 0.0, 375.0, 667.0) layoutSubviews() (0.0, 0.0, 375.0, 667.0) viewDidAppear (0.0, 0.0, 375.0, 667.0) loadView 直接指定视图的大小 loadView() (0.0, 0.0 , 395.0, 667.0) viewDidLoad() (0.0, 0.0, 395.0, 667.0) viewWillAppear (0.0, 0.0, 395.0, 667.0) viewWillLayoutSubviews() (0.0, 0.0, 375.0, 667.0) viewDidLayoutSubviews() (0.0, 0.0, 375.0, 667.0) layoutSubviews() (0.0, 0.0, 375.0, 667.0) viewDidAppear (0.0, 0.0, 375.0, 667.0) * viewWillLayoutSubviews 函数中,视图的大小被修改为 屏幕的大小,自动布局系统做的 在 didLayoutSubviews 重新设置了 view 的大小 loadView() (0.0, 0.0, 395.0, 667.0) viewDidLoad() (0.0, 0.0, 395.0, 667.0) viewWillAppear (0.0, 0.0, 395.0, 667.0) viewWillLayoutSubviews() (0.0, 0.0, 375.0, 667.0) viewDidLayoutSubviews() (0.0, 0.0, 395.0, 667.0) layoutSubviews() (0.0, 0.0, 395.0, 667.0) viewDidAppear (0.0, 0.0, 395.0, 667.0) 但是,在 dismiss 的时候,会执行 viewWillLayoutSubviews() (0.0, 667.0, 395.0, 667.0) viewDidLayoutSubviews() (0.0, 0.0, 395.0, 667.0) 造成了屏幕的闪动 > 提示:beta 4 & beta 5运行的效果不一样 结论:使用自动布局定义控件,视图大小会变成屏幕大小,如果强行设置,dismiss 又回造成屏幕闪烁! 使用非自动布局,纯代码设置控件大小,dismiss 的时候,不会调用 viewDidLaouySubviews loadView() (0.0, 0.0, 395.0, 667.0) viewDidLoad() (0.0, 0.0, 395.0, 667.0) viewWillAppear (0.0, 0.0, 395.0, 667.0) viewWillLayoutSubviews() (0.0, 0.0, 375.0, 667.0) viewDidLayoutSubviews() (0.0, 0.0, 375.0, 667.0) layoutSubviews() (0.0, 0.0, 395.0, 667.0) viewDidAppear (0.0, 0.0, 375.0, 667.0) */ import UIKit class LifeDemoViewController: UIViewController { override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { dismissViewControllerAnimated(true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() print("\(__FUNCTION__) \(view.frame)") } // override func viewDidAppear(animated: Bool) { // super.viewDidAppear(animated) // var screenBounds = UIScreen.mainScreen().bounds // screenBounds.size.width += 20 // view.frame = screenBounds // // print("\(__FUNCTION__) \(view.frame)") // // } // // override func viewWillAppear(animated: Bool) { // super.viewWillAppear(animated) // print("\(__FUNCTION__) \(view.frame)") // } // // // override func viewDidLayoutSubviews() { // super.viewDidLayoutSubviews() // //// var screenBounds = UIScreen.mainScreen().bounds //// screenBounds.size.width += 20 //// view.frame = screenBounds // // print("\(__FUNCTION__) \(view.frame)") // } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() print("\(__FUNCTION__) \(view.frame)") } override func loadView() { super.loadView() var screenView = UIScreen.mainScreen().bounds screenView.size.width += 20 view = UIView(frame: screenView) let v = LifeView() v.frame = screenView v.backgroundColor = UIColor.redColor() view.addSubview(v) print("\(__FUNCTION__) \(view.frame)") } }
29.081081
82
0.621437
3827fc2cbd77ae7348e6dfc65ae599b49ca178ef
675
// // GroupErrorProposer.swift // // // Created by Dmitriy Khalbaev on 05/06/2018. // Copyright © 2018 Dmitriy Khalbaev. All rights reserved. // import Foundation public class GroupErrorProposer: ErrorProposer { // MARK: Private properties fileprivate var proposers: [ErrorProposer] public init(proposers: [ErrorProposer]) { self.proposers = proposers } public func proposeAction(for error: Error) -> Proposition? { for proposer in proposers { guard let action = proposer.proposeAction(for: error) else { continue } return action } return nil } }
22.5
72
0.616296
9c3987453618f815f093d69bfe37aadd6e218854
11,781
// 9/1/2018 // DLetra App // Created by SEBASTIAN PADUANO (DUWAFARM) on 2018 // Copyright © 2018 DUWAFARM. All rights reserved. import UIKit import CoreData import GoogleMobileAds class RankingPropioViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, GADInterstitialDelegate{ @IBOutlet weak var lb_aciertos: UILabel! @IBOutlet weak var lb_tiempo: UILabel! @IBOutlet weak var lb_nombre: UILabel! @IBOutlet weak var lb_pos: UILabel! @IBOutlet weak var lb_nivelMostrado: UILabel! @IBOutlet weak var btn_menu: UIButton! @IBOutlet weak var btn_eligenivel: UIButton! @IBOutlet weak var btn_niveles: UIButton! @IBOutlet weak var miTabla: UITableView! //Variables private var colorVerde = UIColor(hex: "000000") var managedObjectContext: NSManagedObjectContext! var interstitial : GADInterstitial! //Intersticial private var PartidasVoz = [PartidaCuadrado]() //TIPO VOZ private var PartidasTexto = [PartidaCuadradoTexto]() //TIPO TEXTO var aciertos = Int() var formaHecha = String() var tiempoEmpleado = Int() var modoDeJuego: Bool = false private var nombreIntroducidoCambiarColor = "" private var puntosIntroducidosCambiarColor = Double() //Nombre introducido por el usuario private var btn_pressed = false //Booleano para el interstiticial var fontSize = CGFloat() var idUltimo = Int() private func resizeTextos(){ fontSize = Constantes.screenSize(screenSize: self.view.frame.size.width) lb_nivelMostrado.font = UIFont(descriptor: lb_tiempo.font.fontDescriptor, size: fontSize + 4) lb_tiempo.font = UIFont(descriptor: lb_tiempo.font.fontDescriptor, size: fontSize) lb_nombre.font = UIFont(descriptor: lb_tiempo.font.fontDescriptor, size: fontSize - 2) lb_pos.font = UIFont(descriptor: lb_tiempo.font.fontDescriptor, size: fontSize) lb_aciertos.font = UIFont(descriptor: lb_tiempo.font.fontDescriptor, size: fontSize) btn_menu.titleLabel?.font = UIFont(descriptor: (btn_menu.titleLabel?.font.fontDescriptor)!, size: fontSize) btn_niveles.titleLabel?.font = UIFont(descriptor: (btn_niveles.titleLabel?.font.fontDescriptor)!, size: fontSize) } override func viewDidLoad() { super.viewDidLoad() miTabla.separatorStyle = .none resizeTextos() cargarAnuncio() lb_nivelMostrado.text = formaHecha if(modoDeJuego){ loadDataVoz() } else{ loadDataTexto() } NotificationCenter.default.addObserver(self, selector: #selector(loadList), name: NSNotification.Name(rawValue: "load"), object: nil) //Notificacion para cargar la tabla desde otro lado. ponerPopUp() } func loadList(notification: NSNotification){ colorVerde = UIColor(hex: "0EA80E") //load data here if(modoDeJuego){ loadDataVoz() } else{ loadDataTexto() } miTabla.reloadData() } private func cargarAnuncio(){ //Cargamos el anuncio interstitial = GADInterstitial(adUnitID: "ca-app-pub-1913552533139737/7518229003") let request: GADRequest = GADRequest() interstitial.load(request) interstitial.delegate = self } private func loadDataTexto(){ managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext //Declaramos un objeto de tipo Managed Object Context para trabajar en el core data let predicateNivel:NSPredicate = NSPredicate(format: "nivel == %@", formaHecha) let predicate:NSPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateNivel] ) let partidaRequestTexto:NSFetchRequest<PartidaCuadradoTexto> = PartidaCuadradoTexto.fetchRequest() partidaRequestTexto.predicate = predicate do{ PartidasTexto = try managedObjectContext.fetch(partidaRequestTexto) } catch { } } private func loadDataVoz(){ managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext //Declaramos un objeto de tipo Managed Object Context para trabajar en el core data let predicateNivel:NSPredicate = NSPredicate(format: "nivel == %@", formaHecha) let predicate:NSPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateNivel] ) let partidaRequestVoz:NSFetchRequest<PartidaCuadrado> = PartidaCuadrado.fetchRequest() partidaRequestVoz.predicate = predicate do{ //Try and catch para ver si funciona el cargado de datos PartidasVoz = try managedObjectContext.fetch(partidaRequestVoz) } catch { } } private func orderData(){ if(modoDeJuego){ PartidasVoz = PartidasVoz.sorted{$0.puntos > $1.puntos} } else { PartidasTexto = PartidasTexto.sorted{$0.puntos > $1.puntos} } miTabla.reloadData() } private func ponerPopUp(){ let popOverVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "sbPopUpID") as! PopUpViewController self.addChildViewController(popOverVC) popOverVC.view.frame = self.view.frame self.view.addSubview(popOverVC.view) popOverVC.didMove(toParentViewController: self) popOverVC.aciertos = aciertos popOverVC.tiempoEmpleado = tiempoEmpleado popOverVC.formaHecha = formaHecha popOverVC.modoDeJuego = modoDeJuego } private func reloadTableView(_ tableView: UITableView) { let contentOffset = tableView.contentOffset tableView.reloadData() tableView.layoutIfNeeded() tableView.setContentOffset(contentOffset, animated: false) } private func comprobarNuevoJugador(puntos: Double, nombreJugador: String, nuevo: Bool) -> Bool { if(nombreJugador == nombreIntroducidoCambiarColor && puntos == puntosIntroducidosCambiarColor ){ return true } else { return false } } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewCell //Los fondos se eliminan cell.backgroundColor = .clear miTabla.separatorStyle = .none cell.selectionStyle = .none cell.lb_posicion.font = UIFont(descriptor: lb_tiempo.font.fontDescriptor, size: fontSize) cell.lb_tiempo.font = UIFont(descriptor: lb_tiempo.font.fontDescriptor, size: fontSize) cell.lb_nombre.font = UIFont(descriptor: lb_tiempo.font.fontDescriptor, size: fontSize) cell.lb_aciertos.font = UIFont(descriptor: lb_tiempo.font.fontDescriptor, size: fontSize) cell.lb_posicion.text = String(indexPath.row + 1) if(modoDeJuego){ //SI EL JUGADOR JUEGA EN MODO VOZ.... var arrayClasePartida = [ClasePartida]() for index in 0...PartidasVoz.count - 1 { let nombre = PartidasVoz[index].nombre let aciertos = Int(PartidasVoz[index].aciertos!) let tiempo = Int(PartidasVoz[index].tiempo!) let puntos = PartidasVoz[index].puntos let clasePartida = ClasePartida(_nombre: nombre!, _aciertos: aciertos!, _tiempo: tiempo!, _puntos: puntos, _id: index) arrayClasePartida.append(clasePartida) } idUltimo = (arrayClasePartida.last?.id)! arrayClasePartida = arrayClasePartida.sorted{$0.puntos > $1.puntos} if(arrayClasePartida[indexPath.row].id == idUltimo ){ changeColorGreen(cell: cell) } else { changeColorBlack(cell: cell) } cell.lb_nombre.text = PartidasVoz[indexPath.row].nombre cell.lb_tiempo.text = PartidasVoz[indexPath.row].tiempo cell.lb_aciertos.text = PartidasVoz[indexPath.row].aciertos } else{ var arrayClasePartida = [ClasePartida]() for index in 0...PartidasTexto.count - 1 { let nombre = PartidasTexto[index].nombre let aciertos = Int(PartidasTexto[index].aciertos!) let tiempo = Int(PartidasTexto[index].tiempo!) let puntos = PartidasTexto[index].puntos let clasePartida = ClasePartida(_nombre: nombre!, _aciertos: aciertos!, _tiempo: tiempo!, _puntos: puntos, _id: index) arrayClasePartida.append(clasePartida) } idUltimo = (arrayClasePartida.last?.id)! arrayClasePartida = arrayClasePartida.sorted{$0.puntos > $1.puntos} if(arrayClasePartida[indexPath.row].id == idUltimo ){ changeColorGreen(cell: cell) } else { changeColorBlack(cell: cell) } cell.lb_nombre.text = arrayClasePartida[indexPath.row].nombre cell.lb_tiempo.text = String(arrayClasePartida[indexPath.row].tiempo) cell.lb_aciertos.text = String(arrayClasePartida[indexPath.row].aciertos) } cell.lb_nombre.sizeToFit() return cell } func changeColorBlack(cell: TableViewCell){ cell.lb_nombre.textColor = UIColor.black cell.lb_tiempo.textColor = UIColor.black cell.lb_aciertos.textColor = UIColor.black cell.lb_posicion.textColor = UIColor.black } func changeColorGreen(cell: TableViewCell){ cell.lb_nombre.textColor = colorVerde cell.lb_tiempo.textColor = colorVerde cell.lb_aciertos.textColor = colorVerde cell.lb_posicion.textColor = colorVerde } //Esta funcion se llama para ver cuantas rows va a haber en nuestra tabla. public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if(modoDeJuego){ if(PartidasVoz.count > 0 && PartidasVoz.count <= 10) { return PartidasVoz.count } else if(PartidasTexto.count <= 0) { return 0 } else { return 10 } } else { if(PartidasTexto.count > 0 && PartidasTexto.count <= 10) { return PartidasTexto.count } else if(PartidasTexto.count <= 0) { return 0 } else { return 10 } } } func interstitialDidDismissScreen(_ ad: GADInterstitial) { if(btn_pressed){ self.performSegue(withIdentifier: "unwindNiveles", sender: self) } else { self.performSegue(withIdentifier: "unwindMenu", sender: self) } } private func reproducirAnuncio(){ if(interstitial.isReady){ interstitial.present(fromRootViewController: self) } else { if(btn_pressed){ self.performSegue(withIdentifier: "unwindNiveles", sender: self) } else { self.performSegue(withIdentifier: "unwindMenu", sender: self) } } } @IBAction func btn_menuPrincipal(_ sender: Any) { btn_pressed = false reproducirAnuncio() } @IBAction func btn_menuNiveles(_ sender: Any) { btn_pressed = true reproducirAnuncio() } }
42.075
193
0.63212
18cdd3d5cc7e4ffff8e95aaa4d3ea4554dcf8542
3,156
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation extension TBX.DeviceService { public enum DeviceServiceValidateCode { public static let service = APIService<Response>(id: "DeviceService.validateCode", tag: "DeviceService", method: "POST", path: "/DeviceServices/validateCode", hasBody: false) public final class Request: APIRequest<Response> { public struct Options { public var apiKey: String public var code: String public init(apiKey: String, code: String) { self.apiKey = apiKey self.code = code } } public var options: Options public init(options: Options) { self.options = options super.init(service: DeviceServiceValidateCode.service) } /// convenience initialiser so an Option doesn't have to be created public convenience init(apiKey: String, code: String) { let options = Options(apiKey: apiKey, code: code) self.init(options: options) } public override var parameters: [String: Any] { var params: [String: Any] = [:] params["api_key"] = options.apiKey params["code"] = options.code return params } } public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible { public typealias SuccessType = [String: Any] /** Request was successful */ case status200([String: Any]) public var success: [String: Any]? { switch self { case .status200(let response): return response } } public var response: Any { switch self { case .status200(let response): return response } } public var statusCode: Int { switch self { case .status200: return 200 } } public var successful: Bool { switch self { case .status200: return true } } public init(statusCode: Int, data: Data) throws { let decoder = JSONDecoder() switch statusCode { case 200: self = try .status200(decoder.decodeAny([String: Any].self, from: data)) default: throw APIError.unexpectedStatusCode(statusCode: statusCode, data: data) } } public var description: String { return "\(statusCode) \(successful ? "success" : "failure")" } public var debugDescription: String { var string = description let responseString = "\(response)" if responseString != "()" { string += "\n\(responseString)" } return string } } } }
30.941176
182
0.508872
26c8bf8fca3ae27fa6ff85be2adc9802e0a15dde
1,787
// Copyright 2018-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest import MaterialComponents.MaterialAppBar import MaterialComponents.MaterialAppBar_TypographyThemer import MaterialComponents.MaterialTypography import MaterialComponentsTestingSupport.MaterialTypographyScheme_TestingSupport class AppBarTypographyThemerTests: XCTestCase { func traitsForFont(_ font: UIFont) -> [String: NSNumber] { guard let fontTraits = font.fontDescriptor.object(forKey: UIFontDescriptorTraitsAttribute) as? [String: NSNumber] else { return [:] } return fontTraits } func testTypographyThemerAffectsSubComponents() { // Given let appBar = MDCAppBar() let typographyScheme = MDCTypographyScheme.withVaryingFontSize() // When MDCAppBarTypographyThemer.applyTypographyScheme(typographyScheme, to: appBar) // Then XCTAssertEqual(appBar.navigationBar.titleFont.fontName, typographyScheme.headline6.fontName) XCTAssertEqual(appBar.navigationBar.titleFont.pointSize, typographyScheme.headline6.pointSize) XCTAssertEqual(traitsForFont(appBar.navigationBar.titleFont), traitsForFont(typographyScheme.headline6)) } }
37.229167
100
0.771684
e265fca795ea578048963f6bde7bbd6aa1271628
604
import XCTest import SwiftUI import SwiftUILib_AnyViewArrayBuilder final class AnyViewArrayBuilderTests: XCTestCase { func testCounts() throws { func count(@AnyViewArrayBuilder _ content: () -> [AnyView]) -> Int { content().count } XCTAssertEqual(count { }, 0) XCTAssertEqual(count { Text("") }, 1) XCTAssertEqual(count { Text("") Color.clear }, 2) // The contents of the ForEach must be counted individually XCTAssertEqual(count { Text("") Color.clear ForEach(1..<4) { Text("\($0)") } }, 5) } }
17.257143
72
0.59106
6a1c5a64747414d6bd431b91f492a62733f4ea03
3,067
// // FindNum1.swift // leetcode // // Created by youzhuo wang on 2020/4/2. // Copyright © 2020 youzhuo wang. All rights reserved. // import Foundation // 给一个数组,这个数左边的都比它小,右边的都比它大,如[7,4,2,8,9,12]结果是8,9 // 思路:借助两个辅助数组来标记 class FindNum1 { func findNum(_ nums:[Int]) -> [Int] { if nums.count < 3 { return [] } var list:[Int] = Array() var maxNumList: [Int] = [Int](repeating: 0, count: nums.count) var minNumList: [Int] = [Int](repeating: 0, count: nums.count) var maxNum = nums[0] for (index,item) in nums.enumerated() { if item > maxNum { maxNum = item } maxNumList[index] = maxNum } var minValue = nums[nums.count-1] for (index,item) in nums.enumerated().reversed() { if item < minValue { minValue = item } minNumList[index] = minValue } for i in (1..<nums.count-1) { if maxNumList[i] == minNumList[i] && maxNumList[i] > maxNumList[i-1] { list.append(nums[i]) } } return list } // func findOneNum(_ n: Int) -> Int { // var nTemp = n // var count = 0 // let nB = String(nTemp, radix: 2) // while(nTemp != 0) { // if nTemp & 1 == abs(1) { // count = count + 1 // } // nTemp = nTemp >> 1 // } // return count // } func countPositionNumber3(_ number:Int) -> Int { var num:Int = number var count:Int = 0 while num != 0 { count += 1 num = num & (num-1) } return count } // 递归实现1加到100 func addToNum(_ n: Int) -> Int{ if n == 1 { return 1 } return n + addToNum(n-1) //return addNum(0, n) } // 尾递归 private func addNum(_ result: Int, _ n: Int) -> Int { if n == 1 { return result + n } return addNum(result + n, n-1) } func test() { // print(findNum([7,4,2,8,9,12])) // print(findNum([7,4,2,8,9,3])) // print(findOneNum(0)) // print(findOneNum(8)) // print(findOneNum(9)) // print(countPositionNumber3(-8)) // print(9%4) // print(9%(-4)) // print((-9)%4) // print((-9)%(-4)) //print(addToNum(100)) // 0 ^ 0 = 0 // 1 ^ 0 = 1 // 0 ^ 1 = 1 // 1 ^ 1 = 0 let arr = [0, 3, 8, 3, 5] // let a = 0 var result = 0 var zeroCount:Int = 0 for item in arr { if item == 0 { zeroCount += 1 if zeroCount > 1 { print("zeroCount:", zeroCount) break } continue } result = item ^ result print("result:", result) } } }
24.34127
82
0.418976
8915b77e3f889b7d3c026ee444484658f8ba820e
774
import UIKit import XCTest import PKTutorialViewController class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
25.8
111
0.612403
6ad976b7e153487f8ec4175fd9df47984d71e45c
19,490
import XCTest @testable import PerfectNet import PerfectThread @testable import PerfectRedis class HashTests: XCTestCase { override func setUp() { NetEvent.initialize() } override func tearDown() { super.tearDown() RedisClient.getClient(withIdentifier: clientIdentifier()) { c in do { let client = try c() client.flushAll() { _ in } } catch { print("Failed to clean up after test \(error)") } } } func clientIdentifier() -> RedisClientIdentifier { return RedisClientIdentifier() } func testHashSetHashGet() { let (key, field, value) = ("mykey", "myfield", "myvalue") let expectation = self.expectation(description: "RedisClient") RedisClient.getClient(withIdentifier: clientIdentifier()) { c in do { let client = try c() client.hashSet(key: key, field: field, value: .string(value)) { response in guard case .integer(let result) = response else { XCTFail("Unexpected response \(response)") expectation.fulfill() return } client.hashGet(key: key, field: field) { response in defer { RedisClient.releaseClient(client) expectation.fulfill() } guard case .bulkString = response else { XCTFail("Unexpected response \(response)") return } let s = response.toString() XCTAssertEqual(s, value, "Unexpected response \(response)") } } } catch { XCTFail("Could not connect to server \(error)") expectation.fulfill() return } } self.waitForExpectations(timeout: 60.0) { _ in } } /** the test sets a field for a hash then: - checks for existance of that field in the hash - checks if the field can be removed from the hash - checks that the field does not exist anymore - checks that the field cannot be removed once it does not exist */ func testHashDelAndHashExist() { let (key, field, value) = ("mykey", "myfield", "myvalue") let expectation = self.expectation(description: "RedisClient") RedisClient.getClient(withIdentifier: clientIdentifier()) { c in do { let client = try c() client.hashSet(key: key, field: field, value: .string(value)) { _ in client.hashExists(key: key, field: field) { response in let s = response.toString() XCTAssertEqual(s, "1", "Unexpected response \(response)") client.hashDel(key: key, fields: field) { response in let s = response.toString() XCTAssertEqual(s, "1", "Unexpected response \(response)") client.hashExists(key: key, field: field) { response in let s = response.toString() XCTAssertEqual(s, "0", "Unexpected response \(response)") client.hashDel(key: key, fields: field) { response in defer { RedisClient.releaseClient(client) expectation.fulfill() } let s = response.toString() XCTAssertEqual(s, "0", "Unexpected response \(response)") } } } } } } catch { XCTFail("Could not connect to server \(error)") expectation.fulfill() return } } self.waitForExpectations(timeout: 60.0) { _ in } } func testHashMultiSetAndHashGetAll() { let key = "mykey" let hashFieldsValues: [(String, RedisClient.RedisValue)] = [ ("myfield", .string("myvalue")), ("myfield2", .string("myvalue2")) ] let expectedDict = ["myfield": "myvalue", "myfield2": "myvalue2"] let expectation = self.expectation(description: "RedisClient") RedisClient.getClient(withIdentifier: clientIdentifier()) { c in do { let client = try c() client.hashSet(key: key, fieldsValues: hashFieldsValues) { response in client.hashGetAll(key: key) { response in defer { RedisClient.releaseClient(client) expectation.fulfill() } switch response { case .array(let a): XCTAssertEqual(4, a.count) var resultDict: [String: String] = [:] var ar = a while ar.count > 0 { let value: String = ar.popLast()!.toString()! let key: String = ar.popLast()!.toString()! resultDict[key] = value } XCTAssertEqual(expectedDict, resultDict, "Unexpected dictionary returned \(resultDict)") default: XCTFail("Unexpected response \(response)") } } } } catch { XCTFail("Could not connect to server \(error)") expectation.fulfill() return } } self.waitForExpectations(timeout: 60.0) { _ in } } func testHashMultiGet() { let key = "mykey" let hashFieldsValues: [(String, RedisClient.RedisValue)] = [ ("myfield", .string("myvalue")), ("myfield2", .string("myvalue2")), ("myfield3", .string("myvalue3")) ] let expectedValues = ["myvalue3", "myvalue2"] let expectation = self.expectation(description: "RedisClient") RedisClient.getClient(withIdentifier: clientIdentifier()) { c in do { let client = try c() client.hashSet(key: key, fieldsValues: hashFieldsValues) { response in client.hashGet(key: key, fields: ["myfield3", "myfield2"]) { response in defer { RedisClient.releaseClient(client) expectation.fulfill() } switch response { case .array(let a): let resultArray: [String] = a.map { return $0.toString()! } XCTAssertEqual(expectedValues, resultArray, "Unexpected array returned \(a)") default: XCTFail("Unexpected response \(response)") } } } } catch { XCTFail("Could not connect to server \(error)") expectation.fulfill() return } } self.waitForExpectations(timeout: 60.0) { _ in } } func testHashKeysValuesLen() { let key = "mykey" let hashFieldsValues: [(String, RedisClient.RedisValue)] = [ ("myfield", .string("myvalue")), ("myfield2", .string("myvalue2")), ("myfield3", .string("myvalue3")) ] let expectedKeys = hashFieldsValues.map { $0.0 } let expectedValues = ["myvalue", "myvalue2", "myvalue3"] let expectedLength = hashFieldsValues.count let expectation = self.expectation(description: "RedisClient") RedisClient.getClient(withIdentifier: clientIdentifier()) { c in do { let client = try c() client.hashSet(key: key, fieldsValues: hashFieldsValues) { response in client.hashKeys(key: key) { response in switch response { case .array(let a): let resultArray: [String] = a.map { return $0.toString()! } XCTAssertEqual(expectedKeys, resultArray, "Unexpected array returned \(a)") default: XCTFail("Unexpected response \(response)") } client.hashValues(key: key) { response in switch response { case .array(let a): let resultArray: [String] = a.map { return $0.toString()! } XCTAssertEqual(expectedValues, resultArray, "Unexpected array returned \(a)") default: XCTFail("Unexpected response \(response)") } client.hashLength(key: key) { response in switch response { case .integer(let len): XCTAssertEqual(expectedLength, len, "Unexpected integer returned \(len)") default: XCTFail("Unexpected response \(response)") } RedisClient.releaseClient(client) expectation.fulfill() } } } } } catch { XCTFail("Could not connect to server \(error)") expectation.fulfill() return } } self.waitForExpectations(timeout: 60.0) { _ in } } func testHashSetNX() { let (key, field, value) = ("mykey", "myfield", "myvalue") let expectation = self.expectation(description: "RedisClient") RedisClient.getClient(withIdentifier: clientIdentifier()) { c in do { let client = try c() client.hashSetIfNonExists(key: key, field: field, value: .string(value)) { response in guard case .integer(let result) = response , result == 1 else { XCTFail("Unexpected response \(response)") expectation.fulfill() return } client.hashSetIfNonExists(key: key, field: field, value: .string(value)) { response in defer { RedisClient.releaseClient(client) expectation.fulfill() } guard case .integer(let result) = response , result == 0 else { XCTFail("Unexpected response \(response)") expectation.fulfill() return } } } } catch { XCTFail("Could not connect to server \(error)") expectation.fulfill() return } } self.waitForExpectations(timeout: 60.0) { _ in } } func testHashStrlen() { let (key, field, value) = ("mykey", "myfield", "myvalue") let expectation = self.expectation(description: "RedisClient") RedisClient.getClient(withIdentifier: clientIdentifier()) { c in do { let client = try c() client.hashSet(key: key, field: field, value: .string(value)) { response in guard case .integer(let result) = response else { XCTFail("Unexpected response \(response)") expectation.fulfill() return } client.hashStringLength(key: key, field: field) { response in guard case .integer(let result) = response , result == 7 else { XCTFail("Unexpected response \(response)") expectation.fulfill() return } client.hashStringLength(key: key, field: "nonexisting") { response in guard case .integer(let result) = response , result == 0 else { XCTFail("Unexpected response \(response)") expectation.fulfill() return } client.hashStringLength(key: "nonexisting", field: "nonexisting") { response in defer { RedisClient.releaseClient(client) expectation.fulfill() } guard case .integer(let result) = response , result == 0 else { XCTFail("Unexpected response \(response)") expectation.fulfill() return } } } } } } catch { XCTFail("Could not connect to server \(error)") expectation.fulfill() return } } self.waitForExpectations(timeout: 60.0) { _ in } } func testHashIncrementBy() { let (key, field) = ("mykey", "myfield") let expectation = self.expectation(description: "RedisClient") RedisClient.getClient(withIdentifier: clientIdentifier()) { c in do { let client = try c() client.hashIncrementBy(key: key, field: field, by: 1) { response in guard case .integer(let result) = response , result == 1 else { XCTFail("Unexpected response \(response)") expectation.fulfill() return } client.hashIncrementBy(key: key, field: field, by: -1) { response in guard case .integer(let result) = response , result == 0 else { XCTFail("Unexpected response \(response)") expectation.fulfill() return } client.hashIncrementBy(key: key, field: field, by: 1.5) { response in defer { RedisClient.releaseClient(client) expectation.fulfill() } guard case .bulkString = response else { XCTFail("Unexpected response \(response)") expectation.fulfill() return } let result = Double(response.toString()!)! XCTAssertEqual(1.5, result, accuracy: 0.1, "Unexpected response \(response)") } } } } catch { XCTFail("Could not connect to server \(error)") expectation.fulfill() return } } self.waitForExpectations(timeout: 60.0) { _ in } } func testHashScan() { let key = "mykey" let hashFieldsValues: [(String, RedisClient.RedisValue)] = [ ("myfield", .string("myvalue")), ("myfield2", .string("myvalue2")) ] let expectation = self.expectation(description: "RedisClient") let expectedDict = ["myfield": "myvalue", "myfield2": "myvalue2"] RedisClient.getClient(withIdentifier: clientIdentifier()) { c in do { let client = try c() client.hashSet(key: key, fieldsValues: hashFieldsValues) { response in client.hashScan(key: key, cursor: 0) { response in defer { RedisClient.releaseClient(client) expectation.fulfill() } switch response { case .array(let a): XCTAssertEqual("0", a[0].toString()) var resultDict: [String: String] = [:] switch a[1] { case .array(var ar): while ar.count > 0 { let value: String = ar.popLast()!.toString()! let key: String = ar.popLast()!.toString()! resultDict[key] = value } XCTAssertEqual(expectedDict, resultDict, "Unexpected dictionary returned \(resultDict)") default: XCTFail("Was expecting an array of strings as the second element of the response") } default: XCTFail("Unexpected response \(response)") } } } } catch { XCTFail("Could not connect to server \(error)") expectation.fulfill() return } } self.waitForExpectations(timeout: 60.0) { _ in } } static var allTests : [(String, (HashTests) -> () throws -> Void)] { return [ ("testHashSetHashGet", testHashSetHashGet), ("testHashDelAndHashExist", testHashDelAndHashExist), ("testHashMultiSetAndHashGetAll", testHashMultiSetAndHashGetAll), ("testHashMultiGet", testHashMultiGet), ("testHashKeysValuesLen", testHashKeysValuesLen), ("testHashSetNX", testHashSetNX), ("testHashStrlen", testHashStrlen), ("testHashIncrementBy", testHashIncrementBy), ("testHashScan", testHashScan) ] } }
40.604167
128
0.43217
d765522dd8da23e2bab7c87a8759644ba02096be
15,361
// DO NOT EDIT. // swift-format-ignore-file // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: cosmos/feegrant/v1beta1/feegrant.proto // // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file // was generated by a version of the `protoc` Swift plug-in that is // incompatible with the version of SwiftProtobuf to which you are linking. // Please ensure that you are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} typealias Version = _2 } /// BasicAllowance implements Allowance with a one-time grant of tokens /// that optionally expires. The grantee can use up to SpendLimit to cover fees. public struct Cosmos_Feegrant_V1beta1_BasicAllowance { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// spend_limit specifies the maximum amount of tokens that can be spent /// by this allowance and will be updated as tokens are spent. If it is /// empty, there is no spend limit and any amount of coins can be spent. public var spendLimit: [Cosmos_Base_V1beta1_Coin] = [] /// expiration specifies an optional time when this allowance expires public var expiration: SwiftProtobuf.Google_Protobuf_Timestamp { get {return _expiration ?? SwiftProtobuf.Google_Protobuf_Timestamp()} set {_expiration = newValue} } /// Returns true if `expiration` has been explicitly set. public var hasExpiration: Bool {return self._expiration != nil} /// Clears the value of `expiration`. Subsequent reads from it will return its default value. public mutating func clearExpiration() {self._expiration = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _expiration: SwiftProtobuf.Google_Protobuf_Timestamp? = nil } /// PeriodicAllowance extends Allowance to allow for both a maximum cap, /// as well as a limit per time period. public struct Cosmos_Feegrant_V1beta1_PeriodicAllowance { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// basic specifies a struct of `BasicAllowance` public var basic: Cosmos_Feegrant_V1beta1_BasicAllowance { get {return _basic ?? Cosmos_Feegrant_V1beta1_BasicAllowance()} set {_basic = newValue} } /// Returns true if `basic` has been explicitly set. public var hasBasic: Bool {return self._basic != nil} /// Clears the value of `basic`. Subsequent reads from it will return its default value. public mutating func clearBasic() {self._basic = nil} /// period specifies the time duration in which period_spend_limit coins can /// be spent before that allowance is reset public var period: SwiftProtobuf.Google_Protobuf_Duration { get {return _period ?? SwiftProtobuf.Google_Protobuf_Duration()} set {_period = newValue} } /// Returns true if `period` has been explicitly set. public var hasPeriod: Bool {return self._period != nil} /// Clears the value of `period`. Subsequent reads from it will return its default value. public mutating func clearPeriod() {self._period = nil} /// period_spend_limit specifies the maximum number of coins that can be spent /// in the period public var periodSpendLimit: [Cosmos_Base_V1beta1_Coin] = [] /// period_can_spend is the number of coins left to be spent before the period_reset time public var periodCanSpend: [Cosmos_Base_V1beta1_Coin] = [] /// period_reset is the time at which this period resets and a new one begins, /// it is calculated from the start time of the first transaction after the /// last period ended public var periodReset: SwiftProtobuf.Google_Protobuf_Timestamp { get {return _periodReset ?? SwiftProtobuf.Google_Protobuf_Timestamp()} set {_periodReset = newValue} } /// Returns true if `periodReset` has been explicitly set. public var hasPeriodReset: Bool {return self._periodReset != nil} /// Clears the value of `periodReset`. Subsequent reads from it will return its default value. public mutating func clearPeriodReset() {self._periodReset = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _basic: Cosmos_Feegrant_V1beta1_BasicAllowance? = nil fileprivate var _period: SwiftProtobuf.Google_Protobuf_Duration? = nil fileprivate var _periodReset: SwiftProtobuf.Google_Protobuf_Timestamp? = nil } /// AllowedMsgAllowance creates allowance only for specified message types. public struct Cosmos_Feegrant_V1beta1_AllowedMsgAllowance { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// allowance can be any of basic and filtered fee allowance. public var allowance: SwiftProtobuf.Google_Protobuf_Any { get {return _allowance ?? SwiftProtobuf.Google_Protobuf_Any()} set {_allowance = newValue} } /// Returns true if `allowance` has been explicitly set. public var hasAllowance: Bool {return self._allowance != nil} /// Clears the value of `allowance`. Subsequent reads from it will return its default value. public mutating func clearAllowance() {self._allowance = nil} /// allowed_messages are the messages for which the grantee has the access. public var allowedMessages: [String] = [] public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _allowance: SwiftProtobuf.Google_Protobuf_Any? = nil } /// Grant is stored in the KVStore to record a grant with full context public struct Cosmos_Feegrant_V1beta1_Grant { // SwiftProtobuf.Message conformance is added in an extension below. See the // `Message` and `Message+*Additions` files in the SwiftProtobuf library for // methods supported on all messages. /// granter is the address of the user granting an allowance of their funds. public var granter: String = String() /// grantee is the address of the user being granted an allowance of another user's funds. public var grantee: String = String() /// allowance can be any of basic and filtered fee allowance. public var allowance: SwiftProtobuf.Google_Protobuf_Any { get {return _allowance ?? SwiftProtobuf.Google_Protobuf_Any()} set {_allowance = newValue} } /// Returns true if `allowance` has been explicitly set. public var hasAllowance: Bool {return self._allowance != nil} /// Clears the value of `allowance`. Subsequent reads from it will return its default value. public mutating func clearAllowance() {self._allowance = nil} public var unknownFields = SwiftProtobuf.UnknownStorage() public init() {} fileprivate var _allowance: SwiftProtobuf.Google_Protobuf_Any? = nil } // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "cosmos.feegrant.v1beta1" extension Cosmos_Feegrant_V1beta1_BasicAllowance: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".BasicAllowance" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .standard(proto: "spend_limit"), 2: .same(proto: "expiration"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeRepeatedMessageField(value: &self.spendLimit) }() case 2: try { try decoder.decodeSingularMessageField(value: &self._expiration) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.spendLimit.isEmpty { try visitor.visitRepeatedMessageField(value: self.spendLimit, fieldNumber: 1) } if let v = self._expiration { try visitor.visitSingularMessageField(value: v, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Cosmos_Feegrant_V1beta1_BasicAllowance, rhs: Cosmos_Feegrant_V1beta1_BasicAllowance) -> Bool { if lhs.spendLimit != rhs.spendLimit {return false} if lhs._expiration != rhs._expiration {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Cosmos_Feegrant_V1beta1_PeriodicAllowance: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".PeriodicAllowance" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "basic"), 2: .same(proto: "period"), 3: .standard(proto: "period_spend_limit"), 4: .standard(proto: "period_can_spend"), 5: .standard(proto: "period_reset"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._basic) }() case 2: try { try decoder.decodeSingularMessageField(value: &self._period) }() case 3: try { try decoder.decodeRepeatedMessageField(value: &self.periodSpendLimit) }() case 4: try { try decoder.decodeRepeatedMessageField(value: &self.periodCanSpend) }() case 5: try { try decoder.decodeSingularMessageField(value: &self._periodReset) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._basic { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } if let v = self._period { try visitor.visitSingularMessageField(value: v, fieldNumber: 2) } if !self.periodSpendLimit.isEmpty { try visitor.visitRepeatedMessageField(value: self.periodSpendLimit, fieldNumber: 3) } if !self.periodCanSpend.isEmpty { try visitor.visitRepeatedMessageField(value: self.periodCanSpend, fieldNumber: 4) } if let v = self._periodReset { try visitor.visitSingularMessageField(value: v, fieldNumber: 5) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Cosmos_Feegrant_V1beta1_PeriodicAllowance, rhs: Cosmos_Feegrant_V1beta1_PeriodicAllowance) -> Bool { if lhs._basic != rhs._basic {return false} if lhs._period != rhs._period {return false} if lhs.periodSpendLimit != rhs.periodSpendLimit {return false} if lhs.periodCanSpend != rhs.periodCanSpend {return false} if lhs._periodReset != rhs._periodReset {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Cosmos_Feegrant_V1beta1_AllowedMsgAllowance: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".AllowedMsgAllowance" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "allowance"), 2: .standard(proto: "allowed_messages"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularMessageField(value: &self._allowance) }() case 2: try { try decoder.decodeRepeatedStringField(value: &self.allowedMessages) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if let v = self._allowance { try visitor.visitSingularMessageField(value: v, fieldNumber: 1) } if !self.allowedMessages.isEmpty { try visitor.visitRepeatedStringField(value: self.allowedMessages, fieldNumber: 2) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Cosmos_Feegrant_V1beta1_AllowedMsgAllowance, rhs: Cosmos_Feegrant_V1beta1_AllowedMsgAllowance) -> Bool { if lhs._allowance != rhs._allowance {return false} if lhs.allowedMessages != rhs.allowedMessages {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } } extension Cosmos_Feegrant_V1beta1_Grant: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { public static let protoMessageName: String = _protobuf_package + ".Grant" public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ 1: .same(proto: "granter"), 2: .same(proto: "grantee"), 3: .same(proto: "allowance"), ] public mutating func decodeMessage<D: SwiftProtobuf.Decoder>(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { // The use of inline closures is to circumvent an issue where the compiler // allocates stack space for every case branch when no optimizations are // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularStringField(value: &self.granter) }() case 2: try { try decoder.decodeSingularStringField(value: &self.grantee) }() case 3: try { try decoder.decodeSingularMessageField(value: &self._allowance) }() default: break } } } public func traverse<V: SwiftProtobuf.Visitor>(visitor: inout V) throws { if !self.granter.isEmpty { try visitor.visitSingularStringField(value: self.granter, fieldNumber: 1) } if !self.grantee.isEmpty { try visitor.visitSingularStringField(value: self.grantee, fieldNumber: 2) } if let v = self._allowance { try visitor.visitSingularMessageField(value: v, fieldNumber: 3) } try unknownFields.traverse(visitor: &visitor) } public static func ==(lhs: Cosmos_Feegrant_V1beta1_Grant, rhs: Cosmos_Feegrant_V1beta1_Grant) -> Bool { if lhs.granter != rhs.granter {return false} if lhs.grantee != rhs.grantee {return false} if lhs._allowance != rhs._allowance {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } }
44.915205
155
0.743051
87462635162331936a6c10b5bcff262f7a1d01f1
518
// // ViewController.swift // iOS Example // // Created by Nathan Lanza on January 18, 2017. // Copyright © 2017 Nathan Lanza. All rights reserved. // import UIKit class ViewController: UIViewController { 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. } }
19.923077
80
0.671815
265d4f5b694d97d3b6a25287235ce4700a251c4d
10,292
// // ListObserverDemoViewController.swift // CoreStoreDemo // // Created by John Rommel Estropia on 2015/05/02. // Copyright © 2018 John Rommel Estropia. All rights reserved. // import UIKit import CoreStore struct ColorsDemo { enum Filter: String { case all = "All Colors" case light = "Light Colors" case dark = "Dark Colors" func next() -> Filter { switch self { case .all: return .light case .light: return .dark case .dark: return .all } } func whereClause() -> Where<Palette> { switch self { case .all: return .init() case .light: return (\Palette.brightness >= 0.9) case .dark: return (\Palette.brightness <= 0.4) } } } static var filter = Filter.all { didSet { self.palettes.refetch( self.filter.whereClause(), OrderBy<Palette>(.ascending(\.hue)) ) } } static let stack: DataStack = { return DataStack( CoreStoreSchema( modelVersion: "ColorsDemo", entities: [ Entity<Palette>("Palette"), ], versionLock: [ "Palette": [0x8c25aa53c7c90a28, 0xa243a34d25f1a3a7, 0x56565b6935b6055a, 0x4f988bb257bf274f] ] ) ) }() static let palettes: ListMonitor<Palette> = { try! ColorsDemo.stack.addStorageAndWait( SQLiteStore( fileName: "ColorsDemo.sqlite", localStorageOptions: .recreateStoreOnModelMismatch ) ) return ColorsDemo.stack.monitorSectionedList( From<Palette>() .sectionBy(\.colorName) .orderBy(.ascending(\.hue)) ) }() } // MARK: - ListObserverDemoViewController class ListObserverDemoViewController: UITableViewController, ListSectionObserver { // MARK: NSObject deinit { ColorsDemo.palettes.removeObserver(self) } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() let navigationItem = self.navigationItem navigationItem.leftBarButtonItems = [ self.editButtonItem, UIBarButtonItem( barButtonSystemItem: .trash, target: self, action: #selector(self.resetBarButtonItemTouched(_:)) ) ] let filterBarButton = UIBarButtonItem( title: ColorsDemo.filter.rawValue, style: .plain, target: self, action: #selector(self.filterBarButtonItemTouched(_:)) ) navigationItem.rightBarButtonItems = [ UIBarButtonItem( barButtonSystemItem: .add, target: self, action: #selector(self.addBarButtonItemTouched(_:)) ), UIBarButtonItem( barButtonSystemItem: .refresh, target: self, action: #selector(self.shuffleBarButtonItemTouched(_:)) ), filterBarButton ] self.filterBarButton = filterBarButton ColorsDemo.palettes.addObserver(self) self.setTable(enabled: !ColorsDemo.palettes.isPendingRefetch) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) switch (segue.identifier, segue.destination, sender) { case ("ObjectObserverDemoViewController"?, let destinationViewController as ObjectObserverDemoViewController, let palette as Palette): destinationViewController.palette = palette default: break } } // MARK: UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return ColorsDemo.palettes.numberOfSections() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return ColorsDemo.palettes.numberOfObjects(in: section) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PaletteTableViewCell") as! PaletteTableViewCell let palette = ColorsDemo.palettes[indexPath] cell.colorView?.backgroundColor = palette.color cell.label?.text = palette.colorText return cell } // MARK: UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) self.performSegue( withIdentifier: "ObjectObserverDemoViewController", sender: ColorsDemo.palettes[indexPath] ) } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { switch editingStyle { case .delete: let palette = ColorsDemo.palettes[indexPath] ColorsDemo.stack.perform( asynchronous: { (transaction) in transaction.delete(palette) }, completion: { _ in } ) default: break } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return ColorsDemo.palettes.sectionInfo(at: section).name } // MARK: ListObserver func listMonitorWillChange(_ monitor: ListMonitor<Palette>) { self.tableView.beginUpdates() } func listMonitorDidChange(_ monitor: ListMonitor<Palette>) { self.tableView.endUpdates() } func listMonitorWillRefetch(_ monitor: ListMonitor<Palette>) { self.setTable(enabled: false) } func listMonitorDidRefetch(_ monitor: ListMonitor<Palette>) { self.filterBarButton?.title = ColorsDemo.filter.rawValue self.tableView.reloadData() self.setTable(enabled: true) } // MARK: ListObjectObserver func listMonitor(_ monitor: ListMonitor<Palette>, didInsertObject object: Palette, toIndexPath indexPath: IndexPath) { self.tableView.insertRows(at: [indexPath], with: .automatic) } func listMonitor(_ monitor: ListMonitor<Palette>, didDeleteObject object: Palette, fromIndexPath indexPath: IndexPath) { self.tableView.deleteRows(at: [indexPath], with: .automatic) } func listMonitor(_ monitor: ListMonitor<Palette>, didUpdateObject object: Palette, atIndexPath indexPath: IndexPath) { if let cell = self.tableView.cellForRow(at: indexPath) as? PaletteTableViewCell { let palette = ColorsDemo.palettes[indexPath] cell.colorView?.backgroundColor = palette.color cell.label?.text = palette.colorText } } func listMonitor(_ monitor: ListMonitor<Palette>, didMoveObject object: Palette, fromIndexPath: IndexPath, toIndexPath: IndexPath) { self.tableView.moveRow(at: fromIndexPath, to: toIndexPath) } // MARK: ListSectionObserver func listMonitor(_ monitor: ListMonitor<Palette>, didInsertSection sectionInfo: NSFetchedResultsSectionInfo, toSectionIndex sectionIndex: Int) { self.tableView.insertSections(IndexSet(integer: sectionIndex), with: .automatic) } func listMonitor(_ monitor: ListMonitor<Palette>, didDeleteSection sectionInfo: NSFetchedResultsSectionInfo, fromSectionIndex sectionIndex: Int) { self.tableView.deleteSections(IndexSet(integer: sectionIndex), with: .automatic) } // MARK: Private private var filterBarButton: UIBarButtonItem? @IBAction private dynamic func resetBarButtonItemTouched(_ sender: AnyObject?) { ColorsDemo.stack.perform( asynchronous: { (transaction) in try transaction.deleteAll(From<Palette>()) }, completion: { _ in } ) } @IBAction private dynamic func filterBarButtonItemTouched(_ sender: AnyObject?) { ColorsDemo.filter = ColorsDemo.filter.next() } @IBAction private dynamic func addBarButtonItemTouched(_ sender: AnyObject?) { ColorsDemo.stack.perform( asynchronous: { (transaction) in let palette = transaction.create(Into<Palette>()) palette.setInitialValues(in: transaction) }, completion: { _ in } ) } @IBAction private dynamic func shuffleBarButtonItemTouched(_ sender: AnyObject?) { self.setTable(enabled: false) ColorsDemo.stack.perform( asynchronous: { (transaction) in for palette in try transaction.fetchAll(From<Palette>()) { palette.hue .= Palette.randomHue() palette.colorName .= nil } }, completion: { _ in self.setTable(enabled: true) } ) } private func setTable(enabled: Bool) { tableView.isUserInteractionEnabled = enabled UIView.animate( withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: { () -> Void in if let tableView = self.tableView { tableView.alpha = enabled ? 1.0 : 0.5 } }, completion: nil ) } }
29.321937
150
0.5685
d6e0432618b9b57d54bf36be9092c9978812d06a
755
// // GradientCircle.swift // breadwallet // // Created by Adrian Corscadden on 2016-11-22. // Copyright © 2016 breadwallet LLC. All rights reserved. // import UIKit class GradientCircle: UIView, GradientDrawable { static let defaultSize: CGFloat = 48.0 init() { super.init(frame: CGRect()) backgroundColor = .clear } override func draw(_ rect: CGRect) { drawGradient(rect) maskToCircle(rect) } private func maskToCircle(_ rect: CGRect) { let maskLayer = CAShapeLayer() maskLayer.path = UIBezierPath(ovalIn: rect).cgPath layer.mask = maskLayer } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
21.571429
59
0.639735
20c4495bb7bd014ca2f0da5d1e82fb125d4f7aee
1,782
// // DefaultCoordinatorService.swift // CNIntegration // // Created by Pavel Pronin on 27.07.2020. // Copyright © 2020 Pavel Pronin. All rights reserved. // final class DefaultCoordinatorService { private let exchangeType: ExchangeType init(exchangeType: ExchangeType) { self.exchangeType = exchangeType } // MARK: - Navigation func showScannerScreen(delegate: ScannerDelegate?) { let currentViewController = self.currentViewController() let newVC = ScannerViewController() newVC.delegate = delegate currentViewController?.present(newVC, animated: true, completion: nil) } func showChooseCurrencyScreen(fromCurrencyTicker: String, toCurrencyTicker: String, selectedState: ChooseCurrencyState, exchangeType: ExchangeType, delegate: ChooseCurrencyDelegate?) { let currentViewController = self.currentViewController() let newVC = ChooseCurrencyViewController(fromCurrencyTicker: fromCurrencyTicker, toCurrencyTicker: toCurrencyTicker, selectedState: selectedState, exchangeType: exchangeType) newVC.delegate = delegate if #available(iOS 13.0, *) { newVC.modalPresentationStyle = .automatic } else { newVC.modalPresentationStyle = .overCurrentContext } currentViewController?.present(newVC, animated: true, completion: nil) } func currentViewController() -> UIViewController? { return UIApplication.topViewController() } }
36.367347
88
0.603255
76566e12124b30aee847585a9d73ffa92a40151d
9,385
// // Location.swift // Safety // // Created by Yudhvir Raj on 2018-03-03. // Copyright © 2018 D'Arcy Smith. All rights reserved. // import Foundation import UIKit import CoreLocation import UserNotifications class Location { static let LOCATION_CHANGED = "LOCATION_CHANGED" static let LOCATION_AUTHORIZATION_CHANGED = "LOCATION_AUTHORIZATION_CHANGED" static let LOCATION_PERMISSION_FALIED = "LOCAITON_PERMISSION_FAILED" static let REQUESTED_ALWAYS_AUTHORIZATION = "REQUESTED_ALWAYS_AUTHORIZATION" static let REQUESTED_INUSE_AUTHORIZATION = "REQUESTED_INUSE_AUTHORIZATION" static let TRACK_ME_AT_ALL_TIMES = "trackMeAtAllTimes" static var currentLocation = CLLocation() static var requestedAuthorizationStatus: CLAuthorizationStatus = CLAuthorizationStatus.notDetermined static let appDelegate = UIApplication.shared.delegate as! AppDelegate static func startLocationUpdatesAlways(caller: UIViewController?) { print("starting location updates always") requestedAuthorizationStatus = .authorizedAlways // if we don't have always access if CLLocationManager.authorizationStatus() != .authorizedAlways { // if the user has previously denied it. if UserDefaults.standard.bool(forKey: Location.REQUESTED_ALWAYS_AUTHORIZATION) { locationAuthorizationStatus(viewController: caller, status: CLLocationManager.authorizationStatus()) return } else { // we can request it print("don't have always access, requesting now") appDelegate.locationManager.requestAlwaysAuthorization() UserDefaults.standard.set(true, forKey: Location.REQUESTED_ALWAYS_AUTHORIZATION) //UserDefaults.standard.set(true, forKey: Location.REQUESTED_ALWAYS_AUTHORIZATION) } return // delegate will handle turning on location updates if approved. } else { locationAuthorizationStatus(viewController: caller, status: CLLocationManager.authorizationStatus()) } } static func stopBackgroundUpdates() { print("stopBackgroundUpdates()") requestedAuthorizationStatus = .notDetermined appDelegate.locationManager.stopUpdatingLocation() appDelegate.locationManager.stopMonitoringSignificantLocationChanges() appDelegate.locationManager.allowsBackgroundLocationUpdates = false; } static func startLocationUpdatesWhenInUse(caller: UIViewController?) { print("starting location updates when in use") requestedAuthorizationStatus = .authorizedWhenInUse let status = CLLocationManager.authorizationStatus() // if we don't have the required permission already if status != .authorizedAlways && status != .authorizedWhenInUse { // if the user has previously denied it. if UserDefaults.standard.bool(forKey: Location.REQUESTED_INUSE_AUTHORIZATION) { locationAuthorizationStatus(viewController: caller, status: status) return } else { // we can request it appDelegate.locationManager.requestWhenInUseAuthorization() } return // delegate will handle turning on location updates if approved. } else { // already have permission locationAuthorizationStatus(viewController: caller, status: status) } // appDelegate.locationManager.requestWhenInUseAuthorization() // appDelegate.locationManager.requestLocation() // //appDelegate.locationManager.startMonitoringSignificantLocationChanges() // appDelegate.locationManager.startUpdatingLocation() } static func locationAuthorizationStatus(viewController: UIViewController?, status: CLAuthorizationStatus) { print("Location.swift: locationAuthorizationChanged!") if requestedAuthorizationStatus == .authorizedWhenInUse { UserDefaults.standard.set(true, forKey: Location.REQUESTED_INUSE_AUTHORIZATION) } if requestedAuthorizationStatus == .authorizedAlways { UserDefaults.standard.set(true, forKey: Location.REQUESTED_ALWAYS_AUTHORIZATION) } Notifications.post(messageName: LOCATION_AUTHORIZATION_CHANGED, object: nil) if requestedAuthorizationStatus == .authorizedWhenInUse || requestedAuthorizationStatus == .authorizedAlways { appDelegate.locationManager.requestLocation() appDelegate.locationManager.startUpdatingLocation() appDelegate.locationManager.startMonitoringSignificantLocationChanges() } // default appDelegate.locationManager.allowsBackgroundLocationUpdates = false switch status { case .authorizedAlways: print("always is authorized") if(requestedAuthorizationStatus == .authorizedAlways) { appDelegate.locationManager.allowsBackgroundLocationUpdates = true } return case .authorizedWhenInUse: print("when in use") if(requestedAuthorizationStatus == .authorizedAlways) { locationPermissionFailed(viewController: viewController, message: "Please enable background location in the Settings app") } case .denied: print("denied") if(requestedAuthorizationStatus == .authorizedAlways || requestedAuthorizationStatus == .authorizedWhenInUse) { locationPermissionFailed(viewController: viewController, message: "Please enable location services in the Settings app") } case .notDetermined: print("not determined") // if(requestedAuthorizationStatus == .authorizedAlways || requestedAuthorizationStatus == .authorizedWhenInUse) { // locationPermissionFailed(viewController: viewController, message: "Please enable location services in the Settings app") // } return case .restricted: print("restricted") if(requestedAuthorizationStatus == .authorizedAlways || requestedAuthorizationStatus == .authorizedWhenInUse) { locationPermissionFailed(viewController: viewController, message: "Location services disabled by your administrator") } } } static func locationPermissionFailed(viewController: UIViewController?, message: String) { Notifications.post(messageName: Location.LOCATION_PERMISSION_FALIED, object: nil) let alertController = UIAlertController(title: "Location Denied", message: message, preferredStyle: UIAlertControllerStyle.alert) //Replace UIAlertControllerStyle.Alert by let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in print("OK") } alertController.addAction(okAction) if let controller = viewController { controller.present(alertController, animated: true, completion: nil) } else { print("no controller to present results to") } } // decide what to do with the new location. Depends if this user has a moving Naloxone kit static func updateUser(location: CLLocation) { /* if AppDelegate.fcmtoken == "" { AppDelegate.fcmtoken = Messaging.messaging().fcmToken } print ("token : \(AppDelegate.fcmtoken ?? "")") let date = Date()// Aug 25, 2017, 11:55 AM let calendar = Calendar.current let hour = calendar.component(.hour, from: date) //11 let minute = calendar.component(.minute, from: date) //55 let sec = calendar.component(.second, from: date) //33 let weekDay = calendar.component(.weekday, from: date) //6 (Friday) print("Time = \(weekDay) \(hour):\(minute):\(sec), Location = Lat:\(location.coordinate.latitude), Long:\(location.coordinate.longitude)") currentLocation = location Notifications.post(messageName: LOCATION_CHANGED, object: location, userInfo: nil) let loc = ["lat" : location.coordinate.latitude, "lng" : location.coordinate.longitude] as [String : Any] guard let uid = Auth.auth().currentUser?.uid else { return } let value = ["id" : AppDelegate.fcmtoken, "loc" : loc] as [String : Any] // firebase database reference of statickits locationAngelsRef = Database.database().reference().child("userLocations") // locationAngelsRef.setValue(uid) locationAngelsRef.child(uid).updateChildValues(value) // locationAngelsRef.child(uid) */ } }
40.804348
179
0.636121
f97266d1fb9a7241ce800f398093d78c3dba7c3d
129
func +=<Key, Value>(lhs: inout [Key: Value], rhs: [Key: Value]) { for (key, value) in rhs { lhs[key] = value } }
21.5
65
0.511628
f8f3acf5482a34c453cd44fff36232c1b8661ffb
518
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The view controller used as the root of the split view's master-side navigation controller. */ import UIKit class MasterViewController: UITableViewController { @IBAction func unwindInMaster(_ segue: UIStoryboardSegue) { /* Empty. Exists solely so that "unwind in master" segues can find this instance as a destination. */ } }
27.263158
95
0.677606
f738d17e25552938ca845bdc4afd3d158a2ec2f9
1,862
// // Color.swift // Sage // // Copyright 2016-2017 Nikolai Vazquez // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /// A chess color. public enum Color: String, CustomStringConvertible { /// White chess color. case white /// Black chess color. case black /// An array of all colors. public static let all: [Color] = [.white, .black] /// Whether the color is white or not. public var isWhite: Bool { return self == .white } /// Whether the color is black or not. public var isBlack: Bool { return self == .black } /// A textual representation of `self`. public var description: String { return rawValue } /// The lowercase character for the color. `White` is "w", `Black` is "b". public var character: Character { return self.isWhite ? "w" : "b" } /// Create a color from a character of any case. public init?(character: Character) { switch character { case "W", "w": self = .white case "B", "b": self = .black default: return nil } } /// Returns the inverse of `self`. public func inverse() -> Color { return self.isWhite ? .black : .white } /// Inverts the color of `self`. public mutating func invert() { self = inverse() } }
25.861111
78
0.619227
0eba76de4ee8ae5845fd4889fb32f423afa2cd4b
3,514
// // WeakKeyRetainsValueTests.swift // WeakDictionary // // Created by Nicholas Cross on 29/10/2016. // Copyright © 2016 Nicholas Cross. All rights reserved. // import XCTest @testable import WeakDictionary class WeakKeyRetainsValuesTests: XCTestCase { private var weakDictionary: WeakKeyDictionary<ExampleKey, ExampleValue>! override func setUp() { super.setUp() weakDictionary = WeakKeyDictionary<ExampleKey, ExampleValue>(valuesRetainedByKey: true) } func testAssignmentWithValuesRetainedByKey() { let accessingKey: ExampleKey = ExampleKey(name: "Left") var retainingKey: ExampleKey! = ExampleKey(name: "Left") var retainedValue: ExampleValue! = ExampleValue() weakDictionary[retainingKey!] = retainedValue XCTAssertEqual(weakDictionary.count, 1, "Expected to be left holding a reference") weak var accessedValue = weakDictionary[retainingKey] XCTAssertNotNil(accessedValue, "Expected key to have a value") retainedValue = nil XCTAssertEqual(weakDictionary.count, 1, "Expected to be left holding a reference") weak var transientAccessValue = weakDictionary[accessingKey] XCTAssertNotNil(transientAccessValue, "Expected key to have a value because it is retained by the key") weakDictionary.reap() XCTAssertNotNil(transientAccessValue, "Expected value to exist because it is retained by the key reference") retainingKey = nil weak var absentAccessValue = weakDictionary[accessingKey] XCTAssertEqual(weakDictionary.count, 1, "Expected to be left holding an empty reference") XCTAssertNil(absentAccessValue, "Expected key to no longer have a value because the key no longer retains it") XCTAssertNotNil(transientAccessValue, "Expected value to exist because it is retained by the key reference") weakDictionary.reap() XCTAssertNil(transientAccessValue, "Expected value to be nil as it is no longer retained by the key reference") } func testInitFromDictionary() { var transientKey: ExampleKey! = ExampleKey(name: "Left") var transientValue: ExampleValue! = ExampleValue() var dictionary: [ExampleKey: ExampleValue]! = [ transientKey: transientValue, ExampleKey(name: "Right"): ExampleValue() ] weakDictionary = WeakKeyDictionary<ExampleKey, ExampleValue>(dictionary: dictionary, valuesRetainedByKey: true) dictionary = nil weak var weaklyHeldValue: ExampleValue? = transientValue transientValue = nil XCTAssertNotNil(weakDictionary[ExampleKey(name: "Left")], "Expected value to be retained by key") XCTAssertNotNil(weaklyHeldValue, "Expected to be retained by key") transientKey = nil XCTAssertNil(weakDictionary[ExampleKey(name: "Left")], "Expected value to no longer be accessible by key") XCTAssertNotNil(weaklyHeldValue, "Expected to be retained by key container even though key is gone") weakDictionary.reap() XCTAssertNil(weaklyHeldValue, "Expected weakly held reference would be released after reaping") } } private class ExampleValue { } private class ExampleKey: Hashable { let value: String init(name: String) { value = name } public static func == (lhs: ExampleKey, rhs: ExampleKey) -> Bool { return lhs.value == rhs.value } public var hashValue: Int { return value.hash } }
36.989474
119
0.70461
e8f61a73132b7970f05a2a0637d302cacbf42688
266
import Foundation public protocol MemoryStorage { associatedtype Object var keys: Set<String> { get } func store(value: Object, forKey key: String) func value(forKey key: String) -> Object? func remove(forKey key: String) func removeAll() }
24.181818
49
0.695489
d7fb2ac1faf4f80d74389fd5d1abc2b25bb9ef03
17,192
// // SwiftCode.swift // SVGToSwift // // Created by Le Quang on 4/9/20. // Copyright © 2020 Le Viet Quang. All rights reserved. // import Foundation final class SwiftCode : CodeMaker { static let shared = SwiftCode() internal func makeRect(_ rect:CGRect, _ name:String, _ model:SVGDataModel = SVGDataModel())->String{ let code = "let \(name) = UIBezierPath(rect: CGRect(x: \(rect.origin.x), y: \(rect.origin.y), width: \(rect.size.width), height: \(rect.size.height)))\n" return code } internal func makePath(_ svgPath: SVGPath, _ name:String, _ model:SVGDataModel = SVGDataModel()) -> String { var code:String = "let \(name) = UIBezierPath()\n"; for command in svgPath.commands { switch command.type { case .move: code += "\(name).move(to: CGPoint(x: \(command.point.x.str), y: \(command.point.y.str)))\n" break case .line: code += "\(name).addLine(to: CGPoint(x: \(command.point.x.str), y: \(command.point.y.str)))\n" break case .quadCurve: code += "\(name).addQuadCurve(to: CGPoint(x: \(command.point.x.str), y: \(command.point.y.str)), controlPoint: CGPoint(x: \(command.control1.x.str), y: \(command.control1.y.str)))\n" break case .cubeCurve: code += "\(name).addCurve(to: CGPoint(x: \(command.point.x.str), y: \(command.point.y.str)), controlPoint1: CGPoint(x: \(command.control1.x.str), y: \(command.control1.y.str)), controlPoint2: CGPoint(x: \(command.control2.x.str), y: \(command.control2.y.str)))\n" break case .close: code += "\(name).close()\n" break case .style: code += "\(name).fill(\"\(command.nameStyle)\")\n" } } return code } func makeGrapth(_ name: String, _ model: SVGDataModel) -> String { var code = "\nlet \(model.name) = CAShapeLayer()\n" //code += "\(model.name).frame = CGRect(x: \(model.frame.origin.x), y: \(model.frame.origin.y), width: \(model.frame.size.width), height: \(model.frame.size.height))\n" if let namelayer = model.layerName { code += "\(model.name).name = \(namelayer.swiftStr())\n" } else { code += "\(model.name).name = \(model.name.swiftStr())\n" } return code } func makeSVG(_ model:SVGDataModel)->String { var code = "\nlet \(model.name) = CAShapeLayer()\n" code += "\(model.name).frame = CGRect(x: \(model.frame.origin.x), y: \(model.frame.origin.y), width: \(model.frame.size.width), height: \(model.frame.size.height))\n" code += "\(model.name).name = \(model.name.swiftStr())\n" code += "let viewSize = \(model.name).frame.size\n" code += "let affine = CGAffineTransform.init(translationX: (UIScreen.main.bounds.size.width-viewSize.width)/2, y: (UIScreen.main.bounds.size.height-viewSize.height)/2)\n" code += "\(model.name).setAffineTransform(affine)\n" return code } func makeCircle(_ model: SVGDataModel, _ center:CGPoint, _ radius:Double) -> String { let code = "let \(model.name) = UIBezierPath(circle: CGPoint(x: \(center.x), y: \(center.y)), radius: \(radius))\n" return code } func makeClipPath(_ model:SVGDataModel, childs:[CodeGroup]) -> String { var code = "\nlet \(model.name) = CAShapeLayer()\n" if childs.count > 0 { if childs.count == 1 { let ele = childs[0] as CodeGroup code += ele.code code += "\(model.name).path = \(ele.name).cgPath\n" } else { code += "let \(model.name)_path = CGMutablePath()\n" for ele in childs { code += ele.code code += "\(model.name)_path.addPath(\(ele.name).cgPath)\n" } code += "\(model.name).path = \(model.name).cgPath\n" } } return code } func makeDefs(_ model: SVGDataModel) -> String { return "" } func makeEllipse(_ model: SVGDataModel, _ center:CGPoint, _ radius1:Double, _ radius2:Double) -> String { return "let \(model.name) = UIBezierPath(ellipse: CGPoint(x: \(center.x), y: \(center.y)), rx: \(radius1), ry: \(radius2))\n" } func makeGlyph(_ model: SVGDataModel) -> String { return "" } func makeLine(_ model: SVGDataModel, _ point1:CGPoint, _ point2:CGPoint) -> String { return "let \(model.name) = UIBezierPath(line: CGPoint(x: \(point1.x), y: \(point1.y)), point2: CGPoint(x: \(point2.x), y: \(point2.y)))\n" } func makePolyline(_ model:SVGDataModel, _ points:[CGPoint]) -> String { if points.count >= 3 { var code:String = "let \(model.name) = UIBezierPath()\n" code += "\(model.name).move(to: CGPoint(x: \(points[0].x), y: \(points[0].y)))\n" for i in 1...points.count-1 { code += "\(model.name).addLine(to: CGPoint(x: \(points[i].x), y: \(points[i].y)))\n" } code += "\(model.name).close()\n" return code } return "" } func makeRadialGradient(_ model:SVGDataModel, _ colors:[String], _ locations:[NSNumber], _ point:CGPoint, _ radius:Double) -> String { let newcolor = colors.map { (ele) -> String in return "\(ele.swiftStr()).colorValue.cgColor" } let newlocation = locations.map { (ele) -> String in return "\(ele.doubleValue)" } var code = "let \(model.name)Mask = CAShapeLayer()\n" code += "\(model.name)Mask.path = UIBezierPath(circle: CGPoint(x: \(point.x), y: \(point.y)), radius: \(radius)).cgPath\n" code += "\(model.name)Mask.strokeColor = UIColor.clear.cgColor\n" code += "\(model.name)Mask.fillColor = UIColor.clear.cgColor\n" code += "let \(model.name) = CAGradientLayer()\n" code += "\(model.name).startPoint = CGPoint(x: 0.0, y: 0.0)\n" code += "\(model.name).endPoint = CGPoint(x: 1.0, y: 1.0)\n" code += "\(model.name).mask = \(model.name)Mask\n" code += "\(model.name).colors = [\(newcolor.joined(separator: ","))]\n" code += "\(model.name).locations = [\(newlocation.joined(separator: ","))]\n" return code } func makePolygon(_ model:SVGDataModel, _ points:[CGPoint])->String { if points.count >= 3 { var code:String = "let \(model.name) = UIBezierPath()\n"; code += "\(model.name).move(to: CGPoint(x: \(points[0].x), y: \(points[0].y)))\n" for i in 1...points.count-1 { code += "\(model.name).addLine(to: CGPoint(x: \(points[i].x), y: \(points[i].y)))\n" } code += "\(model.name).close()\n" return code } return "" } func parseModel(_ model:SVGDataModel, _ style:StyleSheet, _ deep:Int) -> String { model.printModel("\(deep)") var code = model.code let childPaths = model.childs.findPaths() var isOnePath = false if childPaths.count == 1 { isOnePath = true } for child in model.childs { if child.isPath { code += child.code /*let name = "\(model.type.rawValue)\(child.name.trim(child.type.rawValue))" code += "let \(name) = CAShapeLayer()\n" code += "\(name).path = \(child.name).cgPath\n" child.name = name code += applyShapeStyle(child, style) code += "\(model.name).addSublayer(\(child.name))\n\n"*/ if isOnePath == false { let name = "\(model.type.rawValue)\(child.name.trim(child.type.rawValue))" code += "let \(name) = CAShapeLayer()\n" code += "\(name).path = \(child.name).cgPath\n" child.name = name code += applyShapeStyle(child, style, child.name) code += "\(model.name).addSublayer(\(child.name))\n\n" } else { code += "\(model.name).path = \(child.name).cgPath\n" code += applyShapeStyle(child, style, model.name) } } else if child.isShape { code += self.parseModel(child, style, deep+1) code += applyShapeStyle(child, style, child.name) code += "\(model.name).addSublayer(\(child.name))\n\n" } } /* let childPaths = model.childs.findPaths() if(childPaths.count > 0) { for path in childPaths { code += path.code let name = "\(model.type.rawValue)\(path.name.trim(path.type.rawValue))" code += "let \(name) = CAShapeLayer()\n" code += "\(name).path = \(path.name).cgPath\n\n" path.name = name code += applyShapeStyle(path, style) code += "\(model.name).addSublayer(\(path.name))\n" } if childPaths.count >= 2 { code += "let \(model.name)_path = CGMutablePath()\n" code += "\n\n" for item in childPaths { if(item.code != ""){ code += item.code code += applyPathStyle(item, style) code += "\(model.name)_path.addPath(\(item.name).cgPath)\n" } } code += "\(model.name).path = \(model.name)_path\n\n" } else { code += childPaths.first!.code code += applyPathStyle(childPaths.first!, style) code += "\(model.name).path = \(childPaths.first!.name).cgPath\n\n" } } let childShapes = model.childs.findShape() if(childShapes.count > 0){ for item in childShapes { code += self.parseModel(item, style, deep+1) code += applyShapeStyle(item, style) code += "\(model.name).addSublayer(\(item.name))\n" } } */ return code } func getCode(_ model:SVGDataModel, _ style:StyleSheet) -> String { let code = parseModel(model, style, 0) return """ \(swiftExtensionTemplate) \(swiftHeaderTemplate(model.name)) \(code) \(swiftFooterTemplate(model.name)) """ } //MARK:-- //MARK: Apply Style to Draw private func applyStyle(_ model:SVGDataModel, _ style:StyleSheet) -> String { var code = "" if model.isShape { code += applyShapeStyle(model, style, model.name) } else { code += applyPathStyle(model, style) } return code } private func applyPathStyle(_ model:SVGDataModel, _ style:StyleSheet) -> String { var code = "" let pathAttribute = model.getPathAttributeModel(style) if pathAttribute.lineWidth != 1.0 { code += "\(model.name).lineWidth = \(pathAttribute.lineWidth)\n" } if pathAttribute.lineCapStyle != .butt { if pathAttribute.lineCapStyle == .round { code += "\(model.name).lineCapStyle = .round\n" } else if pathAttribute.lineCapStyle == .square { code += "\(model.name).lineCapStyle = .square\n" } } if pathAttribute.lineJoinStyle != .miter { if pathAttribute.lineJoinStyle == .bevel { code += "\(model.name).lineJoinStyle = .bevel\n" } else if pathAttribute.lineJoinStyle == .round { code += "\(model.name).lineJoinStyle = .round\n" } } if pathAttribute.miterLimit != 10 { code += "\(model.name).miterLimit = \(pathAttribute.miterLimit)\n" } if pathAttribute.flatness != 0.6 { code += "\(model.name).flatness = \(pathAttribute.flatness)\n" } if pathAttribute.usesEvenOddFillRule != false { code += "\(model.name).usesEvenOddFillRule = true\n" } if let strokeColor = pathAttribute.strokeColor { code += "\(model.name).strokeWithHex(\(strokeColor.swiftHex()))\n" } if let fillColor = pathAttribute.fillColor { code += "\(model.name).fillWithHex(\(fillColor.swiftHex()))\n" } return code } private func applyShapeStyle(_ model:SVGDataModel, _ style:StyleSheet, _ name:String) -> String { let shapeStyle = model.getStyleList(style).getLastStyle() return applyStyle(Shape: shapeStyle, model, name) /* var shapeAttribute = model.getShapeAttributeModel(style) var code = "" // if shapeAttribute.isDefault == true { // if let parent = model.parentNode { // shapeAttribute = parent.getShapeAttributeModel(style) // } // } if let fillColor = shapeAttribute.fillColor { code += "\(model.name).fill(\(fillColor.swiftHex()))\n" } if let name = shapeAttribute.name { code += "\(model.name).name = \(name.swiftStr())\n" } if shapeAttribute.fillRule != .nonZero { code += "\(model.name).fillRule = CAShapeLayerFillRule.evenOdd\n" } if shapeAttribute.lineCap != .butt { if shapeAttribute.lineCap == .round { code += "\(model.name).lineCap = .round\n" } else if shapeAttribute.lineCap == .square { code += "\(model.name).lineCap = .square\n" } } if shapeAttribute.lineDashPhase != 0 { code += "\(model.name).lineDashPhase = \(shapeAttribute.lineDashPhase)\n" } if shapeAttribute.lineJoin != .miter { if shapeAttribute.lineJoin == .bevel { code += "\(model.name).lineJoin = .bevel\n" } else if shapeAttribute.lineJoin == .round { code += "\(model.name).lineJoin = .round\n" } } if shapeAttribute.lineWidth != 1 { code += "\(model.name).lineWidth = \(shapeAttribute.lineWidth)\n" } if shapeAttribute.miterLimit != 10 { code += "\(model.name).miterLimit = \(shapeAttribute.miterLimit)\n" } if let strokeColor = shapeAttribute.strokeColor { code += "\(model.name).strokeColor = \(strokeColor.swiftHex()).colorValue.cgColor\n" } if shapeAttribute.opacity != 1 { code += "\(model.name).opacity = Float(\(shapeAttribute.opacity))\n" } return code */ } private func applyStyle(Shape shapeStyle:ShapeStyleModel, _ model:SVGDataModel, _ name:String) -> String { var code = "" if let fillColor = shapeStyle.fillColor { code += "\(name).fill(\(fillColor.swiftHex()))\n" } if let nameStr = shapeStyle.name { code += "\(name).name = \(nameStr.swiftStr())\n" } if shapeStyle.fillRule.0 != .nonZero { code += "\(name).fillRule = CAShapeLayerFillRule.evenOdd\n" } if shapeStyle.lineCap.0 != .butt { if shapeStyle.lineCap.0 == .round { code += "\(name).lineCap = .round\n" } else if shapeStyle.lineCap.0 == .square { code += "\(name).lineCap = .square\n" } } if shapeStyle.lineDashPhase.0 != 0 { code += "\(name).lineDashPhase = \(shapeStyle.lineDashPhase.0)\n" } if shapeStyle.lineJoin.0 != .miter { if shapeStyle.lineJoin.0 == .bevel { code += "\(name).lineJoin = .bevel\n" } else if shapeStyle.lineJoin.0 == .round { code += "\(name).lineJoin = .round\n" } } if shapeStyle.lineWidth.0 != 1 { code += "\(name).lineWidth = \(shapeStyle.lineWidth.0)\n" } if shapeStyle.miterLimit.0 != 10 { code += "\(name).miterLimit = \(shapeStyle.miterLimit.0)\n" } if let strokeColor = shapeStyle.strokeColor { code += "\(name).strokeColor = \(strokeColor.swiftHex()).colorValue.cgColor\n" } if shapeStyle.opacity.0 != 1 { code += "\(name).opacity = Float(\(shapeStyle.opacity.0))\n" } return code } }
38.984127
279
0.511052
01882f5e3c36ba8872a62eea6427a6a8b6005faa
2,508
/* MIT License Copyright (c) 2017-2019 MessageKit 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 import UIKit internal extension UIColor { private static func colorFromAssetBundle(named: String) -> UIColor { guard let color = UIColor(named: named, in: Bundle.messageKitAssetBundle, compatibleWith: nil) else { fatalError(MessageKitError.couldNotFindColorAsset) } return color } static var incomingMessageBackground: UIColor { colorFromAssetBundle(named: "incomingMessageBackground") } static var outgoingMessageBackground: UIColor { colorFromAssetBundle(named: "outgoingMessageBackground") } static var incomingMessageLabel: UIColor { colorFromAssetBundle(named: "incomingMessageLabel") } static var outgoingMessageLabel: UIColor { colorFromAssetBundle(named: "outgoingMessageLabel") } static var incomingAudioMessageTint: UIColor { colorFromAssetBundle(named: "incomingAudioMessageTint") } static var outgoingAudioMessageTint: UIColor { colorFromAssetBundle(named: "outgoingAudioMessageTint") } static var collectionViewBackground: UIColor { colorFromAssetBundle(named: "collectionViewBackground") } static var typingIndicatorDot: UIColor { colorFromAssetBundle(named: "typingIndicatorDot") } static var label: UIColor { colorFromAssetBundle(named: "label") } static var avatarViewBackground: UIColor { colorFromAssetBundle(named: "avatarViewBackground") } }
43.241379
111
0.76874
488c7cfff2d4fd23c421435d9a40f74ce73e5452
5,417
import Flutter import UIKit import UserNotifications public class SwiftNotificationPermissionsPlugin: NSObject, FlutterPlugin { var permissionGranted:String = "granted" var permissionUnknown:String = "unknown" var permissionDenied:String = "denied" var permissionProvisional:String = "provisional" public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "notification_permissions", binaryMessenger: registrar.messenger()) let instance = SwiftNotificationPermissionsPlugin() registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { if (call.method == "requestNotificationPermissions") { // check if we can ask for permissions getNotificationStatus(completion: { status in if (status == self.permissionUnknown || status == self.permissionProvisional) { if #available(iOS 10.0, *) { let center = UNUserNotificationCenter.current() var options = UNAuthorizationOptions() if let arguments = call.arguments as? Dictionary<String, Bool> { if(arguments["sound"] != nil){ options.insert(.sound) } if(arguments["alert"] != nil){ options.insert(.alert) } if(arguments["badge"] != nil){ options.insert(.badge) } } center.requestAuthorization(options: options) { (success, error) in if error == nil { if success == true { result(self.permissionGranted) } else { result(self.permissionDenied) } } else { result(error?.localizedDescription) } } } else { // If the permission status is unknown, the user hasn't denied it var notificationTypes = UIUserNotificationType(rawValue: 0) if let arguments = call.arguments as? Dictionary<String, Bool> { if arguments["sound"] != nil { notificationTypes.insert(UIUserNotificationType.sound) } if arguments["alert"] != nil { notificationTypes.insert(UIUserNotificationType.alert) } if arguments["badge"] != nil { notificationTypes.insert(UIUserNotificationType.badge) } var settings: UIUserNotificationSettings? = nil settings = UIUserNotificationSettings(types: notificationTypes, categories: nil) if let settings = settings { UIApplication.shared.registerUserNotificationSettings(settings) } self.getNotificationStatus(completion: { status in result(status) }); } } } else if (status == self.permissionDenied) { // The user has denied the permission he must go to the settings screen if let arguments = call.arguments as? Dictionary<String, Bool> { if (arguments["openSettings"] != nil && arguments["openSettings"] == false) { result(self.permissionDenied) return } } if let url = URL(string:UIApplication.openSettingsURLString) { if UIApplication.shared.canOpenURL(url) { if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil) } else { UIApplication.shared.openURL(url) } } } result(nil) } else { result(nil) } }) } else if (call.method == "getNotificationPermissionStatus") { getNotificationStatus(completion: { status in result(status) }) } else { result(FlutterMethodNotImplemented) } } func getNotificationStatus(completion: @escaping ((String) -> Void)) { if #available(iOS 10.0, *) { let current = UNUserNotificationCenter.current() current.getNotificationSettings(completionHandler: { settings in if settings.authorizationStatus == .notDetermined { completion(self.permissionUnknown) } else if settings.authorizationStatus == .denied { completion(self.permissionDenied) } else if settings.authorizationStatus == .authorized { completion(self.permissionGranted) } else if #available(iOS 12.0, *){ if (settings.authorizationStatus == .provisional){ completion(self.permissionProvisional) } } }) } else { // Fallback on earlier versions if UIApplication.shared.isRegisteredForRemoteNotifications { completion(self.permissionGranted) } else { completion(self.permissionDenied) } } } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToUIApplicationOpenExternalURLOptionsKeyDictionary(_ input: [String: Any]) -> [UIApplication.OpenExternalURLOptionsKey: Any] { return Dictionary(uniqueKeysWithValues: input.map { key, value in (UIApplication.OpenExternalURLOptionsKey(rawValue: key), value)}) }
39.830882
157
0.606055
d5240d65dc7cb74a3e169b2f9f15ef707dd4c0d5
3,145
// // PetResponse.swift // Petulia // // Created by Johandre Delgado on 02.08.2020. // Copyright © 2020 Johandre Delgado . All rights reserved. import Foundation // MARK: - Animal Modeling API response struct Animal: Codable, Identifiable { let id: Int let organizationID: String? let url: String? let type, species: String? let age, gender, size: String? let tags: [String]? let attributes: Attributes? let name, animalDescription, description: String? let status: String? let publishedAt: String? let photos: [Photo]? let distance: Double? let breeds: Breed? enum CodingKeys: String, CodingKey { case id case organizationID = "organization_id" case url, type, age, tags, attributes, name, species, size, gender, animalDescription, description, photos, distance, breeds case status case publishedAt = "published_at" } } // MARK: - Component DTOs struct AllAnimals: Codable { let animals: [Animal]? let pagination: PaginationDTO } struct PaginationDTO: Codable { var countPerPage: Int var totalCount: Int var currentPage: Int var totalPages: Int let links: PaginationLinks? enum CodingKeys: String, CodingKey { case countPerPage = "count_per_page" case totalCount = "total_count" case currentPage = "current_page" case totalPages = "total_pages" case links = "_links" } } extension PaginationDTO { static var new: PaginationDTO { PaginationDTO(countPerPage: 20, totalCount: 20, currentPage: 1, totalPages: 1, links: PaginationLinks(previous: nil, next: nil)) } } struct PaginationLinks: Codable { let previous: LinkString? let next: LinkString? } struct LinkString: Codable { let href: String } struct Photo: Codable { let small, medium, large, full: String? func imagePath(for size: Size) -> String { let noUrlString = "no-image" switch size { case .small: return self.small ?? noUrlString case .medium: return self.medium ?? noUrlString case .large: return self.large ?? noUrlString case .full: return self.full ?? noUrlString } } } enum Size: String, Codable { case small, medium, large, full } // MARK: - Address struct Address: Codable { let address1, address2, city, state: String? let postcode, country: String? } struct Breed: Codable { let primary, secondary: String? let mixed: Bool let unknown: Bool static var new: Breed { Breed(primary: nil, secondary: nil, mixed: false, unknown: true) } } struct Attributes: Codable { var spayed: Bool? var trained: Bool? var declawed: Bool? var special: Bool? var vacinated: Bool? enum CodingKeys: String, CodingKey { case spayed = "spayed_neutered" case trained = "house_trained" case declawed = "declawed" case special = "special_needs" case vacinated = "shots_current" } } extension Attributes { var list: [String: Bool] { return [ "spayed": spayed ?? false, "trained": trained ?? false, "declawed": declawed ?? false, "special": special ?? false, "vacinated": vacinated ?? false ] } }
21.689655
132
0.674086
61952f9b2340d61bc487f36a449726dcea12e4e3
1,225
// // DYZBUITests.swift // DYZBUITests // // Created by maxine on 2018/1/19. // Copyright © 2018年 maxine. All rights reserved. // import XCTest class DYZBUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.108108
182
0.658776
fe606be910e61d8947d8e70768bc4bf56edcb089
2,009
// // SocketRequests.swift // freechat-swift // // Created by Dzung on 10/05/2021. // Copyright © 2021 Young Monkeys. All rights reserved. // public class SocketRequests { private init() {} public static func sendGetContacts() { let requestData = NSMutableDictionary() requestData["skip"] = 0 requestData["limit"] = 100 getApp()?.send(cmd: Commands.GET_CONTACTS, data: requestData) } public static func sendGetSuggestContacts() { getApp()?.send(cmd: Commands.SUGGEST_CONTACTS) } public static func sendBotMessage(message: String) { let requestData = NSMutableDictionary() requestData["message"] = message getApp()?.send(cmd: Commands.CHAT_BOT_MESSAGE, data: requestData) } public static func sendUserMessage(channelId: Int64, message: String) { let requestData = NSMutableDictionary() requestData["channelId"] = channelId requestData["message"] = message getApp()?.send(cmd: Commands.CHAT_USER_MESSAGE, data: requestData) } public static func sendSearchContacts(keyword: String) { let requestData = NSMutableDictionary() requestData["keyword"] = keyword getApp()?.send(cmd: Commands.SEARCH_CONTACTS, data: requestData) } public static func sendSearchExistedContacts(keyword: String) { let requestData = NSMutableDictionary() requestData["skip"] = 0 requestData["limit"] = 100 requestData["keyword"] = keyword getApp()?.send(cmd: Commands.SEARCH_EXISTED_CONTACTS, data: requestData); } public static func sendAddContacts(user: String) { let requestData = NSMutableDictionary() requestData["target"] = [user] getApp()?.send(cmd: Commands.ADD_CONTACTS, data: requestData) } private static func getApp() -> EzyApp? { return EzyClients.getInstance() .getDefaultClient() .getApp() } }
32.403226
81
0.642111
71c9cd0f8a231cdc954b67c2fbd518d0b2d46ecb
1,324
// // LocalStorageService.swift // Stellar // // Created by Nguyen Minh Quan on 11/18/20. // import Foundation public protocol LocalStorageServiceType { func saveData<T: Codable>(_ data: T, key: String) func loadData<T: Decodable>(_ key: String, dataType: T.Type) -> [T]? func removeAll() } public final class LocalStorageService: LocalStorageServiceType { private let userDefault: UserDefaults public init(userDefault: UserDefaults) { self.userDefault = userDefault } public func removeAll() { if let appDomain = Bundle.main.bundleIdentifier { UserDefaults.standard.removePersistentDomain(forName: appDomain) } } public func saveData<T: Codable>(_ data: T, key: String) { if let data = try? PropertyListEncoder().encode(data) { userDefault.setValue(data, forKey: key) } } public func loadData<T: Decodable>(_ key: String, dataType: T.Type) -> [T]? { if let data = userDefault.data(forKey: key) { return try? PropertyListDecoder().decode([T].self, from: data) } return nil } } extension LocalStorageService { static let `default`: LocalStorageService = { return LocalStorageService(userDefault: UserDefaults.standard) }() }
27.020408
81
0.641994
b9a0227ba0169dfd449c0226b65536e8190ece84
506
import UIKit class AboutViewController: UIViewController { //let renderer = MongolUnicodeRenderer.sharedInstance @IBOutlet weak var chimeeVersionLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // get current version number let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String chimeeVersionLabel.text = "Chimee \(version ?? "")" } }
22
82
0.620553
896cdc92768044ce41de74e933459914721ea348
7,157
// // XRouter.swift // XRouter // // Created by Reece Como on 5/1/19. // import UIKit /** An appliance that analyzes the navigation stack, and navigates you to the content you are trying to display. ```swift // Define your router, with a `RouteProvider` let router = Router<AppRoutes>() ``` */ open class Router<Route: RouteProvider> { // MARK: - Properties /// Custom transition delegate public weak var customTransitionDelegate: RouterCustomTransitionDelegate? /// Register url matcher group private lazy var urlMatcherGroup: URLMatcherGroup? = Route.registerURLs() // MARK: - Computed properties /// The navigation controller for the currently presented view controller public var currentTopViewController: UIViewController? { return UIApplication.shared.getTopViewController() } // MARK: - Methods /// Initialiser public init() { // Placeholder, required to expose `init` as `public` } /// /// Navigate to a route. /// /// - Note: Has no effect if the destination view controller is the view controller or navigation controller /// you are presently on - as provided by `RouteProvider(_:).prepareForTransition(...)`. /// open func navigate(to route: Route, animated: Bool = true, completion: ((Error?) -> Void)? = nil) { prepareForNavigation(to: route, animated: animated, successHandler: { source, destination in self.performNavigation(from: source, to: destination, with: route.transition, animated: animated, completion: completion) }, errorHandler: { error in completion?(error) }) } /// /// Open a URL to a route. /// /// - Note: Register your URL mappings in your `RouteProvider` by /// implementing the static method `registerURLs`. /// @discardableResult open func openURL(_ url: URL, animated: Bool = true, completion: ((Error?) -> Void)? = nil) -> Bool { do { if let route = try findMatchingRoute(for: url) { navigate(to: route, animated: animated, completion: completion) return true } else { completion?(nil) // No matching route. } } catch { completion?(error) // There was an error. } return false } // MARK: - Implementation /// /// Prepare the route for navigation. /// /// - Fetching the view controller we want to present /// - Checking if its already in the view heirarchy /// - Checking if it is a direct ancestor and then closing its children/siblings /// /// - Note: The completion block will not execute if we could not find a route /// private func prepareForNavigation(to route: Route, animated: Bool, successHandler: @escaping (_ source: UIViewController, _ destination: UIViewController) -> Void, errorHandler: @escaping (Error) -> Void) { guard let source = currentTopViewController else { errorHandler(RouterError.missingSourceViewController) return } let destination: UIViewController do { destination = try route.prepareForTransition(from: source) } catch { errorHandler(error) return } guard let nearestAncestor = source.getLowestCommonAncestor(with: destination) else { // No common ancestor - Adding destination to the stack for the first time successHandler(source, destination) return } // Clear modal - then prepare for child view controller. nearestAncestor.transition(toDescendant: destination, animated: animated) { successHandler(nearestAncestor.visibleViewController, destination) } } /// Perform navigation private func performNavigation(from source: UIViewController, to destination: UIViewController, with transition: RouteTransition, animated: Bool, completion: ((Error?) -> Void)?) { // Already here/on current navigation controller if destination === source || destination === source.navigationController { // No error? -- maybe throw an "already here" error completion?(nil) return } // The source view controller will be the navigation controller where // possible - but will otherwise default to the current view controller // i.e. for "present" transitions. let source = source.navigationController ?? source switch transition { case .push: if let navController = source as? UINavigationController { navController.pushViewController(destination, animated: animated) { completion?(nil) } } else { completion?(RouterError.missingRequiredNavigationController(for: transition)) } case .set: if let navController = source as? UINavigationController { navController.setViewControllers([destination], animated: animated) { completion?(nil) } } else { completion?(RouterError.missingRequiredNavigationController(for: transition)) } case .modal: source.present(destination, animated: animated) { completion?(nil) } case .custom: if let customTransitionDelegate = customTransitionDelegate { customTransitionDelegate.performTransition(to: destination, from: source, transition: transition, animated: animated, completion: completion) } else { completion?(RouterError.missingCustomTransitionDelegate) } } } /// /// Find a matching Route for a URL. /// /// - Note: This method throws an error when the route is mapped /// but the mapping fails. /// private func findMatchingRoute(for url: URL) throws -> Route? { if let urlMatcherGroup = urlMatcherGroup { for urlMatcher in urlMatcherGroup.matchers { if let route = try urlMatcher.match(url: url) { return route } } } return nil } }
36.146465
134
0.543803
33d959670701f461d74a1a6002a7f39e293df0c7
10,301
import XCTest #if GRDBCIPHER import GRDBCipher #elseif GRDBCUSTOMSQLITE import GRDBCustomSQLite #else import GRDB #endif private enum CustomValue : Int, DatabaseValueConvertible, Equatable { case a = 0 case b = 1 case c = 2 } class RowFromDictionaryLiteralTests : RowTestCase { func testRowAsSequence() { let row: Row = ["a": 0, "b": 1, "c": 2] var columnNames = Set<String>() var ints = Set<Int>() var bools = Set<Bool>() for (columnName, dbValue) in row { columnNames.insert(columnName) ints.insert(Int.fromDatabaseValue(dbValue)!) bools.insert(Bool.fromDatabaseValue(dbValue)!) } XCTAssertEqual(columnNames, ["a", "b", "c"]) XCTAssertEqual(ints, [0, 1, 2]) XCTAssertEqual(bools, [false, true, true]) } func testColumnOrderIsPreserved() { // Paramount for tests let row: Row = ["a": 0, "i": 8, "b": 1, "h": 7, "c": 2, "g": 6, "d": 3, "f": 5, "e": 4] XCTAssertEqual(Array(row.columnNames), ["a", "i", "b", "h", "c", "g", "d", "f", "e"]) } func testDuplicateColumnNames() { // Paramount for tests let row: Row = ["a": 0, "a": 1] XCTAssertEqual(Array(row.columnNames), ["a", "a"]) XCTAssertEqual(row["a"] as Int, 0) } func testRowValueAtIndex() { let row: Row = ["a": 0, "b": 1, "c": 2] let aIndex = row.distance(from: row.startIndex, to: row.index(where: { (column, value) in column == "a" })!) let bIndex = row.distance(from: row.startIndex, to: row.index(where: { (column, value) in column == "b" })!) let cIndex = row.distance(from: row.startIndex, to: row.index(where: { (column, value) in column == "c" })!) // Raw extraction assertRowRawValueEqual(row, index: aIndex, value: 0 as Int64) assertRowRawValueEqual(row, index: bIndex, value: 1 as Int64) assertRowRawValueEqual(row, index: cIndex, value: 2 as Int64) // DatabaseValueConvertible & StatementColumnConvertible assertRowConvertedValueEqual(row, index: aIndex, value: 0 as Int) assertRowConvertedValueEqual(row, index: bIndex, value: 1 as Int) assertRowConvertedValueEqual(row, index: cIndex, value: 2 as Int) // DatabaseValueConvertible assertRowConvertedValueEqual(row, index: aIndex, value: CustomValue.a) assertRowConvertedValueEqual(row, index: bIndex, value: CustomValue.b) assertRowConvertedValueEqual(row, index: cIndex, value: CustomValue.c) // Expect fatal error: // // row[-1] // row[3] } func testRowValueNamed() { let row: Row = ["a": 0, "b": 1, "c": 2] // Raw extraction assertRowRawValueEqual(row, name: "a", value: 0 as Int64) assertRowRawValueEqual(row, name: "b", value: 1 as Int64) assertRowRawValueEqual(row, name: "c", value: 2 as Int64) // DatabaseValueConvertible & StatementColumnConvertible assertRowConvertedValueEqual(row, name: "a", value: 0 as Int) assertRowConvertedValueEqual(row, name: "b", value: 1 as Int) assertRowConvertedValueEqual(row, name: "c", value: 2 as Int) // DatabaseValueConvertible assertRowConvertedValueEqual(row, name: "a", value: CustomValue.a) assertRowConvertedValueEqual(row, name: "b", value: CustomValue.b) assertRowConvertedValueEqual(row, name: "c", value: CustomValue.c) } func testRowValueFromColumn() { let row: Row = ["a": 0, "b": 1, "c": 2] // Raw extraction assertRowRawValueEqual(row, column: Column("a"), value: 0 as Int64) assertRowRawValueEqual(row, column: Column("b"), value: 1 as Int64) assertRowRawValueEqual(row, column: Column("c"), value: 2 as Int64) // DatabaseValueConvertible & StatementColumnConvertible assertRowConvertedValueEqual(row, column: Column("a"), value: 0 as Int) assertRowConvertedValueEqual(row, column: Column("b"), value: 1 as Int) assertRowConvertedValueEqual(row, column: Column("c"), value: 2 as Int) // DatabaseValueConvertible assertRowConvertedValueEqual(row, column: Column("a"), value: CustomValue.a) assertRowConvertedValueEqual(row, column: Column("b"), value: CustomValue.b) assertRowConvertedValueEqual(row, column: Column("c"), value: CustomValue.c) } func testDataNoCopy() { do { let data = "foo".data(using: .utf8)! let row: Row = ["a": data] XCTAssertEqual(row.dataNoCopy(atIndex: 0), data) XCTAssertEqual(row.dataNoCopy(named: "a"), data) XCTAssertEqual(row.dataNoCopy(Column("a")), data) } do { let emptyData = Data() let row: Row = ["a": emptyData] XCTAssertEqual(row.dataNoCopy(atIndex: 0), emptyData) XCTAssertEqual(row.dataNoCopy(named: "a"), emptyData) XCTAssertEqual(row.dataNoCopy(Column("a")), emptyData) } do { let row: Row = ["a": nil] XCTAssertNil(row.dataNoCopy(atIndex: 0)) XCTAssertNil(row.dataNoCopy(named: "a")) XCTAssertNil(row.dataNoCopy(Column("a"))) } } func testRowDatabaseValueAtIndex() throws { let row: Row = ["null": nil, "int64": 1, "double": 1.1, "string": "foo", "blob": "SQLite".data(using: .utf8)] let nullIndex = row.distance(from: row.startIndex, to: row.index(where: { (column, value) in column == "null" })!) let int64Index = row.distance(from: row.startIndex, to: row.index(where: { (column, value) in column == "int64" })!) let doubleIndex = row.distance(from: row.startIndex, to: row.index(where: { (column, value) in column == "double" })!) let stringIndex = row.distance(from: row.startIndex, to: row.index(where: { (column, value) in column == "string" })!) let blobIndex = row.distance(from: row.startIndex, to: row.index(where: { (column, value) in column == "blob" })!) guard case .null = (row[nullIndex] as DatabaseValue).storage else { XCTFail(); return } guard case .int64(let int64) = (row[int64Index] as DatabaseValue).storage, int64 == 1 else { XCTFail(); return } guard case .double(let double) = (row[doubleIndex] as DatabaseValue).storage, double == 1.1 else { XCTFail(); return } guard case .string(let string) = (row[stringIndex] as DatabaseValue).storage, string == "foo" else { XCTFail(); return } guard case .blob(let data) = (row[blobIndex] as DatabaseValue).storage, data == "SQLite".data(using: .utf8) else { XCTFail(); return } } func testRowDatabaseValueNamed() throws { let row: Row = ["null": nil, "int64": 1, "double": 1.1, "string": "foo", "blob": "SQLite".data(using: .utf8)] guard case .null = (row["null"] as DatabaseValue).storage else { XCTFail(); return } guard case .int64(let int64) = (row["int64"] as DatabaseValue).storage, int64 == 1 else { XCTFail(); return } guard case .double(let double) = (row["double"] as DatabaseValue).storage, double == 1.1 else { XCTFail(); return } guard case .string(let string) = (row["string"] as DatabaseValue).storage, string == "foo" else { XCTFail(); return } guard case .blob(let data) = (row["blob"] as DatabaseValue).storage, data == "SQLite".data(using: .utf8) else { XCTFail(); return } } func testRowCount() { let row: Row = ["a": 0, "b": 1, "c": 2] XCTAssertEqual(row.count, 3) } func testRowColumnNames() { let row: Row = ["a": 0, "b": 1, "c": 2] XCTAssertEqual(Array(row.columnNames).sorted(), ["a", "b", "c"]) } func testRowDatabaseValues() { let row: Row = ["a": 0, "b": 1, "c": 2] XCTAssertEqual(row.databaseValues.sorted { Int.fromDatabaseValue($0)! < Int.fromDatabaseValue($1)! }, [0.databaseValue, 1.databaseValue, 2.databaseValue]) } func testRowIsCaseInsensitive() { let row: Row = ["name": "foo"] XCTAssertEqual(row["name"] as DatabaseValue, "foo".databaseValue) XCTAssertEqual(row["NAME"] as DatabaseValue, "foo".databaseValue) XCTAssertEqual(row["NaMe"] as DatabaseValue, "foo".databaseValue) XCTAssertEqual(row["name"] as String, "foo") XCTAssertEqual(row["NAME"] as String, "foo") XCTAssertEqual(row["NaMe"] as String, "foo") } func testMissingColumn() { let row: Row = ["name": "foo"] XCTAssertFalse(row.hasColumn("missing")) XCTAssertTrue(row["missing"] as DatabaseValue? == nil) XCTAssertTrue(row["missing"] == nil) } func testRowHasColumnIsCaseInsensitive() { let row: Row = ["nAmE": "foo", "foo": 1] XCTAssertTrue(row.hasColumn("name")) XCTAssertTrue(row.hasColumn("NAME")) XCTAssertTrue(row.hasColumn("Name")) XCTAssertTrue(row.hasColumn("NaMe")) XCTAssertTrue(row.hasColumn("foo")) XCTAssertTrue(row.hasColumn("Foo")) XCTAssertTrue(row.hasColumn("FOO")) } func testScopes() { let row: Row = ["a": 0, "b": 1, "c": 2] XCTAssertTrue(row.scopes.isEmpty) XCTAssertTrue(row.scopes["missing"] == nil) XCTAssertTrue(row.scopesTree["missing"] == nil) } func testCopy() { let row: Row = ["a": 0, "b": 1, "c": 2] let copiedRow = row.copy() XCTAssertEqual(copiedRow.count, 3) XCTAssertEqual(copiedRow["a"] as Int, 0) XCTAssertEqual(copiedRow["b"] as Int, 1) XCTAssertEqual(copiedRow["c"] as Int, 2) } func testEqualityWithCopy() { let row: Row = ["a": 0, "b": 1, "c": 2] let copiedRow = row.copy() XCTAssertEqual(row, copiedRow) } func testDescription() throws { let row: Row = ["a": 0, "b": 1, "c": 2] XCTAssertEqual(row.description, "[a:0 b:1 c:2]") XCTAssertEqual(row.debugDescription, "[a:0 b:1 c:2]") } }
43.100418
162
0.591302
87bf6c4b906c8bdbc1b5bee60d1d0bd95f794385
2,125
// // MIT License // // Copyright (c) 2018-2019 Radix DLT ( https://radixdlt.com ) // // 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 extension Data { func toHexString(case: String.Case? = nil, mode: StringConversionMode? = nil) -> HexString { let hexString = HexString(data: asData) var hex = hexString.stringValue.changeCaseIfNeeded(to: `case`) switch mode { case .none: break case .minimumLength(let minimumLength, let concatMode)?: hex.prependOrAppend(character: "0", toLength: minimumLength, mode: concatMode) case .trim?: hex.trim(character: "0") } return HexString(validated: hex) } func toBase64String(minLength: Int? = nil) -> Base64String { let data = toData(minByteCount: minLength, concatMode: .prepend) return Base64String(data: data) } func toBase58String(minLength: Int? = nil) -> Base58String { let data = toData(minByteCount: minLength, concatMode: .prepend) return Base58String(data: data) } }
40.865385
96
0.701176
2fbdd384922dc7ea7ba1c59077f3e0fd62232cbf
856
// // QuickAddListResponseModel.swift // goTapAPI // // Created by Dennis Pashkov on 8/4/16. // Copyright © 2016 Tap Payments. All rights reserved. // /// Quick add list response model. public class QuickAddListResponseModel: GetListResponseModel { //MARK: - Public - //MARK: Properties /// Screen. public var screen: QuickAddListResponseScreen = QuickAddListResponseScreen.Home //MARK: Methods internal override func dataModelWith(serializedObject: Any?) -> Self? { guard let dictionary = serializedObject as? [String: AnyObject] else { return nil } guard let model = super.dataModelWith(serializedObject: serializedObject) as? QuickAddListResponseModel else { return nil } model.screen = QuickAddListResponseScreen.with(stringValue: dictionary.parseString(forKey: Constants.Key.Screen)) return model.tap_asSelf() } }
28.533333
125
0.748832
1852b9be474d59e3a3f576ba18a0943d4e114ff5
309
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class a { protocol A { let f = { struct Q<T { protocol A { } } return ""[Void{ struct Q<T { func g: NSObject { class case c, class a<d wher
17.166667
87
0.708738
bb2298442fcb2d5c1d64cdffbd0b3ec21951695f
940
// import Foundation import UIKit public class KVTTextField: UITextField { public override init(frame: CGRect){ super.init(frame: frame) setupView() } required init?(coder: NSCoder) { super.init(coder: coder) setupView() } override public func layoutSubviews() { super.layoutSubviews() } override open func editingRect(forBounds bounds: CGRect) -> CGRect { return bounds.inset(by: UIEdgeInsets(top: 2, left: 6, bottom: 2, right: 4)) } override open func textRect(forBounds bounds: CGRect) -> CGRect { return bounds.inset(by: UIEdgeInsets(top: 2, left: 6, bottom: 2, right: 4)) } override public var intrinsicContentSize: CGSize { return CGSize(width: 180.0, height: 55.0) } func setupView() { font = .systemFont(ofSize: 16) textColor = theme.primaryColor?.color() } }
24.736842
83
0.607447
bf64cb69b28fc30a661c20af6332c084acc32c92
260
// // MOScore.swift // Project_Get_Word // // Created by Давид on 06/12/2019. // Copyright © 2019 David. All rights reserved. // import Foundation import CoreData @objc(MOScore) internal class MOScore: NSManagedObject { @NSManaged var score: Int16 }
16.25
48
0.711538
224691b5572fe6ed8ef56c06c99197b62ab488df
987
// // SwiftPracticeTests.swift // SwiftPracticeTests // // Created by 吴蕾君 on 16/1/8. // Copyright © 2016年 rayjuneWu. All rights reserved. // import XCTest @testable import SwiftPractice class SwiftPracticeTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
26.675676
111
0.640324
75dbefdc12bf3ed13ae68ed2844df5071a2a1f8f
6,545
//===----------------------------------------------------------*- swift -*-===// // // This source file is part of the Swift Argument Parser 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 // //===----------------------------------------------------------------------===// struct ArgumentDefinition { enum Update { typealias Nullary = (InputOrigin, Name?, inout ParsedValues) throws -> Void typealias Unary = (InputOrigin, Name?, String, inout ParsedValues) throws -> Void case nullary(Nullary) case unary(Unary) } typealias Initial = (InputOrigin, inout ParsedValues) throws -> Void enum Kind { case named([Name]) case positional } struct Help { var options: Options var help: ArgumentHelp? var discussion: String? var defaultValue: String? var keys: [InputKey] var allValues: [String] = [] var isComposite: Bool = false struct Options: OptionSet { var rawValue: UInt static let isOptional = Options(rawValue: 1 << 0) static let isRepeating = Options(rawValue: 1 << 1) } init(options: Options = [], help: ArgumentHelp? = nil, defaultValue: String? = nil, key: InputKey, isComposite: Bool = false) { self.options = options self.help = help self.defaultValue = defaultValue self.keys = [key] self.isComposite = isComposite } init<T: ExpressibleByArgument>(type: T.Type, options: Options = [], help: ArgumentHelp? = nil, defaultValue: String? = nil, key: InputKey) { self.options = options self.help = help self.defaultValue = defaultValue self.keys = [key] self.allValues = type.allValueStrings } } /// This folds the public `ArrayParsingStrategy` and `SingleValueParsingStrategy` /// into a single enum. enum ParsingStrategy { /// Expect the next `SplitArguments.Element` to be a value and parse it. Will fail if the next /// input is an option. case nextAsValue /// Parse the next `SplitArguments.Element.value` case scanningForValue /// Parse the next `SplitArguments.Element` as a value, regardless of its type. case unconditional /// Parse multiple `SplitArguments.Element.value` up to the next non-`.value` case upToNextOption /// Parse all remaining `SplitArguments.Element` as values, regardless of its type. case allRemainingInput } var kind: Kind var help: Help var completion: CompletionKind var parsingStrategy: ParsingStrategy var update: Update var initial: Initial var names: [Name] { switch kind { case .named(let n): return n case .positional: return [] } } var valueName: String { return help.help?.valueName ?? preferredNameForSynopsis?.valueString ?? help.keys.first?.rawValue.convertedToSnakeCase(separator: "-") ?? "value" } init( kind: Kind, help: Help, completion: CompletionKind, parsingStrategy: ParsingStrategy = .nextAsValue, update: Update, initial: @escaping Initial = { _, _ in } ) { if case (.positional, .nullary) = (kind, update) { preconditionFailure("Can't create a nullary positional argument.") } self.kind = kind self.help = help self.completion = completion self.parsingStrategy = parsingStrategy self.update = update self.initial = initial } } extension ArgumentDefinition.ParsingStrategy { init(_ other: SingleValueParsingStrategy) { switch other { case .next: self = .nextAsValue case .scanningForValue: self = .scanningForValue case .unconditional: self = .unconditional } } init(_ other: ArrayParsingStrategy) { switch other { case .singleValue: self = .scanningForValue case .unconditionalSingleValue: self = .unconditional case .upToNextOption: self = .upToNextOption case .remaining: self = .allRemainingInput } } } extension ArgumentDefinition: CustomDebugStringConvertible { var debugDescription: String { switch (kind, update) { case (.named(let names), .nullary): return names .map { $0.synopsisString } .joined(separator: ",") case (.named(let names), .unary): return names .map { $0.synopsisString } .joined(separator: ",") + " <\(valueName)>" case (.positional, _): return "<\(valueName)>" } } } extension ArgumentDefinition { var optional: ArgumentDefinition { var result = self result.help.options.insert(.isOptional) return result } var nonOptional: ArgumentDefinition { var result = self result.help.options.remove(.isOptional) return result } } extension ArgumentDefinition { var isPositional: Bool { if case .positional = kind { return true } return false } var isRepeatingPositional: Bool { isPositional && help.options.contains(.isRepeating) } var isNullary: Bool { if case .nullary = update { return true } else { return false } } var allowsJoinedValue: Bool { names.contains(where: { $0.allowsJoined }) } } extension ArgumentDefinition.Kind { static func name(key: InputKey, specification: NameSpecification) -> ArgumentDefinition.Kind { let names = specification.makeNames(key) return ArgumentDefinition.Kind.named(names) } } extension ArgumentDefinition.Update { static func appendToArray<A: ExpressibleByArgument>(forType type: A.Type, key: InputKey) -> ArgumentDefinition.Update { return ArgumentDefinition.Update.unary { (origin, name, value, values) in guard let v = A(argument: value) else { throw ParserError.unableToParseValue(origin, name, value, forKey: key) } values.update(forKey: key, inputOrigin: origin, initial: [A](), closure: { $0.append(v) }) } } } // MARK: - Help Options protocol ArgumentHelpOptionProvider { static var helpOptions: ArgumentDefinition.Help.Options { get } } extension Optional: ArgumentHelpOptionProvider { static var helpOptions: ArgumentDefinition.Help.Options { return [.isOptional] } } extension ArgumentDefinition.Help.Options { init<A>(type: A.Type) { if let t = type as? ArgumentHelpOptionProvider.Type { self = t.helpOptions } else { self = [] } } }
26.714286
144
0.645073
72d36c9debc8bfcb46e5fbe01c1a2e90cb818c9e
547
import Foundation public struct TargetReference: Equatable, Codable, ExpressibleByStringInterpolation { public var projectPath: Path? public var targetName: String public init(projectPath: Path?, target: String) { self.projectPath = projectPath targetName = target } public init(stringLiteral value: String) { self = .init(projectPath: nil, target: value) } public static func project(path: Path, target: String) -> TargetReference { .init(projectPath: path, target: target) } }
27.35
85
0.685558
d940d0e4bedfff1af26131b68b7623725e0e4009
697
// // MainViewController.swift // DYZB // // Created by buyun1 on 2017/11/6. // Copyright © 2017年 buyun1. All rights reserved. // import UIKit class MainViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() addChildVC(storyName: "Home"); addChildVC(storyName: "Live"); addChildVC(storyName: "Follow"); addChildVC(storyName: "Profile"); } private func addChildVC(storyName:String) { //1、通过storyboard获取控制器 let childVC = UIStoryboard(name: storyName, bundle: nil).instantiateInitialViewController()!; //2、将childVC作为子控制器 addChildViewController(childVC); } }
23.233333
101
0.645624
e0a021169d1574fe37ac79949f43c8e750f8757d
27,023
// Forked from: https://github.com/insidegui/MultipeerKit // Copyright (c) 2020 Guilherme Rambo // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import CommonCrypto import Foundation import MultipeerConnectivity import MultipeerConnectivity.MCPeerID import Foundation import os.log // MARK: - Public // MARK: Peer /// Represents a remote peer. public struct Peer: Hashable, Identifiable { let underlyingPeer: MCPeerID /// The unique identifier for the peer. public let id: String /// The peer's display name. public let name: String /// Discovery info provided by the peer. public let discoveryInfo: [String: String]? /// `true` if we are currently connected to this peer. public internal(set) var isConnected: Bool } extension Peer { init(peer: MCPeerID, discoveryInfo: [String: String]?) throws { let peerData = try NSKeyedArchiver.archivedData( withRootObject: peer, requiringSecureCoding: true) self.id = peerData.idHash self.underlyingPeer = peer self.name = peer.displayName self.discoveryInfo = discoveryInfo self.isConnected = false } } extension Data { fileprivate var idHash: String { var sha1 = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH)) withUnsafeBytes { _ = CC_SHA1($0.baseAddress, CC_LONG(count), &sha1) } return sha1.map({ String(format: "%02hhx", $0) }).joined() } } // MARK: MultipeerConfiguration // Configures several aspects of the multipeer communication. public struct MultipeerConfiguration { /// Defines how the multipeer connection handles newly discovered peers. /// New peers can be invited automatically, invited with a custom context and timeout, /// or not invited at all, in which case you must invite them manually. public enum Invitation { /// When `.automatic` is used, all found peers will be immediately invited to join the session. case automatic /// Use `.custom` when you want to control the invitation of new peers to your session, /// but still invite them at the time of discovery. case custom((Peer) throws -> (context: Data, timeout: TimeInterval)?) /// Use `.none` when you want to manually invite peers by calling `invite` /// in `MultipeerTransceiver`. case none } /// Configures security-related aspects of the multipeer connection. public struct Security { public typealias InvitationHandler = (Peer, Data?, @escaping (Bool) -> Void) -> Void /// An array of information that can be used to identify the peer to other nearby peers. /// The first object in this array should be a `SecIdentity` object that provides the /// local peer’s identity. /// /// The remainder of the array should contain zero or more additional SecCertificate objects /// that provide any /// intermediate certificates that nearby peers might require when verifying the local /// peer’s identity. /// These certificates should be sent in certificate chain order. /// /// Check Apple's `MCSession` docs for more information. public var identity: [Any]? /// Configure the level of encryption to be used for communications. public var encryptionPreference: MCEncryptionPreference /// A custom closure to be used when handling invitations received by remote peers. /// /// It receives the `Peer` that sent the invitation, a custom `Data` value /// that's a context that can be used to customize the invitation, /// and a closure to be called with `true` to accept the invitation or `false` to reject it. /// /// The default implementation accepts all invitations. public var invitationHandler: InvitationHandler public init( identity: [Any]?, encryptionPreference: MCEncryptionPreference, invitationHandler: @escaping InvitationHandler ) { self.identity = identity self.encryptionPreference = encryptionPreference self.invitationHandler = invitationHandler } /// The default security configuration, which has no identity, uses no encryption and /// accepts all invitations. public static let `default` = Security( identity: nil, encryptionPreference: .none, invitationHandler: { _, _, closure in closure(true) }) } /// This must be the same accross your app running on multiple devices, /// it must be a short string. /// /// Check Apple's docs on `MCNearbyServiceAdvertiser` for more info on the limitations /// for this field. public var serviceType: String /// A display name for this peer that will be shown to nearby peers. public var peerName: String /// An instance of `UserDefaults` that's used to store this peer's identity so that it /// remains stable between different sessions. If you use MultipeerKit in app extensions, /// make sure to use a shared app group if you wish to maintain a stable identity. public var defaults: UserDefaults /// The security configuration. public var security: Security /// Defines how the multipeer connection handles newly discovered peers. public var invitation: Invitation /// Creates a new configuration. /// - Parameters: /// - serviceType: This must be the same accross your app running on multiple devices, /// it must be a short string. /// Check Apple's docs on `MCNearbyServiceAdvertiser` for more info on the limitations /// for this field. /// - peerName: A display name for this peer that will be shown to nearby peers. /// - defaults: An instance of `UserDefaults` that's used to store this peer's identity /// so that it remains stable between different sessions. If you use MultipeerKit in /// app extension make sure to use a shared app group if you wish to maintain a stable identity. /// - security: The security configuration. /// - invitation: Defines how the multipeer connection handles newly discovered peers. /// New peers can be invited automatically, invited with a custom context /// or not invited at all, in which case you must invite them manually. public init( serviceType: String, peerName: String, defaults: UserDefaults, security: Security, invitation: Invitation ) { precondition(peerName.utf8.count <= 63, "peerName can't be longer than 63 bytes") self.serviceType = serviceType self.peerName = peerName self.defaults = defaults self.security = security self.invitation = invitation } /// The default configuration, uses the service type `MKSVC`, the name of the device/computer /// as the display name, `UserDefaults.standard`, the default security configuration /// and automatic invitation. public static let `default` = MultipeerConfiguration( serviceType: "MKSVC", peerName: MCPeerID.defaultDisplayName, defaults: .standard, security: .default, invitation: .automatic ) } // MARK: - MultipeerDataSource @available(tvOS 13.0, *) @available(OSX 10.15, *) @available(iOS 13.0, *) /// This class can be used to monitor nearby peers in a reactive way, /// it's especially useful for SwiftUI apps. public final class MultipeerDataSource: ObservableObject { public let transceiver: MultipeerTransceiver /// Initializes a new data source. /// - Parameter transceiver: The transceiver to be used by this data source. /// Note that the data source will set `availablePeersDidChange` on the /// transceiver, so if you wish to use that closure yourself, you /// won't be able to use the data source. public init(transceiver: MultipeerTransceiver) { self.transceiver = transceiver transceiver.availablePeersDidChange = { [weak self] peers in self?.availablePeers = peers } } /// Peers currently available for invitation, connection and data transmission. @Published public private(set) var availablePeers: [Peer] = [] } //MARK: - MultipeerTransceiver /// Handles all aspects related to the multipeer communication. public final class MultipeerTransceiver { private let log = MultipeerKit.log(for: MultipeerTransceiver.self) let connection: MultipeerProtocol /// Called on the main queue when available peers have changed (new peers discovered or peers removed). public var availablePeersDidChange: ([Peer]) -> Void = { _ in } /// All peers currently available for invitation, connection and data transmission. public var availablePeers: [Peer] = [] { didSet { guard availablePeers != oldValue else { return } DispatchQueue.main.async { self.availablePeersDidChange(self.availablePeers) } } } /// Initializes a new transceiver. /// - Parameter configuration: The configuration, uses the default configuration if none specified. public init(configuration: MultipeerConfiguration = .default) { self.connection = MultipeerConnection( modes: MultipeerConnection.Mode.allCases, configuration: configuration ) configure(connection) } init(connection: MultipeerProtocol) { self.connection = connection configure(connection) } private func configure(_ connection: MultipeerProtocol) { connection.didReceiveData = { [weak self] data, peer in self?.handleDataReceived(data, from: peer) } connection.didFindPeer = { [weak self] peer in DispatchQueue.main.async { self?.handlePeerAdded(peer) } } connection.didLosePeer = { [weak self] peer in DispatchQueue.main.async { self?.handlePeerRemoved(peer) } } connection.didConnectToPeer = { [weak self] peer in DispatchQueue.main.async { self?.handlePeerConnected(peer) } } connection.didDisconnectFromPeer = { [weak self] peer in DispatchQueue.main.async { self?.handlePeerDisconnected(peer) } } } /// Configures a new handler for a specific `Codable` type. /// - Parameters: /// - type: The `Codable` type to receive. /// - closure: Will be called whenever a payload of the specified type is received. /// - payload: The payload decoded from the remote message. /// /// MultipeerKit communicates data between peers as JSON-encoded payloads which originate with /// `Codable` entities. You register a closure to handle each specific type of entity, /// and this closure is automatically called by the framework when a remote peer sends /// a message containing an entity that decodes to the specified type. public func receive<T: Codable>(_ type: T.Type, using closure: @escaping (_ payload: T) -> Void) { MultipeerMessage.register(type, for: String(describing: type), closure: closure) } /// Resumes the transceiver, allowing this peer to be discovered and to discover remote peers. public func resume() { connection.resume() } /// Stops the transceiver, preventing this peer from discovering and being discovered. public func stop() { connection.stop() } /// Sends a message to all connected peers. /// - Parameter payload: The payload to be sent. public func broadcast<T: Encodable>(_ payload: T) { MultipeerMessage.register(T.self, for: String(describing: T.self)) do { let message = MultipeerMessage(type: String(describing: T.self), payload: payload) let data = try JSONEncoder().encode(message) try connection.broadcast(data) } catch { os_log( "Failed to send payload %@: %{public}@", log: self.log, type: .error, String(describing: payload), String(describing: error)) } } /// Sends a message to a specific peer. /// - Parameters: /// - payload: The payload to be sent. /// - peers: An array of peers to send the message to. public func send<T: Encodable>(_ payload: T, to peers: [Peer]) { MultipeerMessage.register(T.self, for: String(describing: T.self)) do { let message = MultipeerMessage(type: String(describing: T.self), payload: payload) let data = try JSONEncoder().encode(message) try connection.send(data, to: peers) } catch { os_log( "Failed to send payload %@: %{public}@", log: self.log, type: .error, String(describing: payload), String(describing: error)) } } private func handleDataReceived(_ data: Data, from peer: PeerName) { os_log("%{public}@", log: log, type: .debug, #function) do { let message = try JSONDecoder().decode(MultipeerMessage.self, from: data) os_log("Received message %@", log: self.log, type: .debug, String(describing: message)) } catch { os_log( "Failed to decode message: %{public}@", log: self.log, type: .error, String(describing: error)) } } /// Manually invite a peer for communicating. /// - Parameters: /// - peer: The peer to be invited. /// - context: Custom data to be sent alongside the invitation. /// - timeout: How long to wait for the remote peer to accept the invitation. /// - completion: Called when the invitation succeeds or fails. /// /// You can call this method to manually invite a peer for communicating if you set the /// `invitation` parameter to `.none` in the transceiver's `configuration`. /// /// - warning: If the invitation parameter is not set to `.none`, you shouldn't call this method, /// since the transceiver does the inviting automatically. public func invite( _ peer: Peer, with context: Data?, timeout: TimeInterval, completion: InvitationCompletionHandler? ) { connection.invite(peer, with: context, timeout: timeout, completion: completion) } private func handlePeerAdded(_ peer: Peer) { guard !availablePeers.contains(peer) else { return } availablePeers.append(peer) } private func handlePeerRemoved(_ peer: Peer) { guard let idx = availablePeers.firstIndex(where: { $0.underlyingPeer == peer.underlyingPeer }) else { return } availablePeers.remove(at: idx) } private func handlePeerConnected(_ peer: Peer) { setConnected(true, on: peer) } private func handlePeerDisconnected(_ peer: Peer) { setConnected(false, on: peer) } private func setConnected(_ connected: Bool, on peer: Peer) { guard let idx = availablePeers.firstIndex(where: { $0.underlyingPeer == peer.underlyingPeer }) else { return } var mutablePeer = availablePeers[idx] mutablePeer.isConnected = connected availablePeers[idx] = mutablePeer } } // MARK: - Internal // MARK: MCPeerID+Me extension MCPeerID { private static let defaultsKey = "_multipeerKit.mePeerID" private static func fetchExisting(with config: MultipeerConfiguration) -> MCPeerID? { guard let data = config.defaults.data(forKey: Self.defaultsKey) else { return nil } do { let peer = try NSKeyedUnarchiver.unarchivedObject(ofClass: MCPeerID.self, from: data) guard peer?.displayName == config.peerName else { return nil } return peer } catch { return nil } } static func fetchOrCreate(with config: MultipeerConfiguration) -> MCPeerID { fetchExisting(with: config) ?? MCPeerID(displayName: config.peerName) } } #if os(iOS) || os(tvOS) import UIKit extension MCPeerID { public static var defaultDisplayName: String { UIDevice.current.name } } #else import Cocoa extension MCPeerID { public static var defaultDisplayName: String { Host.current().localizedName ?? "Unknown Mac" } } #endif // MARK: MultipeerMessage struct MultipeerMessage: Codable { let type: String let payload: Any? init(type: String, payload: Any) { self.type = type self.payload = payload } enum CodingKeys: String, CodingKey { case type case payload } private typealias MessageDecoder = (KeyedDecodingContainer<CodingKeys>) throws -> Any private typealias MessageEncoder = (Any, inout KeyedEncodingContainer<CodingKeys>) throws -> Void private static var decoders: [String: MessageDecoder] = [:] private static var encoders: [String: MessageEncoder] = [:] static func register<T: Codable>( _ type: T.Type, for typeName: String, closure: @escaping (T) -> Void ) { decoders[typeName] = { container in let payload = try container.decode(T.self, forKey: .payload) DispatchQueue.main.async { closure(payload) } return payload } register(T.self, for: typeName) } static func register<T: Encodable>(_ type: T.Type, for typeName: String) { encoders[typeName] = { payload, container in try container.encode(payload as! T, forKey: .payload) } } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) type = try container.decode(String.self, forKey: .type) if let decode = Self.decoders[type] { payload = try decode(container) } else { payload = nil } } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(type, forKey: .type) if let payload = self.payload { guard let encode = Self.encoders[type] else { let context = EncodingError.Context( codingPath: [], debugDescription: "Invalid payload type: \(type).") throw EncodingError.invalidValue(self, context) } try encode(payload, &container) } else { try container.encodeNil(forKey: .payload) } } } // MARK: MockMultipeerConnection final class MockMultipeerConnection: MultipeerProtocol { var didReceiveData: ((Data, PeerName) -> Void)? var didFindPeer: ((Peer) -> Void)? var didLosePeer: ((Peer) -> Void)? var didConnectToPeer: ((Peer) -> Void)? var didDisconnectFromPeer: ((Peer) -> Void)? var isRunning = false func resume() { isRunning = true } func stop() { isRunning = false } func broadcast(_ data: Data) throws { didReceiveData?(data, "MockPeer") } func send(_ data: Data, to peers: [Peer]) throws { } func invite( _ peer: Peer, with context: Data?, timeout: TimeInterval, completion: InvitationCompletionHandler?) { } } //MARK: MultipeerConnection public typealias InvitationCompletionHandler = (_ result: Result<Peer, Error>) -> Void public struct MultipeerError: LocalizedError { public var localizedDescription: String } final class MultipeerConnection: NSObject, MultipeerProtocol { enum Mode: Int, CaseIterable { case receiver case transmitter } private let log = MultipeerKit.log(for: MultipeerConnection.self) let modes: [Mode] let configuration: MultipeerConfiguration let me: MCPeerID init(modes: [Mode] = Mode.allCases, configuration: MultipeerConfiguration = .default) { self.modes = modes self.configuration = configuration self.me = MCPeerID.fetchOrCreate(with: configuration) } var didReceiveData: ((Data, PeerName) -> Void)? var didFindPeer: ((Peer) -> Void)? var didLosePeer: ((Peer) -> Void)? var didConnectToPeer: ((Peer) -> Void)? var didDisconnectFromPeer: ((Peer) -> Void)? private var discoveredPeers: [MCPeerID: Peer] = [:] func resume() { os_log("%{public}@", log: log, type: .debug, #function) if modes.contains(.receiver) { advertiser.startAdvertisingPeer() } if modes.contains(.transmitter) { browser.startBrowsingForPeers() } } func stop() { os_log("%{public}@", log: log, type: .debug, #function) if modes.contains(.receiver) { advertiser.stopAdvertisingPeer() } if modes.contains(.transmitter) { browser.stopBrowsingForPeers() } } private lazy var session: MCSession = { let s = MCSession( peer: me, securityIdentity: configuration.security.identity, encryptionPreference: configuration.security.encryptionPreference ) s.delegate = self return s }() private lazy var browser: MCNearbyServiceBrowser = { let b = MCNearbyServiceBrowser(peer: me, serviceType: configuration.serviceType) b.delegate = self return b }() private lazy var advertiser: MCNearbyServiceAdvertiser = { let a = MCNearbyServiceAdvertiser( peer: me, discoveryInfo: nil, serviceType: configuration.serviceType) a.delegate = self return a }() func broadcast(_ data: Data) throws { guard !session.connectedPeers.isEmpty else { os_log("Not broadcasting message: no connected peers", log: self.log, type: .error) return } try session.send(data, toPeers: session.connectedPeers, with: .reliable) } func send(_ data: Data, to peers: [Peer]) throws { let ids = peers.map { $0.underlyingPeer } try session.send(data, toPeers: ids, with: .reliable) } private var invitationCompletionHandlers: [MCPeerID: InvitationCompletionHandler] = [:] func invite( _ peer: Peer, with context: Data?, timeout: TimeInterval, completion: InvitationCompletionHandler? ) { invitationCompletionHandlers[peer.underlyingPeer] = completion browser.invitePeer(peer.underlyingPeer, to: session, withContext: context, timeout: timeout) } } // MARK: - Session delegate extension MultipeerConnection: MCSessionDelegate { func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) { os_log("%{public}@", log: log, type: .debug, #function) guard let peer = discoveredPeers[peerID] else { return } let handler = invitationCompletionHandlers[peerID] DispatchQueue.main.async { switch state { case .connected: handler?(.success(peer)) self.invitationCompletionHandlers[peerID] = nil self.didConnectToPeer?(peer) case .notConnected: handler?(.failure(MultipeerError(localizedDescription: "Failed to connect to peer."))) self.invitationCompletionHandlers[peerID] = nil self.didDisconnectFromPeer?(peer) case .connecting: break @unknown default: break } } } func session( _ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID ) { os_log("%{public}@", log: log, type: .debug, #function) didReceiveData?(data, peerID.displayName) } func session( _ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID ) { os_log("%{public}@", log: log, type: .debug, #function) } func session( _ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress ) { os_log("%{public}@", log: log, type: .debug, #function) } func session( _ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error? ) { os_log("%{public}@", log: log, type: .debug, #function) } } // MARK: - Browser delegate extension MultipeerConnection: MCNearbyServiceBrowserDelegate { func browser( _ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String: String]? ) { os_log("%{public}@", log: log, type: .debug, #function) do { let peer = try Peer(peer: peerID, discoveryInfo: info) discoveredPeers[peerID] = peer didFindPeer?(peer) switch configuration.invitation { case .automatic: browser.invitePeer(peerID, to: session, withContext: nil, timeout: 10.0) case .custom(let inviter): guard let invite = try inviter(peer) else { os_log( "Custom invite not sent for peer %@", log: self.log, type: .error, String(describing: peer)) return } browser.invitePeer( peerID, to: session, withContext: invite.context, timeout: invite.timeout ) case .none: os_log("Auto-invite disabled", log: self.log, type: .debug) return } } catch { os_log( "Failed to initialize peer based on peer ID %@: %{public}@", log: self.log, type: .error, String(describing: peerID), String(describing: error)) } } func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) { os_log("%{public}@", log: log, type: .debug, #function) guard let peer = discoveredPeers[peerID] else { return } didLosePeer?(peer) discoveredPeers[peerID] = nil } } // MARK: - Advertiser delegate extension MultipeerConnection: MCNearbyServiceAdvertiserDelegate { func advertiser( _ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: Data?, invitationHandler: @escaping (Bool, MCSession?) -> Void ) { os_log("%{public}@", log: log, type: .debug, #function) guard let peer = discoveredPeers[peerID] else { return } configuration.security.invitationHandler( peer, context, { [weak self] decision in guard let self = self else { return } invitationHandler(decision, decision ? self.session : nil) }) } } // MARK: - Advertiser delegate struct MultipeerKit { static let subsystemName = "swift.package.multipeer" static func log(for type: AnyClass) -> OSLog { OSLog(subsystem: subsystemName, category: String(describing: type)) } } // MARK: - MultipeerProtocol typealias PeerName = String protocol MultipeerProtocol: AnyObject { var didReceiveData: ((Data, PeerName) -> Void)? { get set } var didFindPeer: ((Peer) -> Void)? { get set } var didLosePeer: ((Peer) -> Void)? { get set } var didConnectToPeer: ((Peer) -> Void)? { get set } var didDisconnectFromPeer: ((Peer) -> Void)? { get set } func resume() func stop() func invite( _ peer: Peer, with context: Data?, timeout: TimeInterval, completion: InvitationCompletionHandler?) func broadcast(_ data: Data) throws func send(_ data: Data, to peers: [Peer]) throws }
34.076923
105
0.692928
16f5cf880d504c794260e83e04d7a80ff93f4607
495
// // PublishRelay+Signal.swift // RxCocoa // // Created by Krunoslav Zaher on 12/28/15. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // import RxSwift import RxRelay extension PublishRelay { /// Converts `PublishRelay` to `Signal`. /// /// - returns: Observable sequence. public func asSignal() -> Signal<Element> { let source = self.asObservable() .observeOn(SignalSharingStrategy.scheduler) return SharedSequence(source) } }
22.5
58
0.658586
edf2058ba6daa21f0dea54c1117a3e8735f0cb29
230
// // ACNAdLoadProtocol.swift // ACNSDK // // Created by chenchao on 2019/1/3. // Copyright © 2019 tataufo. All rights reserved. // @objc public protocol ACNAdLoadProtocol { func loadRequest(requset: ACNAdRequest) }
17.692308
50
0.691304
2228323517929d38dfa0d5c1e22c0ff434073d9c
2,342
// // AppDelegate.swift // TestApp1 // // Created by igork on 11/23/17. // Copyright © 2017 Igor Kotkovets. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { print("opened") return true; } }
46.84
285
0.74509
69d997006fddf6a5e775d88ca9862006103e130f
695
// swift-tools-version:4.0 import PackageDescription let package = Package( name: "VaporApp", products: [ .library(name: "VaporApp", targets: ["App"]), ], dependencies: [ // 💧 A server-side Swift web framework. .package(url: "https://github.com/vapor/vapor.git", from: "3.0.0"), // 🔵 Swift ORM (queries, models, relations, etc) built on SQLite 3. .package(url: "https://github.com/vapor/fluent-sqlite.git", from: "3.0.0") ], targets: [ .target(name: "App", dependencies: ["FluentSQLite", "Vapor"]), .target(name: "Run", dependencies: ["App"]), .testTarget(name: "AppTests", dependencies: ["App"]) ] )
31.590909
82
0.582734
b90130675df183fb8f7724cd79241c9c2441009f
66
// // File.swift // AvoidSoftinputExample // import Foundation
9.428571
25
0.69697
e8ee272988360e24cc8e69f889eef2cb21e51f09
2,721
// // AppDelegate.swift // ReviewTime // // Created by Nathan Hegedus on 25/05/15. // Copyright (c) 2015 Nathan Hegedus. All rights reserved. // import UIKit import XCGLogger let log = XCGLogger.defaultInstance() @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. Common.configureAppearance() Common.configureFabric() Common.configureGoogleAnalytics() Common.saveCurrentVersion() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { if url.scheme == "RTUrlType" { NSNotificationCenter.defaultCenter().postNotificationName(url.host!, object: nil) return true } return false } }
41.861538
285
0.727306
759961fd2aed801a1c1a7215005fe743bfbbd4a2
464
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. //___COPYRIGHT___ // import Foundation import Viperit final class ___FILEBASENAMEASIDENTIFIER___Router: Router { } // MARK: - VIPER COMPONENTS API (Auto-generated code) private extension ___FILEBASENAMEASIDENTIFIER___Router { var presenter: ___FILEBASENAMEASIDENTIFIER___Presenter { return _presenter as! ___FILEBASENAMEASIDENTIFIER___Presenter } }
22.095238
69
0.786638
4600b8b27c57e676bf30fe98825c4e0b8b7a78ca
3,466
// // APIClientServiceTests.swift // // Copyright (c) 2021 Tiago Henriques // // 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 XCTest @testable import Carrots class MockClient: APIClientService { var result: Result<Response, APIClientError>? func run(resource: Resource, completion: @escaping (Result<Response, APIClientError>) -> Void) { result.map(completion) } } final class APIClientServiceTests: XCTestCase { func testRunWithSuccess() throws { let expectedUsers = [User(id: 1, name: "Tiago")] let encodedData = try JSONEncoder().encode(expectedUsers) let response = Response(request: UsersAPI.users.request(with: API.baseUsersURL), data: encodedData, httpUrlResponse: nil) let mockClient = MockClient() mockClient.result = .success(response) var result: Result<Response, APIClientError>? mockClient.run(resource: UsersAPI.users) { result = $0 } XCTAssertEqual(response, result?.value) let decodeResponse = try result?.value?.decode(to: [User].self) XCTAssertEqual(decodeResponse, expectedUsers) } func testRunWithFailure() throws { let mockClient = MockClient() mockClient.result = .failure(APIClientError.noData) var result: Result<Response, APIClientError>? mockClient.run(resource: UsersAPI.users) { result = $0 } XCTAssertNotNil(result?.error) XCTAssertTrue(result?.error?.errorDescription == "No data.") } func testRunBefore() { let sut = APIClient(baseURL: API.baseUsersURL) sut.run(resource: UsersAPI.users) { _ in } let lastRequest = sut.session.tasks.last?.currentRequest XCTAssertEqual(lastRequest?.url, UsersAPI.users.request(with: API.baseUsersURL).url) } } extension URLSession { var tasks: [URLSessionTask] { var tasks: [URLSessionTask] = [] let group = DispatchGroup() group.enter() getAllTasks { tasks = $0 group.leave() } group.wait() return tasks } } extension Response: Equatable { public static func == (lhs: Response, rhs: Response) -> Bool { return lhs.data == rhs.data && lhs.request == rhs.request && lhs.httpUrlResponse == rhs.httpUrlResponse } }
34.316832
129
0.664166
7569756e3f38451b423679b279240750094589a0
10,597
import XCTest @testable import ClickHouseNIO import NIO import Logging class TestConnection { let logger: Logger let connection: ClickHouseConnection let eventLoopGroup: EventLoopGroup init() { var logger = ClickHouseLogging.base logger.logLevel = .trace self.logger = logger eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1) let ip = ProcessInfo.processInfo.environment["CLICKHOUSE_SERVER"] ?? "172.25.101.30" let user = ProcessInfo.processInfo.environment["CLICKHOUSE_USER"] ?? "default" let password = ProcessInfo.processInfo.environment["CLICKHOUSE_PASSWORD"] ?? "admin" logger.info("Connecting to ClickHouse server at \(ip)") // openssl req -subj "/CN=my.host.name" -days 365 -nodes -new -x509 -keyout /etc/clickhouse-server/server.key -out /etc/clickhouse-server/server.crt // openssl dhparam -out /etc/clickhouse-server/dhparam.pem 1024 // NOTE use 4096 in prod // chown -R clickhouse:clickhouse /etc/clickhouse-server/ // Port 9440 = secure tcp, 9000 regular tcp let socket = try! SocketAddress(ipAddress: ip, port: 9440) let tls = TLSConfiguration.forClient(certificateVerification: .none) let config = ClickHouseConfiguration( serverAddresses: socket, user: user, password: password, connectTimeout: .seconds(10), readTimeout: .seconds(3), queryTimeout: .seconds(5), tlsConfiguration: tls) connection = try! ClickHouseConnection.connect(configuration: config, on: eventLoopGroup.next()).wait() } deinit { try! eventLoopGroup.syncShutdownGracefully() } } final class ClickHouseNIOTests: XCTestCase { var conn = TestConnection() func testShowDatabases() { XCTAssertNoThrow(try conn.connection.query(sql: "SHOW DATABASES;").map{res in print(res) }.wait()) } func testPing() { try! conn.connection.ping().wait() } func testSyntaxError() { // Test correct throw on syntax error // If invalid SQL is send, and exception is thrown, but the connection is supposed to stay active XCTAssertThrowsError(try conn.connection.command(sql: "something wrong").wait(), "awdawf") { e in guard case let error as ExceptionMessage = e else { XCTFail() return } XCTAssertEqual(error.code, 1040187392) XCTAssertEqual(error.name, "DB::Exception") XCTAssertTrue(error.displayText.starts(with: "DB::Exception: Syntax error: failed at position 1")) } XCTAssertNoThrow(try conn.connection.ping().wait()) XCTAssertFalse(conn.connection.isClosed) XCTAssertTrue(conn.connection.channel.isActive) } /// Test correct string truncation with multibyte character func testFixedString() { try! conn.connection.command(sql: "DROP TABLE IF EXISTS test").wait() let fixedLength = 7 let sql = """ CREATE TABLE test ( id String, string FixedString(\(fixedLength)) ) ENGINE = MergeTree() PRIMARY KEY id ORDER BY id """ try! conn.connection.command(sql: sql).wait() let data = [ ClickHouseColumn("id", ["1","🎅☃🧪","234"]), ClickHouseColumn("string", ["🎅☃🧪","a","awfawfawf"]) ] try! conn.connection.insert(into: "test", data: data).wait() try! conn.connection.query(sql: "SELECT * FROM test").map { res in print(res) guard let str = res.columns.first(where: {$0.name == "string"})!.values as? [String] else { fatalError("Column `string`, was not a String array") } XCTAssertEqual(str, ["🎅☃", "awfawfa", "a"]) guard let id = res.columns.first(where: {$0.name == "id"})!.values as? [String] else { fatalError("Column `id`, was not a String array") } XCTAssertEqual(id, ["1", "234", "🎅☃🧪"]) }.wait() } func testCreateTable() { try! conn.connection.command(sql: "DROP TABLE IF EXISTS test").wait() let sql = """ CREATE TABLE test ( stationid Int32, timestamp Int64, value Float32, varstring String, fixstring FixedString(2) ) ENGINE = MergeTree() PRIMARY KEY stationid ORDER BY stationid """ try! conn.connection.command(sql: sql).wait() let count = 110 let data = [ ClickHouseColumn("stationid", (0..<count).map{Int32($0)}), ClickHouseColumn("timestamp", (0..<count).map{Int64($0)}), ClickHouseColumn("value", (0..<count).map{Float($0)}), ClickHouseColumn("varstring", (0..<count).map{"\($0)"}), ClickHouseColumn("fixstring", (0..<count).map{"\($0)"}) ] try! conn.connection.insert(into: "test", data: data).wait() try! conn.connection.query(sql: "SELECT * FROM test").map { res in //print(res) guard let str = res.columns.first(where: {$0.name == "fixstring"})!.values as? [String] else { fatalError() } XCTAssertEqual((0..<count).map{String("\($0)".prefix(2))}, str) }.wait() } func testTimeout() { XCTAssertThrowsError(try conn.connection.command(sql: "SELECT sleep(3)", timeout: .milliseconds(1500)).wait()) { error in guard case ClickHouseError.queryTimeout = error else { XCTFail() return } } } func testUUID() { try! conn.connection.command(sql: "DROP TABLE IF EXISTS test").wait() let sql = """ CREATE TABLE test ( id Int32, uuid UUID ) ENGINE = MergeTree() PRIMARY KEY id ORDER BY id """ try! conn.connection.command(sql: sql).wait() let uuidStrings : [String] = ["ba4a9cd7-c69c-9fe8-5335-7631f448b597", "ad4f8401-88ff-ca3d-0443-e0163288f691", "5544beae-2370-c5e8-b8b6-c6c46156d28d"] let uuids = uuidStrings.map { UUID(uuidString: $0)!} let ids : [Int32] = [1, 2, 3] print(uuids) let data = [ ClickHouseColumn("id", ids), ClickHouseColumn("uuid", uuids) ] try! conn.connection.insert(into: "test", data: data).wait() try! conn.connection.query(sql: "SELECT id, uuid, toString(uuid) as uuidString FROM test").map { res in print(res) guard let datatype = res.columns.first(where: {$0.name == "uuidString"})!.values as? [String] else { fatalError("Column `uuidString`, was not a String array") } XCTAssertEqual(datatype, uuidStrings ) guard let id = res.columns.first(where: {$0.name == "id"})!.values as? [Int32] else { fatalError("Column `id`, was not an Int32 array") } XCTAssertEqual(id, [1, 2, 3]) }.wait() } func testCommandForInsertsFromSelectWorks() { try! conn.connection.command(sql: "DROP TABLE IF EXISTS test").wait() let sql = """ CREATE TABLE test ( stationid Int32, timestamp Int64, value Float32, varstring String, fixstring FixedString(2), nullable Nullable(UInt32) ) ENGINE = MergeTree() PRIMARY KEY stationid ORDER BY stationid """ try! conn.connection.command(sql: sql).wait() let count = 110 let data = [ ClickHouseColumn("stationid", (0..<count).map{Int32($0)}), ClickHouseColumn("timestamp", (0..<count).map{Int64($0)}), ClickHouseColumn("value", (0..<count).map{Float($0)}), ClickHouseColumn("varstring", (0..<count).map{"\($0)"}), ClickHouseColumn("fixstring", (0..<count).map{"\($0)"}), ClickHouseColumn("nullable", (0..<count).map{ $0 < 0 ? nil : UInt32($0)}) ] try! conn.connection.insert(into: "test", data: data).wait() // insert again, but this time via a select from the database try! conn.connection.command(sql: "Insert into test Select * from test").wait() } func testNullable() { try! conn.connection.command(sql: "DROP TABLE IF EXISTS test").wait() let sql = """ CREATE TABLE test ( id Int32, nullable Nullable(UInt32), str Nullable(String) ) ENGINE = MergeTree() PRIMARY KEY id ORDER BY id """ try! conn.connection.command(sql: sql).wait() let data = [ ClickHouseColumn("id", [Int32(1),2,3,3,4,5,6,7,8,9]), ClickHouseColumn("nullable", [nil,nil,UInt32(1),3,4,5,6,7,8,8]), ClickHouseColumn("str", [nil,nil,"1","3","4","5","6","7","8","8"]) ] try! conn.connection.insert(into: "test", data: data).wait() print("send complete") try! conn.connection.query(sql: "SELECT nullable.null FROM test").map { res in //print(res) guard let null = res.columns[0].values as? [UInt8?] else { fatalError("Column `nullable`, was not a Nullable UInt32 array") } XCTAssertEqual(null, [1,1,0,0,0,0,0,0,0,0]) }.wait() try! conn.connection.query(sql: "SELECT nullable, str FROM test").map { res in //print(res) XCTAssertEqual(res.columns.count, 2) XCTAssertEqual(res.columns[0].name, "nullable") guard let id = res.columns[0].values as? [UInt32?] else { fatalError("Column `nullable`, was not a Nullable UInt32 array") } XCTAssertEqual(id, [nil,nil,UInt32(1),3,4,5,6,7,8,8]) XCTAssertEqual(res.columns[1].name, "str") guard let str = res.columns[1].values as? [String?] else { fatalError("Column `nullable`, was not a Nullable UInt32 array") } XCTAssertEqual(str, [nil,nil,"1","3","4","5","6","7","8","8"]) }.wait() } }
39.394052
174
0.550439
4a27f1cfb958e5f2afeafd90b488f6a9256284f5
14,546
// // NotificationCategoryConfigurator.swift // HomeAssistant // // Created by Robert Trencheny on 9/28/18. // Copyright © 2018 Robbie Trencheny. All rights reserved. // import Foundation import UIKit import Eureka import UserNotifications import RealmSwift import Shared // swiftlint:disable type_body_length class NotificationCategoryConfigurator: FormViewController, TypedRowControllerType { var row: RowOf<ButtonRow>! /// A closure to be called when the controller disappears. public var onDismissCallback: ((UIViewController) -> Void)? var category: NotificationCategory = NotificationCategory() var newCategory: Bool = true var shouldSave: Bool = false private var maxActionsForCategory = 10 private var defaultMultivalueOptions: MultivaluedOptions = [.Reorder, .Insert, .Delete] private var addButtonRow: ButtonRow = ButtonRow() private let realm = Current.realm() convenience init(category: NotificationCategory?) { self.init() if #available(iOS 13, *) { self.isModalInPresentation = true } if let category = category { self.category = category if self.category.isServerControlled { defaultMultivalueOptions = [] } else if self.category.Actions.count >= maxActionsForCategory { defaultMultivalueOptions = [.Reorder, .Delete] } self.newCategory = false } } // swiftlint:disable:next cyclomatic_complexity function_body_length override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if !category.isServerControlled { let cancelSelector = #selector(NotificationCategoryConfigurator.cancel) self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: cancelSelector) let saveSelector = #selector(NotificationCategoryConfigurator.save) self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: saveSelector) } let infoBarButtonItem = Constants.helpBarButtonItem infoBarButtonItem.action = #selector(getInfoAction) infoBarButtonItem.target = self let previewButton = UIBarButtonItem( image: MaterialDesignIcons.eyeIcon.image(ofSize: CGSize(width: 25, height: 25), color: .black), style: .plain, target: self, action: #selector(NotificationCategoryConfigurator.preview) ) let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil) self.setToolbarItems([infoBarButtonItem, flexibleSpace, previewButton], animated: false) self.navigationController?.setToolbarHidden(false, animated: false) self.title = L10n.NotificationsConfigurator.Category.NavigationBar.title if newCategory == false { self.title = category.Name } TextRow.defaultCellUpdate = { cell, row in if !row.isValid { cell.textLabel?.textColor = .red } } TextAreaRow.defaultCellUpdate = { cell, row in if !row.isValid { cell.placeholderLabel?.textColor = .red } } NotificationIdentifierRow.defaultCellUpdate = { cell, row in if !row.isValid { cell.textLabel?.textColor = .red } } let settingsFooter: String? if category.isServerControlled { settingsFooter = nil } else if newCategory { settingsFooter = L10n.NotificationsConfigurator.Settings.footer } else { settingsFooter = L10n.NotificationsConfigurator.Settings.Footer.idSet } self.form +++ Section(header: L10n.NotificationsConfigurator.Settings.header, footer: settingsFooter) <<< TextRow { $0.tag = "name" $0.title = L10n.NotificationsConfigurator.Category.Rows.Name.title $0.add(rule: RuleRequired()) if self.category.isServerControlled { $0.disabled = true } if !newCategory { $0.value = self.category.Name } }.onChange { row in // swiftlint:disable:next force_try try! self.realm.write { if let value = row.value { self.category.Name = value } } } <<< NotificationIdentifierRow { $0.tag = "identifier" $0.title = L10n.NotificationsConfigurator.identifier $0.uppercaseOnly = false if !newCategory { $0.value = self.category.Identifier $0.disabled = true } }.onChange { row in // swiftlint:disable:next force_try try! self.realm.write { if let value = row.value { self.category.Identifier = value } } } +++ Section( header: L10n.NotificationsConfigurator.Category.Rows.HiddenPreviewPlaceholder.header, footer: L10n.NotificationsConfigurator.Category.Rows.HiddenPreviewPlaceholder.footer ) { if category.isServerControlled { $0.hidden = true } } <<< TextAreaRow { $0.tag = "hiddenPreviewsBodyPlaceholder" $0.placeholder = L10n.NotificationsConfigurator.Category.Rows.HiddenPreviewPlaceholder.default if !newCategory && self.category.HiddenPreviewsBodyPlaceholder != "" { $0.value = self.category.HiddenPreviewsBodyPlaceholder } else { $0.value = L10n.NotificationsConfigurator.Category.Rows.HiddenPreviewPlaceholder.default } }.onChange { row in // swiftlint:disable:next force_try try! self.realm.write { if let value = row.value { self.category.HiddenPreviewsBodyPlaceholder = value } } } self.form +++ Section( header: L10n.NotificationsConfigurator.Category.Rows.CategorySummary.header, footer: L10n.NotificationsConfigurator.Category.Rows.CategorySummary.footer ) { if category.isServerControlled { $0.hidden = true } } <<< TextAreaRow { $0.tag = "categorySummaryFormat" if !newCategory && self.category.CategorySummaryFormat != "" { $0.value = self.category.CategorySummaryFormat } else { $0.value = L10n.NotificationsConfigurator.Category.Rows.CategorySummary.default } }.onChange { row in // swiftlint:disable:next force_try try! self.realm.write { if let value = row.value { self.category.CategorySummaryFormat = value } } } self.form +++ MultivaluedSection( multivaluedOptions: defaultMultivalueOptions, header: L10n.NotificationsConfigurator.Category.Rows.Actions.header, footer: L10n.NotificationsConfigurator.Category.Rows.Actions.footer ) { section in if category.isServerControlled { section.footer = nil } section.multivaluedRowToInsertAt = { index in if index >= self.maxActionsForCategory - 1 { section.multivaluedOptions = [.Reorder, .Delete] self.addButtonRow.hidden = true DispatchQueue.main.async { // I'm not sure why this is necessary self.addButtonRow.evaluateHidden() } } return self.getActionRow(nil) } section.addButtonProvider = { _ in self.addButtonRow = ButtonRow { $0.title = L10n.addButtonLabel $0.cellStyle = .value1 }.cellUpdate { cell, _ in cell.textLabel?.textAlignment = .left } return self.addButtonRow } for action in self.category.Actions { section <<< self.getActionRow(action) } } form +++ YamlSection( tag: "exampleServiceCall", header: L10n.NotificationsConfigurator.Category.ExampleCall.title, yamlGetter: { [category] in category.exampleServiceCall }, present: { [weak self] controller in self?.present(controller, animated: true, completion: nil) } ) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func rowsHaveBeenRemoved(_ rows: [BaseRow], at indexes: [IndexPath]) { super.rowsHaveBeenRemoved(rows, at: indexes) if let index = indexes.first?.section, let section = form.allSections[index] as? MultivaluedSection { let deletedIDs = rows.compactMap { $0.tag } // swiftlint:disable:next force_try try! self.realm.write { // if the category isn't persisted yet, we need to remove the actions manually category.Actions.remove( atOffsets: category.Actions .enumerated() .reduce(into: IndexSet()) { indexSet, val in if deletedIDs.contains(val.element.Identifier) { indexSet.insert(val.offset) } } ) self.realm.delete(realm.objects(NotificationAction.self).filter("Identifier IN %@", deletedIDs)) } if section.count < maxActionsForCategory { section.multivaluedOptions = self.defaultMultivalueOptions self.addButtonRow.hidden = false self.addButtonRow.evaluateHidden() } self.updatePreview() } } private func updatePreview() { if let section = form.sectionBy(tag: "exampleServiceCall") as? YamlSection { DispatchQueue.main.async { section.update() } } } override func valueHasBeenChanged(for row: BaseRow, oldValue: Any?, newValue: Any?) { super.valueHasBeenChanged(for: row, oldValue: oldValue, newValue: newValue) if row.section?.tag != "exampleServiceCall" { updatePreview() } } func getActionRow(_ existingAction: NotificationAction?) -> ButtonRowWithPresent<NotificationActionConfigurator> { var action = existingAction var identifier = "new_action_"+UUID().uuidString var title = L10n.NotificationsConfigurator.NewAction.title if let action = action { identifier = action.Identifier title = action.Title } return ButtonRowWithPresent<NotificationActionConfigurator> { row in row.tag = identifier row.title = title row.presentationMode = PresentationMode.show(controllerProvider: ControllerProvider.callback { [category] in return NotificationActionConfigurator(category: category, action: action) }, onDismiss: { vc in vc.navigationController?.popViewController(animated: true) if let vc = vc as? NotificationActionConfigurator { // if the user goes to re-edit the action before saving the category, we want to show the same one action = vc.action row.tag = vc.action.Identifier vc.row.title = vc.action.Title vc.row.updateCell() Current.Log.verbose("action \(vc.action)") // swiftlint:disable:next force_try try! self.realm.write { // only add into realm if the category is also persisted self.category.realm?.add(vc.action, update: .all) if self.category.Actions.contains(vc.action) == false { self.category.Actions.append(vc.action) } } self.updatePreview() } }) } } @objc func getInfoAction(_ sender: Any) { openURLInBrowser( URL(string: "https://companion.home-assistant.io/app/ios/actionable-notifications")!, self ) } @objc func save(_ sender: Any) { Current.Log.verbose("Go back hit, check for validation") Current.Log.verbose("Validate result \(self.form.validate())") if self.form.validate().count == 0 { Current.Log.verbose("Category form is valid, calling dismiss callback!") self.shouldSave = true onDismissCallback?(self) } } @objc func cancel(_ sender: Any) { Current.Log.verbose("Cancel hit, calling dismiss") self.shouldSave = false onDismissCallback?(self) } @objc func preview(_ sender: Any) { Current.Log.verbose("Preview hit") let content = UNMutableNotificationContent() content.title = L10n.NotificationsConfigurator.Category.PreviewNotification.title content.body = L10n.NotificationsConfigurator.Category.PreviewNotification.body(self.category.Name) content.sound = .default content.categoryIdentifier = self.category.Identifier content.userInfo = ["preview": true] UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: self.category.Identifier, content: content, trigger: nil)) } }
36.274314
120
0.568197
7afce8c3c0e8066698e326b2972e2ed1155845ab
5,845
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Cocoa import MaterialIcons struct TabPosition: OptionSet { static let first = TabPosition(rawValue: 1 << 0) static let last = TabPosition(rawValue: 1 << 1) let rawValue: Int } class Tab<Rep: TabRepresentative>: NSView { var title: String { self.tabRepresentative.title } var tabRepresentative: Rep { willSet { if self.isSelected == newValue.isSelected { return } self.adjustToSelectionChange(newValue.isSelected) } didSet { if self.titleView.stringValue == self.title { return } self.titleView.stringValue = self.title self.adjustWidth() } } init(withTabRepresentative tabRepresentative: Rep, in tabBar: TabBar<Rep>) { self.tabBar = tabBar self.tabRepresentative = tabRepresentative super.init(frame: .zero) self.configureForAutoLayout() self.wantsLayer = true self.autoSetDimension(.height, toSize: self.theme.tabHeight) self.titleView.stringValue = tabRepresentative.title self.addViews() self.adjustToSelectionChange(self.tabRepresentative.isSelected) self.adjustWidth() } func updateTheme() { self.adjustColors(self.isSelected) } override func mouseUp(with _: NSEvent) { self.tabBar?.select(tab: self) } override func draw(_: NSRect) { self.drawSeparators() self.drawSelectionIndicator() } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } var position: TabPosition = [] { willSet { self.needsDisplay = self.position != newValue } } private weak var tabBar: TabBar<Rep>? private let closeButton = NSButton(forAutoLayout: ()) private let titleView = NSTextField(forAutoLayout: ()) private var widthConstraint: NSLayoutConstraint? @objc func closeAction(_: NSButton) { self.tabBar?.close(tab: self) } } // MARK: - Private extension Tab { private var isSelected: Bool { self.tabRepresentative.isSelected } private var theme: Theme { // We set tabBar in init, it's weak only because we want to avoid retain cycle. self.tabBar!.theme } private func adjustColors(_ newIsSelected: Bool) { if newIsSelected { self.layer?.backgroundColor = self.theme.selectedBackgroundColor.cgColor self.titleView.textColor = self.theme.selectedForegroundColor self.closeButton.image = self.theme.selectedCloseButtonImage } else { self.layer?.backgroundColor = self.theme.backgroundColor.cgColor self.titleView.textColor = self.theme.foregroundColor self.closeButton.image = self.theme.closeButtonImage } self.needsDisplay = true } // We need the arg since we are calling this function also in willSet. private func adjustToSelectionChange(_ newIsSelected: Bool) { self.adjustColors(newIsSelected) if newIsSelected { self.titleView.font = self.theme.selectedTitleFont } else { self.titleView.font = self.theme.titleFont } self.adjustWidth() self.needsDisplay = true } private func adjustWidth() { let idealWidth = 3 * self.theme.tabHorizontalPadding + self.theme.iconDimension.width + self.titleView.intrinsicContentSize.width let targetWidth = min(max(self.theme.tabMinWidth, idealWidth), self.theme.tabMaxWidth) if let c = self.widthConstraint { self.removeConstraint(c) } self.widthConstraint = self.autoSetDimension(.width, toSize: targetWidth) } private func addViews() { let close = self.closeButton let title = self.titleView self.addSubview(close) self.addSubview(title) close.imagePosition = .imageOnly close.image = self.theme.closeButtonImage close.isBordered = false (close.cell as? NSButtonCell)?.highlightsBy = .contentsCellMask close.target = self close.action = #selector(Self.closeAction) title.drawsBackground = false title.font = self.theme.titleFont title.textColor = self.theme.foregroundColor title.isEditable = false title.isBordered = false title.isSelectable = false title.usesSingleLineMode = true title.lineBreakMode = .byTruncatingTail close.autoSetDimensions(to: self.theme.iconDimension) close.autoPinEdge(toSuperviewEdge: .left, withInset: self.theme.tabHorizontalPadding) close.autoAlignAxis(toSuperviewAxis: .horizontal) title.autoPinEdge(.left, to: .right, of: close, withOffset: self.theme.tabHorizontalPadding) title.autoPinEdge(toSuperviewEdge: .right, withInset: self.theme.tabHorizontalPadding) title.autoAlignAxis(toSuperviewAxis: .horizontal) } private func drawSeparators() { let b = self.bounds let left = CGRect(x: 0, y: 0, width: self.theme.separatorThickness, height: b.height) let right = CGRect(x: b.maxX - 1, y: 0, width: self.theme.separatorThickness, height: b.height) let bottom = CGRect( x: 0, y: 0, width: b.width, height: self.theme.separatorThickness ) guard let context = NSGraphicsContext.current?.cgContext else { return } context.saveGState() defer { context.restoreGState() } self.theme.separatorColor.set() if self.position.isEmpty { left.fill() right.fill() } if self.position == .first { right.fill() } if self.position == .last { left.fill() } bottom.fill() } private func drawSelectionIndicator() { guard self.isSelected else { return } let b = self.bounds let rect = CGRect( x: self.theme.separatorThickness, y: 0, width: b.width, height: self.theme.tabSelectionIndicatorThickness ) guard let context = NSGraphicsContext.current?.cgContext else { return } context.saveGState() defer { context.restoreGState() } self.theme.tabSelectedIndicatorColor.set() rect.fill() } }
29.079602
99
0.703678
f9472be2704adbb7560f1b7d96c573e67db04ac0
933
// // NSSegmentedControl+Helper.swift // Swift-NSToolBar // // Created by Bin Shang on 2020/3/31. // Copyright © 2020 Knowstack. All rights reserved. // import Cocoa @available(OSX 10.12, *) public extension NSSegmentedControl { static func create(_ rect: NSRect, items: [Any]) -> Self { let control = Self.init(frame: rect) control.segmentStyle = .texturedRounded control.trackingMode = .momentary control.segmentCount = items.count let width: CGFloat = rect.width/CGFloat(control.segmentCount) for e in items.enumerated() { if e.element is NSImage { control.setImage((e.element as! NSImage), forSegment: e.offset) } else { control.setLabel(e.element as! String, forSegment: e.offset) } control.setWidth(width, forSegment: e.offset) } return control; } }
28.272727
79
0.606645
2f428b912391fee6d9ff84c9b0adc373233247cc
1,748
// // ControllerTableViewCell.swift // ATests // // Created by Radu Costea on 09/06/16. // Copyright © 2016 Radu Costea. All rights reserved. // import UIKit class ControllerTableViewCell: UITableViewCell { var controller: ContainedViewController? func didMoveToControllerViewHierarchy(parentController: UIViewController) { if let containedController = controller { parentController.addChildViewController(containedController) containedController.view.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(containedController.view) let constraints = [ containedController.view.leadingAnchor.constraintEqualToAnchor(contentView.leadingAnchor), containedController.view.trailingAnchor.constraintEqualToAnchor(contentView.trailingAnchor), containedController.view.bottomAnchor.constraintEqualToAnchor(contentView.bottomAnchor), containedController.view.topAnchor.constraintEqualToAnchor(contentView.topAnchor), ] for constraint in constraints { constraint.priority = 950 constraint.active = true } containedController.didMoveToParentViewController(parentController) containedController.presenter = parentController } } override func prepareForReuse() { if let containedController = controller { containedController.removeFromParentViewController() containedController.view.removeFromSuperview() containedController.didMoveToParentViewController(nil) controller = nil } } }
38
108
0.681922
21fc49590a76aae7a8174038cf172266561a7376
1,016
// // Extensions.swift // MyMovies // // Created by Victor on 19/04/17. // Copyright © 2017 Victor. All rights reserved. // import UIKit import RealmSwift import Alamofire extension UITableViewController { func setMessageOnTableFooterView(text: String) { let view = UIView() if text != "" { let textHeight = UIScreen.main.bounds.size.height/3 let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.numberOfLines = 0 label.textAlignment = .center label.text = text view.addSubview(label) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[label]-|", options: [], metrics: nil, views: ["label": label])) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-\(textHeight)-[label]", options: [], metrics: nil, views: ["label": label])) } tableView.tableFooterView = view } }
29.028571
162
0.626969
ab9c85cf167d945e2765aea14074940eb81533f7
860
public class Var: Formula, Hashable, CustomStringConvertible, CustomPlaygroundQuickLookable { public let name: String public init(_ name: String) { precondition(!name.hasPrefix("_"), "Underscore is reserved for switching variables") self.name = name } private static var switchingCount = 0 init() { Var.switchingCount += 1 name = "_\(Var.switchingCount)" } public var f: FormulaImp { return .variable(self) } public var description: String { return name } public var customPlaygroundQuickLook: PlaygroundQuickLook { return .text(description) } public var hashValue: Int { return ObjectIdentifier(self).hashValue } public static func ==(lhs: Var, rhs: Var) -> Bool { return lhs === rhs } }
24.571429
93
0.60814
5d044892b80fbdca51fe6e7e4af2864cae5a65e1
574
// // Regex.swift // // // Created by Melvin Gundlach on 09.05.17. // import Foundation extension String { func matchingStrings(regex: String) -> [[String]] { guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] } let nsString = self as NSString let results = regex.matches(in: self, options: [], range: NSRange(0..<nsString.length)) return results.map { result in (0..<result.numberOfRanges).map { result.range(at: $0).location != NSNotFound ? nsString.substring(with: result.range(at: $0)) : "" } } } }
24.956522
92
0.651568
11dee23fa9734903b9b93f5e8625339065517dfb
2,829
// // SCNCapsule.swift // SwifterSwift // // Created by Max Härtwig on 06.04.19. // Copyright © 2019 SwifterSwift // #if canImport(SceneKit) import SceneKit // MARK: - Methods public extension SCNCapsule { /// Creates a capsule geometry with the specified diameter and height. /// /// - Parameters: /// - capDiameter: The diameter both of the capsule’s cylindrical body and of its hemispherical ends. /// - height: The height of the capsule along the y-axis of its local coordinate space. convenience init(capDiameter: CGFloat, height: CGFloat) { self.init(capRadius: capDiameter / 2, height: height) } /// Creates a capsule geometry with the specified radius and height. /// /// - Parameters: /// - capRadius: The radius both of the capsule’s cylindrical body and of its hemispherical ends. /// - height: The height of the capsule along the y-axis of its local coordinate space. /// - material: The material of the geometry. convenience init(capRadius: CGFloat, height: CGFloat, material: SCNMaterial) { self.init(capRadius: capRadius, height: height) materials = [material] } /// Creates a capsule geometry with the specified diameter and height. /// /// - Parameters: /// - capDiameter: The diameter both of the capsule’s cylindrical body and of its hemispherical ends. /// - height: The height of the capsule along the y-axis of its local coordinate space. /// - material: The material of the geometry. convenience init(capDiameter: CGFloat, height: CGFloat, material: SCNMaterial) { self.init(capRadius: capDiameter / 2, height: height) materials = [material] } /// Creates a capsule geometry with the specified radius and height. /// /// - Parameters: /// - capRadius: The radius both of the capsule’s cylindrical body and of its hemispherical ends. /// - height: The height of the capsule along the y-axis of its local coordinate space. /// - material: The material of the geometry. convenience init(capRadius: CGFloat, height: CGFloat, color: UIColor) { self.init(capRadius: capRadius, height: height) materials = [SCNMaterial(color: color)] } /// Creates a capsule geometry with the specified diameter and height. /// /// - Parameters: /// - capDiameter: The diameter both of the capsule’s cylindrical body and of its hemispherical ends. /// - height: The height of the capsule along the y-axis of its local coordinate space. /// - material: The material of the geometry. convenience init(capDiameter: CGFloat, height: CGFloat, color: UIColor) { self.init(capRadius: capDiameter / 2, height: height) materials = [SCNMaterial(color: color)] } } #endif
39.84507
107
0.671615
626022029c01d0df2dfb8d6fd8ce3449073b61d8
1,345
// // LSYProgressView.swift // LSYWeiBo // // Created by 李世洋 on 16/7/4. // Copyright © 2016年 李世洋. All rights reserved. // import UIKit class LSYProgressView: UIView { var progress : CGFloat = 0 { didSet { setNeedsDisplay() } } override func drawRect(rect: CGRect) { super.drawRect(rect) // 1.获取参数 let center = CGPoint(x: rect.width * 0.5, y: rect.height * 0.5) let r = min(rect.width, rect.height) * 0.5 - 6 let start = CGFloat(-M_PI_2) let end = start + progress * 2 * CGFloat(M_PI) /** 参数: 1. 中心点 2. 半径 3. 起始弧度 4. 截至弧度 5. 是否顺时针 */ // 2.根据进度画出中间的圆 let path = UIBezierPath(arcCenter: center, radius: r, startAngle: start, endAngle: end, clockwise: true) path.addLineToPoint(center) path.closePath() UIColor(white: 1.0, alpha: 0.5).setFill() path.fill() // 3.画出边线 let rEdge = min(rect.width, rect.height) * 0.5 - 2 let endEdge = start + 2 * CGFloat(M_PI) let pathEdge = UIBezierPath(arcCenter: center, radius: rEdge, startAngle: start, endAngle: endEdge, clockwise: true) UIColor(white: 1.0, alpha: 0.5).setStroke() pathEdge.stroke() } }
25.377358
124
0.536059
0e623299fb252f854e1f47224986bf8ed921c702
2,365
// // LNMyCollectionCell.swift // TaoKeThird // // Created by 付耀辉 on 2018/10/31. // Copyright © 2018年 付耀辉. All rights reserved. // import UIKit class LNMyCollectionCell: UITableViewCell { @IBOutlet weak var earn_money: UIButton! @IBOutlet weak var good_icon: UIImageView! @IBOutlet weak var good_title: UILabel! @IBOutlet weak var discount: UILabel! @IBOutlet weak var discountLabel: UILabel! @IBOutlet weak var sale_count: UILabel! @IBOutlet weak var quanLabel: UILabel! @IBOutlet weak var now_price: UILabel! @IBOutlet weak var old_price: UILabel! @IBOutlet weak var goodImage: UIButton! override func awakeFromNib() { super.awakeFromNib() earn_money.clipsToBounds = true earn_money.layer.cornerRadius = 4 good_icon.cornerRadius = 5 good_icon.clipsToBounds = true quanLabel.textColor = kMainColor1() now_price.textColor = kMainColor1() // good_title.textColor = kMainColor1() discount.textColor = kMainColor1() discountLabel.textColor = kMainColor1() } public var model : LNMyCollectionModel? { didSet { if model == nil{ return } switch model!.type { case "1": goodImage.setImage(UIImage.init(named: "miaosha_mark"), for: .normal) case "2": goodImage.setImage(UIImage.init(named: "jd_mark"), for: .normal) default: goodImage.setImage(UIImage.init(named: "pdd_mark"), for: .normal) } earn_money.setTitle(model?.coupon_price, for: .normal) discount.text = "¥"+OCTools().getStrWithIntStr(model!.coupon_price) good_title.text = model?.title sale_count.text = "销量"+(model?.volume)!+"件" now_price.text = "¥"+(model?.final_price)! old_price.text = "原价¥"+(model?.price)! good_icon.sd_setImage(with: OCTools.getEfficientAddress(model?.pic_url), placeholderImage: UIImage.init(named: "goodImage_1")) } } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
28.841463
138
0.601691
693811336698d4bc7b99803da00b202f20eb9b13
644
// // GameViewController.swift // Conquer // // Created by Manny Yusuf on 3/11/19. // Copyright © 2019 Manny Yusuf. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let scene = GameScene(size: view.bounds.size) let skView = view as! SKView skView.showsFPS = true skView.showsNodeCount = true skView.ignoresSiblingOrder = true scene.scaleMode = .resizeFill skView.presentScene(scene) } override var prefersStatusBarHidden: Bool { return true } }
23
54
0.653727
f7118e35729ff98afc15a2c61c91755092363176
288
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a { class A { func g protocol d { let : AnyObject.E == } class B<d where g: P { let a { class A { { } class d<T: f
16.941176
87
0.694444
5dfd3e1de10dccf3c82e0564726a2162a3eb7bcf
1,179
// // RequestTextViewController.swift // NetworkMonitor // // Created by Watanabe Toshinori on 12/29/17. // import UIKit class RequestTextViewController: UIViewController { @IBOutlet weak var textView: UITextView! var text: String! // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() text = { guard let log = Session.current.selectedLog, let data = log.request.httpBodyStream?.read() else { return "" } return String(data: data, encoding: .utf8) ?? "" }() textView.text = text navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(RequestTextViewController.activityTapped(_:))) } // MARK: - Action @objc func activityTapped(_ sender: Any) { let viewController = UIActivityViewController(activityItems: [text], applicationActivities: nil) present(viewController, animated: true, completion: nil) } }
26.2
124
0.573367
67d109383d891f02f182b9bbf1bd7ca374e005fe
282
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing } } class b<i : b> i: g{ func c {} e g { : g { h func i() -> }
21.692308
87
0.659574
64d0ccf55a4556460a1b1f0a5f9c8e1254600678
3,795
// // ImageCropper.swift // HeartstoneDustCounter // // Created by Lucas Santos on 30/03/18. // Copyright © 2018 lucasSantos. All rights reserved. // import Foundation import UIKit public class ImageCropper { public init() { } /** Crop an UIImage, to a percentage (values between 0 to 1) according to a anchor point, and reisze it to the desired size - Parameter image: The image to crop - Parameter toSize: The return size of the cropped image - Parameter anchor: Starts the cropping from this anchor point - Parameter percentualWidth: Value between 0 and 1 for width - Parameter percentualHeight: Value between 0 and 1 for height - Returns: A new image with dimensions from the toSize parameter */ public func resizeAndCrop(image: UIImage, toSize desiredSize: CGSize, anchorTo: CroppingAnchor, percentualWidth: CGFloat, percentualHeight: CGFloat) -> UIImage { var retImage = UIImage() let croppedImage = self.crop(image: image, anchor: anchorTo, percentualWidth: percentualWidth, percentualHeight: percentualHeight) retImage = self.resize(image: croppedImage, toSize: desiredSize) return retImage } /** Resize an UIImage, to the parameter toSize - Parameter image: The image to crop - Parameter toSize: The return size of the cropped image - Returns: A new image with dimensions from the toSize parameter */ public func resize(image: UIImage, toSize size: CGSize) -> UIImage { let deisiredRect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(size, false, 0.0) image.draw(in: deisiredRect) let resizedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return resizedImage } /** Crop an UIImage, to a percentage (values between 0 to 1) according to a anchor point - Parameter image: The image to crop - Parameter anchor: Starts the cropping from this anchor point - Parameter percentualWidth: Value between 0 and 1 for width - Parameter percentualHeight: Value between 0 and 1 for height - Returns: A new image with dimensions: width * percentualWidth, height * percentualHeight */ public func crop(image: UIImage, anchor: CroppingAnchor, percentualWidth: CGFloat, percentualHeight: CGFloat) -> UIImage { let imageWidth = image.size.width let imageHeight = image.size.height print(imageWidth) let rectSize = CGSize(width: imageWidth * percentualWidth, height: imageHeight * percentualHeight) var croppingRect = CGRect() switch anchor { case .bottonLeft: croppingRect = CGRect(x: 0, y: imageHeight - rectSize.height, width: rectSize.width, height: rectSize.height) case .topLeft: croppingRect = CGRect(x: 0, y: 0, width: rectSize.width, height: rectSize.height) case .topRight: croppingRect = CGRect(x: imageWidth - rectSize.width, y: 0, width: rectSize.width, height: rectSize.height) case .bottonRight: croppingRect = CGRect(x: imageWidth - rectSize.width, y: imageHeight - rectSize.height, width: rectSize.width, height: rectSize.height) case .center: let rectOriginPoint = CGPoint.init(x: (imageWidth / 2) - (rectSize.width / 2), y: (imageHeight / 2) - (rectSize.height / 2)) croppingRect = CGRect(origin: rectOriginPoint, size: rectSize) } let croppedImage = image.cgImage!.cropping(to: croppingRect) return UIImage(cgImage: croppedImage!) } }
39.123711
165
0.660343
fe5f82e13f03e4466dd20795641d185907ca48d2
11,361
// Copyright 2020 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit class ViewController: UIViewController { /// Image picker for accessing the photo library or camera. private var imagePicker = UIImagePickerController() /// Style transferer instance reponsible for running the TF model. private var styleTransferer: StyleTransferer? /// Target image to transfer a style onto. private var targetImage: UIImage? /// Style-representative image applied to the input image to create a pastiche. private var styleImage: UIImage? /// Style transfer result. private var styleTransferResult: StyleTransferResult? // UI elements @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var photoCameraButton: UIButton! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var cropSwitch: UISwitch! @IBOutlet weak var inferenceStatusLabel: UILabel! @IBOutlet weak var legendLabel: UILabel! @IBOutlet weak var styleImageView: UIImageView! @IBOutlet weak var runButton: UIButton! @IBOutlet weak var pasteImageButton: UIButton! override func viewDidLoad() { super.viewDidLoad() imageView.contentMode = .scaleAspectFill // Setup image picker. imagePicker.delegate = self imagePicker.sourceType = .photoLibrary // Set default style image. styleImage = StylePickerDataSource.defaultStyle() styleImageView.image = styleImage // Enable camera option only if current device has camera. let isCameraAvailable = UIImagePickerController.isCameraDeviceAvailable(.front) || UIImagePickerController.isCameraDeviceAvailable(.rear) if isCameraAvailable { photoCameraButton.isEnabled = true } // Initialize a style transferer instance. StyleTransferer.newInstance { result in switch result { case let .success(transferer): self.styleTransferer = transferer case .error(let wrappedError): print("Failed to initialize: \(wrappedError)") } } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // Observe foregrounding events for pasteboard access. addForegroundEventHandler() pasteImageButton.isEnabled = imageFromPasteboard() != nil } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NotificationCenter.default.removeObserver(self) } @IBAction func onTapPasteImage(_ sender: Any) { guard let image = imageFromPasteboard() else { return } let actionSheet = imageRoleSelectionAlert(image: image) present(actionSheet, animated: true, completion: nil) } @IBAction func onTapRunButton(_ sender: Any) { // Make sure that the cached target image is available. guard targetImage != nil else { self.inferenceStatusLabel.text = "Error: Input image is nil." return } runStyleTransfer(targetImage!) } @IBAction func onTapChangeStyleButton(_ sender: Any) { let pickerController = StylePickerViewController.fromStoryboard() pickerController.delegate = self present(pickerController, animated: true, completion: nil) } /// Open camera to allow user taking photo. @IBAction func onTapOpenCamera(_ sender: Any) { guard UIImagePickerController.isCameraDeviceAvailable(.front) || UIImagePickerController.isCameraDeviceAvailable(.rear) else { return } imagePicker.sourceType = .camera present(imagePicker, animated: true) } /// Open photo library for user to choose an image from. @IBAction func onTapPhotoLibrary(_ sender: Any) { imagePicker.sourceType = .photoLibrary present(imagePicker, animated: true) } /// Handle tapping on different display mode: Input, Style, Result @IBAction func onSegmentChanged(_ sender: Any) { switch segmentedControl.selectedSegmentIndex { case 0: // Mode 0: Show input image imageView.image = targetImage case 1: // Mode 1: Show style image imageView.image = styleImage case 2: // Mode 2: Show style transfer result. imageView.image = styleTransferResult?.resultImage default: break } } /// Handle changing center crop setting. @IBAction func onCropSwitchValueChanged(_ sender: Any) { // Make sure that the cached target image is available. guard targetImage != nil else { self.inferenceStatusLabel.text = "Error: Input image is nil." return } // Re-run style transfer upon center-crop setting changed. runStyleTransfer(targetImage!) } } // MARK: - Style Transfer extension ViewController { /// Run style transfer on the given image, and show result on screen. /// - Parameter image: The target image for style transfer. func runStyleTransfer(_ image: UIImage) { clearResults() // Make sure that the style transferer is initialized. guard let styleTransferer = styleTransferer else { inferenceStatusLabel.text = "ERROR: Interpreter is not ready." return } guard let targetImage = self.targetImage else { inferenceStatusLabel.text = "ERROR: Select a target image." return } // Center-crop the target image if the user has enabled the option. let willCenterCrop = cropSwitch.isOn let image = willCenterCrop ? targetImage.cropCenter() : targetImage // Cache the potentially cropped image. self.targetImage = image // Show the potentially cropped image on screen. imageView.image = image // Make sure that the image is ready before running style transfer. guard image != nil else { inferenceStatusLabel.text = "ERROR: Image could not be cropped." return } guard let styleImage = styleImage else { inferenceStatusLabel.text = "ERROR: Select a style image." return } // Lock the crop switch and run buttons while style transfer is running. cropSwitch.isEnabled = false runButton.isEnabled = false // Run style transfer. styleTransferer.runStyleTransfer( style: styleImage, image: image!, completion: { result in // Show the result on screen switch result { case let .success(styleTransferResult): self.styleTransferResult = styleTransferResult // Change to show style transfer result self.segmentedControl.selectedSegmentIndex = 2 self.onSegmentChanged(self) // Show result metadata self.showInferenceTime(styleTransferResult) case let .error(error): self.inferenceStatusLabel.text = error.localizedDescription } // Regardless of the result, re-enable switching between different display modes self.segmentedControl.isEnabled = true self.cropSwitch.isEnabled = true self.runButton.isEnabled = true }) } /// Clear result from previous run to prepare for new style transfer. private func clearResults() { inferenceStatusLabel.text = "Running inference with TensorFlow Lite..." legendLabel.text = nil segmentedControl.isEnabled = false segmentedControl.selectedSegmentIndex = 0 } /// Show processing time on screen. private func showInferenceTime(_ result: StyleTransferResult) { let timeString = "Preprocessing: \(Int(result.preprocessingTime * 1000))ms.\n" + "Style prediction: \(Int(result.stylePredictTime * 1000))ms.\n" + "Style transfer: \(Int(result.styleTransferTime * 1000))ms.\n" + "Post-processing: \(Int(result.postprocessingTime * 1000))ms.\n" inferenceStatusLabel.text = timeString } } // MARK: - UIImagePickerControllerDelegate extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController( _ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any] ) { if let pickedImage = info[.originalImage] as? UIImage { // Rotate target image to .up orientation to avoid potential orientation misalignment. guard let targetImage = pickedImage.transformOrientationToUp() else { inferenceStatusLabel.text = "ERROR: Image orientation couldn't be fixed." return } self.targetImage = targetImage if styleImage != nil { runStyleTransfer(targetImage) } else { imageView.image = targetImage } } dismiss(animated: true) } } // MARK: StylePickerViewControllerDelegate extension ViewController: StylePickerViewControllerDelegate { func picker(_: StylePickerViewController, didSelectStyle image: UIImage) { styleImage = image styleImageView.image = image if let targetImage = targetImage { runStyleTransfer(targetImage) } } } // MARK: Pasteboard images extension ViewController { fileprivate func imageFromPasteboard() -> UIImage? { return UIPasteboard.general.images?.first } fileprivate func imageRoleSelectionAlert(image: UIImage) -> UIAlertController { let controller = UIAlertController(title: "Paste Image", message: nil, preferredStyle: .actionSheet) controller.popoverPresentationController?.sourceView = view let setInputAction = UIAlertAction(title: "Set input image", style: .default) { _ in // Rotate target image to .up orientation to avoid potential orientation misalignment. guard let targetImage = image.transformOrientationToUp() else { self.inferenceStatusLabel.text = "ERROR: Image orientation couldn't be fixed." return } self.targetImage = targetImage self.imageView.image = targetImage } let setStyleAction = UIAlertAction(title: "Set style image", style: .default) { _ in guard let croppedImage = image.cropCenter() else { self.inferenceStatusLabel.text = "ERROR: Unable to crop style image." return } self.styleImage = croppedImage self.styleImageView.image = croppedImage } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in controller.dismiss(animated: true, completion: nil) } controller.addAction(setInputAction) controller.addAction(setStyleAction) controller.addAction(cancelAction) return controller } fileprivate func addForegroundEventHandler() { NotificationCenter.default.addObserver(self, selector: #selector(onForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil) } @objc fileprivate func onForeground(_ sender: Any) { self.pasteImageButton.isEnabled = self.imageFromPasteboard() != nil } }
32.646552
95
0.699938
508499382d743d188f783275d564dafad9236494
453
// // InAppPurchaseButton.swift // JPPerformance // // Created by Christoph Pageler on 12.12.19. // Copyright © 2019 Christoph Pageler. All rights reserved. // import UIKit class InAppPurchaseButton: UIButton { override func layoutSubviews() { super.layoutSubviews() layer.cornerRadius = frame.size.height / 2.0 layer.borderColor = tintColor.withAlphaComponent(0.5).cgColor layer.borderWidth = 2.0 } }
18.875
69
0.679912
efd165ceda5353062d2ae31abd4344722b017ff0
2,924
// // HttpServer.swift // Swifter // // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved. // import Foundation open class HttpServer: HttpServerIO { public static let VERSION: String = { #if os(Linux) return "1.5.0" #else let bundle = Bundle(for: HttpServer.self) guard let version = bundle.infoDictionary?["CFBundleShortVersionString"] as? String else { return "Unspecified" } return version #endif }() private let router = HttpRouter() public override init() { self.DELETE = MethodRoute(method: .DELETE, router: router) self.PATCH = MethodRoute(method: .PATCH, router: router) self.HEAD = MethodRoute(method: .HEAD, router: router) self.POST = MethodRoute(method: .POST, router: router) self.GET = MethodRoute(method: .GET, router: router) self.PUT = MethodRoute(method: .PUT, router: router) self.delete = MethodRoute(method: .DELETE, router: router) self.patch = MethodRoute(method: .PATCH, router: router) self.head = MethodRoute(method: .HEAD, router: router) self.post = MethodRoute(method: .POST, router: router) self.get = MethodRoute(method: .GET, router: router) self.put = MethodRoute(method: .PUT, router: router) } public var DELETE, PATCH, HEAD, POST, GET, PUT: MethodRoute public var delete, patch, head, post, get, put: MethodRoute public subscript(path: String) -> ((HttpRequest, HttpResponseHeaders) -> HttpResponse)? { set { router.register(nil, path: path, handler: newValue) } get { return nil } } public var routes: [String] { return router.routes() } public var notFoundHandler: ((HttpRequest, HttpResponseHeaders) -> HttpResponse)? public var middleware = [(HttpRequest, HttpResponseHeaders) -> HttpResponse?]() override open func dispatch(_ request: HttpRequest, _ responseHeaders: HttpResponseHeaders) -> ([String: String], (HttpRequest, HttpResponseHeaders) -> HttpResponse) { for layer in middleware { if let response = layer(request, responseHeaders) { return ([:], { (_, _) in response }) } } if let result = router.route(request.method, path: request.path) { return result } if let notFoundHandler = self.notFoundHandler { return ([:], notFoundHandler) } return super.dispatch(request, responseHeaders) } public struct MethodRoute { public let method: HttpMethod public let router: HttpRouter public subscript(path: String) -> ((HttpRequest, HttpResponseHeaders) -> HttpResponse)? { set { router.register(method, path: path, handler: newValue) } get { return nil } } } }
34.4
171
0.615253
5dfc19e66597be7c62b93d333d0b3b00dd0decb8
7,565
/* ----------------------------------------------------------------------------- This source file is part of MedKitMIP. Copyright 2016-2018 Jon Griffeth Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ----------------------------------------------------------------------------- */ import Foundation import MedKitCore /** Queue */ class WSFPReader: WSFPReaderWriter { enum OpCode : UInt8 { case ContinuationFrame = 0x00 case TextFrame = 0x01 case BinaryFrame = 0x02 case Close = 0x08 case Ping = 0x09 case Pong = 0x0a } var code : WSFPReaderWriter.OpCode? { return self.opcode } var isData : Bool { return opcode == .ContinuationFrame || opcode == .TextFrame || opcode == .BinaryFrame } var isControl : Bool { return opcode == .Close || opcode == .Ping || opcode == .Pong } var payload : Data { return Data(payloadData!) } // header state private var valid : Bool = false private var contBuf : [UInt8]? private var fin : Bool = false private var maskingKey : [UInt8]? private var opcode : WSFPReaderWriter.OpCode? private var rsv1 : Bool = false private var rsv2 : Bool = false private var rsv3 : Bool = false private var payloadSize : UInt64 = 0 private var payloadData : [UInt8]? func reset() { fin = false opcode = nil maskingKey = nil rsv1 = false rsv2 = false rsv3 = false payloadData = nil payloadSize = 0 valid = false } /** Get message from queue. - Parameters: - queue: */ func getMessage(from queue: DataQueue) -> Bool { if getHeader(from: queue) { if let payload = getPayload(from: queue) { if isControl { // control messages can be received at anytime payloadData = payload return true } if contBuf == nil { contBuf = payload } else { contBuf! += payload } if fin { payloadData = contBuf contBuf = nil } return fin } } return false } /** Get header from queue. - Parameters: - queue: */ private func getHeader(from queue: DataQueue) -> Bool { if !valid && queue.count >= UInt64(MinSize) { var headerSize : Int = MinSize var headerBuf : [UInt8]! var maskingkeyOffset : Int = MinSize var payloadMode : UInt8 headerBuf = queue.peek(count: headerSize) let x = headerBuf[1] payloadMode = x & PayloadSizeMask switch payloadMode { case PayloadMode16Bit : headerSize += 2 maskingkeyOffset += 2 case PayloadMode64Bit : headerSize += 8 maskingkeyOffset += 8 default : break } if (headerBuf[1] & MASKING_KEY) == MASKING_KEY { headerSize += MaskingKeySize } if queue.count >= UInt64(headerSize) { headerBuf = queue.read(count: headerSize) fin = (headerBuf[0] & FIN ) == FIN rsv1 = (headerBuf[0] & RSV1) == RSV1 rsv2 = (headerBuf[0] & RSV2) == RSV2 rsv3 = (headerBuf[0] & RSV3) == RSV3 let x = headerBuf[0] & OPCODE opcode = OpCode(rawValue: x) switch payloadMode { case PayloadMode16Bit : payloadSize = decode16(headerBuf, PayloadSizeOffset) case PayloadMode64Bit : payloadSize = decode64(headerBuf, PayloadSizeOffset) default : payloadSize = UInt64(payloadMode) break } if (headerBuf[1] & MASKING_KEY) != 0 { maskingKey = Array<UInt8>(headerBuf[maskingkeyOffset..<headerBuf.count]) } } if !verify() { return false } valid = true } return valid } private func decode16(_ buffer: [UInt8], _ offset: Int) -> UInt64 { var data = Data(repeating: 0, count: 2) var value = UInt16() for i in 0..<data.count { data[i] = buffer[offset + i] } withUnsafeMutablePointer(to: &value) { data.copyBytes(to: UnsafeMutableRawPointer($0).assumingMemoryBound(to: UInt8.self), count: 2) } return UInt64(value.bigEndian) } private func decode64(_ buffer: [UInt8], _ offset: Int) -> UInt64 { var data = Data(repeating: 0, count: 8) var value = UInt64() for i in 0..<data.count { data[i] = buffer[offset + i] } withUnsafeMutablePointer(to: &value) { data.copyBytes(to: UnsafeMutableRawPointer($0).assumingMemoryBound(to: UInt8.self), count: 8) } return value.bigEndian } /** Get payload from queue. - Parameters: - queue: */ private func getPayload(from queue: DataQueue) -> [UInt8]? { if queue.count >= payloadSize { var payload = queue.read(count: Int(payloadSize)) if let maskingKey = self.maskingKey { for i in 0..<payload.count { payload[i] = payload[i] ^ maskingKey[i % 4] } } return payload } return nil } /** Verify header. */ private func verify() -> Bool { if !rsv1 && !rsv2 && !rsv3 { if let opcode = self.opcode { switch opcode { case .ContinuationFrame : return contBuf != nil case .TextFrame, .BinaryFrame : return contBuf == nil case .Close, .Ping, .Pong : return fin && payloadSize < PayloadMin16Bit } } } return false } } // End of File
28.874046
137
0.454461
111065d9242a3887b1bb635822bb30ec5c09e502
29,946
// // ChatVC.swift // mChat // // Created by Vitaliy Paliy on 11/21/19. // Copyright © 2019 PALIY. All rights reserved. // import UIKit import Firebase import AVFoundation import CoreServices import Lottie class ChatVC: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate, AVAudioRecorderDelegate { // ---------------------------------------------------------------------------------------------------------------------------------------------------- // // ChatVC. This controller is responsible for sending and receiving messages. It supports text, audio, video and image messages. var friend: FriendInfo! var messages = [Messages]() let chatNetworking = ChatNetworking() let chatAudio = ChatAudio() var userResponse = UserResponse() var containerHeight: CGFloat! var collectionView: MessageCollectionView! var messageContainer: MessageContainer! var refreshIndicator: MessageLoadingIndicator! let blankLoadingView = AnimationView(animation: Animation.named("chatLoadingAnim")) let calendar = Calendar(identifier: .gregorian) // ---------------------------------------------------------------------------------------------------------------------------------------------------- // override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = ThemeColors.selectedBackgroundColor setupChat() notificationCenterHandler() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tabBarController?.tabBar.isHidden = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) chatNetworking.removeObserves() } deinit { NotificationCenter.default.removeObserver(self) } // If Iphone X or >, it will move inputTF up override func viewSafeAreaInsetsDidChange() { super.viewSafeAreaInsetsDidChange() var topConst: CGFloat! if view.safeAreaInsets.bottom > 0 { containerHeight = 70 topConst = 28 }else{ containerHeight = 45 topConst = 8 } messageContainer = MessageContainer(height: containerHeight, const: topConst, chatVC: self) collectionView = MessageCollectionView(collectionViewLayout: UICollectionViewFlowLayout.init(), chatVC: self) refreshIndicator = MessageLoadingIndicator(frame: view.frame, const: topConst, chatVC: self) hideKeyboardOnTap() setupChatBlankView() } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // private func setupChatBlankView() { view.addSubview(blankLoadingView) blankLoadingView.translatesAutoresizingMaskIntoConstraints = false blankLoadingView.backgroundColor = .white blankLoadingView.play() blankLoadingView.loopMode = .loop blankLoadingView.backgroundBehavior = .pauseAndRestore let constraints = [ blankLoadingView.leadingAnchor.constraint(equalTo: view.leadingAnchor), blankLoadingView.trailingAnchor.constraint(equalTo: view.trailingAnchor), blankLoadingView.bottomAnchor.constraint(equalTo: messageContainer.topAnchor), blankLoadingView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor) ] NSLayoutConstraint.activate(constraints) } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // func setupChat(){ chatNetworking.chatVC = self chatNetworking.friend = friend setupChatNavBar() fetchMessages() navigationItem.rightBarButtonItem = UIBarButtonItem(customView: ProfileImageButton(chatVC: self, url: friend.profileImage ?? "")) observeFriendTyping() } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // private func setupChatNavBar(){ let loginDate = NSDate(timeIntervalSince1970: (friend.lastLogin ?? 0).doubleValue) navigationController?.navigationBar.tintColor = .black if friend.isOnline ?? false { navigationItem.setNavTitles(navTitle: friend.name ?? "", navSubtitle: "Online") }else{ navigationItem.setNavTitles(navTitle: friend.name ?? "", navSubtitle: calendar.calculateLastLogin(loginDate)) } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // // MARK: CLIP IMAGE BUTTON PRESSED METHOD @objc func clipImageButtonPressed() { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.mediaTypes = [kUTTypeImage as String, kUTTypeMovie as String] let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Take Photo", style: .default, handler: { (alertAction) in if UIImagePickerController.isSourceTypeAvailable(.camera) { imagePicker.sourceType = .camera self.present(imagePicker, animated: true, completion: nil) } })) alert.addAction(UIAlertAction(title: "Open Photo Library", style: .default, handler: { (alertAction) in imagePicker.sourceType = .photoLibrary self.present(imagePicker, animated: true, completion: nil) })) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) cancelAction.setValue(UIColor.systemRed, forKey: "titleTextColor") alert.addAction(cancelAction) present(alert, animated: true, completion: nil) } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { if let originalImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage { chatNetworking.uploadImage(image: originalImage) { (storageRef, image, mediaName) in self.chatNetworking.downloadImage(storageRef, image, mediaName) } dismiss(animated: true, completion: nil) } if let videoUrl = info[UIImagePickerController.InfoKey.mediaURL] as? URL { chatNetworking.uploadVideoFile(videoUrl) dismiss(animated: true, completion: nil) } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // // MARK: SEND BUTTON PRESSED METHOD @objc func sendButtonPressed(){ setupTextMessage() } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // // MARK: HIDE KEYBOARD ON TAP private func hideKeyboardOnTap(){ let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard)) tap.cancelsTouchesInView = false collectionView.addGestureRecognizer(tap) navigationController?.navigationBar.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))) } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // @objc private func hideKeyboard(){ view.endEditing(true) } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // // MARK: SEND TEXT MESSAGE METHOD private func setupTextMessage(){ let trimmedMessage = messageContainer.messageTV.text.trimmingCharacters(in: .whitespacesAndNewlines) guard trimmedMessage.count > 0 , let friendId = friend.id else { return } let senderRef = Database.database().reference().child("messages").child(CurrentUser.uid).child(friendId).childByAutoId() let friendRef = Database.database().reference().child("messages").child(friendId).child(CurrentUser.uid).child(senderRef.key!) guard let messageId = senderRef.key else { return } var values = ["message": trimmedMessage, "sender": CurrentUser.uid!, "recipient": friend.id!, "time": Date().timeIntervalSince1970, "messageId": messageId] as [String : Any] if userResponse.repliedMessage != nil || userResponse.messageToForward != nil{ let repValues = userResponse.messageToForward != nil ? userResponse.messageToForward : userResponse.repliedMessage if repValues?.message != nil { values["repMessage"] = repValues?.message }else if repValues?.mediaUrl != nil{ values["repMediaMessage"] = repValues?.mediaUrl } values["repMID"] = repValues?.id values["repSender"] = userResponse.messageSender exitResponseButtonPressed() } chatNetworking.sendMessageHandler(senderRef: senderRef, friendRef: friendRef, values: values) { (error) in self.handleMessageTextSent(error) } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // private func handleMessageTextSent(_ error: Error?){ guard error == nil else { showAlert(title: "Error", message: error?.localizedDescription) return } messageContainer.messageTV.text = "" messageContainer.messageTV.subviews[2].isHidden = false self.scrollToTheBottom(animated: false) hideKeyboard() chatNetworking.disableIsTyping() messageContainer.messageTV.constraints.forEach { (constraint) in if constraint.firstAttribute == .height { constraint.constant = 32 if sendingIsFinished(const: messageContainer.heightAnchr){ return } } view.layoutIfNeeded() } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // // MARK: FETCH MESSAGES METHOD func fetchMessages(){ chatNetworking.loadMore = true chatNetworking.scrollToIndex = [] chatNetworking.getMessages(view, messages) { (newMessages, order) in self.chatNetworking.lastMessageReached = newMessages.count == 0 if self.chatNetworking.lastMessageReached { self.observeMessageActions() return } self.chatNetworking.scrollToIndex = newMessages self.refreshIndicator.startAnimating() if order { self.refreshIndicator.order = order self.messages.append(contentsOf: newMessages) }else{ self.refreshIndicator.order = order self.messages.insert(contentsOf: newMessages, at: 0) } self.handleReload() } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // private func observeMessageActions(){ self.blankLoadingView.isHidden = true chatNetworking.observeUserMessageSeen() let ref = Database.database().reference().child("messages").child(CurrentUser.uid).child(friend.id ?? "") ref.observe(.childRemoved) { (snap) in self.chatNetworking.deleteMessageHandler(self.messages, for: snap) { (index) in self.messages.remove(at: index) self.collectionView.deleteItems(at: [IndexPath(item: index, section: 0)]) } } ref.queryLimited(toLast: 1).observe(.childAdded) { (snap) in self.chatNetworking.newMessageRecievedHandler(self.messages, for: snap) { (newMessage) in self.messages.append(newMessage) self.collectionView.reloadData() if newMessage.determineUser() != CurrentUser.uid { self.scrollToTheBottom(animated: true) } } } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // private func handleReload(){ DispatchQueue.main.async { self.collectionView.reloadData() if self.refreshIndicator.order{ self.scrollToTheBottom(animated: false) }else{ let index = self.chatNetworking.scrollToIndex.count - 1 self.collectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .top, animated: false) } self.chatNetworking.loadMore = false self.refreshIndicator.stopAnimating() } observeMessageActions() } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // @objc func profileImageTapped(){ let friendController = FriendInformationVC() friendController.friend = friend friendController.modalPresentationStyle = .fullScreen show(friendController, sender: self) } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // func textFieldShouldReturn(_ textField: UITextField) -> Bool { sendButtonPressed() return true } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // // MARK: ZOOM IMAGE METHOD func zoomImageHandler(image: UIImageView, message: Messages) { if !collectionView.isLongPress { view.endEditing(true) let _ = SelectedImageView(image, message, self) } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // func messageContainerHeightHandler(_ const: NSLayoutConstraint, _ estSize: CGSize){ if sendingIsFinished(const: const) { return } var height = estSize.height if userResponse.responseStatus { height = estSize.height + 50 } if height > 150 { return } if messageContainer.messageTV.calculateLines() >= 2 { if containerHeight > 45 { const.constant = height + 35 }else{ const.constant = height + 15 } } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // func messageHeightHandler(_ constraint: NSLayoutConstraint, _ estSize: CGSize){ let height: CGFloat = userResponse.responseStatus == true ? 100 : 150 if estSize.height > height{ messageContainer.messageTV.isScrollEnabled = true return }else if messageContainer.messageTV.calculateLines() < 2 { constraint.constant = 32 self.view.layoutIfNeeded() return } constraint.constant = estSize.height self.view.layoutIfNeeded() } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // private func sendingIsFinished(const: NSLayoutConstraint) -> Bool{ let height: CGFloat = userResponse.responseStatus == true ? containerHeight + 50 : containerHeight if messageContainer.messageTV.text.count == 0 { messageContainer.messageTV.isScrollEnabled = false const.constant = height return true }else{ return false } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // // MARK: NOTIFICATION CENTER private func notificationCenterHandler() { NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: UIApplication.willResignActiveNotification, object: nil) } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // @objc private func willResignActive(_ notification: Notification) { chatNetworking.disableIsTyping() } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // @objc private func handleKeyboardWillShow(notification: NSNotification){ let kFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect let kDuration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double guard let height = kFrame?.height, let duration = kDuration else { return } if containerHeight > 45 { messageContainer.bottomAnchr.constant = 13.2 collectionView.contentOffset.y -= 13.2 } messageContainer.bottomAnchr.constant -= height collectionView.contentOffset.y += height UIView.animate(withDuration: duration) { self.view.layoutIfNeeded() } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // @objc private func handleKeyboardWillHide(notification: NSNotification){ let kFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect let kDuration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double guard let height = kFrame?.height else { return } guard let duration = kDuration else { return } if containerHeight > 45 { collectionView.contentOffset.y += 13.2 } collectionView.contentOffset.y -= height messageContainer.bottomAnchr.constant = 0 UIView.animate(withDuration: duration) { self.view.layoutIfNeeded() } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // func animateActionButton(){ var buttonToAnimate = UIButton() if messageContainer.messageTV.text.count >= 1 { messageContainer.micButton.alpha = 0 if messageContainer.sendButton.alpha == 1 { return } messageContainer.sendButton.alpha = 1 buttonToAnimate = messageContainer.sendButton }else if messageContainer.messageTV.text.count == 0{ messageContainer.micButton.alpha = 1 messageContainer.sendButton.alpha = 0 buttonToAnimate = messageContainer.micButton } buttonToAnimate.transform = CGAffineTransform(scaleX: 0.2, y: 0.2) UIView.animate(withDuration: 0.55, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: .curveEaseIn, animations: { buttonToAnimate.transform = .identity }) } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // // MARK: OBSERVE TYPING METHOD private func observeFriendTyping(){ chatNetworking.observeIsUserTyping() { (friendActivity) in if friendActivity.friendId == self.friend.id && friendActivity.isTyping ?? false { self.navigationItem.setupTypingNavTitle(navTitle: self.friend.name ?? "") }else{ self.setupChatNavBar() } } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // private func scrollToTheBottom(animated: Bool){ if messages.count > 0 { let indexPath = IndexPath(item: messages.count - 1, section: 0) collectionView.scrollToItem(at: indexPath, at: .bottom, animated: animated) } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // @objc func handleLongPressGesture(longPress: UILongPressGestureRecognizer){ if longPress.state != UIGestureRecognizer.State.began { return } collectionView.isLongPress = true let point = longPress.location(in: collectionView) guard let indexPath = collectionView.indexPathForItem(at: point) else { return } guard let cell = collectionView.cellForItem(at: indexPath) as? ChatCell else { return } let message = messages[indexPath.row] openToolsMenu(message, cell) } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // private func openToolsMenu(_ message: Messages, _ selectedCell: ChatCell){ UIImpactFeedbackGenerator(style: .medium).impactOccurred() hideKeyboard() collectionView.isUserInteractionEnabled = false selectedCell.isHidden = true let _ = ToolsMenu(message, selectedCell, self) } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // func forwardButtonPressed(_ message: Messages) { chatNetworking.getMessageSender(message: message) { (name) in self.userResponse.messageToForward = message let convController = NewConversationVC() convController.forwardDelegate = self convController.forwardName = name let navController = UINavigationController(rootViewController: convController) self.present(navController, animated: true, completion: nil) } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // func responseButtonPressed(_ message: Messages, forwardedName: String? = nil){ responseViewChangeAlpha(a: 0) messageContainer.micButton.alpha = 0 messageContainer.sendButton.alpha = 1 messageContainer.messageTV.becomeFirstResponder() userResponse.responseStatus = true userResponse.repliedMessage = message messageContainer.heightAnchr.constant += 50 UIView.animate(withDuration: 0.1, animations: { self.view.layoutIfNeeded() self.responseMessageLine(message, forwardedName) }) { (true) in self.responseViewChangeAlpha(a: 1) } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // @objc func handleAudioRecording(){ chatAudio.recordingSession = AVAudioSession.sharedInstance() if !chatAudio.requestPermisson() { return } if chatAudio.audioRecorder == nil { startAudioRecording() }else{ stopAudioRecording() } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // // MARK: START RECORDING METHOD private func startAudioRecording(){ let fileName = chatAudio.getDirectory().appendingPathComponent("sentAudio.m4a") let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 12000, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue] do{ chatAudio.audioRecorder = try AVAudioRecorder(url: fileName, settings: settings) chatAudio.audioRecorder.delegate = self chatAudio.audioRecorder.record() prepareContainerForRecording() }catch{ showAlert(title: "Error", message: error.localizedDescription) } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // private func prepareContainerForRecording(){ chatAudio.timer = Timer(timeInterval: 1.0, target: self, selector: #selector(audioTimerHandler), userInfo: nil, repeats: true) RunLoop.current.add(chatAudio.timer, forMode: RunLoop.Mode.common) messageContainer.micButton.setImage(UIImage(systemName: "stop.circle"), for: .normal) messageContainer.recordingLabel.isHidden = false UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .curveEaseIn, animations: { self.messageContainer.recordingLabel.frame.origin.x += self.messageContainer.frame.width/6 self.messageContainer.messageTV.frame.origin.y += self.containerHeight self.messageContainer.clipImageButton.frame.origin.y += self.containerHeight self.view.layoutIfNeeded() self.messageContainer.recordingAudioView.isHidden = false }) { (true) in self.messageContainer.actionCircle.isHidden = false } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // @objc private func audioTimerHandler(){ chatAudio.timePassed += 1 let (m,s) = chatAudio.timePassedFrom(seconds: chatAudio.timePassed) let minutes = m < 10 ? "0\(m)" : "\(m)" let seconds = s < 10 ? "0\(s)" : "\(s)" messageContainer.recordingLabel.text = "\(minutes):\(seconds)" } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // // MARK: STOP RECORDING METHOD private func stopAudioRecording() { chatAudio.audioRecorder.stop() chatAudio.audioRecorder = nil chatAudio.timePassed = 0 do{ let data = try Data(contentsOf: chatAudio.getDirectory().appendingPathComponent("sentAudio.m4a")) chatNetworking.uploadAudio(file: data) removeRecordingUI() }catch{ print(error.localizedDescription) } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // private func removeRecordingUI(){ messageContainer.recordingAudioView.isHidden = true if chatAudio.timer != nil { chatAudio.timer.invalidate() } messageContainer.micButton.setImage(UIImage(systemName: "mic"), for: .normal) UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .curveEaseOut, animations: { self.messageContainer.actionCircle.isHidden = true self.messageContainer.recordingLabel.frame.origin.x -= self.messageContainer.frame.width/6 self.messageContainer.messageTV.frame.origin.y -= self.containerHeight self.messageContainer.clipImageButton.frame.origin.y -= self.containerHeight self.view.layoutIfNeeded() }) { (true) in self.messageContainer.recordingAudioView.isHidden = true self.messageContainer.recordingLabel.text = "00:00" } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // func handleUserPressedAudioButton(for cell: ChatCell){ if chatAudio.audioPlayer == nil { chatAudio.audioPlayer = cell.audioPlayer chatAudio.audioPlayer?.play() cell.audioPlayButton.setImage(UIImage(systemName: "pause.circle.fill"), for: .normal) cell.timer = Timer(timeInterval: 0.3, target: cell, selector: #selector(cell.timerHandler), userInfo: nil, repeats: true) RunLoop.current.add(cell.timer, forMode: RunLoop.Mode.common) }else{ chatAudio.audioPlayer?.pause() } } // ---------------------------------------------------------------------------------------------------------------------------------------------------- // }
49.091803
181
0.514092
d5b277f1516ee108423454ee5641556a456da577
10,108
// // InjectedKeyedDecodingContainer.swift // AdvancedCodableHelpers // // Created by Tyler Anger on 2018-11-06. // import Foundation /// A keyed decoding container that allows the coder to inject extra keyed values into the decoding process /// /// Unsupported functions: superDecoder(), superDecoder(forKey:) public class InjectedKeyedDecodingContainer<K>: KeyedDecodingContainerProtocol where K: CodingKey { public typealias Key = K /*private struct HashedKey: Hashable { let key: Key #if !swift(>=4.1) public var hashValue: Int { return key.stringValue.hashValue } #endif public init(_ key: Key) { self.key = key } public init(_ key: String) { self.init(Key(stringValue: key)!) } #if swift(>=4.1) public func hash(into hasher: inout Hasher) { hasher.combine(self.key.stringValue) } #endif static func == (lhs: InjectedKeyedDecodingContainer<K>.HashedKey, rhs: InjectedKeyedDecodingContainer<K>.HashedKey) -> Bool { return lhs.key.stringValue == rhs.key.stringValue } }*/ private var injections: [String: Any] = [:] public let codingPath: [CodingKey] public var allKeys: [K] { var rtn: [K] = [] for k in self.injections.keys { // Must try and add injected keys if they do not exist alread if let kv = K(stringValue: k) { if !rtn.contains(where: { $0.stringValue == k }) { rtn.append(kv) } } } return rtn } public init(_ codingPath: [CodingKey], injections: [String: Any]) { self.codingPath = codingPath self.injections = injections } public convenience init(_ codingPath: [CodingKey], injection: (key: String, value: Any)) { self.init(codingPath, injections: [injection.key: injection.value]) } public func toKeyedContainer() -> KeyedDecodingContainer<Key> { return KeyedDecodingContainer<Key>(self) } public func contains(_ key: K) -> Bool { return self.injections.keys.contains(key.stringValue) } public func decodeNil(forKey key: K) throws -> Bool { return !self.injections.keys.contains(key.stringValue) //return try self.container.decodeNil(forKey: key) } public func decode(_ type: Bool.Type, forKey key: K) throws -> Bool { guard let aV = self.injections[key.stringValue], let v = aV as? Bool else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath.appending(key), debugDescription: "Key Not Found")) } return v } public func decode(_ type: String.Type, forKey key: K) throws -> String { guard let aV = self.injections[key.stringValue], let v = aV as? String else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath.appending(key), debugDescription: "Key Not Found")) } return v } public func decode(_ type: Double.Type, forKey key: K) throws -> Double { guard let aV = self.injections[key.stringValue], let v = aV as? Double else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath.appending(key), debugDescription: "Key Not Found")) } return v } public func decode(_ type: Float.Type, forKey key: K) throws -> Float { guard let aV = self.injections[key.stringValue], let v = aV as? Float else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath.appending(key), debugDescription: "Key Not Found")) } return v } public func decode(_ type: Int.Type, forKey key: K) throws -> Int { guard let aV = self.injections[key.stringValue], let v = aV as? Int else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath.appending(key), debugDescription: "Key Not Found")) } return v } public func decode(_ type: Int8.Type, forKey key: K) throws -> Int8 { guard let aV = self.injections[key.stringValue], let v = aV as? Int8 else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath.appending(key), debugDescription: "Key Not Found")) } return v } public func decode(_ type: Int16.Type, forKey key: K) throws -> Int16 { guard let aV = self.injections[key.stringValue], let v = aV as? Int16 else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath.appending(key), debugDescription: "Key Not Found")) } return v } public func decode(_ type: Int32.Type, forKey key: K) throws -> Int32 { guard let aV = self.injections[key.stringValue], let v = aV as? Int32 else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath.appending(key), debugDescription: "Key Not Found")) } return v } public func decode(_ type: Int64.Type, forKey key: K) throws -> Int64 { guard let aV = self.injections[key.stringValue], let v = aV as? Int64 else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath.appending(key), debugDescription: "Key Not Found")) } return v } public func decode(_ type: UInt.Type, forKey key: K) throws -> UInt { guard let aV = self.injections[key.stringValue], let v = aV as? UInt else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath.appending(key), debugDescription: "Key Not Found")) } return v } public func decode(_ type: UInt8.Type, forKey key: K) throws -> UInt8 { guard let aV = self.injections[key.stringValue], let v = aV as? UInt8 else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath.appending(key), debugDescription: "Key Not Found")) } return v } public func decode(_ type: UInt16.Type, forKey key: K) throws -> UInt16 { guard let aV = self.injections[key.stringValue], let v = aV as? UInt16 else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath.appending(key), debugDescription: "Key Not Found")) } return v } public func decode(_ type: UInt32.Type, forKey key: K) throws -> UInt32 { guard let aV = self.injections[key.stringValue], let v = aV as? UInt32 else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath.appending(key), debugDescription: "Key Not Found")) } return v } public func decode(_ type: UInt64.Type, forKey key: K) throws -> UInt64 { guard let aV = self.injections[key.stringValue], let v = aV as? UInt64 else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath.appending(key), debugDescription: "Key Not Found")) } return v } public func decode<T>(_ type: T.Type, forKey key: K) throws -> T where T : Decodable { guard let aV = self.injections[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath.appending(key), debugDescription: "Key Not Found")) } if let v = aV as? T { return v } else if let d = aV as? [String: Any] { let injector = InjectedKeyedDecodingContainer<CodableKey>(self.codingPath.appending(key), injections: d) let decoder = WrappedKeyedDecoder<CodableKey>(injector) return try T(from: decoder) } else if let a = aV as? [Any] { let injector = InjectedUnkeyedDecodingContainer(self.codingPath.appending(key), objects: a) let decoder = WrappedUnkeyedDecoder(injector) return try T(from: decoder) } else { let injector = InjectedSingleValueDecodingContainer(self.codingPath.appending(key), object: aV) let decoder = WrappedSingleValueDecoder(injector) return try T(from: decoder) //throw DecodingError._typeMismatch(at: self.codingPath.appending(key), expectation: type, reality: aV) } } public func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: K) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey { let aV = self.injections[key.stringValue] ?? Dictionary<String, Any>() if let d = aV as? [String: Any] { let injector = InjectedKeyedDecodingContainer<CodableKey>(self.codingPath.appending(key), injections: d) let bridge = BridgedKeyedDecodingContainer<CodableKey, NestedKey>(injector) return KeyedDecodingContainer<NestedKey>(bridge) } else { throw DecodingError._typeMismatch(at: self.codingPath.appending(key), expectation: type, reality: aV) } } public func nestedUnkeyedContainer(forKey key: K) throws -> UnkeyedDecodingContainer { guard let aV = self.injections[key.stringValue] else { throw DecodingError.keyNotFound(key, DecodingError.Context(codingPath: self.codingPath.appending(key), debugDescription: "Key Not Found")) } return InjectedUnkeyedDecodingContainer(self.codingPath.appending(key), object: aV) } private func _superDecoder(forKey key: CodingKey) throws -> Decoder { fatalError("Unsupported Method") } public func superDecoder() throws -> Decoder { return try _superDecoder(forKey: CodableKey.super) } public func superDecoder(forKey key: K) throws -> Decoder { return try _superDecoder(forKey: key) } }
43.568966
161
0.640582
9b9471ff40cbcac78a378e28d64de3ad3b163e08
1,045
// Copyright 2022 Pera Wallet, LDA // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ChoosePasswordViewController+Theme.swift import MacaroonUIKit import Foundation extension ChoosePasswordViewController { struct Theme: LayoutSheet, StyleSheet { let choosePasswordViewTheme: ChoosePasswordViewTheme let backgroundColor: Color init(_ family: LayoutFamily) { choosePasswordViewTheme = ChoosePasswordViewTheme() backgroundColor = AppColors.Shared.System.background } } }
32.65625
75
0.737799
87948563523caffb5023577ac5ca12852b39f8a9
11,941
// // SBAScheduledActivityArchive.swift // BridgeApp (iOS) // // Copyright © 2016-2018 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation import JsonModel private let kScheduledActivityGuidKey = "scheduledActivityGuid" private let kScheduleIdentifierKey = "scheduleIdentifier" private let kScheduledOnKey = "scheduledOn" private let kScheduledActivityLabelKey = "activityLabel" private let kDataGroups = "dataGroups" private let kSchemaRevisionKey = "schemaRevision" private let kSurveyCreatedOnKey = "surveyCreatedOn" private let kSurveyGuidKey = "surveyGuid" private let kMetadataFilename = "metadata.json" /// A subclass of the `SBBDataArchive` that implements `RSDDataArchive` for task results. open class SBAScheduledActivityArchive: SBBDataArchive, RSDDataArchive { /// The identifier for this archive. public let identifier: String /// The schedule used to start this task (if any). public let schedule: SBBScheduledActivity? /// The schema info for this archive. public let schemaInfo: RSDSchemaInfo /// Is the archive a top-level archive? public let isPlaceholder: Bool /// Hold the task result (if any) used to create the archive. internal var taskResult: RSDTaskResult? /// The schedule identifier is the `SBBScheduledActivity.guid` which is a combination of the activity /// guid and the `scheduledOn` property. public var scheduleIdentifier: String? { return schedule?.guid } public init(identifier: String, schemaInfo: RSDSchemaInfo, schedule: SBBScheduledActivity?, isPlaceholder: Bool = false) { self.identifier = identifier self.schedule = schedule self.schemaInfo = schemaInfo self.isPlaceholder = isPlaceholder super.init(reference: schemaInfo.schemaIdentifier ?? identifier, jsonValidationMapping: nil) // set info values. self.setArchiveInfoObject(NSNumber(value: schemaInfo.schemaVersion), forKey: kSchemaRevisionKey) if let surveyReference = schedule?.activity.survey { // Survey schema is better matched by created date and survey guid self.setArchiveInfoObject(surveyReference.guid, forKey: kSurveyGuidKey) let createdOn = surveyReference.createdOn ?? Date() if let stamp = (createdOn as NSDate).iso8601String() { self.setArchiveInfoObject(stamp, forKey: kSurveyCreatedOnKey) } } } /// By default, the task result is not included and metadata are **not** archived directly, while the /// answer map is included. open func shouldInsertData(for filename: RSDReservedFilename) -> Bool { return filename == .answers } /// Get the archivable object for the given result. open func archivableData(for result: RSDResult, sectionIdentifier: String?, stepPath: String?) -> RSDArchivable? { if self.usesV1LegacySchema, let answerResult = result as? RSDAnswerResult { return SBAAnswerResultWrapper(sectionIdentifier: sectionIdentifier, result: answerResult) } else if let archivable = result as? RSDArchivable { return archivable } else { return nil } } /// Insert the data into the archive. By default, this will call `insertData(intoArchive:,filename:, createdOn:)`. /// /// - note: The "answers.json" file is special-cased to *not* include the `.json` extension if this is /// for a `v1_legacy` archive. This allows the v1 schema to use `answers.foo` which reads better in the /// Synapse tables. open func insertDataIntoArchive(_ data: Data, manifest: RSDFileManifest) throws { var filename = manifest.filename let fileKey = (filename as NSString).deletingPathExtension if let reserved = RSDReservedFilename(rawValue: fileKey), reserved == .answers { if self.usesV1LegacySchema { filename = fileKey } else { self.dataFilename = filename } } self.insertData(intoArchive: data, filename: filename, createdOn: manifest.timestamp) } /// Close the archive. open func completeArchive(with metadata: RSDTaskMetadata) throws { let metadataDictionary = try metadata.rsd_jsonEncodedDictionary() try completeArchive(createdOn: metadata.startDate, with: metadataDictionary) } /// Close the archive with optional metadata from a task result. open func completeArchive(createdOn: Date, with metadata: [String : Any]? = nil) throws { // If the archive is empty and this is a placeholder archive, then exit early without // adding the metadata. if self.isEmpty() && isPlaceholder { return } // Set up the activity metadata. var metadataDictionary: [String : Any] = metadata ?? [:] // Add metadata values from the schedule. if let schedule = self.schedule { metadataDictionary[kScheduledActivityGuidKey] = schedule.guid metadataDictionary[kScheduleIdentifierKey] = schedule.activity.guid metadataDictionary[kScheduledOnKey] = (schedule.scheduledOn as NSDate).iso8601String() metadataDictionary[kScheduledActivityLabelKey] = schedule.activity.label } // Add the current data groups. if let dataGroups = SBAParticipantManager.shared.studyParticipant?.dataGroups { metadataDictionary[kDataGroups] = dataGroups.joined(separator: ",") } // insert the dictionary. insertDictionary(intoArchive: metadataDictionary, filename: kMetadataFilename, createdOn: createdOn) // Look to see that the answers.json file is included, even if it is empty. // syoung 11/12/2019 This is a belt-and-suspenders for MP2-270 because I'm not sure why it // isn't always included and I can't repro the bug. Due to the timing of this issue with // needing to release, pushing a work-around while I continue to investigate. if !self.usesV1LegacySchema, self.answersDictionary == nil, let taskResult = self.taskResult { let builder = RSDDefaultScoreBuilder() let answers = builder.getScoringData(from: taskResult) as? [String : Any] ?? [String : Any]() self.insertAnswersDictionary(answers) } // complete the archive. try complete() } } func bridgifyFilename(_ filename: String) -> String { return filename.replacingOccurrences(of: ".", with: "_").replacingOccurrences(of: " ", with: "_") } private let kIdentifierKey = "identifier" private let kItemKey = "item" private let kStartDateKey = "startDate" private let kEndDateKey = "endDate" private let kQuestionResultQuestionTypeKey = "questionType" private let kQuestionResultSurveyAnswerKey = "answer" private let kNumericResultUnitKey = "unit" /// The wrapper is used to encode the surveys in the expected format. struct SBAAnswerResultWrapper : RSDArchivable { let sectionIdentifier : String? let result : RSDAnswerResult var identifier: String { if let section = sectionIdentifier { return "\(section).\(result.identifier)" } else { return result.identifier } } func buildArchiveData(at stepPath: String?) throws -> (manifest: RSDFileManifest, data: Data)? { var json: [String : Any] = [:] // Synapse exporter expects item value to match base filename let item = bridgifyFilename(self.identifier) json[kIdentifierKey] = result.identifier json[kStartDateKey] = result.startDate json[kEndDateKey] = result.endDate json[kItemKey] = item if let answer = (result.value as? JsonValue)?.jsonObject() { json[result.answerType.bridgeAnswerKey] = answer json[kQuestionResultSurveyAnswerKey] = answer json[kQuestionResultQuestionTypeKey] = result.answerType.bridgeAnswerType if let unit = result.answerType.unit { json[kNumericResultUnitKey] = unit } } let jsonObject = (json as NSDictionary).jsonObject() let data = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) let manifest = RSDFileManifest(filename: "\(item).json", timestamp: result.endDate, contentType: "application/json") return (manifest, data) } } extension RSDAnswerResultType { var bridgeAnswerType: String { guard self.sequenceType == nil else { return "MultipleChoice" } if let dataType = self.formDataType, case .collection(let collectionType, _) = dataType, collectionType == .singleChoice { return "SingleChoice" } switch self.baseType { case .boolean: return "Boolean" case .string, .data, .codable: return "Text" case .integer: return "Integer" case .decimal: return "Decimal" case .date: if self.dateFormat == "HH:mm:ss" || self.dateFormat == "HH:mm" { return "TimeOfDay" } else { return "Date" } } } var bridgeAnswerKey: String { guard self.sequenceType == nil else { return "choiceAnswers" } if let dataType = self.formDataType, case .collection(let collectionType, _) = dataType, collectionType == .singleChoice { return "choiceAnswers" } switch self.baseType { case .boolean: return "booleanAnswer" case .string, .data, .codable: return "textAnswer" case .integer, .decimal: return "numericAnswer" case .date: if self.dateFormat == "HH:mm:ss" || self.dateFormat == "HH:mm" { return "dateComponentsAnswer" } else { return "dateAnswer" } } } }
41.318339
126
0.65832
9b1cc036908c5a7360c94c40e05907ad14cccd69
390
// // Text+Extensions.swift // ModernOctopodium // // Created by Nuno Gonçalves on 30/08/2019. // Copyright © 2019 numicago. All rights reserved. // import SwiftUI extension Text { init(_ locationType: LocationType) { self.init(locationType.name) _ = tag(locationType) } func tag(with locationType: LocationType) -> some View { tag(locationType) } }
19.5
80
0.661538
f715a41ae567ac1a2695626722b197e87dbc6084
4,511
// // ProjectsListActivitySplitViewController.swift // TogglTargets // // Created by David Dávila on 28.12.17. // Copyright 2016-2018 David Dávila // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Cocoa import Result import ReactiveSwift class ProjectsListActivityViewController: NSViewController, BindingTargetProvider { // MARK: - Interface internal typealias Interface = ( projectIDsByTimeTargets: ProjectIDsByTimeTargetsProducer, selectedProjectId: BindingTarget<ProjectID?>, selectProjectId: SignalProducer<ProjectID?, NoError>, runningEntry: SignalProducer<RunningEntry?, NoError>, currentDate: SignalProducer<Date, NoError>, periodPreference: SignalProducer<PeriodPreference, NoError>, modelRetrievalStatus: SignalProducer<ActivityStatus, NoError>, readProject: ReadProject, readTimeTarget: ReadTimeTarget, readReport: ReadReport) private let lastBinding = MutableProperty<Interface?>(nil) internal var bindingTarget: BindingTarget<Interface?> { return lastBinding.bindingTarget } private let displayActivity = MutableProperty(false) // MARK: - Contained view controllers private var projectsListViewController: ProjectsListViewController? lazy private var activityViewController: ActivityViewController = { let activity = self.storyboard!.instantiateController(withIdentifier: "ActivityViewController") as! ActivityViewController // swiftlint:disable:this force_cast addChild(activity) stackView.addView(activity.view, in: .bottom) activity.view.leadingAnchor.constraint(equalTo: stackView.leadingAnchor).isActive = true activity.view.trailingAnchor.constraint(equalTo: stackView.trailingAnchor).isActive = true return activity }() @IBOutlet weak var stackView: NSStackView! override func prepare(for segue: NSStoryboardSegue, sender: Any?) { if let projects = segue.destinationController as? ProjectsListViewController { projectsListViewController = projects projects <~ lastBinding.producer.skipNil().map { ($0.projectIDsByTimeTargets, $0.selectedProjectId, $0.selectProjectId, $0.runningEntry, $0.currentDate, $0.periodPreference, $0.readProject, $0.readTimeTarget, $0.readReport) } } } // MARK: - override func viewDidLoad() { super.viewDidLoad() activityViewController <~ SignalProducer<ActivityViewController.Interface, NoError>( value: (modelRetrievalStatus: lastBinding.latestOutput { $0.modelRetrievalStatus }, requestDisplay: displayActivity.bindingTarget) ) // Duplicated to allow independent animations let showActivity: BindingTarget<Void> = activityViewController.view.reactive .makeBindingTarget { [unowned self] activityView, _ in NSAnimationContext.runAnimationGroup({ context in context.allowsImplicitAnimation = false activityView.animator().isHidden = false self.stackView.layoutSubtreeIfNeeded() }, completionHandler: nil) } let hideActivity: BindingTarget<Void> = activityViewController.view.reactive .makeBindingTarget { [unowned self] activityView, _ in NSAnimationContext.runAnimationGroup({ context in context.allowsImplicitAnimation = true activityView.isHidden = true self.stackView.layoutSubtreeIfNeeded() }, completionHandler: nil) } showActivity <~ displayActivity.signal.skipRepeats().filter { $0 }.map { _ in () } hideActivity <~ displayActivity.signal.skipRepeats().filter { !$0 }.map { _ in () } } }
40.276786
103
0.673687
62f9adec2952add8a1e9372b72a2a30e375ff181
115
import Foundation public enum VisitAction: String, Codable { case advance case replace case restore }
14.375
42
0.721739
e0a9e1aa7dc8fec2890e1e4e14904da5ff11311d
19,938
// // OTPViewController.swift // goSellSDK // // Copyright © 2019 Tap Payments. All rights reserved. // import CoreGraphics import struct TapAdditionsKitV2.TypeAlias import class UIKit.NSLayoutConstraint.NSLayoutConstraint import enum UIKit.UIApplication.UIStatusBarStyle import class UIKit.UIButton.UIButton import class UIKit.UIColor.UIColor import class UIKit.UIFont.UIFont import class UIKit.UIGestureRecognizer.UIGestureRecognizer import class UIKit.UIImage.UIImage import class UIKit.UIImageView.UIImageView import class UIKit.UILabel.UILabel import class UIKit.UIStoryboard.UIStoryboard import class UIKit.UITapGestureRecognizer.UITapGestureRecognizer import class UIKit.UIView.UIView import class UIKit.UIViewController.UIViewController import protocol UIKit.UIViewControllerTransitioning.UIViewControllerAnimatedTransitioning import protocol UIKit.UIViewControllerTransitioning.UIViewControllerInteractiveTransitioning import protocol UIKit.UIViewControllerTransitioning.UIViewControllerTransitioningDelegate import class TapVisualEffectViewV2.TapVisualEffectView /// View controller that handles Tap OTP input. import UIKit internal final class OTPViewController: SeparateWindowViewController { // MARK: - Internal - // MARK: Properties internal override var preferredStatusBarStyle: UIStatusBarStyle { return Theme.current.commonStyle.statusBar[.fullscreen].uiStatusBarStyle } // MARK: Methods internal static func show(with topOffset: CGFloat = 0.0, with phoneNumber: String, delegate: OTPViewControllerDelegate) { let controller = self.createAndSetupController() controller.delegate = delegate controller.phoneNumber = phoneNumber if controller.presentingViewController == nil { controller.showExternally(topOffset: topOffset) } else { controller.startAnotherAttempt() } } internal func addInteractiveDismissalRecognizer(_ recognizer: UIGestureRecognizer) { self.dismissalView?.addGestureRecognizer(recognizer) } internal override func hide(animated: Bool = true, async: Bool = true, completion: TypeAlias.ArgumentlessClosure? = nil) { super.hide(animated: animated, async: async) { OTPViewController.destroyInstance() ResizablePaymentContainerViewController.tap_findInHierarchy()?.makeWindowedBack { completion?() } } } internal override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.startFirstAttemptIfNotYetStarted() } internal override func localizationChanged() { super.localizationChanged() self.countdownDateFormatter.locale = LocalizationManager.shared.selectedLocale self.updateResendButtonTitle(with: self.timerDataManager.state) self.confirmationButton?.setLocalizedText(.btn_confirm_title) self.updateDescriptionLabelText() } internal override func themeChanged() { super.themeChanged() let settings = Theme.current.otpScreenStyle self.otpInputView?.setDigitsStyle(settings.digits) self.otpInputView?.setDigitsHolderViewBackgroundColor(settings.otpDigitsBackgroundColor.color) self.otpInputView?.setDigitsHolderBorderColor(settings.otpDigitsBorderColor.color) self.updateDescriptionLabelText() self.updateResendButtonTitle(with: self.timerDataManager.state) self.dismissalArrowImageView?.image = settings.arrowIcon blurView.style = Theme.current.commonStyle.blurStyle[Process.shared.appearance].style } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) ThemeManager.shared.resetCurrentThemeToDefault() themeChanged() } deinit { self.transitioning = nil self.timerDataManager.invalidateTimer() } // MARK: - Fileprivate - // MARK: Properties fileprivate var dismissalInteractionController: OTPDismissalInteractionController? // MARK: - Private - /// Transition handler for OTP view controller. private final class Transitioning: NSObject, UIViewControllerTransitioningDelegate { fileprivate var shouldUseDefaultOTPAnimation = true fileprivate func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { if let otpController = presented as? OTPViewController { let interactionController = OTPDismissalInteractionController(viewController: otpController) otpController.dismissalInteractionController = interactionController } guard let to = presented as? PopupPresentationAnimationController.PopupPresentationViewController else { return nil } return PopupPresentationAnimationController(presentationFrom: presenting, to: to, overlaysFromView: false, overlaySupport: PaymentOptionsViewController.tap_findInHierarchy()) } fileprivate func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { guard let from = dismissed as? UIViewController & PopupPresentationSupport, let to = from.presentingViewController else { return nil } return PopupPresentationAnimationController(dismissalFrom: from, to: to, overlaysToView: false, overlaySupport: PaymentOptionsViewController.tap_findInHierarchy()) } fileprivate func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { if let otpAnimator = animator as? PopupPresentationAnimationController, let otpController = otpAnimator.fromViewController as? OTPViewController, let interactionController = otpController.dismissalInteractionController, interactionController.isInteracting { otpAnimator.canFinishInteractiveTransitionDecisionHandler = { [weak otpController] (decision) in guard let controller = otpController else { decision(true) return } controller.canDismissInteractively(decision) } interactionController.delegate = otpAnimator return interactionController } else { return nil } } } private struct Constants { fileprivate static let dismissalArrowImage: UIImage = { guard let result = UIImage.tap_named("ic_close_otp", in: .goSellSDKResources) else { fatalError("Failed to load \"ic_close_otp\" icon from the resources bundle.") } return result }() fileprivate static let descriptionFont: UIFont = .helveticaNeueRegular(14.0) fileprivate static let countdownFont: UIFont = .helveticaNeueRegular(13.0) fileprivate static let resendFont: UIFont = .helveticaNeueMedium(13.0) fileprivate static let descriptionColor: UIColor = .tap_hex("535353") fileprivate static let numberColor: UIColor = .tap_hex("1584FC") fileprivate static let resendColor: UIColor = .tap_hex("007AFF") fileprivate static let resendHighlightedColor: UIColor = .tap_hex("0D61E7") fileprivate static let updateTimerTimeInterval: TimeInterval = 1.0 fileprivate static let resendButtonTitleDateFormat = "mm:ss" //@available(*, unavailable) private init() { } } // MARK: Properties @IBOutlet private weak var dismissalView: UIView? @IBOutlet weak var blurView: TapVisualEffectView! @IBOutlet weak var otpHolderView: UIView?{ didSet { self.otpHolderView?.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.36).loadCompatibleDarkModeColor(forColorNamed: "OTPHolderColor") } } @IBOutlet private weak var dismissalArrowImageView: UIImageView? { didSet { self.dismissalArrowImageView?.image = Constants.dismissalArrowImage } } @IBOutlet private weak var otpInputView: OTPInputView? { didSet { self.otpInputView?.delegate = self self.updateConfirmationButtonState() } } @IBOutlet private weak var descriptionLabel: UILabel? { didSet { self.updateDescriptionLabelText() } } @IBOutlet private weak var resendButton: UIButton? @IBOutlet private weak var resendButtonLabel: UILabel? @IBOutlet private weak var confirmationButton: TapButton? { didSet { self.confirmationButton?.delegate = self self.confirmationButton?.themeStyle = Theme.current.buttonStyles.first(where: { $0.type == .confirmOTP })! self.updateConfirmationButtonState() } } @IBOutlet private weak var contentViewTopOffsetConstraint: NSLayoutConstraint? private static var storage: OTPViewController? private var alreadyStartedFirstAttempt: Bool = false private lazy var timerDataManager: OTPTimerDataManager = OTPTimerDataManager() private lazy var countdownDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.locale = LocalizationManager.shared.selectedLocale formatter.dateFormat = Constants.resendButtonTitleDateFormat return formatter }() private var phoneNumber: String = .tap_empty { didSet { self.updateDescriptionLabelText() } } private weak var delegate: OTPViewControllerDelegate? private var transitioning: Transitioning? = Transitioning() // MARK: Methods private static func createAndSetupController() -> OTPViewController { KnownStaticallyDestroyableTypes.add(OTPViewController.self) let controller = self.shared controller.modalPresentationStyle = .custom controller.transitioningDelegate = controller.transitioning return controller } private func updateDescriptionLabelText() { guard let nonnullLabel = self.descriptionLabel, self.phoneNumber.tap_length > 0 else { return } let numberString = "\u{202A}\(self.phoneNumber)\u{202C}" let descriptionText = String(format: LocalizationManager.shared.localizedString(for: .otp_guide_text), numberString) let themeSettings = Theme.current.otpScreenStyle let descriptionAttributes = themeSettings.descriptionText.asStringAttributes let attributedDescriptionText = NSMutableAttributedString(string: descriptionText, attributes: descriptionAttributes) if let range = attributedDescriptionText.string.tap_nsRange(of: numberString) { let numberAttributes = themeSettings.descriptionNumber.asStringAttributes let attributedMaskedNumberText = NSAttributedString(string: numberString, attributes: numberAttributes) attributedDescriptionText.replaceCharacters(in: range, with: attributedMaskedNumberText) } nonnullLabel.attributedText = NSAttributedString(attributedString: attributedDescriptionText) } private func startFirstAttemptIfNotYetStarted() { guard !self.alreadyStartedFirstAttempt else { return } self.startAnotherAttempt() self.alreadyStartedFirstAttempt = true } private func updateConfirmationButtonState() { guard let inputView = self.otpInputView else { return } self.makeConfirmationButtonEnabled(inputView.isProvidedDataValid) } private func makeConfirmationButtonEnabled(_ enabled: Bool) { self.confirmationButton?.isEnabled = enabled } private func startAttempt() { self.timerDataManager.startTimer(force: false) { [weak self] (state) in self?.updateResendButtonTitle(with: state) } } private func updateResendButtonTitle(with state: OTPTimerState) { let themeSettings = Theme.current.otpScreenStyle switch state { case .ticking(let remainingSeconds): let remainingDate = Date(timeIntervalSince1970: remainingSeconds) let title = self.countdownDateFormatter.string(from: remainingDate) self.resendButtonLabel?.text = title self.resendButtonLabel?.setTextStyle(themeSettings.timer) self.resendButtonLabel?.alpha = 1.0 self.resendButton?.isEnabled = false case .notTicking: self.resendButtonLabel?.setLocalizedText(.btn_resend_title) self.resendButtonLabel?.setTextStyle(themeSettings.resend) self.resendButtonLabel?.alpha = 1.0 self.resendButton?.isEnabled = true case .attemptsFinished: self.resendButtonLabel?.setLocalizedText(.btn_resend_title) self.resendButtonLabel?.setTextStyle(themeSettings.resend) self.resendButtonLabel?.alpha = 0.5 self.resendButton?.isEnabled = false } } private func startAnotherAttempt() { self.otpInputView?.startEditing() self.startAttempt() } private func setResendLabelHighlighted(_ highlighted: Bool) { UIView.animate(withDuration: 0.1) { self.resendButtonLabel?.textColor = highlighted ? Constants.resendHighlightedColor : Constants.resendColor } } @IBAction private func resendButtonHighlighted(_ sender: Any) { self.setResendLabelHighlighted(true) } @IBAction private func resendButtonLostHighlight(_ sender: Any) { self.setResendLabelHighlighted(false) } @IBAction private func resendButtonTouchUpInside(_ sender: Any) { self.resendOTPCode() } @IBAction private func dismissalViewTapDetected(_ recognizer: UITapGestureRecognizer) { guard let recognizerView = recognizer.view, recognizerView.bounds.contains(recognizer.location(in: recognizerView)), recognizer.state == .ended else { return } self.showCancelAttemptAlert { (shouldCancel) in if shouldCancel { self.delegate?.otpViewControllerDidCancel(self) self.hide(animated: true) } } } private func resendOTPCode() { self.delegate?.otpViewControllerResendButtonTouchUpInside(self) } private func confirmOTPCode() { guard let code = self.otpInputView?.otp else { return } self.delegate?.otpViewController(self, didEnter: code) } private func canDismissInteractively(_ decision: @escaping TypeAlias.BooleanClosure) { self.showCancelAttemptAlert { [weak self] (shouldCancel) in guard let strongSelf = self else { decision(shouldCancel) return } if shouldCancel { strongSelf.delegate?.otpViewControllerDidCancel(strongSelf) } decision(shouldCancel) } } private func showCancelAttemptAlert(_ decision: @escaping TypeAlias.BooleanClosure) { let alert = TapAlertController(titleKey: .alert_cancel_payment_title, messageKey: .alert_cancel_payment_message, preferredStyle: .alert) let cancelCancelAction = TapAlertController.Action(titleKey: .alert_cancel_payment_btn_no_title, style: .cancel) { [weak alert] (action) in guard let nonnullAlert = alert else { decision(false) return } nonnullAlert.hide { decision(false) } } let confirmCancelAction = TapAlertController.Action(titleKey: .alert_cancel_payment_btn_confirm_title, style: .destructive) { [weak alert] (action) in guard let nonnullAlert = alert else { decision(true) return } nonnullAlert.hide { decision(true) } } alert.addAction(cancelCancelAction) alert.addAction(confirmCancelAction) alert.show() } } // MARK: - InstantiatableFromStoryboard extension OTPViewController: InstantiatableFromStoryboard { internal static var hostingStoryboard: UIStoryboard { return .goSellSDKPayment } } // MARK: - DelayedDestroyable extension OTPViewController: DelayedDestroyable { internal static var hasAliveInstance: Bool { return self.storage != nil } internal static func destroyInstance(_ completion: TypeAlias.ArgumentlessClosure? = nil) { if let nonnullStorage = self.storage { nonnullStorage.transitioning?.shouldUseDefaultOTPAnimation = false nonnullStorage.hide(animated: true) { self.storage = nil KnownStaticallyDestroyableTypes.delayedDestroyableInstanceDestroyed() completion?() } } else { completion?() } } } // MARK: - Singleton extension OTPViewController: Singleton { internal static var shared: OTPViewController { if let nonnullStorage = self.storage { return nonnullStorage } let instance = OTPViewController.instantiate() instance.transitioning?.shouldUseDefaultOTPAnimation = true self.storage = instance return instance } } // MARK: - TapButton.Delegate extension OTPViewController: TapButton.Delegate { internal var canBeHighlighted: Bool { return true } internal func buttonTouchUpInside() { self.confirmOTPCode() } internal func securityButtonTouchUpInside() { self.buttonTouchUpInside() } internal func disabledButtonTouchUpInside() {} } // MARK: - OTPInputViewDelegate extension OTPViewController: OTPInputViewDelegate { internal func otpInputView(_ otpInputView: OTPInputView, inputStateChanged valid: Bool, wholeOTPAtOnce: Bool) { self.makeConfirmationButtonEnabled(valid) if valid && wholeOTPAtOnce { self.confirmOTPCode() } } } // MARK: - PopupPresentationSupport extension OTPViewController: PopupPresentationSupport { internal var presentationAnimationAnimatingConstraint: NSLayoutConstraint? { return self.contentViewTopOffsetConstraint } internal var viewToLayout: UIView { return self.view } } // MARK: - LoadingViewSupport extension OTPViewController: LoadingViewSupport { internal var loadingViewContainer: UIView { return self.view } }
31.748408
186
0.654178
ef21b4f72c88b4868266c6b2f5485a21852edb21
1,133
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "FlexibleSheet", platforms: [ .iOS(.v14), .macOS(.v11) ], products: [ // Products define the executables and libraries a package produces, and make them visible to other packages. .library( name: "FlexibleSheet", targets: ["FlexibleSheet"]) ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages this package depends on. .target( name: "FlexibleSheet", dependencies: []) // .testTarget( // name: "FlexibleSheetTests", // dependencies: ["FlexibleSheet"]), ] )
34.333333
117
0.596646
161af56b5b2be899429d189496dfdb25cb7b9c12
31,181
// // Config.swift // AssetImportKit // // Created by Eugene Bokhan on 2/11/18. // Copyright © 2018 Eugene Bokhan. All rights reserved. // import Foundation import scene import postprocess /** Enables time measurements. * * If enabled, measures the time needed for each part of the loading * process (i.e. IO time, importing, postprocessing, ..) and dumps * these timings to the DefaultLogger. See the @link perf Performance * Page@endlink for more information on this topic. * * Property type: bool. Default value: false. */ public let AI_CONFIG_GLOB_MEASURE_TIME = "GLOB_MEASURE_TIME" // --------------------------------------------------------------------------- /** Global setting to disable generation of skeleton dummy meshes * * Skeleton dummy meshes are generated as a visualization aid in cases which * the input data contains no geometry, but only animation data. * Property data type: bool. Default value: false */ // --------------------------------------------------------------------------- public let AI_CONFIG_IMPORT_NO_SKELETON_MESHES = "IMPORT_NO_SKELETON_MESHES" // --------------------------------------------------------------------------- /** Set Assimp's multithreading policy. * * This setting is ignored if Assimp was built without boost.thread * support (ASSIMP_BUILD_NO_THREADING, which is implied by ASSIMP_BUILD_BOOST_WORKAROUND). * Possible values are: -1 to let Assimp decide what to do, 0 to disable * multithreading entirely and any number larger than 0 to force a specific * number of threads. Assimp is always free to ignore this settings, which is * merely a hint. Usually, the default value (-1) will be fine. However, if * Assimp is used concurrently from multiple user threads, it might be useful * to limit each Importer instance to a specific number of cores. * * For more information, see the @link threading Threading page@endlink. * Property type: int, default value: -1. */ public let AI_CONFIG_GLOB_MULTITHREADING = "GLOB_MULTITHREADING" // ########################################################################### // POST PROCESSING SETTINGS // Various stuff to fine-tune the behavior of a specific post processing step. // ########################################################################### // --------------------------------------------------------------------------- /** Maximum bone count per mesh for the SplitbyBoneCount step. * * Meshes are split until the maximum number of bones is reached. The default * value is AI_SBBC_DEFAULT_MAX_BONES, which may be altered at * compile-time. * Property data type: integer. */ // --------------------------------------------------------------------------- public let AI_CONFIG_PP_SBBC_MAX_BONES = "PP_SBBC_MAX_BONES" // default limit for bone count public let AI_SBBC_DEFAULT_MAX_BONES = UInt32(60) // --------------------------------------------------------------------------- /** Specifies the maximum angle that may be between two vertex tangents * that their tangents and bi-tangents are smoothed. * * This applies to the CalcTangentSpace-Step. The angle is specified * in degrees. The maximum value is 175. * Property type: float. Default value: 45 degrees */ public let AI_CONFIG_PP_CT_MAX_SMOOTHING_ANGLE = "PP_CT_MAX_SMOOTHING_ANGLE" // --------------------------------------------------------------------------- /** Source UV channel for tangent space computation. * * The specified channel must exist or an error will be raised. * Property type: integer. Default value: 0 */ // --------------------------------------------------------------------------- public let AI_CONFIG_PP_CT_TEXTURE_CHANNEL_INDEX = "PP_CT_TEXTURE_CHANNEL_INDEX" // --------------------------------------------------------------------------- /** Specifies the maximum angle that may be between two face normals * at the same vertex position that their are smoothed together. * * Sometimes referred to as 'crease angle'. * This applies to the GenSmoothNormals-Step. The angle is specified * in degrees, so 180 is PI. The default value is 175 degrees (all vertex * normals are smoothed). The maximum value is 175, too. Property type: float. * Warning: setting this option may cause a severe loss of performance. The * performance is unaffected if the #AI_CONFIG_FAVOUR_SPEED flag is set but * the output quality may be reduced. */ public let AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE = "PP_GSN_MAX_SMOOTHING_ANGLE" // --------------------------------------------------------------------------- /** Sets the colormap (= palette) to be used to decode embedded * textures in MDL (Quake or 3DGS) files. * * This must be a valid path to a file. The file is 768 (256*3) bytes * large and contains RGB triplets for each of the 256 palette entries. * The default value is colormap.lmp. If the file is not found, * a default palette (from Quake 1) is used. * Property type: string. */ public let AI_CONFIG_IMPORT_MDL_COLORMAP = "IMPORT_MDL_COLORMAP" // --------------------------------------------------------------------------- /** Configures the #aiProcess_RemoveRedundantMaterials step to * keep materials matching a name in a given list. * * This is a list of 1 to n strings, ' ' serves as delimiter character. * Identifiers containing whitespaces must be enclosed in *single* * quotation marks. For example:<tt> * "keep-me and_me_to anotherMaterialToBeKept \'name with whitespace\'"</tt>. * If a material matches on of these names, it will not be modified or * removed by the postprocessing step nor will other materials be replaced * by a reference to it. <br> * This option might be useful if you are using some magic material names * to pass additional semantics through the content pipeline. This ensures * they won't be optimized away, but a general optimization is still * performed for materials not contained in the list. * Property type: String. Default value: n/a * @note Linefeeds, tabs or carriage returns are treated as whitespace. * Material names are case sensitive. */ public let AI_CONFIG_PP_RRM_EXCLUDE_LIST = "PP_RRM_EXCLUDE_LIST" // --------------------------------------------------------------------------- /** Configures the #aiProcess_PretransformVertices step to * keep the scene hierarchy. Meshes are moved to worldspace, but * no optimization is performed (read: meshes with equal materials are not * joined. The total number of meshes won't change). * * This option could be of use for you if the scene hierarchy contains * important additional information which you intend to parse. * For rendering, you can still render all meshes in the scene without * any transformations. * Property type: bool. Default value: false. */ public let AI_CONFIG_PP_PTV_KEEP_HIERARCHY = "PP_PTV_KEEP_HIERARCHY" // --------------------------------------------------------------------------- /** Configures the #aiProcess_PretransformVertices step to normalize * all vertex components into the [-1,1] range. That is, a bounding box * for the whole scene is computed, the maximum component is taken and all * meshes are scaled appropriately (uniformly of course!). * This might be useful if you don't know the spatial dimension of the input * data*/ public let AI_CONFIG_PP_PTV_NORMALIZE = "PP_PTV_NORMALIZE" // --------------------------------------------------------------------------- /** Configures the #aiProcess_PretransformVertices step to use * a users defined matrix as the scene root node transformation before * transforming vertices. * Property type: bool. Default value: false. */ public let AI_CONFIG_PP_PTV_ADD_ROOT_TRANSFORMATION = "PP_PTV_ADD_ROOT_TRANSFORMATION" // --------------------------------------------------------------------------- /** Configures the #aiProcess_PretransformVertices step to use * a users defined matrix as the scene root node transformation before * transforming vertices. This property correspond to the 'a1' component * of the transformation matrix. * Property type: aiMatrix4x4. */ public let AI_CONFIG_PP_PTV_ROOT_TRANSFORMATION = "PP_PTV_ROOT_TRANSFORMATION" // --------------------------------------------------------------------------- /** Configures the #aiProcess_FindDegenerates step to * remove degenerated primitives from the import - immediately. * * The default behaviour converts degenerated triangles to lines and * degenerated lines to points. See the documentation to the * #aiProcess_FindDegenerates step for a detailed example of the various ways * to get rid of these lines and points if you don't want them. * Property type: bool. Default value: false. */ public let AI_CONFIG_PP_FD_REMOVE = "PP_FD_REMOVE" // --------------------------------------------------------------------------- /** Configures the #aiProcess_OptimizeGraph step to preserve nodes * matching a name in a given list. * * This is a list of 1 to n strings, ' ' serves as delimiter character. * Identifiers containing whitespaces must be enclosed in *single* * quotation marks. For example:<tt> * "keep-me and_me_to anotherNodeToBeKept \'name with whitespace\'"</tt>. * If a node matches on of these names, it will not be modified or * removed by the postprocessing step.<br> * This option might be useful if you are using some magic node names * to pass additional semantics through the content pipeline. This ensures * they won't be optimized away, but a general optimization is still * performed for nodes not contained in the list. * Property type: String. Default value: n/a * @note Linefeeds, tabs or carriage returns are treated as whitespace. * Node names are case sensitive. */ public let AI_CONFIG_PP_OG_EXCLUDE_LIST = "PP_OG_EXCLUDE_LIST" // --------------------------------------------------------------------------- /** Set the maximum number of triangles in a mesh. * * This is used by the "SplitLargeMeshes" PostProcess-Step to determine * whether a mesh must be split or not. * @note The default value is AI_SLM_DEFAULT_MAX_TRIANGLES * Property type: integer. */ public let AI_CONFIG_PP_SLM_TRIANGLE_LIMIT = "PP_SLM_TRIANGLE_LIMIT" // default value for AI_CONFIG_PP_SLM_TRIANGLE_LIMIT public let AI_SLM_DEFAULT_MAX_TRIANGLES = UInt32(1000000) // --------------------------------------------------------------------------- /** Set the maximum number of vertices in a mesh. * * This is used by the "SplitLargeMeshes" PostProcess-Step to determine * whether a mesh must be split or not. * @note The default value is AI_SLM_DEFAULT_MAX_VERTICES * Property type: integer. */ public let AI_CONFIG_PP_SLM_VERTEX_LIMIT = "PP_SLM_VERTEX_LIMIT" // default value for AI_CONFIG_PP_SLM_VERTEX_LIMIT public let AI_SLM_DEFAULT_MAX_VERTICES = UInt32(1000000) // --------------------------------------------------------------------------- /** Set the maximum number of bones affecting a single vertex * * This is used by the #aiProcess_LimitBoneWeights PostProcess-Step. * @note The default value is AI_LBW_MAX_WEIGHTS * Property type: integer.*/ public let AI_CONFIG_PP_LBW_MAX_WEIGHTS = "PP_LBW_MAX_WEIGHTS" // default value for AI_CONFIG_PP_LBW_MAX_WEIGHTS public let AI_LMW_MAX_WEIGHTS = UInt32(0x4) // !! AI_LMW_MAX_WEIGHTS // --------------------------------------------------------------------------- /** Lower the deboning threshold in order to remove more bones. * * This is used by the #aiProcess_Debone PostProcess-Step. * @note The default value is AI_DEBONE_THRESHOLD * Property type: float.*/ public let AI_CONFIG_PP_DB_THRESHOLD = "PP_DB_THRESHOLD" // default value for AI_CONFIG_PP_LBW_MAX_WEIGHTS public let AI_DEBONE_THRESHOLD = UInt32(1.0) // !! AI_DEBONE_THRESHOLD // --------------------------------------------------------------------------- /** Require all bones qualify for deboning before removing any * * This is used by the #aiProcess_Debone PostProcess-Step. * @note The default value is 0 * Property type: bool.*/ public let AI_CONFIG_PP_DB_ALL_OR_NONE = "PP_DB_ALL_OR_NONE" /** Default value for the #AI_CONFIG_PP_ICL_PTCACHE_SIZE property */ public let PP_ICL_PTCACHE_SIZE = UInt32(12) // --------------------------------------------------------------------------- /** Set the size of the post-transform vertex cache to optimize the * vertices for. This configures the #aiProcess_ImproveCacheLocality step. * * The size is given in vertices. Of course you can't know how the vertex * format will exactly look like after the import returns, but you can still * guess what your meshes will probably have. * @note The default value is #PP_ICL_PTCACHE_SIZE. That results in slight * performance improvements for most nVidia/AMD cards since 2002. * Property type: integer. */ public let AI_CONFIG_PP_ICL_PTCACHE_SIZE = "PP_ICL_PTCACHE_SIZE" // --------------------------------------------------------------------------- /** Input parameter to the #aiProcess_RemoveComponent step: * Specifies the parts of the data structure to be removed. * * See the documentation to this step for further details. The property * is expected to be an integer, a bitwise combination of the * #aiComponent flags defined above in this header. The default * value is 0. Important: if no valid mesh is remaining after the * step has been executed (e.g you thought it was funny to specify ALL * of the flags defined above) the import FAILS. Mainly because there is * no data to work on anymore ... */ // Remove a specific color channel 'n' public func aiComponent_COLORSn(_ n: UInt32) -> UInt32 { return UInt32(1) << (n + UInt32(20)) } // Remove a specific UV channel 'n' public func aiComponent_TEXCOORDSn(_ n: UInt32) -> UInt32 { return UInt32(1) << (n + UInt32(25)) } public let AI_CONFIG_PP_RVC_FLAGS = "PP_RVC_FLAGS" // --------------------------------------------------------------------------- /** Input parameter to the #aiProcess_SortByPType step: * Specifies which primitive types are removed by the step. * * This is a bitwise combination of the aiPrimitiveType flags. * Specifying all of them is illegal, of course. A typical use would * be to exclude all line and point meshes from the import. This * is an integer property, its default value is 0. */ public let AI_CONFIG_PP_SBP_REMOVE = "PP_SBP_REMOVE" // --------------------------------------------------------------------------- /** Input parameter to the #aiProcess_FindInvalidData step: * Specifies the floating-point accuracy for animation values. The step * checks for animation tracks where all frame values are absolutely equal * and removes them. This tweakable controls the epsilon for floating-point * comparisons - two keys are considered equal if the invariant * abs(n0-n1)>epsilon holds true for all vector respectively quaternion * components. The default value is 0.f - comparisons are exact then. */ public let AI_CONFIG_PP_FID_ANIM_ACCURACY = "PP_FID_ANIM_ACCURACY" // TransformUVCoords evaluates UV scalings public let AI_UVTRAFO_SCALING = UInt32(0x1) // TransformUVCoords evaluates UV rotations public let AI_UVTRAFO_ROTATION = UInt32(0x2) // TransformUVCoords evaluates UV translation public let AI_UVTRAFO_TRANSLATION = UInt32(0x4) // Everything baked together -> default value public let AI_UVTRAFO_ALL = ( AI_UVTRAFO_SCALING | AI_UVTRAFO_ROTATION | AI_UVTRAFO_TRANSLATION ) // --------------------------------------------------------------------------- /** Input parameter to the #aiProcess_TransformUVCoords step: * Specifies which UV transformations are evaluated. * * This is a bitwise combination of the AI_UVTRAFO_XXX flags (integer * property, of course). By default all transformations are enabled * (AI_UVTRAFO_ALL). */ public let AI_CONFIG_PP_TUV_EVALUATE = "PP_TUV_EVALUATE" // --------------------------------------------------------------------------- /** A hint to assimp to favour speed against import quality. * * Enabling this option may result in faster loading, but it needn't. * It represents just a hint to loaders and post-processing steps to use * faster code paths, if possible. * This property is expected to be an integer, != 0 stands for true. * The default value is 0. */ public let AI_CONFIG_FAVOUR_SPEED = "FAVOUR_SPEED" // ########################################################################### // IMPORTER SETTINGS // Various stuff to fine-tune the behaviour of specific importer plugins. // ########################################################################### // --------------------------------------------------------------------------- /** Set whether the fbx importer will merge all geometry layers present * in the source file or take only the first. * * The default value is true (1) * Property type: bool */ public let AI_CONFIG_IMPORT_FBX_READ_ALL_GEOMETRY_LAYERS = "IMPORT_FBX_READ_ALL_GEOMETRY_LAYERS" // --------------------------------------------------------------------------- /** Set whether the fbx importer will read all materials present in the * source file or take only the referenced materials. * * This is void unless IMPORT_FBX_READ_MATERIALS=1. * * The default value is false (0) * Property type: bool */ public let AI_CONFIG_IMPORT_FBX_READ_ALL_MATERIALS = "IMPORT_FBX_READ_ALL_MATERIALS" // --------------------------------------------------------------------------- /** Set whether the fbx importer will read materials. * * The default value is true (1) * Property type: bool */ public let AI_CONFIG_IMPORT_FBX_READ_MATERIALS = "IMPORT_FBX_READ_MATERIALS" // --------------------------------------------------------------------------- /** Set whether the fbx importer will read cameras. * * The default value is true (1) * Property type: bool */ public let AI_CONFIG_IMPORT_FBX_READ_CAMERAS = "IMPORT_FBX_READ_CAMERAS" // --------------------------------------------------------------------------- /** Set whether the fbx importer will read light sources. * * The default value is true (1) * Property type: bool */ public let AI_CONFIG_IMPORT_FBX_READ_LIGHTS = "IMPORT_FBX_READ_LIGHTS" // --------------------------------------------------------------------------- /** Set whether the fbx importer will read animations. * * The default value is true (1) * Property type: bool */ public let AI_CONFIG_IMPORT_FBX_READ_ANIMATIONS = "IMPORT_FBX_READ_ANIMATIONS" // --------------------------------------------------------------------------- /** Set whether the fbx importer will act in strict mode in which only * FBX 2013 is supported and any other sub formats are rejected. FBX 2013 * is the primary target for the importer, so this format is best * supported and well-tested. * * The default value is false (0) * Property type: bool */ public let AI_CONFIG_IMPORT_FBX_STRICT_MODE = "IMPORT_FBX_STRICT_MODE" // --------------------------------------------------------------------------- /** Set whether the fbx importer will preserve pivot points for * transformations (as extra nodes). If set to false, pivots and offsets * will be evaluated whenever possible. * * The default value is true (1) * Property type: bool */ public let AI_CONFIG_IMPORT_FBX_PRESERVE_PIVOTS = "IMPORT_FBX_PRESERVE_PIVOTS" // --------------------------------------------------------------------------- /** Specifies whether the importer will drop empty animation curves or * animation curves which match the bind pose transformation over their * entire defined range. * * The default value is true (1) * Property type: bool */ public let AI_CONFIG_IMPORT_FBX_OPTIMIZE_EMPTY_ANIMATION_CURVES = "IMPORT_FBX_OPTIMIZE_EMPTY_ANIMATION_CURVES" // --------------------------------------------------------------------------- /** Set the vertex animation keyframe to be imported * * ASSIMP does not support vertex keyframes (only bone animation is supported). * The library reads only one frame of models with vertex animations. * By default this is the first frame. * \note The default value is 0. This option applies to all importers. * However, it is also possible to override the global setting * for a specific loader. You can use the AI_CONFIG_IMPORT_XXX_KEYFRAME * options (where XXX is a placeholder for the file format for which you * want to override the global setting). * Property type: integer. */ public let AI_CONFIG_IMPORT_GLOBAL_KEYFRAME = "IMPORT_GLOBAL_KEYFRAME" public let AI_CONFIG_IMPORT_MD3_KEYFRAME = "IMPORT_MD3_KEYFRAME" public let AI_CONFIG_IMPORT_MD2_KEYFRAME = "IMPORT_MD2_KEYFRAME" public let AI_CONFIG_IMPORT_MDL_KEYFRAME = "IMPORT_MDL_KEYFRAME" public let AI_CONFIG_IMPORT_MDC_KEYFRAME = "IMPORT_MDC_KEYFRAME" public let AI_CONFIG_IMPORT_SMD_KEYFRAME = "IMPORT_SMD_KEYFRAME" public let AI_CONFIG_IMPORT_UNREAL_KEYFRAME = "IMPORT_UNREAL_KEYFRAME" // --------------------------------------------------------------------------- /** Configures the AC loader to collect all surfaces which have the * "Backface cull" flag set in separate meshes. * * Property type: bool. Default value: true. */ public let AI_CONFIG_IMPORT_AC_SEPARATE_BFCULL = "IMPORT_AC_SEPARATE_BFCULL" // --------------------------------------------------------------------------- /** Configures whether the AC loader evaluates subdivision surfaces ( * indicated by the presence of the 'subdiv' attribute in the file). By * default, Assimp performs the subdivision using the standard * Catmull-Clark algorithm * * * Property type: bool. Default value: true. */ public let AI_CONFIG_IMPORT_AC_EVAL_SUBDIVISION = "IMPORT_AC_EVAL_SUBDIVISION" // --------------------------------------------------------------------------- /** Configures the UNREAL 3D loader to separate faces with different * surface flags (e.g. two-sided vs. single-sided). * * * Property type: bool. Default value: true. */ public let AI_CONFIG_IMPORT_UNREAL_HANDLE_FLAGS = "UNREAL_HANDLE_FLAGS" // --------------------------------------------------------------------------- /** Configures the terragen import plugin to compute uv's for * terrains, if not given. Furthermore a default texture is assigned. * * UV coordinates for terrains are so simple to compute that you'll usually * want to compute them on your own, if you need them. This option is intended * for model viewers which want to offer an easy way to apply textures to * terrains. * * Property type: bool. Default value: false. */ public let AI_CONFIG_IMPORT_TER_MAKE_UVS = "IMPORT_TER_MAKE_UVS" // --------------------------------------------------------------------------- /** Configures the ASE loader to always reconstruct normal vectors * basing on the smoothing groups loaded from the file. * * Some ASE files have carry invalid normals, other don't. * * Property type: bool. Default value: true. */ public let AI_CONFIG_IMPORT_ASE_RECONSTRUCT_NORMALS = "IMPORT_ASE_RECONSTRUCT_NORMALS" // --------------------------------------------------------------------------- /** Configures the M3D loader to detect and process multi-part * Quake player models. * * These models usually consist of 3 files, lower.md3, upper.md3 and * head.md3. If this property is set to true, Assimp will try to load and * combine all three files if one of them is loaded. * Property type: bool. Default value: true. */ public let AI_CONFIG_IMPORT_MD3_HANDLE_MULTIPART = "IMPORT_MD3_HANDLE_MULTIPART" // --------------------------------------------------------------------------- /** Tells the MD3 loader which skin files to load. * * When loading MD3 files, Assimp checks whether a file * <md3_file_name>_<skin_name>.skin is existing. These files are used by * Quake III to be able to assign different skins (e.g. red and blue team) * to models. 'default', 'red', 'blue' are typical skin names. * Property type: String. Default value: "default". */ public let AI_CONFIG_IMPORT_MD3_SKIN_NAME = "IMPORT_MD3_SKIN_NAME" // --------------------------------------------------------------------------- /** Specify the Quake 3 shader file to be used for a particular * MD3 file. This can also be a search path. * * By default Assimp's behaviour is as follows: If a MD3 file * <tt><any_path>/models/<any_q3_subdir>/<model_name>/<file_name>.md3</tt> is * loaded, the library tries to locate the corresponding shader file in * <tt><any_path>/scripts/<model_name>.shader</tt>. This property overrides this * behaviour. It can either specify a full path to the shader to be loaded * or alternatively the path (relative or absolute) to the directory where * the shaders for all MD3s to be loaded reside. Assimp attempts to open * <tt><dir>/<model_name>.shader</tt> first, <tt><dir>/<file_name>.shader</tt> * is the fallback file. Note that <dir> should have a terminal (back)slash. * Property type: String. Default value: n/a. */ public let AI_CONFIG_IMPORT_MD3_SHADER_SRC = "IMPORT_MD3_SHADER_SRC" // --------------------------------------------------------------------------- /** Configures the LWO loader to load just one layer from the model. * * LWO files consist of layers and in some cases it could be useful to load * only one of them. This property can be either a string - which specifies * the name of the layer - or an integer - the index of the layer. If the * property is not set the whole LWO model is loaded. Loading fails if the * requested layer is not available. The layer index is zero-based and the * layer name may not be empty.<br> * Property type: Integer. Default value: all layers are loaded. */ public let AI_CONFIG_IMPORT_LWO_ONE_LAYER_ONLY = "IMPORT_LWO_ONE_LAYER_ONLY" // --------------------------------------------------------------------------- /** Configures the MD5 loader to not load the MD5ANIM file for * a MD5MESH file automatically. * * The default strategy is to look for a file with the same name but the * MD5ANIM extension in the same directory. If it is found, it is loaded * and combined with the MD5MESH file. This configuration option can be * used to disable this behaviour. * * * Property type: bool. Default value: false. */ public let AI_CONFIG_IMPORT_MD5_NO_ANIM_AUTOLOAD = "IMPORT_MD5_NO_ANIM_AUTOLOAD" // --------------------------------------------------------------------------- /** Defines the begin of the time range for which the LWS loader * evaluates animations and computes aiNodeAnim's. * * Assimp provides full conversion of LightWave's envelope system, including * pre and post conditions. The loader computes linearly subsampled animation * chanels with the frame rate given in the LWS file. This property defines * the start time. Note: animation channels are only generated if a node * has at least one envelope with more tan one key assigned. This property. * is given in frames, '0' is the first frame. By default, if this property * is not set, the importer takes the animation start from the input LWS * file ('FirstFrame' line)<br> * Property type: Integer. Default value: taken from file. * * AI_CONFIG_IMPORT_LWS_ANIM_END - end of the imported time range */ public let AI_CONFIG_IMPORT_LWS_ANIM_START = "IMPORT_LWS_ANIM_START" public let AI_CONFIG_IMPORT_LWS_ANIM_END = "IMPORT_LWS_ANIM_END" // --------------------------------------------------------------------------- /** Defines the output frame rate of the IRR loader. * * IRR animations are difficult to convert for Assimp and there will * always be a loss of quality. This setting defines how many keys per second * are returned by the converter. * Property type: integer. Default value: 100 */ public let AI_CONFIG_IMPORT_IRR_ANIM_FPS = "IMPORT_IRR_ANIM_FPS" // --------------------------------------------------------------------------- /** Ogre Importer will try to find referenced materials from this file. * * Ogre meshes reference with material names, this does not tell Assimp the file * where it is located in. Assimp will try to find the source file in the following * order: <material-name>.material, <mesh-filename-base>.material and * lastly the material name defined by this config property. * Property type: String. Default value: Scene.material. */ public let AI_CONFIG_IMPORT_OGRE_MATERIAL_FILE = "IMPORT_OGRE_MATERIAL_FILE" // --------------------------------------------------------------------------- /** Ogre Importer detect the texture usage from its filename. * * Ogre material texture units do not define texture type, the textures usage * depends on the used shader or Ogres fixed pipeline. If this config property * is true Assimp will try to detect the type from the textures filename postfix: * _n, _nrm, _nrml, _normal, _normals and _normalmap for normal map, _s, _spec, * _specular and _specularmap for specular map, _l, _light, _lightmap, _occ * and _occlusion for light map, _disp and _displacement for displacement map. * The matching is case insensitive. Post fix is taken between last "_" and last ".". * Default behavior is to detect type from lower cased texture unit name by * matching against: normalmap, specularmap, lightmap and displacementmap. * For both cases if no match is found aiTextureType_DIFFUSE is used. * <br> * Property type: Bool. Default value: false. */ public let AI_CONFIG_IMPORT_OGRE_TEXTURETYPE_FROM_FILENAME = "IMPORT_OGRE_TEXTURETYPE_FROM_FILENAME" /** Specifies whether the IFC loader skips over IfcSpace elements. * * IfcSpace elements (and their geometric representations) are used to * represent, well, free space in a building storey.<br> * Property type: Bool. Default value: true. */ public let AI_CONFIG_IMPORT_IFC_SKIP_SPACE_REPRESENTATIONS = "IMPORT_IFC_SKIP_SPACE_REPRESENTATIONS" // --------------------------------------------------------------------------- /** Specifies whether the IFC loader skips over * shape representations of type 'Curve2D'. * * A lot of files contain both a faceted mesh representation and a outline * with a presentation type of 'Curve2D'. Currently Assimp doesn't convert those, * so turning this option off just clutters the log with errors.<br> * Property type: Bool. Default value: true. */ public let AI_CONFIG_IMPORT_IFC_SKIP_CURVE_REPRESENTATIONS = "IMPORT_IFC_SKIP_CURVE_REPRESENTATIONS" // --------------------------------------------------------------------------- /** Specifies whether the IFC loader will use its own, custom triangulation * algorithm to triangulate wall and floor meshes. * * If this property is set to false, walls will be either triangulated by * #aiProcess_Triangulate or will be passed through as huge polygons with * faked holes (i.e. holes that are connected with the outer boundary using * a dummy edge). It is highly recommended to set this property to true * if you want triangulated data because #aiProcess_Triangulate is known to * have problems with the kind of polygons that the IFC loader spits out for * complicated meshes. * Property type: Bool. Default value: true. */ public let AI_CONFIG_IMPORT_IFC_CUSTOM_TRIANGULATION = "IMPORT_IFC_CUSTOM_TRIANGULATION" public let AI_CONFIG_IMPORT_COLLADA_IGNORE_UP_DIRECTION = "IMPORT_COLLADA_IGNORE_UP_DIRECTION"
45.653001
110
0.654758
22c525ad79c58d0c5fbc713f691503a1223dc6e6
260
// // Coordinator.swift // Weather // // Created by akashial on 13/03/22. // import UIKit protocol Coordinator { var navigationController: UINavigationController { get set } var childCoordinators: [Coordinator] { get set } func start() }
16.25
64
0.673077
2129b9f32af85dfa3b1f0302ba22735856f37f09
513
// // GallerySettingsViewModelProtocol.swift // RedditGallery // // Created by Andrea Cerra on 7/11/20. // Copyright © 2020 Andrea Cerra. All rights reserved. // import Foundation import RxSwift protocol GallerySettingsViewModelProtocol { var imageCache: Observable<Double> { get } var dataCache: Observable<Double> { get } /// Method used for notify the ViewAppear func eventViewAppeared() /// Method for delete all the local cache data func deleteCacheRequested() }
22.304348
55
0.705653
d9863a6b278a1be9226a66781283673ded2ba56b
7,266
// // AppNavigation.swift // Core // // Created by Nykolas Mayko Maia Barbosa on 30/11/21. // import UIKit public final class AppNavigation { public static let shared: AppNavigation = AppNavigation() public let navigationController: UINavigationController = UINavigationController() private var currentJourney: Journey? private var rawDeeplink: String? private var handlers: Dictionary<Journey, ModuleHandler> = [:] // MARK: - Initializer private init () {} // MARK: - Action Functions func setRootViewController(_ viewController: UIViewController, from currentViewController: UIViewController? = nil, animated: Bool = false) { if currentViewController?.navigationController != navigationController { currentViewController?.dismiss(animated: animated) } if let rootVC = navigationController.viewControllers.first, type(of: rootVC) == type(of: viewController) { popToViewControllerWithType(type(of: viewController)) } else { navigationController.setViewControllers([viewController], animated: animated) } } func push(_ viewController: UIViewController, from currrentViewController: UIViewController? = nil, animated: Bool = true) { if currrentViewController?.navigationController != navigationController { currrentViewController?.dismiss(animated: animated) } if let currrentViewController = currrentViewController { popToViewControllerWithType(type(of: currrentViewController)) } navigationController.pushViewController(viewController, animated: animated) } public func push(_ journey: Journey, from currentViewController: UIViewController?, animated: Bool = true) { push(start(journey), from: currentViewController, animated: animated) } public func popViewController(animated: Bool = true) { navigationController.popViewController(animated: animated) } @discardableResult public func popToViewControllerWithType<T: UIViewController>(_ type: T.Type) -> Array<UIViewController>? { return navigationController.popToViewControllerWithType(T.self) } public func present(_ viewController: UIViewController, animated: Bool = true, completion: (() -> Void)? = nil) { navigationController.present(viewController, animated: animated, completion: completion) } @discardableResult public func resolve(_ rawDeeplink: String?) -> Bool { guard let rawDeeplink = rawDeeplink, let deeplink = getDeeplink(from: rawDeeplink), let destinationJourney = deeplink.value, let url = deeplink.url, let handler = getHandler(from: destinationJourney) else { return false } guard handler.canStart() else { self.rawDeeplink = rawDeeplink return false } self.rawDeeplink = nil if currentJourney != destinationJourney { let deeplinkNavigation = UINavigationController(rootViewController: start(destinationJourney, with: url)) deeplinkNavigation.modalPresentationStyle = .fullScreen present(deeplinkNavigation) return true } else { // TODO: Push when the module is started return false } } public func resolveDeeplinkIfNeeded() { resolve(rawDeeplink) } public func register(_ jorneys: Array<Journey>, with stater: ModuleHandler) { jorneys.forEach{ [weak self] jorney in self?.handlers[jorney] = stater } } public func getHandler(from jorney: Journey) -> ModuleHandler? { return handlers[jorney] } public func start(_ journey: Journey, to subJourney: Journey? = nil, from currentJourney: Journey? = nil, with url: URL? = nil, baseFlowDelegate: BaseFlowDelegate = AppNavigation.shared, baseFlowDataSource: BaseFlowDataSource = AppNavigation.shared, customModuleAnalytics: Any? = nil, value: Any? = nil) -> UIViewController { guard let handler = getHandler(from: journey) else { return UIViewController() } self.currentJourney = currentJourney == nil ? journey : currentJourney! return handler.start(from: url, with: baseFlowDelegate, baseFlowDataSource, customModuleAnalytics, subJourney, value) } public func show(_ journeys: Array<Journey>, from currentViewController: UIViewController? = nil, animated: Bool) { let journeysControllers = journeys.compactMap{ [weak self] journey -> UIViewController? in let firstModuleVC = self?.start(journey) firstModuleVC?.loadViewIfNeeded() return firstModuleVC } if journeysControllers.count > 1 { if currentViewController?.navigationController != navigationController { currentViewController?.dismiss(animated: animated) } navigationController.setViewControllers(journeysControllers, animated: animated) } else if !journeysControllers.isEmpty { setRootViewController(journeysControllers.first!, from: currentViewController, animated: animated) } } private func getDeeplink(from rawDeeplink: String) -> Deeplink<Journey>? { guard let url = URL(string: rawDeeplink), let host = url.host, let jorneyModule = getJorneyModule(from: host) else { return nil } return .init(value: jorneyModule, url: url) } private func getJorneyModule(from name: String) -> Journey? { return handlers.first{ $0.value.getName().lowercased() == name.lowercased() }?.key } } // MARK: - BaseFlowDelegate extension AppNavigation: BaseFlowDelegate { public func perform(_ action: BaseFlowDelegateAction, in viewController: UIViewController, with value: Any?) { switch action { case .finish(let journey): debugPrint("====== AppNavigation didFinish: \(journey.rawValue)") break case .goTo(let destinationJourney, let currentJourney): handleGo(to: destinationJourney, from: currentJourney, in: viewController, with: value) break case .finishCurrentAndGoTo(let destinationJourney, let currentJourney): debugPrint("====== AppNavigation didFinish: \(currentJourney.rawValue)") handleGo(to: destinationJourney, from: currentJourney, in: viewController, with: value) break } } private func handleGo(to destinationJourney: Journey, from currentJourney: Journey, in viewController: UIViewController, with value: Any?) { guard let handler = getHandler(from: currentJourney) else { return } handler.handleGo(to: destinationJourney, in: viewController, with: value) } } // MARK: - BaseFlowDataSource extension AppNavigation: BaseFlowDataSource { public func get(_ journey: Journey, from currentJourney: Journey, with baseFlowDelegate: BaseFlowDelegate, customAnalytics: Any?) -> UIViewController { guard let handler = getHandler(from: journey) else { return UIViewController() } return handler.handleGet(from: currentJourney, to: journey, with: baseFlowDelegate, analytics: customAnalytics) } }
44.851852
329
0.685934
2f72831fe0de51959d7990e96f7dd16990636900
918
// // URLoadingSystemTests.swift // URLoadingSystemTests // // Created by larryhou on 3/23/15. // Copyright (c) 2015 larryhou. All rights reserved. // import UIKit import XCTest class URLoadingSystemTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
24.810811
111
0.623094
11a44a6296a23100098205eac1cc075b824a7f88
37,742
// // UDOfflineForm.swift import Foundation import Alamofire @objc public enum UDFeedbackStatus: Int { case null case never case feedbackForm case feedbackFormAndChat var isNotOpenFeedbackForm: Bool { return self == .null || self == .never } var isOpenFeedbackForm: Bool { return self == .feedbackForm || self == .feedbackFormAndChat } } class UDOfflineForm: UIViewController, UITextFieldDelegate { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var contentView: UIView! @IBOutlet weak var scrollViewBC: NSLayoutConstraint! @IBOutlet weak var textLabel: UILabel! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var tableViewHC: NSLayoutConstraint! @IBOutlet weak var sendMessageButton: UIButton! @IBOutlet weak var sendLoader: UIActivityIndicatorView! @IBOutlet weak var sendedView: UIView! @IBOutlet weak var sendedViewBC: NSLayoutConstraint! @IBOutlet weak var sendedCornerRadiusView: UIView! @IBOutlet weak var sendedImage: UIImageView! @IBOutlet weak var sendedLabel: UILabel! @IBOutlet weak var closeButton: UIButton! var url = "" var isFromBase = false weak var usedesk: UseDeskSDK? private var configurationStyle: ConfigurationStyle = ConfigurationStyle() private var selectedIndexPath: IndexPath? = nil private var fields: [UDInfoItem] = [] private var textViewYPositionCursor: CGFloat = 0.0 private var keyboardHeight: CGFloat = 336 private var isShowKeyboard = false private var isFirstOpen = true private var previousOrientation: Orientation = .portrait private var selectedTopicIndex: Int? = nil private var dialogflowVC : DialogflowView = DialogflowView() convenience init() { let nibName: String = "UDOfflineForm" self.init(nibName: nibName, bundle: BundleId.bundle(for: nibName)) } override func viewDidLoad() { super.viewDidLoad() firstState() // Notification NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() guard !isFirstOpen else { isFirstOpen = false return } if UIScreen.main.bounds.height > UIScreen.main.bounds.width { if previousOrientation != .portrait { previousOrientation = .portrait self.view.endEditing(true) } } else { if previousOrientation != .landscape { previousOrientation = .landscape self.view.endEditing(true) } } } // MARK: - Private func firstState() { guard usedesk != nil else {return} configurationStyle = usedesk?.configurationStyle ?? ConfigurationStyle() self.view.backgroundColor = configurationStyle.chatStyle.backgroundColor scrollView.delegate = self scrollView.backgroundColor = configurationStyle.chatStyle.backgroundColor contentView.backgroundColor = configurationStyle.chatStyle.backgroundColor sendLoader.alpha = 0 configurationStyle = usedesk?.configurationStyle ?? ConfigurationStyle() title = usedesk?.callbackSettings.title ?? usedesk!.model.stringFor("Chat") navigationItem.leftBarButtonItem = UIBarButtonItem(image: configurationStyle.navigationBarStyle.backButtonImage, style: .plain, target: self, action: #selector(self.backAction)) let feedbackFormStyle = configurationStyle.feedbackFormStyle tableView.register(UINib(nibName: "UDTextAnimateTableViewCell", bundle: BundleId.thisBundle), forCellReuseIdentifier: "UDTextAnimateTableViewCell") tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 64 tableView.delegate = self tableView.dataSource = self tableView.backgroundColor = configurationStyle.chatStyle.backgroundColor textLabel.textColor = feedbackFormStyle.textColor textLabel.font = feedbackFormStyle.textFont textLabel.text = usedesk?.callbackSettings.greeting ?? usedesk!.model.stringFor("FeedbackText") sendMessageButton.backgroundColor = feedbackFormStyle.buttonColorDisabled sendMessageButton.tintColor = feedbackFormStyle.buttonTextColor sendMessageButton.titleLabel?.font = feedbackFormStyle.buttonFont sendMessageButton.isEnabled = false sendMessageButton.layer.masksToBounds = true sendMessageButton.layer.cornerRadius = feedbackFormStyle.buttonCornerRadius sendMessageButton.setTitle(usedesk!.model.stringFor("Send"), for: .normal) sendedViewBC.constant = -400 sendedCornerRadiusView.layer.cornerRadius = 13 sendedCornerRadiusView.backgroundColor = configurationStyle.chatStyle.backgroundColor sendedView.backgroundColor = configurationStyle.chatStyle.backgroundColor sendedView.layer.masksToBounds = false sendedView.layer.shadowColor = UIColor.black.cgColor sendedView.layer.shadowOpacity = 0.6 sendedView.layer.shadowOffset = CGSize.zero sendedView.layer.shadowRadius = 20.0 sendedImage.image = feedbackFormStyle.sendedImage sendedLabel.text = usedesk!.model.stringFor("FeedbackSendedMessage") closeButton.backgroundColor = feedbackFormStyle.buttonColor closeButton.tintColor = feedbackFormStyle.buttonTextColor closeButton.titleLabel?.font = feedbackFormStyle.buttonFont closeButton.layer.masksToBounds = true closeButton.layer.cornerRadius = feedbackFormStyle.buttonCornerRadius closeButton.setTitle(usedesk!.model.stringFor("Close"), for: .normal) if usedesk != nil { fields = [UDInfoItem(type: .name, value: UDTextItem(text: usedesk!.model.name)), UDInfoItem(type: .email, value: UDContactItem(contact: usedesk?.model.email ?? "")), UDInfoItem(type: .selectTopic, value: UDTextItem(text: ""))] for custom_field in usedesk!.callbackSettings.checkedCustomFields { fields.append(UDInfoItem(type: .custom, value: UDCustomFieldItem(field: custom_field))) } fields.append(UDInfoItem(type: .message, value: UDTextItem(text: ""))) } selectedIndexPath = IndexPath(row: 2, section: 0) tableView.reloadData() setHeightTables() } @objc func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { if !isShowKeyboard { isShowKeyboard = true keyboardHeight = keyboardSize.height UIView.animate(withDuration: 0.4) { self.scrollViewBC.constant = self.keyboardHeight var offsetPlus: CGFloat = 0 if self.selectedIndexPath != nil { if let cell = self.tableView.cellForRow(at: self.selectedIndexPath!) as? UDTextAnimateTableViewCell { offsetPlus = cell.frame.origin.y + cell.frame.height + self.tableView.frame.origin.y - self.scrollView.contentOffset.y } } self.view.layoutSubviews() self.view.layoutIfNeeded() if offsetPlus > (self.view.frame.height - self.keyboardHeight) { self.scrollView.contentOffset.y += offsetPlus - (self.view.frame.height - self.keyboardHeight) } } } } } @objc func keyboardWillHide(notification: NSNotification) { if isShowKeyboard { UIView.animate(withDuration: 0.4) { self.scrollViewBC.constant = 0 if self.scrollView.contentSize.height <= self.scrollView.frame.height { UIView.animate(withDuration: 0.4) { self.scrollView.contentOffset.y = 0 } } else { let offset = self.keyboardHeight - 138 UIView.animate(withDuration: 0.4) { if offset > self.scrollView.contentOffset.y { self.scrollView.contentOffset.y = 0 } else { self.scrollView.contentOffset.y -= offset } } } self.view.layoutIfNeeded() } isShowKeyboard = false } } func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView.isTracking && selectedIndexPath != nil { selectedIndexPath = nil DispatchQueue.main.async { self.tableView.reloadData() } } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func indexFieldsForType(_ type: UDNameFields) -> Int { var flag = true var index = 0 while flag && index < fields.count { if fields[index].type == type { flag = false } else { index += 1 } } return flag ? 0 : index } func showAlert(_ title: String?, text: String?) { guard usedesk != nil else {return} let alert = UIAlertController(title: title, message: text, preferredStyle: .alert) let ok = UIAlertAction(title: usedesk!.model.stringFor("Understand"), style: .default, handler: {_ in }) alert.addAction(ok) present(alert, animated: true) } func setHeightTables() { var height: CGFloat = 0 var selectedCellPositionY: CGFloat = tableView.frame.origin.y for index in 0..<fields.count { var text = "" if fields[index].type == .email { if let contactItem = fields[index].value as? UDContactItem { text = contactItem.contact } } else if let textItem = fields[index].value as? UDTextItem { text = textItem.text } else if let fieldItem = fields[index].value as? UDCustomFieldItem { text = fieldItem.field.text } if index == selectedIndexPath?.row { selectedCellPositionY += height } let minimumHeightText = "t".size(availableWidth: tableView.frame.width - 30, attributes: [NSAttributedString.Key.font : configurationStyle.feedbackFormStyle.valueFont], usesFontLeading: true).height var heightText = text.size(availableWidth: tableView.frame.width - 30, attributes: [NSAttributedString.Key.font : configurationStyle.feedbackFormStyle.valueFont], usesFontLeading: true).height heightText = heightText < minimumHeightText ? minimumHeightText : heightText height += heightText + 47 } UIView.animate(withDuration: 0.3) { self.tableViewHC.constant = height self.view.layoutIfNeeded() } let heightNavigationBar = navigationController?.navigationBar.frame.height ?? 44 let yPositionCursor = (textViewYPositionCursor + (selectedCellPositionY - scrollView.contentOffset.y)) if yPositionCursor > self.view.frame.height - heightNavigationBar - keyboardHeight - 30 { UIView.animate(withDuration: 0.3) { self.scrollView.contentOffset.y = (yPositionCursor + self.scrollView.contentOffset.y) - (self.view.frame.height - heightNavigationBar - self.keyboardHeight - 30) } } } func showSendedView() { UIView.animate(withDuration: 0.6) { self.sendedViewBC.constant = 0 self.view.layoutIfNeeded() } } func startChat(text: String) { guard usedesk != nil else { showSendedView() return } usedesk!.startWithoutGUICompanyID(companyID: usedesk!.model.companyID, chanelId: usedesk!.model.chanelId, knowledgeBaseID: usedesk!.model.knowledgeBaseID, api_token: usedesk!.model.api_token, email: usedesk!.model.email, phone: usedesk!.model.phone, url: usedesk!.model.urlWithoutPort, port: usedesk!.model.port, name: usedesk!.model.name, operatorName: usedesk!.model.operatorName, nameChat: usedesk!.model.nameChat, token: usedesk!.model.token, connectionStatus: { [weak self] success, feedbackStatus, token in guard let wSelf = self else {return} guard wSelf.usedesk != nil else {return} if wSelf.usedesk!.closureStartBlock != nil { wSelf.usedesk!.closureStartBlock!(success, feedbackStatus, token) } if !success && feedbackStatus == .feedbackForm { wSelf.showSendedView() } else { if wSelf.navigationController?.visibleViewController != wSelf.dialogflowVC { DispatchQueue.main.async(execute: { wSelf.dialogflowVC.usedesk = wSelf.usedesk wSelf.dialogflowVC.isFromBase = wSelf.isFromBase wSelf.dialogflowVC.isFromOfflineForm = true wSelf.dialogflowVC.delegate = self wSelf.usedesk?.uiManager?.pushViewController(wSelf.dialogflowVC) wSelf.dialogflowVC.updateChat() wSelf.usedesk?.sendMessage(text) if let index = wSelf.navigationController?.viewControllers.firstIndex(of: wSelf) { wSelf.navigationController?.viewControllers.remove(at: index) } }) } } }, errorStatus: { [weak self] error, description in guard let wSelf = self else {return} guard wSelf.usedesk != nil else {return} if wSelf.usedesk!.closureErrorBlock != nil { wSelf.usedesk!.closureErrorBlock!(error, description) } wSelf.close() }) } @objc func backAction() { if isFromBase { usedesk?.closeChat() navigationController?.popViewController(animated: true) } else { usedesk?.releaseChat() dismiss(animated: true) } } // MARK: - IB Actions @IBAction func sendMessage(_ sender: Any) { guard usedesk != nil else {return} sendLoader.alpha = 1 sendLoader.startAnimating() sendMessageButton.setTitle("", for: .normal) let email = (fields[indexFieldsForType(.email)].value as? UDContactItem)?.contact ?? "" let name = (fields[indexFieldsForType(.name)].value as? UDTextItem)?.text ?? (usedesk?.model.name ?? "") let topic = (fields[indexFieldsForType(.selectTopic)].value as? UDTextItem)?.text ?? "" var isValidTopic = true if usedesk!.callbackSettings.isRequiredTopic { if topic == "" { isValidTopic = false } } var customFields: [UDCallbackCustomField] = [] var isValidFields = true var indexErrorFields: [Int] = [] for index in 3..<fields.count { if let fieldItem = fields[index].value as? UDCustomFieldItem { if fieldItem.field.text != "" { customFields.append(fieldItem.field) } else { if fieldItem.field.isRequired { isValidFields = false fieldItem.field.isValid = false fields[index].value = fieldItem indexErrorFields.append(index) } } } } if email.udIsValidEmail() && name != "" && isValidTopic && isValidFields { self.view.endEditing(true) if let message = fields[indexFieldsForType(.message)].value as? UDTextItem { usedesk!.sendOfflineForm(name: name, email: email, message: message.text, topic: topic, fields: customFields) { [weak self] (result) in guard let wSelf = self else {return} if result { if wSelf.usedesk != nil { if wSelf.usedesk!.callbackSettings.type == .always_and_chat { var text = name + "\n" + email if topic != "" { text += "\n" + topic } for field in customFields { text += "\n" + field.text } text += "\n" + message.text wSelf.startChat(text: text) } else { wSelf.sendLoader.alpha = 0 wSelf.sendLoader.stopAnimating() wSelf.showSendedView() } } } } errorStatus: { [weak self] (_, _) in guard let wSelf = self else {return} wSelf.sendLoader.alpha = 0 wSelf.sendLoader.stopAnimating() wSelf.showAlert(wSelf.usedesk!.model.stringFor("Error"), text: wSelf.usedesk!.model.stringFor("ServerError")) } } } else { selectedIndexPath = nil if !email.udIsValidEmail() { fields[indexFieldsForType(.email)].value = UDContactItem(contact: email, isValid: false) selectedIndexPath = IndexPath(row: 1, section: 0) } if !isValidTopic { if let topic = fields[indexFieldsForType(.selectTopic)].value as? UDTextItem { fields[indexFieldsForType(.selectTopic)].value = UDTextItem(text: topic.text, isValid: false) } } if !isValidFields { selectedIndexPath = IndexPath(row: indexErrorFields[0], section: 0) } tableView.reloadData() sendLoader.alpha = 0 sendLoader.stopAnimating() sendMessageButton.setTitle(usedesk!.model.stringFor("Send"), for: .normal) } } @IBAction func close(_ sender: Any) { if isFromBase { usedesk?.closeChat() navigationController?.popViewController(animated: true) } else { usedesk?.releaseChat() self.dismiss(animated: true) } } // MARK: - Methods Cells func createNameCell(indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "UDTextAnimateTableViewCell", for: indexPath) as! UDTextAnimateTableViewCell cell.configurationStyle = usedesk?.configurationStyle ?? ConfigurationStyle() if let nameClient = fields[indexPath.row].value as? UDTextItem { if usedesk != nil { let isValid = nameClient.text == "" && indexPath != selectedIndexPath ? false : true var title = usedesk!.model.stringFor("Name") var attributedTitleString: NSMutableAttributedString? = nil var text = nameClient.text var attributedTextString: NSMutableAttributedString? = nil attributedTitleString = NSMutableAttributedString() attributedTitleString!.append(NSAttributedString(string: title, attributes: [NSAttributedString.Key.font : usedesk!.configurationStyle.feedbackFormStyle.headerFont, NSAttributedString.Key.foregroundColor : usedesk!.configurationStyle.feedbackFormStyle.headerColor])) attributedTitleString!.append(NSAttributedString(string: " *", attributes: [NSAttributedString.Key.font : usedesk!.configurationStyle.feedbackFormStyle.headerFont, NSAttributedString.Key.foregroundColor : usedesk!.configurationStyle.feedbackFormStyle.headerSelectedColor])) if !isValid { attributedTextString = attributedTitleString text = title title = usedesk!.model.stringFor("MandatoryField") attributedTitleString = nil } cell.setCell(title: title, titleAttributed: attributedTitleString, text: text, textAttributed: attributedTextString, indexPath: indexPath, isValid: isValid, isTitleErrorState: !isValid, isLimitLengthText: false) } } cell.delegate = self if indexPath == selectedIndexPath { cell.setSelectedAnimate() } else { cell.setNotSelectedAnimate() } return cell } func createEmailCell(indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "UDTextAnimateTableViewCell", for: indexPath) as! UDTextAnimateTableViewCell cell.configurationStyle = usedesk?.configurationStyle ?? ConfigurationStyle() if let emailClient = fields[indexPath.row].value as? UDContactItem { if usedesk != nil { var isValid = emailClient.isValid var title = usedesk!.model.stringFor("Email") var attributedTitleString: NSMutableAttributedString? = nil var text = emailClient.contact var attributedTextString: NSMutableAttributedString? = nil if !isValid { title = usedesk!.model.stringFor("ErrorEmail") } else { attributedTitleString = NSMutableAttributedString() attributedTitleString!.append(NSAttributedString(string: title, attributes: [NSAttributedString.Key.font : usedesk!.configurationStyle.feedbackFormStyle.headerFont, NSAttributedString.Key.foregroundColor : usedesk!.configurationStyle.feedbackFormStyle.headerColor])) attributedTitleString!.append(NSAttributedString(string: " *", attributes: [NSAttributedString.Key.font : usedesk!.configurationStyle.feedbackFormStyle.headerFont, NSAttributedString.Key.foregroundColor : usedesk!.configurationStyle.feedbackFormStyle.headerSelectedColor])) } if emailClient.contact == "" && indexPath != selectedIndexPath { attributedTextString = attributedTitleString text = title title = usedesk!.model.stringFor("MandatoryField") attributedTitleString = nil isValid = false } cell.setCell(title: title, titleAttributed: attributedTitleString, text: text, textAttributed: attributedTextString, indexPath: indexPath, isValid: isValid, isTitleErrorState: !isValid, isLimitLengthText: false) } } cell.delegate = self if indexPath == selectedIndexPath { cell.setSelectedAnimate() } else { cell.setNotSelectedAnimate() } return cell } func createSelectTopicCell(indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "UDTextAnimateTableViewCell", for: indexPath) as! UDTextAnimateTableViewCell cell.configurationStyle = usedesk?.configurationStyle ?? ConfigurationStyle() if let titleTopics = fields[indexPath.row].value as? UDTextItem { if usedesk != nil { var title = usedesk!.model.stringFor("TopicTitle") var attributedTitleString: NSMutableAttributedString? = nil var text = titleTopics.text var attributedTextString: NSMutableAttributedString? = nil if usedesk!.callbackSettings.isRequiredTopic { attributedTitleString = NSMutableAttributedString() attributedTitleString!.append(NSAttributedString(string: usedesk!.callbackSettings.titleTopics, attributes: [NSAttributedString.Key.font : usedesk!.configurationStyle.feedbackFormStyle.headerFont, NSAttributedString.Key.foregroundColor : usedesk!.configurationStyle.feedbackFormStyle.headerColor])) attributedTitleString!.append(NSAttributedString(string: " *", attributes: [NSAttributedString.Key.font : usedesk!.configurationStyle.feedbackFormStyle.headerFont, NSAttributedString.Key.foregroundColor : usedesk!.configurationStyle.feedbackFormStyle.headerSelectedColor])) } else { title = usedesk!.callbackSettings.titleTopics } if !titleTopics.isValid { attributedTextString = attributedTitleString text = title title = usedesk!.model.stringFor("MandatoryField") attributedTitleString = nil } cell.setCell(title: title, titleAttributed: attributedTitleString, text: text, textAttributed: attributedTextString, indexPath: indexPath, isValid: titleTopics.isValid, isNeedSelectImage: true, isUserInteractionEnabled: false, isLimitLengthText: false) } } return cell } func createCustomFieldCell(indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "UDTextAnimateTableViewCell", for: indexPath) as! UDTextAnimateTableViewCell cell.configurationStyle = usedesk?.configurationStyle ?? ConfigurationStyle() if var fieldItem = fields[indexPath.row].value as? UDCustomFieldItem { if usedesk != nil { var isValid = true if fieldItem.field.isRequired { isValid = fieldItem.field.text != "" } if !fieldItem.isChanged { isValid = true } var title = usedesk!.model.stringFor("CustomField") var attributedTitleString: NSMutableAttributedString? = nil var text = fieldItem.field.text var attributedTextString: NSMutableAttributedString? = nil if fieldItem.field.isRequired { attributedTitleString = NSMutableAttributedString() attributedTitleString!.append(NSAttributedString(string: fieldItem.field.title, attributes: [NSAttributedString.Key.font : usedesk!.configurationStyle.feedbackFormStyle.headerFont, NSAttributedString.Key.foregroundColor : usedesk!.configurationStyle.feedbackFormStyle.headerColor])) attributedTitleString!.append(NSAttributedString(string: " *", attributes: [NSAttributedString.Key.font : usedesk!.configurationStyle.feedbackFormStyle.headerFont, NSAttributedString.Key.foregroundColor : usedesk!.configurationStyle.feedbackFormStyle.headerSelectedColor])) title = "" } else { title = fieldItem.field.title } if indexPath == selectedIndexPath { fieldItem.isChanged = true fields[indexPath.row].value = fieldItem } else { if !isValid { attributedTextString = attributedTitleString text = title title = usedesk!.model.stringFor("MandatoryField") attributedTitleString = nil } } cell.setCell(title: title, titleAttributed: attributedTitleString, text: text, textAttributed: attributedTextString, indexPath: indexPath, isValid: isValid, isLimitLengthText: false) } } cell.delegate = self if indexPath == selectedIndexPath { cell.setSelectedAnimate() } else { cell.setNotSelectedAnimate() } return cell } func createMessageCell(indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "UDTextAnimateTableViewCell", for: indexPath) as! UDTextAnimateTableViewCell cell.configurationStyle = usedesk?.configurationStyle ?? ConfigurationStyle() if let message = fields[indexPath.row].value as? UDTextItem { if usedesk != nil { let title = usedesk!.model.stringFor("Message") cell.setCell(title: title, text: message.text, indexPath: indexPath, isLimitLengthText: false) } } cell.delegate = self if indexPath == selectedIndexPath { cell.setSelectedAnimate() } else { cell.setNotSelectedAnimate() } return cell } func setSelectedCell(indexPath: IndexPath, isNeedFocusedTextView: Bool = true) { if let cell = tableView.cellForRow(at: indexPath) as? UDTextAnimateTableViewCell { if !cell.isValid && cell.teextAttributed != nil { cell.isValid = true cell.titleAttributed = cell.teextAttributed cell.defaultAttributedTitle = cell.teextAttributed if var contactItem = fields[indexPath.row].value as? UDContactItem { contactItem.isValid = true fields[indexPath.row].value = contactItem } else if var textItem = fields[indexPath.row].value as? UDTextItem { textItem.isValid = true fields[indexPath.row].value = textItem } else if var fieldItem = fields[indexPath.row].value as? UDCustomFieldItem { fieldItem.field.isValid = true fields[indexPath.row].value = fieldItem } } if fields[indexPath.row].type == .custom { if var fieldItem = fields[indexPath.row].value as? UDCustomFieldItem { fieldItem.isChanged = true fields[indexPath.row].value = fieldItem } } cell.setSelectedAnimate(isNeedFocusedTextView: isNeedFocusedTextView) } } } // MARK: - UITableViewDelegate extension UDOfflineForm: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return fields.count } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch fields[indexPath.row].type { case .name: return createNameCell(indexPath: indexPath) case .email: return createEmailCell(indexPath: indexPath) case .selectTopic: return createSelectTopicCell(indexPath: indexPath) case .custom: return createCustomFieldCell(indexPath: indexPath) case .message: return createMessageCell(indexPath: indexPath) } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if fields[indexPath.row].type == .selectTopic { let offlineFormTopicsSelectVC = UDOfflineFormTopicsSelect() offlineFormTopicsSelectVC.usedesk = usedesk offlineFormTopicsSelectVC.topics = usedesk?.callbackSettings.checkedTopics ?? [] if selectedTopicIndex != nil { offlineFormTopicsSelectVC.selectedIndexPath = IndexPath(row: selectedTopicIndex!, section: 0) } offlineFormTopicsSelectVC.delegate = self selectedIndexPath = nil self.navigationController?.pushViewController(offlineFormTopicsSelectVC, animated: true) tableView.reloadData() } else if selectedIndexPath != indexPath { if selectedIndexPath != nil { if let cellDidNotSelect = tableView.cellForRow(at: selectedIndexPath!) as? UDTextAnimateTableViewCell { cellDidNotSelect.setNotSelectedAnimate() } } selectedIndexPath = indexPath setSelectedCell(indexPath: selectedIndexPath!) } } } // MARK: - UDOfflineFormTopicsSelectDelegate extension UDOfflineForm: UDOfflineFormTopicsSelectDelegate { func selectedTopic(indexTopic: Int?) { if var textItemTopic = fields[indexFieldsForType(.selectTopic)].value as? UDTextItem { if usedesk != nil && indexTopic != nil { if usedesk!.callbackSettings.checkedTopics.count > indexTopic! { textItemTopic.text = usedesk!.callbackSettings.checkedTopics[indexTopic!].text } } else { textItemTopic.text = "" } textItemTopic.isValid = true fields[indexFieldsForType(.selectTopic)].value = textItemTopic tableView.reloadData() } selectedTopicIndex = indexTopic } } // MARK: - ChangeabelTextCellDelegate extension UDOfflineForm: ChangeabelTextCellDelegate { func newValue(indexPath: IndexPath, value: String, isValid: Bool, positionCursorY: CGFloat) { textViewYPositionCursor = positionCursorY switch fields[indexPath.row].type { case .name, .message: if fields[indexPath.row].value is UDTextItem { fields[indexPath.row].value = UDTextItem(text: value, isValid: isValid) } if fields[indexPath.row].type == .message { sendMessageButton.isEnabled = value.count > 0 ? true : false sendMessageButton.backgroundColor = value.count > 0 ? configurationStyle.feedbackFormStyle.buttonColor : configurationStyle.feedbackFormStyle.buttonColorDisabled } case .custom: if let fieldItem = fields[indexPath.row].value as? UDCustomFieldItem { fieldItem.field.text = value fieldItem.field.isValid = fieldItem.field.isRequired && fieldItem.field.text == "" ? false : true fields[indexPath.row].value = fieldItem } case .email: if fields[indexPath.row].value is UDContactItem { fields[indexPath.row].value = UDContactItem(contact: value, isValid: isValid) } default: break } tableView.beginUpdates() tableView.endUpdates() setHeightTables() } func tapingTextView(indexPath: IndexPath, position: CGFloat) { guard selectedIndexPath != indexPath else {return} if let cell = tableView.cellForRow(at: indexPath) as? UDTextAnimateTableViewCell { if selectedIndexPath != nil { if let cellDidNotSelect = tableView.cellForRow(at: selectedIndexPath!) as? UDTextAnimateTableViewCell { cellDidNotSelect.setNotSelectedAnimate() } } selectedIndexPath = indexPath setSelectedCell(indexPath: selectedIndexPath!, isNeedFocusedTextView: false) let textFieldRealYPosition = position + cell.frame.origin.y + tableView.frame.origin.y - scrollView.contentOffset.y let heightNavigationBar = navigationController?.navigationBar.frame.height ?? 44 if textFieldRealYPosition > (self.view.frame.height - heightNavigationBar - keyboardHeight - 30) { UIView.animate(withDuration: 0.4) { self.scrollView.contentOffset.y = (textFieldRealYPosition + self.scrollView.contentOffset.y) - (self.view.frame.height - heightNavigationBar - self.keyboardHeight - 30) } } } } func endWrite(indexPath: IndexPath) { if selectedIndexPath == indexPath { if let cellDidNotSelect = tableView.cellForRow(at: selectedIndexPath!) as? UDTextAnimateTableViewCell { cellDidNotSelect.setNotSelectedAnimate() } selectedIndexPath = nil } } } // MARK: - DialogflowVCDelegate extension UDOfflineForm: DialogflowVCDelegate { func close() { if isFromBase { navigationController?.popViewController(animated: true) } } } // MARK: - Structures enum UDNameFields { case name case email case selectTopic case custom case message } struct UDInfoItem { var type: UDNameFields = .name var value: Any! init(type: UDNameFields, value: Any) { self.type = type self.value = value } } struct UDTextItem { var isValid = true var text = "" init(text: String, isValid: Bool = true) { self.text = text self.isValid = isValid } } struct UDContactItem { var isValid = true var contact = "" init(contact: String, isValid: Bool = true) { self.contact = contact self.isValid = isValid } } struct UDCustomFieldItem { var isValid = true var isChanged = false var field: UDCallbackCustomField! init(field: UDCallbackCustomField, isValid: Bool = true) { self.field = field self.isValid = isValid } }
47.474214
520
0.614302
182e7fc5d21425e95a55be56cd7a47db29262a9f
519
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2017 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 // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck let g{struct Q{struct Q{class A{struct d{class a{{}}struct B{let h:A{{{}}}}}}}}}class S<T{func a<h{func b<T where h.g=a{
51.9
120
0.726397
03a1fbb407022b30c27e1ec09ee2dbf9a21b3428
1,256
// // FlixUITests.swift // FlixUITests // // Created by Sandyna Sandaire Jerome on 9/27/18. // Copyright © 2018 Sandyna Sandaire Jerome. All rights reserved. // import XCTest class FlixUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.945946
182
0.664013
626828dcc4214ff999a29924a82adac515fdf8fe
13,831
import Quick import Nimble import PathKit import SourceKittenFramework @testable import Sourcery @testable import SourceryFramework @testable import SourceryRuntime private func build(_ source: String) -> [String: SourceKitRepresentable]? { return try? Structure(file: File(contents: source)).dictionary } class FileParserVariableSpec: QuickSpec { override func spec() { describe("Parser") { describe("parseVariable") { func parse(_ code: String) -> Variable? { guard let parser = try? FileParser(contents: code) else { fail(); return nil } let code = build(code) guard let substructures = code?[SwiftDocKey.substructure.rawValue] as? [SourceKitRepresentable], let src = substructures.first as? [String: SourceKitRepresentable] else { fail() return nil } _ = try? parser.parse() return parser.parseVariable(src, definedIn: nil) } it("reports variable mutability") { expect(parse("var name: String")?.isMutable).to(beTrue()) expect(parse("let name: String")?.isMutable).to(beFalse()) expect(parse("private(set) var name: String")?.isMutable).to(beTrue()) expect(parse("var name: String { return \"\" }")?.isMutable).to(beFalse()) } it("extracts standard property correctly") { expect(parse("var name: String")).to(equal(Variable(name: "name", typeName: TypeName("String"), accessLevel: (read: .internal, write: .internal), isComputed: false))) } context("given variable with initial value") { it("extracts default value") { expect(parse("var name: String = String()")?.defaultValue).to(equal("String()")) expect(parse("var name = Parent.Children.init()")?.defaultValue).to(equal("Parent.Children.init()")) expect(parse("var name = [[1, 2], [1, 2]]")?.defaultValue).to(equal("[[1, 2], [1, 2]]")) expect(parse("var name = { return 0 }()")?.defaultValue).to(equal("{ return 0 }()")) expect(parse("var name = \t\n { return 0 }() \t\n")?.defaultValue).to(equal("{ return 0 }()")) expect(parse("var name: Int = \t\n { return 0 }() \t\n")?.defaultValue).to(equal("{ return 0 }()")) expect(parse("var name: String = String() { didSet { print(0) } }")?.defaultValue).to(equal("String()")) expect(parse("var name: String = String() {\n\tdidSet { print(0) }\n}")?.defaultValue).to(equal("String()")) expect(parse("var name: String = String()\n{\n\twillSet { print(0) }\n}")?.defaultValue).to(equal("String()")) } it("extracts property with default initializer correctly") { expect(parse("var name = String()")?.typeName).to(equal(TypeName("String"))) expect(parse("var name = Parent.Children.init()")?.typeName).to(equal(TypeName("Parent.Children"))) expect(parse("var name: String? = String()")?.typeName).to(equal(TypeName("String?"))) expect(parse("var name = { return 0 }() ")?.typeName).toNot(equal(TypeName("{ return 0 }"))) expect(parse( """ var reducer = Reducer<WorkoutTemplate.State, WorkoutTemplate.Action, GlobalEnvironment<Programs.Environment>>.combine( periodizationConfiguratorReducer.optional().pullback(state: \\.periodizationConfigurator, action: /WorkoutTemplate.Action.periodizationConfigurator, environment: { $0.map { _ in Programs.Environment() } })) { somethingUnrealted.init() } """ )?.typeName).to(equal(TypeName("Reducer<WorkoutTemplate.State, WorkoutTemplate.Action, GlobalEnvironment<Programs.Environment>>"))) } it("extracts property with literal value correctrly") { expect(parse("var name = 1")?.typeName).to(equal(TypeName("Int"))) expect(parse("var name = 1.0")?.typeName).to(equal(TypeName("Double"))) expect(parse("var name = \"1\"")?.typeName).to(equal(TypeName("String"))) expect(parse("var name = true")?.typeName).to(equal(TypeName("Bool"))) expect(parse("var name = false")?.typeName).to(equal(TypeName("Bool"))) expect(parse("var name = nil")?.typeName).to(equal(TypeName("Optional"))) expect(parse("var name = Optional.none")?.typeName).to(equal(TypeName("Optional"))) expect(parse("var name = Optional.some(1)")?.typeName).to(equal(TypeName("Optional"))) expect(parse("var name = Foo.Bar()")?.typeName).to(equal(TypeName("Foo.Bar"))) } it("extracts property with array literal value correctly") { expect(parse("var name = [Int]()")?.typeName).to(equal(TypeName("[Int]"))) expect(parse("var name = [1]")?.typeName).to(equal(TypeName("[Int]"))) expect(parse("var name = [1, 2]")?.typeName).to(equal(TypeName("[Int]"))) expect(parse("var name = [1, \"a\"]")?.typeName).to(equal(TypeName("[Any]"))) expect(parse("var name = [1, nil]")?.typeName).to(equal(TypeName("[Int?]"))) expect(parse("var name = [1, [1, 2]]")?.typeName).to(equal(TypeName("[Any]"))) expect(parse("var name = [[1, 2], [1, 2]]")?.typeName).to(equal(TypeName("[[Int]]"))) expect(parse("var name = [Int()]")?.typeName).to(equal(TypeName("[Int]"))) } it("extracts property with dictionary literal value correctly") { expect(parse("var name = [Int: Int]()")?.typeName).to(equal(TypeName("[Int: Int]"))) expect(parse("var name = [1: 2]")?.typeName).to(equal(TypeName("[Int: Int]"))) expect(parse("var name = [1: 2, 2: 3]")?.typeName).to(equal(TypeName("[Int: Int]"))) expect(parse("var name = [1: 1, 2: \"a\"]")?.typeName).to(equal(TypeName("[Int: Any]"))) expect(parse("var name = [1: 1, 2: nil]")?.typeName).to(equal(TypeName("[Int: Int?]"))) expect(parse("var name = [1: 1, 2: [1, 2]]")?.typeName).to(equal(TypeName("[Int: Any]"))) expect(parse("var name = [[1: 1, 2: 2], [1: 1, 2: 2]]")?.typeName).to(equal(TypeName("[[Int: Int]]"))) expect(parse("var name = [1: [1: 1, 2: 2], 2: [1: 1, 2: 2]]")?.typeName).to(equal(TypeName("[Int: [Int: Int]]"))) expect(parse("var name = [Int(): String()]")?.typeName).to(equal(TypeName("[Int: String]"))) } it("extracts property with tuple literal value correctly") { expect(parse("var name = (1, 2)")?.typeName).to(equal(TypeName("(Int, Int)"))) expect(parse("var name = (1, b: \"[2,3]\", c: 1)")?.typeName).to(equal(TypeName("(Int, b: String, c: Int)"))) expect(parse("var name = (_: 1, b: 2)")?.typeName).to(equal(TypeName("(Int, b: Int)"))) expect(parse("var name = ((1, 2), [\"a\": \"b\"])")?.typeName).to(equal(TypeName("((Int, Int), [String: String])"))) expect(parse("var name = ((1, 2), [1, 2])")?.typeName).to(equal(TypeName("((Int, Int), [Int])"))) expect(parse("var name = ((1, 2), [\"a,b\": \"b\"])")?.typeName).to(equal(TypeName("((Int, Int), [String: String])"))) } } it("extracts standard let property correctly") { let r = parse("let name: String") expect(r).to(equal(Variable(name: "name", typeName: TypeName("String"), accessLevel: (read: .internal, write: .none), isComputed: false))) } it("extracts computed property correctly") { expect(parse("var name: Int { return 2 }")).to(equal(Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .none), isComputed: true))) expect(parse("let name: Int")).to(equal(Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .none), isComputed: false))) expect(parse("var name: Int")).to(equal(Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .internal), isComputed: false))) expect(parse("var name: Int { \nget { return 0 } \nset {} }")).to(equal(Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .internal), isComputed: true))) expect(parse("var name: Int \n{ willSet { } }")).to(equal(Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .internal), isComputed: false))) expect(parse("var name: Int { \ndidSet {} }")).to(equal(Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .internal), isComputed: false))) } it("extracts generic property correctly") { expect(parse("let name: Observable<Int>")).to(equal(Variable(name: "name", typeName: TypeName("Observable<Int>"), accessLevel: (read: .internal, write: .none), isComputed: false))) } context("given it has sourcery annotations") { it("extracts single annotation") { let expectedVariable = Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .none), isComputed: true) expectedVariable.annotations["skipEquability"] = NSNumber(value: true) expect(parse("// sourcery: skipEquability\n" + "var name: Int { return 2 }")).to(equal(expectedVariable)) } it("extracts multiple annotations on the same line") { let expectedVariable = Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .none), isComputed: true) expectedVariable.annotations["skipEquability"] = NSNumber(value: true) expectedVariable.annotations["jsonKey"] = "json_key" as NSString expect(parse("// sourcery: skipEquability, jsonKey = \"json_key\"\n" + "var name: Int { return 2 }")).to(equal(expectedVariable)) } it("extracts multi-line annotations, including numbers") { let expectedVariable = Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .none), isComputed: true) expectedVariable.annotations["skipEquability"] = NSNumber(value: true) expectedVariable.annotations["jsonKey"] = "json_key" as NSString expectedVariable.annotations["thirdProperty"] = NSNumber(value: -3) let result = parse( "// sourcery: skipEquability, jsonKey = \"json_key\"\n" + "// sourcery: thirdProperty = -3\n" + "var name: Int { return 2 }") expect(result).to(equal(expectedVariable)) } it("extracts annotations interleaved with comments") { let expectedVariable = Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .none), isComputed: true) expectedVariable.annotations["isSet"] = NSNumber(value: true) expectedVariable.annotations["numberOfIterations"] = NSNumber(value: 2) let result = parse( "// sourcery: isSet\n" + "/// isSet is used for something useful\n" + "// sourcery: numberOfIterations = 2\n" + "var name: Int { return 2 }") expect(result).to(equal(expectedVariable)) } it("stops extracting annotations if it encounters a non-comment line") { let expectedVariable = Variable(name: "name", typeName: TypeName("Int"), accessLevel: (read: .internal, write: .none), isComputed: true) expectedVariable.annotations["numberOfIterations"] = NSNumber(value: 2) let result = parse( "// sourcery: isSet\n" + "\n" + "// sourcery: numberOfIterations = 2\n" + "var name: Int { return 2 }") expect(result).to(equal(expectedVariable)) } } } } } }
72.794737
236
0.508351
28c9f31a026dbeaacb5b8731916a85a8f2800dac
2,400
// // View+Extension.swift // SwiftyImpress // // Created by Pluto Y on 24/09/2016. // Copyright © 2016 com.pluto-y. All rights reserved. // extension View: SwiftyImpressCompatible { } // MARK: - Associated Key private var transform3DKey: Void? private var completionKey: Void? public typealias CompletionHandler = (_ view: View) -> () public struct CompleteClosureWrapper { var closure: CompletionHandler init(_ closure: @escaping CompletionHandler) { self.closure = closure } } public extension SwiftyImpress where Base: View { public var transform3D: CATransform3D { get { if let transform = objc_getAssociatedObject(base, &transform3DKey) as? CATransform3D { return transform } return CATransform3DIdentity } set { objc_setAssociatedObject(base, &transform3DKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } public var size: CGSize { set { base.frame = CGRect(origin: base.frame.origin, size: newValue) } get { return base.bounds.size } } public var completion: CompleteClosureWrapper? { get { if let completion = objc_getAssociatedObject(base, &completionKey) as? CompleteClosureWrapper { return completion } return nil } set { objc_setAssociatedObject(base, &completionKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) } } @discardableResult public func from(_ base: View, transform: CATransform3D) -> SwiftyImpress { let view = base self.transform3D = makeTransforms([pure(transform)], from: view.si.transform3D) return self } @discardableResult public func with(transform: CATransform3D) -> SwiftyImpress { self.transform3D = transform return self } @discardableResult public func config(clouse: (_: Base) -> ()) -> SwiftyImpress { clouse(base) return self } @discardableResult public func when(entered completion: CompletionHandler?) -> SwiftyImpress { if let closure = completion { self.completion = CompleteClosureWrapper(closure) } else { self.completion = nil } return self } }
27.272727
107
0.612917
1463254cbc2e864c896c17b0e8d9b84d2764c38d
477
import UIKit import MobileCoreServices class ActionRequestHandler: NSObject, NSExtensionRequestHandling { func beginRequestWithExtensionContext(context: NSExtensionContext) { let attachment = NSItemProvider(contentsOfURL: NSBundle.mainBundle().URLForResource("blockerList", withExtension: "json"))! let item = NSExtensionItem() item.attachments = [attachment] context.completeRequestReturningItems([item], completionHandler: nil) } }
34.071429
131
0.75891
08f1de7e1f85ed71ee4463950603361a202e39ae
676
// // AlertController.swift // OctoEye // // Created by mzp on 2017/07/31. // Copyright © 2017 mzp. All rights reserved. // import UIKit extension UIViewController { func presentError(title: String, error: Swift.Error) { DispatchQueue.main.async { let alertController = UIAlertController( title: title, message: error.localizedDescription, preferredStyle: .alert) let close = UIAlertAction(title: "Close", style: UIAlertActionStyle.default) { _ in } alertController.addAction(close) self.present(alertController, animated: true) {} } } }
27.04
95
0.60503
bf51f7ec93cd78b1edc8219b3244f97efda5660c
23,681
// // ImageDrawing.swift // Kingfisher // // Created by onevcat on 2018/09/28. // // Copyright (c) 2019 Wei Wang <[email protected]> // // 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 Accelerate #if canImport(AppKit) import AppKit #endif #if canImport(UIKit) import UIKit #endif // MARK: - Image Transforming extension KingfisherWrapper where Base: Image { // MARK: Blend Mode /// Create image from `base` image and apply blend mode. /// /// - parameter blendMode: The blend mode of creating image. /// - parameter alpha: The alpha should be used for image. /// - parameter backgroundColor: The background color for the output image. /// /// - returns: An image with blend mode applied. /// /// - Note: This method only works for CG-based image. #if !os(macOS) public func image(withBlendMode blendMode: CGBlendMode, alpha: CGFloat = 1.0, backgroundColor: Color? = nil) -> Image { guard let _ = cgImage else { assertionFailure("[Kingfisher] Blend mode image only works for CG-based image.") return base } let rect = CGRect(origin: .zero, size: size) return draw(to: rect.size) { _ in if let backgroundColor = backgroundColor { backgroundColor.setFill() UIRectFill(rect) } base.draw(in: rect, blendMode: blendMode, alpha: alpha) } } #endif #if os(macOS) // MARK: Compositing /// Creates image from `base` image and apply compositing operation. /// /// - Parameters: /// - compositingOperation: The compositing operation of creating image. /// - alpha: The alpha should be used for image. /// - backgroundColor: The background color for the output image. /// - Returns: An image with compositing operation applied. /// /// - Note: This method only works for CG-based image. For any non-CG-based image, `base` itself is returned. public func image(withCompositingOperation compositingOperation: NSCompositingOperation, alpha: CGFloat = 1.0, backgroundColor: Color? = nil) -> Image { guard let _ = cgImage else { assertionFailure("[Kingfisher] Compositing Operation image only works for CG-based image.") return base } let rect = CGRect(origin: .zero, size: size) return draw(to: rect.size) { _ in if let backgroundColor = backgroundColor { backgroundColor.setFill() rect.fill() } base.draw(in: rect, from: .zero, operation: compositingOperation, fraction: alpha) } } #endif // MARK: Round Corner /// Creates a round corner image from on `base` image. /// /// - Parameters: /// - radius: The round corner radius of creating image. /// - size: The target size of creating image. /// - corners: The target corners which will be applied rounding. /// - backgroundColor: The background color for the output image /// - Returns: An image with round corner of `self`. /// /// - Note: This method only works for CG-based image. The current image scale is kept. /// For any non-CG-based image, `base` itself is returned. public func image(withRoundRadius radius: CGFloat, fit size: CGSize, roundingCorners corners: RectCorner = .all, backgroundColor: Color? = nil) -> Image { guard let _ = cgImage else { assertionFailure("[Kingfisher] Round corner image only works for CG-based image.") return base } let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(to: size) { _ in #if os(macOS) if let backgroundColor = backgroundColor { let rectPath = NSBezierPath(rect: rect) backgroundColor.setFill() rectPath.fill() } let path = NSBezierPath(roundedRect: rect, byRoundingCorners: corners, radius: radius) #if swift(>=4.2) path.windingRule = .evenOdd #else path.windingRule = .evenOddWindingRule #endif path.addClip() base.draw(in: rect) #else guard let context = UIGraphicsGetCurrentContext() else { assertionFailure("[Kingfisher] Failed to create CG context for image.") return } if let backgroundColor = backgroundColor { let rectPath = UIBezierPath(rect: rect) backgroundColor.setFill() rectPath.fill() } let path = UIBezierPath( roundedRect: rect, byRoundingCorners: corners.uiRectCorner, cornerRadii: CGSize(width: radius, height: radius) ) context.addPath(path.cgPath) context.clip() base.draw(in: rect) #endif } } #if os(iOS) || os(tvOS) func resize(to size: CGSize, for contentMode: UIView.ContentMode) -> Image { switch contentMode { case .scaleAspectFit: return resize(to: size, for: .aspectFit) case .scaleAspectFill: return resize(to: size, for: .aspectFill) default: return resize(to: size) } } #endif // MARK: Resizing /// Resizes `base` image to an image with new size. /// /// - Parameter size: The target size in point. /// - Returns: An image with new size. /// - Note: This method only works for CG-based image. The current image scale is kept. /// For any non-CG-based image, `base` itself is returned. public func resize(to size: CGSize) -> Image { guard let _ = cgImage else { assertionFailure("[Kingfisher] Resize only works for CG-based image.") return base } let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(to: size) { _ in #if os(macOS) base.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0) #else base.draw(in: rect) #endif } } /// Resizes `base` image to an image of new size, respecting the given content mode. /// /// - Parameters: /// - targetSize: The target size in point. /// - contentMode: Content mode of output image should be. /// - Returns: An image with new size. /// /// - Note: This method only works for CG-based image. The current image scale is kept. /// For any non-CG-based image, `base` itself is returned. public func resize(to targetSize: CGSize, for contentMode: ContentMode) -> Image { let newSize = size.kf.resize(to: targetSize, for: contentMode) return resize(to: newSize) } // MARK: Cropping /// Crops `base` image to a new size with a given anchor. /// /// - Parameters: /// - size: The target size. /// - anchor: The anchor point from which the size should be calculated. /// - Returns: An image with new size. /// /// - Note: This method only works for CG-based image. The current image scale is kept. /// For any non-CG-based image, `base` itself is returned. public func crop(to size: CGSize, anchorOn anchor: CGPoint) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Crop only works for CG-based image.") return base } let rect = self.size.kf.constrainedRect(for: size, anchor: anchor) guard let image = cgImage.cropping(to: rect.scaled(scale)) else { assertionFailure("[Kingfisher] Cropping image failed.") return base } return KingfisherWrapper.image(cgImage: image, scale: scale, refImage: base) } // MARK: Blur /// Creates an image with blur effect based on `base` image. /// /// - Parameter radius: The blur radius should be used when creating blur effect. /// - Returns: An image with blur effect applied. /// /// - Note: This method only works for CG-based image. The current image scale is kept. /// For any non-CG-based image, `base` itself is returned. public func blurred(withRadius radius: CGFloat) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Blur only works for CG-based image.") return base } // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) // if d is odd, use three box-blurs of size 'd', centered on the output pixel. let s = Float(max(radius, 2.0)) // We will do blur on a resized image (*0.5), so the blur radius could be half as well. // Fix the slow compiling time for Swift 3. // See https://github.com/onevcat/Kingfisher/issues/611 let pi2 = 2 * Float.pi let sqrtPi2 = sqrt(pi2) var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5) if targetRadius.isEven { targetRadius += 1 } // Determine necessary iteration count by blur radius. let iterations: Int if radius < 0.5 { iterations = 1 } else if radius < 1.5 { iterations = 2 } else { iterations = 3 } let w = Int(size.width) let h = Int(size.height) let rowBytes = Int(CGFloat(cgImage.bytesPerRow)) func createEffectBuffer(_ context: CGContext) -> vImage_Buffer { let data = context.data let width = vImagePixelCount(context.width) let height = vImagePixelCount(context.height) let rowBytes = context.bytesPerRow return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes) } guard let context = beginContext(size: size, scale: scale, inverting: true) else { assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") return base } context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h)) endContext() var inBuffer = createEffectBuffer(context) guard let outContext = beginContext(size: size, scale: scale, inverting: true) else { assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") return base } defer { endContext() } var outBuffer = createEffectBuffer(outContext) for _ in 0 ..< iterations { let flag = vImage_Flags(kvImageEdgeExtend) vImageBoxConvolve_ARGB8888( &inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, flag) // Next inBuffer should be the outButter of current iteration (inBuffer, outBuffer) = (outBuffer, inBuffer) } #if os(macOS) let result = outContext.makeImage().flatMap { fixedForRetinaPixel(cgImage: $0, to: size) } #else let result = outContext.makeImage().flatMap { Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation) } #endif guard let blurredImage = result else { assertionFailure("[Kingfisher] Can not make an blurred image within this context.") return base } return blurredImage } // MARK: Overlay /// Creates an image from `base` image with a color overlay layer. /// /// - Parameters: /// - color: The color should be use to overlay. /// - fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, /// 1.0 means transparent overlay. /// - Returns: An image with a color overlay applied. /// /// - Note: This method only works for CG-based image. The current image scale is kept. /// For any non-CG-based image, `base` itself is returned. public func overlaying(with color: Color, fraction: CGFloat) -> Image { guard let _ = cgImage else { assertionFailure("[Kingfisher] Overlaying only works for CG-based image.") return base } let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) return draw(to: rect.size) { context in #if os(macOS) base.draw(in: rect) if fraction > 0 { color.withAlphaComponent(1 - fraction).set() rect.fill(using: .sourceAtop) } #else color.set() UIRectFill(rect) base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0) if fraction > 0 { base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction) } #endif } } // MARK: Tint /// Creates an image from `base` image with a color tint. /// /// - Parameter color: The color should be used to tint `base` /// - Returns: An image with a color tint applied. public func tinted(with color: Color) -> Image { #if os(watchOS) return base #else return apply(.tint(color)) #endif } // MARK: Color Control /// Create an image from `self` with color control. /// /// - Parameters: /// - brightness: Brightness changing to image. /// - contrast: Contrast changing to image. /// - saturation: Saturation changing to image. /// - inputEV: InputEV changing to image. /// - Returns: An image with color control applied. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image { #if os(watchOS) return base #else return apply(.colorControl((brightness, contrast, saturation, inputEV))) #endif } /// Return an image with given scale. /// /// - Parameter scale: Target scale factor the new image should have. /// - Returns: The image with target scale. If the base image is already in the scale, `base` will be returned. public func scaled(to scale: CGFloat) -> Image { guard scale != self.scale else { return base } guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Scaling only works for CG-based image.") return base } return KingfisherWrapper.image(cgImage: cgImage, scale: scale, refImage: base) } } // MARK: - Decoding Image extension KingfisherWrapper where Base: Image { /// Returns the decoded image of the `base` image. It will draw the image in a plain context and return the data /// from it. This could improve the drawing performance when an image is just created from data but not yet /// displayed for the first time. /// /// - Note: This method only works for CG-based image. The current image scale is kept. /// For any non-CG-based image or animated image, `base` itself is returned. public var decoded: Image { return decoded(scale: scale) } /// Returns decoded image of the `base` image at a given scale. It will draw the image in a plain context and /// return the data from it. This could improve the drawing performance when an image is just created from /// data but not yet displayed for the first time. /// /// - Parameter scale: The given scale of target image should be. /// - Returns: The decoded image ready to be displayed. /// /// - Note: This method only works for CG-based image. The current image scale is kept. /// For any non-CG-based image or animated image, `base` itself is returned. public func decoded(scale: CGFloat) -> Image { // Prevent animated image (GIF) losing it's images #if os(iOS) if imageSource != nil { return base } #else if images != nil { return base } #endif guard let imageRef = cgImage else { assertionFailure("[Kingfisher] Decoding only works for CG-based image.") return base } let size = CGSize(width: CGFloat(imageRef.width) / scale, height: CGFloat(imageRef.height) / scale) return draw(to: size, inverting: true, scale: scale) { context in context.draw(imageRef, in: CGRect(origin: .zero, size: size)) } } } extension KingfisherWrapper where Base: Image { func beginContext(size: CGSize, scale: CGFloat, inverting: Bool = false) -> CGContext? { #if os(macOS) guard let rep = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: cgImage?.bitsPerComponent ?? 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .calibratedRGB, bytesPerRow: 0, bitsPerPixel: 0) else { assertionFailure("[Kingfisher] Image representation cannot be created.") return nil } rep.size = size NSGraphicsContext.saveGraphicsState() guard let context = NSGraphicsContext(bitmapImageRep: rep) else { assertionFailure("[Kingfisher] Image context cannot be created.") return nil } NSGraphicsContext.current = context return context.cgContext #else UIGraphicsBeginImageContextWithOptions(size, false, scale) guard let context = UIGraphicsGetCurrentContext() else { return nil } if inverting { // If drawing a CGImage, we need to make context flipped. context.scaleBy(x: 1.0, y: -1.0) context.translateBy(x: 0, y: -size.height) } return context #endif } func endContext() { #if os(macOS) NSGraphicsContext.restoreGraphicsState() #else UIGraphicsEndImageContext() #endif } func draw(to size: CGSize, inverting: Bool = false, scale: CGFloat? = nil, refImage: Image? = nil, draw: (CGContext) -> Void) -> Image { let targetScale = scale ?? self.scale guard let context = beginContext(size: size, scale: targetScale, inverting: inverting) else { assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") return base } defer { endContext() } draw(context) guard let cgImage = context.makeImage() else { return base } return KingfisherWrapper.image(cgImage: cgImage, scale: targetScale, refImage: refImage ?? base) } #if os(macOS) func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image { let image = Image(cgImage: cgImage, size: base.size) let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) return draw(to: self.size) { context in image.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0) } } #endif } extension CGImage: KingfisherCompatible {} /// High Performance Image Resizing /// @see https://nshipster.com/image-resizing/ extension KingfisherWrapper where Base: CGImage { var size: CGSize { return CGSize(width: CGFloat(base.width), height: CGFloat(base.height)) } /// Resizes `base` CGImage to a CGImage of new size, respecting the given content mode. /// /// - Parameters: /// - targetSize: The target size in point. /// - contentMode: Content mode of output image should be. /// - Returns: A CGImage with new size. #if os(iOS) || os(tvOS) public func resize(to size: CGSize, for contentMode: UIView.ContentMode) -> CGImage { switch contentMode { case .scaleAspectFit: return resize(to: size, for: .aspectFit) case .scaleAspectFill: return resize(to: size, for: .aspectFill) default: return resize(to: size) } } #endif // MARK: - Resize /// Resizes `base` CGImage to a CGImage with new size. /// /// - Parameter size: The target size in point. /// - Returns: A CGImage with new size. public func resize(to size: CGSize) -> CGImage { let alphaInfo = base.alphaInfo.rawValue & CGBitmapInfo.alphaInfoMask.rawValue var hasAlpha = false if alphaInfo == CGImageAlphaInfo.premultipliedLast.rawValue || alphaInfo == CGImageAlphaInfo.premultipliedFirst.rawValue || alphaInfo == CGImageAlphaInfo.first.rawValue || alphaInfo == CGImageAlphaInfo.last.rawValue { hasAlpha = true } var bitmapInfo = CGImageByteOrderInfo.order32Little.rawValue bitmapInfo |= hasAlpha ? CGImageAlphaInfo.premultipliedFirst.rawValue : CGImageAlphaInfo.noneSkipFirst.rawValue guard let context = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: base.bitsPerComponent, bytesPerRow: base.bytesPerRow, space: base.colorSpace ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo) else { return base } let rect = CGRect(origin: .zero, size: size) context.interpolationQuality = .high context.draw(base, in: rect) return context.makeImage() ?? base } /// Resizes `base` CGImage to a CGImage of new size, respecting the given content mode. /// /// - Parameters: /// - targetSize: The target size in point. /// - contentMode: Content mode of output image should be. /// - Returns: A CGImage with new size. public func resize(to targetSize: CGSize, for contentMode: ContentMode) -> CGImage { let newSize = size.kf.resize(to: targetSize, for: contentMode) return resize(to: newSize) } }
39.206954
140
0.591529
287e4629c46c690f2d7efd68facfe5ae29da2a1b
1,676
// // TradePresenter.swift // ExchangeApp // // Created by Юрий Нориков on 04.12.2019. // Copyright (c) 2019 norikoff. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit protocol TradePresentationLogic { func presentChart(response: Trade.Something.Response) func presentUpdateChart(response: Trade.Something.Response) func presentError(response: Trade.Something.Response) func presentSuccess(response: Trade.Something.Response) } class TradePresenter: TradePresentationLogic { weak var viewController: TradeDisplayLogic? // MARK: Action func presentChart(response: Trade.Something.Response){ let viewModel = Trade.Something.ViewModel(chart: response.chart, errorMessage: response.errorMessage) viewController?.displayChart(viewModel: viewModel) } func presentUpdateChart(response: Trade.Something.Response){ let viewModel = Trade.Something.ViewModel(chart: response.chart, errorMessage: response.errorMessage) viewController?.displayUpdatedChart(viewModel: viewModel) } func presentError(response: Trade.Something.Response) { let viewModel = Trade.Something.ViewModel(chart: nil, errorMessage: response.errorMessage) viewController?.displayAllert(viewModel: viewModel) } func presentSuccess(response: Trade.Something.Response){ let viewModel = Trade.Something.ViewModel(chart: nil, errorMessage: response.errorMessage) viewController?.displaySuccess(viewModel: viewModel) } }
33.52
109
0.740453
e20cac8be72a1137f0cf3a933759e7bc79dc51cf
3,125
// // HomeViewController.swift // DYZB // // Created by 刘金萌 on 2019/7/12. // Copyright © 2019 刘金萌. All rights reserved. // import UIKit private let kTitleViewH:CGFloat = 40 class HomeViewController: UIViewController { // MARK:- 懒加载属性 private lazy var pageTitleView: PageTitleView = {[weak self] in let titleFrame = CGRect(x: 0, y: kStatusBarH+kNavigationBarH, width: kScreenW, height: kTitleViewH) let titles = ["推荐","游戏","娱乐","趣玩"] let titleView = PageTitleView(frame: titleFrame, titles: titles) titleView.delegate = self return titleView }() private lazy var pageContentView: PageContentView = {[weak self] in // 1.确定内容的frame let contentH = kScreenH-kStatusBarH-kNavigationBarH-kTitleViewH-kTabBarH let contentFrame = CGRect(x: 0, y: kStatusBarH+kNavigationBarH+kTitleViewH, width: kScreenW, height: contentH) // 2.确定所有的子控制器 var childVcs = [UIViewController]() childVcs.append(RecommendViewController()) childVcs.append(GameViewController()) childVcs.append(AmuseViewController()) childVcs.append(FunnyViewController()) let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentViewController: self) contentView.delegate = self return contentView }() // MARK:- 系统回调函数 override func viewDidLoad() { super.viewDidLoad() // 设置UI界面 setupUI() } } // MARK:- 设置UI界面 extension HomeViewController { private func setupUI(){ // 0.不需要调整UIScrollview的内编剧 automaticallyAdjustsScrollViewInsets = false // 1.设置导航栏 setupNavigationBar() // 2.添加TitleView view.addSubview(pageTitleView) // 3.添加ContentView view.addSubview(pageContentView) pageContentView.backgroundColor = UIColor.purple } private func setupNavigationBar(){ // 1.设置左侧的Item navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo") // 2.设置右侧的Item let size = CGSize(width: 40, height: 40) let historyItem = UIBarButtonItem(imageName: "image_my_history", hightImageName: "Image_my_history_click", size: size) let searchItem = UIBarButtonItem(imageName: "btn_search", hightImageName: "btn_search_clicked", size: size) let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", hightImageName: "Image_scan_click", size: size) navigationItem.rightBarButtonItems = [historyItem,searchItem,qrcodeItem] } } // MARK:- 遵守PageTitleViewDelegate协议 extension HomeViewController:PageTitleViewDelegate{ func pageTitleView(titleView: PageTitleView, selectedIndex index: Int) { pageContentView.setCurrentIndex(currentIndex: index) } } // MARK:- 遵守PageContentViewDelegate协议 extension HomeViewController:PageContentViewDelegate{ func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { pageTitleView.setTitleWithProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
35.91954
126
0.69216
014712faeeab00ed6e13b6177b40cd298e6093c3
2,011
// // ModalViewController.swift // Demo // // Created by takuya osawa on 2020/10/29. // import Foundation import UIKit import HalfModal final class NavModalViewController: UITableViewController, HalfModalPresenter { class func make() -> NavModalViewController { let vc = UIStoryboard(name: "NavModalViewController", bundle: nil).instantiateInitialViewController() as! NavModalViewController return vc } var targetScrollView: UIScrollView? { return tableView } override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .close, target: self, action: #selector(close)) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") tableView.register(UITableViewCell.self, forCellReuseIdentifier: NSStringFromClass(UITableViewCell.self)) tableView.reloadData() if let controller = navigationController as? NavigationController { controller.halfModalPresentationController?.didChangeModalPosition = { p in print(p) } controller.halfModalPresentationController?.didChangeOriginY = { y in print(y) } } } @objc private func close() { dismiss(animated: true, completion: nil) } private let array: [Int] = (0...100).map({ $0 }) override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return array.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") else { return tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(UITableViewCell.self)) ?? UITableViewCell() } cell.textLabel?.text = array[indexPath.row].description return cell } }
35.280702
136
0.671308
915972ae9bb6941f9a4ea641c32760b66c0ea64d
1,021
// // KRProgressHUDViewController.swift // KRProgressHUD // // Copyright © 2016年 Krimpedance. All rights reserved. // import UIKit class KRProgressHUDViewController: UIViewController { var statusBarStyle = UIStatusBarStyle.default var statusBarHidden = false override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(white: 0, alpha: 0.4) } override var preferredStatusBarStyle: UIStatusBarStyle { guard let vc = UIApplication.topViewController() else { return statusBarStyle } if !vc.isKind(of: KRProgressHUDViewController.self) { statusBarStyle = vc.preferredStatusBarStyle } return statusBarStyle } override var prefersStatusBarHidden: Bool { guard let vc = UIApplication.topViewController() else { return statusBarHidden } if !vc.isKind(of: KRProgressHUDViewController.self) { statusBarHidden = vc.prefersStatusBarHidden } return statusBarHidden } }
29.171429
88
0.693438
e9eb0bb8faf0d5c7cda0a77ece1b0bf73d6516de
1,252
// // BoutiqueTableModel.swift // QTRadio // // Created by Enrica on 2017/11/15. // Copyright © 2017年 Enrica. All rights reserved. // import UIKit @objcMembers class BoutiqueTableModel: NSObject { // MARK: - 模型数组 /// 用于保存转换完成的模型数据 lazy var tableRecommendModeArray = [BoutiqueTableRecommendsModel]() // MARK: - 服务器返回的模型属性 /// headerView上面的标题 var name: String = "" /// 简介 var brief_name: String = "" /// 数组中的字典数据 var recommends: [[String: Any]]? { didSet { // 校验数组recommends中是否有数据 guard let recommends = recommends else { return } // 遍历数组recommends,取出它里面的字典 for dict in recommends { // 将字典转为模型 let item = BoutiqueTableRecommendsModel(dict: dict) // 将转换完成的模型数据保存起来 self.tableRecommendModeArray.append(item) } } } // MARK: - 自定义构造函数 /// 将字典转为模型 init(dict: [String: Any]) { super.init() // 利用KVC将字典转为模型 setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) { } }
20.193548
74
0.520767
69742029870cf752ad190345779c66700184a96c
676
import Foundation public struct Variable: CustomStringConvertible { var value: Attachment // var serializationType: SerializationType public static func actionOutput(name: String? = nil) -> Variable { return Variable(value: Attachment(uuid: UUID(), outputName: name, type: "ActionOutput")) } var propertyList: PropertyList { return [ "Value": value.propertyList, // "WFSerializationType": type ] } public var description: String { let data = try! JSONSerialization.data(withJSONObject: value.propertyList) return "\u{fffc}\(String(decoding: data, as: UTF8.self))\u{fffd}" } }
29.391304
96
0.650888
08cf944262315847b67620a2bbb7e4322f57d92b
384
// // PostData.swift // HAckerNews // // Created by Gunjan Paul on 18/09/20. // Copyright © 2020 Gunjan Paul. All rights reserved. // import Foundation struct Result:Decodable { let hits: [Hits] } struct Hits:Decodable, Identifiable { var id: String{ return objectID } let objectID:String let points:Int let title:String let url:String? }
16
55
0.648438
bb2d6fd851cb44f588b2da397ac1e8843bb20b8e
1,240
// // ExampleUITests.swift // ExampleUITests // // Created by Diego Ernst on 9/5/16. // Copyright © 2016 Diego Ernst. All rights reserved. // import XCTest class ExampleUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
33.513514
182
0.66129
392153c1752e5fc32ed1938a98912a5118619587
1,883
// // NativeGame+PostMessage.swift // ODREurobet // // Created by Madhusudhan Reddy Putta on 11/05/21. // import Foundation import WebKit typealias EventData = Dictionary<String, Any> //MARK: - Script Handler Delegate extension NativeGame: WKScriptMessageHandler { public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { guard let data = message.body as? String, let dict = parseMessageType(data) else { return } if message.name == eventName { handlePostMessage(dict) return } } fileprivate func parseMessageType(_ messageBody :String) -> EventData? { let data = messageBody.data(using: .utf8)! do { guard let json = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? EventData else { print("bad json") return nil } return json } catch let error as NSError { print(error) return nil } } fileprivate func handlePostMessage(_ json :EventData) { guard let action = json["type"] as? String else { return } action == "closeGame" ? closeGame() : goToUrl(json) } fileprivate func closeGame() { view.window!.rootViewController?.dismiss(animated: false) { UIDevice.current.setValue(UIDeviceOrientation.portrait.rawValue, forKey: "orientation") } } fileprivate func goToUrl(_ json :EventData) { guard let data = json["data"] as? Dictionary<String, String>, let urlString = data["url"], let url = URL(string: urlString) else { return } UIApplication.shared.open(url, options: [:], completionHandler: nil) } }
30.370968
138
0.601699